content
stringlengths 5
1.05M
|
|---|
--------------------------------------------------------------------------------
--- List directory content
--
-- @usage
--
-- -- List directory, recursive:
--
-- local ls = require("gears.filesystem.ls")
--
-- ls('/tmp', function(result) dbg.dump(result) end, true)
--
-- @author Michael Perlov
-- @copyright 2018 Michael Perlov
-- @module gears.filesystem.ls
--------------------------------------------------------------------------------
local Gio = require("lgi").Gio
local gdebug = require("gears.debug")
local gfs = require("gears.filesystem")
local ls = {}
local protected_call = require("gears.protected_call")
local do_protected_call, call_callback
do
-- Lua 5.1 cannot yield across a protected call. Instead of hardcoding a
-- check, we check for this problem: The following coroutine yields true on
-- success (so resume() returns true, true). On failure, pcall returns
-- false and a message, so resume() returns true, false, message.
local _, has_yieldable_pcall = coroutine.resume(coroutine.create(function()
return pcall(coroutine.yield, true)
end))
if has_yieldable_pcall then
do_protected_call = protected_call.call
call_callback = function(callback, ...)
return callback(...)
end
else
do_protected_call = function(f, ...)
return f(...)
end
call_callback = protected_call.call
end
end
--- List directory content.
-- @tparam string directory The directory path.
-- @tparam function callback Will be fired when directory was parsed
-- with the resulting list of files as argument.
-- @tparam boolean recursive Work recursively. Default false.
-- @function gears.filesystem.ls
function ls.ls(directory, callback, recursive)
local function enumerator(gfile, result)
local enum, err = gfile:async_enumerate_children("standard::name,standard::type,access::can-read",
Gio.FileQueryInfoFlags.NONE)
if not enum then
gdebug.print_error(err)
return
end
while true do
local list, err = enum:async_next_files(100)
if err then
gdebug.print_error(err)
return
end
for _, gfileinfo in ipairs(list) do
local file_child = enum:get_child(gfileinfo)
local file_type = gfileinfo:get_file_type()
local readable = gfileinfo:get_attribute_boolean("access::can-read")
if file_type == 'REGULAR' and readable then
local path = file_child:get_path()
if path then
table.insert(result, path)
end
elseif file_type == 'DIRECTORY' and recursive then
enumerator(file_child, result)
end
end
if #list == 0 then
break
end
end
enum:async_close()
end
Gio.Async.start(do_protected_call)(function()
local result = {}
enumerator(Gio.File.new_for_path(directory), result)
call_callback(callback, result)
end)
end
return setmetatable(ls, { __call = function(_,...) ls.ls(...) end})
|
--[[
Copyright (c) 2021-2022 Jason Morley, Tom Sutcliffe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
_ENV = module()
fns = {
[0x861E] = "IoPlaySoundW",
[0x861F] = "IoPlaySoundA",
[0x8620] = "IoPlaySoundCancel",
[0x8B1B] = "GenGetLanguageCode",
[0x8D0E] = "wInquireWindow",
[0x8D11] = "wFree",
[0x8D7E] = "wserv8D7E",
[0x8DF5] = "wSetSprite",
[0x8DF6] = "wCreateSprite",
[0x8E28] = "HwGetScanCodes",
}
function dumpRegisters(registers)
local function fmt(reg)
if ~reg then
return string.format("0x%04X", reg)
else
return tostring(reg)
end
end
return string.format("ax=%s, bx=%s, cx=%s, dx=%s, si=%s, di=%s",
fmt(registers.ax), fmt(registers.bx), fmt(registers.cx), fmt(registers.dx), fmt(registers.si), fmt(registers.di))
end
function syscall(runtime, fn, params, results)
-- printf("syscall fn=%02X %s\n", fn, dumpRegisters(params))
local fnSub = (fn << 8) | ((params.ax >> 8) & 0xFF)
local fnName = fns[fnSub]
if not fnName then
-- See if there's one with no sub
fnName = fns[fn << 8]
end
if fnName and _ENV[fnName] then
return _ENV[fnName](runtime, params, results)
else
printf("Unimplemented fn=%02X Params %s results %s\n", fn, dumpRegisters(params), dumpRegisters(results))
unimplemented(string.format("syscall.%04X", fnSub))
end
end
function GenGetLanguageCode(runtime, params, results)
results.ax = require("sis").Locales["en_GB"]
return 0
end
function wInquireWindow(runtime, params, results)
local winId = params.bx
local ctx = runtime:getGraphicsContext(winId)
assert(ctx and ctx.isWindow, KErrInvalidWindow)
local resultAddr = runtime:addrFromInt(results.si)
resultAddr:write(string.pack("<I2I2I2I2I2xxxx", 0, ctx.winX, ctx.winY, ctx.width, ctx.height))
return 0
end
function wFree(runtime, params, results)
-- We're going to ignore this one for now because we don't have separate
-- namespaces for all the types of identifier that wFree apparently
-- accepts...
return 0
end
function wserv8D7E(runtime, params, results)
local al = params.ax & 0xFF
if al == 2 then
printf("wDisableKeyClick disable=%s\n", params.bx ~= 0)
return 0
else
unimplemented("syscall.8D.7E."..tostring(al))
end
end
local function getSpriteFrame(runtime, addr)
local bmpBlackSet, bmpBlackClear, bmpBlackInvert, bmpGreySet, bmpGreyClear, bmpGreyInvert, relx, rely, delay =
string.unpack("<I2I2I2I2I2I2I2I2I4", runtime:addrFromInt(addr):read(24))
-- print("Sprite params", bmpBlackSet, bmpBlackClear, bmpBlackInvert, bmpGreySet, bmpGreyClear, bmpGreyInvert, relx, rely, delay)
-- These are returned in the same order as accepted by SPRITECHANGE and SPRITEAPPEND
return delay * 0.1, bmpBlackSet, bmpBlackSet, true, relx, rely
end
function wSetSprite(runtime, params, results)
-- print("wSetSprite", dumpRegisters(params))
local spriteId = params.bx
local bmp = require("opx.bmp")
if params.cx ~= 0 then
local x = runtime:addrAsVariable(params.cx, DataTypes.EWord)()
local y = runtime:addrAsVariable(params.cx + 2, DataTypes.EWord)()
bmp.SPRITEPOS(runtime, spriteId, x, y)
end
if params.di ~= 0 then
local frameId = params.dx + 1 -- Or si...?
bmp.SPRITECHANGE(runtime, spriteId, frameId, getSpriteFrame(runtime, params.di))
end
results.ax = 0
return 0
end
function wCreateSprite(runtime, params, results)
print("wCreateSprite", dumpRegisters(params))
local winId = params.bx
if winId == 0 then
-- Apparently 0 can mean default win?
winId = 1
end
local x = runtime:addrAsVariable(params.cx, DataTypes.EWord)()
local y = runtime:addrAsVariable(params.cx + 2, DataTypes.EWord)()
local bmp = require("opx.bmp")
local id = bmp.SPRITECREATE(runtime, winId, x, y, 0)
local numSprites = params.di
local spriteInfoAddr = params.si
for i = 1, numSprites do
bmp.SPRITEAPPEND(runtime, getSpriteFrame(runtime, spriteInfoAddr))
spriteInfoAddr = spriteInfoAddr + 24
end
bmp.SPRITEDRAW(runtime)
results.ax = id
return 0
end
function IoPlaySoundW(runtime, params, results)
-- print("IoPlaySoundW", dumpRegisters(params))
-- Fortunately PlaySound doesn't care (and will respect) what the type of
-- var is, so even though system.lua expects an ELong, we are OK to use an
-- EWord here.
local var = runtime:makeTemporaryVar(DataTypes.EWord)
params.di = var:addressOf()
IoPlaySoundA(runtime, params, results)
runtime:waitForRequest(var)
results.ax = var() -- This will sign extend into AH which is ok
-- printf("IoPlaySoundW returned %d\n", var())
return 0
end
function IoPlaySoundA(runtime, params, results)
local path = runtime:abs(string.unpack("z", runtime:addrFromInt(params.bx):read(255)))
if not runtime:EXIST(path) then
path = path .. ".WVE"
end
local duration = params.cx
local volume = params.dx
printf("IoPlaySoundA path=%s\n", path)
local var = runtime:addrAsVariable(params.di, DataTypes.EWord)
runtime:PlaySoundA(var, path)
return 0, 0
end
function IoPlaySoundCancel(runtime, params, results)
print("IoPlaySoundCancel")
runtime:StopSound()
results.ax = 0
return 0
end
local function byte(bit0, bit1, bit2, bit3, bit4, bit5, bit6, bit7)
return
(bit0 and 1 or 0) |
(bit1 and 0x2 or 0) |
(bit2 and 0x4 or 0) |
(bit3 and 0x8 or 0) |
(bit4 and 0x10 or 0) |
(bit5 and 0x20 or 0) |
(bit6 and 0x40 or 0) |
(bit7 and 0x80 or 0)
end
function HwGetScanCodes(runtime, params, results)
-- print("HwGetScanCodes", dumpRegisters(params), dumpRegisters(results))
local keys = runtime:iohandler().keysDown()
local scanCodes = require("oplkeycode").series3aScanCodes
local bytes = {}
for i = 0, 19 do
local base = 1 + (8 * i)
bytes[i + 1] = byte(
keys[scanCodes[base]],
keys[scanCodes[base + 1]],
keys[scanCodes[base + 2]],
keys[scanCodes[base + 3]],
keys[scanCodes[base + 4]],
keys[scanCodes[base + 5]],
keys[scanCodes[base + 6]],
keys[scanCodes[base + 7]]
)
end
local buf = string.pack("BBBBBBBBBBBBBBBBBBBB", table.unpack(bytes))
runtime:addrFromInt(results.bx):write(buf)
return 0
end
return _ENV
|
local stringx = require "pl.stringx"
local url = require "socket.url"
local utils = require "api-umbrella.proxy.utils"
local append_args = utils.append_args
local startswith = stringx.startswith
local url_build = url.build
local url_parse = url.parse
-- Parse the "cache-lookup" status out of the Via header into a simplified
-- X-Cache HIT/MISS value:
-- https://docs.trafficserver.apache.org/en/7.1.x/appendices/faq.en.html?highlight=asked#how-do-i-interpret-the-via-header-code
--
-- Note: Ideally we could handle this at the TrafficServer lua layer with the
-- simpler ts.http.get_cache_lookup_status(). However, that lookup status isn't
-- always accurate, since certain scenarios trigger cache revalidation without
-- updating the status code (like cache items not used due to authorization
-- headers, or this similar issue using the same underling
-- TSHttpTxnCacheLookupStatusGet:
-- https://issues.apache.org/jira/browse/TS-3432). So instead, we'll continue
-- to handle it here, using nginx's lua layer, instead of TrafficServer's lua
-- layer, since nginx's compiled regexes are probably a bit better optimized.
local function set_cache_header()
local cache = "MISS"
local via = ngx.header["Via"]
if via then
local matches, match_err = ngx.re.match(via, "ApacheTrafficServer \\[.(.)", "jo")
if matches and matches[1] then
local cache_lookup_code = matches[1]
if cache_lookup_code == "H" or cache_lookup_code == "R" then
cache = "HIT"
end
elseif match_err then
ngx.log(ngx.ERR, "regex error: ", match_err)
end
end
-- If the underlying API backend returned it's own X-Cache header, allow that
-- to take precedent, unless we have a cache hit at our layer.
local existing_x_cache = ngx.header["X-Cache"]
if not existing_x_cache or cache == "HIT" then
ngx.header["X-Cache"] = cache
end
end
local function set_default_headers(settings)
if settings["_default_response_headers"] then
local existing_headers = ngx.resp.get_headers()
for _, header in ipairs(settings["_default_response_headers"]) do
if not existing_headers[header["key"]] then
ngx.header[header["key"]] = header["value"]
end
end
end
end
local function set_override_headers(settings)
if settings["_override_response_headers"] then
for _, header in ipairs(settings["_override_response_headers"]) do
ngx.header[header["key"]] = header["value"]
end
end
end
local function rewrite_redirects()
local location = ngx.header["Location"]
if type(location) ~= "string" or location == "" then
return
end
-- If the redirect was forced within the gatekeeper layer by an error handler
-- (and the redirect didn't actually come from the API backend), then no
-- further rewriting is necessary.
if ngx.ctx.gatekeeper_denied_code then
return
end
local parsed, parse_err = url_parse(location)
if not parsed or parse_err then
ngx.log(ngx.ERR, "error parsing Location header: ", location, " error: ", parse_err)
return
end
local matched_api = ngx.ctx.matched_api
local host_matches = (matched_api and parsed["host"] == matched_api["_backend_host_normalized"])
local relative = (not parsed["host"])
local changed = false
if host_matches then
-- For wildcard hosts, keep the same host as on the incoming request. For
-- all others, use the frontend host declared on the API.
local host
if matched_api["frontend_host"] == "*" then
host = ngx.ctx.host_normalized
else
host = matched_api["_frontend_host_normalized"]
end
local scheme = parsed["scheme"]
if scheme == "http" and config["override_public_http_proto"] then
scheme = config["override_public_http_proto"]
elseif scheme == "https" and config["override_public_https_proto"] then
scheme = config["override_public_https_proto"]
end
local port
if scheme == "https" then
port = config["override_public_https_port"] or config["https_port"]
if port == 443 then
port = nil
end
elseif scheme == "http" then
port = config["override_public_http_port"] or config["http_port"]
if port == 80 then
port = nil
end
end
parsed["scheme"] = scheme
parsed["host"] = host
parsed["port"] = port
parsed["authority"] = nil
changed = true
end
-- If the redirect being returned possibly contains paths for the underlying
-- backend URL, then rewrite the path.
if (host_matches or relative) and matched_api then
-- If the redirect path begins with the backend prefix, then consider it
-- for rewriting.
local url_match = ngx.ctx.matched_api_url_match
if url_match and startswith(parsed["path"], url_match["backend_prefix"]) then
-- As long as the patah matches the backend prefix, mark as changed, so
-- the api key is appended (regardless of whether we actually replaced
-- the path).
changed = true
-- Don't rewrite the path if the frontend prefix contains the backend
-- prefix and the redirect path already contains the frontend prefix.
--
-- This helps ensure that if the API backend is already returning
-- public/frontend URLs, we don't try to rewrite these again. -
local rewrite_path = true
if url_match["_frontend_prefix_contains_backend_prefix"] and startswith(parsed["path"], url_match["frontend_prefix"]) then
rewrite_path = false
end
if rewrite_path then
parsed["path"] = ngx.re.sub(parsed["path"], url_match["_backend_prefix_regex"], url_match["frontend_prefix"], "jo")
end
end
end
if changed and ngx.ctx.api_key then
parsed["query"] = append_args(parsed["query"], "api_key=" .. ngx.ctx.api_key)
changed = true
end
if changed then
ngx.header["Location"] = url_build(parsed)
end
end
return function(settings)
set_cache_header()
if settings then
set_default_headers(settings)
set_override_headers(settings)
end
if config["app_env"] == "test" then
if ngx.var.http_x_api_umbrella_test_debug_workers == "true" then
ngx.header["X-Api-Umbrella-Test-Worker-Id"] = ngx.worker.id()
ngx.header["X-Api-Umbrella-Test-Worker-Count"] = ngx.worker.count()
ngx.header["X-Api-Umbrella-Test-Worker-Pid"] = ngx.worker.pid()
end
if ngx.var.http_x_api_umbrella_test_return_request_id == "true" then
ngx.header["X-Api-Umbrella-Test-Request-Id"] = ngx.var.x_api_umbrella_request_id
end
end
rewrite_redirects()
end
|
function num_of_factors(num)
local n = 0
local factor = 1
while factor * factor < num do
if num % factor == 0 then
n = n + 1
end
factor = factor + 1
end
if factor * factor > num then
return n * 2
else
-- perfect square
return n * 2 + 1
end
end
triangle = 0
for i = 1, math.huge do
triangle = triangle + i
if num_of_factors(triangle) > 500 then
print(triangle)
break
end
end
|
function Blink(keys)
local point = keys.target_points[1]
local caster = keys.caster
local casterPos = caster:GetAbsOrigin()
FindClearSpaceForUnit(caster, point, false)
ProjectileManager:ProjectileDodge(caster)
end
|
local att = {}
att.name = "bg_6inchsw29"
att.displayName = "Long Barrel"
att.displayNameShort = "Long"
att.isBG = true
att.statModifiers = {RecoilMult = 0.15,
AimSpreadMult = -0.4,
DrawSpeedMult = -0.2,
OverallMouseSensMult = -0.1,
DamageMult = 0.06}
if CLIENT then
att.displayIcon = surface.GetTextureID("atts/bg_6inchsw29")
end
function att:attachFunc()
self:setBodygroup(self.BarrelBGs.main, self.BarrelBGs.long)
if not self:isAttachmentActive("sights") then
self:updateIronsights("M29Long")
end
end
function att:detachFunc()
self:setBodygroup(self.BarrelBGs.main, self.BarrelBGs.snub)
self:revertToOriginalIronsights()
end
CustomizableWeaponry:registerAttachment(att)
|
local lume = require "lib.lume"
local vector = require "lib.vector"
local input = require "input"
local assets = require "assets"
local atlas = assets.atlas0
local lightbulb = {
filter = function (self, ent)
return ent.type == "LightBulb"
end,
setup = function (self, ent, world)
ent.interactable = true
ent.Color[4] = 0.25
table.insert(world.level.lights, {
x = ent.position.x+(ent.collider.w/2),
y = ent.position.y+(ent.collider.h/2),
area = ent.Area or 30,
color = ent.Color or {1, 1, 1, 1}
})
ent.collider = nil
end,
process = function (self, ent)
ent.destroy = true
end
}
local blank = {
filter = function (self, ent)
return ent.type == "Blank"
end,
setup = function (self, ent)
local w, h = ent.sprite:getDimensions()
if ent.quad then
_, _, w, h = ent.quad:getViewport()
end
ent.shine = ent.Shine or 1
ent.scale = vector(ent.collider.w / w, ent.collider.h / h)
ent.blend = (ent.Blend or "alpha"):lower()
if ent.Tint then
ent.Tint[4] = ent.Alpha or 1
end
ent.collider = nil
end
}
local particle = {
filter = function (self, ent)
return ent.type == "Particle"
end,
setup = function (self, ent)
ent.life = 0
ent.Tint = ent.Tint or {1, 1, 1, 1}
local s = lm.random(50, 100)/100
ent.scale = vector(s, s)
ent.sprite_offset = vector(1, 1)
ent.shine = 0.1
ent.Tint[4] = 0.7
end,
process = function (self, ent, delta)
local l = ent.life/ent.lifespan
local d = math.abs(((l + 0.5) % 1) - 0.5) *2
--ent.Tint[4]
--if ent.sus then
-- print(ent.Tint[4])
--end
--ent.scale = ent.scale:lerp(ent.end_scale, l)
ent.scale.x = d
ent.scale.y = d
ent.destroy = ent.life > ent.lifespan
ent.life = ent.life + delta*4
--ent.rotation = ent.life/10
end
}
local particle_spawner = {
filter = function (self, ent)
return ent.type == "ParticleSpawner"
end,
setup = function(self, ent)
ent.invisible = true
ent.timer = 0
ent.w = ent.collider.w
ent.h = ent.collider.h
ent.collider = nil
end,
process = function (self, ent, delta, world)
if ent.timer > ent.Frequency then
ent.timer = 0
for x=1, ent.Rate do
world:add_entity{
type = "Particle",
lifespan = ent.Lifespan,
sprite = ent.sprite,
quad = ent.quad,
blend = "add",
velocity = vector(
lume.vector(lm.random(0, 10), lm.random(50, 150)/100)
),
Tint = ent.Color,
position = ent.position + vector(
lm.random(ent.w),
lm.random(ent.h)
)
}
end
end
ent.timer = ent.timer + delta
end
}
local speaker = {
filter = function(self, ent)
return ent.type == "Speaker" and
assets.music[ent.Stream] and
ent.position
end,
setup = function(self, ent)
local snd = assets.music[ent.Stream]
ent.current = ent.Share and snd or snd:clone()
ent.current:setVolume(ent.Volume)
ent.current:setLooping(not ent.Stops)
ent.current:play()
ent.collider = nil
end,
process = function(self, ent, _, world)
local x, y = ent.position:unpack()
ent.current:setPosition(x + world.level.x, y + world.level.y)
ent.current:setAttenuationDistances(2, ent.Area)
self.destroy = ent.Stops and not ent.current:isPlaying()
end
}
local door = {
filter = function(self, ent)
return ent.type == "Door" and ent.Door
end,
setup = function(self, ent)
ent.collider = nil
ent.velocity = nil
ent.interactable = true
ent.indicator_offset = vector(4, 0)
end,
process = function(self, ent, delta, world)
if ent.interacting then
world.transition.happening = true
world.transition.callback = function()
local snd = assets[ent.Sound]
if snd then
snd:stop()
snd:setAttenuationDistances(0, math.huge)
snd:setVolume(0.3)
snd:setPosition(0, 0)
snd:play()
end
world.player.checkpoint = ent.Door
world.player.position = vector.copy(ent.Door.position)
world.camera.real = world.player.position:copy()
world:load_level(ent.Door.in_level)
end
end
end
}
local slime = {
filter = function(self, ent)
return ent.type == "Slime"
end,
setup = function(self, ent)
ent.is_enemy = true
ent.scale = vector(1, 1)
ent.sprite_offset = vector(0, 0)
ent.sprite_center = vector(8, 16)
ent.velocity = vector(0, 0)
ent.direction = 1
ent.gravity_acceleration = 0
end,
process = function(self, ent)
local sin = 0.7+((1+math.sin(State.timer*4))/6)
ent.scale.y = sin
ent.sprite_offset.y = (1-sin) * 16
-- The AI for those is the sokamoka equivalent
-- of a goomba. :P
if ent.collider.against_wall then
ent.direction = -ent.direction
end
ent.scale.x = ent.direction
ent.velocity.x = sin * ent.direction * 16
ent.sprite_offset.x = ent.direction < 0 and 16 or 0
end
}
local enemy = {
filter = function(self, ent)
return ent.is_enemy and
vector.is_vector(ent.position)
end,
process = function(self, ent)
end
}
local bullet = {
filter = function(self, ent)
return ent.type == "Bullet"
end,
setup = function(self, ent)
ent.gravity_acceleration = 1
ent.sprite = atlas
if ent.horizontal then
ent.collider = { w = 1, h = 4 }
ent.quad = lg.quad(3*8, 8, 1, 4, atlas:getWidth(), atlas:getHeight())
return
end
ent.collider = { w = 4, h = 1 }
ent.quad = lg.quad(3*8, 8, 4, 1, atlas:getWidth(), atlas:getHeight())
end,
process = function(self, ent)
ent.destroy = ent.detonated
if ent.collider.against_wall or
ent.collider.against_ceil or
ent.collider.against_ground then
ent.detonated = true
end
end
}
local player = {
filter = function (self, ent)
return ent.type == "Player"
end,
ANI_MAIN = {
lg.quad(48, 00, 16, 16, atlas:getWidth(), atlas:getHeight()),
lg.quad(48, 16, 16, 16, atlas:getWidth(), atlas:getHeight()),
lg.quad(48, 32, 16, 16, atlas:getWidth(), atlas:getHeight()),
lg.quad(48, 48, 16, 16, atlas:getWidth(), atlas:getHeight()),
lg.quad(48, 64, 16, 16, atlas:getWidth(), atlas:getHeight())
},
setup = function (self, ent, world)
ent.quad = self.ANI_MAIN[1]
ent.sprite = atlas
ent.acceleration = 64
ent.velocity = vector.zero:copy()
ent.scale = vector.one:copy()
ent.center = vector(8, 16)
ent.gravity_acceleration = 0
ent.collider.w = 8
ent.sprite_offset = vector(-4, 0)
ent.anim_counter = 0
world.player = ent
world.level.has_player = true
ent.is_listener = true
ent.is_player = true
ent.checkpoint = {
position = ent.position,
collider = ent.collider
}
end,
fake_filter = function ()
return "cross"
end,
process = function (self, ent, delta, world)
ent.camera_target = true
local velocity = input.get_direction() * ent.acceleration
if math.abs(velocity.x) > 0 then
ent.acceleration = math.min(ent.acceleration+delta, 128)
if velocity.x>0 then
ent.scale.x = 1
elseif velocity.x<0 then
ent.scale.x = -1
end
if not ent.moving then
ent.anim_counter = 2
end
ent.anim_counter = ent.anim_counter + delta * ent.acceleration * 0.1
ent.moving = true
else
ent.acceleration = 64
ent.anim_counter = 0
ent.moving = false
end
local q = math.floor(ent.anim_counter % 4) +1
ent.quad = self.ANI_MAIN[q]
if ent.collider.against_ground then
ent.velocity.y = 0
end
if input.holding("up") and ent.collider.against_ground then
ent.velocity.y = -86
end
if not ent.collider.against_ground then
if ent.velocity.y > 0 then
ent.quad = self.ANI_MAIN[5]
q = 5
else
ent.quad = self.ANI_MAIN[2]
q = 2
end
if input.just_pressed("up") and not ent.double_jumped then
ent.velocity.y = -86
ent.gravity_acceleration = 0
ent.double_jumped = true
assets.steps:play()
assets.steps:setPosition(
(ent.position + world.level.position + ent.velocity * delta):unpack()
)
end
else
ent.double_jumped = false
end
if ent.collider.against_ceil then
ent.velocity.y = 0
end
ent.velocity.x = lume.lerp(ent.velocity.x, velocity.x, delta*6)
local y_offset = 0
if (q == 2 or q == 4) then
if ent.past_quad ~= q then
assets.steps:play()
assets.steps:setPosition(
(ent.position + world.level.position + ent.velocity * delta):unpack()
)
end
if ent.collider.against_ground then
y_offset = -1
end
end
ent.past_quad = q
ent.sprite_offset.y = lume.lerp(ent.sprite_offset.y, y_offset, delta*22)
--if lc.isDown(1) then
-- local window = vector(lg.getDimensions()) / world.camera.scale / 2
-- local mouse = vector(lc.getX(), lc.getY()) / world.camera.scale
--
-- local center = (ent.past_position or ent.position):lerp(ent.position, State.alpha) + vector(4, 8)
-- mouse = mouse + world.camera.real - window
-- local direction = (mouse - center) * 4
--
-- world:add_entity({
-- type = "Bullet",
-- velocity = direction,
-- position = center,
-- })
--end
local out_of_bounds =
ent.position.x > world.level.width or
ent.position.x < 0 or
ent.position.y > world.level.height or
ent.position.y < 0
if out_of_bounds then
ent.on_transition = true
world.transition.happening = true
world.transition.callback = function ()
local ck = ent.checkpoint
ent.position = ck.position:copy()-- + vector(ck.collider.w / 2, ck.collider.h / 2)
ent.past_position = ent.position:copy()
ent.gravity_acceleration = 0
ent.velocity = vector(0, 0)
ent.acceleration = 64
ent.on_transition = false
world.level.world:move(ent, ent.position.x, ent.position.y, self.fake_filter)
end
end
end
}
local movement = {
filter = function (self, ent)
return vector.is_vector(ent.position) and
vector.is_vector(ent.velocity)
end,
collision_filter = function(a, b)
if (a.on_transition) then
return "cross"
end
if (a.type == "Player" and b.type == "Checkpoint") then
a.checkpoint = b
return "cross"
end
if (b.is_enemy or b.type == "Player" or b.is_bullet) then
return "cross"
end
if b.Trespass and b.position.y < (a.position.y+a.collider.h) then
return "cross"
end
return "slide"
end,
process = function (self, ent, delta, world)
ent.past_position = ent.position
local _position = ent.position + ent.velocity * delta
if ent.collider then
local x, y = world.level.world:move(ent, _position.x, _position.y, self.collision_filter)
local diffx = lume.bsign(x - _position.x)
local diffy = lume.bsign(y - _position.y)
_position.x = x
_position.y = y
ent.collider.against_wall = diffx ~= 0
ent.collider.against_ground = diffy == -1
ent.collider.against_ceil = diffy == 1
end
ent.position = _position
end
}
local listener = {
filter = function (self, ent)
return ent.is_listener and ent.position and ent.past_position
end,
process = function (self, ent, _, world)
local x, y = ent.position:unpack()
la.setPosition(x + world.level.x, y + world.level.y, 0)
la.setVolume(State.MUTED and 0 or 1)
la.setDistanceModel("linearclamped")
--la.setVelocity((ent.position - ent.past_position):unpack())
end
}
local gravity = {
filter = function (self, ent)
return vector.is_vector(ent.velocity)
and ent.gravity_acceleration
and ent.collider
end,
process = function (self, ent, delta)
if ent.collider.against_ground then
ent.gravity_acceleration = 0
end
ent.gravity_acceleration = ent.gravity_acceleration + delta * 30
ent.velocity.y = ent.velocity.y + ent.gravity_acceleration
end
}
local out = {
blank, particle_spawner, particle,
speaker, door, player, lightbulb, bullet,
enemy, slime, gravity, movement, listener
}
return out
|
--[[
################################################################################
#
# Copyright (c) 2014-2019 Ultraschall (http://ultraschall.fm)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
################################################################################
]]
dofile(reaper.GetResourcePath().."/UserPlugins/ultraschall_api.lua")
-- print (reaper.GetResourcePath())
-- Grab all of the functions and classes from our GUI library
-- local info = debug.getinfo(1,'S');
-- script_path = info.source:match[[^@?(.*[\/])[^\/]-$]]
GUI = dofile(reaper.GetResourcePath() .. "/Scripts/ultraschall_gui_lib.lua")
slideshow_path = reaper.GetResourcePath() .. "/Scripts/Ultraschall_Slideshows/"
local info2 = debug.getinfo(1,'S');
slideshow_slug = info2.source:match("^.+/(.+)$")
slideshow_slug = slideshow_slug:sub(0, #slideshow_slug - 4) .. "_"
-- print (slideshow_slug)
---- Window settings and user functions ----
function run_action(commandID)
CommandNumber = reaper.NamedCommandLookup(commandID)
reaper.Main_OnCommand(CommandNumber,0)
end
function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
function build_slideshow_table(slug)
slideshow_table = {}
for i = 1, 10 do
slide_name = slideshow_path .. slug .. tostring(i) .. ".png"
if file_exists(slide_name) then
table.insert(slideshow_table, slide_name)
-- print (slide_name)
else
return slideshow_table
end
end
end
GUI.name = "Ultraschall Welcome Slideshow"
GUI.w, GUI.h = 800, 665
------------------------------------------------------
-- position always in the center of the screen
------------------------------------------------------
l, t, r, b = 0, 0, GUI.w, GUI.h
__, __, screen_w, screen_h = reaper.my_getViewport(l, t, r, b, l, t, r, b, 1)
GUI.x, GUI.y = (screen_w - GUI.w) / 2, (screen_h - GUI.h) / 2
------------------------------------------------------
-- Aufbau der nicht interkativen GUI-Elemente wie Logos etc.
------------------------------------------------------
function buildGui(slide_number)
if slide_number == nil then slide_number = 1 end
GUI.elms = {}
-- name = element type x y w h zoom caption ...other params...
local picture_path = slideshow_table[slide_number]
picture = GUI.Pic:new( 0, 0, 0, 0, 1, picture_path)
table.insert(GUI.elms, picture)
-----------------------------------------------------------------
-- Zurück-Button
-----------------------------------------------------------------
if slide_number ~= 1 then
previous_slide_number = slide_number -1
button_settings = GUI.Btn:new(20, 630, 85, 20, " Back...", buildGui, previous_slide_number)
table.insert(GUI.elms, button_settings)
end
-----------------------------------------------------------------
-- Weiter-Button
-----------------------------------------------------------------
if slide_number ~= #slideshow_table then
next_slide_number = slide_number +1
button_settings = GUI.Btn:new(700, 630, 85, 20, " Next...", buildGui, next_slide_number)
table.insert(GUI.elms, button_settings)
end
end
slideshow_table = build_slideshow_table(slideshow_slug)
GUI.func = buildGui() -- Dauerschleife
GUI.freq = 1 -- Aufruf jede Sekunde
if reaper.GetExtState("Ultraschall_Windows", GUI.name) == "" then windowcounter=0 -- Check if window was ever opened yet(and external state for it exists already). yes, use temporarily 0 as opened windows-counter;will be changed by ultraschall_gui_lib.lua later
else windowcounter=tonumber(reaper.GetExtState("Ultraschall_Windows", GUI.name)) end -- get number of opened windows
-- print (slideshow_table[1])
if windowcounter<1 then -- you can choose how many GUI.name-windows are allowed to be opened at the same time.
-- 1 means 1 window, 2 means 2 windows, 3 means 3 etc
GUI.Init()
GUI.Main()
end
function atexit()
reaper.SetExtState("Ultraschall_Windows", GUI.name, 0, false)
end
reaper.atexit(atexit)
|
--[[
Copyright (C) 2017-2018 ZTE, Inc. and others. All rights reserved. (ZTE)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local _M = {}
_M._VERSION = '1.0.0'
local pl_stringx = require "pl.stringx"
local split = pl_stringx.split
local strip = pl_stringx.strip
function _M.mark_empty_as_nil(t)
if t == "" then
return nil
else
return t
end
end
--- splits a string.
-- just a placeholder to the penlight `pl.stringx.split` function
-- @function split
_M.split = split
--- strips whitespace from a string.
-- just a placeholder to the penlight `pl.stringx.strip` function
-- @function strip
_M.strip = strip
return _M
|
function passive(spell, target, caster, turns, statustype)
if target[statustype][spell.name] then
target[statustype][spell.name].turns = target[statustype][spell.name].turns + (turns-1)
return
end
target[statustype][spell.name] = turns
if not spell.blurb then spell.blurb = "" end
table.insert(state.battle.turns, {{target=target.name, caster=caster.name, status=spell.name, blurb=target.name..spell.blurb}})
end
function battlepassives()
repeat
for _, spell in pairs(state.battle.participants[state.battle.open].persona.spellDeck) do
if spell ~= "" then
lspell = require("data/spells/"..spell)
if lspell.passive then
lspell.activate()
end
end
end
state.battle.open = state.battle.open + 1
until
state.battle.open > #state.battle.participants
state.battle.open = 1
state.battle.turns = {}
end
function countdownpassives()
countablepassives = {"attackstatus", "defendstatus", "dodgestatus", "turnstatus"}
for _, passivetype in pairs(countablepassives) do
for statname, turnsleft in pairs(state.battle.participants[state.battle.open][passivetype]) do
if turnsleft then
if turnsleft-1 < 0 then
state.battle.participants[state.battle.open][passivetype][statname] = nil
if passivetype == "turnstatus" then state.battle.participants[state.battle.open].status = nil end
else state.battle.participants[state.battle.open][passivetype][statname] = turnsleft-1 end
end
end
end
for spellname, _ in pairs(state.battle.participants[state.battle.open]["turnstatus"]) do
spell = require("data/spells/"..spellname)
if spell.process then spell.process() end
end
end
|
local format = require("cmp_git.format")
local sort = require("cmp_git.sort")
require("cmp_git").setup({
-- defaults
filetypes = { "gitcommit", "octo" },
remotes = { "upstream", "origin" }, -- in order of most to least prioritized
enableRemoteUrlRewrites = false, -- enable git url rewrites, see https://git-scm.com/docs/git-config#Documentation/git-config.txt-urlltbasegtinsteadOf
git = {
commits = {
limit = 100,
sort_by = sort.git.commits,
format = format.git.commits,
},
},
github = {
issues = {
fields = { "title", "number", "body", "updatedAt", "state" },
filter = "all", -- assigned, created, mentioned, subscribed, all, repos
limit = 100,
state = "open", -- open, closed, all
sort_by = sort.github.issues,
format = format.github.issues,
},
mentions = {
limit = 100,
sort_by = sort.github.mentions,
format = format.github.mentions,
},
pull_requests = {
fields = { "title", "number", "body", "updatedAt", "state" },
limit = 100,
state = "open", -- open, closed, merged, all
sort_by = sort.github.pull_requests,
format = format.github.pull_requests,
},
},
gitlab = {
issues = {
limit = 100,
state = "opened", -- opened, closed, all
sort_by = sort.gitlab.issues,
format = format.gitlab.issues,
},
mentions = {
limit = 100,
sort_by = sort.gitlab.mentions,
format = format.gitlab.mentions,
},
merge_requests = {
limit = 100,
state = "opened", -- opened, closed, locked, merged
sort_by = sort.gitlab.merge_requests,
format = format.gitlab.merge_requests,
},
},
trigger_actions = {
{
debug_name = "git_commits",
trigger_character = ":",
action = function(sources, trigger_char, callback, params, git_info)
return sources.git:get_commits(callback, params, trigger_char)
end,
},
{
debug_name = "gitlab_issues",
trigger_character = "#",
action = function(sources, trigger_char, callback, params, git_info)
return sources.gitlab:get_issues(callback, git_info, trigger_char)
end,
},
{
debug_name = "gitlab_mentions",
trigger_character = "@",
action = function(sources, trigger_char, callback, params, git_info)
return sources.gitlab:get_mentions(callback, git_info, trigger_char)
end,
},
{
debug_name = "gitlab_mrs",
trigger_character = "!",
action = function(sources, trigger_char, callback, params, git_info)
return sources.gitlab:get_merge_requests(callback, git_info, trigger_char)
end,
},
{
debug_name = "github_issues_and_pr",
trigger_character = "#",
action = function(sources, trigger_char, callback, params, git_info)
return sources.github:get_issues_and_prs(callback, git_info, trigger_char)
end,
},
{
debug_name = "github_mentions",
trigger_character = "@",
action = function(sources, trigger_char, callback, params, git_info)
return sources.github:get_mentions(callback, git_info, trigger_char)
end,
},
},
})
|
local status_ok, gitsigns = pcall(require, 'gitsigns')
if not status_ok then
return
end
gitsigns.setup {
current_line_blame = true,
signs = {
add = { hl = 'GitSignsAdd', text = '▌' },
change = { hl = 'GitSignsChange', text = '▌' },
delete = { hl = 'GitSignsDelete', text = '▌' },
topdelete = { hl = 'GitSignsDelete', text = '▌' },
changedelete = { hl = 'GitSignsChange', text = '▌' },
},
on_attach = function(bufnr)
vim.keymap.set('n', '[c', gitsigns.prev_hunk, { buffer = bufnr })
vim.keymap.set('n', ']c', gitsigns.next_hunk, { buffer = bufnr })
vim.keymap.set('n', '<leader>hp', gitsigns.preview_hunk, { buffer = bufnr })
vim.keymap.set('n', '<leader>hr', gitsigns.reset_hunk, { buffer = bufnr })
end,
}
|
AmiUI = {
log = function(self, text)
cecho("AmiUI: " .. text .. "\n")
end
}
AUITriggers = AUITriggers or {}
AmiUI:log("Initializing AmiUI...")
tempTimer( 0, function () raiseEvent( "AmiUI.Loaded" ) end )
|
Network = class('Network')
-- initialize some basic values
function Network:initialize()
--self.ip = '73.130.6.29'
self.ip = 'localhost'
self.port = '22122'
-- used as the divider between tag and message in networked data communication
self.magicChar = '|'
self.lastEvent = nil
self.peer = nil
end
-- create a host to the ip and port
function Network:connect()
self.host = enet.host_create()
self.host:connect(self.ip .. ':' .. self.port)
-- activates data compression, may take more processing time
--self.host:compress_with_range_coder()
end
function Network:checkForData()
-- check some events, 100ms timeout
local event = self.host:service(0)
if event then
--event.peer:ping_interval(1000)
self.lastEvent = event
self.peer = event.peer
if event.type == 'connect' then
self.state = 'run'
self.timer = 0
signal.emit('connect')
elseif event.type == 'receive' then
local str = event.data
local location = string.find(str, self.magicChar)
if not location then -- invalid data was sent
else
--[[
The event.data (message sent through networking) is spliced into the tag and message
For example, if the event.data is "chat|Hello ikroth", the tag will be "chat" and the message will be "Hello ikroth"
A signal is emitted with the tag name ("chat"), and it is emitted with the message ("Hello ikroth")
]]
local dataType = string.sub(str, 1, location - 1)
local message = string.sub(str, location + 1)
-- insert code to de-serialize the message if it is a table
signal.emit(dataType, peerIndex, message)
end
elseif event.type == 'disconnect' then
signal.emit('disconnect')
end
end
end
function Network:sendMessage(dataType, message)
local str = dataType .. self.magicChar .. message
if self.peer then
self.peer:send(str)
end
end
-- send coordinates to the server
function Network:sendCoordinates(dataType, x, y)
local str = dataType .. self.magicChar .. x .. ' ' .. y
if self.peer then
self.peer:send(str)
end
end
-- accepts any number of arguments. it should all be numbers or strings
function Network:sendValues(dataType, ...)
local str = '' -- start with an empty string
-- add an element to the string
for i, v in ipairs({...}) do
if i > 1 then -- add a space before it if not the first variable
str = str .. ' '
end
str = str .. v
end
self:sendDataToAll(dataType, str)
end
function Network:sendDataToAll(dataType, inputStr) -- inputStr should NOT already include the tag
local str = self:assembleString(dataType, inputStr)
self.host:broadcast(str)
end
function Network:assembleString(dataType, str)
return dataType .. self.magicChar .. str
end
-- works with any number of values
function Network:convertDataString(dataStr)
-- looks for the space character
local location = string.find(dataStr, ' ')
if not location then -- only one element left
return dataStr
else
-- just make this into a function
local first = string.sub(dataStr, 1, location - 1)
local second = string.sub(dataStr, location + 1)
return first, self:convertDataString(second)
end
end
function Network:drawInformation()
local x, y = 0, 0
local h = 40
local i = 0
love.graphics.print('Total sent data: ' .. self.host:total_sent_data() .. ' bytes', x, y + i*h)
i = i + 1
love.graphics.print('Total received data: ' .. self.host:total_received_data() .. ' bytes', x, y + i*h)
i = i + 1
love.graphics.print('Service time: ' .. self.host:service_time(), x, y + i*h)
i = i + 1
love.graphics.print('Max peers: ' .. self.host:peer_count(), x, y + i*h)
i = i + 1
love.graphics.print('Socket address ' .. self.host:get_socket_address(), x, y + i*h)
i = i + 1
if self.peer then
love.graphics.print('Peer index: ' .. self.peer:index(), x, y + i*h)
i = i + 1
end
end
|
RegisterServerEvent("pixel:watermark")
AddEventHandler("pixel:watermark", function() TriggerClientEvent("pixel", source, GetPlayers())
end)
Citizen.CreateThread(function()
Citizen.Wait(5000)
print(
"^0============================================================================================^7\n" ..
"^0[^4PxP Resources^0]^7 :^0 ^0Thanks For Downloading PxP-Watermark-v1^7\n" ..
"^0[^4Support^0]^7 :^0 ^0Full Support In Our Discord! - discord.gg/e3S4Svrewg^7\n" ..
"^0[^4ToS^0]^7 :^0 ^0You Don't Have The Rights To Reupload Whiteout Linking The Normal Resource!^7\n" ..
"^0[^4PxP^0]^7 :^0 ^0Resource By PxPScripts^7\n" ..
"^0============================================================================================^7"
)
end)
|
include('qword.lua');
include("addresses.lua");
include("database.lua");
include("functions.lua");
include("classes/player.lua");
include("classes/equipment.lua");
include("classes/inventory.lua");
include("classes/bank.lua");
include("classes/guildbank.lua");
include("classes/cursor.lua");
include("classes/camera.lua");
include("classes/waypoint.lua");
include("classes/waypointlist.lua");
include("classes/waypointlist_wander.lua");
include("classes/node.lua");
include("classes/object.lua");
include("classes/objectlist.lua");
include("classes/eggpet.lua");
include("classes/store.lua");
include("classes/party.lua");
include("classes/itemtypes.lua");
include("classes/pet.lua");
include("classes/memdatabase.lua");
include("classes/codemod.lua");
include("settings.lua");
include("macros.lua");
function printHeader(name, padchar)
local width = 79;
local padchar = padchar or '=';
local midpoint = math.ceil((width + #name)/2);
local left = width - midpoint;
local right = width - #name - left;
print(string.rep(padchar, left) .. name .. string.rep(padchar, right));
end
function printLine(headWidth, header, ...)
header = sprintf("%" .. headWidth .. "s", header)
print(header, ...);
end
function getClassName(classId)
if( classId == nil ) then
return "Nil";
end
if( classId == CLASS_NONE ) then
return "none";
elseif( classId == CLASS_GM ) then
return "GM";
elseif( classId == CLASS_WARRIOR ) then
return "Warrior";
elseif( classId == CLASS_SCOUT ) then
return "Scout"
elseif( classId == CLASS_ROGUE ) then
return "Rogue";
elseif( classId == CLASS_MAGE ) then
return "Mage";
elseif( classId == CLASS_PRIEST ) then
return "Priest"
elseif( classId == CLASS_KNIGHT ) then
return "Knight";
elseif( classId == CLASS_WARDEN ) then
return "Warden";
elseif( classId == CLASS_DRUID ) then
return "Druid";
elseif( classId == CLASS_WARLOCK ) then
return "Warlock";
elseif( classId == CLASS_CHAMPION ) then
return "Champion";
else
return "Unknown class " .. classId;
end
end
function getEquipSlotName(slotId)
if( slotId == 0 ) then
return "Head";
elseif( slotId == 1 ) then
return "Hands";
elseif( slotId == 2 ) then
return "Feet";
elseif( slotId == 3 ) then
return "Upper body";
elseif( slotId == 4 ) then
return "Lower body";
elseif( slotId == 5 ) then
return "Cape";
elseif( slotId == 6 ) then
return "Belt";
elseif( slotId == 7 ) then
return "Shoulders";
elseif( slotId == 8 ) then
return "Necklace";
elseif( slotId == 9 ) then
return "Ammo";
elseif( slotId == 10 ) then
return "Ranged weapon";
elseif( slotId == 11 ) then
return "Ring 1";
elseif( slotId == 12 ) then
return "Ring 2";
elseif( slotId == 13 ) then
return "Earring 1";
elseif( slotId == 14 ) then
return "earring 2";
elseif( slotId == 15 ) then
return "Main hand";
elseif( slotId == 16 ) then
return "Offhand";
elseif( slotId == 17 ) then
return "Gathering tool";
elseif( slotId == 18 ) then
return "Amulet 1";
elseif( slotId == 19 ) then
return "Amulet 2";
elseif( slotId == 20 ) then
return "Amulet 3";
elseif( slotId == 21 ) then
return "Back/wings";
else
return "Unknown slot " .. (slotId or 'nil');
end
end
printHeader("Player Info");
local colWidth = 20;
player = CPlayer.new();
printLine(colWidth, "Name:", player.Name);
printLine(colWidth, "Class 1:", getClassName(player.Class1) .. " lvl " .. player.Level);
printLine(colWidth, "Class 2:", getClassName(player.Class2) .. " lvl " .. player.Level2);
printLine(colWidth, "HP:", player.HP .. "/" .. player.MaxHP);
printLine(colWidth, "MP:", player.MP .. "/" .. player.MaxMP);
printLine(colWidth, "MP2:", player.MP2 .. "/" .. player.MaxMP2);
print("");
printHeader("Craft Levels");
local colWidth = 20;
printLine(colWidth, "Blacksmithing:", player:getCraftLevel(CRAFT_BLACKSMITHING));
printLine(colWidth, "Carpentry:", player:getCraftLevel(CRAFT_CARPENTRY));
printLine(colWidth, "Armorcrafting:", player:getCraftLevel(CRAFT_ARMORCRAFTING));
printLine(colWidth, "Tailoring:", player:getCraftLevel(CRAFT_TAILORING));
printLine(colWidth, "Cooking:", player:getCraftLevel(CRAFT_COOKING));
printLine(colWidth, "Alchemy:", player:getCraftLevel(CRAFT_ALCHEMY));
printLine(colWidth, "Mining:", player:getCraftLevel(CRAFT_MINING));
printLine(colWidth, "Woodcutting:", player:getCraftLevel(CRAFT_WOODCUTTING));
printLine(colWidth, "Herbalism:", player:getCraftLevel(CRAFT_HERBALISM));
print("");
printHeader("Game/Loading Check");
printLine(colWidth, "In-Game:", isInGame())
printLine(colWidth, "Loading:", isLoading())
print("")
printHeader("Casting")
CPawn.updateCasting(player)
printLine(colWidth, "Casting (Pawn):", player.Casting);
player:updateCasting()
printLine(colWidth, "Casting (Player):", player.Casting);
printLine(colWidth, "Harvesting:", player.Harvesting);
printLine(colWidth, "Collecting Type", player:getCollectingType());
print("")
printHeader("Equipment Info");
equipment = CEquipment();
for i = 0,#equipment.BagSlot do
local item = equipment.BagSlot[i];
printLine(colWidth, getEquipSlotName(i), sprintf("ID: %6d\tName: %s", item.Id, item.Name));
end
print("");
printHeader("Memdatabase");
attackId = 540000
attackAddress = GetItemAddress(attackId)
printLine(colWidth, "Attack skill address:", sprintf("0x%X", attackAddress or 0));
if( attackAddress ~= nil and attackAddress > 0 ) then
skill = CItem()
skill.Address = attackAddress
skill:update()
printLine(colWidth, "Skill ID:", skill.Id, "Expecting " .. attackId);
printLine(colWidth, "Skill Name:", skill.Name);
end
print("");
printHeader("Texts");
local expectations = {
['AC_INSTRUCTION_01'] = 'AC command (Zone 81)',
['AC_INSTRUCTION_02'] = 'Set season',
['ZONE955_JOLIN_S1'] = 'Only I can sing on my stage!'
}
for i,key in pairs({'AC_INSTRUCTION_01', 'AC_INSTRUCTION_02', 'ZONE955_JOLIN_S1'}) do
printLine(colWidth, key, sprintf("%-25s", getTEXT(key)), sprintf("%-25s", expectations[key]));
end
print("\nLoading data for additional testing...");
attach(getWin(player.Name));
include("/language/english.lua")
database.load();
settings.loadProfile("Default")
inventory = CInventory();
inventory:update()
print("\n")
printHeader("Inventory");
print("")
printHeader("Item Shop Backpack", ' ');
found = 0
for i = 0,49 do
v = inventory.BagSlot[i]
if( v and not v.Empty ) then
printLine(colWidth, i, sprintf("ID: %-8d Count: %-5d %s", v.Id or 0, v.ItemCount or 0, v.Name));
found = found + 1
end
end
if( found == 0 ) then
print("No items were found in this inventory")
end
print("\n")
printHeader("Backpack(s)", ' ');
found = 0;
local foundItem = nil;
for i = 60,239 do
v = inventory.BagSlot[i]
if( v and not v.Empty ) then
if( foundItem == nil and v.Id == 200663) then
-- We'll dump more details on this item later
foundItem = v;
end
printLine(colWidth, i, sprintf("ID: %-8d Bound: %d Count: %-5d %s", v.Id or 0, v.Bound and 1 or 0, v.ItemCount or 0, v.Name or ""));
found = found + 1
end
end
if( found == 0 ) then
print("No items were found in this inventory")
end
print("\n")
printHeader("Bank", ' ');
bank = CBank()
found = 0
for i,v in pairs(bank.BagSlot) do
if( v and not v.Empty ) then
printLine(colWidth, i, sprintf("ID: %-8d Count: %-5d %s", v.Id or 0, v.ItemCount or 0, v.Name));
found = found + 1
end
end
if( found == 0 ) then
print("No items were found in the bank")
end
if( foundItem ) then
print("\n")
printHeader("Item details", ' ');
printLine(colWidth, 'Address', sprintf("0x%X", foundItem.Address));
printLine(colWidth, 'ID', foundItem.Id);
printLine(colWidth, 'Name', foundItem.Name);
printLine(colWidth, 'Empty', foundItem.Empty);
printLine(colWidth, 'Location', foundItem.Location);
printLine(colWidth, 'SlotNumber', foundItem.SlotNumber);
printLine(colWidth, 'BagId', foundItem.BagId);
printLine(colWidth, 'Available', foundItem.Available);
printLine(colWidth, 'Quality', foundItem.Quality);
printLine(colWidth, 'Color', sprintf("0x%X", foundItem.Color));
printLine(colWidth, 'BoundStatus', foundItem.BoundStatus);
printLine(colWidth, 'Bound', foundItem.Bound);
printLine(colWidth, 'InUse', foundItem.InUse);
printLine(colWidth, 'CoolDownTime', foundItem.CoolDownTime);
printLine(colWidth, 'ItemCount', foundItem.ItemCount);
printLine(colWidth, 'RequiredLvl', foundItem.RequiredLvl);
end
print("")
printHeader("Object List");
local olist = CObjectList();
olist:update()
local displayCount = math.min(10, #olist.Objects)
printLine(colWidth, "Objects found:", #olist.Objects);
printLine(colWidth, sprintf("Top %d items", displayCount));
for i = 1, displayCount do
v = olist.Objects[i];
local lootable = memoryReadRepeat("byte", getProc(), v.Address + addresses.game_root.pawn.lootable_flags) or -1;
printLine(colWidth, i, sprintf("ID: %-8d Address: 0x%08x Type: %d Name: %s, Lootable: %d", v.Id or 0, v.Address or 0, v.Type or -1, v.Name or "", lootable));
end
print("")
printHeader("Cursor Item");
local cursor = CCursor();
cursor:update()
printLine(colWidth, "Cursor item ID:", cursor.ItemId or '<invalid>');
printLine(colWidth, "Cursor item Bag ID:", cursor.ItemBagId or '<invalid>');
print("")
printHeader("Mount test");
local mount, mountMethod = player:getMount();
if( mount ~= nil ) then
print("Mounting...");
player:mount()
local start = os.time();
repeat
yrest(500);
player:updateCasting()
if( os.time() - start > 5 ) then
player.Casting = false;
print("Took too long.")
end
until player.Casting == false
print("Dismounting...");
player:mount(true)
else
print("Could not find mount for player; skipping mount test.")
end
print("");
printHeader("Skills", ' ');
settings.loadSkillSet(player.Class1)
getResourceName = function (skill)
if skill.Mana > 0 then
return "Mana";
end
if skill.Rage > 0 then
return "Rage";
end
if skill.Energy > 0 then
return "Energy";
end
if skill.Focus > 0 then
return "Focus";
end
if skill.Nature > 0 then
return "Nature";
end
if skill.Psi > 0 then
return "Psi";
end
end
print("\n")
printf(" %-8s %-26s %-6s %-4s %-12s %-10s\n", "ID", "Name", "Level", "As", "Resource", "Hotkey");
for i,v in pairs(settings.profile.skills) do
local resource = getResourceName(v)
local amount = v[resource] or 0
local resourceDesc = '---';
if resource then
resourceDesc = sprintf("%d %s", amount, resource or '--')
end
printf(" %-8d %-26s %-6d %-4d %-12s %-10s\n", v.Id, v.Name, v.Level, v.aslevel, resourceDesc, v.hotkey);
end
print("")
printHeader("Code Mods");
printHeader("Check Code In Memory", ' ');
local installableCodemods = {}
for i,v in pairs(addresses.code_mod) do
local codemod = CCodeMod(v.base,
v.original_code,
v.replace_code
);
if( codemod:checkModified() == false ) then
cprintf_ex("%s|green|[+]|white| %s looks good\n", string.rep(" ", 12), i);
installableCodemods[i] = codemod;
else
cprintf_ex("%s|red|[x]|white| %s appears malformed/modified\n", string.rep(" ", 12), i);
end
end
print("");
printHeader("Test if installable", ' ');
for i,codemod in pairs(installableCodemods) do
local success = codemod:safeInstall();
if( success ) then
yrest(1000);
success = codemod:safeUninstall();
yrest(200);
end
if( success ) then
cprintf_ex("%s|green|[+]|white| %s OK!\n", string.rep(" ", 12), i);
else
cprintf_ex("%s|red|[x]|white| Failed\n", string.rep(" ", 12), i);
end
end
|
local ChangeLog = require('ui.changelog')
ChangeLog:create(1, 0, 0):normal(L['First version'])
ChangeLog:create(2, 0, 0):normal(L['Second version'])
ChangeLog:update()
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local Resources = require(ReplicatedStorage:WaitForChild("Resources"))
local Registerable = require(script.Registerable)
local AuraAgent = require(script.AuraAgent)
local SyncEvent = Resources:GetRemoteEvent(".Aurora")
local SyncFunction = Resources:GetRemoteFunction(".Aurora")
local IsServer = RunService:IsServer()
local IsReady = false
-- Library
local Aurora = {
Auras = Registerable.new("Auras");
Effects = Registerable.new("Effects");
TickRate = 0.5;
SafeMemoryMode = true;
MaxAgentTimeInactive = math.huge;
SyncActionIndex = -1;
InitialSyncCompleted = IsServer;
}
local Agents = setmetatable({}, {
__mode = "k";
__index = function(self, instance)
local agent = AuraAgent.new(instance, Aurora.Auras, Aurora.Effects, IsServer and Aurora.SyncAction)
self[instance] = agent
return agent
end
})
function Aurora.GetAgent(instance)
local agent = Agents[instance]
if not agent.Destroyed then
return agent
else
Agents[instance] = nil
return Agents[instance]
end
end
local function warnIfTooLate()
if IsReady then
warn(
"[Aurora] You are registering Auras/Effects too late. Please do not yield between your first require of Aurora"
.. " and your register calls."
)
end
end
function Aurora.RegisterAurasIn(object)
warnIfTooLate()
Aurora.Auras:LookIn(object)
end
function Aurora.RegisterEffectsIn(object)
warnIfTooLate()
Aurora.Effects:LookIn(object)
end
function Aurora.SetTickRate(seconds)
Aurora.TickRate = seconds
end
function Aurora.SetSafeMemoryMode(mode)
Aurora.SafeMemoryMode = mode
end
function Aurora.SetMaxAgentTimeInactive(seconds)
Aurora.MaxAgentTimeInactive = seconds
end
function Aurora.SyncAction(agent, method, ...)
Aurora.SyncActionIndex = Aurora.SyncActionIndex + 1
SyncEvent:FireAllClients({
Type = "SyncAction";
ActionIndex = Aurora.SyncActionIndex;
Payload = {
Instance = agent.Instance;
Method = method;
Args = {...}
}
})
end
--- Creates a snapshot of every agent's auras as they are in this moment
-- to be sent to a newly connected client (agents with no auras are excluded)
function Aurora.Serialize(filter)
local snapshot = {}
for instance, agent in pairs(Agents) do
if agent.Destroyed then
Agents[instance] = nil
elseif agent.TimeInactive <= 0 then
local agentSerialize = agent:Serialize(filter)
snapshot[#snapshot + 1] = {
Instance = instance;
Auras = agentSerialize;
}
end
end
return snapshot
end
-- Register auras
Aurora.RegisterAurasIn(script.BuiltInAuras)
Aurora.RegisterEffectsIn(script.BuiltInEffects)
-- Event connections
if IsServer then
local lastRequest = {}
SyncFunction.OnServerInvoke = function (player)
-- rate limit
if lastRequest[player] and tick() - lastRequest[player] < 60 then
return nil
end
lastRequest[player] = tick()
return Aurora.Serialize(function(aura)
return aura.Status.Replicated == true
end)
end
game:GetService("Players").PlayerRemoving:Connect(function(player)
lastRequest[player] = nil
end)
end
-- Update loop
spawn(function()
-- We delay setting up network stuff until after a cycle, to let the developer
-- register their Auras
if not IsServer then
require(script.ClientNetwork)(Aurora)
end
IsReady = true
while true do
local dt = wait(Aurora.TickRate)
for instance, agent in pairs(Agents) do
if
agent.TimeInactive > Aurora.MaxAgentTimeInactive
or (
Aurora.SafeMemoryMode == true
and not agent.Destroyed
and instance:IsDescendantOf(game) == false
)
then
-- dump agents referring to instances that are not parented to the game tree
agent:Destroy()
Agents[instance] = nil
elseif agent.Destroyed then
-- agent was destroyed externally
Agents[instance] = nil
else
agent:Update(dt)
end
end
end
end)
return Aurora
|
Description="Add doc.qt.io reference links to HTML, LaTeX, RTF and ODT output of C++ code"
-- optional parameter: syntax description
function syntaxUpdate(desc)
if desc~="C and C++" then
return
end
function getURL(token)
url='http://doc.qt.io/qt-5/'..string.lower(token).. '.html'
if (HL_OUTPUT== HL_FORMAT_HTML or HL_OUTPUT == HL_FORMAT_XHTML) then
return '<a class="hl" target="new" href="' .. url .. '">'.. token .. '</a>'
elseif (HL_OUTPUT == HL_FORMAT_LATEX) then
return '\\href{'..url..'}{'..token..'}'
elseif (HL_OUTPUT == HL_FORMAT_RTF) then
return '{{\\field{\\*\\fldinst HYPERLINK "'..url..'" }{\\fldrslt\\ul\\ulc0 '..token..'}}}'
elseif (HL_OUTPUT == HL_FORMAT_ODT) then
return '<text:a xlink:type="simple" xlink:href="'..url..'">'..token..'</text:a>'
end
end
function Decorate(token, state)
if (state ~= HL_STANDARD and state ~= HL_KEYWORD and state ~=HL_PREPROC) then
return
end
if string.find(token, "Q%u%l")==1 then
return getURL(token)
end
end
end
function themeUpdate(desc)
if (HL_OUTPUT == HL_FORMAT_HTML or HL_OUTPUT == HL_FORMAT_XHTML) then
Injections[#Injections+1]="a.hl, a.hl:visited {color:inherit;font-weight:inherit;}"
elseif (HL_OUTPUT==HL_FORMAT_LATEX) then
Injections[#Injections+1]="\\usepackage[colorlinks=false, pdfborderstyle={/S/U/W 1}]{hyperref}"
end
end
Plugins={
{ Type="lang", Chunk=syntaxUpdate },
{ Type="theme", Chunk=themeUpdate },
}
|
--[[
Bags for Minetest
Copyright (c) 2012 cornernote, Brett O'Donnell <cornernote@gmail.com>
Source Code: https://github.com/cornernote/minetest-particles
License: GPLv3
]]--
-- get_formspec
local get_formspec = function(player,page)
if page=="bags" then
local player_inv = player:get_inventory()
player_inv:set_size("b", 1)
local type = player:get_inventory():get_stack("b",1):get_name()
if type == "tutorial:bag_schluessel1" then
ba5 = "bag5"
ba6 = "bags"
ba7 = "bags"
ba8 = "bags"
elseif type == "tutorial:bag_schluessel2" then
ba5 = "bag5"
ba6 = "bag6"
ba7 = "bags"
ba8 = "bags"
elseif type == "tutorial:bag_schluessel3" then
ba5 = "bag5"
ba6 = "bag6"
ba7 = "bag7"
ba8 = "bags"
elseif type == "tutorial:bag_schluessel4" then
ba5 = "bag5"
ba6 = "bag6"
ba7 = "bag7"
ba8 = "bag8"
else
ba5 = "bags"
ba6 = "bags"
ba7 = "bags"
ba8 = "bags"
end
return "size[10.5,10.3]"
.."list[current_player;main;1.25,6.25;8,1;]"
.."list[current_player;main;1.25,7.5;8,3;8]"
.."background[10.5,10.3;1,1;gui_formbg.png;true]"
.."listcolors[#00000069;#5A5A5A;#141318;#30434C;#FFF]"
.."bgcolor[#080808BB;true]"
.."button[0,0;2,0.5;inven;Back]"
.."button[2,0;2,0.5;main;Main]"
.."button[2,2;2,0.5;bag1;Bag 1]"
.."button[4,2;2,0.5;bag2;Bag 2]"
.."button[6,2;2,0.5;bag3;Bag 3]"
.."button[8,2;2,0.5;bag4;Bag 4]"
.."button[2,5;2,0.5;"..ba5..";Bag 5]"
.."button[4,5;2,0.5;"..ba6..";Bag 6]"
.."button[6,5;2,0.5;"..ba7..";Bag 7]"
.."button[8,5;2,0.5;"..ba8..";Bag 8]"
.."list[detached:"..player:get_player_name().."_bags;bag1;2.5,1;1,1;]"
.."list[detached:"..player:get_player_name().."_bags;bag2;4.5,1;1,1;]"
.."list[detached:"..player:get_player_name().."_bags;bag3;6.5,1;1,1;]"
.."list[detached:"..player:get_player_name().."_bags;bag4;8.5,1;1,1;]"
.."list[detached:"..player:get_player_name().."_bags;bag5;2.5,4;1,1;]"
.."list[detached:"..player:get_player_name().."_bags;bag6;4.5,4;1,1;]"
.."list[detached:"..player:get_player_name().."_bags;bag7;6.5,4;1,1;]"
.."list[detached:"..player:get_player_name().."_bags;bag8;8.5,4;1,1;]"
.."list[current_player;b;0.5,4;1,1;]"
.."label[0.5,4.8;Bagkey]"
end
for i=1,8 do
if page=="bag"..i then
local image = player:get_inventory():get_stack("bag"..i, 1):get_definition().inventory_image
return "size[8,11.5]"
.."background[8,11.5;1,1;gui_formbg.png;true]"
.."listcolors[#00000069;#5A5A5A;#141318;#30434C;#FFF]"
.."bgcolor[#080808BB;true]"
.."list[current_player;main;0,7.5;8,1;]"
.."list[current_player;main;0,8.75;8,3;8]"
.."button[0,0;2,0.75;bags;Back]"
.."button[2,0;2,0.75;main;Main]"
.."image[7,0;1,1;"..image.."]"
.."list[current_player;bag"..i.."contents;0,1;8,8;]"
.."listring[current_player;bag"..i.."contents]"
.."listring[current_player;main]"
end
end
end
-- register_on_player_receive_fields
minetest.register_on_player_receive_fields(function(player, formname, fields)
if fields.bags then
inventory_plus.set_inventory_formspec(player, get_formspec(player,"bags"))
return
end
for i=1,8 do
local page = "bag"..i
if fields[page] then
if player:get_inventory():get_stack(page, 1):get_definition().groups.bagslots==nil then
page = "bags"
end
inventory_plus.set_inventory_formspec(player, get_formspec(player,page))
return
end
end
end)
-- register_on_joinplayer
minetest.register_on_joinplayer(function(player)
local player_inv = player:get_inventory()
local bags_inv = minetest.create_detached_inventory(player:get_player_name().."_bags",{
on_put = function(inv, listname, index, stack, player)
player:get_inventory():set_stack(listname, index, stack)
player:get_inventory():set_size(listname.."contents", stack:get_definition().groups.bagslots)
end,
on_take = function(inv, listname, index, stack, player)
player:get_inventory():set_stack(listname, index, nil)
end,
allow_put = function(inv, listname, index, stack, player)
if stack:get_definition().groups.bagslots then
return 1
else
return 0
end
end,
allow_take = function(inv, listname, index, stack, player)
if player:get_inventory():is_empty(listname.."contents")==true then
return stack:get_count()
else
return 0
end
end,
allow_move = function(inv, from_list, from_index, to_list, to_index, count, player)
return 0
end,
})
for i=1,8 do
local bag = "bag"..i
player_inv:set_size(bag, 1)
bags_inv:set_size(bag, 1)
bags_inv:set_stack(bag,1,player_inv:get_stack(bag,1))
end
end)
-- register bag tools
minetest.register_tool("bags:small", {
description = "Small Bag",
inventory_image = "bags_small.png",
groups = {bagslots=8},
})
minetest.register_tool("bags:medium", {
description = "Medium Bag",
inventory_image = "bags_medium.png",
groups = {bagslots=16},
})
minetest.register_tool("bags:large", {
description = "Large Bag",
inventory_image = "bags_large.png",
groups = {bagslots=24},
})
minetest.register_tool("bags:trolley", {
description = "Trolley",
inventory_image = "bags_trolley.png",
groups = {bagslots=32},
})
minetest.register_tool("bags:small_admin", {
description = "Small Bag Regnum",
inventory_image = "bags_small_admin.png",
groups = {bagslots=36},
})
minetest.register_tool("bags:medium_admin", {
description = "Medium Bag Regnum",
inventory_image = "bags_medium_admin.png",
groups = {bagslots=40},
})
minetest.register_tool("bags:large_admin", {
description = "Large Bag Regnum",
inventory_image = "bags_large_admin.png",
groups = {bagslots=44},
})
minetest.register_tool("bags:trolley_admin", {
description = "Trolley Regnum",
inventory_image = "bags_trolley_admin.png",
groups = {bagslots=48},
})
-- register bag crafts
minetest.register_craft({
output = "bags:small",
recipe = {
{"", "default:stick", ""},
{"default:wood", "default:wood", "default:wood"},
{"default:wood", "default:wood", "default:wood"},
},
})
minetest.register_craft({
output = "bags:small",
recipe = {
{"", "default:stick", ""},
{"default:junglewood", "default:junglewood", "default:junglewood"},
{"default:junglewood", "default:junglewood", "default:junglewood"},
},
})
minetest.register_craft({
output = "bags:small",
recipe = {
{"", "default:stick", ""},
{"default:pine_wood", "default:pine_wood", "default:pine_wood"},
{"default:pine_wood", "default:pine_wood", "default:pine_wood"},
},
})
minetest.register_craft({
output = "bags:small",
recipe = {
{"", "default:stick", ""},
{"default:acacia_wood", "default:acacia_wood", "default:acacia_wood"},
{"default:acacia_wood", "default:acacia_wood", "default:acacia_wood"},
},
})
minetest.register_craft({
output = "bags:small",
recipe = {
{"", "default:stick", ""},
{"default:aspen_wood", "default:aspen_wood", "default:aspen_wood"},
{"default:aspen_wood", "default:aspen_wood", "default:aspen_wood"},
},
})
minetest.register_craft({
output = "bags:medium",
recipe = {
{"", "default:stick", ""},
{"bags:small", "bags:small", "bags:small"},
{"bags:small", "bags:small", "bags:small"},
},
})
minetest.register_craft({
output = "bags:large",
recipe = {
{"", "default:stick", ""},
{"bags:medium", "bags:medium", "bags:medium"},
{"bags:medium", "bags:medium", "bags:medium"},
},
})
minetest.register_craft({
output = "bags:trolley",
recipe = {
{"", "default:stick", ""},
{"bags:large", "bags:large", "bags:large"},
{"bags:large", "bags:large", "bags:large"},
},
})
minetest.register_craft({
output = "bags:small_admin",
recipe = {
{"", "tutorial:regnum", ""},
{"", "bags:trolley", ""},
{"", "", ""},
},
})
minetest.register_craft({
output = "bags:medium_admin",
recipe = {
{"", "tutorial:regnum", ""},
{"", "bags:small_admin", ""},
{"", "", ""},
},
})
minetest.register_craft({
output = "bags:large_admin",
recipe = {
{"", "tutorial:regnum", ""},
{"", "bags:medium_admin", ""},
{"", "", ""},
},
})
minetest.register_craft({
output = "bags:trolley_admin",
recipe = {
{"", "tutorial:regnum", ""},
{"", "bags:large_admin", ""},
{"", "", ""},
},
})
-- log that we started
minetest.log("action", "[MOD]"..minetest.get_current_modname().." -- loaded from "..minetest.get_modpath(minetest.get_current_modname()))
|
-- This module is loaded if a script calls require "gplus.objects".
local g = golly()
local gp = require "gplus"
local pattern = gp.pattern
local m = {}
m.block = pattern([[
**
**
]])
m.blinker = pattern("***", -1, 0)
m.glider = pattern([[
.**
**.
..*
]])
m.lwss = pattern([[
****.
*...*
*....
.*..*
]])
m.mwss = pattern([[
*****.
*....*
*.....
.*...*
...*..
]])
m.hwss = pattern([[
******.
*.....*
*......
.*....*
...**..
]])
m.eater = pattern([[
**
*
.***
...*
]])
m.hook = m.eater
m.queenbee = pattern([[
**..
..*.
...*
...*
...*
..*.
**..
]])
m.herschel = pattern([[
***.
.*..
.***
]])
m.bheptomino = pattern([[
**.
.**
**.
*..
]])
m.tub = pattern([[
.*.
*.*
.*.
]], -1, -1)
m.boat = pattern([[
**.
*.*
.*.
]])
m.long_boat = pattern([[
**.
*.*
.*.*
..*
]])
m.ship = pattern([[
**.
*.*
.**
]], -1, -1)
m.beehive = pattern([[
.**.
*..*
.**.
]], 0, -1)
m.loaf = pattern([[
.**.
*..*
*.*.
.*..
]])
m.snake = pattern([[
*.**
**.*
]])
m.aircraft_carrier = pattern([[
**..
*..*
..**
]])
m.honeyfarm = pattern([[
......*......
.....*.*.....
.....*.*.....
......*......
.............
.**.......**.
*..*.....*..*
.**.......**.
.............
......*......
.....*.*.....
.....*.*.....
......*......
]], -6, -6)
m.beacon = pattern([[
**..
*...
...*
..**
]])
m.blocker = pattern([[
......*.*.
.....*....
**..*....*
**.*..*.**
....**....
]])
m.clock = pattern([[
..*.
**..
..**
.*..
]])
m.dart = pattern([[
........*.
.......*.*
......**..
.........*
.....*...*
..*..*....
.*.*..****
*..*......
.*.*..****
..*..*....
.....*...*
.........*
......**..
.......*.*
........*.
]], 0, -7)
m.big_beacon = pattern([[
***...
***...
***...
...***
...***
...***
]])
m.middleweight_volcano = pattern([[
...*******...
.***.***.***.
*....***....*
.****.*.***.*
...........*.
*.**.*.*.*...
**.*.*.*.**..
....*..*.*...
.....**..*...
.........**..
]], -6, 0)
m.heavyweight_volcano = pattern([[
.........*..........................
........*.*.........................
......***.*.........................
.....*....**.*......................
.....*.**...**......**..............
....**.*.**.........*.*.............
.........*.*****......*..*.**.......
..*.**.**.*.....*....**.*.**.*......
.....**.....****........*....*......
*...*.*..*...*.*....**.*.****.**....
*...*.*..**.*.**.**....*.*....*.*...
.....**...***.**.*.***.*..***...*...
..*.**.**.**.............*.*..*.*.**
...........*......*.*.*.*..**.*.*.*.
....**.*.*.**......**.*.*.*...*.*.*.
.....*.**.*..*.......*.**..****.**..
.....*....*.*........*...**.........
....**....**........**...*..*.......
...........................**.......
]])
m.galaxy = pattern([[
******.**
******.**
.......**
**.....**
**.....**
**.....**
**.......
**.******
**.******
]], -4, -4)
m.orion = pattern([[
...**.........
...*.*........
...*..........
**.*..........
*....*........
*.**......***.
.....***....**
......***.*.*.
.............*
......*.*.....
.....**.*.....
......*.......
....**.*......
.......*......
.....**.......
]])
m.pentadecathlon = pattern([[
..*....*..
**.****.**
..*....*..
]], 0, -1)
m.pi = pattern([[
***
*.*
*.*
]])
m.pond = pattern([[
.**.
*..*
*..*
.**.
]])
m.pulsar = pattern([[
..***...***..
.............
*....*.*....*
*....*.*....*
*....*.*....*
..***...***..
.............
..***...***..
*....*.*....*
*....*.*....*
*....*.*....*
.............
..***...***..
]], -6, -6)
m.rpentomino = pattern([[
.**
**
.*
]])
m.rabbits = pattern([[
*...***
***..*.
.*.....
]])
m.spider = pattern([[
.........*.......*.........
...**.*.*.**...**.*.*.**...
***.*.***.........***.*.***
*...*.*.....*.*.....*.*...*
....**......*.*......**....
.**.........*.*.........**.
.**.**...............**.**.
.....*...............*.....
]], -13, 0)
m.lightweight_volcano = pattern([[
...**..**...
.***.**.***.
*..........*
.****..****.
....*..*....
.**......**.
.*..*..*..*.
..***..***..
............
****.**.****
*..**..**..*
]])
m.unix = pattern([[
..**....
....*.**
*..*..**
*.*.....
.*......
........
.**.....
.**.....
]])
m.biblocker = pattern([[
..................*...........
.................*.**.........
.................*.**.........
..................**..........
..............................
.......**............**.......
.......**............**.......
..............................
..............................
......*.*.....................
.....*..................**....
**..*....*..........**.*..*.**
**.*..*.**..........**..*....*
....**...................*....
..........................*.*.
]])
--------------------------------------------------------------------------------
-- this section emulates glife's herschel.py
m.herschel_ghost = pattern([[
***
.
.*.*
]])
-- A Herschel conduit is represented by its pattern and
-- the transformation it applies to the Herschel.
-- Hence the additional .transform field.
local block = m.block
local eater = m.eater
local snake = m.snake
m.hc64 = block.t(14, -8) + block.t(9, -13) + block.t(13, -15) + block.t(7, -19)
m.hc64.transform = {-9, -9, gp.rccw}
m.hc77 = block.t(9, -13) + eater.t(10, 0, gp.swap_xy) + eater.t(-7, -12, gp.swap_xy_flip)
m.hc77.transform = {10, -25, gp.flip_x}
m.hc112 = block.t(16, -10) + block.t(-3, -11) + m.aircraft_carrier.t(13, -3, gp.swap_xy) +
eater.t(10, 1) + eater.t(-3, -14, gp.flip) + eater.t(9, -16, gp.flip_y)
m.hc112.transform = {35, -12, gp.rcw}
m.hc117 = eater.t(10, 1) + eater.t(13, -9, gp.swap_xy) + eater.t(0, -12, gp.swap_xy_flip) +
block.t(8, -22) + snake.t(15, -19)
m.hc117.transform = {6, -40, gp.identity}
m.hc119 = block.t(-14, -3) + block.t(-13, -8) + block.t(-19, -9) + eater.t(-17, -2, gp.rcw)
m.hc119.transform = {-12, -20, gp.flip_x}
m.hc156 = eater.t(10, 0, gp.swap_xy) + eater.t(12, -9, gp.swap_xy) + eater.t(0, -12, gp.swap_xy_flip) +
eater.t(17, -21, gp.flip_y) + snake.t(21, -5, gp.rccw) + block.t(24, -15) + m.tub.t(11, -24)
m.hc156.transform = {43, -17, gp.rcw}
m.hc158 = eater.t(-2, -13, gp.flip) + eater.t(-3, -8, gp.rcw) + eater.t(20, -19, gp.rccw) +
pattern([[
.....**
.....*.*
.......*
.......*.*.**
..**.*.*.**.*
..**.**.*
........*
..**.***
...*.*
...*.*
**.**
*.*
..*
..**
]], 14, -12)
m.hc158.transform = {7, -27, gp.flip_x}
m.hc190 = eater.t(-3, -8, gp.rcw) + eater.t(-10, -12, gp.swap_xy) + eater.t(-3, -12, gp.swap_xy_flip) +
eater.t(-8, -17) + eater.t(11, -27, gp.flip_y) + block.t(2, -25) + snake.t(5, -31, gp.rccw) +
pattern([[
..**.*
..**.***
........*
..**.***
...*.*
...*.*
**.**
*.*
..*
..**
]], 14, -8)
m.hc190.transform = {-16, -22, gp.rccw}
--------------------------------------------------------------------------------
return m
|
local cjson = require ("cjson")
local client = require ("resty.kafka.client")
local broker_list = {
{ host = "127.0.0.1", port = 9092 },
}
local cli = client:new(broker_list)
local brokers, partitions = cli:fetch_metadata("test")
if not brokers then
ngx.say("fetch_metadata failed, err:", partitions)
end
ngx.say("brokers: ", cjson.encode(brokers), "; partitions: ", cjson.encode(partitions))
|
-- Set the Maximum amount of Product for all Data Assembler --
for _, da in pairs (global.dataAssemblerTable or {}) do
for _, recipe in pairs (da.recipeTable) do
if recipe.amount ~= nil and recipe.amount ~= 0 then
for _, product in pairs (recipe.products) do
product.max = recipe.amount
end
end
end
end
|
-- {{{ Use protected call so we don't error on first use.
local packer_ok, packer = pcall(require, 'packer')
if not packer_ok then return end
-- ------------------------------------------------------------------------- }}}
-- {{{ Packer startup function definition.
return packer.startup(function(use)
-- ------------------------------------------------------------------------- }}}
-- {{{ Packer can manage itself as an optional plugin.
use {'wbthomason/packer.nvim', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Color scheme
use {'Traap/nvim-base16.lua', opt = false}
use {'norcalli/nvim-colorizer.lua', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Completion
use {'hrsh7th/nvim-cmp', opt = false}
use {'hrsh7th/cmp-buffer', opt = false}
use {'hrsh7th/cmp-calc', opt = false}
use {'hrsh7th/cmp-cmdline', opt = false}
use {'hrsh7th/cmp-nvim-lsp', opt = false}
use {'hrsh7th/cmp-nvim-lsp-document-symbol', opt = false}
use {'hrsh7th/cmp-nvim-lua', opt = false}
use {'hrsh7th/cmp-path', opt = false}
use {'f3fora/cmp-spell', opt = false}
use {'onsails/lspkind-nvim', opt = false}
-- use {'simrat39/symbols-outline.nvim'}
-- ------------------------------------------------------------------------- }}}
-- {{{ Easyalign & snippets
use {'junegunn/vim-easy-align', opt = false}
use {'L3MON4D3/LuaSnip', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ File manager
use {'kyazdani42/nvim-tree.lua', opt = false}
use {'kyazdani42/nvim-web-devicons', opt = false}
use {'NTBBloodbath/galaxyline.nvim', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Fuzzy finder
use {'nvim-telescope/telescope.nvim', opt = false}
use {'nvim-lua/popup.nvim', opt = false}
use {'nvim-lua/plenary.nvim', opt = false}
use {'nvim-telescope/telescope-media-files.nvim', opt = false}
use {'nvim-telescope/telescope-snippets.nvim', opt = false}
use {'norcalli/snippets.nvim', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Lua development
-- use {'tjdevries/nlua.nvim', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ LSP
use {'neovim/nvim-lspconfig', opt = false}
use {'williamboman/nvim-lsp-installer', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Profiling
use {'tweekmonster/startuptime.vim', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ PlantUML
use {'aklt/plantuml-syntax', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ neovim without Tpope? No Way!!!
use {'tpope/vim-characterize', opt = false}
use {'tpope/vim-commentary', opt = false}
use {'tpope/vim-dispatch', opt = false}
use {'tpope/vim-endwise', opt = false}
use {'tpope/vim-fugitive', opt = false}
use {'tpope/vim-repeat', opt = false}
use {'tpope/vim-surround', opt = false}
use {'tpope/vim-unimpaired', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ RipGrep
use {'traap/vim-ripgrep', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Treesitter
use {'nvim-treesitter/nvim-treesitter', run = ':TSUpdate', opt = false}
use {'romgrk/nvim-treesitter-context', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Tmux
use {'christoomey/vim-tmux-navigator', opt = false}
use {'christoomey/vim-tmux-runner', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Utility
use {'sbdchd/neoformat', opt = false}
use {'triglav/vim-visual-increment', opt = false}
use {'vim-utils/vim-most-minimal-folds', opt = false}
use {'xiyaowong/nvim-transparent', opt = false}
use {'mechatroner/rainbow_csv', opt = false}
use {'iamcco/markdown-preview.nvim', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ VimTex
use {'lervag/vimtex', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Wiki.Vim
use {'lervag/wiki.vim', opt = false}
use {'dkarter/bullets.vim', opt = false}
use {'lervag/wiki-ft.vim', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Zulu : Reuse Traap's vim bundles last.
use {'Traap/vim-bundle-autocmd', opt = false}
use {'Traap/vim-bundle-plantuml', opt = false}
use {'Traap/vim-bundle-vimtex', opt = false}
use {'Traap/vim-bundle-vimwiki', opt = false}
-- ------------------------------------------------------------------------- }}}
-- {{{ Auto compile and install plugins when packer is bootstrapped.
if vim.g.nvim_bootstrapped == 1 then
packer.sync()
end
-- ------------------------------------------------------------------------- }}}
-- {{{ Display boarders
-- end,
-- {
-- display = {
-- border = require('traap/config).display_boarder
-- }
-- }
-- )
end)
-- ------------------------------------------------------------------------- }}}
|
local mayConflictList = {
"2433702881", -- Chaos Mod
}
local willConflictList = {
"2415158477", -- Sprint and Walk
"2417915839", -- Flymode
}
local compatTimer = 0
local willConflict = false
local conflicts = {}
function checkCompat()
for i=1, #mayConflictList do
local id = mayConflictList[i]
local active = GetBool("mods.available.steam-"..id..".active")
if active then
willConflict = true
table.insert(conflicts, ' ' .. GetString("mods.available.steam-"..id..".listname"))
end
end
for i=1, #willConflictList do
local id = willConflictList[i]
local active = GetBool("mods.available.steam-"..id..".active")
if active then
willConflict = true
table.insert(conflicts, '!!! ' .. GetString("mods.available.steam-"..id..".listname") .. ' !!!')
end
end
end
function compatDraw()
if willConflict and compatTimer < 8 then
compatTimer = compatTimer + GetTimeStep()
local opacity = 1
if compatTimer > 7 then
opacity = 1 - (compatTimer - 7)
end
local header = "Bunnyhop Mod may conflict or cause problems with the following mods:"
local text = ""
for i=1, #conflicts do
local name = conflicts[i]
text = text .. "\n" .. name
end
UiPush()
UiAlign("center bottom")
UiTranslate(UiCenter(), UiHeight() - 70)
UiFont("MOD/assets/ui/Roboto-Bold.ttf", 20)
local hw, hh = UiGetTextSize(header)
UiFont("MOD/assets/ui/Roboto-Regular.ttf", 20)
local dw, dh = UiGetTextSize(text)
UiColor(1, 1, 1, opacity)
UiPush()
UiTranslate(0, 5)
UiColor(1, 0.25, 0.2, opacity)
local mw = hw
if dw > hw then mw = dw end
UiRect(mw + 10, hh + dh + 10)
UiPop()
UiPush()
UiTranslate(0, -dh)
UiFont("MOD/assets/ui/Roboto-Bold.ttf", 20)
UiText(header)
UiPop()
UiPush()
UiFont("MOD/assets/ui/Roboto-Regular.ttf", 20)
UiText(text)
UiPop()
UiPop()
end
end
|
--[[
Title: Adv. Dupe 2 Codec
Desc: Dupe encoder/decoder.
Author: emspike
Version: 2.0
]]
local REVISION = 4
local hasModule = false
if(SERVER)then
if(system.IsWindows())then
hasModule = file.Exists("lua/bin/gmsv_ad2filestream_win32.dll", "GAME")
print(hasModule)
if(!hasModule)then
print("[AdvDupe2Notify]\tMODULE NOT INSTALLED CORRECTLY. SAVING WILL BE SLOW.")
else
require("ad2filestream")
end
end
end
include "sh_codec_legacy.lua"
AddCSLuaFile "sh_codec_legacy.lua"
local pairs = pairs
local type = type
local error = error
local Vector = Vector
local Angle = Angle
local format = string.format
local char = string.char
local byte = string.byte
local sub = string.sub
local gsub = string.gsub
local find = string.find
local gmatch = string.gmatch
local match = string.match
local concat = table.concat
local compress = util.Compress
local decompress = util.Decompress
AdvDupe2.CodecRevision = REVISION
--[[
Name: GenerateDupeStamp
Desc: Generates an info table.
Params: <player> ply
Return: <table> stamp
]]
function AdvDupe2.GenerateDupeStamp(ply)
local stamp = {}
stamp.name = ply:GetName()
stamp.time = os.date("%I:%M %p")
stamp.date = os.date("%d %B %Y")
stamp.timezone = os.date("%z")
hook.Call("AdvDupe2_StampGenerated",GAMEMODE,stamp)
return stamp
end
local function makeInfo(tbl)
local info = ""
for k,v in pairs(tbl) do
info = concat{info,k,"\1",v,"\1"}
end
return info.."\2"
end
local AD2FF = "AD2F%s\n%s\n%s"
local tables
local buff
local function noserializer() end
local enc = {}
for i=1,255 do enc[i] = noserializer end
local function isArray(tbl)
local ret = true
local m = 0
for k, v in pairs(tbl) do
m = m + 1
if k ~= m or enc[TypeID(v)]==noserializer then
ret = false
break
end
end
return ret
end
local function write(obj)
enc[TypeID(obj)](obj)
end
local len
local tables,tablesLookup
if(not system.IsWindows() or not hasModule)then
enc[TYPE_TABLE] = function(obj) --table
tables = tables + 1
if not tablesLookup[obj] then
tablesLookup[obj] = tables
else
buff:WriteByte(247)
buff:WriteShort(tablesLookup[obj])
return
end
if isArray(obj) then
buff:WriteByte(254)
for i,v in pairs(obj) do
write(v)
end
else
buff:WriteByte(255)
for k,v in pairs(obj) do
if(enc[TypeID(v)]!=noserializer)then
write(k)
write(v)
end
end
end
buff:WriteByte(0)
end
enc[TYPE_BOOL] = function(obj) --boolean
buff:WriteByte(obj and 253 or 252)
end
enc[TYPE_NUMBER] = function(obj) --number
buff:WriteByte(251)
buff:WriteDouble(obj)
end
enc[TYPE_VECTOR] = function(obj) --vector
buff:WriteByte(250)
buff:WriteDouble(obj.x)
buff:WriteDouble(obj.y)
buff:WriteDouble(obj.z)
end
enc[TYPE_ANGLE] = function(obj) --angle
buff:WriteByte(249)
buff:WriteDouble(obj.p)
buff:WriteDouble(obj.y)
buff:WriteDouble(obj.r)
end
enc[TYPE_STRING] = function(obj) --string
len = #obj
if len > 0 and len < 247 then
buff:WriteByte(len)
buff:Write(obj)
else
buff:WriteByte(248)
buff:Write(obj)
buff:WriteByte(0)
end
end
else
enc[TYPE_TABLE] = function(obj) --table
tables = tables + 1
if not tablesLookup[obj] then
tablesLookup[obj] = tables
else
AdvDupe2_WriteByte(247)
AdvDupe2_WriteShort(tablesLookup[obj])
return
end
if isArray(obj) then
AdvDupe2_WriteByte(254)
for i,v in pairs(obj) do
write(v)
end
else
AdvDupe2_WriteByte(255)
for k,v in pairs(obj) do
if(enc[TypeID(v)]!=noserializer)then
write(k)
write(v)
end
end
end
AdvDupe2_WriteByte(0)
end
enc[TYPE_BOOL] = function(obj) --boolean
AdvDupe2_WriteByte(obj and 253 or 252)
end
enc[TYPE_NUMBER] = function(obj) --number
AdvDupe2_WriteByte(251)
AdvDupe2_WriteDouble(obj)
end
enc[TYPE_VECTOR] = function(obj) --vector
AdvDupe2_WriteByte(250)
AdvDupe2_WriteDouble(obj.x)
AdvDupe2_WriteDouble(obj.y)
AdvDupe2_WriteDouble(obj.z)
end
enc[TYPE_ANGLE] = function(obj) --angle
AdvDupe2_WriteByte(249)
AdvDupe2_WriteDouble(obj.p)
AdvDupe2_WriteDouble(obj.y)
AdvDupe2_WriteDouble(obj.r)
end
enc[TYPE_STRING] = function(obj) --string
len = #obj
if len > 0 and len < 247 then
AdvDupe2_WriteByte(len)
AdvDupe2_WriteString(obj)
else
AdvDupe2_WriteByte(248)
AdvDupe2_WriteString(obj)
AdvDupe2_WriteByte(0)
end
end
end
local function error_nodeserializer()
buff:Seek(buff:Tell()-1)
error(format("couldn't find deserializer for type {typeid:%d}", buff:ReadByte()))
end
local dec = {}
local reference = 0
for i=1,255 do dec[i] = error_nodeserializer end
local function read()
local tt = buff:ReadByte()
if not tt then
error("expected value, got EOF")
end
if tt == 0 then
return nil
end
return dec[tt]()
end
dec[255] = function() --table
local t = {}
local k
reference = reference + 1
local ref = reference
repeat
k = read()
if k ~= nil then
t[k] = read()
end
until (k == nil)
tables[ref] = t
return t
end
dec[254] = function() --array
local t = {}
local k,v = 0
reference = reference + 1
local ref = reference
repeat
k = k + 1
v = read()
if(v != nil) then
t[k] = v
end
until (v == nil)
tables[ref] = t
return t
end
dec[253] = function()
return true
end
dec[252] = function()
return false
end
dec[251] = function()
return buff:ReadDouble()
end
dec[250] = function()
return Vector(buff:ReadDouble(),buff:ReadDouble(),buff:ReadDouble())
end
dec[249] = function()
return Angle(buff:ReadDouble(),buff:ReadDouble(),buff:ReadDouble())
end
dec[248] = function() --null-terminated string
local start = buff:Tell()
local slen = 0
while buff:ReadByte() != 0 do
slen = slen + 1
end
buff:Seek(start)
local retv = buff:Read(slen)
if(not retv)then retv="" end
buff:ReadByte()
return retv
end
dec[247] = function() --table reference
reference = reference + 1
return tables[buff:ReadShort()]
end
local function vsr()
buff:Seek(buff:Tell() - 1)
slen = buff:ReadByte()
return buff:Read(slen)
end
for i=1,246 do dec[i] = vsr end
local function serialize(tbl)
tables = 0
tablesLookup = {}
if(not system.IsWindows() or not hasModule)then
buff = file.Open("ad2temp.txt", "wb", "DATA")
write(tbl)
buff:Close()
else
if(not AdvDupe2_OpenStream)then print("[AdvDupe2Notify]\tMODULE NOT INSTALLED CORRECTLY. YOU WILL NOT BE ABLE TO SAVE.") return "" end
if(not AdvDupe2_OpenStream())then error("Filestream could not be opened.") return "" end
write(tbl)
AdvDupe2_CloseStream()
end
buff = file.Open("ad2temp.txt","rb","DATA")
local ret = buff:Read(buff:Size())
buff:Close()
return ret
end
local function deserialize(str)
if(str==nil)then
error("File could not be decompressed.")
return {}
end
tables = {}
reference = 0
buff = file.Open("ad2temp.txt","wb","DATA")
buff:Write(str)
buff:Flush()
buff:Close()
buff = file.Open("ad2temp.txt","rb", "DATA")
local tbl = read()
buff:Close()
return tbl
end
--[[
Name: Encode
Desc: Generates the string for a dupe file with the given data.
Params: <table> dupe, <table> info, <function> callback, <...> args
Return: runs callback(<string> encoded_dupe, <...> args)
]]
function AdvDupe2.Encode(dupe, info, callback, ...)
local encodedTable = compress(serialize(dupe))
info.check = "\r\n\t\n"
info.size = #encodedTable
callback(AD2FF:format(char(REVISION), makeInfo(info), encodedTable),...)
end
--seperates the header and body and converts the header to a table
local function getInfo(str)
local last = str:find("\2")
if not last then
error("attempt to read AD2 file with malformed info block")
end
local info = {}
local ss = str:sub(1,last-1)
for k,v in ss:gmatch("(.-)\1(.-)\1") do
info[k] = v
end
if info.check ~= "\r\n\t\n" then
if info.check == "\10\9\10" then
error("detected AD2 file corrupted in file transfer (newlines homogenized)(when using FTP, transfer AD2 files in image/binary mode, not ASCII/text mode)")
else
error("attempt to read AD2 file with malformed info block")
end
end
return info, str:sub(last+2)
end
--decoders for individual versions go here
local versions = {}
versions[1] = AdvDupe2.LegacyDecoders[1]
versions[2] = AdvDupe2.LegacyDecoders[2]
versions[3] = function(encodedDupe)
encodedDupe = encodedDupe:Replace("\r\r\n\t\r\n", "\t\t\t\t")
encodedDupe = encodedDupe:Replace("\r\n\t\n", "\t\t\t\t")
encodedDupe = encodedDupe:Replace("\r\n", "\n")
encodedDupe = encodedDupe:Replace("\t\t\t\t", "\r\n\t\n")
return versions[4](encodedDupe)
end
versions[4] = function(encodedDupe)
local info, dupestring = getInfo(encodedDupe:sub(7))
return deserialize(
decompress(dupestring)
), info
end
--[[
Name: Decode
Desc: Generates the table for a dupe from the given string. Inverse of Encode
Params: <string> encodedDupe, <function> callback, <...> args
Return: runs callback(<boolean> success, <table/string> tbl, <table> info)
]]
function AdvDupe2.Decode(encodedDupe, callback, ...)
local sig, rev = encodedDupe:match("^(....)(.)")
if not rev then
error("malformed dupe (wtf <5 chars long?!)")
end
rev = rev:byte()
if sig ~= "AD2F" then
if sig == "[Inf" then --legacy support, ENGAGE (AD1 dupe detected)
local success, tbl, info, moreinfo = pcall(AdvDupe2.LegacyDecoders[0], encodedDupe)
if success then
info.size = #encodedDupe
info.revision = 0
info.ad1 = true
else
ErrorNoHalt(tbl)
end
callback(success, tbl, info, moreinfo, ...)
else
error("unknown duplication format")
end
elseif rev > REVISION then
error(format("this install lacks the codec version to parse the dupe (have rev %u, need rev %u)",REVISION,rev))
elseif rev < 1 then
error(format("attempt to use an invalid format revision (rev %d)", rev))
else
local success, tbl, info = pcall(versions[rev], encodedDupe)
if success then
info.revision = rev
else
ErrorNoHalt(tbl)
end
callback(success, tbl, info, ...)
end
end
|
--IupTree Example in IupLua
--Creates a tree with some branches and leaves. Uses a Lua Table to define the IupTree structure.
require( "iuplua" )
tree = iup.tree{}
dlg = iup.dialog{tree ; title = "TableTree result", size = "200x200"}
dlg:showxy(iup.CENTER,iup.CENTER)
t = {
{
"Horse",
"Whale";
branchname = "Mammals"
},
{
"Shrimp",
"Lobster";
branchname = "Crustaceans"
};
branchname = "Animals"
}
iup.TreeAddNodes(tree, t)
if (iup.MainLoopLevel()==0) then
iup.MainLoop()
end
|
-- Super Nicknames are saved in gc_nickcache.colorname
local acceptedChars = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
local nickLimit = 22
local originalName = {
-- [player] = name
}
function setSuperNick(player,bool)
-- originalName[source] = getPlayerName( source )
local playerSuperNick = getVipSetting(player, 2, 'supernick')
if bool == true and playerSuperNick and playerSuperNick ~= "" and isPlayerVIP(player) then
local colorlessNick = string.gsub(playerSuperNick, "#%x%x%x%x%x%x", "")
setElementData(player, "vip.colorNick", playerSuperNick)
setPlayerName(player, colorlessNick)
if getPlayerName( player ) ~= colorlessNick then
-- If name change is not succes, try again
setTimer( setPlayerName, 3000, 1, colorlessNick )
end
return true
elseif bool == false and player and isElement(player) and getElementType(player) == "player" then
removeElementData( player, "vip.colorNick" )
if originalName[player] then
setPlayerName(player, originalName[player])
end
end
end
addEvent('onClientRequestNickSettings', true)
addEventHandler('onClientRequestNickSettings', root,
function()
triggerClientEvent(source, 'sendNickSettings', source, acceptedChars, nickLimit)
end)
addEvent('onClientChangeCustomNickname', true)
addEventHandler('onClientChangeCustomNickname', root,
function(nick)
if not isPlayerVIP(source) or not vipPlayers[source] then return end
local colorlessNick = string.gsub(nick, "#%x%x%x%x%x%x", "")
local nickLength = string.len(colorlessNick)
if nickLength > nickLimit then
vip_outputChatBox("Nick is too long", source, 255, 50, 0)
return
elseif nickLength == 0 then
vip_outputChatBox("Nick can't be empty", source, 255, 50, 0)
return
end
for i, p in ipairs(getElementsByType("player")) do
if p ~= source and string.lower(getPlayerName(p):gsub("#%x%x%x%x%x%x", "")) == string.lower(colorlessNick) then
vip_outputChatBox("Nick already in use", source, 255, 50, 0)
return
end
end
saveVipSetting(source,2,"supernick",nick)
setSuperNick(source, true)
vip_outputChatBox("Super Nick Successfully set!", source, 0, 255, 100)
end)
addEvent('onClientResetCustomNickname', true)
addEventHandler('onClientResetCustomNickname', root,
function()
if not isPlayerVIP(source) or not vipPlayers[source] then return end
local forumid = exports.gc:getPlayerForumID(source)
-- success = success and dbExec(handlerConnect, "UPDATE gc_nickcache SET colorname=null WHERE forumid=?", forumid)
local success = saveVipSetting(source,2,"supernick",false)
if success then
removeElementData( source, 'vip.colorNick' )
if originalName[source] then
setPlayerName( source, originalName[source])
originalName[source] = nil
end
vip_outputChatBox("Your super nick was succesfully cleared!",source,0,255,100)
else
vip_outputChatBox("There was an error while clearing your name!",source,255,0,0)
end
end)
addEventHandler('onPlayerChangeNick', root,
function(old,new,byPlayer)
if getElementData(source, "vip.colorNick" ) and isPlayerVIP(source) and vipPlayers[source] and byPlayer then
-- removeElementData( source, 'vip.colorNick' )
vip_outputChatBox("Please remove VIP SuperNick before changing your name!",source,255,0,0)
cancelEvent( true, "Please remove VIP SuperNick first!" )
end
end)
addEventHandler('onPlayerVip', resourceRoot,
function(player, loggedIn)
if player and isElement(player) and getElementType(player) == "player" then
if loggedIn then
local playerSuperNick = vipPlayers[player].options[2].supernick
if playerSuperNick and playerSuperNick ~= "" then
originalName[player] = getPlayerName(player)
setSuperNick(player,true)
-- vip_outputChatBox("Your nickname has been set to your VIP nickname.", player, 0, 255, 100)
end
else
-- Handle logout
setSuperNick(source,false)
end
end
end
)
addEventHandler('onResourceStop', resourceRoot,
function()
for i, p in ipairs(getElementsByType('player')) do
if originalName[p] then
setPlayerName( p, originalName[p] )
end
removeElementData( p, 'vip.colorNick' )
end
end)
|
local nested_ordered = {}
local KEY_ORDER_KEY = '__key_order'
function nested_ordered.new()
return setmetatable({
[KEY_ORDER_KEY] = {},
}, nested_ordered)
end
function nested_ordered.__newindex(t, index, value)
local order = rawget(t, KEY_ORDER_KEY)
order[#order + 1] = index
rawset(t, index, value)
end
function nested_ordered.__pairs(t)
local i = 0
local keys = t[KEY_ORDER_KEY]
return function()
i = i + 1
local idx = keys[i]
return idx, t[idx]
end
end
return nested_ordered
|
local web = require('http')
local function http_magick(self)
print(555555555555555)
return self:http("hello")(self)
end
print(4)
local function print_body(self)
print(66666666666666)
print(self:body_read())
print("Content-Type")
print(self:http_header("Content-Type"))
print(77777777777777)
self:finish()
end
local app = web.application()
app:handler_http("http","hello",print_body)
app:dispatcher("http",http_magick)
app:start()
|
-- This file is part of SA MoonLoader package.
-- Licensed under the MIT License.
-- Copyright (c) 2016, BlastHack Team <blast.hk>
local sampfuncs = {
-- RPCs
RPC_CLICKPLAYER = 23,
RPC_CLIENTJOIN = 25,
RPC_ENTERVEHICLE = 26,
RPC_ENTEREDITOBJECT = 27,
RPC_SCRIPTCASH = 31,
RPC_SERVERCOMMAND = 50,
RPC_SPAWN = 52,
RPC_DEATH = 53,
RPC_NPCJOIN = 54,
RPC_DIALOGRESPONSE = 62,
RPC_CLICKTEXTDRAW = 83,
RPC_SCMEVENT = 96,
RPC_WEAPONPICKUPDESTROY = 97,
RPC_CHAT = 101,
RPC_SRVNETSTATS = 102,
RPC_CLIENTCHECK = 103,
RPC_DAMAGEVEHICLE = 106,
RPC_GIVETAKEDAMAGE = 115,
RPC_EDITATTACHEDOBJECT = 116,
RPC_EDITOBJECT = 117,
RPC_SETINTERIORID = 118,
RPC_MAPMARKER = 119,
RPC_REQUESTCLASS = 128,
RPC_REQUESTSPAWN = 129,
RPC_PICKEDUPPICKUP = 131,
RPC_MENUSELECT = 132,
RPC_VEHICLEDESTROYED = 136,
RPC_MENUQUIT = 140,
RPC_EXITVEHICLE = 154,
RPC_UPDATESCORESPINGSIPS = 155,
RPC_SCRSETPLAYERNAME = 11,
RPC_SCRSETPLAYERPOS = 12,
RPC_SCRSETPLAYERPOSFINDZ = 13,
RPC_SCRSETPLAYERHEALTH = 14,
RPC_SCRTOGGLEPLAYERCONTROLLABLE = 15,
RPC_SCRPLAYSOUND = 16,
RPC_SCRSETPLAYERWORLDBOUNDS = 17,
RPC_SCRGIVEPLAYERMONEY = 18,
RPC_SCRSETPLAYERFACINGANGLE = 19,
RPC_SCRRESETPLAYERMONEY = 20,
RPC_SCRRESETPLAYERWEAPONS = 21,
RPC_SCRGIVEPLAYERWEAPON = 22,
RPC_SCRSETVEHICLEPARAMSEX = 24,
RPC_SCRCANCELEDIT = 28,
RPC_SCRSETPLAYERTIME = 29,
RPC_SCRTOGGLECLOCK = 30,
RPC_SCRWORLDPLAYERADD = 32,
RPC_SCRSETPLAYERSHOPNAME = 33,
RPC_SCRSETPLAYERSKILLLEVEL = 34,
RPC_SCRSETPLAYERDRUNKLEVEL = 35,
RPC_SCRCREATE3DTEXTLABEL = 36,
RPC_SCRDISABLECHECKPOINT = 37,
RPC_SCRSETRACECHECKPOINT = 38,
RPC_SCRDISABLERACECHECKPOINT = 39,
RPC_SCRGAMEMODERESTART = 40,
RPC_SCRPLAYAUDIOSTREAM = 41,
RPC_SCRSTOPAUDIOSTREAM = 42,
RPC_SCRREMOVEBUILDINGFORPLAYER = 43,
RPC_SCRCREATEOBJECT = 44,
RPC_SCRSETOBJECTPOS = 45,
RPC_SCRSETOBJECTROT = 46,
RPC_SCRDESTROYOBJECT = 47,
RPC_SCRDEATHMESSAGE = 55,
RPC_SCRSETPLAYERMAPICON = 56,
RPC_SCRREMOVEVEHICLECOMPONENT = 57,
RPC_SCRUPDATE3DTEXTLABEL = 58,
RPC_SCRCHATBUBBLE = 59,
RPC_SCRSOMEUPDATE = 60,
RPC_SCRSHOWDIALOG = 61,
RPC_SCRDESTROYPICKUP = 63,
RPC_SCRLINKVEHICLETOINTERIOR = 65,
RPC_SCRSETPLAYERARMOUR = 66,
RPC_SCRSETPLAYERARMEDWEAPON = 67,
RPC_SCRSETSPAWNINFO = 68,
RPC_SCRSETPLAYERTEAM = 69,
RPC_SCRPUTPLAYERINVEHICLE = 70,
RPC_SCRREMOVEPLAYERFROMVEHICLE = 71,
RPC_SCRSETPLAYERCOLOR = 72,
RPC_SCRDISPLAYGAMETEXT = 73,
RPC_SCRFORCECLASSSELECTION = 74,
RPC_SCRATTACHOBJECTTOPLAYER = 75,
RPC_SCRINITMENU = 76,
RPC_SCRSHOWMENU = 77,
RPC_SCRHIDEMENU = 78,
RPC_SCRCREATEEXPLOSION = 79,
RPC_SCRSHOWPLAYERNAMETAGFORPLAYER = 80,
RPC_SCRATTACHCAMERATOOBJECT = 81,
RPC_SCRINTERPOLATECAMERA = 82,
RPC_SCRSETOBJECTMATERIAL = 84,
RPC_SCRGANGZONESTOPFLASH = 85,
RPC_SCRAPPLYANIMATION = 86,
RPC_SCRCLEARANIMATIONS = 87,
RPC_SCRSETPLAYERSPECIALACTION = 88,
RPC_SCRSETPLAYERFIGHTINGSTYLE = 89,
RPC_SCRSETPLAYERVELOCITY = 90,
RPC_SCRSETVEHICLEVELOCITY = 91,
RPC_SCRCLIENTMESSAGE = 93,
RPC_SCRSETWORLDTIME = 94,
RPC_SCRCREATEPICKUP = 95,
RPC_SCRMOVEOBJECT = 99,
RPC_SCRENABLESTUNTBONUSFORPLAYER = 104,
RPC_SCRTEXTDRAWSETSTRING = 105,
RPC_SCRSETCHECKPOINT = 107,
RPC_SCRGANGZONECREATE = 108,
RPC_SCRPLAYCRIMEREPORT = 112,
RPC_SCRSETPLAYERATTACHEDOBJECT = 113,
RPC_SCRGANGZONEDESTROY = 120,
RPC_SCRGANGZONEFLASH = 121,
RPC_SCRSTOPOBJECT = 122,
RPC_SCRSETNUMBERPLATE = 123,
RPC_SCRTOGGLEPLAYERSPECTATING = 124,
RPC_SCRPLAYERSPECTATEPLAYER = 126,
RPC_SCRPLAYERSPECTATEVEHICLE = 127,
RPC_SCRSETPLAYERWANTEDLEVEL = 133,
RPC_SCRSHOWTEXTDRAW = 134,
RPC_SCRTEXTDRAWHIDEFORPLAYER = 135,
RPC_SCRSERVERJOIN = 137,
RPC_SCRSERVERQUIT = 138,
RPC_SCRINITGAME = 139,
RPC_SCRREMOVEPLAYERMAPICON = 144,
RPC_SCRSETPLAYERAMMO = 145,
RPC_SCRSETGRAVITY = 146,
RPC_SCRSETVEHICLEHEALTH = 147,
RPC_SCRATTACHTRAILERTOVEHICLE = 148,
RPC_SCRDETACHTRAILERFROMVEHICLE = 149,
RPC_SCRSETWEATHER = 152,
RPC_SCRSETPLAYERSKIN = 153,
RPC_SCRSETPLAYERINTERIOR = 156,
RPC_SCRSETPLAYERCAMERAPOS = 157,
RPC_SCRSETPLAYERCAMERALOOKAT = 158,
RPC_SCRSETVEHICLEPOS = 159,
RPC_SCRSETVEHICLEZANGLE = 160,
RPC_SCRSETVEHICLEPARAMSFORPLAYER = 161,
RPC_SCRSETCAMERABEHINDPLAYER = 162,
RPC_SCRWORLDPLAYERREMOVE = 163,
RPC_SCRWORLDVEHICLEADD = 164,
RPC_SCRWORLDVEHICLEREMOVE = 165,
RPC_SCRWORLDPLAYERDEATH = 166,
-- Packets
PACKET_INTERNAL_PING = 6,
PACKET_PING = 7,
PACKET_PING_OPEN_CONNECTIONS = 8,
PACKET_CONNECTED_PONG = 9,
PACKET_REQUEST_STATIC_DATA = 10,
PACKET_CONNECTION_REQUEST = 11,
PACKET_AUTH_KEY = 12,
PACKET_BROADCAST_PINGS = 14,
PACKET_SECURED_CONNECTION_RESPONSE = 15,
PACKET_SECURED_CONNECTION_CONFIRMATION = 16,
PACKET_RPC_MAPPING = 17,
PACKET_SET_RANDOM_NUMBER_SEED = 19,
PACKET_RPC = 20,
PACKET_RPC_REPLY = 21,
PACKET_DETECT_LOST_CONNECTIONS = 23,
PACKET_OPEN_CONNECTION_REQUEST = 24,
PACKET_OPEN_CONNECTION_REPLY = 25,
PACKET_CONNECTION_COOKIE = 26,
PACKET_RSA_PUBLIC_KEY_MISMATCH = 28,
PACKET_CONNECTION_ATTEMPT_FAILED = 29,
PACKET_NEW_INCOMING_CONNECTION = 30,
PACKET_NO_FREE_INCOMING_CONNECTIONS = 31,
PACKET_DISCONNECTION_NOTIFICATION = 32,
PACKET_CONNECTION_LOST = 33,
PACKET_CONNECTION_REQUEST_ACCEPTED = 34,
PACKET_INITIALIZE_ENCRYPTION = 35,
PACKET_CONNECTION_BANNED = 36,
PACKET_INVALID_PASSWORD = 37,
PACKET_MODIFIED_PACKET = 38,
PACKET_PONG = 39,
PACKET_TIMESTAMP = 40,
PACKET_RECEIVED_STATIC_DATA = 41,
PACKET_REMOTE_DISCONNECTION_NOTIFICATION = 42,
PACKET_REMOTE_CONNECTION_LOST = 43,
PACKET_REMOTE_NEW_INCOMING_CONNECTION = 44,
PACKET_REMOTE_EXISTING_CONNECTION = 45,
PACKET_REMOTE_STATIC_DATA = 46,
PACKET_ADVERTISE_SYSTEM = 56,
PACKET_VEHICLE_SYNC = 200,
PACKET_RCON_COMMAND = 201,
PACKET_RCON_RESPONCE = 202,
PACKET_AIM_SYNC = 203,
PACKET_WEAPONS_UPDATE = 204,
PACKET_STATS_UPDATE = 205,
PACKET_BULLET_SYNC = 206,
PACKET_PLAYER_SYNC = 207,
PACKET_MARKERS_SYNC = 208,
PACKET_UNOCCUPIED_SYNC = 209,
PACKET_TRAILER_SYNC = 210,
PACKET_PASSENGER_SYNC = 211,
PACKET_SPECTATOR_SYNC = 212,
-- Gamestates
GAMESTATE_NONE = 0,
GAMESTATE_WAIT_CONNECT = 1,
GAMESTATE_AWAIT_JOIN = 2,
GAMESTATE_CONNECTED = 3,
GAMESTATE_RESTARTING = 4,
GAMESTATE_DISCONNECTED = 5,
-- BitStream
BS_TYPE_BYTE = 0,
BS_TYPE_BOOL = 1,
BS_TYPE_SHORT = 2,
BS_TYPE_INT = 3,
BS_TYPE_FLOAT = 4,
BS_TYPE_ARRAY = 5,
BS_TYPE_BITSTREAM = 6,
-- Priorities
SYSTEM_PRIORITY = 0,
HIGH_PRIORITY = 1,
MEDIUM_PRIORITY = 2,
LOW_PRIORITY = 3,
-- Reliability
UNRELIABLE = 6,
UNRELIABLE_SEQUENCED = 7,
RELIABLE = 8,
RELIABLE_ORDERED = 9,
RELIABLE_SEQUENCED = 10,
-- Sendrates
ONFOOTSENDRATE = 1,
INCARSENDRATE = 2,
AIMSENDRATE = 3,
-- SAMP Limits
MAX_PLAYERS = 1004,
MAX_VEHICLES = 2000,
MAX_PICKUPS = 4096,
MAX_OBJECTS = 1000,
MAX_GANGZONES = 1024,
MAX_3DTEXTS = 2048,
MAX_TEXTDRAWS = 2048,
MAX_CLIENTCMDS = 144,
MAX_MENUS = 128,
-- Text Styles
FCR_NONE = 0x0,
FCR_BOLD = 0x1,
FCR_ITALICS = 0x2,
FCR_BORDER = 0x4,
FCR_SHADOW = 0x8,
FCR_UNDERLINE = 0x10,
FCR_STRIKEOUT = 0x20,
-- SAMP SCM Events
SCMEVENT_PAINTJOB = 1,
SCMEVENT_UPGRADE = 2,
SCMEVENT_COLOR = 3,
SCMEVENT_MODSHOPENTEREXIT = 4,
-- Special Actions
SPECIAL_ACTION_NONE = 0,
SPECIAL_ACTION_DUCK = 1,
SPECIAL_ACTION_USEJETPACK = 2,
SPECIAL_ACTION_ENTER_VEHICLE = 3,
SPECIAL_ACTION_EXIT_VEHICLE = 4,
SPECIAL_ACTION_DANCE1 = 5,
SPECIAL_ACTION_DANCE2 = 6,
SPECIAL_ACTION_DANCE3 = 7,
SPECIAL_ACTION_DANCE4 = 8,
SPECIAL_ACTION_HANDSUP = 10,
SPECIAL_ACTION_USECELLPHONE = 11,
SPECIAL_ACTION_SITTING = 12,
SPECIAL_ACTION_STOPUSECELLPHONE = 13,
SPECIAL_ACTION_DRINK_BEER = 20,
SPECIAL_ACTION_SMOKE_CIGGY = 21,
SPECIAL_ACTION_DRINK_WINE = 22,
SPECIAL_ACTION_DRINK_SPRUNK = 23,
SPECIAL_ACTION_CUFFED = 24,
SPECIAL_ACTION_CARRY = 25,
SPECIAL_ACTION_URINATE = 68,
-- SAMP Dialog Styles
DIALOG_STYLE_MSGBOX = 0,
DIALOG_STYLE_INPUT = 1,
DIALOG_STYLE_LIST = 2,
DIALOG_STYLE_PASSWORD = 3,
DIALOG_STYLE_TABLIST = 4,
DIALOG_STYLE_TABLIST_HEADERS = 5,
-- SAMP Cursor Modes
CMODE_DISABLED = 0,
CMODE_LOCKKEYS_NOCURSOR = 1,
CMODE_LOCKCAMANDCONTROL = 2,
CMODE_LOCKCAM = 3,
CMODE_LOCKCAM_NOCURSOR = 4,
-- Primitive Types
D3DPT_POINTLIST = 1,
D3DPT_LINELIST = 2,
D3DPT_LINESTRIP = 3,
D3DPT_TRIANGLELIST = 4,
D3DPT_TRIANGLESTRIP = 5,
D3DPT_TRIANGLEFAN = 6
}
-- Copy table 'sampfuncs' to a global scope
for k, v in pairs(sampfuncs) do
_G[k] = v
end
return sampfuncs
|
minetest.register_craftitem("bitumen:blueprint_paper", {
description = "Blueprint Paper",
stack_max = 99,
inventory_image = "default_paper.png^[colorize:blue:120",
groups = {flammable = 3},
})
minetest.register_craftitem("bitumen:blueprint_book", {
description = "Blueprint Paper",
stack_max = 99,
inventory_image = "default_book.png^[colorize:blue:120",
groups = {flammable = 3},
})
bitumen.registered_blueprints = {
-- ["bitumen:cement_mixer_blueprint"] = 1,
}
-- registers the blueprint item, adds it to the bookshelf, and registers the constructor craft recipe
bitumen.register_blueprint = function(def)
local name = def.name.."_blueprint"
local parent_def = minetest.registered_nodes[def.name]
if parent_def == nil then
print("Warning: parent node not registered yet. Place bitumen.register_blueprint call after node registration.")
return
end
minetest.register_craftitem(name, {
description = parent_def.description.." Blueprint",
stack_max = 1,
inventory_image = parent_def.inventory_image .. "^bitumen_blueprint.png",
groups = {flammable = 3},
})
if not def.no_constructor_craft then
-- the actual constructor must be registered elsewhere
minetest.register_craft({
output = def.name..'_constructor',
recipe = {
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'default:steel_ingot', name, 'default:steel_ingot'},
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
}
})
end
bitumen.registered_blueprints[name] = def
end
local blueprint_bookshelf_formspec =
"size[8,8;]" ..
default.gui_bg ..
default.gui_bg_img ..
default.gui_slots ..
"list[context;blueprints;0,0.3;8,3;]" ..
"list[current_player;main;0,3.85;8,1;]" ..
"list[current_player;main;0,5.08;8,3;8]" ..
"listring[context;blueprints]" ..
"listring[current_player;main]" ..
default.get_hotbar_bg(0,3.85)
minetest.register_node("bitumen:blueprint_bookshelf", {
description = "Blueprint Bookshelf",
tiles = {"default_junglewood.png", "default_junglewood.png", "default_junglewood.png",
"default_junglewood.png", "default_bookshelf.png^[colorize:blue:120", "default_junglewood.png"},
paramtype2 = "facedir",
is_ground_content = false,
groups = {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3},
sounds = default.node_sound_wood_defaults(),
stack_max = 1,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", blueprint_bookshelf_formspec)
local inv = meta:get_inventory()
inv:set_size("blueprints", 8 * 3)
-- fill in the known blueprints
local list = {}
for name,def in pairs(bitumen.registered_blueprints) do
table.insert(list, name)
end
inv:set_list("blueprints", list)
end,
allow_metadata_inventory_put = function(pos, listname, index, stack)
return 0
end,
allow_metadata_inventory_move = function(pos, listname, index, stack)
return 0
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
-- print(" -- "..listname.. " " ..index.." "..dump(stack))
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory(meta)
inv:set_stack(listname, index, stack)
end,
})
|
local popup = require"plenary.popup"
local M = {}
-- State
local _hmap_input_bufwin = nil
local _hmap_input_win_id = nil
local _hmap_results_bufwin = nil
local _hmap_results_win_id = nil
local _hmap_results = nil
local _hmap_maps = nil
-- Locals
local function list(m)
local map_list = {}
local maps = vim.api.nvim_get_keymap(m)
for i, map in ipairs(maps) do
map_list[i] = {
rhs = map.rhs,
lhs = map.lhs
}
end
return map_list
end
local function close_window(win_id)
if win_id and vim.api.nvim_win_is_valid(win_id) then
vim.api.nvim_win_close(win_id, true)
end
end
local function create_window(opts)
local borderchars = { "─", "│", "─", "│", "╭", "╮", "╯", "╰" }
-- Creates a temporary buffer
local bufwin = vim.api.nvim_create_buf(false, true)
-- Create the input popup
local win_id, _ = popup.create(bufwin, {
title = opts.title,
highlight = opts.highlight,
line = math.floor(((vim.o.lines - opts.height) / 2) - 1) - opts.line_offset,
col = math.floor((vim.o.columns - opts.width) / 2) - opts.col_offset,
minwidth = opts.width,
minheight = opts.height,
borderchars = borderchars
})
return {
bufwin = bufwin,
win_id = win_id,
}
end
local function set_window_options(winbuf, content, menu_name)
vim.api.nvim_buf_set_name(winbuf, menu_name)
vim.api.nvim_buf_set_lines(winbuf, 0, #content, false, content)
vim.api.nvim_buf_set_option(winbuf, "filetype", "hmap")
vim.api.nvim_buf_set_option(winbuf, 'swapfile', false)
vim.api.nvim_buf_set_option(winbuf, "buftype", "nofile")
-- Clear on hide
vim.api.nvim_buf_set_option(winbuf, 'bufhidden', 'wipe')
end
local function is_window_open()
return (_hmap_input_win_id ~= nil and vim.api.nvim_win_is_valid(_hmap_input_win_id)) and (_hmap_results ~= nil and vim.api.nvim_win_is_valid(_hmap_results_win_id))
end
local function update_results(value)
if value == nil or value == "" then
_hmap_results = _hmap_maps
return
end
vim.api.nvim_buf_set_option(_hmap_results_bufwin, "modifiable", true)
local filtered_results = {}
local lvalue = string.lower(value)
-- Filter _hmap_results by value
for _, map_str in ipairs(_hmap_maps) do
local lmap_str = string.lower(map_str)
if string.find(lmap_str, lvalue) then
table.insert(filtered_results, map_str)
end
end
_hmap_results = filtered_results
vim.api.nvim_buf_set_lines(_hmap_results_bufwin, 0, -1, true, filtered_results)
vim.api.nvim_buf_set_option(_hmap_results_bufwin, "modifiable", false)
end
-- API
M.toggle_window = function()
local is_open = is_window_open()
if is_open then
close_window(_hmap_input_win_id)
close_window(_hmap_results_win_id)
_hmap_input_win_id = nil
_hmap_input_bufwin = nil
_hmap_results_win_id = nil
_hmap_results_bufwin = nil
return
end
local content = list("n")
-- Results window
local results_win_info = create_window({
title = "Results",
width = 60,
height = 10,
line_offset = 0,
col_offset = 0,
highlight = "HmapResultsWindow"
})
-- Input window
local input_win_info = create_window({
title = "Input",
width = 60,
height = 1,
line_offset = -8,
col_offset = 0,
highlight = "HmapInputWindow"
})
_hmap_input_win_id = input_win_info.win_id
_hmap_input_bufwin = input_win_info.bufwin
_hmap_results_win_id = results_win_info.win_id
_hmap_results_bufwin = results_win_info.bufwin
-- Content needs to be strings currently list of tables
for idx = 1, #content do
content[idx] = string.format("%s --- %s", content[idx].lhs, content[idx].rhs)
end
_hmap_results = content
_hmap_maps = content
set_window_options(_hmap_input_bufwin, {}, "hmap-input-menu")
set_window_options(_hmap_results_bufwin, _hmap_results, "hmap-results-menu")
vim.api.nvim_buf_set_option(_hmap_results_bufwin, "modifiable", false)
-- Set toggle bindings to input window as it will be the only interactible window
vim.api.nvim_buf_set_keymap(
_hmap_input_bufwin,
"n",
"q",
"<Cmd>lua require('hmap').toggle_window()<CR>",
{ silent = true }
)
vim.api.nvim_buf_set_keymap(
_hmap_input_bufwin,
"n",
"<ESC>",
"<Cmd>lua require('hmap').toggle_window()<CR>",
{ silent = true }
)
-- Start in insert mode
vim.cmd [[startinsert]]
vim.cmd("autocmd BufLeave <buffer> ++nested ++once silent lua require('hmap').toggle_window()")
-- Bind on change events
vim.cmd(
string.format(
"autocmd TextChanged,TextChangedI <buffer=%s> lua require('hmap').on_input_change()",
_hmap_input_bufwin
)
)
end
M.on_input_change = function()
local buffval = vim.api.nvim_buf_get_lines(_hmap_input_bufwin, 0, -1, false)
local value = table.concat(buffval, "\n")
update_results(value)
end
return M
|
local config = require'nlspsettings.config'
local nlspsettings = require'nlspsettings'
local a = vim.api
local uv = vim.loop
local M = {}
--- Returns the name of the server connected to the current buffer.
---@param bufnr number? buffer number
---@return string server_name
local get_server_name = function(bufnr)
vim.validate {
bufnr = { bufnr, 'n', true }
}
local server_names = {}
local clients = vim.lsp.buf_get_clients(bufnr)
for _, _client in pairs(clients) do
if not vim.tbl_contains(server_names, _client.name) then
table.insert(server_names, _client.name)
end
end
if #server_names == 0 then
return
end
local server_name = server_names[1]
if #server_names > 1 then
local list = {}
for i, v in ipairs(server_names) do
table.insert(list, string.format('%d: %s', i, v))
end
table.insert(list, 1, 'Select server: ')
local idx = vim.fn.inputlist(list)
if idx == 0 then
return
end
server_name = server_names[idx]
end
return server_name
end
--- Open a settings file that matches the current buffer
M.open_buf_config = function()
local server_name = get_server_name()
if server_name == nil then
return
end
M.open_config(server_name)
end
---Open the settings file for the specified server.
---@param server_name string
M.open_config = function(server_name)
vim.validate {
server_name = { server_name, 's' }
}
local home = config.get('config_home')
if vim.fn.isdirectory(home) == 0 then
if vim.fn.confirm(string.format([[Config directory "%s" not exists, create?]], home), "&Yes\n&No", 1) ~= 1 then
return
end
vim.fn.mkdir(home, 'p')
end
local path = string.format('%s/%s.json', home, server_name)
-- If the file does not exist, LSP will not be able to complete it, so create it
do
local stat = uv.fs_stat(path)
local exists = not vim.tbl_isempty(stat or {})
if not exists then
local mode = tonumber('644', 8)
local fd = uv.fs_open(path, "w", mode)
if not fd then error('Could not create file: ' .. path) end
uv.fs_close(fd)
end
end
local cmd = (vim.api.nvim_buf_get_option(0, 'modified') and 'split') or 'edit'
vim.api.nvim_command(string.format([[%s %s]], cmd, path))
end
---Update the setting values.
---@param server_name string
M.update_settings = function(server_name)
vim.cmd [[redraw]]
local errors = nlspsettings.update_settings(server_name)
if errors then
a.nvim_echo({{string.format(' Nlsp[%s][Error] Failed to update the settings.', server_name), 'ErrorMsg'}}, false, {})
else
a.nvim_echo({{string.format(' Nlsp[%s][Info] Success to update the settings.', server_name), 'Normal'}}, false, {})
end
end
---What to do when BufWritePost fires
---@param afile string
M._BufWritePost = function(afile)
local server_name = string.match(afile, '([^/]+)%.json$')
M.update_settings(server_name)
end
return M
|
title = "My Webpage"
page = [[
<html !DOCTYPE="html">
<head>
<title>]] .. title .. [[</title>
</head>
<body>
</body>
</html>
]]
io.write(page)
|
requireInjector(getfenv(1))
local Config = require('config')
local Event = require('event')
local UI = require('ui')
local Util = require('util')
multishell.setTitle(multishell.getCurrent(), 'Files')
UI:configure('Files', ...)
local config = {
showHidden = false,
showDirSizes = false,
}
Config.load('Files', config)
local copied = { }
local marked = { }
local directories = { }
local cutMode = false
function formatSize(size)
if size >= 1000000 then
return string.format('%dM', math.floor(size/1000000, 2))
elseif size >= 1000 then
return string.format('%dK', math.floor(size/1000, 2))
end
return size
end
local Browser = UI.Page {
menuBar = UI.MenuBar {
buttons = {
{ text = '^-', event = 'updir' },
{ text = 'File', event = 'dropdown', dropdown = 'fileMenu' },
{ text = 'Edit', event = 'dropdown', dropdown = 'editMenu' },
{ text = 'View', event = 'dropdown', dropdown = 'viewMenu' },
},
},
fileMenu = UI.DropMenu {
buttons = {
{ text = 'Run', event = 'run' },
{ text = 'Edit e', event = 'edit' },
{ text = 'Shell s', event = 'shell' },
UI.Text { value = ' ------------ ' },
{ text = 'Quit q', event = 'quit' },
UI.Text { },
}
},
editMenu = UI.DropMenu {
buttons = {
{ text = 'Cut ^x', event = 'cut' },
{ text = 'Copy ^c', event = 'copy' },
{ text = 'Paste ^v', event = 'paste' },
UI.Text { value = ' --------------- ' },
{ text = 'Mark m', event = 'mark' },
{ text = 'Unmark all u', event = 'unmark' },
UI.Text { value = ' --------------- ' },
{ text = 'Delete del', event = 'delete' },
UI.Text { },
}
},
viewMenu = UI.DropMenu {
buttons = {
{ text = 'Refresh r', event = 'refresh' },
{ text = 'Hidden ^h', event = 'toggle_hidden' },
{ text = 'Dir Size ^s', event = 'toggle_dirSize' },
UI.Text { },
}
},
grid = UI.ScrollingGrid {
columns = {
{ heading = 'Name', key = 'name' },
{ key = 'flags', width = 2 },
{ heading = 'Size', key = 'fsize', width = 6 },
},
sortColumn = 'name',
y = 2, ey = -2,
},
statusBar = UI.StatusBar {
columns = {
{ key = 'status' },
{ key = 'totalSize', width = 6 },
},
},
accelerators = {
q = 'quit',
e = 'edit',
s = 'shell',
r = 'refresh',
space = 'mark',
backspace = 'updir',
m = 'move',
u = 'unmark',
d = 'delete',
delete = 'delete',
[ 'control-h' ] = 'toggle_hidden',
[ 'control-x' ] = 'cut',
[ 'control-c' ] = 'copy',
paste = 'paste',
},
}
function Browser:enable()
UI.Page.enable(self)
self:setFocus(self.grid)
end
function Browser.grid:sortCompare(a, b)
if self.sortColumn == 'fsize' then
return a.size < b.size
elseif self.sortColumn == 'flags' then
return a.flags < b.flags
end
if a.isDir == b.isDir then
return a.name:lower() < b.name:lower()
end
return a.isDir
end
function Browser.grid:getRowTextColor(file, selected)
if file.marked then
return colors.green
end
if file.isDir then
return colors.cyan
end
if file.isReadOnly then
return colors.pink
end
return colors.white
end
function Browser.grid:getRowBackgroundColorX(file, selected)
if selected then
return colors.gray
end
return self.backgroundColor
end
function Browser.grid:eventHandler(event)
if event.type == 'copy' then -- let copy be handled by parent
return false
end
return UI.ScrollingGrid.eventHandler(self, event)
end
function Browser.statusBar:draw()
if self.parent.dir then
local info = '#:' .. Util.size(self.parent.dir.files)
local numMarked = Util.size(marked)
if numMarked > 0 then
info = info .. ' M:' .. numMarked
end
self:setValue('info', info)
self:setValue('totalSize', formatSize(self.parent.dir.totalSize))
UI.StatusBar.draw(self)
end
end
function Browser:setStatus(status, ...)
self.statusBar:timedStatus(string.format(status, ...))
end
function Browser:unmarkAll()
for k,m in pairs(marked) do
m.marked = false
end
Util.clear(marked)
end
function Browser:getDirectory(directory)
local s, dir = pcall(function()
local dir = directories[directory]
if not dir then
dir = {
name = directory,
size = 0,
files = { },
totalSize = 0,
index = 1
}
directories[directory] = dir
end
self:updateDirectory(dir)
return dir
end)
return s, dir
end
function Browser:updateDirectory(dir)
dir.size = 0
dir.totalSize = 0
Util.clear(dir.files)
local files = fs.listEx(dir.name)
if files then
dir.size = #files
for _, file in pairs(files) do
file.fullName = fs.combine(dir.name, file.name)
file.directory = directory
file.flags = ''
if not file.isDir then
dir.totalSize = dir.totalSize + file.size
file.fsize = formatSize(file.size)
else
if config.showDirSizes then
file.size = fs.getSize(file.fullName, true)
dir.totalSize = dir.totalSize + file.size
file.fsize = formatSize(file.size)
end
file.flags = 'D'
end
if file.isReadOnly then
file.flags = file.flags .. 'R'
end
if config.showHidden or file.name:sub(1, 1) ~= '.' then
dir.files[file.fullName] = file
end
end
end
-- self.grid:update()
-- self.grid:setIndex(dir.index)
self.grid:setValues(dir.files)
end
function Browser:setDir(dirName, noStatus)
self:unmarkAll()
if self.dir then
self.dir.index = self.grid:getIndex()
end
DIR = fs.combine('', dirName)
shell.setDir(DIR)
local s, dir = self:getDirectory(DIR)
if s then
self.dir = dir
elseif noStatus then
error(dir)
else
self:setStatus(dir)
self:setDir('', true)
return
end
if not noStatus then
self.statusBar:setValue('status', '/' .. self.dir.name)
self.statusBar:draw()
end
self.grid:setIndex(self.dir.index)
end
function Browser:run(path, ...)
local tabId = shell.openTab(path, ...)
multishell.setFocus(tabId)
end
function Browser:hasMarked()
if Util.size(marked) == 0 then
local file = self.grid:getSelected()
if file then
file.marked = true
marked[file.fullName] = file
self.grid:draw()
end
end
return Util.size(marked) > 0
end
function Browser:eventHandler(event)
local file = self.grid:getSelected()
if event.type == 'quit' then
Event.exitPullEvents()
elseif event.type == 'edit' and file then
self:run('edit', file.name)
elseif event.type == 'shell' then
self:run('sys/apps/shell')
elseif event.type == 'refresh' then
self:updateDirectory(self.dir)
self.grid:draw()
self:setStatus('Refreshed')
elseif event.type == 'toggle_hidden' then
config.showHidden = not config.showHidden
Config.update('Files', config)
self:updateDirectory(self.dir)
self.grid:draw()
if not config.showHidden then
self:setStatus('Hiding hidden')
else
self:setStatus('Displaying hidden')
end
elseif event.type == 'toggle_dirSize' then
config.showDirSizes = not config.showDirSizes
Config.update('Files', config)
self:updateDirectory(self.dir)
self.grid:draw()
if config.showDirSizes then
self:setStatus('Displaying dir sizes')
end
elseif event.type == 'mark' and file then
file.marked = not file.marked
if file.marked then
marked[file.fullName] = file
else
marked[file.fullName] = nil
end
self.grid:draw()
self.statusBar:draw()
elseif event.type == 'unmark' then
self:unmarkAll()
self.grid:draw()
self:setStatus('Marked files cleared')
elseif event.type == 'grid_select' or event.type == 'run' then
if file then
if file.isDir then
self:setDir(file.fullName)
else
self:run(file.name)
end
end
elseif event.type == 'updir' then
local dir = (self.dir.name:match("(.*/)"))
self:setDir(dir or '/')
elseif event.type == 'delete' then
if self:hasMarked() then
local width = self.statusBar:getColumnWidth('status')
self.statusBar:setColumnWidth('status', UI.term.width)
self.statusBar:setValue('status', 'Delete marked? (y/n)')
self.statusBar:draw()
self.statusBar:sync()
local _, ch = os.pullEvent('char')
if ch == 'y' or ch == 'Y' then
for k,m in pairs(marked) do
pcall(function()
fs.delete(m.fullName)
end)
end
end
marked = { }
self.statusBar:setColumnWidth('status', width)
self.statusBar:setValue('status', '/' .. self.dir.name)
self:updateDirectory(self.dir)
self.statusBar:draw()
self.grid:draw()
self:setFocus(self.grid)
end
elseif event.type == 'copy' or event.type == 'cut' then
if self:hasMarked() then
cutMode = event.type == 'cut'
Util.clear(copied)
Util.merge(copied, marked)
--self:unmarkAll()
self.grid:draw()
self:setStatus('Copied %d file(s)', Util.size(copied))
end
elseif event.type == 'paste' then
for k,m in pairs(copied) do
local s, m = pcall(function()
if cutMode then
fs.move(m.fullName, fs.combine(self.dir.name, m.name))
else
fs.copy(m.fullName, fs.combine(self.dir.name, m.name))
end
end)
end
self:updateDirectory(self.dir)
self.grid:draw()
self:setStatus('Pasted ' .. Util.size(copied) .. ' file(s)')
else
return UI.Page.eventHandler(self, event)
end
self:setFocus(self.grid)
return true
end
--[[-- Startup logic --]]--
local args = { ... }
Browser:setDir(args[1] or shell.dir())
UI:setPage(Browser)
Event.pullEvents()
UI.term:reset()
|
function breakpoint()
if(fa.sharedmemory("read", 0x00, 0x01, "") == "!")then
error("--- BREAK POINT ---")
end
sleep(0)
end
function putMessage(msg)
fa.sharedmemory("write", 0x01, 0xFE, msg)
end
fa.sharedmemory("write", 0x00, 0x01, "-")
|
-- supporting testfile; belongs to 'cl_spec.lua'
describe("Tests the busted command-line options", function()
it("is a test with a tag #tag1", function()
-- works by counting failure
error("error 1 on tag1")
end)
it("is a test with a tag #tag1", function()
-- works by counting failure
error("error 2 on tag1")
end)
it("is a test with a tag #tag2", function()
-- works by counting failure
error("error on tag2")
end)
it("is a test with a tag #tag3", function()
-- nothing here, makes it succeed
end)
it("is a test with two tags #tag3 #tag4", function ()
-- Always succeed
end)
end)
|
object_tangible_loot_creature_loot_collections_tusken_bantha_tooth = object_tangible_loot_creature_loot_collections_shared_tusken_bantha_tooth:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_tusken_bantha_tooth, "object/tangible/loot/creature/loot/collections/tusken_bantha_tooth.iff")
|
function factorial(n)
for i = 1, n-1 do
n = n*i
end
return n
end
io.write(factorial(4))
|
ModalClass(textentry)
function textentry:ctor(cb, title)
self:ModalInit()
self:ModalCallback(cb)
local scn = self.Elements
scn.content:SetFocus()
scn.title.Text = title
scn.content:OnTextEntered(function(name)
self:Close('ok', name, 0)
end)
scn.close:OnClick(function()
self:Close('cancel')
end)
end
|
local strsub = string.sub
local m = require 'lpeg'
local contiguous_byte_ranges = require 'parse.char.utf8.data.contiguous_byte_ranges'
local make_set = require 'parse.char.utf8.make.set'
local m_char = require 'parse.char.utf8'
local m_char_no_more = m_char * m.P(-1)
local char_tools = require 'parse.char.utf8.tools'
local next_char = char_tools.next
local c_char_rest = m.C(m_char) * m.C( m.P(1)^0 )
local map_proto = {}
local map_meta = {__index = map_proto}
local leaf_proto = {}
local leaf_meta = {__index = leaf_proto}
local branch_proto = {}
local branch_meta = {__index = branch_proto}
local conditional_proto = {}
local conditional_meta = {__index = conditional_proto}
local three_chars = m.C(m_char) * m.C(m_char) * m.C(m_char) * m.P(-1)
local function make_map(def)
local map = setmetatable({}, map_meta)
for i, entry in ipairs(def) do
if type(entry) == 'string' then
local first_char, rest = c_char_rest:match(entry)
if first_char == nil then
error('invalid utf-8 sequence')
end
map:add(first_char, rest)
elseif type(entry) == 'table' then
local step = entry.step
if step ~= nil then
-- table of ranges
for i, entry in ipairs(entry) do
local from_char, to_char, last_to_char = three_chars:match(entry)
if from_char == nil then
error('invalid utf-8 sequence')
end
if to_char > last_to_char then
goto done
end
map:add(from_char, to_char)
repeat
for i = 1, step do
to_char = next_char(to_char)
if to_char > last_to_char then
goto done
end
from_char = next_char(from_char)
end
map:add(from_char, to_char)
until to_char == last_to_char
::done::
end
else
local check_suffix = entry.check_suffix
if check_suffix ~= nil then
for i, entry in ipairs(entry) do
if type(entry) == 'string' then
local first_char, rest = c_char_rest:match(entry)
if first_char == nil then
error('invalid utf-8 sequence')
end
local conditional = setmetatable({}, conditional_meta)
conditional.char = first_char
conditional.on_success = rest
conditional.check_suffix = check_suffix
map:add(first_char, conditional)
else
local conditional = setmetatable({}, conditional_meta)
conditional.char = entry.char
conditional.check_suffix = entry.check_suffix
conditional.on_success = entry.on_success
conditional.on_failure = entry.on_failure
map:add(char, conditional)
end
end
end
end
end
end
return map
end
function map_proto:add(char, then_pattern)
local leaf
if #char == 1 then
leaf = self['']
if leaf == nil then
leaf = setmetatable({}, leaf_meta)
self[''] = leaf
end
leaf[char] = then_pattern
return
end
local context = self
for i = 1, #char-1 do
local c = strsub(char, i, i)
local new_context = context[c]
if new_context == nil then
if i == #char-1 then
new_context = setmetatable({}, leaf_meta)
else
new_context = setmetatable({}, branch_meta)
end
context[c] = new_context
end
context = new_context
end
context[strsub(char, -1)] = then_pattern
end
local function add_prefixed(dest, src, prefix)
for k,v in pairs(src) do
local m = getmetatable(v)
if m == branch_meta then
add_prefixed(dest, v, prefix..k)
elseif m == leaf_meta then
for k2,v in pairs(v) do
dest[#dest+1] = prefix .. k .. k2
end
end
end
end
function map_proto:make_set_from_keys()
local S_list = {}
add_prefixed(S_list, self, '')
return make_set { S=table.concat(S_list) }
end
function map_proto:make_set_from_values()
local S_list = {}
local function process(context, prefix)
for k,v in pairs(context) do
local meta = getmetatable(v)
if meta == branch_meta or meta == leaf_meta then
process(v, prefix .. k)
elseif meta == conditional_meta then
if v.on_success then
if not (type(v.on_success) == 'string' and m_char_no_more:match(v.on_success)) then
error('set values are not all single-character')
end
S_list[#S_list+1] = v.on_success
end
if v.on_failure then
if not (type(v.on_failure) == 'string' and m_char_no_more:match(v.on_failure)) then
error('set values are not all single-character')
end
S_list[#S_list+1] = v.on_failure
end
elseif type(v) == 'string' then
if not m_char_no_more:match(v) then
print(string.format(string.rep(' %02X', #v), string.byte(v, 1, #v)))
error('set values are not all single-character')
end
S_list[#S_list+1] = v
else
error('set values not all simple strings')
end
end
end
process(self, '')
return make_set { S=table.concat(S_list) }
end
local function get_patt(source, keys)
local m_patt = m.P(false)
for i = #keys, 1, -1 do
local key = keys[i]
local value = source[key]
local meta = getmetatable(value)
if meta == leaf_meta or meta == branch_meta then
local sub_keys = {}
for k in pairs(value) do
sub_keys[#sub_keys+1] = k
end
table.sort(sub_keys)
value = get_patt(value, sub_keys)
elseif meta == conditional_meta then
value = value:compile()
elseif type(value) == 'string' then
value = m.Cc(value)
end
m_patt = key * value + m_patt
end
return m_patt
end
function map_proto:compile()
local keys = {}
for k,v in pairs(self) do
keys[#keys+1] = k
end
table.sort(keys)
local m_one_char
if keys[1] == '' then
table.remove(keys, 1)
local p_1 = m.P(false)
local p_2 = m.P(false)
local cap_set = {}
for k,v in pairs(self['']) do
if type(v) == 'string' then
p_1 = p_1 + k
cap_set[k] = v
else
if getmetatable(v) == conditional_meta then
v = v:compile()
end
p_2 = p_2 + (k * v)
end
end
m_one_char = p_1 / cap_set + p_2
end
if keys[1] == nil then
return m_one_char
end
local m_multibyte = get_patt(self, keys)
return m_one_char + m_multibyte
end
local function reverse_aux(context, reversed_map, prefix)
for k,v in pairs(context) do
local meta = getmetatable(v)
if meta == branch_meta or meta == leaf_meta then
reverse_aux(v, reversed_map, prefix .. k)
elseif type(v) == 'string' then
if not m_char_no_more:match(v) then
error 'char mapping must be one-to-one to be reversible'
end
reversed_map:add(v, prefix .. k)
else
error 'char mapping must not include custom patterns to be reversible'
end
end
end
function map_proto:reverse()
local reversed_map = setmetatable({}, map_meta)
reverse_aux(self, reversed_map, '')
return reversed_map
end
local function clone(v)
local copy = setmetatable({}, getmetatable(v))
for k,v in pairs(v) do
local m = getmetatable(v)
if m == branch_meta or m == leaf_meta then
copy[k] = clone(v)
else
copy[k] = v
end
end
return copy
end
local function apply(self, other)
for k,v in pairs(other) do
local m = getmetatable(v)
if m == branch_meta or m == leaf_meta then
local my_v = rawget(self, k)
if my_v == nil then
self[k] = clone(v)
else
apply(my_v, v)
end
else
self[k] = v
end
end
end
function map_meta:__add(other)
if getmetatable(other) == nil then
other = make_map(other)
end
local copy = clone(self)
apply(copy, other)
return copy
end
-- get byte position of first possible match
-- gets false positives but not false negatives
-- pass true to ignore characters in ASCII-7 range
function map_proto:make_quick_scanner(higher_planes_only)
local p = m.P(false)
for k,v in pairs(self) do
if k == '' then
if not higher_planes_only then
for k in pairs(v) do
p = p + k
end
end
else
p = p + k
end
end
return (1 - p)^0 * m.Cp() * m.P(1)
end
function conditional_proto:compile()
local on_success = self.on_success
on_success = on_success and m.Cc(on_success) or m.P(true)
local on_failure = self.on_failure
on_failure = on_failure and m.Cc(on_failure) or m.P(false)
return self.check_suffix * on_success + on_failure
end
return make_map
|
client_script 'client.lua'
files {
'index.html',
'application.js'
}
ui_page 'index.html'
|
--
-- tests/api/test_directory_kind.lua
-- Tests the directory API value type.
-- Copyright (c) 2013 Jason Perkins and the Premake project
--
local suite = test.declare("api_directory_kind")
local api = premake.api
--
-- Setup and teardown
--
function suite.setup()
api.register {
name = "testapi",
kind = "directory",
list = true,
scope = "project"
}
test.createsolution()
end
function suite.teardown()
testapi = nil
end
--
-- Values should be converted to absolute paths, relative to
-- the currently running script.
--
function suite.convertsToAbsolute()
testapi "self/local"
test.isequal({os.getcwd() .. "/self/local"}, api.scope.project.testapi)
end
--
-- Check expansion of wildcards.
--
function suite.expandsWildcards()
testapi (_TESTS_DIR .. "/*")
test.istrue(table.contains(api.scope.project.testapi, _TESTS_DIR .. "/api"))
end
|
object_draft_schematic_droid_droid_texture_kit = object_draft_schematic_droid_shared_droid_texture_kit:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_droid_droid_texture_kit, "object/draft_schematic/droid/droid_texture_kit.iff")
|
object_mobile_outbreak_undead_scientist_m_hum_02 = object_mobile_shared_outbreak_undead_scientist_m_hum_02:new {
}
ObjectTemplates:addTemplate(object_mobile_outbreak_undead_scientist_m_hum_02, "object/mobile/outbreak_undead_scientist_m_hum_02.iff")
|
local un = encode.mime.unstructured_header_line
local mbl = encode.mime.mailbox_list_header_line
local function encode_container(parts, container)
if container.multipart then
local boundary
boundary = "BOUNDARY--" .. multirand.string(
24,
"123456789BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
)
parts[#parts+1] = "Content-Type: "
parts[#parts+1] = "multipart/"
parts[#parts+1] = container.multipart
parts[#parts+1] = "; boundary="
parts[#parts+1] = boundary
parts[#parts+1] = "\r\n\r\nMIME multipart\r\n" -- last \r\n optional
for idx, sub_container in ipairs(container) do
parts[#parts+1] = "\r\n--"
parts[#parts+1] = boundary
parts[#parts+1] = "\r\n"
encode_container(parts, sub_container)
end
parts[#parts+1] = "\r\n--"
parts[#parts+1] = boundary
parts[#parts+1] = "--\r\n"
else
parts[#parts+1] = "Content-Type: "
parts[#parts+1] = container.content_type or "text/plain"
parts[#parts+1] = "\r\n"
if container.content_id then
parts[#parts+1] = "Content-ID: <"
parts[#parts+1] = container.content_id
parts[#parts+1] = ">\r\n"
end
if container.attachment_filename then
parts[#parts+1] = "Content-Disposition: attachment; filename="
parts[#parts+1] = encode.mime.atom_token(
container.attachment_filename
)
parts[#parts+1] = "\r\n"
end
if container.binary then
parts[#parts+1] = "Content-Transfer-Encoding: base64\r\n\r\n"
parts[#parts+1] = encode.mime.base64(container.content)
else
parts[#parts+1] =
"Content-Transfer-Encoding: quoted-printable\r\n\r\n"
parts[#parts+1] =
encode.mime.quoted_printable_text_content(container.content)
end
end
end
function encode.mime.mail(args)
local parts = {}
parts[#parts+1] = mbl("From", args.from)
parts[#parts+1] = mbl("Sender", args.sender)
parts[#parts+1] = mbl("Reply-To", args.reply_to)
parts[#parts+1] = mbl("To", args.to)
parts[#parts+1] = mbl("Cc", args.cc)
parts[#parts+1] = mbl("Bcc", args.bcc)
parts[#parts+1] = un("Subject", args.subject)
parts[#parts+1] = "MIME-Version: 1.0\r\n"
encode_container(parts, args)
return table.concat(parts)
end
|
--[[--ldoc desc
@Module BetView.lua
@Author JasonLiu
Date: 2018-10-24 19:13:25
Last Modified by: JasonLiu
Last Modified time: 2018-10-25 14:41:11
]]
local BetView = class("BetView", cc.load("boyaa").mvc.BoyaaView);
local BehaviorExtend = cc.load("boyaa").behavior.BehaviorExtend;
local Chip = require("app.demo.JasonLiu.widget.Chip2")
local Table = require("app.demo.JasonLiu.widget.Table")
local Clock = require("app.demo.JasonLiu.widget.Clock")
BehaviorExtend(BetView);
function BetView:ctor(data)
self:initData(data)
self:initView()
end
function BetView:initData(data)
self._data = {
selectValue = 1,
chipData = data.chipData or {},
betEnabled = false,
}
self.chipViews = {}
self.betTipss = {}
self.smallChipData = {}
end
--[[
@function initView 初始化View
]]
function BetView:initView()
self:addTable()
self:addChips()
self:addBetTipss()
self:addClock()
end
--[[
@function addTable 添加桌子
]]
function BetView:addTable()
local tableOffSetX, tableOffSetY = 0, 20
self.table = Table:create():move(tableOffSetX, tableOffSetY)
self.table:addClickListener(function (no)
if self._data.betEnabled then
-- 添加一个小筹码
self:addSmallChip(no, tableOffSetX, tableOffSetY)
-- 更新下注提示
self:updataBetTips(no)
end
end)
self:addChild(self.table)
end
--[[
@function addChips 添加筹码
]]
function BetView:addChips()
for i, data in ipairs(self._data.chipData) do
self.chipViews[i] = Chip:create(0, data.color, data.value)
local marginSize = 12
local chipWidth = self.chipViews[i]:getContentSize().width
self.chipViews[i]:move(-((chipWidth * #self._data.chipData + marginSize * (#self._data.chipData - 1)) / 2) + (chipWidth + marginSize) * (i - 1) + chipWidth / 2, -(self.table:getContentSize().height / 2 + marginSize))
self.chipViews[i]:addClickListener(function ()
self:updataChipsState(i)
end)
self:addChild(self.chipViews[i])
end
self:updataChipsState(self._data.selectValue)
end
--[[
@function addBetTipss 添加下注提示
]]
function BetView:addBetTipss()
for i, v in ipairs(self.table.areas) do
self.betTipss[i] = cc.Node:create():setLocalZOrder(999999):setVisible(false)
self.betTipss[i]:move(cc.p(v:getPosition()).x + v:getContentSize().width / 2, cc.p(v:getPosition()).y - v:getContentSize().height / 2 + 20)
cc.Sprite:create("Images/koprokdice/dice_room_self_bet_money_bg.png"):setContentSize(cc.size(20, 8)):setName("bg"):addTo(self.betTipss[i])
cc.Label:createWithTTF("0K", "fonts/HKYuanMini.ttf", 7, cc.size(0, 0), cc.TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_CENTER):setName("label"):setColor(cc.c3b(255,140,0)):addTo(self.betTipss[i])
self:addChild(self.betTipss[i])
end
end
--[[
@function addSmallChip 添加一个小筹码
]]
function BetView:addSmallChip(index, offSetX, offSetY)
local chip = Chip:create(1, self.chipViews[self._data.selectValue]._data.color):move(self.chipViews[self._data.selectValue]:getPosition())
local rx, ry = self.table:getRandomAreaPos(index, chip:getContentSize().width / 2)
local point = cc.p(self.table.areas[index]:getPosition())
chip:runAction(cc.MoveTo:create(self.table:getAreaMoveTime(index), cc.p(point.x + rx + offSetX, point.y - ry + offSetY)))
table.insert(self.smallChipData, {chip = chip, areaNo = index})
self:addChild(chip)
end
--[[
@function addClock 添加时钟
]]
function BetView:addClock()
self.clock = Clock:create():move(0, 88)
self.clock:setScale(self.table:getContentSize().width * 0.2 / self.clock:getContentSize().width)
self.clock:setVisible(false)
self:addChild(self.clock)
end
--[[
@function updataChipsState 更新筹码选中状态
]]
function BetView:updataChipsState(index)
self._data.selectValue = index
for i, v in ipairs(self.chipViews) do
if i ~= index then
v:setLight(false)
else
v:setLight(true)
end
end
end
--[[
@function updataBetTips 更新下注提示
]]
function BetView:updataBetTips(index)
self.betTipss[index]:setVisible(true)
local label = self.betTipss[index]:getChildByName("label")
local chipValue = self.chipViews[self._data.selectValue]._data.value
local oldValue = label:getString()
local sum = tonumber(string.sub(oldValue, 1, string.len(oldValue) - 1)) + tonumber(string.sub(chipValue, 1, string.len(chipValue) - 1))
label:setString(sum .. string.sub(oldValue, string.len(oldValue), string.len(oldValue)))
end
--[[
@function startCountdown 开始倒计时
]]
function BetView:startCountdown(time, callback)
self.clock:setVisible(true)
self.clock:countdown(function ()
self.clock:setVisible(false)
callback()
end, time, true)
end
--[[
@function setBetEnabled 设置是否能够下注
]]
function BetView:setBetEnabled(enabled)
self._data.betEnabled = enabled
end
--[[
@function updateWinningState 更新中奖状态
@param #data table 中奖数据
]]
function BetView:updateWinningState(data)
self.table:updateTableWinningArea(data)
end
--[[
@function clearSmallChip 清除小筹码
]]
function BetView:clearSmallChip()
for i, v in ipairs(self.smallChipData) do
self:removeChild(v.chip)
end
self.smallChipData = {}
end
--[[
@function resetBetTipss 重置下注提示
]]
function BetView:resetBetTipss()
for i, v in pairs(self.betTipss) do
v:getChildByName("label"):setString("0K")
v:setVisible(false)
end
end
return BetView;
|
--- Hardware timestamping.
local mod = {}
local ffi = require "ffi"
local dpdkc = require "dpdkc"
local dpdk = require "dpdk"
local device = require "device"
local eth = require "proto.ethernet"
local memory = require "memory"
local timer = require "timer"
local log = require "log"
local filter = require "filter"
local libmoon = require "libmoon"
local mg = require "moongen"
local timestamper = {}
timestamper.__index = timestamper
local ETH_DST = "3c:fd:fe:b7:e7:f5"
--- Create a new timestamper.
--- A NIC can only be used by one thread at a time due to clock synchronization.
--- Best current pratice is to use only one timestamping thread to avoid problems.
function configure(parser)
parser:description("Generates bidirectional CBR traffic with hardware rate control and measure latencies.")
parser:argument("dev1", "Device to transmit/receive from."):convert(tonumber)
parser:argument("dev2", "Device to transmit/receive from."):convert(tonumber)
parser:option("-r --rate", "Transmit rate in Mbit/s."):default(10000):convert(tonumber)
parser:option("-f --file", "Filename of the latency histogram."):default("histogram.csv")
end
function master(args)
local dev1 = device.config({port = args.dev1, rxQueues = 2, txQueues = 2})
local dev2 = device.config({port = args.dev2, rxQueues = 2, txQueues = 2})
device.waitForLinks()
mg.startTask("newTimestamper", dev1:getTxQueue(1), dev2:getRxQueue(1))
mg.waitForTasks()
end
function newTimestamper(txQueue, rxQueue, mem, udp, doNotConfigureUdpPort)
mem = mem or memory.createMemPool(function(buf)
-- defaults are good enough for us here
udp = 1
if udp then
buf:getUdpPtpPacket():fill{
ethSrc = txQueue,
ethDst = rxQueue,
}
else
printf("Sending Ptp Packets")
buf:getPtpPacket():fill{
ethSrc = txQueue,
}
end
end)
printf("Enabling timestamps")
txQueue:enableTimestamps()
rxQueue:enableTimestamps()
if udp and rxQueue.dev.supportsFdir then
rxQueue:filterUdpTimestamps()
elseif not udp then
rxQueue:filterL2Timestamps()
end
txBufs = mem:bufArray(1)
rxBufs = mem:bufArray(128)
txDev = txQueue.dev
rxDev = rxQueue.dev
while mg.running() do
measureLatency(function(buf) buf:getEthernetPacket().eth.dst:setString(ETH_DST) end,txBufs, rxBufs, txQueue, rxQueue, txDev, rxDev)
mg.sleepMillis(1000)
end
end
--- Try to measure the latency of a single packet.
--- @param pktSize optional, the size of the generated packet, optional, defaults to the smallest possible size
--- @param packetModifier optional, a function that is called with the generated packet, e.g. to modified addresses
--- @param maxWait optional (cannot be the only argument) the time in ms to wait before the packet is assumed to be lost (default = 15)
function measureLatency(packetModifier, txBufs, rxBufs, txQueue, rxQueue, txDev, rxDev)
udp = true
seq = 1
pktSize = pktSize or udp and 76 or 60
maxWait = (maxWait or 15) / 1000
txBufs:alloc(pktSize)
local buf = txBufs[1]
buf:enableTimestamps()
local expectedSeq = seq
seq = (seq + 1) % 2^16
if udp then
buf:getUdpPtpPacket().ptp:setSequenceID(expectedSeq)
else
buf:getPtpPacket().ptp:setSequenceID(expectedSeq)
end
local skipReconfigure
if packetModifier then
skipReconfigure = packetModifier(buf)
end
if udp then
-- change timestamped UDP port as each packet may be on a different port
--printf("Enabling timestamp for udp port %d\n", buf:getUdpPacket().udp:getDstPort())
rxQueue:enableTimestamps(buf:getUdpPacket().udp:getDstPort())
buf:getUdpPtpPacket():setLength(pktSize)
--buf:getUdpPtpPacket().eth:setDstString(ETH_DST)
--buf:getUdpPtpPacket():dump()
txBufs:offloadUdpChecksums()
if rxQueue.dev.reconfigureUdpTimestampFilter and not skipReconfigure then
-- i40e driver fdir filters are broken
-- it is not possible to match on flex bytes in udp packets without matching IPs and ports as well
-- so we have to look at that packet and reconfigure the filters
--printf("Reconfigure udp timestamp filter")
rxQueue.dev:reconfigureUdpTimestampFilter(rxQueue, buf:getUdpPacket())
end
end
syncClocks(txDev, rxDev)
-- clear any "leftover" timestamps
rxDev:clearTimestamps()
txQueue:send(txBufs)
local tx = txQueue:getTimestamp(500)
local numPkts = 0
if tx then
-- sent was successful, try to get the packet back (assume that it is lost after a given delay)
printf("Packet Sent")
local timer = timer:new(maxWait)
while timer:running() do
local rx = rxQueue:tryRecv(rxBufs, 1000)
numPkts = numPkts + rx
printf("num Packets = %d", numPkts)
local timestampedPkt = rxDev:hasRxTimestamp()
if not timestampedPkt then
-- NIC didn't save a timestamp yet, just throw away the packets
printf("Response is not timestamped")
rxBufs:freeAll()
else
-- received a timestamped packet (not necessarily in this batch)
printf("Response has timestamp")
for i = 1, rx do
local buf = rxBufs[i]
local timesync = rxQueue.dev.useTimsyncIds and buf:getTimesync() or 0
local seq = (udp and buf:getUdpPtpPacket() or buf:getPtpPacket()).ptp:getSequenceID()
if buf:hasTimestamp() and seq == expectedSeq and (seq == timestampedPkt or timestampedPkt == -1) then
-- yay!
local rxTs = rxQueue:getTimestamp(nil, timesync)
if not rxTs then
-- can happen if you hotplug cables
return nil, numPkts
end
rxBufs:freeAll()
local lat = rxTs - tx
if lat > 0 and lat < 2 * maxWait * 10^9 then
-- negative latencies may happen if the link state changes
-- (timers depend on a clock that scales with link speed on some NICs)
-- really large latencies (we only wait for up to maxWait ms)
-- also sometimes happen since changing to DPDK for reading the timing registers
-- probably something wrong with the DPDK wraparound tracking
-- (but that's really rare and the resulting latency > a few days, so we don't really care)
printf("Latency = %d ns", lat)
return lat, numPkts
end
elseif buf:hasTimestamp() and (seq == timestampedPkt or timestampedPkt == -1) then
-- we got a timestamp but the wrong sequence number. meh.
rxQueue:getTimestamp(nil, timesync) -- clears the register
-- continue, we may still get our packet :)
elseif seq == expectedSeq and (seq ~= timestampedPkt and timestampedPkt ~= -1) then
-- we got our packet back but it wasn't timestamped
-- we likely ran into the previous case earlier and cleared the ts register too late
rxBufs:freeAll()
return nil, numPkts
end
end
end
end
-- looks like our packet got lost :(
return nil, numPkts
else
-- happens when hotplugging cables
log:warn("Failed to timestamp packet on transmission")
timer:new(maxWait):wait()
return nil, numPkts
end
end
function syncClocks(dev1, dev2)
local regs1 = dev1.timeRegisters
local regs2 = dev2.timeRegisters
if regs1[1] ~= regs2[1]
or regs1[2] ~= regs2[2]
or regs1[3] ~= regs2[3]
or regs1[4] ~= regs2[4] then
log:fatal("NICs incompatible, cannot sync clocks")
end
dpdkc.libmoon_sync_clocks(dev1.id, dev2.id, unpack(regs1))
-- just to tell the driver that we are resetting the clock
-- otherwise the cycle tracker becomes confused on long latencies
dev1:resetTimeCounters()
dev2:resetTimeCounters()
end
|
-- s-125 ln
GT = {};
GT_t.ws = 0;
set_recursive_metatable(GT, GT_t.generic_stationary);
set_recursive_metatable(GT.chassis, GT_t.CH_t.STATIC);
GT.visual.shape = "5P73_LAUNCH";
GT.visual.shape_dstr = "5P73_LAUNCH_P_1";
GT.sensor = {};
set_recursive_metatable(GT.sensor, GT_t.SN_visual);
GT.sensor.height = 2.707;
--Burning after hit
GT.visual.fire_size = 0.3; --relative burning size
GT.visual.fire_pos[1] = 0; -- center of burn at long axis shift(meters)
GT.visual.fire_pos[2] = 0; -- center of burn shift at vertical shift(meters)
GT.visual.fire_pos[3] = 0; -- center of burn at transverse axis shift(meters)
GT.visual.fire_time = 500; --burning time (seconds)
-- weapon systems
GT.WS = {};
GT.WS.maxTargetDetectionRange = 28000;
local ws = GT_t.inc_ws();
GT.WS[ws] = {};
GT.WS[ws].center = 'CENTER_TOWER';
GT.WS[ws].angles = {
{math.rad(180), math.rad(-180), math.rad(0), math.rad(56)},
};
GT.WS[ws].drawArgument1 = 0;
GT.WS[ws].drawArgument2 = 1;
GT.WS[ws].omegaY = 0.323599;
GT.WS[ws].omegaZ = 0.174533;
GT.WS[ws].reference_angle_Z = math.rad(25);
GT.WS[ws].pidY = { p = 5, i = 0, d = 2, inn = 1};
GT.WS[ws].pidZ = { p = 5, i = 0, d = 2, inn = 1};
__LN = add_launcher(GT.WS[ws], GT_t.LN_t._S125HD);
__LN.depends_on_unit = {{{"snr s-125 tr", 1},},};
__LN.min_launch_angle = math.rad(9);
__LN = nil;
GT.Name = "5p73 V-601P ln";
GT.DisplayName = _("SAM SA-3 (V-601P) S-125 LN");
GT.DisplayNameShort = _("SA-3 (HDS)");
GT.Rate = 5;
GT.DetectionRange = 0;
GT.ThreatRange = GT.WS[ws].LN[1].distanceMax;
GT.mapclasskey = "P0091000082";
GT.attribute = {wsType_Ground,wsType_SAM,wsType_Miss,SA3_LN,
"AA_missile",
"MR SAM",
"SAM LL",
};
GT.tags =
{
"Air Defence",
"Launcher",
};
GT.category = "Air Defence";
|
require 'torch'
require 'xlua'
local evaluator = {}
function evaluator:evaluate(model, criterion, x, y, f_n, verbose)
local avg_score = 0
local cumulative_loss = 0
model:evaluate()
for t =1, #x do
if not verbose then
xlua.progress(t, #x)
end
local output = model:forward(x[t])
local score, onset, offset = criterion:predict(output)
local loss = criterion:task_loss(y[t], {onset, offset})
avg_score = avg_score + score
cumulative_loss = cumulative_loss + loss
-- printings
if verbose then
print('Filename: ' .. f_n[t] .. ', score: ' .. score .. ', y_hat: [' .. onset .. ', ' .. offset ..'], y: [' .. y[t][1] .. ', ' .. y[t][2] .. '], loss: ' .. loss)
end
end
cumulative_loss = cumulative_loss / #x
avg_score = avg_score / #x
-- printings
if verbose then
print('\nAverage score: ' .. avg_score)
print('Average cumulative loss: ' .. cumulative_loss)
end
return cumulative_loss, avg_score
end
return evaluator
|
--[[
Copyright 2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--taken from https://github.com/luvit/luvit/blob/master/deps/http-codec.lua and modified to run as normal lua module
local exports = {}
local string = require('string')
local find = string.find
local gsub = string.gsub
local char = string.char
local byte = string.byte
local format = string.format
local match = string.match
local gmatch = string.gmatch
function exports.urldecode(str)
str = gsub(str, '+', ' ')
str = gsub(str, '%%(%x%x)', function(h)
return char(tonumber(h, 16))
end)
str = gsub(str, '\r\n', '\n')
return str
end
function exports.urlencode(str)
if str then
str = gsub(str, '\n', '\r\n')
str = gsub(str, '([^%w ])', function(c)
return format('%%%02X', byte(c))
end)
str = gsub(str, ' ', '+')
end
return str
end
-- parse querystring into table. urldecode tokens
function exports.parse(str, sep, eq)
if not sep then sep = '&' end
if not eq then eq = '=' end
local vars = {}
for pair in gmatch(tostring(str), '[^' .. sep .. ']+') do
if not find(pair, eq) then
vars[exports.urldecode(pair)] = ''
else
local key, value = match(pair, '([^' .. eq .. ']*)' .. eq .. '(.*)')
if key then
vars[exports.urldecode(key)] = exports.urldecode(value)
end
end
end
return vars
end
return exports
|
return Def.ActorFrame{
Def.Quad{
InitCommand=cmd(FullScreen;diffuse,color("1,1,1,1"));
OnCommand=cmd(diffusealpha,0;sleep,0.8;linear,0.1;diffusealpha,1);
};
StartTransitioningCommand=function(self) SOUND:DimMusic(0,math.huge) end,
}
|
local exports = {}
local path = require('path')
local w = require('tables').wrap
exports.dirs = clink.dirmatches
exports.files = clink.filematches
exports.create_dirs_matcher = function (dir_pattern, show_dotfiles)
return function (token)
return w(clink.find_dirs(dir_pattern))
:filter(function(dir)
return clink.is_match(token, dir) and (path.is_real_dir(dir) or show_dotfiles)
end )
end
end
exports.create_files_matcher = function (file_pattern)
return function (token)
return w(clink.find_files(file_pattern))
:filter(function(file)
-- Filter out '.' and '..' entries as well
return clink.is_match(token, file) and path.is_real_dir(file)
end )
end
end
return exports
|
-- Command shortcuts
local opt = vim.opt
local api = vim.api
local fn = vim.fn
local cmd = vim.cmd
-- Configure plugins
require('packer').startup(function()
-- Packer can manage itself
use 'wbthomason/packer.nvim'
use {
'nvim-telescope/telescope.nvim',
requires = { {'nvim-lua/plenary.nvim'} },
config = function()
local actions = require 'telescope.actions'
local api = vim.api
local function set_map(map, cmd_name)
return api.nvim_set_keymap('n', map, "<cmd>lua require('telescope.builtin')."..cmd_name.."()<cr>", {
noremap = true,
silent = true
})
end
local function set_map_raw(map, cmd)
return api.nvim_set_keymap('n', map, cmd, {
noremap = true,
silent = true
})
end
set_map('ff', 'find_files')
set_map('fg', 'live_grep')
set_map('fb', 'buffers')
set_map('fh', 'help_tags')
set_map_raw('fd', '<cmd>Telescope find_files find_command=rg,--ignore,--hidden,--files<cr>')
set_map_raw('<C-P>', '<cmd>Telescope commands<cr>')
set_map_raw('tt', '<cmd>Telescope<cr>')
require 'telescope'.setup {
defaults = {
initial_mode = 'insert',
file_ignore_patterns = { '.git' },
mappings = {
i = {
["<esc>"] = actions.close,
["<C-j>"] = actions.move_selection_next,
["<C-k>"] = actions.move_selection_previous,
},
},
color_devicons = true,
},
pickers = {
buffers = {
mappings = {
n = {
["<c-d>"] = require'telescope.actions'.delete_buffer,
}
}
}
},
}
end
}
use {
'nvim-treesitter/nvim-treesitter',
config = function()
require 'nvim-treesitter.configs'.setup {
ensure_installed = 'maintained',
highlight = {enable = true}
}
end,
}
-- Language Server Protocol
use {
'neovim/nvim-lspconfig',
config = function()
local on_attach = function(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
-- Enable completion triggered by <c-x><c-o>
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
end
require'lspconfig'.ccls.setup{ -- https://github.com/MaskRay/ccls/wiki
on_attach = on_attach,
init_options = {
cache = {
directory = ".ccls-cache"
}
}
}
end,
}
use {
'hoob3rt/lualine.nvim',
requires = {'kyazdani42/nvim-web-devicons', opt = true},
config = function()
require 'lualine'.setup{
options = {
theme = 'ayu_mirage'
}
}
end
}
-- File tree
use {
'kyazdani42/nvim-tree.lua',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require'nvim-tree'.setup{}
vim.api.nvim_set_keymap('n', '<space>tre', '<cmd>NvimTreeToggle<cr>', { noremap = true, silent = true })
end
}
use {
'lewis6991/gitsigns.nvim',
requires = { 'nvim-lua/plenary.nvim' },
config = function()
require'gitsigns'.setup{
current_line_blame = true
}
end
}
-- Completion list
use {
"hrsh7th/nvim-cmp",
requires = {
'hrsh7th/cmp-nvim-lsp',
'hrsh7th/cmp-buffer'
},
config = function()
local cmp = require 'cmp'
cmp.setup {
mapping = {
['<C-p>'] = cmp.mapping.select_prev_item(),
['<S-Tab>'] = cmp.mapping.select_prev_item(),
['<C-n>'] = cmp.mapping.select_next_item(),
['<Tab>'] = cmp.mapping.select_next_item(),
['<C-d>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.close(),
['<CR>'] = cmp.mapping.confirm {
behavior = cmp.ConfirmBehavior.Replace,
select = true,
},
},
sources = {
{ name = 'nvim_lsp' },
{ name = 'buffer' }
},
}
end
}
-- Fix for tabing for next in list
local function replace_code(str)
return api.nvim_replace_termcodes(str, true, true, true)
end
function _G.smart_tab()
return fn.pumvisible() == 1 and replace_code'<C-n>' or replace_code'<Tab>'
end
api.nvim_set_keymap('i', '<Tab>', 'v:lua.smart_tab()', {expr = true, noremap = true})
end)
-- User configs
-- Mouse support
opt.mouse = 'a'
-- Whitespaces
opt.listchars = 'tab:› ,trail:~,extends:>,precedes:<,space:∙'
opt.list = true -- Show whitespace
-- Line numbers
opt.nu = true -- Turn on line number
opt.rnu = true -- Set as relative mode
-- Tab and spaces
opt.expandtab = true
opt.smarttab = true
opt.shiftwidth = 4
opt.tabstop = 4
opt.lbr = true -- linebreak
opt.tw = 500 -- text width
opt.ai = true -- Auto indent
opt.si = true -- Smart indent
-- Misc
opt.completeopt = {'menuone', 'noinsert', 'noselect'}
opt.wildmode = {'list', 'longest'} -- Command-line completion mode
opt.splitbelow = true -- Put new windows below current
opt.splitright = true -- Put new windows right of current
-- Line wrap
opt.wrap = false
-- Enable Background buffers
opt.hidden = true
-- Global options
vim.o.wildmenu = true -- Command line completion mode
vim.o.wildmode = 'full' -- Command line completion mode
-- MAP ESCAPE TO jk
api.nvim_set_keymap('i', 'jk', '<Esc>', { noremap = true })
-- Turn off line numbers in terminal mode
api.nvim_command('autocmd TermOpen * setlocal nonu nornu nolist')
api.nvim_command('autocmd TermEnter * setlocal nonu nornu nolist')
-- Escape from insert mode in terminal
api.nvim_set_keymap('t', '<Esc>', '<C-\\><C-n>', { noremap = true })
|
-------------------------------------------------------------------------------
-- コマンド ノーマルモード 挿入モード コマンドラインモード ビジュアルモード
-- map/noremap @ - - @
-- nmap/nnoremap @ - - -
-- imap/inoremap - @ - -
-- cmap/cnoremap - - @ -
-- vmap/vnoremap - - - @
-- map!/noremap! - @ @ -
-------------------------------------------------------------------------------
-- <CR>: 次の行へ
vim.api.nvim_set_keymap('n', '<CR>', ':<C-u>call append(".", "")<CR>', {noremap = true, silent = true} )
-- <Tab>: 次のバッファへ
vim.api.nvim_set_keymap( 'n', '<Tab>', ':bnext<CR>', {noremap = true, silent = true} )
-- MiddleMouse の無効化
vim.api.nvim_set_keymap('', '<MiddleMouse>', '<Nop>', {})
vim.api.nvim_set_keymap('', '<2-MiddleMouse>', '<Nop>', {})
vim.api.nvim_set_keymap('', '<3-MiddleMouse>', '<Nop>', {})
vim.api.nvim_set_keymap('', '<4-MiddleMouse>', '<Nop>', {})
vim.api.nvim_set_keymap('i', '<MiddleMouse>', '<Nop>', {})
vim.api.nvim_set_keymap('i', '<2-MiddleMouse>', '<Nop>', {})
vim.api.nvim_set_keymap('i', '<3-MiddleMouse>', '<Nop>', {})
-- EXモード: 無効化
vim.api.nvim_set_keymap('n', 'q', '<Nop>', {noremap = true})
vim.api.nvim_set_keymap('n', 'Q', '<Nop>', {noremap = true})
-- Y: 行末までヤンク
vim.api.nvim_set_keymap('n', 'Y', 'y$', {noremap = true})
-- +/-: 数字を変化させる
vim.api.nvim_set_keymap('n', '+', '<C-a>', {noremap = true})
vim.api.nvim_set_keymap('n', '-', '<C-x>', {noremap = true})
-- <Esc><Esc>: ハイライトの切り替え
vim.api.nvim_set_keymap('n', '<Esc><Esc>', ':<C-u>set nohlsearch!<CR>', {noremap = true, silent = true})
-- <ESC>: terminalモードからコマンドモードに変更
vim.api.nvim_set_keymap('t', '<ESC>', '<C-\\><C-n>', {noremap = true, silent = true})
-- Window {{{
-- <Space>w: Windowモード
vim.api.nvim_set_keymap('n', '[Window]', '<Nop>', {noremap = true})
vim.api.nvim_set_keymap('n', '<Space>w', '[Window]', {})
-- 分割
-- [Window]s 横分割
vim.api.nvim_set_keymap('n', '[Window]s', ':<C-u>split<CR>', {noremap = true, silent = true})
-- [Window]w 縦分割
vim.api.nvim_set_keymap('n', '[Window]w', ':<C-u>vsplit<CR>', {noremap = true, silent = true})
-- 移動
vim.api.nvim_set_keymap('n', '[Window]h', ':<C-u>h', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '[Window]j', ':<C-u>j', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '[Window]k', ':<C-u>k', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '[Window]l', ':<C-u>L', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '[Window]H', ':<C-u>H', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '[Window]J', ':<C-u>J', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '[Window]K', ':<C-u>K', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '[Window]L', ':<C-u>L', {noremap = true, silent = true})
-- }}}
|
object_building_kashyyyk_thm_kash_zonegate_gate_simple = object_building_kashyyyk_shared_thm_kash_zonegate_gate_simple:new {
}
ObjectTemplates:addTemplate(object_building_kashyyyk_thm_kash_zonegate_gate_simple, "object/building/kashyyyk/thm_kash_zonegate_gate_simple.iff")
|
module( "search", package.seeall )
local Providers = {}
function AddProvider( func, id )
local prov = {
func = func,
}
if ( id ) then
Providers[ id ] = prov
else
table.insert( Providers, prov )
end
end
function GetResults( str, types, maxResults )
if ( !maxResults || maxResults < 1 ) then maxResults = 1024 end
local str = str:lower()
if ( str == "" ) then return {} end
local results = {}
for k, v in pairs( Providers ) do
if ( isstring( types ) ) then
if ( types != k ) then continue end
elseif ( istable( types ) ) then
if ( !table.HasValue( types, k ) ) then continue end
end
local tbl = v.func( str )
for _, e in pairs( tbl ) do
table.insert( results, e )
end
if ( #results >= maxResults ) then break end
end
-- Todo. Sort, weighted?
return results
end
|
local Addonname, Addontable = ...
-- Maw of Souls
Addontable.maw = {
-- Ymiron, the Fallen King
133637, -- Utgarde Royal Signet
133644, -- Memento of Angerboda
137326, -- Fragmented Meteorite Whetstone
133629, -- Crown of Fallen Kings
133682, -- Northern Gale
133616, -- Legwraps of Unworthy Souls
133614, -- Frost Stricken Cuffs
133625, -- Shoulderguards of Bane
134199, -- Biornskin Belt
134217, -- Bonespeaker Gloves
134210, -- Tideskorn Sabatons
-- Harbaron
133632, -- Void Touched Wristplates
133771, -- Seacursed Wrap
133768, -- Harbarons Tether
137324, -- Bleak Underworld Treads
137327, -- Relinquishing Grip of Helheim
133611, -- Soul Stitched Robes
137325, -- Afterlife Manacles
133645, -- Naglfar Fare
134183, -- Skoldiir Legguards
134197, -- Biornskin Vest
134211, -- Tideskorn Coif
134218, -- Bonespeaker Leggings
-- Helya
137331, -- Belt of Eternal Torment
133636, -- Brysngamen Torc of Helheim
137329, -- Figurehead of The Naglfar
133634, -- Grasping Tentacle Loop
133618, -- Kraken Hide Helm
137332, -- Mantle of The Dark Sea
133608, -- Mistbound Helarjar Footwraps
137334, -- Salt Laden Stompers
133684, -- Screams of The Unworthy
133683, -- Seacursed Mist
137333, -- Seaworthy Deck Hands
134184, -- Skoldiir Shoulderguards
133770, -- Slack Tide Girdle
133769, -- Tempered Seaborne Leggings
134195, -- Biornskin Gloves
134221, -- Bonespeaker Mantle
134214, -- Tideskorn Vest
}
|
surface.CreateFont("lambda_sb_def", {font = "Verdana", size = 22, weight = 400, antialias = true})
surface.CreateFont("lambda_sb_num", {font = "HudHintTextLarge", size = 18, weight = 600, antialias = true})
surface.CreateFont("lambda_sb_def_sm", {font = "Roboto Light", size = 16, weight = 300, antialias = true})
surface.CreateFont("lambda_sb_def_nsm", {font = "DermaLarge", size = 26, weight = 600, antialias = true})
local lambda_logo = Material("lambda/logo_512.png", "noclamp smooth")
local frag_logo = Material("lambda/icons/gun.png", "noclamp smooth")
local death_logo = Material("lambda/icons/skull.png", "noclamp smooth")
local time_logo = Material("lambda/icons/stopwatch.png", "noclamp smooth")
local ping_logo = Material("lambda/icons/ping.png", "noclamp smooth")
local gradientL = Material("vgui/gradient-l")
local gradientR = Material("vgui/gradient-r")
local orange = Color(255, 147, 30, 190)
local orange2 = Color(93, 93, 93, 230)
local dark = Color(0, 0, 0, 180)
local dark2 = Color(0, 0, 0, 150)
local white = Color(235, 235, 235, 235)
local SB_PING_METER = {}
local SB_PLY_LINE = {}
local SB_PANEL = {}
function SB_PING_METER:Init()
self:Dock(FILL)
self:DockMargin(0, 3, 0, 0)
self.PingNum = self:Add("DLabel")
self.PingNum:SetPos(18, 2)
self.PingNum:SetFont("DebugFixed")
self.PingNum:SetTextColor(white)
self.PingNum:SetContentAlignment(4)
self:SetWidth(50)
end
function SB_PING_METER:Setup(ply)
self.Player = ply
self.Think(self)
end
function SB_PING_METER:Think()
if not IsValid(self.Player) then return end
self.PlyPing = self.Player:Ping()
self.PingNum:SetText(self.PlyPing)
end
function SB_PING_METER:Paint(w, h)
surface.SetDrawColor(Color(90, 90, 92, 200))
surface.DrawRect(0, 15, 3, 4)
surface.DrawRect(4, 12, 3, 7)
surface.DrawRect(8, 8, 3, 11)
surface.DrawRect(12, 4, 3, 15)
if self.PlyPing <= 50 then
surface.SetDrawColor(Color(0, 255, 0, 200))
surface.DrawRect(0, 15, 3, 4)
surface.DrawRect(4, 12, 3, 7)
surface.DrawRect(8, 8, 3, 11)
surface.DrawRect(12, 4, 3, 15)
elseif self.PlyPing <= 100 and self.PlyPing > 50 then
surface.SetDrawColor(Color(255, 227, 0, 200))
surface.DrawRect(0, 15, 3, 4)
surface.DrawRect(4, 12, 3, 7)
surface.DrawRect(8, 8, 3, 11)
elseif self.PlyPing <= 150 and self.PlyPing > 100 then
surface.SetDrawColor(Color(255, 80, 0, 200))
surface.DrawRect(0, 15, 3, 4)
surface.DrawRect(4, 12, 3, 7)
elseif self.PlyPing > 150 then
surface.SetDrawColor(Color(255, 0, 0, 200))
surface.DrawRect(0, 15, 3, 4)
end
end
derma.DefineControl("SBPingmeter", "Draws ping", SB_PING_METER, "DPanel")
function SB_PLY_LINE:Init()
self.AvatarButton = self:Add("DButton")
self.AvatarButton:Dock(LEFT)
self.AvatarButton:DockMargin(6, 0, 0, 0)
self.AvatarButton:SetSize(32, 32)
self.AvatarButton.DoClick = function()
m = DermaMenu()
m:AddOption("Profile", function() end):SetIcon("icon16/user.png")
m:Open()
end
self.Avatar = vgui.Create("AvatarImage", self.AvatarButton)
self.Avatar:SetSize(32, 32)
self.Avatar:DockMargin(6, 0, 0, 0)
self.Avatar:SetMouseInputEnabled(false)
self.AvatarDeath = vgui.Create("DImage", self.Avatar)
self.AvatarDeath:SetSize(32, 32)
self.AvatarDeath:SetImage("lambda/cross.png")
self.AvatarDeath:SetMouseInputEnabled(false)
self.AvatarDeath:SetVisible(false)
self.Name = self:Add("DLabel")
self.Name:Dock(FILL)
self.Name:SetFont("lambda_sb_def")
self.Name:SetTextColor(white)
self.Name:DockMargin(8, 0, 0, 0)
self.Ping = self:Add("SBPingmeter")
self.Ping:Dock(RIGHT)
self.Ping:DockMargin(-25, 3, -5, 0)
self.Ping:SetWidth(50)
self.Deaths = self:Add("DLabel")
self.Deaths:Dock(RIGHT)
self.Deaths:DockMargin(0, 0, 40, 0)
self.Deaths:SetWidth(50)
self.Deaths:SetFont("lambda_sb_num")
self.Deaths:SetTextColor(white)
self.Deaths:SetContentAlignment(5)
self.Kills = self:Add("DLabel")
self.Kills:Dock(RIGHT)
self.Kills:DockMargin(0, 0, 0, 0)
self.Kills:SetWidth(50)
self.Kills:SetFont("lambda_sb_num")
self.Kills:SetTextColor(white)
self.Kills:SetContentAlignment(5)
if GAMEMODE:GetGameType().PlayerTiming then
self.PB = self:Add("DLabel")
self.PB:Dock(RIGHT)
self.PB:DockMargin(0, 0, 25, 0)
self.PB:SetWidth(70)
self.PB:SetFont("lambda_sb_num")
self.PB:SetTextColor(white)
self.PB:SetText("00:00:00")
self.PB:SetContentAlignment(5)
end
self:Dock(TOP)
self:DockPadding(3, 3, 3, 3)
self:SetHeight(32 + 3 * 2)
self:DockMargin(2, 0, 2, 2)
end
function SB_PLY_LINE:Setup(ply)
self.Player = ply
self.Avatar:SetPlayer(ply)
self.Think(self)
self.Ping:Setup(ply)
end
function SB_PLY_LINE:Think()
if not IsValid(self.Player) then
self:SetZPos(9999)
self:Remove()
return
end
self.AvatarDeath:SetVisible(not self.Player:Alive())
self.Name:SetText(self.Player:Nick())
self.Kills:SetText(self.Player:Frags())
self.Deaths:SetText(self.Player:Deaths())
if self.Player:Team() == TEAM_CONNECTING then
self:SetZPos(2000 + self.Player:EntIndex())
return
end
local kd = self.Player:Frags()
if self.Player:Deaths() > 0 then
kd = kd / self.Player:Deaths()
end
if kd < 0 then
kd = 0
end
self:SetZPos((kd * -50) + self.Player:EntIndex())
end
function SB_PLY_LINE:Paint(w, h)
if not IsValid(self.Player) then
return
end
if self.Player:Team() == TEAM_CONNECTING then
surface.SetDrawColor(orange2)
surface.DrawRect(0, 0, 4, h)
surface.SetDrawColor(dark)
surface.DrawRect(0, 4, 0, w, h)
return
end
if not self.Player:Alive() then
surface.SetDrawColor(orange2)
surface.DrawRect(0, 0, 4, h)
surface.SetDrawColor(dark)
surface.DrawRect(4, 0, w, h)
return
end
draw.RoundedBox(0, 0, 0, 4, h, orange)
draw.RoundedBox(0, 4, 0, w, h, dark)
end
SBPlayerLine = vgui.RegisterTable(SB_PLY_LINE, "DPanel")
function SB_PANEL:Init()
self.Scores = self:Add("DScrollPanel")
self.Scores:Dock(FILL)
self.Scores:DockMargin(0, 250, 0, 0)
self.Focused = false
end
function SB_PANEL:PerformLayout()
self:SetSize(700, ScrH() - 250)
self:SetPos(ScrW() / 2 - 350, 0)
end
local function DrawBar(x, y, w, name, value)
surface.SetDrawColor(orange)
surface.DrawRect(x + 2, y - 56, 4, 24)
surface.SetMaterial(gradientL)
surface.SetDrawColor(dark2)
surface.DrawRect(x + 6, y - 56, w - 11, 24)
name = string.upper(Localize(name))
value = string.upper(Localize(value))
draw.SimpleTextOutlined(name, "lambda_sb_def_sm", x + 10, y - 52, white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 0, Color(0, 0, 0, 250))
draw.SimpleTextOutlined(value, "lambda_sb_def_sm", x + w - 12, y - 52, white, TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP, 0, Color(0, 0, 0, 250))
end
local function DrawHostName(x,y,w,h)
surface.SetMaterial(gradientR)
surface.SetDrawColor(dark)
surface.DrawTexturedRect(20, y - 90, w / 2 - 20, 28)
surface.SetMaterial(gradientL)
surface.SetDrawColor(dark)
surface.DrawTexturedRect(w / 2, y - 90, w / 2 - 20, 28)
draw.SimpleTextOutlined(GetHostName(), "lambda_sb_def_nsm", w / 2, y - 91, white, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 0, Color(0, 0, 0, 250))
end
function SB_PANEL:Paint(w, h)
local _, y = self.Scores:GetPos()
-- this was the best way to get an image in here... screw u dimage and power of 2
surface.SetMaterial(lambda_logo)
surface.SetDrawColor(white)
surface.DrawTexturedRect(94, -160, 512, 512)
local n = 700 / table.Count(GAMEMODE:GetGameType():GetScoreboardInfo())
local x = 0
for k, v in pairs(GAMEMODE:GetGameType():GetScoreboardInfo()) do
DrawBar(x, y, n, v.name, v.value)
x = x + n + 2
end
DrawHostName(x,y,w,h)
surface.SetMaterial(gradientR)
surface.SetDrawColor(dark)
surface.DrawTexturedRect(300, y - 28, w - 302, 24)
if GAMEMODE:GetGameType().PlayerTiming then
surface.SetMaterial(time_logo)
surface.SetDrawColor(white)
surface.DrawTexturedRect(467, y - 24, 16, 16)
end
surface.SetMaterial(frag_logo)
surface.SetDrawColor(white)
surface.DrawTexturedRect(550, y - 24, 16, 16)
surface.SetMaterial(death_logo)
surface.SetDrawColor(white)
surface.DrawTexturedRect(601, y - 24, 16, 16)
surface.SetMaterial(ping_logo)
surface.SetDrawColor(white)
surface.DrawTexturedRect(650, y - 24, 16, 16)
end
function SB_PANEL:Think()
self.ScoreEntries = self.ScoreEntries or {}
for k, v in pairs(player.GetAll()) do
if self.ScoreEntries[v] ~= nil then
continue
end
local entry = vgui.CreateFromTable(SBPlayerLine, v.ScoreEntry)
entry:Setup(v)
self.ScoreEntries[v] = entry
self.Scores:AddItem(entry)
end
if input.IsMouseDown(MOUSE_RIGHT) and not self.Focus then
self.Focus = true
gui.EnableScreenClicker(true)
end
end
SBMain = vgui.RegisterTable(SB_PANEL, "EditablePanel")
LAMBDA_SCOREBOARD = LAMBDA_SCOREBOARD or nil
LAMBDA_SCOREBOARD_OPEN = LAMBDA_SCOREBOARD_OPEN or false
if IsValid(LAMBDA_SCOREBOARD) then
LAMBDA_SCOREBOARD:Remove()
LAMBDA_SCOREBOARD = nil
end
function GM:ScoreboardShow(keepOpen)
if not IsValid(LAMBDA_SCOREBOARD) then
LAMBDA_SCOREBOARD = vgui.CreateFromTable(SBMain)
end
if IsValid(LAMBDA_SCOREBOARD) then
LAMBDA_SCOREBOARD:Show()
LAMBDA_SCOREBOARD_OPEN = true
end
if LAMBDA_SCOREBOARD.KeepOpen ~= true then
LAMBDA_SCOREBOARD.KeepOpen = keepOpen
end
return false
end
function GM:IsScoreboardOpen()
return LAMBDA_SCOREBOARD_OPEN
end
function GM:ScoreboardHide()
if IsValid(LAMBDA_SCOREBOARD) then
if LAMBDA_SCOREBOARD.KeepOpen ~= true then
LAMBDA_SCOREBOARD.Focus = false
gui.EnableScreenClicker(false)
LAMBDA_SCOREBOARD:Hide()
LAMBDA_SCOREBOARD_OPEN = false
end
end
return false
end
|
local tApis = {}
for k,v in pairs( _G ) do
if type(k) == "string" and type(v) == "table" and k ~= "_G" then
table.insert( tApis, k )
end
end
table.insert( tApis, "shell" )
table.insert( tApis, "package" )
if multishell then
table.insert( tApis, "multishell" )
end
table.sort( tApis )
textutils.pagedTabulate( tApis )
|
local S = minetest.get_translator("item_repair")
-- Please don't change this, I don't protect against division by zero!
local base_time = 1.0 -- 0.4 max
local base_repair = 65535.0 * (item_repair_settings.repair_percent / 100.0)
item_repair_internal.update = function (pos, elapsed)
local meta=minetest.get_meta(pos)
local inv=meta:get_inventory()
local repair=base_repair
local time=base_time
if not inv:is_empty("upgrades") then
for i, s in ipairs(inv:get_list("upgrades")) do
-- minetest.log("action", "[item_repair] Slot: "..i.." Contains: "..s:get_name())
if s:get_name() == "item_repair:upgrade_amount" then
-- This item focuses on amount
repair = repair + base_repair
elseif s:get_name() == "item_repair:upgrade_time" then
-- This item focuses on time
time = time - 0.2 -- 0.4
elseif s:get_name() == "item_repair:upgrade_multi" then
-- This item applies a weaker version of both (To be considered "better" is not quite right)
repair = repair + (base_repair * 0.75)
time = time - 0.1 -- 0.7
end
end
end
meta:set_float("repair_amount", repair)
meta:set_float("repair_time", time)
local repairs_per_sec = repair / time
-- The repair time has updated, restart the timer with the new value
local timer = minetest.get_node_timer(pos)
timer:stop()
meta:set_int("state", 2)
if inv:is_empty("done") then
minetest.get_node_timer(pos):stop()
meta:set_int("state", 0)
item_repair_internal.inv_update(pos) -- Update the formspec
if item_repair_settings.log_deep then
minetest.log("action", "[item_repair] item_repair:repair_active at ("..pos.x..", "..pos.y..", "..pos.z..") by '"..meta:get_string("owner").."' will repair "..repair.." amount every "..time.." second(s) ("..string.format("%.1f", repairs_per_sec).."/s")
minetest.log("action", "[item_repair] stopped")
end
local reported = false
if inv:is_empty("done") and not reported then
meta:set_string("infotext", "Item Repair [Nothing to repair] (" .. meta:get_string("owner") .. ")")
reported = true
end
minetest.swap_node(pos, {name ="item_repair:repair"})
return false
else
for i, s in ipairs(inv:get_list("done")) do
s:add_wear(-repair)
if s:get_wear() ~= 0 and item_repair_settings.log_production then
minetest.log("action", "[item_repair] item_repair:repair_active at "..minetest.pos_to_string(pos).." by '"..meta:get_string("owner").."' Slot: "..i.." now has "..s:get_wear().." remaining.")
end
inv:set_stack("done", i, s)
end
end
item_repair_internal.inv_update(pos) -- Update the formspec
if item_repair_settings.log_deep then
minetest.log("action", "[item_repair] update "..repair.." / "..time.." = "..string.format("%.1f", repairs_per_sec))
end
meta:set_string("infotext", "Item Repair "..string.format("%.1f", repairs_per_sec).."/s (" .. meta:get_string("owner") .. ")")
return false
end
-- Attempt to get the MCL formspec to build a formspec able to be shown via their stuff
local mclform = rawget(_G, "mcl_formspec") or nil
-- This formspec will auto-change if MCL detected
item_repair_internal.inv_update = function(pos)
local meta=minetest.get_meta(pos)
local inv=meta:get_inventory()
local names=meta:get_string("names")
local op=meta:get_int("open")
local open=""
if op==0 then
open="Only U"
elseif op==1 then
open="Members"
else
open="Public"
end
local state = meta:get_int("state")
local repair = meta:get_float("repair_amount")
local time = meta:get_float("repair_time")
local repairs_per_sec = ""
local per_sec = repair / time
if item_repair_settings.log_deep then
minetest.log("action", "[item_repair] inv_update "..repair.." / "..time.." = "..string.format("%.1f", per_sec))
end
if state~=0 then
repairs_per_sec = ""..string.format("%.1f", per_sec).."/s"
else
repairs_per_sec = "0/s"
end
if item_repair.game_mode() == "MTG" then
meta:set_string("formspec",
"size[8,11]" ..
"label[0.3,0.3;"..minetest.formspec_escape(repairs_per_sec).."]" ..
"list[context;upgrades;2,0;3,1;]" ..
"button[0,1; 1.5,1;save;Save]" ..
"button[0,2; 1.5,1;open;" .. open .."]" ..
"textarea[2.2,1.3;6,1.8;names;Members List (Inventory access);" .. names .."]"..
"list[context;done;0,2.9;8,4;]" ..
"list[current_player;main;0,7;8,4;]" ..
"listring[current_player;main]" ..
"listring[current_name;done]"
)
elseif item_repair.game_mode() == "MCL" and mclform ~= nil then
meta:set_string("formspec",
"size[9, 10.5]"..
"label[0.3,0.3;"..minetest.formspec_escape(repairs_per_sec).."]"..
"list[context;upgrades;2,0;3,1;]"..
mclform.get_itemslot_bg(2, 0, 3, 1)..
"button[0,1; 1.9,1;save;Save]"..
"button[0,2; 1.9,1;open;" .. open .."]" ..
"label[2.16, 0.9;Members List (Inventory Access)]"..
"textarea[2.2,1.3;6,1.8;names;;" .. names .."]"..
"list[context;done;0,2.9;9,3;]" ..
mclform.get_itemslot_bg(0, 2.9, 9, 3)..
"label[0,5.85;"..minetest.formspec_escape("Inventory").."]"..
-- "list[current_player;main;0,6.5;9,4;]" ..
-- mclform.get_itemslot_bg(0, 6.5, 9, 4)..
"list[current_player;main;0,6.5;9,3;9]"..
mclform.get_itemslot_bg(0,6.5,9,3)..
"list[current_player;main;0,9.74;9,1;]"..
mclform.get_itemslot_bg(0,9.74,9,1)..
"listring[current_player;main]" ..
"listring[current_name;done]"
)
end
end
item_repair_internal.inv = function (placer, pos)
local meta=minetest.get_meta(pos)
item_repair_internal.inv_update(pos)
meta:set_string("infotext", "Item Repair (" .. placer:get_player_name() .. ")")
end
-- Now we use all this to make our machine
local mod_name = "item_repair_"
local extent = ".png"
local grouping = nil
local sounding = nil
if item_repair.game_mode() == "MCL" then
local mcl_sounds = rawget(_G, "mcl_sounds") or item_repair_internal.throw_error("Failed to obtain MCL Sounds")
grouping = {handy=1}
sounding = mcl_sounds.node_sound_metal_defaults()
elseif item_repair.game_mode() == "MTG" then
local default = rawget(_G, "default") or item_repair_internal.throw_error("Failed to obtain MTG Sounds")
grouping = {crumbly = 3}
sounding = default.node_sound_metal_defaults()
else
grouping = {crumbly = 3, handy=1}
end
minetest.register_node("item_repair:repair", {
description = "Item Repair",
_doc_items_long_desc = S("Repairs are technology from the future, they can repair multiple items, and can be upgraded."),
_dock_items_usagehelp = S("Place the item wished to be repair in the middle slots, place upgrades in the top slots, or add players (1 per line) to allow others and change to Members."),
_dock_items_hidden=false,
tiles = {
mod_name.."plate_off"..extent,
mod_name.."plate_off"..extent,
mod_name.."plate_off"..extent,
mod_name.."plate_off"..extent,
mod_name.."plate_off"..extent,
mod_name.."plate_off"..extent,
},
groups = grouping,
sounds = sounding,
paramtype2 = "facedir",
light_source = 1,
drop = "item_repair:repair",
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", "Item Repair")
meta:set_string("owner", "")
meta:set_int("open", 0)
meta:set_int("state", 0)
meta:set_string("names", "")
meta:set_float("repair_amount", base_repair) -- Add the base value
meta:set_float("repair_time", base_time) -- Add the base value
local inv = meta:get_inventory()
if item_repair.game_mode() == "MTG" then
inv:set_size("done", 32) -- 4*8
elseif item_repair.game_mode() == "MCL" then
inv:set_size("done", 27) -- 3*9
end
inv:set_size("upgrades", 3)
end,
after_place_node = function(pos, placer, itemstack)
local meta = minetest.get_meta(pos)
meta:set_string("owner", (placer:get_player_name() or ""))
local inv = meta:get_inventory()
item_repair_internal.inv(placer,pos)
end,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
local meta=minetest.get_meta(pos)
local open=meta:get_int("open")
local name=player:get_player_name()
local owner=meta:get_string("owner")
if meta:get_int("state") ~= 1 then
minetest.get_node_timer(pos):start(meta:get_int("repair_time"))
minetest.swap_node(pos, {name ="item_repair:repair_active"})
meta:set_int("state", 1)
end
if name==owner then return stack:get_count() end
if open==2 and listname=="done" then return stack:get_count() end
if open==1 and listname=="done" then
local names=meta:get_string("names")
local txt=names.split(names,"\n")
for i in pairs(txt) do
if name==txt[i] then
return stack:get_count()
end
end
end
return 0
end,
allow_metadata_inventory_take = function(pos, listname, index, stack, player)
local meta=minetest.get_meta(pos)
local open=meta:get_int("open")
local name=player:get_player_name()
local owner=meta:get_string("owner")
if meta:get_int("state") ~= 1 then
minetest.get_node_timer(pos):start(meta:get_int("repair_time"))
minetest.swap_node(pos, {name ="item_repair:repair_active"})
meta:set_int("state", 1)
end
if name==owner then return stack:get_count() end
if open==2 and listname=="done" then return stack:get_count() end
if open==1 and listname=="done" then
local names=meta:get_string("names")
local txt=names.split(names,"\n")
for i in pairs(txt) do
if name==txt[i] then
return stack:get_count()
end
end
end
return 0
end,
can_dig = function(pos, player)
local meta=minetest.get_meta(pos)
local owner=meta:get_string("owner")
local inv=meta:get_inventory()
if (inv:is_empty("upgrades") and inv:is_empty("done")) then
-- Only check it's the owner
if (player:get_player_name()==owner) and owner ~= "" then
minetest.get_node_timer(pos):stop()
end
return (player:get_player_name()==owner and
owner~="")
else
return false
end
end,
allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
local meta = minetest.get_meta(pos)
if meta:get_int("state") ~= 1 then
minetest.get_node_timer(pos):start(meta:get_int("repair_time"))
minetest.swap_node(pos, {name ="item_repair:repair_active"})
meta:set_int("state", 1)
end
if meta:get_int("open")==0 and player:get_player_name()~=meta:get_string("owner") then
return 0
end
return count
end,
on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
if sender:get_player_name() ~= meta:get_string("owner") then
return false
end
if fields.save then
meta:set_string("names", fields.names)
item_repair_internal.inv(sender,pos)
end
if fields.open then
local open=meta:get_int("open")
open=open+1
if open>2 then open=0 end
meta:set_int("open",open)
item_repair_internal.inv(sender,pos)
end
end,
on_timer = function(pos, elapsed)
local meta = minetest.get_meta(pos)
local rc = item_repair_internal.update(pos, elapsed)
if meta:get_int("state") == 2 then
if item_repair_settings.log_deep then
minetest.log("action", "[item_repair] Timer set to "..meta:get_float("repair_time").." for "..minetest.pos_to_string(pos))
end
minetest.get_node_timer(pos):start(meta:get_float("repair_time"))
meta:set_int("state", 1)
end
return rc
end
})
minetest.register_node("item_repair:repair_active", {
description = "Item Repair",
tiles = {
mod_name.."plate_on"..extent,
mod_name.."plate_on"..extent,
mod_name.."plate_on"..extent,
mod_name.."plate_on"..extent,
mod_name.."plate_on"..extent,
mod_name.."plate_on"..extent,
},
groups = grouping,
sounds = sounding,
paramtype2 = "facedir",
light_source = 5,
drop = "item_repair:repair",
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", "Item Repair")
meta:set_string("owner", "")
meta:set_int("open", 0)
meta:set_int("state", 0)
meta:set_string("names", "")
meta:set_float("repair_amount", base_repair) -- Add the base value
meta:set_float("repair_time", base_time) -- Add the base value
local inv = meta:get_inventory()
if item_repair.game_mode() == "MTG" then
inv:set_size("done", 32) -- 8*4
elseif item_repair.game_mode() == "MCL" then
inv:set_size("done", 27) -- 9*3
end
inv:set_size("upgrades", 3)
end,
after_place_node = function(pos, placer, itemstack)
local meta = minetest.get_meta(pos)
if meta:get_string("owner") == "" then
meta:set_string("owner", placer:get_player_name() or "")
end
local inv = meta:get_inventory()
item_repair_internal.inv(placer,pos)
end,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
local meta=minetest.get_meta(pos)
local open=meta:get_int("open")
local name=player:get_player_name()
local owner=meta:get_string("owner")
if meta:get_int("state") ~= 1 then
minetest.get_node_timer(pos):start(meta:get_int("repair_time"))
minetest.swap_node(pos, {name = "item_repair:repair_active"})
meta:set_int("state", 1)
end
if name==owner then return stack:get_count() end
if open==2 and listname=="done" then return stack:get_count() end
if open==1 and listname=="done" then
local names=meta:get_string("names")
local txt=names.split(names,"\n")
for i in pairs(txt) do
if name==txt[i] then
return stack:get_count()
end
end
end
return 0
end,
allow_metadata_inventory_take = function(pos, listname, index, stack, player)
local meta=minetest.get_meta(pos)
local open=meta:get_int("open")
local name=player:get_player_name()
local owner=meta:get_string("owner")
if meta:get_int("state") ~= 1 then
minetest.get_node_timer(pos):start(meta:get_int("repair_time"))
minetest.swap_node(pos, {name ="item_repair:repair_active"})
meta:set_int("state", 1)
end
if name==owner then return stack:get_count() end
if open==2 and listname=="done" then return stack:get_count() end
if open==1 and listname=="done" then
local names=meta:get_string("names")
local txt=names.split(names,"\n")
for i in pairs(txt) do
if name==txt[i] then
return stack:get_count()
end
end
end
return 0
end,
can_dig = function(pos, player)
local meta=minetest.get_meta(pos)
local owner=meta:get_string("owner")
local inv=meta:get_inventory()
if (inv:is_empty("upgrades") and inv:is_empty("done")) then
-- Only check it's the owner
if (player:get_player_name()==owner) and owner ~= "" then
minetest.get_node_timer(pos):stop()
end
return (player:get_player_name()==owner and
owner~="")
else
return false
end
end,
allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
local meta = minetest.get_meta(pos)
if meta:get_int("state") ~= 1 then
minetest.get_node_timer(pos):start(meta:get_int("repair_time"))
minetest.swap_node(pos, {name ="item_repair:repair_active"})
meta:set_int("state", 1)
end
if meta:get_int("open")==0 and player:get_player_name()~=meta:get_string("owner") then
return 0
end
return count
end,
on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
if sender:get_player_name() ~= meta:get_string("owner") then
return false
end
if fields.save then
meta:set_string("names", fields.names)
item_repair_internal.inv(sender,pos)
end
if fields.open then
local open=meta:get_int("open")
open=open+1
if open>2 then open=0 end
meta:set_int("open",open)
item_repair_internal.inv(sender,pos)
end
end,
on_timer = function(pos, elapsed)
local meta = minetest.get_meta(pos)
local rc = item_repair_internal.update(pos, elapsed)
if meta:get_int("state") == 2 then
if item_repair_settings.log_deep then
minetest.log("action", "[item_repair] Timer set to "..meta:get_float("repair_time").." for "..minetest.pos_to_string(pos))
end
minetest.get_node_timer(pos):start(meta:get_float("repair_time"))
meta:set_int("state", 1)
end
return rc
end
})
minetest.register_craftitem("item_repair:upgrade_amount", {
description = "Repair Upgrade Capacitor",
inventory_image = "item_repair_upgrade_amount.png",
stack_max = 1
})
minetest.register_craftitem("item_repair:upgrade_time", {
description = "Repair Upgrade Processor",
inventory_image = "item_repair_upgrade_time.png",
stack_max = 1
})
minetest.register_craftitem("item_repair:upgrade_multi", {
description = "Repair Upgrade Complex",
inventory_image = "item_repair_upgrade_multi.png",
stack_max = 1
})
if item_repair_settings.craft then
if minetest.get_modpath("default") or false then
local planks = "group:wood"
local obsidian = "default:obsidian"
local tin = "default:tin_ingot"
local copper = "default:copper_ingot"
local bronze = "default:bronze_ingot"
local mese_crystal = "default:mese_crystal"
-- Machine
minetest.register_craft({
output = "item_repair:repair",
recipe = {
{planks, planks, planks},
{planks, obsidian, planks},
{planks, planks, planks}
}
})
-- Upgrades
minetest.register_craft({
output = "item_repair:upgrade_amount",
recipe = {
{"", tin, ""},
{tin, mese_crystal, tin},
{"", tin, ""}
}
})
minetest.register_craft({
output = "item_repair:upgrade_time",
recipe = {
{"", copper, ""},
{copper, mese_crystal, copper},
{"", copper, ""}
}
})
minetest.register_craft({
output = "item_repair:upgrade_multi",
recipe = {
{"", bronze, ""},
{bronze, mese_crystal, bronze},
{"", bronze, ""}
}
})
end
if (minetest.get_modpath("mcl_core") or false) then
local plank = "group:wood"
local anvil = "mcl_anvils:anvil"
local anvil_1 = "mcl_anvils:anvil_damage_1"
local anvil_2 = "mcl_anvils:anvil_damage_2"
local iron = "mcl_core:iron_ingot"
local gold = "mcl_core:gold_ingot"
local redstone = "mcl_core:diamond"
-- Machine
minetest.register_craft({
output = "item_repair:repair",
recipe = {
{plank, plank, plank},
{plank, anvil, plank},
{plank, plank, plank}
}
})
minetest.register_craft({
output = "item_repair:repair",
recipe = {
{plank, plank, plank},
{plank, anvil_1, plank},
{plank, plank, plank}
}
})
minetest.register_craft({
output = "item_repair:repair",
recipe = {
{plank, plank, plank},
{plank, anvil_2, plank},
{plank, plank, plank}
}
})
-- Upgrades
minetest.register_craft({
output = "item_repair:upgrade_amount",
recipe = {
{"", iron, ""},
{iron, redstone, iron},
{"", iron, ""}
}
})
minetest.register_craft({
output = "item_repair:upgrade_time",
recipe = {
{"", gold, ""},
{gold, redstone, gold},
{"", gold, ""}
}
})
minetest.register_craft({
output = "item_repair:upgrade_multi",
recipe = {
{iron, gold, iron},
{gold, redstone, gold},
{iron, gold, iron}
}
})
end
end
-- Allow the item to be "recycled" (if so desired)
minetest.register_craft({
type = "fuel",
recipe = "item_repair:repair",
burntime = 300
})
minetest.register_craft({
type = "fuel",
recipe = "item_repair:repair_active",
burntime = 300
})
minetest.register_craft({
type = "fuel",
recipe = "item_repair:upgrade_amount",
burntime = 100
})
minetest.register_craft({
type = "fuel",
recipe = "item_repair:upgrade_time",
burntime = 100
})
minetest.register_craft({
type = "fuel",
recipe = "item_repair:upgrade_multi",
burntime = 150
})
-- For those who don't want an active repairs in their inventory. (Looks only)
minetest.register_craft({
type = "shapeless",
output = "item_repair:repair",
recipe = {
"item_repair:repair_active",
}
}) -- Or perhaps you want it to look active.
minetest.register_craft({
type = "shapeless",
output = "item_repair:repair_active",
recipe = {
"item_repair:repair",
}
})
|
forge.clear()
bladeHeight = math.random(6, 14) / 10;
bladeWidth = math.random(7, 9) /10;
guardHeight = 0.1;
hiltHeight = 0.1;
if math.random(0, 2) == 1 then
blades = {
"Swords/blade",
"Swords/blade_bend",
"Swords/blade_broken",
"Swords/blade_dagger",
"Swords/blade_dual",
"Swords/blade_skew",
"Swords/blade_skrimitar",
"Swords/blade_rounded"
}
blade = blades[math.random(#blades)];
forge.build(blade, {0, 0, 0}, {0, 0, 0}, {bladeWidth, bladeHeight, 1})
else
mixedBladeMiddles = {
"Swords/blade_dual_middle",
"Swords/blade_middle",
"Swords/blade_middle_broken",
}
mixedBladeTops = {
"Swords/blade_dual_top",
"Swords/blade_top_broken"
}
mixedBladeMiddle = mixedBladeMiddles[math.random(#mixedBladeMiddles)];
mixedBladeTop = mixedBladeTops[math.random(#mixedBladeTops)];
forge.build(mixedBladeMiddle, {0, 0, 0}, {0, 0, 0}, {bladeWidth, bladeHeight, 1})
forge.build(mixedBladeTop, {0, bladeHeight, 0}, {0, 0, 0}, {bladeWidth, bladeHeight/3, 1})
end
guards = {
"Swords/guard",
"Swords/guard_detailed",
"Swords/guard_round",
"Swords/guard_slant",
"Swords/guard_slant_cross",
"Swords/guard_up"
}
guard = guards[math.random(#guards)];
forge.build(guard, {0, -guardHeight, 0}, {0, 0, 0}, {1, 1, 1})
hilts = {
"Swords/hilt",
"Swords/hilt_handle",
"Swords/hilt_handle_guard",
"Swords/hilt_handle_heavy",
"Swords/hilt_long",
"Swords/hilt_long_wide",
"Swords/hilt_smooth"
}
hilt = hilts[math.random(#hilts)];
forge.build(hilt, {0, -2*(hiltHeight+guardHeight)-guardHeight, 0}, {0, 0, 0})
|
object_ship_kihraxz_tier9 = object_ship_shared_kihraxz_tier9:new {
}
ObjectTemplates:addTemplate(object_ship_kihraxz_tier9, "object/ship/kihraxz_tier9.iff")
|
local types = require "resty.nettle.types.common"
local context = require "resty.nettle.types.sha3"
local lib = require "resty.nettle.library"
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local setmetatable = setmetatable
local hashes = {
shake256 = {
length = 32,
context = context.sha3_256,
init = lib.nettle_sha3_256_init,
update = lib.nettle_sha3_256_update,
digest = lib.nettle_sha3_256_shake
},
}
hashes[256] = hashes.shake256
local sha3shake = {}
sha3shake.__index = sha3shake
function sha3shake:update(data, len)
return self.hash.update(self.context, len or #data, data)
end
function sha3shake:digest(digest_len)
local length = digest_len or self.length
local buffer = types.buffers(length)
local hash = self.hash
hash.digest(self.context, length, buffer)
return ffi_str(buffer, length)
end
local function factory(hash)
return setmetatable({
new = function()
local ctx = ffi_new(hash.context)
hash.init(ctx)
return setmetatable({ context = ctx, hash = hash }, sha3shake)
end
}, {
__call = function(_, data, len, digest_len)
local ctx = ffi_new(hash.context)
hash.init(ctx)
hash.update(ctx, len or #data, data)
local length = digest_len or hash.length
local buffer = types.buffers(length)
hash.digest(ctx, length, buffer)
return ffi_str(buffer, length)
end
})
end
return setmetatable({
shake256 = factory(hashes.shake256),
}, {
__call = function(_, bits, data, len, digest_len)
local hash = hashes[bits]
if not hash then
return nil, "the only supported SHA3-SHAKE algorithm is the 256 bit one"
end
local ctx = ffi_new(hash.context)
hash.init(ctx)
hash.update(ctx, len or #data, data, digest_len)
local length = digest_len or hash.length
local buffer = types.buffers(length)
hash.digest(ctx, length, buffer)
return ffi_str(buffer, length)
end
})
|
--[[
© 2021 Tony Ferguson, do not share, re-distribute or modify
without permission of its author ( devultj@gmail.com - Tony Ferguson, http://www.tferguson.co.uk/ )
]]
AddCSLuaFile()
ENT.Base = "base_anim"
ENT.Type = "anim"
ENT.Author = "DevulTj"
ENT.PrintName = "Drill Base"
ENT.Spawnable = false
ENT.AdminSpawnable = true
ENT.DHeists = true
ENT.physicsBox = {
mins = Vector( -7, -20, -5 ),
maxs = Vector( 7, 10, 6 )
}
sound.Add {
name = "dHeists.drillSound",
channel = CHAN_STATIC,
volume = 0.75,
level = SNDLVL_65dB,
pitch = 120,
sound = "vehicles/digger_grinder_loop1.wav"
}
function ENT:SetupDataTables()
self:NetworkVar( "Bool", 0, "IsDrilling" )
self:NetworkVar( "Float", 0, "DrillStart" )
self:NetworkVar( "Float", 1, "DrillEnd" )
self:NetworkVar( "Entity", 1, "LastPickedUp" )
end
function ENT:SpawnFunction( ply, tr, ClassName )
if not tr.Hit then return end
local SpawnPos = tr.HitPos + tr.HitNormal * 16
local ent = ents.Create( ClassName )
ent:SetPos( SpawnPos )
ent:setDevEntity( "creator", ply )
ent:Spawn()
ent:Activate()
return ent
end
function ENT:Initialize()
local selectedModel = dHeists.config.drillModel
local isValidModel = file.Exists( selectedModel, "GAME" )
if not isValidModel then
selectedModel = "models/hunter/blocks/cube05x05x05.mdl"
end
self:SetModel( selectedModel )
self:PhysicsInitBox( self.physicsBox.mins, self.physicsBox.maxs )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetUseType( SIMPLE_USE )
self:PhysicsInitBox( self.physicsBox.mins, self.physicsBox.maxs )
self:Activate()
self:SetAutomaticFrameAdvance( false )
self:SetSkin( self.DrillSkin or 0 )
self:SetModelScale( self.DrillScale or 1 )
end
function ENT:getPercent()
return math.TimeFraction( self:GetDrillStart(), self:GetDrillEnd(), CurTime() )
end
function ENT:isFinished()
return self:getPercent() >= 1
end
ENT.DrillStates = {
[ "Active" ] = 1,
[ "Finished" ] = 2,
[ "Error" ] = 3,
[ "NotSetup" ] = 4
}
function ENT:getDrillState()
if self:getPercent() < 1 and self:getPercent() > 0 then
return self.DrillStates.Active
elseif not IsValid( self:GetParent() ) then
return self.DrillStates.NotSetup
elseif self:getPercent() >= 1 then
return self.DrillStates.Finished
end
return self.DrillStates.Error
end
function ENT:doDestroyAction( player )
dHeists.actions.doAction( player, dHeists.config.drillDestroyTime or 5, function()
if not IsValid( self ) or self.IsTaken then return end
SafeRemoveEntity( self )
if IsValid( self:GetParent() ) then
self:GetParent():StopSound( "dHeists.drillSound" )
end
self.IsTaken = true
if dHeists.config.drillDestroyRewardEnabled then
local moneyGiven = dHeists.config.drillDestroyMoneyPrize or 500
dHeists.addMoney( player, moneyGiven )
end
player:dHeistsNotify( dL( "drill_destroyed_text", string.formatMoney( moneyGiven ) ), NOTIFY_GENERIC )
end, {
ent = self,
ActionColor = dHeists.config.drillDestroyActionColor,
ActionTimeRemainingTextPhrase = dL( "destroying_drill" )
} )
end
function ENT:Use( player )
if player:KeyDown( IN_WALK ) then return end
local shouldDestroy = dHeists.gamemodes:isPolice( player )
if shouldDestroy then
self:doDestroyAction( player )
end
end
function ENT:StartTouch( eEnt )
if not IsEntity( eEnt ) then return end
if eEnt.IsRobbableEntity and eEnt.setDrill then
eEnt:setDrill( self )
self:SetIsDrilling( true )
end
end
if CLIENT then
ENT.PanelInfo = {
pos = Vector( -8.5, 8.2, 2.2 ),
w = 72,
h = 60
}
ENT.DrillStateNames = {
"DRILLING",
"FINISHED",
"ERROR",
"PLACE ME"
}
ENT.DrillColors = {
Color( 0, 150, 0 ),
Color( 255, 150, 0 ),
Color( 150, 0, 0 ),
Color( 150, 150, 150 ),
}
function ENT:Draw()
self:DrawModel()
local drillState = self:getDrillState()
local fFraction = math.Clamp( math.TimeFraction( self:GetDrillStart(), self:GetDrillEnd(), CurTime() ), 0, 1 )
local sActive = not IsValid( self:GetParent() ) and "?" or math.Clamp( math.ceil( self:GetDrillEnd() - CurTime() ), 0, 5000 ) .. " sec"
local sPercentage = self.DrillStateNames[ drillState ] or ""
local drillStateColor = self.DrillColors[ drillState ]
local nModelScale = self:GetModelScale()
local vPos = self:GetPos() + ( ( self:GetUp() * 2 + self:GetRight() * - 9.7 + self:GetForward() * 6.6 ) * nModelScale )
local aAng = self:GetAngles()
aAng:RotateAroundAxis( aAng:Right(), 60 )
aAng:RotateAroundAxis( aAng:Up(), -90 )
aAng:RotateAroundAxis( aAng:Forward(), 0 )
cam.Start3D2D( vPos, aAng, 0.1 * nModelScale )
draw.RoundedBox( 0, 0, 0, self.PanelInfo.w, self.PanelInfo.h, Color( 255, 255, 255 ) )
draw.RoundedBox( 0, 2, 2, self.PanelInfo.w - 4, self.PanelInfo.h - 4, Color( 50, 50, 50 ) )
draw.RoundedBox( 0, 2, 2, self.PanelInfo.w - 4, 6, Color( 150, 150, 150 ) )
draw.RoundedBox( 0, 8, 36, self.PanelInfo.w - 16, 4, Color( 0, 0, 0, 150 ) )
draw.RoundedBox( 0, 8, 36, ( self.PanelInfo.w - 16 ) * fFraction, 4, drillStateColor )
draw.SimpleText( sActive, "dHeistsSmall", self.PanelInfo.w / 2 + 2, self.PanelInfo.h / 2.9 + 2, Color( 0, 0, 0, 200 ), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
draw.SimpleText( sActive, "dHeistsSmall", self.PanelInfo.w / 2, self.PanelInfo.h / 2.9, Color( 250, 250, 250 ), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
draw.SimpleText( sPercentage, "dHeistsSmall", self.PanelInfo.w / 2 + 2, self.PanelInfo.h / 1.3 + 2, Color( 0, 0, 0, 200 ), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
draw.SimpleText( sPercentage, "dHeistsSmall", self.PanelInfo.w / 2, self.PanelInfo.h / 1.3, drillStateColor, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
cam.End3D2D()
end
function ENT:Initialize()
self:DrawShadow( false )
end
end
|
require "scripts.core.variable"
local mana_max = class(Variable);
function mana_max:GetValue()
local baseMana = 75
if self.owner:HasValue("base_mana") then
baseMana = self.owner:GetValue("base_mana")
end
return baseMana + self.owner:GetValue("intelligence")*12;
end
return mana_max;
|
-- #######################################
-- ## Project: MTA:scp-088 ##
-- ## Name: Remover.lua ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- #######################################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
Remover = {};
Remover.__index = Remover;
--[[
]]
-- ///////////////////////////////
-- ///// New //////
-- ///// Returns: Object //////
-- ///////////////////////////////
function Remover:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// RemoveObjects //////
-- ///// Returns: void //////
-- ///////////////////////////////
function Remover:RemoveObjects()
-- removing level 1 room top
--removeWorldModel(2008, 10, 326.65228271484, 187.49096679688, 1013.1875, 3)
--removeWorldModel()
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function Remover:Constructor(...)
self:RemoveObjects()
logger:OutputInfo("[CALLING] Remover: Constructor");
end
-- EVENT HANDLER --
|
local lsp_signature = require 'lsp_signature'
lsp_signature.setup {
hint_enable = true,
hint_prefix = '🤔️ ',
}
|
require('nvim_mappings')
function load_rc_files()
local files =
vim.api.nvim_eval([[sort(glob(g:lua_plugin_config_dir .. '/*.lua', '', v:true))]])
for _, file in ipairs(files) do
-- local name = file:sub(#vim.g.lua_plugin_config_dir+2, file:len()-4)
-- require('rc/' .. name)
dofile(file)
end
end
load_rc_files()
function _G.pprint(...)
local objects = vim.tbl_map(vim.inspect, { ... })
print(unpack(objects))
end
-- function plenary_luarocks()
-- -- https://github.com/tjdevries/config_manager/blob/49fe3dc80f077b051f3bfb958413ff6e74920f83/xdg_config/nvim/lua/init.lua
-- -- 1回のみ実行する
-- -- if false then
-- -- local neorocks = require('plenary.neorocks')
-- --
-- -- -- package-name, lua-name
-- -- -- neorocks.install('penlight', 'pl')
-- -- -- neorocks.install('microlight', 'ml')
-- -- -- neorocks.install('moses')
-- -- -- neorocks.install('Lua-cURL')
-- --
-- -- -- local pl = require'pl' で使える!
-- -- end
-- end
-- plenary_luarocks()
|
-- Copyright (c) 2018 Redfern, Trevor <trevorredfern@gmail.com>
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
return {
inventory = require "components.inventory",
position = require "components.position",
size = require "components.size",
sprite = require "components.sprite",
storage = require "components.storage"
}
|
it('creates commands', function()
local mapx = require 'mapx'
mapx.setup { global = true }
expect.notNil(cmd)
expect.notNil(cmdbang)
local cmd = mapx.cmd
local cmdbang = mapx.cmdbang
local var = nil
-- option test
cmd('SetVar', function(opt)
if opt.register ~= '' then
var = opt.register
elseif #opt.modifiers > 0 then
var = opt.modifiers[1]
elseif opt.bang then
var = nil
elseif not var and #opt.arguments > 0 then
var = opt.arguments[1]
elseif not var and opt.count > 0 then
var = opt.count
end
end, {
nargs = '?',
count = true,
register = true,
}, {
bang = true,
}, {})
vim.cmd [[SetVar 1]]
expect.equal(1, var)
vim.cmd [[2SetVar]]
expect.equal(1, var)
vim.cmd [[SetVar!]]
expect.equal(nil, var)
vim.cmd [[2SetVar]]
expect.equal(2, var)
vim.cmd [[vertical SetVar]]
expect.equal('vertical', var)
vim.cmd [[SetVar x]]
expect.equal('x', var)
-- function table test
cmdbang('SetVar', {
function(opt)
if opt.register ~= '' then
var = opt.register
end
end,
function(opt)
if #opt.modifiers > 0 then
var = opt.modifiers[1]
end
end,
}, {
nargs = 0,
}, {
register = true,
})
vim.cmd [[belowright SetVar]]
expect.equal('belowright', var)
vim.cmd [[SetVar a]]
expect.equal('a', var)
-- function Vim command string test
vim.g.var = nil
cmdbang('SetVar', 'let g:var = <q-reg>', {
nargs = 0,
register = true,
})
vim.cmd [[SetVar b]]
expect.equal('b', vim.g.var)
end)
|
color = {}
color.red = { 1, 0, 0, 1 }
color.green = { 0, 1, 0, 1 }
color.blue = { 0, 0, 1, 1 }
color.white = { 1, 1, 1, 1 }
color.black = { 0, 0, 0, 1 }
color.clear = { 0, 0, 0, 0 }
color.gray = { 0.25, 0.25, 0.25, 1.0 }
function color.random()
return {
math.random(),
math.random(),
math.random(),
1,
}
end
|
----------------------------------------
-- Sassilization
-- http://sassilization.com
-- By Sassafrass / Spacetech / LuaPineapple
----------------------------------------
--This code is old and now useless //Hateful
/*
local require = require
local pairs = pairs
local _G = _G
module( "alliance" )
if( not _G.sh_alliance ) then return end
for k, v in pairs( _G.sh_alliance ) do
if not _M[k] then
_M[k] = v
end
end
_G.sh_alliance = nil
_G = nil
*/
function SetAllianceRequest(len)
ent = net.ReadEntity()
local string = net.ReadString()
if string != "nil" then
ent.request = string
else
ent.request = nil
end
end
net.Receive("SetAllianceRequest", SetAllianceRequest)
function SetAlliance(len)
ent = net.ReadEntity()
local string = net.ReadString()
if string != "nil" then
ent.alliance = string
else
ent.alliance = nil
end
end
net.Receive("SetAlliance", SetAlliance)
function SetPublicAlliance(len)
ply1 = net.ReadEntity()
ply1.allies = net.ReadTable()
ply1.allianceCount = net.ReadInt(8)
end
net.Receive("SetPublicAlliance", SetPublicAlliance)
function IsAllied(emp1, emp2)
if !emp1 or !emp2 then return end
local player1 = emp1:GetPlayer()
local player2 = emp2:GetPlayer()
if player1 and player2 and player1.allies and player2.allies then
for k,v in pairs(player1.allies) do
if v == player2 then
return true
end
end
end
return false
end
|
--[=[
[ContainerService](https://github.com/csqrl/containerservice-knit/) by csqrl. ContainerService is a Service and Controller pair for Sleitnick's Knit framework,
which allows for selective replication to clients. This means that an Instance can be replicated to a specific client without it being replicated to any other client.
ContainerService handles replication to individual clients.
@server
@class ContainerService
]=]
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HttpService = game:GetService("HttpService")
local RunService = game:GetService("RunService")
local Knit = require(ReplicatedStorage.Knit)
local CatchFactory = require(ReplicatedStorage.Knit.Util.Additions.Promises.CatchFactory)
local Enumeration = require(ReplicatedStorage.Knit.Util.Additions.Enumeration)
local Promise = require(ReplicatedStorage.Knit.Util.Promise)
local PromiseChildOfClass = require(ReplicatedStorage.Knit.Util.Additions.Promises.PromiseChildOfClass)
local Signal = require(ReplicatedStorage.Knit.Util.Signal)
local Typer = require(ReplicatedStorage.Knit.Util.Additions.Debugging.Typer)
local ContainerService = Knit.CreateService({
Client = {};
Name = "ContainerService";
})
ContainerService.Attribute = "__CONTAINER_ID__"
ContainerService.PendingContainers = {}
--[=[
@prop Hashes {[UserId]: HashString}
@within ContainerService
]=]
ContainerService.Hashes = {}
--[=[
@prop InstanceReferences {[BaseInstance]: {[UserId]: CloneInstance}}
@within ContainerService
]=]
ContainerService.InstanceReferences = {}
--[=[
@prop RootContainers {[UserId]: RootContainerScreenGui}
@within ContainerService
]=]
ContainerService.RootContainers = {}
--[=[
@prop PendingContainerCompleted Signal<UserId: number, ContainerId: string>
@within ContainerService
]=]
ContainerService.PendingContainerCompleted = Signal.new()
--[=[
@prop RootContainerReady RemoteSignal<Hash: string>
@tag Client
@within ContainerService
]=]
ContainerService.Client.RootContainerReady = Knit.CreateSignal()
local PostSimulationEvent = RunService.Heartbeat
local function LinkToInstanceLite(Object: Instance, Function: () -> ())
local Connection
Connection = Object:GetPropertyChangedSignal("Parent"):Connect(function()
PostSimulationEvent:Wait()
if not Connection.Connected then
Function()
end
end)
end
local function PlayerAdded(Player: Player)
local ContainerHash = HttpService:GenerateGUID()
local UserId = Player.UserId
ContainerService.Hashes[UserId] = ContainerHash
ContainerService.RootContainers[UserId] = Promise.new(function(Resolve)
local Container = Instance.new("ScreenGui")
Container.Name = ContainerHash
Container.ResetOnSpawn = false
PromiseChildOfClass(Player, "PlayerGui", 10):Then(function(PlayerGui: PlayerGui)
Container.Parent = PlayerGui
end):Catch(CatchFactory("PromiseChildOfClass")):Wait()
Resolve(Container)
ContainerService.Client.RootContainerReady:Fire(Player, ContainerHash)
end)
end
local function PlayerRemoving(Player: Player)
local UserId = Player.UserId
ContainerService.Hashes[UserId] = nil
ContainerService.RootContainers[UserId] = nil
for InstanceReference, CloneReferences in next, ContainerService.InstanceReferences do
for UserIdReference in next, CloneReferences do
if UserIdReference == UserId then
ContainerService.InstanceReferences[InstanceReference][UserIdReference] = nil
end
end
end
end
--[=[
Gets the Container for the given Player and ContainerId.
@param Player Player
@param ContainerId string
@return Promise<Folder>
]=]
function ContainerService:GetContainer(Player: Player, ContainerId: string)
local UserId = Player.UserId
if not self.RootContainers[UserId] then
return Enumeration.ContainerStatus.NotReady.Value
end
if not self.PendingContainers[UserId] then
self.PendingContainers[UserId] = {}
end
return self.RootContainers[UserId]:Then(function(RootContainer)
local Container = RootContainer:FindFirstChild(ContainerId)
if Container then
return Container
else
if self.PendingContainers[UserId][ContainerId] then
return Promise.FromEvent(self.PendingContainerCompleted, function(PendingUserId, PendingContainerId)
return PendingUserId == UserId and PendingContainerId == ContainerId
end):Then(function()
return self:GetContainer(Player, ContainerId)
end)
end
self.PendingContainers[UserId][ContainerId] = true
Container = Instance.new("Folder")
Container:SetAttribute(self.Attribute, ContainerId)
Container.Name = ContainerId
Container.Parent = RootContainer
self.PendingContainers[UserId][ContainerId] = nil
self.PendingContainerCompleted:Fire(UserId, ContainerId)
return Container
end
end)
end
--[=[
Clears the Container for the given Player and ContainerId.
@param Player Player
@param ContainerId string
@return Promise<void>
]=]
function ContainerService:ClearContainer(Player: Player, ContainerId: string)
return self:GetContainer(Player, ContainerId):Then(function(Container: Folder)
Container:ClearAllChildren()
end)
end
--[=[
Replicates the given Object to the Player with the ContainerId.
@param Player Player
@param ContainerId string
@param Object Instance
@return Promise<Instance>
]=]
function ContainerService:ReplicateTo(Player: Player, ContainerId: string, Object: Instance)
local UserId = Player.UserId
if not self.InstanceReferences[Object] then
self.InstanceReferences[Object] = {}
end
if self.InstanceReferences[Object][UserId] then
return Promise.Resolve(self.InstanceReferences[Object][UserId])
end
return self:GetContainer(Player, ContainerId):Then(function(Container: Folder)
local CloneObject = Object:Clone()
self.InstanceReferences[Object][UserId] = CloneObject
CloneObject.Parent = Container
LinkToInstanceLite(CloneObject, function()
if self.InstanceReferences[Object][UserId] == CloneObject then
self.InstanceReferences[Object][UserId] = nil
end
end)
return CloneObject
end)
end
--[=[
Dereplicates the Object from the Player.
@param Player Player
@param Object Instance
]=]
function ContainerService:DereplicateFrom(Player: Player, Object: Instance)
local UserId = Player.UserId
local InstanceReference = self.InstanceReferences[Object]
if InstanceReference and InstanceReference[UserId] then
InstanceReference[UserId]:Destroy()
end
end
--[=[
Requests the root container hash for the player.
@tag Client
@param Player Player -- You do not need to pass this on the client, it'll automatically be passed.
@return Hash string?
@return StatusCode number
]=]
function ContainerService.Client:RequestRootContainerHash(Player: Player): (string?, number)
local UserId = Player.UserId
local RootContainerHash = self.Server.Hashes[UserId]
if RootContainerHash then
return RootContainerHash, Enumeration.ContainerStatus.Success.Value
end
return nil, Enumeration.ContainerStatus.NotReady.Value
end
ContainerService.GetContainer = Typer.PromiseAssignSignature(2, Typer.InstanceWhichIsAPlayer, Typer.String, ContainerService.GetContainer)
ContainerService.ClearContainer = Typer.PromiseAssignSignature(2, Typer.InstanceWhichIsAPlayer, Typer.String, ContainerService.ClearContainer)
ContainerService.ReplicateTo = Typer.PromiseAssignSignature(2, Typer.InstanceWhichIsAPlayer, Typer.String, Typer.Instance, ContainerService.DereplicateFrom)
ContainerService.DereplicateFrom = Typer.AssignSignature(2, Typer.InstanceWhichIsAPlayer, Typer.Instance, ContainerService.DereplicateFrom)
ContainerService.Client.RequestRootContainerHash = Typer.AssignSignature(2, Typer.InstanceWhichIsAPlayer, ContainerService.Client.RequestRootContainerHash)
function ContainerService:KnitInit()
for _, Player in ipairs(Players:GetPlayers()) do
task.spawn(PlayerAdded, Player)
end
Players.PlayerAdded:Connect(PlayerAdded)
Players.PlayerRemoving:Connect(PlayerRemoving)
end
return ContainerService
|
--- DENG: dynamic engine - powerful 3D game engine
--- licence: Apache, see LICENCE file
--- file: premake5.lua - main premake5 configuration file
--- author: Karl-Mihkel Ott
workspace "deng"
cleancommands { "make clean %{cfg.buildcfg}" }
configurations { "Debug", "Release" }
platforms { "Win32", "Linux" }
includedirs {
"./headers",
"./modules/imgui",
"./modules/glad/include",
"./modules/nekowin/include"
}
architecture "x86_64"
defines { "ImDrawIdx=unsigned int", "__DENG_LIB_EXPORT" }
pic "On"
-- Ignore safety warnings that MSVC gives
filter "platforms:Win32"
defines { "_CRT_SECURE_NO_WARNINGS" }
-- Enable debug symbols if specified
filter "configurations:Debug"
symbols "On"
optimize "Debug"
targetdir "build/debug"
defines { "__DEBUG" }
filter "configurations:Release"
symbols "Off"
optimize "Speed"
targetdir "build/release"
filter {}
--!!! Add new options to use !!!--
-- Create an option to build DENG sandboxapp using specific sandbox configuration
newoption {
trigger = "sandbox-mode",
value = "MODE",
description = "Select sandbox application mode",
allowed = {
{ "deng", "Build an application for testing the renderer by loading assets" },
{ "imgui", "Build an application for testing ImGui with DENG renderer" },
{ "opengl", "Build a test application for testing OpenGL functionality" },
{ "all", "Build all sandbox applications" },
{ "none", "Do not build any sandbox applications" }
}
}
-- Check if given operating system is even supported
function oscheck()
if(not os.istarget("linux") and not os.istarget("windows")) then
local host = os.target()
host = host:gsub("%a", string.upper, 1)
print(host .. " is not supported by DENG! :(")
os.exit();
end
end
-- Define the clean action
function cleanoptcheck()
if _ACTION == "clean" then
print("Cleaning project files")
if(os.host() == "linux") then
os.execute("rm -rf *.make obj Makefile")
os.exit()
elseif(os.host() == "windows") then
os.execute("del /s /q deng.sln obj *.vcxproj*")
os.exit()
end
end
end
-- Check for the SDK path to be used in correct situation
function vksdkoptcheck()
-- Check if Vulkan SDK path should be and if it is specified
if os.istarget("windows") and _OPTIONS["vk-sdk-path"] then
libdirs { _OPTIONS["vk-sdk-path"] .. "\\Lib" }
includedirs{ _OPTIONS["vk-sdk-path"] .. "\\Include" }
elseif os.istarget("windows") then
libdirs { "C:/VulkanSDK/*/Lib" }
includedirs { "C:/VulkanSDK/*/Include" }
end
end
-- Check if given options are valid
function optcheck()
cleanoptcheck()
vksdkoptcheck()
end
-- Check which modules to build
function modcheck()
-- These modules are going to be required so they are built
local imgui = require("premake/imgui")
imgui.build()
local libneko = require("premake/libneko");
libneko.build()
end
-- Setup build destinations
function buildcfg()
if _OPTIONS["sandbox-mode"] then
-- Sandbox application build configuration
if _OPTIONS["sandbox-mode"] == "deng" or _OPTIONS["sandbox-mode"] == "all" then
local dengbox = require("premake/dengbox")
dengbox.build()
end
if _OPTIONS["sandbox-mode"] == "imgui" or _OPTIONS["sandbox-mode"] == "all" then
local imgui_sandbox = require("premake/imgui_sandbox")
imgui_sandbox.build()
end
if _OPTIONS["sandbox-mode"] == "opengl" or _OPTIONS["sandbox-mode"] == "all" then
local opengl_sandbox = require("premake/opengl_sandbox")
opengl_sandbox.build()
end
end
-- Build DENG runtime library
local libdeng = require("premake/libdeng")
libdeng.build()
--- Filters for libdeng build regarding sandbox application builds
filter "options:sandbox-mode=all or options:sandbox-mode=imgui or options:sandbox-mode=opengl or options:sandbox-mode=deng"
postbuildcommands {
"{RMDIR} %{cfg.targetdir}/assets",
"{COPYDIR} assets %{cfg.targetdir}/assets",
"{RMDIR} %{cfg.targetdir}/shaders",
"{COPYDIR} shaders %{cfg.targetdir}/shaders",
"{RMDIR} %{cfg.targetdir}/textures",
"{COPYDIR} textures %{cfg.targetdir}/textures"
}
filter "options:sandbox-mode=none"
postbuildcommands {
"{RMDIR} %{cfg.targetdir}/shaders",
"{COPYDIR} shaders %{cfg.targetdir}/shaders"
}
-- Build DENG asset manager application
local dam = require("premake/dam")
dam.build()
-- Build DENG scene editor
local scene_ed = require("premake/scene_ed")
scene_ed.build()
end
-- Script entry point, check if not help
if not _OPTIONS["help"] then
oscheck()
optcheck()
modcheck()
buildcfg()
end
|
function love.conf(t)
t.modules.window = false
end
|
assets = require('libs.cargo').init('assets')
Button = require "Button"
Signal = require 'libs.hump.signal'
local game = require "game"
local menu = {}
music = love.audio.newSource("assets/music/theme.wav", "static")
local startBtn = Button(assets.gfx.btnstart, 150, 160, 32, 16)
function menu:enter()
canvas = love.graphics.newCanvas(256, 192)
music:setLooping(true)
love.audio.setVolume(0.4)
music:play()
end
Signal.register('startGame', function()
love.graphics.setCanvas(canvas)
love.graphics.clear()
love.graphics.setCanvas()
Gamestate.switch(game)
end)
function menu:draw()
love.graphics.setCanvas(canvas)
love.graphics.clear()
love.graphics.setBlendMode("alpha")
love.graphics.draw(assets.gfx.title, 0, 0)
startBtn:draw()
love.graphics.setCanvas()
love.graphics.scale(4, 4)
love.graphics.setColor(1, 1, 1, 1)
love.graphics.setBlendMode("alpha", "premultiplied")
love.graphics.draw(canvas)
end
function menu:mousereleased(x, y, button)
startBtn:mousereleased(x, y, button)
end
return menu
|
--Copyright (c) 2013, Banggugyangu
--All rights reserved.
--Redistribution and use in source and binary forms, with or without
--modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of <addon name> nor the
-- names of its contributors may be used to endorse or promote products
-- derived from this software without specific prior written permission.
--THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
--ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
--WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
--DISCLAIMED. IN NO EVENT SHALL <your name> BE LIABLE FOR ANY
--DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
--(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
--LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
--ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
--(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
--SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function event_load()
version = '1.0.0'
PetNuke = ' '
PetHeal = ' '
TP_Set = ' '
Idle_Set = ' '
send_command('alias ps lua c petschool')
send_command('alias petschool lua c petschool')
options_load()
end
--Function Designer: Byrth
function options_load()
local f = io.open(lua_base_path..'data/settings.txt', "r")
if f == nil then
local g = io.open(lua_base_path..'data/settings.txt', "w")
g:write('Release Date: 2:16 PM, 4-22-13\46\n')
g:write('Author Comment: This document is whitespace sensitive, which means that you need the same number of spaces between things as exist in this initial settings file\46\n')
g:write('Author Comment: It looks at the first two words separated by spaces and then takes anything as the value in question if the first two words are relevant\46\n')
g:write('Author Comment: If you ever mess it up so that it does not work, you can just delete it and PetSchool will regenerate it upon reload\46\n')
g:write('Author Comment: For the Gearset, simply place the name of the spellcast set for each setting exactly how it is spelled in spellcast.\n')
g:write('Author Comment: The design of the settings file is credited to Byrthnoth as well as the creation of the settings file.\n\n\n\n')
g:write('Fill In Settings Below:\n')
g:write('PetNuke Set: PetNuke\nPetHeal Set: PetHeal\nTP Set: TP\nIdle Set: Movement\n')
g:close()
write('Default settings file created')
add_to_chat(17,'PetSchool created a settings file and loaded!')
add_to_chat(17,'Please Modify the Settings file to fit your spellcast .XML file')
else
f:close()
for curline in io.lines(lua_base_path..'data/settings.txt') do
local splat = split(curline,' ')
local cmd = ''
if splat[2] ~=nil then
cmd = (splat[1]..' '..splat[2]):gsub(':',''):lower()
end
if cmd == 'petnuke set' then
PetNuke = splat[3]
elseif cmd == 'petheal set' then
PetHeal = splat[3]
elseif cmd == 'tp set' then
TP_Set = splat[3]
elseif cmd == 'idle set' then
Idle_Set = splat[3]
end
end
add_to_chat(17,'PetSchool read from a settings file and loaded!')
end
end
function event_action(act)
local player = get_player()
local pet = get_mob_by_index(get_mob_by_index(get_player()['index'])['pet_index'])['id']
local actor = act.actor_id
local category = act.category
local targets = act.targets
local actionTarget = get_mob_by_id(targets[1]['id'])
if actor == pet then
if category == 8 then
if actionTarget.is_npc == true then
send_command('sc set ' .. PetNuke)
add_to_chat(17, ' Pet Spellcast Started: Nuking')
elseif actionTarget.is_npc == false then
send_command('sc set ' .. PetHeal)
add_to_chat(17, ' Pet Spellcast Started: Curing/Buffing')
end
elseif category == 4 then
if (player.status:lower() == 'engaged') then
send_command('sc set ' .. TP_Set)
add_to_chat(17, ' Pet Spellcast Finished')
elseif (player.status:lower() == 'idle') then
send_command('sc set ' .. Idle_Set)
add_to_chat(17, ' Pet Spellcast Finished')
end
end
end
end
--Function Author: Byrth
function split(msg, match)
local length = msg:len()
local splitarr = {}
local u = 1
while u <= length do
local nextanch = msg:find(match,u)
if nextanch ~= nil then
splitarr[#splitarr+1] = msg:sub(u,nextanch-match:len())
if nextanch~=length then
u = nextanch+match:len()
else
u = lengthlua
end
else
splitarr[#splitarr+1] = msg:sub(u,length)
u = length+1
end
end
return splitarr
end
--Function Designer: Byrth
function event_addon_command(...)
local term = table.concat({...}, ' ')
local splitarr = split(term,' ')
if splitarr[1]:lower() == 'reload' then
options_load()
elseif splitarr[1]:lower() == 'help' then
add_to_chat(17, 'PetSchool v'..version..'commands:')
add_to_chat(17, '//ps [options]')
add_to_chat(17, ' reload - Reloads settings')
add_to_chat(17, ' help - Displays this help text')
end
end
|
AddCSLuaFile()
DEFINE_BASECLASS("emod_base")
ENT.Category = "EMod"
ENT.Spawnable = true
ENT.PrintName = "EMod Meter"
ENT.EMODable = true
if SERVER then
function ENT:Initialize()
self:SetModel("models/emod/emod_meter.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:PhysWake()
self:SetCollisionGroup(COLLISION_GROUP_NONE)
self.Temperature = 25.0
self.EModOutputs = {{name="INPUT",pinPos=Vector(-26.922850,15.989843,0.077148)},{name="OUTPUT",pinPos=Vector(-26.922947,-15.988745,0.101563)}}
self.EModScheme = {
[1]={[2]={}},
[2]={[1]={}}
}
self:RegisterCallback(1,function(edata,dedata) self:SetVal(math.Clamp(dedata.I,self:GetMinVal(),self:GetMaxVal())) self.LastCurrent = CurTime() end)
self:RegisterCallback(2,function(edata,dedata) self:SetVal(math.Clamp(-dedata.I,self:GetMinVal(),self:GetMaxVal())) self.LastCurrent = CurTime() end)
self.LastCurrent = 0
end
function ENT:Think()
if CurTime()-self.LastCurrent > EMODTick then self:SetVal(0) end
self:NextThink(CurTime() + EMODTick)
return true
end
end
if CLIENT then
ENT.valSys = SysTime()
ENT.preval = 0
ENT.moveTo = 0
ENT.Move = false
function ENT:Draw()
self:DrawModel()
cam.Start3D2D(self:LocalToWorld(Vector(-0.45,-5.6,9.95)),self:LocalToWorldAngles(Angle(0,90,90)),0.1)
local w,t = 114,56
local light = GetLightAmount(self:LocalToWorld(Vector(-0.45,-5.65,9.95)))
if self.preval != self:GetVal() and not self.Move then self.valSys = SysTime() self.Move = true self.moveTo = self:GetVal() end
if Erp(SysTime()-self.valSys,1,self.preval,self.moveTo) == self.moveTo and self.Move then
self.preval = self.moveTo
self.Move = false
end
local goval = Erp(SysTime()-self.valSys,1,self.preval,self.moveTo)
local Val = math.Remap(math.Clamp(goval,self:GetMinVal(),self:GetMaxVal()),self:GetMinVal(),self:GetMaxVal(),0,1)
local angle = math.Remap(math.Clamp(Val,0,1),0,1,-30,-150)
draw.NoTexture()
surface.SetDrawColor(Color(0,0,0,light))
surface.HalfCircle(w/2-(t*0.8),t*0.3,t*0.8,true)
draw.SimpleText(self:GetMinVal(),"DermaDefault",w/2-t*0.75,t*0.62,Color(0,0,0,light),1,1)
draw.SimpleText(self:GetMaxVal(),"DermaDefault",w/2+t*0.75,t*0.62,Color(0,0,0,light),1,1)
draw.SimpleText(self:GetLetter(),"DermaLarge",w/2,t*0.7,Color(50,0,0,light),1,1)
surface.SetDrawColor(Color(100,0,0,light))
surface.DrawTexturedRectRotatedPoint(w/2,t*1.1,t,3,angle,t*0.3,0)
cam.End3D2D()
end
function surface.DrawTexturedRectRotatedPoint( x, y, w, h, rot, x0, y0 )
local c = math.cos( math.rad( rot ) )
local s = math.sin( math.rad( rot ) )
local newx = y0 * s - x0 * c
local newy = y0 * c + x0 * s
surface.DrawTexturedRectRotated( x + newx, y + newy, w, h, rot )
end
function Erp(t, d, b, c) return (c-b) * (math.pow(math.Clamp(t,0,d) / d - 1, 3) + 1) + b end
function surface.HalfCircle(x0,y0,r,side)
x0 = x0+r
if side then y0 = y0+r end
local function y(x) return side and y0-math.sqrt((r^2)-((x-x0)^2)) or y0+math.sqrt((r^2)-((x-x0)^2)) end
local dots = {}
if side then
for I=x0-r,x0+r,0.1 do
table.insert(dots,{x=I,y=y(I)})
end
else
for I=x0+r,x0-r,-0.1 do
table.insert(dots,{x=I,y=y(I)})
end
end
surface.DrawPoly(dots)
end
end
function ENT:SetupDataTables()
self:NetworkVar("Float",0,"Val")
self:NetworkVar("Float",1,"MinVal")
self:NetworkVar("Float",2,"MaxVal")
self:NetworkVar("String",0,"Letter")
if SERVER then
self:SetVal(0)
self:SetLetter("A")
self:SetMinVal(0)
self:SetMaxVal(1)
end
end
|
--[[
This script is an heavy modification of the soundstreamer package :
https://github.com/BlueMountainsIO/OnsetLuaScripts/tree/master/soundstreamer
Modified By GalaxHD551
]]--
local StreamedLights = {}
AddEvent("OnPackageStart", function()
math.randomseed(os.time())
end)
AddEvent("OnPackageStop", function()
for k, v in pairs(StreamedLights) do
DestroyObject(k)
end
StreamedLights = nil
end)
AddFunctionExport("CreateLight", function (lighttype, x, y, z, rx, ry, rz, color, intensity, distance)
if lighttype == nil or x == nil or y == nil or z == nil then
return false
end
rx = rx or 0.0
ry = ry or 0.0
rz = rz or 0.0
color = color or RGB(255, 255, 255)
intensity = intensity or 5000.0
stream_distance = distance or 12000.0
-- Create an object that will help us to attach the light to it
local lightid = CreateObject(1, x, y, z)
if lightid == false then
return false
end
SetObjectStreamDistance(lightid, stream_distance)
SetObjectRotation(lightid, rx, ry, rz)
local _lightStream = { }
_lightStream.is_attached = false
_lightStream.lighttype = lighttype
_lightStream.color = color
_lightStream.intensity = intensity
_lightStream.stream_distance = stream_distance
_lightStream.attenuation_radius = 1000.0
_lightStream.shadow = true
if lighttype == "SPOTLIGHT" then
_lightStream.outer_cone = 44.0
_lightStream.inner_cone = 0.0
_lightStream.source_radius = 0.0
_lightStream.soft_source_radius = 0.0
_lightStream.source_lenght = 0.0
_lightStream.falloff = 0.0
elseif lighttype == "POINTLIGHT" then
_lightStream.source_radius = 0.0
_lightStream.soft_source_radius = 0.0
_lightStream.source_lenght = 0.0
_lightStream.falloff = 0.0
elseif lighttype == "RECTLIGHT" then
_lightStream.source_width = 64.0
_lightStream.source_height = 64.0
_lightStream.barn_door_angle = 88.0
_lightStream.barn_door_lenght = 20.0
end
SetObjectPropertyValue(lightid, "_lightStream", _lightStream)
StreamedLights[lightid] = _lightStream
return lightid
end)
AddFunctionExport("DuplicateLight", function (lightid)
if lightid == nil then
return false
end
local x, y, z = GetObjectLocation(lightid)
local newlight = CreateObject(1, x, y, z)
if lightid == false then
return false
end
local rx, ry, rz = GetObjectRotation(lightid)
SetObjectRotation(newlight, rx, ry, rz)
SetObjectPropertyValue(newlight, "_lightStream", StreamedLights[lightid])
StreamedLights[newlight] = StreamedLights[lightid]
return newlight
end)
AddFunctionExport("SetLightAttached", function(lightid, attachtype, attachid, x, y, z, rx, ry, rz, SocketName)
if lightid == nil or attachtype == nil or attachid == nil then
return false
end
x = x or 0.0
y = y or 0.0
z = z or 0.0
rx = rx or 0.0
ry = ry or 0.0
rz = rz or 0.0
bone = SocketName or ""
if StreamedLights[lightid] == nil then
return false
end
if SetObjectAttached(lightid, attachtype, attachid, x, y, z, rx, ry, rz, bone) == false then
return false
end
StreamedLights[lightid].is_attached = true
StreamedLights[lightid].attach = attachtype
StreamedLights[lightid].id = attachid
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetAttachedLights", function(attachtype, id)
if attachtype == nil or id == nil then
return false
end
local lights = { }
for k, v in pairs(StreamedLights) do
if v.is_attached == true then
if v.attach == attachtype and v.id == id then
table.insert(lights, k)
end
end
end
return lights
end)
AddFunctionExport("SetLightDetached", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].is_attached == false then
return false
end
SetObjectDetached(lightid)
return true
end)
AddFunctionExport("DestroyLight", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
StreamedLights[lightid] = nil
return DestroyObject(lightid)
end)
AddFunctionExport("GetAllLights", function()
local _table = {}
for k,v in pairs(StreamedLights) do
table.insert(_table, k)
end
return _table
end)
AddFunctionExport("IsValidLight", function(lightid)
return StreamedLights[lightid] ~= nil
end)
AddFunctionExport("IsAttachedLight", function(lightid)
if StreamedLights[lightid] == nil then
return false
end
return StreamedLights[lightid].is_attached
end)
AddFunctionExport("SetLightIntensity", function(lightid, intensity)
if lightid == nil or intensity == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
StreamedLights[lightid].intensity = intensity
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("SetLightColor", function(lightid, color)
if lightid == nil or color == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
StreamedLights[lightid].color = color
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightColor", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
return StreamedLights[lightid].color
end)
AddFunctionExport("SetLightAttenuationRadius", function(lightid, radius)
if lightid == nil or radius == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
StreamedLights[lightid].attenuation_radius = radius
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightAttenuationRadius", function(lightid)
if lightid == nil or radius == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
return StreamedLights[lightid].attenuation_radius
end)
AddFunctionExport("SetLightIntensityUnits", function(lightid, intensityU)
if lightid == nil or intensityU == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
StreamedLights[lightid].intensityU = intensityU
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightIntensityUnits", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
return StreamedLights[lightid].intensityU
end)
AddFunctionExport("SetLightFalloffExponent", function(lightid, falloff)
if lightid == nil or falloff == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype == "RECTLIGHT" then
return false
end
StreamedLights[lightid].falloff = falloff
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightFalloffExponent", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype == "RECTLIGHT" then
return false
end
return StreamedLights[lightid].falloff
end)
AddFunctionExport("SetLightSoftSourceRadius", function(lightid, radius)
if lightid == nil or radius == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype == "RECTLIGHT" then
return false
end
StreamedLights[lightid].soft_source_radius = radius
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightSoftSourceRadius", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype == "RECTLIGHT" then
return false
end
return StreamedLights[lightid].soft_source_radius
end)
AddFunctionExport("SetLightSourceLength", function(lightid, lenght)
if lightid == nil or lenght == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype == "RECTLIGHT" then
return false
end
StreamedLights[lightid].source_lenght = lenght
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightSourceLength", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype == "RECTLIGHT" then
return false
end
return StreamedLights[lightid].source_lenght
end)
AddFunctionExport("SetLightSourceRadius", function(lightid, radius)
if lightid == nil or radius == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype == "RECTLIGHT" then
return false
end
StreamedLights[lightid].source_radius = radius
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightSourceRadius", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype == "RECTLIGHT" then
return false
end
return StreamedLights[lightid].source_radius
end)
AddFunctionExport("SetLightCastShadows", function(lightid, bEnable)
if lightid == nil or bEnable == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
StreamedLights[lightid].shadow = bEnable
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightCastShadows", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
return StreamedLights[lightid].shadow
end)
AddFunctionExport("SetLightOuterConeAngle", function(lightid, degree)
if lightid == nil or degree == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "SPOTLIGHT" then
return false
end
StreamedLights[lightid].outer_cone = degree
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightOuterConeAngle", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "SPOTLIGHT" then
return false
end
return StreamedLights[lightid].outer_cone
end)
AddFunctionExport("SetLightInnerConeAngle", function(lightid, degree)
if lightid == nil or degree == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "SPOTLIGHT" then
return false
end
StreamedLights[lightid].inner_cone = degree
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightInnerConeAngle", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "SPOTLIGHT" then
return false
end
return StreamedLights[lightid].inner_cone
end)
AddFunctionExport("SetLightBarnDoorAngle", function(lightid, degree)
if lightid == nil or degree == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "RECTLIGHT" then
return false
end
StreamedLights[lightid].barn_door_angle = degree
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightBarnDoorAngle", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "RECTLIGHT" then
return false
end
return StreamedLights[lightid].barn_door_angle
end)
AddFunctionExport("SetLightBarnDoorLength", function(lightid, lenght)
if lightid == nil or lenght == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "RECTLIGHT" then
return false
end
StreamedLights[lightid].barn_door_lenght = lenght
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightBarnDoorLength", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "RECTLIGHT" then
return false
end
return StreamedLights[lightid].barn_door_lenght
end)
AddFunctionExport("SetLightSourceHeight", function(lightid, height)
if lightid == nil or height == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "RECTLIGHT" then
return false
end
StreamedLights[lightid].source_height = height
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightSourceHeight", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "RECTLIGHT" then
return false
end
return StreamedLights[lightid].source_height
end)
AddFunctionExport("SetLightSourceWidth", function(lightid, width)
if lightid == nil or width == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "RECTLIGHT" then
return false
end
StreamedLights[lightid].source_width = width
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightSourceWidth", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].lighttype ~= "RECTLIGHT" then
return false
end
return StreamedLights[lightid].source_width
end)
AddFunctionExport("SetLightStreamDistance", function(lightid, distance)
if lightid == nil or distance == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
SetObjectStreamDistance(lightid, distance)
StreamedLights[lightid].stream_distance = distance
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("GetLightStreamRadius", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
return StreamedLights[lightid].stream_distance
end)
AddFunctionExport("SetLightDimension", function(lightid, dimension)
if lightid == nil or dimension == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
return SetObjectDimension(lightid, dimension)
end)
AddFunctionExport("GetLightDimension", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
return GetObjectDimension(lightid)
end)
AddFunctionExport("SetLightLocation", function(lightid, x, y, z)
if lightid == nil or x == nil or y == nil or z == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].is_attached == true then
return false -- Can't sent location of an attached light
end
SetObjectLocation(lightid, x, y, z)
return true
end)
AddFunctionExport("GetLightLocation", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].is_attached == true then
return false
end
local x, y, z = GetObjectLocation(lightid)
return x, y, z
end)
AddFunctionExport("SetLightRotation", function(lightid, rx, ry, rz)
if lightid == nil or rx == nil or ry == nil or rz == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
SetObjectRotation(lightid, rx, ry, rz)
return true
end)
AddFunctionExport("GetLightRotation", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
local rx, ry, rz = GetObjectRotation(lightid)
return rx, ry, rz
end)
AddFunctionExport("SetLightRandomLoopColor", function(lightid, interval)
if lightid == nil or interval == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
loopcolor = CreateTimer(function()
r = math.random(1, 255)
g = math.random(1, 255)
b = math.random(1, 255)
color = RGB(r, g, b)
StreamedLights[lightid].color = color
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
end, interval)
StreamedLights[lightid].loopcolor = loopcolor
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("StopLightRandomLoopColor", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].loopcolor == nil then
return false
end
if DestroyTimer(StreamedLights[lightid].loopcolor) == false then
return false
end
StreamedLights[lightid].loopcolor = nil
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("SetLightLoopRotation", function(lightid, xAxis, yAxis, zAxis, speed)
if lightid == nil or (xAxis == nil and yAxis == nil and zAxis == nil) then
return false
end
if StreamedLights[lightid] == nil then
return false
end
xAxis = xAxis or 0
yAxis = yAxis or 0
zAxis = zAxis or 0
speed = speed or 350
looprotation = CreateTimer(function()
local rx, ry, rz = GetObjectRotation(lightid)
SetObjectRotation(lightid, rx + xAxis, ry + yAxis, rz + zAxis)
end, speed)
StreamedLights[lightid].looprotation = looprotation
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("StopLightLoopRotation", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].looprotation == nil then
return false
end
if DestroyTimer(StreamedLights[lightid].looprotation) == false then
return false
end
StreamedLights[lightid].looprotation = nil
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("SetLightFlash", function(lightid, interval)
if lightid == nil or interval == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
local currentcolor = StreamedLights[lightid].color
local offcolor = RGB(0, 0, 0)
local flashinterval = CreateTimer(function()
if StreamedLights[lightid].color == currentcolor then
StreamedLights[lightid].color = offcolor
else
StreamedLights[lightid].color = currentcolor
end
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
end, interval)
StreamedLights[lightid].flashinterval = flashinterval
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
AddFunctionExport("StopLightFlash", function(lightid)
if lightid == nil then
return false
end
if StreamedLights[lightid] == nil then
return false
end
if StreamedLights[lightid].flashinterval == nil then
return false
end
if DestroyTimer(StreamedLights[lightid].flashinterval) == false then
return false
end
StreamedLights[lightid].flashinterval = nil
SetObjectPropertyValue(lightid, "_lightStream", StreamedLights[lightid])
return true
end)
|
local self = {}
CAC.Vermilion2BanSystem = CAC.MakeConstructor (self, CAC.IBanSystem)
function self:ctor ()
end
-- IReadOnlyBanSystem
function self:GetId ()
return "Vermilion2BanSystem"
end
function self:GetName ()
return "Vermilion 2"
end
function self:IsAvailable ()
return istable (Vermilion) and
istable (Vermilion.Modules) and
istable (Vermilion.Modules.bans)
end
function self:IsDefault ()
return false
end
-- Bans
function self:IsUserBanned (userId)
local banInfo = Vermilion.Modules.bans:GetBanData (userId)
if not banInfo then return false end
if banInfo.ExpiryTime == 0 then return true end
return os.time () <= banInfo.ExpiryTime
end
function self:GetCurrentBan (userId)
if self:IsUserBanned (userId) then return userId end
return nil
end
function self:GetBanReason (banId)
if not self:IsUserBanned (banId) then return nil end
local banInfo = Vermilion.Modules.bans:GetBanData (banId)
if not banInfo then return nil end
return banInfo.Reason
end
function self:GetBanTimeRemaining (banId)
if not self:IsUserBanned (banId) then return nil end
local banInfo = Vermilion.Modules.bans:GetBanData (banId)
if not banInfo then return nil end
if banInfo.ExpiryTime == 0 then return math.huge end
return math.max (0, os.time () - banInfo.ExpiryTime)
end
function self:GetBannerId (banId)
if not self:IsUserBanned (banId) then return nil end
local banInfo = Vermilion.Modules.bans:GetBanData (banId)
if not banInfo then return nil end
local bannerId = banInfo.BannerSteamID
if bannerId == "VERMILION" then
bannerId = "Server"
end
return bannerId
end
-- IBanSystem
function self:Ban (userId, duration, reason, bannerId)
if duration == math.huge then duration = 0 end
local ply = CAC.PlayerMonitor:GetUserEntity (userId) or NULL
if not ply:IsValid () then ply = NULL end
local banner = CAC.PlayerMonitor:GetUserEntity (bannerId) or NULL
if not banner:IsValid () then banner = NULL end
Vermilion.Modules.bans:BanPlayer (ply, banner, duration, reason)
end
function self:CanBanOfflineUsers ()
return false
end
CAC.SystemRegistry:RegisterSystem ("BanSystem", CAC.Vermilion2BanSystem ())
|
--[[
# Element: ClassPower
Handles the visibility and updating of the player's class resources (like Chi Orbs or Holy Power) and combo points.
## Widget
ClassPower - An `table` consisting of as many StatusBars as the theoretical maximum return of [UnitPowerMax](http://wowprogramming.com/docs/api/UnitPowerMax.html).
## Sub-Widgets
.bg - A `Texture` used as a background. It will inherit the color of the main StatusBar.
## Sub-Widget Options
.multiplier - Used to tint the background based on the widget's R, G and B values. Defaults to 1 (number)[0-1]
## Notes
A default texture will be applied if the sub-widgets are StatusBars and don't have a texture set.
If the sub-widgets are StatusBars, their minimum and maximum values will be set to 0 and 1 respectively.
Supported class powers:
- All - Combo Points
- Mage - Arcane Charges
- Monk - Chi Orbs
- Paladin - Holy Power
- Warlock - Soul Shards
## Examples
local ClassPower = {}
for index = 1, 10 do
local Bar = CreateFrame('StatusBar', nil, self)
-- Position and size.
Bar:SetSize(16, 16)
Bar:SetPoint('TOPLEFT', self, 'BOTTOMLEFT', (index - 1) * Bar:GetWidth(), 0)
ClassPower[index] = Bar
end
-- Register with oUF
self.ClassPower = ClassPower
--]]
local _, ns = ...
local oUF = ns.oUF
local _, PlayerClass = UnitClass('player')
-- sourced from FrameXML/Constants.lua
local SPEC_MAGE_ARCANE = SPEC_MAGE_ARCANE or 1
local SPEC_MONK_WINDWALKER = SPEC_MONK_WINDWALKER or 3
local SPEC_PALADIN_RETRIBUTION = SPEC_PALADIN_RETRIBUTION or 3
local SPEC_WARLOCK_DESTRUCTION = SPEC_WARLOCK_DESTRUCTION or 3
local SPELL_POWER_ENERGY = Enum.PowerType.Energy or 3
local SPELL_POWER_COMBO_POINTS = Enum.PowerType.ComboPoints or 4
local SPELL_POWER_SOUL_SHARDS = Enum.PowerType.SoulShards or 7
local SPELL_POWER_HOLY_POWER = Enum.PowerType.HolyPower or 9
local SPELL_POWER_CHI = Enum.PowerType.Chi or 12
local SPELL_POWER_ARCANE_CHARGES = Enum.PowerType.ArcaneCharges or 16
-- Holds the class specific stuff.
local ClassPowerID, ClassPowerType
local ClassPowerEnable, ClassPowerDisable
local RequireSpec, RequirePower, RequireSpell
local function UpdateColor(element, powerType)
local color = element.__owner.colors.power[powerType]
local r, g, b = color[1], color[2], color[3]
for i = 1, #element do
local bar = element[i]
bar:SetStatusBarColor(r, g, b)
local bg = bar.bg
if(bg) then
local mu = bg.multiplier or 1
bg:SetVertexColor(r * mu, g * mu, b * mu)
end
end
end
local function Update(self, event, unit, powerType)
if(not (unit and (UnitIsUnit(unit, 'player') and powerType == ClassPowerType
or unit == 'vehicle' and powerType == 'COMBO_POINTS'))) then
return
end
local element = self.ClassPower
--[[ Callback: ClassPower:PreUpdate(event)
Called before the element has been updated.
* self - the ClassPower element
]]
if(element.PreUpdate) then
element:PreUpdate()
end
local cur, max, mod, oldMax
if(event ~= 'ClassPowerDisable') then
local powerID = unit == 'vehicle' and SPELL_POWER_COMBO_POINTS or ClassPowerID
cur = UnitPower(unit, powerID, true)
max = UnitPowerMax(unit, powerID)
mod = UnitPowerDisplayMod(powerID)
-- mod should never be 0, but according to Blizz code it can actually happen
cur = mod == 0 and 0 or cur / mod
-- BUG: Destruction is supposed to show partial soulshards, but Affliction and Demonology should only show full ones
if(ClassPowerType == 'SOUL_SHARDS' and GetSpecialization() ~= SPEC_WARLOCK_DESTRUCTION) then
cur = cur - cur % 1
end
local numActive = cur + 0.9
for i = 1, max do
if(i > numActive) then
element[i]:Hide()
element[i]:SetValue(0)
else
element[i]:Show()
element[i]:SetValue(cur - i + 1)
end
end
oldMax = element.__max
if(max ~= oldMax) then
if(max < oldMax) then
for i = max + 1, oldMax do
element[i]:Hide()
element[i]:SetValue(0)
end
end
element.__max = max
end
end
--[[ Callback: ClassPower:PostUpdate(cur, max, hasMaxChanged, powerType)
Called after the element has been updated.
* self - the ClassPower element
* cur - the current amount of power (number)
* max - the maximum amount of power (number)
* hasMaxChanged - indicates whether the maximum amount has changed since the last update (boolean)
* powerType - the active power type (string)
--]]
if(element.PostUpdate) then
return element:PostUpdate(cur, max, oldMax ~= max, powerType)
end
end
local function Path(self, ...)
--[[ Override: ClassPower.Override(self, event, unit, ...)
Used to completely override the internal update function.
* self - the parent object
* event - the event triggering the update (string)
* unit - the unit accompanying the event (string)
* ... - the arguments accompanying the event
--]]
return (self.ClassPower.Override or Update) (self, ...)
end
local function Visibility(self, event, unit)
local element = self.ClassPower
local shouldEnable
if(UnitHasVehicleUI('player')) then
shouldEnable = PlayerVehicleHasComboPoints()
unit = 'vehicle'
elseif(ClassPowerID) then
if(not RequireSpec or RequireSpec == GetSpecialization()) then
-- use 'player' instead of unit because 'SPELLS_CHANGED' is a unitless event
if(not RequirePower or RequirePower == UnitPowerType('player')) then
if(not RequireSpell or IsPlayerSpell(RequireSpell)) then
self:UnregisterEvent('SPELLS_CHANGED', Visibility)
shouldEnable = true
unit = 'player'
else
self:RegisterEvent('SPELLS_CHANGED', Visibility, true)
end
end
end
end
local isEnabled = element.isEnabled
local powerType = unit == 'vehicle' and 'COMBO_POINTS' or ClassPowerType
if(shouldEnable) then
--[[ Override: ClassPower:UpdateColor(powerType)
Used to completely override the internal function for updating the widgets' colors.
* self - the ClassPower element
* powerType - the active power type (string)
--]]
(element.UpdateColor or UpdateColor) (element, powerType)
end
if(shouldEnable and not isEnabled) then
ClassPowerEnable(self)
elseif(not shouldEnable and (isEnabled or isEnabled == nil)) then
ClassPowerDisable(self)
elseif(shouldEnable and isEnabled) then
Path(self, event, unit, powerType)
end
end
local function VisibilityPath(self, ...)
--[[ Override: ClassPower.OverrideVisibility(self, event, unit)
Used to completely override the internal visibility function.
* self - the parent object
* event - the event triggering the update (string)
* unit - the unit accompanying the event (string)
--]]
return (self.ClassPower.OverrideVisibility or Visibility) (self, ...)
end
local function ForceUpdate(element)
return VisibilityPath(element.__owner, 'ForceUpdate', element.__owner.unit)
end
do
function ClassPowerEnable(self)
self:RegisterEvent('UNIT_POWER_FREQUENT', Path)
self:RegisterEvent('UNIT_MAXPOWER', Path)
self.ClassPower.isEnabled = true
if(UnitHasVehicleUI('player')) then
Path(self, 'ClassPowerEnable', 'vehicle', 'COMBO_POINTS')
else
Path(self, 'ClassPowerEnable', 'player', ClassPowerType)
end
end
function ClassPowerDisable(self)
self:UnregisterEvent('UNIT_POWER_FREQUENT', Path)
self:UnregisterEvent('UNIT_MAXPOWER', Path)
local element = self.ClassPower
for i = 1, #element do
element[i]:Hide()
end
self.ClassPower.isEnabled = false
Path(self, 'ClassPowerDisable', 'player', ClassPowerType)
end
if(PlayerClass == 'MONK') then
ClassPowerID = SPELL_POWER_CHI
ClassPowerType = 'CHI'
RequireSpec = SPEC_MONK_WINDWALKER
elseif(PlayerClass == 'PALADIN') then
ClassPowerID = SPELL_POWER_HOLY_POWER
ClassPowerType = 'HOLY_POWER'
RequireSpec = SPEC_PALADIN_RETRIBUTION
elseif(PlayerClass == 'WARLOCK') then
ClassPowerID = SPELL_POWER_SOUL_SHARDS
ClassPowerType = 'SOUL_SHARDS'
elseif(PlayerClass == 'ROGUE' or PlayerClass == 'DRUID') then
ClassPowerID = SPELL_POWER_COMBO_POINTS
ClassPowerType = 'COMBO_POINTS'
if(PlayerClass == 'DRUID') then
RequirePower = SPELL_POWER_ENERGY
RequireSpell = 5221 -- Shred
end
elseif(PlayerClass == 'MAGE') then
ClassPowerID = SPELL_POWER_ARCANE_CHARGES
ClassPowerType = 'ARCANE_CHARGES'
RequireSpec = SPEC_MAGE_ARCANE
end
end
local function Enable(self, unit)
local element = self.ClassPower
if(element and UnitIsUnit(unit, 'player')) then
element.__owner = self
element.__max = #element
element.ForceUpdate = ForceUpdate
if(RequireSpec or RequireSpell) then
self:RegisterEvent('PLAYER_TALENT_UPDATE', VisibilityPath, true)
end
if(RequirePower) then
self:RegisterEvent('UNIT_DISPLAYPOWER', VisibilityPath)
end
element.ClassPowerEnable = ClassPowerEnable
element.ClassPowerDisable = ClassPowerDisable
for i = 1, #element do
local bar = element[i]
if(bar:IsObjectType('StatusBar')) then
if(not bar:GetStatusBarTexture()) then
bar:SetStatusBarTexture([[Interface\TargetingFrame\UI-StatusBar]])
end
bar:SetMinMaxValues(0, 1)
end
end
return true
end
end
local function Disable(self)
if(self.ClassPower) then
ClassPowerDisable(self)
self:UnregisterEvent('PLAYER_TALENT_UPDATE', VisibilityPath)
self:UnregisterEvent('UNIT_DISPLAYPOWER', VisibilityPath)
self:UnregisterEvent('SPELLS_CHANGED', Visibility)
end
end
oUF:AddElement('ClassPower', VisibilityPath, Enable, Disable)
|
local h = require("helper")
vim.bo.tabstop = 2
vim.bo.softtabstop = 2
vim.bo.shiftwidth = 2
h.map("n", "<Leader>gf", "<cmd>lua require('ftplugin.yaml').go_task_file()<CR>")
|
DB_TEMPLATE_EQUIP =
{
[1] = {name = "weapon_sword_1", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = nil, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 98, element = nil, attack = 15, defense = 0, mAttack = 0, speed = 0, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 200, suit = 0},
[2] = {name = "weapon_sword_2", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {12,0,0,0}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 96, element = nil, attack = 24, defense = 0, mAttack = 0, speed = -1, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 360, suit = 0},
[3] = {name = "weapon_sword_3", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {15,0,10,0}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 97, element = nil, attack = 32, defense = 0, mAttack = 5, speed = 0, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 600, suit = 0},
[4] = {name = "weapon_sword_4", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {18,0,0,0}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 94, element = nil, attack = 42, defense = 0, mAttack = 0, speed = 1, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 3, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 1000, suit = 0},
[5] = {name = "weapon_sword_5", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {22,0,0,20}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 92, element = nil, attack = 50, defense = 3, mAttack = 0, speed = -2, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 4, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 1500, suit = 0},
[6] = {name = "weapon_sword_6", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {24,0,16,0}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 95, element = nil, attack = 60, defense = 0, mAttack = 4, speed = 2, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 2200, suit = 0},
[7] = {name = "weapon_sword_7", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {32,20,0,0}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 93, element = nil, attack = 76, defense = -8, mAttack = 0, speed = 0, hitPoint = 0, manaPoint = 0, stamina = 0, luck = -3, resist = nil, accuracy = 0, avoid = 0, critical = 8, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 3100, suit = 0},
[8] = {name = "weapon_sword_8", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {40,0,24,32}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 98, element = nil, attack = 90, defense = 6, mAttack = 8, speed = 0, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 4200, suit = 0},
[9] = {name = "weapon_sword_9", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {50,30,0,40}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 96, element = nil, attack = 110, defense = 0, mAttack = 5, speed = 3, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 20, buff = nil, debuff = nil, magic = "", skill = "", price = 4200, suit = 0},
[10] = {name = "weapon_sword_10", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {60,45,30,50}, mainValue = "attack", rangeType = "", rangeValue = 1, hitRate = 94, element = nil, attack = 150, defense = 10, mAttack = 0, speed = 5, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 10, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 4200, suit = 0},
[11] = {name = "weapon_sword_11", icon = "weapon_sword", sound = "", type = 0, part = 0, requirement = {70,50,40,60}, mainValue = "attack", rangeType = "", rangeValue = 2, hitRate = 98, element = nil, attack = 200, defense = 15, mAttack = 10, speed = 10, hitPoint = 0, manaPoint = 0, stamina = 0, luck = 0, resist = nil, accuracy = 0, avoid = 0, critical = 0, counter = 0, movePoint = 0, atkTimes = 0, actionTwice = false, moveMagic = false, hpSave = 0, mpSave = 0, absorb = 0, hitMp = 0, hpRestore = 0, mpRestore = 0, spFast = 0, buff = nil, debuff = nil, magic = "", skill = "", price = 4200, suit = 0}
}
function TemplateEquipGet()
return nil
end
|
local K, C, L = unpack(select(2, ...))
local Module = K:NewModule("RaidUtility", "AceEvent-3.0")
local _G = _G
local find = string.find
local ipairs, pairs, next = ipairs, pairs, next
local tinsert, twipe, tsort = table.insert, table.wipe, table.sort
local CreateFrame = _G.CreateFrame
local CUSTOM_CLASS_COLORS = _G.CUSTOM_CLASS_COLORS
local DoReadyCheck = _G.DoReadyCheck
local GameTooltip = _G.GameTooltip
local GameTooltip_Hide = _G.GameTooltip_Hide
local GetNumGroupMembers = _G.GetNumGroupMembers
local GetRaidRosterInfo = _G.GetRaidRosterInfo
local GetTexCoordsForRole = _G.GetTexCoordsForRole
local InCombatLockdown = _G.InCombatLockdown
local InitiateRolePoll = _G.InitiateRolePoll
local IsInGroup = _G.IsInGroup
local IsInInstance = _G.IsInInstance
local IsInRaid = _G.IsInRaid
local RAID_CLASS_COLORS = _G.RAID_CLASS_COLORS
local ToggleFriendsFrame = _G.ToggleFriendsFrame
local UnitGroupRolesAssigned = _G.UnitGroupRolesAssigned
local UnitIsGroupAssistant = _G.UnitIsGroupAssistant
local UnitIsGroupLeader = _G.UnitIsGroupLeader
K["RaidUtility"] = Module
local PANEL_HEIGHT = 100
local CLASS_COLOR =
K.Class == "PRIEST" and K.PriestColors or (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[K.Class] or RAID_CLASS_COLORS[K.Class])
-- Check if We are Raid Leader or Raid Officer
local function CheckRaidStatus()
local inInstance, instanceType = IsInInstance()
if ((IsInGroup() and not IsInRaid()) or UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")) and not (inInstance and (instanceType == "pvp" or instanceType == "arena"))
then
return true
else
return false
end
end
local function ButtonEnter(self)
if not C["General"].ColorTextures then -- Fix a rare nil error
self:SetBackdropBorderColor(CLASS_COLOR.r, CLASS_COLOR.g, CLASS_COLOR.b, 1)
end
self.Backgrounds:SetColorTexture(CLASS_COLOR.r * .15, CLASS_COLOR.g * .15, CLASS_COLOR.b * .15, C["Media"].BackdropColor[4])
end
local function ButtonLeave(self)
if not C["General"].ColorTextures then -- Fix a rare nil error
self:SetBackdropBorderColor()
end
self.Backgrounds:SetColorTexture(C["Media"].BackdropColor[1], C["Media"].BackdropColor[2], C["Media"].BackdropColor[3], C["Media"].BackdropColor[4])
end
-- Function to create buttons in this module
function Module:CreateUtilButton(name, parent, template, width, height, point, relativeto, point2, xOfs, yOfs, text, texture)
local b = CreateFrame("Button", name, parent, template)
b:SetWidth(width)
b:SetHeight(height)
b:SetPoint(point, relativeto, point2, xOfs, yOfs)
b:HookScript("OnEnter", ButtonEnter)
b:HookScript("OnLeave", ButtonLeave)
if text then
local t = b:CreateFontString(nil, "OVERLAY", b)
t:FontTemplate()
t:SetPoint("CENTER", b, "CENTER", 0, -1)
t:SetJustifyH("CENTER")
t:SetText(text)
b:SetFontString(t)
elseif texture then
local t = b:CreateTexture(nil, "OVERLAY", nil)
t:SetTexture(texture)
t:SetPoint("TOPLEFT", b, "TOPLEFT", K.Mult, -K.Mult)
t:SetPoint("BOTTOMRIGHT", b, "BOTTOMRIGHT", -K.Mult, K.Mult)
end
end
function Module:ToggleRaidUtil(event)
if InCombatLockdown() then
self:RegisterEvent("PLAYER_REGEN_ENABLED", "ToggleRaidUtil")
return
end
if CheckRaidStatus() then
if RaidUtilityPanel.toggled == true then
RaidUtility_ShowButton:Hide()
RaidUtilityPanel:Show()
else
RaidUtility_ShowButton:Show()
RaidUtilityPanel:Hide()
end
else
RaidUtility_ShowButton:Hide()
RaidUtilityPanel:Hide()
end
if event == "PLAYER_REGEN_ENABLED" then
self:UnregisterEvent("PLAYER_REGEN_ENABLED", "ToggleRaidUtil")
end
end
-- Credits oRA3 for the RoleIcons
local function sortColoredNames(a, b)
return a:sub(11) < b:sub(11)
end
local roleIconRoster = {}
local function onEnter(self)
twipe(roleIconRoster)
for i = 1, NUM_RAID_GROUPS do
roleIconRoster[i] = {}
end
local role = self.role
local point = K.GetScreenQuadrant(RaidUtility_ShowButton)
local bottom = point and find(point, "BOTTOM")
local left = point and find(point, "LEFT")
local anchor1 = (bottom and left and "BOTTOMLEFT") or (bottom and "BOTTOMRIGHT") or (left and "TOPLEFT") or "TOPRIGHT"
local anchor2 = (bottom and left and "BOTTOMRIGHT") or (bottom and "BOTTOMLEFT") or (left and "TOPRIGHT") or "TOPLEFT"
local anchorX = left and 2 or -2
GameTooltip:SetOwner(self, "ANCHOR_NONE")
GameTooltip:SetPoint(anchor1, self, anchor2, anchorX, 0)
GameTooltip:SetText(_G["INLINE_" .. role .. "_ICON"] .. _G[role])
local name, group, class, groupRole, color, coloredName, _
for i = 1, GetNumGroupMembers() do
name, _, group, _, _, class, _, _, _, _, _, groupRole = GetRaidRosterInfo(i)
if name and groupRole == role then
color = class == "PRIEST" and K.PriestColors or (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[class] or RAID_CLASS_COLORS[class])
coloredName = ("|cff%02x%02x%02x%s"):format(color.r * 255, color.g * 255, color.b * 255, name:gsub("%-.+", "*"))
tinsert(roleIconRoster[group], coloredName)
end
end
for group, list in ipairs(roleIconRoster) do
tsort(list, sortColoredNames)
for _, name in ipairs(list) do
GameTooltip:AddLine(("[%d] %s"):format(group, name), 1, 1, 1)
end
roleIconRoster[group] = nil
end
GameTooltip:Show()
end
local function RaidUtility_PositionRoleIcons()
local point = K.GetScreenQuadrant(RaidUtility_ShowButton)
local left = point and find(point, "LEFT")
RaidUtilityRoleIcons:ClearAllPoints()
if left then
RaidUtilityRoleIcons:SetPoint("LEFT", RaidUtilityPanel, "RIGHT", 6, 0)
else
RaidUtilityRoleIcons:SetPoint("RIGHT", RaidUtilityPanel, "LEFT", -6, 0)
end
end
local count = {}
local function UpdateIcons(self)
local raid = IsInRaid()
local party --= IsInGroup() --We could have this in party :thinking:
if not (raid or party) then
self:Hide()
return
else
self:Show()
RaidUtility_PositionRoleIcons()
end
twipe(count)
local role
for i = 1, GetNumGroupMembers() do
role = UnitGroupRolesAssigned((raid and "raid" or "party") .. i)
if role and role ~= "NONE" then
count[role] = (count[role] or 0) + 1
end
end
if (not raid) and party then -- only need this party (we believe)
local myRole = K.GetPlayerRole()
if myRole then
count[myRole] = (count[myRole] or 0) + 1
end
end
for role, icon in next, RaidUtilityRoleIcons.icons do
icon.count:SetText(count[role] or 0)
end
end
function Module:OnInitialize()
if C["Raid"].RaidUtility == false then
return
end
-- Create main frame
local RaidUtilityPanel = CreateFrame("Frame", "RaidUtilityPanel", UIParent, "SecureHandlerBaseTemplate")
RaidUtilityPanel:SetWidth(230)
RaidUtilityPanel:SetHeight(PANEL_HEIGHT)
RaidUtilityPanel:SetPoint("TOP", UIParent, "TOP", -400, 1)
RaidUtilityPanel:SetFrameLevel(3)
RaidUtilityPanel.toggled = false
RaidUtilityPanel:SetFrameStrata("HIGH")
RaidUtilityPanel:CreateBorder()
--Show Button
self:CreateUtilButton("RaidUtility_ShowButton", UIParent, "UIMenuButtonStretchTemplate, SecureHandlerClickTemplate", 136, 18, "TOP", UIParent, "TOP", -400, 4, RAID_CONTROL, nil )
RaidUtility_ShowButton:SetFrameRef("RaidUtilityPanel", RaidUtilityPanel)
RaidUtility_ShowButton:SetAttribute("_onclick", ([=[
local raidUtil = self:GetFrameRef("RaidUtilityPanel")
local closeButton = raidUtil:GetFrameRef("RaidUtility_CloseButton")
self:Hide()
raidUtil:Show()
local point = self:GetPoint()
local raidUtilPoint, closeButtonPoint, yOffset
if string.find(point, "BOTTOM") then
raidUtilPoint = "BOTTOM"
closeButtonPoint = "TOP"
yOffset = 1
else
raidUtilPoint = "TOP"
closeButtonPoint = "BOTTOM"
yOffset = -1
end
yOffset = yOffset * (tonumber(%d))
raidUtil:ClearAllPoints()
closeButton:ClearAllPoints()
raidUtil:SetPoint(raidUtilPoint, self, raidUtilPoint)
closeButton:SetPoint(raidUtilPoint, raidUtil, closeButtonPoint, 0, yOffset)
]=]):format(-6 + 4 * 3))
RaidUtility_ShowButton:SetScript("OnMouseUp", function()
RaidUtilityPanel.toggled = true
RaidUtility_PositionRoleIcons()
end)
RaidUtility_ShowButton:SetMovable(true)
RaidUtility_ShowButton:SetClampedToScreen(true)
RaidUtility_ShowButton:SetClampRectInsets(0, 0, -1, 1)
RaidUtility_ShowButton:RegisterForDrag("RightButton")
RaidUtility_ShowButton:SetFrameStrata("HIGH")
RaidUtility_ShowButton:SetScript("OnDragStart", function(self)
self:StartMoving()
end)
RaidUtility_ShowButton:SetScript("OnDragStop", function(self)
self:StopMovingOrSizing()
local point = self:GetPoint()
local xOffset = self:GetCenter()
local screenWidth = UIParent:GetWidth() / 2
xOffset = xOffset - screenWidth
self:ClearAllPoints()
if find(point, "BOTTOM") then
self:SetPoint("BOTTOM", UIParent, "BOTTOM", xOffset, -1)
else
self:SetPoint("TOP", UIParent, "TOP", xOffset, 1)
end
end)
-- Close Button
self:CreateUtilButton("RaidUtility_CloseButton", RaidUtilityPanel, "UIMenuButtonStretchTemplate, SecureHandlerClickTemplate", 136, 18, "TOP", RaidUtilityPanel, "BOTTOM", 0, -1, CLOSE, nil )
RaidUtility_CloseButton:SetFrameRef("RaidUtility_ShowButton", RaidUtility_ShowButton)
RaidUtility_CloseButton:SetAttribute("_onclick", [=[self:GetParent():Hide() self:GetFrameRef("RaidUtility_ShowButton"):Show()]=] )
RaidUtility_CloseButton:SetScript("OnMouseUp", function()
RaidUtilityPanel.toggled = false
end)
RaidUtilityPanel:SetFrameRef("RaidUtility_CloseButton", RaidUtility_CloseButton)
-- Role Icons
local RoleIcons = CreateFrame("Frame", "RaidUtilityRoleIcons", RaidUtilityPanel)
RoleIcons:SetPoint("LEFT", RaidUtilityPanel, "RIGHT", 6, 0)
RoleIcons:SetSize(36, PANEL_HEIGHT)
RoleIcons:CreateBorder()
RoleIcons:RegisterEvent("PLAYER_ENTERING_WORLD")
RoleIcons:RegisterEvent("GROUP_ROSTER_UPDATE")
RoleIcons:SetScript("OnEvent", UpdateIcons)
RoleIcons.icons = {}
local roles = {"TANK", "HEALER", "DAMAGER"}
for i, role in ipairs(roles) do
local frame = CreateFrame("Frame", "$parent_" .. role, RoleIcons)
if i == 1 then
frame:SetPoint("BOTTOM", 0, 4)
else
frame:SetPoint("BOTTOM", _G["RaidUtilityRoleIcons_" .. roles[i - 1]], "TOP", 0, 4)
end
frame:SetSize(28, 28)
local texture = frame:CreateTexture(nil, "OVERLAY")
texture:SetTexture(337499)
local texA, texB, texC, texD = GetTexCoordsForRole(role)
texture:SetTexCoord(texA, texB, texC, texD)
local texturePlace = 2
texture:SetPoint("TOPLEFT", frame, "TOPLEFT", -texturePlace, texturePlace)
texture:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", texturePlace, -texturePlace)
frame.texture = texture
local count = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
count:SetPoint("BOTTOMRIGHT", -2, 2)
count:SetText(0)
frame.count = count
frame.role = role
frame:SetScript("OnEnter", onEnter)
frame:SetScript("OnLeave", GameTooltip_Hide)
RoleIcons.icons[role] = frame
end
-- Disband Raid button
self:CreateUtilButton("DisbandRaidButton", RaidUtilityPanel, "UIMenuButtonStretchTemplate", RaidUtilityPanel:GetWidth() * 0.8, 18, "TOP", RaidUtilityPanel, "TOP", 0, -5, L["Blizzard"].Disband_Group, nil )
DisbandRaidButton:SetScript("OnMouseUp", function()
if CheckRaidStatus() then
K.StaticPopup_Show("DISBAND_RAID")
end
end)
-- Role Check button
self:CreateUtilButton("RoleCheckButton", RaidUtilityPanel, "UIMenuButtonStretchTemplate", RaidUtilityPanel:GetWidth() * 0.8, 18, "TOP", DisbandRaidButton, "BOTTOM", 0, -6, ROLE_POLL, nil )
RoleCheckButton:SetScript("OnMouseUp", function()
if CheckRaidStatus() then
InitiateRolePoll()
end
end)
-- Ready Check button
self:CreateUtilButton("ReadyCheckButton", RaidUtilityPanel, "UIMenuButtonStretchTemplate", RoleCheckButton:GetWidth() * 0.75, 18, "TOPLEFT", RoleCheckButton, "BOTTOMLEFT", 0, -6, READY_CHECK, nil )
ReadyCheckButton:SetScript("OnMouseUp", function()
if CheckRaidStatus() then
DoReadyCheck()
end
end)
-- Raid Control Panel
self:CreateUtilButton("RaidControlButton", RaidUtilityPanel, "UIMenuButtonStretchTemplate", RoleCheckButton:GetWidth(), 18, "TOPLEFT", ReadyCheckButton, "BOTTOMLEFT", 0, -6, L["Blizzard"].Raid_Menu, nil )
RaidControlButton:SetScript("OnMouseUp", function()
ToggleFriendsFrame(3)
end)
local buttons = {
"DisbandRaidButton",
"RoleCheckButton",
"ReadyCheckButton",
"RaidControlButton",
"RaidUtility_ShowButton",
"RaidUtility_CloseButton"
}
if CompactRaidFrameManager then
-- Reposition/Resize and Reuse the World Marker Button
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:ClearAllPoints()
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:SetPoint("TOPRIGHT", RoleCheckButton, "BOTTOMRIGHT", 0, -6 )
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:SetParent("RaidUtilityPanel")
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:SetHeight(18)
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:SetWidth(RoleCheckButton:GetWidth() * 0.22)
-- Put other stuff back
CompactRaidFrameManagerDisplayFrameLeaderOptionsInitiateReadyCheck:ClearAllPoints()
CompactRaidFrameManagerDisplayFrameLeaderOptionsInitiateReadyCheck:SetPoint("BOTTOMLEFT", CompactRaidFrameManagerDisplayFrameLockedModeToggle, "TOPLEFT", 0, 1 )
CompactRaidFrameManagerDisplayFrameLeaderOptionsInitiateReadyCheck:SetPoint("BOTTOMRIGHT", CompactRaidFrameManagerDisplayFrameHiddenModeToggle, "TOPRIGHT", 0, 1 )
CompactRaidFrameManagerDisplayFrameLeaderOptionsInitiateRolePoll:ClearAllPoints()
CompactRaidFrameManagerDisplayFrameLeaderOptionsInitiateRolePoll:SetPoint("BOTTOMLEFT", CompactRaidFrameManagerDisplayFrameLeaderOptionsInitiateReadyCheck, "TOPLEFT", 0, 1 )
CompactRaidFrameManagerDisplayFrameLeaderOptionsInitiateRolePoll:SetPoint("BOTTOMRIGHT", CompactRaidFrameManagerDisplayFrameLeaderOptionsInitiateReadyCheck, "TOPRIGHT", 0, 1 )
tinsert(buttons, "CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton")
else
K.StaticPopup_Show("WARNING_BLIZZARD_ADDONS")
end
-- Reskin Stuff
for _, button in pairs(buttons) do
local f = _G[button]
f.BottomLeft:SetAlpha(0)
f.BottomRight:SetAlpha(0)
f.BottomMiddle:SetAlpha(0)
f.TopMiddle:SetAlpha(0)
f.TopLeft:SetAlpha(0)
f.TopRight:SetAlpha(0)
f.MiddleLeft:SetAlpha(0)
f.MiddleRight:SetAlpha(0)
f.MiddleMiddle:SetAlpha(0)
f:SetHighlightTexture("")
f:SetDisabledTexture("")
f:HookScript("OnEnter", ButtonEnter)
f:HookScript("OnLeave", ButtonLeave)
f:CreateBorder()
end
-- Automatically show/hide the frame if we have RaidLeader or RaidOfficer
self:RegisterEvent("GROUP_ROSTER_UPDATE", "ToggleRaidUtil")
self:RegisterEvent("PLAYER_ENTERING_WORLD", "ToggleRaidUtil")
end
|
jinkinsConvoTemplate = ConvoTemplate:new {
initialScreen = "",
templateType = "Lua",
luaClassHandler = "theme_park_nym_conv_handler",
screens = {}
}
----------
--Jinkins convos if quest completed
----------
good_work = ConvoScreen:new {
id = "good_work",
leftDialog = "@celebrity/jinkins:good_work", -- Securing that memory module proves that you have the makings of a true pirate. I'm sure you'll go far with the Lok Revenants. Now, is there something else I can do for you?
stopConversation = "false",
options = {
}
}
jinkinsConvoTemplate:addScreen(good_work);
talk_to_kole = ConvoScreen:new {
id = "talk_to_kole",
leftDialog = "@celebrity/jinkins:talk_to_kole", -- Kole is planning a new mission for you, based on the information I recovered from that memory module. You should talk to him to receive your next assignment.
stopConversation = "true",
options = {
}
}
jinkinsConvoTemplate:addScreen(talk_to_kole);
talk_to_nym = ConvoScreen:new {
id = "talk_to_nym",
leftDialog = "@celebrity/jinkins:talk_to_nym", -- You've already done my dirty work. But talk to Nym... I think he might need something from you.
stopConversation = "true",
options = {
}
}
jinkinsConvoTemplate:addScreen(talk_to_nym);
good_bye = ConvoScreen:new {
id = "good_bye",
leftDialog = "@celebrity/jinkins:good_bye", -- Alright, but I suggest you talk to Nym or Kole if you're still interested in our crew.
stopConversation = "true",
options = {
}
}
jinkinsConvoTemplate:addScreen(good_bye);
----------
--Jinkins convo if quest is in progress
----------
you_got_memory = ConvoScreen:new {
id = "you_got_memory",
leftDialog = "@celebrity/jinkins:you_got_memory", -- Did you retrieve it? The memory module?
stopConversation = "false",
options = {
{"@celebrity/jinkins:tell_me_again", "quest_info_again"}, -- Can you tell me again what you need?
{"@celebrity/jinkins:yes", "hand_it_over"}, -- Yeah, I have it.
{"@celebrity/jinkins:no", "get_back_to_work"}, -- Not yet.
}
}
jinkinsConvoTemplate:addScreen(you_got_memory);
quest_info_again = ConvoScreen:new {
id = "quest_info_again",
leftDialog = "@celebrity/jinkins:quest_info_again", -- I need you - or someone more skilled - to retrieve a memory module from a droid that the Sulfur Lake Pirates have evidently captured. You may want to discuss the pirates' lair with one of their former members.
stopConversation = "false",
options = {
{"@celebrity/jinkins:sulfur_lake_pirates", "pirate_info"}, -- Who are the Sulfur Lake Pirates?
}
}
jinkinsConvoTemplate:addScreen(quest_info_again);
get_back_to_work = ConvoScreen:new {
id = "get_back_to_work",
leftDialog = "@celebrity/jinkins:get_back_to_work", -- Really? One of our operatives, a slicer who has infiltrated the Sulfur Pirate lair, is certain he saw you there. He also believes that you have already retrieved the module. But perhaps he was mistaken. Head to that cave and find the memory module for me.
stopConversation = "true",
options = {
}
}
jinkinsConvoTemplate:addScreen(get_back_to_work);
hand_it_over = ConvoScreen:new {
id = "hand_it_over",
leftDialog = "@celebrity/jinkins:hand_it_over", -- Excellent. Now, if you'll just hand it to me...
stopConversation = "true",
options = {
}
}
jinkinsConvoTemplate:addScreen(hand_it_over);
----------
--This is the initial Jinkins convo
----------
first_time_hello = ConvoScreen:new {
id = "first_time_hello",
leftDialog = "@celebrity/jinkins:first_time_hello", -- Hmmm? You must be a new recruit. This crew changes faces faster than a Shi'odo spy. But I'm glad we have some fresh blood: The last "pirate" who wandered in here is still being digested by a kimogila somewhere past Rancid Ridge.
stopConversation = "false",
options = {
{"@celebrity/jinkins:who_are_you", "i_am_jinkins"}, -- Jinkins, eh? What do you do?
{"@celebrity/jinkins:tell_me_quest", "quest_info"}, -- Do you need me to do anything for you?
}
}
jinkinsConvoTemplate:addScreen(first_time_hello);
i_am_jinkins = ConvoScreen:new {
id = "i_am_jinkins",
leftDialog = "@celebrity/jinkins:i_am_jinkins", -- I'm Jinkins, Nym's chief engineer. Nym asks for weapons, and I build them. I joined up with the Lok Revenants a few months before the Battle of Naboo, which makes me one of this crew's oldest members, along with Kole of course.
stopConversation = "false",
options = {
{"@celebrity/jinkins:who_is_kole", "kole_is_friend"}, -- Who is Kole?
{"@celebrity/jinkins:who_is_nym", "nym_is_boss"}, -- Tell me about Nym.
{"@celebrity/jinkins:tell_me_quest", "quest_info"}, -- Do you need me to do anything for you?
}
}
jinkinsConvoTemplate:addScreen(i_am_jinkins);
kole_is_friend = ConvoScreen:new {
id = "kole_is_friend",
leftDialog = "@celebrity/jinkins:kole_is_friend", -- Kole is Nym's first mate. He's been with this crew longer than I have. In his younger days, he was a brilliant disguise artist and even worked for a few years as an assassin. Now, he mostly watches Nym's back.
stopConversation = "false",
options = {
{"@celebrity/jinkins:who_is_nym", "nym_is_boss"}, -- Tell me about Nym.
{"@celebrity/jinkins:tell_me_quest", "quest_info"}, -- Do you need me to do anything for you?
}
}
jinkinsConvoTemplate:addScreen(kole_is_friend);
nym_is_boss = ConvoScreen:new {
id = "nym_is_boss",
leftDialog = "@celebrity/jinkins:nym_is_boss", -- You must be joking... Nym is the most feared pirate in the Maramere system. He routed the Trade Federation from Lok and its neighboring planets right around the start of the Clone Wars, and he's maintained complete control over the spacelanes in this region ever since. There's nobody with more power on Lok. And except for Jabba the Hutt, he's probably the most powerful alien in the Outer Rim. The Imperials on this planet couldn't even lift Nym's shadow... And he has no love for the Empire, if you catch my meaning...
stopConversation = "false",
options = {
{"@celebrity/jinkins:who_is_kole", "kole_is_friend"}, -- Who is Kole?
{"@celebrity/jinkins:tell_me_quest", "quest_info"}, -- Do you need me to do anything for you?
}
}
jinkinsConvoTemplate:addScreen(nym_is_boss);
quest_info = ConvoScreen:new {
id = "quest_info",
leftDialog = "@celebrity/jinkins:quest_info", -- Actually, there is something I'd like you to look into, if you can. I recently intercepted a distress call from a starship that crashed-landed on Lok. Ships nose-dive into the planet all the time, but this one took off from an Imperial mining installation on Lok and never made it into the atmosphere. I think it slammed down near the hideout of the Sulfur Lake Pirates. I'm very interested in this vessel...
stopConversation = "false",
options = {
{"@celebrity/jinkins:distress_call", "crashed_ship"}, -- You intercepted a distress call?
}
}
jinkinsConvoTemplate:addScreen(quest_info);
crashed_ship = ConvoScreen:new {
id = "crashed_ship",
leftDialog = "@celebrity/jinkins:crashed_ship", -- Yes. As part of my duties, I monitor comlink and transceiver activity around the system. We don't want a Star Destroyer sneaking up on us, do we? Anyway, this particular starship interests me because it was carrying Imperial cargo. A droid, in fact, that was once owned by General Otto at an Imperial base here on Lok.
stopConversation = "false",
options = {
{"@celebrity/jinkins:droid_memory", "imperial_info"}, -- What's so special about this droid?
}
}
jinkinsConvoTemplate:addScreen(crashed_ship);
imperial_info = ConvoScreen:new {
id = "imperial_info",
leftDialog = "@celebrity/jinkins:imperial_info", -- Probably nothing. But, as an Imperial droid, it might be carrying some very interesting data. Shipping schedules, guard rosters, prisoner transfer information, schematics for some terrifying super weapon... Anything the droid knows could be sold on the black market or traded back to Otto for a favor down the road. It might also tell us something about that Imperial mining facility, which we haven't been able to infiltrate. You'd be rewarded well if you could secure that droid's memory module.
stopConversation = "false",
options = {
{"@celebrity/jinkins:ill_get_memory", "heres_droid_memory"}, -- I'll recover the module. Where can I find this droid?
}
}
jinkinsConvoTemplate:addScreen(imperial_info);
heres_droid_memory = ConvoScreen:new {
id = "heres_droid_memory",
leftDialog = "@celebrity/jinkins:heres_droid_memory", -- Excellent. I'll provide you with a waypoint to the Sulfur Lake. Our scouts learned that the Sulfur Lake Pirates have already taken the cargo - including the droid - from the crashed starship, so don't waste your time looking through the wreckage. Just head to the pirates' lair, locate the droid, and grab the memory module. Oh, and watch out for the pirates' "bridge troll." I'm not sure what that is, but it sounds dangerous...
stopConversation = "true",
options = {
{"@celebrity/jinkins:sulfur_lake_pirates", "pirate_info"}, -- Who are the Sulfur Lake Pirates?
}
}
jinkinsConvoTemplate:addScreen(heres_droid_memory);
pirate_info = ConvoScreen:new {
id = "pirate_info",
leftDialog = "@celebrity/jinkins:pirate_info", -- Probably the most bloodthirsty, least-intelligent pirates on Lok. Like all the other pirate bands, they are constantly trying to dethrone Nym as Lok's reigning pirate king. They hate Nym for taking control of all the nearby hyperspace routes and claim that he's working with the Imperials. The gravel maggots have been looking for an excuse to go to war with us for years... There's a hermit living near Nym's stronghold who once worked for the Sulfur Pirates. He might be able to tell you more.
stopConversation = "false",
options = {
{"@celebrity/jinkins:whos_the_guy", "deals_with_pirates"}, -- Who is this hermit?
}
}
jinkinsConvoTemplate:addScreen(pirate_info);
deals_with_pirates = ConvoScreen:new {
id = "deals_with_pirates",
leftDialog = "@celebrity/jinkins:deals_with_pirates", -- I don't know much about him. We think he was some sort of droid designer for the Old Republic, but fled to Lok when the Empire took power. A few years ago, Nym used him to fence good on Coruscant. But before that, he was performing droid upgrades for the Sulfur Lake Pirates. He can probably tell you about their base.
stopConversation = "false",
options = {
{"@celebrity/jinkins:ill_see_the_guy", "heres_the_guy"}, -- Okay, I'll go talk to him.
}
}
jinkinsConvoTemplate:addScreen(deals_with_pirates);
heres_the_guy = ConvoScreen:new {
id = "heres_the_guy",
leftDialog = "@celebrity/jinkins:heres_the_guy", -- Good. I'll mark his last known location in your datapad. Be sure to ask him about the pirates, see what he knows.
stopConversation = "false",
options = {
{"@celebrity/jinkins:anything_else", "you_know_all"}, -- Is there anything else you can tell me?
}
}
jinkinsConvoTemplate:addScreen(heres_the_guy);
you_know_all = ConvoScreen:new {
id = "you_know_all",
leftDialog = "@celebrity/jinkins:you_know_all", -- Not really. You know everything I know.
stopConversation = "true",
options = {
}
}
jinkinsConvoTemplate:addScreen(you_know_all);
addConversationTemplate("jinkinsConvoTemplate", jinkinsConvoTemplate);
|
local jdtls = require 'jdtls'
local api = vim.api
local M = {}
-- https://github.com/mfussenegger/nvim-jdtls/wiki/UI-Extensions
-- use telescope for code actions etc...
local function jdtls_setup_ui()
local finders = require'telescope.finders'
local sorters = require'telescope.sorters'
local actions = require'telescope.actions'
local pickers = require'telescope.pickers'
require('jdtls.ui').pick_one_async = function(items, prompt, label_fn, cb)
local opts = {}
pickers.new(opts, {
prompt_title = prompt,
finder = finders.new_table {
results = items,
entry_maker = function(entry)
return {
value = entry,
display = label_fn(entry),
ordinal = label_fn(entry),
}
end,
},
sorter = sorters.get_generic_fuzzy_sorter(),
attach_mappings = function(prompt_bufnr)
actions.select_default:replace(function()
local selection = actions.get_selected_entry(prompt_bufnr)
actions.close(prompt_bufnr)
cb(selection.value)
end)
return true
end,
}):find()
end
end
local function on_attach(client, bufnr, attach_opts)
require "lsp_signature".on_attach()
-- =========================================================
-- general navigation actions for all LSP clients
-- =========================================================
-- 'go to' navigation
--map('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>') -- not supported by jdtls
map('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>')
map('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>')
map('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>')
map('n', 'gK', '<cmd>lua vim.lsp.buf.type_definition()<CR>')
-- find style navigation
map('n', '<leader>u', '<cmd>lua vim.lsp.buf.incoming_calls()<CR>') -- usages
--map('n', '<leader>go', '<cmd>lua vim.lsp.buf.outgoing_calls()<CR>') -- not too useful
map('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>')
map('n', '<leader>m', '<cmd>Telescope lsp_document_symbols<CR>')
--map('n', '<leader>gW', '<cmd>lua vim.lsp.buf.workspace_symbol()<CR>')
-- `code_action` is a superset of vim.lsp.buf.code_action and you'll be able to
-- use this jdtls mapping also with other non-jdtls language servers
map('n', '<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) -- see jdtls refactor below
map("n", "<a-CR>", "<Cmd>lua require'jdtls'.code_action()<CR>")
map("n", "<leader>r", "<Cmd>lua require'jdtls'.code_action(false, 'refactor')<CR>")
map("v", "<a-CR>", "<Esc><Cmd>lua require'jdtls'.code_action(true)<CR>")
map("v", "<leader>r", "<Esc><Cmd>lua require'jdtls'.code_action(true, 'refactor')<CR>")
map('n', '<leader>b', '<cmd>lua require"dap".toggle_breakpoint()<CR>')
map('n', '<leader>B', '<Cmd>lua require"dap".toggle_breakpoint(vim.fn.input("Breakpoint Condition: "), nil, nil, true)<CR>')
map('n', '<f7>', '<cmd>lua require"dap".step_into()<CR>')
map('n', '<f8>', '<cmd>lua require"dap".step_over()<CR>')
map('n', '<shift><f8>', '<cmd>lua require"dap".step_out()<CR>')
map('n', '<f9>', '<cmd>lua require"dap".continue()<CR>')
--map('n', '<leader>lp', '<Cmd> require'me.dap'.toggle_breakpoint(nil, nil, vim.fn.input('Log point message: '), true)<CR>
map('n', "]d", '<Cmd>lua vim.lsp.diagnostic.goto_next()<CR>')
map('n', "[d", '<Cmd>lua vim.lsp.diagnostic.goto_prev()<CR>')
-- require('lsp_compl').attach(client, bufnr, attach_opts)
-- api.nvim_buf_set_var(bufnr, "lsp_client_id", client.id)
-- api.nvim_buf_set_option(bufnr, "omnifunc", "v:lua.vim.lsp.omnifunc")
-- api.nvim_buf_set_option(bufnr, "bufhidden", "hide")
--
-- if client.resolved_capabilities.goto_definition then
-- api.nvim_buf_set_option(bufnr, 'tagfunc', "v:lua.require'me.lsp.ext'.tagfunc")
-- end
-- local opts = { silent = true; }
-- for _, mappings in pairs(key_mappings) do
-- local capability, mode, lhs, rhs = unpack(mappings)
-- if client.resolved_capabilities[capability] then
-- api.nvim_buf_set_keymap(bufnr, mode, lhs, rhs, opts)
-- end
-- end
-- api.nvim_buf_set_keymap(bufnr, "n", "<space>", "<Cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>", opts)
-- api.nvim_buf_set_keymap(bufnr, "n", "crr", "<Cmd>lua vim.lsp.buf.rename(vim.fn.input('New Name: '))<CR>", opts)
-- api.nvim_buf_set_keymap(bufnr, "i", "<c-n>", "<Cmd>lua require('lsp_compl').trigger_completion()<CR>", opts)
-- vim.cmd('augroup lsp_aucmds')
-- vim.cmd(string.format('au! * <buffer=%d>', bufnr))
-- vim.cmd(string.format('au User LspDiagnosticsChanged <buffer=%d> redrawstatus!', bufnr))
-- vim.cmd(string.format('au User LspMessageUpdate <buffer=%d> redrawstatus!', bufnr))
-- if client.resolved_capabilities['document_highlight'] then
-- vim.cmd(string.format('au CursorHold <buffer=%d> lua vim.lsp.buf.document_highlight()', bufnr))
-- vim.cmd(string.format('au CursorHoldI <buffer=%d> lua vim.lsp.buf.document_highlight()', bufnr))
-- vim.cmd(string.format('au CursorMoved <buffer=%d> lua vim.lsp.buf.clear_references()', bufnr))
-- end
-- if vim.lsp.codelens and client.resolved_capabilities['code_lens'] then
-- -- vim.cmd(string.format('au BufEnter,BufModifiedSet,InsertLeave <buffer=%d> lua vim.lsp.codelens.refresh()', bufnr))
-- api.nvim_buf_set_keymap(bufnr, "n", "<leader>cr", "<Cmd>lua vim.lsp.codelens.refresh()<CR>", opts)
-- api.nvim_buf_set_keymap(bufnr, "n", "<leader>ce", "<Cmd>lua vim.lsp.codelens.run()<CR>", opts)
-- end
-- vim.cmd('augroup end')
end
local function jdtls_on_attach(client, bufnr)
on_attach(client, bufnr)
local opts = { silent = true; }
jdtls.setup_dap({ hotcodereplace = 'auto' })
--require('jdtls.dap').setup_dap_main_class_configs()
jdtls.setup.add_commands()
map("n", "<leader>xt", "<Cmd>lua require'jdtls'.test_class()<CR>") -- eXecute Test
map("n", "<leader>xT", "<Cmd>lua require'jdtls'.test_nearest_method()<CR>")
jdtls_setup_ui()
-- jdtls specific maps
-- api.nvim_buf_set_keymap(bufnr, "n", "<A-o>", "<Cmd>lua require'jdtls'.organize_imports()<CR>", opts)
-- api.nvim_buf_set_keymap(bufnr, "v", "crv", "<Esc><Cmd>lua require('jdtls').extract_variable(true)<CR>", opts)
-- api.nvim_buf_set_keymap(bufnr, "n", "crv", "<Cmd>lua require('jdtls').extract_variable()<CR>", opts)
-- api.nvim_buf_set_keymap(bufnr, "v", "crm", "<Esc><Cmd>lua require('jdtls').extract_method(true)<CR>", opts)
end
function M.start_jdt()
print("starting jdt")
-- local root_markers = {'gradlew', '.git'}
-- local root_dir = require('jdtls.setup').find_root(root_markers)
-- local home = os.getenv('HOME')
-- local workspace_folder = home .. "/.local/share/eclipse/" .. vim.fn.fnamemodify(root_dir, ":p:h:t")
-- local config = mk_config()
-- config.flags.server_side_fuzzy_completion = true
-- config.settings = {
-- java = {
-- signatureHelp = { enabled = true };
-- contentProvider = { preferred = 'fernflower' };
-- completion = {
-- favoriteStaticMembers = {
-- "org.hamcrest.MatcherAssert.assertThat",
-- "org.hamcrest.Matchers.*",
-- "org.hamcrest.CoreMatchers.*",
-- "org.junit.jupiter.api.Assertions.*",
-- "java.util.Objects.requireNonNull",
-- "java.util.Objects.requireNonNullElse",
-- "org.mockito.Mockito.*"
-- }
-- };
-- sources = {
-- organizeImports = {
-- starThreshold = 9999;
-- staticStarThreshold = 9999;
-- };
-- };
-- codeGeneration = {
-- toString = {
-- template = "${object.className}{${member.name()}=${member.value}, ${otherMembers}}"
-- }
-- };
-- configuration = {
-- runtimes = {
-- {
-- name = "JavaSE-11",
-- path = "/usr/lib/jvm/java-11-openjdk/",
-- },
-- {
-- name = "JavaSE-15",
-- path = "/usr/lib/jvm/java-15-openjdk/",
-- },
-- }
-- };
-- };
-- }
local root_markers = {'.git'}
local root_dir = require('jdtls.setup').find_root(root_markers)
local home = os.getenv('HOME')
-- the "project id" is the root .git directory prefixed with its parent directory. This is to accomodate git worktrees
local project_id = vim.fn.fnamemodify(root_dir, ':p:h:h:t') .. '_' .. vim.fn.fnamemodify(root_dir, ':p:h:t')
local workspace_folder = home .. '/dev/lsp-workspace/' .. project_id
local config = {}
-- Run our custom jdtls.sh and give it a workspace based on the filename
config.cmd = {'jdtls.sh', workspace_folder}
config.on_attach = jdtls_on_attach
config.settings = {
['java.format.settings.url'] = "/home/collin/Code/sonatype/1/codestyle/sonatype-eclipse.xml"
}
local jar_patterns = {
'/home/collin/Code/nvim-infra/java-debug/com.microsoft.java.debug.plugin/target/com.microsoft.java.debug.plugin-*.jar',
-- TODO '/dev/dgileadi/vscode-java-decompiler/server/*.jar',
'/home/collin/Code/nvim-infra/vscode-java-test/server/*.jar'
}
local bundles = {}
for _, jar_pattern in ipairs(jar_patterns) do
for _, bundle in ipairs(vim.split(vim.fn.glob(jar_pattern), '\n')) do
-- exclude this jar as it is not a bundle
if not vim.endswith(bundle, 'com.microsoft.java.test.runner.jar') then
table.insert(bundles, bundle)
end
end
end
-- TODO - what is this?
-- local extendedClientCapabilities = jdtls.extendedClientCapabilities;
-- extendedClientCapabilities.resolveAdditionalTextEditsSupport = true;
config.init_options = {
bundles = bundles;
-- extendedClientCapabilities = extendedClientCapabilities;
}
--vim.api.nvim_echo({{'first chunk and ', 'None'}, {'second chunk to echo', 'None'}}, true, {})
--vim.api.nvim_err_writeln("test")
jdtls.start_or_attach(config)
end
function M.setup()
require('dap').configurations.java = {
{
type = 'java';
request = 'attach';
name = "Debug (Attach) - Remote";
hostName = "127.0.0.1";
port = 5005;
},
}
require("dapui").setup()
-- require('jdtls.ui').pick_one_async = require('fzy').pick_one -- currently using telescope
-- require('jdtls').jol_path = os.getenv('HOME') .. '/apps/jol.jar'
-- require('me.lsp.conf').setup()
-- require('hop').setup()
-- require('lint').linters_by_ft = {
-- markdown = {'vale'},
-- rst = {'vale'},
-- java = {'codespell'},
-- lua = {'codespell', 'luacheck'},
-- sh = {'shellcheck'},
-- ['yaml.ansible'] = {'ansible_lint'},
-- }
--
-- U = M
-- P = function(...)
-- print(unpack(vim.tbl_map(vim.inspect, {...})))
-- end
-- PL = function(...)
-- local log_date_format = "%FT%H:%M:%S%z"
-- local fp = io.open('/tmp/nvim-debug.log', 'a+')
-- local line = table.concat(vim.tbl_map(vim.inspect, {...}), ', ')
-- fp:write('[' .. os.date(log_date_format) .. '] ' .. line .. '\n')
-- fp:flush()
-- fp:close()
-- end
-- local debug_view = nil
-- PB = function(...)
-- if not debug_view then
-- debug_view = require('dap.ui').new_view(
-- function()
-- return api.nvim_create_buf(false, true)
-- end,
-- function(buf)
-- vim.cmd('split')
-- api.nvim_win_set_buf(0, buf)
-- return api.nvim_get_current_win()
-- end
-- )
-- end
-- debug_view.open()
-- local text = table.concat(vim.tbl_map(vim.inspect, {...}), ', ')
-- local lines = vim.split(vim.trim(text), '\n')
-- vim.fn.appendbufline(debug_view.buf, '$', lines)
-- end
end
return M
-- vim.lsp.buf.clear_references()
-- vim.lsp.buf.completion()
-- vim.lsp.buf.document_highlight()
-- vim.lsp.buf.formatting()
-- buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
-- buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
-- buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
-- buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
-- buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
-- buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
-- buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
-- buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
--
-- -- " LSP config (the mappings used in the default file don't quite work right)
-- -- nnoremap <silent> <C-n> <cmd>lua vim.lsp.diagnostic.goto_prev()<CR>
-- -- nnoremap <silent> <C-p> <cmd>lua vim.lsp.diagnostic.goto_next()<CR>
--
-- --
-- -- nnoremap <A-o> <Cmd>lua require'jdtls'.organize_imports()<CR>
-- -- nnoremap crv <Cmd>lua require('jdtls').extract_variable()<CR>
-- -- vnoremap crv <Esc><Cmd>lua require('jdtls').extract_variable(true)<CR>
-- -- nnoremap crc <Cmd>lua require('jdtls').extract_constant()<CR>
-- -- vnoremap crc <Esc><Cmd>lua require('jdtls').extract_constant(true)<CR>
-- -- vnoremap crm <Esc><Cmd>lua require('jdtls').extract_method(true)<CR>
|
return {
-- ID of the actor (optional, defaults to filepath)
id = "starwalker",
-- Width and height of the actor (if unsure, just use sprite size)
width = 37,
height = 36,
-- In-world hitbox, relative to the actor's topleft
-- (these numbers are based on the actual deltarune hitbox)
hitbox = {2, 26, 27, 10},
-- Path to the actor's sprites
path = "npcs/starwalker",
-- Default animation or sprite relative to the path
default = ""
}
|
local api = vim.api
local function create_buf()
return api.nvim_create_buf(false, true)
end
local function create_win(x, y, width, color, blend)
local buf = api.nvim_create_buf(false, true)
local options = {
relative='win',
focusable=false,
bufpos={x, y},
row=0,
col=0,
width=width,
height=1,
style='minimal',
win=wid,
}
win = api.nvim_open_win(buf, false, options)
api.nvim_win_set_option(win, 'winhl', 'Normal:HiFloat' .. color)
api.nvim_win_set_option(win, 'winblend', blend)
return win
end
local function close_win(buf)
return vim.api.nvim_win_close(buf, true)
end
return {
create_win = create_win,
close = close_win,
}
|
trinium.creative_mode = minetest.settings:get_bool"creative_mode"
local speed = 100
local caps = {times = {speed, speed, speed}, uses = 0, maxlevel = 456}
if trinium.creative_mode then
minetest.register_item(":", {
type = "none",
wield_image = "wieldhand.png",
wield_scale = {x = 1, y = 1, z = 2.5},
groups = {hidden_from_nei = 1},
tool_capabilities = {
full_punch_interval = 0.5,
max_drop_level = 456,
groupcaps = {
cracky = caps,
choppy = caps,
snappy = caps,
crumbly = caps,
dig_immediate = caps,
oddly_breakable_by_hand = caps,
},
damage_groups = {fleshy = 10},
}
})
minetest.register_on_joinplayer(function(player)
local privs = minetest.get_player_privs(player:get_player_name())
privs.fly = 1
minetest.set_player_privs(player:get_player_name(), privs)
end)
else
minetest.register_item(":", {
type = "none",
wield_image = "wieldhand.png",
wield_scale = {x = 1, y = 1, z = 2.5},
tool_capabilities = {
full_punch_interval = 0.9,
max_drop_level = 0,
groupcaps = {
crumbly = {times = {[2] = 3.00, [3] = 0.70}, uses = 0, maxlevel = 1},
snappy = {times = {[3] = 0.40}, uses = 0, maxlevel = 1},
oddly_breakable_by_hand = {times = {3.50, 2.00, 0.70}, uses = 0},
},
damage_groups = {fleshy = 1},
}
})
end
local old_handle_node_drops = minetest.handle_node_drops
function minetest.handle_node_drops(pos, drops, digger)
return digger and digger:is_player() and (trinium.creative_mode or old_handle_node_drops(pos, drops, digger))
end
minetest.register_on_placenode(function()
return trinium.creative_mode
end)
|
project "Launch"
RuntimeModule()
kind "ConsoleApp"
links
{
"Core"
}
includedirs
{
"%{RuntimeInclude.Core}"
}
-- Filters
RuntimeFilters()
|
local sysinfo = require 'utils.sysinfo'
local base_app = require 'app.base'
local app = base_app:subclass("FREEIOE_DATA_SIM_APP")
app.static.API_VER = 4
function app:initialize(name, sys, conf)
base_app.initialize(self, name, sys, conf)
self._devs = {}
end
function app:on_start()
local dev_count = self._conf.device_count or 4
local tag_count = self._conf.tag_count or 4
for d = 1, dev_count do
local dev_sn = self._sys:id()..'.'..self._name..'.'..d
local inputs = {}
local outputs = {}
for i = 1, tag_count do
inputs[#inputs + 1] = {
name = 'tag'..i,
desc = 'input '..i,
}
end
inputs[#inputs + 1] = {
name = 'tag_string',
desc = 'input as string',
vt = 'string',
}
local meta = self._api:default_meta()
meta.name = "Data Simulation"
meta.description = "Data Simulation device"
meta.series = "X"
local dev = self._api:add_device(dev_sn, meta, inputs)
table.insert(self._devs, dev)
end
return true
end
function app:on_close(reason)
--print(self._name, reason)
end
function app:on_run(tms)
local tag_count = self._conf.tag_count or 4
local run_loop = self._conf.run_loop or 1000 -- ms
for _, dev in ipairs(self._devs) do
--[[
for i = 1, tag_count do
dev:set_input_prop('tag'..i, 'value', math.random(0xFFFFFFFF))
end
]]--
dev:set_input_prop('tag_string', 'value', os.date())
end
return run_loop
end
return app
|
NewShipType = StartShipConfig()
NewShipType.displayedName="$10020"
NewShipType.sobDescription="$10021"
NewShipType.maxhealth=getShipNum(NewShipType, "maxhealth", 1200)
NewShipType.regentime=0
NewShipType.minRegenTime=0
NewShipType.sideArmourDamage = getShipNum(NewShipType, "sideArmourDamage", 1.0)
NewShipType.rearArmourDamage = getShipNum(NewShipType, "rearArmourDamage", 1.0)
setTacticsMults(NewShipType, "MAXSPEED", 0.90, 1.10, 1.0)
setTacticsMults(NewShipType, "ENGINEACCEL", 1.10, 0.90, 1.0)
setTacticsMults(NewShipType, "THRUSTERACCEL", 1.10, 0.90, 1.0)
setTacticsMults(NewShipType, "ROTATION", 0.95, 1.05, 1.0)
setTacticsMults(NewShipType, "ROTATIONACCEL", 1.10, 0.90, 1.0)
setTacticsMults(NewShipType, "DAMAGEAPPLIED", 1.0, 1.0, 1.0)
NewShipType.isTransferable=1
NewShipType.formationSpacing=45
NewShipType.defaultROE="Defensive"
NewShipType.defaultStance="Neutral"
NewShipType.holdSlots=3
NewShipType.mass=15
NewShipType.collisionMultiplier=0.4
NewShipType.thrusterMaxSpeed=255
NewShipType.mainEngineMaxSpeed=255
NewShipType.rotationMaxSpeed=120
NewShipType.thrusterAccelTime=2.6
NewShipType.thrusterBrakeTime=1
NewShipType.mainEngineAccelTime=2.6
NewShipType.mainEngineBrakeTime=1
NewShipType.rotationAccelTime=0.6
NewShipType.rotationBrakeTime=0.3
NewShipType.thrusterUsage=0.5
NewShipType.accelerationAngle=170
NewShipType.mirrorAngle=30
NewShipType.secondaryTurnAngle=0
NewShipType.maxBankingAmount=85
NewShipType.descendPitch=0
NewShipType.goalReachEpsilon=5
NewShipType.slideMoveRange=0
NewShipType.controllerType="Ship"
NewShipType.tumbleStaticX=10
NewShipType.tumbleStaticY=20
NewShipType.tumbleStaticZ=5
NewShipType.tumbleDynamicX=50
NewShipType.tumbleDynamicY=100
NewShipType.tumbleDynamicZ=25
NewShipType.tumbleSpecialDynamicX=2
NewShipType.tumbleSpecialDynamicY=10
NewShipType.tumbleSpecialDynamicZ=5
NewShipType.relativeMoveFactor=6
NewShipType.swayUpdateTime=3
NewShipType.swayOffsetRandomX=10
NewShipType.swayOffsetRandomY=10
NewShipType.swayOffsetRandomZ=10
NewShipType.swayBobbingFactor=0.025
NewShipType.swayRotateFactor=0
NewShipType.dustCloudDamageTime=240
NewShipType.nebulaDamageTime=50
NewShipType.MinimalFamilyToFindPathAround="SuperCap"
NewShipType.mirrorAboveManeuver="ImmelMann"
NewShipType.mirrorBelowManeuver="Split_S"
NewShipType.BuildFamily="Corvette_Kus"
NewShipType.AttackFamily="Corvette_hw1"
NewShipType.DockFamily="Corvette"
NewShipType.AvoidanceFamily="Strikecraft"
NewShipType.DisplayFamily="Corvette"
NewShipType.AutoFormationFamily="Corvette"
NewShipType.CollisionFamily="Small"
NewShipType.ArmourFamily=getShipStr(NewShipType, "ArmourFamily", "LightArmour_hw1")
setSupplyValue(NewShipType, "Corvette", 1.0)
setSupplyValue(NewShipType, "SalvageCorvette", 1.0)
setSupplyValue(NewShipType, "LayoutCorvette", 1.0)
NewShipType.AttackPriorityMultiplier=0.94
NewShipType.fighterValue=0
NewShipType.corvetteValue=5
NewShipType.frigateValue=0
NewShipType.neutralValue=0
NewShipType.antiFighterValue=0
NewShipType.antiCorvetteValue=0
NewShipType.antiFrigateValue=0
NewShipType.totalValue=5
NewShipType.buildCost=250
NewShipType.buildTime=25
NewShipType.buildPriorityOrder=50
NewShipType.retaliationRange=2000
NewShipType.retaliationDistanceFromGoal=160
NewShipType.visualRange=1000
NewShipType.prmSensorRange=4000
NewShipType.secSensorRange=5000
NewShipType.detectionStrength=1
NewShipType.TOIcon="Square"
NewShipType.TOScale=1
NewShipType.TODistanceFade0=7000
NewShipType.TODistanceDisappear0=5000
NewShipType.TODistanceFade1=2500
NewShipType.TODistanceDisappear1=2000
NewShipType.TODistanceFade2=12000
NewShipType.TODistanceDisappear2=35000
NewShipType.TOGroupScale=1
NewShipType.TOGroupMergeSize=0
NewShipType.mouseOverMinFadeSize=0.045
NewShipType.mouseOverMaxFadeSize=0.1
NewShipType.healthBarStyle=1
NewShipType.nlips=0.00025
NewShipType.nlipsRange=10000
NewShipType.nlipsFar=0
NewShipType.nlipsFarRange=20000
NewShipType.SMRepresentation="HardDot"
NewShipType.meshRenderLimit=11000
NewShipType.dotRenderLimit=10
NewShipType.visibleInSecondary=1
NewShipType.minLOD=0.3
NewShipType.goblinsStartFade=410
NewShipType.goblinsOff=410
NewShipType.minimumZoomFactor=0.75
NewShipType.selectionLimit=150000
NewShipType.preciseATILimit=0
NewShipType.selectionPriority=75
NewShipType.militaryUnit=0
addAbility(NewShipType,"MoveCommand",1,0);
addAbility(NewShipType,"CanDock",1,1);
NewShipType.dockTimeBetweenTwoFormations=0.5
NewShipType.dockTimeBeforeStart=0.5
NewShipType.dockNrOfShipsInDockFormation=1
NewShipType.dockFormation="n_delta"
NewShipType.queueFormation="n_delta"
NewShipType.dontDockWithOtherRaceShips = getShipNum(NewShipType, "dontDockWithOtherRaceShips", 1)
NewShipType.ignoreRaceWhenDocking=0
addAbility(NewShipType,"CanLaunch");
NewShipType.launchTimeBetweenTwoFormations=0.5
NewShipType.launchTimeBeforeStart=1.5
NewShipType.launchNrOfShipsInDockFormation=1
NewShipType.launchFormation="n_delta"
NewShipType.strikeGroupRadius=25
addAbility(NewShipType,"ParadeCommand",1);
addAbility(NewShipType,"WaypointMove");
addAbility(NewShipType,"SalCapCommand",1,500,0,0);
addAbility(NewShipType,"GuardCommand",1,3000,500);
if hypBool == 1 then
addAbility(NewShipType,"HyperspaceViaGateCommand",1,3,1,0.3);
end
addAbility(NewShipType,"RetireAbility",1,0);
addAbility(NewShipType,"CanBeRepaired","RepCap");
addAbility(NewShipType,"CanAttack",1,0,2,0,0.35,1,"Fighter_hw1, Fighter, Corvette_hw1, Corvette, Frigate, Utility, Resource, SmallCapitalShip, BigCapitalShip, Mothership","kamikaze",
{SubSystem="kamikaze"},
{ResourceLarge="kamikaze"});
NewShipType.noCombatGrouping=1
LoadSharedModel(NewShipType,"Kus_SalvageCorvette");
addShield(NewShipType,"EMP",65,20);
NewShipType.battleScarCoverage=1
NewShipType.sobDieTime=2
NewShipType.sobSpecialDieTime=1
NewShipType.specialDeathSpeed=40
NewShipType.chanceOfSpecialDeath=0
NewShipType.deadSobFadeTime=0
setEngineTrail(NewShipType,0,3.2,"trail_ribbon.tga",0.1,0.2,0.025,3);
setEngineTrail(NewShipType,1,3.2,"trail_ribbon.tga",0.1,0.2,0.025,3);
setEngineBurn(NewShipType,12,0.5,1,15,0,0.7,0.15,30);
loadShipPatchList(NewShipType,"data:sound/sfx/ship/Hiigaran/Corvette/",0,"Engines/HCorvetteEng","",1,"Ambience/HCorvetteAmb","");
loadLatchPointList(NewShipType,"RepCap","RepairPoint0");
NewShipType.minFalloffDamageDist=25
NewShipType.maxFalloffDamageDist=25*3
NewShipType.maxFalloffScuttleDamageDist=25*4
NewShipType.explosiveScuttleDamageOnDeath=95
NewShipType.maxFalloffForce=25*10
NewShipType.explosiveDamageOnDeath=19
NewShipType.radiusDamageEvadeMod=1.1
NewShipType.hideNormalAttackUICooldown=1
NewShipType.agileFlight=1
NewShipType.homingDistance=2000
NewShipType.homingDelay=0.5
NewShipType.strikeGroupSpeed=5000
|
---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
---------------------------------------------------
-- {{{ Grab environment
local io = { open = io.open }
local setmetatable = setmetatable
local string = { find = string.find }
-- }}}
-- Mboxc: provides the count of total, old and new messages in mbox files
-- vicious.widgets.mboxc
local mboxc = {}
-- {{{ Mbox count widget type
local function worker(format, warg)
if not warg then return end
-- Initialize counters
local count = { old = 0, total = 0, new = 0 }
-- Get data from mbox files
for i=1, #warg do
local f = io.open(warg[i])
while true do
-- Read the mbox line by line, if we are going to read
-- some *HUGE* folders then switch to reading chunks
local lines = f:read("*line")
if not lines then break end
-- Find all messages
-- * http://www.jwz.org/doc/content-length.html
local _, from = string.find(lines, "^From[%s]")
if from ~= nil then count.total = count.total + 1 end
-- Read messages have the Status header
local _, status = string.find(lines, "^Status:[%s]RO$")
if status ~= nil then count.old = count.old + 1 end
-- Skip the folder internal data
local _, int = string.find(lines, "^Subject:[%s].*FOLDER[%s]INTERNAL[%s]DATA")
if int ~= nil then count.total = count.total - 1 end
end
f:close()
end
-- Substract total from old to get the new count
count.new = count.total - count.old
return {count.total, count.old, count.new}
end
-- }}}
return setmetatable(mbox, { __call = function(_, ...) return worker(...) end })
|
-- Set the FPS cap at runtime.
--[[=begin
setfps
======
Run ``setfps <number>`` to set the FPS cap at runtime, in case you want to watch
combat in slow motion or something.
=end]]
local cap = ...
local capnum = tonumber(cap)
if not capnum or capnum < 1 then
qerror('Invalid FPS cap value: '..cap)
end
df.global.enabler.fps = capnum
|
#!/usr/bin/env lua
-- Application template.
-- Uses the GLFW/OpenGL backend shipped with MoonNuklear.
local glfw = moonglfw
local gl = moongl
local backend = require("moonnuklear.glbackend")
local nk = moonnuklear
local TITLE = "Template" -- GLFW window title
local FPS = 30 -- desired frames per seconds
local W, H = 800, 640 -- window width and height
local BGCOLOR = {0.10, 0.18, 0.24, 1.0} -- background color
local VBO_SIZE, EBO_SIZE = 512*1024, 128*1024 -- size of GL buffers
local ANTI_ALIASING = true -- use anti-aliasing
local CLIPBOARD = false -- use clipboard
local DEFAULT_FONT_PATH = nil -- full path filename of a ttf file (optional)
local R, G, B, A
local window, ctx, atlas
local function set_bgcolor(color)
BGCOLOR = color or BGCOLOR
R, G, B, A = table.unpack(BGCOLOR)
end
set_bgcolor()
-- GL/GLFW inits
glfw.version_hint(3, 3, 'core')
window = glfw.create_window(W, H, TITLE)
glfw.make_context_current(window)
gl.init()
-- Initialize the backend
ctx = backend.init(window, {
vbo_size = VBO_SIZE,
ebo_size = EBO_SIZE,
anti_aliasing = ANTI_ALIASING,
clipboard = CLIPBOARD,
callbacks = true
})
-- Load fonts: if none of these are loaded a default font will be used
atlas = backend.font_stash_begin()
local default_font = atlas:add(13, DEFAULT_FONT_PATH)
local droid = atlas:add(14, "fonts/DroidSans.ttf")
local roboto = atlas:add(14, "fonts/Roboto-Regular.ttf")
local future = atlas:add(13, "fonts/kenvector_future_thin.ttf")
local clean = atlas:add(12, "fonts/ProggyClean.ttf")
local tiny = atlas:add(10, "fonts/ProggyTiny.ttf")
local cousine = atlas:add(13, "fonts/Cousine-Regular.ttf")
backend.font_stash_end(ctx, default_font)
glfw.set_key_callback(window, function (window, key, scancode, action, shift, control, alt, super)
if key == 'escape' and action == 'press' then
glfw.set_window_should_close(window, true)
end
backend.key_callback(window, key, scancode, action, shift, control, alt, super)
end)
collectgarbage()
collectgarbage('stop')
local window_flags = nk.WINDOW_BORDER|nk.WINDOW_MOVABLE|nk.WINDOW_CLOSABLE|nk.WINDOW_SCALABLE
while not glfw.window_should_close(window) do
glfw.wait_events_timeout(1/FPS) --glfw.poll_events()
backend.new_frame()
-- Draw the GUI --------------------------------------------
if nk.window_begin(ctx, "GUI", {50, 50, 220, 220}, window_flags) then
end
nk.window_end(ctx)
------------------------------------------------------------
-- Render
W, H = glfw.get_window_size(window)
gl.viewport(0, 0, W, H)
gl.clear_color(R, G, B, A)
gl.clear('color')
backend.render()
glfw.swap_buffers(window)
collectgarbage()
end
backend.shutdown()
|
--websocket协议的网关
--负责连接验证以及网络协议解析和网络数据的转发
local skynet = require "skynet"
local crypt = require "skynet.crypt"
local netpack = require "skynet.netpack"
local cluster = require "skynet.cluster"
local socket = require "skynet.socket"
local protobuf = require "protobuf"
local subid_online = {} -- subid -> { uid, secret, handshake_index, agent, source_login }
local internal_id = 0
--暂时用5个 有需要可以增加
local balance = 5
local wsagent = {}
local hall_servers = {} -- 大厅服务器集群
local game_servers = {} -- 游戏服务器集群
local backend_servers = {} -- 所有后端服务器 大厅+游戏
-- 从中心服务器获取所有大厅服务器
local function update_hall_state()
local pack = netmsg_pack("center.request_hall_server_list", {})
local ok, ret = pcall(cluster.call, "cluster_center", "@center", "pbrpc", pack)
if not ok then
LOG_ERROR("update_hall_state failed")
return
end
local module, method, msg = netmsg_unpack(ret)
hall_servers = msg.halls
skynet.error("hall server begin")
for k, v in pairs(msg.halls) do
skynet.error(v.clusterid .. "=" .. v.clustername)
end
skynet.error("hall server end")
end
-- 从中心服务器获取所有游戏服务器
local function update_game_state()
local pack = netmsg_pack("center.request_game_server_list", {})
local ok, ret = pcall(cluster.call, "cluster_center", "@center", "pbrpc", pack)
if not ok then
LOG_ERROR("update_game_state failed")
return
end
local module, method, msg = netmsg_unpack(ret)
game_servers = msg.games
skynet.error("game server begin")
for k, v in pairs(msg.games) do
skynet.error(v.clusterid .. "=" .. v.clustername)
end
skynet.error("game server end")
end
-- 从中心服务器获取所有后端服务器
local function update_server_state()
update_hall_state()
update_game_state()
backend_servers = {}
for k, v in pairs(hall_servers) do
backend_servers[v.clusterid] = { module = "hall", clustername = v.clustername }
end
for k, v in pairs(game_servers) do
backend_servers[v.clusterid] = { module = "game", clustername = v.clustername }
end
for k, v in pairs(wsagent) do
skynet.send(v, "lua", "serverlist", hall_servers, backend_servers)
end
end
-- 统计网络错误
local function collect_error(uid, ip, reason)
if not reason or reason == NERR_NORMAL then
return
end
-- TODO 根据规则 可以加入黑名单等
LOG_ERROR(string.format("%d(%s)网络错误:%d", uid, ip, reason))
end
local CMD = {}
local rpc = {}
function CMD.close_conn(source, fd, reason)
skynet.send(wsagent[fd % balance + 1], "lua", "close_conn", fd, reason)
end
function CMD.pbrpc(source, pb, fd)
if fd then
skynet.send(wsagent[fd % balance + 1], "lua", "forward", fd, pb)
else
local netmsg = protobuf.decode("netmsg.netmsg", pb)
if not netmsg then
LOG_ERROR("msg_unpack error")
error("msg_unpack error")
return
end
local msg = protobuf.decode(netmsg.name, netmsg.payload)
if not msg then
LOG_ERROR(netmsg.name .. " decode error")
return
end
local module, method = netmsg.name:match "([^.]*).(.*)"
local f = assert(rpc[method])
return f(source, msg)
end
end
-- 由登陆服务器调用
function rpc.kick(source, msg)
if msg.subid then
local s = subid_online[msg.subid]
if s and s.agent then
skynet.call(s.agent, "lua", "kick", msg.uid)
end
subid_online[msg.subid] = nil
end
end
-- 由登陆服务器调用
function rpc.login(source, msg)
internal_id = internal_id + 1
local subid = internal_id
subid_online[subid] = { uid = msg.uid, secret = msg.secret, handshake_index = 0, source_login = source }
return subid
end
function CMD.start(source, conf)
cluster.register("gateway")
protobuf.register_file("./protocol/netmsg.pb")
protobuf.register_file("./protocol/center.pb")
protobuf.register_file("./protocol/hall.pb")
protobuf.register_file("./protocol/login.pb")
protobuf.register_file("./protocol/game.pb")
local pack = netmsg_pack("center.register_gate_server", { gate = { clusterid = tonumber(skynet.getenv("clusterid")), clustername = skynet.getenv("clustername"), endpoint = skynet.getenv("endpoint") }})
local ok, ret = pcall(cluster.call, "cluster_center", "@center", "pbrpc", pack)
if not ok then
LOG_ERROR("center.register_gate_server failed")
end
local module, method, msg = netmsg_unpack(ret)
skynet.error(msg.desc)
for i= 1, balance do
wsagent[i] = skynet.newservice("wsagent", skynet.self())
end
local endpoint = skynet.getenv("endpoint")
local ip, port = string.match(endpoint, "([^:]*):([^:]*)")
ip = "0.0.0.0"
local protocol = "ws"
local s = socket.listen(ip, tonumber(port))
skynet.error(string.format("Listen websocket %s protocol:%s", endpoint, protocol))
socket.start(s, function(id, addr)
skynet.send(wsagent[id % balance + 1], "lua", id, protocol, addr)
end)
update_server_state()
skynet.fork(function ()
while true do
skynet.sleep(60000) -- 600s
update_server_state()
end
end)
end
function CMD.auth(source, subid)
-- TODO 判断黑名单用户和IP
return subid_online[tonumber(subid)]
end
function CMD.unauth(source, subid, uid, ip, reason)
collect_error(uid, ip, reason)
subid_online[tonumber(subid)] = nil
end
function CMD.handshake(source, subid, index, agent)
local user = subid_online[tonumber(subid)]
if user then
user.handshake_index = index
user.agent = tonumber(agent)
return true
end
return false
end
function CMD.center_notify_update_score(source, userid, score)
for k, v in pairs(subid_online) do
if v.uid == userid then
skynet.send(v.agent, "lua", "center_notify_update_score", userid, score)
break
end
end
end
skynet.start(function ()
skynet.dispatch("lua", function(_, source, command, ...)
local f = CMD[command]
skynet.ret(skynet.pack(f(source,...)))
end)
end)
|
RegisterCommand(Config.SwitchVehicleJobCommand, function()
if IsPedInAnyVehicle(ESX.PlayerData.ped, true) and GetPedInVehicleSeat(GetVehiclePedIsIn(ESX.PlayerData.ped), -1) == ESX.PlayerData.ped then
local vehicle = GetVehiclePedIsIn(ESX.PlayerData.ped, false)
local plate = GetVehicleNumberPlateText(vehicle)
ESX.TriggerServerCallback("glz_veh:hasPlayerVehicleByPlate", function(has)
if has then
TriggerServerEvent("glz_veh:switchVehicleJob",plate)
else
pNotify(_U("not_owned"), "error")
end
end, plate)
end
end, false)
|
-- Tests for GLib Regex functions
-- written by Hadriel Kaplan, based on Lrexlib's test suite
-- This is a test script for tshark/wireshark.
-- This script runs inside tshark/wireshark, so to run it do:
-- tshark -r empty.cap -X lua_script:<path_to_testdir>/lua/gregex.lua -X lua_script1:glib
--
-- if you have to give addtional paths to find the dependent lua files,
-- use the '-X lua_script1:' syntax to add more arguments
--
-- available arguments:
-- -d<dir> provides path directory for lua include files
-- -v verbose mode
-- -V very verbose mode
-- save args before we do anything else
local args = {...}
for i,v in ipairs(args) do
print(i.." = "..v)
end
-- save current locale and replace it with C-locale
local old_locale = os.setlocale()
print("Previous locale was '" .. old_locale .. "', setting it to C-locale now")
os.setlocale("C")
local function testing(...)
print("---- Testing "..tostring(...).." ----")
end
local count = 0
local function test(name, ...)
count = count + 1
io.write("test "..name.."-"..count.."...")
if (...) == true then
io.write("passed\n")
io.flush()
else
io.write("failed!\n")
io.flush()
error(name.." test failed!")
end
end
------------- First test some basic stuff to make sure we're sane -----------
print("Lua version: ".._VERSION)
testing("Lrexlib GLib Regex library")
local lib = GRegex
test("global",_G.GRegex == lib)
for name, val in pairs(lib) do
print("\t"..name.." = "..type(val))
end
test("class",type(lib) == 'table')
test("class",type(lib._VERSION) == 'string')
test("class",type(lib.find) == 'function')
test("class",type(lib.compile_flags) == 'function')
test("class",type(lib.match_flags) == 'function')
test("class",type(lib.flags) == 'function')
test("class",type(lib.gsub) == 'function')
test("class",type(lib.gmatch) == 'function')
test("class",type(lib.new) == 'function')
test("class",type(lib.match) == 'function')
test("class",type(lib.split) == 'function')
test("class",type(lib.version) == 'function')
testing("info and flags")
test("typeof",typeof(lib) == 'GRegex')
print(lib._VERSION)
print("Glib version = "..lib.version())
local function getTSize(t)
local c = 0
for k,v in pairs(t) do
-- print(k.." = "..v)
c = c + 1
end
return c
end
local flags = lib.flags()
-- print("size = "..c)
-- it's 84 for newer GLib, 61 for older
test("flags", getTSize(flags) > 60)
test("cflags", getTSize(lib.compile_flags()) > 15)
test("eflags", getTSize(lib.match_flags()) > 8)
testing("new")
local results
local function checkFunc(objname,funcname,...)
results = { pcall(objname[funcname],...) }
if results[1] then
return true
end
-- print("Got this error: '"..tostring(results[2]).."'")
return false
end
test("new", checkFunc(lib,"new",".*"))
test("new", checkFunc(lib,"new",""))
test("new", checkFunc(lib,"new","(hello|world)"))
test("new_err", not checkFunc(lib,"new","*"))
test("new_err", not checkFunc(lib,"new"))
test("new_err", not checkFunc(lib,"new","(hello|world"))
test("new_err", not checkFunc(lib,"new","[0-9"))
-- invalid compile flag
test("new_err", not checkFunc(lib,"new","[0-9]",flags.PARTIAL))
local val1 = "hello world foo bar"
local val2 = "hello wORld FOO bar"
local patt = "hello (world) (.*) bar"
local rgx = lib.new(patt)
local rgx2 = lib.new(patt,flags.CASELESS)
testing("typeof")
test("typeof",typeof(rgx) == 'GRegex')
test("typeof",typeof(rgx2) == 'GRegex')
testing("match")
test("match", checkFunc(lib,"match", val1,patt, 1, flags.CASELESS) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(lib,"match", val2,patt, 1, flags.CASELESS) and results[2] == "wORld" and results[3] == "FOO")
test("match", checkFunc(lib,"match", val1,rgx) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(rgx,"match", rgx,val1) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(rgx2,"match", rgx2,val2, 1) and results[2] == "wORld" and results[3] == "FOO")
-- different offset won't match this pattern
test("match_err", checkFunc(rgx2,"match", rgx2,val2, 4) and results[2] == nil)
-- invalid compile flag
test("match_err", not checkFunc(lib,"match", val1,patt, 1, flags.PARTIAL))
-- invalid match flag
test("match_err", not checkFunc(rgx,"match", rgx,val1, 1, flags.CASELESS))
testing("find")
test("find", checkFunc(lib,"find", val1,patt) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
test("find", checkFunc(lib,"find", val1,rgx) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
test("find", checkFunc(rgx,"find", rgx,val1) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
testing("match")
--checkFunc(rgx,"exec", rgx,val1)
--print(results[4][3],results[4][4])
test("exec", checkFunc(rgx,"exec", rgx,val1) and results[2] == 1 and results[3] == val1:len()
and results[4][1] == 7 and results[4][2] == 11 and results[4][3] == 13 and results[4][4] == 15)
print("\n----------------------------------------------------------\n")
------- OK, we're sane, so run all the library's real tests ---------
testing("Lrexlib-provided tests")
-- we're not using the "real" lib name
local GLIBNAME = "GRegex"
local isglobal = true
do
local dir
for i = 1, select ("#", ...) do
local arg = select (i, ...)
--print(arg)
if arg:sub(1,2) == "-d" then
dir = arg:sub(3)
end
end
dir = dir:gsub("[/\\]+$", "")
local path = dir .. "/?.lua;"
if package.path:sub(1, #path) ~= path then
package.path = path .. package.path
end
end
local luatest = require "luatest"
-- returns: number of failures
local function test_library (libname, setfile, verbose, really_verbose)
if verbose then
print (("[lib: %s; file: %s]"):format (libname, setfile))
end
local lib = isglobal and _G[libname] or require (libname)
local f = require (setfile)
local sets = f (libname, isglobal)
local n = 0 -- number of failures
for _, set in ipairs (sets) do
if verbose then
print (set.Name or "Unnamed set")
end
local err = luatest.test_set (set, lib, really_verbose)
if verbose then
for _,v in ipairs (err) do
print ("\nTest " .. v.i)
print (" Expected result:\n "..tostring(v))
luatest.print_results (v[1], " ")
table.remove(v,1)
print ("\n Got:")
luatest.print_results (v, " ")
end
end
n = n + #err
end
if verbose then
print ""
end
return n
end
local avail_tests = {
posix = { lib = "rex_posix", "common_sets", "posix_sets" },
gnu = { lib = "rex_gnu", "common_sets", "emacs_sets", "gnu_sets" },
oniguruma = { lib = "rex_onig", "common_sets", "oniguruma_sets", },
pcre = { lib = "rex_pcre", "common_sets", "pcre_sets", "pcre_sets2", },
glib = { lib = GLIBNAME, "common_sets", "pcre_sets", "pcre_sets2", "glib_sets" },
spencer = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" },
tre = { lib = "rex_tre", "common_sets", "posix_sets", "spencer_sets", --[["tre_sets"]] },
}
do
local verbose, really_verbose, tests, nerr = false, false, {}, 0
local dir
-- check arguments
for i = 1, select ("#", ...) do
local arg = select (i, ...)
--print(arg)
if arg:sub(1,1) == "-" then
if arg == "-v" then
verbose = true
elseif arg == "-V" then
verbose = true
really_verbose = true
elseif arg:sub(1,2) == "-d" then
dir = arg:sub(3)
end
else
if avail_tests[arg] then
tests[#tests+1] = avail_tests[arg]
else
error ("invalid argument: [" .. arg .. "]")
end
end
end
assert (#tests > 0, "no library specified")
-- give priority to libraries located in the specified directory
if dir and not isglobal then
dir = dir:gsub("[/\\]+$", "")
for _, ext in ipairs {"dll", "so", "dylib"} do
if package.cpath:match ("%?%." .. ext) then
local cpath = dir .. "/?." .. ext .. ";"
if package.cpath:sub(1, #cpath) ~= cpath then
package.cpath = cpath .. package.cpath
end
break
end
end
end
-- do tests
for _, test in ipairs (tests) do
package.loaded[test.lib] = nil -- to force-reload the tested library
for _, setfile in ipairs (test) do
nerr = nerr + test_library (test.lib, setfile, verbose, really_verbose)
end
end
print ("Total number of failures: " .. nerr)
assert(nerr == 0, "Test failed!")
end
print("Resetting locale to: " .. old_locale)
os.setlocale(old_locale)
print("\n-----------------------------\n")
print("All tests passed!\n\n")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.