content
stringlengths 5
1.05M
|
|---|
--3L·MyonMyonMyonMyon
local m=37564807
local cm=_G["c"..m]
if not pcall(function() require("expansions/script/c37564765") end) then require("script/c37564765") end
cm.named_with_myon=4
function cm.initial_effect(c)
senya.lfusm(c,nil,2,2)
senya.leff(c,m)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(aux.tgoval)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetValue(aux.imval1)
c:RegisterEffect(e2)
end
function cm.effect_operation_3L(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(400)
e1:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e1,true)
return e1
end
|
vim.cmd [[
augroup TermDetect
autocmd!
autocmd TermOpen term://* set ft=term
augroup END
]]
|
pipe = class:new()
function pipe:init(t, x, y, r)
self.cox = x
self.coy = y
self.x = x-1
self.y = y-1
self.width = 28/16 --smb: 22/16
self.height = 26/16
self.active = false
self.static = true
self.r = {unpack(r)}
table.remove(self.r, 1)
table.remove(self.r, 1)
self.world = 1
self.level = 1
self.sub = 0
self.exitid = 1
--defaults
self.dir = "down"
self.dir2 = false
self.exit = false
self.t = "pipe"
self.size = "big"
self.legacy = true
if t == "pipe" then
self.dir = "down"
self.dir2 = "right"
self.t = "pipe"
elseif t == "pipe2" then
self.dir = "up"
self.dir2 = "left"
self.t = "pipe"
elseif t == "pipespawn" then
self.dir = "up"
self.dir2 = false
self.t = "pipespawn"
elseif t == "pipespawndown" then
self.dir = "down"
self.dir2 = false
self.t = "pipespawn"
elseif t == "pipespawnhor" then
self.dir = "right"
if inmap(x+1, y) and tilequads[map[x+1][y][1]] and tilequads[map[x+1][y][1]]["collision"] then
self.dir = "left"
end
self.dir2 = false
self.t = "pipespawn"
elseif t == "warppipe" then
self.dir = "down"
self.t = "warppipe"
end
--right click menu
if #self.r > 0 and self.r[1] ~= "link" then
if self.t == "pipe" then
--target sub, exitid, direction
local v = convertr(self.r[1], {"num", "num", "string", "string"}, true)
self.sub = v[1]
self.exitid = v[2] or 1
if v[3] then
self.dir2 = false
self.dir = v[3]
self.size = v[4]
self.legacy = false
end
elseif self.t == "pipespawn" then
--entry sub, exitid, direction
local v = convertr(self.r[1], {"num", "num", "string", "string"}, true)
self.sub = v[1]
self.exitid = v[2] or 1
if v[3] then
self.dir = v[3]
self.size = v[4]
self.legacy = false
end
elseif self.t == "warppipe" then
--world, level, direction
local v = convertr(self.r[1], {"string", "num", "string", "string"}, true)
local world = tonumber(v[1]) or 1
if not tonumber(v[1]) then
local f1 = alphabet:find(tostring(v[1]))
if f1 then
world = 9+f1
else
world = 1
end
end
local worldstring = world
if hudworldletter and tonumber(world) and world > 9 and world <= 9+#alphabet then
worldstring = alphabet:sub(world-9, world-9)
end
self.worldstring = worldstring
self.world = world
self.level = v[2] or 1
if v[3] then
self.dir = v[3]
self.size = v[4]
self.legacy = false
end
end
table.remove(self.r, 1)
end
--set type
if self.t == "pipe" then
self.quad = pipesquad[1][self.dir]
elseif self.t == "pipespawn" then
--decide if it should be exited from
local targetsublevel = self.sub or 0
local exitid = self.exitid or 1
--testing sublevels (I KNOW YOULL ALSO NEED THIS)
--print(prevsublevel, mariosublevel, pipeexitid)
--print(targetsublevel, targetsublevel, exitid)
if (prevsublevel == targetsublevel or
(mariosublevel == targetsublevel and blacktime == sublevelscreentime)) and (((not pipeexitid) and exitid == 1) or
(pipeexitid == exitid)) then
pipestartx = x
pipestarty = y
pipestartdir = self.dir
end
self.exit = true
self.quad = pipesquad[2][self.dir]
elseif self.t == "warppipe" then
--insert warp pipe numbers
table.insert(warpzonenumbers, {x, y, self.worldstring})
self.quad = pipesquad[3][self.dir]
end
--dir
self.scissor = {}
self.scissor["up"] = {self.cox-4, self.coy-1-4, 5, 4}
self.scissor["down"] = {self.cox-4, self.coy, 5, 4}
self.scissor["left"] = {self.cox-1-4, self.coy-4, 4, 5}
self.scissor["right"] = {self.cox, self.coy-4, 4, 5}
--set size
if self.size == "big" then
self.x = x-1
self.y = y
elseif self.size == "giant" then
self.width = self.width*2
self.height = self.height*2
self.x = x-2
self.y = y
elseif self.size == "small" then
self.width = 1
self.height = 1
self.x = x-.5
self.y = y
elseif self.size == "tiny" then
self.width = 10/16
self.height = 10/16
self.x = x-.5
self.y = y
end
end
function pipe:draw()
love.graphics.draw(pipesimg, self.quad, math.floor((self.cox-1-xscroll)*16*scale), ((self.coy-1-yscroll)*16-8)*scale, 0, scale, scale)
end
function pipe:inside(dir, c, b) --direction of entrance, cox or coy, player
if (not self.exit) then
local p = b.x+b.width/2
local px, pw, py, ph = b.x, b.width, b.y, b.height
if hugemario then --hugemario cheat should still enter pipes i guess
pw, ph = 24/16, 24/16
px = b.x+b.width/2-pw/2
py = b.y+b.height-ph
end
local enterdir = false
if dir == self.dir then --multiple enter directions for backwards compatibility
enterdir = self.dir
elseif dir == self.dir2 then
enterdir = self.dir2
end
if enterdir then
if enterdir == "up" or enterdir == "down" then
if c == self.coy then
if (px >= self.x-self.width/2 and px+pw <= self.x+self.width/2) or bigmario then
return true
end
end
elseif enterdir == "left" or enterdir == "right" then
if c == self.cox then
--accurate pipe entering
--[[if py >= self.y-self.height and py+ph <= self.y then
return true
end]]
--mari0 1.6 pipe entering
--all it needs is a collision
if ((ph <= self.height) or bigmario) and --should he fit at all?
py+ph > self.coy-1 and py < self.coy and --is the player touching the pipe entity
py+ph*.5 < self.coy then --is the middle of the player within the pipe? (just to make it resonable)
return true
end
end
end
end
end
return false
end
function pipe:opp(dir)
if dir == "down" then
return "up"
elseif dir == "up" then
return "down"
elseif dir == "left" then
return "right"
elseif dir == "right" then
return "left"
end
end
|
local M = {}
--- Taken from <https://github.com/lukas-reineke/indent-blankline.nvim/blob/0a98fa8dacafe22df0c44658f9de3968dc284d20/lua/indent_blankline/utils.lua#L231-L235>.
function M.first_non_nil(...)
for i = 1, select('#', ...) do
local val = select(i, ...)
if val ~= nil then
return val
end
end
end
function M.tbl_to_set(tbl, default_value)
if type(tbl) ~= 'table' then
error(string.format('tbl: expected table, got %s', type(tbl)))
end
if default_value == nil then default_value = true end
local result = {}
for _, value in pairs(tbl) do
result[value] = default_value
end
return result
end
return M
|
return {
summary = 'Get the Collider the Shape is attached to.',
description = 'Returns the Collider the Shape is attached to.',
arguments = {},
returns = {
{
name = 'collider',
type = 'Collider',
description = 'The Collider the Shape is attached to.'
}
},
notes = 'A Shape can only be attached to one Collider at a time.',
related = {
'Collider',
'Collider:addShape',
'Collider:removeShape'
}
}
|
local moon = require("moon")
local json = require("json")
local socket = require("moon.socket")
local test_assert = require("test_assert")
local large_data = {}
for i=1,100000 do
large_data[i]="HelloWorld"..tostring(i)
end
local data = json.encode(large_data)
local listenfd = socket.listen("127.0.0.1", 30002, moon.PTYPE_SOCKET)
socket.start(listenfd)
socket.on("accept",function(fd)
test_assert.assert(socket.set_enable_frame(fd,"rw"),"set_enable_frame failed!")
end)
socket.on("message",function(_, msg)
test_assert.equal(msg:bytes(),data)
test_assert.success()
end)
socket.on("error",function(_, msg)
test_assert.assert(false,msg:bytes())
end)
moon.start(function()
local fd = socket.sync_connect("127.0.0.1", 30002, moon.PTYPE_SOCKET)
test_assert.assert(fd>0,"connect server failed")
socket.set_enable_frame(fd,"rw")
socket.write_then_close(fd,data)
end)
moon.destroy(function()
socket.close(listenfd)
end)
|
--[[
/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <arrayfire.h>
using namespace af;
array clamp(const array &in, float min = 0.0f, float max = 255.0f)
{
return ((in<min)*0.0f + (in>max)*255.0f + (in >= min && in <= max)*in);
}
array hurl(const array &in, int randomization, int repeat)
{
int w = in.dims(0);
int h = in.dims(1);
float f = randomization / 100.0f;
int dim = (int)(f*w*h);
array ret_val = in.copy();
array temp = moddims(ret_val, w*h, 3);
for (int i = 0; i<repeat; ++i) {
array idxs = (w*h) * randu(dim);
array rndR = 255.0f * randu(dim);
array rndG = 255.0f * randu(dim);
array rndB = 255.0f * randu(dim);
temp(idxs, 0) = rndR;
temp(idxs, 1) = rndG;
temp(idxs, 2) = rndB;
}
ret_val = moddims(temp, in.dims());
return ret_val;
}
array getRandomNeighbor(const array &in, int windW, int windH)
{
array rnd = 2.0f*randu(in.dims(0), in.dims(1)) - 1.0f;
array sx = seq(in.dims(0));
array sy = seq(in.dims(1));
array vx = tile(sx, 1, in.dims(1)) + floor(rnd*windW);
array vy = tile(sy.T(), in.dims(0), 1) + floor(rnd*windH);
array vxx = clamp(vx, 0, in.dims(0));
array vyy = clamp(vy, 0, in.dims(1));
array in2 = moddims(in, vx.elements(), 3);
return moddims(in2(vyy*in.dims(0) + vxx, span), in.dims());
}
array spread(const array &in, int window_width, int window_height)
{
return getRandomNeighbor(in, window_width, window_height);
}
array pick(const array &in, int randomization, int repeat)
{
int w = in.dims(0);
int h = in.dims(1);
float f = randomization / 100.0f;
int dim = (int)(f*w*h);
array ret_val = in.copy();
for (int i = 0; i<repeat; ++i) {
array idxs = (w*h) * randu(dim);
array rnd = getRandomNeighbor(ret_val, 1, 1);
array temp_src = moddims(rnd, w*h, 3);
array temp_dst = moddims(ret_val, w*h, 3);
temp_dst(idxs, span) = temp_src(idxs, span);
ret_val = moddims(temp_dst, in.dims());
}
return ret_val;
}
void prewitt(array &mag, array &dir, const array &in)
{
static float h1[] = { 1, 1, 1 };
static float h2[] = { -1, 0, 1 };
static array h1d(3, h1);
static array h2d(3, h2);
// Find the gradients
array Gy = af::convolve(h2d, h1d, in) / 6;
array Gx = af::convolve(h1d, h2d, in) / 6;
// Find magnitude and direction
mag = hypot(Gx, Gy);
dir = atan2(Gy, Gx);
}
void sobelFilter(array &mag, array &dir, const array &in)
{
// Find the gradients
array Gy, Gx;
af::sobel(Gx, Gy, in);
// Find magnitude and direction
mag = hypot(Gx, Gy);
dir = atan2(Gy, Gx);
}
void normalizeImage(array &in)
{
float min = af::min<float>(in);
float max = af::max<float>(in);
in = 255.0f*((in - min) / (max - min));
}
array DifferenceOfGaussian(const array &in, int window_radius1, int window_radius2)
{
array ret_val;
int w1 = 2 * window_radius1 + 1;
int w2 = 2 * window_radius2 + 1;
array g1 = gaussianKernel(w1, w1);
array g2 = gaussianKernel(w2, w2);
ret_val = (convolve(in, g1) - convolve(in, g2));
normalizeImage(ret_val);
return ret_val;
}
array medianfilter(const array &in, int window_width, int window_height)
{
array ret_val(in.dims());
ret_val(span, span, 0) = medfilt(in(span, span, 0), window_width, window_height);
ret_val(span, span, 1) = medfilt(in(span, span, 1), window_width, window_height);
ret_val(span, span, 2) = medfilt(in(span, span, 2), window_width, window_height);
return ret_val;
}
array gaussianblur(const array &in, int window_width, int window_height, int sigma)
{
array g = gaussianKernel(window_width, window_height, sigma, sigma);
return convolve(in, g);
}
array emboss(const array &input, float azimuth, float elevation, float depth)
{
if (depth<1 || depth>100) {
printf("Depth should be in the range of 1-100");
return input;
}
static float x[3] = { -1, 0, 1 };
static array hg(3, x);
static array vg = hg.T();
array in = input;
if (in.dims(2)>1)
in = colorSpace(input, AF_GRAY, AF_RGB);
else
in = input;
// convert angles to radians
float phi = elevation*af::Pi / 180.0f;
float theta = azimuth*af::Pi / 180.0f;
// compute light pos in cartesian coordinates
// and scale with maximum intensity
// phi will effect the amount of we intend to put
// on a pixel
float pos[3];
pos[0] = 255.99f * cos(phi)*cos(theta);
pos[1] = 255.99f * cos(phi)*sin(theta);
pos[2] = 255.99f * sin(phi);
// compute gradient vector
array gx = convolve(in, vg);
array gy = convolve(in, hg);
float pxlz = (6 * 255.0f) / depth;
array zdepth = constant(pxlz, gx.dims());
array vdot = gx*pos[0] + gy*pos[1] + pxlz*pos[2];
array outwd = vdot < 0.0f;
array norm = vdot / sqrt(gx*gx + gy*gy + zdepth*zdepth);
array color = outwd * 0.0f + (1 - outwd) * norm;
return color;
}
int main(int argc, char **argv)
{
try {
int device = argc > 1 ? atoi(argv[1]) : 0;
af::setDevice(device);
af::info();
array lena = loadImage(ASSETS_DIR "/examples/images/vegetable-woman.jpg", true);
array prew_mag, prew_dir;
array sob_mag, sob_dir;
array lena1ch = colorSpace(lena, AF_GRAY, AF_RGB);
prewitt(prew_mag, prew_dir, lena1ch);
sobelFilter(sob_mag, sob_dir, lena1ch);
array sprd = spread(lena, 3, 3);
array hrl = hurl(lena, 10, 1);
array pckng = pick(lena, 40, 2);
array difog = DifferenceOfGaussian(lena, 1, 2);
array bil = bilateral(hrl, 3.0f, 40.0f);
array mf = medianfilter(hrl, 5, 5);
array gb = gaussianblur(hrl, 3, 3, 0.8);
array emb = emboss(lena, 45, 20, 10);
af::Window wnd("Image Filters Demo");
std::cout << "Press ESC while the window is in focus to exit" << std::endl;
while (!wnd.close()) {
wnd.grid(2, 5);
wnd(0, 0).image(hrl / 255, "Hurl noise");
wnd(1, 0).image(gb / 255, "Gaussian blur");
wnd(0, 1).image(bil / 255, "Bilateral filter on hurl noise");
wnd(1, 1).image(mf / 255, "Median filter on hurl noise");
wnd(0, 2).image(prew_mag / 255, "Prewitt edge filter");
wnd(1, 2).image(sob_mag / 255, "Sobel edge filter");
wnd(0, 3).image(sprd / 255, "Spread filter");
wnd(1, 3).image(pckng / 255, "Pick filter");
wnd(0, 4).image(difog / 255, "Difference of gaussians(3x3 and 5x5)");
wnd(1, 4).image(emb / 255, "Emboss effect");
wnd.show();
}
}
catch (af::exception& e) {
fprintf(stderr, "%s\n", e.what());
throw;
}
#ifdef WIN32 // pause in Windows
if (!(argc == 2 && argv[1][0] == '-')) {
printf("hit [enter]...");
fflush(stdout);
getchar();
}
#endif
return 0;
}
]]
|
require "sys.serialize"
local core = require "sys.core"
local RpcDef = {}
local TypeMap = {
I = "number",
T = "table",
S = "string",
}
function RpcDef:GetRealType(simpleType)
return TypeMap[simpleType]
end
function RpcDef:InitRpcHandle(rpcHandleDef, precheckfunc)
local handle = rpcHandleDef[1]
local funcDef = rpcHandleDef[2]
local dispatcher = {}
local handleDesc = {}
for i, def in ipairs(funcDef) do
local rpcName = def[1]
local argTypeList = def[2]
handleDesc [rpcName] = argTypeList
end
dispatcher["rpc"] = function(fd, cmd, msg)
local args = unserialize(msg.content)
if not args then
return
end
local rpcName = args[1]
if not rpcName then
core.log("no rpcname found in msg", msg)
return
end
local definedTypeList = handleDesc[rpcName]
if not definedTypeList then
core.log("no define found", rpcName)
return
end
if not handle[rpcName] then
core.log("no handle found", rpcName)
return
end
if not self:CheckRpcArgs(args, definedTypeList) then
return
end
local argc = #args - 1
if precheckfunc then
local bok, msg = precheckfunc(fd, rpcName, table.unpack(args, 2, argc + 1))
if not bok then
return "rpc", {content = msg or "precheck failed"}
end
end
local ret = handle[rpcName](handle, fd, table.unpack(args, 2, argc + 1))
return "rpc", {content = ret}
end
return dispatcher
end
function RpcDef:CheckRpcArgs(args, definedTypeList, rpcName)
local argc = #args - 1
if argc ~= #definedTypeList then
core.log("arg count mismatch", argc, #definedTypeList)
return
end
for argIdx = 1,argc do
local simpleType = string.sub(definedTypeList, argIdx, argIdx)
local definedType = self:GetRealType(simpleType)
local realType = type(args[argIdx+1])
if definedType ~= realType then
core.log("arg type mismatch rpcName is ", rpcName, ". argIdx is ",argIdx, ". definedType is ", definedType ,". real type is ", realType)
return
end
end
return true
end
function RpcDef:AttachRpcSender(rpcSenderDef, rpcInstance, bServer)
local handle = rpcSenderDef[1]
local funcDef = rpcSenderDef[2]
local dispatcher = {}
local handleDesc = {}
for i, def in ipairs(funcDef) do
local rpcName = def[1]
local argTypeList = def[2]
if bServer then
handle[rpcName] = function(handle, fd, ...)
local args = {rpcName, ...}
local content = serialize(args)
if not RpcDef:CheckRpcArgs(args, argTypeList, rpcName) then
return
end
local ack = rpcInstance:call(fd, "rpc", {content = content})
if ack and ack.content then
return ack.content
end
end
else
handle[rpcName] = function(handle, fd, ...)
local args = {rpcName, ...}
local content = serialize(args)
if not RpcDef:CheckRpcArgs(args, argTypeList, rpcName) then
return
end
local ack = rpcInstance:call("rpc", {content = content})
if ack and ack.content then
return ack.content
end
end
end
end
end
return RpcDef
|
local g = vim.g
local api = vim.api
g.mapleader = ","
api.nvim_set_keymap("x", "<C-c>", '"+y', { noremap = true })
api.nvim_set_keymap("n", "<C-h>", "<C-W>h", { noremap = true })
api.nvim_set_keymap("n", "<C-j>", "<C-W>j", { noremap = true })
api.nvim_set_keymap("n", "<C-k>", "<C-W>k", { noremap = true })
api.nvim_set_keymap("n", "<C-l>", "<C-W>l", { noremap = true })
api.nvim_set_keymap("n", "<TAB>", ":BufferLineCycleNext<CR>", { noremap = true })
api.nvim_set_keymap("n", "<S-TAB>", ":BufferLineCyclePrev<CR>", { noremap = true })
api.nvim_set_keymap("n", "<C-t>", ":tabnew<CR>", { noremap = true })
api.nvim_set_keymap("n", "Q", "<nop>", { noremap = true })
api.nvim_set_keymap("n", "q:", "<nop>", { noremap = true })
api.nvim_set_keymap("n", "<S-x>", ":Bdelete<cr>", { noremap = true })
api.nvim_set_keymap("n", "<esc>", ":nohlsearch<return><esc>", { noremap = true, silent = true })
api.nvim_set_keymap("n", "gD", ":lua vim.lsp.buf.declaration()<CR>", { noremap = true })
api.nvim_set_keymap("n", "gd", ":lua vim.lsp.buf.definition()<CR>", { noremap = true })
api.nvim_set_keymap("n", "K", ":lua vim.lsp.buf.hover()<CR>", { noremap = true })
api.nvim_set_keymap("n", "gi", ":lua vim.lsp.buf.implementation()<CR>", { noremap = true })
api.nvim_set_keymap("n", "<C-s>", ":lua vim.lsp.buf.signature_help()<CR>", { noremap = true })
api.nvim_set_keymap("n", "gr", ":lua vim.lsp.buf.references()<CR>", { noremap = true })
api.nvim_set_keymap("v", "<", '<gv', { noremap = true })
api.nvim_set_keymap("v", ">", '>gv', { noremap = true })
|
--scripts/modtools/attack-trigger.lua
--author expwnent
--based on itemsyndrome by Putnam
--triggers scripts when a unit attacks another with a weapon type, a weapon of a particular material, or a weapon contaminated with a particular material, or when a unit equips/unequips a particular item type, an item of a particular material, or an item contaminated with a particular material
local eventful = require 'plugins.eventful'
local utils = require 'utils'
itemTriggers = itemTriggers or {}
materialTriggers = materialTriggers or {}
contaminantTriggers = contaminantTriggers or {}
eventful.enableEvent(eventful.eventType.UNIT_ATTACK,1) -- this event type is cheap, so checking every tick is fine
eventful.enableEvent(eventful.eventType.INVENTORY_CHANGE,5) --this is expensive, but you might still want to set it lower
eventful.enableEvent(eventful.eventType.UNLOAD,1)
eventful.onUnload.itemTrigger = function()
itemTriggers = {}
materialTriggers = {}
contaminantTriggers = {}
end
function processTrigger(command)
local command2 = {}
for i,arg in ipairs(command.command) do
if arg == '\\ATTACKER_ID' then
command2[i] = '' .. command.attacker.id
elseif arg == '\\DEFENDER_ID' then
command2[i] = '' .. command.defender.id
elseif arg == '\\ITEM_MATERIAL' then
command2[i] = command.itemMat:getToken()
elseif arg == '\\ITEM_MATERIAL_TYPE' then
command2[i] = command.itemMat['type']
elseif arg == '\\ITEM_MATERIAL_INDEX' then
command2[i] = command.itemMat.index
elseif arg == '\\ITEM_ID' then
command2[i] = '' .. command.item.id
elseif arg == '\\ITEM_TYPE' then
command2[i] = command.itemType
elseif arg == '\\CONTAMINANT_MATERIAL' then
command2[i] = command.contaminantMat:getToken()
elseif arg == '\\CONTAMINANT_MATERIAL_TYPE' then
command2[i] = command.contaminantMat['type']
elseif arg == '\\CONTAMINANT_MATERIAL_INDEX' then
command2[i] = command.contaminantMat.index
elseif arg == '\\MODE' then
command2[i] = command.mode
elseif arg == '\\UNIT_ID' then
command2[i] = command.unit.id
elseif string.sub(arg,1,1) == '\\' then
command2[i] = string.sub(arg,2)
else
command2[i] = arg
end
end
dfhack.run_command(table.unpack(command2))
end
function handler(table)
local itemMat = dfhack.matinfo.decode(table.item)
local itemMatStr = itemMat:getToken()
local itemType = dfhack.items.getSubtypeDef(table.item:getType(),table.item:getSubtype()).id
table.itemMat = itemMat
table.itemType = itemType
for _,command in ipairs(itemTriggers[itemType] or {}) do
if command[table.mode] then
utils.fillTable(command,table)
processTrigger(command)
utils.unfillTable(command,table)
end
end
for _,command in ipairs(materialTriggers[itemMatStr] or {}) do
if command[table.mode] then
utils.fillTable(command,table)
processTrigger(command)
utils.unfillTable(command,table)
end
end
for _,contaminant in ipairs(table.item.contaminants or {}) do
local contaminantMat = dfhack.matinfo.decode(contaminant.mat_type, contaminant.mat_index)
local contaminantStr = contaminantMat:getToken()
table.contaminantMat = contaminantMat
for _,command in ipairs(contaminantTriggers[contaminantStr] or {}) do
utils.fillTable(command,table)
processTrigger(command)
utils.unfillTable(command,table)
end
table.contaminantMat = nil
end
end
function equipHandler(unit, item, isEquip)
local mode = (isEquip and 'onEquip') or (not isEquip and 'onUnequip')
local table = {}
table.mode = mode
table.item = df.item.find(item)
table.unit = df.unit.find(unit)
handler(table)
end
eventful.onInventoryChange.equipmentTrigger = function(unit, item, item_old, item_new)
if item_old and item_new then
return
end
local isEquip = item_new and not item_old
equipHandler(unit,item,isEquip)
end
eventful.onUnitAttack.attackTrigger = function(attacker,defender,wound)
attacker = df.unit.find(attacker)
defender = df.unit.find(defender)
if not attacker then
return
end
local attackerWeapon
for _,item in ipairs(attacker.inventory) do
if item.mode == df.unit_inventory_item.T_mode.Weapon then
attackerWeapon = item.item
break
end
end
if not attackerWeapon then
return
end
local table = {}
table.attacker = attacker
table.defender = defender
table.item = attackerWeapon
table.mode = 'onStrike'
handler(table)
end
validArgs = validArgs or utils.invert({
'clear',
'help',
'checkAttackEvery',
'checkInventoryEvery',
'command',
'itemType',
'onStrike',
'onEquip',
'onUnequip',
'material',
'contaminant',
})
local args = utils.processArgs({...}, validArgs)
if args.help then
print([[scripts/modtools/item-trigger.lua usage
arguments:
-help
print this help message
-clear
clear all registered triggers
-checkAttackEvery n
check the attack event at least every n ticks
-checkInventoryEvery n
check inventory event at least every n ticks
-itemType type
trigger the command for items of this type
examples:
ITEM_WEAPON_PICK
-onStrike
trigger the command when someone strikes someone with an appropriate weapon
-onEquip
trigger the command when someone equips an appropriate item
-onUnequip
trigger the command when someone unequips an appropriate item
-material mat
trigger the commmand on items with the given material
examples
INORGANIC:IRON
CREATURE_MAT:DWARF:BRAIN
PLANT_MAT:MUSHROOM_HELMET_PLUMP:DRINK
-contaminant mat
trigger the command on items with a given material contaminant
examples
INORGANIC:IRON
CREATURE_MAT:DWARF:BRAIN
PLANT_MAT:MUSHROOM_HELMET_PLUMP:DRINK
-command [ commandStrs ]
specify the command to be executed
commandStrs
\\ATTACKER_ID
\\DEFENDER_ID
\\ITEM_MATERIAL
\\ITEM_MATERIAL_TYPE
\\ITEM_ID
\\ITEM_TYPE
\\CONTAMINANT_MATERIAL
\\CONTAMINANT_MATERIAL_TYPE
\\CONTAMINANT_MATERIAL_INDEX
\\MODE
\\UNIT_ID
\\anything -> \anything
anything -> anything
]])
return
end
if args.clear then
itemTriggers = {}
materialTriggers = {}
contaminantTriggers = {}
end
if args.checkAttackEvery then
if not tonumber(args.checkAttackEvery) then
error('checkAttackEvery must be a number')
end
eventful.enableEvent(eventful.eventType.UNIT_ATTACK,tonumber(args.checkAttackEvery))
end
if args.checkInventoryEvery then
if not tonumber(args.checkInventoryEvery) then
error('checkInventoryEvery must be a number')
end
eventful.enableEvent(eventful.eventType.INVENTORY_CHANGE,tonumber(args.checkInventoryEvery))
end
if not args.command then
if not args.clear then
error 'specify a command'
end
return
end
if args.itemType then
local temp
for _,itemdef in ipairs(df.global.world.raws.itemdefs.all) do
if itemdef.id == args.itemType then
temp = args.itemType --itemdef.subtype
break
end
end
if not temp then
error 'Could not find item type.'
end
args.itemType = temp
end
local numConditions = (args.material and 1 or 0) + (args.itemType and 1 or 0) + (args.contaminant and 1 or 0)
if numConditions > 1 then
error 'too many conditions defined: not (yet) supported (pester expwnent if you want it)'
elseif numConditions == 0 then
error 'specify a material, weaponType, or contaminant'
end
if args.material then
if not materialTriggers[args.material] then
materialTriggers[args.material] = {}
end
table.insert(materialTriggers[args.material],args)
elseif args.itemType then
if not itemTriggers[args.itemType] then
itemTriggers[args.itemType] = {}
end
table.insert(itemTriggers[args.itemType],args)
elseif args.contaminant then
if not contaminantTriggers[args.contaminant] then
contaminantTriggers[args.contaminant] = {}
end
table.insert(contaminantTriggers[args.contaminant],args)
end
|
if game.PlaceId == 155615604 then
local Library = loadstring(game:HttpGet("https://raw.githubusercontent.com/Attrixx/Scandia/main/KavoUiLib.lua"))()
local Window = Library.CreateLib("Scandia Hub - Prison Life", "Ocean")
local Main = Window:NewTab("Main")
local Player = Window:NewTab("Player")
-- Main
local MainSection = Main:NewSection("Main")
MainSection:NewDropdown("Give Gun", "Gives LocalPlayer a Gun", {"M9", "M4A1", "AK-47", "Remington 870"}, function(currentOption)
local give = game:GetService("Workspace")["Prison_ITEMS"].giver[currentOption].ITEMPICKUP
local Event = game:GetService("Workspace").Remote.ItemHandler
Event:InvokeServer(give)
end)
MainSection:NewDropdown("Gun Mod", "Makes the gun OP", {"M9", "M4A1", "AK-47", "Remington 870"}, function(currentOption)
local module = nil
if game:GetService("Players").LocalPlayer.Backpack:FindFirstChild(currentOption) then
module = game:GetService("Players").LocalPlayer.Backpack[currentOption].GunStates
elseif game:GetService("Players").LocalPlayer.Character:FindFirstChild(currentOption) then
module = require(game:GetService("Players").LocalPlayer.Character[currentOption].GunStates)
end
if module ~= nil then
module["MaxAmmo"] = math.huge
module["CurrentAmmo"] = math.huge
module["StoredAmmo"] = math.huge
module["FireRate"] = 0.0000001
module["Spread"] = 0
module["ReloadTime"] = 0
module["Bullets"] = 10
module["Range"] = math.huge
module["Damage"] = math.huge
end
end)
-- PLAYER
local SectionPlayer = Player:NewSection("Player")
SectionPlayer:NewSlider("WalkSpeed", "Changes Player WalkSpeed", 500, 16, function(v)
game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = v
end)
SectionPlayer:NewSlider("JumpPower", "Changes Player JumpPower", 500, 50, function(v)
game.Players.LocalPlayer.Character.Humanoid.JumpPower = v
end)
end
|
lotj.chat.routeMessage("commnet")
-- Track commnet messages to potentially squash a redundant translation
-- message on the next line
lotj.chat.commnetLastChannel = matches[2]
lotj.chat.commnetLastMessage = matches[3]
|
local plpretty = require "pl.pretty"
local class = require("pl.class")
local syslog = require("syslog")
local socket = require("socket")
local OutputFile = class()
function OutputFile:_init(config)
self.config = config
assert(type(config.filePattern) == "string")
assert(type(config.lineFormat) == "string")
self.patternFields = {
hostname = socket.dns.gethostname(),
}
end
function OutputFile:Write(data)
local h = self:CheckRotate()
h:write(string.formatEx(self.config.lineFormat, data) .. "\n")
h:flush()
end
function OutputFile:CheckRotate()
local fn = self:GenerateFileName()
local reopen = false
if not self.currentFileName or fn ~= self.currentFileName then
self.currentFileName = fn
reopen = true
end
if reopen then
if self.handle then
self.handle:close()
end
local h = io.open(fn, "a+")
h:setvbuf("no")
self.handle = h
return h
end
return self.handle
end
function OutputFile:GenerateFileName()
local f = self.patternFields
local d = os.date("*t")
d["isdst"] = nil
for k,v in pairs(d) do
f[k] = string.format("%02d", tonumber(v))
end
return string.formatEx(self.config.filePattern, f)
end
return OutputFile
|
-- Data processing based on openmaptiles.org schema
-- https://openmaptiles.org/schema/
-- Copyright (c) 2016, KlokanTech.com & OpenMapTiles contributors.
-- Used under CC-BY 4.0
-- Nodes will only be processed if one of these keys is present
node_keys = { "amenity", "shop", "sport", "tourism", "place", "office", "natural", "addr:housenumber" }
-- Initialize Lua logic
function init_function()
end
-- Finalize Lua logic()
function exit_function()
end
-- Assign nodes to a layer, and set attributes, based on OSM tags
function node_function(node)
local amenity = node:Find("amenity")
local shop = node:Find("shop")
local sport = node:Find("sport")
local tourism = node:Find("tourism")
local office = node:Find("office")
local historic = node:Find("historic")
local housenumber = node:Find("addr:housenumber")
if amenity~="" or shop~="" or sport~="" or tourism ~= "" or office ~= "" or historic ~= "" then
local rank = 10
local class = ""
if amenity~="" then
rank = 4
class = amenity
if amenity == "parking" then
rank = 10
end
elseif shop~="" then
rank = 5
class = shop
elseif sport~="" then
rank = 6
class = sport
elseif tourism~="" then
rank = 3
class = tourism
elseif historic~="" then
rank = 5
class = historic
elseif office~="" then
rank = 7
class = office
end
if rank <= 4 then
node:Layer("poi", false)
else
node:Layer("poi_detail", false)
end
node:Attribute("class", class)
node:AttributeNumeric("rank", rank)
end
local place = node:Find("place")
if place ~= "" then
local rank = 1
if place == "continent" then rank = 1 end
if place == "country" then rank = 1 end
if place == "state" then rank = 1 end
if place == "city" then rank = 2 end
if place == "town" then rank = 3 end
if place == "village" then rank = 4 end
if place == "suburb" then rank = 3 end
if place == "neighbourhood" then rank = 3 end
if place == "locality" then rank = 4 end
if place == "hamlet" then rank = 4 end
if rank <= 3 then
node:Layer("place", false)
else
node:Layer("place_detail", false)
end
node:AttributeNumeric("rank", rank)
node:Attribute("class", place)
end
if natural ~= "" then
if natural == "peak" then
node:Layer("mountain_peak", false)
local ele = node:Find("ele")
if ele ~= "" then
node:AttributeNumeric("ele", ele)
end
node:AttributeNumeric("rank", 5)
end
if natural == "bay" then
node:Layer("water_name", false)
end
end
if historic~="" then
node:Layer("poi_detail", false)
node:AttributeNumeric("rank", 5)
return
end
if housenumber~="" then
node:Layer("housenumber", false)
node:Attribute("housenumber", housenumber)
return
end
SetNameAttributes (node)
end
function SetNameAttributes (obj)
local name = obj:Find("name")
if name ~= "" then
obj:Attribute("name", name)
end
local name_en = name
local name_de = name
if obj:Find("name:en") ~= "" then
name_en = obj:Find("name:en")
end
if obj:Find("name:de") ~= "" then
name_de = obj:Find("name:de")
end
if name_en ~= "" then
obj:Attribute("name_en", name_en)
end
if name_de ~= "" then
obj:Attribute("name_de", name_de)
end
end
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
-- https://stackoverflow.com/a/7615129/4288232
function split(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
-- Similarly for ways
function way_function(way)
local highway = way:Find("highway")
local waterway = way:Find("waterway")
local building = way:Find("building")
local natural = way:Find("natural")
local historic = way:Find("historic")
local landuse = way:Find("landuse")
local leisure = way:Find("leisure")
local amenity = way:Find("amenity")
local aeroway = way:Find("aeroway")
local railway = way:Find("railway")
local sport = way:Find("sport")
local shop = way:Find("shop")
local tourism = way:Find("tourism")
local man_made = way:Find("man_made")
local disused = way:Find("disused")
local isClosed = way:IsClosed()
if disused == "yes" or disused == "1" or disused == "true" then
return
end
if highway~="" then
way:Layer("transportation", false)
local minorRoadValues = Set { "unclassified", "residential", "road" }
if minorRoadValues[highway] then highway = "minor" end
local trackValues = Set { "cycleway", "byway", "bridleway" }
if trackValues[highway] then highway = "track" end
local pathValues = Set { "footway" }
if pathValues[highway] then highway = "path" end
local service = way:Find("service")
if highway == "service" and service ~="" then
way:Attribute("service", service)
end
local linkValues = Set { "motorway_link", "trunk_link", "primary_link", "secondary_link", "tertiary_link" }
if linkValues[highway] then
splitHighway = split(highway, "_")
highway = splitHighway[1]
way:AttributeNumeric("ramp",1)
end
way:Attribute("class", highway)
local bridge = way:Find("bridge")
local tunnel = way:Find("tunnel")
local ford = way:Find("ford")
if bridge == "yes" then
way:Attribute("brunnel", "bridge")
elseif tunnel == "yes" then
way:Attribute("brunnel", "tunnel")
elseif ford == "yes" then
way:Attribute("brunnel", "ford")
end
local oneway = way:Find("oneway")
if oneway == "yes" or oneway == "1" then
way:AttributeNumeric("oneway",1)
end
if oneway == "-1" then
-- TODO
end
if highway ~= "minor" and highway ~= "track" and highway ~= "path" and highway ~= "service" then
way:Layer("transportation_name", false)
else
way:Layer("transportation_name_detail", false)
end
SetNameAttributes(way)
way:Attribute("class", highway)
-- way:Attribute("id",way:Id())
-- way:AttributeNumeric("area",37)
end
if railway~="" then
way:Layer("transportation", false)
way:Attribute("class", railway)
way:Layer("transportation_name", false)
SetNameAttributes(way)
way:Attribute("class", "rail")
end
if waterway~="" then
if waterway == "riverbank" then
way:Layer("water", isClosed)
way:Attribute("class", "river")
elseif waterway == "dock" then
way:Layer("water", isClosed)
way:Attribute("class", "lake")
way:LayerAsCentroid("water_name_detail")
SetNameAttributes(way)
elseif waterway == "boatyard" then
way:Layer("landuse", isClosed)
way:Attribute("class", "industrial")
elseif waterway == "dam" then
way:Layer("building", isClosed)
elseif waterway == "fuel" then
way:Layer("landuse", isClosed)
way:Attribute("class", "industrial")
else
way:Layer("waterway", false)
way:Attribute("class", waterway)
end
end
if building~="" then
way:Layer("building", true)
if way:Holds("name") then
way:LayerAsCentroid("poi_detail")
SetNameAttributes(way)
way:AttributeNumeric("rank", 10)
end
end
if shop~="" then
if way:Holds("name") then
way:LayerAsCentroid("poi_detail")
SetNameAttributes(way)
way:AttributeNumeric("rank", 6)
way:Attribute("class", "shop")
way:Attribute("landuse", shop)
end
end
if natural~="" then
local landcoverkeys = Set { "wood" }
if natural=="water" then
local covered = way:Find("covered")
local river = way:Find("river")
if covered ~= "yes" then
way:Layer("water", true)
if river == "yes" then
way:Attribute("class", "river")
else
way:Attribute("class", "lake")
end
way:LayerAsCentroid("water_name_detail")
SetNameAttributes(way)
if river ~= "yes" then
way:Attribute("class", "lake")
end
end
end
if landcoverkeys[natural] then
way:Layer("landcover", true)
way:Attribute("class", natural)
end
if natural=="glacier" then
way:Layer("landcover", true)
way:Attribute("class", "ice")
end
if natural=="grassland" then
way:Layer("landcover", true)
way:Attribute("class", "grass")
way:Attribute("subclass", natural)
end
if way:Holds("name") then
way:LayerAsCentroid("poi_detail")
SetNameAttributes(way)
way:AttributeNumeric("rank", 8)
way:Attribute("class", "landuse")
way:Attribute("landuse", natural)
end
end
if landuse~="" then
local subclass = ""
local landcover = ""
local water = ""
local farmValues = Set { "field", "farmyard", "allotments", "orchard", "vineyard", "plant_nursery", "farmland"}
if farmValues[landuse] then
landcover = "farmland"
if landuse == "field" then landuse = "farmland" end
if landuse == "farmyard" then landuse = "farm" end
subclass = landuse
end
if landuse == "meadow" then
local meadow = way:Find("meadow")
if meadow == "agricultural" then
landcover = "farmland"
subclass = landuse
else
landcover = "grass"
end
end
if landuse == "recreation_ground" then
landcover = "grass"
subclass = "recreation_ground"
end
if landuse == "village_green" then
landcover = "grass"
subclass = "village_green"
end
if landuse == "wetland" then
landcover = "wetland"
subclass = way:Find("wetland")
end
if landuse == "grass" then
landcover = "grass"
end
if landuse == "reservoir" then
water = "lake"
end
if landuse=="park" then --Incorrect tag but process it anyway
way:Layer("landcover", true)
way:Attribute("class", "grass")
way:Attribute("subclass", "park")
end
if landcover ~= "" then
way:Layer("landcover", true)
way:Attribute("class", landcover)
elseif water ~= "" then
way:Layer("water", true)
way:Attribute("class", water)
else
way:Layer("landuse", true)
way:Attribute("class", landuse)
end
if subclass ~= "" then way:Attribute("subclass", subclass) end
if way:Holds("name") then
way:LayerAsCentroid("poi")
SetNameAttributes(way)
way:AttributeNumeric("rank", 6)
way:Attribute("class", "landuse")
if subclass ~= "" then
way:Attribute("subclass", subclass)
end
end
end
if amenity~="" then
local landusekeys = Set { "school", "university", "kindergarten", "college", "library", "hospital"}
if landusekeys[amenity] then
way:Layer("landuse", true)
way:Attribute("class", amenity)
end
way:LayerAsCentroid("poi")
SetNameAttributes(way)
way:AttributeNumeric("rank", 6)
way:Attribute("class", "amenity")
way:Attribute("subclass", amenity)
end
if leisure~="" then
if leisure=="nature_reserve" then
way:Layer("park", true)
way:Attribute("class", leisure)
end
if leisure=="stadium" then
way:Layer("landuse", true)
way:Attribute("class", leisure)
end
if leisure=="park" then
way:Layer("landcover", true)
way:Attribute("class", "grass")
way:Attribute("subclass", "park")
end
if leisure=="common" then
way:Layer("landcover", true)
way:Attribute("class", "grass")
way:Attribute("subclass", "park")
end
if leisure=="golf_course" then
way:Layer("landcover", true)
way:Attribute("class", "grass")
end
if leisure=="pitch" then
way:Layer("landcover", true)
way:Attribute("class", "grass")
end
if leisure == "recreation_ground" then -- Wrong tag but process anyway
way:Layer("landcover", true)
way:Attribute("class", "grass")
way:Attribute("subclass", "recreation_ground")
end
if way:Holds("name") then
way:LayerAsCentroid("poi_detail")
SetNameAttributes(way)
way:AttributeNumeric("rank", 6)
way:Attribute("class", "leisure")
way:Attribute("subclass", leisure)
end
end
if aeroway~="" then
way:Layer("aeroway", isClosed)
if way:Holds("name") then
way:LayerAsCentroid("poi_detail")
SetNameAttributes(way)
way:AttributeNumeric("rank", 11)
way:Attribute("class", "aeroway")
way:Attribute("subclass", aeroway)
end
end
if man_made~="" then
if way:Holds("name") then
way:LayerAsCentroid("poi_detail")
SetNameAttributes(way)
way:AttributeNumeric("rank", 11)
way:Attribute("class", "man_made")
way:Attribute("subclass", man_made)
end
end
if sport~="" then
if way:Holds("name") then
way:LayerAsCentroid("poi_detail")
SetNameAttributes(way)
way:AttributeNumeric("rank", 10)
way:Attribute("class", "sport")
way:Attribute("subclass", sport)
end
end
if tourism~="" then
if way:Holds("name") then
way:LayerAsCentroid("poi")
SetNameAttributes(way)
way:AttributeNumeric("rank", 5)
way:Attribute("class", "tourism")
way:Attribute("subclass", tourism)
end
end
if historic~="" then
if way:Holds("name") then
way:LayerAsCentroid("poi_detail")
SetNameAttributes(way)
way:AttributeNumeric("rank", 5)
way:Attribute("class", "historic")
way:Attribute("subclass", historic)
end
end
end
|
local lust = require 'test.lust'
local describe, it, expect = lust.describe, lust.it, lust.expect
local EquipmentModifier = require 'valueobjects.EquipmentModifier'
describe('EquipmentModifier', function ()
it('instantiate', function ()
expect(EquipmentModifier()).to.be.a('table')
end)
local data = {
tohit = 123,
attacktimes = 456,
}
local instance
it('instantiate from number', function ()
instance = EquipmentModifier(data)
expect(instance).to.be.a('table')
end)
it('__eq', function ()
expect(instance == EquipmentModifier { tohit = 123, attacktimes = 456 }).to.be.truthy()
expect(instance == EquipmentModifier { tohit = 789, attacktimes = 456 }).to_not.be.truthy()
expect(instance == EquipmentModifier { tohit = 123, attacktimes = 789 }).to_not.be.truthy()
end)
it('__add', function ()
expect(
instance + EquipmentModifier { tohit = 1000, attacktimes = 2000 }
).to.be(EquipmentModifier { tohit = 1123, attacktimes = 2456 })
end)
it('modify', function ()
expect(
instance:modify { tohit = 1000, attacktimes = 2000 }
).to.be(EquipmentModifier { tohit = 1123, attacktimes = 2456 })
end)
it('__call == modify', function ()
expect(
instance { tohit = 1000, attacktimes = 2000 }
== instance:modify { tohit = 1000, attacktimes = 2000 }
).to.be.truthy()
end)
end)
|
local app = app
local libcore = require "core.libcore"
local Class = require "Base.Class"
local Unit = require "Unit"
local GainBias = require "Unit.ViewControl.GainBias"
local Encoder = require "Encoder"
local BumpMap = Class {}
BumpMap:include(Unit)
function BumpMap:init(args)
args.title = "Bump Scanner"
args.mnemonic = "BS"
Unit.init(self, args)
end
function BumpMap:onLoadGraph(channelCount)
if channelCount == 2 then
self:loadStereoGraph()
else
self:loadMonoGraph()
end
end
function BumpMap:loadMonoGraph()
local bump = self:addObject("bump1", libcore.BumpMap())
local center = self:addObject("center", app.ParameterAdapter())
local width = self:addObject("width", app.ParameterAdapter())
local height = self:addObject("height", app.ParameterAdapter())
local fade = self:addObject("fade", app.ParameterAdapter())
connect(self, "In1", bump, "In")
connect(bump, "Out", self, "Out1")
tie(bump, "Center", center, "Out")
tie(bump, "Width", width, "Out")
tie(bump, "Height", height, "Out")
tie(bump, "Fade", fade, "Out")
self:addMonoBranch("center", center, "In", center, "Out")
self:addMonoBranch("width", width, "In", width, "Out")
self:addMonoBranch("height", height, "In", height, "Out")
self:addMonoBranch("fade", fade, "In", fade, "Out")
end
function BumpMap:loadStereoGraph()
local bump1 = self:addObject("bump1", libcore.BumpMap())
local bump2 = self:addObject("bump2", libcore.BumpMap())
local center = self:addObject("center", app.ParameterAdapter())
local width = self:addObject("width", app.ParameterAdapter())
local height = self:addObject("height", app.ParameterAdapter())
local fade = self:addObject("fade", app.ParameterAdapter())
connect(self, "In1", bump1, "In")
connect(self, "In2", bump2, "In")
connect(bump1, "Out", self, "Out1")
connect(bump2, "Out", self, "Out2")
tie(bump1, "Center", center, "Out")
tie(bump1, "Width", width, "Out")
tie(bump1, "Height", height, "Out")
tie(bump1, "Fade", fade, "Out")
tie(bump2, "Center", center, "Out")
tie(bump2, "Width", width, "Out")
tie(bump2, "Height", height, "Out")
tie(bump2, "Fade", fade, "Out")
self:addMonoBranch("center", center, "In", center, "Out")
self:addMonoBranch("width", width, "In", width, "Out")
self:addMonoBranch("height", height, "In", height, "Out")
self:addMonoBranch("fade", fade, "In", fade, "Out")
end
local views = {
expanded = {
"center",
"width",
"height",
"fade"
},
collapsed = {}
}
function BumpMap:onLoadViews(objects, branches)
local controls = {}
controls.center = GainBias {
button = "center",
branch = branches.center,
description = "Center",
gainbias = objects.center,
range = objects.center,
biasMap = Encoder.getMap("[-1,1]"),
biasUnits = app.unitNone,
initialBias = 0.0,
gainMap = Encoder.getMap("gain")
}
controls.width = GainBias {
button = "width",
branch = branches.width,
description = "Width",
gainbias = objects.width,
range = objects.width,
biasMap = Encoder.getMap("unit"),
biasUnits = app.unitNone,
initialBias = 0.5,
gainMap = Encoder.getMap("gain")
}
controls.height = GainBias {
button = "height",
branch = branches.height,
description = "Height",
gainbias = objects.height,
range = objects.height,
biasMap = Encoder.getMap("[-1,1]"),
biasUnits = app.unitNone,
initialBias = 0.5,
gainMap = Encoder.getMap("gain")
}
controls.fade = GainBias {
button = "fade",
branch = branches.fade,
description = "Fade",
gainbias = objects.fade,
range = objects.fade,
biasMap = Encoder.getMap("unit"),
biasUnits = app.unitNone,
initialBias = 0.25,
gainMap = Encoder.getMap("gain")
}
return controls, views
end
return BumpMap
|
--[[
State switcher class: stateswitcher.lua
Author: Daniel Duris, 2014+
dusoft[at]staznosti.sk
http://www.ambience.sk
License: MIT
]]--
passvar={}
state={}
function state.switch(state)
passvar={}
local matches={}
for match in string.gmatch(state,"[^;]+") do
matches[#matches+1]=match
end
state=matches[1]
matches[1]=nil
if (matches[2]~=nil) then
for i,match in pairs(matches) do
passvar[#passvar+1]=match
end
end
-- remove info from metatable about state loaded to allow for new require of the state
package.loaded[state]=false
require(state)
end
function state.clear()
passvar=nil
end
return state
|
local pthread = require'pthread'
local lua = require'luastate'
local ffi = require'ffi'
local glue = require'glue'
local pp = require'pp'
io.stdout:setvbuf'no'
--helpers
local function addr(cdata)
return tonumber(ffi.cast('intptr_t', ffi.cast('void*', cdata)))
end
local function ptr(ctype, p)
return ffi.cast(ctype, ffi.cast('void*', p))
end
--globals
local function test_priority_range()
local pr0 = pthread.min_priority()
local pr1 = pthread.max_priority()
print('priority range: ', pr0, pr1)
assert(pr1 >= pr0)
end
--threads
--test pthread_create(), pthread_join()
--create a new Lua state and a new thread, and run a worker function
--in that state and thread.
local function create_thread(worker, args, attrs)
local state = lua.open()
state:openlibs()
state:push(function(worker, args)
local ffi = require'ffi'
local function pass(...)
_G.retvals = {n = select('#', ...), ...}
end
local function wrapper()
pass(worker(args))
end
local wrapper_cb = ffi.cast('void *(*)(void *)', wrapper)
return tonumber(ffi.cast('intptr_t', wrapper_cb))
end)
local wrapper_cb_ptr = ffi.cast('void *', state:call(worker, args))
local thread = pthread.new(wrapper_cb_ptr, attrs)
local function join()
local status = thread:join()
state:getglobal'retvals'
local t = state:get(-1) or {n = 0}
state:close()
return status, unpack(t, 1, t.n)
end
return join, thread
end
--test pthread_self(), pthread_equal()
local function test_thread_self_equal()
local join, th1 = create_thread(function()
local pthread = require'pthread'
local ffi = require'ffi'
local th = pthread.self()
return ffi.string(th, ffi.sizeof(th))
end)
local _, ths = join()
local th2 = ffi.new'pthread_t'
ffi.copy(th2, ths, #ths)
assert(th1:equal(th2))
end
local function test_priorities()
create_thread(function() end, nil,
{priority = pthread.max_priority()})()
create_thread(function() end, nil,
{priority = pthread.min_priority()})()
end
--speed/leak long test
local function stress_test(times)
io.stdout:write'creating many threads '
for i=1,times do
local joins = {}
local n=10
for i=1,n do
local join, th = create_thread(function(i)
io.stdout:write(i..' ')
end, i)
table.insert(joins, join)
end
for i=n,1,-1 do
joins[i]()
end
collectgarbage()
end
print()
end
--mutexes
local function test_mutex(times, threads)
local m = pthread.mutex{type = 'recursive'}
local joins = {}
local n = ffi.new'int[1]'
for i=1,threads do
local join = create_thread(function(args)
local m, times, n = unpack(args)
local ffi = require'ffi'
local pthread = require'pthread'
local function ptr(ctype, p)
return ffi.cast(ctype, ffi.cast('void*', p))
end
local m = ptr('pthread_mutex_t*', m)
n = ptr('int*', n)
local p=0
for i=1,times do
while not m:trylock() do
p=p+1
end
n[0]=n[0]+1
m:unlock()
end
return p
end, {addr(m), times, addr(n)})
table.insert(joins, join)
end
print'mutex trylocks:'
local np = 0
for i=1,threads do
local _, p = joins[i]()
print('', 'thread ', i, p)
np = np + p
end
assert(n[0] == threads * times)
print(string.format('failed trylocks: %d%%', np / n[0] * 100))
m:free()
end
--test cond. vars
local function test_cond_var(times, timeout)
local mutex = pthread.mutex()
local cond = pthread.cond()
local n = ffi.new('double[1]', -times/2)
local join1 = create_thread(function(args)
local mutex, cond, times, timeout, n = unpack(args)
local ffi = require'ffi'
local pthread = require'pthread'
local function ptr(ctype, p)
return ffi.cast(ctype, ffi.cast('void*', p))
end
local mutex = ptr('pthread_mutex_t*', mutex)
local cond = ptr('pthread_cond_t*', cond)
n = ptr('double*', n)
local p, t = 0, 0
for i=1,times do
mutex:lock()
if n[0] == 100 then
mutex:unlock()
break
end
while n[0] < 0 do
if not cond:wait(mutex, os.time() + timeout) then
t = t + 1
else
--p = p + 1
end
end
if n[0] >= 0 then
p = p + 1
end
mutex:unlock()
end
return p, t
end, {addr(mutex), addr(cond), times, timeout, addr(n)})
local join2 = create_thread(function(args)
local mutex, cond, times, n = unpack(args)
local ffi = require'ffi'
local pthread = require'pthread'
local function ptr(ctype, p)
return ffi.cast(ctype, ffi.cast('void*', p))
end
local mutex = ptr('pthread_mutex_t*', mutex)
local cond = ptr('pthread_cond_t*', cond)
n = ptr('double*', n)
for i=1,times do
mutex:lock()
n[0] = math.sin(i/10)
if n[0] >= 0 then
cond:broadcast()
end
mutex:unlock()
end
--signal exit to other thread
mutex:lock()
n[0] = 100
cond:broadcast()
mutex:unlock()
end, {addr(mutex), addr(cond), times, addr(n)})
local _, p, t = join1()
join2()
print(string.format('cond. var: caught: %d%%, timeouts: %d%%',
p/times * 100, t/times * 100))
cond:free()
mutex:free()
end
--test r/w locks
local function test_rwlock(readtimes, readthreads, writetimes, writethreads)
local rwlock = pthread.rwlock()
local joins = {}
local n = ffi.new'int[1]'
for i = 1, readthreads + writethreads do
local reader = i > writethreads
local join = create_thread(function(args)
local rwlock, times, n, reader = unpack(args)
local ffi = require'ffi'
local pthread = require'pthread'
local function ptr(ctype, p)
return ffi.cast(ctype, ffi.cast('void*', p))
end
local rwlock = ptr('pthread_rwlock_t*', rwlock)
n = ptr('int*', n)
local p=0
for i = 1, times do
if reader then
while not rwlock:tryreadlock() do
p=p+1
end
rwlock:unlock()
else
while not rwlock:trywritelock() do
p=p+1
end
n[0]=n[0]+1
rwlock:unlock()
end
end
return p
end, {
addr(rwlock),
reader and readtimes or writetimes,
addr(n),
reader,
})
table.insert(joins, join)
end
print'rwlock trylocks:'
local np = 0
for i = 1, readthreads + writethreads do
local _, p = joins[i]()
print('', (i > writethreads and 'read' or 'write')..' thread ', i, p)
np = np + p
end
assert(n[0] == writethreads * writetimes)
print(string.format('failed trywritelocks: %d%%', np / n[0] * 100))
rwlock:free()
end
local function test_all()
test_priority_range()
test_thread_self_equal()
test_priorities()
stress_test(10)
test_mutex(50000, 10)
test_cond_var(100000, 1)
test_rwlock(50000, 10, 50000, 1)
end
test_all()
|
local clock = require "clock"
local fiber = require "fiber"
local log = require "log"
local ffi = require "ffi"
local json = require "json".new()
json.cfg {encode_invalid_as_nil = true}
--==================================================================================
-- Embedded indexpiration with some adjustments to stop a worker on non-leader node.
-- Original: https://github.com/moonlibs/indexpiration
--==================================================================================
local M = {}
local function table_clear(t)
if type(t) ~= "table" then
error("bad argument #1 to 'clear' (table expected, got " .. (t ~= nil and type(t) or "no value") .. ")", 2)
end
local count = #t
for i = 0, count do
t[i] = nil
end
return
end
local function typeeq(src, ref)
if ref == "str" then
return src == "STR" or src == "str" or src == "string"
elseif ref == "num" then
return src == "NUM" or src == "num" or src == "number" or src == "unsigned"
else
return src == ref
end
end
local function _mk_keyfunc(index)
local fun
if #index.parts == 1 then
fun = ("return function (t) return t and t[%s] or nil end"):format(index.parts[1].fieldno)
else
local rows = {}
for k = 1, #index.parts do
table.insert(
rows,
("\tt[%s]==nil and NULL or t[%s],\n"):format(index.parts[k].fieldno, index.parts[k].fieldno)
)
end
fun =
"local NULL = require'msgpack'.NULL return function(t) return " ..
"t and {\n" .. table.concat(rows, "") .. "} or nil end\n"
end
-- print(fun)
return dostring(fun)
end
local function _callable(f)
if type(f) == "function" then
return true
else
local mt = debug.getmetatable(f)
return mt and mt.__call
end
end
local F = {}
function F:terminate()
self._terminate = true
self:stop_worker()
end
function F:start_watchdog(space_name)
self._watcher =
fiber.create(
function(expiration)
fiber.name("indexpiration-watchdog")
local is_running = false
while not expiration._terminate do
if (box.info.ro == false or box.info.election.state == "leader") and is_running == false then
log.info("Starting indexpiration worker on %q for %q", box.info.listen, space_name)
expiration:start_worker()
is_running = true
elseif (box.info.ro == true and box.info.election.state ~= "leader") and is_running == true then
log.info("Stopping indexpiration worker on %q for %q", box.info.listen, space_name)
expiration:stop_worker()
is_running = false
end
fiber.sleep(0.01)
end
end,
self
)
end
function F:stop_worker()
if not self.running then
return
end
self.running = false
self._wait:put(true, 0)
end
function F:start_worker()
if self._terminate or self.running then
return
end
self.running = true
self._worker =
fiber.create(
function(space, expiration, expire_index)
local fname = space.name .. ".xpr"
if package.reload then
fname = fname .. "." .. package.reload.count
end
fiber.name(string.sub(fname, 1, 32))
repeat
fiber.sleep(0.001)
until space.expiration
log.info("Worker started")
local curwait
local collect = {}
while box.space[space.name] and space.expiration == expiration and expiration.running do
local r, e =
pcall(
function()
-- print("runat loop 2 ",box.time64())
local remaining
for _, t in expire_index:pairs({0}, {iterator = box.index.GT}) do
-- print("checking ",t)
local delta = expiration.check(t)
if delta <= 0 then
table.insert(collect, t)
else
remaining = delta
break
end
if #collect >= expiration.batch_size then
remaining = 0
break
end
end
if next(collect) then
-- print("batch collected", #collect)
if expiration.txn then
box.begin()
end
for _, t in pairs(collect) do
if not expiration.txn then
if not expiration.running then
remaining = 0
break
end
t = box.space[space.name]:get(expiration._pk(t))
if expiration.check(t) > 0 then
t = nil
end
end
if t then
if expiration.on_delete then
expiration.on_delete(t)
end
space:delete(expiration._pk(t))
end
end
if expiration.txn then
box.commit()
end
-- print("batch deleted")
end
if remaining then
if remaining >= 0 and remaining < 1 then
return remaining
end
end
return 1
end
)
table_clear(collect)
if r then
curwait = e
else
curwait = 1
log.error("Worker/ERR: %s", e)
end
-- log.info("Wait %0.2fs",curwait)
if curwait == 0 then
fiber.sleep(0)
end
expiration._wait:get(curwait)
end
if expiration.running then
log.info("Worker finished")
else
log.info("Worker stopped")
end
end,
box.space[self.space],
self,
self.expire_index
)
end
function M.upgrade(space, opts, depth)
depth = depth or 0
log.info("Indexpiration upgrade(%s,%s)", space.name, json.encode(opts))
if not opts.field then
error("opts.field required", 2)
end
local self = setmetatable({}, {__index = F})
if space.expiration then
self._wait = space.expiration._wait
self._stat = space.expiration._stat
else
self._wait = fiber.channel(0)
end
self.debug = not (not opts.debug)
if opts.txn ~= nil then
self.txn = not (not opts.txn)
else
self.txn = true
end
self.on_delete = opts.on_delete
self.precise = not (not self.precise)
self.batch_size = opts.batch_size or 300
local format_av = box.space._space.index.name:get(space.name)[7]
local format = {}
local have_format = false
for no, f in pairs(format_av) do
format[f.name] = {
name = f.name,
type = f.type,
no = no
}
format[no] = format[f.name]
have_format = true
end
for _, idx in pairs(space.index) do
for _, part in pairs(idx.parts) do
format[part.fieldno] = format[part.fieldno] or {no = part.fieldno}
format[part.fieldno].type = part.type
end
end
local expire_field_no
if have_format then
expire_field_no = format[opts.field].no
else
expire_field_no = opts.field
end
if type(expire_field_no) ~= "number" then
error("Need correct `.field` option", 2 + depth)
end
-- 2. index check
local expire_index
local has_non_tree
for _, index in pairs(space.index) do
if index.parts[1].fieldno == expire_field_no then
if index.type == "TREE" then
expire_index = index
break
else
has_non_tree = index
end
end
end
if not expire_index then
if has_non_tree then
error(string.format("index %s must be TREE (or create another)", has_non_tree.name), 2 + depth)
else
error(string.format("field %s requires tree index with it as first field", opts.field), 2 + depth)
end
end
self._pk = _mk_keyfunc(space.index[0])
-- if not self._stat then
-- self._stat = {
-- counts = {};
-- }
-- end
if opts.kind == "time" or opts.kind == "time64" then
if not typeeq(expire_index.parts[1].type, "num") then
error(("Can't use field %s as %s"):format(opts.field, opts.kind), 2 + depth)
end
if opts.kind == "time" then
self.check = function(t)
return t[expire_field_no] - clock.realtime()
end
elseif opts.kind == "time64" then
self.check = function(t)
return tonumber(ffi.cast("int64_t", t[expire_field_no]) - ffi.cast("int64_t", clock.realtime64())) / 1e9
end
end
elseif _callable(opts.kind) then
self.check = opts.kind
else
error(("Unsupported kind: %s"):format(opts.kind), 2 + depth)
end
self.space = space.id
self.expire_index = expire_index
self._terminate = false
self.running = false
self:start_watchdog(space.name)
if self.precise then
self._on_repl =
space:on_replace(
function(old, new)
self._wait:put(true, 0)
end,
self._on_repl
)
end
rawset(space, "expiration", self)
while self._wait:has_readers() do
self._wait:put(true, 0)
end
log.info("Upgraded %s into indexpiration (status=%s)", space.name, box.info.status)
end
local function indexpiration(space, opts)
M.upgrade(space, opts, 1)
end
--===================================================================
-- Centrifuge Tarantool module.
-- Provides PUB/SUB, ephemeral history streams and channel presence.
--===================================================================
local centrifuge = {}
local function on_disconnect()
local id = box.session.storage.subscriber_id
if id == nil then
return
end
local channelsById = centrifuge.id_to_channels[id] or {}
for key, _ in pairs(channelsById) do
centrifuge.channel_to_ids[key][id] = nil
if next(centrifuge.channel_to_ids[key]) == nil then
centrifuge.channel_to_ids[key] = nil
end
channelsById[key] = nil
end
centrifuge.id_to_channels[id] = nil
centrifuge.id_to_fiber[id]:close()
centrifuge.id_to_fiber[id] = nil
centrifuge.id_to_messages[id] = nil
end
centrifuge.init_spaces = function(opts)
if not opts then
opts = {}
end
local pubs_sync = opts.pubs_sync or false
local meta_sync = opts.meta_sync or false
local pubs_opts = {if_not_exists = true}
if pubs_sync == true then
pubs_opts.is_sync = true
end
box.schema.create_space("pubs", pubs_opts)
box.space.pubs:format(
{
{name = "id", type = "unsigned"},
{name = "channel", type = "string"},
{name = "offset", type = "unsigned"},
{name = "exp", type = "number"},
{name = "data", type = "string"},
}
)
box.space.pubs:create_index(
"primary",
{
parts = {{field = "id", type = "unsigned"}},
if_not_exists = true
}
)
box.space.pubs:create_index(
"channel",
{
parts = {{field = "channel", type = "string"}, {field = "offset", type = "unsigned"}},
if_not_exists = true
}
)
box.space.pubs:create_index(
"exp",
{
parts = {{field = "exp", type = "number"}, {field = "id", type = "unsigned"}},
if_not_exists = true
}
)
local meta_opts = {if_not_exists = true}
if meta_sync == true then
meta_opts.is_sync = true
end
box.schema.create_space("meta", meta_opts)
box.space.meta:format(
{
{name = "channel", type = "string"},
{name = "offset", type = "unsigned"},
{name = "epoch", type = "string"},
{name = "exp", type = "number"}
}
)
box.space.meta:create_index(
"primary",
{
parts = {{field = "channel", type = "string"}},
if_not_exists = true
}
)
box.space.meta:create_index(
"exp",
{
parts = {{field = "exp", type = "number"}, {field = "channel", type = "string"}},
if_not_exists = true
}
)
box.schema.create_space("presence", {if_not_exists = true, temporary = true})
box.space.presence:format(
{
{name = "channel", type = "string"},
{name = "client_id", type = "string"},
{name = "user_id", type = "string"},
{name = "data", type = "string"},
{name = "exp", type = "number"}
}
)
box.space.presence:create_index(
"primary",
{
parts = {{field = "channel", type = "string"}, {field = "client_id", type = "string"}},
if_not_exists = true
}
)
box.space.presence:create_index(
"exp",
{
parts = {{field = "exp", type = "number"}},
if_not_exists = true
}
)
end
centrifuge.start = function(opts)
if not opts then
opts = {}
end
indexpiration(
box.space.pubs,
{
field = "exp",
kind = "time",
precise = true
}
)
indexpiration(
box.space.meta,
{
field = "exp",
kind = "time",
precise = true
}
)
indexpiration(
box.space.presence,
{
field = "exp",
kind = "time",
precise = true
}
)
if not rawget(_G, "__centrifuge_cleanup_set") then
box.session.on_disconnect(on_disconnect)
rawset(_G, "__centrifuge_cleanup_set", true)
end
end
centrifuge.id_to_channels = {}
centrifuge.channel_to_ids = {}
centrifuge.id_to_messages = {}
centrifuge.id_to_fiber = {}
function centrifuge.get_messages(id, use_polling, timeout)
timeout = timeout or 0
if not box.session.storage.subscriber_id then
-- register poller connection. Connection will use this id
-- to register or remove subscriptions.
box.session.storage.subscriber_id = id
centrifuge.id_to_fiber[id] = fiber.channel()
return
end
assert(box.session.storage.subscriber_id == id)
local now = fiber.time()
while true do
-- TODO recheck unsubscribe
local messages = centrifuge.id_to_messages[id]
centrifuge.id_to_messages[id] = nil
if messages then
if use_polling then
-- write all messages to connection and return.
return messages
else
local ok = box.session.push(messages)
if ok ~= true then
error("Write error")
end
end
else
local left = (now + timeout) - fiber.time()
if left <= 0 then
-- timed out, client poller will call get_messages again.
return
end
centrifuge.id_to_fiber[id]:get(left)
end
end
end
function centrifuge.subscribe(id, channels)
for _, v in ipairs(channels) do
local idChannels = centrifuge.id_to_channels[id] or {}
idChannels[v] = true
centrifuge.id_to_channels[id] = idChannels
local channelIds = centrifuge.channel_to_ids[v] or {}
channelIds[id] = true
centrifuge.channel_to_ids[v] = channelIds
end
end
function centrifuge.unsubscribe(id, channels)
for _, v in ipairs(channels) do
if centrifuge.id_to_channels[id] then
centrifuge.id_to_channels[id][v] = nil
end
if centrifuge.channel_to_ids[v] then
centrifuge.channel_to_ids[v][id] = nil
end
if centrifuge.id_to_channels[id] and next(centrifuge.id_to_channels[id]) == nil then
centrifuge.id_to_channels[id] = nil
end
if centrifuge.channel_to_ids[v] and next(centrifuge.channel_to_ids[v]) == nil then
centrifuge.channel_to_ids[v] = nil
end
end
end
local function publish_to_subscribers(channel, message_tuple)
local channelIds = centrifuge.channel_to_ids[channel] or {}
for k, _ in pairs(channelIds) do
centrifuge.id_to_messages[k] = centrifuge.id_to_messages[k] or {}
table.insert(centrifuge.id_to_messages[k], message_tuple)
end
end
local function wake_up_subscribers(channel)
local ids = centrifuge.channel_to_ids[channel] or {}
for k, _ in pairs(ids) do
local chan = centrifuge.id_to_fiber[k]
if chan:has_readers() then
chan:put(true, 0)
end
end
end
function centrifuge._publish(msg_type, channel, data, ttl, size, meta_ttl)
local epoch = ""
local offset = 0
if ttl > 0 and size > 0 then
local now = clock.realtime()
local meta_exp = 0
if meta_ttl > 0 then
meta_exp = now + meta_ttl
end
local stream_meta = box.space.meta:get(channel)
if stream_meta then
offset = stream_meta[2] + 1
epoch = stream_meta[3]
else
epoch = tostring(now)
offset = 1
end
-- Need to use field numbers to work with Tarantool 1.10, otherwise we could write:
-- box.space.meta:upsert({channel, offset, epoch, meta_exp}, {{'=', 'channel', channel}, {'+', 'offset', 1}, {'=', 'exp', meta_exp}})
box.space.meta:upsert({channel, offset, epoch, meta_exp}, {{"=", 1, channel}, {"+", 2, 1}, {"=", 4, meta_exp}})
box.space.pubs:auto_increment {channel, offset, clock.realtime() + tonumber(ttl), data}
local max_offset_to_keep = offset - size
if max_offset_to_keep > 0 then
for _, v in box.space.pubs.index.channel:pairs({channel, max_offset_to_keep}, {iterator = box.index.LE}) do
box.space.pubs:delete {v.id}
end
end
end
-- raise
publish_to_subscribers(channel, {msg_type, channel, offset, epoch, data})
-- raise
wake_up_subscribers(channel)
return {epoch = epoch, offset = offset}
end
function centrifuge.publish(msg_type, channel, data, ttl, size, meta_ttl)
if not ttl then
ttl = 0
end
if not size then
size = 0
end
if not meta_ttl then
meta_ttl = 0
end
box.begin()
local rc, res = pcall(centrifuge._publish, msg_type, channel, data, ttl, size, meta_ttl)
if not rc then
log.warn(
"Publish error: %q %q %q %q %q %q %q",
tostring(res),
msg_type,
channel,
data,
ttl,
size,
meta_ttl
)
box.rollback()
error("Publish error: " .. tostring(res))
end
box.commit()
return res.offset, res.epoch
end
function centrifuge._history(channel, since_offset, limit, reverse, include_pubs, meta_ttl)
if not meta_ttl then
meta_ttl = 0
end
local meta_exp = 0
local now = clock.realtime()
if meta_ttl > 0 then
meta_exp = now + meta_ttl
end
local epoch = tostring(now)
-- Need to use field numbers to work with Tarantool 1.10, otherwise we could write:
-- box.space.meta:upsert({channel, 0, epoch, meta_exp}, {{'=', 'channel', channel}, {'=', 'exp', meta_exp}})
box.space.meta:upsert({channel, 0, epoch, meta_exp}, {{"=", 1, channel}, {"=", 4, meta_exp}})
local stream_meta = box.space.meta:get(channel)
if not include_pubs then
return {stream_meta["offset"], stream_meta["epoch"], nil}
end
if reverse == false and stream_meta["offset"] == since_offset - 1 then
return {stream_meta["offset"], stream_meta["epoch"], nil}
end
local num_entries = 0
local get_offset = since_offset
local iterator = box.index.GE
if reverse == true then
iterator = box.index.LE
if since_offset == 0 then
get_offset = stream_meta["offset"]
end
end
local pubs =
box.space.pubs.index.channel:pairs({channel, get_offset}, {iterator = iterator}):take_while(
function(x)
num_entries = num_entries + 1
return x.channel == channel and (limit < 1 or num_entries < limit + 1)
end
):totable()
return {stream_meta["offset"], stream_meta["epoch"], pubs}
end
function centrifuge.history(channel, since_offset, limit, reverse, include_pubs, meta_ttl)
if channel == nil then
error("No channel specified")
end
box.begin()
local rc, res = pcall(centrifuge._history, channel, since_offset, limit, reverse, include_pubs, meta_ttl)
if not rc then
log.warn("History error %q %q %q %q %q %q", channel, since_offset, limit, reverse, include_pubs, meta_ttl)
box.rollback()
error("History error: " .. tostring(res))
end
box.commit()
return res[1], res[2], res[3]
end
function centrifuge.remove_history(channel)
local batch_size = 10000
box.begin()
for _, v in box.space.pubs.index.channel:pairs {channel} do
box.space.pubs:delete {v.id}
batch_size = batch_size - 1
if batch_size <= 0 then
batch_size = 10000
box.commit()
fiber.yield()
box.begin()
end
end
box.commit()
end
function centrifuge.add_presence(channel, ttl, client_id, user_id, data)
if not ttl then
ttl = 0
end
local exp = clock.realtime() + ttl
box.space.presence:put({channel, client_id, user_id, data, exp})
end
function centrifuge.remove_presence(channel, client_id)
box.space.presence:delete {channel, client_id}
end
function centrifuge.presence(channel)
if channel == nil then
error("No specified channel")
end
return box.space.presence:select {channel}
end
function centrifuge.presence_stats(channel)
if channel == nil then
error("No specified channel")
end
local users = {}
local num_clients = 0
local num_users = 0
for _, v in box.space.presence:pairs({channel}, {iterator = box.index.EQ}) do
num_clients = num_clients + 1
if not users[v.user_id] then
num_users = num_users + 1
users[v.user_id] = true
end
end
return num_clients, num_users
end
function centrifuge.stop()
box.session.on_disconnect(on_disconnect, nil)
rawset(_G, "__centrifuge_cleanup_set", nil)
end
return centrifuge
|
-- The cake is a lie
local portal = {}
portal.__index = portal
--------------------
-- MAIN CALLBACKS --
--------------------
function portal.new(x, y, color)
local self = setmetatable({}, portal)
self.x = x
self.y = y
self.color = color
self.collisionRadius = 15
self.xradius = 20
self.yradius = 32
self.SUMMONING_SICKNESS = 1
return self
end
function portal:update(dt)
local otherPortal
if self.color == "blue" then
otherPortal = state.orangePortal
else --if self.color == "orange" then
otherPortal = state.bluePortal
end
if not otherPortal then return end
if state.player and not state.player.portaled and calcDist(self.x, self.y, state.player.x, state.player.y) <=
(self.collisionRadius + state.player.radius) then
state.player.x = otherPortal.x
state.player.y = otherPortal.y
state.player.portaled = self.SUMMONING_SICKNESS
sounds.teleport:clone():play()
end
if state.opponent and not state.opponent.portaled and calcDist(self.x, self.y, state.opponent.x, state.opponent.y)
<= (self.collisionRadius + state.opponent.radius) then
state.opponent.x = otherPortal.x
state.opponent.y = otherPortal.y
state.opponent.portaled = self.SUMMONING_SICKNESS
sounds.teleport:clone():play()
end
for i, bullet in ipairs(state.bullets) do
if not bullet.portaled and calcDist(self.x, self.y, bullet.x, bullet.y) <=
(self.collisionRadius + bullet.radius) then
bullet.x = otherPortal.x
bullet.y = otherPortal.y
bullet.portaled = self.SUMMONING_SICKNESS
sounds.teleport:clone():play()
end
end
end
function portal:draw()
local thickness = love.graphics.getLineWidth()
love.graphics.setLineWidth(5)
if self.color == "blue" then
love.graphics.setColor(0, 0.396, 1)
elseif self.color == "orange" then
love.graphics.setColor(1, 0.365, 0)
end
love.graphics.ellipse("line", self.x, self.y, self.xradius, self.yradius)
love.graphics.setLineWidth(thickness)
end
---------------------
-- OTHER CALLBACKS --
---------------------
function portal:onDestroy()
if self.color == "blue" then
if state.bluePortal == self then
state.bluePortal = nil
end
elseif self.color == "orange" then
if state.orangePortal == self then
state.orangePortal = nil
end
end
end
classes.portal = portal
|
include( "Civ6Common.lua" ); -- GetCivilizationUniqueTraits, GetLeaderUniqueTraits
include( "SupportFunctions" ); -- Split
CITY_WORK_RANGE = 3
function plotWithinWorkingRange(playerID, plotIndex)
local localPlayerCities = Players[playerID]:GetCities()
local pPlot = Map.GetPlotByIndex(plotIndex)
local plotX = pPlot:GetX()
local plotY = pPlot:GetY()
for _, pCity in localPlayerCities:Members() do
if Map.GetPlotDistance(plotX, plotY, pCity:GetX(), pCity:GetY()) <= CITY_WORK_RANGE then
return true
end
end
return false
end
function plotHasImprovement(plot)
return plot:GetImprovementType() ~= -1;
end
function plotHasResource(plot)
return plot:GetResourceType() ~= -1;
end
function plotHasFeature(plot)
return plot:GetFeatureType() ~= -1;
end
function plotHasWonder(plot)
return plot:GetWonderType() ~= -1;
end
function plotHasDistrict(plot)
return plot:GetDistrictType() ~= -1;
end
function plotHasNaturalWonder(plot)
local featureInfo = GameInfo.Features[plot:GetFeatureType()];
if featureInfo ~= nil and featureInfo.NaturalWonder then
return true
end
return false
end
function plotResourceImprovable(plot)
local plotIndex = plot:GetIndex()
local playerID = Game.GetLocalPlayer()
local valid_terrain = false;
local terrainType = GameInfo.Terrains[plot:GetTerrainType()].TerrainType
-- If the plot has a resource, and the player has discovered it, get the improvement specific to that
if playerHasDiscoveredResource(playerID, plotIndex) then
local resourceInfo = GameInfo.Resources[plot:GetResourceType()]
if resourceInfo ~= nil then
local improvementType;
for validResourceInfo in GameInfo.Improvement_ValidResources() do
if validResourceInfo ~= nil and validResourceInfo.ResourceType == resourceInfo.ResourceType then
improvementType = validResourceInfo.ImprovementType;
-- AZURENCY : check the terrain also
local has_terrain = false;
for inner_row in GameInfo.Improvement_ValidTerrains() do
if(inner_row.ImprovementType == improvementType) then
has_terrain = true;
if(inner_row.TerrainType == terrainType) then
valid_terrain = true;
end
end
end
valid_terrain = not has_terrain or valid_terrain;
if( GameInfo.Terrains[terrainType].TerrainType == "TERRAIN_COAST") then
if ("DOMAIN_SEA" == GameInfo.Improvements[improvementType].Domain) then
valid_terrain = true;
elseif ("DOMAIN_LAND" == GameInfo.Improvements[improvementType].Domain) then
valid_terrain = false;
end
else
if ("DOMAIN_SEA" == GameInfo.Improvements[improvementType].Domain) then
valid_terrain = false;
elseif ("DOMAIN_LAND" == GameInfo.Improvements[improvementType].Domain) then
valid_terrain = true;
end
end
if valid_terrain then
break
end
end
end
if improvementType ~= nil then
local improvementInfo = GameInfo.Improvements[improvementType];
-- print("Plot " .. plotIndex .. " possibly can have " .. improvementType)
return playerCanHave(playerID, improvementInfo);
end
end
end
return false
end
-- General function to check if the player has xmlEntry.PrereqTech and xmlEntry.PrereqTech
-- Also handles unique traits, and bonuses received from city states
function playerCanHave(playerID, xmlEntry)
if xmlEntry == nil then return false; end;
local pPlayer = Players[playerID]
if xmlEntry.PrereqTech ~= nil then
local playerTech:table = pPlayer:GetTechs();
local tech = GameInfo.Technologies[xmlEntry.PrereqTech]
if tech ~= nil and (not playerTech:HasTech(tech.Index)) then
-- print("Player does not have " .. tech.TechnologyType)
return false;
end
end
-- Does the player have the prereq civic if one exists
if xmlEntry.PrereqCivic ~= nil then
local playerCulture = pPlayer:GetCulture();
local civic = GameInfo.Civics[xmlEntry.PrereqCivic]
if civic ~= nil and (not playerCulture:HasCivic(civic.Index)) then
-- print("Player does not have " .. civic.CivicType)
return false;
end
end
-- Is it a Unique thing to a player/civ
if xmlEntry.TraitType ~= nil then
-- print(xmlEntry.TraitType)
local civilizationType = PlayerConfigurations[playerID]:GetCivilizationTypeName()
local leaderType = PlayerConfigurations[playerID]:GetLeaderTypeName()
local isSuzerain:boolean = false;
-- Special handler for city state traits.
local spitResult = Split(xmlEntry.TraitType, "_");
if spitResult[1] == "MINOR" then
local traitLeaderType;
for traitInfo in GameInfo.LeaderTraits() do
if traitInfo.TraitType == xmlEntry.TraitType then
traitLeaderType = traitInfo.LeaderType
break
end
end
if traitLeaderType ~= nil then
-- print("traitLeaderType " .. traitLeaderType)
local traitLeaderID;
-- See if this city state is present in the game
for minorID in ipairs(PlayerManager.GetAliveMinorIDs()) do
local minorLeaderType = PlayerConfigurations[minorID]:GetLeaderTypeName()
if minorLeaderType == traitLeaderType then
traitLeaderID = minorID;
break;
end
end
if traitLeaderID ~= nil then
-- Found the player in the game. Is the suzerain the player
if playerID ~= Players[traitLeaderID]:GetInfluence():GetSuzerain() then
-- print("Player is not the suzerain of " .. minorLeaderType)
return false
else
return true;
end
else
-- print(traitLeaderType .. " is not in this game")
return false;
end
end
end
for traitInfo in GameInfo.CivilizationTraits() do
if traitInfo.TraitType == xmlEntry.TraitType and
traitInfo.CivilizationType ~= nil and
civilizationType ~= traitInfo.CivilizationType then
-- print(civilizationType .. " ~= " .. traitInfo.CivilizationType)
return false
end
end
for traitInfo in GameInfo.LeaderTraits() do
if traitInfo.TraitType == xmlEntry.TraitType and
traitInfo.LeaderType ~= nil and
leaderType ~= traitInfo.LeaderType then
-- print(civilizationType .. " ~= " .. traitInfo.LeaderType)
return false
end
end
end
return true;
end
function playerHasModifier(playerID, modifierType)
-- Get civ, and leader
local civTypeName = PlayerConfigurations[playerID]:GetCivilizationTypeName();
local leaderTypeName = PlayerConfigurations[playerID]:GetLeaderTypeName();
local civUA = GetCivilizationUniqueTraits(civTypeName);
local leaderUA = GetLeaderUniqueTraits(leaderTypeName);
for _, item in ipairs(civUA) do
local traitType = civUA[1].TraitType
-- print("Trait type: " .. traitType)
-- Find the modifier ID
local modifierID;
for row in GameInfo.TraitModifiers() do
if row.TraitType == traitType then
local modifierID = row.ModifierId;
-- Find the matching modifier type
if modifierID ~= nil then
-- print("Modifier ID: " .. modifierID)
for row in GameInfo.Modifiers() do
if row.ModifierId == modifierID and row.ModifierType == modifierType then
-- print("Player has a modifier for district")
return true;
end
end
end
end
end
end
for _, item in ipairs(leaderUA) do
local traitType = leaderUA[1].TraitType
-- print("Trait type: " .. traitType)
-- Find the modifier ID
local modifierID;
for row in GameInfo.TraitModifiers() do
if row.TraitType == traitType then
local modifierID = row.ModifierId;
-- Find the matching modifier type
if modifierID ~= nil then
-- print("Modifier ID: " .. modifierID)
for row in GameInfo.Modifiers() do
if row.ModifierId == modifierID and row.ModifierType == modifierType then
-- print("Player has a modifier for district")
return true;
end
end
end
end
end
end
end
-- Uses same logic as the icon manager (returns true, if the resource icon is being displayed on the map)
function playerHasDiscoveredResource(playerID, plotIndex)
local eObserverID = Game.GetLocalObserver();
local pLocalPlayerVis = PlayerVisibilityManager.GetPlayerVisibility(eObserverID);
local pPlot = Map.GetPlotByIndex(plotIndex);
-- Have a Resource?
local eResource = pLocalPlayerVis:GetLayerValue(VisibilityLayerTypes.RESOURCES, plotIndex);
local bHideResource = ( pPlot ~= nil and ( pPlot:GetDistrictType() > 0 or pPlot:IsCity() ) );
if (eResource ~= nil and eResource ~= -1 and not bHideResource ) then
return true;
end
return false;
end
-- Tells if the district on this plot is complete or not
function districtComplete(playerID, plotIndex)
local pPlayer = Players[playerID];
local pPlot = Map.GetPlotByIndex(plotIndex);
local districtID = pPlot:GetDistrictID();
if districtID ~= nil and districtID >= 0 then
local pDistrict = pPlayer:GetDistricts():FindID(districtID);
if pDistrict ~= nil then
return pDistrict:IsComplete()
end
end
return false;
end
function GetUnitType( playerID: number, unitID : number )
if( playerID == Game.GetLocalPlayer() ) then
local pPlayer :table = Players[playerID];
local pUnit :table = pPlayer:GetUnits():FindID(unitID);
if pUnit ~= nil then
return GameInfo.Units[pUnit:GetUnitType()].UnitType;
end
end
return nil;
end
function has_value (tab, val)
for _, value in ipairs (tab) do
if value == val then
return true
end
end
return false
end
function has_rInfo (tab, val)
for _, value in ipairs (tab) do
if value.ResourceType == val then
return true
end
end
return false
end
function find_and_remove(tab, val)
for i, item in ipairs(tab) do
if item == val then
table.remove(tab, i);
return
end
end
end
function ndup_insert(tab, val)
if not has_value(tab, val) then
table.insert(tab, val);
end
end
function get_common_values(tab1, tab2)
local common_table = {}
for _, value1 in ipairs (tab1) do
for _, value2 in ipairs (tab2) do
if value1 == value2 then
table.insert(common_table, value1)
end
end
end
return common_table
end
--------------------------------------------
-- Plot Iterator, Author: whoward69; URL: https://forums.civfanatics.com/threads/border-and-area-plot-iterators.474634/
-- convert funcs odd-r offset to axial. URL: http://www.redblobgames.com/grids/hexagons/
-- here grid == offset; hex == axial
function ToHexFromGrid(grid)
local hex = {
x = grid.x - (grid.y - (grid.y % 2)) / 2;
y = grid.y;
}
return hex
end
function ToGridFromHex(hex_x, hex_y)
local grid = {
x = hex_x + (hex_y - (hex_y % 2)) / 2;
y = hex_y;
}
return grid.x, grid.y
end
SECTOR_NONE = nil
SECTOR_NORTH = 1
SECTOR_NORTHEAST = 2
SECTOR_SOUTHEAST = 3
SECTOR_SOUTH = 4
SECTOR_SOUTHWEST = 5
SECTOR_NORTHWEST = 6
DIRECTION_CLOCKWISE = false
DIRECTION_ANTICLOCKWISE = true
DIRECTION_OUTWARDS = false
DIRECTION_INWARDS = true
CENTRE_INCLUDE = true
CENTRE_EXCLUDE = false
function PlotRingIterator(pPlot, r, sector, anticlock)
-- print(string.format("PlotRingIterator((%i, %i), r=%i, s=%i, d=%s)", pPlot:GetX(), pPlot:GetY(), r, (sector or SECTOR_NORTH), (anticlock and "rev" or "fwd")))
-- The important thing to remember with hex-coordinates is that x+y+z = 0
-- so we never actually need to store z as we can always calculate it as -(x+y)
-- See http://keekerdc.com/2011/03/hexagon-grids-coordinate-systems-and-distance-calculations/
if (pPlot ~= nil and r > 0) then
local hex = ToHexFromGrid({x=pPlot:GetX(), y=pPlot:GetY()})
local x, y = hex.x, hex.y
-- Along the North edge of the hex (x-r, y+r, z) to (x, y+r, z-r)
local function north(x, y, r, i) return {x=x-r+i, y=y+r} end
-- Along the North-East edge (x, y+r, z-r) to (x+r, y, z-r)
local function northeast(x, y, r, i) return {x=x+i, y=y+r-i} end
-- Along the South-East edge (x+r, y, z-r) to (x+r, y-r, z)
local function southeast(x, y, r, i) return {x=x+r, y=y-i} end
-- Along the South edge (x+r, y-r, z) to (x, y-r, z+r)
local function south(x, y, r, i) return {x=x+r-i, y=y-r} end
-- Along the South-West edge (x, y-r, z+r) to (x-r, y, z+r)
local function southwest(x, y, r, i) return {x=x-i, y=y-r+i} end
-- Along the North-West edge (x-r, y, z+r) to (x-r, y+r, z)
local function northwest(x, y, r, i) return {x=x-r, y=y+i} end
local side = {north, northeast, southeast, south, southwest, northwest}
if (sector) then
for i=(anticlock and 1 or 2), sector, 1 do
table.insert(side, table.remove(side, 1))
end
end
-- This coroutine walks the edges of the hex centered on pPlot at radius r
local next = coroutine.create(function ()
if (anticlock) then
for s=6, 1, -1 do
for i=r, 1, -1 do
coroutine.yield(side[s](x, y, r, i))
end
end
else
for s=1, 6, 1 do
for i=0, r-1, 1 do
coroutine.yield(side[s](x, y, r, i))
end
end
end
return nil
end)
-- This function returns the next edge plot in the sequence, ignoring those that fall off the edges of the map
return function ()
local pEdgePlot = nil
local success, hex = coroutine.resume(next)
-- if (hex ~= nil) then print(string.format("hex(%i, %i, %i)", hex.x, hex.y, -1 * (hex.x+hex.y))) else print("hex(nil)") end
while (success and hex ~= nil and pEdgePlot == nil) do
pEdgePlot = Map.GetPlot(ToGridFromHex(hex.x, hex.y))
if (pEdgePlot == nil) then success, hex = coroutine.resume(next) end
end
return success and pEdgePlot or nil
end
else
-- Iterators have to return a function, so return a function that returns nil
return function () return nil end
end
end
function PlotAreaSpiralIterator(pPlot, r, sector, anticlock, inwards, centre)
-- print(string.format("PlotAreaSpiralIterator((%i, %i), r=%i, s=%i, d=%s, w=%s, c=%s)", pPlot:GetX(), pPlot:GetY(), r, (sector or SECTOR_NORTH), (anticlock and "rev" or "fwd"), (inwards and "in" or "out"), (centre and "yes" or "no")))
-- This coroutine walks each ring in sequence
local next = coroutine.create(function ()
if (centre and not inwards) then
coroutine.yield(pPlot)
end
if (inwards) then
for i=r, 1, -1 do
for pEdgePlot in PlotRingIterator(pPlot, i, sector, anticlock) do
coroutine.yield(pEdgePlot)
end
end
else
for i=1, r, 1 do
for pEdgePlot in PlotRingIterator(pPlot, i, sector, anticlock) do
coroutine.yield(pEdgePlot)
end
end
end
if (centre and inwards) then
coroutine.yield(pPlot)
end
return nil
end)
-- This function returns the next plot in the sequence
return function ()
local success, pAreaPlot = coroutine.resume(next)
return success and pAreaPlot or nil
end
end
-- End of iterator code --------------------
|
local mod = DBM:NewMod(853, "DBM-SiegeOfOrgrimmarV2", nil, 369)
local L = mod:GetLocalizedStrings()
local sndWOP = mod:SoundMM("SoundWOP")
mod:SetRevision(("$Revision: 11372 $"):sub(12, -3))
mod:SetCreatureID(71152, 71153, 71154, 71155, 71156, 71157, 71158, 71160, 71161)
mod:SetEncounterID(1593)
mod:SetMinSyncRevision(10768)
mod:SetHotfixNoticeRev(10768)
mod:SetZone()
mod:SetUsedIcons(3, 1)
mod:SetBossHPInfoToHighest()
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START",
"SPELL_CAST_SUCCESS",
"SPELL_AURA_APPLIED",
"SPELL_AURA_APPLIED_DOSE",
"SPELL_AURA_REMOVED",
"SPELL_PERIODIC_DAMAGE",
"SPELL_PERIODIC_MISSED",
"SPELL_DAMAGE",
"SPELL_MISSED",
"CHAT_MSG_MONSTER_EMOTE",
"UNIT_DIED"
)
----------------------------------------------------------------------------------------------------------------------------------------
-- A moment of silence to remember Malik the Unscathed, the 10th paragon that perished an honorable death in battle against Shek'zeer --
----------------------------------------------------------------------------------------------------------------------------------------
--All
local warnActivated = mod:NewTargetAnnounce(118212, 3, 143542)
--Kil'ruk the Wind-Reaver
local warnGouge = mod:NewTargetAnnounce(143939, 3, nil, mod:IsTank() or mod:IsHealer())--Timing too variable for a CD
local warnDeathFromAbove = mod:NewTargetAnnounce(142232, 3)
local warnReave = mod:NewCastAnnounce(148676, 3)
--Xaril the Poisoned-Mind
local warnToxicInjection = mod:NewSpellAnnounce(142528, 3)
local warnCausticBlood = mod:NewSpellAnnounce(142315, 4, nil, mod:IsTank(), nil, nil, nil, nil, 2)
mod:AddBoolOption("warnToxicCatalyst", true, "announce")
local warnToxicCatalystBlue = mod:NewCastAnnounce(142725, 4, nil, nil, nil, false)
local warnToxicCatalystRed = mod:NewCastAnnounce(142726, 4, nil, nil, nil, false)
local warnToxicCatalystYellow = mod:NewCastAnnounce(142727, 4, nil, nil, nil, false)
local warnToxicCatalystOrange = mod:NewCastAnnounce(142728, 4, nil, nil, nil, false)--Heroic
local warnToxicCatalystPurple = mod:NewCastAnnounce(142729, 4, nil, nil, nil, false)--Heroic
local warnToxicCatalystGreen = mod:NewCastAnnounce(142730, 4, nil, nil, nil, false)--Heroic
--local warnToxicCatalystWhite = mod:NewCastAnnounce(142731, 3, nil, nil, nil, false)--Not in EJ
--Kaz'tik the Manipulator
local warnMesmerize = mod:NewTargetAnnounce(142671, 3)
local warnSonicProjection = mod:NewSpellAnnounce(143765, 3, nil, false)--Spammy, and target scaning didn't work
--Korven the Prime
local warnShieldBash = mod:NewSpellAnnounce(143974, 3, nil, mod:IsTank() or mod:IsHealer())
local warnEncaseInAmber = mod:NewTargetAnnounce(142564, 4)
--Iyyokuk the Lucid
local warnDiminish = mod:NewSpellAnnounce(143666, 4, nil, false)--Spammy, target scanning was iffy
local warnCalculated = mod:NewTargetAnnounce(144095, 3)--Wild variation on timing noted, 34-130.8 variation (wtf)
local warnInsaneCalculationFire = mod:NewCastAnnounce(142416, 4)--3 seconds after 144095
--Ka'roz the Locust
local warnFlash = mod:NewCastAnnounce(143709, 3, 2)--62-70
local warnWhirling = mod:NewTargetAnnounce(143702, 3)
local warnHurlAmber = mod:NewSpellAnnounce(143759, 3)
--Skeer the Bloodseeker
local warnBloodletting = mod:NewSpellAnnounce(143280, 4)
--Rik'kal the Dissector
local warnInjection = mod:NewStackAnnounce(143339)
local warnMutate = mod:NewTargetAnnounce(143337, 3)
local warnResult = mod:NewTargetAnnounce(144095, 3)
--Hisek the Swarmkeeper
local warnAim = mod:NewTargetAnnounce(142948, 4)--Maybe wrong debuff id, maybe 144759 instead
local warnRapidFire = mod:NewSpellAnnounce(143243, 3)
--All
--NOTE, this is purely off assumption the ones that make you vunerable to eachother don't spawn at same time.
--It's also possible tehse tank only activate warnings are useless if 4 vulnerability mobs always spawns in pairs
--Then it just means it's an anti solo tank mechanic and we don't need special warnings for it.
local specWarnActivated = mod:NewSpecialWarningTarget(118212)
local specWarnActivatedVulnerable = mod:NewSpecialWarning("specWarnActivatedVulnerable", mod:IsTank())--Alternate activate warning to warn a tank not to pick up a specific boss
--Kil'ruk the Wind-Reaver
local specWarnGouge = mod:NewSpecialWarningYou(143939)
local specWarnGougeOther = mod:NewSpecialWarningTarget(143939, mod:IsTank() or mod:IsHealer())
local specWarnDeathFromAbove = mod:NewSpecialWarningYou(142232)
local specWarnDeathFromAboveNear = mod:NewSpecialWarningClose(142232)
local yellDeathFromAbove = mod:NewYell(142232)
local specWarnReave = mod:NewSpecialWarningSpell(148676, nil, nil, nil, 2)--Heroic
--Xaril the Poisoned-Mind
local specWarnCausticBlood = mod:NewSpecialWarningSpell(142315, mod:IsTank())
local specWarnToxicBlue = mod:NewSpecialWarningYou(142532)
local specWarnToxicRed = mod:NewSpecialWarningYou(142533)
local specWarnToxicYellow = mod:NewSpecialWarningYou(142534)
--local specWarnToxicOrange = mod:NewSpecialWarningYou(142547)--Heroic
--local specWarnToxicPurple = mod:NewSpecialWarningYou(142548)--Heroic
--local specWarnToxicGreen = mod:NewSpecialWarningYou(142549)--Heroic
local specWarnGas = mod:NewSpecialWarningMove(142797)--BH ADD
--local specWarnToxicWhite = mod:NewSpecialWarningYou(142550)--Not in EJ
local specWarnCatalystBlue = mod:NewSpecialWarningYou(142725, nil, nil, nil, 3)
local specWarnCatalystRed = mod:NewSpecialWarningYou(142726, nil, nil, nil, 3)
local specWarnCatalystYellow = mod:NewSpecialWarningYou(142727, nil, nil, nil, 3)
local specWarnCatalystOrange = mod:NewSpecialWarningYou(142728, nil, nil, nil, 3)--Heroic
local specWarnCatalystPurple = mod:NewSpecialWarningYou(142729, nil, nil, nil, 3)--Heroic
local specWarnCatalystGreen = mod:NewSpecialWarningYou(142730, nil, nil, nil, 3)--Heroic
--local specWarnCatalystWhite = mod:NewSpecialWarningYou(142731, nil, nil, nil, 3)--Not in EJ
mod:AddBoolOption("yellToxicCatalyst", true, "misc")--And lastly, combine yells
local yellCatalystBlue = mod:NewYell(142725, nil, nil, false)
local yellCatalystRed = mod:NewYell(142726, nil, nil, false)
local yellCatalystYellow = mod:NewYell(142727, nil, nil, false)
local yellCatalystOrange = mod:NewYell(142728, nil, nil, false)
local yellCatalystPurple = mod:NewYell(142729, nil, nil, false)
local yellCatalystGreen = mod:NewYell(142730, nil, nil, false)
--Kaz'tik the Manipulator
local specWarnMesmerize = mod:NewSpecialWarningYou(142671)
local yellMesmerize = mod:NewYell(142671, nil, false)
local specWarnKunchongs = mod:NewSpecialWarningSwitch("ej8043", mod:IsDps())
--Korven the Prime
local specWarnShieldBash = mod:NewSpecialWarningYou(143974)
local specWarnShieldBashOther = mod:NewSpecialWarningTarget(143974, mod:IsTank() or mod:IsHealer())
local specWarnEncaseInAmber = mod:NewSpecialWarningTarget(142564, mod:IsDps())--Better than switch because on heroic, you don't actually switch to amber, you switch to a NON amber target. Plus switch gives no targetname
--Iyyokuk the Lucid
local specWarnCalculated = mod:NewSpecialWarningYou(144095)
local yellCalculated = mod:NewYell(144095, nil, false)
local specWarnCriteriaLinked = mod:NewSpecialWarning("specWarnCriteriaLinked")--Linked to Calculated target
local specWarnInsaneCalculationFire = mod:NewSpecialWarningSpell(142416, nil, nil, nil, 2)
--Ka'roz the Locust
local specWarnFlash = mod:NewSpecialWarningSpell(143709, nil, nil, nil, 2)--I realize two abilities on same boss both using same sound is less than ideal, but user can change it now, and 1 or 3 feel appropriate for both of these
local specWarnWhirling = mod:NewSpecialWarningYou(143701)
local yellWhirling = mod:NewYell(143701, nil, false)
local specWarnWhirlingNear = mod:NewSpecialWarningClose(143701)
local specWarnHurlAmber = mod:NewSpecialWarningSpell(143759, nil, nil, nil, 2)--I realize two abilities on same boss both using same sound is less than ideal, but user can change it now, and 1 or 3 feel appropriate for both of these
local specWarnCausticAmber = mod:NewSpecialWarningMove(143735)--Stuff on the ground
local specWarnFireline = mod:NewSpecialWarningMove(142808)
--Skeer the Bloodseeker
local specWarnBloodletting = mod:NewSpecialWarningSwitch(143280, not mod:IsHealer())
--Rik'kal the Dissector
local specWarnMutate = mod:NewSpecialWarningYou(143337)
local specWarnParasiteFixate = mod:NewSpecialWarningYou(143358)
local specWarnInjection = mod:NewSpecialWarningSpell(143339, mod:IsTank(), nil, nil, 3)
--Hisek the Swarmkeeper
local specWarnAim = mod:NewSpecialWarningYou(142948)
local yellAim = mod:NewYell(142948)
local specWarnAimOther = mod:NewSpecialWarningTarget(142948)
local specWarnRapidFire = mod:NewSpecialWarningSpell(143243, nil, nil, nil, 2)
local timerJumpToCenter = mod:NewCastTimer(5, 143545)
--Kil'ruk the Wind-Reaver
local timerGouge = mod:NewTargetTimer(10, 143939, nil, mod:IsTank())
local timerGougeCD = mod:NewCDTimer(20, 143939)
local timerReaveCD = mod:NewCDTimer(33, 148676)
--Xaril the Poisoned-Mind
local timerToxicCatalystCD = mod:NewCDTimer(33, "ej8036")
--Korven the Prime
local timerShieldBash = mod:NewTargetTimer(6, 143974, nil, mod:IsTank())
local timerShieldBashCD = mod:NewCDTimer(17, 143974, nil, mod:IsTank())
local timerEncaseInAmber = mod:NewTargetTimer(10, 142564)
local timerEncaseInAmberCD = mod:NewCDTimer(30, 142564)--Technically a next timer but we use cd cause it's only cast if someone is low when it comes off 30 second internal cd. VERY important timer for heroic
--Iyyokuk the Lucid
local timerCalculated = mod:NewBuffFadesTimer(6, 144095)
local timerInsaneCalculationCD = mod:NewCDTimer(25, 142416)--25 is minimum but variation is wild (25-50 second variation)
--Ka'roz the Locust
local timerFlashCD = mod:NewCDTimer(62, 143709)
local timerWhirling = mod:NewBuffFadesTimer(5, 143701)
local timerHurlAmberCD = mod:NewCDTimer(62, 143759)--TODO< verify cd on spell itself. in my logs he died after only casting it once every time.
--Skeer the Bloodseeker
local timerBloodlettingCD = mod:NewCDTimer(35, 143280)--35-65 variable. most of the time it's around 42 range
--Rik'kal the Dissector
local timerMutate = mod:NewBuffFadesTimer(20, 143337)
local timerMutateCD = mod:NewCDCountTimer(45, 143337)
local timerInjectionCD = mod:NewNextCountTimer(9.5, 143339, nil, mod:IsTank())
--Hisek the Swarmkeeper
local timerAim = mod:NewTargetTimer(5, 142948)--or is it 7, conflicting tooltips
local timerAimCD = mod:NewCDTimer(42, 142948)
local timerRapidFireCD = mod:NewCDTimer(47, 143243)--Heroic, unknown Cd
local berserkTimer = mod:NewBerserkTimer(720)
--local countdownEncaseInAmber = mod:NewCountdown(30, 142564)--Probably switch to secondary countdown if one of his other abilities proves to have priority
local twipe = table.wipe
local chongnum = 0
local firecount = 0
local injcount = 0
local mutatecount = 0
local dissectorlive = true
local showtank = false
local xiezireset = 0
local havecolor = false
local caled = false
local havedebuff = false
mod:AddBoolOption("LTIP", true, "sound")
mod:AddBoolOption("RangeFrame")
mod:AddBoolOption("SetIconOnAim", true)--multi boss fight, will use star and avoid moving skull off a kill target
mod:AddBoolOption("LTchong", mod:IsTank(), "sound")
mod:AddBoolOption("InfoFrame", true, "sound")
mod:AddBoolOption("ShowGrouptarget", true, "sound")
mod:AddBoolOption("HudMAP", true, "sound")
mod:AddBoolOption("HudMAPMZ", true, "sound")
mod:AddBoolOption("dr", true, "sound")
for i = 1, 6 do
mod:AddBoolOption("dr"..i, false, "sound")
end
local function MyJS()
if (mod.Options.dr1 and firecount == 1) or (mod.Options.dr2 and firecount == 2) or (mod.Options.dr3 and firecount == 3) or (mod.Options.dr4 and firecount == 4) or (mod.Options.dr5 and firecount == 5) or (mod.Options.dr6 and firecount == 6) then
return true
end
return false
end
local DBMHudMap = DBMHudMap
local free = DBMHudMap.free
local function register(e)
DBMHudMap:RegisterEncounterMarker(e)
return e
end
local RedMarkers={}
local BlueMarkers={}
local YellowMarkers={}
local MZMarkers={}
local DFMarker={}
local CMMarkers={}
local activatedTargets = {}--A table, for the 3 on pull
local mutateTargets = {}
local activeBossGUIDS = {}
local UnitDebuff = UnitDebuff
local GetSpellInfo = GetSpellInfo
local calculatedShape = nil
local calculatedNumber = nil
local calculatedColor = nil
local calculatingDude = EJ_GetSectionInfo(8012)
local readyToFight = GetSpellInfo(143542)
local bossspellinfo = {}
local xiezi = {}
local ResultTargets = {}
local ResultMeleeTargets = {}
local ResultRangedTargets = {}
local ResultRangedDPSTargets = {}
local ResultGroupTargets = {}
local myGroup = 0
local ResultXFTargets = {}
--[[EJ_GetSectionInfo(8004) --掠风者 71161
EJ_GetSectionInfo(8009) --毒心者 71157
EJ_GetSectionInfo(8010) --操纵者 71156
EJ_GetSectionInfo(8011) --至尊者 71155
EJ_GetSectionInfo(8012) --明澈者 71160
EJ_GetSectionInfo(8013) --暴食蝗 71154
EJ_GetSectionInfo(8014) --觅血者 71152
EJ_GetSectionInfo(8015) --切割者 71158
EJ_GetSectionInfo(8016) --虫群卫士 71153 ]]
local function showspellinfo()
if mod:IsDifficulty("heroic25") then return end
if mod.Options.InfoFrame then
twipe(bossspellinfo)
local onlyactboss = 0
for i = 1, 5 do
local cid = mod:GetCIDFromGUID(UnitGUID("boss"..i))
if cid == 71161 then
bossspellinfo[i] = {name = L.LF, spell = L.LFspell}
onlyactboss = onlyactboss + 1
elseif cid == 71157 then
bossspellinfo[i] = {name = L.DX, spell = L.DXspell}
onlyactboss = onlyactboss + 1
elseif cid == 71156 then
bossspellinfo[i] = {name = L.CZ, spell = L.CZspell}
onlyactboss = onlyactboss + 1
elseif cid == 71155 then
bossspellinfo[i] = {name = L.ZZ, spell = L.ZZspell}
onlyactboss = onlyactboss + 1
elseif cid == 71160 then
bossspellinfo[i] = {name = L.MC, spell = L.MCspell}
onlyactboss = onlyactboss + 1
elseif cid == 71154 then
bossspellinfo[i] = {name = L.BS, spell = L.BSspell}
onlyactboss = onlyactboss + 1
elseif cid == 71152 then
bossspellinfo[i] = {name = L.MX, spell = L.MXspell}
onlyactboss = onlyactboss + 1
elseif cid == 71158 then
bossspellinfo[i] = {name = L.QG, spell = L.QGspell}
onlyactboss = onlyactboss + 1
elseif cid == 71153 then
bossspellinfo[i] = {name = L.CQ, spell = L.CQspell}
onlyactboss = onlyactboss + 1
end
if onlyactboss == 3 then break end
end
local bossnum = 0
for k,v in pairs(bossspellinfo) do
bossnum = bossnum + 1
end
DBM.InfoFrame:SetHeader(L.BossSpellInfo)
local firstboss = 1
if not bossspellinfo[1] then firstboss = 2 end
if bossnum == 1 then
DBM.InfoFrame:Show(1, "other", bossspellinfo[firstboss].spell, bossspellinfo[firstboss].name)
elseif bossnum == 2 then
DBM.InfoFrame:Show(2, "other", bossspellinfo[firstboss].spell, bossspellinfo[firstboss].name, bossspellinfo[firstboss + 1].spell, bossspellinfo[firstboss + 1].name)
elseif bossnum == 3 then
DBM.InfoFrame:Show(3, "other", bossspellinfo[firstboss].spell, bossspellinfo[firstboss].name, bossspellinfo[firstboss + 1].spell, bossspellinfo[firstboss + 1].name, bossspellinfo[firstboss + 2].spell, bossspellinfo[firstboss + 2].name)
end
end
end
local function testinfo()
if not mod:IsDifficulty("heroic25") then return end
local showxiezi = {}
local xiezinum = 0
for k,v in pairs(xiezi) do
xiezinum = xiezinum + 1
showxiezi[xiezinum] = k
end
if mod.Options.InfoFrame then
DBM.InfoFrame:Hide()
DBM.InfoFrame:SetHeader(EJ_GetSectionInfo(8065).." : "..chongnum)
if showxiezi[3] then
DBM.InfoFrame:Show(3, "other", xiezi[showxiezi[1]], showxiezi[1], xiezi[showxiezi[2]], showxiezi[2], xiezi[showxiezi[3]], showxiezi[3])
end
if (not dissectorlive) and (chongnum == 0) then
DBM.InfoFrame:Hide()
end
end
twipe(showxiezi)
xiezinum = 0
end
local function warnActivatedTargets(vulnerable)
if #activatedTargets > 1 then
warnActivated:Show(table.concat(activatedTargets, "<, >"))
-- specWarnActivated:Show(table.concat(activatedTargets, ", "))
else
warnActivated:Show(activatedTargets[1])
if vulnerable and mod:IsTank() then
specWarnActivatedVulnerable:Show(activatedTargets[1])
else
specWarnActivated:Show(activatedTargets[1])
end
end
twipe(activatedTargets)
end
local function warnMutatedTargets()
warnMutate:Show(table.concat(mutateTargets, "<, >"))
twipe(mutateTargets)
if mod:AntiSpam(5, 1) then
mutatecount = mutatecount + 1
sndWOP:Play("ex_so_tb") --突變
if mutatecount == 1 then
sndWOP:Schedule(0.5, "countone")
elseif mutatecount == 2 then
sndWOP:Schedule(0.5, "counttwo")
elseif mutatecount == 3 then
sndWOP:Schedule(0.5, "countthree")
elseif mutatecount == 4 then
sndWOP:Schedule(0.5, "countfour")
elseif mutatecount == 5 then
sndWOP:Schedule(0.5, "countfive")
elseif mutatecount == 6 then
sndWOP:Schedule(0.5, "countsix")
end
timerMutateCD:Start(45, mutatecount+1)
end
end
local function hideRangeFrame()
if mod.Options.RangeFrame then
DBM.RangeCheck:Hide()
end
end
--Another pre target scan (ie targets player BEFORE cast like iron qon)
local function DFAScan()
for i = 1, 5 do
local unitID = "boss"..i
if UnitExists(unitID) and mod:GetCIDFromGUID(UnitGUID(unitID)) == 71161 then
if UnitExists(unitID.."target") and not mod:IsTanking(unitID.."target", unitID) then
mod:Unschedule(DFAScan)
local targetname = DBM:GetUnitFullName(unitID.."target")
warnDeathFromAbove:Show(targetname)
if UnitIsUnit(unitID.."target", "player") then
specWarnDeathFromAbove:Show()
yellDeathFromAbove:Yell()
sndWOP:Play("runaway") --快躲開
else
local x, y = GetPlayerMapPosition(unitID.."target")
if x == 0 and y == 0 then
SetMapToCurrentZone()
x, y = GetPlayerMapPosition(unitID.."target")
end
local inRange = DBM.RangeCheck:GetDistance("player", x, y)
if inRange and inRange < 6 then
specWarnDeathFromAboveNear:Show(targetname)
sndWOP:Play("runaway") --快躲開
end
end
if mod.Options.HudMAPMZ then
DFMarker[targetname] = register(DBMHudMap:PlaceStaticMarkerOnPartyMember("highlight", targetname, 8, 3, 0, 1, 0, 0.8):Appear():RegisterForAlerts())
end
else
mod:Schedule(0.25, DFAScan)
end
return--If we found the boss before hitting 5, want to fire this return to break checking other bosses needlessly
end
end
end
local function HeroicDFAScan()
for i = 1, 5 do
local unitID = "boss"..i
if UnitExists(unitID) and mod:GetCIDFromGUID(UnitGUID(unitID)) == 71161 then
if (not UnitExists(unitID.."target")) or not mod:IsTanking(unitID.."target", unitID) then
mod:Unschedule(HeroicDFAScan)
sndWOP:Play("ex_so_sctj") --死從天降
for i = 1, DBM:GetNumGroupMembers() do
local _, class = UnitClass("raid"..i)
if (class == "DRUID" and UnitPowerMax("raid"..i) > 200000) or class == "HUNTER" or class == "PRIEST" or class == "MAGE" or class == "WARLOCK" or (class == "SHAMAN" and UnitPowerMax("raid"..i) > 200000) or (class == "PALADIN" and UnitPowerMax("raid"..i) > 200000) then
DFMarker[UnitName("raid"..i)] = register(DBMHudMap:PlaceStaticMarkerOnPartyMember("highlight", UnitName("raid"..i), 8, 3, 1, 1 ,1 ,0.4):Appear():RegisterForAlerts())
end
end
else
mod:Schedule(0.2, HeroicDFAScan)
end
return
end
end
end
local function CheckBosses()
local vulnerable = false
for i = 1, 3 do--Assume boss 4 is always the inactive one. Need to verify this works, because filtering by ready to fight causes start timers not to work
local unitID = "boss"..i
--Only 3 bosses activate on pull, however now the inactive or (next boss to activate) also fires IEEU. As such, we have to filter that boss by scaning for readytofight. Works well though.
if UnitExists(unitID) and not activeBossGUIDS[UnitGUID(unitID)] then--Check if new units exist we haven't detected and added yet.
local activetime = GetTime() - mod.combatInfo.pull
activeBossGUIDS[UnitGUID(unitID)] = true
activatedTargets[#activatedTargets + 1] = UnitName(unitID)
--Activation Controller
local cid = mod:GetCIDFromGUID(UnitGUID(unitID))
if cid == 71161 then--Kil'ruk the Wind-Reaver
if mod:IsDifficulty("heroic10", "heroic25") then
timerReaveCD:Start(38.5)
end
if mod:IsDifficulty("heroic10", "heroic25") then
mod:Schedule(15, HeroicDFAScan)--Not a large sample size, data shows it happen 29-30 seconds after IEEU fires on two different pulls. Although 2 is a poor sample
else
mod:Schedule(23, DFAScan)--Not a large sample size, data shows it happen 29-30 seconds after IEEU fires on two different pulls. Although 2 is a poor sample
end
timerGougeCD:Start()
if UnitDebuff("player", GetSpellInfo(142929)) then vulnerable = true end
if activetime >= 15 then
sndWOP:Play("ex_so_lfz") --掠風者參戰
end
elseif cid == 71157 then--Xaril the Poisoned-Mind
if UnitDebuff("player", GetSpellInfo(142931)) then vulnerable = true end
if activetime >= 15 then
sndWOP:Play("ex_so_dxz") --毒心者參戰
end
elseif cid == 71156 then--Kaz'tik the Manipulator
if activetime >= 15 then
sndWOP:Play("ex_so_czz") --操縱者參戰
sndWOP:Schedule(1, "ex_so_ylcz")
end
elseif cid == 71155 then--Korven the Prime
timerShieldBashCD:Start(19)--20seconds from REAL IEEU
if activetime >= 15 then
sndWOP:Play("ex_so_zzz") --至尊者參戰
end
elseif cid == 71160 then--Iyyokuk the Lucid
timerInsaneCalculationCD:Start()
if activetime >= 15 then
sndWOP:Play("ex_so_mcz") --明澈者參戰
end
elseif cid == 71154 then--Ka'roz the Locust
timerFlashCD:Start(14)--In final LFR test, he didn't cast this for 20 seconds. TODO check this change
timerHurlAmberCD:Start(44)
if activetime >= 15 then
sndWOP:Play("ex_so_bsh") --暴食蝗參戰
end
elseif cid == 71152 then--Skeer the Bloodseeker
timerBloodlettingCD:Start(9)
if UnitDebuff("player", GetSpellInfo(143279)) then vulnerable = true end
if activetime >= 15 then
sndWOP:Play("ex_so_nxz") --覓血者參戰
end
elseif cid == 71158 then--Rik'kal the Dissector
timerInjectionCD:Start(7.5, 1)
if mod.Options.LTchong then
DBM:ShowLTSpecialWarning("NEXT:1", 1, 0, 0, nil, 144286, nil, 7.5)
showtank = true
end
timerMutateCD:Start(34, 1)
if UnitDebuff("player", GetSpellInfo(143275)) then vulnerable = true end
if activetime >= 15 then
sndWOP:Play("ex_so_qgz") --切割者參戰
end
elseif cid == 71153 then--Hisek the Swarmkeeper
timerAimCD:Start(37)--Might be 32 now with the UnitBuff filter, so pay attention to that and adjust as needed
if mod:IsDifficulty("heroic10", "heroic25") then
timerRapidFireCD:Start(44.5)
end
if activetime >= 15 then
sndWOP:Play("ex_so_cqws") --蟲群衛士參戰
end
end
end
end
if #activatedTargets >= 1 then
warnActivatedTargets(vulnerable)--Down here so we can send tank vulnerable status
end
showspellinfo()
end
function mod:OnCombatStart(delay)
twipe(activeBossGUIDS)
twipe(activatedTargets)
twipe(mutateTargets)
twipe(RedMarkers)
twipe(BlueMarkers)
twipe(YellowMarkers)
twipe(MZMarkers)
twipe(CMMarkers)
twipe(DFMarker)
twipe(xiezi)
twipe(ResultXFTargets)
twipe(ResultTargets)
twipe(ResultMeleeTargets)
twipe(ResultRangedTargets)
twipe(ResultRangedDPSTargets)
twipe(ResultGroupTargets)
calculatedShape = nil
calculatedNumber = nil
calculatedColor = nil
chongnum = 0
firecount = 0
injcount = 0
mutatecount = 0
dissectorlive = true
self:RegisterShortTermEvents(
"INSTANCE_ENCOUNTER_ENGAGE_UNIT"--We register here to make sure we wipe variables on pull
)
timerJumpToCenter:Start(-delay)
berserkTimer:Start(-delay)
xiezireset = 0
showtank = false
havecolor = false
havedebuff = false
caled = false
end
function mod:OnCombatEnd()
warnWhirling:Show(table.concat(ResultXFTargets, "<, >"))
self:UnregisterShortTermEvents()
if self.Options.RangeFrame then
DBM.RangeCheck:Hide()
end
if self.Options.InfoFrame then
DBM.InfoFrame:Hide()
end
if self.Options.HudMAP or self.Options.HudMAPMZ then
DBMHudMap:FreeEncounterMarkers()
end
if self.Options.LTchong or self.Options.LTIP then
-- DBM:HideLTSpecialWarning()
end
end
--"<13.6 19:16:29> [UNIT_SPELLCAST_SUCCEEDED] Iyyokuk the Lucid [[boss2:Jump to Center::0:143545]]", -- [95]
--^don't let above fool you, not all of the paragons fire this spell!!! that is why we MUST use IEEU
function mod:INSTANCE_ENCOUNTER_ENGAGE_UNIT()
self:Unschedule(CheckBosses)
self:Schedule(1, CheckBosses)--Delay check to make sure we run function only once on pull
end
function mod:SPELL_CAST_START(args)
if args.spellId == 142725 then
timerToxicCatalystCD:Start()
if self.Options.warnToxicCatalyst then
warnToxicCatalystBlue:Show()
end
if UnitDebuff("player", GetSpellInfo(142532)) then
specWarnCatalystBlue:Show()
if self.Options.yellToxicCatalyst then
yellCatalystBlue:Yell()
end
sndWOP:Play("ex_so_lsbz") --藍色爆炸準備
else
sndWOP:Play("ex_so_lsch") --藍色催化
end
elseif args.spellId == 142726 then
timerToxicCatalystCD:Start()
if self.Options.warnToxicCatalyst then
warnToxicCatalystRed:Show()
end
if UnitDebuff("player", GetSpellInfo(142533)) then
specWarnCatalystRed:Show()
if self.Options.yellToxicCatalyst then
yellCatalystRed:Yell()
end
sndWOP:Play("runout") --離開人群
else
sndWOP:Play("ex_so_hsch") --紅色催化
if self.Options.HudMAP then
for i = 1, DBM:GetNumGroupMembers() do
if UnitDebuff("raid"..i, GetSpellInfo(142533)) then
RedMarkers[UnitName("raid"..i)] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("timer", UnitName("raid"..i), 10, 3, 1, 1 ,1 ,0.8):Appear():RegisterForAlerts():Rotate(360, 3.2))
end
end
end
end
elseif args.spellId == 142727 then
timerToxicCatalystCD:Start()
if self.Options.warnToxicCatalyst then
warnToxicCatalystYellow:Show()
end
if UnitDebuff("player", GetSpellInfo(142534)) then
specWarnCatalystYellow:Show()
if self.Options.yellToxicCatalyst then
yellCatalystYellow:Yell()
end
sndWOP:Play("ex_so_hsdq") --黃色毒氣準備
else
sndWOP:Play("ex_so_ysch") --黃色催化
if self.Options.HudMAP then
for i = 1, DBM:GetNumGroupMembers() do
if UnitDebuff("raid"..i, GetSpellInfo(142534)) then
YellowMarkers[UnitName("raid"..i)] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("timer", UnitName("raid"..i), 8, 3, 1, 1 ,0 ,0.8):Appear():RegisterForAlerts():Rotate(360, 3.2))
end
end
end
end
elseif args.spellId == 142728 then
timerToxicCatalystCD:Start()
if self.Options.warnToxicCatalyst then
warnToxicCatalystOrange:Show()
end
if UnitDebuff("player", GetSpellInfo(142533)) or UnitDebuff("player", GetSpellInfo(142534)) then--Red or Yellow
specWarnCatalystOrange:Show()
if self.Options.yellToxicCatalyst then
yellCatalystOrange:Yell()
end
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(142728, 1, 0, 0, 1, 142728, 3)
end
PlaySoundFile("Sound\\Creature\\HoodWolf\\HoodWolfTransformPlayer01.ogg", "Master")
else
if havecolor then
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(_G["NO"], 1, 1, 1, nil, 142728, 2)
end
else
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(GetSpellInfo(142728).."??", 1, 0, 0, 1, 142728, 2)
end
PlaySoundFile("Sound\\Creature\\HoodWolf\\HoodWolfTransformPlayer01.ogg", "Master")
end
end
sndWOP:Play("ex_so_csch") --橙色催化
sndWOP:Schedule(3, "ex_so_bzhh") --爆炸火環準備
sndWOP:Schedule(4, "countthree")
sndWOP:Schedule(5, "counttwo")
sndWOP:Schedule(6, "countone")
elseif args.spellId == 142729 then
timerToxicCatalystCD:Start()
if self.Options.warnToxicCatalyst then
warnToxicCatalystPurple:Show()
end
if UnitDebuff("player", GetSpellInfo(142533)) or UnitDebuff("player", GetSpellInfo(142532)) then--Red or Blue
specWarnCatalystPurple:Show()
if self.Options.yellToxicCatalyst then
yellCatalystPurple:Yell()
end
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(142729, 1, 0, 0, 1, 142729, 3)
end
PlaySoundFile("Sound\\Creature\\HoodWolf\\HoodWolfTransformPlayer01.ogg", "Master")
else
if havecolor then
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(_G["NO"], 1, 1, 1, nil, 142729, 2)
end
else
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(GetSpellInfo(142729).."??", 1, 0, 0, 1, 142729, 2)
end
PlaySoundFile("Sound\\Creature\\HoodWolf\\HoodWolfTransformPlayer01.ogg", "Master")
end
end
sndWOP:Play("ex_so_zsch") --紫色催化
elseif args.spellId == 142730 then
timerToxicCatalystCD:Start()
if self.Options.warnToxicCatalyst then
warnToxicCatalystGreen:Show()
end
if UnitDebuff("player", GetSpellInfo(142534)) or UnitDebuff("player", GetSpellInfo(142532)) then--Yellow or Blue
specWarnCatalystGreen:Show()
if self.Options.yellToxicCatalyst then
yellCatalystGreen:Yell()
end
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(142730, 1, 0, 0, 1, 142730, 3)
end
PlaySoundFile("Sound\\Creature\\HoodWolf\\HoodWolfTransformPlayer01.ogg", "Master")
else
if havecolor then
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(_G["NO"], 1, 1, 1, nil, 142730, 2)
end
else
if self.Options.LTIP then
DBM:ShowLTSpecialWarning(GetSpellInfo(142730).."??", 1, 0, 0, 1, 142730, 3)
end
PlaySoundFile("Sound\\Creature\\HoodWolf\\HoodWolfTransformPlayer01.ogg", "Master")
end
end
sndWOP:Play("ex_so_lvsch") --綠色催化
sndWOP:Schedule(2, "ex_so_xxls") --小心綠水
elseif args.spellId == 143765 then
warnSonicProjection:Show()
elseif args.spellId == 143666 then
warnDiminish:Show()
elseif args.spellId == 142416 then
warnInsaneCalculationFire:Show()
specWarnInsaneCalculationFire:Show()
if caled then
sndWOP:Play("linesoon") --準備連線
caled = false
else
sndWOP:Play("ex_so_yllx") --遠離連線
end
elseif args.spellId == 143709 then
warnFlash:Show()
specWarnFlash:Show()
timerFlashCD:Start()
sndWOP:Play("chargemove") --衝鋒快躲
--[[DELETE if self.Options.RangeFrame then
DBM.RangeCheck:Show(6)--Range assumed, spell tooltips not informative enough
self:Schedule(5, hideRangeFrame)
end]]
if self.Options.LTIP and (not showtank) then
DBM:ShowLTSpecialWarning(143709, 1, 0, 0, 1, 143709, 2)
end
elseif args.spellId == 143280 then
warnBloodletting:Show()
specWarnBloodletting:Show()
timerBloodlettingCD:Start()
sndWOP:Play("ex_so_zbrn")
sndWOP:Schedule(3.5, "ex_so_rnkd")
elseif args.spellId == 143974 then
warnShieldBash:Show()
timerShieldBashCD:Start()
elseif args.spellId == 142315 then
for i = 1, 5 do
local bossUnitID = "boss"..i
if UnitExists(bossUnitID) and UnitGUID(bossUnitID) == args.sourceGUID and UnitDetailedThreatSituation("player", bossUnitID) then--We are highest threat target
warnCausticBlood:Show()
specWarnCausticBlood:Show()--So show tank warning
break
end
end
elseif args.spellId == 143243 then
warnRapidFire:Show()
specWarnRapidFire:Show()
sndWOP:Play("ex_mop_ybzb") --音波準備
if self.Options.LTIP and (not showtank) then
DBM:ShowLTSpecialWarning(143243, 1, 0, 0, 1, 143243, 2)
end
timerRapidFireCD:Start()
elseif args.spellId == 143339 then
for i = 1, 5 do
local bossUnitID = "boss"..i
if UnitExists(bossUnitID) and UnitGUID(bossUnitID) == args.sourceGUID and UnitDetailedThreatSituation("player", bossUnitID) then
specWarnInjection:Show()
break
end
end
injcount = injcount + 1
timerInjectionCD:Start(9.5, injcount + 1)
if self.Options.LTchong then
self:Schedule(1, function()
if injcount == 7 then
DBM:ShowLTSpecialWarning("NEXT:"..(injcount + 1), 1, 0, 0, nil, 144286, nil, 8.5)
else
DBM:ShowLTSpecialWarning("NEXT:"..(injcount + 1), 0, 1, 0, nil, 143339, nil, 8.5)
end
end)
end
elseif args.spellId == 148676 then
warnReave:Show()
specWarnReave:Show()
sndWOP:Play("ex_so_xft") --旋風準備
timerReaveCD:Start()
self:Unschedule(HeroicDFAScan)
self:Schedule(15, HeroicDFAScan)
end
end
function mod:SPELL_CAST_SUCCESS(args)
if args.spellId == 142528 then
warnToxicInjection:Show()
timerToxicCatalystCD:Start(21)--21-23 variance observed on normal and heroic
elseif args.spellId == 142232 then
self:Unschedule(DFAScan)
self:Schedule(17, DFAScan)
elseif args.spellId == 144286 then
if xiezi[args.sourceName] then
xiezi[args.sourceName] = xiezi[args.sourceName] + 1
testinfo()
end
elseif args.spellId == 142416 then
firecount = firecount + 1
if MyJS() then
sndWOP:Play("defensive") --注意減傷
sndWOP:Schedule(0.7, "defensive")
else
DBM:PlayCountSound(firecount)
end
if firecount == 6 then firecount = 0 end
end
end
function mod:SPELL_AURA_APPLIED(args)
if args.spellId == 143339 then
local amount = args.amount or 1
warnInjection:Show(args.destName, amount)
elseif args.spellId == 142532 and args:IsPlayer() then
specWarnToxicBlue:Show()
sndWOP:Play("ex_so_lsds") --藍色毒素
havecolor = true
elseif args.spellId == 142533 and args:IsPlayer() then
specWarnToxicRed:Show()
sndWOP:Play("ex_so_hsds") --紅色毒素
havecolor = true
elseif args.spellId == 142534 and args:IsPlayer() then
specWarnToxicYellow:Show()
sndWOP:Play("ex_so_huds") --黃色毒素
havecolor = true
--[[ elseif args.spellId == 142547 and args:IsPlayer() then
specWarnToxicOrange:Show()
elseif args.spellId == 142548 and args:IsPlayer() then
specWarnToxicPurple:Show()
elseif args.spellId == 142549 and args:IsPlayer() then
specWarnToxicGreen:Show()--]]
elseif args.spellId == 142671 then
warnMesmerize:Show(args.destName)
if args.IsPlayer() then
specWarnMesmerize:Show()
yellMesmerize:Yell()
sndWOP:Play("ex_so_nbcm") --你被催眠
else
specWarnKunchongs:Show()
sndWOP:Play("ex_so_czkd") --蟲子快打
if self.Options.HudMAPMZ then
CMMarkers[args.destName] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("highlight", args.destName, 5, 15, 1, 1 ,0 ,1):Pulse(0.5, 0.5))
end
end
elseif args.spellId == 142564 then
warnEncaseInAmber:Show(args.destName)
specWarnEncaseInAmber:Show(args.destName)
timerEncaseInAmber:Start(args.destName)
sndWOP:Play("ex_so_hupd") --琥珀快打
timerEncaseInAmberCD:Start()
if self:IsMythic() then
-- countdownEncaseInAmber:Start()
end
elseif args.spellId == 143939 then
warnGouge:Show(args.destName)
timerGouge:Start(args.destName)
timerGougeCD:Start()
if args.IsPlayer() then
specWarnGouge:Show()
sndWOP:Play("ex_so_zj") --鑿擊
else
specWarnGougeOther:Show(args.destName)
if mod:IsHealer() then
sndWOP:Play("tankheal") --注意刷坦
end
end
elseif args.spellId == 143974 then
timerShieldBash:Start(args.destName)
if args.IsPlayer() then
specWarnShieldBash:Show()
sndWOP:Play("ex_so_dj") --盾擊
else
specWarnShieldBashOther:Show(args.destName)
if mod:IsHealer() then
sndWOP:Play("tankheal") --注意刷坦
end
end
elseif args.spellId == 143701 then
warnWhirling:CombinedShow(0.5, args.destName)
if args.IsPlayer() then
specWarnWhirling:Show()
yellWhirling:Yell()
timerWhirling:Start()
else
local uId = DBM:GetRaidUnitId(args.destName)
if uId then
local inRange = DBM.RangeCheck:GetDistance("player", uId)
if inRange and inRange < 6 then
specWarnWhirlingNear:Show(args.destName)
sndWOP:Play("runaway") --快躲開
end
end
end
local xftime = GetTime() - mod.combatInfo.pull
xftime = ("%d:%0.2d"):format(xftime/60, math.fmod(xftime, 60))
ResultXFTargets[#ResultXFTargets + 1] = args.destName.."("..xftime..")"
elseif args.spellId == 143759 then
warnHurlAmber:Show()
specWarnHurlAmber:Show()
timerHurlAmberCD:Start()
sndWOP:Play("ex_so_tzhp") --投擲琥珀
if self.Options.LTIP and (not showtank) then
DBM:ShowLTSpecialWarning(143759, 1, 0, 0, 1, 143759, 2)
end
elseif args.spellId == 143337 then
mutateTargets[#mutateTargets + 1] = args.destName
if args.IsPlayer() then
specWarnMutate:Show()
sndWOP:Play("ex_so_bsjx") --變身巨蠍
timerMutate:Start()
end
self:Unschedule(warnMutatedTargets)
self:Schedule(0.5, warnMutatedTargets)
xiezireset = xiezireset + 1
if xiezireset == 4 then
twipe(xiezi)
xiezireset = 1
end
if not xiezi[args.destName] then
xiezi[args.destName] = 0
testinfo()
end
elseif args.spellId == 143358 then
if args.IsPlayer() then
specWarnParasiteFixate:Show()
end
elseif args.spellId == 142948 then
warnAim:Show(args.destName)
timerAim:Start(args.destName)
timerAimCD:Start()
if args.IsPlayer() then
specWarnAim:Show()
sndWOP:Play("ex_so_nbmz") --你被瞄準
yellAim:Yell()
else
specWarnAimOther:Show(args.destName)
sndWOP:Play("ex_so_fdyb") --準備分擔音波
sndWOP:Schedule(1.5, "countfour")
sndWOP:Schedule(2.5, "countthree")
sndWOP:Schedule(3.5, "counttwo")
sndWOP:Schedule(4.5, "countone")
if self.Options.HudMAPMZ then
MZMarkers[args.destName] = register(DBMHudMap:PlaceRangeMarkerOnPartyMember("timer", args.destName, 5, 6, 1, 1 ,1 ,0.8):Appear():RegisterForAlerts():Rotate(360, 5.2))
end
end
if self.Options.RangeFrame then
DBM.RangeCheck:Show(5)
end
if self.Options.SetIconOnAim then
self:SetIcon(args.destName, 1)
end
elseif args.spellId == 142797 and args.IsPlayer() and self:AntiSpam(2, 3) then
specWarnGas:Show()
sndWOP:Play("runaway") --快躲開
end
end
mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED
function mod:SPELL_AURA_REMOVED(args)
if args.spellId == 142564 then
timerEncaseInAmber:Cancel(args.destName)
elseif args.spellId == 143939 then
timerGouge:Cancel(args.destName)
elseif args.spellId == 143974 then
timerShieldBash:Cancel(args.destName)
--[[DELETE elseif args.spellId == 143700 and self.Options.RangeFrame then
DBM.RangeCheck:Hide()]]
elseif args.spellId == 142948 then
--[[DELETE if self.Options.RangeFrame then
DBM.RangeCheck:Hide()
end]]
if self.Options.SetIconOnAim then
self:SetIcon(args.destName, 0)
end
if MZMarkers[args.destName] then
MZMarkers[args.destName] = free(MZMarkers[args.destName])
end
elseif args.spellId == 143339 then
self:Schedule(3, function()
if dissectorlive then
chongnum = chongnum + 8
testinfo()
end
end)
elseif args.spellId == 142671 then
if CMMarkers[args.destName] then
CMMarkers[args.destName] = free(CMMarkers[args.destName])
end
end
end
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 143735 and destGUID == UnitGUID("player") and self:AntiSpam(2, 2) then
specWarnCausticAmber:Show()
sndWOP:Play("runaway") --快躲開
elseif spellId == 142797 and destGUID == UnitGUID("player") and self:AntiSpam(2, 3) then
specWarnGas:Show()
sndWOP:Play("runaway") --快躲開
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
function mod:UNIT_DIED(args)
local cid = self:GetCIDFromGUID(args.destGUID)
if cid == 71161 then--Kil'ruk the Wind-Reaver
if mod:IsDifficulty("heroic10", "heroic25") then
self:Unschedule(HeroicDFAScan)
else
self:Unschedule(DFAScan)
end
timerReaveCD:Cancel()
timerGougeCD:Cancel()
elseif cid == 71157 then--Xaril the Poisoned-Mind
timerToxicCatalystCD:Cancel()
elseif cid == 71156 then--Kaz'tik the Manipulator
elseif cid == 71155 then--Korven the Prime
timerShieldBashCD:Cancel()
timerEncaseInAmberCD:Cancel()
-- countdownEncaseInAmber:Cancel()
elseif cid == 71160 then--Iyyokuk the Lucid
timerInsaneCalculationCD:Cancel()
elseif cid == 71154 then--Ka'roz the Locust
timerFlashCD:Cancel()
timerHurlAmberCD:Cancel()
elseif cid == 71152 then--Skeer the Bloodseeker
timerBloodlettingCD:Cancel()
elseif cid == 71158 then--Rik'kal the Dissector
timerMutateCD:Cancel()
timerInjectionCD:Cancel()
dissectorlive = false
if self.Options.LTchong then
-- DBM:HideLTSpecialWarning()
showtank = false
end
testinfo()
elseif cid == 71153 then--Hisek the Swarmkeeper
timerAimCD:Cancel()
timerRapidFireCD:Cancel()
elseif cid == 71578 then--chong
chongnum = chongnum - 1
testinfo()
end
end
------------------
--Normal Only
--143605 Red Sword
--143606 Purple Sword
--143607 Blue Sword
--143608 Green Sword
--143609 Yellow Sword
--143610 Red Drum
--143611 Purple Drum
--143612 Blue Drum
--143613 Green Drum
--143614 Yellow Drum
--143615 Red Bomb
--143616 Purple Bomb
--143617 Blue Bomb
--143618 Green Bomb
--143619 Yellow Bomb
----------------------
--25man Only
--143620 Red Mantid
--143621 Purple Mantid
--143622 Blue Mantid
--143623 Green Mantid
--143624 Yellow Mantid
--143627 Red Staff
--143628 Purple Staff
--143629 Blue Staff
--143630 Green Staff
--143631 Yellow Staff
local colors = {"Red", "Purple", "Blue", "Green", "Yellow"}
local RedDebuffs = {GetSpellInfo(143605), GetSpellInfo(143610), GetSpellInfo(143615), GetSpellInfo(143620), (GetSpellInfo(143627))}
local PurpleDebuffs = {GetSpellInfo(143606), GetSpellInfo(143611), GetSpellInfo(143616), GetSpellInfo(143621), (GetSpellInfo(143628))}
local BlueDebuffs = {GetSpellInfo(143607), GetSpellInfo(143612), GetSpellInfo(143617), GetSpellInfo(143622), (GetSpellInfo(143629))}
local GreenDebuffs = {GetSpellInfo(143608), GetSpellInfo(143613), GetSpellInfo(143618), GetSpellInfo(143623), (GetSpellInfo(143630))}
local YellowDebuffs = {GetSpellInfo(143610), GetSpellInfo(143614), GetSpellInfo(143619), GetSpellInfo(143624), (GetSpellInfo(143631))}
local SwordDebuffs = {GetSpellInfo(143605), GetSpellInfo(143606), GetSpellInfo(143607), GetSpellInfo(143608), GetSpellInfo(143609)}
local DrumDebuffs = {GetSpellInfo(143610), GetSpellInfo(143611), GetSpellInfo(143612), GetSpellInfo(143613), (GetSpellInfo(143614))}
local BombDebuffs = {GetSpellInfo(143615), GetSpellInfo(143616), GetSpellInfo(143617), GetSpellInfo(143618), (GetSpellInfo(143619))}
local MantidDebuffs = {GetSpellInfo(143620), GetSpellInfo(143621), GetSpellInfo(143622), GetSpellInfo(143623), (GetSpellInfo(143624))}
local StaffDebuffs = {GetSpellInfo(143627), GetSpellInfo(143628), GetSpellInfo(143629), GetSpellInfo(143630), (GetSpellInfo(143631))}
local AllDebuffs = {
GetSpellInfo(143605), GetSpellInfo(143606), GetSpellInfo(143607), GetSpellInfo(143608), GetSpellInfo(143609),
GetSpellInfo(143610), GetSpellInfo(143611), GetSpellInfo(143612), GetSpellInfo(143613), GetSpellInfo(143614),
GetSpellInfo(143615), GetSpellInfo(143616), GetSpellInfo(143617), GetSpellInfo(143618), GetSpellInfo(143619),
GetSpellInfo(143620), GetSpellInfo(143621), GetSpellInfo(143622), GetSpellInfo(143623), GetSpellInfo(143624),
GetSpellInfo(143627), GetSpellInfo(143628), GetSpellInfo(143629), GetSpellInfo(143630), (GetSpellInfo(143631))
}
local function parseDebuff(player)
local count
for i= 1, 5 do
count = select(4, UnitDebuff(player, SwordDebuffs[i]))
if count then
return "Sword", colors[i], (count == 0) and 1 or count
end
count = select(4,UnitDebuff(player, DrumDebuffs[i]))
if count then
return "Drum", colors[i], (count == 0) and 1 or count
end
count = select(4,UnitDebuff(player, BombDebuffs[i]))
if count then
return "Bomb", colors[i], (count == 0) and 1 or count
end
count = select(4,UnitDebuff(player, MantidDebuffs[i]))
if count then
return "Mantid", colors[i], (count == 0) and 1 or count
end
count = select(4,UnitDebuff(player, StaffDebuffs[i]))
if count then
return "Staff", colors[i], (count == 0) and 1 or count
end
end
return false
end
function mod:CHAT_MSG_MONSTER_EMOTE(msg, npc, _, _, target)
local targetname = DBM:GetUnitFullName(target)
if npc == calculatingDude then
-- warnCalculated:Show(targetname)
timerCalculated:Start()
timerInsaneCalculationCD:Start()
if target == UnitName("player") then
specWarnCalculated:Show()
sndWOP:Play("ex_so_lxdn") --連線點你
yellCalculated:Yell()
caled = true
end
if self:IsMythic() then
local resultshape, resultcolor, resultnumber = parseDebuff(target)
local shape, color, number = parseDebuff("player")
if shape then
if shape == resultshape or color == resultcolor or number == resultnumber then
if target ~= UnitName("player") then
specWarnCalculated:Show()
sndWOP:Play("ex_so_lxdn")
yellCalculated:Yell()
caled = true
end
else
if target ~= UnitName("player") then
caled = false
end
end
end
twipe(ResultTargets)
twipe(ResultGroupTargets)
twipe(ResultMeleeTargets)
twipe(ResultRangedTargets)
twipe(ResultRangedDPSTargets)
local _, _, mysubgroup = GetRaidRosterInfo(UnitInRaid("player"))
myGroup = mysubgroup
for i = 1, DBM:GetNumGroupMembers() do
local shapecheck, colorcheck, numbercheck = parseDebuff(UnitName("raid"..i))
if shapecheck then
if shapecheck == resultshape or colorcheck == resultcolor or numbercheck == resultnumber then
if mod.Options.ShowGrouptarget then
local _, _, subgroup = GetRaidRosterInfo(i)
if subgroup == myGroup then
ResultGroupTargets[#ResultGroupTargets + 1] = UnitName("raid"..i)
end
else
ResultTargets[#ResultTargets + 1] = UnitName("raid"..i)
local _, class = UnitClass("raid"..i)
if (class == "DRUID" and UnitPowerMax("raid"..i) > 200000) or class == "HUNTER" or class == "PRIEST" or class == "MAGE" or class == "WARLOCK" or (class == "SHAMAN" and UnitPowerMax("raid"..i) > 200000) or (class == "PALADIN" and UnitPowerMax("raid"..i) > 200000) then
ResultRangedTargets[#ResultRangedTargets + 1] = UnitName("raid"..i)
if self:UnitIsDps("raid"..i) then
ResultRangedDPSTargets[#ResultRangedDPSTargets + 1] = UnitName("raid"..i)
end
else
ResultMeleeTargets[#ResultMeleeTargets + 1] = UnitName("raid"..i)
end
end
end
end
end
if mod.Options.ShowGrouptarget and self:IsMythic() then
DBM.InfoFrame:SetHeader(GetSpellInfo(144095).."("..(firecount+1)..")")
if #ResultGroupTargets == 1 then
DBM.InfoFrame:Show(1, "other", ResultGroupTargets[1], "1")
elseif #ResultGroupTargets == 2 then
DBM.InfoFrame:Show(2, "other", ResultGroupTargets[1], "1", ResultGroupTargets[2], "2")
elseif #ResultGroupTargets == 3 then
DBM.InfoFrame:Show(3, "other", ResultGroupTargets[1], "1", ResultGroupTargets[2], "2", ResultGroupTargets[3], "3")
elseif #ResultGroupTargets == 4 then
DBM.InfoFrame:Show(4, "other", ResultGroupTargets[1], "1", ResultGroupTargets[2], "2", ResultGroupTargets[3], "3", ResultGroupTargets[4], "4")
elseif #ResultGroupTargets == 5 then
DBM.InfoFrame:Show(5, "other", ResultGroupTargets[1], "1", ResultGroupTargets[2], "2", ResultGroupTargets[3], "3", ResultGroupTargets[4], "4", ResultGroupTargets[5], "5")
else
DBM.InfoFrame:Show(1, "other", "No one", "0")
end
twipe(ResultGroupTargets)
end
warnResult:Show(table.concat(ResultMeleeTargets, "<, >"))
warnResult:Show(table.concat(ResultRangedTargets, "<, >"))
--[[if #ResultMeleeTargets < 7 then
local meleenum = #ResultMeleeTargets
local needranged = 7 - meleenum
for i = 1, needranged do
if ResultRangedDPSTargets[i] == UnitName("player") then
sndWOP:Play("gather")
end
end
end]]
end
end
end
function mod:SPELL_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 142809 and destGUID == UnitGUID("player") and self:AntiSpam(2, 3) then
if UnitDebuff("player", GetSpellInfo(142808)) then
havedebuff = true
self:Schedule(10, function() havedebuff = false end)
end
if (not havedebuff) then
specWarnFireline:Show()
sndWOP:Play("runaway") --快躲開
end
end
end
mod.SPELL_MISSED = mod.SPELL_DAMAGE
|
return {
print = macos.print
}
|
registerMonsterType = {}
setmetatable(registerMonsterType,
{
__call =
function(self, mtype, mask)
for _,parse in pairs(self) do
parse(mtype, mask)
end
end
})
MonsterType.register = function(self, mask)
return registerMonsterType(self, mask)
end
registerMonsterType.name = function(mtype, mask)
if mask.name then
mtype:name(mask.name)
end
end
registerMonsterType.description = function(mtype, mask)
if mask.description then
mtype:nameDescription(mask.description)
end
end
registerMonsterType.experience = function(mtype, mask)
if mask.experience then
mtype:experience(mask.experience)
end
end
registerMonsterType.raceId = function(mtype, mask)
if mask.raceId then
mtype:raceId(mask.raceId)
end
end
registerMonsterType.Bestiary = function(mtype, mask)
if mask.Bestiary then
if mask.Bestiary.race then
mtype:Bestiaryrace(mask.Bestiary.race)
end
if mask.Bestiary.class then
mtype:Bestiaryclass(mask.Bestiary.class)
end
if mask.Bestiary.toKill then
mtype:BestiarytoKill(mask.Bestiary.toKill)
end
if mask.Bestiary.FirstUnlock then
mtype:BestiaryFirstUnlock(mask.Bestiary.FirstUnlock)
end
if mask.Bestiary.SecondUnlock then
mtype:BestiarySecondUnlock(mask.Bestiary.SecondUnlock)
end
if mask.Bestiary.CharmsPoints then
mtype:BestiaryCharmsPoints(mask.Bestiary.CharmsPoints)
end
if mask.Bestiary.Stars then
mtype:BestiaryStars(mask.Bestiary.Stars)
end
if mask.Bestiary.Occurrence then
mtype:BestiaryOccurrence(mask.Bestiary.Occurrence)
end
if mask.Bestiary.Locations then
mtype:BestiaryLocations(mask.Bestiary.Locations)
end
end
end
registerMonsterType.skull = function(mtype, mask)
if mask.skull then
mtype:skull(mask.skull)
end
end
registerMonsterType.outfit = function(mtype, mask)
if mask.outfit then
mtype:outfit(mask.outfit)
end
end
registerMonsterType.maxHealth = function(mtype, mask)
if mask.maxHealth then
mtype:maxHealth(mask.maxHealth)
end
end
registerMonsterType.health = function(mtype, mask)
if mask.health then
mtype:health(mask.health)
end
end
registerMonsterType.maxSummons = function(mtype, mask)
if mask.maxSummons then
mtype:maxSummons(mask.maxSummons)
end
end
registerMonsterType.race = function(mtype, mask)
if mask.race then
mtype:race(mask.race)
end
end
registerMonsterType.manaCost = function(mtype, mask)
if mask.manaCost then
mtype:manaCost(mask.manaCost)
end
end
registerMonsterType.speed = function(mtype, mask)
if mask.speed then
mtype:baseSpeed(mask.speed)
end
end
registerMonsterType.corpse = function(mtype, mask)
if mask.corpse then
mtype:corpseId(mask.corpse)
end
end
registerMonsterType.faction = function(mtype, mask)
if mask.faction then
mtype:faction(mask.faction)
end
end
registerMonsterType.targetPreferPlayer = function(mtype, mask)
if mask.targetPreferPlayer then
mtype:targetPreferPlayer(mask.targetPreferPlayer)
end
end
registerMonsterType.targetPreferMaster = function(mtype, mask)
if mask.targetPreferMaster then
mtype:targetPreferMaster(mask.targetPreferMaster)
end
end
registerMonsterType.enemyFactions = function(mtype, mask)
if mask.enemyFactions then
for _, enemyFaction in pairs(mask.enemyFactions) do
if not enemyFaction then
print("[Error - Loading monsters] Monster: \"" .. mtype:name() .. "\". Unknown enemy faction.")
else
mtype:enemyFactions(enemyFaction)
end
end
end
end
registerMonsterType.flags = function(mtype, mask)
if mask.flags then
if mask.flags.attackable ~= nil then
mtype:isAttackable(mask.flags.attackable)
end
if mask.flags.convinceable ~= nil then
mtype:isConvinceable(mask.flags.convinceable)
end
if mask.flags.summonable ~= nil then
mtype:isSummonable(mask.flags.summonable)
end
if mask.flags.illusionable ~= nil then
mtype:isIllusionable(mask.flags.illusionable)
end
if mask.flags.hostile ~= nil then
mtype:isHostile(mask.flags.hostile)
end
if mask.flags.healthHidden ~= nil then
mtype:isHealthHidden(mask.flags.healthHidden)
end
if mask.flags.pushable ~= nil then
mtype:isPushable(mask.flags.pushable)
end
if mask.flags.canPushItems ~= nil then
mtype:canPushItems(mask.flags.canPushItems)
end
if mask.flags.rewardBoss then
mtype:isRewardBoss(mask.flags.rewardBoss)
end
if mask.flags.familiar then
mtype:familiar(mask.flags.familiar)
end
if mask.flags.respawntype or mask.flags.respawnType then
Spdlog.warn(string.format("[registerMonsterType.flags] - Monster: %s. Deprecated flag 'respawnType', use instead table 'respawnType = { period = RespawnPeriod_t, underground = boolean}'",
mtype:name()))
end
if mask.flags.canPushCreatures ~= nil then
mtype:canPushCreatures(mask.flags.canPushCreatures)
end
if mask.flags.targetDistance then
mtype:targetDistance(math.max(1, mask.flags.targetDistance))
end
if mask.flags.runHealth then
mtype:runHealth(mask.flags.runHealth)
end
if mask.flags.staticAttackChance then
mtype:staticAttackChance(mask.flags.staticAttackChance)
end
if mask.flags.canWalkOnEnergy ~= nil then
mtype:canWalkOnEnergy(mask.flags.canWalkOnEnergy)
end
if mask.flags.canWalkOnFire ~= nil then
mtype:canWalkOnFire(mask.flags.canWalkOnFire)
end
if mask.flags.canWalkOnPoison ~= nil then
mtype:canWalkOnPoison(mask.flags.canWalkOnPoison)
end
if mask.flags.isBlockable ~= nil then
mtype:isBlockable(mask.flags.isBlockable)
end
end
end
registerMonsterType.light = function(mtype, mask)
if mask.light then
if mask.light.color then
local color = mask.light.color
end
if mask.light.level then
mtype:light(color, mask.light.level)
end
end
end
registerMonsterType.changeTarget = function(mtype, mask)
if mask.changeTarget then
if mask.changeTarget.chance then
mtype:changeTargetChance(mask.changeTarget.chance)
end
if mask.changeTarget.interval then
mtype:changeTargetSpeed(mask.changeTarget.interval)
end
end
end
registerMonsterType.strategiesTarget = function(mtype, mask)
if mask.strategiesTarget then
if mask.strategiesTarget.nearest then
mtype:strategiesTargetNearest(mask.strategiesTarget.nearest)
end
if mask.strategiesTarget.health then
mtype:strategiesTargetHealth(mask.strategiesTarget.health)
end
if mask.strategiesTarget.damage then
mtype:strategiesTargetDamage(mask.strategiesTarget.damage)
end
if mask.strategiesTarget.random then
mtype:strategiesTargetRandom(mask.strategiesTarget.random)
end
end
end
registerMonsterType.respawnType = function(mtype, mask)
if mask.respawnType then
if mask.respawnType.period then
mtype:respawnTypePeriod(mask.respawnType.period)
end
if mask.respawnType.underground then
mtype:respawnTypeIsUnderground(mask.respawnType.underground)
end
end
end
registerMonsterType.voices = function(mtype, mask)
if type(mask.voices) == "table" then
local interval, chance
if mask.voices.interval then
interval = mask.voices.interval
end
if mask.voices.chance then
chance = mask.voices.chance
end
for k, v in pairs(mask.voices) do
if type(v) == "table" then
mtype:addVoice(v.text, interval, chance, v.yell)
end
end
end
end
registerMonsterType.summons = function(mtype, mask)
if type(mask.summons) == "table" then
for k, v in pairs(mask.summons) do
mtype:addSummon(v.name, v.interval, v.chance)
end
end
end
registerMonsterType.events = function(mtype, mask)
if type(mask.events) == "table" then
for k, v in pairs(mask.events) do
mtype:registerEvent(v)
end
end
end
function sortLootByChance(loot)
if not configManager.getBoolean(configKeys.SORT_LOOT_BY_CHANCE) then
return
end
table.sort(loot, function(loot1, loot2)
if not loot1.chance or not loot2.chance then
return 0
end
return loot1.chance < loot2.chance
end)
end
registerMonsterType.loot = function(mtype, mask)
if type(mask.loot) == "table" then
sortLootByChance(mask.loot)
local lootError = false
for _, loot in pairs(mask.loot) do
local parent = Loot()
if loot.name then
if not parent:setIdFromName(loot.name) then
lootError = true
end
else
if not isInteger(loot.id) or loot.id < 1 then
lootError = true
end
parent:setId(loot.id)
end
if loot.subType or loot.charges then
parent:setSubType(loot.subType or loot.charges)
else
local lType = ItemType(loot.name and loot.name or loot.id)
if lType and lType:getCharges() > 1 then
parent:setSubType(lType:getCharges())
end
end
if loot.chance then
parent:setChance(loot.chance)
end
if loot.minCount then
parent:setMinCount(loot.minCount)
end
if loot.maxCount then
parent:setMaxCount(loot.maxCount)
end
if loot.aid or loot.actionId then
parent:setActionId(loot.aid or loot.actionId)
end
if loot.text or loot.description then
parent:setText(loot.text or loot.description)
end
if loot.name then
parent:setNameItem(loot.name)
end
if loot.article then
parent:setArticle(loot.article)
end
if loot.attack then
parent:setAttack(loot.attack)
end
if loot.defense then
parent:setDefense(loot.defense)
end
if loot.extraDefense or loot.extraDef then
parent:setExtraDefense(loot.extraDefense or loot.extraDef)
end
if loot.armor then
parent:setArmor(loot.armor)
end
if loot.shootRange or loot.range then
parent:setShootRange(loot.shootRange or loot.range)
end
if loot.unique then
parent:setUnique(loot.unique)
end
if loot.child then
sortLootByChance(loot.child)
for _, children in pairs(loot.child) do
local child = Loot()
if children.name then
if not child:setIdFromName(children.name) then
lootError = true
end
else
if not isInteger(children.id) or children.id < 1 then
lootError = true
end
child:setId(children.id)
end
if children.subType or children.charges then
child:setSubType(children.subType or children.charges)
else
local cType = ItemType(children.name and children.name or children.id)
if cType and cType:getCharges() > 1 then
child:setSubType(cType:getCharges())
end
end
if children.chance then
child:setChance(children.chance)
end
if children.minCount then
child:setMinCount(children.minCount)
end
if children.maxCount then
child:setMaxCount(children.maxCount)
end
if children.aid or children.actionId then
child:setActionId(children.aid or children.actionId)
end
if children.text or children.description then
child:setText(children.text or children.description)
end
if loot.name then
child:setNameItem(loot.name)
end
if children.article then
child:setArticle(children.article)
end
if children.attack then
child:setAttack(children.attack)
end
if children.defense then
child:setDefense(children.defense)
end
if children.extraDefense or children.extraDef then
child:setExtraDefense(children.extraDefense or children.extraDef)
end
if children.armor then
child:setArmor(children.armor)
end
if children.shootRange or children.range then
child:setShootRange(children.shootRange or children.range)
end
if children.unique then
child:setUnique(children.unique)
end
parent:addChildLoot(child)
end
end
mtype:addLoot(parent)
end
if lootError then
Spdlog.warn("[registerMonsterType.loot] - Monster: ".. mtype:name() .. " loot could not correctly be load")
end
end
end
registerMonsterType.elements = function(mtype, mask)
if type(mask.elements) == "table" then
for _, element in pairs(mask.elements) do
if element.type and element.percent then
mtype:addElement(element.type, element.percent)
end
end
end
end
registerMonsterType.reflects = function(mtype, mask)
if type(mask.reflects) == "table" then
for _, reflect in pairs(mask.reflects) do
if reflect.type and reflect.percent then
mtype:addReflect(reflect.type, reflect.percent)
end
end
end
end
registerMonsterType.heals = function(mtype, mask)
if type(mask.heals) == "table" then
for _, heal in pairs(mask.heals) do
if heal.type and heal.percent then
mtype:addHealing(heal.type, heal.percent)
end
end
end
end
registerMonsterType.immunities = function(mtype, mask)
if type(mask.immunities) == "table" then
for _, immunity in pairs(mask.immunities) do
if immunity.type and immunity.combat then
mtype:combatImmunities(immunity.type)
end
if immunity.type and immunity.condition then
mtype:conditionImmunities(immunity.type)
end
end
end
end
registerMonsterType.attacks = function(mtype, mask)
if type(mask.attacks) == "table" then
for _, attack in pairs(mask.attacks) do
mtype:addAttack(readSpell(attack))
end
end
end
registerMonsterType.defenses = function(mtype, mask)
if type(mask.defenses) == "table" then
if mask.defenses.defense then
mtype:defense(mask.defenses.defense)
end
if mask.defenses.armor then
mtype:armor(mask.defenses.armor)
end
for _, defense in pairs(mask.defenses) do
if type(defense) == "table" then
mtype:addDefense(readSpell(defense))
end
end
end
end
function readSpell(incomingLua)
local spell = MonsterSpell()
if incomingLua.name then
if incomingLua.name == "melee" then
spell:setType("melee")
if incomingLua.attack and incomingLua.skill then
spell:setAttackValue(incomingLua.attack, incomingLua.skill)
end
if incomingLua.minDamage and incomingLua.maxDamage then
spell:setCombatValue(incomingLua.minDamage, incomingLua.maxDamage)
end
if incomingLua.interval then
spell:setInterval(incomingLua.interval)
end
if incomingLua.effect then
spell:setCombatEffect(incomingLua.effect)
end
else
spell:setType(incomingLua.name)
if incomingLua.type then
if incomingLua.name == "combat" then
spell:setCombatType(incomingLua.type)
elseif incomingLua.name == "condition" then
spell:setConditionType(incomingLua.type)
else
Spdlog.warn("[readSpell] - Monster ".. mtype:name() .. ": Loading spell ".. incomingLua.name .. ". Parameter type applies only for condition and combat.")
end
end
if incomingLua.interval then
spell:setInterval(incomingLua.interval)
end
if incomingLua.chance then
spell:setChance(incomingLua.chance)
end
if incomingLua.range then
spell:setRange(incomingLua.range)
end
if incomingLua.duration then
spell:setConditionDuration(incomingLua.duration)
end
if incomingLua.speedChange then
spell:setConditionSpeedChange(incomingLua.speedChange)
end
if incomingLua.target then
spell:setNeedTarget(incomingLua.target)
end
if incomingLua.length then
spell:setCombatLength(incomingLua.length)
end
if incomingLua.spread then
spell:setCombatSpread(incomingLua.spread)
end
if incomingLua.radius then
spell:setCombatRadius(incomingLua.radius)
end
if incomingLua.outfitMonster then
spell:setOutfitMonster(incomingLua.outfitMonster)
end
if incomingLua.outfitItem then
spell:setOutfitItem(incomingLua.outfitItem)
end
if incomingLua.minDamage and incomingLua.maxDamage then
if incomingLua.name == "combat" or Spell(incomingLua.name) then
spell:setCombatValue(incomingLua.minDamage, incomingLua.maxDamage)
else
local startDamage = 0
if incomingLua.startDamage then
startDamage = incomingLua.startDamage
end
spell:setConditionDamage(incomingLua.minDamage, incomingLua.maxDamage, startDamage)
end
end
if incomingLua.effect then
spell:setCombatEffect(incomingLua.effect)
end
if incomingLua.shootEffect then
spell:setCombatShootEffect(incomingLua.shootEffect)
end
end
-- This is for a complex spell, that has combat damage AND some condition
-- For example scorpions, which attack and cause poison on attack
if incomingLua.condition then
if incomingLua.condition.type then
spell:setConditionType(incomingLua.condition.type)
end
if incomingLua.condition.duration then
spell:setConditionDuration(incomingLua.condition.duration)
end
if incomingLua.condition.interval then
spell:setConditionTickInterval(incomingLua.condition.interval)
end
spell:setConditionDamage(incomingLua.condition.totalDamage, incomingLua.condition.totalDamage, 0)
end
elseif incomingLua.script then
spell:setScriptName("monster/" .. incomingLua.script .. ".lua")
if incomingLua.interval then
spell:setInterval(incomingLua.interval)
end
if incomingLua.chance then
spell:setChance(incomingLua.chance)
end
if incomingLua.minDamage and incomingLua.maxDamage then
spell:setCombatValue(incomingLua.minDamage, incomingLua.maxDamage)
end
if incomingLua.target then
spell:setNeedTarget(incomingLua.target)
end
end
return spell
end
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by llll.
--- DateTime: 2019/8/28 23:28
---
local fmt = require("fmt.fmt")
local View = {}
print("start scripts")
function View:Start()
print("start scripts")
print(self)
end
return View
|
class_C("EffectMoney", ClassLoader:aquireClass("Effect")).execute = function (slot0)
return 0
end
return class_C("EffectMoney", ClassLoader.aquireClass("Effect"))
|
local ls = require("luasnip")
local s = ls.s
local t = ls.t
local i = ls.i
local c = ls.c
local sn = ls.sn
local parse = require("plugins.luasnip.util").parse
ls.snippets.markdown = {
parse({ trig = "oritatami" }, {
"<details><summary>${1}</summary><div>",
"",
"${0}",
"",
"</div></details>",
}),
}
|
function main(splash)
local snapshots = {}
local timer = splash:call_later(function()
snapshots["a"] = splash:html()
splash:wait(1.0)
snapshots["b"] = splash:html()
end, 1.5)
assert(splash:go(splash.args.url))
splash:wait(3.0)
timer:reraise()
return snapshots
end
|
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
--
-- em_mapIconBase
--
--
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
print("Loading ERIS_MINIMAP_MAPICONS");
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
em_mapIconBase = {};
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:getAlpha()
return self.a;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:getColor()
return self.r, self.g, self.b, self.a;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:getClass()
return self.class;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:getLocation()
return self.x, self.y;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:getObj()
return self.obj;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:getX()
return self.x;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:getY()
return self.y;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:setAlpha(_a)
self.a = _a or self.a;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:setColor(_r, _g, _b, _a)
self.r = _r or self.r;
self.g = _g or self.g;
self.b = _b or self.b;
self.a = _a or self.a;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:setClass(_class)
self.class = _class;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:setLocation(_x, _y)
self.x, self.y = _x, _y;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:setObj(_obj)
self.obj = _obj;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:setX(_x)
self.x = _x;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:setY(_y)
self.y = _y;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:updateTimeStamp(_updateTime)
self.lastupdateTime = self.updateTime;
self.updateTime = _updateTime;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:updateLocation(_x, _y)
if self.obj or _x and _y then
self.lastX, self.lastY = self.x, self.y;
self.x, self.y = _x or self.obj:getX(), _y or self.obj:getY();
else
self.lastX, self.lastY = 0, 0;
self.x, self.y = 0, 0;
end;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:update(_updateTime)
self:updateTimeStamp(_updateTime);
self:updateLocation();
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:initID()
self.ID = self.obj:getID();
self.iconID = self.class .. self.ID;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
function em_mapIconBase:new()
local o = {};
setmetatable(o, self)
o.__index = self;
o.obj = nil;
o.class = "base";
o.iconID = "0";
o.x = 0;
o.y = 0;
o.lastX = 0;
o.lastY = 0;
o.minViewDist = 5;
o.maxViewDist = 30;
o.maxViewAngle = 70;
o.delta = 0;
o.rect = {x1=0, x2=0, x3=0, x4=0, y1=0, y2=0, y3=0, y4=0};
o.iconData = "";
o.iconDataExt = "";
o.iconTexture = nil;
o.iconTextureExt = nil;
o.r = 1;
o.g = 1;
o.b = 1;
o.a = 1;
o.fadeStep = 0.1;
o.mapScale = false;
o.updateTime = 0;
o.lastupdateTime = 0;
return o;
end
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
|
local volume = {}
local audio = hs.audiodevice
function volume.mute()
local dev = audio.defaultOutputDevice()
return dev and dev:setMuted(true)
end
function volume.unmute()
local dev = audio.defaultOutputDevice()
return dev and dev:setMuted(false)
end
function volume.muted()
local dev = audio.defaultOutputDevice()
return dev and dev:muted()
end
function volume.increment()
local dev = audio.defaultOutputDevice()
if dev == nil then
return nil
end
local volume = dev:volume()
volume = math.min(volume + 6.25, 100)
if dev:setVolume(volume) then
return volume
end
return false
end
function volume.decrement()
local dev = audio.defaultOutputDevice()
if dev == nil then
return nil
end
local volume = dev:volume()
volume = math.max(volume - 6.25, 0)
if dev:setVolume(volume) then
return volume
end
return false
end
function volume.set(volume)
local dev = audio.defaultOutputDevice()
if dev == nil then
return nil
end
return dev:setVolume(volume)
end
return volume
|
object_mobile_nova_orion_employee_08 = object_mobile_shared_nova_orion_employee_08:new {
}
ObjectTemplates:addTemplate(object_mobile_nova_orion_employee_08, "object/mobile/nova_orion_employee_08.iff")
|
require "luarocks.loader"
local Sh = require('minilib.shell')
local Pr = require('minilib.process')
local Util = require('minilib.util')
local Cfg = require('mxctl.config')
local Cmds = require('mxctl.control_cmds')
local pop_term = string.format("%s %s", Cfg.pop_term, Cfg.pop_termopts[Cfg.pop_term])
function pa_sinks()
local iv = Pr.pipe()
.add(Sh.exec('pacmd list-sinks'))
.add(Sh.grep('name: <(.+)>'))
.run()
return iv
end
local Funs = {}
function Funs:tmenu_select_pa_sinks()
local opts = ""
for i, v in ipairs(pa_sinks()) do
opts = opts .. v .. "\n"
end
Pr.pipe()
.add(Sh.exec(string.format('echo "%s" | %s', opts, Cfg.menu_sel)))
.add(function(id)
Util:exec('pacmd set-default-sink '..id)
end)
.run()
end
function Funs:dmenu_select_pa_sinks()
Util:exec(pop_term .. " fun tmenu_select_pa_sinks")
end
return Funs
|
slot0 = class_C("TransformSwing", ClassLoader:aquireClass("TransformAction"))
slot0.onCreate = function (slot0)
slot0.super.onCreate(slot0)
slot0:addProperty("targetAction")
slot0:addProperty("count")
end
slot0.onCreateFinish = function (slot0)
slot0.super.onCreateFinish(slot0)
slot0:setValue("count", 1)
end
slot0.update = function (slot0, slot1)
slot5 = slot0:getValue("targetAction").getValue(slot2, "duration") * 2
if slot4 > (slot3 or slot1) - slot5 * math.floor((slot3 or slot1) / slot5) then
slot2:update(slot1)
else
slot2:update(slot5 - slot1)
end
end
slot0.on_targetAction_changed = function (slot0)
slot1 = slot0:getValue("targetAction")
slot0:setValue("duration", slot1:getValue("duration") * 2 * slot0:getValue("count"))
slot1:bindSameName("actionTarget", slot0)
slot1:setValue("actionTarget", slot0:getValue("actionTarget"))
end
return slot0
|
#include "scripts/utils.lua"
#include "scripts/savedata.lua"
#include "scripts/menu.lua"
#include "scripts/varhandlers.lua"
#include "datascripts/keybinds.lua"
#include "datascripts/inputList.lua"
#include "datascripts/color4.lua"
toolName = "drivableplane"
toolReadableName = "Drivable Plane"
--TODO: Fix offset weirdness.
local menu_disabled = false
savedVars = {
Speed = { name = "Speed",
boxDescription = "Plane speed.",
default = 30,
current = nil,
valueType = "float",
configurable = true,
minVal = 0.1,
maxVal = 50,
},
TurnSpeed = { name = "Turn Speed",
boxDescription = "Plane turn speed.",
default = 5,
current = nil,
valueType = "float",
configurable = true,
minVal = 0.1,
maxVal = 50
},
CameraLerpSpeed = { name = "Camera Lerp Speed",
boxDescription = "Camera move speed.",
default = 50,
current = nil,
valueType = "float",
configurable = false,
minVal = 0.1,
maxVal = 100,
},
ExplodeOnImpact = { name = "Explode On Impact",
boxDescription = "Explosions on hit.",
default = false,
current = nil,
valueType = "bool",
configurable = true,
},
DieOnImpact = { name = "Die On Impact",
boxDescription = "Stop flight on hit.",
default = false,
current = nil,
valueType = "bool",
configurable = true,
},
}
menuVarOrder = { "Speed", "TurnSpeed", "ExplodeOnImpact", "DieOnImpact", }
local inFlightCamera = false
local firstCameraTick = false
local planeActive = false
local planeTransform = Transform(planePosition, planeRotation)
local planeDirection = Vec(0, 0, -1) -- local space
--local planeTilt = 0
local cameraTransform = Transform()
local cameraLocalPos = Vec(0, 0.5, 10)
local cameraLocalLookPos = Vec(0, 0.25, 0)
local cameraLocalRot = QuatLookAt(cameraLocalPos, cameraLocalLookPos)
local planeTest = LoadSprite("MOD/sprites/square.png")
local localPlaneTransforms = {
Transform(Vec(-0.9, -0.4, -1.5), Quat()),
Transform(Vec(-0.45 * 2, 0, 0), Quat()),
Transform(Vec(-0.45, 0, 0), Quat())
}
local selectedPlane = 1
local planeCount = #localPlaneTransforms
local targetSprite = LoadSprite("MOD/sprites/target.png")
local damageTick = 0
local maxDamageTick = 0.1
local forceWaveRange = 2 * 2
local collisionForce = 20
local collisionRayLength = 0.1 * 10
local collisionRayWidth = 0.25 * 2
local maxPlayerFromCameraDist = 20
local setGoalPos = Vec()
local setGoalPosActive = false
function init()
saveFileInit(savedVars)
menu_init()
RegisterTool(toolName, toolReadableName, "MOD/vox/plane.vox")
SetBool("game.tool." .. toolName .. ".enabled", true)
end
function allStatic()
QueryRequire("dynamic")
local bodies = QueryAabbBodies
local playerPos = GetPlayerTransform().pos
local range = 200
local minPos = VecAdd(playerPos, Vec(-range, -range, -range))
local maxPos = VecAdd(playerPos, Vec(range, range, range))
local bodies = QueryAabbBodies(minPos, maxPos)
for i = 1, #bodies do
local hitBody = bodies[i]
SetBodyDynamic(hitBody, false)
SetBodyVelocity(hitBody, Vec())
end
SetString("hud.notification", #bodies .. " set to static.")
end
function tick(dt)
if not menu_disabled then
menu_tick(dt)
end
local isMenuOpenRightNow = isMenuOpen()
if isMenuOpenRightNow then
SetTimeScale(0.1)
end
if not canUseTool() and not planeActive then
return
end
planeBodiesLogic(dt)
if planeActive then
handleKeyInputs()
SetString("game.player.tool", toolName)
--[[function rotateTest()
local newRot = QuatAxisAngle(Vec(0, 0, 1), dt * 100)
localPlaneTransforms[selectedPlane].rot = QuatRotateQuat(localPlaneTransforms[selectedPlane].rot, newRot)
end
renderPlaneSprite()
rotateTest()]]--
if inFlightCamera then
--DebugWatch("dist", VecDist(GetPlayerCameraTransform().pos, planeTransform.pos))
if VecDist(GetPlayerCameraTransform().pos, planeTransform.pos) > maxPlayerFromCameraDist and firstCameraTicks <= 0 then
inFlightCamera = false
end
if firstCameraTicks then
firstCameraTicks = firstCameraTicks - 1
end
cameraLogic(dt)
--renderPlaneSprite()
end
if setGoalPosActive then
renderBillboardSprite(targetSprite, setGoalPos, GetCameraTransform().pos, 0.5, Color4.Red)
--renderSetGoalSprite()
end
handleFlight(dt)
if damageTick <= 0 then
handlePlaneCollisions(planeTransform.pos)
else
damageTick = damageTick - dt
end
end
if isMenuOpenRightNow then
return
end
if InputPressed(binds["Shoot"]) and not planeActive then
startFlight()
end
end
function draw(dt)
menu_draw(dt)
end
function handleKeyInputs()
if InputPressed(binds["Fly_To_Target"]) and not inFlightCamera and not isMenuOpen() then
setSetGoalPos()
end
if InputPressed(binds["Release_Target"]) and not isMenuOpen() then
setGoalPosActive = false
end
if InputPressed(binds["Toggle_Camera"]) then
inFlightCamera = not inFlightCamera
if inFlightCamera then
firstCameraTicks = 2
end
end
if InputPressed(binds["Disengage"]) then
planeActive = false
setGoalPosActive = false
end
end
function planeBodiesLogic(dt)
SetToolTransform(Transform(), 0)
local toolBody = GetToolBody()
local toolTransform = GetBodyTransform(toolBodyx)
local toolShapes = GetBodyShapes(toolBody)
local planeShape = toolShapes[selectedPlane]
if planeActive then
local scroll = InputValue(binds["Plane_Select_Move"])
if scroll > 0 then
selectedPlane = selectedPlane - 1
if selectedPlane < 1 then
selectedPlane = planeCount
end
elseif scroll < 0 then
selectedPlane = selectedPlane + 1
if selectedPlane > planeCount then
selectedPlane = 1
end
end
placeLocalBodyAtPos(toolBody, planeShape, planeTransform, localPlaneTransforms[selectedPlane])
end
for i = 1, planeCount do
if i ~= selectedPlane or (i == selectedPlane and not planeActive) then
placeLocalBodyAtPos(toolBody, toolShapes[i], Transform(Vec(0, -500, 0)), Quat(), Transform())
end
end
end
function renderPlaneSprite()
local cameraTransform = GetCameraTransform()
local planePosition = planeTransform.pos
local lookRot = QuatLookAt(planePosition, cameraTransform.pos)
local spriteTransform = Transform(planePosition, lookRot)
DrawSprite(planeTest, spriteTransform, 0.25, 0.25, 0.5, 0.5, 0.5, 1, true, true)
end
--[[function renderPlaneSprite()
renderBillboardSprite(planeTest, planeTransform.pos, cameraTransform.pos, 0.25, Color4.White, true, true)
end]]--
--[[function drawRay(origin, dir, dist, width)
local endVec = VecScale(dir, dist)
for x = -1, 1 do
for y = -1, 1 do
if (math.abs(x) == 1 and math.abs(y) ~= 1) or
(math.abs(x) ~= 1 and math.abs(y) == 1) then
local offsetOrigin = VecAdd(origin, VecScale(Vec(x, y, 0), width))
DebugLine(offsetOrigin, VecAdd(offsetOrigin, endVec), 1, 1, 1, 1)
end
end
end
end]]--
function canUseTool()
return GetString("game.player.tool") == toolName and GetPlayerVehicle() == 0
end
function setSetGoalPos()
local cameraTransform = GetPlayerCameraTransform()
local origin = cameraTransform.pos
local direction = TransformToParentVec(cameraTransform, Vec(0, 0, -1))
local hit, hitPoint = raycast(origin, direction)
if hit then
setGoalPos = hitPoint
setGoalPosActive = true
end
end
function startFlight()
local playerCameraTransform = GetPlayerCameraTransform()
local planePosition = VecAdd(playerCameraTransform.pos, Vec(0, 1, 0))
local planeRotation = playerCameraTransform.rot
planeTransform = Transform(planePosition, planeRotation)
planeActive = true
local localCameraTransform = Transform(cameraLocalPos, cameraLocalRot)
local worldCameraTransform = TransformToParentTransform(planeTransform, localCameraTransform)
cameraTransform.pos = worldCameraTransform.pos
cameraTransform.rot = worldCameraTransform.rot
end
function thirdPersonControls()
local planePosition = planeTransform.pos
local planeRotation = planeTransform.rot
local goalRot = nil
local mouseDeltaX = InputValue("mousedx") / 2
local mouseDeltaY = InputValue("mousedy") / 2
local rotDist = -5
local turnDir = Vec(mouseDeltaX, -mouseDeltaY, rotDist)
local goalPos = TransformToParentPoint(planeTransform, turnDir)
goalRot = QuatLookAt(planePosition, goalPos)
return goalRot
end
function rcControls()
local planePosition = planeTransform.pos
local planeRotation = planeTransform.rot
local goalRot = nil
local playerCameraTransform = GetPlayerCameraTransform()
local origin = playerCameraTransform.pos
local direction = TransformToParentVec(playerCameraTransform, Vec(0, 0, -1))
local hit, hitPoint = raycast(origin, direction)
if hit then
goalRot = QuatLookAt(planePosition, hitPoint)
else
local goalPos = VecAdd(planePosition, direction)
goalRot = QuatLookAt(planePosition, goalPos)
end
return goalRot
end
function handleFlight(dt)
local localVelocity = VecScale(planeDirection, GetValue("Speed") * dt)
local planePosition = planeTransform.pos
local planeRotation = planeTransform.rot
local worldVelocity = TransformToParentVec(planeTransform, localVelocity)
planePosition = VecAdd(planePosition, worldVelocity)
local goalRot = nil
if not isMenuOpen() then
if not setGoalPosActive then
if inFlightCamera then
goalRot = thirdPersonControls()
else
goalRot = rcControls()
end
else
goalRot = QuatLookAt(planePosition, setGoalPos)
if VecDist(planeTransform.pos, setGoalPos) < 1 then
setGoalPosActive = false
end
end
if goalRot ~= nil then
planeRotation = QuatSlerp(planeRotation, goalRot, GetValue("TurnSpeed") * dt)
end
end
planeTransform.pos = planePosition
planeTransform.rot = planeRotation
end
function handlePlaneCollisions(fromPos)
local origin = fromPos
local direction = TransformToParentVec(planeTransform, Vec(0, 0, -1))
local hit, hitPoint = raycast(origin, direction, collisionRayLength, collisionRayWidth)
if hit then
if not GetValue("ExplodeOnImpact") then
MakeHole(hitPoint, 4, 4, 4)
else
Explosion(hitPoint, 2)
end
damageTick = maxDamageTick
QueryRequire("dynamic")
local inFrontPos = VecAdd(origin, VecScale(direction, forceWaveRange / 2))
local minPos = VecAdd(inFrontPos, Vec(-forceWaveRange, -forceWaveRange, -forceWaveRange))
local maxPos = VecAdd(inFrontPos, Vec(forceWaveRange, forceWaveRange, forceWaveRange))
local bodies = QueryAabbBodies(minPos, maxPos)
for i = 1, #bodies do
local hitBody = bodies[i]
SetBodyVelocity(hitBody, VecScale(direction, collisionForce))
--local bodyMass = GetBodyMass(hitBody)
--ApplyBodyImpulse(hitBody, hitPoint, VecScale(direction, bodyMass * collisionForce))
end
if GetValue("DieOnImpact") then
planeActive = false
setGoalPosActive = false
end
end
end
function placeLocalBodyAtPos(toolBody, toolShape, currPlaneTransform, localShapeTransform)
local toolTransform = GetBodyTransform(toolBody)
local localPlaneTransform = TransformToLocalTransform(toolTransform, currPlaneTransform)
local outsideShapeTransform = TransformToParentTransform(localPlaneTransform, localShapeTransform)
--[[localPlaneTransform.pos = VecAdd(localPlaneTransform.pos, localShapeTransform.pos)
localPlaneTransform.rot = QuatRotateQuat(localPlaneTransform.rot, localShapeTransform.rot)
local worldShapeTransform = TransformToParentTransform(localPlaneTransform, outsideShapeTransform)
ParticleReset()
ParticleColor(1, 0, 0)
ParticleRadius(0.2)
SpawnParticle(worldShapeTransform.pos, Vec(), 0.2)]]--
SetShapeLocalTransform(toolShape, outsideShapeTransform)
end
function cameraLogic(dt)
local localCameraTransform = Transform(cameraLocalPos, cameraLocalRot)
local worldCameraTransform = TransformToParentTransform(planeTransform, localCameraTransform)
cameraTransform.pos = VecLerp(cameraTransform.pos, worldCameraTransform.pos, GetValue("CameraLerpSpeed") * dt)
cameraTransform.rot = worldCameraTransform.rot
SetPlayerTransform(cameraTransform)
end
function resetShapeLocation(toolShape)
local tempTransform = Transform(Vec(0, 0, 0), Quat())
local localTransform = TransformToLocalTransform(toolTransform, tempTransform)
SetShapeLocalTransform(toolShape, localTransform)
end
|
local rspamd_logger = require "rspamd_logger"
local argparse = require "argparse"
local lua_util = require "lua_util"
local ucl = require "ucl"
local parser = argparse()
:name "rspamadm neural_test"
:description "Test the neural network with labelled dataset"
:help_description_margin(32)
parser:option "-c --config"
:description "Path to config file"
:argname("<cfg>")
:default(rspamd_paths["CONFDIR"] .. "/" .. "rspamd.conf")
parser:option "-H --hamdir"
:description("Ham directory")
:argname("<dir>")
parser:option "-S --spamdir"
:description("Spam directory")
:argname("<dir>")
parser:option "-t --timeout"
:description("Timeout for client connections")
:argname("<sec>")
:convert(tonumber)
:default(60)
parser:option "-n --conns"
:description("Number of parallel connections")
:argname("<N>")
:convert(tonumber)
:default(10)
parser:option "-c --connect"
:description("Connect to specific host")
:argname("<host>")
:default('localhost:11334')
parser:option "-r --rspamc"
:description("Use specific rspamc path")
:argname("<path>")
:default('rspamc')
parser:option '--rule'
:description 'Rule to test'
:argname('<rule>')
local HAM = "HAM"
local SPAM = "SPAM"
local function load_config(opts)
local _r,err = rspamd_config:load_ucl(opts['config'])
if not _r then
rspamd_logger.errx('cannot parse %s: %s', opts['config'], err)
os.exit(1)
end
_r,err = rspamd_config:parse_rcl({'logging', 'worker'})
if not _r then
rspamd_logger.errx('cannot process %s: %s', opts['config'], err)
os.exit(1)
end
end
local function scan_email(rspamc_path, host, n_parallel, path, timeout)
local rspamc_command = string.format("%s --connect %s -j --compact -n %s -t %.3f %s",
rspamc_path, host, n_parallel, timeout, path)
local result = assert(io.popen(rspamc_command))
result = result:read("*all")
return result
end
local function encoded_json_to_log(result)
-- Returns table containing score, action, list of symbols
local filtered_result = {}
local ucl_parser = ucl.parser()
local is_good, err = ucl_parser:parse_string(result)
if not is_good then
rspamd_logger.errx("Parser error: %1", err)
return nil
end
result = ucl_parser:get_object()
filtered_result.score = result.score
if not result.action then
rspamd_logger.errx("Bad JSON: %1", result)
return nil
end
local action = result.action:gsub("%s+", "_")
filtered_result.action = action
filtered_result.symbols = {}
for sym, _ in pairs(result.symbols) do
table.insert(filtered_result.symbols, sym)
end
filtered_result.filename = result.filename
filtered_result.scan_time = result.scan_time
return filtered_result
end
local function filter_scan_results(results, actual_email_type)
local logs = {}
results = lua_util.rspamd_str_split(results, "\n")
if results[#results] == "" then
results[#results] = nil
end
for _, result in pairs(results) do
result = encoded_json_to_log(result)
if result then
result['type'] = actual_email_type
table.insert(logs, result)
end
end
return logs
end
local function get_stats_from_scan_results(results, rules)
local rule_stats = {}
for rule,_ in pairs(rules) do
rule_stats[rule] = {tp = 0, tn = 0, fp = 0, fn = 0}
end
for _,result in ipairs(results) do
for _,symbol in ipairs(result["symbols"]) do
for name,rule in pairs(rules) do
if rule.symbol_spam and rule.symbol_spam == symbol then
if result.type == HAM then
rule_stats[name].fp = rule_stats[name].fp + 1
elseif result.type == SPAM then
rule_stats[name].tp = rule_stats[name].tp + 1
end
elseif rule.symbol_ham and rule.symbol_ham == symbol then
if result.type == HAM then
rule_stats[name].tn = rule_stats[name].tn + 1
elseif result.type == SPAM then
rule_stats[name].fn = rule_stats[name].fn + 1
end
end
end
end
end
for rule,_ in pairs(rules) do
rule_stats[rule].fpr = rule_stats[rule].fp / (rule_stats[rule].fp + rule_stats[rule].tn)
rule_stats[rule].fnr = rule_stats[rule].fn / (rule_stats[rule].fn + rule_stats[rule].tp)
end
return rule_stats
end
local function print_neural_stats(neural_stats)
for rule, stats in pairs(neural_stats) do
rspamd_logger.messagex("\nStats for rule: %s", rule)
rspamd_logger.messagex("False positive rate: %s%%", stats.fpr * 100)
rspamd_logger.messagex("False negative rate: %s%%", stats.fnr * 100)
end
end
local function handler(args)
local opts = parser:parse(args)
local ham_directory = opts['hamdir']
local spam_directory = opts['spamdir']
local connections = opts["conns"]
load_config(opts)
local neural_opts = rspamd_config:get_all_opt('neural')
if opts["rule"] then
local found = false
for rule_name, _ in pairs(neural_opts.rules) do
if string.lower(rule_name) == string.lower(opts["rule"]) then
found = true
else
neural_opts.rules[rule_name] = nil
end
end
if not found then
rspamd_logger.errx("Couldn't find the rule %s", opts["rule"])
return
end
end
local results = {}
if ham_directory then
rspamd_logger.messagex("Scanning ham corpus...")
local ham_results = scan_email(opts.rspamc, opts.connect, connections, ham_directory, opts.timeout)
ham_results = filter_scan_results(ham_results, HAM)
for _, result in pairs(ham_results) do
table.insert(results, result)
end
end
if spam_directory then
rspamd_logger.messagex("Scanning spam corpus...")
local spam_results = scan_email(opts.rspamc, opts.connect, connections, spam_directory, opts.timeout)
spam_results = filter_scan_results(spam_results, SPAM)
for _, result in pairs(spam_results) do
table.insert(results, result)
end
end
local neural_stats = get_stats_from_scan_results(results, neural_opts.rules)
print_neural_stats(neural_stats)
end
return {
name = "neuraltest",
aliases = {"neural_test"},
handler = handler,
description = parser._description
}
|
BRACKET_PRECEDENCE = 20
DEEP_PRECEDENCE = BRACKET_PRECEDENCE * 1000
function IS_LEFT_TO_RIGHT(p)
return (p ~= 2) and (p ~= 14)
end
-- enum OperatorOrder
OperatorOrder = {
OrderNone = 1,
OrderPrefix = 2,
OrderInfix = 3,
OrderPostfix = 4
}
OperatorPrecedence = {
-- TokenNone
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 0,
Name = "none",
},
-- TokenComma
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 0,
Name = ",",
},
-- TokenAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "=",
},
-- TokenAddAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "+=",
},
-- TokenSubtractAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "-=",
},
-- TokenMultiplyAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "*=",
},
-- TokenDivideAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "/=",
},
-- TokenModulusAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "%=",
},
-- TokenShiftLeftAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "<<=",
},
-- TokenShiftRightAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = ">>=",
},
-- TokenArithmeticAndAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "&=",
},
-- TokenArithmeticOrAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "|=",
},
-- TokenArithmeticExorAssign
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 2,
Name = "^=",
},
-- TokenQuestionMark
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 3,
Name = "?",
},
-- TokenColon
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 3,
Name = ":",
},
-- TokenLogicalOr
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 4,
Name = "||",
},
-- TokenLogicalAnd
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 5,
Name = "&&",
},
-- TokenArithmeticOr
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 6,
Name = "=",
},
-- TokenArithmeticExor
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 7,
Name = "^",
},
-- TokenAmpersand
{
PrefixPrecedence = 14,
PostfixPrecedence = 0,
InfixPrecedence = 8,
Name = "&",
},
-- TokenEqual
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 9,
Name = "==",
},
-- TokenNotEqual
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 9,
Name = "!=",
},
-- TokenLessThan
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 10,
Name = "<",
},
-- TokenGreaterThan
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 10,
Name = ">",
},
-- TokenLessEqual
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 10,
Name = "<=",
},
-- TokenGreaterEqual
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 10,
Name = ">=",
},
-- TokenShiftLeft
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 11,
Name = "<<",
},
-- TokenShiftRight
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 11,
Name = ">>",
},
-- TokenPlus
{
PrefixPrecedence = 14,
PostfixPrecedence = 0,
InfixPrecedence = 12,
Name = "+",
},
-- TokenMinus
{
PrefixPrecedence = 14,
PostfixPrecedence = 0,
InfixPrecedence = 12,
Name = "-",
},
-- TokenAsterisk
{
PrefixPrecedence = 14,
PostfixPrecedence = 0,
InfixPrecedence = 13,
Name = "*",
},
-- TokenSlash
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 13,
Name = "/",
},
-- TokenModulus
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 13,
Name = "%",
},
-- TokenIncrement
{
PrefixPrecedence = 14,
PostfixPrecedence = 15,
InfixPrecedence = 0,
Name = "++",
},
-- TokenDecrement
{
PrefixPrecedence = 14,
PostfixPrecedence = 15,
InfixPrecedence = 0,
Name = "--",
},
-- TokenUnaryNot
{
PrefixPrecedence = 14,
PostfixPrecedence = 0,
InfixPrecedence = 0,
Name = "!",
},
-- TokenUnaryExor
{
PrefixPrecedence = 14,
PostfixPrecedence = 0,
InfixPrecedence = 0,
Name = "~",
},
-- TokenSizeof
{
PrefixPrecedence = 14,
PostfixPrecedence = 0,
InfixPrecedence = 0,
Name = "sizeof",
},
-- TokenCast
{
PrefixPrecedence = 14,
PostfixPrecedence = 0,
InfixPrecedence = 0,
Name = "cast",
},
-- TokenLeftSquareBracket
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 15,
Name = "[",
},
-- TokenRightSquareBracket
{
PrefixPrecedence = 0,
PostfixPrecedence = 15,
InfixPrecedence = 0,
Name = "]",
},
-- TokenDot
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 15,
Name = ".",
},
-- TokenArrow
{
PrefixPrecedence = 0,
PostfixPrecedence = 0,
InfixPrecedence = 15,
Name = "->",
},
-- TokenOpenBracket
{
PrefixPrecedence = 15,
PostfixPrecedence = 0,
InfixPrecedence = 0,
Name = "(",
},
-- TokenCloseBracket
{
PrefixPrecedence = 0,
PostfixPrecedence = 15,
InfixPrecedence = 0,
Name = ")",
},
}
function IsTypeToken(Parser, t, LexValue)
local VarValue
if t >= LexToken.TokenIntType and t <= LexToken.TokenUnsignedType then
return true
end
if t == LexToken.TokenIdentifier then
if VariableDefined(Parser.pc, LexValue.Val) then
VarValue = VariableGet(Parser.pc, Parser, LexValue.Val)
if VarValue.Typ == Parser.pc.TypeType then
return true
end
end
end
return false
end
function ExpressionCoerceInteger(Val)
if Val.Typ.Base == BaseType.TypeInt then
return PointerGetSignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedInt then
return PointerGetUnsignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeChar then
return PointerGetSignedChar(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedChar then
return PointerGetUnsignedChar(Val.Val)
elseif Val.Typ.Base == BaseType.TypeShort then
return PointerGetSignedShort(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedShort then
return PointerGetUnsignedShort(Val.Val)
elseif Val.Typ.Base == BaseType.TypeLong then
return PointerGetSignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedLong then
return PointerGetUnsignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypePointer then
-- Getting the absolute address of a pointer is not supported
-- If pointer is not null, cast a dummy address
if IsPointerNull(Val.Val) then
return 0
else
return 0xCCCC
end
elseif Val.Typ.Base == BaseType.TypeFP then
return (math.floor(PointerGetFP(Val.Val)) + 0x80000000) % 0x100000000 - 0x80000000
else
return 0
end
end
function ExpressionCoerceUnsignedInteger(Val)
if Val.Typ.Base == BaseType.TypeInt then
return PointerGetUnsignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedInt then
return PointerGetUnsignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeChar then
return PointerGetUnsignedChar(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedChar then
return PointerGetUnsignedChar(Val.Val)
elseif Val.Typ.Base == BaseType.TypeShort then
return PointerGetUnsignedShort(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedShort then
return PointerGetUnsignedShort(Val.Val)
elseif Val.Typ.Base == BaseType.TypeLong then
return PointerGetUnsignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedLong then
return PointerGetUnsignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypePointer then
-- Getting the absolute address of a pointer is not supported
-- If pointer is not null, cast a dummy address
if IsPointerNull(Val.Val) then
return 0
else
return 0xCCCC
end
elseif Val.Typ.Base == BaseType.TypeFP then
return math.floor(PointerGetFP(Val.Val)) % 0x100000000
else
return 0
end
end
function ExpressionCoerceFP(Val)
if Val.Typ.Base == BaseType.TypeInt then
return PointerGetSignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedInt then
return PointerGetUnsignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeChar then
return PointerGetSignedChar(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedChar then
return PointerGetUnsignedChar(Val.Val)
elseif Val.Typ.Base == BaseType.TypeShort then
return PointerGetSignedShort(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedShort then
return PointerGetUnsignedShort(Val.Val)
elseif Val.Typ.Base == BaseType.TypeLong then
return PointerGetSignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeUnsignedLong then
return PointerGetUnsignedInt(Val.Val)
elseif Val.Typ.Base == BaseType.TypeFP then
return PointerGetFP(Val.Val)
else
return 0
end
end
function ExpressionAssignInt(Parser, DestValue, FromInt, After)
local Result
if not DestValue.IsLValue then
ProgramFail(Parser, "can't assign to this")
end
if After then
Result = ExpressionCoerceInteger(DestValue)
else
Result = FromInt
end
if (DestValue.Typ.Base == BaseType.TypeInt or
DestValue.Typ.Base == BaseType.TypeUnsignedInt) then
PointerSetSignedOrUnsignedInt(DestValue.Val, FromInt)
elseif (DestValue.Typ.Base == BaseType.TypeChar or
DestValue.Typ.Base == BaseType.TypeUnsignedChar) then
PointerSetSignedOrUnsignedChar(DestValue.Val, FromInt)
elseif (DestValue.Typ.Base == BaseType.TypeShort or
DestValue.Typ.Base == BaseType.TypeUnsignedShort) then
PointerSetSignedOrUnsignedShort(DestValue.Val, FromInt)
elseif (DestValue.Typ.Base == BaseType.TypeLong or
DestValue.Typ.Base == BaseType.TypeUnsignedLong) then
PointerSetSignedOrUnsignedInt(DestValue.Val, FromInt)
end
--if VariableDebug then
-- print("Variable:", FromInt)
--end
return Result
end
function ExpressionAssignFP(Parser, DestValue, FromFP)
if not DestValue.IsLValue then
ProgramFail(Parser, "can't assign to this")
end
PointerSetFP(DestValue.Val, FromFP)
--if VariableDebug then
-- print("Variable:", FromFP)
--end
return FromFP
end
function ExpressionStackPushValueNode(Parser, StackTop, ValueLoc)
local StackNode
StackNode = VariableAlloc(Parser.pc, Parser, false)
if StackTop == nil then
StackNode.NextNodeId = 0
else
StackNode.NextNodeId = StackTop.StackId
end
StackNode.Val = ValueLoc
StackNode.Op = LexToken.TokenNone
StackNode.Precedence = 0
StackNode.Order = OperatorOrder.OrderNone
StackTop = StackNode
-- #ifdef FANCY_ERROR_MESSAGES
--StackNode.Line = Parser.Line
--StackNode.CharacterPos = Parser.CharacterPos
-- #endif
-- #ifdef DEBUG_EXPRESSIONS
-- ExpressionStackShow(Parser.pc, StackTop)
-- #endif
return StackTop
end
function ExpressionStackPushValueByType(Parser, StackTop, PushType)
local ValueLoc
ValueLoc = VariableAllocValueFromType(Parser.pc, Parser,
PushType, false, nil, false)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, ValueLoc)
--if Debug then
-- print("Set", ValueLoc.Typ.Base)
--end
return ValueLoc, StackTop
end
function ExpressionStackPushValue(Parser, StackTop, PushValue)
local ValueLoc = VariableAllocValueAndCopy(Parser.pc, Parser,
PushValue, false)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, ValueLoc)
return StackTop
end
function ExpressionStackPushLValue(Parser, StackTop, PushValue, Offset)
local ValueLoc = VariableAllocValueShared(Parser, PushValue)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, ValueLoc)
return StackTop
end
function ExpressionStackPushDereference(Parser, StackTop, DereferenceValue)
local DerefIsLValue, DerefVal, ValueLoc, DerefType
local DerefDataLoc
DerefDataLoc, DerefVal, DerefType, _, DerefIsLValue =
VariableDereferencePointer(DereferenceValue)
--print("Dereference:", DerefType.Base)
if DerefDataLoc == nil then
ProgramFail(Parser, "trying to dereference a void pointer - is the pointer NULL or pointing to a deallocated variable?")
end
ValueLoc = VariableAllocValueFromExistingData(Parser, DerefType,
DerefDataLoc, DerefIsLValue, DerefVal)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, ValueLoc)
return StackTop
end
function ExpressionPushInt(Parser, StackTop, IntValue)
local ValueLoc = VariableAllocValueFromType(Parser.pc, Parser,
Parser.pc.IntType, false, nil, false)
PointerSetSignedOrUnsignedInt(ValueLoc.Val, IntValue)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, ValueLoc)
return StackTop
end
function ExpressionPushFP(Parser, StackTop, FPValue)
local ValueLoc = VariableAllocValueFromType(Parser.pc, Parser,
Parser.pc.FPType, false, nil, false)
PointerSetFP(ValueLoc.Val, FPValue)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, ValueLoc)
return StackTop
end
function ExpressionAssignToPointer(Parser, ToValue, FromValue, FuncName, ParamNo, AllowPointerCoercion)
local PointedToType = ToValue.Typ.FromType
if (FromValue.Typ == ToValue.Typ or
FromValue.Typ == Parser.pc.VoidPtrType or
(ToValue.Typ == Parser.pc.VoidPtrType and
FromValue.Typ.Base == BaseType.TypePointer)) then
PointerCopyPointer(ToValue.Val, FromValue.Val)
elseif (FromValue.Typ.Base == BaseType.TypeArray and
(PointedToType == FromValue.Typ.FromType or
ToValue.Typ == Parser.pc.VoidPtrType)) then
PointerReference(ToValue.Val, FromValue.Val)
--print("CoercePointer:", PointerGetSignedInt(ToValue.Val))
elseif (FromValue.Typ.Base == BaseType.TypePointer and
FromValue.Typ.FromType.Base == BaseType.TypeArray and
(PointedToType == FromValue.Typ.FromType.FromType or
ToValue.Typ == Parser.pc.VoidPtrType)) then
PointerCopyPointer(ToValue.Val, FromValue.Val)
elseif (IS_NUMERIC_COERCIBLE(FromValue) and
ExpressionCoerceInteger(FromValue) == 0) then
PointerSetNull(ToValue.Val)
elseif AllowPointerCoercion and IS_NUMERIC_COERCIBLE(FromValue) then
-- Assigning absolute address is not supported:
-- There is no real address space!
ProgramFail(Parser, "assigning absolute address to pointer is not supported")
elseif AllowPointerCoercion and FromValue.Typ.Base == BaseType.TypePointer then
PointerCopyPointer(ToValue.Val, FromValue.Val)
else
AssignFail(Parser, "%t from %t", ToValue.Typ, FromValue.Typ, 0, 0,
FuncName, ParamNo)
end
end
function ExpressionAssign(Parser, DestValue, SourceValue, Force, FuncName, ParamNo, AllowPointerCoercion)
if not DestValue.IsLValue and not Force then
AssignFail(Parser, "not an lvalue", nil, nil, 0, 0, FuncName, ParamNo)
end
if (IS_NUMERIC_COERCIBLE(DestValue) and
not IS_NUMERIC_COERCIBLE_PLUS_POINTERS(SourceValue, AllowPointerCoercion)) then
AssignFail(Parser, "%t from %t", DestValue.Typ, SourceValue.Typ, 0, 0,
FuncName, ParamNo)
end
if DestValue.Typ.Base == BaseType.TypeInt then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceInteger(SourceValue))
--end
PointerSetSignedOrUnsignedInt(DestValue.Val, ExpressionCoerceInteger(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypeShort then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceInteger(SourceValue))
--end
PointerSetSignedOrUnsignedShort(DestValue.Val, ExpressionCoerceInteger(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypeChar then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceInteger(SourceValue))
--end
PointerSetSignedOrUnsignedChar(DestValue.Val, ExpressionCoerceInteger(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypeLong then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceInteger(SourceValue))
--end
PointerSetSignedOrUnsignedInt(DestValue.Val, ExpressionCoerceInteger(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypeUnsignedInt then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceInteger(SourceValue))
--end
PointerSetSignedOrUnsignedInt(DestValue.Val, ExpressionCoerceUnsignedInteger(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypeUnsignedShort then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceInteger(SourceValue))
--end
PointerSetSignedOrUnsignedShort(DestValue.Val, ExpressionCoerceUnsignedInteger(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypeUnsignedLong then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceInteger(SourceValue))
--end
PointerSetSignedOrUnsignedInt(DestValue.Val, ExpressionCoerceUnsignedInteger(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypeUnsignedChar then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceInteger(SourceValue))
--end
PointerSetSignedOrUnsignedChar(DestValue.Val, ExpressionCoerceInteger(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypeFP then
--if VariableDebug then
-- print("Variable:", ExpressionCoerceFP(SourceValue))
--end
if not IS_NUMERIC_COERCIBLE_PLUS_POINTERS(SourceValue, AllowPointerCoercion) then
AssignFail(Parser, "%t from %t", DestValue.Typ, SourceValue.Typ, 0, 0,
FuncName, ParamNo)
end
PointerSetFP(DestValue.Val, ExpressionCoerceFP(SourceValue))
elseif DestValue.Typ.Base == BaseType.TypePointer then
ExpressionAssignToPointer(Parser, DestValue, SourceValue, FuncName,
ParamNo, AllowPointerCoercion)
elseif DestValue.Typ.Base == BaseType.TypeArray then
local DerefVal, Size
if (SourceValue.Typ.Base == BaseType.TypeArray and
DestValue.Typ.ArraySize == 0) then
DestValue.Typ = SourceValue.Typ
VariableRealloc(Parser, DestValue, TypeSizeValue(DestValue, false))
if DestValue.LValueFrom ~= nil then
DestValue.LValueFrom.Val = DestValue.Val
DestValue.LValueFrom.AnyValOnHeap = DestValue.AnyValOnHeap
end
end
if (DestValue.Typ.FromType.Base == BaseType.TypeChar and
SourceValue.Typ.Base == BaseType.TypePointer and
SourceValue.Typ.FromType.Base == BaseType.TypeChar) then
DerefVal = PointerDereference(SourceValue.Val)
if DestValue.Typ.ArraySize == 0 then
Size = PointerStringLen(DerefVal)
DestValue.Typ = TypeGetMatching(Parser.pc, Parser,
DestValue.Typ.FromType, DestValue.Typ.Base,
Size, DestValue.Typ.Identifier, true)
VariableRealloc(Parser, DestValue, TypeSizeValue(DestValue,
false))
end
PointerCopyValue(DestValue.Val, DerefVal, DestValue.Typ)
else
if DestValue.Typ ~= SourceValue.Typ then
AssignFail(Parser, "%t from %t", DestValue.Typ, SourceValue.Typ,
0, 0, FuncName, ParamNo)
end
if DestValue.Typ.ArraySize ~= SourceValue.Typ.ArraySize then
AssignFail(Parser, "from an array of size %d to one of size %d",
nil, nil, DestValue.Typ.ArraySize,
SourceValue.Typ.ArraySize, FuncName, ParamNo)
end
PointerCopyValue(DestValue.Val, SourceValue.Val, DestValue.Typ)
end
elseif (DestValue.Typ.Base == BaseType.TypeStruct or
DestValue.Typ.Base == BaseType.TypeUnion) then
if DestValue.Typ ~= SourceValue.Typ then
AssignFail(Parser, "%t from %t", DestValue.Typ, SourceValue.Typ,
0, 0, FuncName, ParamNo)
end
PointerCopyValue(DestValue.Val, SourceValue.Val, DestValue.Typ)
else
AssignFail(Parser, "%t", DestValue.Typ, nil, 0, 0, FuncName, ParamNo)
end
end
function ExpressionQuestionMarkOperator(Parser, StackTop, BottomValue, TopValue)
if not IS_NUMERIC_COERCIBLE(TopValue) then
ProgramFail(Parser, "first argument to '?' should be a number")
end
if ExpressionCoerceInteger(TopValue) ~= 0 then
StackTop = ExpressionStackPushValue(Parser, StackTop, BottomValue)
else
_, StackTop = ExpressionStackPushValueByType(Parser, StackTop, Parser.pc.VoidType)
end
return StackTop
end
function ExpressionColonOperator(Parser, StackTop, BottomValue, TopValue)
if TopValue.Typ.Base == BaseType.TypeVoid then
StackTop = ExpressionStackPushValue(Parser, StackTop, BottomValue)
else
StackTop = ExpressionStackPushValue(Parser, StackTop, TopValue)
end
return StackTop
end
function ExpressionPrefixOperator(Parser, StackTop, Op, TopValue)
local Result, Typ
local ResultFP, ResultInt, TopInt
if Op == LexToken.TokenAmpersand then
if not TopValue.IsLValue then
ProgramFail(Parser, "can't get the address of this")
end
Result = VariableAllocValueFromType(Parser.pc, Parser,
TypeGetMatching(Parser.pc, Parser, TopValue.Typ,
BaseType.TypePointer, 0, Parser.pc.StrEmpty, true),
false, nil, false)
PointerReference(Result.Val, TopValue.Val)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, Result)
elseif Op == LexToken.TokenAsterisk then
if StackTop ~= nil then
if StackTop.Op == LexToken.TokenSizeof then
_, StackTop = ExpressionStackPushValueByType(Parser, StackTop, TopValue.Typ)
else
StackTop = ExpressionStackPushDereference(Parser, StackTop, TopValue)
end
else
StackTop = ExpressionStackPushDereference(Parser, StackTop, TopValue)
end
elseif Op == LexToken.TokenSizeof then
if TopValue.Typ == Parser.pc.TypeType then
Typ = TopValue.Val.Typ -- Val here points to Typ, not AnyValue type
else
Typ = TopValue.Typ
end
--if Typ.FromType ~= nil then
-- if Typ.FromType.Base == BaseType.TypeStruct then
-- Typ = Typ.FromType
-- end
--end
StackTop = ExpressionPushInt(Parser, StackTop, TypeSize(Typ, Typ.ArraySize, true))
else
if TopValue.Typ == Parser.pc.FPType then
ResultFP = 0.0
if Op == LexToken.TokenPlus then
ResultFP = PointerGetFP(TopValue.Val)
elseif Op == LexToken.TokenMinus then
ResultFP = -PointerGetFP(TopValue.Val)
elseif Op == LexToken.TokenIncrement then
ResultFP = ExpressionAssignFP(Parser, TopValue,
PointerGetFP(TopValue.Val) + 1)
elseif Op == LexToken.TokenDecrement then
ResultFP = ExpressionAssignFP(Parser, TopValue,
PointerGetFP(TopValue.Val) - 1)
elseif Op == LexToken.TokenUnaryNot then
if PointerGetFP(TopValue.Val) == 0 then
ResultFP = 1
else
ResultFP = 0
end
else
ProgramFail(Parser, "invalid operation")
end
StackTop = ExpressionPushFP(Parser, StackTop, ResultFP)
elseif IS_NUMERIC_COERCIBLE(TopValue) then
ResultInt = 0
TopInt = 0
if TopValue.Typ.Base == BaseType.TypeLong then
TopInt = PointerGetSignedInt(TopValue.Val)
else
TopInt = ExpressionCoerceInteger(TopValue)
end
if Op == LexToken.TokenPlus then
ResultInt = TopInt
elseif Op == LexToken.TokenMinus then
ResultInt = -TopInt
elseif Op == LexToken.TokenIncrement then
ResultInt = ExpressionAssignInt(Parser, TopValue,
TopInt + 1, false)
elseif Op == LexToken.TokenDecrement then
ResultInt = ExpressionAssignInt(Parser, TopValue,
TopInt - 1, false)
elseif Op == LexToken.TokenUnaryNot then
if TopInt == 0 then
ResultInt = 1
else
ResultInt = 0
end
elseif Op == LexToken.TokenUnaryExor then
ResultInt = bnot(TopInt)
else
ProgramFail(Parser, "invalid operation")
end
StackTop = ExpressionPushInt(Parser, StackTop, ResultInt)
elseif TopValue.Typ.Base == BaseType.TypePointer then
local Size = TypeSize(TopValue.Typ.FromType, 0, true)
local StackValue
if Op ~= LexToken.TokenUnaryNot and IsPointerNull(TopValue.Val) then
ProgramFail(Parser, "a. invalid use of a NULL pointer")
end
if not TopValue.IsLValue then
ProgramFail(Parser, "can't assign to this")
end
if Op == LexToken.TokenIncrement then
PointerMovePointer(TopValue.Val, Size)
elseif Op == LexToken.TokenDecrement then
PointerMovePointer(TopValue.Val, -Size)
elseif Op == LexToken.TokenUnaryNot then
if IsPointerNull(TopValue.Val) then
StackTop = ExpressionPushInt(Parser, StackTop, 1)
else
StackTop = ExpressionPushInt(Parser, StackTop, 0)
end
return StackTop
else
ProgramFail(Parser, "invalid operation")
end
StackValue, StackTop = ExpressionStackPushValueByType(Parser, StackTop,
TopValue.Typ)
StackValue.Val = PointerCopyAllValues(TopValue.Val, true)
else
ProgramFail(Parser, "invalid operation")
end
end
return StackTop
end
function ExpressionPostfixOperator(Parser, StackTop, Op, TopValue)
local ResultFP, ResultInt, TopInt
if TopValue.Typ == Parser.pc.FPType then
ResultFP = 0.0
if Op == LexToken.TokenIncrement then
ResultFP = ExpressionAssignFP(Parser, TopValue, PointerGetFP(TopValue.Val) + 1)
elseif Op == LexToken.TokenDecrement then
ResultFP = ExpressionAssignFP(Parser, TopValue, PointerGetFP(TopValue.Val) - 1)
else
ProgramFail(Parser, "invalid operation")
end
StackTop = ExpressionPushFP(Parser, StackTop, ResultFP)
elseif IS_NUMERIC_COERCIBLE(TopValue) then
ResultInt = 0
TopInt = ExpressionCoerceInteger(TopValue)
if Op == LexToken.TokenIncrement then
ResultInt = ExpressionAssignInt(Parser, TopValue, TopInt + 1, true)
elseif Op == LexToken.TokenDecrement then
ResultInt = ExpressionAssignInt(Parser, TopValue, TopInt - 1, true)
elseif Op == LexToken.TokenRightSquareBracket then
ProgramFail(Parser, "not supported")
elseif Op == LexToken.TokenCloseBracket then
ProgramFail(Parser, "not supported")
else
ProgramFail(Parser, "invalid operation")
end
StackTop = ExpressionPushInt(Parser, StackTop, ResultInt)
elseif TopValue.Typ.Base == BaseType.TypePointer then
local Size = TypeSize(TopValue.Typ.FromType, 0, true)
local StackValue
local OrigPointerVal = {}
if IsPointerNull(TopValue.Val) then
ProgramFail(Parser, "a. invalid use of a NULL or void pointer")
end
if not TopValue.IsLValue then
ProgramFail(Parser, "can't assign to this")
end
OrigPointerVal = PointerCopyAllValues(TopValue.Val, true)
if Op == LexToken.TokenIncrement then
PointerMovePointer(TopValue.Val, Size)
elseif Op == LexToken.TokenDecrement then
PointerMovePointer(TopValue.Val, -Size)
else
ProgramFail(Parser, "invalid operation")
end
StackValue, StackTop = ExpressionStackPushValueByType(Parser, StackTop,
TopValue.Typ)
StackValue.Val = PointerCopyAllValues(OrigPointerVal, true)
else
ProgramFail(Parser, "invalid operation")
end
return StackTop
end
function ExpressionInfixOperator(Parser, StackTop, Op, BottomValue, TopValue)
local NewValue
local ResultInt, StackValue
local ArrayIndex, Result
local ResultIsInt, ResultFP, TopFP, BottomFP
local TopInt, BottomInt
local ValueLoc
if BottomValue == nil or TopValue == nil then
ProgramFail(Parser, "invalid expression")
end
--if Debug then
-- print("ExpressionInfixOperator Enter", Op, "Position:", Parser.Line, Parser.CharacterPos)
--end
if Op == LexToken.TokenLeftSquareBracket then
--if Debug then
-- print("Infix ArrayOperation")
--end
if not IS_NUMERIC_COERCIBLE(TopValue) then
ProgramFail(Parser, "array index must be an integer")
end
ArrayIndex = ExpressionCoerceInteger(TopValue)
if BottomValue.Typ.Base == BaseType.TypeArray then
NewValue = {}
PointerDeriveNewValue(NewValue, BottomValue.Val, true)
NewValue.Offset = NewValue.Offset + TypeSize(BottomValue.Typ, ArrayIndex, true)
--print("Coerce1:", PointerGetSignedInt(NewValue))
Result = VariableAllocValueFromExistingData(Parser,
BottomValue.Typ.FromType, NewValue,
BottomValue.IsLValue, BottomValue.LValueFrom)
--print("Coerce1:", ArrayIndex, NewValue.Offset)
--print("Coerce1:", string.len(Result.Val.RawValue.Val))
--print("Coerce1:", PointerGetSignedInt(Result.Val))
elseif BottomValue.Typ.Base == BaseType.TypePointer then
NewValue = PointerCopyAllValues(BottomValue.Val, true)
PointerMovePointer(NewValue, TypeSize(BottomValue.Typ.FromType, 0, true) * ArrayIndex)
NewValue = PointerDereference(NewValue)
if NewValue ~= nil then
Result = VariableAllocValueFromExistingData(Parser,
BottomValue.Typ.FromType, NewValue,
BottomValue.IsLValue, BottomValue.LValueFrom)
else
ProgramFail(Parser, "trying to dereference a void pointer - is the pointer NULL or pointing to a deallocated variable?")
end
else
ProgramFail(Parser, "this %t is not an array", BottomValue.Typ)
end
StackTop = ExpressionStackPushValueNode(Parser, StackTop, Result)
elseif Op == LexToken.TokenQuestionMark then
StackTop = ExpressionQuestionMarkOperator(Parser, StackTop, TopValue, BottomValue)
elseif Op == LexToken.TokenColon then
StackTop = ExpressionColonOperator(Parser, StackTop, TopValue, BottomValue)
elseif ((TopValue.Typ == Parser.pc.FPType and BottomValue.Typ == Parser.pc.FPType) or
(TopValue.Typ == Parser.pc.FPType and IS_NUMERIC_COERCIBLE(BottomValue)) or
(IS_NUMERIC_COERCIBLE(TopValue) and BottomValue.Typ == Parser.pc.FPType)) then
ResultIsInt = false
ResultFP = 0.0
if TopValue.Typ == Parser.pc.FPType then
TopFP = PointerGetFP(TopValue.Val)
else
TopFP = ExpressionCoerceInteger(TopValue)
end
if BottomValue.Typ == Parser.pc.FPType then
BottomFP = PointerGetFP(BottomValue.Val)
else
BottomFP = ExpressionCoerceInteger(BottomValue)
end
if Op == LexToken.TokenAssign then
if IS_FP(BottomValue) then
ResultFP = ExpressionAssignFP(Parser, BottomValue, TopFP)
else
ResultInt = ExpressionAssignInt(Parser, BottomValue, TopFP, false)
ResultIsInt = true
end
elseif Op == LexToken.TokenAddAssign then
if IS_FP(BottomValue) then
ResultFP = ExpressionAssignFP(Parser, BottomValue, TopFP + BottomFP)
else
ResultInt = ExpressionAssignInt(Parser, BottomValue, TopFP + BottomFP, false)
ResultIsInt = true
end
elseif Op == LexToken.TokenSubtractAssign then
if IS_FP(BottomValue) then
ResultFP = ExpressionAssignFP(Parser, BottomValue, BottomFP - TopFP)
else
ResultInt = ExpressionAssignInt(Parser, BottomValue, BottomFP - TopFP, false)
ResultIsInt = true
end
elseif Op == LexToken.TokenMultiplyAssign then
if IS_FP(BottomValue) then
ResultFP = ExpressionAssignFP(Parser, BottomValue, BottomFP * TopFP)
else
ResultInt = ExpressionAssignInt(Parser, BottomValue, BottomFP * TopFP, false)
ResultIsInt = true
end
elseif Op == LexToken.TokenDivideAssign then
if IS_FP(BottomValue) then
ResultFP = ExpressionAssignFP(Parser, BottomValue, BottomFP / TopFP)
else
ResultInt = ExpressionAssignInt(Parser, BottomValue, math.floor(BottomFP / TopFP), false)
ResultIsInt = true
end
elseif Op == LexToken.TokenEqual then
ResultInt = LUA_BOOLEAN_TO_C(BottomFP == TopFP)
ResultIsInt = true
elseif Op == LexToken.TokenNotEqual then
ResultInt = LUA_BOOLEAN_TO_C(BottomFP ~= TopFP)
ResultIsInt = true
elseif Op == LexToken.TokenLessThan then
ResultInt = LUA_BOOLEAN_TO_C(BottomFP < TopFP)
ResultIsInt = true
elseif Op == LexToken.TokenGreaterThan then
ResultInt = LUA_BOOLEAN_TO_C(BottomFP > TopFP)
ResultIsInt = true
elseif Op == LexToken.TokenLessEqual then
ResultInt = LUA_BOOLEAN_TO_C(BottomFP <= TopFP)
ResultIsInt = true
elseif Op == LexToken.TokenGreaterEqual then
ResultInt = LUA_BOOLEAN_TO_C(BottomFP >= TopFP)
ResultIsInt = true
elseif Op == LexToken.TokenPlus then
ResultFP = BottomFP + TopFP
elseif Op == LexToken.TokenMinus then
ResultFP = BottomFP - TopFP
elseif Op == LexToken.TokenAsterisk then
ResultFP = BottomFP * TopFP
elseif Op == LexToken.TokenSlash then
ResultFP = BottomFP / TopFP
else
ProgramFail(Parser, "invalid operation")
end
if ResultIsInt then
StackTop = ExpressionPushInt(Parser, StackTop, ResultInt)
else
StackTop = ExpressionPushFP(Parser, StackTop, ResultFP)
end
elseif IS_NUMERIC_COERCIBLE(TopValue) and IS_NUMERIC_COERCIBLE(BottomValue) then
TopInt = ExpressionCoerceInteger(TopValue)
BottomInt = ExpressionCoerceInteger(BottomValue)
--if Debug then
-- print("TopInt:", TopInt)
-- print("BottomInt:", BottomInt)
--end
if Op == LexToken.TokenAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, TopInt, false)
elseif Op == LexToken.TokenAddAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, BottomInt + TopInt, false)
elseif Op == LexToken.TokenSubtractAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, BottomInt - TopInt, false)
elseif Op == LexToken.TokenMultiplyAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, BottomInt * TopInt, false)
elseif Op == LexToken.TokenDivideAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, math.floor(BottomInt / TopInt), false)
elseif Op == LexToken.TokenModulusAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, BottomInt % TopInt, false)
elseif Op == LexToken.TokenShiftLeftAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, lshift(BottomInt, TopInt), false)
elseif Op == LexToken.TokenShiftRightAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, rshift(BottomInt, TopInt), false)
elseif Op == LexToken.TokenArithmeticAndAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, band(BottomInt, TopInt), false)
elseif Op == LexToken.TokenArithmeticOrAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, bor(BottomInt, TopInt), false)
elseif Op == LexToken.TokenArithmeticExorAssign then
ResultInt = ExpressionAssignInt(Parser, BottomValue, bxor(BottomInt, TopInt), false)
elseif Op == LexToken.TokenLogicalOr then
ResultInt = C_LOGICAL_OR(BottomInt, TopInt)
elseif Op == LexToken.TokenLogicalAnd then
ResultInt = C_LOGICAL_AND(BottomInt, TopInt)
elseif Op == LexToken.TokenArithmeticOr then
ResultInt = bor(BottomInt, TopInt)
elseif Op == LexToken.TokenArithmeticExor then
ResultInt = bxor(BottomInt, TopInt)
elseif Op == LexToken.TokenAmpersand then
ResultInt = band(BottomInt, TopInt)
elseif Op == LexToken.TokenEqual then
ResultInt = LUA_BOOLEAN_TO_C(BottomInt == TopInt)
elseif Op == LexToken.TokenNotEqual then
ResultInt = LUA_BOOLEAN_TO_C(BottomInt ~= TopInt)
elseif Op == LexToken.TokenLessThan then
ResultInt = LUA_BOOLEAN_TO_C(BottomInt < TopInt)
elseif Op == LexToken.TokenGreaterThan then
ResultInt = LUA_BOOLEAN_TO_C(BottomInt > TopInt)
elseif Op == LexToken.TokenLessEqual then
ResultInt = LUA_BOOLEAN_TO_C(BottomInt <= TopInt)
elseif Op == LexToken.TokenGreaterEqual then
ResultInt = LUA_BOOLEAN_TO_C(BottomInt >= TopInt)
elseif Op == LexToken.TokenShiftLeft then
ResultInt = lshift(BottomInt, TopInt)
elseif Op == LexToken.TokenShiftRight then
ResultInt = rshift(BottomInt, TopInt)
elseif Op == LexToken.TokenPlus then
ResultInt = BottomInt + TopInt
elseif Op == LexToken.TokenMinus then
ResultInt = BottomInt - TopInt
elseif Op == LexToken.TokenAsterisk then
ResultInt = BottomInt * TopInt
elseif Op == LexToken.TokenSlash then
ResultInt = math.floor(BottomInt / TopInt)
elseif Op == LexToken.TokenModulus then
ResultInt = BottomInt % TopInt
else
ProgramFail(Parser, "invalid operation")
end
StackTop = ExpressionPushInt(Parser, StackTop, ResultInt)
elseif (BottomValue.Typ.Base == BaseType.TypePointer and
IS_NUMERIC_COERCIBLE(TopValue)) then
TopInt = ExpressionCoerceInteger(TopValue)
if Op == LexToken.TokenEqual or Op == LexToken.TokenNotEqual then
if TopInt ~= 0 then
ProgramFail(Parser, "invalid operation")
end
if Op == LexToken.TokenEqual then
StackTop = ExpressionPushInt(Parser, StackTop,
LUA_BOOLEAN_TO_C(IsPointerNull(BottomValue.Val)))
else
StackTop = ExpressionPushInt(Parser, StackTop,
LUA_BOOLEAN_TO_C(not IsPointerNull(BottomValue.Val)))
end
elseif Op == LexToken.TokenPlus or Op == LexToken.TokenMinus then
local Size = TypeSize(BottomValue.Typ.FromType, 0, true)
local NewOffset = 0
if IsPointerNull(BottomValue.Val) then
ProgramFail(Parser, "c. invalid use of a NULL or void pointer")
end
if Op == LexToken.TokenPlus then
NewOffset = TopInt * Size
else
NewOffset = -TopInt * Size
end
StackValue, StackTop = ExpressionStackPushValueByType(Parser, StackTop,
BottomValue.Typ)
StackValue.Val = PointerCopyAllValues(BottomValue.Val, true)
PointerMovePointer(StackValue.Val, NewOffset)
elseif Op == LexToken.TokenAssign and TopInt == 0 then
-- Recover Value on the stack (the operand) as we only push a ExpressionStack
-- So on the top of the stack it is now ExpressionStack + Value
HeapUnpopStack(Parser.pc)
ExpressionAssign(Parser, BottomValue, TopValue, false, nil, 0, false)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, BottomValue)
elseif Op == LexToken.TokenAddAssign or Op == LexToken.TokenSubtractAssign then
local Size = TypeSize(BottomValue.Typ.FromType, 0, true)
local NewOffset = 0
if IsPointerNull(BottomValue.Val) then
ProgramFail(Parser, "c. invalid use of a NULL or void pointer")
end
if Op == LexToken.TokenAddAssign then
NewOffset = TopInt * Size
else
NewOffset = -TopInt * Size
end
HeapUnpopStack(Parser.pc)
PointerMovePointer(BottomValue.Val, NewOffset)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, BottomValue)
else
ProgramFail(Parser, "invalid operation")
end
elseif (BottomValue.Typ.Base == BaseType.TypePointer and
TopValue.Typ.Base == BaseType.TypePointer and Op ~= LexToken.TokenAssign) then
local CompareResult
if Op == LexToken.TokenEqual then
CompareResult, _ = PointerComparePointer(TopValue.Val, BottomValue.Val, true)
StackTop = ExpressionPushInt(Parser, StackTop,
LUA_BOOLEAN_TO_C(CompareResult))
elseif Op == LexToken.TokenNotEqual then
CompareResult, _ = PointerComparePointer(TopValue.Val, BottomValue.Val, true)
StackTop = ExpressionPushInt(Parser, StackTop,
LUA_BOOLEAN_TO_C(not CompareResult))
elseif Op == LexToken.TokenMinus then
local RefOffsetDifference
CompareResult, RefOffsetDifference = PointerComparePointer(TopValue.Val, BottomValue.Val, false)
if (not CompareResult or
TopValue.Typ.FromType.Base ~= BottomValue.Typ.FromType.Base) then
-- Difference between pointers referencing different
-- variables is not supported here
ProgramFail(Parser, "comparison between pointers with different base addresses is not supported")
end
StackTop = ExpressionPushInt(Parser, StackTop,
math.floor(RefOffsetDifference / TypeSize(BottomValue.Typ.FromType, 0, true)))
else
ProgramFail(Parser, "invalid operation")
end
elseif Op == LexToken.TokenAssign then
HeapUnpopStack(Parser.pc)
ExpressionAssign(Parser, BottomValue, TopValue, false, nil, 0, false)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, BottomValue)
elseif Op == LexToken.TokenCast then
ValueLoc, StackTop = ExpressionStackPushValueByType(Parser, StackTop, BottomValue.Val.Typ)
ExpressionAssign(Parser, ValueLoc, TopValue, true, nil, 0, true)
--if Debug then
-- print("Infix Cast Operation")
--end
else
ProgramFail(Parser, "invalid operation");
end
return StackTop
end
function ExpressionStackCollapse(Parser, StackTop, Precedence, IgnorePrecedence)
local FoundPrecedence = Precedence
local TopValue, BottomValue, TopStackNode, TopOperatorNode
TopStackNode = StackTop
while (TopStackNode ~= nil and HeapGetStackNode(Parser.pc, TopStackNode.NextNodeId) ~= nil and
FoundPrecedence >= Precedence) do
if TopStackNode.Order == OperatorOrder.OrderNone then
-- ExpressionStack + Value
TopOperatorNode = HeapGetStackNode(Parser.pc, TopStackNode.NextNodeId)
else
TopOperatorNode = TopStackNode
end
FoundPrecedence = TopOperatorNode.Precedence
if FoundPrecedence >= Precedence and TopOperatorNode ~= nil then
if TopOperatorNode.Order == OperatorOrder.OrderPrefix then
TopValue = TopStackNode.Val
--if Debug then
-- print("Top:", PointerGetSignedInt(TopValue.Val))
--end
-- OperatorNode, Value, ExpressionStack
-- (From bottom to top)
HeapPopStack(Parser.pc, 3)
--HeapPopStack(Parser.pc, 2) -- ExpressionStack + Value
--HeapPopStack(Parser.pc, 1, TopOperatorNode.StackId - 1) -- OperatorNode
StackTop = HeapGetStackNode(Parser.pc, TopOperatorNode.NextNodeId)
if Parser.Mode == RunMode.RunModeRun then
StackTop = ExpressionPrefixOperator(Parser, StackTop,
TopOperatorNode.Op, TopValue)
else
StackTop = ExpressionPushInt(Parser, StackTop, 0)
end
elseif TopOperatorNode.Order == OperatorOrder.OrderPostfix then
TopValue = HeapGetStackNode(Parser.pc, TopStackNode.NextNodeId).Val
-- Value, ExpressionStack, OperatorNode
-- (From bottom to top)
HeapPopStack(Parser.pc, 3)
--HeapPopStack(Parser.pc, 1) -- OperatorNode
--HeapPopStack(Parser.pc, 2, TopValue.StackId - 1) -- ExpressionStack + Value
StackTop = HeapGetStackNode(Parser.pc,
HeapGetStackNode(Parser.pc, TopStackNode.NextNodeId).NextNodeId)
if Parser.Mode == RunMode.RunModeRun then
StackTop = ExpressionPostfixOperator(Parser, StackTop,
TopOperatorNode.Op, TopValue)
else
StackTop = ExpressionPushInt(Parser, StackTop, 0)
end
elseif TopOperatorNode.Order == OperatorOrder.OrderInfix then
--if Debug then
-- print("Collapse Infix")
--end
TopValue = TopStackNode.Val
if TopValue ~= nil then
BottomValue = HeapGetStackNode(Parser.pc, TopOperatorNode.NextNodeId).Val
--if Debug then
-- print("Top:", PointerGetSignedInt(TopValue.Val), TopValue.Typ)
-- print("Bottom:", PointerGetSignedInt(BottomValue.Val), BottomValue.Typ)
--end
-- Value, ExpressionStack, OperatorNode, Value, ExpressionStack
-- (From bottom to top)
HeapPopStack(Parser.pc, 5)
--HeapPopStack(Parser.pc, 2) -- ExpressionStack + Value
--HeapPopStack(Parser.pc, 1) -- OperatorNode
--HeapPopStack(Parser.pc, 2, BottomValue.StackId - 1) -- ExpressionStack + Value
StackTop = HeapGetStackNode(Parser.pc,
HeapGetStackNode(Parser.pc, TopOperatorNode.NextNodeId).NextNodeId)
if Parser.Mode == RunMode.RunModeRun then
StackTop = ExpressionInfixOperator(Parser, StackTop,
TopOperatorNode.Op, BottomValue, TopValue)
else
StackTop = ExpressionPushInt(Parser, StackTop, 0)
end
else
FoundPrecedence = -1
end
else
-- empty
end
if FoundPrecedence <= IgnorePrecedence then
IgnorePrecedence = DEEP_PRECEDENCE
end
end
TopStackNode = StackTop
end
return StackTop, IgnorePrecedence
end
function ExpressionStackPushOperator(Parser, StackTop, Order, Token, Precedence)
local StackNode
StackNode = VariableAlloc(Parser.pc, Parser, false)
if StackTop == nil then
StackNode.NextNodeId = 0
else
StackNode.NextNodeId = StackTop.StackId
end
StackNode.Order = Order
StackNode.Op = Token
StackNode.Precedence = Precedence
StackTop = StackNode
--StackNode.Line = Parser.Line
--StackNode.CharacterPos = Parser.CharacterPos
return StackTop
end
function ExpressionGetStructElement(Parser, StackTop, Token)
local Ident
local ParamVal, StructVal, StructType, DerefDataLoc, MemberValue, Result
local TokenG
local PF1, PF2
local Success
local LValueFrom
TokenG, Ident = LexGetToken(Parser, Ident, true)
if TokenG ~= LexToken.TokenIdentifier then
if Token == LexToken.TokenDot then
ProgramFail(Parser, "need an structure or union member after '.'")
else
ProgramFail(Parser, "need an structure or union member after '->'")
end
end
if Parser.Mode == RunMode.RunModeRun then
ParamVal = StackTop.Val
StructVal = ParamVal
StructType = ParamVal.Typ
DerefDataLoc = {}
MemberValue = nil
PointerDeriveNewValue(DerefDataLoc, ParamVal.Val, false)
if Token == LexToken.TokenArrow then
DerefDataLoc, StructVal, StructType, _, _ = VariableDereferencePointer(ParamVal)
if DerefDataLoc == nil then
ProgramFail(Parser, "trying to dereference a void pointer - is the pointer NULL or pointing to a deallocated variable?")
end
-- Change the identity of dereferenced value - members in a struct are *de jure* different objects
-- but *de facto* the struct itself with different offsets
DerefDataLoc.Ident = math.random(1, 0x7FFFFFFF)
end
if StructType.Base ~= BaseType.TypeStruct and StructType.Base ~= BaseType.TypeUnion then
if Token == LexToken.TokenDot then PF1 = "."
else PF1 = "->" end
if Token == LexToken.TokenArrow then PF2 = "pointer"
else PF2 = "" end
ProgramFail(Parser, "can't use '%s' on something that's not a struct or union %s : it's a %t",
PF1, PF2, ParamVal.Typ)
end
-- Ident: Value
Success, MemberValue, _, _, _ = TableGet(StructType.Members, Ident.Val) -- Changed from Ident.Val.Identifier
if not Success then
ProgramFail(Parser, "doesn't have a member called '%s",
Ident.Val.RawValue.Val) -- Changed from Ident.Val.Identifier
end
HeapPopStack(Parser.pc, 2, ParamVal.StackId - 1) -- ExpressionStack + Value
StackTop = HeapGetStackNode(Parser.pc, StackTop.NextNodeId)
if StructVal ~= nil then
LValueFrom = StructType.LValueFrom
else
LValueFrom = nil
end
DerefDataLoc.Offset = DerefDataLoc.Offset +
PointerGetSignedInt(MemberValue.Val)
Result = VariableAllocValueFromExistingData(Parser, MemberValue.Typ,
DerefDataLoc, true, LValueFrom)
StackTop = ExpressionStackPushValueNode(Parser, StackTop, Result)
end
return StackTop
end
function ExpressionParse(Parser)
local PrefixState = true
local Done = false
local BracketPrecedence = 0
local LocalPrecedence
local Precedence = 0
local IgnorePrecedence = DEEP_PRECEDENCE
local TernaryDepth = 0
local LexValue
local StackTop = nil
local Result
repeat
local PreState = {}
local Token
ParserCopy(PreState, Parser)
Token, LexValue = LexGetToken(Parser, LexValue, true)
--print("Token:", Token)
if (((Token > LexToken.TokenComma and Token <= LexToken.TokenOpenBracket) or
(Token == LexToken.TokenCloseBracket and BracketPrecedence ~= 0)) and
(Token ~= LexToken.TokenColon or TernaryDepth > 0)) then
if PrefixState then
--if Debug then
-- print("Prefix Precedence:", Token, OperatorPrecedence[Token].InfixPrecedence)
--end
if OperatorPrecedence[Token].PrefixPrecedence == 0 then
ProgramFail(Parser, "operator not expected here")
end
LocalPrecedence = OperatorPrecedence[Token].PrefixPrecedence
Precedence = BracketPrecedence + LocalPrecedence
if Token == LexToken.TokenOpenBracket then
local BracketToken
BracketToken, LexValue = LexGetToken(Parser, LexValue, false)
local Cond = false
if StackTop == nil then
Cond = true
else
if StackTop.Op ~= LexToken.TokenSizeof then
Cond = true
else
Cond = false
end
end
if IsTypeToken(Parser, BracketToken, LexValue) and Cond then
local CastType
local CastTypeValue
local Tok
--if Debug then
-- print("Type Cast", BracketToken)
--end
CastType, _, _ = TypeParse(Parser)
Tok, LexValue = LexGetToken(Parser, LexValue, true)
if Tok ~= LexToken.TokenCloseBracket then
ProgramFail(Parser, "brackets not closed")
end
Precedence = BracketPrecedence +
OperatorPrecedence[LexToken.TokenCast].PrefixPrecedence
StackTop, IgnorePrecedence = ExpressionStackCollapse(Parser,
StackTop, Precedence + 1, IgnorePrecedence)
CastTypeValue = VariableAllocValueFromType(Parser.pc,
Parser, Parser.pc.TypeType, false, nil, false)
CastTypeValue.Val.Typ = CastType -- Val here points to Typ, not AnyValue type
StackTop = ExpressionStackPushValueNode(Parser, StackTop,
CastTypeValue)
StackTop = ExpressionStackPushOperator(Parser, StackTop,
OperatorOrder.OrderInfix, LexToken.TokenCast, Precedence)
else
BracketPrecedence = BracketPrecedence + BRACKET_PRECEDENCE
end
else
local NextToken
local TempPrecedenceBoost = 0
NextToken, _ = LexGetToken(Parser, nil, false)
if NextToken > LexToken.TokenComma and NextToken < LexToken.TokenOpenBracket then
local NextPrecedence =
OperatorPrecedence[NextToken].PrefixPrecedence
if LocalPrecedence == NextPrecedence then
TempPrecedenceBoost = -1
end
end
StackTop, IgnorePrecedence = ExpressionStackCollapse(Parser,
StackTop, Precedence, IgnorePrecedence)
StackTop = ExpressionStackPushOperator(Parser, StackTop, OperatorOrder.OrderPrefix,
Token, Precedence + TempPrecedenceBoost)
--if Debug then
-- print("Prefix")
--end
end
else
--if Debug then
-- print("Precedence:", Token, OperatorPrecedence[Token].InfixPrecedence)
--end
if OperatorPrecedence[Token].PostfixPrecedence ~= 0 then
if (Token == LexToken.TokenCloseBracket or
Token == LexToken.TokenRightSquareBracket) then
if BracketPrecedence == 0 then
ParserCopy(Parser, PreState)
Done = true
else
StackTop, IgnorePrecedence = ExpressionStackCollapse(Parser,
StackTop, BracketPrecedence, IgnorePrecedence)
BracketPrecedence = BracketPrecedence - BRACKET_PRECEDENCE
end
else
Precedence = BracketPrecedence +
OperatorPrecedence[Token].PostfixPrecedence
StackTop, IgnorePrecedence = ExpressionStackCollapse(Parser,
StackTop, Precedence, IgnorePrecedence)
StackTop = ExpressionStackPushOperator(Parser, StackTop,
OperatorOrder.OrderPostfix, Token, Precedence)
--if Debug then
-- print("Postfix")
--end
end
elseif OperatorPrecedence[Token].InfixPrecedence ~= 0 then
Precedence = BracketPrecedence +
OperatorPrecedence[Token].InfixPrecedence
if IS_LEFT_TO_RIGHT(OperatorPrecedence[Token].InfixPrecedence) then
StackTop, IgnorePrecedence = ExpressionStackCollapse(Parser,
StackTop, Precedence, IgnorePrecedence)
else
StackTop, IgnorePrecedence = ExpressionStackCollapse(Parser,
StackTop, Precedence + 1, IgnorePrecedence)
end
if Token == LexToken.TokenDot or Token == LexToken.TokenArrow then
StackTop = ExpressionGetStructElement(Parser, StackTop, Token)
else
if ((Token == LexToken.TokenLogicalOr or Token == LexToken.TokenLogicalAnd) and
IS_NUMERIC_COERCIBLE(StackTop.Val)) then
local LHSInt = ExpressionCoerceInteger(StackTop.Val)
if (((Token == LexToken.TokenLogicalOr and LHSInt ~= 0) or
(Token == LexToken.TokenLogicalAnd and LHSInt == 0)) and
(IgnorePrecedence > Precedence)) then
IgnorePrecedence = Precedence
end
end
StackTop = ExpressionStackPushOperator(Parser, StackTop,
OperatorOrder.OrderInfix, Token, Precedence)
PrefixState = true
--if Debug then
-- print("Infix")
--end
if Token == LexToken.TokenQuestionMark then
TernaryDepth = TernaryDepth + 1
elseif Token == LexToken.TokenColon then
TernaryDepth = TernaryDepth - 1
end
end
if Token == LexToken.TokenLeftSquareBracket then
BracketPrecedence = BracketPrecedence + BRACKET_PRECEDENCE
end
else
ProgramFail(Parser, "operator not expected here")
end
end
elseif Token == LexToken.TokenIdentifier then
--if Debug then
-- print("Precedence:", Token)
--end
if not PrefixState then
ProgramFail(Parser, "identifier not expected here")
end
local Tok
Tok, _ = LexGetToken(Parser, nil, false)
if Tok == LexToken.TokenOpenBracket then
StackTop = ExpressionParseFunctionCall(Parser, StackTop,
LexValue.Val, -- Changed from LexValue.Val.Identifier
Parser.Mode == RunMode.RunModeRun and Precedence < IgnorePrecedence)
else
if Parser.Mode == RunMode.RunModeRun then
local VariableValue
VariableValue = VariableGet(Parser.pc, Parser, LexValue.Val) -- Changed from LexValue.Val.Identifier
if VariableValue.Typ.Base == BaseType.TypeMacro then
local MacroParser = {}
local MacroResult
ParserCopy(MacroParser, VariableValue.Val.MacroDef.Body)
MacroParser.Mode = Parser.Mode
if VariableValue.Val.MacroDef.NumParams ~= 0 then
ProgramFail(MacroParser, "macro arguments missing")
end
local Success
Success, MacroResult = ExpressionParse(MacroParser)
Tok, _ = LexGetToken(MacroParser, nil, false)
if (not Success) or Tok ~= LexToken.TokenEndOfFunction then
ProgramFail(MacroParser, "expression expected")
end
StackTop = ExpressionStackPushValueNode(Parser, StackTop, MacroResult)
elseif VariableValue.Typ == Parser.pc.VoidType then
ProgramFail(Parser, "a void value isn't much use here")
else
StackTop = ExpressionStackPushLValue(Parser, StackTop,
VariableValue, 0)
end
else
StackTop = ExpressionPushInt(Parser, StackTop, 0)
end
end
if Precedence <= IgnorePrecedence then
IgnorePrecedence = DEEP_PRECEDENCE
end
PrefixState = false
elseif Token > LexToken.TokenCloseBracket and Token <= LexToken.TokenCharacterConstant then
if not PrefixState then
ProgramFail(Parser, "value not expected here")
end
PrefixState = false
StackTop = ExpressionStackPushValue(Parser, StackTop, LexValue)
--if Debug then
-- print(LexValue.Val.Offset)
--end
elseif IsTypeToken(Parser, Token, LexValue) then
local Typ
local TypeValue
if not PrefixState then
ProgramFail(Parser, "type not expected here")
end
PrefixState = false
ParserCopy(Parser, PreState)
Typ, _, _ = TypeParse(Parser)
TypeValue = VariableAllocValueFromType(Parser.pc, Parser,
Parser.pc.TypeType, false, nil, false)
TypeValue.Val.Typ = Typ -- Val here points to Typ, not AnyValue type
StackTop = ExpressionStackPushValueNode(Parser, StackTop, TypeValue)
else
ParserCopy(Parser, PreState)
Done = true
end
until Done
if BracketPrecedence > 0 then
ProgramFail(Parser, "brackets not closed")
end
StackTop, IgnorePrecedence = ExpressionStackCollapse(Parser, StackTop, 0, IgnorePrecedence)
if StackTop ~= nil then
if Parser.Mode == RunMode.RunModeRun then
if (StackTop.Order ~= OperatorOrder.OrderNone or
HeapGetStackNode(Parser.pc, StackTop.NextNodeId) ~= nil) then
ProgramFail(Parser, "invalid expression")
end
Result = StackTop.Val
HeapPopStack(Parser.pc, 1, StackTop.StackId - 1) -- Pop ExpressionStack, Value is left on stack
else
HeapPopStack(Parser.pc, 2, StackTop.Val.StackId - 1) -- Pop ExpressionStack + Value
end
end
return StackTop ~= nil, Result
end
function ExpressionParseMacroCall(Parser, StackTop, MacroName, MDef)
local ArgCount
local Token
local ReturnValue = nil
local Param
local ParamArray = nil
if Parser.Mode == RunMode.RunModeRun then
_, StackTop = ExpressionStackPushValueByType(Parser, StackTop, Parser.pc.FPType)
ReturnValue = StackTop.Val
HeapPushStackFrame(Parser.pc)
ParamArray = HeapAllocStack(Parser.pc)
if ParamArray == nil then
ProgramFail(Parser, "(ExpressionParseMacroCall) out of memory")
end
else
StackTop = ExpressionPushInt(Parser, StackTop, 0)
end
ArgCount = 0
repeat
local StackNotNull
StackNotNull, Param = ExpressionParse(Parser)
if StackNotNull then
if Parser.Mode == RunMode.RunModeRun then
if ArgCount < MDef.NumParams then
ParamArray[ArgCount + 1] = Param
else
-- MacroName: AnyValue
ProgramFail(Parser, "too many arguments to %s()", MacroName.RawValue.Val)
end
end
ArgCount = ArgCount + 1
Token, _ = LexGetToken(Parser, nil, true)
if Token ~= LexToken.TokenComma and Token ~= LexToken.TokenCloseBracket then
ProgramFail(Parser, "comma expected")
end
else
Token, _ = LexGetToken(Parser, nil, true)
if Token ~= LexToken.TokenCloseBracket then
ProgramFail(Parser, "bad argument")
end
end
until Token == LexToken.TokenCloseBracket
if Parser.Mode == RunMode.RunModeRun then
local MacroParser = {}
local EvalValue
if ArgCount < MDef.NumParams then
ProgramFail(Parser, "not enough arguments to '%s'", MacroName.RawValue.Val)
end
if MDef.Body.ParsingTokens == nil then
ProgramFail(Parser,
"ExpressionParseMacroCall MacroName: '%s' is undefined", MacroName.RawValue.Val)
end
ParserCopy(MacroParser, MDef.Body)
MacroParser.Mode = Parser.Mode
VariableStackFrameAdd(Parser, MacroName, 0)
local TopStackFrame = HeapGetStackNode(Parser.pc, Parser.pc.TopStackFrameId)
TopStackFrame.NumParams = ArgCount
TopStackFrame.ReturnValue = ReturnValue
for Count = 1, MDef.NumParams do
VariableDefine(Parser.pc, Parser, MDef.ParamName[Count],
ParamArray[Count], nil, true)
end
_, EvalValue = ExpressionParse(MacroParser)
ExpressionAssign(Parser, ReturnValue, EvalValue, true, MacroName, 0, false)
VariableStackFramePop(Parser)
HeapPopStackFrame(Parser.pc)
end
return StackTop
end
function ExpressionParseFunctionCall(Parser, StackTop, FuncName, RunIt)
local ArgCount
local Token
local OldMode = Parser.Mode
local ReturnValue = nil
local FuncValue = nil
local Param = nil
local ParamArray = nil
local ParamStartStackId = 0
Token, _ = LexGetToken(Parser, nil, true)
if RunIt then
FuncValue = VariableGet(Parser.pc, Parser, FuncName)
if FuncValue.Typ.Base == BaseType.TypeMacro then
StackTop = ExpressionParseMacroCall(Parser, StackTop, FuncName,
FuncValue.Val.MacroDef)
return StackTop
end
--if Debug then
-- print("Enter Function")
--end
if FuncValue.Typ.Base ~= BaseType.TypeFunction then
ProgramFail(Parser, "%t is not a function - can't call",
FuncValue.Typ)
end
_, StackTop = ExpressionStackPushValueByType(Parser, StackTop,
FuncValue.Val.FuncDef.ReturnType)
ReturnValue = StackTop.Val
--print("Set StackFrame ReturnValue 1", StackTop.Val.Typ.Base)
HeapPushStackFrame(Parser.pc)
ParamArray = HeapAllocStack(Parser.pc)
if ParamArray == nil then
ProgramFail(Parser, "(ExpressionParseFunctionCall) out of memory")
end
else
StackTop = ExpressionPushInt(Parser, StackTop, 0)
Parser.Mode = RunMode.RunModeSkip
end
ArgCount = 0
repeat
if RunIt and ArgCount < FuncValue.Val.FuncDef.NumParams then
ParamArray[ArgCount + 1] = VariableAllocValueFromType(Parser.pc, Parser,
FuncValue.Val.FuncDef.ParamType[ArgCount + 1], false, nil, false)
if ArgCount == 0 then
ParamStartStackId = ParamArray[ArgCount + 1].StackId
end
end
local StackNotNull
StackNotNull, Param = ExpressionParse(Parser)
if StackNotNull then
if RunIt then
if ArgCount < FuncValue.Val.FuncDef.NumParams then
ExpressionAssign(Parser, ParamArray[ArgCount + 1], Param, true,
FuncName, ArgCount + 1, false)
VariableStackPop(Parser, Param)
else
if not FuncValue.Val.FuncDef.VarArgs then
-- FuncName: AnyValue
ProgramFail(Parser, "too many arguments to %s()", FuncName.RawValue.Val)
end
end
end
ArgCount = ArgCount + 1
Token, _ = LexGetToken(Parser, nil, true)
if Token ~= LexToken.TokenComma and Token ~= LexToken.TokenCloseBracket then
ProgramFail(Parser, "comma expected")
end
else
Token, _ = LexGetToken(Parser, nil, true)
if Token ~= LexToken.TokenCloseBracket then
ProgramFail(Parser, "bad argument")
end
end
until Token == LexToken.TokenCloseBracket
if RunIt then
if ArgCount < FuncValue.Val.FuncDef.NumParams then
ProgramFail(Parser, "not enough arguments to '%s'", FuncName.RawValue.Val)
end
if FuncValue.Val.FuncDef.Intrinsic == nil then
local OldScopeID = Parser.ScopeID
local FuncParser = {}
if FuncValue.Val.FuncDef.Body.ParsingTokens == nil then
ProgramFail(Parser,
"ExpressionParseFunctionCall FuncName: '%s' is undefined",
FuncName.RawValue.Val)
end
ParserCopy(FuncParser, FuncValue.Val.FuncDef.Body)
if FuncValue.Val.FuncDef.Intrinsic ~= nil then
VariableStackFrameAdd(Parser, FuncName, FuncValue.Val.FuncDef.NumParams)
else
VariableStackFrameAdd(Parser, FuncName, 0)
end
local TopStackFrame = HeapGetStackNode(Parser.pc, Parser.pc.TopStackFrameId)
TopStackFrame.NumParms = ArgCount
--print("Set StackFrame ReturnValue", Parser.pc.TopStackFrameId)
TopStackFrame.ReturnValue = ReturnValue
--print("Set StackFrame ReturnValue", ReturnValue.Typ.Base)
Parser.ScopeID = -1
for Count = 1, FuncValue.Val.FuncDef.NumParams do
--if Debug then
-- print("ParamName:", ParamArray[Count].Typ)
--end
VariableDefine(Parser.pc, Parser,
FuncValue.Val.FuncDef.ParamName[Count], ParamArray[Count],
nil, true)
end
Parser.ScopeID = OldScopeID
if ParseStatement(FuncParser, true) ~= ParserResult.ParseResultOk then
ProgramFail(FuncParser, "function body expected")
end
if RunIt then
if (FuncParser.Mode == RunMode.RunModeRun and
FuncValue.Val.FuncDef.ReturnType ~= Parser.pc.VoidType) then
ProgramFail(FuncParser,
"no value returned from a function returning %t",
FuncValue.Val.FuncDef.ReturnType)
elseif FuncParser.Mode == RunMode.RunModeGoto then
ProgramFail(FuncParser, "couldn't find goto label '%s'",
FuncParser.SearchGotoLabel)
end
end
VariableStackFramePop(Parser)
else
FuncValue.Val.FuncDef.Intrinsic(Parser, ReturnValue, ParamArray,
ArgCount, ParamStartStackId)
end
--if Debug then
-- print("Pop")
--end
HeapPopStackFrame(Parser.pc)
end
Parser.Mode = OldMode
return StackTop
end
function ExpressionParseInt(Parser)
local Result = 0
local Val
local ParseResult
ParseResult, Val = ExpressionParse(Parser)
if not ParseResult then
ProgramFail(Parser, "expression expected")
end
if Parser.Mode == RunMode.RunModeRun then
if not IS_NUMERIC_COERCIBLE_PLUS_POINTERS(Val, true) then
ProgramFail(Parser, "integer value expected instead of %t", Val.Typ)
end
Result = ExpressionCoerceInteger(Val)
--if Debug then
-- print("ExpressionParseInt:", Result)
--end
VariableStackPop(Parser, Val)
end
return Result
end
|
local defaultSettings = {
AddSetEquipScreenOrder = true,
AllowSyncEquip = true,
AllowAddSet = false,
AddSetBackups = true,
Debug = false,
EquipBags = { 8, 10, 11, 12, 0 };
EnableNomadStorage = false,
ForceDisableBags = { },
ForceEnableBags = { },
RemoveEquipmentForPacker = true,
PetskillDelay = 4.0,
WeaponskillDelay = 3.0,
AbilityDelay = 2.5,
SpellOffset = 1.0,
RangedBase = 10.0,
RangedOffset = 0.5,
ItemOffset = 1.0,
FastCast = 0,
Snapshot = 0
};
return defaultSettings;
|
local K, C = unpack(select(2, ...))
local Module = K:NewModule("VehicleSeat", "AceEvent-3.0")
if C["ActionBar"].Enable ~= true then
return
end
-- Wow Lua
local _G = _G
-- Wow API
local UIParent = _G.UIParent
local hooksecurefunc = _G.hooksecurefunc
function Module:PositionVehicleFrame()
local VehicleSeatMover = CreateFrame("Frame", "VehicleSeatMover", UIParent)
VehicleSeatMover:SetPoint("TOPLEFT", UIParent, "TOPLEFT", 4, -4)
VehicleSeatMover:SetWidth((VehicleSeatIndicator:GetWidth() - 25))
VehicleSeatMover:SetHeight(VehicleSeatIndicator:GetHeight() - 25)
VehicleSeatIndicator:ClearAllPoints()
VehicleSeatIndicator:SetPoint("CENTER", VehicleSeatMover, "CENTER", 0, 0)
VehicleSeatIndicator:SetScale(0.8)
-- This will block UIParent_ManageFramePositions() to be executed
VehicleSeatIndicator.IsShown = function()
return false
end
K.Movers:RegisterFrame(VehicleSeatMover)
end
function Module:OnInitialize()
self:PositionVehicleFrame()
end
|
local moon = require("moon")
moon.start(function()
local mysql = require("moon.db.mysql")
moon.async(function()
local db, err = mysql.connect({
host="192.168.81.129",
port=3306,
database="game",
user="root",
password="4321",
timeout= 1000,--连接超时ms
max_packet_size = 1024 * 1024, --数据包最大字节数
})
if not db then
error(err)
end
local res = db:query("select * from t_users;")
print_r(res)
end)
end)
|
local GSE = GSE
local L = GSE.L
local Statics = GSE.Static
local libS = LibStub:GetLibrary("AceSerializer-3.0")
local libC = LibStub:GetLibrary("LibCompress")
local libCE = libC:GetAddonEncodeTable()
local bytetoB64 = {
[0] = "a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"(",
")"
}
local B64tobyte = {
a = 0,
b = 1,
c = 2,
d = 3,
e = 4,
f = 5,
g = 6,
h = 7,
i = 8,
j = 9,
k = 10,
l = 11,
m = 12,
n = 13,
o = 14,
p = 15,
q = 16,
r = 17,
s = 18,
t = 19,
u = 20,
v = 21,
w = 22,
x = 23,
y = 24,
z = 25,
A = 26,
B = 27,
C = 28,
D = 29,
E = 30,
F = 31,
G = 32,
H = 33,
I = 34,
J = 35,
K = 36,
L = 37,
M = 38,
N = 39,
O = 40,
P = 41,
Q = 42,
R = 43,
S = 44,
T = 45,
U = 46,
V = 47,
W = 48,
X = 49,
Y = 50,
Z = 51,
["0"] = 52,
["1"] = 53,
["2"] = 54,
["3"] = 55,
["4"] = 56,
["5"] = 57,
["6"] = 58,
["7"] = 59,
["8"] = 60,
["9"] = 61,
["("] = 62,
[")"] = 63
}
-- This code is based on the Encode7Bit algorithm from LibCompress
-- Credit goes to Galmok of European Stormrage (Horde), galmok@gmail.com
-- This version was lifted straight from WeakAuras 2
local encodeB64Table = {}
function GSE.encodeB64(str)
local B64 = encodeB64Table
local remainder = 0
local remainder_length = 0
local encoded_size = 0
local l = #str
local code
for i = 1, l do
code = string.byte(str, i)
remainder = remainder + bit.lshift(code, remainder_length)
remainder_length = remainder_length + 8
while (remainder_length) >= 6 do
encoded_size = encoded_size + 1
B64[encoded_size] = bytetoB64[bit.band(remainder, 63)]
remainder = bit.rshift(remainder, 6)
remainder_length = remainder_length - 6
end
end
if remainder_length > 0 then
encoded_size = encoded_size + 1
B64[encoded_size] = bytetoB64[remainder]
end
return table.concat(B64, "", 1, encoded_size)
end
local decodeB64Table = {}
function GSE.decodeB64(str)
local bit8 = decodeB64Table
local decoded_size = 0
local ch
local i = 1
local bitfield_len = 0
local bitfield = 0
local l = #str
while true do
if bitfield_len >= 8 then
decoded_size = decoded_size + 1
bit8[decoded_size] = string.char(bit.band(bitfield, 255))
bitfield = bit.rshift(bitfield, 8)
bitfield_len = bitfield_len - 8
end
ch = B64tobyte[str:sub(i, i)]
bitfield = bitfield + bit.lshift(ch or 0, bitfield_len)
bitfield_len = bitfield_len + 6
if i > l then
break
end
i = i + 1
end
return table.concat(bit8, "", 1, decoded_size)
end
-- This encodes a LUA Table for transmission
function GSE.EncodeMessage(tab)
local one = libS:Serialize(tab)
GSE.PrintDebugMessage("Compress Stage 1: " .. one, Statics.SourceTransmission)
local two = libC:Compress(one)
GSE.PrintDebugMessage("Compress Stage 2: " .. two, Statics.SourceTransmission)
local final = GSE.encodeB64(two)
GSE.PrintDebugMessage("Compress Stage Result: " .. final, Statics.SourceTransmission)
return final
end
-- This decodes a string into a LUA Table. This returns a bool (success) and an object that contains the results.
function GSE.DecodeMessage(data)
-- Decode the compressed data
local one = GSE.decodeB64(data)
-- Decompress the decoded data
local two, message = libC:Decompress(one)
if (not two) then
GSE.PrintDebugMessage("Error decompressing: " .. message, Statics.SourceTransmission)
return
end
-- Deserialize the decompressed data
local success, final = libS:Deserialize(two)
if (not success) then
GSE.PrintDebugMessage("Error deserializing " .. final, Statics.SourceTransmission)
return
end
GSE.PrintDebugMessage("Data Finalised", Statics.SourceTransmission)
return success, final
end
function GSE.TransmitSequence(key, channel, target)
local t = {}
t.Command = "GS-E_TRANSMITSEQUENCE"
local elements = GSE.split(key, ",")
local classid = tonumber(elements[1])
local SequenceName = elements[2]
GSE.PrintDebugMessage("Sending Seqence [" .. classid .. "][" .. SequenceName .. "]", Statics.SourceTransmission)
t.ClassID = classid
t.SequenceName = SequenceName
t.Sequence = GSE.Library[classid][SequenceName]
GSE.sendMessage(t, channel, target)
GSE.GUITransmissionFrame:SetStatusText(SequenceName .. L[" sent"])
end
function GSE.sendMessage(tab, channel, target, priority)
local _, instanceType = IsInInstance()
GSE.PrintDebugMessage(tab.Command, Statics.SourceTransmission)
if tab.Command == "GS-E_TRANSMITSEQUENCE" then
GSE.PrintDebugMessage(tab.SequenceName, Statics.SourceTransmission)
GSE.PrintDebugMessage(GSE.isEmpty(tab.Sequence))
GSE.PrintDebugMessage(GSE.ExportSequence(tab.Sequence, tab.SequenceName), Statics.SourceTransmission)
end
local transmission = GSE.EncodeMessage(tab)
GSE.PrintDebugMessage("Transmission: \n" .. transmission, Statics.SourceTransmission)
if GSE.isEmpty(channel) then
if IsInRaid() then
channel =
(not IsInRaid(LE_PARTY_CATEGORY_HOME) and IsInRaid(LE_PARTY_CATEGORY_INSTANCE)) and "INSTANCE_CHAT" or
"RAID"
else
channel =
(not IsInGroup(LE_PARTY_CATEGORY_HOME) and IsInGroup(LE_PARTY_CATEGORY_INSTANCE)) and "INSTANCE_CHAT" or
"PARTY"
end
end
if target and not UnitIsSameServer(target) then
if UnitInRaid(target) then
channel = "RAID"
transmission = ("§§%s:%s"):format(target, transmission)
elseif UnitInParty(target) then
channel = "PARTY"
transmission = ("§§%s:%s"):format(target, transmission)
end
end
GSE:SendCommMessage(Statics.CommPrefix, transmission, channel, target)
end
function GSE.performVersionCheck(version)
if string.match(GSE.VersionString, "development") then
local developer = true
GSE.old = false
else
if GSE.ParseVersion(version) ~= nil and GSE.ParseVersion(version) > GSE.VersionNumber then
if not GSE.old then
GSE.Print(
L[
"GSE is out of date. You can download the newest version from https://www.curseforge.com/wow/addons/gse-gnome-sequencer-enhanced-advanced-macros."
],
Statics.SourceTransmission
)
GSE.old = true
if (GSE.ParseVersion(version) - GSE.VersionNumber >= 5) then
StaticPopup_Show("GSE_UPDATE_AVAILABLE")
end
end
end
end
end
function GSE.SendSequence(ClassID, SequenceName, recipient, channel)
if GSE.isEmpty(channel) then
channel = "WHISPER"
end
local key = ClassID .. "," .. SequenceName
GSE.TransmitSequence(key, channel, recipient)
end
function GSE.SendSequenceMeta(ClassID, SequenceName, gseuser, channel)
if GSE.isEmpty(channel) then
channel = "WHISPER"
end
local t = {}
t.Command = "GSE_SEQUENCEMETA"
t.ClassID = ClassID
t.SequenceName = SequenceName
t.LastUpdated = GSE.Library[ClassID][SequenceName].MetaData.LastUpdated
t.Help = GSE.Library[ClassID][SequenceName].MetaData.Help
GSE.sendMessage(t, channel, gseuser)
end
function GSE.SendSpellCache(channel)
local t = {}
t.Command = "GSE_SPELLCACHE"
t.cache = GSESpellCache
GSE.sendMessage(t, channel)
end
function GSE.RequestSequence(ClassID, SequenceName, gseuser, channel)
if GSE.isEmpty(channel) then
channel = "WHISPER"
end
local t = {}
t.Command = "GSE_REQUESTSEQUENCE"
t.ClassID = ClassID
t.SequenceName = SequenceName
GSE.sendMessage(t, channel, gseuser)
end
function GSE.RequestSequenceMeta(ClassID, SequenceName, gseuser, channel)
if GSE.isEmpty(channel) then
channel = "WHISPER"
end
local t = {}
t.Command = "GSE_REQUESTSEQUENCEMETA"
t.ClassID = ClassID
t.SequenceName = SequenceName
GSE.sendMessage(t, channel, gseuser)
end
function GSE.ReceiveSequence(classid, SequenceName, Sequence, sender)
GSE.AddSequenceToCollection(SequenceName, Sequence, classid)
GSE.Print(L["Received Sequence "] .. SequenceName .. L[" from "] .. sender)
end
function GSE.storeSender(sender, senderversion)
if GSE.isEmpty(GSE.UnsavedOptions["PartyUsers"]) then
GSE.UnsavedOptions["PartyUsers"] = {}
end
GSE.UnsavedOptions["PartyUsers"][sender] = senderversion
end
function GSE.sendVersionCheck()
local _, instanceType = IsInInstance()
local t = {}
t.Command = "GS-E_VERSIONCHK"
t.Version = GSE.VersionString
GSE.sendMessage(t)
end
function GSE.ListSequences(recipient, channel)
if GSE.isEmpty(channel) then
channel = "WHISPER"
end
local sequenceTable = GSE.GetSequenceSummary()
local t = {}
t.Command = "GSE_SEQUENCELIST"
t.SequenceTable = sequenceTable
GSE.sendMessage(t, channel, recipient)
end
function GSE.RequestSequenceList(gseuser, channel)
if GSE.isEmpty(channel) then
channel = "WHISPER"
end
local t = {}
t.Command = "GSE_LISTSEQUENCES"
GSE.sendMessage(t, channel, gseuser)
end
function GSE:OnCommReceived(prefix, message, channel, sender)
GSE.PrintDebugMessage("GSE:onCommReceived", Statics.SourceTransmission)
GSE.PrintDebugMessage(prefix .. " " .. message .. " " .. channel .. " " .. sender, Statics.SourceTransmission)
if channel == "PARTY" or channel == "RAID" then
local dest, msg = string.match(message, "^§§([^:]+):(.+)$")
if dest then
local dName, dServer = string.match(dest, "^(.*)-(.*)$")
local myName, myServer = UnitName("player")
if myName == dName and myServer == dServer then
message = msg
end
end
end
local success, t = GSE.DecodeMessage(message)
if success then
if t.Command == "GS-E_VERSIONCHK" then
if not GSE.old then
GSE.performVersionCheck(t.Version)
end
GSE.storeSender(sender, t.Version)
elseif t.Command == "GS-E_TRANSMITSEQUENCE" then
if sender ~= GetUnitName("player", true) then
GSE.ReceiveSequence(t.ClassID, t.SequenceName, t.Sequence, sender)
else
GSE.PrintDebugMessage("Ignoring Sequence from me.", Statics.SourceTransmission)
GSE.PrintDebugMessage(
GSE.ExportSequence(t.Sequence, t.SequenceName, false, "ID", false),
Statics.SourceTransmission
)
end
elseif t.Command == "GSE_LISTSEQUENCES" then
if sender ~= GetUnitName("player", true) then
GSE.ListSequences(sender, "WHISPER")
else
GSE.PrintDebugMessage("Ignoring List Request from me.", Statics.SourceTransmission)
end
elseif t.Command == "GSE_SEQUENCELIST" then
if sender ~= GetUnitName("player", true) then
GSE.ShowSequenceList(t.SequenceTable, sender, channel)
else
GSE.PrintDebugMessage("Ignoring SequenceList from me.", Statics.SourceTransmission)
end
elseif t.Command == "GSE_REQUESTSEQUENCE" then
if sender ~= GetUnitName("player", true) then
if not GSE.isEmpty(GSE3Storage[tonumber(t.ClassID)][t.SequenceName]) then
GSE.SendSequence(tonumber(t.ClassID),t.SequenceName, sender, "WHISPER")
end
else
GSE.PrintDebugMessage("Ignoring RequestSequence from me.", Statics.SourceTransmission)
end
elseif t.Command == "GSE_REQUESTSEQUENCEMETA" then
if sender ~= GetUnitName("player", true) then
if not GSE.isEmpty(GSE3Storage[t.ClassID][t.SequenceName]) then
GSE.SendSequenceMeta(t.ClassID, t.SequenceName, sender, "WHISPER")
end
else
GSE.PrintDebugMessage("Ignoring SequenceMeta from me.", Statics.SourceTransmission)
end
elseif t.Command == "GSE_SEQUENCEMETA" then
if sender ~= GetUnitName("player", true) then
if not GSE.isEmpty(GSE3Storage[t.ClassID][t.SequenceName]) then
local sequence = GSE.Library[t.ClassID][t.SequenceName]
if sequence.MetaData.LastUpdated ~= t.LastUpdated then
GSE.RequestSequence(t.ClassID, t.SequenceName, sender, "WHISPER")
end
end
else
GSE.PrintDebugMessage("Ignoring SequenceMeta data from me.", Statics.SourceTransmission)
end
elseif t.Command == "GSE_SPELLCACHE" then
if sender ~= GetUnitName("player", true) then
if GSE.isEmpty(GSESpellCache) then
GSESpellCache = {
["enUS"] = {}
}
end
if not GSE.isEmpty(t.cache) and table.getn(t.cache) > 0 then
for locale, spells in pairs(t.cache) do
GSE.PrintDebugMessage("processing Locale" .. locale, Statics.SourceTransmission)
for k, v in pairs(spells) do
GSE.PrintDebugMessage("processing spell" .. k, Statics.SourceTransmission)
if GSE.isEmpty(GSESpellCache[locale]) then
GSESpellCache[locale] = {}
end
if GSE.isEmpty(GSESpellCache[locale][k]) then
GSE.PrintDebugMessage("Added spell" .. k .. " " .. v, Statics.SourceTransmission)
GSESpellCache[locale][k] = v
end
end
end
end
end
end
end
end
function GSE.SequenceChatPattern(sequenceName, classID)
local playerName = UnitName("player")
return "[GSE: " .. playerName .. " - " .. sequenceName .. " - " .. classID .. "]"
end
function GSE.CreateSequenceLink(sequenceName, classID, playerName)
if GSE.isEmpty(playerName) then
playerName = UnitName("player")
end
local message = "GSE Sequence: " .. sequenceName .. "' (" .. GSE.GetClassName(classID) .. ")"
local command = "seq@" .. sequenceName .. "@" .. playerName .. "@" .. classID
local link = "|cFFFFFF00|Hgarrmission:GSE:" .. command .. "|h[" .. message .. "]|h|r"
return link
end
-- This filter function courtesy of WeakAuras -- https://github.com/WeakAuras/WeakAuras2/blob/main/WeakAuras/Transmission.lua#L147
local function filterFunc(_, event, msg, player, l, cs, t, flag, channelId, ...)
if flag == "GM" or flag == "DEV" or (event == "CHAT_MSG_CHANNEL" and type(channelId) == "number" and channelId > 0) then
return
end
local newMsg = ""
local remaining = msg
local done
repeat
local start, finish, characterName, sequenceName, classID =
remaining:find("%[GSE: ([^%s]+) %- ([^%s]+) %- ([^]]+)")
if (characterName and sequenceName and classID) then
characterName = characterName:gsub("|c[Ff][Ff]......", ""):gsub("|r", "")
sequenceName = sequenceName:gsub("|c[Ff][Ff]......", ""):gsub("|r", "")
classID = classID:gsub("|c[Ff][Ff]......", ""):gsub("|r", "")
newMsg = newMsg .. remaining:sub(1, start - 1)
newMsg = newMsg .. GSE.CreateSequenceLink(sequenceName, classID, characterName)
remaining = remaining:sub(finish + 1)
else
done = true
end
until (done)
if newMsg ~= "" then
local trimmedPlayer = Ambiguate(player, "none")
if event == "CHAT_MSG_WHISPER" and not UnitInRaid(trimmedPlayer) and not UnitInParty(trimmedPlayer) then -- XXX: Need a guild check
local _, num = BNGetNumFriends()
for i = 1, num do
if C_BattleNet then -- introduced in 8.2.5 PTR
local toon = C_BattleNet.GetFriendNumGameAccounts(i)
for j = 1, toon do
local gameAccountInfo = C_BattleNet.GetFriendGameAccountInfo(i, j)
if gameAccountInfo.characterName == trimmedPlayer and gameAccountInfo.clientProgram == "WoW" then
return false, newMsg, player, l, cs, t, flag, channelId, ... -- Player is a real id friend, allow it
end
end
else -- keep old method for 8.2 and Classic
local toon = BNGetNumFriendGameAccounts(i)
for j = 1, toon do
local _, rName, rGame = BNGetFriendGameAccountInfo(i, j)
if rName == trimmedPlayer and rGame == "WoW" then
return false, newMsg, player, l, cs, t, flag, channelId, ... -- Player is a real id friend, allow it
end
end
end
end
return true -- Filter strangers
else
return false, newMsg, player, l, cs, t, flag, channelId, ...
end
end
end
ChatFrame_AddMessageEventFilter("CHAT_MSG_CHANNEL", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_YELL", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_GUILD", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_OFFICER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY_LEADER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID_LEADER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_SAY", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER_INFORM", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_BN_WHISPER", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_BN_WHISPER_INFORM", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_INSTANCE_CHAT", filterFunc)
ChatFrame_AddMessageEventFilter("CHAT_MSG_INSTANCE_CHAT_LEADER", filterFunc)
-- process chatlinks
hooksecurefunc("SetItemRef", function(link)
local linkType, addon, param1 = strsplit(":", link)
if linkType == "garrmission" and addon == "GSE" then
if param1 == "foo" then
print("Processed test link foo")
else
local cmd, sequenceName, player, ClassID = strsplit("@", param1)
if cmd == "seq" then
if player == UnitName("player") then
GSE.GUILoadEditor(ClassID .. "," .. sequenceName, GSE.GUIViewFrame)
else
GSE.Print("Requested " .. sequenceName .. " from " .. player, Statics.SourceTransmission)
GSE.RequestSequence(ClassID, sequenceName, player, "WHISPER")
end
end
end
end
end
)
GSE:RegisterComm("GSE")
|
print("-- test "..os.date())
|
--copy
local m=14400002
local cm=_G["c"..m]
xpcall(function() require("expansions/script/c37564765") end,function() require("script/c37564765") end)
function cm.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--CopyEffect
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(37564765,7))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_CHAINING)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(cm.InstantCopyCondition(excon))
e2:SetOperation(cm.op)
c:RegisterEffect(e2)
end
function cm.op(e,tp,eg,ep,ev,re,r,rp)
local rtype=bit.band(re:GetActiveType(),0x7)
local g=Group.CreateGroup()
Duel.ChangeTargetCard(ev,g)
Duel.ChangeChainOperation(ev,cm.repop)
end
function cm.repop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetLabel(1-tp)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetCondition(cm.con)
e1:SetCost(cm.ForbiddenCost(cost))
e1:SetTarget(cm.InstantCopyTarget)
e1:SetOperation(cm.CopyOperation)
Duel.RegisterEffect(e1,tp)
end
function cm.con(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==1-tp
end
function cm.InstantCopyCondition(excon)
return function(e,tp,eg,ep,ev,re,r,rp)
return rp~=tp and (not excon or excon(e,tp,eg,ep,ev,re,r,rp))
end
end
function cm.InstantCopyTarget(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then
local te=e:GetLabelObject()
local tg=te:GetTarget()
return te:IsHasProperty(EFFECT_FLAG_CARD_TARGET) and cm.ProtectedRun(tg,e,tp,eg,ep,ev,re,r,rp,0,chkc)
end
local te=re:Clone()
local tg=te:GetTarget()
local code=te:GetCode()
local tres,teg,tep,tev,tre,tr,trp
if code>0 and code~=EVENT_FREE_CHAIN and code~=EVENT_CHAINING and Duel.CheckEvent(code) then
tres,teg,tep,tev,tre,tr,trp=Duel.CheckEvent(code,true)
end
if chk==0 then
if e:GetLabel()==0 then return false end
e:SetLabel(0)
local res=false
if not tg then return true end
if tres then return cm.ProtectedRun(tg,e,tp,teg,tep,tev,tre,tr,trp,0)
else return cm.ProtectedRun(tg,e,tp,eg,ep,ev,re,r,rp,0) end
end
e:SetLabel(te:GetLabel())
e:SetCategory(te:GetCategory())
e:SetProperty(te:GetProperty())
if tg then
if tres then
cm.ProtectedRun(tg,e,tp,teg,tep,tev,tre,tr,trp,1)
else
cm.ProtectedRun(tg,e,tp,eg,ep,ev,re,r,rp,1)
end
end
te:SetLabelObject(e:GetLabelObject())
e:SetLabelObject(te)
local ex=Effect.GlobalEffect()
ex:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ex:SetCode(EVENT_CHAIN_END)
ex:SetLabelObject(e)
ex:SetOperation(function(e)
e:GetLabelObject():SetLabel(0)
ex:Reset()
end)
Duel.RegisterEffect(ex,tp)
end
function cm.ProtectedRun(f,...)
if not f then return true end
local params={...}
local ret={}
local res_test=pcall(function()
ret={f(table.unpack(params))}
end)
if not res_test then return false end
return table.unpack(ret)
end
function cm.ForbiddenCost(costf)
return function(e,tp,eg,ep,ev,re,r,rp,chk)
e:SetLabel(1)
if not costf then return true end
return costf(e,tp,eg,ep,ev,re,r,rp,chk)
end
end
function cm.CopySpellNormalFilter(c,f,e,tp)
return (c:GetType()==TYPE_SPELL or c:GetType()==TYPE_SPELL+TYPE_QUICKPLAY
or c:GetType()==TYPE_TRAP or c:GetType()==TYPE_TRAP+TYPE_COUNTER)
and c:IsAbleToRemoveAsCost() and c:CheckActivateEffect(true,true,false) and (not f or f(c,e,tp))
end
function cm.CopySpellNormalTarget(loc1,loc2,f,x)
return function(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then
local te=e:GetLabelObject()
local tg=te:GetTarget()
return te:IsHasProperty(EFFECT_FLAG_CARD_TARGET) and cm.ProtectedRun(tg,e,tp,eg,ep,ev,re,r,rp,0,chkc)
end
local og=Duel.GetFieldGroup(tp,loc1,loc2)
if x then og:Merge(e:GetHandler():GetOverlayGroup()) end
if chk==0 then
if e:GetLabel()==0 then return false end
e:SetLabel(0)
return og:IsExists(cm.CopySpellNormalFilter,1,nil,f,e,tp)
end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=og:FilterSelect(tp,cm.CopySpellNormalFilter,1,1,nil,f,e,tp)
local te,ceg,cep,cev,cre,cr,crp=g:GetFirst():CheckActivateEffect(true,true,true)
Duel.Remove(g,POS_FACEUP,REASON_COST)
e:SetCategory(te:GetCategory())
e:SetProperty(te:GetProperty())
e:SetLabel(te:GetLabel())
local tg=te:GetTarget()
if tg then tg(e,tp,ceg,cep,cev,cre,cr,crp,1) end
te:SetLabelObject(e:GetLabelObject())
e:SetLabelObject(te)
local ex=Effect.GlobalEffect()
ex:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ex:SetCode(EVENT_CHAIN_END)
ex:SetLabelObject(e)
ex:SetOperation(function(e)
e:GetLabelObject():SetLabel(0)
ex:Reset()
end)
Duel.RegisterEffect(ex,tp)
end
end
function cm.CopyOperation(e,tp,eg,ep,ev,re,r,rp)
local te=e:GetLabelObject()
if not te then return end
e:SetLabelObject(te:GetLabelObject())
local op=te:GetOperation()
if te:IsHasType(EFFECT_TYPE_ACTIVATE) then
e:GetHandler():ReleaseEffectRelation(e)
end
cm.ProtectedRun(op,e,tp,eg,ep,ev,re,r,rp)
end
function cm.CopySpellChainingFilter(c,e,tp,eg,ep,ev,re,r,rp,f)
if (c:GetType()==TYPE_SPELL or c:GetType()==TYPE_SPELL+TYPE_QUICKPLAY
or c:GetType()==TYPE_TRAP or c:GetType()==TYPE_TRAP+TYPE_COUNTER) and c:IsAbleToRemoveAsCost() and (not f or f(c,e,tp,eg,ep,ev,re,r,rp)) then
if c:CheckActivateEffect(true,true,false) then return true end
local te=c:GetActivateEffect()
if te:GetCode()~=EVENT_CHAINING then return false end
local tg=te:GetTarget()
if not cm.ProtectedRun(tg,e,tp,eg,ep,ev,re,r,rp,0) then return false end
return true
else return false end
end
function cm.CopySpellChainingTarget(loc1,loc2,f,x)
return function(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then
local te=e:GetLabelObject()
local tg=te:GetTarget()
return te:IsHasProperty(EFFECT_FLAG_CARD_TARGET) and (not tg or tg(e,tp,eg,ep,ev,re,r,rp,0,chkc))
end
local og=Duel.GetFieldGroup(tp,loc1,loc2)
if x then og:Merge(e:GetHandler():GetOverlayGroup()) end
if chk==0 then
if e:GetLabel()==0 then return false end
e:SetLabel(0)
return og:IsExists(cm.CopySpellChainingFilter,1,nil,e,tp,eg,ep,ev,re,r,rp,f)
end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=og:FilterSelect(tp,cm.CopySpellChainingFilter,1,1,nil,e,tp,eg,ep,ev,re,r,rp,f)
local tc=g:GetFirst()
local te,ceg,cep,cev,cre,cr,crp
local fchain=cm.CopySpellNormalFilter(tc)
if fchain then
te,ceg,cep,cev,cre,cr,crp=tc:CheckActivateEffect(true,true,true)
else
te=tc:GetActivateEffect()
end
Duel.Remove(g,POS_FACEUP,REASON_COST)
e:SetLabel(te:GetLabel())
e:SetCategory(te:GetCategory())
e:SetProperty(te:GetProperty())
local tg=te:GetTarget()
if tg then
if fchain then
cm.ProtectedRun(tg,e,tp,ceg,cep,cev,cre,cr,crp,1)
else
cm.ProtectedRun(tg,e,tp,eg,ep,ev,re,r,rp,1)
end
end
te:SetLabelObject(e:GetLabelObject())
e:SetLabelObject(te)
local ex=Effect.GlobalEffect()
ex:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ex:SetCode(EVENT_CHAIN_END)
ex:SetLabelObject(e)
ex:SetOperation(function(e)
e:GetLabelObject():SetLabel(0)
ex:Reset()
end)
Duel.RegisterEffect(ex,tp)
end
end
function cm.CopySpellModule(c,loc1,loc2,f,con,cost,ctlm,ctlmid,eloc,x)
local e2=Effect.CreateEffect(c)
eloc=eloc or LOCATION_MZONE
ctlmid=ctlmid or 1
e2:SetDescription(aux.Stringid(37564765,6))
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetRange(eloc)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetHintTiming(0x3c0)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
if ctlm then e2:SetCountLimit(ctlm,ctlmid) end
e2:SetCondition(function(e,tp,eg,ep,ev,re,r,rp)
return not Duel.CheckEvent(EVENT_CHAINING) and (not con or con(e,tp,eg,ep,ev,re,r,rp))
end)
e2:SetCost(cm.ForbiddenCost(cost))
e2:SetTarget(cm.CopySpellNormalTarget(loc1,loc2,f,x))
e2:SetOperation(cm.CopyOperation)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(37564765,6))
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_CHAINING)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
if ctlm then e3:SetCountLimit(ctlm,ctlmid) end
e3:SetCost(cm.ForbiddenCost(cost))
e3:SetCondition(function(e,tp,eg,ep,ev,re,r,rp)
return not con or con(e,tp,eg,ep,ev,re,r,rp)
end)
e3:SetTarget(cm.CopySpellChainingTarget(loc1,loc2,f,x))
e3:SetOperation(cm.CopyOperation)
c:RegisterEffect(e3)
return e2,e3
end
|
--https://devforum.roblox.com/t/a-guide-to-a-better-looking-and-more-realistic-day-night-cycle/392643
--time changer
local mam --minutes after midnight
local timeShift = 1 --how many minutes you shift every "tick"
local waitTime = 15/30 --length of the tick
local pi = math.pi
--brightness
local amplitudeB = 1
local offsetB = 2
--outdoor ambieant
local var
local amplitudeO = 20
local offsetO = 100
--shadow softness
local amplitudeS = .2
local offsetS = .8
--color shift top
local pointer
-- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
local rColorList = {000,000,000,000,000,255,255,255,255,255,255,255,255,255,255,255,255,255,255,000,000,000,000,000}
local gColorList = {165,165,165,165,165,255,215,230,255,255,255,255,255,255,255,245,230,215,255,165,165,165,165,165}
local bColorList = {255,255,255,255,255,255,110,135,255,255,255,255,255,255,255,215,135,110,255,255,255,255,255,255}
local r
local g
local b
if game.ServerStorage:FindFirstChild("disableNightCycle") == nil then
while true do
--time changer
mam = game.Lighting:GetMinutesAfterMidnight() + timeShift
game.Lighting:SetMinutesAfterMidnight(mam)
mam = mam/60
--brightness
game.Lighting.Brightness = amplitudeB*math.cos(mam*(pi/12)+pi)+offsetB
--outdoor ambient
var=amplitudeO*math.cos(mam*(pi/12)+pi)+offsetO
game.Lighting.OutdoorAmbient = Color3.fromRGB(var,var,var)
--shadow softness
game.Lighting.ShadowSoftness = amplitudeS*math.cos(mam*(pi/6))+offsetS
--color shift top
pointer= math.clamp(math.ceil(mam), 1, 24)
r=((rColorList[pointer%24+1]-rColorList[pointer])*(mam-pointer+1))+rColorList[pointer]
g=((gColorList[pointer%24+1]-gColorList[pointer])*(mam-pointer+1))+gColorList[pointer]
b=((bColorList[pointer%24+1]-bColorList[pointer])*(mam-pointer+1))+bColorList[pointer]
game.Lighting.ColorShift_Top=Color3.fromRGB(r,g,b)
--tick
wait(waitTime)
end
end
|
-- The Shell of the Missile, this is just the body of the missile
-- Individual warheads have to be attached
minetest.register_craftitem("yatm_armoury_icbm:icbm_shell", {
description = "ICBM Shell",
groups = {
icbm_shell = 1,
},
inventory_image = "yatm_icbm_shell.png",
})
|
local EventBus = require("eventbus")
local vatsimbriefHelperStub = {
frequencyToAtcInfosMap = {}
}
vatsimbriefHelperStub.frequencyToAtcInfosMap["129.200"] = {
{id = "TPA_GND", description = "Just testing"},
{id = "SEA_GND", description = "Online until appx 2300z / How am I doing?"},
{id = "CYVR_GND", description = "Vancouver Ground^§Charts at www.fltplan.com^§Info at czvr.vatcan.ca"}
}
vatsimbriefHelperStub.ownCallSign = "THATSME"
vatsimbriefHelperStub.defaultTestVatsimClients = {
{
type = "Plane",
callSign = vatsimbriefHelperStub.ownCallSign,
vatsimClientId = "23895389539",
latitude = "6.1708",
longitude = "-75.4276",
altitude = "39000.0",
heading = "270.0",
groundSpeed = "450",
currentDistance = 0.0
},
{
type = "Plane",
callSign = "DLH53N",
vatsimClientId = "3252352323",
latitude = "8.0",
longitude = "-76.0",
altitude = "24000.0",
heading = "183.0",
groundSpeed = "409",
currentDistance = 10.0
},
{
type = "Plane",
callSign = "DLH62X",
vatsimClientId = "215476763534",
latitude = "7.0",
longitude = "-76.0",
altitude = "13000.0",
heading = "51.0",
groundSpeed = "220",
currentDistance = 20.0
},
{
type = "Plane",
callSign = "DLH57D",
vatsimClientId = "884848237",
latitude = "10.0",
longitude = "-73.0",
altitude = "23000.0",
heading = "355.0",
groundSpeed = "320",
currentDistance = 30.0
},
{
type = "Station",
id = "SKRG_APP",
vatsimClientId = "341212145",
latitude = "5.0",
longitude = "-75.0",
frequency = "118.000",
currentDistance = 40.0
}
}
vatsimbriefHelperStub.testVatsimClients = defaultTestVatsimClients
local hiddenInterface = {
getInterfaceVersion = function()
return 2
end,
getAtcStationsForFrequencyClosestFirst = function(fullFrequencyString)
return vatsimbriefHelperStub.frequencyToAtcInfosMap[fullFrequencyString]
end,
getOwnCallSign = function()
return vatsimbriefHelperStub.ownCallSign
end,
getAllVatsimClientsClosestFirstWithTimestamp = function()
return vatsimbriefHelperStub.testVatsimClients, 0
end
}
VatsimbriefHelperEventOnVatsimDataRefreshed = "EventBus_EventName_VatsimbriefHelperEventOnVatsimDataRefreshed "
function vatsimbriefHelperStub:activateInterface()
VatsimbriefHelperPublicInterface = hiddenInterface
VatsimbriefHelperEventBus = EventBus.new()
end
function vatsimbriefHelperStub:deactivateInterface()
VatsimbriefHelperPublicInterface = nil
VatsimbriefHelperEventBus = nil
end
function vatsimbriefHelperStub:emitVatsimDataRefreshEvent()
VatsimbriefHelperEventBus.emit(VatsimbriefHelperEventOnVatsimDataRefreshed)
end
function vatsimbriefHelperStub:overrideTestVatsimClients(newClients)
self.testVatsimClients = newClients
end
function vatsimbriefHelperStub:reset()
self.testVatsimClients = self.defaultTestVatsimClients
end
return vatsimbriefHelperStub
|
local audioEngine = require('audioEngine')
local colors = require('colors')
local cupcakeScreen = require('cupcakeScreen')
local introScreen = require('introScreen')
local particleEngine = require('particleEngine')
local proto = require('proto')
local rainbowStripes = require('rainbowStripes')
local rectangleEngine = require('rectangleEngine')
local resolutionEngine = require('resolutionEngine')
local textEngine = require('textEngine')
local ui = require('ui')
local vectors = require('vectors')
local unscaleF = resolutionEngine.unscaleFloat
local scaleF = resolutionEngine.scaleFloat
local vec2 = vectors.vec2
local vec3 = vectors.vec3
local rainbowGradient = particleEngine.linearGradientParticle:extend({
origin = vec3(unpack(colors.rainbow[6])),
intermediate = {
vec3(unpack(colors.rainbow[1])),
vec3(unpack(colors.rainbow[2])),
vec3(unpack(colors.rainbow[3])),
vec3(unpack(colors.rainbow[4])),
vec3(unpack(colors.rainbow[5])),
},
target = vec3(unpack(colors.rainbow[6])),
duration = 40000,
next = function (self)
particleEngine.add(self)
end,
})
local titleText = proto.object:extend({
top = nil,
left = nil,
width = nil,
height = nil,
text = 'Ultra Rainbow Bake Sale',
font = 'title',
textObject = nil,
refresh = function (self)
local width, height = resolutionEngine.getUnscaledDimensions()
self.textObject = textEngine.getTextObject(self.font, self.text)
self.width = unscaleF(self.textObject:getWidth())
self.height = unscaleF(self.textObject:getHeight())
self.left = width / 2 - self.width / 2
self.top = height / 2 - self.height / 2
end,
paint = function (self)
textEngine.paintTextObject(
rainbowGradient:getColor(),
self.textObject,
self.left,
self.top)
end,
})
local titleTextBox = proto.object:extend({
top = nil,
left = nil,
width = nil,
height = nil,
margin = { -30, 30 },
refresh = function (self)
self.left = titleText.left - self.margin[1]
self.top = titleText.top - self.margin[2]
self.width = titleText.width + self.margin[1] * 2
self.height = titleText.height + self.margin[2] * 2
end,
paint = function (self)
rectangleEngine.paintRounded(
colors.inverseText,
self.left,
self.top,
self.width,
self.height)
end,
})
local titleShine = particleEngine.shineParticle:extend({
origin = vec2(-200, 0),
target = vec2(-199, 0),
width = 20,
height = 100,
color = { 255, 255, 255, 208 },
rotation = math.pi / 8,
duration = 300,
refresh = function (self)
local y = titleText.top + titleText.height / 2
self.origin = vec2(titleText.left, y)
self.target = vec2(titleText.left + titleText.width, y)
end,
})
local titleShineDelay = particleEngine.delayParticle:extend({
duration = 10000,
next = function (self)
particleEngine.add(self.proto:extend())
particleEngine.add(titleShine:extend())
end,
})
local cupcakeShadow = {
foil = { 255, 255, 255 },
foilHighlight = { 255, 255, 255 },
cake = { 255, 255, 255 },
icing = { 255, 255, 255 },
icingHighlight = { 255, 255, 255 },
}
local flyingParticle = particleEngine.lineParticle:extend({
size = nil,
minSize = nil,
maxSize = nil,
easing = particleEngine.linear,
paint = function (self)
love.graphics.push()
love.graphics.scale(scaleF(1), scaleF(1))
love.graphics.translate(self.position.x, self.position.y)
love.graphics.scale(unscaleF(1), unscaleF(1))
love.graphics.scale(self.size, self.size)
love.graphics.rotate(math.pi / 8)
self:paintSprite()
love.graphics.pop()
end,
makeRandom = function (self)
local y = math.random(3000)
local origin = vec2(-100, y + 100)
local target = vec2(y, 0)
local size = math.random() * (self.maxSize - self.minSize) + self.minSize
local speed = (size + math.random() * 0.2) / 0.3 * 0.2
local duration = (target - origin):length() / speed
return self:extend({
origin = origin,
target = target,
duration = duration,
size = size,
})
end,
})
local cupcakeParticle = flyingParticle:extend({
minSize = 0.5,
maxSize = 0.8,
paintSprite = function (self)
cupcakeScreen.paintCupcake(cupcakeShadow, 0, 0)
end,
})
local cupcakeSpawnDelay = particleEngine.delayParticle:extend({
duration = 200,
next = function (self)
particleEngine.add(self.proto:extend())
particleEngine.add(cupcakeParticle:makeRandom())
end,
})
local starParticle = flyingParticle:extend({
minSize = 0.1,
maxSize = 0.5,
paintSprite = function (self)
cupcakeScreen.paintStar(cupcakeShadow.icing, 0, 0, 0)
end,
})
local starSpawnDelay = particleEngine.delayParticle:extend({
duration = 200,
next = function (self)
particleEngine.add(self.proto:extend())
particleEngine.add(starParticle:makeRandom())
end,
})
local screen = ui.screen:extend({
backgroundColor = colors.inverseText,
next = introScreen.screen,
update = function (self, time)
self:refresh()
particleEngine.update(time)
end,
refresh = function (self)
ui.cursor:clickable()
titleText:refresh()
titleTextBox:refresh()
titleShine:refresh()
end,
paint = function (self)
rainbowStripes.stripes:paint()
titleTextBox:paint()
titleText:paint()
particleEngine.paint()
end,
mousepressed = function (self, x, y, button, istouch)
audioEngine.startMusic()
self:showNext()
end,
start = function (self)
local seed = love.timer.getTime()
print(string.format('Seeding title with %f', seed))
math.randomseed(seed)
particleEngine.add(titleShineDelay:extend({
duration = 200,
}))
particleEngine.add(cupcakeSpawnDelay:extend({
duration = 200,
}))
particleEngine.add(starSpawnDelay:extend({
duration = 200,
}))
particleEngine.add(rainbowGradient)
end,
showNext = function (self, ...)
particleEngine.reset()
ui.screen.showNext(self, ...)
end,
})
return {
screen = screen,
}
|
local srp = require("wow/srp")
local _M = {}
local logon_proof = function(self, M)
self.M2 = srp.M2(self.A, self.M1, self.K)
local M2, M2_l = self.M2:get_digest()
local M, M_l = M:get_digest()
for i = 1, M2_l do
if M2:sub(i, i) ~= M:sub(i, i) then
return nil
end
end
return true
end
-- # auth_challenge
-- Create a new SRP table and process authentication challenge response.
--
-- > I [string] The account identifier (I).
-- > password [string] The plaintext password.
-- > s [string] The salt (s) as hex string.
-- > B [string] The host public ephemeral (B) as hex string.
-- > g [number] The generator (g).
-- > N [string] The prime (N) as hex string.
-- > k [number] The multiplier (k).
-- Optional - defaults to srp.k.
--
-- < [table] The SRP table otherwise nil on error.
function _M.auth_challenge(I, password, s, B, g, N, k)
local t = {}
t.logon_proof = logon_proof
t.k = srp.dec2bn(k or srp.k)
t.I = I
t.p = srp.p(I, password)
if not t.p then
return nil
end
t.s = srp.hex2bn(s)
t.B = srp.hex2bn(B)
t.g = srp.dec2bn(g)
t.N = srp.hex2bn(N)
t.x = srp.x(t.p, t.s)
if not t.x then
return nil
end
t.v = srp.v(t.x, t.g, t.N)
t.A, t.a = srp.A(t.g, t.N)
if not t.A then
return nil
end
t.u = srp.u(t.A, t.B, t.N)
if not t.u then
return nil
end
t.S = srp.S_user(t.a, t.B, t.u, t.x, t.g, t.N, t.k)
t.K = srp.K(t.S)
t.M1 = srp.M1(t.I, t.s, t.A, t.B, t.K, t.g, t.N)
return t
end
return _M
|
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
local enum = require("enum")
--
-- The entries are used to synchronize the state of services instances and the
-- Publish/-Subscribe handling.
-- See also: section 4.1.2.3 Entry Format (https://www.autosar.org/fileadmin/user_upload/standards/foundation/19-11/AUTOSAR_PRS_SOMEIPServiceDiscoveryProtocol.pdf
-- -)
SomeIpSdEntries = class.class(KaitaiStruct)
function SomeIpSdEntries:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function SomeIpSdEntries:_read()
self.entries = {}
local i = 0
while not self._io:is_eof() do
self.entries[i + 1] = SomeIpSdEntries.SdEntry(self._io, self, self._root)
i = i + 1
end
end
SomeIpSdEntries.SdEntry = class.class(KaitaiStruct)
SomeIpSdEntries.SdEntry.EntryTypes = enum.Enum {
find = 0,
offer = 1,
subscribe = 6,
subscribe_ack = 7,
}
function SomeIpSdEntries.SdEntry:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function SomeIpSdEntries.SdEntry:_read()
self.header = SomeIpSdEntries.SdEntry.SdEntryHeader(self._io, self, self._root)
local _on = self.header.type
if _on == SomeIpSdEntries.SdEntry.EntryTypes.find then
self.content = SomeIpSdEntries.SdEntry.SdServiceEntry(self._io, self, self._root)
elseif _on == SomeIpSdEntries.SdEntry.EntryTypes.offer then
self.content = SomeIpSdEntries.SdEntry.SdServiceEntry(self._io, self, self._root)
elseif _on == SomeIpSdEntries.SdEntry.EntryTypes.subscribe then
self.content = SomeIpSdEntries.SdEntry.SdEventgroupEntry(self._io, self, self._root)
elseif _on == SomeIpSdEntries.SdEntry.EntryTypes.subscribe_ack then
self.content = SomeIpSdEntries.SdEntry.SdEventgroupEntry(self._io, self, self._root)
end
end
SomeIpSdEntries.SdEntry.SdEntryHeader = class.class(KaitaiStruct)
function SomeIpSdEntries.SdEntry.SdEntryHeader:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function SomeIpSdEntries.SdEntry.SdEntryHeader:_read()
self.type = SomeIpSdEntries.SdEntry.EntryTypes(self._io:read_u1())
self.index_first_options = self._io:read_u1()
self.index_second_options = self._io:read_u1()
self.number_first_options = self._io:read_bits_int_be(4)
self.number_second_options = self._io:read_bits_int_be(4)
self._io:align_to_byte()
self.service_id = self._io:read_u2be()
self.instance_id = self._io:read_u2be()
self.major_version = self._io:read_u1()
self.ttl = self._io:read_bits_int_be(24)
end
SomeIpSdEntries.SdEntry.SdServiceEntry = class.class(KaitaiStruct)
function SomeIpSdEntries.SdEntry.SdServiceEntry:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function SomeIpSdEntries.SdEntry.SdServiceEntry:_read()
self.minor_version = self._io:read_u4be()
end
SomeIpSdEntries.SdEntry.SdEventgroupEntry = class.class(KaitaiStruct)
function SomeIpSdEntries.SdEntry.SdEventgroupEntry:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function SomeIpSdEntries.SdEntry.SdEventgroupEntry:_read()
self.reserved = self._io:read_u1()
self.initial_data_requested = self._io:read_bits_int_be(1)
self.reserved2 = self._io:read_bits_int_be(3)
self.counter = self._io:read_bits_int_be(4)
self._io:align_to_byte()
self.event_group_id = self._io:read_u2be()
end
|
testResultHandler = require('yunit.test_result_handlers').MsvcTextTestProgressHandler:new()
|
local language = "korean";
local PLUGIN = PLUGIN;
PLUGIN:AddPluginLanguage("plugin_pc_setrank", "%s 님이 %s 님의 랭크를 %s 로 설정하였습니다.", language);
PLUGIN:AddPluginLanguage("plugin_pc_spawn", "%s 님이 %s 님을 스폰 하였습니다.", language);
PLUGIN:AddPluginLanguage("plugin_pc_kick", "%s 님이 %s 님을 킥하였습니다.", language);
PLUGIN:AddPluginLanguage("plugin_pc_syntax_reason", "<사유>", language);
PLUGIN:AddPluginLanguage("plugin_pc_ban", "%s 님이 %s 님을 %s분 동안 밴하였습니다.", language);
|
if UseItem(124) == true then goto label0 end;
do return end;
::label0::
AddItem(124, -1);
Talk(0, "老前辈,我看这蜜蜂很难驯养哦!", "talkname0", 1);
Talk(64, "没什么的,再过一阵子我就会让这百花谷中到处都是蜜蜂飞舞.", "talkname64", 0);
Talk(0, "我这有罐玉蜂浆,你拿去试看看,会不会比较好用.", "talkname0", 1);
ModifyEvent(-2, -2, -2, -2, -2, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(-2, 2, -2, -2, -1, -1, 408, -2, -2, -2, -2, -2, -2);--by fanyu|启动408脚本。场景20-编号2
ModifyEvent(-2, 3, -2, -2, -1, -1, 408, -2, -2, -2, -2, -2, -2);--by fanyu|启动408脚本。场景20-编号3
do return end;
|
methods = {
'CanUpgrade',
'UpgradeRequire',
'Upgrade',
}
local ExpCost = { 200, 1000, 5000 }
local GoldCost = { 20, 100, 500 }
function CanUpgrade(follower)
if follower.CurLevel < 30 then return false end
if follower.MaxStar == follower.CurStar then return false end
if PlayerObject.Instance.Self.Exp < ExpCost[follower.CurStar + 1] then return false end
if PlayerObject.Instance.Self.Money < GoldCost[follower.CurStar + 1] then return false end
return true
end
function UpgradeRequire(follower)
pack = Package()
pack.Exp = ExpCost[follower.CurStar + 1]
pack.Money = GoldCost[follower.CurStar + 1]
return pack
end
function Upgrade(follower)
pack = UpgradeRequire(follower)
PlayerObject.Instance.Self.Exp = PlayerObject.Instance.Self.Exp - pack.Exp
PlayerObject.Instance.Self.Money = PlayerObject.Instance.Self.Money - pack.Money
follower.CurStar = follower.CurStar + 1
follower.CurLevel = follower.CurLevel - 30
return true
end
|
ccs = ccs or {}
---ArmatureDisplayData object
---@class ArmatureDisplayData : DisplayData
local ArmatureDisplayData = {}
ccs.ArmatureDisplayData = ArmatureDisplayData
--------------------------------
--
---@return ArmatureDisplayData
function ArmatureDisplayData:create() end
--------------------------------
---js ctor
---@return ArmatureDisplayData
function ArmatureDisplayData:ArmatureDisplayData() end
return ArmatureDisplayData
|
--[[ Mob -- Fel Crystal.lua
This script was written and is protected
by the GPL v2. This script was released
by BrantX of the Blua Scripting
Project. Please give proper accredidations
when re-releasing or sharing this script
with others in the emulation community.
~~End of License Agreement
-- BrantX, February 01, 2009. ]]
function FelCrystal_OnSpawn(Unit,Event)
Unit:StopMovement(1)
Unit:SetCombatMeleeCapable(1)
Unit:SetCombatCapable(1)
Unit:SetCombatTargetingCapable(1)
end
function FelCrystal_OnDied(Unit,Event)
Unit:RemoveEvents()
Unit:RegisterEvent("FelCrystal_RemoveFromWorld", 3500, 1)
end
function FelCrystal_RemoveFromWorld(Unit,Event)
Unit:RemoveFromWorld()
end
RegisterUnitEvent(24722,18,"FelCrystal_OnSpawn")
RegisterUnitEvent(24722,4,"FelCrystal_OnDied")
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_enigma_midnight_pulse_lua_thinker = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_enigma_midnight_pulse_lua_thinker:IsHidden()
return true
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_enigma_midnight_pulse_lua_thinker:OnCreated( kv )
-- references
self.radius = self:GetAbility():GetSpecialValueFor( "radius" )
self.damage = self:GetAbility():GetSpecialValueFor( "damage_percent" )
local interval = 1
if IsServer() then
-- destroy trees
GridNav:DestroyTreesAroundPoint( self:GetParent():GetOrigin(), self.radius, true )
-- precache damage
self.damageTable = {
-- victim = target,
attacker = self:GetCaster(),
-- damage = 500,
damage_type = self:GetAbility():GetAbilityDamageType(),
ability = self:GetAbility(), --Optional.
}
-- Start interval
self:StartIntervalThink( interval )
-- self:OnIntervalThink()
-- play effects
self:PlayEffects()
end
end
function modifier_enigma_midnight_pulse_lua_thinker:OnDestroy()
if IsServer() then
-- stop sound
-- StopSoundOn( self.sound_cast, self:GetParent() )
-- kill thinker
UTIL_Remove( self:GetParent() )
end
end
--------------------------------------------------------------------------------
-- Interval Effects
function modifier_enigma_midnight_pulse_lua_thinker:OnIntervalThink()
-- find units in radius
local enemies = FindUnitsInRadius(
self:GetCaster():GetTeamNumber(), -- int, your team number
self:GetParent():GetOrigin(), -- point, center point
nil, -- handle, cacheUnit. (not known)
self.radius, -- float, radius. or use FIND_UNITS_EVERYWHERE
DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter
DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- int, type filter
DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, -- int, flag filter
0, -- int, order filter
false -- bool, can grow cache
)
for _,enemy in pairs(enemies) do
-- apply damage
self.damageTable.victim = enemy
self.damageTable.damage = enemy:GetMaxHealth()*self.damage/100
ApplyDamage( self.damageTable )
end
end
--------------------------------------------------------------------------------
-- Graphics & Animations
function modifier_enigma_midnight_pulse_lua_thinker:PlayEffects()
-- Get Resources
local particle_cast = "particles/units/heroes/hero_enigma/enigma_midnight_pulse.vpcf"
self.sound_cast = "Hero_Enigma.Midnight_Pulse"
-- Create Particle
local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_WORLDORIGIN, nil )
ParticleManager:SetParticleControl( effect_cast, 0, self:GetParent():GetOrigin() )
ParticleManager:SetParticleControl( effect_cast, 1, Vector( self.radius, 0, 0 ) )
-- ParticleManager:ReleaseParticleIndex( effect_cast )
-- buff particle
self:AddParticle(
effect_cast,
false, -- bDestroyImmediately
false, -- bStatusEffect
-1, -- iPriority
false, -- bHeroEffect
false -- bOverheadEffect
)
-- Create Sound
EmitSoundOn( self.sound_cast, self:GetParent() )
end
|
-- language specific higlights
local lush = require("lush")
local base = require("apprentice.base")
local M = {}
M = lush(function()
return {
moonSpecialOp {base.ApprenticeFg3},
moonExtendedOp {base.ApprenticeFg3},
moonFunction {base.ApprenticeFg3},
moonObject {base.ApprenticeYellow},
}
end)
return M
|
local item = {
id = 3,
title = "Big potion",
type = "potion",
health = 100,
mana = 100
}
function item:use(character)
character.health = character.health + item.health
if character.health > character:getMaxHealth() then
character.health = character:getMaxHealth()
end
character.mana = character.mana + item.mana
if character.mana > character:getMaxMana() then
character.mana = character:getMaxMana()
end
end
return item
|
Locales['pl'] = {
-- Inventory
['inventory'] = 'ekwipunek %s / %s',
['use'] = 'użyj',
['give'] = 'daj',
['remove'] = 'usuń',
['return'] = 'wróć',
['give_to'] = 'daj dla',
['amount'] = 'ilość',
['giveammo'] = 'daj amunicje',
['amountammo'] = 'ilość amunicji',
['noammo'] = 'nie posiadasz wystarczającej ilości amunicji!',
['gave_item'] = 'dajesz ~y~%sx~s~ ~b~%s~s~ dla ~y~%s~s~',
['received_item'] = 'otrzymujesz ~y~%sx~s~ ~b~%s~s~ od ~b~%s~s~',
['gave_weapon'] = 'dajesz ~b~%s~s~ dla ~y~%s~s~',
['gave_weapon_ammo'] = 'dałeś/aś ~o~%sx %s~s~ do ~b~%s~s~ dla ~y~%s~s~',
['gave_weapon_withammo'] = 'dałeś/aś ~b~%s~s~ z ~o~%sx %s~s~ dla ~y~%s~s~',
['gave_weapon_hasalready'] = '~y~%s~s~ już posiada ~y~%s~s~',
['gave_weapon_noweapon'] = '~y~%s~s~ nie posiada tej broni',
['received_weapon'] = 'otrzymałeś/aś ~b~%s~s~ od ~b~%s~s~',
['received_weapon_ammo'] = 'otrzymałeś/aś ~o~%sx %s~s~ do twojego ~b~%s~s~ od ~b~%s~s~',
['received_weapon_withammo'] = 'otrzymałeś/aś ~b~%s~s~ z ~o~%sx %s~s~ od ~b~%s~s~',
['received_weapon_hasalready'] = '~b~%s~s~ próbował/a przekazać ci ~y~%s~s~, lecz już posiadasz jedno',
['received_weapon_noweapon'] = '~b~%s~s~ próbował/a przekazać ci amunicje do ~y~%s~s~, lecz nie posiadasz tej broni',
['gave_account_money'] = 'dajesz ~g~%s$~s~ (%s) dla ~y~%s~s~',
['received_account_money'] = 'otrzymujesz ~g~%s$~s~ (%s) od ~b~%s~s~',
['amount_invalid'] = 'nieprawidłowa ilość',
['players_nearby'] = 'brak graczy w pobliżu',
['ex_inv_lim'] = 'akcja nie jest możliwa, nie możesz mieć więcej ~y~%s~s~',
['imp_invalid_quantity'] = 'akcja jest niemożliwa, nieprawidłowa ilość',
['imp_invalid_amount'] = 'akcja jest niemożliwa, nieprawidłowa kwota',
['threw_standard'] = 'wyrzuciłeś/aś ~y~%sx~s~ ~b~%s~s~',
['threw_account'] = 'wyrzuciłeś/aś ~g~$%s~s~ ~b~%s~s~',
['threw_weapon'] = 'wyrzuciłeś/aś ~b~%s~s~',
['threw_weapon_ammo'] = 'wyrzuciłeś/aś ~b~%s~s~ z ~o~%sx %s~s~',
['threw_weapon_already'] = 'you already carry the same weapon',
['threw_cannot_pickup'] = 'you cannot pickup that because your inventory is full!',
['threw_pickup_prompt'] = 'press ~y~E~s~ to pickup',
-- Key mapping
['keymap_showinventory'] = 'show Inventory',
-- Salary related
['received_salary'] = 'otrzymałeś wynagrodzenie: ~g~%s$~s~',
['received_help'] = 'otrzymałem zapomogę: ~g~$%s~s~',
['company_nomoney'] = 'firma, w której pracujesz, jest zbyt biedna, by wypłacić twoją pensję',
['received_paycheck'] = 'otrzymana wypłata',
['bank'] = 'bank',
['account_bank'] = 'bank',
['account_black_money'] = 'dirty Money',
['account_money'] = 'cash',
['act_imp'] = 'działanie niemożliwe',
['in_vehicle'] = 'nie możesz przekazywać przedmiotów w pojeździe',
-- Commands
['setjob'] = 'przydziel prace użytkownikowi',
['id_param'] = 'ID użytkownika',
['setjob_param2'] = 'praca, którą chcesz przydzielić',
['setjob_param3'] = 'poziom pracy',
['spawn_car'] = 'sprowadź pojazd',
['spawn_car_param'] = 'nazwa samochodu',
['delete_vehicle'] = 'usuń pojazd',
['invalid_account'] = 'błędne konto',
['account'] = 'konto',
['giveaccountmoney'] = 'daj pieniądze na konto',
['invalid_item'] = 'nieprawidłowy przedmiot',
['item'] = 'przedmiot',
['giveitem'] = 'daj przedmiot',
['weapon'] = 'broń',
['giveweapon'] = 'daj broń',
['chat_clear'] = 'wyczyść czat',
['chat_clear_all'] = 'wyczyść czat dla wszystkich',
['command_clearinventory'] = 'usuń wszystkie przedmioty z ekwipunku',
['command_clearloadout'] = 'usuń wszystkie bronie z wyposażenia',
-- Locale settings
['locale_digit_grouping_symbol'] = ' ',
['locale_currency'] = '$%s',
-- Weapons
['weapon_knife'] = 'nóż',
['weapon_nightstick'] = 'pałka',
['weapon_hammer'] = 'młotek',
['weapon_bat'] = 'kij',
['weapon_golfclub'] = 'kij golfowy',
['weapon_crowbar'] = 'łom',
['weapon_pistol'] = 'pistolet',
['weapon_combatpistol'] = 'pistolet bojowy',
['weapon_appistol'] = 'ap pistol',
['weapon_pistol50'] = 'pistol .50',
['weapon_microsmg'] = 'micro smg',
['weapon_smg'] = 'smg',
['weapon_assaultsmg'] = 'assault smg',
['weapon_assaultrifle'] = 'assault rifle',
['weapon_carbinerifle'] = 'carbine rifle',
['weapon_advancedrifle'] = 'advanced rifle',
['weapon_mg'] = 'mg',
['weapon_combatmg'] = 'combat mg',
['weapon_pumpshotgun'] = 'pump shotgun',
['weapon_sawnoffshotgun'] = 'sawed off shotgun',
['weapon_assaultshotgun'] = 'assault shotgun',
['weapon_bullpupshotgun'] = 'bullpup shotgun',
['weapon_stungun'] = 'tazer',
['weapon_sniperrifle'] = 'karabin snajperski',
['weapon_heavysniper'] = 'ciężki karabin snajperski',
['weapon_grenadelauncher'] = 'granatnik',
['weapon_rpg'] = 'wyrzutnia rakiet',
['weapon_minigun'] = 'minigun',
['weapon_grenade'] = 'granat',
['weapon_stickybomb'] = 'ładunek przylepny',
['weapon_smokegrenade'] = 'granat dymny',
['weapon_bzgas'] = 'bz gas',
['weapon_molotov'] = 'koktajl Mołotowa',
['weapon_fireextinguisher'] = 'gaśnica',
['weapon_petrolcan'] = 'kanister',
['weapon_ball'] = 'piłka',
['weapon_snspistol'] = 'sns pistolet',
['weapon_bottle'] = 'butelka',
['weapon_gusenberg'] = 'gusenberg sweeper',
['weapon_specialcarbine'] = 'special carbine',
['weapon_heavypistol'] = 'heavy pistol',
['weapon_bullpuprifle'] = 'karabin wyborowy',
['weapon_dagger'] = 'sztylet',
['weapon_vintagepistol'] = 'vintage pistol',
['weapon_firework'] = 'fajerwerki',
['weapon_musket'] = 'muszkiet',
['weapon_heavyshotgun'] = 'ciężki shotgun',
['weapon_marksmanrifle'] = 'marksman rifle',
['weapon_hominglauncher'] = 'program uruchamiający',
['weapon_proxmine'] = 'mina zbliżeniowa',
['weapon_snowball'] = 'śnieżka',
['weapon_flaregun'] = 'flara',
['weapon_combatpdw'] = 'combat pdw',
['weapon_marksmanpistol'] = 'marksman pistol',
['weapon_knuckle'] = 'kastety',
['weapon_hatchet'] = 'toporek',
['weapon_railgun'] = 'karabin',
['weapon_machete'] = 'meczeta',
['weapon_machinepistol'] = 'pistolet maszynowy',
['weapon_switchblade'] = 'scyzoryk',
['weapon_revolver'] = 'ciężki rewolwer',
['weapon_dbshotgun'] = 'dwururka',
['weapon_compactrifle'] = 'compact rifle',
['weapon_autoshotgun'] = 'auto shotgun',
['weapon_battleaxe'] = 'topór bitewny',
['weapon_compactlauncher'] = 'compact launcher',
['weapon_minismg'] = 'mini smg',
['weapon_pipebomb'] = 'bomba rurowa',
['weapon_poolcue'] = 'kij bilardowy',
['weapon_wrench'] = 'klucz do rur',
['weapon_flashlight'] = 'latarka',
['gadget_parachute'] = 'spadochron',
['weapon_flare'] = 'pistolet sygnałowy',
['weapon_doubleaction'] = 'double-Action Revolver',
-- Weapon Components
['component_clip_default'] = 'domyślny tłumik',
['component_clip_extended'] = 'rozszerzony tłumik',
['component_clip_drum'] = 'drum Magazine',
['component_clip_box'] = 'box Magazine',
['component_flashlight'] = 'latarka',
['component_scope'] = 'luneta',
['component_scope_advanced'] = 'zaawansowana luneta',
['component_suppressor'] = 'tłumik',
['component_grip'] = 'uchwyt',
['component_luxary_finish'] = 'luxary Weapon Finish',
-- Weapon Ammo
['ammo_rounds'] = 'round(s)',
['ammo_shells'] = 'shell(s)',
['ammo_charge'] = 'charge',
['ammo_petrol'] = 'gallons of fuel',
['ammo_firework'] = 'firework(s)',
['ammo_rockets'] = 'rocket(s)',
['ammo_grenadelauncher'] = 'grenade(s)',
['ammo_grenade'] = 'grenade(s)',
['ammo_stickybomb'] = 'bomb(s)',
['ammo_pipebomb'] = 'bomb(s)',
['ammo_smokebomb'] = 'bomb(s)',
['ammo_molotov'] = 'cocktail(s)',
['ammo_proxmine'] = 'mine(s)',
['ammo_bzgas'] = 'can(s)',
['ammo_ball'] = 'ball(s)',
['ammo_snowball'] = 'snowball(s)',
['ammo_flare'] = 'flare(s)',
['ammo_flaregun'] = 'flare(s)',
-- Weapon Tints
['tint_default'] = 'default skin',
['tint_green'] = 'green skin',
['tint_gold'] = 'gold skin',
['tint_pink'] = 'pink skin',
['tint_army'] = 'army skin',
['tint_lspd'] = 'blue skin',
['tint_orange'] = 'orange skin',
['tint_platinum'] = 'platinum skin',
}
|
return {'irenisch','irene','irene','ireen','irena','ireland','irenische','ireens','irenas','irenes'}
|
--[[
================================================================================
ProjectNukeEmergencyService
Provides a listener and action response to an emergency alarm.
Three emergency states:
ALERT
CLEAR
NONE
================================================================================
Author: stuntguy3000
--]]
-- Service Packet Definitions
local EmergencyServicePacket = ProjectNukeCoreClasses.Packet.new(1, nil)
-- End Service Packet Definitions
local EmergencyState = "NONE"
function SendState(EmergencyState)
EmergencyServicePacket:setData(EmergencyState)
ProjectNukeCoreRednetHandler.SendPacket(EmergencyServicePacket)
end
function Run()
if (EmergencyState == "ALERT") then
RunAlertSequence()
elseif (EmergencyState == "CLEAR") then
RunClearSequence()
else
-- Wait for receipt of emergency service packet
Data = ProjectNukeCoreRednetHandler.WaitForPacket(EmergencyServicePacket:getId())
EmergencyState = EmergencyServicePacket.new(EmergencyServicePacket:getId(), Data['data']):getData()
end
end
function RunAlertSequence()
for i = 3,1,-1 do
ProjectNukeCoreGUIUtil.DrawErrorMessages({[1] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[2] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[3] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[4] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[5] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[6] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[7] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[8] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[9] = "ALERT"}, 0.1)
ProjectNukeCoreGUIUtil.DrawErrorMessages({[10] = "ALERT"}, 0.1)
end
end
function RunClearSequence()
for i = 3,1,-1 do
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[1] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[2] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[3] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[4] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[5] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[6] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[7] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[8] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[9] = "CLEAR"}, 0.1)
ProjectNukeCoreGUIUtil.DrawSuccessMessages({[10] = "CLEAR"}, 0.1)
end
end
|
function SAME (me, sub)
local sub = sub or me[#me]
me.aw.n = sub.aw.n
me.aw.t = sub.aw.t
me.aw.forever_ = sub.aw.forever_
end
function U (s1, s2)
for i, v in ipairs(s2) do
s1[#s1+1] = v
end
for k,v in pairs(s2) do
if type(k) ~= 'number' then
s1[k] = v
end
end
end
function MIN (a, b)
return (a < b) and a or b
end
_AWAITS = {
n = 0, -- number of global awaits
}
F = {
Node_pre = function (me)
me.aw = {
n = 0,
t = {},
forever_ = false,
}
end,
Node = function (me)
if not F[me.tag] then
if _AST.isNode(me[#me]) then
SAME(me)
end
end
end,
Root = function (me)
for _, cls in ipairs(me) do
_AWAITS.n = _AWAITS.n + #cls.aw.t
end
end,
-- TODO: remove all!
--[[
Node_pos = function (me)
if me.aw.n == 1 then
if me.depth >= 1 then
U(_AST.iter()().aw.t, me.aw.t)
end
end
end,
Root = function (me)
for _, cls in ipairs(me) do
if cls.aw.forever_ and cls.glbs then
for awt in pairs(cls.aw.t) do
local id = awt[1].evt
_AWAITS.t[id] = {} -- new glb candidate
ALL[awt] = nil -- remove them from non-glb
end
end
end
for awt in pairs(ALL) do
local id = awt[1].evt
if _AWAITS.t[id] then
_AWAITS.t[id] = nil -- remove non-glb from glb
end
end
local t = {}
for id in pairs(_AWAITS.t) do
_AWAITS.n = _AWAITS.n + 1
t[#t+1] = id.id
end
DBG('Global awaits: ', table.concat(t,', '))
-- disable global awaits
--for id in pairs(_AWAITS.t) do
--_AWAITS.t[id] = nil
--end
end,
]]
Stmts = function (me)
local last = me[#me]
if not last then
return
end
-- if the last runs forever, all previous must be tight
if last.aw.forever_ then
for i=1, #me-1 do
local sub = me[i]
if sub.aw.n > 0 then
me.aw.n = 2
me.aw.t = {}
return
end
end
SAME(me)
-- otherwise, add all
else
F.ParAnd(me)
end
end,
ParAnd = function (me)
me.aw.n = 0
for _, sub in ipairs(me) do
me.aw.n = me.aw.n + sub.aw.n
U(me.aw.t, sub.aw.t)
end
if me.aw.n > 1 then
me.aw.t = {} -- no candidates
end
end,
ParEver = function (me)
for _, sub in ipairs(me) do
if sub.aw.forever_ then
U(me.aw.t, sub.aw.t)
end
end
me.aw.n = 2
me.aw.forever_ = true
end,
If = function (me)
local c, t, f = unpack(me)
local t_aw_n = t and t.aw.n or 0
local f_aw_n = f and f.aw.n or 0
if t_aw_n == f_aw_n then
me.aw.n = t_aw_n
if me.aw.n == 1 then
U(me.aw.t, t.aw.t)
U(me.aw.t, f.aw.t)
end
else
me.aw.n = 2 -- avoid inner and following awaits
me.aw.t = {}
end
me.aw.forever_ = t and f and t.aw.forever_ and f.aw.forever_
end,
ParOr = function (me)
me.aw.n = me[1].aw.n
for _, sub in ipairs(me) do
me.aw.n = MIN(me.aw.n, sub.aw.n)
if sub.aw.forever_ or sub.aw.n==1 then
U(me.aw.t, sub.aw.t)
end
end
if me.aw.n == 0 then
me.aw.n = 1 -- assumes it always awaits (avoid tight loops)
end
end,
-- TODO: breaks e rets dentro de ParEver, Loop
Escape = function (me)
_AST.iter'SetBlock'().aw.forever_ = false
end,
SetBlock_pre = 'Loop_pre',
SetBlock = 'Loop',
Break = function (me)
_AST.iter'Loop'().aw.forever_ = false
end,
Loop_pre = function (me)
me.aw.forever_ = true
end,
Loop = function (me)
local sub = (me.tag=='Loop' and me[1]) or me[2]
me.aw.n = sub.aw.n
me.aw.t = sub.aw.t
-- but not forever_
if not me.aw.forever_ then
me.aw.n = 2
me.aw.t = {}
end
if me.aw.n == 0 then
me.aw.n = 1 -- assumes it always awaits (avoid tight loops)
end
end,
SetAwait = function (me)
SAME(me, me[2])
end,
AwaitT = 'AwaitExt',
AwaitInt = 'AwaitExt',
AwaitExt = function (me)
me.aw.n = 1
me.aw.t[ #me.aw.t+1 ] = me
end,
--[=[
-- TODO: remove
AwaitInt = function (me)
if (not me[1].org) or (me[1].org.tag=='This') then -- only local awaits
-- TODO: why?
F.AwaitExt(me)
end
end,
]=]
Async = function (me)
me.aw.n = 1
end,
AwaitT = function (me)
me.aw.n = 1
end,
AwaitN = function (me)
me.aw.n = 1
me.aw.forever_ = true
end,
}
_AST.visit(F)
|
-- This program checks the weather and turns off rain.
--
-- If the signal is on, then the program runs the command to stop the rain.
-- Note: You'll need the Debug Card from creative mode.
-- OpenComputer stack is set up as follows:
-- [Computer][Debug Card]
-- [Screen]
-- [Disk Drive]
-- [Floor]
local keyboard = require("keyboard")
local debug = require("component").debug
local world = debug.getWorld()
local gpu = require("component").gpu
local status
local w, h = gpu.getResolution()
gpu.setResolution(24,10)
while not keyboard.isKeyDown(keyboard.keys.space)
do
gpu.fill(1, 1, w, h, " ")
if world.isRaining() then
status = "Raining"
world.setRaining(false)
else
status = "Clear"
end
gpu.set(1,1,"No Rain Enabled")
gpu.set(1,3,"Weather : " .. status)
gpu.set(1,6,"Press [Space] to exit")
os.sleep(5)
end
gpu.setResolution(80,25)
-- End
|
local CONST = require(script:GetCustomProperty("MetaAbilityProgressionConstants_API"))
local Equipment = script:GetCustomProperty("Equipment"):WaitForObject()
local function META_CP()
return _G["Class.Progression"]
end
-------------------------------------------------------------------------------
-- Local Variables
-------------------------------------------------------------------------------
local regenPrevent = time()
local regenAmount = 0.1
local regenPeriod = 1.0
local nextRegen = 0
local classId = 1
local listener
local function GetRegenValue(player, classId)
local regenForClass = CONST.CLASS_REGEN[classId]
return (0.41 + (0.008 * META_CP().GetClassLevel(player, classId))) * regenForClass
end
local function PlayerDamageTaken(attackData)
local object = attackData.object
if object ~= Equipment.owner or attackData.damage.amount < 0 then
return
end
regenPrevent = time() + 10
end
local function IsOutOfCombat()
return regenPrevent < time()
end
function OnEquipped(equipment, player)
classId = player:GetResource("CLASS_MAP")
listener = Events.Connect("CombatWrapAPI.OnDamageTaken", PlayerDamageTaken)
end
function OnUnequipped(equipment, player)
listener:Disconnect()
listener = nil
end
function Tick(deltaTime)
if not listener then
return
end
if
Equipment and Equipment.owner and Object.IsValid(Equipment.owner) and not Equipment.owner.isDead and
Equipment.owner.hitPoints < Equipment.owner.maxHitPoints and
time() > nextRegen and
IsOutOfCombat()
then
--local classId = Equipment.owner:GetResource("CLASS_MAP")
-- Starts at 0.1 and maxes out at 2
local regenAmount = GetRegenValue(Equipment.owner, classId)
Equipment.owner.hitPoints =
CoreMath.Clamp(Equipment.owner.hitPoints + regenAmount, 0, Equipment.owner.maxHitPoints)
nextRegen = time() + regenPeriod
end
end
-------------------------------------------------------------------------------
-- Listeners
-------------------------------------------------------------------------------
Equipment.equippedEvent:Connect(OnEquipped)
Equipment.unequippedEvent:Connect(OnUnequipped)
|
-- Copyright 2016-2021 Gabriel Dubatti. See LICENSE.
--functions to define common controls like buttons, combo-boxes, etc in the toolbars
local events, events_connect = events, events.connect
--buttons callback functions
toolbar.cmds={} --functions with the name of the clicked button as an argument
toolbar.cmds_d={} --functions with the name of the double clicked button as an argument
toolbar.cmds_r={} --functions with the name of the right clicked button as an argument
--config panel values
toolbar.cfgpnl_chkval={} --checks/radios value
toolbar.cfgpnl_chknotify={} --checks/radios callbacks
local function rm_namenum(buttonname)
--"name#num" --> "name"
local bname,lnum= string.match(buttonname,"(.-)#(.*)")
if bname then return bname end
return buttonname
end
function toolbar.getnum_cmd(cmd)
if cmd then return tonumber(string.match(cmd,".-#(.*)")) end
end
--define a graphical toolbar button
function toolbar.cmd(name,func,tooltip,icon,base)
toolbar.addbutton(name,tooltip,base)
toolbar.cmds[name]= func
if icon == nil or icon == "" then
toolbar.setthemeicon(name,name) --no icon: use 'name' from theme
elseif string.match(icon,"%.png") == nil then
toolbar.setthemeicon(name,icon) --no ".png": use 'icon' from theme
else
toolbar.seticon(name,icon,toolbar.TTBI_TB.IT_NORMAL) --"icon.png": use the given icon file
end
end
--define a text toolbar button
function toolbar.cmdtext(text,func,tooltip,name,usebutsz,dropbt,leftalign,bold)
if not name then name=text end
local w=0
if usebutsz then w=toolbar.cfg.butsize end
toolbar.addtext(name,text,tooltip,w,dropbt,leftalign,bold)
toolbar.cmds[name]= func
end
--define a combo-box using a pop-up toolbar
local combo_open= 0 --1:open 2:open + auto-close (timer running)
local combo_op_name= ""
local function end_combo_select()
if combo_op_name ~= "" then
toolbar.selected(combo_op_name, false, false)
combo_op_name= ""
end
combo_open= 0
end
local function end_combo_open()
if combo_open == 2 then end_combo_select() end
return false
end
local combo_data= {}
local combo_width= {}
local combo_func= {}
local combo_txt= {}
local combo_sel_i= 0
local function close_combo()
toolbar.popup(toolbar.COMBO_POPUP,false) --hide combo popup
if combo_open == 1 then
end_combo_select()
combo_open= 2 --auto-close
timeout(1,end_combo_open)
end
end
local function close_combo_ev(npop)
if npop == toolbar.COMBO_POPUP then close_combo() end
end
events_connect("popup_close", close_combo_ev)
local function combo_clicked(btname)
end_combo_select()
close_combo()
local cname, cval= string.match(btname, "(.-)#(.+)$")
if cname then
local newidx= tonumber(cval)
local newtxt= combo_data[cname][newidx]
combo_txt[cname]= newtxt
toolbar.settext(cname, newtxt)
local cback= combo_func[cname]
if cback then cback(cname, newidx, newtxt) end
end
end
local function getnum_keycode(keycode)
--convert keycode to 0..9
if keycode >= toolbar.KEY._0 and keycode <= toolbar.KEY._9 then return keycode-toolbar.KEY._0 end
if keycode >= toolbar.KEY.KP0 and keycode <= toolbar.KEY.KP9 then return keycode-toolbar.KEY.KP0 end
return -1 --not a number
end
local function change_comboselection(newsel)
if combo_sel_i ~= newsel and newsel >=1 and newsel <= #combo_data[combo_op_name] then
toolbar.selected(combo_op_name.."#"..combo_sel_i, false, false)
combo_sel_i= newsel
toolbar.selected(combo_op_name.."#"..combo_sel_i, false, true)
return true
end
return false
end
local function popup_key_ev(npop, keycode,keyflags)
if npop == toolbar.COMBO_POPUP and combo_open == 1 and (keyflags & toolbar.KEYFLAGS.ALL_MODS) == 0 then --ignore key if shift/ctrl/alt/meta are pressed
if keycode == toolbar.KEY.RETURN or keycode == toolbar.KEY.KPRETURN then
combo_clicked(combo_op_name.."#"..combo_sel_i) --select and close
elseif keycode == toolbar.KEY.UP or keycode == toolbar.KEY.LEFT then
change_comboselection( combo_sel_i-1 ) --select previous item
elseif keycode == toolbar.KEY.DOWN or keycode == toolbar.KEY.RIGHT then
change_comboselection( combo_sel_i+1 ) --select next item
else
change_comboselection( getnum_keycode(keycode) ) --select item # 1..9
end
end
--ui.statusbar_text= "pop key= ".. keycode
--return true to cancel default key actions (like close on ESCAPE)
end
events_connect("popup_key", popup_key_ev)
function toolbar.get_combo_txt(name)
return combo_txt[name]
end
local function show_combo_list(btname)
if combo_open > 0 then
end_combo_select()
return
end
combo_open= 1
combo_op_name= btname
toolbar.selected(combo_op_name, false, true)
toolbar.new(27, 24, 16, toolbar.COMBO_POPUP, toolbar.themepath)
toolbar.addgroup(toolbar.GRPC.ITEMSIZE, toolbar.GRPC.ITEMSIZE|toolbar.GRPC.VERT_SCROLL,0,0)
toolbar.adjust(24,24,3,3,0,0)
toolbar.setdefaulttextfont()
toolbar.themed_icon(toolbar.globalicon, "ttb-combo-list", toolbar.TTBI_TB.BACKGROUND)
toolbar.themed_icon(toolbar.globalicon, "ttb-button-hilight", toolbar.TTBI_TB.BUT_HILIGHT)
toolbar.themed_icon(toolbar.globalicon, "ttb-button-press", toolbar.TTBI_TB.BUT_HIPRESSED)
toolbar.themed_icon(toolbar.globalicon, "ttb-combo-selected", toolbar.TTBI_TB.BUT_SELECTED)
local currit= combo_txt[btname]
combo_sel_i= 0
for i=1,#combo_data[btname] do
local itname= btname.."#"..i
local ittxt= combo_data[btname][i]
toolbar.addtext(itname,ittxt,"",282,false,true)
if ittxt == currit then combo_sel_i= i toolbar.selected(itname, false, true) end
toolbar.cmds[itname]= combo_clicked
end
toolbar.popup(toolbar.COMBO_POPUP,true,btname,35,combo_width[btname]-2)
toolbar.sel_combo_popup()
end
function toolbar.cmd_combo(name,func,tooltip,txtarray,txtval,width,bold)
if idx == 0 then idx=1 end
if width == 0 then width=300 end --configure this
combo_data[name]= txtarray
combo_width[name]= width
if not txtval then txtval= txtarray[1] end
combo_txt[name]= txtval
toolbar.addtext(name,txtval,tooltip,width,true,true,bold) --show current value
toolbar.cmds[name]= show_combo_list --pass the combo name when clicked
combo_func[name]= func
end
function toolbar.set_combo_txt(name, txtval,dontset_toolbar)
combo_txt[name]= txtval
if not dontset_toolbar then toolbar.settext(name, txtval) end
end
local font_val= {}
function toolbar.set_font_val(name, txtval, dontset_toolbar)
font_val[name]= txtval
if not dontset_toolbar then toolbar.settext(name, txtval) end
end
function toolbar.get_font_val(name)
local font= font_val[name]
if not font then font= toolbar.DEFAULT_FONT end
return font
end
function toolbar.get_cfg_font_num(name)
return toolbar.get_font_num(toolbar.get_font_val(name))
end
function toolbar.get_cfg_font_extrasize(name)
local extrasz= toolbar.get_combo_txt("cbo."..name:gsub("%.","size_")) or ""
local esz= string.match(extrasz, "(.-)%s.+$")
return tonumber(esz) or 0
end
events_connect("toolbar_clicked", function(buttonname,ntoolbar,ngroup,keyflags)
toolbar.keyflags= keyflags
if buttonname == "TOOLBAR" then
buttonname= "TOOLBAR".. ntoolbar --button name="TOOLBAR#" (#=toolbar num)
elseif buttonname == "GROUP" then
buttonname= "GROUP".. ngroup.. "-"..ntoolbar --button name="GROUP#-T" (#=group num, T=toolbar num)
end
if toolbar.cmds[buttonname] ~= nil then
toolbar.cmds[buttonname](buttonname) --pass the name of the button
elseif toolbar.cmds[buttonname] ~= nil then
--is a config checkbox?
if toolbar.cfgpnl_chkval ~= nil and toolbar.cfgpnl_chkval[buttonname] ~= nil then
toolbar.cmds[buttonname](buttonname) --pass the name of the checkbox
else
toolbar.cmds[buttonname](buttonname)
end
--else ui.statusbar_text= buttonname.." clicked"
end
end)
function toolbar.cmd_dclick(name,func)
--connect to double click
toolbar.cmds_d[ rm_namenum(name) ]= func
end
events_connect("toolbar_2clicked", function(buttonname,ntoolbar,ngroup,keyflags)
toolbar.keyflags= keyflags
local bfunc= rm_namenum(buttonname) --"name#num" --> "name"
--pass the complete name of the button ("name#num")
if toolbar.cmds_d[bfunc] ~= nil then return toolbar.cmds_d[bfunc](buttonname) end
end)
function toolbar.cmd_rclick(name,func)
--open a context menu over this item
toolbar.cmds_r[ rm_namenum(name) ]= func
end
events_connect("toolbar_Rclicked", function(buttonname,ntoolbar,ngroup,keyflags)
toolbar.keyflags= keyflags
if buttonname == "TOOLBAR" then
buttonname= "TOOLBAR".. ntoolbar --button name="TOOLBAR#" (#=toolbar num)
elseif buttonname == "GROUP" then
buttonname= "GROUP".. ngroup.. "-"..ntoolbar --button name="GROUP#-T" (#=group num, T=toolbar num)
end
local bfunc= rm_namenum(buttonname) --"name#num" --> "name"
--pass the complete name of the button ("name#num")
if toolbar.cmds_r[bfunc] ~= nil then return toolbar.cmds_r[bfunc](buttonname) end
end)
--checks/radios
function toolbar.clear_checks_vars()
toolbar.cfgpnl_chkval={}
toolbar.cfgpnl_chknotify={}
end
function toolbar.set_notify_on_change(name,func)
toolbar.cfgpnl_chknotify[name]=func
end
function toolbar.set_check_val(name,checked,dontset_toolbar)
toolbar.cfgpnl_chkval[name]= checked
if not dontset_toolbar then toolbar.selected(name, checked) end
end
function toolbar.get_check_val(name)
if toolbar.cfgpnl_chkval[name] then return true end
return false
end
local function check_clicked(name)
--toggle checkbox value
toolbar.set_check_val(name, not toolbar.get_check_val(name))
toolbar.config_change=true
if toolbar.cfgpnl_chknotify[name] ~= nil then toolbar.cfgpnl_chknotify[name]() end
end
function toolbar.cmd_check(name,tooltip,checked)
toolbar.cmd(name, check_clicked, tooltip, nil, toolbar.TTBI_TB.CHECK_BASE)
toolbar.selected(name, checked)
toolbar.cfgpnl_chkval[name]=checked
end
local function radio_clicked(name,dontset_toolbar,dont_notify)
--set new radio button value
toolbar.cfgpnl_chkval[name]= true
if not dontset_toolbar then toolbar.selected(name, true) end
--reset the others (same rname in "rname:option-value")
local rname=string.match(name, "(.-):.+$")
if rname then
local i=1
while toolbar.cfgpnl_chkval[rname..':'..i] ~= nil do
local rbn=rname..':'..i
if name ~= rbn and toolbar.cfgpnl_chkval[rbn] then
toolbar.cfgpnl_chkval[rbn]= false
if not dontset_toolbar then toolbar.selected(rbn, false) end
end
i=i+1
end
end
toolbar.config_change=true
if (not dont_notify) and (toolbar.cfgpnl_chknotify[rname] ~= nil) then
toolbar.cfgpnl_chknotify[rname]()
end
end
function toolbar.cmd_radio(name,tooltip,checked)
toolbar.cmd(name, radio_clicked, tooltip, nil, toolbar.TTBI_TB.RADIO_BASE)
toolbar.selected(name, checked)
toolbar.cfgpnl_chkval[name]=checked
end
function toolbar.set_radio_val(name,val,dontset_toolbar,maxnum)
if maxnum then --create all missing items
local i=1
while i <= maxnum do
if toolbar.cfgpnl_chkval[name..':'..i] == nil then
toolbar.cfgpnl_chkval[name..':'..i]=false
end
i=i+1
end
end
radio_clicked(name..":"..val,dontset_toolbar,true)
end
function toolbar.get_radio_val(name,maxnum)
local i=1
if maxnum then
while i <= maxnum do
if toolbar.cfgpnl_chkval[name..':'..i] then
return i
end
i=i+1
end
else
while toolbar.cfgpnl_chkval[name..':'..i] ~= nil do
if toolbar.cfgpnl_chkval[name..':'..i] then
return i
end
i=i+1
end
end
return 0
end
function toolbar.top_right_resize_handle(rzname, wmin, func) --add a resize handle
toolbar.gotopos(0, 0)
toolbar.addbutton(rzname,"Resize panel")
toolbar.anchor(rzname, 25) --anchor to the right
toolbar.setresize(rzname, true, wmin) --is a resize button
toolbar.cmds[rzname]= func
toolbar.setthemeicon(rzname, "transparent", toolbar.TTBI_TB.IT_NORMAL)
toolbar.setthemeicon(rzname, "resize-tr", toolbar.TTBI_TB.BACKGROUND)
toolbar.setthemeicon(rzname, "resize-tr-hilight", toolbar.TTBI_TB.IT_HILIGHT)
toolbar.setthemeicon(rzname, "resize-tr-hilight", toolbar.TTBI_TB.IT_HIPRESSED)
end
function toolbar.set_expand_icon(cmd,icon)
toolbar.setthemeicon(cmd, icon, toolbar.TTBI_TB.IT_NORMAL)
toolbar.setthemeicon(cmd, icon.."-hilight", toolbar.TTBI_TB.IT_HILIGHT)
toolbar.setthemeicon(cmd, icon.."-hilight", toolbar.TTBI_TB.IT_HIPRESSED)
toolbar.setthemeicon(cmd, "transparent", toolbar.TTBI_TB.IT_SELECTED)
end
---- LIST ---
toolbar.listtb_y= 1
toolbar.listtb_x= 3
toolbar.list_cmdright= 18
toolbar.listright= 250
function toolbar.list_addbutton(name, tooltip, funct, icon)
toolbar.gotopos( 0, toolbar.listtb_y)
toolbar.cmd(name, funct, tooltip or "", icon)
toolbar.list_cmdright= toolbar.list_cmdright + toolbar.cfg.butsize
toolbar.anchor(name, toolbar.list_cmdright) --anchor to the right
end
function toolbar.list_addaction(action)
toolbar.gotopos( 0, toolbar.listtb_y)
toolbar.addaction(action)
toolbar.list_cmdright= toolbar.list_cmdright + toolbar.cfg.butsize
toolbar.anchor(action, toolbar.list_cmdright) --anchor to the right
end
local lbl_n= 0
function toolbar.list_addinfo(text,bold)
--add a text to the list
toolbar.gotopos(toolbar.listtb_x, toolbar.listtb_y)
lbl_n= lbl_n+1
local name= "_lbl_"..lbl_n
toolbar.addlabel(text, "", toolbar.listright, true, bold, name)
toolbar.listtb_y= toolbar.listtb_y + toolbar.cfg.butsize
toolbar.list_cmdright= 18
toolbar.anchor(name, toolbar.list_cmdright, true)
toolbar.listtb_x= 3
return name
end
function toolbar.get_openback_icon(isopen)
return toolbar.themepath..(isopen and "open-back.png" or "closed-back.png")
end
function toolbar.list_add_txt_ico(name, text, tooltip, bold, click_fun, bicon, evenrow, indent, idlen, open_hi, lstwidth)
if not idlen then idlen=0 end
if idlen > 0 then indent= indent + 10 end --add a collapse icon
local xtxt= indent
if bicon then xtxt= indent + toolbar.cfg.barsize end
toolbar.gotopos(3, toolbar.listtb_y)
toolbar.addtext(name, text, tooltip, lstwidth, false, true, bold, xtxt, 0)
if evenrow then toolbar.setbackcolor(name, toolbar.cfg.backcolor_erow,false,true) end
toolbar.anchor(name, 10, true)
if bicon then
if open_hi > 0 then --open/closed file highlight
toolbar.adjust(toolbar.cfg.butsize+4,toolbar.cfg.butsize,3,3,4,4)
toolbar.gotopos(3 + indent, toolbar.listtb_y)
local iobut= "open-"..name
toolbar.cmd(iobut, nil, "", toolbar.get_openback_icon(open_hi == 1))
toolbar.enable(iobut,false,false) --non-selectable image
toolbar.adjust(toolbar.cfg.butsize,toolbar.cfg.butsize,3,3,4,4)
end
toolbar.gotopos(3 + indent, toolbar.listtb_y)
local icbut= "ico-"..name
toolbar.cmd(icbut, nil, "", bicon)
toolbar.enable(icbut,false,false) --non-selectable image
end
toolbar.cmds[name]= click_fun
if idlen > 0 then return true end --toolbar.list_add_collapse() must be called
toolbar.listtb_y= toolbar.listtb_y + toolbar.cfg.butsize
end
function toolbar.list_add_collapse(name, click_fun, indent, hide_nrows, colla_tab)
toolbar.gotopos( indent+3, toolbar.listtb_y)
local exbut= "exp-"..name
toolbar.cmd(exbut, click_fun, "", "list-colapse2")
toolbar.set_expand_icon(exbut,"list-colapse2")
toolbar.collapse(exbut, false, toolbar.cfg.butsize * hide_nrows, true)
colla_tab[exbut]= false
toolbar.listtb_y= toolbar.listtb_y + toolbar.cfg.butsize
end
function toolbar.list_add_separator()
toolbar.gotopos(3, toolbar.listtb_y)
toolbar.addspace()
toolbar.listtb_y= toolbar.listtb_y + toolbar.cfg.butsize/2
end
toolbar.icon_ext= {
["txt"]= "text-plain",
["md"]= "text-richtext",
["c"]= "text-x-c",
["cpp"]= "text-x-c++",
["h"]= "text-x-chdr",
["hpp"]= "text-x-c++hdr",
["lua"]= "text-x-lua",
["py"]= "text-x-python",
["java"]= "text-x-java",
["ctag"]= "text-x-ctag",
["asm"]= "text-x-source",
["mas"]= "text-x-source",
["inc"]= "text-x-source",
["lst"]= "x-office-document",
["map"]= "application-msword",
["sym"]= "application-msword",
["s19"]= "multipart-encrypted",
["html"]= "text-html",
["htm"]= "text-html",
["xml"]= "text-xml",
["css"]= "text-css",
["js"]= "text-x-javascript",
["php"]= "application-x-php",
["conf"]= "text-x-copying",
["pdf"]= "application-pdf",
["sh"]= "text-x-script",
["bash"]= "text-x-script",
["glade"]="text-x-generic-template",
["exe"]= "application-x-executable",
["bat"]= "text-x-script",
["rc"]= "text-x-generic-template",
["rb"]= "application-x-ruby",
["mak"]= "text-x-makefile",
["sql"]= "text-x-sql",
["tex"]= "text-x-tex",
}
toolbar.icon_ext_path= _USERHOME.."/toolbar/icons/mime/"
function toolbar.icon_fname(fname)
local p,f,e= Util.splitfilename(string.lower(fname))
if p then
local eh= string.match(e, "^(.-):head")
if eh then e=eh end --remove ":head" from extension
local icon= toolbar.icon_ext[e]
if icon then return toolbar.icon_ext_path..icon..".png" end
if f == "makefile" then return toolbar.icon_ext_path.."text-x-makefile.png" end
if f == "readme" then return toolbar.icon_ext_path.."text-x-readme.png" end
end
return toolbar.icon_ext_path.."text-plain.png"
end
toolbar.icon_lex= nil
function toolbar.icon_lexer(lexername)
if toolbar.icon_lex == nil then
toolbar.icon_lex= {
["cmake"]= "text-x-makefile",
["objective_c"]= "text-x-c",
["bibtex"]= "text-x-bibtex",
}
for ext,icon in pairs(toolbar.icon_ext) do
if ext ~= "hpp" and ext ~= "h" then --"h" and "hpp" use the "cpp" lexer, ignore this icons
local lex= textadept.file_types.extensions[ext]
if lex ~= nil and toolbar.icon_lex[lex] == nil then toolbar.icon_lex[lex]= icon end
end
end
end
local icon= toolbar.icon_lex[lexername] or "text-plain"
return toolbar.icon_ext_path..icon..".png"
end
|
AddCSLuaFile()
local DbgPrint = GetLogging("MapScript")
local MAPSCRIPT = {}
MAPSCRIPT.PlayersLocked = false
MAPSCRIPT.DefaultLoadout =
{
Weapons =
{
},
Ammo =
{
},
Armor = 0,
HEV = true,
}
MAPSCRIPT.InputFilters =
{
}
MAPSCRIPT.EntityFilterByClass =
{
--["env_global"] = true,
}
MAPSCRIPT.EntityFilterByName =
{
--["spawnitems_template"] = true,
}
MAPSCRIPT.VehicleGuns = true
function MAPSCRIPT:Init()
DbgPrint("-- Mapscript: Template loaded --")
end
function MAPSCRIPT:PostInit()
if SERVER then
end
end
function MAPSCRIPT:PostPlayerSpawn(ply)
--DbgPrint("PostPlayerSpawn")
end
return MAPSCRIPT
|
-- conveyors push entities with forcerecievers
return {}
|
local BulletChar = require "bosses/lekkerchat/projectiles/bulletchar"
local BulletCharW = BulletChar:extend("BulletCharW")
function BulletCharW:new(...)
BulletCharW.super.new(self, ...)
self:setImage("bosses/lekkerchat/char_w")
self.velocity.x = -BulletChar.xSpeed
self.startY = self.y
self.timer = 0
self.dir = _.coin()
end
function BulletCharW:update(dt)
self.timer = self.timer + dt
self.y = self.startY + math.sin(self.timer * PI) * (self.dir and 200 or -200)
BulletCharW.super.update(self, dt)
end
function BulletCharW:draw()
BulletCharW.super.draw(self)
end
return BulletCharW
|
local rotate
if minetest.global_exists("screwdriver") then rotate = screwdriver.rotate_simple end
local doublecorner_selectionbox = {
type = "fixed",
fixed = { -8/16, -8/16, -8/16, 8/16, -6/16, 8/16 },
}
local rules = {
{
{ x = 1, y = 0, z = 0 },
{ x = 0, y = 0, z = 1 },
},
{
{ x = -1, y = 0, z = 0 },
{ x = 0, y = 0, z = -1 },
},
}
local doublecorner_rules = {}
for k = 1, 4 do
doublecorner_rules[k] = table.copy(rules)
for i, r in ipairs(rules) do
rules[i] = mesecon.rotate_rules_left(r)
end
end
local function doublecorner_get_rules(node)
return doublecorner_rules[node.param2 % 4 + 1]
end
local doublecorner_states = {
"mesecons_extrawires:doublecorner_00",
"mesecons_extrawires:doublecorner_01",
"mesecons_extrawires:doublecorner_10",
"mesecons_extrawires:doublecorner_11",
}
local wire1_states = { "off", "off", "on", "on" }
local wire2_states = { "off", "on", "off", "on" }
for k, state in ipairs(doublecorner_states) do
local w1 = wire1_states[k]
local w2 = wire2_states[k]
local groups = { dig_immediate = 3 }
if k ~= 1 then groups.not_in_creative_inventory = 1 end
minetest.register_node(state, {
drawtype = "mesh",
mesh = "mesecons_extrawires_doublecorner.obj",
description = "Insulated Mesecon Double Corner",
tiles = {
{ name = "jeija_insulated_wire_sides_" .. w1 .. ".png", backface_culling = true },
{ name = "jeija_insulated_wire_ends_" .. w1 .. ".png", backface_culling = true },
{ name = "jeija_insulated_wire_sides_" .. w2 .. ".png", backface_culling = true },
{ name = "jeija_insulated_wire_ends_" .. w2 .. ".png", backface_culling = true },
},
paramtype = "light",
paramtype2 = "facedir",
is_ground_content = false,
walkable = false,
sunlight_propagates = true,
selection_box = doublecorner_selectionbox,
groups = groups,
drop = doublecorner_states[1],
sounds = default.node_sound_defaults(),
mesecons = {
conductor = {
states = doublecorner_states,
rules = doublecorner_get_rules,
},
},
on_blast = mesecon.on_blastnode,
on_rotate = rotate,
})
end
minetest.register_craft({
type = "shapeless",
output = "mesecons_extrawires:doublecorner_00",
recipe = {
"mesecons_extrawires:corner_off",
"mesecons_extrawires:corner_off",
},
})
minetest.register_craft({
type = "shapeless",
output = "mesecons_extrawires:corner_off 2",
recipe = {
"mesecons_extrawires:doublecorner_00",
},
})
|
--[[
© 2018 Thriving Ventures AB do not share, re-distribute or modify
without permission of its author (gustaf@thrivingventures.com).
]]
local plugin = plugin
plugin.disconnects = plugin.disconnects or {}
plugin:IncludeFile("shared.lua", SERVERGUARD.STATE.SHARED)
plugin:IncludeFile("cl_panel.lua", SERVERGUARD.STATE.CLIENT)
serverguard.netstream.Hook("sgRequestDisconnects", function(player, data)
if (serverguard.player:HasPermission(player, "View Disconnects")) then
for k, v in pairs(plugin.disconnects) do
serverguard.netstream.Start(player, "sgGetDisconnects", v)
end
end
end)
local function removeDisconnect(steamid)
for k, v in pairs(plugin.disconnects) do
if v[1] == steamid then
table.remove(plugin.disconnects, k)
end
end
end
hook.Add("PlayerDisconnected", "serverguard.disconnects.PlayerDisconnected", function(player)
if IsValid(player) then
local steamid = player:SteamID()
table.insert(plugin.disconnects, {steamid, serverguard.player:GetRank(player), player:Name()})
timer.Simple(600, function()
removeDisconnect(steamid)
end)
end
end)
hook.Add("PlayerInitialSpawn", "serverguard.disconnects.PlayerInitialSpawn", function(player)
removeDisconnect(player:SteamID())
end)
|
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
RegisterServerEvent('force_drugsGiveReward')
AddEventHandler('force_drugsGiveReward', function(rewardItem, randomAmount)
local player = ESX.GetPlayerFromId(source)
player.addInventoryItem(rewardItem, math.random(5, randomAmount))
end)
|
object_static_item_lair_rock_shelter_small = object_static_item_shared_lair_rock_shelter_small:new {
}
ObjectTemplates:addTemplate(object_static_item_lair_rock_shelter_small, "object/static/item/lair_rock_shelter_small.iff")
|
--------------------------------------------------------------------------------
--[[
The Runtest file for the Dusk benchmarks.
--]]
--------------------------------------------------------------------------------
local dusk = require("Dusk.Dusk")
local table_insert = table.insert
local table_concat = table.concat
local tostring = tostring
local string_format = string.format
local system_getTimer = system.getTimer
-- from http://lua-users.org/wiki/FormattingNumbers
local function commas(n) local n = tostring(n) local left, num, right = n:match('^([^%d]*%d)(%d*)(.-)$') return left .. (num:reverse():gsub('(%d%d%d)','%1,'):reverse()) .. right end
-- Runtest
local function runtest(name)
local startTime = system_getTimer()
local map = dusk.buildMap("tests/benchmarks/" .. name .. ".json")
local buildTime = system_getTimer() - startTime; buildTime = string_format("%.03f", buildTime)
local numTiles = commas(map.data.mapWidth * map.data.mapHeight)
local str = "\n\nruntest " .. name .. "\n"
str = str .. "-> map built" .. "\n"
str = str .. "-> " .. numTiles .. " tiles" .. "\n"
str = str .. "-> " .. buildTime .. " ms to load" .. "\n"
print(str)
map.setTrackingLevel(0.3)
function map.drag(event)
local viewX, viewY = map.getViewpoint()
if "began" == event.phase then
display.getCurrentStage():setFocus(map)
map.isFocus = true
map._x, map._y = event.x + viewX, event.y + viewY
elseif map.isFocus then
if "moved" == event.phase then
map.setViewpoint(map._x - event.x, map._y - event.y)
map.updateView() -- Update the map's camera and culling directly after changing position
elseif "ended" == event.phase then
display.getCurrentStage():setFocus(nil)
map.isFocus = false
end
end
end
map:addEventListener("touch", map.drag)
Runtime:addEventListener("enterFrame", map.updateView)
end
return runtest
|
-- Copyright (c) 2013-2015: G-CSC, Goethe University Frankfurt
-- Author: Andreas Vogel
--
-- This file is part of UG4.
--
-- UG4 is free software: you can redistribute it and/or modify it under the
-- terms of the GNU Lesser General Public License version 3 (as published by the
-- Free Software Foundation) with the following additional attribution
-- requirements (according to LGPL/GPL v3 §7):
--
-- (1) The following notice must be displayed in the Appropriate Legal Notices
-- of covered and combined works: "Based on UG4 (www.ug4.org/license)".
--
-- (2) The following notice must be displayed at a prominent place in the
-- terminal output of covered works: "Based on UG4 (www.ug4.org/license)".
--
-- (3) The following bibliography is recommended for citation and must be
-- preserved in all covered files:
-- "Reiter, S., Vogel, A., Heppner, I., Rupp, M., and Wittum, G. A massively
-- parallel geometric multigrid solver on hierarchically distributed grids.
-- Computing and visualization in science 16, 4 (2013), 151-164"
-- "Vogel, A., Reiter, S., Rupp, M., Nägel, A., and Wittum, G. UG4 -- a novel
-- flexible software system for simulating pde based models on high performance
-- computers. Computing and visualization in science 16, 4 (2013), 165-179"
--
-- 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 Lesser General Public License for more details.
--[[!
\file time_step_util.lua
\defgroup scripts_util_timestep Timestep Utility
\ingroup scripts_util
\{
]]--
util = util or {}
--!
--! @param domainDisc
--! @param timeScheme theta, impleuler, expleuer, crank-nicolson, alexander, fracstep, or bdf
--! @param orderOrTheta theat is timeScheme=theta
function util.CreateTimeDisc(domainDisc, timeScheme, orderOrTheta)
local timeDisc = nil;
if timeScheme:lower() == "theta" then
timeDisc = ThetaTimeStep(domainDisc)
timeDisc:set_theta(orderOrTheta) -- 1.0 is implicit euler
elseif timeScheme:lower() == "impleuler" then
timeDisc = ThetaTimeStep(domainDisc)
timeDisc:set_theta(1.0) -- 1.0 is implicit euler
elseif timeScheme:lower() == "expleuler" then
timeDisc = ThetaTimeStep(domainDisc)
timeDisc:set_theta(0.0) -- 0.0 is explicit euler
elseif timeScheme:lower() == "crank-nicolson" then
timeDisc = ThetaTimeStep(domainDisc)
timeDisc:set_theta(0.5) -- 0.5 is crank-nicolson
elseif timeScheme:lower() == "alexander" then
timeDisc = ThetaTimeStep(domainDisc, "Alexander")
elseif timeScheme:lower() == "fracstep" then
timeDisc = ThetaTimeStep(domainDisc, "FracStep")
elseif timeScheme:lower() == "bdf" then
timeDisc = BDF(domainDisc)
elseif timeScheme:lower() == "sdirk" then
timeDisc = SDIRK(domainDisc, orderOrTheta)
else
print("Time scheme '"..timeScheme.."' not found. Supported Schemes:")
print("Theta, ImplEuler, ExplEuler, Crank-Nicolson, Alexander, FracStep, BDF, SDIRK")
print("Aborting")
exit();
end
return timeDisc
end
function util.PrintUsageOfSolveTimeProblem()
print("Usage of ")
print("util.SolveNonlinearTimeProblem(u, domainDisc, solver, out, filename")
print(" timeScheme, orderOrTheta, startTime, endTime,")
print(" maxStepSize, minStepSize, reductionFactor)")
print("util.SolveLinearTimeProblem( u, domainDisc, solver, out, filename")
print(" timeScheme, orderOrTheta, startTime, endTime,")
print(" maxStepSize, minStepSize, reductionFactor)")
print("Parameters:")
print("------")
print("u -- [in] GridFunction with Startvalues, [out] Solution")
print("domainDisc -- Domain Discretization ")
print("solver -- Linear or Nonlinear Solver")
print("out -- a VTKOutput (pass nil for no output)")
print("filename -- filename for output")
print("timeScheme -- Name of time step scheme: ")
print(" Theta, ImplEuler, ExplEuler, Crank-Nicolson,")
print(" Alexander, FracStep, BDF")
print("orderOrTheta -- theta param if 'Theta', order if 'BDF'")
print("startTime -- start time point")
print("endTime -- end time point")
print("maxStepSize -- maximal step sized used")
print("minStepSize -- (optional) minimal step sized used")
print("reductionFactor -- (optional) factor by which the step size is ")
print(" reduced, if the problem was not solved. ")
print(" Iterated until minStepSize is reached.")
print("bFinishTimeStep -- (optional) boolean if finish_timestep should be")
print(" called or not.")
print("useCheckpointing -- (optional) if true, use checkpointing.")
print("postProcess -- (optional) if passed, will be called after every time step.")
print("startTSNo -- (optional) time step number of the initial condition (normally 0).")
print("endTSNo -- (optional) if passed, stop after the time step with this number.")
end
--! Time stepping with a fixed step size. Returns number of time steps done and the last time.
--! @param u [in] GridFunction with Startvalues, [out] Solution"
--! @param domainDisc Domain Discretization
--! @param newtonSolver Nonlinear Solver
--! @param out a VTKOutput (pass nil for no output)
--! @param filename filename for output
--! @param timeScheme Name of time step scheme:
--! Theta, ImplEuler, ExplEuler, Crank-Nicolson
--! Alexander, FracStep, BDF
--! @param orderOrTheta theta param if 'Theta', order if 'BDF'
--! @param startTime start time point
--! @param endTime end time point")
--! @param maxStepSize maximal step sized used
--! @param minStepSize (optional) minimal step sized used
--! @param reductionFactor (optional) factor by which the step size is
--! reduced, if the problem was not solved.
--! Iterated until minStepSize is reached.
--! @param bFinishTimeStep (optional) boolean if finish_timestep should be
--! called or not.
--! @param useCheckpointing (optional) if true, use checkpointing.
--! @param postProcess (optional) if passed, this can be either a function or a table:
--! a) If this is a function then it is called after
--! solving the non-linear problem in EVERY STAGE
--! of the time-stepping scheme;
--! b) if this is a table, it can contain 4 optional functions:
--! prepareTimeStep to call before the time step,
--! preProcess to call before the non-linear solver in EVERY STAGE,
--! postProcess as in a),
--! finalizeTimeStep to call after the time step,
--! rewindTimeStep to call if some of the computations of the time step failed,
--! Arguments of the functions are: (u, step, time, dt)
--! u, time: old before the solver, new after it
--! @param startTSNo (optional) time step number of the initial condition (normally 0).
--! @param endTSNo (optional) if passed, stop after the time step with this number.
--! @param newtonLineSearchFallbacks (optional) Sequence of line-search objects.
--! Each time the newton-solver fails in a time-step,
--! the next line-search object from the sequence is used.
function util.SolveNonlinearTimeProblem(
u,
domainDisc,
newtonSolver,
out,
filename,
timeScheme,
orderOrTheta,
startTime,
endTime,
maxStepSize,
minStepSize,
reductionFactor,
bFinishTimeStep,
useCheckpointing,
postProcess,
startTSNo,
endTSNo,
newtonLineSearchFallbacks)
if u == nil then
print("SolveNonlinearTimeProblem: Illegal parameters: No grid function for the solution specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if domainDisc == nil then
print("SolveNonlinearTimeProblem: Illegal parameters: No domain discretization specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if newtonSolver == nil then
print("SolveNonlinearTimeProblem: Illegal parameters: No nonlin. solver specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if timeScheme == nil then
print("SolveNonlinearTimeProblem: Illegal parameters: No time scheme specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if startTime == nil then
print("SolveNonlinearTimeProblem: Illegal parameters: Start time not specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if endTime == nil and endTSNo == nil then
print("SolveNonlinearTimeProblem: Illegal parameters: End time or number of steps not specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if maxStepSize == nil then
print("SolveNonlinearTimeProblem: Illegal parameters: No max. time step specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
local prepareTimeStep = nil
local preProcess = nil
local finalizeTimeStep = nil
local rewindTimeStep = nil
if postProcess ~= nil then
if type(postProcess) ~= "function" then
if type(postProcess) ~= "table" then
print("SolveNonlinearTimeProblem: Illegal parameters: postProcess must be a function.")
exit()
end
prepareTimeStep = postProcess.prepareTimeStep
preProcess = postProcess.preProcess
finalizeTimeStep = postProcess.finalizeTimeStep
rewindTimeStep = postProcess.rewindTimeStep
postProcess = postProcess.postProcess
end
end
-- check parameters
if filename == nil then filename = "sol" end
if minStepSize == nil then minStepSize = maxStepSize end
if reductionFactor == nil then reductionFactor = 0.5 end
if reductionFactor >= 1 then
print("SolveNonlinearTimeProblem: Illegal parameters: reductionFactor must be < 1.")
exit()
end
-- create time disc
local timeDisc = util.CreateTimeDisc(domainDisc, timeScheme, orderOrTheta)
-- print newtonSolver setup
print("SolveNonlinearTimeProblem, Newton Solver setup:")
print(newtonSolver:config_string())
-- start
local time = startTime
local step = startTSNo or 0
local nlsteps = 0;
if useCheckpointing then
--- Read Checkpoint if necessary
if util.HasParamOption("-restartWithCheckpoint") then
cp = util.ReadCheckpoint(u)
if cp ~= nil then
time = cp.myData.time
step = cp.myData.step
end
end
end
-- write start solution
print(">> Writing start values")
if type(out) == "function" then out(u, step, time)
elseif type(out) == "userdata" then out:print(filename, u, step, time)
end
-- store grid function in vector of old solutions
local solTimeSeries = SolutionTimeSeries()
solTimeSeries:push(u:clone(), time)
-- update newtonSolver
newtonSolver:init(AssembledOperator(timeDisc, u:grid_level()))
-- store old solution (used for reinit in multistep)
local uOld
if minStepSize <= maxStepSize * reductionFactor or newtonLineSearchFallbacks ~= nil then
uOld = u:clone()
end
-- TODO: This can be optimized because the "old" solution is stored in
-- solTimeSeries. Note that 'u' keeps not (always) the new solution but
-- an iterate of the Newton method. If the Newton method fails, one should
-- reset this iterate from the old solution: The Newton method needs a good
-- initial approximation and its convergence depends on it strongly!
-- set order for bdf to 1 (initially)
if timeScheme:lower() == "bdf" then timeDisc:set_order(1) end
-- bound on t-stepper from machine precision (conservative)
relPrecisionBound = 1e-12
local defaultLineSearch = newtonSolver:line_search()
-- stop if size of remaining t-domain (relative to `maxStepSize`) lies below `relPrecisionBound`
while (endTime == nil or ((time < endTime) and ((endTime-time)/maxStepSize > relPrecisionBound))) and ((endTSNo == nil) or (step < endTSNo)) do
step = step+1
print("++++++ TIMESTEP " .. step .. " BEGIN (current time: " .. time .. ") ++++++");
-- initial t-step size
local currdt = maxStepSize
-- adjust in case of over-estimation
if time+currdt > endTime then currdt = endTime-time end
-- adjust if size of remaining t-domain (relative to `maxStepSize`) lies below `relPrecisionBound`
if ((endTime-(time+currdt))/maxStepSize < relPrecisionBound) then currdt = endTime-time end
-- try time step
local bSuccess = false;
while bSuccess == false do
TerminateAbortedRun()
print("++++++ Time step size: "..currdt);
local newtonSuccess = false
local newtonTry = 1
newtonSolver:set_line_search(defaultLineSearch)
while newtonSuccess == false do
-- get old solution if the restart with a smaller time step is possible
if uOld ~= nil then
VecAssign(u, uOld)
end
local pp_res -- result of pre- and postprocess routines
pp_res = true
if prepareTimeStep ~= nil then
pp_res = prepareTimeStep(u, step, time, currdt)
if type(pp_res) == "boolean" and pp_res == false then -- i.e. not nil, not something else, but "false"!
print("\n++++++ Preparation of the time step failed.")
else
pp_res = true
end
end
if pp_res == false then break end
for stage = 1, timeDisc:num_stages() do
if timeDisc:num_stages() > 1 then
print(" +++ STAGE " .. stage .. " BEGIN ++++++")
end
-- call pre process
if preProcess ~= nil then
pp_res = preProcess(u, step, time, currdt)
if type(pp_res) == "boolean" and pp_res == false then -- i.e. not nil, not something else, but "false"!
print("\n++++++ PreProcess failed.")
newtonSuccess = false
break
end
end
timeDisc:set_stage(stage)
-- setup time Disc for old solutions and timestep size
timeDisc:prepare_step(solTimeSeries, currdt)
-- prepare newton solver
if newtonSolver:prepare(u) == false then
print ("\n++++++ Newton solver failed."); exit();
end
-- apply newton solver
newtonSuccess = newtonSolver:apply(u)
-- start over again if failed
if newtonSuccess == false then break end
-- call post process
if postProcess ~= nil then
pp_res = postProcess(u, step, timeDisc:future_time(), currdt)
if type(pp_res) == "boolean" and pp_res == false then -- i.e. not nil, not something else, but "false"!
print("\n++++++ PostProcess failed.")
newtonSuccess = false
break
end
end
--total_linsolver_calls()
-- push oldest solutions with new values to front, oldest sol pointer is poped from end
if timeScheme:lower() == "bdf" and step < orderOrTheta then
print("++++++ BDF: Increasing order to "..step+1)
timeDisc:set_order(step+1)
solTimeSeries:push(u:clone(), timeDisc:future_time())
else
local oldestSol = solTimeSeries:oldest()
VecAssign(oldestSol, u)
solTimeSeries:push_discard_oldest(oldestSol, timeDisc:future_time())
end
if not (bFinishTimeStep == nil) and bFinishTimeStep then
timeDisc:finish_step_elem(solTimeSeries, u:grid_level())
end
if timeDisc:num_stages() > 1 then
print(" +++ STAGE " .. stage .. " END ++++++")
end
end -- loop over the stages
if newtonSuccess and finalizeTimeStep ~= nil then
pp_res = finalizeTimeStep(u, step, time, currdt)
if type(pp_res) == "boolean" and pp_res == false then -- i.e. not nil, not something else, but "false"!
write("\n++++++ Finalization of the time step failed. ")
newtonSuccess = false
else
pp_res = true
end
end
if pp_res == false then break end
if newtonSuccess == false and newtonLineSearchFallbacks ~= nil then
if newtonLineSearchFallbacks[newtonTry] == nil or newtonSolver:last_num_newton_steps() == 0 then
write("\n++++++ Adaptive Newton failed.")
break
else
newtonSolver:set_line_search(newtonLineSearchFallbacks[newtonTry])
write("Restarting Newton method with line search fallback " .. newtonTry .. ".\n");
newtonTry = newtonTry + 1
end
else
break
end
end -- newtonLineSearchFallbacks
-- call post process
if newtonSuccess == false then
currdt = currdt * reductionFactor;
write("\n++++++ Newton method failed. ");
write("Trying decreased stepsize " .. currdt .. ".\n");
if(bSuccess == false and currdt < minStepSize) then
write("++++++ Time Step size "..currdt.." below minimal step ")
write("size "..minStepSize..". Cannot solve problem. Aborting.");
test.require(false, "Time Solver failed.")
end
bSuccess = false
if rewindTimeStep ~= nil then
rewindTimeStep(u, step, time, currdt)
end
else
-- update new time
time = timeDisc:future_time()
nlsteps = nlsteps + newtonSolver:num_newton_steps()
bSuccess = true
end
end -- while bSuccess == false
-- save this solution if the restard with a smaller time step is possible
if uOld ~= nil then
VecAssign (uOld, u)
end
-- plot solution
if type(out) == "function" then out(u, step, time)
elseif type(out) == "userdata" then out:print(filename, u, step, time)
end
print("++++++ TIMESTEP "..step.." END (current time: " .. time .. ") ++++++");
if useCheckpointing then
----------------------------------------------------------
--- Write Checkpoint if necessary
util.WriteCheckpointIntervallic(u, time, {time=time, step=step, endTime=endTime})
----------------------------------------------------------
end
end
if useCheckpointing and timeDisc:num_stages() > 1 then
ug_warning("WARNING: Checkpointing won't work at the moment with timeDisc:num_stages() > 1")
end
if type(out) == "userdata" then out:write_time_pvd(filename, u) end
return step, time
end
--!
--! @param u [in] GridFunction with Startvalues, [out] Solution"
--! @param domainDisc Domain Discretization
--! @param solver Linear or Nonlinear Solver
--! @param out a VTKOutput (pass nil for no output)
--! @param filename filename for output
--! @param timeScheme Name of time step scheme:
--! Theta, ImplEuler, ExplEuler, Crank-Nicolson
--! Alexander, FracStep, BDF
--! @param orderOrTheta theta param if 'Theta', order if 'BDF'
--! @param startTime start time point
--! @param endTime end time point")
--! @param maxStepSize maximal step sized used
--! @param minStepSize (optinal) minimal step sized used
--! @param reductionFactor (optinal) factor by which the step size is
--! reduced, if the problem was not solved.
--! Iterated until minStepSize is reached.
--! @param useCheckpointing (optional) if true, use checkpointing.
function util.SolveLinearTimeProblem(
u,
domainDisc,
linSolver,
out,
filename,
timeScheme,
orderOrTheta,
startTime,
endTime,
maxStepSize,
minStepSize,
reductionFactor,
useCheckpointing)
if u == nil then
print("SolveLinearTimeProblem: Illegal parameters: No grid function for the solution specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if domainDisc == nil then
print("SolveLinearTimeProblem: Illegal parameters: No domain discretization specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if linSolver == nil then
print("SolveLinearTimeProblem: Illegal parameters: No lin. solver specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if timeScheme == nil then
print("SolveLinearTimeProblem: Illegal parameters: No time scheme specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if startTime == nil or endTime == nil then
print("SolveLinearTimeProblem: Illegal parameters: Start or end time not specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
if maxStepSize == nil then
print("SolveLinearTimeProblem: Illegal parameters: No max. time step specified.")
util.PrintUsageOfSolveTimeProblem()
exit()
end
-- check parameters
if minStepSize == nil then minStepSize = maxStepSize end
if reductionFactor == nil then reductionFactor = 0.5 end
-- create time disc
local timeDisc = util.CreateTimeDisc(domainDisc, timeScheme, orderOrTheta)
if timeScheme:lower() == "alexander" or
timeScheme:lower() == "fracstep" then
print("Only Theta, ImplEuler, ExplEuler, Crank-Nicolson, BDF supported.")
print("For Multistage use Nonlinear time loop.")
print("Aborting")
exit()
end
-- print newtonSolver setup
print("SolveLinearTimeProblem, Linear Solver setup:")
print(linSolver:config_string())
-- start
local time = startTime
local step = 0
if useCheckpointing then
--- Read Checkpoint if necessary
if util.HasParamOption("-restartWithCheckpoint") then
cp = util.ReadCheckpoint(u)
if cp ~= nil then
time = cp.myData.time
step = cp.myData.step
end
end
end
-- write start solution
print(">> Writing start values")
if not (out==nil) then out:print(filename, u, step, time) end
-- store grid function in vector of old solutions
local solTimeSeries = SolutionTimeSeries()
solTimeSeries:push(u:clone(), time)
local gl = u:grid_level()
-- matrix and vectors
local A = AssembledLinearOperator(timeDisc, gl)
local b = u:clone()
-- set order for bdf to 1 (initially)
if timeScheme:lower() == "bdf" then timeDisc:set_order(1) end
local assembled_dt = nil
while time < endTime do
step = step + 1
print("++++++ TIMESTEP "..step.." BEGIN (current time: " .. time .. ") ++++++");
-- initial time step size
-- assure, that not reaching beyond end of interval and care for round-off
local currdt = maxStepSize
if time+currdt > endTime then currdt = endTime - time end
if ((endTime - (time+currdt))/currdt) < 1e-8 then currdt = endTime - time end
-- try time step
local bSuccess = false;
while bSuccess == false do
TerminateAbortedRun()
print("++++++ Time step size: "..currdt);
-- reassemble matrix if necessary
if not(currdt == assembled_dt) then
print("++++++ Assembling Matrix/Rhs for step size "..currdt);
timeDisc:prepare_step(solTimeSeries, currdt)
timeDisc:assemble_linear(A, b, gl)
linSolver:init(A, u)
assembled_dt = currdt
else
timeDisc:prepare_step(solTimeSeries, currdt)
timeDisc:assemble_rhs(b, gl)
end
-- apply linear solver
if linSolver:apply(u,b) == false then
currdt = currdt * reductionFactor;
write("\n++++++ Linear solver failed. ");
write("Trying decreased stepsize " .. currdt .. ".\n");
else
bSuccess = true;
end
-- check valid step size
if(bSuccess == false and currdt < minStepSize) then
write("++++++ Time Step size "..currdt.." below minimal step ")
write("size "..minStepSize..". Cannot solve problem. Aborting.");
test.require(false, "Time Solver failed.")
end
end
-- update new time
time = solTimeSeries:time(0) + currdt
-- push oldest solutions with new values to front, oldest sol pointer is poped from end
if timeScheme:lower() == "bdf" and step < orderOrTheta then
print("++++++ BDF: Increasing order to "..step+1)
timeDisc:set_order(step+1)
solTimeSeries:push(u:clone(), time)
else
oldestSol = solTimeSeries:oldest()
VecScaleAssign(oldestSol, 1.0, u)
solTimeSeries:push_discard_oldest(oldestSol, time)
end
-- plot solution
if not (out==nil) then out:print(filename, u, step, time) end
--SaveVectorForConnectionViewer(u, filename.."_t"..step..".vec")
print("++++++ TIMESTEP "..step.." END (current time: " .. time .. ") ++++++");
if useCheckpointing then
----------------------------------------------------------
--- Write Checkpoint if necessary
util.WriteCheckpointIntervallic(u, time, {time=time, step=step, endTime=endTime})
----------------------------------------------------------
end
end
if not (out==nil) then out:write_time_pvd(filename, u) end
if useCheckpointing and timeDisc:num_stages() > 1 then
ug_warning("WARNING: Checkpointing won't work at the moment with timeDisc:num_stages() > 1")
end
end
--! Time stepping with the adaptive step size. Returns number of time steps done and the last time.
--! @param u [in] GridFunction with Startvalues, [out] Solution"
--! @param domainDisc Domain Discretization
--! @param newtonSolver Nonlinear Solver
--! @param out a VTKOutput (pass nil for no output)
--! @param filename filename for output
--! @param startTime start time point
--! @param endTime end time point
--! @param dt time step
--! @param maxStepSize maximal step sized used
--! @param minStepSize (optional) minimal step sized used
--! @param adaptiveStepInfo adaptive stepping controls
--! @param bFinishTimeStep (optional) boolean if finish_timestep should be
--! called or not.
--! @param postProcess (optional) if passed, will be called after every time step.
--! @param startTSNo (optional) time step number of the initial condition (normally 0).
--! @param endTSNo (optional) if passed, stop after the time step with this number.
function util.SolveNonlinearProblemAdaptiveTimestep(
u,
domainDisc,
newtonSolver,
out,
filename,
startTime,
endTime,
dt,
minStepSize,
maxStepSize,
adaptiveStepInfo,
--reductionFactor,
--tol,
bFinishTimeStep,
postProcess,
startTSNo,
endTSNo)
local doControl = true
local doExtrapolation = true
local timeScheme = "ImplEuler"
local orderOrTheta = 1.0
if u == nil then
print("SolveNonlinearProblemAdaptiveTimestep: Illegal parameters: No grid function for the solution specified.")
exit()
end
if domainDisc == nil then
print("SolveNonlinearProblemAdaptiveTimestep: Illegal parameters: No domain discretization specified.")
exit()
end
if newtonSolver == nil then
print("SolveNonlinearProblemAdaptiveTimestep: Illegal parameters: No nonlin. solver specified.")
exit()
end
if startTime == nil then
print("SolveNonlinearProblemAdaptiveTimestep: Illegal parameters: Start time not specified.")
exit()
end
if endTime == nil and endTSNo == nil then
print("SolveNonlinearProblemAdaptiveTimestep: Illegal parameters: End time or number of steps not specified.")
exit()
end
if maxStepSize == nil then
print("SolveNonlinearProblemAdaptiveTimestep: Illegal parameters: No max. time step specified.")
exit()
end
-- read adaptive stuff
local tol = adaptiveStepInfo["TOLERANCE"] or 1e-3 -- tolerance
local red = adaptiveStepInfo["REDUCTION"] or 0.5 -- reduction
local inc_fac = adaptiveStepInfo["INCREASE"] or 1.5 -- increase of time step
local safety_fac = adaptiveStepInfo["SAFETY"] or 0.8 -- safety factor
local errorEst = adaptiveStepInfo["ESTIMATOR"]
-- check parameters
if filename == nil then filename = "sol" end
if minStepSize == nil then minStepSize = maxStepSize end
-- if red == nil then red = 0.5 end -- reduction of time step
-- if inc_fac == nil then inc_fac = 1.5 end
-- if errorEst == nil then errorEst = Norm2Estimator() end
-- if tol == nil then
-- if safety_fac == nil then safety_fac = 0.8 end
-- create time disc
local timeDisc = util.CreateTimeDisc(domainDisc, timeScheme, orderOrTheta)
-- print newtonSolver setup
print("SolveNonlinearTimeProblem, Newton Solver setup:")
print(newtonSolver:config_string())
-- start
local time = startTime
local step = startTSNo or 0
local nlsteps = 0;
-- write start solution
print(">> Writing start values")
if type(out) == "function" then out(u, step, time) end
if type(out) == "userdata" then out:print(filename, u, step, time) end
-- store grid function in vector of old solutions
local solTimeSeries = SolutionTimeSeries()
local old = u:clone()
solTimeSeries:push(old, time)
-- update newtonSolver
local nlop = AssembledOperator(timeDisc, u:grid_level())
newtonSolver:init(nlop)
-- extra options for adaptive scheme
local timeDisc2
local solTimeSeries2
local nlop2
local timex
local u2, old2, aux
if (doControl) then
timeDisc2 = util.CreateTimeDisc(domainDisc, timeScheme, orderOrTheta)
nlop2 = AssembledOperator(timeDisc2, u:grid_level())
old2 = old:clone() -- second solution
u2 = old:clone() -- second solution
aux = old:clone()
-- time series
solTimeSeries2 = SolutionTimeSeries()
solTimeSeries2:push(old2, time)
if (doExtrapolation) then
-- Aitken-Neville-type time extrapolation
timex = AitkenNevilleTimex({1,2}, errorEst)
end
end
-- set order for bdf to 1 (initially)
if timeScheme:lower() == "bdf" then timeDisc:set_order(1) end
local currdt = dt
while ((endTime == nil) or (time < endTime)) and ((endTSNo == nil) or (step < endTSNo)) do
step = step + 1
print("++++++ TIMESTEP "..step.." BEGIN (current time: " .. time .. ") "..endTime.."++++++");
-- initial time step size
-- assure, that not reaching beyond end of interval
currdt = math.min(currdt, endTime-time);
-- try time step
local bSuccess = false;
while bSuccess == false do
TerminateAbortedRun()
print("++++++ Time step size: "..currdt);
local dtold = currdt
-- setup time Disc for old solutions and timestep size
timeDisc:prepare_step(solTimeSeries, currdt)
newtonSolver:init(nlop)
-- prepare newton solver
if newtonSolver:prepare(u) == false then
print ("\n++++++ Newton solver failed."); exit();
end
-- apply newton solver
if newtonSolver:apply(u) == false then
currdt = currdt * red;
write("\n++++++ Newton solver failed. ");
write("Trying decreased stepsize " .. currdt .. ".\n");
else
bSuccess = true;
end
-- time step control
-- compute solution u2
if (bSuccess and doControl) then
newtonSolver:init(nlop2)
----------------------------
-- step 1/2
print("Control 1/2:");
-- time2 = time-tau/2; -- intermediate time step
--VecScaleAdd2(u2, 1.0-0.5*currdt, old, 0.5*currdt, u); -- w/ linear interpolation (first guess)
timeDisc2:prepare_step(solTimeSeries2, 0.5*currdt)
if newtonSolver:prepare(u2) == false then
print ("Newton solver failed at step "..step.."+1/2.");
exit();
end
if newtonSolver:apply(u2) == false then
print ("Newton solver failed at step "..step.."+1/2.");
end
----------------------------
-- step 2/2
print("Control 2/2:");
-- push back solution
time2 = time + 0.5*currdt
tmp2 = solTimeSeries2:oldest() -- solution at time t
VecScaleAssign(tmp2, 1.0, u2) -- is removed and replaced by u2(t+tau/2)
solTimeSeries2:push_discard_oldest(tmp2, time2) -- re-insert as new solution
-- (now old2 is discarded)
timeDisc2:prepare_step(solTimeSeries2, 0.5*currdt)
if newtonSolver:prepare(u2) == false then
print ("Newton solver failed at step "..step.."+2/2.");
exit();
end
if newtonSolver:apply(u2) == false then
print ("Newton solver failed at step "..step.."+2/2.");
bSuccess = false;
end
if (doExtrapolation) then
-- extrapolation (more accurate)
timex:set_solution(u, 0)
timex:set_solution(u2, 1)
timex:apply()
eps = timex:get_error_estimate(1)
else
-- no extrapolation (less accurate)
VecScaleAdd2(aux, 1.0, u, -1.0, u2);
local l2_fine_est = L2Norm(aux, "c", 2);
eps = 2.0*l2_fine_est;
l2_ex_err = "---";
l2_ex_est = "---";
end
-------------------------
-- Adaptive step control
-------------------------
local lambda = math.pow(safety_fac*tol/eps, 0.5) -- (eps<=tol) implies (tol/eps >= 1)
dtEst = lambda*currdt
print("dtEst= "..dtEst..", eps="..eps..", tol = " ..tol..", fac = "..lambda)
-- determine potential new step size
print ("EULEX-DT:\t".. dtEst .."\t"..inc_fac*currdt.."\t"..maxStepSize);
currdt = math.min(dtEst, inc_fac*currdt, maxStepSize)
if (eps <= tol) then
-- accept
print ("EULEX-ACCEPTING:\t".. time .."\t"..dtold.."\t"..currdt.."\tq=\t2");
bAcceptStep = true;
bSuccess =true;
else
-- discard
bAcceptStep = false;
bSuccess = false;
-- reset initial guess (important for non-linear coarse problem)
VecScaleAssign(u, 1.0, old)
-- reset solTimeSeries2
utmp = solTimeSeries2:oldest()
VecScaleAssign(utmp, 1.0, old)
solTimeSeries2:push_discard_oldest(utmp, time)
end
end -- if (bSuccess and doControl)
-- check valid step size
if(bSuccess == false and currdt < minStepSize) then
write("++++++ Time Step size "..currdt.." below minimal step ")
write("size "..minStepSize..". Cannot solve problem. Aborting.");
test.require(false, "Time Solver failed.")
end
-- start over again if failed
if bSuccess == false then
print ("EULEX-REJECTING:\t".. time .."\t"..dtold.."\t"..currdt.."\tq=\t2");
break
end
-- update new time
time = timeDisc:future_time()
nlsteps = nlsteps + newtonSolver:num_newton_steps()
-- push oldest solutions with new values to front, and
-- pop oldest sol pointer from end
oldestSol = solTimeSeries:oldest()
VecScaleAssign(oldestSol, 1.0, u2)
solTimeSeries:push_discard_oldest(oldestSol, time)
if (doControl) then
-- do the same for second
oldestSol = solTimeSeries2:oldest()
VecScaleAssign(oldestSol, 1.0, u2)
solTimeSeries2:push_discard_oldest(oldestSol, time)
end
if not (bFinishTimeStep == nil) and (bFinishTimeStep) then
timeDisc:finish_step_elem(solTimeSeries, u:grid_level())
end
end -- while bSuccess == false -- aka 'try time step'
-- step was executed successfully
-- call post process
if type(postProcess) == "function" then postProcess(u, step, time, currdt) end
-- plot solution
if type(out) == "function" then out(u, step, time) end
if type(out) == "userdata" then out:print(filename, u, step, time) end
-- print("Integral("..time..")="..Integral(massLinker, u, "INNER2"))
print("++++++ TIMESTEP "..step.." END (current time: " .. time .. ", nlsteps: "..nlsteps..") ++++++");
end
if type(out) == "userdata" then out:write_time_pvd(filename, u) end
return step, time
end
function util.SolveNonlinearProblemAdaptiveLimex(
u,
domainDisc,
newtonSolver,
out,
filename,
startTime,
endTime,
dt,
minStepSize,
maxStepSize,
adaptiveStepInfo,
--reductionFactor,
--tol,
bFinishTimeStep,
postProcess,
startTSNo,
endTSNo)
-- read adaptive stuff
local tol = adaptiveStepInfo["TOLERANCE"]
local red = adaptiveStepInfo["REDUCTION"]
local inc_fac = adaptiveStepInfo["INCREASE"]
local safety_fac = adaptiveStepInfo["SAFETY"]
local errorEst = adaptiveStepInfo["ESTIMATOR"]
-- check parameters
if filename == nil then filename = "sol" end
if minStepSize == nil then minStepSize = maxStepSize end
if red == nil then red = 0.5 end -- reduction of time step
if inc_fac == nil then inc_fac = 1.5 end -- increase of time step
if errorEst == nil then
print "WARNING: Error estimator not set. Default is euclidean norm! "
errorEst = Norm2ErrorEst()
end
if tol == nil then
tol = 1e-3
print ("WARNING: Using default tolerance "..tol)
end
if safety_fac == nil then safety_fac = 0.8 end -- safety factor
local doControl = true
local doExtrapolation = true
local timeScheme = "ImplEuler"
local orderOrTheta = 1.0
if u == nil or domainDisc == nil or newtonSolver == nil or timeScheme == nil
or startTime == nil or endTime == nil or maxStepSize == nil then
print("Wrong usage found. Please specify parameters as below:")
if (u == nil) then print ("Did not find u!"); end;
if (domainDisc == nil) then print ("Did not find domainDisc!"); end;
if (timeScheme == nil) then print ("Did not find timeScheme!"); end;
if (startTime == nil) then print ("Did not find endTime!"); end;
if (endTime == nil) then print ("Did not find endTime!"); end;
if (maxStepSize == nil) then print ("Did not find maxStepSize!"); end;
util.PrintUsageOfSolveTimeProblem()
exit()
end
print ("maxStepSize ="..maxStepSize)
print ("minStepSize ="..minStepSize)
print ("startTime ="..startTime)
print ("endTime ="..endTime)
-- check parameters
if filename == nil then filename = "sol" end
if minStepSize == nil then minStepSize = maxStepSize end
if reductionFactor == nil then reductionFactor = 0.5 end
-- create time disc
local timeDisc = LinearImplicitEuler(domainDisc)
-- print newtonSolver setup
print("SolveNonlinearTimeProblem, Newton Solver setup:")
print(newtonSolver:config_string())
-- start
local time = startTime
local step = startTSNo or 0
local nlsteps = 0;
-- write start solution
print(">> Writing start values")
if type(out) == "function" then out(u, step, time) end
if type(out) == "userdata" then out:print(filename, u, step, time) end
-- store grid function in vector of old solutions
local solTimeSeries = SolutionTimeSeries()
local old = u:clone()
solTimeSeries:push(old, time)
-- update newtonSolver
local nlop = AssembledOperator(timeDisc, u:grid_level())
newtonSolver:init(nlop)
-- extra options for adaptive scheme
local timeDisc2
local solTimeSeries2
local nlop2
local timex
local u2, old2, aux
if (doControl) then
timeDisc2 = LinearImplicitEuler(domainDisc)
nlop2 = AssembledOperator(timeDisc2, u:grid_level())
old2 = old:clone() -- second solution
u2 = old:clone() -- second solution
aux = old:clone()
-- time series
solTimeSeries2 = SolutionTimeSeries()
solTimeSeries2:push(old2, time)
if (doExtrapolation) then
-- Aitken-Neville-type time extrapolation
timex = AitkenNevilleTimex({1,2}, errorEst)
end
end
-- set order for bdf to 1 (initially)
-- if timeScheme:lower() == "bdf" then timeDisc:set_order(1) end
local currdt = dt
while ((endTime == nil) or (time < endTime)) and ((endTSNo == nil) or (step < endTSNo)) do
step = step + 1
print("++++++ TIMESTEP "..step.." BEGIN (current time: " .. time .. ") "..endTime.."++++++");
-- initial time step size
-- assure, that not reaching beyond end of interval
currdt = math.min(currdt, endTime-time);
-- try time step
local bSuccess = false;
while bSuccess == false do
TerminateAbortedRun()
print("++++++ Time step size: "..currdt);
-- setup time Disc for old solutions and timestep size
timeDisc:prepare_step(solTimeSeries, currdt)
newtonSolver:init(nlop)
-- prepare newton solver
if newtonSolver:prepare(u) == false then
print ("\n++++++ Newton solver failed."); exit();
end
-- apply newton solver
if newtonSolver:apply(u) == false then
currdt = currdt * reductionFactor;
write("\n++++++ Newton solver failed. ");
write("Trying decreased stepsize " .. currdt .. ".\n");
else
bSuccess = true;
end
-- time step control
-- compute solution u2
if (bSuccess and doControl) then
newtonSolver:init(nlop2)
----------------------------
-- step 1/2
print("Control 1/2:");
-- time2 = time-tau/2; -- intermediate time step
--VecScaleAdd2(u2, 1.0-0.5*currdt, old, 0.5*currdt, u); -- w/ linear interpolation (first guess)
timeDisc2:prepare_step(solTimeSeries2, 0.5*currdt)
if newtonSolver:prepare(u2) == false then print ("Newton solver failed at step "..step.."+1/2."); exit(); end
if newtonSolver:apply(u2) == false then
print ("Newton solver failed at step "..step.."+1/2.");
end
----------------------------
-- step 2/2
print("Control 2/2:");
-- push back solution
tmp2 = solTimeSeries2:oldest() -- solution at time t
VecScaleAssign(tmp2, 1.0, u2) -- is removed and replaced by u2(t+tau/2)
solTimeSeries2:push_discard_oldest(tmp2, time + 0.5*currdt) -- re-insert as new solution
-- (now old2 is discarded)
timeDisc2:prepare_step(solTimeSeries2, 0.5*currdt)
if newtonSolver:prepare(u2) == false then print ("Newton solver failed at step "..step.."+2/2."); exit(); end
if newtonSolver:apply(u2) == false then
print ("Newton solver failed at step "..step.."+2/2.");
bSuccess = false;
end
if (doExtrapolation) then
-- extrapolation (more accurate)
timex:set_solution(u, 0)
timex:set_solution(u2, 1)
timex:apply()
eps = timex:get_error_estimate(1)
--out:print("ExSol.vtu", u2, step, time)
else
-- no extrapolation (less accurate)
VecScaleAdd2(aux, 1.0, u, -1.0, u2);
local l2_fine_est = L2Norm(aux, "c", 2);
eps = 2.0*l2_fine_est;
l2_ex_err = "---";
l2_ex_est = "---";
end
--vtk = VTKOutput()
--vtk:select_nodal(GridFunctionNumberData(u, "c"), "CNodal")
--vtk:select_nodal(GridFunctionNumberData(u, "p"), "PNodal")
--out:print("CoarseLimexSol.vtu", u, step, time)
--out:print("FineLimexSol.vtu", u2, step, time)
--print("TIME_ERROR (t="..time+tau..", |u|="..l2normB.. ") :\t" .. l2_coarse_err .. "\t"..l2_fine_err .. "\t"..l2_ex_err .. "\| ---\t"..l2_fine_est .. "\t"..l2_ex_est.. "\t"..eps)
--file:write(time+tau.."\t" ..l2normB.. "\t" .. l2_coarse_err .. "\t"..l2_fine_err .. "\t"..l2_ex_err .. "\t"..l2_fine_est .. "\t"..l2_ex_est.. "\t"..eps.."\n")
--file:flush()
-------------------------
-- Adaptive step control
-------------------------
--dtEst = math.pow(0.9*tol/eps, 0.5)*currdt -- (eps<=tol) implies (tol/eps >= 1)
--print("dtEst= "..dtEst..", eps="..eps..", tol = " ..tol..", fac = "..math.pow(0.9*tol/eps, 0.5))
local lambda = math.pow(safety_fac*tol/eps, 0.5) -- (eps<=tol) implies (tol/eps >= 1)
dtEst = lambda*currdt
print("dtEst= "..dtEst..", eps="..eps..", tol = " ..tol..", fac = "..lambda)
-- determine potential new step size
currdt = math.min(dtEst, inc_fac*currdt, maxStepSize)
if (eps <= tol) then
-- accept
print ("ACCEPTING solution, dtnew="..currdt);
bAcceptStep = true;
bSuccess =true;
else
-- discard
print ("DISCARDING solution, dtnew="..currdt);
bAcceptStep = false;
bSuccess = false;
-- reset solTimeSeries2
utmp = solTimeSeries2:oldest()
VecScaleAssign(utmp, 1.0, old)
solTimeSeries2:push_discard_oldest(utmp, time)
end
end
-- check valid step size
if(bSuccess == false and currdt < minStepSize) then
write("++++++ Time Step size "..currdt.." below minimal step ")
print("size "..minStepSize..". Cannot solve problem. Aborting.");
test.require(false, "Time Solver failed.")
end
-- start over again if failed
if bSuccess == false then break end
-- update new time
time = timeDisc:future_time()
nlsteps = nlsteps + newtonSolver:num_newton_steps()
-- push oldest solutions with new values to front, oldest sol pointer is poped from end
oldestSol = solTimeSeries:oldest()
VecScaleAssign(oldestSol, 1.0, u2)
solTimeSeries:push_discard_oldest(oldestSol, time)
if (doControl) then
-- do the same for second
oldestSol = solTimeSeries2:oldest()
VecScaleAssign(oldestSol, 1.0, u2)
solTimeSeries2:push_discard_oldest(oldestSol, time)
end
if not (bFinishTimeStep == nil) and bFinishTimeStep then
timeDisc:finish_step_elem(solTimeSeries, u:grid_level())
end
end
-- call post process
if type(postProcess) == "function" then postProcess(u, step, time, currdt) end
-- plot solution
if type(out) == "function" then out(u, step, time) end
if type(out) == "userdata" then out:print(filename, u, step, time) end
print("++++++ TIMESTEP "..step.." END (current time: " .. time .. ", nlsteps: "..nlsteps..") ++++++");
end
if type(out) == "userdata" then out:write_time_pvd(filename, u) end
return step, time
end
--[[!
\}
]]--
|
ITEM.name = "Euro Notes"
ITEM.description = "A bundle of European currency."
ITEM.longdesc = "While this currency is not the primary way of trading in the zone, it does still retain value to people residing in european countries, and other financially interested people. Aside from a trading perspective, foreign currency is practically useless in an alienated environment such as the zone."
ITEM.model = "models/kek1ch/money_euro.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.price = 52 -- lower than real conversion rate, intended
ITEM.quantity = 5000
ITEM.flatweight = 0
ITEM.weight = 0.001
ITEM.exRender = true
ITEM.iconCam = {
pos = Vector(0, 0, 200),
ang = Angle(90, 0, 0),
fov = 2.5,
}
function ITEM:GetPrice()
return self.price * self:GetData("quantity", self.quantity)
end
ITEM.functions.combine = {
OnCanRun = function(item, data)
if !data then
return false
end
local targetItem = ix.item.instances[data[1]]
if targetItem.uniqueID == item.uniqueID then
return true
else
return false
end
end,
OnRun = function(item, data)
local targetItem = ix.item.instances[data[1]]
local targetQuantDiff = targetItem.quantity - targetItem:GetData("quantity", targetItem.quantity)
local localQuant = item:GetData("quantity", item.quantity)
local targetQuant = targetItem:GetData("quantity", targetItem.quantity)
item.player:EmitSound("stalkersound/inv_properties.mp3", 110)
if targetQuantDiff >= localQuant then
targetItem:SetData("quantity", targetQuant + localQuant)
return true
else
item:SetData("quantity", localQuant - targetQuantDiff)
targetItem:SetData("quantity", targetItem.quantity)
return false
end
end,
}
function ITEM:OnInstanced()
if (!self:GetData("quantity")) then
self:SetData("quantity", 1)
end
end
|
--redis-cli --eval /Users/laukikragji/Documents/Git/Local/partition-pg/lua/identity.lua T1 Inventory , 50
local requested_type_key = KEYS[1]
local inventory_key = KEYS[2]
local requested_range = tonumber(ARGV[1])
local result = {}
local parseResourceDefinition = function (inputstr)
local sep=","
local t={}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, tonumber(str))
end
return t
end
local loadNextResource = function (type_key)
redis.call("DEL",type_key)
if redis.call("EXISTS",inventory_key) == 0 then return {-1,"No resources available"} end
local next_resource = redis.call("LPOP",inventory_key)
local new_resource_def = parseResourceDefinition(next_resource)
redis.call("HMSET",type_key, "DBID", new_resource_def[1], "TBID",new_resource_def[2], "ROWS", new_resource_def[3], "OFF", "1")
return {0}
end
if redis.call("EXISTS",requested_type_key) == 0 then
local status = loadNextResource(requested_type_key)
if(status[1] ~= 0) then return status end
end
local db_id = tonumber(redis.call("HGET",requested_type_key,"DBID"))
local tb_id = tonumber(redis.call("HGET",requested_type_key,"TBID"))
local max_rows = tonumber(redis.call("HGET",requested_type_key,"ROWS"))
local offset = tonumber(redis.call("HGET",requested_type_key,"OFF"))
while(requested_range > 0)
do
local capacity = (max_rows - offset) + 1
if capacity > requested_range then
if table.getn(result) == 0 then table.insert(result,{requested_range,db_id,tb_id,offset,"START1"}) end --START1
offset = offset + requested_range
redis.call("HMSET",requested_type_key,"OFF",offset)
requested_range = 0
table.insert(result,{1,db_id,tb_id,offset-1,"END1"}) --END1
else
table.insert(result,{requested_range,db_id,tb_id,offset,"START2"}) --START2
requested_range = requested_range - capacity
if requested_range <= 0 then table.insert(result,{1,db_id,tb_id,max_rows,"END2"}) end --END2
offset = 1
local status = loadNextResource(requested_type_key)
if(status[1] ~= 0) then
if table.getn(result) == 0 then return status end
table.insert(result, 1, -2)-- Partial Success
return result
end
db_id = tonumber(redis.call("HGET",requested_type_key,"DBID"))
tb_id = tonumber(redis.call("HGET",requested_type_key,"TBID"))
max_rows = tonumber(redis.call("HGET",requested_type_key,"ROWS"))
offset = tonumber(redis.call("HGET",requested_type_key,"OFF"))
end
end
table.insert(result,1,0)
return result
--Retuns
--[0]: -1 = No more space or ERROR; -2 Partial Sucess; 0 = Sucess;
--[N][0]: Seq Counter
--[N][1]: DB ID
--[N][2]: Table ID
--[N][3]: Row ID
|
local SentientAxe = Class(function(self, inst)
self.inst = inst
self.time_to_convo = 10
self.inst:ListenForEvent("ondropped", function() self:OnDropped() end)
self.inst:ListenForEvent("equipped", function(_, data) self:OnEquipped(data.owner) end)
self.inst:ListenForEvent("finishedwork", function(_, data) self:OnFinishedWork(data.target, data.action) end, GetPlayer())
self.inst:ListenForEvent("beavernessdelta", function(_, data) self:OnBeaverDelta(data.oldpercent, data.newpercent) end, GetPlayer())
self.inst:ListenForEvent("beaverstart", function(_, data) self:OnBecomeBeaver() end, GetPlayer())
self.inst:ListenForEvent("beaverend", function(_, data) self:OnBecomeHuman() end, GetPlayer())
local dt = 5
self.inst:DoPeriodicTask(dt, function() self:OnUpdate(dt) end)
self.warnlevel = 0
end)
function SentientAxe:OnFinishedWork(target, action)
if action == ACTIONS.CHOP and
self.inst.components.inventoryitem.owner == GetPlayer() and
self.inst.components.equippable:IsEquipped() and
(GetPlayer().components.beaverness and GetPlayer().components.beaverness:GetPercent() < .25) then
self:Say(STRINGS.LUCY.on_chopped)
end
end
function SentientAxe:OnBeaverDelta(old, new)
if GetPlayer().components.beaverness:IsBeaver() then return end
if new > old then
if new > .33 and old <= .33 and self.warnlevel < 1 then
self:Say(STRINGS.LUCY.beaver_up_early)
self.warnlevel = 1
elseif new > .66 and old <= .66 and self.warnlevel < 2 then
self:Say(STRINGS.LUCY.beaver_up_mid)
self.warnlevel = 2
elseif new > .9 and old <= .9 and self.warnlevel < 3 then
self:Say(STRINGS.LUCY.beaver_up_late)
self.warnlevel = 3
self.washigh = true
end
else
if self.warnlevel == 3 and new < .66 then
self.warnlevel = 2
elseif self.warnlevel == 2 and new < .33 then
self.warnlevel = 1
end
if new <= 0 and old > 0 then
if self.washigh then
local warn_sounds = {"dontstarve/characters/woodie/lucy_warn_1","dontstarve/characters/woodie/lucy_warn_2","dontstarve/characters/woodie/lucy_warn_3"}
self:Say(STRINGS.LUCY.beaver_down_washigh, warn_sounds[self.warnlevel])
self.warnlevel = 0
self.washigh = false
end
end
end
end
function SentientAxe:OnBecomeHuman()
self:Say(STRINGS.LUCY.transform_woodie)
end
function SentientAxe:OnBecomeBeaver()
self:Say(STRINGS.LUCY.transform_beaver, "dontstarve/characters/woodie/lucy_transform")
end
function SentientAxe:OnDropped()
if GetPlayer().components.beaverness and GetPlayer().components.beaverness:IsBeaver() then
self:Say(STRINGS.LUCY.transform_beaver)
else
self:Say(STRINGS.LUCY.on_dropped)
end
end
function SentientAxe:OnEquipped(picked_up_by)
if picked_up_by == GetPlayer() then
self:Say(STRINGS.LUCY.on_pickedup)
end
end
function SentientAxe:OnUpdate(dt)
self.time_to_convo = self.time_to_convo - dt
if self.time_to_convo <= 0 then
self:MakeConversation()
end
end
function SentientAxe:Say(list, sound_override)
self.sound_override = sound_override
self.inst.components.talker:Say(list[math.random(#list)])
self.time_to_convo = math.random(60, 120)
end
function SentientAxe:MakeConversation()
local grand_owner = self.inst.components.inventoryitem:GetGrandOwner()
local owner = self.inst.components.inventoryitem.owner
local quiplist = nil
if owner == GetPlayer() then
if self.inst.components.equippable:IsEquipped() then
--currently equipped
quiplist = STRINGS.LUCY.equipped
else
--in player inventory
end
elseif owner == nil then
--on the ground
quiplist = STRINGS.LUCY.on_ground
elseif grand_owner ~= owner and grand_owner == GetPlayer() then
--in a backpack
quiplist = STRINGS.LUCY.in_container
elseif owner and owner.components.container then
--in a container
quiplist = STRINGS.LUCY.in_container
else
--owned by someone else
quiplist = STRINGS.LUCY.other_owner
end
if quiplist then
self:Say(quiplist)
end
end
return SentientAxe
|
local GameTime = CurTime()
local GameOver = false
local InvasionTime = 90
local SurviveTime = 900
if (SERVER) then
util.AddNetworkString("Gameover")
util.AddNetworkString("GameTime")
hook.Add("Tick","ZSTime",function()
if (!GameOver) then
if (!HasEnoughPlayers()) then
GameTime = CurTime()
ZombifiedPlayers = {}
for k,v in pairs(player.GetAllZombies()) do
if (v:Alive()) then
v.Zomb = nil
v:KillSilent()
end
end
return
end
local plz = player.GetAllZombies()
local pla = player.GetAllAlive()
local pls = player.GetAll()
if (#pla < 1) then Gameover(false)
elseif (GetGameTime() > SurviveTime) then Gameover(true)
elseif (#plz < 1 and GetGameTime() > InvasionTime) then
table.Random(player.GetAllAlive()):ZombifyPlayer("Zombie")
end
end
end)
hook.Add("PlayerAuthed","SyncGametime",function(pl)
timer.Simple(1,function()
net.Start("GameTime")
net.WriteUInt(math.ceil(GameTime),32)
net.Send(pl)
end)
end)
function Gameover(bool)
net.Start("Gameover")
net.WriteBit(bool)
net.Broadcast()
GameOver = true
timer.Simple(30,function() game.LoadNextMap() end)
end
else
local Music
local TogMus = 0
hook.Add("Tick","ZSTime",function()
if (!HasEnoughPlayers() and !GameOver) then
GameTime = CurTime()
for k,v in pairs(player.GetAllZombies()) do
if (v:Alive()) then
v.Zomb = nil
end
end
end
local lp = LocalPlayer()
if (lp:IsValid()) then
if (GameOver) then
if (TogMus != 1) then
if (Music) then Music:Stop() end
Music = CreateSound(lp,"mawzombiesurvival/music/over1.mp3")
Music:Play()
Music:ChangeVolume(0.4,0)
TogMus = 1
end
elseif (GetGameTime() > InvasionTime) then
if (TogMus != 2) then
if (Music) then Music:Stop() end
Music = CreateSound(lp,"mawzombiesurvival/music/battle1.mp3")
Music:Play()
Music:ChangeVolume(0.4,0)
TogMus = 2
end
else
if (TogMus != 3) then
if (Music) then Music:Stop() end
Music = CreateSound(lp,"mawzombiesurvival/music/prologue.mp3")
Music:Play()
Music:ChangeVolume(0.4,0)
TogMus = 3
end
end
end
end)
net.Receive("Gameover",function()
local Won = net.ReadBit()
if (Won == 1) then
GAMEMODE.WinData = {
Text = "Humans have won!",
Color = Color(0,100,255),
Time = CurTime()+30,
}
else
GAMEMODE.WinData = {
Text = "Zombies have won!",
Color = Color(0,250,0),
Time = CurTime()+30,
}
end
GameOver = true
end)
net.Receive("GameTime",function() GameTime = net.ReadUInt(32) end)
end
function GetGameTime()
return CurTime()-GameTime
end
function HasEnoughPlayers()
return (#player.GetAll() > 1)
end
|
-- Copyright (C) 2017 yushi studio <ywb94@qq.com>
-- Licensed to the public under the GNU General Public License v3.
local IPK_Version="20200406.1.36"
local m, s, o
local redir_run=0
local reudp_run=0
local sock5_run=0
local ssock5_run=0
local v2sock5_run=0
local server_run=0
local sserver_run=0
local v2server_run=0
local kcptun_run=0
local tunnel_run=0
local udp2raw_run=0
local udpspeeder_run=0
local gfw_count=0
local ad_count=0
local ip_count=0
local gfwmode=0
local pdnsd_run=0
local dnsforwarder_run=0
local dnscrypt_proxy_run=0
local chinadns_run=0
local dns2socks_run=0
local haproxy_run=0
local privoxy_run=0
if nixio.fs.access("/etc/dnsmasq.vssr/gfw_list.conf") then
gfwmode=1
end
local vssr= "vssr"
-- html constants
font_blue = [[<font color="green">]]
font_off = [[</font>]]
bold_on = [[<strong>]]
bold_off = [[</strong>]]
local fs = require "nixio.fs"
local sys = require "luci.sys"
local kcptun_version=translate("Unknown")
local kcp_file="/usr/bin/kcptun-client"
if not fs.access(kcp_file) then
kcptun_version=translate("Not exist")
else
if not fs.access(kcp_file, "rwx", "rx", "rx") then
fs.chmod(kcp_file, 755)
end
kcptun_version=sys.exec(kcp_file .. " -v | awk '{printf $3}'")
if not kcptun_version or kcptun_version == "" then
kcptun_version = translate("Unknown")
end
end
local udp2raw_version=translate("Unknown")
local udp2raw_file="/usr/bin/udp2raw"
if not fs.access(udp2raw_file) then
udp2raw_version=translate("Not exist")
else
if not fs.access(udp2raw_file, "rwx", "rx", "rx") then
fs.chmod(udp2raw_file, 755)
end
udp2raw_version=sys.exec(udp2raw_file .. " -h |grep 'git version' |awk -F ':' '{print $2}'|awk '{print $1}'")
if not udp2raw_version or udp2raw_version == "" then
udp2raw_version = translate("Unknown")
end
end
local udpspeeder_version=translate("Unknown")
local udpspeeder_file="/usr/bin/udpspeeder"
if not fs.access(udpspeeder_file) then
udpspeeder_version=translate("Not exist")
else
if not fs.access(udpspeeder_file, "rwx", "rx", "rx") then
fs.chmod(udpspeeder_file, 755)
end
udpspeeder_version=sys.exec(udpspeeder_file .. " -h |grep 'git version' |awk -F ':' '{print $2}'|awk '{print $1}'")
if not udpspeeder_version or udpspeeder_version == "" then
udpspeeder_version = translate("Unknown")
end
end
if gfwmode==1 then
gfw_count = tonumber(sys.exec("cat /etc/dnsmasq.vssr/gfw_list.conf | wc -l"))/2
if nixio.fs.access("/etc/dnsmasq.vssr/ad.conf") then
ad_count=tonumber(sys.exec("cat /etc/dnsmasq.vssr/ad.conf | wc -l"))
end
end
if nixio.fs.access("/etc/china_ssr.txt") then
ip_count = sys.exec("cat /etc/china_ssr.txt | wc -l")
end
function processlist()
local data = {}
local netf = {}
local k
local ps = luci.util.execi("/bin/busybox top -bn1 | egrep -v dnsmasq")
local nets = luci.util.execi("netstat -netupl | egrep -v dnsmasq | awk '{print $1,$4,_,$6,$7}'")
if not ps or not nets then
return
end
for line in nets do
-- tcp 0 0 127.0.0.1:1234 0.0.0.0:* LISTEN 5103/v2ray
-- udp 0 0 127.0.0.1:1234 0.0.0.0:* 5147/v2ray
-- local proto, ip, port, nid = line:match("([^%s]+) +.* +([^ ]*):(%d+) +.* +(%d+)\/.*")
local proto, ip, port, nid = line:match("([^%s]+) (.*):(%d+)[^%d]+(%d+)\/.*")
local idx = tonumber(nid)
if idx and ip then
local newstr = "://" .. ip .. ":" .. port
local isnew = (netf[idx] and netf[idx]['listen']) and netf[idx]['listen']:match(proto .. newstr) or false
netf[idx] = {
['listen'] = ((netf[idx] and netf[idx]['listen']) and (not isnew) and (netf[idx]['listen'] .. "\n" .. proto) or proto) .. newstr,
}
end
end
-- 5103 1 root S 661m 543% 0% /usr/bin/v2ray/v2ray -config /var/etc/shadowsocksr.json
for line in ps do
local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match(
"^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+.?) +(%d+%%) +(%d+%%) +(.+)"
)
if cmd then
local idx = tonumber(pid)
local bin, param, cfg = cmd:match("^.*\/([^ ]*) *([^ ]*) *\/var\/etc\/([^ ]*).*")
if idx and cfg then
local listen = "NONE"
if netf[idx] and netf[idx]['listen'] then
listen = netf[idx]['listen']
end
data[idx] = {
['PID'] = pid,
['COMMAND'] = bin,
['LISTEN'] = listen,
['CONFIG'] = cfg,
['%MEM'] = mem,
['%CPU'] = cpu,
}
end
end
end
return data
end
function printstat(status, form, name)
local tabs = {
["Global Client"] = "shadowsocksr.json",
["Game Mode UDP Relay"] = "shadowsocksr_u.json",
["PDNSD"] = "pdnsd.conf",
["DNS Forward"] = "shadowsocksr_d.json",
["SOCKS5 Proxy"] = "shadowsocksr_s.json",
["Global SSR Server"] = "shadowsocksr_0.json",
}
local stat = translate("Unknown")
local sname = stat
if tabs[name] and status then
stat = translate("Not Running")
for idx, cfg in pairs(status) do
if status[idx]['CONFIG'] and status[idx]['CONFIG'] == tabs[name] then
stat = font_blue .. bold_on .. translate("Running") .. bold_off .. " > " .. status[idx]['COMMAND'] .. " -c " .. status[idx]['CONFIG'] .. font_off
sname = translate(status[idx]['COMMAND'])
break
end
end
end
local section = form:field(DummyValue,name,translate(name) .. ": " .. sname)
section.rawhtml = true
section.value = stat
return section
end
procs=processlist()
local icount=sys.exec("ps -w | grep ssr-reudp |grep -v grep| wc -l")
if tonumber(icount)>0 then
reudp_run=1
else
icount=sys.exec("ps -w | grep ssr-retcp |grep \"\\-u\"|grep -v grep| wc -l")
if tonumber(icount)>0 then
reudp_run=1
end
end
if luci.sys.call("ps -w | grep ssr-retcp | grep -v grep >/dev/null") == 0 then
redir_run=1
end
if luci.sys.call("pidof ssr-local >/dev/null") == 0 then
sock5_run=1
end
if luci.sys.call("pidof ss-local >/dev/null") == 0 then
ssock5_run=1
end
if luci.sys.call("ps -w | grep v2-ssr-local | grep -v grep >/dev/null") == 0 then
v2sock5_run=1
end
if luci.sys.call("pidof privoxy >/dev/null") == 0 then
privoxy_run=1
end
if luci.sys.call("pidof kcptun-client >/dev/null") == 0 then
kcptun_run=1
end
if luci.sys.call("pidof ssr-server >/dev/null") == 0 then
server_run=1
end
if luci.sys.call("busybox ps -w | grep ssr-tunnel |grep -v grep >/dev/null") == 0 then
tunnel_run=1
end
if luci.sys.call("pidof ss-server >/dev/null") == 0 then
sserver_run=1
end
if luci.sys.call("ps -w | grep v2ray-server | grep -v grep >/dev/null") == 0 then
v2server_run=1
end
if luci.sys.call("ps -w | grep ssr-tunnel |grep -v grep >/dev/null") == 0 then
tunnel_run=1
end
if luci.sys.call("pidof udp2raw >/dev/null") == 0 then
udp2raw_run=1
end
if luci.sys.call("pidof udpspeeder >/dev/null") == 0 then
udpspeeder_run=1
end
if luci.sys.call("pidof chinadns >/dev/null") == 0 then
chinadns_run=1
end
if luci.sys.call("pidof pdnsd >/dev/null") == 0 then
pdnsd_run=1
end
if luci.sys.call("pidof dnsparsing >/dev/null") == 0 then
dnsforwarder_run=1
end
if luci.sys.call("pidof dnscrypt-proxy >/dev/null") == 0 then
dnscrypt_proxy_run=1
end
if luci.sys.call("pidof dns2socks >/dev/null") == 0 then
dns2socks_run=1
end
if luci.sys.call("pidof haproxy >/dev/null") == 0 then
haproxy_run=1
end
m = SimpleForm("Version")
m.reset = false
m.submit = false
t = m:section(Table, procs, translate("Running Details: ") .. "(/var/etc)")
t:option(DummyValue, "PID", translate("PID"))
t:option(DummyValue, "COMMAND", translate("CMD"))
t:option(DummyValue, "LISTEN", translate("LISTEN"))
t:option(DummyValue, "%CPU", translate("CPU usage (%)"))
t:option(DummyValue, "%MEM", translate("Memory usage (%)"))
s=m:field(DummyValue,"redir_run",translate("Global Client"))
s.rawhtml = true
if redir_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
s=m:field(DummyValue,"reudp_run",translate("Game Mode UDP Relay"))
s.rawhtml = true
if reudp_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
s=m:field(DummyValue,"haproxy_run",translate("Load Balancing"))
s.rawhtml = true
if haproxy_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
if nixio.fs.access("/usr/bin/chinadns") then
s=m:field(DummyValue,"chinadns_run",translate("ChinaDNS"))
s.rawhtml = true
if chinadns_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
s=m:field(DummyValue,"pdnsd_run",translate("PDNSD"))
s.rawhtml = true
if pdnsd_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
if nixio.fs.access("/usr/bin/dns2socks") then
s=m:field(DummyValue,"dns2socks_run",translate("DNS2SOCKS"))
s.rawhtml = true
if dns2socks_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
s=m:field(DummyValue,"dnsforwarder_run",translate("dnsforwarder"))
s.rawhtml = true
if dnsforwarder_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
s=m:field(DummyValue,"dnscrypt_proxy_run",translate("dnscrypt_proxy"))
s.rawhtml = true
if dnscrypt_proxy_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
if nixio.fs.access("/usr/bin/ss-local") then
s=m:field(DummyValue,"ssock5_run",translate("SSOCKS5 Proxy"))
s.rawhtml = true
if ssock5_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
if nixio.fs.access("/usr/bin/ssr-local") then
s=m:field(DummyValue,"sock5_run",translate("SSR SOCKS5 Proxy"))
s.rawhtml = true
if sock5_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
if nixio.fs.access("/usr/bin/v2ray/v2ray") then
s=m:field(DummyValue,"ssock5_run",translate("V2SOCKS5 Proxy"))
s.rawhtml = true
if v2sock5_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
if nixio.fs.access("/usr/sbin/privoxy") then
s=m:field(DummyValue,"privoxy_run",translate("HTTP Proxy"))
s.rawhtml = true
if privoxy_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
if nixio.fs.access("/usr/bin/ssr-server") then
s=m:field(DummyValue,"server_run",translate("Global SSR Server"))
s.rawhtml = true
if server_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
if nixio.fs.access("/usr/bin/ss-server") then
s=m:field(DummyValue,"sserver_run",translate("Global SS Server"))
s.rawhtml = true
if sserver_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
if nixio.fs.access("/usr/bin/v2ray") then
s=m:field(DummyValue,"v2server_run",translate("Global V2RAY Server"))
s.rawhtml = true
if v2server_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
if nixio.fs.access("/usr/bin/kcptun-client") then
s=m:field(DummyValue,"kcp_version",translate("KcpTun Version"))
s.rawhtml = true
s.value =kcptun_version
s=m:field(DummyValue,"kcptun_run",translate("KcpTun"))
s.rawhtml = true
if kcptun_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
end
s=m:field(DummyValue,"version",translate("IPK Version"))
s.rawhtml = true
s.value =IPK_Version
s=m:field(DummyValue,"udp2raw_version",translate("udp2raw Version"))
s.rawhtml = true
s.value =udp2raw_version
s=m:field(DummyValue,"udp2raw_run",translate("udp2raw"))
s.rawhtml = true
if udp2raw_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
s=m:field(DummyValue,"udpspeeder_version",translate("UDPspeeder Version"))
s.rawhtml = true
s.value =udpspeeder_version
s=m:field(DummyValue,"udpspeeder_run",translate("UDPspeeder"))
s.rawhtml = true
if udpspeeder_run == 1 then
s.value =font_blue .. bold_on .. translate("Running") .. bold_off .. font_off
else
s.value = translate("Not Running")
end
s=m:field(DummyValue,"feedback",translate("Feedback"))
s.template = "vssr/feedback"
s.value =translate("No feedback")
return m
|
PLUGIN.name = "Flashlight item"
PLUGIN.author = "SleepyMode"
PLUGIN.description = "Adds an item allowing players to toggle their flashlight."
function PLUGIN:PlayerSwitchFlashlight(client, bEnabled)
local character = client:GetCharacter()
if (character and character:GetData("headlamp", false) == true) then
return true
end
end
|
-----------------------------------
--
-- Zone: Promyvion-Vahzl (22)
--
-----------------------------------
local ID = require("scripts/zones/Promyvion-Vahzl/IDs")
require("scripts/globals/promyvion")
require("scripts/globals/missions")
require("scripts/globals/settings")
require("scripts/globals/status")
-----------------------------------
function onInitialize(zone)
tpz.promyvion.initZone(zone)
end
function onZoneIn(player, prevZone)
local cs = -1
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
player:setPos(-14.744, 0.036, -119.736, 1) -- To Floor 1 {R}
end
if player:getCurrentMission(COP) == tpz.mission.id.cop.DESIRES_OF_EMPTINESS and player:getCharVar("PromathiaStatus") == 0 then
cs = 50
end
return cs
end
function afterZoneIn(player)
if ENABLE_COP_ZONE_CAP == 1 then
player:addStatusEffect(tpz.effect.LEVEL_RESTRICTION, 50, 0, 0)
end
end
function onRegionEnter(player, region)
tpz.promyvion.onRegionEnter(player, region)
end
function onRegionLeave(player, region)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 50 then
player:setCharVar("PromathiaStatus", 1)
elseif csid == 45 and option == 1 then
player:setPos(-379.947, 48.045, 334.059, 192, 9) -- To Pso'Xja {R}
end
end
|
local function brew()
local present, toggleterm = pcall(require, "toggleterm")
if not present then
return
end
toggleterm.setup{
-- size can be a number or function which is passed the current terminal
size = 10,
-- size = function(term)
-- if term.direction == "horizontal" then
-- return 15
-- elseif term.direction == "vertical" then
-- return vim.o.columns * 0.4
-- end
-- end,
open_mapping = [[<c-t>]],
-- on_open = fun(t: Terminal), -- function to run when the terminal opens
-- on_close = fun(t: Terminal), -- function to run when the terminal closes
hide_numbers = true, -- hide the number column in toggleterm buffers
shade_filetypes = {},
shade_terminals = true,
shading_factor = '2', -- the degree by which to darken to terminal colour, default: 1 for dark backgrounds, 3 for light
start_in_insert = true,
insert_mappings = true, -- whether or not the open mapping applies in insert mode
terminal_mappings = true, -- whether or not the open mapping applies in the opened terminals
persist_size = true,
direction = "horizontal", -- 'vertical' | 'horizontal' | 'window' | 'float',
close_on_exit = true, -- close the terminal window when the process exits
shell = vim.o.shell, -- change the default shell
-- This field is only relevant if direction is set to 'float'
float_opts = {
-- The border key is *almost* the same as 'nvim_open_win'
-- see :h nvim_open_win for details on borders however
-- the 'curved' border is a custom border type
-- not natively supported but implemented in this plugin.
border = "curved", -- 'single' | 'double' | 'shadow' | 'curved' | ... other options supported by win open
width = 120,
height = 40,
winblend = 3,
highlights = {
border = "Normal",
background = "Normal",
}
},
-- execs = {
-- { "lazygit", "<leader>gg", "LazyGit", "float" },
-- { "lazygit", "<c-\\><c-g>", "LazyGit", "float" },
-- },
}
-- vim.api.nvim_exec([[
-- let g:toggleterm_terminal_mapping = '<C-t>'
-- autocmd TermEnter term://*toggleterm#* tnoremap <silent><c-t> <Cmd>exe v:count1 . "ToggleTerm"<CR>
-- nnoremap <silent><c-t> <Cmd>exe v:count1 . "ToggleTerm"<CR>
-- inoremap <silent><c-t> <Esc><Cmd>exe v:count1 . "ToggleTerm"<CR>
-- ]],
-- false
-- )
function _G.set_terminal_keymaps()
local opts = { noremap = true }
-- vim.api.nvim_buf_set_keymap(0, "t", "<esc>", [[<C-\><C-n>]], opts)
-- vim.api.nvim_buf_set_keymap(0, "t", "jk", [[<C-\><C-n>]], opts)
vim.api.nvim_buf_set_keymap(0, "t", "<C-h>", [[<C-\><C-n><C-W>h]], opts)
vim.api.nvim_buf_set_keymap(0, "t", "<C-j>", [[<C-\><C-n><C-W>j]], opts)
vim.api.nvim_buf_set_keymap(0, "t", "<C-k>", [[<C-\><C-n><C-W>k]], opts)
vim.api.nvim_buf_set_keymap(0, "t", "<C-l>", [[<C-\><C-n><C-W>l]], opts)
end
vim.cmd("autocmd! TermOpen term://* lua set_terminal_keymaps()")
end
return {
"akinsho/toggleterm.nvim",
config = brew(),
}
|
--[[
Licensed under GNU General Public License v2
* (c) 2013, Luca CPZ
* (c) 2010-2012, Peter Hofmann
--]]
local helpers = require("lain.helpers")
local wibox = require("wibox")
local math = { ceil = math.ceil }
local string = { format = string.format,
gmatch = string.gmatch }
local tostring = tostring
-- CPU usage
-- lain.widget.cpu
local function factory(args)
local cpu = { core = {}, widget = wibox.widget.textbox() }
local args = args or {}
local timeout = args.timeout or 2
local settings = args.settings or function() end
function cpu.update()
-- Read the amount of time the CPUs have spent performing
-- different kinds of work. Read the first line of /proc/stat
-- which is the sum of all CPUs.
local times = helpers.lines_match("cpu","/proc/stat")
for index,time in pairs(times) do
local coreid = index - 1
local core = cpu.core[coreid] or
{ last_active = 0 , last_total = 0, usage = 0 }
local at = 1
local idle = 0
local total = 0
for field in string.gmatch(time, "[%s]+([^%s]+)") do
-- 4 = idle, 5 = ioWait. Essentially, the CPUs have done
-- nothing during these times.
if at == 4 or at == 5 then
idle = idle + field
end
total = total + field
at = at + 1
end
local active = total - idle
if core.last_active ~= active or core.last_total ~= total then
-- Read current data and calculate relative values.
local dactive = active - core.last_active
local dtotal = total - core.last_total
local usage = math.ceil((dactive / dtotal) * 100)
core.last_active = active
core.last_total = total
core.usage = usage
-- Save current data for the next run.
cpu.core[coreid] = core
end
end
cpu_now = cpu.core
cpu_now.usage = cpu_now[0].usage
widget = cpu.widget
settings()
end
helpers.newtimer("cpu", timeout, cpu.update)
return cpu
end
return factory
|
-- Copyright (C) by Kwanhur Huang
describe("ImageAttr", function()
local info = debug.getinfo(1, "S")
local path = info.source
path = string.sub(path, 2, -1)
image_dir = string.match(path, "^.*/")
image_name = "test_image.png"
image_filename = image_dir .. image_name
local imagick = require("resty.imagick")
local img, msg, code = imagick.load_image(image_filename)
assert.is_true(img ~= nil)
it("getWidthHeight", function()
local w = img:get_width()
local h = img:get_height()
assert.is_true(w == 64 and h == 64)
end)
it("getSetFormat", function()
local format = img:get_format()
assert.is_true(format == "png")
local ok, msg, code = img:set_format('jpeg')
assert.truthy(ok)
format = img:get_format()
assert.is_true(format == "jpeg")
end)
it("getSetQuality", function()
local quality = img:get_quality()
assert.truthy(quality == 0)
img:set_quality(75)
quality = img:get_quality()
assert.truthy(quality == 75)
end)
it("getDepth", function()
local depth = img:get_depth()
assert.truthy(depth == 8)
end)
it("getUnits", function()
local unit = img:get_units()
assert.truthy(unit == "PixelsPerCentimeterResolution")
end)
it("getSetGravity", function()
local gravity = img:get_gravity()
assert.truthy(gravity == "ForgetGravity")
img:set_gravity("SouthGravity")
gravity = img:get_gravity()
assert.truthy(gravity == "SouthGravity")
end)
it("getSetColorspace", function()
local cs = img:get_colorspace()
assert.is_true(cs == "LuvColorspace")
img:set_colorspace("RGB")
cs = img:get_colorspace()
assert.truthy(cs == "RGBColorspace")
end)
it("getSetImageType", function()
local it = img:get_type()
assert.is_true(it == "TrueColorAlphaType")
img:set_type("Bilevel")
it = img:get_type()
assert.is_true(it == "BilevelType")
end)
it("getSetEndian", function()
local ed = img:get_endian()
assert.is_true(ed == "UndefinedEndian")
img:set_endian("LSB")
ed = img:get_endian()
assert.is_true(ed == "LSBEndian")
end)
it("getSetRendering", function()
local re = img:get_rendering_intent()
assert.is_true(re == "PerceptualIntent")
img:set_rendering_intent("Relative")
re = img:get_rendering_intent()
assert.is_true(re == "RelativeIntent")
end)
it("getSetGamma", function()
local ga = img:get_gamma()
assert.is_true(ga < 0.45455 and ga > 0.45)
img:set_gamma(0.4)
ga = img:get_gamma()
assert.is_true(0.4 == ga)
end)
it("getSetInterlaceScheme", function()
local int = img:get_interlace_scheme()
assert.is_true( int == "NoInterlace")
img:set_interlace_scheme("PNG")
int = img:get_interlace_scheme()
assert.is_true(int == "PNGInterlace")
end)
it("getSetCompose", function()
local com = img:get_compose()
assert.is_true(com == "XorCompositeOp")
img:set_compose("In")
com = img:get_compose()
assert.is_true(com == "InCompositeOp")
end)
it("getSetCompression", function()
local com = img:get_compression()
assert.is_true("ZipCompression" == com)
img:set_compression("LZW")
com = img:get_compression()
assert.is_true("LZWCompression" == com)
end)
it("getSetOrientation", function()
local ori = img:get_orientation()
assert.is_true("UndefinedOrientation" == ori)
img:set_orientation("TopLeft")
ori = img:get_orientation()
assert.is_true("TopLeftOrientation" == ori)
end)
it("getSetDispose", function()
local dis = img:get_dispose()
assert.is_true(dis == "UndefinedDispose")
img:set_dispose("None")
dis = img:get_dispose()
assert.is_true(dis == "NoneDispose")
end)
it("getSetIterations", function()
local it = img:get_iterations()
assert.is_true(it == 0)
img:set_iterations(1)
it = img:get_iterations()
assert.is_true(it == 1)
end)
it("getSetPage", function()
local w, h, x, y = img:get_page()
assert.is_true(w == 64 and h == 64 and x == 0 and y == 0)
img:set_page(66, 66, 0, 0)
w, h, x, y = img:get_page()
assert.is_true(w == 66)
img:reset_page()
w, h, x, y = img:get_page()
assert.is_true(w == 0 and h == 0 and x == 0 and y == 0)
end)
it("getSetFilename", function()
local fn = img:get_filename()
assert.is_true(image_filename == fn)
img:set_filename('spec/test_image.jpg')
fn = img:get_filename()
assert.is_true(fn == "spec/test_image.jpg")
end)
it("getAlphaChannel", function()
local ok, msg, code = img:get_alpha_channel()
assert.is_true(not ok)
end)
it("getColors", function()
local num = img:get_colors()
assert.is_true(num == 2)
end)
it("getSetDelay", function()
local delay = img:get_delay()
assert.is_true(0 == delay)
img:set_delay(1)
delay = img:get_delay()
assert.is_true(1 == delay)
end)
it("getSetFuzz", function()
local fuzz = img:get_fuzz()
assert.is_true(fuzz == 0)
img:set_fuzz(1)
fuzz = img:get_fuzz()
assert.is_true(1 == fuzz)
end)
it("getNumber", function()
local num = img:get_number()
assert.is_true(num == 1)
end)
it("getTotalInkDensity", function()
local den = img:get_total_ink_density()
assert.is_true(den == 0)
end)
it("getSignature", function()
local sig = img:get_signature()
print(sig)
assert.is_true("0fb068547da285471c32933b16d85663baed20ae49818d61a199d7dc55d1b684" == sig)
end)
it("indentify", function()
local sig = img:identify()
assert.is_true(string.len(sig) > 0)
end)
end)
|
require 'torch';
require 'nn';
-- train the image set on the CNN
-- [input: dataset] the training dataset. Must comply with Torch NN classes
-- dataset must have 3 functions implemented:
-- nChannels(): number of color channels
-- w(): width of the images
-- h(): height of the images
-- the CNN parameters will be adjusted based on it
-- [input: use_cuda] if on, the training dataset must already be on GPU (not done because it would restric the dataset data structure)
-- [output: net] return the neural network
function train( dataset, no_classes, use_cuda )
-- get number of color channels, width and height of the images
c = dataset:nChannels()
w = dataset:w()
h = dataset:h()
-- calculate the output dimensions of the tensors for each layer
f1 = 5
f2 = 2
s2 = 2
w2 = w - f1 + 1
h2 = h - f1 + 1
w3 = math.floor((w2 - f2) / s2 + 1)
h3 = math.floor((h2 - f2) / s2 + 1)
w4 = w3 - f1 + 1
h4 = h3 - f1 + 1
w5 = math.floor((w4 - f2) / s2 + 1)
h5 = math.floor((h4 - f2) / s2 + 1)
-- simple CNN architecture
net = nn.Sequential()
net:add(nn.SpatialConvolution( c, 6, f1, f1 ))
net:add(nn.ReLU())
net:add(nn.SpatialMaxPooling( f2, f2, s2, s2 ))
net:add(nn.SpatialConvolution(6, 16, f1, f1))
net:add(nn.ReLU())
net:add(nn.SpatialMaxPooling( f2, f2, s2, s2 ))
net:add(nn.View(16 * w5 * h5))
net:add(nn.Linear(16 * w5 * h5, 120))
net:add(nn.ReLU())
net:add(nn.Linear(120, 84))
net:add(nn.ReLU())
net:add(nn.Linear(84, no_classes))
net:add(nn.LogSoftMax())
criterion = nn.ClassNLLCriterion()
-- load data on GPU if cuda option is on
if use_cuda then
require 'cunn';
require 'cutorch';
require 'cudnn';
-- cudnn faster than nn with cuda
cudnn.fastest = true
cudnn.benchmark = true
-- cudnn.verbose = true
cudnn.convert(net, cudnn)
net:cuda()
criterion:cuda()
end
sgd = nn.StochasticGradient(net, criterion)
sgd.learningRate = 0.01
sgd.maxIteration = 10 -- # of epochs
sgd:train(dataset)
return net
end
|
local gui = require("__flib__.gui-beta")
--Buttons: Entities / Recipes / ...
-- On-click, change subsection
--Subsection: Depending on button active
-- Entities: belts, pipes, decider combinator, arithmetic combinator
local loop_plugins = require("v2/plugins/loops/loops")
local filter_plugins = require("v2/plugins/filters/filters")
local data_fillers = require("v2/plugins/data_fill/data_fillers")
local gui_generic = require("v2/gui/gui_generic")
local function search_params_gui(search_id)
return {
type = "frame",
direction = "vertical",
style = "inside_shallow_frame_with_padding",
style_mods = {padding = 12},
children = {
{
type = "label", caption = {"search_engine.looking_for"}
},
{
type = "flow",
direction = "horizontal",
ref = { "loop_plugins" },
children = loop_plugins.gui_elements()
},
{
type = "flow", direction = "vertical", ref = { "loop_params" }
},
{
type = "label", caption = {"search_engine.where_filters"}
},
filter_plugins.generic_controls(search_id),
{
type = "label", caption = {"search_engine.would_like_to_know"}
},
{
type = "button", caption = {"search_engine.search_button"}, actions = {
on_click = { action = "start_search", gui = 1, search_id = search_id }
}
},
{
type = "label", caption = {"search_engine.progress",0,0,0}, ref = { "results_count" }
}
}
}
end
local function create_guis(player)
local search_id = "search-" .. player.index .. "-" .. game.tick
local search_gui = gui.build(player.gui.screen, {
{
type = "frame",
direction = "vertical",
ref = {"search_window"},
tags = { search_id = search_id },
children = {
gui_generic.header(),
{
type = "flow", direction = "vertical", ref = { "internal" }, children = {
search_params_gui(search_id)
}
}
}
}
})
local loop_id = gui.get_tags(search_gui.loop_plugins.children[1]).loop_id
local loop_params = gui.build(search_gui.loop_params, loop_plugins.controls(loop_id))
search_gui.titlebar.flow.drag_target = search_gui.search_window
search_gui.search_window.force_auto_center()
global.searches = global.searches or {}
global.searches[search_id] = {
search_id = search_id,
filters = {},
player = player,
gui = search_gui,
gui_loop_params = loop_params,
params = {}
}
end
local function determine_provides(search)
local provides = {}
search.provides = provides
provides[search.job.loop_provides] = true
for _, data_filler_id in pairs(search.job.data_fillers) do
if data_fillers.plugins_support.is_supported_key(data_filler_id, search) then
for k in pairs(data_fillers.provides(data_filler_id)) do
provides[k] = true
end
end
end
return provides
end
local function start_search(msg)
local search = global.searches[msg.search_id]
local loop_id = gui.get_tags(search.gui.loop_plugins.children[1]).loop_id
local loop_data = loop_plugins.create_loop(loop_id, search)
local loop_provides = loop_plugins.provides(loop_id)
-- TODO: search.plugins = { filters = ..., data_fillers = ..., gui = ... } ???
search.results = {}
search.results_count = 0
search.result_headers = { loop_provides }
search.job = {
loop_provides = loop_provides,
running = true,
progress = nil,
loop_id = loop_id,
loop_data = loop_data,
loop_data_count = table_size(loop_data),
data_fillers = { "position", "circuit_networks", "recipe" }
}
search.provides = determine_provides(search)
end
local function handle_action(msg, e)
if msg.action == "start_search" then
start_search(msg, e)
end
end
return {
open_small_gui = create_guis, handle_action = handle_action
}
|
object_static_item_item_hoth_crate_03 = object_static_item_shared_item_hoth_crate_03:new {
}
ObjectTemplates:addTemplate(object_static_item_item_hoth_crate_03, "object/static/item/item_hoth_crate_03.iff")
|
-- Creator:
-- AltiV, April 26th, 2019
LinkLuaModifier("modifier_imba_rattletrap_battery_assault", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_rattletrap_battery_assault_fragmentation_rend", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_rattletrap_battery_assault_percussive_maint_aura", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_rattletrap_battery_assault_percussive_maint", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_rattletrap_power_cogs", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_rattletrap_cog_push", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_HORIZONTAL)
LinkLuaModifier("modifier_imba_rattletrap_power_cogs_charge_coil_counter", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_rattletrap_power_cogs_charge_coil_instance", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_rattletrap_power_cogs_rotational", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_HORIZONTAL)
LinkLuaModifier("modifier_imba_rattletrap_rocket_flare_critical", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_rattletrap_hookshot", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_HORIZONTAL)
imba_rattletrap_battery_assault = class({})
modifier_imba_rattletrap_battery_assault = class({})
modifier_imba_rattletrap_battery_assault_fragmentation_rend = class({})
modifier_imba_rattletrap_battery_assault_percussive_maint_aura = class({})
modifier_imba_rattletrap_battery_assault_percussive_maint = class({})
imba_rattletrap_power_cogs = class({})
modifier_imba_rattletrap_power_cogs = class({})
modifier_imba_rattletrap_cog_push = class({})
modifier_imba_rattletrap_power_cogs_charge_coil_counter = class({})
modifier_imba_rattletrap_power_cogs_charge_coil_instance = class({})
modifier_imba_rattletrap_power_cogs_rotational = class({})
imba_rattletrap_rocket_flare = class({})
modifier_imba_rattletrap_rocket_flare_critical = class({})
imba_rattletrap_hookshot = class({})
modifier_imba_rattletrap_hookshot = class({})
---------------------
-- BATTERY ASSAULT --
---------------------
function imba_rattletrap_battery_assault:GetBehavior()
return DOTA_ABILITY_BEHAVIOR_NO_TARGET + DOTA_ABILITY_BEHAVIOR_IGNORE_BACKSWING + DOTA_ABILITY_BEHAVIOR_IMMEDIATE + DOTA_ABILITY_BEHAVIOR_AUTOCAST
end
function imba_rattletrap_battery_assault:GetIntrinsicModifierName()
return "modifier_imba_rattletrap_battery_assault_percussive_maint_aura"
end
function imba_rattletrap_battery_assault:OnSpellStart()
if not IsServer() then return end
self:GetCaster():StartGesture(ACT_DOTA_RATTLETRAP_BATTERYASSAULT)
if self:GetCaster():GetName() == "npc_dota_hero_rattletrap" then
local random_response = RandomInt(3, 18)
if random_response <= 9 then
self:GetCaster():EmitSound("rattletrap_ratt_ability_batt_0"..random_response)
else
self:GetCaster():EmitSound("rattletrap_ratt_ability_batt_"..random_response)
end
end
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_rattletrap_battery_assault", {duration = self:GetSpecialValueFor("duration")})
end
------------------------------
-- BATTERY ASSAULT MODIFIER --
------------------------------
-- function modifier_imba_rattletrap_battery_assault:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_imba_rattletrap_battery_assault:OnCreated()
-- AbilitySpecials
self.radius = self:GetAbility():GetSpecialValueFor("radius")
self.interval = self:GetAbility():GetTalentSpecialValueFor("interval")
self.fragmentation_mult = self:GetAbility():GetSpecialValueFor("fragmentation_mult")
self.fragmentation_damage = self:GetAbility():GetSpecialValueFor("fragmentation_damage")
self.fragmentation_duration = self:GetAbility():GetSpecialValueFor("fragmentation_duration")
if not IsServer() then return end
self.damage = self:GetAbility():GetAbilityDamage()
self.damage_type = self:GetAbility():GetAbilityDamageType()
self:GetParent():EmitSound("Hero_Rattletrap.Battery_Assault")
-- Damages immediately on modifier creation
self:OnIntervalThink()
if self:GetAbility() and self:GetAbility():GetAutoCastState() then
self:StartIntervalThink(self.interval / self.fragmentation_mult)
else
self:StartIntervalThink(self.interval)
end
end
function modifier_imba_rattletrap_battery_assault:OnIntervalThink()
if not IsServer() then return end
self:GetParent():EmitSound("Hero_Rattletrap.Battery_Assault_Launch")
local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_battery_assault.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent())
ParticleManager:ReleaseParticleIndex(particle)
local particle2 = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_battery_shrapnel.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent())
local enemies = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP, DOTA_UNIT_TARGET_FLAG_NO_INVIS, FIND_ANY_ORDER, false)
if #enemies >= 1 then
enemies[1]:EmitSound("Hero_Rattletrap.Battery_Assault_Impact")
ParticleManager:SetParticleControl(particle2, 1, enemies[1]:GetAbsOrigin())
-- Standard logic
if not self:GetAbility() or (self:GetAbility() and not self:GetAbility():GetAutoCastState()) then
local damageTable = {
victim = enemies[1],
damage = self.damage,
damage_type = self.damage_type,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self:GetAbility()
}
ApplyDamage(damageTable)
enemies[1]:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_stunned", {duration = 0.1 * (1 - enemies[1]:GetStatusResistance())})
else
-- IMBAfication: Fragmentation Rend
local damageTable = {
victim = enemies[1],
damage = self.damage * self.fragmentation_damage * 0.01,
damage_type = self.damage_type,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self:GetAbility()
}
ApplyDamage(damageTable)
enemies[1]:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_battery_assault_fragmentation_rend", {duration = self.fragmentation_duration * (1 - enemies[1]:GetStatusResistance())})
end
else
ParticleManager:SetParticleControl(particle2, 1, self:GetParent():GetAbsOrigin() + RandomVector(RandomInt(0, 128))) -- Arbitrary numbers
end
ParticleManager:ReleaseParticleIndex(particle)
if self:GetAbility() and self:GetAbility():GetAutoCastState() then
self:StartIntervalThink(self.interval / self.fragmentation_mult)
else
self:StartIntervalThink(self.interval)
end
end
function modifier_imba_rattletrap_battery_assault:OnDestroy()
if not IsServer() then return end
self:GetParent():StopSound("Hero_Rattletrap.Battery_Assault")
end
-------------------------------------------------
-- BATTERY ASSAULT FRAGMENTATION REND MODIFIER --
-------------------------------------------------
function modifier_imba_rattletrap_battery_assault_fragmentation_rend:OnCreated()
if self:GetAbility() then
self.fragmentation_vuln = self:GetAbility():GetSpecialValueFor("fragmentation_vuln")
self.fragmentation_vision = self:GetAbility():GetSpecialValueFor("fragmentation_vision")
self.fragmentation_resist = self:GetAbility():GetSpecialValueFor("fragmentation_resist")
else
self:Destroy()
return
end
if not IsServer() then return end
self:IncrementStackCount()
end
function modifier_imba_rattletrap_battery_assault_fragmentation_rend:OnRefresh()
if not IsServer() then return end
self:IncrementStackCount()
end
function modifier_imba_rattletrap_battery_assault_fragmentation_rend:DeclareFunctions()
local decFuncs = {
MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE,
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING,
MODIFIER_PROPERTY_BONUS_VISION_PERCENTAGE
}
return decFuncs
end
function modifier_imba_rattletrap_battery_assault_fragmentation_rend:GetModifierIncomingDamage_Percentage()
return self:GetStackCount() * self.fragmentation_vuln
end
function modifier_imba_rattletrap_battery_assault_fragmentation_rend:GetModifierStatusResistanceStacking()
return self:GetStackCount() * self.fragmentation_resist
end
function modifier_imba_rattletrap_battery_assault_fragmentation_rend:GetBonusVisionPercentage()
return self:GetStackCount() * self.fragmentation_vision
end
------------------------------------------------
-- BATTERY ASSAULT PERCUSSIVE MAINTENACE AURA --
------------------------------------------------
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:IsHidden() return true end
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:IsAura() return true end
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:IsAuraActiveOnDeath() return false end
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:GetAuraRadius() return self:GetAbility():GetTalentSpecialValueFor("percussive_maint_radius") end
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:GetAuraSearchFlags() return DOTA_UNIT_TARGET_FLAG_NONE end
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_FRIENDLY end
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:GetAuraSearchType() return DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP + DOTA_UNIT_TARGET_OTHER end
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:GetModifierAura() return "modifier_imba_rattletrap_battery_assault_percussive_maint" end
function modifier_imba_rattletrap_battery_assault_percussive_maint_aura:GetAuraEntityReject(hEntity) return self:GetCaster():PassivesDisabled() end
----------------------------------------------------
-- BATTERY ASSAULT PERCUSSIVE MAINTENACE MODIFIER --
----------------------------------------------------
function modifier_imba_rattletrap_battery_assault_percussive_maint:OnCreated()
self.percussive_maint_base_chance = self:GetAbility():GetSpecialValueFor("percussive_maint_base_chance")
self.percussive_maint_frag_chance = self:GetAbility():GetSpecialValueFor("percussive_maint_frag_chance")
end
function modifier_imba_rattletrap_battery_assault_percussive_maint:DeclareFunctions()
return {
MODIFIER_EVENT_ON_ATTACK_LANDED
}
end
function modifier_imba_rattletrap_battery_assault_percussive_maint:OnAttackLanded(keys)
if not IsServer() then return end
if keys.target == self:GetParent() then
if (not self:GetAbility() or not self:GetAbility():GetAutoCastState()) then
if RollPseudoRandom(self.percussive_maint_base_chance, self) then
self:GetParent():AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_battery_assault", {duration = FrameTime()})
end
elseif RollPseudoRandom(self.percussive_maint_frag_chance, self) then
self:GetParent():AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_battery_assault", {duration = FrameTime()})
end
end
end
----------------
-- POWER COGS --
----------------
function imba_rattletrap_power_cogs:GetBehavior()
return DOTA_ABILITY_BEHAVIOR_NO_TARGET + DOTA_ABILITY_BEHAVIOR_AUTOCAST
end
function imba_rattletrap_power_cogs:OnSpellStart()
if not IsServer() then return end
local caster_pos = self:GetCaster():GetAbsOrigin()
local num_of_cogs = 8 -- You're probably gonna get some really weird results if you change this number
local cogs_radius = self:GetSpecialValueFor("cogs_radius")
-- Static value cause this is kinda hot-fixing for now
local square_dist = 160
local cog_vector = GetGroundPosition(caster_pos + Vector(0, cogs_radius, 0), nil)
local second_cog_vector = GetGroundPosition(caster_pos + Vector(0, cogs_radius * 2, 0), nil)
self:GetCaster():StartGesture(ACT_DOTA_RATTLETRAP_POWERCOGS)
-- if not self:GetAutoCastState() then
for cog = 1, num_of_cogs do
local cog = CreateUnitByName("npc_dota_rattletrap_cog", cog_vector, false, self:GetCaster(), self:GetCaster(), self:GetCaster():GetTeamNumber())
cog:EmitSound("Hero_Rattletrap.Power_Cogs")
cog:AddNewModifier(self:GetCaster(), self, "modifier_imba_rattletrap_power_cogs",
{
duration = self:GetSpecialValueFor("duration"),
x = (cog_vector - caster_pos).x,
y = (cog_vector - caster_pos).y,
-- Also need to store these for the Rotational IMBAfication
center_x = caster_pos.x,
center_y = caster_pos.y,
center_z = caster_pos.z
})
-- Talent: Second Gear (might be too laggy with Rotational...)
if self:GetCaster():HasTalent("special_bonus_imba_rattletrap_second_gear") then
local second_cog = CreateUnitByName("npc_dota_rattletrap_cog", second_cog_vector, false, self:GetCaster(), self:GetCaster(), self:GetCaster():GetTeamNumber())
second_cog:EmitSound("Hero_Rattletrap.Power_Cogs")
second_cog:AddNewModifier(self:GetCaster(), self, "modifier_imba_rattletrap_power_cogs",
{
duration = self:GetSpecialValueFor("duration"),
x = (second_cog_vector - caster_pos).x,
y = (second_cog_vector - caster_pos).y,
-- Also need to store these for the Rotational IMBAfication
center_x = caster_pos.x,
center_y = caster_pos.y,
center_z = caster_pos.z,
second_gear = true
})
second_cog_vector = RotatePosition(caster_pos, QAngle(0, 360 / num_of_cogs, 0), second_cog_vector)
end
cog_vector = RotatePosition(caster_pos, QAngle(0, 360 / num_of_cogs, 0), cog_vector)
end
-- else
-- local cog_vectors =
-- {
-- Vector(-square_dist, square_dist, 0), Vector(0, square_dist, 0), Vector(square_dist, square_dist, 0),
-- Vector(-square_dist, 0, 0), Vector(square_dist, 0, 0),
-- Vector(-square_dist, -square_dist, 0), Vector(0, -square_dist, 0), Vector(square_dist, -square_dist, 0)
-- }
-- for cog = 1, #cog_vectors do
-- local cog = CreateUnitByName("npc_dota_rattletrap_cog", self:GetCaster():GetAbsOrigin() + cog_vectors[cog], false, self:GetCaster(), self:GetCaster(), self:GetCaster():GetTeamNumber())
-- cog:EmitSound("Hero_Rattletrap.Power_Cogs")
-- cog:AddNewModifier(self:GetCaster(), self, "modifier_imba_rattletrap_power_cogs",
-- {
-- duration = self:GetSpecialValueFor("duration"),
-- x = (cog:GetAbsOrigin() - self:GetCaster():GetAbsOrigin()).x,
-- y = (cog:GetAbsOrigin() - self:GetCaster():GetAbsOrigin()).y,
-- -- Also need to store these for the Rotational IMBAfication
-- center_x = self:GetCaster():GetAbsOrigin().x,
-- center_y = self:GetCaster():GetAbsOrigin().y,
-- center_z = self:GetCaster():GetAbsOrigin().z
-- })
-- end
-- end
local deploy_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_cog_deploy.vpcf", PATTACH_ABSORIGIN, self:GetCaster())
ParticleManager:ReleaseParticleIndex(deploy_particle)
if self:GetCaster():GetName() == "npc_dota_hero_rattletrap" and RollPercentage(50) then
local responses = {"rattletrap_ratt_ability_cogs_01", "rattletrap_ratt_ability_cogs_02", "rattletrap_ratt_ability_cogs_07"}
self:GetCaster():EmitSound(responses[RandomInt(1, #responses)])
end
local units = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetCaster():GetAbsOrigin(), nil, self:GetSpecialValueFor("cogs_radius") + 80, DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false)
-- Set everyone nearby to get "sucked" into cogs, otherwise you sometimes have people stuck in-between cogs
for _, unit in pairs(units) do
if (unit:GetAbsOrigin() - self:GetCaster():GetAbsOrigin()):Length2D() <= self:GetSpecialValueFor("cogs_radius") then
-- Friendly units won't get displaced towards caster, while enemies do
if unit:GetTeamNumber() == self:GetCaster():GetTeamNumber() then
FindClearSpaceForUnit(unit, unit:GetAbsOrigin(), false)
else
FindClearSpaceForUnit(unit, self:GetCaster():GetAbsOrigin() + RandomVector(self:GetSpecialValueFor("extra_pull_buffer")), false)
end
else
FindClearSpaceForUnit(unit, unit:GetAbsOrigin(), false)
end
end
end
-------------------------
-- POWER COGS MODIFIER --
-------------------------
function modifier_imba_rattletrap_power_cogs:IsHidden() return true end
function modifier_imba_rattletrap_power_cogs:IsPurgable() return false end
function modifier_imba_rattletrap_power_cogs:GetEffectName()
-- No idea if this is actually a thing but w/e using assets as I see them
return "particles/units/heroes/hero_rattletrap/rattletrap_cog_ambient_blur.vpcf"
end
function modifier_imba_rattletrap_power_cogs:OnCreated(params)
if self:GetAbility() then
self.damage = self:GetAbility():GetSpecialValueFor("damage")
self.mana_burn = self:GetAbility():GetSpecialValueFor("mana_burn")
self.attacks_to_destroy = self:GetAbility():GetSpecialValueFor("attacks_to_destroy")
self.push_length = self:GetAbility():GetTalentSpecialValueFor("push_length")
self.push_duration = self:GetAbility():GetSpecialValueFor("push_duration")
self.trigger_distance = self:GetAbility():GetSpecialValueFor("trigger_distance")
self.rotational_speed = self:GetAbility():GetSpecialValueFor("rotational_speed")
self.charge_coil_duration = self:GetAbility():GetSpecialValueFor("charge_coil_duration")
-- Use this variable to track if the cog is currently charged
self.powered = true
-- Use this variable to track how much "health" the cog has (the health doesn't actually change in vanilla)
self.health = self:GetAbility():GetSpecialValueFor("attacks_to_destroy")
else
self:Destroy()
return
end
if not IsServer() then return end
-- Make the cog face a certain way to determine when it should shock people using its "face"
self:GetParent():SetForwardVector(Vector(params.x, params.y, 0))
-- Get the center of all the cogs (basically where the caster cast this spell)
self.center_loc = Vector(params.center_x, params.center_y, params.center_z)
-- Check if the cog is from the Second Gear talent (it will be rotating the other way under Rotational)
self.second_gear = params.second_gear
self.particle = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_cog_ambient.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent())
ParticleManager:SetParticleControl(self.particle, 62, Vector(0, 0, 0))
self:AddParticle(self.particle, false, false, -1, false, false)
self:OnIntervalThink()
self:StartIntervalThink(FrameTime())
end
function modifier_imba_rattletrap_power_cogs:OnIntervalThink()
if not IsServer() then return end
-- Lag...
-- if self:GetAbility() and self:GetAbility():GetAutoCastState() then
-- if not self.second_gear then
-- self:GetParent():SetAbsOrigin(GetGroundPosition(RotatePosition(self.center_loc, QAngle(0, self.rotational_speed * FrameTime(), 0), self:GetParent():GetAbsOrigin()), nil))
-- else
-- self:GetParent():SetAbsOrigin(GetGroundPosition(RotatePosition(self.center_loc, QAngle(0, self.rotational_speed * FrameTime() * (-1), 0), self:GetParent():GetAbsOrigin()), nil))
-- end
-- -- Update forward vector to face away from the center
-- self:GetParent():SetForwardVector(self:GetParent():GetAbsOrigin() - self.center_loc)
-- -- Try to make sure people don't get stuck in-between the cogs if they slip in a gap
-- ResolveNPCPositions(self:GetParent():GetAbsOrigin(), self:GetParent():GetHullRadius())
-- end
if self:GetAbility() then
if self:GetAbility():GetAutoCastState() and not self:GetParent():HasModifier("modifier_imba_rattletrap_power_cogs_rotational") then
self:GetParent():AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_power_cogs_rotational",
{
center_loc_x = self.center_loc.x,
center_loc_y = self.center_loc.y,
center_loc_z = self.center_loc.z,
rotational_speed = self.rotational_speed
})
elseif not self:GetAbility():GetAutoCastState() and self:GetParent():HasModifier("modifier_imba_rattletrap_power_cogs_rotational") then
self:GetParent():RemoveModifierByName("modifier_imba_rattletrap_power_cogs_rotational")
end
end
local enemies = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self.trigger_distance, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP, DOTA_UNIT_TARGET_FLAG_MANA_ONLY, FIND_CLOSEST, false)
for _, enemy in pairs(enemies) do
-- QANGLES, HOW DO THEY WORK
-- Basically this if statement checks if the cog is powered (i.e. hasn't pushed someone yet), if the target themselves isn't already being pushed by another cog, and if the difference between the cog's "face" vector and the directional vector between the enemy and the cog is less than 90 degrees both ways (so 180 degrees of the cog face is valid for shocking)
if self.powered and not enemy:HasModifier("modifier_imba_rattletrap_cog_push") and math.abs(AngleDiff(VectorToAngles(self:GetParent():GetForwardVector()).y, VectorToAngles(enemy:GetAbsOrigin() - self:GetParent():GetAbsOrigin()).y)) <= 90 then
-- The cog is the caster here, as its position will be passed into the modifier
enemy:AddNewModifier(self:GetParent(), self:GetAbility(), "modifier_imba_rattletrap_cog_push",
{
duration = self.push_duration * (1 - enemy:GetStatusResistance()),
damage = self.damage,
mana_burn = self.mana_burn,
push_length = self.push_length
})
self.powered = false
ParticleManager:DestroyParticle(self.particle, false)
ParticleManager:ReleaseParticleIndex(self.particle)
-- Can't break interval think anymore if I want to have the Rotational IMBAfication handled here too
--self:StartIntervalThink(-1)
break
end
end
end
function modifier_imba_rattletrap_power_cogs:OnDestroy()
if not IsServer() then return end
self:GetParent():StopSound("Hero_Rattletrap.Power_Cogs")
self:GetParent():EmitSound("Hero_Rattletrap.Power_Cog.Destroy")
if self:GetRemainingTime() <= 0 then
self:GetParent():RemoveSelf()
end
end
function modifier_imba_rattletrap_power_cogs:CheckState()
return {
[MODIFIER_STATE_SPECIALLY_DENIABLE] = true,
[MODIFIER_STATE_FLYING_FOR_PATHING_PURPOSES_ONLY] = true
}
end
function modifier_imba_rattletrap_power_cogs:DeclareFunctions()
local decFuncs = {
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_MAGICAL,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PHYSICAL,
MODIFIER_PROPERTY_ABSOLUTE_NO_DAMAGE_PURE,
MODIFIER_EVENT_ON_ATTACK_LANDED
}
return decFuncs
end
function modifier_imba_rattletrap_power_cogs:GetAbsoluteNoDamageMagical()
return 1
end
function modifier_imba_rattletrap_power_cogs:GetAbsoluteNoDamagePhysical()
return 1
end
function modifier_imba_rattletrap_power_cogs:GetAbsoluteNoDamagePure()
return 1
end
function modifier_imba_rattletrap_power_cogs:OnAttackLanded(keys)
if not IsServer() then return end
if keys.target == self:GetParent() then
if keys.attacker == self:GetCaster() then
self:GetParent():Kill(nil, self:GetCaster())
for count = 1, self.attacks_to_destroy do
keys.attacker:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_power_cogs_charge_coil_counter",
{
duration = self.charge_coil_duration,
push_duration = self.push_duration,
damage = self.damage,
mana_burn = self.mana_burn,
push_length = self.push_length,
})
keys.attacker:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_power_cogs_charge_coil_instance", {duration = self.charge_coil_duration})
end
else
self.health = self.health - 1
if self.health <= 0 then
self:GetParent():Kill(nil, keys.attacker)
if keys.attacker:GetTeamNumber() == self:GetParent():GetTeamNumber() then
for count = 1, self.attacks_to_destroy do
keys.attacker:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_power_cogs_charge_coil_counter",
{
duration = self.charge_coil_duration,
push_duration = self.push_duration,
damage = self.damage,
mana_burn = self.mana_burn,
push_length = self.push_length,
})
keys.attacker:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_power_cogs_charge_coil_instance", {duration = self.charge_coil_duration})
end
end
end
end
end
end
------------------------------
-- POWER COGS PUSH MODIFIER --
------------------------------
function modifier_imba_rattletrap_cog_push:OnCreated(params)
if not IsServer() then return end
self.duration = params.duration
self.damage = params.damage
self.mana_burn = params.mana_burn
self.push_length = params.push_length
-- This is purely for if a cog is destroyed while it is applying a push, so the attacker can be rerouted to the cog owner to properly deal damage
self.owner = self:GetCaster():GetOwner() or self:GetCaster()
-- Normally I put the sounds and particles in the spell cast, but due to having two sources that can potentially call this modifier, I'm putting them in here
self:GetCaster():EmitSound("Hero_Rattletrap.Power_Cogs_Impact")
-- Create cog zap particle
local attack_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_cog_attack.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetCaster())
if self:GetCaster():GetName() == "npc_dota_rattletrap_cog" then
ParticleManager:SetParticleControlEnt(attack_particle, 1, self:GetParent(), PATTACH_POINT_FOLLOW, "attach_hitloc", self:GetParent():GetAbsOrigin(), true)
else
-- Charge Coil particle attachment
ParticleManager:SetParticleControlEnt(attack_particle, 1, self:GetParent(), PATTACH_POINT_FOLLOW, "attach_attack1", self:GetParent():GetAbsOrigin(), true)
end
-- Calculate speed at which modifier owner will be knocked back
self.knockback_speed = self.push_length / self.duration
-- Get the center of the cog to know which direction to get knocked back
self.position = self:GetCaster():GetAbsOrigin()
-- If horizontal motion cannot be applied, remove the modifier
if self:ApplyHorizontalMotionController() == false then
self:Destroy()
return
end
end
function modifier_imba_rattletrap_cog_push:UpdateHorizontalMotion( me, dt )
if not IsServer() then return end
local distance = (me:GetOrigin() - self.position):Normalized()
me:SetOrigin( me:GetOrigin() + distance * self.knockback_speed * dt )
end
-- This typically gets called if the caster uses a position breaking tool (ex. Blink Dagger) while in mid-motion
function modifier_imba_rattletrap_cog_push:OnHorizontalMotionInterrupted()
self:Destroy()
end
function modifier_imba_rattletrap_cog_push:OnDestroy()
if not IsServer() then return end
self:GetParent():RemoveHorizontalMotionController( self )
-- "Applies the damage first, and then the mana loss."
local damageTable = {
victim = self:GetParent(),
damage = self.damage,
damage_type = DAMAGE_TYPE_MAGICAL,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self:GetAbility()
}
if not damageTable.attacker then
damageTable.attacker = self.owner
end
ApplyDamage(damageTable)
self:GetParent():ReduceMana(self.mana_burn)
-- "At the end of the knock back, trees within a 100 radius of the unit are destroyed."
GridNav:DestroyTreesAroundPoint(self:GetParent():GetAbsOrigin(), 100, true )
end
function modifier_imba_rattletrap_cog_push:CheckState()
local state = {
[MODIFIER_STATE_STUNNED] = true
}
return state
end
function modifier_imba_rattletrap_cog_push:DeclareFunctions()
local decFuncs = {
MODIFIER_PROPERTY_OVERRIDE_ANIMATION
}
return decFuncs
end
function modifier_imba_rattletrap_cog_push:GetOverrideAnimation()
return ACT_DOTA_FLAIL
end
---------------------------------------------
-- POWER COGS CHARGE COIL COUNTER MODIFIER --
---------------------------------------------
function modifier_imba_rattletrap_power_cogs_charge_coil_counter:OnStackCountChanged()
if not IsServer() then return end
-- If there are no charges on charge coil, remove the modifier
if self:GetStackCount() <= 0 then
-- Safety destructors (this should never be called ideally cause they'd be handled naturally)
local charge_coil_instances = self:GetParent():FindAllModifiersByName("modifier_imba_rattletrap_power_cogs_charge_coil_instance")
if #charge_coil_instances >= 1 then
for _, modifier in pairs(charge_coil_instances) do
modifier:Destroy()
end
end
self:Destroy()
end
end
function modifier_imba_rattletrap_power_cogs_charge_coil_counter:OnCreated(params)
if not IsServer() then return end
-- These are needed to feed into the knockback modifier from a separate entity (since it'd be an attacker and not a cog this time)
self.push_duration = params.push_duration
self.damage = params.damage
self.mana_burn = params.mana_burn
self.push_length = params.push_length
self:IncrementStackCount()
end
function modifier_imba_rattletrap_power_cogs_charge_coil_counter:OnRefresh()
if not IsServer() then return end
self:IncrementStackCount()
end
function modifier_imba_rattletrap_power_cogs_charge_coil_counter:DeclareFunctions()
local decFuncs = {
MODIFIER_EVENT_ON_ATTACK_LANDED,
MODIFIER_EVENT_ON_ATTACK_FAIL
}
return decFuncs
end
function modifier_imba_rattletrap_power_cogs_charge_coil_counter:OnAttackLanded(keys)
if not IsServer() then return end
-- Charge Coil will not work on buildings, ward-type units, magic immune enemies, or other cogs, and only works if they don't already have the push modifier
if keys.attacker == self:GetParent() and not keys.target:IsBuilding() and not keys.target:IsMagicImmune() and not keys.target:IsOther() and keys.target:GetName() ~= "npc_dota_rattletrap_cog" and not keys.target:HasModifier("modifier_imba_rattletrap_cog_push") then
local charge_coil_instances = self:GetParent():FindAllModifiersByName("modifier_imba_rattletrap_power_cogs_charge_coil_instance")
if #charge_coil_instances >= 1 then
keys.target:AddNewModifier(self:GetParent(), self:GetAbility(), "modifier_imba_rattletrap_cog_push",
{
duration = self.push_duration * (1 - keys.target:GetStatusResistance()),
damage = self.damage,
mana_burn = self.mana_burn,
push_length = 0
})
charge_coil_instances[1]:Destroy()
end
end
end
-- Charge Coil loses a stack if the modifier holder is a ranged attacker it misses (something something LOGIC IN MY VIDEO GAMES???)
function modifier_imba_rattletrap_power_cogs_charge_coil_counter:OnAttackFail(keys)
if not IsServer() then return end
-- Charge Coil will not work on buildings, ward-type units, magic immune enemies, or other cogs, and only works if they don't already have the push modifier
if keys.attacker:IsRangedAttacker() and keys.attacker == self:GetParent() and not keys.target:IsBuilding() and not keys.target:IsMagicImmune() and not keys.target:IsOther() and keys.target:GetName() ~= "npc_dota_rattletrap_cog" and not keys.target:HasModifier("modifier_imba_rattletrap_cog_push") then
local charge_coil_instances = self:GetParent():FindAllModifiersByName("modifier_imba_rattletrap_power_cogs_charge_coil_instance")
if #charge_coil_instances >= 1 then
charge_coil_instances[1]:Destroy()
end
end
end
----------------------------------------------
-- POWER COGS CHARGE COIL INSTANCE MODIFIER --
----------------------------------------------
function modifier_imba_rattletrap_power_cogs_charge_coil_instance:IsHidden() return true end
function modifier_imba_rattletrap_power_cogs_charge_coil_instance:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_imba_rattletrap_power_cogs_charge_coil_instance:OnDestroy()
if not IsServer() then return end
local charge_coil_modifier = self:GetParent():FindModifierByNameAndCaster("modifier_imba_rattletrap_power_cogs_charge_coil_counter", self:GetCaster())
if charge_coil_modifier then
charge_coil_modifier:DecrementStackCount()
end
end
------------------------------------
-- POWER COGS ROTATIONAL MODIFIER --
------------------------------------
function modifier_imba_rattletrap_power_cogs_rotational:OnCreated(params)
if not IsServer() then return end
self.center_loc = Vector(params.center_loc_x, params.center_loc_y, params.center_loc_z)
self.rotational_speed = params.rotational_speed
-- If horizontal motion cannot be applied, remove the modifier
if self:ApplyHorizontalMotionController() == false then
self:Destroy()
return
end
end
function modifier_imba_rattletrap_power_cogs_rotational:UpdateHorizontalMotion( me, dt )
me:SetOrigin(GetGroundPosition(RotatePosition(self.center_loc, QAngle(0, self.rotational_speed * dt, 0), me:GetAbsOrigin()), nil))
me:SetForwardVector(me:GetAbsOrigin() - self.center_loc)
end
-- This typically gets called if the caster uses a position breaking tool (ex. Blink Dagger) while in mid-motion
function modifier_imba_rattletrap_power_cogs_rotational:OnHorizontalMotionInterrupted()
self:Destroy()
end
function modifier_imba_rattletrap_power_cogs_rotational:OnDestroy()
if not IsServer() then return end
self:GetParent():RemoveHorizontalMotionController( self )
end
------------------
-- ROCKET FLARE --
------------------
function imba_rattletrap_rocket_flare:GetBehavior()
return DOTA_ABILITY_BEHAVIOR_POINT + DOTA_ABILITY_BEHAVIOR_AOE + DOTA_ABILITY_BEHAVIOR_IGNORE_BACKSWING + DOTA_ABILITY_BEHAVIOR_AUTOCAST
end
function imba_rattletrap_rocket_flare:GetAOERadius()
return self:GetSpecialValueFor("radius")
end
function imba_rattletrap_rocket_flare:OnSpellStart()
-- Preventing projectiles getting stuck in one spot due to potential 0 length vector
if self:GetCursorPosition() == self:GetCaster():GetAbsOrigin() then
self:GetCaster():SetCursorPosition(self:GetCursorPosition() + self:GetCaster():GetForwardVector())
end
-- This temporarily deletes the rocket model from Clockwerk
if self:GetCaster():GetName() == "npc_dota_hero_rattletrap" then
self:GetCaster():EmitSound("rattletrap_ratt_ability_flare_0"..RandomInt(1, 7))
if self:GetCaster():GetTogglableWearable( DOTA_LOADOUT_TYPE_MISC ) then
self:GetCaster():GetTogglableWearable( DOTA_LOADOUT_TYPE_MISC ):AddEffects(EF_NODRAW)
end
end
-- Standard logic
if not self:GetAutoCastState() then
-- Why is this a tracking projectile...
local rocket_target = CreateModifierThinker(self:GetCaster(), self, nil, {
duration = FrameTime() -- Don't really need these things to be existing at all except to be a target for the rocket to go towards -_-
},
self:GetCursorPosition(), self:GetCaster():GetTeamNumber(), false)
-- This "dummy" literally only exists to attach the rocket travel sound to
local rocket_dummy = CreateModifierThinker(self:GetCaster(), self, nil, {}, self:GetCaster():GetAbsOrigin(), self:GetCaster():GetTeamNumber(), false)
if self:GetCaster():HasTalent("special_bonus_imba_rattletrap_rocket_flare_truesight") then
rocket_dummy:AddNewModifier(self:GetCaster(), self, "modifier_item_gem_of_true_sight", {})
end
-- Need to look at how to shoot the rocket from the correct place + make the rocet "disappear" from Clockwerk for the duration
local rocket_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_rocket_flare.vpcf", PATTACH_CUSTOMORIGIN, nil)
ParticleManager:SetParticleControl(rocket_particle, 0, self:GetCaster():GetAttachmentOrigin(self:GetCaster():ScriptLookupAttachment("attach_rocket")))
ParticleManager:SetParticleControl(rocket_particle, 1, self:GetCursorPosition())
ParticleManager:SetParticleControl(rocket_particle, 2, Vector(self:GetTalentSpecialValueFor("speed"), 0, 0))
local rocket =
{
Target = rocket_target,
Source = self:GetCaster(),
Ability = self,
--EffectName = "particles/units/heroes/hero_rattletrap/rattletrap_rocket_flare.vpcf", // IDK why this works as a projectile but you have to use it like a particle anyways and split everything up ugh
iMoveSpeed = self:GetTalentSpecialValueFor("speed"),
vSourceLoc = self:GetCaster():GetAttachmentOrigin(self:GetCaster():ScriptLookupAttachment("attach_rocket")),
bDrawsOnMinimap = true,
bDodgeable = true,
bIsAttack = false,
bVisibleToEnemies = true,
bReplaceExisting = false,
flExpireTime = GameRules:GetGameTime() + 20,
bProvidesVision = true,
iVisionRadius = self:GetSpecialValueFor("vision_radius"),
iVisionTeamNumber = self:GetCaster():GetTeamNumber(),
ExtraData = {rocket_dummy = rocket_dummy:entindex(), rocket_particle = rocket_particle, x = self:GetCaster():GetAbsOrigin().x, y = self:GetCaster():GetAbsOrigin().y, z = self:GetCaster():GetAbsOrigin().z}
}
self:GetCaster():EmitSound("Hero_Rattletrap.Rocket_Flare.Fire")
-- Arbitrary band-aid fix for lingering sounds when cast too close to caster
if (self:GetCursorPosition() - self:GetCaster():GetAbsOrigin()):Length2D() > 200 then
rocket_dummy:EmitSound("Hero_Rattletrap.Rocket_Flare.Travel")
end
ProjectileManager:CreateTrackingProjectile(rocket)
-- Just in case this thing isn't destroying itself
rocket_target:RemoveSelf()
else
-- IMBAfication: Carpet Fire
for instance = 0, self:GetSpecialValueFor("carpet_fire_rockets") - 1 do
local cursor_position = self:GetCursorPosition()
-- Copy pasting the above code with minor visions for stuff like location and damage
Timers:CreateTimer(self:GetSpecialValueFor("carpet_fire_delay") * instance, function()
-- You never know if things are going to go around deleting themselves before they fire...
if self then
local random_position = cursor_position + RandomVector(RandomInt(0, self:GetSpecialValueFor("radius") * self:GetSpecialValueFor("carpet_fire_spread")))
-- Why is this a tracking projectile...
local rocket_target = CreateModifierThinker(self:GetCaster(), self, nil, {
duration = FrameTime() -- Don't really need these things to be existing at all except to be a target for the rocket to go towards -_-
},
random_position, self:GetCaster():GetTeamNumber(), false)
-- This "dummy" literally only exists to attach the rocket travel sound to
local rocket_dummy = CreateModifierThinker(self:GetCaster(), self, nil, {}, self:GetCaster():GetAbsOrigin(), self:GetCaster():GetTeamNumber(), false)
-- Need to look at how to shoot the rocket from the correct place + make the rocet "disappear" from Clockwerk for the duration
local rocket_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_rocket_flare.vpcf", PATTACH_CUSTOMORIGIN, nil)
ParticleManager:SetParticleControl(rocket_particle, 0, self:GetCaster():GetAttachmentOrigin(self:GetCaster():ScriptLookupAttachment("attach_rocket")))
ParticleManager:SetParticleControl(rocket_particle, 1, random_position)
ParticleManager:SetParticleControl(rocket_particle, 2, Vector(self:GetTalentSpecialValueFor("speed"), 0, 0))
local rocket =
{
Target = rocket_target,
Source = self:GetCaster(),
Ability = self,
--EffectName = "particles/units/heroes/hero_rattletrap/rattletrap_rocket_flare.vpcf", // IDK why this works as a projectile but you have to use it like a particle anyways and split everything up ugh
iMoveSpeed = self:GetTalentSpecialValueFor("speed"),
vSourceLoc = self:GetCaster():GetAttachmentOrigin(self:GetCaster():ScriptLookupAttachment("attach_rocket")),
bDrawsOnMinimap = true,
bDodgeable = true,
bIsAttack = false,
bVisibleToEnemies = true,
bReplaceExisting = false,
flExpireTime = GameRules:GetGameTime() + 20,
bProvidesVision = true,
iVisionRadius = self:GetSpecialValueFor("vision_radius"),
iVisionTeamNumber = self:GetCaster():GetTeamNumber(),
ExtraData = {rocket_dummy = rocket_dummy:entindex(), rocket_particle = rocket_particle, x = self:GetCaster():GetAbsOrigin().x, y = self:GetCaster():GetAbsOrigin().y, z = self:GetCaster():GetAbsOrigin().z, carpet_fire = true}
}
self:GetCaster():EmitSound("Hero_Rattletrap.Rocket_Flare.Fire")
rocket_dummy:EmitSound("Hero_Rattletrap.Rocket_Flare.Travel")
ProjectileManager:CreateTrackingProjectile(rocket)
-- Just in case this thing isn't destroying itself
rocket_target:RemoveSelf()
end
end)
end
end
end
-- Make the travel sound follow the rocket
function imba_rattletrap_rocket_flare:OnProjectileThink_ExtraData(vLocation, ExtraData)
EntIndexToHScript(ExtraData.rocket_dummy):SetAbsOrigin(vLocation)
end
function imba_rattletrap_rocket_flare:OnProjectileHit_ExtraData(hTarget, vLocation, ExtraData)
ParticleManager:DestroyParticle(ExtraData.rocket_particle, false)
ParticleManager:ReleaseParticleIndex(ExtraData.rocket_particle)
-- This brings back the rocket model for Clockwerk
if self:GetCaster():GetName() == "npc_dota_hero_rattletrap" and self:GetCaster():GetTogglableWearable( DOTA_LOADOUT_TYPE_MISC ) then
self:GetCaster():GetTogglableWearable( DOTA_LOADOUT_TYPE_MISC ):RemoveEffects(EF_NODRAW)
end
EntIndexToHScript(ExtraData.rocket_dummy):StopSound("Hero_Rattletrap.Rocket_Flare.Travel")
EntIndexToHScript(ExtraData.rocket_dummy):RemoveSelf()
EmitSoundOnLocationWithCaster(vLocation, "Hero_Rattletrap.Rocket_Flare.Explode", self:GetCaster())
local illumination_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_rocket_flare_illumination.vpcf", PATTACH_POINT, hTarget)
-- CP1 controls how long the particle stays for as the x coordinate of vector
ParticleManager:SetParticleControl(illumination_particle, 1, Vector(self:GetSpecialValueFor("duration"), 0, 0))
ParticleManager:ReleaseParticleIndex(illumination_particle)
local enemies = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), vLocation, nil, self:GetSpecialValueFor("radius"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)
local damage = self:GetAbilityDamage()
-- Carpet Fire damage reduction
if ExtraData.carpet_fire then
damage = damage * self:GetSpecialValueFor("carpet_fire_damage") * 0.01
end
-- Retrieve where the Rocket Flare was originally fired from to check for System Critical IMBAfication
local cast_position = Vector(ExtraData.x, ExtraData.y, ExtraData.z)
for _, enemy in pairs(enemies) do
-- Standard damage
local flare_damage = damage
local travel_distance = (enemy:GetAbsOrigin() - cast_position):Length2D()
local target_distance = (enemy:GetAbsOrigin() - vLocation):Length2D()
-- IMBAfication: System Critical
if not ExtraData.carpet_fire and travel_distance >= self:GetSpecialValueFor("system_min_distance") and (target_distance <= self:GetSpecialValueFor("system_radius")) then
flare_damage = damage * self:GetSpecialValueFor("system_crit") * 0.01
SendOverheadEventMessage(nil, OVERHEAD_ALERT_CRITICAL, enemy, flare_damage, nil)
-- Destroy all their mana (only if not a Carpet Fire shot cause """balance""")
-- if enemy.SetMana and not ExtraData.carpet_fire then
-- enemy:SetMana(0)
-- end
enemy:AddNewModifier(self:GetCaster(), self, "modifier_imba_rattletrap_rocket_flare_critical", {duration = self:GetSpecialValueFor("system_duration") * (1 - enemy:GetStatusResistance())})
end
local damageTable = {
victim = enemy,
damage = flare_damage,
damage_type = self:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self
}
ApplyDamage(damageTable)
-- Voice response for "Killing enemy, 6000 minimum travel distance"
if not enemy:IsAlive() and self:GetCaster():GetName() == "npc_dota_hero_rattletrap" and travel_distance >= 6000 then
local random_response = RandomInt(8, 12)
if random_response <= 9 then
self:GetCaster():EmitSound("rattletrap_ratt_ability_flare_0"..random_response)
else
self:GetCaster():EmitSound("rattletrap_ratt_ability_flare_"..random_response)
end
end
end
AddFOWViewer(self:GetCaster():GetTeamNumber(), vLocation, self:GetSpecialValueFor("radius"), self:GetSpecialValueFor("duration"), false)
-- Truesight talent (Carpet Fire doesn't get this for "balance" reasons)
if self:GetCaster():HasTalent("special_bonus_imba_rattletrap_rocket_flare_truesight") and not ExtraData.carpet_fire then
local sight_area = CreateModifierThinker(self:GetCaster(), self, "modifier_item_gem_of_true_sight", {
duration = self:GetSpecialValueFor("duration")
},
vLocation, self:GetCaster():GetTeamNumber(), false)
end
end
------------------------------------
-- ROCKET FLARE CRITICAL MODIFIER --
------------------------------------
function modifier_imba_rattletrap_rocket_flare_critical:IsPurgable() return false end
function modifier_imba_rattletrap_rocket_flare_critical:GetStatusEffectName()
return "particles/status_fx/status_effect_techies_stasis.vpcf"
end
function modifier_imba_rattletrap_rocket_flare_critical:OnCreated()
self.system_mana_loss_pct = self:GetAbility():GetSpecialValueFor("system_mana_loss_pct")
end
function modifier_imba_rattletrap_rocket_flare_critical:CheckState()
local state = {
[MODIFIER_STATE_FROZEN] = true,
[MODIFIER_STATE_STUNNED] = true,
[MODIFIER_STATE_PASSIVES_DISABLED] = true
}
return state
end
function modifier_imba_rattletrap_rocket_flare_critical:DeclareFunctions()
local decFuncs = {
MODIFIER_PROPERTY_MANA_REGEN_TOTAL_PERCENTAGE
}
return decFuncs
end
function modifier_imba_rattletrap_rocket_flare_critical:GetModifierTotalPercentageManaRegen()
return (self.system_mana_loss_pct - 100) / 100
end
--------------
-- HOOKSHOT --
--------------
function imba_rattletrap_hookshot:GetBehavior()
return DOTA_ABILITY_BEHAVIOR_POINT + DOTA_ABILITY_BEHAVIOR_IGNORE_BACKSWING + DOTA_ABILITY_BEHAVIOR_AUTOCAST
end
function imba_rattletrap_hookshot:GetCooldown(iLevel)
if self:GetCaster():HasScepter() then
return self:GetSpecialValueFor("cooldown_scepter")
else
return self.BaseClass.GetCooldown(self, iLevel)
end
end
function imba_rattletrap_hookshot:OnAbilityPhaseStart()
if not IsServer() then return end
self:GetCaster():StartGesture(ACT_DOTA_RATTLETRAP_HOOKSHOT_START)
return true
end
function imba_rattletrap_hookshot:OnSpellStart()
if not IsServer() then return end
-- Preventing projectiles getting stuck in one spot due to potential 0 length vector
if self:GetCursorPosition() == self:GetCaster():GetAbsOrigin() then
self:GetCaster():SetCursorPosition(self:GetCursorPosition() + self:GetCaster():GetForwardVector())
end
self:GetCaster():EmitSound("Hero_Rattletrap.Hookshot.Fire")
-- Direction the hook is facing
self.direction = (self:GetCursorPosition() - self:GetCaster():GetAbsOrigin()):Normalized()
-- In case the z-axis shoots off to some weird alternate dimension
self.direction.z = 0
-- Accounts for total of travel time to and from the full distance
local hookshot_duration = ((self:GetSpecialValueFor("tooltip_range") + GetCastRangeIncrease(self:GetCaster())) / self:GetSpecialValueFor("speed")) * 2
local hookshot_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_rattletrap/rattletrap_hookshot.vpcf", PATTACH_CUSTOMORIGIN, nil)
-- CP0 is the hook's starting point
ParticleManager:SetParticleControlEnt(hookshot_particle, 0, self:GetCaster(), PATTACH_POINT_FOLLOW, "attach_weapon", self:GetCaster():GetAbsOrigin(), true)
-- CP1 is the farthest point the hook will travel
ParticleManager:SetParticleControl(hookshot_particle, 1, self:GetCaster():GetAbsOrigin() + self.direction * (self:GetSpecialValueFor("tooltip_range") + GetCastRangeIncrease(self:GetCaster())))
-- CP2 is the speed at which the hook travels
ParticleManager:SetParticleControl(hookshot_particle, 2, Vector(self:GetSpecialValueFor("speed"), 0, 0))
-- CP3 is the duration at which the hook will last for
ParticleManager:SetParticleControl(hookshot_particle, 3, Vector(hookshot_duration, 0, 0))
local linear_projectile = {
Ability = self,
-- EffectName = "particles/units/heroes/hero_rattletrap/rattletrap_hookshot.vpcf", -- Doesn't do anything
vSpawnOrigin = self:GetCaster():GetAbsOrigin(),
fDistance = self:GetSpecialValueFor("tooltip_range") + GetCastRangeIncrease(self:GetCaster()),
fStartRadius = self:GetSpecialValueFor("latch_radius"),
fEndRadius = self:GetSpecialValueFor("latch_radius"),
Source = self:GetCaster(),
bHasFrontalCone = false,
bReplaceExisting = false,
iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_BOTH,
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_INVULNERABLE,
iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP,
fExpireTime = GameRules:GetGameTime() + 10.0,
bDeleteOnHit = true,
vVelocity = (self:GetCursorPosition() - self:GetCaster():GetAbsOrigin()):Normalized() * self:GetSpecialValueFor("speed") * Vector(1, 1, 0),
bProvidesVision = false,
ExtraData = {hookshot_particle = hookshot_particle}
}
-- IMBAfication: Shish Kabob
if self:GetAutoCastState() then
linear_projectile.ExtraData.autocast = true
self.shish_kabob = {}
end
-- Clear out Razor Wind IMBAfication table to begin adding new victims if applicable
self.razor_wind = {}
self.projectile = ProjectileManager:CreateLinearProjectile(linear_projectile)
-- This temporarily deletes the hook model from Clockwerk
if self:GetCaster():GetName() == "npc_dota_hero_rattletrap" and self:GetCaster():GetTogglableWearable( DOTA_LOADOUT_TYPE_WEAPON ) then
self:GetCaster():GetTogglableWearable( DOTA_LOADOUT_TYPE_WEAPON ):AddEffects(EF_NODRAW)
end
-- This block is just for the hook model returning back if a hook is missed
local caster = self:GetCaster()
Timers:CreateTimer(hookshot_duration, function()
-- Return the hook model to Clockwerk
if caster:GetName() == "npc_dota_hero_rattletrap" and caster:GetTogglableWearable( DOTA_LOADOUT_TYPE_WEAPON ) then
caster:GetTogglableWearable( DOTA_LOADOUT_TYPE_WEAPON ):RemoveEffects(EF_NODRAW)
end
end)
end
-- IMBAfication: Razor Wind
function imba_rattletrap_hookshot:OnProjectileThink_ExtraData(vLocation, ExtraData)
if not IsServer() then return end
local enemies = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), vLocation, nil, self:GetSpecialValueFor("razor_wind_radius"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false)
for _, enemy in pairs(enemies) do
local distance_vector = enemy:GetAbsOrigin() - vLocation
-- If the hook isn't going to latch onto the enemy to begin with, and the angle that the hook passes the enemy at is between 60 and 120 degrees relative to its own direction (the double math.abs is to just save on having to an an additional conditional), then they get affected by Razor Wind
-- 60 to 120 degrees is just a safety deviation from the standard perpendicular angle (90 degrees) expected to pass by
if distance_vector:Length2D() > self:GetSpecialValueFor("latch_radius") and math.abs(math.abs(AngleDiff(VectorToAngles(distance_vector).y, VectorToAngles(self.direction).y)) - 90) <= 30 and not self.razor_wind[enemy:GetEntityIndex()] then
enemy:AddNewModifier(self:GetCaster(), self, "modifier_stunned", {duration = 0.1 * (1 - enemy:GetStatusResistance())})
local damageTable = {
victim = enemy,
damage = self:GetSpecialValueFor("damage") * self:GetSpecialValueFor("razor_wind_damage") * 0.01,
damage_type = DAMAGE_TYPE_MAGICAL,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self
}
ApplyDamage(damageTable)
-- Add enemy to Razor Wind table so they don't get affected again by the same hook
self.razor_wind[enemy:GetEntityIndex()] = true
end
end
end
function imba_rattletrap_hookshot:OnProjectileHit_ExtraData(hTarget, vLocation, ExtraData)
if not IsServer() then return end
if hTarget then
if hTarget ~= self:GetCaster() then
if not ExtraData.autocast then
-- No matter what I try, these god damn sounds won't consistently stop which is pissing me off
self:GetCaster():StopSound("Hero_Rattletrap.Hookshot.Fire")
hTarget:EmitSound("Hero_Rattletrap.Hookshot.Impact")
-- Retract sound lingers if target is too close to caster at start so only make it play if they were farther to begin with
if (self:GetCaster():GetAbsOrigin() - hTarget:GetAbsOrigin()):Length2D() > self:GetSpecialValueFor("latch_radius") then
self:GetCaster():EmitSound("Hero_Rattletrap.Hookshot.Retract")
end
ParticleManager:SetParticleControlEnt(ExtraData.hookshot_particle, 1, hTarget, PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", hTarget:GetAbsOrigin(), true)
-- "The pulling lasts a maximum of 0.5 seconds, so if the target moves away, Clockwerk may not fully reach it."
-- Gonna make this last cast range / speed seconds instead of 0.5 due to warped values; the vanilla always has speed at double max range but things are a little different here
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_rattletrap_hookshot",
{
duration = (self:GetSpecialValueFor("tooltip_range") + self:GetCaster():GetCastRangeBonus()) / self:GetSpecialValueFor("speed"),
latch_radius = self:GetSpecialValueFor("latch_radius"),
stun_radius = self:GetSpecialValueFor("stun_radius"),
stun_duration = self:GetSpecialValueFor("duration"),
speed = self:GetSpecialValueFor("speed"),
damage = self:GetSpecialValueFor("damage"),
ent_index = hTarget:GetEntityIndex(),
particle = ExtraData.hookshot_particle
})
-- This line is so Clockwerk doesn't pierce through everyone if there are multiple targets (although that would be pretty cool)
-- It may interfere with previous projectiles if you're shooting multiple at once (aka WTF mode) but come on now, vanilla arguably handles this even worse with lingering particles so no bulli
ProjectileManager:DestroyLinearProjectile(self.projectile)
return true
else
hTarget:EmitSound("Hero_Rattletrap.Hookshot.Impact")
table.insert(self.shish_kabob, hTarget:GetEntityIndex())
ParticleManager:SetParticleControlEnt(ExtraData.hookshot_particle, 1, hTarget, PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", hTarget:GetAbsOrigin(), true)
end
if hTarget:GetTeamNumber() ~= self:GetCaster():GetTeamNumber() then
hTarget:AddNewModifier(self:GetCaster(), self, "modifier_stunned", {duration = self:GetSpecialValueFor("duration") * (1 - hTarget:GetStatusResistance())})
end
end
else
if ExtraData.autocast and #self.shish_kabob > 0 then
-- Retract sound lingers if target is too close to caster at start so only make it play if they were farther to begin with
if (self:GetCaster():GetAbsOrigin() - EntIndexToHScript(self.shish_kabob[#self.shish_kabob]):GetAbsOrigin()):Length2D() > self:GetSpecialValueFor("latch_radius") then
self:GetCaster():EmitSound("Hero_Rattletrap.Hookshot.Retract")
end
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_rattletrap_hookshot",
{
duration = (self:GetSpecialValueFor("tooltip_range") + self:GetCaster():GetCastRangeBonus()) / self:GetSpecialValueFor("speed"),
latch_radius = self:GetSpecialValueFor("latch_radius"),
stun_radius = self:GetSpecialValueFor("stun_radius"),
stun_duration = self:GetSpecialValueFor("duration"),
speed = self:GetSpecialValueFor("speed"),
damage = self:GetSpecialValueFor("damage"),
ent_index = self.shish_kabob[#self.shish_kabob],
particle = ExtraData.hookshot_particle,
shish_kabob = true
})
end
ParticleManager:SetParticleControl(ExtraData.hookshot_particle, 1, self:GetCaster():GetAbsOrigin())
end
end
-----------------------
-- HOOKSHOT MODIFIER --
-----------------------
function modifier_imba_rattletrap_hookshot:IgnoreTenacity() return true end
function modifier_imba_rattletrap_hookshot:IsPurgable() return false end
function modifier_imba_rattletrap_hookshot:OnCreated(params)
if not IsServer() then return end
self.duration = params.duration
self.latch_radius = params.latch_radius
self.stun_radius = params.stun_radius
self.stun_duration = params.stun_duration
self.speed = params.speed
self.damage = params.damage
self.particle = params.particle
self.shish_kabob = params.shish_kabob
self.target = EntIndexToHScript(params.ent_index)
-- This will be called in the horizontal motion updater, as it is based on target's location rather than hook's landing spot
self.distance = (self.target:GetAbsOrigin() - self:GetCaster():GetAbsOrigin()):Normalized()
-- Initialize table of enemies hit
self.enemies_hit = {}
-- If horizontal motion cannot be applied, remove the modifier
if self:ApplyHorizontalMotionController() == false or (self:GetCaster():GetAbsOrigin() - self.target:GetAbsOrigin()):Length2D() <= self.latch_radius then
self:Destroy()
return
elseif self:GetCaster():GetName() == "npc_dota_hero_rattletrap" then
local responses = {
"rattletrap_ratt_ability_batt_06",
"rattletrap_ratt_ability_batt_07",
"rattletrap_ratt_ability_batt_11",
"rattletrap_ratt_ability_hook_01",
"rattletrap_ratt_ability_hook_02",
"rattletrap_ratt_ability_hook_06",
}
self:GetCaster():EmitSound(responses[RandomInt(1, #responses)])
end
end
function modifier_imba_rattletrap_hookshot:UpdateHorizontalMotion( me, dt )
if not IsServer() then return end
if self:GetCaster() == self:GetParent() then
-- Secondary stun (whoever is passed by Clockwerk in close proximity)
for _, unit in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetCaster():GetAbsOrigin(), nil, self.stun_radius, DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false)) do
-- Apply pass-by stun modifier to enemies
if unit:GetTeamNumber() ~= self:GetCaster():GetTeamNumber() and not self.enemies_hit[unit:GetEntityIndex()] then
unit:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_stunned", {duration = self.stun_duration * (1 - unit:GetStatusResistance())})
ApplyDamage({
victim = unit,
damage = self.damage,
damage_type = DAMAGE_TYPE_MAGICAL,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self:GetAbility()
})
self.enemies_hit[unit:GetEntityIndex()] = true
end
-- Shish Kabob drags units (friend and foe) along with Clockwerk until he reaches the last target
-- Can be blocked by Disabling Help cause this can easily be a griefing ability
if self.shish_kabob and unit ~= self.target and not unit:IsMagicImmune() then
unit:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_rattletrap_hookshot",
{
duration = self:GetRemainingTime(),
latch_radius = self.latch_radius,
stun_radius = 0,
stun_duration = 0,
speed = self.speed,
damage = 0,
ent_index = self.target:GetEntityIndex()
})
end
end
end
self.distance = (self.target:GetAbsOrigin() - self:GetCaster():GetAbsOrigin()):Normalized()
me:SetOrigin( me:GetOrigin() + self.distance * self.speed * dt )
-- IDK what conditionals they use for collision detection so w/e let's use a random one
if (self:GetCaster():GetAbsOrigin() - self.target:GetAbsOrigin()):Length2D() <= self.latch_radius then
FindClearSpaceForUnit(self:GetParent(), self.target:GetAbsOrigin() - self.distance * (self:GetParent():GetHullRadius() + self.target:GetHullRadius()), true)
self:Destroy()
end
end
-- This typically gets called if the caster uses a position breaking tool (ex. Blink Dagger) while in mid-motion
function modifier_imba_rattletrap_hookshot:OnHorizontalMotionInterrupted()
self:Destroy()
end
function modifier_imba_rattletrap_hookshot:OnDestroy()
if not IsServer() then return end
self:GetParent():RemoveHorizontalMotionController( self )
self:GetCaster():StopSound("Hero_Rattletrap.Hookshot.Retract")
self:GetCaster():EmitSound("Hero_Rattletrap.Hookshot.Damage")
-- The things I go through to replicate voice responses zzz
if self:GetCaster():GetName() == "npc_dota_hero_rattletrap" and (self:GetCaster():GetAbsOrigin() - self.target:GetAbsOrigin()):Length2D() <= self.latch_radius and RollPercentage(15) then
if self.target:GetName() == "npc_dota_hero_pudge" then
local responses = {
"rattletrap_ratt_ability_hook_08",
"rattletrap_ratt_ability_hook_11",
"rattletrap_ratt_ability_hook_12"
}
self:GetCaster():EmitSound(responses[RandomInt(1, #responses)])
elseif self.target:GetName() == "npc_dota_hero_tinker" then
self:GetCaster():EmitSound("rattletrap_ratt_ability_hook_13")
else
self:GetCaster():EmitSound("rattletrap_ratt_ability_hook_0"..RandomInt(4, 5))
end
end
if self.particle then
ParticleManager:DestroyParticle(self.particle, false)
ParticleManager:ReleaseParticleIndex(self.particle)
end
self:GetCaster():StartGesture(ACT_DOTA_RATTLETRAP_HOOKSHOT_END)
-- Return the hook model to Clockwerk
if self:GetCaster():GetName() == "npc_dota_hero_rattletrap" and self:GetCaster():GetTogglableWearable( DOTA_LOADOUT_TYPE_WEAPON ) then
self:GetCaster():GetTogglableWearable( DOTA_LOADOUT_TYPE_WEAPON ):RemoveEffects(EF_NODRAW)
end
if self:GetCaster() == self:GetParent() then
for _, unit in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetCaster():GetAbsOrigin(), nil, self.stun_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false)) do
if not self.enemies_hit[unit:GetEntityIndex()] then
unit:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_stunned", {duration = self.stun_duration * (1 - unit:GetStatusResistance())})
ApplyDamage({
victim = unit,
damage = self.damage,
damage_type = DAMAGE_TYPE_MAGICAL,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self:GetAbility()
})
self.enemies_hit[unit:GetEntityIndex()] = true
end
end
end
end
function modifier_imba_rattletrap_hookshot:CheckState()
if self:GetParent():GetTeamNumber() ~= self:GetCaster():GetTeamNumber() or self:GetParent() == self:GetCaster() then
return {
[MODIFIER_STATE_SILENCED] = true,
[MODIFIER_STATE_DISARMED] = true,
}
end
end
function modifier_imba_rattletrap_hookshot:DeclareFunctions()
return {
MODIFIER_PROPERTY_OVERRIDE_ANIMATION
}
end
function modifier_imba_rattletrap_hookshot:GetOverrideAnimation()
return ACT_DOTA_RATTLETRAP_HOOKSHOT_LOOP
end
---------------------
-- TALENT HANDLERS --
---------------------
LinkLuaModifier("modifier_special_bonus_imba_rattletrap_battery_assault_aura", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_rattletrap_rocket_flare_truesight", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_rattletrap_rocket_flare_speed", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_rattletrap_battery_assault_interval", "components/abilities/heroes/hero_rattletrap", LUA_MODIFIER_MOTION_NONE)
modifier_special_bonus_imba_rattletrap_battery_assault_aura = modifier_special_bonus_imba_rattletrap_battery_assault_aura or class({})
modifier_special_bonus_imba_rattletrap_rocket_flare_truesight = modifier_special_bonus_imba_rattletrap_rocket_flare_truesight or class({})
modifier_special_bonus_imba_rattletrap_rocket_flare_speed = modifier_special_bonus_imba_rattletrap_rocket_flare_speed or class({})
modifier_special_bonus_imba_rattletrap_battery_assault_interval = modifier_special_bonus_imba_rattletrap_battery_assault_interval or class({})
function modifier_special_bonus_imba_rattletrap_battery_assault_aura:IsHidden() return true end
function modifier_special_bonus_imba_rattletrap_battery_assault_aura:IsPurgable() return false end
function modifier_special_bonus_imba_rattletrap_battery_assault_aura:RemoveOnDeath() return false end
function modifier_special_bonus_imba_rattletrap_rocket_flare_truesight:IsHidden() return true end
function modifier_special_bonus_imba_rattletrap_rocket_flare_truesight:IsPurgable() return false end
function modifier_special_bonus_imba_rattletrap_rocket_flare_truesight:RemoveOnDeath() return false end
function modifier_special_bonus_imba_rattletrap_rocket_flare_speed:IsHidden() return true end
function modifier_special_bonus_imba_rattletrap_rocket_flare_speed:IsPurgable() return false end
function modifier_special_bonus_imba_rattletrap_rocket_flare_speed:RemoveOnDeath() return false end
function modifier_special_bonus_imba_rattletrap_battery_assault_interval:IsHidden() return true end
function modifier_special_bonus_imba_rattletrap_battery_assault_interval:IsPurgable() return false end
function modifier_special_bonus_imba_rattletrap_battery_assault_interval:RemoveOnDeath() return false end
|
-- Copyright 2016-2021 Gabriel Dubatti. See LICENSE.
if toolbar then
local Util = Util
require('toolbar.constants')
if actions then require('toolbar.actions') end
require('toolbar.minimap')
require('toolbar.controls')
require('toolbar.configtb') --config panel on toolbar #3
require('toolbar.dialogs')
local events, events_connect = events, events.connect
toolbar.tabpos= 0
toolbar.keyflags= 0 --key modifiers for current toolbar event (toolbar.KEYFLAGS.xxx)
--select a toolbar as current
function toolbar.sel_toolbar_n(ntb, ngrp, emptygrp)
if ngrp == nil then ngrp = 0 end
if toolbar.current_toolbar ~= ntb or toolbar.current_tb_group ~= ngrp or emptygrp then
toolbar.current_toolbar= ntb
toolbar.current_tb_group= ngrp
toolbar.seltoolbar(ntb,ngrp,emptygrp)
end
end
--select a toolbar by name
function toolbar.sel_top_bar(ngrp, emptygrp)
toolbar.sel_toolbar_n(toolbar.TOP_TOOLBAR, ngrp, emptygrp)
end
function toolbar.sel_left_bar(ngrp, emptygrp)
toolbar.sel_toolbar_n(toolbar.LEFT_TOOLBAR, ngrp, emptygrp)
end
function toolbar.sel_stat_bar(ngrp, emptygrp)
toolbar.sel_toolbar_n(toolbar.STAT_TOOLBAR, ngrp, emptygrp)
end
function toolbar.sel_config_bar(ngrp, emptygrp)
toolbar.sel_toolbar_n(toolbar.RIGHT_TOOLBAR, ngrp, emptygrp)
end
function toolbar.sel_minimap(ngrp, emptygrp)
toolbar.sel_toolbar_n(toolbar.MINIMAP_TOOLBAR)
end
function toolbar.sel_results_bar(ngrp, emptygrp)
toolbar.sel_toolbar_n(toolbar.RESULTS_TOOLBAR, ngrp, emptygrp)
end
function toolbar.sel_combo_popup(ngrp, emptygrp)
toolbar.sel_toolbar_n(toolbar.COMBO_POPUP, ngrp, emptygrp)
end
function toolbar.sel_dialog_popup(ngrp, emptygrp)
toolbar.sel_toolbar_n(toolbar.DIALOG_POPUP, ngrp, emptygrp)
end
function toolbar.setthemeicon(name,icon,num)
--set button icon, get icon from theme's icons folder
toolbar.seticon(name,toolbar.iconspath..icon..".png",num or toolbar.TTBI_TB.IT_NORMAL)
end
function toolbar.isbufhide(buf)
--hide all project buffers (but not projects in edit mode)
if Proj then return Proj.isHiddenTabBuf(buf) end
--show all other buffers
return false
end
--select the top toolbar and return the tab number of a buffer
local function getntabbuff(buf)
--tabs are in the top bar
toolbar.sel_top_bar()
if buf._buffnum == nil then
--assign a unique number to each buffer
buf._buffnum= toolbar.buffnum
toolbar.buffnum= toolbar.buffnum+1
toolbar.buffers[_BUFFERS[buf]]= buf._buffnum
elseif buf._buffnum >= toolbar.buffnum then toolbar.buffnum= buf._buffnum+1 end --restore toolbar.buffnum after reset
return buf._buffnum
end
local function set_chg_tabbuf(buf)
if buf == nil then
--update current tab
buf= buffer
end
--select the top toolbar and get the tab number of the buffer
local ntab= getntabbuff(buf)
--update tab text
local filename = buf.filename or buf._type or Util.UNTITLED_TEXT
local tabtext= string.match(filename, ".-([^\\/]*)$")
--update modified indicator in tab
if toolbar.cfg.tabmodified == 0 and buf.modify then tabtext= tabtext .. "*" end --modified: change tab text
if buf._right_side then
tabtext= ">"..tabtext
end
local tooltip= buf.filename
if tooltip then
if buf.mod_time then tooltip= tooltip.."\n"..os.date('%c', buf.mod_time) end
else
tooltip= filename
end
toolbar.settab(ntab, tabtext:iconv('UTF-8',_CHARSET), tooltip:iconv('UTF-8',_CHARSET))
toolbar.hidetab(ntab, toolbar.isbufhide(buf))
if toolbar.cfg.tabmodified ~= 0 then toolbar.modifiedtab(ntab, buf.modify) end --modified: change tab color/img
end
function toolbar.update_all_modified()
for i, buf in ipairs(_BUFFERS) do
set_chg_tabbuf(buf)
end
end
--select a buffer's tab
function toolbar.seltabbuf(buf)
--select the top toolbar and get the tab number of the buffer
local ntab= getntabbuff(buf)
--force visible state 'before' activate the tab
toolbar.hidetab(ntab, toolbar.isbufhide(buf))
toolbar.currenttab= ntab
toolbar.activatetab(ntab)
set_chg_tabbuf(buf)
end
--select the top toolbar and get the buffer number of a tab
function toolbar.gettabnbuff(ntab)
--tabs are in the top bar
toolbar.sel_top_bar()
for i=1,#_BUFFERS do
if toolbar.buffers[i] == ntab then return i end
end
return 0 --not found
end
events_connect(events.SAVE_POINT_REACHED, set_chg_tabbuf)
events_connect(events.SAVE_POINT_LEFT, set_chg_tabbuf)
function toolbar.selecttab(ntab)
--select the top toolbar and get the buffer number of a tab
local nb= toolbar.gettabnbuff(ntab)
if nb > 0 then
local buf= _BUFFERS[nb]
toolbar.seltabbuf(buf)
--check if a view change is needed
if Proj and Proj.tab_changeView(buf) then return end
Util.goto_buffer(buf)
end
end
local function lexer_selected(lex_sel)
buffer:set_lexer(lex_sel)
events.emit(events.UPDATE_UI, 1) -- for updating statusbar
toolbar.update_lexerdefaults() --update config panel
end
function toolbar.select_lexer()
local lexers = {}
local LEXERS = _SCINTILLA.properties.lexer_language[1]
for name in buffer:private_lexer_call(LEXERS):gmatch('[^\n]+') do lexers[#lexers + 1] = name end
toolbar.small_chooser(_L['Select Lexer'], buffer:get_lexer(), lexer_selected, lexers, "T2_TAB#4",
toolbar.ANCHOR.HCENTER, 250, 300, "LEXER")
end
local function eol_selected(eol_sel)
local mode= string.match(eol_sel,'%+') and buffer.EOL_CRLF or buffer.EOL_LF
buffer.eol_mode = mode
buffer:convert_eols(mode)
events.emit(events.UPDATE_UI,1) -- for updating statusbar
toolbar.setcfg_from_eolmode() --update config panel
end
local function change_eol()
local eol_list
if WIN32 then eol_list= {"CR+LF (OS default)","LF"} else eol_list= {"CR+LF","LF (OS default)"} end
toolbar.small_chooser("Select EOL", eol_list[buffer.eol_mode == buffer.EOL_CRLF and 1 or 2], eol_selected, eol_list, "T2_TAB#5",
toolbar.ANCHOR.HCENTER, 210, 110, "dialog-apply")
end
local function enc_selected(enc_sel)
buffer:set_encoding(enc_sel)
events.emit(events.UPDATE_UI, 1) -- for updating statusbar
if actions then
actions.updateaction("set_enc_utf8")
actions.updateaction("set_enc_ascii")
actions.updateaction("set_enc_1252")
actions.updateaction("set_enc_8859")
actions.updateaction("set_enc_utf16")
end
end
local function change_encoding()
local enc_list= {'UTF-8','ASCII','CP1252','ISO-8859-1','UTF-16LE'}
toolbar.small_chooser("Select buffer enconding", buffer.encoding, enc_selected, enc_list, "T2_TAB#7",
toolbar.ANCHOR.HCENTER, 210, 185, "insert-text")
end
local function go_line_col(line, col)
if line and col then
line= math.floor(line)
col= math.floor(col)
buffer:ensure_visible_enforce_policy(line)
local pos = buffer:find_column(line, col)
buffer:goto_pos(pos)
end
end
local function gotoline_selected(linenum)
go_line_col(tonumber(linenum), 1)
end
local function gotocol_selected(colnum)
local line = buffer:line_from_position(buffer.current_pos)
go_line_col(line, tonumber(colnum))
end
events_connect("toolbar_tabclicked", function(ntab,ntoolbar,ntabgroup,keyflags)
toolbar.keyflags= keyflags
--ui.statusbar_text= "tab "..ntab.." clicked"
if ntoolbar == toolbar.TOP_TOOLBAR then
--tab bar click
toolbar.selecttab(ntab)
elseif ntoolbar == toolbar.STAT_TOOLBAR then
--status bar click
if ntab == 1 then --info
if toolbar.results_onoff then toolbar.results_onoff() end --show/hide result toolbar
elseif ntab == 2 then --Line
if Proj then Proj.store_current_pos(true) end
toolbar.small_edit("Goto line", "", "Line number", gotoline_selected, "T2_TAB#2", toolbar.ANCHOR.HCENTER, 200, 59, "go-jump")
elseif ntab == 3 then --Col
if Proj then Proj.store_current_pos(true) end
toolbar.small_edit("Goto Column", "", "Column number", gotocol_selected, "T2_TAB#3", toolbar.ANCHOR.HCENTER, 200, 59, "go-jump")
elseif ntab == 4 then --lexer
--textadept.file_types.select_lexer()
toolbar.select_lexer()
elseif ntab == 5 then --eol
change_eol()
elseif ntab == 6 then --indent
toolbar.toggle_buffer_configtab()
elseif ntab == 7 then --encoding
change_encoding()
end
elseif ntoolbar == toolbar.RIGHT_TOOLBAR then
--config panel
toolbar.config_tab_click(ntab)
end
end)
events_connect("toolbar_tabRclicked", function(ntab,ntoolbar,ntabgroup,keyflags)
toolbar.keyflags= keyflags
--ui.statusbar_text= "tab "..ntab.." R clicked"
if ntoolbar == toolbar.TOP_TOOLBAR then
toolbar.selecttab(ntab)
return true --open context menu
end
end)
events_connect("toolbar_tab2clicked", function(ntab,ntoolbar,ntabgroup,keyflags)
toolbar.keyflags= keyflags
--double click tab: close current buffer
--ui.statusbar_text= "tab "..ntab.." 2 clicked"
if ntoolbar == 0 and toolbar.cfg.tab2clickclose then
if Proj then Proj.close_buffer() else buffer:close() end
end
end)
events_connect("toolbar_tabclose", function(ntab,ntoolbar,ntabgroup,keyflags)
toolbar.keyflags= keyflags
--close tab button clicked: close current buffer
--ui.statusbar_text= "tab "..ntab.." close clicked"
if ntoolbar == 0 then
if Proj then Proj.close_buffer() else buffer:close() end
end
end)
events_connect(events.FILE_OPENED, function()
--select the top toolbar and get the tab number of the buffer
local ntab= getntabbuff(buffer)
local filename = buffer.filename or buffer._type or Util.UNTITLED_TEXT
toolbar.settab(ntab, string.match(filename, ".-([^\\/]*)$"), filename)
toolbar.seltabbuf(buffer)
end)
events_connect(events.BUFFER_NEW, function()
if _BUFFERS[buffer] > 0 then --ignore command line TA
--select the top toolbar and get the tab number of the buffer
local ntab= getntabbuff(buffer)
local filename= Util.UNTITLED_TEXT
toolbar.settab(ntab, filename, filename)
toolbar.seltabbuf(buffer)
end
end)
events_connect(events.BUFFER_DELETED, function()
--TA doesn't inform which buffer was deleted so,
--check the tab list to find out
--tabs are in the top bar
toolbar.sel_top_bar()
if #toolbar.buffers == #_BUFFERS+1 then
local deleted= false
for i=1, #_BUFFERS do
if toolbar.buffers[i] ~= _BUFFERS[i]._buffnum then
toolbar.deletetab(toolbar.buffers[i])
deleted= true
break
end
end
if not deleted then --delete the last one
toolbar.deletetab(toolbar.buffers[#toolbar.buffers])
end
--rebuild the buffers list
toolbar.buffers={}
for i=1,#_BUFFERS do
toolbar.buffers[i]= _BUFFERS[i]._buffnum
end
else
ui.statusbar_text= "ERROR, toolbar N="..#toolbar.buffers.." buffers N="..#_BUFFERS
end
--select current buffer's tab
toolbar.seltabbuf(buffer)
end)
events_connect(events.BUFFER_AFTER_SWITCH, function()
toolbar.seltabbuf(buffer)
end)
events_connect(events.VIEW_AFTER_SWITCH, function()
toolbar.seltabbuf(buffer)
end)
local function getCfgNum(line, field)
if line:find('^'..field..':') then
toolbar[field]= tonumber(line:match('^'..field..':(.+)$'))
return true
end
return false
end
local function getCfgBool(line, field)
if line:find('^'..field..':t') then
toolbar[field]= true
return true
end
if line:find('^'..field..':f') then
toolbar[field]= false
return true
end
return false
end
--define config fields
local function tbconfig_int(var, defval)
local ci= Util.cfg_int
if type(defval) == "table" then ci= Util.cfg_int2 + #defval -2 end
Util.add_config_field(toolbar.cfg, var, ci, defval)
end
local function tbconfig_color(var, defval)
Util.add_config_field(toolbar.cfg, var, Util.cfg_hex, defval)
end
local function tbconfig_bool(var, defval)
Util.add_config_field(toolbar.cfg, var, Util.cfg_bool, defval)
end
local function tbconfig_str(var, defval)
Util.add_config_field(toolbar.cfg, var, Util.cfg_str, defval)
end
local function tbconfig_imgs(var, maxidx)
Util.add_config_field(toolbar.cfg, var, Util.cfg_str, "", maxidx)
end
--config images
local function load_multipart_img()
--already loaded?
if toolbar.multipartimgs and toolbar.multipartimgs[0] == toolbar.themepath then return end
toolbar.multipartimgs= {}
toolbar.multipartimgs[0]= toolbar.themepath --save theme path
for fname in lfs.dir(toolbar.themepath) do
local baseimg= string.match(fname, "(.-)__[LRTBWH0123456789]+%.png$")
if baseimg then toolbar.multipartimgs[baseimg]= string.match(fname, "(.-)%.png$") end
end
end
--add the multipart img suffix
function toolbar.themed_multipart_img(img)
load_multipart_img()
return toolbar.multipartimgs[img] or img
end
function toolbar.themed_icon(name,icon,nicon)
--change image only in this toolbar
toolbar.seticon(name,toolbar.themed_multipart_img(icon),nicon or toolbar.TTBI_TB.IT_NORMAL,true)
end
function toolbar.get_img(idx)
return toolbar.cfg[ "toolbar_img#"..idx ]
end
function toolbar.set_img(idx, newimg, onlyifempty)
if onlyifempty and toolbar.get_img(idx) ~= "" then return end
toolbar.cfg[ "toolbar_img#"..idx ]= newimg
end
function toolbar.get_img_count()
return toolbar.cfg[toolbar.cfg[0]["toolbar_img#1"]][4]
end
function toolbar.get_backimg(idx)
return toolbar.cfg[ "toolbar_back#"..idx ]
end
function toolbar.set_backimg(idx, newimg, onlyifempty)
if onlyifempty and toolbar.get_backimg(idx) ~= "" then return end
toolbar.cfg[ "toolbar_back#"..idx ]= newimg
end
function toolbar.get_backimg_count()
return toolbar.cfg[toolbar.cfg[0]["toolbar_back#1"]][4]
end
--get adjust settings (idx=1..6)
local function tbconfig_getadj(idx)
local vadj= toolbar.cfg.toolbar_adj[idx]
--bwidth(idx=1) / bheight(idx=2): 0=use "butsize"
if vadj <= 0 and idx <= 2 then vadj= toolbar.cfg.butsize end
return vadj
end
local function tbconfig_is_adjset()
return (toolbar.cfg.toolbar_adj[1] >= 0) --(-1 not used)
end
function toolbar.set_defaults()
--set toolbar defaults
toolbar.buffnum= 1 --assign a unique number to each buffer
toolbar.buffers= {} --list of buffnum in use
toolbar.themepath= _USERHOME.."/toolbar/bar-sm-light/"
toolbar.iconspath= _USERHOME.."/toolbar/icons/light/"
toolbar.tb0= true --only show toolbar 0 (horizontal)
toolbar.tb1= false
toolbar.statbar= 0 --0:use default statusbar 1:create 2:already created
toolbar.html_tb=false --html toolbar on/off
toolbar.list_tb=false --list toolbar on/off
toolbar.results_tb=false --results toolbar on/off
--config panel
toolbar.cfgpnl_width=350
toolbar.cfgpnl_ymargin=3
toolbar.cfgpnl_xmargin=3
toolbar.cfgpnl_xtext=30
toolbar.cfgpnl_xcontrol3=170
toolbar.cfgpnl_xcontrol2=230
toolbar.cfgpnl_xcontrol=290
toolbar.cfgpnl_rheight=24
--toolbar config
toolbar.cfg= {}
--toolbar images
tbconfig_imgs( "toolbar_img", toolbar.TTBI_TB.N) --toolbar_img#1..#N
tbconfig_imgs( "toolbar_back", 5) --toolbar_back#1..#5
--icons theme
tbconfig_str( "icons", "light")
--adjust
tbconfig_int( "toolbar_adj", {-1, 0, 2, 1, 4, 4}) --0=use "butsize" (-1 not used)
tbconfig_int( "barsize", 27)
tbconfig_int( "butsize", 24)
tbconfig_int( "imgsize", 16)
tbconfig_int( "newrowoff", 3)
tbconfig_int( "textfont_sz", 12)
tbconfig_int( "textfont_yoffset", 0)
tbconfig_color( "textcolor_normal", 0x101010)
tbconfig_color( "textcolor_grayed", 0x808080)
tbconfig_color( "backcolor_erow", -1) --even rows background color (-1:don't change it)
tbconfig_color( "backcolor_hi", -1) --highlight row color (-1:don't change it)
--tabs
tbconfig_int( "tabxmargin", 5)
tbconfig_int( "tabxsep", -1)
tbconfig_bool( "tabwithclose", false)
tbconfig_bool( "tab2clickclose", true)
tbconfig_int( "tabmodified", 0)
tbconfig_int( "tabfont_sz", 0)
tbconfig_int( "tabfont_yoffset", 0)
tbconfig_color( "tabcolor_normal", 0x000000)
tbconfig_color( "tabcolor_hilight", 0x000000)
tbconfig_color( "tabcolor_active", 0x000000)
tbconfig_color( "tabcolor_modif", 0x800000)
tbconfig_color( "tabcolor_grayed", 0x808080)
tbconfig_int( "tabwidthmode", 0) --0=text >0=fixed <0=expand
tbconfig_int( "tabwidthmin", 0)
tbconfig_int( "tabwidthmax", 0)
--status bar
tbconfig_int( "statsize", 20)
tbconfig_int( "statbutsize", 20)
tbconfig_int( "statimgsize", 16)
tbconfig_int( "statxmargin", -3)
tbconfig_int( "statxsep", -1)
tbconfig_int( "statfont_sz", 12)
tbconfig_int( "statfont_yoffset", -2)
tbconfig_color( "statcolor_normal", 0x202020)
tbconfig_color( "statcolor_hilight",0x000000)
--pop-ups
tbconfig_color( "popup_back", 0xFFFFFF)
end
function toolbar.set_theme(theme)
toolbar.themepath= _USERHOME.."/toolbar/"..theme.."/"
Util.load_config_file(toolbar.cfg, toolbar.themepath.."toolbar.cfg")
toolbar.iconspath= _USERHOME.."/toolbar/icons/"..toolbar.cfg.icons.."/"
end
function toolbar.add_tabs_here(extrah, tabwithclose, tabwidthmode, tabwidthmin)
local xcontrol=4 --x-expanded: use all available space
if toolbar.tabpos > 1 then
xcontrol=5 --x-expanded + left align (new row)
end
if not extrah then extrah=0 end
if tabwithclose == nil then tabwithclose= toolbar.cfg.tabwithclose end
if tabwidthmode == nil then tabwidthmode= toolbar.cfg.tabwidthmode end
if tabwidthmin == nil then tabwidthmin= toolbar.cfg.tabwidthmin end
--toolbar.addtabs(xmargin,xsep,withclose,modified(1=img,2=color),fontsz,fontyoffset,[tab-drag],[xcontrol],[height],[font-num])
toolbar.addtabs(toolbar.cfg.tabxmargin, toolbar.cfg.tabxsep, tabwithclose, toolbar.cfg.tabmodified,
toolbar.cfg.tabfont_sz+toolbar.font_tabs_extrasz, toolbar.cfg.tabfont_yoffset,true,xcontrol,toolbar.cfg.barsize+extrah,toolbar.font_tabs) --enable drag support
--toolbar.tabfontcolor(NORMcol,HIcol,ACTIVEcol,MODIFcol,GRAYcol)
toolbar.tabfontcolor(toolbar.cfg.tabcolor_normal, toolbar.cfg.tabcolor_hilight, toolbar.cfg.tabcolor_active,
toolbar.cfg.tabcolor_modif, toolbar.cfg.tabcolor_grayed)
--tabwidthmode: 0=text >0=fixed <0=expand
toolbar.tabwidth(0, tabwidthmode, tabwidthmin, toolbar.cfg.tabwidthmax)
end
--put next buttons in a new row/column
function toolbar.newrow(yoff)
toolbar.gotopos(toolbar.cfg.newrowoff + (yoff or 0)) --new row
end
local function check_tab_img(idx, withclose, defimg)
local img= toolbar.get_img(idx)
if img ~= "" then
--remove "-close" from current if set
local baseimg= string.match(img, "(.-)-close$")
if baseimg then img=baseimg end
else
img= defimg --not set, use default
end
--add "-close" when needed
if withclose then img= img.. "-close" end
toolbar.set_img(idx, img)
end
function toolbar.add_close_tabimg(withclose)
check_tab_img(toolbar.TTBI_TB.TAB_NORMAL, withclose, "ttb-tab-normal")
check_tab_img(toolbar.TTBI_TB.TAB_DISABLED, withclose, "ttb-tab-disabled")
check_tab_img(toolbar.TTBI_TB.TAB_HILIGHT, withclose, "ttb-tab-hilight")
check_tab_img(toolbar.TTBI_TB.TAB_ACTIVE, withclose, "ttb-tab-active")
end
--create the toolbar (tabpos, nvertcols)
--tabpos=0: 1 row, use default tabs
--tabpos=1: 1 row, tabs & buttons in the same line
--tabpos=2: 2 rows, tabs at the top
--tabpos=3: 2 rows, tabs at the bottom
--nvertcols= 0..2 = number of columns in vertical toolbar
--stbar=0: use default
--stbar=1: use tatoolbar
--configpanel==true: add a button to show config panel and create the config panel
function toolbar.create(tabpos, nvertcols, stbar, configpanel)
toolbar.current_toolbar=-1
toolbar.tabpos= tabpos
ui.tabs= (tabpos == 0) --hide regular tabbar if needed
toolbar.statbar= stbar
toolbar.configpanel=configpanel
--tabs to show
if not nvertcols then nvertcols= 0 end
toolbar.tb1= (nvertcols > 0) --vertical
toolbar.tb0= ((tabpos > 0) or (nvertcols==0)) --horizontal
local bsz0= toolbar.cfg.barsize
local butth= bsz0
if tabpos >= 2 then
bsz0= bsz0*2 +1 --two rows
butth= butth+1
end
local bsz1= toolbar.cfg.barsize
if nvertcols > 1 then
bsz1= bsz1*2 +1 --two rows
end
--create toolbar: barsize,buttonsize,imgsize,[numtoolbar/isvertical],[imgpath]
if toolbar.tb0 then --create the horizontal toolbar
toolbar.new(bsz0, toolbar.cfg.butsize, toolbar.cfg.imgsize, toolbar.TOP_TOOLBAR, toolbar.themepath)
toolbar.current_toolbar= 0
toolbar.current_tb_group= 0
--choose the right tab image
toolbar.add_close_tabimg(toolbar.cfg.tabwithclose)
--add/change some images
for i=1, toolbar.get_img_count() do
local img= toolbar.get_img(i)
if img ~= "" then toolbar.themed_icon(toolbar.globalicon, img, i) end
end
if tabpos == 1 then --horizontal back x 1row
toolbar.themed_icon(toolbar.globalicon, toolbar.get_backimg(1), toolbar.TTBI_TB.BACKGROUND)
elseif tabpos > 1 then --horizontal back x 2rows
toolbar.themed_icon(toolbar.globalicon, toolbar.get_backimg(2), toolbar.TTBI_TB.BACKGROUND)
end
if tabpos == 2 then
--2 rows, tabs at the top
toolbar.add_tabs_here(1)
--put buttons in another group
butth= toolbar.cfg.barsize
end
--buttons group: align left + width=use buttons / fixed height=butth
toolbar.addgroup(toolbar.GRPC.FIRST|toolbar.GRPC.ITEMSIZE, 0, 0, butth)
if tbconfig_is_adjset() then
--bwidth,bheight,xmargin,ymargin,xoff,yoff
toolbar.adjust(tbconfig_getadj(1),tbconfig_getadj(2),tbconfig_getadj(3),tbconfig_getadj(4),tbconfig_getadj(5),tbconfig_getadj(6))
end
toolbar.setdefaulttextfont()
else
--hide the horizonatal (top) toolbar
toolbar.sel_top_bar()
toolbar.show(false)
end
--create toolbar: barsize,buttonsize,imgsize,[numtoolbar/isvertical],[imgpath]
if toolbar.tb1 then --create the vertical toolbar
toolbar.new(bsz1, toolbar.cfg.butsize, toolbar.cfg.imgsize, toolbar.LEFT_TOOLBAR, toolbar.themepath)
toolbar.current_toolbar= 1
toolbar.current_tb_group= 0
--buttons group: align top + height=use buttons / fixed width
toolbar.addgroup(0, toolbar.GRPC.FIRST|toolbar.GRPC.ITEMSIZE, toolbar.cfg.barsize, 0)
if tbconfig_is_adjset() then
--bwidth,bheight,xmargin,ymargin,xoff,yoff
toolbar.adjust(tbconfig_getadj(1),tbconfig_getadj(2),tbconfig_getadj(3),tbconfig_getadj(4),tbconfig_getadj(5),tbconfig_getadj(6))
end
--add/change some images
for i=1, toolbar.get_img_count() do
local img= toolbar.get_img(i)
if img ~= "" then toolbar.themed_icon(toolbar.globalicon, img, i) end
end
if nvertcols < 2 then --vertical back x 1col
toolbar.themed_icon(toolbar.globalicon, toolbar.get_backimg(3), toolbar.TTBI_TB.BACKGROUND)
else --vertical back x 2cols
toolbar.themed_icon(toolbar.globalicon, toolbar.get_backimg(4), toolbar.TTBI_TB.BACKGROUND)
end
toolbar.setdefaulttextfont()
toolbar.show(true)
else
--hide the vertical (left) toolbar
toolbar.sel_left_bar()
toolbar.show(false)
end
if toolbar.tb0 then
--add buttons in the horizontal (top) toolbar
toolbar.sel_top_bar()
end
--call addpending() later
toolbar._pending= true
end
--add tabs to top toolbar if pending
function toolbar.addpending()
toolbar.sel_top_bar()
if toolbar._pending then
toolbar._pending= false
--1 row, tabs in the same line or 2 rows, tabs at the bottom
if toolbar.tabpos == 1 or toolbar.tabpos == 3 then
toolbar.add_tabs_here()
end
toolbar.show(toolbar.tb0) --show the horizontal toolbar
end
end
function toolbar.addrightgroup()
--buttons group: align right + width=use buttons / fixed height=butth
toolbar.addgroup(toolbar.GRPC.LAST|toolbar.GRPC.ITEMSIZE, 0, 0, toolbar.cfg.barsize)
if tbconfig_is_adjset() then
--bwidth,bheight,xmargin,ymargin,xoff,yoff
toolbar.adjust(tbconfig_getadj(1),tbconfig_getadj(2),0,tbconfig_getadj(4),tbconfig_getadj(5),tbconfig_getadj(6))
end
end
function toolbar.create_statusbar()
toolbar.new(toolbar.cfg.statsize, toolbar.cfg.statbutsize, toolbar.cfg.statimgsize, toolbar.STAT_TOOLBAR, toolbar.themepath)
toolbar.current_toolbar= 2
toolbar.current_tb_group= 0
local bki= toolbar.get_backimg(5)
toolbar.themed_icon(toolbar.globalicon, bki, toolbar.TTBI_TB.TAB_NORMAL)
toolbar.themed_icon(toolbar.globalicon, bki, toolbar.TTBI_TB.TAB_DISABLED)
toolbar.themed_icon(toolbar.globalicon, bki, toolbar.TTBI_TB.TAB_HILIGHT)
toolbar.themed_icon(toolbar.globalicon, bki, toolbar.TTBI_TB.TAB_ACTIVE)
toolbar.setdefaulttextfont()
toolbar.statbar= 2 --created
end
function toolbar.shw_statusbar()
if toolbar.statbar == 1 then
--use tatoolbar's status bar
toolbar.create_statusbar()
end
toolbar.sel_stat_bar()
if toolbar.statbar == 2 then
--toolbar.addtabs(xmargin,xsep,withclose,modified(1=img,2=color),fontsz,fontyoffset,[tab-drag],[xcontrol],[height],[font-num])
toolbar.addtabs(toolbar.cfg.statxmargin, toolbar.cfg.statxsep, false, 0,
toolbar.cfg.statfont_sz+toolbar.font_status_extrasz, toolbar.cfg.statfont_yoffset, false, 4, toolbar.cfg.statsize, toolbar.font_status) --x-expanded
toolbar.tabfontcolor( toolbar.cfg.statcolor_normal, toolbar.cfg.statcolor_hilight, toolbar.cfg.tabcolor_active,
toolbar.cfg.tabcolor_modif, toolbar.cfg.statcolor_normal ) --grayed= normal
--statusbar has 7 sections: 1=text, 2=line, 3=col, 4=lexer, 5=eol, 6=indent, 7=encoding
--change the order of enconding and indentation so that a click in the last section (indent) opens the config panel
local statorder= {1,2,3,4,5,7,6}
for i=1, 7 do
toolbar.settab(statorder[i],"", "") --create the status panels
end
toolbar.tabwidth(1,-1, 150) --expand this section, min width= 150
--NOTE: using variable width in fields 2..7 in "WIN32" breaks the UI!!
-- this fields are updated from the UPDATE-UI event and
-- calling gdk_cairo_create in this context (to get the text extension) freeze the UI for a second
-- and breaks the editor update mecanism (this works fine under LINUX, though)
-- so, fixed width is used for these fields.
toolbar.tabwidth(2, _L['Line:'].." 99999/99999")
local s="actionscript" --same width = looks better
toolbar.tabwidth(3,s) --"Col: 999"
toolbar.tabwidth(4,s) --"actionscript"
toolbar.tabwidth(5,s) --"CRLF"
s= "Tabuladores: 8" --Spanish translation is longer
toolbar.tabwidth(6,s) --"Spaces: 8"
toolbar.tabwidth(7,s) --"ISO-8859-1"
toolbar.show(true)
else
--use the default status bar
toolbar.show(false)
end
end
--toolbar ready, show it
function toolbar.ready()
--add HTML quicktype toolbar if required
if toolbar.add_html_toolbar ~= nil then toolbar.add_html_toolbar() else toolbar.sel_left_bar() end
if toolbar.configpanel then
--add a button to show/hide the config panel
toolbar.add_showconfig_button()
end
toolbar.addpending()
--show status bar if enabled
toolbar.shw_statusbar()
toolbar.sel_top_bar()
if toolbar.configpanel then
--create the config panel
toolbar.add_config_panel()
end
end
events_connect(events.INITIALIZED, function()
if toolbar.tabpos > 0 then
toolbar.sel_top_bar()
--load existing buffers in tab-bar
toolbar.buffers={}
if #_BUFFERS > 0 then
for i, buf in ipairs(_BUFFERS) do
set_chg_tabbuf(buf)
toolbar.buffers[i]= _BUFFERS[i]._buffnum
end
end
toolbar.seltabbuf(buffer) --select current buffer
end
end)
--set the configured theme
function toolbar.set_theme_from_config()
--read the configuration file
toolbar.load_config(true)
local theme= toolbar.get_combo_txt("cbo.theme") or "bar-sm-light"
toolbar.set_theme(theme)
if toolbar.font_support() then
--change editor font
local nfont= toolbar.get_cfg_font_num("font.editor")
local extrasz= toolbar.get_cfg_font_extrasize("font.editor")
if nfont > 0 then
local font= toolbar.get_font_name(nfont)
for _, buff in ipairs(_BUFFERS) do buff.property['font']= font end
end
if extrasz ~= 0 then
extrasz= extrasz + buffer.property['fontsize']
for _, buff in ipairs(_BUFFERS) do buff.property['fontsize']=extrasz end
end
--load toolbar fonts
toolbar.font_toolbars= toolbar.get_cfg_font_num("font.toolbars")
toolbar.font_toolbars_extrasz= toolbar.get_cfg_font_extrasize("font.toolbars")
toolbar.font_tabs= toolbar.get_cfg_font_num("font.tabs")
toolbar.font_tabs_extrasz= toolbar.get_cfg_font_extrasize("font.tabs")
toolbar.font_status= toolbar.get_cfg_font_num("font.status")
toolbar.font_status_extrasz= toolbar.get_cfg_font_extrasize("font.status")
else
toolbar.font_toolbars= 0
toolbar.font_toolbars_extrasz= 0
toolbar.font_tabs= 0
toolbar.font_tabs_extrasz= 0
toolbar.font_status= 0
toolbar.font_status_extrasz= 0
end
end
--create the configured toolbars
function toolbar.create_from_config()
local tabclose= toolbar.get_radio_val("tbtabclose",3)
if tabclose == 1 then toolbar.cfg.tabwithclose=false
elseif tabclose == 2 then toolbar.cfg.tabwithclose=true end
tabclose= toolbar.get_radio_val("tbtab2clickclose",3)
if tabclose == 1 then toolbar.cfg.tab2clickclose=false
elseif tabclose == 2 then toolbar.cfg.tab2clickclose=true end
--create the toolbars (tabpos, nvertcols, stbar, configpanel)
--tabpos=0: 1 row, use default tabs
--tabpos=1: 1 row, tabs & buttons in the same line
--tabpos=2: 2 rows, tabs at the top
--tabpos=3: 2 rows, tabs at the bottom
local tabpos= toolbar.get_radio_val("tbtabs",4) -1
if tabpos < 0 then tabpos= 1 end
--nvertcols= 0..2 = number of columns in vertical toolbar
local nvertcols= toolbar.get_radio_val("tbvertbar", 3)
if nvertcols < 1 then nvertcols=1 end --default= 1 row
if nvertcols == 3 then --hide (only if htmltoolbar is not used)
if toolbar.add_html_toolbar == nil then nvertcols=0 else nvertcols=1 end
end
--stbar=0: use default status bar
--stbar=1: use toolbar's status bar
local statbar= (toolbar.get_check_val("tbshowstatbar") and 1 or 0)
--configpanel==true: add a button to show config panel and create the config panel
toolbar.create(tabpos,nvertcols,statbar,true)
--hide vertical scrollbar
toolbar.tbshowminimap= toolbar.get_check_val("tbshowminimap")
toolbar.tbhidemmapcfg= toolbar.get_check_val("tbhidemmapcfg")
toolbar.tbreplvscroll= toolbar.get_check_val("tbreplvscroll")
toolbar.tbreplhscroll= toolbar.get_check_val("tbreplhscroll")
--create "results" toolbar
if toolbar.createresultstb then toolbar.createresultstb() end
--create "lists" toolbar (add buttons to top_bar to select the lists)
if toolbar.createlisttb then toolbar.createlisttb() end
end
toolbar.set_defaults()
end
|
local request = require('lib.request')
local validator = require('lib.validator')
local response = require('lib.response')
local sms_service = require("services.sms_service")
local _M = {}
function _M:handle()
local args = request:all()
local ok, msg = validator:check(args,{'sms_code', 'phone'})
if not ok then
return false, response:json(0x000001, msg)
end
ok = sms_service:verify_sms_code(args.phone, args.sms_code)
if not ok then
return false, response:json(0x010004)
end
return true
end
return _M
|
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
local generalLoaded = false
local PlayingAnim = false
-------------------------------------------------------------------------------------------------
-------------------------------------- AJOUTE de PNJ --------------------------------------------
-------------------------------------------------------------------------------------------------
local ShopClerk = {
-- ID: id de PNJ | nom: Nom du Blip | BlipID: Icone de Blip | VoiceName: NPC Talk Quand près de lui | Ambiance: Ambiance de Boutique | Arme: Hash of Weapon | modelHash: Modèle | X: Position x | Y: Position Y | Z: Position Z | Rubrique: Où Npc regarde
{id = 1, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 24.392, y = -1345.413, z = 29.497, heading = 264.900}, -- coté de l hobital
{id = 2, name = "Ammunation", VoiceName = "GENERIC_HI", Ambiance = "AMMUCITY", Weapon = 0xA2719263, modelHash = "s_m_y_ammucity_01", x = 841.843566894531, y = -1035.70556640625, z = 28.1948642730713, heading = 3.31448912620544}, -- a coté de pizagouzi
{id = 10, name = "Seller", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "s_m_y_shop_mask", x = 73.842, y = -1393.191, z = 29.376, heading = 285.399}, -- Vendeur Caisse Innocence Boulevard
{id = 11, name = "Seller", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "s_m_y_shop_mask", x = 427.093, y = -806.699, z = 29.491, heading = 86.450}, -- Vendeur Caisse Sinners Passage
{id = 14, name = "Seller", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "a_m_m_indian_01", x = 449.759, y = -802.769, z = 27.805, heading = 292.705}, -- Vendeuse Assistante Sinners Passage
{id = 33, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 24.392, y = -1345.413, z = 29.497, heading = 264.900115966797}, -- Vendeur 24/7 -- Innocence Bld
{id = 34, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = -1221.462, y = -908.003, z = 12.326, heading = 32.798}, -- Vendeur 24/7 -- San Andreas Avenue
{id = 35, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = -706.140, y = -914.504, z = 19.216, heading = 87.130}, -- Vendeur 24/7 -- Palomino Avenue
{id = 36, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = -47.351, y = -1758.636, z = 29.421, heading = 51.165}, -- Vendeur 24/7 -- Davis Avenue
{id = 37, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 1134.337, y = -983.169, z = 46.416, heading = 277.749}, -- Vendeur 24/7 -- El Rancho Bld
{id = 38, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 1164.831, y = -323.663, z = 69.205, heading = 98.426}, -- Vendeur 24/7 -- Mirror Drive West
{id = 39, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 372.991, y = 328.073, z = 103.566, heading = 251.717}, -- Vendeur 24/7 -- Clinton Avenue
{id = 40, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = -1485.916, y = -378.423, z = 40.163, heading = 133.809}, -- Vendeur 24/7 -- Prosperity Street
{id = 41, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = -2966.493, y = 390.399, z = 15.043, heading = 85.741}, -- Vendeur 24/7 -- Great Ocean Highway
{id = 42, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 2555.530, y = 380.910, z = 108.623, heading = 357.827}, -- Vendeur 24/7 -- Palomino Freeway
{id = 43, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = -1819.568, y = 793.541, z = 138.087, heading = 133.800}, -- Vendeur 24/7 -- Banham Canyon Drive
{id = 44, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 1959.255, y = 3741.502, z = 32.344, heading = 300.083}, -- Vendeur 24/7 -- Niland Avenue (Sandy)
{id = 45, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 1697.309, y = 4923.473, z = 42.064, heading = 326.237}, -- Vendeur 24/7 -- Graperssed Main Street
{id = 46, name = "Shop", VoiceName = "GENERIC_HI", Weapon = 0xA2719263, modelHash = "mp_m_shopkeep_01", x = 1728.634, y = 6416.733, z = 35.037, heading = 239.685}, -- Vendeur 24/7 -- Senora Freeway
{id = 13, name = "Seller", VoiceName = "GENERIC_HI", Weapon = 0x5D71A46F, modelHash = "S_F_Y_AirHostess_01", animation="random@shop_clothes@mid", x = 244.202, y = 226.018, z = 106.112, heading = 143.161} -- Accueil PacifiqueBank
}
-------------------------------------------------------------------------------------------------
-------------------------------- FIN d'AJOUTE de PNJ --------------------------------------------
-------------------------------------------------------------------------------------------------
-- Blip pour NPC
Citizen.CreateThread(function()
for k,v in pairs(ShopClerk)do
--local blip = AddBlipForCoord(v.x, v.y, v.z)
--SetBlipSprite(blip, v.BlipID)
SetBlipScale(blip, 0.8)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(v.name)
EndTextCommandSetBlipName(blip)
end
end)
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
-- PNJ de Spawn
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if (not generalLoaded) then
for i=1, #ShopClerk do
RequestModel(GetHashKey(ShopClerk[i].modelHash))
while not HasModelLoaded(GetHashKey(ShopClerk[i].modelHash)) do
Wait(1)
end
ShopClerk[i].id = CreatePed(2, ShopClerk[i].modelHash, ShopClerk[i].x, ShopClerk[i].y, ShopClerk[i].z, ShopClerk[i].heading, false, true)
SetPedFleeAttributes(ShopClerk[i].id, 0, 0)
SetAmbientVoiceName(ShopClerk[i].id, ShopClerk[i].Ambiance)
SetPedDropsWeaponsWhenDead(ShopClerk[i].id, false)
SetPedDiesWhenInjured(ShopClerk[i].id, false)
GiveWeaponToPed(ShopClerk[i].id, ShopClerk[i].Weapon, 2800, false, true)
end
generalLoaded = true
end
end
end)
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
-- Action lorsque joueur Près de NPC (ou non)
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
RequestAnimDict("random@shop_gunstore")
while (not HasAnimDictLoaded("random@shop_gunstore")) do
Citizen.Wait(0)
end
for i=1, #ShopClerk do
distance = GetDistanceBetweenCoords(ShopClerk[i].x, ShopClerk[i].y, ShopClerk[i].z, GetEntityCoords(GetPlayerPed(-1)))
if distance < 3 and PlayingAnim ~= true then
TaskPlayAnim(ShopClerk[i].id,"random@shop_gunstore","_greeting", 1.0, -1.0, 4000, 0, 1, true, true, true)
PlayAmbientSpeech1(ShopClerk[i].id, ShopClerk[i].VoiceName, "SPEECH_PARAMS_FORCE", 1)
PlayingAnim = true
Citizen.Wait(4000)
TaskPlayAnim(ShopClerk[i].id,"random@shop_gunstore","_idle_b", 1.0, -1.0, -1, 0, 1, true, true, true)
Citizen.Wait(4000)
else
--don't touch this
--TaskPlayAnim(ShopClerk[i].id,"random@shop_gunstore","_idle", 1.0, -1.0, -1, 0, 1, true, true, true)
end
if distance > 4 and distance < 7 then
PlayingAnim = false
end
end
end
end)
|
local K, C = unpack(select(2, ...))
if C["Inventory"].Enable ~= true then
return
end
if IsAddOnLoaded("AdiBags")
or IsAddOnLoaded("ArkInventory")
or IsAddOnLoaded("cargBags_Nivaya")
or IsAddOnLoaded("cargBags")
or IsAddOnLoaded("Bagnon")
or IsAddOnLoaded("Combuctor")
or IsAddOnLoaded("TBag")
or IsAddOnLoaded("BaudBag") then
return
end
local _G = _G
local math_abs = _G.math.abs
local math_ceil = _G.math.ceil
local math_min = _G.math.min
local string_find = _G.string.find
local string_format = _G.string.format
local string_gsub = _G.string.gsub
local table_insert = _G.table.insert
local table_remove = _G.table.remove
local table_sort = _G.table.sort
local BankButtonIDToInvSlotID = _G.BankButtonIDToInvSlotID
local ClearCursor = _G.ClearCursor
local CreateFrame = _G.CreateFrame
local GetBagName = _G.GetBagName
local GetBagSlotFlag = _G.GetBagSlotFlag
local GetBankBagSlotFlag = _G.GetBankBagSlotFlag
local GetContainerItemInfo = _G.GetContainerItemInfo
local GetContainerItemLink = _G.GetContainerItemLink
local GetContainerNumSlots = _G.GetContainerNumSlots
local GetItemInfo = _G.GetItemInfo
local GetTime = _G.GetTime
local InCombatLockdown = _G.InCombatLockdown
local PickupContainerItem = _G.PickupContainerItem
local Start, LT, Move, TooltipInfo, Sort, Stack, Initialize, ContainerClass, Item
local CONTAINERS
function _G.SortBags()
CONTAINERS = {0, 1, 2, 3, 4}
for i = #CONTAINERS, 1, -1 do
if GetBagSlotFlag(i - 1, LE_BAG_FILTER_FLAG_IGNORE_CLEANUP) then
table_remove(CONTAINERS, i)
end
end
Start()
end
function _G.SortBankBags()
CONTAINERS = {-1, 5, 6, 7, 8, 9, 10}
for i = #CONTAINERS, 1, -1 do
if GetBankBagSlotFlag(i - 1, LE_BAG_FILTER_FLAG_IGNORE_CLEANUP) then
table_remove(CONTAINERS, i)
end
end
Start()
end
function _G.GetSortBagsRightToLeft(enabled)
return SortBagsRightToLeft
end
function _G.SetSortBagsRightToLeft(enabled)
SortBagsRightToLeft = enabled and 1 or nil
end
local function set(...)
local t = {}
local n = select("#", ...)
for i = 1, n do
t[select(i, ...)] = true
end
return t
end
local function union(...)
local t = {}
local n = select("#", ...)
for i = 1, n do
for k in pairs(select(i, ...)) do
t[k] = true
end
end
return t
end
local MOUNTS = set(
-- rams
5864, 5872, 5873, 18785, 18786, 18787, 18244, 19030, 13328, 13329,
-- horses
2411, 2414, 5655, 5656, 18778, 18776, 18777, 18241, 12353, 12354,
-- sabers
8629, 8631, 8632, 18766, 18767, 18902, 18242, 13086, 19902, 12302, 12303, 8628, 12326,
-- mechanostriders
8563, 8595, 13321, 13322, 18772, 18773, 18774, 18243, 13326, 13327,
-- kodos
15277, 15290, 18793, 18794, 18795, 18247, 15292, 15293,
-- wolves
1132, 5665, 5668, 18796, 18797, 18798, 18245, 12330, 12351,
-- raptors
8588, 8591, 8592, 18788, 18789, 18790, 18246, 19872, 8586, 13317,
-- undead horses
13331, 13332, 13333, 13334, 18791, 18248, 13335,
-- qiraji battle tanks
21218, 21321, 21323, 21324, 21176
)
local SPECIAL = set(5462, 17696, 17117, 13347, 13289, 11511)
local KEYS = set(9240, 17191, 13544, 12324, 16309, 12384, 20402)
local TOOLS = set(7005, 12709, 19727, 5956, 2901, 6219, 10498, 6218, 6339, 11130, 11145, 16207, 9149, 15846, 6256, 6365, 6367)
local ENCHANTING_MATERIALS = set(
-- dust
10940, 11083, 11137, 11176, 16204,
-- essence
10938, 10939, 10998, 11082, 11134, 11135, 11174, 11175, 16202, 16203,
-- shard
10978, 11084, 11138, 11139, 11177, 11178, 14343, 14344,
-- crystal
20725
)
local HERBS = set(765, 785, 2447, 2449, 2450, 2452, 2453, 3355, 3356, 3357, 3358, 3369, 3818, 3819, 3820, 3821, 4625, 8153, 8831, 8836, 8838, 8839, 8845, 8846, 13463, 13464, 13465, 13466, 13467, 13468)
local SEEDS = set(17034, 17035, 17036, 17037, 17038)
local CLASSES = {
-- arrow
{
containers = {2101, 5439, 7278, 11362, 3573, 3605, 7371, 8217, 2662, 19319, 18714},
items = set(2512, 2515, 3030, 3464, 9399, 11285, 12654, 18042, 19316),
},
-- bullet
{
containers = {2102, 5441, 7279, 11363, 3574, 3604, 7372, 8218, 2663, 19320},
items = set(2516, 2519, 3033, 3465, 4960, 5568, 8067, 8068, 8069, 10512, 10513, 11284, 11630, 13377, 15997, 19317),
},
-- soul
{
containers = {22243, 22244, 21340, 21341, 21342},
items = set(6265),
},
-- ench
{
containers = {22246, 22248, 22249},
items = union(
ENCHANTING_MATERIALS,
-- rods
set(6218, 6339, 11130, 11145, 16207)
),
},
-- herb
{
containers = {22250, 22251, 22252},
items = union(HERBS, SEEDS)
},
}
local model, itemStacks, itemClasses, itemSortKeys
do
local f = CreateFrame("Frame")
f:Hide()
local timeout
function Start()
if f:IsShown() then return end
Initialize()
timeout = GetTime() + 7
f:Show()
end
local delay = 0
f:SetScript("OnUpdate", function(_, arg1)
if InCombatLockdown() or GetTime() > timeout then
f:Hide()
return
end
delay = delay - arg1
if delay <= 0 then
delay = .2
local complete = Sort()
if complete then
f:Hide()
return
end
Stack()
end
end)
end
function LT(a, b)
local i = 1
while true do
if a[i] and b[i] and a[i] ~= b[i] then
return a[i] < b[i]
elseif not a[i] and b[i] then
return true
elseif not b[i] then
return false
end
i = i + 1
end
end
function Move(src, dst)
local texture, _, srcLocked = GetContainerItemInfo(src.container, src.position)
local _, _, dstLocked = GetContainerItemInfo(dst.container, dst.position)
if texture and not srcLocked and not dstLocked then
ClearCursor()
PickupContainerItem(src.container, src.position)
PickupContainerItem(dst.container, dst.position)
if src.item == dst.item then
local count = math_min(src.count, itemStacks[dst.item] - dst.count)
src.count = src.count - count
dst.count = dst.count + count
if src.count == 0 then
src.item = nil
end
else
src.item, dst.item = dst.item, src.item
src.count, dst.count = dst.count, src.count
end
return true
end
end
function TooltipInfo(container, position)
-- local chargesPattern = "^" .. gsub(gsub(ITEM_SPELL_CHARGES_P1, "%%d", "(%%d+)"), "%%%d+%$d", "(%%d+)") .. "$" TODO retail
local chargesPattern = "^" .. string_gsub(string_gsub(ITEM_SPELL_CHARGES, "%%d", "(%%d+)"), "%%%d+%$d", "(%%d+)") .. "$"
K.ScanTooltip:SetOwner(UIParent, "ANCHOR_NONE")
K.ScanTooltip:ClearLines()
if container == BANK_CONTAINER then
K.ScanTooltip:SetInventoryItem("player", BankButtonIDToInvSlotID(position))
else
K.ScanTooltip:SetBagItem(container, position)
end
local charges, usable, soulbound, quest, conjured
for i = 1, K.ScanTooltip:NumLines() do
local text = _G[K.ScanTooltip:GetName().."TextLeft"..i]:GetText()
local _, _, chargeString = string_find(text, chargesPattern)
if chargeString then
charges = tonumber(chargeString)
elseif string_find(text, "^" .. ITEM_SPELL_TRIGGER_ONUSE) then
usable = true
elseif text == ITEM_SOULBOUND then
soulbound = true
elseif text == ITEM_BIND_QUEST then -- TODO retail can maybe use GetItemInfo bind info instead
quest = true
elseif text == ITEM_CONJURED then
conjured = true
end
end
return charges or 1, usable, soulbound, quest, conjured
end
function Sort()
local complete = true
for _, dst in ipairs(model) do
if dst.targetItem and (dst.item ~= dst.targetItem or dst.count < dst.targetCount) then
complete = false
local sources, rank = {}, {}
for _, src in ipairs(model) do
if src.item == dst.targetItem
and src ~= dst
and not (dst.item and src.class and src.class ~= itemClasses[dst.item])
and not (src.targetItem and src.item == src.targetItem and src.count <= src.targetCount)
then
rank[src] = math_abs(src.count - dst.targetCount + (dst.item == dst.targetItem and dst.count or 0))
table_insert(sources, src)
end
end
table_sort(sources, function(a, b) return rank[a] < rank[b] end)
for _, src in ipairs(sources) do
if Move(src, dst) then
break
end
end
end
end
return complete
end
function Stack()
for _, src in ipairs(model) do
if src.item and src.count < itemStacks[src.item] and src.item ~= src.targetItem then
for _, dst in ipairs(model) do
if dst ~= src and dst.item and dst.item == src.item and dst.count < itemStacks[dst.item] and dst.item ~= dst.targetItem then
Move(src, dst)
end
end
end
end
end
do
local counts
local function insert(t, v)
if SortBagsRightToLeft then
table_insert(t, v)
else
table_insert(t, 1, v)
end
end
local function assign(slot, item)
if counts[item] > 0 then
local count
if SortBagsRightToLeft and mod(counts[item], itemStacks[item]) ~= 0 then
count = mod(counts[item], itemStacks[item])
else
count = math_min(counts[item], itemStacks[item])
end
slot.targetItem = item
slot.targetCount = count
counts[item] = counts[item] - count
return true
end
end
function Initialize()
model, counts, itemStacks, itemClasses, itemSortKeys = {}, {}, {}, {}, {}
for _, container in ipairs(CONTAINERS) do
local class = ContainerClass(container)
for position = 1, GetContainerNumSlots(container) do
local slot = {container=container, position=position, class=class}
local item = Item(container, position)
if item then
local _, count = GetContainerItemInfo(container, position)
slot.item = item
slot.count = count
counts[item] = (counts[item] or 0) + count
end
insert(model, slot)
end
end
local free = {}
for item, count in pairs(counts) do
local stacks = math_ceil(count / itemStacks[item])
free[item] = stacks
if itemClasses[item] then
free[itemClasses[item]] = (free[itemClasses[item]] or 0) + stacks
end
end
for _, slot in ipairs(model) do
if slot.class and free[slot.class] then
free[slot.class] = free[slot.class] - 1
end
end
local items = {}
for item in pairs(counts) do
table_insert(items, item)
end
table_sort(items, function(a, b)
return LT(itemSortKeys[a], itemSortKeys[b])
end)
for _, slot in ipairs(model) do
if slot.class then
for _, item in ipairs(items) do
if itemClasses[item] == slot.class and assign(slot, item) then
break
end
end
else
for _, item in ipairs(items) do
if (not itemClasses[item] or free[itemClasses[item]] > 0) and assign(slot, item) then
if itemClasses[item] then
free[itemClasses[item]] = free[itemClasses[item]] - 1
end
break
end
end
end
end
end
end
function ContainerClass(container)
if container ~= 0 and container ~= BANK_CONTAINER then
local name = GetBagName(container)
if name then
for class, info in pairs(CLASSES) do
for _, itemID in pairs(info.containers) do
if name == GetItemInfo(itemID) then
return class
end
end
end
end
end
end
function Item(container, position)
local link = GetContainerItemLink(container, position)
if link then
local _, _, itemID, enchantID, suffixID, uniqueID = string_find(link, "item:(%d+):(%d*):(%d*):(%d*)")
itemID = tonumber(itemID)
local _, _, quality, _, _, _, _, stack, slot, _, _, classId, subClassId = GetItemInfo("item:" .. itemID)
local charges, usable, soulbound, quest, conjured = TooltipInfo(container, position)
local sortKey = {}
-- hearthstone
if itemID == 6948 then
table_insert(sortKey, 1)
-- mounts
elseif MOUNTS[itemID] then
table_insert(sortKey, 2)
-- special items
elseif SPECIAL[itemID] then
table_insert(sortKey, 3)
-- key items
elseif KEYS[itemID] then
table_insert(sortKey, 4)
-- tools
elseif TOOLS[itemID] then
table_insert(sortKey, 5)
-- soul shards
elseif itemID == 6265 then
table_insert(sortKey, 14)
-- conjured items
elseif conjured then
table_insert(sortKey, 15)
-- soulbound items
elseif soulbound then
table_insert(sortKey, 6)
-- reagents
elseif classId == 9 then
table_insert(sortKey, 7)
-- quest items
elseif quest then
table_insert(sortKey, 9)
-- consumables
elseif usable and classId ~= 1 and classId ~= 2 and classId ~= 8 or classId == 4 then
table_insert(sortKey, 8)
-- enchanting materials
elseif ENCHANTING_MATERIALS[itemID] then
table_insert(sortKey, 11)
-- herbs
elseif HERBS[itemID] then
table_insert(sortKey, 12)
-- higher quality
elseif quality > 1 then
table_insert(sortKey, 10)
-- common quality
elseif quality == 1 then
table_insert(sortKey, 13)
-- junk
elseif quality == 0 then
table_insert(sortKey, 14)
end
table_insert(sortKey, classId)
table_insert(sortKey, slot)
table_insert(sortKey, subClassId)
table_insert(sortKey, -quality)
table_insert(sortKey, itemID)
table_insert(sortKey, (SortBagsRightToLeft and 1 or -1) * charges)
table_insert(sortKey, suffixID)
table_insert(sortKey, enchantID)
table_insert(sortKey, uniqueID)
local key = string_format("%s:%s:%s:%s:%s:%s", itemID, enchantID, suffixID, uniqueID, charges, (soulbound and 1 or 0))
itemStacks[key] = stack
itemSortKeys[key] = sortKey
for class, info in pairs(CLASSES) do
if info.items[itemID] then
itemClasses[key] = class
break
end
end
return key
end
end
|
#!/usr/bin/env tarantool
local fio = require('fio')
-- require in-repo version of graphql/ sources despite current working directory
package.path = fio.abspath(debug.getinfo(1).source:match("@?(.*/)")
:gsub('/./', '/'):gsub('/+$', '')) .. '/../../?.lua' .. ';' .. package.path
local tap = require('tap')
local test_utils = require('test.test_utils')
local testdata = require('test.testdata.user_order_item_testdata')
local graphql = require('graphql')
local graphql_utils = require('graphql.utils')
local test_run = graphql_utils.optional_require('test_run')
test_run = test_run and test_run.new()
local e = graphql.error_codes
local apply_timeout_to = test_run and test_run:get_cfg('apply_timeout_to') or
'graphql'
local test_graphql_opts = {
timeout_ms = 0.001,
}
local function run_queries(gql_wrapper)
local test = tap.test('result cnt')
test:plan(1)
local query = [[
query object_result_max {
user_collection {
id
last_name
first_name
order_connection {
id
user_id
description
}
}
}
]]
local query_opts = apply_timeout_to == 'query' and test_graphql_opts or nil
local gql_query = gql_wrapper:compile(query, query_opts)
local variables = {}
local result = gql_query:execute(variables)
assert(result.data == nil, "this test should fail")
assert(result.errors ~= nil, "this test should fail")
local exp_err = 'query execution timeout exceeded timeout_ms limit (0.001 ms)'
local err = result.errors[1].message
local code = result.errors[1].extensions.error_code
test:is_deeply({err, code}, {exp_err, e.TIMEOUT_EXCEEDED}, 'timeout test')
assert(test:check(), 'check plan')
end
box.cfg({})
local graphql_opts = apply_timeout_to == 'graphql' and test_graphql_opts or nil
test_utils.run_testdata(testdata, {
run_queries = run_queries,
graphql_opts = graphql_opts,
})
os.exit()
|
-- Copyright 2015 Boundary, Inc.
--
-- 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.
-- Add require statements for built-in libaries we wish to use
local math = require('math')
local os = require('os')
local string = require('string')
local timer = require('timer')
local io = require('io')
local fs = require('fs')
local net = require('net')
local json = require('json')
local table = require('table')
local params = json.parse(fs.readFileSync('param.json')) or {}
local options = params.items or {}
--[[
@Vitiwari
This function creates the JSON RPC command to meter according to the params
]]--
function getProcessData(opt)
local parameter = {}
parameter.process = opt.processName or ''
parameter.path_expr = opt.processPath or ''
parameter.cwd_expr = opt.processCwd or ''
parameter.args_expr = opt.processArgs or ''
parameter.reconcile = opt.reconcile or ''
local prm = parameter or { match = ''}
return '{"jsonrpc":"2.0","method":"get_process_info","id":1,"params":' .. json.stringify(prm) .. '}\n'
end
--Utility functions
function parseJson(body)
return pcall(json.parse, body)
end
function trim(val)
return string.match(val, '^%s*(.-)%s*$')
end
function isEmpty(str)
return (str == nil or trim(str) == '')
end
function notEmpty(str, default)
return not isEmpty(str) and str or default
end
local POLL_INTERVAL = 5000; -- currently poll as 2sec TODO Dynamic
-- this function is called for every param
local jsonRpcCall=function (process)
local callback = function()
--print("callback called")
end
local socket = net.createConnection(9192, '127.0.0.1', callback)
socket:write(getProcessData(process))
socket:once('data',function(data)
local sucess, parsed = parseJson(data)
if(parsed.result.processes==nil)then
--print No process Stay Silent TODO logs
else
for K,V in pairs(parsed.result.processes) do
local per = V["cpuPct"]/100
local name = process.source.."_"..V["name"]
local timestamp=os.time()
print(string.format("%s %s %s %s", 'TRUESIGHT_METER_PROCESSCPU', per,name, timestamp))
end
end
socket:destroy()
end)
socket:once('error',function(data)
print("Socket Resulted in error "..json.stringify(data))
end)
end
local poll=function ()
for key,process in pairs(options) do
jsonRpcCall(process)
end
end
-- Set the timer interval and call back function poll().
timer.setInterval(POLL_INTERVAL, poll)
|
prime_list = {2}
for x = 3, 100, 2 do
a = true
for y = 1, #prime_list do
z = prime_list[y]
if x % z == 0 then
a = false
break
end
end
if a then
table.insert(prime_list, x)
end
end
for x = 1, #prime_list do
io.write(prime_list[x])
io.write(" ")
end
print()
|
require("lualine").setup({
options = {
theme = "onedark",
},
--[[ sections = {
lualine_c = { "os.date('%a')", "data", "require'lsp-status'.status()" },
}, ]]
})
|
local M = {};
local mod = require "mod";
local tex = require "tex";
local font = require "font";
local spr = require "spr";
local mus = require "mus";
local snd = require "snd";
local function LoadAll()
spr.font_00 = SpriteLoad(mod.dir .. "textures/mbf_big_00.png", 10, 12, 16,
16, 256, 0, 0);
spr.font_04 = SpriteLoad(mod.dir .. "textures/mbf_big_04.png", 10, 12, 16,
16, 256, 0, 0);
font.main = FontCreate("Main", 5);
FontAddAtlas(font.main, spr.font_00, 0);
FontAddAtlas(font.main, spr.font_04, 4);
tex.arena = TextureLoad(mod.dir .. "textures/arena.png");
tex.people1 = TextureLoad(mod.dir .. "textures/people1.png");
tex.people2 = TextureLoad(mod.dir .. "textures/people2.png");
tex.people3 = TextureLoad(mod.dir .. "textures/people3.png");
tex.people4 = TextureLoad(mod.dir .. "textures/people4.png");
tex.bg = TextureLoad(mod.dir .. "textures/background.png");
spr.blue_cube = {};
spr.red_cube = {};
spr.green_cube = {};
spr.bottle = {};
spr.object = {};
spr.object[0] = {};
spr.object[0][0] = SpriteLoadSimple(mod.dir .. "textures/blue_cube.png", 0, 16);
spr.object[0][1] = SpriteLoadSimple(mod.dir .. "textures/blue_cube.png", 16, 16);
spr.object[1] = {};
spr.object[1][0] = SpriteLoadSimple(mod.dir .. "textures/red_cube.png", 0, 16);
spr.object[1][1] = SpriteLoadSimple(mod.dir .. "textures/red_cube.png", 16, 16);
spr.object[2] = {};
spr.object[2][0] = SpriteLoadSimple(mod.dir .. "textures/green_cube.png", 0, 16);
spr.object[2][1] = SpriteLoadSimple(mod.dir .. "textures/green_cube.png", 16, 16);
spr.object[3] = {};
spr.object[3][0] = SpriteLoadSimple(mod.dir .. "textures/bottle.png", 0, 16);
spr.object[3][1] = SpriteLoadSimple(mod.dir .. "textures/bottle.png", 16, 16);
spr.object[4] = {};
spr.object[4][0] = SpriteLoadSimple(mod.dir .. "textures/jar.png", 0, 16);
spr.object[4][1] = SpriteLoadSimple(mod.dir .. "textures/jar.png", 16, 16);
spr.object[5] = {};
spr.object[5][0] = SpriteLoadSimple(mod.dir .. "textures/goblet.png", 0, 16);
spr.object[5][1] = SpriteLoadSimple(mod.dir .. "textures/goblet.png", 16, 16);
spr.object[6] = {};
spr.object[6][0] = SpriteLoadSimple(mod.dir .. "textures/container.png", 0, 16);
spr.object[6][1] = SpriteLoadSimple(mod.dir .. "textures/container.png", 16, 16);
spr.object[7] = {};
spr.object[7][0] = SpriteLoadSimple(mod.dir .. "textures/box.png", 0, 16);
spr.object[7][1] = SpriteLoadSimple(mod.dir .. "textures/box.png", 16, 16);
spr.object[8] = {};
spr.object[8][0] = SpriteLoadSimple(mod.dir .. "textures/box2.png", 0, 16);
spr.object[8][1] = SpriteLoadSimple(mod.dir .. "textures/box2.png", 16, 16);
spr.hero = SpriteLoad(mod.dir .. "textures/hero.png", 64, 64, 1, 2, 2, 32,
64);
mus.main = AudioMusicLoad(mod.dir .. "music/bu-the-absurd-puppy.ogg");
snd.set = AudioSoundLoad(mod.dir .. "sounds/set.wav");
snd.fall = AudioSoundLoad(mod.dir .. "sounds/fall.wav");
end;
M.LoadAll = LoadAll;
return M;
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
|
local included = pcall(debug.getlocal, 5, 1)
local bimap = require("bimap")
local T = require("u-test")
local expect = T.expect
local func = T.is_function
local tbl = T.is_table
--# = bimap
--# :toc:
--# :toc-placement!:
--#
--# Bidirectional map implementation.
--#
--# toc::[]
--#
--# == *bimap.new*() -> _Table_, _Table_
--# Create a new map.
--#
--# === Returns
--# [options="header",width="72%"]
--# |===
--# |Type |Description
--# |table |Array side
--# |table |Map side
--# |===
local new = function()
func(bimap.new)
local l, r = bimap.new()
tbl(l)
tbl(r)
end
local raw = function()
local l, r = bimap.new()
l.test = true
l.nope = false
local left = l("raw")
local right = r("raw")
expect(true)(left["test"])
expect(false)(left["nope"])
expect("test")(right[true])
expect("nope")(right[false])
end
local len = function()
local t = { 1 }
expect(1)(#t)
local l, r = bimap.new()
l.test = 1
l.nope = 2
expect(0)(l("len"))
expect(2)(r("len"))
end
local testing = function(l, r)
expect(2)(l.bar)
expect("bar")(r[2])
local r1 = r("raw")
expect("foo")(r1[1])
expect("bar")(r1[2])
expect("baz")(r1[3])
local t1 = l("raw")
expect(1)(t1.foo)
expect(2)(t1.bar)
expect(3)(t1.baz)
expect(3)(r("len"))
l.baz = nil
expect(2)(#(r("raw")))
r[r("len")] = nil
local r2 = r("raw")
expect("foo")(r2[1])
local l1 = l("raw")
expect(1)(l1.foo)
expect(1)(r("len"))
l.spam = "eggs"
r.eggs = "chunky"
l["chunky"] = "bacon"
expect("bacon")(l["chunky"])
expect("chunky")(r["bacon"])
expect(nil)(l["spam"])
expect(nil)(r["eggs"])
local r3 = r("raw")
local l2 = l("raw")
expect("foo")(r3[1])
expect("chunky")(r3.bacon)
expect(1)(l2.foo)
expect("bacon")(l2.chunky)
local fn = function()
l.evil = 1
end
T.error_raised(
fn,
'cannot assign value "1" to key "evil": ' .. 'already assigned to key "foo"'
)
end
local left = function()
local l, r = bimap.new()
l.foo = 1
l.bar = 2
l.baz = 3
testing(l, r)
end
local right = function()
local l, r = bimap.new{"foo", "bar", "baz"}
testing(r, l)
end
local iter = function()
local l, r = bimap.new{"foo", "bar", "baz"}
local t = {}
local x = l("raw")
for n = 1, l("len") do
t[n] = x[n]
end
expect("foo")(t[1])
expect("bar")(t[2])
expect("baz")(t[3])
end
if included then
return function()
T["new"] = new
T["raw argument"] = raw
T["len argument"] = len
T["left"] = left
T["right"] = right
T["iteration"] = iter
end
else
T["new"] = new
T["raw argument"] = raw
T["len argument"] = len
T["left"] = left
T["right"] = right
T["iteration"] = iter
end
|
---
-- An image element.
-- @classmod Image
-- @alias Image
local class = require("middleclass")
local AnAL = require("AnAL")
local Base = require("silicone.elements.Base")
local Image = class("silicone.Image", Base)
---
-- Internal.
-- Internal methods
-- @section Internal
---
-- Initializes an Image element
-- @tparam table spec Menu specification
-- @tparam Root root Root element
function MenuImage:initialize(spec, root)
self.type = "Image"
self.angle = 0
self.xScale = 1
self.yScale = 1
self.xShear = 0
self.yShear = 0
self.autoScale = true
self.image = false
Base.initialize(self, spec, root)
if not spec.height and not spec.heightOffset then
self.heightOffset = self.image:getHeight()
end
if not spec.width and not spec.widthOffset then
self.widthOffset = self.image:getWidth()
end
end
---
-- Getters/Setters.
-- Getters and setters for element properties
-- @section Getters/Setters
---
-- Returns the @{love:Image} associated with the element
-- @treturn @{love:Image} Image
function MenuImage:getImage()
return self.image
end
---
-- Sets the @{love:Image} associated with the element
-- @tparam @{love:Image} image Image
function MenuImage:setImage(image)
self.image = image
end
---
-- Returns an image's angle
-- @treturn number angle
function MenuImage:getAngle()
return self.angle
end
---
-- Sets an image's angle
-- @tparam number angle angle
function MenuImage:setAngle(angle)
self.angle = angle
end
---
-- Returns an image's X scale
-- @treturn number X scale
function MenuImage:getXScale()
return self.xScale
end
---
-- Sets an image's X scale
-- @tparam number x X scale
function MenuImage:setXScale(x)
self.autoScale = false
self.xScale = x
end
---
-- Returns an image's Y scale
-- @treturn number Y scale
function MenuImage:getYScale()
return self.yScale
end
---
-- Sets an image's Y scale
-- @tparam number y Y scale
function MenuImage:setYScale(y)
self.autoScale = false
self.yScale = y
end
---
-- Returns an image's scale
-- @treturn number X scale
-- @treturn number Y scale
function MenuImage:getScale()
return self:getXScale(), self:getYScale()
end
---
-- Sets an image's scale
-- @tparam number x X scale
-- @tparam number y Y scale
function MenuImage:setScale(x, y)
self:setXScale(x)
self:setYScale(y)
end
---
-- Returns whether or not the image is set to auto scale
-- @treturn bool autoscale
function MenuImage:getAutoScale()
return self.autoScale
end
---
-- Sets whether or not the image should auto scale
-- @tparam bool scale autoscale
function MenuImage:setAutoScale(scale)
self.autoScale = scale
end
---
-- Returns the shearing factor for the image's X-axis
-- @treturn number Shear factor
function MenuImage:getXShear()
return self.xShear
end
---
-- Sets the shearing factor for the image's X-axis
-- @tparam number x Shear factor
function MenuImage:setXShear(x)
self.xShear = x
end
---
-- Returns the shearing factor for the image's Y-axis
-- @treturn number Shear factor
function MenuImage:getYShear()
return self.yShear
end
---
-- Sets the shearing factor for the image's X-axis
-- @tparam number y Shear factor
function MenuImage:setYShear(y)
self.yShear = y
end
---
-- Returns the shearing factor for the image's X and Y axes
-- @treturn number X Shear factor
-- @treturn number Y Shear factor
function MenuImage:getShear()
return self:getXShear(), self:getYShear()
end
---
-- Sets the shearing factor for the image's X and Y axes
-- @tparam number x X Shear factor
-- @tparam number y Y Shear factor
function MenuImage:setShear(x, y)
self:setXShear(x)
self:setYShear(y)
end
---
-- Returns the image element's absolute X position.
--
return Image
|
log = require "log"
file = io.open("test.lua", "r")
x = 300
log.trace("linghibin"..x)
log.debug("12")
log.info(...)
log.warn(...)
log.error(...)
log.fatal(...)
a={"Hello","World";a=1,b=2,z=3,x=10,y=20;"Good","Bye"}
for i, v in ipairs(a) do
log.error(v..i.."---linghaibin")
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.