repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
Scavenge/darkstar
scripts/zones/Aht_Urhgan_Whitegate/Shared.lua
12
5555
----------------------------------- -- Tables and Functions Used at Multiple Places within Aht Urgan Whitegate ----------------------------------- require("scripts/globals/settings"); -- Lua Set Initializer http://www.lua.org/pil/11.5.html function Set (list) local set = {} for _, l in ipairs(list) do set[l] = true end return set end -- Set of Royal Palace Approved Armor ROYAL_PALACE_ALLOWED_BODY_ARMORS = Set{ 12548, -- Adaman Cuirass Lv. 73 WAR / PLD 13746, -- Gem Cuirass Lv. 73 WAR / PLD 13742, -- Aketon Lv. 60 MNK / WHM / RDM / THF / PLD / BST / BRD / DRG / SMN / BLU / COR / PUP / DNC 13743, -- Aketon +1 Lv. 60 MNK / WHM / RDM / THF / PLD / BST / BRD / DRG / SMN / BLU / COR / PUP / DNC 14525, -- Amir Korazin Lv. 72 WAR / PLD / DRK / SAM /DRG 13795, -- Arhat's Gi Lv. 64 MNK / SAM / NIN 13802, -- Arhat's Gi +1 Lv. 64 MNK / SAM / NIN 14416, -- Barone Corazza Lv. 70 WAR / DRG 14417, -- Conte Corazza Lv. 70 WAR / DRG 13779, -- Black Cloak Lv. 68 BLM 13780, -- Demon's Cloak Lv. 68 BLM 13754, -- Black Cotehardie Lv. 59 MNK / WHM / BLM / RDM / THF / BST / BRD / RNG / NIN / SMN / BLU / PUP / DNC / SCH 13755, -- Flora Cotehardie Lv. 59 MNK / WHM / BLM / RDM / THF / BST / BRD / RNG / NIN / SMN / BLU / PUP / DNC / SCH 14436, -- Blessed Briault Lv. 70 WHM 14438, -- Blessed Briault +1 Lv. 70 WHM 13775, -- Blue Cotehardie Lv. 69 RDM / THF / RNG / NIN / COR / DNC 13776, -- Blue Cotehardie +1 Lv. 69 RDM / THF / RNG / NIN / COR / DNC 13740, -- Byrnie Lv. 60 WAR / PLD / DRK / BST / SAM / NIN 13741, -- Byrnie +1 Lv. 60 WAR / PLD / DRK / BST / SAM / NIN 13703, -- Brigandine Lv. 45 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 13710, -- Brigandine +1 Lv. 45 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14372, -- Cardinal Vest Lv. 73 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14373, -- Bachelor Vest Lv. 73 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14440, -- Chasuble Lv. 72 RDM 14441, -- Chasuble +1 Lv. 72 RDM 12573, -- Dusk Jerkin Lv. 72 WAR / RDM / THF / PLD / DRK / BST /BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14391, -- Dusk Jerkin +1 Lv. 72 WAR / RDM / THF / PLD / DRK / BST /BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14389, -- Dragon Harness Lv. 73 THF 14390, -- Dragon Harness +1 Lv. 73 THF 14380, -- Errant Houppelande Lv. 72 WHM / BLM / RDM / BRD / SMN / BLU / PUP / SCH 14381, -- Mahatma Houppelande Lv. 72 WHM / BLM / RDM / BRD / SMN / BLU / PUP / SCH 14437, -- Hachiman Domaru Lv. 70 SAM 14439, -- Hachiman Domaru +1 Lv. 70 SAM 12555, -- Haubergeon Lv. 59 WAR / PLD / DRK / BST / SAM /NIN 13735, -- Haubergeon Lv. 59 WAR / PLD / DRK / BST / SAM /NIN 12556, -- Hauberk Lv. 69 WAR / DRK / BST 13793, -- Hauberk +1 Lv. 69 WAR / DRK / BST 13812, -- Holy Breastplate Lv. 40 WHM 13813, -- Divine Breastplate Lv. 40 WHM 14488, -- Homam Corazza Lv. 75 THF / PLD / DRK / DRG / BLU 14420, -- Igqira Weskit Lv. 73 BLM 14421, -- Genie Weskit Lv. 73 BLM 14526, -- Jaridah Peti Lv. 55 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 14529, -- Akinji Peti Lv. 55 WAR / RDM / THF / PLD / DRK / BST / BRD / RNG / SAM / NIN / DRG / BLU / COR / DNC 13744, -- Justaucorps Lv. 58 MNK / WHM / BLM / RDM / THF / DRK / BRD / RNG / SMN / BLU / COR / PUP / DNC / SCH 13745, -- Justaucorps +1 Lv. 58 MNK / WHM / BLM / RDM / THF / DRK / BRD / RNG / SMN / BLU / COR / PUP / DNC / SCH 14489, -- Nashira Manteel Lv. 75 WHM / BLM / RDM / SMN / BLU 12605, -- Noble's Tunic Lv. 68 WHM 13774, -- Aristocrat's Coat Lv. 68 WHM 14530, -- Pahluwan Khazagand Lv. 72 MNK / RDM / THF / BST / RNG / NIN / DRG / COR / PUP / DNC 14382, -- Plastron Lv. 71 DRK 14383, -- Plastron +1 Lv. 71 DRK 14376, -- Rasetsu Samue Lv. 72 MNK / SAM / NIN 14377, -- Rasetsu Samue +1 Lv. 72 MNK / SAM / NIN 13748, -- Vermillion Cloak Lv. 59 MNK / WHM / BLM / RDM / PLD / BRD / RNG / SMN / BLU / PUP / SCH 13749, -- Royal Cloak Lv. 59 MNK / WHM / BLM / RDM / PLD / BRD / RNG / SMN / BLU / PUP / SCH 12579, -- Scorpion Harness Lv. 57 WAR / MNK / RDM / THF / PLD / DRK / BST / BRD / SAM / NIN / DRG / BLU / COR / DNC 13734, -- Scorpion Harness +1 Lv. 57 WAR / MNK / RDM / THF / PLD / DRK / BST / BRD / SAM / NIN / DRG / BLU / COR / DNC 14524, -- Sipahi Jawshan Lv. 59 WAR / PLD / DRK / BST / SAM 14528, -- Abtal Jawshan Lv. 59 WAR / PLD / DRK / BST / SAM 14414, -- Sha'ir Manteel Lv. 72 BRD 14415 -- Sheikh Manteel Lv. 72 BRD } -- Function to check if the player is wearing armor that is appropriate for the royal palace. function doRoyalPalaceArmorCheck(player) local bodyArmor = player:getEquipID(SLOT_BODY); local check = (ROYAL_PALACE_ALLOWED_BODY_ARMORS[bodyArmor] ~= nil); local hasHandArmor = player:getEquipID(SLOT_HANDS); local hasLegArmor = player:getEquipID(SLOT_LEGS); local hasFeetArmor = player:getEquipID(SLOT_FEET); if (hasHandArmor == 0 or hasLegArmor == 0 or hasFeetArmor == 0) then check = false; -- printf("Royal Palace Armor Check for Player <%s> -> Missing Required Hand/Leg/Feet Armor", player:getName()); end -- printf("Royal Palace Armor Check for Player <%s> with Body Armor <%u>, allowed = %s", player:getName(), bodyArmor, check); return check; end
gpl-3.0
Scavenge/darkstar
scripts/globals/items/plate_of_patlican_salata.lua
12
1352
----------------------------------------- -- ID: 5582 -- Item: plate_of_patlican_salata -- Food Effect: 180Min, All Races ----------------------------------------- -- Agility 4 -- Vitality -1 -- Evasion +6 -- hHP +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5582); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 4); target:addMod(MOD_VIT, -1); target:addMod(MOD_EVA, 6); target:addMod(MOD_HPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 4); target:delMod(MOD_VIT, -1); target:delMod(MOD_EVA, 6); target:delMod(MOD_HPHEAL, 2); end;
gpl-3.0
PredatorMF/Urho3D
Source/ThirdParty/LuaJIT/dynasm/dasm_x86.lua
24
71256
------------------------------------------------------------------------------ -- DynASM x86/x64 module. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ local x64 = x64 -- Module information: local _info = { arch = x64 and "x64" or "x86", description = "DynASM x86/x64 module", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub local concat, sort, remove = table.concat, table.sort, table.remove local bit = bit or require("bit") local band, bxor, shl, shr = bit.band, bit.bxor, bit.lshift, bit.rshift -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { -- int arg, 1 buffer pos: "DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB", -- action arg (1 byte), int arg, 1 buffer pos (reg/num): "VREG", "SPACE", -- ptrdiff_t arg, 1 buffer pos (address): !x64 "SETLABEL", "REL_A", -- action arg (1 byte) or int arg, 2 buffer pos (link, offset): "REL_LG", "REL_PC", -- action arg (1 byte) or int arg, 1 buffer pos (link): "IMM_LG", "IMM_PC", -- action arg (1 byte) or int arg, 1 buffer pos (offset): "LABEL_LG", "LABEL_PC", -- action arg (1 byte), 1 buffer pos (offset): "ALIGN", -- action args (2 bytes), no buffer pos. "EXTERN", -- action arg (1 byte), no buffer pos. "ESC", -- no action arg, no buffer pos. "MARK", -- action arg (1 byte), no buffer pos, terminal action: "SECTION", -- no args, no buffer pos, terminal action: "STOP" } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number (dynamically generated below). local map_action = {} -- First action number. Everything below does not need to be escaped. local actfirst = 256-#action_names -- Action list buffer and string (only used to remove dupes). local actlist = {} local actstr = "" -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 -- VREG kind encodings, pre-shifted by 5 bits. local map_vreg = { ["modrm.rm.m"] = 0x00, ["modrm.rm.r"] = 0x20, ["opcode"] = 0x20, ["sib.base"] = 0x20, ["sib.index"] = 0x40, ["modrm.reg"] = 0x80, ["vex.v"] = 0xa0, ["imm.hi"] = 0xc0, } -- Current number of VREG actions contributing to REX/VEX shrinkage. local vreg_shrink_count = 0 ------------------------------------------------------------------------------ -- Compute action numbers for action names. for n,name in ipairs(action_names) do local num = actfirst + n - 1 map_action[name] = num end -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist local last = actlist[nn] or 255 actlist[nn] = nil -- Remove last byte. if nn == 0 then nn = 1 end out:write("static const unsigned char ", name, "[", nn, "] = {\n") local s = " " for n,b in ipairs(actlist) do s = s..b.."," if #s >= 75 then assert(out:write(s, "\n")) s = " " end end out:write(s, last, "\n};\n\n") -- Add last byte back. end ------------------------------------------------------------------------------ -- Add byte to action list. local function wputxb(n) assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, a, num) wputxb(assert(map_action[action], "bad action name `"..action.."'")) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Optionally add a VREG action. local function wvreg(kind, vreg, psz, sk, defer) if not vreg then return end waction("VREG", vreg) local b = assert(map_vreg[kind], "bad vreg kind `"..vreg.."'") if b < (sk or 0) then vreg_shrink_count = vreg_shrink_count + 1 end if not defer then b = b + vreg_shrink_count * 8 vreg_shrink_count = 0 end wputxb(b + (psz or 0)) end -- Add call to embedded DynASM C code. local function wcall(func, args) wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true) end -- Delete duplicate action list chunks. A tad slow, but so what. local function dedupechunk(offset) local al, as = actlist, actstr local chunk = char(unpack(al, offset+1, #al)) local orig = find(as, chunk, 1, true) if orig then actargs[1] = orig-1 -- Replace with original offset. for i=offset+1,#al do al[i] = nil end -- Kill dupe. else actstr = as..chunk end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) local offset = actargs[1] if #actlist == offset then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. dedupechunk(offset) wcall("put", actargs) -- Add call to dasm_put(). actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped byte. local function wputb(n) if n >= actfirst then waction("ESC") end -- Need to escape byte. wputxb(n) end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 10 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end local n = next_global if n > 246 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=10,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=10,next_global-1 do out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=10,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = -1 local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n < -256 then werror("too many extern labels") end next_extern = n - 1 t[name] = n return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("Extern labels:\n") for i=1,-next_extern-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("static const char *const ", name, "[] = {\n") for i=1,-next_extern-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = {} -- Ext. register name -> int. name. local map_reg_rev = {} -- Int. register name -> ext. name. local map_reg_num = {} -- Int. register name -> register number. local map_reg_opsize = {} -- Int. register name -> operand size. local map_reg_valid_base = {} -- Int. register name -> valid base register? local map_reg_valid_index = {} -- Int. register name -> valid index register? local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex. local reg_list = {} -- Canonical list of int. register names. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for _PTx macros). local addrsize = x64 and "q" or "d" -- Size for address operands. -- Helper functions to fill register maps. local function mkrmap(sz, cl, names) local cname = format("@%s", sz) reg_list[#reg_list+1] = cname map_archdef[cl] = cname map_reg_rev[cname] = cl map_reg_num[cname] = -1 map_reg_opsize[cname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[cname] = true map_reg_valid_index[cname] = true end if names then for n,name in ipairs(names) do local iname = format("@%s%x", sz, n-1) reg_list[#reg_list+1] = iname map_archdef[name] = iname map_reg_rev[iname] = name map_reg_num[iname] = n-1 map_reg_opsize[iname] = sz if sz == "b" and n > 4 then map_reg_needrex[iname] = false end if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end for i=0,(x64 and sz ~= "f") and 15 or 7 do local needrex = sz == "b" and i > 3 local iname = format("@%s%x%s", sz, i, needrex and "R" or "") if needrex then map_reg_needrex[iname] = true end local name if sz == "o" or sz == "y" then name = format("%s%d", cl, i) elseif sz == "f" then name = format("st%d", i) else name = format("r%d%s", i, sz == addrsize and "" or sz) end map_archdef[name] = iname if not map_reg_rev[iname] then reg_list[#reg_list+1] = iname map_reg_rev[iname] = name map_reg_num[iname] = i map_reg_opsize[iname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end reg_list[#reg_list+1] = "" end -- Integer registers (qword, dword, word and byte sized). if x64 then mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"}) end mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"}) mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"}) mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"}) map_reg_valid_index[map_archdef.esp] = false if x64 then map_reg_valid_index[map_archdef.rsp] = false end if x64 then map_reg_needrex[map_archdef.Rb] = true end map_archdef["Ra"] = "@"..addrsize -- FP registers (internally tword sized, but use "f" as operand size). mkrmap("f", "Rf") -- SSE registers (oword sized, but qword and dword accessible). mkrmap("o", "xmm") -- AVX registers (yword sized, but oword, qword and dword accessible). mkrmap("y", "ymm") -- Operand size prefixes to codes. local map_opsize = { byte = "b", word = "w", dword = "d", qword = "q", oword = "o", yword = "y", tword = "t", aword = addrsize, } -- Operand size code to number. local map_opsizenum = { b = 1, w = 2, d = 4, q = 8, o = 16, y = 32, t = 10, } -- Operand size code to name. local map_opsizename = { b = "byte", w = "word", d = "dword", q = "qword", o = "oword", y = "yword", t = "tword", f = "fpword", } -- Valid index register scale factors. local map_xsc = { ["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3, } -- Condition codes. local map_cc = { o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7, s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15, c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7, pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15, } -- Reverse defines for registers. function _M.revdef(s) return gsub(s, "@%w+", map_reg_rev) end -- Dump register names and numbers local function dumpregs(out) out:write("Register names, sizes and internal numbers:\n") for _,reg in ipairs(reg_list) do if reg == "" then out:write("\n") else local name = map_reg_rev[reg] local num = map_reg_num[reg] local opsize = map_opsizename[map_reg_opsize[reg]] out:write(format(" %-5s %-8s %s\n", name, opsize, num < 0 and "(variable)" or num)) end end end ------------------------------------------------------------------------------ -- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC). local function wputlabel(aprefix, imm, num) if type(imm) == "number" then if imm < 0 then waction("EXTERN") wputxb(aprefix == "IMM_" and 0 or 1) imm = -imm-1 else waction(aprefix.."LG", nil, num); end wputxb(imm) else waction(aprefix.."PC", imm, num) end end -- Put signed byte or arg. local function wputsbarg(n) if type(n) == "number" then if n < -128 or n > 127 then werror("signed immediate byte out of range") end if n < 0 then n = n + 256 end wputb(n) else waction("IMM_S", n) end end -- Put unsigned byte or arg. local function wputbarg(n) if type(n) == "number" then if n < 0 or n > 255 then werror("unsigned immediate byte out of range") end wputb(n) else waction("IMM_B", n) end end -- Put unsigned word or arg. local function wputwarg(n) if type(n) == "number" then if shr(n, 16) ~= 0 then werror("unsigned immediate word out of range") end wputb(band(n, 255)); wputb(shr(n, 8)); else waction("IMM_W", n) end end -- Put signed or unsigned dword or arg. local function wputdarg(n) local tn = type(n) if tn == "number" then wputb(band(n, 255)) wputb(band(shr(n, 8), 255)) wputb(band(shr(n, 16), 255)) wputb(shr(n, 24)) elseif tn == "table" then wputlabel("IMM_", n[1], 1) else waction("IMM_D", n) end end -- Put operand-size dependent number or arg (defaults to dword). local function wputszarg(sz, n) if not sz or sz == "d" or sz == "q" then wputdarg(n) elseif sz == "w" then wputwarg(n) elseif sz == "b" then wputbarg(n) elseif sz == "s" then wputsbarg(n) else werror("bad operand size") end end -- Put multi-byte opcode with operand-size dependent modifications. local function wputop(sz, op, rex, vex, vregr, vregxb) local psz, sk = 0, nil if vex then local tail if vex.m == 1 and band(rex, 11) == 0 then if x64 and vregxb then sk = map_vreg["modrm.reg"] else wputb(0xc5) tail = shl(bxor(band(rex, 4), 4), 5) psz = 3 end end if not tail then wputb(0xc4) wputb(shl(bxor(band(rex, 7), 7), 5) + vex.m) tail = shl(band(rex, 8), 4) psz = 4 end local reg, vreg = 0, nil if vex.v then reg = vex.v.reg if not reg then werror("bad vex operand") end if reg < 0 then reg = 0; vreg = vex.v.vreg end end if sz == "y" or vex.l then tail = tail + 4 end wputb(tail + shl(bxor(reg, 15), 3) + vex.p) wvreg("vex.v", vreg) rex = 0 if op >= 256 then werror("bad vex opcode") end else if rex ~= 0 then if not x64 then werror("bad operand size") end elseif (vregr or vregxb) and x64 then rex = 0x10 sk = map_vreg["vex.v"] end end local r if sz == "w" then wputb(102) end -- Needs >32 bit numbers, but only for crc32 eax, word [ebx] if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end if op >= 65536 then if rex ~= 0 then local opc3 = band(op, 0xffff00) if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end end wputb(shr(op, 16)); op = band(op, 0xffff); psz = psz + 1 end if op >= 256 then local b = shr(op, 8) if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end wputb(b); op = band(op, 255); psz = psz + 1 end if rex ~= 0 then wputb(64 + band(rex, 15)); psz = 2 end if sz == "b" then op = op - 1 end wputb(op) return psz, sk end -- Put ModRM or SIB formatted byte. local function wputmodrm(m, s, rm, vs, vrm) assert(m < 4 and s < 16 and rm < 16, "bad modrm operands") wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7)) end -- Put ModRM/SIB plus optional displacement. local function wputmrmsib(t, imark, s, vsreg, psz, sk) local vreg, vxreg local reg, xreg = t.reg, t.xreg if reg and reg < 0 then reg = 0; vreg = t.vreg end if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end if s < 0 then s = 0 end -- Register mode. if sub(t.mode, 1, 1) == "r" then wputmodrm(3, s, reg) wvreg("modrm.reg", vsreg, psz+1, sk, vreg) wvreg("modrm.rm.r", vreg, psz+1, sk) return end local disp = t.disp local tdisp = type(disp) -- No base register? if not reg then local riprel = false if xreg then -- Indexed mode with index register only. -- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp) wputmodrm(0, s, 4) if imark == "I" then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vxreg) wputmodrm(t.xsc, xreg, 5) wvreg("sib.index", vxreg, psz+2, sk) else -- Pure 32 bit displacement. if x64 and tdisp ~= "table" then wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp) wvreg("modrm.reg", vsreg, psz+1, sk) if imark == "I" then waction("MARK") end wputmodrm(0, 4, 5) else riprel = x64 wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp) wvreg("modrm.reg", vsreg, psz+1, sk) if imark == "I" then waction("MARK") end end end if riprel then -- Emit rip-relative displacement. if match("UWSiI", imark) then werror("NYI: rip-relative displacement followed by immediate") end -- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f. wputlabel("REL_", disp[1], 2) else wputdarg(disp) end return end local m if tdisp == "number" then -- Check displacement size at assembly time. if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too) if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0] elseif disp >= -128 and disp <= 127 then m = 1 else m = 2 end elseif tdisp == "table" then m = 2 end -- Index register present or esp as base register: need SIB encoding. if xreg or band(reg, 7) == 4 then wputmodrm(m or 2, s, 4) -- ModRM. if m == nil or imark == "I" then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vxreg or vreg) wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB. wvreg("sib.index", vxreg, psz+2, sk, vreg) wvreg("sib.base", vreg, psz+2, sk) else wputmodrm(m or 2, s, reg) -- ModRM. if (imark == "I" and (m == 1 or m == 2)) or (m == nil and (vsreg or vreg)) then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vreg) wvreg("modrm.rm.m", vreg, psz+1, sk) end -- Put displacement. if m == 1 then wputsbarg(disp) elseif m == 2 then wputdarg(disp) elseif m == nil then waction("DISP", disp) end end ------------------------------------------------------------------------------ -- Return human-readable operand mode string. local function opmodestr(op, args) local m = {} for i=1,#args do local a = args[i] m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?") end return op.." "..concat(m, ",") end -- Convert number to valid integer or nil. local function toint(expr) local n = tonumber(expr) if n then if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then werror("bad integer number `"..expr.."'") end return n end end -- Parse immediate expression. local function immexpr(expr) -- &expr (pointer) if sub(expr, 1, 1) == "&" then return "iPJ", format("(ptrdiff_t)(%s)", sub(expr,2)) end local prefix = sub(expr, 1, 2) -- =>expr (pc label reference) if prefix == "=>" then return "iJ", sub(expr, 3) end -- ->name (global label reference) if prefix == "->" then return "iJ", map_global[sub(expr, 3)] end -- [<>][1-9] (local label reference) local dir, lnum = match(expr, "^([<>])([1-9])$") if dir then -- Fwd: 247-255, Bkwd: 1-9. return "iJ", lnum + (dir == ">" and 246 or 0) end local extname = match(expr, "^extern%s+(%S+)$") if extname then return "iJ", map_extern[extname] end -- expr (interpreted as immediate) return "iI", expr end -- Parse displacement expression: +-num, +-expr, +-opsize*num local function dispexpr(expr) local disp = expr == "" and 0 or toint(expr) if disp then return disp end local c, dispt = match(expr, "^([+-])%s*(.+)$") if c == "+" then expr = dispt elseif not c then werror("bad displacement expression `"..expr.."'") end local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$") local ops, imm = map_opsize[opsize], toint(tailops) if ops and imm then if c == "-" then imm = -imm end return imm*map_opsizenum[ops] end local mode, iexpr = immexpr(dispt) if mode == "iJ" then if c == "-" then werror("cannot invert label reference") end return { iexpr } end return expr -- Need to return original signed expression. end -- Parse register or type expression. local function rtexpr(expr) if not expr then return end local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg local rnum = map_reg_num[reg] if not rnum then werror("type `"..(tname or expr).."' needs a register override") end if not map_reg_valid_base[reg] then werror("bad base register override `"..(map_reg_rev[reg] or reg).."'") end return reg, rnum, tp end return expr, map_reg_num[expr] end -- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }. local function parseoperand(param) local t = {} local expr = param local opsize, tailops = match(param, "^(%w+)%s*(.+)$") if opsize then t.opsize = map_opsize[opsize] if t.opsize then expr = tailops end end local br = match(expr, "^%[%s*(.-)%s*%]$") repeat if br then t.mode = "xm" -- [disp] t.disp = toint(br) if t.disp then t.mode = x64 and "xm" or "xmO" break end -- [reg...] local tp local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if not t.reg then -- [expr] t.mode = x64 and "xm" or "xmO" t.disp = dispexpr("+"..br) break end if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr] local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$") if xsc then if not map_reg_valid_index[reg] then werror("bad index register `"..map_reg_rev[reg].."'") end t.xsc = map_xsc[xsc] t.xreg = t.reg t.vxreg = t.vreg t.reg = nil t.vreg = nil t.disp = dispexpr(tailsc) break end if not map_reg_valid_base[reg] then werror("bad base register `"..map_reg_rev[reg].."'") end -- [reg] or [reg+-disp] t.disp = toint(tailr) or (tailr == "" and 0) if t.disp then break end -- [reg+xreg...] local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$") xreg, t.xreg, tp = rtexpr(xreg) if not t.xreg then -- [reg+-expr] t.disp = dispexpr(tailr) break end if not map_reg_valid_index[xreg] then werror("bad index register `"..map_reg_rev[xreg].."'") end if t.xreg == -1 then t.vxreg, tailx = match(tailx, "^(%b())(.*)$") if not t.vxreg then werror("bad variable register expression") end end -- [reg+xreg*xsc...] local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$") if xsc then t.xsc = map_xsc[xsc] tailx = tailsc end -- [...] or [...+-disp] or [...+-expr] t.disp = dispexpr(tailx) else -- imm or opsize*imm local imm = toint(expr) if not imm and sub(expr, 1, 1) == "*" and t.opsize then imm = toint(sub(expr, 2)) if imm then imm = imm * map_opsizenum[t.opsize] t.opsize = nil end end if imm then if t.opsize then werror("bad operand size override") end local m = "i" if imm == 1 then m = m.."1" end if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end if imm >= -128 and imm <= 127 then m = m.."S" end t.imm = imm t.mode = m break end local tp local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if t.reg then if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- reg if tailr == "" then if t.opsize then werror("bad operand size override") end t.opsize = map_reg_opsize[reg] if t.opsize == "f" then t.mode = t.reg == 0 and "fF" or "f" else if reg == "@w4" or (x64 and reg == "@d4") then wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'")) end t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm") end t.needrex = map_reg_needrex[reg] break end -- type[idx], type[idx].field, type->field -> [reg+offset_expr] if not tp then werror("bad operand `"..param.."'") end t.mode = "xm" t.disp = format(tp.ctypefmt, tailr) else t.mode, t.imm = immexpr(expr) if sub(t.mode, -1) == "J" then if t.opsize and t.opsize ~= addrsize then werror("bad operand size override") end t.opsize = addrsize end end end until true return t end ------------------------------------------------------------------------------ -- x86 Template String Description -- =============================== -- -- Each template string is a list of [match:]pattern pairs, -- separated by "|". The first match wins. No match means a -- bad or unsupported combination of operand modes or sizes. -- -- The match part and the ":" is omitted if the operation has -- no operands. Otherwise the first N characters are matched -- against the mode strings of each of the N operands. -- -- The mode string for each operand type is (see parseoperand()): -- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl -- FP register: "f", +"F" for st0 -- Index operand: "xm", +"O" for [disp] (pure offset) -- Immediate: "i", +"S" for signed 8 bit, +"1" for 1, -- +"I" for arg, +"P" for pointer -- Any: +"J" for valid jump targets -- -- So a match character "m" (mixed) matches both an integer register -- and an index operand (to be encoded with the ModRM/SIB scheme). -- But "r" matches only a register and "x" only an index operand -- (e.g. for FP memory access operations). -- -- The operand size match string starts right after the mode match -- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty. -- The effective data size of the operation is matched against this list. -- -- If only the regular "b", "w", "d", "q", "t" operand sizes are -- present, then all operands must be the same size. Unspecified sizes -- are ignored, but at least one operand must have a size or the pattern -- won't match (use the "byte", "word", "dword", "qword", "tword" -- operand size overrides. E.g.: mov dword [eax], 1). -- -- If the list has a "1" or "2" prefix, the operand size is taken -- from the respective operand and any other operand sizes are ignored. -- If the list contains only ".", all operand sizes are ignored. -- If the list has a "/" prefix, the concatenated (mixed) operand sizes -- are compared to the match. -- -- E.g. "rrdw" matches for either two dword registers or two word -- registers. "Fx2dq" matches an st0 operand plus an index operand -- pointing to a dword (float) or qword (double). -- -- Every character after the ":" is part of the pattern string: -- Hex chars are accumulated to form the opcode (left to right). -- "n" disables the standard opcode mods -- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q") -- "X" Force REX.W. -- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode. -- "m"/"M" generates ModRM/SIB from the 1st/2nd operand. -- The spare 3 bits are either filled with the last hex digit or -- the result from a previous "r"/"R". The opcode is restored. -- "u" Use VEX encoding, vvvv unused. -- "v"/"V" Use VEX encoding, vvvv from 1st/2nd operand (the operand is -- removed from the list used by future characters). -- "L" Force VEX.L -- -- All of the following characters force a flush of the opcode: -- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand. -- "s" stores a 4 bit immediate from the last register operand, -- followed by 4 zero bits. -- "S" stores a signed 8 bit immediate from the last operand. -- "U" stores an unsigned 8 bit immediate from the last operand. -- "W" stores an unsigned 16 bit immediate from the last operand. -- "i" stores an operand sized immediate from the last operand. -- "I" dito, but generates an action code to optionally modify -- the opcode (+2) for a signed 8 bit immediate. -- "J" generates one of the REL action codes from the last operand. -- ------------------------------------------------------------------------------ -- Template strings for x86 instructions. Ordered by first opcode byte. -- Unimplemented opcodes (deliberate omissions) are marked with *. local map_op = { -- 00-05: add... -- 06: *push es -- 07: *pop es -- 08-0D: or... -- 0E: *push cs -- 0F: two byte opcode prefix -- 10-15: adc... -- 16: *push ss -- 17: *pop ss -- 18-1D: sbb... -- 1E: *push ds -- 1F: *pop ds -- 20-25: and... es_0 = "26", -- 27: *daa -- 28-2D: sub... cs_0 = "2E", -- 2F: *das -- 30-35: xor... ss_0 = "36", -- 37: *aaa -- 38-3D: cmp... ds_0 = "3E", -- 3F: *aas inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m", dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m", push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or "rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i", pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m", -- 60: *pusha, *pushad, *pushaw -- 61: *popa, *popad, *popaw -- 62: *bound rdw,x -- 63: x86: *arpl mw,rw movsxd_2 = x64 and "rm/qd:63rM", fs_0 = "64", gs_0 = "65", o16_0 = "66", a16_0 = not x64 and "67" or nil, a32_0 = x64 and "67", -- 68: push idw -- 69: imul rdw,mdw,idw -- 6A: push ib -- 6B: imul rdw,mdw,S -- 6C: *insb -- 6D: *insd, *insw -- 6E: *outsb -- 6F: *outsd, *outsw -- 70-7F: jcc lb -- 80: add... mb,i -- 81: add... mdw,i -- 82: *undefined -- 83: add... mdw,S test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi", -- 86: xchg rb,mb -- 87: xchg rdw,mdw -- 88: mov mb,r -- 89: mov mdw,r -- 8A: mov r,mb -- 8B: mov r,mdw -- 8C: *mov mdw,seg lea_2 = "rx1dq:8DrM", -- 8E: *mov seg,mdw -- 8F: pop mdw nop_0 = "90", xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm", cbw_0 = "6698", cwde_0 = "98", cdqe_0 = "4898", cwd_0 = "6699", cdq_0 = "99", cqo_0 = "4899", -- 9A: *call iw:idw wait_0 = "9B", fwait_0 = "9B", pushf_0 = "9C", pushfd_0 = not x64 and "9C", pushfq_0 = x64 and "9C", popf_0 = "9D", popfd_0 = not x64 and "9D", popfq_0 = x64 and "9D", sahf_0 = "9E", lahf_0 = "9F", mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi", movsb_0 = "A4", movsw_0 = "66A5", movsd_0 = "A5", cmpsb_0 = "A6", cmpsw_0 = "66A7", cmpsd_0 = "A7", -- A8: test Rb,i -- A9: test Rdw,i stosb_0 = "AA", stosw_0 = "66AB", stosd_0 = "AB", lodsb_0 = "AC", lodsw_0 = "66AD", lodsd_0 = "AD", scasb_0 = "AE", scasw_0 = "66AF", scasd_0 = "AF", -- B0-B7: mov rb,i -- B8-BF: mov rdw,i -- C0: rol... mb,i -- C1: rol... mdw,i ret_1 = "i.:nC2W", ret_0 = "C3", -- C4: *les rdw,mq -- C5: *lds rdw,mq -- C6: mov mb,i -- C7: mov mdw,i -- C8: *enter iw,ib leave_0 = "C9", -- CA: *retf iw -- CB: *retf int3_0 = "CC", int_1 = "i.:nCDU", into_0 = "CE", -- CF: *iret -- D0: rol... mb,1 -- D1: rol... mdw,1 -- D2: rol... mb,cl -- D3: rol... mb,cl -- D4: *aam ib -- D5: *aad ib -- D6: *salc -- D7: *xlat -- D8-DF: floating point ops -- E0: *loopne -- E1: *loope -- E2: *loop -- E3: *jcxz, *jecxz -- E4: *in Rb,ib -- E5: *in Rdw,ib -- E6: *out ib,Rb -- E7: *out ib,Rdw call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J", jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB -- EA: *jmp iw:idw -- EB: jmp ib -- EC: *in Rb,dx -- ED: *in Rdw,dx -- EE: *out dx,Rb -- EF: *out dx,Rdw lock_0 = "F0", int1_0 = "F1", repne_0 = "F2", repnz_0 = "F2", rep_0 = "F3", repe_0 = "F3", repz_0 = "F3", -- F4: *hlt cmc_0 = "F5", -- F6: test... mb,i; div... mb -- F7: test... mdw,i; div... mdw clc_0 = "F8", stc_0 = "F9", -- FA: *cli cld_0 = "FC", std_0 = "FD", -- FE: inc... mb -- FF: inc... mdw -- misc ops not_1 = "m:F72m", neg_1 = "m:F73m", mul_1 = "m:F74m", imul_1 = "m:F75m", div_1 = "m:F76m", idiv_1 = "m:F77m", imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi", imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi", movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:", movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:", bswap_1 = "rqd:0FC8r", bsf_2 = "rmqdw:0FBCrM", bsr_2 = "rmqdw:0FBDrM", bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU", btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU", btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU", bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU", shld_3 = "mriqdw:0FA4RmU|mrC/qq:0FA5Rm|mrC/dd:|mrC/ww:", shrd_3 = "mriqdw:0FACRmU|mrC/qq:0FADRm|mrC/dd:|mrC/ww:", rdtsc_0 = "0F31", -- P1+ rdpmc_0 = "0F33", -- P6+ cpuid_0 = "0FA2", -- P1+ -- floating point ops fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m", fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m", fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m", fpop_0 = "DDD8", -- Alias for fstp st0. fist_1 = "xw:nDF2m|xd:DB2m", fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m", fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m", fxch_0 = "D9C9", fxch_1 = "ff:D9C8r", fxch_2 = "fFf:D9C8r|Fff:D9C8R", fucom_1 = "ff:DDE0r", fucom_2 = "Fff:DDE0R", fucomp_1 = "ff:DDE8r", fucomp_2 = "Fff:DDE8R", fucomi_1 = "ff:DBE8r", -- P6+ fucomi_2 = "Fff:DBE8R", -- P6+ fucomip_1 = "ff:DFE8r", -- P6+ fucomip_2 = "Fff:DFE8R", -- P6+ fcomi_1 = "ff:DBF0r", -- P6+ fcomi_2 = "Fff:DBF0R", -- P6+ fcomip_1 = "ff:DFF0r", -- P6+ fcomip_2 = "Fff:DFF0R", -- P6+ fucompp_0 = "DAE9", fcompp_0 = "DED9", fldenv_1 = "x.:D94m", fnstenv_1 = "x.:D96m", fstenv_1 = "x.:9BD96m", fldcw_1 = "xw:nD95m", fstcw_1 = "xw:n9BD97m", fnstcw_1 = "xw:nD97m", fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m", fnstsw_1 = "Rw:nDFE0|xw:nDD7m", fclex_0 = "9BDBE2", fnclex_0 = "DBE2", fnop_0 = "D9D0", -- D9D1-D9DF: unassigned fchs_0 = "D9E0", fabs_0 = "D9E1", -- D9E2: unassigned -- D9E3: unassigned ftst_0 = "D9E4", fxam_0 = "D9E5", -- D9E6: unassigned -- D9E7: unassigned fld1_0 = "D9E8", fldl2t_0 = "D9E9", fldl2e_0 = "D9EA", fldpi_0 = "D9EB", fldlg2_0 = "D9EC", fldln2_0 = "D9ED", fldz_0 = "D9EE", -- D9EF: unassigned f2xm1_0 = "D9F0", fyl2x_0 = "D9F1", fptan_0 = "D9F2", fpatan_0 = "D9F3", fxtract_0 = "D9F4", fprem1_0 = "D9F5", fdecstp_0 = "D9F6", fincstp_0 = "D9F7", fprem_0 = "D9F8", fyl2xp1_0 = "D9F9", fsqrt_0 = "D9FA", fsincos_0 = "D9FB", frndint_0 = "D9FC", fscale_0 = "D9FD", fsin_0 = "D9FE", fcos_0 = "D9FF", -- SSE, SSE2 andnpd_2 = "rmo:660F55rM", andnps_2 = "rmo:0F55rM", andpd_2 = "rmo:660F54rM", andps_2 = "rmo:0F54rM", clflush_1 = "x.:0FAE7m", cmppd_3 = "rmio:660FC2rMU", cmpps_3 = "rmio:0FC2rMU", cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:", cmpss_3 = "rrio:F30FC2rMU|rxi/od:", comisd_2 = "rro:660F2FrM|rx/oq:", comiss_2 = "rro:0F2FrM|rx/od:", cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:", cvtdq2ps_2 = "rmo:0F5BrM", cvtpd2dq_2 = "rmo:F20FE6rM", cvtpd2ps_2 = "rmo:660F5ArM", cvtpi2pd_2 = "rx/oq:660F2ArM", cvtpi2ps_2 = "rx/oq:0F2ArM", cvtps2dq_2 = "rmo:660F5BrM", cvtps2pd_2 = "rro:0F5ArM|rx/oq:", cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:", cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:", cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM", cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM", cvtss2sd_2 = "rro:F30F5ArM|rx/od:", cvtss2si_2 = "rr/do:F30F2DrM|rr/qo:|rxd:|rx/qd:", cvttpd2dq_2 = "rmo:660FE6rM", cvttps2dq_2 = "rmo:F30F5BrM", cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:", cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:", fxsave_1 = "x.:0FAE0m", fxrstor_1 = "x.:0FAE1m", ldmxcsr_1 = "xd:0FAE2m", lfence_0 = "0FAEE8", maskmovdqu_2 = "rro:660FF7rM", mfence_0 = "0FAEF0", movapd_2 = "rmo:660F28rM|mro:660F29Rm", movaps_2 = "rmo:0F28rM|mro:0F29Rm", movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:", movdqa_2 = "rmo:660F6FrM|mro:660F7FRm", movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm", movhlps_2 = "rro:0F12rM", movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm", movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm", movlhps_2 = "rro:0F16rM", movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm", movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm", movmskpd_2 = "rr/do:660F50rM", movmskps_2 = "rr/do:0F50rM", movntdq_2 = "xro:660FE7Rm", movnti_2 = "xrqd:0FC3Rm", movntpd_2 = "xro:660F2BRm", movntps_2 = "xro:0F2BRm", movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm", movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm", movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm", movupd_2 = "rmo:660F10rM|mro:660F11Rm", movups_2 = "rmo:0F10rM|mro:0F11Rm", orpd_2 = "rmo:660F56rM", orps_2 = "rmo:0F56rM", pause_0 = "F390", pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nRmU", -- Mem op: SSE4.1 only. pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:", pmovmskb_2 = "rr/do:660FD7rM", prefetchnta_1 = "xb:n0F180m", prefetcht0_1 = "xb:n0F181m", prefetcht1_1 = "xb:n0F182m", prefetcht2_1 = "xb:n0F183m", pshufd_3 = "rmio:660F70rMU", pshufhw_3 = "rmio:F30F70rMU", pshuflw_3 = "rmio:F20F70rMU", pslld_2 = "rmo:660FF2rM|rio:660F726mU", pslldq_2 = "rio:660F737mU", psllq_2 = "rmo:660FF3rM|rio:660F736mU", psllw_2 = "rmo:660FF1rM|rio:660F716mU", psrad_2 = "rmo:660FE2rM|rio:660F724mU", psraw_2 = "rmo:660FE1rM|rio:660F714mU", psrld_2 = "rmo:660FD2rM|rio:660F722mU", psrldq_2 = "rio:660F733mU", psrlq_2 = "rmo:660FD3rM|rio:660F732mU", psrlw_2 = "rmo:660FD1rM|rio:660F712mU", rcpps_2 = "rmo:0F53rM", rcpss_2 = "rro:F30F53rM|rx/od:", rsqrtps_2 = "rmo:0F52rM", rsqrtss_2 = "rmo:F30F52rM", sfence_0 = "0FAEF8", shufpd_3 = "rmio:660FC6rMU", shufps_3 = "rmio:0FC6rMU", stmxcsr_1 = "xd:0FAE3m", ucomisd_2 = "rro:660F2ErM|rx/oq:", ucomiss_2 = "rro:0F2ErM|rx/od:", unpckhpd_2 = "rmo:660F15rM", unpckhps_2 = "rmo:0F15rM", unpcklpd_2 = "rmo:660F14rM", unpcklps_2 = "rmo:0F14rM", xorpd_2 = "rmo:660F57rM", xorps_2 = "rmo:0F57rM", -- SSE3 ops fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m", addsubpd_2 = "rmo:660FD0rM", addsubps_2 = "rmo:F20FD0rM", haddpd_2 = "rmo:660F7CrM", haddps_2 = "rmo:F20F7CrM", hsubpd_2 = "rmo:660F7DrM", hsubps_2 = "rmo:F20F7DrM", lddqu_2 = "rxo:F20FF0rM", movddup_2 = "rmo:F20F12rM", movshdup_2 = "rmo:F30F16rM", movsldup_2 = "rmo:F30F12rM", -- SSSE3 ops pabsb_2 = "rmo:660F381CrM", pabsd_2 = "rmo:660F381ErM", pabsw_2 = "rmo:660F381DrM", palignr_3 = "rmio:660F3A0FrMU", phaddd_2 = "rmo:660F3802rM", phaddsw_2 = "rmo:660F3803rM", phaddw_2 = "rmo:660F3801rM", phsubd_2 = "rmo:660F3806rM", phsubsw_2 = "rmo:660F3807rM", phsubw_2 = "rmo:660F3805rM", pmaddubsw_2 = "rmo:660F3804rM", pmulhrsw_2 = "rmo:660F380BrM", pshufb_2 = "rmo:660F3800rM", psignb_2 = "rmo:660F3808rM", psignd_2 = "rmo:660F380ArM", psignw_2 = "rmo:660F3809rM", -- SSE4.1 ops blendpd_3 = "rmio:660F3A0DrMU", blendps_3 = "rmio:660F3A0CrMU", blendvpd_3 = "rmRo:660F3815rM", blendvps_3 = "rmRo:660F3814rM", dppd_3 = "rmio:660F3A41rMU", dpps_3 = "rmio:660F3A40rMU", extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU", insertps_3 = "rrio:660F3A41rMU|rxi/od:", movntdqa_2 = "rxo:660F382ArM", mpsadbw_3 = "rmio:660F3A42rMU", packusdw_2 = "rmo:660F382BrM", pblendvb_3 = "rmRo:660F3810rM", pblendw_3 = "rmio:660F3A0ErMU", pcmpeqq_2 = "rmo:660F3829rM", pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:", pextrd_3 = "mri/do:660F3A16RmU", pextrq_3 = "mri/qo:660F3A16RmU", -- pextrw is SSE2, mem operand is SSE4.1 only phminposuw_2 = "rmo:660F3841rM", pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:", pinsrd_3 = "rmi/od:660F3A22rMU", pinsrq_3 = "rmi/oq:660F3A22rXMU", pmaxsb_2 = "rmo:660F383CrM", pmaxsd_2 = "rmo:660F383DrM", pmaxud_2 = "rmo:660F383FrM", pmaxuw_2 = "rmo:660F383ErM", pminsb_2 = "rmo:660F3838rM", pminsd_2 = "rmo:660F3839rM", pminud_2 = "rmo:660F383BrM", pminuw_2 = "rmo:660F383ArM", pmovsxbd_2 = "rro:660F3821rM|rx/od:", pmovsxbq_2 = "rro:660F3822rM|rx/ow:", pmovsxbw_2 = "rro:660F3820rM|rx/oq:", pmovsxdq_2 = "rro:660F3825rM|rx/oq:", pmovsxwd_2 = "rro:660F3823rM|rx/oq:", pmovsxwq_2 = "rro:660F3824rM|rx/od:", pmovzxbd_2 = "rro:660F3831rM|rx/od:", pmovzxbq_2 = "rro:660F3832rM|rx/ow:", pmovzxbw_2 = "rro:660F3830rM|rx/oq:", pmovzxdq_2 = "rro:660F3835rM|rx/oq:", pmovzxwd_2 = "rro:660F3833rM|rx/oq:", pmovzxwq_2 = "rro:660F3834rM|rx/od:", pmuldq_2 = "rmo:660F3828rM", pmulld_2 = "rmo:660F3840rM", ptest_2 = "rmo:660F3817rM", roundpd_3 = "rmio:660F3A09rMU", roundps_3 = "rmio:660F3A08rMU", roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:", roundss_3 = "rrio:660F3A0ArMU|rxi/od:", -- SSE4.2 ops crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:", pcmpestri_3 = "rmio:660F3A61rMU", pcmpestrm_3 = "rmio:660F3A60rMU", pcmpgtq_2 = "rmo:660F3837rM", pcmpistri_3 = "rmio:660F3A63rMU", pcmpistrm_3 = "rmio:660F3A62rMU", popcnt_2 = "rmqdw:F30FB8rM", -- SSE4a extrq_2 = "rro:660F79rM", extrq_3 = "riio:660F780mUU", insertq_2 = "rro:F20F79rM", insertq_4 = "rriio:F20F78rMUU", lzcnt_2 = "rmqdw:F30FBDrM", movntsd_2 = "xr/qo:nF20F2BRm", movntss_2 = "xr/do:F30F2BRm", -- popcnt is also in SSE4.2 -- AES-NI aesdec_2 = "rmo:660F38DErM", aesdeclast_2 = "rmo:660F38DFrM", aesenc_2 = "rmo:660F38DCrM", aesenclast_2 = "rmo:660F38DDrM", aesimc_2 = "rmo:660F38DBrM", aeskeygenassist_3 = "rmio:660F3ADFrMU", pclmulqdq_3 = "rmio:660F3A44rMU", -- AVX FP ops vaddsubpd_3 = "rrmoy:660FVD0rM", vaddsubps_3 = "rrmoy:F20FVD0rM", vandpd_3 = "rrmoy:660FV54rM", vandps_3 = "rrmoy:0FV54rM", vandnpd_3 = "rrmoy:660FV55rM", vandnps_3 = "rrmoy:0FV55rM", vblendpd_4 = "rrmioy:660F3AV0DrMU", vblendps_4 = "rrmioy:660F3AV0CrMU", vblendvpd_4 = "rrmroy:660F3AV4BrMs", vblendvps_4 = "rrmroy:660F3AV4ArMs", vbroadcastf128_2 = "rx/yo:660F38u1ArM", vcmppd_4 = "rrmioy:660FVC2rMU", vcmpps_4 = "rrmioy:0FVC2rMU", vcmpsd_4 = "rrrio:F20FVC2rMU|rrxi/ooq:", vcmpss_4 = "rrrio:F30FVC2rMU|rrxi/ood:", vcomisd_2 = "rro:660Fu2FrM|rx/oq:", vcomiss_2 = "rro:0Fu2FrM|rx/od:", vcvtdq2pd_2 = "rro:F30FuE6rM|rx/oq:|rm/yo:", vcvtdq2ps_2 = "rmoy:0Fu5BrM", vcvtpd2dq_2 = "rmoy:F20FuE6rM", vcvtpd2ps_2 = "rmoy:660Fu5ArM", vcvtps2dq_2 = "rmoy:660Fu5BrM", vcvtps2pd_2 = "rro:0Fu5ArM|rx/oq:|rm/yo:", vcvtsd2si_2 = "rr/do:F20Fu2DrM|rx/dq:|rr/qo:|rxq:", vcvtsd2ss_3 = "rrro:F20FV5ArM|rrx/ooq:", vcvtsi2sd_3 = "rrm/ood:F20FV2ArM|rrm/ooq:F20FVX2ArM", vcvtsi2ss_3 = "rrm/ood:F30FV2ArM|rrm/ooq:F30FVX2ArM", vcvtss2sd_3 = "rrro:F30FV5ArM|rrx/ood:", vcvtss2si_2 = "rr/do:F30Fu2DrM|rxd:|rr/qo:|rx/qd:", vcvttpd2dq_2 = "rmo:660FuE6rM|rm/oy:660FuLE6rM", vcvttps2dq_2 = "rmoy:F30Fu5BrM", vcvttsd2si_2 = "rr/do:F20Fu2CrM|rx/dq:|rr/qo:|rxq:", vcvttss2si_2 = "rr/do:F30Fu2CrM|rxd:|rr/qo:|rx/qd:", vdppd_4 = "rrmio:660F3AV41rMU", vdpps_4 = "rrmioy:660F3AV40rMU", vextractf128_3 = "mri/oy:660F3AuL19RmU", vextractps_3 = "mri/do:660F3Au17RmU", vhaddpd_3 = "rrmoy:660FV7CrM", vhaddps_3 = "rrmoy:F20FV7CrM", vhsubpd_3 = "rrmoy:660FV7DrM", vhsubps_3 = "rrmoy:F20FV7DrM", vinsertf128_4 = "rrmi/yyo:660F3AV18rMU", vinsertps_4 = "rrrio:660F3AV21rMU|rrxi/ood:", vldmxcsr_1 = "xd:0FuAE2m", vmaskmovps_3 = "rrxoy:660F38V2CrM|xrroy:660F38V2ERm", vmaskmovpd_3 = "rrxoy:660F38V2DrM|xrroy:660F38V2FRm", vmovapd_2 = "rmoy:660Fu28rM|mroy:660Fu29Rm", vmovaps_2 = "rmoy:0Fu28rM|mroy:0Fu29Rm", vmovd_2 = "rm/od:660Fu6ErM|rm/oq:660FuX6ErM|mr/do:660Fu7ERm|mr/qo:", vmovq_2 = "rro:F30Fu7ErM|rx/oq:|xr/qo:660FuD6Rm", vmovddup_2 = "rmy:F20Fu12rM|rro:|rx/oq:", vmovhlps_3 = "rrro:0FV12rM", vmovhpd_2 = "xr/qo:660Fu17Rm", vmovhpd_3 = "rrx/ooq:660FV16rM", vmovhps_2 = "xr/qo:0Fu17Rm", vmovhps_3 = "rrx/ooq:0FV16rM", vmovlhps_3 = "rrro:0FV16rM", vmovlpd_2 = "xr/qo:660Fu13Rm", vmovlpd_3 = "rrx/ooq:660FV12rM", vmovlps_2 = "xr/qo:0Fu13Rm", vmovlps_3 = "rrx/ooq:0FV12rM", vmovmskpd_2 = "rr/do:660Fu50rM|rr/dy:660FuL50rM", vmovmskps_2 = "rr/do:0Fu50rM|rr/dy:0FuL50rM", vmovntpd_2 = "xroy:660Fu2BRm", vmovntps_2 = "xroy:0Fu2BRm", vmovsd_2 = "rx/oq:F20Fu10rM|xr/qo:F20Fu11Rm", vmovsd_3 = "rrro:F20FV10rM", vmovshdup_2 = "rmoy:F30Fu16rM", vmovsldup_2 = "rmoy:F30Fu12rM", vmovss_2 = "rx/od:F30Fu10rM|xr/do:F30Fu11Rm", vmovss_3 = "rrro:F30FV10rM", vmovupd_2 = "rmoy:660Fu10rM|mroy:660Fu11Rm", vmovups_2 = "rmoy:0Fu10rM|mroy:0Fu11Rm", vorpd_3 = "rrmoy:660FV56rM", vorps_3 = "rrmoy:0FV56rM", vpermilpd_3 = "rrmoy:660F38V0DrM|rmioy:660F3Au05rMU", vpermilps_3 = "rrmoy:660F38V0CrM|rmioy:660F3Au04rMU", vperm2f128_4 = "rrmiy:660F3AV06rMU", vptestpd_2 = "rmoy:660F38u0FrM", vptestps_2 = "rmoy:660F38u0ErM", vrcpps_2 = "rmoy:0Fu53rM", vrcpss_3 = "rrro:F30FV53rM|rrx/ood:", vrsqrtps_2 = "rmoy:0Fu52rM", vrsqrtss_3 = "rrro:F30FV52rM|rrx/ood:", vroundpd_3 = "rmioy:660F3AV09rMU", vroundps_3 = "rmioy:660F3AV08rMU", vroundsd_4 = "rrrio:660F3AV0BrMU|rrxi/ooq:", vroundss_4 = "rrrio:660F3AV0ArMU|rrxi/ood:", vshufpd_4 = "rrmioy:660FVC6rMU", vshufps_4 = "rrmioy:0FVC6rMU", vsqrtps_2 = "rmoy:0Fu51rM", vsqrtss_2 = "rro:F30Fu51rM|rx/od:", vsqrtpd_2 = "rmoy:660Fu51rM", vsqrtsd_2 = "rro:F20Fu51rM|rx/oq:", vstmxcsr_1 = "xd:0FuAE3m", vucomisd_2 = "rro:660Fu2ErM|rx/oq:", vucomiss_2 = "rro:0Fu2ErM|rx/od:", vunpckhpd_3 = "rrmoy:660FV15rM", vunpckhps_3 = "rrmoy:0FV15rM", vunpcklpd_3 = "rrmoy:660FV14rM", vunpcklps_3 = "rrmoy:0FV14rM", vxorpd_3 = "rrmoy:660FV57rM", vxorps_3 = "rrmoy:0FV57rM", vzeroall_0 = "0FuL77", vzeroupper_0 = "0Fu77", -- AVX2 FP ops vbroadcastss_2 = "rx/od:660F38u18rM|rx/yd:|rro:|rr/yo:", vbroadcastsd_2 = "rx/yq:660F38u19rM|rr/yo:", -- *vgather* (!vsib) vpermpd_3 = "rmiy:660F3AuX01rMU", vpermps_3 = "rrmy:660F38V16rM", -- AVX, AVX2 integer ops -- In general, xmm requires AVX, ymm requires AVX2. vaesdec_3 = "rrmo:660F38VDErM", vaesdeclast_3 = "rrmo:660F38VDFrM", vaesenc_3 = "rrmo:660F38VDCrM", vaesenclast_3 = "rrmo:660F38VDDrM", vaesimc_2 = "rmo:660F38uDBrM", vaeskeygenassist_3 = "rmio:660F3AuDFrMU", vlddqu_2 = "rxoy:F20FuF0rM", vmaskmovdqu_2 = "rro:660FuF7rM", vmovdqa_2 = "rmoy:660Fu6FrM|mroy:660Fu7FRm", vmovdqu_2 = "rmoy:F30Fu6FrM|mroy:F30Fu7FRm", vmovntdq_2 = "xroy:660FuE7Rm", vmovntdqa_2 = "rxoy:660F38u2ArM", vmpsadbw_4 = "rrmioy:660F3AV42rMU", vpabsb_2 = "rmoy:660F38u1CrM", vpabsd_2 = "rmoy:660F38u1ErM", vpabsw_2 = "rmoy:660F38u1DrM", vpackusdw_3 = "rrmoy:660F38V2BrM", vpalignr_4 = "rrmioy:660F3AV0FrMU", vpblendvb_4 = "rrmroy:660F3AV4CrMs", vpblendw_4 = "rrmioy:660F3AV0ErMU", vpclmulqdq_4 = "rrmio:660F3AV44rMU", vpcmpeqq_3 = "rrmoy:660F38V29rM", vpcmpestri_3 = "rmio:660F3Au61rMU", vpcmpestrm_3 = "rmio:660F3Au60rMU", vpcmpgtq_3 = "rrmoy:660F38V37rM", vpcmpistri_3 = "rmio:660F3Au63rMU", vpcmpistrm_3 = "rmio:660F3Au62rMU", vpextrb_3 = "rri/do:660F3Au14nRmU|rri/qo:|xri/bo:", vpextrw_3 = "rri/do:660FuC5rMU|xri/wo:660F3Au15nRmU", vpextrd_3 = "mri/do:660F3Au16RmU", vpextrq_3 = "mri/qo:660F3Au16RmU", vphaddw_3 = "rrmoy:660F38V01rM", vphaddd_3 = "rrmoy:660F38V02rM", vphaddsw_3 = "rrmoy:660F38V03rM", vphminposuw_2 = "rmo:660F38u41rM", vphsubw_3 = "rrmoy:660F38V05rM", vphsubd_3 = "rrmoy:660F38V06rM", vphsubsw_3 = "rrmoy:660F38V07rM", vpinsrb_4 = "rrri/ood:660F3AV20rMU|rrxi/oob:", vpinsrw_4 = "rrri/ood:660FVC4rMU|rrxi/oow:", vpinsrd_4 = "rrmi/ood:660F3AV22rMU", vpinsrq_4 = "rrmi/ooq:660F3AVX22rMU", vpmaddubsw_3 = "rrmoy:660F38V04rM", vpmaxsb_3 = "rrmoy:660F38V3CrM", vpmaxsd_3 = "rrmoy:660F38V3DrM", vpmaxuw_3 = "rrmoy:660F38V3ErM", vpmaxud_3 = "rrmoy:660F38V3FrM", vpminsb_3 = "rrmoy:660F38V38rM", vpminsd_3 = "rrmoy:660F38V39rM", vpminuw_3 = "rrmoy:660F38V3ArM", vpminud_3 = "rrmoy:660F38V3BrM", vpmovmskb_2 = "rr/do:660FuD7rM|rr/dy:660FuLD7rM", vpmovsxbw_2 = "rroy:660F38u20rM|rx/oq:|rx/yo:", vpmovsxbd_2 = "rroy:660F38u21rM|rx/od:|rx/yq:", vpmovsxbq_2 = "rroy:660F38u22rM|rx/ow:|rx/yd:", vpmovsxwd_2 = "rroy:660F38u23rM|rx/oq:|rx/yo:", vpmovsxwq_2 = "rroy:660F38u24rM|rx/od:|rx/yq:", vpmovsxdq_2 = "rroy:660F38u25rM|rx/oq:|rx/yo:", vpmovzxbw_2 = "rroy:660F38u30rM|rx/oq:|rx/yo:", vpmovzxbd_2 = "rroy:660F38u31rM|rx/od:|rx/yq:", vpmovzxbq_2 = "rroy:660F38u32rM|rx/ow:|rx/yd:", vpmovzxwd_2 = "rroy:660F38u33rM|rx/oq:|rx/yo:", vpmovzxwq_2 = "rroy:660F38u34rM|rx/od:|rx/yq:", vpmovzxdq_2 = "rroy:660F38u35rM|rx/oq:|rx/yo:", vpmuldq_3 = "rrmoy:660F38V28rM", vpmulhrsw_3 = "rrmoy:660F38V0BrM", vpmulld_3 = "rrmoy:660F38V40rM", vpshufb_3 = "rrmoy:660F38V00rM", vpshufd_3 = "rmioy:660Fu70rMU", vpshufhw_3 = "rmioy:F30Fu70rMU", vpshuflw_3 = "rmioy:F20Fu70rMU", vpsignb_3 = "rrmoy:660F38V08rM", vpsignw_3 = "rrmoy:660F38V09rM", vpsignd_3 = "rrmoy:660F38V0ArM", vpslldq_3 = "rrioy:660Fv737mU", vpsllw_3 = "rrmoy:660FVF1rM|rrioy:660Fv716mU", vpslld_3 = "rrmoy:660FVF2rM|rrioy:660Fv726mU", vpsllq_3 = "rrmoy:660FVF3rM|rrioy:660Fv736mU", vpsraw_3 = "rrmoy:660FVE1rM|rrioy:660Fv714mU", vpsrad_3 = "rrmoy:660FVE2rM|rrioy:660Fv724mU", vpsrldq_3 = "rrioy:660Fv733mU", vpsrlw_3 = "rrmoy:660FVD1rM|rrioy:660Fv712mU", vpsrld_3 = "rrmoy:660FVD2rM|rrioy:660Fv722mU", vpsrlq_3 = "rrmoy:660FVD3rM|rrioy:660Fv732mU", vptest_2 = "rmoy:660F38u17rM", -- AVX2 integer ops vbroadcasti128_2 = "rx/yo:660F38u5ArM", vinserti128_4 = "rrmi/yyo:660F3AV38rMU", vextracti128_3 = "mri/oy:660F3AuL39RmU", vpblendd_4 = "rrmioy:660F3AV02rMU", vpbroadcastb_2 = "rro:660F38u78rM|rx/ob:|rr/yo:|rx/yb:", vpbroadcastw_2 = "rro:660F38u79rM|rx/ow:|rr/yo:|rx/yw:", vpbroadcastd_2 = "rro:660F38u58rM|rx/od:|rr/yo:|rx/yd:", vpbroadcastq_2 = "rro:660F38u59rM|rx/oq:|rr/yo:|rx/yq:", vpermd_3 = "rrmy:660F38V36rM", vpermq_3 = "rmiy:660F3AuX00rMU", -- *vpgather* (!vsib) vperm2i128_4 = "rrmiy:660F3AV46rMU", vpmaskmovd_3 = "rrxoy:660F38V8CrM|xrroy:660F38V8ERm", vpmaskmovq_3 = "rrxoy:660F38VX8CrM|xrroy:660F38VX8ERm", vpsllvd_3 = "rrmoy:660F38V47rM", vpsllvq_3 = "rrmoy:660F38VX47rM", vpsravd_3 = "rrmoy:660F38V46rM", vpsrlvd_3 = "rrmoy:660F38V45rM", vpsrlvq_3 = "rrmoy:660F38VX45rM", -- Intel ADX adcx_2 = "rmqd:660F38F6rM", adox_2 = "rmqd:F30F38F6rM", } ------------------------------------------------------------------------------ -- Arithmetic ops. for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3, ["and"] = 4, sub = 5, xor = 6, cmp = 7 } do local n8 = shl(n, 3) map_op[name.."_2"] = format( "mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi", 1+n8, 3+n8, n, n, 5+n8, n) end -- Shift ops. for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3, shl = 4, shr = 5, sar = 7, sal = 4 } do map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n) end -- Conditional ops. for cc,n in pairs(map_cc) do map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n) map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+ end -- FP arithmetic ops. for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3, sub = 4, subr = 5, div = 6, divr = 7 } do local nc = 0xc0 + shl(n, 3) local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8)) local fn = "f"..name map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n) if n == 2 or n == 3 then map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n) else map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n) map_op[fn.."p_1"] = format("ff:DE%02Xr", nr) map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr) end map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n) end -- FP conditional moves. for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6) map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+ map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+ end -- SSE / AVX FP arithmetic ops. for name,n in pairs{ sqrt = 1, add = 8, mul = 9, sub = 12, min = 13, div = 14, max = 15 } do map_op[name.."ps_2"] = format("rmo:0F5%XrM", n) map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n) map_op[name.."pd_2"] = format("rmo:660F5%XrM", n) map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n) if n ~= 1 then map_op["v"..name.."ps_3"] = format("rrmoy:0FV5%XrM", n) map_op["v"..name.."ss_3"] = format("rrro:F30FV5%XrM|rrx/ood:", n) map_op["v"..name.."pd_3"] = format("rrmoy:660FV5%XrM", n) map_op["v"..name.."sd_3"] = format("rrro:F20FV5%XrM|rrx/ooq:", n) end end -- SSE2 / AVX / AVX2 integer arithmetic ops (66 0F leaf). for name,n in pairs{ paddb = 0xFC, paddw = 0xFD, paddd = 0xFE, paddq = 0xD4, paddsb = 0xEC, paddsw = 0xED, packssdw = 0x6B, packsswb = 0x63, packuswb = 0x67, paddusb = 0xDC, paddusw = 0xDD, pand = 0xDB, pandn = 0xDF, pavgb = 0xE0, pavgw = 0xE3, pcmpeqb = 0x74, pcmpeqd = 0x76, pcmpeqw = 0x75, pcmpgtb = 0x64, pcmpgtd = 0x66, pcmpgtw = 0x65, pmaddwd = 0xF5, pmaxsw = 0xEE, pmaxub = 0xDE, pminsw = 0xEA, pminub = 0xDA, pmulhuw = 0xE4, pmulhw = 0xE5, pmullw = 0xD5, pmuludq = 0xF4, por = 0xEB, psadbw = 0xF6, psubb = 0xF8, psubw = 0xF9, psubd = 0xFA, psubq = 0xFB, psubsb = 0xE8, psubsw = 0xE9, psubusb = 0xD8, psubusw = 0xD9, punpckhbw = 0x68, punpckhwd = 0x69, punpckhdq = 0x6A, punpckhqdq = 0x6D, punpcklbw = 0x60, punpcklwd = 0x61, punpckldq = 0x62, punpcklqdq = 0x6C, pxor = 0xEF } do map_op[name.."_2"] = format("rmo:660F%02XrM", n) map_op["v"..name.."_3"] = format("rrmoy:660FV%02XrM", n) end ------------------------------------------------------------------------------ local map_vexarg = { u = false, v = 1, V = 2 } -- Process pattern string. local function dopattern(pat, args, sz, op, needrex) local digit, addin, vex local opcode = 0 local szov = sz local narg = 1 local rex = 0 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 6 positions. if secpos+6 > maxsecpos then wflush() end -- Process each character. for c in gmatch(pat.."|", ".") do if match(c, "%x") then -- Hex digit. digit = byte(c) - 48 if digit > 48 then digit = digit - 39 elseif digit > 16 then digit = digit - 7 end opcode = opcode*16 + digit addin = nil elseif c == "n" then -- Disable operand size mods for opcode. szov = nil elseif c == "X" then -- Force REX.W. rex = 8 elseif c == "L" then -- Force VEX.L. vex.l = true elseif c == "r" then -- Merge 1st operand regno. into opcode. addin = args[1]; opcode = opcode + (addin.reg % 8) if narg < 2 then narg = 2 end elseif c == "R" then -- Merge 2nd operand regno. into opcode. addin = args[2]; opcode = opcode + (addin.reg % 8) narg = 3 elseif c == "m" or c == "M" then -- Encode ModRM/SIB. local s if addin then s = addin.reg opcode = opcode - band(s, 7) -- Undo regno opcode merge. else s = band(opcode, 15) -- Undo last digit. opcode = shr(opcode, 4) end local nn = c == "m" and 1 or 2 local t = args[nn] if narg <= nn then narg = nn + 1 end if szov == "q" and rex == 0 then rex = rex + 8 end if t.reg and t.reg > 7 then rex = rex + 1 end if t.xreg and t.xreg > 7 then rex = rex + 2 end if s > 7 then rex = rex + 4 end if needrex then rex = rex + 16 end local psz, sk = wputop(szov, opcode, rex, vex, s < 0, t.vreg or t.vxreg) opcode = nil local imark = sub(pat, -1) -- Force a mark (ugly). -- Put ModRM/SIB with regno/last digit as spare. wputmrmsib(t, imark, s, addin and addin.vreg, psz, sk) addin = nil elseif map_vexarg[c] ~= nil then -- Encode using VEX prefix local b = band(opcode, 255); opcode = shr(opcode, 8) local m = 1 if b == 0x38 then m = 2 elseif b == 0x3a then m = 3 end if m ~= 1 then b = band(opcode, 255); opcode = shr(opcode, 8) end if b ~= 0x0f then werror("expected `0F', `0F38', or `0F3A' to precede `"..c.. "' in pattern `"..pat.."' for `"..op.."'") end local v = map_vexarg[c] if v then v = remove(args, v) end b = band(opcode, 255) local p = 0 if b == 0x66 then p = 1 elseif b == 0xf3 then p = 2 elseif b == 0xf2 then p = 3 end if p ~= 0 then opcode = shr(opcode, 8) end if opcode ~= 0 then wputop(nil, opcode, 0); opcode = 0 end vex = { m = m, p = p, v = v } else if opcode then -- Flush opcode. if szov == "q" and rex == 0 then rex = rex + 8 end if needrex then rex = rex + 16 end if addin and addin.reg == -1 then local psz, sk = wputop(szov, opcode - 7, rex, vex, true) wvreg("opcode", addin.vreg, psz, sk) else if addin and addin.reg > 7 then rex = rex + 1 end wputop(szov, opcode, rex, vex) end opcode = nil end if c == "|" then break end if c == "o" then -- Offset (pure 32 bit displacement). wputdarg(args[1].disp); if narg < 2 then narg = 2 end elseif c == "O" then wputdarg(args[2].disp); narg = 3 else -- Anything else is an immediate operand. local a = args[narg] narg = narg + 1 local mode, imm = a.mode, a.imm if mode == "iJ" and not match("iIJ", c) then werror("bad operand size for label") end if c == "S" then wputsbarg(imm) elseif c == "U" then wputbarg(imm) elseif c == "W" then wputwarg(imm) elseif c == "i" or c == "I" then if mode == "iJ" then wputlabel("IMM_", imm, 1) elseif mode == "iI" and c == "I" then waction(sz == "w" and "IMM_WB" or "IMM_DB", imm) else wputszarg(sz, imm) end elseif c == "J" then if mode == "iPJ" then waction("REL_A", imm) -- !x64 (secpos) else wputlabel("REL_", imm, 2) end elseif c == "s" then local reg = a.reg if reg < 0 then wputb(0) wvreg("imm.hi", a.vreg) else wputb(shl(reg, 4)) end else werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'") end end end end end ------------------------------------------------------------------------------ -- Mapping of operand modes to short names. Suppress output with '#'. local map_modename = { r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm", f = "stx", F = "st0", J = "lbl", ["1"] = "1", I = "#", S = "#", O = "#", } -- Return a table/string showing all possible operand modes. local function templatehelp(template, nparams) if nparams == 0 then return "" end local t = {} for tm in gmatch(template, "[^%|]+") do local s = map_modename[sub(tm, 1, 1)] s = s..gsub(sub(tm, 2, nparams), ".", function(c) return ", "..map_modename[c] end) if not match(s, "#") then t[#t+1] = s end end return t end -- Match operand modes against mode match part of template. local function matchtm(tm, args) for i=1,#args do if not match(args[i].mode, sub(tm, i, i)) then return end end return true end -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return templatehelp(template, nparams) end local args = {} -- Zero-operand opcodes have no match part. if #params == 0 then dopattern(template, args, "d", params.op, nil) return end -- Determine common operand size (coerce undefined size) or flag as mixed. local sz, szmix, needrex for i,p in ipairs(params) do args[i] = parseoperand(p) local nsz = args[i].opsize if nsz then if sz and sz ~= nsz then szmix = true else sz = nsz end end local nrex = args[i].needrex if nrex ~= nil then if needrex == nil then needrex = nrex elseif needrex ~= nrex then werror("bad mix of byte-addressable registers") end end end -- Try all match:pattern pairs (separated by '|'). local gotmatch, lastpat for tm in gmatch(template, "[^%|]+") do -- Split off size match (starts after mode match) and pattern string. local szm, pat = match(tm, "^(.-):(.*)$", #args+1) if pat == "" then pat = lastpat else lastpat = pat end if matchtm(tm, args) then local prefix = sub(szm, 1, 1) if prefix == "/" then -- Exactly match leading operand sizes. for i = #szm,1,-1 do if i == 1 then dopattern(pat, args, sz, params.op, needrex) -- Process pattern. return elseif args[i-1].opsize ~= sub(szm, i, i) then break end end else -- Match common operand size. local szp = sz if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes. if prefix == "1" then szp = args[1].opsize; szmix = nil elseif prefix == "2" then szp = args[2].opsize; szmix = nil end if not szmix and (prefix == "." or match(szm, szp or "#")) then dopattern(pat, args, szp, params.op, needrex) -- Process pattern. return end end gotmatch = true end end local msg = "bad operand mode" if gotmatch then if szmix then msg = "mixed operand size" else msg = sz and "bad operand size" or "missing operand size" end end werror(msg.." in `"..opmodestr(params.op, args).."'") end ------------------------------------------------------------------------------ -- x64-specific opcode for 64 bit immediates and displacements. if x64 then function map_op.mov64_2(params) if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end if secpos+2 > maxsecpos then wflush() end local opcode, op64, sz, rex, vreg local op64 = match(params[1], "^%[%s*(.-)%s*%]$") if op64 then local a = parseoperand(params[2]) if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa3 else op64 = match(params[2], "^%[%s*(.-)%s*%]$") local a = parseoperand(params[1]) if op64 then if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa1 else if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then werror("bad operand mode") end op64 = params[2] if a.reg == -1 then vreg = a.vreg opcode = 0xb8 else opcode = 0xb8 + band(a.reg, 7) end rex = a.reg > 7 and 9 or 8 end end local psz, sk = wputop(sz, opcode, rex, nil, vreg) wvreg("opcode", vreg, psz, sk) waction("IMM_D", format("(unsigned int)(%s)", op64)) waction("IMM_D", format("(unsigned int)((%s)>>32)", op64)) end end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. local function op_data(params) if not params then return "imm..." end local sz = sub(params.op, 2, 2) if sz == "a" then sz = addrsize end for _,p in ipairs(params) do local a = parseoperand(p) if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then werror("bad mode or size in `"..p.."'") end if a.mode == "iJ" then wputlabel("IMM_", a.imm, 1) else wputszarg(sz, a.imm) end if secpos+2 > maxsecpos then wflush() end end end map_op[".byte_*"] = op_data map_op[".sbyte_*"] = op_data map_op[".word_*"] = op_data map_op[".dword_*"] = op_data map_op[".aword_*"] = op_data ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_2"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end if secpos+2 > maxsecpos then wflush() end local a = parseoperand(params[1]) local mode, imm = a.mode, a.imm if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then -- Local label (1: ... 9:) or global label (->global:). waction("LABEL_LG", nil, 1) wputxb(imm) elseif mode == "iJ" then -- PC label (=>pcexpr:). waction("LABEL_PC", imm) else werror("bad label definition") end -- SETLABEL must immediately follow LABEL_LG/LABEL_PC. local addr = params[2] if addr then local a = parseoperand(addr) if a.mode == "iPJ" then waction("SETLABEL", a.imm) else werror("bad label assignment") end end end map_op[".label_1"] = map_op[".label_2"] ------------------------------------------------------------------------------ -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]] if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", nil, 1) wputxb(align-1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end -- Spacing pseudo-opcode. map_op[".space_2"] = function(params) if not params then return "num [, filler]" end if secpos+1 > maxsecpos then wflush() end waction("SPACE", params[1]) local fill = params[2] if fill then fill = tonumber(fill) if not fill or fill < 0 or fill > 255 then werror("bad filler") end end wputxb(fill or 0) end map_op[".space_1"] = map_op[".space_2"] ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end if reg and not map_reg_valid_base[reg] then werror("bad base register `"..(map_reg_rev[reg] or reg).."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg and map_reg_rev[tp.reg] or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION") wputxb(num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpregs(out) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
lingmann/dcos
packages/adminrouter/extra/src/lib/url.lua
16
11957
-- neturl.lua - a robust url parser and builder -- https://raw.githubusercontent.com/golgote/neturl/master/lib/net/url.lua -- -- Bertrand Mansion, 2011-2013; License MIT -- Copyright (c) 2011-2013 Bertrand Mansion -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- @module neturl -- @alias M local M = {} M.version = "0.9.0" --- url options -- separator is set to `&` by default but could be anything like `&amp;amp;` or `;` -- @todo Add an option to limit the size of the argument table M.options = { separator = '&' } --- list of known and common scheme ports -- as documented in <a href="http://www.iana.org/assignments/uri-schemes.html">IANA URI scheme list</a> M.services = { acap = 674, cap = 1026, dict = 2628, ftp = 21, gopher = 70, http = 80, https = 443, iax = 4569, icap = 1344, imap = 143, ipp = 631, ldap = 389, mtqp = 1038, mupdate = 3905, news = 2009, nfs = 2049, nntp = 119, rtsp = 554, sip = 5060, snmp = 161, telnet = 23, tftp = 69, vemmi = 575, afs = 1483, jms = 5673, rsync = 873, prospero = 191, videotex = 516 } local legal = { ["-"] = true, ["_"] = true, ["."] = true, ["!"] = true, ["~"] = true, ["*"] = true, ["'"] = true, ["("] = true, [")"] = true, [":"] = true, ["@"] = true, ["&"] = true, ["="] = true, ["+"] = true, ["$"] = true, [","] = true, [";"] = true -- can be used for parameters in path } local function decode(str) local str = str:gsub('+', ' ') return (str:gsub("%%(%x%x)", function(c) return string.char(tonumber(c, 16)) end)) end local function encode(str) return (str:gsub("([^A-Za-z0-9%_%.%-%~])", function(v) return string.upper(string.format("%%%02x", string.byte(v))) end)) end -- for query values, prefer + instead of %20 for spaces local function encodeValue(str) local str = encode(str) return str:gsub('%%20', '+') end local function encodeSegment(s) local legalEncode = function(c) if legal[c] then return c end return encode(c) end return s:gsub('([^a-zA-Z0-9])', legalEncode) end --- builds the url -- @return a string representing the built url function M:build() local url = '' if self.path then local path = self.path path:gsub("([^/]+)", function (s) return encodeSegment(s) end) url = url .. tostring(path) end if self.query then local qstring = tostring(self.query) if qstring ~= "" then url = url .. '?' .. qstring end end if self.host then local authority = self.host if self.port and self.scheme and M.services[self.scheme] ~= self.port then authority = authority .. ':' .. self.port end local userinfo if self.user and self.user ~= "" then userinfo = self.user if self.password then userinfo = userinfo .. ':' .. self.password end end if userinfo and userinfo ~= "" then authority = userinfo .. '@' .. authority end if authority then if url ~= "" then url = '//' .. authority .. '/' .. url:gsub('^/+', '') else url = '//' .. authority end end end if self.scheme then url = self.scheme .. ':' .. url end if self.fragment then url = url .. '#' .. self.fragment end return url end --- builds the querystring -- @param tab The key/value parameters -- @param sep The separator to use (optional) -- @param key The parent key if the value is multi-dimensional (optional) -- @return a string representing the built querystring function M.buildQuery(tab, sep, key) local query = {} if not sep then sep = M.options.separator or '&' end local keys = {} for k in pairs(tab) do keys[#keys+1] = k end table.sort(keys) for _,name in ipairs(keys) do local value = tab[name] name = encode(tostring(name)) if key then name = string.format('%s[%s]', tostring(key), tostring(name)) end if type(value) == 'table' then query[#query+1] = M.buildQuery(value, sep, name) else local value = encodeValue(tostring(value)) if value ~= "" then query[#query+1] = string.format('%s=%s', name, value) else query[#query+1] = name end end end return table.concat(query, sep) end --- Parses the querystring to a table -- This function can parse multidimensional pairs and is mostly compatible -- with PHP usage of brackets in key names like ?param[key]=value -- @param str The querystring to parse -- @param sep The separator between key/value pairs, defaults to `&` -- @todo limit the max number of parameters with M.options.max_parameters -- @return a table representing the query key/value pairs function M.parseQuery(str, sep) if not sep then sep = M.options.separator or '&' end local values = {} for key,val in str:gmatch(string.format('([^%q=]+)(=*[^%q=]*)', sep, sep)) do local key = decode(key) local keys = {} key = key:gsub('%[([^%]]*)%]', function(v) -- extract keys between balanced brackets if string.find(v, "^-?%d+$") then v = tonumber(v) else v = decode(v) end table.insert(keys, v) return "=" end) key = key:gsub('=+.*$', "") key = key:gsub('%s', "_") -- remove spaces in parameter name val = val:gsub('^=+', "") if not values[key] then values[key] = {} end if #keys > 0 and type(values[key]) ~= 'table' then values[key] = {} elseif #keys == 0 and type(values[key]) == 'table' then values[key] = decode(val) end local t = values[key] for i,k in ipairs(keys) do if type(t) ~= 'table' then t = {} end if k == "" then k = #t+1 end if not t[k] then t[k] = {} end if i == #keys then t[k] = decode(val) end t = t[k] end end setmetatable(values, { __tostring = M.buildQuery }) return values end --- set the url query -- @param query Can be a string to parse or a table of key/value pairs -- @return a table representing the query key/value pairs function M:setQuery(query) local query = query if type(query) == 'table' then query = M.buildQuery(query) end self.query = M.parseQuery(query) return query end --- set the authority part of the url -- The authority is parsed to find the user, password, port and host if available. -- @param authority The string representing the authority -- @return a string with what remains after the authority was parsed function M:setAuthority(authority) self.authority = authority self.port = nil self.host = nil self.userinfo = nil self.user = nil self.password = nil authority = authority:gsub('^([^@]*)@', function(v) self.userinfo = v return '' end) authority = authority:gsub("^%[[^%]]+%]", function(v) -- ipv6 self.host = v return '' end) authority = authority:gsub(':([^:]*)$', function(v) self.port = tonumber(v) return '' end) if authority ~= '' and not self.host then self.host = authority:lower() end if self.userinfo then local userinfo = self.userinfo userinfo = userinfo:gsub(':([^:]*)$', function(v) self.password = v return '' end) self.user = userinfo end return authority end --- Parse the url into the designated parts. -- Depending on the url, the following parts can be available: -- scheme, userinfo, user, password, authority, host, port, path, -- query, fragment -- @param url Url string -- @return a table with the different parts and a few other functions function M.parse(url) local comp = {} M.setAuthority(comp, "") M.setQuery(comp, "") local url = tostring(url or '') url = url:gsub('#(.*)$', function(v) comp.fragment = v return '' end) url =url:gsub('^([%w][%w%+%-%.]*)%:', function(v) comp.scheme = v:lower() return '' end) url = url:gsub('%?(.*)', function(v) M.setQuery(comp, v) return '' end) url = url:gsub('^//([^/]*)', function(v) M.setAuthority(comp, v) return '' end) comp.path = decode(url) setmetatable(comp, { __index = M, __tostring = M.build} ) return comp end --- removes dots and slashes in urls when possible -- This function will also remove multiple slashes -- @param path The string representing the path to clean -- @return a string of the path without unnecessary dots and segments function M.removeDotSegments(path) local fields = {} if string.len(path) == 0 then return "" end local startslash = false local endslash = false if string.sub(path, 1, 1) == "/" then startslash = true end if (string.len(path) > 1 or startslash == false) and string.sub(path, -1) == "/" then endslash = true end path:gsub('[^/]+', function(c) table.insert(fields, c) end) local new = {} local j = 0 for i,c in ipairs(fields) do if c == '..' then if j > 0 then j = j - 1 end elseif c ~= "." then j = j + 1 new[j] = c end end local ret = "" if #new > 0 and j > 0 then ret = table.concat(new, '/', 1, j) else ret = "" end if startslash then ret = '/'..ret end if endslash then ret = ret..'/' end return ret end local function absolutePath(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return '/' .. string.gsub(relative_path, '^[%./]+', '') end local path = base_path if relative_path ~= "" then path = '/'..path:gsub("[^/]*$", "") end path = path .. relative_path path = path:gsub("([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(path, "([^/]*/%.%.?)$", function (s) if s ~= "../.." then return "" else return s end end) local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, '^/?%.%./', '') end return '/' .. path end --- builds a new url by using the one given as parameter and resolving paths -- @param other A string or a table representing a url -- @return a new url table function M:resolve(other) if type(self) == "string" then self = M.parse(self) end if type(other) == "string" then other = M.parse(other) end if other.scheme then return other else other.scheme = self.scheme if not other.authority or other.authority == "" then other:setAuthority(self.authority) if not other.path or other.path == "" then other.path = self.path local query = other.query if not query or not next(query) then other.query = self.query end else other.path = absolutePath(self.path, other.path) end end return other end end --- normalize a url path following some common normalization rules -- described on <a href="http://en.wikipedia.org/wiki/URL_normalization">The URL normalization page of Wikipedia</a> -- @return the normalized path function M:normalize() if type(self) == 'string' then self = M.parse(self) end if self.path then local path = self.path path = absolutePath(path, "") -- normalize multiple slashes path = string.gsub(path, "//+", "/") self.path = path end return self end return M
apache-2.0
Scavenge/darkstar
scripts/zones/Dynamis-Windurst/mobs/Tzee_Xicu_Idol.lua
22
1314
----------------------------------- -- Area: Dynamis Windurst -- MOB: Tzee Xicu Idol ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/dynamis"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) SpawnMob(17543597):updateEnmity(target); -- 122 SpawnMob(17543598):updateEnmity(target); -- 123 SpawnMob(17543599):updateEnmity(target); -- 124 SpawnMob(17543600):updateEnmity(target); -- 125 SpawnMob(17543170):updateEnmity(target); -- Maa Febi the Steadfast SpawnMob(17543171):updateEnmity(target); -- Muu Febi the Steadfast end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) if (alreadyReceived(player,8) == false) then addDynamisList(player,128); player:addTitle(DYNAMISWINDURST_INTERLOPER); -- Add title local npc = GetNPCByID(17543480); -- Spawn ??? npc:setPos(mob:getXPos(),mob:getYPos(),mob:getZPos()); npc:setStatus(0); player:launchDynamisSecondPart(); -- Spawn dynamis second part end end;
gpl-3.0
Yuijam/forsync
utils.lua
1
11314
require(".const") local Card = require('.card') local M = {} --所有的find方法,数据结构是{name = CARD_TYPE.XXX, {}, {}} --里面保存的是索引,而不是牌面值 function M:findDan(cards) if #cards < 1 then return nil end local dan = {name = CARD_TYPE.DAN} local preCard = -1 for i, v in ipairs(cards) do if v ~= preCard then table.insert(dan, {i}) preCard = v end end if #dan == 0 then return nil end return dan end function M:findDui(cards) if #cards < 2 then return nil end local dui = {name = CARD_TYPE.DUI} local i = 1 local lastDuiVal = -1 while(i <= #cards-1) do local card = cards[i] if card == cards[i+1] and card ~= lastDuiVal then local group = {i, i+1} table.insert(dui, group) i = i + 2 lastDuiVal = card else i = i + 1 end end if #dui == 0 then return nil end return dui end function M:findSan(cards) if #cards < 3 then return nil end local san = {name = CARD_TYPE.SAN} local i = 1 while(i < #cards-2) do local card = cards[i] if card == cards[i+1] and card == cards[i+2] then local group = {i, i+1, i+2} table.insert(san, group) i = i + 3 else i = i + 1 end end if #san == 0 then return nil end return san end function M:findSanDaiYi(cards) if #cards < 4 then return nil end local san = self:findSan(cards) --{{1,2,3}, {7,8,9}} local sanDaiYi = {} for _, v in ipairs(san) do for i, c in ipairs(cards) do if c ~= cards[v[1]] then local tmp = self:backUpTable(v) table.insert(tmp, i) table.insert(sanDaiYi, tmp) end end end if #sanDaiYi == nil then return nil end return sanDaiYi end function M:findSiDaiEr(cards) end function M:findLianDui(cards) --连对至少要有6张牌 if #cards < 6 then return nil end local dui = self:findDui(cards) if not dui then return nil end local lianDui = {name = CARD_TYPE.LIAN_DUI} for i=1, #dui-2 do local startDuiIdx = dui[i][1] local startDuiVal = cards[startDuiIdx] if startDuiVal == cards[dui[i+1][1]]-1 and startDuiVal == cards[dui[i+2][1]]-2 then local tmp = {dui[i], dui[i+1], dui[i+2]} table.insert(lianDui, tmp) local lastDuiVal = cards[dui[i+2][1]] for j=i+3, #dui do local dIdx = dui[j][1] local dVal = cards[dui[j][1]] if dVal == lastDuiVal+1 then lastDuiVal = cards[dui[j][1]] local backUpTmp = self:backUpTable(tmp) table.insert(backUpTmp, dui[j]) table.insert(lianDui, backUpTmp) end end end end if #lianDui == 0 then return nil end return lianDui end function M:findNumAddOne(x, cards, idx) for i = idx+1, idx+4 do if cards[i] == x+1 then return i end end return false end function M:findShun(cards) if #cards < 5 then return nil end local shun = {name = CARD_TYPE.SHUN} local preCard = -1 for i = 1, #cards do local card = cards[i] if card ~= preCard then preCard = card self:findShunZiStartAtX(card, shun, cards, i) end end if #shun == 0 then return nil end return shun end function M:findSanLian(cards) local san = self:findSan(cards) local SanLian = {} for i=1, #san-1 do local startIdx = san[i][1] local startVal = cards[startIdx] local preVal = startVal local group = san[i] for j=i+1, #san do if preVal == cards[san[j][1]] - 1 then preVal = cards[san[j][1]] local g = self:backUpTable(group) for _, v in ipairs(san[j]) do table.insert(g, v) end table.insert(SanLian, g) group = g else break end end end if #SanLian == 0 then return nil end return SanLian end function M:findFeiJi(cards) if #cards < 8 then return nil end local SanLian = self:findSanLian(cards) local FeiJi = {name = CARD_TYPE.FEI_JI} for k=1, #SanLian do local group = SanLian[k] for i=1, #cards-1 do for j=i+1, #cards do if (i<group[1] or i>group[#group]) and (j<group[1] or j>group[#group]) then --将索引不在连对范围内的添加进来 local g = self:backUpTable(group) table.insert(g, i) table.insert(g, j) table.insert(FeiJi, g) end end end end if #FeiJi == 0 then return nil end return FeiJi end function M:backUpTable(t) local t1 = {} for k, v in pairs(t) do local tmp = v if type(v) == 'table' then tmp = self:backUpTable(v) end t1[k] = tmp end return t1 end function M:findShunZiStartAtX(x, shunGroup, cards, idx) local idxs = {idx} for i = x, x+3 do local idx = self:findNumAddOne(i, cards, idxs[#idxs]) if idx then table.insert(idxs, idx) else return false end end if #idxs ~= 5 then error('shun group size is not 5') end --测试没问题可以删掉这句 table.insert(shunGroup, self:backUpTable(idxs)) for i = x+4, x+10 do local idx = self:findNumAddOne(i, cards, idxs[#idxs]) if idx then table.insert(idxs, idx) table.insert(shunGroup, self:backUpTable(idxs)) else break end end end function M:findZha(cards) if #cards < 4 then return nil end local four = {name = CARD_TYPE.ZHA} local i = 1 while(i < #cards-3) do local card = cards[i] if card == cards[i+1] and card == cards[i+2] and card == cards[i+3] then local group = {i, i+1, i+2, i+3} table.insert(four, group) i = i + 4 else i = i + 1 end end if #four == 0 then return nil end return four end function M:findWangZha(cards) if #cards < 2 then return nil end local WangZha = {name = CARD_TYPE.WANG_ZHA} if cards[#cards] == 19 and cards[#cards-1] == 18 then table.insert(WangZha, #cards-1) table.insert(WangZha, #cards) end if #WangZha == 0 then return nil end return WangZha end function M:getAllTypes() return {CARD_TYPE.DAN, CARD_TYPE.DUI, CARD_TYPE.SAN_DAI_YI , CARD_TYPE.SAN, CARD_TYPE.SI_DAI_ER, CARD_TYPE.ZHA, CARD_TYPE.LIAN_DUI , CARD_TYPE.SHUN, CARD_TYPE.WANG_ZHA} end function M:getOutCartTypes(tableDB, user) local tableCard = tableDB:getTableCard() --当牌桌上的牌的是我自己出的那张的时候说明绕了一圈没人打得起 --或者游戏刚刚开始的时候 --这两种情况可以出的牌就是所有种类 if tableDB.gameStatus == GAME_STATUS.START or tableCard.owner.name == user.name then return self:getAllTypes() end local outCardTypes = {} --当不是炸的时候就可以出炸弹或者和当前牌对应的牌的种类 --如果是炸弹就只能出炸弹 --如果是王炸就返回一个空的table if tableCard.typeCode ~= CARD_TYPE.ZHA or tableCard.typeCode ~= CARD_TYPE.WANG_ZHA then table.insert(outCardTypes, tableCard.typeCode) table.insert(outCardTypes, CARD_TYPE.ZHA) table.insert(outCardTypes, CARD_TYPE.WANG_ZHA) elseif tableCard.typeCode == CARD_TYPE.ZHA then table.insert(outCardTypes, CARD_TYPE.ZHA) table.insert(outCardTypes, CARD_TYPE.WANG_ZHA) end return outCardTypes end function M:findCardChoices(tableDB, user) if #user.cards == 4 and user.name == 'p2' then print('') end --先根据table card来判断能打哪些类型牌 local types = self:getOutCartTypes(tableDB, user) --{CARD_TYPE.DUI, CARD_TYPE.ZHA, CARD_TYPE.WANG_ZHA} local outCardChoices = {} local cards = user.cards --先找到所有要找的类型 for _, v in pairs(types) do if v == CARD_TYPE.DAN then table.insert(outCardChoices, self:findDan(cards)) elseif v == CARD_TYPE.DUI then table.insert(outCardChoices, self:findDui(cards)) elseif v == CARD_TYPE.SAN then table.insert(outCardChoices, self:findSan(cards)) elseif v == CARD_TYPE.SAN_DAY_YI then table.insert(outCardChoices, self:findSanDaiYi(cards)) elseif v == CARD_TYPE.SHUN then table.insert(outCardChoices, self:findShun(cards)) elseif v == CARD_TYPE.LIAN_DUI then table.insert(outCardChoices, self:findLianDui(cards)) -- elseif v == CARD_TYPE.SI_DAI_ER then table.insert(outCardChoices, self:findSiDaiEr(cards)) elseif v == CARD_TYPE.ZHA then table.insert(outCardChoices, self:findZha(cards)) elseif v == CARD_TYPE.WANG_ZHA then table.insert(outCardChoices, self:findWangZha(cards)) end end --outCardChoices = {{name = CARD_TYPE.PASS}, {name = CARD_TYPE.DUI,{1,2},{3,4}},{name = CARD_TYPE.ZHA, {5,6,7,8}}, {name = CARD_TYPE.WANG_ZHA, {9,10}}} --过滤掉比tableCard小的牌 local tableCard = tableDB:getTableCard() local tableCardType = tableCard.typeCode --tableCard不可能是PASS,所以不用是考虑PASS --自己随意出牌的时候,就不用继续过滤,直接return if tableDB.gameStatus == GAME_STATUS.START or tableCard.owner.name == user.name then return outCardChoices end for i = 1, #outCardChoices do local choice = outCardChoices[i] local choiceType = choice.name --单,对子,三个,三带一,四代二,炸 这几种只要比较第一个元素就知道大小了 if tableCardType >= CARD_TYPE.DAN and tableCardType < CARD_TYPE.LIAN_DUI and choiceType == tableCardType then for k = #choice, 1, -1 do -- k是个table,里面装了这个对子 if cards[choice[k][1]] <= tableCard.value[1] then table.remove(choice, k) end end end --连队和顺子就要比较长度以及第一个数 if (tableCardType == CARD_TYPE.LIAN_DUI or tableCardType == CARD_TYPE.SHUN) and choiceType == tableCardType then for k = #choice, 1, -1 do if #choice[k] ~= #tableCard.value or cards[choice[k][1]] <= tableCard.value[1] then table.remove(choice, k) end end end end return outCardChoices end function M:createTableCard(tableDB, card, user, type) local tableCard = {} tableCard.cardUser = user tableCard.type = type tableCard.value = {} for i, v in ipairs(card) do tableCard.value[i] = user.cards[v] end return tableCard end function M:parseCardIdx(user, cardsIdx, typeCode) -- cardsIdx是一个装满了idx的table,这里将idx转换成一个card local cards = user.cards local value = {} for _, idx in ipairs(cardsIdx) do table.insert(value, cards[idx]) end local card = Card:new(typeCode, value, user) return card end return M
apache-2.0
Scavenge/darkstar
scripts/zones/Southern_San_dOria/npcs/Nokkhi_Jinjahl.lua
9
13235
----------------------------------- -- Area: Southern San d'Oria -- NPC: Nokkhi Jinjahl -- Type: Travelling Merchant NPC / NPC Quiver Maker / San d'Oria 1st Place -- @zone 230 -- @pos 24.829 0.978 -13.110 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); local carnation = trade:getItemQty(948) ----------------ARROWS---------------------------- local antlion = (trade:getItemQty(19195) / 99) local beetle = (trade:getItemQty(18154) / 99) local demon = (trade:getItemQty(18159) / 99) local gargou = (trade:getItemQty(19800) / 99) local horn = (trade:getItemQty(18156) / 99) local irona = (trade:getItemQty(17320) / 99) local kabura = (trade:getItemQty(17325) / 99) local ruszor = (trade:getItemQty(19182) / 99) local scorpion = (trade:getItemQty(18155) / 99) local silvera = (trade:getItemQty(17321) / 99) local sleepa = (trade:getItemQty(18158) / 99) ----------------BOLTS----------------------------- local acid = (trade:getItemQty(18148) / 99) local adamana = (trade:getItemQty(19801) / 99) local blind = (trade:getItemQty(18150) / 99) local bloody = (trade:getItemQty(18151) / 99) local darka = (trade:getItemQty(19183) / 99) local darkling = (trade:getItemQty(19196) / 99) local darksteel = (trade:getItemQty(17338) / 99) local fusion = (trade:getItemQty(19197) / 99) local holy = (trade:getItemQty(18153) / 99) local mythril = (trade:getItemQty(17337) / 99) local sleepb = (trade:getItemQty(18149) / 99) local venom = (trade:getItemQty(18152) / 99) ----------------BULLETS--------------------------- local adamanb = (trade:getItemQty(19803) / 99) local bullet = (trade:getItemQty(17340) / 99) local bronze = (trade:getItemQty(17343) / 99) local darkb = (trade:getItemQty(19184) / 99) local dweomer = (trade:getItemQty(19198) / 99) local ironb = (trade:getItemQty(17312) / 99) local oberons = (trade:getItemQty(19199) / 99) local orichalcum = (trade:getItemQty(19802) / 99) local silverb = (trade:getItemQty(17341) / 99) local steel = (trade:getItemQty(18723) / 99) local spartan = (trade:getItemQty(18160) / 99) ----------------CARDS----------------------------- local fire = (trade:getItemQty(2176) / 99) local ice = (trade:getItemQty(2177) / 99) local wind = (trade:getItemQty(2178) / 99) local earth = (trade:getItemQty(2179) / 99) local thunder = (trade:getItemQty(2180) / 99) local water = (trade:getItemQty(2181) / 99) local light = (trade:getItemQty(2182) / 99) local dark = (trade:getItemQty(2183) / 99) ----------------------------------------------------- local quiver = (antlion + beetle + demon + gargou + horn + irona + kabura + ruszor + scorpion + silvera + sleepa + acid + adamana + blind + bloody + darka + darkling + darksteel + fusion + holy + mythril + sleepb + venom + adamanb + bullet + bronze + darkb + dweomer + ironb + oberons + orichalcum + silverb + steel + spartan + fire + ice + wind + earth + thunder + water + light + dark) if (((quiver * 99) + carnation) == count) then if ((quiver == math.floor(quiver)) and (quiver == carnation) and (player:getFreeSlotsCount() >= carnation)) then player:tradeComplete(); ----------------ARROWS---------------------------- if (antlion > 0) then player:addItem(5819,antlion); player:messageSpecial(ITEM_OBTAINED,5819); end if (beetle > 0) then player:addItem(4221,beetle); player:messageSpecial(ITEM_OBTAINED,4221); end if (demon > 0) then player:addItem(4224,demon); player:messageSpecial(ITEM_OBTAINED,4224); end if (gargou > 0) then player:addItem(5912,gargouille); player:messageSpecial(ITEM_OBTAINED,5912); end if (horn > 0) then player:addItem(4222,horn); player:messageSpecial(ITEM_OBTAINED,4222); end if (irona > 0) then player:addItem(4225,irona); player:messageSpecial(ITEM_OBTAINED,4225); end if (kabura > 0) then player:addItem(5332,kabura); player:messageSpecial(ITEM_OBTAINED,5332); end if (ruszor > 0) then player:addItem(5871,ruszor); player:messageSpecial(ITEM_OBTAINED,5871); end if (scorpion > 0) then player:addItem(4223,scorpion); player:messageSpecial(ITEM_OBTAINED,4223); end if (silvera > 0) then player:addItem(4226,silvera); player:messageSpecial(ITEM_OBTAINED,4226); end if (sleepa > 0) then player:addItem(5333,sleepa); player:messageSpecial(ITEM_OBTAINED,5333); end ----------------BOLTS----------------------------- if (acid > 0) then player:addItem(5335,acid); player:messageSpecial(ITEM_OBTAINED,5335); end if (adamana > 0) then player:addItem(5913,adamana); player:messageSpecial(ITEM_OBTAINED,5913); end if (blind > 0) then player:addItem(5334,blind); player:messageSpecial(ITEM_OBTAINED,5334); end if (bloody > 0) then player:addItem(5339,bloody); player:messageSpecial(ITEM_OBTAINED,5339); end if (darka > 0) then player:addItem(5872,darka); player:messageSpecial(ITEM_OBTAINED,5872); end if (darkling > 0) then player:addItem(5820,darkling); player:messageSpecial(ITEM_OBTAINED,5820); end if (darksteel > 0) then player:addItem(4229,darksteel); player:messageSpecial(ITEM_OBTAINED,4229); end if (fusion > 0) then player:addItem(5821,fusion); player:messageSpecial(ITEM_OBTAINED,5821); end if (holy > 0) then player:addItem(5336,holy); player:messageSpecial(ITEM_OBTAINED,5336); end if (mythril > 0) then player:addItem(4228,mythril); player:messageSpecial(ITEM_OBTAINED,4228); end if (sleepb > 0) then player:addItem(5337,sleepb); player:messageSpecial(ITEM_OBTAINED,5337); end if (venom > 0) then player:addItem(5338,venom); player:messageSpecial(ITEM_OBTAINED,5338); end ----------------BULLETS--------------------------- if (adamanb > 0) then player:addItem(5915,adamanb); player:messageSpecial(ITEM_OBTAINED,5915); end if (bullet > 0) then player:addItem(5363,bullet); player:messageSpecial(ITEM_OBTAINED,5363); end if (bronze > 0) then player:addItem(5359,bronze); player:messageSpecial(ITEM_OBTAINED,5359); end if (darkb > 0) then player:addItem(5873,darkb); player:messageSpecial(ITEM_OBTAINED,5873); end if (dweomer > 0) then player:addItem(5822,dweomer); player:messageSpecial(ITEM_OBTAINED,5822); end if (ironb > 0) then player:addItem(5353,ironb); player:messageSpecial(ITEM_OBTAINED,5353); end if (oberons > 0) then player:addItem(5823,oberons); player:messageSpecial(ITEM_OBTAINED,5823); end if (orichalcum > 0) then player:addItem(5914,orichalcum); player:messageSpecial(ITEM_OBTAINED,5914); end if (silverb > 0) then player:addItem(5340,silverb); player:messageSpecial(ITEM_OBTAINED,5340); end if (steel > 0) then player:addItem(5416,steel); player:messageSpecial(ITEM_OBTAINED,5416); end if (spartan > 0) then player:addItem(5341,spartan); player:messageSpecial(ITEM_OBTAINED,5341); end ----------------CARDS----------------------------- if (fire > 0) then player:addItem(5402,fire); player:messageSpecial(ITEM_OBTAINED,5402); end if (ice > 0) then player:addItem(5403,ice); player:messageSpecial(ITEM_OBTAINED,5403); end if (wind > 0) then player:addItem(5404,wind); player:messageSpecial(ITEM_OBTAINED,5404); end if (earth > 0) then player:addItem(5405,earth); player:messageSpecial(ITEM_OBTAINED,5405); end if (thunder > 0) then player:addItem(5406,thunder); player:messageSpecial(ITEM_OBTAINED,5406); end if (water > 0) then player:addItem(5407,water); player:messageSpecial(ITEM_OBTAINED,5407); end if (light > 0) then player:addItem(5408,light); player:messageSpecial(ITEM_OBTAINED,5408); end if (dark > 0) then player:addItem(5409,dark); player:messageSpecial(ITEM_OBTAINED,5409); end end end -- 948 - carnation -- SINGLE -- ARROWS---------------- STACK -- 19195 - antlion arrow - 5819 -- 18154 - beetle arrow - 4221 -- 18159 - demon arrow - 4224 -- 19800 - gargouille arrow - 5912 -- 18156 - horn arrow - 4222 -- 17320 - iron arrow - 4225 -- 17325 - kabura arrow - 5332 -- 19182 - ruszor arrow - 5871 -- 18155 - scorpion arrow - 4223 -- 17321 - silver arrow - 4226 -- 18158 - sleep arrow - 5333 ---------- BOLTS ----------------------- -- 18148 - acid bolt - 5335 -- 19801 - adaman bolt - 5913 -- 18150 - blind bolt - 5334 -- 18151 - bloody bolt - 5339 -- 19183 - dark adaman bolt - 5872 -- 19196 - darkling bolt - 5820 -- 17338 - darksteel bolt - 4229 -- 19197 - fusion bolt - 5821 -- 18153 - holy bolt - 5336 -- 17337 - mythril bolt - 4228 -- 18149 - sleep bolt - 5337 -- 18152 - venom bolt - 5338 ---------- BULLETS --------------------- -- 19803 - adaman bullet - 5915 -- 17340 - bullet - 5363 -- 17343 - bronze bullet - 5359 -- 19184 - dark adaman bullet - 5873 -- 19198 - dweomer bullet - 5822 -- 17312 - iron bullet - 5353 -- 19199 - oberon's bullet - 5823 -- 19802 - orichalcum bullet - 5914 -- 17341 - silver bullet - 5340 -- 18723 - steel bullet - 5416 -- 18160 - spartan bullet - 5341 ---------- CARDS ----------------------- -- 2176 - fire card - 5402 -- 2177 - ice card - 5403 -- 2178 - wind card - 5404 -- 2179 - earth card - 5405 -- 2180 - thunder card - 5406 -- 2181 - water card - 5407 -- 2182 - light card - 5408 -- 2183 - dark card - 5409 -------------------------------------- end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02ab,npc:getID()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/The_Eldieme_Necropolis_[S]/npcs/Lennart.lua
14
1105
---------------------------------- -- Area: The Eldieme Necropolis [S] -- NPC: Lennart -- Type: Item Deliverer -- @pos 378.783 -36 61.805 175 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/events/harvest_festivals.lua
16
11444
--------------------------------------------------------- --------------------------------------------------------- ------------ Harvest Festivals -------------------- --------------------------------------------------------- --------------------------------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); --------------------------------------------------------- --------------------------------------------------------- function isHalloweenEnabled() local option = 0; local month = tonumber(os.date("%m")); local day = tonumber(os.date("%d")); if (month == 10 and day >= 20 or month == 11 and day == 1 or HALLOWEEN_YEAR_ROUND ~= 0) then -- According to wiki Harvest Fest is Oct 20 - Nov 1. if (HALLOWEEN_2005 == 1) then option = 1; elseif (HALLOWEEN_2008 == 1) then option = 2; elseif (HALLOWEEN_2009 == 1) then option = 3; elseif (HALLOWEEN_2010 == 1) then option = 4; end end return option; end; function halloweenItemsCheck(player) local headSlot = player:getEquipID(SLOT_HEAD); local mainHand = player:getEquipID(SLOT_MAIN); local reward = 0; -- Normal Quality Rewards local pumpkinHead = 13916 local pumpkinHead2 = 15176; local trickStaff = 17565; local trickStaff2 = 17587; reward_list = {pumpkinHead,pumpkinHead2,trickStaff,trickStaff2}; -- Checks for HQ Upgrade for ri = 1, #reward_list do if (headSlot == reward_list[ri] or mainHand == reward_list[ri]) then if (headSlot == pumpkinHead and player:hasItem(13917) == false) then reward = 13917; -- Horror Head elseif (headSlot == pumpkinHead2 and player:hasItem(15177) == false) then reward = 15177; -- Horror Head II elseif (mainHand == trickStaff and player:hasItem(17566) == false) then reward = 17566; -- Treat Staff elseif (mainHand == trickStaff2 and player:hasItem(17588) == false) then reward = 17588; -- Treat Staff II end return reward; end end -- Checks the possible item rewards to ensure player doesnt already have the item we are about to give them local cnt = #reward_list; while cnt ~= 0 do local picked = reward_list[math.random(1,#reward_list)]; if (player:hasItem(picked) == false) then reward = picked; cnt = 0; else table.remove(reward_list,picked); cnt = cnt - 1; end return reward; end; end; function onHalloweenTrade(player,trade,npc) local zone = player:getZoneName(); local TextIDs = "scripts/zones/" .. zone .. "/TextIDs"; package.loaded[TextIDs] = nil; require(TextIDs); local contentEnabled = isHalloweenEnabled(); local item = trade:getItemId(); ------------------- -- 2005 edition --- ------------------- if (contentEnabled == 1) then ----------------------------------- -- Treats allowed ----------------------------------- treats_table = {4510, -- Acorn Cookie 5646, -- Bloody Chocolate 4496, -- Bubble Chocolate 4397, -- Cinna-cookie 4394, -- Ginger Cookie 4495, -- Goblin Chocolate 4413, -- Apple Pie 4488, -- Jack-o'-Pie 4421, -- Melon Pie 4563, -- Pamama Tart 4446, -- Pumpkin Pie 4414, -- Rolanberry Pie 4406, -- Baked Apple 5729, -- Bavarois 5745, -- Cherry Bavarois 5653, -- Cherry Muffin 5655, -- Coffee Muffin 5718, -- Cream Puff 5144, -- Crimson Jelly 5681, -- Cupid Chocolate 5672, -- Dried Berry 5567, -- Dried Date 4556, -- Icecap Rolanberry 5614, -- Konigskuchen 5230, -- Love Chocolate 4502, -- Marron Glace 4393, -- Orange Kuchen 5147, -- Snoll Gelato 4270, -- Sweet Rice Cake 5645, -- Witch Nougat 5552, -- Black Pudding --safe 5550, -- Buche au Chocolat -- safe @ 43 items 5616, -- Lebkuchen House --breaks 5633, -- Chocolate Cake 5542, -- Gateau aux Fraises 5572, -- Irmik Helvasi 5625, -- Maple Cake 5559, -- Mille Feuille 5557, -- Mont Blanc 5629, -- Orange Cake 5631, -- Pumpkin Cake 5577, -- Sutlac 5627}; -- Yogurt Cake for itemInList = 1, #treats_table do if (item == treats_table[itemInList]) then local itemReward = halloweenItemsCheck(player); local varName = "harvestFestTreats"; local harvestFestTreats; if (itemInList < 32) then -- The size of the list is too big for int 32 used that stores the bit mask, as such there are two lists harvestFestTreats = player:getVar(varName); else varName = "harvestFestTreats2"; harvestFestTreats = player:getVar(varName); -- this is the second list itemInList = itemInList - 32; end local AlreadyTradedChk = player:getMaskBit(harvestFestTreats,itemInList); if (itemReward ~= 0 and player:getFreeSlotsCount() >= 1 and math.random(1,3) < 2) then -- Math.random added so you have 33% chance on getting item player:messageSpecial(HERE_TAKE_THIS); player:addItem(itemReward); player:messageSpecial(ITEM_OBTAINED,itemReward); elseif (player:canUseCostume() and AlreadyTradedChk == false) then -- Other neat looking halloween type costumes -- two dragon skins: @420/421 -- @422 dancing weapon -- @ 433/432 golem -- 265 dark eye, 266 Giant version -- 290 dark bombs -- 301 dark mandy -- 313 black spiders -- 488 gob -- 531 - 548 shade -- 564/579 skele -- Possible costume values: Yagudo = math.random(580,607); Quadav = math.random(644,671); Shade = math.random(535,538); Orc = math.random(612,639); Ghost = 368; Hound = 365; Skeleton = 564; Dark_Stalker = math.random(531,534); halloween_costume_list = {Quadav,Orc,Yagudo,Shade,Ghost,Hound,Skeleton,Dark_Stalker}; local costumePicked = halloween_costume_list[math.random(1,#halloween_costume_list)]; -- will randomly pick one of the costumes in the list player:addStatusEffect(EFFECT_COSTUME,costumePicked,0,3600); -- pitchForkCostumeList defines the special costumes per zone that can trigger the pitch fork requirement -- zone, costumeID pitchForkCostumeList = {234,Shade,Skeleton, -- Bastok mines 235,Hound,Ghost, -- Bastok Markets 230,Ghost,Skeleton, -- Southern Sandoria 231,Hound,Skeleton, -- Northern Sandoria 241,Ghost,Shade, -- Windurst Woods 238,Shade,Hound}; -- Windurst Woods for zi = 1, #pitchForkCostumeList, 3 do if (zone == pitchForkCostumeList[zi] and (costumePicked == pitchForkCostumeList[zi + 1] or zone == pitchForkCostumeList[zi] and costumePicked == pitchForkCostumeList[zi + 2])) then -- Gives special hint for pitch fork costume player:messageSpecial(IF_YOU_WEAR_THIS); elseif (zi == 16) then player:messageSpecial(THANK_YOU_TREAT); end end else player:messageSpecial(THANK_YOU); end if (AlreadyTradedChk == false) then player:setMaskBit(harvestFestTreats,varName,itemInList,true); end player:tradeComplete(); break; end end end end; function applyHalloweenNpcCostumes(zoneid) if (isHalloweenEnabled() ~= 0) then -- npcID, skinID (skin ID can be found in mob_change_skin Sql table) local npc_costume_map = { [234] = { [17735795] = 40, -- Proud_Beard - Bastok Mines [17735742] = 41, -- Faustin - Bastok Mines [17814119] = 42, -- Aulavia - Bastok Mines [17735744] = 43, -- Mille - Bastok Mines [17735818] = 44 -- Emaliveulaux - Bastok Mines }, [235] = { [17739805] = 45 -- Olwyn - Bastok Markets }, [230] = { [17719306] = 46, -- Apairemant - Southern Sandoria [17719303] = 47, -- Machielle - Southern Sandoria [17719305] = 48, -- Phamelise - Southern Sandoria [17719493] = 49, -- Pourette - Southern Sandoria [17719304] = 50 -- Corua -- Southern Sandoria }, [231] = { [17723497] = 51, -- Attarena - Northern Sandoria [17723492] = 52, -- Antonian - Northern Sandoria [17723487] = 53 -- Vichuel - Northern Sandoria }, [241] = { [17764401] = 54, -- Kuzah_Hpirohpon - Windurst Woods [17764400] = 55, -- Meriri - Windurst Woods [17764464] = 56, -- Nhobi_Zalkia - Windurst Woods [17764465] = 57, -- Millerovieunet - Windurst Woods [17764462] = 58 -- Taraihi-Perunhi - Windurst Woods }, [238] = { [17752101] = 59, -- Ness_Rugetomal - Windurst Waters [17752098] = 60, -- Upih_Khachla - Windurst Waters [17752097] = 61, -- Ensasa - Windurst Waters [17752103] = 62, -- Ahyeekih - Windurst Waters [17752102] = 63 -- Maqu_Molpih - Windurst Waters } }; for id,skin in pairs(npc_costume_map[zoneid]) do local hfNpc = GetNPCByID(id); if (hfNpc ~= nil) then hfNpc:changeSkin(skin); end end end end;
gpl-3.0
JanRavn/google-diff-match-patch
lua/diff_match_patch_test.lua
264
39109
--[[ * Test Harness for Diff Match and Patch * * Copyright 2006 Google Inc. * http://code.google.com/p/google-diff-match-patch/ * * Based on the JavaScript implementation by Neil Fraser * Ported to Lua by Duncan Cross * * 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. --]] local dmp = require 'diff_match_patch' local DIFF_INSERT = dmp.DIFF_INSERT local DIFF_DELETE = dmp.DIFF_DELETE local DIFF_EQUAL = dmp.DIFF_EQUAL -- Utility functions. local function pretty(v) if (type(v) == 'string') then return string.format('%q', v):gsub('\\\n', '\\n') elseif (type(v) == 'table') then local str = {} local next_i = 1 for i, v in pairs(v) do if (i == next_i) then next_i = next_i + 1 str[#str + 1] = pretty(v) else str[#str + 1] = '[' .. pretty(i) .. ']=' .. pretty(v) end end return '{' .. table.concat(str, ',') .. '}' else return tostring(v) end end function assertEquals(...) local msg, expected, actual if (select('#', ...) == 2) then expected, actual = ... msg = 'Expected: \'' .. pretty(expected) .. '\' Actual: \'' .. pretty(actual) .. '\'' else msg, expected, actual = ... end assert(expected == actual, msg) end function assertTrue(...) local msg, actual if (select('#', ...) == 1) then actual = ... assertEquals(true, actual) else msg, actual = ... assertEquals(msg, true, actual) end end function assertFalse(...) local msg, actual if (select('#', ...) == 1) then actual = ... assertEquals(flase, actual) else msg, actual = ... assertEquals(msg, false, actual) end end -- If expected and actual are the equivalent, pass the test. function assertEquivalent(...) local msg, expected, actual expected, actual = ... msg = 'Expected: \'' .. pretty(expected) .. '\' Actual: \'' .. pretty(actual) .. '\'' if (_equivalent(expected, actual)) then assertEquals(msg, pretty(expected), pretty(actual)) else assertEquals(msg, expected, actual) end end -- Are a and b the equivalent? -- Recursive. function _equivalent(a, b) if (a == b) then return true end if (type(a) == 'table') and (type(b) == 'table') then for k, v in pairs(a) do if not _equivalent(v, b[k]) then return false end end for k, v in pairs(b) do if not _equivalent(v, a[k]) then return false end end return true end return false end function diff_rebuildtexts(diffs) -- Construct the two texts which made up the diff originally. local text1, text2 = {}, {} for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if (op ~= DIFF_INSERT) then text1[#text1 + 1] = data end if (op ~= DIFF_DELETE) then text2[#text2 + 1] = data end end return table.concat(text1), table.concat(text2) end -- DIFF TEST FUNCTIONS function testDiffCommonPrefix() -- Detect any common prefix. -- Null case. assertEquals(0, dmp.diff_commonPrefix('abc', 'xyz')) -- Non-null case. assertEquals(4, dmp.diff_commonPrefix('1234abcdef', '1234xyz')) -- Whole case. assertEquals(4, dmp.diff_commonPrefix('1234', '1234xyz')) end function testDiffCommonSuffix() -- Detect any common suffix. -- Null case. assertEquals(0, dmp.diff_commonSuffix('abc', 'xyz')) -- Non-null case. assertEquals(4, dmp.diff_commonSuffix('abcdef1234', 'xyz1234')) -- Whole case. assertEquals(4, dmp.diff_commonSuffix('1234', 'xyz1234')) end function testDiffCommonOverlap() -- Detect any suffix/prefix overlap. -- Null case. assertEquals(0, dmp.diff_commonOverlap('', 'abcd')); -- Whole case. assertEquals(3, dmp.diff_commonOverlap('abc', 'abcd')); -- No overlap. assertEquals(0, dmp.diff_commonOverlap('123456', 'abcd')); -- Overlap. assertEquals(3, dmp.diff_commonOverlap('123456xxx', 'xxxabcd')); --[[ -- Unicode. -- Some overly clever languages (C#) may treat ligatures as equal to their -- component letters. E.g. U+FB01 == 'fi' -- LUANOTE: No ability to handle Unicode. assertEquals(0, dmp.diff_commonOverlap('fi', '\ufb01i')); --]] end function testDiffHalfMatch() -- Detect a halfmatch. dmp.settings{Diff_Timeout = 1} -- No match. assertEquivalent({nil}, {dmp.diff_halfMatch('1234567890', 'abcdef')}) assertEquivalent({nil}, {dmp.diff_halfMatch('12345', '23')}) -- Single Match. assertEquivalent({'12', '90', 'a', 'z', '345678'}, {dmp.diff_halfMatch('1234567890', 'a345678z')}) assertEquivalent({'a', 'z', '12', '90', '345678'}, {dmp.diff_halfMatch('a345678z', '1234567890')}) assertEquivalent({'abc', 'z', '1234', '0', '56789'}, {dmp.diff_halfMatch('abc56789z', '1234567890')}) assertEquivalent({'a', 'xyz', '1', '7890', '23456'}, {dmp.diff_halfMatch('a23456xyz', '1234567890')}) -- Multiple Matches. assertEquivalent({'12123', '123121', 'a', 'z', '1234123451234'}, {dmp.diff_halfMatch('121231234123451234123121', 'a1234123451234z')}) assertEquivalent({'', '-=-=-=-=-=', 'x', '', 'x-=-=-=-=-=-=-='}, {dmp.diff_halfMatch('x-=-=-=-=-=-=-=-=-=-=-=-=', 'xx-=-=-=-=-=-=-=')}) assertEquivalent({'-=-=-=-=-=', '', '', 'y', '-=-=-=-=-=-=-=y'}, {dmp.diff_halfMatch('-=-=-=-=-=-=-=-=-=-=-=-=y', '-=-=-=-=-=-=-=yy')}) -- Non-optimal halfmatch. -- Optimal diff would be -q+x=H-i+e=lloHe+Hu=llo-Hew+y not -qHillo+x=HelloHe-w+Hulloy assertEquivalent({'qHillo', 'w', 'x', 'Hulloy', 'HelloHe'}, {dmp.diff_halfMatch('qHilloHelloHew', 'xHelloHeHulloy')}) -- Optimal no halfmatch. dmp.settings{Diff_Timeout = 0} assertEquivalent({nill}, {dmp.diff_halfMatch('qHilloHelloHew', 'xHelloHeHulloy')}) end function testDiffCleanupMerge() -- Cleanup a messy diff. -- Null case. local diffs = {} dmp.diff_cleanupMerge(diffs) assertEquivalent({}, diffs) -- No change case. diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_INSERT, 'c'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_INSERT, 'c'}}, diffs) -- Merge equalities. diffs = {{DIFF_EQUAL, 'a'}, {DIFF_EQUAL, 'b'}, {DIFF_EQUAL, 'c'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_EQUAL, 'abc'}}, diffs) -- Merge deletions. diffs = {{DIFF_DELETE, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_DELETE, 'c'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_DELETE, 'abc'}}, diffs) -- Merge insertions. diffs = {{DIFF_INSERT, 'a'}, {DIFF_INSERT, 'b'}, {DIFF_INSERT, 'c'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_INSERT, 'abc'}}, diffs) -- Merge interweave. diffs = {{DIFF_DELETE, 'a'}, {DIFF_INSERT, 'b'}, {DIFF_DELETE, 'c'}, {DIFF_INSERT, 'd'}, {DIFF_EQUAL, 'e'}, {DIFF_EQUAL, 'f'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_DELETE, 'ac'}, {DIFF_INSERT, 'bd'}, {DIFF_EQUAL, 'ef'}}, diffs) -- Prefix and suffix detection. diffs = {{DIFF_DELETE, 'a'}, {DIFF_INSERT, 'abc'}, {DIFF_DELETE, 'dc'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'd'}, {DIFF_INSERT, 'b'}, {DIFF_EQUAL, 'c'}}, diffs) -- Prefix and suffix detection with equalities. diffs = {{DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'a'}, {DIFF_INSERT, 'abc'}, {DIFF_DELETE, 'dc'}, {DIFF_EQUAL, 'y'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_EQUAL, 'xa'}, {DIFF_DELETE, 'd'}, {DIFF_INSERT, 'b'}, {DIFF_EQUAL, 'cy'}}, diffs) -- Slide edit left. diffs = {{DIFF_EQUAL, 'a'}, {DIFF_INSERT, 'ba'}, {DIFF_EQUAL, 'c'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_INSERT, 'ab'}, {DIFF_EQUAL, 'ac'}}, diffs) -- Slide edit right. diffs = {{DIFF_EQUAL, 'c'}, {DIFF_INSERT, 'ab'}, {DIFF_EQUAL, 'a'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_EQUAL, 'ca'}, {DIFF_INSERT, 'ba'}}, diffs) -- Slide edit left recursive. diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_EQUAL, 'c'}, {DIFF_DELETE, 'ac'}, {DIFF_EQUAL, 'x'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'acx'}}, diffs) -- Slide edit right recursive. diffs = {{DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'ca'}, {DIFF_EQUAL, 'c'}, {DIFF_DELETE, 'b'}, {DIFF_EQUAL, 'a'}} dmp.diff_cleanupMerge(diffs) assertEquivalent({{DIFF_EQUAL, 'xca'}, {DIFF_DELETE, 'cba'}}, diffs) end function testDiffCleanupSemanticLossless() -- Slide diffs to match logical boundaries. -- Null case. local diffs = {} dmp.diff_cleanupSemanticLossless(diffs) assertEquivalent({}, diffs) -- Blank lines. diffs = {{DIFF_EQUAL, 'AAA\r\n\r\nBBB'}, {DIFF_INSERT, '\r\nDDD\r\n\r\nBBB'}, {DIFF_EQUAL, '\r\nEEE'}} dmp.diff_cleanupSemanticLossless(diffs) assertEquivalent({{DIFF_EQUAL, 'AAA\r\n\r\n'}, {DIFF_INSERT, 'BBB\r\nDDD\r\n\r\n'}, {DIFF_EQUAL, 'BBB\r\nEEE'}}, diffs) -- Line boundaries. diffs = {{DIFF_EQUAL, 'AAA\r\nBBB'}, {DIFF_INSERT, ' DDD\r\nBBB'}, {DIFF_EQUAL, ' EEE'}} dmp.diff_cleanupSemanticLossless(diffs) assertEquivalent({{DIFF_EQUAL, 'AAA\r\n'}, {DIFF_INSERT, 'BBB DDD\r\n'}, {DIFF_EQUAL, 'BBB EEE'}}, diffs) -- Word boundaries. diffs = {{DIFF_EQUAL, 'The c'}, {DIFF_INSERT, 'ow and the c'}, {DIFF_EQUAL, 'at.'}} dmp.diff_cleanupSemanticLossless(diffs) assertEquivalent({{DIFF_EQUAL, 'The '}, {DIFF_INSERT, 'cow and the '}, {DIFF_EQUAL, 'cat.'}}, diffs) -- Alphanumeric boundaries. diffs = {{DIFF_EQUAL, 'The-c'}, {DIFF_INSERT, 'ow-and-the-c'}, {DIFF_EQUAL, 'at.'}} dmp.diff_cleanupSemanticLossless(diffs) assertEquivalent({{DIFF_EQUAL, 'The-'}, {DIFF_INSERT, 'cow-and-the-'}, {DIFF_EQUAL, 'cat.'}}, diffs) -- Hitting the start. diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'ax'}} dmp.diff_cleanupSemanticLossless(diffs) assertEquivalent({{DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'aax'}}, diffs) -- Hitting the end. diffs = {{DIFF_EQUAL, 'xa'}, {DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'a'}} dmp.diff_cleanupSemanticLossless(diffs) assertEquivalent({{DIFF_EQUAL, 'xaa'}, {DIFF_DELETE, 'a'}}, diffs) -- Sentence boundaries. diffs = {{DIFF_EQUAL, 'The xxx. The '}, {DIFF_INSERT, 'zzz. The '}, {DIFF_EQUAL, 'yyy.'}} dmp.diff_cleanupSemanticLossless(diffs) assertEquivalent({{DIFF_EQUAL, 'The xxx.'}, {DIFF_INSERT, ' The zzz.'}, {DIFF_EQUAL, ' The yyy.'}}, diffs) end function testDiffCleanupSemantic() -- Cleanup semantically trivial equalities. -- Null case. local diffs = {} dmp.diff_cleanupSemantic(diffs) assertEquivalent({}, diffs) -- No elimination #1. diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, 'cd'}, {DIFF_EQUAL, '12'}, {DIFF_DELETE, 'e'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_DELETE, 'ab'}, {DIFF_INSERT, 'cd'}, {DIFF_EQUAL, '12'}, {DIFF_DELETE, 'e'}}, diffs) -- No elimination #2. diffs = {{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'ABC'}, {DIFF_EQUAL, '1234'}, {DIFF_DELETE, 'wxyz'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'ABC'}, {DIFF_EQUAL, '1234'}, {DIFF_DELETE, 'wxyz'}}, diffs) -- Simple elimination. diffs = {{DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'b'}, {DIFF_DELETE, 'c'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'b'}}, diffs) -- Backpass elimination. diffs = {{DIFF_DELETE, 'ab'}, {DIFF_EQUAL, 'cd'}, {DIFF_DELETE, 'e'}, {DIFF_EQUAL, 'f'}, {DIFF_INSERT, 'g'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_DELETE, 'abcdef'}, {DIFF_INSERT, 'cdfg'}}, diffs) -- Multiple eliminations. diffs = {{DIFF_INSERT, '1'}, {DIFF_EQUAL, 'A'}, {DIFF_DELETE, 'B'}, {DIFF_INSERT, '2'}, {DIFF_EQUAL, '_'}, {DIFF_INSERT, '1'}, {DIFF_EQUAL, 'A'}, {DIFF_DELETE, 'B'}, {DIFF_INSERT, '2'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_DELETE, 'AB_AB'}, {DIFF_INSERT, '1A2_1A2'}}, diffs) -- Word boundaries. diffs = {{DIFF_EQUAL, 'The c'}, {DIFF_DELETE, 'ow and the c'}, {DIFF_EQUAL, 'at.'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_EQUAL, 'The '}, {DIFF_DELETE, 'cow and the '}, {DIFF_EQUAL, 'cat.'}}, diffs) -- No overlap elimination. diffs = {{DIFF_DELETE, 'abcxx'}, {DIFF_INSERT, 'xxdef'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_DELETE, 'abcxx'}, {DIFF_INSERT, 'xxdef'}}, diffs) -- Overlap elimination. diffs = {{DIFF_DELETE, 'abcxxx'}, {DIFF_INSERT, 'xxxdef'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'xxx'}, {DIFF_INSERT, 'def'}}, diffs) -- Reverse overlap elimination. diffs = {{DIFF_DELETE, 'xxxabc'}, {DIFF_INSERT, 'defxxx'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_INSERT, 'def'}, {DIFF_EQUAL, 'xxx'}, {DIFF_DELETE, 'abc'}}, diffs) -- Two overlap eliminations. diffs = {{DIFF_DELETE, 'abcd1212'}, {DIFF_INSERT, '1212efghi'}, {DIFF_EQUAL, '----'}, {DIFF_DELETE, 'A3'}, {DIFF_INSERT, '3BC'}} dmp.diff_cleanupSemantic(diffs) assertEquivalent({{DIFF_DELETE, 'abcd'}, {DIFF_EQUAL, '1212'}, {DIFF_INSERT, 'efghi'}, {DIFF_EQUAL, '----'}, {DIFF_DELETE, 'A'}, {DIFF_EQUAL, '3'}, {DIFF_INSERT, 'BC'}}, diffs) end function testDiffCleanupEfficiency() -- Cleanup operationally trivial equalities. local diffs dmp.settings{Diff_EditCost = 4} -- Null case. diffs = {} dmp.diff_cleanupEfficiency(diffs) assertEquivalent({}, diffs) -- No elimination. diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'wxyz'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}} dmp.diff_cleanupEfficiency(diffs) assertEquivalent({{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'wxyz'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}, diffs) -- Four-edit elimination. diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'xyz'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}} dmp.diff_cleanupEfficiency(diffs) assertEquivalent({ {DIFF_DELETE, 'abxyzcd'}, {DIFF_INSERT, '12xyz34'} }, diffs) -- Three-edit elimination. diffs = { {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'} } dmp.diff_cleanupEfficiency(diffs) assertEquivalent({ {DIFF_DELETE, 'xcd'}, {DIFF_INSERT, '12x34'} }, diffs) -- Backpass elimination. diffs = { {DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'xy'}, {DIFF_INSERT, '34'}, {DIFF_EQUAL, 'z'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '56'} } dmp.diff_cleanupEfficiency(diffs) assertEquivalent({ {DIFF_DELETE, 'abxyzcd'}, {DIFF_INSERT, '12xy34z56'} }, diffs) -- High cost elimination. dmp.settings{Diff_EditCost = 5} diffs = { {DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'wxyz'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'} } dmp.diff_cleanupEfficiency(diffs) assertEquivalent({ {DIFF_DELETE, 'abwxyzcd'}, {DIFF_INSERT, '12wxyz34'} }, diffs) dmp.settings{Diff_EditCost = 4} end function testDiffPrettyHtml() -- Pretty print. local diffs = { {DIFF_EQUAL, 'a\n'}, {DIFF_DELETE, '<B>b</B>'}, {DIFF_INSERT, 'c&d'} } assertEquals( '<span>a&para;<br></span>' .. '<del style="background:#ffe6e6;">&lt;B&gt;b&lt;/B&gt;' .. '</del><ins style="background:#e6ffe6;">c&amp;d</ins>', dmp.diff_prettyHtml(diffs) ) end function testDiffText() -- Compute the source and destination texts. local diffs = { {DIFF_EQUAL, 'jump'}, {DIFF_DELETE, 's'}, {DIFF_INSERT, 'ed'}, {DIFF_EQUAL, ' over '}, {DIFF_DELETE, 'the'}, {DIFF_INSERT, 'a'}, {DIFF_EQUAL, ' lazy'} } assertEquals('jumps over the lazy', dmp.diff_text1(diffs)) assertEquals('jumped over a lazy', dmp.diff_text2(diffs)) end function testDiffDelta() -- Convert a diff into delta string. local diffs = { {DIFF_EQUAL, 'jump'}, {DIFF_DELETE, 's'}, {DIFF_INSERT, 'ed'}, {DIFF_EQUAL, ' over '}, {DIFF_DELETE, 'the'}, {DIFF_INSERT, 'a'}, {DIFF_EQUAL, ' lazy'}, {DIFF_INSERT, 'old dog'} } local text1 = dmp.diff_text1(diffs) assertEquals('jumps over the lazy', text1) local delta = dmp.diff_toDelta(diffs) assertEquals('=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog', delta) -- Convert delta string into a diff. assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta)) -- Generates error (19 ~= 20). success, result = pcall(dmp.diff_fromDelta, text1 .. 'x', delta) assertEquals(false, success) -- Generates error (19 ~= 18). success, result = pcall(dmp.diff_fromDelta, string.sub(text1, 2), delta) assertEquals(false, success) -- Generates error (%c3%xy invalid Unicode). success, result = pcall(dmp.patch_fromDelta, '', '+%c3%xy') assertEquals(false, success) --[[ -- Test deltas with special characters. -- LUANOTE: No ability to handle Unicode. diffs = {{DIFF_EQUAL, '\u0680 \000 \t %'}, {DIFF_DELETE, '\u0681 \x01 \n ^'}, {DIFF_INSERT, '\u0682 \x02 \\ |'}} text1 = dmp.diff_text1(diffs) assertEquals('\u0680 \x00 \t %\u0681 \x01 \n ^', text1) delta = dmp.diff_toDelta(diffs) assertEquals('=7\t-7\t+%DA%82 %02 %5C %7C', delta) --]] -- Convert delta string into a diff. assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta)) -- Verify pool of unchanged characters. diffs = { {DIFF_INSERT, 'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # '} } local text2 = dmp.diff_text2(diffs) assertEquals( 'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # ', text2 ) delta = dmp.diff_toDelta(diffs) assertEquals( '+A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # ', delta ) -- Convert delta string into a diff. assertEquivalent(diffs, dmp.diff_fromDelta('', delta)) end function testDiffXIndex() -- Translate a location in text1 to text2. -- Translation on equality. assertEquals(6, dmp.diff_xIndex({ {DIFF_DELETE, 'a'}, {DIFF_INSERT, '1234'}, {DIFF_EQUAL, 'xyz'} }, 3)) -- Translation on deletion. assertEquals(2, dmp.diff_xIndex({ {DIFF_EQUAL, 'a'}, {DIFF_DELETE, '1234'}, {DIFF_EQUAL, 'xyz'} }, 4)) end function testDiffLevenshtein() -- Levenshtein with trailing equality. assertEquals(4, dmp.diff_levenshtein({ {DIFF_DELETE, 'abc'}, {DIFF_INSERT, '1234'}, {DIFF_EQUAL, 'xyz'} })) -- Levenshtein with leading equality. assertEquals(4, dmp.diff_levenshtein({ {DIFF_EQUAL, 'xyz'}, {DIFF_DELETE, 'abc'}, {DIFF_INSERT, '1234'} })) -- Levenshtein with middle equality. assertEquals(7, dmp.diff_levenshtein({ {DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'xyz'}, {DIFF_INSERT, '1234'} })) end function testDiffBisect() -- Normal. local a = 'cat' local b = 'map' -- Since the resulting diff hasn't been normalized, it would be ok if -- the insertion and deletion pairs are swapped. -- If the order changes, tweak this test as required. assertEquivalent({ {DIFF_DELETE, 'c'}, {DIFF_INSERT, 'm'}, {DIFF_EQUAL, 'a'}, {DIFF_DELETE, 't'}, {DIFF_INSERT, 'p'} }, dmp.diff_bisect(a, b, 2 ^ 31)) -- Timeout. assertEquivalent({ {DIFF_DELETE, 'cat'}, {DIFF_INSERT, 'map'} }, dmp.diff_bisect(a, b, 0)) end function testDiffMain() -- Perform a trivial diff. local a,b -- Null case. assertEquivalent({}, dmp.diff_main('', '', false)) -- Equality. assertEquivalent({ {DIFF_EQUAL, 'abc'} }, dmp.diff_main('abc', 'abc', false)) -- Simple insertion. assertEquivalent({ {DIFF_EQUAL, 'ab'}, {DIFF_INSERT, '123'}, {DIFF_EQUAL, 'c'} }, dmp.diff_main('abc', 'ab123c', false)) -- Simple deletion. assertEquivalent({ {DIFF_EQUAL, 'a'}, {DIFF_DELETE, '123'}, {DIFF_EQUAL, 'bc'} }, dmp.diff_main('a123bc', 'abc', false)) -- Two insertions. assertEquivalent({ {DIFF_EQUAL, 'a'}, {DIFF_INSERT, '123'}, {DIFF_EQUAL, 'b'}, {DIFF_INSERT, '456'}, {DIFF_EQUAL, 'c'} }, dmp.diff_main('abc', 'a123b456c', false)) -- Two deletions. assertEquivalent({ {DIFF_EQUAL, 'a'}, {DIFF_DELETE, '123'}, {DIFF_EQUAL, 'b'}, {DIFF_DELETE, '456'}, {DIFF_EQUAL, 'c'} }, dmp.diff_main('a123b456c', 'abc', false)) -- Perform a real diff. -- Switch off the timeout. dmp.settings{ Diff_Timeout=0 } -- Simple cases. assertEquivalent({ {DIFF_DELETE, 'a'}, {DIFF_INSERT, 'b'} }, dmp.diff_main('a', 'b', false)) assertEquivalent({ {DIFF_DELETE, 'Apple'}, {DIFF_INSERT, 'Banana'}, {DIFF_EQUAL, 's are a'}, {DIFF_INSERT, 'lso'}, {DIFF_EQUAL, ' fruit.'} }, dmp.diff_main('Apples are a fruit.', 'Bananas are also fruit.', false)) --[[ -- LUANOTE: No ability to handle Unicode. assertEquivalent({ {DIFF_DELETE, 'a'}, {DIFF_INSERT, '\u0680'}, {DIFF_EQUAL, 'x'}, {DIFF_DELETE, '\t'}, {DIFF_INSERT, '\0'} }, dmp.diff_main('ax\t', '\u0680x\0', false)) ]]-- -- Overlaps. assertEquivalent({ {DIFF_DELETE, '1'}, {DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'y'}, {DIFF_EQUAL, 'b'}, {DIFF_DELETE, '2'}, {DIFF_INSERT, 'xab'} }, dmp.diff_main('1ayb2', 'abxab', false)) assertEquivalent({ {DIFF_INSERT, 'xaxcx'}, {DIFF_EQUAL, 'abc'}, {DIFF_DELETE, 'y'} }, dmp.diff_main('abcy', 'xaxcxabc', false)) assertEquivalent({ {DIFF_DELETE, 'ABCD'}, {DIFF_EQUAL, 'a'}, {DIFF_DELETE, '='}, {DIFF_INSERT, '-'}, {DIFF_EQUAL, 'bcd'}, {DIFF_DELETE, '='}, {DIFF_INSERT, '-'}, {DIFF_EQUAL, 'efghijklmnopqrs'}, {DIFF_DELETE, 'EFGHIJKLMNOefg'} }, dmp.diff_main('ABCDa=bcd=efghijklmnopqrsEFGHIJKLMNOefg', 'a-bcd-efghijklmnopqrs', false)) -- Large equality. assertEquivalent({ {DIFF_INSERT, ' '}, {DIFF_EQUAL, 'a'}, {DIFF_INSERT, 'nd'}, {DIFF_EQUAL, ' [[Pennsylvania]]'}, {DIFF_DELETE, ' and [[New'} }, dmp.diff_main('a [[Pennsylvania]] and [[New', ' and [[Pennsylvania]]', false)) -- Timeout. dmp.settings{Diff_Timeout = 0.1} -- 100ms -- Increase the text lengths by 1024 times to ensure a timeout. a = string.rep([[ `Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe. ]], 1024) b = string.rep([[ I am the very model of a modern major general, I've information vegetable, animal, and mineral, I know the kings of England, and I quote the fights historical, From Marathon to Waterloo, in order categorical. ]], 1024) local startTime = os.clock() dmp.diff_main(a, b) local endTime = os.clock() -- Test that we took at least the timeout period. assertTrue(0.1 <= endTime - startTime) -- Test that we didn't take forever (be forgiving). -- Theoretically this test could fail very occasionally if the -- OS task swaps or locks up for a second at the wrong moment. assertTrue(0.1 * 2 > endTime - startTime) dmp.settings{Diff_Timeout = 0} -- Test the linemode speedup. -- Must be long to pass the 100 char cutoff. -- Simple line-mode. a = string.rep('1234567890\n', 13) b = string.rep('abcdefghij\n', 13) assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true)) -- Single line-mode. a = string.rep('1234567890', 13) b = string.rep('abcdefghij', 13) assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true)) -- Overlap line-mode. a = string.rep('1234567890\n', 13) b = [[ abcdefghij 1234567890 1234567890 1234567890 abcdefghij 1234567890 1234567890 1234567890 abcdefghij 1234567890 1234567890 1234567890 abcdefghij ]] local texts_linemode = diff_rebuildtexts(dmp.diff_main(a, b, true)) local texts_textmode = diff_rebuildtexts(dmp.diff_main(a, b, false)) assertEquivalent(texts_textmode, texts_linemode) -- Test null inputs. success, result = pcall(dmp.diff_main, nil, nil) assertEquals(false, success) end -- MATCH TEST FUNCTIONS function testMatchAlphabet() -- Initialise the bitmasks for Bitap. -- Unique. assertEquivalent({a=4, b=2, c=1}, dmp.match_alphabet('abc')) -- Duplicates. assertEquivalent({a=37, b=18, c=8}, dmp.match_alphabet('abcaba')) end function testMatchBitap() -- Bitap algorithm. dmp.settings{Match_Distance=100, Match_Threshold=0.5} -- Exact matches. assertEquals(6, dmp.match_bitap('abcdefghijk', 'fgh', 6)) assertEquals(6, dmp.match_bitap('abcdefghijk', 'fgh', 1)) -- Fuzzy matches. assertEquals(5, dmp.match_bitap('abcdefghijk', 'efxhi', 1)) assertEquals(3, dmp.match_bitap('abcdefghijk', 'cdefxyhijk', 6)) assertEquals(-1, dmp.match_bitap('abcdefghijk', 'bxy', 2)) -- Overflow. assertEquals(3, dmp.match_bitap('123456789xx0', '3456789x0', 3)) -- Threshold test. dmp.settings{Match_Threshold = 0.4} assertEquals(5, dmp.match_bitap('abcdefghijk', 'efxyhi', 2)) dmp.settings{Match_Threshold = 0.3} assertEquals(-1, dmp.match_bitap('abcdefghijk', 'efxyhi', 2)) dmp.settings{Match_Threshold = 0.0} assertEquals(2, dmp.match_bitap('abcdefghijk', 'bcdef', 2)) dmp.settings{Match_Threshold = 0.5} -- Multiple select. assertEquals(1, dmp.match_bitap('abcdexyzabcde', 'abccde', 4)) assertEquals(9, dmp.match_bitap('abcdexyzabcde', 'abccde', 6)) -- Distance test. dmp.settings{Match_Distance = 10} -- Strict location. assertEquals(-1, dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 25)) assertEquals(1, dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdxxefg', 2)) dmp.settings{Match_Distance = 1000} -- Loose location. assertEquals(1, dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 25)) end function testMatchMain() -- Full match. -- Shortcut matches. assertEquals(1, dmp.match_main('abcdef', 'abcdef', 1000)) assertEquals(-1, dmp.match_main('', 'abcdef', 2)) assertEquals(4, dmp.match_main('abcdef', '', 4)) assertEquals(4, dmp.match_main('abcdef', 'de', 4)) -- Beyond end match. assertEquals(4, dmp.match_main("abcdef", "defy", 5)) -- Oversized pattern. assertEquals(1, dmp.match_main("abcdef", "abcdefy", 1)) -- Complex match. assertEquals(5, dmp.match_main( 'I am the very model of a modern major general.', ' that berry ', 6 )) -- Test null inputs. success, result = pcall(dmp.match_main, nil, nil, 0) assertEquals(false, success) end -- PATCH TEST FUNCTIONS function testPatchObj() -- Patch Object. local p = dmp.new_patch_obj() p.start1 = 21 p.start2 = 22 p.length1 = 18 p.length2 = 17 p.diffs = { {DIFF_EQUAL, 'jump'}, {DIFF_DELETE, 's'}, {DIFF_INSERT, 'ed'}, {DIFF_EQUAL, ' over '}, {DIFF_DELETE, 'the'}, {DIFF_INSERT, 'a'}, {DIFF_EQUAL, '\nlaz'} } local strp = tostring(p) assertEquals( '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n', strp ) end function testPatchFromText() local strp strp = '' assertEquivalent({}, dmp.patch_fromText(strp)) strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n' assertEquals(strp, tostring(dmp.patch_fromText(strp)[1])) assertEquals( '@@ -1 +1 @@\n-a\n+b\n', tostring(dmp.patch_fromText('@@ -1 +1 @@\n-a\n+b\n')[1]) ) assertEquals( '@@ -1,3 +0,0 @@\n-abc\n', tostring(dmp.patch_fromText('@@ -1,3 +0,0 @@\n-abc\n')[1]) ) assertEquals( '@@ -0,0 +1,3 @@\n+abc\n', tostring(dmp.patch_fromText('@@ -0,0 +1,3 @@\n+abc\n')[1]) ) -- Generates error. success, result = pcall(dmp.patch_fromText, 'Bad\nPatch\n') assertEquals(false, success) end function testPatchToText() local strp, p strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n' p = dmp.patch_fromText(strp) assertEquals(strp, dmp.patch_toText(p)) strp = '@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n' .. '@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n' p = dmp.patch_fromText(strp) assertEquals(strp, dmp.patch_toText(p)) end function testPatchAddContext() local p dmp.settings{Patch_Margin = 4} p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[1] dmp.patch_addContext(p, 'The quick brown fox jumps over the lazy dog.') assertEquals( '@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n', tostring(p) ) -- Same, but not enough trailing context. p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[1] dmp.patch_addContext(p, 'The quick brown fox jumps.') assertEquals( '@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n', tostring(p) ) -- Same, but not enough leading context. p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[1] dmp.patch_addContext(p, 'The quick brown fox jumps.') assertEquals('@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n', tostring(p)) -- Same, but with ambiguity. p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[1] dmp.patch_addContext(p, 'The quick brown fox jumps. The quick brown fox crashes.') assertEquals('@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n', tostring(p)) end function testPatchMake() -- Null case. local patches = dmp.patch_make('', '') assertEquals('', dmp.patch_toText(patches)) local text1 = 'The quick brown fox jumps over the lazy dog.' local text2 = 'That quick brown fox jumped over a lazy dog.' -- Text2+Text1 inputs. local expectedPatch = '@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n' .. '@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n' -- The second patch must be "-21,17 +21,18", -- not "-22,17 +21,18" due to rolling context. patches = dmp.patch_make(text2, text1) assertEquals(expectedPatch, dmp.patch_toText(patches)) -- Text1+Text2 inputs. expectedPatch = '@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n' .. '@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n' patches = dmp.patch_make(text1, text2) assertEquals(expectedPatch, dmp.patch_toText(patches)) -- Diff input. local diffs = dmp.diff_main(text1, text2, false) patches = dmp.patch_make(diffs) assertEquals(expectedPatch, dmp.patch_toText(patches)) -- Text1+Diff inputs. patches = dmp.patch_make(text1, diffs) assertEquals(expectedPatch, dmp.patch_toText(patches)) -- Text1+Text2+Diff inputs (deprecated). patches = dmp.patch_make(text1, text2, diffs) assertEquals(expectedPatch, dmp.patch_toText(patches)) -- Character encoding. patches = dmp.patch_make('`1234567890-=[]\\;\',./', '~!@#$%^&*()_+{}|="<>?') assertEquals('@@ -1,21 +1,21 @@\n' .. '-%601234567890-=%5B%5D%5C;\',./\n' .. '+~!@#$%25%5E&*()_+%7B%7D%7C=%22%3C%3E?\n', dmp.patch_toText(patches)) -- Character decoding. diffs = { {DIFF_DELETE, '`1234567890-=[]\\;\',./'}, {DIFF_INSERT, '~!@#$%^&*()_+{}|="<>?'} } assertEquivalent(diffs, dmp.patch_fromText( '@@ -1,21 +1,21 @@' .. '\n-%601234567890-=%5B%5D%5C;\',./' .. '\n+~!@#$%25%5E&*()_+%7B%7D%7C=%22%3C%3E?\n' )[1].diffs) -- Long string with repeats. text1 = string.rep('abcdef', 100) text2 = text1 .. '123' expectedPatch = '@@ -573,28 +573,31 @@\n' .. ' cdefabcdefabcdefabcdefabcdef\n+123\n' patches = dmp.patch_make(text1, text2) assertEquals(expectedPatch, dmp.patch_toText(patches)) -- Test null inputs. success, result = pcall(dmp.patch_make, nil, nil) assertEquals(false, success) end function testPatchSplitMax() -- Assumes that dmp.Match_MaxBits is 32. local patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz01234567890', 'XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0') dmp.patch_splitMax(patches) assertEquals('@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n', dmp.patch_toText(patches)) patches = dmp.patch_make('abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz', 'abcdefuvwxyz') local oldToText = dmp.patch_toText(patches) dmp.patch_splitMax(patches) assertEquals(oldToText, dmp.patch_toText(patches)) patches = dmp.patch_make('1234567890123456789012345678901234567890123456789012345678901234567890', 'abc') dmp.patch_splitMax(patches) assertEquals('@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n', dmp.patch_toText(patches)) patches = dmp.patch_make('abcdefghij , h = 0 , t = 1 abcdefghij , h = 0 , t = 1 abcdefghij , h = 0 , t = 1', 'abcdefghij , h = 1 , t = 1 abcdefghij , h = 1 , t = 1 abcdefghij , h = 0 , t = 1') dmp.patch_splitMax(patches) assertEquals('@@ -2,32 +2,32 @@\n bcdefghij , h = \n-0\n+1\n , t = 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h = \n-0\n+1\n , t = 1 abcdef\n', dmp.patch_toText(patches)) end function testPatchAddPadding() -- Both edges full. local patches = dmp.patch_make('', 'test') assertEquals('@@ -0,0 +1,4 @@\n+test\n', dmp.patch_toText(patches)) dmp.patch_addPadding(patches) assertEquals('@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n', dmp.patch_toText(patches)) -- Both edges partial. patches = dmp.patch_make('XY', 'XtestY') assertEquals('@@ -1,2 +1,6 @@\n X\n+test\n Y\n', dmp.patch_toText(patches)) dmp.patch_addPadding(patches) assertEquals('@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n', dmp.patch_toText(patches)) -- Both edges none. patches = dmp.patch_make('XXXXYYYY', 'XXXXtestYYYY') assertEquals('@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches)) dmp.patch_addPadding(patches) assertEquals('@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches)) end function testPatchApply() local patches dmp.settings{Match_Distance = 1000} dmp.settings{Match_Threshold = 0.5} dmp.settings{Patch_DeleteThreshold = 0.5} -- Null case. patches = dmp.patch_make('', '') assertEquivalent({'Hello world.', {}}, {dmp.patch_apply(patches, 'Hello world.')}) -- Exact match. patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.', 'That quick brown fox jumped over a lazy dog.') assertEquivalent( {'That quick brown fox jumped over a lazy dog.', {true, true}}, {dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.')}) -- Partial match. assertEquivalent( {'That quick red rabbit jumped over a tired tiger.', {true, true}}, {dmp.patch_apply(patches, 'The quick red rabbit jumps over the tired tiger.')}) -- Failed match. assertEquivalent( {'I am the very model of a modern major general.', {false, false}}, {dmp.patch_apply(patches, 'I am the very model of a modern major general.')}) -- Big delete, small change. patches = dmp.patch_make( 'x1234567890123456789012345678901234567890123456789012345678901234567890y', 'xabcy') assertEquivalent({'xabcy', {true, true}}, {dmp.patch_apply(patches, 'x123456789012345678901234567890-----++++++++++-----' .. '123456789012345678901234567890y')}) -- Big delete, big change 1. patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789' .. '012345678901234567890y', 'xabcy') assertEquivalent({'xabc12345678901234567890' .. '---------------++++++++++---------------' .. '12345678901234567890y', {false, true}}, {dmp.patch_apply(patches, 'x12345678901234567890' .. '---------------++++++++++---------------' .. '12345678901234567890y' )}) -- Big delete, big change 2. dmp.settings{Patch_DeleteThreshold = 0.6} patches = dmp.patch_make( 'x1234567890123456789012345678901234567890123456789' .. '012345678901234567890y', 'xabcy' ) assertEquivalent({'xabcy', {true, true}}, {dmp.patch_apply( patches, 'x12345678901234567890---------------++++++++++---------------' .. '12345678901234567890y' )} ) dmp.settings{Patch_DeleteThreshold = 0.5} -- Compensate for failed patch. dmp.settings{Match_Threshold = 0, Match_Distance = 0} patches = dmp.patch_make( 'abcdefghijklmnopqrstuvwxyz--------------------1234567890', 'abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------' .. '1234567YYYYYYYYYY890' ) assertEquivalent({ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890', {false, true} }, {dmp.patch_apply( patches, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890' )}) dmp.settings{Match_Threshold = 0.5} dmp.settings{Match_Distance = 1000} -- No side effects. patches = dmp.patch_make('', 'test') local patchstr = dmp.patch_toText(patches) dmp.patch_apply(patches, '') assertEquals(patchstr, dmp.patch_toText(patches)) -- No side effects with major delete. patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.', 'Woof') patchstr = dmp.patch_toText(patches) dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.') assertEquals(patchstr, dmp.patch_toText(patches)) -- Edge exact match. patches = dmp.patch_make('', 'test') assertEquivalent({'test', {true}}, {dmp.patch_apply(patches, '')}) -- Near edge exact match. patches = dmp.patch_make('XY', 'XtestY') assertEquivalent({'XtestY', {true}}, {dmp.patch_apply(patches, 'XY')}) -- Edge partial match. patches = dmp.patch_make('y', 'y123') assertEquivalent({'x123', {true}}, {dmp.patch_apply(patches, 'x')}) end function runTests() local passed = 0 local failed = 0 for name, func in pairs(_G) do if (type(func) == 'function') and tostring(name):match("^test") then local success, message = pcall(func) if success then print(name .. ' Ok.') passed = passed + 1 else print('** ' .. name .. ' FAILED: ' .. tostring(message)) failed = failed + 1 end end end print('Tests passed: ' .. passed) print('Tests failed: ' .. failed) if failed ~= 0 then os.exit(1) end end runTests()
apache-2.0
Scavenge/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/_5e9.lua
14
1772
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Gate: Magical Gizmo -- Involved In Mission: The Heart of the Matter -- @pos 584 0 -660 194 ----------------------------------- package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Outer_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Check if we are on Windurst Mission 1-2 if (player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER and player:getVar("MissionStatus") == 3 and player:hasKeyItem(SOUTHEASTERN_STAR_CHARM)) then player:startEvent(0x002c); else player:messageSpecial(DOOR_FIRMLY_SHUT); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- If we just finished the cutscene for Windurst Mission 1-2 if (csid == 0x002c) then player:setVar("MissionStatus",4); player:messageSpecial(ALL_G_ORBS_ENERGIZED); -- Remove the charm that opens this door player:delKeyItem(SOUTHEASTERN_STAR_CHARM); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Renadile.lua
16
4338
----------------------------------- -- Area: Southern San d'Oria [S] -- NPC: Renadile -- Armor Storage NPC ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/armorstorage"); require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); Deposit = 0x0272; Withdrawl = 0x0273; ArraySize = #StorageArray; G1 = 0; G2 = 0; G3 = 0; G4 = 0; G5 = 0; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) for SetId = 1,ArraySize,11 do TradeCount = trade:getItemCount(); T1 = trade:hasItemQty(StorageArray[SetId + 5],1); if (T1 == true) then if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then if (TradeCount == StorageArray[SetId + 3]) then T2 = trade:hasItemQty(StorageArray[SetId + 4],1); T3 = trade:hasItemQty(StorageArray[SetId + 6],1); T4 = trade:hasItemQty(StorageArray[SetId + 7],1); T5 = trade:hasItemQty(StorageArray[SetId + 8],1); if (StorageArray[SetId + 4] == 0) then T2 = true; end; if (StorageArray[SetId + 6] == 0) then T3 = true; end; if (StorageArray[SetId + 7] == 0) then T4 = true; end; if (StorageArray[SetId + 8] == 0) then T5 = true; end; if (T2 == true and T3 == true and T4 == true and T5 == true) then player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]); player:addKeyItem(StorageArray[SetId + 10]); player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]); break; end; end; end; end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CurrGil = player:getGil(); for KeyItem = 11,ArraySize,11 do if player:hasKeyItem(StorageArray[KeyItem]) then if StorageArray[KeyItem - 9] == 1 then G1 = G1 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 2 then G2 = G2 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 3 then G3 = G3 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 4 then G4 = G4 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 6 then G5 = G5 + StorageArray[KeyItem - 8]; end; end; end; player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) if (csid == Withdrawl) then player:updateEvent(StorageArray[option * 11 - 6], StorageArray[option * 11 - 5], StorageArray[option * 11 - 4], StorageArray[option * 11 - 3], StorageArray[option * 11 - 2], StorageArray[option * 11 - 1]); end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == Withdrawl) then if (option > 0 and option <= StorageArray[ArraySize] - 10) then if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:addItem(StorageArray[option * 11 - Item],1); player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]); end; end; player:delKeyItem(StorageArray[option * 11]); player:setGil(player:getGil() - StorageArray[option * 11 - 1]); else for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]); end; end; end; end; end; if (csid == Deposit) then player:tradeComplete(); end; end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Port_San_dOria/npcs/Nazar.lua
30
1317
----------------------------------- -- Area: Port San d'Oria -- NPC: Nazar -- Type: Standard NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 3 do vHour = vHour - 6; end if ( vHour == -3) then vHour = 3; elseif ( vHour == -2) then vHour = 4; elseif ( vHour == -1) then vHour = 5; end local seconds = math.floor(2.4 * ((vHour * 60) + vMin)); player:startEvent( 0x02BF, seconds, 0, 0, 0, 0, 0, 0, 0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
devwawi/VIP-TEAM_Wawi8
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
agpl-3.0
Zero-K-Experiments/Zero-K-Experiments
lups/headers/nanoupdate.lua
13
5026
-- $Id: general.lua 3171 2008-11-06 09:06:29Z det $ --------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- -- -- file: nanoupdate.lua -- brief: shared code between all nano particle effects -- authors: jK -- last updated: Feb. 2010 -- -- Copyright (C) 2010. -- Licensed under the terms of the GNU GPL, v2 or later. -- --------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- local function GetUnitMidPos(unitID) local _,_,_, x, y, z = Spring.GetUnitPosition(unitID, true) return x, y, z end local function GetFeatureMidPos(featureID) local _,_,_, x, y, z = Spring.GetFeaturePosition(featureID, true) return x, y, z end local function GetCmdTag(unitID) local cmdTag = 0 local cmds = Spring.GetFactoryCommands(unitID,1) if (cmds) then local cmd = cmds[1] if cmd then cmdTag = cmd.tag end end if cmdTag == 0 then local cmds = Spring.GetUnitCommands(unitID,1) if (cmds) then local cmd = cmds[1] if cmd then cmdTag = cmd.tag end end end return cmdTag end function UpdateNanoParticles(self) --// UPDATE START- & FINALPOS local lastup = self._lastupdate or (thisGameFrame - 1) if (not self._dead)and(thisGameFrame - lastup >= 1) then self._lastupdate = thisGameFrame --// UPDATE STARTPOS local uid = self.unitID if Spring.ValidUnitID(uid) then self.pos = {Spring.GetUnitPiecePosDir(uid,self.unitpiece)} else if (not self._dead) then --// assigned source unit died self._dead = true return end end --// UPDATE FINALPOS local tid = self.targetID if (tid >= 0) then if (not self.isFeature) then if Spring.ValidUnitID(tid) then self.targetpos = {GetUnitMidPos(tid)} else if (not self._dead) then --// assigned target unit died self._dead = true return end end else if Spring.ValidFeatureID(tid) then self.targetpos = {GetFeatureMidPos(tid)} self.targetpos[2] = self.targetpos[2] + 25 else if (not self._dead) then --// assigned target feature died self._dead = true return end end end end local cmdTag = GetCmdTag(self.unitID) if (cmdTag == 0 or cmdTag ~= self.cmdTag) then self._dead = true return end end --// UPDATE LOS local allied = (self.allyID==LocalAllyTeamID)or(LocalAllyTeamID==Script.ALL_ACCESS_TEAM) local lastup_los = self._lastupdate_los or (thisGameFrame - 16) if (not self._lastupdate_los) or ((thisGameFrame - lastup_los > 16)and(not allied)) then self._lastupdate_los = thisGameFrame local startPos = self.pos local endPos = self.targetpos if (not endPos) then --//this just happens when the target feature/unit was already dead when the fx was created self._dead = true RemoveParticles(self.id) return end if (allied) then self.visibility = 1 else self.visibility = 0 local _,startLos = Spring.GetPositionLosState(startPos[1],startPos[2],startPos[3], LocalAllyTeamID) local _,endLos = Spring.GetPositionLosState( endPos[1], endPos[2], endPos[3], LocalAllyTeamID) if (not startLos)and(not endLos) then self.visibility = 0 elseif (startLos and endLos) then self.visibility = 1 elseif (startLos) then local dir = Vsub(endPos, startPos) local losRayTile = math.ceil(Vlength(dir)/Game.squareSize) for i=losRayTile,0,-1 do local losPos = Vadd(self.pos,Vmul(dir,i/losRayTile)) local _,los = Spring.GetPositionLosState(losPos[1],losPos[2],losPos[3], LocalAllyTeamID) if (los) then self.visibility = i/losRayTile; break end end endPos = Vadd(endPos,Vmul(dir,self.visibility-1)) self.targetpos = endPos else --//if (endLos) then local dir = Vsub(endPos, startPos) local losRayTile = math.ceil(Vlength(dir)/Game.squareSize) for i=0,losRayTile do local losPos = Vadd(self.pos,Vmul(dir,i/losRayTile)) local _,los = Spring.GetPositionLosState(losPos[1],losPos[2],losPos[3], LocalAllyTeamID) if (los) then self.visibility = -i/losRayTile; break end end startPos = Vadd(startPos,Vmul(dir,-self.visibility)) self.pos = startPos end end local dir = Vsub(endPos, startPos) local half_dir = Vmul(dir, 0.5) local length = Vlength(dir) self.dir = dir self.normdir = Vmul( dir, 1/length ) self._midpos = Vadd(startPos, half_dir) self._radius = length*0.5 + 200 end end
gpl-2.0
Scavenge/darkstar
scripts/zones/Port_Bastok/npcs/Valah_Molkot.lua
26
3641
----------------------------------- -- Area: Port Bastok -- NPC: Valah Molkot -- Starts and Finishes Quest: A Lady's Heart -- @zone 236 -- @pos 59 8 -221 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); gil = trade:getGil(); itemQuality = 0; if (trade:getItemCount() == 1 and trade:getGil() == 0) then if (trade:hasItemQty(957,1)) then -- Amaryllis itemQuality = 2; elseif (trade:hasItemQty(2554,1) or -- Asphodel trade:hasItemQty(948,1) or -- Carnation trade:hasItemQty(1120,1) or -- Casablanca trade:hasItemQty(1413,1) or -- Cattleya trade:hasItemQty(636,1) or -- Chamomile trade:hasItemQty(959,1) or -- Dahlia trade:hasItemQty(835,1) or -- Flax Flower trade:hasItemQty(956,1) or -- Lilac trade:hasItemQty(2507,1) or -- Lycopodium Flower trade:hasItemQty(958,1) or -- Marguerite trade:hasItemQty(1412,1) or -- Olive Flower trade:hasItemQty(938,1) or -- Papaka Grass trade:hasItemQty(1411,1) or -- Phalaenopsis trade:hasItemQty(949,1) or -- Rain Lily trade:hasItemQty(941,1) or -- Red Rose trade:hasItemQty(1725,1) or -- Snow Lily trade:hasItemQty(1410,1) or -- Sweet William trade:hasItemQty(950,1) or -- Tahrongi Cactus trade:hasItemQty(2960,1) or -- Water Lily trade:hasItemQty(951,1)) then -- Wijnruit itemQuality = 1; end end ALadysHeart = player:getQuestStatus(BASTOK,A_LADY_S_HEART); if (itemQuality == 2) then if (ALadysHeart == QUEST_COMPLETED) then player:startEvent(0x00a0, 0, 236, 4); else player:startEvent(0x00a0, 0, 236, 2); end elseif (itemQuality == 1) then if (ALadysHeart == QUEST_COMPLETED) then player:startEvent(0x00a0, 0, 236, 5); elseif (ALadysHeart == QUEST_ACCEPTED) then player:startEvent(0x00a0, 0, 236, 3); else player:startEvent(0x00a0, 0, 236, 1); end else player:startEvent(0x00a0, 0, 236, 0); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00a0, 0, 236, 10); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00a0 and option == 2002) then player:tradeComplete(); player:completeQuest(BASTOK,A_LADY_S_HEART); player:addFame(BASTOK,120); player:moghouseFlag(2); player:messageSpecial(MOGHOUSE_EXIT); elseif (csid == 0x00a0 and option == 1) then player:tradeComplete(); player:addQuest(BASTOK,A_LADY_S_HEART); end end;
gpl-3.0
shengnoah/hilua
bin/scaffold/nginx/handle.lua
2
2255
-- most code is from https://github.com/ostinelli/gin/blob/master/gin/cli/base_launcher.lua local function create_dirs(necessary_dirs) for _, dir in pairs(necessary_dirs) do os.execute("mkdir -p " .. dir .. " > /dev/null") end end local function create_nginx_conf(nginx_conf_file_path, nginx_conf_content) local fw = io.open(nginx_conf_file_path, "w") fw:write(nginx_conf_content) fw:close() end local function remove_nginx_conf(nginx_conf_file_path) os.remove(nginx_conf_file_path) end local function nginx_command(env, nginx_conf_file_path, nginx_signal) local env_cmd = "" if env ~= nil then env_cmd = "-g \"env FW_ENV=" .. env .. ";\"" end local cmd = "nginx " .. nginx_signal .. " " .. env_cmd .. " -p `pwd`/ -c " .. nginx_conf_file_path print("execute: " .. cmd) return os.execute(cmd) end local function start_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '') end local function stop_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '-s stop') end local function reload_nginx(env, nginx_conf_file_path) return nginx_command(env, nginx_conf_file_path, '-s reload') end local NginxHandle = {} NginxHandle.__index = NginxHandle function NginxHandle.new(necessary_dirs, nginx_conf_content, nginx_conf_file_path) local instance = { nginx_conf_content = nginx_conf_content, nginx_conf_file_path = nginx_conf_file_path, necessary_dirs = necessary_dirs } setmetatable(instance, NginxHandle) return instance end function NginxHandle:start(env) create_dirs(self.necessary_dirs) -- create_nginx_conf(self.nginx_conf_file_path, self.nginx_conf_content) return start_nginx(env, self.nginx_conf_file_path) end function NginxHandle:stop(env) local result = stop_nginx(env, self.nginx_conf_file_path) -- remove_nginx_conf(self.nginx_conf_file_path) return result end function NginxHandle:reload(env) -- remove_nginx_conf(self.nginx_conf_file_path) create_dirs(self.necessary_dirs) -- create_nginx_conf(self.nginx_conf_file_path, self.nginx_conf_content) return reload_nginx(env, self.nginx_conf_file_path) end return NginxHandle
bsd-2-clause
Joker-Developer/jokersuper
plugins/short2.lua
4
1631
--[[ # For More Information ....! # Developer : Aziz < @devss_bot > #Dev # our channel: @help_tele ]] local function run(msg, matches) local yon = http.request('http://api.yon.ir/?url='..URL.escape(matches[1])) local jdat = json:decode(yon) local bitly = https.request('https://api-ssl.bitly.com/v3/shorten?access_token=f2d0b4eabb524aaaf22fbc51ca620ae0fa16753d&longUrl='..URL.escape(matches[1])) local data = json:decode(bitly) local yeo = http.request('http://yeo.ir/api.php?url='..URL.escape(matches[1])..'=') local opizo = http.request('http://api.gpmod.ir/shorten/?url='..URL.escape(matches[1])..'&username=mohamad.khoshnava@gmail.com') local u2s = http.request('http://u2s.ir/?api=1&return_text=1&url='..URL.escape(matches[1])) local llink = http.request('http://llink.ir/yourls-api.php?signature=a13360d6d8&action=shorturl&url='..URL.escape(matches[1])..'&format=simple') return ' الرابط الاصلي :\n'..data.data.long_url..'\n\nلقد حصلت على 6 اختصارات للرابط : \n bitly :\n___________________________\n'..data.data.url..'\n___________________________\n yeo :\n'..yeo..'\n___________________________\n and :\n'..opizo..'\n___________________________\n u2s :\n'..u2s..'\n___________________________\n llink : \n'..llink..'\n___________________________\n yon : \nyon.ir/'..jdat.output..'\n___________________________' end return { usage = "کوتاه کردن لینک سایت مورد نظر به 5 روش\n/short your Link\n لینک حتما با http://شروع شود", patterns = { "^اختصار (.*)$", "^shortlink (.*)$" }, run = run }
gpl-2.0
Scavenge/darkstar
scripts/zones/Ordelles_Caves/TextIDs.lua
7
1991
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6544; -- Obtained: <item>. GIL_OBTAINED = 6545; -- Obtained <number> gil. KEYITEM_OBTAINED = 6547; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7205; -- You can't fish here. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7388; -- You unlock the chest! CHEST_FAIL = 7389; -- Fails to open the chest. CHEST_TRAP = 7390; -- The chest was trapped! CHEST_WEAK = 7391; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7392; -- The chest was a mimic! CHEST_MOOGLE = 7393; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7394; -- The chest was but an illusion... CHEST_LOCKED = 7395; -- The chest appears to be locked. -- Quest Dialog NOTHING_OUT_OF_ORDINARY = 6558; -- There is nothing out of the ordinary here. SENSE_OF_FOREBODING = 6559; -- You are suddenly overcome with a sense of foreboding... A_SQUIRE_S_TEST_II_DIALOG_I = 7353; -- You place your hands into the pool. A_SQUIRE_S_TEST_II_DIALOG_II = 7356; -- The dew from the stalactite slips through your fingers. A_SQUIRE_S_TEST_II_DIALOG_III = 7357; -- You have already obtained the dew. GERWITZS_AXE_DIALOG = 7410; -- Mine axe shall rend thy throat! GERWITZS_SWORD_DIALOG = 7411; -- Mine sword shall pierce thy tongue! GERWITZS_SOUL_DIALOG = 7412; -- Long have I waited. I will tell all... -- Mission Dialog RUILLONT_INITIAL_DIALOG = 7342; -- Confound it! If I only had my sword, I'd cut through these fiends single-handedly... -- conquest Base CONQUEST_BASE = 0; -- Strange Apparatus DEVICE_NOT_WORKING = 7319; -- The device is not working. SYS_OVERLOAD = 7328; -- arning! Sys...verload! Enterin...fety mode. ID eras...d YOU_LOST_THE = 7333; -- You lost the #.
gpl-3.0
Scavenge/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5cf.lua
14
1068
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: _5cf (Gate of Wind) -- @pos -332 0 99 192 ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(DOOR_FIRMLY_CLOSED); return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Joker-Developer/jokersuper
plugins/invite.lua
4
1420
--[[ # For More Information ....! # Developer : Aziz < @devss_bot > #Dev # our channel: @help_tele ]] do local function callbackres(extra, success, result) --vardump(result) local user = 'user#id'..result.peer_id local chat = 'chat#id'..extra.chatid local channel = 'channel#id'..extra.chatid if is_banned(result.id, extra.chatid) then send_large_msg(chat, 'User is banned.') send_large_msg(channel, 'User is banned.') elseif is_gbanned(result.id) then send_large_msg(chat, 'User is globaly banned.') send_large_msg(channel, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_momod(msg) then return end if not is_admin1(msg) then -- For admins only ! return 'Only admins can invite.' end if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin1(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' or msg.to.type ~= 'channel' then local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") resolve_username(username, callbackres, cbres_extra) end end return { patterns = { "^invite (.*)$", "^اضافه (.*)" }, run = run } end
gpl-2.0
Scavenge/darkstar
scripts/zones/Mhaura/npcs/Runito-Monito.lua
17
1508
----------------------------------- -- Area: Mhaura -- NPC: Runito-Monito -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,RUNITOMONITO_SHOP_DIALOG); stock = {0x4015,106, --Cat Bagnakhs 0x4017,1554, --Brass Bagnakhs 0x4041,855, --Brass Dagger 0x42a3,92, --Bronze Rod 0x42b9,634, --Brass Rod 0x4093,3601, --Brass Xiphos 0x40c7,2502, --Claymore 0x4140,618, --Butterfly Axe 0x439b,9, --Dart 0x43a6,3, --Wooden Arrow 0x43a7,4, --Bone Arrow 0x43b8,5} --Crossbow Bolts showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/bcnm.lua
8
44063
require("scripts/globals/status"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); -- NEW SYSTEM BCNM NOTES -- The "core" functions TradeBCNM EventUpdateBCNM EventTriggerBCNM EventFinishBCNM all return TRUE if the action performed is covered by the function. -- This means all the old code will still be executed if the new functions don't support it. This means that there is effectively 'backwards compatibility' with the old system. -- array to map (for each zone) the item id of the valid trade item with the bcnmid in the database -- e.g. zone, {itemid, bcnmid, itemid, bcnmid, itemid, bcnmid} -- DO NOT INCLUDE MAAT FIGHTS itemid_bcnmid_map = {6, {0, 0}, -- Bearclaw_Pinnacle 8, {0, 0}, -- Boneyard_Gully 10, {0, 0}, -- The_Shrouded_Maw 13, {0, 0}, -- Mine_Shaft_2716 17, {0, 0}, -- Spire of Holla 19, {0, 0}, -- Spire of Dem 21, {0, 0}, -- Spire of Mea 23, {0, 0}, -- Spire of Vahzl 29, {0, 0}, -- Riverne Site #B01 31, {0, 0}, -- Monarch Linn 32, {0, 0}, -- Sealion's Den 35, {0, 0}, -- The Garden of RuHmet 36, {0, 0}, -- Empyreal Paradox 57, {0, 0}, -- Talacca Cove 64, {0, 0}, -- Navukgo Execution Chamber 67, {0, 0}, -- Jade Sepulcher 139, {1177, 4, 1552, 10, 1553, 11, 1131, 12, 1175, 15, 1180, 17}, -- Horlais Peak 140, {1551, 34, 1552, 35, 1552, 36}, -- Ghelsba Outpost 144, {1166, 68, 1178, 81, 1553, 76, 1180, 82, 1130, 79, 1552, 73}, -- Waughroon Shrine 146, {1553, 107, 1551, 105, 1177, 100}, -- Balgas Dias 163, {1130, 129, 1130, 130}, -- Sacrificial Chamber 168, {0, 0}, -- Chamber of Oracles 170, {0, 0}, -- Full Moon Fountain 180, {1550, 293}, -- LaLoff Amphitheater 181, {0, 0}, -- The Celestial Nexus 201, {1546, 418, 1174, 417}, -- Cloister of Gales 202, {1548, 450, 1172, 449}, -- Cloister of Storms 203, {1545, 482, 1171, 481}, -- Cloister of Frost 206, {0, 0}, -- Qu'Bia Arena 207, {1544, 545}, -- Cloister of Flames 209, {1547, 578, 1169, 577}, -- Cloister of Tremors 211, {1549, 609}}; -- Cloister of Tides -- array to map (for each zone) the BCNM ID to the Event Parameter corresponding to this ID. -- DO NOT INCLUDE MAAT FIGHTS (only included one for testing!) -- bcnmid, paramid, bcnmid, paramid, etc -- The BCNMID is found via the database. -- The paramid is a bitmask which you need to find out. Being a bitmask, it will be one of: -- 0, 1, 2, 3, 4, 5, ... bcnmid_param_map = {6, {640, 0, 643, 3}, 8, {672, 0, 673, 1}, 10, {704, 0, 706, 2}, 13, {736, 0}, 17, {768, 0}, 19, {800, 0}, 21, {832, 0}, 23, {864, 0}, 29, {896, 0}, 31, {960, 0, 961, 1}, 32, {992, 0, 993, 1}, 35, {1024, 0}, 36, {1056, 0}, 57, {1092, 4}, 64, {1124, 4}, 67, {1156, 4}, 139, {0, 0, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 10, 10, 11, 11, 12, 12, 15, 15, 17, 17}, 140, {32, 0, 33, 1, 34, 2, 35, 3, 36, 4}, 144, {65, 1, 73, 9, 64, 0, 67, 3, 68, 4, 70, 6, 71, 7, 72, 8, 81, 17, 76, 12, 82, 18, 79, 15}, 146, {99, 3, 96, 0, 101, 5, 102, 6, 103, 7, 107, 11, 105, 9}, 163, {128, 0, 129, 1, 130, 2}, 165, {160, 0, 161, 1}, 168, {192, 0, 194, 2, 195, 3, 196, 4}, 170, {224, 0, 225, 1}, 179, {256, 0}, 180, {293, 5, 288, 0, 289, 1, 290, 2, 291, 3, 292, 4}, 181, {320, 0}, 201, {416, 0, 417, 1, 418, 2, 420, 4}, 202, {448, 0, 449, 1, 450, 2, 452, 4}, 203, {480, 0, 481, 1, 482, 2, 484, 4}, 206, {512, 0, 516, 4, 517, 5, 518, 6, 519, 7, 532, 20}, 207, {544, 0, 545, 1, 547, 3}, 209, {576, 0, 577, 1, 578, 2, 580, 4}, 211, {608, 0, 609, 1, 611, 3}}; -- Call this onTrade for burning circles function TradeBCNM(player, zone, trade, npc) -- return false; if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then -- cant start a new bc player:messageBasic(94, 0, 0); return false; elseif (player:hasWornItem(trade:getItemId())) then -- If already used orb or testimony player:messageBasic(56, 0, 0); -- i need correct dialog return false; end if (CheckMaatFights(player, zone, trade, npc)) then -- This function returns true for maat fights return true; end -- the following is for orb battles, etc local id = ItemToBCNMID(player, zone, trade); if (id == -1) then -- no valid BCNMs with this item -- todo: display message based on zone text offset player:setVar("trade_bcnmid", 0); player:setVar("trade_itemid", 0); return false; else -- a valid BCNM with this item, start it. mask = GetBattleBitmask(id, zone, 1); if (mask == -1) then -- Cannot resolve this BCNMID to an event number, edit bcnmid_param_map! print("Item is for a valid BCNM but cannot find the event parameter to display to client."); player:setVar("trade_bcnmid", 0); player:setVar("trade_itemid", 0); return false; end if (player:isBcnmsFull() == 1) then -- temp measure, this will precheck the instances print("all bcnm instances are currently occupied."); npc:messageBasic(246, 0, 0); -- this wont look right in other languages! return true; end player:startEvent(0x7d00, 0, 0, 0, mask, 0, 0, 0, 0); return true; end end; function EventTriggerBCNM(player, npc) player:setVar("trade_bcnmid", 0); player:setVar("trade_itemid", 0); if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then if (player:isInBcnm() == 1) then player:startEvent(0x7d03); -- Run Away or Stay menu else -- You're not in the BCNM but you have the Battlefield effect. Think: non-trader in a party status = player:getStatusEffect(EFFECT_BATTLEFIELD); playerbcnmid = status:getPower(); playermask = GetBattleBitmask(playerbcnmid, player:getZoneID(), 1); if (playermask~=-1) then -- This gives players who did not trade to go in the option of entering the fight player:startEvent(0x7d00, 0, 0, 0, playermask, 0, 0, 0, 0); else player:messageBasic(94, 0, 0); end end return true; else if (checkNonTradeBCNM(player, npc)) then return true; end end return false; end; function EventUpdateBCNM(player, csid, option, entrance) -- return false; local id = player:getVar("trade_bcnmid"); -- this is 0 if the bcnm isnt handled by new functions local skip = CutsceneSkip(player, npc); print("UPDATE csid "..csid.." option "..option); -- seen: option 2, 3, 0 in that order if (csid == 0x7d03 and option == 2) then -- leaving a BCNM the player is currently in. player:updateEvent(3); return true; elseif (csid == 0x7d03 and option == 3) then -- leaving a BCNM the player is currently in. player:updateEvent(0); return true; end if (option == 255 and csid == 0x7d00) then -- Clicked yes, try to register bcnmid if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then -- You're entering a bcnm but you already had the battlefield effect, so you want to go to the -- instance that your battlefield effect represents. player:setVar("bcnm_instanceid_tick", 0); player:setVar("bcnm_instanceid", player:getBattlefieldID()); -- returns 255 if non-existent. return true; end inst = player:bcnmRegister(id); if (inst > 0) then player:setVar("bcnm_instanceid", inst); player:setVar("bcnm_instanceid_tick", 0); player:updateEvent(0, 3, 0, 0, 1, 0); if (entrance ~= nil and player:getBattlefield() ~= nil) then player:getBattlefield():setEntrance(entrance); end -- player:tradeComplete(); else -- no free battlefields at the moment! print("no free instances"); player:setVar("bcnm_instanceid", 255); player:setVar("bcnm_instanceid_tick", 0); end elseif (option == 0 and csid == 0x7d00) then -- Requesting an Instance -- Increment the instance ticker. -- The client will send a total of THREE EventUpdate packets for each one of the free instances. -- If the first instance is free, it should respond to the first packet -- If the second instance is free, it should respond to the second packet, etc local instance = player:getVar("bcnm_instanceid_tick"); instance = instance + 1; player:setVar("bcnm_instanceid_tick", instance); if (instance == player:getVar("bcnm_instanceid")) then -- respond to this packet local mask = GetBattleBitmask(id, player:getZoneID(), 2); local status = player:getStatusEffect(EFFECT_BATTLEFIELD); local playerbcnmid = status:getPower(); if (mask < playerbcnmid) then mask = GetBattleBitmask(playerbcnmid, player:getZoneID(), 2); player:updateEvent(2, mask, 0, 1, 1, skip); -- Add mask number for the correct entering CS player:bcnmEnter(id); player:setVar("bcnm_instanceid_tick", 0); -- print("mask is "..mask) -- print("playerbcnmid is "..playerbcnmid); elseif (mask >= playerbcnmid) then mask = GetBattleBitmask(id, player:getZoneID(), 2); player:updateEvent(2, mask, 0, 1, 1, skip); -- Add mask number for the correct entering CS player:bcnmEnter(id); player:setVar("bcnm_instanceid_tick", 0); -- print("mask2 is "..mask) -- print("playerbcnmid2 is "..playerbcnmid); end if (entrance ~= nil and player:getBattlefield() ~= nil) then player:getBattlefield():setEntrance(entrance); end elseif (player:getVar("bcnm_instanceid") == 255) then -- none free -- print("nfa"); -- player:updateEvent(2, 5, 0, 0, 1, 0); -- @cs 32000 0 0 0 0 0 0 0 2 -- param1 -- 2=generic enter cs -- 3=spam increment instance requests -- 4=cleared to enter but cant while ppl engaged -- 5=dont meet req, access denied. -- 6=room max cap -- param2 alters the eventfinish option (offset) -- param7/8 = does nothing?? end -- @pos -517 159 -209 -- @pos -316 112 -103 -- player:updateEvent(msgid, bcnmFight, 0, record, numadventurers, skip); skip=1 to skip anim -- msgid 1=wait a little longer, 2=enters end return true; end; function EventFinishBCNM(player, csid, option) print("FINISH csid "..csid.." option "..option); if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then -- Temp condition for normal bcnm (started with onTrigger) return false; else local id = player:getVar("trade_bcnmid"); local item = player:getVar("trade_itemid"); if (id == 68 or id == 418 or id == 450 or id == 482 or id == 545 or id == 578 or id == 609 or id == 293) then player:tradeComplete(); -- Removes the item elseif ((item >= 1426 and item <= 1440) or item == 1130 or item == 1131 or item == 1175 or item == 1177 or item == 1180 or item == 1178 or item == 1551 or item == 1552 or item == 1553) then -- Orb and Testimony (one time item) player:createWornItem(item); end return true; end end; -- Returns TRUE if you're trying to do a maat fight, regardless of outcome e.g. if you trade testimony on wrong job, this will return true in order to prevent further execution of TradeBCNM. Returns FALSE if you're not doing a maat fight (in other words, not trading a testimony!!) function CheckMaatFights(player, zone, trade, npc) player:setVar("trade_bcnmid", 0); player:setVar("trade_itemid", 0); -- check for maat fights (one maat fight per zone in the db, but >1 mask entries depending on job, so we -- need to choose the right one depending on the players job, and make sure the right testimony is traded, -- and make sure the level is right! local itemid = trade:getItemId(); local job = player:getMainJob(); local lvl = player:getMainLvl(); if (itemid >= 1426 and itemid <= 1440) then -- The traded item IS A TESTIMONY if (lvl < 66) then return true; end if (player:isBcnmsFull() == 1) then -- temp measure, this will precheck the instances print("all bcnm instances are currently occupied."); npc:messageBasic(246, 0, 0); return true; end -- Zone, {item, job, menu, bcnmid, ...} maatList = {139, {1426, 1, 32, 5, 1429, 4, 64, 6, 1436, 11, 128, 7}, -- Horlais Peak [WAR BLM RNG] 144, {1430, 5, 64, 70, 1431, 6, 128, 71, 1434, 9, 256, 72}, -- Waughroon Shrine [RDM THF BST] 146, {1427, 2, 32, 101, 1428, 3, 64, 102, 1440, 15, 128, 103}, -- Balga's Dais [MNK WHM SMN] 168, {1437, 12, 4, 194, 1438, 13, 8, 195, 1439, 14, 16, 196}, -- Chamber of Oracles [SAM NIN DRG] 206, {1432, 7, 32, 517, 1433, 8, 64, 518, 1435, 10, 128, 519} };-- Qu'Bia Arena [PLD DRK BRD] for nb = 1, #maatList, 2 do if (maatList[nb] == zone) then for nbi = 1, #maatList[nb + 1], 4 do if (itemid == maatList[nb + 1][nbi] and job == maatList[nb + 1][nbi + 1]) then player:startEvent(0x7d00, 0, 0, 0, maatList[nb + 1][nbi + 2], 0, 0, 0, 0); player:setVar("trade_bcnmid", maatList[nb + 1][nbi + 3]); player:setVar("trade_itemid", maatList[nb + 1][nbi]); break; end end end end return true; end -- if it got this far then its not a testimony return false; end; function GetBattleBitmask(id, zone, mode) -- normal sweep for NON MAAT FIGHTS local ret = -1; local mask = 0; for zoneindex = 1, #bcnmid_param_map, 2 do if (zone==bcnmid_param_map[zoneindex]) then -- matched zone for bcnmindex = 1, #bcnmid_param_map[zoneindex + 1], 2 do -- loop bcnms in this zone if (id==bcnmid_param_map[zoneindex+1][bcnmindex]) then -- found bcnmid if (mode == 1) then ret = mask + (2^bcnmid_param_map[zoneindex+1][bcnmindex+1]); -- for trigger (mode 1): 1, 2, 4, 8, 16, 32, ... else ret = mask + bcnmid_param_map[zoneindex+1][bcnmindex+1]; -- for update (mode 2): 0, 1, 2, 3, 4, 5, 6, ... end end end end end return ret; end; function ItemToBCNMID(player, zone, trade) for zoneindex = 1, #itemid_bcnmid_map, 2 do if (zone==itemid_bcnmid_map[zoneindex]) then -- matched zone for bcnmindex = 1, #itemid_bcnmid_map[zoneindex + 1], 2 do -- loop bcnms in this zone if (trade:getItemId()==itemid_bcnmid_map[zoneindex+1][bcnmindex]) then local item = trade:getItemId(); local questTimelineOK = 0; -- Job/lvl condition for smn battle lvl20 if (item >= 1544 and item <= 1549 and player:getMainJob() == JOBS.SMN and player:getMainLvl() >= 20) then questTimelineOK = 1; elseif (item == 1166 and player:getVar("aThiefinNorgCS") == 6) then -- AF3 SAM condition questTimelineOK = 1; elseif (item == 1551) then -- BCNM20 questTimelineOK = 1; elseif (item == 1552) then -- BCNM30 questTimelineOK = 1; elseif (item == 1131) then -- BCNM40 questTimelineOK = 1; elseif (item == 1177) then -- BCNM50 questTimelineOK = 1; elseif (item == 1130) then -- BCNM60 questTimelineOK = 1; elseif (item == 1175) then -- KSNM30 questTimelineOK = 1; elseif (item == 1178) then -- KSNM30 questTimelineOK = 1; elseif (item == 1180) then -- KSNM30 questTimelineOK = 1; elseif (item == 1553) then -- KSNM99 questTimelineOK = 1; elseif (item == 1550 and (player:getQuestStatus(OUTLANDS, DIVINE_MIGHT) == QUEST_ACCEPTED or player:getQuestStatus(OUTLANDS, DIVINE_MIGHT_REPEAT) == QUEST_ACCEPTED)) then -- Divine Might questTimelineOK = 1; elseif (item == 1169 and player:getVar("ThePuppetMasterProgress") == 2) then -- The Puppet Master questTimelineOK = 1; elseif (item == 1171 and player:getVar("ClassReunionProgress") == 5) then -- Class Reunion questTimelineOK = 1; elseif (item == 1172 and player:getVar("CarbuncleDebacleProgress") == 3) then -- Carbuncle Debacle (Gremlims) questTimelineOK = 1; elseif (item == 1174 and player:getVar("CarbuncleDebacleProgress") == 6) then -- Carbuncle Debacle (Ogmios) questTimelineOK = 1; end if (questTimelineOK == 1) then player:setVar("trade_bcnmid", itemid_bcnmid_map[zoneindex+1][bcnmindex+1]); player:setVar("trade_itemid", itemid_bcnmid_map[zoneindex+1][bcnmindex]); return itemid_bcnmid_map[zoneindex+1][bcnmindex+1]; end end end end end return -1; end; -- E.g. mission checks go here, you must know the right bcnmid for the mission you want to code. -- You also need to know the bitmask (event param) which should be put in bcnmid_param_map function checkNonTradeBCNM(player, npc) local mask = 0; local Zone = player:getZoneID(); if (Zone == 6) then -- Bearclaw_Pinnacle if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 6) then -- flames_for_the_dead mask = GetBattleBitmask(640, Zone, 1); player:setVar("trade_bcnmid", 640); elseif (player:hasKeyItem(ZEPHYR_FAN)) then -- Brothers ENM mask = GetBattleBitmask(643, Zone, 1); player:setVar("trade_bcnmid", 643); end elseif (Zone == 8) then -- Boneyard_Gully if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 5) then -- head_wind mask = GetBattleBitmask(672, Zone, 1); player:setVar("trade_bcnmid", 672); elseif (player:hasKeyItem(MIASMA_FILTER)==true) then mask = GetBattleBitmask(673, Zone, 1); player:setVar("trade_bcnmid", 673); else end elseif (Zone == 10) then -- The_Shrouded_Maw if (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 2) then-- DARKNESS_NAMED mask = GetBattleBitmask(704, Zone, 1); player:setVar("trade_bcnmid", 704); elseif (player:hasKeyItem(VIAL_OF_DREAM_INCENSE)==true) then -- waking_dreams (diabolos avatar quest) mask = GetBattleBitmask(706, Zone, 1); player:setVar("trade_bcnmid", 706); end elseif (Zone == 13) then -- Mine_Shaft_2716 if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 5) then -- century_of_hardship mask = GetBattleBitmask(736, Zone, 1); player:setVar("trade_bcnmid", 736); end elseif (Zone == 17) then -- Spire of Holla if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then mask = GetBattleBitmask(768, Zone, 1); player:setVar("trade_bcnmid", 768); elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_HOLLA) == false) then -- light of holla mask = GetBattleBitmask(768, Zone, 1); player:setVar("trade_bcnmid", 768); end elseif (Zone == 19) then -- Spire of Dem if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then mask = GetBattleBitmask(800, Zone, 1); player:setVar("trade_bcnmid", 800); elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_DEM) == false) then -- light of dem mask = GetBattleBitmask(800, Zone, 1); player:setVar("trade_bcnmid", 800); end elseif (Zone == 21) then -- Spire of Mea if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then mask = GetBattleBitmask(832, Zone, 1); player:setVar("trade_bcnmid", 832); elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_MEA) == false) then -- light of mea mask = GetBattleBitmask(832, Zone, 1); player:setVar("trade_bcnmid", 832); end elseif (Zone == 23) then -- Spire of vahzl if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==8) then -- desires of emptiness mask = GetBattleBitmask(864, Zone, 1); player:setVar("trade_bcnmid", 864); end elseif (Zone == 29) then -- Riverne Site #B01 if (player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_ACCEPTED and player:getVar('StormsOfFate') == 2) then -- Storms of Fate BCNM mask = GetBattleBitmask(896, Zone, 1); player:setVar("trade_bcnmid", 896); end elseif (Zone == 31) then -- Monarch Linn if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then -- Ancient Vows bcnm mask = GetBattleBitmask(960, Zone, 1); player:setVar("trade_bcnmid", 960); elseif (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 1) then mask = GetBattleBitmask(961, Zone, 1); player:setVar("trade_bcnmid", 961); end elseif (Zone == 32) then -- Sealion's Den if (player:getCurrentMission(COP) == ONE_TO_BE_FEARED and player:getVar("PromathiaStatus")==2) then -- one_to_be_feared mask = GetBattleBitmask(992, Zone, 1); player:setVar("trade_bcnmid", 992); elseif (player:getCurrentMission(COP) == THE_WARRIOR_S_PATH) then -- warriors_path mask = GetBattleBitmask(993, Zone, 1); player:setVar("trade_bcnmid", 993); end elseif (Zone == 35) then -- The Garden of RuHmet if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4) then -- when_angels_fall mask = GetBattleBitmask(1024, Zone, 1); player:setVar("trade_bcnmid", 1024); end elseif (Zone == 36) then -- Empyreal Paradox if (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==2) then -- dawn mask = GetBattleBitmask(1056, Zone, 1); player:setVar("trade_bcnmid", 1056); end elseif (Zone == 57) then -- Talacca Cove if (player:getCurrentMission(TOAU) == LEGACY_OF_THE_LOST) then -- TOAU-35 Legacy of the Lost mask = GetBattleBitmask(1092, Zone, 1); player:setVar("trade_bcnmid", 1092); end elseif (Zone == 64) then -- Navukgo Execution Chamber if (player:getCurrentMission(TOAU) == SHIELD_OF_DIPLOMACY and player:getVar("AhtUrganStatus")==2) then -- TOAU-22 shield of diplomacy mask = GetBattleBitmask(1124, Zone, 1); player:setVar("trade_bcnmid", 1124); end elseif (Zone == 67) then -- Jade Sepulcher if (player:getCurrentMission(TOAU) == PUPPET_IN_PERIL and player:getVar("AhtUrganStatus")==1) then -- TOAU-29 Puppet in Peril mask = GetBattleBitmask(1156, Zone, 1); player:setVar("trade_bcnmid", 1156); end elseif (Zone == 139) then -- Horlais Peak if ((player:getCurrentMission(BASTOK) == THE_EMISSARY_SANDORIA2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_SANDORIA2) and player:getVar("MissionStatus") == 9) then -- Mission 2-3 mask = GetBattleBitmask(0, Zone, 1); player:setVar("trade_bcnmid", 0); elseif (player:getCurrentMission(SANDORIA) == THE_SECRET_WEAPON and player:getVar("SecretWeaponStatus") == 2) then mask = GetBattleBitmask(3, Zone, 1) player:setVar("trade_bcnmid", 3); end elseif (Zone == 140) then -- Ghelsba Outpost local MissionStatus = player:getVar("MissionStatus"); local sTcCompleted = player:hasCompletedMission(SANDORIA, SAVE_THE_CHILDREN) if (player:getCurrentMission(SANDORIA) == SAVE_THE_CHILDREN and (sTcCompleted and MissionStatus <= 2 or sTcCompleted == false and MissionStatus == 2)) then -- Sandy Mission 1-3 mask = GetBattleBitmask(32, Zone, 1); player:setVar("trade_bcnmid", 32); elseif (player:hasKeyItem(DRAGON_CURSE_REMEDY)) then -- DRG Flag Quest mask = GetBattleBitmask(33, Zone, 1); player:setVar("trade_bcnmid", 33); end elseif (Zone == 144) then -- Waughroon Shrine if ((player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) and player:getVar("MissionStatus") == 10) then -- Mission 2-3 mask = GetBattleBitmask(64, Zone, 1); player:setVar("trade_bcnmid", 64); elseif ((player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 2)) then mask = GetBattleBitmask(67, Zone, 1); player:setVar("trade_bcnmid", 67); end elseif (Zone == 146) then -- Balga's Dais if (player:hasKeyItem(DARK_KEY)) then -- Mission 2-3 mask = GetBattleBitmask(96, Zone, 1); player:setVar("trade_bcnmid", 96); elseif ((player:getCurrentMission(WINDURST) == SAINTLY_INVITATION) and (player:getVar("MissionStatus") == 1)) then -- Mission 6-2 mask = GetBattleBitmask(99, Zone, 1); player:setVar("trade_bcnmid", 99); end elseif (Zone == 163) then -- Sacrificial Chamber if (player:getCurrentMission(ZILART) == THE_TEMPLE_OF_UGGALEPIH) then -- Zilart Mission 4 mask = GetBattleBitmask(128, Zone, 1); player:setVar("trade_bcnmid", 128); end elseif (Zone == 165) then -- Throne Room if (player:getCurrentMission(player:getNation()) == 15 and player:getVar("MissionStatus") == 3) then -- Mission 5-2 mask = GetBattleBitmask(160, Zone, 1); player:setVar("trade_bcnmid", 160); elseif (player:getCurrentMission(BASTOK) == WHERE_TWO_PATHS_CONVERGE and player:getVar("BASTOK92") == 1) then -- bastok 9-2 mask = GetBattleBitmask(161, Zone, 1); player:setVar("trade_bcnmid", 161); end elseif (Zone == 168) then -- Chamber of Oracles if (player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES or player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then -- Zilart Mission 6 mask = GetBattleBitmask(192, Zone, 1); player:setVar("trade_bcnmid", 192); end elseif (Zone == 170) then -- Full Moon Fountain if (player:hasKeyItem(MOON_BAUBLE)) then -- The Moonlit Path mask = GetBattleBitmask(224, Zone, 1); player:setVar("trade_bcnmid", 224); elseif ((player:getCurrentMission(WINDURST) == MOON_READING) and player:getVar("WINDURST92") == 2) then -- Moon reading mask = GetBattleBitmask(225, Zone, 1); player:setVar("trade_bcnmid", 225); end elseif (Zone == 179) then -- Stellar Fulcrum if (player:getCurrentMission(ZILART) == RETURN_TO_DELKFUTTS_TOWER and player:getVar("ZilartStatus") == 3) then -- Zilart Mission 8 mask = GetBattleBitmask(256, Zone, 1); player:setVar("trade_bcnmid", 256); end elseif (Zone == 180) then -- La'Loff Amphitheater if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then local qmid = npc:getID(); if (qmid == 17514791 and player:hasKeyItem(SHARD_OF_APATHY) == false) then -- Hume, Ark Angels 1 mask = GetBattleBitmask(288, Zone, 1); player:setVar("trade_bcnmid", 288); elseif (qmid == 17514792 and player:hasKeyItem(SHARD_OF_COWARDICE) == false) then -- Tarutaru, Ark Angels 2 mask = GetBattleBitmask(289, Zone, 1); player:setVar("trade_bcnmid", 289); elseif (qmid == 17514793 and player:hasKeyItem(SHARD_OF_ENVY) == false) then -- Mithra, Ark Angels 3 mask = GetBattleBitmask(290, Zone, 1); player:setVar("trade_bcnmid", 290); elseif (qmid == 17514794 and player:hasKeyItem(SHARD_OF_ARROGANCE) == false) then -- Elvaan, Ark Angels 4 mask = GetBattleBitmask(291, Zone, 1); player:setVar("trade_bcnmid", 291); elseif (qmid == 17514795 and player:hasKeyItem(SHARD_OF_RAGE) == false) then -- Galka, Ark Angels 5 mask = GetBattleBitmask(292, Zone, 1); player:setVar("trade_bcnmid", 292); end end elseif (Zone == 181) then -- The Celestial Nexus if (player:getCurrentMission(ZILART) == THE_CELESTIAL_NEXUS) then -- Zilart Mission 16 mask = GetBattleBitmask(320, Zone, 1); player:setVar("trade_bcnmid", 320); end elseif (Zone == 201) then -- Cloister of Gales if (player:hasKeyItem(TUNING_FORK_OF_WIND)) then -- Trial by Wind mask = GetBattleBitmask(416, Zone, 1); player:setVar("trade_bcnmid", 416); elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_EMERALD_SEAL)) then mask = GetBattleBitmask(420, Zone, 1); player:setVar("trade_bcnmid", 420); end elseif (Zone == 202) then -- Cloister of Storms if (player:hasKeyItem(TUNING_FORK_OF_LIGHTNING)) then -- Trial by Lightning mask = GetBattleBitmask(448, Zone, 1); player:setVar("trade_bcnmid", 448); elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_VIOLET_SEAL)) then mask = GetBattleBitmask(452, Zone, 1); player:setVar("trade_bcnmid", 452); end elseif (Zone == 203) then -- Cloister of Frost if (player:hasKeyItem(TUNING_FORK_OF_ICE)) then -- Trial by Ice mask = GetBattleBitmask(480, Zone, 1); player:setVar("trade_bcnmid", 480); elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_AZURE_SEAL)) then mask = GetBattleBitmask(484, Zone, 1); player:setVar("trade_bcnmid", 484); end elseif (Zone == 206) then -- Qu'Bia Arena if (player:getCurrentMission(player:getNation()) == 14 and player:getVar("MissionStatus") == 11) then -- Mission 5-1 mask = GetBattleBitmask(512, Zone, 1); player:setVar("trade_bcnmid", 512); elseif (player:getCurrentMission(SANDORIA) == THE_HEIR_TO_THE_LIGHT and player:getVar("MissionStatus") == 3) then -- sando 9-2 mask = GetBattleBitmask(516, Zone, 1); player:setVar("trade_bcnmid", 516); -- Temp disabled pending BCNM mob fixes -- elseif (player:getCurrentMission(ACP) >= THOSE_WHO_LURK_IN_SHADOWS_III and player:hasKeyItem(MARK_OF_SEED)) then -- ACP Mission 7 -- mask = GetBattleBitmask(532, Zone, 1); -- player:setVar("trade_bcnmid", 532); end elseif (Zone == 207) then -- Cloister of Flames if (player:hasKeyItem(TUNING_FORK_OF_FIRE)) then -- Trial by Fire mask = GetBattleBitmask(544, Zone, 1); player:setVar("trade_bcnmid", 544); elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_SCARLET_SEAL)) then mask = GetBattleBitmask(547, Zone, 1); player:setVar("trade_bcnmid", 547); end elseif (Zone == 209) then -- Cloister of Tremors if (player:hasKeyItem(TUNING_FORK_OF_EARTH)) then -- Trial by Earth mask = GetBattleBitmask(576, Zone, 1); player:setVar("trade_bcnmid", 576); elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_AMBER_SEAL)) then mask = GetBattleBitmask(580, Zone, 1); player:setVar("trade_bcnmid", 580); end elseif (Zone == 211) then -- Cloister of Tides if (player:hasKeyItem(TUNING_FORK_OF_WATER)) then -- Trial by Water mask = GetBattleBitmask(608, Zone, 1); player:setVar("trade_bcnmid", 608); elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_CERULEAN_SEAL)) then mask = GetBattleBitmask(611, Zone, 1); player:setVar("trade_bcnmid", 611); end end if (mask == -1) then print("BCNMID/Mask pair not found"); -- something went wrong return true; elseif (mask ~= 0) then player:startEvent(0x7d00, 0, 0, 0, mask, 0, 0, 0, 0); print("BCNMID found with mask "..mask); return true; else return false; end end; function CutsceneSkip(player, npc) local skip = 0; local Zone = player:getZoneID(); if (Zone == 6) then -- Bearclaw Pinnacle if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") > 6)) then -- flames_for_the_dead skip = 1; end elseif (Zone == 8) then -- Boneyard Gully if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") > 5)) then -- head_wind skip = 1; end elseif (Zone == 10) then -- The_Shrouded_Maw if ((player:hasCompletedMission(COP, DARKNESS_NAMED)) or (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") > 2)) then -- DARKNESS_NAMED skip = 1; elseif ((player:hasCompleteQuest(WINDURST, WAKING_DREAMS)) or (player:hasKeyItem(WHISPER_OF_DREAMS))) then -- waking_dreams (diabolos avatar quest) skip = 1; end elseif (Zone == 13) then -- Mine Shaft 2716 if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") > 5)) then -- century_of_hardship skip = 1; end elseif (Zone == 17) then -- Spire of Holla if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_HOLLA))) then -- light of holla skip = 1; end elseif (Zone == 19) then -- Spire of Dem if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_DEM))) then -- light of dem skip = 1; end elseif (Zone == 21) then -- Spire of Mea if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_MEA))) then -- light of mea skip = 1; end elseif (Zone == 23) then -- Spire of Vahzl if ((player:hasCompletedMission(COP, DESIRES_OF_EMPTINESS)) or (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus") > 8)) then -- desires of emptiness skip = 1; end elseif (Zone == 29) then -- Riverne Site #B01 if ((player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_COMPLETED) or (player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_ACCEPTED and player:getVar("StormsOfFate") > 2)) then -- Storms of Fate skip = 1; end elseif (Zone == 31) then -- Monarch Linn if (player:hasCompletedMission(COP, ANCIENT_VOWS)) then -- Ancient Vows skip = 1; elseif ((player:hasCompletedMission(COP, THE_SAVAGE)) or (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") > 1)) then skip = 1; end elseif (Zone == 32) then -- Sealion's Den if (player:hasCompletedMission(COP, ONE_TO_BE_FEARED)) then -- one_to_be_feared skip = 1; elseif (player:hasCompletedMission(COP, THE_WARRIOR_S_PATH)) then -- warriors_path skip = 1; end elseif (Zone == 35) then -- The Garden of RuHmet if ((player:hasCompletedMission(COP, WHEN_ANGELS_FALL)) or (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") > 4)) then -- when_angels_fall skip = 1; end elseif (Zone == 36) then -- Empyreal Paradox if ((player:hasCompletedMission(COP, DAWN)) or (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus") > 2)) then -- dawn skip = 1; end elseif (Zone == 139) then -- Horlais Peak if ((player:hasCompletedMission(BASTOK, THE_EMISSARY_SANDORIA2) or player:hasCompletedMission(WINDURST, THE_THREE_KINGDOMS_SANDORIA2)) or ((player:getCurrentMission(BASTOK) == THE_EMISSARY_SANDORIA2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_SANDORIA2) and player:getVar("MissionStatus") > 9)) then -- Mission 2-3 skip = 1; elseif ((player:hasCompletedMission(SANDORIA, THE_SECRET_WEAPON)) or (player:getCurrentMission(SANDORIA) == THE_SECRET_WEAPON and player:getVar("SecretWeaponStatus") > 2)) then skip = 1; end elseif (Zone == 140) then -- Ghelsba Outpost if ((player:hasCompletedMission(SANDORIA, SAVE_THE_CHILDREN)) or (player:getCurrentMission(SANDORIA) == SAVE_THE_CHILDREN and player:getVar("MissionStatus") > 2)) then -- Sandy Mission 1-3 skip = 1; elseif (player:hasCompleteQuest(SANDORIA, THE_HOLY_CREST)) then -- DRG Flag Quest skip = 1; end elseif (Zone == 144) then -- Waughroon Shrine if ((player:hasCompletedMission(SANDORIA, JOURNEY_TO_BASTOK2) or player:hasCompletedMission(WINDURST, THE_THREE_KINGDOMS_BASTOK2)) or ((player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) and player:getVar("MissionStatus") > 10)) then -- Mission 2-3 skip = 1; elseif ((player:hasCompletedMission(BASTOK, ON_MY_WAY)) or (player:getCurrentMission(BASTOK) == ON_MY_WAY and player:getVar("MissionStatus") > 2)) then skip = 1; end elseif (Zone == 146) then -- Balga's Dais if ((player:hasCompletedMission(SANDORIA, JOURNEY_TO_WINDURST2) or player:hasCompletedMission(BASTOK, THE_EMISSARY_WINDURST2)) or ((player:getCurrentMission(SANDORIA) == JOURNEY_TO_WINDURST2 or player:getCurrentMission(BASTOK) == THE_EMISSARY_WINDURST2) and player:getVar("MissionStatus") > 8)) then -- Mission 2-3 skip = 1; elseif ((player:hasCompletedMission(WINDURST, SAINTLY_INVITATION)) or (player:getCurrentMission(WINDURST) == SAINTLY_INVITATION and player:getVar("MissionStatus") > 1)) then -- Mission 6-2 skip = 1; end elseif (Zone == 165) then -- Throne Room if ((player:hasCompletedMission(player:getNation(), 15)) or (player:getCurrentMission(player:getNation()) == 15 and player:getVar("MissionStatus") > 3)) then -- Mission 5-2 skip = 1; end elseif (Zone == 168) then -- Chamber of Oracles if (player:hasCompletedMission(ZILART, THROUGH_THE_QUICKSAND_CAVES)) then -- Zilart Mission 6 skip = 1; end elseif (Zone == 170) then -- Full Moon Fountain if ((player:hasCompleteQuest(WINDURST, THE_MOONLIT_PATH)) or (player:hasKeyItem(WHISPER_OF_THE_MOON))) then -- The Moonlit Path skip = 1; end elseif (Zone == 179) then -- Stellar Fulcrum if (player:hasCompletedMission(ZILART, RETURN_TO_DELKFUTTS_TOWER)) then -- Zilart Mission 8 skip = 1; end elseif (Zone == 180) then -- La'Loff Amphitheater if (player:hasCompletedMission(ZILART, ARK_ANGELS)) then skip = 1; end elseif (Zone == 181) then -- The Celestial Nexus if (player:hasCompletedMission(ZILART, THE_CELESTIAL_NEXUS)) then -- Zilart Mission 16 skip = 1; end elseif (Zone == 201) then -- Cloister of Gales if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_WIND)) or (player:hasKeyItem(WHISPER_OF_GALES))) then -- Trial by Wind skip = 1; end elseif (Zone == 202) then -- Cloister of Storms if ((player:hasCompleteQuest(OTHER_AREAS, TRIAL_BY_LIGHTNING)) or (player:hasKeyItem(WHISPER_OF_STORMS))) then -- Trial by Lightning skip = 1; end elseif (Zone == 203) then -- Cloister of Frost if ((player:hasCompleteQuest(SANDORIA, TRIAL_BY_ICE)) or (player:hasKeyItem(WHISPER_OF_FROST))) then -- Trial by Ice skip = 1; end elseif (Zone == 206) then -- Qu'Bia Arena if ((player:hasCompletedMission(player:getNation(), 14)) or (player:getCurrentMission(player:getNation()) == 14 and player:getVar("MissionStatus") > 11)) then -- Mission 5-1 skip = 1; elseif ((player:hasCompletedMission(player:getNation(), 23)) or (player:getCurrentMission(player:getNation()) == 23 and player:getVar("MissionStatus") > 4)) then -- Mission 9-2 skip = 1; end elseif (Zone == 207) then -- Cloister of Flames if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_FIRE)) or (player:hasKeyItem(WHISPER_OF_FLAMES))) then -- Trial by Fire skip = 1; end elseif (Zone == 209) then -- Cloister of Tremors if ((player:hasCompleteQuest(BASTOK, TRIAL_BY_EARTH)) or (player:hasKeyItem(WHISPER_OF_TREMORS))) then -- Trial by Earth skip = 1; end elseif (Zone == 211) then -- Cloister of Tides if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_WATER)) or (player:hasKeyItem(WHISPER_OF_TIDES))) then -- Trial by Water skip = 1; end end return skip; end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
LuaRules/Gadgets/unit_regeneration.lua
2
2926
if not gadgetHandler:IsSyncedCode() then return end function gadget:GetInfo() return { name = "Regeneration", desc = "Handles idle regeneration for air units", author = "Sprung", date = "2015-05-22", license = "PD", layer = 0, enabled = true, } end local spGetUnitIsStunned = Spring.GetUnitIsStunned local spGetUnitHealth = Spring.GetUnitHealth local spSetUnitHealth = Spring.SetUnitHealth local spGetUnitRulesParam = Spring.GetUnitRulesParam local spSetUnitRulesParam = Spring.SetUnitRulesParam local units = {} local unitList = {} local unitCount = 0 local regenDefs = {} local losTable = {inlos = true} for id, def in pairs(UnitDefs) do regenDefs[id] = {idleTime = def.idleTime, rate = def.customParams.idle_regen / 2 } end local currentFrame function gadget:Initialize() currentFrame = Spring.GetGameFrame() end function gadget:GameFrame (frame) currentFrame = frame if ((frame % 15) == 7) then local setParam = ((frame % 30) == 7) local unitID, data, slowMult, amount, health for i = 1, unitCount do unitID = unitList[i] data = units[unitID] if (data.idleFrame < frame) and (not spGetUnitIsStunned(unitID)) and (spGetUnitRulesParam(unitID, "disarmed") ~= 1) then slowMult = (1-(spGetUnitRulesParam(unitID,"slowState") or 0)) amount = data.rate * slowMult health = spGetUnitHealth(unitID) if health then spSetUnitHealth(unitID, health + amount) end end if setParam then spSetUnitRulesParam(unitID, "idleRegenTimer", data.idleFrame - frame, losTable) end end end end local function SetUnitIdleRegen(unitID, idleTime, idleRate) if units[unitID] then units[unitID].idleFrame = 0 units[unitID].idleTime = idleTime units[unitID].rate = idleRate else unitCount = unitCount + 1 unitList[unitCount] = unitID units[unitID] = { idleFrame = 0, idleTime = idleTime, rate = idleRate, index = unitCount } end end function gadget:UnitCreated(unitID, unitDefID) SetUnitIdleRegen(unitID, regenDefs[unitDefID].idleTime, regenDefs[unitDefID].rate) local regen = Spring.GetUnitRulesParam(unitID, "comm_autorepair_rate") if regen then SetUnitIdleRegen(unitID, 0, regen / 2) end end function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage) if units[unitID] then units[unitID].idleFrame = currentFrame + units[unitID].idleTime spSetUnitRulesParam(unitID, "idleRegenTimer", units[unitID].idleTime, losTable) end end function gadget:UnitDestroyed(unitID) if units[unitID] then local index = units[unitID].index unitList[index] = unitList[unitCount] units[unitList[index]].index = index unitList[unitCount] = nil unitCount = unitCount - 1 units[unitID] = nil end end function gadget:Initialize() GG.SetUnitIdleRegen = SetUnitIdleRegen for _, unitID in ipairs(Spring.GetAllUnits()) do local unitDefID = Spring.GetUnitDefID(unitID) gadget:UnitCreated(unitID, unitDefID) end end
gpl-2.0
Scavenge/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Dkhaaya.lua
14
2530
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Dkhaaya -- Type: Standard NPC -- @pos -73.212 -1 -5.842 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local olduumQuest = player:getQuestStatus(AHT_URHGAN, OLDUUM); local ringCheck = player:hasItem(2217); if (olduumQuest == QUEST_AVAILABLE) then player:startEvent(0x004); elseif (player:hasKeyItem(ELECTROLOCOMOTIVE) or player:hasKeyItem(ELECTROPOT) or player:hasKeyItem(ELECTROCELL) and ringCheck == false) then if (olduumQuest == QUEST_ACCEPTED) then player:startEvent(0x006); else player:startEvent(0x008); end elseif (olduumQuest ~= QUEST_AVAILABLE and ringCheck == false) then player:startEvent(0x005); else player:startEvent(0x007); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x004) then player:addKeyItem(DKHAAYAS_RESEARCH_JOURNAL); player:messageSpecial(KEYITEM_OBTAINED, DKHAAYAS_RESEARCH_JOURNAL); player:addQuest(AHT_URHGAN, OLDUUM); elseif (csid == 0x006 or csid == 0x008) then if (player:getFreeSlotsCount() >= 1) then player:addItem(2217); player:messageSpecial(ITEM_OBTAINED, 2217); player:delKeyItem(DKHAAYAS_RESEARCH_JOURNAL); player:delKeyItem(ELECTROLOCOMOTIVE); player:delKeyItem(ELECTROPOT); player:delKeyItem(ELECTROCELL); if (csid == 0x006) then player:completeQuest(AHT_URHGAN, OLDUUM); end else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 2217); end end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/sandfish.lua
12
1323
----------------------------------------- -- ID: 4291 -- Item: sandfish -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 3 -- Mind -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4291); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -5); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Den_of_Rancor/Zone.lua
12
1639
----------------------------------- -- -- Zone: Den_of_Rancor (160) -- ----------------------------------- package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Den_of_Rancor/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) UpdateTreasureSpawnPoint(17433077); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(196.421,34.595,-60.319,110); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/The_Shrine_of_RuAvitau/npcs/blank_4.lua
14
4986
----------------------------------- -- Area: The Shrine of Ru'Avitau -- NPC: ??? divine might mission -- @pos -40 0 -151 178 ----------------------------------- package.loaded["scripts/zones/The_Shrine_of_RuAvitau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Shrine_of_RuAvitau/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CurrentZM = player:getCurrentMission(ZILART); local ZMProgress = player:getVar("ZilartStatus"); local DMStatus = player:getQuestStatus(OUTLANDS,DIVINE_MIGHT); local DMRepeat = player:getQuestStatus(OUTLANDS,DIVINE_MIGHT_REPEAT); local AAKeyitems = 0; local DMEarrings = 0; local DivineStatus = player:getVar("DivineMight"); local MoonOre = player:hasKeyItem(MOONLIGHT_ORE); -- Count keyitems for i=SHARD_OF_APATHY, SHARD_OF_RAGE do if (player:hasKeyItem(i) == true) then AAKeyitems = AAKeyitems + 1; end end -- Count Earrings for i=14739, 14743 do if (player:hasItem(i) == true) then DMEarrings = DMEarrings + 1; end end if (CurrentZM == ARK_ANGELS and ZMProgress == 0 and DMEarrings <= NUMBER_OF_DM_EARRINGS) then -- First step in Ark Angels player:startEvent(53,917,1408,1550); elseif (CurrentZM == ARK_ANGELS and ZMProgress == 1 and DivineStatus < 2) then -- Reminder CS/starts Divine Might (per Wiki) player:startEvent(54,917,1408,1550); elseif (CurrentZM >= ARK_ANGELS and DMStatus == QUEST_AVAILABLE and AAKeyitems > 0) then -- Alternative cutscene for those that have done one or more AA fight player:startEvent(56,917,1408,1550); elseif (DMStatus == QUEST_ACCEPTED and DivineStatus >= 2) then -- CS when player has completed Divine might, award earring player:startEvent(55,14739,14740,14741,14742,14743); elseif (DMStatus == QUEST_COMPLETED and DMEarrings < NUMBER_OF_DM_EARRINGS and DMRepeat ~= QUEST_ACCEPTED) then -- You threw away old Earring, start the repeat quest player:startEvent(57,player:getVar("DM_Earring")); elseif (DMRepeat == QUEST_ACCEPTED and DivineStatus < 2) then if (MoonOre == false) then player:startEvent(58); -- Reminder for Moonlight Ore else player:startEvent(56,917,1408,1550); -- Reminder for Ark Pentasphere end elseif (DMRepeat == QUEST_ACCEPTED and DivineStatus == 2 and MoonOre == true) then -- Repeat turn in player:startEvent(59); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); -- Need some kind of feedback end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 59 and option == 2) then player:updateEvent(14739,14740,14741,14742,14743); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 53) then -- Got the required cutscene for AA player:setVar("ZilartStatus",1); elseif ((csid == 54 or csid == 56) and player:getQuestStatus(OUTLANDS,DIVINE_MIGHT) == QUEST_AVAILABLE) then -- Flag Divine Might player:addQuest(OUTLANDS,DIVINE_MIGHT); elseif (csid == 57) then -- Divine Might Repeat player:delQuest(OUTLANDS,DIVINE_MIGHT_REPEAT); player:addQuest(OUTLANDS,DIVINE_MIGHT_REPEAT); elseif (csid == 55 or csid == 59) then -- Turning in Divine Might or Repeat local reward = 0; if (option == 1) then reward = 14739; -- Suppanomimi elseif (option == 2) then reward = 14740; -- Knight's Earring elseif (option == 3) then reward = 14741; -- Abyssal Earring elseif (option == 4) then reward = 14742; -- Beastly Earring elseif (option == 5) then reward = 14743; -- Bushinomimi end if (reward ~= 0) then if (player:getFreeSlotsCount() >= 1 and player:hasItem(reward) == false) then player:addItem(reward); player:messageSpecial(ITEM_OBTAINED,reward); if (csid == 55) then player:completeQuest(OUTLANDS,DIVINE_MIGHT); else player:completeQuest(OUTLANDS,DIVINE_MIGHT_REPEAT); player:delKeyItem(MOONLIGHT_ORE); end player:setVar("DivineMight",0); player:setVar("DM_Earring",reward); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward); end end end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Sea_Serpent_Grotto/npcs/Hurr_the_Betrayer.lua
14
3619
----------------------------------- -- Area: Sea Serpent Grotto -- NPC: Hurr the Betrayer -- Type: Involved in the "Sahagin Key Quest" -- @zone 176 -- @pos 305.882 26.768 234.279 -- ----------------------------------- package.loaded["scripts/zones/Sea_Serpent_Grotto/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Sea_Serpent_Grotto/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getVar("SahaginKeyItems") == 1) then --If player was told to use 3 Mythril Beastcoins if (trade:hasItemQty(749,3) and trade:hasItemQty(1135,1)) then player:startEvent(0x006b); end elseif (player:getVar("SahaginKeyItems") == 2) then --If player was told to use a Gold Beastcoin if (trade:hasItemQty(748,1) and trade:hasItemQty(1135,1) and trade:getItemCount() == 2) then player:startEvent(0x006b); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("SahaginKeyProgress") == 2 and player:hasItem(1197) == false) then --If player has never before finished the quest player:startEvent(0x0069); player:setVar("SahaginKeyItems",1); elseif (player:getVar("SahaginKeyProgress") == 3 and player:getVar("SahaginKeyItems") == 0 and player:hasItem(1197) == false) then rand = math.random(2); --Setup random variable to determine which item will be required. if (rand == 1) then player:startEvent(0x0069); --Requires 3 Mythril Beastcoins and a Norg Shell player:setVar("SahaginKeyItems",1); elseif (rand == 2) then player:startEvent(0x006a); --Requires Gold Beastcoin and a Norg Shell player:setVar("SahaginKeyItems",2); end elseif (player:getVar("SahaginKeyProgress") == 3 and player:getVar("SahaginKeyItems") == 1) then player:startEvent(0x0069); --If player was told to use 3 Mythril Beastcoins elseif (player:getVar("SahaginKeyProgress") == 3 and player:getVar("SahaginKeyItems") == 2) then player:startEvent(0x006a); --If player was told to use a Gold Beastcoin elseif (player:getVar("SahaginKeyProgress") == 2 and player:hasItem(1197) == true) then player:startEvent(0x0068); --Doesn't offer the key again if the player has one else player:startEvent(0x0068); --Doesn't offer the key if the player hasn't spoken to the first 2 NPCs end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x006b and player:getVar("SahaginKeyProgress") == 2) then player:tradeComplete(); player:setVar("SahaginKeyProgress",3); --Mark the quest progress player:setVar("SahaginKeyItems",0); player:addItem(1197); -- Sahagin Key player:messageSpecial(ITEM_OBTAINED, 1197); elseif (csid == 0x006b and player:getVar("SahaginKeyProgress") == 3) then player:tradeComplete(); player:setVar("SahaginKeyItems",0); player:addItem(1197); -- Sahagin Key player:messageSpecial(ITEM_OBTAINED, 1197); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/bowl_of_ocean_soup.lua
12
1839
----------------------------------------- -- ID: 4285 -- Item: bowl_of_ocean_soup -- Food Effect: 4Hrs, All Races ----------------------------------------- -- HP +5% (cap 150) -- MP +5 -- DEX +4 -- Attack +14% (cap 90) -- Ranged Attack +14% (cap 90) -- HP recovered while healing +9 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4285); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 5); target:addMod(MOD_FOOD_HP_CAP, 150); target:addMod(MOD_MP, 5); target:addMod(MOD_DEX, 4); target:addMod(MOD_HPHEAL, 9); target:addMod(MOD_FOOD_ATTP, 14); target:addMod(MOD_FOOD_ATT_CAP, 90); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 90); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 5); target:delMod(MOD_FOOD_HP_CAP, 150); target:delMod(MOD_MP, 5); target:delMod(MOD_DEX, 4); target:delMod(MOD_HPHEAL, 9); target:delMod(MOD_FOOD_ATTP, 14); target:delMod(MOD_FOOD_ATT_CAP, 90); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 90); end;
gpl-3.0
Zomis/FactorioMods
search-engine_0.0.1/v2/gui/step_1_search_spec.lua
1
4307
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 }
mit
smanolache/kong
kong/dao/factory.lua
1
6193
local DAO = require "kong.dao.dao" local utils = require "kong.tools.utils" local Object = require "classic" local stringy = require "stringy" local ModelFactory = require "kong.dao.model_factory" local CORE_MODELS = {"apis", "consumers", "plugins", "nodes"} local _db local Factory = Object:extend() function Factory:__index(key) local daos = rawget(self, "daos") if daos and daos[key] then return daos[key] else return Factory[key] end end local function build_constraints(schemas) local all_constraints = {} for m_name, schema in pairs(schemas) do local constraints = {foreign = {}, unique = {}} for col, field in pairs(schema.fields) do if type(field.foreign) == "string" then local f_entity, f_field = unpack(stringy.split(field.foreign, ":")) if f_entity ~= nil and f_field ~= nil then local f_schema = schemas[f_entity] constraints.foreign[col] = { table = f_schema.table, schema = f_schema, col = f_field, f_entity = f_entity } end end if field.unique then constraints.unique[col] = { table = schema.table, schema = schema } end end all_constraints[m_name] = constraints end return all_constraints end local function load_daos(self, schemas, constraints, events_handler) for m_name, schema in pairs(schemas) do if constraints[m_name] ~= nil and constraints[m_name].foreign ~= nil then for col, f_constraint in pairs(constraints[m_name].foreign) do local parent_name = f_constraint.f_entity local parent_constraints = constraints[parent_name] if parent_constraints.cascade == nil then parent_constraints.cascade = {} end parent_constraints.cascade[m_name] = { table = schema.table, schema = schema, f_col = col, col = f_constraint.col } end end end for m_name, schema in pairs(schemas) do self.daos[m_name] = DAO(_db, ModelFactory(schema), schema, constraints[m_name], events_handler) end end function Factory:new(db_type, options, plugins, events_handler) self.db_type = db_type self.daos = {} self.properties = options self.plugins_names = plugins or {} local schemas = {} local DB = require("kong.dao."..db_type.."_db") _db = DB(options) for _, m_name in ipairs(CORE_MODELS) do schemas[m_name] = require("kong.dao.schemas."..m_name) end for _, plugin_name in ipairs(self.plugins_names) do local has_dao, plugin_daos = utils.load_module_if_exists("kong.plugins."..plugin_name..".dao."..self.db_type) if has_dao then for k, v in pairs(plugin_daos) do self.daos[k] = v(options) end end local has_schema, plugin_schemas = utils.load_module_if_exists("kong.plugins."..plugin_name..".daos") if has_schema then for k, v in pairs(plugin_schemas) do schemas[k] = v end end end local constraints = build_constraints(schemas) load_daos(self, schemas, constraints, events_handler) end function Factory:init() return _db:init() end -- Migrations function Factory:infos() return _db:infos() end function Factory:drop_schema() for _, dao in pairs(self.daos) do _db:drop_table(dao.table) end if _db.additional_tables then for _, v in ipairs(_db.additional_tables) do _db:drop_table(v) end end _db:drop_table("schema_migrations") end function Factory:truncate_tables() for _, dao in pairs(self.daos) do _db:truncate_table(dao.table) end if _db.additional_tables then for _, v in ipairs(_db.additional_tables) do _db:truncate_table(v) end end end function Factory:migrations_modules() local migrations = { core = require("kong.dao.migrations."..self.db_type) } for _, plugin_name in ipairs(self.plugins_names) do local ok, plugin_mig = utils.load_module_if_exists("kong.plugins."..plugin_name..".migrations."..self.db_type) if ok then migrations[plugin_name] = plugin_mig end end return migrations end function Factory:current_migrations() local rows, err = _db:current_migrations() if err then return nil, err end local cur_migrations = {} for _, row in ipairs(rows) do cur_migrations[row.id] = row.migrations end return cur_migrations end local function migrate(self, identifier, migrations_modules, cur_migrations, on_migrate, on_success) local migrations = migrations_modules[identifier] local recorded = cur_migrations[identifier] or {} local to_run = {} for i, mig in ipairs(migrations) do if mig.name ~= recorded[i] then to_run[#to_run + 1] = mig end end if #to_run > 0 and on_migrate ~= nil then -- we have some migrations to run on_migrate(identifier) end for _, migration in ipairs(to_run) do local err local mig_type = type(migration.up) if mig_type == "string" then err = _db:queries(migration.up) elseif mig_type == "function" then err = migration.up(_db, self.properties, self) end if err then return false, string.format("Error during migration %s: %s", migration.name, err) end -- record success err = _db:record_migration(identifier, migration.name) if err then return false, string.format("Error recording migration %s: %s", migration.name, err) end if on_success ~= nil then on_success(identifier, migration.name) end end return true end function Factory:run_migrations(on_migrate, on_success) local migrations_modules = self:migrations_modules() local cur_migrations, err = self:current_migrations() if err then return false, err end local ok, err = migrate(self, "core", migrations_modules, cur_migrations, on_migrate, on_success) if not ok then return false, err end for identifier in pairs(migrations_modules) do if identifier ~= "core" then ok, err = migrate(self, identifier, migrations_modules, cur_migrations, on_migrate, on_success) if not ok then return false, err end end end return true end return Factory
apache-2.0
Scavenge/darkstar
scripts/zones/Spire_of_Vahzl/npcs/_0n0.lua
22
1534
----------------------------------- -- Area: Spire of Vahzl -- NPC: Web of Recollection ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; else player:messageSpecial(FAINT_SCRAPING); return 1; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; else return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
LuaDist2/lualibrarytemplate
luacmodule.lua
2
2496
#!/usr/bin/env lua local lfs = require("lfs") local datafile = require("lualibrarytemplate.dummy") --local datafile = require("datafile") -- luarocks agnostic resource loader local windows = (package.config:sub(1,1) == "\\") -- copies a file, each line with a match for 'pattern' will be handed to 'handler' -- and the result returned will be used as the line in the target file. -- returns the number of matches handled local filehandler=function(source, target, pattern, handler) local s = assert(datafile.open(source, "r")) local t = assert(io.open(target, "w")) local m = 0 local line = s:read("*l") while line do if pattern and line:match(pattern) then line = handler(line) m = m + 1 end t:write(line.."\n") line = s:read("*l") end s:close() t:close() return m end --============================= -- get going here local target = arg[1] if not target then print"Lua C module generator" print"" print"USAGE: luacmodule [modulename]" print"" print"Generates a new Lua C module by name [modulename]. A new directory in the" print"current path will be created by the same name, which will contain the source." print"" os.exit() end assert(lfs.mkdir(target)) assert(lfs.chdir(target)) -- lua_template.c filehandler("template/lua_template.c", target..".c", "lua_template", function(line) return line:gsub("lua_template", target) end) -- lua_template.h filehandler("template/lua_template.h", target..".h", "lua_template", function(line) return line:gsub("lua_template", target) end) -- readme.md; copy verbatim filehandler("template/readme.md", "readme.md") -- Rockspec filehandler("template/lua_template-scm-1.rockspec", target.."-scm-1.rockspec", "lua_template", function(line) return line:gsub("lua_template", target) end) if windows then -- VS project filehandler("template/lua_template.vcxproj", target..".vcxproj", "lua_template", function(line) return line:gsub("lua_template", target) end) -- VS project filter file filehandler("template/lua_template.vcxproj.filters", target..".vcxproj.filters", "lua_template", function(line) return line:gsub("lua_template", target) end) -- VS/SDK console compilation batch file filehandler("template/compile.bat", "compile.bat", "lua_template", function(line) return line:gsub("lua_template", target) end) end print("Succesfully generated project; "..target)
mit
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/unit_snipers.lua
2
6698
function widget:GetInfo() return { name = "Sniper Finder 2", desc = "sniper on the roof!", license = "PD", layer = -2, enabled = false, } end local sniperDefID = WeaponDefNames.armsnipe_shockrifle.id local sniperRange = WeaponDefNames.armsnipe_shockrifle.range local basicTacnuke = {b = 900, r = 300, l = 15} local empTacnuke = {b = 2500, r = 700, l = 200} -- fairly asspulled but roughly works local tacnukeRanges = { [WeaponDefNames.tacnuke_weapon.id] = basicTacnuke, [WeaponDefNames.napalmmissile_weapon.id] = basicTacnuke, [WeaponDefNames.empmissile_emp_weapon.id] = empTacnuke, [WeaponDefNames.seismic_seismic_weapon.id] = basicTacnuke, } local tacnukeRange = WeaponDefNames.tacnuke_weapon.range local berthas = { [WeaponDefNames.armbrtha_plasma.id] = true, -- two are enough to triangulate [WeaponDefNames.raveparty_red_killer.id] = true, [WeaponDefNames.raveparty_orange_roaster.id] = true, } local foundBerthas = {} local potentialBerthas = {} local enabledSnipers local enabledTacnukes local enabledBerthas local enabledAny local myTeamID local spectating local function RebuildGlobals() spectating = Spring.GetSpectatingState () enabledAny = (not spectating) and (enabledSnipers or enabledTacnukes or enabledBerthas) myTeamID = Spring.GetMyTeamID() end options_path = 'Game/Unit Marker' options_order = { 'trace_snipers', 'trace_tacnukes', 'trace_berthas' } options = { trace_snipers = { name = "Trace snipers", desc = "Approximate location of snipers based on shot trajectory.", type = 'bool', value = false, noHotkey = true, OnChange = function (self) enabledSnipers = self.value RebuildGlobals() end, }, trace_tacnukes = { name = "Trace tacnukes", desc = "Approximate location of tacnuke silo based on shot trajectory.", type = 'bool', value = false, noHotkey = true, OnChange = function (self) enabledTacnukes = self.value RebuildGlobals() end, }, trace_berthas = { name = "Trace berthas", desc = "Approximate location of long range plasma artillery based on shot trajectory.", type = 'bool', value = false, noHotkey = true, OnChange = function (self) enabledBerthas = self.value RebuildGlobals() end, }, } local abs = math.abs local max = math.max local spAreTeamsAllied = Spring.AreTeamsAllied local spGetGroundHeight = Spring.GetGroundHeight local spGetProjectileDefID = Spring.GetProjectileDefID local spGetProjectileTeamID = Spring.GetProjectileTeamID local spGetProjectilePosition = Spring.GetProjectilePosition local spGetProjectilesInRectangle = Spring.GetProjectilesInRectangle local count = 0 local bullets = {} local bulletsByID = {} function widget:Initialize() RebuildGlobals() end function widget:PlayerChanged () RebuildGlobals() end function widget:GameFrame (n) if not enabledAny then return end for i = 1, count do local bulletID = bullets[i] local bullet = bulletsByID[bulletID] bullet.alive = false end local projectiles = spGetProjectilesInRectangle (0, 0, Game.mapSizeX, Game.mapSizeZ) for i = 1, #projectiles do local projID = projectiles[i] local teamID = spGetProjectileTeamID (projID) local defID = spGetProjectileDefID (projID) if teamID and not spAreTeamsAllied(teamID, myTeamID) and defID and ((enabledSnipers and defID == sniperDefID) or (enabledTacnukes and tacnukeRanges[defID]) or (enabledBerthas and berthas[defID])) then local bullet = bulletsByID[projID] local x, y, z = spGetProjectilePosition (projID) if bullet then bullet.alive = true bullet.x2 = x bullet.y2 = y bullet.z2 = z else count = count + 1 bullets[count] = projID local newBullet = { x1 = x, x2 = x, y1 = y, y2 = y, z1 = z, z2 = z, alive = true, defID = defID, unitID = Spring.GetProjectileOwnerID(projID) } bulletsByID[projID] = newBullet end end end local i = 1 while i <= count do local bulletID = bullets[i] local bullet = bulletsByID[bulletID] if not bullet.alive then local lastBulletID = bullets[count] bullets[i] = lastBulletID bullets[count] = nil count = count - 1 bulletsByID[bulletID] = nil local x = bullet.x2 local y = bullet.y2 local z = bullet.z2 local xx = bullet.x1 - x local yy = bullet.y1 - y local zz = bullet.z1 - z local angle = math.atan2(zz, xx) local dx = math.cos (angle) local dz = math.sin (angle) local defID = bullet.defID if defID == sniperDefID then local tx = x + sniperRange * dx local tz = z + sniperRange * dz local ty = spGetGroundHeight (tx, tz) + 10 Spring.MarkerAddLine (x, y, z, tx, ty, tz) Spring.MarkerAddPoint (tx, ty, tz, "!") elseif tacnukeRanges[defID] then local dy = yy / math.sqrt(xx * xx + zz * zz) local found = false local heightData = tacnukeRanges[defID] local wantedHeight = heightData.b + heightData.r * math.tan((math.atan(dy) / 2) + math.pi / 4) local leeway = heightData.l local consecutiveX, consecutiveZ for i = 0, tacnukeRange, 20 do local tx = x + i * dx local ty = y + i * dy local tz = z + i * dz if tx < 0 or tz < 0 or tx >= Game.mapSizeX or tz >= Game.mapSizeZ then break end local h = max(0, spGetGroundHeight(tx, tz)) if (abs (ty - h - wantedHeight) < leeway) then if not consecutiveX then found = true consecutiveX = tx consecutiveZ = tz end else if consecutiveX then Spring.MarkerAddLine (consecutiveX, spGetGroundHeight(consecutiveX, consecutiveZ), consecutiveZ, tx, spGetGroundHeight(tx, tz), tz) local avgX = (consecutiveX + tx) / 2 local avgZ = (consecutiveZ + tz) / 2 Spring.MarkerAddPoint (avgX, spGetGroundHeight(avgX, avgZ), avgZ, "!") consecutiveX = nil end end end if not found then local tx = x + dx * tacnukeRange local tz = z + dz * tacnukeRange local ty = spGetGroundHeight(tx, tz) + 5 Spring.MarkerAddPoint (tx, ty, tz, "!") Spring.MarkerAddLine (x, y, z, tx, ty, tz) end else -- elseif berthas[defID] then local bertha = bullet.unitID if bertha then if potentialBerthas[bertha] then local previousBullet = potentialBerthas[bertha] potentialBerthas[bertha] = nil local tx, tz = 123, 123 -- FIXME: i forgot how to intersect and dont have internet atm to check --Spring.MarkerAddPoint (tx, spGetGroundHeight(tx, tz), tz, "!") foundBerthas[bertha] = true elseif not foundBerthas[bertha] then potentialBerthas[bertha] = bullet end end end else i = i + 1 end end end
gpl-2.0
Brenin/PJ-3100
Working Launchers/Games/Stepmania/StepMania 5/Themes/default/Graphics/ScreenSelectMusic DifficultyDisplay/default.lua
1
2551
local t = Def.ActorFrame {}; local function GetEdits( in_Song, in_StepsType ) if in_Song then local sSong = in_Song; local sCurrentStyle = GAMESTATE:GetCurrentStyle(); local sStepsType = in_StepsType; local iNumEdits = 0; if sSong:HasEdits( sStepsType ) then local tAllSteps = sSong:GetAllSteps(); for i,Step in pairs(tAllSteps) do if Step:IsAnEdit() and Step:GetStepsType() == sStepsType then iNumEdits = iNumEdits + 1; end end return iNumEdits; else return iNumEdits; end else return 0; end end; t[#t+1] = Def.ActorFrame { LoadActor("_Background"); }; -- for idx,diff in pairs(Difficulty) do local sDifficulty = ToEnumShortString( diff ); local tLocation = { Beginner = 32*-1.25, Easy = 32*-0.25, Medium = 32*0.75, Hard = 32*1.75, Challenge = 32*2.75, Edit = 32*4.75, }; t[#t+1] = Def.ActorFrame { SetCommand=function(self) local c = self:GetChildren(); -- local Bar = self:GetChild("Bar"); -- local Meter = self:GetChild("Meter" local song = GAMESTATE:GetCurrentSong() local bHasStepsTypeAndDifficulty = false; local meter = ""; if song then local st = GAMESTATE:GetCurrentStyle():GetStepsType() bHasStepsTypeAndDifficulty = song:HasStepsTypeAndDifficulty( st, diff ); local steps = song:GetOneSteps( st, diff ); if steps then meter = steps:GetMeter(); append = "" -- if diff == 'Difficulty_Edit' then meter = GetEdits( song, st ); append = ( GetEdits( song, st ) > 1 ) and "Edits" or "Edit" meter = meter .. " " .. append end end end c.Meter:settext( meter ); self:playcommand( bHasStepsTypeAndDifficulty and "Show" or "Hide" ); end; CurrentSongChangedMessageCommand=cmd(playcommand,"Set"); -- LoadActor("_barpeice " .. sDifficulty ) .. { Name="BarPeice"; ShowCommand=cmd(stoptweening;linear,0.1;diffuse,CustomDifficultyToColor( sDifficulty )); HideCommand=cmd(stoptweening;decelerate,0.05;diffuse,CustomDifficultyToDarkColor( sDifficulty )); InitCommand=cmd(diffuse,CustomDifficultyToColor( sDifficulty )); }; LoadFont("StepsDisplay","Meter") .. { Name="Meter"; Text=(sDifficulty == "Edit") and "0 Edits" or "0"; ShowCommand=cmd(stoptweening;linear,0.1;diffuse,CustomDifficultyToColor( sDifficulty )); HideCommand=cmd(stoptweening;decelerate,0.05;diffuse,CustomDifficultyToDarkColor( sDifficulty )); InitCommand=cmd(x,-64-8+tLocation[sDifficulty];shadowlength,1;zoom,0.75;diffuse,CustomDifficultyToColor( sDifficulty )); }; }; end return t
mit
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/dbg_ballisticcalculator.lua
17
19308
function widget:GetInfo() return { name = "Ballistic Calculator", desc = "Simulate and plot weapon's ballistic range & calculate Spring's weapon range modification. For weapon setting testing. \n\nInstruction: select any unit, press attack (trajectory will be drawn), follow on-screen helptext, BLUE circle is weapon-range-mod, YELLOW circle is ballistic range.", author = "msafwan", --using component from "gui_jumpjets.lua" by quantum, date = "April 5 2014", license = "GNU GPL, v2 or later", layer = 10000, enabled = false, } end local customMyGravity = 130 local customWeaponVelocity = 232 local flightTime =0 local highTrajectory = 0 local maximumRange = 0 local apexHeight = 0 local currRange = 0 local customHeightMod = 1 local customCylinderTargeting = 1 local customMaxRange = 620 local customHeightBoost = -1 local moddedMaxRange = 620 local weaponName = "Cannon" local spGetActiveCommand = Spring.GetActiveCommand local spGetMouseState = Spring.GetMouseState local spTraceScreenRay = Spring.TraceScreenRay local spGetModKeyState = Spring.GetModKeyState local spGetSelectedUnits = Spring.GetSelectedUnits local spGetCommandQueue = Spring.GetCommandQueue function widget:DrawWorld() local _, activeCommand = spGetActiveCommand() if (activeCommand == CMD.ATTACK) then local mouseX, mouseY = spGetMouseState() local category, arg = spTraceScreenRay(mouseX, mouseY) local _, _, _, shift = spGetModKeyState() local units = spGetSelectedUnits() for i=1,#units do DrawMouseArc(units[i], shift, category == 'ground' and arg) end end end local spGetUnitPosition = Spring.GetUnitPosition local cachedResult = {nil,nil,nil,nil,nil,nil} local calculateNow= false local _2DDist = 0 local hide = false function DrawMouseArc(unitID, shift, groundPos) if (not groundPos) then return end local queue = spGetCommandQueue(unitID) local deltaV = customWeaponVelocity local customRange = customMaxRange if (not queue or #queue == 0 or not shift) then local unitPos = {spGetUnitPosition(unitID)} _2DDist = cachedResult[5] or 0 local maxRange = cachedResult[6] or 0 if not hide then if calculateNow then maxRange,_ = CalculateBallisticConstant(deltaV,customMyGravity,nil,unitPos, groundPos) _2DDist = GetDist2D(unitPos, groundPos) cachedResult[6]= maxRange cachedResult[5]= _2DDist end DrawArc(unitID, unitPos, groundPos, maxRange,_2DDist, deltaV, customMyGravity) end moddedMaxRange = DrawModdedRange(unitPos, groundPos,deltaV, customMyGravity,customRange) maximumRange = maxRange calculateNow= false --wait for GameFrame() end end function GetDist2D(a, b) return ((a[1] - b[1])^2 + (a[3] - b[3])^2)^0.5 end local spGetGroundHeight = Spring.GetGroundHeight function CalculateBallisticConstant(deltaV,myGravity,heightDiff,start, finish) local angle = math.pi/4 --use test range of 45 degree for optimal launch --determine maximum range & time local xVel = math.cos(angle)*deltaV --horizontal portion local yVel = math.sin(angle)*deltaV --vertical portion local t = nil local yDist = heightDiff or start[2] - spGetGroundHeight(finish[1],finish[3]) -- set vertical height of 0 (a round trip from 0 height to 0 height) local a = myGravity -- 0 = yVel*t - a*t*t/2 --this is the basic equation of motion for vertical motion, we set distance to 0 or yDist (this have 2 meaning: either is launching from ground or is hitting ground) then we find solution for time (t) using a quadratic solver -- 0 = (yVel)*t - (a/2)*t*t --^same equation as above rearranged to highlight time (t) local discriminant =(yVel^2 - 4*(-a/2)*(yDist))^0.5 local denominator = 2*(-a/2) local t1 = (-yVel + discriminant)/denominator ---formula for finding root for quadratic equation (quadratic solver). Ref: http://www.sosmath.com/algebra/quadraticeq/quadraformula/summary/summary.html local t2 = (-yVel - discriminant)/denominator xDist1 = xVel*t1 --distance travelled horizontally in "t" amount of time xDist2 = xVel*t2 local maxRange = nil if xDist1>= xDist2 then maxRange=xDist1 --maximum range t=t1 --flight time else maxRange=xDist2 t=t2 end -- --Non-changing value so far: maxRange. This depends on: mapGravity and deltaV. -- return maxRange, t --return maximum range and flight time. end local glVertex = gl.Vertex local glColor = gl.Color local glDrawGroundCircle = gl.DrawGroundCircle local glBeginEnd = gl.BeginEnd local glLineStipple = gl.LineStipple local GL_LINE_STRIP = GL.LINE_STRIP local yellow = { 1, 1, 0.5, 1} local green = {0.5, 1, 0.5, 1} local noSolution = false function DrawArc(unitID, start, finish, range, dist, deltaV, myGravity) --TODO: cache the correct trajectory, don't calculate it every DrawWorld frame. Is CPU intensive. --x, y, z direction to target local vector = {} for i=1, 3 do vector[i] = finish[i] - start[i] end --draw max range local col = yellow glColor(col[1], col[2], col[3], col[4]) glDrawGroundCircle(start[1], start[2], start[3], range, 100) --calculate correct trajectory local correctAngle= cachedResult[1] or 0 local yVelocity = cachedResult[2] or 0 local horizontalSpeed = cachedResult[3] or 0 if calculateNow then --let GameFrame() control when to calculate this rather than letting it to DrawWorld() local goodValue = {deviation= 999} local searchPattern = {startAngle = -1.571, endAngle = 0.707, stepAngle = 0.005} if highTrajectory == 1 then searchPattern= {startAngle = 0.707, endAngle = 1.57, stepAngle = 0.005} end for i= searchPattern.startAngle ,searchPattern.endAngle, searchPattern.stepAngle do local angle = i local xVel = math.cos(angle)*deltaV local yVel = math.sin(angle)*deltaV local yDist = start[2] - spGetGroundHeight(finish[1],finish[3]) local a = myGravity local t1 = nil local t2 = nil -- yDist = yVel*t - a*t*t/2 -- 0 = -yDist + (yVel)*t - (a/2)*t*t local discriminant =(yVel^2 - 4*(-a/2)*(yDist))^0.5 local denominator = 2*(-a/2) t1 = (-yVel + discriminant)/denominator t2 = (-yVel - discriminant)/denominator local xDist1 = xVel*t1 local xDist2 = xVel*t2 if math.abs(xDist1 - dist) <= goodValue.deviation and t1>=0 then goodValue[2] = angle goodValue[3] = xVel goodValue[4] = yVel goodValue[5]= t1 goodValue.deviation = math.abs(xDist1 - dist) currRange = xDist1 --Note: --Formula to find root is: t = (-b +- (b*b - 4*(a)*(c))^0.5)/(2*a) ..... a & b & c is: 0= c + b*t - a*t*t --but when it have only 1 solution (which only happen at the top-most of the arch/trajectory, the discriminant become 0, simplifying the equation to: t = -b /(2*a) local flightTimeApex = -yVel/(2*(-a/2)) --time to apex^ apexHeight = yVel*flightTimeApex - a*flightTimeApex*flightTimeApex/2 --from: yDist = yVel*t - a*t*t/2 elseif math.abs(xDist2 - dist) <= goodValue.deviation and t2>=0 then goodValue[2] = angle goodValue[3] = xVel goodValue[4] = yVel goodValue[5]= t2 goodValue.deviation = math.abs(xDist2 - dist) currRange = xDist2 local flightTimeApex = -yVel/(2*(-a/2)) --time to apex^ apexHeight = yVel*flightTimeApex - a*flightTimeApex*flightTimeApex/2 --from: yDist = yVel*t - a*t*t/2 end end correctAngle = goodValue[2] or 1.57 horizontalSpeed = goodValue[3] yVelocity = goodValue[4] flightTime= goodValue[5] or 0 cachedResult[1] = correctAngle --update cache cachedResult[2] = yVelocity cachedResult[3] = horizontalSpeed end if flightTime == 0 then -- Spring.Echo("Ballistic plot error: No solution found") noSolution = true return end noSolution = false --draw real time trajectory gl.DepthTest (true) glLineStipple('') glBeginEnd(GL_LINE_STRIP, DrawLoop, start, vector, green, dist, flightTime, yVelocity, horizontalSpeed, myGravity) glLineStipple(false) gl.DepthTest(false) glColor(1, 1, 1, 1) end local blue = {0.5, 1, 1, 1} function DrawModdedRange(start, finish, deltaV, myGravity, customRange) --draw modded max range local moddedRange = cachedResult[4] or 0 if calculateNow then --30 per second moddedRange = CalculateModdedMaxRange(start, finish,deltaV,myGravity,customRange) cachedResult[4] = moddedRange end local col = blue glColor(col[1], col[2], col[3], col[4]) glDrawGroundCircle(start[1], start[2], start[3], moddedRange, 100) return moddedRange end local modType = 0 function CalculateModdedMaxRange(start,finish,deltaV,myGravity,customRange) local heightDiff = start[2] - finish[2] local heightModded = (heightDiff)*customHeightMod if modType == 0 then --Ballistic -- Spring.Echo(scaleDown) local maxFlatRange = CalculateBallisticConstant(deltaV,myGravity,0) local scaleDown = customRange/maxFlatRange --Example: UpdateRange() in Spring\rts\Sim\Weapons\Cannon.cpp local heightBoostFactor = customHeightBoost if heightBoostFactor < 0 and scaleDown > 0 then heightBoostFactor = (2 - scaleDown) / math.sqrt(scaleDown) --such that: heightBoostFactor == 1 when scaleDown == 1 end heightModded = heightModded*heightBoostFactor local moddedRange = CalculateBallisticConstant(deltaV,myGravity,heightModded) return moddedRange*scaleDown --Example: GetRange2D() in Spring\rts\Sim\Weapons\Cannon.cpp elseif modType == 1 then --Sphere return math.sqrt(customRange^2 - heightModded^2) --Pythagoras theorem. Example: GetRange2D() in Spring\rts\Sim\Weapons\Weapon.cpp elseif modType == 2 then --Cylinder return customRange - heightModded*customHeightMod --Example: GetRange2D() in Spring\rts\Sim\Weapons\StarburstLauncher.cpp --Note: for unknown reason we must "Minus the heightMod" instead of adding it. This is the opposite of what shown on the source-code, but ingame test suggest "Minus heightMod" and not adding. elseif modType == 3 then --Pure Cylinder if customCylinderTargeting * customRange > math.abs(heightModded) then return customRange --Example: TestRange() in Spring\rts\Sim\Weapons\Weapon.cpp else return 0 end end return 0 end local lineProgress = 0 function DrawLoop(start, vector, color,dist, flightTime, yVelocity, horizontalSpeed, myGravity) glColor(color[1], color[2], color[3], color[4]) local currentProjectilePosition = lineProgress --breakdown horizontal speed into x and z component. local directionxz_radian = math.atan2(vector[3]/dist, vector[1]/dist) local xVelocity = math.cos(directionxz_radian)*horizontalSpeed local zVelocity = math.sin(directionxz_radian)*horizontalSpeed local simStep = 0.017 --set resolution of the plot for i=0, currentProjectilePosition,simStep do local x = start[1] + xVelocity*i local y = start[2] + (yVelocity)*i - (myGravity/2)*i*i local z = start[3] + zVelocity*i glVertex(x, y, z) end --lineProgress = lineProgress + 1sec, update at GameFrame() if lineProgress >= flightTime then lineProgress = 0 end end local lastUpdate=0 function widget:GameFrame(n) lineProgress = lineProgress + (1/30) calculateNow =true -- if n- lastUpdate >= 30 then -- Spring.Echo("myGravity: ".. string.format("%.3f", customMyGravity).. " ("..string.format("%.3f", customMyGravity/888.888888) .. " Spring91), weaponVelocity: ".. string.format("%.3f", customWeaponVelocity) .. ", flightTime: " .. string.format("%.3f", flightTime) .." ,apexHeight: " .. string.format("%.3f", apexHeight) .. " , currentRange: " .. string.format("%.3f", currRange) .. " ,maximumRange: ".. string.format("%.3f", maximumRange)) -- lastUpdate = n -- end end local modTypeBak = 0 function widget:DrawScreen() local currCmd = Spring.GetActiveCommand() --remember current command local activeCmd = Spring.GetActiveCmdDesc(currCmd) if activeCmd and activeCmd.id == CMD.ATTACK then local mx,my = Spring.GetMouseState() local k = -25 gl.Text("##Range Mod##", mx+40, my+k, 10,"") k = k - 10 gl.Text("\"[\"&\"]\": show different MaxRange", mx+40, my+k, 10,"") k = k - 10 gl.Text("\";\"&\"'\": show different HeightMod", mx+40, my+k, 10,"") k = k - 10 gl.Text("\".\"&\"/\": show different CylinderTargeting", mx+40, my+k, 10,"") k = k - 10 gl.Text("\"\\\": show different TargetingMod", mx+40, my+k, 10,"") k = k - 10 gl.Text("customMaxRange: " .. string.format("%.3f", customMaxRange), mx+40, my+k, 10,"") k = k - 10 gl.Text("customHeightMod: " .. string.format("%.3f", customHeightMod), mx+40, my+k, 10,"") k = k - 10 gl.Text("customCylinderTargeting: " .. string.format("%.3f", customCylinderTargeting) .. (customCylinderTargeting<=0 and " (base on weapontype)" or "(strict cylinder)"), mx+40, my+k, 10,"") k = k - 10 gl.Text("moddedMaxRange: " .. string.format("%.3f", moddedMaxRange), mx+40, my+k, 10,"") if modType== modTypeBak then k = k - 10 gl.Text("weaponName: " .. weaponName .. " (default:" ..(modType==0 and "Ballistic)" or (modType==1 and "Sphere)") or "Cylinder)"), mx+40, my+k, 10,"") else k = k - 10 gl.Text("targetMod: " .. (modType==0 and " Ballistic" or (modType==1 and " Sphere") or (modType==2 and " Cylinder") or " Strict Cylinder"), mx+40, my+k, 10,"") end -- if modType==0 then -- k = k - 10 -- gl.Text("customHeightBoost: " .. string.format("%.3f", customHeightBoost), mx+40, my+k, 10,"") -- end gl.Text("\"M\": load value from unit", mx+40, my-5, 10,"") gl.Text("2D distance: " .. string.format("%.3f", _2DDist), mx+40, my+5, 10,"") if not noSolution and not hide then local y = 25 --From gui_lasso_terraform.lua gl.Text("myGravity: ".. string.format("%.3f", customMyGravity).. " (tag value:"..string.format("%.3f", customMyGravity/888.888888) .. " Spring91)", mx+40, my+y, 10,"") y = y + 10 gl.Text("weaponVelocity: ".. string.format("%.3f", customWeaponVelocity), mx+40, my+y, 10,"") y = y + 10 gl.Text("flightTime: " .. string.format("%.3f", flightTime), mx+40, my+y, 10,"") y = y + 10 gl.Text("apexHeight: " .. string.format("%.3f", apexHeight), mx+40, my+y, 10,"") -- y = y + 10 -- gl.Text("currentRange: " .. string.format("%.3f", currRange), mx+40, my+y, 10,"") y = y + 10 gl.Text("maximumRange: ".. string.format("%.3f", maximumRange) .. " (45degree)", mx+40, my+y, 10,"") y = y + 10 gl.Text("\",\": toggle trajectory ("..(highTrajectory==1 and "high)" or "low)"), mx+40, my+y, 10,"") y = y + 10 gl.Text("\"K\"&\"L\": show different weapon velocity", mx+40, my+y, 10,"") y = y + 10 gl.Text("\"O\"&\"P\": show different weapon gravity", mx+40, my+y, 10,"") y = y + 10 gl.Text("\"N\": hide/show ballistic plot", mx+40, my+y, 10,"") y = y + 10 gl.Text("##Ballistic##", mx+40, my+y, 10,"") else local y = 25 gl.Text("##Cannot plot ballistic trajectory##", mx+40, my+y, 10,"") y = y + 10 gl.Text("weaponVelocity: ".. string.format("%.3f", customWeaponVelocity), mx+40, my+y, 10,"") y = y + 10 gl.Text("myGravity: ".. string.format("%.3f", customMyGravity).. " (tag value:"..string.format("%.3f", customMyGravity/888.888888) .. " Spring91)", mx+40, my+y, 10,"") y = y + 10 gl.Text("\"N\": hide/show ballistic plot", mx+40, my+y, 10,"") end end end ---using code from central_build_AI.lua by Troy H. Cheek local incGravity = string.byte( "p" ) --"i" "o", "k" "l", "m" local decGravity = string.byte( "o" ) local incVelocity = string.byte( "l" ) local decVelocity = string.byte( "k" ) local trajectory = string.byte( "," ) local loadUnits = string.byte( "m" ) local incMaxRange = string.byte( "]" ) --"i" "o", "k" "l", "m" local decMaxRange = string.byte( "[" ) local incHeightMod = string.byte( "'" ) local decHeightMod = string.byte( ";" ) local incCylinder = string.byte( "/" ) local decCylinder = string.byte( "." ) local targetingMod = string.byte( "\\" ) local hideBallisticPlot = string.byte( "n" ) function widget:KeyPress(key, mods, isRepeat) if ( key == incGravity ) then customMyGravity = customMyGravity + ((isRepeat and 1) or 0.1) return true elseif ( key == decGravity ) then customMyGravity = customMyGravity - ((isRepeat and 1) or 0.1) return true elseif ( key == incVelocity ) then customWeaponVelocity = customWeaponVelocity + ((isRepeat and 10) or 1) return true elseif ( key == decVelocity ) then customWeaponVelocity = customWeaponVelocity - ((isRepeat and 10) or 1) return true elseif ( key == trajectory ) then highTrajectory = highTrajectory + 1 highTrajectory = highTrajectory%2 return true elseif ( key == incMaxRange ) then customMaxRange = customMaxRange + ((isRepeat and 10) or 1) return true elseif ( key == decMaxRange ) then customMaxRange = customMaxRange - ((isRepeat and 10) or 1) return true elseif ( key == incHeightMod ) then customHeightMod = customHeightMod + ((isRepeat and 0.1) or 0.01) return true elseif ( key == decHeightMod ) then customHeightMod = customHeightMod - ((isRepeat and 0.1) or 0.01) return true elseif ( key == hideBallisticPlot ) then hide = not hide return true elseif ( key == targetingMod ) then modType = modType + 1 modType = modType % 4 if modType == 3 then customCylinderTargeting = 3 else customCylinderTargeting = 0 end return true elseif ( key == incCylinder ) then customCylinderTargeting = customCylinderTargeting + ((isRepeat and 0.1) or 0.01) if customCylinderTargeting >= 0.01 then modType = 3 --pure cylinder (no heightMod) else modType = modTypeBak end return true elseif ( key == decCylinder ) then customCylinderTargeting = customCylinderTargeting - ((isRepeat and 0.1) or 0.01) if customCylinderTargeting < 0.01 then modType = modTypeBak else modType = 3 --pure cylinder (no heightMod) end return true elseif (key == loadUnits ) then local selectedUnits = Spring.GetSelectedUnits() if selectedUnits and #selectedUnits> 0 then local unitDefID = Spring.GetUnitDefID(selectedUnits[1]) local weaponList = UnitDefs[unitDefID].weapons if #weaponList > 0 then local weaponDefID = weaponList[1].weaponDef local weaponDef = WeaponDefs[weaponDefID] customMyGravity = (weaponDef.myGravity > 0 and weaponDef.myGravity*888.888888) or (Game.gravity) or 0 customWeaponVelocity = weaponDef.projectilespeed*30 customMaxRange = weaponDef.range customHeightMod = weaponDef.heightMod customCylinderTargeting = weaponDef.cylinderTargeting customHeightBoost = weaponDef.heightBoostFactor GetRangeModType(weaponDef) if customCylinderTargeting >= 0.01 then --Strict Cylinder modType = 3 --pure cylinder (no heightMod) end end end return true end end function GetRangeModType(weaponDef) weaponName = weaponDef.type if (weaponDef.type == "Cannon") or (weaponDef.type == "EmgCannon") or (weaponDef.type == "DGun" and weaponDef.gravityAffected) or (weaponDef.type == "AircraftBomb") then --Ballistic modType = 0 modTypeBak = 0 elseif (weaponDef.type == "LaserCannon" or weaponDef.type == "BeamLaser" or weaponDef.type == "Melee" or weaponDef.type == "Flame" or weaponDef.type == "LightningCannon" or (weaponDef.type == "DGun" and not weaponDef.gravityAffected)) then --Sphere modType = 1 modTypeBak = 1 elseif (weaponDef.type == "MissileLauncher" or weaponDef.type == "StarburstLauncher" or weaponDef.type == "TorpedoLauncher") then --Cylinder modType = 2 modTypeBak = 2 end end
gpl-2.0
BlockMen/minetest_next
mods/default/items/books.lua
1
3152
local function book_on_use(itemstack, user, pointed_thing) local player_name = user:get_player_name() local data = minetest.deserialize(itemstack:get_metadata()) local title, text, owner = "", "", player_name if data then title, text, owner = data.title, data.text, data.owner end local formspec if owner == player_name then formspec = "size[8,8]"..default.gui_bg.. "field[0.5,1;7.5,0;title;Title:;".. minetest.formspec_escape(title).."]".. "textarea[0.5,1.5;7.5,7;text;Contents:;".. minetest.formspec_escape(text).."]".. "button_exit[2.5,7.5;3,1;save;Save]" else formspec = "size[8,8]"..default.gui_bg.. "label[0.5,0.5;by "..owner.."]".. "label[0.5,0;"..minetest.formspec_escape(title).."]".. "textarea[0.5,1.5;7.5,7;;"..minetest.formspec_escape(text)..";]" end minetest.show_formspec(user:get_player_name(), "default:book", formspec) end minetest.register_on_player_receive_fields(function(player, form_name, fields) if form_name ~= "default:book" or not fields.save or fields.title == "" or fields.text == "" then return end local inv = player:get_inventory() local stack = player:get_wielded_item() local new_stack, data if stack:get_name() ~= "default:book_written" then local count = stack:get_count() if count == 1 then stack:set_name("default:book_written") else stack:set_count(count - 1) new_stack = ItemStack("default:book_written") end else data = minetest.deserialize(stack:get_metadata()) end if not data then data = {} end data.title = fields.title data.text = fields.text data.owner = player:get_player_name() local data_str = minetest.serialize(data) if new_stack then new_stack:set_metadata(data_str) if inv:room_for_item("main", new_stack) then inv:add_item("main", new_stack) else minetest.add_item(player:getpos(), new_stack) end else stack:set_metadata(data_str) end player:set_wielded_item(stack) end) minetest.register_craftitem("default:book", { description = "Book", inventory_image = "default_book.png", groups = {book=1,fuel=2}, on_use = book_on_use, }) minetest.register_craftitem("default:book_written", { description = "Book with Text", inventory_image = "default_book_written.png", groups = {book=1, not_in_creative_inventory=1, fuel=2}, stack_max = 1, on_use = book_on_use, }) -- Copy books minetest.register_craft({ type = "shapeless", output = "default:book_written", recipe = { "default:book", "default:book_written" } }) minetest.register_on_craft(function(itemstack, player, old_craft_grid, craft_inv) if itemstack:get_name() ~= "default:book_written" then return end local copy = ItemStack("default:book_written") local original local index for i = 1, player:get_inventory():get_size("craft") do if old_craft_grid[i]:get_name() == "default:book_written" then original = old_craft_grid[i] index = i end end if not original then return end local copymeta = original:get_metadata() -- copy of the book held by player's mouse cursor itemstack:set_metadata(copymeta) -- put the book with metadata back in the craft grid craft_inv:set_stack("craft", index, original) end)
gpl-3.0
Scavenge/darkstar
scripts/commands/addquest.lua
12
1546
--------------------------------------------------------------------------------------------------- -- func: addquest <logID> <questID> <player> -- desc: Adds a quest to the given targets log. --------------------------------------------------------------------------------------------------- require("scripts/globals/quests"); cmdprops = { permission = 1, parameters = "sss" }; function onTrigger(player, logId, questId, target) local logName; logId = tonumber(logId) or _G[logId]; if ((type(logId) == "table")) then logName = logId.full_name; logId = logId.quest_log; end questId = tonumber(questId) or _G[questId]; if (questId == nil or logId == nil) then player:PrintToPlayer( "You must enter a valid log ID and quest ID!" ); player:PrintToPlayer( "@addquest <logID> <questID> <player>" ); return; end if (target == nil) then target = player:getName(); end local targ = GetPlayerByName(target); if (targ ~= nil) then targ:addQuest( logId, questId ); if (logName) then player:PrintToPlayer( string.format( "Added %s Quest with ID %u for %s", logName, questId, target ) ); else player:PrintToPlayer( string.format( "Added Quest for log %u with ID %u to %s", logId, questId, target ) ); end else player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) ); player:PrintToPlayer( "@addquest <logID> <questID> <player>" ); end end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
units/armspy.lua
3
4904
unitDef = { unitname = [[armspy]], name = [[Infiltrator]], description = [[Cloaked Scout/Anti-Heavy]], acceleration = 0.3, activateWhenBuilt = true, brakeRate = 0.9, buildCostEnergy = 280, buildCostMetal = 280, buildPic = [[armspy.png]], buildTime = 280, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], cloakCost = 4, cloakCostMoving = 12, corpse = [[DEAD]], customParams = { description_de = [[Spion, Anti-Heavy]], description_fr = [[Espion, contre les unités lourdes]], helptext = [[The Infiltrator is useful in two ways. Firstly it is an excellent scout, and very difficult to detect. It can penetrate deep into enemy lines. It also has the capacity to shoot a paralyzing bolt that will freeze any one target, good against heavy enemies and enemy infrastructure.]], helptext_de = [[Der Infiltrator ist für zwei Dinge nützlich. Erstens ist er ein exzellenter Aufklärer und sehr schwer zu entdecken. Er kann sich tief hinter die feindlichen Linien begeben. Außerdem besitzt er die Eigentschaft einen paralysierenden Bolzen abzuschießen, der jedes Ziel einfriert, was gegen schwere Einheiten und feindliche Infrastruktur sehr nützlich ist.]], helptext_fr = [[L'infiltrator est une unité légère invisible. Il peut typiquement être utilisé comme un éclaireur permettant d'espionner la base enemie sans se faire repérer. Il peut aussi libérer une décharge EMP de très haute puissance pour paralyser une cible unique, utile contre les unités lourdes et l'infrastructure. En cas d'échec le temps de recharge très long signifie la perte certaine de cette unité.]], }, explodeAs = [[BIG_UNITEX]], fireState = 0, footprintX = 2, footprintZ = 2, iconType = [[walkerscout]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, initCloaked = true, maxDamage = 270, maxSlope = 36, maxVelocity = 2.55, maxWaterDepth = 22, minCloakDistance = 60, movementClass = [[TKBOT3]], moveState = 0, noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]], objectName = [[infiltrator.s3o]], script = [[armspy.lua]], seismicSignature = 16, selfDestructAs = [[BIG_UNITEX]], sightDistance = 550, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ChickenTrackPointyShort]], trackWidth = 45, turnRate = 1800, weapons = { { def = [[spy]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP]], }, }, weaponDefs = { spy = { name = [[Electro-Stunner]], areaOfEffect = 8, collideFriendly = false, craterBoost = 0, craterMult = 0, customParams = { light_color = [[1.85 1.85 0.45]], light_radius = 300, }, damage = { default = 8000.1, }, duration = 8, explosionGenerator = [[custom:YELLOW_LIGHTNINGPLOSION]], fireStarter = 0, heightMod = 1, impactOnly = true, impulseBoost = 0, impulseFactor = 0, intensity = 12, interceptedByShieldType = 1, paralyzer = true, paralyzeTime = 30, range = 100, reloadtime = 35, rgbColor = [[1 1 0.25]], soundStart = [[weapon/LightningBolt]], soundTrigger = true, targetborder = 1, texture1 = [[lightning]], thickness = 10, tolerance = 10000, turret = true, weaponType = [[LightningCannon]], weaponVelocity = 450, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[Infiltrator_wreck.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2a.s3o]], }, }, } return lowerkeys({ armspy = unitDef })
gpl-2.0
MOSAVI17/ABCD
plugins/join.lua
26
1488
--[[ Bot can join into a group by replying a message contain an invite link or by typing !join [invite link]. URL.parse cannot parsing complicated message. So, this plugin only works for single [invite link] in a post. [invite link] may be preceeded but must not followed by another characters. --]] do local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) i = 0 for k,segment in pairs(parsed_path) do i = i + 1 if segment == 'joinchat' then invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '') break end end return invite_link end local function action_by_reply(extra, success, result) local hash = parsed_url(result.text) join = import_chat_link(hash, ok_cb, false) end function run(msg, matches) if is_sudo(msg.from.id) then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) elseif matches[1] then local hash = parsed_url(matches[1]) join = import_chat_link(hash, ok_cb, false) end end end return { description = 'Invite the bot into a group chat via its invite link.', usage = { '!join : Join a group by replying a message containing invite link.', '!join [invite_link] : Join into a group by providing their [invite_link].' }, patterns = { '^!join$', '^!join (.*)$' }, run = run } end
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
effects/riot.lua
25
2909
-- riot_shell_m -- riot_shell_l -- riot_shell_h return { ["riot_shell_m"] = { usedefaultexplosions = false, shell = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[0.75 0 0 1 0.75 0 0 1]], directional = true, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, -0.5, 0]], numparticles = 1, particlelife = 30, particlelifespread = 0, particlesize = 6.0, particlesizespread = 0, particlespeed = 3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[shell]], }, }, }, ["riot_shell_l"] = { usedefaultexplosions = false, shell = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[0.75 0 0 1 0.75 0 0 1]], directional = true, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, -0.5, 0]], numparticles = 1, particlelife = 15, particlelifespread = 0, particlesize = 6.0, particlesizespread = 0, particlespeed = 3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[shell]], }, }, }, ["riot_shell_h"] = { usedefaultexplosions = false, shell = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[0.75 0 0 1 0.75 0 0 1]], directional = true, emitrot = 0, emitrotspread = 20, emitvector = [[dir]], gravity = [[0, -0.5, 0]], numparticles = 1, particlelife = 60, particlelifespread = 0, particlesize = 12.0, particlesizespread = 0, particlespeed = 2, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[shell]], }, }, }, }
gpl-2.0
DEVSEIKO/seikodev
plugins/lock_fwd.lua
2
1656
--[[ _____ _ _ _ _____ Dev @lIMyIl |_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il | |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a | |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22 |_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI CH > @lTSHAKEl_CH --]] do local function pre_process(msg) local hash = 'mate:'..msg.to.id if redis:get(hash) and msg.fwd_from and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) then delete_msg(msg.id, ok_cb, true) return "done" end return msg end local function moody(msg, matches) chat_id = msg.to.id if is_momod(msg) and matches[1] == 'قفل اعاده توجيه' then local hash = 'mate:'..msg.to.id redis:set(hash, true) return "" elseif is_momod(msg) and matches[1] == 'فتح اعاده توجيه' then local hash = 'mate:'..msg.to.id redis:del(hash) return "" end end return { patterns = { '^(قفل اعاده توجيه)$', '^(فتح اعاده توجيه)$', '^[/!#](قفل اعاده توجيه)$', '^[/!#](فتح اعاده توجيه)$' }, run = moody, pre_process = pre_process } end --[[ _____ _ _ _ _____ Dev @lIMyIl |_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il | |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a | |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22 |_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI CH > @lTSHAKEl_CH --]]
gpl-2.0
Scavenge/darkstar
scripts/zones/Rabao/npcs/Irmilant.lua
12
3934
----------------------------------- -- Area: Rabao -- NPC: Irmilant -- Starts and Ends Quests: The Immortal Lu Shang and Indomitable Spirit ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) Indomitable = player:getQuestStatus(OUTLANDS,INDOMITABLE_SPIRIT); ImmortalLuShang = player:getQuestStatus(OUTLANDS,THE_IMMORTAL_LU_SHANG); if ((ImmortalLuShang == QUEST_ACCEPTED or ImmortalLuShang == QUEST_COMPLETED) and trade:hasItemQty(720,1) and trade:hasItemQty(489,1) and trade:hasItemQty(4102,2) and trade:getItemCount() == 4) then player:startEvent(0x004e); elseif ((Indomitable == QUEST_ACCEPTED or Indomitable == QUEST_COMPLETED) and trade:hasItemQty(1837,1) and trade:hasItemQty(1826,1) and trade:getItemCount() == 2) then player:startEvent(0x0084); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Indomitable = player:getQuestStatus(OUTLANDS,INDOMITABLE_SPIRIT); ImmortalLuShang = player:getQuestStatus(OUTLANDS,THE_IMMORTAL_LU_SHANG); realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day if (player:hasItem(489) == true and (ImmortalLuShang == QUEST_AVAILABLE or ImmortalLuShang == QUEST_COMPLETED)) then player:startEvent(0x004d); --Offer the quest if the player has the broken rod elseif (player:hasKeyItem(1977) == true and (Indomitable == QUEST_AVAILABLE or Indomitable == QUEST_COMPLETED)) then player:startEvent(0x0083); --Begins Indomitable Spirit elseif ((Indomitable == QUEST_ACCEPTED or Indomitable == QUEST_COMPLETED) and realday == player:getVar("IndomitableSpiritVar")) then player:startEvent(0x0085); --Asks the player to wait elseif ((Indomitable == QUEST_ACCEPTED or Indomitable == QUEST_COMPLETED) and realday ~= player:getVar("IndomitableSpiritVar")) then player:startEvent(0x0086); --Ends the Quest elseif (Indomitable == QUEST_COMPLETED) then player:startEvent(0x0087); --Dialogue for those who have completed Indomitable Spirit else player:startEvent(0x004C); --Standard Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x004d) then player:addQuest(OUTLANDS,THE_IMMORTAL_LU_SHANG); elseif (csid == 0x004e) then player:tradeComplete(); player:addTitle(265); player:addItem(17386); -- Lu Shang's Fishing Rod player:messageSpecial(ITEM_OBTAINED, 17386); player:completeQuest(OUTLANDS,THE_IMMORTAL_LU_SHANG); player:addFame(RABAO,60); elseif (csid == 0x0083) then player:addQuest(OUTLANDS,201); elseif (csid == 0x0084) then player:tradeComplete(); player:setVar("IndomitableSpiritVar", os.date("%j")); -- %M for next minute, %j for next day elseif (csid == 0x0086) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17011); else player:addTitle(265); player:addItem(17011); -- Ebisu Fishing Rod player:messageSpecial(ITEM_OBTAINED, 17011); player:completeQuest(OUTLANDS,201); player:addFame(RABAO,100); end end end;
gpl-3.0
PicoleDeLimao/Ninpou2
game/dota_addons/ninpou2/scripts/vscripts/modifiers/modifier_tree.lua
1
1364
modifier_tree = class({}) function modifier_tree:OnCreated(event) self.disable_turning = event.disable_turning == 1 and 1 or 1 self.magic_immune = event.magic_immune == 1 self.deniable = event.deniable == 1 end function modifier_tree:GetModifierDisableTurning() return self.disable_turning end function modifier_tree:GetModifierIgnoreCastAngle() return self.disable_turning or 1 end function modifier_tree:CheckState() return { [MODIFIER_STATE_MAGIC_IMMUNE] = self.magic_immune or true, [MODIFIER_STATE_SPECIALLY_DENIABLE] = self.deniable or true, --add setting in building_settings.kv [MODIFIER_STATE_ROOTED] = true, [MODIFIER_STATE_LOW_ATTACK_PRIORITY] = true, [MODIFIER_STATE_INVULNERABLE] = true, [MODIFIER_STATE_UNSELECTABLE] = true, [MODIFIER_STATE_NO_HEALTH_BAR] = true, [MODIFIER_STATE_OUT_OF_GAME] = true } end function modifier_tree:DeclareFunctions() return { MODIFIER_PROPERTY_DISABLE_TURNING, MODIFIER_PROPERTY_IGNORE_CAST_ANGLE, MODIFIER_PROPERTY_MOVESPEED_LIMIT, } end function modifier_tree:GetAttributes() return MODIFIER_ATTRIBUTE_PERMANENT end function modifier_tree:GetModifierMoveSpeed_Limit() return 0 end function modifier_tree:IsHidden() return true end function modifier_tree:IsPurgable() return false end
apache-2.0
Crystalwarrior/ZombieDefence
lib/HardonCollider/init.lua
10
4573
--[[ Copyright (c) 2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _NAME, common_local = ..., common if not (type(common) == 'table' and common.class and common.instance) then assert(common_class ~= false, 'No class commons specification available.') require(_NAME .. '.class') end local Shapes = require(_NAME .. '.shapes') local Spatialhash = require(_NAME .. '.spatialhash') -- reset global table `common' (required by class commons) if common_local ~= common then common_local, common = common, common_local end local newPolygonShape = Shapes.newPolygonShape local newCircleShape = Shapes.newCircleShape local newPointShape = Shapes.newPointShape local HC = {} function HC:init(cell_size) self.hash = common_local.instance(Spatialhash, cell_size or 100) end -- spatial hash management function HC:resetHash(cell_size) local hash = self.hash self.hash = common_local.instance(Spatialhash, cell_size or 100) for shape in pairs(hash:shapes()) do self.hash:register(shape, shape:bbox()) end return self end function HC:register(shape) self.hash:register(shape, shape:bbox()) -- keep track of where/how big the shape is for _, f in ipairs({'move', 'rotate', 'scale'}) do local old_function = shape[f] shape[f] = function(this, ...) local x1,y1,x2,y2 = this:bbox() old_function(this, ...) self.hash:update(this, x1,y1,x2,y2, this:bbox()) return this end end return shape end function HC:remove(shape) self.hash:remove(shape, shape:bbox()) for _, f in ipairs({'move', 'rotate', 'scale'}) do shape[f] = function() error(f.."() called on a removed shape") end end return self end -- shape constructors function HC:polygon(...) return self:register(newPolygonShape(...)) end function HC:rectangle(x,y,w,h) return self:polygon(x,y, x+w,y, x+w,y+h, x,y+h) end function HC:circle(x,y,r) return self:register(newCircleShape(x,y,r)) end function HC:point(x,y) return self:register(newPointShape(x,y)) end -- collision detection function HC:neighbors(shape) local neighbors = self.hash:inSameCells(shape:bbox()) rawset(neighbors, shape, nil) return neighbors end function HC:collisions(shape) local candidates = self:neighbors(shape) for other in pairs(candidates) do local collides, dx, dy = shape:collidesWith(other) if collides then rawset(candidates, other, {dx,dy, x=dx, y=dy}) else rawset(candidates, other, nil) end end return candidates end -- the class and the instance HC = common_local.class('HardonCollider', HC) local instance = common_local.instance(HC) -- the module return setmetatable({ new = function(...) return common_local.instance(HC, ...) end, resetHash = function(...) return instance:resetHash(...) end, register = function(...) return instance:register(...) end, remove = function(...) return instance:remove(...) end, polygon = function(...) return instance:polygon(...) end, rectangle = function(...) return instance:rectangle(...) end, circle = function(...) return instance:circle(...) end, point = function(...) return instance:point(...) end, neighbors = function(...) return instance:neighbors(...) end, collisions = function(...) return instance:collisions(...) end, hash = function() return instance.hash end, }, {__call = function(_, ...) return common_local.instance(HC, ...) end})
unlicense
Zero-K-Experiments/Zero-K-Experiments
gamedata/sounds.lua
2
3522
-- see http://springrts.com/wiki/Sounds.lua for help local Sounds = { SoundItems = { default = { }, IncomingChat = { --file = "sounds/talk.wav", file = nil, }, --MultiSelect = { -- file = "sounds/button9.wav", --}, MapPoint = { file = "sounds/beep4_decrackled.wav", maxconcurrent = 3, }, --[[ MyAwesomeSounds = { file = "sounds/booooom.wav", gain = 2.0, --- for uber-loudness pitch = 0.2, --- bass-test priority = 15, --- very high maxconcurrent = 1, ---only once maxdist = 500, --- only when near preload = true, --- you got it in3d = true, looptime = "1000", --- in miliseconds, can / will be stopped like regular items MapEntryValExtract(items, "dopplerscale", dopplerScale); MapEntryValExtract(items, "rolloff", rolloff); }, --]] BladeSwing = { file = "sounds/weapon/blade/blade_swing.wav", pitchmod = 0.1, gainmod = 0.1, pitch = 0.8, gain = 0.9, priority = 1, }, BladeHit = { file = "sounds/weapon/blade/blade_hit.wav", pitchmod = 0.5, gainmod = 0.2, }, DefaultsForSounds = { -- this are default settings file = "ThisEntryMustBePresent.wav", gain = 1.0, pitch = 1.0, priority = 0, maxconcurrent = 4, --- some reasonable limits maxdist = FLT_MAX, --- no cutoff at all }, Sparks = { file = "sounds/sparks.wav", priority = -10, maxconcurrent = 1, maxdist = 1000, preload = false, in3d = true, rolloff = 4, }, TorpedoHitVariable = { file = "sounds/explosion/wet/ex_underwater.wav", pitchmod = 0.1, gainmod = 0.05, }, }, } -------------------------------------------------------------------------------- -- Automagical sound handling -------------------------------------------------------------------------------- local VFSUtils = VFS.Include('gamedata/VFSUtils.lua') local optionOverrides = { } local defaultOpts = { pitchmod = 0, --0.02, gainmod = 0, } local replyOpts = { pitchmod = 0, --0.02, gainmod = 0, } local noVariation = { dopplerscale = 0, in3d = false, pitchmod = 0, gainmod = 0, pitch = 1, gain = 1, } local ignoredExtensions = { ["svn-base"] = true, } local function AutoAdd(subDir, generalOpts) generalOpts = generalOpts or {} local opts local dirList = RecursiveFileSearch("sounds/" .. subDir) --local dirList = RecursiveFileSearch("sounds/") --Spring.Echo("Adding sounds for " .. subDir) for _, fullPath in ipairs(dirList) do local path, key, ext = fullPath:match("sounds/(.*/(.*)%.(.*))") local pathPart = fullPath:match("(.*)[.]") pathPart = pathPart:sub(8, -1) -- truncates extension fullstop and "sounds/" part of path --Spring.Echo(pathPart) if path ~= nil and (not ignoredExtensions[ext]) then if optionOverrides[pathPart] then opts = optionOverrides[pathPart] --Spring.Echo("optionOverrides for " .. pathPart) else opts = generalOpts end --Spring.Echo(path,key,ext, pathPart) Sounds.SoundItems[pathPart] = { file = tostring('sounds/'..path), rolloff = opts.rollOff, dopplerscale = opts.dopplerscale, maxdist = opts.maxdist, maxconcurrent = opts.maxconcurrent, priority = opts.priority, in3d = opts.in3d, gain = opts.gain, gainmod = opts.gainmod, pitch = opts.pitch, pitchmod = opts.pitchmod } --Spring.Echo(Sounds.SoundItems[key].file) end end end -- add sounds AutoAdd("weapon", defaultOpts) AutoAdd("explosion", defaultOpts) AutoAdd("reply", replyOpts) AutoAdd("music", noVariation) return Sounds
gpl-2.0
Scavenge/darkstar
scripts/zones/Abyssea-Uleguerand/npcs/qm10.lua
14
1347
----------------------------------- -- Zone: Abyssea-Uleguerand -- NPC: qm10 (???) -- Spawns Audumbla -- @pos ? ? ? 253 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3258,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17813940) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17813940):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3258); -- Inform player what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kirubz/Penlight
tests/test-strict.lua
8
1149
local strict = require 'pl.strict' local test = require 'pl.test' local app = require 'pl.app' -- in strict mode, you must assign to a global first, even if just nil. test.assertraise(function() print(x) print 'ok?' end,"variable 'x' is not declared") -- can assign to globals in main (or from C extensions) but not anywhere else! test.assertraise(function() Boo = 3 end,"assign to undeclared global 'Boo'") Boo = true Boo2 = nil -- once declared, you can assign to globals from anywhere (function() Boo = 42; Boo2 = 6*7 end)() --- a module may use strict.module() to generate a simularly strict environment -- (see lua/mymod.lua) app.require_here 'lua' local M = require 'mymod' --- these are fine M.answer() M.question() -- spelling mistakes become errors... test.assertraise(function() print(M.Answer()) end,"variable 'Answer' is not declared in 'mymod'") --- for the extra paranoid, you can choose to make all global tables strict... strict.make_all_strict(_G) test.assertraise(function() print(math.sine(1.2)) end,"variable 'sine' is not declared in 'math'")
mit
Scavenge/darkstar
scripts/globals/items/plate_of_sublime_sushi.lua
12
1962
----------------------------------------- -- ID: 6468 -- Item: plate_of_sublime_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- HP +40 -- MP +20 -- STR +6 -- DEX +7 -- MND -3 -- CHR +6 -- Accuracy +10% (cap 100) -- Ranged Accuracy +10% (cap 100) -- Resist Sleep +1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,6468); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 40); target:addMod(MOD_MP, 20); target:addMod(MOD_STR, 6); target:addMod(MOD_DEX, 7); target:addMod(MOD_MND, -3); target:addMod(MOD_CHR, 6); target:addMod(MOD_FOOD_ACCP, 10); target:addMod(MOD_FOOD_ACC_CAP, 100); target:addMod(MOD_FOOD_RACCP, 10); target:addMod(MOD_FOOD_RACC_CAP, 100); target:addMod(MOD_SLEEPRES, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 40); target:delMod(MOD_MP, 20); target:delMod(MOD_STR, 6); target:delMod(MOD_DEX, 7); target:delMod(MOD_MND, -3); target:delMod(MOD_CHR, 6); target:delMod(MOD_FOOD_ACCP, 10); target:delMod(MOD_FOOD_ACC_CAP, 100); target:delMod(MOD_FOOD_RACCP, 10); target:delMod(MOD_FOOD_RACC_CAP, 100); target:delMod(MOD_SLEEPRES, 1); end;
gpl-3.0
tonyli71/kolla
docker/heka/plugins/decoders/os_swift_log.lua
4
1578
-- Copyright 2016 Mirantis, 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. -- -- The code in this file was inspired by Heka's rsyslog.lua decoder plugin. -- https://github.com/mozilla-services/heka/blob/master/sandbox/lua/decoders/rsyslog.lua local syslog = require "syslog" local utils = require "os_utils" local msg = { Timestamp = nil, Type = 'log', Hostname = read_config("hostname"), Payload = nil, Pid = nil, Severity = nil, Fields = nil } -- See https://github.com/openstack/swift/blob/2a8b455/swift/common/utils.py#L1423-L1424 local swift_grammar = syslog.build_rsyslog_grammar('<%PRI%>%programname%: %msg%') function process_message () local log = read_message("Payload") local fields = swift_grammar:match(log) if not fields then return -1 end msg.Severity = fields.pri.severity fields.syslogfacility = fields.pri.facility fields.pri = nil msg.Payload = fields.msg fields.msg = nil msg.Fields = fields return utils.safe_inject_message(msg) end
apache-2.0
Zero-K-Experiments/Zero-K-Experiments
effects/gundam_bluegreennovaexplode.lua
25
2601
-- bluegreennovaexplo return { ["bluegreennovaexplo"] = { groundflash = { air = true, alwaysvisible = true, circlealpha = 0.2, circlegrowth = 4, flashalpha = 0.5, flashsize = 50, ground = true, ttl = 10, water = true, color = { [1] = 0.10000000149012, [2] = 1, [3] = 0.60000002384186, }, }, poof02 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[0.2 0.8 0.8 0.01 0.2 0.8 0.2 0.01 0.0 0.0 0.0 0.01]], directional = false, emitrot = 45, emitrotspread = 32, emitvector = [[0, 1, 0]], gravity = [[0, -0.005, 0]], numparticles = 8, particlelife = 5, particlelifespread = 8, particlesize = 10, particlesizespread = 0, particlespeed = 8, particlespeedspread = 3, pos = [[0, 2, 0]], sizegrowth = 0.8, sizemod = 1.0, texture = [[randdots]], useairlos = false, }, }, pop1 = { air = true, class = [[heatcloud]], count = 2, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1, maxheat = 10, pos = [[0, 5, 0]], size = 0.2, sizegrowth = 8, speed = [[0, 0, 0]], texture = [[greennovaexplo]], }, }, pop2 = { air = true, class = [[heatcloud]], count = 2, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 2, maxheat = 15, pos = [[r-3 r3, 5, r-3 r3]], size = 0.2, sizegrowth = 3, speed = [[0, 1, 0]], texture = [[3explo]], }, }, }, }
gpl-2.0
peaking-development/peak
common/buffer.lua
1
1401
local Promise = require 'common/promise' return function(h, data, write) local buffer local pos = 1 local function read(len) local res = buffer:sub(pos, pos + len - 1) pos = pos + len if pos > #buffer + 1 then pos = #buffer + 1 end return res end function h.read(len) buffer = data() local res if len == math.huge then res = buffer:sub(pos) pos = #buffer elseif len == 'line' then local index = buffer:find('[\n\r]', pos) local m = buffer:match('[\n\r]*', pos) res = read(index - pos) read(#m) elseif type(len) == 'number' and len > 0 then res = read(len) else res = read(10) end buffer = nil return Promise.resolved(true, res) end function h.seek(whence, offset) if whence == 'set' then pos = offset + 1 elseif whence == 'cur' then pos = pos + offset else return ret(Promise.resolved(false, 'invalid whence: ' .. tostring(whence))) end if pos > #data() + 1 then return ret(Promise.resolved(false, E.badpos, pos, #data() + 1)) end return Promise.resolved(true, pos - 1) end function h.close() return Promise.resolved(true) end if write then function h.write(_data) buffer = data() buffer = buffer:sub(1, pos - 1) .. _data .. buffer:sub(pos + #_data) data(buffer) buffer = nil return Promise.resolved(true) end function h.flush() return Promise.resolved(true) end end return h end
mit
google/guetzli
premake5.lua
3
1475
workspace "guetzli" configurations { "Release", "Debug" } language "C++" flags { "C++11" } includedirs { ".", "third_party/butteraugli" } filter "action:vs*" platforms { "x86_64", "x86" } filter "platforms:x86" architecture "x86" filter "platforms:x86_64" architecture "x86_64" -- workaround for #41 filter "action:gmake" symbols "On" filter "configurations:Debug" symbols "On" filter "configurations:Release" optimize "Full" filter {} project "guetzli_static" kind "StaticLib" files { "guetzli/*.cc", "guetzli/*.h", "third_party/butteraugli/butteraugli/butteraugli.cc", "third_party/butteraugli/butteraugli/butteraugli.h" } removefiles "guetzli/guetzli.cc" filter "action:gmake" linkoptions { "`pkg-config --static --libs libpng || libpng-config --static --ldflags`" } buildoptions { "`pkg-config --static --cflags libpng || libpng-config --static --cflags`" } project "guetzli" kind "ConsoleApp" filter "action:gmake" linkoptions { "`pkg-config --libs libpng || libpng-config --ldflags`" } buildoptions { "`pkg-config --cflags libpng || libpng-config --cflags`" } filter "action:vs*" links { "shlwapi" } filter {} files { "guetzli/*.cc", "guetzli/*.h", "third_party/butteraugli/butteraugli/butteraugli.cc", "third_party/butteraugli/butteraugli/butteraugli.h" }
apache-2.0
Scavenge/darkstar
scripts/zones/Windurst_Woods/npcs/Spare_Two.lua
17
1505
----------------------------------- -- Area: Windurst Woods -- NPC: Spare Two -- Working 100% -- Involved in quest: A Greeting Cardian ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/globals/quests"] = nil; require("scripts/globals/quests"); package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) AGreetingCardian = player:getQuestStatus(WINDURST,A_GREETING_CARDIAN); local AGCcs = player:getVar("AGreetingCardian_Event"); if (AGreetingCardian == QUEST_ACCEPTED and AGCcs == 2) then player:startEvent(0x0127); -- A Greeting Cardian step two else player:startEvent(0x117); -- standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0127) then player:setVar("AGreetingCardian_Event",3); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Port_Windurst/npcs/Ohruru.lua
14
5022
----------------------------------- -- Area: Windurst Waters -- NPC: Ohruru -- Starts & Finishes Repeatable Quest: Catch me if you can -- Working 90% -- Involved in Quest: Wonder Wands -- Note: Animation for his "Cure" is not functioning. Unable to capture option 1, so if the user says no, he heals them anyways. -- @zone = 240 -- @pos = -108 -5 94 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- player:delQuest(WINDURST,CATCH_IT_IF_YOU_CAN); -- ======== FOR TESTING ONLY ==========----- -- ======== FOR TESTING ONLY ==========----- -- if (player:getVar("QuestCatchItIfYouCan_var") == 0 and player:hasStatusEffect(EFFECT_MUTE) == false and player:hasStatusEffect(EFFECT_BANE) == false and player:hasStatusEffect(EFFECT_PLAGUE) == false) then -- rand = math.random(1,3); -- if (rand == 1) then -- player:addStatusEffect(EFFECT_MUTE,0,0,100); -- elseif (rand == 2) then -- player:addStatusEffect(EFFECT_BANE,0,0,100); -- elseif (rand == 3) then -- player:addStatusEffect(EFFECT_PLAGUE,0,0,100); -- end -- end -- ======== FOR TESTING ONLY ==========----- Catch = player:getQuestStatus(WINDURST,CATCH_IT_IF_YOU_CAN); WonderWands = player:getQuestStatus(WINDURST,WONDER_WANDS); if (WonderWands == QUEST_ACCEPTED) then player:startEvent(0x0102,0,17053); elseif (Catch == 0) then prog = player:getVar("QuestCatchItIfYouCan_var"); if (prog == 0) then player:startEvent(0x00e6); -- CATCH IT IF YOU CAN: Before Quest 1 player:setVar("QuestCatchItIfYouCan_var",1); elseif (prog == 1) then player:startEvent(0x00fd); -- CATCH IT IF YOU CAN: Before Start player:setVar("QuestCatchItIfYouCan_var",2); elseif (prog == 2) then player:startEvent(0x00e7); -- CATCH IT IF YOU CAN: Before Quest 2 end elseif (Catch >= 1 and (player:hasStatusEffect(EFFECT_MUTE) == true or player:hasStatusEffect(EFFECT_BANE) == true or player:hasStatusEffect(EFFECT_PLAGUE) == true)) then player:startEvent(0x00f6); -- CATCH IT IF YOU CAN: Quest Turn In 1 elseif (Catch >= 1 and player:needToZone()) then player:startEvent(0x00ff); -- CATCH IT IF YOU CAN: After Quest elseif (Catch == 1 and player:hasStatusEffect(EFFECT_MUTE) == false and player:hasStatusEffect(EFFECT_BANE) == false and player:hasStatusEffect(EFFECT_PLAGUE) == false) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x00f8); -- CATCH IT IF YOU CAN: During Quest 1 else player:startEvent(0x00fb); -- CATCH IT IF YOU CAN: During Quest 2 end elseif (WonderWands == QUEST_COMPLETED) then player:startEvent(0x0109); else player:startEvent(0x00e6); -- STANDARD CONVERSATION end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00e7) then player:addQuest(WINDURST,CATCH_IT_IF_YOU_CAN); elseif (csid == 0x00f6 and option == 0) then player:needToZone(true); if (player:hasStatusEffect(EFFECT_MUTE) == true) then player:delStatusEffect(EFFECT_MUTE); player:addGil(GIL_RATE*1000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1000); elseif (player:hasStatusEffect(EFFECT_BANE) == true) then player:delStatusEffect(EFFECT_BANE); player:addGil(GIL_RATE*1200); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1200); elseif (player:hasStatusEffect(EFFECT_PLAGUE) == true) then player:delStatusEffect(EFFECT_PLAGUE); player:addGil(GIL_RATE*1500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500); end player:setVar("QuestCatchItIfYouCan_var",0); if (player:getQuestStatus(WINDURST,CATCH_IT_IF_YOU_CAN) == QUEST_ACCEPTED) then player:completeQuest(WINDURST,CATCH_IT_IF_YOU_CAN); player:addFame(WINDURST,75); else player:addFame(WINDURST,8); end end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Sauromugue_Champaign/npcs/Tiger_Bones.lua
14
1914
----------------------------------- -- Area: Sauromugue Champaign -- NPC: Tiger Bones -- Involed in Quest: The Fanged One. -- @pos 666 -8 -379 120 ------------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ------------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,THE_FANGED_ONE) == QUEST_ACCEPTED) then local oldTiger = 17268808; local tigerAction = GetMobAction(oldTiger); local fangedOneCS = player:getVar("TheFangedOneCS"); if (player:hasKeyItem(OLD_TIGERS_FANG) == false and fangedOneCS == 2) then player:addKeyItem(OLD_TIGERS_FANG); player:messageSpecial(KEYITEM_OBTAINED, OLD_TIGERS_FANG); player:setVar("TheFangedOneCS", 0); elseif (tigerAction == ACTION_NONE and fangedOneCS == 1) then SpawnMob(oldTiger):addStatusEffect(EFFECT_POISON,40,10,210); player:messageSpecial(OLD_SABERTOOTH_DIALOG_I); else player:messageSpecial(NOTHING_HAPPENS); end; end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
jchuang1977/openwrt
package/diy/luci-app-dockerman/luasrc/model/cbi/dockerman/images.lua
2
9332
--[[ LuCI - Lua Configuration Interface Copyright 2019 lisaac <https://github.com/lisaac/luci-app-dockerman> ]]-- require "luci.util" local uci = luci.model.uci.cursor() local docker = require "luci.model.docker" local dk = docker.new() local containers, images local res = dk.images:list() if res.code <300 then images = res.body else return end res = dk.containers:list({query = {all=true}}) if res.code <300 then containers = res.body else return end function get_images() local data = {} for i, v in ipairs(images) do local index = v.Created .. v.Id data[index]={} data[index]["_selected"] = 0 data[index]["id"] = v.Id:sub(8) data[index]["_id"] = '<a href="javascript:new_tag(\''..v.Id:sub(8,20)..'\')" class="dockerman-link" title="'..translate("New tag")..'">' .. v.Id:sub(8,20) .. '</a>' if v.RepoTags and next(v.RepoTags)~=nil then for i, v1 in ipairs(v.RepoTags) do data[index]["_tags"] =(data[index]["_tags"] and ( data[index]["_tags"] .. "<br>" )or "") .. ((v1:match("<none>") or (#v.RepoTags == 1)) and v1 or ('<a href="javascript:un_tag(\''..v1..'\')" class="dockerman_link" title="'..translate("Remove tag")..'" >' .. v1 .. '</a>')) if not data[index]["tag"] then data[index]["tag"] = v1--:match("<none>") and nil or v1 end end else data[index]["_tags"] = v.RepoDigests[1] and v.RepoDigests[1]:match("^(.-)@.+") data[index]["_tags"] = (data[index]["_tags"] and data[index]["_tags"] or "<none>" ).. ":<none>" end data[index]["_tags"] = data[index]["_tags"]:gsub("<none>","&lt;none&gt;") -- data[index]["_tags"] = '<a href="javascript:handle_tag(\''..data[index]["_id"]..'\')">' .. data[index]["_tags"] .. '</a>' for ci,cv in ipairs(containers) do if v.Id == cv.ImageID then data[index]["_containers"] = (data[index]["_containers"] and (data[index]["_containers"] .. " | ") or "").. '<a href='..luci.dispatcher.build_url("admin/docker/container/"..cv.Id)..' class="dockerman_link" title="'..translate("Container detail")..'">'.. cv.Names[1]:sub(2).."</a>" end end data[index]["_size"] = string.format("%.2f", tostring(v.Size/1024/1024)).."MB" data[index]["_created"] = os.date("%Y/%m/%d %H:%M:%S",v.Created) end return data end local image_list = get_images() -- m = Map("docker", translate("Docker")) m = SimpleForm("docker", translate("Docker")) m.submit=false m.reset=false local pull_value={_image_tag_name="", _registry="index.docker.io"} local pull_section = m:section(SimpleSection, translate("Pull Image")) pull_section.template="cbi/nullsection" local tag_name = pull_section:option(Value, "_image_tag_name") tag_name.template = "dockerman/cbi/inlinevalue" tag_name.placeholder="lisaac/luci:latest" local action_pull = pull_section:option(Button, "_pull") action_pull.inputtitle= translate("Pull") action_pull.template = "dockerman/cbi/inlinebutton" action_pull.inputstyle = "add" tag_name.write = function(self, section, value) local hastag = value:find(":") if not hastag then value = value .. ":latest" end pull_value["_image_tag_name"] = value end action_pull.write = function(self, section) local tag = pull_value["_image_tag_name"] local json_stringify = luci.jsonc and luci.jsonc.stringify if tag and tag ~= "" then docker:write_status("Images: " .. "pulling" .. " " .. tag .. "...\n") -- local x_auth = nixio.bin.b64encode(json_stringify({serveraddress= server})) , header={["X-Registry-Auth"] = x_auth} local res = dk.images:create({query = {fromImage=tag}}, docker.pull_image_show_status_cb) -- {"errorDetail": {"message": "failed to register layer: ApplyLayer exit status 1 stdout: stderr: write \/docker: no space left on device" }, "error": "failed to register layer: ApplyLayer exit status 1 stdout: stderr: write \/docker: no space left on device" } if res and res.code == 200 and (res.body[#res.body] and not res.body[#res.body].error and res.body[#res.body].status and (res.body[#res.body].status == "Status: Downloaded newer image for ".. tag)) then docker:clear_status() else docker:append_status("code:" .. res.code.." ".. (res.body[#res.body] and res.body[#res.body].error or (res.body.message or res.message)).. "\n") end else docker:append_status("code: 400 please input the name of image name!") end luci.http.redirect(luci.dispatcher.build_url("admin/docker/images")) end local import_section = m:section(SimpleSection, translate("Import Images")) local im = import_section:option(DummyValue, "_image_import") im.template = "dockerman/images_import" local image_table = m:section(Table, image_list, translate("Images")) local image_selecter = image_table:option(Flag, "_selected","") image_selecter.disabled = 0 image_selecter.enabled = 1 image_selecter.default = 0 local image_id = image_table:option(DummyValue, "_id", translate("ID")) image_id.rawhtml = true image_table:option(DummyValue, "_tags", translate("RepoTags")).rawhtml = true image_table:option(DummyValue, "_containers", translate("Containers")).rawhtml = true image_table:option(DummyValue, "_size", translate("Size")) image_table:option(DummyValue, "_created", translate("Created")) image_selecter.write = function(self, section, value) image_list[section]._selected = value end local remove_action = function(force) local image_selected = {} -- 遍历table中sectionid local image_table_sids = image_table:cfgsections() for _, image_table_sid in ipairs(image_table_sids) do -- 得到选中项的名字 if image_list[image_table_sid]._selected == 1 then image_selected[#image_selected+1] = (image_list[image_table_sid]["_tags"]:match("<br>") or image_list[image_table_sid]["_tags"]:match("&lt;none&gt;")) and image_list[image_table_sid].id or image_list[image_table_sid].tag end end if next(image_selected) ~= nil then local success = true docker:clear_status() for _,img in ipairs(image_selected) do docker:append_status("Images: " .. "remove" .. " " .. img .. "...") local query if force then query = {force = true} end local msg = dk.images:remove({id = img, query = query}) if msg.code ~= 200 then docker:append_status("code:" .. msg.code.." ".. (msg.body.message and msg.body.message or msg.message).. "\n") success = false else docker:append_status("done\n") end end if success then docker:clear_status() end luci.http.redirect(luci.dispatcher.build_url("admin/docker/images")) end end local docker_status = m:section(SimpleSection) docker_status.template = "dockerman/apply_widget" docker_status.err = docker:read_status() docker_status.err = docker_status.err and docker_status.err:gsub("\n","<br>"):gsub(" ","&nbsp;") if docker_status.err then docker:clear_status() end local action = m:section(Table,{{}}) action.notitle=true action.rowcolors=false action.template="cbi/nullsection" local btnremove = action:option(Button, "remove") btnremove.inputtitle= translate("Remove") btnremove.template = "dockerman/cbi/inlinebutton" btnremove.inputstyle = "remove" btnremove.forcewrite = true btnremove.write = function(self, section) remove_action() end local btnforceremove = action:option(Button, "forceremove") btnforceremove.inputtitle= translate("Force Remove") btnforceremove.template = "dockerman/cbi/inlinebutton" btnforceremove.inputstyle = "remove" btnforceremove.forcewrite = true btnforceremove.write = function(self, section) remove_action(true) end local btnsave = action:option(Button, "save") btnsave.inputtitle= translate("Save") btnsave.template = "dockerman/cbi/inlinebutton" btnsave.inputstyle = "edit" btnsave.forcewrite = true btnsave.write = function (self, section) local image_selected = {} local image_table_sids = image_table:cfgsections() for _, image_table_sid in ipairs(image_table_sids) do if image_list[image_table_sid]._selected == 1 then image_selected[#image_selected+1] = image_list[image_table_sid].id --image_id:cfgvalue(image_table_sid) end end if next(image_selected) ~= nil then local names for _,img in ipairs(image_selected) do names = names and (names .. "&names=".. img) or img end local first local cb = function(res, chunk) if res.code == 200 then if not first then first = true luci.http.header('Content-Disposition', 'inline; filename="images.tar"') luci.http.header('Content-Type', 'application\/x-tar') end luci.ltn12.pump.all(chunk, luci.http.write) else if not first then first = true luci.http.prepare_content("text/plain") end luci.ltn12.pump.all(chunk, luci.http.write) end end docker:write_status("Images: " .. "save" .. " " .. table.concat(image_selected, "\n") .. "...") local msg = dk.images:get({query = {names = names}}, cb) if msg.code ~= 200 then docker:append_status("code:" .. msg.code.." ".. (msg.body.message and msg.body.message or msg.message).. "\n") success = false else docker:clear_status() end end end local btnload = action:option(Button, "load") btnload.inputtitle= translate("Load") btnload.template = "dockerman/images_load" btnload.inputstyle = "add" return m
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/unit_jumper_jumpOverObstacle.lua
5
20451
local version = "v0.507" function widget:GetInfo() return { name = "Auto Jump Over Terrain", desc = version .. " Jumper automatically jump over terrain or buildings if it shorten walk time.", author = "Msafwan", date = "4 February 2014", license = "GNU GPL, v2 or later", layer = 21, enabled = false } end VFS.Include("LuaRules/Configs/customcmds.h.lua") VFS.Include("LuaRules/Utilities/isTargetReachable.lua") local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitRulesParam = Spring.GetUnitRulesParam local spValidUnitID = Spring.ValidUnitID local spValidFeatureID = Spring.ValidFeatureID local spGetCommandQueue = Spring.GetCommandQueue local spGiveOrderArrayToUnitArray = Spring.GiveOrderArrayToUnitArray local spGetFeaturePosition = Spring.GetFeaturePosition local spGetUnitIsStunned = Spring.GetUnitIsStunned local spGetGameSeconds = Spring.GetGameSeconds ------------------------------------------------------------ ------------------------------------------------------------ local gaussUnitDefID = UnitDefNames["armpb"].id local myTeamID local jumperAddInfo={} --Spread job stuff: (spread looping across 1 second) local spreadJobs=nil; local effectedUnit={}; local spreadPreviousIndex = nil; --end spread job stuff --Network lag hax stuff: (wait until unit receive command before processing 2nd time) local waitForNetworkDelay = nil; local issuedOrderTo = {} --end network lag stuff local jumpersToJump = {} local jumpersToWatch = {} local jumpersToJump_Count = 0 local jumpersUnitID = {} local jumperDefs = VFS.Include("LuaRules/Configs/jump_defs.lua") local exclusions = { UnitDefNames["corsumo"].id, -- has AoE damage on jump, could harm allies --UnitDefNames["corsktl"].id -- jump is precious } for i = 1, #exclusions do jumperDefs[exclusions[i]] = nil end function widget:Initialize() local _, _, spec, teamID = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) if spec then widgetHandler:RemoveWidget() return false end myTeamID = teamID end function widget:GameFrame(n) if n%30==14 then --every 30 frame period (1 second) at the 14th frame: --check if we were waiting for lag for too long local currentSecond = spGetGameSeconds() if waitForNetworkDelay then if currentSecond - waitForNetworkDelay[1] > 4 then waitForNetworkDelay = nil end end end if ( n%15==0 and not waitForNetworkDelay) or spreadJobs then local numberOfUnitToProcess = 29 --NUMBER OF UNIT PER SECOND. minimum: 29 unit per second local numberOfUnitToProcessPerFrame = math.ceil(numberOfUnitToProcess/29) --spread looping to entire 1 second spreadJobs = false local numberOfLoopToProcessPerFrame = math.ceil(jumpersToJump_Count/29) local currentLoopIndex = spreadPreviousIndex or 1 local currentLoopCount = 0 local currentUnitProcessed = 0 local finishLoop = false if currentLoopIndex >= jumpersToJump_Count then finishLoop =true end local k = currentLoopIndex while (k<=jumpersToJump_Count) do local unitID = jumpersToJump[k][2] local validUnitID = spValidUnitID(unitID) if not validUnitID then DeleteEntryThenReIndex(k,unitID) k = k -1 end if validUnitID then local unitDefID = jumpersToJump[k][1] if not jumperAddInfo[unitDefID] then local moveID = UnitDefs[unitDefID].moveDef.id local ud = UnitDefs[unitDefID] local halfJumprangeSq = (jumperDefs[unitDefID].range/2)^2 local heightSq = jumperDefs[unitDefID].height^2 local totalFlightDist = math.sqrt(halfJumprangeSq+heightSq)*2 local jumpTime = (totalFlightDist/jumperDefs[unitDefID].speed + jumperDefs[unitDefID].delay)/30 -- is in second local unitSpeed = ud.speed --speed is in elmo-per-second local weaponRange = GetUnitFastestWeaponRange(ud) local unitSize = math.max(ud.xsize*4, ud.zsize*4) jumperAddInfo[unitDefID] = {moveID,jumpTime,unitSpeed,weaponRange, unitSize} end repeat --note: not looping, only for using "break" as method of escaping code local _,_,inBuild = spGetUnitIsStunned(unitID) if inBuild then break; --a.k.a: Continue end --IS NEW UNIT? initialize them-- effectedUnit[unitID] = effectedUnit[unitID] or {cmdCount=0,cmdOne={id=nil,x=nil,y=nil,z=nil},cmdTwo={id=nil,x=nil,y=nil,z=nil}} --IS UNIT IDLE? skip-- local cmd_queue = spGetCommandQueue(unitID, -1); if not (cmd_queue and cmd_queue[1]) then DeleteEntryThenReIndex(k,unitID) k = k -1 break; --a.k.a: Continue end -- IS UNIT WAITING? skip-- if (cmd_queue[1].id== CMD.WAIT) then break; end --IS UNIT CHARGING JUMP? skip-- local jumpReload = spGetUnitRulesParam(unitID,"jumpReload") if jumpReload then if jumpReload < 0.95 then break; --a.k.a: Continue end end --EXTRACT RELEVANT FIRST COMMAND -- local cmd_queue2 local unitIsAttacking for i=1, #cmd_queue do local cmd = cmd_queue[i] local equivalentMoveCMD = ConvertCMDToMOVE({cmd}) if equivalentMoveCMD then unitIsAttacking = (cmd.id == CMD.ATTACK) cmd_queue2 = equivalentMoveCMD break end end if not cmd_queue2 then break end currentUnitProcessed = currentUnitProcessed + 1 --CHECK POSITION OF PREVIOUS JUMP-- local extraCmd1 = nil local extraCmd2 = nil local jumpCmdPos = 0 if effectedUnit[unitID].cmdCount >0 then for i=1, #cmd_queue do local cmd = cmd_queue[i] if cmd.id == effectedUnit[unitID].cmdOne.id and cmd.params[1] == effectedUnit[unitID].cmdOne.x and cmd.params[2] == effectedUnit[unitID].cmdOne.y and cmd.params[3] == effectedUnit[unitID].cmdOne.z then extraCmd1 = {CMD.REMOVE, {cmd.tag},{"shift"}} jumpCmdPos = i end if cmd.id == effectedUnit[unitID].cmdTwo.id and cmd.params[1] == effectedUnit[unitID].cmdTwo.x and cmd.params[2] == effectedUnit[unitID].cmdTwo.y and cmd.params[3] == effectedUnit[unitID].cmdTwo.z then extraCmd2 = {CMD.REMOVE, {cmd.tag},{"shift"}} jumpCmdPos = jumpCmdPos or i break end end end --CHECK FOR OBSTACLE IN LINE-- local tx,ty,tz = cmd_queue2.params[1],cmd_queue2.params[2],cmd_queue2.params[3] local px,py,pz = spGetUnitPosition(unitID) local enterPoint_X,enterPoint_Y,enterPoint_Z,exitPoint_X,exitPoint_Y,exitPoint_Z = GetNearestObstacleEnterAndExitPoint(px,py,pz, tx,tz, unitDefID) if exitPoint_X and exitPoint_Z then local unitSpeed = jumperAddInfo[unitDefID][3] local moveID = jumperAddInfo[unitDefID][1] local weaponRange = jumperAddInfo[unitDefID][4] --MEASURE REGULAR DISTANCE-- local distance = GetWaypointDistance(unitID,moveID,cmd_queue2,px,py,pz,unitIsAttacking,weaponRange) local normalTimeToDest = (distance/unitSpeed) --is in second --MEASURE DISTANCE WITH JUMP-- cmd_queue2.params[1]=enterPoint_X cmd_queue2.params[2]=enterPoint_Y cmd_queue2.params[3]=enterPoint_Z distance = GetWaypointDistance(unitID,moveID,cmd_queue2,px,py,pz,false,0) --distance to jump-start point local timeToJump = (distance/unitSpeed) --is in second cmd_queue2.params[1]=tx --target coordinate cmd_queue2.params[2]=ty cmd_queue2.params[3]=tz local jumpTime = jumperAddInfo[unitDefID][2] distance = GetWaypointDistance(unitID,moveID,cmd_queue2,exitPoint_X,exitPoint_Y,exitPoint_Z,unitIsAttacking,weaponRange) --dist out of jump-landing point local timeFromExitToDestination = (distance/unitSpeed) --in second local totalTimeWithJump = timeToJump + timeFromExitToDestination + jumpTime --NOTE: time to destination is in second. local normalPathTime = normalTimeToDest - 2 --add 2 second benefit to regular walking (make walking more attractive choice unless jump can save more than 1 second travel time) if totalTimeWithJump < normalPathTime then local commandArray = {[1]=nil,[2]=nil,[3]=nil,[4]=nil} if (math.abs(enterPoint_X-px)>50 or math.abs(enterPoint_Z-pz)>50) then commandArray[1]= {CMD.INSERT, {0, CMD.MOVE, CMD.OPT_INTERNAL, enterPoint_X,enterPoint_Y,enterPoint_Z}, {"alt"}} commandArray[2]= {CMD.INSERT, {0, CMD_JUMP, CMD.OPT_INTERNAL, exitPoint_X,exitPoint_Y,exitPoint_Z}, {"alt"}} commandArray[3]= extraCmd2 commandArray[4]= extraCmd1 effectedUnit[unitID].cmdCount = 2 effectedUnit[unitID].cmdOne.id = CMD.MOVE effectedUnit[unitID].cmdOne.x = enterPoint_X effectedUnit[unitID].cmdOne.y = enterPoint_Y effectedUnit[unitID].cmdOne.z = enterPoint_Z effectedUnit[unitID].cmdTwo.id = CMD_JUMP effectedUnit[unitID].cmdTwo.x = exitPoint_X effectedUnit[unitID].cmdTwo.y = exitPoint_Y effectedUnit[unitID].cmdTwo.z = exitPoint_Z issuedOrderTo[unitID] = {CMD.MOVE,enterPoint_X,enterPoint_Y,enterPoint_Z} else commandArray[1]= {CMD.INSERT, {0, CMD_JUMP, CMD.OPT_INTERNAL, exitPoint_X,exitPoint_Y,exitPoint_Z}, {"alt"}} commandArray[2]= extraCmd2 commandArray[3]= extraCmd1 effectedUnit[unitID].cmdCount = 1 effectedUnit[unitID].cmdTwo.id = CMD_JUMP effectedUnit[unitID].cmdTwo.x = exitPoint_X effectedUnit[unitID].cmdTwo.y = exitPoint_Y effectedUnit[unitID].cmdTwo.z = exitPoint_Z issuedOrderTo[unitID] = {CMD_JUMP,exitPoint_X,exitPoint_Y,exitPoint_Z} end spGiveOrderArrayToUnitArray({unitID},commandArray) waitForNetworkDelay = waitForNetworkDelay or {spGetGameSeconds(),0} waitForNetworkDelay[2] = waitForNetworkDelay[2] + 1 end elseif jumpCmdPos >= 2 then spGiveOrderArrayToUnitArray({unitID},{extraCmd2,extraCmd1}) --another command was sandwiched before the Jump command, making Jump possibly outdated/no-longer-optimal. Remove Jump effectedUnit[unitID].cmdCount = 0 end until true currentLoopCount = currentLoopCount + 1 end if k >= jumpersToJump_Count then finishLoop =true break elseif currentUnitProcessed >= numberOfUnitToProcessPerFrame or currentLoopCount>= numberOfLoopToProcessPerFrame then spreadJobs = true spreadPreviousIndex = k+1 --continue at next frame break end k = k + 1 end if finishLoop then spreadPreviousIndex = nil end end end function DeleteEntryThenReIndex(k,unitID) --last position to current position if k ~= jumpersToJump_Count then local lastUnitID = jumpersToJump[jumpersToJump_Count][2] jumpersToJump[k] = jumpersToJump[jumpersToJump_Count] jumpersUnitID[lastUnitID] = k end effectedUnit[unitID] = nil jumpersUnitID[unitID] = nil jumpersToJump[jumpersToJump_Count] = nil jumpersToJump_Count = jumpersToJump_Count - 1 end function GetNearestObstacleEnterAndExitPoint(currPosX,currPosY, currPosZ, targetPosX,targetPosZ, unitDefID) local nearestEnterPoint_X,original_X = currPosX,currPosX local nearestEnterPoint_Z,original_Z = currPosZ,currPosZ local nearestEnterPoint_Y,original_Y = currPosY,currPosY local exitPoint_X, exitPoint_Z,exitPoint_Y local overobstacle = false local distFromObstacle = 0 local distToTarget= 0 local unitBoxDist local defaultJumprange = jumperDefs[unitDefID].range -20 local addingFunction = function() end local check_n_SavePosition = function(x,z,gradient,addValue) local endOfLine = (math.abs(x-targetPosX) < 20) and (math.abs(z-targetPosZ) < 20) if endOfLine then return x,z,true end local y = Spring.GetGroundHeight(x, z) local clear,_ = Spring.TestBuildOrder(gaussUnitDefID or unitDefID, x,y ,z, 1) -- Spring.MarkerAddPoint(x,y ,z, clear) if clear == 0 then overobstacle = true if distToTarget==0 then distToTarget = math.sqrt((targetPosX-x)^2 + (targetPosZ-z)^2) local backX,backZ = addingFunction(x,z,addValue*-5,gradient) local backY = Spring.GetGroundHeight(backX, backZ) distFromObstacle = math.sqrt((x-backX)^2 + (z-backZ)^2) local backDistToTarget = math.sqrt((targetPosX-backX)^2 + (targetPosZ-backZ)^2) local unitDistToTarget = math.sqrt((targetPosX-original_X)^2 + (targetPosZ-original_Z)^2) if unitDistToTarget > backDistToTarget then nearestEnterPoint_X = backX --always used 1 step behind current box, avoid too close to terrain nearestEnterPoint_Z = backZ nearestEnterPoint_Y = backY else nearestEnterPoint_X = original_X --always used 1 step behind current box, avoid too close to terrain nearestEnterPoint_Z = original_Z nearestEnterPoint_Y = original_Y end -- Spring.MarkerAddPoint(backX,backY,backZ, "enter") else distFromObstacle = distFromObstacle + unitBoxDist distToTarget = distToTarget - unitBoxDist end elseif overobstacle then distFromObstacle = distFromObstacle + unitBoxDist distToTarget = distToTarget - unitBoxDist if distFromObstacle < defaultJumprange and distToTarget>0 then exitPoint_X = x exitPoint_Z = z exitPoint_Y = y -- Spring.MarkerAddPoint(x,y,z, "exit") else return x,z,true end end x,z = addingFunction(x,z,addValue,gradient) return x,z,false end local x, z = currPosX,currPosZ local xDiff = targetPosX -currPosX local zDiff = targetPosZ -currPosZ local unitBoxSize = jumperAddInfo[unitDefID][5] local finish=false if math.abs(xDiff) > math.abs(zDiff) then local xSgn = xDiff/math.abs(xDiff) local gradient = zDiff/xDiff unitBoxDist = math.sqrt(unitBoxSize*unitBoxSize + unitBoxSize*gradient*unitBoxSize*gradient) local xadd = unitBoxSize*xSgn addingFunction = function(x,z,addValue,gradient) return x+addValue, z+addValue*gradient end for i=1, 9999 do x,z,finish = check_n_SavePosition(x,z,gradient,xadd) if finish then break end end else local zSgn = zDiff/math.abs(zDiff) local gradient = xDiff/zDiff unitBoxDist = math.sqrt(unitBoxSize*unitBoxSize + unitBoxSize*gradient*unitBoxSize*gradient) local zadd = unitBoxSize*zSgn addingFunction = function(x,z,addValue,gradient) return x+addValue*gradient, z + addValue end for i=1, 9999 do x,z,finish = check_n_SavePosition(x,z,gradient,zadd) if finish then break end end end return nearestEnterPoint_X,nearestEnterPoint_Y,nearestEnterPoint_Z,exitPoint_X,exitPoint_Y,exitPoint_Z end function GetUnitFastestWeaponRange(unitDef) local fastestReloadTime, fastReloadRange = 999,-1 for _, weapons in ipairs(unitDef.weapons) do --reference: gui_contextmenu.lua by CarRepairer local weaponsID = weapons.weaponDef local weaponsDef = WeaponDefs[weaponsID] if weaponsDef.name and not (weaponsDef.name:find('fake') or weaponsDef.name:find('noweapon')) then --reference: gui_contextmenu.lua by CarRepairer if not weaponsDef.isShield then --if not shield then this is conventional weapon local reloadTime = weaponsDef.reload if reloadTime < fastestReloadTime then --find the weapon with the smallest reload time fastestReloadTime = reloadTime fastReloadRange = weaponsDef.range end end end end return fastReloadRange end function ConvertCMDToMOVE(command) if (command == nil) then return nil end command = command[1] if (command == nil) then return nil end if command.id == CMD.MOVE or command.id == CMD.PATROL or command.id == CMD.FIGHT or command.id == CMD.JUMP or command.id == CMD.ATTACK then if not command.params[2] then local x,y,z = spGetUnitPosition(command.params[1]) if not x then --outside LOS and radar return nil end command.id = CMD.MOVE command.params[1] = x command.params[2] = y command.params[3] = z return command else command.id = CMD.MOVE return command end end if command.id == CMD.RECLAIM or command.id == CMD.REPAIR or command.id == CMD.GUARD or command.id == CMD.RESSURECT then local isPossible2PartAreaCmd = command.params[5] if not command.params[4] or isPossible2PartAreaCmd then --if not area-command or the is the 2nd part of area-command (1st part have radius at 4th-param, 2nd part have unitID/featureID at 1st-param and radius at 5th-param) if not command.params[2] or isPossible2PartAreaCmd then local x,y,z if command.id == CMD.REPAIR or command.id == CMD.GUARD then x,y,z = GetUnitOrFeaturePosition(command.params[1]) elseif command.id == CMD.RECLAIM or command.id == CMD.RESSURECT then x,y,z = GetUnitOrFeaturePosition(command.params[1]) end if not x then return nil end command.id = CMD.MOVE command.params[1] = x command.params[2] = y command.params[3] = z return command else command.id = CMD.MOVE return command end else return nil --no area command allowed end end if command.id < 0 then if command.params[3]==nil then --is building unit in factory return nil end command.id = CMD.MOVE return command end if command.id == CMD_WAIT_AT_BEACON then return command end return nil end function GetWaypointDistance(unitID,moveID,queue,px,py,pz,isAttackCmd,weaponRange) --Note: source is from unit_transport_ai.lua (by Licho) local d = 0 if (queue == nil) then return 99999 end local v = queue if (v.id == CMD.MOVE) then local reachable = true --always assume target reachable local waypoints if moveID then --unit has compatible moveID? local minimumGoalDist = (isAttackCmd and weaponRange-20) or 128 local result, lastwaypoint result, lastwaypoint, waypoints = Spring.Utilities.IsTargetReachable(moveID,px,py,pz,v.params[1],v.params[2],v.params[3],minimumGoalDist) if result == "outofreach" then --abit out of reach? reachable=false --target is unreachable! end end if reachable then local distOffset = (isAttackCmd and weaponRange-20) or 0 if waypoints then --we have waypoint to destination? local way1,way2,way3 = px,py,pz for i=1, #waypoints do --sum all distance in waypoints d = d + Dist(way1,way2,way3, waypoints[i][1],waypoints[i][2],waypoints[i][3]) way1,way2,way3 = waypoints[i][1],waypoints[i][2],waypoints[i][3] end d = d + math.max(0,Dist(way1,way2,way3, v.params[1], v.params[2], v.params[3])-distOffset) --connect endpoint of waypoint to destination else --so we don't have waypoint? d = d + math.max(0,Dist(px,py, pz, v.params[1], v.params[2], v.params[3])-distOffset) --we don't have waypoint then measure straight line end else --pathing says target unreachable?! d = d + Dist(px,py, pz, v.params[1], v.params[2], v.params[3])*10 +9999 --target unreachable! end end return d end function Dist(x,y,z, x2, y2, z2) local xd = x2-x local yd = y2-y local zd = z2-z return math.sqrt(xd*xd + yd*yd + zd*zd) end function GetUnitOrFeaturePosition(id) --copied from cmd_commandinsert.lua widget (by dizekat) if id<=Game.maxUnits and spValidUnitID(id) then return spGetUnitPosition(id) elseif spValidFeatureID(id-Game.maxUnits) then return spGetFeaturePosition(id-Game.maxUnits) --featureID is always offset by maxunit count end return nil end ------------------------------------------------------------ ------------------------------------------------------------ function widget:UnitFinished(unitID,unitDefID,unitTeam) if myTeamID==unitTeam and jumperDefs[unitDefID] and not jumpersUnitID[unitID] then jumpersToJump_Count = jumpersToJump_Count + 1 jumpersToJump[jumpersToJump_Count] = {unitDefID,unitID} jumpersUnitID[unitID] = jumpersToJump_Count end end function widget:UnitCommand(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions) if myTeamID==unitTeam and jumperDefs[unitDefID] then if (cmdID ~= CMD.INSERT) then if not jumpersUnitID[unitID] then jumpersToJump_Count = jumpersToJump_Count + 1 jumpersToJump[jumpersToJump_Count] = {unitDefID,unitID} jumpersUnitID[unitID] = jumpersToJump_Count end end if (cmdID == CMD.INSERT) then --detected our own command (indicate network delay have passed) local issuedOrderContent = issuedOrderTo[unitID] if issuedOrderContent and (cmdParams[4] == issuedOrderContent[2] and cmdParams[5] == issuedOrderContent[3] and cmdParams[6] == issuedOrderContent[4]) then issuedOrderTo[unitID] = nil if waitForNetworkDelay then waitForNetworkDelay[2] = waitForNetworkDelay[2] - 1 if waitForNetworkDelay[2]==0 then waitForNetworkDelay = nil end end end end end end
gpl-2.0
1yvT0s/luvit
tests/test-tls-client-openssl-server.lua
12
2320
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. 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. --]] local childprocess = require('childprocess') local los = require('los') local tls = require('tls') local timer = require('timer') local path = require('luvi').path require('tap')(function(test) test('tls client econnreset', function(expect) local port, args, child, interval, timerCallback, key, cert local onInterval, onStartClient, client, data local count, maxCount if los.type() == 'win32' then return end count = 0 maxCount = 5 data = '' port = 32312 key = path.join(module.dir, 'fixtures', 'keys', 'agent1-key.pem') cert = path.join(module.dir, 'fixtures', 'keys', 'agent1-cert.pem') args = { 's_server', '-accept', port, '-key', key, '-cert', cert } child = childprocess.spawn('openssl', args) child.stdout:once('data', function(data) p(data) timer.setTimeout(100, begin) end) function begin() p('begin') interval = timer.setInterval(200, onInterval) timer.setTimeout(100, startClient) end function onInterval() p('onInterval') child.stdin:write('hello world\n') count = count + 1 if count == maxCount then timer.clearInterval(interval) end end function startClient() local onData, options, count p('onStartClient') options = { port = port, host = '127.0.0.1', rejectUnauthorized = false, } count = 0 function onData(_data) p('client data ' .. _data) data = data .. _data count = count + 1 if count == 5 then client:destroy() child:kill() end end client = tls.connect(options) client:on('data', onData) end end) end)
apache-2.0
Scavenge/darkstar
scripts/zones/Windurst_Woods/npcs/Bopa_Greso.lua
14
1855
----------------------------------- -- Area: Windurst Woods -- NPC: Bopa Greso -- Type: Standard NPC -- @zone 241 -- @pos 59.773 -6.249 216.766 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES); thickAsThievesCS = player:getVar("thickAsThievesCS"); if (thickAsThieves == QUEST_ACCEPTED) then player:startEvent(0x01FA); if (thickAsThievesCS == 1) then player:setVar("thickAsThievesCS",2); elseif (thickAsThievesCS == 3) then player:setVar("thickAsThievesCS",4); rand1 = math.random(2,7); player:setVar("thickAsThievesGrapplingCS",rand1); player:setVar("thickAsThievesGamblingCS",1); end else player:startEvent(0x004d); -- standard cs end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Tehf_Kimasnahya.lua
14
3139
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Tehf Kimasnahya -- Type: Standard NPC -- @pos -89.897 -1 6.199 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local gotitall = player:getQuestStatus(AHT_URHGAN,GOT_IT_ALL); local gotItAllProg = player:getVar("gotitallCS"); local threeMenProg = player:getVar("threemenandaclosetCS"); if (gotitall == QUEST_AVAILABLE) then player:startEvent(0x0208); elseif (gotItAllProg == 4) then player:startEvent(0x020d); elseif (gotItAllProg == 6) then player:startEvent(0x020f); elseif (gotItAllProg >= 7 and player:getVar("Wait1DayForgotitallCS_date") < os.time() and player:needToZone() == false) then player:startEvent(0x0210); elseif (gotItAllProg >= 7) then player:startEvent(0x021b); elseif (gotItAllProg >= 1 and gotItAllProg <= 3) then player:startEvent(0x0209); elseif (threeMenProg == 5) then player:startEvent(0x034b); elseif (threeMenProg == 6) then player:startEvent(0x034c); else player:startEvent(0x0211); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0208) then player:addQuest(AHT_URHGAN,GOT_IT_ALL); player:setVar("gotitallCS",1); elseif (csid == 0x020d and option == 0) then player:setVar("gotitallCS",5); player:delKeyItem(VIAL_OF_LUMINOUS_WATER); elseif (csid == 0x020f) then player:setVar("gotitallCS",7); player:setVar("Wait1DayForgotitallCS_date", getMidnight()); player:needToZone(true); elseif (csid == 0x021b) then player:setVar("gotitallCS",8); elseif (csid == 0x0210) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18257); else player:setVar("Wait1DayForgotitallCS_date",0); player:setVar("gotitallCS",0); player:addItem(18257); -- Bibiki Seashell player:messageSpecial(ITEM_OBTAINED,18257); player:completeQuest(AHT_URHGAN,GOT_IT_ALL); end elseif (csid == 0x034b and option == 1) then player:setVar("threemenandaclosetCS",6); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Port_San_dOria/npcs/Leonora.lua
14
1532
----------------------------------- -- Area: Port San d'Oria -- NPC: Leonora -- Involved in Quest: -- @zone 232 -- @pos -24 -8 15 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getZPos() >= 12) then player:startEvent(0x0206); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
endlessm/chromium-browser
third_party/flatbuffers/src/tests/MyGame/Example/TestSimpleTableWithEnum.lua
10
1204
-- automatically generated by the FlatBuffers compiler, do not modify -- namespace: Example local flatbuffers = require('flatbuffers') local TestSimpleTableWithEnum = {} -- the module local TestSimpleTableWithEnum_mt = {} -- the class metatable function TestSimpleTableWithEnum.New() local o = {} setmetatable(o, {__index = TestSimpleTableWithEnum_mt}) return o end function TestSimpleTableWithEnum.GetRootAsTestSimpleTableWithEnum(buf, offset) local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) local o = TestSimpleTableWithEnum.New() o:Init(buf, n + offset) return o end function TestSimpleTableWithEnum_mt:Init(buf, pos) self.view = flatbuffers.view.New(buf, pos) end function TestSimpleTableWithEnum_mt:Color() local o = self.view:Offset(4) if o ~= 0 then return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos) end return 2 end function TestSimpleTableWithEnum.Start(builder) builder:StartObject(1) end function TestSimpleTableWithEnum.AddColor(builder, color) builder:PrependUint8Slot(0, color, 2) end function TestSimpleTableWithEnum.End(builder) return builder:EndObject() end return TestSimpleTableWithEnum -- return the module
bsd-3-clause
omidtarh/wezard
plugins/torrent_search.lua
411
1622
--[[ NOT USED DUE TO SSL ERROR -- See https://getstrike.net/api/ local function strike_search(query) local strike_base = 'http://getstrike.net/api/v2/torrents/' local url = strike_base..'search/?phrase='..URL.escape(query) print(url) local b,c = http.request(url) print(b,c) local search = json:decode(b) vardump(search) if c ~= 200 then return search.message end vardump(search) local results = search.results local text = 'Results: '..results local results = math.min(results, 3) for i=1,results do local torrent = search.torrents[i] text = text..torrent.torrent_title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.seeds ..'\n'..torrent.magnet_uri..'\n\n' end return text end]]-- local function search_kickass(query) local url = 'http://kat.cr/json.php?q='..URL.escape(query) local b,c = http.request(url) local data = json:decode(b) local text = 'Results: '..data.total_results..'\n\n' local results = math.min(#data.list, 5) for i=1,results do local torrent = data.list[i] local link = torrent.torrentLink link = link:gsub('%?title=.+','') text = text..torrent.title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.leechs ..'\n'..link --..'\n magnet:?xt=urn:btih:'..torrent.hash ..'\n\n' end return text end local function run(msg, matches) local query = matches[1] return search_kickass(query) end return { description = "Search Torrents", usage = "!torrent <search term>: Search for torrent", patterns = { "^!torrent (.+)$" }, run = run }
gpl-2.0
Scavenge/darkstar
scripts/zones/Cirdas_Caverns/Zone.lua
17
1223
----------------------------------- -- -- Zone: Cirdas Caverns -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Cirdas_Caverns/TextIDs"] = nil; require("scripts/zones/Cirdas_Caverns/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-180,30,-314,203); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/weaponskills/spirits_within.lua
9
2186
----------------------------------- -- Spirits Within -- Sword weapon skill -- Spirits Within Sword Weapon Skill -- TrolandAdded by Troland -- Skill Level: 175 -- Delivers an unavoidable attack. Damage varies with HP and TP. -- Not aligned with any "elemental gorgets" or "elemental belts" due to it's absence of Skillchain properties. -- Element: None -- Modifiers: HP: -- 100%TP 200%TP 300%TP -- 12.5% 50% 100% ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); require("scripts/globals/utils"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local HP = player:getHP(); local WSC = 0; local tpHits = 0; -- Damage calculations based on https://www.bg-wiki.com/index.php?title=Spirits_Within&oldid=269806 if (tp == 3000) then WSC = math.floor(HP * 120/256); elseif (tp >= 2000) then WSC = math.floor(HP * (math.floor(0.072 * tp) - 96) / 256) elseif (tp >= 1000) then WSC = math.floor(HP * (math.floor(0.016 * tp) + 16) / 256) end if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then -- Damage calculations changed based on: http://www.bg-wiki.com/bg/Spirits_Within http://www.bluegartr.com/threads/121610-Rehauled-Weapon-Skills-tier-lists?p=6142188&viewfull=1#post6142188 if (tp == 3000) then WSC = HP; elseif (tp >= 2000) then WSC = math.floor(HP * .5); elseif (tp >= 1000) then WSC = math.floor(HP * .125); end end local damage = target:breathDmgTaken(WSC); if (damage > 0) then if (player:getOffhandDmg() > 0) then tpHits = 2; else tpHits = 1; end end if (player:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID) > 0) then damage = damage * (100 + player:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID))/100 end damage = damage * WEAPON_SKILL_POWER damage = takeWeaponskillDamage(target, player, {}, primary, damage, SLOT_MAIN, tpHits, 0, nil) return tpHits, 0, false, damage; end
gpl-3.0
Scavenge/darkstar
scripts/zones/Fort_Karugo-Narugo_[S]/npcs/Mortimer.lua
14
1077
---------------------------------- -- Area: Fort Karugo Narugo [S] -- NPC: Mortimer -- Type: Item Deliverer -- @zone 96 -- @pos -24.08 -68.508 93.88 -- ----------------------------------- package.loaded["scripts/zones/Fort_Karugo-Narugo_[S]/TextIDs"] = nil; require("scripts/zones/Fort_Karugo-Narugo_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
1yvT0s/luvit
tests/test-tls-connect-simple-twice.lua
11
1173
require('tap')(function (test) local fixture = require('./fixture-tls') local tls = require('tls') local options = { cert = fixture.certPem, key = fixture.keyPem } local serverConnected = 0 local clientConnected = 0 test("tls connect simple twice", function() local server server = tls.createServer(options, function(conn,err) p(conn) p(err) serverConnected = serverConnected + 1 if (serverConnected == 2) then server:close() end conn:destroy() end) server:listen(fixture.commonPort, function() p('listen') local client1, client2 client1 = tls.connect({port = fixture.commonPort, host = '127.0.0.1'}) client1:on('connect', function() p('connect 1') clientConnected = clientConnected + 1 client1:on('end',function() client1:destroy() end) client2 = tls.connect({port = fixture.commonPort, host = '127.0.0.1'}) client2:on('connect', function() p('connect 2') clientConnected = clientConnected + 1 client2:on('end',function() client2:destroy() end) end) end) end) end) end)
apache-2.0
Necktrox/mta-discord-bot
mta/discord/util.lua
4
2093
function utf8.split(self, separator) assert(type(self) == "string", "expected string at argument 1, got ".. type(self)) assert(type(separator) == "string", "expected string at argument 2, got ".. type(separator)) local rows = {} local position, startpoint = false, 1 local sepLength = utf8.len(separator) repeat position = utf8.find(self, separator, startpoint, true) local part = utf8.sub(self, startpoint, position and (position - 1) or nil) startpoint = position and (position + sepLength) if part ~= "" then rows[#rows + 1] = part end until not position return rows end local function isKeyValuePairJSONCompatible(key_t, value_t) return (key_t == "boolean" or key_t == "number" or key_t == "string") and (value_t == "boolean" or value_t == "number" or value_t == "string" or value_t == "table") end function table.rawcopy(self) assert(type(self) == "table", "expected table at argument 1, got ".. type(self)) local references = {} local function recursive(self) local copy = {} for key, value in pairs(self) do local key_t = type(key) local value_t = type(value) if isKeyValuePairJSONCompatible(key_t, value_t) then if value_t == "table" then -- Recursive if references[key] == nil then references[key] = recursive(value) end copy[key] = references[key] else copy[key] = value end end end return copy end return recursive(self) end function table.json(self, compact) assert(type(self) == "table", "expected table at argument 1, got ".. type(self)) assert(compact == nil or type(compact) == "boolean", "expected boolean at argument 2, got ".. type(compact)) compact = (compact == nil or compact) return toJSON(table.rawcopy(self), compact):sub(compact and 2 or 3, compact and -2 or -3) end
isc
Kyklas/luci-proto-hso
applications/luci-olsr/luasrc/controller/olsr.lua
35
9709
module("luci.controller.olsr", package.seeall) function index() local ipv4,ipv6 if nixio.fs.access("/etc/config/olsrd") then ipv4 = 1 end if nixio.fs.access("/etc/config/olsrd6") then ipv6 = 1 end if not ipv4 and not ipv6 then return end require("luci.model.uci") local uci = luci.model.uci.cursor_state() uci:foreach("olsrd", "olsrd", function(s) if s.SmartGateway and s.SmartGateway == "yes" then has_smartgw = true end end) local page = node("admin", "status", "olsr") page.target = template("status-olsr/overview") page.title = _("OLSR") page.subindex = true local page = node("admin", "status", "olsr", "json") page.target = call("action_json") page.title = nil page.leaf = true local page = node("admin", "status", "olsr", "neighbors") page.target = call("action_neigh") page.title = _("Neighbours") page.subindex = true page.order = 5 local page = node("admin", "status", "olsr", "routes") page.target = call("action_routes") page.title = _("Routes") page.order = 10 local page = node("admin", "status", "olsr", "topology") page.target = call("action_topology") page.title = _("Topology") page.order = 20 local page = node("admin", "status", "olsr", "hna") page.target = call("action_hna") page.title = _("HNA") page.order = 30 local page = node("admin", "status", "olsr", "mid") page.target = call("action_mid") page.title = _("MID") page.order = 50 if has_smartgw then local page = node("admin", "status", "olsr", "smartgw") page.target = call("action_smartgw") page.title = _("SmartGW") page.order = 60 end local page = node("admin", "status", "olsr", "interfaces") page.target = call("action_interfaces") page.title = _("Interfaces") page.order = 70 odsp = entry( {"admin", "services", "olsrd", "display"}, cbi("olsr/olsrddisplay"), _("Display") ) end function action_json() local http = require "luci.http" local utl = require "luci.util" local uci = require "luci.model.uci".cursor_state() local jsonreq4 local jsonreq6 jsonreq4 = utl.exec("echo /status | nc 127.0.0.1 9090") jsonreq6 = utl.exec("echo /status | nc ::1 9090") http.prepare_content("application/json") if not jsonreq4 or jsonreq4 == "" then jsonreq4 = "{}" end if not jsonreq6 or jsonreq6 == "" then jsonreq6 = "{}" end http.write('{"v4":' .. jsonreq4 .. ', "v6":' .. jsonreq6 .. '}') end function action_neigh(json) local data, has_v4, has_v6, error = fetch_jsoninfo('links') if error then return end local uci = require "luci.model.uci".cursor_state() local resolve = uci:get("luci_olsr", "general", "resolve") local ntm = require "luci.model.network".init() local devices = ntm:get_wifidevs() local sys = require "luci.sys" local assoclist = {} --local neightbl = require "neightbl" local ipc = require "luci.ip" luci.sys.net.routes(function(r) if r.dest:prefix() == 0 then defaultgw = r.gateway:string() end end) local function compare(a,b) if a.proto == b.proto then return a.linkCost < b.linkCost else return a.proto < b.proto end end for _, dev in ipairs(devices) do for _, net in ipairs(dev:get_wifinets()) do assoclist[#assoclist+1] = {} assoclist[#assoclist]['ifname'] = net.iwdata.ifname assoclist[#assoclist]['network'] = net.iwdata.network assoclist[#assoclist]['device'] = net.iwdata.device assoclist[#assoclist]['list'] = net.iwinfo.assoclist end end for k, v in ipairs(data) do local interface local snr = 0 local signal = 0 local noise = 0 local arptable = sys.net.arptable() local mac = "" local rmac = "" local lmac = "" local ip local neihgt = {} if resolve == "1" then hostname = nixio.getnameinfo(v.remoteIP, nil, 100) if hostname then v.hostname = hostname end end if v.proto == '4' then uci:foreach("network", "interface",function(vif) if vif.ipaddr and vif.ipaddr == v.localIP then interface = vif['.name'] or vif.interface lmac = string.lower(vif.macaddr or "") return end end) for _, arpt in ipairs(arptable) do ip = arpt['IP address'] if ip == v.remoteIP then rmac = string.lower(arpt['HW address'] or "") end end elseif v.proto == '6' then uci:foreach("network", "interface",function(vif) local name = vif['.name'] local net = ntm:get_network(name) local device = net and net:get_interface() local locip = ipc.IPv6(v.localIP) if device and device:ip6addrs() and locip then for _, a in ipairs(device:ip6addrs()) do if not a:is6linklocal() then if a:host() == locip:host() then interface = name --neihgt = neightbl.get(device.ifname) or {} end end end end end) --[[ for ip,mac in pairs(neihgt) do if ip == v.remoteIP then rmac = mac end end ]]-- end for _, val in ipairs(assoclist) do if val.network == interface and val.list then for assocmac, assot in pairs(val.list) do assocmac = string.lower(assocmac or "") if rmac == assocmac then signal = tonumber(assot.signal) noise = tonumber(assot.noise) snr = (noise*-1) - (signal*-1) end end end end if interface then v.interface = interface end v.snr = snr v.signal = signal v.noise = noise if rmac then v.remoteMAC = rmac end if lmac then v.localMAC = lmac end if defaultgw == v.remoteIP then v.defaultgw = 1 end end table.sort(data, compare) luci.template.render("status-olsr/neighbors", {links=data, has_v4=has_v4, has_v6=has_v6}) end function action_routes() local data, has_v4, has_v6, error = fetch_jsoninfo('routes') if error then return end local uci = require "luci.model.uci".cursor_state() local resolve = uci:get("luci_olsr", "general", "resolve") for k, v in ipairs(data) do if resolve == "1" then local hostname = nixio.getnameinfo(v.gateway, nil, 100) if hostname then v.hostname = hostname end end end local function compare(a,b) if a.proto == b.proto then return a.rtpMetricCost < b.rtpMetricCost else return a.proto < b.proto end end table.sort(data, compare) luci.template.render("status-olsr/routes", {routes=data, has_v4=has_v4, has_v6=has_v6}) end function action_topology() local data, has_v4, has_v6, error = fetch_jsoninfo('topology') if error then return end local function compare(a,b) if a.proto == b.proto then return a.tcEdgeCost < b.tcEdgeCost else return a.proto < b.proto end end table.sort(data, compare) luci.template.render("status-olsr/topology", {routes=data, has_v4=has_v4, has_v6=has_v6}) end function action_hna() local data, has_v4, has_v6, error = fetch_jsoninfo('hna') if error then return end local uci = require "luci.model.uci".cursor_state() local resolve = uci:get("luci_olsr", "general", "resolve") local function compare(a,b) if a.proto == b.proto then return a.genmask < b.genmask else return a.proto < b.proto end end for k, v in ipairs(data) do if resolve == "1" then hostname = nixio.getnameinfo(v.gateway, nil, 100) if hostname then v.hostname = hostname end end if v.validityTime then v.validityTime = tonumber(string.format("%.0f", v.validityTime / 1000)) end end table.sort(data, compare) luci.template.render("status-olsr/hna", {hna=data, has_v4=has_v4, has_v6=has_v6}) end function action_mid() local data, has_v4, has_v6, error = fetch_jsoninfo('mid') if error then return end local function compare(a,b) if a.proto == b.proto then return a.ipAddress < b.ipAddress else return a.proto < b.proto end end table.sort(data, compare) luci.template.render("status-olsr/mid", {mids=data, has_v4=has_v4, has_v6=has_v6}) end function action_smartgw() local data, has_v4, has_v6, error = fetch_jsoninfo('gateways') if error then return end local function compare(a,b) if a.proto == b.proto then return a.tcPathCost < b.tcPathCost else return a.proto < b.proto end end table.sort(data, compare) luci.template.render("status-olsr/smartgw", {gws=data, has_v4=has_v4, has_v6=has_v6}) end function action_interfaces() local data, has_v4, has_v6, error = fetch_jsoninfo('interfaces') if error then return end local function compare(a,b) return a.proto < b.proto end table.sort(data, compare) luci.template.render("status-olsr/interfaces", {iface=data, has_v4=has_v4, has_v6=has_v6}) end -- Internal function fetch_jsoninfo(otable) local uci = require "luci.model.uci".cursor_state() local utl = require "luci.util" local json = require "luci.json" local IpVersion = uci:get_first("olsrd", "olsrd","IpVersion") local jsonreq4 = "" local jsonreq6 = "" jsonreq4 = utl.exec("echo /" .. otable .. " | nc 127.0.0.1 9090") jsonreq6 = utl.exec("echo /" .. otable .. " | nc ::1 9090") local jsondata4 = {} local jsondata6 = {} local data4 = {} local data6 = {} local has_v4 = False local has_v6 = False if jsonreq4 == '' and jsonreq6 == '' then luci.template.render("status-olsr/error_olsr") return nil, 0, 0, true end if jsonreq4 ~= "" then has_v4 = 1 jsondata4 = json.decode(jsonreq4) if otable == 'status' then data4 = jsondata4 or {} else data4 = jsondata4[otable] or {} end for k, v in ipairs(data4) do data4[k]['proto'] = '4' end end if jsonreq6 ~= "" then has_v6 = 1 jsondata6 = json.decode(jsonreq6) if otable == 'status' then data6 = jsondata6 or {} else data6 = jsondata6[otable] or {} end for k, v in ipairs(data6) do data6[k]['proto'] = '6' end end for k, v in ipairs(data6) do table.insert(data4, v) end return data4, has_v4, has_v6, false end
apache-2.0
xincun/nginx-openresty-windows
lua-resty-mysql-0.15/t/lib/ljson.lua
76
1871
local ngx_null = ngx.null local tostring = tostring local byte = string.byte local gsub = string.gsub local sort = table.sort local pairs = pairs local ipairs = ipairs local concat = table.concat local ok, new_tab = pcall(require, "table.new") if not ok then new_tab = function (narr, nrec) return {} end end local _M = {} local metachars = { ['\t'] = '\\t', ["\\"] = "\\\\", ['"'] = '\\"', ['\r'] = '\\r', ['\n'] = '\\n', } local function encode_str(s) -- XXX we will rewrite this when string.buffer is implemented -- in LuaJIT 2.1 because string.gsub cannot be JIT compiled. return gsub(s, '["\\\r\n\t]', metachars) end local function is_arr(t) local exp = 1 for k, _ in pairs(t) do if k ~= exp then return nil end exp = exp + 1 end return exp - 1 end local encode encode = function (v) if v == nil or v == ngx_null then return "null" end local typ = type(v) if typ == 'string' then return '"' .. encode_str(v) .. '"' end if typ == 'number' or typ == 'boolean' then return tostring(v) end if typ == 'table' then local n = is_arr(v) if n then local bits = new_tab(n, 0) for i, elem in ipairs(v) do bits[i] = encode(elem) end return "[" .. concat(bits, ",") .. "]" end local keys = {} local i = 0 for key, _ in pairs(v) do i = i + 1 keys[i] = key end sort(keys) local bits = new_tab(0, i) i = 0 for _, key in ipairs(keys) do i = i + 1 bits[i] = encode(key) .. ":" .. encode(v[key]) end return "{" .. concat(bits, ",") .. "}" end return '"<' .. typ .. '>"' end _M.encode = encode return _M
bsd-2-clause
Dyaxler/SpartanUI
Modules/RaidFrames/scripts/Options.lua
1
5384
local SUI = SUI local L = SUI.L local RaidFrames = SUI.RaidFrames ---------------------------------------------------------------------------------------------------- function RaidFrames:OnInitialize() SUI.opt.args['RaidFrames'].args['DisplayOpts'] = { name = L['DisplayOpts'], type = 'group', order = 100, inline = true, args = { toggleraid = { name = L['ShowRFrames'], type = 'toggle', order = 1, get = function(info) return SUI.DBMod.RaidFrames.showRaid end, set = function(info, val) SUI.DBMod.RaidFrames.showRaid = val RaidFrames:UpdateRaid('FORCE_UPDATE') end }, toggleparty = { name = L['PartyDispParty'], type = 'toggle', order = 2, get = function(info) return SUI.DBMod.RaidFrames.showParty end, set = function(info, val) SUI.DBMod.RaidFrames.showParty = val RaidFrames:UpdateRaid('FORCE_UPDATE') end }, togglesolo = { name = L['PartyDispSolo'], type = 'toggle', order = 4, get = function(info) return SUI.DBMod.RaidFrames.showSolo end, set = function(info, val) SUI.DBMod.RaidFrames.showSolo = val RaidFrames:UpdateRaid('FORCE_UPDATE') end }, toggleclassname = { name = L['ClrNameClass'], type = 'toggle', order = 1, get = function(info) return SUI.DBMod.RaidFrames.showClass end, set = function(info, val) SUI.DBMod.RaidFrames.showClass = val RaidFrames:UpdateRaid('FORCE_UPDATE') end }, scale = { name = L['ScaleSize'], type = 'range', order = 5, width = 'full', step = .01, min = .01, max = 2, get = function(info) return SUI.DBMod.RaidFrames.scale end, set = function(info, val) if (InCombatLockdown()) then SUI:Print(ERR_NOT_IN_COMBAT) else SUI.DBMod.RaidFrames.scale = val RaidFrames:UpdateRaid('FORCE_UPDATE') end end }, bar1 = {name = L['LayoutConf'], type = 'header', order = 20}, maxColumns = { name = L['MaxCols'], type = 'range', order = 21, width = 'full', step = 1, min = 1, max = 40, get = function(info) return SUI.DBMod.RaidFrames.maxColumns end, set = function(info, val) if (InCombatLockdown()) then SUI:Print(ERR_NOT_IN_COMBAT) else SUI.DBMod.RaidFrames.maxColumns = val RaidFrames:UpdateRaid('FORCE_UPDATE') end end }, unitsPerColumn = { name = L['UnitPerCol'], type = 'range', order = 22, width = 'full', step = 1, min = 1, max = 40, get = function(info) return SUI.DBMod.RaidFrames.unitsPerColumn end, set = function(info, val) if (InCombatLockdown()) then SUI:Print(ERR_NOT_IN_COMBAT) else SUI.DBMod.RaidFrames.unitsPerColumn = val RaidFrames:UpdateRaid('FORCE_UPDATE') end end }, columnSpacing = { name = L['ColSpacing'], type = 'range', order = 23, width = 'full', step = 1, min = 0, max = 200, get = function(info) return SUI.DBMod.RaidFrames.columnSpacing end, set = function(info, val) if (InCombatLockdown()) then SUI:Print(ERR_NOT_IN_COMBAT) else SUI.DBMod.RaidFrames.columnSpacing = val RaidFrames:UpdateRaid('FORCE_UPDATE') end end }, desc1 = {name = L['LayoutConfDesc'], type = 'description', order = 29.9}, bar3 = {name = L['TextStyle'], type = 'header', order = 30}, healthtextstyle = { name = L['HTextStyle'], type = 'select', order = 31, desc = L['TextStyle1Desc'] .. '|n' .. L['TextStyle2Desc'] .. '|n' .. L['TextStyle3Desc'], values = { ['long'] = L['TextStyle1'], ['longfor'] = L['TextStyle2'], ['dynamic'] = L['TextStyle3'], ['disabled'] = L['Disabled'] }, get = function(info) return SUI.DBMod.RaidFrames.bars.health.textstyle end, set = function(info, val) SUI.DBMod.RaidFrames.bars.health.textstyle = val RaidFrames:UpdateText() end }, healthtextmode = { name = L['HTextMode'], type = 'select', order = 32, values = {[1] = L['HTextMode1'], [2] = L['HTextMode2'], [3] = L['HTextMode3']}, get = function(info) return SUI.DBMod.RaidFrames.bars.health.textmode end, set = function(info, val) SUI.DBMod.RaidFrames.bars.health.textmode = val RaidFrames:UpdateText() end } } } SUI.opt.args['RaidFrames'].args['mode'] = { name = L['LayMode'], type = 'select', order = 3, values = {['NAME'] = L['LayName'], ['GROUP'] = L['LayGrp'], ['ASSIGNEDROLE'] = L['LayRole']}, get = function(info) return SUI.DBMod.RaidFrames.mode end, set = function(info, val) SUI.DBMod.RaidFrames.mode = val RaidFrames:UpdateRaid('FORCE_UPDATE') end } SUI.opt.args['RaidFrames'].args['raidLockReset'] = { name = L['ResetRaidPos'], type = 'execute', order = 11, func = function() if (InCombatLockdown()) then SUI:Print(ERR_NOT_IN_COMBAT) else SUI.DBMod.RaidFrames.moved = false RaidFrames:UpdateRaidPosition() end end } SUI.opt.args['RaidFrames'].args['HideBlizz'] = { name = L['HideBlizzFrames'], type = 'toggle', order = 4, get = function(info) return SUI.DBMod.RaidFrames.HideBlizzFrames end, set = function(info, val) SUI.DBMod.RaidFrames.HideBlizzFrames = val end } end
gpl-3.0
Scavenge/darkstar
scripts/zones/Cloister_of_Frost/npcs/Ice_Protocrystal.lua
14
1920
----------------------------------- -- Area: Cloister of Frost -- NPC: Ice Protocrystal -- Involved in Quests: Trial by Ice, Trial Size Trial by Ice -- @pos 558 0 596 203 ----------------------------------- package.loaded["scripts/zones/Cloister_of_Frost/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); require("scripts/zones/Cloister_of_Frost/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:getVar("ASA4_Azure") == 1) then player:startEvent(0x0002); elseif (EventTriggerBCNM(player,npc)) then return; else player:messageSpecial(PROTOCRYSTAL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (csid==0x0002) then player:delKeyItem(DOMINAS_AZURE_SEAL); player:addKeyItem(AZURE_COUNTERSEAL); player:messageSpecial(KEYITEM_OBTAINED,AZURE_COUNTERSEAL); player:setVar("ASA4_Azure","2"); elseif (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
BlockMen/minetest_next
mods/default/environment.lua
2
6086
-- -- Lavacooling -- default.cool_lava_source = function(pos) minetest.set_node(pos, {name = "default:obsidian"}) minetest.sound_play("default_cool_lava", {pos = pos, max_hear_distance = 16, gain = 0.25}) end default.cool_lava_flowing = function(pos) minetest.set_node(pos, {name = "default:stone"}) minetest.sound_play("default_cool_lava", {pos = pos, max_hear_distance = 16, gain = 0.25}) end minetest.register_abm({ nodenames = {"default:lava_flowing"}, neighbors = {"group:water"}, interval = 1, chance = 2, action = function(...) default.cool_lava_flowing(...) end, }) minetest.register_abm({ nodenames = {"default:lava_source"}, neighbors = {"group:water"}, interval = 1, chance = 2, action = function(...) default.cool_lava_source(...) end, }) -- -- Growing -- -- Grass minetest.register_abm({ nodenames = {"default:dirt"}, interval = 2, chance = 200, action = function(pos, node) local above = {x = pos.x, y = pos.y + 1, z = pos.z} local name = minetest.get_node(above).name local nodedef = minetest.registered_nodes[name] if nodedef and (nodedef.sunlight_propagates or nodedef.paramtype == "light") and nodedef.liquidtype == "none" and (minetest.get_node_light(above) or 0) >= 13 then if name == "default:snow" or name == "default:snowblock" then minetest.set_node(pos, {name = "default:dirt_with_snow"}) else minetest.set_node(pos, {name = "default:dirt_with_grass"}) end end end }) -- Remove grass minetest.register_abm({ nodenames = {"default:dirt_with_grass", "default:dirt_with_dry_grass"}, interval = 2, chance = 20, action = function(pos, node) local above = {x = pos.x, y = pos.y + 1, z = pos.z} local name = minetest.get_node(above).name local nodedef = minetest.registered_nodes[name] if name ~= "ignore" and nodedef and not ((nodedef.sunlight_propagates or nodedef.paramtype == "light") and nodedef.liquidtype == "none") then minetest.set_node(pos, {name = "default:dirt"}) end end }) -- Cactus function default.grow_cactus(pos, node) if node.param2 >= 4 then return end pos.y = pos.y - 1 if minetest.get_item_group(minetest.get_node(pos).name, "sand") == 0 then return end pos.y = pos.y + 1 local height = 0 while node.name == "default:cactus" and height < 4 do height = height + 1 pos.y = pos.y + 1 node = minetest.get_node(pos) end if height == 4 or node.name ~= "air" then return end minetest.set_node(pos, {name = "default:cactus"}) return true end minetest.register_abm({ nodenames = {"default:cactus"}, neighbors = {"group:sand"}, interval = 50, chance = 20, action = function(...) default.grow_cactus(...) end }) -- Papyrus function default.grow_papyrus(pos, node) pos.y = pos.y - 1 local name = minetest.get_node(pos).name if name ~= "default:dirt_with_grass" and name ~= "default:dirt" then return end if not minetest.find_node_near(pos, 3, {"group:water"}) then return end pos.y = pos.y + 1 local height = 0 while node.name == "default:papyrus" and height < 4 do height = height + 1 pos.y = pos.y + 1 node = minetest.get_node(pos) end if height == 4 or node.name ~= "air" then return end minetest.set_node(pos, {name = "default:papyrus"}) return true end minetest.register_abm({ nodenames = {"default:papyrus"}, neighbors = {"default:dirt", "default:dirt_with_grass", "default:sand"}, interval = 50, chance = 20, action = function(...) default.grow_papyrus(...) end }) -- -- Leafdecay -- default.leafdecay_trunk_cache = {} default.leafdecay_enable_cache = true -- Spread the load of finding trunks default.leafdecay_trunk_find_allow_accumulator = 0 minetest.register_globalstep(function(dtime) local finds_per_second = 5000 default.leafdecay_trunk_find_allow_accumulator = math.floor(dtime * finds_per_second) end) default.after_place_leaves = function(pos, placer, itemstack, pointed_thing) local node = minetest.get_node(pos) node.param2 = 1 minetest.set_node(pos, node) end minetest.register_abm({ nodenames = {"group:leafdecay"}, neighbors = {"air", "group:liquid"}, -- A low interval and a high inverse chance spreads the load interval = 2, chance = 5, action = function(p0, node, _, _) local do_preserve = false local d = minetest.registered_nodes[node.name].groups.leafdecay if not d or d == 0 then --print("not groups.leafdecay") return end local n0 = minetest.get_node(p0) if n0.param2 ~= 0 then return end local p0_hash = nil if default.leafdecay_enable_cache then p0_hash = minetest.hash_node_position(p0) local trunkp = default.leafdecay_trunk_cache[p0_hash] if trunkp then local n = minetest.get_node(trunkp) local reg = minetest.registered_nodes[n.name] -- Assume ignore is a trunk, to make the thing -- work at the border of the active area if n.name == "ignore" or (reg and reg.groups.tree and reg.groups.tree ~= 0) then return end -- Cache is invalid table.remove(default.leafdecay_trunk_cache, p0_hash) end end if default.leafdecay_trunk_find_allow_accumulator <= 0 then return end default.leafdecay_trunk_find_allow_accumulator = default.leafdecay_trunk_find_allow_accumulator - 1 -- Assume ignore is a trunk, to make the thing -- work at the border of the active area local p1 = minetest.find_node_near(p0, d, {"ignore", "group:tree"}) if p1 then do_preserve = true if default.leafdecay_enable_cache then -- Cache the trunk default.leafdecay_trunk_cache[p0_hash] = p1 end end if not do_preserve then -- Drop stuff other than the node itself local itemstacks = minetest.get_node_drops(n0.name) for _, itemname in ipairs(itemstacks) do if minetest.get_item_group(n0.name, "leafdecay_drop") ~= 0 or itemname ~= n0.name then local p_drop = { x = p0.x - 0.5 + math.random(), y = p0.y - 0.5 + math.random(), z = p0.z - 0.5 + math.random(), } minetest.add_item(p_drop, itemname) end end -- Remove node minetest.remove_node(p0) nodeupdate(p0) end end })
gpl-3.0
Brenin/PJ-3100
Working Launchers/Games/Stepmania/StepMania 5/Themes/_fallback/Graphics/ScreenHighScores ScrollerItem/default.lua
1
2703
local t = Def.ActorFrame { InitCommand=cmd(runcommandsonleaves,cmd(ztest,true)); }; t[#t+1] = LoadActor("frame") .. { InitCommand=cmd(diffusealpha,0.1;); }; t[#t+1] = Def.TextBanner { InitCommand=cmd(x,-196;y,0;Load,"TextBannerHighScores"); SetCommand=function(self, params) if params.Song then self:SetFromSong( params.Song ); self:diffuse( SONGMAN:GetSongColor(params.Song) ); else self:SetFromString( params.Course:GetTitle() ); self:diffuse( SONGMAN:GetCourseColor(params.Course) ); end end; }; local NumColumns = THEME:GetMetric(Var "LoadingScreen", "NumColumns"); local c; local Scores = Def.ActorFrame { InitCommand = function(self) c = self:GetChildren(); end; }; t[#t+1] = Scores; for idx=1,NumColumns do local x_pos = -60 + 80 * (idx-1); Scores[#Scores+1] = LoadFont(Var "LoadingScreen","Name") .. { Name = idx .. "Name"; InitCommand=cmd(x,x_pos;y,6;shadowlengthx,0;shadowlengthy,2;shadowcolor,color("#000000");maxwidth,68;); }; Scores[#Scores+1] = LoadFont(Var "LoadingScreen","Score") .. { Name = idx .. "Score"; InitCommand=cmd(x,x_pos;y,-10;shadowlengthx,0;shadowlengthy,2;shadowcolor,color("#000000");maxwidth,68;); }; Scores[#Scores+1] = LoadActor("filled") .. { Name = idx .. "Filled"; InitCommand=cmd(x,x_pos;); }; Scores[#Scores+1] = LoadActor("empty") .. { Name = idx .. "Empty"; InitCommand=cmd(x,x_pos;); }; end local sNoScoreName = THEME:GetMetric("Common", "NoScoreName"); Scores.SetCommand=function(self, params) local pProfile = PROFILEMAN:GetMachineProfile(); for name, child in pairs(c) do child:visible(false); end for idx=1,NumColumns do c[idx .. "Empty"]:visible(true); end local Current = params.Song or params.Course; if Current then for idx, CurrentItem in pairs(params.Entries) do if CurrentItem then local hsl = pProfile:GetHighScoreList(Current, CurrentItem); local hs = hsl and hsl:GetHighScores(); --[[Warn( tostring(CurrentItem:GetStepsType()) .. ", " .. tostring(CurrentItem:GetDifficulty()) .. ": " .. tostring(hsl) .. ", " .. tostring(#hs) );]] local name = c[idx .. "Name"]; local score = c[idx .. "Score"]; local filled = c[idx .. "Filled"]; local empty = c[idx .. "Empty"]; --assert( c[sNameType], sNameType ); --assert( c[sScoreType], sScoreType ); name:visible( true ); score:visible( true ); filled:visible( true ); empty:visible( false ); if hs and #hs > 0 then name:settext( hs[1]:GetName() ); score:settext( FormatPercentScore( hs[1]:GetPercentDP() ) ); else name:settext( sNoScoreName ); score:settext( FormatPercentScore( 0 ) ); end end end; end end; return t;
mit
Kyklas/luci-proto-hso
modules/admin-full/luasrc/model/cbi/admin_network/wifi_add.lua
35
5096
--[[ LuCI - Lua Configuration Interface Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local nw = require "luci.model.network" local fw = require "luci.model.firewall" local uci = require "luci.model.uci".cursor() local http = require "luci.http" local iw = luci.sys.wifi.getiwinfo(http.formvalue("device")) local has_firewall = fs.access("/etc/config/firewall") if not iw then luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless")) return end m = SimpleForm("network", translate("Join Network: Settings")) m.cancel = translate("Back to scan results") m.reset = false function m.on_cancel() local dev = http.formvalue("device") http.redirect(luci.dispatcher.build_url( dev and "admin/network/wireless_join?device=" .. dev or "admin/network/wireless" )) end nw.init(uci) fw.init(uci) m.hidden = { device = http.formvalue("device"), join = http.formvalue("join"), channel = http.formvalue("channel"), mode = http.formvalue("mode"), bssid = http.formvalue("bssid"), wep = http.formvalue("wep"), wpa_suites = http.formvalue("wpa_suites"), wpa_version = http.formvalue("wpa_version") } if iw and iw.mbssid_support then replace = m:field(Flag, "replace", translate("Replace wireless configuration"), translate("An additional network will be created if you leave this unchecked.")) function replace.cfgvalue() return "1" end else replace = m:field(DummyValue, "replace", translate("Replace wireless configuration")) replace.default = translate("The hardware is not multi-SSID capable and the existing " .. "configuration will be replaced if you proceed.") function replace.formvalue() return "1" end end if http.formvalue("wep") == "1" then key = m:field(Value, "key", translate("WEP passphrase"), translate("Specify the secret encryption key here.")) key.password = true key.datatype = "wepkey" elseif (tonumber(m.hidden.wpa_version) or 0) > 0 and (m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2") then key = m:field(Value, "key", translate("WPA passphrase"), translate("Specify the secret encryption key here.")) key.password = true key.datatype = "wpakey" --m.hidden.wpa_suite = (tonumber(http.formvalue("wpa_version")) or 0) >= 2 and "psk2" or "psk" end newnet = m:field(Value, "_netname_new", translate("Name of the new network"), translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " .. "<code>0-9</code> and <code>_</code>" )) newnet.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wwan" newnet.datatype = "uciname" if has_firewall then fwzone = m:field(Value, "_fwzone", translate("Create / Assign firewall-zone"), translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it.")) fwzone.template = "cbi/firewall_zonelist" fwzone.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wan" end function newnet.parse(self, section) local net, zone if has_firewall then local zval = fwzone:formvalue(section) zone = fw:get_zone(zval) if not zone and zval == '-' then zval = m:formvalue(fwzone:cbid(section) .. ".newzone") if zval and #zval > 0 then zone = fw:add_zone(zval) end end end local wdev = nw:get_wifidev(m.hidden.device) wdev:set("disabled", false) wdev:set("channel", m.hidden.channel) if replace:formvalue(section) then local n for _, n in ipairs(wdev:get_wifinets()) do wdev:del_wifinet(n) end end local wconf = { device = m.hidden.device, ssid = m.hidden.join, mode = (m.hidden.mode == "Ad-Hoc" and "adhoc" or "sta") } if m.hidden.wep == "1" then wconf.encryption = "wep-open" wconf.key = "1" wconf.key1 = key and key:formvalue(section) or "" elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then wconf.encryption = (tonumber(m.hidden.wpa_version) or 0) >= 2 and "psk2" or "psk" wconf.key = key and key:formvalue(section) or "" else wconf.encryption = "none" end if wconf.mode == "adhoc" or wconf.mode == "sta" then wconf.bssid = m.hidden.bssid end local value = self:formvalue(section) net = nw:add_network(value, { proto = "dhcp" }) if not net then self.error = { [section] = "missing" } else wconf.network = net:name() local wnet = wdev:add_wifinet(wconf) if wnet then if zone then fw:del_network(net:name()) zone:add_network(net:name()) end uci:save("wireless") uci:save("network") uci:save("firewall") luci.http.redirect(wnet:adminlink()) end end end if has_firewall then function fwzone.cfgvalue(self, section) self.iface = section local z = fw:get_zone_by_network(section) return z and z:name() end end return m
apache-2.0
Scavenge/darkstar
scripts/globals/items/yellow_globe.lua
12
1327
----------------------------------------- -- ID: 4403 -- Item: yellow_globe -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4403); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
taxler/radish
lua/parse/char/utf8/set/Diacritic.lua
1
2402
local make_set = require 'parse.char.utf8.make.set' return make_set { S = '^`' .. '\u{a8}\u{af}\u{b4}\u{b7}\u{b8}' .. '\u{374}\u{375}\u{37a}\u{384}\u{385}\u{559}\u{5bf}\u{5c1}\u{5c2}\u{5c4}' .. '\u{657}\u{658}\u{6df}\u{6e0}\u{6e5}\u{6e6}\u{7f4}\u{7f5}\u{818}\u{819}' .. '\u{93c}\u{94d}\u{971}\u{9bc}\u{9cd}\u{a3c}\u{a4d}\u{abc}\u{acd}\u{b3c}' .. '\u{b4d}\u{bcd}\u{c4d}\u{cbc}\u{ccd}\u{d4d}\u{dca}\u{e4e}\u{f18}\u{f19}' .. '\u{f35}\u{f37}\u{f39}\u{f3e}\u{f3f}\u{f86}\u{f87}\u{fc6}' .. '\u{1037}\u{1039}\u{103a}\u{108d}\u{108f}\u{109a}\u{109b}\u{17dd}\u{1a7f}' .. '\u{1b34}\u{1b44}\u{1baa}\u{1bab}\u{1c36}\u{1c37}\u{1cd3}\u{1ce1}\u{1ced}' .. '\u{1cf4}\u{1cf8}\u{1cf9}\u{1df5}\u{1fbd}\u{1ffd}\u{1ffe}\u{2e2f}\u{302e}' .. '\u{302f}\u{30fc}\u{a66f}\u{a67c}\u{a67d}\u{a67f}\u{a69c}\u{a69d}\u{a6f0}' .. '\u{a6f1}\u{a720}\u{a721}\u{a788}\u{a7f8}\u{a7f9}\u{a8c4}\u{a8e0}\u{a8f1}' .. '\u{a92e}\u{a953}\u{a9b3}\u{a9c0}\u{a9e5}\u{aaf6}\u{ab5b}\u{abec}\u{abed}' -- cool cool cool .. '\u{fb1e}\u{ff3e}\u{ff40}\u{ff70}\u{ff9e}\u{ff9f}\u{ffe3}' .. '\u{102e0}\u{10ae5}\u{10ae6}\u{110b9}\u{110ba}\u{11133}\u{11134}\u{11173}' .. '\u{111c0}\u{11235}\u{11236}\u{112e9}\u{112ea}\u{1133c}\u{1134d}\u{114c2}' .. '\u{114c3}\u{115bf}\u{115c0}\u{1163f}\u{116b6}\u{116b7}\u{1172b}'; R = { '\u{2b0}\u{34e}', '\u{350}\u{357}', '\u{35d}\u{362}', '\u{483}\u{487}'; '\u{591}\u{5a1}', '\u{5a3}\u{5bd}', '\u{64b}\u{652}', '\u{6ea}\u{6ec}'; '\u{730}\u{74a}', '\u{7a6}\u{7b0}', '\u{7eb}\u{7f3}', '\u{8e3}\u{8fe}'; '\u{951}\u{954}', '\u{e47}\u{e4c}', '\u{ec8}\u{ecc}', '\u{f82}\u{f84}'; '\u{1087}\u{108c}', '\u{17c9}\u{17d3}', '\u{1939}\u{193b}', '\u{1a75}\u{1a7c}'; '\u{1ab0}\u{1abd}', '\u{1b6b}\u{1b73}', '\u{1c78}\u{1c7d}', '\u{1cd0}\u{1cd2}'; '\u{1cd4}\u{1ce0}', '\u{1ce2}\u{1ce8}', '\u{1d2c}\u{1d6a}', '\u{1dc4}\u{1dcf}'; '\u{1dfd}\u{1dff}', '\u{1fbf}\u{1fc1}', '\u{1fcd}\u{1fcf}', '\u{1fdd}\u{1fdf}'; '\u{1fed}\u{1fef}', '\u{2cef}\u{2cf1}', '\u{302a}\u{302d}', '\u{3099}\u{309c}'; '\u{a717}\u{a71f}', '\u{a92b}\u{a92d}', '\u{aa7b}\u{aa7d}', '\u{aabf}\u{aac2}'; '\u{ab5c}\u{ab5f}', '\u{fe20}\u{fe2f}'; '\u{111ca}\u{111cc}', '\u{11366}\u{1136c}', '\u{11370}\u{11374}', '\u{16af0}\u{16af4}'; '\u{16f8f}\u{16f92}', '\u{16f93}\u{16f9f}', '\u{1d167}\u{1d169}', '\u{1d16d}\u{1d172}'; '\u{1d17b}\u{1d182}', '\u{1d185}\u{1d18b}', '\u{1d1aa}\u{1d1ad}', '\u{1e8d0}\u{1e8d6}'; }; }
mit
Scavenge/darkstar
scripts/zones/Port_San_dOria/npcs/Auvare.lua
17
1656
----------------------------------- -- Area: Port San d'Oria -- NPC: Auvare -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeAuvare") == 0) then player:messageSpecial(AUVARE_DIALOG); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeAuvare",1); player:messageSpecial(FLYER_ACCEPTED); player:messageSpecial(FLYERS_HANDED,17 - player:getVar("FFR")); player:tradeComplete(); elseif (player:getVar("tradeAuvare") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x256); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Metalworks/npcs/Udine_AMAN.lua
33
1311
----------------------------------- -- Area: Metalworks -- NPC: Udine A.M.A.N -- Type: Mentor Recruiter ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local var = 0; if (player:getMentor() == 0) then if (player:getMainLvl() >= 30 and player:getPlaytime() >= 648000) then var = 1; end elseif (player:getMentor() >= 1) then var = 2; end player:startEvent(0x033A, var); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0X033A and option == 0) then player:setMentor(1); end end;
gpl-3.0
mohammad2016mr/seed
bot/seedbot.lua
180
10314
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "admin" }, sudo_users = {110626080,103649648,143723991,111020322,0,tonumber(our_id)},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Our team! Alphonse (@Iwals) I M /-\ N (@Imandaneshi) Siyanew (@Siyanew) Rondoozle (@Potus) Seyedan (@Seyedan25) Special thanks to: Juan Potato Siyanew Topkecleon Vamptacus Our channels: English: @TeleSeedCH Persian: @IranSeed ]], help_text_realm = [[ Realm Commands: !creategroup [name] Create a group !createrealm [name] Create a realm !setname [name] Set realm name !setabout [group_id] [text] Set a group's about text !setrules [grupo_id] [text] Set a group's rules !lock [grupo_id] [setting] Lock a group's setting !unlock [grupo_id] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [grupo_id] Kick all memebers and delete group !kill realm [realm_id] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Get a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups » Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id Return group id or user id !help Get commands list !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules [text] Set [text] as rules !set about [text] Set [text] as about !settings Returns group settings !newlink Create/revoke your group link !link Returns group link !owner Returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] [text] Save [text] as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] Returns user id !log Will return group logs !banlist Will return group ban list » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
agpl-3.0
omidtarh/wbot
plugins/pokedex.lua
626
1668
do local images_enabled = true; local function get_sprite(path) local url = "http://pokeapi.co/"..path print(url) local b,c = http.request(url) local data = json:decode(b) local image = data.image return image end local function callback(extra) send_msg(extra.receiver, extra.text, ok_cb, false) end local function send_pokemon(query, receiver) local url = "http://pokeapi.co/api/v1/pokemon/" .. query .. "/" local b,c = http.request(url) local pokemon = json:decode(b) if pokemon == nil then return 'No pokémon found.' end -- api returns height and weight x10 local height = tonumber(pokemon.height)/10 local weight = tonumber(pokemon.weight)/10 local text = 'Pokédex ID: ' .. pokemon.pkdx_id ..'\nName: ' .. pokemon.name ..'\nWeight: ' .. weight.." kg" ..'\nHeight: ' .. height.." m" ..'\nSpeed: ' .. pokemon.speed local image = nil if images_enabled and pokemon.sprites and pokemon.sprites[1] then local sprite = pokemon.sprites[1].resource_uri image = get_sprite(sprite) end if image then image = "http://pokeapi.co"..image local extra = { receiver = receiver, text = text } send_photo_from_url(receiver, image, callback, extra) else return text end end local function run(msg, matches) local receiver = get_receiver(msg) local query = URL.escape(matches[1]) return send_pokemon(query, receiver) end return { description = "Pokedex searcher for Telegram", usage = "!pokedex [Name/ID]: Search the pokédex for Name/ID and get info of the pokémon!", patterns = { "^!pokedex (.*)$", "^!pokemon (.+)$" }, run = run } end
gpl-2.0
smanolache/kong
spec/integration/02-cli/cmds/status_spec.lua
3
1055
local spec_helper = require "spec.spec_helpers" describe("CLI", function() setup(function() pcall(spec_helper.stop_kong) end) teardown(function() pcall(spec_helper.stop_kong) end) it("the status check should fail when Kong is not running", function() assert.error_matches(function() spec_helper.status_kong() end, "Kong is not running", nil, true) end) it("the status check should not fail when Kong is running", function() local _, code = spec_helper.start_kong() assert.are.same(0, code) local ok = pcall(spec_helper.status_kong) assert.truthy(ok) local ok = pcall(spec_helper.stop_kong) assert.truthy(ok) end) it("the status check should fail when some services are not running", function() local _, code = spec_helper.start_kong() assert.are.same(0, code) os.execute("pkill serf") assert.error_matches(function() spec_helper.status_kong() end, "Some services required by Kong are not running. Please execute \"kong restart\"!", nil, true) end) end)
apache-2.0
tarikgwa/nfd
lua/libs/lfs_cache.lua
5
3388
-- -- Easily power a caching system based on Filesystem -- It's recommended to use ramdisk to get better performances -- @ mkdir -p /tmp/ram -- @ sudo mount -t tmpfs -o size=512M tmpfs /tmp/ram/ -- Set the CACHE_DIRECTORY setting to this directory -- -- -- Copyright (C) 2013-2014 Arezqui Belaid <areski@gmail.com> -- -- Permission is hereby granted, free of charge, to any person -- obtaining a copy of this software and associated documentation files -- (the "Software"), to deal in the Software without restriction, -- including without limitation the rights to use, copy, modify, merge, -- publish, distribute, sublicense, and/or sell copies of the Software, -- and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -- BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. local lfs = require "lfs" local md5 = require "md5" local LFS_Caching = { -- default field values debugger = nil, CACHE_DIRECTORY = '/tmp', } function LFS_Caching:new (o) o = o or {} -- create object if user does not provide one setmetatable(o, self) self.__index = self return o end -- -- Check file exists and readable function LFS_Caching:file_exists(path) local attr = lfs.attributes(path) if (attr ~= nil) then return true else return false end end -- -- return a md5 file for the caching function LFS_Caching:key_filepath(key) return self.CACHE_DIRECTORY..'/'..md5.sumhexa(key) end -- get all lines from a file, returns an empty -- list/table if the file does not exist function LFS_Caching:read_from_file(file) if not self:file_exists(file) then return nil end local f = io.open(file, "rb") local content = f:read("*all") f:close() return content end -- -- Write content to file function LFS_Caching:write_to_file(path, content) local file = io.open(path, "w") file:write(content) file:close() return true end -- Creates a cache for the key with content -- key: value of the cache -- content: object # whatever is compatible function LFS_Caching:set(key, content) local path = self:key_filepath(key) local success = self:write_to_file(path, content) if not success then --print("Couldn't archive cache '%s' to '%s'", key, path) end end -- Returns contents of cache keys -- key: value of the cache -- ttl: number [optional] max age of file in seconds function LFS_Caching:get(key, ttl) local path = self:key_filepath(key) if not self:file_exists(path) then return nil end if ttl then local cache_age = os.time() - lfs.attributes(path).modification if cache_age > ttl then return nil end end result = self:read_from_file(path) return result end return LFS_Caching
mpl-2.0
Scavenge/darkstar
scripts/zones/Nashmau/npcs/Leleroon.lua
6
3492
----------------------------------- -- Area: Nashmau -- NPC: Leleroon -- Corsair AF2 and AF3 quests -- @pos -14.687 0.000 25.114 53 ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_ACCEPTED and player:getVar("NavigatingtheUnfriendlySeas") <= 2) then if (trade:hasItemQty(2341,1) and trade:getItemCount() == 1) then -- Trade Hydrogauage player:startEvent(0x11B); player:setVar("NavigatingtheUnfriendlySeas",2); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(AHT_URHGAN,AGAINST_ALL_ODDS) >= QUEST_ACCEPTED) then local letterGreen = player:getVar("LeleroonsLetterGreen"); local letterBlue = player:getVar("LeleroonsLetterBlue"); local letterRed = player:getVar("LeleroonsLetterRed"); if (letterGreen >= 1 and letterGreen < 5) then player:startEvent(285); -- player is on green letter route elseif (letterBlue >= 1 and letterBlue < 5) then player:startEvent(286); -- player is on blue letter route elseif (letterRed >= 1 and letterRed < 5) then player:startEvent(287); -- player is on red letter route elseif (letterGreen < 5 or letterBlue < 5 or letterRed < 5) then local excludeFromMenu = 0; if (letterGreen == 5) then excludeFromMenu = excludeFromMenu + 2; end; -- finished green if (letterBlue == 5) then excludeFromMenu = excludeFromMenu + 4; end; -- finished blue if (letterRed == 5) then excludeFromMenu = excludeFromMenu + 8; end; -- finished red player:startEvent(282,0,0,0,0,0,0,0,excludeFromMenu); -- choose new route else player:startEvent(264); -- default dialog end; else player:startEvent(264); -- default dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 282) then if (option == 1) then player:addKeyItem(LELEROONS_LETTER_GREEN); player:messageSpecial(KEYITEM_OBTAINED,LELEROONS_LETTER_GREEN) player:setVar("LeleroonsLetterGreen",1); elseif (option == 2) then player:addKeyItem(LELEROONS_LETTER_BLUE); player:messageSpecial(KEYITEM_OBTAINED,LELEROONS_LETTER_BLUE) player:setVar("LeleroonsLetterBlue",1); elseif (option == 3) then player:addKeyItem(LELEROONS_LETTER_RED); player:messageSpecial(KEYITEM_OBTAINED,LELEROONS_LETTER_RED) player:setVar("LeleroonsLetterRed",1); end; end; end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/crepe_belle_helene.lua
12
1493
----------------------------------------- -- ID: 5778 -- Item: Crepe Belle Helene -- Food Effect: 30 Min, All Races ----------------------------------------- -- Intelligence +2 -- MP Healing +3 -- Magic Accuracy +21% (cap 50) -- Magic Defense +1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5778); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 2); target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_FOOD_MACCP, 21); target:addMod(MOD_FOOD_MACC_CAP, 50); target:addMod(MOD_MDEF, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 2); target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_FOOD_MACCP, 21); target:delMod(MOD_FOOD_MACC_CAP, 50); target:delMod(MOD_MDEF, 1); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Port_San_dOria/npcs/Answald.lua
17
1672
----------------------------------- -- Area: Port San d'Oria -- NPC: Answald -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeAnswald") == 0) then player:messageSpecial(ANSWALD_DIALOG); player:messageSpecial(FLYER_ACCEPTED); player:tradeComplete(); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeAnswald",1); player:messageSpecial(FLYERS_HANDED, 17 - player:getVar("FFR")); elseif (player:getVar("tradeAnswald") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x248); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Selbina/npcs/HomePoint#1.lua
27
1256
----------------------------------- -- Area: Selbina -- NPC: HomePoint#1 -- @pos 36.117 -10.729 34.635 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 43); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/spells/bluemagic/asuran_claws.lua
33
1769
----------------------------------------- -- Spell: Asuran Claws -- Delivers a sixfold attack. Accuracy varies with TP -- Spell cost: 81 MP -- Monster Type: Beasts -- Spell Type: Physical (Blunt) -- Blue Magic Points: 2 -- Stat Bonus: AGI +3 -- Level: 70 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Skillchain Element(s): Fire (Primary) and Lightning (Secondary) - (can open Scission, Detonation, Liquefaction, or Fusion; can close Liquefaction, Impaction, or Fusion) -- Combos: Counter ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ACC; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_IMPACTION; params.numhits = 6; params.multiplier = 1.0; params.tp150 = 1.05; params.tp300 = 1.1; params.azuretp = 1.2; params.duppercap = 21; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Rabao/npcs/Maryoh_Comyujah.lua
14
2106
----------------------------------- -- Area: Rabao -- NPC: Maryoh Comyujah -- Involved in Mission: The Mithra and the Crystal (Zilart 12) -- @pos 0 8 73 247 ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(ZILART) == THE_MITHRA_AND_THE_CRYSTAL) then if (player:getVar("ZilartStatus") == 0) then player:startEvent(0x0051); -- Start elseif (player:hasKeyItem(SCRAP_OF_PAPYRUS)) then player:startEvent(0x0053); -- Finish elseif (player:getVar("ZilartStatus") == 2) then player:startEvent(0x0054); -- Go to hall of the gods else player:startEvent(0x0052); end elseif (player:hasCompletedMission(ZILART,THE_MITHRA_AND_THE_CRYSTAL)) then player:startEvent(0x0055); -- New standard dialog after ZM12 else player:startEvent(0x002b); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0051 and option == 1) then player:setVar("ZilartStatus",1); elseif (csid == 0x0053) then player:setVar("ZilartStatus",2); player:delKeyItem(SCRAP_OF_PAPYRUS); player:addKeyItem(CERULEAN_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,CERULEAN_CRYSTAL); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Abyssea-Konschtat/npcs/qm4.lua
4
1344
----------------------------------- -- Zone: Abyssea-Konschtat -- NPC: qm4 (???) -- Spawns Hexenpilz -- @pos ? ? ? 15 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(2908,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(16838837) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(16838837):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 2908); -- Inform payer what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
smanolache/kong
spec/plugins/key-auth/hooks_spec.lua
1
4967
local json = require "cjson" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" local cache = require "kong.tools.database_cache" local STUB_GET_URL = spec_helper.STUB_GET_URL local API_URL = spec_helper.API_URL describe("Key Authentication Hooks", function() setup(function() spec_helper.prepare_db() end) teardown(function() spec_helper.stop_kong() end) before_each(function() spec_helper.restart_kong() spec_helper.drop_db() spec_helper.insert_fixtures { api = { {request_host = "keyauth.com", upstream_url = "http://mockbin.com"} }, consumer = { {username = "consumer1"} }, plugin = { {name = "key-auth", config = {}, __api = 1} }, keyauth_credential = { {key = "key123", __consumer = 1} } } end) describe("Key Auth Credentials entity invalidation", function() it("should invalidate when Key Auth Credential entity is deleted", function() -- It should work local _, status = http_client.get(STUB_GET_URL, {apikey="key123"}, {host="keyauth.com"}) assert.equals(200, status) -- Check that cache is populated local cache_key = cache.keyauth_credential_key("key123") local _, status = http_client.get(API_URL.."/cache/"..cache_key) assert.equals(200, status) -- Retrieve credential ID local response, status = http_client.get(API_URL.."/consumers/consumer1/key-auth/") assert.equals(200, status) local credential_id = json.decode(response).data[1].id assert.truthy(credential_id) -- Delete Key Auth credential (which triggers invalidation) local _, status = http_client.delete(API_URL.."/consumers/consumer1/key-auth/"..credential_id) assert.equals(204, status) -- Wait for cache to be invalidated local exists = true while(exists) do local _, status = http_client.get(API_URL.."/cache/"..cache_key) if status ~= 200 then exists = false end end -- It should not work local _, status = http_client.get(STUB_GET_URL, {apikey="key123"}, {host="keyauth.com"}) assert.equals(403, status) end) it("should invalidate when Key Auth Credential entity is updated", function() -- It should work local _, status = http_client.get(STUB_GET_URL, {apikey="key123"}, {host="keyauth.com"}) assert.equals(200, status) -- It should not work local _, status = http_client.get(STUB_GET_URL, {apikey="updkey123"}, {host="keyauth.com"}) assert.equals(403, status) -- Check that cache is populated local cache_key = cache.keyauth_credential_key("key123") local _, status = http_client.get(API_URL.."/cache/"..cache_key) assert.equals(200, status) -- Retrieve credential ID local response, status = http_client.get(API_URL.."/consumers/consumer1/key-auth/") assert.equals(200, status) local credential_id = json.decode(response).data[1].id assert.truthy(credential_id) -- Delete Key Auth credential (which triggers invalidation) local _, status = http_client.patch(API_URL.."/consumers/consumer1/key-auth/"..credential_id, {key="updkey123"}) assert.equals(200, status) -- Wait for cache to be invalidated local exists = true while(exists) do local _, status = http_client.get(API_URL.."/cache/"..cache_key) if status ~= 200 then exists = false end end -- It should work local _, status = http_client.get(STUB_GET_URL, {apikey="updkey123"}, {host="keyauth.com"}) assert.equals(200, status) -- It should not work local _, status = http_client.get(STUB_GET_URL, {apikey="key123"}, {host="keyauth.com"}) assert.equals(403, status) end) end) describe("Consumer entity invalidation", function() it("should invalidate when Consumer entity is deleted", function() -- It should work local _, status = http_client.get(STUB_GET_URL, {apikey="key123"}, {host="keyauth.com"}) assert.equals(200, status) -- Check that cache is populated local cache_key = cache.keyauth_credential_key("key123") local _, status = http_client.get(API_URL.."/cache/"..cache_key) assert.equals(200, status) -- Delete Consumer (which triggers invalidation) local _, status = http_client.delete(API_URL.."/consumers/consumer1") assert.equals(204, status) -- Wait for cache to be invalidated local exists = true while(exists) do local _, status = http_client.get(API_URL.."/cache/"..cache_key) if status ~= 200 then exists = false end end -- It should not work local _, status = http_client.get(STUB_GET_URL, {apikey="key123"}, {host="keyauth.com"}) assert.equals(403, status) end) end) end)
apache-2.0
Scavenge/darkstar
scripts/globals/spells/bluemagic/reactor_cool.lua
26
2059
----------------------------------------- -- Spell: Reactor Cool -- Enhances defense and covers you with magical ice spikes. Enemies that hit you take ice damage -- Spell cost: 28 MP -- Monster Type: Luminions -- Spell Type: Magical (Ice) -- Blue Magic Points: 5 -- Stat Bonus: INT+3 MND+3 -- Level: 74 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Duration: 120 seconds (2 minutes) -- -- Combos: Magic Attack Bonus ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffectOne = EFFECT_ICE_SPIKES local typeEffectTwo = EFFECT_DEFENSE_BOOST local powerOne = 5; local powerTwo = 12 local duration = 120; local returnEffect = typeEffectOne; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:addStatusEffect(typeEffectOne,powerOne,0,duration) == false and target:addStatusEffect(typeEffectTwo,powerTwo,0,duration) == false) then -- both statuses fail to apply spell:setMsg(75); elseif (target:addStatusEffect(typeEffectOne,powerOne,0,duration) == false) then -- the first status fails to apply target:addStatusEffect(typeEffectTwo,powerTwo,0,duration) spell:setMsg(230); returnEffect = typeEffectTwo; else target:addStatusEffect(typeEffectOne,powerOne,0,duration) target:addStatusEffect(typeEffectTwo,powerTwo,0,duration) spell:setMsg(230); end; return returnEffect; end;
gpl-3.0
LuaDist2/vida
test/demo.lua
3
3552
local ffi = require('ffi') local vida = require('vida') local os = require('os') local bench = require('bench') local fast = vida.compile( vida.interface [[ int func(int a, int b); ]], vida.code [[ EXPORT int func(int a, int b) { return a + b; } ]]) local vector = vida.compile( vida.interface [[ void add(int *, int *, size_t); void mix(int *, int *, size_t, float); void sort(int *, size_t); ]], vida.code [[ #include <stddef.h> EXPORT void add(int *x, int *y, size_t n) { while (n--) *x++ += *y++; } EXPORT void mix(int *x, int *y, size_t n, float alpha) { while (n--) { *x++ += (int)(alpha * (*y++)); } } void quicksort_h(int *list, int m, int n) { int key, i, j, k, tmp; if (m < n) { k = (m + n) / 2; // pivot tmp = list[m]; list[m] = list[k]; list[k] = tmp; key = list[m]; i = m + 1; j = n; while (i <= j) { while((i <= n) && (list[i] <= key)) i++; while((j >= m) && (list[j] > key)) j--; if (i < j) { tmp = list[i]; list[i] = list[j]; list[j] = tmp; } } tmp = list[m]; list[m] = list[j]; list[j] = tmp; quicksort_h(list, m, j - 1); quicksort_h(list, j + 1, n); } } EXPORT void sort(int *list, size_t n) { quicksort_h(list, 0, n - 1); } ]]) assert(8 == fast.func(3, 5)) local n = 10000 local xvec = ffi.new('int[?]', n) local xx = {} local originalxx = {} for i = 0, n - 1 do xvec[i] = math.random(n) if i == 100 then xvec[i] = 999999 end xx[i] = xvec[i] originalxx[i] = xx[i] end local function ms(v) return string.format('%s ms', v * 1000) end local t = 0.5 for i = 0, n - 1 do xx[i] = originalxx[i] end print('luajit sort', ms(bench.smart(t, function () table.sort(xx) end))) assert(xx[n - 1] == 999999) -- spot check output for i = 0, n - 1 do xvec[i] = originalxx[i] end print('vector sort', ms(bench.smart(t, function () vector.sort(xvec, n) end))) assert(xvec[n - 1] == 999999) -- spot check output local n = 10000 local xvec = ffi.new('int[?]', n) local yvec = ffi.new('int[?]', n) local xx = {} local yy = {} for i = 0, n-1 do xvec[i] = i xx[i] = i yvec[i] = i * i yy[i] = i * i end vector.add(xvec, yvec, n) assert(110 == xvec[10]) vector.mix(xvec, yvec, n, 0.5) assert(160 == xvec[10]) print('luajit add (cdata)', ms(bench.smart(t, function () for j = 0, n - 1 do xvec[j] = xvec[j] + yvec[j] end end))) print('luajit add (hash)', ms(bench.smart(t, function () for j = 0, n - 1 do xx[j] = xx[j] + yy[j] end end))) jit.off() print('luajit add (hash nojit)', ms(bench.smart(t, function () for j = 0, n - 1 do xx[j] = xx[j] + yy[j] end end))) jit.on() jit.off() print('luajit add (nojit)', ms(bench.smart(t, function () for j = 0, n - 1 do xvec[j] = xvec[j] + yvec[j] end end))) jit.on() print('vector.add', ms(bench.smart(t, function () vector.add(xvec, yvec, n) end))) print('luajit mix', ms(bench.smart(t, function () local alpha = 0.001 for j = 0, n - 1 do xvec[j] = xvec[j] + alpha * yvec[j] end end))) print('vector.mix', ms(bench.smart(t, function () local alpha = 0.001 vector.mix(xvec, yvec, n, alpha) end)))
mit
Scavenge/darkstar
scripts/zones/Temenos/mobs/Dark_Elemental.lua
23
1253
----------------------------------- -- Area: Temenos E T -- NPC: Dark_Elemental ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local mobID = mob:getID(); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); switch (mobID): caseof { -- 100 a 106 inclut (Temenos -Northern Tower ) [16928892] = function (x) GetNPCByID(16928768+70):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+70):setStatus(STATUS_NORMAL); end , [16928893] = function (x) GetNPCByID(16928768+123):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+123):setStatus(STATUS_NORMAL); end , } end;
gpl-3.0
DebugClub/slua
build/luajit-2.1.0/src/jit/bcsave.lua
26
18244
---------------------------------------------------------------------------- -- LuaJIT module to save/list bytecode. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module saves or lists the bytecode for an input file. -- It's run by the -b command line option. -- ------------------------------------------------------------------------------ local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local bit = require("bit") -- Symbol name prefix for LuaJIT bytecode. local LJBC_PREFIX = "luaJIT_BC_" ------------------------------------------------------------------------------ local function usage() io.stderr:write[[ Save LuaJIT bytecode: luajit -b[options] input output -l Only list bytecode. -s Strip debug info (default). -g Keep debug info. -n name Set module name (default: auto-detect from input name). -t type Set output file type (default: auto-detect from output name). -a arch Override architecture for object files (default: native). -o os Override OS for object files (default: native). -e chunk Use chunk string as input. -- Stop handling options. - Use stdin as input and/or stdout as output. File types: c h obj o raw (default) ]] os.exit(1) end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function readfile(input) if type(input) == "function" then return input end if input == "-" then input = nil end return check(loadfile(input)) end local function savefile(name, mode) if name == "-" then return io.stdout end return check(io.open(name, mode)) end ------------------------------------------------------------------------------ local map_type = { raw = "raw", c = "c", h = "h", o = "obj", obj = "obj", } local map_arch = { x86 = true, x64 = true, arm = true, arm64 = true, ppc = true, mips = true, mipsel = true, } local map_os = { linux = true, windows = true, osx = true, freebsd = true, netbsd = true, openbsd = true, dragonfly = true, solaris = true, } local function checkarg(str, map, err) str = string.lower(str) local s = check(map[str], "unknown ", err) return s == true and str or s end local function detecttype(str) local ext = string.match(string.lower(str), "%.(%a+)$") return map_type[ext] or "raw" end local function checkmodname(str) check(string.match(str, "^[%w_.%-]+$"), "bad module name") return string.gsub(str, "[%.%-]", "_") end local function detectmodname(str) if type(str) == "string" then local tail = string.match(str, "[^/\\]+$") if tail then str = tail end local head = string.match(str, "^(.*)%.[^.]*$") if head then str = head end str = string.match(str, "^[%w_.%-]+") else str = nil end check(str, "cannot derive module name, use -n name") return string.gsub(str, "[%.%-]", "_") end ------------------------------------------------------------------------------ local function bcsave_tail(fp, output, s) local ok, err = fp:write(s) if ok and output ~= "-" then ok, err = fp:close() end check(ok, "cannot write ", output, ": ", err) end local function bcsave_raw(output, s) local fp = savefile(output, "wb") bcsave_tail(fp, output, s) end local function bcsave_c(ctx, output, s) local fp = savefile(output, "w") if ctx.type == "c" then fp:write(string.format([[ #ifdef _cplusplus extern "C" #endif #ifdef _WIN32 __declspec(dllexport) #endif const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname)) else fp:write(string.format([[ #define %s%s_SIZE %d static const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) end local t, n, m = {}, 0, 0 for i=1,#s do local b = tostring(string.byte(s, i)) m = m + #b + 1 if m > 78 then fp:write(table.concat(t, ",", 1, n), ",\n") n, m = 0, #b + 1 end n = n + 1 t[n] = b end bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n") end local function bcsave_elfobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint32_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF32header; typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint64_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF64header; typedef struct { uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize; } ELF32sectheader; typedef struct { uint32_t name, type; uint64_t flags, addr, ofs, size; uint32_t link, info; uint64_t align, entsize; } ELF64sectheader; typedef struct { uint32_t name, value, size; uint8_t info, other; uint16_t sectidx; } ELF32symbol; typedef struct { uint32_t name; uint8_t info, other; uint16_t sectidx; uint64_t value, size; } ELF64symbol; typedef struct { ELF32header hdr; ELF32sectheader sect[6]; ELF32symbol sym[2]; uint8_t space[4096]; } ELF32obj; typedef struct { ELF64header hdr; ELF64sectheader sect[6]; ELF64symbol sym[2]; uint8_t space[4096]; } ELF64obj; ]] local symname = LJBC_PREFIX..ctx.modname local is64, isbe = false, false if ctx.arch == "x64" then is64 = true elseif ctx.arch == "ppc" or ctx.arch == "mips" then isbe = true end -- Handle different host/target endianess. local function f32(x) return x end local f16, fofs = f32, f32 if ffi.abi("be") ~= isbe then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end if is64 then local two32 = ffi.cast("int64_t", 2^32) function fofs(x) return bit.bswap(x)*two32 end else fofs = f32 end end -- Create ELF object and fill in header. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj") local hdr = o.hdr if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi. local bf = assert(io.open("/bin/ls", "rb")) local bs = bf:read(9) bf:close() ffi.copy(o, bs, 9) check(hdr.emagic[0] == 127, "no support for writing native object files") else hdr.emagic = "\127ELF" hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0 end hdr.eclass = is64 and 2 or 1 hdr.eendian = isbe and 2 or 1 hdr.eversion = 1 hdr.type = f16(1) hdr.machine = f16(({ x86=3, x64=62, arm=40, arm64=183, ppc=20, mips=8, mipsel=8 })[ctx.arch]) if ctx.arch == "mips" or ctx.arch == "mipsel" then hdr.flags = 0x50001006 end hdr.version = f32(1) hdr.shofs = fofs(ffi.offsetof(o, "sect")) hdr.ehsize = f16(ffi.sizeof(hdr)) hdr.shentsize = f16(ffi.sizeof(o.sect[0])) hdr.shnum = f16(6) hdr.shstridx = f16(2) -- Fill in sections and symbols. local sofs, ofs = ffi.offsetof(o, "space"), 1 for i,name in ipairs{ ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack", } do local sect = o.sect[i] sect.align = fofs(1) sect.name = f32(ofs) ffi.copy(o.space+ofs, name) ofs = ofs + #name+1 end o.sect[1].type = f32(2) -- .symtab o.sect[1].link = f32(3) o.sect[1].info = f32(1) o.sect[1].align = fofs(8) o.sect[1].ofs = fofs(ffi.offsetof(o, "sym")) o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0])) o.sect[1].size = fofs(ffi.sizeof(o.sym)) o.sym[1].name = f32(1) o.sym[1].sectidx = f16(4) o.sym[1].size = fofs(#s) o.sym[1].info = 17 o.sect[2].type = f32(3) -- .shstrtab o.sect[2].ofs = fofs(sofs) o.sect[2].size = fofs(ofs) o.sect[3].type = f32(3) -- .strtab o.sect[3].ofs = fofs(sofs + ofs) o.sect[3].size = fofs(#symname+1) ffi.copy(o.space+ofs+1, symname) ofs = ofs + #symname + 2 o.sect[4].type = f32(1) -- .rodata o.sect[4].flags = fofs(2) o.sect[4].ofs = fofs(sofs + ofs) o.sect[4].size = fofs(#s) o.sect[5].type = f32(1) -- .note.GNU-stack o.sect[5].ofs = fofs(sofs + ofs + #s) -- Write ELF object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_peobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint16_t arch, nsects; uint32_t time, symtabofs, nsyms; uint16_t opthdrsz, flags; } PEheader; typedef struct { char name[8]; uint32_t vsize, vaddr, size, ofs, relocofs, lineofs; uint16_t nreloc, nline; uint32_t flags; } PEsection; typedef struct __attribute((packed)) { union { char name[8]; uint32_t nameref[2]; }; uint32_t value; int16_t sect; uint16_t type; uint8_t scl, naux; } PEsym; typedef struct __attribute((packed)) { uint32_t size; uint16_t nreloc, nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel, unused[3]; } PEsymaux; typedef struct { PEheader hdr; PEsection sect[2]; // Must be an even number of symbol structs. PEsym sym0; PEsymaux sym0aux; PEsym sym1; PEsymaux sym1aux; PEsym sym2; PEsym sym3; uint32_t strtabsize; uint8_t space[4096]; } PEobj; ]] local symname = LJBC_PREFIX..ctx.modname local is64 = false if ctx.arch == "x86" then symname = "_"..symname elseif ctx.arch == "x64" then is64 = true end local symexport = " /EXPORT:"..symname..",DATA " -- The file format is always little-endian. Swap if the host is big-endian. local function f32(x) return x end local f16 = f32 if ffi.abi("be") then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end end -- Create PE object and fill in header. local o = ffi.new("PEobj") local hdr = o.hdr hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch]) hdr.nsects = f16(2) hdr.symtabofs = f32(ffi.offsetof(o, "sym0")) hdr.nsyms = f32(6) -- Fill in sections and symbols. o.sect[0].name = ".drectve" o.sect[0].size = f32(#symexport) o.sect[0].flags = f32(0x00100a00) o.sym0.sect = f16(1) o.sym0.scl = 3 o.sym0.name = ".drectve" o.sym0.naux = 1 o.sym0aux.size = f32(#symexport) o.sect[1].name = ".rdata" o.sect[1].size = f32(#s) o.sect[1].flags = f32(0x40300040) o.sym1.sect = f16(2) o.sym1.scl = 3 o.sym1.name = ".rdata" o.sym1.naux = 1 o.sym1aux.size = f32(#s) o.sym2.sect = f16(2) o.sym2.scl = 2 o.sym2.nameref[1] = f32(4) o.sym3.sect = f16(-1) o.sym3.scl = 2 o.sym3.value = f32(1) o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant. ffi.copy(o.space, symname) local ofs = #symname + 1 o.strtabsize = f32(ofs + 4) o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs) ffi.copy(o.space + ofs, symexport) ofs = ofs + #symexport o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs) -- Write PE object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_machobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags; } mach_header; typedef struct { mach_header; uint32_t reserved; } mach_header_64; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint32_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint64_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command_64; typedef struct { char sectname[16], segname[16]; uint32_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2; } mach_section; typedef struct { char sectname[16], segname[16]; uint64_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2, reserved3; } mach_section_64; typedef struct { uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; } mach_symtab_command; typedef struct { int32_t strx; uint8_t type, sect; int16_t desc; uint32_t value; } mach_nlist; typedef struct { uint32_t strx; uint8_t type, sect; uint16_t desc; uint64_t value; } mach_nlist_64; typedef struct { uint32_t magic, nfat_arch; } mach_fat_header; typedef struct { uint32_t cputype, cpusubtype, offset, size, align; } mach_fat_arch; typedef struct { struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[1]; mach_nlist sym_entry; uint8_t space[4096]; } mach_obj; typedef struct { struct { mach_header_64 hdr; mach_segment_command_64 seg; mach_section_64 sec; mach_symtab_command sym; } arch[1]; mach_nlist_64 sym_entry; uint8_t space[4096]; } mach_obj_64; typedef struct { mach_fat_header fat; mach_fat_arch fat_arch[2]; struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[2]; mach_nlist sym_entry; uint8_t space[4096]; } mach_fat_obj; ]] local symname = '_'..LJBC_PREFIX..ctx.modname local isfat, is64, align, mobj = false, false, 4, "mach_obj" if ctx.arch == "x64" then is64, align, mobj = true, 8, "mach_obj_64" elseif ctx.arch == "arm" then isfat, mobj = true, "mach_fat_obj" elseif ctx.arch == "arm64" then is64, align, isfat, mobj = true, 8, true, "mach_fat_obj" else check(ctx.arch == "x86", "unsupported architecture for OSX") end local function aligned(v, a) return bit.band(v+a-1, -a) end local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE. -- Create Mach-O object and fill in header. local o = ffi.new(mobj) local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12}, arm64={0x01000007,0x0100000c} })[ctx.arch] local cpusubtype = ({ x86={3}, x64={3}, arm={3,9}, arm64={3,0} })[ctx.arch] if isfat then o.fat.magic = be32(0xcafebabe) o.fat.nfat_arch = be32(#cpusubtype) end -- Fill in sections and symbols. for i=0,#cpusubtype-1 do local ofs = 0 if isfat then local a = o.fat_arch[i] a.cputype = be32(cputype[i+1]) a.cpusubtype = be32(cpusubtype[i+1]) -- Subsequent slices overlap each other to share data. ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0]) a.offset = be32(ofs) a.size = be32(mach_size-ofs+#s) end local a = o.arch[i] a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface a.hdr.cputype = cputype[i+1] a.hdr.cpusubtype = cpusubtype[i+1] a.hdr.filetype = 1 a.hdr.ncmds = 2 a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym) a.seg.cmd = is64 and 0x19 or 0x1 a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec) a.seg.vmsize = #s a.seg.fileoff = mach_size-ofs a.seg.filesize = #s a.seg.maxprot = 1 a.seg.initprot = 1 a.seg.nsects = 1 ffi.copy(a.sec.sectname, "__data") ffi.copy(a.sec.segname, "__DATA") a.sec.size = #s a.sec.offset = mach_size-ofs a.sym.cmd = 2 a.sym.cmdsize = ffi.sizeof(a.sym) a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs a.sym.nsyms = 1 a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs a.sym.strsize = aligned(#symname+2, align) end o.sym_entry.type = 0xf o.sym_entry.sect = 1 o.sym_entry.strx = 1 ffi.copy(o.space+1, symname) -- Write Macho-O object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, mach_size)) bcsave_tail(fp, output, s) end local function bcsave_obj(ctx, output, s) local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write this file type") if ctx.os == "windows" then return bcsave_peobj(ctx, output, s, ffi) elseif ctx.os == "osx" then return bcsave_machobj(ctx, output, s, ffi) else return bcsave_elfobj(ctx, output, s, ffi) end end ------------------------------------------------------------------------------ local function bclist(input, output) local f = readfile(input) require("jit.bc").dump(f, savefile(output, "w"), true) end local function bcsave(ctx, input, output) local f = readfile(input) local s = string.dump(f, ctx.strip) local t = ctx.type if not t then t = detecttype(output) ctx.type = t end if t == "raw" then bcsave_raw(output, s) else if not ctx.modname then ctx.modname = detectmodname(input) end if t == "obj" then bcsave_obj(ctx, output, s) else bcsave_c(ctx, output, s) end end end local function docmd(...) local arg = {...} local n = 1 local list = false local ctx = { strip = true, arch = jit.arch, os = string.lower(jit.os), type = false, modname = false, } while n <= #arg do local a = arg[n] if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then table.remove(arg, n) if a == "--" then break end for m=2,#a do local opt = string.sub(a, m, m) if opt == "l" then list = true elseif opt == "s" then ctx.strip = true elseif opt == "g" then ctx.strip = false else if arg[n] == nil or m ~= #a then usage() end if opt == "e" then if n ~= 1 then usage() end arg[1] = check(loadstring(arg[1])) elseif opt == "n" then ctx.modname = checkmodname(table.remove(arg, n)) elseif opt == "t" then ctx.type = checkarg(table.remove(arg, n), map_type, "file type") elseif opt == "a" then ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture") elseif opt == "o" then ctx.os = checkarg(table.remove(arg, n), map_os, "OS name") else usage() end end end else n = n + 1 end end if list then if #arg == 0 or #arg > 2 then usage() end bclist(arg[1], arg[2] or "-") else if #arg ~= 2 then usage() end bcsave(ctx, arg[1], arg[2]) end end ------------------------------------------------------------------------------ -- Public module functions. return { start = docmd -- Process -b command line option. }
mit
Scavenge/darkstar
scripts/globals/spells/absorb-acc.lua
9
1334
-------------------------------------- -- Spell: Absorb-ACC -- Steals an enemy's accuracy. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if (caster:hasStatusEffect(EFFECT_ACCURACY_BOOST)) then spell:setMsg(75); -- no effect else local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local resist = applyResistance(caster,spell,target,dINT,37,0); if (resist <= 0.125) then spell:setMsg(85); else spell:setMsg(533); caster:addStatusEffect(EFFECT_ACCURACY_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains ACC target:addStatusEffect(EFFECT_ACCURACY_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASABLE); -- target loses ACC end end return EFFECT_ACCURACY_BOOST; end;
gpl-3.0
cyclonetm/XmakanX
plugins/help.lua
337
5009
do function pairsByKeys(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end -- Returns true if is not empty local function has_usage_data(dict) if (dict.usage == nil or dict.usage == '') then return false end return true end -- Get commands for that plugin local function plugin_help(name,number,requester) local plugin = "" if number then local i = 0 for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else i = i + 1 if i == tonumber(number) then plugin = plugins[name] end end end else plugin = plugins[name] if not plugin then return nil end end local text = "" if (type(plugin.usage) == "table") then for ku,usage in pairs(plugin.usage) do if ku == 'user' then -- usage for user if (type(plugin.usage.user) == "table") then for k,v in pairs(plugin.usage.user) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.user..'\n' end elseif ku == 'moderator' then -- usage for moderator if requester == 'moderator' or requester == 'admin' or requester == 'sudo' then if (type(plugin.usage.moderator) == "table") then for k,v in pairs(plugin.usage.moderator) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.moderator..'\n' end end elseif ku == 'admin' then -- usage for admin if requester == 'admin' or requester == 'sudo' then if (type(plugin.usage.admin) == "table") then for k,v in pairs(plugin.usage.admin) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.admin..'\n' end end elseif ku == 'sudo' then -- usage for sudo if requester == 'sudo' then if (type(plugin.usage.sudo) == "table") then for k,v in pairs(plugin.usage.sudo) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.sudo..'\n' end end else text = text..usage..'\n' end end text = text..'======================\n' elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage..'\n======================\n' end return text end -- !help command local function telegram_help() local i = 0 local text = "Plugins list:\n\n" -- Plugins names for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else i = i + 1 text = text..i..'. '..name..'\n' end end text = text..'\n'..'There are '..i..' plugins help available.' text = text..'\n'..'Write "!help [plugin name]" or "!help [plugin number]" for more info.' text = text..'\n'..'Or "!help all" to show all info.' return text end -- !help all command local function help_all(requester) local ret = "" for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else ret = ret .. plugin_help(name, nil, requester) end end return ret end local function run(msg, matches) if is_sudo(msg) then requester = "sudo" elseif is_admin(msg) then requester = "admin" elseif is_momod(msg) then requester = "moderator" else requester = "user" end if matches[1] == "!help" then return telegram_help() elseif matches[1] == "!help all" then return help_all(requester) else local text = "" if tonumber(matches[1]) then text = plugin_help(nil, matches[1], requester) else text = plugin_help(matches[1], nil, requester) end if not text then text = telegram_help() end return text end end return { description = "Help plugin. Get info from other plugins. ", usage = { "!help: Show list of plugins.", "!help all: Show all commands for every plugin.", "!help [plugin name]: Commands for that plugin.", "!help [number]: Commands for that plugin. Type !help to get the plugin number." }, patterns = { "^!help$", "^!help all", "^!help (.+)" }, run = run } end
gpl-2.0
Scavenge/darkstar
scripts/globals/weaponskills/trueflight.lua
19
1978
----------------------------------- -- Trueflight -- Skill Level: N/A -- Description: Deals light elemental damage. Damage varies with TP. Gastraphetes: Aftermath effect varies with TP. -- Available only after completing the Unlocking a Myth (Ranger) quest. -- Does not work with Flashy Shot. -- Does not work with Stealth Shot. -- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget. -- Aligned with the Breeze Belt, Thunder Belt & Soil Belt. -- Properties -- Element: Light -- Skillchain Properties: Fragmentation/Scission -- Modifiers: AGI:30% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 4.0 4.25 4.75 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.ftp100 = 4; params.ftp200 = 4.25; params.ftp300 = 4.75; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_MRK; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 3.8906; params.ftp200 = 6.3906; params.ftp300 = 9.3906; params.agi_wsc = 1.0; end local damage, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params); if ((player:getEquipID(SLOT_RANGED) == 19001) and (player:getMainJob() == JOBS.RNG)) then if (damage > 0) then local params = initAftermathParams() params.subpower.lv1 = 3 params.subpower.lv2 = 4 params.subpower.lv3 =2 applyAftermathEffect(player, tp, params) end end return tpHits, extraHits, criticalHit, damage; end;
gpl-3.0