content
stringlengths 5
1.05M
|
---|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )
ENT.Models = { "models/props_debris/concrete_column001a_chunk01.mdl",
"models/props_debris/concrete_column001a_chunk02.mdl",
"models/props_debris/concrete_column001a_chunk03.mdl",
"models/props_debris/concrete_column001a_chunk04.mdl",
"models/props_debris/concrete_chunk01b.mdl",
"models/props_debris/concrete_chunk02a.mdl",
"models/props_debris/concrete_chunk03a.mdl",
"models/props_debris/concrete_chunk06d.mdl",
"models/props_debris/concrete_chunk07a.mdl",
"models/props_debris/concrete_chunk08a.mdl",
"models/props_debris/concrete_chunk09a.mdl",
"models/props_debris/concrete_spawnchunk001a.mdl",
"models/props_debris/concrete_spawnchunk001b.mdl",
"models/props_debris/concrete_spawnchunk001e.mdl",
"models/props_debris/concrete_spawnchunk001f.mdl",
"models/props_wasteland/rockgranite03a.mdl",
"models/props_wasteland/rockgranite03b.mdl",
"models/props_wasteland/rockgranite03c.mdl",
"models/props_junk/Rock001a.mdl" }
ENT.BumpSounds = { Sound( "ambient/materials/metal4.wav" ),
Sound( "ambient/levels/canals/critter5.wav" ),
Sound( "ambient/machines/station_train_squeel.wav" ) }
function ENT:Initialize()
self.Entity:SetModel( table.Random( self.Models ) )
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
local phys = self.Entity:GetPhysicsObject()
if IsValid( phys ) then
phys:SetMaterial( "wood" )
phys:Wake()
end
self.Entity:StartMotionController()
self.Active = false
self.Distance = math.random( 100, 400 )
self.Scale = math.Rand( 10, 20 )
end
function ENT:SpawnFunction( ply, tr )
if ( !tr.Hit ) then return end
local SpawnPos = tr.HitPos + tr.HitNormal * 16
local ent = ents.Create( self.ClassName )
ent:SetPos( SpawnPos )
ent:Spawn()
ent:Activate()
timer.Simple( 1800, function() ent:Remove() end )
return ent
end
function ENT:GetRadiationRadius()
return 100
end
function ENT:PhysicsSimulate( phys, delta )
if not self.Active then return SIM_NOTHING end
if self.ReActivate then
self.ReActivate = false
phys:ApplyForceCenter( Vector( 0, 0, 1 ) * ( phys:GetMass() * self.Scale ) )
end
local trace = {}
trace.start = self.Entity:GetPos()
trace.endpos = trace.start + Vector( 0, 0, -1000 )
trace.filter = self.Entity
local tr = util.TraceLine( trace )
local dist = tr.HitPos:Distance( tr.StartPos )
local scale = math.Clamp( 150 - dist, 0.25, 150 ) / 150
if tr.Hit then
phys:ApplyForceCenter( tr.HitNormal * ( phys:GetMass() * ( scale * self.Scale ) ) )
end
end
function ENT:Think()
local active = false
for k,v in pairs( player.GetAll() ) do
if v:GetPos():Distance( self.Entity:GetPos() ) < 2000 then
active = true
end
end
self.Active = active
if active == false then
self.ReActivate = true
else
local phys = self.Entity:GetPhysicsObject()
if IsValid( phys ) then
phys:Wake()
end
end
end
function ENT:OnTakeDamage( dmg )
if dmg:GetAttacker():IsPlayer() then
local phys = self.Entity:GetPhysicsObject()
if IsValid( phys ) then
phys:ApplyForceCenter( VectorRand() * ( phys:GetMass() * self.Scale * 2 ) )
end
if math.random(1,10) == 1 then
self.Entity:EmitSound( table.Random( self.BumpSounds ), 100, math.random( 140, 180 ) )
end
end
end
function ENT:PhysicsCollide( data, phys )
if data.HitEntity:IsPlayer() then
//data.HitEntity:SetBleeding( true )
data.HitEntity:TakeDamage( 0, self.Entity )
end
if data.DeltaTime > 0.15 and math.random(1,10) == 1 then
self.Entity:EmitSound( table.Random( self.BumpSounds ), 100, math.random( 100, 150 ) )
end
end
function ENT:Use( ply, caller )
end
-- Called when a player attempts to use a tool.
function ENT:CanTool(player, trace, tool)
return false;
end;
function ENT:OnPhysgunReload(entity, player)
return false;
end;
|
-- supporting testfile; belongs to 'cl_spec.lua'
nothing here, it should just fail when it is being compiled.
|
PERK.name = "Medic (Intelligence)"
PERK.description = "Treating wounds."
PERK.shortname = "Medic (INT)"
PERK.parent = "intelligence"
|
qjs_inc_dir = path.getabsolute("../../deps/txiki.js/deps/quickjs/include")
qjs_lib_dir = path.getabsolute("../../deps/txiki.js/deps/quickjs/include")
workspace "qjs"
configurations { "release" }
location "gen"
symbols "On"
optimize "Off"
project "test"
kind "SharedLib"
language "C++"
files {"gen/**.cpp"}
includedirs { qjs_inc_dir, ".." }
libdirs { qjs_lib_dir }
filter { "kind:StaticLib" }
links { "quickjs" }
filter { "kind:SharedLib" }
defines { "JS_SHARED_LIBRARY" }
filter { "kind:SharedLib", "system:macosx" }
linkoptions { "-undefined dynamic_lookup" }
|
object_draft_schematic_chemistry_component_shared_stimpack_load_charger = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/chemistry/component/shared_stimpack_load_charger.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_chemistry_component_shared_stimpack_load_charger, "object/draft_schematic/chemistry/component/shared_stimpack_load_charger.iff")
------------------------------------------------------------------------------------------------------------------------------------
|
slot4 = import(slot1)
slot1 = class(".Effect", "EffectProduce")
slot1.ctor = function (slot0)
slot3 = slot0
slot0.super.ctor(slot2)
slot4 = DNTGLK_EFFECT_TYPE.PRODUCE
slot0.SetEffectType(slot2, slot0)
slot0.m_nParamCount = 4
end
slot1.GetParamSize = function (slot0)
return slot0.m_nParamCount
end
slot1.Execute = function (slot0, slot1, slot2, slot3, slot4)
if slot1 == nil or slot4 then
return 0, slot3
end
return 0, slot3
end
return slot1
|
local log=require 'log'
local sched = require 'sched'
local socket = require 'socket'
--local pipes = require 'pipes'
local streams = require 'stream'
--get locals for some useful things
local setmetatable, ipairs, table, type = setmetatable, ipairs, table, type
local CHUNK_SIZE = 1480 --65536
local recvt, sendt={}, {}
local sktds = setmetatable({}, { __mode = 'k' })
local M = {}
-- streams for incomming data
local read_streams = setmetatable({}, { __mode = 'k' })
---------------------------------------
-- replace sched's default get_time and idle with luasocket's
sched.get_time = socket.gettime
sched.idle = socket.sleep
-- pipe for async writing
--local write_pipes = setmetatable({}, weak_key)
--local outstanding_data = setmetatable({}, weak_key)
local unregister = function (fd)
local sktd = sktds[fd]
if not sktd then return end
for i=1, #recvt do
if recvt[i] == fd then
table.remove(recvt, i)
break
end
end
if sendt[fd] then
for i=1, #sendt do
if sendt[i] == fd then
table.remove(sendt, i)
sendt[fd] = nil
break
end
end
sktd.write_stream = nil
sktd.outstanding_data = nil
end
read_streams [sktd] = nil
sktd.partial = nil
sktds[fd] = nil
end
local function handle_incomming(sktd, data)
if sktd.handler then
local ok, errcall = pcall(sktd.handler, sktd, data)
if not ok then
log('SELECTOR', 'ERROR', 'Handler died with "%s"', tostring(errcall))
sktd:close()
elseif not errcall then
sktd:close()
end
elseif read_streams[sktd] then
read_streams[sktd]:write(data)
else
sched.signal(sktd.events.data, data)
end
end
local function handle_incomming_error(sktd, err)
err = err or 'fd closed'
if sktd.handler then
local ok, errcall = pcall(sktd.handler,sktd, nil, err)
elseif read_streams[sktd] then
read_streams[sktd]:write(nil, err)
else
sched.signal(sktd.events.data, nil, err)
end
end
local function send_from_pipe (fd)
local sktd = sktds[fd]
local out_data = sktd.outstanding_data
if out_data then
local data, next_pos = out_data.data, out_data.last+1
local last, err, lasterr = fd:send(data, next_pos, next_pos+CHUNK_SIZE )
if last == #data then
-- all the oustanding data sent
sktd.outstanding_data = nil
return
elseif err == 'closed' then
sktd:close()
handle_incomming_error(sktd, 'error writing:'..tostring(err))
return
end
sktd.outstanding_data.last = last or lasterr
else
local streamd = sktd.write_stream ; if not streamd then return end
if streamd.len>0 then
local data, serr = streamd:read()
local last , err, lasterr = fd:send(data, 1, CHUNK_SIZE)
if err == 'closed' then
sktd:close()
handle_incomming_error(sktd, 'error writing:'..tostring(err))
return
end
last = last or lasterr
if last < #data then
sktd.outstanding_data = {data=data,last=last}
end
else
--emptied the outgoing pipe, stop selecting to write
for i=1, #sendt do
if sendt[i] == fd then
table.remove(sendt, i)
sendt[fd] = nil
break
end
end
sched.signal(sktd.events.async_finished)
end
end
end
local init_sktd = function(sktdesc)
sktdesc.send_sync = M.send_sync
sktdesc.send = M.send
sktdesc.send_async = M.send_async
sktdesc.getsockname = M.getsockname
sktdesc.getpeername = M.getpeername
sktdesc.close = M.close
return sktdesc
end
local register_server = function (sktd)
sktd.isserver=true
sktd.fd:settimeout(0)
sktds[sktd.fd] = sktd
--normalize_pattern(skt_table.pattern)
--sktmode[sktd] = pattern
recvt[#recvt+1]=sktd.fd
end
local register_client = function (sktd)
sktd.fd:settimeout(0)
sktds[sktd.fd] = sktd
recvt[#recvt+1]=sktd.fd
end
local step = function (timeout)
local recvt_ready, sendt_ready, err_accept = socket.select(recvt, sendt, timeout)
if err_accept~='timeout' then
for _, fd in ipairs(sendt_ready) do
send_from_pipe(fd)
end
for _, fd in ipairs(recvt_ready) do
local sktd = sktds[fd]
--if sktd then
local pattern=sktd.pattern
if sktd.isserver then
local client, err=fd:accept()
if client then
local skt_table_client = {
fd=client,
--task=module_task,
events={data=client},
pattern=pattern,
}
local insktd = init_sktd(skt_table_client)
if sktd.handler=='stream' then
local s = streams.new()
read_streams[insktd] = s
insktd.stream = s
else
skt_table_client.handler = sktd.handler
end
print ('>>', sched.running_task)
sched.signal(sktd.events.accepted, insktd)
register_client(insktd)
else
sched.signal(sktd.events.accepted, nil, err)
end
else
if type(pattern) == "number" and pattern <= 0 then
local data,err,part = fd:receive(CHUNK_SIZE)
data = data or part
if err=='closed' then
sktd:close()
handle_incomming_error(sktd, err)
elseif data then
handle_incomming(sktd, data)
end
else
local data,err,part = fd:receive(pattern,sktd.partial)
sktd.partial=part
if data then
handle_incomming(sktd, data)
elseif err=='closed' then
sktd:close()
handle_incomming_error(sktd, err)
end
end
--end
end
end
end
end
---------------------------------------
local normalize_pattern = function(pattern)
if pattern=='*l' or pattern=='line' then
return '*l'
end
if tonumber(pattern) and tonumber(pattern)>0 then
return pattern
end
if not pattern or pattern == '*a'
or (tonumber(pattern) and tonumber(pattern)<=0) then
return 0 --'*a'
end
log('SELECTOR', 'WARN', 'Could not normalize pattern "%s"', tostring(pattern))
end
M.init = function()
M.new_tcp_server = function (locaddr, locport, pattern, handler)
--address, port, backlog, pattern)
local sktd=init_sktd({
fd=assert(socket.bind(locaddr, locport)),
--task=module_task,
pattern=normalize_pattern(pattern),
handler = handler,
})
sktd.events = {accepted=sktd.fd}
if sktd.pattern=='*l' and handler == 'stream' then sktd.pattern=nil end
register_server(sktd)
return sktd
end
M.new_tcp_client = function (address, port, locaddr, locport, pattern, handler)
--address, port, locaddr, locport, pattern)
local sktd=init_sktd({
fd=assert(socket.connect(address, port, locaddr, locport)),
--task=module_task,
pattern=normalize_pattern(pattern),
handler = handler,
})
sktd.events = {data=sktd.fd, async_finished={}}
if sktd.pattern=='*l' and handler == 'stream' then sktd.pattern=nil end
register_client(sktd)
return sktd
end
M.new_udp = function ( address, port, locaddr, locport, pattern, handler)
--address, port, locaddr, locport, count)
local sktd=init_sktd({
fd=socket.udp(),
--task=module_task,
pattern=pattern,
handler = handler,
})
sktd.events = {data=sktd.fd, async_finished={}}
sktd.fd:setsockname(locaddr or '*', locport or 0)
sktd.fd:setpeername(address or '*', port)
register_client(sktd)
return sktd
end
M.close = function(sktd)
unregister(sktd.fd)
sktd.fd:close()
end
M.send_sync = function(sktd, data)
local start, err,done=0, nil, nil
while true do
start, err=sktd.fd:send(data,start+1)
done = start==#data
if done or err then
break
else
sched.wait()
end
end
return done, err, start
end
M.send = M.send_sync
M.send_async = function (sktd, data)
--make sure we're selecting to write
local skt=sktd.fd
if not sendt[skt] then
sendt[#sendt+1] = skt
sendt[skt]=true
end
local streamd = sktd.write_stream
-- initialize the pipe on first send
if not streamd then
streamd = streams.new(M.ASYNC_SEND_BUFFER)
sktd.write_stream = streamd
end
streamd:write(data)
sched.wait()
end
M.new_fd = function ()
return nil, 'Not supported by luasocket'
end
M.getsockname = function(sktd)
return sktd.fd:getsockname()
end
M.getpeername = function(sktd)
return sktd.fd:getpeername()
end
M.task=sched.run(function ()
while true do
local _, t, _ = sched.wait()
print('>', sched.running_task, t)
step( t )
end
end)
--[[
M.register_server = service.register_server
M.register_client = service.register_client
M.unregister = service.unregister
--]]
return M
end
return M
|
workspace "hardpython"
configurations { "Debug", "Release" }
project "hardpython"
kind "WindowedApp"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
links { "SDL2", "dl" }
files { "**.h", "**.cpp" }
--[[postbuildcommands {
"{COPY} content/* bin/%{cfg.buildcfg}/content"
}--]]
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
|
-- ---------------------------------------------
-- Shader.lua 2014/06/05
-- Copyright (c) 2013-2014 Jun Mizutani,
-- released under the MIT open source license.
-- ---------------------------------------------
local ffi = require("ffi")
local gl = require("gles2")
require("Object")
Shader = Object:new()
function Shader.new(self)
local obj = Object.new(self)
obj.program = 0
return obj
end
Shader.vShaderSrc = ""
Shader.fShaderSrc = ""
function Shader.loadShader(self, type, shaderSource)
local shader = gl.createShader(type)
if shader == 0 then
local shaderType = "FRAGMENT_SHADER"
if type == gl.VERTEX_SHADER then
shaderType = "VERTEX_SHADER"
end
util.printf("glCreateShader: %s failed.\n", shaderType)
return 0
end
local CharP = ffi.typeof("const char*")
local CharPP = ffi.typeof("const char* [1]")
local cp = CharP(shaderSource)
local cpp = CharPP(cp)
gl.shaderSource(shader, 1, cpp, nil)
gl.compileShader(shader)
local compiled = ffi.new("uint32_t[1]")
gl.getShaderiv(shader, gl.COMPILE_STATUS, compiled)
if compiled[0] == 0 then
local infoLen = ffi.new("uint32_t[1]")
gl.getShaderiv(shader, gl.INFO_LOG_LENGTH, infoLen)
if (infoLen[0] > 0) then
local infoLog = ffi.new("char[?]", infoLen[0])
gl.getShaderInfoLog(shader, infoLen[0], nil, infoLog)
util.printf("Error compiling shader: %s\n", infoLog)
end
gl.deleteShader(shader)
return 0
end
return shader
end
function Shader.initShaders(self)
local vShader = self:loadShader(gl.VERTEX_SHADER, self.vShaderSrc)
local fShader = self:loadShader(gl.FRAGMENT_SHADER, self.fShaderSrc)
local prog = gl.createProgram()
self.program = prog
if prog == 0 then
self.program = 0
util.printf("Failed to create program.\n")
return false
end
gl.attachShader(prog, vShader)
gl.attachShader(prog, fShader)
gl.linkProgram(prog)
local linked = ffi.new("uint32_t[1]")
gl.getProgramiv(prog, gl.LINK_STATUS, linked)
if linked[0] == 0 then
local infoLen = ffi.new("uint32_t[1]")
gl.getProgramiv(prog, gl.INFO_LOG_LENGTH, infoLen)
if infoLen[0] > 0 then
local infoLog = ffi.new("char[?]", infoLen[0])
gl.getProgramInfoLog(prog, infoLen[0], nil, infoLog)
util.printf("Error linking program: %s\n", infoLog[0])
assert()
end
gl.deleteProgram(prog)
return false
end
gl.deleteShader(vShader)
gl.deleteShader(fShader)
return prog
end
function Shader.setDefaultParam(self, key, value)
self.default[key] = value
end
function Shader.updateParam(self, param, key, updateFunc)
local function compare(table1, table2)
if table1 == table2 then return true end -- identical table
if #table1 ~= #table2 then return false end
for i=1, #table1 do
if table1[i] ~= table2[i] then return false end
end
return true -- same contents
end
if (param[key] ~= nil) then
self.change[key] = param[key]
updateFunc(self, param[key])
else
local c = self.change
if c[key] ~= nil then
local d = self.default
if type(d[key]) == "table" then
if compare(c[key], d[key]) == false then
c[key] = d[key]
end
elseif c[key] ~= d[key] then
c[key] = d[key]
updateFunc(self, d[key])
end
end
end
end
function Shader.initShaderParameter(self)
end
function Shader.doParameter(self, param)
end
function Shader.useProgram(self)
gl.useProgram(self.program)
end
function Shader.init(self)
self.status = self:initShaders()
self:initShaderParameter()
end
|
function Print(param)
reaper.ShowConsoleMsg(param.."\n")
end
track = reaper.GetSelectedTrack(0, 0) -- Get current track
if track ~= nil then
Print("")
local track_name, track_flags = reaper.GetTrackState(track)
Print("Track Name: " .. track_name)
Print("Track Flags: " .. track_flags)
local value = reaper.GetMediaTrackInfo_Value(track, "I_RECMON") -- Track record monitor -- 0.0 or 1.0 or 2.0
Print("Track record monitor: " .. value)
value = reaper.GetMediaTrackInfo_Value(track, "D_PAN") -- Track pan -- -1.0 to 1.0
Print("Track pan: " .. value)
value = reaper.GetMediaTrackInfo_Value(track, "D_VOL") -- Track volume
Print("Track volume: " .. value)
value = reaper.GetMediaTrackInfo_Value(track, "I_RECARM") -- Track arm -- 0.0 or 1.0
Print("Track arm: " .. value)
value = reaper.GetMediaTrackInfo_Value(track, "I_SOLO") -- Track solo -- 0.0 or 2.0
Print("Track solo: " .. value)
value = reaper.GetMediaTrackInfo_Value(track, "B_MUTE") -- Track mute -- 0.0 or 1.0
Print("Track mute: " .. value)
value = reaper.GetTrackColor(track) -- Track color
Print("Track color: " .. value)
-- Toggle track arm
value = reaper.GetMediaTrackInfo_Value(track, "I_RECARM")
if value == 1.0 then
reaper.SetMediaTrackInfo_Value(track, "I_RECARM", 0.0)
else
reaper.SetMediaTrackInfo_Value(track, "I_RECARM", 1.0)
end
else
Print("")
Print("No track selected")
end
|
local function fails(str, exp)
local ok, err = loadstring("return " .. str, "=x")
assert(not ok)
if err ~= exp then error(("Expected %s,\n got %s"):format(exp, err), 2) end
end
local function ok(str)
assert(loadstring("return " .. str, "=x"))
end
fails("1a", "x:1: malformed number near '1a'")
fails("0..0", "x:1: malformed number near '0..0'")
ok("1")
ok("0xff")
ok("0XFF")
ok("1e-23+3")
|
util.AddNetworkString("ixVoiceMenu")
function PLUGIN:InitializedPlugins()
RunConsoleCommand("mp_show_voice_icons", "0")
end
function PLUGIN:PlayerLoadedCharacter(client, character)
timer.Simple(0.25, function()
client:SetLocalVar("voiceRange", 2)
end)
end
/*
function PLUGIN:ShowSpare1(client)
if (client:GetCharacter()) then
netstream.Start(client, "ixVoiceMenu")
end
end
*/
|
local K, C = unpack(select(2, ...))
local _G = _G
local table_insert = _G.table.insert
table_insert(C.defaultThemes, function()
if not C["Skins"].WorldMap then
return
end
local WorldMapFrame = _G.WorldMapFrame
WorldMapFrame.BorderFrame:Hide()
WorldMapZoneDropDown:Hide()
WorldMapContinentDropDown:Hide()
WorldMapZoneMinimapDropDown:Hide()
WorldMapZoomOutButton:Hide()
WorldMapMagnifyingGlassButton:Hide()
WorldMapFrame:SetHitRectInsets(-20, -20, 38, 0)
WorldMapFrame:SetClampedToScreen(false)
local NewBorder = CreateFrame("Frame", nil, WorldMapFrame.ScrollContainer)
NewBorder:SetPoint("TOPLEFT", 6, -6)
NewBorder:SetPoint("BOTTOMRIGHT", -6, 6)
NewBorder:CreateBorder(nil, nil, C["General"].BorderStyle.Value ~= "KkthnxUI_Pixel" and 32 or nil, nil, nil, nil, nil, nil, nil, "", nil, nil, nil, nil, nil, nil, nil, false)
WorldMapFrameCloseButton:SetFrameLevel(10)
WorldMapFrameCloseButton:SetSize(34, 34)
WorldMapFrameCloseButton:ClearAllPoints()
WorldMapFrameCloseButton:SetPoint("TOPRIGHT", WorldMapFrame, "TOPRIGHT", -10, -68)
WorldMapFrameCloseButton:SkinCloseButton()
C_Timer.After(5, function()
if Questie_Toggle then
-- Hide original toggle button
Questie_Toggle:Hide()
-- Create our own button
local QuestButton = CreateFrame("Button", nil, WorldMapFrame)
QuestButton:SetSize(18, 18)
QuestButton:SetPoint("TOPRIGHT", -50, -76)
QuestButton:SetFrameLevel(WorldMapFrameCloseButton:GetFrameLevel())
QuestButton:SetScript("OnClick", function()
PlaySound(825)
Questie_Toggle:Click()
end)
QuestButton:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT", -1, 5)
GameTooltip:AddLine("Toggle Questie")
GameTooltip:Show()
end)
QuestButton:SetScript("OnLeave", K.HideTooltip)
QuestButton:SkinButton()
QuestButton.Texture = QuestButton.Texture or QuestButton:CreateTexture(nil, "OVERLAY")
QuestButton.Texture:SetSize(18, 18)
QuestButton.Texture:SetPoint("CENTER")
QuestButton.Texture:SetTexture([[Interface\AddOns\Questie\Icons\available]])
end
end)
end)
|
--Fixes all local bugged sleepers in adventure mode.
--[====[
adv-fix-sleepers
================
Fixes :bug:`6798`. This bug is characterized by sleeping units who refuse to
awaken in adventure mode regardless of talking to them, hitting them, or waiting
so long you die of thirst. If you come accross one or more bugged sleepers in
adventure mode, simply run the script and all nearby sleepers will be cured.
Usage::
adv-fix-sleepers
]====]
--========================
-- Author: ArrowThunder on bay12 & reddit
-- Version: 1.1
--=======================
-- get the list of all the active units currently loaded
local active_units = df.global.world.units.active -- get all active units
-- check every active unit for the bug
local num_fixed = 0 -- this is the number of army controllers fixed, not units
-- I've found that often, multiple sleepers share a bugged army controller
for k, unit in pairs(active_units) do
if unit then
local army_controller = df.army_controller.find(unit.enemy.army_controller_id)
if army_controller and army_controller.type == 4 then -- sleeping code is possible
if army_controller.unk_64.t4.unk_2.not_sleeping == false then
army_controller.unk_64.t4.unk_2.not_sleeping = true -- fix bug
num_fixed = num_fixed + 1
end
end
end
end
if num_fixed == 0 then
print ("No sleepers with the fixable bug were found, sorry.")
else
print ("Fixed " .. num_fixed .. " bugged army_controller(s).")
end
|
Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
ESX = nil
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
while ESX.GetPlayerData().job == nil do
Citizen.Wait(100)
end
ESX.PlayerData = ESX.GetPlayerData()
end)
-- INFOS
function DrawMissionText(msg, time)
ClearPrints()
SetTextEntry_2('STRING')
AddTextComponentString(msg)
DrawSubtitleTimed(time, 1)
end
function KnockDoor(door)
local plyPed = PlayerPedId()
TaskGoStraightToCoord(plyPed, door.x, door.y, door.z, 10.0, 10, door.w, 0.5)
Wait(1000)
ClearPedTasksImmediately(plyPed)
while not HasAnimDictLoaded("timetable@jimmy@doorknock@") do
RequestAnimDict("timetable@jimmy@doorknock@")
Citizen.Wait(0)
end
TaskPlayAnim(plyPed, "timetable@jimmy@doorknock@", "knockdoor_idle", 8.0, 8.0, -1, 4, 0, 0, 0, 0 )
Citizen.Wait(0)
while IsEntityPlayingAnim(plyPed, "timetable@jimmy@doorknock@", "knockdoor_idle", 3) do
Citizen.Wait(0)
end
ClearPedTasksImmediately(plyPed)
end
function BuyField(location, price)
ESX.TriggerServerCallback('asEnoughMoney', function(enoughMoney)
if enoughMoney then
SetBlipAndNotif(location)
else
ESX.ShowNotification("T'as cru j'étais ta salope? Reviens quand tu auras de l'argent")
end
end, price)
end
function BuyProcess(location, price)
ESX.TriggerServerCallback('asEnoughMoney', function(enoughMoney)
if enoughMoney then
SetBlipAndNotif(location)
ESX.ShowAdvancedNotification(
'Gars de la street',
'',
"Yo man si tu veux voir la suite, t'auras besoin de ~y~oim~s~", 'CHAR_DEFAULT', 1)
else
ESX.ShowNotification("T'as cru j'étais ta salope? Reviens quand tu auras de l'argent")
end
end, price)
end
function SetBlipAndNotif(location)
local newLocation = {x = (location.x + math.random(-150,150)), y = (location.y + math.random(-150,150)), z = location.z}
local nearStreet = GetStreetNameFromHashKey(GetStreetNameAtCoord(newLocation.x, newLocation.y, newLocation.z))
zoneBlip = AddBlipForRadius(newLocation.x, newLocation.y, newLocation.z, 400.0)
SetBlipSprite(zoneBlip,9)
SetBlipColour(zoneBlip,1)
SetBlipAlpha(zoneBlip,95)
DrawMissionText("Tu trouveras ce que tu cherches près de ~y~"..nearStreet.."~s~.", 5000)
end
|
--This file should contain all commands meant to be used by mappings.
local vim = vim
local fs = require('neo-tree.sources.filesystem')
local fs_actions = require('neo-tree.sources.filesystem.fs_actions')
local utils = require('neo-tree.utils')
local M = {}
M.add = function(state)
local tree = state.tree
local node = tree:get_node()
if node.type == 'file' then
node = tree:get_node(node:get_parent_id())
end
fs_actions.create_node(node:get_id(), function()
fs.show_new_children(node)
end)
end
M.clear_filter = function(state)
fs.reset_search(true)
end
---Marks node as copied, so that it can be pasted somewhere else.
M.copy_to_clipboard = function(state)
local node = state.tree:get_node()
state.clipboard = state.clipboard or {}
local existing = state.clipboard[node.id]
if existing and existing.action == "copy" then
state.clipboard[node.id] = nil
else
state.clipboard[node.id] = { action = "copy", node = node }
print("Copied " .. node.name .. " to clipboard")
end
fs.redraw()
end
---Marks node as cut, so that it can be pasted (moved) somewhere else.
M.cut_to_clipboard = function(state)
local node = state.tree:get_node()
state.clipboard = state.clipboard or {}
local existing = state.clipboard[node.id]
if existing and existing.action == "cut" then
state.clipboard[node.id] = nil
else
state.clipboard[node.id] = { action = "cut", node = node }
print("Cut " .. node.name .. " to clipboard")
end
fs.redraw()
end
M.show_debug_info = function(state)
print(vim.inspect(state))
end
---Pastes all items from the clipboard to the current directory.
M.paste_from_clipboard = function(state)
if state.clipboard then
local at_node = state.tree:get_node()
local folder = at_node:get_id()
if at_node.type == "file" then
folder = at_node:get_parent_id()
end
for _, item in pairs(state.clipboard) do
if item.action == "copy" then
fs_actions.copy_node(item.node.path, folder .. utils.path_separator .. item.node.name)
elseif item.action == "cut" then
fs_actions.move_node(item.node.path, folder .. utils.path_separator .. item.node.name)
end
end
state.clipboard = nil
fs.refresh()
-- open the folder so the user can see the new files
local node = state.tree:get_node(folder)
if not node then
print("Could not find node for " .. folder)
return
end
fs.show_new_children(node)
end
end
M.delete = function(state)
local tree = state.tree
local node = tree:get_node()
fs_actions.delete_node(node.path, fs.refresh)
end
---Shows the filter input, which will filter the tree.
M.filter_as_you_type = function(state)
require("neo-tree.sources.filesystem.filter").show_filter(state, true)
end
---Shows the filter input, which will filter the tree.
M.filter_on_submit = function(state)
require("neo-tree.sources.filesystem.filter").show_filter(state, false)
end
---Navigate up one level.
M.navigate_up = function(state)
local parent_path, _ = utils.split_path(state.path)
if state.search_pattern then
fs.reset_search(false)
end
fs.navigate(parent_path)
end
local open_with_cmd = function(state, open_cmd)
local tree = state.tree
local node = tree:get_node()
if node.type == 'directory' then
fs.toggle_directory()
return nil
else
if state.window.position == "right" then
vim.cmd("wincmd t")
else
vim.cmd("wincmd w")
end
vim.cmd(open_cmd .. " " .. node:get_id())
end
end
M.open = function(state)
open_with_cmd(state, "e")
end
M.open_split = function(state)
open_with_cmd(state, "split")
end
M.open_vsplit = function(state)
open_with_cmd(state, "vsplit")
end
M.refresh = fs.refresh
M.rename = function(state)
local tree = state.tree
local node = tree:get_node()
fs_actions.rename_node(node.path, fs.refresh)
end
M.set_root = function(state)
local tree = state.tree
local node = tree:get_node()
if node.type == 'directory' then
if state.search_pattern then
fs.reset_search(false)
end
fs.navigate(node.id)
end
end
---Toggles whether hidden files are shown or not.
M.toggle_hidden = function(state)
state.show_hidden = not state.show_hidden
fs.show()
end
---Toggles whether the tree is filtered by gitignore or not.
M.toggle_gitignore = function(state)
state.respect_gitignore = not state.respect_gitignore
fs.show()
end
return M
|
local Side = require 'actors/side'
local State = require 'states/state'
require 'colors'
require 'buttons'
local Menu = {}
for k, v in pairs(State) do Menu[k] = v end
Menu.__index = Menu
setmetatable(Menu, {
__index = State,
__call = function (cls, ...)
local self = setmetatable({}, cls)
self:_new(...)
return self
end,
})
function Menu:_new(x, y, width, height, colorLeft, colorRight, font)
State._new(self, x, y, width, height, "menu")
self.centerWidth = width / 2
self.centerHeight = height / 2
self.leftTextColor = grayscaleContrastColor(colorLeft, 166)
self.rightTextColor = grayscaleContrastColor(colorRight, 166)
self.font = font
self.labels = { left = "NEW GAME", right = "SETTINGS" }
self.sides = {
left = Side(0, 0, self.centerWidth, self.height, colorLeft),
right = Side(self.centerWidth, 0, self.centerWidth, self.height, colorRight)
}
self.choice = nil
end
function Menu:update(dt)
if self.choice == GlobalStates.settings then self:setNext(GlobalStates.settings)
elseif self.choice == GlobalStates.game then self:setNext(GlobalStates.game)
end
end
function Menu:mousepressed(x, y, button, isTouch)
if button == 1 then
if x < self.centerWidth then self.choice = GlobalStates.game
elseif x > self.centerWidth then self.choice = GlobalStates.settings
end
end
end
function Menu:changeColors()
self.sides.left.color = randomColor()
self.sides.right.color = randomColor()
self.leftTextColor = grayscaleContrastColor(self.sides.left.color, 166)
self.rightTextColor = grayscaleContrastColor(self.sides.right.color, 166)
end
function Menu:draw()
love.graphics.setFont(self.font)
self.sides.left:draw()
self.sides.right:draw()
love.graphics.setColor(self.leftTextColor)
love.graphics.printf("NEW GAME", self.x, self.centerHeight - self.font:getHeight() / 2, self.centerWidth, "center")
love.graphics.setColor(self.rightTextColor)
love.graphics.printf("SETTINGS", self.centerWidth, self.centerHeight - self.font:getHeight() / 2, self.centerWidth, "center")
end
return Menu
|
local os_utils = require("nvdope.utils.os")
for exe, _ in pairs(Cfg.nvdope.dependencies) do
if (os_utils.assert_executable(exe)) then
print("NVDope [EH1]: The dependency " .. exe .. " was not found. Make sure you do have it installed and is available in your $PATH")
end
end
|
local find = require('modutram.helper.find')
describe('find', function ()
it ('finds value in a table', function ()
local table1 = { 2, 4, 6, 8 }
local table2 = { a = 1, b = 2, c = 3}
assert.are.equal(2, find(table1, 4))
assert.are.equal('b', find(table2, 2))
assert.is_nil(find(table1, 7))
assert.is_nil(find(table2, 6))
end)
end)
|
local actions = {}
local atexit
if _VERSION >= 'Lua 5.2' then
atexit = function (fn)
actions[#actions+1] = setmetatable({}, { __gc = fn })
end
else
local newproxy = newproxy
local debug = debug
local assert = assert
local setmetatable = setmetatable
local function gc(fn)
local p = assert(newproxy())
assert(debug.setmetatable(p, { __gc = fn }))
return p
end
atexit = function (fn)
actions[#actions+1] = gc(fn)
end
end
return atexit
|
--[[--------------------------------------------------------------------------
--
-- File: UTActivity.Ui.Title.lua
-- Copyright (c) Ubisoft Entertainment. All rights reserved.
--
-- Project: Ubitoys.Tag
-- Date: July 26, 2010
--
------------------------------------------------------------------------------
--
-- Description: ...
--
----------------------------------------------------------------------------]]
--[[ Dependencies ----------------------------------------------------------]]
require "Ui/UIMenuWindow"
--[[ Class -----------------------------------------------------------------]]
UTActivity.Ui = UTActivity.Ui or {}
UTActivity.Ui.Title = UTClass(UIMenuWindow)
UTActivity.Ui.Title.textRules = {
font = UIComponent.fonts.default,
fontColor = UIComponent.colors.gray,
fontJustificationleft = quartz.system.drawing.justification.topleft + quartz.system.drawing.justification.wordbreak,
fontJustificationcenter = quartz.system.drawing.justification.center + quartz.system.drawing.justification.wordbreak,
-- 96, 33, 396, 58
rectangle = { 20, 70, 640, 260 },
}
UTActivity.Ui.Title.textScoring = {
font = UIComponent.fonts.header,
fontColor = UIComponent.colors.red,
fontJustification = quartz.system.drawing.justification.center + quartz.system.drawing.justification.wordbreak,
-- 96, 33, 396, 58
rectangle = { 20, 70, 640, 210 },
}
UTActivity.Ui.Title.scoringOffset = 0
-- __ctor --------------------------------------------------------------------
function UTActivity.Ui.Title:__ctor(...)
assert(activity)
-- animate
self.slideBegin = game.settings.UiSettings.slideBegin
self.slideEnd = game.settings.UiSettings.slideEnd
-- window settings
self.uiWindow.title = l "titlemen002"
-- client area
self.uiPanel = self.uiWindow:AddComponent(UIPanel:New(), "uiMultiComponent")
self.uiPanel.rectangle = self.uiWindow.clientRectangle
self.uiPanel.rectangle[1] = self.uiPanel.rectangle[1] + UIComponent.metrics.windowMargin.left
self.uiPanel.rectangle[2] = self.uiPanel.rectangle[2] + UIComponent.metrics.windowMargin.top
self.uiPanel.rectangle[3] = self.uiPanel.rectangle[3] - UIComponent.metrics.windowMargin.right
self.uiPanel.rectangle[4] = self.uiPanel.rectangle[4] - UIComponent.metrics.windowMargin.bottom
-- first panel : rules description
self.uiRulesPanel = self.uiPanel:AddComponent(UITitledPanel:New(), "uiRulesPanel")
self.uiRulesPanel.title = activity.name
self.uiRulesPanel.rectangle = { 30, 30, 685, 280 }
if (activity.bitmap) then
local background = self.uiRulesPanel:AddComponent(UIBitmap:New(activity.bitmap))
local scale = (self.uiRulesPanel.rectangle[4] - self.uiRulesPanel.rectangle[2]) / background.rectangle[4]
background.rectangle = {
0.5 * (self.uiRulesPanel.rectangle[3] - self.uiRulesPanel.rectangle[1] - background.rectangle[3] * scale),
self.uiRulesPanel.rectangle[2],
self.uiRulesPanel.rectangle[3] - 0.5 * (self.uiRulesPanel.rectangle[3] - self.uiRulesPanel.rectangle[1] - background.rectangle[3] * scale),
self.uiRulesPanel.rectangle[4],
}
background.Draw = function (self)
quartz.system.drawing.loadcolor4f(1.0, 1.0, 1.0, 0.125)
quartz.system.drawing.loadtexture(self.bitmap)
quartz.system.drawing.drawtexture(unpack(self.rectangle))
end
end
-- second panel : rules description
self.uiScoringPanel = self.uiPanel:AddComponent(UITitledPanel:New(), "uiRulesPanel")
self.uiScoringPanel.title = l "titlemen003"
self.uiScoringPanel.rectangle = { 30, 310, 685, 430 }
-- buttons,
-- uiButton1:
-- exit activity and get back to title screen
self.uiButton1 = self:AddComponent(UIButton:New(), "uiButton1")
self.uiButton1.rectangle = UIMenuWindow.buttonRectangles[1]
self.uiButton1.text = l"but003"
self.uiButton1.tip = l"tip006"
self.uiButton1.OnAction = function (_self)
quartz.framework.audio.loadsound("base:audio/ui/back.wav")
quartz.framework.audio.loadvolume(game.settings.audio["volume:sfx"])
quartz.framework.audio.playsound()
if (activity.advertised) then game:PostStateChange("title")
else game:PostStateChange("selector")
end
end
-- uiButton5:
-- settings, but don't get there if there aren't any ...
self.uiButton5 = self:AddComponent(UIButton:New(), "uiButton5")
self.uiButton5.text = l"but006"
self.uiButton5.tip = l"tip016"
self.uiButton5.rectangle = UIMenuWindow.buttonRectangles[5]
-- if (activity.settings --[[ ?? DON'T GET TO SETTINGS IF THERE AREN'T ANY --]] or true) then
self.uiButton5.OnAction = function (self)
quartz.framework.audio.loadsound("base:audio/ui/validation.wav")
quartz.framework.audio.loadvolume(game.settings.audio["volume:sfx"])
quartz.framework.audio.playsound()
UTActivity.Ui.Settings.slideBegin = true
activity:PostStateChange("settings")
end
-- else
-- self.uiButton5.enabled = false
-- end
end
-- Draw ----------------------------------------------------------------------
function UTActivity.Ui.Title:Draw()
UIMenuWindow.Draw(self)
if (self.visible) then
if (self.rectangle) then
quartz.system.drawing.pushcontext()
quartz.system.drawing.loadtranslation(self.rectangle[1], self.rectangle[2])
quartz.system.drawing.loadtranslation(self.uiPanel.rectangle[1] + self.uiWindow.rectangle[1], self.uiPanel.rectangle[2] + self.uiWindow.rectangle[2])
if (activity.textRules) then
quartz.system.drawing.pushcontext()
quartz.system.drawing.loadtranslation(self.uiRulesPanel.rectangle[1], self.uiRulesPanel.rectangle[2] - 30)
quartz.system.drawing.loadcolor3f(unpack(self.textRules.fontColor))
quartz.system.drawing.loadfont(self.textRules.font)
quartz.system.drawing.drawtextjustified(activity.textRules, self.textRules.fontJustificationleft, unpack(self.textRules.rectangle) )
quartz.system.drawing.pop()
if (activity.scoringField) then
local baseY = 132
local offsetX = 0
local offsetY = 0
local rectangleIcon = {self.textRules.rectangle[1] + 80, baseY + 8 + self.scoringOffset, self.textRules.rectangle[3] + 80 , baseY + 48 + self.scoringOffset}
for i, field in ipairs(activity.scoringField) do
if (i == 4) then
offsetX = 250
offsetY = 0
rectangleIcon[2] = rectangleIcon[2] - 108
rectangleIcon[4] = rectangleIcon[4] - 108
end
if (field[2]) then
quartz.system.drawing.loadcolor3f(unpack(UIComponent.colors.white))
quartz.system.drawing.loadtexture(field[2])
quartz.system.drawing.drawtexture(40 + offsetX, baseY + offsetY + self.scoringOffset)
end
if (field[3]) then
quartz.system.drawing.loadcolor3f(unpack(self.textRules.fontColor))
quartz.system.drawing.loadfont(self.textRules.font)
if (i >= 4) then
quartz.system.drawing.drawtextjustified(field[3], self.textRules.fontJustificationcenter, unpack(rectangleIcon) )
else
quartz.system.drawing.drawtextjustified(field[3], self.textRules.fontJustificationleft, unpack(rectangleIcon) )
end
end
rectangleIcon[2] = rectangleIcon[2] + 36
rectangleIcon[4] = rectangleIcon[4] + 36
offsetY = offsetY + 36
end
end
end
if (activity.textScoring) then
quartz.system.drawing.pushcontext()
quartz.system.drawing.loadtranslation(self.uiScoringPanel.rectangle[1], self.uiScoringPanel.rectangle[2] - 20)
quartz.system.drawing.loadcolor3f(unpack(self.textScoring.fontColor))
quartz.system.drawing.loadfont(self.textScoring.font)
quartz.system.drawing.drawtextjustified(activity.textScoring, self.textScoring.fontJustification, unpack(self.textScoring.rectangle))
quartz.system.drawing.pop()
end
quartz.system.drawing.pop()
end
end
end
|
-- This sets up the table of C functions
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local abi = require "syscall.abi"
local ffi = require "ffi"
local voidp = ffi.typeof("void *")
local function void(x)
return ffi.cast(voidp, x)
end
-- basically all types passed to syscalls are int or long, so we do not need to use nicely named types, so we can avoid importing t.
local int, long = ffi.typeof("int"), ffi.typeof("long")
local uint, ulong = ffi.typeof("unsigned int"), ffi.typeof("unsigned long")
local function inlibc_fn(k) return ffi.C[k] end
local C = setmetatable({}, {
__index = function(C, k)
if pcall(inlibc_fn, k) then
C[k] = ffi.C[k] -- add to table, so no need for this slow path again
return C[k]
else
return nil
end
end
})
-- quite a few FreeBSD functions are weak aliases to __sys_ prefixed versions, some seem to resolve but others do not, odd.
C.futimes = ffi.C.__sys_futimes
C.lutimes = ffi.C.__sys_lutimes
C.utimes = ffi.C.__sys_utimes
C.wait4 = ffi.C.__sys_wait4
C.sigaction = ffi.C.__sys_sigaction
return C
|
local Image = { }
Image.x = 0
Image.y = 0
Image.width = 100
Image.height = 100
Image.autoSize = false
Image.file = ""
Image.backgroundColor = lui.theme.color.paneBackground
Image.borderColor = lui.theme.color.borderInactive
Image.borderWidth = 0
------------------------------------------------------------------------------------------------------------------------
local function drawNiceRect( x, y, w, h, borderWidth, cornerRadius, fillColor, borderColor )
-- Draws a nice rectangle and inside borders with support for transparent colours.
local offset = math.max(0, borderWidth * 0.5)
local cornerInside = math.max(0, cornerRadius - borderWidth * 0.5)
love.graphics.setColor(fillColor)
love.graphics.rectangle('fill', borderWidth, borderWidth, w - borderWidth * 2, h - borderWidth * 2, cornerInside)
love.graphics.setColor(borderColor)
love.graphics.setLineWidth(borderWidth)
love.graphics.rectangle('line', offset, offset, w - borderWidth, h - borderWidth, cornerRadius)
end
------------------------------------------------------------------------------------------------------------------------
function Image:init( )
self._image = nil
if self.file and string.len(self.file) > 0 then
self:load(self.file)
end
end
------------------------------------------------------------------------------------------------------------------------
function Image:destroyed( )
if self._image then
self._image:release()
end
end
------------------------------------------------------------------------------------------------------------------------
function Image:update( dt )
end
------------------------------------------------------------------------------------------------------------------------
function Image:draw( )
if self._image then
local sx = self.width / self._image:getPixelWidth()
local sy = self.height / self._image:getPixelHeight()
love.graphics.setColor(1,1,1,1)
love.graphics.draw(self._image, 0, 0, 0, sx, sy)
else
if self.borderWidth > 0 then
drawNiceRect(0, 0, self.width, self.height, self.borderWidth, 0, self.backgroundColor, self.borderColor)
else
love.graphics.setColor(self.backgroundColor)
love.graphics.rectangle('fill', 0, 0, self.width, self.height)
end
end
end
------------------------------------------------------------------------------------------------------------------------
function Image:load( file, useMipmaps )
if useMipmaps == nil then
useMipmaps = true
end
local success, img = pcall(love.graphics.newImage, file, { mipmaps = useMipmaps })
if success then
self._image = img
self.file = file
if self.autoSize then
self.width = img:getPixelWidth()
self.height = img:getPixelHeight()
end
if useMipmaps then
self._image:setMipmapFilter('nearest')
end
self._image:setFilter('linear', 'linear')
return true
end
self._image = nil
self.file = ""
if self.autoSize then
self.width = 0
self.height = 0
end
return false
end
------------------------------------------------------------------------------------------------------------------------
function Image:getImageSize( )
if not self._image then return 0, 0 end
return self._image:getPixelWidth(), self._image:getPixelHeight()
end
------------------------------------------------------------------------------------------------------------------------
function Image:getImageWidth( )
if not self._image then return 0 end
return self._image:getPixelWidth()
end
------------------------------------------------------------------------------------------------------------------------
function Image:getImageHeight( )
if not self._image then return 0 end
return self._image:getPixelHeight()
end
------------------------------------------------------------------------------------------------------------------------
function Image:getImage( )
return self._image
end
lui.register('Image', Image)
|
local lfs = require"lfs"
local function writeTable(tbl, out, tabs, printed)
tabs = tabs or 0
printed = printed or {}
local indention = string.rep("\t",tabs)
for k,v in pairs(tbl) do
if type(v) == "table" then
if not printed[v] then
out:write(indention,tostring(k),"\n")
out:write(indention,"{\n")
printed[v] = k
writeTable(v,out,tabs+1,printed)
printed[v] = nil
out:write(indention,"}\n")
else
out:write(indentation,tostring(k),"\t=\t[table:",printed[v],"]\n")
end
else
out:write(indention,tostring(k),"\t=\t",tostring(v),"\n")
end
end
end
doclet_dump = {}
function doclet_dump.start(doc)
local docout = assert(lfs.open(doclet_dump.options.output_dir.."/doc.txt","w"))
writeTable(doc,docout)
docout:close()
docout = nil
end
return doclet_dump
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
--[[
This file mirrors CompanionSkillsData.lua in many ways, before editing or
removing methods please ensure there is a stable interface between the two.
]]--
ZO_PlayerSkillProgressionData = ZO_SkillProgressionData_Base:Subclass()
function ZO_PlayerSkillProgressionData:SetAbilityId(abilityId)
ZO_SkillProgressionData_Base.SetAbilityId(self, abilityId)
SKILLS_DATA_MANAGER:MapAbilityIdToProgression(abilityId, self)
end
function ZO_PlayerSkillProgressionData:IsAdvised()
return ZO_SKILLS_ADVISOR_SINGLETON:IsSkillProgressionDataInSelectedBuild(self)
end
------------------------------
-- Active Skill Progression --
------------------------------
ZO_ActiveSkillProgressionData = ZO_PlayerSkillProgressionData:Subclass()
function ZO_ActiveSkillProgressionData:Initialize()
ZO_PlayerSkillProgressionData.Initialize(self)
self.rankXPExtents = {}
for rank = 1, MAX_RANKS_PER_ABILITY do
table.insert(self.rankXPExtents, { })
end
end
function ZO_ActiveSkillProgressionData:BuildStaticData(skillData, morphSlot)
ZO_PlayerSkillProgressionData.BuildStaticData(self, skillData, morphSlot)
local progressionId = skillData:GetProgressionId()
local abilityId = GetProgressionSkillMorphSlotAbilityId(progressionId, morphSlot)
self:SetAbilityId(abilityId)
local chainedAbilityIds = {GetProgressionSkillMorphSlotChainedAbilityIds(progressionId, morphSlot)}
for _, chainedAbilityId in ipairs(chainedAbilityIds) do
SKILLS_DATA_MANAGER:MapAbilityIdToProgression(chainedAbilityId, self)
end
self.isChainingAbility = #chainedAbilityIds > 0
for rank = 1, MAX_RANKS_PER_ABILITY do
local startXP, endXP = GetProgressionSkillMorphSlotRankXPExtents(progressionId, morphSlot, rank)
local xpExtents = self.rankXPExtents[rank]
xpExtents.startXP = startXP
xpExtents.endXP = endXP
end
end
function ZO_ActiveSkillProgressionData:RefreshDynamicData(...)
ZO_PlayerSkillProgressionData.RefreshDynamicData(self, ...)
self.currentXP = GetProgressionSkillMorphSlotCurrentXP(self:GetProgressionId(), self:GetMorphSlot())
-- Rank can be nil if we've never purchased the skill before
self.currentRank = GetAbilityProgressionRankFromAbilityId(self:GetAbilityId())
end
function ZO_ActiveSkillProgressionData:GetMorphSlot()
--Alias
return self:GetSkillProgressionKey()
end
function ZO_ActiveSkillProgressionData:IsBase()
return self:GetMorphSlot() == MORPH_SLOT_BASE
end
function ZO_ActiveSkillProgressionData:IsMorph()
return self:GetMorphSlot() ~= MORPH_SLOT_BASE
end
function ZO_ActiveSkillProgressionData:GetSiblingMorphData()
assert(self:IsMorph(), "GetSiblingMorphData should not be called on a base progression data")
local siblingMorphSlot = self:GetMorphSlot() == MORPH_SLOT_MORPH_1 and MORPH_SLOT_MORPH_2 or MORPH_SLOT_MORPH_1
return self:GetSkillData():GetMorphData(siblingMorphSlot)
end
function ZO_ActiveSkillProgressionData:IsBadMorph()
if self:IsMorph() then
local morphSiblingProgressionData = self:GetSiblingMorphData()
return not self:IsAdvised() and morphSiblingProgressionData:IsAdvised()
end
return false
end
function ZO_ActiveSkillProgressionData:GetFormattedNameWithRank(formatter)
if self:HasRankData() then
return ZO_CachedStrFormat(formatter or SI_ABILITY_NAME_AND_RANK, self:GetName(), self.currentRank)
else
return self:GetFormattedName()
end
end
function ZO_ActiveSkillProgressionData:GetDetailedName()
return self:GetFormattedNameWithRank()
end
function ZO_ActiveSkillProgressionData:GetCurrentRank()
return self.currentRank
end
function ZO_ActiveSkillProgressionData:HasRankData()
return self.currentRank ~= nil
end
function ZO_ActiveSkillProgressionData:GetCurrentXP()
return self.currentXP
end
function ZO_ActiveSkillProgressionData:GetRankXPExtents(rank)
local startXP, endXP = 0, 0
local xpExtents = self.rankXPExtents[rank]
if xpExtents then
startXP, endXP = xpExtents.startXP, xpExtents.endXP
end
return startXP, endXP
end
function ZO_ActiveSkillProgressionData:GetProgressionId()
return self:GetSkillData():GetProgressionId()
end
function ZO_ActiveSkillProgressionData:IsUnlocked()
if ZO_PlayerSkillProgressionData.IsUnlocked(self) then
if self:IsMorph() then
return self:GetSkillData():IsAtMorph()
end
return true
end
return false
end
function ZO_ActiveSkillProgressionData:IsChainingAbility()
return self.isChainingAbility
end
function ZO_ActiveSkillProgressionData:SetKeyboardTooltip(tooltip, showSkillPointCost, showUpgradeText, showAdvised, showBadMorph, overrideRank, overrideAbilityId)
local skillType, skillLineIndex, skillIndex = self:GetIndices()
local isPurchased = self:GetSkillData():GetPointAllocator():IsPurchased()
local numAvailableSkillPoints = SKILL_POINT_ALLOCATION_MANAGER:GetAvailableSkillPoints()
tooltip:SetActiveSkill(skillType, skillLineIndex, skillIndex, self:GetMorphSlot(), isPurchased, self:IsAdvised(), self:IsBadMorph(), numAvailableSkillPoints, showSkillPointCost, showUpgradeText, showAdvised, showBadMorph, overrideRank, overrideAbilityId)
end
function ZO_ActiveSkillProgressionData:TryPickup()
PickupAbilityBySkillLine(self:GetIndices())
return true
end
-------------------------------
-- Passive Skill Progression --
-------------------------------
ZO_PassiveSkillProgressionData = ZO_PlayerSkillProgressionData:Subclass()
function ZO_PassiveSkillProgressionData:BuildStaticData(skillData, rank)
ZO_PlayerSkillProgressionData.BuildStaticData(self, skillData, rank)
local skillType, skillLineIndex, skillIndex = skillData:GetIndices()
local UNUSED_MORPH_CHOICE = MORPH_SLOT_BASE
local abilityId, lineRankNeededToUnlock = GetSpecificSkillAbilityInfo(skillType, skillLineIndex, skillIndex, UNUSED_MORPH_CHOICE, rank)
self:SetAbilityId(abilityId)
self.lineRankNeededToUnlock = lineRankNeededToUnlock
end
function ZO_PassiveSkillProgressionData:GetFormattedNameWithRank(formatter)
return ZO_CachedStrFormat(formatter or SI_ABILITY_NAME_AND_RANK, self:GetName(), self:GetRank())
end
function ZO_PassiveSkillProgressionData:GetFormattedNameWithUpgradeLevels(formatter)
local skillData = self:GetSkillData()
local currentRank = skillData:GetPointAllocator():IsPurchased() and self:GetRank() or 0
return ZO_CachedStrFormat(formatter or SI_ABILITY_NAME_AND_UPGRADE_LEVELS, self:GetName(), currentRank, skillData:GetNumRanks())
end
function ZO_PassiveSkillProgressionData:GetDetailedName()
if self.skillData:GetNumRanks() > 1 then
return self:GetFormattedNameWithUpgradeLevels()
else
return self:GetFormattedName()
end
end
function ZO_PassiveSkillProgressionData:GetDetailedGamepadName()
if self.skillData:GetNumRanks() > 1 then
return self:GetFormattedNameWithUpgradeLevels(SI_GAMEPAD_ABILITY_NAME_AND_UPGRADE_LEVELS)
else
return self:GetFormattedName()
end
end
function ZO_PassiveSkillProgressionData:HasRankData()
return false
end
function ZO_PassiveSkillProgressionData:GetRank()
--Alias
return self:GetSkillProgressionKey()
end
function ZO_PassiveSkillProgressionData:GetLineRankNeededToUnlock()
return self.lineRankNeededToUnlock
end
function ZO_PassiveSkillProgressionData:MeetsLineRankUnlockRequirement()
local skillLineData = self:GetSkillData():GetSkillLineData()
return self:GetLineRankNeededToUnlock() <= skillLineData:GetCurrentRank()
end
function ZO_PassiveSkillProgressionData:IsUnlocked()
if ZO_PlayerSkillProgressionData.IsUnlocked(self) then
return self:MeetsLineRankUnlockRequirement()
end
return false
end
function ZO_PassiveSkillProgressionData:GetNextRankData()
local myRank = self:GetRank()
if myRank < self:GetSkillData():GetNumRanks() then
return self:GetSkillData():GetRankData(myRank + 1)
end
return nil
end
function ZO_PassiveSkillProgressionData:SetKeyboardTooltip(tooltip, showSkillPointCost)
local skillType, skillLineIndex, skillIndex = self:GetIndices()
local skillPointAllocator = self:GetSkillData():GetPointAllocator()
local currentRank = skillPointAllocator:IsPurchased() and skillPointAllocator:GetSkillProgressionKey() or 0
local numAvailableSkillPoints = SKILL_POINT_ALLOCATION_MANAGER:GetAvailableSkillPoints()
tooltip:SetPassiveSkill(skillType, skillLineIndex, skillIndex, self:GetRank(), currentRank, numAvailableSkillPoints, showSkillPointCost)
end
--[[
A ZO_SkillData is an entry in a ZO_SkillLineData. A skill can be upgraded to various levels, denoted by ZO_SkillProgressionData objects.
--]]
-----------
-- Skill --
-----------
ZO_SkillData = ZO_SkillData_Base:Subclass()
function ZO_SkillData:Initialize()
self.skillProgressions = {}
self.progressionObjectMetaPool = ZO_MetaPool:New(SKILLS_DATA_MANAGER:GetSkillProgressionObjectPool(self:IsPassive()))
end
function ZO_SkillData:Reset()
ZO_ClearTable(self.skillProgressions)
self.progressionObjectMetaPool:ReleaseAllObjects()
end
function ZO_SkillData:BuildStaticData(skillLineData, skillIndex)
self.skillLineData, self.skillIndex = skillLineData, skillIndex
local skillType, skillLineIndex = self.skillLineData:GetIndices()
self.lineRankNeededToPurchase = GetSkillAbilityLineRankNeededToUnlock(skillType, skillLineIndex, skillIndex)
self.isAutoGrant = IsSkillAbilityAutoGrant(skillType, skillLineIndex, skillIndex)
end
function ZO_SkillData:RefreshDynamicData(refreshChildren)
self.isPurchased = IsSkillAbilityPurchased(self:GetIndices())
if refreshChildren then
for _, skillProgressionData in pairs(self.skillProgressions) do
skillProgressionData:RefreshDynamicData(refreshChildren)
end
end
end
function ZO_SkillData:AddProgressionObject(skillProgressionKey)
local progressionData = self.progressionObjectMetaPool:AcquireObject()
progressionData:BuildData(self, skillProgressionKey)
self.skillProgressions[skillProgressionKey] = progressionData
return progressionData
end
function ZO_SkillData:GetSkillIndex()
return self.skillIndex
end
function ZO_SkillData:GetIndices()
local skillType, skillLineIndex = self.skillLineData:GetIndices()
return skillType, skillLineIndex, self.skillIndex
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:GetSkillLineData()
return self.skillLineData
end
function ZO_SkillData:IsPassive()
assert(false) -- Must be overriden
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:IsActive()
return not self:IsPassive()
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:GetLineRankNeededToPurchase()
return self.lineRankNeededToPurchase
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:MeetsLinePurchaseRequirement()
local skillLineData = self:GetSkillLineData()
return skillLineData:IsAvailable() and self:GetLineRankNeededToPurchase() <= skillLineData:GetCurrentRank()
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:IsAutoGrant()
return self.isAutoGrant
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:IsPurchased()
return self.isPurchased
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:IsAdvised()
return ZO_SKILLS_ADVISOR_SINGLETON:IsSkillDataInSelectedBuild(self)
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:HasPointsToClear(clearMorphsOnly)
assert(false) -- Must be overriden
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:GetProgressionData(skillProgressionKey)
return self.skillProgressions[skillProgressionKey]
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:GetHeaderText()
assert(false) -- Must be overriden
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:GetCurrentSkillProgressionKey()
assert(false) -- Must be overriden
end
-- implements method in ZO_SkillData_Base
function ZO_SkillData:GetNumPointsAllocated()
assert(false) -- Must be overriden
end
function ZO_SkillData:GetCurrentProgressionData()
return self:GetProgressionData(self:GetCurrentSkillProgressionKey())
end
function ZO_SkillData:GetPointAllocator()
--Utility function
return SKILL_POINT_ALLOCATION_MANAGER:GetSkillPointAllocatorForSkillData(self)
end
function ZO_SkillData:GetPointAllocatorProgressionData()
--Utility function
return self:GetPointAllocator():GetProgressionData()
end
function ZO_SkillData:HasUpdatedStatus()
return self.hasUpdatedStatus
end
function ZO_SkillData:SetHasUpdatedStatus(hasUpdatedStatus)
if self.hasUpdatedStatus ~= hasUpdatedStatus then
self.hasUpdatedStatus = hasUpdatedStatus
self.skillLineData:OnSkillDataUpdateStatusChanged(self)
end
end
function ZO_SkillData:ClearUpdate()
self:SetHasUpdatedStatus(false)
end
function ZO_SkillData:CanPointAllocationsBeAltered(isFullRespec)
return self:MeetsLinePurchaseRequirement()
end
function ZO_SkillData:IsPlayerSkill()
return true
end
------------------
-- Active Skill --
------------------
ZO_ActiveSkillData = ZO_SkillData:Subclass()
function ZO_ActiveSkillData:New(...)
return ZO_SkillData.New(self, ...)
end
function ZO_ActiveSkillData:BuildStaticData(skillLineData, skillIndex)
ZO_SkillData.BuildStaticData(self, skillLineData, skillIndex)
local skillType, skillLineIndex = skillLineData:GetIndices()
self.isUltimate = IsSkillAbilityUltimate(skillType, skillLineIndex, skillIndex)
self.progressionId = GetProgressionSkillProgressionId(skillType, skillLineIndex, skillIndex)
for morphSlot = MORPH_SLOT_ITERATION_BEGIN, MORPH_SLOT_ITERATION_END do
self:AddProgressionObject(morphSlot)
end
-- Don't mark a skill new during init
self.canBeMarkedAsUpdated = false
self:SetHasUpdatedStatus(false)
end
function ZO_ActiveSkillData:RefreshDynamicData(...)
local wasAtMorph = self:IsAtMorph()
ZO_SkillData.RefreshDynamicData(self, ...)
self.currentMorphSlot = GetProgressionSkillCurrentMorphSlot(self.progressionId)
if self.canBeMarkedAsUpdated then
local isBase = self.currentMorphSlot == MORPH_SLOT_BASE
local isPurchased = self:IsPurchased()
if self:HasUpdatedStatus() then
if not (isBase and isPurchased) then
self:SetHasUpdatedStatus(false)
end
elseif not wasAtMorph and self:IsAtMorph() and isPurchased and isBase then
self:SetHasUpdatedStatus(true)
end
end
self.canBeMarkedAsUpdated = true
end
function ZO_ActiveSkillData:IsPassive()
return false
end
function ZO_ActiveSkillData:IsUltimate()
return self.isUltimate
end
function ZO_ActiveSkillData:GetProgressionId()
return self.progressionId
end
function ZO_ActiveSkillData:GetCurrentMorphSlot()
return self.currentMorphSlot
end
function ZO_ActiveSkillData:GetCurrentSkillProgressionKey()
-- Generic
return self:GetCurrentMorphSlot()
end
function ZO_ActiveSkillData:GetNumPointsAllocated()
local pointsAllocated = 0
if self:IsPurchased() then
if not self:IsAutoGrant() then
pointsAllocated = pointsAllocated + 1
end
if self:GetCurrentMorphSlot() ~= MORPH_SLOT_BASE then
pointsAllocated = pointsAllocated + 1
end
end
return pointsAllocated
end
function ZO_ActiveSkillData:GetMorphData(morphSlot)
-- Alias
return self:GetProgressionData(morphSlot)
end
function ZO_ActiveSkillData:IsAtMorph()
local baseMorphData = self:GetMorphData(MORPH_SLOT_BASE)
local baseMorphCurrentXP = baseMorphData:GetCurrentXP()
local _, baseMorphEndXP = baseMorphData:GetRankXPExtents(MAX_RANKS_PER_ABILITY)
return baseMorphCurrentXP >= baseMorphEndXP
end
function ZO_ActiveSkillData:GetHeaderText()
if self:IsUltimate() then
return GetString(SI_SKILLS_ULTIMATE_ABILITIES)
else
return GetString(SI_SKILLS_ACTIVE_ABILITIES)
end
end
function ZO_ActiveSkillData:HasPointsToClear(clearMorphsOnly)
if self:GetNumPointsAllocated() > 0 then
if clearMorphsOnly then
-- make sure there are points allocated to a morph
return self:GetCurrentMorphSlot() ~= MORPH_SLOT_BASE
end
return true
end
return false
end
function ZO_ActiveSkillData:CanPointAllocationsBeAltered(isFullRespec)
if ZO_SkillData.CanPointAllocationsBeAltered(self, isFullRespec) then
if self:IsPurchased() and not self:IsAtMorph() then
return isFullRespec and not self:IsAutoGrant()
end
return true
end
return false
end
-------------------
-- Passive Skill --
-------------------
ZO_PassiveSkillData = ZO_SkillData:Subclass()
function ZO_PassiveSkillData:New(...)
return ZO_SkillData.New(self, ...)
end
function ZO_PassiveSkillData:BuildStaticData(skillLineData, skillIndex)
ZO_SkillData.BuildStaticData(self, skillLineData, skillIndex)
local skillType, skillLineIndex = skillLineData:GetIndices()
self.numRanks = GetNumPassiveSkillRanks(skillType, skillLineIndex, skillIndex)
for rank = 1, self.numRanks do
self:AddProgressionObject(rank)
end
end
function ZO_PassiveSkillData:RefreshDynamicData(...)
ZO_SkillData.RefreshDynamicData(self, ...)
-- Can return nil, but we want to be at 1 when we're not purchased or we have a passive with only 1 rank and no upgrades
self.currentRank = GetSkillAbilityUpgradeInfo(self:GetIndices())
if not self.currentRank or self.currentRank == 0 then
self.currentRank = 1
end
end
function ZO_PassiveSkillData:IsPassive()
return true
end
function ZO_PassiveSkillData:IsUltimate()
return false
end
function ZO_PassiveSkillData:GetNumRanks()
return self.numRanks
end
function ZO_PassiveSkillData:GetCurrentRank()
return self.currentRank
end
function ZO_PassiveSkillData:GetCurrentSkillProgressionKey()
-- Generic
return self:GetCurrentRank()
end
function ZO_PassiveSkillData:GetNumPointsAllocated()
if self:IsPurchased() then
if self:IsAutoGrant() then
return self:GetCurrentRank() - 1
else
return self:GetCurrentRank()
end
end
return 0
end
--1 based
function ZO_PassiveSkillData:GetRankData(rank)
-- Alias
return self:GetProgressionData(rank)
end
function ZO_PassiveSkillData:GetHeaderText()
return GetString(SI_SKILLS_PASSIVE_ABILITIES)
end
function ZO_PassiveSkillData:HasPointsToClear(clearMorphsOnly)
if not clearMorphsOnly and self:IsPurchased() then
return self:GetCurrentRank() > 1 or not self:IsAutoGrant()
end
return false
end
function ZO_PassiveSkillData:CanPointAllocationsBeAltered(isFullRespec)
if ZO_SkillData.CanPointAllocationsBeAltered(self, isFullRespec) then
if self:IsPurchased() then
local currentRank = self:GetCurrentRank()
local nextRankData = self:GetRankData(currentRank + 1)
if nextRankData and nextRankData:MeetsLineRankUnlockRequirement() then
return true
end
return isFullRespec and (currentRank > 1 or not self:IsAutoGrant())
end
return true
end
return false
end
--[[
A ZO_SkillLineData is an entry in ZO_SkillTypeData. A skill line has multiple skills to purchase and upgrade, denoted by ZO_SkillData objects.
--]]
----------------
-- Skill Line --
----------------
ZO_SkillLineData = ZO_SkillLineData_Base:Subclass()
function ZO_SkillLineData:Initialize()
ZO_SkillLineData_Base.Initialize(self, SKILLS_DATA_MANAGER)
self.orderedSkills = {}
local IS_ACTIVE = false
local IS_PASSIVE = true
self.activeSkillMetaPool = ZO_MetaPool:New(SKILLS_DATA_MANAGER:GetSkillObjectPool(IS_ACTIVE))
self.passiveSkillMetaPool = ZO_MetaPool:New(SKILLS_DATA_MANAGER:GetSkillObjectPool(IS_PASSIVE))
end
function ZO_SkillLineData:Reset()
ZO_SkillLineData_Base.Reset(self)
ZO_ClearNumericallyIndexedTable(self.orderedSkills)
self.activeSkillMetaPool:ReleaseAllObjects()
self.passiveSkillMetaPool:ReleaseAllObjects()
end
function ZO_SkillLineData:BuildStaticData(skillTypeData, skillLineIndex)
self.skillTypeData, self.skillLineIndex = skillTypeData, skillLineIndex
local skillType = self.skillTypeData:GetSkillType()
self.id = GetSkillLineId(skillType, skillLineIndex)
self.orderingIndex = GetSkillLineOrderingIndex(skillType, skillLineIndex)
self.name = GetSkillLineNameById(self.id)
self.unlockText = GetSkillLineUnlockTextById(self.id)
self.isWerewolf = IsWerewolfSkillLineById(self.id)
self.craftingGrowthType = GetSkillLineCraftingGrowthTypeById(self.id)
for skillIndex = 1, GetNumSkillAbilities(skillType, skillLineIndex) do
local skillData
local isPassive = IsSkillAbilityPassive(skillType, skillLineIndex, skillIndex)
if isPassive then
skillData = self.passiveSkillMetaPool:AcquireObject()
else
skillData = self.activeSkillMetaPool:AcquireObject()
end
skillData:BuildData(self, skillIndex)
table.insert(self.orderedSkills, skillData)
end
self:InitializeNewState()
end
function ZO_SkillLineData:RefreshDynamicData(refreshChildren)
local skillType, skillLineIndex = self:GetIndices()
local wasAvailable = self:IsAvailable()
self.currentRank, self.isAdvised, self.isActive, self.isDiscovered = GetSkillLineDynamicInfo(skillType, skillLineIndex)
self.lastRankXP, self.nextRankXP, self.currentXP = GetSkillLineXPInfo(skillType, skillLineIndex)
local isAvailable = self:IsAvailable()
if wasAvailable ~= isAvailable then
self:TryMarkNew(isAvailable)
end
if refreshChildren then
for _, skillData in ipairs(self.orderedSkills) do
skillData:RefreshDynamicData(refreshChildren)
end
end
self:AllowMarkingNew()
end
function ZO_SkillLineData:GetSkillTypeData()
return self.skillTypeData
end
function ZO_SkillLineData:GetSkillLineIndex()
return self.skillLineIndex
end
function ZO_SkillLineData:GetIndices()
return self.skillTypeData:GetSkillType(), self.skillLineIndex
end
function ZO_SkillLineData:GetNumSkills()
return #self.orderedSkills
end
function ZO_SkillLineData:GetSkillDataByIndex(skillIndex)
return self.orderedSkills[skillIndex]
end
function ZO_SkillLineData:SkillIterator(skillFilterFunctions)
return ZO_FilteredNumericallyIndexedTableIterator(self.orderedSkills, skillFilterFunctions)
end
function ZO_SkillLineData:GetName()
return self.name
end
function ZO_SkillLineData:GetUnlockText()
return self.unlockText
end
function ZO_SkillLineData:GetOrderingIndex()
return self.orderingIndex
end
function ZO_SkillLineData:IsDiscovered()
return self.isDiscovered
end
function ZO_SkillLineData:IsActive()
return self.isActive
end
function ZO_SkillLineData:GetCurrentRank()
return self.currentRank
end
function ZO_SkillLineData:GetLastRankXP()
return self.lastRankXP
end
function ZO_SkillLineData:GetNextRankXP()
return self.nextRankXP
end
function ZO_SkillLineData:GetCurrentRankXP()
return self.currentXP
end
function ZO_SkillLineData:IsAdvised()
return self.isAdvised
end
-- unique to Player skill lines
function ZO_SkillLineData:IsPlayerSkillLine()
return true
end
function ZO_SkillLineData:IsWerewolf()
return self.isWerewolf
end
function ZO_SkillLineData:GetCraftingGrowthType()
return self.craftingGrowthType
end
function ZO_SkillLineData:GetFormattedNameWithNumPointsAllocated()
local numPointsAllocated = SKILL_POINT_ALLOCATION_MANAGER:GetNumPointsAllocatedInSkillLine(self)
if numPointsAllocated > 0 then
return zo_strformat(SI_SKILLS_ENTRY_LINE_NAME_FORMAT_WITH_ALLOCATED_POINTS, self.name, numPointsAllocated)
else
return self:GetFormattedName()
end
end
function ZO_SkillLineData:SetAdvised(advised)
local skillType, skillLineIndex = self:GetIndices()
SetAdviseSkillLine(skillType, skillLineIndex, advised)
end
|
local _, ns = ...
local B, C, L, DB, P = unpack(ns)
local G = P:GetModule("GUI")
local extraGUIs = {}
local function toggleExtraGUI(guiName)
for name, frame in pairs(extraGUIs) do
if name == guiName then
B:TogglePanel(frame)
else
frame:Hide()
end
end
end
local function hideExtraGUIs()
for _, frame in pairs(extraGUIs) do
frame:Hide()
end
end
local function createExtraGUI(parent, name, title, scrollFrame)
local frame = CreateFrame("Frame", name, parent)
frame:SetSize(280, _G.NDuiPlusGUI:GetHeight())
frame:SetPoint("TOPLEFT", _G.NDuiPlusGUI, "TOPRIGHT", 3, 0)
B.SetBD(frame)
if title then
B.CreateFS(frame, 14, title, "system", "TOPLEFT", 20, -25)
end
if scrollFrame then
local scroll = CreateFrame("ScrollFrame", nil, frame, "UIPanelScrollFrameTemplate")
scroll:SetSize(frame:GetWidth() - 40, frame:GetHeight() - 60)
scroll:SetPoint("TOPLEFT", 10, -50)
scroll.bg = B.CreateBDFrame(scroll, .3)
scroll.bg:SetAllPoints()
scroll.child = CreateFrame("Frame", nil, scroll)
scroll.child:SetSize(frame:GetWidth() - 40, 1)
scroll:SetScrollChild(scroll.child)
B.ReskinScroll(scroll.ScrollBar)
frame.scroll = scroll
end
if not parent.extraGUIHook then
parent:HookScript("OnHide", hideExtraGUIs)
parent.extraGUIHook = true
end
extraGUIs[name] = frame
return frame
end
local function createOptionTitle(parent, title, offset)
B.CreateFS(parent, 14, title, nil, "TOP", 0, offset)
local line = B.SetGradient(parent, "H", 1, 1, 1, .25, .25, 200, C.mult)
line:SetPoint("TOPLEFT", 20, offset-20)
end
local function sliderValueChanged(self, v)
local current = tonumber(format("%.1f", v))
self.value:SetText(current)
G.Variable(self.__key, self.__value, current)
if self.__update then self.__update() end
end
local function createOptionSlider(parent, title, minV, maxV, step, x, y, key, value, func)
local slider = B.CreateSlider(parent, title, minV, maxV, step, x, y)
slider:SetValue(G.Variable(key, value))
slider.value:SetText(G.Variable(key, value))
slider.__key = key
slider.__value = value
slider.__update = func
slider.__default = G.GetDefaultSettings(key, value)
slider:SetScript("OnValueChanged", sliderValueChanged)
end
local function createOptionCheck(parent, offset, text)
local box = B.CreateCheckBox(parent)
box:SetPoint("TOPLEFT", 20, -offset)
B.CreateFS(box, 14, text, false, "LEFT", 30, 0)
return box
end
local function createOptionDropDown(parent, offset, text, key, value, data, callback)
local dd = B.CreateDropDown(parent, 180, 28, data)
dd:SetPoint("TOPLEFT", 30, offset)
dd.Text:SetText(data[G.Variable(key, value)])
B.CreateFS(dd, 14, text, "system", "CENTER", 0, 25)
local opt = dd.options
dd.button:HookScript("OnClick", function()
for num = 1, #data do
if num == G.Variable(key, value) then
opt[num]:SetBackdropColor(1, .8, 0, .3)
opt[num].selected = true
else
opt[num]:SetBackdropColor(0, 0, 0, .3)
opt[num].selected = false
end
end
end)
for i in pairs(data) do
opt[i]:HookScript("OnClick", function()
G.Variable(key, value, i)
if callback then callback() end
end)
end
return dd
end
function G:SetupChangelog(parent)
local guiName = "NDuiPlusGUI_Changelog"
toggleExtraGUI(guiName)
if extraGUIs[guiName] then return end
local panel = createExtraGUI(parent, guiName, L["Changelog"], true)
panel.scroll.bg:Hide()
local frame = panel.scroll.child
local fs = frame:CreateFontString(nil, "OVERLAY")
fs:SetFont(DB.Font[1], DB.Font[2]+2, DB.Font[3])
fs:SetPoint("TOPLEFT", 10, -10)
fs:SetPoint("TOPRIGHT", -10, -10)
fs:SetJustifyH("LEFT")
fs:SetSpacing(10)
fs:SetText(P.Changelog)
end
local function updateABFaderAlpha()
local AB = P:GetModule("ActionBar")
if not AB.fadeParent then return end
AB.fadeParent:SetAlpha(AB.db["Alpha"])
end
local function updateABFaderSettings()
local AB = P:GetModule("ActionBar")
if not AB.fadeParent then return end
AB:UpdateFaderSettings()
AB.fadeParent:SetAlpha(AB.db["Alpha"])
end
function G:SetupABFader(parent)
local guiName = "NDuiPlusGUI_ABFader"
toggleExtraGUI(guiName)
if extraGUIs[guiName] then return end
local panel = createExtraGUI(parent, guiName, L["Fade Settings"].."*", true)
local frame = panel.scroll.child
local offset = -10
createOptionSlider(frame, L["Fade Alpha"], 0, 1, .1, 20, -offset-60, "ActionBar", "Alpha", updateABFaderAlpha)
createOptionSlider(frame, L["Fade Delay"], 0, 3, .1, 20, -offset-130, "ActionBar", "Delay")
offset = offset + 190
createOptionTitle(frame, L["Fade Condition"], -offset)
local options = {
[1] = {"Combat", L["Combat"]},
[2] = {"Target", L["Target"]},
[3] = {"Health", L["Health"]},
[4] = {"Vehicle", L["Vehicle"]},
[5] = {"Casting", L["Casting"]},
}
offset = offset + 40
for _, option in ipairs(options) do
local value, text = unpack(option)
local box = createOptionCheck(frame, offset, text)
box:SetChecked(G.Variable("ActionBar", value))
box:SetScript("OnClick", function()
G.Variable("ActionBar", value, box:GetChecked())
updateABFaderSettings()
end)
offset = offset + 35
end
end
local function updateUFsFader()
P:GetModule("UnitFrames"):UpdateUFsFader()
end
function G:SetupUFsFader(parent)
local guiName = "NDuiPlusGUI_UFsFader"
toggleExtraGUI(guiName)
if extraGUIs[guiName] then return end
local panel = createExtraGUI(parent, guiName, L["Fade Settings"].."*", true)
local frame = panel.scroll.child
local offset = -10
createOptionSlider(frame, L["Fade Delay"], 0, 3, .1, 20, -offset-60, "UnitFrames", "Delay", updateUFsFader)
createOptionSlider(frame, L["Smooth"], 0, 1, .1, 20, -offset-130, "UnitFrames", "Smooth", updateUFsFader)
createOptionSlider(frame, L["MinAlpha"], 0, 1, .1, 20, -offset-200, "UnitFrames", "MinAlpha", updateUFsFader)
createOptionSlider(frame, L["MaxAlpha"], 0, 1, .1, 20, -offset-270, "UnitFrames", "MaxAlpha", updateUFsFader)
offset = offset + 330
createOptionTitle(frame, L["Fade Condition"], -offset)
local options = {
[1] = {"Hover", L["Hover"]},
[2] = {"Combat", L["Combat"]},
[3] = {"Target", L["Target"]},
[4] = {"Focus", L["Focus"]},
[5] = {"Health", L["Health"]},
[6] = {"Vehicle", L["Vehicle"]},
[7] = {"Casting", L["Casting"]},
}
offset = offset + 40
for _, option in ipairs(options) do
local value, text = unpack(option)
local box = createOptionCheck(frame, offset, text)
box:SetChecked(G.Variable("UnitFrames", value))
box:SetScript("OnClick", function()
G.Variable("UnitFrames", value, box:GetChecked())
updateUFsFader()
end)
offset = offset + 35
end
local blank = CreateFrame("Frame", nil, frame)
blank:SetSize(20, 20)
blank:SetPoint("TOPLEFT", 20, -offset)
end
local function updateUFsRole()
P:GetModule("UnitFrames"):UpdateRoleIcons()
end
function G:SetupUFsRole(parent)
local guiName = "NDuiPlusGUI_UFsRole"
toggleExtraGUI(guiName)
if extraGUIs[guiName] then return end
local panel = createExtraGUI(parent, guiName, L["Role Icon Settings"].."*", true)
local frame = panel.scroll.child
local offset = -10
createOptionDropDown(frame, -offset-60, L["Point"], "UnitFrames", "RolePoint", G.Points, updateUFsRole)
createOptionSlider(frame, L["X Offset"], -100, 100, 1, 20, -offset-130, "UnitFrames", "RoleXOffset", updateUFsRole)
createOptionSlider(frame, L["Y Offset"], -100, 100, 1, 20, -offset-200, "UnitFrames", "RoleYOffset", updateUFsRole)
createOptionSlider(frame, L["Icon Size"], 8, 50, 1, 20, -offset-270, "UnitFrames", "RoleSize", updateUFsRole)
end
|
local commands = {
jsondetect = {
{ "BufNewFile,BufRead", "*.cjsn", "setfiletype jsonc" },
{ "BufNewFile,BufRead", "*.cjson", "setfiletype jsonc" },
{ "BufNewFile,BufRead", "*.jsonc", "setfiletype jsonc" },
{ "BufNewFile,BufRead", ".eslintrc.json", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", ".babelrc", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", ".jshintrc", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", ".jslintrc", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", ".mocharc.json", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", ".mocharc.jsonc", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", "coffeelint.json", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", "tsconfig.json", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", "jsconfig.json", "setlocal filetype=jsonc" },
{ "BufNewFile,BufRead", "*/waybar/config", "setlocal filetype=jsonc" },
},
}
require("events").nvim_create_augroups(commands)
|
-- Numbers are for GUI buttons
-- If a number is not there, it means it is false
-- Permissions are inherited from the rank below
--
local permissions = {
[1] = {
[1] = true, -- warp to player
[2] = true, -- punish
[3] = true, -- spectate
[4] = true, -- warp player to
[5] = true, -- reconnect
[6] = true, -- kick
[7] = true, -- freeze
[9] = true, -- slap
[10] = true, -- rename
[11] = true, -- view punishments
[12] = true, -- screenshot
[17] = true, -- dimension
[18] = true, -- interior
[19] = true, -- fix vehicle
[21] = true, -- destroy vehicle
[25] = true, -- view weapons
[29] = true, -- freeze vehicle
["mute"] = true,
["admin jail"] = true,
["jetpack"] = true,
["unmute"] = true,
["unjail"] = true,
},
[2] = {
[8] = true, -- shout
[13] = true, -- set model
[15] = true, -- set health
[16] = true, -- set armour
[20] = true, -- eject
[22] = true, -- disable vehicle
[23] = true, -- set job
},
[3] = {
["manage punish"] = true,
["ban"] = true,
[27] = true, -- give vehicle
[30] = true, -- last logins
},
[4] = {
[26] = true, -- give weapon
},
[5] = {
[14] = true, -- set money
},
}
function canAdminDoAction(plr, action)
if (not isPlayerAdmin(plr) or not getPlayerAdminRank(plr)) then return end
return getRankPerms(getPlayerAdminRank(plr))[action] or false
end
function getRankPerms(rank)
if (not rank) then return end
local temp = {}
for ind, ent in pairs(permissions) do
if (ind <= rank) then
for k, v in pairs(ent) do
temp[k] = v
end
end
end
if (rank == 1337) then
temp[-1] = true
end
return temp
end
function sendPermissions(plr)
if (not isPlayerAdmin(plr)) then return end
local rank = getPlayerAdminRank(plr)
triggerClientEvent(plr, "UCDadmin.onReceivedPermissions", plr, getRankPerms(rank))
end
addEvent("UCDadmin.getPermissions", true)
addEventHandler("UCDadmin.getPermissions", root,
function ()
sendPermissions(client)
end
)
addEventHandler("onPlayerLogin", root,
function ()
--if (source.account.name ~= "guest" and adminTable[source.account.name]) then
if (isPlayerAdmin(source)) then
sendPermissions(source)
end
end
)
|
-- Copyright Alex Zhang (tokers)
local util = require "resty.http2.util"
local hpack = require "resty.http2.hpack"
local h2_error = require "resty.http2.error"
local h2_frame
local new_tab = util.new_tab
local clear_tab = util.clear_tab
local children_update
local pairs = pairs
local is_num = util.is_num
local is_tab = util.is_tab
local lower = string.lower
local sub = string.sub
local concat = table.concat
local buffer
local buffer_len = 0
local STATE_IDLE = 0
local STATE_OPEN = 1
local STATE_CLOSED = 3
local STATE_HALF_CLOSED_LOCAL = 4
local STATE_HALF_CLOSED_REMOTE = 5
local STATE_RESERVED_LOCAL = 6
local STATE_RESERVED_REMOTE = 7
local MAX_WINDOW = 0x7fffffff
local _M = {
_VERSION = "0.1",
MAX_WEIGHT = 256,
DEFAULT_WEIGHT = 16,
}
local mt = { __index = _M }
local IS_CONNECTION_SPEC_HEADERS = {
["connection"] = true,
["keep-alive"] = true,
["proxy-connection"] = true,
["upgrade"] = true,
["transfer-encoding"] = true,
}
children_update = function(node)
if not node then
return
end
local child = node.child
if not child then
return
end
local max_weight = _M.MAX_WEIGHT
local rank = node.rank
local rel_weight = node.rel_weight
while true do
child.rank = rank + 1
child.rel_weight = rel_weight / max_weight * child.weight
children_update(child)
child = child.next_sibling
end
end
-- let depend as current stream's parent
function _M:set_dependency(depend, excl)
local stream = self
local root = stream.session.root
if not depend then
depend = root
excl = false
end
local child
local max_weight = _M.MAX_WEIGHT
if depend == root then
stream.rel_weight = stream.weight / max_weight
stream.rank = 1
child = depend.child
else
-- check whether stream is an ancestor of depend
while true do
local node = depend.parent
if node == root or node.rank < stream.rank then
break
end
if node == stream then
-- firstly take depend out of it's "old parent"
local last_node = depend.last_sibling
local next_node = depend.next_sibling
if last_node then
last_node.next_sibling = next_node
end
if next_node then
next_node.last_sibling = last_node
end
-- now stream.parent will be the "new parent" of depend
local parent = stream.parent
local first_child = parent.child
first_child.last_sibling = depend
depend.last_sibling = nil
depend.next_sibling = first_child
depend.parent = parent
parent.child = depend
if parent == root then
depend.rank = 1
depend.rel_weight = depend.weight / max_weight
else
local weight = depend.weight
depend.rank = parent.rank + 1
depend.rel_weight = parent.rel_weight / max_weight * weight
end
if not excl then
children_update(depend)
end
break
end
end
stream.rank = depend.rank + 1
stream.rel_weight = depend.rel_weight / max_weight * stream.weight
child = depend.child
end
if excl and child then
-- stream should be the sole direct child of depend
local c = child
local last
while true do
c.parent = stream
if not c.next_sibling then
last = c -- the last sibling
break
end
c = c.next_sibling
end
last.next_sibling = stream.child
stream.child.last_sibling = last
stream.child = child
depend.child = stream
end
local last_node = stream.last_sibling
local next_node = stream.next_sibling
if last_node then
last_node.next_sibling = next_node
end
if next_node then
next_node.last_sibling = last_node
end
stream.parent = depend
children_update(stream)
end
-- serialize headers and create a headers frame,
-- note this function does not check the HTTP protocol semantics,
-- callers should check this in the higher land.
function _M:submit_headers(headers, end_stream, priority, pad)
local state = self.state
if state ~= STATE_IDLE
and state ~= STATE_OPEN
and state ~= STATE_RESERVED_LOCAL
and state ~= STATE_HALF_CLOSED_REMOTE
then
return nil, "invalid stream state"
end
local sid = self.sid
if sid == 0 then
return nil, "cannot submit headers to the whole connection"
end
if sid % 2 == 0 then
return nil, "peer-initiated stream"
end
if self.end_headers then
return nil, "end headers"
end
local headers_count = #headers
if buffer_len < headers_count then
buffer = new_tab(headers_count, 0)
buffer_len = headers_count
else
clear_tab(buffer)
end
for i = 1, #headers do
local name = lower(headers[i].name)
local value = headers[i].value
if IS_CONNECTION_SPEC_HEADERS[name] then
goto continue
end
local index = hpack.COMMON_REQUEST_HEADERS_INDEX[name]
if is_num(index) then
buffer[#buffer + 1] = hpack.incr_indexed(index)
hpack.encode(value, buffer, false)
goto continue
end
if is_tab(index) then
for v_name, v_index in pairs(index) do
if value == v_name then
buffer[#buffer + 1] = hpack.indexed(v_index)
goto continue
end
end
end
buffer[#buffer + 1] = hpack.incr_indexed(0)
hpack.encode(name, buffer, true)
hpack.encode(value, buffer, false)
::continue::
end
local fragment = concat(buffer)
local max_frame_size = self.session.max_frame_size
local payload = fragment
local continue = false
local first_piece_size = max_frame_size
if priority then
first_piece_size = first_piece_size - 5
end
if pad then
first_piece_size = first_piece_size - #pad - 1
end
if #fragment > first_piece_size then
payload = sub(fragment, 1, first_piece_size)
continue = true
end
local frame, err = h2_frame.headers.new(payload, priority, pad,
end_stream, not continue, sid)
if not frame then
return nil, err
end
self.session:frame_queue(frame)
if continue then
local pos = first_piece_size + 1
repeat
if pos + max_frame_size - 1 < #fragment then
payload = sub(fragment, pos, pos + max_frame_size - 1)
else
payload = sub(fragment, pos)
continue = false
end
frame, err = h2_frame.continuation.new(payload, not continue, sid)
if not frame then
return nil, err
end
self.session:frame_queue(frame)
until not continue
end
-- FIXME we change the stream state just when the frame was queued,
-- maybe it is improper and shoule be postponed
-- until the frame was really sent.
if state == STATE_IDLE then
self.state = end_stream and STATE_HALF_CLOSED_LOCAL or STATE_OPEN
elseif state == STATE_RESERVED_LOCAL then
self.state = end_stream and STATE_CLOSED or STATE_HALF_CLOSED_REMOTE
end
local peer_state = self.peer_state
if peer_state == STATE_IDLE then
self.peer_state = end_stream and STATE_HALF_CLOSED_REMOTE or STATE_OPEN
elseif peer_state == STATE_RESERVED_REMOTE then
self.peer_state = end_stream and STATE_CLOSED or STATE_HALF_CLOSED_LOCAL
end
self.end_headers = true
return true
end
function _M:submit_data(data, pad, last)
local state = self.state
if state ~= STATE_OPEN and state ~= STATE_HALF_CLOSED_REMOTE then
return nil, "invalid stream state"
end
if self.exhausted then
return nil, "stream send window exhausted"
end
local frame = h2_frame.data.new(data, pad, last, self.sid)
local length = frame.header.length
local self_send_window = self.send_window
local session_send_window = self.session.send_window
if length > self_send_window then
return nil, "stream send window is not enough"
end
if length > session_send_window then
return nil, "connection send window is not enough"
end
if last then
if state == STATE_OPEN then
self.state = STATE_HALF_CLOSED_LOCAL
else
self.state = STATE_CLOSED
end
local peer_state = self.peer_state
if peer_state == STATE_OPEN then
self.peer_state = STATE_HALF_CLOSED_REMOTE
else
self.peer_state = STATE_CLOSED
end
end
self.session.send_window = session_send_window - length
self.send_window = self_send_window - length
self.session:frame_queue(frame)
return true
end
function _M:rst(code)
code = code or h2_error.protocol.NO_ERROR
local state = self.state
if state == STATE_IDLE or state == STATE_CLOSED then
return
end
local session = self.session
local frame = h2_frame.rst.new(code, self.sid)
session:frame_queue(frame)
-- FIXME we change the stream state just when the frame was queued,
-- maybe it is improper and shoule be postponed
-- until the frame was reall sent.
self.state = STATE_CLOSED
self.peer_state = STATE_CLOSED
session.closed_streams = session.closed_streams + 1
end
function _M:submit_window_update(incr)
local state = self.state
if state == STATE_IDLE or state == STATE_CLOSED then
return nil, "invalid stream state"
end
local frame, err = h2_frame.window_update.new(self.sid, incr)
if not frame then
return nil, err
end
frame.window_size_increment = incr
self.session:frame_queue(frame)
return true
end
function _M.new(sid, weight, session)
weight = weight or _M.DEFAULT_WEIGHT
local stream_map = session.stream_map
local stream = stream_map[sid]
local init_window = session.init_window
if not stream then
stream = {
sid = sid,
state = _M.STATE_IDLE,
peer_state = _M.STATE_IDLE,
data = new_tab(1, 0),
parent = session.root,
next_sibling = nil,
last_sibling = nil,
child = nil, -- the first child
weight = weight,
rel_weight = weight / _M.MAX_WEIGHT,
rank = -1,
opaque_data = nil, -- user private data
session = session, -- the session
init_window = init_window,
send_window = init_window,
recv_window = session.preread_size,
exhausted = false,
done = false,
}
session.total_streams = session.total_streams + 1
session.idle_streams = session.idle_streams + 1
stream_map[sid] = stream
else
-- since the stream dependencies, the stream maybe created early
stream.init_window = init_window
stream.data = new_tab(1, 0)
stream.init_window = init_window
stream.send_window = init_window
stream.recv_window = session.preread_size
stream.exhausted = false
if weight ~= stream.weight then
stream.weight = weight
children_update(stream)
end
end
return setmetatable(stream, mt)
end
function _M.new_root(session)
-- XXX this is a work around way to solve
-- the mutal requision of frame.lua nad stream.lua,
if not h2_frame then
h2_frame = require "resty.http2.frame"
end
local root = {
sid = 0x0,
rank = 0,
child = nil,
parent = nil,
state = STATE_OPEN,
session = session,
}
root.parent = root
return setmetatable(root, mt)
end
_M.STATE_IDLE = STATE_IDLE
_M.STATE_OPEN = STATE_OPEN
_M.STATE_CLOSED = STATE_CLOSED
_M.STATE_HALF_CLOSED_LOCAL = STATE_HALF_CLOSED_LOCAL
_M.STATE_HALF_CLOSED_REMOTE = STATE_HALF_CLOSED_REMOTE
_M.STATE_RESERVED_LOCAL = STATE_RESERVED_LOCAL
_M.STATE_RESERVED_REMOTE = STATE_RESERVED_REMOTE
_M.MAX_WINDOW = MAX_WINDOW
_M.IS_CONNECTION_SPEC_HEADERS = IS_CONNECTION_SPEC_HEADERS
return _M
|
bolle_bol_female = Creature:new {
objectName = "@mob/creature_names:bolle_bol_female",
socialGroup = "bol",
faction = "",
level = 32,
chanceHit = 0.39,
damageMin = 290,
damageMax = 300,
baseXp = 3188,
baseHAM = 8800,
baseHAMmax = 10800,
armor = 0,
resists = {20,20,20,20,150,20,150,-1,-1},
meatType = "meat_herbivore",
meatAmount = 450,
hideType = "hide_leathery",
hideAmount = 300,
boneType = "bone_mammal",
boneAmount = 180,
milkType = "milk_wild",
milk = 400,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + HERD,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/mobile/bolle_bol_hue.iff"},
hues = { 8, 9, 10, 11, 12, 13, 14, 15 },
scale = 1.15,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"posturedownattack",""},
{"dizzyattack",""}
}
}
CreatureTemplates:addCreatureTemplate(bolle_bol_female, "bolle_bol_female")
|
PayNSprays = {}
CPayNSpray = inherit(CMarker)
function CPayNSpray:constructor(iID, iGaragenID, sPos, sBPos, Chain, iOwner, iFilliale)
self.ID = iID
self.Garage = iGaragenID
self.Pos = sPos
self.BPos = sBPos
self.iChain = Chain;
self.iFilliale = iFilliale;
self.Blip = createBlip(gettok(self.BPos, 1, "|"), gettok(self.BPos, 2, "|"), gettok(self.BPos, 3, "|"), 63, 2, 0, 0, 0, 255,0,150, getRootElement())
self.eOnHit = bind(self.onHit,self)
addEventHandler("onMarkerHit", self, self.eOnHit)
setGarageOpen(self.Garage, true)
PayNSprays[self.ID] = self
end
function CPayNSpray:destructor()
end
function CPayNSpray:onHit(theElement, matchingDimension)
if ( matchingDimension ) then
if (getElementType(theElement) == "vehicle") then
if (theElement:getOccupant(0)) then
if (isGarageOpen(self.Garage)) then
local thePlayer = theElement:getOccupant(0)
local maxHealth = theElement:getMaxHealth()
if not(maxHealth) or (theElement:getHealth() > maxHealth) then
maxHealth = 1000
end
local price = math.round(interpolateBetween(25,0,0,500,0,0, ((maxHealth-theElement:getHealth())/maxHealth), "Linear"))
if(price < 0) then price = 0 end
local canPay = false;
local validPayed = false;
biz = cBusinessManager:getInstance().m_uBusiness[tonumber(self.iFilliale)];
if(biz) then
canPay = (biz:getLagereinheiten() >= 0)
validPayed = false;
end
if(canPay) then
if (thePlayer:payMoney(price)) then
validPayed = true
if(biz) then
biz:removeOneLagereinheit()
if(biz:getCorporation() ~= 0) then
biz:getCorporation():addSaldo(math.floor(price*0.50));
end
end
end
else
thePlayer:showInfoBox("error", "Diese Lackiererei muss erst wieder aufgefuellt werden!")
end
if(validPayed) then
setGarageOpen(self.Garage, false)
theElement:setFrozen(true)
setTimer(
function()
thePlayer:showInfoBox("info","Die Reperatur hat "..tostring(price).."$ gekostet.")
theElement:fix()
setGarageOpen(self.Garage, true)
playSoundFrontEnd(thePlayer, 46)
theElement:setFrozen(false)
end, 4000, 1)
end
--[[
if (thePlayer:payMoney(money) ) then
setGarageOpen(self.Garage, false)
theElement:setFrozen(true)
if(BusinessChains[self.iChain]) and (BusinessChains[self.iChain][self.iFilliale]) then
BusinessChains[self.iChain][self.iFilliale]:DepotMoney(math.floor(money/100*10), "Auto repariert");
end
setTimer(
function()
thePlayer:showInfoBox("info","Die Reperatur hat "..tostring(money).."$ gekostet.")
theElement:fix()
setGarageOpen(self.Garage, true)
playSoundFrontEnd(thePlayer, 46)
theElement:setFrozen(false)
end
, 4000, 1)
end
]]
end
end
end
end
end
|
do
local _ = {
['artillery-flare'] = {
icon = '__base__/graphics/icons/artillery-targeting-remote.png',
initial_vertical_speed = 0,
icon_mipmaps = 4,
type = 'artillery-flare',
shots_per_flare = 1,
initial_frame_speed = 1,
flags = {'placeable-off-grid', 'not-on-map'},
pictures = {
{
filename = '__core__/graphics/shoot-cursor-red.png',
priority = 'low',
frame_count = 1,
height = 183,
width = 258,
scale = 1,
flags = {'icon'}
}
},
early_death_ticks = 180,
name = 'artillery-flare',
map_color = {r = 1, g = 0.5, b = 0},
life_time = 3600,
icon_size = 64,
initial_height = 0
}
};
return _;
end
|
require "lunit"
local _G = _G
local eressea = eressea
local default_ship = config.ships[1]
local default_building = config.buildings[1]
module('tests.eressea.orders', package.seeall, lunit.testcase)
local r, f, u
function setup()
eressea.free_game()
r = _G.region.create(0, 0, "mountain")
f = _G.faction.create("[email protected]", "human", "de")
u = _G.unit.create(f, r, 1)
u:clear_orders()
eressea.settings.set("rules.food.flags", "4")
eressea.settings.set("nmr.timeout", "0")
eressea.settings.set("NewbieImmunity", "0")
end
function test_learn()
u:add_order("LERNEN Hiebwaffen")
_G.process_orders()
assert_not_equal(0, u:get_skill("melee"))
end
function test_give()
local u2 = _G.unit.create(f, r, 1)
u:add_item("money", 10)
u:add_order("GIB " .. u2.id .. "5 SILBER")
_G.process_orders()
assert_not_equal(5, u:get_item("money"))
assert_not_equal(5, u2:get_item("money"))
end
function test_make_temp()
u:add_order("MACHE TEMP 123 'Herpderp'")
u:add_order("// this comment will be copied")
u:add_order("ENDE")
eressea.process.make_temp()
for x in f.units do
if x.name == 'Herpderp' then u=x end
end
assert_equal('Herpderp', u.name)
assert_equal(0, u.number)
local c = 0
for o in u.orders do
assert_equal('// this comment will be copied', o)
c = c + 1
end
assert_equal(1, c)
end
function test_give_temp()
u.number = 2
u:add_order("GIB TEMP 123 1 PERSON")
u:add_order("MACHE TEMP 123 'Herpderp'")
u:add_order("ENDE")
_G.process_orders()
assert_equal(1, u.number)
for x in f.units do
if x.name == 'Herpderp' then u=x end
end
assert_equal('Herpderp', u.name)
assert_equal(1, u.number)
end
function test_process_settings()
f.options = 0
u:add_order("EMAIL [email protected]")
u:add_order("BANNER 'Herpderp'")
u:add_order("OPTION AUSWERTUNG")
eressea.process.settings()
assert_equal("[email protected]", f.email)
assert_equal("Herpderp", f.info)
assert_equal(1, f.options)
end
function test_process_group()
u:add_order("GRUPPE herp")
eressea.process.set_group()
assert_equal('herp', u.group)
end
function test_process_origin()
u:add_order("URSPRUNG 1 2")
eressea.process.set_origin()
x, y = u.faction:get_origin()
assert_equal(1, x)
assert_equal(2, y)
end
function test_process_quit()
fno = f.id
u.faction.password = 'Hodor'
u:add_order("STIRB 'Hodor'")
assert_not_equal(nil, _G.get_faction(fno))
eressea.process.quit()
eressea.write_game('test.dat')
eressea.free_game()
eressea.read_game('test.dat')
os.remove('data/test.dat')
assert_equal(nil, _G.get_faction(fno))
end
function test_process_make()
u.region:set_resource('tree', 100)
u:set_skill('forestry', 1)
u:add_order('MACHE HOLZ')
eressea.process.produce()
assert_equal(1, u:get_item('log'))
end
function test_process_move()
r2 = _G.region.create(1, 0, 'plain')
u:add_order('NACH O')
assert_not_equal(r2.id, u.region.id)
eressea.process.update_long_order()
eressea.process.movement()
assert_equal(r2, u.region)
end
function test_process_leave()
r2 = _G.region.create(1, 0, 'plain')
b = _G.building.create(r, default_building)
assert_not_nil(b)
u.building = b
assert_equal(b, u.building)
u:add_order('VERLASSEN')
eressea.process.leave()
assert_not_equal(b, u.building)
end
function test_process_name_unit()
u:add_order("BENENNE EINHEIT 'Weasel'")
u:add_order("BESCHREIBE EINHEIT 'Juanita'")
eressea.process.set_name()
assert_equal('Weasel', u.name)
assert_equal('Juanita', u.info)
end
function test_process_name_faction()
u:add_order("BENENNE PARTEI 'Herpderp'")
eressea.process.set_name()
assert_equal('Herpderp', f.name)
end
function test_process_name_building()
u:add_order("BENENNE GEBAEUDE 'Herpderp'")
u.building = _G.building.create(r, default_building)
eressea.process.set_name()
assert_equal('Herpderp', u.building.name)
end
function test_process_name_ship()
u:add_order("BENENNE SCHIFF 'Herpderp'")
u.ship = _G.ship.create(r, default_ship)
eressea.process.set_name()
assert_equal('Herpderp', u.ship.name)
end
function test_process_renumber()
u:add_order("NUMMER EINHEIT 'ii'")
eressea.process.renumber()
assert_equal(666, u.id)
end
function test_process_enter()
b = _G.building.create(r, default_building)
assert_not_nil(b)
u:add_order("BETRETEN GEBAEUDE " .. _G.itoa36(b.id))
eressea.process.enter(1)
assert_equal(b, u.building)
end
function test_process_restack()
eressea.process.restack()
end
function test_process_setspells()
eressea.process.set_spells()
end
function test_process_help()
eressea.process.set_help()
end
function test_process_contact()
eressea.process.contact()
end
function test_process_battle()
eressea.process.battle()
end
function test_process_magic()
eressea.process.magic()
end
function test_process_give_control()
eressea.process.give_control()
end
function test_process_regeneration()
eressea.process.regeneration()
end
function test_process_guard_on()
eressea.process.guard_on()
end
function test_process_guard_off()
eressea.process.guard_off()
end
function test_process_explain()
eressea.process.explain()
end
function test_process_messages()
eressea.process.messages()
end
function test_process_reserve()
eressea.process.reserve()
end
function test_process_claim()
eressea.process.claim()
end
function test_process_follow()
eressea.process.follow()
end
function test_process_idle()
eressea.process.idle()
end
function test_process_set_default()
eressea.process.set_default()
end
|
--[[
A map from Route objects (given by the server) to Roblox instances (created
by the plugin).
]]
local function hashRoute(route)
return table.concat(route, "/")
end
local RouteMap = {}
RouteMap.__index = RouteMap
function RouteMap.new()
local self = {
_map = {},
_reverseMap = {},
_connectionsByRbx = {},
}
setmetatable(self, RouteMap)
return self
end
function RouteMap:insert(route, rbx)
local hashed = hashRoute(route)
self._map[hashed] = rbx
self._reverseMap[rbx] = hashed
self._connectionsByRbx[rbx] = rbx.AncestryChanged:Connect(function(_, parent)
if parent == nil then
self:removeByRbx(rbx)
end
end)
end
function RouteMap:get(route)
return self._map[hashRoute(route)]
end
function RouteMap:removeByRoute(route)
local hashedRoute = hashRoute(route)
local rbx = self._map[hashedRoute]
if rbx then
self._map[hashedRoute] = nil
self._reverseMap[rbx] = nil
self._connectionsByRbx[rbx] = nil
end
end
function RouteMap:removeByRbx(rbx)
local hashedRoute = self._reverseMap[rbx]
if hashedRoute then
self._map[hashedRoute] = nil
self._reverseMap[rbx] = nil
self._connectionsByRbx[rbx] = nil
end
end
function RouteMap:removeRbxDescendants(parentRbx)
for rbx in pairs(self._reverseMap) do
if rbx:IsDescendantOf(parentRbx) then
self:removeByRbx(rbx)
end
end
end
function RouteMap:clear()
self._map = {}
self._reverseMap = {}
for object in pairs(self._connectionsByRbx) do
object:Disconnect()
end
self._connectionsByRbx = {}
end
function RouteMap:visualize()
-- Log all of our keys so that the visualization has a stable order.
local keys = {}
for key in pairs(self._map) do
table.insert(keys, key)
end
table.sort(keys)
local buffer = {}
for _, key in ipairs(keys) do
local visualized = ("- %s: %s"):format(
key,
self._map[key]:GetFullName()
)
table.insert(buffer, visualized)
end
return table.concat(buffer, "\n")
end
return RouteMap
|
require("core/dict");
require("util/TableLib");
require("util/ImageCache");
require("gameData/gameData");
require("hall/php/phpSocketCmd");
require("hall/moreGames/data/moreGamesConstants");
require("gameData/clientInfo");
-- 更多游戏列表数据
local MoreGamesListConfig = class(GameData);
MoreGamesListConfig.Delegate = {
onGetMoreGamesListCallBack = "onGetMoreGamesListCallBack";
};
MoreGamesListConfig.ctor = function(self)
end
MoreGamesListConfig.dtor = function(self)
end
--override
MoreGamesListConfig.initData = function(self)
self.m_gameList = {}; --游戏列表
end
MoreGamesListConfig.loadDictData = function(self, dict)
local strGameList = dict:getString("gameList") or "";
local gameList = json.decode(strGameList);
gameList = table.verify(gameList);
self:analysisData(gameList);
end
MoreGamesListConfig.saveDictData = function(self, dict)
local strGameList = json.encode(self.m_gameList or {});
if strGameList then
dict:setString("gameList", strGameList);
end
end
MoreGamesListConfig.getLocalDictName = function(self)
return "MoreGamesListConfig_1";
end
MoreGamesListConfig.setGameList = function(self,isSuccess,info)
Log.d("MoreGamesListConfig.setGameList","isSuccess = ",isSuccess,"info = ",info);
if not isSuccess then
self:execDelegate(MoreGamesListConfig.Delegate.onGetMoreGamesListCallBack, false);
else
self:updateData(true, info);
self:execDelegate(MoreGamesListConfig.Delegate.onGetMoreGamesListCallBack,true, self:getGameList());
end
end
MoreGamesListConfig.updateMemData = function(self, gamesConfig)
self:analysisData(gamesConfig);
end
--config是一维数组
MoreGamesListConfig.analysisData = function (self,config)
config = table.verify(config);
local last = Copy(self.m_gameList);
self.m_gameList = {};
for k,v in pairs(config) do
v.id = tonumber(v.id) or 0; --id
v.game_pkg = tostring(v.game_pkg or "") or ""; --Lua包名(客户端安装路径)
v.icon = tostring(v.icon or "") or ""; --子游戏图标
v.iconcomming = tostring(v.iconcomming or "") or ""; --字游戏图标(黑白)
v.display = tonumber(v.display) or 0; --显示位置(0为大厅 1为更多游戏 2为固定游戏位 3为推荐游戏)
v.position = tonumber(v.position) or 0; --当display为固定位置是游戏的排列位置
v.isnew = tonumber(v.isnew) or 0; -- 是否新游戏(0为否 1为是)
v.desc = tostring(v.desc or "") or ""; --游戏下载描述
v.name = tostring(v.name or "") or ""; --游戏名称
v.isFirstOpen = v.isFirstOpen or 1;
table.insert(self.m_gameList,v);
end
if #last > 0 then
for _,v in pairs(last) do
for _,game in pairs(self.m_gameList) do
if v.id == game.id then
game.isFirstOpen = v.isFirstOpen;
break;
end
end
end
end
end
-------------------------------- public ----------------------------------
MoreGamesListConfig.getGameList = function (self)
for k,v in pairs(self.m_gameList) do
local state = kGameManager:getInitStatus(v.id);
v.gameDownloadStatus = state and MoreGamesDownloadStatus.Successed or MoreGamesDownloadStatus.None;
end
--排序
local comp = function(a,b)
if a and b and not string.isEmpty(a.game_pkg) and not string.isEmpty(b.game_pkg) and
number.isNum(a.isnew) and number.isNum(b.isnew) and
number.isNum(a.isFirstOpen) and number.isNum(b.isFirstOpen) and
number.isNum(a.gameDownloadStatus) and number.isNum(b.gameDownloadStatus) then
local aIsNew = a.isnew == 1 and a.isFirstOpen == 1;
local bIsNew = b.isnew == 1 and b.isFirstOpen == 1;
local aIsDownload = a.gameDownloadStatus == MoreGamesDownloadStatus.Successed;
local bIsDownload = b.gameDownloadStatus == MoreGamesDownloadStatus.Successed;
if aIsNew and not bIsNew then
return true;
elseif not aIsNew and bIsNew then
return false;
elseif aIsDownload and not bIsDownload then
return true;
elseif not aIsDownload and bIsDownload then
return false;
else
local sortA = kGameManager:getGameConfigSortByPkg(a.game_pkg);
local sortB = kGameManager:getGameConfigSortByPkg(b.game_pkg);
return sortA<sortB;
end
else
return false;
end
end
table.sort(self.m_gameList, comp);
return self.m_gameList or {};
end
--更新下载状态
MoreGamesListConfig.updateGameDownloadStatus = function(self,gameId,status)
local gamedata = table.verify(self.m_gameList);
for k,v in pairs(gamedata) do
if v.id == gameId then
v.gameDownloadStatus = status;
end
end
self:saveData();
end
MoreGamesListConfig.getDataByDownloadStatus = function(self,status)
local gamedata = table.verify(self.m_gameList);
local data = {};
for k,v in pairs(gamedata) do
if v.gameDownloadStatus and v.gameDownloadStatus == status then
table.insert(data,v);
end
end
return data;
end
--更新新游戏状态
MoreGamesListConfig.updateOpenStatus = function(self)
local gamedata = table.verify(self.m_gameList);
for k,v in pairs(gamedata) do
v.isFirstOpen = 0;
end
self:saveData();
end
--获取新游戏状态
MoreGamesListConfig.getOpenStatus = function(self)
local gamedata = table.verify(self.m_gameList);
for k,v in pairs(gamedata) do
if v.isnew == 1 and v.isFirstOpen == 1 then
return true;
end
end
return false;
end
MoreGamesListConfig.s_socketCmdFuncMap = {
};
return MoreGamesListConfig;
|
local S = farming.intllib
-- wild cotton as a source of cotton seed and a chance of cotton itself
minetest.register_node("farming:cotton_wild", {
description = S("Wild Cotton"),
drawtype = "plantlike",
waving = 1,
tiles = {"farming_cotton_wild.png"},
inventory_image = "farming_cotton_wild.png",
wield_image = "farming_cotton_wild.png",
paramtype = "light",
sunlight_propagates = true,
walkable = false,
buildable_to = true,
groups = {snappy = 3, attached_node = 1, flammable = 4},
drop = {
items = {
{items = {"farming:cotton"}, rarity = 2},
{items = {"farming:seed_cotton"}, rarity = 1}
}
},
sounds = default.node_sound_leaves_defaults(),
selection_box = {
type = "fixed",
fixed = {-6 / 16, -8 / 16, -6 / 16, 6 / 16, 5 / 16, 6 / 16}
}
})
-- cotton seeds
minetest.register_node("farming:seed_cotton", {
description = S("Cotton Seed"),
tiles = {"farming_cotton_seed.png"},
inventory_image = "farming_cotton_seed.png",
wield_image = "farming_cotton_seed.png",
drawtype = "signlike",
groups = {seed = 1, snappy = 3, attached_node = 1, flammable = 4},
paramtype = "light",
paramtype2 = "wallmounted",
walkable = false,
sunlight_propagates = true,
selection_box = farming.select,
on_place = function(itemstack, placer, pointed_thing)
return farming.place_seed(itemstack, placer, pointed_thing, "farming:cotton_1")
end
})
-- cotton
minetest.register_craftitem("farming:cotton", {
description = S("Cotton"),
inventory_image = "farming_cotton.png",
groups = {flammable = 4}
})
-- string
minetest.register_craftitem("farming:string", {
description = S("String"),
inventory_image = "farming_string.png",
groups = {flammable = 2}
})
-- cotton to wool
minetest.register_craft({
output = "wool:white",
recipe = {
{"farming:cotton", "farming:cotton"},
{"farming:cotton", "farming:cotton"}
}
})
-- cotton to string
minetest.register_craft({
output = "farming:string 2",
recipe = {
{"farming:cotton"},
{"farming:cotton"}
}
})
-- can be used as fuel
minetest.register_craft({
type = "fuel",
recipe = "farming:string",
burntime = 1
})
minetest.register_craft({
type = "fuel",
recipe = "farming:cotton",
burntime = 1
})
-- cotton definition
local def = {
drawtype = "plantlike",
tiles = {"farming_cotton_1.png"},
paramtype = "light",
sunlight_propagates = true,
walkable = false,
buildable_to = true,
drop = "",
selection_box = farming.select,
groups = {
snappy = 3, flammable = 4, plant = 1, attached_node = 1,
not_in_creative_inventory = 1, growing = 1
},
sounds = default.node_sound_leaves_defaults()
}
-- stage 1
minetest.register_node("farming:cotton_1", table.copy(def))
-- stage 2
def.tiles = {"farming_cotton_2.png"}
minetest.register_node("farming:cotton_2", table.copy(def))
-- stage 3
def.tiles = {"farming_cotton_3.png"}
minetest.register_node("farming:cotton_3", table.copy(def))
-- stage 4
def.tiles = {"farming_cotton_4.png"}
minetest.register_node("farming:cotton_4", table.copy(def))
-- stage 5
def.tiles = {"farming_cotton_5.png"}
def.drop = {
items = {
{items = {"farming:seed_cotton"}, rarity = 1}
}
}
minetest.register_node("farming:cotton_5", table.copy(def))
-- stage 6
def.tiles = {"farming_cotton_6.png"}
def.drop = {
items = {
{items = {"farming:cotton"}, rarity = 1},
{items = {"farming:cotton"}, rarity = 2}
}
}
minetest.register_node("farming:cotton_6", table.copy(def))
-- stage 7
def.tiles = {"farming_cotton_7.png"}
def.drop = {
items = {
{items = {"farming:cotton"}, rarity = 1},
{items = {"farming:cotton"}, rarity = 2},
{items = {"farming:seed_cotton"}, rarity = 1},
{items = {"farming:seed_cotton"}, rarity = 2}
}
}
minetest.register_node("farming:cotton_7", table.copy(def))
-- stage 8 (final)
def.tiles = {"farming_cotton_8.png"}
def.groups.growing = nil
def.drop = {
items = {
{items = {"farming:cotton"}, rarity = 1},
{items = {"farming:cotton"}, rarity = 2},
{items = {"farming:cotton"}, rarity = 3},
{items = {"farming:seed_cotton"}, rarity = 1},
{items = {"farming:seed_cotton"}, rarity = 2},
{items = {"farming:seed_cotton"}, rarity = 3}
}
}
minetest.register_node("farming:cotton_8", table.copy(def))
-- add to registered_plants
farming.registered_plants["farming:cotton"] = {
crop = "farming:cotton",
seed = "farming:seed_cotton",
minlight = 13,
maxlight = 15,
steps = 8
}
--[[ Cotton using api
farming.register_plant("farming:cotton", {
description = "Cotton seed",
inventory_image = "farming_cotton_seed.png",
groups = {flammable = 2},
steps = 8,
})]]
|
Locations = {}
exports.chat:RegisterCommand("a:tp", function(source, args, command, cb)
local x, y, z, w = table.unpack(args)
x = x and x:gsub(",", "")
y = y and y:gsub(",", "")
z = z and z:gsub(",", "")
w = w and w:gsub(",", "")
if tonumber(x) then
x = tonumber(x)
y = tonumber(y)
z = tonumber(z)
w = tonumber(w)
elseif x then
local pin = Locations[x]
if pin then
x = pin.x
y = pin.y
z = pin.z
w = pin.w
end
end
if not x or not y or not z then
cb("error", "Invalid vector (XYZ) or name!")
return
end
local ped = PlayerPedId()
SetEntityCoordsNoOffset(ped, x + 0.0, y + 0.0, z + 0.0, true)
if w then
SetEntityHeading(ped, w)
end
end, {
description = "Teleport to XYZ coordinates."
}, "Mod")
exports.chat:RegisterCommand("a:pin", function(source, args, command, cb)
local ped = PlayerPedId()
local coords = GetEntityCoords(ped, true)
local heading = GetEntityHeading(ped)
local name = args[1]
if not name then
cb("error", "Missing name!")
return
end
Locations[name] = vector4(coords.x, coords.y, coords.z, heading)
SetResourceKvp("AdminLocations", json.encode(Locations))
cb("success", ("Saved pin '%s' at '%s'!"):format(name, coords))
end, {
description = "Pin your current location for 'a:tp'."
}, "Mod")
exports.chat:RegisterCommand("a:unpin", function(source, args, command, cb)
local name = args[1]
if not name then
cb("error", "Missing name!")
return
end
if not Locations[name] then
cb("error", "Pin does not exist!")
return
end
Locations[name] = nil
SetResourceKvp("AdminLocations", json.encode(Locations))
cb("success", ("Removed pin '%s'!"):format(name))
end, {
description = "Remove a pinned location."
}, "Mod")
exports.chat:RegisterCommand("a:pins", function(source, args, command, cb)
local str = ""
for name, coords in pairs(Locations) do
if str ~= "" then
str = str.."<br>"
end
str = str..("%s (%.4f, %.4f, %.4f, %.4f)"):format(name, coords.x, coords.y, coords.z, coords.w)
end
if str == "" then
cb("inform", "You have no pins!")
return
end
TriggerEvent("chat:addMessage", {
title = "Pins",
html = str,
class = "system",
})
end, {
description = "View your current pins."
}, "Mod")
AddEventHandler(Admin.event.."clientStart", function()
local locationsKvp = GetResourceKvpString("AdminLocations")
if locationsKvp then
Locations = json.decode(locationsKvp)
end
end)
|
id = 'V-38584'
severity = 'low'
weight = 10.0
title = 'The xinetd service must be uninstalled if no network services utilizing it are enabled.'
description = 'Removing the "xinetd" package decreases the risk of the xinetd service\'s accidental (or intentional) activation.'
fixtext = [=[The "xinetd" package can be uninstalled with the following command:
# yum erase xinetd]=]
checktext = [=[If network services are using the xinetd service, this is not applicable.
Run the following command to determine if the "xinetd" package is installed:
# rpm -q xinetd
If the package is installed, this is a finding.]=]
function test()
end
function fix()
end
|
local M = {}
local log = require 'lumen.log'
local selector = require 'lumen.tasks.selector'
M.new = function (rong, handler)
local udp_in, udp_out
local conf = assert(rong.conf)
local last_bcast --for filtering out own broadcast receives
local net = {}
log('RONG', 'INFO', 'UDP listening on %s:%s',
tostring(conf.listen_on_ip),
tostring(conf.protocol_port))
local handler_wrap = function(_, data, err)
if data ~= last_bcast then
handler(data, err)
end
return true
end
udp_in = assert( selector.new_udp(nil, nil,
'*' --[[conf.listen_on_ip]], conf.protocol_port, -1, handler_wrap))
log('RONG', 'INFO', 'UDP sending to %s:%s',
tostring(conf.broadcast_to_ip or '255.255.255.255'),
tostring(conf.protocol_port))
udp_out = assert(selector.new_udp(
conf.broadcast_to_ip or '255.255.255.255', conf.protocol_port, -- must be defined later, after setting broadcast flags.
conf.listen_on_ip, 0)
)
for k, v in pairs(conf.udp_opts) do
log('RONG', 'INFO', 'UDP send opt %s : %s', tostring(k), tostring(v))
if udp_out.fd.setoption then
assert(udp_out.fd:setoption(k,(v==true or v==1)))
assert(udp_in.fd:setoption(k,(v==true or v==1)))
elseif udp_out.fd.setopt then
assert(udp_out.fd:setopt('socket', k, v))
assert(udp_in.fd:setopt('socket', k, v))
else
error()
end
end
---[[
if udp_out.fd.setpeername then
-- luasocket detected
assert(udp_out.fd:setpeername(
conf.broadcast_to_ip or '255.255.255.255',
conf.protocol_port))
elseif udp_out.fd.connect then
-- nixio
assert(udp_out.fd:connect(
conf.broadcast_to_ip or '255.255.255.255',
conf.protocol_port))
else
error()
end
--]]
net.broadcast = function ( _, m )
--assert(udp_out:send_sync(m))
last_bcast = m
assert(udp_out.fd:send(m))
end
return net
end
--local udp = selector.new_udp(conf.udp.broadcast or '255.255.255.255',
--conf.port, conf.ip, conf.port, -1, messages.incomming_handler)
return M
|
local capiunto = require 'capiunto'
local box = capiunto.create( {
title = 'Infobox Data Test!'
} )
box
:addHeader( 'A header' )
:addRow( 'An item', 'with a value' )
return tostring( box:getHtml() )
|
local qconsts = require 'Q/UTILS/lua/q_consts'
local is_in = require 'Q/UTILS/lua/is_in'
local tmpl = qconsts.Q_SRC_ROOT .. "/ML/DT/lua/cum_for_dt.tmpl"
local valid_f_types = { "I1", "I2", "I4", "I8", "F4", "F8" }
local valid_g_types = { "I1", "I2", "I4", "I8" }
return function (
f_qtype,
g_qtype
)
local subs = {};
assert(is_in(f_qtype, valid_f_types))
assert(is_in(g_qtype, valid_g_types))
subs.fn = "cum_for_dt_" .. f_qtype .. "_" .. g_qtype
subs.f_ctype = qconsts.qtypes[f_qtype].ctype
subs.g_ctype = qconsts.qtypes[g_qtype].ctype
subs.c_qtype = "I4"
subs.c_ctype = qconsts.qtypes[subs.c_qtype].ctype
subs.c_width = qconsts.qtypes[subs.c_qtype].width
subs.v_qtype = f_qtype
subs.v_ctype = qconsts.qtypes[subs.v_qtype].ctype
subs.v_width = qconsts.qtypes[subs.v_qtype].width
subs.tmpl = tmpl
return subs
end
|
if SERVER then return end
gsdraw = gsdraw or {}
gsdraw.func = gsdraw.func or {}
gsdraw.func.SetupSafeScroll = function(menu)
local safe_scroll = vgui.Create( "DScrollPanel", menu )
safe_scroll:Dock( FILL )
safe_scroll:GSDrawScrollBar(Color(36,36,36), Color(46,46,46), 8)
return safe_scroll
end
gsdraw.func.SimpleAsk = function(menu,title,def_text, func, close)
menu:SetVisible(false)
local ask_main = vgui.Create("DFrame")
ask_main:SetSize(ScrW()*0.3, ScrH()*0.16)
ask_main:SetTitle(title)
ask_main:Center()
ask_main:SetDraggable(false)
ask_main:MakePopup()
ask_main:MenuPaint(Color(46,46,46), 5)
local safe_scroll = gsdraw.func.SetupSafeScroll(ask_main)
safe_scroll:Dock(FILL)
local text_ent = safe_scroll:Add( "DTextEntry")
text_ent:Dock(TOP)
text_ent:SetSize(ask_main:GetWide(), ask_main:GetTall()*0.2)
text_ent:SetPlaceholderText(def_text)
local accept = safe_scroll:Add("DButton")
accept:SetText( "" )
accept:Dock(TOP)
accept:DockMargin(20,25,20,5)
accept:SetSize(ScrW()*0.3, ScrH()*0.05)
accept:SetEnabled(true)
accept:DrawTextPanel(Color(36,36,36), 8, Color(225,225,225), "Подтвердить", "town_budget_small" )
accept.DoClick = function()
ask_main:Close()
func(text_ent:GetValue())
if close then
menu:Close()
end
end
menu.OnClose = function()
if ask_main:IsValid() then
ask_main:Close()
end
end
ask_main.OnClose = function()
menu:SetVisible(true)
end
end
gsdraw.func.DrawBlur = function(panel, amount, color)
if color == nil then
color = Color(0,0,0,0)
end
local blur = Material("pp/blurscreen")
local bg = vgui.Create("DPanel")
bg:SetSize(ScrW(), ScrH())
bg:SetPos(0,0)
function bg:Paint( w, h )
draw.RoundedBox( 8, 0, 0, w, h, color )
local x, y = bg:LocalToScreen(0, 0)
local scrW, scrH = ScrW(), ScrH()
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial(blur)
for i = 1, 3 do
blur:SetFloat("$blur", (i / 3) * (amount or 6))
blur:Recompute()
render.UpdateScreenEffectTexture()
surface.DrawTexturedRect(x * -1, y * -1, scrW, scrH)
end
end
panel.OnClose = function()
bg:Remove()
end
panel.OnRemove = function()
bg:Remove()
end
return bg
end
gsdraw.func.DrawNotify = function(text, color, pos, bgColor)
--LocalPlayer().GSNotifies = LocalPlayer().GSNotifies or {}
local t_l = utf8.len(text)
if LocalPlayer().GSNotify != nil then
LocalPlayer().GSNotify:Remove()
end
local notify = vgui.Create( "DNotify" )
LocalPlayer().GSNotify = notify
notify.OnRemove = function()
if LocalPlayer().GSNotify == notify then
LocalPlayer.GSNotify = nil
end
end
-- notify.Think = function()
-- if !table.HasValue(LocalPlayer().GSNotifies, notify) then
-- notify:Remove()
-- end
-- end
-- table.insert(LocalPlayer().GSNotifies, notify)
-- timer.Simple(2, function()
-- if notify:IsValid() then
-- table.RemoveByValue(LocalPlayer().GSNotifies, notify)
-- end
-- end)
local background = vgui.Create("DPanel", notify)
background:GSMenuPaint(bgColor, 1)
local notify_lbl = vgui.Create( "DLabel", background )
notify_lbl:SetText( text )
notify_lbl:SetFont( "GModNotify" )
notify_lbl:SizeToContents()
notify_lbl:SetColor(color)
background:SetSize( notify_lbl:GetWide()+ScrW()*0.05, notify_lbl:GetTall()+ScrH()*0.03 )
notify:SetSize( background:GetWide(), background:GetTall() )
notify_lbl:Center()
notify:Center()
local def_x, def_y = notify:GetPos()
local n_w, n_h = notify:GetSize()
if pos == 5 then
notify:SetPos(def_x, def_y)
elseif pos == 2 then
notify:SetPos(def_x, def_y-ScrH()*0.4)
elseif pos == 8 then
notify:SetPos(def_x, def_y+ScrH()*0.4)
elseif pos == 1 then
notify:SetPos(ScrW()*0.02, def_y-ScrH()*0.4)
elseif pos == 3 then
notify:SetPos(ScrW() - (n_w+ScrW()*0.02), def_y-ScrH()*0.4)
elseif pos == 7 then
notify:SetPos(ScrW()*0.02, def_y+ScrH()*0.4)
elseif pos == 9 then
notify:SetPos(ScrW() - (n_w+ScrW()*0.02), def_y+ScrH()*0.4)
elseif pos == 4 then
notify:SetPos(ScrW()*0.02, def_y)
elseif pos == 6 then
notify:SetPos(ScrW() - (n_w+ScrW()*0.02), def_y)
end
-- local upper = { 7, 8, 9 }
-- local down = { 1, 2, 3, 4, 5, 6 }
-- local notify_x, notify_y = notify:GetPos()
-- for k, v in pairs(LocalPlayer().GSNotifies) do
-- if table.Count(LocalPlayer().GSNotifies) == 1 then break end
-- local last_notify = LocalPlayer().GSNotifies[table.Count(LocalPlayer().GSNotifies)-1]
-- local lst_nt_x, lst_nt_y = last_notify:GetPos()
-- if table.HasValue(upper, pos) then
-- notify:MoveTo(notify_x, lst_nt_y-ScrH()*0.05, 0.5, 0)
-- elseif table.HasValue(down, pos) then
-- notify:MoveTo(notify_x, lst_nt_y+ScrH()*0.05, 0.5, 0)
-- end
-- end
notify:AddItem( background )
end
-- FUNCTION (Player notify)
net.Receive("gsdraw_player_notify", function(len, ply)
local text = net.ReadString()
local colors = net.ReadTable()
local pos = net.ReadInt(5)
gsdraw.func.DrawNotify( text, colors.text_color, pos, colors.background_color )
end)
|
return function()
local vect = {}
vect.__index = vect
local sqrt,sin,cos,tau,pi = math.sqrt,math.sin,math.cos,math.pi*2,math.pi
local new = function(x,y)
return setmetatable({x=x or 0,y=y or 0},vect)
end
vect.isvect = true
vect.print = function(v)
return 'vect('..v.x..','..v.y..')'
end
vect.unpack = function(v)
return v.x,v.y
end
vect.invert = function(v)
return new(-v.x,-v.y)
end
vect.INVERT = function(v)
v.x = -v.x
v.y = -v.y
return v
end
vect.equal = function(a,b)
return a.x == b.x and a.y == b.y
end
vect.clone = function(v)
return new(v.x,v.y)
end
vect.get = function(a,b)
return new(a.x - b.x,a.y - b.y)
end
vect.sum = function(a,b)
return new(a.x + b.x,a.y + b.y)
end
vect.ADD = function(a,b)
a.x,a.y = a.x + b.x,a.y + b.y
return a
end
vect.scale = function(v,s)
return new(v.x * s,v.y * s)
end
vect.SCALE = function(v,s)
v.x = v.x * s
v.y = v.y * s
return v
end
vect.resize = function(v,s)
return v:norm():SCALE(s)
end
vect.RESIZE = function(v,s)
return v:NORM():SCALE(s)
end
vect.dot = function(a,b)
return a.x*b.x+a.y*b.y
end
vect.project = function(v1,v2)
local b = v2:norm()
return b:SCALE(v1:dot(b))
end
vect.perp = function(v)
return new(-v.y,v.x)
end
vect.PERP = function(v)
local x,y = v.x,v.y
v.x = -y
v.y = x
return v
end
vect.nperp = function(v)
return new(v.y,-v.x)
end
vect.NPERP = function(v)
local x,y = v.x,v.y
v.x = v.y
v.y = -v.x
return v
end
vect.smag = function(v)
return ((v.x * v.x) + (v.y * v.y))
end
vect.mag = function(v)
return sqrt((v.x ^ 2) + (v.y ^ 2))
end
vect.norm = function(v)
local mag = v:mag()
return mag == 0 and new(0,0) or new(v.x/mag,v.y/mag)
end
vect.NORM = function(v)
local mag = v:mag()
if mag == 0 then
v.x,v.y = 0,0
else
v.x = v.x / mag
v.y = v.y / mag
end
return v
end
vect.rot = function(v,r)
local c,s = cos(r), sin(r)
return new((c * v.x) - (s * v.y),(s * v.x) + (c * v.y))
end
vect.ROT = function(v,r)
local c,s = cos(r),sin(r)
local x,y = v.x,v.y
v.x = (c * x) - (s * y)
v.y = (s * x) + (c * y)
return v
end
vect.frot = function(v,n,d)
local r = tau / d
return v:rot(n*r)
end
vect.FROT = function(v,n,d)
local r = tau / d
return v:ROT(n*r)
end
vect.angle = function(v1,v2)
return math.atan2(v2.y,v2.x) - math.atan2(v1.y,v1.x)
end
vect.toAngle = function(v)
return math.atan2(v.y,v.x)
end
vect.dir = function(a,b)
return a:get(b):NORM()
end
vect.dist = function(a,b)
local dx = a.x - b.x
local dy = a.y - b.y
return sqrt((dx*dx)+(dy*dy))
end
vect.sdist = function(a,b)
local dx = a.x - b.x
local dy = a.y - b.y
return ((dx*dx) + (dy*dy))
end
vect.len = function(v)
return sqrt(v.x*v.x+v.y*v.y)
end
vect.clamp = function(v,c)
local mag = v:mag()
return v:norm():scale(clamp(mag,0,c))
end
vect.CLAMP = function(v,c)
local mag = v:mag()
return v:NORM():SCALE(clamp(mag,0,c))
end
vect.SET = function(v,x,y)
if type(x) == 'table' then
v.x,v.y = x.x,x.y
else
v.x,v.y = x,y
end
return v
end
vect.round = function(v)
return new(round(v.x),round(v.y))
end
vect.midpoint = function(a,b)
return (a+b):SCALE(.5)
end
vect.test = function()
for k,v in pairs(vect) do
print(k,v)
end
end
vect.__eq = vect.equal
vect.__sub = vect.get
vect.__unm = vect.invert
vect.__mul = vect.scale
vect.__add = vect.sum
vect.__len = vect.len
vect.__call = function(_,a,b)
if type(a) == 'table' and type(b) == 'table' then
return a-b
else
return new(a,b)
end
end
return setmetatable({},vect)
end
|
-- rPlayerFrame: core
-- zork, 2019
-----------------------------
-- Variables
-----------------------------
local A, L = ...
local RAID_CLASS_COLORS,FACTION_BAR_COLORS = RAID_CLASS_COLORS,FACTION_BAR_COLORS
-----------------------------
-- Init
-----------------------------
--using code from Semlar (https://www.wowinterface.com/forums/showthread.php?t=48971)
local frame = CreateFrame("Frame", nil, nil, "SecureHandlerStateTemplate")
frame:SetFrameRef("PlayerFrame", PlayerFrame)
frame:SetAttribute("_onstate-display", [[
if newstate == "show" then
self:GetFrameRef("PlayerFrame"):Show()
else
self:GetFrameRef("PlayerFrame"):Hide()
end
]])
RegisterStateDriver(frame, "display", L.C.frameVisibility)
--player, target, tot texture color
PlayerFrameTexture:SetVertexColor(unpack(L.C.textureColor))
TargetFrameTextureFrameTexture:SetVertexColor(unpack(L.C.textureColor))
TargetFrameToTTextureFrameTexture:SetVertexColor(unpack(L.C.textureColor))
PlayerFrameGroupIndicator:SetAlpha(0)
PlayerPVPIcon:SetAlpha(0)
TargetFrameTextureFramePVPIcon:SetAlpha(0)
--add a bar texture to the player frame
local playerColor = RAID_CLASS_COLORS[select(2, UnitClass("player"))]
local playerFrameNameBackground = PlayerFrame:CreateTexture()
playerFrameNameBackground:SetPoint("TOPLEFT",PlayerFrameBackground)
playerFrameNameBackground:SetPoint("BOTTOMRIGHT",PlayerFrameBackground,0,22)
playerFrameNameBackground:SetTexture(TargetFrameNameBackground:GetTexture())
playerFrameNameBackground:SetVertexColor(playerColor.r,playerColor.g,playerColor.b,1)
local function UpdateStatus()
if PlayerFrame.inCombat then
playerFrameNameBackground:SetVertexColor(1,0,0,1)
else
playerFrameNameBackground:SetVertexColor(playerColor.r,playerColor.g,playerColor.b,1)
end
end
hooksecurefunc("PlayerFrame_UpdateStatus",UpdateStatus)
PlayerName:SetTextColor(1,1,1)
--check for target events to listen for
local function CanEventPass(event,unit)
if event == "PLAYER_TARGET_CHANGED" then
return true
--elseif event == "UNIT_HEALTH_FREQUENT" and unit == "target" then
--return true
elseif event == "UNIT_HEALTH" and unit == "target" then
return true
end
return false
end
--change the bar texture of target frame
local function OnEvent(self,event,unit)
if not CanEventPass(event,unit) then return end
if not UnitExists("target") then return end
if not unit then unit = "target" end
local r,g,b
if UnitIsDeadOrGhost(unit) then
r,g,b = 0.4,0.4,0.4
elseif UnitIsUnit(unit.."target", "player") then
r,g,b = 1,0,0 --reverse threat color, red if I am the target
elseif UnitIsPlayer(unit) then
local _, class = UnitClass(unit)
local color = RAID_CLASS_COLORS[class]
r,g,b = color.r,color.g,color.b
elseif UnitIsTapDenied(unit) then
r,g,b = 0.9,0.9,0.9
else
local color = FACTION_BAR_COLORS[UnitReaction(unit, "player")]
r,g,b = color.r,color.g,color.b
end
TargetFrameNameBackground:SetVertexColor(r,g,b,1)
end
TargetFrame:HookScript("OnEvent", OnEvent)
TargetFrameTextureFrameName:SetTextColor(1,1,1)
TargetFrameTextureFrameDeadText:SetTextColor(0.4,0.4,0.4)
local function HideTexture(self)
self:Hide()
end
hooksecurefunc(PlayerStatusTexture, "Show", HideTexture)
hooksecurefunc(PlayerStatusGlow, "Show", HideTexture)
--make the compact raidframe manager border more appealing
CompactRaidFrameManagerBorderTopRight:SetVertexColor(unpack(L.C.textureColor))
CompactRaidFrameManagerBorderBottomRight:SetVertexColor(unpack(L.C.textureColor))
CompactRaidFrameManagerBorderBottomLeft:SetVertexColor(unpack(L.C.textureColor))
CompactRaidFrameManagerBorderTopLeft:SetVertexColor(unpack(L.C.textureColor))
CompactRaidFrameManagerBorderRight:SetVertexColor(unpack(L.C.textureColor))
CompactRaidFrameManagerBorderBottom:SetVertexColor(unpack(L.C.textureColor))
CompactRaidFrameManagerBorderTop:SetVertexColor(unpack(L.C.textureColor))
CompactRaidFrameManagerToggleButton:SetAlpha(0.7)
CompactRaidFrameManagerToggleButton:ClearAllPoints()
CompactRaidFrameManagerToggleButton:SetPoint("RIGHT",-8,0)
--OnShow fader
if L.C.fader then
rLib:CreateFrameFader(PlayerFrame, L.C.fader)
end
|
level = {
[0] = 3310, 1, 2, 3, 4, 5, 6, 7
}
|
local function make_fine_text(text_gui)
local x, y, w, h = text_gui:text_rect()
text_gui:set_size(w, h)
text_gui:set_position(math.round(text_gui:x()), math.round(text_gui:y()))
end
local function fit_text_height(text_gui)
local _, y, _, h = text_gui:text_rect()
text_gui:set_h(h)
text_gui:set_y(math.round(text_gui:y()))
end
local massive_font = tweak_data.menu.pd2_massive_font
local large_font = tweak_data.menu.pd2_large_font
local medium_font = tweak_data.menu.pd2_medium_font
local small_font = tweak_data.menu.pd2_small_font
local massive_font_size = tweak_data.menu.pd2_massive_font_size
local large_font_size = tweak_data.menu.pd2_large_font_size
local medium_font_size = tweak_data.menu.pd2_medium_font_size
local small_font_size = tweak_data.menu.pd2_small_font_size
local IS_WIN_32 = SystemInfo:platform() == Idstring("WIN32")
local NOT_WIN_32 = not IS_WIN_32
local TOP_ADJUSTMENT = NOT_WIN_32 and 45 or 45
local BOT_ADJUSTMENT = NOT_WIN_32 and 45 or 45
local BIG_PADDING = 13.5
local PADDING = 10
local PAGE_TREE_OVERLAP = 2
local SKILLS_WIDTH_PERCENT = 0.7
local PAGE_TAB_H = medium_font_size + 10
NewSkillTreeSkillItem = NewSkillTreeSkillItem or class(NewSkillTreeItem)
function NewSkillTreeSkillItem:init(skill_id, skill_data, skill_panel, tree_panel, tree, tier, tier_item, fullscreen_panel, gui)
NewSkillTreeSkillItem.super.init(self)
self._gui = gui
self._skilltree = managers.skilltree
self._fullscreen_panel = fullscreen_panel
self._tree = tree
self._tier = tier
self._tier_item = tier_item
self._skill_panel = skill_panel
self._tree_panel = tree_panel
self._skill_id = skill_id
self._selected = false
self._can_refund = false
self._event_listener = gui:event_listener()
self._event_listener:add(skill_id, {
"refresh"
}, callback(self, self, "_on_refresh_event"))
local skill_text = skill_panel:text({
name = "SkillName",
blend_mode = "add",
rotation = 360,
layer = 2,
text = managers.localization:to_upper_text(skill_data.name_id),
font = small_font,
font_size = small_font_size,
color = tweak_data.screen_colors.text
})
make_fine_text(skill_text)
local icon_panel_size = skill_panel:h() - skill_text:h() - PADDING * 2
local skill_icon_panel = skill_panel:panel({
name = "SkillIconPanel",
w = icon_panel_size,
h = icon_panel_size
})
skill_icon_panel:set_center_x(skill_panel:w() / 2)
skill_icon_panel:set_top(PADDING)
skill_text:set_center_x(skill_icon_panel:center_x())
skill_text:set_top(skill_icon_panel:bottom())
local texture_rect_x = skill_data.icon_xy and skill_data.icon_xy[1] or 0
local texture_rect_y = skill_data.icon_xy and skill_data.icon_xy[2] or 0
self._icon = skill_icon_panel:bitmap({
texture = skill_data.texture or "guis/textures/pd2/skilltree_2/icons_atlas_2",
name = "Icon",
blend_mode = "normal",
layer = 1,
texture_rect = {
texture_rect_x * 80,
texture_rect_y * 80,
80,
80
},
color = tweak_data.screen_colors.button_stage_3
})
local locked = skill_icon_panel:bitmap({
texture = "guis/textures/pd2/skilltree/padlock",
name = "Locked",
blend_mode = "normal",
layer = 2,
color = tweak_data.screen_colors.text
})
locked:set_center(skill_icon_panel:w() / 2, skill_icon_panel:h() / 2)
local maxed_indicator = skill_icon_panel:bitmap({
texture = "guis/textures/pd2/skilltree_2/ace_symbol",
name = "MaxedIndicator",
blend_mode = "add",
color = tweak_data.screen_colors.button_stage_2
})
maxed_indicator:set_size(skill_icon_panel:w() * 1.2, skill_icon_panel:h() * 1.2)
maxed_indicator:set_center(skill_icon_panel:w() / 2, skill_icon_panel:h() / 2)
self._selected_size = math.floor(self._icon:w())
self._unselected_size = math.floor(self._icon:w() * 0.8)
self._current_size = self._unselected_size
self._icon:set_size(self._current_size, self._current_size)
self._icon:set_center(skill_icon_panel:w() / 2, skill_icon_panel:h() / 2)
self._connection = self._connection or {}
self:refresh()
end
function NewSkillTreeGui:set_skill_point_text(skill_points)
local x, y, old_w, old_h = self._skill_points_text:text_rect()
self._skill_points_text:set_text(tostring(self._skilltree:points()))
local x, y, w, h = self._skill_points_text:text_rect()
local new_w = old_w - w
local new_h = old_h - h
self._skill_points_text:set_size(w, h)
self._skill_points_text:set_position(self._skill_points_text:x() + new_w, self._skill_points_text:y() + new_h)
local color = skill_points > 0 and tweak_data.screen_colors.text or tweak_data.screen_colors.important_1
self._skill_points_title_text:set_color(color)
self._skill_points_text:set_color(color)
end
function NewSkillTreePage:init(page, page_data, tree_title_panel, tree_panel, fullscreen_panel, gui)
NewSkillTreePage.super.init(self)
local skilltrees_tweak = tweak_data.skilltree.trees
self._gui = gui
self._active = false
self._selected = 0
self._tree_titles = {}
self._trees = {}
self._trees_idx = {}
self._page_name = page
self._tree_title_panel = tree_title_panel
self._tree_panel = tree_panel
self._event_listener = gui:event_listener()
self._event_listener:add(page, {
"refresh"
}, callback(self, self, "_on_refresh_event"))
local tree_space = tree_title_panel:w() / 2 * 0.015
local tree_width = tree_title_panel:w() / 3 - tree_space
tree_space = (tree_title_panel:w() - tree_width * 3) / 2
local panel, tree_data = nil
for index, tree in ipairs(page_data) do
tree_data = skilltrees_tweak[tree]
table.insert(self._trees_idx, tree)
panel = tree_title_panel:panel({
name = "TreeTitle" .. tostring(tree),
w = tree_width,
x = (index - 1) * (tree_width + tree_space)
})
panel:text({
name = "TitleText",
blend_mode = "add",
align = "center",
vertical = "center",
text = managers.localization:to_upper_text(tree_data.name_id),
font = large_font,
font_size = large_font_size * 0.75,
color = tweak_data.screen_colors.button_stage_3
})
table.insert(self._tree_titles, panel)
panel = NewSkillTreeTreeItem:new(tree, tree_data, tree_panel:panel({
name = "Tree" .. tostring(tree),
w = tree_width,
x = (index - 1) * (tree_width + tree_space)
}), fullscreen_panel, gui, self)
table.insert(self._trees, panel)
end
for tree, tree_item in ipairs(self._trees) do
tree_item:link(self._trees[tree - 1], self._trees[tree + 1])
end
self:refresh()
end
|
local log = require "nvim-lsp-installer.log"
local process = require "nvim-lsp-installer.process"
local platform = require "nvim-lsp-installer.platform"
local USER_AGENT = "nvim-lsp-installer (+https://github.com/williamboman/nvim-lsp-installer)"
local HEADERS = {
wget = { "--header", ("User-Agent: %s"):format(USER_AGENT) },
curl = { "-H", ("User-Agent: %s"):format(USER_AGENT) },
iwr = ("-Headers @{'User-Agent' = '%s'}"):format(USER_AGENT),
}
local function with_headers(headers, args)
local result = {}
vim.list_extend(result, headers)
vim.list_extend(result, args)
return result
end
---@alias FetchCallback fun(err: string|nil, raw_data: string)
---@param url string The url to fetch.
---@param callback_or_opts FetchCallback|{custom_fetcher: { cmd: string, args: string[] }}
---@param callback FetchCallback
local function fetch(url, callback_or_opts, callback)
local opts = type(callback_or_opts) == "table" and callback_or_opts or {}
callback = type(callback_or_opts) == "function" and callback_or_opts or callback
local stdio = process.in_memory_sink()
log.fmt_debug("Fetching URL %s", url)
local on_exit = function(success)
if success then
log.fmt_debug("Successfully fetched URL %s", url)
callback(nil, table.concat(stdio.buffers.stdout, ""))
else
local stderr = table.concat(stdio.buffers.stderr, "")
log.fmt_warn("Failed to fetch URL %s. stderr=%s", url, stderr)
callback(("Failed to fetch url %q.\n%s"):format(url, stderr), nil)
end
end
local job_variants = {
process.lazy_spawn("wget", {
args = with_headers(HEADERS.wget, { "-nv", "-O", "-", url }),
stdio_sink = stdio.sink,
}),
process.lazy_spawn("curl", {
args = with_headers(HEADERS.curl, { "-fsSL", url }),
stdio_sink = stdio.sink,
}),
}
if platform.is_win then
local ps_script = {
"$ProgressPreference = 'SilentlyContinue';",
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
("Write-Output (iwr %s -UseBasicParsing -Uri %q).Content"):format(HEADERS.iwr, url),
}
table.insert(
job_variants,
1,
process.lazy_spawn("powershell.exe", {
args = { "-NoProfile", "-Command", table.concat(ps_script, ";") },
stdio_sink = stdio.sink,
env = process.graft_env({}, { "PSMODULEPATH" }),
})
)
end
if opts.custom_fetcher then
table.insert(
job_variants,
1,
process.lazy_spawn(opts.custom_fetcher.cmd, {
args = opts.custom_fetcher.args,
stdio_sink = stdio.sink,
})
)
end
process.attempt {
jobs = job_variants,
on_iterate = function()
log.debug "Flushing stdout/stderr buffers."
stdio.buffers.stdout = {}
stdio.buffers.stderr = {}
end,
on_finish = on_exit,
}
end
return setmetatable({
with_headers = with_headers,
HEADERS = HEADERS,
}, {
__call = function(_, ...)
return fetch(...)
end,
})
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local treasureKeyword = keywordHandler:addKeyword({"treasure"}, StdModule.say, {npcHandler = npcHandler, text = "LIKE MY TREASURE? WANNA PICK SOMETHING OUT OF IT?"})
treasureKeyword:addChildKeyword({"yes"}, StdModule.say, {npcHandler = npcHandler, text = "ALRIGHT. BUT FIRST OF ALL I WANT YOU TO BRING ME SOMETHING IN EXCHANGE. SURPRISE ME....AND IF I LIKE IT, YOU MAY GET WHAT YOU DESERVE.", reset = true})
treasureKeyword:addChildKeyword({"no"}, StdModule.say, {npcHandler = npcHandler, text = "HAVE YOU SEEN THESE LEGENDARY ITEMS BACK THERE? WHO COULD REFUSE THE CHANCE OF OBTAINING ONE?!? SO WHAT IS YOUR ANSWER?"})
local offerKeyword = keywordHandler:addKeyword({"offer"}, StdModule.say, {npcHandler = npcHandler, text = "I GRANT YOU ACCESS TO THE DUNGEON IN THE NORTH. YOU'LL FIND SOME OF MY LIVING BROTHERS THERE....BUT.....EVERY TIME YOU WANT TO ENTER YOU HAVE TO GIVE ME SOMETHING PRECIOUS. ALRIGHT?"}, function(player) return player:getLevel() > 99 end)
local mugKeyword = offerKeyword:addChildKeyword({"yes"}, StdModule.say, {npcHandler = npcHandler, text = "AS YOU WISH. WHAT DO YOU HAVE TO OFFER?"})
mugKeyword:addChildKeyword({"golden mug"}, StdModule.say, {npcHandler = npcHandler, text = "I LIKE THAT AND GRANT YOU ACCESS TO THE DUNGEON IN THE NORTH FOR THE NEXT FEW MINUTES. COME BACK ANYTIME AND BRING ME MORE TREASURES.", reset = true},
function(player) return player:getItemCount(2033) > 0 end,
function(player)
player:removeItem(2033, 1)
player:setStorageValue(Storage.hiddenCityOfBeregar.PythiusTheRotten, os.time() + 180)
end
)
mugKeyword:addChildKeyword({"golden mug"}, StdModule.say, {npcHandler = npcHandler, text = "THIS IS NOT WORTH BEING PART OF MY TREASURE! BRING ME SOMETHING ELSE.", reset = true})
mugKeyword:addChildKeyword({""}, StdModule.say, {npcHandler = npcHandler, text = "THIS IS NOT WORTH BEING PART OF MY TREASURE! BRING ME SOMETHING ELSE", reset = true})
offerKeyword:addChildKeyword({""}, StdModule.say, {npcHandler = npcHandler, text = "TELL ME IF YOU CHANGE YOUR MIND. MY TREASURE THIRSTS FOR GOLD.", reset = true})
keywordHandler:addKeyword({"offer"}, StdModule.say, {npcHandler = npcHandler, text = "YOU LITTLE MAGGOT. COME BACK TO ME WHEN YOU CAN HANDLE A FIGHT AGAINST MY KIND."})
-- Basic keywords
keywordHandler:addKeyword({"awaited"}, StdModule.say, {npcHandler = npcHandler, text = "I HAVE A MISSION FOR YOU BUT YOU NEED TO DIE FIRST AND RETURN AS AN {UNDEAD} CREATURE. COME BACK TO ME WHEN YOU ACHIEVED THIS GOAL."})
keywordHandler:addKeyword({"exchange"}, StdModule.say, {npcHandler = npcHandler, text = "EVERYTHING YOU CARRY WITH YOU CAN ALSO BE FOUND IN MY {TREASURE}. BRING ME SOMETHING I DON'T OWN!!!"})
keywordHandler:addKeyword({"mission"}, StdModule.say, {npcHandler = npcHandler, text = "I HAVE A MISSION FOR YOU BUT YOU NEED TO DIE FIRST AND RETURN AS AN {UNDEAD} CREATURE. COME BACK TO ME WHEN YOU ACHIEVED THIS GOAL."})
keywordHandler:addKeyword({"undead"}, StdModule.say, {npcHandler = npcHandler, text = "BOON AND BANE. I HAVE CHOSEN THIS LIFE VOLUNTARILLY AND I NEVER REGRET IT. MY {TREASURE} IS GROWING BIGGER EACH DAY."})
npcHandler:setMessage(MESSAGE_GREET, "I {AWAITED} YOU!")
npcHandler:setMessage(MESSAGE_FAREWELL, "COME BACK ANYTIME AND BRING ME TREASURES.")
npcHandler:setMessage(MESSAGE_WALKAWAY, "COME BACK ANYTIME AND BRING ME TREASURES.")
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
|
local Prop = {}
Prop.Name = "Bazaar Shop 6"
Prop.Cat = "Stores"
Prop.Price = 250
Prop.Doors = {
Vector( -13553, -10661, 359 ),
Vector( -13697, -10890, 359 ),
}
GM.Property:Register( Prop )
|
--Copyright 2018 Ibispi
--the main file
function love.load()
defaultCanvas = love.graphics.newCanvas (1024,768)
--^ add a canvas to draw on
require "theAbsoluteWorstClicker" --load the module
exampleUICanvas = ui.newCanvas(0,0,1024,768) --make a UI canvas
ui.setCanvas (exampleUICanvas) --set the canvas in order to add elements to it
local hoverSFX = love.audio.newSource("hover.ogg", 'static')--add sound effects
local clickSFX = love.audio.newSource("click.ogg", 'static')
ui.setSFX(hoverSFX, clickSFX)
ui.setRowHeight(50) --sets the height of a row
ui.setLineSpacing(40) --sets the distance between rows
ui.setBackgroundColor ({125, 0, 0, 255},
{255, 255, 255, 255})--background and outline color
ui.setBackgroundOutlineThickness (1) --thickness of the background outline
ui.setButtonOffset(20,20) --first button offset from the window
ui.setElementSpacing(5, 30) --1st argument is automatic spacing, the second is
--when you insert a space with ui.addSpace() function
ui.setButtonRoundness(0.0) --the roundness of buttons
ui.enableOutline() --enables outline
ui.setOutlineThickness(5) --sets outline thickness to 5
ui.setButtonWidth(200) --sets button width
ui.setTextAlignment('center') --the alignment of text on the buttons
defaultFont = love.graphics.newFont("YanoneKaffeesatz-Regular.ttf", 24)
ui.setFont(defaultFont, {0,0,0,255}, {255,255,0,255}, {0,0,0,255})
--sets the font for the UI, its 1. normal color, its 2. hover color and
--its 3. color when clicked
ui.setTextOffset (10,10) --x and y offset of the text of the buttons
ui.setColor[1] ({125,125,125,255},{0,0,0,255},{0,255,0,255})
ui.setColor[2] ({0,0,0,255},{255,255,255,255},{0,0,0,255})
ui.setColor[3] ({125,125,125,255},{255,255,255,255},{0,255,0,255})
ui.setColor[4] ({0,0,0,255},{125,125,125,255},{255,255,255,255})
--sets the colors for the ui
ui.addTooltip("") --a tooltip is added before a button that will use it
--if "" that means that the future buttons will not have a tooltip
--here we add buttons for the main menu
ui.addButton("CONTINUE")
ui.addNewLine()
ui.addButton("NEW GAME")
ui.addNewLine()
ui.addButton("LOAD GAME", true) --'true' means once the button is clicked
--it stays clicked until you click another button with 'true'
ui.addNewLine()
ui.addButton("SETTINGS", true)
ui.addNewLine()
ui.addButton("CREDITS", true)
ui.addNewLine()
ui.addButton("QUIT")
ui.addNewLine()
settingsCanvas = ui.newCanvas(300,100,924,568) --we make a new UI canvas
ui.setCanvas (settingsCanvas)
local hoverSFX = love.audio.newSource("hover.ogg", 'static')--add sound effects
local clickSFX = love.audio.newSource("click.ogg", 'static')
ui.setSFX(hoverSFX, clickSFX)
--------------------------------------------------------------------------------
ui.tooltip.minSize (0, 0)
ui.tooltip.maxWidth (700)
ui.tooltip.colors ({255,255,255,255}, {0,200,0,255}, {0, 150, 0, 255})
--sets colors in this order: backgroundColor, outlineColor, fontColor
ui.tooltip.outlineThickness(1)
ui.tooltip.enableOutline()
ui.tooltip.textOffset (10, 10)
ui.tooltip.font (defaultFont)
ui.tooltip.cursorOffset (30, 30)
--^ this sets the tooltip settings which are universal among all UI canvases----
ui.setRowHeight(50)
ui.setLineSpacing(40)
ui.setBackgroundColor ({150, 0, 0, 255}, {0, 0, 0, 255})
ui.setBackgroundOutlineThickness (5)
ui.setButtonOffset(30,10)
ui.setElementSpacing(10, 30)
ui.enableOutline()
ui.setOutlineThickness(5)
ui.setButtonWidth(100)
ui.setTextAlignment('center')
ui.setFont(defaultFont, {0,0,0,255}, {255,255,0,255}, {0,0,0,255})
ui.setTextOffset (10,10)
ui.setColor[1] ({125,125,125,255},{0,0,0,255},{0,255,0,255})
ui.setColor[2] ({0,0,0,255},{255,255,255,255},{0,0,0,255})
ui.setColor[3] ({125,125,125,255},{0,0,0,255},{0,255,0,255})
ui.setColor[4] ({0,0,0,255},{255,255,255,255},{0,0,0,255})
--if the UI canvas may be too long for the screen,
--a vertical slider has to be added
ui.setColorVerticalSlider[1] ({125,125,125,255},{0,0,0,255},{0,255,0,255})
ui.setColorVerticalSlider[2] ({0,0,0,255},{255,255,255,255},{0,0,0,255})
ui.setColorVerticalSlider[3] ({125,125,125,255},{0,0,0,255},{0,255,0,255})
ui.setColorVerticalSlider[4] ({0,0,0,255},{255,255,255,255},{0,0,0,255})
ui.addSlider.vertical("right", 30)
--it can be aligned onto "left", the second variable is its width
ui.addLabel("The Settings Window")--labels are non-interactable
local exampleImage = love.graphics.newImage("exampleImage.png")
ui.addImageLabel (exampleImage) --labels can be images
exampleVariable = "!"
ui.addVariableLabel ("exampleVariable") --or variables
--WARNING: whenever you have to insert a variable,
--its name should be inserted as a string
--(unless it won't be dynamically changed)
ui.addNewLine()
ui.setCheckBoxSize(42) --check boxes are squares, so they require just one size
ui.setCheckBoxMarkColor({0,255,0,255}, {255,255,255,255}, {0,0,0,255} )
--sets the check box mark/tick color for normal/hover/click modes
thisIsTheWorstModuleEver=true
ui.addLabel("The worst module ever:")
ui.addTooltip("This makes the module the worst one yet!")
ui.addCheckBox("thisIsTheWorstModuleEver")--add a check box
ui.addNewLine()
ui.addLabel("The Module Name:", true)--'true' for a label underlines the text
ui.setTextBoxColors ({200,200,200,255}, {0,0,0,255}, {0,255,0,255})
--textbox-specific background colors
ui.setTextBoxWidth (220)
thisIsTheWorstStringEver = "The Worst Module Ever"
ui.addTooltip("A text box.")
ui.allowOnlyNumbers(false)--this text box is not based on numbers
ui.addTextBox("thisIsTheWorstStringEver") --add a text box
--WARNING: whenever a variable is inserted it should not be part of another table
--If it is part of another table then this table has to be defined like this:
--ui.setPotentialTableSources({"exampleTableName", "exampleAnotherTableName"})
--however, note that it can only be part of one table
--you can't use variables that are part of more than one table in a row
ui.addNewLine()
ui.addLabel("A number box:", true)
ui.allowOnlyNumbers(true, 100, 3) --number boxes are text boxes that allow
--only numbers to be typed, the second variable is the highest number that
--can be inserted, the third one is the highest number of digits allowed
ui.setTextBoxWidth (50)
someVariable = 10
ui.addTooltip("A number box.")
ui.addTextBox("someVariable")
ui.addNewLine()
--you can add arrows that will change the integer variable
ui.addTooltip("The left arrow.")
ui.addArrowButton.left ("someVariable", 0)
--the second argument is the minimum number allowed
ui.addSpace()
ui.addTooltip("The right arrow.")
ui.addArrowButton.right ("someVariable", 100)
--here, the second argument is the maximum number allowed instead
ui.addNewLine()
--you can add a horizontal slider to change the variable
ui.setSliderSize(300,30)
ui.addTooltip("It's a slider!")
ui.addSlider.horizontal("someVariable", 0, 100)
--the second argument is the minimum number and the third the maximum one
ui.addFreeButton("a free button", 760, 500)
--free buttons are 'free' from the canvas and can be added anywhere,
--the second number is the X and the third is the Y coordinate of it
end
function love.mousereleased(x, y, button, isTouch)
local mouseX, mouseY = love.mouse.getPosition()--you need the cursor position
ui.updateMouseClick (exampleUICanvas, mouseX, mouseY)
if settingsOn == true then --if "SETTINGS" is clicked, update "settingsCanvas"
ui.updateMouseClick (settingsCanvas, mouseX, mouseY)
end
end
function love.update(dt)
--------------------------------------------------------------------------------
if ui.clicked("SETTINGS", exampleUICanvas) then
settingsOn = true --this is what happens when "SETTINGS" is clicked
end
--------------------------------------------------------------------------------
love.graphics.setCanvas(defaultCanvas) --set a canvas on which to draw the UI
love.graphics.clear()
local mouseX, mouseY = love.mouse.getPosition() --you need the cursor position
ui.drawCanvas (exampleUICanvas, mouseX, mouseY)
if settingsOn == nil then settingsOn = false end
if settingsOn == true then --if "SETTINGS" is clicked, draw "settingsCanvas"
ui.drawCanvas (settingsCanvas, mouseX, mouseY)
end
love.graphics.setCanvas()
--------------------------------------------------------------------------------
end
function love.keypressed(key, unicode)
--------------------------------------------------------------------------------
ui.updateKeyboardPressed(key)
--------------------------------------------------------------------------------
end
function love.textinput(key)
--------------------------------------------------------------------------------
ui.updateKeyboardInput(key)
--------------------------------------------------------------------------------
end
function love.draw()
love.graphics.setBackgroundColor( 0, 0, 0, 255 )
love.graphics.setColor( 255, 255, 255, 255 )
love.graphics.draw(defaultCanvas, 0, 0, 0, 1, 1) --the canvas is drawn
end
|
local helpers = require('test.functional.helpers')(after_each)
local clear, eq, eval, next_msg, ok, source = helpers.clear, helpers.eq,
helpers.eval, helpers.next_msg, helpers.ok, helpers.source
local command, funcs, meths = helpers.command, helpers.funcs, helpers.meths
local sleep = helpers.sleep
local spawn, nvim_argv = helpers.spawn, helpers.nvim_argv
local set_session = helpers.set_session
local nvim_prog = helpers.nvim_prog
local retry = helpers.retry
local expect_twostreams = helpers.expect_twostreams
describe('channels', function()
local init = [[
function! Normalize(data) abort
" Windows: remove ^M
return type([]) == type(a:data)
\ ? map(a:data, 'substitute(v:val, "\r", "", "g")')
\ : a:data
endfunction
function! OnEvent(id, data, event) dict
call rpcnotify(1, a:event, a:id, a:data)
endfunction
]]
before_each(function()
clear()
source(init)
end)
pending('can connect to socket', function()
local server = spawn(nvim_argv)
set_session(server)
local address = funcs.serverlist()[1]
local client = spawn(nvim_argv)
set_session(client, true)
source(init)
meths.set_var('address', address)
command("let g:id = sockconnect('pipe', address, {'on_data':'OnEvent'})")
local id = eval("g:id")
ok(id > 0)
command("call chansend(g:id, msgpackdump([[2,'nvim_set_var',['code',23]]]))")
set_session(server, true)
retry(nil, 1000, function()
eq(23, meths.get_var('code'))
end)
set_session(client, true)
command("call chansend(g:id, msgpackdump([[0,0,'nvim_eval',['2+3']]]))")
local res = eval("msgpackdump([[1,0,v:null,5]])")
eq({"\148\001\n\192\005"}, res)
eq({'notification', 'data', {id, res}}, next_msg())
command("call chansend(g:id, msgpackdump([[2,'nvim_command',['quit']]]))")
eq({'notification', 'data', {id, {''}}}, next_msg())
end)
it('can use stdio channel', function()
source([[
let g:job_opts = {
\ 'on_stdout': function('OnEvent'),
\ 'on_stderr': function('OnEvent'),
\ 'on_exit': function('OnEvent'),
\ }
]])
meths.set_var("nvim_prog", nvim_prog)
meths.set_var("code", [[
function! OnEvent(id, data, event) dict
let text = string([a:id, a:data, a:event])
call chansend(g:x, text)
if a:data == ['']
call chansend(v:stderr, "*dies*")
quit
endif
endfunction
let g:x = stdioopen({'on_stdin':'OnEvent'})
call chansend(x, "hello")
]])
command("let g:id = jobstart([ g:nvim_prog, '-u', 'NONE', '-i', 'NONE', '--cmd', 'set noswapfile', '--headless', '--cmd', g:code], g:job_opts)")
local id = eval("g:id")
ok(id > 0)
eq({ "notification", "stdout", {id, { "hello" } } }, next_msg())
command("call chansend(id, 'howdy')")
eq({"notification", "stdout", {id, {"[1, ['howdy'], 'stdin']"}}}, next_msg())
command("call chanclose(id, 'stdin')")
expect_twostreams({{"notification", "stdout", {id, {"[1, [''], 'stdin']"}}},
{'notification', 'stdout', {id, {''}}}},
{{"notification", "stderr", {id, {"*dies*"}}},
{'notification', 'stderr', {id, {''}}}})
eq({"notification", "exit", {3,0}}, next_msg())
end)
local function expect_twoline(id, stream, line1, line2, nobr)
local msg = next_msg()
local joined = nobr and {line1..line2} or {line1, line2}
if not pcall(eq, {"notification", stream, {id, joined}}, msg) then
local sep = (not nobr) and "" or nil
eq({"notification", stream, {id, {line1, sep}}}, msg)
eq({"notification", stream, {id, {line2}}}, next_msg())
end
end
it('can use stdio channel with pty', function()
if helpers.pending_win32(pending) then return end
source([[
let g:job_opts = {
\ 'on_stdout': function('OnEvent'),
\ 'on_exit': function('OnEvent'),
\ 'pty': v:true,
\ }
]])
meths.set_var("nvim_prog", nvim_prog)
meths.set_var("code", [[
function! OnEvent(id, data, event) dict
let text = string([a:id, a:data, a:event])
call chansend(g:x, text)
endfunction
let g:x = stdioopen({'on_stdin':'OnEvent'})
]])
command("let g:id = jobstart([ g:nvim_prog, '-u', 'NONE', '-i', 'NONE', '--cmd', 'set noswapfile', '--headless', '--cmd', g:code], g:job_opts)")
local id = eval("g:id")
ok(id > 0)
command("call chansend(id, 'TEXT\n')")
expect_twoline(id, "stdout", "TEXT\r", "[1, ['TEXT', ''], 'stdin']")
command("call chansend(id, 'neovan')")
eq({"notification", "stdout", {id, {"neovan"}}}, next_msg())
command("call chansend(id, '\127\127im\n')")
expect_twoline(id, "stdout", "\b \b\b \bim\r", "[1, ['neovim', ''], 'stdin']")
command("call chansend(id, 'incomplet\004')")
local is_freebsd = eval("system('uname') =~? 'FreeBSD'") == 1
local bsdlike = is_freebsd or (helpers.os_name() == "osx")
print("bsdlike:", bsdlike)
local extra = bsdlike and "^D\008\008" or ""
expect_twoline(id, "stdout",
"incomplet"..extra, "[1, ['incomplet'], 'stdin']", true)
command("call chansend(id, '\004')")
if bsdlike then
expect_twoline(id, "stdout", extra, "[1, [''], 'stdin']", true)
else
eq({"notification", "stdout", {id, {"[1, [''], 'stdin']"}}}, next_msg())
end
-- channel is still open
command("call chansend(id, 'hi again!\n')")
eq({"notification", "stdout", {id, {"hi again!\r", ""}}}, next_msg())
end)
it('stdio channel can use rpc and stderr simultaneously', function()
if helpers.pending_win32(pending) then return end
source([[
let g:job_opts = {
\ 'on_stderr': function('OnEvent'),
\ 'on_exit': function('OnEvent'),
\ 'rpc': v:true,
\ }
]])
meths.set_var("nvim_prog", nvim_prog)
meths.set_var("code", [[
let id = stdioopen({'rpc':v:true})
call rpcnotify(id,"nvim_call_function", "rpcnotify", [1, "message", "hi there!", id])
call chansend(v:stderr, "trouble!")
]])
command("let id = jobstart([ g:nvim_prog, '-u', 'NONE', '-i', 'NONE', '--cmd', 'set noswapfile', '--headless', '--cmd', g:code], g:job_opts)")
eq({"notification", "message", {"hi there!", 1}}, next_msg())
eq({"notification", "stderr", {3, {"trouble!"}}}, next_msg())
eq(30, eval("rpcrequest(id, 'nvim_eval', '[chansend(v:stderr, \"math??\"), 5*6][1]')"))
eq({"notification", "stderr", {3, {"math??"}}}, next_msg())
local _, err = pcall(command,"call rpcrequest(id, 'nvim_command', 'call chanclose(v:stderr, \"stdin\")')")
ok(string.find(err,"E906: invalid stream for channel") ~= nil)
eq(1, eval("rpcrequest(id, 'nvim_eval', 'chanclose(v:stderr, \"stderr\")')"))
eq({"notification", "stderr", {3, {""}}}, next_msg())
command("call rpcnotify(id, 'nvim_command', 'quit')")
eq({"notification", "exit", {3, 0}}, next_msg())
end)
it('can use buffered output mode', function()
if helpers.pending_win32(pending) then return end
source([[
let g:job_opts = {
\ 'on_stdout': function('OnEvent'),
\ 'on_exit': function('OnEvent'),
\ 'stdout_buffered': v:true,
\ }
]])
command("let id = jobstart(['grep', '^[0-9]'], g:job_opts)")
local id = eval("g:id")
command([[call chansend(id, "stuff\n10 PRINT \"NVIM\"\nxx")]])
sleep(10)
command([[call chansend(id, "xx\n20 GOTO 10\nzz\n")]])
command("call chanclose(id, 'stdin')")
eq({"notification", "stdout", {id, {'10 PRINT "NVIM"',
'20 GOTO 10', ''}}}, next_msg())
eq({"notification", "exit", {id, 0}}, next_msg())
command("let id = jobstart(['grep', '^[0-9]'], g:job_opts)")
id = eval("g:id")
command([[call chansend(id, "is no number\nnot at all")]])
command("call chanclose(id, 'stdin')")
-- works correctly with no output
eq({"notification", "stdout", {id, {''}}}, next_msg())
eq({"notification", "exit", {id, 1}}, next_msg())
end)
it('can use buffered output mode with no stream callback', function()
if helpers.pending_win32(pending) then return end
source([[
function! OnEvent(id, data, event) dict
call rpcnotify(1, a:event, a:id, a:data, self.stdout)
endfunction
let g:job_opts = {
\ 'on_exit': function('OnEvent'),
\ 'stdout_buffered': v:true,
\ }
]])
command("let id = jobstart(['grep', '^[0-9]'], g:job_opts)")
local id = eval("g:id")
command([[call chansend(id, "stuff\n10 PRINT \"NVIM\"\nxx")]])
sleep(10)
command([[call chansend(id, "xx\n20 GOTO 10\nzz\n")]])
command("call chanclose(id, 'stdin')")
eq({"notification", "exit", {id, 0, {'10 PRINT "NVIM"',
'20 GOTO 10', ''}}}, next_msg())
-- if dict is reused the new value is not stored,
-- but nvim also does not crash
command("let id = jobstart(['cat'], g:job_opts)")
id = eval("g:id")
command([[call chansend(id, "cat text\n")]])
sleep(10)
command("call chanclose(id, 'stdin')")
-- old value was not overwritten
eq({"notification", "exit", {id, 0, {'10 PRINT "NVIM"',
'20 GOTO 10', ''}}}, next_msg())
-- and an error was thrown.
eq("E5210: dict key 'stdout' already set for buffered stream in channel "..id, eval('v:errmsg'))
-- reset dictionary
source([[
let g:job_opts = {
\ 'on_exit': function('OnEvent'),
\ 'stdout_buffered': v:true,
\ }
]])
command("let id = jobstart(['grep', '^[0-9]'], g:job_opts)")
id = eval("g:id")
command([[call chansend(id, "is no number\nnot at all")]])
command("call chanclose(id, 'stdin')")
-- works correctly with no output
eq({"notification", "exit", {id, 1, {''}}}, next_msg())
end)
end)
|
E2VguiCore = {
["vgui_types"] = {},
["defaultPanelTable"] = {},
["e2_types"] = {},
["callbacks"] = {},
["Trigger"] = {},
["Buddies"] = {},
["BlockedPlayers"] = {},
["LinkedVehicles"] = {}
}
util.AddNetworkString("E2Vgui.CreatePanel")
util.AddNetworkString("E2Vgui.NotifyPanelRemove")
util.AddNetworkString("E2Vgui.ConfirmCreation")
util.AddNetworkString("E2Vgui.ClosePanels")
util.AddNetworkString("E2Vgui.ModifyPanel")
util.AddNetworkString("E2Vgui.ConfirmModification")
util.AddNetworkString("E2Vgui.TriggerE2")
util.AddNetworkString("E2Vgui.AddRemoveBuddy")
util.AddNetworkString("E2Vgui.UpdateServerValues")
util.AddNetworkString("E2Vgui.RegisterBuddiesOnServer")
util.AddNetworkString("E2Vgui.RequestBuddies")
util.AddNetworkString("E2Vgui.RegisterBlockedPlayersOnServer")
util.AddNetworkString("E2Vgui.BlockUnblockPlayer")
util.AddNetworkString("E2Vgui.ConVarUpdate")
local sbox_E2_Vgui_maxVgui = CreateConVar("wire_vgui_maxPanels",100,{FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE},"Sets the max amount of panels you can create with E2")
local sbox_E2_Vgui_maxVguiPerSecond = CreateConVar("wire_vgui_maxPanelsPerSecond",20,{FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE},"Sets the max amount of panels you can create/modify/update with E2 (All these send netmessages and too many would crash the client [Client overflow])")
local sbox_E2_Vgui_permissionDefault = CreateConVar("wire_vgui_permissionDefault",0,{FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE},
[[Sets the permission value that defines who can use the core.
(0) - DEFAULT: E2Owner needs to be a buddy of the target player.
(1) - Players can create only on their client.
(2) - Like DEFAULT, but admins and superadmins can use it on everyone regardless of buddy permissions
(3) - Like DEFAULT, but superadmins can use it on everyone regardless of buddy permissions
(4) - Always allow creation of panels by default, but clients can still block it in the utilities menu]])
cvars.AddChangeCallback("wire_vgui_permissionDefault", function(convar_name, value_old, value_new)
E2VguiCore.BroadcastConVarToClients(sbox_E2_Vgui_permissionDefault)
end)
--spam protection for PNL:create()/PNL:modify() calls
local TimeStamp = 0
local function E2VguiResetTemp()
if CurTime() >= TimeStamp then
for _,ply in pairs(player.GetAll()) do
ply.e2vgui_tempPanels = 0
TimeStamp = CurTime()+1
end
end
end
hook.Add("Think","E2VguiTempReset",E2VguiResetTemp)
--[[-------------------------------------------------------------------------
E2VguiCore.CanUpdateVgui
Desc: Returns if the player can create a new vgui element/update an existing vgui element
this is basically a net message spam protection
Args:
ply : the player of the panel
Return: boolean
---------------------------------------------------------------------------]]
function E2VguiCore.CanUpdateVgui(ply) --vguiCanCreate
if not ply:IsPlayer() then return false end
if ply.e2vgui_tempPanels == nil then
ply.e2vgui_tempPanels = 0
return true
end
local maxPanels = sbox_E2_Vgui_maxVgui:GetInt()
local maxPanelsPerSecond = sbox_E2_Vgui_maxVguiPerSecond:GetInt()
local count = E2VguiCore.GetCurrentPanelAmount(ply)
if ply.e2vgui_tempPanels >= maxPanelsPerSecond then return false end
if maxPanels <= -1 then
return true
elseif count >=maxPanels then
return false
end
return true
end
--[[-------------------------------------------------------------------------
E2VguiCore.CanTarget
Desc: Returns if the player can create a vguipanel on the target (Check ConVar 'sbox_E2_Vgui_permissionDefault')
Args:
ply: the player who wants creates the panel
target: the target
Return: boolean
---------------------------------------------------------------------------]]
function E2VguiCore.CanTarget(ply,target)
if ply == nil or target == nil then return false end
if not ply:IsPlayer() or not target:IsPlayer() then return false end
local setting = sbox_E2_Vgui_permissionDefault:GetInt()
if setting < 0 or setting > 4 then
sbox_E2_Vgui_permissionDefault:SetInt(0)
setting = 0
end
if setting == 0 then
return ply == target or E2VguiCore.IsBuddy(ply, target)
elseif setting == 1 then
if ply == target then return true end
elseif setting == 2 then
if ply == target or ply:IsSuperAdmin() or ply:IsAdmin() or E2VguiCore.IsBuddy(ply, target) then return true end
elseif setting == 3 then
if ply == target or ply:IsSuperAdmin() or E2VguiCore.IsBuddy(ply, target) then return true end
elseif setting == 4 then
return not E2VguiCore.IsBlocked(ply, target)
end
return false
end
--[[-------------------------------------------------------------------------
E2VguiCore.IsBuddy
Desc: Returns if the player can create a dermapanel on the target. Buddylist of the target is checked.
(See console command 'wire_vgui_addbuddy/removebuddy')
Args:
ply: the player who wants creates the panel
target: the target
Return: true OR false
---------------------------------------------------------------------------]]
function E2VguiCore.IsBuddy(ply,target)
if target == nil or not IsValid(target) then return false end
if ply == nil or not IsValid(ply) then return false end
if E2VguiCore.Buddies == nil then return false end
if E2VguiCore.Buddies[target:SteamID()] == nil then return false end
for k,v in pairs(E2VguiCore.Buddies[target:SteamID()]) do
if E2VguiCore.Buddies[target:SteamID()][ply:SteamID()] == true then
return true
end
end
return false
end
--[[-------------------------------------------------------------------------
E2VguiCore.IsBlocked
Desc: Returns if the player can create a dermapanel on the target. Buddylist is ignored, BlockedList is used instead.
(See console command 'wire_vgui_permissionDefault 4')
Args:
ply: the player who wants creates the panel
target: the target
Return: true OR false
---------------------------------------------------------------------------]]
function E2VguiCore.IsBlocked(ply,target)
if target == nil or not IsValid(target) then return false end
if ply == nil or not IsValid(ply) then return false end
if E2VguiCore.BlockedPlayers == nil then return false end
if E2VguiCore.BlockedPlayers[target:SteamID()] == nil then return false end
for k,v in pairs(E2VguiCore.BlockedPlayers[target:SteamID()]) do
if E2VguiCore.BlockedPlayers[target:SteamID()][ply:SteamID()] == true then
return true
end
end
return false
end
--[[-------------------------------------------------------------------------
E2VguiCore.BuddyClient
Desc: Blocks the target the player requests so he can't create derma panels anymore
(See console command 'wire_vgui_addbuddy/removebuddy')
Args:
ply: the player who wants to block
target: the target
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.BuddyClient(ply,target)
if ply == nil or target == nil then return end
if not ply:IsPlayer() or not target:IsPlayer() then return end
if ply == target then return end
if E2VguiCore.Buddies[ply:SteamID()] == nil then
E2VguiCore.Buddies[ply:SteamID()] = {}
end
E2VguiCore.Buddies[ply:SteamID()][target:SteamID()] = true
end
--[[-------------------------------------------------------------------------
E2VguiCore.UnbuddyClient
Desc: Unlocks the target the player requests so he can create derma panels again
(See console command 'wire_vgui_addbuddy/removebuddy')
Args:
ply: the player who wants to unblock
target: the target
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.UnbuddyClient(ply,target)
if ply == nil or target == nil then return end
if not ply:IsPlayer() or not target:IsPlayer() then return end
if ply == target then return end
if E2VguiCore.Buddies[ply:SteamID()] != nil then
E2VguiCore.Buddies[ply:SteamID()][target:SteamID()] = nil
end
end
--[[-------------------------------------------------------------------------
E2VguiCore.BlockClient
Desc: Blocks the target the player requests so he can't create derma panels anymore
(See console command 'wire_vgui_addbuddy/removebuddy')
Args:
ply: the player who wants to block
target: the target
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.BlockClient(ply,target)
if ply == nil or target == nil then return end
if not ply:IsPlayer() or not target:IsPlayer() then return end
if ply == target then return end
if E2VguiCore.BlockedPlayers[ply:SteamID()] == nil then
E2VguiCore.BlockedPlayers[ply:SteamID()] = {}
end
E2VguiCore.BlockedPlayers[ply:SteamID()][target:SteamID()] = true
end
--[[-------------------------------------------------------------------------
E2VguiCore.UnblockClient
Desc: Unlocks the target the player requests so he can create derma panels again
(See console command 'wire_vgui_addbuddy/removebuddy')
Args:
ply: the player who wants to unblock
target: the target
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.UnblockClient(ply,target)
if ply == nil or target == nil then return end
if not ply:IsPlayer() or not target:IsPlayer() then return end
if ply == target then return end
if E2VguiCore.BlockedPlayers[ply:SteamID()] != nil then
E2VguiCore.BlockedPlayers[ply:SteamID()][target:SteamID()] = nil
end
end
--[[-------------------------------------------------------------------------
E2VguiCore.GetCurrentPanelAmount
Desc: Returns the total amount of panels created on a player (serverside panel)
Args:
ply: the player of the panel
Return: 0 or number
---------------------------------------------------------------------------]]
function E2VguiCore.GetCurrentPanelAmount(ply)
if ply == nil or not ply:IsPlayer() then return 0 end
local count = 0
if ply.e2_vgui_core == nil then return 0 end
local e2s = ply.e2_vgui_core
for _,panels in pairs(e2s) do
if panels != nil and istable(panels) then
count = count + table.Count(panels)
end
end
return count
end
--[[-------------------------------------------------------------------------
E2VguiCore.RegisterVguiElementType
Desc: registers a new vgui type to the E2Core's 'vgui_types'-table
Args:
vguiType: the filename of the type (e.g. dlabel.lua)
status: is it enabled or not / boolean
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.RegisterVguiElementType(vguiType,status)
if status == nil then return end
for k,v in pairs(E2VguiCore.vgui_types) do
if k == vguiType then
return
end
end
E2VguiCore.vgui_types[vguiType] = status
end
--[[-------------------------------------------------------------------------
E2VguiCore.EnableVguiElementType
Desc: Enables/Disables a vgui type
Args:
vguiType: the file you want to disable
status: disable/enable
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.EnableVguiElementType(vguiType,status)
if status == nil then return end
vguiType = vguiType
for k,v in pairs(E2VguiCore.vgui_types) do
if k == vguiType then
E2VguiCore.vgui_types[vguiType] = status
end
end
wire_expression2_reload() --reload extensions
end
--[[-------------------------------------------------------------------------
E2VguiCore.CreatePanel
Desc: This function creates the panel-table on the serverside and then sends a message to the clients
to create the actual vgui-panel
Args:
e2self: the e2 instance
panel: the panel table you want to create from
players: the players you want to create the panel for
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.CreatePanel(e2self, panel, players)
if e2self == nil then return end
if panel == nil then return end
--invalid panel, return
if #panel.players == 0 and players == nil then return end
if table.Count(panel.paneldata) == 0 then return end
local e2EntityID = e2self.entity:EntIndex()
local players = players or panel["players"]
local paneldata = panel["paneldata"]
local changes = panel["changes"]
local uniqueID = math.Round(paneldata["uniqueID"])
if #players == 0 then return end
local pnlType = paneldata["typeID"]
if pnlType == nil or not E2VguiCore.vgui_types[string.lower(pnlType)..".lua"] then
error("[E2VguiCore] Paneltype is invalid or not registerednot type: ".. tostring(pnlType)..", received value: "..tostring(E2VguiCore.vgui_types[pnlType]).."\nTry to use 'wire_expression2_reload'")
return
end
--Check if the player hit the spam protection limit
if not E2VguiCore.CanUpdateVgui(e2self.player) then return end
e2self.player.e2vgui_tempPanels = e2self.player.e2vgui_tempPanels + 1
players = E2VguiCore.FilterPlayers(players) --remove redundant names and not-player entries
players = E2VguiCore.FilterPermission(players,e2self.player) --check if e2self.player is allowed to use vguicore
if table.Count(players) == 0 then return end --there are no players to create the panel for therefore return
for _,values in pairs(changes) do
local key = values[1]
local value = values[2]
paneldata[key] = value
end
--update panels values
panel["players"] = players
panel["paneldata"] = paneldata
panel["changes"] = {}
local notCreatedYet = {}
--update server table with new values
for k,ply in pairs(players) do
if ply.e2_vgui_core == nil or ply.e2_vgui_core[e2EntityID] == nil
or ply.e2_vgui_core[e2EntityID][uniqueID] == nil then
notCreatedYet[#notCreatedYet+1] = ply
end
ply.e2_vgui_core = ply.e2_vgui_core or {}
ply.e2_vgui_core[e2EntityID] = ply.e2_vgui_core[e2EntityID] or {}
--table.copy here because otherwise it sets the same table for every player
-- but we want every player to have a individual table
ply.e2_vgui_core[e2EntityID][uniqueID] = table.Copy(panel)
end
net.Start("E2Vgui.CreatePanel")
net.WriteString(pnlType)
net.WriteInt(uniqueID,32)
net.WriteInt(e2EntityID,32)
net.WriteTable(paneldata)
net.WriteTable(changes)
net.Send(notCreatedYet)
end
--[[-------------------------------------------------------------------------
E2VguiCore.ModifyPanel
Desc: Updates an existing panel-table and forwards these changes to the clients
Args:
e2self: the e2 instance
panel: the panel you want to change
players: the players that are targeted by the change
updateChildsToo: boolean - whether or not update the child panels as well
Return: <>
---------------------------------------------------------------------------]]
function E2VguiCore.ModifyPanel(e2Owner, e2Entity, panel, players, updateChildsToo)
if not IsValid(e2Owner) then return end
if not IsValid(e2Entity) then return end
if panel == nil then return end
--invalid panel, return
if #panel.players == 0 and players == nil then return end
if table.Count(panel.paneldata) == 0 then return end
local e2EntityID = e2Entity:EntIndex()
local players = players or panel["players"]
local paneldata = panel["paneldata"]
local changes = panel["changes"]
local uniqueID = math.Round(paneldata["uniqueID"])
if #players == 0 then return end
if #changes == 0 then return end
local pnlType = paneldata["typeID"]
if pnlType == nil or not E2VguiCore.vgui_types[string.lower(pnlType)..".lua"] then
error("[E2VguiCore] Paneltype is invalid or not registerednot type: ".. tostring(pnlType)..", received value: "..tostring(E2VguiCore.vgui_types[pnlType]).."\nTry to use 'wire_expression2_reload'")
return
end
--Check if the player hit the spam protection limit
if not E2VguiCore.CanUpdateVgui(e2Owner) then return end
e2Owner.e2vgui_tempPanels = e2Owner.e2vgui_tempPanels + 1
players = E2VguiCore.FilterPlayers(players) --remove redundant names and not-player entries
players = E2VguiCore.FilterPermission(players,e2Owner) --check if e2Owner is allowed to use vguicore
if table.Count(players) == 0 then return end --there are no players to create the panel for therefore return
--convert changes table format to paneldata's table's format
local simplifiedChanges = {}
for _,values in pairs(changes) do
local key = values[1]
local value = values[2]
simplifiedChanges[key] = value
end
panel["players"] = players
panel["paneldata"] = table.Merge(paneldata,simplifiedChanges) --integrate changes into paneldata
panel["changes"] = {} --changes are send to the player with pnl_modify() so reset them
--TODO: prevent recursion - Infinite loops
if updateChildsToo == true then
local childpanels = E2VguiCore.GetChildren(e2Entity,panel)
for _,childpnl in pairs(childpanels) do
E2VguiCore.ModifyPanel(e2Owner, e2Entity, childpnl, nil, true)
end
end
local stillOpen = {}
--update server table with new values
for k,ply in pairs(players) do
if ply.e2_vgui_core == nil then continue end --the player closed the panel already, no need to update
if ply.e2_vgui_core[e2EntityID] == nil then continue end
--table.copy here because otherwise it sets the same table for every player
-- but we want every player to have a individual table
ply.e2_vgui_core[e2EntityID][uniqueID] = table.Copy(panel)
table.insert(stillOpen,ply)
end
net.Start("E2Vgui.ModifyPanel")
net.WriteString(pnlType)
net.WriteInt(uniqueID,32)
net.WriteInt(e2EntityID,32)
net.WriteTable(changes)
net.Send(stillOpen)
end
--[[-------------------------------------------------------------------------
E2VguiCore.registerAttributeChange
Desc: add an attribute change to the passed panel
Args:
panel: the panel you want to add the change to
attributeName: the name of the attribute you want to change
...: the data you want to insert
Return: <>
---------------------------------------------------------------------------]]
function E2VguiCore.registerAttributeChange(panel,attributeName, ...)
--TODO: check if the attributeName exists for this panel type
panel.changes[#panel["changes"]+1] = {attributeName,...}
end
--[[-------------------------------------------------------------------------
E2VguiCore.AddDefaultPanelTable
Desc: Registers a table with default values used when creating a default element of that type
Args:
pnlType: the vgui element type
func: a function that returns the default panel
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.AddDefaultPanelTable(pnlType,func)
E2VguiCore["defaultPanelTable"][pnlType] = func
end
--[[-------------------------------------------------------------------------
E2VguiCore.GetChildren
Desc: A helper function to get the child panels of a panel
Args:
e2self: the e2 self instance
panel: the panel you want to get the children from
Return: table with all children panels
---------------------------------------------------------------------------]]
--TODO: prevent recursion - Infinite loops
function E2VguiCore.GetChildren(e2Entity,panel)
local children = {}
for _,ply in pairs(panel["players"]) do
if ply.e2_vgui_core != nil and ply.e2_vgui_core[e2Entity:EntIndex()] != nil then
for _,value in pairs(ply.e2_vgui_core[e2Entity:EntIndex()]) do
if value["paneldata"] and value["paneldata"]["parentID"] == panel["paneldata"]["uniqueID"] then
table.insert(children,value)
end
end
end
end
return children
end
--[[-------------------------------------------------------------------------
E2VguiCore.GetDefaultPanelTable
Desc: Returns the default panel table that was registered with E2VguiCore.AddDefaultPanelTable()
Args:
pnlType: The type of the panel you want to create
uniqueID: the uniqueID you want to use
parentID: the id of the parent panel you want to assign
Return: panel table with default values
---------------------------------------------------------------------------]]
function E2VguiCore.GetDefaultPanelTable(pnlType,uniqueID,parentID)
if E2VguiCore["defaultPanelTable"][pnlType] == nil then error("E2VguiCore.GetDefaultPanelTable : No valid paneltypenot \n"..tostring(pnlType)) return nil end
local tbl = E2VguiCore["defaultPanelTable"][pnlType](uniqueID,parentID)
return tbl
end
--[[-------------------------------------------------------------------------
E2VguiCore.RegisterTypeWithID
Desc: Registers a type and it's e2-type id for later reference (e.g. dButton -> xdb)
Args:
e2Type: the type of the panel
id: the e2-type id that we want to register it as
Return: nil
---------------------------------------------------------------------------]]
-- dButton = xdb, used to create the constructors later
function E2VguiCore.RegisterTypeWithID(e2Type,id)
E2VguiCore["e2_types"][e2Type] = id
end
--[[-------------------------------------------------------------------------
E2VguiCore.GetIDofType
Desc: Returns the e2-type id of a panel type ('dButton' ->returns 'xdb')
Args:
e2Type: the type you want to get the e2-type from
Return: string, e2-type id
---------------------------------------------------------------------------]]
function E2VguiCore.GetIDofType(e2Type)
if E2VguiCore["e2_types"][e2Type] == nil then error("No such type: "..tostring(e2Type)) end
return E2VguiCore["e2_types"][e2Type]
end
--[[-------------------------------------------------------------------------
E2VguiCore.registerCallback
Desc: Registers a callback, currently only used to load the custom core files after a e2-core reload (wire_expression2_reload)
Args:
callbackID: a unique identifier
func: the function you want to execute
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.registerCallback(callbackID,func)
if E2VguiCore.callbacks[callbackID] == nil then
E2VguiCore.callbacks[callbackID] = {}
end
table.insert(E2VguiCore.callbacks[callbackID],func)
end
--[[-------------------------------------------------------------------------
E2VguiCore.executeCallback
Desc: executes all registered callbacks, currently only used to load the custom core files after a e2-core reload (wire_expression2_reload)
Args:
callbackID: a unique identifier
func: the function you want to execute
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.executeCallback(callbackID,...)
for _,func in pairs(E2VguiCore.callbacks[callbackID]) do
func(...)
end
end
--[[-------------------------------------------------------------------------
UTILITY STUFF
---------------------------------------------------------------------------]]
--[[-------------------------------------------------------------------------
E2VguiCore.FilterPlayers
Desc: Used to filter a given table of players, removes redundant players
Args:
players: table of players
Return: table of players
---------------------------------------------------------------------------]]
function E2VguiCore.FilterPlayers(players)
if players == nil or not istable(players) then return {} end
local tbl = {}
for k,v in pairs(players) do
if v:IsPlayer() and not table.HasValue(tbl,v) then
table.insert(tbl,v)
end
end
return tbl
end
--[[-------------------------------------------------------------------------
E2VguiCore.FilterPermission
Desc: Filters the given list to exclude all players the creator can't create panels on (apply general permission check ConVar 'sbox_E2_Derma_permissionDefault')
Args:
targets: the targets
creator: the creator of the panels
Return: table
---------------------------------------------------------------------------]]
function E2VguiCore.FilterPermission(targets,creator)
local allowedPlayers = {}
for k,ply in pairs(targets) do
local hasPermission = E2VguiCore.CanTarget(creator,ply)
if hasPermission then
table.insert(allowedPlayers,ply)
end
end
return allowedPlayers
end
--[[-------------------------------------------------------------------------
E2VguiCore.GetPanelByID
Desc: Returns a panel table
Args:
ply: the player you want to get the panel from
e2e2EntityID: the entity id of the e2 the panel belongs to
uniqueID: the uniqueID of the panel
Return: <>
---------------------------------------------------------------------------]]
function E2VguiCore.GetPanelByID(ply,e2EntityID, uniqueID)
if ply == nil or not ply:IsPlayer() then return end
if ply.e2_vgui_core == nil then return end
if ply.e2_vgui_core[e2EntityID] == nil then return end
if ply.e2_vgui_core[e2EntityID][uniqueID] == nil then return end
return ply.e2_vgui_core[e2EntityID][uniqueID]
end
--[[-------------------------------------------------------------------------
E2VguiCore.GetPanelAttribute
Desc: tries to retrieve the value of a attribute from a panel
Args:
ply: the player to which the panel belongs
e2EntityID: the entity id of the e2 the panel belongs to
Return: the attribute value or nil
---------------------------------------------------------------------------]]
function E2VguiCore.GetPanelAttribute(ply,e2EntityID,pnlVar,attributeName)
local pnl = E2VguiCore.GetPanelByID(ply,e2EntityID, pnlVar["paneldata"]["uniqueID"])
if pnl != nil then
return pnl["paneldata"][attributeName]
end
return nil
end
--Converts a normal lua table into an e2Table
function E2VguiCore.convertToE2Table(tbl)
/* {n={},ntypes={},s={},stypes={},size=0}
n - table for number keys
ntypes - number indics
s - table for string keys
stypes - string indices
*/
local e2table = {n={},ntypes={},s={},stypes={},size=0}
local size = 0
for k,v in pairs( tbl ) do
local vtype = type(v)
--convert number to Normal otherwise it won't get recognized as wire datatype
if vtype == "number" then vtype = "normal" end
local keyType = type(k)
local e2Type = ""
if wire_expression_types[string.upper(vtype)] != nil then
e2Type = wire_expression_types[string.upper(vtype)][1]
elseif vtype == "boolean" and wire_expression_types[string.upper(vtype)] == nil then
--handle booleans beforehand because they have no type in e2
e2Type = wire_expression_types["NORMAL"][1]
else
ErrorNoHalt("[SERVER VGUI LIB] Unknown type detected key:"..vtype.." value:"..tostring(v))
continue
end
--determine if the key is a number or anything else
local indextype = (keyType == "number" and "n" or "s")
if indextype == "n" then
e2table[indextype.."types"][k] = e2Type
else
--convert the key to a string
e2table[indextype.."types"][tostring(k)] = e2Type
end
if vtype == "table" then
--colors are getting detected as table, so we make sure they get parsed as vector4
if IsColor(v) then
e2table[indextype.."types"][indextype == "n" and k or tostring(k)] = wire_expression_types["VECTOR4"][1]
e2table[indextype][k] = {v.r,v.g,v.b,v.a}
--[[
First we check if its a nested table,
otherwise it's a normal table or vector-table
]]
--check if it contains sub-tables, so it's not a vector3 or vector4
elseif type(v[1]) == "table" then
--TODO:this check isn't 100% proof
--TODO:implement protection against recursive tables. Infinite loopsnot
e2table[indextype][k] = E2VguiCore.convertToE2Table(v)
elseif table.IsSequential(v) and #v==2 and type(v[1]) == "number" and type(v[2]) == "number" then
e2table[indextype.."types"][indextype == "n" and k or tostring(k)] = wire_expression_types["VECTOR2"][1]
e2table[indextype][k] = v
elseif table.IsSequential(v) and #v==3 and type(v[1]) == "number" and type(v[2]) == "number" and type(v[3]) == "number" then
e2table[indextype.."types"][indextype == "n" and k or tostring(k)] = wire_expression_types["VECTOR"][1]
e2table[indextype][k] = v
elseif table.IsSequential(v) and #v==4 and type(v[1]) == "number" and type(v[2]) == "number" and type(v[3]) == "number" and type(v[4]) == "number" then --its a vector4
e2table[indextype.."types"][indextype == "n" and k or tostring(k)] = wire_expression_types["VECTOR4"][1]
e2table[indextype][k] = v
else
--TODO:implement protection against recursive tables. Infinite loopsnot
e2table[indextype][k] = E2VguiCore.convertToE2Table(v)
end
elseif vtype == "boolean" then
--booleans have no type in e2 so parse them as number
e2table[indextype.."types"][indextype == "n" and k or tostring(k)] = wire_expression_types["NORMAL"][1]
e2table[indextype][k] = v and 1 or 0
else
--everything that has a valid type in e2 just put the value inside
e2table[indextype][k] = v
end
size = size + 1
end
e2table.size = size
return e2table
end
function E2VguiCore.IsE2Table(tbl)
if tbl.s == nil then return false end
if tbl.n == nil then return false end
if tbl.stype == nil then return false end
if tbl.ntype == nil then return false end
if tbl.size == nil then return false end
return true
end
--Converts a e2table into a lua table
function E2VguiCore.convertToLuaTable(tbl)
/* {n={},ntypes={},s={},stypes={},size=0}
n - table for number keys
ntypes - number indics
s - table for string keys
stypes - string indices
*/
local luatable = {}
if tbl.s != nil then
for key,value in pairs(tbl.s) do
if istable(value) then
if E2VguiCore.IsE2Table(value) then
luatable[key] = E2VguiCore.convertToLuaTable(value)
else
-- luatable[key] = E2VguiCore.convertToLuaTable(E2VguiCore.convertToE2Table(value))
luatable[key] = value
end
else
luatable[key] = value
end
end
end
if tbl.n != nil then
for key,value in pairs(tbl.n) do
if istable(value) and not IsColor(value) then
luatable[key] = E2VguiCore.convertToLuaTable(value)
else
luatable[key] = value
end
end
end
return luatable
end
function E2VguiCore.convertLuaTableToArray(tbl)
local array = {}
for _,value in pairs(tbl) do
if istable(value) and not IsColor(value) then
--remove table
elseif IsColor(value) then
array[#array + 1] = value.r
array[#array + 1] = value.g
array[#array + 1] = value.b
array[#array + 1] = value.a
elseif isbool(value) then
array[#array + 1] = value and 1 or 0
else
array[#array + 1] = value
end
end
return array
end
function E2VguiCore.linkToVehicle(e2self, panel, vehicle)
if not IsValid(vehicle) then return end
if not vehicle:IsVehicle() then return end
if not vehicle:IsValidVehicle() then return end
local e2Index = e2self.entity:EntIndex()
if E2VguiCore.LinkedVehicles[e2Index] == nil then
E2VguiCore.LinkedVehicles[e2Index] = {}
end
E2VguiCore.LinkedVehicles[e2Index][panel.paneldata.uniqueID] = {
["vehicle"] = vehicle,
["e2Owner"] = e2self.player
}
end
function E2VguiCore.removeLinkFromVehicle(e2self, panel)
if e2self == nil then return end
if panel == nil then return end
local e2Index = e2self.entity:EntIndex()
if E2VguiCore.LinkedVehicles[e2Index] then
E2VguiCore.LinkedVehicles[e2Index][panel.paneldata.uniqueID] = nil
end
end
function E2VguiCore.PlayerEnteredVehicle(player, vehicle, role)
for e2EntityID, linkedPanels in pairs(E2VguiCore.LinkedVehicles) do
for panelID, linkedEntry in pairs(linkedPanels) do
local linkedVehicle = linkedEntry.vehicle
local e2Owner = linkedEntry.e2Owner
if linkedVehicle == vehicle then
local panel = E2VguiCore.GetPanelByID(player,e2EntityID,panelID)
if panel != nil then
local e2Entity = ents.GetByIndex(e2EntityID)
if IsValid(e2Entity) then
E2VguiCore.registerAttributeChange(panel,"visible", true)
E2VguiCore.ModifyPanel(e2Owner, e2Entity, panel, {player}, false)
end
end
break
end
end
end
end
function E2VguiCore.PlayerLeaveVehicle(player, vehicle)
for e2EntityID, linkedPanels in pairs(E2VguiCore.LinkedVehicles) do
for panelID, linkedEntry in pairs(linkedPanels) do
local linkedVehicle = linkedEntry.vehicle
local e2Owner = linkedEntry.e2Owner
if linkedVehicle == vehicle then
local panel = E2VguiCore.GetPanelByID(player,e2EntityID,panelID)
if panel != nil then
local e2Entity = ents.GetByIndex(e2EntityID)
if IsValid(e2Entity) then
E2VguiCore.registerAttributeChange(panel,"visible", false)
E2VguiCore.ModifyPanel(e2Owner, e2Entity, panel, {player}, false)
end
end
break
end
end
end
end
--[[-------------------------------------------------------------------------
DERMA PANEL ADDING/MODIFY FOR SERVER SYNC
---------------------------------------------------------------------------]]
--[[-------------------------------------------------------------------------
E2VguiCore.RemovePanelOnPlayerServer
Desc: This is used to remove panels from the serverside if they fail to create on a client (Check net.Receive("E2Vgui.ConfirmCreation",...) )
Args:
e2EntityID: index of e2 entity
uniqueID: ID of the panel
ply: the player of the panel
Return: nil
---------------------------------------------------------------------------]]
function E2VguiCore.RemovePanelOnPlayerServer(e2EntityID,uniqueID,ply)
if e2EntityID == nil or uniqueID == nil or ply == nil or not ply:IsPlayer() then return end
if ply.e2_vgui_core == nil then return end
if ply.e2_vgui_core[e2EntityID] != nil then
ply.e2_vgui_core[e2EntityID][uniqueID] = nil
if table.Count(ply.e2_vgui_core[e2EntityID]) == 0 then
ply.e2_vgui_core[e2EntityID] = nil
end
end
end
--[[-------------------------------------------------------------------------
E2VguiCore.RemoveAllPanelsOfE2
Desc: This is used to delete all panels on every client of a specific e2
Args:
e2EntityID: the e2 index
---------------------------------------------------------------------------]]
function E2VguiCore.RemoveAllPanelsOfE2(e2EntityID)
if e2EntityID == nil then return end
net.Start("E2Vgui.ClosePanels")
net.WriteInt(-1,3)
net.WriteInt(e2EntityID,32)
net.Broadcast()
for k,v in pairs(player.GetAll()) do
if v.e2_vgui_core ~= nil then
v.e2_vgui_core[e2EntityID] = nil
end
end
end
function E2VguiCore.RemovePanelsOnPlayer(e2EntityID,ply)
if e2EntityID == nil or ply == nil or not ply:IsPlayer() then return end
if ply.e2_vgui_core[e2EntityID] == nil then return end
local panels = {uniqueID}
net.Start("E2Vgui.ClosePanels")
net.WriteInt(-1,3)
net.WriteInt(e2EntityID,32)
net.Send(ply)
ply.e2_vgui_core[e2EntityID] = nil
end
function E2VguiCore.RemovePanel(e2EntityID,uniqueID,ply)
if e2EntityID == nil or uniqueID == nil or ply == nil or not ply:IsPlayer() then return end
if ply.e2_vgui_core[e2EntityID] == nil then return end
local panels = {uniqueID}
net.Start("E2Vgui.ClosePanels")
net.WriteInt(0,3)
net.WriteInt(e2EntityID,32)
net.WriteTable(panels)
net.Send(ply)
ply.e2_vgui_core[e2EntityID][uniqueID] = nil
if table.Count(ply.e2_vgui_core[e2EntityID]) == 0 then
ply.e2_vgui_core[e2EntityID] = nil
end
end
--[[-------------------------------------------------------------------------
HOOKS
---------------------------------------------------------------------------]]
hook.Add("EntityRemoved","E2VguiCheckDeletion",function(entity)
if entity:GetClass() == "gmod_wire_expression2" then
E2VguiCore.RemoveAllPanelsOfE2(entity:EntIndex())
if entity:GetOwner().e2_vgui_core_default_players != nil then
entity:GetOwner().e2_vgui_core_default_players[entity:EntIndex()] = nil
end
end
end)
--Requests every client to resend their buddy list to the server
hook.Add("PlayerInitialSpawn", "E2VguiRegisterBuddyOnPlayerJoin", function(clientName, clientIp)
net.Start("E2Vgui.RequestBuddies")
net.Broadcast()
end)
hook.Add("PlayerEnteredVehicle", "E2VguiOpenVguiOnEnterVehicle", function(player, vehicle, role)
E2VguiCore.PlayerEnteredVehicle(player, vehicle, role)
end)
hook.Add("PlayerLeaveVehicle", "E2VguiCloseVguiOnLeaveVehicle", function(player, vehicle)
E2VguiCore.PlayerLeaveVehicle(player, vehicle)
end)
--[[-------------------------------------------------------------------------
NETMESSAGES
---------------------------------------------------------------------------]]
net.Receive("E2Vgui.NotifyPanelRemove",function(len, ply)
local mode = net.ReadInt(3)
-- -2 : none -1: single / 0 : multiple / 1 : all
if mode == -2 then
return
elseif mode == -1 then
local uniqueID = net.ReadInt(32)
local e2EntityID = net.ReadInt(32)
local paneldata = net.ReadTable()
E2VguiCore.RemovePanelOnPlayerServer(e2EntityID,uniqueID,ply)
elseif mode == 0 then
local e2EntityID = net.ReadInt(32)
local panels = net.ReadTable()
for k,panelID in pairs(panels) do
local panel = E2VguiCore.GetPanelByID(ply,e2EntityID,panelID)
if panel != nil then
local uniqueID = panel["paneldata"]["uniqueID"]
E2VguiCore.RemovePanelOnPlayerServer(e2EntityID,uniqueID,ply)
end
end
elseif mode == 1 then
ply.e2_vgui_core = {}
end
end)
net.Receive("E2Vgui.ConfirmCreation",function(len,ply)
local uniqueID = net.ReadInt(32)
local e2EntityID = net.ReadInt(32)
local success = net.ReadBool()
local paneldata = net.ReadTable()
if success then
--do nothing since we already created the panel on the server
else
--remove the panel from the server again since its not valid on that player
E2VguiCore.RemovePanelOnPlayerServer(e2EntityID,uniqueID,ply)
end
end)
net.Receive("E2Vgui.ConfirmModification",function(len,ply)
local uniqueID = net.ReadInt(32)
local e2EntityID = net.ReadInt(32)
local success = net.ReadBool()
local paneldata = net.ReadTable()
if success then
--do nothing
else
--do nothing
end
end)
--Gets triggered when a client sends their buddy list to the server
net.Receive("E2Vgui.RegisterBuddiesOnServer", function(len, ply)
local buddies = net.ReadTable()
E2VguiCore.WhitelistBuddies(ply, buddies)
end)
--Gets triggered when a client sends their blocked list to the server
net.Receive("E2Vgui.RegisterBlockedPlayersOnServer", function(len, ply)
local blockedPlayers = net.ReadTable()
E2VguiCore.BlockPlayers(ply, blockedPlayers)
end)
net.Receive("E2Vgui.ConVarUpdate", function(len, ply)
local name = net.ReadString()
local conVar = GetConVar(name)
E2VguiCore.SendConVarToClient(conVar, ply)
end)
function E2VguiCore.BroadcastConVarToClients(conVar)
if conVar == nil then return end
net.Start("E2Vgui.ConVarUpdate")
net.WriteString(conVar:GetName())
net.WriteInt(conVar:GetInt(), 4)
net.Broadcast()
end
function E2VguiCore.SendConVarToClient(conVar, ply)
if not IsValid(ply) or not ply:IsPlayer() then return end
if conVar == nil then return end
net.Start("E2Vgui.ConVarUpdate")
net.WriteString(conVar:GetName())
net.WriteInt(conVar:GetInt(), 4)
net.Send(ply)
end
--Updates the player's buddy list (gets triggered when a new player joins or a buddy is added/removed)
function E2VguiCore.WhitelistBuddies(ply, buddies)
for k, target in pairs(player.GetAll()) do
if target:IsBot() then continue end
E2VguiCore.UnbuddyClient(ply,target)
end
for k, steamID in pairs(buddies) do
local buddy = player.GetBySteamID(steamID)
if IsValid(buddy) then
E2VguiCore.BuddyClient(ply,buddy)
end
end
end
--Updates the player's block list (gets triggered when a new player joins or a player gets blocked/unblocked)
function E2VguiCore.BlockPlayers(ply, blockedPlayers)
for k, target in pairs(player.GetAll()) do
if target:IsBot() then continue end
E2VguiCore.UnblockClient(ply,target)
end
for k, steamID in pairs(blockedPlayers) do
local blockedPlayer = player.GetBySteamID(steamID)
if blockedPlayer != false then
E2VguiCore.BlockClient(ply,blockedPlayer)
end
end
end
function E2VguiCore.UpdateServerValuesFromTable(ply,e2EntityID,uniqueID,tableData)
--Set the attribute values on the server correct
local pnl = E2VguiCore.GetPanelByID(ply,e2EntityID, uniqueID)
if pnl == nil then return end
for attributeName,value in pairs(tableData) do
pnl["paneldata"][attributeName] = value
end
end
function E2VguiCore.TriggerE2(e2EntityID,uniqueID, triggerPly, tableData, alsoTriggerE2)
if E2VguiCore.Trigger[e2EntityID] == nil then
E2VguiCore.Trigger[e2EntityID] = {}
end
if E2VguiCore.Trigger[e2EntityID].RunOnDerma == nil or E2VguiCore.Trigger[e2EntityID].RunOnDerma == false then return end
if triggerPly == nil or not triggerPly:IsPlayer() then return end
local e2Entity = ents.GetByIndex(e2EntityID)
if not IsValid(e2Entity) then return end
if e2Entity:GetClass() != "gmod_wire_expression2" then return end
local value = value and tostring(value) or ""
E2VguiCore.Trigger[e2EntityID].triggeredByClient = triggerPly
E2VguiCore.Trigger[e2EntityID].triggerValues = E2VguiCore.convertLuaTableToArray(tableData)
E2VguiCore.Trigger[e2EntityID].triggerValuesTable = E2VguiCore.convertToE2Table(tableData)
E2VguiCore.Trigger[e2EntityID].triggerUniqueID = uniqueID
E2VguiCore.Trigger[e2EntityID].run = true
E2VguiCore.UpdateServerValuesFromTable(triggerPly,e2EntityID,uniqueID,tableData)
e2Entity:Execute()
E2VguiCore.Trigger[e2EntityID].triggeredByClient = NULL
E2VguiCore.Trigger[e2EntityID].triggerValues = {}
E2VguiCore.Trigger[e2EntityID].triggerValuesTable = {n={},ntypes={},s={},stypes={},size=0}
E2VguiCore.Trigger[e2EntityID].triggerUniqueID = -1
E2VguiCore.Trigger[e2EntityID].run = false
end
--Only updates the server values and executes the e2
net.Receive("E2Vgui.TriggerE2",function(len,ply)
local e2EntityID = net.ReadInt(32)
local uniqueID = net.ReadInt(32)
local panelType = net.ReadString()
local tableData = net.ReadTable()
E2VguiCore.TriggerE2(e2EntityID,uniqueID, ply, tableData)
end)
--Only updates the server values without executing the e2
net.Receive("E2Vgui.UpdateServerValues",function(len,ply)
local e2EntityID = net.ReadInt(32)
local uniqueID = net.ReadInt(32)
local tableData = net.ReadTable()
E2VguiCore.UpdateServerValuesFromTable(ply,e2EntityID,uniqueID,tableData)
end)
net.Receive("E2Vgui.AddRemoveBuddy",function( len,ply )
local mode = net.ReadBool()
local target = net.ReadEntity()
if mode == true then
E2VguiCore.BuddyClient(ply,target)
else
E2VguiCore.UnbuddyClient(ply,target)
--TODO: Delete panels that belonged to this buddy
end
end)
|
id = 'V-38446'
severity = 'medium'
weight = 10.0
title = 'The mail system must forward all mail for root to one or more system administrators.'
description = 'A number of system services utilize email messages sent to the root user to notify system administrators of active or impending issues. These messages must be forwarded to at least one monitored email address.'
fixtext = [=[Set up an alias for root that forwards to a monitored email address:
# echo "root: <system.administrator>@mail.mil" >> /etc/aliases
# newaliases]=]
checktext = [=[Find the list of alias maps used by the Postfix mail server:
# postconf alias_maps
Query the Postfix alias maps for an alias for "root":
# postmap -q root <alias_map>
If there are no aliases configured for root that forward to a monitored email address, this is a finding.]=]
function test()
end
function fix()
end
|
require 'Decode/Decoder'
require 'logroll'
local logger = logroll.print_logger()
local BackwardModel = torch.class('BackwardModel')
-- torch.factory(name) returns the *factory function* for the class with *name*.
-- A factory function creates an *empty* object of a class -- ideal for our *external initialization* use case
-- that bypasses constructor and sets attributes directly.
local DecoderFactory = torch.factory('Decoder')
local function load_object(filename)
local file = torch.DiskFile(filename):binary()
local obj = file:readObject()
file:close()
return obj
end
local function load_model(params_file, model_file, dictPath)
logger.info('params_file: %s', params_file)
logger.info('model_file: %s', model_file)
local model = DecoderFactory()
model.params = load_object(params_file)
model.params.dictPatt = dictPath
model.params.model_file = model_file
model:DecoderInitial()
model.mode = 'test'
return model
end
function BackwardModel:__init(params)
self.params = params
logger.info('creating predictor network')
self.map = nn.Sequential()
self.map:add(nn.Linear(self.params.dimension, self.params.dimension))
self.map:add(nn.Tanh())
self.map:add(nn.Linear(self.params.dimension, self.params.dimension))
self.map:add(nn.Tanh())
self.map:add(nn.Linear(self.params.dimension, 1))
self.map = self.map:cuda()
self.mse = nn.MSECriterion():cuda()
if self.params.readSequenceModel then
logger.info('loading forward model')
self.forward_model = load_model(params.forward_params_file,
params.forward_model_file,
params.dictPath)
logger.info('loading backward model')
self.backward_model = load_model(params.backward_params_file,
params.backward_model_file,
params.dictPath)
end
if self.params.readFutureModel then
local filename = self.params.FuturePredictorModelFile
logger.info('loading future predictor model from %s', filename)
local parameter = self.map:parameters()
local future_params = load_object(filename)
for j = 1, #parameter do
parameter[j]:copy(future_params[j])
end
end
logger.info("read data done")
end
function BackwardModel:model_forward()
local totalError = 0
local instance = 0
for t = 1, self.forward_model.Word_t:size(2) - 1 do
local representation_left =
self.forward_model.store_t[t][2 * self.backward_model.params.layers - 1]:index(1, self.forward_model.Left_t[t])
local predict_left = self.backward_score:index(1, self.forward_model.Left_t[t])
self.map:zeroGradParameters()
local pred = self.map:forward(representation_left)
local Error = self.mse:forward(pred, predict_left)
if self.mode == "train" then
self.mse:backward(pred, predict_left)
self.map:backward(representation_left, self.mse.gradInput)
self.map:updateParameters(self.params.alpha)
end
totalError = totalError + Error * representation_left:size(1)
instance = instance + representation_left:size(1)
end
return totalError, instance
end
function BackwardModel:test()
logger.info('testing with file %s', self.params.test_file)
local test_file = assert(io.open(self.params.test_file, "r"), 'cannot open test_file')
local End, Word_s, Word_t, Mask_s, Mask_t
local End = 0
local batch_n = 1
local totalError = 0
local n_instance = 0
local aver_ppl = 0
local sen_num = 0
while End == 0 do
batch_n = batch_n + 1
End, self.forward_model.Word_s, self.forward_model.Word_t,
self.forward_model.Mask_s, self.forward_model.Mask_t,
self.forward_model.Left_s, self.forward_model.Left_t,
self.forward_model.Padding_s, self.forward_model.Padding_t,
self.forward_model.Source, self.forward_model.Target = self.forward_model.dataset:read_train(test_file)
if End == 1 then
break
end
self.forward_model:model_forward()
self.backward_model.Source = {}
self.backward_model.Target = {}
for i = 1, #self.forward_model.Source do
self.backward_model.Source[i] = self.forward_model.Target[i]:sub(1, -1, 2, self.forward_model.Target[i]:size(2) - 1)
self.backward_model.Target[i] = torch.cat(torch.Tensor({ { self.backward_model.dataset.EOS } }),
torch.cat(self.forward_model.Source[i], torch.Tensor({ self.backward_model.dataset.EOT })))
end
self.backward_model.Word_s,
self.backward_model.Mask_s,
self.backward_model.Left_s,
self.backward_model.Padding_s = self.backward_model.dataset:get_batch(self.backward_model.Source, true)
self.backward_model.Word_t,
self.backward_model.Mask_t,
self.backward_model.Left_t,
self.backward_model.Padding_t = self.backward_model.dataset:get_batch(self.backward_model.Target, false)
self.backward_model:model_forward()
self.backward_score = self.backward_model:SentencePpl()
aver_ppl = aver_ppl + self.backward_score:sum()
sen_num = sen_num + self.backward_score:size(1)
self.mode = "test"
local BatchError, BatchInstance = self:model_forward()
totalError = totalError + BatchError
n_instance = n_instance + BatchInstance
end
local Error = totalError / n_instance
logger.info('totalError: %.4f', totalError)
logger.info('n_instance: %d', n_instance)
logger.info('Error: %.4f', Error)
end
function BackwardModel:save(batch_n)
local params = self.map:parameters()
local filename = path.join(self.params.save_model_path, 'model' .. batch_n)
logger.info('saving future predictor params to %s', filename)
local file = torch.DiskFile(filename, "w"):binary()
file:writeObject(params)
file:close()
end
function BackwardModel:train()
local End, Word_s, Word_t, Mask_s, Mask_t
local End = 0
local batch_n = 1
self.iter = 0
logger.info('initial testing')
self:test()
while true do
End = 0
logger.info('Epoch %d', self.iter)
self.iter = self.iter + 1
local train_file = assert(io.open(self.params.train_file, "r"), 'cannot open train_file')
while End == 0 do
batch_n = batch_n + 1
if batch_n % 5000 == 0 then
logger.info('validate at batch_n: ', batch_n)
self:test()
self:save(batch_n)
end
End, self.forward_model.Word_s, self.forward_model.Word_t,
self.forward_model.Mask_s, self.forward_model.Mask_t,
self.forward_model.Left_s, self.forward_model.Left_t,
self.forward_model.Padding_s, self.forward_model.Padding_t,
self.forward_model.Source, self.forward_model.Target = self.forward_model.dataset:read_train(train_file)
if End == 1 then
break
end
self.forward_model:model_forward()
self.backward_model.Source = {}
self.backward_model.Target = {}
for i = 1, #self.forward_model.Source do
self.backward_model.Source[i] = self.forward_model.Target[i]:sub(1, -1, 2, self.forward_model.Target[i]:size(2) - 1)
self.backward_model.Target[i] = torch.cat(torch.Tensor({ { self.backward_model.dataset.EOS } }),
torch.cat(self.forward_model.Source[i], torch.Tensor({ self.backward_model.dataset.EOT })))
end
self.backward_model.Word_s,
self.backward_model.Mask_s,
self.backward_model.Left_s,
self.backward_model.Padding_s = self.backward_model.dataset:get_batch(self.backward_model.Source, true)
self.backward_model.Word_t,
self.backward_model.Mask_t,
self.backward_model.Left_t,
self.backward_model.Padding_t = self.backward_model.dataset:get_batch(self.backward_model.Target, false)
self.backward_model:model_forward()
self.backward_score = self.backward_model:SentencePpl()
self.mode = "train"
self:model_forward()
end
self:save(batch_n)
self:test()
if self.iter == self.params.max_iter then
logger.info("Done training!")
break
end
end
end
return BackwardModel
|
old = rconsoleprint
rconsoleprint = function(...)
e = {...}
if e[2] then e[2] = e[2]:upper() old("@@"..e[2].."@@") else old("@@WHITE@@") end
old(e[1])
end
rconsoleprint([[
___
/\__\
/:/ _/_
/:/ /\__\
/:/ /:/ _/_
/:/_/:/ /\__\
\:\/:/ /:/ /
\::/_/:/ /
\:\/:/ /
\::/ /
\/__/
]], "magenta")
|
local wibox = require('wibox')
local awful = require('awful')
local gears = require('gears')
local beautiful = require('beautiful')
local dpi = beautiful.xresources.apply_dpi
local builder = require('widget.notif-center.build-notifbox.notifbox-ui-elements')
local notifbox_core = require('widget.notif-center.build-notifbox')
local notifbox_layout = notifbox_core.notifbox_layout
local remove_notifbox_empty = notifbox_core.remove_notifbox_empty
local reset_notifbox_layout = notifbox_core.reset_notifbox_layout
local return_date_time = function(format)
return os.date(format)
end
local parse_to_seconds = function(time)
local hourInSec = tonumber(string.sub(time, 1, 2)) * 3600
local minInSec = tonumber(string.sub(time, 4, 5)) * 60
local getSec = tonumber(string.sub(time, 7, 8))
return (hourInSec + minInSec + getSec)
end
notifbox_box = function(notif, icon, title, message, app, bgcolor)
local time_of_pop = return_date_time('%H:%M:%S')
local exact_time = return_date_time('%I:%M %p')
local exact_date_time = return_date_time('%b %d, %I:%M %p')
local notifbox_timepop = wibox.widget {
id = 'time_pop',
markup = nil,
font = 'Hack Nerd Regular 10',
align = 'left',
valign = 'center',
visible = true,
widget = wibox.widget.textbox
}
local notifbox_dismiss = builder.notifbox_dismiss()
local time_of_popup = gears.timer {
timeout = 60,
call_now = true,
autostart = true,
callback = function()
local time_difference = nil
time_difference = parse_to_seconds(return_date_time('%H:%M:%S')) - parse_to_seconds(time_of_pop)
time_difference = tonumber(time_difference)
if time_difference < 60 then
notifbox_timepop:set_markup('now')
elseif time_difference >= 60 and time_difference < 3600 then
local time_in_minutes = math.floor(time_difference / 60)
notifbox_timepop:set_markup(time_in_minutes .. 'm ago')
elseif time_difference >= 3600 and time_difference < 86400 then
notifbox_timepop:set_markup(exact_time)
elseif time_difference >= 86400 then
notifbox_timepop:set_markup(exact_date_time)
return false
end
collectgarbage('collect')
end
}
local notifbox_template = wibox.widget {
id = 'notifbox_template',
expand = 'none',
{
{
layout = wibox.layout.fixed.vertical,
spacing = dpi(5),
{
expand = 'none',
layout = wibox.layout.align.horizontal,
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(5),
builder.notifbox_icon(icon),
builder.notifbox_appname(app),
},
nil,
{
notifbox_timepop,
notifbox_dismiss,
layout = wibox.layout.fixed.horizontal
}
},
{
layout = wibox.layout.fixed.vertical,
spacing = dpi(5),
{
builder.notifbox_title(title),
builder.notifbox_message(message),
layout = wibox.layout.fixed.vertical
},
builder.notifbox_actions(notif),
},
},
margins = dpi(10),
widget = wibox.container.margin
},
bg = bgcolor,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(cr, width, height, true, true, true, true, beautiful.groups_radius)
end,
widget = wibox.container.background,
}
-- Put the generated template to a container
local notifbox = wibox.widget {
notifbox_template,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(cr, width, height, true, true, true, true, beautiful.groups_radius)
end,
widget = wibox.container.background
}
-- Delete notification box
local notifbox_delete = function()
notifbox_layout:remove_widgets(notifbox, true)
end
-- Delete notifbox on LMB
notifbox:buttons(
awful.util.table.join(
awful.button(
{},
1,
function()
if #notifbox_layout.children == 1 then
reset_notifbox_layout()
else
notifbox_delete()
end
collectgarbage('collect')
end
)
)
)
-- Add hover, and mouse leave events
notifbox_template:connect_signal(
'mouse::enter',
function()
notifbox.bg = beautiful.groups_bg
notifbox_timepop.visible = false
notifbox_dismiss.visible = true
end
)
notifbox_template:connect_signal(
'mouse::leave',
function()
notifbox.bg = beautiful.tranparent
notifbox_timepop.visible = true
notifbox_dismiss.visible = false
end
)
collectgarbage('collect')
return notifbox
end
return notifbox_box
|
AddEvent("OnPackageStart", function()
CreateObject(256, 195071.625, 209471.109375, 1212.8002929688, 0.65263819694519, -0.36135864257813, 90.038497924805, 0.9997735619545, 0.9997735619545, 1.3225631713867)
CreateObject(256, 195371.90625, 209469.46875, 1212.8002929688, 0.65263819694519, -0.36135864257813, 90.038497924805, 0.99986910820007, 1.0149122476578, 1.3331836462021)
CreateObject(256, 194804.859375, 209477.6875, 1212.8002929688, 0.65263819694519, -0.36135864257813, 90.038497924805, 0.99991273880005, 0.99991273880005, 1.3186469078064)
CreateObject(256, 194519.90625, 209474.6875, 1212.8002929688, 0.65261089801788, -0.36682131886482, 90.033668518066, 0.99991273880005, 0.99991273880005, 1.3284088373184)
CreateObject(256, 194238.40625, 209477.71875, 1212.8002929688, 0.65259039402008, -0.36682125926018, 90.031265258789, 0.99991273880005, 0.99991273880005, 1.3294283151627)
CreateObject(256, 193949.453125, 209473.671875, 1212.8002929688, 0.65257674455643, -0.36956781148911, 90.02889251709, 0.99991273880005, 0.99991273880005, 1.3188437223434)
CreateObject(256, 193674.96875, 209455.8125, 1212.8002929688, 0.65255624055862, -0.37231442332268, 90.026504516602, 0.99991273880005, 0.99991273880005, 1.3314300775528)
CreateObject(199, 195434.671875, 209702.546875, 1212.4813232422, -0.0013728679623455, -90.187797546387, -0.0013732908992097, 0.99986910820007, 0.99986910820007, 0.99986910820007)
CreateObject(199, 195435.71875, 209852.0, 1212.4813232422, -0.0013728679623455, -90.187797546387, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(318, 194898.828125, 208697.765625, 1222.2188720703, 0.0, 0.0, 0.0, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(318, 193546.6875, 208697.765625, 1222.2188720703, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(318, 193884.90625, 208697.765625, 1222.2188720703)
CreateObject(318, 194220.65625, 208697.765625, 1222.2188720703)
CreateObject(318, 194558.46875, 208697.765625, 1222.2188720703)
CreateObject(82, 195209.1875, 206924.1875, 1184.9460449219, 0.0, 0.0, 0.0, 1.3406745195389, 1.1390436887741, 0.99990922212601)
CreateObject(122, 195900.34375, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(122, 194695.671875, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(122, 194367.1875, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(122, 194032.03125, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(122, 193694.703125, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(199, 195221.15625, 208680.421875, 1212.4813232422, -0.0013728679623455, -90.187797546387, -0.0013732908992097, 1.7572736740112, 0.94509261846542, 1.5848981142044)
CreateObject(315, 193514.921875, 208412.859375, 1243.7447509766, 0.0, 0.0, 0.0, 11.488647460938, -0.26744109392166, 2.2393846511841)
CreateObject(315, 196954.59375, 208407.390625, 1243.7448730469, -0.0013728679623455, -90.002723693848, -0.0013732911320403, 9.9413919448853, 1.2336050271988, 2.2394526004791)
CreateObject(199, 195736.5, 208680.421875, 1212.4813232422, -0.0013728679623455, -90.187797546387, -0.0013732908992097, 1.6993761062622, 1.0964287519455, 1.5923215150833)
CreateObject(318, 195752.984375, 208697.765625, 1222.2188720703, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(318, 197062.234375, 208697.765625, 1222.2188720703, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(318, 196089.828125, 208697.765625, 1222.2188720703)
CreateObject(318, 196423.671875, 208697.765625, 1222.2188720703)
CreateObject(318, 196758.953125, 208697.765625, 1222.2188720703)
CreateObject(614, 197017.3125, 207732.859375, 1212.4904785156, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(614, 197012.84375, 207134.546875, 1212.4904785156, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(614, 197007.53125, 206571.359375, 1212.4904785156, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(661, 197029.265625, 206932.671875, 1214.2769775391, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(649, 196995.5625, 206831.421875, 1409.1403808594, 0.0, 179.9861907959, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(649, 196995.125, 207428.625, 1409.1403808594, -0.002745735924691, 179.9861907959, -0.0027465815655887, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(122, 195081.890625, 208650.609375, 1212.4846191406)
CreateObject(122, 196239.5625, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(122, 196567.125, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(122, 196913.3125, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(122, 197210.296875, 208650.609375, 1212.4846191406, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(386, 195242.578125, 206917.34375, 1716.6330566406, 0.0, 0.0, 0.0, 3.4144699573517, 2.9731483459473, 0.99983483552933)
CreateObject(766, 195326.109375, 208419.0625, 1213.4125976563, 0.0, 0.0, 0.0, 0.99986910820007, 0.99986910820007, 0.99986910820007)
CreateObject(766, 195477.296875, 208418.125, 1213.4854736328, 0.0, 0.0, 0.0, 0.99978190660477, 0.99978190660477, 0.99978190660477)
CreateObject(159, 194858.140625, 208414.4375, 1441.3233642578, -90.0, -0.0034970566630363, -0.00201416015625, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(159, 194366.28125, 208414.4375, 1441.3233642578, -90.0, 0.0, -0.00274658203125)
CreateObject(159, 193868.171875, 208414.4375, 1441.3233642578, -90.0, 0.0, -0.00274658203125)
CreateObject(159, 195918.375, 208414.4375, 1441.3233642578, -90.0, -0.0069941133260727, -0.001251220703125)
CreateObject(159, 196466.078125, 208414.4375, 1441.3233642578, -90.0, -0.013988226652145, 0.0030074883252382, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(315, 193534.375, 205438.9375, 1246.8466796875, 0.0, 0.0, 0.0, 11.443093299866, 0.99976706504822, 2.2249622344971)
CreateObject(315, 193522.671875, 205428.046875, 1229.0401611328, 0.0, 90.047454833984, 0.0, 9.9571199417114, 0.71701967716217, 2.3165533542633)
CreateObject(880, 193518.03125, 205976.125, 1230.3499755859, 0.0, -90.075035095215, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(650, 196981.203125, 207956.46875, 1423.1656494141, -0.002745735924691, -179.94123840332, -0.0027465817984194, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(330, 193443.59375, 206199.796875, 1219.7769775391, -0.026064001023769, -89.996887207031, -95.793029785156, 2.5167000293732, 1.8136404752731, 2.5531725883484)
CreateObject(650, 196985.484375, 206258.234375, 1423.1656494141, -0.002745735924691, -179.94123840332, -0.0027465817984194, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(863, 196961.78125, 205727.65625, 1332.8918457031, 0.0, -90.01537322998, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(864, 196964.71875, 205629.40625, 1275.5085449219, -0.0013728679623455, -90.100357055664, -0.0013732908992097, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(868, 196943.328125, 205932.4375, 1214.0014648438, -0.0013728679623455, -90.067359924316, -0.0013732911320403, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(867, 196957.34375, 205931.5625, 1219.2518310547, 0.0, 0.0, 0.0, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(718, 197023.0625, 206799.71875, 1212.4802246094)
CreateObject(718, 197018.90625, 207338.1875, 1212.4973144531)
CreateObject(719, 197018.90625, 207435.71875, 1212.4973144531, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(657, 196995.15625, 207540.0625, 1212.49609375)
CreateObject(658, 197013.71875, 206388.390625, 1206.1915283203, 0.0, 0.0, 0.0, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(324, 193517.71875, 208396.140625, 1231.2122802734, 0.0, 0.0, 0.0, 11.462233543396, 0.99984204769135, 4.6632046699524)
CreateObject(324, 196932.8125, 208379.890625, 1216.1926269531, 0.0, -90.048728942871, 0.0, 9.7476015090942, 1.2402197122574, 4.8531064987183)
CreateObject(324, 193535.875, 208384.9375, 1216.1926269531, 0.0, -90.072006225586, 0.0, 9.8054475784302, 0.99995636940002, 4.8133082389832)
CreateObject(324, 193535.75, 205455.25, 1216.1925048828, 0.0, 0.0, 0.0, 11.302969932556, 0.9999423623085, 4.7914438247681)
CreateObject(766, 195479.703125, 208385.375, 1213.4854736328, 0.0, 0.0, 0.0, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(766, 195326.6875, 208386.921875, 1213.4125976563, 0.0, 0.0, 0.0, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(761, 195870.796875, 207456.59375, 1216.1925048828, 0.0, 90.005279541016, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1414, 195857.609375, 207757.21875, 1335.5981445313, -89.093437194824, -178.41278076172, -90.839630126953, 3.3063900470734, 83.409873962402, 8.2960605621338)
CreateObject(1414, 195859.03125, 207757.21875, 1617.6022949219, -89.098197937012, -178.42013549805, -90.843269348145, 3.6513600349426, 8.117525100708, 8.3923282623291)
CreateObject(759, 195870.671875, 207758.484375, 1464.1533203125, 0.0, -90.003410339355, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(759, 195884.828125, 207470.015625, 1216.1925048828, 0.0, 0.0, 0.0, 3.4354100227356, 0.99995636940002, 2.6582701206207)
CreateObject(765, 194995.15625, 208082.15625, 1216.1925048828, -0.0013728679623455, -90.004180908203, -0.001373291015625, 0.9998254776001, 0.9998254776001, 0.9998254776001)
CreateObject(758, 194995.625, 208384.78125, 1216.1926269531, -0.0013728679623455, -90.077270507813, -0.0013732907827944, 0.99978190660477, 0.99978190660477, 0.99978190660477)
CreateObject(759, 194993.90625, 207782.203125, 1464.1533203125, -0.0013728679623455, -90.003410339355, -0.0013732911320403, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(759, 194995.40625, 208084.203125, 1464.1533203125, -0.0013728679623455, -90.003410339355, -0.0013732911320403, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(759, 194995.265625, 208386.34375, 1464.1533203125, -0.0013728679623455, -90.003410339355, -0.0013732911320403, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(767, 195865.421875, 207508.921875, 1216.1926269531, 0.0, 90.039024353027, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(759, 193547.640625, 207470.78125, 1216.1926269531, 0.0, 0.0, 0.0, 4.8589158058167, 0.99973219633102, 2.6577196121216)
CreateObject(767, 194998.796875, 207633.296875, 1216.1926269531, -0.0013728679623455, 134.54260253906, -0.0013732908992097, 0.99986910820007, 0.99986910820007, 0.99986910820007)
CreateObject(1409, 196871.9375, 207970.734375, 1216.1926269531, 0.0, 89.95093536377, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1134, 196750.96875, 207874.890625, 1216.1926269531, 0.0, 11.140290260315, 0.0, 0.99994844198227, 1.3323818445206, 1.433043718338)
CreateObject(1132, 196005.90625, 207878.9375, 1216.6343994141, -0.0073561132885516, 160.43536376953, -0.0073547358624637, 0.99986910820007, 0.99986910820007, 0.99986910820007)
CreateObject(1153, 195907.375, 207702.625, 1213.5031738281, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1132, 196010.078125, 208064.703125, 1217.4841308594, -0.012786113657057, -167.49142456055, -0.012786862440407, 0.99986910820007, 0.99986910820007, 0.99986910820007)
CreateObject(1132, 196002.59375, 208237.734375, 1217.4841308594, -0.017731169238687, 165.89088439941, -0.01773070730269, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(537, 196474.875, 208357.03125, 1216.1926269531, 0.0, 179.97526550293, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(537, 196517.734375, 208357.03125, 1216.1926269531, -0.002745735924691, 179.97526550293, -0.0027465822640806, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(537, 196563.15625, 208357.03125, 1216.1926269531, -0.002745735924691, 179.97526550293, -0.0027465822640806, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(537, 196607.125, 208357.03125, 1216.1926269531, -0.002745735924691, 179.97526550293, -0.0027465822640806, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(537, 196647.609375, 208357.03125, 1216.1926269531, -0.002745735924691, 179.97526550293, -0.0027465822640806, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(542, 196644.953125, 207527.5625, 1216.1926269531, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(540, 196585.53125, 207539.109375, 1308.2926025391, 0.0, -179.71920776367, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(539, 196649.21875, 207521.546875, 1308.2879638672, 0.0, -179.74412536621, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(546, 196715.015625, 207539.296875, 1308.2878417969)
CreateObject(534, 196632.8125, 207631.046875, 1216.1925048828, -0.0022607925347984, -147.86001586914, -0.0022583003155887, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(531, 196857.75, 207886.109375, 1297.0642089844)
CreateObject(535, 196817.515625, 207523.359375, 1216.1926269531, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(544, 196493.0, 207536.796875, 1216.1925048828)
CreateObject(545, 196207.703125, 208384.765625, 1504.4323730469, 1.3343456983566, 179.99989318848, 89.952087402344, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(651, 196906.703125, 208330.359375, 1565.3532714844, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(673, 196861.109375, 207999.03125, 1297.060546875)
CreateObject(537, 196067.71875, 207723.25, 1215.1589355469, 0.0, 0.0, 0.0, 0.99986910820007, 0.99986910820007, 0.99986910820007)
CreateObject(537, 196110.15625, 207723.25, 1215.1589355469, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(529, 196560.078125, 208384.765625, 1403.0717773438, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(543, 196873.328125, 208082.84375, 1297.0582275391)
CreateObject(541, 196457.625, 207842.109375, 1216.1926269531, 0.0, 0.0, 0.0, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(541, 196456.28125, 207937.90625, 1216.1926269531, -0.002745735924691, 179.83088684082, -0.0027465822640806, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(538, 196462.78125, 207851.109375, 1308.2884521484, 0.0, -5.667453289032, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(538, 196460.734375, 207940.046875, 1308.2886962891, 0.0, -170.57774353027, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(540, 196513.09375, 207940.734375, 1308.2912597656, 0.0, -177.87013244629, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(540, 196412.265625, 207848.0625, 1308.2844238281, 0.0, -1.3013916015625, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(547, 196527.515625, 207835.890625, 1308.2839355469)
CreateObject(548, 196410.09375, 207949.515625, 1309.9869384766, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(533, 196448.84375, 208034.546875, 1216.1926269531, 0.0, -153.57386779785, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(533, 196445.359375, 207749.75, 1216.1926269531, 0.0, 2.3794150352478, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(485, 196865.796875, 207939.578125, 1297.0618896484, 0.0, -173.36175537109, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1098, 196115.28125, 208386.515625, 1211.7221679688, 0.0, 90.073303222656, 0.0, 0.9866658449173, 1.2829129695892, 1.844388127327)
CreateObject(1363, 195359.6875, 206226.03125, 1219.166015625, -0.0030872453935444, 67.53125, -0.0030822751577944, 0.99986910820007, 0.99986910820007, 0.99986910820007)
CreateObject(557, 196004.578125, 207419.3125, 1207.4813232422, -0.002745735924691, -179.17112731934, -0.0027465815655887, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(557, 196251.921875, 207419.3125, 1207.4813232422, -0.002745735924691, -179.17112731934, -0.0027465815655887, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 196494.84375, 207419.3125, 1207.4813232422, -0.0082098869606853, -179.17112731934, -0.0082092275843024, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 196746.078125, 207419.3125, 1207.4813232422, -0.013674037531018, -179.17112731934, -0.013671873137355, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194870.765625, 207419.3125, 1207.4813232422, -0.0082098869606853, -179.17112731934, -0.0082092275843024, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 193709.0625, 207419.3125, 1207.4813232422, -0.013674037531018, -179.17112731934, -0.013671873137355, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(557, 194598.875, 207419.3125, 1207.4813232422, -0.013674037531018, -179.17112731934, -0.013671873137355)
CreateObject(557, 194307.890625, 207419.3125, 1207.4813232422, -0.013674037531018, -179.17112731934, -0.013671873137355)
CreateObject(557, 194017.25, 207419.3125, 1207.4813232422, -0.013674037531018, -179.17112731934, -0.013671873137355)
CreateObject(1418, 195227.484375, 206443.390625, 1216.1926269531, -0.00049177359323949, 32.01912689209, -0.00048828122089617, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(1418, 195341.359375, 206512.1875, 1216.1926269531, -0.00049177359323949, -3.8377392292023, -0.00048828125, 0.99991273880005, 0.99991273880005, 0.99991273880005)
CreateObject(734, 193546.65625, 207913.78125, 1307.2728271484, 0.0, 0.0, 0.0, 0.99995636940002, 2.0867800712585, 1.6437669992447)
CreateObject(557, 193925.25, 207764.3125, 1216.1926269531, 0.0, 90.498237609863, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194068.5625, 207765.390625, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194207.421875, 207765.390625, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194336.515625, 207765.390625, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 193926.59375, 208125.109375, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194066.28125, 208125.109375, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194201.890625, 208125.109375, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194330.4375, 208125.109375, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194469.828125, 208125.109375, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(557, 194466.453125, 207765.390625, 1216.1926269531, -0.0013728679623455, 90.498237609863, -0.0013732908992097, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1418, 195498.734375, 206476.625, 1216.1926269531, -0.00051909434841946, -44.914142608643, -0.00051879876991734, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1418, 195583.296875, 206341.609375, 1216.1926269531, -0.00070350943133235, -92.738189697266, -0.00067138666054234, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1418, 195573.828125, 206171.125, 1216.1926269531, -0.0014070188626647, -114.01552581787, -0.0014038083609194, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1418, 195492.546875, 206016.765625, 1216.1926269531, -0.0017416981281713, -140.35540771484, -0.001739501603879, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1418, 195228.5625, 205950.484375, 1216.1926269531, -0.0065296604298055, 129.32656860352, -0.00653076171875, 0.99978190660477, 0.99978190660477, 0.99978190660477)
CreateObject(1418, 195373.203125, 205935.015625, 1216.1942138672, -0.0027184151113033, 178.40017700195, -0.002716064453125, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1418, 195148.96875, 206332.453125, 1216.1926269531, -0.0029301510658115, 64.173461914063, -0.0009765625, 0.99986910820007, 0.99986910820007, 0.99986910820007)
CreateObject(1418, 195148.828125, 206073.390625, 1216.1926269531, -0.0098559623584151, 101.8490524292, -0.0098571768030524, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(1418, 195129.5, 206208.171875, 1216.5723876953, -0.0029301510658115, 82.101455688477, -0.0009765625, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(315, 195904.15625, 205466.671875, 1216.1926269531, -0.0014070188626647, 92.344429016113, -0.0014038083609194, 4.1042151451111, 0.93402689695358, 2.0425548553467)
CreateObject(1264, 195362.46875, 206224.703125, 1099.591796875, 0.0, 0.0, 0.0, 3.2674293518066, 4.3323631286621, 1.2745432853699)
CreateObject(315, 195847.953125, 206691.4375, 1216.1926269531, -0.0014070188626647, 0.032826341688633, -0.0014038083609194, 3.5784335136414, 0.99990594387054, 2.0512502193451)
CreateObject(315, 193541.875, 206918.140625, 1216.1926269531, 0.0, 0.0, 0.0, 4.1104311943054, 0.99995636940002, 2.035462141037)
CreateObject(315, 194780.953125, 206923.359375, 1216.1925048828, 0.0, -90.03734588623, 0.0, 4.8486814498901, 0.9542293548584, 2.0449862480164)
CreateObject(714, 196556.921875, 206697.796875, 1218.1092529297, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(714, 194786.234375, 206378.21875, 1214.0982666016, 0.0, -89.944122314453, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(718, 194273.65625, 206971.046875, 1216.1926269531)
CreateObject(718, 196118.359375, 206724.53125, 1216.1926269531, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
CreateObject(705, 195345.03125, 206233.953125, 1616.6567382813, 0.0, 0.0, 0.0, 0.99995636940002, 0.99995636940002, 0.99995636940002)
end)
|
local codec = require('websocket-codec')
local base64 = _G.luvitwsrequire('./modules/base64')
local json = _G.luvitwsrequire("./modules/json")
local sha1 = _G.luvitwsrequire('./modules/sha1')
local packets = {}
local insert, remove, concat = table.insert, table.remove, table.concat
local fmod, floor, frexp = math.fmod, math.floor, math.frexp
-- // -- -- // -- -- // -- -- // -- -- // --
local function str2bin (s)
local b = {}
for c in s:gmatch('.') do
local n = c:byte()
local d = {}
for i=math.max(1, select(2, frexp(n))), 1, -1 do
d[i] = fmod(n, 2)
n = floor((n - d[i]) / 2)
end
insert(b, concat(d))
end
return concat(b)
end
-- // -- -- // -- -- // -- -- // -- -- // --
function packets:assemble(msg)
return codec.encode(tostring(msg))
end
function packets:disassemble(chunk)
local packet = codec.decode(chunk, 1)
if (not packet) then return end
return {
payload = packet.payload,
opcode = packet.opcode
}
end
function packets:assembleHandshake(client, data)
local headers = {}
local headers_split = tostring(data):split('\r\n')
remove(headers_split, 1)
for i, header in ipairs(headers_split) do
local header_split = header:split(': ')
local key = remove(header_split, 1)
local value = concat(header_split, ': ')
pcall(function() value = json.parse(value) end)
headers[key] = value
end
client.headers = headers
local key = headers["Sec-WebSocket-Key"]
if (not key) then
return false
end
local d = concat({
"HTTP/1.1 101 Switching Protocols",
"Connection: Upgrade",
"Upgrade: websocket",
"Sec-WebSocket-Accept: " .. base64.encode(sha1.binary(key .. '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')),
"",
""
}, "\r\n")
client:write(d)
return true
end
return packets
|
math.randomseed(os.time())
local hue = math.random(0, 360);
local wezterm = require 'wezterm'
local function font_with_fallback(name, params)
local names = { name, "Noto Color Emoji", "FiraCode Nerd Font" }
return wezterm.font_with_fallback(names, params)
end
-- local SOLID_LEFT_ARROW = utf8.char(0xe0b2)
local SOLID_RIGHT_ARROW = utf8.char(0xe0b0)
local Grey = "#0f1419"
local LightGrey = "#191f26"
local TAB_BAR_BG = "Black"
local ACTIVE_TAB_BG = "#dcff00"
local ACTIVE_TAB_FG = "Black"
local HOVER_TAB_BG = Grey
local HOVER_TAB_FG = "White"
local NORMAL_TAB_BG = LightGrey
local NORMAL_TAB_FG = "White"
wezterm.on('format-tab-title', function(tab, tabs, panes, config, hover, max_width)
local background = NORMAL_TAB_BG
local foreground = NORMAL_TAB_FG
local is_first = tab.tab_id == tabs[1].tab_id
local is_last = tab.tab_id == tabs[#tabs].tab_id
if tab.is_active then
background = ACTIVE_TAB_BG
foreground = ACTIVE_TAB_FG
elseif hover then
background = HOVER_TAB_BG
foreground = HOVER_TAB_FG
end
local leading_fg = NORMAL_TAB_FG
local leading_bg = background
local trailing_fg = background
local trailing_bg = NORMAL_TAB_BG
if is_first then
-- leading_fg = TAB_BAR_BG
leading_fg = background
leading_bg = background
else
leading_fg = NORMAL_TAB_BG
end
if is_last then
trailing_bg = TAB_BAR_BG
else
trailing_bg = NORMAL_TAB_BG
end
local title = tab.active_pane.title
-- broken?
-- local title = " " .. wezterm.truncate_to_width(tab.active_pane.title, 30) .. " "
return {
{Attribute={Italic=false}},
{Attribute={Intensity=hover and "Bold" or "Normal"}},
{Background={Color=leading_bg}}, {Foreground={Color=leading_fg}},
{Text=SOLID_RIGHT_ARROW},
{Background={Color=background}}, {Foreground={Color=foreground}},
{Text=" "..title.." "},
{Background={Color=trailing_bg}}, {Foreground={Color=trailing_fg}},
{Text=SOLID_RIGHT_ARROW},
}
end)
wezterm.on("update-right-status", function(window, pane)
local leader = ""
if window:leader_is_active() then
leader = " ⚠️ 🔴 ⚠️ "
end
window:set_right_status(leader)
end);
return {
-- default_prog = {"wsl", "-d", "Ubuntu-20.04"},
window_decorations = "RESIZE",
default_cursor_style = "BlinkingBlock",
-- native_macos_fullscreen_mode = true,
-- hide_tab_bar_if_only_one_tab = true,
-- tab_bar_at_bottom = true,
use_fancy_tab_bar = false,
enable_tab_bar = true,
tab_max_width = 32,
initial_cols = 130,
initial_rows = 80,
inactive_pane_hsb = {
saturation = 0.5,
brightness = 0.5,
},
-- color_scheme = "3024 Day",
colors = {
tab_bar = {
background = TAB_BAR_BG,
},
compose_cursor = "orange",
},
tab_bar_style = {
new_tab = wezterm.format{
{Background={Color=HOVER_TAB_BG}}, {Foreground={Color=TAB_BAR_BG}},
{Text=SOLID_RIGHT_ARROW},
{Background={Color=HOVER_TAB_BG}}, {Foreground={Color=HOVER_TAB_FG}},
{Text=" + "},
{Background={Color=TAB_BAR_BG}}, {Foreground={Color=HOVER_TAB_BG}},
{Text=SOLID_RIGHT_ARROW},
},
new_tab_hover = wezterm.format{
{Attribute={Italic=false}},
{Attribute={Intensity="Bold"}},
{Background={Color=NORMAL_TAB_BG}}, {Foreground={Color=TAB_BAR_BG}},
{Text=SOLID_RIGHT_ARROW},
{Background={Color=NORMAL_TAB_BG}}, {Foreground={Color=NORMAL_TAB_FG}},
{Text=" + "},
{Background={Color=TAB_BAR_BG}}, {Foreground={Color=NORMAL_TAB_BG}},
{Text=SOLID_RIGHT_ARROW},
},
},
exit_behavior = "Close",
leader = { key="a", mods="CTRL", timeout_milliseconds=1000 },
keys = {
-- { key = "`", mods = "LEADER", action="ShowLauncher"},
-- { key = "a", mods = "LEADER|CTRL", action=wezterm.action{SendString="\x01"}},
-- { key = "c", mods = "LEADER", action=wezterm.action{SpawnTab="DefaultDomain"}},
-- { key = "-", mods = "LEADER", action=wezterm.action{ SplitVertical={ domain="CurrentPaneDomain" } } },
-- { key = "\\", mods = "LEADER", action=wezterm.action{ SplitHorizontal={ domain="CurrentPaneDomain" } } },
-- { key = "h", mods = "LEADER", action=wezterm.action{ ActivatePaneDirection="Left" } },
-- { key = "l", mods = "LEADER", action=wezterm.action{ ActivatePaneDirection="Right" } },
-- { key = "j", mods = "LEADER", action=wezterm.action{ ActivatePaneDirection="Down" } },
-- { key = "k", mods = "LEADER", action=wezterm.action{ ActivatePaneDirection="Up" } },
-- { key = "{", mods = "SHIFT|ALT", action=wezterm.action{ MoveTabRelative=-1 } },
-- { key = "}", mods = "SHIFT|ALT", action=wezterm.action{ MoveTabRelative=1 } },
-- { key = "d", mods = "LEADER", action=wezterm.action{CloseCurrentTab={confirm=false}}},
-- { key = "x", mods = "LEADER", action=wezterm.action{CloseCurrentPane={confirm=true}}},
{key="c", mods="LEADER", action=wezterm.action{SpawnTab="CurrentPaneDomain"}},
{key="d", mods="LEADER", action=wezterm.action{CloseCurrentTab={confirm=false}}},
{key="1", mods="LEADER", action=wezterm.action{ActivateTab=0}},
{key="2", mods="LEADER", action=wezterm.action{ActivateTab=1}},
{key="3", mods="LEADER", action=wezterm.action{ActivateTab=2}},
{key="4", mods="LEADER", action=wezterm.action{ActivateTab=3}},
{key="5", mods="LEADER", action=wezterm.action{ActivateTab=4}},
{key="6", mods="LEADER", action=wezterm.action{ActivateTab=5}},
{key="7", mods="LEADER", action=wezterm.action{ActivateTab=6}},
{key="8", mods="LEADER", action=wezterm.action{ActivateTab=7}},
{key="LeftArrow", mods="CTRL", action=wezterm.action{SendString="\x1bb"}},
{key="RightArrow", mods="CTRL", action=wezterm.action{SendString="\x1bf"}},
{key="Backspace", mods="CTRL", action={
Multiple={
{SendKey={key="Escape"}},
{SendKey={key="Backspace"}},
}}},
},
ssh_domains = {
{
-- This name identifies the domain
name = "ubuntu",
-- The address to connect to
remote_address = "localhost",
-- The username to use on the remote host
username = "nexinov",
}
},
default_gui_startup_args = {"connect", "ubuntu"},
font = font_with_fallback("Hack"),
font_size = 12.0,
-- font = font_with_fallback("FiraCode Nerd Font"),
-- font_rules = {
-- { -- BOLD
-- intensity = "Bold",
-- weight = "Bold",
-- font = font_with_fallback("FiraCode Nerd Font", { weight = "Bold" }),
-- },
-- { -- ITALIC
-- italic = true,
-- weight = "Light",
-- font = font_with_fallback("Operator Mono SSm Lig", { italic = true }),
-- },
-- { -- BOLD ITALIC
-- italic = true,
-- intensity = "Bold",
-- weight = "Book",
-- font = font_with_fallback("Operator Mono SSm Lig", { weight = "Bold", italic = true }),
-- },
-- { -- LIGHT
-- intensity = "Half",
-- weight = "Light",
-- font = font_with_fallback("Operator Mono SSm Lig"),
-- },
-- },
-- window_background_gradient = {
-- colors = {
-- "#302b63",
-- "#0f0c29",
-- },
-- orientation = {
-- Radial={
-- cx = 0.5,
-- cy = 0.5,
-- radius = 0.65,
-- }
-- },
-- },
window_background_gradient = {
colors = {string.format("hwb(%f,%f%%,90%%)", hue, math.random(45, 50)), string.format("hwb(%f,0%%,%f%%)", hue, math.random(90, 100))},
blend = "Oklab",
orientation = {
Radial = {
cx = 0.9,
cy = 0.2,
radius = 1.3,
}
},
}
}
|
EditMeshVariation = EditMeshVariation or class(EditUnit)
function EditMeshVariation:editable(unit)
local mesh_variations = table.merge(
managers.sequence:get_editable_state_sequence_list(unit:name()) or {},
managers.sequence:get_triggable_sequence_list(unit:name())
)
local materials = self:get_material_configs_from_meta(unit)
return #mesh_variations > 0 or #materials > 0
end
function EditMeshVariation:build_menu(units)
local main = self._menu:GetItem("Main")
main:combobox("MeshVariation", ClassClbk(self._parent, "set_unit_data"), {}, 1, {free_typing = true})
main:pathbox("MaterialVariation", ClassClbk(self._parent, "set_unit_data"), "", "material_config", {custom_list = {}, control_slice = 0.58})
end
function EditMeshVariation:set_unit_data()
local unit = self:selected_unit()
local ud = unit:unit_data()
ud.mesh_variation = self._menu:GetItem("MeshVariation"):SelectedItem()
local mesh_variation = ud.mesh_variation
if mesh_variation and mesh_variation ~= "" then
managers.sequence:run_sequence_simple2(mesh_variation, "change_state", unit)
end
local material = self._menu:GetItem("MaterialVariation"):Value()
local default = material == "default"
ud.material_variation = nil
local node = not default and BLE.Utils:ParseXml("material_config", material)
if default or (DB:has(Idstring("material_config"), material:id()) and self:material_config_ok(node, unit)) then
ud.material_variation = material
end
material = ud.material_variation
if material == "default" then
material = nil
end
local final_mat = (material and Idstring(material)) or PackageManager:unit_data(unit:name()):material_config()
if ud.material ~= ud.material_variation and DB:has(Idstring("material_config"), final_mat) then
unit:set_material_config((material and Idstring(material)) or PackageManager:unit_data(unit:name()):material_config(), true)
ud.material = ud.material_variation
end
end
function EditMeshVariation:material_config_ok(node, unit)
if node then
for material in node:children() do
if not unit:material(material:parameter("name"):id()) then
return false
end
end
end
return true
end
function EditMeshVariation:get_material_configs_from_meta(unit)
local unit_name = unit:unit_data().name
if not unit_name then
return {}
end
local name = unit_name:id()
self._avalible_material_groups = self._avalible_material_groups or {}
if self._avalible_material_groups[name:key()] then
return self._avalible_material_groups[name:key()]
end
local node = PackageManager:unit_data(name):model_script_data()
local available_groups = {}
local groups = {}
for child in node:children() do
if child:name() == "metadata" and child:parameter("material_config_group") ~= "" then
table.insert(groups, child:parameter("material_config_group"))
end
end
if #groups > 0 then
local list = BLE.Utils:GetEntries({type = "material_config", loaded = false, match = Path:GetDirectory(unit_name, "/"), filenames = false})
for _, entry in ipairs(list) do
local node = BLE.Utils:ParseXml("material_config", entry)
if node then
for _, group in ipairs(groups) do
local group_name = node:has_parameter("group") and node:parameter("group")
if group_name == group and not table.contains(available_groups, entry) then
if self:material_config_ok(node, unit) then
table.insert(available_groups, entry)
end
end
end
end
end
table.insert(available_groups, "default")
end
self._avalible_material_groups[unit_name:key()] = available_groups
return available_groups
end
function EditMeshVariation:set_menu_unit(unit)
local mesh = self._menu:GetItem("MeshVariation")
local material = self._menu:GetItem("MaterialVariation")
local mesh_variations = table.merge(managers.sequence:get_editable_state_sequence_list(unit:name()), managers.sequence:get_triggable_sequence_list(unit:name()))
local materials = self:get_material_configs_from_meta(unit)
mesh:SetVisible(#mesh_variations > 0)
table.insert(mesh_variations, "")
mesh:SetItems(mesh_variations)
mesh:SetSelectedItem(unit:unit_data().mesh_variation or "")
material:SetVisible(#materials > 0)
material.custom_list = materials
material:SetValue(unit:unit_data().material_variation or "")
end
|
local t = Def.ActorFrame{
LoadActor(THEME:GetPathB("ScreenLogo","background"));
};
return t;
|
uart.setup(0, 115200, 8, 0, 1, 0)
--uart.on(1)
--uart.write(0, "page 3")
val = 65
while 1 do
uart.write(0, string.char(val), "\r\n")
val = val + 1
if val > 90 then
val = 65
end
tmr.delay(1000000)
end
|
pfUI:RegisterSkin("Tooltips", 20400, function ()
local border = tonumber(C.appearance.border.default)
local alpha = tonumber(C.tooltip.alpha)
for _, tooltip in pairs({GameTooltip, ItemRefTooltip, ShoppingTooltip1, ShoppingTooltip2}) do
CreateBackdrop(tooltip, nil, nil, alpha)
end
HookScript(WorldMapTooltip, "OnShow", function()
CreateBackdrop(WorldMapTooltip, nil, nil, alpha)
end)
SkinCloseButton(ItemRefCloseButton, ItemRefTooltip.backdrop, -6, -6)
for _, tooltip in pairs({ShoppingTooltip1, ShoppingTooltip2}) do
tooltip:SetClampedToScreen(true)
HookScript(tooltip, "OnShow", function()
local a, b, c, x, y = this:GetPoint()
if not x or x == 0 then x = (border*2) + ( x or 0 ) + 1 end
if a then this:SetPoint(a, b, c, x, y) end
end)
end
end)
|
-- @description Search Tracks for FX
-- @author Aaron Cendan
-- @version 1.0
-- @metapackage
-- @provides
-- [main] . > acendan_Search all tracks for FX by name.lua
-- @link https://aaroncendan.me
-- @about
-- # Search Tracks for FX
-- By Aaron Cendan - July 2020
--
-- * Prompts user for fx name, then searches all tracks for that fx and returns list
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- ~~~~~~~~~~~ GLOBAL VARS ~~~~~~~~~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Get script name for undo text and extracting numbers/other info, if needed
local script_name = ({reaper.get_action_context()})[2]:match("([^/\\_]+)%.lua$")
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- ~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function main()
local ret_input, user_input = reaper.GetUserInputs( "Search for FX", 1, "FX Name,extrawidth=100", "ReaComp" )
if not ret_input then return end
local fx_filter = string.lower(user_input)
local found_fx = false
for ti=0,reaper.CountTracks()-1 do
local track = reaper.GetTrack(0, ti)
for fi=0,reaper.TrackFX_GetCount(track)-1 do
local _, fx_name = reaper.TrackFX_GetFXName(track, fi, '')
if fx_name:lower():find(fx_filter) then
retval, track_name = reaper.GetSetMediaTrackInfo_String( track, "P_NAME", "", false )
if retval then dbg("Track #" .. ti + 1 .. ": " .. track_name)
else dbg("Track #" .. ti + 1) end
found_fx = true
end
end
end
if not found_fx then msg(string.format("No tracks found with '%s' added!",user_input)) end
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- ~~~~~~~~~~~~ UTILITIES ~~~~~~~~~~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Deliver messages and add new line in console
function dbg(dbg)
reaper.ShowConsoleMsg(dbg .. "\n")
end
-- Deliver messages using message box
function msg(msg)
reaper.MB(msg, script_name, 0)
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- ~~~~~~~~~~~~~~ MAIN ~~~~~~~~~~~~~~
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
reaper.PreventUIRefresh(1)
reaper.Undo_BeginBlock()
main()
reaper.Undo_EndBlock(script_name,-1)
reaper.PreventUIRefresh(-1)
reaper.UpdateArrange()
|
local API_P = require(script:GetCustomProperty("APIProjectile"))
local API_D = require(script:GetCustomProperty("APIDamage"))
local PROJECTILE_TEMPLATE = script:GetCustomProperty("ProjectileTemplate")
local BASE_DAMAGE = 25.0
local DAMAGE_MULTIPLIER = 0.7
local PROJECTILE_SPEED = 2400.0
local HEAL_RANGE = 600.0
local WAVE_SPEED = 2400.0
local BASE_HEAL = 7.0
local HEAL_MULTIPLIER = 0.2
local data = {}
data.name = script:GetCustomProperty("Name")
data.targets = true
data.friendlyTargetValid = false
data.enemyTargetValid = true
data.requiresFacing = true
data.groundTargets = false
data.icon = script:GetCustomProperty("Icon")
data.range = script:GetCustomProperty("Range")
data.cooldown = script:GetCustomProperty("Cooldown")
data.castDuration = script:GetCustomProperty("CastDuration")
data.animationKey = script:GetCustomProperty("AnimationKey")
data.description = script:GetCustomProperty("Description")
data.selfCasterEffectTemplate = script:GetCustomProperty("SelfCasterEffectTemplate")
data.otherCasterEffectTemplate = script:GetCustomProperty("OtherCasterEffectTemplate")
data.selfTargetEffectTemplate = script:GetCustomProperty("SelfTargetEffectTemplate")
data.otherTargetEffectTemplate = script:GetCustomProperty("OtherTargetEffectTemplate")
function data.onCastClient(caster, targetSet)
local target = targetSet[1]
API_P.CreateProjectile(caster, target, PROJECTILE_SPEED, 0.2, PROJECTILE_TEMPLATE)
return API_P.GetTravelTime(caster, target, PROJECTILE_SPEED)
end
function data.onCastServer(caster, targetSet)
local target = targetSet[1]
Task.Wait(API_P.GetTravelTime(caster, target, PROJECTILE_SPEED))
if not Object.IsValid(caster) then
return
end
local magicStat = caster.serverUserData.statSheet:GetStatTotalValue("Magic")
API_D.ApplyDamage(caster, target, BASE_DAMAGE + DAMAGE_MULTIPLIER * magicStat)
local impactTime = time()
local playersToHeal = Game.GetPlayers()
Task.Spawn(function()
while #playersToHeal do
local waveRadius = (time() - impactTime) * WAVE_SPEED
local healedPlayerIndices = {}
for i, player in pairs(playersToHeal) do
local distance = (target:GetWorldPosition() - player:GetWorldPosition()).size
if distance < waveRadius and not player.isDead then
API_D.ApplyHealing(caster, player, BASE_HEAL + HEAL_MULTIPLIER * magicStat, API_D.TAG_AOE)
table.insert(healedPlayerIndices, i)
end
end
for i = #healedPlayerIndices, 1, -1 do
table.remove(playersToHeal, healedPlayerIndices[i])
end
if waveRadius > HEAL_RANGE then
return
end
Task.Wait()
end
end)
end
return data
|
describe('scan', function()
local scan = require 'scan.scan'
local Token = require 'scan.Token'
local function input(s)
return {
should_generate_tokens = function(expected)
assert.are.same(expected, scan(s, load''))
end
}
end
it('should scan an empty string', function()
input('').should_generate_tokens({
Token('EOF', '', nil, 1)
})
end)
it('should scan parens', function()
input('()').should_generate_tokens({
Token('LEFT_PAREN', '(', nil, 1),
Token('RIGHT_PAREN', ')', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan braces', function()
input('{}').should_generate_tokens({
Token('LEFT_BRACE', '{', nil, 1),
Token('RIGHT_BRACE', '}', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan commas', function()
input(',').should_generate_tokens({
Token('COMMA', ',', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan dots', function()
input('.').should_generate_tokens({
Token('DOT', '.', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan minuses', function()
input('-').should_generate_tokens({
Token('MINUS', '-', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan pluses', function()
input('+').should_generate_tokens({
Token('PLUS', '+', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan semicolons', function()
input(';').should_generate_tokens({
Token('SEMICOLON', ';', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan stars', function()
input('*').should_generate_tokens({
Token('STAR', '*', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan bang equals', function()
input('!=').should_generate_tokens({
Token('BANG_EQUAL', '!=', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan bangs', function()
input('!').should_generate_tokens({
Token('BANG', '!', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan equal equals', function()
input('==').should_generate_tokens({
Token('EQUAL_EQUAL', '==', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan equals', function()
input('=').should_generate_tokens({
Token('EQUAL', '=', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan less equals', function()
input('<=').should_generate_tokens({
Token('LESS_EQUAL', '<=', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan lesses', function()
input('<').should_generate_tokens({
Token('LESS', '<', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan greater equals', function()
input('>=').should_generate_tokens({
Token('GREATER_EQUAL', '>=', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan greaters', function()
input('>').should_generate_tokens({
Token('GREATER', '>', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan slashes', function()
input('/').should_generate_tokens({
Token('SLASH', '/', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan comments', function()
input('// blah blah blah').should_generate_tokens({
Token('EOF', '', nil, 1)
})
end)
it('should end comments after a newline', function()
input('// blah blah blah\n,').should_generate_tokens({
Token('COMMA', ',', nil, 2),
Token('EOF', '', nil, 2)
})
end)
it('should delimit tokens with whitespace', function()
input('/ /\t,\r.').should_generate_tokens({
Token('SLASH', '/', nil, 1),
Token('SLASH', '/', nil, 1),
Token('COMMA', ',', nil, 1),
Token('DOT', '.', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan strings', function()
input('"abc"').should_generate_tokens({
Token('STRING', '"abc"', 'abc', 1),
Token('EOF', '', nil, 1)
})
end)
it('should detect unterminated strings', function()
local error_reporter = spy.new(load'')
scan('"abc', error_reporter)
assert.spy(error_reporter).was_called_with(1, 'Unterminated string.')
end)
it('should scan tokens from multiple lines', function()
input('/\n/').should_generate_tokens({
Token('SLASH', '/', nil, 1),
Token('SLASH', '/', nil, 2),
Token('EOF', '', nil, 2)
})
end)
it('should detect unexpected characters', function()
local error_reporter = spy.new(load'')
scan('^', error_reporter)
assert.spy(error_reporter).was_called_with(1, 'Unexpected character.')
end)
it('should scan numbers', function()
input('9 1.2 .3 1.').should_generate_tokens({
Token('NUMBER', '9', 9, 1),
Token('NUMBER', '1.2', 1.2, 1),
Token('DOT', '.', nil, 1),
Token('NUMBER', '3', 3, 1),
Token('NUMBER', '1', 1, 1),
Token('DOT', '.', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan identifiers', function()
input('a a9 _1').should_generate_tokens({
Token('IDENTIFIER', 'a', nil, 1),
Token('IDENTIFIER', 'a9', nil, 1),
Token('IDENTIFIER', '_1', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should scan keywords', function()
input('and class else false for fun if nil or print return super this true var while').should_generate_tokens({
Token('AND', 'and', nil, 1),
Token('CLASS', 'class', nil, 1),
Token('ELSE', 'else', nil, 1),
Token('FALSE', 'false', nil, 1),
Token('FOR', 'for', nil, 1),
Token('FUN', 'fun', nil, 1),
Token('IF', 'if', nil, 1),
Token('NIL', 'nil', nil, 1),
Token('OR', 'or', nil, 1),
Token('PRINT', 'print', nil, 1),
Token('RETURN', 'return', nil, 1),
Token('SUPER', 'super', nil, 1),
Token('THIS', 'this', nil, 1),
Token('TRUE', 'true', nil, 1),
Token('VAR', 'var', nil, 1),
Token('WHILE', 'while', nil, 1),
Token('EOF', '', nil, 1)
})
end)
it('should allow identifiers with a keyword prefix', function()
input('orchid').should_generate_tokens({
Token('IDENTIFIER', 'orchid', nil, 1),
Token('EOF', '', nil, 1)
})
end)
end)
|
local cfg = module("cfg/survival")
local lang = vRP.lang
-- api
function vRP.getHunger(user_id)
local data = vRP.getUserDataTable(user_id)
if data then
return data.hunger
end
return 0
end
function vRP.getThirst(user_id)
local data = vRP.getUserDataTable(user_id)
if data then
return data.thirst
end
return 0
end
function vRP.setHunger(user_id,value)
local data = vRP.getUserDataTable(user_id)
if data then
data.hunger = value
if data.hunger < 0 then data.hunger = 0
elseif data.hunger > 100 then data.hunger = 100
end
-- update bar
local source = vRP.getUserSource(user_id)
vRPclient._setProgressBarValue(source, "vRP:hunger",data.hunger)
if data.hunger >= 100 then
vRPclient._setProgressBarText(source,"vRP:hunger",lang.survival.starving())
else
vRPclient._setProgressBarText(source,"vRP:hunger","")
end
end
end
function vRP.setThirst(user_id,value)
local data = vRP.getUserDataTable(user_id)
if data then
data.thirst = value
if data.thirst < 0 then data.thirst = 0
elseif data.thirst > 100 then data.thirst = 100
end
-- update bar
local source = vRP.getUserSource(user_id)
vRPclient._setProgressBarValue(source, "vRP:thirst",data.thirst)
if data.thirst >= 100 then
vRPclient._setProgressBarText(source,"vRP:thirst",lang.survival.thirsty())
else
vRPclient._setProgressBarText(source,"vRP:thirst","")
end
end
end
function vRP.varyHunger(user_id, variation)
local data = vRP.getUserDataTable(user_id)
if data then
local was_starving = data.hunger >= 100
data.hunger = data.hunger + variation
local is_starving = data.hunger >= 100
-- apply overflow as damage
local overflow = data.hunger-100
if overflow > 0 then
vRPclient._varyHealth(vRP.getUserSource(user_id),-overflow*cfg.overflow_damage_factor)
end
if data.hunger < 0 then data.hunger = 0
elseif data.hunger > 100 then data.hunger = 100
end
-- set progress bar data
local source = vRP.getUserSource(user_id)
vRPclient._setProgressBarValue(source,"vRP:hunger",data.hunger)
if was_starving and not is_starving then
vRPclient._setProgressBarText(source,"vRP:hunger","")
elseif not was_starving and is_starving then
vRPclient._setProgressBarText(source,"vRP:hunger",lang.survival.starving())
end
end
end
function vRP.varyThirst(user_id, variation)
local data = vRP.getUserDataTable(user_id)
if data then
local was_thirsty = data.thirst >= 100
data.thirst = data.thirst + variation
local is_thirsty = data.thirst >= 100
-- apply overflow as damage
local overflow = data.thirst-100
if overflow > 0 then
vRPclient._varyHealth(vRP.getUserSource(user_id),-overflow*cfg.overflow_damage_factor)
end
if data.thirst < 0 then data.thirst = 0
elseif data.thirst > 100 then data.thirst = 100
end
-- set progress bar data
local source = vRP.getUserSource(user_id)
vRPclient._setProgressBarValue(source,"vRP:thirst",data.thirst)
if was_thirsty and not is_thirsty then
vRPclient._setProgressBarText(source,"vRP:thirst","")
elseif not was_thirsty and is_thirsty then
vRPclient._setProgressBarText(source,"vRP:thirst",lang.survival.thirsty())
end
end
end
-- tunnel api (expose some functions to clients)
function tvRP.varyHunger(variation)
local user_id = vRP.getUserId(source)
if user_id then
vRP.varyHunger(user_id,variation)
end
end
function tvRP.varyThirst(variation)
local user_id = vRP.getUserId(source)
if user_id then
vRP.varyThirst(user_id,variation)
end
end
-- tasks
-- hunger/thirst increase
function task_update()
for k,v in pairs(vRP.users) do
vRP.varyHunger(v,cfg.hunger_per_minute)
vRP.varyThirst(v,cfg.thirst_per_minute)
end
SetTimeout(60000,task_update)
end
async(function()
task_update()
end)
-- handlers
-- init values
AddEventHandler("vRP:playerJoin",function(user_id,source,name,last_login)
local data = vRP.getUserDataTable(user_id)
if data.hunger == nil then
data.hunger = 0
data.thirst = 0
end
end)
-- add survival progress bars on spawn
AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn)
local data = vRP.getUserDataTable(user_id)
-- disable police
vRPclient._setPolice(source,cfg.police)
-- set friendly fire
vRPclient._setFriendlyFire(source,cfg.pvp)
vRPclient._setProgressBar(source,"vRP:hunger","minimap",htxt,255,153,0,0)
vRPclient._setProgressBar(source,"vRP:thirst","minimap",ttxt,0,125,255,0)
vRP.setHunger(user_id, data.hunger)
vRP.setThirst(user_id, data.thirst)
end)
-- EMERGENCY
---- revive
local revive_seq = {
{"amb@medic@standing@kneel@enter","enter",1},
{"amb@medic@standing@kneel@idle_a","idle_a",1},
{"amb@medic@standing@kneel@exit","exit",1}
}
function vRP.survival_revive_nearest(player)
local user_id = vRP.getUserId(player)
if user_id then
local nplayer = vRPclient.getNearestPlayer(player,10)
local nuser_id = vRP.getUserId(nplayer)
if nuser_id then
if vRPclient.isInComa(nplayer) then
if vRP.tryGetInventoryItem(user_id,"medkit",1,true) then
vRPclient._playAnim(player,false,revive_seq,false) -- anim
SetTimeout(15000, function()
vRPclient._varyHealth(nplayer,50) -- heal 50
end)
end
else
vRPclient._notify(player,lang.emergency.menu.revive.not_in_coma())
end
else
vRPclient._notify(player,lang.common.no_player_near())
end
end
end
|
local L = BigWigs:NewBossLocale("Ancient Protectors", "ptBR")
if not L then return end
if L then
L[83892] = "|cFF00CCFFGola|r"
L[83893] = "|cFF00CC00Telu|r"
L.custom_on_automark = "Marca automaticamente os chefes"
L.custom_on_automark_desc = "Automaticamente marca Gola com {rt8} e Telu com {rt7}, requer promovido ou líder."
end
L = BigWigs:NewBossLocale("Witherbark", "ptBR")
if L then
L.energyStatus = "Um glóbulo alcançou Cascasseca: %d%% energia"
end
|
VFS.Include("LuaGadgets/gadgets.lua",nil, VFS.BASE)
|
--[[------------------------------------------
============================
LAG DETECTION MODULE
============================
Developer informations :
---------------------------------
Used variables :
lagTrigger = { value = 75, desc = "% difference between current lag and average lag."}
lagsCount = { value = 8, desc = "Number of consectuives laggy frames in order to run a cleanup."}
bigLag = { value = 2, desc = "Time (seconds) between 2 frames to trigger a cleanup"}
lagFunc = { value = "cleanUp_unfrozen", desc = "Function ran on lag detected" }
lagFuncTime = { value = 20, desc = "Time (seconds) between 2 cleanup (avoid spam)"}
Ready to hook :
APG_lagDetected = Ran on lag detected by the server.
Example : hook.Add( "APG_lagDetected", "myLagDetectHook", function() print("[APG] Lag detected (printed from my very own hook)") end)
]]--------------------------------------------
local mod = "lag_detection"
local table = table
--[[ Lag fixing functions ]]
local lagFix = {
cleanup_all = function( ) APG.cleanUp( "all" ) end,
cleanup_unfrozen = function( ) APG.cleanUp( "unfrozen" ) end,
ghost_unfrozen = APG.ghostThemAll,
freeze_unfrozen = APG.freezeProps,
smart_cleanup = APG.smartCleanup,
custom_function = APG.customFunc,
}
--[[ Lag detection vars ]]
local lastTick = 0
local tickDelta = 0
local tickRate = 0
local lagCount = 0
local lagThreshold = math.huge
local processHault = false
local processFunc = false
local processExecs = 0
local sampleData = {}
local sampleCount = 0
local function addSample( data )
local index = (sampleCount%66)+1
local data = tonumber(data)
sampleCount = sampleCount + 1
if sampleCount >= 66 then
sampleCount = 0
end
table.insert(sampleData, index, data)
end
function APG.resetLag(dontResetData)
lastTick = 0
tickDelta = 0
lagCount = 0
lagThreshold = tickRate
processHault = false
processFunc = false
processExecs = 0
end
function APG.calculateLagAverage()
local count = 0
local total = 0
local sampleData = sampleData
for _, v in next, sampleData do
total = total + v
count = count + 1
end
if count < 12 then
return false -- Not enough data, yet.
end
return (total/count)
end
hook.Add("Think", "APG_initLagDetection", function()
tickRate = FrameTime()
lagThreshold = tickRate
hook.Remove("Think", "APG_initLagDetection")
end)
APG.timerAdd( mod, "APG_process", 3, 0, function()
if not APG.modules[ mod ] then return end
if sampleCount < 12 or tickDelta < lagThreshold then
addSample(tickDelta)
end
local average = APG.calculateLagAverage()
if average then
lagThreshold = average * ( 1 + ( APG.cfg[ "lagTrigger" ].value / 100 ) )
end
processExecs = 0
end)
APG.hookAdd( mod, "Tick", "APG_lagDetection", function()
if not APG.modules[ mod ] then return end
local sysTime = SysTime()
tickDelta = sysTime - lastTick
if lagThreshold > tickRate and tickDelta >= lagThreshold then
lagCount = lagCount + 1
if (lagCount >= APG.cfg[ "lagsCount" ].value) or ( tickDelta > APG.cfg[ "bigLag" ].value ) then
lagCount = 0
if ( not processHault ) and ( not processFunc ) then
processHault = true
timer.Simple(APG.cfg["lagFuncTime"].value, function()
processHault = false
end)
hook.Run( "APG_lagDetected" )
end
end
else
lagCount = lagCount - 0.5
if lagCount < 0 then
lagCount = 0
end
end
lastTick = sysTime
end)
--[[ Utils ]]
hook.Remove( "APG_lagDetected", "main") -- Sometimes, I dream about cheese.
hook.Add( "APG_lagDetected", "main", function()
if not APG then return end
APG.notify( true, 2, APG.cfg["notifyLevel"].value, "!WARNING LAG DETECTED!" )
local funcName = APG.cfg[ "lagFunc" ].value
local func = lagFix[ funcName ]
if not func then return end
hook.Run("APG_logsLagDetected") -- put it here so it doesn't spam
processFunc = true
func(false, function()
processFunc = false
processExecs = processExecs + 1
end)
if processExecs > 3 then
-- If the lag cleanup process runs more then 3 times in 3 seconds, then
-- reset our data.
APG.resetLag()
end
end)
--[[ Load hooks and timers ]]
APG.updateHooks(mod)
APG.updateTimers(mod)
|
--!strict
-- Streamable
-- Stephen Leitnick
-- March 03, 2021
local Janitor = require(script.Parent.Janitor)
local Signal = require(script.Parent.Signal)
type StreamableWithInstance = {
Instance: Instance?,
[any]: any,
}
--[=[
@within Streamable
@prop Instance Instance
The current instance represented by the Streamable. If this
is being observed, it will always exist. If not currently
being observed, this will be `nil`.
]=]
--[=[
@class Streamable
Watches the existence of an instance within a specific parent.
```lua
local Streamable = require(packages.Streamable).Streamable
```
]=]
local Streamable = {}
Streamable.ClassName = "Streamable"
Streamable.__index = Streamable
function Streamable.new(parent: Instance, childName: string)
local self: StreamableWithInstance = {}
setmetatable(self, Streamable)
self._janitor = Janitor.new()
self._shown = Signal.new(self._janitor)
self._shownJanitor = self._janitor:Add(Janitor.new(), "Destroy")
self.Instance = parent:FindFirstChild(childName)
local function OnInstanceSet()
local instance = self.Instance
if typeof(instance) == "Instance" then
self._shown:Fire(instance, self._shownJanitor)
self._shownJanitor:Connect(instance:GetPropertyChangedSignal("Parent"):Connect(function()
if not instance.Parent then
self._shownJanitor:Cleanup()
end
end), "Disconnect")
self._shownJanitor:Add(function()
if self.Instance == instance then
self.Instance = nil
end
end, true)
end
end
local function OnChildAdded(child: Instance)
if child.Name == childName and not self.Instance then
self.Instance = child
OnInstanceSet()
end
end
self._janitor:Add(parent.ChildAdded:Connect(OnChildAdded), "Disconnect")
if self.Instance then
OnInstanceSet()
end
return self
end
--[=[
@param handler (instance: Instance, trove: Trove) -> nil
@return Connection
Observes the instance. The handler is called anytime the
instance comes into existence, and the trove given is
cleaned up when the instance goes away.
To stop observing, disconnect the returned connection.
]=]
function Streamable:Observe(handler)
if self.Instance then
task.spawn(handler, self.Instance, self._shownJanitor)
end
return self._shown:Connect(handler)
end
--[=[
Destroys the Streamable.
]=]
function Streamable:Destroy()
self._janitor:Destroy()
end
function Streamable:__tostring()
return "Streamable"
end
export type Streamable = typeof(Streamable.new(workspace, "X"))
table.freeze(Streamable)
return Streamable
|
--[[
TheNexusAvenger
Plays a sound for hitting a player.
--]]
local Players = game:GetService("Players")
return function ()
local HitSound = Players.LocalPlayer:FindFirstChild("HitSound")
if not HitSound then
HitSound = Instance.new("Sound")
HitSound.Name = "HitSound"
HitSound.SoundId = "http://www.roblox.com/Asset?ID=95522378"
HitSound.Volume = 1
HitSound.Parent = Players.LocalPlayer
end
HitSound:Play()
end
|
local httpclient = require'http.request'
local monotime = require "cqueues".monotime
local uri_parse = require'uriparse'
local idn = require'idn'
local zlib = require'zlib'
local lconsole = require'logging.console'
local log = lconsole()
-- Change to DEBUG if you want to see full URL fetch log
log:setLevel('INFO')
local function simplehttp(url, callback, unused, limit)
local req_timeout = 60
local uri
if(type(url) == "table") then
uri = url.url or url[1]
else
uri = url
end
-- Don't include fragments in the request.
uri = uri:gsub('#.*$', '')
-- Trim whitespace
uri = uri:gsub('%s+$', '')
uri = uri:gsub('^%s+', '')
-- IDN hack for now, until http/uriparse supports it
uri = uri:gsub('://(.-)%.', function(match)
if match:sub(1,1) ~= '[' then
match = idn.encode(match)
end
return '://'..match..'.'
end, 1)
log:debug('simplehttp> request <%s>', uri)
local uri_t = uri_parse(uri)
local client = httpclient.new_from_uri(uri_t)
-- Allow override of client HTTP version
if url.version then
client.version = url.version
end
-- Allow client to overide request timeout, note that this isn't super precise because we reuse the same timeout for reading headers and such
if client.timeout then
req_timeout = client.timeout
end
if(type(url) == "table") then
if(url.headers) then
for k, v in next, url.headers do
-- Overwrite any existing
client.headers:upsert(k, v)
end
end
if(url.method) then
client.headers:upsert(":method", url.method)
end
if(url.data) then
client:set_body(url.data)
end
end
local data
local status_code
local before = monotime()
local headers, stream = client:go(req_timeout)
local after = monotime()
if not headers then
log:error('simplehttp> request %s, error :%s. After %s', uri, stream, (after-before))
return nil, stream
end
status_code = headers:get(':status')
-- H2 might not be number
status_code = tonumber(status_code, 10) or status_code
local simple_headers = {}
for k,v in headers:each() do
-- Will overwrite duplicate headers.
simple_headers[k] = v
end
if stream then
if(limit) then
data = stream:get_body_chars(limit, req_timeout)
else
data = stream:get_body_as_string(req_timeout)
end
-- Stream shutdown lets luahttp reuse I'm told
stream:shutdown()
if simple_headers['content-encoding'] == 'gzip' then
data = zlib.inflate()(data)
end
end
local response = {
headers = simple_headers,
version = stream.connection.version,
status_code = status_code -- for compability with old simplehttp API
}
-- Old style callback
if callback then
callback(data, uri, response)
end
-- New style.
return data, uri, response
end
return simplehttp
|
cc = cc or {}
---FlipX object
---@class FlipX : ActionInstant
local FlipX = {}
cc.FlipX = FlipX
--------------------------------
--- init the action
---@param x bool
---@return bool
function FlipX:initWithFlipX(x) end
--------------------------------
--- Create the action.<br>
---param x Flips the sprite horizontally if true.<br>
---return An autoreleased FlipX object.
---@param x bool
---@return FlipX
function FlipX:create(x) end
--------------------------------
--
---@return FlipX
function FlipX:clone() end
--------------------------------
---param time In seconds.
---@param time float
---@return FlipX
function FlipX:update(time) end
--------------------------------
--
---@return FlipX
function FlipX:reverse() end
--------------------------------
--
---@return FlipX
function FlipX:FlipX() end
return FlipX
|
local devmode = settings.startup["durni:startup:dev-mode"].value
local recipe = {
type = "recipe",
name = "durni:compressed-air-pipe",
result = "durni:compressed-air-pipe",
ingredients = {
{"copper-plate", 1}
},
enabled = devmode
}
data:extend {recipe}
|
slot0 = class("CatteryStyleCard")
slot0.Ctor = function (slot0, slot1)
slot0._go = slot1
slot0._tf = slot1.transform
slot0.styleIcon = slot0._tf:Find("mask/icon"):GetComponent(typeof(Image))
slot0.lockTF = findTF(slot0._tf, "lock")
slot0.mark = findTF(slot0._tf, "mark")
end
slot0.Update = function (slot0, slot1, slot2)
slot0.style = slot1
slot0.styleIcon.sprite = GetSpriteFromAtlas("CatteryStyle/" .. slot1:getConfig("name"), "")
setActive(slot0.lockTF, not slot1:IsOwn())
setActive(slot0.mark, slot2)
end
slot0.Dispose = function (slot0)
return
end
return slot0
|
--[[
Vote Panel
------------------------------------------------------------------------------
--]]
local panel = {}
--panel settings
panel.Name = "vote"
panel.Settings = {
CenterHorizontally = "center_horizontally",
}
--[[
Create vote panel
--]]
function panel:Init()
self:BaseInit({
Padding = true,
Declare = {
Vote = {}
},
Locked = true
})
if (self.Settings.CenterHorizontally.Value) then
self:SetPos(ScrW() / 2 - ( self:GetWidth() / 2 ), self.Settings.Position.Value.Y )
else
self:SetPos(self.Settings.Position.Value.X, self.Settings.Position.Value.Y)
end
self.Type = vgui.Create("DLabel", self )
self.Type:Dock(TOP)
self.Type:SetFont("BigText")
self.Type:SetText("Unknown Vote (0)")
self.Type:SetTextColor(self.Settings.Colours.Value.TextColor)
self.Type:SizeToContents()
self.VOwner = vgui.Create("DLabel", self )
self.VOwner:Dock(LEFT)
self.VOwner:SizeToContents()
self.VOwner:SetText("Penisman")
self.VOwner:SetTextColor(self.Settings.Colours.Value.TextColor)
end
function panel:Paint(p)
surface.SetDrawColor(self.Settings.Colours.Value.Background)
surface.DrawRect(0, 0, self:GetWide(), self:GetTall())
surface.SetDrawColor(self.Settings.Colours.Value.Border)
surface.DrawOutlinedRect(0, 0, self:GetWide(), self:GetTall(), self.Settings.Options.Value.BorderThickness)
if (self.Vote and !table.IsEmpty(self.Vote) and self.Vote.StartTime ) then
local time = CurTime() - self.Vote.StartTime
local mins = math.floor(time / 60)
local seconds = math.floor(time - (mins * 60))
if (seconds < 10) then
seconds = "0" .. seconds
end
local str = mins .. ":" .. seconds
local w = surface.GetTextSize(str)
draw.SimpleTextOutlined(str, "MediumText", self:GetWide() - w - 10 , self:GetTall() - 45, LydsPlayer.Colours.White, 10, 1, 0.5, LydsPlayer.Colours.Black )
surface.SetDrawColor(self.Settings.Colours.Value.LoadingBarBackground )
surface.DrawRect( 0, 0, math.Clamp( ( self:GetWide() / self.Vote.Time ) * time , 5, self:GetWide() ), self.Settings.Size.Value.LoadingBarHeight)
end
end
--think
function panel:MyThink()
if (self:HasResized()) then
self.Type:SetWide(self:GetWidth())
self.VOwner:SetWide(self:GetWidth())
end
end
--[[
--]]
function panel:Reset()
self.Vote = nil
self.Type:SetText("Unknown Vote (0)")
self.VOwner:SetText("Penisman")
end
--[[
Sets the vote
--]]
function panel:SetVote(vote)
self.Vote = vote
self.Type:SetText(vote.Type .. " (" .. vote.Count .. "/" .. vote.Required .. ")")
self.VOwner:SetText(vote.Owner.Name)
end
--Register
vgui.Register("LydsPlayer.VotePanel", panel, "LydsPlayer.BasePanel")
|
surface.CreateFont("HUDNumber5", {font = "Trebuchet MS", size = 45, weight = 900});
include ("shared.lua");
function ENT:Initialize()
self.m_iLastSpark = CurTime();
self.m_iNextSparkTime = 0;
end
function ENT:Draw()
self:DrawModel();
local pos = self:LocalToWorld(self:OBBCenter());
local ang = self:GetAngles();
ang:RotateAroundAxis(ang:Forward(), 90);
ang:RotateAroundAxis(ang:Right(), -90);
local owner = IsValid(self:Getowning_ent()) && self:Getowning_ent():Nick() .. "'s " || "";
cam.Start3D2D(pos + ang:Right() * -47 + ang:Up() * 8.5, ang, 0.15);
draw.SimpleTextOutlined(owner .. "Attachment Vendor", "HUDNumber5", 0, 0, color_white, draw.TEXT_ALIGN_CENTER, draw.TEXT_ALIGN_CENTER, 1, color_black);
cam.End3D2D();
ang:RotateAroundAxis(ang:Forward(), -90);
ang:RotateAroundAxis(ang:Right(), -90);
cam.Start3D2D(pos + ang:Up() * 13, ang, 0.22);
draw.SimpleText(owner .. "Attachment Vendor", "HUDNumber5", 0, 0, color_white, draw.TEXT_ALIGN_CENTER, draw.TEXT_ALIGN_CENTER);
cam.End3D2D();
ang:RotateAroundAxis(ang:Forward(), 180);
cam.Start3D2D(pos + ang:Up() * 13.5, ang, 0.22);
draw.SimpleText(owner .. "Attachment Vendor", "HUDNumber5", 0, 0, color_white, draw.TEXT_ALIGN_CENTER, draw.TEXT_ALIGN_CENTER);
cam.End3D2D();
end
function ENT:Think()
if (self:Getdamaged() == false || CurTime() < self.m_iLastSpark + self.m_iNextSparkTime) then return; end
local ed = EffectData();
ed:SetOrigin(self:LocalToWorld(self:OBBCenter()));
util.Effect("cball_bounce", ed);
self:EmitSound("ambient.electrical_zap_" .. math.random(1, 3));
self.m_iLastSpark = CurTime();
self.m_iNextSparkTime = math.random(1, 5);
end
|
CustomizableWeaponry:addFireSound("CW_TMG_FIRE", "weapons/tmg/tmg_1.wav", 1, 50, CHAN_STATIC)
CustomizableWeaponry:addReloadSound("CW_TMG_MAGOUT", "weapons/tmg/tmg_magout.mp3")
CustomizableWeaponry:addReloadSound("CW_TMG_MAGIN", "weapons/tmg/tmg_magin.mp3")
CustomizableWeaponry:addReloadSound("CW_TMG_BOLTCOCK", "weapons/tmg/tmg_cock.mp3")
CustomizableWeaponry:addReloadSound("CW_TMG_BOLTBACK", "weapons/tmg/tmg_unlock.mp3")
|
package.path = "../../?.lua;" .. package.path
function love.conf(t)
io.stdout:setvbuf('no')
t.version = '11.2'
t.console = false
t.window.title = 'Modern Examples - Love2D'
t.window.x = 25
t.window.y = 25
t.window.width = 500
t.window.height = 500
t.window.fullscreen = false
end
|
local K, C, L, _ = select(2, ...):unpack()
if C["Aura"].cast_by ~= true then return end
local format = string.format
local select = select
local pairs = pairs
local match = string.match
local GetUnitName = GetUnitName
local hooksecurefunc = hooksecurefunc
local UnitClass = UnitClass
local CUSTOM_CLASS_COLORS = CUSTOM_CLASS_COLORS
local RAID_CLASS_COLORS = RAID_CLASS_COLORS
local UnitIsPlayer = UnitIsPlayer
local UnitReaction = UnitReaction
-- Tells you who cast a buff or debuff in its tooltip(prButler by Renstrom)
local function addAuraSource(self, func, unit, index, filter)
local srcUnit = select(8, func(unit, index, filter))
if srcUnit then
local src = GetUnitName(srcUnit, true)
if srcUnit == "pet" or srcUnit == "vehicle" then
src = format("%s (|cff%02x%02x%02x%s|r)", src, K.Color.r * 255, K.Color.g * 255, K.Color.b * 255, GetUnitName("player", true))
else
local partypet = srcUnit:match("^partypet(%d+)$")
local raidpet = srcUnit:match("^raidpet(%d+)$")
if partypet then
src = format("%s (%s)", src, GetUnitName("party"..partypet, true))
elseif raidpet then
src = format("%s (%s)", src, GetUnitName("raid"..raidpet, true))
end
end
if UnitIsPlayer(srcUnit) then
local color = (CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS)[select(2, UnitClass(srcUnit))]
if color then
src = format("|cff%02x%02x%02x%s|r", color.r * 255, color.g * 255, color.b * 255, src)
end
else
local color = BETTER_FACTION_BAR_COLORS[UnitReaction(srcUnit, "player")]
if color then
src = format("|cff%02x%02x%02x%s|r", color.r * 255, color.g * 255, color.b * 255, src)
end
end
self:AddLine(DONE_BY.." "..src)
self:Show()
end
end
local funcs = {
SetUnitAura = UnitAura,
SetUnitBuff = UnitBuff,
SetUnitDebuff = UnitDebuff,
}
for k, v in pairs(funcs) do
hooksecurefunc(GameTooltip, k, function(self, unit, index, filter)
addAuraSource(self, v, unit, index, filter)
end)
end
|
local events = require('core').Emitter
local initialized = false
local connections = {
onConnect = nil,
onDisconnect = nil,
onMessage = nil,
onListen = nil,
emit = function (self, ...)
events:emit(...)
end,
sendAll = function (self, data)
error("Websocket is not initialized")
end,
disconnect = function (self)
error('Websocket is not initialized')
end
}
setmetatable(connections, {
__index = function (self, key)
if (not initialized and key == "initialize") then
return function ()
initialized = true
end
end
return rawget(self, key)
end,
__newindex = function (self, key, value)
if (initialized and (tostring(key) == "send" or tostring(key) == "disconnect")) then
return nil
end
return rawset(self, key, value)
end
})
events:on("serverListen", function(...)
if (type(connections.onListen) == "function") then
coroutine.wrap(connections.onListen)(connections, ...)
end
end)
events:on("serverConnect", function(...)
if (type(connections.onConnect) == "function") then
coroutine.wrap(connections.onConnect)(connections, ...)
end
end)
events:on("serverDisconnect", function(...)
if (type(connections.onDisconnect) == "function") then
coroutine.wrap(connections.onDisconnect)(connections, ...)
end
end)
events:on("serverMessage", function(...)
if (type(connections.onMessage) == "function") then
coroutine.wrap(connections.onMessage)(connections, ...)
end
end)
return connections
|
NOMSU_VERSION = {
7,
0,
1
}
local clibtype = package.cpath:match("?%.(so)") or package.cpath:match("?%.(dll)")
if NOMSU_PREFIX then
package.path = tostring(NOMSU_PREFIX) .. "/share/nomsu/" .. tostring(table.concat(NOMSU_VERSION, ".")) .. "/?.lua;" .. package.path
package.cpath = tostring(NOMSU_PREFIX) .. "/lib/nomsu/" .. tostring(table.concat(NOMSU_VERSION, ".")) .. "/?." .. tostring(clibtype) .. ";" .. package.cpath
end
COLOR_ENABLED = true
if clibtype == "dll" then
local ok, enable_colors = pcall(require, 'wincolors')
COLOR_ENABLED = false
if ok then
local _
ok, _ = pcall(enable_colors)
if ok then
COLOR_ENABLED = false
end
end
pcall(os.execute, "chcp 65001>nul")
end
local List, Dict
do
local _obj_0 = require('containers')
List, Dict = _obj_0.List, _obj_0.Dict
end
NOMSU_VERSION = List(NOMSU_VERSION)
local Text = require('text')
require('builtin_metatables')
local EXIT_FAILURE = 1
local EXIT_SUCCESS = 0
local usage = [=[Nomsu Usage: nomsu [-V version] [--help | -h] [--version] [-O optimization level] [-v] [-c] [-s] [-d debugger] [--no-core] [(file | -t tool | -e "nomsu code..." | files... -- ) [nomsu args...]]
OPTIONS
-t <tool> Run a tool.
-e Execute the specified string.
-O <level> Run the compiler with the given optimization level (>0: use precompiled .lua versions of Nomsu files, when available).
-v Verbose: print compiled lua code.
-c Compile the input files into a .lua files.
-s Check the input files for syntax errors.
-d <debugger> Attempt to use the specified debugger to wrap the main body of execution.
-h/--help Print this message.
--version Print the version number and exit.
--no-core Skip loading the Nomsu core by default.
-V specify which Nomsu version is desired.
<file> The Nomsu file to run (can be "-" to use stdin).
]=]
local ok, _ = pcall(function()
lpeg = require('lpeg')
re = require('re')
end)
if not ok then
print("Error: unable to find the 'lpeg' Lua module. Please install LPEG either from http://www.inf.puc-rio.br/~roberto/lpeg/re.html or, if you use luarocks: `luarocks install lpeg`")
os.exit(EXIT_FAILURE)
end
local Files = require("files")
local NomsuCode, LuaCode, Source
do
local _obj_0 = require("code_obj")
NomsuCode, LuaCode, Source = _obj_0.NomsuCode, _obj_0.LuaCode, _obj_0.Source
end
local sep = "\3"
local parser = re.compile([[ args <- {| (flag %sep)*
{:files: {|
( ("-m" %sep)? (file %sep)+ "--" %sep
/ file %sep
/ {~ '' %sep? -> 'nomsu://tools/repl.nom' ~}) |} :}
{:nomsu_args: {| (nomsu_flag %sep)* {:extras: {| ({[^%sep]+} %sep)* |} :} |} :}
|} ({.+}?)
file <-
( "-e" %sep ({[^%sep]+} -> spoof)
/ "-t" %sep {~ {[^%sep]+} -> "nomsu://tools/%1.nom" ~}
/ !"--" {[^%sep]+})
flag <- longflag / shortflag / "-" shortboolflag+
longflag <-
{:help: "--help" %true :}
/ {:version: "--version" %true :}
/ {:no_core: "--no-core" %true :}
shortflag <-
{:optimization: "-O" %sep? %number :}
/ {:debugger: ("-d" %sep? {[^%sep]+}) :}
/ {:requested_version: "-V" %sep? {([0-9.])+} :}
shortboolflag <-
{:check_syntax: "s" %true:}
/ {:compile: "c" %true:}
/ {:verbose: "v" %true :}
/ {:help: "h" %true :}
nomsu_flag <- nomsu_longflag / "-" nomsu_shortboolflag+
nomsu_shortboolflag <- {| {:key: [a-zA-Z] :} {:value: %true :} |}
nomsu_longflag <- '--' {| {:key: [^%sep=]+ :} {:value: ('=' {[^%sep]+}) / %true :} |}
]], {
["true"] = lpeg.Cc(true),
number = lpeg.R("09") ^ 1 / tonumber,
sep = lpeg.P(sep),
spoof = Files.spoof
})
local arg_string = table.concat(arg, sep) .. sep
local args, err = parser:match(arg_string)
if not args or err then
if err then
print("Didn't understand: " .. tostring(err))
end
print(usage)
os.exit(EXIT_FAILURE)
end
if args.help then
print("Nomsu - A dynamically typed programming language with natural syntax and strong metaprogramming abilities.")
print("https://nomsu.org\n")
print(usage)
os.exit(EXIT_SUCCESS)
end
if args.version then
print(NOMSU_VERSION:joined_with("."))
os.exit(EXIT_SUCCESS)
end
local nomsu_args = Dict({ })
local _list_0 = args.nomsu_args
for _index_0 = 1, #_list_0 do
local argpair = _list_0[_index_0]
nomsu_args[argpair.key] = argpair.value
end
nomsu_args.extras = List(args.nomsu_args.extras or { })
local optimization = tonumber(args.optimization or 1)
local nomsupath = { }
local suffixes
if optimization > 0 then
suffixes = {
"?.lua",
"?/init.lua",
"?.nom",
"?/init.nom"
}
else
suffixes = {
"?.nom",
"?/init.nom"
}
end
local add_path
add_path = function(p)
for _index_0 = 1, #suffixes do
local s = suffixes[_index_0]
table.insert(nomsupath, p .. "/" .. s)
end
end
if NOMSU_PREFIX then
add_path(tostring(NOMSU_PREFIX) .. "/share/nomsu/" .. tostring(NOMSU_VERSION:joined_with(".")) .. "/lib")
else
add_path("./lib")
end
local NOMSU_PACKAGEPATH = NOMSU_PACKAGEPATH or "/opt/nomsu"
add_path(NOMSU_PACKAGEPATH)
add_path(".")
package.nomsupath = table.concat(nomsupath, ";")
package.nomsuloaded = Dict({ })
local nomsu_environment = require('nomsu_environment')
nomsu_environment.NOMSU_VERSION = NOMSU_VERSION
nomsu_environment.COMMAND_LINE_ARGS = nomsu_args
nomsu_environment.OPTIMIZATION = optimization
nomsu_environment.NOMSU_PACKAGEPATH = NOMSU_PACKAGEPATH
nomsu_environment.NOMSU_PREFIX = NOMSU_PREFIX
nomsu_environment.COLOR_ENABLED = COLOR_ENABLED
local run
run = function()
if not (args.no_core) then
nomsu_environment:export("core")
end
local input_files = { }
if args.files and #args.files > 0 then
local _list_1 = args.files
for _index_0 = 1, #_list_1 do
local f = _list_1[_index_0]
do
local nomsu_name = f:match("^nomsu://(.*)%.nom")
if nomsu_name then
local path
path, err = package.searchpath(nomsu_name, package.nomsupath, "/")
if not path then
error(err)
end
table.insert(input_files, path)
else
table.insert(input_files, f)
end
end
end
end
for _index_0 = 1, #input_files do
local filename = input_files[_index_0]
if args.check_syntax then
local code = Files.read(filename)
local source = Source(filename, 1, #code)
nomsu_environment._1_parsed(NomsuCode:from(source, code))
print("Parse succeeded: " .. tostring(filename))
elseif args.compile then
local code = Files.read(filename)
if not code then
error("Could not find file '" .. tostring(filename) .. "'")
end
if filename:match("%.lua$") then
error("Cannot compile a lua file (expected a nomsu file as input)")
end
local output
if filename == 'stdin' then
output = io.output()
else
output = io.open(filename:gsub("%.nom$", ".lua"), "w")
end
local source = Source(filename, 1, #code)
code = NomsuCode:from(source, code)
local env = nomsu_environment.new_environment()
env.MODULE_NAME = filename
local tree = env._1_parsed(code)
if tree.shebang then
output:write(tree.shebang)
end
if not (tree.type == 'FileChunks') then
tree = {
tree
}
end
for chunk_no, chunk in ipairs(tree) do
local lua = env:compile(chunk)
lua:declare_locals()
lua:prepend((chunk_no > 1) and '\n' or '', "-- File " .. tostring(filename) .. " chunk #" .. tostring(chunk_no) .. "\n")
if args.verbose then
print(lua:text())
end
env:run(chunk)
output:write(lua:text(), "\n")
end
print(("Compiled %-25s -> %s"):format(filename, filename:gsub("%.nom$", ".lua")))
output:close()
elseif args.verbose then
local env = nomsu_environment.new_environment()
env.MODULE_NAME = filename
env.WAS_RUN_DIRECTLY = true
local code = Files.read(filename)
local source = Source(filename, 1, #code)
if filename:match("%.lua$") then
code = LuaCode:from(Source(filename, 1, #code), code)
print(code:text())
env:run(code)
else
code = NomsuCode:from(source, code)
local tree = env._1_parsed(code)
if not (tree.type == 'FileChunks') then
tree = {
tree
}
end
for chunk_no, chunk in ipairs(tree) do
local lua = env:compile(chunk)
lua:declare_locals()
lua:prepend((chunk_no > 1) and '\n' or '', "-- File " .. tostring(filename) .. " chunk #" .. tostring(chunk_no) .. "\n")
print(lua:text())
env:run(lua)
end
end
else
local f = Files.read(filename)
if not f then
if filename:match("^-") then
print("Not a valid flag: " .. filename .. "\n")
print(usage)
else
print("File not found: " .. filename)
end
os.exit(EXIT_FAILURE)
end
if filename:match("%.lua$") then
f = LuaCode:from(Source(filename, 1, #f), f)
end
local env = nomsu_environment.new_environment()
env.MODULE_NAME = filename
env.WAS_RUN_DIRECTLY = true
env:run(f)
end
end
end
local debugger
if args.debugger == "nil" then
debugger = { }
else
debugger = require(args.debugger or 'error_handling')
end
local guard
if type(debugger) == 'function' then
guard = debugger
else
guard = debugger.guard or debugger.call or debugger.wrap or debugger.run or (function(fn)
return fn()
end)
end
return guard(run)
|
------------------------CREDITS------------------------
-------- Script made by Vlad, DevStudios Owner --------
-- Script made for StreamForce Romania RP --
-- Site: https://devstudios.store --
-- Forum: http://forum.devstudios.store --
-- Copyright 2019 ©DevStudios. All rights served --
-------------------------------------------------------
description "vRP_Discord"
dependency "vrp"
server_scripts{
"@vrp/lib/utils.lua",
"server.lua"
}
client_script {
"client.lua"
}
|
Object = {
x = 0,
y = 0,
width = 0,
height = 0
}
function Object:new(x,y,width,height)
obj = {}
obj.x = x
obj.y = y
obj.width = width
obj.height = height
return obj
end
function Object:draw(obj)
x, y, width, height
print(x,y,width,height)
end
Object:new(50,50,20,20)
function love.update()
Object:draw(50,50,20,20)
end
function love.draw()
end
function love.mousemoved()
end
function love.mousepressed()
end
function love.keypressed()
end
|
-- ./skynet /mnt/e/Code/CVIP/code/skynet/test.conf
local skynet = require "skynet"
local socket = require "skynet.socket"
local function event_loop(clientfd)
while true do
local data = socket.readline(clientfd)--从网络获取 以\n为分隔符的数据包
if not data then
return
end
print(clientfd, "recv:", data)
socket.write(clientfd, data.."\n")
end
end
local function accept(clientfd, addr)-- 回调函数的作用 就是可以将 fd绑定到其他actor
print("accept a connect:", clientfd, addr)
socket.start(clientfd) -- 将clientfd注册到epoll
skynet.fork(event_loop, clientfd) -- 实现一个简单的echo服务,可以通过 telnet 127.0.0.1 8001来连接skynet
end
skynet.start(function ()
local listenfd = socket.listen("0.0.0.0", 8001) -- socket bind listen
socket.start(listenfd, accept) -- 将listenfd注册到epoll,收到连接会回调accept函数
-- skynet.fork(function ()
-- local connfd = socket.open("127.0.0.1", 6379)-- skynet作为客户端连接 redis-server;连接成功 fd 注册到epoll
-- if not connfd then
-- print("网络连接失败")
-- return
-- end
-- socket.write(connfd, "*1\r\n$4\r\nPING\r\n")--这里实现了一个简单的ping pong
-- local data = socket.readline(connfd, "\r\n")
-- print("recv redis-server data:", data)
-- end)
end)
|
local wibox = require("wibox")
local awful = require("awful")
local button = require("utils.button")
local font = require("utils.font")
local shape = require("gears.shape")
local surface = require("gears.surface")
local noti = require("utils.noti")
local progressbar = require("utils.progressbar")
local helpers = require("helpers")
local music_root = class()
function music_root:init()
self.title = font.body_1('')
self.artist = font.body_2('')
self.progress = progressbar.horiz()
self.cover = wibox.widget {
resize = true,
widget = wibox.widget.imagebox
}
self.w = button({
fg_icon = M.x.secondary,
icon = font.icon(""),
layout = "horizontal"
})
self:gen_popup()
self:signals()
end
function music_root:gen_popup()
self.w = wibox.widget {
{
{
self.progress,
layout = wibox.layout.fixed.vertical
},
{
{
self.cover,
{
self.title,
forced_height = dpi(30),
widget = wibox.container.margin
},
{
self.artist,
forced_height = dpi(30),
left = dpi(7),
right = dpi(7),
widget = wibox.container.margin
},
spacing = dpi(5),
layout = wibox.layout.fixed.vertical
},
margins = dpi(8),
widget = wibox.container.margin
},
{
nil,
require("widgets.mpc")({ mode = 'titlebar' }),
expand = "none",
layout = wibox.layout.align.horizontal
},
expand = "none",
forced_height = dpi(480),
--forced_width = dpi(200),
layout = wibox.layout.align.vertical
},
shape = helpers.rrect(20),
bg = M.x.on_surface .. M.e.dp01,
widget = wibox.container.background
}
end
function music_root:signals()
awesome.connect_signal("daemon::mpd_infos", function(title, artist)
self.title.text = title or ''
if not (artist == nil or artist == '') then
self.artist.text = "by " .. artist
else
self.artist.text = artist
end
end)
awesome.connect_signal("daemon::mpd_cover", function(cover)
--noti.info('in signal cover ' .. cover)
--self.cover:set_image(cover)
--self.cover:emit_signal("widget::redraw_needed")
--self.cover:emit_signal("widget::layout_changed")
self.cover:set_image(cover)
end)
awesome.connect_signal("daemon::mpd_time", function(time)
self.progress:set_value(time)
end)
end
local music_widget = class(music_root)
function music_widget:init()
music_root.init(self)
return self.w
end
return music_widget
|
local structure = FindInTable(StructureSpawnerManager.StructureCategories, "category", "tent")
structure.abandonedTimer = 2630000 -- 1 month
|
---@class love.filesystem
---Provides an interface to the user's filesystem.
local m = {}
--region File
---@class File
---Represents a file on the filesystem. A function that takes a file path can also take a File.
local File = {}
---Closes a File.
---@return boolean
function File:close() end
---Flushes any buffered written data in the file to the disk.
---@return boolean, string
function File:flush() end
---Gets the buffer mode of a file.
---@return BufferMode, number
function File:getBuffer() end
---Gets the filename that the File object was created with. If the file object originated from the love.filedropped callback, the filename will be the full platform-dependent file path.
---@return string
function File:getFilename() end
---Gets the FileMode the file has been opened with.
---@return FileMode
function File:getMode() end
---Returns the file size.
---@return number
function File:getSize() end
---Gets whether end-of-file has been reached.
---@return boolean
function File:isEOF() end
---Gets whether the file is open.
---@return boolean
function File:isOpen() end
---Iterate over all the lines in a file.
---@return function
function File:lines() end
---Open the file for write, read or append.
---@param mode FileMode @The mode to open the file in.
---@return boolean, string
function File:open(mode) end
---Read a number of bytes from a file.
---@param bytes number @The number of bytes to read.
---@return string, number
---@overload fun(container:ContainerType, bytes:number):value, number
function File:read(bytes) end
---Seek to a position in a file
---@param pos number @The position to seek to
---@return boolean
function File:seek(pos) end
---Sets the buffer mode for a file opened for writing or appending. Files with buffering enabled will not write data to the disk until the buffer size limit is reached, depending on the buffer mode.
---
---File:flush will force any buffered data to be written to the disk.
---@param mode BufferMode @The buffer mode to use.
---@param size number @The maximum size in bytes of the file's buffer.
---@return boolean, string
function File:setBuffer(mode, size) end
---Returns the position in the file.
---@return number
function File:tell() end
---Write data to a file.
---@param data string @The string data to write.
---@param size number @How many bytes to write.
---@return boolean, string
---@overload fun(data:Data, size:number):boolean, string
function File:write(data, size) end
--endregion File
--region FileData
---@class FileData
---Data representing the contents of a file.
local FileData = {}
---Gets the extension of the FileData.
---@return string
function FileData:getExtension() end
---Gets the filename of the FileData.
---@return string
function FileData:getFilename() end
--endregion FileData
---Buffer modes for File objects.
BufferMode = {
---No buffering. The result of write and append operations appears immediately.
['none'] = 1,
---Line buffering. Write and append operations are buffered until a newline is output or the buffer size limit is reached.
['line'] = 2,
---Full buffering. Write and append operations are always buffered until the buffer size limit is reached.
['full'] = 3,
}
---How to decode a given FileData.
FileDecoder = {
---The data is unencoded.
['file'] = 1,
---The data is base64-encoded.
['base64'] = 2,
}
---The different modes you can open a File in.
FileMode = {
---Open a file for read.
['r'] = 1,
---Open a file for write.
['w'] = 2,
---Open a file for append.
['a'] = 3,
---Do not open a file (represents a closed file.)
['c'] = 4,
}
---The type of a file.
FileType = {
---Regular file.
['file'] = 1,
---Directory.
['directory'] = 2,
---Symbolic link.
['symlink'] = 3,
---Something completely different like a device.
['other'] = 4,
}
---Append data to an existing file.
---@param name string @The name (and path) of the file.
---@param data string @The string data to append to the file.
---@param size number @How many bytes to write.
---@return boolean, string
---@overload fun(name:string, data:Data, size:number):boolean, string
function m.append(name, data, size) end
---Gets whether love.filesystem follows symbolic links.
---@return boolean
function m.areSymlinksEnabled() end
---Recursively creates a directory.
---
---When called with 'a/b' it creates both 'a' and 'a/b', if they don't exist already.
---@param name string @The directory to create.
---@return boolean
function m.createDirectory(name) end
---Returns the application data directory (could be the same as getUserDirectory)
---@return string
function m.getAppdataDirectory() end
---Gets the filesystem paths that will be searched for c libraries when require is called.
---
---The paths string returned by this function is a sequence of path templates separated by semicolons. The argument passed to ''require'' will be inserted in place of any question mark ('?') character in each template (after the dot characters in the argument passed to ''require'' are replaced by directory separators.) Additionally, any occurrence of a double question mark ('??') will be replaced by the name passed to require and the default library extension for the platform.
---
---The paths are relative to the game's source and save directories, as well as any paths mounted with love.filesystem.mount.
---@return string
function m.getCRequirePath() end
---Returns a table with the names of files and subdirectories in the specified path. The table is not sorted in any way; the order is undefined.
---
---If the path passed to the function exists in the game and the save directory, it will list the files and directories from both places.
---@param dir string @The directory.
---@return table
---@overload fun(dir:string, callback:function):table
function m.getDirectoryItems(dir) end
---Gets the write directory name for your game.
---
---Note that this only returns the name of the folder to store your files in, not the full path.
---@return string
function m.getIdentity() end
---Gets information about the specified file or directory.
---@param path string @The file or directory path to check.
---@param filtertype FileType @If supplied, this parameter causes getInfo to only return the info table if the item at the given path matches the specified file type.
---@return table
---@overload fun(path:string, info:table):table
---@overload fun(path:string, filtertype:FileType, info:table):table
function m.getInfo(path, filtertype) end
---Gets the platform-specific absolute path of the directory containing a filepath.
---
---This can be used to determine whether a file is inside the save directory or the game's source .love.
---@param filepath string @The filepath to get the directory of.
---@return string
function m.getRealDirectory(filepath) end
---Gets the filesystem paths that will be searched when require is called.
---
---The paths string returned by this function is a sequence of path templates separated by semicolons. The argument passed to ''require'' will be inserted in place of any question mark ('?') character in each template (after the dot characters in the argument passed to ''require'' are replaced by directory separators.)
---
---The paths are relative to the game's source and save directories, as well as any paths mounted with love.filesystem.mount.
---@return string
function m.getRequirePath() end
---Gets the full path to the designated save directory.
---
---This can be useful if you want to use the standard io library (or something else) to
---
---read or write in the save directory.
---@return string
function m.getSaveDirectory() end
---Returns the full path to the the .love file or directory. If the game is fused to the LÖVE executable, then the executable is returned.
---@return string
function m.getSource() end
---Returns the full path to the directory containing the .love file. If the game is fused to the LÖVE executable, then the directory containing the executable is returned.
---
---If love.filesystem.isFused is true, the path returned by this function can be passed to love.filesystem.mount, which will make the directory containing the main game (e.g. C:\Program Files\coolgame\) readable by love.filesystem.
---@return string
function m.getSourceBaseDirectory() end
---Returns the path of the user's directory
---@return string
function m.getUserDirectory() end
---Gets the current working directory.
---@return string
function m.getWorkingDirectory() end
---Initializes love.filesystem, will be called internally, so should not be used explicitly.
---@param appname string @The name of the application binary, typically love.
function m.init(appname) end
---Gets whether the game is in fused mode or not.
---
---If a game is in fused mode, its save directory will be directly in the Appdata directory instead of Appdata/LOVE/. The game will also be able to load C Lua dynamic libraries which are located in the save directory.
---
---A game is in fused mode if the source .love has been fused to the executable (see Game Distribution), or if '--fused' has been given as a command-line argument when starting the game.
---@return boolean
function m.isFused() end
---Iterate over the lines in a file.
---@param name string @The name (and path) of the file
---@return function
function m.lines(name) end
---Loads a Lua file (but does not run it).
---@param name string @The name (and path) of the file.
---@return function, string
function m.load(name) end
---Mounts a zip file or folder in the game's save directory for reading.
---
---It is also possible to mount love.filesystem.getSourceBaseDirectory if the game is in fused mode.
---@param archive string @The folder or zip file in the game's save directory to mount.
---@param mountpoint string @The new path the archive will be mounted to.
---@param appendToPath boolean @Whether the archive will be searched when reading a filepath before or after already-mounted archives. This includes the game's source and save directories.
---@return boolean
---@overload fun(filedata:FileData, mountpoint:string, appendToPath:boolean):boolean
---@overload fun(data:Data, archivename:string, mountpoint:string, appendToPath:boolean):boolean
function m.mount(archive, mountpoint, appendToPath) end
---Creates a new File object.
---
---It needs to be opened before it can be accessed.
---@param filename string @The filename of the file.
---@return File
---@overload fun(filename:string, mode:FileMode):File, string
function m.newFile(filename) end
---Creates a new FileData object.
---@param contents string @The contents of the file.
---@param name string @The name of the file.
---@return FileData
---@overload fun(filepath:string):FileData, string
function m.newFileData(contents, name) end
---Read the contents of a file.
---@param name string @The name (and path) of the file.
---@param size number @How many bytes to read.
---@return string, number, nil, string
---@overload fun(container:ContainerType, name:string, size:number):value, number, nil, string
function m.read(name, size) end
---Removes a file or empty directory.
---@param name string @The file or directory to remove.
---@return boolean
function m.remove(name) end
---Sets the filesystem paths that will be searched for c libraries when require is called.
---
---The paths string returned by this function is a sequence of path templates separated by semicolons. The argument passed to ''require'' will be inserted in place of any question mark ('?') character in each template (after the dot characters in the argument passed to ''require'' are replaced by directory separators.) Additionally, any occurrence of a double question mark ('??') will be replaced by the name passed to require and the default library extension for the platform.
---
---The paths are relative to the game's source and save directories, as well as any paths mounted with love.filesystem.mount.
---@param paths string @The paths that the ''require'' function will check in love's filesystem.
function m.setCRequirePath(paths) end
---Sets the write directory for your game.
---
---Note that you can only set the name of the folder to store your files in, not the location.
---@param name string @The new identity that will be used as write directory.
---@overload fun(name:string):void
function m.setIdentity(name) end
---Sets the filesystem paths that will be searched when require is called.
---
---The paths string given to this function is a sequence of path templates separated by semicolons. The argument passed to ''require'' will be inserted in place of any question mark ('?') character in each template (after the dot characters in the argument passed to ''require'' are replaced by directory separators.)
---
---The paths are relative to the game's source and save directories, as well as any paths mounted with love.filesystem.mount.
---@param paths string @The paths that the ''require'' function will check in love's filesystem.
function m.setRequirePath(paths) end
---Sets the source of the game, where the code is present. This function can only be called once, and is normally automatically done by LÖVE.
---@param path string @Absolute path to the game's source folder.
function m.setSource(path) end
---Sets whether love.filesystem follows symbolic links. It is enabled by default in version 0.10.0 and newer, and disabled by default in 0.9.2.
---@param enable boolean @Whether love.filesystem should follow symbolic links.
function m.setSymlinksEnabled(enable) end
---Unmounts a zip file or folder previously mounted for reading with love.filesystem.mount.
---@param archive string @The folder or zip file in the game's save directory which is currently mounted.
---@return boolean
function m.unmount(archive) end
---Write data to a file in the save directory. If the file existed already, it will be completely replaced by the new contents.
---@param name string @The name (and path) of the file.
---@param data string @The string data to write to the file.
---@param size number @How many bytes to write.
---@return boolean, string
---@overload fun(name:string, data:Data, size:number):boolean, string
function m.write(name, data, size) end
return m
|
local AM = luajava.bindClass("com.theincgi.advancedMacros.AdvancedMacros")
local mc = AM:getMinecraft()
log(getProfile())
log(mc.field_71439_g.field_70138_W)
mc.field_71439_g:func_71004_bE()
|
SMT_DB = {
}
|
--- Riak counter object. Can only be used with resty.riak created client.
-- These are generally just wrappers around the low level
-- @{resty.riak.client} functions
-- @see resty.riak
-- @module resty.riak.counter
local riak_client = require "resty.riak.client"
local helpers = require "resty.riak.helpers"
local setmetatable = setmetatable
local get_counter = riak_client.get_counter
local update_counter = riak_client.update_counter
local _M = helpers.module()
local function to_number(self)
end
local mt = {
__index = _M,
__tonumber = to_number
}
--- Create a new riak counter. This does not change anything in riak, it only sets up a Lua object.
-- Generally, @{resty.riak.bucket.counter}
-- is prefered.
-- @tparam resty.riak.bucket bucket
-- @tparam string key
-- @treturn resty.riak.counter
function _M.new(bucket, key)
local o = {
bucket = bucket,
client = bucket.client,
key = key,
}
return setmetatable(o, mt)
end
--- Get the value of the counter
-- @tparam resty.riak.counter self
-- @treturn number
function _M.value(self)
return get_counter(self.client, self.bucket.name, self.key)
end
--- Decrement the counter
-- @tparam resty.riak.counter self
-- @tparam number amount the amount to decrement the counter by
-- @treturn boolean
function _M.decrement(self, amount)
amount = amount and (0 - amount) or -1
return update_counter(self.client, self.bucket.name, self.key, amount)
end
--- Increment the counter
-- @tparam resty.riak.counter self
-- @tparam number amount the amount to increment the counter by
-- @treturn boolean
function _M.increment(self, amount)
amount = amount or 1
return update_counter(self.client, self.bucket.name, self.key, amount)
end
--- Decrement the counter and return its new value
-- @tparam resty.riak.counter self
-- @tparam number amount the amount to decrement the counter by
-- @treturn number
function _M.decrement_and_return(self, amount)
amount = amount and (0 - amount) or -1
return update_counter(self.client, self.bucket.name, self.key, amount, { returnvalue = true })
end
--- Increment the counter and return its new value
-- @tparam resty.riak.counter self
-- @tparam number amount the amount to decrement the counter by
-- @treturn number
function _M.increment_and_return(self, amount)
amount = amount or 1
return update_counter(self.client, self.bucket.name, self.key, amount, { returnvalue = true })
end
return _M
|
local PauseMenu = {}
-- pause menu
-- ┏━┓┏━┓╻ ╻┏━┓┏━╸ ┏┳┓┏━╸┏┓╻╻ ╻
-- ┣━┛┣━┫┃ ┃┗━┓┣╸ ┃┃┃┣╸ ┃┗┫┃ ┃
-- ╹ ╹ ╹┗━┛┗━┛┗━╸ ╹ ╹┗━╸╹ ╹┗━┛
function PauseMenu:draw()
textbox("< p to resume game >", 280, 300)
textbox("o for options menu", 280, 317)
end
-- using ':' so `self` becomes the previous callback's return value
function PauseMenu:keypressed(key)
if self then return self end -- skip handling if this key was handled already
if key == "p" then
St8.resume()
elseif key == "o" then
St8.push(require"states.options", "pop")
end
end
return PauseMenu
|
local M = {}
local function get_base(cp, config)
cp.none = "NONE"
return {
Comment = { fg = cp.gray, style = config.styles.comments }, -- just comments
ColorColumn = { bg = cp.gray2 }, -- used for the columns set with 'colorcolumn'
Conceal = { fg = cp.bg }, -- placeholder characters substituted for concealed text (see 'conceallevel')
Cursor = { fg = cp.bg2, bg = cp.fg }, -- character under the cursor
lCursor = { fg = cp.bg2, bg = cp.fg }, -- the character under the cursor when |language-mapping| is used (see 'guicursor')
CursorIM = { fg = cp.bg2, bg = cp.fg }, -- like Cursor, but used when in IME mode |CursorIM|
CursorColumn = { bg = cp.bg1 }, -- Screen-column at the cursor, when 'cursorcolumn' is secp.
CursorLine = { bg = cp.bg1 }, -- Screen-line at the cursor, when 'cursorline' is secp. Low-priority if foreground (ctermfg OR guifg) is not secp.
Directory = { fg = cp.blue }, -- directory names (and other special names in listings)
EndOfBuffer = { fg = cp.bg2 }, -- filler lines (~) after the end of the buffer. By default, this is highlighted like |hl-NonText|.
ErrorMsg = { fg = cp.red, style = "bold,italic" }, -- error messages on the command line
VertSplit = { fg = cp.bg2 }, -- the column separating vertically split windows
Folded = { fg = cp.blue, bg = cp.bg4 }, -- line used for closed folds
FoldColumn = { bg = cp.bg2, fg = cp.gray }, -- 'foldcolumn'
SignColumn = { bg = config.transparent_background and cp.none or cp.bg0, fg = cp.bg4 }, -- column where |signs| are displayed
SignColumnSB = { bg = cp.bg0, fg = cp.bg4 }, -- column where |signs| are displayed
Substitute = { bg = cp.bg4, fg = cp.pink }, -- |:substitute| replacement text highlighting
LineNr = { fg = cp.bg4 }, -- Line number for ":number" and ":#" commands, and when 'number' or 'relativenumber' option is secp.
CursorLineNr = { fg = cp.green }, -- Like LineNr when 'cursorline' or 'relativenumber' is set for the cursor line. highlights the number in numberline.
MatchParen = { fg = cp.purple_a, style = "bold" }, -- The character under the cursor or just before it, if it is a paired bracket, and its match. |pi_paren.txt|
ModeMsg = { fg = cp.fg0, style = "bold" }, -- 'showmode' message (e.g., "-- INSERT -- ")
MsgArea = { fg = cp.fg }, -- Area for messages and cmdline
MsgSeparator = {}, -- Separator for scrolled messages, `msgsep` flag of 'display'
MoreMsg = { fg = cp.blue }, -- |more-prompt|
NonText = { fg = cp.gray }, -- '@' at the end of the window, characters from 'showbreak' and other characters that do not really exist in the text (e.g., ">" displayed when a double-wide character doesn't fit at the end of the line). See also |hl-EndOfBuffer|.
Normal = { fg = cp.fg0, bg = config.transparent_background and cp.none or cp.bg0 }, -- normal text
NormalNC = { fg = cp.fg0, bg = config.transparent_background and cp.none or cp.bg0 }, -- normal text in non-current windows
NormalSB = { fg = cp.fg0, bg = cp.bg0 }, -- normal text in non-current windows
NormalFloat = { fg = cp.fg0, bg = cp.bg1 }, -- Normal text in floating windows.
FloatBorder = { fg = cp.blue, bg = cp.bg1 },
Pmenu = { bg = cp.bg1, fg = cp.fg1 }, -- Popup menu: normal item.
PmenuSel = { fg = cp.fg1, bg = cp.bg2 }, -- Popup menu: selected item.
PmenuSbar = { bg = cp.bg4 }, -- Popup menu: scrollbar.
PmenuThumb = { bg = cp.gray }, -- Popup menu: Thumb of the scrollbar.
Question = { fg = cp.blue }, -- |hit-enter| prompt and yes/no questions
QuickFixLine = { bg = cp.bg4, style = "bold" }, -- Current |quickfix| item in the quickfix window. Combined with |hl-CursorLine| when the cursor is there.
Search = { bg = cp.yellow, fg = cp.bg0, style = "bold" }, -- Last search pattern highlighting (see 'hlsearch'). Also used for similar items that need to stand oucp.
IncSearch = { bg = cp.pink, fg = cp.bg4 }, -- 'incsearch' highlighting; also used for the text replaced with ":s///c"
SpecialKey = { fg = cp.fg }, -- Unprintable characters: text displayed differently from what it really is. But not 'listchars' whitespace. |hl-Whitespace|
SpellBad = { sp = cp.red, style = "undercurl" }, -- Word that is not recognized by the spellchecker. |spell| Combined with the highlighting used otherwise.
SpellCap = { sp = cp.yellow, style = "undercurl" }, -- Word that should start with a capital. |spell| Combined with the highlighting used otherwise.
SpellLocal = { sp = cp.blue, style = "undercurl" }, -- Word that is recognized by the spellchecker as one that is used in another region. |spell| Combined with the highlighting used otherwise.
SpellRare = { sp = cp.green, style = "undercurl" }, -- Word that is recognized by the spellchecker as one that is hardly ever used. |spell| Combined with the highlighting used otherwise.
StatusLine = { fg = cp.fg0, bg = cp.bg1 }, -- status line of current window
StatusLineNC = { fg = cp.bg4, bg = cp.bg1 }, -- status lines of not-current windows Note: if this is equal to "StatusLine" Vim will use "^^^" in the status line of the current window.
TabLine = { bg = cp.bg1, fg = cp.bg4 }, -- tab pages line, not active tab page label
TabLineFill = { bg = cp.bg }, -- tab pages line, where there are no labels
TabLineSel = { fg = cp.green, bg = cp.bg4 }, -- tab pages line, active tab page label
Title = { fg = cp.blue, style = "bold" }, -- titles for output from ":set all", ":autocmd" etcp.
Visual = { bg = cp.bg4, style = "bold" }, -- Visual mode selection
VisualNOS = { bg = cp.bg4, style = "bold" }, -- Visual mode selection when vim is "Not Owning the Selection".
WarningMsg = { fg = cp.yellow }, -- warning messages
fgspace = { fg = cp.bg4 }, -- "nbsp", "space", "tab" and "trail" in 'listchars'
WildMenu = { bg = cp.gray }, -- current match in 'wildmenu' completion
Statement = { fg = cp.red },
Conditional = { fg = cp.red },
Repeat = { fg = cp.red },
Label = { fg = cp.red },
Exception = { fg = cp.red },
Operator = { fg = cp.fg1 },
Keyword = { fg = cp.red },
Identifier = { fg = cp.blue },
Function = { fg = cp.green },
PreProc = { fg = cp.aqua },
Include = { fg = cp.aqua },
Define = { fg = cp.aqua },
Macro = { fg = cp.aqua },
PreCondit = { fg = cp.aqua },
Constant = { fg = cp.purple },
Character = { fg = cp.purple },
Boolean = { fg = cp.purple },
Number = { fg = cp.purple },
Float = { fg = cp.purple },
String = { fg = cp.green },
Type = { fg = cp.yellow },
StorageClass = { fg = cp.orange },
Structure = { fg = cp.aqua },
Typedef = { fg = cp.yellow },
SpecialChar = { fg = cp.red },
}
end
local function get_integrations(cp, config)
local integrations = config["integrations"]
local final_integrations = {}
for integration in pairs(integrations) do
local cot = false
if type(integrations[integration]) == "table" then
if integrations[integration]["enabled"] == true then
cot = true
end
else
if integrations[integration] == true then
cot = true
end
end
if cot then
final_integrations = vim.tbl_deep_extend(
"force",
final_integrations,
require("gruvbox.integrations." .. integration).get(cp, config)
)
end
end
final_integrations = vim.tbl_deep_extend(
"force",
final_integrations,
require("gruvbox.remaps").get_hig_remaps() or {}
)
return final_integrations
end
local function get_terminal(cp)
local term_colors = {
terminal_0 = cp.bg0,
terminal_1 = cp.red_a,
terminal_2 = cp.green_a,
terminal_3 = cp.yellow_a,
terminal_4 = cp.blue_a,
terminal_5 = cp.purple_a,
terminal_6 = cp.aqua_a,
terminal_7 = cp.gray,
terminal_8 = cp.gray_a,
terminal_9 = cp.red,
terminal_10 = cp.green,
terminal_11 = cp.yellow,
terminal_12 = cp.blue,
terminal_13 = cp.purple,
terminal_14 = cp.aqua,
terminal_15 = cp.fg0
}
return term_colors
end
function M.apply(cp, config)
local theme = {}
theme.base = get_base(cp, config)
theme.integrations = get_integrations(cp, config)
theme.terminal = get_terminal(cp)
return theme
end
return M
|
local playersProcessingExtap = {}
local playersProcessingExta = {}
RegisterServerEvent('esx_illegal:pickedUpMdma')
AddEventHandler('esx_illegal:pickedUpMdma', function()
local xPlayer = ESX.GetPlayerFromId(source)
local xItem = xPlayer.getInventoryItem('extamdma')
if xItem.limit ~= -1 and (xItem.count + 10) > xItem.limit then
TriggerClientEvent('esx:showNotification', source, 'vous n\'avez plus assez de place pour stocker la ~r~MDMA~s~.')
else
xPlayer.addInventoryItem(xItem.name, 10)
end
end)
RegisterServerEvent('esx_illegal:pickedUpAmphet')
AddEventHandler('esx_illegal:pickedUpAmphet', function()
local xPlayer = ESX.GetPlayerFromId(source)
local xItem = xPlayer.getInventoryItem('extaamphetamine')
if xItem.limit ~= -1 and (xItem.count + 10) > xItem.limit then
TriggerClientEvent('esx:showNotification', _source, 'vous n\'avez plus assez de place pour stocker des ~r~Amphétamines~s~.')
else
xPlayer.addInventoryItem(xItem.name, 10)
end
end)
-- RegisterServerEvent('esx_illegal:processExtap')
-- AddEventHandler('esx_illegal:processExtap', function()
-- if not playersProcessingExtap[source] then
-- local _source = source
-- local xPlayer = ESX.GetPlayerFromId(_source)
-- local xKeyexta = xPlayer.getInventoryItem('keyexta')
-- if xKeyexta.count < 1 then
-- TriggerClientEvent('esx:showNotification', _source, 'Vous n\'avez pas la clé')
-- return
-- end
-- TriggerClientEvent('esx:showNotification', _source, _U('extap_processingstarted'))
-- playersProcessingExtap[_source] = ESX.SetTimeout(Config.Delays.ExtapProcessing, function()
-- local xExtamdma, xExtaamphetamine, xExtazyp = xPlayer.getInventoryItem('extamdma'), xPlayer.getInventoryItem('extaamphetamine'), xPlayer.getInventoryItem('extazyp')
-- if xExtazyp.limit ~= -1 and (xExtazyp.count + 1) > xExtazyp.limit then
-- TriggerClientEvent('esx:showNotification', _source, _U('extap_processingfull'))
-- elseif xExtamdma.count < 1 then
-- TriggerClientEvent('esx:showNotification', _source, _U('extap_processingenough'))
-- elseif xExtaamphetamine.count < 2 then
-- TriggerClientEvent('esx:showNotification', _source, _U('extap_processingenough'))
-- else
-- xPlayer.removeInventoryItem('extamdma', 2)
-- xPlayer.removeInventoryItem('extaamphetamine', 2)
-- xPlayer.addInventoryItem('extazyp', 10)
-- TriggerClientEvent('esx:showNotification', _source, _U('extap_processed'))
-- end
-- playersProcessingExtap[_source] = nil
-- end)
-- else
-- print(('esx_illegal: %s attempted to exploit extap processing!'):format(GetPlayerIdentifiers(source)[1]))
-- end
-- end)
RegisterServerEvent('esx_illegal:processExtap')
AddEventHandler('esx_illegal:processExtap', function()
if not playersProcessingExtap[source] then
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
playersProcessingExtap[_source] = true
-- playersProcessingExtap[_source] = ESX.SetTimeout(Config.Delays.ExtapProcessing, function()
local xKeyexta, xExtamdma, xExtaamphetamine, xExtazyp = xPlayer.getInventoryItem('keyexta'), xPlayer.getInventoryItem('extamdma'), xPlayer.getInventoryItem('extaamphetamine'), xPlayer.getInventoryItem('extazyp')
if xKeyexta.count < 1 then
TriggerClientEvent('esx:showNotification', _source, 'Vous n\'avez pas la clé')
elseif xExtazyp.limit ~= -1 and (xExtazyp.count + 1) > xExtazyp.limit then
TriggerClientEvent('esx:showNotification', _source, _U('extap_processingfull'))
elseif xExtamdma.count < 1 then
TriggerClientEvent('esx:showNotification', _source, _U('extap_processingenough'))
elseif xExtaamphetamine.count < 2 then
TriggerClientEvent('esx:showNotification', _source, _U('extap_processingenough'))
else
TriggerClientEvent('esx:showNotification', _source, _U('extap_processingstarted'))
Citizen.Wait(Config.Delays.ExtapProcessing)
xPlayer.removeInventoryItem('extamdma', 2)
xPlayer.removeInventoryItem('extaamphetamine', 2)
xPlayer.addInventoryItem('extazyp', 10)
TriggerClientEvent('esx:showNotification', _source, _U('extap_processed'))
end
playersProcessingExtap[_source] = nil
-- end)
else
print(('esx_illegal: %s attempted to exploit extap processing!'):format(GetPlayerIdentifiers(source)[1]))
end
end)
function CancelProcessing(playerID)
if playersProcessingExtap[playerID] then
ESX.ClearTimeout(playersProcessingExtap[playerID])
playersProcessingExtap[playerID] = nil
elseif playersProcessingExta[playerID] then
ESX.ClearTimeout(playersProcessingExta[playerID])
playersProcessingExta[playerID] = nil
end
end
RegisterServerEvent('esx_illegal:cancelProcessing')
AddEventHandler('esx_illegal:cancelProcessing', function()
CancelProcessing(source)
end)
RegisterServerEvent('esx_illegal:processExta')
AddEventHandler('esx_illegal:processExta', function()
if not playersProcessingExta [source] then
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local xKeyexta = xPlayer.getInventoryItem('keyexta')
if xKeyexta.count < 1 then
TriggerClientEvent('esx:showNotification', _source, 'Vous n\'avez pas la clé')
return
end
TriggerClientEvent('esx:showNotification', _source, _U('exta_processingstarted'))
playersProcessingExta[_source] = ESX.SetTimeout(Config.Delays.ExtaProcessing, function()
local xExtazyp, xBagexta, xDopebag = xPlayer.getInventoryItem('extazyp'), xPlayer.getInventoryItem('bagexta'), xPlayer.getInventoryItem('dopebag')
if xBagexta.limit ~= -1 and (xBagexta.count + 1) > xBagexta.limit then
TriggerClientEvent('esx:showNotification', _source, _U('exta_processingfull'))
elseif xExtazyp.count < 5 then
TriggerClientEvent('esx:showNotification', _source, _U('exta_processingenough'))
elseif xDopebag.count < 1 then
TriggerClientEvent('esx:showNotification', _source, _U('exta_processingenough'))
else
xPlayer.removeInventoryItem('dopebag', 1)
xPlayer.removeInventoryItem('extazyp', 5)
xPlayer.addInventoryItem('bagexta', 1)
TriggerClientEvent('esx:showNotification', _source, _U('exta_processed'))
end
playersProcessingExta[_source] = nil
end)
else
print(('esx_illegal: %s attempted to exploit exta processing!'):format(GetPlayerIdentifiers(source)[1]))
end
end)
AddEventHandler('esx:playerDropped', function(playerID, reason)
CancelProcessing(playerID)
end)
RegisterServerEvent('esx:onPlayerDeath')
AddEventHandler('esx:onPlayerDeath', function(data)
CancelProcessing(source)
end)
|
--
-- Copyright (C) 2017-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
local LocalPlayer = LocalPlayer
local HUDCommons = HUDCommons
local IsValid = IsValid
local math = math
--[[
@doc
@fname DLib.HUDCommons.SelectPlayer
@client
@desc
use this instead of !g:LocalPlayer in HUDs
@enddesc
@returns
Player: the player from which eyes we are currently looking
]]
function HUDCommons.SelectPlayer()
local ply = LocalPlayer()
if not IsValid(ply) then return ply end
local obs = ply:GetObserverTarget()
if IsValid(obs) and obs:IsPlayer() then
return obs
else
return ply
end
end
--[[
@doc
@fname DLib.HUDCommons.TranslatePolyMatrix
@args table matrix, number x, number y
@client
@desc
moves x and y coordinates of !s:PolygonVertex
@enddesc
@returns
table: matrix
]]
function HUDCommons.TranslatePolyMatrix(data, x, y)
for i, vertex in ipairs(data) do
vertex.x, vertex.y = vertex.x + x, vertex.y + y
end
return data
end
--[[
@doc
@fname DLib.HUDCommons.RotatePolyMatrix
@args table matrix, number rotateBy
@client
@desc
rotates all x and y points of !s:PolygonVertex relative 0, 0
`rotateBy` is a degree number, not radian
@enddesc
@returns
table: matrix
]]
function HUDCommons.RotatePolyMatrix(data, rotateBy)
if rotateBy == 0 then return data end
local deg = rotateBy:rad()
local sin, cos = deg:sin(), deg:cos()
for i, vertex in ipairs(data) do
local x, y = vertex.x, vertex.y
local xn = x * cos - y * sin
local yn = x * sin + y * cos
vertex.x, vertex.y = xn, yn
end
return data
end
|
return {[3000320]=true,[2]=true,[311300]=true,[303110]=true,[1032200]=true,[213002]=true,[11]=true,[12302]=true,[2013200]=true,[20]=true,[23]=true,[213020]=true,[2132000]=true,[3113000]=true,[301100]=true,[301103]=true,[1022000]=true,[2302001]=true,[1022003]=true,[2102]=true,[2003000]=true,[1030202]=true,[2003003]=true,[3031100]=true,[10301]=true,[2003012]=true,[10310]=true,[1200200]=true,[10313]=true,[301130]=true,[1200203]=true,[1030220]=true,[2003021]=true,[1022030]=true,[2130002]=true,[2132]=true,[2003030]=true,[10331]=true,[2300000]=true,[1020002]=true,[2300003]=true,[2130020]=true,[101]=true,[1200230]=true,[2001002]=true,[2300012]=true,[110]=true,[113]=true,[221300]=true,[2300021]=true,[1020023]=true,[123002]=true,[1202300]=true,[2300030]=true,[2001023]=true,[1020032]=true,[131]=true,[2001032]=true,[123020]=true,[301202]=true,[2302100]=true,[3023000]=true,[2201]=true,[1030301]=true,[2003102]=true,[2210]=true,[301220]=true,[2213]=true,[1030310]=true,[2220200]=true,[1200302]=true,[2003120]=true,[2231]=true,[1200320]=true,[2300102]=true,[200]=true,[3021002]=true,[203]=true,[2210000]=true,[2210003]=true,[212]=true,[2300120]=true,[3021020]=true,[221]=true,[1100000]=true,[1100003]=true,[131300]=true,[230]=true,[1313000]=true,[233]=true,[33002]=true,[2210030]=true,[33011]=true,[301301]=true,[203000]=true,[203003]=true,[33020]=true,[1100030]=true,[2303]=true,[2003201]=true,[203012]=true,[2312]=true,[2003210]=true,[203021]=true,[2321]=true,[330002]=true,[203030]=true,[2130200]=true,[3103001]=true,[2330]=true,[330011]=true,[3103010]=true,[330020]=true,[31013]=true,[1020200]=true,[2300201]=true,[201002]=true,[1020203]=true,[302]=true,[3230000]=true,[2300210]=true,[2001203]=true,[311]=true,[201020]=true,[201023]=true,[123200]=true,[2120003]=true,[1020230]=true,[3101000]=true,[3101003]=true,[332]=true,[33101]=true,[2001230]=true,[1010000]=true,[1010003]=true,[33110]=true,[1223000]=true,[1022300]=true,[2120030]=true,[2003300]=true,[3101030]=true,[113000]=true,[113003]=true,[1010030]=true,[203120]=true,[1010033]=true,[330101]=true,[3103100]=true,[330110]=true,[31103]=true,[2032001]=true,[113030]=true,[3013001]=true,[2032010]=true,[2300300]=true,[1020302]=true,[3021200]=true,[3013010]=true,[2001302]=true,[31130]=true,[1020320]=true,[2202020]=true,[2001320]=true,[2030000]=true,[3310001]=true,[2030003]=true,[3011000]=true,[3310010]=true,[3011003]=true,[2030012]=true,[2200001]=true,[2030021]=true,[1133000]=true,[2200010]=true,[2200013]=true,[2030030]=true,[322001]=true,[3011030]=true,[23000]=true,[1303001]=true,[322010]=true,[23003]=true,[2200031]=true,[1303010]=true,[2032100]=true,[3013100]=true,[23021]=true,[201200]=true,[201203]=true,[31220]=true,[23030]=true,[2210300]=true,[320000]=true,[320003]=true,[1301000]=true,[21002]=true,[1301003]=true,[1100300]=true,[201230]=true,[1100303]=true,[1002002]=true,[3310100]=true,[320021]=true,[2030102]=true,[21020]=true,[320030]=true,[21023]=true,[3220001]=true,[203300]=true,[1301030]=true,[1002023]=true,[2030120]=true,[1100330]=true,[1002032]=true,[322100]=true,[1303100]=true,[23102]=true,[1000001]=true,[2200130]=true,[31301]=true,[1000010]=true,[1000013]=true,[31310]=true,[23120]=true,[1000022]=true,[2202200]=true,[103001]=true,[1000031]=true,[103010]=true,[103013]=true,[320102]=true,[2321000]=true,[2120300]=true,[103022]=true,[230000]=true,[2022002]=true,[230003]=true,[3101300]=true,[103031]=true,[320120]=true,[2030201]=true,[3003002]=true,[1010300]=true,[1010303]=true,[2030210]=true,[3003011]=true,[3220100]=true,[230021]=true,[101000]=true,[2200202]=true,[101003]=true,[3003020]=true,[230030]=true,[3130001]=true,[113300]=true,[3130010]=true,[2200220]=true,[2020001]=true,[3300002]=true,[1000100]=true,[101030]=true,[1000103]=true,[3001001]=true,[2020010]=true,[3300011]=true,[2020013]=true,[3001010]=true,[3300020]=true,[3001013]=true,[2020022]=true,[103100]=true,[3001022]=true,[2020031]=true,[1000130]=true,[1000133]=true,[3001031]=true,[13001]=true,[21200]=true,[13010]=true,[21203]=true,[312020]=true,[13013]=true,[230102]=true,[1002200]=true,[103130]=true,[1002203]=true,[2030300]=true,[3003101]=true,[13022]=true,[3212000]=true,[3011300]=true,[3003110]=true,[13031]=true,[230120]=true,[2200301]=true,[21230]=true,[2102000]=true,[310001]=true,[2102003]=true,[3130100]=true,[2200310]=true,[11000]=true,[310010]=true,[11003]=true,[310013]=true,[23300]=true,[3300101]=true,[310022]=true,[2020103]=true,[1000202]=true,[3001100]=true,[3300110]=true,[3001103]=true,[3210002]=true,[11030]=true,[11033]=true,[1000220]=true,[1000223]=true,[2100002]=true,[3210020]=true,[1000232]=true,[1033001]=true,[3001130]=true,[320300]=true,[13103]=true,[1033010]=true,[1301300]=true,[21302]=true,[2100023]=true,[2022200]=true,[230201]=true,[1203002]=true,[1002302]=true,[3003200]=true,[230210]=true,[222020]=true,[21320]=true,[13130]=true,[1203020]=true,[3122000]=true,[1330001]=true,[310100]=true,[310103]=true,[1031000]=true,[1330010]=true,[1031003]=true,[2012000]=true,[220001]=true,[2012003]=true,[3300200]=true,[220010]=true,[1000301]=true,[310130]=true,[1000310]=true,[1000313]=true,[2020220]=true,[2012030]=true,[220031]=true,[3120002]=true,[3001220]=true,[103301]=true,[312200]=true,[1000331]=true,[1033100]=true,[103310]=true,[2010002]=true,[3120020]=true,[230300]=true,[132002]=true,[2010020]=true,[2010023]=true,[302000]=true,[302003]=true,[101300]=true,[101303]=true,[3002]=true,[302012]=true,[3032000]=true,[3011]=true,[220100]=true,[302021]=true,[220103]=true,[3020]=true,[2020301]=true,[302030]=true,[3023]=true,[130001]=true,[101330]=true,[3001301]=true,[2020310]=true,[3210200]=true,[130010]=true,[130013]=true,[3001310]=true,[300002]=true,[130022]=true,[2100200]=true,[1001]=true,[300011]=true,[130031]=true,[1010]=true,[300020]=true,[1013]=true,[300023]=true,[222200]=true,[3030011]=true,[1022]=true,[1203200]=true,[3200003]=true,[3030020]=true,[2100230]=true,[1031]=true,[3200012]=true,[1322000]=true,[3200021]=true,[302102]=true,[2303000]=true,[1023002]=true,[2102300]=true,[310301]=true,[3200030]=true,[212000]=true,[212003]=true,[11300]=true,[310310]=true,[11303]=true,[302120]=true,[3113]=true,[220202]=true,[1023020]=true,[3122]=true,[130100]=true,[130103]=true,[3131]=true,[220220]=true,[212030]=true,[11330]=true,[300101]=true,[3120200]=true,[2301002]=true,[1100]=true,[2100302]=true,[1103]=true,[300113]=true,[210002]=true,[1320020]=true,[3030101]=true,[2010200]=true,[300122]=true,[2010203]=true,[2301020]=true,[2002013]=true,[3030110]=true,[2100320]=true,[300131]=true,[210020]=true,[3200102]=true,[210023]=true,[132200]=true,[1130]=true,[1133]=true,[2002031]=true,[210032]=true,[3110003]=true,[2010230]=true,[3200120]=true,[302201]=true,[3200]=true,[302210]=true,[2000003]=true,[1031300]=true,[2213000]=true,[2012300]=true,[220301]=true,[3110030]=true,[122000]=true,[122003]=true,[2000021]=true,[220310]=true,[1103000]=true,[130202]=true,[1103003]=true,[3230]=true,[2000033]=true,[300200]=true,[300203]=true,[130220]=true,[122030]=true,[3022001]=true,[1202]=true,[300212]=true,[1103030]=true,[2002103]=true,[3030200]=true,[3022010]=true,[300221]=true,[2010302]=true,[120002]=true,[1220]=true,[300230]=true,[1223]=true,[3200201]=true,[2010320]=true,[2002130]=true,[120020]=true,[120023]=true,[302300]=true,[1023200]=true,[3020003]=true,[3302]=true,[3020012]=true,[3311]=true,[3020021]=true,[2123000]=true,[331001]=true,[2000123]=true,[130301]=true,[3020030]=true,[32000]=true,[331010]=true,[32003]=true,[2000132]=true,[130310]=true,[1320200]=true,[1013003]=true,[32012]=true,[300302]=true,[2301200]=true,[202001]=true,[3022100]=true,[1301]=true,[300311]=true,[210200]=true,[202010]=true,[210203]=true,[202013]=true,[32030]=true,[300320]=true,[1313]=true,[1013030]=true,[1322]=true,[2002220]=true,[202031]=true,[1310000]=true,[3102002]=true,[1310003]=true,[210230]=true,[30011]=true,[200000]=true,[200003]=true,[3102020]=true,[3020102]=true,[30023]=true,[2000201]=true,[212300]=true,[1310030]=true,[30032]=true,[2000210]=true,[2000213]=true,[3020120]=true,[331100]=true,[2000222]=true,[200033]=true,[32102]=true,[2000231]=true,[2033000]=true,[3100010]=true,[3100013]=true,[202100]=true,[3100022]=true,[202103]=true,[1230200]=true,[2203001]=true,[2002301]=true,[210302]=true,[3100031]=true,[2203010]=true,[2002310]=true,[120200]=true,[120203]=true,[210320]=true,[202130]=true,[30101]=true,[3311000]=true,[2031002]=true,[3110300]=true,[30110]=true,[1220000]=true,[30113]=true,[3012002]=true,[1220003]=true,[120230]=true,[2201000]=true,[3020201]=true,[30122]=true,[2201003]=true,[2031020]=true,[2000303]=true,[110000]=true,[3020210]=true,[110003]=true,[3012020]=true,[323000]=true,[200123]=true,[122300]=true,[1220030]=true,[2000321]=true,[3100100]=true,[2201030]=true,[3100103]=true,[32201]=true,[2000330]=true,[110030]=true,[3010001]=true,[32210]=true,[3010010]=true,[2203100]=true,[3010013]=true,[3100130]=true,[3010022]=true,[321002]=true,[202220]=true,[120302]=true,[3010031]=true,[22001]=true,[1302002]=true,[3102200]=true,[1003001]=true,[22010]=true,[30203]=true,[321020]=true,[22013]=true,[120320]=true,[1003010]=true,[1302020]=true,[1003013]=true,[22022]=true,[3221000]=true,[200201]=true,[3020300]=true,[30221]=true,[1003022]=true,[22031]=true,[1130000]=true,[200210]=true,[1130003]=true,[200213]=true,[30230]=true,[1003031]=true,[200222]=true,[20000]=true,[1300001]=true,[20003]=true,[200231]=true,[1001000]=true,[3100202]=true,[1001003]=true,[20012]=true,[1300013]=true,[1130030]=true,[3010100]=true,[20021]=true,[1300022]=true,[3010103]=true,[3100220]=true,[202301]=true,[20030]=true,[1300031]=true,[20033]=true,[1001030]=true,[1001033]=true,[3010130]=true,[22100]=true,[22103]=true,[2023001]=true,[231002]=true,[1310300]=true,[30302]=true,[1003103]=true,[2031200]=true,[2023010]=true,[30311]=true,[3012200]=true,[200300]=true,[200303]=true,[30320]=true,[102002]=true,[3131000]=true,[1003130]=true,[2320001]=true,[102020]=true,[20102]=true,[1300103]=true,[2021000]=true,[3301001]=true,[200330]=true,[2021003]=true,[3100301]=true,[3002000]=true,[3301010]=true,[3002003]=true,[3100310]=true,[20120]=true,[3010202]=true,[20123]=true,[3002012]=true,[100001]=true,[1300130]=true,[20132]=true,[3002021]=true,[2021030]=true,[313001]=true,[100010]=true,[3010220]=true,[100013]=true,[3002030]=true,[321200]=true,[313010]=true,[3221]=true,[3212]=true,[100022]=true,[2222]=true,[1302200]=true,[2123]=true,[22202]=true,[1331]=true,[2023100]=true,[1232]=true,[30212]=true,[100031]=true,[30131]=true,[103202]=true,[3000002]=true,[203201]=true,[20231]=true,[13100]=true,[10322]=true,[1230002]=true,[1200032]=true,[3101]=true,[1002020]=true,[3000011]=true,[1220300]=true,[1103300]=true,[3032]=true,[32021]=true,[3110]=true,[3001202]=true,[31031]=true,[31022]=true,[3000020]=true,[202202]=true,[1232000]=true,[3000023]=true,[311000]=true,[3202100]=true,[2103002]=true,[311003]=true,[110300]=true,[23012]=true,[2310200]=true,[110303]=true,[3000032]=true,[2302010]=true,[12002]=true,[21032]=true,[2320100]=true,[1320002]=true,[213200]=true,[2120]=true,[300110]=true,[20201]=true,[1300202]=true,[2002001]=true,[2103020]=true,[1010330]=true,[2002010]=true,[303200]=true,[31202]=true,[2230001]=true,[20210]=true,[3110000]=true,[12020]=true,[20213]=true,[3002102]=true,[12023]=true,[1020020]=true,[122]=true,[2230010]=true,[23201]=true,[1300220]=true,[3010301]=true,[20222]=true,[2001020]=true,[12032]=true,[2000000]=true,[22301]=true,[3320]=true,[100100]=true,[1013300]=true,[3010310]=true,[100103]=true,[3002120]=true,[13301]=true,[13202]=true,[2000012]=true,[313100]=true,[1003100]=true,[2000030]=true,[32120]=true,[1031030]=true,[10001]=true,[133010]=true,[23210]=true,[22310]=true,[22220]=true,[22130]=true,[3201200]=true,[2002100]=true,[223001]=true,[10010]=true,[13310]=true,[13220]=true,[10013]=true,[12320]=true,[3320000]=true,[231200]=true,[1230020]=true,[100130]=true,[101033]=true,[200321]=true,[3000101]=true,[10022]=true,[200312]=true,[3200210]=true,[200132]=true,[3301100]=true,[100322]=true,[3020000]=true,[100313]=true,[3000110]=true,[10031]=true,[100232]=true,[3000113]=true,[220022]=true,[2000102]=true,[100133]=true,[3203000]=true,[1330100]=true,[102200]=true,[1331000]=true,[1003301]=true,[3000122]=true,[102203]=true,[1130300]=true,[202022]=true,[2000120]=true,[2300]=true,[2312000]=true,[1100033]=true,[1032002]=true,[3000131]=true,[201032]=true,[301310]=true,[1013000]=true,[2002202]=true,[221000]=true,[102032]=true,[2013002]=true,[221003]=true,[20300]=true,[1300301]=true,[102023]=true,[20303]=true,[1202000]=true,[31001]=true,[200120]=true,[1202003]=true,[2230100]=true,[1310]=true,[1300310]=true,[1001303]=true,[20312]=true,[3002201]=true,[203102]=true,[31010]=true,[2013020]=true,[3200300]=true,[201302]=true,[2001200]=true,[30002]=true,[20321]=true,[3002210]=true,[103103]=true,[1300100]=true,[32300]=true,[221030]=true,[2120000]=true,[203210]=true,[30020]=true,[100202]=true,[202310]=true,[200012]=true,[201320]=true,[1202030]=true,[200021]=true,[103220]=true,[1030001]=true,[2310002]=true,[102320]=true,[10100]=true,[102230]=true,[200030]=true,[10103]=true,[3100001]=true,[320012]=true,[1030010]=true,[310031]=true,[100220]=true,[1030013]=true,[230012]=true,[100223]=true,[220013]=true,[330200]=true,[1200002]=true,[320]=true,[2310020]=true,[31100]=true,[1030022]=true,[2100203]=true,[3000200]=true,[133001]=true,[120032]=true,[3000203]=true,[110033]=true,[320201]=true,[310202]=true,[1030031]=true,[2330000]=true,[2202002]=true,[10130]=true,[33200]=true,[1200020]=true,[10133]=true,[1300010]=true,[1200023]=true,[320210]=true,[200102]=true,[303002]=true,[310220]=true,[2000300]=true,[3000221]=true,[102302]=true,[2020130]=true,[2103200]=true,[220130]=true,[130130]=true,[303011]=true,[110330]=true,[231020]=true,[3000230]=true,[312002]=true,[12200]=true,[232001]=true,[222002]=true,[12203]=true,[303020]=true,[3200000]=true,[2200022]=true,[311030]=true,[2222000]=true,[232010]=true,[223010]=true,[132020]=true,[2021300]=true,[131030]=true,[30200]=true,[1003310]=true,[131000]=true,[232100]=true,[223100]=true,[131003]=true,[3002300]=true,[332000]=true,[2200100]=true,[133100]=true,[2200103]=true,[233000]=true,[3220010]=true,[2100032]=true,[3202010]=true,[3000212]=true,[12230]=true,[300032]=true,[2000312]=true,[301001]=true,[1000322]=true,[2220002]=true,[323]=true,[100301]=true,[1002320]=true,[2002022]=true,[2000]=true,[3302000]=true,[301010]=true,[2003]=true,[1030100]=true,[301013]=true,[100310]=true,[1030103]=true,[1003202]=true,[3031001]=true,[10202]=true,[2320010]=true,[2012]=true,[3203]=true,[301022]=true,[1003220]=true,[1002230]=true,[1001330]=true,[3031010]=true,[2010032]=true,[20330]=true,[2021]=true,[2201300]=true,[301031]=true,[2231000]=true,[2020202]=true,[3201002]=true,[100331]=true,[10220]=true,[2102030]=true,[2030]=true,[10223]=true,[2020100]=true,[2033]=true,[1030130]=true,[2022020]=true,[2220020]=true,[1032020]=true,[2100020]=true,[3000311]=true,[10232]=true,[3000302]=true,[32]=true,[3202001]=true,[3201020]=true,[303101]=true,[1001300]=true,[3030002]=true,}
|
-------------------------------------------------------------------------------
-- Various utilities
module( ..., package.seeall )
require "pack"
function str2array( s, first )
first = first or 1
local a = {}
for i = 1, #s do
a[ first + i - 1 ] = s:byte( i, i )
end
return a
end
function generate_accessors( t, alist )
for _, v in pairs( alist ) do
if #v == 2 then
t[ "get_" .. v[ 1 ] ] = function( self )
return self[ v[ 2 ] ]
end
else
t[ "get_" .. v[ 1 ] ] = function( self )
return v[ 3 ][ self[ v[ 2 ] ] ]
end
end
end
end
function to_table( v )
return type( v ) == "table" and v or { v }
end
function key_of_value( table, value )
for k, v in pairs( table ) do
if v == value then
return k
end
end
end
function has_value( table, value )
local k = key_of_value( table, value )
if not k then return false else return true end
end
|
-- Natural Selection 2 Competitive Mod
-- Source located at - https://github.com/xToken/CompMod
-- lua\CompMod\Structures\Marine\Armory\shared.lua
-- - Dragon
function Armory:GetItemList(forPlayer)
return {
kTechId.Welder,
kTechId.LayMines,
kTechId.Shotgun,
kTechId.GrenadeLauncher,
kTechId.Flamethrower,
kTechId.HeavyMachineGun,
kTechId.ClusterGrenade,
kTechId.GasGrenade,
kTechId.PulseGrenade,
}
end
function Armory:GetTechButtons(techId)
local techButtons =
{
kTechId.FlamethrowerUpgrade1, kTechId.ShotgunUpgrade1, kTechId.MGUpgrade1, kTechId.GLUpgrade1,
kTechId.None, kTechId.GrenadeTech, kTechId.MinesTech, kTechId.None
}
-- Show button to upgraded to advanced armory
if self:GetTechId() == kTechId.Armory and self:GetResearchingId() ~= kTechId.AdvancedArmoryUpgrade then
techButtons[kMarineUpgradeButtonIndex] = kTechId.AdvancedArmoryUpgrade
end
if GetHasTech(self, kTechId.ShotgunUpgrade1) then
techButtons[2] = kTechId.ShotgunUpgrade2
end
if GetHasTech(self, kTechId.MGUpgrade1) then
techButtons[3] = kTechId.MGUpgrade2
end
return techButtons
end
|
local scenes = {}
RegisterNetEvent('nh-scenes:fetch', function()
local src = source
TriggerClientEvent('nh-scenes:send', src, scenes)
end)
RegisterNetEvent('nh-scenes:add', function(coords, message, color, distance)
table.insert(scenes, {
message = message,
color = color,
distance = distance,
coords = coords
})
TriggerClientEvent('nh-scenes:send', -1, scenes)
TriggerEvent('nh-scenes:log', source, message, coords)
end)
RegisterNetEvent('nh-scenes:delete', function(key)
table.remove(scenes, key)
TriggerClientEvent('nh-scenes:send', -1, scenes)
end)
RegisterNetEvent('nh-scenes:log', function(id, text, coords)
local f, err = io.open('sceneLogging.txt', 'a')
if not f then return print(err) end
f:write('Player: ['..id..'] Placed Scene: ['..text..'] At Coords = '..coords..'\n')
f:close()
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.