content
stringlengths 5
1.05M
|
---|
return {'poerim','poedel','poedelen','poedelhond','poedelnaakt','poedelprijs','poeder','poederblusser','poederbrief','poederbrieven','poederchocolade','poederdons','poederdoos','poederen','poederig','poederkalk','poederkoffie','poederkool','poederkwast','poedermelk','poedersneeuw','poedersuiker','poedervorm','poedervormig','poef','poeh','poeha','poeier','poeieren','poeierig','poel','poelen','poelet','poelier','poelje','poelslak','poelsnip','poema','poen','poenen','poenerig','poenig','poep','poepdoos','poepen','poeper','poeperd','poeperij','poepers','poer','poeren','poerimfeest','poes','poesiealbum','poesje','poesjenel','poesjenellenkelder','poeslief','poesmooi','poespas','poesta','poet','poets','poetsbeurt','poetsdoek','poetsdoos','poetsen','poetser','poetsgerei','poetsgoed','poetskatoen','poetslap','poetsmiddel','poetspommade','poetsster','poetsvrouw','poetszak','poezel','poezelig','poezeligheid','poezen','poezig','poeem','poeet','poema','poesis','poetaster','poetica','poeticaal','poetiek','poetisch','poetiseren','poezie','poeziealbum','poezieavond','poeziebundel','poeziedebuut','poeziefestival','poeziekritiek','poezieliefhebber','poezieprijs','poezietijdschrift','poeziewedstrijd','poeziezomer','poencontract','poepgat','poezieopvatting','poederzeep','poepbruin','poetsextract','poesisleraar','poepluier','poetshulp','poelkikker','poepbroek','poeplucht','poetsdienst','poetsploeg','poetswerk','poezielezer','poezieslag','poezieproject','poedercoating','poepseks','poezenbeest','poezieroute','poederzwamgast','poesjenellentheater','poeziekrant','poeziekroniek','poederlee','poeke','poelkapelle','poesele','poetin','poelmann','poels','poell','poelstra','poelmans','poelarends','poelma','poeth','poepjes','poelsma','poeran','poeste','poeze','poedelde','poedelden','poedelnaakte','poedelprijzen','poedels','poedelt','poedeltje','poedeltjes','poederblussers','poederde','poederden','poederdonzen','poederdozen','poederkwasten','poeders','poedert','poedertje','poedertjes','poedervormige','poefs','poeierde','poeierden','poeiers','poeiert','poeiertje','poeiertjes','poeliers','poeljen','poeljes','poelslakken','poelsnippen','poeltje','poeltjes','poemas','poemaatje','poemaatjes','poenerige','poenige','poeniger','poenigste','poeperds','poepertje','poepertjes','poept','poepte','poepten','poerde','poerden','poert','poesen','poesjenellen','poesjes','poeslieve','poetsdoeken','poetslappen','poetst','poetste','poetsten','poezele','poezelige','poezeliger','poezeligst','poezeligste','poemata','poemen','poetasters','poeten','poetische','poetischer','poetiseert','poeziealbums','poeziebundels','poezieliefhebbers','poedelhonden','poederige','poefen','poepende','poerimfeesten','poesjenellenkelders','poetsdozen','poetsvrouwen','poezige','poetiseerde','poeziefestivals','poestas','poesmooie','poetsers','poeticale','poepbruine','poepgaatje','poeticas','poepdozen','poencontracten','poepgaten','poetsextracten','poemas','poesisleraars','poesisleraren','poetins','poepje','poepjes','poepluiers','poetsbeurten','poetsmiddelen','poezieavonden','poezielezers','poetsdoekjes','poezieprijzen','poepbroeken','poeziewedstrijden','poedercoatings','poetsdoekje','poelkikkers','poepgaatjes','poezietijdschriften','poeziekritieken'} |
project "Air-Engine"
kind "StaticLib"
language "C++"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
targetdir ("%{wks.location}/bin/" .. outputdir .. "%{prj.name}")
objdir ("%{wks.location}/bin/" .. outputdir .. "%{prj.name}/int")
files {
"src/**.h",
"src/**.hpp",
"src/**.cpp"
}
defines {
"GLEW_STATIC"
}
includedirs {
"Dependencies/glad/include",
"src"
}
links {
"opengl32",
"glad"
}
pchheader "airpch.h"
pchsource "src/airpch.cpp"
filter "configurations:Debug"
optimize "Debug"
symbols "Full"
defines {
"_DEBUG",
"AIR_BUILD_DEBUG",
"AIR_ASSERTIONS_ENABLED",
"AIR_ENABLE_LOGGING"
}
filter "configurations:Release"
optimize "On"
defines {
"AIR_BUILD_RELEASE",
"AIR_ENABLE_LOGGING"
}
filter "configurations:Distribution"
optimize "Full"
symbols "Off"
defines {
"AIR_BUILD_DISTR",
"AIR_ENABLE_LOGGING"
}
filter "system:windows"
defines {
"AIR_PLATFORM_WINDOWS"
} |
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("cl_hooks.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
resource.AddSingleFile("materials/icon64/arcade_cabinet.png")
resource.AddSingleFile("models/props_arcade/cabinet/cabinet.mdl")
resource.AddSingleFile("models/props_arcade/cabinet/cabinet.phy")
resource.AddSingleFile("models/props_arcade/cabinet/cabinet.sw.vtx")
resource.AddSingleFile("models/props_arcade/cabinet/cabinet.vvd")
resource.AddSingleFile("models/props_arcade/cabinet/cabinet.dx80.vtx")
resource.AddSingleFile("models/props_arcade/cabinet/cabinet.dx90.vtx")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet.vmt")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet_artwork.vmt")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet_driving.vmt")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet_artwork_driving.vmt")
resource.AddSingleFile("materials/models/props_arcade/cabinet/cabinet_artwork_normal.vtf")
resource.AddSingleFile("materials/models/props_arcade/cabinet/cabinet_artwork_driving_normal.vtf")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet_buttons.vmt")
resource.AddSingleFile("materials/models/props_arcade/cabinet/cabinet_buttons_normal.vtf")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet_marque.vmt")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet_marque_driving.vmt")
resource.AddSingleFile("materials/models/props_arcade/cabinet/cabinet_outerglass.vmt")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet_screen.vmt")
resource.AddFile("materials/models/props_arcade/cabinet/cabinet_wheel.vmt")
resource.AddSingleFile("materials/models/props_arcade/cabinet/cabinet_wheel_normal.vtf")
local function RecursiveAddCSGameFiles(path)
local prefix = path .. "/"
local _, dirs = file.Find(prefix .. "*", "LUA")
local files = file.Find(prefix .. "*.lua", "LUA")
for _, f in ipairs(files) do
AddCSLuaFile(prefix .. f)
end
for _, d in ipairs(dirs) do
RecursiveAddCSGameFiles(prefix .. d)
end
end
RecursiveAddCSGameFiles("arcade_cabinet_games")
RecursiveAddCSGameFiles("arcade_cabinet_lib")
AddCSLuaFile("arcade_cabinet_launcher.lua")
function ENT:SpawnFunction(ply, tr)
if not tr.Hit then return end
local ent = ents.Create(self.Class)
ent:SetPos(tr.HitPos)
ent:SetAngles(Angle(0, (ply:GetPos() - tr.HitPos):Angle().y, 0))
ent:Spawn()
ent:Activate()
ent.Owner = ply
undo.Create(self.Class)
undo.AddEntity(ent)
undo.SetPlayer(ply)
undo.Finish()
return ent
end
function ENT:Initialize()
self:SetModel("models/props_arcade/cabinet/cabinet.mdl")
self:SetUseType(SIMPLE_USE)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:PhysicsInit(SOLID_VPHYSICS)
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:EnableMotion(false)
end
-- Seat
local seat = ents.Create("prop_vehicle_prisoner_pod")
seat:SetModel("models/nova/airboat_seat.mdl")
seat:SetParent(self)
seat:SetKeyValue("vehiclescript", "scripts/vehicles/prisoner_pod.txt")
seat:SetKeyValue("limitview", "0")
seat:SetLocalPos(Vector(30, 0, -7))
seat:SetLocalAngles(Angle(0, 90, 0))
-- Can't use nodraw on server as entity will not be networked
seat:SetRenderMode(RENDERMODE_NONE)
seat:DrawShadow(false)
seat:Spawn()
seat:SetNotSolid(true)
self:DeleteOnRemove(seat)
timer.Simple(0.05, function() -- Thanks gmod
self:SetSeat(seat)
self:OnSeatCreated("Seat", NULL, seat)
seat:SetOwner(self:GetOwner())
end)
self.CanLeaveVehicle = false
end
function ENT:Think()
if self:GetSeat():GetDriver() ~= self:GetPlayer() then
self:SetPlayer(self:GetSeat():GetDriver())
self:SetCoins(0)
end
self:NextThink(CurTime() + 0.1)
return true
end
function ENT:Use(activator, caller)
if not IsValid(activator) or not activator:IsPlayer() then return end
if not IsValid(self:GetPlayer()) then
self:SetPlayer(activator)
self:GetPlayer():EnterVehicle(self:GetSeat())
self:GetSeat().CanLeaveVehicle = false
self:GetPlayer().ArcadeWasAllowedWeaponsInVehicle = self:GetPlayer():GetAllowWeaponsInVehicle()
self:GetPlayer():SetAllowWeaponsInVehicle(false)
end
end
function ENT:OnRemove()
end
hook.Add("PlayerLeaveVehicle", "arcade_cabinet_leavevehicle", function(ply, veh)
if not IsValid(veh.ArcadeCabinet) then return end
ply:SetPos(veh:GetPos() + veh:GetForward() * -10 + veh:GetUp() * 10)
ply:SetEyeAngles((veh.ArcadeCabinet:GetPos() - ply:EyePos()):Angle())
end)
util.AddNetworkString("arcade_cabinet_insertcoin")
net.Receive("arcade_cabinet_insertcoin", function(len, ply)
local veh = ply:GetVehicle()
if not IsValid(veh) or not IsValid(veh.ArcadeCabinet) or veh.ArcadeCabinet:GetPlayer() ~= ply then return end
local cost = veh.ArcadeCabinet:GetCost()
if cost > 0 and veh.ArcadeCabinet:GetPlayer() == ply and hook.Run("ArcadeCabinetInsertCoin", ply, cost) == false then
return
end
veh.ArcadeCabinet:SetCoins(veh.ArcadeCabinet:GetCoins() + 1)
end)
util.AddNetworkString("arcade_cabinet_takecoins")
net.Receive("arcade_cabinet_takecoins", function(len, ply)
local veh = ply:GetVehicle()
if not IsValid(veh) or not IsValid(veh.ArcadeCabinet) or veh.ArcadeCabinet:GetPlayer() ~= ply then return end
local amount = net.ReadInt(16)
if not amount or amount > veh.ArcadeCabinet:GetCoins() then return end
veh.ArcadeCabinet:SetCoins(veh.ArcadeCabinet:GetCoins() - amount)
end) |
-- score.lua
score = {}
function score:load()
-- Score of each player
self.scoreP1 = 0
self.scoreP2 = 0
-- Load font and color
self.font = love.graphics.newFont("fonts/HelvetiPixel.ttf", 100)
self.color = {0, 0, 0, 255/255}
end
function score:update(dt)
if self.scoreP1 == 6 or self.scoreP2 == 6 or love.keyboard.isDown("q") then
currentScene = "quit"
end
end
function score:draw()
love.graphics.setColor(self.color)
love.graphics.setFont(self.font)
love.graphics.printf(self.scoreP1, 50, 50, love.graphics.getWidth()/2 - 70, "center")
-- love.graphics.printf("-", love.graphics.getWidth()/2 - 20, 40, 40, "center")
love.graphics.printf(self.scoreP2, love.graphics.getWidth()/2 + 20, 50, love.graphics.getWidth()/2 - 70, "center")
end
|
object_tangible_wearables_necklace_necklace_rodian_safari = object_tangible_wearables_necklace_shared_necklace_rodian_safari:new {
}
ObjectTemplates:addTemplate(object_tangible_wearables_necklace_necklace_rodian_safari, "object/tangible/wearables/necklace/necklace_rodian_safari.iff")
|
hongmoguanB_background=Class(background)
function hongmoguanB_background:init()
background.init(self,false)
LoadTexture('hongmoguanB_floor','THlib\\background\\hongmoguanB\\floor.png')
LoadImage('hongmoguanB_floor','hongmoguanB_floor',0,0,482,2780)
LoadTexture('hongmoguanB_mask','THlib\\background\\hongmoguanB\\mask.png')
LoadImage('hongmoguanB_mask','hongmoguanB_mask',0,0,256,256)
LoadImageFromFile('hongmoguanB_white','THlib\\background\\hongmoguanB\\white.png')
--
Set3D('eye',0.2,1.1,-0.2)
Set3D('at',0,0.1,5.2)
Set3D('up',0,1,0)
Set3D('fovy',0.35)
Set3D('z',1,100)
Set3D('fog',0.3,24.2,Color(0x00000000))
--
self.zos=0
self.speed=0.0015
end
function hongmoguanB_background:frame()
self.zos=self.zos+self.speed
end
function hongmoguanB_background:render()
Set3D('eye',0.2,1.1,-0.2)
Set3D('at',0,0.1,5.2)
Set3D('up',0,1,0)
Set3D('fovy',0.35)
Set3D('z',1,100)
Set3D('fog',0.3,24.2,Color(0x00000000))
SetViewMode'3d'
local showboss = IsValid(_boss)
if showboss then
PostEffectCapture()
end
Render4V('hongmoguanB_white',-200,-200,100,200,-200,100,200,200,100,-200,200,100)
local z=self.zos%1
for i=-4,4 do
Render4V('hongmoguanB_floor',-0.8,0,5.77*(1.6-z)+5.78*i,0.8,0,5.77*(1.6-z)+5.78*i,0.8,0,5.77*(0-z)+5.78*i,-0.8,0,5.77*(0-z)+5.78*i)
end
for i=-12,24 do
Render4V('hongmoguanB_mask',-1,0.2,1-6*z+i,1,0.2,1-6*z+i,1,0.2,0-6*z+i,-1,0.2,0-6*z+i)
Render4V('hongmoguanB_mask',-0.8,0.4,1-6*z+i,0.8,0.4,1-6*z+i,0.8,0.4,0-6*z+i,-0.8,0.4,0-6*z+i)
end
if showboss then
local x,y = WorldToScreen(_boss.x,_boss.y)
local x1 = x * screen.scale
local y1 = (screen.height - y) * screen.scale
local fxr = _boss.fxr or 163
local fxg = _boss.fxg or 73
local fxb = _boss.fxb or 164
PostEffectApply("boss_distortion", "", {
centerX = x1,
centerY = y1,
size = _boss.aura_alpha*200*lstg.scale_3d,
color = Color(125,fxr,fxg,fxb),
colorsize = _boss.aura_alpha*200*lstg.scale_3d,
arg=1500*_boss.aura_alpha/128*lstg.scale_3d,
timer = self.timer
})
end
SetViewMode'world'
end
|
module:set_global();
local helpers = require "util.helpers";
local function init(module, events, name)
helpers.log_events(events, name, module._log);
function module.unload()
helpers.revert_log_events(events);
end
end
init(module, prosody.events, "global");
function module.add_host(module)
init(module, prosody.hosts[module.host].events, module.host);
end
|
-----------------------------------
--
-- Zone: Talacca_Cove (57)
--
-----------------------------------
local ID = require("scripts/zones/Talacca_Cove/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/settings")
require("scripts/globals/titles")
-----------------------------------
function onInitialize(zone)
end
function onZoneIn(player, prevZone)
local cs = -1
if (player:getCurrentMission(TOAU) == tpz.mission.id.toau.TESTING_THE_WATERS and player:getCharVar("AhtUrganStatus") == 1) then
player:setPos(-88.879, -7.318, -109.233, 173)
cs = 106
elseif (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(64.007, -9.281, -99.988, 88)
end
return cs
end
function onRegionEnter(player, region)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 106) then
player:completeMission(TOAU, tpz.mission.id.toau.TESTING_THE_WATERS)
player:delKeyItem(tpz.ki.EPHRAMADIAN_GOLD_COIN)
player:addKeyItem(tpz.ki.PERCIPIENT_EYE)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.PERCIPIENT_EYE)
player:setTitle(tpz.title.TREASURE_TROVE_TENDER)
player:setCharVar("AhtUrganStatus", 0)
player:addMission(TOAU, tpz.mission.id.toau.LEGACY_OF_THE_LOST)
end
end
|
--[[
Author: Ractidous
Date: 25.01.2015.
Swaps with the sub ability and plays a sound that can be stopped.
]]
function StartSinging( event )
local caster = event.caster
local ability = event.ability
-- Swap sub_ability
local sub_ability_name = event.sub_ability_name
local main_ability_name = ability:GetAbilityName()
caster:SwapAbilities( main_ability_name, sub_ability_name, false, true )
-- Make cooldown
sub_ability = caster:FindAbilityByName( sub_ability_name )
local cooldown = sub_ability:GetCooldown( sub_ability:GetLevel() - 1 )
sub_ability:EndCooldown()
sub_ability:StartCooldown( cooldown )
-- Play the song, which will be stopped when the sub ability fires
caster:EmitSound( "Hero_NagaSiren.SongOfTheSiren" )
end
--[[
Author: Ractidous
Date: 25.01.2015.
Stops the sound and swaps the abilities back to the original state.
]]
function CancelSinging( event )
local caster = event.caster
-- Stops the song
caster:StopSound( "Hero_NagaSiren.SongOfTheSiren" )
-- Plays the cancel sound
caster:EmitSound( "Hero_NagaSiren.SongOfTheSiren.Cancel" )
end
--[[
Author: Ractidous
Date: 25.01.2015.
Swap the abilities back to the original state.
]]
function EndSinging( event )
local caster = event.caster
local ability = event.ability
-- Swap the sub_ability back to normal
local main_ability_name = ability:GetAbilityName()
local sub_ability_name = event.sub_ability_name
caster:SwapAbilities( main_ability_name, sub_ability_name, true, false )
end
--[[
Author: Noya
Date: 16.01.2015.
Levels up the ability_name to the same level of the ability that runs this
]]
function LevelUpAbility( event )
local caster = event.caster
local this_ability = event.ability
local this_abilityName = this_ability:GetAbilityName()
local this_abilityLevel = this_ability:GetLevel()
-- The ability to level up
local ability_name = event.ability_name
local ability_handle = caster:FindAbilityByName(ability_name)
local ability_level = ability_handle:GetLevel()
-- Check to not enter a level up loop
if ability_level ~= this_abilityLevel then
ability_handle:SetLevel(this_abilityLevel)
end
end |
-- Copyright © (C) Zhendong (DDJ)
--[[ init_bip_gain_timer:是日志黑名单ip收集器,也属于定时器,
但是它和redis没有交互,只需要定期将指定日志当中的非法请求ip
过滤出来,然后进行筛选,并且写入black ip zone共享空间,
实现将受到黑名单保护的location路径避免被这些ip再次访问
更新日期:
2019.03.27 11:48
shell命令的过滤规则是:
间隔时间:与定时器执行间隔相同
会过滤出访问次数默认大于等于三次的非法ip,小于三次的,
会认为可能是用户误访问。
]]
--local shell = require"resty.kerri.basic.shell"
local redis = require"resty.kerri.basic.redis_conn"
local tts = require"resty.kerri.basic.table_to_str"
local stt = require"resty.kerri.basic.str_to_table"
local sm = require"resty.kerri.basic.send_message"
local sec = require"resty.kerri.basic.get_ngx_sec"
local wbip = require"resty.kerri.black_white_ip.dynamic_bwip"
local cj = require"cjson"
local black_ip_zone = ngx.shared['black_ip_zone']
local logfile = ngx.req.get_uri_args()["logfile"]
local exptime = ngx.req.get_uri_args()["exptime"]
local count = ngx.req.get_uri_args()["count"]
local delay = ngx.req.get_uri_args()["delay"]
local log = ngx.log
local INFO = ngx.INFO
local ERR = ngx.ERR
local say = ngx.say
local timer = ngx.timer.at
local timers = ngx.timer.every
local pairs = pairs
local setmetatable = setmetatable
-- 白名单,即使被检测出来的ip,但是存在于这个列表当中,那么就不写入dict
local black_ip_white_list = {
"127.0.0.1"
}
-- 初始化函数,调用dynamic_bwip库当中的函数,来添加黑名单ip
local wb = wbip:new()
local insert = wb.add_bip
local del = wb.del_bip
-- write black ip to dict
local function write_black_ip(read_ip)
local read_ip = stt.stt(read_ip)
for num = 1, #read_ip do
-- 白名单检测
for bnum = 1, #black_ip_white_list do
if black_ip_white_list[bnum] ~= read_ip[num] then
insert(read_ip[num], exptime)
else
del(read_ip[num], 'one')
end
end
end
end
-- read logfile
-- 读取日志文件,将非法ip读出来
local function read_logfile()
-- 下面是一条完整的shell命令,用来统计当前指定阈值的ip出现次数最多的(折行)
-- before="["`date -d "-2440 minute" +%d/%b/%Y:%H:%M:%S`;now="["`date +%d/%b/%Y:%H:%M:%S`;cat black-ip-access.log |
-- awk '"'"$before"'"<$4 && "'"$now"'">$4 {{status[$1]++}}END{for( i in status){print i,status[i]}}'|sort -k2rn |uniq |
-- awk ' $2>= 3 {print $1}' |awk 'BEGIN{ORS="\", \""}{print $0}'
-- 当第一次执行的时候,dict表为空,那么需要将之前的ip一次性导入
-- 因此需要考虑到一种情况,就是不依赖redis的black名单,每次重启
-- nginx都是无状态的
-- cat black-ip-access.log| awk '{{status[$1]++}}END{for( i in status){print i,status[i]}}'|sort -k2rn |uniq |
-- awk ' $2>= 3 {print $1}' |awk 'BEGIN{ORS="\", \""}{print $0}'
--local logfile = '/home/nginx/log/errorlog/black-ip-access.log'
--local second = 266000
--local count = 3
local logfile = logfile
local second = delay
local count = count
local cmd = 'before="["`date -d "-'..second..' second" +%d/%b/%Y:%H:%M:%S`;'
..'now="["`date +%d/%b/%Y:%H:%M:%S`;cat '..logfile..'| '
.."awk '"..'"'.."'"..'"$before"'.."'"..'"<$4 && "'.."'"..'"$now"'
.."'"..'">$4 {{status[$1]++}}END{for( i in status){print i,status[i]}}'
.."'|sort -k2rn |uniq |".."awk ' $2>= "..count.." {print $1}' "
.."|awk 'BEGIN{ORS="..'"\\", \\""}{print $0}'.."'"
local init_cmd = "cat "..logfile.." | "
.."awk '{{status[$1]++}}END{for( i in status)"
.."{print i,status[i]}}'|sort -k2rn |uniq |"
.."awk ' $2>= "..count.." {print $1}' "
.."|awk 'BEGIN{ORS="..'"\\", \\""}{print $0}'.."'"
--local args = {
-- socket = "unix:/home/nginx/openresty/nginx/script/socket/shell.sock",
--}
--local status, out, err = shell.execute(cmd, args)
--say(out)
-- 查看标记是否存在,通过这个判断,这个定时器是不是第一次执行
local ok, err =
black_ip_zone:get('read_point')
if not ok then
ok = sm.sh(init_cmd)
black_ip_zone:set('read_point', '1')
else
ok = sm.sh(cmd)
end
if ok == 0 then
log(INFO, '[ INFO ]: '
..'BIP GAIN read ip'
..' current IS NULL......')
return
end
local read_ip = ok
local len = string.len(read_ip)
local read_ip = string.sub(read_ip, 0, len - 3)
local read_ip = '{"'..read_ip..'}'
log(INFO, '[ INFO ]: '
..'READ BLACK IP: '..read_ip)
return read_ip
end
-- 日志非法ip收集主函数
function gain_main()
local read_ip = read_logfile()
if read_ip then
write_black_ip(read_ip)
end
end
timer(2, gain_main)
timers(delay, gain_main)
|
function natural_affinity(keys)
local caster = keys.caster
local ability = keys.ability
local level = ability:GetLevel() - 1
local radius = ability:GetLevelSpecialValueFor("radius", level)
local block_damage = ability:GetLevelSpecialValueFor("block_damage", level)
local trees = GridNav:GetAllTreesAroundPoint(caster:GetAbsOrigin(), radius,
false)
local count = #trees * block_damage
caster:RemoveModifierByName("modifier_natural_affinity_jianshang")
if count ~= 0 then
ability:ApplyDataDrivenModifier(caster, caster,
"modifier_natural_affinity_jianshang",
{duration = -1})
caster:SetModifierStackCount("modifier_natural_affinity_jianshang",
caster, count)
end
end
|
local ffi = require "ffi"
local base = require "resty.core.base"
local C = ffi.C
local ffi_new = ffi.new
local ffi_str = ffi.string
local var = ngx.var
local type = type
local error = error
local assert = assert
local tostring = tostring
local tonumber = tonumber
local getmetatable = getmetatable
local get_request = base.get_request
local get_size_ptr = base.get_size_ptr
local get_phase = ngx.get_phase
local subsystem = ngx.config.subsystem
local NGX_OK = ngx.OK
local NGX_ERROR = ngx.ERROR
local NGX_DECLINED = ngx.DECLINED
local variable_index = {}
local metatable_patched
--Add back if stream module is implemented to aid readability
--see bottom of: https://luajit.org/ext_ffi_tutorial.html
--local ngx_lua_kong_ffi_var_get_by_index
--local ngx_lua_kong_ffi_var_set_by_index
--local ngx_lua_kong_ffi_var_load_indexes
if subsystem == "http" then
ffi.cdef[[
int ngx_http_lua_kong_ffi_var_get_by_index(ngx_http_request_t *r,
unsigned int var_index, char **value, size_t *value_len, char **err);
int ngx_http_lua_kong_ffi_var_set_by_index(ngx_http_request_t *r,
unsigned int index, const unsigned char *value, size_t value_len,
char **err);
unsigned int ngx_http_lua_kong_ffi_var_load_indexes(ngx_str_t **names);
]]
--Add back if stream module is implemented to aid readability
--see bottom of: https://luajit.org/ext_ffi_tutorial.html
--ngx_lua_kong_ffi_var_get_by_index = C.ngx_http_lua_kong_ffi_var_get_by_index
--ngx_lua_kong_ffi_var_set_by_index = C.ngx_http_lua_kong_ffi_var_set_by_index
--ngx_lua_kong_ffi_var_load_indexes = C.ngx_http_lua_kong_ffi_var_load_indexes
end
local value_ptr = ffi_new("unsigned char *[1]")
local errmsg = base.get_errmsg_ptr()
local function load_indexes()
if get_phase() ~= "init" then
error("load_indexes can only be called in init phase")
end
--Add back if stream module is implemented to aid readability
--see bottom of: https://luajit.org/ext_ffi_tutorial.html
--local count = ngx_lua_kong_ffi_var_load_indexes(nil)
local count = C.ngx_http_lua_kong_ffi_var_load_indexes(nil)
count = tonumber(count)
local names_buf = ffi_new("ngx_str_t *[?]", count)
--Add back if stream module is implemented to aid readability
--see bottom of: https://luajit.org/ext_ffi_tutorial.html
--local rc = ngx_lua_kong_ffi_var_load_indexes(names_buf)
local rc = C.ngx_http_lua_kong_ffi_var_load_indexes(names_buf)
if rc == NGX_OK then
for i = 0, count - 1 do
local name = ffi_str(names_buf[i].data, names_buf[i].len)
variable_index[name] = i
end
end
return variable_index
end
local function var_get_by_index(index)
local r = get_request()
if not r then
error("no request found")
end
local value_len = get_size_ptr()
--Add back if stream module is implemented to aid readability
--see bottom of: https://luajit.org/ext_ffi_tutorial.html
--local rc = ngx_lua_kong_ffi_var_get_by_index(r, index, value_ptr, value_len, errmsg)
local rc = C.ngx_http_lua_kong_ffi_var_get_by_index(r, index, value_ptr,
value_len, errmsg)
if rc == NGX_OK then
return ffi_str(value_ptr[0], value_len[0])
end
if rc == NGX_DECLINED then
return nil
end
assert(rc == NGX_ERROR)
error(ffi_str(errmsg[0]), 2)
end
local function var_set_by_index(index, value)
local r = get_request()
if not r then
error("no request found")
end
local value_len
if value == nil then
value_len = 0
else
if type(value) ~= 'string' then
value = tostring(value)
end
value_len = #value
end
--Add back if stream module is implemented to aid readability
--see bottom of: https://luajit.org/ext_ffi_tutorial.html
--local rc = ngx_lua_kong_ffi_var_set_by_index(r, index, value,
-- value_len, errmsg)
local rc = C.ngx_http_lua_kong_ffi_var_set_by_index(r, index, value,
value_len, errmsg)
if rc == NGX_OK then
return
end
assert(rc == NGX_ERROR)
error(ffi_str(errmsg[0]), 2)
end
local function patch_metatable()
if get_phase() ~= "init" then
error("patch_metatable can only be called in init phase")
end
if metatable_patched then
error("patch_metatable should only be called once")
end
metatable_patched = true
load_indexes()
local mt = getmetatable(var)
local orig_get = mt.__index
local orig_set = mt.__newindex
mt.__index = function(self, name)
local index = variable_index[name]
if index then
return var_get_by_index(index)
end
return orig_get(self, name)
end
mt.__newindex = function(self, name, value)
local index = variable_index[name]
if index then
return var_set_by_index(index, value)
end
return orig_set(self, name, value)
end
end
local function set_by_name(name, value)
local index = assert(variable_index[name], "nginx variable is not indexed")
return var_set_by_index(index, value)
end
local function get_by_name(name)
local index = assert(variable_index[name], "nginx variable is not indexed")
return var_get_by_index(index)
end
if subsystem == "stream" then
patch_metatable = function() end
load_indexes = function() end
set_by_name = function() end
get_by_name = function() end
end
return {
patch_metatable = patch_metatable,
load_indexes = load_indexes,
set = set_by_name,
get = get_by_name,
}
|
local typedefs = require "kong.db.schema.typedefs"
local function validate_flows(config)
if config.enable_authorization_code
or config.enable_implicit_grant
or config.enable_client_credentials
or config.enable_password_grant
then
return true
end
return nil, "at least one of these fields must be true: enable_authorization_code, enable_implicit_grant, enable_client_credentials, enable_password_grant"
end
return {
name = "oauth2",
fields = {
{ consumer = typedefs.no_consumer },
{ protocols = typedefs.protocols_http },
{ config = {
type = "record",
fields = {
{ scopes = { type = "array", elements = { type = "string" }, }, },
{ mandatory_scope = { type = "boolean", default = false, required = true }, },
{ provision_key = { type = "string", unique = true, auto = true, required = true }, },
{ token_expiration = { type = "number", default = 7200, required = true }, },
{ enable_authorization_code = { type = "boolean", default = false, required = true }, },
{ enable_implicit_grant = { type = "boolean", default = false, required = true }, },
{ enable_client_credentials = { type = "boolean", default = false, required = true }, },
{ enable_password_grant = { type = "boolean", default = false, required = true }, },
{ hide_credentials = { type = "boolean", default = false, required = true }, },
{ accept_http_if_already_terminated = { type = "boolean", default = false, required = true }, },
{ anonymous = { type = "string" }, },
{ global_credentials = { type = "boolean", default = false, required = true }, },
{ auth_header_name = { type = "string", default = "authorization" }, },
{ refresh_token_ttl = { type = "number", default = 1209600, required = true }, },
{ reuse_refresh_token = { type = "boolean", default = false, required = true }, },
{ pkce = { type = "string", default = "lax", required = false, one_of = { "none", "lax", "strict" } }, },
},
custom_validator = validate_flows,
entity_checks = {
{ conditional = {
if_field = "mandatory_scope",
if_match = { eq = true },
then_field = "scopes",
then_match = { required = true },
}, },
},
},
},
},
}
|
local flipbook = script:FindFirstAncestor("flipbook")
local Roact = require(flipbook.Packages.Roact)
local App = require(script.Parent.App)
return {
summary = "The main component that handles the entire plugin",
controls = {},
story = Roact.createElement(App),
}
|
if not modules then modules = { } end modules ['font-otr'] = {
version = 1.001,
comment = "companion to font-ini.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
-- Okay, compressing fonts this way is rather simple but one might wonder what the gain
-- is in this time of 4K youtube movies and most of the web pages wasting space and
-- bandwidth on advertisements. For version 2 we can use "woff2_decompress" from google
-- and in a tex environment one can as well store the ttf/otf files in the tex tree. So,
-- eventually we might even remove this code when version 1 is obsolete.
local ioopen = io.open
local replacesuffix = file.replacesuffix
local readers = fonts and fonts.handlers.otf.readers
local streamreader = readers and readers.streamreader or utilities.files
local streamwriter = readers and readers.streamwriter or utilities.files
local readstring = streamreader.readstring
local readcardinal2 = streamreader.readcardinal2
local readcardinal4 = streamreader.readcardinal4
local getsize = streamreader.getsize
local setposition = streamreader.setposition
local getposition = streamreader.getposition
local writestring = streamwriter.writestring
local writecardinal4 = streamwriter.writecardinal4
local writecardinal2 = streamwriter.writecardinal2
local writebyte = streamwriter.writebyte
local decompress = zlib.decompress
directives.register("fonts.streamreader",function()
streamreader = utilities.streams
readstring = streamreader.readstring
readcardinal2 = streamreader.readcardinal2
readcardinal4 = streamreader.readcardinal4
getsize = streamreader.getsize
setposition = streamreader.setposition
getposition = streamreader.getposition
end)
local infotags = {
["os/2"] = true,
["head"] = true,
["maxp"] = true,
["hhea"] = true,
["hmtx"] = true,
["post"] = true,
["cmap"] = true,
}
local report = logs.reporter("fonts","woff")
local runner = sandbox.registerrunner {
name = "woff2otf",
method = "execute",
program = "woff2_decompress",
template = "%inputfile% %outputfile%",
reporter = report,
checkers = {
inputfile = "readable",
outputfile = "writable",
}
}
local function woff2otf(inpname,outname,infoonly)
local outname = outname or replacesuffix(inpname,"otf")
local inp = ioopen(inpname,"rb")
if not inp then
report("invalid input file %a",inpname)
return
end
local signature = readstring(inp,4)
if not (signature == "wOFF" or signature == "wOF2") then
inp:close()
report("invalid signature in %a",inpname)
return
end
local flavor = readstring(inp,4)
if not (flavor == "OTTO" or flavor == "true" or flavor == "\0\1\0\0") then
inp:close()
report("unsupported flavor %a in %a",flavor,inpname)
return
end
if signature == "wOF2" then
inp:close()
if false then
if runner then
runner {
inputfile = inpname,
outputfile = outname,
}
end
return outname, flavor
else
report("skipping version 2 file %a",inpname)
return
end
end
local out = ioopen(outname,"wb")
if not out then
inp:close()
report("invalid output file %a",outname)
return
end
local header = {
signature = signature,
flavor = flavor,
length = readcardinal4(inp),
numtables = readcardinal2(inp),
reserved = readcardinal2(inp),
totalsfntsize = readcardinal4(inp),
majorversion = readcardinal2(inp),
minorversion = readcardinal2(inp),
metaoffset = readcardinal4(inp),
metalength = readcardinal4(inp),
metaoriglength = readcardinal4(inp),
privoffset = readcardinal4(inp),
privlength = readcardinal4(inp),
}
local entries = { }
for i=1,header.numtables do
local entry = {
tag = readstring (inp,4),
offset = readcardinal4(inp),
compressed = readcardinal4(inp),
size = readcardinal4(inp),
checksum = readcardinal4(inp),
}
if not infoonly or infotags[lower(entry.tag)] then
entries[#entries+1] = entry
end
end
local nofentries = #entries
local entryselector = 0 -- we don't need these
local searchrange = 0 -- we don't need these
local rangeshift = 0 -- we don't need these
writestring (out,flavor)
writecardinal2(out,nofentries)
writecardinal2(out,entryselector)
writecardinal2(out,searchrange)
writecardinal2(out,rangeshift)
local offset = 12 + nofentries * 16
local offsets = { }
for i=1,nofentries do
local entry = entries[i]
local size = entry.size
writestring(out,entry.tag)
writecardinal4(out,entry.checksum)
writecardinal4(out,offset) -- the new offset
writecardinal4(out,size)
offsets[i] = offset
offset = offset + size
local p = 4 - offset % 4
if p > 0 then
offset = offset + p
end
end
for i=1,nofentries do
local entry = entries[i]
local offset = offsets[i]
local size = entry.size
setposition(inp,entry.offset+1)
local data = readstring(inp,entry.compressed)
if #data ~= size then
data = decompress(data)
end
setposition(out,offset+1)
writestring(out,data)
local p = 4 - offset + size % 4
if p > 0 then
for i=1,p do
writebyte(out,0)
end
end
end
inp:close()
out:close()
return outname, flavor
end
if readers then
readers.woff2otf = woff2otf
else
return woff2otf
end
|
id = 'V-38647'
severity = 'low'
weight = 10.0
title = 'The system default umask in /etc/profile must be 077.'
description = 'The umask value influences the permissions assigned to files when they are created. A misconfigured umask value could result in files with excessive permissions that can be read and/or written to by unauthorized users.'
fixtext = [=[To ensure the default umask controlled by "/etc/profile" is set properly, add or correct the "umask" setting in "/etc/profile" to read as follows:
umask 077]=]
checktext = [=[Verify the "umask" setting is configured correctly in the "/etc/profile" file by running the following command:
# grep "umask" /etc/profile
All output must show the value of "umask" set to 077, as shown in the below:
# grep "umask" /etc/profile
umask 077
If the above command returns no output, or if the umask is configured incorrectly, this is a finding.]=]
function test()
end
function fix()
end
|
local WIF_MODAL = far.Flags.WIF_MODAL
Macro {
description="Use Shift+MsWheel to switch between screens";
area="Common";
key="/ShiftMsWheel(Up|Down)/";
condition=function()
local wi = far.AdvControl("ACTL_GETWINDOWINFO")
return wi and band(wi.Flags,WIF_MODAL)==0
end;
action=function()
Keys("F12",mf.akey(1,1):match(".%l+$"),"Enter")
end;
}
|
-- Make such a thing
minetest.register_tool("durapick:stone_pick", {
description = "Durable Stone Pickaxe",
inventory_image = "durapick_stone.png",
tool_capabilities = {
full_punch_interval = 1.3,
max_drop_level=1,
groupcaps={
-- Added ability for stone pick to mine like steel pick, just slower
cracky = {times={[2]=2.0, [3]=1.00}, uses=(durapick_durability_stone * durapick_durability_factor), maxlevel=1},
},
damage_groups = {fleshy=4},
},
sound = {breaks = "default_tool_breaks"},
groups = {pickaxe = 1}
})
if durapick_previous_pick then
minetest.register_craft({
type = "shaped",
output = "durapick:stone_pick 1",
recipe = { -- Use globals to allow customized recipes
{durapick_resource_stone, "durapick:wood_pick", durapick_resource_stone},
{"", durapick_stick, ""},
{"", durapick_stick, ""}
},
})
else
minetest.register_craft({
type = "shaped",
output = "durapick:stone_pick 1",
recipe = { -- Use globals to allow customized recipes
{durapick_resource_stone, durapick_resource_stone, durapick_resource_stone},
{"", durapick_stick, ""},
{"", durapick_stick, ""}
},
})
end |
------------------------
-- Energy Steal --
------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
-- TODO: Should steal MP based on TP and not wake the mob involved.
return 1, 0, false, 65
end
|
---------------------------------------------
-- Emetic Discharge
-- Family: Bloodlapper and Brummbar
-- Description: Transfers all ailments to target
-- Type: Enfeebling
-- Utsusemi/Blink absorb: 2-3 shadows
-- Notes:
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local removables = {tpz.effect.FLASH, tpz.effect.BLINDNESS, tpz.effect.ELEGY, tpz.effect.REQUIEM, tpz.effect.PARALYSIS, tpz.effect.POISON,
tpz.effect.CURSE_I, tpz.effect.CURSE_II, tpz.effect.DISEASE, tpz.effect.PLAGUE, tpz.effect.WEIGHT, tpz.effect.BIND,
tpz.effect.BIO, tpz.effect.DIA, tpz.effect.BURN, tpz.effect.FROST, tpz.effect.CHOKE, tpz.effect.RASP, tpz.effect.SHOCK, tpz.effect.DROWN,
tpz.effect.STR_DOWN, tpz.effect.DEX_DOWN, tpz.effect.VIT_DOWN, tpz.effect.AGI_DOWN, tpz.effect.INT_DOWN, tpz.effect.MND_DOWN,
tpz.effect.CHR_DOWN, tpz.effect.ADDLE, tpz.effect.SLOW, tpz.effect.HELIX, tpz.effect.ACCURACY_DOWN, tpz.effect.ATTACK_DOWN,
tpz.effect.EVASION_DOWN, tpz.effect.DEFENSE_DOWN, tpz.effect.MAGIC_ACC_DOWN, tpz.effect.MAGIC_ATK_DOWN, tpz.effect.MAGIC_EVASION_DOWN,
tpz.effect.MAGIC_DEF_DOWN, tpz.effect.MAX_TP_DOWN, tpz.effect.MAX_MP_DOWN, tpz.effect.MAX_HP_DOWN}
local dmg = utils.takeShadows(target, 1, math.random(2,3)) --removes 2-3 shadows
--if removed more shadows than were up or there weren't any
if (dmg > 0) then
for i, effect in ipairs(removables) do
if (mob:hasStatusEffect(effect)) then
local statusEffect = mob:getStatusEffect(effect)
target:addStatusEffect(effect, statusEffect:getPower(), statusEffect:getTickCount(), statusEffect:getDuration())
mob:delStatusEffect(effect)
end
end
end
skill:setMsg(tpz.msg.basic.SKILL_NO_EFFECT) -- no effect
return 0
end
|
local t = Instance.new("Tool")
t.Parent = game.Players.d3athwish87.Backpack
t.Name = "Staff"
script.Parent = t.Parent.Parent.Character
local b = Instance.new("Part")
b.Parent = t
b.Size = Vector3.new(1,6,1)
b.BrickColor = BrickColor.new("Really black")
b.Anchored = false
b.Locked = true
b.Name = "Handle"
b.TopSurface = "Smooth"
b.BottomSurface = "Smooth"
a = Instance.new("Part")
a.Parent = t
a.Size = Vector3.new(1,1,1)
a.BrickColor = BrickColor.new("White")
a.Anchored = false
a.Locked = true
a.Name = "Handlee"
a.TopSurface = "Smooth"
a.BottomSurface = "Smooth"
w2 = Instance.new("Weld")
w2.Parent = b
w2.Part0 = a
w2.Part1 = b
w2.C0 = CFrame.fromEulerAnglesXYZ(0, 0, 0) + Vector3.new(0, -3, 0)
m1 = Instance.new("CylinderMesh")
m1.Scale = Vector3.new(0.2,1,0.2)
m1.Parent = b
m2 = Instance.new("CylinderMesh")
m2.Scale = Vector3.new(0.19,1,0.19)
m2.Parent = a
local SPL = Instance.new("SelectionPartLasso")
SPL.Parent = a
SPL.Humanoid = t.Parent.Parent.Character:findFirstChild("Humanoid")
SPL.Color = BrickColor.new("Bright red")
SPL.Part = a |
-- counted strings
local io = require "vstruct.io"
local c = {}
function c.width(n)
return nil
end
function c.unpack(fd, _, width)
assert(width)
local buf = fd:read(width)
local len = io("u", "unpack", nil, buf, width)
if len == 0 then
return ""
end
return fd:read(len)
end
function c.pack(fd, data, width)
return io("u", "pack", nil, #data, width)
.. io("s", "pack", nil, data)
end
return c
|
-- local ll1 = require 'll1.ll1'
local parser = require 'luainlua.lua.parser'
local utils = require 'luainlua.common.utils'
local re = require 'luainlua.parsing.re'
local undump = require 'luainlua.bytecode.undump'
--print(config:pretty())
--print(utils.to_list(config:follow('block')))
--print(config:follows():dot())
--ll1.yacc(parser.grammar)
-- print(utils.to_list(config:get_dependency_graph().reverse['suffixedexp\'star#1']))
--print(utils.to_list(config:first('stat')))
--local seen = {['suffixedexp\'star#1'] = true}
--for node, _, forward, reverse in config:get_dependency_graph():reverse_dfs('suffixedexp\'star#1') do
-- if seen[node] then
-- print(node)
-- for rev, tag in pairs(reverse) do
-- for suffix in pairs(tag) do
-- local first = ll1.first(config, suffix)
-- if first[''] then
-- print('', rev, utils.to_string(suffix))
-- seen[rev] = true
-- end
-- if first['LBRACE'] or first['String'] or first['LBRACK'] or first['LPAREN'] then
-- if not first[''] then print('', rev, utils.to_string(suffix)) end
-- print('', '', utils.to_list(ll1.first(config, suffix)))
-- end
-- end
-- end
-- end
--end
--ll1.yacc(parser.grammar)
--local srcs = {}
--for line in io.lines 'lua/parser.lua' do
-- table.insert(srcs, line)
--end
--debug.sethook(
-- function(...)
-- local info = debug.getinfo(2)
-- local info2 = debug.getinfo(4)
-- if not info.name and info.short_src == './lua/parser.lua' and info2.short_src == './ll1/ll1.lua' then
-- -- print("call: " .. info.short_src .. ':' .. info.currentline .. ':')
-- local local_src = srcs[info.linedefined]
-- if local_src:sub(1, #'__GRAMMAR__.grammar["') == '__GRAMMAR__.grammar["' then
-- local _, index = debug.getlocal(4, 7)
-- local _, conf = debug.getlocal(4, 1)
-- local _, state = debug.getlocal(4, 3)
-- local production = conf.configuration[state][index]
-- print(utils.to_string(production))
-- print("call: " .. info.short_src .. ':' .. info.currentline .. ':', srcs[info.linedefined])
-- end
-- end
-- end,
-- "c")
local luac = require "luainlua.luac"
local dump = require "luainlua.bytecode.dump"
local undump = require "luainlua.bytecode.undump"
--local prototype = undump.undump(function(...) print(...) end)
--for pc, op in ipairs(prototype.code) do
-- print(pc, op)
--end
--
--local foo, bytecode, prototype, dumper = luac "testing/hello_world.lua"
--dumper()
--foo()
local compiler, bytecode, prototype, dumper = luac.luac "luainlua/lua/compiler.lua"
-- dumper()
compiler = compiler()
local tree = parser(io.open("luainlua/lua/compiler.lua", 'r'):read('*all'))
local prototype = compiler(tree)
local bytecode = dump.dump(prototype)
local compiler, err = loadstring(tostring(bytecode))
compiler = compiler()
local tree = parser(io.open("luainlua/lua/compiler.lua", 'r'):read('*all'))
local prototype = compiler(tree)
local bytecode = dump.dump(prototype)
local compiler, err = loadstring(tostring(bytecode))
compiler = compiler()
local tree = parser(io.open("luainlua/testing/hello_world.lua", 'r'):read('*all'))
local prototype = compiler(tree)
local bytecode = dump.dump(prototype)
local func, err = loadstring(tostring(bytecode))
func()
--local foo = luac "testing/hello_world.lua"
--foo() |
local override_original = true --change to "true" if you want original and placed fences replaced
local function dockable(nodename)
if nodename == "default:wood" or string.find(nodename, "wallet:wall") or nodename == "default:brick" or nodename == "default:cobble" or nodename == "default:dirt" or nodename == "default:sandstone" or nodename == "default:stone" or string.find(nodename, "fences:fence_wood") or string.find(nodename, "fences:fencegate") then
return true
end
end
local function find_dock(pos, second)
if pos == nil then
return false
end
local h1 = minetest.get_node({x=pos.x+1, y=pos.y, z=pos.z})
local v1 = minetest.get_node({x=pos.x-1, y=pos.y, z=pos.z})
local r1 = minetest.get_node({x=pos.x, y=pos.y, z=pos.z+1})
local l1 = minetest.get_node({x=pos.x, y=pos.y, z=pos.z-1})
local code = 0
if dockable(l1.name) then
code = code+1
if second < 2 then
minetest.punch_node({x=pos.x, y=pos.y, z=pos.z-1})
end
end
if dockable(r1.name) then
code = code+2
if second < 2 then
minetest.punch_node({x=pos.x, y=pos.y, z=pos.z+1})
end
end
if dockable(v1.name) then
code = code+11
if second < 2 then
minetest.punch_node({x=pos.x-1, y=pos.y, z=pos.z})
end
end
if dockable(h1.name) then
code = code+21
if second < 2 then
minetest.punch_node({x=pos.x+1, y=pos.y, z=pos.z})
end
end
local me = minetest.get_node(pos)
if code > 0 then
local tmp_name = "fences:fence_wood_"..code
local tmp_node = {name=tmp_name, param1=me.param1, param2=me.param2}
if second > 0 then
local tmp_node = {name=tmp_name, param1=me.param1, param2=me.param2}
minetest.set_node(pos, tmp_node)
end
elseif code == 0 then
if second == 2 then
local tmp_node = {name="fences:fence_wood", param1=me.param1, param2=me.param2}
minetest.set_node(pos, tmp_node)
end
end
end
local function punch(pos, puncher)
if not puncher ~= '' then
find_dock(pos, 2)
elseif not puncher:is_player() then
find_dock(pos, 2)
end
end
local p0 = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16}
local p1 = {-2/16, 1/2, -2/16, -2/16, 1/2+8/16, -2/16}
local p2 = {-2/16, 1/2, 2/16, -2/16, 1/2+8/16, 2/16}
local p4 = {2/16, 1/2, -2/16, 2/16, 1/2+8/16, -2/16}
local p5 = {2/16, 1/2, 2/16, 2/16, 1/2+8/16, 2/16}
local x1 = {-2/16, 1/2-4/16, 1/16, -1/2, 1/2-1/16, -1/16} --oben(quer) -x
local x12 = {-2/16, -1/2+6/16, 1/16, -1/2, -1/2+9/16, -1/16} --unten(quer) -x
local x2 = {2/16, 1/2-4/16, -1/16, 1/2, 1/2-1/16, 1/16} --oben(quer) x
local x22 = {2/16, -1/2+6/16, -1/16, 1/2, -1/2+9/16, 1/16} --unten(quer) x
local z1 = {1/16, 1/2-4/16, -2/16, -1/16, 1/2-1/16, -1/2} --oben(quer) -z
local z12 = {1/16, -1/2+6/16, -2/16, -1/16, -1/2+9/16, -1/2} --unten(quer) -z
local z2 = {-1/16, 1/2-4/16, 2/16, 1/16, 1/2-1/16, 1/2} --oben(quer) z
local z22 = {-1/16, -1/2+6/16, 2/16, 1/16, -1/2+9/16, 1/2} --unten(quer) z
local bz1 = {1/16, 1/2-1/16, -6/16, 1/16, 1/2+8/16, -6/16} --oben_block(quer) -z 1seite
local bz11 = {-1/16, 1/2-1/16, -6/16, -1/16, 1/2+8/16, -6/16} --oben_block(quer) -z 2seite
local bz2 = {1/16, 1/2-1/16, 5/16, 1/16, 1/2+8/16, 5/16} --oben_block(quer) z 1seite
local bz21 = {-1/16, 1/2-1/16, 5/16, -1/16, 1/2+8/16, 5/16} --oben_block(quer) z 2seite
local bx1 = {-6/16, 1/2-1/16, 1/16, -6/16, 1/2+8/16, 1/16} --oben_block(quer) -x 1seite
local bx11 = {-6/16, 1/2-1/16, -1/16, -6/16, 1/2+8/16, -1/16} --oben_block(quer) -x 2seite
local bx2 = {5/16, 1/2-1/16, 1/16, 5/16, 1/2+8/16, 1/16} --oben_block(quer) x 1seite
local bx21 = {5/16, 1/2-1/16, -1/16, 5/16, 1/2+8/16, -1/16} --oben_block(quer) x 2seite
minetest.register_node("fences:fence_wood", {
description = "Wooden Fence",
tiles = {"default_wood.png"},
inventory_image = "default_fence.png",
wield_image = "default_fence.png",
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1, decorative = 1},
drop = 'fences:fence_wood',
stack_max = 64,
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {p0,p1,p2,p4,p5,}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_construct = function(pos)
find_dock(pos, 1)
end,
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
--different fence types- (1=left,2=right,3=top,4=bottom)
minetest.register_node("fences:fence_wood_1", {
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p5,
z1,z12,
bz1,bz11,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_2", {
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z2,z22,
bz2,bz21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_3", { --left+right(3)
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z1,z12,z2,z22,
bz1,bz11,bz2,bz21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_11", { --top
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
x1,x12,
bx1,bx11,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_21", { --bottom
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
x2,x22,
bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_32", { --top+bottom(32)
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
x1,x12,x2,x22,
bx1,bx11,bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_14", { --left+right(3)+ top(11) =14
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z1,z12,z2,z22,x1,x12,
bz1,bz11,bz2,bz21,bx1,bx11,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_24", { --left+right(3)+ bottom(21) =24
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z1,z12,z2,z22,x2,x22,
bz1,bz11,bz2,bz21,bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_35", { --left+right(3)+top+bottom(32) = 35
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
x1,x12,x2,x22,z1,z12,z2,z22,
bz1,bz11,bz2,bz21,bx1,bx11,bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_12", { --left(1)+top(11)=12
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z1,z12,x1,x12,
bz1,bz11,bx1,bx11,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_22", { --left(1)+bottom(21)=22
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z1,z12,x2,x22,
bz1,bz11,bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_33", { --left(1)+top+bottom(32)=33
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z1,z12,x1,x12,x2,
bz1,bz11,bx1,bx11,bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_34", { --right(2)+top+bottom(32)=34
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z2,z22,x1,x12,x2,x22,
bz2,bz21,bx1,bx11,bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_23", { --right(2)+bottom(21)=23
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z2,z22,x2,x22,
bz2,bz21,bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fence_wood_13", { --right(2)+top(11)=13
tiles = {"default_wood.png"},
paramtype = "light",
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1},
drop = 'fences:fence_wood',
sunlight_propagates = true,
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
p0,p1,p2,p4,p5,
z2,z22,x1,x12,
bz1,bz11,bx1,bx11,
}
},
selection_box = {
type = "fixed",
fixed = {-2/16, -1/2, -2/16, 2/16, 1/2, 2/16},
},
on_punch = function(pos, puncher)
punch(pos, puncher)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_alias("default:fence_wood", "fences:fence")
minetest.register_craft({
output = 'fences:fence_wood 2',
recipe = {
{'default:stick', 'default:stick', 'default:stick'},
{'default:stick', 'default:stick', 'default:stick'},
}
})
minetest.register_craft({
output = 'fences:fencegate',
recipe = {
{'default:stick', 'default:wood', 'default:stick'},
{'default:stick', 'default:wood', 'default:stick'},
}
})
local meta2
local state2 = 0
local function update_gate(pos, node)
minetest.set_node(pos, node)
end
local function punch_gate(pos, node)
meta2 = minetest.get_meta(pos)
state2 = meta2:get_int("state")
local tmp_node2
if state2 == 1 then
state2 = 0
minetest.sound_play("door_close", {gain = 0.3, max_hear_distance = 10})
tmp_node2 = {name="fences:fencegate", param1=node.param1, param2=node.param2}
else
state2 = 1
minetest.sound_play("door_open", {gain = 0.3, max_hear_distance = 10})
tmp_node2 = {name="fences:fencegate_open", param1=node.param1, param2=node.param2}
end
update_gate(pos, tmp_node2)
meta2:set_int("state", state2)
end
minetest.register_node("fences:fencegate_open", {
tiles = {"default_wood.png"},
inventory_image = "default_fence.png",
wield_image = "default_fence.png",
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
walkable = true,
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,fences=1,not_in_inventory=1,mesecon_effector_on=1},
drop = 'fences:fencegate',
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-1/2, -1/2+5/16, -1/16, -1/2+2/16, 1/2, 1/16}, --links abschluss
{1/2-2/16, -1/2+5/16, -1/16, 1/2, 1/2, 1/16}, --rechts abschluss
{-1/2, 1/2-4/16, 1/16, -1/2+2/16, 1/2-1/16, 1/2-2/16}, --oben-links(quer) x
{-1/2, -1/2+6/16, 1/16, -1/2+2/16, -1/2+9/16, 1/2-2/16}, --unten-links(quer) x
{1/2-2/16, 1/2-4/16, 1/16, 1/2, 1/2-1/16, 1/2}, --oben-rechts(quer) x
{1/2-2/16, -1/2+6/16, 1/16, 1/2, -1/2+9/16, 1/2}, --unten-rechts(quer) x
{-1/2, -1/2+6/16, 6/16, -1/2+2/16, 1/2-1/16, 1/2}, --mitte links
{1/2-2/16, 1/2-4/16, 1/2, 1/2, -1/2+9/16, 6/16}, --mitte rechts
}
},
selection_box = {
type = "fixed",
fixed = {
{-1/2, -1/2+5/16, -1/16, 1/2, 1/2, 1/16}, --gate
}
},
--on_punch = function(pos, node, puncher)
on_rightclick = function(pos, node, clicker)
punch_gate(pos, node)
end,
mesecons = {effector = {
action_on = (function(pos, node)
punch_gate(pos, node)
end),
}},
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
minetest.register_node("fences:fencegate", {
description = "Wooden Fancegate",
tiles = {"default_wood.png"},
inventory_image = "fences_fencegate.png",
wield_image = "fences_fencegate.png",
paramtype = "light",
stack_max = 16,
paramtype2 = "facedir",
sunlight_propagates = true,
walkable = true,
groups = {snappy=1,choppy=2,oddly_breakable_by_hand=2,flammable=2,mesecon_effector_on=1,fences=1, mese = 1},
drop = 'fences:fencegate',
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-1/2, -1/2+5/16, -1/16, -1/2+2/16, 1/2, 1/16}, --links abschluss
{1/2-2/16, -1/2+5/16, -1/16, 1/2, 1/2, 1/16}, --rechts abschluss
{-2/16, -1/2+6/16, -1/16, 0, 1/2-1/16, 1/16}, --mitte links
{0, -1/2+6/16, -1/16, 2/16, 1/2-1/16, 1/16}, --mitte rechts
{-2/16, 1/2-4/16, 1/16, -1/2, 1/2-1/16, -1/16}, --oben(quer) -z
{-2/16, -1/2+6/16, 1/16, -1/2, -1/2+9/16, -1/16}, --unten(quer) -z
{2/16, 1/2-4/16, -1/16, 1/2, 1/2-1/16, 1/16}, --oben(quer) z
{2/16, -1/2+6/16, -1/16, 1/2, -1/2+9/16, 1/16}, --unten(quer) z
p1,p2,p4,p5,
bx1,bx11,bx2,bx21,
}
},
selection_box = {
type = "fixed",
fixed = {
{-1/2, -1/2+5/16, -1/16, 1/2, 1/2, 1/16}, --gate
}
},
on_construct = function(pos)
me2 = minetest.get_node(pos)
meta2 = minetest.get_meta(pos)
meta2:set_int("state", 0)
state2 = 0
find_dock(pos, -1)
end,
mesecons = {effector = {
action_on = (function(pos, node)
punch_gate(pos, node)
end),
}},
on_rightclick = function(pos, node, clicker)
punch_gate(pos, node)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
find_dock(pos, -1)
end
})
if override_original == true then
minetest.register_abm({
nodenames = {"default:fence_wood"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local tmp_node3 = {name="fences:fence_wood"}
minetest.set_node(pos, tmp_node3)
minetest.punch_node(pos)
end
})
end
|
-- extract id from *id parameter
function handler.all(req, rsp)
rsp.body.extract_id = 'all'
end
|
local wk = require("which-key")
vim.opt.timeoutlen = 300
wk.setup({
plugins = {
spelling = {
enabled = true,
},
},
})
wk.register({
["space"] = "prev-buffer",
["!"] = "force-quit",
w = "write-file",
q = "quit-file",
b = {
name = "+buffer",
e = "sort-extension",
d = "sort-directory",
l = "next",
h = "prev",
q = "quit",
},
c = {
name = "+code",
e = "list-diagnostics",
-- f = "format",
n = "rename",
},
d = {
name = "+debug",
b = "toggle-breakpoint",
B = "conditional-breakpoint",
c = "continue",
d = "run-last",
h = "hover",
j = "step-into",
J = "down-callstack",
k = "step-out",
K = "up-callstack",
l = "step-over",
m = "log-breakpoint",
q = "disconnect",
Q = "restart",
u = "toggle-ui",
},
f = {
name = "+find",
b = "buffers",
B = "buitins",
d = "git-files",
e = "file-explorer",
f = "files",
h = "help",
q = "quickfix",
Q = "locallist",
r = "grep",
s = "symbols",
g = {
name = "+git",
b = "branches",
c = "commits",
l = "local-commits",
s = "status",
},
},
g = {
name = "+git",
a = "add-file",
b = "blame-file",
c = "create-commit",
d = "diff-file",
m = "commit-under-cursor",
n = "neogit",
p = "diff-pick",
h = {
name = "+hunk",
b = "blame",
p = "preview",
r = "reset",
s = "stage",
u = "unstage",
},
},
t = {
name = "+toggle",
e = "file-explorer",
g = "git-blame-line",
h = "search-highlight",
n = "line-number",
z = "zen",
},
x = {
name = "+trouble",
d = "document-diagnostics",
l = "local-list",
q = "quickfix",
w = "workspace-diagnostics",
x = "toggle",
},
["1"] = "which_key_ignore",
["2"] = "which_key_ignore",
["3"] = "which_key_ignore",
["4"] = "which_key_ignore",
["5"] = "which_key_ignore",
["6"] = "which_key_ignore",
["7"] = "which_key_ignore",
["8"] = "which_key_ignore",
["9"] = "which_key_ignore",
}, {
prefix = "<leader>",
})
|
-- powerup movement, colliding
-- similarly to the player ball.
function bonus_mvmt(w)
for i=#w.bonuses,1,-1 do
local bn=w.bonuses[i]
bn.t=bn.t or 0
bn.lethalt=bn.lethalt or 0
local args={_sc={},c=0,spd=speed(bn),i=i}
if bn.t>=8 then
collide(bn,args,w)
if args.removed then goto removed end
end
bn.dy=bn.dy+grav
bn.x=bn.x+bn.dx
bn.y=bn.y+bn.dy
--bn.dx=bn.dx*0.98
pixelperfect(bn,bn.imgdata,w.ball,w.ball.imgdata,function(args)
w.plrbonus=w.plrbonus+1
playsnd(audio.get)
rem(w.bonuses,args.i)
return true
end,args)
bn.t=bn.t+1
::removed::
end
end |
--This should be at the front of all the GLX files that use functions.
return [[
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <GL/glx.h>
#define GLE_FUNCPTR
]]
|
Locales['de'] = {
['skin_menu'] = 'Skin Menü',
['use_rotate_view'] = 'benutze ~INPUT_VEH_FLY_ROLL_LEFT_ONLY~ und ~INPUT_VEH_FLY_ROLL_RIGHT_ONLY~ um die Sicht zu drehen.',
['skin'] = 'Skin ändern',
['saveskin'] = 'Skin speichern',
['confirm_escape'] = 'do you want to cancel the skin changer? All changes go unsaved.',
['no'] = 'no',
['yes'] = 'yes',
}
|
--
-- A LUA module to verify the sender constrained token binding for a JWT sent via a Mutual TLS connection
--
local _M = {}
local b64 = require 'ngx.base64'
local ssl = require 'ngx.ssl'
local jwt = require 'resty.jwt'
local sha256 = require 'resty.sha256'
local str = require 'resty.string'
--
-- Return errors due to invalid requests or server technical problems
--
local function error_response(status, code, message)
local jsonData = '{"code":"' .. code .. '", "message":"' .. message .. '"}'
ngx.status = status
ngx.header['content-type'] = 'application/json'
ngx.say(jsonData)
ngx.exit(status)
end
--
-- Return an error message to indicate an unauthorized request
--
local function unauthorized_error_response()
error_response(ngx.HTTP_UNAUTHORIZED, 'unauthorized', 'Missing, invalid or expired access token')
end
--
-- Parse the JWT and retrieve the cnf/x5t#S256 claim issued at the time of authentication
--
local function read_token_thumbprint(jwt_text)
local jwt = jwt:load_jwt(jwt_text)
if jwt.valid and jwt.payload.cnf and jwt.payload.cnf['x5t#S256'] then
return jwt.payload.cnf['x5t#S256']
end
return nil
end
--
-- Calculate the SHA256 hash of the client certificate received via Mutual TLS
-- https://www.rfc-editor.org/rfc/rfc8705.html#section-3.1
--
local function get_sha256_thumbprint(certificate)
local der = ssl.cert_pem_to_der(certificate)
local hash = sha256:new()
hash:update(der)
local digest = hash:final()
return b64.encode_base64url(digest)
end
--
-- The public entry point to verify sender constrained access token details
--
function _M.execute(config)
if config.type ~= 'certificate-bound' then
ngx.log(ngx.WARN, 'An invalid or unsupported type parameter was received')
error_response(ngx.HTTP_INTERNAL_SERVER_ERROR, 'server_error', 'Problem encountered processing the request')
end
local auth_header = ngx.req.get_headers()['Authorization']
if auth_header and string.len(auth_header) > 7 and string.lower(string.sub(auth_header, 1, 7)) == 'bearer ' then
local access_token = string.sub(auth_header, 8)
-- Get the client certificate
if ngx.var.ssl_client_raw_cert == nil then
ngx.log(ngx.WARN, 'The request did not contain a valid client certificate')
unauthorized_error_response()
end
-- Read the thumbprint
local jwtThumbprint = read_token_thumbprint(access_token)
if jwtThumbprint == nil then
ngx.log(ngx.WARN, 'Unable to parse the x5t#S256 from the received JWT access token')
unauthorized_error_response()
end
-- Calculate the SHA256 hash of the client certificate and check it matches that in the JWT
local certThumbprint = get_sha256_thumbprint(ngx.var.ssl_client_raw_cert)
if certThumbprint ~= jwtThumbprint then
ngx.log(ngx.WARN, 'The client certificate details of the request and the JWT do not match')
unauthorized_error_response()
end
else
ngx.log(ngx.WARN, 'No valid access token was found in the HTTP Authorization header')
unauthorized_error_response(config)
end
end
return _M
|
local PLUGIN = PLUGIN
PLUGIN.name = "Notes+"
PLUGIN.author = "AleXXX_007"
PLUGIN.desc = "Write text on notes and pick up them like items."
NOTELIMIT = 10000
WRITINGDATA = WRITINGDATA or {}
nut.util.include("sv_plugin.lua")
nut.util.include("cl_vgui.lua")
if (CLIENT) then
netstream.Hook("receiveNote", function(id, contents, write)
local note = vgui.Create("noteRead")
note:allowEdit(write)
note:setText(contents)
note.id = id
end)
end
|
return {'wraak','wraakactie','wraakbaar','wraakengel','wraakgedachte','wraakgevoel','wraakgevoelens','wraakgierig','wraakgierigheid','wraakgodin','wraaklust','wraaklustig','wraakneming','wraakoefening','wraakroepend','wraakzucht','wraakzuchtig','wrak','wrake','wraken','wrakgoed','wrakgoederen','wrakhout','wraking','wrakingskamer','wrakingsverzoek','wrakker','wrakkig','wrakstuk','wrang','wrangheid','wrangwortel','wrat','wratachtig','wrattenkruid','wrattenzwijn','wrattig','wratziekte','wrap','wrattenbijter','wraakbare','wraakengelen','wraakgierige','wraakgodinnen','wraaknemingen','wraakoefeningen','wraakroepende','wraakt','wraakte','wraakten','wraakzuchtige','wraakzuchtiger','wrakingen','wrakke','wrakken','wrakstukken','wrange','wrangen','wranger','wrangere','wrangst','wrangste','wraps','wratachtige','wratten','wrattige','wraakacties','wraaklustige','wrakkige','wrattenzwijnen','wraakbaarder','wraakbaarst','wrakst','wratjes','wrakingsverzoeken'} |
--[[
--=====================================================================================================--
Script Name: Tag, for SAPP (PC & CE)
Description: Tag, you're it!
This is a game involving two or more players.
An initial game of tag is started by whacking a player.
This player will become 'it' (the tagger).
Their turn ends when they tag their first victim or their turn time is up;
If the turn time lapses before they tag someone, a new random player will be chosen to be the new tagger.
** FEATURES **
- All runners have plasma rifles and the taggers have an oddball.
The plasma rifle was a design choice, not a random decision, as it slows down the tagger when shot at.
- You will accumulate 5 points every 10 seconds as a runner.
- The score limit is 10,000.
- Taggers get a 1.5x speed boost, runners have normal speed.
- Tagging someone earns you 500 points.
- Runners cannot earn points for killing.
- This game mode is best played on medium & small maps:
timberland bloodgulch damnation longest
chillout carousel ratrace putput
prisoner wizard beavercreek hangemhigh
Copyright (c) 2022, Jericho Crosby <[email protected]>
* Notice: You can use this document subject to the following conditions:
https://github.com/Chalwk77/HALO-SCRIPT-PROJECTS/blob/master/LICENSE
--=====================================================================================================--
]]--
-- config starts:
local Tag = {
-- Game score limit:
-- Default: 10000
score_limit = 10000,
-- Points awarded for tagging someone:
-- Default: 500
points_on_tag = 500,
-- Runners will accumulate 5 points every 10 seconds while a game of tag is in play:
-- Defaults: 5 & 10
runner_points = 5,
points_interval = 10,
-- Tag turn timer (in seconds):
-- Default: 60
turn_time = 60,
-- Min players required to start a game of tag:
-- Default: 2
players_required = 2,
-- Running speed (tagger & runner):
-- Defaults: 1.5, & 1
speed = { 1.5, 1 },
-- Messages sent when someone is tagged:
on_tag = {
"Tag, you're it! ($name got you)", -- tagger sees this message.
'$name was tagged by $tagger' -- everyone else will see this message.
},
-- Message sent when someone's turn is up and we select a new random tagger:
-- Same message appears if the tagger quits and
-- 'new_tagger_on_quit' or 'new_tagger_on_death' is set to true.
random_tagger = '$name is now the tagger!',
-- When a tagger quits, should we select a new random tagger?
-- Default: true
new_tagger_on_quit = true,
-- Should we pick a new tagger if the current tagger dies?
-- Default: false
new_tagger_on_death = false,
-- A message relay function temporarily removes the server prefix
-- and will restore it to this when the relay is finished:
server_prefix = '**SAPP**'
}
-- config ends
local players = {}
local time = os.time
local tagger, game_over
local tagger_weapon_meta_id
local runner_weapon_meta_id
local tagger_weapon, runner_weapon
-- Object interaction with these tags will be disabled:
local objects = {
-- allow interaction with these objects:
--'powerups\\health pack',
--'powerups\\over shield',
--'powerups\\active camouflage',
-- block interaction with these objects:
'weapons\\frag grenade\\frag grenade',
'weapons\\plasma grenade\\plasma grenade',
'vehicles\\ghost\\ghost_mp',
'vehicles\\rwarthog\\rwarthog',
'vehicles\\banshee\\banshee_mp',
'vehicles\\warthog\\mp_warthog',
'vehicles\\scorpion\\scorpion_mp',
'vehicles\\c gun turret\\c gun turret_mp',
'weapons\\ball\\ball',
'weapons\\flag\\flag',
'weapons\\pistol\\pistol',
'weapons\\shotgun\\shotgun',
'weapons\\needler\\mp_needler',
'weapons\\flamethrower\\flamethrower',
'weapons\\plasma rifle\\plasma rifle',
'weapons\\sniper rifle\\sniper rifle',
'weapons\\plasma pistol\\plasma pistol',
'weapons\\plasma_cannon\\plasma_cannon',
'weapons\\assault rifle\\assault rifle',
'weapons\\rocket launcher\\rocket launcher'
}
-- New Player has joined:
-- * Creates a new player table; Inherits the Tag parent object.
-- @Param o (player table [table])
-- @Return o (player table [table])
function Tag:NewPlayer(o)
setmetatable(o, self) -- inherit the .__index of Tag.
self.__index = self
-- Variable for weapon assignments:
o.assign = true
-- Holds the object id of the players weapon:
o.drone = ''
-- Stores the id of the person who just killed you:
o.killer = 0
return o
end
-- Returns true if this player is the tagger:
function Tag:IsTagger()
return (self.pid == tagger)
end
-- Sets running speed of all players:
-- @Param last_man (id of the last person online):
function Tag:SetSpeed(last_man)
execute_command('s ' .. self.pid .. ' ' .. self.speed[1])
for i, v in pairs(players) do
if (i ~= self.pid or i == last_man) then
execute_command('s ' .. i .. ' ' .. v.speed[2])
end
end
end
local function SetPeriodicTimers()
for i, v in pairs(players) do
if (i == tagger) then
v.periodic_scoring = false
-- only do this if it's not already set:
elseif (not v.periodic_scoring) then
v:NewRunnerTime()
end
end
end
-- Sets the tagger:
-- @Param TaggerName (name of the person who just tagged someone) [string]
function Tag:SetTagger(TaggerName)
tagger = self.pid
self.assign = true
self.periodic_scoring = false
self:NewTurnTime()
self:SetSpeed()
SetPeriodicTimers()
if (TaggerName) then
local t_msg = self.on_tag[1]
local to_tagger = t_msg:gsub('$name', TaggerName)
local r_msg = self.on_tag[2]
local to_runner = r_msg:gsub('$name', self.name):gsub('$tagger', TaggerName)
for i, v in pairs(players) do
if (i == tagger) then
v:Broadcast(to_tagger, true)
else
v:Broadcast(to_runner, true)
end
end
return
end
local msg = self.random_tagger
msg = msg:gsub('$name', self.name)
self:Broadcast(msg)
end
-- Resets turn timer variables:
function Tag:NewTurnTime()
self.turn_start = time
self.turn_finish = time() + self.turn_time
end
-- Timer variables used to periodically update runner score:
function Tag:NewRunnerTime()
self.periodic_scoring = true
self.runner_start = time
self.runner_finish = time() + self.points_interval
end
-- Function responsible for handling scoring:
function Tag:UpdateScore(Deduct, RunnerPoints)
local score = tonumber(get_var(self.pid, '$score'))
-- prevent player from scoring from last kill:
if (Deduct) then
score = (score - 1 < 0 and 0 or score - 1)
elseif (not RunnerPoints) then
score = score + self.points_on_tag -- update tagger points
else
score = score + self.runner_points -- update runner points
end
execute_command('score ' .. self.pid .. ' ' .. score)
end
-- Binds nav marker to tagger:
function Tag:SetNav()
local player = get_player(self.pid)
if (tagger and self.pid ~= tagger) then
write_word(player + 0x88, to_real_index(tagger))
else
write_word(player + 0x88, to_real_index(self.pid))
end
end
-- Returns the MetaID of the tag address:
-- @Param Type (tag class)
-- @Param Name (tag path)
-- @Return tag address [number]
local function GetTag(Type, Name)
local ObjTag = lookup_tag(Type, Name)
return (ObjTag ~= 0 and read_dword(ObjTag + 0xC)) or nil
end
-- Sends a server-wide message:
-- * Temporarily removes the server prefix.
-- @Params msg (message string)
function Tag:Broadcast(msg, pm)
execute_command('msg_prefix ""')
if (not pm) then
say_all(msg)
else
say(self.pid, msg)
end
execute_command('msg_prefix "' .. self.server_prefix .. '"')
end
-- Destroy the players weapon:
-- @Param Assign [boolean], true if we need to trigger weapon a assignment.
function Tag:DeleteDrone(Assign)
destroy_object(self.drone)
self.assign = Assign
end
-- Weapon assignment logic:
function Tag:AssignWeapons()
-- Assign appropriate weapons:
if (self.assign) then
self.assign = false
execute_command_sequence('nades ' .. self.pid .. ' 0; wdel ' .. self.pid)
local weapon = (tagger == self.pid and tagger_weapon or runner_weapon)
self.drone = spawn_object('', '', 0, 0, -9999, 0, weapon)
assign_weapon(self.drone, self.pid)
end
end
-- Determines if enough players are online for a game of tag:
-- @Param quit [boolean], true if we need to deduct 1 from n:
-- SAPP var $pn does not update immediately after a player quits,
-- so we have to deduct one manually.
function Tag:EnoughPlayers(quit)
local n = tonumber(get_var(0, '$pn'))
n = (quit and n - 1 or n)
return (n >= self.players_required)
end
-- Picks a random player to become the tagger.
-- Excludes the previous tagger.
-- @Param quit (boolean), true if we need to deduct 1 from n in EnoughPlayers().
function Tag:PickRandomTagger(quit)
if not self:EnoughPlayers(quit) then
tagger = nil
self:SetSpeed(self.pid)
self:Broadcast('Game of tag has ended. Not enough players.')
return
end
-- Trigger weapon assignment for previous tagger:
self.assign = true
-- set candidates:
local t = {}
for i = 1, #players do
if (player_present(i) and i ~= tagger) then
t[#t + 1] = i
end
end
-- Pick and set new tagger from t{}:
if (#t > 0) then
players[t[rand(1, #t + 1)]]:SetTagger()
end
end
-- Disables interaction with game objects (on start).
-- Enables interaction when OnScriptUnload() is called.
local function GameObjects(state)
state = (state and 'enable_object') or 'disable_object'
for i = 1, #objects do
execute_command(state .. ' "' .. objects[i] .. '" 0')
end
end
-- Called when a new game has started:
function OnStart()
if (get_var(0, '$gt') ~= 'n/a') then
tagger_weapon_meta_id = GetTag('jpt!', 'weapons\\ball\\melee')
runner_weapon_meta_id = GetTag('jpt!', 'weapons\\plasma rifle\\melee')
tagger_weapon = GetTag('weap', 'weapons\\ball\\ball')
runner_weapon = GetTag('weap', 'weapons\\plasma rifle\\plasma rifle')
-- set up game tables:
game_over = false
players, tagger = {}, nil
-- disable game objects:
GameObjects(false)
-- Set the score limit:
execute_command('scorelimit ' .. Tag.score_limit)
-- Init player tables (happens if the script is loaded during a match):
for i = 1, 16 do
if player_present(i) then
OnJoin(i)
end
end
end
end
-- Called when the game has ended:
function OnEnd()
game_over = true
end
-- Called every 1/30th second:
function OnTick()
for i, v in pairs(players) do
if (not game_over and player_present(i) and player_alive(i)) then
v:SetNav()
v:AssignWeapons()
execute_command('battery ' .. i .. ' 100')
if (v:IsTagger() and v.turn_start() >= v.turn_finish) then
v:PickRandomTagger()
-- Update runner score periodically:
elseif (v.periodic_scoring and v.runner_start() >= v.runner_finish) then
v:NewRunnerTime()
v:UpdateScore(false, true) -- update runner points
end
end
end
end
-- Called when a player receives damage or is killed:
-- @Param Victim (victim id) [number]
-- @Param Causer (killer id) [number]
-- @Param MetaID (DamageTagID) [number]
function OnDamage(Victim, Causer, MetaID)
local killer = tonumber(Causer)
local victim = tonumber(Victim)
local k = players[killer]
local v = players[victim]
if (not game_over and killer > 0 and k and v and k:EnoughPlayers()) then
--
-- event_damage_application:
--
if (MetaID) then
-- Prevent runners from attacking each other:
if (tagger and not k:IsTagger() and not v:IsTagger()) then
return false
end
local case1 = (not tagger and MetaID == runner_weapon_meta_id or k:IsTagger())
local case2 = (tagger and MetaID == tagger_weapon_meta_id)
if (killer ~= victim) and (case1 or case2) then
k.assign = true -- trigger weapon assignment
v.killer = killer -- keep track of the player who just killed you
k:UpdateScore() -- update current tagger score
k:NewRunnerTime() -- reset periodic scoring for this player
v:SetTagger(k.name) -- make victim the tagger
end
return
end
--
-- event_die:
--
v:DeleteDrone() -- prevent weapon drop
k:UpdateScore(true) -- prevent this kill from being counted towards score
if (v.new_tagger_on_death and v:IsTagger() and v.killer ~= killer) then
v:PickRandomTagger()
end
end
end
-- Called when a player has finished connecting:
-- @Param P (player id) [number]
function OnJoin(Ply)
players[Ply] = Tag:NewPlayer({
pid = Ply,
name = get_var(Ply, '$name')
})
end
-- Called when a player has quit:
-- * Nullifies the table for this player.
-- @Param P (player id) [number]
function OnQuit(Ply)
local t = players[Ply]
-- Pick a random player to be the tagger:
if (not game_over and t.new_tagger_on_quit and t:IsTagger()) then
t:PickRandomTagger(true)
end
t:DeleteDrone() -- delete their dropped weapon
players[Ply] = nil
end
-- Called when a player has finished respawning:
-- @Param P (player id) [number]
-- Triggers weapon assignment
function OnSpawn(Ply)
local t = players[Ply]
t.assign = true
t.killer = 0
if (t:IsTagger()) then
t:SetSpeed() -- just in case
elseif (tagger) then
t:NewRunnerTime() -- only do this if a game of tag is in play:
end
end
-- Called when a player drops a weapon.
-- Makes a call to destroy their weapon.
function OnDrop(Ply)
players[Ply]:DeleteDrone(true)
end
-- Registers needed event callbacks for SAPP:
function OnScriptLoad()
register_callback(cb['EVENT_TICK'], 'OnTick')
register_callback(cb['EVENT_JOIN'], 'OnJoin')
register_callback(cb['EVENT_SPAWN'], 'OnSpawn')
register_callback(cb['EVENT_DIE'], 'OnDamage')
register_callback(cb['EVENT_LEAVE'], 'OnQuit')
register_callback(cb['EVENT_GAME_END'], 'OnEnd')
register_callback(cb['EVENT_WEAPON_DROP'], 'OnDrop')
register_callback(cb['EVENT_GAME_START'], 'OnStart')
register_callback(cb['EVENT_DAMAGE_APPLICATION'], 'OnDamage')
OnStart()
end
function OnScriptUnload()
GameObjects(true)
end
api_version = '1.12.0.0' |
----------------------------------------------------------------------------------------------------
-- localized English (tooltip module) strings
--
--get the add-on engine
local AddOnName = ...;
--prepare locale
local L = LibStub("AceLocale-3.0"):NewLocale(AddOnName, "enUS", true);
if not L then return; end
--tooltip module
L["TOOLTIP_MODULE"] = "Tooltip";
L["TOOLTIP_MODULE_ENABLE"] = "Enable Tooltip Changes";
L["TOOLTIP_MODULE_ENABLE_DESC"] = "Attach an additional tooltip with the item details";
L["TOOLTIP_CUSTOMIZE"] = "Customize tooltip";
L["TOOLTIP_CUSTOMIZE_DESC"] = "Enable to customize the appearance of the tooltip";
L["TOOLTIP_COLOR"] = "Tooltip color";
L["TOOLTIP_COLOR_DESC"] = "Change the tooltip color"; |
local K, C = unpack(select(2, ...))
local Module = K:GetModule("Announcements")
local _G = _G
local string_format = _G.string.format
local table_wipe = _G.table.wipe
local date = _G.date
local C_VignetteInfo_GetVignetteInfo = _G.C_VignetteInfo.GetVignetteInfo
local GetAtlasInfo = _G.GetAtlasInfo
local GetInstanceInfo = _G.GetInstanceInfo
local UIErrorsFrame = _G.UIErrorsFrame
local RareAlertCache = {}
local isIgnored = {
[1153] = true, -- Horde Fortress
[1159] = true, -- Alliance fortress
[1803] = true, -- Yongquan Beach
[1876] = true, -- Tribal torrent
[1943] = true, -- Alliance Rapids
[2111] = true, -- Black coast front
}
function Module:RareAlert_Update(id)
if id and not RareAlertCache[id] then
local info = C_VignetteInfo_GetVignetteInfo(id)
if not info then
return
end
local filename, width, height, txLeft, txRight, txTop, txBottom = GetAtlasInfo(info.atlasName)
if not filename then
return
end
local atlasWidth = width / (txRight-txLeft)
local atlasHeight = height / (txBottom-txTop)
local tex = string_format("|T%s:%d:%d:0:0:%d:%d:%d:%d:%d:%d|t", filename, 0, 0, atlasWidth, atlasHeight, atlasWidth * txLeft, atlasWidth * txRight, atlasHeight * txTop, atlasHeight * txBottom)
-- UIErrorsFrame:AddMessage(K.InfoColor.."Rare Nearby!"..tex..(info.name or ""))
local currrentTime = C["Chat"].TimestampFormat.Value == 1 and "|cff00ff00["..date("%H:%M:%S").."]|r" or ""
K.Print(currrentTime.." >> "..K.InfoColor.."Rare nearby!"..tex..(info.name or ""))
RareAlertCache[id] = true
end
if #RareAlertCache > 666 then
table_wipe(RareAlertCache)
end
end
function Module:RareAlert_CheckInstance()
local _, instanceType, _, _, maxPlayers, _, _, instID = GetInstanceInfo()
if (instID and isIgnored[instID]) or (instanceType == "scenario" and (maxPlayers == 3 or maxPlayers == 6)) then
K:UnregisterEvent("VIGNETTE_MINIMAP_UPDATED", Module.RareAlert_Update)
else
K:RegisterEvent("VIGNETTE_MINIMAP_UPDATED", Module.RareAlert_Update)
end
end
function Module:CreateRareAnnounce()
if C["Announcements"].RareAlert then
self:RareAlert_CheckInstance()
K:RegisterEvent("PLAYER_ENTERING_WORLD", self.RareAlert_CheckInstance)
else
table_wipe(RareAlertCache)
K:UnregisterEvent("VIGNETTE_MINIMAP_UPDATED", self.RareAlert_Update)
K:UnregisterEvent("PLAYER_ENTERING_WORLD", self.RareAlert_CheckInstance)
end
end |
local menu = {}
function menu:control_button(command, menuState)
if command == Command.Deny then
self.isClosed = true
end
end
function menu:draw()
love.graphics.print("In development...", 20, 20)
end
return menu |
require('plugset.packer')
require('plugset.compe')
require('plugset.lspconfig')
|
SetFlyThroughWindscreenParams(Config.ejectVelocity, Config.unknownEjectVelocity, Config.unknownModifier, Config.minDamage);
local seatbeltOn = false
local ped = nil
local uiactive = false
Citizen.CreateThread(function()
while true do
ped = PlayerPedId()
Citizen.Wait(500)
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(10)
if IsPedInAnyVehicle(ped) then
if seatbeltOn then
if Config.fixedWhileBuckled then
DisableControlAction(0, 75, true) -- Disable exit vehicle when stop
DisableControlAction(27, 75, true) -- Disable exit vehicle when Driving
end
toggleUI(false)
else
toggleUI(true)
end
else
if seatbeltOn then
seatbeltOn = false
toggleSeatbelt(false, false)
end
toggleUI(false)
Citizen.Wait(1000)
end
end
end)
function toggleSeatbelt(makeSound, toggle)
if toggle == nil then
if seatbeltOn then
playSound("unbuckle")
SetFlyThroughWindscreenParams(Config.ejectVelocity, Config.unknownEjectVelocity, Config.unknownModifier, Config.minDamage)
else
playSound("buckle")
SetFlyThroughWindscreenParams(10000.0, 10000.0, 17.0, 500.0);
end
seatbeltOn = not seatbeltOn
else
if toggle then
playSound("buckle")
SetFlyThroughWindscreenParams(10000.0, 10000.0, 17.0, 500.0);
else
playSound("unbuckle")
SetFlyThroughWindscreenParams(Config.ejectVelocity, Config.unknownEjectVelocity, Config.unknownModifier, Config.minDamage)
end
seatbeltOn = toggle
end
end
function toggleUI(status)
if Config.showUnbuckledIndicator then
if uiactive ~= status then
uiactive = status
if status then
SendNUIMessage({type = "showindicator"})
else
SendNUIMessage({type = "hideindicator"})
end
end
end
end
function playSound(action)
if Config.playSound then
if Config.playSoundForPassengers then
local veh = GetVehiclePedIsUsing(ped)
local maxpeds = GetVehicleMaxNumberOfPassengers(veh) - 2
local passengers = {}
for i = -1, maxpeds do
if not IsVehicleSeatFree(veh, i) then
local ped = GetPlayerServerId( NetworkGetPlayerIndexFromPed(GetPedInVehicleSeat(veh, i)) )
table.insert(passengers, ped)
end
end
TriggerServerEvent('seatbelt:server:PlaySound', action, json.encode(passengers))
else
SendNUIMessage({type = action, volume = Config.volume})
end
end
end
RegisterCommand('toggleseatbelt', function(source, args, rawCommand)
if IsPedInAnyVehicle(ped, false) then
local class = GetVehicleClass(GetVehiclePedIsIn(ped))
if class ~= 8 and class ~= 13 and class ~= 14 then
toggleSeatbelt(true)
end
end
end, false)
RegisterNetEvent('seatbelt:client:PlaySound')
AddEventHandler('seatbelt:client:PlaySound', function(action, volume)
SendNUIMessage({type = action, volume = volume})
end)
exports("status", function() return seatbeltOn end)
RegisterKeyMapping('toggleseatbelt', 'Toggle Seatbelt', 'keyboard', 'B')
|
function count(s)
function mapper(rec)
return 1
end
local function reducer(v1, v2)
return v1 + v2
end
return s : map(mapper) : reduce(reducer)
end |
local Prop = {}
Prop.Name = "Kelle Co."
Prop.Cat = "Warehouse"
Prop.Price = 850
Prop.Doors = {
Vector( -13378.000000, 12119.000000, -13386.000000 ),
}
GM.Property:Register( Prop ) |
object_tangible_loot_loot_schematic_imperial_gunner_helmet_schematic = object_tangible_loot_loot_schematic_shared_imperial_gunner_helmet_schematic:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_loot_schematic_imperial_gunner_helmet_schematic, "object/tangible/loot/loot/schematic/imperial_gunner_helmet_schematic.iff")
|
local mod_gui = require("__core__.lualib.mod-gui")
local function create_mod_gui_button(player)
-- Disabled for now, until button looks better (should be darker and should show magnifying glass)
if true then return end
local button_flow = mod_gui.get_button_flow(player)
if button_flow.search_engine then
return
end
button_flow.add {
type = "button",
name = "search_engine",
style = mod_gui.button_style,
sprite = "search_engine_magnify",
tooltip = { "search_engine.search_engine" },
tags = {
[script.mod_name] = {
flib = {
on_click = "open_search_window"
}
}
}
}
end
local function frame_action_button()
return {
type = "sprite-button",
style = "frame_action_button",
actions = {
on_click = "close_window"
}
}
end
local function header()
return {
type = "flow", ref = {"titlebar", "flow"},
children = {
{type = "label", style = "frame_title", caption = {"search_engine.header"}, ignored_by_interaction = true},
{type = "empty-widget", style = "flib_titlebar_drag_handle", ignored_by_interaction = true},
frame_action_button()
}
}
end
return {
create_mod_gui_button = create_mod_gui_button,
header = header
}
|
i = 0
while i < 1000 do
-- i = discard_origin(i + 1)
i = i + 1
end
assert(i == 1000)
|
local OpCodes = require "cheese.luanetc.opcodes"
module(..., package.seeall)
luavalue_type = "object"
luavalue_array_type = "object[]"
luavalue_ref = "object [lua]Lua.UpValue::Ref"
luavalue_ref_type = "class [lua]Lua.UpValue"
luavalue_ref_cons = "instance void [lua]Lua.UpValue::.ctor()"
luaref_type = "class [lua]Lua.Reference"
int4_type = "int32"
double_type = "float64"
array_copy = "void [mscorlib]System.Array::Copy(class [mscorlib]System.Array,int32,class [mscorlib]System.Array,int32,int32)"
env_field = "class [lua]Lua.Reference [lua]Lua.Closure::Env"
closure_cons = "instance void [lua]Lua.Closure::.ctor()"
symbol_intern = "class [lua]Lua.Symbol [lua]Lua.Symbol::Intern(string)"
string_cons = "instance void [lua]Lua.String::.ctor()"
table_cons = "instance void [lua]Lua.Table::.ctor()"
nil_singleton = "class [lua]Lua.Reference [lua]Lua.Nil::Instance"
false_singleton = "class [lua]Lua.Reference [lua]Lua.False::Instance"
true_singleton = "class [lua]Lua.Reference [lua]Lua.True::Instance"
gettable_method = "instance object [lua]Lua.Reference::get_Item(object)"
gettable_symbol_method = "instance object [lua]Lua.Reference::get_Item(class [lua]Lua.Symbol)"
gettable_number_method = "instance object [lua]Lua.Reference::get_Item(float64)"
settable_method = "instance void [lua]Lua.Reference::set_Item(object, object)"
settable_symbol_method = "instance void [lua]Lua.Reference::set_Item(class [lua]Lua.Symbol, object)"
settable_number_method = "instance void [lua]Lua.Reference::set_Item(float64, object)"
neg_method = "instance object [lua]Lua.Reference::Negate()"
len_method = "instance object [lua]Lua.Reference::Length()"
concat_method = "object [lua]Lua.Reference::Concat(object, object)"
arith_method = {
add = "instance object [lua]Lua.Reference::Add(object)",
sub = "instance object [lua]Lua.Reference::Subtract(object)",
mul = "instance object [lua]Lua.Reference::Multiply(object)",
div = "instance object [lua]Lua.Reference::Divide(object)",
rem = "instance object [lua]Lua.Reference::Mod(object)",
exp = "instance object [lua]Lua.Reference::Pow(object)"
}
arith_method_slow = {
add = "instance object [lua]Lua.Reference::Add(float64)",
sub = "instance object [lua]Lua.Reference::Subtract(float64)",
mul = "instance object [lua]Lua.Reference::Multiply(float64)",
div = "instance object [lua]Lua.Reference::Divide(float64)",
rem = "instance object [lua]Lua.Reference::Mod(float64)",
exp = "instance object [lua]Lua.Reference::Pow(float64)"
}
rel_method = {
beq = "instance bool [lua]Lua.Reference::Equals(class [lua]Lua.Reference)",
bne = "instance bool [lua]Lua.Reference::NotEquals(class [lua]Lua.Reference)",
blt = "instance bool [lua]Lua.Reference::LessThan(class [lua]Lua.Reference)",
bgt = "instance bool [lua]Lua.Reference::GreaterThan(class [lua]Lua.Reference)",
ble = "instance bool [lua]Lua.Reference::LessThanOrEquals(class [lua]Lua.Reference)",
bge = "instance bool [lua]Lua.Reference::GreaterThanOrEquals(class [lua]Lua.Reference)"
}
max_args = 7
local function call_with(nargs, nres)
local ret_type, invoke_name
if not nres or nres == 0 or nres == 1 then
ret_type = "object"
invoke_name = "InvokeS"
else
ret_type = "object[]"
invoke_name = "InvokeM"
end
if not nargs then
return "instance " .. ret_type .. " [lua]Lua.Reference::" .. invoke_name .. "(object[])"
else
local args = {}
for j = 1, nargs do args[#args + 1] = "object" end
return "instance " .. ret_type .. " [lua]Lua.Reference::" .. invoke_name ..
"(" .. table.concat(args, ", ") .. ")"
end
end
function new(compiler)
local ilgen = { ops = {}, labels = {}, loops = {},
temps = {}, compiler = compiler }
setmetatable(ilgen, { __index = _M })
return ilgen
end
function _M:jump_if_false(to)
local temp = self:get_temp()
self:store_local(temp)
self:load_local(temp)
self:emit(OpCodes.ldsfld, nil_singleton)
self:emit(OpCodes.beq, to)
self:load_local(temp)
self:emit(OpCodes.ldsfld, false_singleton)
self:emit(OpCodes.beq, to)
self:release_temp(temp)
end
function _M:jump_if_nil(to)
self:emit(OpCodes.ldsfld, nil_singleton)
self:emit(OpCodes.beq, to)
end
function _M:define_label()
local label = #self.labels + 1
self.labels[label] = "label" .. label
return label
end
function _M:mark_label(label)
self.ops[#self.ops + 1] = { "label", self.labels[label] }
end
function _M:start_loop()
local label = self:define_label()
self.loops[#self.loops + 1] = label
end
function _M:end_loop()
self:mark_label(self.loops[#self.loops])
self.loops[#self.loops] = nil
end
function _M:break_loop()
self:emit(OpCodes.br, self.loops[#self.loops])
end
function _M:store_local(localvar)
if localvar.isupval then
if localvar.func == self.compiler.current_func then
self:store_local(localvar.temp)
self:emit(OpCodes.ldloc, localvar)
self:load_local(localvar.temp)
if localvar.type == "number" then
self:box_number()
end
self:emit(OpCodes.stfld, luavalue_ref)
else
local temp = self:get_temp((localvar.type == "number" and double_type) or nil)
self:store_local(temp)
self:emit(OpCodes.ldarg_0)
self:emit(OpCodes.ldfld, localvar)
self:load_local(temp)
if localvar.type == "number" then
self:box_number()
end
self:emit(OpCodes.stfld, luavalue_ref)
self:release_temp(temp)
end
elseif localvar.isarg then
self:emit(OpCodes.starg, localvar)
else
self:emit(OpCodes.stloc, localvar)
end
end
function _M:load_local(localvar)
if localvar.isupval then
if localvar.func == self.compiler.current_func then
self:emit(OpCodes.ldloc, localvar)
self:emit(OpCodes.ldfld, luavalue_ref)
if localvar.type == "number" then
self:unbox_number()
end
else
self:emit(OpCodes.ldarg_0)
self:emit(OpCodes.ldfld, localvar)
self:emit(OpCodes.ldfld, luavalue_ref)
if localvar.type == "number" then
self:unbox_number()
end
end
elseif localvar.isarg then
self:emit(OpCodes.ldarg, localvar)
else
self:emit(OpCodes.ldloc, localvar)
end
end
function _M:get_temp(type)
type = type or luavalue_type
if not self.temps[type] then
self.temps[type] = {}
end
local temps = self.temps[type]
if #temps > 0 then
local temp = temps[#temps]
temps[#temps] = nil
return temp
else
local func = self.compiler.current_func
local new_temp = { name = "temp_" .. #func.locals,
func = func, type = type }
func.locals[#func.locals + 1] = new_temp
return new_temp
end
end
function _M:release_temp(temp)
if not self.temps[temp.type] then
self.temps[temp.type] = {}
end
local temps = self.temps[temp.type]
temps[#temps + 1] = temp
end
function _M:jump_if_not_equal(exp1, exp2, to)
self:rel("beq", exp1, exp2)
self:jump_if_false(to)
end
function _M:neg(exp)
local slow_track = self:define_label()
local out = self:define_label()
self.compiler:compile(exp)
if exp.type ~= "number" then
self:emit(OpCodes.dup)
self:emit(OpCodes.isinst, double_type)
self:emit(OpCodes.brfalse, slow_track)
self:emit(OpCodes.unbox_any, double_type)
end
self:emit(OpCodes.neg)
if exp.type ~= "number" then
self:emit(OpCodes.box, double_type)
self:emit(OpCodes.br, out)
self:mark_label(slow_track)
self:emit(OpCodes.castclass, luaref_type)
self:emit(OpCodes.callvirt, neg_method)
self:mark_label(out)
end
end
function _M:arith(op, exp1, exp2, final_type)
local slow_track = self:define_label()
local very_slow_track = self:define_label()
local out = self:define_label()
self.compiler:compile(exp1)
if exp1.type ~= "number" then
self:emit(OpCodes.dup)
self:emit(OpCodes.isinst, double_type)
self:emit(OpCodes.brfalse, slow_track)
self:emit(OpCodes.unbox_any, double_type)
end
self.compiler:compile(exp2)
if exp2.type ~= "number" then
self:emit(OpCodes.dup)
self:emit(OpCodes.isinst, double_type)
self:emit(OpCodes.brfalse, very_slow_track)
self:emit(OpCodes.unbox_any, double_type)
end
self:emit(op)
if final_type ~= "number" then
self:emit(OpCodes.box, double_type)
self:emit(OpCodes.br, out)
end
if exp1.type ~= "number" then
self:mark_label(slow_track)
self:emit(OpCodes.castclass, luaref_type)
self.compiler:compile(exp2)
if exp2.type == "number" then self:box_number() end
self:emit(OpCodes.callvirt, arith_method[op])
self:emit(OpCodes.br, out)
end
if exp2.type ~= "number" then
self:mark_label(very_slow_track)
local temp1 = self:get_temp()
local temp2 = self:get_temp(double_type)
self:emit(OpCodes.stloc, temp1)
self:emit(OpCodes.stloc, temp2)
self:emit(OpCodes.ldloc, temp1)
self:emit(OpCodes.castclass, luaref_type)
self:emit(OpCodes.ldloc, temp2)
self:emit(OpCodes.callvirt, arith_method_slow[op])
self:release_temp(temp2)
self:release_temp(temp1)
end
self:mark_label(out)
end
function _M:rel(op, exp1, exp2, label)
local load_true = self:define_label()
local slow_track = self:define_label()
local type_mismatch_number = self:define_label()
local type_mismatch_ref = self:define_label()
local out = self:define_label()
self.compiler:compile(exp1)
if exp1.type ~= "number" then
self:emit(OpCodes.dup)
self:emit(OpCodes.isinst, double_type)
self:emit(OpCodes.brfalse, slow_track)
self:emit(OpCodes.unbox_any, double_type)
end
self.compiler:compile(exp2)
if exp2.type ~= "number" then
self:emit(OpCodes.dup)
self:emit(OpCodes.isinst, double_type)
self:emit(OpCodes.brfalse, type_mismatch_number)
self:emit(OpCodes.unbox_any, double_type)
end
if label then
self:emit(op, label)
else
self:emit(op, load_true)
self:load_false()
end
self:emit(OpCodes.br, out)
if not label then
self:mark_label(load_true)
self:load_true()
self:emit(OpCodes.br, out)
end
if exp1.type ~= "number" then
self:mark_label(slow_track)
if exp2.type ~= "number" then
self:emit(OpCodes.castclass, luaref_type)
self.compiler:compile(exp2)
if exp2.type ~= "string" then
self:emit(OpCodes.dup)
self:emit(OpCodes.isinst, luaref_type)
self:emit(OpCodes.brfalse, type_mismatch_ref)
end
self:emit(OpCodes.castclass, luaref_type)
self:emit(OpCodes.callvirt, rel_method[op])
if label then
self:emit(OpCodes.brtrue, label)
else
self:emit(OpCodes.brtrue, load_true)
self:load_false()
end
self:emit(OpCodes.br, out)
if exp2.type ~= "string" then
self:mark_label(type_mismatch_ref)
self:emit(OpCodes.pop)
self:emit(OpCodes.pop)
if op == "beq" then
if not label then self:load_false() end
self:emit(OpCodes.br, out)
else
self:error("type mismatch in comparison")
end
end
else
self:emit(OpCodes.pop)
if op == "beq" then
if not label then self:load_false() end
self:emit(OpCodes.br, out)
else
self:error("type mismatch in comparison")
end
end
end
if exp2.type ~= "number" then
self:mark_label(type_mismatch_number)
self:emit(OpCodes.pop)
self:emit(OpCodes.pop)
if op == "beq" then
if not label then self:load_false() end
else
self:error("type mismatch in comparison")
end
end
self:mark_label(out)
end
function _M:concat(exp1, exp2)
self:emit(OpCodes.call, concat_method)
end
function _M:error(err)
self:emit(OpCodes.ldstr, err)
self:emit(OpCodes.newobj, "instance void [mscorlib]System.Exception::.ctor(string)")
self:emit(OpCodes.throw)
end
function _M:logical_and(exp1, exp2)
local out = self:define_label()
local load_false = self:define_label()
self.compiler:compile(exp1)
if exp1.type ~= "number" then
self:jump_if_false(load_false)
else
self:emit(OpCodes.pop)
end
self.compiler:compile(exp2)
self:emit(OpCodes.br, out)
self:mark_label(load_false)
self:load_false()
self:mark_label(out)
end
function _M:logical_or(exp1, exp2)
local out = self:define_label()
local try_exp2 = self:define_label()
self.compiler:compile(exp1)
if exp1.type ~= "number" then
self:emit(OpCodes.dup)
self:jump_if_false(try_exp2)
self:emit(OpCodes.br, out)
self:mark_label(try_exp2)
self:emit(OpCodes.pop)
self.compiler:compile(exp2)
self:mark_label(out)
end
end
function _M:logical_not(exp)
local out = self:define_label()
local load_true = self:define_label()
self.compiler:compile(exp)
if exp.type ~= "number" then
self:jump_if_false(load_true)
self:load_false()
self:emit(OpCodes.br, out)
self:mark_label(load_true)
self:load_true()
self:mark_label(out)
else
self:emit(OpCodes.pop)
self:load_false()
end
end
function _M:len(exp)
self.compiler:compile(exp)
self:emit(OpCodes.castclass, luaref_type)
self:emit(OpCodes.callvirt, len_method)
end
function _M:argslist(list, return_array)
if #list > max_args then return_array = true end
local temp = self:get_temp(luavalue_array_type)
local last = list[#list]
if last and last.tag == "call" then
if #list == 1 then
self.compiler:compile(last, "array")
self:release_temp(temp)
return nil
end
return_array = true
list[#list] = nil
local size = self:get_temp(int4_type)
self.compiler:compile(last, "array")
self:store_local(temp)
self:load_local(temp)
self:emit(OpCodes.ldlen)
self:store_local(size)
self:load_local(temp)
self:emit(OpCodes.ldc_i4_0)
self:load_local(size)
self:emit(OpCodes.ldc_i4, #list)
self:emit(OpCodes.add)
self:emit(OpCodes.newarr, luavalue_type)
self:store_local(temp)
self:load_local(temp)
self:emit(OpCodes.ldc_i4, #list)
self:load_local(size)
self:emit(OpCodes.call, array_copy)
self:release_temp(size)
elseif return_array then
self:emit(OpCodes.ldc_i4, #list)
self:emit(OpCodes.newarr, luavalue_type)
self:store_local(temp)
end
if return_array then
for i = 1, #list do
self:load_local(temp)
self:emit(OpCodes.ldc_i4, i - 1)
self.compiler:compile(list[i])
if list[i].type == "number" then self:box_number() end
self:emit(OpCodes.stelem, luavalue_type)
end
self:load_local(temp)
self:release_temp(temp)
return nil
else
for i = 1, #list do
self.compiler:compile(list[i])
if list[i].type == "number" then self:box_number() end
end
self:release_temp(temp)
return #list
end
self:release_temp(temp)
end
function _M:explist(list, adjust_n)
local i = 1
while i < #list and i <= adjust_n do
self.compiler:compile(list[i])
i = i + 1
end
if i <= adjust_n then
if list[i] and list[i].tag == "call" then
self.compiler:compile(list[i], adjust_n - i + 1)
else
self.compiler:compile(list[i])
for i = (i + 1), adjust_n do
self:load_nil()
end
end
i = i + 1
end
while i <= #list do
self.compiler:compile(list[i])
self:emit(OpCodes.pop)
i = i + 1
end
end
function _M:store_global(name)
local temp = self:get_temp()
self:store_local(temp)
self:emit(OpCodes.ldarg_0)
self:emit(OpCodes.ldfld, env_field)
self:load_string(name)
self:load_local(temp)
self:settable_symbol()
self:release_temp(temp)
end
function _M:load_global(name)
self:emit(OpCodes.ldarg_0)
self:emit(OpCodes.ldfld, env_field)
self:load_string(name)
self:gettable_symbol()
end
function _M:settable()
self:emit(OpCodes.callvirt, settable_method)
end
function _M:settable_symbol()
self:emit(OpCodes.callvirt, settable_symbol_method)
end
function _M:settable_number()
self:emit(OpCodes.callvirt, settable_number_method)
end
function _M:gettable()
self:emit(OpCodes.callvirt, gettable_method)
end
function _M:gettable_symbol()
self:emit(OpCodes.callvirt, gettable_symbol_method)
end
function _M:gettable_number()
self:emit(OpCodes.callvirt, gettable_number_method)
end
function _M:load_string(name)
self:emit(OpCodes.ldsfld, self.compiler:get_literal(name))
end
function _M:load_number(n)
self:emit(OpCodes.ldc_r8, n)
end
function _M:box_number()
self:emit(OpCodes.box, double_type)
end
function _M:unbox_number()
self:emit(OpCodes.unbox_any, double_type)
end
function _M:load_nil()
self:emit(OpCodes.ldsfld, nil_singleton)
end
function _M:load_true()
self:emit(OpCodes.ldsfld, true_singleton)
end
function _M:load_false()
self:emit(OpCodes.ldsfld, false_singleton)
end
function _M:call(nargs, nres, is_tail)
local call_op = (is_tail and OpCodes.tail_callvirt) or OpCodes.callvirt
self:emit(call_op, call_with(nargs, nres))
if nres == 0 then
self:emit(OpCodes.pop)
elseif type(nres) == "number" and nres > 1 then
local temp = self:get_temp(luavalue_array_type)
local size = self:get_temp(int4_type)
self:store_local(temp)
self:load_local(temp)
self:emit(OpCodes.ldlen)
self:store_local(size)
for i = 0, nres - 1 do
local load_nil = self:define_label()
local next = self:define_label()
self:emit(OpCodes.ldc_i4, i)
self:load_local(size)
self:emit(OpCodes.bge, load_nil)
self:load_local(temp)
self:emit(OpCodes.ldc_i4, i)
self:emit(OpCodes.ldelem, luavalue_type)
self:emit(OpCodes.br, next)
self:mark_label(load_nil)
self:load_nil()
self:mark_label(next)
end
self:release_temp(temp)
self:release_temp(size)
end
end
function _M:emit(opcode, ...)
if opcode == OpCodes.castclass then
self:emit(OpCodes.unbox_any, ...)
else
self.ops[#self.ops + 1] = { opcode, ... }
end
end
function _M:new_func(func)
local temp = self:get_temp()
for upval, _ in pairs(func.upvals) do
if upval.func == self.compiler.current_func then
self:emit(OpCodes.ldloc, upval)
else
self:emit(OpCodes.ldarg_0)
self:emit(OpCodes.ldfld, upval)
end
end
self:emit(OpCodes.newobj, "instance void " .. func.clr_type .. "::" .. func.ctor_name)
self:emit(OpCodes.dup)
self:emit(OpCodes.ldarg_0)
self:emit(OpCodes.ldfld, env_field)
self:emit(OpCodes.stfld, env_field)
self:release_temp(temp)
end
function _M:prologue()
local func = self.compiler.current_func
local args, locals = func.args, func.locals
for _, var in ipairs(locals) do
if var.isupval then
self:emit(OpCodes.newobj, luavalue_ref_cons)
self:emit(OpCodes.stloc, var)
var.temp = self:get_temp((var.type == "number" and double_type) or nil)
end
end
for _, arg in ipairs(args) do
if arg.isupval then
locals[#locals + 1] = arg
self:emit(OpCodes.newobj, luavalue_ref_cons)
self:emit(OpCodes.stloc, arg)
self:emit(OpCodes.ldloc, arg)
self:emit(OpCodes.ldarg, arg)
self:emit(OpCodes.stfld, luavalue_ref)
arg.isarg = false
end
end
end
function _M:new_table()
self:emit(OpCodes.newobj, table_cons)
end
function _M:constructor()
self:emit(OpCodes.ldarg_0)
self:emit(OpCodes.call, closure_cons)
local func = self.compiler.current_func
local args = {}
for upval, _ in pairs(func.upvals) do
args[#args + 1] = "class [lua]Lua.UpValue " .. upval.name
self:emit(OpCodes.ldarg_0)
self:emit(OpCodes.ldarg, #args)
self:emit(OpCodes.stfld, upval)
end
self:emit(OpCodes.ret)
func.ctor_name = ".ctor(" .. table.concat(args, ", ") .. ")"
end
function _M:class_constructor()
local func = self.compiler.current_func
for val, _ in pairs(func.literals) do
if type(val) == "boolean" then
if val then
self:emit(OpCodes.ldsfld, true_singleton)
else
self:emit(OpCodes.ldsfld, false_singleton)
end
else
self:emit(OpCodes.ldstr, val)
self:emit(OpCodes.call, symbol_intern);
end
self:emit(OpCodes.stsfld, self.compiler:get_literal(val))
end
self:emit(OpCodes.ldsfld, nil_singleton)
self:emit(OpCodes.stsfld, self.compiler:get_literal())
self:emit(OpCodes.ret)
end
function _M:invoke(func_type, nargs, fargs, ret_type, invoke_name, isvararg)
if nargs == "array" then
self:emit(OpCodes.ldarg_1)
self:emit(OpCodes.ldlen)
self:emit(OpCodes.stloc_0)
self:emit(OpCodes.ldarg_0)
for i = 1, fargs do
local lnil = self:define_label()
local next = self:define_label()
self:emit(OpCodes.ldc_i4, i)
self:emit(OpCodes.ldloc_0)
self:emit(OpCodes.bgt, lnil)
self:emit(OpCodes.ldarg_1)
self:emit(OpCodes.ldc_i4, i - 1)
self:emit(OpCodes.ldelem, luavalue_type)
self:emit(OpCodes.br, next)
self:mark_label(lnil)
self:load_nil()
self:mark_label(next)
end
if isvararg then
local has_varargs = self:define_label()
local call = self:define_label()
self:emit(OpCodes.ldloc_0)
self:emit(OpCodes.ldc_i4, fargs)
self:emit(OpCodes.sub)
self:emit(OpCodes.stloc_0)
self:emit(OpCodes.ldloc_0)
self:emit(OpCodes.ldc_i4_0)
self:emit(OpCodes.bgt, has_varargs)
self:emit(OpCodes.ldnull)
self:emit(OpCodes.br, call)
self:mark_label(has_varargs)
self:emit(OpCodes.ldarg_1)
self:emit(OpCodes.ldc_i4, fargs)
self:emit(OpCodes.ldloc_0)
self:emit(OpCodes.newarr, luavalue_type)
self:emit(OpCodes.dup)
self:emit(OpCodes.starg_1)
self:emit(OpCodes.ldc_i4_0)
self:emit(OpCodes.ldloc_0)
self:emit(OpCodes.call, array_copy)
self:emit(OpCodes.ldarg_1)
self:mark_label(call)
end
else
self:emit(OpCodes.ldarg_0)
for i = 1, fargs do
if i > nargs then
self:load_nil()
else
self:emit(OpCodes.ldarg, i)
end
end
if isvararg then
if nargs > fargs then
local nvarargs = nargs - fargs
self:emit(OpCodes.ldc_i4, nvarargs)
self:emit(OpCodes.newarr, luavalue_type)
for i = fargs, nargs - 1 do
self:emit(OpCodes.dup)
self:emit(OpCodes.ldarg, i)
self:emit(OpCodes.ldc_i4, i - fargs)
self:emit(OpCodes.stelem, luavalue_type)
end
else
self:emit(OpCodes.ldnull)
end
end
end
local args = {}
local vararg = ""
if isvararg then
vararg = ", object[]"
end
for i = 1, fargs do args[#args + 1] = "object" end
local func_invoke = "instance " .. ret_type .. " " ..
func_type .. "::" .. invoke_name .. "(" .. table.concat(args, ", ") .. vararg .. ")"
self:emit(OpCodes.call, func_invoke)
self:emit(OpCodes.ret)
end
|
mp=RE.motionPanel()
mot=mp:currMotion()
discontinuity=boolN()
fn=Fltk.chooseFile("Choose con", "../Resource/motion/", "*.dis", false)
file=util.BinaryFile()
file:openRead(fn)
file:unpack(discontinuity)
file:close()
for i=0,mot:numFrames()-1 do
mot:setConstraint(i, FootstepDetection.IS_DISCONTINUOUS, discontinuity(i))
end
mp:scrollPanel():addPanel(discontinuity:bit(), CPixelRGB8(255,255,0))
|
local AnimationSystem = tiny.processingSystem()
AnimationSystem.filter = tiny.requireAll('animation')
function AnimationSystem:process(entity, dt)
entity.animation:update(dt)
end
return AnimationSystem |
local autoc = require("autoc")
local log = require("autoc.log")
local autocmd = {
autocs = {}
}
function autocmd.InsertCharPre(bufnr)
log.print(">>> InsertCharPre", bufnr)
autocmd.autocs[bufnr]:InsertCharPre()
end
function autocmd.CompleteDone(bufnr)
log.print(">>> CompleteDone", bufnr)
autocmd.autocs[bufnr]:CompleteDone()
end
function autocmd.attach(client, bufnr)
autocmd.autocs[bufnr] = autoc:new(client, bufnr)
vim.cmd(
string.format(
[[
augroup autoc_group_%d
au!
autocmd InsertCharPre <buffer=%d> lua require("autoc.autocmd").InsertCharPre(%d)
autocmd CompleteDone <buffer=%d> lua require("autoc.autocmd").CompleteDone(%d)
augroup end
]],
bufnr,
bufnr,
bufnr,
bufnr,
bufnr
)
)
end
return autocmd
|
local GSE = GSE
local L = GSE.L
GSE.GUIEditFrame = {}
StaticPopupDialogs["GSE_ConfirmReloadUIDialog"] = {
text = L["You need to reload the User Interface to complete this task. Would you like to do this now?"],
button1 = L["Yes"],
button2 = L["No"],
OnAccept = function()
ReloadUI();
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3 -- Avoid some UI taint, see https://www.wowace.com/news/376-how-to-avoid-some-ui-taint
}
StaticPopupDialogs["GS-DebugOutput"] = {
text = "Dump of GS Debug messages",
button1 = L["Update"],
button2 = L["Close"],
OnAccept = function(self, data)
self.editBox:SetText(GSE.DebugOutput)
end,
OnShow = function(self, data)
self.editBox:SetText(GSE.DebugOutput)
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3, -- Avoid some UI taint, see https://www.wowace.com/news/376-how-to-avoid-some-ui-taint
hasEditBox = true
}
StaticPopupDialogs['GSE_UPDATE_AVAILABLE'] = {
text = L["GSE is out of date. You can download the newest version from https://www.curseforge.com/wow/addons/gse-gnome-sequencer-enhanced-advanced-macros."],
hasEditBox = 1,
OnShow = function(self)
self.editBox:SetAutoFocus(false)
self.editBox:SetWidth(220)
self.editBox:SetText("https://www.curseforge.com/wow/addons/gse-gnome-sequencer-enhanced-advanced-macros")
self.editBox:HighlightText()
ChatEdit_FocusActiveWindow();
end,
OnHide = function(self)
self.editBox:SetWidth(self.editBox.width or 50)
end,
hideOnEscape = 1,
button1 = OKAY,
EditBoxOnEnterPressed = function(self)
ChatEdit_FocusActiveWindow();
self:GetParent():Hide();
end,
EditBoxOnEscapePressed = function(self)
ChatEdit_FocusActiveWindow();
self:GetParent():Hide();
end,
EditBoxOnTextChanged = function(self)
if (self:GetText() ~= "https://www.curseforge.com/wow/addons/gse-gnome-sequencer-enhanced-advanced-macros") then
self:SetText("https://www.curseforge.com/wow/addons/gse-gnome-sequencer-enhanced-advanced-macros")
end
self:HighlightText()
self:ClearFocus()
ChatEdit_FocusActiveWindow();
end,
OnEditFocusGained = function(self)
self:HighlightText()
end,
showAlert = 1
}
StaticPopupDialogs['GSE_SEQUENCEHELP'] = {
text = L["Copy this link and open it in a Browser."],
hasEditBox = 1,
url = "https://wowlazymacros.com",
OnShow = function(self)
self.editBox:SetAutoFocus(false)
self.editBox.width = self.editBox:GetWidth()
self.editBox:SetWidth(220)
self.editBox:SetText(StaticPopupDialogs['GSE_SEQUENCEHELP'].url)
self.editBox:HighlightText()
ChatEdit_FocusActiveWindow();
end,
OnHide = function(self)
self.editBox:SetWidth(self.editBox.width or 50)
self.editBox.width = nil
end,
hideOnEscape = 1,
button1 = OKAY,
EditBoxOnEnterPressed = function(self)
ChatEdit_FocusActiveWindow();
self:GetParent():Hide();
end,
EditBoxOnEscapePressed = function(self)
ChatEdit_FocusActiveWindow();
self:GetParent():Hide();
end,
EditBoxOnTextChanged = function(self)
if (self:GetText() ~= StaticPopupDialogs['GSE_SEQUENCEHELP'].url) then
self:SetText(StaticPopupDialogs['GSE_SEQUENCEHELP'].url)
end
self:HighlightText()
self:ClearFocus()
ChatEdit_FocusActiveWindow();
end,
OnEditFocusGained = function(self)
self:HighlightText()
end,
showAlert = 1
}
StaticPopupDialogs["GSE-SampleMacroDialog"] = {
text = L["There are No Macros Loaded for this class. Would you like to load the Sample Macro?"],
button1 = L["Load"],
button2 = L["Close"],
OnAccept = function(self, data)
GSE.LoadSampleMacros(GSE.GetCurrentClassID())
end,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3 -- Avoid some UI taint, see https://www.wowace.com/news/376-how-to-avoid-some-ui-taint
}
StaticPopupDialogs["GSE-MacroImportSuccess"] = {
text = L["Macro Import Successful."],
button1 = L["Close"],
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3 -- Avoid some UI taint, see https://www.wowace.com/news/376-how-to-avoid-some-ui-taint
}
StaticPopupDialogs["GSE-GenericMessage"] = {
text = L["Macro Import Successful."],
button1 = L["Close"],
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3 -- Avoid some UI taint, see https://www.wowace.com/news/376-how-to-avoid-some-ui-taint
}
StaticPopupDialogs["GSE-MacroImportFailure"] = {
text = L["Macro unable to be imported."],
button1 = L["Close"],
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3 -- Avoid some UI taint, see https://www.wowace.com/news/376-how-to-avoid-some-ui-taint
}
StaticPopupDialogs["GSE-DeleteMacroDialog"] = {
text = "",
button1 = L["Delete"],
button2 = L["Cancel"],
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = STATICPOPUPS_NUMDIALOGS,
showAlert = true,
exclusive = true
}
|
--[[
--
-- Template for running Lua output.
--
--]]
--
package.path = package.path .. ";../../libatscc2lua/?.lua"
require "output.main_dats"
main_dynload()
|
EditCtrl = relative_import('edit_utils').create_edit_class(nil, 'editor/edit/uieditor_edit_combo')
-- override
function EditCtrl:on_init_ui()
self.combo:SetItems({})
local list = self._validateParm.list
if is_function(list) then
list = list(self)
end
self:_createPopupMenuItem(list)
self.name:SetString(self._validateParm['name'])
end
-- override
function EditCtrl:on_update_data()
end
function EditCtrl:_createPopupMenuItem(info, popUpItem)
local sub_group = info['sub_group']
if sub_group then
local sub_group_name = info['sub_group_name']
local popUpItemNodeType = self.combo:AddPopupMenuItem(sub_group_name, popUpItem)
self:_createPopupMenuItem(info.sub_group, popUpItemNodeType)
else
for _, typeInfo in ipairs(info) do
if typeInfo.sub_group then
self:_createPopupMenuItem(typeInfo, popUpItem)
else
self:_createChildMenuItem(typeInfo, popUpItem)
end
end
end
end
function EditCtrl:_createChildMenuItem(typeInfo, popUpItem)
local name, value = typeInfo[1], typeInfo[2]
if is_equal(self._data, value) then
self.combo:SetString(name)
end
self.combo:AddMenuItem(name, nil, popUpItem, function()
if name ~= self._data then
self.combo:SetString(name)
self._data = value
self._editCallback(self._data)
end
end)
end |
local diamondShop_pin_map = require("qnFiles/qnPlist/hall/diamondShop_pin");
local diamondShopTimeLimit=
{
name="diamondShopTimeLimit",type=0,typeName="View",time=0,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft,
{
name="todayGoodsContent",type=1,typeName="Image",time=68969432,report=0,x=20,y=20,width=920,height=295,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,file="hall/common/bg_blank.png",gridLeft=20,gridRight=20,gridTop=20,gridBottom=20,
{
name="topView",type=0,typeName="View",time=77448693,report=0,x=0,y=0,width=910,height=60,fillTopLeftX=3,fillTopLeftY=0,fillBottomRightX=3,fillBottomRightY=235,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,
{
name="title",type=4,typeName="Text",time=77448695,report=0,x=0,y=0,width=480,height=55,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=32,textAlign=kAlignCenter,colorRed=255,colorGreen=235,colorBlue=186,string=[[今日限时商品:4核安卓平板电脑]]
}
},
{
name="todayGoodsImage",type=1,typeName="Image",time=68969433,report=0,x=0,y=50,width=262,height=200,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file=diamondShop_pin_map['default.png']
},
{
name="infoView",type=0,typeName="View",time=77448380,report=0,x=-2,y=70,width=430,height=200,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,
{
name="priceBg",type=1,typeName="Image",time=77448352,report=0,x=10,y=7,width=200,height=70,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,file=diamondShop_pin_map['diamond_price_bg_l10_r10_t10_b10.png'],gridLeft=10,gridRight=10,gridTop=10,gridBottom=10,
{
name="icon",type=1,typeName="Image",time=77448353,report=0,x=10,y=0,width=50,height=50,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file="hall/common/diamond.png"
},
{
name="needDiamondNum",type=4,typeName="Text",time=77448354,report=0,x=12,y=0,width=120,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignRight,fontSize=30,textAlign=kAlignLeft,colorRed=255,colorGreen=252,colorBlue=0,string=[[x1000]]
}
},
{
name="exchangeBtn",type=2,typeName="Button",time=68969437,report=0,x=40,y=-3,width=200,height=89,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,file="hall/common/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=25,gridRight=25,gridTop=25,gridBottom=25,
{
name="exchangeBtnName",type=4,typeName="Text",time=68969438,report=0,x=0,y=0,width=111,height=43,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=36,textAlign=kAlignCenter,colorRed=255,colorGreen=235,colorBlue=186,string=[[马上抢]]
}
},
{
name="line",type=1,typeName="Image",time=77449521,report=0,x=0,y=0,width=430,height=2,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="hall/common/line.png"
},
{
name="leftNumView",type=0,typeName="View",time=77449121,report=0,x=0,y=50,width=205,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottomLeft,
{
name="Text1",type=4,typeName="Text",time=77449122,report=0,x=10,y=0,width=126,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=28,textAlign=kAlignLeft,colorRed=118,colorGreen=72,colorBlue=18,string=[[剩余个数:]]
},
{
name="leftGoodsNum",type=4,typeName="Text",time=77449123,report=0,x=140,y=0,width=61,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=28,textAlign=kAlignLeft,colorRed=255,colorGreen=252,colorBlue=0,string=[[10个]]
}
},
{
name="leftTimeView",type=0,typeName="View",time=77449243,report=0,x=0,y=0,width=205,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottomLeft,
{
name="Text1",type=4,typeName="Text",time=77449244,report=0,x=10,y=0,width=126,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=28,textAlign=kAlignLeft,colorRed=118,colorGreen=72,colorBlue=18,string=[[剩余时间:]]
},
{
name="leftGoodsTime",type=4,typeName="Text",time=77449245,report=0,x=140,y=0,width=196,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=28,textAlign=kAlignLeft,colorRed=255,colorGreen=252,colorBlue=0,string=[[1天18小时10分]]
}
},
{
name="scanView",type=0,typeName="View",time=77449312,report=0,x=0,y=-50,width=205,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottomLeft,
{
name="Text1",type=4,typeName="Text",time=77449313,report=0,x=110,y=0,width=150,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=24,textAlign=kAlignLeft,colorRed=118,colorGreen=72,colorBlue=18,string=[[人浏览该商品]]
},
{
name="readNum",type=4,typeName="Text",time=77449314,report=0,x=10,y=0,width=100,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=24,textAlign=kAlignLeft,colorRed=0,colorGreen=0,colorBlue=255,string=[[10]]
}
}
}
},
{
name="lastGoodsContent",type=1,typeName="Image",time=68969448,report=0,x=20,y=335,width=450,height=295,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,file="hall/common/bg_blank.png",gridLeft=20,gridRight=20,gridTop=20,gridBottom=20,
{
name="lastGoodsImage",type=1,typeName="Image",time=68969449,report=0,x=15,y=60,width=262,height=200,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file=diamondShop_pin_map['default.png']
},
{
name="topView",type=0,typeName="View",time=77449905,report=0,x=0,y=0,width=440,height=60,fillTopLeftX=3,fillTopLeftY=0,fillBottomRightX=3,fillBottomRightY=235,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,
{
name="title",type=4,typeName="Text",time=77449907,report=0,x=5,y=54,width=440,height=55,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=32,textAlign=kAlignCenter,colorRed=255,colorGreen=235,colorBlue=186,string=[[往期限时商品]]
}
},
{
name="lastGoodsName",type=4,typeName="Text",time=68969452,report=0,x=-26,y=130,width=200,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,fontSize=28,textAlign=kAlignCenter,colorRed=255,colorGreen=235,colorBlue=186,string=[[智能手机]]
},
{
name="lastGoodsBtn",type=2,typeName="Button",time=68969450,report=0,x=-30,y=180,width=200,height=89,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,file="hall/common/btns/btn_gray_163x89_l25_r25_t25_b25.png",gridLeft=25,gridRight=25,gridTop=25,gridBottom=25,
{
name="Text11",type=4,typeName="Text",time=68969451,report=0,x=0,y=0,width=111,height=43,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=36,textAlign=kAlignCenter,colorRed=255,colorGreen=235,colorBlue=186,string=[[已过期]]
}
}
},
{
name="futureGoodsContent",type=1,typeName="Image",time=68969455,report=0,x=490,y=335,width=450,height=295,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,file="hall/common/bg_blank.png",gridLeft=20,gridRight=20,gridTop=20,gridBottom=20,
{
name="topView",type=0,typeName="View",time=77448279,report=0,x=0,y=0,width=440,height=60,fillTopLeftX=3,fillTopLeftY=0,fillBottomRightX=3,fillBottomRightY=235,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,
{
name="title",type=4,typeName="Text",time=77448281,report=0,x=60,y=54,width=440,height=55,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=32,textAlign=kAlignCenter,colorRed=255,colorGreen=235,colorBlue=186,string=[[即将推出]]
}
},
{
name="futureGoodsImage",type=1,typeName="Image",time=68969456,report=0,x=60,y=60,width=262,height=200,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file=diamondShop_pin_map['default.png']
}
}
}
return diamondShopTimeLimit; |
function beginContact(a, b, coll)
x,y = coll:getNormal()
x = maths.round(x, 4) y = maths.round(y, 4)
local aname, bname = a:getUserData().name, b:getUserData().name
anamesub = string.sub(aname,1,3) bnamesub = string.sub(bname,1,3)
if aname == nil then aname = "Unknown" end if bname == nil then bname = "Unknown" end
cbtxt = cbtxt.."\n"..aname.." collided with "..bname.." with a vector normal of: "..x..", "..y
if anamesub == "bat" and (bname == "Ara" or bname == "Evo") then
a:getUserData().state = "dying"
cbtxt = cbtxt.. "\n bat got whacked! Is now " .. a:getUserData().state
-- deademies[#deademies] = a:getUserData()
--killEnemy(a:getUserData())
elseif bnamesub == "bat" and (aname == "Ara" or aname == "Evo") then
b:getUserData().state = "dying"
cbtxt = cbtxt .. "\n bat got whacked! Is now " .. b:getUserData().state
--killEnemy(b:getUserData())
-- deademies[#deademies] = b:getUserData()
end
end
function endContact(a, b, coll)
local aname, bname = a:getUserData().name, b:getUserData().name
if aname == nil then aname = "Unknown" end if bname == nil then bname = "Unknown" end
cbpersists = 0
cbtxt = cbtxt.."\n"..aname.." seperated from "..bname
end
function preSolve(a, b, coll)
local aname, bname = a:getUserData().name, b:getUserData().name
if aname == nil then aname = "Unknown" end if bname == nil then bname = "Unknown" end
if cbpersists == 0 then -- only say when they first start touching
cbtxt = cbtxt.."\n"..aname.." touched "..bname
elseif cbpersists < 21 then -- then just start counting
cbtxt = cbtxt.." "..cbpersists
end
cbpersists = cbpersists + 1 -- keep track of how many updates they've been touching for
end
function postSolve(a, b, coll, normalimpulse1, tangentimpulse1, normalimpulse2, tangentimpulse2)
end |
-- luacheck: no global
-- Definitions
VER_MAJOR = "3"
VER_MINOR = "45"
VER_MICRO = "2"
MINFARVERSION = "{ 3, 0, 0, 4878 }"
COPYRIGHT = "Shmuel Zeigerman, 2007-2021"
-- Derivative values --
VER_STRING = VER_MAJOR.."."..VER_MINOR.."."..VER_MICRO
|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author ([email protected]).
--]]
local ITEM = Clockwork.item:New("weapon_base");
ITEM.name = "ItemSuitcase";
ITEM.cost = 12;
ITEM.model = "models/weapons/w_suitcase_passenger.mdl";
ITEM.weight = 2;
ITEM.access = "1";
ITEM.business = true;
ITEM.category = "Reusables";
ITEM.uniqueID = "cw_suitcase";
--ITEM.isFakeWeapon = true;
ITEM.isMeleeWeapon = true;
ITEM.description = "ItemSuitcaseDesc";
ITEM.isAttachment = true;
ITEM.attachmentBone = "ValveBiped.Bip01_R_Hand";
ITEM.attachmentOffsetAngles = Angle(0, 90, -10);
ITEM.attachmentOffsetVector = Vector(0, 0, 4);
-- A function to get whether the attachment is visible.
function ITEM:GetAttachmentVisible(player, entity)
return (Clockwork.player:GetWeaponClass(player) == self("weaponClass"));
end;
-- Called when a player drops the item.
function ITEM:OnDrop(player, position) end;
ITEM:Register(); |
local networkVars =
{
sntl_numEggs = "integer",
sntl_numMaxEggs = "integer",
sntl_numRespawnLeft = "integer",
sntl_numRespawnMax = "integer"
}
function GameInfo:GetNumEggs()
return self.sntl_numEggs
end
function GameInfo:GetNumMaxEggs()
return self.sntl_numMaxEggs
end
function GameInfo:GetNumMarineRespawnLeft()
return self.sntl_numRespawnLeft
end
function GameInfo:GetNumMarineRespawnMax()
return self.sntl_numRespawnMax
end
if Server then
local old_GameInfo_OnCreate = GameInfo.OnCreate
function GameInfo:OnCreate()
old_GameInfo_OnCreate(self)
self.sntl_numEggs = 0
self.sntl_numMaxEggs = 0
self.sntl_numRespawnLeft = 0
self.sntl_numRespawnMax = 0
end
end
if Server then
function GameInfo:SetNumEggs( n )
self.sntl_numEggs = n
end
function GameInfo:SetNumMaxEggs( n )
self.sntl_numMaxEggs = n
end
function GameInfo:SetNumMarineRespawnLeft( n )
self.sntl_numRespawnLeft = n
end
function GameInfo:SetNumMarineRespawnMax( n )
self.sntl_numRespawnMax = n
end
end
Shared.LinkClassToMap("GameInfo", nil, networkVars)
|
-------------------------------------------------------------------------------
-- wrap for c.server
-------------------------------------------------------------------------------
local _PACKAGE = (...):match("^(.+)[%./][^%./]+") or ""
local coroutine_running = coroutine.running
local coroutine_resume = coroutine.resume
local coroutine_yield = coroutine.yield
local string = string
local c = tengine.c
local co_pool = require(_PACKAGE .. "/pool")
local localaddress = function(self)
if self.server then
return self.server:localaddress()
end
return "unknown"
end
local remoteaddress = function(self, ...)
if self.server then
return self.server:remoteaddress(...)
end
return "unknown"
end
local send = function(self, ...)
if self.server then
self.server:send(...)
end
end
local close = function(self, session)
if self.server then
self.server:close(session)
end
end
local methods = {
localaddress = localaddress,
remoteaddress = remoteaddress,
send = send,
close = close,
}
local new = function(port, accept, read, closed)
local self = setmetatable({}, {__index = methods})
self.port = port
self.server = c.server(port, {
on_accept =
function(session)
local co = co_pool.new(accept)
local succ, err = coroutine_resume(co, session)
if not succ then
error(err)
end
end,
on_read =
function(session, data, size)
local co = co_pool.new(read)
local succ, err = coroutine_resume(co, session, data, size)
if not succ then
error(err)
end
end,
on_closed =
function(session, err)
local co = co_pool.new(closed)
local succ, err = coroutine_resume(co, session, err)
if not succ then
error(err)
end
end
})
return self
end
return {
new = new
}
|
-- Array functions
function tprint(t)
for key,value in pairs(t) do
print(key, value)
end
end
function has_value (tab, val)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
-- File functions
-- http://lua-users.org/wiki/FileInputOutput
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- Node Voxel
function generateNodeVoxel(file)
local lines = lines_from(file)
local aNodevoxel = {}
-- print all line numbers and their contents
for k,v in pairs(lines) do
if k >= 4 then -- Pass the description header
x, y, z, cubeColor = v:match("([^,]+) ([^,]+) ([^,]+) ([^,]+)")
if has_value(aNodevoxel, cubeColor) then
print 'Nodevoxel exists, does not create it'
else
print("Nodevoxel does not exist, create it: " .. cubeColor)
table.insert(aNodevoxel, cubeColor)
minetest.register_node("nodevoxel:cube" .. cubeColor, {
description = "Nodevoxel Cube" .. cubeColor,
tiles = {
"nodevoxel_cube_up.png^[colorize:#" .. cubeColor .. "50",
"nodevoxel_cube_down.png^[colorize:#" .. cubeColor .. "50",
"nodevoxel_cube_right.png^[colorize:#" .. cubeColor .. "50",
"nodevoxel_cube_left.png^[colorize:#" .. cubeColor .. "50",
"nodevoxel_cube_back.png^[colorize:#" .. cubeColor .. "50",
"nodevoxel_cube_front.png^[colorize:#" .. cubeColor .. "50"
},
is_ground_content = true,
groups = {
cracky = 3
},
})
end
print (k .. ' : ', x, y, z, cubeColor)
end
end
end
-- Object voxel list
local aObjectVoxel = {'obj01.txt'}
for key,value in pairs(aObjectVoxel) do
print(key, value)
generateNodeVoxel(value)
end
-- Chat commands
minetest.register_chatcommand("nodevoxel", {
params = "<entity name> <entity param>",
description = "Add an nodevoxel with parameters",
func = function(user, args)
if args == "" then
return false, "Parameters required."
end
local nodevoxelAction, nodevoxelParam = args:match("^(%S+)%s(%S+)$")
if not nodevoxelParam then
return false, "Entity parameters required"
end
local player = minetest.get_player_by_name(user)
if not player then
return false, "Player not found"
end
local fmt = "Add an %s nodevoxel at: (%.2f,%.2f,%.2f)"
local pos = player:getpos()
-- /nodevoxel add 1
if nodevoxelAction == "add" then
minetest.chat_send_player(user, "Add nodevoxel " .. nodevoxelParam)
if nodevoxelParam == "01" then
-- y = height
local file = "obj" .. nodevoxelParam .. ".txt"
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
if k >= 4 then
x, y, z, cubeColor = v:match("([^,]+) ([^,]+) ([^,]+) ([^,]+)")
minetest.set_node({x=pos.x + x, y=pos.y + z, z=pos.z + y}, {name="nodevoxel:cube" .. cubeColor})
print (k .. ' : ', x, y, z, cubeColor)
end
end
return true, fmt:format(args, pos.x, pos.y, pos.z)
end
else
return false, "No nodevoxel added"
end
return false, "No nodevoxel added"
end
})
|
--泛之调停者
local m=14010014
local cm=_G["c"..m]
cm.named_with_Engraver=1
function cm.initial_effect(c)
--link summon
aux.AddLinkProcedure(c,cm.matfilter,3,3,cm.lcheck)
c:EnableReviveLimit()
--spsummon condition
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e0:SetCode(EFFECT_SPSUMMON_CONDITION)
e0:SetValue(cm.splimit)
c:RegisterEffect(e0)
--No.16
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(m,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,m+EFFECT_COUNT_CODE_DUEL)
e1:SetCondition(cm.con)
e1:SetCost(cm.cost)
e1:SetTarget(cm.tg)
e1:SetOperation(cm.op)
c:RegisterEffect(e1)
end
function cm.matfilter(c)
return c:IsLinkType(TYPE_LINK)
end
function cm.lcheck(g,lc)
return g:GetClassCount(Card.GetCode)==g:GetCount()
end
function cm.splimit(e,se,sp,st)
return bit.band(st,SUMMON_TYPE_LINK)==SUMMON_TYPE_LINK
end
function cm.con(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLinkState()
end
function cm.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function cm.tg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CARDTYPE)
e:SetLabel(Duel.AnnounceType(tp))
end
function cm.op(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetTargetRange(1,1)
if e:GetLabel()==0 then
e1:SetDescription(aux.Stringid(m,1))
e1:SetValue(cm.aclimit1)
elseif e:GetLabel()==1 then
e1:SetDescription(aux.Stringid(m,2))
e1:SetValue(cm.aclimit2)
else
e1:SetDescription(aux.Stringid(m,3))
e1:SetValue(cm.aclimit3)
end
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,1)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_DISABLE)
e2:SetTargetRange(LOCATION_ONFIELD,LOCATION_ONFIELD)
if e:GetLabel()==0 then
e2:SetDescription(aux.Stringid(m,1))
e2:SetTarget(cm.disable1)
elseif e:GetLabel()==1 then
e2:SetDescription(aux.Stringid(m,2))
e2:SetTarget(cm.disable2)
else
e2:SetDescription(aux.Stringid(m,3))
e2:SetTarget(cm.disable3)
end
e2:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,1)
Duel.RegisterEffect(e2,tp)
end
function cm.aclimit1(e,re,tp)
return re:IsActiveType(TYPE_MONSTER) and not re:GetHandler():IsImmuneToEffect(e)
end
function cm.aclimit2(e,re,tp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:IsActiveType(TYPE_SPELL) and not re:GetHandler():IsImmuneToEffect(e)
end
function cm.aclimit3(e,re,tp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:IsActiveType(TYPE_TRAP) and not re:GetHandler():IsImmuneToEffect(e)
end
function cm.disable1(e,c)
return (c:IsType(TYPE_EFFECT) or bit.band(c:GetOriginalType(),TYPE_EFFECT)==TYPE_EFFECT) and c:IsType(TYPE_MONSTER)
end
function cm.disable2(e,c)
return c:IsType(TYPE_SPELL)
end
function cm.disable3(e,c)
return c:IsType(TYPE_TRAP)
end |
object_tangible_component_cybernetic_shared_cybernetic_module_base = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/component/cybernetic/shared_cybernetic_module_base.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_component_cybernetic_shared_cybernetic_module_base, "object/tangible/component/cybernetic/shared_cybernetic_module_base.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_component_cybernetic_shared_cybernetic_module_base_one_core = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/component/cybernetic/shared_cybernetic_module_base_one_core.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_component_cybernetic_shared_cybernetic_module_base_one_core, "object/tangible/component/cybernetic/shared_cybernetic_module_base_one_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_component_cybernetic_shared_cybernetic_module_base_three_core = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/component/cybernetic/shared_cybernetic_module_base_three_core.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_component_cybernetic_shared_cybernetic_module_base_three_core, "object/tangible/component/cybernetic/shared_cybernetic_module_base_three_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_component_cybernetic_shared_cybernetic_module_base_two_core = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/component/cybernetic/shared_cybernetic_module_base_two_core.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_component_cybernetic_shared_cybernetic_module_base_two_core, "object/tangible/component/cybernetic/shared_cybernetic_module_base_two_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
|
DEBUG_MODE = true;
local bgColor = {0, 0, 0};
require 'error'
require 'globals'
require 'functions'
require 'manager'
function love.load()
love.window.setTitle("Pokemon Remake")
font_n = love.graphics.newFont("fonts/Pokemon GB.ttf", 8)
font_lg = love.graphics.newFont("fonts/Pokemon GB.ttf", 16)
font_xl = love.graphics.newFont("fonts/Pokemon GB.ttf", 24)
bank_font = love.graphics.newFont("fonts/bank.ttf", 10)
love.graphics.setFont(font_n)
debug_init();
mgr_init();
game_load();
-- more init junk
game_state = "game"; -- splash, menu, game, credits - where the game starts
-- loading is last.
load_resources();
mgr_load();
end
function love.update(dt)
if not (critical_error) then
mgr_update(dt);
end
debug_update();
end
function love.draw()
if not (critical_error) then
--love.graphics.push()
mgr_draw();
--love.graphics.pop()
end
love.graphics.push()
debug_draw();
love.graphics.pop()
end
|
tmr.alarm(0, 60000, 1, function()
SDA_PIN = 6 -- sda pin, GPIO12
SCL_PIN = 5 -- scl pin, GPIO14
si7021 = require("si7021")
si7021.init(SDA_PIN, SCL_PIN)
si7021.read(OSS)
h = si7021.getHumidity()
t = si7021.getTemperature()
-- pressure in differents units
print("Humidity: "..(h / 100).."."..(h % 100).." %")
-- temperature in degrees Celsius and Farenheit
print("Temperature: "..(t/100).."."..(t%100).." deg C")
print("Temperature: "..(9 * t / 500 + 32).."."..(9 * t / 50 % 10).." deg F")
-- release module
si7021 = nil
package.loaded["si7021"]=nil
end)
|
local allowpolice = 0
local function SetGamePlayVars()
Citizen.CreateThread(function()
for i = 1, 25 do
EnableDispatchService(i, false)
end
-- enable pvp
for i = 0, 255 do
if NetworkIsPlayerConnected(i) then
if NetworkIsPlayerConnected(i) and GetPlayerPed(i) ~= nil then
SetCanAttackFriendly(GetPlayerPed(i), true, true)
end
end
end
NetworkSetFriendlyFireOption(true)
-- Disable vehicle rewards
DisablePlayerVehicleRewards(PlayerId())
while true do
Citizen.Wait(0)
local ped = PlayerPedId()
local timer = 0
if IsPedWearingHelmet(ped) then
timer = timer + 1
if timer >= 5000 and not IsPedInAnyVehicle(ped, true) then
RemovePedHelmet(ped, false)
timer = 0
end
end
end
end)
Citizen.CreateThread(function()
while true do
Wait(1000)
local id = PlayerId()
if allowpolice == 0 then
SetPlayerWantedLevel(id, 0, false)
SetPlayerWantedLevelNow(id, false)
else
if allowpolice == 1 then
for i = 1, 25 do
EnableDispatchService(i, false)
end
else
for i = 1, 25 do
EnableDispatchService(i, true)
end
end
SetPlayerWantedLevel(id, 2, false)
SetPlayerWantedLevelNoDrop(id, 2, false)
SetPlayerWantedLevelNow(id)
end
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(1000)
local pos = GetEntityCoords(PlayerPedId(), false)
local dist = GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), 2729.47, 1514.56, 23.79,false)
if dist > 150.0 then
ClearAreaOfCops(pos, 400.0)
else
Wait(5000)
end
end
end)
end
local gamePlayStarted = false
AddEventHandler("npc-core:playerSessionStarted", function()
if gamePlayStarted then return end
gamePlayStarted = true
SetGamePlayVars()
end)
RegisterNetEvent('robbery:aids')
AddEventHandler('robbery:aids', function()
local dist = GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), 2729.47, 1514.56, 23.79,false)
local myjob = exports["isPed"]:isPed("myjob")
if myjob == "ems" or myjob == "doctor" or myjob == "cop" then
allowpolice = 0
return
end
if dist < 100.0 then
if allowpolice > 0 then
allowpolice = 240
return
else
allowpolice = 240
end
while allowpolice > 0 do
Wait(1000)
allowpolice = allowpolice - 1
end
allowpolice = 0
end
end) |
--
-- created with TexturePacker - https://www.codeandweb.com/texturepacker
--
-- $TexturePacker:SmartUpdate:17b0fbf8a06a03411d042f0a38486ef0:4aa9984bcd18354344f573f467a295ff:11dc3e4dff043026a37f29c722a8b93f$
--
-- local sheetInfo = require("mysheet")
-- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() )
-- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} )
--
local SheetInfo = {}
SheetInfo.sheet =
{
frames = {
{
-- Monster 2-1
x=2,
y=2,
width=210,
height=196,
},
{
-- Monster 2-2
x=2,
y=200,
width=210,
height=196,
},
{
-- Monster 2-3
x=2,
y=398,
width=210,
height=196,
},
{
-- Monster 2-4
x=2,
y=200,
width=210,
height=196,
},
{
-- Monster 2-5
x=2,
y=2,
width=210,
height=196,
},
},
sheetContentWidth = 214,
sheetContentHeight = 596
}
SheetInfo.frameIndex =
{
["Monster 2-1"] = 1,
["Monster 2-2"] = 2,
["Monster 2-3"] = 3,
["Monster 2-4"] = 4,
["Monster 2-5"] = 5,
}
SheetInfo.sequences = {
{name = "walking", start = 1, count = 5, time = 500},
}
function SheetInfo:getSequences()
return self.sequences
end
function SheetInfo:getSheet()
return self.sheet;
end
function SheetInfo:getFrameIndex(name)
return self.frameIndex[name];
end
return SheetInfo
|
m = Map("buttons", "Buttons")
s = m:section(TypedSection, "button", translate("Configure Buttons"))
s.addremove = false
s.template = "cbi/tblsection"
en = s:option(Flag, "enable", "Enable")
en.rmempty = true
en.default = "1"
--if TECUSER then
--minp = s:option(Value, "minpress", "Minimum Press Time (ms)")
--minp.rmempty = true
--minp.datatype = "uinteger"
--minp.default = "1000"
--end
return m
|
-----------------------------------
-- Area: Abyssea_Vunkeral
-- NPC: Liloune
-- Standard Info NPC
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
player:startEvent(1099)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
local Util = require("vlua.util")
local Dep = require("vlua.dep")
local warn = Util.warn
local setmetatable = setmetatable
local type = type
local V_GETTER = 1
local V_SETTER = 2
---@class Ref
---@field value any
---@field get fun():any
---@param set fun(newValue:any):nil
---@param getter fun(self:any):any
---@param setter fun(self:any, newValue:any):nil
---@return Ref
local function ref(value, isReadonly)
local dep = Dep.new()
local function get(self)
if (Dep.target) then
dep:depend()
end
return value
end
local selfSet, set
if isReadonly then
set = function()
warn("readonly ref value")
end
selfSet = set
else
selfSet = function(self, newValue)
value = newValue
dep:notify()
end
set = function(newValue)
value = newValue
dep:notify()
end
end
local RefMetatable = {
__index = function(self, key)
assert(key == "value", 'only access Ref getter with "value" key')
return get()
end,
__newindex = function(self, key, newValue)
assert(key == "value", 'only access Ref setter with "value" key')
set(newValue)
end
}
local obj = {
get = get,
set = set,
[V_GETTER] = get,
[V_SETTER] = selfSet,
__isref = true
}
setmetatable(obj, RefMetatable)
return obj
end
return {
ref = ref
}
|
function onCreate()
makeLuaSprite('swag','pissing_too',120,-35)
scaleObject('swag',0.521814815,0.521814815)
addLuaSprite('swag',false)
close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage
end |
--
-- Lua INIT
--
-- Only runs this script if Alpha Screen loads -- only if there isn't files to read
if (vim.api.nvim_exec('echo argc()', true) == "0")
then
math.randomseed( os.time() ) -- For random header.
-- To split our quote, artist and source.
-- And automatically center it for screen loader of the header.
local function split(s)
local t = {}
local max_line_length = vim.api.nvim_get_option('columns')
local longest = 0 -- Value of longest string is 0 by default
for far in s:gmatch("[^\r\n]+") do
-- Break the line if it's actually bigger than terminal columns
local line
far:gsub('(%s*)(%S+)',
function(spc, word)
if not line or #line + #spc + #word > max_line_length then
table.insert(t, line)
line = word
else
line = line..spc..word
longest = max_line_length
end
end)
-- Get the string that is the longest
if (#line > longest) then
longest = #line
end
table.insert(t, line)
end
-- Center all strings by the longest
for i = 1, #t do
local space = longest - #t[i]
local left = math.floor(space/2)
local right = space - left
t[i] = string.rep(' ', left) .. t[i] .. string.rep(' ', right)
end
return t
end
-- Function to retrieve console output.
local function capture(cmd)
local handle = assert(io.popen(cmd, 'r'))
local output = assert(handle:read('*a'))
handle:close()
return output
end
-- Create button for initial keybind.
--- @param sc string
--- @param txt string
--- @param keybind string optional
--- @param keybind_opts table optional
local function button(sc, txt, keybind, keybind_opts)
local sc_ = sc:gsub("%s", ""):gsub("SPC", "<leader>")
local opts = {
position = "center",
shortcut = sc,
cursor = 5,
width = 50,
align_shortcut = "right",
hl_shortcut = "Keyword",
}
if keybind then
keybind_opts = vim.F.if_nil(keybind_opts, {noremap = true, silent = true, nowait = true})
opts.keymap = {"n", sc_, keybind, keybind_opts}
end
local function on_press()
local key = vim.api.nvim_replace_termcodes(sc_ .. '<Ignore>', true, false, true)
vim.api.nvim_feedkeys(key, "normal", false)
end
return {
type = "button",
val = txt,
on_press = on_press,
opts = opts,
}
end
-- All custom headers
Headers = {
{
[[ ]],
[[ ███████████ █████ ██ ]],
[[ ███████████ █████ ]],
[[ ████████████████ ███████████ ███ ███████ ]],
[[ ████████████████ ████████████ █████ ██████████████ ]],
[[ █████████████████████████████ █████ █████ ████ █████ ]],
[[ ██████████████████████████████████ █████ █████ ████ █████ ]],
[[ ██████ ███ █████████████████ ████ █████ █████ ████ ██████ ]],
[[ ██████ ██ ███████████████ ██ █████████████████ ]],
[[ ██████ ██ ███████████████ ██ █████████████████ ]],
},
{
'⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡀⠀⠀⠀⠀⢀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ',
'⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡖⠁⠀⠀⠀⠀⠀⠀⠈⢲⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀ ',
'⠀⠀⠀⠀⠀⠀⠀⠀⣼⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣧⠀⠀⠀⠀⠀⠀⠀⠀ ',
'⠀⠀⠀⠀⠀⠀⠀⣸⣿⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣇⠀⠀⠀⠀⠀⠀⠀ ',
'⠀⠀⠀⠀⠀⠀⠀⣿⣿⡇⠀⢀⣀⣤⣤⣤⣤⣀⡀⠀⢸⣿⣿⠀⠀⠀⠀⠀⠀⠀ ',
'⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣔⢿⡿⠟⠛⠛⠻⢿⡿⣢⣿⣿⡟⠀⠀⠀⠀⠀⠀⠀ ',
'⠀⠀⠀⠀⣀⣤⣶⣾⣿⣿⣿⣷⣤⣀⡀⢀⣀⣤⣾⣿⣿⣿⣷⣶⣤⡀⠀⠀⠀⠀ ',
'⠀⠀⢠⣾⣿⡿⠿⠿⠿⣿⣿⣿⣿⡿⠏⠻⢿⣿⣿⣿⣿⠿⠿⠿⢿⣿⣷⡀⠀⠀ ',
'⠀⢠⡿⠋⠁⠀⠀⢸⣿⡇⠉⠻⣿⠇⠀⠀⠸⣿⡿⠋⢰⣿⡇⠀⠀⠈⠙⢿⡄⠀ ',
'⠀⡿⠁⠀⠀⠀⠀⠘⣿⣷⡀⠀⠰⣿⣶⣶⣿⡎⠀⢀⣾⣿⠇⠀⠀⠀⠀⠈⢿⠀ ',
'⠀⡇⠀⠀⠀⠀⠀⠀⠹⣿⣷⣄⠀⣿⣿⣿⣿⠀⣠⣾⣿⠏⠀⠀⠀⠀⠀⠀⢸⠀ ',
'⠀⠁⠀⠀⠀⠀⠀⠀⠀⠈⠻⢿⢇⣿⣿⣿⣿⡸⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠈⠀ ',
'⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⣿⣿⣿⣿⣧⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ',
'⠀⠀⠀⠐⢤⣀⣀⢀⣀⣠⣴⣿⣿⠿⠋⠙⠿⣿⣿⣦⣄⣀⠀⠀⣀⡠⠂⠀⠀⠀ ',
'⠀⠀⠀⠀⠀⠈⠉⠛⠛⠛⠛⠉⠀⠀⠀⠀⠀⠈⠉⠛⠛⠛⠛⠋⠁⠀⠀⠀⠀⠀ ',
},
{
[[================= =============== =============== ======== ========]],
[[\\ . . . . . . .\\ //. . . . . . .\\ //. . . . . . .\\ \\. . .\\// . . //]],
[[||. . ._____. . .|| ||. . ._____. . .|| ||. . ._____. . .|| || . . .\/ . . .||]],
[[|| . .|| ||. . || || . .|| ||. . || || . .|| ||. . || ||. . . . . . . ||]],
[[||. . || || . .|| ||. . || || . .|| ||. . || || . .|| || . | . . . . .||]],
[[|| . .|| ||. _-|| ||-_ .|| ||. . || || . .|| ||. _-|| ||-_.|\ . . . . ||]],
[[||. . || ||-' || || `-|| || . .|| ||. . || ||-' || || `|\_ . .|. .||]],
[[|| . _|| || || || || ||_ . || || . _|| || || || |\ `-_/| . ||]],
[[||_-' || .|/ || || \|. || `-_|| ||_-' || .|/ || || | \ / |-_.||]],
[[|| ||_-' || || `-_|| || || ||_-' || || | \ / | `||]],
[[|| `' || || `' || || `' || || | \ / | ||]],
[[|| .===' `===. .==='.`===. .===' /==. | \/ | ||]],
[[|| .==' \_|-_ `===. .===' _|_ `===. .===' _-|/ `== \/ | ||]],
[[|| .==' _-' `-_ `=' _-' `-_ `=' _-' `-_ /| \/ | ||]],
[[|| .==' _-' '-__\._-' '-_./__-' `' |. /| | ||]],
[[||.==' _-' `' | /==.||]],
[[==' _-' N E O V I M \/ `==]],
[[\ _-' `-_ /]],
[[ `'' ``' ]],
},
{
[[ /|_ ]],
[[ (o o / ]],
[[ |. ~. ]],
[[ じしf_,)ノ ]],
},
{
' ▀████▀▄▄ ▄█ ',
' █▀ ▀▀▄▄▄▄▄ ▄▄▀▀█ ',
' ▄ █ ▀▀▀▀▄ ▄▀ ',
' ▄▀ ▀▄ ▀▄ ▀▄▀ ',
' ▄▀ █ █▀ ▄█▀▄ ▄█ ',
' ▀▄ ▀▄ █ ▀██▀ ██▄█ ',
' ▀▄ ▄▀ █ ▄██▄ ▄ ▄ ▀▀ █ ',
' █ ▄▀ █ ▀██▀ ▀▀ ▀▀ ▄▀ ',
' █ █ █ ▄▄ ▄▀ ',
},
{
" ",
" ███╗ ██╗███████╗ ██████╗ ██╗ ██╗██╗███╗ ███╗ ",
" ████╗ ██║██╔════╝██╔═══██╗██║ ██║██║████╗ ████║ ",
" ██╔██╗ ██║█████╗ ██║ ██║██║ ██║██║██╔████╔██║ ",
" ██║╚██╗██║██╔══╝ ██║ ██║╚██╗ ██╔╝██║██║╚██╔╝██║ ",
" ██║ ╚████║███████╗╚██████╔╝ ╚████╔╝ ██║██║ ╚═╝ ██║ ",
" ╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚═══╝ ╚═╝╚═╝ ╚═╝ ",
" ",
},
{
[[ __ ]],
[[ ___ ___ ___ __ __ /\_\ ___ ___ ]],
[[ / _ `\ / __`\ / __`\/\ \/\ \\/\ \ / __` __`\ ]],
[[/\ \/\ \/\ __//\ \_\ \ \ \_/ |\ \ \/\ \/\ \/\ \ ]],
[[\ \_\ \_\ \____\ \____/\ \___/ \ \_\ \_\ \_\ \_\]],
[[ \/_/\/_/\/____/\/___/ \/__/ \/_/\/_/\/_/\/_/]],
},
}
--
-- Sections for Alpha.
--
local header = {
type = "text",
val = Headers[math.random(#Headers)],
opts = {
position = "center",
hl = "Type"
-- wrap = "overflow";
}
}
local footer = {
type = "text",
-- Change 'rdn' to any program that gives you a random quote.
-- https://github.com/BeyondMagic/scripts/blob/master/quotes/rdn
-- Which returns one to three lines, being each divided by a line break.
-- Or just an array: { "I see you:", "Above you." }
val = split(capture('rdn')),
opts = {
position = "center",
hl = "Number",
}
}
local buttons = {
type = "group",
val = {
button("e", " New Buffer", ':tabnew<CR>'),
button("f", " Find file", ':Telescope find_files<CR>'),
button("h", " Recently opened files", ':Telescope oldfiles<CR>'),
button("r", " Frecency/MRU", ':Telescope oldfiles<CR>'),
button("g", " Open Last Session", ':source ~/.config/nvim/session.vim<CR>'),
button("m", " Word Finder", ':Telescope live_grep<CR>'),
button("l", " Marks", ':Telescope marks<CR>'),
},
opts = {
spacing = 1
}
}
--
-- Centering handler of ALPHA
--
local ol = { -- occupied lines
icon = #header.val, -- CONST: number of lines that your header will occupy
message = 1 + #footer.val, -- CONST: because of padding at the bottom
length_buttons = #buttons.val * 2 - 1, -- CONST: it calculate the number that buttons will occupy
neovim_lines = 3, -- CONST: 2 of command line, 1 of the top bar
padding_between = 2, -- STATIC: can be set to anything, padding between keybinds and header
}
local left_terminal_value = vim.api.nvim_get_option('lines') - (ol.length_buttons + ol.message + ol.padding_between + ol.icon + ol.neovim_lines)
local top_padding = math.floor(left_terminal_value / 2)
local bottom_padding = left_terminal_value - top_padding
--
-- Set alpha sections
--
local opts = {
layout = {
{ type = "padding", val = top_padding },
header,
{ type = "padding", val = ol.padding_between },
buttons,
footer,
{ type = "padding", val = bottom_padding },
},
opts = {
margin = 5
},
}
require('alpha').setup(opts)
--else
--vim.api.nvim_exec('silent source ~/.config/nvim/session.vim', false)
end
|
-- -*- lua-indent-level: 4; -*-
--- GeminiConfigCmd-1.0 handles access to an options table through the "command line" interface via the ChatFrames.
--[[
GeminiConfigCmd-1.0
Handles commandline optionstable access
REQUIRES: AceConsole-3.0 for command registration (loaded on demand)
]]
-- TODO: plugin args
local MAJOR, MINOR = "Gemini:ConfigCmd-1.0", 1
local APkg = Apollo.GetPackage(MAJOR)
if APkg and (APkg.nVersion or 0) >= MINOR then
return -- no upgrade is needed
end
local GeminiConfigCmd = APkg and APkg.tPackage or {}
local tLibError = Apollo.GetPackage("Gemini:LibError-1.0")
local fnErrorHandler = tLibError and tLibError.tPackage and tLibError.tPackage.Error or Print
GeminiConfigCmd.commands = GeminiConfigCmd.commands or {}
local commands = GeminiConfigCmd.commands
local cfgreg = Apollo.GetPackage("Gemini:ConfigRegistry-1.0").tPackage
-- Lua APIs
local strsub, strsplit, strlower, strmatch, strtrim = string.sub, string.split, string.lower, string.match, string.trim
local format, tonumber, tostring = string.format, tonumber, tostring
local tsort, tinsert = table.sort, table.insert
local select, pairs, next, type = select, pairs, next, type
local error, assert = error, assert
local print = Print
-- WoW APIs
local _G = _G
local L = setmetatable({}, { -- TODO: replace with proper locale
__index = function(self,k) return k end
})
-- constants used by getparam() calls below
local handlertypes = { ["table"] = true }
local handlermsg = "expected a table"
local functypes = { ["function"] = true, ["string"] = true }
local funcmsg = "expected function or member name"
-- pickfirstset() - picks the first non-nil value and returns it
local function pickfirstset(...)
for i = 1, select("#", ...) do
if select(i, ...) ~= nil then
return select(i, ...)
end
end
end
-- err() - produce real error() regarding malformed options tables etc
local function err(info, inputpos, msg)
local cmdstr = " " .. strsub(info.input, 1, inputpos - 1)
error(MAJOR .. ": /" .. info[0] .. cmdstr .. ": " .. (msg or "malformed options table"), 2)
end
-- usererr() - produce chatframe message regarding bad slash syntax etc
local function usererr(info, inputpos, msg)
local cmdstr = strsub(info.input, 1, inputpos - 1);
print("/" .. info[0] .. " " .. cmdstr .. ": " .. (msg or "malformed options table"))
end
-- callmethod() - call a given named method (e.g. "get", "set") with given arguments
local function callmethod(info, inputpos, tab, methodtype, ...)
local method = info[methodtype]
if not method then
err(info, inputpos, "'" .. methodtype .. "': not set")
end
info.arg = tab.arg
info.option = tab
info.type = tab.type
if type(method) == "function" then
return method(info, ...)
elseif type(method) == "string" then
if type(info.handler[method]) ~= "function" then
err(info, inputpos, "'" .. methodtype .. "': '" .. method .. "' is not a member function of " .. tostring(info.handler))
end
return info.handler[method](info.handler, info, ...)
else
assert(false) -- type should have already been checked on read
end
end
-- callfunction() - call a given named function (e.g. "name", "desc") with given arguments
local function callfunction(info, tab, methodtype, ...)
local method = tab[methodtype]
info.arg = tab.arg
info.option = tab
info.type = tab.type
if type(method) == "function" then
return method(info, ...)
else
assert(false) -- type should have already been checked on read
end
end
-- do_final() - do the final step (set/execute) along with validation and confirmation
local function do_final(info, inputpos, tab, methodtype, ...)
if info.validate then
local res = callmethod(info, inputpos, tab, "validate", ...)
if type(res) == "string" then
usererr(info, inputpos, "'" .. strsub(info.input, inputpos) .. "' - " .. res)
return
end
end
-- console ignores .confirm
callmethod(info, inputpos, tab, methodtype, ...)
end
-- getparam() - used by handle() to retreive and store "handler", "get", "set", etc
local function getparam(info, inputpos, tab, depth, paramname, types, errormsg)
local old, oldat = info[paramname], info[paramname .. "_at"]
local val = tab[paramname]
if val ~= nil then
if val == false then
val = nil
elseif not types[type(val)] then
err(info, inputpos, "'" .. paramname .. "' - " .. errormsg)
end
info[paramname] = val
info[paramname .. "_at"] = depth
end
return old, oldat
end
-- iterateargs(tab) - custom iterator that iterates both t.args and t.plugins.*
local dummytable = {}
local function iterateargs(tab)
if not tab.plugins then
return pairs(tab.args)
end
local argtabkey, argtab = next(tab.plugins)
local v
return function(_, k)
while argtab do
k, v = next(argtab, k)
if k then return k, v end
if argtab == tab.args then
argtab = nil
else
argtabkey, argtab = next(tab.plugins, argtabkey)
if not argtabkey then
argtab = tab.args
end
end
end
end
end
local function checkhidden(info, inputpos, tab)
if tab.cmdHidden ~= nil then
return tab.cmdHidden
end
local hidden = tab.hidden
if type(hidden) == "function" or type(hidden) == "string" then
info.hidden = hidden
hidden = callmethod(info, inputpos, tab, 'hidden')
info.hidden = nil
end
return hidden
end
local function showhelp(info, inputpos, tab, depth, noHead)
if not noHead then
-- print("<T TextColor=\"ff33ff99\">"..info.appName.."</T>: Arguments to <T TextColor=\"ffffff78\">/"..info[0].."</T> "..strsub(info.input,1,inputpos-1)..":")
print(info.appName .. ": Arguments to /" .. info[0] .. " " .. strsub(info.input, 1, inputpos - 1) .. ":")
end
local sortTbl = {} -- [1..n]=name
local refTbl = {} -- [name]=tableref
for k, v in iterateargs(tab) do
if not refTbl[k] then -- a plugin overriding something in .args
tinsert(sortTbl, k)
refTbl[k] = v
end
end
tsort(sortTbl, function(one, two)
local o1 = refTbl[one].order or 100
local o2 = refTbl[two].order or 100
if type(o1) == "function" or type(o1) == "string" then
info.order = o1
info[#info + 1] = one
o1 = callmethod(info, inputpos, refTbl[one], "order")
info[#info] = nil
info.order = nil
end
if type(o2) == "function" or type(o1) == "string" then
info.order = o2
info[#info + 1] = two
o2 = callmethod(info, inputpos, refTbl[two], "order")
info[#info] = nil
info.order = nil
end
if o1 < 0 and o2 < 0 then return o1 < o2 end
if o2 < 0 then return true end
if o1 < 0 then return false end
if o1 == o2 then return tostring(one) < tostring(two) end -- compare names
return o1 < o2
end)
for i = 1, #sortTbl do
local k = sortTbl[i]
local v = refTbl[k]
if not checkhidden(info, inputpos, v) then
if v.type ~= "description" and v.type ~= "header" then
-- recursively show all inline groups
local name, desc = v.name, v.desc
if type(name) == "function" then
name = callfunction(info, v, 'name')
end
if type(desc) == "function" then
desc = callfunction(info, v, 'desc')
end
if v.type == "group" and pickfirstset(v.cmdInline, v.inline, false) then
print(" " .. (desc or name) .. ":")
local oldhandler, oldhandler_at = getparam(info, inputpos, v, depth, "handler", handlertypes, handlermsg)
showhelp(info, inputpos, v, depth, true)
info.handler, info.handler_at = oldhandler, oldhandler_at
else
local key = k:gsub(" ", "_")
print(" |cffffff78" .. key .. "|r - " .. (desc or name or ""))
end
end
end
end
end
local function keybindingValidateFunc(text)
if text == nil or text == "NONE" then
return nil
end
text = text:upper()
local shift, ctrl, alt
local modifier
while true do
if text == "-" then
break
end
modifier, text = strsplit('-', text, 2)
if text then
if modifier ~= "SHIFT" and modifier ~= "CTRL" and modifier ~= "ALT" then
return false
end
if modifier == "SHIFT" then
if shift then
return false
end
shift = true
end
if modifier == "CTRL" then
if ctrl then
return false
end
ctrl = true
end
if modifier == "ALT" then
if alt then
return false
end
alt = true
end
else
text = modifier
break
end
end
if text == "" then
return false
end
if not text:find("^F%d+$") and text ~= "CAPSLOCK" and text:len() ~= 1 and (text:byte() < 128 or text:len() > 4) and not _G["KEY_" .. text] then
return false
end
local s = text
if shift then
s = "SHIFT-" .. s
end
if ctrl then
s = "CTRL-" .. s
end
if alt then
s = "ALT-" .. s
end
return s
end
-- handle() - selfrecursing function that processes input->optiontable
-- - depth - starts at 0
-- - retfalse - return false rather than produce error if a match is not found (used by inlined groups)
local function handle(info, inputpos, tab, depth, retfalse)
if not (type(tab) == "table" and type(tab.type) == "string") then err(info, inputpos) end
-------------------------------------------------------------------
-- Grab hold of handler,set,get,func,etc if set (and remember old ones)
-- Note that we do NOT validate if method names are correct at this stage,
-- the handler may change before they're actually used!
local oldhandler, oldhandler_at = getparam(info, inputpos, tab, depth, "handler", handlertypes, handlermsg)
local oldset, oldset_at = getparam(info, inputpos, tab, depth, "set", functypes, funcmsg)
local oldget, oldget_at = getparam(info, inputpos, tab, depth, "get", functypes, funcmsg)
local oldfunc, oldfunc_at = getparam(info, inputpos, tab, depth, "func", functypes, funcmsg)
local oldvalidate, oldvalidate_at = getparam(info, inputpos, tab, depth, "validate", functypes, funcmsg)
--local oldconfirm,oldconfirm_at = getparam(info,inputpos,tab,depth,"confirm",functypes,funcmsg)
-------------------------------------------------------------------
-- Act according to .type of this table
if tab.type == "group" then
------------ group --------------------------------------------
if type(tab.args) ~= "table" then err(info, inputpos) end
if tab.plugins and type(tab.plugins) ~= "table" then err(info, inputpos) end
-- grab next arg from input
local _, nextpos, arg = (info.input):find(" *([^ ]+) *", inputpos)
if not arg then
showhelp(info, inputpos, tab, depth)
return
end
nextpos = nextpos + 1
-- loop .args and try to find a key with a matching name
for k, v in iterateargs(tab) do
if not (type(k) == "string" and type(v) == "table" and type(v.type) == "string") then err(info, inputpos, "options table child '" .. tostring(k) .. "' is malformed") end
-- is this child an inline group? if so, traverse into it
if v.type == "group" and pickfirstset(v.cmdInline, v.inline, false) then
info[depth + 1] = k
if handle(info, inputpos, v, depth + 1, true) == false then
info[depth + 1] = nil
-- wasn't found in there, but that's ok, we just keep looking down here
else
return -- done, name was found in inline group
end
-- matching name and not a inline group
elseif strlower(arg) == strlower(k:gsub(" ", "_")) then
info[depth + 1] = k
return handle(info, nextpos, v, depth + 1)
end
end
-- no match
if retfalse then
-- restore old infotable members and return false to indicate failure
info.handler, info.handler_at = oldhandler, oldhandler_at
info.set, info.set_at = oldset, oldset_at
info.get, info.get_at = oldget, oldget_at
info.func, info.func_at = oldfunc, oldfunc_at
info.validate, info.validate_at = oldvalidate, oldvalidate_at
--info.confirm,info.confirm_at = oldconfirm,oldconfirm_at
return false
end
-- couldn't find the command, display error
usererr(info, inputpos, "'" .. arg .. "' - " .. L["unknown argument"])
return
end
local str = strsub(info.input, inputpos);
if tab.type == "execute" then
------------ execute --------------------------------------------
do_final(info, inputpos, tab, "func")
elseif tab.type == "input" then
------------ input --------------------------------------------
local res = true
if tab.pattern then
if not (type(tab.pattern) == "string") then err(info, inputpos, "'pattern' - expected a string") end
if not strmatch(str, tab.pattern) then
usererr(info, inputpos, "'" .. str .. "' - " .. L["invalid input"])
return
end
end
do_final(info, inputpos, tab, "set", str)
elseif tab.type == "toggle" then
------------ toggle --------------------------------------------
local b
local str = strtrim(strlower(str))
if str == "" then
b = callmethod(info, inputpos, tab, "get")
if tab.tristate then
--cycle in true, nil, false order
if b then
b = nil
elseif b == nil then
b = false
else
b = true
end
else
b = not b
end
elseif str == L["on"] then
b = true
elseif str == L["off"] then
b = false
elseif tab.tristate and str == L["default"] then
b = nil
else
if tab.tristate then
usererr(info, inputpos, format(L["'%s' - expected 'on', 'off' or 'default', or no argument to toggle."], str))
else
usererr(info, inputpos, format(L["'%s' - expected 'on' or 'off', or no argument to toggle."], str))
end
return
end
do_final(info, inputpos, tab, "set", b)
elseif tab.type == "range" then
------------ range --------------------------------------------
local val = tonumber(str)
if not val then
usererr(info, inputpos, "'" .. str .. "' - " .. L["expected number"])
return
end
if type(info.step) == "number" then
val = val - (val % info.step)
end
if type(info.min) == "number" and val < info.min then
usererr(info, inputpos, val .. " - " .. format(L["must be equal to or higher than %s"], tostring(info.min)))
return
end
if type(info.max) == "number" and val > info.max then
usererr(info, inputpos, val .. " - " .. format(L["must be equal to or lower than %s"], tostring(info.max)))
return
end
do_final(info, inputpos, tab, "set", val)
elseif tab.type == "select" then
------------ select ------------------------------------
local str = strtrim(strlower(str))
local values = tab.values
if type(values) == "function" or type(values) == "string" then
info.values = values
values = callmethod(info, inputpos, tab, "values")
info.values = nil
end
if str == "" then
local b = callmethod(info, inputpos, tab, "get")
local fmt = "|cffffff78- [%s]|r %s"
local fmt_sel = "|cffffff78- [%s]|r %s |cffff0000*|r"
print(L["Options for |cffffff78" .. info[#info] .. "|r:"])
for k, v in pairs(values) do
if b == k then
print(fmt_sel:format(k, v))
else
print(fmt:format(k, v))
end
end
return
end
local ok
for k, v in pairs(values) do
if strlower(k) == str then
str = k -- overwrite with key (in case of case mismatches)
ok = true
break
end
end
if not ok then
usererr(info, inputpos, "'" .. str .. "' - " .. L["unknown selection"])
return
end
do_final(info, inputpos, tab, "set", str)
elseif tab.type == "multiselect" then
------------ multiselect -------------------------------------------
local str = strtrim(strlower(str))
local values = tab.values
if type(values) == "function" or type(values) == "string" then
info.values = values
values = callmethod(info, inputpos, tab, "values")
info.values = nil
end
if str == "" then
local fmt = "|cffffff78- [%s]|r %s"
local fmt_sel = "|cffffff78- [%s]|r %s |cffff0000*|r"
print(L["Options for |cffffff78" .. info[#info] .. "|r (multiple possible):"])
for k, v in pairs(values) do
if callmethod(info, inputpos, tab, "get", k) then
print(fmt_sel:format(k, v))
else
print(fmt:format(k, v))
end
end
return
end
--build a table of the selections, checking that they exist
--parse for =on =off =default in the process
--table will be key = true for options that should toggle, key = [on|off|default] for options to be set
local sels = {}
for v in str:gmatch("[^ ]+") do
--parse option=on etc
local opt, val = v:match('(.+)=(.+)')
--get option if toggling
if not opt then
opt = v
end
--check that the opt is valid
local ok
for k, v in pairs(values) do
if strlower(k) == opt then
opt = k -- overwrite with key (in case of case mismatches)
ok = true
break
end
end
if not ok then
usererr(info, inputpos, "'" .. opt .. "' - " .. L["unknown selection"])
return
end
--check that if val was supplied it is valid
if val then
if val == L["on"] or val == L["off"] or (tab.tristate and val == L["default"]) then
--val is valid insert it
sels[opt] = val
else
if tab.tristate then
usererr(info, inputpos, format(L["'%s' '%s' - expected 'on', 'off' or 'default', or no argument to toggle."], v, val))
else
usererr(info, inputpos, format(L["'%s' '%s' - expected 'on' or 'off', or no argument to toggle."], v, val))
end
return
end
else
-- no val supplied, toggle
sels[opt] = true
end
end
for opt, val in pairs(sels) do
local newval
if (val == true) then
--toggle the option
local b = callmethod(info, inputpos, tab, "get", opt)
if tab.tristate then
--cycle in true, nil, false order
if b then
b = nil
elseif b == nil then
b = false
else
b = true
end
else
b = not b
end
newval = b
else
--set the option as specified
if val == L["on"] then
newval = true
elseif val == L["off"] then
newval = false
elseif val == L["default"] then
newval = nil
end
end
do_final(info, inputpos, tab, "set", opt, newval)
end
elseif tab.type == "color" then
------------ color --------------------------------------------
local str = strtrim(strlower(str))
if str == "" then
--TODO: Show current value
return
end
local r, g, b, a
local hasAlpha = tab.hasAlpha
if type(hasAlpha) == "function" or type(hasAlpha) == "string" then
info.hasAlpha = hasAlpha
hasAlpha = callmethod(info, inputpos, tab, 'hasAlpha')
info.hasAlpha = nil
end
if hasAlpha then
if str:len() == 8 and str:find("^%x*$") then
--parse a hex string
r, g, b, a = tonumber(str:sub(1, 2), 16) / 255, tonumber(str:sub(3, 4), 16) / 255, tonumber(str:sub(5, 6), 16) / 255, tonumber(str:sub(7, 8), 16) / 255
else
--parse seperate values
r, g, b, a = str:match("^([%d%.]+) ([%d%.]+) ([%d%.]+) ([%d%.]+)$")
r, g, b, a = tonumber(r), tonumber(g), tonumber(b), tonumber(a)
end
if not (r and g and b and a) then
usererr(info, inputpos, format(L["'%s' - expected 'RRGGBBAA' or 'r g b a'."], str))
return
end
if r >= 0.0 and r <= 1.0 and g >= 0.0 and g <= 1.0 and b >= 0.0 and b <= 1.0 and a >= 0.0 and a <= 1.0 then
--values are valid
elseif r >= 0 and r <= 255 and g >= 0 and g <= 255 and b >= 0 and b <= 255 and a >= 0 and a <= 255 then
--values are valid 0..255, convert to 0..1
r = r / 255
g = g / 255
b = b / 255
a = a / 255
else
--values are invalid
usererr(info, inputpos, format(L["'%s' - values must all be either in the range 0..1 or 0..255."], str))
end
else
a = 1.0
if str:len() == 6 and str:find("^%x*$") then
--parse a hex string
r, g, b = tonumber(str:sub(1, 2), 16) / 255, tonumber(str:sub(3, 4), 16) / 255, tonumber(str:sub(5, 6), 16) / 255
else
--parse seperate values
r, g, b = str:match("^([%d%.]+) ([%d%.]+) ([%d%.]+)$")
r, g, b = tonumber(r), tonumber(g), tonumber(b)
end
if not (r and g and b) then
usererr(info, inputpos, format(L["'%s' - expected 'RRGGBB' or 'r g b'."], str))
return
end
if r >= 0.0 and r <= 1.0 and g >= 0.0 and g <= 1.0 and b >= 0.0 and b <= 1.0 then
--values are valid
elseif r >= 0 and r <= 255 and g >= 0 and g <= 255 and b >= 0 and b <= 255 then
--values are valid 0..255, convert to 0..1
r = r / 255
g = g / 255
b = b / 255
else
--values are invalid
usererr(info, inputpos, format(L["'%s' - values must all be either in the range 0-1 or 0-255."], str))
end
end
do_final(info, inputpos, tab, "set", r, g, b, a)
elseif tab.type == "keybinding" then
------------ keybinding --------------------------------------------
local str = strtrim(strlower(str))
if str == "" then
--TODO: Show current value
return
end
local value = keybindingValidateFunc(str:upper())
if value == false then
usererr(info, inputpos, format(L["'%s' - Invalid Keybinding."], str))
return
end
do_final(info, inputpos, tab, "set", value)
elseif tab.type == "description" then
------------ description --------------------
-- ignore description, GUI config only
else
err(info, inputpos, "unknown options table item type '" .. tostring(tab.type) .. "'")
end
end
--- Handle the chat command.
-- This is usually called from a chat command handler to parse the command input as operations on an aceoptions table.\\
-- GeminiConfigCmd uses this function internally when a slash command is registered with `:CreateChatCommand`
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output)
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param input The commandline input (as given by the WoW handler, i.e. without the command itself)
-- @usage
-- MyAddon = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("MyAddon")
-- -- Use AceConsole-3.0 to register a Chat Command
-- Apollo.GetPackage("Gemini:ConfigCmd-1.0").tPackage:RegisterChatCommand("mychat", "ChatCommand")
--
-- -- Show the GUI if no input is supplied, otherwise handle the chat input.
-- function MyAddon:ChatCommand(input)
-- -- Assuming "MyOptions" is the appName of a valid options table
-- if not input or input:trim() == "" then
-- Apollo.GetPackage("Gemini:ConfigDialog-1.0").tPackage:Open("MyOptions")
-- else
-- Apollo.GetPackage("Gemini:ConfigCmd-1.0").tPackage.HandleCommand(MyAddon, "mychat", "MyOptions", input)
-- end
-- end
function GeminiConfigCmd:HandleCommand(slashcmd, input)
local appName = self:GetChatCommandOptions(slashcmd)
local optgetter = cfgreg:GetOptionsTable(appName)
if not optgetter then
error([[Usage: HandleCommand("slashcmd", "appName", "input"): 'appName' - no options table "]] .. tostring(appName) .. [[" has been registered]], 2)
end
local options = assert(optgetter("cmd", MAJOR))
local info = {
-- Don't try to recycle this, it gets handed off to callbacks and whatnot
[0] = slashcmd,
appName = appName,
options = options,
input = input,
self = self,
handler = self,
uiType = "cmd",
uiName = MAJOR,
}
xpcall(function() handle(info, 1, options, 0) end, fnErrorHandler)
end
--- Utility function to create a slash command handler.
-- Also registers tab completion with AceTab
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output)
-- @param appName The application name as given to `:RegisterOptionsTable()`
function GeminiConfigCmd:CreateChatCommand(slashcmd, appName)
Apollo.RegisterSlashCommand(slashcmd, "HandleCommand", self)
commands[slashcmd] = appName
end
--- Utility function that returns the options table that belongs to a slashcommand.
-- Designed to be used for the AceTab interface.
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output)
-- @return The options table associated with the slash command (or nil if the slash command was not registered)
function GeminiConfigCmd:GetChatCommandOptions(slashcmd)
return commands[slashcmd]
end
Apollo.RegisterPackage(GeminiConfigCmd, MAJOR, MINOR, {})
|
local maps = {
{
mode = "n",
key = "<C-_>",
cmd = ":CommentToggle<cr>",
options = {
noremap = true,
}
},
{
mode = "v",
key = "<C-_>",
cmd = ":'<,'>CommentToggle<cr>",
options = {
noremap = true,
}
},
}
return maps
|
SWEP.Base = "aw_tool_base"
SWEP.PrintName = "Remover"
SWEP.ToolName = "aw_remover"
function SWEP:PrimaryAttack()
if SERVER then
local trace = self:MakeTrace()
if IsValid(trace.Entity) then
trace.Entity:Remove()
end
else
local trace = self:MakeTrace()
if IsValid(trace.Entity) then
trace.Entity:EmitSound("buttons/button15.wav", 75, 100, 1, CHAN_WEAPON)
end
end
end
function SWEP:ToolOptions(frame)
end
|
include("PopupDialog.lua");
include("CQUICommon.lua");
-- ===========================================================================
-- Cached Base Functions
-- ===========================================================================
BASE_CQUI_UpdateDragMap = UpdateDragMap;
BASE_CQUI_OnUnitSelectionChanged = OnUnitSelectionChanged;
BASE_CQUI_DefaultKeyDownHandler = DefaultKeyDownHandler;
BASE_CQUI_DefaultKeyUpHandler = DefaultKeyUpHandler;
BASE_CQUI_ClearAllCachedInputState = ClearAllCachedInputState;
BASE_CQUI_OnUserRequestClose = OnUserRequestClose;
-- ===========================================================================
-- CQUI Members
-- ===========================================================================
local CQUI_HOTKEYMODE_ENHANCED = 2;
local CQUI_HOTKEYMODE_CLASSIC = 1;
local CQUI_HOTKEYMODE_STANDARD = 0;
local CQUI_cityview :boolean = false;
local CQUI_hotkeyMode :number = CQUI_HOTKEYMODE_ENHANCED;
local CQUI_isShiftDown :boolean = false;
local CQUI_isAltDown :boolean = false;
function CQUI_OnSettingsUpdate()
CQUI_hotkeyMode = GameConfiguration.GetValue("CQUI_BindingsMode");
end
LuaEvents.CQUI_SettingsUpdate.Add( CQUI_OnSettingsUpdate );
LuaEvents.CQUI_SettingsInitialized.Add( CQUI_OnSettingsUpdate );
-- ===========================================================================
-- CQUI Base Extension Functions
-- Each of these functions call the Base Function found in WorldInput.lua
-- ===========================================================================
function OnUserRequestClose()
CQUI_isAltDown = false;
CQUI_isShiftDown = false;
BASE_CQUI_OnUserRequestClose();
end
-- ===========================================================================
function UpdateDragMap()
if g_isMouseDragging then
-- Event sets a global in PlotInfo so tiles are not purchased while dragging
LuaEvents.CQUI_StartDragMap();
end
return BASE_CQUI_UpdateDragMap();
end
-- ===========================================================================
function OnUnitSelectionChanged( playerID:number, unitID:number, hexI:number, hexJ:number, hexK:number, isSelected:boolean, isEditable:boolean )
local msg = "** Function Entry: OnUnitSelectionChanged (CQUI Hook). playerId:"..tostring(playerID).." unitId:"..tostring(unitID).." hexI:"..tostring(hexI).." hexJ:"..tostring(hexJ).." hexK:"..tostring(hexK).." isSelected:"..tostring(isSelected).." isEditable:"..tostring(isEditable);
print_debug(msg);
if playerID ~= Game.GetLocalPlayer() then
return;
end
-- CQUI (Azurency) : Fixes a Vanilla bug from SelectUnit.lua (not taking in account the district range attack)
-- CQUI (Azurency) : If a selection is occuring and the district attack interface mode is up, take it down.
if UI.GetInterfaceMode() == InterfaceModeTypes.DISTRICT_RANGE_ATTACK then
UI.SetInterfaceMode(InterfaceModeTypes.SELECTION);
end
return BASE_CQUI_OnUnitSelectionChanged( playerID, unitID, hexI, hexJ, hexK, isSelected, isEditable );
end
-- ===========================================================================
function DefaultKeyDownHandler( uiKey:number )
print_debug("** Function Entry: DefaultKeyDownHandler (CQUI Hook). uiKey: "..tostring(uiKey));
-- Note: This function always returns false, by design in Base game
BASE_CQUI_DefaultKeyDownHandler( uiKey );
--CQUI Keybinds
local keyPanChanged :boolean = false;
if uiKey == Keys.VK_SHIFT then
print_debug("CQUI_isShiftDown = true");
CQUI_isShiftDown = true;
end
if uiKey == Keys.VK_ALT then
print_debug("CQUI_isAltDown = true");
CQUI_isAltDown = true;
end
if CQUI_hotkeyMode == CQUI_HOTKEYMODE_ENHANCED then
if (uiKey == Keys.W) then
keyPanChanged = true;
m_isUPpressed = true;
end
if (uiKey == Keys.D) then
keyPanChanged = true;
m_isRIGHTpressed = true;
end
if (uiKey == Keys.S) then
keyPanChanged = true;
m_isDOWNpressed = true;
end
if (uiKey == Keys.A) then
keyPanChanged = true;
m_isLEFTpressed = true;
end
end
if (keyPanChanged == true) then
-- Base game file uses m_edgePanX and m_edgePanY... but those values do not ever appear change from 0, so just send 0.
ProcessPan(0, 0);
return true;
end
-- Allow other handlers of KeyDown events to capture input, if any exist after World Input
return false;
end
-- ===========================================================================
function DefaultKeyUpHandler( uiKey:number )
print_debug("** Function Entry: DefaultKeyUpHandler (CQUI Hook) uiKey: "..tostring(uiKey));
-- If set to Standard, just let the game do its thing
if CQUI_hotkeyMode == CQUI_HOTKEYMODE_STANDARD then
if uiKey == Keys.VK_SHIFT then
CQUI_isShiftDown = false;
end
if uiKey == Keys.VK_ALT then
CQUI_isAltDown = false;
end
return BASE_CQUI_DefaultKeyUpHandler(uiKey);
end
local keyPanChanged :boolean = false;
local cquiHandledKey :boolean = false;
local selectedUnit = UI.GetHeadSelectedUnit();
local unitType = nil;
local formationClass = nil;
if (selectedUnit) then
unitType = GameInfo.Units[selectedUnit:GetUnitType()].UnitType;
formationClass = GameInfo.Units[selectedUnit:GetUnitType()].FormationClass;
end
--CQUI Keybinds
if CQUI_hotkeyMode == CQUI_HOTKEYMODE_ENHANCED then
if (uiKey == Keys.W) then
m_isUPpressed = false;
keyPanChanged = true;
end
if (uiKey == Keys.D) then
m_isRIGHTpressed = false;
keyPanChanged = true;
end
if (uiKey == Keys.S) then
m_isDOWNpressed = false;
keyPanChanged = true;
end
if (uiKey == Keys.A) then
m_isLEFTpressed = false;
keyPanChanged = true;
end
if (uiKey == Keys.E) then
if (CQUI_isAltDown == true) then
-- Behave as if just "E" was pressed, send the unit exploring
-- Calling this using UnitOperationTypes doesn't work as Automate_Explore hash does not appear among the GameInfo.OperationTypes
UnitManager.RequestOperation(UI.GetHeadSelectedUnit(), GameInfo.UnitOperations["UNITOPERATION_AUTOMATE_EXPLORE"].Hash);
cquiHandledKey = true;
elseif (CQUI_cityview) then
LuaEvents.CQUI_GoNextCity();
cquiHandledKey = true;
else
UI.SelectNextReadyUnit();
cquiHandledKey = true;
end
end
if (uiKey == Keys.Q) then
if (CQUI_isAltDown == true and unitType == "UNIT_BUILDER" ) then
-- Do nothing, this case is handled later on in this function
elseif (CQUI_cityview) then
LuaEvents.CQUI_GoPrevCity();
cquiHandledKey = true;
else
UI.SelectPrevReadyUnit();
cquiHandledKey = true;
end
end
-- TODO: Not a huge fan of the Shift key being used to do things when the Shift key should just be a modifier.
-- Taking it out for now and will address with Issue #40
-- if (uiKey == Keys.VK_SHIFT and ContextPtr:LookUpControl("/InGame/TechTree"):IsHidden() and ContextPtr:LookUpControl("/InGame/CivicsTree"):IsHidden()) then
-- cquiHandledKey = true;
-- if (CQUI_cityview) then
-- UI.SetInterfaceMode(InterfaceModeTypes.SELECTION);
-- UI.SelectNextReadyUnit();
-- else
-- LuaEvents.CQUI_GoNextCity();
-- end
-- end
if (keyPanChanged == true) then
-- Base game file uses m_edgePanX and m_edgePanY... but I do not see evidence where these are assigned to, except for the initial 0.
ProcessPan(0, 0);
cquiHandledKey = true;
end
else -- CQUI_hotkeyMode == CQUI_HOTKEYMODE_CLASSIC (Classic binds that overlap with enhanced binds)
if (uiKey == Keys.Q) then
if (unitType == "UNIT_BUILDER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_QUARRY"].Hash);
cquiHandledKey = true;
end
end
-- TODO: AIR_ATTACK requires a separate set of parameters be passed to it, pointing at the object to attack
-- Similar to how the CQUI_BuildImprovement generates an object based on where the Builder/Engineer unit happens to be.
-- Logged on GitHub as Issue #40
-- if (uiKey == Keys.S) then
-- if (formationClass == "FORMATION_CLASS_AIR") then
-- UnitManager.RequestCommand(UI.GetHeadSelectedUnit(), UnitOperationTypes.AIR_ATTACK);
-- cquiHandledKey = true;
-- end
-- end
end -- Classic binds that overlap with enhanced binds
-- Focus Capital hotkey
if (uiKey == Keys.VK_HOME) then
UI.SelectCity(Players[Game.GetLocalPlayer()]:GetCities():GetCapitalCity());
cquiHandledKey = true;
end
if (uiKey == Keys.VK_BACK) then
if (unitType ~= nil) then
UnitManager.RequestCommand(UI.GetHeadSelectedUnit(), UnitCommandTypes.CANCEL);
cquiHandledKey = true;
end
end
if (uiKey == Keys.C and CQUI_isAltDown == true) then
if (unitType == "UNIT_BUILDER") or (unitType == "UNIT_MILITARY_ENGINEER") then
UnitManager.RequestOperation(UI.GetHeadSelectedUnit(), UnitOperationTypes.HARVEST_RESOURCE);
UnitManager.RequestOperation(UI.GetHeadSelectedUnit(), UnitOperationTypes.REMOVE_FEATURE);
cquiHandledKey = true;
end
end
if (uiKey == Keys.F) then
if (unitType == "UNIT_BUILDER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_FISHING_BOATS"].Hash);
cquiHandledKey = true;
elseif (unitType == "UNIT_MILITARY_ENGINEER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_FORT"].Hash);
cquiHandledKey = true;
end
end
if (uiKey == Keys.H and unitType == "UNIT_BUILDER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_CAMP"].Hash);
cquiHandledKey = true;
end
if (uiKey == Keys.I and unitType == "UNIT_BUILDER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_FARM"].Hash);
cquiHandledKey = true;
end
if (uiKey == Keys.L and unitType == "UNIT_BUILDER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_LUMBER_MILL"].Hash);
cquiHandledKey = true;
end
if (uiKey == Keys.N) then
-- See TODO note Below
-- cquiHandledKey = true;
if (unitType == "UNIT_BUILDER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_MINE"].Hash);
cquiHandledKey = true;
else
-- TODO: WMD_STRIKE requires a separate set of parameters be passed to it, pointing at the object to attack
-- Similar to how the CQUI_BuildImprovement generates an object based on where the Builder/Engineer unit happens to be.
-- Logged on GitHub as Issue #40
-- UnitManager.RequestOperation(UI.GetHeadSelectedUnit(), UnitOperationTypes.WMD_STRIKE);
end
end
if (uiKey == Keys.O) then
if (unitType == "UNIT_BUILDER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_OIL_WELL"].Hash);
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_OFFSHORE_OIL_RIG"].Hash);
cquiHandledKey = true;
end
end
if (uiKey == Keys.P) then
if (CQUI_isShiftDown) then
PlaceMapPin();
cquiHandledKey = true;
else
if (unitType == "UNIT_BUILDER") then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_PASTURE"].Hash);
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_PLANTATION"].Hash);
cquiHandledKey = true;
end
end
end
if (uiKey == Keys.Q) then
if (CQUI_isAltDown == true and unitType == "UNIT_BUILDER" ) then
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.Improvements["IMPROVEMENT_QUARRY"].Hash);
cquiHandledKey = true;
end
end
if (uiKey == Keys.R) then
if (unitType == "UNIT_MILITARY_ENGINEER") then
-- Build Road/Rail is a UnitOperation
CQUI_BuildImprovement(UI.GetHeadSelectedUnit(), GameInfo.UnitOperations["UNITOPERATION_BUILD_ROUTE"].Hash);
cquiHandledKey = true;
-- TODO: Rebase requires a separate set of parameters be passed to it, pointing at the location to move to
-- Similar to how the CQUI_BuildImprovement generates an object based on where the Builder/Engineer unit happens to be.
-- Logged on GitHub as Issue #40
-- elseif (formationClass == "FORMATION_CLASS_AIR") then
-- UnitManager.RequestOperation(UI.GetHeadSelectedUnit(), UnitOperationTypes.REBASE);
-- cquiHandledKey = true;
end
end
-- TODO: AIR_ATTACK requires a separate set of parameters be passed to it, pointing at the object to attack
-- Similar to how the CQUI_BuildImprovement generates an object based on where the Builder/Engineer unit happens to be.
-- Logged on GitHub as Issue #40
-- if (uiKey == Keys.S and CQUI_isAltDown == true) then
-- if (formationClass == "FORMATION_CLASS_AIR") then
-- UnitManager.RequestCommand(UI.GetHeadSelectedUnit(), UnitOperationTypes.AIR_ATTACK);
-- cquiHandledKey = true;
-- end
-- end
if uiKey == Keys.VK_SHIFT then
-- We need to let the base function also handle the Shift Up action
CQUI_isShiftDown = false;
end
if uiKey == Keys.VK_ALT then
-- We need to let the base function also handle the Alt Up action
CQUI_isAltDown = false;
end
if (cquiHandledKey == false) then
print_debug("** CQUI DefaultKeyUpHandler did not handle key: "..tostring(uiKey));
cquiHandledKey = BASE_CQUI_DefaultKeyUpHandler(uiKey);
end
return cquiHandledKey;
end
-- ===========================================================================
function ClearAllCachedInputState()
print_debug("** Function Entry: ClearAllCachedInputState (CQUI Hook)");
BASE_CQUI_ClearAllCachedInputState();
CQUI_isShiftDown = false;
CQUI_isAltDown = false;
end
-- ===========================================================================
-- CQUI Base Replacement Functions
-- These functions do not call the function of the same name found in base WorldInput.lua
-- ===========================================================================
function RealizeMovementPath(showQueuedPath:boolean, unitID:number)
print_debug("** Function Entry: RealizeMovementPath (CQUI Hook) -- showQueuedPath: "..tostring(showQueuedPath).." unitID"..tostring(unitID));
-- Largely the same as the base RealizeMovementPath, save for the additional unitID parameter
-- The unitID allows CQUI to show the movement path when a unit is hovered over (base game returns because no unit is actually selected)
if not UI.IsMovementPathOn() or UI.IsGameCoreBusy() then
return;
end
-- CQUI (Azurency) : Check if in CITY_MANAGEMENT or STRIKE modes
CQUI_im = UI.GetInterfaceMode();
if (CQUI_im == InterfaceModeTypes.CITY_MANAGEMENT or CQUI_im == InterfaceModeTypes.CITY_RANGE_ATTACK or CQUI_im == InterfaceModeTypes.DISTRICT_RANGE_ATTACK) then
return;
end
-- Bail if no selected unit
-- CQUI: If unitID is not null (as happens when hovering option is enabled), then that will be used instead
local kUnit :table = nil;
if unitID then
kUnit = Players[Game.GetLocalPlayer()]:GetUnits():FindID(unitID);
else
kUnit = UI.GetHeadSelectedUnit();
end
if kUnit == nil then
UILens.SetActive("Default");
m_cachedPathUnit = nil;
m_cachedPathPlotId = -1;
return;
end
-- Bail if unit is not a type that allows movement.
if GameInfo.Units[kUnit:GetUnitType()].IgnoreMoves then
return;
end
-- Bail if end plot is not determined.
local endPlotId :number = UI.GetCursorPlotID();
-- Use the queued destination to show the queued path
if (showQueuedPath) then
local queuedEndPlotId:number = UnitManager.GetQueuedDestination( kUnit );
if queuedEndPlotId then
endPlotId = queuedEndPlotId;
elseif unitID then -- AZURENCY : bail if the unit have no endplot and we wanted to draw its path
return;
end
end
-- Ensure this is a proper plot ID
if (not Map.IsPlot(endPlotId)) then
return;
end
-- Only update if a new unit or new plot from the previous update.
if m_cachedPathUnit ~= kUnit or m_cachedPathPlotId ~= endPlotId then
UILens.ClearLayerHexes( g_MovementPath );
UILens.ClearLayerHexes( g_Numbers );
UILens.ClearLayerHexes( g_AttackRange );
if m_cachedPathPlotId ~= -1 then
UILens.UnFocusHex( g_AttackRange, m_cachedPathPlotId );
end
m_cachedPathUnit = kUnit;
m_cachedPathPlotId = endPlotId;
-- Obtain ordered list of plots.
local variations : table = {}; -- 2 to 3 values
local eLocalPlayer : number = Game.GetLocalPlayer();
--check for unit position swap first
local startPlotId :number = Map.GetPlot(kUnit:GetX(),kUnit:GetY()):GetIndex();
if startPlotId ~= endPlotId then
local pathPlots :table = {};
local plot :table = Map.GetPlotByIndex(endPlotId);
local tParameters :table = {};
tParameters[UnitOperationTypes.PARAM_X] = plot:GetX();
tParameters[UnitOperationTypes.PARAM_Y] = plot:GetY();
if ( UnitManager.CanStartOperation( kUnit, UnitOperationTypes.SWAP_UNITS, nil, tParameters) ) then
lensNameBase = "MovementGood";
if not UILens.IsLensActive(lensNameBase) then
UILens.SetActive(lensNameBase);
end
table.insert(pathPlots, startPlotId);
table.insert(pathPlots, endPlotId);
table.insert(variations, {lensNameBase.."_Destination",startPlotId} );
table.insert(variations, {lensNameBase.."_Counter", startPlotId} ); -- show counter pip
UI.AddNumberToPath( 1, startPlotId);
table.insert(variations, {lensNameBase.."_Destination",endPlotId} );
table.insert(variations, {lensNameBase.."_Counter", endPlotId} ); -- show counter pip
UI.AddNumberToPath( 1, endPlotId);
UILens.SetLayerHexesPath(g_MovementPath, eLocalPlayer, pathPlots, variations);
return;
end
end
local pathInfo : table = UnitManager.GetMoveToPathEx( kUnit, endPlotId );
if table.count(pathInfo.plots) > 1 then
-- Start and end art "variations" when drawing path
local startHexId:number = kUnit:GetPlotId();
local endHexId :number = pathInfo.plots[table.count(pathInfo.plots)];
-- Don't show the implicit arrow if the unit has no remaining moves
-- NOTE: UnitManager.CanStartOperation and kUnit:GetAttacksRemaining both indicate a ranged
-- unit with 0 remaining moves can still attack, so we check using kUnit:GetMovesRemaining
if kUnit:GetMovesRemaining() > 0 then
-- Check if our desired "movement" is actually a ranged attack. Early out if so.
local isImplicitRangedAttack :boolean = false;
local pResults = UnitManager.GetOperationTargets(kUnit, UnitOperationTypes.RANGE_ATTACK );
local pAllPlots = pResults[UnitOperationResults.PLOTS];
if pAllPlots ~= nil then
for i, modifier in ipairs( pResults[UnitOperationResults.MODIFIERS] ) do
if modifier == UnitOperationResults.MODIFIER_IS_TARGET then
if pAllPlots[i] == endPlotId then
isImplicitRangedAttack = true;
break;
end
end
end
end
if isImplicitRangedAttack then
-- Unit can apparently perform a ranged attack on that hex. Show the arrow!
local kVariations:table = {};
local kEmpty:table = {};
table.insert(kVariations, {"EmptyVariant", startHexId, endHexId} );
UILens.SetLayerHexesArea(g_AttackRange, eLocalPlayer, kEmpty, kVariations);
-- Focus must be called AFTER the attack range variants are set.
UILens.FocusHex( g_AttackRange, endHexId );
return; -- We're done here. Do not show a movement path.
end
end
-- Any plots of path in Fog Of War or midfog?
local isPathInFog:boolean = false;
local pPlayerVis :table = PlayersVisibility[eLocalPlayer];
if pPlayerVis ~= nil then
for _,plotIds in pairs(pathInfo.plots) do
isPathInFog = not pPlayerVis:IsVisible(plotIds);
if isPathInFog then
break;
end
end
end
-- If any plots are in Fog Of War (FOW) then switch to the FOW movement lens.
local lensNameBase :string = "MovementGood";
local movePostfix :string = "";
local isPathHaveRestriction,restrictedPlotId = IsPlotPathRestrictedForUnit( pathInfo.plots, pathInfo.turns, kUnit );
if showQueuedPath then
lensNameBase = "MovementQueue";
elseif isPathHaveRestriction then
lensNameBase = "MovementBad";
m_isPlotFlaggedRestricted = true;
if restrictedPlotId ~= nil and restrictedPlotId ~= -1 then
table.insert(variations, {"MovementBad_Destination", restrictedPlotId} );
end
elseif isPathInFog then
lensNameBase = "MovementFOW";
movePostfix = "_FOW";
end
-- Turn on lens.
if not UILens.IsLensActive(lensNameBase) then
UILens.SetActive(lensNameBase);
end
-- is there an enemy unit at the end?
local bIsEnemyAtEnd:boolean = false;
local endPlot :table = Map.GetPlotByIndex(endPlotId);
if ( endPlot ~= nil ) then
local unitList = Units.GetUnitsInPlotLayerID( endPlot:GetX(), endPlot:GetY(), MapLayers.ANY );
for i, pUnit in ipairs(unitList) do
if ( eLocalPlayer ~= pUnit:GetOwner() and pPlayerVis ~= nil and pPlayerVis:IsVisible(endPlot:GetX(), endPlot:GetY()) and pPlayerVis:IsUnitVisible(pUnit) ) then
bIsEnemyAtEnd = true;
end
end
end
-- Hide the destination indicator only if the attack is guaranteed this turn.
-- Regular movements and attacks planned for later turns still get the indicator.
if not showQueuedPath then
table.insert(variations, {lensNameBase.."_Origin",startHexId} );
end
local nTurnCount :number = pathInfo.turns[table.count( pathInfo.turns )];
if not bIsEnemyAtEnd or nTurnCount > 1 then
table.insert(variations, {lensNameBase.."_Destination",endHexId} );
end
-- Since pathInfo.turns are matched against plots, this should be the same # as above.
if table.count(pathInfo.turns) > 1 then
-- Track any "holes" in the path.
local pathHole:table = {};
for i=1,table.count(pathInfo.plots),1 do
pathHole[i] = true;
end
local lastTurn:number = 1;
for i,value in pairs(pathInfo.turns) do
-- If a new turn entry exists, or it's the very last entry of the path... show turn INFO.
if value > lastTurn then
if i > 1 then
table.insert(variations, {lensNameBase.."_Counter", pathInfo.plots[i-1]} ); -- show counter pip
UI.AddNumberToPath( lastTurn, pathInfo.plots[i-1] );
pathHole[i-1]=false;
end
lastTurn = value;
end
if i == table.count(pathInfo.turns) and i > 1 then
table.insert(variations, {lensNameBase.."_Counter", pathInfo.plots[i]} ); -- show counter pip
UI.AddNumberToPath( lastTurn, pathInfo.plots[i] );
if lastTurn == 2 then
if m_previousTurnsCount == 1 then
UI.PlaySound("UI_Multi_Turn_Movement_Alert");
end
end
m_previousTurnsCount = lastTurn;
pathHole[i]=false;
end
end
-- Any obstacles? (e.g., rivers)
if not showQueuedPath then
local plotIndex:number = 1;
for i,value in pairs(pathInfo.obstacles) do
while( pathInfo.plots[plotIndex] ~= value ) do plotIndex = plotIndex + 1; end -- Get ID to use for river's next plot
table.insert(variations, {lensNameBase.."_Minus", value, pathInfo.plots[plotIndex+1]} );
end
end
-- Any variations not filled in earlier (holes), are filled in with Pips
for i,isHole in pairs(pathHole) do
if isHole then
table.insert(variations, {lensNameBase.."_Pip", pathInfo.plots[i]} ); -- non-counter pip
end
end
end
else
-- No path; is it a bad path or is the player have the cursor on the same hex as the unit?
local startPlotId :number = Map.GetPlot(kUnit:GetX(),kUnit:GetY()):GetIndex();
if startPlotId ~= endPlotId then
if not UILens.IsLensActive("MovementBad") then
UILens.SetActive("MovementBad");
lensNameBase = "MovementBad";
end
table.insert(pathInfo.plots, endPlotId);
table.insert(variations, {"MovementBad_Destination", endPlotId} );
else
table.insert(pathInfo.plots, endPlotId);
table.insert(variations, {"MovementGood_Destination", endPlotId} );
end
end
-- Handle mountain tunnels
-- TODO consider adding variations for entering/exiting portals
local pPathSegment = { };
for i,plot in pairs(pathInfo.plots) do
-- Prepend an exit portal if one exists
local pExit = pathInfo.exitPortals[i];
if (pExit and pExit >= 0) then
table.insert(pPathSegment, pExit);
end
-- Add the next plot to the segment
table.insert(pPathSegment, plot);
-- Append an entrance portal if one exists
local pEntrance = pathInfo.entrancePortals[i];
if (pEntrance and pEntrance >= 0) then
table.insert(pPathSegment, pEntrance);
-- Submit the segment so far and start a new segment
UILens.SetLayerHexesPath(g_MovementPath, eLocalPlayer, pPathSegment, { });
pPathSegment = { };
end
end
-- Submit the final segment
UILens.SetLayerHexesPath(g_MovementPath, eLocalPlayer, pPathSegment, variations);
end
end
-- ===========================================================================
function ClearMovementPath()
print_debug("** Function Entry: ClearMovementPath (CQUI Hook)");
-- Replace base function because of the if statement around the UILens.ClearLayerHexes
UILens.ClearLayerHexes( g_MovementPath );
UILens.ClearLayerHexes( g_Numbers );
-- CQUI : As we show path on over
if (UI.GetInterfaceMode() ~= InterfaceModeTypes.CITY_RANGE_ATTACK and UI.GetInterfaceMode() ~= InterfaceModeTypes.DISTRICT_RANGE_ATTACK) then
UILens.ClearLayerHexes( g_AttackRange );
end
m_cachedPathUnit = nil;
m_cachedPathPlotId = -1;
end
-- ===========================================================================
function OnInterfaceModeEnter_CityManagement( eNewMode:number )
print_debug("** Function Entry: OnInterfaceModeEnter_CityManagement (CQUI Hook)");
UIManager:SetUICursor(CursorTypes.RANGE_ATTACK);
-- AZURENCY : fix the Appeal lens not being applied in city view
-- UILens.SetActive("CityManagement");
end
-- ===========================================================================
function OnMouseBuildingPlacementCancel( pInputStruct:table )
print_debug("** Function Entry: OnMouseBuildingPlacementCancel (CQUI Hook)");
if IsCancelAllowed() then
LuaEvents.CQUI_CityviewEnable();
-- CQUI: Do not call ExitPlacementMode here
-- ExitPlacementMode( true );
end
end
-- ===========================================================================
function OnMouseDistrictPlacementCancel( pInputStruct:table )
print_debug("** Function Entry: OnMouseDistrictPlacementCancel (CQUI Hook)");
if IsCancelAllowed() then
LuaEvents.StoreHash(0);
LuaEvents.CQUI_CityviewEnable();
-- CQUI: Do not call ExitPlacementMode here
-- ExitPlacementMode( true );
end
end
-- ===========================================================================
function OnCycleUnitSelectionRequest()
print_debug("** Function Entry: OnCycleUnitSelectionRequest (CQUI Hook)");
if (UI.GetInterfaceMode() ~= InterfaceModeTypes.CINEMATIC or m_isMouseButtonRDown) then
-- AZURENCY : OnCycleUnitSelectionRequest is called by UI.SetCycleAdvanceTimer()
-- in SelectedUnit.lua causing a conflict with the auto-cyling of unit
-- (not the same given by UI.SelectNextReadyUnit() and player:GetUnits():GetFirstReadyUnit())
local pPlayer :table = Players[Game.GetLocalPlayer()];
if pPlayer ~= nil then
if pPlayer:IsTurnActive() then
local unit:table = pPlayer:GetUnits():GetFirstReadyUnit();
-- AZURENCY : we also check if there is not already a unit selected,
-- bacause UI.SetCycleAdvanceTimer() is always called after deselecting a unit
if unit ~= nil and not UI.GetHeadSelectedUnit() then
UI.DeselectAllUnits();
UI.DeselectAllCities();
UI.SelectUnit(unit);
UI.LookAtPlot(unit:GetX(), unit:GetY());
end
end
end
end
end
-- ===========================================================================
-- CQUI: Unique Functions
-- These functions are unique to CQUI, do not exist in the Base WorldInput.lua
-- ===========================================================================
-- ===========================================================================
function CQUI_BuildImprovement (unit, improvementHash: number)
print_debug("** Function Entry: CQUI_BuildImprovement (CQUI Hook)");
if unit == nil then return end
local tParameters = {};
tParameters[UnitOperationTypes.PARAM_X] = unit:GetX();
tParameters[UnitOperationTypes.PARAM_Y] = unit:GetY();
tParameters[UnitOperationTypes.PARAM_IMPROVEMENT_TYPE] = improvementHash;
UnitManager.RequestOperation( unit, UnitOperationTypes.BUILD_IMPROVEMENT, tParameters );
end
-- ===========================================================================
-- CQUI: Initialize Function
-- ===========================================================================
-- ===========================================================================
function Initialize()
print_debug("** Function Entry: Initialize (CQUI Hook)");
-- CQUI Events from end of Initialize
LuaEvents.CQUI_WorldInput_CityviewEnable.Add( function() CQUI_cityview = true; end );
LuaEvents.CQUI_WorldInput_CityviewDisable.Add( function() CQUI_cityview = false; end );
LuaEvents.CQUI_showUnitPath.Add(RealizeMovementPath);
LuaEvents.CQUI_clearUnitPath.Add(ClearMovementPath);
end
Initialize();
|
local plpath = require 'pl.path'
local srcdir = "../gen_src/"
local incdir = "../gen_inc/"
if ( not plpath.isdir(srcdir) ) then plpath.mkdir(srcdir) end
if ( not plpath.isdir(incdir) ) then plpath.mkdir(incdir) end
local gen_code = require("Q/UTILS/lua/gen_code")
local q_qtypes = nil; local bqtypes = nil
if ( arg[1] ) then
a_qtypes = { arg[1] }
else
a_qtypes = { 'I1', 'I2', 'I4', 'I8','F4', 'F8' }
end
if ( arg[2] ) then
b_qtypes = { arg[2] }
else
b_qtypes = { 'I1', 'I2', 'I4', 'I8','F4', 'F8' }
end
-- TODO local sort_order = { 'unsorted', 'asc' }
local sort_order = { 'asc', 'unsorted' }
local sp_fn = require 'ainb_specialize'
local num_produced = 0
for _, b_sort_order in ipairs(sort_order) do
local b_len = 1024
if ( b_sort_order == "unsorted" ) then b_len = 8 end
for _, atype in ipairs(a_qtypes) do
for _, btype in ipairs(b_qtypes) do
-- print(atype, btype, b_sort_order)
local status, subs = pcall(sp_fn, atype, btype,
b_len, b_sort_order)
if ( status ) then
gen_code.doth(subs, incdir)
gen_code.dotc(subs, srcdir)
-- print("Generated ", subs.fn)
num_produced = num_produced + 1
else
print(subs)
end
end
end
end
assert(num_produced > 0)
|
object_tangible_painting_painting_grievous_01 = object_tangible_painting_shared_painting_grievous_01:new {
}
ObjectTemplates:addTemplate(object_tangible_painting_painting_grievous_01, "object/tangible/painting/painting_grievous_01.iff")
|
-----------------------------------
-- Area: Metalworks
-- Door: _6ld (President's Office)
-- !pos 92 -19 0.1 237
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getCurrentMission(BASTOK) == tpz.mission.id.bastok.XARCABARD_LAND_OF_TRUTHS and player:hasKeyItem(tpz.ki.SHADOW_FRAGMENT)) then
player:startEvent(603);
else
player:startEvent(604);
end
return 1;
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 603) then
finishMissionTimeline(player,1,csid,option);
end
end; |
local mu = require('musicutil')
--
-- TamblaNoteGen
--
local TamblaNoteGen = sky.Device:extend()
function TamblaNoteGen:new(model, controller)
TamblaNoteGen.super.new(self)
self.model = model
self.controller = controller
self.default_duration = 0.8
self._scheduler = nil
self._notes = {}
self._next_notes = nil
self._last_index = {}
for i = 1, self.model.NUM_ROWS do
self._last_index[i] = 0
end
end
function TamblaNoteGen:device_inserted(chain)
self._scheduler = chain:scheduler(self)
self._scheduler:run(function(output)
while true do
clock.sleep(self.model.tick_period)
output(self.model:mk_tick())
end
end)
end
function TamblaNoteGen:device_removed(chain)
self._scheduler = nil
end
function TamblaNoteGen:process(event, output, state)
if self.model.is_tick(event) then
output(event) -- pass the tick along
local beat = event.beat
local chance_off = not self.controller.chance_mod
local chance_boost = self.model:chance_boost()
local velocity_scale = self.model:velocity_scale()
local velocity_on = self.controller.velocity_mod
local length_on = self.controller.length_mod
for i, r in ipairs(self.model:slot().rows) do
local idx = r:step_index(self.model:sync(i, beat))
if idx ~= self._last_index[i] then
-- we are at a new step
local step = r.steps[idx] -- which step within row
local note = self._notes[i] -- note which matches row based on order held
if note ~= nil then
local row_voice = self.model:voice(i)
if chance_off or (math.random() < (step.chance + chance_boost)) then
-- determine velocity
local velocity = 127
if velocity_on then
velocity = math.floor(note.vel * step.velocity)
end
velocity = math.floor(velocity * velocity_scale)
if velocity > 0 then
-- determine length
local duration = self.default_duration
if length_on then
duration = step.duration * r.res / 16 -- why?
end
local duration_sec = clock.get_beat_sec() * duration
-- print("duration:", duration)
-- print("duration sec:", duration_sec)
-- requires a make_note device to produce note off
local ev = sky.mk_note_on(note.note, velocity, note.ch, duration_sec)
ev.voice = row_voice
output(ev)
end
end
-- always output aux?
local cc = util.linlin(0, 1, 0, 127, step.aux)
local cc_ev = sky.mk_control_change(1, cc, note.ch)
cc_ev.voice = row_voice
output(cc_ev)
end
end
-- note that we've looked at this step
self._last_index[i] = idx
end
elseif sky.is_type(event, sky.HELD_EVENT) then
self._notes = event.notes
-- update note row sync offsets
local note_sync = self.controller.note_sync
for i, r in ipairs(self.model:slot().rows) do
local note = self._notes[i]
if note and note_sync then
self.model:set_sync(i, note.beat)
end
end
else
output(event)
end
end
--
-- Route
--
local Route = sky.Device:extend()
function Route:new(props)
Route.super.new(self, props)
self.property = props.key or 'route'
self._count = 0
for i, child in ipairs(props) do
self[i] = child
self._count = i
end
self:set_default(props.default or 1)
end
function Route:process(event, output, state)
local where = event[self.property]
if where == nil then
output(event)
return
end
if where == 0 then where = self.default end
local chain = self[where]
if chain ~= nil and not chain.bypass then
chain:process(event)
else
output(event)
end
end
function Route:set_default(which)
self.default = util.clamp(which, 1, self._count)
end
--
-- Random
--
local Random = sky.Device:extend()
function Random:new(props)
Random.super.new(self, props)
self._active = {}
self:set_scale(props.scale or 1)
self:set_choices(props.choices or 1)
self:set_chance(props.chance or 0.1)
self:set_sign(props.sign or 'add')
end
function Random:set_scale(scale)
self._array = util.clamp(scale, 1, 24)
end
function Random:set_choices(choice)
self._choices = util.clamp(choice, 1, 24)
end
function Random:set_chance(chance)
self._chance = util.clamp(chance, 0, 1)
end
function Random:set_sign(sign)
if sign == 'add' then self._sign = 'add'
elseif sign == 'sub' then self._sign = 'sub'
elseif sign == 'bi' then self._sign = 'bi'
end
end
function Random:process(event, output, state)
if not self.bypass and sky.is_type(event, sky.types.NOTE_ON) then
if math.random() < self._chance then
local id = event.correlation
local delta = math.floor(math.random() * self._choices * self._array)
if self._sign == 'sub' or (self._sign == 'bi' and math.random() < 0.5) then
delta = -delta
end
local shifted = util.clamp(event.note + delta, 0, 127)
self._active[id] = shifted
event.note = shifted
end
elseif sky.is_type(event, sky.types.NOTE_OFF) then
local id = event.correlation
local shifted = self._active[id]
if shifted then
self._active[id] = nil
event.note = shifted
end
end
output(event)
end
--
-- Scale
--
local Scale = sky.Device:extend()
function Scale:new(props)
Scale.super.new(self, props)
self:set_root(props.root or 0, true)
self:set_scale(props.scale or 'major', true)
self:set_octaves(props.octaves or 10, true)
self:build()
self._active = {}
end
function Scale:set_root(note, quiet)
self._root = note
if not quiet then self:build() end
end
function Scale:set_scale(name, quiet)
self._name = name
if not quiet then self:build() end
end
function Scale:set_octaves(octaves, quiet)
self._octaves = octaves
if not quiet then self:build() end
end
function Scale:build()
self._array = mu.generate_scale(self._root, self._name, self._octaves)
end
-- FIXME: it might be worth exploring using a dense scale array to avoid the
-- need to do the type of searching which `snap_note_to_array` does thus
-- lowering the code of process
function Scale:process(event, output, state)
if not self.bypass and sky.is_type(event, sky.types.NOTE_ON) then
local id = event.correlation
local corrected = mu.snap_note_to_array(event.note, self._array)
self._active[id] = corrected
event.note = corrected
elseif sky.is_type(event, sky.types.NOTE_OFF) then
local id = event.correlation
local corrected = self._active[id]
if corrected then
self._active[id] = nil
event.note = corrected
end
end
output(event)
end
--
-- module
--
return {
TamblaNoteGen = TamblaNoteGen,
Route = Route,
Random = Random,
Scale = Scale,
}
|
-- example HTTP POST script which demonstrates setting the
-- HTTP method, body, and adding a header
wrk.method = "POST"
wrk.body = "{ products { name } categories { name }}"
wrk.headers["Content-Type"] = "application/graphql"
|
local M = {}
local function _adjust(line, start_col, end_col)
local end_line = line:sub(start_col, end_col)
local pattern = ("\\v\\k*%%%sc\\zs."):format(end_col)
local last_char = vim.fn.matchstr(line, pattern)
if last_char == "" then
return end_line .. "\n"
end
local str = end_line:gsub(".$", last_char)
return str
end
function M.get_text(bufnr, start_row, start_col, end_row, end_col)
local lines = vim.api.nvim_buf_get_lines(bufnr, start_row, end_row + 1, false)
local count = #lines
if count == 0 then
return ""
end
if count == 1 then
return _adjust(lines[count], start_col, end_col)
end
lines[1] = lines[1]:sub(start_col)
lines[count] = _adjust(lines[count], 1, end_col)
return table.concat(lines, "\n")
end
return M
|
function printf(...)
print(string.format(...))
end
local function touhous()
local reimu = Person:new():name('Reimu'):lastname('Hakurei'):age(19)
local sanae = Person:new():name('Sanae'):lastname('Kochiya'):age(17)
print(reimu:greet())
print(sanae:greet())
print(reimu:meet(sanae))
print(sanae:meet(reimu))
print(sanae:meet(sanae))
print(reimu:meet(reimu))
end
local function files()
local file = File:open('pangrams.txt')
local contents = {}
print('contents:')
while true do
local line = file:readline()
if not line then break end
table.insert(contents,line)
end
print(#contents)
file:close()
end
local function filechars()
local file = File:open('pangrams.txt')
local chars = {}
while true do
local char = file:read()
if char < 0 then break end
table.insert(chars,string.format('%02X',char))
end
print('local chars = {'..table.concat(chars,',')..'}')
end
local function filetouhous()
local file = File:open('touhous.txt')
local touhous = {}
for i=1,3 do
local th = Person:new()
:name(file:readline())
:lastname(file:readline())
:age(file:readline())
print(th:greet())
th.file = file
table.insert(touhous,th)
end
file:close()
for i=1,#touhous do
for j=1,#touhous do
print(touhous[i]:meet(touhous[j]))
end
end
end
return filetouhous |
local torch = { }
function torch:new()
local o = {
iob = ex_iob:new(),
torch = ex_torch:new(),
animation = ex_animation:new(32.0, 32.0, 2),
position = ex_position:new(),
next_position = ex_next_position:new(),
sprite = ex_sprite:new("./assets/textures/torch.png", true),
}
setmetatable(o, self);
return o;
end
return torch |
tpz = tpz or {}
tpz.magic = tpz.magic or {}
------------------------------------
-- Spell flag bits
------------------------------------
tpz.magic.spellFlag =
{
NONE = 0x00,
HIT_ALL = 0x01, -- Hit all targets in range regardless of party
WIPE_SHADOWS = 0x02, -- Wipe shadows even if single target and miss/resist (example: "Maiden's Virelai")
IGNORE_SHADOWS = 0x04 -- Ignore shadows and hit player anyways (example: Mobs "Death" spell)
}
------------------------------------
-- Spell AOE IDs
------------------------------------
tpz.magic.aoe =
{
NONE = 0,
RADIAL = 1,
CONAL = 2,
RADIAL_MANI = 3, -- AOE when under SCH stratagem Manifestation
RADIAL_ACCE = 4, -- AOE when under SCH stratagem Accession
PIANISSIMO = 5, -- Single target when under BRD JA Pianissimo
DIFFUSION = 6, -- AOE when under Diffusion
}
------------------------------------
-- Spell Groups
------------------------------------
tpz.magic.spellGroup =
{
NONE = 0,
SONG = 1,
BLACK = 2,
BLUE = 3,
NINJUTSU = 4,
SUMMONING = 5,
WHITE = 6,
}
------------------------------------
-- Elements
------------------------------------
tpz.magic.element =
{
NONE = 0,
FIRE = 1,
EARTH = 2,
WATER = 3,
WIND = 4,
ICE = 5,
LIGHTNING = 6,
THUNDER = 6,
LIGHT = 7,
DARK = 8,
}
tpz.magic.ele = tpz.magic.element
------------------------------------
-- Spell Families
------------------------------------
tpz.magic.spellFamily =
{
NONE = 0,
CURE = 1,
CURAGA = 2,
RAISE = 3,
NA = 4,
HOLY = 5,
DIA = 6,
BANISH = 7,
DIAGA = 8,
BANISHGA = 9,
PROTECT = 10,
SHELL = 11,
SLOW = 12,
HASTE = 13,
PARALYZE = 14,
ELE_BAR = 15,
ELE_BAR_RA = 16,
STATUS_BAR = 17,
STATUS_BAR_RA = 18,
RECALL = 19,
CURA = 20,
ENFIRE = 21,
ENBLIZZARD = 22,
ENAERO = 23,
ENSTONE = 24,
ENTHUNDER = 25,
ENWATER = 26,
PHALANX = 27,
REGEN = 28,
REFRESH = 29,
SANDSTORM = 30,
RAINSTORM = 31,
WINDSTORM = 32,
FIRESTORM = 33,
HAILSTORM = 34,
THUNDERSTORM = 35,
VOIDSTORM = 36,
AURORASTORM = 37,
TELEPORT = 38,
PROTECTRA = 39,
SHELLRA = 40,
RERAISE = 41,
FIRE = 42,
BLIZZARD = 43,
AERO = 44,
STONE = 45,
THUNDER = 46,
WATER = 47,
FIRAGA = 48,
BLIZZAGA = 49,
AEROGA = 50,
STONEGA = 51,
THUNDAGA = 52,
WATERGA = 53,
FLARE = 54,
FREEZE = 55,
TORNADO = 56,
QUAKE = 57,
BURST = 58,
FLOOD = 59,
GRAVITY = 60,
METEOR = 61,
POISON = 62,
POISONGA = 63,
BIO = 64,
ELE_DOT = 65,
ABSORB = 66,
DRAIN = 67,
ASPIR = 68,
SPIKES = 69,
STATUS = 70,
SLEEP = 71,
BLIND = 72,
WARP = 73,
TRACTOR = 74,
SLEEPGA = 75,
GEOHELIX = 76,
HYDROHELIX = 77,
ANEMOHELIX = 78,
PYROHELIX = 79,
CRYOHELIX = 80,
IONOHELIX = 81,
NOCTOHELIX = 82,
LUMINOHELIX = 83,
ADDLE = 84,
SPIRIT = 85,
AVATAR = 86,
ANIMUS = 87,
ENLIGHT = 88,
ENDARK = 89,
KATON = 90,
HYOTON = 91,
HUTON = 92,
DOTON = 93,
RAITON = 94,
SUITON = 95,
UTSUSEMI = 96,
JUBAKU = 97,
HOJO = 98,
KURAYAMI = 99,
DOKUMORI = 100,
TONKO = 101,
STATUS_GA = 102,
FOE_REQUIEM = 103,
HORDE_LULLABY = 104,
ARMYS_PAEON = 105,
MAGES_BALLAD = 106,
KNIGHTS_MINNE = 107,
VALOR_MINUET = 108,
MADRIGAL = 109,
PRELUDE = 110,
MAMBO = 111,
OPERETTA = 112,
MARCH = 113,
ELEGY = 114,
STR_ETUDE = 115,
DEX_ETUDE = 116,
VIT_ETUDE = 117,
AGI_ETUDE = 118,
INT_ETUDE = 119,
MND_ETUDE = 120,
CHR_ETUDE = 121,
FIRE_CAROL = 122,
ICE_CAROL = 123,
WIND_CAROL = 124,
EARTH_CAROL = 125,
LIGHTNING_CAROL = 126,
WATER_CAROL = 127,
LIGHT_CAROL = 128,
DARK_CAROL = 129,
FIRE_THRENODY = 130,
ICE_THRENODY = 131,
WIND_THRENODY = 132,
EARTH_THRENODY = 133,
LIGHTNING_THRENODY = 134,
WATER_THRENODY = 135,
LIGHT_THRENODY = 136,
DARK_THRENODY = 137,
FOE_LULLABY = 138,
MAZURKA = 139,
BOOST = 140,
GAIN = 141,
TEMPER = 142,
JA = 143,
INDI_BUFF = 144,
INDI_DEBUFF = 145,
GEO_BUFF = 146,
GEO_DEBUFF = 147,
FIRA = 148,
LIZZARA = 149,
AERORA = 150,
STONERA = 151,
THUNDARA = 152,
WATERA = 153,
DISTRACT = 154,
FRAZZLE = 155,
FLURRY = 156,
}
------------------------------------
-- Spell IDs
------------------------------------
tpz.magic.spell =
{
CURE = 1,
CURE_II = 2,
CURE_III = 3,
CURE_IV = 4,
CURE_V = 5,
CURE_VI = 6,
CURAGA = 7,
CURAGA_II = 8,
CURAGA_III = 9,
CURAGA_IV = 10,
CURAGA_V = 11,
RAISE = 12,
RAISE_II = 13,
POISONA = 14,
PARALYNA = 15,
BLINDNA = 16,
SILENA = 17,
STONA = 18,
VIRUNA = 19,
CURSNA = 20,
HOLY = 21,
HOLY_II = 22,
DIA = 23,
DIA_II = 24,
DIA_III = 25,
DIA_IV = 26,
DIA_V = 27,
BANISH = 28,
BANISH_II = 29,
BANISH_III = 30,
BANISH_IV = 31,
BANISH_V = 32,
DIAGA = 33,
DIAGA_II = 34,
DIAGA_III = 35,
DIAGA_IV = 36,
DIAGA_V = 37,
BANISHGA = 38,
BANISHGA_II = 39,
BANISHGA_III = 40,
BANISHGA_IV = 41,
BANISHGA_V = 42,
PROTECT = 43,
PROTECT_II = 44,
PROTECT_III = 45,
PROTECT_IV = 46,
PROTECT_V = 47,
SHELL = 48,
SHELL_II = 49,
SHELL_III = 50,
SHELL_IV = 51,
SHELL_V = 52,
BLINK = 53,
STONESKIN = 54,
AQUAVEIL = 55,
SLOW = 56,
HASTE = 57,
PARALYZE = 58,
SILENCE = 59,
BARFIRE = 60,
BARBLIZZARD = 61,
BARAERO = 62,
BARSTONE = 63,
BARTHUNDER = 64,
BARWATER = 65,
BARFIRA = 66,
BARBLIZZARA = 67,
BARAERA = 68,
BARSTONRA = 69,
BARTHUNDRA = 70,
BARWATERA = 71,
BARSLEEP = 72,
BARPOISON = 73,
BARPARALYZE = 74,
BARBLIND = 75,
BARSILENCE = 76,
BARPETRIFY = 77,
BARVIRUS = 78,
SLOW_II = 79,
PARALYZE_II = 80,
RECALL_JUGNER = 81,
RECALL_PASHH = 82,
RECALL_MERIPH = 83,
BARAMNESIA = 84,
BARAMNESRA = 85,
BARSLEEPRA = 86,
BARPOISONRA = 87,
BARPARALYZRA = 88,
BARBLINDRA = 89,
BARSILENCERA = 90,
BARPETRA = 91,
BARVIRA = 92,
CURA = 93,
SACRIFICE = 94,
ESUNA = 95,
AUSPICE = 96,
REPRISAL = 97,
REPOSE = 98,
SANDSTORM = 99,
ENFIRE = 100,
ENBLIZZARD = 101,
ENAERO = 102,
ENSTONE = 103,
ENTHUNDER = 104,
ENWATER = 105,
PHALANX = 106,
PHALANX_II = 107,
REGEN = 108,
REFRESH = 109,
REGEN_II = 110,
REGEN_III = 111,
FLASH = 112,
RAINSTORM = 113,
WINDSTORM = 114,
FIRESTORM = 115,
HAILSTORM = 116,
THUNDERSTORM = 117,
VOIDSTORM = 118,
AURORASTORM = 119,
TELEPORT_YHOAT = 120,
TELEPORT_ALTEP = 121,
TELEPORT_HOLLA = 122,
TELEPORT_DEM = 123,
TELEPORT_MEA = 124,
PROTECTRA = 125,
PROTECTRA_II = 126,
PROTECTRA_III = 127,
PROTECTRA_IV = 128,
PROTECTRA_V = 129,
SHELLRA = 130,
SHELLRA_II = 131,
SHELLRA_III = 132,
SHELLRA_IV = 133,
SHELLRA_V = 134,
RERAISE = 135,
INVISIBLE = 136,
SNEAK = 137,
DEODORIZE = 138,
TELEPORT_VAHZL = 139,
RAISE_III = 140,
RERAISE_II = 141,
RERAISE_III = 142,
ERASE = 143,
FIRE = 144,
FIRE_II = 145,
FIRE_III = 146,
FIRE_IV = 147,
FIRE_V = 148,
BLIZZARD = 149,
BLIZZARD_II = 150,
BLIZZARD_III = 151,
BLIZZARD_IV = 152,
BLIZZARD_V = 153,
AERO = 154,
AERO_II = 155,
AERO_III = 156,
AERO_IV = 157,
AERO_V = 158,
STONE = 159,
STONE_II = 160,
STONE_III = 161,
STONE_IV = 162,
STONE_V = 163,
THUNDER = 164,
THUNDER_II = 165,
THUNDER_III = 166,
THUNDER_IV = 167,
THUNDER_V = 168,
WATER = 169,
WATER_II = 170,
WATER_III = 171,
WATER_IV = 172,
WATER_V = 173,
FIRAGA = 174,
FIRAGA_II = 175,
FIRAGA_III = 176,
FIRAGA_IV = 177,
FIRAGA_V = 178,
BLIZZAGA = 179,
BLIZZAGA_II = 180,
BLIZZAGA_III = 181,
BLIZZAGA_IV = 182,
BLIZZAGA_V = 183,
AEROGA = 184,
AEROGA_II = 185,
AEROGA_III = 186,
AEROGA_IV = 187,
AEROGA_V = 188,
STONEGA = 189,
STONEGA_II = 190,
STONEGA_III = 191,
STONEGA_IV = 192,
STONEGA_V = 193,
THUNDAGA = 194,
THUNDAGA_II = 195,
THUNDAGA_III = 196,
THUNDAGA_IV = 197,
THUNDAGA_V = 198,
WATERGA = 199,
WATERGA_II = 200,
WATERGA_III = 201,
WATERGA_IV = 202,
WATERGA_V = 203,
FLARE = 204,
FLARE_II = 205,
FREEZE = 206,
FREEZE_II = 207,
TORNADO = 208,
TORNADO_II = 209,
QUAKE = 210,
QUAKE_II = 211,
BURST = 212,
BURST_II = 213,
FLOOD = 214,
FLOOD_II = 215,
GRAVITY = 216,
GRAVITY_II = 217,
METEOR = 218,
COMET = 219,
POISON = 220,
POISON_II = 221,
POISON_III = 222,
POISON_IV = 223,
POISON_V = 224,
POISONGA = 225,
POISONGA_II = 226,
POISONGA_III = 227,
POISONGA_IV = 228,
POISONGA_V = 229,
BIO = 230,
BIO_II = 231,
BIO_III = 232,
BIO_IV = 233,
BIO_V = 234,
BURN = 235,
FROST = 236,
CHOKE = 237,
RASP = 238,
SHOCK = 239,
DROWN = 240,
RETRACE = 241,
ABSORB_ACC = 242,
ABSORB_ATTRI = 243,
METEOR_II = 244,
DRAIN = 245,
DRAIN_II = 246,
ASPIR = 247,
ASPIR_II = 248,
BLAZE_SPIKES = 249,
ICE_SPIKES = 250,
SHOCK_SPIKES = 251,
STUN = 252,
SLEEP = 253,
BLIND = 254,
BREAK = 255,
VIRUS = 256,
CURSE = 257,
BIND = 258,
SLEEP_II = 259,
DISPEL = 260,
WARP = 261,
WARP_II = 262,
ESCAPE = 263,
TRACTOR = 264,
TRACTOR_II = 265,
ABSORB_STR = 266,
ABSORB_DEX = 267,
ABSORB_VIT = 268,
ABSORB_AGI = 269,
ABSORB_INT = 270,
ABSORB_MND = 271,
ABSORB_CHR = 272,
SLEEPGA = 273,
SLEEPGA_II = 274,
ABSORB_TP = 275,
BLIND_II = 276,
DREAD_SPIKES = 277,
GEOHELIX = 278,
HYDROHELIX = 279,
ANEMOHELIX = 280,
PYROHELIX = 281,
CRYOHELIX = 282,
IONOHELIX = 283,
NOCTOHELIX = 284,
LUMINOHELIX = 285,
ADDLE = 286,
KLIMAFORM = 287,
FIRE_SPIRIT = 288,
ICE_SPIRIT = 289,
AIR_SPIRIT = 290,
EARTH_SPIRIT = 291,
THUNDER_SPIRIT = 292,
WATER_SPIRIT = 293,
LIGHT_SPIRIT = 294,
DARK_SPIRIT = 295,
CARBUNCLE = 296,
FENRIR = 297,
IFRIT = 298,
TITAN = 299,
LEVIATHAN = 300,
GARUDA = 301,
SHIVA = 302,
RAMUH = 303,
DIABOLOS = 304,
ODIN = 305,
ALEXANDER = 306,
CAIT_SITH = 307,
ANIMUS_AUGEO = 308,
ANIMUS_MINUO = 309,
ENLIGHT = 310,
ENDARK = 311,
ENFIRE_II = 312,
ENBLIZZARD_II = 313,
ENAERO_II = 314,
ENSTONE_II = 315,
ENTHUNDER_II = 316,
ENWATER_II = 317,
MONOMI_ICHI = 318,
AISHA_ICHI = 319,
KATON_ICHI = 320,
KATON_NI = 321,
KATON_SAN = 322,
HYOTON_ICHI = 323,
HYOTON_NI = 324,
HYOTON_SAN = 325,
HUTON_ICHI = 326,
HUTON_NI = 327,
HUTON_SAN = 328,
DOTON_ICHI = 329,
DOTON_NI = 330,
DOTON_SAN = 331,
RAITON_ICHI = 332,
RAITON_NI = 333,
RAITON_SAN = 334,
SUITON_ICHI = 335,
SUITON_NI = 336,
SUITON_SAN = 337,
UTSUSEMI_ICHI = 338,
UTSUSEMI_NI = 339,
UTSUSEMI_SAN = 340,
JUBAKU_ICHI = 341,
JUBAKU_NI = 342,
JUBAKU_SAN = 343,
HOJO_ICHI = 344,
HOJO_NI = 345,
HOJO_SAN = 346,
KURAYAMI_ICHI = 347,
KURAYAMI_NI = 348,
KURAYAMI_SAN = 349,
DOKUMORI_ICHI = 350,
DOKUMORI_NI = 351,
DOKUMORI_SAN = 352,
TONKO_ICHI = 353,
TONKO_NI = 354,
SIREN = 355,
PARALYGA = 356,
SLOWGA = 357,
HASTEGA = 358,
SILENCEGA = 359,
DISPELGA = 360,
BLINDGA = 361,
BINDGA = 362,
SLEEPGA = 363,
SLEEPGA_II = 364,
BREAKGA = 365,
GRAVIGA = 366,
DEATH = 367,
FOE_REQUIEM = 368,
FOE_REQUIEM_II = 369,
FOE_REQUIEM_III = 370,
FOE_REQUIEM_IV = 371,
FOE_REQUIEM_V = 372,
FOE_REQUIEM_VI = 373,
FOE_REQUIEM_VII = 374,
FOE_REQUIEM_VIII = 375,
HORDE_LULLABY = 376,
HORDE_LULLABY_II = 377,
ARMYS_PAEON = 378,
ARMYS_PAEON_II = 379,
ARMYS_PAEON_III = 380,
ARMYS_PAEON_IV = 381,
ARMYS_PAEON_V = 382,
ARMYS_PAEON_VI = 383,
ARMYS_PAEON_VII = 384,
ARMYS_PAEON_VIII = 385,
MAGES_BALLAD = 386,
MAGES_BALLAD_II = 387,
MAGES_BALLAD_III = 388,
KNIGHTS_MINNE = 389,
KNIGHTS_MINNE_II = 390,
KNIGHTS_MINNE_III = 391,
KNIGHTS_MINNE_IV = 392,
KNIGHTS_MINNE_V = 393,
VALOR_MINUET = 394,
VALOR_MINUET_II = 395,
VALOR_MINUET_III = 396,
VALOR_MINUET_IV = 397,
VALOR_MINUET_V = 398,
SWORD_MADRIGAL = 399,
BLADE_MADRIGAL = 400,
HUNTERS_PRELUDE = 401,
ARCHERS_PRELUDE = 402,
SHEEPFOE_MAMBO = 403,
DRAGONFOE_MAMBO = 404,
FOWL_AUBADE = 405,
HERB_PASTORAL = 406,
CHOCOBO_HUM = 407,
SHINING_FANTASIA = 408,
SCOPS_OPERETTA = 409,
PUPPETS_OPERETTA = 410,
JESTERS_OPERETTA = 411,
GOLD_CAPRICCIO = 412,
DEVOTEE_SERENADE = 413,
WARDING_ROUND = 414,
GOBLIN_GAVOTTE = 415,
CACTUAR_FUGUE = 416,
HONOR_MARCH = 417,
PROTECTED_ARIA = 418,
ADVANCING_MARCH = 419,
VICTORY_MARCH = 420,
BATTLEFIELD_ELEGY = 421,
CARNAGE_ELEGY = 422,
MASSACRE_ELEGY = 423,
SINEWY_ETUDE = 424,
DEXTROUS_ETUDE = 425,
VIVACIOUS_ETUDE = 426,
QUICK_ETUDE = 427,
LEARNED_ETUDE = 428,
SPIRITED_ETUDE = 429,
ENCHANTING_ETUDE = 430,
HERCULEAN_ETUDE = 431,
UNCANNY_ETUDE = 432,
VITAL_ETUDE = 433,
SWIFT_ETUDE = 434,
SAGE_ETUDE = 435,
LOGICAL_ETUDE = 436,
BEWITCHING_ETUDE = 437,
FIRE_CAROL = 438,
ICE_CAROL = 439,
WIND_CAROL = 440,
EARTH_CAROL = 441,
LIGHTNING_CAROL = 442,
WATER_CAROL = 443,
LIGHT_CAROL = 444,
DARK_CAROL = 445,
FIRE_CAROL_II = 446,
ICE_CAROL_II = 447,
WIND_CAROL_II = 448,
EARTH_CAROL_II = 449,
LIGHTNING_CAROL_II = 450,
WATER_CAROL_II = 451,
LIGHT_CAROL_II = 452,
DARK_CAROL_II = 453,
FIRE_THRENODY = 454,
ICE_THRENODY = 455,
WIND_THRENODY = 456,
EARTH_THRENODY = 457,
LIGHTNING_THRENODY = 458,
WATER_THRENODY = 459,
LIGHT_THRENODY = 460,
DARK_THRENODY = 461,
MAGIC_FINALE = 462,
FOE_LULLABY = 463,
GODDESSS_HYMNUS = 464,
CHOCOBO_MAZURKA = 465,
MAIDENS_VIRELAI = 466,
RAPTOR_MAZURKA = 467,
FOE_SIRVENTE = 468,
ADVENTURERS_DIRGE = 469,
SENTINELS_SCHERZO = 470,
FOE_LULLABY_II = 471,
PINING_NOCTURNE = 472,
REFRESH_II = 473,
CURA_II = 474,
CURA_III = 475,
CRUSADE = 476,
REGEN_IV = 477,
EMBRAVA = 478,
BOOST_STR = 479,
BOOST_DEX = 480,
BOOST_VIT = 481,
BOOST_AGI = 482,
BOOST_INT = 483,
BOOST_MND = 484,
BOOST_CHR = 485,
GAIN_STR = 486,
GAIN_DEX = 487,
GAIN_VIT = 488,
GAIN_AGI = 489,
GAIN_INT = 490,
GAIN_MND = 491,
GAIN_CHR = 492,
TEMPER = 493,
ARISE = 494,
ADLOQUIUM = 495,
FIRAJA = 496,
BLIZZAJA = 497,
AEROJA = 498,
STONEJA = 499,
THUNDAJA = 500,
WATERJA = 501,
KAUSTRA = 502,
IMPACT = 503,
REGEN_V = 504,
GEKKA_ICHI = 505,
YAIN_ICHI = 506,
MYOSHU_ICHI = 507,
YURIN_ICHI = 508,
KAKKA_ICHI = 509,
MIGAWARI_ICHI = 510,
HASTE_II = 511,
VENOM_SHELL = 513,
MAELSTROM = 515,
METALLIC_BODY = 517,
SCREWDRIVER = 519,
MP_DRAINKISS = 521,
DEATH_RAY = 522,
SANDSPIN = 524,
SMITE_OF_RAGE = 527,
BLUDGEON = 529,
REFUELING = 530,
ICE_BREAK = 531,
BLITZSTRAHL = 532,
SELF_DESTRUCT = 533,
MYSTERIOUS_LIGHT = 534,
COLD_WAVE = 535,
POISON_BREATH = 536,
STINKING_GAS = 537,
MEMENTO_MORI = 538,
TERROR_TOUCH = 539,
SPINAL_CLEAVE = 540,
BLOOD_SABER = 541,
DIGEST = 542,
MANDIBULAR_BITE = 543,
CURSED_SPHERE = 544,
SICKLE_SLASH = 545,
COCOON = 547,
FILAMENTED_HOLD = 548,
POLLEN = 549,
POWER_ATTACK = 551,
DEATH_SCISSORS = 554,
MAGNETITE_CLOUD = 555,
EYES_ON_ME = 557,
FRENETIC_RIP = 560,
FRIGHTFUL_ROAR = 561,
HECATOMB_WAVE = 563,
BODY_SLAM = 564,
RADIANT_BREATH = 565,
HELLDIVE = 567,
JET_STREAM = 569,
BLOOD_DRAIN = 570,
SOUND_BLAST = 572,
FEATHER_TICKLE = 573,
FEATHER_BARRIER = 574,
JETTATURA = 575,
YAWN = 576,
FOOT_KICK = 577,
WILD_CARROT = 578,
VORACIOUS_TRUNK = 579,
HEALING_BREEZE = 581,
CHAOTIC_EYE = 582,
SHEEP_SONG = 584,
RAM_CHARGE = 585,
CLAW_CYCLONE = 587,
LOWING = 588,
DIMENSIONAL_DEATH = 589,
HEAT_BREATH = 591,
BLANK_GAZE = 592,
MAGIC_FRUIT = 593,
UPPERCUT = 594,
THOUSAND_NEEDLES = 595,
PINECONE_BOMB = 596,
SPROUT_SMACK = 597,
SOPORIFIC = 598,
QUEASYSHROOM = 599,
WILD_OATS = 603,
BAD_BREATH = 604,
GEIST_WALL = 605,
AWFUL_EYE = 606,
FROST_BREATH = 608,
INFRASONICS = 610,
DISSEVERMENT = 611,
ACTINIC_BURST = 612,
REACTOR_COOL = 613,
SALINE_COAT = 614,
PLASMA_CHARGE = 615,
TEMPORAL_SHIFT = 616,
VERTICAL_CLEAVE = 617,
BLASTBOMB = 618,
BATTLE_DANCE = 620,
SANDSPRAY = 621,
GRAND_SLAM = 622,
HEAD_BUTT = 623,
BOMB_TOSS = 626,
FRYPAN = 628,
FLYING_HIP_PRESS = 629,
HYDRO_SHOT = 631,
DIAMONDHIDE = 632,
ENERVATION = 633,
LIGHT_OF_PENANCE = 634,
WARM_UP = 636,
FIRESPIT = 637,
FEATHER_STORM = 638,
TAIL_SLAP = 640,
HYSTERIC_BARRAGE = 641,
AMPLIFICATION = 642,
CANNONBALL = 643,
MIND_BLAST = 644,
EXUVIATION = 645,
MAGIC_HAMMER = 646,
ZEPHYR_MANTLE = 647,
REGURGITATION = 648,
SEEDSPRAY = 650,
CORROSIVE_OOZE = 651,
SPIRAL_SPIN = 652,
ASURAN_CLAWS = 653,
SUB_ZERO_SMASH = 654,
TRIUMPHANT_ROAR = 655,
ACRID_STREAM = 656,
BLAZING_BOUND = 657,
PLENILUNE_EMBRACE = 658,
DEMORALIZING_ROAR = 659,
CIMICINE_DISCHARGE = 660,
ANIMATING_WAIL = 661,
BATTERY_CHARGE = 662,
LEAFSTORM = 663,
REGENERATION = 664,
FINAL_STING = 665,
GOBLIN_RUSH = 666,
VANITY_DIVE = 667,
MAGIC_BARRIER = 668,
WHIRL_OF_RAGE = 669,
BENTHIC_TYPHOON = 670,
AURORAL_DRAPE = 671,
OSMOSIS = 672,
QUADRATIC_CONTINUUM = 673,
FANTOD = 674,
THERMAL_PULSE = 675,
EMPTY_THRASH = 677,
DREAM_FLOWER = 678,
OCCULTATION = 679,
CHARGED_WHISKER = 680,
WINDS_OF_PROMYVION = 681,
DELTA_THRUST = 682,
EVRYONES_GRUDGE = 683,
REAVING_WIND = 684,
BARRIER_TUSK = 685,
MORTAL_RAY = 686,
WATER_BOMB = 687,
HEAVY_STRIKE = 688,
DARK_ORB = 689,
WHITE_WIND = 690,
SUDDEN_LUNGE = 692,
QUADRASTRIKE = 693,
VAPOR_SPRAY = 694,
THUNDER_BREATH = 695,
ORCISH_COUNTERSTANCE = 696,
AMORPHIC_SPIKES = 697,
WIND_BREATH = 698,
BARBED_CRESCENT = 699,
NATURES_MEDITATION = 700,
TEMPESTUOUS_UPHEAVAL = 701,
RENDING_DELUGE = 702,
EMBALMING_EARTH = 703,
PARALYZING_TRIAD = 704,
FOUL_WATERS = 705,
GLUTINOUS_DART = 706,
RETINAL_GLARE = 707,
SUBDUCTION = 708,
THRASHING_ASSAULT = 709,
ERRATIC_FLUTTER = 710,
RESTORAL = 711,
RAIL_CANNON = 712,
DIFFUSION_RAY = 713,
SINKER_DRILL = 714,
MOLTING_PLUMAGE = 715,
NECTAROUS_DELUGE = 716,
SWEEPING_GOUGE = 717,
ATRAMENTOUS_LIBATIONS = 718,
SEARING_TEMPEST = 719,
SPECTRAL_FLOE = 720,
ANVIL_LIGHTNING = 721,
ENTOMB = 722,
SAURIAN_SLIDE = 723,
PALLING_SALVO = 724,
BLINDING_FULGOR = 725,
SCOURING_SPATE = 726,
SILENT_STORM = 727,
TENEBRAL_CRUSH = 728,
THUNDERBOLT = 736,
HARDEN_SHELL = 737,
ABSOLUTE_TERROR = 738,
GATES_OF_HADES = 739,
TOURBILLION = 740,
PYRIC_BULWARK = 741,
BILGESTORM = 742,
BLOODRAKE = 743,
DRONING_WHIRLWIND = 744,
CARCHARIAN_VERVE = 745,
BLISTERING_ROAR = 746,
UPROOT = 747,
CRASHING_THUNDER = 748,
POLAR_ROAR = 749,
MIGHTY_GUARD = 750,
CRUEL_JOKE = 751,
CESSPOOL = 752,
TEARING_GUST = 753,
INDI_REGEN = 768,
INDI_POISON = 769,
INDI_REFRESH = 770,
INDI_HASTE = 771,
INDI_STR = 772,
INDI_DEX = 773,
INDI_VIT = 774,
INDI_AGI = 775,
INDI_INT = 776,
INDI_MND = 777,
INDI_CHR = 778,
INDI_FURY = 779,
INDI_BARRIER = 780,
INDI_ACUMEN = 781,
INDI_FEND = 782,
INDI_PRECISION = 783,
INDI_VOIDANCE = 784,
INDI_FOCUS = 785,
INDI_ATTUNEMENT = 786,
INDI_WILT = 787,
INDI_FRAILTY = 788,
INDI_FADE = 789,
INDI_MALAISE = 790,
INDI_SLIP = 791,
INDI_TORPOR = 792,
INDI_VEX = 793,
INDI_LANGUOR = 794,
INDI_SLOW = 795,
INDI_PARALYSIS = 796,
INDI_GRAVITY = 797,
GEO_REGEN = 798,
GEO_POISON = 799,
GEO_REFRESH = 800,
GEO_HASTE = 801,
GEO_STR = 802,
GEO_DEX = 803,
GEO_VIT = 804,
GEO_AGI = 805,
GEO_INT = 806,
GEO_MND = 807,
GEO_CHR = 808,
GEO_FURY = 809,
GEO_BARRIER = 810,
GEO_ACUMEN = 811,
GEO_FEND = 812,
GEO_PRECISION = 813,
GEO_VOIDANCE = 814,
GEO_FOCUS = 815,
GEO_ATTUNEMENT = 816,
GEO_WILT = 817,
GEO_FRAILTY = 818,
GEO_FADE = 819,
GEO_MALAISE = 820,
GEO_SLIP = 821,
GEO_TORPOR = 822,
GEO_VEX = 823,
GEO_LANGUOR = 824,
GEO_SLOW = 825,
GEO_PARALYSIS = 826,
GEO_GRAVITY = 827,
FIRA = 828,
FIRA_II = 829,
BLIZZARA = 830,
BLIZZARA_II = 831,
AERA = 832,
AERA_II = 833,
STONERA = 834,
STONERA_II = 835,
THUNDARA = 836,
THUNDARA_II = 837,
WATERA = 838,
WATERA_II = 839,
FOIL = 840,
DISTRACT = 841,
DISTRACT_II = 842,
FRAZZLE = 843,
FRAZZLE_II = 844,
FLURRY = 845,
FLURRY_II = 846,
ATOMOS = 847,
RERAISE_IV = 848,
FIRE_VI = 849,
BLIZZARD_VI = 850,
AERO_VI = 851,
STONE_VI = 852,
THUNDER_VI = 853,
WATER_VI = 854,
ENLIGHT_II = 855,
ENDARK_II = 856,
SANDSTORM_II = 857,
RAINSTORM_II = 858,
WINDSTORM_II = 859,
FIRESTORM_II = 860,
HAILSTORM_II = 861,
THUNDERSTORM_II = 862,
VOIDSTORM_II = 863,
AURORASTORM_II = 864,
FIRA_III = 865,
BLIZZARA_III = 866,
AERA_III = 867,
STONERA_III = 868,
THUNDARA_III = 869,
WATERA_III = 870,
FIRE_THRENODY_II = 871,
ICE_THRENODY_II = 872,
WIND_THRENODY_II = 873,
EARTH_THRENODY_II = 874,
LIGHTNING_THRENODY_II = 875,
WATER_THRENODY_II = 876,
LIGHT_THRENODY_II = 877,
DARK_THRENODY_II = 878,
INUNDATION = 879,
DRAIN_III = 880,
ASPIR_III = 881,
DISTRACT_III = 882,
FRAZZLE_III = 883,
ADDLE_II = 884,
GEOHELIX_II = 885,
HYDROHELIX_II = 886,
ANEMOHELIX_II = 887,
PYROHELIX_II = 888,
CRYOHELIX_II = 889,
IONOHELIX_II = 890,
NOCTOHELIX_II = 891,
LUMINOHELIX_II = 892,
FULL_CURE = 893,
REFRESH_III = 894,
TEMPER_II = 895,
SHANTOTTO = 896,
NAJI = 897,
KUPIPI = 898,
EXCENMILLE = 899,
AYAME = 900,
NANAA_MIHGO = 901,
CURILLA = 902,
VOLKER = 903,
AJIDO_MARUJIDO = 904,
TRION = 905,
ZEID = 906,
LION = 907,
TENZEN = 908,
MIHLI_ALIAPOH = 909,
VALAINERAL = 910,
JOACHIM = 911,
NAJA_SALAHEEM = 912,
PRISHE = 913,
ULMIA = 914,
SHIKAREE_Z = 915,
CHERUKIKI = 916,
IRON_EATER = 917,
GESSHO = 918,
GADALAR = 919,
RAINEMARD = 920,
INGRID = 921,
LEHKO_HABHOKA = 922,
NASHMEIRA = 923,
ZAZARG = 924,
OVJANG = 925,
MNEJING = 926,
SAKURA = 927,
LUZAF = 928,
NAJELITH = 929,
ALDO = 930,
MOOGLE = 931,
FABLINIX = 932,
MAAT = 933,
DOMINA_SHANTOTTO = 934,
STAR_SIBYL = 935,
KARAHA_BARUHA = 936,
CID = 937,
GILGAMESH = 938,
AREUHAT = 939,
SEMIH_LAFIHNA = 940,
ELIVIRA = 941,
NOILLURIE = 942,
LHU_MHAKARACCA = 943,
FERREOUS_COFFIN = 944,
LILISETTE = 945,
MUMOR = 946,
UKA_TOTLIHN = 947,
KLARA = 948,
ROMAA_MIHGO = 949,
KUYIN_HATHDENNA = 950,
RAHAL = 951,
KORU_MORU = 952,
PIEUJE_UC = 953,
INVINCIBLE_SHIELD_UC = 954,
APURURU_UC = 955,
JAKOH_UC = 956,
FLAVIRIA_UC = 957,
BABBAN = 958,
ABENZIO = 959,
RUGHADJEEN = 960,
KUKKI_CHEBUKKI = 961,
MARGRET = 962,
CHACHAROON = 963,
LHE_LHANGAVO = 964,
ARCIELA = 965,
MAYAKOV = 966,
QULTADA = 967,
ADELHEID = 968,
AMCHUCHU = 969,
BRYGID = 970,
MILDAURION = 971,
HALVER = 972,
RONGELOUTS = 973,
LEONOYNE = 974,
MAXIMILIAN = 975,
KAYEEL_PAYEEL = 976,
ROBEL_AKBEL = 977,
KUPOFRIED = 978,
SELHTEUS = 979,
YORAN_ORAN_UC = 980,
SYLVIE_UC = 981,
ABQUHBAH = 982,
BALAMOR = 983,
AUGUST = 984,
ROSULATIA = 985,
TEODOR = 986,
ULLEGORE = 987,
MAKKI_CHEBUKKI = 988,
KING_OF_HEARTS = 989,
MORIMAR = 990,
DARRCUILN = 991,
AAHM = 992,
AAEV = 993,
AAMR = 994,
AATT = 995,
AAGK = 996,
IROHA = 997,
YGNAS = 998,
MONBERAUX = 999,
EXCENMILLE_S = 1004,
AYAME_UC = 1005,
MAAT_UC = 1006,
ALDO_UC = 1007,
NAJA_UC = 1008,
LION_II = 1009,
ZEID_II = 1010,
PRISHE_II = 1011,
NASHMEIRA_II = 1012,
LILISETTE_II = 1013,
TENZEN_II = 1014,
MUMOR_II = 1015,
INGRID_II = 1016,
ARCIELA_II = 1017,
IROHA_II = 1018,
SHANTOTTO_II = 1019,
}
|
return {'ubacher','ubachs','ubags','ubaghs','ubach'} |
--[[
--=====================================================================================================--
Script Name: Server Name Changer (UTILITY), for SAPP (PC & CE)
Description: This script will periodically change the name of the server.
Copyright (c) 2021, Jericho Crosby <[email protected]>
* Notice: You can use this document subject to the following conditions:
https://github.com/Chalwk77/HALO-SCRIPT-PROJECTS/blob/master/LICENSE
--=====================================================================================================--
]]--
api_version = "1.12.0.0"
-- config starts --
-- The script will pick a new server name every 15 seconds:
local interval = 1000 * 15 -- in milliseconds (1000*1 = 1 second)
local server_names = {
"My Cool Server",
"A server!",
" ", -- blank
"Ya mom!",
"CoronaVirus", -- repeat the structure to add more entries.
}
-- config ends --
local network_struct
function OnScriptLoad()
network_struct = read_dword(sig_scan("F3ABA1????????BA????????C740??????????E8????????668B0D") + 3)
timer(interval, "ChangeServerName")
end
local index = 1
function ChangeServerName()
write_widestring(network_struct + 0x8, server_names[index], 0x42)
index = index + 1
if (index > #server_names) then
index = 1
end
return true
end
----------------------------------------------
-- Credits to Devieth for these two functions:
function write_widestring(address, str, len)
local Count = 0
for _ = 1, len do
write_byte(address + Count, 0)
Count = Count + 2
end
local count = 0
local length = string.len(str)
for i = 1, length do
write_byte(address + count, string.byte(string.sub(str, i, i)))
count = count + 2
end
end
function read_widestring(Address, Size)
local str = ""
for i = 0, Size - 1 do
if (read_byte(Address + i * 2) ~= 00) then
str = str .. string.char(read_byte(Address + i * 2))
end
end
if (str ~= "") then
return str
end
return nil
end |
local unpack = unpack
local shared, ngx_time = ngx.shared, ngx.time
local log, ERR = ngx.log, ngx.ERR
local lock = require "resty.lock"
local LOCK_OPTS = {
exptime = 0.05,
timeout = 0.04
}
local exports = {}
local STATE_NORMAL = 0
local STATE_FLOP = 1
local STATE_RECOVER = 2
exports.STATE_NORMAL = STATE_NORMAL
exports.STATE_FLOP = STATE_FLOP
exports.STATE_RECOVER = STATE_RECOVER
exports.new = function(shm_key, key, hit_intl, hit_thres, flop_intl, rc_thres, rc_thres_suc)
local dict = shared[shm_key]
if not dict then
log(ERR, "shm not found, key: ", shm_key)
return nil
end
return {
shm_key = shm_key,
dict = dict,
lock_key = "baffle:l:" .. key,
state_key = "baffle:s:" .. key,
tick_key = "baffle:t:" .. key,
hit_key = "baffle:h:" .. key,
hit_intl = hit_intl,
hit_thres = hit_thres,
flop_intl = flop_intl,
rc_rest_key = "baffle:rr:" .. key,
rc_hit_key = "baffle:rh:" .. key,
rc_suc_key = "baffle:rs:" .. key,
rc_thres = rc_thres,
rc_thres_suc = rc_thres_suc
}
end
local locked_method = function(self, method, args)
local lck = lock.new(nil, self.shm_key, LOCK_OPTS)
lock.lock(lck, self.lock_key)
local res = {method(self, args)}
lock.unlock(lck)
return unpack(res)
end
local check_in = function(self, _)
local now = ngx_time()
local dict = self.dict
local allowed = true
local state, state_new = dict:get(self.state_key), nil
if STATE_FLOP == state then
allowed = false
local tick = dict:get(self.tick_key)
if now >= tick then
allowed = true
if self.rc_thres then
state_new = STATE_RECOVER
dict:set(self.rc_rest_key, self.rc_thres)
dict:set(self.rc_hit_key, 0)
dict:set(self.rc_suc_key, 0)
else
state_new = STATE_NORMAL
end
dict:delete(self.tick_key)
end
elseif STATE_RECOVER == state then
local rc_rest = dict:get(self.rc_rest_key)
if rc_rest > 0 then
dict:incr(self.rc_rest_key, -1)
else
allowed = false
end
elseif not state then
state, state_new = STATE_NORMAL, STATE_NORMAL
end
if state_new then
dict:set(self.state_key, state_new)
end
return allowed, state_new or state, state
end
exports.check_in = function(self)
return locked_method(self, check_in, nil)
end
local check_out = function(self, args)
local now = ngx_time()
local suc, state_in = args[1], args[2]
local dict = self.dict
local state, state_new = dict:get(self.state_key), nil
if state_in ~= state then return state_in, state_in end
if STATE_NORMAL == state then
if not suc then
local hit
local ok = dict:add(self.hit_key, 1, self.hit_intl)
if ok then
hit = 1
else
hit = dict:incr(self.hit_key, 1)
end
if hit >= self.hit_thres then
state_new = STATE_FLOP
dict:set(self.tick_key, now + self.flop_intl)
dict:delete(self.hit_key)
end
end
elseif STATE_RECOVER == state then
local rc_hit = dict:incr(self.rc_hit_key, 1)
if suc then dict:incr(self.rc_suc_key, 1) end
if self.rc_thres == rc_hit then
local rc_suc = dict:get(self.rc_suc_key)
if (rc_suc or 0) >= self.rc_thres_suc then
state_new = STATE_NORMAL
else
state_new = STATE_FLOP
dict:set(self.tick_key, now + self.flop_intl)
end
end
end
if state_new then
dict:set(self.state_key, state_new)
end
return state_new or state, state
end
exports.check_out = function(self, suc, state)
return locked_method(self, check_out, {suc, state})
end
return exports
|
EnterInstance = function(instanceId)
DecorSetInt(PlayerPedId(), "currentInstance", instanceId)
DecorSetBool(PlayerPedId(), "inInstance", true)
NetworkSetVoiceChannel(instanceId + 1000)
NetworkSetTalkerProximity(0.0)
SpawnFurnishing(instanceId)
end
ExitInstance = function()
DecorSetInt(PlayerPedId(), "currentInstance", 0)
DecorSetBool(PlayerPedId(), "inInstance", false)
NetworkClearVoiceChannel()
NetworkSetTalkerProximity(2.5)
RemoveSpawnedProps()
end
Citizen.CreateThread(function()
Citizen.Wait(0)
while true do
local sleepThread = 100
local ped = PlayerPedId()
local pedCoords = GetEntityCoords(ped)
local currentInstance = DecorGetInt(ped, "currentInstance")
if currentInstance > 0 then
sleepThread = 5
for _, player in pairs(GetActivePlayers()) do
local playerPed = GetPlayerPed(player)
if playerPed ~= ped then
if DoesEntityExist(playerPed) then
if DecorGetInt(playerPed, "currentInstance") ~= currentInstance then
SetEntityCoords(playerPed)
SetEntityLocallyInvisible(playerPed)
SetEntityNoCollisionEntity(ped, playerPed, true)
end
end
end
end
end
Citizen.Wait(sleepThread)
end
end) |
ITEM.name = "Нож"
ITEM.desc = "Охотничий нож представляет собой прочное холодное оружие, предназначенное для охоты, рыбалки, походов и даже пикников. \n\nХАРАКТЕРИСТИКИ: \n-используется для: бой \n-используется для: открытие банок консервов \n-используется для: разделки туш мутантов"
ITEM.price = 1823
ITEM.class = "weapon_cop_knife"
ITEM.weaponCategory = "3"
ITEM.category = "Оружие"
ITEM.exRender = false
ITEM.weight = 0.28
ITEM.model = "models/wick/weapons/stalker/stcopwep/w_knife_stcop.mdl"
ITEM.width = 2
ITEM.height = 1
ITEM.iconCam = {
pos = Vector(-0.89999997615814, 200, 0),
ang = Angle(0, 270, 2.2929935455322),
fov = 3.6
} |
local UNICORN = KEYS[1]
local SUBSESSION = KEYS[2]
redis.call('del', 'sexp:' .. UNICORN)
redis.call('set', 'subs:' .. UNICORN, SUBSESSION)
redis.call('hdel', 'sess:' .. UNICORN, 'kill') |
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
ESX.RegisterUsableItem('bread', function(source)
local xPlayer = ESX.GetPlayerFromId(source)
xPlayer.removeInventoryItem('bread', 1)
TriggerClientEvent('esx_status:add', source, 'hunger', 200000)
TriggerClientEvent('esx_basicneeds:onEat', source)
TriggerClientEvent('esx:showNotification', source, _U('used_bread'))
end)
ESX.RegisterUsableItem('water', function(source)
local xPlayer = ESX.GetPlayerFromId(source)
xPlayer.removeInventoryItem('water', 1)
TriggerClientEvent('esx_status:add', source, 'thirst', 200000)
TriggerClientEvent('esx_basicneeds:onDrink', source)
TriggerClientEvent('esx:showNotification', source, _U('used_water'))
end)
|
require 'lib/util'
local DrawEngine = {}
DrawEngine.__index = DrawEngine
-- constructs the DrawEngine
function DrawEngine.new(game, initialMode)
local o = {}
setmetatable(o, DrawEngine)
o.game = game
o:selectDrawMode(initialMode)
return o
end
-- toggles between the draw modes
function DrawEngine:toggleDrawMode()
if self.draw == DrawEngine.drawPheromones then
self.draw = DrawEngine.drawAnts
else
self.draw = DrawEngine.drawPheromones
end
end
-- selects a draw mode
function DrawEngine:selectDrawMode(mode)
if mode == 'pheromones' then
self.draw = DrawEngine.drawPheromones
else
self.draw = DrawEngine.drawAnts
end
end
-- draws the ant view
function DrawEngine:drawAnts()
-- what we need from the game object
local board = self.game:getBoard()
local ants = self.game.ants
-- what we need from löve
local width = love.graphics.getWidth()
local height = love.graphics.getHeight()
-- our individual cell width and height
local cellWidth = width / board.width
local cellHeight = height / board.height
self:_drawBackground(width, height)
local helperBoard = {}
for a=1, #ants do
local position = ants[a]:getPosition()
self:_drawAnt((position.x-1)*cellWidth, (position.y-1)*cellHeight, cellWidth, cellHeight)
helperBoard[position.x .. '-' .. position.y] = true
end
for x=1,board.width do
for y=1,board.height do
local pheromones = board:getPheromones(x, y)
local _x = (x-1)*cellWidth
local _y = (y-1)*cellHeight
if pheromones ~= -1 and not (type(pheromones) == 'number' and helperBoard[x .. '-' .. y]) then
local color = {r=55, g=55, b=55}
if pheromones == 'start' then
color.g = 255
elseif pheromones == 'food' then
color.b = 255
end
self:_drawPheromones(_x, _y, cellWidth, cellHeight, color)
end
self:_printPheromoneLevel(_x, _y, pheromones)
end
end
end
-- draws the pheromone view
function DrawEngine:drawPheromones()
-- what we need from the game object
local board = self.game:getBoard()
-- what we need from löve
local width = love.graphics.getWidth()
local height = love.graphics.getHeight()
-- our individual cell width and height
local cellWidth = width / board.width
local cellHeight = height / board.height
self:_drawBackground(width, height)
for x=1,board.width do
for y=1,board.height do
local pheromones = board:getPheromones(x, y)
if pheromones ~= -1 then
local color = {r=55, g=55, b=55}
if pheromones == 'start' then
color.g = 255
elseif pheromones == 'food' then
color.b = 255
elseif pheromones > 0 then
color.r = math.clamp(pheromones + 55, 55, 255)
color.g = math.clamp(pheromones - 145, 55, 255)
color.b = math.clamp(pheromones - 345, 55, 255)
end
local _x = (x-1)*cellWidth
local _y = (y-1)*cellHeight
self:_drawPheromones(_x, _y, cellWidth, cellHeight, color)
self:_printPheromoneLevel(_x, _y, pheromones)
end
end
end
end
-- internal helper functions for drawing
function DrawEngine:_drawBackground(width, height)
love.graphics.setColor(0, 0, 0)
love.graphics.rectangle("fill", 0, 0, width, height)
end
function DrawEngine:_drawPheromones(x, y, width, height, color)
love.graphics.setColor(color.r, color.g, color.b)
love.graphics.rectangle("fill", x+1, y+1, width-2, height-2)
end
function DrawEngine:_printPheromoneLevel(x, y, pheromones)
love.graphics.setColor(0, 0, 0)
love.graphics.print(pheromones, x + 4, y + 4, 0, 2)
end
function DrawEngine:_drawAnt(x, y, width, height)
self:_drawPheromones(x, y, width, height, {r=255, g=55, b=55})
end
return DrawEngine |
require("ability.lua")
require("action.lua")
require("action_use.lua")
require("activity.lua")
require("adventurer.lua")
require("ai.lua")
require("autopick.lua")
require("blending.lua")
require("blending_recipe.lua")
require("buff.lua")
require("building.lua")
require("card_info.lua")
require("casino.lua")
require("chara.lua")
require("chara_making.lua")
require("chara_status.lua")
require("class.lua")
require("common.lua")
require("config.lua")
require("crafting.lua")
require("ctrl_inventory.lua")
require("damage.lua")
require("death.lua")
require("element.lua")
require("enchantment.lua")
require("event.lua")
require("fish.lua")
require("food.lua")
require("god.lua")
require("guild.lua")
require("item.lua")
require("item_material.lua")
require("keybindings.lua")
require("magic.lua")
require("main_menu.lua")
require("map.lua")
require("material.lua")
require("mef.lua")
require("meta.lua")
require("misc.lua")
require("mod.lua")
require("net.lua")
require("politics.lua")
require("quest.lua")
require("quest_journal.lua")
require("race.lua")
require("rank.lua")
require("scenario.lua")
require("skill.lua")
require("status_ailment.lua")
require("system.lua")
require("talk_npc.lua")
require("talk_unique.lua")
require("talk_visitor.lua")
require("tcg.lua")
require("trait.lua")
require("ui.lua")
require("win.lua")
require("wish.lua")
|
-- awesome_mode: api-level=4:screen=on
-----------------------------------------------------------
-- Includes {{{1
-- Standard awesome libraries
local awful = require("awful") -- Everything related to window management
-- Widget and layout library
local wibox = require("wibox") -- Awesome own generic widget framework
-- Theme handling library
local beautiful = require("beautiful") -- Awesome theme module
-- Default mod key
local modkey = "Mod4" -- Meta key
local M = {}
-----------------------------------------------------------
-- Volume control {{{1
local volumecfg = {
device = "default",
channel = "Speaker",
}
function M.get_widget()
local volumectrl = wibox.widget({
{
id = "watch_role",
awful.widget.watch(
"bash -c 'amixer -D "
.. volumecfg.device
.. " sget "
.. volumecfg.channel
.. " -M'",
5,
function(widget, stdout)
local volume = stdout:match("%[%d+%%%]")
volume = tonumber(volume:match("%d+"))
local status = stdout:match("%[o[n|ff]%]")
local icon = ""
if status:find("off") then
icon = "婢"
elseif volume >= 60 then
icon = "墳"
elseif volume >= 10 then
icon = "奔"
elseif volume < 10 then
icon = "奄"
else
icon = "ﱝ "
end
widget:set_markup_silently(
string.format(
"<span weight='bold' foreground='%s'>%s </span>%.f%%",
beautiful.nord15,
icon,
volume
)
)
end
),
buttons = {
awful.button({}, 1, function()
os.execute(
"amixer -D "
.. volumecfg.device
.. " sset "
.. volumecfg.channel
.. " toggle"
)
end),
awful.button({}, 3, function()
awful.spawn("pavucontrol")
end),
awful.button({}, 4, function()
os.execute(
"amixer -D "
.. volumecfg.device
.. " sset "
.. volumecfg.channel
.. " 5%+"
)
end),
awful.button({}, 5, function()
os.execute(
"amixer -D "
.. volumecfg.device
.. " sset "
.. volumecfg.channel
.. " 5%-"
)
end),
},
layout = wibox.layout.fixed.horizontal,
},
left = 3 * beautiful.useless_gap,
right = 6 * beautiful.useless_gap,
widget = wibox.container.margin,
})
return volumectrl
end
return M
-- }}}1
|
local local0 = 0
function OnIf_901900(arg0, arg1, arg2)
if arg2 == 0 then
CannonDammy901900_ActAfter_RealTime(arg0, arg1)
end
return
end
function CannonDammy901900Battle_Activate(arg0, arg1)
Common_Clear_Param({}, {}, {})
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetEventRequest(0)
local local3 = arg0:GetDistYSigned(TARGET_ENE_0)
if arg0:HasSpecialEffectId(TARGET_SELF, 5580) and local3 <= 3 then
if local3 <= -3 then
if 20 <= local0 then
arg1:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3002, TARGET_ENE_0, DIST_None)
elseif 15 <= local0 then
arg1:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3001, TARGET_ENE_0, DIST_None)
else
arg1:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3000, TARGET_ENE_0, DIST_None)
end
elseif 20 <= local0 then
arg1:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3005, TARGET_ENE_0, DIST_None)
elseif 15 <= local0 then
arg1:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3004, TARGET_ENE_0, DIST_None)
else
arg1:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3003, TARGET_ENE_0, DIST_None)
end
else
arg1:AddSubGoal(GOAL_COMMON_Wait, 0.1, TARGET_NONE, 0, 0, 0)
end
return
end
function CannonDammy901900_ActAfter_RealTime(arg0, arg1)
return
end
function CannonDammy901900_ActAfter_AdjustSpace(arg0, arg1, arg2)
arg1:AddSubGoal(GOAL_COMMON_If, 10, 0)
return
end
function CannonDammy901900Battle_Update(arg0, arg1)
return GOAL_RESULT_Continue
end
function CannonDammy901900Battle_Terminate(arg0, arg1)
return
end
function CannonDammy901900Battle_Interupt(arg0, arg1)
return false
end
return
|
--[[
print(10) -- no action(comment)
--]]
---[[
print(10) -- add single hyphen to the first line
--]]
|
slot0 = class("ShipProfilePaintingView")
slot0.Ctor = function (slot0, slot1, slot2, slot3)
pg.DelegateInfo.New(slot0)
slot0.prefab = slot1
slot0.painting = slot2
slot0.cg = slot0.painting:GetComponent("CanvasGroup")
slot0.bg = slot0.prefab:Find("bg")
slot0.bgBtn = slot0.bg:GetComponent("Button")
slot0.recorder = {}
slot0.hideObjList = {}
slot0.isPreview = false
slot0.zoomDelegate = GetOrAddComponent(slot0.bg, "MultiTouchZoom")
slot0.dragTrigger = GetOrAddComponent(slot0.bg, "EventTriggerListener")
slot0:SetHideObject()
slot0.isBanRotate = slot3
end
slot0.SetHideObject = function (slot0)
slot1 = slot0.prefab.childCount
slot2 = 0
while slot1 > slot2 do
if slot0.prefab:GetChild(slot2).gameObject.activeSelf and slot3 ~= slot0.painting and slot3 ~= slot0.bg then
slot0.hideObjList[#slot0.hideObjList + 1] = slot3
end
slot2 = slot2 + 1
end
end
slot0.setBGCallback = function (slot0, slot1)
slot0.bgCallback = slot1
end
slot0.Start = function (slot0)
slot0.cg.blocksRaycasts = false
slot0:EnableObjects(false)
slot0:RecodObjectInfo()
LeanTween.moveX(slot0.painting, 0, 0.3):setEase(LeanTweenType.easeInOutSine):setOnComplete(System.Action(function ()
slot0:TweenObjects()
end))
slot0.isPreview = true
end
slot0.EnableObjects = function (slot0, slot1)
_.each(slot0.hideObjList, function (slot0)
setActive(slot0, slot0)
end)
end
slot0.TweenObjects = function (slot0)
if not slot0.isBanRotate then
openPortrait(slot0.prefab)
end
slot1 = true
slot0.exitFlag = false
slot2, slot3 = nil
slot0.zoomDelegate:SetZoomTarget(slot0.painting)
slot0.zoomDelegate.enabled = true
slot0.dragTrigger.enabled = true
slot0.dragTrigger.AddPointDownFunc(slot4, function (slot0)
if Input.touchCount == 1 or Application.isEditor then
slot0.exitFlag = true
slot1 = true
elseif Input.touchCount >= 2 then
slot1 = false
slot0.exitFlag = false
end
end)
slot0.dragTrigger.AddPointUpFunc(slot4, function (slot0)
if Input.touchCount <= 2 then
slot0 = true
end
end)
slot0.dragTrigger.AddBeginDragFunc(slot4, function (slot0, slot1)
slot0.exitFlag = false
slot2 = slot1.position.x * slot0.recorder.widthRate - slot0.recorder.halfWidth - tf(slot0.painting).localPosition.x.position.y * slot0.recorder.heightRate - slot0.recorder.halfHeight - tf(slot0.painting).localPosition.y
end)
slot0.dragTrigger.AddDragFunc(slot4, function (slot0, slot1)
if slot0 then
tf(slot1.painting).localPosition = Vector3(slot1.position.x * slot1.recorder.widthRate - slot1.recorder.halfWidth - slot2 - 150, slot1.position.y * slot1.recorder.heightRate - slot1.recorder.halfHeight - slot3, -22)
end
end)
slot0.bgBtn.enabled = true
onButton(slot0, slot0.bg, function ()
if slot0.bgCallback then
if slot0.exitFlag then
slot0.bgCallback()
end
else
slot0:Finish()
end
end, SFX_CANCEL)
end
slot0.RecodObjectInfo = function (slot0)
slot0.recorder.srcPosX = slot0.painting.anchoredPosition.x
slot0.recorder.srcPosY = slot0.painting.anchoredPosition.y
slot0.recorder.srcWidth = slot0.painting.rect.width
slot0.recorder.srcHeight = slot0.painting.rect.height
slot0.recorder.widthRate = slot0.prefab.rect.width / UnityEngine.Screen.width
slot0.recorder.heightRate = slot0.prefab.rect.height / UnityEngine.Screen.height
slot0.recorder.halfWidth = slot0.recorder.srcWidth / 2
slot0.recorder.halfHeight = slot0.recorder.srcHeight / 2
end
slot0.Finish = function (slot0, slot1)
if not slot1 and not slot0.exitFlag then
return
end
slot0.dragTrigger.enabled = false
slot0.zoomDelegate.enabled = false
_.each(slot0.hideObjList, function (slot0)
setActive(slot0, true)
end)
if not slot0.isBanRotate then
closePortrait(slot0.prefab)
end
slot0.EnableObjects(slot0, true)
slot0.painting.localScale = Vector3(1, 1, 1)
setAnchoredPosition(slot0.painting, {
x = slot0.recorder.srcPosX,
y = slot0.recorder.srcPosY
})
slot0.bgBtn.enabled = false
slot0.cg.blocksRaycasts = true
slot0.isPreview = false
slot0.exitFlag = false
slot0.recorder = {}
end
slot0.Dispose = function (slot0)
if slot0.isPreview then
slot0:Finish(true)
end
if slot0.dragTrigger then
ClearEventTrigger(slot0.dragTrigger)
slot0.dragTrigger = nil
end
slot0.exitFlag = nil
slot0.recorder = nil
slot0.isPreview = nil
pg.DelegateInfo.Dispose(slot0)
end
return slot0
|
-- ----------------------------------------------
-- Copyright (c) 2019, CounterFlow AI, Inc. All Rights Reserved.
-- Author: Collins Huff <[email protected]>
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE.txt file.
-- ----------------------------------------------
require 'analyzer/ip-utils'
require 'analyzer/internal-ip'
function test_bitand_nums()
local x = 123
local y = 123
local z = 123
assert(bitand(x,y) == z)
x = 123
y = 456
z = 72
assert(bitand(x,y) == z)
x = nil
y = 456
z = 72
assert(bitand(x,y) == nil)
end
function test_bitand_strs()
local x = "1111"
local y = "1111"
local z = "1111"
assert(bitand(x,y) == z)
x = "1111"
y = "0000"
z = "0000"
assert(bitand(x,y) == z)
x = "0000"
y = "0000"
z = "0000"
assert(bitand(x,y) == z)
x = "1010"
y = "1101"
z = "1000"
assert(bitand(x,y) == z)
x = nil
y = "1111"
z = nil
assert(bitand(x,y) == nil)
end
function test_get_ip_type()
local ipv4 = "192.168.0.1"
assert(GetIPType(ipv4) == 1)
local ipv6 = "2001:0db8:0000:0000:0000:0000:0000:0000"
assert(GetIPType(ipv6) == 2)
local malformed_ipv4 = "..."
assert(GetIPType(malformed_ipv4) == 3)
local malformed_ipv6 = ":::::::::"
assert(GetIPType(malformed_ipv6) == 3)
end
function test_ipv4_to_long()
local ip = "192.168.0.1"
ip_int = 3232235521
assert(IPv4ToLong(ip) == ip_int)
ip = "255.255.255.255"
ip_int = 4294967295
assert(IPv4ToLong(ip) == ip_int)
ip = "1.1.1.1.1.1"
ip_int = nil
assert(IPv4ToLong(ip) == ip_int)
ip = "...."
ip_int = nil
assert(IPv4ToLong(ip) == ip_int)
end
function test_ipv6_to_bin()
local ipv6 = "1234:5678:9ABC:DEF0:DEAD:BEEF:0000:ABCD"
local ipv6_bin = "00010010001101000101011001111000100110101011110011011110111100001101111010101101101111101110111100000000000000001010101111001101"
assert(ipv6_to_bin(ipv6) == ipv6_bin)
local ipv6 = "1234:5678:9ABC:DEF0:DEAD:BEEF:0000:ABCD"
local ipv6_bin = "00010010001101000101011001111000100110101011110011011110111100001101111010101101101111101110111100000000000000001010101111001101"
assert(ipv6_to_bin(ipv6) == ipv6_bin)
end
function test_ipv4_internal()
local subnet_ip = "192.168.0.1"
local subnet_mask = "255.255.255.0"
local test_ip = "192.168.0.35"
assert(is_internal_ipv4(test_ip, subnet_ip, subnet_mask))
test_ip = "192.168.1.35"
assert(is_internal_ipv4(test_ip, subnet_ip, subnet_mask) == false)
test_ip = "192.198.0.1"
assert(is_internal_ipv4(test_ip, subnet_ip, subnet_mask) == false)
end
function test_ipv6_internal()
local subnet_ipv6 = "2001:0db8:0000:0000:0000:0000:0000:0000"
local subnet_mask = "ffff:ffff:0000:0000:0000:0000:0000:0000"
local test_ipv6 = "2001:0db8:0000:0000:0000:0000:0000:1111"
assert(is_internal_ipv6(test_ipv6, subnet_ipv6, subnet_mask))
test_ipv6 = "3001:0db8:0000:0000:0000:0000:0000:1111"
assert(is_internal_ipv6(test_ipv6, subnet_ipv6, subnet_mask) == false)
end
test_bitand_nums()
test_bitand_strs()
test_get_ip_type()
test_ipv4_to_long()
test_ipv6_to_bin()
test_ipv4_internal()
test_ipv6_internal()
print("PASS")
|
ITEM.name = "Small metal crate"
ITEM.description= "A small metal crate, rewarded for completing a quest. Something is inside."
ITEM.model = "models/lostsignalproject/items/quest/toolkit_drug.mdl"
ITEM.width = 3
ITEM.height = 3
ITEM.flag = "A"
ITEM.itemsForcedDrop = {
{"bagrubles", {["quantity"] = 5500}},
}
ITEM.items[1] = {
dropAmount = 1,
dropRareChance = 35,
dropVeryRareChance = 5,
itemsCommon = {
{"tokarev"},
{"ruger1022"},
},
itemsRare = {
{"toz66short"},
{"toz34short"},
{"makarov"},
},
itemsVeryRare = {
{"toz66"},
{"toz34"},
{"m3supershort"},
},
} |
return {
'nathom/filetype.nvim',
config = function ()
require('plugin.filetype.config')
end,
}
|
SumoWarNpc = {
redWin = function()
local pc = core:getObjectsInMap(15030, BL_PC)
broadcast(
15030,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(15030, "Red Team Wins!")
broadcast(15030, "You will return to the Arena in 5 seconds")
broadcast(
15030,
"-----------------------------------------------------------------------------------------------------"
)
core.gameRegistry["sumo_war_end_timer"] = os.time() + 5
end,
blueWin = function()
local pc = core:getObjectsInMap(15030, BL_PC)
broadcast(
15030,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(15030, "Blue Team Wins!")
broadcast(15030, "You will return to the Arena in 5 seconds")
broadcast(
15030,
"-----------------------------------------------------------------------------------------------------"
)
core.gameRegistry["sumo_war_end_timer"] = os.time() + 5
end,
getStartTimer = function()
local hour, minute, second = 0, 0, 0
if core.gameRegistry["sumo_war_start"] < os.time() then
return "00:00:00"
else
dif = core.gameRegistry["sumo_war_start"] - os.time()
hour = string.format("%02.f", math.floor(dif / 3600))
minute = string.format("%02.f", math.floor(dif / 60 - (hour * 60)))
second = string.format(
"%02.f",
math.floor(dif - hour * 3600 - minute * 60)
)
return hour .. ":" .. minute .. ":" .. second
end
end,
click = async(function(player, npc)
local pc = player:getObjectsInMap(15031, BL_PC)
local n = "<b>[Sumo War]\n\n"
local t = {g = convertGraphic(npc.look, "monster"), c = npc.lookColor}
player.npcGraphic = t.g
player.npcColor = t.c
player.dialogType = 0
local str, par = "", ""
local time = SumoWarNpc.getStartTimer()
local opts = {}
table.insert(opts, "How To Play?")
if core.gameRegistry["sumo_war"] == 1 then
if player.registry["sumo_war_team"] == 0 then
table.insert(opts, "Register For Sumo War")
else
par = " participant."
end
if player.registry["sumo_war_team"] > 0 then
table.insert(opts, "I can't register!")
end
end
table.insert(opts, "Exit")
if core.gameRegistry["sumo_war_start"] > os.time() then
str = "Waiting time: " .. SumoWarNpc.getStartTimer()
end
menu = player:menuString(
n .. "Hello," .. par .. " The game will start in few minutes.\n" .. str .. "\nTotal players: " .. #pc,
opts
)
if menu == "How To Play?" then
player:dialogSeq(
{
t,
n .. "Sumo War is a team based game about knocking oppenents into the water in order to score points.",
n .. "Depending on the total number of players, your team may need 5, 10 or 15 points to win the game.",
n .. "Use your attack to push enemies around, and if they splash into the water your team scores a point.",
n .. "Anyone who gets knocked into the water will re-enter the game after a short wait.",
n .. "Be careful of the bridges, they can be tricky."
},
1
)
player:freeAsync()
SumoWarNpc.click(player, npc)
elseif menu == "Register For Sumo War" then
if os.time() < player.registry["minigameBan"] then
--Check if player is banned from minigames
player:popUp("You are currently banned from minigames! Try again later maybe.")
return
end
local confirm = player:menuSeq(
"It will cost 2,000 gold to play. Do you agree?",
{"Yes, pay 2,000 gold.", "Nevermind."},
{}
)
if confirm == 1 then
if player.money < 2000 then
player:dialogSeq(
{t, "You don't have enough gold to play."},
0
)
return
end
player:removeGold(2000)
player.registry["sumo_war_team"] = math.random(1, 2)
player:warp(15031, math.random(2, 14), math.random(2, 12))
player:sendAnimation(16)
player:playSound(29)
player:dialogSeq(
{
t,
n .. "Alright, your character is registered for Sumo War.\nPlease wait until the game starts!"
},
1
)
end
elseif menu == "I can't register!" then
player.registry["sumo_war_team"] = 0
player:dialogSeq(
{
t,
n .. "Looks like a simple paperwork mixup. You should be all set to register now, have fun at the game!"
},
1
)
player:freeAsync()
SumoWarNpc.click(player, npc)
end
end),
core = function()
SumoWarNpc.closed()
SumoWarNpc.balancing()
SumoWarNpc.begin()
SumoWarNpc.respawn()
SumoWarNpc.endGame()
SumoWarNpc.bridgeController()
end,
open = function()
core.gameRegistry["sumo_war"] = 1
core.gameRegistry["sumo_war_start"] = os.time() + 900
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
-1,
" Sumo War is now open in Kugnae Arena!"
)
broadcast(
-1,
" Entry is closing in 15 minutes!"
)
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
end,
roundTwo = function()
core.gameRegistry["sumo_war"] = 1
core.gameRegistry["sumo_war_start"] = os.time() + 120
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
-1,
" Another chance to play! Get ready!"
)
broadcast(
-1,
" Sumo War is now open in Kugnae Arena!"
)
broadcast(
-1,
" Entry is closing in 2 minutes!"
)
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
end,
closed = function()
local diff = core.gameRegistry["sumo_war_start"] - os.time()
if core.gameRegistry["sumo_war"] == 1 then
if core.gameRegistry["sumo_war_start"] > os.time() then
if diff == 300 then
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
-1,
" Sumo War entry is closing in 5 minute!"
)
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
elseif diff == 600 then
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
-1,
" Sumo War entry is closing in 10 minutes!"
)
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
elseif diff == 60 then
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
-1,
" Sumo War entry is closing in 1 minute!"
)
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
elseif diff == 10 then
broadcast(
15031,
" Sumo War Starts in 10 seconds!"
)
elseif diff <= 3 then
broadcast(
15031,
" Sumo War Starts in " .. diff .. " seconds!"
)
end
elseif core.gameRegistry["sumo_war_start"] < os.time() then
core.gameRegistry["sumo_war"] = 0
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
-1,
" Sumo War entry is closed!"
)
broadcast(
-1,
"-----------------------------------------------------------------------------------------------------"
)
SumoWarNpc.start()
end
end
end,
endGame = function()
local pc = core:getObjectsInMap(15030, BL_PC)
local arenaPC = core:getObjectsInMap(31, BL_PC)
if core.gameRegistry["sumo_war_end_timer"] > 0 and core.gameRegistry[
"sumo_war_end_timer"
] < os.time() then
core.gameRegistry["sumo_war_end_timer"] = 0
core.gameRegistry["sumo_war"] = 0
core.gameRegistry["sumo_war_red_point"] = 0
core.gameRegistry["sumo_war_blue_point"] = 0
core.gameRegistry["sumo_war_bridge_point"] = 0
core.gameRegistry["sumo_war_wait_time"] = 0
core.gameRegistry["sumo_war_warped_players"] = 0
core.gameRegistry["sumo_war_playing"] = 0
if #pc > 0 then
for i = 1, #pc do
pc[i].health = pc[i].maxHealth
pc[i].state = 0
pc[i].gfxClone = 0
pc[i]:updateState()
if pc[i].registry["sumo_war_team"] == core.gameRegistry["sumo_war_winner"] then
SumoWarNpc.victoryLegend(pc[i])
minigames.giveMinigameExp(pc[i], 1)
else
minigames.giveMinigameExp(pc[i], 2)
end
pc[i].registry["sumo_war_team"] = 0
pc[i]:warp(31, math.random(6, 15), math.random(8, 15))
pc[i]:sendAnimation(16)
pc[i]:playSound(29)
pc[i]:calcStat()
end
end
if #arenaPC > 0 then
for i = 1, #arenaPC do
arenaPC[i].gfxClone = 0
arenaPC[i]:updateState()
end
end
core.gameRegistry["sumo_war_winner"] = 0
--[[if core.gameRegistry["sumo_war_round_2"] == 0 then
core.gameRegistry["sumo_war_round_2"] = 1
SumoWarNpc.roundTwo()
elseif core.gameRegistry["sumo_war_round_2"] == 1 then
core.gameRegistry["sumo_war_round_2"] = 0
return
end]]
--
end
end,
stop = function()
local pc = core:getObjectsInMap(15030, BL_PC)
core.gameRegistry["sumo_war_end_timer"] = 0
--core.gameRegistry["sumo_war_players"] = 0
core.gameRegistry["sumo_war"] = 0
core.gameRegistry["sumo_war_winner"] = 0
core.gameRegistry["sumo_war_red_point"] = 0
core.gameRegistry["sumo_war_blue_point"] = 0
core.gameRegistry["sumo_war_bridge_point"] = 0
core.gameRegistry["sumo_war_wait_time"] = 0
core.gameRegistry["sumo_war_playing"] = 0
core.gameRegistry["sumo_war_warped_players"] = 0
if #pc > 0 then
for i = 1, #pc do
--pc[i].registry["sumo_war_registered"] = 0
pc[i].mapRegistry["sumo_war_red_point"] = 0
pc[i].mapRegistry["sumo_war_blue_point"] = 0
pc[i].registry["sumo_war_team"] = 0
pc[i].gfxClone = 0
pc[i]:updateState()
pc[i]:warp(31, math.random(6, 15), math.random(8, 15))
pc[i]:sendAnimation(16)
pc[i]:playSound(29)
pc[i]:calcStat()
end
end
end,
cancel = function()
local pc = core:getObjectsInMap(15031, BL_PC)
core.gameRegistry["sumo_war_winner"] = 0
core.gameRegistry["sumo_war_end_timer"] = 0
--core.gameRegistry["sumo_war_players"] = 0
core.gameRegistry["sumo_war"] = 0
core.gameRegistry["sumo_war_red_point"] = 0
core.gameRegistry["sumo_war_blue_point"] = 0
core.gameRegistry["sumo_war_wait_time"] = 0
core.gameRegistry["sumo_war_playing"] = 0
core.gameRegistry["sumo_war_warped_players"] = 0
if #pc > 0 then
for i = 1, #pc do
--pc[i].registry["sumo_war_registered"] = 0
pc[i].mapRegistry["sumo_war_red_point"] = 0
pc[i].mapRegistry["sumo_war_blue_point"] = 0
pc[i].mapRegistry["sumo_war_bridge_point"] = 0
pc[i].registry["sumo_war_team"] = 0
pc[i]:warp(31, math.random(6, 15), math.random(8, 15))
pc[i]:sendAnimation(16)
pc[i]:playSound(29)
pc[i]:calcStat()
end
end
end,
entryLegend = function(player)
local reg = player.registry["sumo_war_entries"]
if player:hasLegend("sumo_war_entries") then
player:removeLegendbyName("sumo_war_entries")
end
if reg > 0 then
player.registry["sumo_war_entries"] = player.registry[
"sumo_war_entries"
] + 1
player:addLegend(
"Participated in " .. player.registry["sumo_war_entries"] .. " Sumo Wars",
"sumo_war_entries",
204,
16
)
else
player.registry["sumo_war_entries"] = 1
player:addLegend(
"Participated in 1 Sumo War",
"sumo_war_entries",
204,
16
)
end
end,
victoryLegend = function(player)
local reg = player.registry["sumo_war_wins"]
if player:hasLegend("sumo_war_wins") then
player:removeLegendbyName("sumo_war_wins")
end
if reg > 0 then
player.registry["sumo_war_wins"] = player.registry["sumo_war_wins"] + 1
player:addLegend(
"Won " .. player.registry["sumo_war_wins"] .. " Sumo Wars",
"sumo_war_wins",
204,
16
)
else
player.registry["sumo_war_wins"] = 1
player:addLegend("Won 1 Sumo War", "sumo_war_wins", 204, 16)
end
end,
start = function()
livingRedSquirt = {}
livingBlueSquirt = {}
if #livingRedSquirt ~= 0 then
rawset(livingRedSquirt, #livingRedSquirt, nil)
end
if #livingBlueSquirt ~= 0 then
rawset(livingBlueSquirt, #livingBlueSquirt, nil)
end
SumoWarNpc.balancing()
local pc = core:getObjectsInMap(15031, BL_PC)
if core.gameRegistry["sumo_war_warped_players"] == 0 then
core.gameRegistry["sumo_war_warped_players"] = 1
if #pc > 6 then
core.gameRegistry["sumo_war_wait_time"] = (os.time() + 30)
for i = 1, #pc do
if pc[i].registry["sumo_war_team"] > 0 and pc[i].state ~= 0 then
pc[i].state = 0
pc[i].speed = 90
pc[i].registry["mounted"] = 0
pc[i]:updateState()
end
if pc[i].registry["sumo_war_team"] == 1 then
table.insert(livingRedSquirt, pc[i].ID)
SumoWarNpc.costume(pc[i])
end
if pc[i].registry["sumo_war_team"] == 2 then
table.insert(livingBlueSquirt, pc[i].ID)
SumoWarNpc.costume(pc[i])
end
pc[i]:warp(15030, math.random(11, 35), math.random(28, 40))
end
SumoWarNpc.wait()
else
broadcast(
15031,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
15031,
" Not enough players. Sumo War canceled!"
)
broadcast(
15031,
"-----------------------------------------------------------------------------------------------------"
)
SumoWarNpc.cancel()
end
end
end,
wait = function()
broadcast(
15030,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
15030,
" Get Ready! Sumo War starts in 30 seconds!"
)
broadcast(
15030,
"-----------------------------------------------------------------------------------------------------"
)
end,
begin = function()
local pc = core:getObjectsInMap(15030, BL_PC)
if core.gameRegistry["sumo_war_wait_time"] > 0 and core.gameRegistry[
"sumo_war_wait_time"
] < os.time() then
if #pc > 6 then
broadcast(
15030,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
15030,
" The Sumo War has begun!"
)
broadcast(
15030,
"-----------------------------------------------------------------------------------------------------"
)
for i = 1, #pc do
if pc[i].registry["sumo_war_team"] == 1 then
pc[i]:warp(
15030,
math.random(52, 54),
math.random(10, 37)
)
SumoWarNpc.entryLegend(pc[i])
elseif pc[i].registry["sumo_war_team"] == 2 then
pc[i]:warp(
15030,
math.random(95, 97),
math.random(10, 37)
)
SumoWarNpc.entryLegend(pc[i])
end
end
else
broadcast(
15031,
"-----------------------------------------------------------------------------------------------------"
)
broadcast(
15031,
" Not enough players. Sumo War canceled!"
)
broadcast(
15031,
"-----------------------------------------------------------------------------------------------------"
)
SumoWarNpc.stop()
end
core.gameRegistry["sumo_war_playing"] = 1
core.gameRegistry["sumo_war_wait_time"] = 0
end
end,
balancing = function()
local red, blue = {}, {}
local pc = core:getObjectsInMap(15031, BL_PC)
if #pc > 0 then
for i = 1, #pc do
if pc[i].registry["sumo_war_team"] == 1 then
table.insert(red, pc[i].ID)
elseif pc[i].registry["sumo_war_team"] == 2 then
table.insert(blue, pc[i].ID)
end
end
end
if #pc > 0 then
for i = 1, #pc do
if #red > #blue then
if (#red - #blue) ~= 1 then
pc[math.random(#pc)].registry["sumo_war_team"] = 2
break
end
end
if #red < #blue then
if #blue - #red ~= 1 then
pc[math.random(#pc)].registry["sumo_war_team"] = 1
break
end
end
end
end
end,
costume = function(player)
local team = player.registry["sumo_war_team"]
local dye, str = 0, ""
if team == 1 then
dye = 31
elseif team == 2 then
dye = 17
end
if player.sex == 0 then
armor = 5
elseif player.sex == 1 then
armor = 9
end
clone.wipe(player)
clone.equip(player, player)
player.gfxWeap = 65535
player.gfxArmor = armor
player.gfxArmorC = dye
player.gfxDye = dye
player.gfxCrown = 65535
player.gfxShield = 65535
player.gfxNeck = 65535
player.gfxHelm = 65535
player.gfxMantle = 65535
player.gfxMantleC = 0
player.gfxClone = 1
player:updateState()
end,
winnerCheck = function()
local pointsToWin = 30
--[[if core.gameRegistry["sumo_war_players"] <= 6 then
pointsToWin = 5
elseif core.gameRegistry["sumo_war_players"] >= 7 and core.gameRegistry["sumo_war_players"] <= 16 then
pointsToWin = 10
elseif core.gameRegistry["sumo_war_players"] >= 17 then
pointsToWin = 15
end]]
--
if core.gameRegistry["sumo_war_red_point"] == pointsToWin then
core.gameRegistry["sumo_war_winner"] = 1
SumoWarNpc.redWin()
return
elseif core.gameRegistry["sumo_war_blue_point"] == pointsToWin then
core.gameRegistry["sumo_war_winner"] = 2
SumoWarNpc.blueWin()
return
end
end,
push = function(player)
local team = player.registry["sumo_war_team"]
local tile = {
628,
35012,
35013,
17816,
35011,
35010,
35009,
35017,
35015,
35014,
35025,
35016
}
local target = getTargetFacing(player, BL_PC)
local m, x, y = player.m, player.x, player.y
if m == 15031 then
if target ~= nil and target.state ~= 1 then
target.attacker = player.ID
player:sendFrontAnimation(191)
if player.side == 0 then
y = target.y - 1
elseif player.side == 1 then
x = target.x + 1
elseif player.side == 2 then
y = target.y + 1
elseif player.side == 3 then
x = target.x - 1
end
if getPass(m, x, y) == 1 then
return
else
target:sendAnimationXY(191, target.x, target.y)
target:warp(target.m, x, y)
end
end
end
if m == 15030 then
if target ~= nil and target.state ~= 1 and (target.registry["sumo_war_team"] ~= player.registry["sumo_war_team"]) and core.gameRegistry[
"sumo_war_winner"
] == 0 then
target.attacker = player.ID
player:sendFrontAnimation(191)
if player.side == 0 then
y = target.y - 1
elseif player.side == 1 then
x = target.x + 1
elseif player.side == 2 then
y = target.y + 1
elseif player.side == 3 then
x = target.x - 1
end
if player.x < 40 then
if getPass(m, x, y) == 1 then
return
else
target:sendAnimationXY(191, target.x, target.y)
target:warp(target.m, x, y)
end
else
target:sendAnimationXY(191, target.x, target.y)
target:warp(target.m, x, y)
for i = 1, #tile do
if getTile(target.m, target.x, target.y) == tile[i] then
if player.registry["sumo_war_team"] == 1 then
core.gameRegistry["sumo_war_red_point"] = core.gameRegistry[
"sumo_war_red_point"
] + 1
elseif player.registry["sumo_war_team"] == 2 then
core.gameRegistry["sumo_war_blue_point"] = core.gameRegistry[
"sumo_war_blue_point"
] + 1
end
target:sendAnimationXY(142, target.x, target.y)
SumoWarNpc.splash(target)
end
end
end
end
end
end,
splash = function(player)
player.health = 0
player.state = 1
player:updateState()
player:playSound(73)
player:sendAnimationXY(142, player.x, player.y)
player:warp(15030, math.random(11, 35), math.random(28, 40))
broadcast(
15030,
"CURRENT SCORE | RED: " .. core.gameRegistry["sumo_war_red_point"] .. " BLUE: " .. core.gameRegistry[
"sumo_war_blue_point"
] .. " BRIDGE: " .. core.gameRegistry["sumo_war_bridge_point"]
)
SumoWarNpc.winnerCheck()
end,
respawn = function()
local pc = core:getObjectsInMap(15030, BL_PC)
core.gameRegistry["sumo_respawn_time"] = core.gameRegistry[
"sumo_respawn_time"
] + 1
if core.gameRegistry["sumo_respawn_time"] == 15 then
for i = 1, #pc do
if pc[i].state == 1 then
if pc[i].x >= 9 and pc[i].x <= 38 then
if pc[i].y >= 26 and pc[i].y <= 42 then
pc[i].health = pc[i].maxHealth
pc[i].state = 0
if pc[i].registry["sumo_war_team"] == 1 then
pc[i]:warp(
15030,
math.random(52, 54),
math.random(10, 37)
)
end
if pc[i].registry["sumo_war_team"] == 2 then
pc[i]:warp(
15030,
math.random(95, 97),
math.random(10, 37)
)
end
end
end
end
end
core.gameRegistry["sumo_respawn_time"] = 0
end
end,
bridge = function(id)
local x
local y
local map = 15030
if id == 1 or id == 2 or id == 9 or id == 10 or id == 15 then
if id == 1 then
x = 65
y = 25
end
if id == 2 then
x = 65
y = 30
end
if id == 9 then
x = 84
y = 25
end
if id == 10 then
x = 84
y = 30
end
if id == 15 then
x = 58
y = 13
end
if id == 16 then
x = 91
y = 33
end
if id == 17 then
x = 91
y = 13
end
if id == 18 then
x = 58
y = 33
end
tile = getTile(map, x, y)
if tile == 628 then
setTile(map, x, y, 218)
setTile(map, x, y + 1, 221)
setPass(map, x, y, 0)
setPass(map, x, y + 1, 0)
return
else
setTile(map, x, y, 628)
setTile(map, x, y + 1, 628)
setPass(map, x, y, 1)
setPass(map, x, y + 1, 1)
local splashPC1 = core:getObjectsInCell(map, x, y, BL_PC)
local splashPC2 = core:getObjectsInCell(map, x, y + 1, BL_PC)
if #splashPC1 > 0 then
for i = 1, #splashPC1 do
SumoWarNpc.splash(splashPC1[i])
core.gameRegistry["sumo_war_bridge_point"] = core.gameRegistry[
"sumo_war_bridge_point"
] + 1
end
end
if #splashPC2 > 0 then
for i = 1, #splashPC2 do
SumoWarNpc.splash(splashPC2[i])
core.gameRegistry["sumo_war_bridge_point"] = core.gameRegistry[
"sumo_war_bridge_point"
] + 1
end
end
end
return
elseif id == 3 then
x = 71
y = 23
elseif id == 4 then
x = 72
y = 28
elseif id == 5 then
x = 71
y = 33
elseif id == 6 then
x = 76
y = 23
elseif id == 7 then
x = 77
y = 28
elseif id == 8 then
x = 76
y = 33
elseif id == 11 then
x = 84
y = 36
elseif id == 12 then
x = 84
y = 10
elseif id == 13 then
x = 64
y = 10
elseif id == 14 then
x = 64
y = 36
end
local tile = getTile(map, x, y)
if tile == 628 then
setTile(map, x, y, 218)
setTile(map, x + 1, y, 218)
setTile(map, x, y + 1, 221)
setTile(map, x + 1, y + 1, 221)
setPass(map, x, y, 0)
setPass(map, x + 1, y, 0)
setPass(map, x, y + 1, 0)
setPass(map, x + 1, y + 1, 0)
return
else
setTile(map, x, y, 628)
setTile(map, x + 1, y, 628)
setTile(map, x, y + 1, 628)
setTile(map, x + 1, y + 1, 628)
setPass(map, x, y, 1)
setPass(map, x + 1, y, 1)
setPass(map, x, y + 1, 1)
setPass(map, x + 1, y + 1, 1)
local splashPC3 = core:getObjectsInCell(map, x, y, BL_PC)
local splashPC4 = core:getObjectsInCell(map, x + 1, y, BL_PC)
local splashPC5 = core:getObjectsInCell(map, x, y + 1, BL_PC)
local splashPC6 = core:getObjectsInCell(map, x + 1, y + 1, BL_PC)
if #splashPC3 > 0 then
for i = 1, #splashPC3 do
SumoWarNpc.splash(splashPC3[i])
core.gameRegistry["sumo_war_bridge_point"] = core.gameRegistry[
"sumo_war_bridge_point"
] + 1
end
end
if #splashPC4 > 0 then
for i = 1, #splashPC4 do
SumoWarNpc.splash(splashPC4[i])
core.gameRegistry["sumo_war_bridge_point"] = core.gameRegistry[
"sumo_war_bridge_point"
] + 1
end
end
if #splashPC5 > 0 then
for i = 1, #splashPC5 do
SumoWarNpc.splash(splashPC5[i])
core.gameRegistry["sumo_war_bridge_point"] = core.gameRegistry[
"sumo_war_bridge_point"
] + 1
end
end
if #splashPC6 > 0 then
for i = 1, #splashPC6 do
SumoWarNpc.splash(splashPC6[i])
core.gameRegistry["sumo_war_bridge_point"] = core.gameRegistry[
"sumo_war_bridge_point"
] + 1
end
end
end
end,
bridgeController = function()
if core.gameRegistry["sumo_war"] == 1 then
SumoWarNpc.bridge(math.random(1, 18))
end
end
}
|
require("lib.lclass")
class "Database"
function Database:Database()
self.entities = {}
end
function Database:add(entity)
table.insert(self.entities, entity)
end
function Database:filter(predicate)
local candidates = {}
for _,entity in ipairs(self.entities) do
local hasall = true
for _,p in ipairs(predicate) do
hasall = hasall and entity:hasComponent(p)
end
if hasall then
table.insert(candidates, entity)
end
end
return candidates
end
function Database:getById(id)
local match = nil
for _,entity in pairs(self.entities) do
if entity.id == id then
match = entity
break
end
end
return match
end
|
local cache = require('cmp.utils.cache')
local char = require('cmp.utils.char')
local misc = require('cmp.utils.misc')
local str = require('cmp.utils.str')
local config = require('cmp.config')
local types = require('cmp.types')
---@class cmp.Entry
---@field public id number
---@field public cache cmp.Cache
---@field public score number
---@field public exact boolean
---@field public context cmp.Context
---@field public source cmp.Source
---@field public source_offset number
---@field public source_insert_range lsp.Range
---@field public source_replace_range lsp.Range
---@field public completion_item lsp.CompletionItem
---@field public resolved_completion_item lsp.CompletionItem|nil
---@field public resolved_callbacks fun()[]
---@field public resolving boolean
---@field public confirmed boolean
local entry = {}
---Create new entry
---@param ctx cmp.Context
---@param source cmp.Source
---@param completion_item lsp.CompletionItem
---@return cmp.Entry
entry.new = function(ctx, source, completion_item)
local self = setmetatable({}, { __index = entry })
self.id = misc.id('entry')
self.cache = cache.new()
self.score = 0
self.context = ctx
self.source = source
self.source_offset = source.request_offset
self.source_insert_range = source:get_default_insert_range()
self.source_replace_range = source:get_default_replace_range()
self.completion_item = completion_item
self.resolved_completion_item = nil
self.resolved_callbacks = {}
self.resolving = false
self.confirmed = false
return self
end
---Make offset value
---@return number
entry.get_offset = function(self)
return self.cache:ensure('get_offset', function()
local offset = self.source_offset
if misc.safe(self.completion_item.textEdit) then
local range = misc.safe(self.completion_item.textEdit.insert) or misc.safe(self.completion_item.textEdit.range)
if range then
local c = misc.to_vimindex(self.context.cursor_line, range.start.character)
for idx = c, self.source_offset do
if not char.is_white(string.byte(self.context.cursor_line, idx)) then
offset = math.min(offset, idx)
break
end
end
end
else
-- NOTE
-- The VSCode does not implement this but it's useful if the server does not care about word patterns.
-- We should care about this performance.
local word = self:get_word()
for idx = self.source_offset - 1, self.source_offset - #word, -1 do
if char.is_semantic_index(self.context.cursor_line, idx) then
local c = string.byte(self.context.cursor_line, idx)
if char.is_white(c) then
break
end
local match = true
for i = 1, self.source_offset - idx do
local c1 = string.byte(word, i)
local c2 = string.byte(self.context.cursor_line, idx + i - 1)
if not c1 or not c2 or c1 ~= c2 then
match = false
break
end
end
if match then
offset = math.min(offset, idx)
end
end
end
end
return offset
end)
end
---Create word for vim.CompletedItem
---@return string
entry.get_word = function(self)
return self.cache:ensure('get_word', function()
--NOTE: This is nvim-cmp specific implementation.
if misc.safe(self.completion_item.word) then
return self.completion_item.word
end
local word
if misc.safe(self.completion_item.textEdit) then
word = str.trim(self.completion_item.textEdit.newText)
local _, after = self:get_overwrite()
if 0 < after or self.completion_item.insertTextFormat == types.lsp.InsertTextFormat.Snippet then
word = str.get_word(word, string.byte(self.context.cursor_after_line, 1))
end
elseif misc.safe(self.completion_item.insertText) then
word = str.trim(self.completion_item.insertText)
word = str.get_word(word)
else
word = str.trim(self.completion_item.label)
word = str.get_word(word, '')
end
return word
end)
end
---Get overwrite information
---@return number, number
entry.get_overwrite = function(self)
return self.cache:ensure('get_overwrite', function()
if misc.safe(self.completion_item.textEdit) then
local r = misc.safe(self.completion_item.textEdit.insert) or misc.safe(self.completion_item.textEdit.range)
local s = misc.to_vimindex(self.context.cursor_line, r.start.character)
local e = misc.to_vimindex(self.context.cursor_line, r['end'].character)
local before = self.context.cursor.col - s
local after = e - self.context.cursor.col
return before, after
end
return 0, 0
end)
end
---Create filter text
---@return string
entry.get_filter_text = function(self)
return self.cache:ensure('get_filter_text', function()
local word
if misc.safe(self.completion_item.filterText) then
word = self.completion_item.filterText
else
word = str.trim(self.completion_item.label)
end
-- @see https://github.com/clangd/clangd/issues/815
if misc.safe(self.completion_item.textEdit) then
local diff = self.source_offset - self:get_offset()
if diff > 0 then
if char.is_symbol(string.byte(self.context.cursor_line, self:get_offset())) then
local prefix = string.sub(self.context.cursor_line, self:get_offset(), self:get_offset() + diff)
if string.find(word, prefix, 1, true) ~= 1 then
word = prefix .. word
end
end
end
end
return word
end)
end
---Get LSP's insert text
---@return string
entry.get_insert_text = function(self)
return self.cache:ensure('get_insert_text', function()
local word
if misc.safe(self.completion_item.textEdit) then
word = str.trim(self.completion_item.textEdit.newText)
if self.completion_item.insertTextFormat == types.lsp.InsertTextFormat.Snippet then
word = str.remove_suffix(str.remove_suffix(word, '$0'), '${0}')
end
elseif misc.safe(self.completion_item.insertText) then
word = str.trim(self.completion_item.insertText)
if self.completion_item.insertTextFormat == types.lsp.InsertTextFormat.Snippet then
word = str.remove_suffix(str.remove_suffix(word, '$0'), '${0}')
end
else
word = str.trim(self.completion_item.label)
end
return word
end)
end
---Make vim.CompletedItem
---@param suggest_offset number
---@return vim.CompletedItem
entry.get_vim_item = function(self, suggest_offset)
return self.cache:ensure({ 'get_vim_item', suggest_offset, self.resolved_completion_item and 1 or 0 }, function()
local completion_item = self:get_completion_item()
local word = self:get_word()
local abbr = str.trim(completion_item.label)
-- ~ indicator
if #(misc.safe(completion_item.additionalTextEdits) or {}) > 0 then
abbr = abbr .. '~'
elseif completion_item.insertTextFormat == types.lsp.InsertTextFormat.Snippet then
local insert_text = self:get_insert_text()
if word ~= insert_text then
abbr = abbr .. '~'
end
end
-- deprecated
if config.get().formatting.deprecated then
if completion_item.deprecated or vim.tbl_contains(completion_item.tags or {}, types.lsp.CompletionItemTag.Deprecated) then
abbr = str.strikethrough(abbr)
end
end
-- append delta text
if suggest_offset < self:get_offset() then
word = string.sub(self.context.cursor_before_line, suggest_offset, self:get_offset() - 1) .. word
end
-- labelDetails.
local menu = nil
if misc.safe(completion_item.labelDetails) then
menu = ''
if misc.safe(completion_item.labelDetails.parameters) then
menu = menu .. completion_item.labelDetails.parameters
end
if misc.safe(completion_item.labelDetails.type) then
menu = menu .. completion_item.labelDetails.type
end
if misc.safe(completion_item.labelDetails.qualifier) then
menu = menu .. completion_item.labelDetails.qualifier
end
end
-- remove duplicated string.
for i = 1, #word - 1 do
if str.has_prefix(self.context.cursor_after_line, string.sub(word, i, #word)) then
word = string.sub(word, 1, i - 1)
break
end
end
local vim_item = {
word = word,
abbr = abbr,
kind = types.lsp.CompletionItemKind[self:get_kind()] or types.lsp.CompletionItemKind[1],
menu = menu,
dup = self.completion_item.dup or 1,
}
if config.get().formatting.format then
vim_item = config.get().formatting.format(self, vim_item)
end
vim_item.equal = 1
vim_item.empty = 1
vim_item.user_data = { cmp = self.id }
return vim_item
end)
end
---Get commit characters
---@return string[]
entry.get_commit_characters = function(self)
return misc.safe(self:get_completion_item().commitCharacters) or {}
end
---Return insert range
---@return lsp.Range|nil
entry.get_insert_range = function(self)
local insert_range
if misc.safe(self.completion_item.textEdit) then
if misc.safe(self.completion_item.textEdit.insert) then
insert_range = self.completion_item.textEdit.insert
else
insert_range = self.completion_item.textEdit.range
end
else
insert_range = {
start = {
line = self.context.cursor.row - 1,
character = math.min(misc.to_utfindex(self.context.cursor_line, self:get_offset()), self.source_insert_range.start.character),
},
['end'] = self.source_insert_range['end'],
}
end
return insert_range
end
---Return replace range
---@return lsp.Range|nil
entry.get_replace_range = function(self)
return self.cache:ensure('get_replace_range', function()
local replace_range
if misc.safe(self.completion_item.textEdit) then
if misc.safe(self.completion_item.textEdit.replace) then
replace_range = self.completion_item.textEdit.replace
else
replace_range = self.completion_item.textEdit.range
end
else
replace_range = {
start = {
line = self.source_replace_range.start.line,
character = math.min(misc.to_utfindex(self.context.cursor_line, self:get_offset()), self.source_replace_range.start.character),
},
['end'] = self.source_replace_range['end'],
}
end
return replace_range
end)
end
---Get resolved completion item if possible.
---@return lsp.CompletionItem
entry.get_completion_item = function(self)
if self.resolved_completion_item then
return self.resolved_completion_item
end
return self.completion_item
end
---Create documentation
---@return string
entry.get_documentation = function(self)
local item = self:get_completion_item()
local documents = {}
-- detail
if misc.safe(item.detail) and item.detail ~= '' then
table.insert(documents, {
kind = types.lsp.MarkupKind.Markdown,
value = ('```%s\n%s\n```'):format(self.context.filetype, str.trim(item.detail)),
})
end
if type(item.documentation) == 'string' and item.documentation ~= '' then
table.insert(documents, {
kind = types.lsp.MarkupKind.PlainText,
value = str.trim(item.documentation),
})
elseif type(item.documentation) == 'table' and item.documentation.value ~= '' then
table.insert(documents, item.documentation)
end
return vim.lsp.util.convert_input_to_markdown_lines(documents)
end
---Get completion item kind
---@return lsp.CompletionItemKind
entry.get_kind = function(self)
return misc.safe(self.completion_item.kind) or types.lsp.CompletionItemKind.Text
end
---Execute completion item's command.
---@param callback fun()
entry.execute = function(self, callback)
self.source:execute(self:get_completion_item(), callback)
end
---Resolve completion item.
---@param callback fun()
entry.resolve = function(self, callback)
if self.resolved_completion_item then
return callback()
end
table.insert(self.resolved_callbacks, callback)
if not self.resolving then
self.resolving = true
self.source:resolve(self.completion_item, function(completion_item)
self.resolved_completion_item = misc.safe(completion_item) or self.completion_item
for _, c in ipairs(self.resolved_callbacks) do
c()
end
end)
end
end
return entry
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.