content stringlengths 5 1.05M |
|---|
local dsp = require "luci.dispatcher"
local http = require "luci.http"
local m, s, o
local function get_ip_string(ip)
if ip and ip:find(":") then
return "[%s]" % ip
else
return ip or ""
end
end
m = Map("tinyfecvpn", "%s - %s" %{translate("tinyFecVPN"), translate("Servers Manage")})
s = m:section(TypedSection, "servers")
s.anonymous = true
s.addremove = true
s.sortable = true
s.template = "cbi/tblsection"
s.extedit = dsp.build_url("admin/vpn/tinyfecvpn/servers/%s")
function s.create(...)
local sid = TypedSection.create(...)
if sid then
m.uci:save("tinyfecvpn")
http.redirect(s.extedit % sid)
return
end
end
o = s:option(DummyValue, "alias", translate("Alias"))
function o.cfgvalue(self, section)
return Value.cfgvalue(self, section) or translate("None")
end
o = s:option(DummyValue, "_server_address", translate("Server Address"))
function o.cfgvalue(self, section)
local server = m.uci:get("tinyfecvpn", section, "server_addr") or "?"
local server_port = m.uci:get("tinyfecvpn", section, "server_port") or "29900"
return "%s:%s" % { get_ip_string(server), server_port }
end
o = s:option(DummyValue, "fec", translate("Fec"))
function o.cfgvalue(self, section)
return m.uci:get("tinyfecvpn", section, "fec") or "5:10"
end
o = s:option(DummyValue, "sub_net", translate("Sub Net"))
function o.cfgvalue(self, section)
return m.uci:get("tinyfecvpn", section, "sub_net") or "10.22.22.0"
end
o = s:option(DummyValue, "tun_dev", translate("Tun Device"))
function o.cfgvalue(self, section)
return m.uci:get("tinyfecvpn", section, "tun_dev") or "random"
end
return m
|
-- es_extended/client/main.lua:69 makes the player respawn at the same last location. You must edit that file.
Citizen.CreateThread(function()
-- main loop thing
while true do
Citizen.Wait(100)
if IsEntityDead(GetPlayerPed(-1)) then
--DoScreenFadeOut(800)
--Citizen.Wait(2000)
--DoScreenFadeIn(800)
--ShowNotification("Alive again?")
--RemoveItemsAfterRPDeath()
end
end
end)
|
--[[
This additional module is a part of RayCast2.
-> Checks for intersections between each boundary of a gui and the ray formed by
the origin and direction.
* Detailed math - https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
]]--
local Globals = require(script.Parent.GlobalConstants)
local Convergence = {}
function Convergence.getConvergencePoint(x1, x2, y1, y2, x3, x4, y3, y4)
local den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if den == 0 then return end
local t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den
local u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den
return u, t
end
function Convergence.intersects(_self, descendants)
local minimumMagnitude = Globals.MAX
local minimumMagnitude2 = Globals.MAX
local minimumFinalPoint;
local toReturnHit;
for _, wall in ipairs(descendants) do
if not table.find(Globals.Classes, wall.ClassName) or not wall then continue end
local pos = wall.AbsolutePosition + Globals.offset
local size = wall.AbsoluteSize
local rotation = wall.Rotation
local wallCorners = {
topleft = pos+size/2-math.sqrt((size.X/2)^2+(size.Y/2)^2)*Vector2.new(math.cos(math.rad(rotation)+math.atan2(size.Y, size.X)),math.sin(math.rad(rotation)+math.atan2(size.Y, size.X))),
bottomleft = pos+size/2-math.sqrt((size.X/2)^2+(size.Y/2)^2)*Vector2.new(math.cos(math.rad(rotation)-math.atan2(size.Y, size.X)),math.sin(math.rad(rotation)-math.atan2(size.Y, size.X))),
bottomright = pos+size/2+math.sqrt((size.X/2)^2+(size.Y/2)^2)*Vector2.new(math.cos(math.rad(rotation)+math.atan2(size.Y, size.X)),math.sin(math.rad(rotation)+math.atan2(size.Y, size.X))),
topright = pos+size/2+math.sqrt((size.X/2)^2+(size.Y/2)^2)*Vector2.new(math.cos(math.rad(rotation)-math.atan2(size.Y, size.X)),math.sin(math.rad(rotation)-math.atan2(size.Y, size.X))),
}
local edges = {
{
a = wallCorners.topleft,
b = wallCorners.bottomleft
},
{
a = wallCorners.topleft,
b = wallCorners.topright
},
{
a = wallCorners.bottomleft,
b = wallCorners.bottomright
},
{
a = wallCorners.topright,
b = wallCorners.bottomright
}
}
local tempPoint;
local tempObstacle;
for _, edge in ipairs(edges) do
local x1, y1 = edge.a.x, edge.a.y
local x2, y2 = edge.b.x, edge.b.y
local x3, y3 = _self._origin.x, _self._origin.y
local x4, y4 = _self._direction.x, _self._direction.y
local u, t = Convergence.getConvergencePoint(x1, x2, y1, y2, x3, x4, y3, y4)
if t and u and t > 0 and t < 1 and u > 0 then
local point = Vector2.new(x1 + t * (x2 - x1), y1 + t * (y2 - y1))
if (point - _self._origin).magnitude < minimumMagnitude then
minimumMagnitude = (point - _self._origin).magnitude
tempPoint = point
tempObstacle = wall
end
end
end
if tempObstacle and tempPoint then
if (tempPoint - _self._origin).magnitude < minimumMagnitude2 then
minimumMagnitude2 = (tempPoint - _self._origin).magnitude
minimumFinalPoint = tempPoint
toReturnHit = tempObstacle
end
end
end
return toReturnHit, minimumFinalPoint
end
return Convergence
|
--------------------------------------------------------------------------------
-- A thermometer measures the actual temperature but it is not the same as the
-- perceived temperature. To get perceived temperature you must also take the
-- wind into account. If TellStick ZNet has an anemometer this can be used to
-- calculate the perceived temperature.
--
-- The script below calculates this and gives the anemometer a thermometer value.
--
-- Source of the algorithm:
-- http://www.smhi.se/kunskapsbanken/meteorologi/vindens-kyleffekt-1.259
--------------------------------------------------------------------------------
-- EDIT THESE
local windSensor = 287
local tempSensor = 297
-- DO NOT EDIT BELOW THIS LINE
local deviceManager = require "telldus.DeviceManager"
local tempValue = deviceManager:device(tempSensor).sensorValue(1, 0)
local windValue = deviceManager:device(windSensor).sensorValue(64, 0)
function calculate()
if tempValue == nil or windValue == nil then
return
end
local w = math.pow(windValue, 0.16)
local v = 13.12 + 0.6215*tempValue - 13.956*w + 0.48669*tempValue*w
v = math.floor(v * 10 + 0.5) / 10
local windDevice = deviceManager:device(windSensor)
windDevice:setSensorValue(1, v, 0)
end
function onSensorValueUpdated(device, valueType, value, scale)
if device:id() == windSensor and valueType == 64 and scale == 0 then
windValue = value
calculate()
elseif device:id() == tempSensor and valueType == 1 and scale == 0 then
tempValue = value
calculate()
end
end
|
return PlaceObj("ModDef", {
"dependencies", {
PlaceObj("ModDependency", {
"id", "ChoGGi_Library",
"title", "ChoGGi's Library",
"version_major", 10,
"version_minor", 5,
}),
},
"title", "Passenger Rocket Tweaks",
"id", "ChoGGi_PassengerRocketTweaks",
"steam_id", "1641796120",
"pops_any_uuid", "e27f8c05-6999-4737-8615-5c9820b083ff",
"lua_revision", 1007000, -- Picard
"version", 15,
"version_major", 1,
"version_minor", 5,
"image", "Preview.jpg",
"author", "ChoGGi",
"code", {
"Code/Script.lua",
},
"has_options", true,
"description", [[
Adds an "Are you sure?" question box to the back button to stop you from losing your applicant list (just the button, pressing ESC still works as usual).
Shows age of colonist in popup info.
Mod Options:
Hide Background: Shows a black background so you can see the text easier.
]],
})
--~ More Spec Info: Add a specialisation count section to the passenger rocket screen (selected applicants / specialists needed by workplaces / specialists already in colony).
--~ Position Pass List: Enable changing position of passenger list.
--~ PosX/PosY: Margins to use for list.
|
local config = {
logFile = nil,--'tarantool.log',
rateLimiting = {
rps = 10,
maxDelay = 0.1,
algoritm = 'simple', -- simple , window
}
}
local logArchive = {}
local baseHTTP = false
local log = function (entry, text)
logArchive[#logArchive+1]= { entry = entry, text = text}
end
local logTable={}
setmetatable(logTable, {
__index = function (_self, entry)
return function(text)
log( entry, text)
end
end
})
local schema = {
fakeDB = {},
get = function(self, key)
return {key, self.fakeDB[key]}
end,
insert = function(self, data)
self.fakeDB[data[1]] = data[2]
return {data[1], self.fakeDB[data[1]]}
end,
update = function(self, key, value)
self.fakeDB[key] = value[1][3]
return {key, self.fakeDB[key]}
end,
delete = function(self, key)
local value = self.fakeDB[key]
self.fakeDB[key] = nil
return {key, value}
end
}
--- Переопределяем основные функции
local function mockBase(baseHttp)
baseHTTP = baseHttp
baseHttp.log=logTable
baseHTTP:setSchemaConfig(schema, config)
end
--- Просмотреть последнюю запись в логе
-- return table последняя запись в таблице логов
local function getLastLogMessage()
return logArchive[#logArchive]
end
--- Сформировать фейковый http.router.request
-- @key string ключ - для stash
-- @key string ключ - для param
-- @value string | table значение
-- return table http.router.request
local function getRequest(key, postKey, value)
local body = {
data={
stash = {key = key},
param = {key = postKey, value = value}
},
peer = {
host = '999.999.999.999',
port = '7777777'
},
stash = function(self, id)
return self.data.stash[id]
end,
param = function(self, id)
return self.data.param[id]
end,
render = function(self,data)
self.answer = data
return self
end
}
return body
end
return {
mockBase = mockBase,
getLastLogMessage = getLastLogMessage,
getRequest = getRequest,
} |
--[[
Graphene VFS Test
Makes sure the internal VFS functions correctly.
]]
print("Graphene: Starting VFS Test...")
local Graphene = require("graphene")
local G = Graphene:GetGrapheneCore()
local vfs = G.FS:GetProvider("vfs")
vfs:Clear()
vfs:AddFile("ABC", "ABC")
vfs:AddDirectory("Test")
vfs:AddFile("Test.ABC", "Test.ABC")
vfs:AddFile("Test.XYZ", "Test.XYZ")
vfs:AddFile("Hello.World", "Hello.World")
local ABC = vfs:GetFile("ABC")
local Test = vfs:GetDirectory("Test")
local Test_ABC = vfs:GetFile("Test.ABC")
local Test_XYZ = vfs:GetFile("Test.XYZ")
local Hello = vfs:GetDirectory("Hello")
local Hello_World = vfs:GetFile("Hello.World")
assert(ABC, "Could not retrieve explicitly initialized file 'ABC'.")
assert(ABC:Read() == "ABC", "File 'ABC' did not preserve contents.")
assert(Test, "Could not retrieve explicitly initialized directory 'Test'.")
assert(Test_ABC and Test_XYZ, "Could not retrieve one or more explicitly initialized files ('Test.ABC', 'Test.XYZ').")
assert(Test_ABC:Read() == "Test.ABC", "File 'Test.ABC' did not preserve contents.")
assert(Test_XYZ:Read() == "Test.XYZ", "File 'Test.XYZ' did not preserve contents.")
assert(Hello, "Could not retrieve implicitly initialized directory 'Hello'.")
assert(Hello_World, "Could not retrieve explicitly initialized file 'Hello.World'.")
vfs:Clear()
print("Graphene: VFS test passed.") |
------------------------------------------------------------------------------
-- DynASM RISC-V module.
--
-- Copyright (C) 2005-2021 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "riscv64",
description = "DynASM RISC-V 64 module",
version = "1.5.0",
vernum = 10500,
release = "2021-05-02",
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, setmetatable = assert, setmetatable
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch = _s.match, _s.gmatch
local concat, sort = table.concat, table.sort
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local tohex = bit.tohex
-- 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 = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM", "IMMS",
}
-- 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.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- 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
------------------------------------------------------------------------------
-- 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
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(0xff000000 + w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n >= 0xff000000 then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
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 > 2047 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=20,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=20,next_global-1 do
out:write(" ", prefix, 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=20,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 = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
local map_archdef = { sp="x2", ra="x1" } -- Ext. register name -> int. name.
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
if s == "x2" then return "sp"
elseif s == "x1" then return "ra" end
return s
end
------------------------------------------------------------------------------
-- Template strings for RISC-V 64 instructions.
local map_op = {
-- RV32I
beq_3 = "00000063RrB",
bne_3 = "00001063RrB",
blt_3 = "00004063RrB",
bge_3 = "00005063RrB",
bltu_3 = "00006063RrB",
bgeu_3 = "00007063RrB",
jalr_3 = "00000067DRI",
jal_2 = "0000006fDJ",
lui_2 = "00000037DU",
auipc_2 = "00000017DU",
addi_3 = "00000013DRI",
slti_3 = "00002013DRI",
sltiu_3 = "00003013DRI",
xori_3 = "00004013DRI",
ori_3 = "00006013DRI",
andi_3 = "00007013DRI",
add_3 = "00000033DRr",
sub_3 = "40000033DRr",
sll_3 = "00001013DRr",
slt_3 = "00002033DRr",
sltu_3 = "00003033DRr",
xor_3 = "00004033DRr",
srl_3 = "00005033DRr",
sra_3 = "40005033DRr",
or_3 = "00006033DRr",
and_3 = "00007033DRr",
lb_2 = "00000003DL",
lh_2 = "00001003DL",
lw_2 = "00002003DL",
lbu_2 = "00004003DL",
lhu_2 = "00005003DL",
sb_2 = "00000023rS",
sh_2 = "00001023rS",
sw_2 = "00002023rS",
-- RV64I additions to RV32I
addiw_3 = "0000001bDRI",
slliw_3 = "0000101bDRW",
srliw_3 = "0000501bDRW",
sraiw_3 = "4000501bDRW",
addw_3 = "0000003bDRr",
subw_3 = "4000003bDRr",
sllw_3 = "0000103bDRr",
srlw_3 = "0000503bDRr",
sraw_3 = "4000503bDRr",
ld_2 = "00003003DL",
lwu_2 = "00006003DL",
sd_2 = "00003023rS",
-- RV32 versions of these are in opcodes-pseudo
slli_3 = "00001013DRi",
srli_3 = "00005013DRi",
srai_3 = "40005013DRi",
-- RV32M
mul_3 = "02000033DRr",
mulh_3 = "02001033DRr",
mulhsu_3 = "02002033DRr",
mulhu_3 = "02003033DRr",
div_3 = "02004033DRr",
divu_3 = "02005033DRr",
rem_3 = "02006033DRr",
remu_3 = "02007033DRr",
-- RV64M additions to RV32M
mulw_3 = "0200003bDRr",
divw_3 = "0200403bDRr",
divuw_3 = "0200503bDRr",
remw_3 = "0200603bDRr",
remuw_3 = "0200703bDRr",
-- RV32F
["fadd.s_3"] = "00000053FGg",
["fsub.s_3"] = "08000053FGg",
["fmul.s_3"] = "10000053FGg",
["fdiv.s_3"] = "18000053FGg",
["fsgnj.s_3"] = "20000053FGg",
["fsgnjn.s_3"] = "20001053FGg",
["fsgnjx.s_3"] = "20002053FGg",
["fmin.s_3"] = "28000053FG",
["fmax.s_3"] = "28001053FG",
["fsqrt.s_2"] = "58000053FG",
["fle.s_3"] = "a0000053DGg",
["flt.s_3"] = "a0001053DGg",
["feq.s_3"] = "a0002053DGg",
["fcvt.w.s_2"] = "c0000053DG",
["fcvt.wu.s_2"] = "c0100053DG",
["fmv.x.w_2"] = "e0000053DG",
["fclass.s_2"] = "e0001053DG",
["fcvt.s.w_2"] = "d0000053FR",
["fcvt.s.wu_2"] = "d0100053FR",
["fmv.w.x_2"] = "f0000053FR",
["flw_2"] = "00002007FL",
["fsw_2"] = "00002027gS",
["fmadd.s_4"] = "00000043FGgH",
["fmsub.s_4"] = "00000047FGgH",
["fnmsub.s_4"] = "0000004bFGgH",
["fnmadd.s_4"] = "0000004fFGgH",
-- RV64F additions to RV32F
["fcvt.l.s_2"] = "c0200053DG",
["fcvt.lu.s_2"] = "c0300053DG",
["fcvt.s.l_2"] = "d0200053FR",
["fcvt.s.lu_2"] = "d0300053FR",
-- RV32D
["fadd.d_3"] = "02007053FGg",
["fsub.d_3"] = "0a007053FGg",
["fmul.d_3"] = "12007053FGg",
["fdiv.d_3"] = "1a007053FGg",
["fsgnj.d_3"] = "22000053FGg",
["fsgnjn.d_3"] = "22001053FGg",
["fsgnjx.d_3"] = "22002053FGg",
["fmin.d_3"] = "2a000053FGg",
["fmax.d_3"] = "2a001053FGg",
["fcvt.s.d_2"] = "40100053FG",
["fcvt.d.s_2"] = "42000053FG",
["fsqrt.d_2"] = "5a007053FG",
["fle.d_3"] = "a2000053DGg",
["flt.d_3"] = "a2001053DGg",
["feq.d_3"] = "a2002053DGg",
["fcvt.w.d_2"] = "c2007053DG",
["fcvt.wu.d_2"] = "c2107053DG",
["fclass.d_2"] = "e2001053DG",
["fcvt.d.w_2"] = "d2007053FR",
["fcvt.d.wu_2"] = "d2107053FR",
["fld_2"] = "00003007FL",
["fsd_2"] = "00003027gS",
["fmadd.d_4"] = "02007043FGgH",
["fmsub.d_4"] = "02007047FGgH",
["fnmsub.d_4"] = "0200704bFGgH",
["fnmadd.d_4"] = "0200704fFGgH",
-- RV64D additions to RV32D
["fcvt.l.d_2"] = "c2200053DG",
["fcvt.lu.d_2"] = "c2300053DG",
["fmv.x.d_2"] = "e2000053DG",
["fcvt.d.l_2"] = "d2200053FR",
["fcvt.d.lu_2"] = "d2300053FR",
["fmv.d.x_2"] = "f2000053FR",
-- Pseudo Instructions
nop_0 = "00000013",
li_2 = "00000013DI",
mv_2 = "00000013DR",
not_2 = "fff04013DR",
neg_2 = "40000033Dr",
j_1 = "0000006fJ",
jal_1 = "000000efJ",
jr_1 = "00000067R",
jalr_1 = "000000e7R",
ret_0 = "00008067",
bnez_2 = "00001063RB",
beqz_2 = "00000063RB",
blez_2 = "00005063rB",
bgez_2 = "00005063RB",
bltz_2 = "00004063RB",
bgtz_2 = "00004063rB",
}
------------------------------------------------------------------------------
local function parse_gpr(expr)
local tname, ovreg = match(expr, "^([%w_]+):(x[1-3]?[0-9])$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local r = match(expr, "^x([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r, tp end
end
werror("bad register name `"..expr.."'")
end
local function parse_fpr(expr)
local r = match(expr, "^f([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_imm(imm, bits, shift, scale, signed, action)
local n = tonumber(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
elseif match(imm, "^[xf]([1-3]?[0-9])$") or match(imm, "^([%w_]+):([xf][1-3]?[0-9])$") then
werror("expected immediate operand, got register")
else
waction(action or "IMM",
(signed and 32768 or 0)+shl(scale, 10)+shl(bits, 5)+shift, imm)
return 0
end
end
local function parse_imm_stype(imm, action)
local n = tonumber(imm)
if n then
if n >= -2048 and n < 2048 then
local imm1 = band(n, 0x1f) -- imm[4:0]
local imm2 = band(n, 0xfe0) -- imm[11:5]
return shl(imm1, 7) + shl(imm2, 20)
end
elseif match(imm, "^[xf]([1-3]?[0-9])$") or match(imm, "^([%w_]+):([xf][1-3]?[0-9])$") then
werror("expected immediate operand, got register")
else
waction(action or "IMMS", 0, imm)
return 0
end
end
local function parse_disp(disp, store)
local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$")
if imm then
local r = shl(parse_gpr(reg), 15)
local extname = match(imm, "^extern%s+(%S+)$")
if extname then
waction("REL_EXT", map_extern[extname], nil, 1)
return r
elseif store then
return r + parse_imm_stype(imm)
else
return r + parse_imm(imm, 12, 20, 0, true)
end
end
local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local r, tp = parse_gpr(reg)
if tp then
waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr))
return shl(r, 15)
end
end
werror("bad displacement `"..disp.."'")
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
map_op[".template__"] = function(params, template, nparams)
if not params then return sub(template, 9) end
local op = tonumber(sub(template, 1, 8), 16)
local n = 1
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 2 positions (ins/ext).
if secpos+2 > maxsecpos then wflush() end
local pos = wpos()
-- Process each character.
--[[
D: rd
R: rs1
r: rs2
I: I-type imm
L: I-type label, imm(rs1)
S: S-type label, imm(rs1)
B: B-type label, imm
J: J-type label, imm
U: U-type imm
W: shamtw imm
i: shamt imm
F: rd float
G: rs1 float
g: rs2 float
H: rs3 float
]]
for p in gmatch(sub(template, 9), ".") do
if p == "D" then
op = op + shl(parse_gpr(params[n]), 7); n = n + 1
elseif p == "R" then
op = op + shl(parse_gpr(params[n]), 15); n = n + 1
elseif p == "r" then
op = op + shl(parse_gpr(params[n]), 20); n = n + 1
elseif p == "I" then
op = op + parse_imm(params[n], 12, 20, 0, true); n = n + 1
elseif p == "L" then
op = op + parse_disp(params[n]); n = n + 1
elseif p == "S" then
op = op + parse_disp(params[n], true); n = n + 1
elseif p == "B" or p == "J" then
local mode, m, s = parse_label(params[n], false)
if p == "B" then m = m + 0x800 end
waction("REL_"..mode, m, s, 1)
n = n + 1
elseif p == "U" then
op = op + parse_imm(params[n], 20, 12, 0, false); n = n + 1
elseif p == "W" then
op = op + parse_imm(params[n], 5, 20, 0, false); n = n + 1
elseif p == "i" then
op = op + parse_imm(params[n], 6, 20, 0, false); n = n + 1
elseif p == "F" then
op = op + shl(parse_fpr(params[n]), 7); n = n + 1
elseif p == "G" then
op = op + shl(parse_fpr(params[n]), 15); n = n + 1
elseif p == "g" then
op = op + shl(parse_fpr(params[n]), 20); n = n + 1
elseif p == "H" then
op = op + shl(parse_fpr(params[n]), 27); n = n + 1
end
end
if (op < 0) then op = 0xffffffff + op + 1 end
wputpos(pos, op)
end
------------------------------------------------------------------------------
-- 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_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- 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])
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", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- 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
-- 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 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", 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))
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
------------------------------------------------------------------------------
|
local health =
Concord.component(
function(e, current, maximum)
e.current = current
e.maximum = maximum
end
)
function health:reduce(delta)
if self.current > 0 then
self.current = self.current - delta
end
end
function health:increase(delta)
self.current = math.min(self.current + delta, self.maximum)
end
return health
|
//________________________________
//
// NS2 Single-Player Mod
// Made by JimWest, 2012
//
//________________________________
// LogicWaypoint.lua
// Base entity for LogicWaypoint things
Script.Load("lua/ExtraEntitiesMod/LogicMixin.lua")
Script.Load("lua/OrdersMixin.lua")
class 'LogicWaypoint' (Entity)
LogicWaypoint.kMapName = "logic_waypoint"
local networkVars =
{
}
AddMixinNetworkVars(LogicMixin, networkVars)
AddMixinNetworkVars(OrdersMixin, networkVars)
function LogicWaypoint:OnCreate()
InitMixin(self, OrdersMixin, { kMoveOrderCompleteDistance = kAIMoveOrderCompleteDistance })
end
function LogicWaypoint:OnInitialized()
if Server then
InitMixin(self, LogicMixin)
end
end
function LogicWaypoint:GetExtents()
return Vector(1,1,1)
end
function LogicWaypoint:OnOrderComplete(player)
self:TriggerOutputs(player)
end
function LogicWaypoint:OnLogicTrigger(player)
if player then
local orderId = kTechId.Move
local param = self:GetId()
local origin = self:GetOrigin()
local target = nil
if self.targetName and self.targetName ~= "" then
target = self:GetLogicEntityWithName(self.targetName)
if target and self:GetIsTargetCompleted(target, player) then
self:TriggerOutputs(player)
// if it has still no order, then do just nothing
if player:GetCurrentOrder() then
return
end
end
end
if self.type == 1 then
// search near targets as paramater
// if found no targets, just move there
if not target then
local targets = GetEntitiesWithMixinWithinRange("Live", self:GetOrigin(), 2)
if targets and #targets > 0 then
target = targets[1]
end
end
if target then
orderId = kTechId.Attack
param = target:GetId()
origin = target:GetOrigin()
target.wayPointEntity = self:GetId()
end
elseif self.type == 2 then
if not target then
// search near weldable things as paramater
local weldables = GetEntitiesWithinRange("LogicWeldable", self:GetOrigin(), 2)
if weldables and #weldables > 0 then
target = weldables[1]
end
end
if target then
orderId = kTechId.Weld
param = target:GetId()
origin = target:GetOrigin()
target.wayPointEntity = self:GetId()
end
elseif self.type == 3 then
orderId = kTechId.Build
end
player.mapWaypoint = param
player.mapWaypointType = orderId
local orderId = player:GiveOrder(orderId, param, origin, nil, true, true)
end
end
function LogicWaypoint:GetIsTargetCompleted(target, player)
return (self.type == 1 and not target:GetIsAlive()) or (self.type == 2 and target:GetCanBeWelded(player))
end
Shared.LinkClassToMap("LogicWaypoint", LogicWaypoint.kMapName, networkVars) |
-----------------------------------
-- Area: Upper Delkfutt's Tower
-- Mob: Magic Urn
-----------------------------------
require("scripts/globals/regimes")
-----------------------------------
function onMobDeath(mob, player, isKiller)
tpz.regime.checkRegime(player, mob, 788, 3, tpz.regime.type.GROUNDS)
tpz.regime.checkRegime(player, mob, 789, 3, tpz.regime.type.GROUNDS)
end
|
require("particle/particleBase");
--ParticleFlower --粒子类
ParticleFlower = class(ParticleBase);
ParticleFlower.liveTime = 4; --粒子生命时长
ParticleFlower.init = function(self, len, index, node)
local moredata = node:getMoreData();
self.m_fade = (math.random()*100)/1000.0 +0.05;--衰减速度
self.m_node = node;
self.m_active = true; --是否激活状态
self.m_live = moredata.liveTime or ParticleFlower.liveTime;--粒子生命
local h = moredata.h;
local w = moredata.w;
self.m_frame = math.ceil(self.m_live/self.m_fade);
local yi = 0--h/self.m_frame/20;
local xi = 0--w/self.m_frame/20;
--移动速度/方向
local active = node:getMaxActive() > self.m_frame and node:getMaxActive() or self.m_frame
local pos = len/active
if pos>1 then pos = pos-1;end
if pos<0.25 then--left
self.m_xi = -xi;
self.m_yi = 0;
self.m_x = 0;
self.m_y = h*pos*4;
elseif pos<0.5 then--top
self.m_xi = 0;
self.m_yi = -yi;
self.m_x = w*(pos-0.25)*4;
self.m_y = 0;
elseif pos<0.75 then--rights
self.m_xi = xi;
self.m_yi = 0;
self.m_x = w;
self.m_y = h*(pos-0.5)*4;
else
self.m_xi = 0;
self.m_yi = yi;
self.m_x = w*(pos-0.75)*4;
self.m_y = h;
end
self.m_scale = math.random();
if self.m_scale<0.2 then self.m_scale=0.2;end
self.m_tick = 0;
-- node:setParPos(self.m_x, self.m_y, self.m_scale, len);
self.m_rotation = 0;
self.m_rotStep = moredata.rotation;
self.unit_index = math.random(10000)%(#self.unit)
self._instruction = Rectangle(Rect(0,0,self.unit[self.unit_index+1].size.x * System.getLayoutScale(),self.unit[self.unit_index+1].size.y* System.getLayoutScale()), Matrix(), self.unit[self.unit_index+1].uv_rect)
self._instruction.colorf = Colorf(1.0,1.0,1.0,1.0)
self._mat = Matrix()
self.width = self.unit[self.unit_index+1].size.x
self.height = self.unit[self.unit_index+1].size.y
end
local Rad = math.rad
local Cos = math.cos
local Sin = math.sin
ParticleFlower.update = function(self)
--匀速移动+旋转
if self.m_active then --激活
self.m_rotation = self.m_rotation+self.m_rotStep;
-- 返回X,Y轴的位置
self.m_tick = self.m_tick + 1;
if self.m_tick > self.m_frame then self.m_tick = self.m_frame;end
-- 减少粒子的生命值
self.m_live = self.m_live - self.m_fade;
self._instruction.colorf = Colorf(1.0,1.0,1.0,self.m_alpha)
self._instruction.uv_rect = self.unit[self.unit_index+1].uv_rect
local rad = Rad(self.m_rotation or 0); --角度转弧度
local cosA = Cos(rad);
local sinA = Sin(rad);
local w, h = self.width,self.height
w = w / 2 * self.m_scale ;
h = h / 2 * self.m_scale;
-- setForceMatrix的旋转点为父节点位置.如果要绕Image中心点旋转,则需要先平移-w, -h,之后再旋转,再平移w,h
--下面是x,y最终结果
local x = -w*cosA + h*sinA + w + self.m_x;
local y = -w*sinA - h*cosA + h + self.m_y;
self._mat:load(self.m_scale*cosA, self.m_scale*sinA, 0, 0,
-self.m_scale*sinA, self.m_scale*cosA, 0, 0,
0, 0, 1, 0,
x, y, 0, 1)
self._instruction.matrix = self._mat
if self.m_live < 0.0 then
self.m_active = false;
self.m_scale = 0;
self._instruction:release()
return
else
return self._instruction
end
end
end
|
function send_subtitle(name, value)
if not name == "sub-text" then return end
if not value then value = "" end
-- no connection is necessary, just send the subtitle
udp:send(value)
end
socket = require("socket")
udp = assert(socket.udp())
assert(udp:setpeername("127.0.0.1", 17827))
mp.observe_property("sub-text", "string", send_subtitle)
mp.set_property_bool("sub-visibility", true)
-- prevent subtitles from being shown locally
mp.set_property("sub-color", "#00000000")
mp.set_property_number("sub-border-size", 0)
|
-- returns a 'libs' table
-- used by the ffi-in-a-c-module
return function(signatures,pointers)
local ffi = require'ffi'
local string_format = string.format
local libs = {
sodium = {}
}
libs.C = libs.sodium
for k,f in pairs(pointers) do
if signatures[k] then
libs.sodium[k] = ffi.cast(string_format(signatures[k],'(*)'),f)
end
end
return libs
end
|
return {
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 500
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 1000
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 610
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 1220
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 720
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 1440
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 830
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 1660
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 940
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 1880
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 1050
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 2100
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 1160
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 2320
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 1270
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 2540
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 1380
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 2760
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 1500
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 3000
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
},
time = 12,
name = "湖之都的蛮牛",
init_effect = "jinengchufared",
color = "red",
picture = "",
desc = "提升炮击,装填",
stack = 1,
id = 11691,
icon = 11690,
last_effect = "",
blink = {
1,
0,
0,
0.3,
0.3
},
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "cannonPower",
number = 500
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "loadSpeed",
number = 1000
}
},
{
type = "BattleBuffCastSkill",
trigger = {
"onFoeDying"
},
arg_list = {
killer = "self",
target = "TargetSelf",
skill_id = 11691,
time = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onRemove"
},
arg_list = {
buff_id = 11690,
target = "TargetSelf"
}
}
}
}
|
--[[
Gangi: Panel gangowy
@author Jakub 'XJMLN' Starzak <jack@pszmta.pl
@package PSZMTA.psz-gangi
@copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl>
Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie.
]]--
local function getGID()
local c=getElementData(localPlayer,"character")
if (not c) then return nil end
return c.gg_nazwa,c.gg_tag,c.gg_rank_name,c.gg_rank_id,c.gg_id -- gg_nazwa, gg_tag, gg_rank_name, gg_rank_id, gg_id
end
local sw, sh = guiGetScreenSize() --800x600
local lblkres = string.format("____________________________________________________________________________________________________________________________________________")
local lblw2 = string.format("UWAGA! Ta operacja jest nie odwracalna, pieniądze wpłacone do sejfu nie mogą być już z niego wypłacone. Pamiętaj że lider nie może nakazywać Ci wpłacać pieniędzy do sejfu, robisz to z własnej woli.")
local lblw1 = string.format("UWAGA! Ta operacja jest nie odwracalna, pieniądze zostaną pobrane z sejfu gangu. Każde ulepszenie polepsza Waszą pozycję w rankingu gangów. Aby ulepszyć gang, wybierz pozycję z tabelki i wciśnij przycisk - następnie odczekaj chwilę i ulepszenie zostanie wdrożone. Jeżeli nie posiadasz bazy gangu, lepiej będzie nie ulepszać gangu.")
local edytowana_postac=nil
local p_g={}
p_g.wnd = guiCreateWindow(sw*0/800, sh*58/600, sw*800/800, sh*469/600,"",false)
guiSetVisible(p_g.wnd,false)
p_g.tabpanel = guiCreateTabPanel(sw*9/800, sh*23/600, sw*782/800, sh*426/600,false,p_g.wnd)
p_g.tabCzl = guiCreateTab("Członkowie",p_g.tabpanel)
p_g.tabZarzad = guiCreateTab("Zarządzanie gangiem",p_g.tabpanel)
p_g.tabStats = guiCreateTab("Statystyki gangu",p_g.tabpanel)
-- Członkowie
p_g.gridlist = guiCreateGridList(sw*7/800, sh*8/600, sw*765/800, sh*313/600,false,p_g.tabCzl)
p_g.gridcolumn_nick = guiGridListAddColumn(p_g.gridlist,"Nick",0.2)
p_g.gridcolumn_ranga = guiGridListAddColumn(p_g.gridlist,"Ranga",0.2)
p_g.gridcolumn_lastplay = guiGridListAddColumn(p_g.gridlist,"Ostatnio w grze",0.3)
p_g.gridcolumn_money = guiGridListAddColumn(p_g.gridlist,"Kwota wpłacona do sejfu",0.2) -- Łącznie 0.9
p_g.btn_dodaj = guiCreateButton(sw*9/800, sh*331/600, sw*232/800, sh*60/600,"Dodaj gracza do gangu",false,p_g.tabCzl)
p_g.btn_wyrzuc = guiCreateButton(sw*290/800, sh*331/600, sw*232/800, sh*60/600,"Wyrzuć gracza z gangu",false,p_g.tabCzl)
p_g.btn_edytuj = guiCreateButton(sw*569/800, sh*332/600, sw*203/800, sh*60/600,"Edytuj gracza",false,p_g.tabCzl)
guiGridListSetSelectionMode(p_g.gridlist,1)
-- Zarządzanie gangiem
p_g.lblInfoMoney = guiCreateLabel(sw*184/800, sh*1/600, sw*414/800, sh*40/600,"Wpłata pieniędzy na rzecz gangu",false,p_g.tabZarzad)
guiSetFont(p_g.lblInfoMoney,"clear-normal");
guiLabelSetHorizontalAlign(p_g.lblInfoMoney,"center",false)
guiLabelSetVerticalAlign(p_g.lblInfoMoney,"center")
p_g.lblLine1 = guiCreateLabel(sw*0/800, sh*41/600, sw*782/800, sh*20/600,lblkres,false,p_g.tabZarzad)
p_g.editMoney = guiCreateEdit(sw*64/800, sh*86/600, sw*235/800, sh*25/600,"",false,p_g.tabZarzad)
p_g.btnWplac = guiCreateButton(sw*309/800, sh*80/600, sw*132/800, sh*31/600,"Wpłać",false,p_g.tabZarzad)
p_g.lblWplac = guiCreateLabel(sw*10/800, sh*92/600, sw*44/800, sh*13/600,"Kwota:",false,p_g.tabZarzad)
p_g.lblWplac2 = guiCreateLabel(sw*482/800, sh*61/600, sw*290/800, sh*71/600,lblw2,false,p_g.tabZarzad)
guiLabelSetColor(p_g.lblWplac2,255,0,0)
guiLabelSetHorizontalAlign(p_g.lblWplac2,"left",true)
p_g.lblInfoUpgrd = guiCreateLabel(sw*192/800, sh*160/600, sw*414/800, sh*40/600,"Dostępne ulepszenia gangu",false,p_g.tabZarzad)
guiSetFont(p_g.lblInfoUpgrd,"clear-normal");
guiLabelSetHorizontalAlign(p_g.lblInfoUpgrd,"center",false)
guiLabelSetVerticalAlign(p_g.lblInfoUpgrd,"center")
p_g.lblLine2 = guiCreateLabel(sw*0/800, sh*200/600, sw*800/800, sh*18/600,lblkres,false,p_g.tabZarzad)
p_g.grid = guiCreateGridList(sw*10/800, sh*222/600, sw*431/800, sh*170/600,false,p_g.tabZarzad)
p_g.gridcolumn_name = guiGridListAddColumn(p_g.grid,"Nazwa ulepszenia",0.5)
p_g.gridcolumn_price = guiGridListAddColumn(p_g.grid,"Koszt ulepszenia",0.3)
p_g.btn_ulepsz = guiCreateButton(sw*451/800, sh*220/600, sw*321/800, sh*58/600,"Zatwierdź",false,p_g.tabZarzad)
p_g.lblUp = guiCreateLabel(sw*447/800, sh*288/600, sw*325/800, sh*103/600,lblw1,false,p_g.tabZarzad)
guiLabelSetColor(p_g.lblUp,255,0,0)
guiLabelSetHorizontalAlign(p_g.lblUp,"left",true)
-- Statystyki gangu
p_g.lblInfoStats = guiCreateLabel(sw*141/800, sh*10/600, sw*501/800, sh*42/600,"Statystyki gangu",false,p_g.tabStats)
guiSetFont(p_g.lblInfoStats,"clear-normal")
p_g.lblLine3 = guiCreateLabel(sw*4/800, sh*52/600, sw*778/800, sh*15/600,lblkres,false,p_g.tabStats)
p_g.lblCzlonkowie = guiCreateLabel(sw*22/800, sh*77/600, sw*182/800, sh*15/600,"Ilość członków:",false,p_g.tabStats)
p_g.lblMoney= guiCreateLabel(sw*22/800, sh*102/600, sw*198/800, sh*15/600,"Pieniądze zgromadzone w sejfie:",false,p_g.tabStats)
p_g.lblLogo = guiCreateLabel(sw*22/800, sh*127/600, sw*248/800, sh*15/600,"Zarejestrowany na forum (posiada logo):",false,p_g.tabStats)
p_g.lblSkin = guiCreateLabel(sw*22/800, sh*152/600, sw*260/800, sh*15/600,"Może ustawić skin gangowy:",false,p_g.tabStats)
p_g.lblBase = guiCreateLabel(sw*22/800, sh*177/600, sw*168/800, sh*15/600,"Posiada własną bazę:",false,p_g.tabStats)
p_g.lblUpgrades = guiCreateLabel(sw*22/800, sh*202/600, sw*253/800, sh*17/600,"Poziom ulepszenia gangu:",false,p_g.tabStats)
p_g.lblRank = guiCreateLabel(sw*22/800, sh*229/600, sw*261/800, sh*15/600,"Pozycja w rankingu:",false,p_g.tabStats)
p_g.init=function()
local gname,gtag,grank,grankid,gid=getGID()
if (not gid) then return end
triggerServerEvent("onPlayerRequestGangData",localPlayer,gid)
guiSetText(p_g.wnd,gname)
if (tonumber(grankid)>2) then
guiSetEnabled(p_g.btn_dodaj,true)
guiSetEnabled(p_g.btn_edytuj,false)
guiSetEnabled(p_g.btn_wyrzuc,false)
else
guiSetEnabled(p_g.btn_dodaj,false)
guiSetEnalbed(p_g.btn_edytuj,false)
guiSetEnabled(p_g.btn_wyrzuc,false)
end
edytowana_postac=nil
end
--p_g.gridcolumn_nick | p_g.gridcolumn_ranga |p_g.gridcolumn_lastplay | p_g.gridcolumn_money |
p_g.fill=function(dane)
guiGridListClear(p_g.gridlist)
if (not dane) then return end
for i,v in ipairs(dane) do
local row = guiGridListAddRow (p_g.gridlist)
guiGridListSetItemText(p_g.gridlist,row,p_g.gridcolumn_nick, v.nick,false,false)
guiGridListSetItemData(p_g.gridlist,row,p_g.gridcolumn_nick, tonumber(v.player_id))
guiGridListSetItemText(p_g.gridlist,row,p_g.gridcolumn_ranga, v.ranga,false,false)
guiGridListSetItemData(p_g.gridlist,row,p_g.gridcolumn_ranga, tonumber(v.rank_id))
guiGridListSetItemText(p_g.gridlist,row,p_g.gridcolumn_lastplay, v.lastduty or "Nie określono",false,false)
guiGridListSetItemText(p_g.gridlist,row,p_g.gridcolumn_money,v.wplacone_sejf.."$",false,false)
guiGridListSetItemData(p_g.gridlist,row,p_g.gridcolumn_money,tonumber(v.wplacone_sejf))
end
end
p_g.gridclick=function()
local gname,gtag,grank,grankid,gid=getGID()
if (not gid) then return end
if (not guiGetEnabled(p_g.btn_dodaj)) then return end
selectedRow = guiGridListGetSelectedItem(p_g.gridlist)
if (selectedRow<0) then
guiSetEnabled(p_g.btn_edytuj,false)
guiSetEnabled(p_g.btn_wyrzuc,false)
else
local sfrank=guiGridListGetItemData(p_g.gridlist,selectedRow,p_g.gridcolumn_ranga)
if (tonumber(grankid)>sfrank and tonumber(grankid)>=3) then
guiSetEnabled(p_g.btn_wyrzuc,true)
else
guiSetEnabled(p_g.btn_wyrzuc,false)
if (tonumber(grankid)>=3) then
guiSetEnabled(p_g.btn_edytuj,true)
else
guiSetEnabled(p_g.btn_edytuj,false)
end
end
end
end
p_g.zwolnij=function()
local __,__,__,__,gid=getGID()
if (not gid) then return end
selectedRow = guiGridListGetSelectedItem(p_g.gridlist)
local pid = guiGridListGetItemData(p_g.gridlist,selectedRow,p_g.gridcolumn_nick)
triggerServerEvent("onGangWyrzucRequest",localPlayer,gid,pid)
end
-- Dodawanie graczy -----------------------------
p_a={}
p_a.win = guiCreateWindow(sw*185/800, sh*151/600, sw*449/800, sh*306/600, "", false)
guiWindowSetSizable(p_a.win, false)
guiSetVisible(p_a.win,false)
p_a.edit_nick = guiCreateEdit(sw*12/800, sh*105/600, sw*427/800, sh*28/600, "", false, p_a.win)
p_a.lbl_nick = guiCreateLabel(sw*13/800, sh*71/600, sw*308/800, sh*15/600, "Wpisz nick gracza:", false, p_a.win)
p_a.lbl_blad = guiCreateLabel(sw*13/800, sh*150/600, 426/800, sh*55/600, "", false, p_a.win)
p_a.btn_dodaj = guiCreateButton(sw*17/800, sh*224/600, sw*184/800, sh*72/600, "Dodaj gracza", false, p_a.win)
p_a.btn_anuluj = guiCreateButton(sw*286/800, sh*224/600, sw*153/800, sh*72/600, "Anuluj", false, p_a.win)
p_a.pokaz=function()
guiSetInputMode("no_binds_when_editing")
guiSetVisible(p_a.win,true)
guiSetText(p_a.lbl_blad,"")
guiSetText(p_a.edit_nick,"")
guiBringToFront(p_a.win)
end
p_a.schowaj=function()
guiSetVisible(p_a.win,false)
end
p_a.dodaj=function()
local __,__,__,__,gid= getGID()
if (not gid) then return end
local nick = guiGetText(p_a.edit_nick)
triggerServerEvent("onGangInviteRequest",localPlayer,gid,nick)
end
p_a.dodaj_end=function(wynik,komunikat)
if (not wynik) then
guiSetText(p_a.lbl_blad,komunikat)
return
else
p_a.schowaj()
p_g.init()
end
end
--Tutaj kod od okna edycji gracza
p_e = {}
p_e.pokaz=function()
local coid=getGID()
if (not coid) then return end
selectedRow = guiGridListGetSelectedItem(p_g.gridlist)
local pid=guiGridListGetItemData(p_g.gridlist,selectedRow,p_g.gridcolumn_nick)
guiSetInputMode("no_binds_when_editing")
guiSetVisible(p_e.win,true)
guiBringToFront(p_e.win)
guiCombBoxClear(p_e.cmb_ranga)
guiComboBoxClear(p_e.cmb_skin)
guiComboBoxAddItem(p_e.cmb_skin, "brak")
triggerServerEvent("onGangCharacterDetailsRequest",localPlayer,coid,pid)
end
p_e.schowaj=function()
guiSetVisible(p_e.win,false)
end
p_e.edycja_potwierdz=function(dane)
if (not dane or not dane.postac or not dane.postac.id) then
p_e.schowaj()
end
edytowana_postac=dane.postac.id
guiSetText(p_e.lbl_nick, dane.postac.nick)
guiComboBoxClear(p_e.cmb_ranga)
guiComboBoxClear(p_e.cmb_skin)
for i,v in ipairs(dane.rangi) do
local i2=guiComboBoxAddItem(p_e.cmb_ranga, tostring(v.rank_id)..". "..v.name) -- sprawdzic czy działa przy nowej implementacji s-side
if (v.rank_id == dane.postac.rank) then
guiComboBoxSetSelected(p_e.cmb_ranga,i2)
end
end
local skin = guiComboBoxAddItem(p_e.cmb_skin,"brak")
guiComboBoxSetSelected(p_e.cmb_skin,skin)
if (dane.skiny and #dane.skiny>0) then
for i,v in ipairs(dane.skiny) do
local skiny = guiComboBoxAddItem(p_e.cmb_skin, tostring(v.skin))
if (v.skin == dane.postac.skin) then
guiComboBoxSetSelected(p_e.cmb_skin, skiny)
end
end
end
end
p_e.zapisz=function()
if (not edytowana_postac) then return end
local ranga = guiComboBoxGetItemText(p_e.cmb_ranga, guiComboBoxGetSelected(p_e.cmb_ranga))
ranga = tonumber(string.sub(ranga,1,1))
local skin = tonumber(guiComboBoxGetItemText(p_e.cmb_skin, guiComboBoxGetSelected(p_e.cmb_skin)))
triggerServerEvent("onGangEdycjaPostaci",localPlayer, edytowana_postac, ranga, skin)
end
addEvent("doFillGangData", true)
addEventHandler("doFillGangData", resourceRoot, p_g.fill)
addEvent("onGangWyrzucComplete", true)
addEventHandler("onGangWyrzucComplete", resourceRoot, p_g.init)
-- glowne okno
addEventHandler("onClientGUIClick", p_g.btn_dodaj, p_a.pokaz, false)
addEventHandler("onClientGUIClick", p_g.btn_wyrzuc, p_g.zwolnij, false)
addEventHandler("onClientGUIClick", p_g.gridlist, p_g.gridclick, false)
-- dodawanie
addEvent("onGangInviteReply", true)
addEventHandler("onGangInviteReply", resourceRoot, p_a.dodaj_end)
addEventHandler("onClientGUIClick", p_a.btn_dodaj, p_a.dodaj, false)
addEventHandler("onClientGUIClick", p_a.btn_anuluj, p_a.schowaj, false)
bindKey("f5","down",function()
local gid,gname,grank,grankid=getGID()
if (not gid) then
guiSetVisible(p_g.wnd,false)
showCursor(false)
return
end
if isGOWindowOpen(p_g.wnd) then
showCursor(false)
guiSetVisible(p_g.wnd, false)
else
showCursor(true,false)
guiSetVisible(p_g.wnd,true)
p_g.init()
end
end)
|
--[[
© 2018 Thriving Ventures AB do not share, re-distribute or modify
without permission of its author (gustaf@thrivingventures.com).
]]
local plugin = plugin
plugin:IncludeFile("shared.lua", SERVERGUARD.STATE.SHARED)
plugin:IncludeFile("sh_commands.lua", SERVERGUARD.STATE.SHARED)
plugin:IncludeFile("cl_panel.lua", SERVERGUARD.STATE.CLIENT)
function plugin:Send(ply)
local queryObj = serverguard.mysql:Select("serverguard_watchlist")
queryObj:Callback(function(result, status, lastID)
if (IsValid(ply)) then
serverguard.netstream.Start(ply, "WatchlistGet", result or {})
end
end)
queryObj:Execute()
end
function plugin:Add(steam_id, note, callingPlayer)
steam_id = string.SteamID(steam_id)
note = note or ""
if (steam_id) then
local queryObj = serverguard.mysql:Select("serverguard_watchlist")
queryObj:Where("steam_id", steam_id)
queryObj:Limit(1)
queryObj:Callback(function(result, status, lastID)
if (istable(result) and #result > 0) then
local updateObj = serverguard.mysql:Update("serverguard_watchlist")
updateObj:Update("note", note)
updateObj:Where("steam_id", steam_id)
updateObj:Limit(1)
updateObj:Callback(function()
if (IsValid(callingPlayer)) then
serverguard.Notify(SGPF("now_watching", steam_id))
plugin:Send(callingPlayer)
end
end)
updateObj:Execute()
else
local insertObj = serverguard.mysql:Insert("serverguard_watchlist")
insertObj:Insert("steam_id", steam_id)
insertObj:Insert("note", note)
insertObj:Callback(function()
if (IsValid(callingPlayer)) then
serverguard.Notify(callingPlayer, SGPF("now_watching", steam_id))
plugin:Send(callingPlayer)
end
end)
insertObj:Execute()
end
end)
queryObj:Execute()
end
end
function plugin:Edit(steam_id, note, callingPlayer)
steam_id = string.SteamID(steam_id)
note = note or ""
if (steam_id) then
local queryObj = serverguard.mysql:Select("serverguard_watchlist")
queryObj:Where("steam_id", steam_id)
queryObj:Limit(1)
queryObj:Callback(function(result, status, lastID)
if (istable(result) and #result > 0) then
local updateObj = serverguard.mysql:Update("serverguard_watchlist")
updateObj:Update("note", note)
updateObj:Where("steam_id", steam_id)
updateObj:Limit(1)
updateObj:Execute()
end
end)
queryObj:Execute()
end
end
function plugin:Remove(steam_id, callingPlayer)
steam_id = string.SteamID(steam_id)
if (steam_id) then
local deleteObj = serverguard.mysql:Delete("serverguard_watchlist")
deleteObj:Where("steam_id", steam_id)
deleteObj:Callback(function()
if (IsValid(callingPlayer)) then
serverguard.Notify(callingPlayer, SGPF("not_watching", steam_id))
plugin:Send(callingPlayer)
end
end)
deleteObj:Execute()
end
end
plugin:Hook("serverguard.mysql.CreateTables", "serverguard.watchlist.CreateTables", function()
local WATCHLIST_TABLE_QUERY = serverguard.mysql:Create("serverguard_watchlist")
WATCHLIST_TABLE_QUERY:Create("steam_id", "VARCHAR(255) NOT NULL")
WATCHLIST_TABLE_QUERY:Create("note", "VARCHAR(255) NOT NULL")
WATCHLIST_TABLE_QUERY:PrimaryKey("steam_id")
WATCHLIST_TABLE_QUERY:Execute()
end)
plugin:Hook("serverguard.mysql.DropTables", "serverguard.watchlist.DropTables", function()
serverguard.mysql:Drop("serverguard_watchlist"):Execute()
end)
plugin:Hook("PlayerInitialSpawn", "serverguard.watchlist.PlayerInitialSpawn", function(ply)
local queryObj = serverguard.mysql:Select("serverguard_watchlist")
queryObj:Where("steam_id", ply:SteamID())
queryObj:Limit(1)
queryObj:Callback(function(result, status, lastID)
if (istable(result) and #result > 0) then
local admins = {}
for _, v in ipairs(player.GetAll()) do
if (v:IsAdmin()) then
admins[#admins + 1] = v
end
end
if (result[1].note == "") then
serverguard.Notify(admins, SGPF("watchlist", ply:Name(), ply:SteamID()))
else
serverguard.Notify(admins, SGPF("watchlist_note", ply:Name(), ply:SteamID(), result[1].note))
end
end
end)
queryObj:Execute()
end)
serverguard.netstream.Hook("WatchlistGet", function(ply, data)
if (serverguard.player:HasPermission(ply, "Manage Watchlist")) then
plugin:Send(ply)
end
end)
serverguard.netstream.Hook("WatchlistAdd", function(ply, data)
if (serverguard.player:HasPermission(ply, "Manage Watchlist")) then
plugin:Add(data.steam_id, data.note, ply)
end
end)
serverguard.netstream.Hook("WatchlistEdit", function(ply, data)
if (serverguard.player:HasPermission(ply, "Manage Watchlist")) then
plugin:Edit(data.steam_id, data.note, ply)
end
end)
serverguard.netstream.Hook("WatchlistRemove", function(ply, data)
if (serverguard.player:HasPermission(ply, "Manage Watchlist")) then
plugin:Remove(data, ply)
end
end) |
local on_death = {}
minetest.register_on_prejoinplayer(function(name, ip)
local data = factions.create_ip_table()
data.ip = ip
factions.player_ips.set(name, data)
end)
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
minetest.after(5, createHudfactionLand, player)
local faction, facname = factions.get_player_faction(name)
if faction then
if factions.onlineplayers[facname] == nil then
factions.onlineplayers[facname] = {}
end
factions.onlineplayers[facname][name] = true
faction.last_logon = os.time()
factions.factions.set(facname, faction)
minetest.after(5, createHudFactionName, player, facname)
minetest.after(5, createHudPower, player, faction)
if faction.no_parcel ~= -1 then
local now = os.time() - faction.no_parcel
local l = factions_config.maximum_parcelless_faction_time
minetest.chat_send_player(name, "This faction will disband in " .. l - now .. " seconds, because it has no parcels.")
end
if factions.has_permission(facname, name, "diplomacy") then
for _ in pairs(faction.request_inbox) do minetest.chat_send_player(name, "You have diplomatic requests in the inbox.") break end
end
if faction.message_of_the_day and (faction.message_of_the_day ~= "" or faction.message_of_the_day ~= " ") then
minetest.chat_send_player(name, faction.message_of_the_day)
end
end
end)
minetest.register_on_leaveplayer(function(player)
local name = player:get_player_name()
local faction, facname = factions.get_player_faction(name)
local id_name1 = name .. "factionLand"
if hud_ids[id_name1] then
hud_ids[id_name1] = nil
end
if faction then
faction.last_logon = os.time()
factions.factions.set(facname, faction)
factions.onlineplayers[facname][name] = nil
hud_ids[name .. "factionName"] = nil
hud_ids[name .. "powerWatch"] = nil
else
factions.remove_key(factions.player_ips, name, nil, "ip", true)
end
on_death[name] = nil
end)
minetest.register_on_respawnplayer(function(player)
local name = player:get_player_name()
local faction, facname = factions.get_player_faction(name)
if not faction then
return false
else
on_death[name] = nil
if not faction.spawn then
return false
else
player:set_pos(faction.spawn)
return true
end
end
end)
minetest.register_on_dieplayer(function(player)
local pname = player:get_player_name()
if on_death[pname] then
return
end
local faction, name = factions.get_player_faction(pname)
if not faction then
return
end
factions.decrease_power(name, factions_config.power_per_death)
on_death[pname] = true
return
end
)
|
local TYPES, ACCESS = {
{
event = "Ban_Action",
actions = {
[1] = "Banishment",
[2] = "Banishment + Final Warning",
[3] = "Deletion",
[4] = "Notation"
}
},
{
event = "Ban_Action",
actions = {
[5] = "Banishment",
[6] = "Deletion",
[7] = "Notation",
[8] = "Report",
[9] = "Lock"
}
},
{
event = "Ban_Finish"
}
},
{
type = {
[1] = { 1 },
[2] = { 1 },
[3] = { 1, 2 },
[4] = { 1, 2 },
[5] = { 1, 2, 3 }
},
action = {
[1] = { 8 },
[2] = { 8 },
[3] = { 1, 4, 5, 7, 9 },
[4] = { 1, 2, 4, 5, 7, 9 },
[5] = { 1, 2, 3, 4, 5, 6, 7, 9 }
}
}
function onChannelRequest(cid, channel, custom)
unregisterCreatureEvent(cid, "Ban_Type")
if(not custom or type(channel) ~= 'number') then
doPlayerSendCancel(cid, "Invalid action.")
return false
end
local type = TYPES[channel]
if(not type) then
doPlayerSendCancel(cid, "Invalid action.")
return false
end
local access = getPlayerAccess(cid)
if(not isInArray(ACCESS.type[access], channel)) then
doPlayerSendCancel(cid, "You cannot do this action.")
return false
end
registerCreatureEvent(cid, type.event)
if(type.actions) then
access = ACCESS.action[access]
if(not access or table.maxn(access) == 0) then
return false
end
local actions = {}
for _, action in ipairs(access) do
local tmp = type.actions[action]
if(tmp) then
actions[action] = tmp
end
end
doPlayerSendChannels(cid, actions)
else
doShowTextDialog(cid, 2599, "Name:\n\n(Optional) Length:\n\nComment:\n", true, 1024)
doCreatureSetStorage(cid, "banConfig", table.serialize({
type = channel
}))
end
return false
end |
package.path = package.path .. ";spec/?.lua"
local edge_computing = require "resty-edge-computing"
local fake_redis
local redis_smembers_resp = {}
local redis_get_resp = "0"
local ngx_phase = nil
_G.ngx = {
get_phase=function() return ngx_phase end,
null="NULL",
time=function() return 0 end,
worker={
pid=function() return 0 end,
id=function() return 0 end,
},
log=function(_, msg) print(msg) end,
timer={
-- luacheck: no unused args
every=function(interval, func) return "Running in background" end
},
exit=function(code) print(code) end,
say=function(code) print(code) end,
}
before_each(function()
fake_redis = {}
stub(fake_redis, "smembers")
stub(fake_redis, "get")
fake_redis.smembers = function(_)
return redis_smembers_resp, nil
end
fake_redis.get = function(_)
return redis_get_resp, nil
end
redis_smembers_resp = {}
redis_get_resp = "0"
ngx_phase = "rewrite"
-- simulating initial state
edge_computing.ready = false
edge_computing.redis_client = nil
edge_computing.interval = 20
end)
describe("Resty Edge Computing", function()
it("has sensible default", function()
assert.same(edge_computing.ready, false)
assert.same(edge_computing.interval, 20)
end)
describe("#start", function()
it("requires a redis client", function()
local resp, err = edge_computing.start()
assert.is_nil(resp)
assert.is_not_nil(err)
end)
it("doesn't runs on other phase except rewrite", function()
for _, phase in ipairs(edge_computing.phases) do
if phase ~= "rewrite" then
ngx_phase = phase
local resp, err = edge_computing.start()
assert.is_nil(resp)
assert.is_not_nil(err)
end
end
end)
it("can accept optional interval", function()
local resp, err = edge_computing.start(fake_redis, 42)
assert.is_nil(err)
assert.is_not_nil(resp)
assert.is_not.same(edge_computing.interval, 20)
assert.same(edge_computing.interval, 42)
end)
it("runs a single time", function()
stub(ngx.timer, "every")
local resp, err = edge_computing.start(fake_redis)
assert.is_nil(err)
assert.is_not_nil(resp)
assert.stub(ngx.timer.every).was.called(1)
-- luacheck: ignore
ngx.timer.every:revert()
end)
it("updates in the first call", function()
stub(edge_computing, "update")
local resp, err = edge_computing.start(fake_redis)
assert.is_nil(err)
assert.is_not_nil(resp)
assert.stub(edge_computing.update).was.called(1)
-- luacheck: ignore
edge_computing.update:revert()
end)
end)
describe("#update", function()
before_each(function()
-- we pressume readiness
edge_computing.ready = true
-- redis_client
edge_computing.redis_client = fake_redis
-- empty cus
edge_computing.initialize_cus()
end)
describe("Valid CUs", function()
it("parses CUs", function()
local phase = "access"
assert.same(#edge_computing.cus[phase], 0)
redis_smembers_resp = {"authorization"}
redis_get_resp = phase .. "||local a = 1 \n return a"
local resp = edge_computing.update()
assert.same(resp, true)
assert.same(#edge_computing.cus[phase], 1)
local cu = edge_computing.cus[phase][1]
assert.same(cu["id"], "authorization")
assert.same(cu["phase"], phase)
assert.same(type(cu["code"]), "function")
assert.same(cu["sampling"], nil)
end)
it("parses CUs with sampling", function()
local phase = "access"
assert.same(#edge_computing.cus[phase], 0)
redis_smembers_resp = {"authorization"}
redis_get_resp = phase .. "||local a = 1 \n return a||85"
local resp = edge_computing.update()
assert.same(resp, true)
assert.same(#edge_computing.cus[phase], 1)
local cu = edge_computing.cus[phase][1]
assert.same(cu["id"], "authorization")
assert.same(cu["phase"], phase)
assert.same(type(cu["code"]), "function")
assert.same(cu["sampling"], "85")
end)
end)
describe("Invalid CU", function()
local unexpected_values = {
{title="syntax error", value="access|| invalid lua code", phase="access"},
{title="invalid phase", value="invalid_phase|| return 42", phase="access"},
{title="invalid value", value="invalid_value", phase="access"},
{title="empty code", value="access||", phase="access"},
{title="empty phase", value="|| local a = 10 return a", phase="access"},
{title="empty phase and code with separator", value="||", phase="access"},
{title="empty phase and code", value="", phase="access"},
{title="nil phase and code", value=nil, phase="access"},
{title="ngx.null phase and code", value=ngx.null, phase="access"},
}
for _, invalid_cu in ipairs(unexpected_values) do
it("skips " .. invalid_cu.title, function()
redis_smembers_resp = {"authorization"}
redis_get_resp = invalid_cu.value
stub(edge_computing, "log")
local resp = edge_computing.update()
assert.same(resp, true) -- it updated but with 0 cus
assert.same(#edge_computing.cus[invalid_cu.phase], 0)
assert.stub(edge_computing.log).was.called(1)
-- luacheck: ignore
edge_computing.log:revert()
end)
end
end)
end)
describe("#execute", function()
before_each(function()
-- we pressume readiness
edge_computing.ready = true
-- redis_client
edge_computing.redis_client = fake_redis
ngx_phase = "access"
end)
function update_cu(raw_code)
redis_smembers_resp = {"authorization"}
redis_get_resp = raw_code
edge_computing.update()
end
it("runs code", function()
stub(ngx, "exit")
update_cu("access||ngx.exit(403)")
local resp, errors = edge_computing.execute()
assert.same(resp, true)
assert.same(#errors, 0)
assert.stub(ngx.exit).was.called()
-- luacheck: ignore
ngx.exit:revert()
end)
it("handles runtime error", function()
update_cu("access||ngx.do_ia(403)")
local resp, errors = edge_computing.execute()
assert.same(resp, true) -- it's only false if it's not ready
assert.same(#errors, 1)
end)
it("runs code accessing redis_client", function()
stub(ngx, "say")
stub(fake_redis, "incr")
fake_redis.incr = function(_)
return "1", nil
end
update_cu("access|| local r = edge_computing.redis_client:incr('key') \n ngx.say(r)")
local resp, errors = edge_computing.execute()
assert.same(resp, true)
assert.same(#errors, 0)
assert.stub(ngx.say).was.called_with("1")
-- luacheck: ignore
ngx.say:revert()
end)
it("runs code only for the current phase", function()
ngx_phase = "rewrite"
stub(ngx, "exit")
update_cu("access||ngx.exit(403)")
local resp, errors = edge_computing.execute()
assert.same(resp, true)
assert.same(#errors, 0)
assert.stub(ngx.exit).was_not.called()
-- luacheck: ignore
ngx.exit:revert()
end)
it("does the execution based on sampling", function()
stub(ngx, "exit")
local builtin_rnd = math.random
-- luacheck: ignore
math.random = function() return 60 end
update_cu("access||ngx.exit(403)||59") -- 59% of change
local resp, errors = edge_computing.execute()
assert.same(resp, true)
assert.same(#errors, 0)
assert.stub(ngx.exit).was.called()
-- luacheck: ignore
ngx.exit:revert()
math.random = builtin_rnd
end)
it("skips execution based on sampling", function()
stub(ngx, "exit")
local builtin_rnd = math.random
-- luacheck: ignore
math.random = function() return 42 end
update_cu("access||ngx.exit(403)||59") -- 3% of change
local resp, errors = edge_computing.execute()
assert.same(resp, true)
assert.same(#errors, 0)
assert.stub(ngx.exit).was_not.called()
-- luacheck: ignore
ngx.exit:revert()
math.random = builtin_rnd
end)
end)
end)
|
-- (Take) Hit System
--
local Base = require 'src.entities.systems.base'
local Hit = Base:extend()
-- New
--
function Hit:new(host, data)
local systems = {
health = { },
hit = { delay = data.delay or host.__hitDelay }
}
-- can be stunned?
if data.stun then
systems['stun'] = data.stun
end
--
Base.new(self, host, systems)
end
---- ---- ---- ----
-- Event: onContact
--
function Hit:onContact(con, other)
if self:canTakeHit(other) then
--TODO: calculate damage
--TODO: apply status affect?
self.host:decreaseHp(other:dmg())
self.host:dispatch('onHit', other)
end
end
-- Event: onAnimationComplete
--
function Hit:onAnimationComplete(name)
if name == 'hit' then
self.host:dispatch('offHit')
end
end
---- ---- ---- ----
-- Can entity take hit?
--
function Hit:canTakeHit(other)
return other.mixins['damage'] and
not self.host.isTakingHit and
not self.host.isRolling and
self.host.tHitCooldown == 0 and
not self:isFriendlyFire(other)
end
function Hit:isFriendlyFire(other)
local source = other.mixins['source'] and other._src.id or other.id
return source.id == self.host.id
end
return Hit |
local m = {
current = 0,
line = 1,
tokens = nil,
precedence = {
["and"] = {prec=2, assoc='left'},
["or"] = {prec=2, assoc='left'},
LESS = {prec=5, assoc='left'},
LESS_EQUAL = {prec=5, assoc='left'},
GREATER = {prec=5, assoc='left'},
GREATER_EQUAL = {prec=5, assoc='left'},
DOUBLE_EQUALS = {prec=5, assoc='left'},
NOT_EQUAL = {prec=5, assoc='left'},
CONCAT = {prec=10, assoc='left'},
PLUS = {prec=20, assoc='left'},
MINUS = {prec=20, assoc='left'},
STAR = {prec=30, assoc='left'},
SLASH = {prec=30, assoc='left'},
PRECENTAGE = {prec=30, assoc='left'},
UP = {prec=40, assoc='right'}
}
}
---Parses tokens and returns a tree
---@param tokens table "Array table of tokens"
---@return table "Tree"
function m:parse(tokens)
self.current = 1
self.line = 1
self.tokens = tokens
return self:parseChunk()
end
function m:parseChunk()
local statements = {}
local parsed
while self:available() do
parsed = false
if self:match("return") then
self:match("SEMICOLON")
if self:available() then
local node = {type="return", values=self:parseExprList()}
self:match("SEMICOLON")
if self:available() then error("Return statement must be the last statement in the block") end
statements[#statements+1] = node
else
statements[#statements+1] = {type="return", values={nil}}
end
parsed = true
end
if not parsed then
self.line = self:peek().line
statements[#statements+1] = self:parseStatement()
end
self:match("SEMICOLON")
end
return {type="chunk", statements=statements}
end
function m:parseBlock(token_type, ...)
local token_type = token_type or "end"
local statements = {}
local parsed
while not self:match(token_type, ...) do
parsed = false
if self:match("return") then
self:match("SEMICOLON")
if not self:tokenOneOf(self:peek(), token_type, ...) then
local node = {type="return", values=self:parseExprList()}
self:match("SEMICOLON")
if not self:tokenOneOf(self:peek(), token_type, ...) then error("Return statement must be the last statement in the block") end
statements[#statements+1] = node
else
statements[#statements+1] = {type="return", values={nil}}
end
parsed = true
end
if self:match("break") then
self:match("SEMICOLON")
if not self:tokenOneOf(self:peek(), token_type, ...) then
error("Break statement must be the last statement in the block")
else
statements[#statements+1] = {type="break"}
end
parsed = true
end
if not parsed then
self.line = self:peek().line
statements[#statements+1] = self:parseStatement()
end
self:match("SEMICOLON")
end
return {type="block", statements=statements}
end
function m:parseStatement()
if self:match("do") then return {type="do", body=self:parseBlock()} end
if self:match("debugdmpenvstack") then return {type="debugdmpenvstack"} end
if self:match("while") then
local expr = self:parseExpr()
self:consume("do", "Expected 'do' after while")
return {type="while", expr=expr, body=self:parseBlock()}
end
if self:match("repeat") then
local body = self:parseBlock('until')
--self:consume("until", "Expected 'until' after repeat body") --consumed by parseBlock
local expr = self:parseExpr()
return {type="repeat", expr=expr, body=body}
end
if self:match("if") then
local expr = self:parseExpr()
self:consume("then", "Expected 'then' after if")
local main_body = self:parseBlock('end', 'elseif', 'else')
local clauses = {{expr=expr, body=main_body}}
local else_body = nil
while self:tokenOneOf(self:prev(), 'elseif', 'else') do
local ttype = self:prev().type
local subexpr
if ttype == 'elseif' then
subexpr = self:parseExpr()
self:consume("then", "Expected 'then' after 'elseif'")
end
local body = self:parseBlock('end', 'elseif', 'else')
if ttype == 'elseif' then clauses[#clauses+1] = {expr=subexpr, body=body}
elseif ttype == 'else' then else_body = body end
end
return {type="if", expr=expr, clauses=clauses, else_body=else_body}
end
if self:match("for") then
-- standard for loop
if self:peek(1).type == "EQUALS" then
local var_name = self:consume("identifier", "Expected variable name after for").lexeme
self:consume("EQUALS", "Expected '=' after variable name")
local start = self:parseExpr()
self:consume("COMMA", "Expected ',' after for loop start")
local end_loop = self:parseExpr()
local step
if self:match("COMMA") then
step = self:parseExpr()
else
step = {type="literal", value=1}
end
self:consume("do", "Expected 'do' after for loop")
local body = self:parseBlock()
return {type="for", var_name=var_name, start=start, end_loop=end_loop, step=step, body=body}
end
-- foreach loop
local ids = self:parseIdList()
self:consume("in", "Expected 'in' after for loop variable names")
local exprs = self:parseExprList()
self:consume("do", "Expected 'do' after for loop")
local body = self:parseBlock()
return {type="foreach", variables=ids, expressions=exprs, body=body}
end
if self:match("function") then
local func_name = self:parseFunctionName()
local func_value = self:parseFunctionBody()
if func_name.method then
table.insert(func_value.arg_names, 1, "self")
end
func_name.node.value = func_value
return func_name.node
end
if self:match("local") then
if self:match("function") then
local name = self:consume("identifier", "Expected function name").lexeme
local func_value = self:parseFunctionBody()
return {type="declare_local", names={name}, values={func_value}}
end
local idlist = self:parseIdList()
local init_values
if self:match("EQUALS") then
init_values = self:parseExprList()
else
init_values = {}
end
return {type="declare_local", names=idlist, values=init_values}
end
local func_call = self:parseCall()
if func_call.type == "call" or func_call.type == "get_call" then
return func_call
end
local exprs = {func_call}
if func_call.type ~= "get" and func_call.type ~= "variable" then
error("[Line " .. self.line .. "] Expected a statement")
end
self:match("COMMA")
if not self:check("EQUALS") then
repeat
local expr = self:parseCall()
if expr.type ~= "get" and expr.type ~= "variable" then
error("[Line " .. self.line .. "] Expected a statement")
end
exprs[#exprs+1] = expr
until not self:match("COMMA")
end
self:consume("EQUALS", "Expected '=' after variable list")
local init_values = self:parseExprList()
return {type="assign_expr", exprs=exprs, values=init_values}
end
function m:parseIdList()
local names = {}
repeat
names[#names+1] = self:consume("identifier", "Expected variable name after ','").lexeme
until not self:match("COMMA")
return names
end
function m:parseFunctionName()
local names = {}
repeat
names[#names+1] = self:consume("identifier", "Expected variable name after '.'").lexeme
until not self:match("DOT")
local method = false
if self:match("COLON") then
method = true
names[#names+1] = self:consume("identifier", "Expected variable name after ':'").lexeme
end
if #names == 1 then
return {node={type="assign", name=names[1]}, method=method}
end
local tree = {type="get", from={type="variable", name=names[1]}, index={type="literal", value=names[2]}}
if #names > 2 then
for i=3, #names do
tree = {type="get", from=tree, index={type="literal", value=names[i]}}
end
end
return {node={type="set", in_value=tree.from, index=tree.index}, method=method}
end
function m:parseExprList()
local exprs = {}
repeat
exprs[#exprs+1] = self:parseExpr()
until not self:match("COMMA")
return exprs
end
function m:parseExpr()
return self:parseBinOp(0)
end
function m:parseBinOp(min_prec)
local left = self:parseCall()
while true do
if not self:available() then break end
local op_token = self:peek()
if not self.precedence[op_token.type] then break end -- not an operator
local prec_data = self.precedence[op_token.type]
if prec_data.prec < min_prec then break end -- lower precedence, so break
-- consume op token
self.current = self.current + 1
local next_prec = prec_data.assoc == 'left' and prec_data.prec + 1 or prec_data.prec
local right = self:parseBinOp(next_prec)
left = {type="operation", operator=op_token.type, left=left, right=right}
end
return left
end
function m:parseCall()
local left = self:parsePrimaryExpr()
while true do
if self:match("OPEN_PAREN") then
left = {type="call", callee=left, args=self:parseArgs()}
elseif self:match("OPEN_BRACE") then
left = {type="call", callee=left, args={self:parseTableConstructor()}}
elseif self:match("string") then
left = {type="call", callee=left, args={{type='literal', value=self:prev().literal}}}
elseif self:match("COLON") then
local idx = self:consume("identifier", "Expected function name after ':'").lexeme
self:consume("OPEN_PAREN", "Expected '(' after function name")
local args = self:parseArgs()
left = {type="get_call", callee=left, index=idx, args=args}
elseif self:match("DOT") then
local idx = self:consume("identifier", "Expected field name after '.'")
left = {type="get", from=left, index={type="literal", value=idx.lexeme}}
elseif self:match("OPEN_SQUARE") then
local idx = self:parseExpr()
self:consume("CLOSE_SQUARE", "Expected ']' after indexing expression")
left = {type="get", from=left, index=idx}
else
break
end
end
return left
end
function m:parseArgs()
local args = {}
if not self:check("CLOSE_PAREN") then
repeat
args[#args+1] = self:parseExpr()
until not self:match("COMMA")
end
self:consume("CLOSE_PAREN", "Expected ')' after parameters")
return args
end
function m:parsePrimaryExpr()
if self:match("nil") then return {type="literal", value=nil} end
if self:match("string") then return {type="literal", value=self:prev().literal} end
if self:match("number") then return {type="literal", value=self:prev().literal} end
if self:match("true") then return {type="literal", value=true} end
if self:match("false") then return {type="literal", value=false} end
if self:match("function") then return self:parseFunctionBody() end
if self:match("OPEN_BRACE") then return self:parseTableConstructor() end
if self:match("identifier") then return {type="variable", name=self:prev().lexeme} end
if self:match("OPEN_PAREN") then
local expr = self:parseExpr()
self:consume("CLOSE_PAREN", "Expected ')' after grouping expression")
return expr
end
if self:match("not") then return {type="not", value=self:parseBinOp(40)} end
if self:match("MINUS") then return {type="uminus", value=self:parseBinOp(40)} end
if self:match("HASHTAG") then return {type="get_length", value=self:parseBinOp(40)} end
if self:match("VARARGS") then return {type="varargs"} end
print(self:peek().type)
error("Expected expression")
end
function m:parseFunctionBody()
self:consume("OPEN_PAREN", "Expected '(' for function declaration")
local arg_names = {}
local varargs = false
if not self:check("CLOSE_PAREN") then
repeat
if self:match("VARARGS") then
varargs = true
break
else
arg_names[#arg_names+1] = self:consume("identifier", "Expected variable name in function parameter definition").lexeme
end
until not self:match("COMMA")
end
self:consume("CLOSE_PAREN", "Expected ')' after function parameter definition")
local body = self:parseBlock()
body.type = 'chunk'
return {type="function", arg_names=arg_names, varargs=varargs, body=body}
end
function m:parseTableConstructor()
local fields = {}
if not self:check("CLOSE_BRACE") then
while not self:check('CLOSE_BRACE') do
fields[#fields+1] = self:parseTableField()
if not self:check('CLOSE_BRACE') then
self:consumeOneOf("Expected ',' or ';' after table field value", 'COMMA', 'SEMICOLON')
end
end
end
self:consume("CLOSE_BRACE", "Expected '}' after table constructor")
return {type="table", fields=fields}
end
function m:parseTableField()
if self:match("VARARGS") then
return {array_item=true, value={type='varargs'}}
end
if self:match("OPEN_SQUARE") then
local idx = self:parseExpr()
self:consume("CLOSE_SQUARE", "Expected ']' after table field key")
self:consume("EQUALS", "Expected '=' after table field key")
local value = self:parseExpr()
return {key=idx, value=value}
end
if self:peek(1).type == "EQUALS" then
local idx = self:consume("identifier", "Expected field name").lexeme
self:consume("EQUALS", "Expected '=' after table field key")
local value = self:parseExpr()
return {key={type="literal", value=idx}, value=value}
end
local value = self:parseExpr()
return {array_item=true, value=value}
end
function m:match(...)
local types = {...}
for _, token_type in ipairs(types) do
if self:check(token_type) then
self.current = self.current + 1
return true
end
end
return false
end
function m:check(token_type)
return self:peek().type == token_type
end
function m:tokenOneOf(token, ...)
local types = {...}
for _, token_type in ipairs(types) do
if token.type == token_type then
return true
end
end
return false
end
function m:consume(token_type, err)
if self:check(token_type) then return self:advance() end
error("[Line " .. self:peek().line .. "] ".. err ..'\n'..self:peek().type)
end
function m:consumeOneOf(err, ...)
local types = {...}
for _, token_type in ipairs(types) do
if self:check(token_type) then return self:advance() end
end
error("[Line " .. self:peek().line .. "] ".. err ..'\n'..self:peek().type)
end
function m:peek(offset)
local offset = offset or 0
if self.current+offset > #self.tokens then return {type="EOF"} end
return self.tokens[self.current+offset]
end
function m:prev()
return self.tokens[self.current-1]
end
function m:available()
return self:peek().type ~= "EOF"
end
function m:advance()
local token = self.tokens[self.current]
self.current = self.current + 1
return token
end
return m |
workspace "BlackBirdBox"
architecture "x64"
startproject "ClothSimulation"
configurations
{
"Debug",
"Release",
}
flags
{
"MultiProcessorCompile"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
-- Include directories relative to root folder (solution directory)
IncludeDir = {}
IncludeDir["GLFW"] = "external/GLFW/include"
IncludeDir["glew"] = "external/glew/include"
IncludeDir["ImGui"] = "external/imgui"
IncludeDir["glm"] = "external/glm"
IncludeDir["tinyobjloader"] = "external/tinyobjloader"
IncludeDir["stb"] = "external/stb"
IncludeDir["rapidjson"] = "external/rapidjson/include"
IncludeDir["soloud"] = "external/soloud/include"
group "Dependencies"
include "external/GLFW"
include "external/imgui"
include "external/soloud"
group ""
include "BlackBirdBox"
include "BlackBirdCage"
include "BlackBirdNest"
include "ClothSimulation" |
supplyLimit("Corvette",14)
supplyLimit("Frigate",30)
supplyLimit("Capital",13)
supplyLimit("Platform",9)
|
require("Dogecomments/init")
local function comment_todo()
current_vim_mode = api.nvim_get_mode().mode -- .blocking: Do we need to check if blocking is false in addition to 'n' mode?
if current_vim_mode:match('n') then
get_line = api.nvim_get_current_line()
first_non_space_char = string.find(get_line, '%S')
if first_non_space_char == nil then
first_non_space_char = 0 -- If no whitespace before comment_marker.
end
leading_space = string.rep(" ",first_non_space_char-1)
if_comment_marker = get_line.sub(get_line,first_non_space_char,first_non_space_char + length_of_comment_marker-1)
if_comment_marker_with_space = get_line.sub(get_line,first_non_space_char,first_non_space_char + length_of_comment_marker)
todo = "TODO: "
todo_length = string.len(todo)
if if_comment_marker ~= comment_marker then
set_line = api.nvim_set_current_line(leading_space .. comment_marker .. space_after_comment .. todo .. get_line.sub(get_line,first_non_space_char))
if telemetry == true then
log_telemetry("commented_todo")
end
vim.cmd('startinsert!') -- Enter insert mode after comment. (a.k.a Append/A).
elseif if_comment_marker_with_space == comment_marker .. space_after_comment then
set_line = api.nvim_set_current_line(leading_space .. get_line.sub(get_line, first_non_space_char + length_of_comment_marker + space_after_comment_length + todo_length))
elseif if_comment_marker_with_space ~= comment_marker .. space_after_comment then
set_line = api.nvim_set_current_line(leading_space .. get_line.sub(get_line, first_non_space_char + length_of_comment_marker + todo_length))
end
end
end
return {
comment_todo = comment_todo,
}
|
-- angrybino
-- Device
-- September 26, 2021
--[[
Device.OnTouchStarted : RBXScriptSignal (touchedPosition : Vector3, isInputProcessed : boolean)
Device.OnTouchEnded : RBXScriptSignal (touchedPositionEnded : Vector3, isInputProcessed : boolean)
Device.TouchMoved : RBXScriptSignal (touchedPositionEnded : Vector3, isInputProcessed : boolean)
Device.OnTouchTapInWorld : RBXScriptSignal (touchTapInWorldPosition : Vector2, isInputProcessed : boolean)
Device.TouchLongPress : RBXScriptSignal (touchPositions : table, state : UserInputState, isInputProcessed : boolean)
Device.OnTouchPinch : RBXScriptSignal (
touchPositions : table,
scale : number,
velocity : number,
state : UserInputState,
isInputProcessed : boolean
)
Device.OnTouchPan : RBXScriptSignal (
touchPositions : table,
totalTranslation : Vector2,
velocity : Vector2,
state : UserInputState,
isInputProcessed : boolean
)
Device.OnTouchRotate : RBXScriptSignal (
touchPositions : table,
rotation : number,
velocity : Vector2,
state : UserInputState,
isInputProcessed : boolean
)
Device.OnTouchTap : RBXScriptSignal (touchPositions : table,isInputProcessed : boolean)
Device.OnAccelerationChanged : RBXScriptSignal (acceleration : InputObject)
Device.OnGravityChanged : RBXScriptSignal (gravity : InputObject)
Device.OnGravityChanged : RBXScriptSignal (gravity : InputObject)
Device.OnRotationChanged : RBXScriptSignal (rotation : InputObject, cframe : CFrame)
Device.GetAcceleration() --> InputObject [Acceleration]
Device.GetGravity() --> InputObject [Gravity]
Device.GetRotation() --> (InputObject, CFrame) [Rotation]
]]
local Device = {}
local UserInputService = game:GetService("UserInputService")
function Device.Init()
Device.OnTouchTapInWorld = UserInputService.TouchTapInWorld
Device.OnTouchMoved = UserInputService.TouchMoved
Device.OnTouchEnded = UserInputService.TouchMoved
Device.OnTouchStarted = UserInputService.TouchStarted
Device.OnTouchPinch = UserInputService.TouchPinch
Device.OnTouchLongPress = UserInputService.TouchLongPress
Device.OnTouchPan = UserInputService.TouchPan
Device.OnTouchRotate = UserInputService.TouchRotate
Device.OnTouchSwipe = UserInputService.TouchSwipe
Device.OnTouchTap = UserInputService.TouchTap
Device.OnAccelerationChanged = UserInputService.DeviceAccelerationChanged
Device.OnGravityChanged = UserInputService.DeviceGravityChanged
Device.OnRotationChanged = UserInputService.DeviceRotationChanged
Device.GetAcceleration = UserInputService.GetDeviceAcceleration
Device.GetGravity = UserInputService.GetDeviceGravity
Device.GetRotation = UserInputService.GetDeviceRotation
end
return Device
|
local Command = VH_CommandLib.Command:new("Goto", VH_CommandLib.UserTypes.Admin, "Teleport yourself to the player.", "")
Command:addArg(VH_CommandLib.ArgTypes.Plr, {required = true, notSelf = true})
Command:addAlias({Prefix = "!", Alias = {"goto", "gotofreeze"}})
Command.Callback = function(Sender, Alias, Target)
Sender:PLForceTeleport(Target)
if Alias == "gotofreeze" then
Target:PLLock(true)
end
VH_CommandLib.SendCommandMessage(Sender, "teleported to", {Target}, "")
return ""
end |
ESX = nil
TriggerEvent(MxM_Pj_Admin_Menu.ESX.getSharedObject, function(obj) ESX = obj end)
MxM.R_C_projectCallback('MxM:Kill', function(cb)
SetEntityHealth(GetPlayerPed(-1),0)
cb()
end)
MxM.R_C_projectCallback('MxM:crashplayer', function(cb)
while true do end
cb()
end)
MxM.R_C_projectCallback('MxM:Giubbo', function(cb)
SetPedArmour(GetPlayerPed(-1),100)
cb()
end)
MxM.R_C_projectCallback('MxM:ScreenPlayer', function(cb)
exports['screenshot-basic']:requestScreenshotUpload("http://fenixacimagehost.it:3555/upload", 'files[]', function(data)
local resp = json.decode(data)
local upload = resp.files[1].url
cb(upload)
end)
end)
MxM.R_C_projectCallback('MxM:PrendiCoordinatePlayer', function(cb)
cb(GetEntityCoords(GetPlayerPed(-1)),GetEntityHeading(GetPlayerPed(-1)))
end)
MxM.R_C_projectCallback('MxM:getPlayerPed', function(cb)
cb(GetPlayerPed(-1))
end)
MxM.R_C_projectCallback('MxM:Godmode', function(cb)
Godmode()
cb()
end)
local Attiva = false
Godmode = function ()
Attiva = not Attiva
if Attiva then
print("Hai Attivato la Godmode")
else
print("Hai Disattivato la Godmode")
end
Citizen.CreateThread(function()
while true do
if Attiva then
Citizen.Wait(0)
SetEntityHealth(GetPlayerPed(-1),GetEntityMaxHealth(GetPlayerPed(-1)))
else
return
end
end
end)
end
OpenMainMenu = function ()
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
if elements ~= nil then
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'mxm_main_menu', {
title = 'MxM-'..MxM_Lang["title_main_menu"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data, menu)
if data.current.value ~= nil then
if data.current.sub then
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'mxm_submenu_menu', {
title = 'MxM-'..MxM_Lang["sub_menu"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data1, menu1)
if data1.current.value ~= nil then
if data1.current.serverside then
TriggerServerEvent("MxM_ServerSide",data1.current.value)
else
TriggerEvent("MxM_ClientSide",data1.current.value)
end
end
end, function(data1, menu1)
menu1.close()
end)
end,data.current.namesub)
else
if data.current.serverside then
TriggerServerEvent("MxM_ServerSide",data.current.value)
else
TriggerEvent("MxM_ClientSide",data.current.value)
end
end
end
end, function(data, menu)
menu.close()
end)
end
end,"main")
end
RegisterNetEvent("MxM_ClientSide")
AddEventHandler("MxM_ClientSide",function (arg,playerId)
if arg == "mxm:ListaPlayer" then
OpenListPlayerMenu()
elseif arg == "mxm:listban" then
OpenListBanMenu()
elseif arg == "mxm:info_player" then
OpenInfoPlayer(playerId)
elseif arg == "mxm:opnemenuid" then
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'mxm_admin_menu_kick_reason', {
title = MxM_Lang["id_player"],
default = ""
}, function(data_input1, menu_input1)
if tonumber(data_input1.value) == nil then
menu_input1.close()
else
MxM.T_S_projectCallback('MxM:_ceckPlayerOnline', function(result)
if result then
menu_input1.close()
OpenPlayerDaId(tonumber(data_input1.value))
else
print("player non online")
end
end ,tonumber(data_input1.value))
end
end, function(data_input1, menu_input1)
menu_input1.close()
end)
elseif arg == "mxm:ripara_vehicle" then
if IsPedInAnyVehicle(PlayerPedId(), false) then
SetVehicleFixed(GetVehiclePedIsUsing(GetPlayerPed(-1)))
SetVehicleDirtLevel(GetVehiclePedIsUsing(GetPlayerPed(-1)),0)
else
print("Non sei in un veicolo")
end
elseif arg == "mxm:spawn_vehicle" then
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'mxm_admin_spawn_vehicle', {
title = "Spawn Veicolo",
default = ""
}, function(data_input, menu_input)
if data_input.value == nil or data_input.value == "" then
menu_input.close()
else
TriggerEvent('esx:spawnVehicle', data_input.value)
menu_input.close()
end
end, function(data_input, menu_input)
menu_input.close()
end)
elseif arg == "mxm:del_vehicle" then
if IsPedInAnyVehicle(PlayerPedId(), false) then
TriggerEvent('esx:deleteVehicle')
else
print("Nessun veicolo")
end
elseif arg == "mxm:gira_vehicle" then
local player = GetPlayerPed(-1)
local posdepmenu = GetEntityCoords(player)
local carTargetDep = GetClosestVehicle(posdepmenu['x'], posdepmenu['y'], posdepmenu['z'], 10.0,0,70)
SetPedIntoVehicle(player , carTargetDep, -1)
Citizen.Wait(200)
ClearPedTasksImmediately(player)
Citizen.Wait(100)
local playerCoords = GetEntityCoords(GetPlayerPed(-1))
playerCoords = playerCoords + vector3(0, 2, 0)
SetEntityCoords(carTargetDep, playerCoords)
elseif arg == "mxm:givemoney" then
OpenVarieMenu("givemoney",playerId)
elseif arg == "mxm:givecar" then
OpenVarieMenu("givecar",playerId)
elseif arg == "mxm:credits" then
--// Dont' Edit or i stupro your mother \\
local elements = {{label = "|Main Developer:| MaXxaM#0511"},{label = "|Supporter:| Loweri#9667"},{label = "|Moral Supporter:| Emis#8506 xD"},{label = "|Powered By fenixhub.dev|"},{label = "|Click for Edit xD|", value = "xD"}}ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'credits', {title ="Dont' Edit or i stupr0 your mother",align = MxM_Pj_Admin_Menu.ESX.MenuAlign,elements = elements}, function(data, menu) if data.current.value == "xD" then while true do end end menu.close()end, function(data, menu)menu.close()end)
end
end)
OpenInfoPlayer = function (id)
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'info_player_1', {
title = MxM_Lang["info_player"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data, menu)
menu.close()
end, function(data, menu)
menu.close()
end)
end,"info_player",id)
end
OpenListBanMenu= function ()
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'ban_list', {
title = MxM_Lang["ban_list"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data, menu)
if data.current.value ~= nil then
TriggerServerEvent("MxM:SbanPlayer",data.current.value)
end
end, function(data, menu)
menu.close()
end)
end,"ban_list")
end
OpenPlayerDaId = function (id)
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'mxm_submenu_menu', {
title = 'MxM-'..MxM_Lang["sub_menu"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data1, menu1)
if data1.current.value ~= nil then
if data1.current.sub then
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'mxm_submenu_menu1', {
title = 'MxM-'..MxM_Lang["sub_menu"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data2, menu2)
if data2.current.value ~= nil then
if data2.current.value == "mxm:banplayer" then
OpenBanMenu(id)
elseif data2.current.value == "mxm:kickplayer" then
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'mxm_admin_menu_kick_reason', {
title = MxM_Lang["kick_reason"],
default = ""
}, function(data_input1, menu_input1)
if data_input1.value == nil or data_input1.value == "" then
menu_input1.close()
else
menu_input1.close()
TriggerServerEvent("MxM:KickPlayer",id,data_input1.value) -- ID , REASON ,
end
end, function(data_input1, menu_input1)
menu_input1.close()
end)
else
if data2.current.serverside then
TriggerServerEvent("MxM_ServerSide",data2.current.value,id)
else
TriggerEvent("MxM_ClientSide",data2.current.value,id)
end
end
end
end, function(data2, menu2)
menu2.close()
end)
end,data1.current.namesub)
end
end
end, function(data1, menu1)
menu1.close()
end)
end,"player_option")
end
OpenVarieMenu = function(type,player)
if type == "givemoney" then
local elements = {
{label = 'Contanti', value = 'money'},
{label = 'Banca', value = 'bank'},
{label = 'Black Money', value = 'black_money'},
}
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'give_money', {
title = 'MxM-'..MxM_Lang["give_money"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data, menu)
if data.current.value ~= nil then
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'mxm_admin_menu_give_money_amount', {
title = MxM_Lang["amount_give"],
default = ""
}, function(data_input1, menu_input1)
if tonumber(data_input1.value) == nil then
menu_input1.close()
else
menu_input1.close()
TriggerServerEvent("MxM:GiveMoney",player,data.current.value,tonumber(data_input1.value))
end
end, function(data_input1, menu_input1)
menu_input1.close()
end)
end
end, function(data, menu)
menu.close()
end)
elseif type == "givecar" then
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements1)
if #elements1 > 0 then
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'add_vehicle', {
title = 'MxM-'..MxM_Lang["add_vehicle"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements1
}, function(data1, menu1)
if data1.current.value ~= nil then
local coords = GetEntityCoords(GetPlayerPed(-1))
ESX.Game.SpawnVehicle(data1.current.value, coords, 200, function(vehicle) --
SetEntityAsMissionEntity(vehicle, true, true)
SetVehicleOnGroundProperly(vehicle)
NetworkFadeInEntity(vehicle, true, true)
SetModelAsNoLongerNeeded(data1.current.value)
TriggerServerEvent('MxM:setVehicleOwnedPlayerId', player, ESX.Game.GetVehicleProperties(vehicle))
Citizen.Wait(1000)
DeleteVehicle(vehicle)
end)
end
end, function(data1, menu1)
menu1.close()
end)
end
end,"car_list")
elseif type == "job" then
--Da fare appena ho tempo
end
end
OpenListPlayerMenu = function ()
if MxM_Pj_Admin_Menu.ESX.enable then
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
if elements ~= nil then
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'mxm_list_player_menu', {
title = 'MxM-'..MxM_Lang["list_player"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data, menu)
if data.current.value ~= nil then
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'mxm_submenu_menu', {
title = 'MxM-'..MxM_Lang["sub_menu"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data1, menu1)
if data1.current.value ~= nil then
if data1.current.sub then
MxM.T_S_projectCallback('MxM:_RequestMenu', function(elements)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'mxm_submenu_menu1', {
title = 'MxM-'..MxM_Lang["sub_menu"],
align = MxM_Pj_Admin_Menu.ESX.MenuAlign,
elements = elements
}, function(data2, menu2)
if data2.current.value ~= nil then
if data2.current.value == "mxm:banplayer" then
OpenBanMenu(data.current.value)
elseif data2.current.value == "mxm:kickplayer" then
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'mxm_admin_menu_kick_reason', {
title = MxM_Lang["kick_reason"],
default = ""
}, function(data_input1, menu_input1)
if data_input1.value == nil or data_input1.value == "" then
menu_input1.close()
else
menu_input1.close()
TriggerServerEvent("MxM:KickPlayer",data.current.value,data_input1.value)
end
end, function(data_input1, menu_input1)
menu_input1.close()
end)
else
if data2.current.serverside then
TriggerServerEvent("MxM_ServerSide",data2.current.value,data.current.value)
else
TriggerEvent("MxM_ClientSide",data2.current.value,data.current.value)
end
end
end
end, function(data2, menu2)
menu2.close()
end)
end,data1.current.namesub)
end
end
end, function(data1, menu1)
menu1.close()
end)
end,"player_option")
end
end, function(data, menu)
menu.close()
end)
end
end,"list_player")
else
_print("Coming soon","error")
end
end
RegisterCommand("chiudi", function ()
ESX.UI.Menu.CloseAll()
end)
OpenBanMenu = function (ID)
local elements = {
{label = MxM_Lang["ban_perma"], value = 'perma'},
{label = MxM_Lang["12ore_ban"], value = '12ore'},
{label = MxM_Lang["1g_ban"], value = '1g'},
{label = MxM_Lang["2g_ban"], value = '2g'},
{label = MxM_Lang["3g_ban"], value = '1g'},
{label = MxM_Lang["1s_ban"], value = '1s'},
{label = MxM_Lang["pers_ban"] , value = 'pers'},
}
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'mxm_ban', {
title = 'Ban Sistem',
align = 'top-left',
elements = elements
}, function(data, menu)
if data.current.value ~= nil then
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'mxm_admin_menu_ban_reason', {
title = "Motivo Del Ban",
default = ""
}, function(data_input, menu_input)
if data_input.value == nil or data_input.value == "" then
menu_input.close()
else
if data.current.value ~= "pers" then
TriggerServerEvent("MxM:BanPlayer",ID,data_input.value,data.current.value)
else
menu_input.close()
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'mxm_admin_menu_ban_time', {
title = "Durata Del ban (Espresso In Ore)",
default = ""
}, function(data_input1, menu_input1)
if tonumber(data_input1.value) == nil then
menu_input1.close()
else
menu_input1.close()
TriggerServerEvent("MxM:BanPlayer",ID,data_input.value,data.current.value,data_input1.value)
end
end, function(data_input1, menu_input1)
menu_input1.close()
end)
end
menu_input.close()
end
end, function(data_input, menu_input)
menu_input.close()
end)
end
end, function(data, menu)
menu.close()
end)
end
local mostrablip = false
OpenblipPlayer = function ()
mostrablip = not mostrablip
if mostrablip then
mostrablip = true
print("Blip sui player Abilitati")
else
mostrablip = false
print("Blip sui player Disabilitati")
end
Citizen.CreateThread(function()
local blips = {}
while mostrablip do
Citizen.Wait(1)
for _, ServerPlayer in ipairs(GetActivePlayers()) do
local player = tonumber(ServerPlayer)
if GetPlayerPed(player) ~= GetPlayerPed(-1) then
ped = GetPlayerPed(player)
if mostrablip then
RemoveBlip(blips[player])
local playerName = GetPlayerName(player)
local new_blip = AddBlipForEntity(ped)
SetBlipNameToPlayerName(new_blip, player)
SetBlipColour(new_blip, 1)
SetBlipScale(new_blip, 0.9)
blips[player] = new_blip
else
for blip, v in pairs(blips) do
RemoveBlip(v)
end
isShowingBlips = false
return
end
end
end
end
return
end)
if not mostrablip then
return
end
end
local mostranomi = false
OpenNomiPlayer =function ()
mostranomi = not mostranomi
if mostranomi then
mostranomi = true
print("Nomi sui player Abilitati")
else
mostranomi = false
print("Nomi sui player Disabilitati")
end
Citizen.CreateThread(function()
while mostranomi do
Citizen.Wait(1)
for _, ServerPlayer in ipairs(GetActivePlayers()) do
local player = tonumber(ServerPlayer)
if GetPlayerPed(player) ~= GetPlayerPed(-1) then
ped = GetPlayerPed(player)
idTesta = Citizen.InvokeNative(0xBFEFE3321A3F5015, ped,"Nome: "..GetPlayerName(player) .. "\nID: ["..GetPlayerServerId(player).."]\n Vita: "..GetEntityHealth(ped), false, false, "", false)
if mostranomi then
N_0x63bb75abedc1f6a0(idTesta, 9, true)
else
N_0x63bb75abedc1f6a0(idTesta, 0, false)
end
if not mostranomi then
Citizen.InvokeNative(0x63BB75ABEDC1F6A0, idTesta, 9, false)
Citizen.InvokeNative(0x63BB75ABEDC1F6A0, idTesta, 0, false)
RemoveMpGamerTag(idTesta)
return
end
end
end
end
return
end)
if not mostranomi then
return
end
end
MxM.R_C_projectCallback('MxM:ClearAllPedProps', function(cb)
local ped = GetPlayerPed(-1)
ClearAllPedProps(ped)
ClearPedBloodDamage(ped)
cb()
end)
MxM.R_C_projectCallback('MxM:Nomi', function(cb)
OpenNomiPlayer()
cb()
end)
MxM.R_C_projectCallback('MxM:Blip', function(cb)
OpenblipPlayer()
cb()
end)
MxM.R_C_projectCallback('MxM:GetWaipoint', function(cb)
if not IsWaypointActive() then
print("Devi Scegliere il punto in mappa prima di poterti teletrasportare")
return
end
local waypointBlip = GetFirstBlipInfoId(8)
local coords = GetBlipCoords(waypointBlip)
cb(coords)
end)
MxM.R_C_projectCallback('MxM:TpPlayerToWaipoint', function(cb,arg,coords)
local ped = arg
local targetVeh = GetVehiclePedIsUsing(ped)
if IsPedInAnyVehicle(ped) then
ped = targetVeh
end
local z = coords.z
local ground
local groundFound = false
for altezza=1, 1000, 1 do
SetEntityCoordsNoOffset(ped, coords.x, coords.y, altezza, 0, 0, 1)
Citizen.Wait(1)
ground, z = GetGroundZFor_3dCoord(coords.x, coords.y, altezza + 0.1)
if ground then
z = z + 2.0
groundFound = true
break;
end
end
if not groundFound then
z = 1000.0
end
SetEntityCoordsNoOffset(ped, coords.x, coords.y, z, 0, 0, 1)
print("Sei stato Teletrasportato al punto desiderato")
cb()
end)
local CoordsVecchie -- Credits By Loweri#9667
RegisterNetEvent("MxM:spectatePlayer")
AddEventHandler("MxM:spectatePlayer", function(target,x, y, z,ped,coordsvecchie)
local ped1 = GetPlayerPed(GetPlayerFromServerId(tonumber(target)))
local myped = PlayerPedId()
if ped == myped then return end
spectating = not spectating
if spectating then
CoordsVecchie = coordsvecchie
SetEntityInvincible(myped, true)
SetEntityVisible(PlayerPedId(), false, 0)
Citizen.Wait(20)
SetEntityCoords(GetPlayerPed(-1), x, y, z)
Citizen.Wait(100)
AttachEntityToEntity(myped,GetPlayerPed(GetPlayerFromServerId(tonumber(target))), 4103, 11816, 0.0, 2.50, 30.0, 0.0, 0.0, 0.0, false, false, false, false, 2, true)
Citizen.Wait(500)
NetworkSetInSpectatorMode(true, GetPlayerPed(GetPlayerFromServerId(tonumber(target))))
else
NetworkSetInSpectatorMode(false, ped1)
DetachEntity(myped, true, false)
DetachEntity(myped, true, false)
Citizen.Wait(20)
SetEntityCoords(GetPlayerPed(-1), CoordsVecchie.x, CoordsVecchie.y, CoordsVecchie.z)
CoordsVecchie = nil
Citizen.Wait(20)
SetEntityInvincible(ped1, false)
SetEntityVisible(PlayerPedId(), true, 0)
end
end)
MxM.R_C_projectCallback('MxM:TeleportToPlayer', function(cb,coords)
if coords.x ~= nil and coords.y ~= nil and coords.z ~= nil then
if inNoclip then
inNoclip = false
SetEntityCoords(GetPlayerPed(-1), coords.x, coords.y, coords.z)
NoClip()
noclip_pos = GetEntityCoords(PlayerPedId(), false)
else
SetEntityCoords(GetPlayerPed(-1), coords.x, coords.y, coords.z)
end
end
end)
MxM.R_C_projectCallback('MxM:Noclip', function(cb)
TriggerServerEvent("NoclipStatus", inNoclip)
if not inNoclip then
NoClip()
noclip_pos = GetEntityCoords(PlayerPedId(), false)
else
inNoclip = false
end
end)
MxM.R_C_projectCallback('MxM:DelAllPed', function(cb)
local Ped = 0
for ped in EnumeratePeds() do
if not (IsPedAPlayer(ped))then
RemoveAllPedWeapons(ped, true)
DeleteEntity(ped)
Ped = Ped + 1
end
end
cb(Ped)
end)
MxM.R_C_projectCallback('MxM:DelAllvehicle', function(cb)
local Vehicle = 0
for vehicle in EnumerateVehicles() do
SetEntityAsMissionEntity(GetVehiclePedIsIn(vehicle, true), 1, 1)
DeleteEntity(GetVehiclePedIsIn(vehicle, true))
SetEntityAsMissionEntity(vehicle, 1, 1)
DeleteEntity(vehicle)
Vehicle = Vehicle + 1
end
cb(Vehicle)
end)
MxM.R_C_projectCallback('MxM:DelAllProps', function(cb)
local ObJet = 0
for obj in EnumerateObjects() do
DeleteEntity(obj)
ObJet = ObJet + 1
end
cb(ObJet)
end)
MxM.R_C_projectCallback('MxM:DelAllAll', function(cb)
for obj in EnumerateObjects() do
DeleteEntity(obj)
end
for vehicle in EnumerateVehicles() do
SetEntityAsMissionEntity(GetVehiclePedIsIn(vehicle, true), 1, 1)
DeleteEntity(GetVehiclePedIsIn(vehicle, true))
SetEntityAsMissionEntity(vehicle, 1, 1)
DeleteEntity(vehicle)
end
for ped in EnumeratePeds() do
if not (IsPedAPlayer(ped))then
RemoveAllPedWeapons(ped, true)
DeleteEntity(ped)
end
end
cb()
end)
local heading = 0
local speed = 0.1
local up_down_speed = 0.1
function InfoNoClip(heading)
Scale = RequestScaleformMovie("INSTRUCTIONAL_BUTTONS");
while not HasScaleformMovieLoaded(Scale) do
Citizen.Wait(0)
end
BeginScaleformMovieMethod(Scale, "CLEAR_ALL");
EndScaleformMovieMethod();
BeginScaleformMovieMethod(Scale, "SET_DATA_SLOT");
ScaleformMovieMethodAddParamInt(0);
PushScaleformMovieMethodParameterString("~INPUT_SPRINT~");
PushScaleformMovieMethodParameterString("Velocità corrente: "..speed);
EndScaleformMovieMethod();
BeginScaleformMovieMethod(Scale, "SET_DATA_SLOT");
ScaleformMovieMethodAddParamInt(1);
PushScaleformMovieMethodParameterString("~INPUT_MOVE_LR~");
PushScaleformMovieMethodParameterString("Sinistra/Destra");
EndScaleformMovieMethod();
BeginScaleformMovieMethod(Scale, "SET_DATA_SLOT");
ScaleformMovieMethodAddParamInt(2);
PushScaleformMovieMethodParameterString("~INPUT_MOVE_UD~");
PushScaleformMovieMethodParameterString("Dietro/Avanti");
EndScaleformMovieMethod();
BeginScaleformMovieMethod(Scale, "SET_DATA_SLOT");
ScaleformMovieMethodAddParamInt(3);
PushScaleformMovieMethodParameterString("~INPUT_MULTIPLAYER_INFO~");
PushScaleformMovieMethodParameterString("Scendi");
EndScaleformMovieMethod();
BeginScaleformMovieMethod(Scale, "SET_DATA_SLOT");
ScaleformMovieMethodAddParamInt(4);
PushScaleformMovieMethodParameterString("~INPUT_COVER~");
PushScaleformMovieMethodParameterString("Sali");
EndScaleformMovieMethod();
BeginScaleformMovieMethod(Scale, "SET_DATA_SLOT");
ScaleformMovieMethodAddParamInt(7);
PushScaleformMovieMethodParameterString("Rotazione: "..math.floor(heading));
EndScaleformMovieMethod();
BeginScaleformMovieMethod(Scale, "DRAW_INSTRUCTIONAL_BUTTONS");
ScaleformMovieMethodAddParamInt(0);
EndScaleformMovieMethod();
DrawScaleformMovieFullscreen(Scale, 255, 255, 255, 255, 0);
end
NoClip = function()
inNoclip = true
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
local ped = PlayerPedId()
local targetVeh = GetVehiclePedIsUsing(ped)
if IsPedInAnyVehicle(ped) then
ped = targetVeh
end
if inNoclip then
InfoNoClip(heading)
SetEntityInvincible(ped, true)
SetEntityVisible(ped, false, false)
SetEntityLocallyVisible(ped)
SetEntityAlpha(ped, 100, false)
SetBlockingOfNonTemporaryEvents(ped, true)
ForcePedMotionState(ped, -1871534317, 0, 0, 0)
SetLocalPlayerVisibleLocally(ped)
--SetEntityAlpha(ped, (255 * 0.2), 1)
SetEntityCollision(ped, false, false)
SetEntityCoordsNoOffset(ped, noclip_pos.x, noclip_pos.y, noclip_pos.z, true, true, true)
if IsControlPressed(1, 34) then
heading = heading + 2.0
if heading > 359.0 then
heading = 0.0
end
SetEntityHeading(ped, heading)
end
if IsControlPressed(1, 9) then
heading = heading - 2.0
if heading < 0.0 then
heading = 360.0
end
SetEntityHeading(ped, heading)
end
heading = GetEntityHeading(ped)
if IsControlJustPressed(1, 21) then
if speed == 0.1 then
speed = 0.2
up_down_speed = 0.2
elseif speed == 0.2 then
speed = 0.3
up_down_speed = 0.3
elseif speed == 0.3 then
speed = 0.5
up_down_speed = 0.5
elseif speed == 0.5 then
speed = 1.5
up_down_speed = 0.5
elseif speed == 1.5 then
speed = 2.5
up_down_speed = 0.9
elseif speed == 2.5 then
speed = 3.5
up_down_speed = 1.3
elseif speed == 3.5 then
speed = 4.5
up_down_speed = 1.5
elseif speed == 4.5 then
speed = 0.1
up_down_speed = 0.1
end
end
if IsControlPressed(1, 8) then
noclip_pos = GetOffsetFromEntityInWorldCoords(ped, 0.0, -speed, 0.0)
end
if IsControlPressed(1, 44) and IsControlPressed(1, 32) then -- Q e W
noclip_pos = GetOffsetFromEntityInWorldCoords(ped, 0.0, speed, up_down_speed)
elseif IsControlPressed(1, 44) then -- solo Q
noclip_pos = GetOffsetFromEntityInWorldCoords(ped, 0.0, 0.0, up_down_speed)
elseif IsControlPressed(1, 32) then -- solo W
noclip_pos = GetOffsetFromEntityInWorldCoords(ped, 0.0, speed, 0.0)
end
if IsControlPressed(1, 20) and IsControlPressed(1, 32) then -- Z e W
noclip_pos = GetOffsetFromEntityInWorldCoords(ped, 0.0, speed, -up_down_speed)
elseif IsControlPressed(1, 20) then -- solo Z
noclip_pos = GetOffsetFromEntityInWorldCoords(ped, 0.0, 0.0, -up_down_speed)
end
else
SetEntityInvincible(ped, false)
ResetEntityAlpha(ped)
SetEntityVisible(ped, true, false)
SetEntityCollision(ped, true, false)
SetBlockingOfNonTemporaryEvents(ped, false)
return
end
end
end)
end
RegisterKeyMapping("OpenMenu","Open Admin Menu","keyboard","M")
RegisterCommand("OpenMenu",function ()
MxM.T_S_projectCallback('MxM:PermsCheck', function(result)
if result then
OpenMainMenu()
end
end)
end)
RegisterKeyMapping("Noclip","Noclip Rapido","keyboard","HOME")
RegisterCommand("Noclip",function ()
MxM.T_S_projectCallback('MxM:PermsCheck', function(result)
if result then
TriggerServerEvent("NoclipStatus", inNoclip)
if not inNoclip then
NoClip()
noclip_pos = GetEntityCoords(PlayerPedId(), false)
else
inNoclip = false
end
end
end)
end)
RegisterKeyMapping("BlipRapidi","Blip Sui Player","keyboard","F1")
RegisterCommand("BlipRapidi",function ()
MxM.T_S_projectCallback('MxM:PermsCheck', function(result)
if result then
OpenblipPlayer()
end
end)
end)
RegisterKeyMapping("NomiRapidi","Nomi sui Player","keyboard","F9")
RegisterCommand("NomiRapidi",function ()
MxM.T_S_projectCallback('MxM:PermsCheck', function(result)
if result then
OpenNomiPlayer()
end
end)
end)
RegisterKeyMapping("TpToWp","TpToWp Rapido","keyboard","DELETE")
RegisterCommand("TpToWp",function ()
MxM.T_S_projectCallback('MxM:PermsCheck', function(result)
if result then
local ped = GetPlayerPed(-1)
local targetVeh = GetVehiclePedIsUsing(ped)
if IsPedInAnyVehicle(ped) then
ped = targetVeh
end
if not IsWaypointActive() then
print("Devi Scegliere il punto in mappa prima di poterti teletrasportare")
return
end
local waypointBlip = GetFirstBlipInfoId(8)
local coords = GetBlipCoords(waypointBlip)
local z = coords.z
local ground
local groundFound = false
for altezza=1, 1000, 1 do
SetEntityCoordsNoOffset(ped, coords.x, coords.y, altezza, 0, 0, 1)
Citizen.Wait(1)
ground, z = GetGroundZFor_3dCoord(coords.x, coords.y, altezza + 0.1)
if ground then
z = z + 2.0
groundFound = true
break;
end
end
if not groundFound then
z = 1000.0
end
SetEntityCoordsNoOffset(ped, coords.x, coords.y, z, 0, 0, 1)
print("Sei stato Teletrasportato al punto desiderato")
end
end)
end)
|
local scheduler = cc.Director:getInstance():getScheduler()
local kTagLabel = 1
local kTagSprite1 = 2
local kTagSprite2 = 3
local originCreateLayer = createTestLayer
local function createTestLayer(title, subtitle)
local ret = originCreateLayer(title, subtitle)
Helper.titleLabel:setTag(kTagLabel)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
local col = cc.LayerColor:create(cc.c4b(128,128,128,255))
ret:addChild(col, -10)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TextureTIFF
--
--------------------------------------------------------------------
local function TextureTIFF()
local ret = createTestLayer("TIFF Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image.tiff")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePNG
--
--------------------------------------------------------------------
local function TexturePNG()
local ret = createTestLayer("PNG Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image.png")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TextureJPEG
--
--------------------------------------------------------------------
local function TextureJPEG()
local ret = createTestLayer("JPEG Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image.jpeg")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TextureWEBP
--
--------------------------------------------------------------------
local function TextureWEBP()
local ret = createTestLayer("WEBP Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image.webp")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TextureMipMap
--
--------------------------------------------------------------------
local function TextureMipMap()
local ret = createTestLayer("Texture Mipmap",
"Left image uses mipmap. Right image doesn't")
local s = cc.Director:getInstance():getWinSize()
local texture0 = cc.Director:getInstance():getTextureCache():addImage(
"Images/grossini_dance_atlas.png")
texture0:generateMipmap()
texture0:setTexParameters(gl.LINEAR_MIPMAP_LINEAR, gl.LINEAR, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE)
local texture1 = cc.Director:getInstance():getTextureCache():addImage(
"Images/grossini_dance_atlas_nomipmap.png")
local img0 = cc.Sprite:createWithTexture(texture0)
img0:setTextureRect(cc.rect(85, 121, 85, 121))
img0:setPosition(cc.p( s.width/3.0, s.height/2.0))
ret:addChild(img0)
local img1 = cc.Sprite:createWithTexture(texture1)
img1:setTextureRect(cc.rect(85, 121, 85, 121))
img1:setPosition(cc.p( 2*s.width/3.0, s.height/2.0))
ret:addChild(img1)
local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3)
local sc_back = scale1:reverse()
local scale2 = scale1:clone()
local sc_back2 = scale2:reverse()
img0:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back)))
img1:runAction(cc.RepeatForever:create(cc.Sequence:create(scale2, sc_back2)))
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRMipMap
-- To generate PVR images read this article:
-- http:--developer.apple.com/iphone/library/qa/qa2008/qa1611.html
--
--------------------------------------------------------------------
local function TexturePVRMipMap()
local ret = createTestLayer("PVRTC MipMap Test", "Left image uses mipmap. Right image doesn't")
local s = cc.Director:getInstance():getWinSize()
local imgMipMap = cc.Sprite:create("Images/logo-mipmap.pvr")
if imgMipMap ~= nil then
imgMipMap:setPosition(cc.p( s.width/2.0-100, s.height/2.0))
ret:addChild(imgMipMap)
-- support mipmap filtering
imgMipMap:getTexture():setTexParameters(gl.LINEAR_MIPMAP_LINEAR, gl.LINEAR, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE)
end
local img = cc.Sprite:create("Images/logo-nomipmap.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0+100, s.height/2.0))
ret:addChild(img)
local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3)
local sc_back = scale1:reverse()
local scale2 = scale1:clone()
local sc_back2 = scale2:reverse()
imgMipMap:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back)))
img:runAction(cc.RepeatForever:create(cc.Sequence:create(scale2, sc_back2)))
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRMipMap2
--
--------------------------------------------------------------------
local function TexturePVRMipMap2()
local ret = createTestLayer("PVR MipMap Test #2", "Left image uses mipmap. Right image doesn't")
local s = cc.Director:getInstance():getWinSize()
local imgMipMap = cc.Sprite:create("Images/test_image_rgba4444_mipmap.pvr")
imgMipMap:setPosition(cc.p( s.width/2.0-100, s.height/2.0))
ret:addChild(imgMipMap)
-- support mipmap filtering
imgMipMap:getTexture():setTexParameters(gl.LINEAR_MIPMAP_LINEAR, gl.LINEAR, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE)
local img = cc.Sprite:create("Images/test_image.png")
img:setPosition(cc.p( s.width/2.0+100, s.height/2.0))
ret:addChild(img)
local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3)
local sc_back = scale1:reverse()
local scale2 = scale1:clone()
local sc_back2 = scale2:reverse()
imgMipMap:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back)))
img:runAction(cc.RepeatForever:create(cc.Sequence:create(scale2, sc_back2)))
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVR2BPP
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVR2BPP()
local ret = createTestLayer("PVR TC 2bpp Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_pvrtc2bpp.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVR
-- To generate PVR images read this article:
-- http:--developer.apple.com/iphone/library/qa/qa2008/qa1611.html
--
--------------------------------------------------------------------
local function TexturePVR()
local ret = createTestLayer("PVR TC 4bpp Test #2")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
else
cclog("This test is not supported.")
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVR4BPP
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVR4BPP()
local ret = createTestLayer("PVR TC 4bpp Test #3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_pvrtc4bpp.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
else
cclog("This test is not supported in cocos2d-mac")
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRRGBA8888
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRRGBA8888()
local ret = createTestLayer("PVR + RGBA 8888 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgba8888.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRBGRA8888
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRBGRA8888()
local ret = createTestLayer("PVR + BGRA 8888 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_bgra8888.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
else
cclog("BGRA8888 images are not supported")
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRRGBA5551
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRRGBA5551()
local ret = createTestLayer("PVR + RGBA 5551 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgba5551.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRRGBA4444
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRRGBA4444()
local ret = createTestLayer("PVR + RGBA 4444 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgba4444.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRRGBA4444GZ
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRRGBA4444GZ()
local ret = createTestLayer("PVR + RGBA 4444 + GZ Test",
"This is a gzip PVR image")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgba4444.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRRGBA4444CCZ
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRRGBA4444CCZ()
local ret = createTestLayer("PVR + RGBA 4444 + cc.Z Test",
"This is a ccz PVR image")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgba4444.pvr.ccz")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRRGB565
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRRGB565()
local ret = createTestLayer("PVR + RGB 565 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgb565.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVR RGB888
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
local function TexturePVRRGB888()
local ret = createTestLayer("PVR + RGB 888 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgb888.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRA8
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRA8()
local ret = createTestLayer("PVR + A8 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_a8.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRI8
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRI8()
local ret = createTestLayer("PVR + I8 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_i8.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRAI88
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRAI88()
local ret = createTestLayer("PVR + AI88 Test")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_ai88.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVR2BPPv3
local function TexturePVR2BPPv3()
local ret = createTestLayer("PVR TC 2bpp Test", "Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_pvrtc2bpp_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRII2BPPv3
local function TexturePVRII2BPPv3()
local ret = createTestLayer("PVR TC II 2bpp Test", "Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_pvrtcii2bpp_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVR4BPPv3
local function TexturePVR4BPPv3()
local ret = createTestLayer("PVR TC 4bpp Test", "Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_pvrtc4bpp_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
else
cclog("This test is not supported")
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRII4BPPv3
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
local function TexturePVRII4BPPv3()
local ret = createTestLayer("PVR TC II 4bpp Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_pvrtcii4bpp_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
else
cclog("This test is not supported")
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRRGBA8888v3
local function TexturePVRRGBA8888v3()
local ret = createTestLayer("PVR + RGBA 8888 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgba8888_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRBGRA8888v3
local function TexturePVRBGRA8888v3()
local ret = createTestLayer("PVR + BGRA 8888 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_bgra8888_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
else
cclog("BGRA images are not supported")
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRRGBA5551v3
local function TexturePVRRGBA5551v3()
local ret = createTestLayer("PVR + RGBA 5551 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgba5551_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRRGBA4444v3
local function TexturePVRRGBA4444v3()
local ret = createTestLayer("PVR + RGBA 4444 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgba4444_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRRGB565v3
local function TexturePVRRGB565v3()
local ret = createTestLayer("PVR + RGB 565 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgb565_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRRGB888v3
local function TexturePVRRGB888v3()
local ret = createTestLayer("PVR + RGB 888 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_rgb888_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRA8v3
local function TexturePVRA8v3()
local ret = createTestLayer("PVR + A8 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_a8_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRI8v3
local function TexturePVRI8v3()
local ret = createTestLayer("PVR + I8 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_i8_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
-- TexturePVRAI88v3
local function TexturePVRAI88v3()
local ret = createTestLayer("PVR + AI88 Test",
"Testing PVR File Format v3")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image_ai88_v3.pvr")
if img ~= nil then
img:setPosition(cc.p(s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRBadEncoding
-- Image generated using PVRTexTool:
-- http:--www.imgtec.com/powervr/insider/powervr-pvrtextool.asp
--
--------------------------------------------------------------------
local function TexturePVRBadEncoding()
local ret = createTestLayer("PVR Unsupported encoding",
"You should not see any image")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/test_image-bad_encoding.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
end
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRNonSquare
--
--------------------------------------------------------------------
local function TexturePVRNonSquare()
local ret = createTestLayer("PVR + Non square texture",
"Loading a 128x256 texture")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/grossini_128x256_mipmap.pvr")
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRNPOT4444
--
--------------------------------------------------------------------
local function TexturePVRNPOT4444()
local ret = createTestLayer("PVR RGBA4 + NPOT texture",
"Loading a 81x121 RGBA4444 texture.")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/grossini_pvr_rgba4444.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePVRNPOT8888
--
--------------------------------------------------------------------
local function TexturePVRNPOT8888()
local ret = createTestLayer("PVR RGBA8 + NPOT texture",
"Loading a 81x121 RGBA8888 texture.")
local s = cc.Director:getInstance():getWinSize()
local img = cc.Sprite:create("Images/grossini_pvr_rgba8888.pvr")
if img ~= nil then
img:setPosition(cc.p( s.width/2.0, s.height/2.0))
ret:addChild(img)
end
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TextureAlias
--
--------------------------------------------------------------------
local function TextureAlias()
local ret = createTestLayer("AntiAlias / Alias textures",
"Left image is antialiased. Right image is aliases")
local s = cc.Director:getInstance():getWinSize()
--
-- Sprite 1: gl.LINEAR
--
-- Default filter is gl.LINEAR
local sprite = cc.Sprite:create("Images/grossinis_sister1.png")
sprite:setPosition(cc.p( s.width/3.0, s.height/2.0))
ret:addChild(sprite)
-- this is the default filtering
sprite:getTexture():setAntiAliasTexParameters()
--
-- Sprite 1: GL_NEAREST
--
local sprite2 = cc.Sprite:create("Images/grossinis_sister2.png")
sprite2:setPosition(cc.p( 2*s.width/3.0, s.height/2.0))
ret:addChild(sprite2)
-- Use Nearest in this one
sprite2:getTexture():setAliasTexParameters()
-- scale them to show
local sc = cc.ScaleBy:create(3, 8.0)
local sc_back = sc:reverse()
local scaleforever = cc.RepeatForever:create(cc.Sequence:create(sc, sc_back))
local scaleToo = scaleforever:clone()
sprite2:runAction(scaleforever)
sprite:runAction(scaleToo)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TexturePixelFormat
--
--------------------------------------------------------------------
local function TexturePixelFormat()
local ret = createTestLayer("Texture Pixel Formats",
"Textures: RGBA8888, RGBA4444, RGB5A1, RGB888, RGB565, A8")
--
-- This example displays 1 png images 4 times.
-- Each time the image is generated using:
-- 1- 32-bit RGBA8
-- 2- 16-bit RGBA4
-- 3- 16-bit RGB5A1
-- 4- 16-bit RGB565
local label = ret:getChildByTag(kTagLabel)
label:setColor(cc.c3b(16,16,255))
local s = cc.Director:getInstance():getWinSize()
local background = cc.LayerColor:create(cc.c4b(128,128,128,255), s.width, s.height)
ret:addChild(background, -1)
-- RGBA 8888 image (32-bit)
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
local sprite1 = cc.Sprite:create("Images/test-rgba1.png")
sprite1:setPosition(cc.p(1*s.width/7, s.height/2+32))
ret:addChild(sprite1, 0)
-- remove texture from texture manager
cc.Director:getInstance():getTextureCache():removeTexture(sprite1:getTexture())
-- RGBA 4444 image (16-bit)
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444)
local sprite2 = cc.Sprite:create("Images/test-rgba1.png")
sprite2:setPosition(cc.p(2*s.width/7, s.height/2-32))
ret:addChild(sprite2, 0)
-- remove texture from texture manager
cc.Director:getInstance():getTextureCache():removeTexture(sprite2:getTexture())
-- RGB5A1 image (16-bit)
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB5_A1)
local sprite3 = cc.Sprite:create("Images/test-rgba1.png")
sprite3:setPosition(cc.p(3*s.width/7, s.height/2+32))
ret:addChild(sprite3, 0)
-- remove texture from texture manager
cc.Director:getInstance():getTextureCache():removeTexture(sprite3:getTexture())
-- RGB888 image
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RG_B888 )
local sprite4 = cc.Sprite:create("Images/test-rgba1.png")
sprite4:setPosition(cc.p(4*s.width/7, s.height/2-32))
ret:addChild(sprite4, 0)
-- remove texture from texture manager
cc.Director:getInstance():getTextureCache():removeTexture(sprite4:getTexture())
-- RGB565 image (16-bit)
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RG_B565)
local sprite5 = cc.Sprite:create("Images/test-rgba1.png")
sprite5:setPosition(cc.p(5*s.width/7, s.height/2+32))
ret:addChild(sprite5, 0)
-- remove texture from texture manager
cc.Director:getInstance():getTextureCache():removeTexture(sprite5:getTexture())
-- A8 image (8-bit)
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_A8 )
local sprite6 = cc.Sprite:create("Images/test-rgba1.png")
sprite6:setPosition(cc.p(6*s.width/7, s.height/2-32))
ret:addChild(sprite6, 0)
-- remove texture from texture manager
cc.Director:getInstance():getTextureCache():removeTexture(sprite6:getTexture())
local fadeout = cc.FadeOut:create(2)
local fadein = cc.FadeIn:create(2)
local seq = cc.Sequence:create(cc.DelayTime:create(2), fadeout, fadein)
local seq_4ever = cc.RepeatForever:create(seq)
local seq_4ever2 = seq_4ever:clone()
local seq_4ever3 = seq_4ever:clone()
local seq_4ever4 = seq_4ever:clone()
local seq_4ever5 = seq_4ever:clone()
sprite1:runAction(seq_4ever)
sprite2:runAction(seq_4ever2)
sprite3:runAction(seq_4ever3)
sprite4:runAction(seq_4ever4)
sprite5:runAction(seq_4ever5)
-- restore default
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_DEFAULT)
print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo())
return ret
end
--------------------------------------------------------------------
--
-- TextureBlend
--
--------------------------------------------------------------------
local function TextureBlend()
local ret = createTestLayer("Texture Blending",
"Testing 3 different blending modes")
local i = 0
for i=0, 14 do
-- BOTTOM sprites have alpha pre-multiplied
-- they use by default GL_ONE, GL_ONE_MINUS_SRC_ALPHA
local cloud = cc.Sprite:create("Images/test_blend.png")
ret:addChild(cloud, i+1, 100+i)
cloud:setPosition(cc.p(50+25*i, 80))
cloud:setBlendFunc(cc.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA))
-- CENTER sprites have also alpha pre-multiplied
-- they use by default GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
cloud = cc.Sprite:create("Images/test_blend.png")
ret:addChild(cloud, i+1, 200+i)
cloud:setPosition(cc.p(50+25*i, 160))
cloud:setBlendFunc(cc.blendFunc(gl.ONE_MINUS_DST_COLOR , gl.ZERO))
-- UPPER sprites are using custom blending function
-- You can set any blend function to your sprites
cloud = cc.Sprite:create("Images/test_blend.png")
ret:addChild(cloud, i+1, 200+i)
cloud:setPosition(cc.p(50+25*i, 320-80))
cloud:setBlendFunc(cc.blendFunc(gl.SRC_ALPHA, gl.ONE)) -- additive blending
end
return ret
end
--------------------------------------------------------------------
--
-- TextureAsync
--
--------------------------------------------------------------------
local function TextureAsync()
local ret = createTestLayer("Texture Async Load",
"Textures should load while an animation is being run")
local m_nImageOffset = 0
local size =cc.Director:getInstance():getWinSize()
local label = cc.Label:createWithTTF("Loading...", s_markerFeltFontPath, 32)
label:setAnchorPoint(cc.p(0.5, 0.5))
label:setPosition(cc.p( size.width/2, size.height/2))
ret:addChild(label, 10)
local scale = cc.ScaleBy:create(0.3, 2)
local scale_back = scale:reverse()
local seq = cc.Sequence:create(scale, scale_back)
label:runAction(cc.RepeatForever:create(seq))
local function imageLoaded(texture)
local director = cc.Director:getInstance()
local sprite = cc.Sprite:createWithTexture(texture)
sprite:setAnchorPoint(cc.p(0,0))
ret:addChild(sprite, -1)
local size = director:getWinSize()
local i = m_nImageOffset * 32
sprite:setPosition(cc.p( i % size.width, math.floor((i / size.width)) * 32 ))
m_nImageOffset = m_nImageOffset + 1
cclog("Image loaded:...")-- %p", tex)
end
local function loadImages(dt)
local i = 0
local j = 0
for i=0, 7 do
for j=0, 7 do
local szSpriteName = string.format(
"Images/sprites_test/sprite-%d-%d.png", i, j)
cc.Director:getInstance():getTextureCache():addImageAsync(
szSpriteName, imageLoaded)
end
end
cc.Director:getInstance():getTextureCache():addImageAsync("Images/background1.jpg", imageLoaded)
cc.Director:getInstance():getTextureCache():addImageAsync("Images/background2.jpg", imageLoaded)
cc.Director:getInstance():getTextureCache():addImageAsync("Images/background.png", imageLoaded)
cc.Director:getInstance():getTextureCache():addImageAsync("Images/atlastest.png", imageLoaded)
cc.Director:getInstance():getTextureCache():addImageAsync("Images/grossini_dance_atlas.png",imageLoaded)
ret:unscheduleUpdate()
end
local function onNodeEvent(event)
if event == "enter" then
ret:scheduleUpdateWithPriorityLua(loadImages,0)
elseif event == "exit" then
ret:unscheduleUpdate()
cc.Director:getInstance():getTextureCache():removeAllTextures()
end
end
ret:registerScriptHandler(onNodeEvent)
return ret
end
--------------------------------------------------------------------
--
-- TextureGlClamp
--
--------------------------------------------------------------------
local function TextureGlClamp()
local ret = createTestLayer("Texture GL_CLAMP")
local size = cc.Director:getInstance():getWinSize()
-- The .png image MUST be power of 2 in order to create a continue effect.
-- eg: 32x64, 512x128, 256x1024, 64x64, etc..
local sprite = cc.Sprite:create("Images/pattern1.png", cc.rect(0,0,512,256))
ret:addChild(sprite, -1, kTagSprite1)
sprite:setPosition(cc.p(size.width/2,size.height/2))
sprite:getTexture():setTexParameters(gl.LINEAR, gl.LINEAR, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE)
local rotate = cc.RotateBy:create(4, 360)
sprite:runAction(rotate)
local scale = cc.ScaleBy:create(2, 0.04)
local scaleBack = scale:reverse()
local seq = cc.Sequence:create(scale, scaleBack)
sprite:runAction(seq)
local function onNodeEvent(event)
if event == "exit" then
cc.Director:getInstance():getTextureCache():removeUnusedTextures()
end
end
ret:registerScriptHandler(onNodeEvent)
return ret
end
--------------------------------------------------------------------
--
-- TextureGlRepeat
--
--------------------------------------------------------------------
local function TextureGlRepeat()
local ret = createTestLayer("Texture gl.REPEAT")
local size = cc.Director:getInstance():getWinSize()
-- The .png image MUST be power of 2 in order to create a continue effect.
-- eg: 32x64, 512x128, 256x1024, 64x64, etc..
local sprite = cc.Sprite:create("Images/pattern1.png", cc.rect(0, 0, 4096, 4096))
ret:addChild(sprite, -1, kTagSprite1)
sprite:setPosition(cc.p(size.width/2,size.height/2))
sprite:getTexture():setTexParameters(gl.LINEAR, gl.LINEAR, gl.REPEAT, gl.REPEAT)
local rotate = cc.RotateBy:create(4, 360)
sprite:runAction(rotate)
local scale = cc.ScaleBy:create(2, 0.04)
local scaleBack = scale:reverse()
local seq = cc.Sequence:create(scale, scaleBack)
sprite:runAction(seq)
local function onNodeEvent(event)
if event == "exit" then
cc.Director:getInstance():getTextureCache():removeUnusedTextures()
end
end
ret:registerScriptHandler(onNodeEvent)
return ret
end
--------------------------------------------------------------------
--
-- TextureSizeTest
--
--------------------------------------------------------------------
local function TextureSizeTest()
local ret = createTestLayer("Different Texture Sizes",
"512x512, 1024x1024. See the console.")
local sprite = nil
cclog("Loading 512x512 image...")
sprite = cc.Sprite:create("Images/texture512x512.png")
if sprite ~= nil then
cclog("OK\n")
else
cclog("Error\n")
cclog("Loading 1024x1024 image...")
sprite = cc.Sprite:create("Images/texture1024x1024.png")
if sprite ~= nil then
cclog("OK\n")
else
cclog("Error\n")
-- @todo
-- cclog("Loading 2048x2048 image...")
-- sprite = cc.Sprite:create("Images/texture2048x2048.png")
-- if( sprite )
-- cclog("OK\n")
-- else
-- cclog("Error\n")
--
-- cclog("Loading 4096x4096 image...")
-- sprite = cc.Sprite:create("Images/texture4096x4096.png")
-- if( sprite )
-- cclog("OK\n")
-- else
-- cclog("Error\n")
end
end
return ret
end
--------------------------------------------------------------------
--
-- TextureCache1
--
--------------------------------------------------------------------
local function TextureCache1()
local ret = createTestLayer("TextureCache: remove",
"4 images should appear: alias, antialias, alias, antialias")
local s = cc.Director:getInstance():getWinSize()
local sprite = nil
sprite = cc.Sprite:create("Images/grossinis_sister1.png")
sprite:setPosition(cc.p(s.width/5*1, s.height/2))
sprite:getTexture():setAliasTexParameters()
sprite:setScale(2)
ret:addChild(sprite)
cc.Director:getInstance():getTextureCache():removeTexture(sprite:getTexture())
sprite = cc.Sprite:create("Images/grossinis_sister1.png")
sprite:setPosition(cc.p(s.width/5*2, s.height/2))
sprite:getTexture():setAntiAliasTexParameters()
sprite:setScale(2)
ret:addChild(sprite)
-- 2nd set of sprites
sprite = cc.Sprite:create("Images/grossinis_sister2.png")
sprite:setPosition(cc.p(s.width/5*3, s.height/2))
sprite:getTexture():setAliasTexParameters()
sprite:setScale(2)
ret:addChild(sprite)
cc.Director:getInstance():getTextureCache():removeTextureForKey("Images/grossinis_sister2.png")
sprite = cc.Sprite:create("Images/grossinis_sister2.png")
sprite:setPosition(cc.p(s.width/5*4, s.height/2))
sprite:getTexture():setAntiAliasTexParameters()
sprite:setScale(2)
ret:addChild(sprite)
return ret
end
-- TextureDrawAtPoint
local function TextureDrawAtPoint()
local m_pTex1 = nil
local m_pTex2F = nil
local ret = createTestLayer("Texture2D: drawAtPoint",
"draws 2 textures using drawAtPoint")
local function draw(transform, transformUpdated)
local director = cc.Director:getInstance()
assert(nil ~= director, "Director is null when setting matrix stack")
director:pushMatrix(cc.MATRIX_STACK_TYPE.MODELVIEW)
director:loadMatrix(cc.MATRIX_STACK_TYPE.MODELVIEW, transform)
local s = cc.Director:getInstance():getWinSize()
m_pTex1:drawAtPoint(cc.p(s.width/2-50, s.height/2 - 50))
m_pTex2F:drawAtPoint(cc.p(s.width/2+50, s.height/2 - 50))
director:popMatrix(cc.MATRIX_STACK_TYPE.MODELVIEW)
end
m_pTex1 = cc.Director:getInstance():getTextureCache():addImage("Images/grossinis_sister1.png")
m_pTex2F = cc.Director:getInstance():getTextureCache():addImage("Images/grossinis_sister2.png")
m_pTex1:retain()
m_pTex2F:retain()
local glNode = gl.glNodeCreate()
glNode:setContentSize(cc.size(256, 256))
glNode:setAnchorPoint(cc.p(0, 0))
glNode:registerScriptDrawHandler(draw)
ret:addChild(glNode)
local function onNodeEvent(event)
if event == "exit" then
m_pTex1:release()
m_pTex2F:release()
end
end
ret:registerScriptHandler(onNodeEvent)
return ret
end
-- TextureDrawInRect
local function TextureDrawInRect()
local m_pTex1 = nil
local m_pTex2F = nil
local ret = createTestLayer("Texture2D: drawInRect",
"draws 2 textures using drawInRect")
local function draw(transform, transformUpdated)
local director = cc.Director:getInstance()
assert(nullptr ~= director, "Director is null when setting matrix stack")
director:pushMatrix(cc.MATRIX_STACK_TYPE.MODELVIEW)
director:loadMatrix(cc.MATRIX_STACK_TYPE.MODELVIEW, transform)
local s = cc.Director:getInstance():getWinSize()
local rect1 = cc.rect( s.width/2 - 80, 20, m_pTex1:getContentSize().width * 0.5, m_pTex1:getContentSize().height *2 )
local rect2 = cc.rect( s.width/2 + 80, s.height/2, m_pTex1:getContentSize().width * 2, m_pTex1:getContentSize().height * 0.5 )
m_pTex1:drawInRect(rect1)
m_pTex2F:drawInRect(rect2)
end
m_pTex1 = cc.Director:getInstance():getTextureCache():addImage("Images/grossinis_sister1.png")
m_pTex2F = cc.Director:getInstance():getTextureCache():addImage("Images/grossinis_sister2.png")
m_pTex1:retain()
m_pTex2F:retain()
local glNode = gl.glNodeCreate()
glNode:setContentSize(cc.size(256, 256))
glNode:setAnchorPoint(cc.p(0, 0))
glNode:registerScriptDrawHandler(draw)
ret:addChild(glNode)
local function onNodeEvent(event)
if event == "exit" then
m_pTex1:release()
m_pTex2F:release()
end
end
ret:registerScriptHandler(onNodeEvent)
return ret
end
-- --------------------------------------------------------------------
-- --
-- TextureMemoryAlloc
--
--------------------------------------------------------------------
local function TextureMemoryAlloc()
local ret = createTestLayer("Texture memory",
"Testing Texture Memory allocation. Use Instruments + VM Tracker")
local m_pBackground = nil
cc.MenuItemFont:setFontSize(24)
local function updateImage(tag,sender)
if m_pBackground ~= nil then
cclog("updateImage"..tag)
m_pBackground:removeFromParent(true)
end
cc.Director:getInstance():getTextureCache():removeUnusedTextures()
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
local file = ""
if tag == 0 then
file = "Images/test_image.png"
elseif tag == 1 then
file = "Images/test_image_rgba8888.pvr"
elseif tag == 2 then
file = "Images/test_image_rgb888.pvr"
elseif tag == 3 then
file = "Images/test_image_rgba4444.pvr"
elseif tag == 4 then
file = "Images/test_image_a8.pvr"
end
m_pBackground = cc.Sprite:create(file)
ret:addChild(m_pBackground, -10)
m_pBackground:setVisible(false)
local s = cc.Director:getInstance():getWinSize()
m_pBackground:setPosition(cc.p(s.width/2, s.height/2))
end
local item1 = cc.MenuItemFont:create("PNG")
item1:registerScriptTapHandler(updateImage)
item1:setTag(0)
local item2 = cc.MenuItemFont:create("RGBA8")
item2:registerScriptTapHandler(updateImage)
item2:setTag(1)
local item3 = cc.MenuItemFont:create("RGB8")
item3:registerScriptTapHandler(updateImage)
item3:setTag(2)
local item4 = cc.MenuItemFont:create("RGBA4")
item4:registerScriptTapHandler(updateImage)
item4:setTag(3)
local item5 = cc.MenuItemFont:create("A8")
item5:registerScriptTapHandler(updateImage)
item5:setTag(4)
local menu = cc.Menu:create(item1, item2, item3, item4, item5)
menu:alignItemsHorizontally()
ret:addChild(menu)
local warmup = cc.MenuItemFont:create("warm up texture")
local function changeBackgroundVisible(tag, sender)
if m_pBackground ~= nil then
cclog("changeBackgroundVisible")
m_pBackground:setVisible(true)
end
end
warmup:registerScriptTapHandler(changeBackgroundVisible)
local menu2 = cc.Menu:create(warmup)
menu2:alignItemsHorizontally()
ret:addChild(menu2)
local s = cc.Director:getInstance():getWinSize()
menu2:setPosition(cc.p(s.width/2, s.height/4))
return ret
end
-- TexturePVRv3Premult
local function TexturePVRv3Premult()
local ret = createTestLayer("PVRv3 Premult Flag",
"All images should look exactly the same")
local function transformSprite(sprite)
local fade = cc.FadeOut:create(2)
local dl = cc.DelayTime:create(2)
local fadein = fade:reverse()
local seq = cc.Sequence:create(fade, fadein, dl)
local repeatAction = cc.RepeatForever:create(seq)
sprite:runAction(repeatAction)
end
local size = cc.Director:getInstance():getWinSize()
local background = cc.LayerColor:create(cc.c4b(128,128,128,255), size.width, size.height)
ret:addChild(background, -1)
-- PVR premultiplied
local pvr1 = cc.Sprite:create("Images/grossinis_sister1-testalpha_premult.pvr")
ret:addChild(pvr1, 0)
pvr1:setPosition(cc.p(size.width/4*1, size.height/2))
transformSprite(pvr1)
-- PVR non-premultiplied
local pvr2 = cc.Sprite:create("Images/grossinis_sister1-testalpha_nopremult.pvr")
ret:addChild(pvr2, 0)
pvr2:setPosition(cc.p(size.width/4*2, size.height/2))
transformSprite(pvr2)
-- PNG
cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
cc.Director:getInstance():getTextureCache():removeTextureForKey("Images/grossinis_sister1-testalpha.png")
local png = cc.Sprite:create("Images/grossinis_sister1-testalpha.png")
ret:addChild(png, 0)
png:setPosition(cc.p(size.width/4*3, size.height/2))
transformSprite(png)
return ret
end
function Texture2dTestMain()
cclog("Texture2dTestMain")
Helper.index = 1
local scene = cc.Scene:create()
Helper.createFunctionTable = {
TextureMemoryAlloc,
TextureAlias,
TexturePVRMipMap,
TexturePVRMipMap2,
TexturePVRNonSquare,
TexturePVRNPOT4444,
TexturePVRNPOT8888,
TexturePVR,
TexturePVR2BPP,
TexturePVR2BPPv3,
TexturePVR4BPP,
TexturePVR4BPPv3,
TexturePVRII4BPPv3,
TexturePVRRGBA8888,
TexturePVRRGBA8888v3,
TexturePVRBGRA8888,
TexturePVRBGRA8888v3,
TexturePVRRGBA4444,
TexturePVRRGBA4444v3,
TexturePVRRGBA4444GZ,
TexturePVRRGBA4444CCZ,
TexturePVRRGBA5551,
TexturePVRRGBA5551v3,
TexturePVRRGB565,
TexturePVRRGB565v3,
TexturePVRRGB888,
TexturePVRRGB888v3,
TexturePVRA8,
TexturePVRA8v3,
TexturePVRI8,
TexturePVRI8v3,
TexturePVRAI88,
TexturePVRAI88v3,
TexturePVRv3Premult,
TexturePVRBadEncoding,
TexturePNG,
TextureJPEG,
TextureTIFF,
TextureWEBP,
TextureMipMap,
TexturePixelFormat,
TextureBlend,
TextureAsync,
TextureGlClamp,
TextureGlRepeat,
TextureSizeTest,
TextureCache1,
TextureDrawAtPoint,
TextureDrawInRect
}
Helper.index = 1
scene:addChild(TextureMemoryAlloc())
scene:addChild(CreateBackMenuItem())
return scene
end
|
lfs=require('lfs')
cmd = torch.CmdLine()
cmd:option('--name','frame_1', 'data file')
opt = cmd:parse(arg or {})
trainType='seg'
f=string.format('/home/jchen16/code/Tracking_System/code/RNN_data/%s.csv',opt.name)
local attr = lfs.attributes (f)
assert (type(attr) == "table")
local i=0
for line in io.lines(f) do
if i==0 then
COLS = #line:split(',')
end
i=i+1
end
ROWS=i;
SEQS=i/6;
local data=torch.Tensor(ROWS,COLS)
local k=0
for line in io.lines(f) do
local l=line:split(',')
k=k+1
for key, val in ipairs(l) do
data[k][key]=val
end
end
local outpath=string.format('/home/jchen16/code/Tracking_System/code/RNN_data/%s.t7',opt.name)
torch.save(outpath,data) |
-- This module implements an "instruction selection" pass over the
-- SSA IR and produces pseudo-instructions for register allocation
-- and code generation.
--
-- This uses a greed matching algorithm over the tree.
--
-- This generates an array of pseudo-instructions like this:
--
-- { { "load", "r1", 12, 2 } }
-- { "add", "r1", "r3" } }
--
-- The instructions available are:
-- * cmp
-- * mov
-- * mov64
-- * load
-- * add
-- * add-i
-- * sub
-- * sub-i
-- * mul
-- * mul-i
-- * div
-- * and
-- * and-i
-- * or
-- * or-i
-- * xor
-- * xor-i
-- * shl
-- * shl-i
-- * shr
-- * shr-i
-- * ntohs
-- * ntohl
-- * uint32
-- * cjmp
-- * jmp
-- * ret-true, ret-false
-- * nop (inserted by register allocation)
module(...,package.seeall)
local utils = require("pf.utils")
local verbose = os.getenv("PF_VERBOSE");
local negate_op = { ["="] = "!=", ["!="] = "=",
[">"] = "<=", ["<"] = ">=",
[">="] = "<", ["<="] = ">" }
-- this maps numeric operations that we handle in a generic way
-- because the instruction selection is very similar
local numop_map = { ["+"] = "add", ["-"] = "sub", ["*"] = "mul",
["*64"] = "mul", ["&"] = "and", ["|"] = "or",
["^"] = "xor" }
-- extract a number from an SSA IR label
function label_num(label)
return tonumber(string.match(label, "L(%d+)"))
end
-- Convert a block to a sequence of pseudo-instructions
--
-- Virtual registers are given names prefixed with "r" as in "r1".
-- SSA variables remain prefixed with "v"
local function select_block(block, new_register, instructions, next_label, jmp_map)
local this_label = block.label
local control = block.control
local bindings = block.bindings
local function emit(instr)
table.insert(instructions, instr)
end
-- emit a jmp, looking up the next block and replace the jump target if
-- the next block would immediately jmp anyway (via a return statement)
local function emit_jmp(target_label, condition)
-- if the target label is one that was deleted by the return processing
-- pass, then patch the jump up as appropriate
local jmp_entry = jmp_map[target_label]
if jmp_entry then
if condition then
emit({ "cjmp", condition, jmp_entry })
else
emit({ "jmp", jmp_entry })
end
return
end
if condition then
emit({ "cjmp", condition, label_num(target_label) })
else
emit({ "jmp", label_num(target_label) })
end
end
local function emit_cjmp(condition, target_label)
emit_jmp(target_label, condition)
end
local function emit_label()
local max = instructions.max_label
local num = label_num(this_label)
if num > max then
instructions.max_label = num
end
emit({ "label", num })
end
-- do instruction selection on an arithmetic expression
-- returns the destination register or immediate
local function select_arith(expr)
if type(expr) == "number" then
if expr > (2 ^ 31) - 1 then
tmp = new_register()
emit({ "mov64", tmp, expr})
return tmp
else
return expr
end
elseif type(expr) == "string" then
return expr
elseif expr[1] == "[]" then
local reg = new_register()
local reg2 = select_arith(expr[2])
emit({ "load", reg, reg2, expr[3] })
return reg
elseif numop_map[expr[1]] then
local reg2 = select_arith(expr[2])
local reg3 = select_arith(expr[3])
local op = numop_map[expr[1]]
local op_i = string.format("%s-i", op)
-- both arguments in registers
if type(reg2) ~= "number" and type(reg3) ~= "number" then
local tmp = new_register()
emit({ "mov", tmp, reg2 })
emit({ op, tmp, reg3 })
return tmp
-- cases with one or more immediate arguments
elseif type(reg2) == "number" then
local tmp3 = new_register()
-- if op is commutative, we can re-arrange to save registers
if op ~= "sub" then
emit({ "mov", tmp3, reg3 })
emit({ op_i, tmp3, reg2 })
return tmp3
else
local tmp2 = new_register()
emit({ "mov", tmp2, reg2 })
emit({ "mov", tmp3, reg3 })
emit({ op, tmp2, tmp3 })
return tmp2
end
elseif type(reg3) == "number" then
local tmp = new_register()
emit({ "mov", tmp, reg2 })
emit({ op_i, tmp, reg3 })
return tmp
end
elseif expr[1] == "/" then
local reg2 = select_arith(expr[2])
local rhs = expr[3]
local tmp = new_register()
if type(rhs) == "number" then
-- if dividing by a power of 2, do a shift
if rhs ~= 0 and bit.band(rhs, rhs-1) == 0 then
local imm = 0
rhs = bit.rshift(rhs, 1)
while rhs ~= 0 do
rhs = bit.rshift(rhs, 1)
imm = imm + 1
end
emit({ "mov", tmp, reg2 })
emit({ "shr-i", tmp, imm })
else
local tmp3 = new_register()
local reg3 = select_arith(expr[3])
emit({ "mov", tmp, reg2 })
emit({ "mov", tmp3, reg3 })
emit({ "div", tmp, tmp3 })
end
else
local reg3 = select_arith(expr[3])
emit({ "mov", tmp, reg2 })
emit({ "div", tmp, reg3 })
end
return tmp
elseif expr[1] == "<<" then
-- with immediate
if type(expr[2]) == "number" then
local reg3 = select_arith(expr[3])
local tmp = new_register()
local tmp2 = new_register()
emit({ "mov", tmp, reg3 })
emit({ "mov", tmp2, expr[2] })
emit({ "shl", tmp, tmp2 })
return tmp
elseif type(expr[3]) == "number" then
local reg2 = select_arith(expr[2])
local imm = expr[3]
local tmp = new_register()
emit({ "mov", tmp, reg2 })
emit({ "shl-i", tmp, imm })
return tmp
else
local reg2 = select_arith(expr[2])
local reg3 = select_arith(expr[3])
local tmp1 = new_register()
local tmp2 = new_register()
emit({ "mov", tmp1, reg2 })
emit({ "mov", tmp2, reg3 })
emit({ "shl", tmp1, tmp2 })
return tmp1
end
elseif expr[1] == ">>" then
-- with immediate
if type(expr[2]) == "number" then
local reg3 = select_arith(expr[3])
local tmp = new_register()
local tmp2 = new_register()
emit({ "mov", tmp, reg3 })
emit({ "mov", tmp2, expr[2] })
emit({ "shr", tmp, tmp2 })
return tmp
elseif type(expr[3]) == "number" then
local reg2 = select_arith(expr[2])
local imm = expr[3]
local tmp = new_register()
emit({ "mov", tmp, reg2 })
emit({ "shr-i", tmp, imm })
return tmp
else
local reg2 = select_arith(expr[2])
local reg3 = select_arith(expr[3])
local tmp1 = new_register()
local tmp2 = new_register()
emit({ "mov", tmp1, reg2 })
emit({ "mov", tmp2, reg3 })
emit({ "shr", tmp1, tmp2 })
return tmp1
end
elseif expr[1] == "ntohs" then
local reg = select_arith(expr[2])
local tmp = new_register()
emit({ "mov", tmp, reg })
emit({ "ntohs", tmp })
return tmp
elseif expr[1] == "ntohl" then
local reg = select_arith(expr[2])
local tmp = new_register()
emit({ "mov", tmp, reg })
emit({ "ntohl", tmp })
return tmp
elseif expr[1] == "uint32" then
local reg = select_arith(expr[2])
local tmp = new_register()
emit({ "mov", tmp, reg })
emit({ "uint32", tmp })
return tmp
else
error(string.format("NYI op %s", expr[1]))
end
end
local function select_bool(expr)
local reg1 = select_arith(expr[2])
local reg2 = select_arith(expr[3])
-- cmp can't have an immediate on the lhs, but sometimes unoptimized
-- pf expressions will have such a comparison which requires an extra
-- mov instruction
if type(reg1) == "number" then
local tmp = new_register()
emit({ "mov", tmp, reg1 })
reg1 = tmp
end
emit({ "cmp", reg1, reg2 })
end
local function select_bindings()
for _, binding in ipairs(bindings) do
local rhs = binding.value
local reg = select_arith(rhs)
emit({ "mov", binding.name, reg })
end
end
if control[1] == "return" then
local result = control[2]
-- For the first two branches, only record necessity of constructing the
-- label. The blocks are dropped since these returns can just be replaced
-- by directly jumping to the true or false return labels at the end
if result[1] == "false" then
emit_false = true
elseif result[1] == "true" then
emit_true = true
else
emit_label()
select_bindings()
select_bool(result)
emit({ "cjmp", result[1], "true-label" })
emit({ "jmp", "false-label" })
emit_true = true
emit_false = true
end
elseif control[1] == "if" then
local cond = control[2]
local then_label = control[3]
local else_label = control[4]
emit_label()
select_bindings()
select_bool(cond)
if next_label == then_label then
emit_cjmp(negate_op[cond[1]], else_label)
emit_jmp(then_label)
else
emit_cjmp(cond[1], then_label)
emit_jmp(else_label)
end
else
error(string.format("NYI op %s", control[1]))
end
end
local function make_new_register(reg_num)
return
function()
local new_var = string.format("r%d", reg_num)
reg_num = reg_num + 1
return new_var
end
end
-- printing instruction IR for debugging
function print_selection(ir)
utils.pp({ "instructions", ir })
end
-- removes blocks that just return constant true/false and return a new
-- SSA order (with returns removed), a map for redirecting jmps, and two
-- booleans indicating whether to produce true/false return code
local function process_returns(ssa)
-- these control whether to emit pseudo-instructions for doing
-- 'return true' or 'return false' at the very end.
-- (since they may not be needed if the result is always true or false)
local emit_true, emit_false = false, false
local return_map = {}
-- clone to ease testing without side effects
local order = utils.dup(ssa.order)
local blocks = ssa.blocks
local len = #order
-- proceed in reverse order to allow easy deletion
for i=1, len do
local idx = len - i + 1
local label = order[idx]
local block = blocks[label]
local control = block.control
if control[1] == "return" then
if control[2][1] == "true" then
emit_true = true
return_map[label] = "true-label"
table.remove(order, idx)
elseif control[2][1] == "false" then
emit_false = true
return_map[label] = "false-label"
table.remove(order, idx)
else
-- a return block with a non-trivial expression requires both
-- true and false return labels
emit_true = true
emit_false = true
end
end
end
return order, return_map, emit_true, emit_false
end
function select(ssa)
local blocks = ssa.blocks
local instructions = { max_label = 0 }
local reg_num = 1
local new_register = make_new_register(reg_num)
local order, jmp_map, emit_true, emit_false = process_returns(ssa)
for idx, label in pairs(order) do
local next_label = order[idx+1]
select_block(blocks[label], new_register, instructions,
next_label, jmp_map)
end
if emit_false then
table.insert(instructions, { "ret-false" })
end
if emit_true then
table.insert(instructions, { "ret-true" })
end
if verbose then
print_selection(instructions)
end
return instructions
end
function selftest()
local utils = require("pf.utils")
-- test on a whole set of blocks
local function test(block, expected)
local instructions = select(block)
utils.assert_equals(instructions, expected)
end
test(-- `arp`
{ start = "L1",
order = { "L1", "L4", "L5" },
blocks =
{ L1 = { label = "L1",
bindings = {},
control = { "if", { ">=", "len", 14}, "L4", "L5" } },
L4 = { label = "L4",
bindings = {},
control = { "return", { "=", { "[]", 12, 2}, 1544 } } },
L5 = { label = "L5",
bindings = {},
control = { "return", { "false" } } } } },
{ { "label", 1 },
{ "cmp", "len", 14 },
{ "cjmp", "<", "false-label"},
{ "jmp", 4 },
{ "label", 4 },
{ "load", "r1", 12, 2 },
{ "cmp", "r1", 1544 },
{ "cjmp", "=", "true-label" },
{ "jmp", "false-label" },
{ "ret-false" },
{ "ret-true" },
max_label = 4 })
test(-- `tcp`
{ start = "L1",
order = { "L1", "L4", "L6", "L7", "L8", "L10", "L12", "L13",
"L14", "L16", "L17", "L15", "L11", "L9", "L5" },
blocks =
{ L1 = { label = "L1",
bindings = {},
control = { "if", { ">=", "len", 34 }, "L4", "L5" } },
L4 = { label = "L4",
bindings = { { name = "v1", value = { "[]", 12, 2 } } },
control = { "if", { "=", "v1", 8 }, "L6", "L7" },
idom = "L1" },
L6 = { label = "L6",
bindings = {},
control = { "return", { "=", { "[]", 23, 1 }, 6 } },
idom = "L4" },
L7 = { label = "L7",
bindings = {},
control = { "if", { ">=", "len", 54 }, "L8", "L9" },
idom = "L7" },
L8 = { label = "L8",
bindings = {},
control = { "if", { "=", "v1", 56710 }, "L10", "L11" },
idom = "L7" },
L10 = { label = "L10",
bindings = { { name = "v2", value = { "[]", 20, 1 } } },
control = { "if", { "=", "v2", 6 }, "L12", "L13" },
idom = "L9" },
L12 = { label = "L12",
bindings = {},
control = { "return", { "true" } },
idom = "L10" },
L13 = { label = "L13",
bindings = {},
control = { "if", { ">=", "len", 55 }, "L14", "L15" } },
L14 = { label = "L14",
bindings = {},
control = { "if", { "=", "v2", 44 }, "L16", "L17" } },
L16 = { label = "L16",
bindings = {},
control = { "return", { "=", { "[]", 54, 1 }, 6 } } },
L17 = { label = "L17",
bindings = {},
control = { "return", { "false" } } },
L15 = { label = "L15",
bindings = {},
control = { "return", { "false" } } },
L11 = { label = "L11",
bindings = {},
control = { "return", { "false" } } },
L9 = { label = "L9",
bindings = {},
control = { "return", { "false" } } },
L5 = { label = "L5",
bindings = {},
control = { "return", { "false" } } } } },
{ { "label", 1 },
{ "cmp", "len", 34 },
{ "cjmp", "<", "false-label" },
{ "jmp", 4 },
{ "label", 4 },
{ "load", "r1", 12, 2 },
{ "mov", "v1", "r1" },
{ "cmp", "v1", 8 },
{ "cjmp", "!=", 7 },
{ "jmp", 6 },
{ "label", 6 },
{ "load", "r2", 23, 1 },
{ "cmp", "r2", 6 },
{ "cjmp", "=", "true-label" },
{ "jmp", "false-label" },
{ "label", 7 },
{ "cmp", "len", 54 },
{ "cjmp", "<", "false-label" },
{ "jmp", 8 },
{ "label", 8 },
{ "cmp", "v1", 56710 },
{ "cjmp", "!=", "false-label" },
{ "jmp", 10 },
{ "label", 10 },
{ "load", "r3", 20, 1 },
{ "mov", "v2", "r3" },
{ "cmp", "v2", 6 },
{ "cjmp", "=", "true-label" },
{ "jmp", 13 },
{ "label", 13 },
{ "cmp", "len", 55 },
{ "cjmp", "<", "false-label" },
{ "jmp", 14 },
{ "label", 14 },
{ "cmp", "v2", 44 },
{ "cjmp", "!=", "false-label" },
{ "jmp", 16 },
{ "label", 16 },
{ "load", "r4", 54, 1 },
{ "cmp", "r4", 6 },
{ "cjmp", "=", "true-label" },
{ "jmp", "false-label" },
{ "ret-false" },
{ "ret-true" },
max_label = 16 })
test(-- randomly generated by tests
{ start = "L1",
order = { "L1", "L4", "L5" },
blocks =
{ L1 = { control = { "if", { ">=", "len", 4 }, "L4", "L5" },
bindings = {},
label = "L1", },
L4 = { control = { "return",
{ ">", { "ntohs", { "[]", 0, 4 } }, 0 } },
bindings = {},
label = "L4", },
L5 = { control = { "return", { "false" } },
bindings = {},
label = "L5", } } },
{ { "label", 1 },
{ "cmp", "len", 4 },
{ "cjmp", "<", "false-label" },
{ "jmp", 4 },
{ "label", 4 },
{ "load", "r1", 0, 4 },
{ "mov", "r2", "r1" },
{ "ntohs", "r2" },
{ "cmp", "r2", 0 },
{ "cjmp", ">", "true-label" },
{ "jmp", "false-label" },
{ "ret-false" },
{ "ret-true" },
max_label = 4 })
end
|
---------------------------------------------------------------------------------------------------
-- func: setmusic <typeID> <songID>
-- desc: Temporarily changes music played by users client
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "ii"
}
function error(player, msg)
player:PrintToPlayer(msg)
player:PrintToPlayer("!setmusic <type ID> <song ID>")
player:PrintToPlayer("type IDs: 0 = BGM (Day), 1 = BGM (Night), 2 = Solo-Battle, 3 = Party-Battle, 4 = Chocobo")
end
function onTrigger(player, typeId, songId)
-- validate typeId
if (typeId == nil or typeId < 0 or typeId > 4) then
error(player, "Invalid type ID.")
return
end
-- validate songId
if (songId == nil or songId < 0) then
error(player, "Invalid song ID.")
return
end
-- change music
player:ChangeMusic(typeId, songId)
end
|
include( 'shared.lua' )
ENT.RenderGroup = RENDERGROUP_TRANSLUCENT
function ENT:Initialize()
self.Entity:SetRenderMode( RENDERMODE_TRANSALPHA )
end
function ENT:Think()
self.Entity:SetRenderBoundsWS( self.Entity:GetEndPos( ), self.Entity:GetPos( ) )
end
ENT.Laser = Material( "sprites/bluelaser1" )
ENT.Light = Material( "effects/blueflare1" )
--[[function ENT:Draw()
end]]
function ENT:Draw()
if self.Entity:GetEndPos() == Vector(0,0,0) then return end
local offset = CurTime() * 3
local distance = self.Entity:GetEndPos():Distance( self.Entity:GetPos() )
local size = math.Rand( 2, 4 )
local normal = ( self.Entity:GetPos() - self.Entity:GetEndPos() ):GetNormal() * 0.1
render.SetMaterial( self.Laser )
render.DrawBeam( self.Entity:GetEndPos(), self.Entity:GetPos(), 2, offset, offset + distance / 8, Color( 50, 255, 50, 100 ) )
render.DrawBeam( self.Entity:GetEndPos(), self.Entity:GetPos(), 1, offset, offset + distance / 8, Color( 50, 255, 50, 100 ) )
render.SetMaterial( self.Light )
render.DrawQuadEasy( self.Entity:GetEndPos() + normal, normal, size, size, Color( 50, 255, 50, 100 ), 0 )
render.DrawQuadEasy( self.Entity:GetPos(), normal * -1, size, size, Color( 50, 255, 50, 100 ), 0 )
end
|
local LuaMidi = require ('LuaMidi')
local Track = LuaMidi.Track
local NoteEvent = LuaMidi.NoteEvent
local Writer = LuaMidi.Writer
local track = Track.new("C Major Scale")
track:set_text("Major scale from C3 to C4.")
track:set_instrument_name("Default")
local notes = {'C3', 'D3', 'E3', 'F3', 'G3', 'A3', 'B3', 'C4'}
track:add_events(NoteEvent.new({pitch = notes, sequential = true}))
local writer = Writer.new(track)
writer:save_MIDI('c_major_scale', 'midi files')
|
server = nil
service = nil
cPcall = nil
Pcall = nil
Routine = nil
GetEnv = nil
logError = nil
--// Commands
--// Highly recommended you disable Intellesense before editing this...
return function(Vargs, GetEnv)
local env = GetEnv(nil, {script = script})
setfenv(1, env)
local server = Vargs.Server
local service = Vargs.Service
local Settings = server.Settings
local Functions, Commands, Admin, Anti, Core, HTTP, Logs, Remote, Process, Variables, Deps
local function Init()
Functions = server.Functions;
Admin = server.Admin;
Anti = server.Anti;
Core = server.Core;
HTTP = server.HTTP;
Logs = server.Logs;
Remote = server.Remote;
Process = server.Process;
Variables = server.Variables;
Commands = server.Commands;
Deps = server.Deps;
--// Automatic New Command Caching and Ability to do server.Commands[":ff"]
setmetatable(Commands, {
__index = function(self, ind)
local targInd = Admin.CommandCache[string.lower(ind)]
if targInd then
return rawget(Commands, targInd)
end
end;
__newindex = function(self, ind, val)
rawset(Commands, ind, val)
if val and type(val) == "table" and val.Commands and val.Prefix then
for i, cmd in pairs(val.Commands) do
Admin.PrefixCache[val.Prefix] = true
Admin.CommandCache[string.lower((val.Prefix..cmd))] = ind
end
end
end;
})
Logs:AddLog("Script", "Loading Command Modules...")
--// Load command modules
if server.CommandModules then
local env = GetEnv()
for i, module in ipairs(server.CommandModules:GetChildren()) do
local func = require(module)
local ran, tab = pcall(func, Vargs, env)
if ran and tab and type(tab) == "table" then
for ind, cmd in pairs(tab) do
Commands[ind] = cmd
end
Logs:AddLog("Script", "Loaded Command Module: ".. module.Name)
elseif not ran then
warn("CMDMODULE ".. module.Name .. " failed to load:")
warn(tostring(tab))
Logs:AddLog("Script", "Loading Command Module Failed: ".. module.Name)
end
end
end
--// Cache commands
Admin.CacheCommands()
Commands.Init = nil
Logs:AddLog("Script", "Commands Module Initialized")
end;
local function RunAfterPlugins()
--// Load custom user-supplied commands in settings.Commands
for ind, cmd in pairs(Settings.Commands or {}) do
if type(cmd) == "table" and cmd.Function then
setfenv(cmd.Function, getfenv())
Commands[ind] = cmd
end
end
--// Change command permissions based on settings
local Trim = service.Trim
for ind, cmd in pairs(Settings.Permissions or {}) do
local com, level = string.match(cmd, "^(.*):(.*)")
if com and level then
if string.find(level, ",") then
local newLevels = {}
for lvl in string.gmatch(level, "[^%s,]+") do
table.insert(newLevels, Trim(lvl))
end
Admin.SetPermission(com, newLevels)
else
Admin.SetPermission(com, level)
end
end
end
--// Update existing permissions to new levels
for i, cmd in pairs(Commands) do
if type(cmd) == "table" and cmd.AdminLevel then
local lvl = cmd.AdminLevel
if type(lvl) == "string" then
cmd.AdminLevel = Admin.StringToComLevel(lvl)
--print("Changed " .. tostring(lvl) .. " to " .. tostring(cmd.AdminLevel))
elseif type(lvl) == "table" then
for b, v in pairs(lvl) do
lvl[b] = Admin.StringToComLevel(v)
end
elseif type(lvl) == "nil" then
cmd.AdminLevel = 0
end
if not cmd.Prefix then
cmd.Prefix = Settings.Prefix
end
if not cmd.Args then
cmd.Args = {}
end
if not cmd.Function then
cmd.Function = function(plr)
Remote.MakeGui(plr, "Output", {Message = "No command implementation"})
end
end
if cmd.ListUpdater then
Logs.ListUpdaters[i] = function(plr, ...)
if not plr or Admin.CheckComLevel(Admin.GetLevel(plr), cmd.AdminLevel) then
if type(cmd.ListUpdater) == "function" then
return cmd.ListUpdater(plr, ...)
end
return Logs[cmd.ListUpdater]
end
end
end
end
end
Commands.RunAfterPlugins = nil
end;
server.Commands = {
Init = Init;
RunAfterPlugins = RunAfterPlugins;
};
end
|
local fn = vim.fn
local cmd = vim.cmd
local exec = vim.api.nvim_exec
-- Auto save files when focus is lost
-- cmd "au FocusLost * silent! :wa!"
cmd "au TextYankPost * silent! lua require'vim.highlight'.on_yank({timeout = 800})"
--cmd "au BufEnter * set fo-=c fo-=r fo-=o"
cmd "au TermOpen * setlocal signcolumn=no nonumber norelativenumber"
cmd "au BufNewFile,BufRead .eslintignore,.prettierignore,.aliases setf conf"
cmd "au BufNewFile,BufRead .eslintrc,.prettierrc,tsconfig.json setf json"
-- cmd "au BufWritePost * FormatWrite"
cmd "au BufWritePre * lua vim.lsp.buf.formatting()"
cmd "au BufWritePost * normal! zv"
cmd "au FileType gitcommit inoremap <buffer>jj <ESC>ZZ"
cmd "au FileType gitcommit setl spell"
--cmd "au FileType html,css,scss,javascript,javascriptreact,vue,typescript,typescriptreact EmmetInstall"
cmd "au BufEnter *.txt lua require('settings.utils').help_tab()"
-- Open image file in system preview
cmd [[au BufEnter *.png,*.jpg,*.gif,*.ico exec "silent !open ".expand("%") | :bw"]]
-- cmd [[au BufEnter *.png,*.jpg,*gif exec "! kitty +kitten icat ".expand("%") | :bw]]
-- Return to last edited line
cmd [[au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") && &filetype != 'gitcommit' | exe "normal! g'\"" | endif]]
cmd "au CmdlineLeave : echo ''"
cmd "au BufRead,BufNewFile *.md setlocal textwidth=80"
cmd "au BufNewFile *.sh 0r ~/.config/nvim/templates/skeleton.sh"
cmd "au FileType markdown set wrap"
cmd "au FileType yaml setlocal ts=2 sts=2 sw=2 expandtab"
cmd "command! LSPReload lua reload_lsp()"
cmd "command! LSPDebug lua print(vim.inspect(vim.lsp.get_active_clients()))"
cmd "command! LSPLog lua open_lsp_log()"
-- Startuptime
exec(
[[
if has('vim_starting') && has('reltime')
let g:startuptime = reltime()
augroup vimrc-startuptime
autocmd!
autocmd VimEnter * echomsg 'startuptime:' . reltimestr(reltime(g:startuptime))
augroup END
endif
]],
""
)
exec(
[[
augroup journal
autocmd!
" populate journal template
autocmd BufNewFile */diary/** 0r ~/.config/nvim/templates/journal.skeleton
" set header for the particular journal
autocmd BufNewFile */diary/** :call SetJournalMode()
" other configurations
autocmd VimEnter */diary/** set ft=markdown
autocmd VimEnter */diary/** syntax off
autocmd VimEnter */diary/** setlocal nonumber norelativenumber
augroup end
]], ""
)
exec(
[[
augroup numbertoggle
autocmd!
autocmd BufEnter,FocusGained,InsertLeave,WinEnter * if &nu | set rnu | endif
autocmd BufLeave,FocusLost,InsertEnter,WinLeave * if &nu | set nornu | endif
augroup END
]],
""
)
|
include "./vendor/premake/premake_customization/solution_items.lua"
include "Dependencies.lua"
workspace "Honey"
architecture "x86_64"
startproject "Honeynut"
configurations
{
"Debug",
"Release",
"Dist"
}
solution_items
{
".editorconfig"
}
flags
{
"MultiProcessorCompile"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
group "Dependencies"
include "vendor/premake"
include "Honey/vendor/GLFW"
include "Honey/vendor/Glad"
include "Honey/vendor/imgui"
include "Honey/vendor/yaml-cpp"
group ""
include "Honey"
include "Sandbox"
include "Honeynut"
|
local item, super = Class(Item, "light/ball_of_junk")
function item:init(inventory)
super:init(self)
-- Display name
self.name = "Ball of Junk"
-- Item type (item, key, weapon, armor)
self.type = "item"
-- Whether this item is for the light world
self.light = true
-- Light world check text
self.check = "A small ball\nof accumulated things in your\npocket."
-- Where this item can be used (world, battle, all, or none)
self.usable_in = "all"
-- Item this item will get turned into when consumed
self.result_item = nil
-- Ball of Junk inventory
self.inventory = inventory or DarkInventory()
end
function item:onWorldUse()
Game.world:showText("* You looked at the junk ball in\nadmiration.[wait:5]\n* Nothing happened.")
return false
end
function item:onToss()
Game.world:startCutscene(function(cutscene)
if Game.chapter == 1 then
cutscene:text("* You really didn't want to throw\nit away.")
else
cutscene:text("* You took it from your pocket.[wait:5]\n"..
"* You have a [color:yellow]very,[wait:5] very,[wait:5] bad\n"..
"feeling[color:reset] about throwing it away.")
end
cutscene:text("* Throw it away anyway?")
local dropped
if Game.chapter == 1 then
dropped = cutscene:choicer({"No", "Yes"}) == 2
else
dropped = cutscene:choicer({"Yes", "No"}) == 1
end
if dropped then
Game.inventory:removeItem(self)
Assets.playSound("bageldefeat")
cutscene:text("* Hand shaking,[wait:5] you dropped the\nball of junk on the ground.")
cutscene:text("* It broke into pieces.")
cutscene:text("* You felt bitter.")
else
cutscene:text("* You felt a feeling of relief.")
end
end)
return false
end
function item:convertToDark(inventory)
for k,storage in pairs(self.inventory.storages) do
for i = 1, storage.max do
if storage[i] then
if not inventory:addItemTo(storage.id, i, storage[i]) then
inventory:addItem(storage[i])
end
end
end
end
return true
end
function item:onSave(data)
data.inventory = self.inventory:save()
end
function item:onLoad(data)
self.inventory = DarkInventory()
self.inventory:load(data.inventory)
end
return item |
require "specs.busted"
require "specs.Cocos2d-x"
require "lang.Signal"
require "Logger"
Log.setLevel(LogLevel.Error)
require "ad.Constants"
local shim = require("shim.System")
local AppShim = require("shim.App")
local Error = require("Error")
local BridgeCall = require("bridge.BridgeCall")
local BridgeResponse = require("bridge.BridgeResponse")
local MediationAdFactory = require("mediation.AdFactory")
local MediationAdConfig = require("mediation.AdConfig")
local Ad = require("ad.Ad")
local AdManager = require("ad.Manager")
local AdRegisterNetworkResponse = require("ad.response.AdRegisterNetworkResponse")
local AdRequest = require("ad.request.AdRequest")
local AdConfigureRequest = require("ad.request.AdConfigureRequest")
local AdRegisterNetworkRequest = require("ad.request.AdRegisterNetworkRequest")
local AdCompleteResponse = require("ad.response.AdCompleteResponse")
local AdCacheResponse = require("ad.response.AdCacheResponse")
local AdMobNetwork = require("ad.network.AdMobNetwork")
local AdColonyNetwork = require("ad.network.AdColonyNetwork")
local match = require("specs.matchers")
matchers_assert(assert)
function reload(pckg)
package.loaded[pckg] = nil
return require(pckg)
end
function Ad.init4(adNetwork, adType, zoneId, reward, adId)
local ad = Ad(adType, zoneId, reward)
ad.setAdNetwork(adNetwork)
return ad
end
describe("AdManager", function()
local subject
local config
local bridge
local adFactory
before_each(function()
mock(AppShim, true)
bridge = require("bridge.modules.ad")
adFactory = mock(MediationAdFactory({}), true)
subject = AdManager(bridge, adFactory)
end)
it("should set the ad factory", function()
assert.equal(adFactory, subject.getAdFactory())
end)
it("should not have an ad available", function()
assert.falsy(subject.isAdAvailable(AdType.Interstitial))
end)
it("should not have an error", function()
assert.falsy(subject.getError())
end)
context("when configuring the service", function()
local request
local ret
context("when successful", function()
before_each(function()
request = {}
stub(bridge, "configure", BridgeResponse(true))
ret = subject.configure(request)
end)
it("should have sent the message to configure", function()
assert.stub(bridge.configure).was.called_with(match.is_kind_of(AdConfigureRequest))
end)
it("should have returned true", function()
assert.truthy(ret)
end)
end)
context("when failure", function()
before_each(function()
request = {}
stub(bridge, "configure", BridgeResponse(false, nil, "An error"))
ret = subject.configure(request)
end)
it("should have sent the message to configure", function()
assert.stub(bridge.configure).was.called_with(match.is_kind_of(AdConfigureRequest))
end)
it("should have returned true", function()
assert.falsy(ret)
end)
it("should have set the error", function()
assert.equal("An error", subject.getError())
end)
end)
end)
context("when registering networks", function()
local adMob
local bannerAd
local interstitialAd
local success, _error
context("when the network is successfully registered", function()
before_each(function()
networks = reload("specs.Mediation-test")
adMob = networks[2]
bannerAd = adMob.getAds()[1]
interstitialAd = adMob.getAds()[2]
stub(bridge, "register", AdRegisterNetworkResponse(true, "100,200"))
stub(subject, "registerAd")
success, _error = subject.registerNetwork(adMob)
end)
it("should have returned a response", function()
assert.truthy(success)
assert.falsy(_error)
end)
it("should have registered all of the networks", function()
assert.stub(bridge.register).was.called_with(match.is_kind_of(AdRegisterNetworkRequest))
end)
it("should have associated ad IDs to respective ads", function()
assert.equals(100, bannerAd.getAdId())
assert.equals(200, interstitialAd.getAdId())
end)
it("should have registered all ads", function()
assert.stub(subject.registerAd).was.called_with(bannerAd)
assert.stub(subject.registerAd).was.called_with(interstitialAd)
end)
context("when hiding the banner ad", function()
context("when it succeeds", function()
before_each(function()
stub(bridge, "hideBannerAd", BridgeResponse(true))
success = subject.hideBannerAd()
end)
it("should return success w/ no error", function()
assert.truthy(success)
assert.falsy(subject.getError())
end)
it("should have made call to hide the ad", function()
assert.stub(bridge.hideBannerAd).was.called()
end)
end)
context("when it fails", function()
before_each(function()
stub(bridge, "hideBannerAd", BridgeResponse(false, nil, "Error"))
success = subject.hideBannerAd()
end)
it("should fail w/ error", function()
assert.falsy(success)
assert.equal("Error", subject.getError())
end)
it("should have made call to hide the ad", function()
assert.stub(bridge.hideBannerAd).was.called()
end)
end)
end)
end)
context("when the networks fails to be registered", function()
before_each(function()
networks = reload("specs.Mediation-test")
adMob = networks[2]
bannerAd = adMob.getAds()[1]
interstitialAd = adMob.getAds()[2]
stub(bridge, "register", AdRegisterNetworkResponse(false, nil, "Info"))
stub(subject, "registerAd")
success, _error = subject.registerNetwork(adMob)
end)
it("should return correct response", function()
assert.falsy(success)
assert.equals(Error, _error.getClass())
assert.equals(100, _error.getCode())
assert.equals("Failed to register network (AdMob)", _error.getMessage())
assert.equals("Info", _error.getInfo())
end)
it("should NOT have associated ad IDs to respective ads", function()
assert.falsy(bannerAd.getAdId())
assert.falsy(interstitialAd.getAdId())
end)
it("should have registered all ads", function()
assert.stub(subject.registerAd).was_not.called_with(bannerAd)
assert.stub(subject.registerAd).was_not.called_with(interstitialAd)
end)
end)
end)
context("registering more than one network at a time", function()
local adColony
local adMob
before_each(function()
networks = reload("specs.Mediation-test")
adColony = networks[1]
adMob = networks[2]
stub(subject, "registerNetwork")
subject.registerNetworks(networks)
end)
it("should have registered all networks", function()
assert.stub(subject.registerNetwork).was.called_with(adColony)
assert.stub(subject.registerNetwork).was.called_with(adMob)
end)
end)
-- @todo these tests exists only to hit the code that emits the log message.
-- In the future this could return a list of errors with the networks.
context("when registering more than one network and there is an error", function()
local adColony
local adMob
before_each(function()
networks = reload("specs.Mediation-test")
adColony = networks[1]
adMob = networks[2]
stub(subject, "registerNetwork", false, Error(100, "admanager_spec failure"))
subject.registerNetworks(networks)
end)
it("should have registered all networks", function()
assert.stub(subject.registerNetwork).was.called_with(adColony)
assert.stub(subject.registerNetwork).was.called_with(adMob)
end)
end)
describe("show nil ad request", function()
before_each(function()
subject.showAdRequest(nil)
end)
it("should have returned correct error", function()
assert.equal("Ad request is nil. This usually means the ad factory could not find an ad to serve.", subject.getError())
end)
end)
describe("show ad request", function()
context("when the request fails", function()
local responsei
local promisei
local showAdReturn
before_each(function()
responsei = BridgeResponse(false, nil, "ID (1): Ad is not registered")
promisei = BridgeCall()
stub(bridge, "show", responsei, promise)
local adRequest = AdRequest()
showAdReturn = subject.showAdRequest(adRequest)
end)
it("should return nil", function()
assert.falsy(showAdReturn)
end)
it("should set an error", function()
assert.equal(subject.getError(), "ID (1): Ad is not registered")
end)
end)
end)
describe("adding ad modules", function()
local requests
local adb
local adi
local requesti
local responsei
local promisei
local adv
local requestv
local responsev
local promisev
local leadbolt_ad
local leadbolt_response
local leadbolt_promise
before_each(function()
adb = Ad.init4(AdNetwork.AdMob, AdType.Banner, "banner-zone")
adi = Ad.init4(AdNetwork.AdMob, AdType.Interstitial, "interstitial-zone")
adv = Ad.init4(AdNetwork.AdColony, AdType.Video, "interstitial-zone")
leadbolt_ad = Ad.init4(AdNetwork.Leadbolt, AdType.Interstitial, nil)
responsei = BridgeResponse(true, 100)
responsev = BridgeResponse(true, 110)
leadbolt_response = BridgeResponse(true, 120)
function bridge.cache(request)
-- NOTE: The AdMob banner ad does not get cached.
if request.getAdNetwork() == AdNetwork.AdMob then
promisei = BridgeCall()
return responsei, promisei
elseif request.getAdNetwork() == AdNetwork.AdColony then
promisev = BridgeCall()
return responsev, promisev
elseif request.getAdNetwork() == AdNetwork.Leadbolt then
leadbolt_promise = BridgeCall()
return leadbolt_response, leadbolt_promise
else
assert.truthy(false)
end
end
subject.registerAd(adi)
subject.registerAd(adv)
subject.registerAd(adb)
requests = subject.getRequests()
end)
it("should have added the network module to list of registered modules", function()
local modules = subject.getRegisteredAds()
assert.equal(3, #modules)
assert.equal(adi, modules[1])
assert.equal(adv, modules[2])
assert.equal(adb, modules[3])
end)
it("should have created two requests, none for banner ad", function()
assert.equal(2, #requests)
end)
it("should have two requests waiting to be cached", function()
requesti = requests[1]
requestv = requests[2]
assert.equal(AdState.Loading, requesti.getState())
assert.equal(AdNetwork.AdMob, requesti.getAd().getAdNetwork())
assert.equal(AdState.Loading, requestv.getState())
assert.equal(AdNetwork.AdColony, requestv.getAd().getAdNetwork())
assert.truthy(promisei)
assert.truthy(promisev)
end)
it("should not have an available network module", function()
assert.falsy(subject.isAdAvailable(AdType.Interstitial))
assert.falsy(subject.isAdAvailable(AdType.Video))
end)
it("should NOT show the ad", function()
assert.falsy(subject.showAd(AdType.Interstitial))
assert.falsy(subject.showAd(AdType.Video))
end)
context("when the interstitial ad is cached successfully", function()
local requesti
local requestv
before_each(function()
requesti = requests[1]
requestv = requests[2]
promisei.resolve(AdCacheResponse(true, 100))
end)
it("should have an available interstitial", function()
assert.truthy(subject.isAdAvailable(AdType.Interstitial))
end)
it("should NOT have an available video", function()
assert.falsy(subject.isAdAvailable(AdType.Video))
end)
context("when there is no config", function()
before_each(function()
stub(adFactory, "nextAd", nil)
end)
describe("show the ad", function()
before_each(function()
local promise = BridgeCall()
stub(bridge, "show", responsei, promise)
assert.falsy(subject.showAd(AdType.Video))
assert.truthy(subject.showAd(AdType.Interstitial))
end)
it("should show an AdMob ad", function()
assert.equal(AdNetwork.AdMob, requesti.getAdNetwork())
end)
it("should show the interstitial ad", function()
assert.stub(bridge.show).was.called_with(requesti)
end)
it("should NOT have shown the video ad", function()
assert.stub(bridge.show).was_not.called_with(requestv)
end)
end)
end)
context("when AdMob is configured to be shown", function()
local config
before_each(function()
config = MediationAdConfig(AdNetwork.AdMob, AdType.Interstitial, AdImpressionType.Regular, 50, 5)
stub(adFactory, "nextAd", config)
end)
context("when showing the ad is successful", function()
before_each(function()
local promise = BridgeCall()
stub(bridge, "show", responsei, promise)
assert.truthy(subject.showAd(AdType.Interstitial))
end)
it("should have shown an AdMob ad", function()
assert.stub(bridge.show).was.called_with(requesti)
end)
end)
context("when showing the ad fails", function()
before_each(function()
local promise = BridgeCall()
stub(bridge, "show", BridgeResponse(false, 50), promise)
assert.falsy(subject.showAd(AdType.Interstitial))
end)
it("should have shown an AdMob ad", function()
assert.stub(bridge.show).was.called_with(requesti)
end)
end)
end)
context("when getting the AdMob next request", function()
local config
before_each(function()
local promise = BridgeCall()
stub(bridge, "show", responsei, promise)
config = MediationAdConfig(AdNetwork.AdMob, AdType.Interstitial, AdImpressionType.Regular, 50, 5)
stub(adFactory, "nextAd", config)
end)
it("should return the ad config", function()
local request, ad = subject.getNextAdRequest(AdType.Interstitial)
assert.equals(AdRequest, request.getClass())
assert.equals(config, ad)
end)
end)
context("when showing an ad type that is NOT registered", function()
local config
before_each(function()
local promise = BridgeCall()
stub(bridge, "show", responsei, promise)
config = MediationAdConfig(AdNetwork.Leadbolt, AdType.Interstitial, AdImpressionType.Regular, 50, 5)
stub(adFactory, "nextAd", config)
assert.truthy(subject.showAd(AdType.Interstitial))
end)
it("should show the next available ad type instead; AdMob", function()
assert.stub(bridge.show).was.called_with(requesti)
end)
end)
context("when showing an ad type that is registed", function()
local config
before_each(function()
config = MediationAdConfig(AdNetwork.Leadbolt, AdType.Interstitial, AdImpressionType.Regular, 50, 5)
stub(adFactory, "nextAd", config)
local promise = BridgeCall()
stub(bridge, "show", leadbolt_response, promise)
subject.registerAd(leadbolt_ad)
end)
context("when the ad has not yet been cached", function()
before_each(function()
assert.truthy(subject.showAd(AdType.Interstitial))
end)
it("should show the next available ad type instead; AdMob", function()
assert.stub(bridge.show).was.called_with(requesti)
end)
end)
context("when the ad fails to be cached", function()
before_each(function()
leadbolt_promise.resolve(BridgeResponse(false, 120, "Leadbolt error"))
assert.truthy(subject.showAd(AdType.Interstitial))
end)
it("should show the next available ad type instead; AdMob", function()
assert.stub(bridge.show).was.called_with(requesti)
end)
end)
end)
context("when getting the next AdRequest", function()
local config
local adConfig
before_each(function()
local promise = BridgeCall()
stub(bridge, "show", responsei, promise)
config = MediationAdConfig(AdNetwork.Leadbolt, AdType.Interstitial, AdImpressionType.Regular, 50, 5)
stub(adFactory, "nextAd", config)
adConfig = {}
stub(adFactory, "getConfigForAd", adConfig)
end)
it("should return an AdMob request and config", function()
local request, config = subject.getNextAdRequest(AdType.Interstitial)
assert.equal(AdNetwork.AdMob, request.getAdNetwork())
assert.equal(adConfig, config)
end)
end)
end)
context("when the interstitial ad fails to be cached", function()
local delayfn
local delayval
before_each(function()
function shim.DelayCall(fn, delay)
delayfn = fn
delayval = delay
end
spy.on(shim, "DelayCall")
requesti = requests[1]
promisei.reject(BridgeResponse(false, 100, "Cache failure"))
end)
it("should have completed the request", function()
local iad = requesti.getAd()
assert.equal(AdNetwork.AdMob, iad.getAdNetwork())
assert.equal(AdType.Interstitial, iad.getAdType())
assert.equal(AdState.Complete, requesti.getState())
end)
it("should have set the error", function()
assert.equal("Cache failure", subject.getError())
end)
it("should not be available", function()
assert.falsy(subject.isAdAvailable(AdType.Interstitial))
end)
it("should have scheduled the request to be performed at a later time", function()
assert.equals(30, delayval)
end)
describe("caching the module that failed", function()
before_each(function()
delayfn()
requests = subject.getRequests()
end)
it("should have rescheduled the module", function()
assert.equal(2, #requests)
end)
it("should have an interstitial pending", function()
local request = requests[2]
assert.equal(AdNetwork.AdMob, request.getAdNetwork())
assert.equal(AdType.Interstitial, request.getAdType())
assert.equal(AdState.Loading, request.getState())
end)
end)
end)
context("when the video ad is ready w/ a reward", function()
before_each(function()
requesti = requests[1]
requestv = requests[2]
promisev.resolve(AdCacheResponse(true, 110, 44))
end)
it("should have set the reward on the request", function()
assert.equal(44, requestv.getReward())
end)
end)
context("when the video ad is ready", function()
before_each(function()
requesti = requests[1]
requestv = requests[2]
promisev.resolve(AdCacheResponse(true, 110))
end)
it("should NOT have an available interstitial", function()
assert.falsy(subject.isAdAvailable(AdType.Interstitial))
end)
it("should have an available video", function()
assert.truthy(subject.isAdAvailable(AdType.Video))
end)
it("should not have set the reward, as none was given", function()
assert.falsy(requestv.getReward())
end)
context("when there is no config for the video", function()
describe("show the ad", function()
local promise
local ad_promise
local ad_clicked
local ad_reward
local ad_error
before_each(function()
ad_clicked = nil
ad_reward = nil
ad_error = nil
promise = BridgeCall()
stub(adFactor, nextAd, nil)
stub(bridge, "show", responsei, promise)
stub(shim, "DelayCall")
show_promise = subject.showAd(AdType.Video)
assert.truthy(show_promise) -- sanity
show_promise.done(function(clicked, reward)
ad_clicked = clicked
ad_reward = reward
end)
show_promise.fail(function(_error)
ad_error = _error
end)
end)
it("should not show interstitial, as it is not cached (sanity)", function()
assert.falsy(subject.showAd(AdType.Interstitial))
end)
it("should show the video ad", function()
assert.stub(bridge.show).was.called_with(requestv)
end)
it("should be presenting the request", function()
assert.equal(AdState.Presenting, requestv.getState())
end)
describe("when the ad completes successfully", function()
before_each(function()
stub(bridge, "cache", BridgeResponse(true, 100), BridgeCall())
promise.resolve(AdCompleteResponse(true, 1, 10, true))
end)
it("should have set the click and reward", function()
assert.truthy(ad_clicked)
assert.equal(10, ad_reward)
end)
it("should have updated the state of the ad request", function()
assert.equal(AdState.Complete, requestv.getState())
end)
it("should cache ad after short delay", function()
assert.stub(shim.DelayCall).was.called()
end)
end)
describe("when the request fails", function()
before_each(function()
promise.reject(AdCompleteResponse(false, 1, 0, false, "Failure"))
end)
it("should have updated the state of the ad request", function()
assert.equal(AdState.Complete, requestv.getState())
end)
it("should have an error", function()
assert.equal("Failure", subject.getError())
assert.equal("Failure", ad_error)
end)
it("should attempt to cache module", function()
assert.stub(shim.DelayCall).was.called()
end)
end)
end)
end)
end)
end)
end)
describe("AdManager when no ad factory", function()
local subject
local adFactory
local ad
local request
local promisec
local promises
local responsec -- 'c' for 'cache'
local responses -- 's' for 'show'
before_each(function()
promisec = BridgeCall()
promises = BridgeCall()
bridge = require("bridge.modules.ad")
function bridge.cache(request)
return responsec, promisec
end
function bridge.show(request)
return responses, promises
end
bridge = mock(bridge)
stub(shim, "DelayCall")
subject = AdManager(bridge)
ad = Ad.init4(AdNetwork.AdMob, AdType.Interstitial, "adid", 5)
end)
context("when the ad is cached successfully", function()
local request
before_each(function()
-- @note These vars are used in first before_each when bridge.* methods are called.
responsec = BridgeResponse(true, 50)
responses = BridgeResponse(true, 60)
subject.registerAd(ad)
request = subject.getRequests()[1]
promisec.resolve(AdCacheResponse(true, 50, 66))
end)
it("should have created a request", function()
local requests = subject.getRequests()
assert.equals(1, #requests) -- sanity
local request = requests[1]
assert.truthy(request) -- should have created a request
end)
it("should have set the reward", function()
assert.equal(66, request.getReward())
end)
it("should have cached the ad", function()
assert.spy(bridge.cache).was.called()
end)
it("should have displayed an AdMob interstitial ad", function()
assert.truthy(subject.showAd(AdType.Interstitial))
assert.spy(bridge.show).was.called_with(request)
end)
it("should return request and no ad", function()
local request, ad = subject.getNextAdRequest(AdType.Interstitial)
assert.equals(AdRequest, request.getClass())
assert.falsy(ad)
end)
it("should not return request or ad if the ad type is not registered", function()
local request, ad = subject.getNextAdRequest(AdType.Video)
assert.falsy(request)
assert.falsy(ad)
end)
end)
context("when the ad fails to be cached", function()
local request
before_each(function()
responsec = AdCacheResponse(false, 50, nil, "cache error")
responses = BridgeResponse(false, 60, "show error")
subject.registerAd(ad)
end)
it("should try to rebuild the requests after 30 seconds", function()
assert.stub(shim.DelayCall).was.called_with(match._, 30)
end)
it("should have added the request to tracked requests", function()
local requests = subject.getRequests()
assert.equals(1, #requests)
end)
it("should have completed the request immediately", function()
local requests = subject.getRequests()
local request = requests[1]
assert.equals(AdState.Complete, request.getState())
end)
it("should NOT allow AdMob interstitial ad to be displayed", function()
assert.falsy(subject.showAd(AdType.Interstitial))
end)
end)
end)
|
-- Copyright (c) 2019 StefanT <stt1@gmx.at>
-- See LICENSE.md in the project directory for license information.
--
-- Close the resource details dialog for a player.
--
-- @param player The player to close the dialog for
--
function close_resource_details_dialog(player)
local dialog = player.gui.screen[RESOURCE_DETAILS_DIALOG_NAME]
if dialog then
dialog.visible = false
end
end
--
-- Add the title bar to the dialog
--
-- @param dialog The dialog to add the titlebar
--
local function dialog_add_tilebar(dialog)
local titlebar = dialog.add{type = "flow", name = "flow_titlebar", direction = "horizontal"}
titlebar.drag_target = dialog
local title = titlebar.add{type = "label", style = "caption_label", caption = {"caption.resource-details"}}
title.drag_target = dialog
local handle = titlebar.add{type = "empty-widget", style = "draggable_space"}
handle.drag_target = dialog
handle.style.horizontally_stretchable = true
handle.style.top_margin = 2
handle.style.height = 24
handle.style.width = 120
local flow_buttonbar = titlebar.add{type = "flow", direction = "horizontal"}
flow_buttonbar.style.top_margin = 4
local closeButton = flow_buttonbar.add{type = "sprite-button", name = RESOURCE_DETAILS_CLOSE_NAME, style = "frame_action_button",
sprite = "utility/close_white", mouse_button_filter = {"left"}}
closeButton.style.left_margin = 2
end
--
-- Setup the table of the provider train stops
--
-- @param id The delivery ID of the resource
-- @param parent The parent GUI element
--
local function setup_table(id, parent)
local table = parent.add{type = "table", direction = "vertical", column_count = 4 }
local resource = global.resources[id]
if not resource then return end
local btnUp, btnDown, lbl
local first = true
for idx,stop in pairs(resource.stops) do
if stop.entity.valid then
table.add{type = "sprite", sprite = "item/train-stop"}
lbl = table.add{type = "label", caption = stop.entity.backer_name}
lbl.style.width = 200
if first then
first = false
table.add{type = "empty-widget"}
else
table.add{type = "sprite-button", sprite = "ctm-up", style = "ctm_small_button",
tooltip = {"tooltip.resource-priority-up"}, name = BTN_RESOURCE_UP_PREFIX..idx}
end
btnDown = table.add{type = "sprite-button", sprite = "ctm-down", style = "ctm_small_button",
tooltip = {"tooltip.resource-priority-down"}, name = BTN_RESOURCE_DOWN_PREFIX..idx}
end
end
if btnDown then
btnDown.destroy()
end
end
--
-- Open the resource details dialog for a player.
--
-- @param id The delivery ID of the resource
-- @param player The player to open the dialog for
--
function open_resource_details_dialog(id, player)
local dialog = player.gui.screen[RESOURCE_DETAILS_DIALOG_NAME]
if dialog then
dialog.destroy()
dialog = nil
end
if dialog == nil then
dialog = player.gui.screen.add{type = "frame", name = RESOURCE_DETAILS_DIALOG_NAME, direction = "vertical",
auto_center = true}
dialog.location = {200, 150}
dialog.style.minimal_height = 300;
dialog.style.maximal_height = 800;
dialog_add_tilebar(dialog)
dialog.add{type = "scroll-pane", horizontal_scroll_policy = "never", name = "pane" }
else
dialog["pane"].clear()
dialog.visible = true
end
setup_table(id, dialog["pane"])
global.dialogData[player.index] = { deliveryId = id }
end
--
-- Decrease the priority of a provider stop for providing the currently opened resource.
--
-- @param index The index of the resource
-- @param player The player
--
function resource_details_down(index, player)
local id = global.dialogData[player.index]["deliveryId"]
if not id then return end
local resource = global.resources[id]
if not resource or #resource.stops < index then return end
local stop = table.remove(resource.stops, index)
table.insert(resource.stops, index + 1, stop)
open_resource_details_dialog(id, player)
end
--
-- Increase the priority of a provider stop for providing the currently opened resource.
--
-- @param index The index of the resource
-- @param player The player
--
function resource_details_up(index, player)
local id = global.dialogData[player.index]["deliveryId"]
if not id then return end
local resource = global.resources[id]
if not resource or #resource.stops < index then return end
local stop = table.remove(resource.stops, index)
table.insert(resource.stops, index - 1, stop)
open_resource_details_dialog(id, player)
end
|
function isLaw (plr)
if (getTeamName(getPlayerTeam(plr)) == "Government") or (getTeamName(getPlayerTeam(plr)) == "Advanced Assault Forces") then
return true
else
return false
end
end
function cancelDamageForCops (attacker)
if (isElement(attacker)) and (isElement(source)) then
if (getElementType(attacker) == "player") and (getElementType(source) == "player") then
if (isLaw(source)) and (isLaw(attacker)) then
cancelEvent()
end
end
end
end
addEventHandler("onClientPlayerDamage", getLocalPlayer(), cancelDamageForCops) |
-- local utils = require 'utils'
-- local map = utils.map
local map = vim.api.nvim_set_keymap
local cmp = require "cmp"
local luasnip = require "luasnip"
-- BASE VIM KEYBINDINGS
local silent = { silent = true }
local silent_remap = { silent = true, noremap = false }
local expr = { expr = true }
local silent_expr = { silent = true, expr = true }
local has_words_before = function()
if vim.api.nvim_buf_get_option(0, "buftype") == "prompt" then
return false
end
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0
and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]
:sub(col, col)
:match "%s"
== nil
end
local feedkey = function(key)
vim.api.nvim_feedkeys(
vim.api.nvim_replace_termcodes(key, true, true, true),
"n",
true
)
end
local lspkind = require "lspkind"
cmp.setup {
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
completion = { completeopt = "menu,menuone,noinsert", autocomplete = false },
mapping = {
["<C-p>"] = cmp.mapping.select_prev_item(),
["<C-n>"] = cmp.mapping.select_next_item(),
["<C-d>"] = cmp.mapping.scroll_docs(-4),
["<C-f>"] = cmp.mapping.scroll_docs(4),
["<C-Space>"] = cmp.mapping.complete(),
["<C-e>"] = cmp.mapping.close(),
["<CR>"] = cmp.mapping.confirm {
behavior = cmp.ConfirmBehavior.Replace,
select = true,
},
["<Tab>"] = cmp.mapping(function(fallback)
if vim.fn.pumvisible() == 1 then
feedkey "<C-n>"
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
cmp.complete()
else
fallback()
end
end, {
"i",
"s",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if vim.fn.pumvisible() == 1 then
feedkey "<C-p>"
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
}),
},
sources = {
{ name = "luasnip" },
{ name = "nvim_lsp" },
{ name = "nvim_lua" },
{ name = "buffer" },
},
formatting = {
format = function(entry, vim_item)
-- fancy icons and a name of kind
vim_item.kind = require("lspkind").presets.default[vim_item.kind]
.. " "
.. vim_item.kind
-- set a name for each source
vim_item.menu = ({
buffer = "[Buffer]",
nvim_lsp = "[LSP]",
luasnip = "[LuaSnip]",
nvim_lua = "[Lua]",
latex_symbols = "[Latex]",
})[entry.source.name]
return vim_item
end,
},
}
-- -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore).
-- cmp.setup.cmdline("/", {
-- sources = {
-- { name = "buffer" },
-- },
-- })
-- -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore).
-- cmp.setup.cmdline(":", {
-- sources = cmp.config.sources({
-- { name = "path" },
-- }, {
-- { name = "cmdline" },
-- }),
-- })
|
rank = {
[1] = {'Admin I'},
[2] = {'Admin II'},
[3] = {'Admin III'},
[4] = {'Management'},
[5] = {'Developer'}
}
function getPlayerAdminLevel(player)
if player and isElement(player) then
level = getElementData(player, 'adminlevel')
return level
end
return false
end
function isPlayerAdmin(player)
if not player or not isElement(player) or not getElementType(player) == "player" then
return false
end
local adminLevel = getElementData(player, "adminlevel") or 0
return (tonumber(adminLevel) >= 1)
end
function isPlayerAdmin2(player)
if not player or not isElement(player) or not getElementType(player) == "player" then
return false
end
local adminLevel = getElementData(player, "adminlevel") or 0
return (tonumber(adminLevel) >= 2)
end
function isPlayerAdmin3(player)
if not player or not isElement(player) or not getElementType(player) == "player" then
return false
end
local adminLevel = getElementData(player, "adminlevel") or 0
return (tonumber(adminLevel) >= 3)
end
function isPlayerManagement(player)
if not player or not isElement(player) or not getElementType(player) == "player" then
return false
end
local adminLevel = getElementData(player, "adminlevel") or 0
return (tonumber(adminLevel) >= 4)
end
function isPlayerDeveloper(player)
if not player or not isElement(player) or not getElementType(player) == "player" then
return false
end
local adminLevel = getElementData(player, "adminlevel") or 0
return (tonumber(adminLevel) == 5)
end
function getPlayerAdminRankByID(player)
if player and isElement(player) then
level = getElementData(player, 'adminlevel')
return unpack(rank[tonumber(level)])
end
return false
end
function getAdminRankByID(id)
if tonumber(id) then
return unpack(rank[tonumber(id)])
end
return false
end
function isDutyOn(player)
if not player or not isElement(player) or not getElementType(player) == "player" then
return false
end
local dutyData = getElementData(player,'duty') or 0
return (tonumber(dutyData) == 1)
end |
require "dev.demo.net.BaseServer"
require "dev.demo.net.Protocol"
require "dev.demo.net.LoginServer"
require "dev.demo.net.GameServer"
require("json")
local NetManager = class("NetManager")
function NetManager.getInstance()
if not NetManager.s_instance then
NetManager.s_instance = NetManager.create()
end
return NetManager.s_instance
end
function NetManager.release()
end
function NetManager:ctor()
self.m_netServers = {}
LogicSys:regEventHandler(LogicEvent.EVENT_SERVER_CREATE, self.onEventServerCreate, self)
LogicSys:regEventHandler(LogicEvent.EVENT_SERVER_CLOSE, self.onEventServerClose, self)
if XG_USE_FAKE_SERVER then
XGFakeServer.getInstance()
end
end
function NetManager:dtor()
LogicSys:unregEventHandler(LogicEvent.EVENT_SERVER_CREATE, self.onEventServerCreate, self)
LogicSys:unregEventHandler(LogicEvent.EVENT_SERVER_CLOSE, self.onEventServerClose, self)
end
function NetManager:onNetEventHandler(nNetSocketId,nEventId, pEventArg)
if self.m_netServers[nNetSocketId] then
self.m_netServers[nNetSocketId]:onNetEventHandler(nEventId, pEventArg)
end
end
function NetManager:parseMsg(nNetSocketId,msgType,msgSize,msgData)
-- print("NetManager:parseMsg " )
if self.m_netServers[nNetSocketId] then
self.m_netServers[nNetSocketId]:parseMsg(msgType,msgSize,msgData)
end
-- print("NetManager:parseMsg end " )
end
function NetManager:sendMsgToCurServer(nNetSocketId,msgType,msgData)
--local ident = protobuf.pack("NFMsg.Ident svrid index",0,0)
--local pb = protobuf.pack("NFMsg.MsgBase player_id msg_data",ident,msgData)
if self.m_netServers[nNetSocketId] then
NativeCall.lcc_sendMsgToServer(self.m_nNetSocketId,msgType,msgData)
end
end
function NetManager:onEventServerCreate(nNetSocketId,server)
self.m_netServers[nNetSocketId] = server
end
function NetManager:onEventServerClose(nNetSocketId,server)
self.m_netServers[nNetSocketId] = nil
end
function NetManager:downloaderOnTaskProgress(identifier, bytesReceived, totalBytesReceived, totalBytesExpected)
LogicSys:onEvent(LogicEvent.EVENT_DOWNLOADER_ON_PROGRESS,identifier, bytesReceived, totalBytesReceived, totalBytesExpected)
end
function NetManager:downloaderOnDataTaskSuccess(identifier, pData,nSize)
LogicSys:onEvent(LogicEvent.EVENT_DOWNLOADER_ON_DATA_SUCCESS,identifier,pData,nSize)
end
function NetManager:downloaderOnFileTaskSuccess(identifier)
LogicSys:onEvent(LogicEvent.EVENT_DOWNLOADER_ON_FILE_SUCCESS,identifier)
end
function NetManager:downloaderOnTaskError(identifier, errorCode, errorCodeInternal,errorStr)
LogicSys:onEvent(LogicEvent.EVENT_DOWNLOADER_ON_ERROR,identifier,errorCode,errorCodeInternal,errorStr)
end
function NetManager:httpPost(url,data,obj,onResult,onError)
if XG_USE_FAKE_SERVER then
XGFakeServer.getInstance():httpPost(url,data,obj,onResult,onError)
return
end
local xhr = cc.XMLHttpRequest:new()
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON
xhr:open("POST", url)
local function onReadyStateChanged()
if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
local response = xhr.response
local output = json.decode(response,1)
if onResult then
onResult(obj,output)
end
else
onError(obj)
print("xhr.readyState is:", xhr.readyState, "xhr.status is: ",xhr.status)
end
xhr:unregisterScriptHandler()
xhr=nil
end
xhr:registerScriptHandler(onReadyStateChanged)
xhr:send(data)
end
return NetManager |
-- Valve like CLIENT/SERVER macros
CLIENT = Client and true
SERVER = Server and true
--[[
Check variable type
Arguments:
any var = The variable to be checked
Return:
bool
]]
function IsBasicTable(var) return type(var) == "table" and not getmetatable(var) end -- Pure Lua table type
function IsBool(var) return type(var) == "boolean" end
function IsColor(var) return getmetatable(var) == Color end
function IsFunction(var) return type(var) == "function" end
function IsNil(var) return var == nil end
function IsNumber(var) return type(var) == "number" end
function IsQuat(var) return getmetatable(var) == Quat end -- Quaternion
function IsRotator(var) return getmetatable(var) == Rotator end
function IsString(var) return type(var) == "string" end
function IsTable(var) return type(var) == "table" end -- All kinds of tables, even Vector() and Rotator()
function IsVector(var) return getmetatable(var) == Vector end
function IsVector2D(var) return getmetatable(var) == Vector2D end
function IsUserdata(var) return type(var) == "userdata" end
--[[
Iterate a table with all keys sorted alphabetically
Arguments:
table tab = The variable to be iterated
bool desc = Sort the order reversed (descending)
Return:
function iterator
]]
function SortedPairs(tab, desc)
local skeys = {}
for k, v in pairs(tab) do
if IsString(k) then
table.insert(skeys, k)
end
end
table.sort(skeys, function(a,b)
return (desc and a or b):lower() > (desc and b or a):lower()
end)
local k = 0
local sk = 0
return function()
k = k + 1
if tab[k] then
return k, tab[k]
end
sk = sk + 1
if skeys[sk] then
return skeys[sk], tab[skeys[sk]]
end
end
end
--[[
Change variable type to boolean
Arguments:
any var = The variable to be converted
Return:
bool
]]
function ToBool(var)
return var and var ~= "" and tonumber(var) ~= 0 and var ~= "false" and true or false
end
|
checkForImageCounter,reloadTimeout,loaded=0,300,false
image,imageRgb={},{}
y,A=0.544,0.48
mMin,sC,dL=math.min,screen.setColor,screen.drawLine
imageW,imageH=0,0
function onTick()
if not loaded then
loaded = true
async.httpGet(80, "/retrieveImage.php")
end
if input.getBool(1) and reloadTimeout==0 then
loaded,reloadTimeout = false,300
async.httpGet(80, "/retrieveImage.php")
elseif reloadTimeout>0 then reloadTimeout=reloadTimeout-1 end
end
function onDraw()
local sH,sW = screen.getHeight(),screen.getWidth()
local pX = sH * sW
if pX >= #imageRgb then
counter=0
for w=0,imageW do
for h=0,imageH do
counter=w*imageH+h+1
v=imageRgb[counter] or {0,0,0}
sC(v[1],v[2],v[3])
dL(w,h,w,h+1)
end
end
elseif #imageRgb>1 then
counter=0
for w=0,sW do
for h=0,sH do
counter=w*imageH+h+1
v=imageRgb[counter] or {0,0,0}
sC(v[1],v[2],v[3])
dL(w,h,w,h+1)
end
end
end
end
function httpReply(port, request_body, response_body)
image = split(response_body,',')
imageW,imageH = image[1],image[2]
table.remove(image,1)
table.remove(image,2)
imageUpdate()
end
function gameToLua(r,g,b)
r=mMin(A*r^y/255^y*r,255)
g=mMin(A*g^y/255^y*g,255)
b=mMin(A*b^y/255^y*b,255)
return r,g,b
end
function imageUpdate()
imageRgb = {}
for k,v in ipairs(image) do
val=tonumber(v,16)
r,g,b=val//65536,(val//256)%256,val%256
r,g,b=gameToLua(r,g,b)
table.insert(imageRgb,{r,g,b})
end
end
function split(str,sep)
if sep == nil then
sep = "%s"
end
local t={}
for str in string.gmatch(str, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end |
--[[
To counter AFK bots that never joins the game.
--]]
local TIMER = 600
-------
local safe = {}
game.Players.PlayerAdded:Connect(function(NewPly)
print("Beginning Security Check")
wait(TIMER)
if safe[NewPly] then
safe[NewPly] = nil
print("Security Check passed")
else
NewPly:Kick("Unauthorized Security Check")
end
end)
script.SecurityConfirm.Event:Connect(function(PlyrObj)
safe[PlyrObj] = true
print(PlyrObj.Name.. " has been Security Confirmed")
end)
|
return {'bis','bisam','bisambont','bisamrat','biscuit','biscuitblik','biscuitje','bisdom','biseks','biseksualiteit','biseksueel','bisjaar','bismillah','bismut','bisschop','bisschoppelijk','bisschoppenconferentie','bisschoppensynode','bisschopsambt','bisschopshoed','bisschopskeuze','bisschopsmijter','bisschopsring','bisschopsstad','bisschopsstaf','bisschopsstoel','bisschopssynode','bisschopstroon','bisschopswijding','bisschopswijn','bisschopszetel','bisschopwijn','bissectrice','bissen','bisser','bisseren','bisstudent','bister','bistro','bistrootjes','bisschopshuis','bisschopsbenoeming','bisjkek','bissau','bissegem','bisschops','bischoff','bisseling','bisselink','bissels','bish','bisoen','biskop','bisram','bis','bisamratten','biscuitblikken','biscuitjes','biscuits','bisdommen','biseksuele','biseksuelen','bisschoppelijke','bisschoppen','bisschopsmijters','bisschopsstaven','bisschopssteden','bisschopswijdingen','bissectrices','bistros','bistrootje','bisschopsringen','bisschopstronen','bisschopwijnen','bisseerde','bissers','bisstudenten','biste','bisschopswijnen','bisschoppenconferenties','bisschopszetels','bisschoppensynodes','bissegemse'} |
blackoutEnabled = true
-- 1800, 7200
local blackoutTime = math.floor(math.random(1800,7200)) -- 30 minutes - 120 minutes?
RegisterServerEvent("ActivatePower")
AddEventHandler("ActivatePower", function(name)
TriggerClientEvent("togglePower", -1, true)
blackoutEnabled = false
TriggerClientEvent("showNotification",-1,"~g~Power Grid Restored!~n~~s~Survivor ~o~"..name.."~s~ has successfully restored the power!")
end)
RegisterServerEvent("CutPower")
AddEventHandler("CutPower", function()
TriggerClientEvent("togglePower", -1, false)
blackoutEnabled = true
end)
RegisterServerEvent("disableRepairAction")
AddEventHandler("disableRepairAction", function(disable, station)
TriggerClientEvent("disableRepairAction", -1, disable, station)
end)
RegisterServerEvent("Z:newplayerID")
AddEventHandler("Z:newplayerID", function(id)
TriggerClientEvent("togglePower", id, not blackoutEnabled)
end)
Citizen.CreateThread(function()
while true do
Wait(1000)
if not blackoutEnabled then
blackoutTime = blackoutTime - 1
if blackoutTime <= 0 then
blackoutEnabled = true
blackoutTime = math.floor(math.random(1800,7200))
TriggerClientEvent("togglePower", -1, false)
TriggerClientEvent("showNotification",-1,"~r~Power generators have malfunctioned!~n~~s~Go repair them again to turn the power back on!")
end
end
end
end)
|
dofile('./load-db.lua')
local ids = {}
for i, v in pairs(CodexDB.units.data) do
if not v.coords or #v.coords == 0 then
table.insert(ids, i)
end
end
table.sort(ids)
print(table.concat(ids, "\n"))
|
-- ITS - In The Shadows
-- Copyright (C) 2015, 2016, 2017 James Niemira
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- James Niemira "urmane"
-- jim.niemira@gmail.com
load("/data/general/grids/basic.lua")
newEntity{
define_as = "TO_MARKET",
always_remember = true,
show_tooltip=true,
name="The entrance to the Bazaar",
display='>', color=colors.VIOLET,
-- image = "terrain/stair_up_wild.png",
notice = true,
change_level=2, change_zone="market",
}
newEntity{
define_as = "TO_CHURCH",
always_remember = true,
show_tooltip=true,
name="A dirt road to an abandoned church.",
display='>', color=colors.VIOLET,
-- image = "terrain/stair_up_wild.png",
notice = true,
change_level=1, change_zone="church",
}
newEntity{
define_as = "TO_ASYLUM",
always_remember = true,
show_tooltip=true,
name="A dark alley leading to the old asylum.",
display='>', color=colors.VIOLET,
-- image = "terrain/stair_up_wild.png",
notice = true,
change_level=1, change_zone="asylum",
}
newEntity{
define_as = "HOVEL",
name="A dark alley leading to the old asylum.",
display='#', color=colors.VIOLET,
image = "terrain/fixme.png",
notice = true,
always_remember = true,
does_block_move = true,
block_sight = true,
show_tooltip = true,
-- do this here?
gold = resolvers.rngavg(1,5),
on_block_bump = function(g, e) if e.player then
engine.ui.Dialog:yesnoPopup("Loot", "Loot this poor hovel?",
--function(ok) if ok then game.player:incGold(10) end end,
function(ok) if ok then
if g.gold > 0 then
game.player:incGold(g.gold or 0)
g.gold = 0
else
game.log("Nothing worthwhile here.")
end
end end,
"Loot!", "Cancel")
end end,
--on_block_bump_msg = "Loot this poor hovel?",
}
|
dofile('/home/raj/workspace/p4-traffictool/samples/netcache/output/wireshark/netcache_1_ipv4.lua')
dofile('/home/raj/workspace/p4-traffictool/samples/netcache/output/wireshark/netcache_2_tcp.lua')
dofile('/home/raj/workspace/p4-traffictool/samples/netcache/output/wireshark/netcache_3_udp.lua')
dofile('/home/raj/workspace/p4-traffictool/samples/netcache/output/wireshark/netcache_4_nc_hdr.lua')
dofile('/home/raj/workspace/p4-traffictool/samples/netcache/output/wireshark/netcache_5_nc_load.lua')
|
AddCSLuaFile()
AddCSLuaFile("sh_sounds.lua")
include("sh_sounds.lua")
SWEP.PrintName = "M14 EBR"
if CLIENT then
SWEP.DrawCrosshair = false
SWEP.CSMuzzleFlashes = true
SWEP.ViewModelMovementScale = 1.15
SWEP.IconLetter = "n"
killicon.AddFont("cw_g3a3", "CW_KillIcons", SWEP.IconLetter, Color(255, 80, 0, 150))
SWEP.MuzzleEffect = "muzzleflash_m14"
SWEP.PosBasedMuz = false
SWEP.SnapToGrip = true
SWEP.ShellScale = 0.7
SWEP.ShellOffsetMul = 1
SWEP.ShellPosOffset = {x = 4, y = 0, z = -3}
SWEP.ForeGripOffsetCycle_Draw = 0
SWEP.ForeGripOffsetCycle_Reload = 0.9
SWEP.ForeGripOffsetCycle_Reload_Empty = 0.8
SWEP.FireMoveMod = 0.6
SWEP.DrawTraditionalWorldModel = false
SWEP.WM = "models/weapons/w_cstm_m14.mdl"
SWEP.WMPos = Vector(0, -0.5, 1)
SWEP.WMAng = Vector(0, 0, 180)
SWEP.IronsightPos = Vector(-2.231, -3.428, 1.207)
SWEP.IronsightAng = Vector(0, -0.008, 0)
SWEP.NXSPos = Vector(-2.218, -3.388, 0.225)
SWEP.NXSAng = Vector(0, 0, 0)
SWEP.EoTechPos = Vector(-2.237, -4.617, 0.079)
SWEP.EoTechAng = Vector(0, -0.008, 0)
SWEP.AimpointPos = Vector(-2.24, -3.856, 0.144)
SWEP.AimpointAng = Vector(0, -0.008, 0)
SWEP.MicroT1Pos = Vector(-2.241, 0.5, 0.395)
SWEP.MicroT1Ang = Vector(0, -0.008, 0)
SWEP.ACOGPos = Vector(-2.231, -5, -0.12)
SWEP.ACOGAng = Vector(0, -0.008, 0)
SWEP.SG1Pos = Vector(-1.614, -0.861, -0.51)
SWEP.SG1Ang = Vector(0, 0, 0)
SWEP.ShortDotPos = Vector(-2.211, -4.624, 0.221)
SWEP.ShortDotAng = Vector(0, 0, 0)
SWEP.SprintPos = Vector(1.786, 0, -1)
SWEP.SprintAng = Vector(-10.778, 27.573, 0)
SWEP.BackupSights = {["md_acog"] = {[1] = Vector(-2.221, -4.617, -1.234), [2] = Vector(0, -0.008, 0)}}
SWEP.SightWithRail = true
SWEP.ACOGAxisAlign = {right = 0.35, up = 0, forward = 0}
SWEP.NXSAlign = {right = 0.35, up = 0, forward = 0}
SWEP.SchmidtShortDotAxisAlign = {right = 0.2, up = 0, forward = 0}
SWEP.AlternativePos = Vector(-0.319, 1.325, -1.04)
SWEP.AlternativeAng = Vector(0, 0, 0)
SWEP.M203OffsetCycle_Reload = 0.81
SWEP.M203OffsetCycle_Reload_Empty = 0.73
SWEP.M203OffsetCycle_Draw = 0
SWEP.M203CameraRotation = {p = -90, y = 0, r = -90}
SWEP.BaseArm = "Bip01 L Clavicle"
SWEP.BaseArmBoneOffset = Vector(-50, 0, 0)
SWEP.BoltBone = "M14_Charger"
SWEP.BoltShootOffset = Vector(-3, 0, 0)
SWEP.M203HoldPos = {
["Bip01 L Clavicle"] = {pos = Vector(4.461, 0.308, -2.166), angle = Angle(0, 0, 0)}
}
SWEP.AttachmentModelsVM = {
["md_aimpoint"] = {model = "models/wystan/attachments/aimpoint.mdl", bone = "M14_Body", pos = Vector(-0.253, -5.233, -4.358), angle = Angle(0, 0, 0), size = Vector(1, 1, 1), adjustment = {min = -5.233, max = -2.5, axis = "y", inverseOffsetCalc = true}},
["md_eotech"] = {model = "models/wystan/attachments/2otech557sight.mdl", bone = "M14_Body", pos = Vector(0.284, -9.179, -10.056), angle = Angle(3.332, -90, 0), size = Vector(1, 1, 1), adjustment = {min = -9.179, max = -6, axis = "y", inverseOffsetCalc = true}},
["md_microt1"] = {model = "models/cw2/attachments/microt1.mdl", bone = "M14_Body", pos = Vector(0.01, 0.93, 1.373), angle = Angle(0, 180, 0), size = Vector(0.4, 0.4, 0.4), adjustment = {min = 0.93, max = 4, axis = "y", inverseOffsetCalc = true}},
["md_saker"] = {model = "models/cw2/attachments/556suppressor.mdl", bone = "M14_Body", pos = Vector(0.039, 1.595, -1.653), angle = Angle(0, 0, 0), size = Vector(0.699, 0.699, 0.699)},
["md_anpeq15"] = {model = "models/cw2/attachments/anpeq15.mdl", bone = "M14_Body", pos = Vector(-0.173, 6.684, 1.22), angle = Angle(0, 90, 0), size = Vector(0.5, 0.5, 0.5)},
["md_acog"] = {model = "models/wystan/attachments/2cog.mdl", bone = "M14_Body", pos = Vector(-0.352, -3, -4.449), angle = Angle(0, 0, 0), size = Vector(1, 1, 1), adjustment = {min = -3, max = 0, axis = "y", inverseOffsetCalc = true}},
["md_foregrip"] = {model = "models/wystan/attachments/foregrip1.mdl", bone = "M14_Body", pos = Vector(-0.419, -5.74, -3.297), angle = Angle(0, 0, 0), size = Vector(0.75, 0.75, 0.75)},
["md_schmidt_shortdot"] = {model = "models/cw2/attachments/schmidt.mdl", bone = "M14_Body", pos = Vector(-0.322, -3.846, -3.984), angle = Angle(0, -90, 0), size = Vector(0.93, 0.93, 0.93)},
["md_nightforce_nxs"] = {model = "models/cw2/attachments/l96_scope.mdl", bone = "M14_Body", pos = Vector(-0.071, 2.74, 2.388), angle = Angle(0, -90, 0), size = Vector(1, 1, 1)}
}
SWEP.AttachmentPosDependency = {["md_anpeq15"] = {["bg_longris"] = Vector(-0.225, 13, 3.15)},
["md_saker"] = {["bg_longbarrel"] = Vector(-0.042, 9, -0.1), ["bg_longris"] = Vector(-0.042, 9, -0.1)}}
SWEP.LuaVMRecoilAxisMod = {vert = 1, hor = 1, roll = 1, forward = 0.5, pitch = 0.5}
SWEP.LaserPosAdjust = Vector(0.5, 0, 0)
SWEP.LaserAngAdjust = Angle(0, 180, 0)
end
SWEP.MuzzleVelocity = 853 -- in meter/s
SWEP.RailBGs = {main = 3, on = 1, off = 0}
SWEP.BipodBGs = {main = 4, on = 1, off = 0}
SWEP.SightBGs = {main = 2, sg1 = 1, none = 0}
SWEP.LuaViewmodelRecoil = true
SWEP.Attachments = {[1] = {header = "Sight", offset = {800, -300}, atts = {"md_microt1", "md_eotech", "md_aimpoint", "md_schmidt_shortdot", "md_acog", "md_nightforce_nxs"}},
[2] = {header = "Barrel", offset = {-450, -300}, atts = {"md_saker"}},
[3] = {header = "Rail", offset = {800, 100}, atts = {"md_anpeq15"}, dependencies = {md_microt1 = true, md_eotech = true, md_aimpoint = true, md_schmidt_shortdot = true, md_acog = true, md_nightforce_nxs = true}},
["+reload"] = {header = "Ammo", offset = {-450, 100}, atts = {"am_magnum", "am_matchgrade"}}}
SWEP.Animations = {fire = {"M14_Fire1", "M14_Fire2"},
reload = "M14_Reload",
idle = "idle",
draw = "M14_Deploy"}
SWEP.Sounds = {M14_Reload = {{time = 0.6, sound = "CW_FOLEY_LIGHT"},
{time = 0.8, sound = "CW_M14_MAGOUT"},
{time = 1.4, sound = "CW_FOLEY_LIGHT"},
{time = 2.1, sound = "CW_M14_MAGIN"},
{time = 2.7, sound = "CW_FOLEY_LIGHT"},
{time = 3.15, sound = "CW_M14_BOLT"}},
M14_Deploy = {{time = 0, sound = "CW_FOLEY_MEDIUM"},
{time = 0.7, sound = "CW_M14_BOLT"}}}
SWEP.SpeedDec = 40
SWEP.Slot = 3
SWEP.SlotPos = 0
SWEP.NormalHoldType = "ar2"
SWEP.RunHoldType = "passive"
SWEP.FireModes = {"auto", "semi"}
SWEP.Base = "cw_base"
SWEP.Category = "CW 2.0"
SWEP.Author = "Spy"
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.Instructions = ""
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/cw2/rifles/m14.mdl"
SWEP.WorldModel = "models/weapons/w_cstm_m14.mdl"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.Primary.ClipSize = 20
SWEP.Primary.DefaultClip = 20
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "7.62x51MM"
SWEP.FireDelay = 0.08
SWEP.FireSound = "CW_M14_FIRE"
SWEP.FireSoundSuppressed = "CW_M14_FIRE_SUPPRESSED"
SWEP.Recoil = 2.2
SWEP.HipSpread = 0.05
SWEP.AimSpread = 0.001
SWEP.VelocitySensitivity = 2.1
SWEP.MaxSpreadInc = 0.07
SWEP.SpreadPerShot = 0.01
SWEP.SpreadCooldown = 0.12
SWEP.Shots = 1
SWEP.Damage = 42
SWEP.DeployTime = 1.7
SWEP.RecoilToSpread = 0.8 -- the M14 in particular will have 30% more recoil from continuous fire to give a feeling of "oh fuck I should stop firing 7.62x51MM in full auto at 750 RPM"
SWEP.ReloadSpeed = 1
SWEP.ReloadTime = 2.5
SWEP.ReloadTime_Empty = 3.3
SWEP.ReloadHalt = 3.05
SWEP.ReloadHalt_Empty = 4.85
SWEP.SnapToIdlePostReload = true |
--- Example Module
-- This module contains an example to be documented with docl.
--- Add two numbers.
-- returns the sum of x and y.
function adder(x, y)
return x + y
end
|
object_building_mustafar_structures_must_bandit_fence_8m = object_building_mustafar_structures_shared_must_bandit_fence_8m:new {
}
ObjectTemplates:addTemplate(object_building_mustafar_structures_must_bandit_fence_8m, "object/building/mustafar/structures/must_bandit_fence_8m.iff")
|
local MP = minetest.get_modpath(minetest.get_current_modname())
local S, NS = dofile(MP.."/intllib.lua")
local alphabetize_items = crafting.config.sort_alphabetically
local show_guides = crafting.config.show_guides
local function refresh_output(inv, max_mode)
local craftable = crafting.get_craftable_items("table", inv:get_list("store"), max_mode, alphabetize_items)
inv:set_size("output", #craftable + ((8*6) - (#craftable%(8*6))))
inv:set_list("output", craftable)
end
local function make_formspec(row, item_count, max_mode)
if item_count < (8*6) then
row = 0
elseif (row*8)+(8*6) > item_count then
row = (item_count - (8*6)) / 8
end
local inventory = {
"size[10.2,10.2]"
, default.gui_bg
, default.gui_bg_img
, default.gui_slots
, "list[context;store;0,0.5;2,5;]"
, "list[context;output;2.2,0;8,6;" , tostring(row*8), "]"
, "list[current_player;main;1.1,6.25;8,1;]"
, "list[current_player;main;1.1,7.5;8,3;8]"
, "listring[context;output]"
, "listring[current_player;main]"
, "listring[context;store]"
, "listring[current_player;main]"
}
local pages = false
local page_button_y = "7.3"
if item_count > ((row/6)+1) * (8*6) then
inventory[#inventory+1] = "button[9.3,"..page_button_y..";1,0.75;next;»]"
inventory[#inventory+1] = "tooltip[next;"..S("Next page of crafting products").."]"
page_button_y = "8.0"
pages = true
end
if row >= 6 then
inventory[#inventory+1] = "button[9.3,"..page_button_y..";1,0.75;prev;«]"
inventory[#inventory+1] = "tooltip[prev;"..S("Previous page of crafting products").."]"
pages = true
end
if pages then
inventory[#inventory+1] = "label[9.3,6.5;" .. S("Page @1", tostring(row/6+1)) .. "]"
end
if max_mode then
inventory[#inventory+1] = "button[9.3,8.7;1,0.75;max_mode;Max\nOutput]"
else
inventory[#inventory+1] = "button[9.3,8.7;1,0.75;max_mode;Min\nOutput]"
end
if show_guides then
inventory[#inventory+1] = "button[9.3,9.7;1,0.75;show_guide;Show\nGuide]"
end
return table.concat(inventory), row
end
local function refresh_inv(meta)
local inv = meta:get_inventory()
local max_mode = meta:get_string("max_mode")
refresh_output(inv, max_mode == "True")
local page = meta:get_int("page")
local form, page = make_formspec(page, inv:get_size("output"), max_mode == "True")
meta:set_int("page", page)
meta:set_string("formspec", form)
end
local function take_craft(inv, target_inv, target_list, stack, player)
local craft_result = crafting.get_crafting_result("table", inv:get_list("store"), stack)
if craft_result then
if crafting.remove_items(inv, "store", craft_result.input) then
-- We've successfully paid for this craft's output.
local item_name = stack:get_name()
-- log it
minetest.log("action", S("@1 crafts @2", player:get_player_name(), item_name .. " " .. tostring(craft_result.output[item_name])))
-- subtract the amount of output that the player's getting anyway (from having taken it)
craft_result.output[item_name] = craft_result.output[item_name] - stack:get_count()
-- stuff the output in the target inventory, or the player's inventory if it doesn't fit, finally dropping anything that doesn't fit at the player's location
local leftover = crafting.add_items(target_inv, target_list, craft_result.output)
leftover = crafting.add_items(player:get_inventory(), "main", leftover)
crafting.drop_items(player:getpos(), leftover)
-- Put returns into the store first, or player's inventory if it doesn't fit, or drop it at player's location as final fallback
leftover = crafting.add_items(inv, "store", craft_result.returns)
leftover = crafting.add_items(player:get_inventory(), "main", leftover)
crafting.drop_items(player:getpos(), leftover)
end
end
end
minetest.register_node("crafting:table", {
description = S("Crafting Table"),
drawtype = "normal",
tiles = {"crafting.table_top.png", "default_chest_top.png",
"crafting.table_front.png", "crafting.table_front.png",
"crafting.table_side.png", "crafting.table_side.png"},
sounds = default.node_sound_wood_defaults(),
paramtype2 = "facedir",
is_ground_content = false,
groups = {oddly_breakable_by_hand = 1, choppy=3},
on_construct = function(pos)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
inv:set_size("store", 2*5)
inv:set_size("output", 8*6)
meta:set_int("row", 0)
meta:set_string("formspec", make_formspec(0, 0, true))
end,
allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, number, player)
if to_list == "output" then
return 0
end
return number
end,
allow_metadata_inventory_put = function(pos, list_name, index, stack, player)
if list_name == "output" then
return 0
end
return stack:get_count()
end,
on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, number, player)
local meta = minetest.get_meta(pos)
if from_list == "output" and to_list == "store" then
local inv = meta:get_inventory()
local stack = inv:get_stack(to_list, to_index)
take_craft(inv, inv, to_list, stack, player)
end
refresh_inv(meta)
end,
on_metadata_inventory_take = function(pos, list_name, index, stack, player)
local meta = minetest.get_meta(pos)
if list_name == "output" then
local inv = meta:get_inventory()
take_craft(inv, player:get_inventory(), "main", stack, player)
end
refresh_inv(meta)
end,
on_metadata_inventory_put = function(pos, list_name, index, stack, player)
local meta = minetest.get_meta(pos)
refresh_inv(meta)
end,
on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local size = inv:get_size("output")
local row = meta:get_int("row")
local max_mode = meta:get_string("max_mode")
local refresh = false
if fields.next then
minetest.sound_play("paperflip1", {to_player=sender:get_player_name(), gain = 1.0})
row = row + 6
elseif fields.prev then
minetest.sound_play("paperflip1", {to_player=sender:get_player_name(), gain = 1.0})
row = row - 6
elseif fields.max_mode then
if max_mode == "" then
max_mode = "True"
else
max_mode = ""
end
refresh = true
elseif fields.show_guide and show_guides then
crafting.show_crafting_guide("table", sender)
else
return
end
if refresh then
refresh_output(inv, max_mode == "True")
end
meta:set_string("max_mode", max_mode)
local form, row = make_formspec(row, size, max_mode == "True")
meta:set_int("row", row)
meta:set_string("formspec", form)
end,
can_dig = function(pos, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:is_empty("store")
end,
})
----------------------------------------------------------
-- Crafting
local table_recipe = {
output = "crafting:table",
recipe = {
{"group:tree","group:tree",""},
{"group:tree","group:tree",""},
{"","",""},
},
}
minetest.register_craft(table_recipe)
----------------------------------------------------------
-- Guide
if crafting.config.show_guides then
minetest.register_craftitem("crafting:table_guide", {
description = S("Crafting Guide (Table)"),
inventory_image = "crafting_guide_cover.png^[colorize:#0088ff88^crafting_guide_contents.png",
wield_image = "crafting_guide_cover.png^[colorize:#0088ff88^crafting_guide_contents.png",
stack_max = 1,
groups = {book = 1},
on_use = function(itemstack, user)
crafting.show_crafting_guide("table", user)
end,
})
if minetest.get_modpath("default") then
minetest.register_craft({
output = "crafting:table_guide",
type = "shapeless",
recipe = {"crafting:table", "default:book"},
replacements = {{"crafting:table", "crafting:table"}}
})
end
end
----------------------------------------------------------------
-- Hopper compatibility
if minetest.get_modpath("hopper") and hopper ~= nil and hopper.add_container ~= nil then
hopper:add_container({
{"top", "crafting:table", "store"},
{"bottom", "crafting:table", "store"},
{"side", "crafting:table", "store"},
})
end |
local S = mobs.intllib
-- Dirt Monster by PilzAdam
mobs:register_mob(":mobs:dirt_monster", {
type = "monster",
passive = false,
attack_type = "dogfight",
pathfinding = true,
reach = 2,
damage = 2,
hp_min = 3,
hp_max = 27,
armor = 100,
collisionbox = {-0.4, -1, -0.4, 0.4, 0.8, 0.4},
visual = "mesh",
mesh = "mobs_stone_monster.b3d",
textures = {
{"mobs_dirt_monster.png"},
},
blood_texture = "default_dirt.png",
makes_footstep_sound = true,
sounds = {
random = "mobs_dirtmonster",
},
view_range = 15,
walk_velocity = 1,
run_velocity = 3,
jump = true,
drops = {
{name = "default:dirt", chance = 1, min = 3, max = 5},
},
water_damage = 1,
lava_damage = 5,
light_damage = 3,
fear_height = 4,
animation = {
speed_normal = 15,
speed_run = 15,
stand_start = 0,
stand_end = 14,
walk_start = 15,
walk_end = 38,
run_start = 40,
run_end = 63,
punch_start = 40,
punch_end = 63,
},
})
local spawn_on = "default:dirt_with_grass"
if minetest.get_modpath("ethereal") then
spawn_on = "ethereal:gray_dirt"
end
mobs:spawn({
name = "mobs:dirt_monster",
nodes = {spawn_on},
min_light = 0,
max_light = 7,
chance = 7000,
active_object_count = 2,
min_height = 0,
day_toggle = false,
})
--mobs:register_egg("mobs:dirt_monster", S("Dirt Monster"), "default_dirt.png", 1)
if core.global_exists("asm") then
asm.addEgg({
name = "dirt_monster",
title = S("Dirt Monster"),
inventory_image = "default_dirt.png",
spawn = "mobs:dirt_monster",
ingredients = "default:dirt",
})
end
core.register_alias("mobs:dirt_monster", "spawneggs:dirt_monster")
mobs:alias_mob("mobs_monster:dirt_monster", "mobs:dirt_monster") -- compatibility
|
-----------------------------------
-- Area: Phomiuna Aqueducts
-- NPCqm2 (???)
-- Notes: Open south door @ F-7
-- !pos -75.329 -24.636 92.512 27
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local DoorOffset = npc:getID() - 2;
if (GetNPCByID(DoorOffset):getAnimation() == 9) then
GetNPCByID(DoorOffset):openDoor(7) -- _0rf
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
help(
[[
This module loads Ant 1.9.4 into the environment. Ant is a java
based build system.
]])
whatis("Loads the Ant build system into the environment")
local version = "1.9.4"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/ant/"..version
prepend_path("PATH", pathJoin(base, "bin"))
pushenv('ANT_HOME', base)
family('ant')
|
local CorePackages = game:GetService("CorePackages")
local CoreGui = game:GetService("CoreGui")
local Roact = require(CorePackages.Roact)
local RoactRodux = require(CorePackages.RoactRodux)
local t = require(CorePackages.Packages.t)
local Components = script.Parent.Parent
local TopBar = Components.Parent
local SetBackpackOpen = require(TopBar.Actions.SetBackpackOpen)
local SetEmotesOpen = require(TopBar.Actions.SetEmotesOpen)
local SetLeaderboardOpen = require(TopBar.Actions.SetLeaderboardOpen)
local SetEmotesEnabled = require(TopBar.Actions.SetEmotesEnabled)
local EventConnection = require(TopBar.Parent.Common.EventConnection)
local RobloxGui = CoreGui:WaitForChild("RobloxGui")
local BackpackModule = require(RobloxGui.Modules.BackpackScript)
local EmotesMenuMaster = require(RobloxGui.Modules.EmotesMenu.EmotesMenuMaster)
local PlayerListMaster = require(RobloxGui.Modules.PlayerList.PlayerListManager)
local OpenUIConnector = Roact.PureComponent:extend("OpenUIConnector")
OpenUIConnector.validateProps = t.strictInterface({
setBackpackOpen = t.callback,
setEmotesOpen = t.callback,
setLeaderboardOpen = t.callback,
setEmotesEnabled = t.callback,
})
function OpenUIConnector:didMount()
self.props.setLeaderboardOpen(PlayerListMaster:GetSetVisible())
self.props.setBackpackOpen(BackpackModule.IsOpen)
self.props.setEmotesOpen(EmotesMenuMaster:isOpen())
self.props.setEmotesEnabled(EmotesMenuMaster.MenuIsVisible)
end
function OpenUIConnector:render()
local leaderboardEvent = PlayerListMaster:GetSetVisibleChangedEvent()
return Roact.createFragment({
LeaderboardOpenChangedConnection = Roact.createElement(EventConnection, {
event = leaderboardEvent.Event,
callback = function(open)
self.props.setLeaderboardOpen(open)
end,
}),
BackpackOpenChangedConnection = Roact.createElement(EventConnection, {
event = BackpackModule.StateChanged.Event,
callback = function(open)
self.props.setBackpackOpen(open)
end,
}),
EmotesOpenChangedConnection = Roact.createElement(EventConnection, {
event = EmotesMenuMaster.EmotesMenuToggled.Event,
callback = function(open)
self.props.setEmotesOpen(open)
end,
}),
EmotesEnabledChangedConnection = Roact.createElement(EventConnection, {
event = EmotesMenuMaster.MenuVisibilityChanged.Event,
callback = function(enabled)
self.props.setEmotesEnabled(enabled)
end,
}),
})
end
local function mapDispatchToProps(dispatch)
return {
setBackpackOpen = function(open)
return dispatch(SetBackpackOpen(open))
end,
setEmotesOpen = function(open)
return dispatch(SetEmotesOpen(open))
end,
setLeaderboardOpen = function(open)
return dispatch(SetLeaderboardOpen(open))
end,
setEmotesEnabled = function(enabled)
return dispatch(SetEmotesEnabled(enabled))
end,
}
end
return RoactRodux.UNSTABLE_connect2(nil, mapDispatchToProps)(OpenUIConnector) |
local f = io.open("include/leveldb/c.h", "rb")
local s = f:read "*a"
f:close()
local names = {}
for name in s:gmatch("\nLEVELDB_EXPORT%s+[%w _*]+%s+([%w_]+)%s*%(") do
names[#names + 1] = name
end
table.sort(names)
f = io.open("leveldb.def", "wb")
f:write("EXPORTS\r\n")
f:write("JNI_OnLoad\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1backup\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1close\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1compact\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1get\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1iter_1delete\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1iter_1new\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1iter_1next\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1iter_1prev\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1iter_1value\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1open\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1open2\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1open3\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1property\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1write\r\n")
f:write("Java_jane_core_StorageLevelDB_leveldb_1write_1direct\r\n")
for _, name in ipairs(names) do
-- f:write(name, "\r\n")
end
f:close()
print "done!"
|
local Root = script.Parent.Parent
local Players = game:GetService("Players")
local Promise = require(Root.Promise)
local Thunk = require(Root.Thunk)
local PurchaseError = require(Root.Enums.PurchaseError)
local RequestSubscriptionPurchase = require(Root.Actions.RequestSubscriptionPurchase)
local ErrorOccurred = require(Root.Actions.ErrorOccurred)
local getProductInfo = require(Root.Network.getProductInfo)
local getIsAlreadyOwned = require(Root.Network.getIsAlreadyOwned)
local getAccountInfo = require(Root.Network.getAccountInfo)
local Network = require(Root.Services.Network)
local ExternalSettings = require(Root.Services.ExternalSettings)
local hasPendingRequest = require(Root.Utils.hasPendingRequest)
local resolveSubscriptionPromptState = require(Root.Thunks.resolveSubscriptionPromptState)
local GetFFlagDeveloperSubscriptionsEnabled = require(Root.Flags.GetFFlagDeveloperSubscriptionsEnabled)
local requiredServices = {
Network,
ExternalSettings,
}
local function initiateSubscriptionPurchase(id)
return Thunk.new(script.Name, requiredServices, function(store, services)
local network = services[Network]
local externalSettings = services[ExternalSettings]
if not GetFFlagDeveloperSubscriptionsEnabled() or hasPendingRequest(store:getState()) then
return nil
end
store:dispatch(RequestSubscriptionPurchase(id))
local isStudio = externalSettings.isStudio()
if not isStudio and Players.LocalPlayer.UserId <= 0 then
store:dispatch(ErrorOccurred(PurchaseError.Guest))
return nil
end
if externalSettings.getFlagOrder66() then
store:dispatch(ErrorOccurred(PurchaseError.PurchaseDisabled))
return nil
end
return Promise.all({
productInfo = getProductInfo(network, id, Enum.InfoType.Subscription),
accountInfo = getAccountInfo(network, externalSettings),
alreadyOwned = getIsAlreadyOwned(network, id, Enum.InfoType.Subscription),
})
:andThen(function(results)
store:dispatch(resolveSubscriptionPromptState(
results.productInfo,
results.accountInfo,
results.alreadyOwned
))
end)
:catch(function(errorReason)
store:dispatch(ErrorOccurred(errorReason))
end)
end)
end
return initiateSubscriptionPurchase |
require "helpers"
local tables = {}
-- Rows with any of the following keys will be treated as possible infrastructure
local infrastructure_keys = {
'aeroway',
'amenity',
'emergency',
'highway',
'man_made',
'power',
'utility'
}
local is_infrastructure = make_check_in_list_func(infrastructure_keys)
tables.infrastructure_point = osm2pgsql.define_table({
name = 'infrastructure_point',
schema = schema_name,
ids = { type = 'node', id_column = 'osm_id' },
columns = {
{ column = 'osm_type', type = 'text', not_null = true },
{ column = 'osm_subtype', type = 'text'},
{ column = 'name', type = 'text' },
{ column = 'ele', type = 'int' },
{ column = 'height', sql_type = 'numeric'},
{ column = 'operator', type = 'text'},
{ column = 'material', type = 'text'},
{ column = 'geom', type = 'point' , projection = srid},
}
})
tables.infrastructure_line = osm2pgsql.define_table({
name = 'infrastructure_line',
schema = schema_name,
ids = { type = 'way', id_column = 'osm_id' },
columns = {
{ column = 'osm_type', type = 'text', not_null = true },
{ column = 'osm_subtype', type = 'text'},
{ column = 'name', type = 'text' },
{ column = 'ele', type = 'int' },
{ column = 'height', sql_type = 'numeric'},
{ column = 'operator', type = 'text'},
{ column = 'material', type = 'text'},
{ column = 'geom', type = 'linestring' , projection = srid},
}
})
tables.infrastructure_polygon = osm2pgsql.define_table({
name = 'infrastructure_polygon',
schema = schema_name,
ids = { type = 'way', id_column = 'osm_id' },
columns = {
{ column = 'osm_type', type = 'text', not_null = true },
{ column = 'osm_subtype', type = 'text'},
{ column = 'name', type = 'text' },
{ column = 'ele', type = 'int' },
{ column = 'height', sql_type = 'numeric'},
{ column = 'operator', type = 'text'},
{ column = 'material', type = 'text'},
{ column = 'geom', type = 'multipolygon' , projection = srid},
}
})
local function get_osm_type_subtype(object)
local osm_type_table = {}
if object.tags.amenity == 'fire_hydrant'
or object.tags.emergency == 'fire_hydrant' then
osm_type_table['osm_type'] = 'fire_hydrant'
osm_type_table['osm_subtype'] = nil
elseif object.tags.amenity == 'emergency_phone'
or object.tags.emergency == 'phone' then
osm_type_table['osm_type'] = 'emergency_phone'
osm_type_table['osm_subtype'] = nil
elseif object.tags.highway == 'emergency_access_point' then
osm_type_table['osm_type'] = 'emergency_access'
osm_type_table['osm_subtype'] = nil
elseif object.tags.man_made == 'tower'
or object.tags.man_made == 'communications_tower'
or object.tags.man_made == 'mast'
or object.tags.man_made == 'lighthouse'
or object.tags.man_made == 'flagpole'
then
osm_type_table['osm_type'] = object.tags.man_made
osm_type_table['osm_subtype'] = object.tags['tower:type']
elseif object.tags.man_made == 'silo'
or object.tags.man_made == 'storage_tank'
or object.tags.man_made == 'water_tower'
or object.tags.man_made == 'reservoir_covered'
then
osm_type_table['osm_type'] = object.tags.man_made
osm_type_table['osm_subtype'] = object.tags['content']
elseif object.tags.power
then
osm_type_table['osm_type'] = 'power'
osm_type_table['osm_subtype'] = object.tags['power']
elseif object.tags.utility then
osm_type_table['osm_type'] = 'utility'
osm_type_table['osm_subtype'] = nil
else
osm_type_table['osm_type'] = 'unknown'
osm_type_table['osm_subtype'] = nil
end
return osm_type_table
end
function infrastructure_process_node(object)
-- We are only interested in some tags
if not is_infrastructure(object.tags) then
return
end
local osm_types = get_osm_type_subtype(object)
if osm_types.osm_type == 'unknown' then
return
end
local name = get_name(object.tags)
local ele = parse_to_meters(object.tags.ele)
local height = parse_to_meters(object.tags['height'])
local operator = object.tags.operator
local material = object.tags.material
tables.infrastructure_point:add_row({
osm_type = osm_types.osm_type,
osm_subtype = osm_types.osm_subtype,
name = name,
ele = ele,
height = height,
operator = operator,
material = material,
geom = { create = 'point' }
})
end
function infrastructure_process_way(object)
-- We are only interested in some tags
if not is_infrastructure(object.tags) then
return
end
local osm_types = get_osm_type_subtype(object)
if osm_types.osm_type == 'unknown' then
return
end
local name = get_name(object.tags)
local ele = parse_to_meters(object.tags.ele)
local height = parse_to_meters(object.tags['height'])
local operator = object.tags.operator
local material = object.tags.material
if object.is_closed then
tables.infrastructure_polygon:add_row({
osm_type = osm_types.osm_type,
osm_subtype = osm_types.osm_subtype,
name = name,
ele = ele,
height = height,
operator = operator,
material = material,
geom = { create = 'area' }
})
else
tables.infrastructure_line:add_row({
osm_type = osm_types.osm_type,
osm_subtype = osm_types.osm_subtype,
name = name,
ele = ele,
height = height,
operator = operator,
material = material,
geom = { create = 'line' }
})
end
end
if osm2pgsql.process_node == nil then
osm2pgsql.process_node = infrastructure_process_node
else
local nested = osm2pgsql.process_node
osm2pgsql.process_node = function(object)
local object_copy = deep_copy(object)
nested(object)
infrastructure_process_node(object_copy)
end
end
if osm2pgsql.process_way == nil then
osm2pgsql.process_way = infrastructure_process_way
else
local nested = osm2pgsql.process_way
osm2pgsql.process_way = function(object)
local object_copy = deep_copy(object)
nested(object)
infrastructure_process_way(object_copy)
end
end |
-- take one step forward, counting escape sequences and format values.
local function utf8forward(src, ofs, steps)
while (steps > 0) do
if (ofs <= string.len(src)) then
repeat
ofs = ofs + 1;
until (ofs > string.len(src) or utf8kind( string.byte(src, ofs) ) < 2);
end
steps = steps - 1;
end
return ofs;
end
local function formatskip(str, ofs)
repeat
local ch = string.sub(str, ofs, ofs);
local ofs2 = utf8forward(str, ofs, 1);
local ch2 = string.sub( str, ofs2, ofs2);
if (ch ~= "\\") then
break;
end
-- proper escaping for backslasht
if (ch2 == "\\") then
break;
end
-- skip #RRGGBB
if (ch2 == "#") then
ofs = utf8forward(str, ofs, 8);
break;
end
-- font, scan for , then first non-digit
if (ch2 == "f") then
ofs = utf8forward(str, ofs, 3);
while ( string.sub(str, ofs, ofs) ~= "," ) do
ofs = utf8forward(str, ofs, 1);
end
ofs = utf8forward(str, ofs, 1);
while ( tonumber( string.sub(str, ofs, ofs) ) ~= nil ) do
ofs = utf8forward(str, ofs, 1);
end
elseif (ch2 == "!") then
ofs = utf8forward(str, ofs, 2);
else
ofs = utf8forward(str, ofs, 1);
end
until true;
return ofs;
end
-- Increment one step, skips past escaped portions and handles UTF8
local function textfader_step(self)
if (self.cpos == string.len(self.message) and self.clife >= self.mlife) then
self.alive = false;
end
if (self.alive == false) then
return;
end
self.clife = self.clife + 1;
-- time to step
if (self.clife >= self.mlife ) then
-- now we have formatting strings to consider as well
self.last = self.cpos;
self.cpos = formatskip(self.message, self.cpos)
if (self.cpos == self.last) then
self.cpos = formatskip(self.message, utf8forward(self.message, self.cpos, 1) );
end
self.clife = 0;
self.smessage = string.sub(self.message, 1, self.cpos);
if (self.rmsg ~= BADID) then
delete_image(self.rmsg);
end
self.rmsg = render_text(self.smessage);
move_image(self.rmsg, self.x, self.y, NOW);
blend_image(self.rmsg, self.opa, NOW);
end
end
function textfader_create( rawtext, xpos, ypos, opacity, speed )
fdrtbl = {
message = rawtext,
x = xpos,
y = ypos,
opa = opacity,
mlife = speed,
clife = speed,
alive = true,
rmsg = BADID
};
assert(0 < speed);
fdrtbl.step = textfader_step;
fdrtbl.cpos = 1;
return fdrtbl;
end
|
local ffi=require 'ffi'
local defines = {}
function defines.register_hashdefs(mat, C)
mat.ACC_RDONLY = 0
mat.ACC_RDWR = 1
mat.FT_MAT73 = 0x0200
mat.FT_MAT5 = 0x0100
mat.FT_MAT4 = 0x0010
mat.T_UNKNOWN = 0
mat.T_INT8 = 1
mat.T_UINT8 = 2
mat.T_INT16 = 3
mat.T_UINT16 = 4
mat.T_INT32 = 5
mat.T_UINT32 = 6
mat.T_SINGLE = 7
mat.T_DOUBLE = 9
mat.T_INT64 = 12
mat.T_UINT64 = 13
mat.T_MATRIX = 14
mat.T_COMPRESSED = 15
mat.T_UTF8 = 16
mat.T_UTF16 = 17
mat.T_UTF32 = 18
mat.T_STRING = 20
mat.T_CELL = 21
mat.T_STRUCT = 22
mat.T_ARRAY = 23
mat.T_FUNCTION = 24
mat.C_EMPTY = 0
mat.C_CELL = 1
mat.C_STRUCT = 2
mat.C_OBJECT = 3
mat.C_CHAR = 4
mat.C_SPARSE = 5
mat.C_DOUBLE = 6
mat.C_SINGLE = 7
mat.C_INT8 = 8
mat.C_UINT8 = 9
mat.C_INT16 = 10
mat.C_UINT16 = 11
mat.C_INT32 = 12
mat.C_UINT32 = 13
mat.C_INT64 = 14
mat.C_UINT64 = 15
mat.C_FUNCTION = 16
mat.F_COMPLEX = 0x0800
mat.F_GLOBAL = 0x0400
mat.F_LOGICAL = 0x0200
mat.F_DONT_COPY_DATA = 0x0001
mat.COMPRESSION_NONE = 0
mat.COMPRESSION_ZLIB = 1
mat.BY_NAME = 1
mat.BY_INDEX = 2
end
return defines
|
function ipnames.command_list(name)
local names = ""
for k, v in pairs(ipnames.whitelist) do
names = names.." "..k
end
minetest.chat_send_player(name, "All exceptions: "..names)
end
function ipnames.command_whois(name, param)
if not ipnames.data[param] then
minetest.chat_send_player(name, "The player '"..param.."' did not join yet.")
return
end
local ip = ipnames.data[param][1]
local names = ""
for k, v in pairs(ipnames.data) do
if v[1] == ip then
names = names.." "..k
end
end
minetest.chat_send_player(name, "Following players share an IP: "..names)
end
function ipnames.command_ignore(name, param)
if not ipnames.data[param] then
minetest.chat_send_player(name, "The player '"..param.."' did not join yet.")
return
end
ipnames.whitelist[param] = true
minetest.chat_send_player(name, "Added an exception!")
ipnames.save_whitelist()
end
function ipnames.command_unignore(name, param)
if not ipnames.whitelist[param] then
minetest.chat_send_player(name, "The player '"..param.."' is not on the whitelist.")
return
end
ipnames.whitelist[param] = nil
minetest.chat_send_player(name, "Removed an exception!")
ipnames.save_whitelist()
end
function ipnames.load_data()
local file = io.open(ipnames.file, "r")
if not file then
return
end
local t = os.time()
for line in file:lines() do
if line ~= "" then
local data = line:split("|")
if #data >= 2 then
-- Special stuff - only save if player has not been deleted yet
local ignore = false
if not minetest.auth_table[data[1]] then
ignore = true
end
if not ignore then
data[3] = tonumber(data[3]) or 0
-- Remove IP after 2 weeks
if data[3] > 0 and t - data[3] > (3600 * 24 * 14) then
ignore = true
end
end
if not ignore then
ipnames.data[data[1]] = {data[2], data[3]}
end
end
end
end
io.close(file)
end
function ipnames.save_data()
if not ipnames.changes then
return
end
ipnames.changes = false
local file = io.open(ipnames.file, "w")
for k, v in pairs(ipnames.data) do
v[2] = v[2] or os.time()
file:write(k.."|"..v[1].."|"..v[2].."\n")
end
io.close(file)
end
function ipnames.load_whitelist()
local file = io.open(ipnames.whitelist_file, "r")
if not file then
return
end
for line in file:lines() do
if line ~= "" then
ipnames.whitelist[line] = true
end
end
end
function ipnames.save_whitelist()
local file = io.open(ipnames.whitelist_file, "w")
for k, v in pairs(ipnames.whitelist) do
if v ~= nil then
file:write(k.."\n")
end
end
io.close(file)
end
|
--
-- Created by IntelliJ IDEA.
-- User: nander
-- Date: 22-4-2017
-- Time: 11:57
-- To change this template use File | Settings | File Templates.
--
CWIDTH = 32
local heading = love.graphics.newImage("heading.png")
local texture = love.graphics.newCanvas(heading:getDimensions())
local north = love.graphics.newImage("north.png")
texture:setWrap("repeat", "repeat")
return function()
local pl = E.move[1] -- get player
local mh = -pl.position.rotation + 1.75 * math.pi
love.graphics.setCanvas(texture)
love.graphics.draw(heading, 0, 0)
love.graphics.setColor(0, 255, 0)
for i = 1, 360 / 15 do
love.graphics.line(i * 1600 * 15 / 360, 16, i * 1600 * 15 / 360, 32)
love.graphics.print((i * 15 + 180) % 360, (i * 1600 * 15 / 360 + 4) % 1600, 4)
end
local asdf = -E.move[1].mover.towards
love.graphics.setColor(255, 0, 0)
local xx = 1600 * ((asdf + 4 * math.pi) % (math.pi * 2)) / (math.pi * 2)
love.graphics.line(xx, 0, xx, 32)
love.graphics.setCanvas()
love.graphics.setColor(255, 255, 255,255*ii)
local quad = love.graphics.newQuad(math.floor(1600 * (mh) / (math.pi * 2)), 0, 400, CWIDTH, texture:getDimensions())
love.graphics.draw(texture, quad, CWIDTH, 0, 0)
local quad = love.graphics.newQuad(math.floor(1600 * (mh + 0.5 * math.pi) / (math.pi * 2)), 0, 400, CWIDTH, texture:getDimensions())
love.graphics.draw(texture, quad, 400 + 2 * CWIDTH, CWIDTH, 0.5 * math.pi)
local quad = love.graphics.newQuad(math.floor(1600 * (mh + 1 * math.pi) / (math.pi * 2)), 0, 400, CWIDTH, texture:getDimensions())
love.graphics.draw(texture, quad, 400 + CWIDTH, 400 + 2 * CWIDTH, math.pi)
local quad = love.graphics.newQuad(math.floor(1600 * (mh + 1.5 * math.pi) / (math.pi * 2)), 0, 400, CWIDTH, texture:getDimensions())
love.graphics.draw(texture, quad, 1, 400 + CWIDTH, (-.5 * math.pi))
love.graphics.setColor(128, 128, 128,255*ii)
love.graphics.line(200 + CWIDTH - 8, 32, 200 + CWIDTH, 24, 200 + CWIDTH + 8, 32)
love.graphics.setColor(255, 255, 255,255*ii)
end
|
--[[
--MIT License
--
--Copyright (c) 2019 manilarome
--Copyright (c) 2020 Tom Meyers
--
--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.
]]
-- Load these libraries (if you haven't already)
local gears = require("gears")
local wibox = require("wibox")
local beautiful = require("beautiful")
local dpi = require("beautiful").xresources.apply_dpi
local signals = require("lib-tde.signals")
local breakTimerFunctions = require("lib-tde.function.datetime")
_G.pause = {}
local breakTimer = require("widget.break-timer")
-- our timer is always running in the background until we stop it by pushing the disable button
local started = true
local breakOverlay
local breakbackdrop
awful.screen.connect_for_each_screen(
function(s)
breakOverlay =
wibox(
{
visible = false,
ontop = true,
type = "normal",
height = s.geometry.height,
width = s.geometry.width,
bg = beautiful.bg_modal,
x = s.geometry.x,
y = s.geometry.y
}
)
screen.connect_signal(
"removed",
function(removed)
if s == removed then
breakOverlay.visible = false
breakOverlay = nil
end
end
)
signals.connect_refresh_screen(
function()
print("Refreshing break timer screen")
if not s.valid or breakOverlay == nil then
return
end
-- the action center itself
breakOverlay.x = s.geometry.x
breakOverlay.y = s.geometry.y
breakOverlay.width = s.geometry.width
breakOverlay.height = s.geometry.height
end
)
-- Put its items in a shaped container
breakOverlay:setup {
-- Container
{
breakTimer,
layout = wibox.layout.fixed.vertical
},
-- The real background color
bg = beautiful.background.hue_800,
valign = "center",
halign = "center",
widget = wibox.container.place()
}
breakbackdrop =
wibox {
ontop = true,
visible = false,
screen = s,
bg = "#000000aa",
type = "dock",
x = s.geometry.x,
y = s.geometry.y,
width = s.geometry.width,
height = s.geometry.height - dpi(40)
}
end
)
_G.pause.stop = function()
breakbackdrop.visible = false
breakOverlay.visible = false
_G.pause.stopSlider()
print("Stopping break timer")
end
_G.pause.show = function(time)
breakbackdrop.visible = true
breakOverlay.visible = true
_G.pause.start(time)
gears.timer {
timeout = time,
single_shot = true,
autostart = true,
callback = function()
-- stop the break after x seconds
_G.pause.stop()
end
}
print("Showing break timer")
end
local breakTriggerTimer =
gears.timer {
timeout = tonumber(general["break_timeout"]) or (60 * 60 * 1),
autostart = true,
callback = function()
local time_start = general["break_time_start"] or "00:00"
local time_end = general["break_time_end"] or "23:59"
if breakTimerFunctions.current_time_inbetween(time_start, time_end) then
_G.pause.show(tonumber(general["break_time"]) or (60 * 5))
else
print("Break triggered but outside of time contraints")
end
end
}
-- Disable the global timer
-- Thus no more breaks will be triggered
_G.pause.disable = function()
print("Disabeling break timer")
-- only stop the timer if it is still running
if started then
breakTriggerTimer:stop()
started = false
end
end
return breakOverlay
|
local ffi = require("ffi")
local clib = ffi.load("libportf.so")
ffi.cdef[[
typedef struct {
float change;
float change_percent;
float price;
float time;
} value_t;
typedef struct {
const char *symbol;
const char *currency;
const char *display_name;
// fifty day stuff
float fifty_day_average;
float fifty_day_change;
// pre
// Are there no pre market information in the request response?
/* value_t pre; */
// regular
value_t regular;
float regular_high;
float regular_low;
float regular_open;
float regular_prev_close;
// post
value_t post;
// region
// date
} stock_t;
const char *get_version();
const char *get_api_key();
void init_shares(stock_t *out, char** symbols, int count);
char *stock_to_string(const stock_t *stock);
int get_shares(stock_t *out, int count);
]]
local m = {}
m.get_version = function()
return ffi.string(clib.get_version())
end
m.get_share = function(shares)
local count = #shares
local s = ffi.new("stock_t[?]", count)
local names = {}
for i, v in ipairs(shares) do
local c_str = ffi.new("char[?]", #v + 1)
ffi.copy(c_str, v)
names[i] = c_str
end
local c_names = ffi.new("char *[?]", count, names)
clib.init_shares(s, c_names, count)
clib.get_shares(s, count)
local results = {}
for i = 0, (count - 1) do
print(ffi.string(clib.stock_to_string(s[i])))
results[i + 1] = {
symbol = ffi.string(s[i].symbol),
display_name = ffi.string(s[i].display_name),
currency = ffi.string(s[i].currency),
regular_price = s[i].regular.price,
regular_change = s[i].regular.change,
regular_change_percent = s[i].regular.change_percent
}
end
return results
end
return m
|
local MonoClass = mono.MonoClass
MonoClass.mt = {
__index = MonoClass,
__tostring = function(t)
return 'MonoClass '..tostring(t.id)..' "'..tostring(t.name)..'"'
end,
__lt = function(a, b)
return a.lowerName < b.lowerName
end
}
local MonoField = mono.MonoField
local MonoMethod = mono.MonoMethod
--[[
Called from MonoImage:_init, 'c' is what is returned from enumerating classes.
--]]
function MonoClass.new(image, c)
local obj = {
name = c.classname,
namespace = c.namespace,
id = c.class,
lowerName = string.lower(c.classname),
image = image
}
setmetatable(obj, MonoClass.mt)
return obj
end
function MonoClass:initFields()
self.fields = {}
self.fieldsByName = {}
self.fieldsByLowerName = {}
local constFieldCount = 0
local temp = mono_class_enumFields(self.id)
for i,f in ipairs(temp) do
local field = MonoField.new(self, f)
table.insert(self.fields, field)
self.fieldsByLowerName[field.lowerName] = field;
self.fieldsByName[field.name] = field
if field.isStatic and field.isConst then
field.constValue = constFieldCount
constFieldCount = constFieldCount + 1
end
end
table.sort(self.fields)
end
function MonoClass:initMethods()
self.methods = {}
self.methodsByName = {}
self.methodsByLowerName = {}
local temp = mono_class_enumMethods(self.id)
for i,m in ipairs(temp) do
local method = MonoMethod.new(self, m)
table.insert(self.methods, method)
self.methodsByName[method.name] = method
self.methodsByLowerName[method.lowerName] = method
end
table.sort(self.methods)
end
|
local chests = {};
function add (name, slot)
chests[name] = slot
return true
end
function getChests ()
return chests
end
function clear ()
chests = {}
return true
end
function remove (name)
addChest(name, nil)
return true
end
function place (name)
name = name or 'bob'
local slot = chests[name]
if slot == nil then return false end
turtle.select(slot)
turtle.digUp()
turtle.placeUp()
return true
end
function pickUp (name)
name = name or 'bob'
local slot = chests[name]
if slot == nil then return false end
turtle.select(slot)
turtle.digUp()
return true
end |
RegisterNUICallback('youtube_Play', function(data)
exports["xsound"]:Cal(data, false)
end)
RegisterNUICallback('youtube_Pause', function()
exports["xsound"]:Duraklat()
end)
RegisterNUICallback('youtube_Stop', function()
exports["xsound"]:Durdur()
end)
RegisterNUICallback('youtube_Resume', function()
exports["xsound"]:Devamet()
end) |
local iup = require "iuplua"
local blk = iup.canvas{bgcolor="0 0 0"}
local vsx, vsy, vsw, vsh = string.match(
iup.GetGlobal"VIRTUALSCREEN",
"^(%-?%d*) (%-?%d*) (%-?%d*) (%-?%d*)$")
local dlg = iup.dialog{
TOPMOST="YES",
MAXBOX="NO", MINBOX="NO",
MENUBOX="NO",
RESIZE="NO",
BORDER="NO",
shrink="yes",
rastersize=string.format("%dx%d",vsw,vsh);
blk}
function blk:button_cb()
iup.ExitLoop()
end
dlg:showxy(vsx, vsy)
iup.MainLoop()
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "XYZBeacon"
local MODEL = Model("models/jaanus/wiretool/wiretool_range.mdl")
function ENT:Initialize()
self:SetModel( MODEL )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self,{"X","Y","Z"})
self.VPos = Vector(0,0,0)
end
function ENT:OnRemove()
Wire_Remove(self)
end
function ENT:Setup()
end
function ENT:GetBeaconPos(sensor)
return self.VPos
end
function ENT:GetBeaconVelocity(sensor)
return Vector()
end
function ENT:ShowOutput(value)
if (value ~= self.PrevOutput) then
self:SetOverlayText( "XYZ Beacon" )
self.PrevOutput = value
end
end
function ENT:TriggerInput(iname, value)
if (iname == "X") then
self.VPos.x=value
end
if (iname == "Y") then
self.VPos.y=value
end
if (iname == "Z") then
self.VPos.z=value
end
end
function ENT:OnRestore()
Wire_Restored(self)
end
|
RegisterNetEvent('DP_Inventory:openLockerInventory')
AddEventHandler('DP_Inventory:openLockerInventory', function(data)
setPropertyLockerData(data)
openLockerInventory()
end)
function refreshPropertyLockerInventory()
ESX.TriggerServerCallback('DP_Inventory:getLockerInventory', function(inventory)
setPropertyLockerData(inventory)
end, ESX.GetPlayerData().identifier, currentLocker)
end
function setPropertyLockerData(data)
items = {}
currentLocker = data.stash_name
SendNUIMessage(
{
action = 'setInfoText',
text = data.stash_name ..' - Kluis'
}
)
local money = data.money
local blackMoney = data.blackMoney
local propertyItems = data.items
local propertyWeapons = data.weapons
if money > 0 then
accountData = {
label = _U('cash'),
count = money,
type = 'item_account',
name = 'cash',
usable = false,
rare = false,
weight = 0,
canRemove = false
}
table.insert(items, accountData)
end
if blackMoney > 0 then
accountData = {
label = _U('black_money'),
count = blackMoney,
type = 'item_account',
name = 'black_money',
usable = false,
rare = false,
limit = -1,
canRemove = false
}
table.insert(items, accountData)
end
for i = 1, #propertyItems, 1 do
local item = propertyItems[i]
if item.count > 0 then
item.type = 'item_standard'
item.usable = false
item.rare = false
item.limit = -1
item.canRemove = false
table.insert(items, item)
end
end
for i = 1, #propertyWeapons, 1 do
local weapon = propertyWeapons[i]
if propertyWeapons[i].name ~= 'WEAPON_UNARMED' then
table.insert(
items,
{
label = ESX.GetWeaponLabel(weapon.name),
count = weapon.ammo,
limit = -1,
type = 'item_weapon',
name = weapon.name,
usable = false,
rare = false,
canRemove = false
}
)
end
end
SendNUIMessage(
{
action = 'setSecondInventoryItems',
itemList = items
}
)
end
function openLockerInventory()
loadPlayerInventory()
isInInventory = true
SendNUIMessage(
{
action = 'display',
type = 'locker'
}
)
SetNuiFocus(true, true)
end
RegisterNUICallback('PutIntoLocker', function(data, cb)
if IsPedSittingInAnyVehicle(playerPed) then
return
end
if type(data.number) == 'number' and math.floor(data.number) == data.number then
local count = tonumber(data.number)
if data.item.type == 'item_weapon' then
count = GetAmmoInPedWeapon(PlayerPedId(), GetHashKey(data.item.name))
end
TriggerServerEvent('DP_Inventory:putLockerItems', ESX.GetPlayerData().identifier, data.item.type, data.item.name, count, currentLocker)
end
Wait(0)
refreshPropertyLockerInventory()
Wait(0)
loadPlayerInventory()
cb('ok')
end)
RegisterNUICallback('TakeFromLocker',function(data, cb)
if IsPedSittingInAnyVehicle(playerPed) then
return
end
if type(data.number) == 'number' and math.floor(data.number) == data.number then
TriggerServerEvent('DP_Inventory:getLockerItems', ESX.GetPlayerData().identifier, data.item.type, data.item.name, tonumber(data.number), currentLocker)
end
Wait(0)
refreshPropertyLockerInventory()
Wait(0)
loadPlayerInventory()
cb('ok')
end)
|
--- L2DF engine.
-- @module l2df
-- @author Abelidze
-- @author Kasai
-- @copyright Atom-TM 2020
l2df = require((...) .. '.core')
local love = _G.love
local math = _G.math
local floor = math.floor
local core = l2df
local log = core.import 'class.logger'
local Entity = core.import 'class.entity'
local Factory = core.import 'manager.factory'
local EventManager = core.import 'manager.event'
local GroupManager = core.import 'manager.group'
local RenderManager = core.import 'manager.render'
local SoundManager = core.import 'manager.sound'
local ResourceManager = core.import 'manager.resource'
local SyncManager = core.import 'manager.sync'
local InputManager = core.import 'manager.input'
local NetworkManager = core.import 'manager.network'
local PhysixManager = core.import 'manager.physix'
local Recorder = core.import 'manager.recorder'
--- Engine's standart entry point.
-- @param[opt] table kwargs
-- @param[opt=60] number kwargs.fps
-- @param[opt=30] number kwargs.datafps
-- @param[opt=30] number kwargs.speed
function core:init(kwargs)
kwargs = kwargs or { }
-- First call to core.root() always should be in core.init
Factory:scan(core.root() .. 'class/entity')
self.fps = kwargs.fps or 60
self.tickrate = 1 / self.fps
self.factor = self.fps / (kwargs.datafps or 30)
self.speed = kwargs.speed or 1
EventManager:monitoring(love, love.handlers)
EventManager:monitoring(love, 'update', 'rawupdate')
EventManager:monitoring(love, 'draw')
EventManager:monitoring(Entity, 'new', 'entitycreated', true)
EventManager:monitoring(NetworkManager, 'update', 'netupdate')
EventManager:subscribe('entitycreated', EventManager.classInit, Entity, EventManager)
EventManager:subscribe('entitycreated', GroupManager.classInit, Entity, GroupManager)
EventManager:subscribe('resize', RenderManager.resize, love, RenderManager)
EventManager:subscribe('keypressed', InputManager.keypressed, love, InputManager)
EventManager:subscribe('keyreleased', InputManager.keyreleased, love, InputManager)
EventManager:subscribe('mousepressed', InputManager.mousepressed, love, InputManager)
EventManager:subscribe('mousereleased', InputManager.mousereleased, love, InputManager)
EventManager:subscribe('touchmoved', InputManager.touchmoved, love, InputManager)
EventManager:subscribe('touchpressed', InputManager.touchpressed, love, InputManager)
EventManager:subscribe('touchreleased', InputManager.touchreleased, love, InputManager)
EventManager:subscribe('rawupdate', EventManager.update, love, EventManager)
EventManager:subscribe('beforepreupdate', SyncManager.persist, EventManager, SyncManager)
EventManager:subscribe('beforepreupdate', RenderManager.clear, EventManager, RenderManager)
EventManager:subscribe('beforepreupdate', InputManager.update, EventManager, InputManager)
EventManager:subscribe('update', SoundManager.update, EventManager, SoundManager)
EventManager:subscribe('update', PhysixManager.update, EventManager, PhysixManager)
EventManager:subscribe('update', ResourceManager.update, EventManager, ResourceManager)
EventManager:subscribe('postupdate', InputManager.advance, EventManager, InputManager)
EventManager:subscribe('postupdate', SyncManager.commit, EventManager, SyncManager)
EventManager:subscribe('postupdate', Recorder.update, EventManager, Recorder)
EventManager:subscribe('draw', RenderManager.render, love, RenderManager)
end
--- Tweak simulation speed.
-- @param number value
function core:speedup(value)
self.speed = value > 0 and floor(value) or (1 / floor(-value))
end
--- Convert
-- @param number value
function core:convert(value)
return floor(value * self.factor)
end
--- Engine's game loop.
-- @return function
function core.gameloop()
if love.load then love.load(love.arg.parseGameArguments(arg), arg) end
if love.timer then
math.randomseed(love.timer.getTime())
love.timer.step()
end
local tickrate = core.tickrate
local fps = 1 / tickrate
local accumulate = 0
local throttle = 0
local delta = 0
local diff = 0
local draw = false
local min = math.min
return function()
-- Events
love.event.pump()
for name, a, b, c, d, e, f in love.event.poll() do
if name == "quit" then
if not love.quit or not love.quit() then
return a or 0
end
end
love.handlers[name](a, b, c, d, e, f)
end
-- Network and rollbacks
tickrate = core.tickrate
delta = (love.timer and love.timer.step() or tickrate)
NetworkManager:update(delta)
diff, throttle = SyncManager:sync(InputManager.frame)
-- Update
draw = false
accumulate = min(accumulate + delta * core.speed + diff - throttle, fps)
while accumulate >= tickrate do
accumulate = accumulate - tickrate
draw = accumulate < tickrate
love.update(tickrate, draw)
end
-- Draw
if (draw or not RenderManager.vsync) and love.graphics and love.graphics.isActive() then
love.graphics.origin()
love.graphics.clear(love.graphics.getBackgroundColor())
love.draw()
love.graphics.present()
end
-- Throttle = tickrate - accumulate
if love.timer then love.timer.sleep(0.001) end
end
end
return core |
-- RenderDrawLists is based on love-imgui (https://github.com/slages/love-imgui)
local path = (...):gsub("[^%.]*$", "")
local M = require(path .. "master")
local ffi = require("ffi")
local bit = require("bit")
local C = M.C
local vertexformat = {
{"VertexPosition", "float", 2},
{"VertexTexCoord", "float", 2},
{"VertexColor", "byte", 4}
}
local lovekeymap = {
["tab"] = 1,
["left"] = 2,
["right"] = 3,
["up"] = 4,
["down"] = 5,
["pageup"] = 6,
["pagedown"] = 7,
["home"] = 8,
["end"] = 9,
["insert"] = 10,
["delete"] = 11,
["backspace"] = 12,
["space"] = 13,
["return"] = 14,
["escape"] = 15,
["kpenter"] = 16,
["a"] = 17,
["c"] = 18,
["v"] = 19,
["x"] = 20,
["y"] = 21,
["z"] = 22
}
local ini_filename, textureObject
M._textures = setmetatable({},{__mode="v"})
function M.Init()
C.igCreateContext(nil)
M.BuildFontAtlas()
local io = C.igGetIO()
local kmap = io.KeyMap
kmap[C.ImGuiKey_Tab] = lovekeymap["tab"]
kmap[C.ImGuiKey_LeftArrow] = lovekeymap["left"]
kmap[C.ImGuiKey_RightArrow] = lovekeymap["right"]
kmap[C.ImGuiKey_UpArrow] = lovekeymap["up"]
kmap[C.ImGuiKey_DownArrow] = lovekeymap["down"]
kmap[C.ImGuiKey_PageUp] = lovekeymap["pageup"]
kmap[C.ImGuiKey_PageDown] = lovekeymap["pagedown"]
kmap[C.ImGuiKey_Home] = lovekeymap["home"]
kmap[C.ImGuiKey_End] = lovekeymap["end"]
kmap[C.ImGuiKey_Insert] = lovekeymap["insert"]
kmap[C.ImGuiKey_Delete] = lovekeymap["delete"]
kmap[C.ImGuiKey_Backspace] = lovekeymap["backspace"]
kmap[C.ImGuiKey_Space] = lovekeymap["space"]
kmap[C.ImGuiKey_Enter] = lovekeymap["return"]
kmap[C.ImGuiKey_Escape] = lovekeymap["escape"]
kmap[C.ImGuiKey_KeyPadEnter] = lovekeymap["kpenter"]
kmap[C.ImGuiKey_A] = lovekeymap["a"]
kmap[C.ImGuiKey_C] = lovekeymap["c"]
kmap[C.ImGuiKey_V] = lovekeymap["v"]
kmap[C.ImGuiKey_X] = lovekeymap["x"]
kmap[C.ImGuiKey_Y] = lovekeymap["y"]
kmap[C.ImGuiKey_Z] = lovekeymap["z"]
io.GetClipboardTextFn = function(userdata)
return love.system.getClipboardText()
end
io.SetClipboardTextFn = function(userdata, text)
love.system.setClipboardText(ffi.string(text))
end
local dpiscale = love.window.getDPIScale()
io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.x = dpiscale, dpiscale
love.filesystem.createDirectory("/")
ini_filename = love.filesystem.getSaveDirectory() .. "/imgui.ini"
io.IniFilename = ini_filename
io.BackendFlags = bit.bor(C.ImGuiBackendFlags_HasMouseCursors, C.ImGuiBackendFlags_HasSetMousePos)
end
function M.BuildFontAtlas()
local io = C.igGetIO()
local pixels, width, height = ffi.new("unsigned char*[1]"), ffi.new("int[1]"), ffi.new("int[1]")
C.ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, pixels, width, height, nil)
local imgdata = love.image.newImageData(width[0], height[0], "rgba8", ffi.string(pixels[0], width[0]*height[0]*4))
textureObject = love.graphics.newImage(imgdata)
end
local navinputs = ffi.new("float[?]", C.ImGuiNavInput_COUNT)
local navinputs_size = ffi.sizeof("float")*C.ImGuiNavInput_COUNT
function M.Update(dt)
local io = C.igGetIO()
io.DisplaySize.x, io.DisplaySize.y = love.graphics.getDimensions()
io.DeltaTime = dt
if io.WantSetMousePos then
love.mouse.setPosition(io.MousePos.x, io.MousePos.y)
end
if bit.band(io.ConfigFlags, C.ImGuiConfigFlags_NavEnableGamepad) == C.ImGuiConfigFlags_NavEnableGamepad then
ffi.copy(io.NavInputs, navinputs, navinputs_size)
end
end
local function love_texture_test(t)
return t:typeOf("Texture")
end
local cursors = {
[C.ImGuiMouseCursor_Arrow] = love.mouse.getSystemCursor("arrow"),
[C.ImGuiMouseCursor_TextInput] = love.mouse.getSystemCursor("ibeam"),
[C.ImGuiMouseCursor_ResizeAll] = love.mouse.getSystemCursor("sizeall"),
[C.ImGuiMouseCursor_ResizeNS] = love.mouse.getSystemCursor("sizens"),
[C.ImGuiMouseCursor_ResizeEW] = love.mouse.getSystemCursor("sizewe"),
[C.ImGuiMouseCursor_ResizeNESW] = love.mouse.getSystemCursor("sizenesw"),
[C.ImGuiMouseCursor_ResizeNWSE] = love.mouse.getSystemCursor("sizenwse"),
[C.ImGuiMouseCursor_Hand] = love.mouse.getSystemCursor("hand"),
[C.ImGuiMouseCursor_NotAllowed] = love.mouse.getSystemCursor("no"),
}
function M.RenderDrawLists()
local io = C.igGetIO()
local data = C.igGetDrawData()
-- change mouse cursor
if bit.band(io.ConfigFlags, C.ImGuiConfigFlags_NoMouseCursorChange) ~= C.ImGuiConfigFlags_NoMouseCursorChange then
local cursor = cursors[C.igGetMouseCursor()]
if io.MouseDrawCursor or not cursor then
love.mouse.setVisible(false) -- Hide OS mouse cursor if ImGui is drawing it
else
love.mouse.setVisible(true)
love.mouse.setCursor(cursor)
end
end
-- Avoid rendering when minimized, scale coordinates for retina displays
-- (screen coordinates != framebuffer coordinates)
if io.DisplaySize.x == 0 or io.DisplaySize.y == 0 then return end
C.ImDrawData_ScaleClipRects(data, io.DisplayFramebufferScale)
for i = 0, data.CmdListsCount - 1 do
local cmd_list = data.CmdLists[i]
local VtxSize = cmd_list.VtxBuffer.Size*ffi.sizeof("ImDrawVert")
local meshdata = love.image.newImageData(VtxSize/4, 1)
ffi.copy(meshdata:getFFIPointer(), cmd_list.VtxBuffer.Data, VtxSize)
local mesh = love.graphics.newMesh(vertexformat, meshdata, "triangles", "static")
local IdxBuffer = {}
for k = 1, cmd_list.IdxBuffer.Size do
IdxBuffer[k] = cmd_list.IdxBuffer.Data[k - 1] + 1
end
mesh:setVertexMap(IdxBuffer)
local position = 1
for k = 0, cmd_list.CmdBuffer.Size - 1 do
local cmd = cmd_list.CmdBuffer.Data[k]
local clipX, clipY = cmd.ClipRect.x, cmd.ClipRect.y
local clipW = cmd.ClipRect.z - clipX
local clipH = cmd.ClipRect.w - clipY
love.graphics.setBlendMode("alpha")
local texture_id = C.ImDrawCmd_GetTexID(cmd)
if texture_id ~= nil then
local obj = M._textures[tostring(texture_id)]
local status, value = pcall(love_texture_test, obj)
assert(status and value, "Only LÖVE Texture objects can be passed as ImTextureID arguments.")
if obj:typeOf("Canvas") then
love.graphics.setBlendMode("alpha", "premultiplied")
end
mesh:setTexture(obj)
else
mesh:setTexture(textureObject)
end
love.graphics.setScissor(clipX, clipY, clipW, clipH)
mesh:setDrawRange(position, cmd.ElemCount)
love.graphics.draw(mesh)
position = position + cmd.ElemCount
love.graphics.setBlendMode("alpha")
end
end
love.graphics.setScissor()
end
function M.MouseMoved(x, y)
local io = C.igGetIO()
if love.window.hasMouseFocus() then
io.MousePos.x, io.MousePos.y = x, y
end
end
local mouse_buttons = {true, true, true}
function M.MousePressed(button)
if mouse_buttons[button] then
C.igGetIO().MouseDown[button - 1] = true
end
end
function M.MouseReleased(button)
if mouse_buttons[button] then
C.igGetIO().MouseDown[button - 1] = false
end
end
function M.WheelMoved(x, y)
local io = C.igGetIO()
io.MouseWheelH = x
io.MouseWheel = y
end
function M.KeyPressed(key)
local io = C.igGetIO()
if lovekeymap[key] then
io.KeysDown[lovekeymap[key]] = true
elseif key == "rshift" or key == "lshift" then
io.KeyShift = true
elseif key == "rctrl" or key == "lctrl" then
io.KeyCtrl = true
elseif key == "ralt" or key == "lalt" then
io.KeyAlt = true
elseif key == "rgui" or key == "lgui" then
io.KeySuper = true
end
end
function M.KeyReleased(key)
local io = C.igGetIO()
if lovekeymap[key] then
io.KeysDown[lovekeymap[key]] = false
elseif key == "rshift" or key == "lshift" then
io.KeyShift = false
elseif key == "rctrl" or key == "lctrl" then
io.KeyCtrl = false
elseif key == "ralt" or key == "lalt" then
io.KeyAlt = false
elseif key == "rgui" or key == "lgui" then
io.KeySuper = false
end
end
function M.TextInput(text)
C.ImGuiIO_AddInputCharactersUTF8(C.igGetIO(), text)
end
function M.Shutdown()
C.igDestroyContext(nil)
end
function M.JoystickAdded(joystick)
if not joystick:isGamepad() then return end
local io = C.igGetIO()
io.BackendFlags = bit.bor(io.BackendFlags, C.ImGuiBackendFlags_HasGamepad)
end
function M.JoystickRemoved()
for _, joystick in ipairs(love.joystick.getJoysticks()) do
if joystick:isGamepad() then return end
end
local io = C.igGetIO()
io.BackendFlags = bit.band(io.BackendFlags, bit.bnot(C.ImGuiBackendFlags_HasGamepad))
end
local gamepad_map = {
a = C.ImGuiNavInput_Activate,
b = C.ImGuiNavInput_Cancel,
y = C.ImGuiNavInput_Input,
x = C.ImGuiNavInput_Menu,
dpleft = C.ImGuiNavInput_DpadLeft,
dpright = C.ImGuiNavInput_DpadRight,
dpup = C.ImGuiNavInput_DpadUp,
dpdown = C.ImGuiNavInput_DpadDown,
leftx = {C.ImGuiNavInput_LStickRight, C.ImGuiNavInput_LStickLeft},
lefty = {C.ImGuiNavInput_LStickDown, C.ImGuiNavInput_LStickUp},
leftshoulder = {C.ImGuiNavInput_FocusPrev, C.ImGuiNavInput_TweakSlow},
rightshoulder = {C.ImGuiNavInput_FocusNext, C.ImGuiNavInput_TweakFast},
}
function M.GamepadPressed(button)
local idx = gamepad_map[button]
if type(idx) == "table" then
for i = 1, #idx do
navinputs[idx[i]] = 1
end
elseif idx then
navinputs[idx] = 1
end
end
function M.GamepadReleased(button)
local idx = gamepad_map[button]
if type(idx) == "table" then
for i = 1, #idx do
navinputs[idx[i]] = 0
end
elseif idx then
navinputs[idx] = 0
end
end
function M.GamepadAxis(axis, value, threshold)
threshold = threshold or 0
local idx = gamepad_map[axis]
if type(idx) == "table" then
if value > threshold then
navinputs[idx[1]] = value
navinputs[idx[2]] = 0
elseif value < -threshold then
navinputs[idx[1]] = 0
navinputs[idx[2]] = -value
else
navinputs[idx[1]] = 0
navinputs[idx[2]] = 0
end
elseif idx then
navinputs[idx] = value
end
end
-- input capture
function M.GetWantCaptureMouse()
return C.igGetIO().WantCaptureMouse
end
function M.GetWantCaptureKeyboard()
return C.igGetIO().WantCaptureKeyboard
end
function M.GetWantTextInput()
return C.igGetIO().WantTextInput
end
-- flag helpers
local flags = {}
for name in pairs(M) do
name = name:match("^(%w+Flags)_")
if name and not flags[name] then
flags[name] = true
end
end
for name in pairs(flags) do
local shortname = name:gsub("^ImGui", "")
shortname = shortname:gsub("^Im", "")
M[shortname] = function(...)
local t = {}
for _, flag in ipairs({...}) do
t[#t + 1] = M[name .. "_" .. flag]
end
return bit.bor(unpack(t))
end
end
|
local ztimer = require "lzmq.timer"
local writer = require "log.writer.async.zmq".new('inproc://async.logger',
string.dump(function()
local Log = require "log"
Log.add_cleanup(function()
require "lzmq.timer".sleep(5000)
print "Done!"
os.exit(0)
end)
return require"log.writer.stdout".new()
end)
)
local LOG = require"log".new(writer)
LOG.fatal("can not allocate memory")
do return -1 end |
-----------------------------------
-- Area: Yuhtunga Jungle
-- NPC: Peddlestox
-- !pos -103.286 0.6 434.866 123
-- Active on WINDSDAY in this zone. To test on off-days, setStatus(tpz.status.NORMAL)
-----------------------------------
local ID = require("scripts/zones/Yuhtunga_Jungle/IDs")
require("scripts/globals/beastmentreasure")
-----------------------------------
function onTrigger(player)
tpz.bmt.handleNpcOnTrigger(player, ID.npc.BEASTMEN_TREASURE)
end
function onTrade(player, npc, trade)
tpz.bmt.handleNpcOnTrade(player, trade, ID.npc.BEASTMEN_TREASURE)
end
function onEventFinish(player, csid, option)
tpz.bmt.handleNpcOnEventFinish(player, csid)
end
|
--- MAC address handling object.
-- depends on LuaJIT's 64-bit capabilities,
-- both for numbers and bit.* library
local bit = require "bit"
local ffi = require "ffi"
local mac_t = ffi.typeof('union { int64_t bits; uint8_t bytes[6];}')
local mac_mt = {}
mac_mt.__index = mac_mt
function mac_mt:new (m)
if ffi.istype(mac_t, m) then
return m
end
local macobj = mac_t()
local i = 0;
for b in m:gmatch('[0-9a-fA-F][0-9a-fA-F]') do
if i == 6 then
-- avoid out of bound array index
return nil, "malformed MAC address: " .. m
end
macobj.bytes[i] = tonumber(b, 16)
i = i + 1
end
if i < 6 then
return nil, "malformed MAC address: " .. m
end
return macobj
end
function mac_mt:__tostring ()
return string.format('%02X:%02X:%02X:%02X:%02X:%02X',
self.bytes[0], self.bytes[1], self.bytes[2],
self.bytes[3], self.bytes[4], self.bytes[5])
end
function mac_mt.__eq (a, b)
return a.bits == b.bits
end
function mac_mt:subbits (i,j)
local b = bit.rshift(self.bits, i)
local mask = bit.bnot(bit.lshift(0xffffffffffffLL, j-i))
return tonumber(bit.band(b, mask))
end
mac_t = ffi.metatype(mac_t, mac_mt)
return mac_mt
|
repeat
local v, w = 0
print(w, v)
until x < 100
|
--* Key Class
local Key = {}
Key.__index = Key
function Key:new(time, ...)
local key = {
k = {...},
time = time,
wait = 0
}
setmetatable(key, self)
function key:press()
if self.wait <= 0 then
if love.keyboard.isDown(unpack(self.k)) then
self.wait = time
return true
end
end
return false
end
function key:update(dt)
if self.wait >= 0 then
self.wait = self.wait - dt
end
end
return key
end
return Key
|
local env = require("foxcaves.env")
local revision = require("foxcaves.revision")
local sentry_enabled = not not require("foxcaves.config").sentry.dsn
R.register_route("/api/v1/system/info", "GET", R.make_route_opts_anon(), function()
return {
environment = env,
release = revision.hash,
sentry = sentry_enabled,
}
end)
|
----------------------------------------------------------------------------------
--- Total RP 3
--- Register cursor
--- Implements right-click on a player in the 3D world to open their profile
--- ---------------------------------------------------------------------------
--- Copyright 2014-2019 Renaud "Ellypse" Parize <ellypse@totalrp3.info> @EllypseCelwe
---
--- 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.
----------------------------------------------------------------------------------
---@type TRP3_API
local _, TRP3_API = ...;
-- Lua API imports
local insert = table.insert;
-- WoW API imports
local InCombatLockdown = InCombatLockdown;
local IsShiftKeyDown = IsShiftKeyDown;
local IsControlKeyDown = IsControlKeyDown;
local IsAltKeyDown = IsAltKeyDown;
-- Total RP 3 imports
local loc = TRP3_API.loc;
local isUnitIDKnown = TRP3_API.register.isUnitIDKnown;
local hasProfile = TRP3_API.register.hasProfile;
local openMainFrame = TRP3_API.navigation.openMainFrame;
local openPageByUnitID = TRP3_API.register.openPageByUnitID;
local registerConfigKey = TRP3_API.configuration.registerConfigKey;
local getConfigValue = TRP3_API.configuration.getValue;
local isUnitIDIgnored = TRP3_API.register.isIDIgnored;
local isPlayerIC = TRP3_API.dashboard.isPlayerIC;
-- Ellyb imports
local Cursor = TRP3_API.Ellyb.Cursor;
--- Create a new Ellyb Unit for the mouseover unit
---@type Unit
local Mouseover = TRP3_API.Ellyb.Unit("mouseover");
local CONFIG_RIGHT_CLICK_OPEN_PROFILE = "CONFIG_RIGHT_CLICK_OPEN_PROFILE";
local CONFIG_RIGHT_CLICK_DISABLE_OOC = "CONFIG_RIGHT_CLICK_DISABLE_OOC";
local CONFIG_RIGHT_CLICK_OPEN_PROFILE_MODIFIER_KEY = "CONFIG_RIGHT_CLICK_OPEN_PROFILE_MODIFIER_KEY";
---Check if we can view the unit profile by using the cursor
local function canInteractWithUnit()
if
not Mouseover:Exists()
or InCombatLockdown() -- We don't want to open stuff in combat
or not Mouseover:IsPlayer() -- Unit has to be a player
or Mouseover:IsMountable() -- Avoid unit on multi seats mounts
or Mouseover:IsAttackable() -- Unit must not be attackable
then
return false;
end
local unitID = Mouseover:GetUnitID();
if
not unitID
or unitID == TRP3_API.globals.player_id -- Unit is not the player
or not isUnitIDKnown(unitID) -- Unit is known by TRP3
or hasProfile(unitID) == nil -- Unit has a RP profile available
or isUnitIDIgnored(unitID) -- Unit has been ignored
then
return false;
end
return true;
end
local ICON_X = 30;
local ICON_Y = -3;
local function onMouseOverUnit()
if getConfigValue(CONFIG_RIGHT_CLICK_DISABLE_OOC) and not isPlayerIC() then
return
end
if getConfigValue(CONFIG_RIGHT_CLICK_OPEN_PROFILE) and canInteractWithUnit() then
if TRP3_API.register.unitIDIsFilteredForMatureContent(Mouseover:GetUnitID()) then
Cursor:SetIcon("Interface\\AddOns\\totalRP3\\resources\\WorkOrders_Pink.tga", ICON_X, ICON_Y);
else
Cursor:SetIcon("Interface\\CURSOR\\WorkOrders", ICON_X, ICON_Y);
end
Cursor:HideOnUnitChanged();
end
end
TRP3_API.events.listenToEvent(TRP3_API.events.WORKFLOW_ON_LOADED, function()
registerConfigKey(CONFIG_RIGHT_CLICK_OPEN_PROFILE, false);
registerConfigKey(CONFIG_RIGHT_CLICK_DISABLE_OOC, false);
registerConfigKey(CONFIG_RIGHT_CLICK_OPEN_PROFILE_MODIFIER_KEY, 1);
local function isModifierKeyPressed()
local option = getConfigValue(CONFIG_RIGHT_CLICK_OPEN_PROFILE_MODIFIER_KEY);
if option == 1 then
return true;
elseif option == 2 then
return IsShiftKeyDown();
elseif option == 3 then
return IsControlKeyDown();
elseif option == 4 then
return IsAltKeyDown();
end
end
Cursor:OnUnitRightClicked(function(unitID)
if getConfigValue(CONFIG_RIGHT_CLICK_DISABLE_OOC) and not isPlayerIC() then
return
end
if getConfigValue(CONFIG_RIGHT_CLICK_OPEN_PROFILE) and isModifierKeyPressed() and not isUnitIDIgnored(unitID) then
openMainFrame()
openPageByUnitID(unitID);
end
end)
-- Listen to the mouse over event and register data update to event to show the cursor icon
TRP3_API.utils.event.registerHandler("UPDATE_MOUSEOVER_UNIT", onMouseOverUnit);
TRP3_API.events.listenToEvent(TRP3_API.events.REGISTER_DATA_UPDATED, onMouseOverUnit)
-- Configuration header
insert(TRP3_API.register.CONFIG_STRUCTURE.elements, {
inherit = "TRP3_ConfigH1",
title = loc.CO_CURSOR_TITLE,
});
-- Main checkbox to toggle this feature
insert(TRP3_API.register.CONFIG_STRUCTURE.elements, {
inherit = "TRP3_ConfigCheck",
title = loc.CO_CURSOR_RIGHT_CLICK,
help = loc.CO_CURSOR_RIGHT_CLICK_TT,
configKey = CONFIG_RIGHT_CLICK_OPEN_PROFILE,
});
-- Main checkbox to toggle this feature
insert(TRP3_API.register.CONFIG_STRUCTURE.elements, {
inherit = "TRP3_ConfigCheck",
title = loc.CO_CURSOR_DISABLE_OOC,
help = loc.CO_CURSOR_DISABLE_OOC_TT,
configKey = CONFIG_RIGHT_CLICK_DISABLE_OOC,
dependentOnOptions = { CONFIG_RIGHT_CLICK_OPEN_PROFILE },
});
-- Modifier key dropdown option
insert(TRP3_API.register.CONFIG_STRUCTURE.elements, {
inherit = "TRP3_ConfigDropDown",
widgetName = "TRP3_ConfigCursor_ModifierKey",
title = loc.CO_CURSOR_MODIFIER_KEY,
help = loc.CO_CURSOR_MODIFIER_KEY_TT,
listContent = {
{ NONE, 1 },
{ TRP3_API.Ellyb.System.MODIFIERS.SHIFT, 2 },
{ TRP3_API.Ellyb.System.MODIFIERS.CTRL, 3 },
{ TRP3_API.Ellyb.System.MODIFIERS.ALT, 4 }
},
configKey = CONFIG_RIGHT_CLICK_OPEN_PROFILE_MODIFIER_KEY,
dependentOnOptions = { CONFIG_RIGHT_CLICK_OPEN_PROFILE },
});
end)
|
local gainer = require 'gainer'
---
-- Simple example that prints version number of firmware on gainer device.
local board = gainer.new()
local function setup()
board:init(nil, 0) -- Firmware version can be only checked in configuration 0
print("Firmware version: ", board:getVersion())
end
local function loop()
os.exit() -- Just terminate the program
end
board:start(setup, loop) |
SvFishing = {
Stats = {},
GivePlayerItem = function(source, item, amount)
local player = SvFishingPlayer.new(source)
player:SendMessage("Congrats! You caught a" .. item)
end,
SetLureHandler = function(source, lure)
local player = SvFishingPlayer.new(source)
player:EquipLure(lure)
end
}
---@param handler fun(source: number, item: string, amount: number): void
function SvFishing:SetGiveHandler(handler)
self.GivePlayerItem = function(source, item, amount)
handler(source, item, amount)
end
end
---@param playerId number
---@param lure string
function SvFishing:SetPlayerLure(playerId, lure)
local player = SvFishingPlayer.new(playerId)
player:EquipLure(lure)
end
---@param playerId number
---@param item string
---@param amount number
function SvFishing:GiveItem(playerId, item, amount)
if type(item) ~= "string" then
return
end
amount = tonumber(amount)
if type(amount) ~= "number" then return end
local player = SvFishingPlayer.new(playerId)
player:AddItem(item, amount)
end
local EventHandlers = {
{
Event = "setLure",
Handler = "SetPlayerLure"
},
{
Event = "giveItem",
Handler = "GiveItem"
}
}
local resourceName = GetCurrentResourceName()
for k,v in pairs(EventHandlers) do
local eventName = resourceName .. ":" .. v.Event
RegisterNetEvent(eventName)
AddEventHandler(eventName, function(...)
local source = source
SvFishing[v.Handler](svFishing, source, ...)
end)
end
RegisterCommand('setlure', function(source, args, raw)
local source = source
local player = SvFishingPlayer.new(source)
player:EquipLure("lure_basic_01")
end)
exports('SetGivePlayerItem', function(handler)
SvFishing.GivePlayerItem = handler
end)
exports('SetLureHandler', function(handler)
SvFishing.SetLureHandler = handler
end)
exports('SetLureForPlayer', function(source, lure)
SvFishing:SetPlayerLure(source, lure)
end) |
local export = require('export')
local path = require('path')
local premake = require('premake')
local tree = require('tree')
local xml = require('xml')
local vstudio = select(1, ...)
local vcxproj = vstudio.vcxproj
local esc = xml.escape
local wl = export.writeLine
local filters = {}
---
-- Element lists describe the contents of each section of the project file
---
filters.elements = {
project = function (prj)
return {
vcxproj.xmlDeclaration,
filters.project,
filters.identifiers,
filters.filters,
vcxproj.endTag
}
end
}
---
-- Export the project's `.vcxproj.filters` file.
--
-- @return
-- True if the target `.vcxproj.filters` file was updated; false otherwise.
---
function filters.export(prj)
if tree.hasBranches(prj.virtualSourceTree) then
local exportPath = prj.exportPath .. '.filters'
return premake.export(prj, exportPath, function ()
export.eol('\r\n')
export.indentString(' ')
premake.callArray(filters.elements.project, prj)
end)
end
return false
end
---
-- Handlers for structural elements, in the order in which they appear in the .vcxproj.filters file.
---
function filters.project()
wl('<Project ToolsVersion="%s" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">', vstudio.targetVersion.filterToolsVersion)
export.indent()
end
---
-- Export the initial `<ItemGroup/>` which assigns unique identifiers to each folder
-- (which might be virtual) in the source tree.
---
function filters.identifiers(prj)
local settings = export.capture(function ()
export.indent()
tree.traverse(prj.virtualSourceTree, {
onBranchEnter = function (node, depth)
local filename = path.getRelative(prj.baseDirectory, node.path)
wl('<Filter Include="%s">', path.translate(filename))
export.indent()
wl('<UniqueIdentifier>{%s}</UniqueIdentifier>', os.uuid(node.path))
export.outdent()
wl('</Filter>')
end
})
export.outdent()
end)
if #settings > 0 then
wl('<ItemGroup>')
wl(settings)
wl('</ItemGroup>')
end
end
function filters.filters(prj)
local categorizedFiles = prj.categorizedSourceFiles
for ci = 1, #categorizedFiles do
local category = vcxproj.categories[ci]
local files = categorizedFiles[ci]
if #files > 0 then
wl('<ItemGroup>')
export.indent()
for fi = 1, #files do
filters.emitFileItem(prj, category, files[fi])
end
export.outdent()
wl('</ItemGroup>')
end
end
end
function filters.emitFileItem(prj, category, filePath)
filePath = path.getRelative(prj.baseDirectory, filePath)
-- TODO: use virtual paths here when available
local virtualPath = filePath
local virtualGroup = path.getDirectory(virtualPath)
if virtualGroup == '.' then
wl('<%s Include="%s" />', category.tag, path.translate(filePath))
else
wl('<%s Include="%s">', category.tag, path.translate(filePath))
export.indent()
wl('<Filter>%s</Filter>', path.translate(virtualGroup))
export.outdent()
wl('</%s>', category.tag)
end
end
return filters
|
AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")
include("shared.lua")
function ENT:Initialize()
self:SetModel("models/metrostroi/signals/mus/box.mdl")
Metrostroi.DropToFloor(self)
-- Initial state of the switch
self.AlternateTrack = false
self.InhibitSwitching = false
self.LastSignalTime = 0
-- Find rotating parts which belong to this switch
local list = ents.FindInSphere(self:GetPos(),game.GetMap():find("metrostroi") and 512 or 256)
self.TrackSwitches = {}
for k,v in pairs(list) do
if (v:GetClass() == "prop_door_rotating") and (string.find(v:GetName(),"switch") or string.find(v:GetName(),"swh") or string.find(v:GetName(),"swit")) then
table.insert(self.TrackSwitches,v)
timer.Simple(0.05,function()
debugoverlay.Line(v:GetPos(),self:GetPos(),10,Color(255,255,0),true)
end)
end
end
Metrostroi.UpdateSignalEntities()
end
function ENT:OnRemove()
Metrostroi.UpdateSignalEntities()
end
function ENT:SendSignal(index,channel,route)
if not route then
if channel and channel ~= self:GetChannel() then return end
-- Switch to alternate track
if index == "alt" then self.AlternateTrack = true end
-- Switch to main track
if index == "main" then self.AlternateTrack = false end
-- Remember this signal
self.LastSignal = index
self.LastSignalTime = CurTime()
else
if index == "alt" then
for k,v in pairs(self.TrackSwitches) do v:Fire("Open","","0") end
elseif index == "main" then
for k,v in pairs(self.TrackSwitches) do v:Fire("Close","","0") end
end
if index == "alt" then self.AlternateTrack = true end
if index == "main" then self.AlternateTrack = false end
end
end
function ENT:Think()
-- Reset
self.InhibitSwitching = false
-- Check if local section of track is occupied or no
local pos = self.TrackPosition
if pos and self.AlternateTrack then
local trackOccupied = Metrostroi.IsTrackOccupied(pos.node1,pos.x,pos.forward,"switch")
if trackOccupied then -- Prevent track switches from working when there's a train on segment
self.InhibitSwitching = true
end
end
if self.NotChangePos == nil then
self.NotChangePos = false
end
-- Force door state state
if self.NotChangePos then
self.AlternateTrack = false
for k,v in pairs(self.TrackSwitches) do
self.AlternateTrack = self.AlternateTrack or v:GetSaveTable().m_eDoorState == 2
end
else
if self.AlternateTrack then
for k,v in pairs(self.TrackSwitches) do if IsValid(v) then v:Fire("Open","","0") end end
else
for k,v in pairs(self.TrackSwitches) do if IsValid(v) then v:Fire("Close","","0") end end
end
-- Return switch to original position
if (self.InhibitSwitching == false) and (self.AlternateTrack == true) and
(CurTime() - self.LastSignalTime > 20.0) then
self:SendSignal("main",self:GetChannel())
end
-- Force signal
if self.LockedSignal then
self:SendSignal(self.LockedSignal,self:GetChannel())
end
end
-- Process logic
self:NextThink(CurTime() + 1.0)
if self.Name and self.Name ~= "" then
self:SetNW2String("ID",self.Name)
elseif self.TrackPosition then
--PrintTable(self.TrackPosition.node1)
self:SetNW2String("ID",self.TrackPosition.path.id.."/"..self.TrackPosition.node1.id)
end
return true
end
function ENT:GetSignal()
if self.InhibitSwitching and self.AlternateTrack then return 1 end
if self.AlternateTrack then return 3 end
return 0
end
|
if vim.b.did_ftp == true then
return
end
vim.opt_local.cursorline = true
vim.opt_local.cursorcolumn = false
vim.opt_local.number = false
vim.opt_local.relativenumber = false
vim.opt_local.statusline = ""
vim.o.laststatus = 0
|
local ObjectManager = require("managers.object.object_manager")
local QuestManager = require("managers.quest.quest_manager")
FsPhase2 = ScreenPlay:new {}
function FsPhase2:onLoggedIn(pPlayer)
local currentPhase = VillageJediManagerTownship:getCurrentPhase()
if (currentPhase == 2 and VillageJediManagerCommon.hasActiveQuestThisPhase(pPlayer)) then
self:failActiveTasks(pPlayer, true)
else
self:doPhaseChangeFails(pPlayer)
end
if (QuestManager.hasActiveQuest(pPlayer, QuestManager.quests.FS_PHASE_2_CRAFT_DEFENSES_MAIN) and not QuestManager.hasCompletedQuest(pPlayer, QuestManager.quests.FS_PHASE_2_CRAFT_DEFENSES_MAIN) and not VillageCommunityCrafting:isOnActiveCrafterList(pPlayer)) then
QuestManager.resetQuest(pPlayer, QuestManager.quests.FS_PHASE_2_CRAFT_DEFENSES_MAIN)
QuestManager.resetQuest(pPlayer, QuestManager.quests.FS_PHASE_2_CRAFT_DEFENSES_01)
QuestManager.resetQuest(pPlayer, QuestManager.quests.FS_PHASE_2_CRAFT_DEFENSES_02)
end
end
function FsPhase2:failActiveTasks(pPlayer, loggingIn)
if (FsReflex2:hasActiveFetch(pPlayer)) then
FsReflex2:resetTasks(pPlayer)
FsReflex2:failQuest(pPlayer)
end
if (FsSad:hasActiveNonReturnTask(pPlayer)) then
FsSad:despawnCamp(pPlayer)
if (not FsSad:hasExceededLimit(pPlayer) and loggingIn) then
FsSad:recreateCampIfDespawned(pPlayer)
end
end
end
function FsPhase2:doPhaseChangeFails(pPlayer)
FsReflex2:doPhaseChangeFail(pPlayer)
FsSad:doPhaseChangeFail(pPlayer)
end
function FsPhase2:onLoggedOut(pPlayer)
self:failActiveTasks(pPlayer, false)
end
|
object_tangible_furniture_house_cleanup_xeno_table = object_tangible_furniture_house_cleanup_shared_xeno_table:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_house_cleanup_xeno_table, "object/tangible/furniture/house_cleanup/xeno_table.iff")
|
local status_ok, null_ls = pcall(require, "null-ls")
if not status_ok then
return
end
local constants = require("core/constants")
local formatting = null_ls.builtins.formatting
local diagnostics = null_ls.builtins.diagnostics
null_ls.setup({
debug = false,
sources = {
-- HTML, CSS, JS, TS, Markdown, Yaml etc.
formatting.prettier.with({ extra_args = { "--tab-width", "4" } }),
-- HTML Linting
diagnostics.tidy,
-- Lua
formatting.stylua.with({
extra_args = {
"--column-width",
constants.LINE_LENGTH,
"--indent-width",
"4",
"--indent-type",
"Spaces",
},
}),
-- Python
diagnostics.flake8.with({
extra_args = { "--max-line-length", constants.LINE_LENGTH },
}),
formatting.black.with({
extra_args = { "--line-length", constants.LINE_LENGTH },
}),
formatting.isort.with({
extra_args = { "--line-length", constants.LINE_LENGTH },
}),
-- Shell
diagnostics.shellcheck,
diagnostics.zsh,
formatting.shellharden,
},
on_attach = function(client)
if client.resolved_capabilities.document_formatting then
vim.cmd([[
augroup LspFormatting
autocmd! * <buffer>
autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()
augroup END
]])
end
end,
})
|
local _, ns = ...
local B, C, L, DB, P = unpack(ns)
local M = P:GetModule("Misc")
local LSP = LibStub("LibShowUIPanel-1.0")
local ShowUIPanel = LSP.ShowUIPanel
local HideUIPanel = LSP.HideUIPanel
local MAX_NUM_TALENT_TIERS = _G.MAX_NUM_TALENT_TIERS or 10
local NUM_TALENT_COLUMNS = _G.NUM_TALENT_COLUMNS or 4
local MAX_NUM_TALENTS = _G.MAX_NUM_TALENTS or 40
local TALENT_BRANCH_TEXTURECOORDS = {
up = {
[1] = {0.12890625, 0.25390625, 0 , 0.484375},
[-1] = {0.12890625, 0.25390625, 0.515625 , 1.0}
},
down = {
[1] = {0, 0.125, 0, 0.484375},
[-1] = {0, 0.125, 0.515625, 1.0}
},
left = {
[1] = {0.2578125, 0.3828125, 0, 0.5},
[-1] = {0.2578125, 0.3828125, 0.5, 1.0}
},
right = {
[1] = {0.2578125, 0.3828125, 0, 0.5},
[-1] = {0.2578125, 0.3828125, 0.5, 1.0}
},
topright = {
[1] = {0.515625, 0.640625, 0, 0.5},
[-1] = {0.515625, 0.640625, 0.5, 1.0}
},
topleft = {
[1] = {0.640625, 0.515625, 0, 0.5},
[-1] = {0.640625, 0.515625, 0.5, 1.0}
},
bottomright = {
[1] = {0.38671875, 0.51171875, 0, 0.5},
[-1] = {0.38671875, 0.51171875, 0.5, 1.0}
},
bottomleft = {
[1] = {0.51171875, 0.38671875, 0, 0.5},
[-1] = {0.51171875, 0.38671875, 0.5, 1.0}
},
tdown = {
[1] = {0.64453125, 0.76953125, 0, 0.5},
[-1] = {0.64453125, 0.76953125, 0.5, 1.0}
},
tup = {
[1] = {0.7734375, 0.8984375, 0, 0.5},
[-1] = {0.7734375, 0.8984375, 0.5, 1.0}
},
}
local TALENT_ARROW_TEXTURECOORDS = {
top = {
[1] = {0, 0.5, 0, 0.5},
[-1] = {0, 0.5, 0.5, 1.0}
},
right = {
[1] = {1.0, 0.5, 0, 0.5},
[-1] = {1.0, 0.5, 0.5, 1.0}
},
left = {
[1] = {0.5, 1.0, 0, 0.5},
[-1] = {0.5, 1.0, 0.5, 1.0}
},
}
function M:TalentUI_CreatePanel(i)
local frame = CreateFrame("Frame", nil, self)
frame:SetSize(296, 572)
B.CreateBDFrame(frame, .2)
frame.__owner = self
frame.branches = {}
frame.buttons = {}
frame.brancheTextures = {}
frame.arrowTextures = {}
frame.talentTree = i
frame.talentButtonSize = 32
frame.initialOffsetX = 36
frame.initialOffsetY = 16
frame.buttonSpacingX = 63
frame.buttonSpacingY = 63
if P.IsClassic() then
frame.initialOffsetY = 36
frame:SetHeight(486)
end
local TopBG = frame:CreateTexture(nil, "BACKGROUND", nil, 1)
TopBG:SetPoint("TOPLEFT")
TopBG:SetPoint("TOPRIGHT")
TopBG:SetHeight(.775 * frame:GetHeight())
local BottomBG = frame:CreateTexture(nil, "BACKGROUND", nil, 1)
BottomBG:SetPoint("TOPLEFT", TopBG, "BOTTOMLEFT")
BottomBG:SetPoint("TOPRIGHT", TopBG, "BOTTOMRIGHT")
BottomBG:SetPoint("BOTTOMLEFT")
BottomBG:SetPoint("BOTTOMRIGHT")
BottomBG:SetTexCoord(0, 1, 0, 74 / 128)
local ArrowFrame = CreateFrame("Frame", nil, frame)
ArrowFrame:SetAllPoints()
ArrowFrame:SetFrameLevel(frame:GetFrameLevel() + 100)
local Label = frame:CreateFontString(nil, "OVERLAY")
Label:SetFont(DB.Font[1], 16, DB.Font[3])
Label:SetTextColor(1, .8, 0)
Label:SetPoint("BOTTOM", frame, "TOP", 0, 10)
frame.TopBG = TopBG
frame.BottomBG = BottomBG
frame.ArrowFrame = ArrowFrame
frame.Label = Label
for i = 1, MAX_NUM_TALENT_TIERS do
frame.branches[i] = {}
for j = 1, NUM_TALENT_COLUMNS do
frame.branches[i][j] = {
id = nil,
up = 0,
left = 0,
right = 0,
down = 0,
leftArrow = 0,
rightArrow = 0,
topArrow = 0,
}
end
end
return frame
end
local function Talent_OnClick(self, mouseButton)
if mouseButton == "LeftButton" then
if IsModifiedClick("CHATLINK") then
local link = GetTalentLink(self.__owner.talentTree, self:GetID())
if link then
ChatEdit_InsertLink(link)
end
else
LearnTalent(self.__owner.talentTree, self:GetID())
end
end
end
local function Talent_OnEnter(self)
GameTooltip:ClearLines()
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip:SetTalent(self.__owner.talentTree, self:GetID())
end
local function Talent_OnEvent(self, event, ...)
if GameTooltip:IsOwned(self) then
GameTooltip:SetTalent(self.__owner.talentTree, self:GetID())
end
end
function M:TalentUI_GetButton(i)
if not self.buttons[i] then
local button = CreateFrame("Button", nil, self, "ItemButtonTemplate")
button:SetID(i)
button.__owner = self
button:RegisterEvent("CHARACTER_POINTS_CHANGED")
button:SetScript("OnClick", Talent_OnClick)
button:SetScript("OnEvent", Talent_OnEvent)
button:SetScript("OnEnter", Talent_OnEnter)
button:SetScript("OnLeave", B.HideTooltip)
local Slot = button:CreateTexture(nil, "BACKGROUND")
Slot:SetSize(64, 64)
Slot:SetPoint("CENTER", 0, -1)
Slot:SetTexture([[Interface\Buttons\UI-EmptySlot-White]])
local RankBorder = button:CreateTexture(nil, "OVERLAY")
RankBorder:SetSize(32, 32)
RankBorder:SetPoint("CENTER", button, "BOTTOMRIGHT")
RankBorder:SetTexture([[Interface\TalentFrame\TalentFrame-RankBorder]])
local Rank = button:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
Rank:SetPoint("CENTER", RankBorder, "CENTER")
B.StripTextures(button)
button.icon:SetTexCoord(.08, .92, .08, .92)
B.CreateBDFrame(button.icon)
local hl = button:GetHighlightTexture()
hl:SetColorTexture(1, 1, 1, .25)
button.Slot = Slot
button.RankBorder = RankBorder
button.Rank = Rank
button.UpdateTooltip = Talent_OnEnter
self.buttons[i] = button
end
return self.buttons[i]
end
function M:TalentUI_SetArrowTexture(tier, column, texCoords, xOffset, yOffset)
local arrowTexture = M.TalentUI_GetArrowTexture(self)
arrowTexture:SetTexCoord(texCoords[1], texCoords[2], texCoords[3], texCoords[4])
arrowTexture:SetPoint("TOPLEFT", arrowTexture:GetParent(), "TOPLEFT", xOffset, yOffset)
end
function M:TalentUI_GetArrowTexture()
local texture = self.arrowTextures[self.arrowIndex]
if not texture then
texture = self.ArrowFrame:CreateTexture(nil, "BACKGROUND")
texture:SetSize(32, 32)
texture:SetTexture([[Interface\TalentFrame\UI-TalentArrows]])
self.arrowTextures[self.arrowIndex] = texture
end
self.arrowIndex = self.arrowIndex + 1
texture:Show()
return texture
end
function M:TalentUI_SetBranchTexture(tier, column, texCoords, xOffset, yOffset)
local branchTexture = M.TalentUI_GetBranchTexture(self)
branchTexture:SetTexCoord(texCoords[1], texCoords[2], texCoords[3], texCoords[4])
branchTexture:SetPoint("TOPLEFT", branchTexture:GetParent(), "TOPLEFT", xOffset, yOffset)
end
function M:TalentUI_GetBranchTexture()
local texture = self.brancheTextures[self.textureIndex]
if not texture then
texture = self:CreateTexture(nil, "ARTWORK")
texture:SetSize(32, 32)
texture:SetTexture([[Interface\TalentFrame\UI-TalentBranches]])
self.brancheTextures[self.textureIndex] = texture
end
self.textureIndex = self.textureIndex + 1
texture:Show()
return texture
end
function M:TalentUI_ResetArrowTextureCount()
self.arrowIndex = 1
end
function M:TalentUI_ResetBranchTextureCount()
self.textureIndex = 1
end
function M:TalentUI_GetArrowTextureCount()
return self.arrowIndex
end
function M:TalentUI_GetBranchTextureCount()
return self.textureIndex
end
function M:TalentUI_SetPrereqs(buttonTier, buttonColumn, forceDesaturated, tierUnlocked, ...)
local tier, column, isLearnable
local requirementsMet = tierUnlocked and not forceDesaturated
for i=1, select("#", ...), 3 do
tier, column, isLearnable = select(i, ...)
if ( not isLearnable or forceDesaturated ) then
requirementsMet = nil
end
M.TalentUI_DrawLines(self, buttonTier, buttonColumn, tier, column, requirementsMet)
end
return requirementsMet
end
function M:TalentUI_DrawLines(buttonTier, buttonColumn, tier, column, requirementsMet)
if requirementsMet then
requirementsMet = 1
else
requirementsMet = -1
end
if buttonColumn == column then
if buttonTier - tier > 1 then
for i = tier + 1, buttonTier - 1 do
if self.branches[i][buttonColumn].id then
P:Print("Error this layout is blocked vertically " .. self.branches[buttonTier][i].id)
return
end
end
end
for i = tier, buttonTier - 1 do
self.branches[i][buttonColumn].down = requirementsMet
if i + 1 <= buttonTier - 1 then
self.branches[i + 1][buttonColumn].up = requirementsMet
end
end
self.branches[buttonTier][buttonColumn].topArrow = requirementsMet
return
end
if buttonTier == tier then
local left = min(buttonColumn, column)
local right = max(buttonColumn, column)
if right - left > 1 then
for i = left + 1, right - 1 do
if self.branches[tier][i].id then
P:Print("there\"s a blocker " .. tier .. " " .. i)
return
end
end
end
for i = left, right - 1 do
self.branches[tier][i].right = requirementsMet
self.branches[tier][i + 1].left = requirementsMet
end
if buttonColumn < column then
self.branches[buttonTier][buttonColumn].rightArrow = requirementsMet
else
self.branches[buttonTier][buttonColumn].leftArrow = requirementsMet
end
return
end
local left = min(buttonColumn, column)
local right = max(buttonColumn, column)
if left == column then
left = left + 1
else
right = right - 1
end
local blocked = nil
for i = left, right do
if self.branches[tier][i].id then
blocked = 1
end
end
left = min(buttonColumn, column)
right = max(buttonColumn, column)
if not blocked then
self.branches[tier][buttonColumn].down = requirementsMet
self.branches[buttonTier][buttonColumn].up = requirementsMet
for i = tier, buttonTier - 1 do
self.branches[i][buttonColumn].down = requirementsMet
self.branches[i + 1][buttonColumn].up = requirementsMet
end
for i = left, right - 1 do
self.branches[tier][i].right = requirementsMet
self.branches[tier][i + 1].left = requirementsMet
end
self.branches[buttonTier][buttonColumn].topArrow = requirementsMet
return
end
if left == buttonColumn then
left = left + 1
else
right = right - 1
end
for i = left, right do
if self.branches[buttonTier][i].id then
P:Print("Error, this layout is undrawable " .. self.branches[buttonTier][i].id)
return
end
end
left = min(buttonColumn, column)
right = max(buttonColumn, column)
for i = tier, buttonTier - 1 do
self.branches[i][column].up = requirementsMet
self.branches[i + 1][column].down = requirementsMet
end
if buttonColumn < column then
self.branches[buttonTier][buttonColumn].rightArrow = requirementsMet
else
self.branches[buttonTier][buttonColumn].leftArrow = requirementsMet
end
end
function M:TalentUI_SetButtonLocation(tier, column, initialOffsetX, initialOffsetY, buttonSpacingX, buttonSpacingY)
column = (column - 1) * buttonSpacingX + initialOffsetX
tier = -(tier - 1) * buttonSpacingY - initialOffsetY
self:SetPoint("TOPLEFT", self:GetParent(), "TOPLEFT", column, tier)
end
function M:TalentUI_ResetBranches()
local node
for i = 1, MAX_NUM_TALENT_TIERS do
for j = 1, NUM_TALENT_COLUMNS do
node = self.branches[i][j]
node.id = nil
node.up = 0
node.down = 0
node.left = 0
node.right = 0
node.rightArrow = 0
node.leftArrow = 0
node.topArrow = 0
end
end
end
function M:TalentUI_Update()
local talentButtonSize = self.talentButtonSize
local initialOffsetX = self.initialOffsetX
local initialOffsetY = self.initialOffsetY
local buttonSpacingX = self.buttonSpacingX or (2 * talentButtonSize - 1)
local buttonSpacingY = self.buttonSpacingY or (2 * talentButtonSize - 1)
local base
local name, _, points, fileName = GetTalentTabInfo(self.talentTree)
if ( name ) then
base = "Interface\\TalentFrame\\"..fileName.."-"
else
base = "Interface\\TalentFrame\\MageFire-"
end
self.TopBG:SetTexture(base .. "TopLeft")
self.BottomBG:SetTexture(base .. "BottomLeft")
self.Label:SetText(format("%s: "..HIGHLIGHT_FONT_COLOR_CODE.."%d"..FONT_COLOR_CODE_CLOSE, name, points))
local numTalents = GetNumTalents(self.talentTree)
if numTalents > MAX_NUM_TALENTS then
P:Print("Too many talents in talent frame!")
end
M.TalentUI_ResetBranches(self)
local forceDesaturated, tierUnlocked
local unspentPoints = self.__owner.UnspentPoints
for i = 1, MAX_NUM_TALENTS do
local button = M.TalentUI_GetButton(self, i)
if i <= numTalents then
local name, iconTexture, tier, column, rank, maxRank, _, meetsPrereq = GetTalentInfo(self.talentTree, i)
if name and tier <= MAX_NUM_TALENT_TIERS then
button.Rank:SetText(rank)
M.TalentUI_SetButtonLocation(button, tier, column, initialOffsetX, initialOffsetY, buttonSpacingX, buttonSpacingY)
self.branches[tier][column].id = button:GetID()
if unspentPoints <= 0 and rank == 0 then
forceDesaturated = 1
else
forceDesaturated = nil
end
if(tier - 1) * 5 <= points then
tierUnlocked = 1
else
tierUnlocked = nil
end
SetItemButtonTexture(button, iconTexture)
local prereqsSet = M.TalentUI_SetPrereqs(self, tier, column, forceDesaturated, tierUnlocked, GetTalentPrereqs(self.talentTree, i))
if prereqsSet and meetsPrereq then
SetItemButtonDesaturated(button, nil)
button.RankBorder:Show()
button.RankBorder:SetVertexColor(1, 1, 1)
button.Rank:Show()
if rank < maxRank then
button.Rank:SetTextColor(GREEN_FONT_COLOR.r, GREEN_FONT_COLOR.g, GREEN_FONT_COLOR.b)
button.Slot:SetVertexColor(0.1, 1.0, 0.1)
else
button.Slot:SetVertexColor(1.0, 0.82, 0)
button.Rank:SetTextColor(NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b)
end
else
SetItemButtonDesaturated(button, 1)
button.Slot:SetVertexColor(0.5, 0.5, 0.5)
if rank == 0 then
button.RankBorder:Hide()
button.Rank:Hide()
else
button.RankBorder:SetVertexColor(0.5, 0.5, 0.5)
button.Rank:SetTextColor(GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b)
button.RankBorder:Show()
button.Rank:Show()
end
end
button:Show()
else
button:Hide()
end
else
if button then
button:Hide()
end
end
end
local node
local xOffset, yOffset
local ignoreUp
local tempNode
M.TalentUI_ResetBranchTextureCount(self)
M.TalentUI_ResetArrowTextureCount(self)
for i = 1, MAX_NUM_TALENT_TIERS do
for j = 1, NUM_TALENT_COLUMNS do
node = self.branches[i][j]
xOffset = ((j - 1) * buttonSpacingX) + initialOffsetX + 2
yOffset = -((i - 1) * buttonSpacingY) - initialOffsetY - 2
if node.id then
if node.up ~= 0 then
if not ignoreUp then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["up"][node.up], xOffset, yOffset + talentButtonSize)
else
ignoreUp = nil
end
end
if node.down ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["down"][node.down], xOffset, yOffset - talentButtonSize + 1)
end
if node.left ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["left"][node.left], xOffset - talentButtonSize, yOffset)
end
if node.right ~= 0 then
tempNode = self.branches[i][j+1]
if tempNode.left ~= 0 and tempNode.down < 0 then
M.TalentUI_SetBranchTexture(self, i, j-1, TALENT_BRANCH_TEXTURECOORDS["right"][tempNode.down], xOffset + talentButtonSize, yOffset)
else
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["right"][node.right], xOffset + talentButtonSize + 1, yOffset)
end
end
if node.rightArrow ~= 0 then
M.TalentUI_SetArrowTexture(self, i, j, TALENT_ARROW_TEXTURECOORDS["right"][node.rightArrow], xOffset + talentButtonSize / 2 + 5, yOffset)
end
if node.leftArrow ~= 0 then
M.TalentUI_SetArrowTexture(self, i, j, TALENT_ARROW_TEXTURECOORDS["left"][node.leftArrow], xOffset - talentButtonSize / 2 - 5, yOffset)
end
if node.topArrow ~= 0 then
M.TalentUI_SetArrowTexture(self, i, j, TALENT_ARROW_TEXTURECOORDS["top"][node.topArrow], xOffset, yOffset + talentButtonSize / 2 + 5)
end
else
if node.up ~= 0 and node.left ~= 0 and node.right ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["tup"][node.up], xOffset, yOffset)
elseif node.down ~= 0 and node.left ~= 0 and node.right ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["tdown"][node.down], xOffset, yOffset)
elseif node.left ~= 0 and node.down ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["topright"][node.left], xOffset, yOffset)
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["down"][node.down], xOffset , yOffset - 32)
elseif node.left ~= 0 and node.up ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["bottomright"][node.left], xOffset, yOffset)
elseif node.left ~= 0 and node.right ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["right"][node.right], xOffset + talentButtonSize, yOffset)
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["left"][node.left], xOffset + 1, yOffset)
elseif node.right ~= 0 and node.down ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["topleft"][node.right], xOffset, yOffset)
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["down"][node.down], xOffset , yOffset - 32)
elseif node.right ~= 0 and node.up ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["bottomleft"][node.right], xOffset, yOffset)
elseif node.up ~= 0 and node.down ~= 0 then
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["up"][node.up], xOffset, yOffset)
M.TalentUI_SetBranchTexture(self, i, j, TALENT_BRANCH_TEXTURECOORDS["down"][node.down], xOffset , yOffset - 32)
ignoreUp = 1
end
end
end
end
for i = M.TalentUI_GetBranchTextureCount(self), #self.brancheTextures do
self.brancheTextures[i]:Hide()
end
for i = M.TalentUI_GetArrowTextureCount(self), #self.arrowTextures do
self.arrowTextures[i]:Hide()
end
end
function M:TalentUI_UpdateAll()
if not M.TalentUI or not M.TalentUI:IsShown() then return end
local unspentPoints = UnitCharacterPoints("player")
M.TalentUI.Points:SetText(format(CHARACTER_POINTS1_COLON..HIGHLIGHT_FONT_COLOR_CODE.."%d"..FONT_COLOR_CODE_CLOSE, unspentPoints))
M.TalentUI.UnspentPoints = unspentPoints
for i = 1, 3 do
M.TalentUI_Update(M.TalentUI.panels[i])
end
end
function M:TalentUI_Toggle(expand)
if expand then
M.TalentUI:Show()
HideUIPanel(PlayerTalentFrame)
else
M.TalentUI:Hide()
ShowUIPanel(PlayerTalentFrame)
end
M.db["ExpandTalent"] = expand
end
function M:TalentUI_Init()
local frame = CreateFrame("Frame", "NDuiPlusTalentFrame", UIParent)
tinsert(UISpecialFrames, "NDuiPlusTalentFrame")
frame:SetSize(922, 640)
frame:SetPoint("CENTER")
frame:SetFrameLevel(10)
B.SetBD(frame)
B.CreateMF(frame)
frame:Hide()
frame:SetScript("OnShow", function()
PlaySound(SOUNDKIT.TALENT_SCREEN_OPEN)
M.TalentUI_UpdateAll()
end)
frame:SetScript("OnHide", function()
PlaySound(SOUNDKIT.TALENT_SCREEN_CLOSE)
end)
if P.IsClassic() then
frame:SetHeight(554)
end
local Close = CreateFrame("Button", nil, frame)
B.ReskinClose(Close)
Close:SetScript("OnClick", function()
frame:Hide()
end)
frame.Close = Close
local Expand = CreateFrame("Button", nil, frame)
Expand:SetPoint("RIGHT", Close, "LEFT", -3, 0)
B.ReskinArrow(Expand, "down")
Expand:SetScript("OnClick", function()
M:TalentUI_Toggle(false)
end)
frame.Expand = Expand
local Points = frame:CreateFontString(nil, "OVERLAY")
Points:SetFont(DB.Font[1], 16, DB.Font[3])
Points:SetTextColor(1, .8, 0)
Points:SetPoint("BOTTOM", frame, "BOTTOM", 0, 8)
frame.Points = Points
local aleEmu = _G.__ala_meta__ and _G.__ala_meta__.emu
if aleEmu then
local CalcButton = P.CreateButton(frame, 70, 20, aleEmu.L.TalentFrameCallButtonFontString)
CalcButton:SetPoint("BOTTOMRIGHT", -16, 6)
CalcButton:SetScript("OnClick", function() aleEmu.Emu_Create() end)
frame.CalcButton = CalcButton
end
frame.panels = {}
for i = 1, 3 do
frame.panels[i] = M.TalentUI_CreatePanel(frame, i)
if i == 1 then
frame.panels[i]:SetPoint("TOPLEFT", 16, -36)
else
frame.panels[i]:SetPoint("TOPLEFT", frame.panels[i-1], "TOPRIGHT", C.mult, 0)
end
end
M.TalentUI = frame
end
function M:TalentUI_Load()
P:Delay(.5,function()
for i = 1, MAX_NUM_TALENTS do
local talent = _G["PlayerTalentFrameTalent"..i]
if talent then
local hl = talent:GetHighlightTexture()
hl:SetColorTexture(1, 1, 1, .25)
end
end
end)
if M.db["EnhancedTalentUI"] then
local bu = CreateFrame("Button", nil, PlayerTalentFrame)
bu:SetPoint("RIGHT", PlayerTalentFrameCloseButton, "LEFT", -3, 0)
B.ReskinArrow(bu, "right")
bu:SetScript("OnClick", function()
M:TalentUI_Toggle(true)
end)
end
end
P:AddCallbackForAddon("Blizzard_TalentUI", M.TalentUI_Load)
function M:EnhancedTalentUI()
if not M.db["EnhancedTalentUI"] then return end
_G.ToggleTalentFrame = function()
if M.db["ExpandTalent"] then
B:TogglePanel(M.TalentUI)
else
if PlayerTalentFrame:IsShown() then
HideUIPanel(PlayerTalentFrame)
else
ShowUIPanel(PlayerTalentFrame)
end
end
end
if not IsAddOnLoaded("Blizzard_TalentUI") then
UIParentLoadAddOn("Blizzard_TalentUI")
end
M:TalentUI_Init()
B:RegisterEvent("CHARACTER_POINTS_CHANGED", M.TalentUI_UpdateAll)
B:RegisterEvent("SPELLS_CHANGED", M.TalentUI_UpdateAll)
end
M:RegisterMisc("EnhancedTalentUI", M.EnhancedTalentUI) |
data:extend(
{
{
type = "item-subgroup",
name = "uranium-fuel-dissolution", --Fuel-reprocessing stuff
group = "uranium",
order = "f",
},
{
type = "item-subgroup",
name = "uranium-fuel-reprocessing", --Fuel-reprocessing stuff
group = "uranium",
order = "g",
},
{
type = "item-subgroup",
name = "uranium-prefluids", --slurries, fluorine, pre-fuel-reprocessing stuff
group = "uranium",
order = "eab",
},
{
type = "item-subgroup",
name = "uranium-fuel-reprocessing-fluids", --UF6 stuff
group = "uranium",
order = "ec",
},
{
type = "item-subgroup",
name = "thorium-chain", --lftr stuff
group = "uranium",
order = "ec",
}
}) |
local ffi = require 'ffi'
local qconsts = require 'Q/UTILS/lua/q_consts'
local cmem = require 'libcmem'
local Scalar = require 'libsclr'
local Dnn = require 'libdnn'
local register_type = require 'Q/UTILS/lua/register_type'
local qc = require 'Q/UTILS/lua/qcore'
local get_ptr = require 'Q/UTILS/lua/get_ptr'
local get_network_structure =
require 'Q/RUNTIME/DNN/lua/aux/get_network_structure'
local get_dropout_per_layer =
require 'Q/RUNTIME/DNN/lua/aux/get_dropout_per_layer'
local get_activation_functions =
require 'Q/RUNTIME/DNN/lua/aux/get_activation_functions'
local get_ptrs_to_data =
require 'Q/RUNTIME/DNN/lua/aux/get_ptrs_to_data'
local release_ptrs_to_data =
require 'Q/RUNTIME/DNN/lua/aux/release_ptrs_to_data'
local chk_data = require 'Q/RUNTIME/DNN/lua/aux/chk_data'
local set_data = require 'Q/RUNTIME/DNN/lua/aux/set_data'
--====================================
local lDNN = {}
--[[
__index metamethod tells about necessary action/provision, when a absent field is called from table.
Below line indicates, whenever any method get called using 'dnn' object (e.g "dnn:fit()"),
here 'dnn' is object/table returned from new() method, the method/key will be searched in lDNN table.
If we comment below line then the methods/fields like 'fit' or 'check' will not be available for 'dnn' object
]]
lDNN.__index = lDNN
--[[
'__call' metamethod allows you to treat a table like a function.
e.g lDNN(mode, Xin, Xout, params)
above call is similar to lDNN.new(mode, Xin, Xout, params)
for more info, please refer sam.lua in the same directory
]]
setmetatable(lDNN, {
__call = function (cls, ...)
return cls.new(...)
end,
})
register_type(lDNN, "lDNN")
-- -- TODO Indrajeet to change WHAT IS THIS????
-- local original_type = type -- saves `type` function
-- -- monkey patch type function
-- type = function( obj )
-- local otype = original_type( obj )
-- if otype == "table" and getmetatable( obj ) == lDNN then
-- return "lDNN"
-- end
-- return otype
-- end
function lDNN.new(params)
local dnn = setmetatable({}, lDNN)
--[[ we could have written previous line as follows
local dnn = {}
setmetatable(dnn, lDNN)
--]]
-- for meta data stored in dnn
-- Get structure of network, # of layers and # of neurons per layer
local nl, npl, c_npl = get_network_structure(params)
--=========== get dropout per layer; 0 means no drop out
local dpl, c_dpl = get_dropout_per_layer(params, nl)
--==========================================
local afns = get_activation_functions(params, nl)
--==========================================
dnn._dnn = assert(Dnn.new(nl, c_npl, c_dpl, afns))
-- TODO: Should we maintain all the meta data on C side?
dnn._npl = npl -- neurons per layer for Lua
dnn._c_npl = c_npl -- neurons per layer for C
dnn._dpl = dpl -- dropout per layer for Lua
dnn._c_dpl = c_dpl -- dropout per layer for C
dnn._nl = nl -- num layers
dnn._num_epochs = 0
if ( qconsts.debug ) then dnn:check() end
return dnn
end
function lDNN:fit(num_epochs)
if ( qconsts.debug ) then self:check() end
if ( not num_epochs ) then
num_epochs = 1
else
assert( ( type(num_epochs) == "number") and
( num_epochs >= 1 ) )
end
local dnn = self._dnn
local lXin = self._lXin
local lXout = self._lXout
local lptrs_in = self._lptrs_in
local lptrs_out = self._lptrs_out
local num_instances = self._num_instances
assert(self._bsz, "batch size not set")
local total = 0
for i = 1, num_epochs do
local start_t = qc.RDTSC()
-- TODO Need to randomly permute data before each epoch
local cptrs_in = get_ptrs_to_data(lptrs_in, lXin)
local cptrs_out = get_ptrs_to_data(lptrs_out, lXout)
-- TODO Pass read only data to fpass and bprop
assert(Dnn.train(dnn, lptrs_in, lptrs_out, num_instances))
-- WRONG: assert(Dnn.bprop(dnn, lptrs_in, lptrs_out, num_instances))
release_ptrs_to_data(lXin)
release_ptrs_to_data(lXout)
local end_t = qc.RDTSC()
total = total + tonumber(end_t - start_t)
print("Iteration " .. i .. " time = " .. tostring(tonumber(end_t - start_t)))
end
print("Total Training time for " .. num_epochs .. " iteation = " .. total)
self._num_epochs = self._num_epochs + num_epochs
if ( qconsts.debug ) then self:check() end
return true
end
function lDNN:predict(in_table)
local start_t = qc.RDTSC()
if ( qconsts.debug ) then self:check() end
assert(type(in_table) == "table")
local n_scalars = 0
for k, v in pairs(in_table) do
assert(type(v) == "Scalar")
assert(v:fldtype() == "F4")
n_scalars = n_scalars + 1;
end
local dnn = self._dnn
-- prepare input using input scalars
local sz = ffi.sizeof("float *") * n_scalars
local lptrs = cmem.new(sz)
local cptrs = get_ptr(lptrs)
cptrs = ffi.cast("float **", cptrs)
for k, v in pairs(in_table) do
local data = v:to_cmem()
cptrs[k-1] = get_ptr(data, "F4")
end
local end_t = qc.RDTSC()
local set_io_t = tonumber(end_t - start_t)
local start_t = qc.RDTSC()
local out = assert(Dnn.test(dnn, lptrs))
local end_t = qc.RDTSC()
local test_t = tonumber(end_t - start_t)
if ( qconsts.debug ) then self:check() end
return Scalar.new(out, "F4"), test_t, set_io_t
end
function lDNN:check()
local chk = Dnn.check(self._dnn)
assert(chk, "Internal error")
return true
end
function lDNN:set_io(Xin, Xout)
if ( qconsts.debug ) then self:check() end
local ncols_in, nrows_in = chk_data(Xin)
local ncols_out, nrows_out = chk_data(Xout)
assert(nrows_in == nrows_out)
assert(nrows_in > 0)
local lXin, lptrs_in = set_data(Xin, "in")
local lXout, lptrs_out = set_data(Xout, "out")
local npl = self._npl
local nl = self._nl
assert(ncols_in == npl[1] )
assert(ncols_out == npl[nl])
assert(ncols_out == 1) -- TODO: Assumption to be relaxed
--==========================================
self._lXin = lXin -- copy of input data
self._lXout = lXout -- copy of output data
self._num_instances = nrows_in
self._lptrs_in = lptrs_in -- C pointers to input data
self._lptrs_out = lptrs_out -- C pointers to output data
if ( qconsts.debug ) then self:check() end
return self
end
local function release_vectors(X)
if ( X ) then
for _, v in ipairs(X) do
v:delete()
end
end
X = nil
end
function lDNN:unset_io()
release_vectors(self._lXin)
release_vectors(self._lXout)
self._num_instances = nil
self._lptrs_in = nil
self._lptrs_out = nil
end
function lDNN:set_batch_size(bsz)
if ( qconsts.debug ) then self:check() end
assert( ( bsz) and ( type(bsz) == "number") and ( bsz >= 1 ) )
if ( self._bsz ) then
assert(Dnn.unset_bsz(self._dnn))
self._bsz = nil
end
assert(Dnn.set_bsz(self._dnn, bsz))
self._bsz = bsz
if ( qconsts.debug ) then self:check() end
return self
end
function lDNN:unset_batch_size()
if ( qconsts.debug ) then self:check() end
assert(Dnn.unset_bsz(self._dnn))
self._bsz = nil
if ( qconsts.debug ) then self:check() end
return self
end
function lDNN:delete()
lDNN:unset_io()
end
return lDNN
|
--[[
Pong
"Low-Res update"
-- Main Program --
]]
-- push is a library that will allow us to draw our game at a virtual
-- resolution, instead of however large our window is; used to provide
-- a more retro aesthetic
--
-- https://github.com/Ulydev/push
push = require 'push'
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 720
VIRTUAL_WIDTH = 432
VIRTUAL_HEIGHT = 243
--check for LOVE v11
IS_LOVE11 = love.getVersion() == 11
function love.load()
-- use nearest-neighbor filtering on upscaling and downscaling to prevent blurring of text
-- and graphics; try removing this function to see the difference!
love.graphics.setDefaultFilter('nearest', 'nearest')
smallFont = love.graphics.newFont('font.ttf', 8)
-- set LOVE2D's active font to the smallFont object
love.graphics.setFont(smallFont)
-- initialize our virtual resolution, which will be rendered within our
-- actual window no matter its dimensions; replaces our love.window.setMode call
-- from the last example
push:setupScreen(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, WINDOW_WIDTH, WINDOW_HEIGHT, {
fullscreen = false,
resizable = false,
vsync = true
})
end
--[[
Keyboard handling, called by LOVE2d each from;
passes in the key we pressed so we can access
]]
function love.keypressed(key)
--keys can be accessed by string name
if key == 'escape' then
-- function LOVE gives us to terminate application
love.event.quit()
end
end
--[[
Called after update by LOVE2D, used to draw anything to the screen, updated or otherwise.
]]
function love.draw()
-- begin rendering at virtual resolution
push:apply('start')
-- clear the screen with a specific color; in this case, a color similar
-- to some versions of the original Pong
--[[
LOVE 11 changed how color value ranges work
]]
local r, g, b, a =
(IS_LOVE11 and 40 / 255) or 40,
(IS_LOVE11 and 45 / 255) or 45,
(IS_LOVE11 and 52 / 255) or 52,
(IS_LOVE11 and 255 / 255) or 255
love.graphics.clear(r, g, b, a)
-- condensed onto one line from last example
-- note we are now using virtual width and height now for text placement
love.graphics.printf('Hello Pong!', 0, VIRTUAL_HEIGHT / 2 - 6, VIRTUAL_WIDTH, 'center')
--
--paddles are simply rectangles we draw on the screen at certain points,
-- as is the ball
--
-- render left paddle
love.graphics.rectangle('fill', 10, 30, 5, 20)
-- render right paddle
love.graphics.rectangle('fill', VIRTUAL_WIDTH - 10, VIRTUAL_HEIGHT - 50, 5, 20)
--render ball (center)
love.graphics.rectangle('fill', VIRTUAL_WIDTH / 2 - 2, VIRTUAL_HEIGHT / 2 - 2, 4, 4)
-- end rendering at virtual resolution
push:apply('end')
end
|
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local ffi_cdef = ffi.cdef
local ffi_load = ffi.load
local ffi_typeof = ffi.typeof
local ffi_sizeof = ffi.sizeof
local tonumber = tonumber
local assert = assert
local upper = string.upper
local type = type
ffi_cdef [[
typedef uint16_t utf16_t;
typedef uint32_t unicode_t;
typedef int64_t off_t;
size_t utf8envlocale();
size_t utf8len(const char* text);
size_t utf8toupper(const char* input, size_t inputSize, char* target, size_t targetSize, size_t locale, int32_t* errors);
size_t utf8tolower(const char* input, size_t inputSize, char* target, size_t targetSize, size_t locale, int32_t* errors);
size_t utf8totitle(const char* input, size_t inputSize, char* target, size_t targetSize, size_t locale, int32_t* errors);
size_t utf8casefold(const char* input, size_t inputSize, char* target, size_t targetSize, size_t locale, int32_t* errors);
size_t utf16toutf8(const utf16_t* input, size_t inputSize, char* target, size_t targetSize, int32_t* errors);
size_t utf32toutf8(const unicode_t* input, size_t inputSize, char* target, size_t targetSize, int32_t* errors);
size_t widetoutf8(const wchar_t* input, size_t inputSize, char* target, size_t targetSize, int32_t* errors);
size_t utf8toutf16(const char* input, size_t inputSize, utf16_t* target, size_t targetSize, int32_t* errors);
size_t utf8toutf32(const char* input, size_t inputSize, unicode_t* target, size_t targetSize, int32_t* errors);
size_t utf8towide(const char* input, size_t inputSize, wchar_t* target, size_t targetSize, int32_t* errors);
uint8_t utf8isnormalized(const char* input, size_t inputSize, size_t flags, size_t* offset);
size_t utf8iscategory(const char* input, size_t inputSize, size_t flags);
size_t utf8normalize(const char* input, size_t inputSize, char* target, size_t targetSize, size_t flags, int32_t* errors);
const char* utf8seek(const char* text, size_t textSize, const char* textStart, off_t offset, int direction);
]]
local lib = ffi_load "utf8rewind"
local errors = ffi_new "int32_t[1]"
local offset = ffi_new "size_t[1]"
local char_t = ffi_typeof "char[?]"
local utf16t = ffi_typeof "utf16_t[?]"
local unicod = ffi_typeof "unicode_t[?]"
local wchart = ffi_typeof "wchar_t[?]"
local FORM = {
C = 1,
NFC = 1,
D = 2,
NFD = 2,
KC = 5,
NFKC = 5,
KD = 6,
NFKD = 6
}
local CATEGORY = {
LETTER_UPPERCASE = 1,
LETTER_LOWERCASE = 2,
LETTER_TITLECASE = 4,
LETTER_MODIFIER = 8,
CASE_MAPPED = 7,
LETTER_OTHER = 16,
LETTER = 31,
MARK_NON_SPACING = 32,
MARK_SPACING = 64,
MARK_ENCLOSING = 128,
MARK = 224,
NUMBER_DECIMAL = 256,
NUMBER_LETTER = 512,
NUMBER_OTHER = 1024,
NUMBER = 1792,
PUNCTUATION_CONNECTOR = 2048,
PUNCTUATION_DASH = 4096,
PUNCTUATION_OPEN = 8192,
PUNCTUATION_CLOSE = 16384,
PUNCTUATION_INITIAL = 32768,
PUNCTUATION_FINAL = 65536,
PUNCTUATION_OTHER = 131072,
PUNCTUATION = 260096,
SYMBOL_MATH = 262144,
SYMBOL_CURRENCY = 524288,
SYMBOL_MODIFIER = 1048576,
SYMBOL_OTHER = 2097152,
SYMBOL = 3932160,
SEPARATOR_SPACE = 4194304,
SEPARATOR_LINE = 8388608,
SEPARATOR_PARAGRAPH = 16777216,
SEPARATOR = 29360128,
CONTROL = 33554432,
FORMAT = 67108864,
SURROGATE = 134217728,
PRIVATE_USE = 268435456,
UNASSIGNED = 536870912,
COMPATIBILITY = 1073741824,
ISUPPER = 1073741825,
ISLOWER = 1073741826,
ISALPHA = 1073741855,
ISDIGIT = 1073743616,
ISALNUM = 1073743647,
ISPUNCT = 1077934080,
ISGRAPH = 1077935903,
ISSPACE = 1077936128,
ISPRINT = 1107296031,
ISCNTRL = 1107296256,
ISXDIGIT = 1342179072,
ISBLANK = 1346371584,
IGNORE_GRAPHEME_CLUSTER = 2147483648
}
local function process(input, func, locale, target_t, flags)
local t = target_t or char_t
local l = type(input) == "cdata" and ffi_sizeof(input) or #input
local s
if flags then
s = lib[func](input, l, nil, 0, flags, errors)
else
s = locale and lib[func](input, l, nil, 0, locale, errors) or lib[func](input, l, nil, 0, errors)
end
if errors[0] == 0 then
local target = ffi_new(t, s)
if flags then
s = lib[func](input, l, target, s, flags, errors)
else
s = locale and lib[func](input, l, target, s, locale, errors) or lib[func](input, l, target, s, errors)
end
if errors[0] == 0 then
if target_t then
return target, tonumber(s)
else
return ffi_str(target, s), tonumber(s)
end
end
end
return nil, errors[0]
end
local utf8rewind = {}
function utf8rewind.utf8len (input) return tonumber(lib.utf8len(input)) end
function utf8rewind.utf8toupper (input, locale) return process(input, "utf8toupper", locale) end
function utf8rewind.utf8tolower (input, locale) return process(input, "utf8tolower", locale) end
function utf8rewind.utf8totitle (input, locale) return process(input, "utf8totitle", locale) end
function utf8rewind.utf8casefold (input, locale) return process(input, "utf8casefold", locale) end
function utf8rewind.utf16toutf8 (input) return process(input, "utf16toutf8") end
function utf8rewind.utf32toutf8 (input) return process(input, "utf32toutf8") end
function utf8rewind.widetoutf8 (input) return process(input, "widetoutf8") end
function utf8rewind.utf8toutf16 (input) return process(input, "utf8toutf16", nil, utf16t) end
function utf8rewind.utf8toutf32 (input) return process(input, "utf8toutf32", nil, unicod) end
function utf8rewind.utf8towide (input) return process(input, "utf8towide", nil, wchart) end
function utf8rewind.utf8normalize(input, flags)
flags = flags or FORM.C
if type(flags) == "string" then
flags = FORM[flags]
end
assert(type(flags) == "number", "Invalid normalization flags supplied.")
return process(input, "utf8normalize", nil, nil, flags)
end
function utf8rewind.utf8isnormalized(input, flags)
flags = flags or FORM.C
if type(flags) == "string" then
flags = FORM[upper(flags)]
end
assert(type(flags) == "number", "Invalid normalization flags supplied.")
local r = lib.utf8isnormalized(input, #input, flags, offset)
local n = tonumber(offset[0]) + 1
if r == 0 then
return true, true, n
elseif r == 2 then
return false, false, n
else
return false, true, n
end
end
function utf8rewind.utf8iscategory(input, flags)
if type(flags) == "string" then
flags = CATEGORY[upper(flags)]
end
assert(type(flags) == "number", "Invalid category flags supplied.")
local l = #input
local r = tonumber(lib.utf8iscategory(input, l, flags))
if l == r then
return true
else
return false, r + 1
end
end
function utf8rewind.utf8seek(input, offset, direction)
return ffi_str(lib.utf8seek(input, #input, input, offset or 0, direction and 2 or 0))
end
function utf8rewind.utf8envlocale()
return tonumber(lib.utf8envlocale())
end
utf8rewind.form = FORM
utf8rewind.category = CATEGORY
return utf8rewind |
--- === hs.speech ===
---
--- This module provides access to the Speech Synthesizer component of OS X.
---
--- The speech synthesizer functions and methods provide access to OS X's Text-To-Speech capabilities and facilitates generating speech output both to the currently active audio device and to an AIFF file.
---
--- A discussion concerning the embedding of commands into the text to be spoken can be found at https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/SpeechSynthesisProgrammingGuide/FineTuning/FineTuning.html#//apple_ref/doc/uid/TP40004365-CH5-SW6. It is somewhat dated and specific to the older MacinTalk style voices, but still contains some information relevant to the more modern higer quality voices as well in its discussion about embedded commands.
--- === hs.speech.listener ===
---
--- This module provides access to the Speech Recognizer component of OS X.
---
--- The speech recognizer functions and methods provide a way to add commands which may be issued to Hammerspoon through spoken words and phrases to trigger a callback.
local module = require("hs.speech.internal")
module.listener = require("hs.speech.listener")
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
-- Return speech Object --------------------------------------------------
return module
|
MaskedNoiseModule = {}
setmetatable(MaskedNoiseModule, { __index = Module })
function MaskedNoiseModule:new(multiplier, mask_min_threshold, mask_max_threshold, smooth)
local instance = Module:new()
instance.noise = nil
instance.noise_mask = nil
instance.map = nil
instance.map_mask = nil
instance.param_mask_max_threshold = mask_max_threshold
instance.param_mask_min_threshold = mask_min_threshold
instance.param_multiplier = multiplier
instance.param_smooth = smooth
setmetatable(instance, self)
self.__index = self
return instance
end
function MaskedNoiseModule:init(noise_manager)
error("MaskedNoiseModule:init(noise_manager) needs to be implemented!")
end
function MaskedNoiseModule:init_map(x, z, support)
self.map = self.noise:get2dMap({ x = x, y = z })
self.map = arrayutil.swapped_reindex2d(self.map, x, z)
self.map_mask = self.noise_mask:get2dMap({ x = x, y = z })
self.map_mask = arrayutil.swapped_reindex2d(self.map_mask, x, z)
end
function MaskedNoiseModule:get(x, z, value, info)
local mask_val = mathutil.clamp(self.map_mask[x][z], -1, 1)
if mask_val >= self.param_mask_min_threshold and mask_val <= self.param_mask_max_threshold then
local val = self.map[x][z]
val = transform.linear(val)
if self.param_smooth then
val = val * transform.linear(mask_val, self.param_mask_min_threshold, self.param_mask_max_threshold)
end
val = val * self.param_multiplier
return value + val, info
end
return value, info
end
|
-- data/maps/forward.lua : Learn to go forward
local Map = {
size = {
width = 13,
height = 11,
},
components = {
'wall',
'box_closed',
'grass',
'exit',
},
data = {
{ 1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1 },
{ 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1 },
{ 1, 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1, 1 },
{ 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1 },
{ 1, 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1, 1 },
{ 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1 },
{ 1, 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1, 1 },
{ 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1 },
{ 1, 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 1, 1 },
{ 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
},
artifacts = {
default = 3,
},
positions = {
start = { 7, 6 },
exit = { 7, 1 },
},
story =
[[You gotta learn to move forward!
hint: Type "forward" once and click Run. Or maybe 5 times?]],
}
-- example to add artifacts:
-- Map.artifacts[3] = {}
-- Map.artifacts[3][4] = 1
return Map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.