content stringlengths 5 1.05M |
|---|
--[[--ldoc desc
@module paidiandaxiao_2240_1
@author RonanLuo
Date 2018-01-19 15:12:07
Last Modified by RonanLuo
Last Modified time 2018-03-01 09:56:06
]]
--[[
牌点排序
打无主时 牌点大小:大王>小王>黑桃A>级别牌>A>K>Q>J>10>9>8>7>6>5>4>3>2 可跳过牌点相连(例如:级牌=8,7799算连对)
]]
local LibBase = import("..base.LibBase")
local SortUtils = import(".SortUtils")
local M = class(LibBase);
function M:main(data)
local ruleDao = data.ruleDao;
if ruleDao:getMainColor() >= 0 then
return;
end
data.sortFlag = SortUtils.SortFlag.SJ2;
return SortUtils.getCardSize(data, data.args[1]);
end
return M; |
-- // About
-- // Base instance functions for the Assembler
-- // Variables
local TweenService = game:GetService("TweenService")
local IXObjectClassModule = {}
IXObjectClassModule.__index = IXObjectClassModule
IXObjectClassModule.Name = "IXLabelClass"
IXObjectClassModule.Aliases = {
"TextLabel"
}
-- // Functions
function IXObjectClassModule:Enable()
end
function IXObjectClassModule:Disable()
end
function IXObjectClassModule:Fade(FadeIn)
if FadeIn then
self.Cache.FadeInTween:Play()
else
self.Cache.FadeOutTween:Play()
end
end
function IXObjectClassModule:Typewrite(Content)
self.TypewriteMutex = self.TypewriteMutex + 1
local CIndex = self.TypewriteMutex
for Index, Value in ipairs(Content:split("")) do
if self.TypewriteMutex ~= CIndex then
return
end
self.Object.Text = Content:sub(1, Index)
wait(self.Settings.TypewriteTick)
end
end
function IXObjectClassModule:Rainbow(Threaded)
self.RainbowMutex = self.RainbowMutex + 1
local CIndex = self.RainbowMutex
local Hue = 0
local function InitiazeRainbowCallback()
while true do
if CIndex ~= self.RainbowMutex then
break
end
self.Object.TextColor3 = Color3.fromHSV(Hue / 360, 1, 1)
if Hue + 1 >= 360 then
Hue = 1
else
Hue += 1
end
wait(self.Settings.RainbowTick)
end
end
if Threaded then
self.Context.Libary:Spawn(InitiazeRainbowCallback)
else
InitiazeRainbowCallback()
end
end
-- // Internal
function IXObjectClassModule:UpdateDefaults()
if self.Cache.FadeInTween then
self.Cache.FadeInTween:Destroy()
end
if self.Cache.FadeOutTween then
self.Cache.FadeOutTween:Destroy()
end
self.Cache.FadeInTween = TweenService:Create(self.Object, TweenInfo.new(self.Settings.FadeTick), {TextTransparency = 0})
self.Cache.FadeOutTween = TweenService:Create(self.Object, TweenInfo.new(self.Settings.FadeTick), {TextTransparency = 1})
end
function IXObjectClassModule:ConstructClassDescendants()
self.Object:GetPropertyChangedSignal("Parent"):Connect(function()
if self.Object.Parent == nil then
local ParentObject = self.Object.Parent
local IntegrityCheck = pcall(function() self.Object.Parent = workspace end)
if IntegrityCheck then
self.Object.Parent = ParentObject
else
self:Destroy()
end
end
end)
self.Object.ChildAdded:Connect(function(Child)
if Child:IsA("Frame") and not Child:GetAttribute("Disabled") then
self:RegisterElement(Child)
end
end)
self.Object.ChildRemoved:Connect(function(Child)
self.Children[Child.Name] = false
end)
end
-- // Constructor
function IXObjectClassModule.new(Context, Object)
local self = setmetatable({}, IXObjectClassModule)
self.Object = Object
self.Context = Context
self.TypewriteMutex = 0
self.RainbowMutex = 0
self.Cache = {}
self.Settings = {
["TypewriteTick"] = self.Context.Settings.LabelTypewriteTick;
["RainbowTick"] = self.Context.Settings.LabelRainbowTick;
["FadeTick"] = self.Context.Settings.LabelFadeTick;
}
return self
end
return IXObjectClassModule
|
--[[
Skyblock for Minetest
Copyright (c) 2015 cornernote, Brett O'Donnell <cornernote@gmail.com>
Source Code: https://github.com/cornernote/minetest-skyblock
License: GPLv3
]]--
-- set mapgen to singlenode
minetest.register_on_mapgen_init(function(mgparams)
minetest.set_mapgen_params({mgname='singlenode', water_level=-32000})
end)
-- new player
minetest.register_on_newplayer(function(player)
-- spawn player
skyblock.spawn_player(player)
end)
-- respawn player
minetest.register_on_respawnplayer(function(player)
-- unset old spawn position
if skyblock.dig_new_spawn then
local player_name = player:get_player_name()
local spawn = skyblock.get_spawn(player_name)
skyblock.set_spawn(player_name, nil)
skyblock.set_spawn(player_name..'_DEAD', spawn)
end
-- spawn player
skyblock.spawn_player(player)
return true
end)
local spawn_throttle = 1
local function spawn_tick()
for _,player in ipairs(minetest.get_connected_players()) do
local pos = player:getpos()
-- hit the bottom
if pos.y < skyblock.world_bottom and player:get_hp() > 0 then
local spawn = skyblock.get_spawn(player:get_player_name())
if spawn and minetest.get_node(spawn).name == 'skyblock:quest' then
player:set_hp(0)
else
skyblock.spawn_player(player)
end
end
end
minetest.after(spawn_throttle, spawn_tick)
end
-- register globalstep after the server starts
minetest.after(0.1, spawn_tick)
-- register map generation
minetest.register_on_generated(function(minp, maxp, seed)
-- do not handle mapchunks which are too heigh or too low
if( minp.y > 0 or maxp.y < 0) then
return
end
local vm, area, data, emin, emax
-- if no voxelmanip data was passed on, read the data here
if not(vm) or not(area) or not(data) then
vm, emin, emax = minetest.get_mapgen_object('voxelmanip')
if not(vm) then
return
end
area = VoxelArea:new{
MinEdge={x=emin.x, y=emin.y, z=emin.z},
MaxEdge={x=emax.x, y=emax.y, z=emax.z},
}
data = vm:get_data()
end
-- add cloud floor
local cloud_y = skyblock.world_bottom-2
if minp.y<=cloud_y and maxp.y>=cloud_y then
local id_cloud = minetest.get_content_id('default:cloud')
for x=minp.x,maxp.x do
for z=minp.z,maxp.z do
data[area:index(x,cloud_y,z)] = id_cloud
end
end
end
-- add world_bottom_node
if skyblock.world_bottom_node ~= 'air' then
local id_bottom = minetest.get_content_id(skyblock.world_bottom_node)
local y_start = math.max(cloud_y+1,minp.y)
local y_end = math.min(skyblock.start_height,maxp.y)
for x=minp.x,maxp.x do
for z=minp.z,maxp.z do
for y=y_start, y_end do
data[area:index(x,y,z)] = id_bottom
end
end
end
end
-- add starting blocks
--[[
local start_pos_list = skyblock.get_start_positions_in_mapchunk(minp, maxp)
for _,pos in ipairs(start_pos_list) do
skyblock.make_spawn_blocks_on_generated(pos, data, area)
end
]]--
-- store the voxelmanip data
vm:set_data(data)
vm:calc_lighting(emin,emax)
vm:write_to_map(data)
vm:update_liquids()
end)
-- no placing low nodes
minetest.register_on_placenode(function(pos, newnode, placer, oldnode)
if pos.y <= skyblock.world_bottom then
minetest.remove_node(pos)
return true -- give back item
end
end)
|
--
-- Verify 验签签名处理
--
local _M = {}
_M.allowInstall = function ()
local state = require("suma_main_state");
if state.verify_option.status then
return true;
end
return false;
end
local dyn_lib = require("suma_basecom_action");
_M.handle = function (body)
local key = ngx.ctx.deviceID .. ".chain";
local cache_ngx = ngx.shared.ngx_share_dict;
local chain_state = cache_ngx:get (key);
local verify_result = nil;
if chain_state == nil then
verify_result = dyn_lib.verify_chain(body);
if verify_result.code == "000" then
local cache_ngx = ngx.shared.ngx_share_dict;
cache_ngx:set(ngx.ctx.deviceID .. ".chain" , 1);
end
else
verify_result = dyn_lib.verify(body);
end
if verify_result.code ~= "000" then
if ngx.ctx.status == "success" then
ngx.ctx.status = verify_result.details;
end
dyn_lib.default_response_print();
ngx.exit(200);
end
end
return _M; |
--[[
Copyright (C) 2019 Onset Roleplay
Developers:
* Logic
Contributors:
* Blue Mountains GmbH
]]--
-- Variables
local colour = ImportPackage('colours')
DonationData = {}
-- Functions
local function CreateDonationData(playerid)
DonationData[playerid] = {}
DonationData[playerid].level = 0
DonationData[playerid].date = 0
end
local function DestroyDonationData(playerid)
DonationData[playerid] = nil
end
function OnDonationsLoaded(playerid)
if mariadb_get_row_count() == 0 then
DonationData[playerid].level = 0
DonationData[playerid].date = 0
else
DonationData[playerid].level = mariadb_get_value_name_int(1, "level")
DonationData[playerid].date = mariadb_get_value_name_int(1, "time")
if os.time(os.date("!*t")) < DonationData[playerid].date then
AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_DARKGREEN().."\">Your donation level " .. DonationData[playerid].level .. " is active till " .. os.date("%d %B %Y", DonationData[playerid].date) .. ". Thank you for helping and supporting us!</>")
else
AddPlayerChat(playerid, "<span color=\""..colour.COLOR_LIGHTRED()"\">Your donation level " .. DonationData[playerid].level .. " expired on " .. os.date("%d %B %Y", DonationData[playerid].date) .. ". Please consider visiting the UCP for more information.</>")
DonationData[playerid].level = 0
end
end
end
function AddPlayerChatDonator(text)
for _, v in ipairs(GetAllPlayers()) do
if DonationData[v] ~= nil then
if DonationData[v].level ~= 0 then
AddPlayerChat(v, text)
end
end
end
end
-- Events
AddEvent("OnPlayerSteamAuth", function (playerid)
CreateDonationData(playerid)
end)
AddEvent("OnPlayerQuit", function (playerid)
DestroyDonationData(playerid)
end) |
iconDir = APPDIR.."icons/logo.png"
IsMouseActive = false
PaintFrame = createFrame(10, 10, 640, 480, "Графический редактор", "full")
PaintFrame:Show()
centerElement(PaintFrame)
setAppIcon(PaintFrame, iconDir)
setColor(PaintFrame, "FFFFFF", "444444")
ScrollPane, Scrolling = createScrollPane(71, 0, 640-71, 480-51, _, PaintFrame)
setColor(ScrollPane, "CCCCCC", "CCCCCC")
PaintPanel = createPanel(2, 2, 640-73-4-5, 480-51-4-5, ScrollPane)
setColor(PaintPanel, "FFFFFF", "444444")
resizer = createPanel(640-73-7, 480-51-7, 5, 5, ScrollPane)
setColor(resizer, "555555", "555555")
addObjectOnPane(resizer, ScrollPane)
paint = setFrameDrawing(PaintPanel)
paint:Clear()
ToolPanel = createPanel(0, 0, 71, 480, PaintFrame)
setColor(ToolPanel, "444444", "444444")
createMenu(PaintFrame, {"Файл", "Помощь"})
idUndo = addMenuItem("Файл", "Отменить")
idRend = addMenuItem("Файл", "Перерисовать")
idCler = addMenuItem("Файл", "Очистить")
idExit = addMenuItem("Файл", "Выход")
idAbts = addMenuItem("Помощь", "О программе")
SavingColours = {
"FF0000", "00FF00", "0000FF", "4444FF",
"6600FF", "143F72", "FF9900", "18C018",
"C01818", "1818C0", "D73030", "30D730",
"FFFFFF", "000000", "333333", "444444",
"555555", "666666", "AAAAAA", "EEEEEE"
}
SideButton = {}
local n = 0
for i, v in pairs(ToolRegistry) do
local x = 3
n = n+1
if not tostring(n/2):find(".5") then x = 36 end
SideButton[i] = createIconButton(x, (math.ceil(n/2)-1)*33 + 3, 30, 30, v.Icon, _, ToolPanel)
setColor(SideButton[i], CurrentTool == v and "18C018" or "444444", "FFFFFF")
addEvent(SideButton[i], "onMouseEnter", function()
setColor(SideButton[i], "C01818", "FFFFFF")
end)
addEvent(SideButton[i], "onMouseLeave", function()
local color = "444444"
if CurrentTool == v or ( i == "Mouse" and IsMouseActive) then color = "18C018" end
setColor(SideButton[i], color, "FFFFFF")
end)
addEvent(SideButton[i], "onMouseUp", function()
if i ~= "Mouse" then
setCurrentTool(v)
for m in pairs(SideButton) do
if m ~= "Mouse" then setColor(SideButton[m], "444444", "FFFFFF") end
end
setColor(SideButton[i], "18C018", "FFFFFF")
end
end)
end
ColorDialog = nil
n = math.ceil(n/2)
--print(n)
ColorButton = {}
local DefaultColors = {"000000", "FFFFFF"}
CurrentColour = {"000000", "FFFFFF"}
for i = 1, 2 do
ColorButton[i] = createButton((i-1)*33+3, n*36+3, 30, 30, "", _, ToolPanel)
setColor(ColorButton[i], DefaultColors[i], DefaultColors[i])
addEvent(ColorButton[i], "onMouseUp", function()
local r, g, b = getColor(ColorButton[i])
local data = wx.wxColourData()
data:SetColour(wx.wxColour(r, g, b))
for m = 0, 15 do
data:SetCustomColour(m, wx.wxColour(fromHEXToRGB(SavingColours[m+1])))
end
ColorDialog = createColorDialog(PaintFrame, data)
if ColorDialog:ShowModal() == wx.wxID_OK then
local x, y, z = getColFromColour(ColorDialog:GetColourData():GetColour())
CurrentColour[i] = fromRGBToHEX(x, y, z)
setColor(ColorButton[i], CurrentColour[i], CurrentColour[i])
for m = 0, 15 do
local thisColour = getColFromColour(ColorDialog:GetColourData():GetCustomColour(m), true)
SavingColours[m+1] = thisColour
end
end
ColorDialog:Close()
ColorDialog:Destroy()
end)
end
local label = createLabel(3, (n+1)*36+3, 63, 25, "Размер:", _, ToolPanel)
setColor(label, "FFFFFF", "FFFFFF")
SpinSizer = createSpin(3, (n+1)*36+22, 63, 30, "0", ToolPanel, 1, 128)
n = n+1
local labels = createLabel(3, (n+1)*40, 63, 25, "Масштаб:", _, ToolPanel)
setColor(labels, "FFFFFF", "FFFFFF")
SpinScale = createSpin(3, (n+1)*40+22, 63, 30, "100", ToolPanel, 20, 500)
PaintFrame:SetMinSize(wx.wxSize(320, (n+2)*40+70))
function closeApplication(evt)
PaintFrame:Close()
if evt then
evt:Skip()
end
SkippingEvent = true
end |
local combat = createCombatObject()
setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE)
setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, false)
local condition = createConditionObject(CONDITION_HASTE)
setConditionParam(condition, CONDITION_PARAM_TICKS, 5000)
setConditionFormula(condition, 0.9, -81, 0.9, -81)
setCombatCondition(combat, condition)
function onCastSpell(cid, var)
return doCombat(cid, combat, var)
end
|
object_mobile_beast_master_bm_razor_angler = object_mobile_beast_master_shared_bm_razor_angler:new {
}
ObjectTemplates:addTemplate(object_mobile_beast_master_bm_razor_angler, "object/mobile/beast_master/bm_razor_angler.iff")
|
local lfs = require "lfs"
local https = require "ssl.https"
local ltn12 = require "ltn12"
local Util = {}
local INVALIDATION_TIME = 60*60
function Util.SortBuild(a, b)
local build_a = tonumber(a:match("(%d+)$"))
local build_b = tonumber(b:match("(%d+)$"))
if build_a ~= build_b then
return build_a < build_b
end
end
Util.PtrVersion = "?"
local flavorInfo = {
ptr = {flavor = "mainline", header = true,
sort = Util.SortBuild},
mainline = {flavor = "mainline", header = true, build = "9.2.5.",
sort = Util.SortBuild},
tbc = {flavor = "tbc", header = true, build = "2.5.4."},
vanilla = {flavor = "vanilla", header = true, build = "1.14.3."},
}
Util.RelativePath = {
["."] = true,
[".."] = true,
}
function Util:MakeDir(path)
if not lfs.attributes(path) then
lfs.mkdir(path)
end
end
function Util:WriteFile(path, text)
print("Writing", path)
local file = io.open(path, "w")
file:write(text)
file:close()
end
--- Downloads a file
---@param path string Path to write the file to
---@param url string URL to download from
---@param isCache boolean If the file should be redownloaded after `INVALIDATION_TIME`
function Util:DownloadFile(path, url, isCache)
if self:ShouldDownload(path, isCache) then
local body = https.request(url)
self:WriteFile(path, body)
end
end
--- Downloads and runs a Lua file
---@param path string Path to write the file to
---@param url string URL to download from
---@return ... @ The values returned from the Lua file, if applicable
function Util:DownloadAndRun(path, url)
self:DownloadFile(path, url, true)
return require(path:gsub("%.lua", ""))
end
--- Sends a POST request and downloads a file
---@param path string Path to write the file to
---@param url string URL to download from
---@param requestBody string Contents of the request
---@param isCache boolean If the file should be redownloaded after `INVALIDATION_TIME`
function Util:DownloadFilePost(path, url, requestBody, isCache)
if self:ShouldDownload(path, isCache) then
local body = self:HttpPostRequest(url, requestBody)
if body then
self:WriteFile(path, body)
end
end
end
function Util:ShouldDownload(path, isCache)
local attr = lfs.attributes(path)
if not attr then
return true
elseif isCache and os.time() > attr.modification+INVALIDATION_TIME then
return true
end
end
-- https://github.com/brunoos/luasec/wiki/LuaSec-1.0.x#httpsrequesturl---body
function Util:HttpPostRequest(url, request)
local response = {}
local _, code = https.request{
url = url,
method = "POST",
headers = {
["Content-Length"] = string.len(request),
["Content-Type"] = "application/x-www-form-urlencoded"
},
source = ltn12.source.string(request),
sink = ltn12.sink.table(response)
}
if code == 204 then -- tly no result
return false
elseif code ~= 200 then
error("HTTP error: "..code)
end
return table.concat(response)
end
function Util:CopyTable(tbl)
local t = {}
for k, v in pairs(tbl) do
t[k] = v
end
return t
end
function Util:Wipe(tbl)
for k in pairs(tbl) do
tbl[k] = nil
end
end
function Util:ToMap(tbl)
local t = {}
for _, v in pairs(tbl) do
t[v] = true
end
return t
end
function Util:SortTable(tbl, func)
local t = {}
for k in pairs(tbl) do
table.insert(t, k)
end
table.sort(t, func)
return t
end
function Util:SortTableCustom(tbl, func)
local t = {}
for k, v in pairs(tbl) do
table.insert(t, {
key = k,
value = v
})
end
table.sort(t, func)
return t
end
function Util.SortNocase(a, b)
return a:lower() < b:lower()
end
-- https://stackoverflow.com/a/7615129/1297035
function Util:strsplit(input, sep)
local t = {}
for s in string.gmatch(input, "([^"..sep.."]+)") do
table.insert(t, s)
end
return t
end
--- combines table keys
---@vararg string
---@return table
function Util:CombineTable(...)
local t = {}
for i = 1, select("#", ...) do
local tbl = select(i, ...)
for k in pairs(tbl) do
t[k] = true
end
end
return t
end
function Util:GetFullName(apiTable)
local fullName
if apiTable.System.Namespace then
fullName = format("%s.%s", apiTable.System.Namespace, apiTable.Name)
else
fullName = apiTable.Name
end
return fullName
end
function Util:GetPatchVersion(v)
return v:match("%d+%.%d+%.%d+")
end
local classicVersions = {
"^1.13.",
"^1.14.",
"^2.5.",
}
function Util:IsClassicVersion(v)
for _, pattern in pairs(classicVersions) do
if v:find(pattern) then
return true
end
end
return false
end
-- accepts an options table or a game flavor
function Util:GetFlavorOptions(info)
local infoType = type(info)
if infoType == "table" then
return info
elseif infoType == "string" then
return flavorInfo[info]
elseif not info then
return flavorInfo.ptr
end
end
function Util:ReadCSV(dbc, parser, options, func)
local csv = parser:ReadCSV(dbc, options)
local tbl = {}
for l in csv:lines() do
local ID = tonumber(l.ID)
if ID then
func(tbl, ID, l) -- maybe bad code
end
end
return tbl
end
function Util:IterateFiles(folder, func)
for fileName in lfs.dir(folder) do
local path = folder.."/"..fileName
local attr = lfs.attributes(path)
if attr.mode == "directory" then
if not self.RelativePath[fileName] then
self:IterateFiles(path, func)
end
else
local ext = fileName:match("%.(%a+)")
if ext == "lua" or ext == "xml" then
func(path)
end
end
end
end
-- https://stackoverflow.com/a/32660766/1297035
function Util:equals(a, b)
if a == b then return true end
local type_a, type_b = type(a), type(b)
if type_a ~= type_b then return false end
if type_a ~= "table" then return false end
for k, v in pairs(a) do
if b[k] == nil or not self:equals(v, b[k]) then return false end
end
for k in pairs(b) do
if a[k] == nil then return false end
end
return true
end
function Util:Print(...)
if self.DEBUG then
print(...)
end
end
return Util
|
package("libdivsufsort")
set_homepage("https://android.googlesource.com/platform/external/libdivsufsort/")
set_description("A lightweight suffix array sorting library")
add_urls("https://android.googlesource.com/platform/external/libdivsufsort.git")
add_versions("2021.2.18", "d6031097d39aabfff1372e9a1601eed3fbd5fd9b")
if is_plat("linux") then
add_extsources("apt::libdivsufsort-dev")
end
add_deps("cmake")
add_configs("use_64", {description = "Build 64bit suffxi array sorting APIs", default = false, type = "boolean"})
on_install(function (package)
import("package.tools.cmake")
local configs = {}
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
if package:config("shared") then
table.insert(configs, "-DBUILD_SHARED_LIBS=on")
else
table.insert(configs, "-DBUILD_SHARED_LIBS=off")
end
if package:config("use_64") then
table.insert(configs, "-DBUILD_DIVSUFSORT64=on")
end
cmake.install(package, configs)
end)
on_test(function (package)
if package:config("use_64") then
assert(package:has_cfuncs("sa_search64", {includes = "divsufsort64.h"}))
else
assert(package:has_cfuncs("sa_search", {includes = "divsufsort.h"}))
end
end)
|
--
-- Table utility functions
--
-- See also https://www.hammerspoon.org/docs/hs.fnutils.html
--
local tl = {}
function tl.print(t)
for k, v in pairs(t) do
print(k, ':', v)
end
end
tl.show = tl.print
function tl.printList(t)
for i=1, #t do
print(i, ':', t[i])
end
end
tl.showList = tl.printList
function tl.isInList(t, elem)
for i=1, #t do
if t[i] == elem then
return true
end
end
return false
end
-- https://stackoverflow.com/a/15278426/524588
function tl.concat(t1, t2)
for i=1, #t2 do
t1[#t1+1] = t2[i]
end
return t1
end
-- https://stackoverflow.com/questions/1252539/most-efficient-way-to-determine-if-a-lua-table-is-empty-contains-no-entries
function tl.empty(t)
return next(t) == nil
end
return tl
|
local flyWithLuaStub = require("xplane_fly_with_lua_stub")
flyWithLuaStub:suppressLogMessagesContaining(
{
"A320 NORMAL CHECKLIST using '"
}
)
require("test_high_level_behaviour")
require("test_configuration")
|
local BaseInstance = import("./BaseInstance")
local GuiService = BaseInstance:extend("GuiService")
return GuiService |
-- Pandoc writer for TikiWiki syntax
-- Author: Chat Wacharamanotham
-- Based on pandoc example
-- Character escaping
local function escape(s, in_attribute)
return s:gsub("[<>&“”‘’—%\\%[]",
function(x)
if x == '<' then
return '~lt~'
elseif x == '>' then
return '~gt~'
elseif x == '&' then
return '~amp~'
elseif x == '“' then
return '~ldq~'
elseif x == '”' then
return '~rdq~'
elseif x == '‘' then
return '~lsq~'
elseif x == '’' then
return '~rsq~'
elseif x == '—' then
return '~--~'
elseif x == '\\' then
return '~bs~'
elseif x == '[' then
return '[['
else
return x
end
end)
end
-- Helper function to convert an attributes table into
-- a string that can be put into HTML tags.
local function attributes(attr)
local attr_table = {}
for x,y in pairs(attr) do
if y and y ~= "" then
table.insert(attr_table, ' ' .. x .. '="' .. escape(y,true) .. '"')
end
end
return table.concat(attr_table)
end
-- Table to store footnotes, so they can be included at the end.
local notes = {}
-- Blocksep is used to separate block elements.
function Blocksep()
return "\n\n"
end
-- This function is called once for the whole document. Parameters:
-- body is a string, metadata is a table, variables is a table.
-- This gives you a fragment. You could use the metadata table to
-- fill variables in a custom lua template. Or, pass `--template=...`
-- to pandoc, and pandoc will add do the template processing as
-- usual.
function Doc(body, metadata, variables)
local buffer = {}
local function add(s)
table.insert(buffer, s)
end
add(body)
if #notes > 0 then
add('<ol class="footnotes">')
for _,note in pairs(notes) do
add(note)
end
add('</ol>')
end
return table.concat(buffer,'\n') .. '\n'
end
-- The functions that follow render corresponding pandoc elements.
-- s is always a string, attr is always a table of attributes, and
-- items is always an array of strings (the items in a list).
-- Comments indicate the types of other variables.
function Str(s)
return escape(s)
end
function Space()
return " "
end
function SoftBreak()
return "\n"
end
function LineBreak()
return "%%%"
end
function Emph(s)
return "''" .. s .. "''"
end
function Strong(s)
return "__" .. s .. "__"
end
function Subscript(s)
return "{SUB()}" .. s .. "{SUB}"
end
function Superscript(s)
return "{SUP()}" .. s .. "{SUP}"
end
function SmallCaps(s)
return '<span style="font-variant: small-caps;">' .. s .. '</span>'
end
function Strikeout(s)
return '--' .. s .. '--'
end
function Link(s, src, tit, attr)
return "[" .. escape(src,true) .. "|" .. s .. "]"
end
function Image(s, src, tit, attr)
return "{img src='" .. escape(src,true) .. "' title='" ..
escape(tit,true) .. "}"
end
function Code(s, attr)
return "-+" .. escape(s) .. "+-"
end
function InlineMath(s)
return "\\(" .. escape(s) .. "\\)"
end
function DisplayMath(s)
return "\\[" .. escape(s) .. "\\]"
end
function Note(s)
local num = #notes + 1
-- insert the back reference right before the final closing tag.
s = string.gsub(s,
'(.*)</', '%1 <a href="#fnref' .. num .. '">↩</a></')
-- add a list item with the note to the note table.
table.insert(notes, '<li id="fn' .. num .. '">' .. s .. '</li>')
-- return the footnote reference, linked to the note.
return '<a id="fnref' .. num .. '" href="#fn' .. num ..
'"><sup>' .. num .. '</sup></a>'
end
function Span(s, attr)
return "<span" .. attributes(attr) .. ">" .. s .. "</span>"
end
function RawInline(format, str)
if format == "html" then
return str
else
return ''
end
end
function Cite(s, cs)
local ids = {}
for _,cit in ipairs(cs) do
table.insert(ids, cit.citationId)
end
return "<span class=\"cite\" data-citation-ids=\"" .. table.concat(ids, ",") ..
"\">" .. s .. "</span>"
end
function Plain(s)
return s
end
function Para(s)
return s
end
-- lev is an integer, the header level.
function Header(lev, s, attr)
return string.rep("!", lev) .. escape(s)
end
function BlockQuote(s)
return "{QUOTE()}" .. s .. "{QUOTE}"
end
function HorizontalRule()
return "----"
end
function LineBlock(ls)
return table.concat(ls, '%%%')
end
function CodeBlock(s, attr)
return "{CODE(" .. attributes(attr) .. ")}" .. escape(s) .. "{CODE}"
end
-- create nested list inside the top-level list
function sub_list(s)
return s:gsub("\n#", "##"):gsub("\n%*", "**")
end
function BulletList(items)
local buffer = {}
for _, item in pairs(items) do
table.insert(buffer, "* " .. sub_list(item))
end
return table.concat(buffer, "\n")
end
function OrderedList(items)
local buffer = {}
for _, item in pairs(items) do
table.insert(buffer, "# " .. sub_list(item))
end
return table.concat(buffer, "\n")
end
function DefinitionList(items)
local buffer = {}
for _,item in pairs(items) do
local k, v = next(item)
table.insert(buffer, "<dt>" .. k .. "</dt>\n<dd>" ..
table.concat(v, "</dd>\n<dd>") .. "</dd>")
end
return "<dl>\n" .. table.concat(buffer, "\n") .. "\n</dl>"
end
-- Convert pandoc alignment to something HTML can use.
-- align is AlignLeft, AlignRight, AlignCenter, or AlignDefault.
function html_align(align)
if align == 'AlignLeft' then
return 'left'
elseif align == 'AlignRight' then
return 'right'
elseif align == 'AlignCenter' then
return 'center'
else
return 'left'
end
end
function CaptionedImage(src, tit, caption, attr)
return '<div class="figure">\n<img src="' .. escape(src,true) ..
'" title="' .. escape(tit,true) .. '"/>\n' ..
'<p class="caption">' .. caption .. '</p>\n</div>'
end
-- Caption is a string, aligns is an array of strings,
-- widths is an array of floats, headers is an array of
-- strings, rows is an array of arrays of strings.
function Table(caption, aligns, widths, headers, rows)
local buffer = {}
local function add(s)
table.insert(buffer, s)
end
if caption ~= "" then
add("__Table:__ " .. caption )
end
add("\n")
-- table header row
local header_row = {}
local empty_header = true
for i, h in pairs(headers) do
table.insert(header_row, "__" .. h .. "__")
empty_header = empty_header and h == ""
end
if empty_header then
add("||")
else
add("|| " .. table.concat(header_row, " | ") .. "\n")
end
-- each body row
for _, row in pairs(rows) do
add(table.concat(row, " | ") .. "\n")
end
add('||')
return table.concat(buffer,'')
end
function RawBlock(format, str)
if format == "html" then
return str
else
return ''
end
end
function Div(s, attr)
return "<div" .. attributes(attr) .. ">\n" .. s .. "</div>"
end
-- The following code will produce runtime warnings when you haven't defined
-- all of the functions you need for the custom writer, so it's useful
-- to include when you're working on a writer.
local meta = {}
meta.__index =
function(_, key)
io.stderr:write(string.format("WARNING: Undefined function '%s'\n",key))
return function() return "" end
end
setmetatable(_G, meta)
|
local EQUIPMENT = script:FindAncestorByType("Equipment")
-- Data for the grenade and explosion
local WEAPON_TYPE = script:GetCustomProperty("WeaponType")
local PROJECTILE_BODY = script:GetCustomProperty("ProjectileBody")
local IMPACT = script:GetCustomProperty("ProjectileImpact")
local BOUNCE_SOUND = script:GetCustomProperty("ProjectileBounceSound")
local PROJECTILE_BOUNCINESS = script:GetCustomProperty("ProjectileBounciness")
local DAMAGE_RANGE = script:GetCustomProperty("DamageRange")
local EXPLOSION_RADIUS = script:GetCustomProperty("ExplosionRadius")
local EXPLOSION_KNOCKBACK_SPEED = script:GetCustomProperty("ExplosionKnockbackSpeed")
local PROJECTILE_LIFE_SPAN = script:GetCustomProperty("ProjectileLifeSpan")
local PROJECTILE_GRAVITY = script:GetCustomProperty("ProjectileGravity")
local PROJECTILE_LENGTH = script:GetCustomProperty("ProjectileLength")
local PROJECTILE_RADIUS = script:GetCustomProperty("ProjectileRadius")
local PROJECTILE_DRAG = script:GetCustomProperty("ProjectileDrag")
local PROJECTILE_BOUNCES = script:GetCustomProperty("ProjectileBounces")
local PROJECTILE_PIERCES = script:GetCustomProperty("ProjectilePierces")
local killEvent = nil
function OnEquipped(Equipment, player)
killEvent = player.diedEvent:Connect(OnPlayerDied)
end
function OnPlayerDied(player, damage)
-- spawn Grenade!
--print ("On player died!")
CleanupEvent()
SpawnGrenade(player)
end
function CleanupEvent()
--print ("Equipment was destroyed")
if killEvent then
killEvent:Disconnect()
killEvent = nil
end
end
function OnProjectileImpact(projectile, other, hitResult)
local pos = hitResult:GetImpactPosition()
World.SpawnAsset(BOUNCE_SOUND, {position = pos})
if projectile.bouncesRemaining == 0 or other:IsA("Player") then
Blast(pos, projectile.owner)
projectile:Destroy()
end
end
function OnProjectileLifeSpanEnded(projectile)
local pos = projectile:GetWorldPosition()
Blast(pos, projectile.owner)
end
function Blast(center, projectileOwner)
if IMPACT then
World.SpawnAsset(IMPACT, {position = center})
end
-- If owner left the server by the time the blast happens, stop the script
if not Object.IsValid(projectileOwner) then return end
local players = Game.FindPlayersInSphere(center, EXPLOSION_RADIUS)
for _, player in pairs(players) do
local canDamage = false
-- Checks to blast the enemy team
if Teams.AreTeamsEnemies(player.team, projectileOwner.team) then
canDamage = true
end
if projectileOwner == player then
canDamage = true
end
-- If canDamage is true and there is no objects obstructing the explosion then damage the player
if canDamage then
local displacement = player:GetWorldPosition() - center
-- The farther the player from the blast the less damage that player takes
local minDamage = DAMAGE_RANGE.x
local maxDamage = DAMAGE_RANGE.y
displacement.z = 0
local t = displacement.size / EXPLOSION_RADIUS
local damageAmount = CoreMath.Lerp(maxDamage, minDamage, t)
-- Create damage information
local damage = Damage.New(damageAmount)
damage.sourcePlayer = projectileOwner
damage.sourceAbility = THROW_ABILITY
-- Apply damage to player
player:ApplyDamage(damage)
Events.Broadcast("AS.PlayerDamaged", projectileOwner, player, WEAPON_TYPE, false)
-- Create a direction at which the player is pushed away from the blast
player:AddImpulse(displacement:GetNormalized() * player.mass * EXPLOSION_KNOCKBACK_SPEED)
end
end
end
function SpawnGrenade(player)
local startPos = player:GetWorldPosition()
local startDir = Vector3.UP
local projectile = Projectile.Spawn(PROJECTILE_BODY, startPos, startDir)
projectile.owner = player
projectile.speed = 100
projectile.lifeSpan = PROJECTILE_LIFE_SPAN
projectile.gravityScale = PROJECTILE_GRAVITY
projectile.capsuleLength = PROJECTILE_LENGTH
projectile.capsuleRadius = PROJECTILE_RADIUS
projectile.drag = PROJECTILE_DRAG
projectile.bouncesRemaining = PROJECTILE_BOUNCES
projectile.piercesRemaining = PROJECTILE_PIERCES
projectile.bounciness = PROJECTILE_BOUNCINESS
projectile.shouldDieOnImpact = false
projectile.impactEvent:Connect(OnProjectileImpact)
projectile.lifeSpanEndedEvent:Connect(OnProjectileLifeSpanEnded)
end
EQUIPMENT.equippedEvent:Connect(OnEquipped)
EQUIPMENT.destroyEvent:Connect(CleanupEvent)
|
local anim8 = require 'pong.vendor.anim8.anim8'
local Constants = require 'pong.constants'
local Court = require 'pong.court'
local Utils = require 'pong.utils'
-- A paddle that a player controls
local Paddle = {}
Paddle.__index = Paddle
Paddle.HEIGHT = 128
Paddle.WIDTH = 16
Paddle.SPEED = 256
function Paddle.init()
Paddle.image = love.graphics.newImage('assets/images/paddle.png')
-- Avoid linear interpolation on the image to get the crisp pixels.
Paddle.image:setFilter('nearest', 'nearest')
Paddle.grid = anim8.newGrid(
Paddle.WIDTH, Paddle.HEIGHT, Paddle.image:getWidth(), Paddle.image:getHeight())
end
local function construct(cls, x, y, up_key, down_key, scene)
local self = setmetatable({}, Paddle)
-- Use the upper left corner to easily draw a rectangle.
self.x = x
self.y = y
-- Store the up/down direction that maps to a key state.
self.up_key = up_key
self.down_key = down_key
self.scene = scene
self.y_direction = Constants.UP
self.animation = anim8.newAnimation(Paddle.grid('1-4', 1, '4-1', 1), 0.06, 'pauseAtEnd')
self.animation:pauseAtStart()
return self
end
setmetatable(Paddle, {__call = construct})
function Paddle:update(dt, key_state)
if key_state[self.up_key] and not self:collide_top() then
self.y_direction = Constants.UP
self:move(dt)
end
if key_state[self.down_key] and not self:collide_bottom() then
self.y_direction = Constants.DOWN
self:move(dt)
end
if Utils.has_any_collision(self, self.scene.balls) then
self.animation:gotoFrame(1)
self.animation:resume()
end
self.animation:update(dt)
end
-- Check if the paddle is in contact with the top of the court.
function Paddle:collide_top()
bbox = self:get_bbox()
-- Keep the paddle in the court at all times. If it went over in an update,
-- set it back within the court.
if bbox.y < Court.TOP then
self.y = Court.TOP
return true
end
return bbox.y == Court.TOP
end
-- Check if the paddle is in contact with the bottom of the court.
function Paddle:collide_bottom()
bbox = self:get_bbox()
-- Keep the paddle in the court at all times. If it went over in an update,
-- set it back within the court.
if bbox.y + bbox.h > Court.BOTTOM then
self.y = Court.BOTTOM - Paddle.HEIGHT
return true
end
return bbox.y + bbox.h == Court.BOTTOM
end
-- Get the bounding box.
function Paddle:get_bbox()
return {
x = self.x,
y = self.y,
h = Paddle.HEIGHT,
w = Paddle.WIDTH,
}
end
-- Change the paddle's vertical position.
function Paddle:move(dt)
self.y = self.y + Paddle.SPEED * self.y_direction * dt
end
function Paddle:draw()
self.animation:draw(Paddle.image, self.x, self.y)
end
return Paddle
|
local array = include( "modules/array" )
local util = include( "modules/util" )
local tooltip_breakice = include( "hud/tooltip_breakice" )
local mathutil = include( "modules/mathutil" )
local hud = include( "hud/hud" )
local cdefs = include( "client_defs" )
local serverdefs = include( "modules/serverdefs" )
local aiplayer = include( "sim/aiplayer" )
local pcplayer = include( "sim/pcplayer" )
local simability = include( "sim/simability" )
local simdefs = include( "sim/simdefs" )
local simquery = include( "sim/simquery" )
local simunit = include( "sim/simunit" )
local store = include( "sim/units/store" )
local worldgen = include( "sim/worldgen" )
local mainframe = include( "sim/mainframe" )
local mainframe_panel = include( "hud/mainframe_panel" )
local shop_panel = include( "hud/shop_panel" )
local mission_util = include( "sim/missions/mission_util" )
local modalDialog = include( "states/state-modal-dialog" )
local null_tooltip = class()
function null_tooltip:init( hud, str, str2 )
self._hud = hud
self._str = str
self._str2 = str2
end
function null_tooltip:setPosition( wx, wy )
self._panel:setPosition( self._hud._screen:wndToUI( wx, wy ))
end
function null_tooltip:getScreen()
return self._hud._screen
end
function null_tooltip:activate( screen )
local combat_panel = include( "hud/combat_panel" )
local COLOR_GREY = util.color(180/255,180/255,180/255,150/255)
self._panel = combat_panel( self._hud, self._hud._screen )
self._panel:refreshPanelFromStr( self._str, self._str2, COLOR_GREY )
end
function null_tooltip:deactivate()
self._panel:setVisible( false )
end
function updateAgentAbilityAI( remove, agentdefs )
if remove then
for i, agentDef in pairs(agentdefs) do
local j = array.find(agentDef.abilities, "W93_combatAI_scan")
if j then
table.remove(agentDef.abilities, j)
end
j = array.find(agentDef.abilities, "W93_combatAI_delay")
if j then
table.remove(agentDef.abilities, j)
end
j = array.find(agentDef.abilities, "W93_combatAI_pwr")
if j then
table.remove(agentDef.abilities, j)
end
j = array.find(agentDef.abilities, "W93_combatAI_disable")
if j then
table.remove(agentDef.abilities, j)
end
end
else
for i, agentDef in pairs(agentdefs) do
if not array.find(agentDef.abilities, "W93_combatAI_scan") then
table.insert(agentDef.abilities, "W93_combatAI_scan")
end
if not array.find(agentDef.abilities, "W93_combatAI_delay") then
table.insert(agentDef.abilities, "W93_combatAI_delay")
end
if not array.find(agentDef.abilities, "W93_combatAI_pwr") then
table.insert(agentDef.abilities, "W93_combatAI_pwr")
end
if not array.find(agentDef.abilities, "W93_combatAI_disable") then
table.insert(agentDef.abilities, "W93_combatAI_disable")
end
end
end
end
function set_colors()
cdefs.TRACKER_COLOURS =
{
util.color.fromBytes( 250, 253, 105 ),
util.color.fromBytes( 250, 253, 105 ),
util.color.fromBytes( 251, 203, 98 ),
util.color.fromBytes( 225, 152, 45 ),
util.color.fromBytes( 246, 90, 21 ),
util.color.fromBytes( 205, 24, 10 ),
util.color.fromBytes( 205, 24, 10 ),
util.color.fromBytes( 180, 15, 5 ),
util.color.fromBytes( 180, 15, 5 ),
}
cdefs.COLOR_AI_WARNING = { r=255/255,g=216/255,b=0/255,a=255/255 }
end
function setProgramGfx()
simdefs.SCREEN_CUSTOMS = util.extend(simdefs.SCREEN_CUSTOMS)
{
["hud-inworld.lua"] =
{
skins =
{
[1] =
{ children = {
[7] =
{
name = [[flailTarget]],
isVisible = true,
noInput = true,
anchor = 1,
rotation = 0,
x = -18,
xpx = true,
y = 59,
ypx = true,
w = 61,
wpx = true,
h = 61,
hpx = true,
sx = 1,
sy = 1,
ctor = [[anim]],
animfile = [[gui/flailAnim]],
symbol = [[box2]],
anim = [[idle]],
color =
{
1,
1,
1,
1,
}
},
[8] =
{
name = [[crossfeedTarget]],
isVisible = true,
noInput = true,
anchor = 1,
rotation = 0,
x = -18,
xpx = true,
y = 59,
ypx = true,
w = 61,
wpx = true,
h = 61,
hpx = true,
sx = 1,
sy = 1,
ctor = [[anim]],
animfile = [[gui/crossfeedAnim2]],
symbol = [[box2]],
anim = [[idle]],
color =
{
1,
1,
1,
1,
}
},
[9] =
{
name = [[crossfeedSource]],
isVisible = true,
noInput = true,
anchor = 1,
rotation = 0,
x = -18,
xpx = true,
y = 59,
ypx = true,
w = 61,
wpx = true,
h = 61,
hpx = true,
sx = 1,
sy = 0.75,
ctor = [[anim]],
animfile = [[gui/crossfeedAnim1]],
symbol = [[box2]],
anim = [[idle]],
color =
{
1,
1,
1,
1,
}
},
[10] =
{
name = [[pwrUplink]],
isVisible = true,
noInput = true,
anchor = 1,
rotation = 0,
x = -18,
xpx = true,
y = 59,
ypx = true,
w = 61,
wpx = true,
h = 61,
hpx = true,
sx = 1,
sy = 1,
ctor = [[anim]],
animfile = [[gui/pwrUplinkAnim]],
symbol = [[box2]],
anim = [[idle]],
color =
{
1,
1,
1,
1,
}
}
}}
}
}
}
end
function setAlarmGfx()
simdefs.SCREEN_CUSTOMS = util.extend(simdefs.SCREEN_CUSTOMS)
{
["hud.lua"] =
{
widgets =
{
[15] =
{
children =
{
[1] =
{
animfile = [[gui/hud_danger_wheel_four]],
},
[5] =
{
sx = 0.4,
sy = 0.4,
}
}
}
}
},
["modal-alarm-first.lua"] =
{
widgets =
{
[2] =
{
children =
{
[8] =
{
animfile = [[gui/hud_danger_wheel_four]],
}
}
}
}
}
}
end
function resetAlarmGfx()
simdefs.SCREEN_CUSTOMS = util.extend(simdefs.SCREEN_CUSTOMS)
{
["hud.lua"] =
{
widgets =
{
[15] =
{
children =
{
[1] =
{
animfile = [[gui/hud_danger_wheel_five]],
},
[5] =
{
sx = 1.05,
sy = 1.05,
}
}
}
}
},
["modal-alarm-first.lua"] =
{
widgets =
{
[2] =
{
children =
{
[8] =
{
animfile = [[gui/hud_danger_wheel_five]],
}
}
}
}
}
}
end
function simquery.getMoveSoundRange( unit, cell )
local range = 0
if not unit:getTraits().sneaking then
range = unit:getTraits().dashSoundRange
else
range = simdefs.SOUND_RANGE_0
end
if unit:getPlayerOwner():getTraits().shackleDaemon and not unit:getTraits().isDrone then
range = math.max(range, simdefs.SOUND_RANGE_1)
end
return range + (cell.noiseRadius or 0)
end
function aiplayer:addMainframeAbility(sim, abilityID, hostUnit, reversalOdds )
local monst3rReverseOdds = reversalOdds or 10
if self:isNPC() then
for _, ability in ipairs( sim:getPC():getAbilities() ) do
if ability.daemonReversalAdd and monst3rReverseOdds > 0 then
monst3rReverseOdds = monst3rReverseOdds + ability.daemonReversalAdd
end
end
end
local count = 0
for _, ability in ipairs( self._mainframeAbilities ) do
if ability:getID() == abilityID then
count = count + 1
end
end
local ability = simability.create( abilityID )
if ability and count < (ability.max_count or math.huge) then
local monst3rReverse = nil
if self:isNPC() and sim:nextRand( 1, 100 ) < monst3rReverseOdds then
monst3rReverse = true
elseif findMainframeAbility("W93_reflect") and findMainframeAbility("W93_reflect"):getCpuCost() <= sim:getPC():getCpus() and sim:getPC():getTraits().reverseAll then
monst3rReverse = true
end
if monst3rReverse and (not sim:isVersion("0.17.5") or not ability.noDaemonReversal ) then
local newAbilityID = serverdefs.REVERSE_DAEMONS[ sim:nextRand( 1, #serverdefs.REVERSE_DAEMONS ) ]
ability = simability.create( newAbilityID )
sim:triggerEvent( simdefs.TRG_DAEMON_REVERSE )
end
table.insert( self._mainframeAbilities, ability )
ability:spawnAbility( self._sim, self, hostUnit )
if self:isNPC() then
sim:dispatchEvent( simdefs.EV_MAINFRAME_INSTALL_PROGRAM, {idx = #self._mainframeAbilities, ability=ability} )
sim:triggerEvent( simdefs.TRG_DAEMON_INSTALL )
end
end
end
function mainframe_panel.panel:refreshBreakIceButton( widget, unit )
local sim = self._hud._game.simCore
local program = self:getCurrentProgram()
local canUse, reason = false, STRINGS.UI.REASON.NO_EQUIPPED_PROGRAM
if program then
canUse, reason = mainframe.canBreakIce( sim, unit, program )
end
if self._hud._game:isReplaying() then
canUse, reason = false, nil
end
local tooltipWidget = widget.binder.btn
local daemonTooltip = nil
widget:setAlias( "BreakIce"..unit:getID() )
if not widget.iceBreak then
widget.binder.btn:setText(unit:getTraits().mainframe_ice)
end
widget.binder.btn:setDisabled( not canUse )
if not canUse then
widget.binder.anim:getProp():setRenderFilter( cdefs.RENDER_FILTERS["desat"] )
else
widget.binder.anim:getProp():setRenderFilter( cdefs.RENDER_FILTERS["normal"] )
end
if unit:getTraits().parasite then
widget.binder.anim:setAnim( "idle_bugged" )
else
widget.binder.anim:setAnim( "idle" )
end
if unit:getTraits().flail_target then
widget.binder.flailTarget:setVisible(true)
else
widget.binder.flailTarget:setVisible(false)
end
if unit:getTraits().crossfeed_source then
widget.binder.crossfeedSource:setVisible(true)
else
widget.binder.crossfeedSource:setVisible(false)
end
if unit:getTraits().crossfeed_target then
widget.binder.crossfeedTarget:setVisible(true)
else
widget.binder.crossfeedTarget:setVisible(false)
end
if unit:getTraits().uplink then
widget.binder.pwrUplink:setVisible(true)
else
widget.binder.pwrUplink:setVisible(false)
end
local programWidget = widget.binder.program
if sim:getHideDaemons() and not unit:getTraits().daemon_sniffed then
programWidget:setVisible( true )
programWidget.binder.daemonUnknown:setVisible(false)
programWidget.binder.daemonKnown:setVisible(false)
programWidget.binder.daemonHidden:setVisible(true)
elseif unit:getTraits().mainframe_program ~= nil then
programWidget:setVisible( true )
local npc_abilities = include( "sim/abilities/npc_abilities" )
local ability = npc_abilities[ unit:getTraits().mainframe_program ]
if unit:getTraits().daemon_sniffed then
programWidget.binder.daemonUnknown:setVisible(false)
programWidget.binder.daemonKnown:setVisible(true)
if unit:getTraits().daemon_sniffed_revealed == nil then
unit:getTraits().daemon_sniffed_revealed = true
programWidget.binder.daemonKnown.binder.txt:spoolText(ability.name, 12)
else
programWidget.binder.daemonKnown.binder.txt:setText(ability.name)
end
daemonTooltip = programWidget.binder.daemonKnown.binder.bg
else
programWidget.binder.daemonKnown:setVisible(false)
programWidget.binder.daemonUnknown:setVisible(true)
end
programWidget.binder.daemonHidden:setVisible(false)
else
programWidget:setVisible( false )
end
if not canUse or program == nil or program.acquireTargets then
widget.binder.btn.onClick = nil
tooltipWidget:setTooltip( nil )
else
widget.binder.btn.onClick = function( widget, ie )
if unit:isValid() and mainframe.canBreakIce( sim, unit, program ) then
MOAIFmodDesigner.playSound( cdefs.SOUND_HUD_MAINFRAME_CONFIRM_ACTION )
self._hud._game:doAction( "mainframeAction", {action = "breakIce", unitID = unit:getID() } )
end
end
end
if reason == "nulldrone" then
tooltipWidget:setTooltip( function()
local str = STRINGS.UI.REASON.SECURED
local str2 = STRINGS.UI.REASON.SECURED_2
return null_tooltip( self._hud, str, str2 )
end )
widget.binder.btn:setText("-")
else
tooltipWidget:setTooltip( function()
local breakIceTooltip = include( "hud/tooltip_breakice" )
return breakIceTooltip( self, widget, unit, reason )
end )
if daemonTooltip then
daemonTooltip:setTooltip( function()
local breakIceTooltip = include( "hud/tooltip_breakice_nolines" )
return breakIceTooltip( self, widget, unit, reason )
end )
end
end
end
function tooltip_breakice:init( mainframePanel, iceWidget, unit, reason )
util.tooltip.init( self, mainframePanel._hud._screen )
self._iceWidget = iceWidget
self.mainframePanel = mainframePanel
local localPlayer = mainframePanel._hud._game:getLocalPlayer()
local equippedProgram = nil
if localPlayer then
equippedProgram = localPlayer:getEquippedProgram()
if equippedProgram then
local programWidget = mainframePanel._panel.binder.programsPanel:findWidget( equippedProgram:getID() )
if programWidget and programWidget:isVisible() then
self._ux0, self._uy0 = programWidget.binder.btn:getAbsolutePosition()
if equippedProgram:canUseAbility( mainframePanel._hud._game.simCore, localPlayer ) then
self.programWidget = programWidget
self.equippedProgram = equippedProgram
end
end
end
end
local section = self:addSection()
section:addLine( "<ttheader>"..util.sformat( STRINGS.UI.TOOLTIPS.MAINFRAME_HACK_UNIT, unit:getName() ).."</>" )
if unit:getTraits().mainframe_ice then
section:addAbility( string.format(STRINGS.UI.TOOLTIPS.FIREWALLS, unit:getTraits().mainframe_ice), STRINGS.UI.TOOLTIPS.FIREWALLS_DESC, "gui/icons/action_icons/Action_icon_Small/icon-action_lock_small.png" )
end
if equippedProgram then
section:addAbility( string.format(STRINGS.UI.TOOLTIPS.CURRENTLY_EQUIPPED, equippedProgram:getDef().name), util.sformat(equippedProgram:getDef().tipdesc, equippedProgram:getCpuCost()), "gui/icons/arrow_small.png" )
end
if unit:getTraits().parasite then
if unit:getTraits().parasiteV2 then
section:addLine( STRINGS.UI.TOOLTIPS.MAINFRAME_PARASITE_V2 )
else
section:addLine( STRINGS.UI.TOOLTIPS.MAINFRAME_PARASITE )
end
end
if unit:getTraits().uplink then
section:addLine( STRINGS.PROGEXTEND.UI.TARGET_PWRUPLINK )
end
if unit:getTraits().crossfeed_source then
section:addLine( STRINGS.PROGEXTEND.UI.TARGET_CROSSFEED_S )
end
if unit:getTraits().crossfeed_target then
section:addLine( STRINGS.PROGEXTEND.UI.TARGET_CROSSFEED_T )
end
if unit:getTraits().flail_target then
section:addLine( STRINGS.PROGEXTEND.UI.TARGET_FLAIL )
end
local sim = mainframePanel._hud._game.simCore
if sim:getHideDaemons() and not unit:getTraits().daemon_sniffed then
section:addRequirement( STRINGS.UI.TOOLTIPS.MAINFRAME_MASKED )
else
if unit:getTraits().mainframe_program then
section:addRequirement( STRINGS.UI.TOOLTIPS.MAINFRAME_DAEMON)
local npc_abilities = include( "sim/abilities/npc_abilities" )
local ability = npc_abilities[ unit:getTraits().mainframe_program ]
if unit:getTraits().daemon_sniffed then
section:addAbility( ability.name, ability.desc, ability.icon )
else
section:addAbility( STRINGS.UI.TOOLTIPS.MAINFRAME_HIDDEN_DAEMON, "?????????", "gui/items/item_quest.png" )
end
end
end
if reason then
section:addRequirement( reason )
end
end
function simunit:processEMP( bootTime, noEmpFX, ignoreMagRei )
local empResisted = false
local doEMPeffect = false
if self:getTraits().mainframe_status == "off" then
if self:getTraits().mainframe_booting then
self:getTraits().mainframe_booting = bootTime -- Restart boot timer.
end
elseif self:getTraits().mainframe_status ~= nil and self:getTraits().mainframe_status ~= "off" then
local EMP_FIREWALL_BREAK_STRENGTH = 2
if self:getTraits().magnetic_reinforcement and self:getTraits().mainframe_ice > 2 and not ignoreMagRei then
empResisted = true
local x1,y1 = self:getLocation()
local sim = self._sim
mainframe.breakIce( sim, self, EMP_FIREWALL_BREAK_STRENGTH )
self._sim:dispatchEvent( simdefs.EV_UNIT_FLOAT_TXT, {txt=STRINGS.UI.TOOLTIPS.MAGNETIC_REINFOREMENTS,x=x1,y=y1,color={r=255/255,g=255/255,b=255/255,a=1}} )
else
self:getTraits().mainframe_status_old = self:getTraits().mainframe_status
if self.deactivate then
self:deactivate( self._sim )
end
if self:getTraits().firewallShield then
self:getTraits().shields = 0
end
self:getTraits().mainframe_status = "off"
self:getTraits().mainframe_booting = bootTime
if self:getTraits().switched then
self:getTraits().switched = nil
self:setSwitchStage(self._sim,"off")
end
if self:getTraits().progress then
self:setSwitchStage(self._sim,"off")
end
if self:getTraits().hacker then
local hacker = self._sim:getUnit(self:getTraits().hacker)
hacker:getTraits().data_hacking = nil
hacker:getSounds().spot = nil
self._sim:dispatchEvent( simdefs.EV_UNIT_TINKER_END, { unit = hacker } )
self._sim:dispatchEvent( simdefs.EV_UNIT_REFRESH, { unit = hacker })
self:getTraits().hacker = nil
end
doEMPeffect = true
end
elseif not empResisted and self:getTraits().heartMonitor == "enabled" then
doEMPeffect = true
end
if doEMPeffect then
if not noEmpFX then
local x0,y0 = self:getLocation()
self._sim:dispatchEvent( simdefs.EV_PLAY_SOUND, {sound="SpySociety/HitResponse/hitby_distrupter_flesh", x=x0,y=y0} )
self._sim:dispatchEvent( simdefs.EV_UNIT_REFRESH, { unit = self, fx = "emp" } )
end
self._sim:triggerEvent( simdefs.TRG_UNIT_EMP, self )
end
if not empResisted and self:getTraits().heartMonitor=="enabled" then
local x1,y1 = self:getLocation()
if self:getTraits().improved_heart_monitor then
self._sim:dispatchEvent( simdefs.EV_UNIT_FLOAT_TXT, {txt=STRINGS.UI.FLY_TXT.IMPROVED_HEART_MONITOR,x=x1,y=y1,color={r=1,g=1,b=41/255,a=1}} )
else
self:getTraits().heartMonitor="disabled"
self._sim:dispatchEvent( simdefs.EV_UNIT_FLOAT_TXT, {txt=STRINGS.UI.FLY_TXT.MONITOR_DISABLED,x=x1,y=y1,color={r=255/255,g=255/255,b=255/255,a=1}} )
end
end
self._sim:getPC():glimpseUnit( self._sim, self:getID() )
end
function reset_servers()
local serverroom_1 = include( "sim/prefabs/shared/serverroom_1" )
local serverroom_2 = include( "sim/prefabs/shared/serverroom_2" )
local serverroom_3 = include( "sim/prefabs/shared/serverroom_3" )
serverroom_1.units =
{
{
maxCount = 5,
spawnChance = 1,
{
{
x = 4,
y = 1,
template = [[console_core]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 3,
y = 3,
template = [[console]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 5,
y = 3,
template = [[console]],
unitData =
{
facing = 4,
},
},
1,
},
{
{
x = 5,
y = 5,
template = [[server_terminal]],
unitData =
{
facing = 4,
tags =
{
"serverFarm",
},
},
},
1,
},
},
}
serverroom_2.units =
{
{
maxCount = 5,
spawnChance = 1,
{
{
x = 9,
y = 6,
template = [[console_core]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 7,
y = 6,
template = [[console]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 5,
y = 6,
template = [[console]],
unitData =
{
facing = 4,
},
},
1,
},
{
{
x = 6,
y = 3,
template = [[server_terminal]],
unitData =
{
facing = 2,
tags =
{
"serverFarm",
},
},
},
1,
},
},
}
serverroom_3.units =
{
{
maxCount = 5,
spawnChance = 1,
{
{
x = 6,
y = 8,
template = [[console_core]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 1,
y = 8,
template = [[console]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 11,
y = 8,
template = [[console]],
unitData =
{
facing = 4,
},
},
1,
},
{
{
x = 6,
y = 1,
template = [[server_terminal]],
unitData =
{
facing = 2,
tags =
{
"serverFarm",
},
},
},
1,
},
},
}
end
function set_servers()
local serverroom_1 = include( "sim/prefabs/shared/serverroom_1" )
local serverroom_2 = include( "sim/prefabs/shared/serverroom_2" )
local serverroom_3 = include( "sim/prefabs/shared/serverroom_3" )
serverroom_1.units =
{
{
maxCount = 5,
spawnChance = 1,
{
{
x = 3,
y = 5,
template = [[extra_server_terminal]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 4,
y = 1,
template = [[console_core]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 3,
y = 3,
template = [[console]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 5,
y = 3,
template = [[console]],
unitData =
{
facing = 4,
},
},
1,
},
{
{
x = 5,
y = 5,
template = [[server_terminal]],
unitData =
{
facing = 4,
tags =
{
"serverFarm",
},
},
},
1,
},
},
}
serverroom_2.units =
{
{
maxCount = 5,
spawnChance = 1,
{
{
x = 6,
y = 9,
template = [[extra_server_terminal]],
unitData =
{
facing = 6,
},
},
1,
},
{
{
x = 9,
y = 6,
template = [[console_core]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 7,
y = 6,
template = [[console]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 5,
y = 6,
template = [[console]],
unitData =
{
facing = 4,
},
},
1,
},
{
{
x = 6,
y = 3,
template = [[server_terminal]],
unitData =
{
facing = 2,
tags =
{
"serverFarm",
},
},
},
1,
},
},
}
serverroom_3.units =
{
{
maxCount = 5,
spawnChance = 1,
{
{
x = 6,
y = 3,
template = [[extra_server_terminal]],
unitData =
{
facing = 6,
},
},
1,
},
{
{
x = 6,
y = 8,
template = [[console_core]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 1,
y = 8,
template = [[console]],
unitData =
{
facing = 0,
},
},
1,
},
{
{
x = 11,
y = 8,
template = [[console]],
unitData =
{
facing = 4,
},
},
1,
},
{
{
x = 6,
y = 1,
template = [[server_terminal]],
unitData =
{
facing = 2,
tags =
{
"serverFarm",
},
},
},
1,
},
},
}
end
function update_base_programs()
local simdefs = include( "sim/simdefs" )
local mainframe_common = include("sim/abilities/mainframe_common")
local mainframe_abilities_base = include("sim/abilities/mainframe_abilities")
local npc_abilities = include("sim/abilities/npc_abilities")
local DEFAULT_ABILITY = mainframe_common.DEFAULT_ABILITY
local createDaemon = mainframe_common.createDaemon
local createReverseDaemon = mainframe_common.createReverseDaemon
local createCountermeasureInterest = mainframe_common.createCountermeasureInterest
mainframe_abilities_base.remoteprocessor = util.extend( DEFAULT_ABILITY )
{
name = STRINGS.PROGEXTEND.PROGRAMS.POWER_DRIP.NAME,
desc = STRINGS.PROGEXTEND.PROGRAMS.POWER_DRIP.DESC,
shortdesc = STRINGS.PROGEXTEND.PROGRAMS.POWER_DRIP.SHORT_DESC,
huddesc = STRINGS.PROGEXTEND.PROGRAMS.POWER_DRIP.HUD_DESC,
icon = "gui/icons/programs_icons/icon-program-powerdrip.png",
icon_100 = "gui/icons/programs_icons/store_icons/StorePrograms_drip.png",
value = 500,
passive = true,
executeAbility = function( self, sim )
local player = sim:getCurrentPlayer()
if not player:isNPC() then
local PWR = 1
sim:dispatchEvent( simdefs.EV_PLAY_SOUND, cdefs.SOUND_HUD_MAINFRAME_PROGRAM_AUTO_RUN )
if sim:getTrackerStage( math.min( simdefs.TRACKER_MAXCOUNT, sim:getTracker() )) == 0 then
PWR = 2
end
sim:dispatchEvent( simdefs.EV_SHOW_WARNING, {txt=string.format(STRINGS.PROGEXTEND.PROGRAMS.POWER_DRIP.WARNING,PWR), color=cdefs.COLOR_PLAYER_WARNING, sound = "SpySociety/Actions/mainframe_gainCPU",icon=self.icon } )
player:addCPUs( PWR )
end
end,
canUseAbility = function( self, sim )
return false
end,
onSpawnAbility = function( self, sim )
DEFAULT_ABILITY.onSpawnAbility( self, sim )
end,
onTrigger = function( self, sim, evType, evData )
DEFAULT_ABILITY.onTrigger( self, sim, evType, evData )
if evType == simdefs.TRG_START_TURN then
self:executeAbility(sim)
end
end,
}
mainframe_abilities_base.fusion_17_10 = util.extend( mainframe_abilities_base.fusion_17_10 )
{
value = 500,
}
mainframe_abilities_base.seed = util.extend( mainframe_abilities_base.seed )
{
value = 550,
}
mainframe_abilities_base.pwr_manager = util.extend( DEFAULT_ABILITY )
{
name = STRINGS.PROGRAMS.PWR_MANAGER.NAME,
desc = STRINGS.PROGEXTEND.PROGRAMS.PWR_MANAGER.DESC,
huddesc = STRINGS.PROGEXTEND.PROGRAMS.PWR_MANAGER.HUD_DESC,
shortdesc = STRINGS.PROGEXTEND.PROGRAMS.PWR_MANAGER.SHORT_DESC,
tipdesc = STRINGS.PROGRAMS.PWR_MANAGER.TIP_DESC,
passive = true,
icon = "gui/icons/programs_icons/Program0019.png",
icon_100 = "gui/icons/programs_icons/store_icons/StorePrograms_0019.png",
value = 300,
canUseAbility = function( self, sim )
return false
end,
onSpawnAbility = function( self, sim, player )
DEFAULT_ABILITY.onSpawnAbility( self, sim )
if not player:getTraits().extraStartingPWR then
player:getTraits().extraStartingPWR = 0
end
if not player:getTraits().PWRmaxBouns then
player:getTraits().PWRmaxBouns = 0
end
player:getTraits().extraStartingPWR = player:getTraits().extraStartingPWR + 4
player:getTraits().PWRmaxBouns = player:getTraits().PWRmaxBouns + 5
end,
onDespawnAbility = function( self, sim, player )
DEFAULT_ABILITY.onDespawnAbility( self, sim )
player:getTraits().PWRmaxBouns = player:getTraits().PWRmaxBouns - 5
end,
}
mainframe_abilities_base.pwr_manager_2 = util.extend( DEFAULT_ABILITY )
{
name = STRINGS.PROGRAMS.PWR_MANAGER_2.NAME,
desc = STRINGS.PROGEXTEND.PROGRAMS.PWR_MANAGER_2.DESC,
huddesc = STRINGS.PROGEXTEND.PROGRAMS.PWR_MANAGER_2.HUD_DESC,
shortdesc = STRINGS.PROGEXTEND.PROGRAMS.PWR_MANAGER_2.SHORT_DESC,
tipdesc = STRINGS.PROGRAMS.PWR_MANAGER_2.TIP_DESC,
passive = true,
icon = "gui/icons/programs_icons/Program0019.png",
icon_100 = "gui/icons/programs_icons/store_icons/StorePrograms_0019.png",
value = 450,
canUseAbility = function( self, sim )
return false
end,
onSpawnAbility = function( self, sim, player )
DEFAULT_ABILITY.onSpawnAbility( self, sim )
if not player:getTraits().extraStartingPWR then
player:getTraits().extraStartingPWR = 0
end
if not player:getTraits().PWRmaxBouns then
player:getTraits().PWRmaxBouns = 0
end
player:getTraits().extraStartingPWR = player:getTraits().extraStartingPWR + 6
player:getTraits().PWRmaxBouns = player:getTraits().PWRmaxBouns + 10
end,
onDespawnAbility = function( self, sim, player )
DEFAULT_ABILITY.onDespawnAbility( self, sim )
player:getTraits().PWRmaxBouns = player:getTraits().PWRmaxBouns - 10
end,
}
mainframe_abilities_base.sniffer = util.extend( mainframe_abilities_base.sniffer )
{
value = 100,
maxCooldown = 1
}
mainframe_abilities_base.rogue = util.extend( mainframe_abilities_base.rogue )
{
value = 150,
cpu_cost = 1
}
mainframe_abilities_base.root = util.extend( DEFAULT_ABILITY )
{
name = STRINGS.PROGRAMS.ROOT.NAME,
desc = STRINGS.PROGEXTEND.PROGRAMS.ROOT.DESC,
shortdesc = STRINGS.PROGEXTEND.PROGRAMS.ROOT.SHORT_DESC,
huddesc = STRINGS.PROGEXTEND.PROGRAMS.ROOT.HUD_DESC,
icon = "gui/icons/programs_icons/icon-program_Root.png",
icon_100 = "gui/icons/programs_icons/store_icons/StorePrograms_Root.png",
value = 600,
pwrMod = 1,
passive = true,
onTrigger = function( self, sim, evType, evData )
if evType == simdefs.TRG_START_TURN and evData:isPC() then
evData:addCPUs( 2 )
sim:dispatchEvent( simdefs.EV_PLAY_SOUND, cdefs.SOUND_HUD_MAINFRAME_PROGRAM_AUTO_RUN )
sim:dispatchEvent( simdefs.EV_SHOW_WARNING, {txt=STRINGS.PROGEXTEND.PROGRAMS.ROOT.WARNING, color=cdefs.COLOR_PLAYER_WARNING, sound = "SpySociety/Actions/mainframe_PWRreverse_off",icon=self.icon } )
end
DEFAULT_ABILITY.onTrigger( self, sim, evType, evData )
end,
canUseAbility = function( self, sim )
return false
end,
onSpawnAbility = function( self, sim )
DEFAULT_ABILITY.onSpawnAbility( self, sim )
end,
onDespawnAbility = function( self, sim, player )
DEFAULT_ABILITY.onDespawnAbility( self, sim )
end,
}
mainframe_abilities_base.faust = util.extend( DEFAULT_ABILITY )
{
name = STRINGS.PROGEXTEND.PROGRAMS.FAUST.NAME,
desc = STRINGS.PROGEXTEND.PROGRAMS.FAUST.DESC,
huddesc = STRINGS.PROGEXTEND.PROGRAMS.FAUST.HUD_DESC,
shortdesc = STRINGS.PROGEXTEND.PROGRAMS.FAUST.SHORT_DESC,
tipdesc = STRINGS.PROGEXTEND.PROGRAMS.FAUST.TIP_DESC,
lockedText = STRINGS.UI.TEAM_SELECT.UNLOCK_CENTRAL_MONSTER,
icon = "gui/icons/programs_icons/icon-program-faust.png",
icon_100 = "gui/icons/programs_icons/store_icons/StorePrograms_faust.png",
value = 500,
passive = true,
executeAbility = function( self, sim )
local player = sim:getCurrentPlayer()
sim:dispatchEvent( simdefs.EV_PLAY_SOUND, cdefs.SOUND_HUD_MAINFRAME_PROGRAM_AUTO_RUN )
sim:dispatchEvent( simdefs.EV_SHOW_WARNING, {txt=STRINGS.PROGRAMS.FAUST.WARNING, color=cdefs.COLOR_PLAYER_WARNING, sound = "SpySociety/Actions/mainframe_gainCPU",icon=self.icon } )
player:addCPUs( 2 )
end,
canUseAbility = function( self, sim )
return false
end,
onTrigger = function( self, sim, evType, evData )
DEFAULT_ABILITY.onTrigger( self, sim, evType, evData )
if evType == simdefs.TRG_START_TURN and evData:isPC() then
self:executeAbility(sim)
if evData:getCpus() % 5 == 0 and sim:getTracker() > 1 then
local programList = nil
local daemon = nil
if sim:isVersion("0.17.5") then
programList = sim:getIcePrograms()
daemon = programList:getChoice( sim:nextRand( 1, programList:getTotalWeight() ))
else
programList = serverdefs.PROGRAM_LIST
daemon = programList[sim:nextRand(1, #programList)]
end
sim:getNPC():addMainframeAbility( sim, daemon )
end
end
end,
}
mainframe_abilities_base.fool = util.extend( DEFAULT_ABILITY )
{
name = STRINGS.PROGRAMS.FOOL.NAME,
desc = STRINGS.PROGRAMS.FOOL.DESC,
huddesc = STRINGS.PROGRAMS.FOOL.HUD_DESC,
shortdesc = STRINGS.PROGRAMS.FOOL.SHORT_DESC,
tipdesc = STRINGS.PROGRAMS.FOOL.TIP_DESC,
icon = "gui/icons/programs_icons/icon-program_Jester.png",
icon_100 = "gui/icons/programs_icons/store_icons/StorePrograms_Jester.png",
cooldown = 0,
maxCooldown = 1,
cpu_cost = 0,
equip_program = true,
equipped = false,
value = 100,
onSpawnAbility = function( self, sim, player )
DEFAULT_ABILITY.onSpawnAbility( self, sim )
player:getTraits().daemonDurationModd = (player:getTraits().daemonDurationModd or 0) + 1
end,
onDespawnAbility = function( self, sim, player )
DEFAULT_ABILITY.onDespawnAbility( self, sim )
player:getTraits().daemonDurationModd = (player:getTraits().daemonDurationModd or 0) - 1
end,
executeAbility = function( self, sim, targetUnit )
DEFAULT_ABILITY.executeAbility(self, sim, targetUnit)
targetUnit:processEMP( 1, false, true )
local programList = nil
local daemon = nil
if sim:isVersion("0.17.5") then
programList = sim:getIcePrograms()
daemon = programList:getChoice( sim:nextRand( 1, programList:getTotalWeight() ))
else
programList = serverdefs.PROGRAM_LIST
daemon = programList[sim:nextRand(1, #programList)]
end
sim:getNPC():addMainframeAbility( sim, daemon )
end,
}
npc_abilities.energize = util.extend( createReverseDaemon( STRINGS.PROGEXTEND.REVERSE_DAEMONS.FORTUNE ) )
{
icon = "gui/icons/daemon_icons/Program0021.png",
standardDaemon = false,
reverseDaemon = true,
premanent = false,
ENDLESS_DAEMONS = false,
PROGRAM_LIST = false,
OMNI_PROGRAM_LIST_EASY = false,
OMNI_PROGRAM_LIST = false,
REVERSE_DAEMONS = true,
onSpawnAbility = function( self, sim, player )
self.duration = 4
for i, unit in pairs(sim:getAllUnits()) do
if unit:getTraits().safeUnit and unit:getPlayerOwner() ~= sim:getPC() and not unit:getTraits().open and unit:getTraits().mainframe_ice then
if unit:getTraits().credits then
unit:getTraits().credits = math.floor(unit:getTraits().credits * 1.5)
end
end
end
sim:dispatchEvent( simdefs.EV_SHOW_REVERSE_DAEMON, { name = self.name, icon=self.icon, txt = util.sformat(self.activedesc, self.duration ) } )
sim:addTrigger( simdefs.TRG_END_TURN, self )
end,
onDespawnAbility = function( self, sim )
sim:removeTrigger( simdefs.TRG_END_TURN, self )
for i, unit in pairs(sim:getAllUnits()) do
if unit:getTraits().safeUnit and unit:getPlayerOwner() ~= sim:getPC() and not unit:getTraits().open and unit:getTraits().mainframe_ice then
if unit:getTraits().credits then
unit:getTraits().credits = math.floor(unit:getTraits().credits / 1.5)
end
end
end
end,
executeTimedAbility = function( self, sim )
sim:getNPC():removeAbility(sim, self )
end,
}
npc_abilities.alertPulse = util.extend( createDaemon( STRINGS.PROGEXTEND.DAEMONS.PULSEV2 ) )
{
icon = "gui/icons/daemon_icons/icon-daemon_pulse.png",
standardDaemon = false,
reverseDaemon = false,
premanent = true,
ENDLESS_DAEMONS = true,
PROGRAM_LIST = false,
OMNI_PROGRAM_LIST_EASY = false,
OMNI_PROGRAM_LIST = false,
REVERSE_DAEMONS = false,
onSpawnAbility = function( self, sim, player )
local pcplayer = sim:getPC()
self.items = {}
sim:dispatchEvent( simdefs.EV_SHOW_DAEMON, { name = self.name, icon=self.icon, txt = self.activedesc, } )
local pcplayer = sim:getPC()
for i, unit in pairs( pcplayer:getUnits() ) do
for i, item in pairs( unit:getChildren() ) do
table.insert( self.items, item )
end
end
for _, item in ipairs(self.items) do
if item:getTraits().cooldownMax then
item:getTraits().cooldownMax = item:getTraits().cooldownMax + 3
end
end
end,
onDespawnAbility = function( self, sim, unit )
for _, item in ipairs(self.items) do
if item:getTraits().cooldownMax then
item:getTraits().cooldownMax = item:getTraits().cooldownMax - 3
end
end
end,
}
npc_abilities.alertModulate = util.extend( createDaemon( STRINGS.PROGEXTEND.DAEMONS.MODULATEV2 ) )
{
icon = "gui/icons/daemon_icons/Daemons00013.png",
standardDaemon = false,
reverseDaemon = false,
premanent = true,
ENDLESS_DAEMONS = true,
PROGRAM_LIST = false,
OMNI_PROGRAM_LIST_EASY = false,
OMNI_PROGRAM_LIST = false,
REVERSE_DAEMONS = false,
onSpawnAbility = function( self, sim, player )
sim:dispatchEvent( simdefs.EV_SHOW_DAEMON, { name = self.name, icon=self.icon, txt = self.activedesc, } )
if not sim:getPC():getTraits().program_cost_modifier then
sim:getPC():getTraits().program_cost_modifier = 0
end
sim:getPC():getTraits().program_cost_modifier = sim:getPC():getTraits().program_cost_modifier + 2
sim:addTrigger( simdefs.TRG_END_TURN, self )
end,
onDespawnAbility = function( self, sim )
sim:getPC():getTraits().program_cost_modifier = sim:getPC():getTraits().program_cost_modifier - 2
sim:removeTrigger( simdefs.TRG_END_TURN, self )
end,
}
npc_abilities.siphon = util.extend( createDaemon( STRINGS.DAEMONS.SIPHON ) )
{
icon = "gui/icons/daemon_icons/Daemons0005.png",
onSpawnAbility = function( self, sim, player )
self._cpu = sim:nextRand(2, 5)
sim:dispatchEvent( simdefs.EV_SHOW_DAEMON, { name = self.name, icon=self.icon, txt = util.sformat(self.activedesc, self._cpu ), } )
sim:getCurrentPlayer():addCPUs( -self._cpu )
sim:getNPC():addCPUs( self._cpu )
player:removeAbility(sim, self )
end,
onDespawnAbility = function( self, sim, unit )
end,
}
npc_abilities.fortify = util.extend( createDaemon( STRINGS.DAEMONS.RUBIKS ) )
{
icon = "gui/icons/daemon_icons/Daemons0001.png",
onSpawnAbility = function( self, sim, player )
sim:dispatchEvent( simdefs.EV_SHOW_DAEMON, { showMainframe=true, name = self.name, icon=self.icon, txt = self.activedesc, } )
sim:dispatchEvent( simdefs.EV_WAIT_DELAY, 0.5 * cdefs.SECONDS )
for _, unit in pairs( sim:getAllUnits() ) do
if unit:getTraits().mainframe_ice and unit:getTraits().mainframe_ice > 0 and unit:getPlayerOwner() ~= sim:getPC() then
unit:increaseIce(sim,1)
end
end
player:removeAbility(sim, self )
end,
onDespawnAbility = function( self, sim, unit )
end,
}
end
function set_shops()
store.STORE_ITEM.storeType.server["progAmount"] = 6
store.STORE_ITEM.storeType["extraserver"] =
{
itemAmount = 0,
progAmount = 4,
weaponAmount = 0,
augmentAmount = 0,
noBreakers = true
}
end
function set_rarity()
for i=1,33,1 do
store.STORE_ITEM.progList:removeChoice(1)
end
for i=1,7,1 do
store.STORE_ITEM.progList_17_5:removeChoice(1)
end
for i=1,24,1 do
store.STORE_ITEM.noBreakerProgList:removeChoice(1)
end
for i=1,5,1 do
store.STORE_ITEM.noBreakerProgList_17_5:removeChoice(1)
end
store.STORE_ITEM.progList:addChoice( "lockpick_1", 20 )
store.STORE_ITEM.progList:addChoice( "lockpick_2", 20 )
store.STORE_ITEM.progList:addChoice( "dagger", 20 )
store.STORE_ITEM.progList:addChoice( "dagger_2", 20 )
store.STORE_ITEM.progList:addChoice( "parasite", 20 )
store.STORE_ITEM.progList:addChoice( "parasite_2", 20 )
store.STORE_ITEM.progList:addChoice( "rapier", 20 )
store.STORE_ITEM.progList:addChoice( "dataBlast", 20 )
store.STORE_ITEM.progList:addChoice( "wrench_2", 10 )
store.STORE_ITEM.progList:addChoice( "wrench_3", 10 )
store.STORE_ITEM.progList:addChoice( "wrench_4", 10 )
store.STORE_ITEM.progList:addChoice( "wrench_5", 10 )
store.STORE_ITEM.progList:addChoice( "hammer", 10 )
store.STORE_ITEM.progList:addChoice( "brimstone", 10 )
store.STORE_ITEM.progList_17_5:addChoice( "mercenary", 10 )
store.STORE_ITEM.progList_17_5:addChoice( "flare", 5 )
store.STORE_ITEM.progList_17_5:addChoice( "feast", 5 )
store.STORE_ITEM.noBreakerProgList:addChoice( "hunter", 20 )
store.STORE_ITEM.noBreakerProgList:addChoice( "mainframePing", 20 )
store.STORE_ITEM.noBreakerProgList:addChoice( "esp", 20 )
store.STORE_ITEM.noBreakerProgList:addChoice( "taurus", 20 )
store.STORE_ITEM.noBreakerProgList:addChoice( "remoteprocessor", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "emergency_drip", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "fusion_17_10", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "seed", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "sniffer", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "oracle", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "pwr_manager", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "faust", 5 )
store.STORE_ITEM.noBreakerProgList:addChoice( "wildfire", 5 )
store.STORE_ITEM.noBreakerProgList:addChoice( "wings", 5 )
store.STORE_ITEM.noBreakerProgList:addChoice( "shade", 5 )
store.STORE_ITEM.noBreakerProgList:addChoice( "leash", 5 )
store.STORE_ITEM.noBreakerProgList:addChoice( "pwr_manager_2", 5 )
store.STORE_ITEM.noBreakerProgList_17_5:addChoice( "lightning", 20 )
store.STORE_ITEM.noBreakerProgList_17_5:addChoice( "dynamo", 10 )
store.STORE_ITEM.noBreakerProgList_17_5:addChoice( "overdrive", 10 )
store.STORE_ITEM.noBreakerProgList_17_5:addChoice( "charge", 10 )
store.STORE_ITEM.noBreakerProgList_17_5:addChoice( "root", 10 )
store.STORE_ITEM.noBreakerProgList_17_5:addChoice( "rogue", 10 )
store.STORE_ITEM.noBreakerProgList_17_5:addChoice( "halt", 5 )
store.STORE_ITEM.noBreakerProgList_17_5:addChoice( "fool", 5 )
end
function set_rarity_dlc()
local dlc = include( "dlc1/mainframe_abilities")
store.STORE_ITEM.progList:addChoice( "golem_17_10", 20 )
store.STORE_ITEM.noBreakerProgList:addChoice( "bless", 20 )
store.STORE_ITEM.noBreakerProgList:addChoice( "burst", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "cycle", 10 )
store.STORE_ITEM.noBreakerProgList:addChoice( "aces", 5 )
end
function pcplayer:lockdownMainframeAbility( num )
local abilitiesTotal = #self:getAbilities()
if num > abilitiesTotal then return end
if (#self:getLockedAbilities()) > 0 then
for _, abilityNum in ipairs(self._lockedMainframeAbilities) do
if abilityNum ~= num then
table.insert(self._lockedMainframeAbilities, num)
end
end
else
table.insert(self._lockedMainframeAbilities, num)
end
end
function aiplayer:onStartTurn( sim )
local units = util.tdupe( self._units )
for i,unit in ipairs( units ) do
if unit:isValid() then
unit:onStartTurn( sim )
end
end
if sim:getTags().clearPWREachTurn then
self:addCPUs( -self:getCpus( ), sim )
end
if sim:getTurnCount() <= 1 then
local counter_ai = sim:getParams().difficultyOptions.W93_AI or -1
if ((counter_ai == 0 and (sim:getParams().world == "omni" or sim:getParams().world == "omni2")) or ( counter_ai <= sim:getParams().difficulty and counter_ai > 0 )) then
sim:getNPC():addMainframeAbility( sim, "W93_AI_assembly", nil, 0 )
end
end
end
function aiplayer:findMainframeAbility(abilityID)
local mainframe_abilities = include( "sim/abilities/mainframe_abilities" )
local npc_abilities = include( "sim/abilities/npc_abilities" )
local testAbility = mainframe_abilities[abilityID]
if not testAbility then
testAbility = npc_abilities[abilityID]
end
return testAbility
end
function mainframe.canBreakIce( sim, targetUnit, equippedProgram )
local player = sim:getCurrentPlayer()
if player == nil then
return false
end
if sim:getMainframeLockout() then
return false, STRINGS.UI.REASON.INCOGNITA_LOCKED_DOWN
end
if (targetUnit:getTraits().mainframe_ice or 0) <= 0 then
return false
end
if targetUnit:getTraits().isDrone and targetUnit:isKO() then
return false
end
if targetUnit:getTraits().mainframe_status == "off" then
if not (targetUnit:getTraits().mainframe_camera and targetUnit:getTraits().mainframe_booting) then
return false
end
end
if targetUnit:getTraits().iceImmune then
return false, STRINGS.PROGEXTEND.UI.JAMMED
end
if equippedProgram == nil then
equippedProgram = player:getEquippedProgram()
end
if equippedProgram == nil then
return false, STRINGS.UI.REASON.NO_PROGRAM
end
if sim:getCurrentPlayer() == nil or equippedProgram:getCpuCost() > player:getCpus() then
return false, STRINGS.UI.REASON.NOT_ENOUGH_PWR
end
local ok, result = equippedProgram:canUseAbility( sim, player, targetUnit )
if not ok then
return result
end
if equippedProgram.sniffer then
if not sim:getHideDaemons() and not targetUnit:getTraits().mainframe_program then
return false, STRINGS.UI.REASON.NO_DAEMON
elseif targetUnit:getTraits().daemon_sniffed then
return false, STRINGS.UI.REASON.DAEMON_REVEALED
end
end
if equippedProgram.daemon_killer then
if not sim:getHideDaemons() and not targetUnit:getTraits().mainframe_program then
return false, STRINGS.UI.REASON.NO_DAEMON
end
end
if equippedProgram.wrench then
if targetUnit:getTraits().mainframe_ice ~= equippedProgram.break_firewalls then
return false, util.sformat( STRINGS.UI.REASON.WRONG_WRENCH, equippedProgram.break_firewalls )
end
end
local x0, y0 = targetUnit:getLocation()
for unitID, unit in pairs( sim:getAllUnits() ) do
local range = unit:getTraits().mainframe_suppress_range
if range and unit:getPlayerOwner() ~= sim:getPC() and not unit:isKO() and unit:getLocation() and unit ~= targetUnit then
local distSqr = mathutil.distSqr2d( x0, y0, unit:getLocation() )
if distSqr <= range * range then
return false, "nulldrone"
end
end
end
return true
end
local function calculateDiscount( unit, tag, buyback )
local discount = 1.00
local penalty = unit:getSim():getPC():getTraits().shopPenalty or 0
discount = discount + penalty
local shopperUnit = unit
if tag == "shop" then
for _, child in pairs( shopperUnit:getChildren() ) do
if child:getTraits().shopDiscount then
discount = discount - child:getTraits().shopDiscount
end
end
end
if buyback then
discount = 0.50
end
return discount
end
local function onClickBuyItem( panel, item, itemType )
local sim = panel._hud._game.simCore
local player = panel._unit
if not panel._unit._isPlayer then
player = panel._unit:getPlayerOwner()
end
if player ~= sim:getCurrentPlayer() then
modalDialog.show( STRINGS.UI.TOOLTIP_CANT_PURCHASE )
return
end
if item:getTraits().mainframe_program then
local maxPrograms = simdefs.MAX_PROGRAMS + (sim:getParams().agency.extraPrograms or 0)
if #player:getAbilities() >= maxPrograms then
modalDialog.show( STRINGS.UI.TOOLTIP_PROGRAMS_FULL )
return
end
if player:hasMainframeAbility( item:getTraits().mainframe_program ) then
modalDialog.show( STRINGS.UI.TOOLTIP_ALREADY_OWN )
return
end
elseif panel._unit:getInventoryCount() >= 8 then
modalDialog.show( STRINGS.UI.TOOLTIP_INVENTORY_FULL )
return
end
local credits = player:getCredits()
if credits < (item:getUnitData().value * panel._discount) then
modalDialog.show( STRINGS.UI.TOOLTIP_NOT_ENOUGH_CREDIT )
return
end
local itemIndex = nil
if panel._buyback then
if itemType == "item" then
itemIndex = array.find( panel._shopUnit.buyback.items, item )
elseif itemType == "weapon" then
itemIndex = array.find( panel._shopUnit.buyback.weapons, item )
elseif itemType == "augment" then
itemIndex = array.find( panel._shopUnit.buyback.augments, item )
end
else
if itemType == "item" then
itemIndex = array.find( panel._shopUnit.items, item )
elseif itemType == "weapon" then
itemIndex = array.find( panel._shopUnit.weapons, item )
elseif itemType == "augment" then
itemIndex = array.find( panel._shopUnit.augments, item )
end
end
MOAIFmodDesigner.playSound(cdefs.SOUND_HUD_BUY)
panel._hud._game:doAction( "buyItem", panel._unit:getID(), panel._shopUnit:getID(), itemIndex, panel._discount, itemType, panel._buyback )
panel.last_action = panel._buyback and "buyback" or "buy"
panel:refresh()
end
local function onClickBuyBack( panel )
panel._buyback = not panel._buyback
if panel._buyback then
panel._discount = 0.50
panel._screen.binder.shop_bg.binder.buybackBtn:setText( STRINGS.UI.SHOP_NANOFAB )
else
if panel._unit then
panel._discount = calculateDiscount(panel._unit, panel._tag, panel._buyback)
else
panel._discount = 1.00
end
panel._screen.binder.shop_bg.binder.buybackBtn:setText( STRINGS.UI.SHOP_BUYBACK )
end
if panel._shopUnit then
if #panel._shopUnit.buyback.items == 0 and #panel._shopUnit.buyback.weapons == 0 and #panel._shopUnit.buyback.augments == 0 then
if not panel._buyback then
panel._screen.binder.shop_bg.binder.buybackBtn:setVisible( false )
end
end
end
panel.last_action = "buyback"
panel:refresh()
end
local function onClickSellItem( panel, item )
local modalDialog = include( "states/state-modal-dialog" )
local result = modalDialog.showYesNo( util.sformat(STRINGS.UI.SHOP_SELL_AREYOUSURE, item:getName(), item:getUnitData().value * 0.5 ), STRINGS.UI.SHOP_SELL_AREYOUSURE_TITLE, nil, STRINGS.UI.SHOP_SELL_CONFIRM, nil, true )
if result == modalDialog.OK then
local itemIndex = array.find( panel._unit:getChildren(), item )
MOAIFmodDesigner.playSound(cdefs.SOUND_HUD_SELL)
panel._hud._game:doAction( "sellItem", panel._unit:getID(), panel._shopUnit:getID(), itemIndex )
local buybackBtn = panel._screen.binder.shop_bg.binder.buybackBtn
buybackBtn:setVisible( true )
buybackBtn.onClick = util.makeDelegate( nil, onClickBuyBack, panel )
panel.last_action = "sell"
panel:refresh()
end
end
local function onClickClose( panel )
panel:destroy()
end
function shop_panel.shop:init( hud, shopperUnit, shopUnit )
local items_panel = include( "hud/items_panel" )
items_panel.base.init( self, hud, shopperUnit, shopUnit:getTraits().storeType )
self._tag = "shop"
self._shopUnit = shopUnit
self._unit = shopperUnit
self._discount = calculateDiscount( shopperUnit, "shop", nil )
local panelBinder = self._screen.binder
panelBinder.sell.binder.titleLbl:setText(STRINGS.UI.SHOP_SELL)
panelBinder.headerTxt:spoolText(STRINGS.UI.SHOP_PRINTER)
panelBinder.shop_bg.binder.closeBtn.onClick = util.makeDelegate( nil, onClickClose, self )
panelBinder.shop_bg:setVisible(true)
panelBinder.shop:setVisible(true)
panelBinder.inventory_bg:setVisible(false)
panelBinder.inventory:setVisible(false)
end
function shop_panel.shop:refresh()
local panelBinder = self._screen.binder
self._discount = calculateDiscount(self._unit, "shop", self._buyback)
local itemCount = 0
for i, widget in panelBinder.items.binder:forEach( "item" ) do
if self:refreshItem( widget, i, "item" ) then
itemCount = itemCount + 1
end
end
for i, widget in panelBinder.weapons.binder:forEach( "item" ) do
if self:refreshItem( widget, i, "weapon" ) then
itemCount = itemCount + 1
end
end
for i, widget in panelBinder.augments.binder:forEach( "item" ) do
if self:refreshItem( widget, i, "augment" ) then
itemCount = itemCount + 1
end
end
local items = {}
for i,childUnit in ipairs(self._unit:getChildren()) do
if not childUnit:getTraits().augment or not childUnit:getTraits().installed then
table.insert(items,childUnit)
end
end
for i, widget in panelBinder.sell.binder:forEach( "item" ) do
self:refreshUserItem( self._unit, items[i], widget, i )
end
self:refreshCredits()
if (itemCount == 0 and not self._buyback) or not self._unit:canAct() then
onClickClose( self )
end
end
function shop_panel.shop:refreshItem( widget, i, itemType )
local guiex = include( "guiex" )
local item = nil
if self._buyback then
if itemType == "item" then
item = self._shopUnit.buyback.items[i]
elseif itemType == "weapon" then
item = self._shopUnit.buyback.weapons[i]
elseif itemType == "augment" then
item = self._shopUnit.buyback.augments[i]
end
else
if itemType == "item" then
item = self._shopUnit.items[i]
elseif itemType == "weapon" then
item = self._shopUnit.weapons[i]
elseif itemType == "augment" then
item = self._shopUnit.augments[i]
end
end
if item == nil then
widget:setVisible( false )
return false
else
guiex.updateButtonFromItem( self._screen, nil, widget, item, self._unit )
widget.binder.itemName:setText( util.toupper(item:getName()) )
widget.binder.cost:setText( util.sformat( STRINGS.FORMATS.CREDITS, math.ceil(item:getUnitData().value * self._discount ) ))
widget.binder.btn.onClick = util.makeDelegate( nil, onClickBuyItem, self, item, itemType )
widget.binder.btn.onDragStart = util.makeDelegate( self, "onDragFromBottom", item:getUnitData().profile_icon, widget.binder.btn.onClick )
return true
end
end
function shop_panel.shop:refreshUserItem( unit, item, widget, i )
local items_panel = include( "hud/items_panel" )
if items_panel.base.refreshUserItem( self, unit, item, widget, i ) then
widget.binder.cost:setVisible(true)
if item:getUnitData().value then
widget.binder.cost:setText( util.sformat( STRINGS.FORMATS.PLUS_CREDS, math.ceil(item:getUnitData().value * 0.5) ))
widget.binder.btn.onClick = util.makeDelegate( nil, onClickSellItem, self, item )
widget.binder.btn.onDragStart = util.makeDelegate( self, "onDragSell", item:getUnitData().profile_icon, widget.binder.btn.onClick )
else
widget.binder.cost:setText( "" )--STRINGS.UI.SHOP_CANNOT_SELL
widget.binder.btn:setDisabled( true )
end
return true
end
end
function mission_util.makeAgentConnection( script, sim )
local SCRIPTS = include('client/story_scripts')
script:waitFor( mission_util.UI_INITIALIZED )
script:queue( { type = "hideInterface" })
sim:dispatchEvent( simdefs.EV_TELEPORT, { units = sim:getPC():getAgents(), warpOut = false } )
local isEndless = sim:getParams().difficultyOptions.maxHours == math.huge
local settingsFile = savefiles.getSettings( "settings" )
if sim:getParams().missionCount == 0 and not isEndless then
script:queue( 1*cdefs.SECONDS )
script:queue( { script = SCRIPTS.INGAME.CENTRAL_FIRST_LEVEL, type="modalConversation" } )
script:queue( { type = "showInterface" })
script:queue( 0.5*cdefs.SECONDS )
script:queue( { type = "showMissionObjectives" })
else
script:queue( 1.5*cdefs.SECONDS )
script:queue( { type = "showInterface" })
script:queue( 0.5*cdefs.SECONDS )
script:queue( { type = "showMissionObjectives" })
script:addHook( mission_util.doAgentBanter )
end
if sim:getParams().difficultyOptions.W93_endless_daemons and sim:getParams().campaignHours then
if sim:getParams().difficultyOptions.W93_endless_daemons < math.floor(sim:getParams().campaignHours/24) and sim:getParams().maxHours == math.huge then
local daemon = serverdefs.ENDLESS_DAEMONS[ sim:nextRand(1, #serverdefs.ENDLESS_DAEMONS) ]
sim:getNPC():addMainframeAbility(sim, daemon, sim:getNPC(), 0 )
end
elseif sim:getParams().endlessAlert then
local daemon = serverdefs.ENDLESS_DAEMONS[ sim:nextRand(1, #serverdefs.ENDLESS_DAEMONS) ]
sim:getNPC():addMainframeAbility(sim, daemon, sim:getNPC(), 0 )
end
end
|
-- Lua code to support BS BL editor
|
option("is_clang")
add_cxxsnippets("is_clang", 'if(__clang__) return 0;', {tryrun = true})
option_end()
option("is_msvc")
add_cxxsnippets("is_msvc", 'if(_MSC_VER) return 0;', {tryrun = true})
option_end()
option("is_unix")
add_cxxsnippets("is_unix", 'if(__unix__) return 0;', {tryrun = true})
option_end()
option("pointer-size")
add_cxxsnippets("VOID_P_SIZE", 'printf("%d", sizeof(void*)); return 0;', {output = true, number = true})
option_end()
project_cxflags = {}
project_mxflags = {}
if(has_config("is_clang")) then
table.insert(project_cxflags, "-Wno-format")
table.insert(project_cxflags, "-Wno-switch")
table.insert(project_cxflags, "-Wno-unknown-pragmas")
table.insert(project_cxflags, "-Wno-ignored-attributes")
table.insert(project_cxflags, "-Wno-ignored-attributes")
table.insert(project_cxflags, "-Wno-deprecated-declarations")
table.insert(project_cxflags, "-Wno-nullability-completeness")
table.insert(project_cxflags, "-Werror=return-type")
end
if(has_config("is_msvc")) then
table.insert(project_cxflags, "/FC")
table.insert(project_cxflags, "/EHsc")
table.insert(project_cxflags, "/GR-")
table.insert(project_cxflags, "/wd4251")
if(has_config("is_clang")) then
table.insert(project_cxflags, "-fexceptions")
table.insert(project_cxflags, "-fcxx-exceptions")
end
end |
return {
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 35,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 34,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 33,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 31,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 30,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 29,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 26,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 25,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 23,
skill_id = 12050
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 20,
skill_id = 12050
}
}
}
},
init_effect = "",
name = "小比叡1",
time = 0,
color = "red",
picture = "",
desc = "",
stack = 1,
id = 12050,
icon = 12050,
last_effect = "",
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onUpdate"
},
arg_list = {
target = "TargetSelf",
time = 35,
skill_id = 12050
}
}
}
}
|
--[[ LuaJIT FFI reflection Library ]]--
--[[ Copyright (C) 2014 Peter Cawley <lua@corsix.org>. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--]]
local ffi = require "ffi"
local bit = require "bit"
local reflect = {}
local CTState, init_CTState
local miscmap, init_miscmap
local function gc_str(gcref)
-- Convert a GCref (to a GCstr) into a string
if gcref ~= 0 then
local ts = ffi.cast("uint32_t*", gcref)
return ffi.string(ts + 4, ts[3])
end
end
local typeinfo = ffi.typeinfo or function(id)
-- ffi.typeof is present in LuaJIT v2.1 since 8th Oct 2014 (d6ff3afc)
-- this is an emulation layer for older versions of LuaJIT
local ctype = (CTState or init_CTState()).tab[id]
return {
info = ctype.info,
size = bit.bnot(ctype.size) ~= 0 and ctype.size,
sib = ctype.sib ~= 0 and ctype.sib,
name = gc_str(ctype.name),
}
end
ffi.cdef(([[
typedef struct GCRef {
%s gcptr;
} GCRef;
]]):format(ffi.abi "gc64" and "uint64_t" or "uint32_t"))
ffi.cdef [[
typedef struct GCcdata {
GCRef nextgc; uint8_t marked; uint8_t gct;
uint16_t ctypeid; /* C type ID. */
} GCcdata;
]]
local function memptr(gcobj)
return tonumber(tostring(gcobj):match "%x*$", 16)
end
function reflect.typeFromId(id)
local cts = CTState or init_CTState()
assert(0 < id and id < cts.top)
local v = ffi.new('uint32_t', id)
local p = ffi.cast('GCcdata*', memptr(v)) - 1
p.ctypeid = 21
return v
end
function reflect.typeFromName(name)
local cts = CTState or init_CTState()
for i = 1, cts.top - 1 do
local ctype = cts.tab[i]
if gc_str(ctype.name) == name then
return reflect.typeFromId(i)
end
end
end
init_CTState = function()
-- Relevant minimal definitions from lj_ctype.h
ffi.cdef [[
typedef struct CType {
uint32_t info;
uint32_t size;
uint16_t sib;
uint16_t next;
uint32_t name;
} CType;
typedef struct CTState {
CType *tab;
uint32_t top;
uint32_t sizetab;
void *L;
void *g;
void *finalizer;
void *miscmap;
} CTState;
]]
-- Acquire a pointer to this Lua universe's CTState
local co = coroutine.create(function()
end) -- Any live coroutine will do.
local uintgc = ffi.abi "gc64" and "uint64_t" or "uint32_t"
local uintgc_ptr = ffi.typeof(uintgc .. "*")
local G = ffi.cast(uintgc_ptr, ffi.cast(uintgc_ptr, memptr(co))[2])
-- In global_State, `MRef ctype_state` is immediately before `GCRef gcroot[GCROOT_MAX]`.
-- We first find (an entry in) gcroot by looking for a metamethod name string.
local anchor = ffi.cast(uintgc, ffi.cast("const char*", "__index"))
local i = 0
while math.abs(tonumber(G[i] - anchor)) > 64 do
i = i + 1
end
-- We then work backwards looking for something resembling ctype_state.
repeat
i = i - 1
CTState = ffi.cast("CTState*", G[i])
until ffi.cast(uintgc_ptr, CTState.g) == G
return CTState
end
init_miscmap = function()
-- Acquire the CTState's miscmap table as a Lua variable
local t = {};
t[0] = t
local uptr = ffi.cast("uintptr_t", (CTState or init_CTState()).miscmap)
if ffi.abi "gc64" then
local tvalue = ffi.cast("uint64_t**", memptr(t))[2]
tvalue[0] = bit.bor(bit.lshift(bit.rshift(tvalue[0], 47), 47), uptr)
else
local tvalue = ffi.cast("uint32_t*", memptr(t))[2]
ffi.cast("uint32_t*", tvalue)[ffi.abi "le" and 0 or 1] = ffi.cast("uint32_t", uptr)
end
miscmap = t[0]
return miscmap
end
-- Information for unpacking a `struct CType`.
-- One table per CT_* constant, containing:
-- * A name for that CT_
-- * Roles of the cid and size fields.
-- * Whether the sib field is meaningful.
-- * Zero or more applicable boolean flags.
local CTs = { [0] = { "int",
"", "size", false,
{ 0x08000000, "bool" },
{ 0x04000000, "float", "subwhat" },
{ 0x02000000, "const" },
{ 0x01000000, "volatile" },
{ 0x00800000, "unsigned" },
{ 0x00400000, "long" },
},
{ "struct",
"", "size", true,
{ 0x02000000, "const" },
{ 0x01000000, "volatile" },
{ 0x00800000, "union", "subwhat" },
{ 0x00100000, "vla" },
},
{ "ptr",
"element_type", "size", false,
{ 0x02000000, "const" },
{ 0x01000000, "volatile" },
{ 0x00800000, "ref", "subwhat" },
},
{ "array",
"element_type", "size", false,
{ 0x08000000, "vector" },
{ 0x04000000, "complex" },
{ 0x02000000, "const" },
{ 0x01000000, "volatile" },
{ 0x00100000, "vla" },
},
{ "void",
"", "size", false,
{ 0x02000000, "const" },
{ 0x01000000, "volatile" },
},
{ "enum",
"type", "size", true,
},
{ "func",
"return_type", "nargs", true,
{ 0x00800000, "vararg" },
{ 0x00400000, "sse_reg_params" },
},
{ "typedef", -- Not seen
"element_type", "", false,
},
{ "attrib", -- Only seen internally
"type", "value", true,
},
{ "field",
"type", "offset", true,
},
{ "bitfield",
"", "offset", true,
{ 0x08000000, "bool" },
{ 0x02000000, "const" },
{ 0x01000000, "volatile" },
{ 0x00800000, "unsigned" },
},
{ "constant",
"type", "value", true,
{ 0x02000000, "const" },
},
{ "extern", -- Not seen
"CID", "", true,
},
{ "kw", -- Not seen
"TOK", "size",
},
}
-- Set of CType::cid roles which are a CTypeID.
local type_keys = {
element_type = true,
return_type = true,
value_type = true,
type = true,
}
-- Create a metatable for each CT.
local metatables = {
}
for _, CT in ipairs(CTs) do
local what = CT[1]
local mt = { __index = {} }
metatables[what] = mt
end
-- Logic for merging an attribute CType onto the annotated CType.
local CTAs = { [0] = function(a, refct)
error("TODO: CTA_NONE")
end,
function(a, refct)
error("TODO: CTA_QUAL")
end,
function(a, refct)
a = 2 ^ a.value
refct.alignment = a
refct.attributes.align = a
end,
function(a, refct)
refct.transparent = true
refct.attributes.subtype = refct.typeid
end,
function(a, refct)
refct.sym_name = a.name
end,
function(a, refct)
error("TODO: CTA_BAD")
end,
}
-- C function calling conventions (CTCC_* constants in lj_refct.h)
local CTCCs = { [0] = "cdecl",
"thiscall",
"fastcall",
"stdcall",
}
local function refct_from_id(id)
-- refct = refct_from_id(CTypeID)
local ctype = typeinfo(id)
local CT_code = bit.rshift(ctype.info, 28)
local CT = CTs[CT_code]
local what = CT[1]
local refct = setmetatable({
what = what,
typeid = id,
name = ctype.name,
}, metatables[what])
-- Interpret (most of) the CType::info field
for i = 5, #CT do
if bit.band(ctype.info, CT[i][1]) ~= 0 then
if CT[i][3] == "subwhat" then
refct.what = CT[i][2]
else
refct[CT[i][2]] = true
end
end
end
if CT_code <= 5 then
refct.alignment = bit.lshift(1, bit.band(bit.rshift(ctype.info, 16), 15))
elseif what == "func" then
refct.convention = CTCCs[bit.band(bit.rshift(ctype.info, 16), 3)]
end
if CT[2] ~= "" then
-- Interpret the CType::cid field
local k = CT[2]
local cid = bit.band(ctype.info, 0xffff)
if type_keys[k] then
if cid == 0 then
cid = nil
else
cid = refct_from_id(cid)
end
end
refct[k] = cid
end
if CT[3] ~= "" then
-- Interpret the CType::size field
local k = CT[3]
refct[k] = ctype.size or (k == "size" and "none")
end
if what == "attrib" then
-- Merge leading attributes onto the type being decorated.
local CTA = CTAs[bit.band(bit.rshift(ctype.info, 16), 0xff)]
if refct.type then
local ct = refct.type
ct.attributes = {}
CTA(refct, ct)
ct.typeid = refct.typeid
refct = ct
else
refct.CTA = CTA
end
elseif what == "bitfield" then
-- Decode extra bitfield fields, and make it look like a normal field.
refct.offset = refct.offset + bit.band(ctype.info, 127) / 8
refct.size = bit.band(bit.rshift(ctype.info, 8), 127) / 8
refct.type = {
what = "int",
bool = refct.bool,
const = refct.const,
volatile = refct.volatile,
unsigned = refct.unsigned,
size = bit.band(bit.rshift(ctype.info, 16), 127),
}
refct.bool, refct.const, refct.volatile, refct.unsigned = nil
end
if CT[4] then
-- Merge sibling attributes onto this type.
while ctype.sib do
local entry = typeinfo(ctype.sib)
if CTs[bit.rshift(entry.info, 28)][1] ~= "attrib" then
break
end
if bit.band(entry.info, 0xffff) ~= 0 then
break
end
local sib = refct_from_id(ctype.sib)
sib:CTA(refct)
ctype = entry
end
end
return refct
end
local function sib_iter(s, refct)
repeat
local ctype = typeinfo(refct.typeid)
if not ctype.sib then
return
end
refct = refct_from_id(ctype.sib)
until refct.what ~= "attrib" -- Pure attribs are skipped.
return refct
end
local function siblings(refct)
-- Follow to the end of the attrib chain, if any.
while refct.attributes do
refct = refct_from_id(refct.attributes.subtype or typeinfo(refct.typeid).sib)
end
return sib_iter, nil, refct
end
metatables.struct.__index.members = siblings
metatables.func.__index.arguments = siblings
metatables.enum.__index.values = siblings
local function find_sibling(refct, name)
local num = tonumber(name)
if num then
for sib in siblings(refct) do
if num == 1 then
return sib
end
num = num - 1
end
else
for sib in siblings(refct) do
if sib.name == name then
return sib
end
end
end
end
metatables.struct.__index.member = find_sibling
metatables.func.__index.argument = find_sibling
metatables.enum.__index.value = find_sibling
--- reflect.typeof returns a so-called refct object, which describes the type passed in to the function.
---@return ffi.refct
function reflect.typeof(x)
-- refct = reflect.typeof(ct)
return refct_from_id(tonumber(ffi.typeof(x)))
end
--- reflect.getmetatable performs the inverse of ffi.metatype - given a ctype, it returns the corresponding metatable that was passed to ffi.metatype.
--- ## Example
--- reflect.getmetatable(ffi.metatype("struct {}", t)) == t
function reflect.getmetatable(x)
-- mt = reflect.getmetatable(ct)
return (miscmap or init_miscmap())[-tonumber(ffi.typeof(x))]
end
---@class ffi.refct
--- A refct object is one of 13 different kinds of type. For example, one of those kinds is "int", which covers all primitive integral types, and another is "ptr", which covers all pointer types. Perhaps unusually, every field within a structure is also considered to be a type, as is every argument within a function type, and every value within an enumerated type. While this may look odd, it results in a nice uniform API for type reflection. Note that typedefs are resolved by the parser, and are therefore not visible when reflected.
local _r = {}
--- All refct objects have a what field, which is a string denoting the kind of type. Other fields will also be present on a refct object, but these vary according to the kind.
_r.what = nil
--[[
"void" kind (refct.what)
Possible attributes: size, alignment, const, volatile.
The primitive empty type, optionally with a const and/or volatile qualifier. The actual type is therefore determined by the const and volatile fields.
Examples:
reflect.typeof("void").what == "void"
reflect.typeof("const void").what == "void"
---
"int" kind (refct.what)
Possible attributes: size, alignment, const, volatile, bool, unsigned, long.
A primitive integral type, such as bool or [const] [volatile] [u]int(8|16|32|64)_t. The in-memory type is determined by the size and unsigned fields, and the final quantified type determined also by the bool, const, and volatile fields.
Examples:
reflect.typeof("long").what == "int"
reflect.typeof("volatile unsigned __int64").what == "int"
---
"float" kind (refct.what)
Possible attributes: size, alignment, const, volatile.
A primitive floating point type, either [const] [volatile] float or [const] [volatile] double.
Examples:
reflect.typeof("double").what == "float"
reflect.typeof("const float").what == "float"
---
"enum" kind (refct.what)
Possible attributes: name, size, alignment, type.
Methods: values, value.
An enumerated type.
Example:
ffi.cdef "enum E{X,Y};"
reflect.typeof("enum E").what == "enum"
---
"constant" kind (refct.what)
Possible attributes: name, type, value.
A particular value within an enumerated type.
Example:
ffi.cdef "enum Bool{False,True};"
reflect.typeof("enum Bool"):value("False").what == "constant"
---
"ptr" kind (refct.what)
Possible attributes: size, alignment, const, volatile, element_type.
A pointer type (note that this includes function pointers). The type being pointed to is given by the element_type attribute.
Examples:
reflect.typeof("char*").what == "ptr"
reflect.typeof("int(*)(void)").what == "ptr"
---
"ref" kind (refct.what)
Possible attributes: size, alignment, const, volatile, element_type.
A reference type. The type being referenced is given by the element_type attribute.
Example:
reflect.typeof("char&").what == "ref"
---
"array" kind (refct.what)
Possible attributes: size, alignment, const, volatile, element_type, vla, vector, complex.
An array type. The type of each element is given by the element_type attribute. The number of elements is not directly available; instead the size attribute needs to be divided by element_type.size.
Examples:
reflect.typeof("char[16]").what == "array"
reflect.typeof("int[?]").what == "array"
---
"struct" kind (refct.what)
Possible attributes: name, size, alignment, const, volatile, vla, transparent.
Methods: members, member.
A structure aggregate type. The members of the structure can be enumerated through the members method, or indexed through the member method.
Example:
reflect.typeof("struct{int x; int y;}").what == "struct"
---
"union" kind (refct.what)
Possible attributes: name, size, alignment, const, volatile, transparent.
Methods: members, member.
A union aggregate type. The members of the union can be enumerated through the members method, or indexed through the member method.
Example:
reflect.typeof("union{int x; int y;}").what == "union"
---
"func" kind (refct.what)
Possible attributes: name, sym_name, return_type, nargs, vararg, sse_reg_params, convention.
Methods: arguments, argument.
A function aggregate type. Note that function pointers will be of the "ptr" kind, with a "func" kind as the element_type. The return type is available as the return_type attribute, while argument types can be enumerated through the arguments method, or indexed through the argument method. The number of arguments is determined from the nargs and vararg attributes.
Example:
ffi.cdef "int strcmp(const char*, const char*);"
reflect.typeof(ffi.C.strcmp).what == "func"
Example:
reflect.typeof("int(*)(void)").element_type.what == "func"
---
"field" kind (refct.what)
Possible attributes: name, offset, type.
An instance of a type within a structure or union, or an occurance of a type as an argument to a function.
Example:
reflect.typeof("struct{int x;}"):member("x").what == "field"
Example:
ffi.cdef "int strcmp(const char*, const char*);"
reflect.typeof(ffi.C.strcmp):argument(2).what == "field"
---
"bitfield" kind (refct.what)
Possible attributes: name, size, offset, type.
An instance of a type within a structure or union, which has an offset and/or size which is not a whole number of bytes.
Example:
reflect.typeof("struct{int x:2;}"):member("x").what == "bitfield"
]]
--
--- refct.name attribute (string or nil)
--- Applies to: struct, union, enum, func, field, bitfield, constant.
---
--- The type's given name, or nil if the type has no name.
--- ## Example
--- reflect.typeof("struct{int x; int y;}"):member(2).name == "y"
--- reflect.typeof("struct{int x; int y;}").name == nil
--- ffi.cdef 'int sc(const char*, const char*) __asm__("strcmp");'
--- reflect.typeof(ffi.C.sc).name == "sc"
_r.name = nil
--
--- refct.sym_name attribute (string or nil)
--- Applies to: func.
---
--- The function's symbolic name, if different to its given name.
--- ## Example
--- ffi.cdef 'int sc(const char*, const char*) __asm__("strcmp");'
--- reflect.typeof(ffi.C.sc).sym_name == "strcmp"
--- ffi.cdef "int strcmp(const char*, const char*);"
--- reflect.typeof(ffi.C.strcmp).sym_name == nil
_r.sym_name = nil
--
--- refct.size attribute (number or string)
--- Applies to: int, float, struct, union, ptr, ref, array, void, enum, bitfield.
---
--- The size of the type, in bytes. For most things this will be a strictly positive integer, although that is not always the case:
--- For empty structures and unions, size will be zero.
--- For types which are essentially void, size will be the string "none".
--- For bitfields, size can have a fractional part, which will be a multiple of 1/8.
--- For structures which terminate with a VLA, this will be the size of the fixed part of the structure.
--- For arrays, size will be the element size multiplied by the number of elements, or the string "none" if the number of elements is not known or not fixed.
--- ## Example
--- reflect.typeof("__int32").size == 4
--- reflect.typeof("__int32[2]").size == 8
--- reflect.typeof("__int32[]").size == "none"
--- reflect.typeof("__int32[?]").size == "none"
--- reflect.typeof("struct{__int32 count; __int32 data[?];}").size == 4
--- reflect.typeof("struct{}").size == 0
--- reflect.typeof("void").size == "none"
--- reflect.typeof("struct{int f:5;}"):member("f").size == 5 / 8
_r.size = nil
--
--- refct.offset attribute (number)
--- Applies to: field, bitfield.
---
--- For structure and union members, the number of bytes between the start of the containing type and the (bit)field. For a normal field, this will be a non-negative integer. For bitfields, this can have a fractional part which is a multiple of 1/8.
---
--- For function arguments, the zero-based index of the argument.
--- ## Example
--- reflect.typeof("struct{__int32 x; __int32 y; __int32 z;}"):member("z").offset == 8
--- reflect.typeof("struct{int x : 3; int y : 4; int z : 5;}"):member("z").offset == 7 / 8
--- reflect.typeof("int(*)(int x, int y)").element_type:argument("y").offset == 1
_r.offset = nil
--
--- refct.alignment attribute (integer)
--- Applies to: int, float, struct, union, ptr, ref, array, void, enum.
---
--- The minimum alignment required by the type, in bytes. Unless explicitly overridden by an alignment qualifier, this will be the value calculated by LuaJIT's C parser. In any case, this will be a power of two.
--- ## Example
--- reflect.typeof("struct{__int32 a; __int32 b;}").alignment == 4
--- reflect.typeof("__declspec(align(16)) int").alignment == 16
_r.alignment = nil
--
--- refct.const attribute (true or nil)
--- Applies to: int, float, struct, union, ptr, ref, array, void.
---
--- If true, this type was declared with the const qualifier. Be aware that for pointer types, this refers to the const-ness of the pointer itself, and not the const-ness of the thing being pointed to.
--- ## Example
--- reflect.typeof("int").const == nil
--- reflect.typeof("const int").const == true
--- reflect.typeof("const char*").const == nil
--- reflect.typeof("const char*").element_type.const == true
--- reflect.typeof("char* const").const == true
_r.const = nil
--
--- refct.volatile attribute (true or nil)
--- Applies to: int, float, struct, union, ptr, ref, array, void.
---
--- If true, this type was declared with the volatile qualifier. Note that this has no meaning to the JIT compiler. Be aware that for pointer types, this refers to the volatility of the pointer itself, and not the volatility of the thing being pointed to.
--- ## Example
--- reflect.typeof("int").volatile == nil
--- reflect.typeof("volatile int").volatile == true
_r.volatile = nil
--
--- refct.element_type attribute (refct)
--- Applies to: ptr, ref, array.
---
--- The type being pointed to (albeit implicitly in the case of a reference).
--- ## Example
--- reflect.typeof("char*").element_type.size == 1
--- reflect.typeof("char&").element_type.size == 1
--- reflect.typeof("char[32]").element_type.size == 1
_r.element_type = nil
--
--- refct.type attribute (refct)
--- Applies to: enum, field, bitfield, constant.
---
--- For (bit)fields, the type of the field.
--- ## Example
--- reflect.typeof("struct{float x; unsigned y;}"):member("y").type.unsigned == true
--- reflect.typeof("int(*)(uint64_t)").element_type:argument(1).type.size == 8
_r.type = nil
--
--- refct.return_type attribute (refct)
--- Applies to: func.
---
--- The return type of the function.
--- ## Example
--- ffi.cdef "int strcmp(const char*, const char*);"
--- reflect.typeof(ffi.C.strcmp).return_type.what == "int"
--- reflect.typeof("void*(*)(void)").element_type.return_type.what == "ptr"
_r.return_type = nil
--
--- refct.bool attribute (true or nil)
--- Applies to: int.
---
--- If true, reading from this type will give a Lua boolean rather than a Lua number.
--- ## Example
--- reflect.typeof("bool").bool == true
--- reflect.typeof("int").bool == nil
--- reflect.typeof("_Bool int").bool == true
_r.bool = nil
--
--- refct.unsigned attribute (true or nil)
--- Applies to: int.
---
--- If true, this type denotes an unsigned integer. Otherwise, it denotes a signed integer.
--- ## Example
--- reflect.typeof("int32_t").unsigned == nil
--- reflect.typeof("uint32_t").unsigned == true
_r.unsigned = nil
--
--- refct.long attribute (true or nil)
--- Applies to: int.
---
--- If true, this type was declared with the long qualifier. If calculating the size of the type, then use the size field rather than this field.
--- ## Example
--- reflect.typeof("long int").long == true
--- reflect.typeof("short int").long == nil
_r.long = nil
--
--- refct.vla attribute (true or nil)
--- Applies to: struct, array.
---
--- If true, this type has a variable length. Otherwise, this type has a fixed length.
--- ## Example
--- reflect.typeof("int[?]").vla == true
--- reflect.typeof("int[2]").vla == nil
--- reflect.typeof("int[]").vla == nil
--- reflect.typeof("struct{int num; int data[?];}").vla == true
--- reflect.typeof("struct{int num; int data[];}").vla == nil
_r.vla = nil
--
--- refct.transparent attribute (true or nil)
--- Applies to: struct, union.
---
--- If true, this type is an anonymous inner type. Such types have no name, and when using the FFI normally, their fields are accessed as fields of the containing type.
--- ## Example
--- for refct in reflect.typeof [[
--- struct {
--- int a;
--- union { int b; int c; };
--- struct { int d; int e; };
--- int f;
--- }
--- ]]:members() do print(refct.transparent) end --> nil, true, true, nil
_r.transparent = nil
--
--- refct.vector attribute (true or nil)
--- Applies to: array.
_r.vector = nil
--
--- refct.complex attribute (true or nil)
--- Applies to: array.
_r.complex = nil
--
--- refct.nargs attribute (integer)
--- Applies to: func.
---
--- The number of fixed arguments accepted by the function. If the vararg field is true, then additional arguments are accepted.
--- ## Example
--- ffi.cdef "int strcmp(const char*, const char*);"
--- reflect.typeof(ffi.C.strcmp).nargs == 2
--- ffi.cdef "int printf(const char*, ...);"
--- reflect.typeof(ffi.C.printf).nargs == 1
_r.nargs = nil
--
--- refct.vararg attribute (true or nil)
--- Applies to: func.
---
--- If true, the function accepts a variable number of arguments (i.e. the argument list declaration was terminated with ...).
--- ## Example
--- ffi.cdef "int strcmp(const char*, const char*);"
--- reflect.typeof(ffi.C.strcmp).vararg == nil
--- ffi.cdef "int printf(const char*, ...);"
--- reflect.typeof(ffi.C.printf).vararg == true
_r.vararg = nil
--
--- refct.sse_reg_params attribute (true or nil)
--- Applies to: func.
_r.sse_reg_params = nil
--
--- refct.convention attribute (string)
--- Applies to: func.
---
--- The calling convention that the function was declared with, which will be one of: "cdecl" (the default), "thiscall", "fastcall", "stdcall". Note that on Windows, LuaJIT will automatically change __cdecl to __stdcall after the first call to the function (if appropriate).
--- ## Example
--- reflect.typeof("int(__stdcall *)(int)").element_type.convention == "stdcall"
--- if not ffi.abi "win" then return "Windows-only example" end
--- ffi.cdef "void* LoadLibraryA(const char*)"
--- print(reflect.typeof(ffi.C.LoadLibraryA).convention) --> cdecl
--- ffi.C.LoadLibraryA("kernel32")
--- print(reflect.typeof(ffi.C.LoadLibraryA).convention) --> stdcall
_r.convention = nil
--
--- refct.value attribute (integer)
--- Applies to: constant.
_r.value = nil
--
--- refct iterator = refct:members()
--- Applies to: struct, union.
---
--- Returns an iterator triple which can be used in a for-in statement to enumerate the constituent members of the structure / union, in the order that they were defined. Each such member will be a refct of kind "field", "bitfield", "struct", or "union". The former two kinds will occur most of the time, with the latter two only occurring for unnamed (transparent) structures and unions. If enumerating the fields of a stucture or union, then you need to recursively enumerate these transparent members.
--- ## Example
--- for refct in reflect.typeof("struct{int x; int y;}"):members() do print(refct.name) end --> x, y
--- for refct in reflect.typeof[[
--- struct {
--- int a;
--- union {
--- int b;
--- int c;
--- };
--- int d : 2;
--- struct {
--- int e;
--- int f;
--- };
--- }
--- ]]:members() do print(refct.what) end --> field, union, bitfield, struct
function _r:members()
end
--
--- refct = refct:member(name_or_index)
--- Applies to: struct, union.
---
--- Like members(), but returns the first member whose name matches the given parameter, or the member given by the 1-based index, or nil if nothing matches. Note that this method takes time linear in the number of members.
function _r:member(name_or_index)
end
--
--- refct iterator = refct:arguments()
--- Applies to: func.
---
--- Returns an iterator triple which can be used in a for-in statement to enumerate the arguments of the function, from left to right. Each such argument will be a refct of kind "field", having a type attribute, zero-based offset attribute, and optionally a name attribute.
--- ## Example
--- ffi.cdef "int strcmp(const char*, const char*);"
--- for refct in reflect.typeof(ffi.C.strcmp):arguments() do print(refct.type.what) end --> ptr, ptr
--- for refct in reflect.typeof"int(*)(int x, int y)".element_type:arguments() do print(refct.name) end --> x, y
function _r:arguments()
end
--
--- refct = refct:argument(name_or_index)
--- Applies to: func.
---
--- Like arguments(), but returns the first argument whose name matches the given parameter, or the argument given by the 1-based index, or nil if nothing matches. Note that this method takes time linear in the number of arguments.
function _r:argument(name_or_index)
end
--
--- refct iterator = refct:values()
--- Applies to: enum.
---
--- Returns an iterator triple which can be used in a for-in statement to enumerate the values which make up an enumerated type. Each such value will be a refct of kind "constant", having name and value attributes.
--- ## Example
--- ffi.cdef "enum EV{EV_A = 1, EV_B = 10, EV_C = 100};"
--- for refct in reflect.typeof("enum EV"):values() do print(refct.name) end --> EV_A, EV_B, EV_C
function _r:values()
end
--
--- refct = refct:value(name_or_index)
--- Applies to: enum.
---
--- Like values(), but returns the value whose name matches the given parameter, or the value given by the 1-based index, or nil if nothing matches. Note that this method takes time linear in the number of values.
function _r:value(name_or_index)
end
return reflect
|
-------------------------------------------------------------------------------
-- wireshark-aun-dissector.lua
-- Acorn Universal Networking protocol dissector for WireShark
-- (c) Eelco Huininga 2018-2019
-------------------------------------------------------------------------------
aun_types = {
[0x01] = "Broadcast",
[0x02] = "Unicast",
[0x03] = "Acknowledge",
[0x04] = "Negative acknowledge",
[0x05] = "Immediate",
[0x06] = "Immediate reply"
}
aun_ports = {
[0x00] = "Immediate",
[0x54] = "DigitalServicesTapeStore",
[0x90] = "FileServerReply",
[0x91] = "FileServerData",
[0x92] = "FileServerData",
[0x93] = "FileServerData / Remote",
[0x94] = "FileServerData",
[0x95] = "FileServerData",
[0x96] = "FileServerData",
[0x97] = "FileServerData",
[0x98] = "FileServerData",
[0x99] = "FileServerCommand",
[0x9C] = "Bridge",
[0x9D] = "ResourceLocator",
[0x9E] = "PrinterServerInquiryReply",
[0x9F] = "PrinterServerInquiry",
[0xA0] = "SJ *FAST protocol",
[0xA1] = "SJ Nexus net find reply",
[0xAF] = "SJ Virtual Econet",
[0xB0] = "FindServer",
[0xB1] = "FindServerReply",
[0xB2] = "TeletextServerCommand",
[0xB3] = "TeletextServerPage",
[0xD0] = "PrintServerDataReply",
[0xD1] = "PrintServerData",
[0xD2] = "TCPIPOverEconet",
[0xD3] = "SIDFrameSlave",
[0xD4] = "Scrollarama",
[0xD5] = "Phone",
[0xD6] = "BroadcastControl",
[0xD7] = "BroadcastData",
[0xD8] = "ImpressionLicenceChecker",
[0xD9] = "DigitalServicesSquirrel",
[0xDA] = "SIDSecondary",
[0xDB] = "DigitalServicesSquirrel2",
[0xDC] = "DataDistributionControl",
[0xDD] = "DataDistributionData",
[0xDE] = "ClassROM",
[0xDF] = "PrinterSpoolerCommand",
[0xE0] = "DigitalServicesNetGain1",
[0xE1] = "DigitalServicesNetGain2",
[0xE2] = "AppFS1",
[0xE3] = "AppFS2",
[0xE4] = "AtomWideFaxNet",
[0xE5] = "AtomWidePrintNet",
[0xE6] = "IotaDataPower",
[0xE7] = "CDNetServerBroadcast",
[0xE8] = "CDNetServerReplies",
[0xE9] = "ClassFS_Server",
[0xEA] = "DigitalServicesTapeStore2",
[0xEB] = "DeveloperSupport",
[0xEC] = "LLS_Net"
}
aun_im_functions = {
[0x00] = "Execute command (OSCLI)",
[0x01] = "Peek",
[0x02] = "Poke",
[0x03] = "JSR",
[0x04] = "UserProcedureCall",
[0x05] = "OSProcedureCall",
[0x06] = "Halt",
[0x07] = "Continue",
[0x08] = "MachinePeek",
[0x09] = "GetRegisters"
}
aun_fs_functions = {
[0x00] = "Execute command (OSCLI)",
[0x01] = "Start client-to-server file transfer (*SAVE)",
[0x02] = "Start server-to-client file transfer (*LOAD)",
[0x03] = "Examine object (*EX)",
[0x04] = "Read catalogue header",
[0x05] = "Load as command",
[0x06] = "Open file",
[0x07] = "Close file",
[0x08] = "Get byte",
[0x09] = "Put byte",
[0x0A] = "Get multiple bytes",
[0x0B] = "Put multiple bytes",
[0x0C] = "Read random access information",
[0x0D] = "Set random access information",
[0x0E] = "Read disc name information",
[0x0F] = "Read logged on users",
[0x10] = "Read date/time",
[0x11] = "Read EOF (End Of File) information",
[0x12] = "Read object information",
[0x13] = "Set object information",
[0x14] = "Delete object",
[0x15] = "Read user environment",
[0x16] = "Set user's boot option",
[0x17] = "Log off",
[0x18] = "Read user information",
[0x19] = "Read file server version number",
[0x1A] = "Read file server free space",
[0x1B] = "Create directory",
[0x1C] = "Set date/time",
[0x1D] = "Create file of specified size",
[0x1E] = "Read user free space",
[0x1F] = "Set user free space",
[0x20] = "Read client user identifier",
[0x40] = "Read account information",
[0x41] = "Read/write system information"
}
aun_fs03_functions = {
[0x00] = "All information in binary format",
[0x01] = "All information as ASCII string",
[0x02] = "File title only",
[0x03] = "File title and access as ASCII string"
}
aun_fs0c_functions = {
[0x00] = "Seqeuential file pointer",
[0x01] = "File extent",
[0x02] = "File size"
}
aun_fs0d_functions = {
[0x00] = "Seqeuential file pointer",
[0x01] = "File extent"
}
aun_fs12_functions = {
[0x01] = "Read object creation date",
[0x02] = "Read load and execute address",
[0x03] = "Read object extent",
[0x04] = "Read access byte",
[0x05] = "Read all object attributes",
[0x06] = "Read access and cycle number of directory",
[0x40] = "Read creation and update time"
}
aun_fs13_functions = {
[0x01] = "Set load/exec/access",
[0x02] = "Set load address",
[0x03] = "Set exec address",
[0x04] = "Set access flags",
[0x05] = "Set creation date",
[0x40] = "Set modify/creation date and time"
}
aun_fs40_functions = {
[0x00] = "Read account info"
}
aun_fs41_functions = {
[0x00] = "Reset print server information",
[0x01] = "Read current state of printer",
[0x02] = "Write current state of printer",
[0x03] = "Read auto printer priority",
[0x04] = "Write auto printer priority",
[0x05] = "Read system message channel",
[0x06] = "Write system message channel",
[0x07] = "Read message level",
[0x08] = "Write message level",
[0x09] = "Read default printer",
[0x0A] = "Write default printer",
[0x0B] = "Read the privilege required to change the file servers date and time",
[0x0C] = "Set the privilege required to change the file servers date and time"
}
aun_clientactions = {
[0x00] = "None",
[0x01] = "*Save",
[0x02] = "*Load",
[0x03] = "*Cat",
[0x04] = "*Info, *Printer, *Printout",
[0x05] = "*I Am",
[0x06] = "*SDisc",
[0x07] = "*Dir, *SDisc",
[0x08] = "*Unrecognized command",
[0x09] = "*Lib"
}
aun_printerstatus = {
[0x00] = "Online",
[0x01] = "Busy with station",
[0x02] = "Jammed",
[0x06] = "Offline",
[0x07] = "Already opened by this station"
}
aun_bootoptions = {
[0x00] = "Off",
[0x01] = "Load",
[0x02] = "Run",
[0x03] = "Exec"
}
aun_tcpiptypes = {
[0x81] = "IP Unicast",
[0x8E] = "IP Broadcast Reply",
[0x8F] = "IP Broadcast",
[0xA1] = "ARP Request",
[0xA2] = "ARP Reply"
}
aun_bridgetypes = {
[0x00] = "NewBridge",
[0x01] = "NewBridgeReply",
[0x02] = "WhatNet",
[0x03] = "IsNet"
}
local aun = Proto("aun","Acorn Universal Networking")
aun.fields.packettype = ProtoField.uint8 ("aun.packettype", "Packet type", base.DEC, aun_types)
aun.fields.bridgetype = ProtoField.uint8 ("aun.bridgetype", "Message type", base.DEC, aun_bridgetypes)
aun.fields.tcpiptype = ProtoField.uint8 ("aun.tcpiptype", "Message type", base.HEX, aun_tcpiptype)
aun.fields.port = ProtoField.uint8 ("aun.port", "Port", base.HEX, aun_ports)
aun.fields.control = ProtoField.uint8 ("aun.control", "Control byte", base.HEX)
aun.fields.retrans = ProtoField.uint8 ("aun.retrans", "Retransmission flag", base.HEX)
aun.fields.sequence = ProtoField.uint32("aun.sequence", "Sequence ID", base.HEX)
aun.fields.im_function = ProtoField.uint8 ("aun.im_function", "Function", base.HEX, aun_im_functions)
aun.fields.fs_function = ProtoField.uint8 ("aun.fs_function", "Function", base.HEX, aun_fs_functions)
aun.fields.fs_subfunc03 = ProtoField.uint8 ("aun.fs_subfunc03", "Sub-function", base.HEX, aun_fs03_functions)
aun.fields.fs_subfunc0c = ProtoField.uint8 ("aun.fs_subfunc0c", "Type", base.HEX, aun_fs0c_functions)
aun.fields.fs_subfunc0d = ProtoField.uint8 ("aun.fs_subfunc0d", "Type", base.HEX, aun_fs0d_functions)
aun.fields.fs_subfunc12 = ProtoField.uint8 ("aun.fs_subfunc12", "Sub-function", base.HEX, aun_fs12_functions)
aun.fields.fs_subfunc13 = ProtoField.uint8 ("aun.fs_subfunc13", "Sub-function", base.HEX, aun_fs13_functions)
aun.fields.fs_subfunc40 = ProtoField.uint8 ("aun.fs_subfunc40", "Sub-function", base.HEX, aun_fs40_functions)
aun.fields.fs_subfunc41 = ProtoField.uint8 ("aun.fs_subfunc41", "Sub-function", base.HEX, aun_fs41_functions)
aun.fields.clientaction = ProtoField.uint8 ("aun.clientaction", "Client action", base.HEX)
aun.fields.result = ProtoField.uint8 ("aun.result", "Result", base.HEX)
aun.fields.replyport = ProtoField.uint8 ("aun.replyport", "Reply port", base.HEX, aun_ports)
aun.fields.dataport = ProtoField.uint8 ("aun.dataport", "Data transmission port", base.HEX, aun_ports)
aun.fields.ackport = ProtoField.uint8 ("aun.ackport", "Data acknowledge port", base.HEX, aun_ports)
aun.fields.urd = ProtoField.uint8 ("aun.urd", "URD handle", base.HEX)
aun.fields.csd = ProtoField.uint8 ("aun.csd", "CSD handle", base.HEX)
aun.fields.lib = ProtoField.uint8 ("aun.lib", "LIB handle", base.HEX)
aun.fields.filehandle = ProtoField.uint8 ("aun.filehandle", "File handle", base.HEX)
aun.fields.loadaddr = ProtoField.uint32("aun.loadaddr", "Load address", base.HEX)
aun.fields.execaddr = ProtoField.uint32("aun.execaddr", "Exec address", base.HEX)
aun.fields.attributes = ProtoField.uint32("aun.attributes", "Attributes", base.HEX)
aun.fields.length = ProtoField.uint24("aun.length", "Length", base.HEX)
aun.fields.offset = ProtoField.uint24("aun.offset", "Offset", base.HEX)
aun.fields.useoffset = ProtoField.bool ("aun.useoffset", "Use specified offset", base.NONE)
aun.fields.bytes8 = ProtoField.uint8 ("aun.bytes8", "Number of bytes", base.HEX)
aun.fields.bytes24 = ProtoField.uint8 ("aun.bytes24", "Number of bytes", base.HEX)
aun.fields.identifier = ProtoField.string("aun.identifier", "Identifier string", base.NONE)
aun.fields.command = ProtoField.string("aun.command", "Command", base.NONE)
aun.fields.filename = ProtoField.string("aun.filename", "Filename", base.NONE)
aun.fields.dirname = ProtoField.string("aun.dirname", "Directory name", base.NONE)
aun.fields.objectname = ProtoField.string("aun.objectname", "Object name", base.NONE)
aun.fields.username = ProtoField.string("aun.username", "User name", base.NONE)
aun.fields.discname = ProtoField.string("aun.discname", "Disc name", base.NONE)
aun.fields.discnumber = ProtoField.string("aun.discnumber", "Disc number", base.NONE)
aun.fields.date = ProtoField.string("aun.date", "Date", base.NONE)
aun.fields.time = ProtoField.string("aun.time", "Time", base.NONE)
aun.fields.createdate = ProtoField.string("aun.createdate", "Creation date", base.NONE)
aun.fields.createtime = ProtoField.string("aun.createtime", "Creation time", base.NONE)
aun.fields.modifydate = ProtoField.string("aun.modifydate", "Modification date", base.NONE)
aun.fields.modigytime = ProtoField.string("aun.modifytime", "Modification time", base.NONE)
aun.fields.startat = ProtoField.uint8 ("aun.startat", "Start at number", base.HEX)
aun.fields.items = ProtoField.uint8 ("aun.items", "Number of items to get", base.HEX)
aun.fields.firstaccount = ProtoField.uint16("aun.firstaccount", "First account to try", base.HEX)
aun.fields.maxaccounts = ProtoField.uint16("aun.maxaccounts", "Maximum number of accounts", base.HEX)
aun.fields.blocks = ProtoField.uint8 ("aun.blocks", "Blocks to allocate", base.HEX)
aun.fields.bootoption = ProtoField.uint8 ("aun.bootoption", "Boot option", base.HEX, aun_bootoptions)
aun.fields.createnew = ProtoField.bool ("aun.createnew", "Create new file", base.NONE)
aun.fields.openupdate = ProtoField.bool ("aun.openupdate", "Open object for update", base.NONE)
aun.fields.printerstatus = ProtoField.uint8 ("aun.printerstatus", "Printer status", base.HEX, aun_printerstatus)
aun.fields.station = ProtoField.uint8 ("aun.station", "Station", base.HEX)
aun.fields.network = ProtoField.uint8 ("aun.network", "Network", base.HEX)
aun.fields.data = ProtoField.bytes ("aun.data", "Data", base.SPACE)
aun.fields.attr_r_owner = ProtoField.uint8 ("aun.r_owner", "R - Read access by owner", base.HEX, {"Set", "Not set"}, 0x01)
aun.fields.attr_w_owner = ProtoField.uint8 ("aun.w_owner", "W - Write access by owner", base.HEX, {"Set", "Not set"}, 0x02)
aun.fields.attr_x_owner = ProtoField.uint8 ("aun.x_owner", "E - Execute by owner", base.HEX, {"Set", "Not set"}, 0x04)
aun.fields.attr_l_owner = ProtoField.uint8 ("aun.l_owner", "L - Locked for owner", base.HEX, {"Set", "Not set"}, 0x08)
aun.fields.attr_r_other = ProtoField.uint8 ("aun.r_other", "r - Read access by others", base.HEX, {"Set", "Not set"}, 0x10)
aun.fields.attr_w_other = ProtoField.uint8 ("aun.w_other", "w - Write access by others", base.HEX, {"Set", "Not set"}, 0x20)
aun.fields.attr_x_other = ProtoField.uint8 ("aun.x_other", "e - Execute by others", base.HEX, {"Set", "Not set"}, 0x40)
aun.fields.attr_l_other = ProtoField.uint8 ("aun.l_other", "l - Locked for others", base.HEX, {"Set", "Not set"}, 0x80)
function aun.dissector(buffer, pinfo, tree)
pinfo.cols.protocol = "AUN"
local size = buffer:len()
local packettype = buffer(0,1):uint()
local port = buffer(1,1):le_uint()
local ctrl = buffer(2,1):le_uint()
subtree = tree:add(aun, buffer(), string.format(aun.description .. " (%d bytes)", size))
if size < 8 then
subtree:add(buffer(0, size), "Malformed data: " .. buffer(0, size))
return
end
-- local header_subtree = subtree:add(buffer(0,8),"Header (8 bytes)")
header_subtree = subtree
header_subtree:add_le(aun.fields.packettype, buffer(0,1))
header_subtree:add_le(aun.fields.port, buffer(1,1))
header_subtree:add_le(aun.fields.control, buffer(2,1))
header_subtree:add_le(aun.fields.retrans, buffer(3,1))
header_subtree:add_le(aun.fields.sequence, buffer(4,4))
if size == 8 then
pinfo.cols.info:set(aun_ports[port] .. ": " ..aun_types[packettype])
return
end
-- local data_subtree = subtree:add(buffer(8,size-8), string.format("Data (%d bytes)", size-8))
local data_subtree = subtree
-- Port &00: Immediate
if port == 0x00 then
pinfo.cols.info:set(aun_ports[port] .. ": " .. aun_im_functions[ctrl])
data_subtree:add_le(aun.fields.im_function, buffer(2,1))
data_subtree:add_le(aun.fields.data, buffer(8,size-8))
return
end
-- Port &90: FileServerReply
if port == 0x90 then
local err = buffer(9,1):le_uint()
data_subtree:add_le(aun.fields.clientaction, buffer(8,1))
if err == 0x00 then
pinfo.cols.info:set(aun_ports[port] .. ": Success")
data_subtree:add_le(aun.fields.result, buffer(9,1), 0, nil, "(Success)")
data_subtree:add_le(aun.fields.data, buffer(10,size-10))
return
else
pinfo.cols.info:set(aun_ports[port] .. ": " .. buffer(10,size-10):string())
data_subtree:add_le(aun.fields.result, buffer(9,1), 0, nil, "(" .. buffer(10,size-10):string() .. ")")
return
end
end
-- Port &99: FileServerCommand
if port == 0x99 then
local fs_func = buffer(9,1):le_uint()
pinfo.cols.info:set(aun_ports[port] .. ": " .. aun_fs_functions[fs_func])
data_subtree:add_le(aun.fields.replyport, buffer(8,1))
data_subtree:add_le(aun.fields.fs_function, buffer(9,1))
-- &00: Command line
if fs_func== 0x00 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.command, buffer(13,size-13))
return
end
-- &01: *Save / &1D: Create file of specified size
if fs_func== 0x01 or fs_func== 0x1D then
data_subtree:add_le(aun.fields.dataport, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.loadaddr, buffer(13,4))
data_subtree:add_le(aun.fields.execaddr, buffer(17,4))
data_subtree:add_le(aun.fields.length, buffer(21,3))
data_subtree:add_le(aun.fields.filename, buffer(24,size-24))
return
end
-- &02: *Load / &05: Load as command
if fs_func== 0x02 or fs_func== 0x05 then
data_subtree:add_le(aun.fields.dataport, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.filename, buffer(13,size-13))
return
end
-- &03: *Ex
if fs_func== 0x03 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.fs_subfunc03, buffer(13,1))
data_subtree:add_le(aun.fields.startat, buffer(14,1))
data_subtree:add_le(aun.fields.items, buffer(15,1))
data_subtree:add_le(aun.fields.dirname, buffer(16,size-16))
return
end
-- &04: Catalogue header
if fs_func== 0x04 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.dirname, buffer(13,size-13))
return
end
-- &06: Open file
if fs_func== 0x06 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.createnew, buffer(13,1))
data_subtree:add_le(aun.fields.openupdate, buffer(14,1))
data_subtree:add_le(aun.fields.filename, buffer(15,size-15))
return
end
-- &07: Close file
if fs_func== 0x07 then
data_subtree:add_le(aun.fields.filehandle, buffer(10,1))
return
end
-- &08: BGET
if fs_func== 0x08 then
data_subtree:add_le(aun.fields.filehandle, buffer(10,1))
return
end
-- &09: BPUT
if fs_func== 0x09 then
data_subtree:add_le(aun.fields.filehandle, buffer(10,1))
data_subtree:add_le(aun.fields.bytes8, buffer(11,1))
return
end
-- &0A: Get multiple bytes / &0B: Put multiple bytes
if fs_func== 0x0A or fs_func== 0x0B then
data_subtree:add_le(aun.fields.ackport, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.filehandle, buffer(13,1))
data_subtree:add_le(aun.fields.useoffset, buffer(14,1))
data_subtree:add_le(aun.fields.bytes24, buffer(15,3))
data_subtree:add_le(aun.fields.offset, buffer(18,3))
return
end
-- &0C: Read random access information
if fs_func== 0x0C then
local ptrtype = buffer(11,1):uint()
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.filehandle, buffer(13,1))
data_subtree:add_le(aun.fields.fs_subfunc0c, buffer(14,1))
return
end
-- &0D: Set random access information
if fs_func== 0x0D then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.filehandle, buffer(13,1))
data_subtree:add_le(aun.fields.fs_subfunc0d, buffer(14,1))
data_subtree:add_le(aun.fields.offset, buffer(15,3))
return
end
-- &0E: Read disc information
if fs_func== 0x0E then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.startat, buffer(13,1))
data_subtree:add_le(aun.fields.items, buffer(14,1))
return
end
-- &0F: Read current users
if fs_func== 0x0F then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.startat, buffer(13,1))
data_subtree:add_le(aun.fields.items, buffer(14,1))
return
end
-- &10: Read date and time
if fs_func== 0x11 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
return
end
-- &11: Read EOF status
if fs_func== 0x11 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.filehandle, buffer(13,1))
return
end
-- &12: Read object information
if fs_func== 0x12 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.fs_subfunc12, buffer(13,1))
data_subtree:add_le(aun.fields.dirname, buffer(14,size-14))
return
end
-- &13: Set object attributes (OSFILE)
if fs_func== 0x13 then
local fs_subfunc = buffer(13,1)
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.fs_subfunc13, buffer(13,1))
-- &01: Set load address, exec address, length and object attributes
if (fs_subfunc == 0x01) then
local attribute = buffer(25,1):le_uint()
data_subtree:add_le(aun.fields.loadaddr, buffer(14,4))
data_subtree:add_le(aun.fields.execaddr, buffer(18,4))
data_subtree:add_le(aun.fields.length, buffer(22,3))
data_subtree:add_le(aun.fields.attributes, buffer(25,1))
local attrib_subtree = subtree:add(buffer(0,8),"Attributes: " .. expand_attributes(port))
attrib_subtree:add_le(aun.fields.attr_r_owner, port)
attrib_subtree:add_le(aun.fields.attr_w_owner, port)
attrib_subtree:add_le(aun.fields.attr_x_owner, port)
attrib_subtree:add_le(aun.fields.attr_l_owner, port)
attrib_subtree:add_le(aun.fields.attr_r_other, port)
attrib_subtree:add_le(aun.fields.attr_w_other, port)
attrib_subtree:add_le(aun.fields.attr_x_other, port)
attrib_subtree:add_le(aun.fields.attr_l_other, port)
return
end
-- &02: Set load address
if (fs_subfunc == 0x02) then
data_subtree:add_le(aun.fields.loadaddr, buffer(14,4))
return
end
-- &03: Set exec address
if (fs_subfunc == 0x03) then
data_subtree:add_le(aun.fields.execaddr, buffer(18,4))
return
end
-- &04: Set object attributes
if (fs_subfunc == 0x04) then
local attribute = buffer(14,1):le_uint()
local attrib_subtree = subtree:add(buffer(14,1),"Attributes: " .. expand_attributes(port))
attrib_subtree:add_le(aun.fields.attr_r_owner, port)
attrib_subtree:add_le(aun.fields.attr_w_owner, port)
attrib_subtree:add_le(aun.fields.attr_x_owner, port)
attrib_subtree:add_le(aun.fields.attr_l_owner, port)
attrib_subtree:add_le(aun.fields.attr_r_other, port)
attrib_subtree:add_le(aun.fields.attr_w_other, port)
attrib_subtree:add_le(aun.fields.attr_x_other, port)
attrib_subtree:add_le(aun.fields.attr_l_other, port)
return
end
-- &05: Set creation date
if (fs_subfunc == 0x05) then
data_subtree:add_le(aun.fields.createdate, buffer(14,2), get_date(buffer(14,2):le_int()))
return
end
-- &40: Set update & creation date and time
if (fs_subfunc == 0x40) then
data_subtree:add_le(aun.fields.createdate, buffer(14,2), get_date(buffer(14,2):le_int()))
data_subtree:add_le(aun.fields.createtime, buffer(16,3), get_time(buffer(16,3):le_int()))
data_subtree:add_le(aun.fields.modifydate, buffer(19,2), get_date(buffer(19,2):le_int()))
data_subtree:add_le(aun.fields.modifytime, buffer(21,3), get_time(buffer(21,3):le_int()))
return
end
-- &xx: Unknown
data_subtree:add_le(aun.fields.data, buffer(14,size-14))
return
end
-- &14: Delete object
if fs_func== 0x14 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.objectname, buffer(13,1))
return
end
-- &15: Read user environment
if fs_func== 0x15 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
return
end
-- &16: Set user boot option
if fs_func== 0x16 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.bootoption, buffer(13,1))
return
end
-- &17: Log off
if fs_func== 0x17 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
return
end
-- &18: Read user information
if fs_func== 0x18 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.username, buffer(13,size-13))
return
end
-- &19: Read fileserver version number
if fs_func== 0x19 then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
return
end
-- &1A: Read fileserver free space
if fs_func== 0x1A then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.filename, buffer(13,size-13))
return
end
-- &1B: Create directory
if fs_func== 0x1B then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.blocks, buffer(13,1))
data_subtree:add_le(aun.fields.filename, buffer(14,size-14))
return
end
-- &1C: Set real time clock
if fs_func== 0x1C then
local date = buffer(13,2):uint()
local time = buffer(15,3):uint()
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.date, buffer(13,2), get_date(buffer(13,2):le_int()))
data_subtree:add_le(aun.fields.time, buffer(15,3), get_time(buffer(15,3):le_int()))
return
end
-- &1E: Read user free space
if fs_func== 0x1E then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.username, buffer(13,size-13))
return
end
-- &1F: Set user free space
if fs_func== 0x1F then
data_subtree:add_le(aun.fields.urd, buffer(10,1))
data_subtree:add_le(aun.fields.csd, buffer(11,1))
data_subtree:add_le(aun.fields.lib, buffer(12,1))
data_subtree:add_le(aun.fields.loadaddr, buffer(13,4))
data_subtree:add_le(aun.fields.username, buffer(17,size-17))
return
end
-- &40: Read account information
if fs_func== 0x40 then
local subfunc = buffer(13,1):le_uint()
data_subtree:add_le(aun.fields.fs_subfunc40, buffer(13,1))
data_subtree:add_le(aun.fields.firstaccount, buffer(14,2))
data_subtree:add_le(aun.fields.maxaccounts, buffer(16,2))
data_subtree:add_le(aun.fields.discnumber, buffer(18,1))
return
end
-- &41: Read/write system information
if fs_func== 0x41 then
local subfunc = buffer(13,1):le_uint()
data_subtree:add_le(aun.fields.fs_subfunc41, buffer(13,1))
data_subtree:add_le(aun.fields.data, buffer(14,size-14))
return
end
-- &xx: Unknown file server function
data_subtree:add_le(aun.fields.data, buffer(10,size-10))
return
end
-- Port &9C: Bridge
if port == 0x9C then
pinfo.cols.info:set(aun_ports[port] .. ": " .. aun_bridgetypes[ctrl])
data_subtree:add_le(aun.fields.bridgetype, buffer(2,1))
if ctrl == 0x00 or ctrl == 0x01 or ctrl == 0x02 or ctrl == 0x03 then
data_subtree:add_le(aun.fields.identifier, buffer(8,6))
data_subtree:add_le(aun.fields.replyport, buffer(14,1))
data_subtree:add_le(aun.fields.data, buffer(15,size-15))
return
else
data_subtree:add_le(aun.fields.data, buffer(8,size-8))
return
end
end
-- Port &9E: PrinterServerEnquiryReply
if port == 0x9E then
pinfo.cols.info:set(aun_ports[port])
data_subtree:add_le(aun.fields.printerstatus, buffer(8,1))
data_subtree:add_le(aun.fields.station, buffer(9,1))
data_subtree:add_le(aun.fields.network, buffer(10,1))
data_subtree:add_le(aun.fields.data, buffer(14,size-14))
return
end
-- Port &D2: TCPIPOverEconet
if port == 0xD2 then
pinfo.cols.info:set(aun_ports[port] .. ": " .. aun_tcpiptypes[ctrl])
data_subtree:add_le(aun.fields.tcpiptype, buffer(2,1))
data_subtree:add_le(aun.fields.data, buffer(8,size-8))
return
end
-- Port &xx: Unknown port
data_subtree:add_le(aun.fields.data, buffer(8,size-8))
pinfo.cols.info:set(aun_ports[port])
end
function get_date(value)
local d_year = 1980 + bit.rshift(bit.band(value, 0x00F0), 4)
local d_month = bit.band(value, 0x000F)
local d_day = bit.rshift(bit.band(value, 0xFF00), 8)
return os.date("%d %b %Y", os.time{year=d_year, month=d_month, day=d_day})
end
function get_time(value)
local hour = value(0,1)
local minute = value(1,1)
local second = value(2,1)
return string.format("%i:%i:%i", hour, minute, second)
end
function expand_attributes(attribute)
local attrib_string = ""
if (bit.band(attribute, 0x01)) then
attrib_string = attrib_string .. "R"
end
if (bit.band(attribute, 0x02)) then
attrib_string = attrib_string .. "W"
end
if (bit.band(attribute, 0x04)) then
attrib_string = attrib_string .. "X"
end
if (bit.band(attribute, 0x08)) then
attrib_string = attrib_string .. "L"
end
if (bit.band(attribute, 0x10)) then
attrib_string = attrib_string .. "r"
end
if (bit.band(attribute, 0x20)) then
attrib_string = attrib_string .. "w"
end
if (bit.band(attribute, 0x40)) then
attrib_string = attrib_string .. "x"
end
if (bit.band(attribute, 0x80)) then
attrib_string = attrib_string .. "l"
end
return attrib_string
end
udp_table = DissectorTable.get("udp.port")
udp_table:add(32768,aun)
|
data:extend(
{
{
type = "repair-tool",
name = "multitool-repair-pack",
icon = "__More_Repair_Packs__/graphics/items/Multitool-repair-pack.png",
icon_size = 63,
subgroup = "tool",
order = "e",
speed = 3,
durability = 500,
stack_size = 250
}
}
) |
--[[
* canvas.lua
*
* .
]]
local wx = require("wx")
local trace = require("lib.trace")
local rybclr = require("lib.RYBColours")
local hsl_con = require("lib.hsl")
local _insert = table.insert
local _remove = table.remove
local _wxColour = rybclr.wxColour
local _colours = rybclr.tColours
-- ----------------------------------------------------------------------------
-- attach tracing to the container
--
local m_trace = trace.new("wxHSL")
-------------------------------------------------------------------------------
--
local Canvas = { }
Canvas.__index = Canvas
-- ----------------------------------------------------------------------------
-- list of created panels, allows to match with self in Windows' events
-- tuple { win id, lua self }
-- a list might be an overside structure since this panel is only used once
-- at run-time in this application, but the idea...
--
local m_tPanels = { }
-- ----------------------------------------------------------------------------
-- get the 'self'
--
local function RoutingTable_Get(inWinId)
for _, aSelf in next, m_tPanels do
if aSelf[1] == inWinId then return aSelf[2] end
end
-- this is a serious error
--
return nil
end
-- ----------------------------------------------------------------------------
-- get the 'self'
--
local function RoutingTable_Add(inWinId, inSelf)
if not RoutingTable_Get(inWinId) then
m_tPanels[#m_tPanels + 1] = { inWinId, inSelf }
end
end
-- ----------------------------------------------------------------------------
-- remove link
--
local function RoutingTable_Del(inWinId)
for i, aSelf in next, m_tPanels do
if aSelf[1] == inWinId then _remove(m_tPanels, i) return end
end
end
-- ----------------------------------------------------------------------------
-- constants
--
local m_BoxingX = 10 -- deflate amount for window's client rect
local m_BoxingY = 10 -- " " " " " "
--local m_defFont = "Lucida Console"
-- ----------------------------------------------------------------------------
--
local tDefColours =
{
clrBackground = _colours.Gray50,
clrForeground = _colours.Gray0,
-- clrText = _colours.Blu,
}
-- ----------------------------------------------------------------------------
-- objects factory
--
function Canvas.new()
local t =
{
-- default values
--
hWindow = nil, -- window's handle
iSizeX = 600, -- width of the client area
iSizeY = 400, -- height of the client area
-- deflated coords of window's client rect
rcClip = { left = 0,
top = 0,
right = 0,
bottom = 0,
},
iRasterOp = wx.wxCOPY, -- wx.wxAND_REVERSE,
bRasterOp = false, -- use a raster operation
hBackDc = nil, -- background device context
hForeDc = nil, -- device context for the foreground
tColours = tDefColours,
penDefault = nil,
brushBack = nil, -- brush for background
tObjects = { }, -- list of objects
}
return setmetatable(t, Canvas)
end
-- ----------------------------------------------------------------------------
-- will return the wxWindow handle
--
function Canvas.GetHandle(self)
-- m_trace:line("Canvas.GetHandle")
return self.hWindow
end
-- ----------------------------------------------------------------------------
-- add a shape to the list
--
function Canvas.AddObject(self, inObject)
-- m_trace:line("Canvas.AddObject")
_insert(self.tObjects, inObject)
end
-- ----------------------------------------------------------------------------
--
function Canvas.SetForeColour(self, inColour)
-- m_trace:line("Canvas.SetForeColour")
self.tColours.clrForeground = inColour
self:Refresh()
end
-- ----------------------------------------------------------------------------
--
function Canvas.SetBackColour(self, inColour)
-- m_trace:line("Canvas.SetBackColour")
self.tColours.clrBackground = inColour
self:CreateGDIObjs()
self:Refresh()
end
-- ----------------------------------------------------------------------------
--
function Canvas.CreateGDIObjs(self)
-- m_trace:line("Canvas.CreateGDIObjs")
local tColours = self.tColours
local clrBack = _wxColour(tColours.clrBackground)
local clrFore = _wxColour(tColours.clrForeground)
-- when creating a pen wider than 2 wxWidgets will try to round it
-- thus showing a little line at both ends when set at 3 pixels wide.
-- with CAP_BUTT wxWidgets will square the end
--
self.penDefault = wx.wxPen(clrFore, 1, wx.wxSOLID)
self.penDefault:SetCap(wx.wxCAP_BUTT)
self.brushBack = wx.wxBrush(clrBack, wx.wxSOLID)
end
-- ----------------------------------------------------------------------------
--
function Canvas.NewMemDC(self)
-- m_trace:line("Canvas.NewMemDC")
local iWidth = self.iSizeX
local iHeight = self.iSizeY
-- create a bitmap wide as the client area
--
local memDC = self.hForeDc
if not memDC then
local bitmap = wx.wxBitmap(iWidth, iHeight)
memDC = wx.wxMemoryDC()
memDC:SelectObject(bitmap)
end
-- draw the background
--
if not self.hBackDc then return nil end
memDC:Blit(0, 0, iWidth, iHeight, self.hBackDc, 0, 0, wx.wxCOPY)
-- draw the shapes
--
local oldRaster = memDC:GetLogicalFunction()
if self.bRasterOp then memDC:SetLogicalFunction(self.iRasterOp) end
for _, object in next, self.tObjects do
object:Draw(memDC)
end
if self.bRasterOp then memDC:SetLogicalFunction(oldRaster) end
return memDC
end
-- ----------------------------------------------------------------------------
-- create a legenda and a grid
--
function Canvas.NewBackground(self)
-- m_trace:line("Canvas.NewBackground")
local iWidth = self.iSizeX
local iHeight = self.iSizeY
-- check for valid arguments when creating the bitmap
--
if 0 >= iWidth or 0 >= iHeight then return nil end
-- create a bitmap wide as the client area
--
local memDC = wx.wxMemoryDC()
local bitmap = wx.wxBitmap(iWidth, iHeight)
memDC:SelectObject(bitmap)
-- set the back color
-- (note that Clear uses the background brush for clearing)
--
memDC:SetBackground(self.brushBack)
memDC:Clear()
return memDC
end
-- ----------------------------------------------------------------------------
--
function Canvas.RefreshBackground(self)
-- m_trace:line("Canvas.RefreshBackground")
if self.hBackDc then
self.hBackDc:delete()
self.hBackDc = nil
end
self.hBackDc = self:NewBackground()
end
-- ----------------------------------------------------------------------------
--
function Canvas.RefreshDrawing(self)
-- m_trace:line("Canvas.RefreshDrawing")
if self.hForeDc then
self.hForeDc:delete()
self.hForeDc = nil
end
self.hForeDc = self:NewMemDC()
end
-- ----------------------------------------------------------------------------
--
function Canvas.CreateCanvas(self, inOwner)
-- m_trace:line("Canvas.CreateCanvas")
-- create the panel, derived from wxWindow
-- deriving from wxPanel raises problems on get focus
-- if not using the wxWANTS_CHARS flag won't respond to
-- the wxEVT_KEY_DOWN for the 4 cursor arrows, only the
-- wxEVT_KEY_UP instead, thus using wxWANTS_CHARS is imperative
--
local hWindow = wx.wxWindow(inOwner, wx.wxID_ANY,
wx.wxDefaultPosition,
wx.wxDefaultSize,
wx.wxWANTS_CHARS)
-- responds to events
--
hWindow:Connect(wx.wxEVT_PAINT, Canvas.OnPaint)
hWindow:Connect(wx.wxEVT_SIZE, Canvas.OnSize)
-- hWindow:Connect(wx.wxEVT_MOUSEWHEEL,Canvas.OnMouseWheel)
-- hWindow:Connect(wx.wxEVT_KEY_UP, Canvas.OnKeyUp)
-- hWindow:Connect(wx.wxEVT_KEY_DOWN, Canvas.OnKeyDown)
hWindow:Connect(wx.wxEVT_LEFT_UP, Canvas.OnLeftBtnUp)
hWindow:Connect(wx.wxEVT_RIGHT_UP, Canvas.OnRightBtnUp)
-- this is necessary to avoid flickering
-- wxBG_STYLE_CUSTOM deprecated use wxBG_STYLE_PAINT
--
hWindow:SetBackgroundStyle(wx.wxBG_STYLE_PAINT)
-- set not using wxBufferedDC anyway
-- (shouldn't be needed though)
--
hWindow:SetDoubleBuffered(false)
-- store interesting members
--
self.hWindow = hWindow
-- add object window to list of objects
--
RoutingTable_Add(hWindow:GetId(), self)
-- create the permanent GDI objects with some defaults
--
self:CreateGDIObjs()
return true
end
-- ----------------------------------------------------------------------------
--
function Canvas.Refresh(self)
-- m_trace:line("Canvas.Refresh")
self:RefreshBackground()
self:RefreshDrawing()
-- call Invalidate
--
local hWindow = self.hWindow
if hWindow then hWindow:Refresh(true) end
end
-- ----------------------------------------------------------------------------
--
function Canvas.OnClose(event)
-- m_trace:line("Canvas.OnClose")
-- simply remove from windows' list
--
RoutingTable_Del(event:GetId())
end
-- ----------------------------------------------------------------------------
--
function Canvas.OnPaint(event)
-- m_trace:line("Canvas.OnPaint")
local aSelf = RoutingTable_Get(event:GetId())
local winDc = wx.wxPaintDC(aSelf.hWindow)
winDc:Blit(0, 0, aSelf.iSizeX, aSelf.iSizeY, aSelf.hForeDc, 0, 0, wx.wxCOPY)
winDc:delete()
end
-- ----------------------------------------------------------------------------
--
function Canvas.OnSize(event)
-- m_trace:line("Canvas.OnSize")
local size = event:GetSize()
local aSelf = RoutingTable_Get(event:GetId())
local rcClip = aSelf.rcClip
aSelf.iSizeX = size:GetWidth()
aSelf.iSizeY = size:GetHeight()
rcClip.left = m_BoxingX / 2
rcClip.top = m_BoxingY / 2
rcClip.right = aSelf.iSizeX - m_BoxingX / 2
rcClip.bottom= aSelf.iSizeY - m_BoxingY / 2
aSelf.rcClip = rcClip
aSelf:Refresh()
end
-- ----------------------------------------------------------------------------
-- handle the mouse wheel, modify the zoom factor
-- if key press CTRL then handles the X otherwise the Y
--
function Canvas.OnMouseWheel(event)
-- m_trace:line("Canvas.OnMouseWheel")
local aSelf = RoutingTable_Get(event:GetId())
-- Update display
--
-- aSelf:Refresh()
end
-- ----------------------------------------------------------------------------
-- handle drawing's options from keyboard
--
function Canvas.OnKeyUp(event)
-- m_trace:line("Canvas.OnKeyUp")
local aSelf = RoutingTable_Get(event:GetId())
local key = event:GetKeyCode() - 48
local bRefresh = false
-- Update display
--
-- if bRefresh then aSelf:Refresh() end
end
-- ----------------------------------------------------------------------------
--
function Canvas.OnKeyDown(event)
-- m_trace:line("Canvas.OnKeyDown")
local aSelf = RoutingTable_Get(event:GetId())
local key = event:GetKeyCode()
local bAlt = event:AltDown()
-- Update display
--
-- aSelf:Refresh()
end
-- ----------------------------------------------------------------------------
-- get the object that the user clicked in
--
function Canvas.ColorFromPoint(self, event)
-- m_trace:line("Canvas.ColorFromPoint")
local iPtX, iPtY = event:GetLogicalPosition(self.hForeDc):GetXY()
for _, object in next, self.tObjects do
local iIndex, aColour = object:HitTest({iPtX, iPtY})
if 0 < iIndex and aColour then return aColour, object.sFunction end
end
return nil
end
-- ----------------------------------------------------------------------------
-- change the current color if clicked object
--
function Canvas.OnLeftBtnUp(event)
-- m_trace:line("Canvas.OnLeftBtnUp")
local aSelf = RoutingTable_Get(event:GetId())
local aColour, sFunction = aSelf:ColorFromPoint(event)
if aColour then
_G.m_App.ForeColourChanged(aColour, sFunction)
end
end
-- ----------------------------------------------------------------------------
-- change the current color if clicked object
--
function Canvas.OnRightBtnUp(event)
-- m_trace:line("Canvas.OnRightBtnUp")
local aSelf = RoutingTable_Get(event:GetId())
local aColour, sFunction = aSelf:ColorFromPoint(event)
if aColour then
_G.m_App.BackColourChanged(aColour, sFunction)
end
end
-- ----------------------------------------------------------------------------
--
return Canvas
-- ----------------------------------------------------------------------------
-- ----------------------------------------------------------------------------
|
-- Disk Drive
local function get_formspec()
return "size[8,8.5]"..
default.gui_bg..
default.gui_bg_img..
default.gui_slots..
"label[0,0;Disk Drive]"..
"list[context;main;1,1;6,1;]"..
"list[current_player;main;0,4.25;8,1;]"..
"list[current_player;main;0,5.5;8,3;8]"..
"listring[context;main]"..
"listring[current_player;main]"..
default.get_hotbar_bg(0, 4.25)
end
local function count_inv(inv)
local count = 0
for _,stack in pairs(inv:get_list("main")) do
if not stack:is_empty() then
count = count + 1
end
end
return count
end
local function timer(pos, elapsed)
local refresh = false
local meta = minetest.get_meta(pos)
local node = minetest.get_node(pos)
local inv = meta:get_inventory()
local count = count_inv(inv)
local cnname = minetest.registered_nodes[node.name]["_basename"]
node.name = cnname..count
holostorage.helpers.swap_node(pos, node)
return refresh
end
local function allow_metadata_inventory_put (pos, listname, index, stack, player)
if minetest.is_protected(pos, player:get_player_name()) then
return 0
end
if not holostorage.disks.is_valid_disk(stack) then
return 0
end
return stack:get_count()
end
local function allow_metadata_inventory_move (pos, from_list, from_index, to_list, to_index, count, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local stack = inv:get_stack(from_list, from_index)
return allow_metadata_inventory_put(pos, to_list, to_index, stack, player)
end
local function allow_metadata_inventory_take (pos, listname, index, stack, player)
if minetest.is_protected(pos, player:get_player_name()) then
return 0
end
return stack:get_count()
end
local function sort_by_stack_name( ... )
-- body
end
local function register_disk_drive(index)
local groups = {
cracky = 1,
holostorage_distributor = 1,
holostorage_device = 1,
holostorage_storage = 1,
disk_drive = 1,
}
local driveoverlay = ""
if index ~= 0 then
groups["not_in_creative_inventory"] = 1
driveoverlay = "^holostorage_drive_section"..index..".png"
end
minetest.register_node("holostorage:disk_drive"..index, {
description = "Disk Drive",
tiles = {
"holostorage_drive_side.png", "holostorage_drive_side.png", "holostorage_drive_side.png",
"holostorage_drive_side.png", "holostorage_drive_side.png", "holostorage_drive.png"..driveoverlay,
},
drop = "holostorage:disk_drive0",
_basename = "holostorage:disk_drive",
paramtype2 = "facedir",
on_timer = timer,
groups = groups,
on_construct = function (pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", get_formspec())
local inv = meta:get_inventory()
inv:set_size("main", 6)
holostorage.network.clear_networks(pos)
end,
after_dig_node = holostorage.network.clear_networks,
allow_metadata_inventory_put = allow_metadata_inventory_put,
allow_metadata_inventory_take = allow_metadata_inventory_take,
allow_metadata_inventory_move = allow_metadata_inventory_move,
on_metadata_inventory_move = function(pos)
minetest.get_node_timer(pos):start(0.02)
end,
on_metadata_inventory_put = function(pos, listname, index, stack, player)
stack = holostorage.server_inventory.ensure_disk_inventory(stack, minetest.pos_to_string(pos))
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
inv:set_stack(listname, index, stack)
minetest.get_node_timer(pos):start(0.02)
end,
on_metadata_inventory_take = function(pos)
minetest.get_node_timer(pos):start(0.02)
end,
})
holostorage.devices["holostorage:disk_drive"..index] = true
end
-- Register 6 variants of the disk drive.
for i = 0, 6 do
register_disk_drive(i)
end
-- Create ABM for syncing disks
minetest.register_abm({
label = "Storage Disk Synchronization",
nodenames = {"group:disk_drive"},
neighbors = {"group:holostorage_distributor"},
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local disks = inv:get_list("main")
for _,stack in pairs(disks) do
local meta = stack:get_meta()
local tag = meta:get_string("storage_tag")
if tag and tag ~= "" then
if not holostorage.server_inventory.cache[tag] then
print("loading drive",tag)
holostorage.server_inventory.load_disk_from_file(stack, tag)
end
end
end
end
})
|
function getAdmins()
local players = exports.pool:getPoolElementsByType("player")
local admins = { }
local count = 1
for key, value in ipairs(players) do
if isPlayerAdmin(value) then
admins[count] = value
count = count + 1
end
end
return admins
end
function isPlayerAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 1
end
function isPlayerFullAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 2
end
function isPlayerSuperAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 3
end
function isPlayerHeadAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 5
end
function isPlayerLeadAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 4
end
function getPlayerAdminLevel(thePlayer)
return isElement( thePlayer ) and tonumber(getElementData(thePlayer, "adminlevel")) or 0
end
local titles = { "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" }
function getPlayerAdminTitle(thePlayer)
local text = titles[getPlayerAdminLevel(thePlayer)] or "Player"
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0
if (hiddenAdmin==1) then
text = text .. " (Hidden)"
end
return text
end
-- Do not even think of adding your own name here unless you made a couple of recent commits.
local scripterAccounts = {
Daniels = true,
mabako = true,
Mount = true
}
function isPlayerScripter(thePlayer)
return getElementType(thePlayer) == "console" or isPlayerHeadAdmin(thePlayer) or scripterAccounts[getElementData(thePlayer, "gameaccountusername")]
end
|
local ESX = nil
local timePlay = {}
local NewPlayers = {}
-- ESX
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
AddEventHandler('esx:playerLoaded', function(source)
local _source = source
local identifier = GetPlayerIdentifier(_source)
timePlay[identifier] = {source = _source, joinTime = os.time(), timePlay = 0}
MySQL.Async.fetchAll("SELECT timePlay FROM users WHERE identifier = @identifier", { ["@identifier"] = identifier }, function(result)
if result then
local timePlayP = result[1].timePlay
timePlay[identifier].timePlay = timePlayP
if timePlayP < Config.newbieTime then
NewPlayers[identifier] = {source = _source}
end
TriggerClientEvent('timeplay:set_tags', -1, NewPlayers)
end
end)
end)
AddEventHandler('playerDropped', function()
local _source = source
if _source ~= nil then
local identifier = GetPlayerIdentifier(_source)
if timePlay[identifier] ~= nil then
local leaveTime = os.time()
local saveTime = leaveTime - timePlay[identifier].joinTime
MySQL.Async.execute('UPDATE users SET timePlay = timePlay + @timePlay WHERE identifier=@identifier',
{
['@identifier'] = identifier,
['@timePlay'] = saveTime
}, function()
timePlay[identifier] = nil
NewPlayers[identifier] = nil
TriggerClientEvent('timeplay:set_tags', -1, NewPlayers)
end)
end
end
end) |
print(string.byte("G")) |
--[[
Project TkJson-Lua
Author T1nKeR
File TkJson.lua
Description
A simple JSON library that decodes a JSON string or encodes a Lua value.
--]]
local TkJson = {}
TkJson.ErrorCode = {
Ok = 'Decode successfully',
ExpectValue = 'Expect a value',
InvalidValue = 'Invalid value',
RootNotSingular = 'Root not singular',
NumberTooBig = 'Number too big',
MissQuotationMark = 'Miss quotation mark',
InvalidStringEscape = 'Invalid string escape',
InvalidStringChar = 'Invalid string char',
InvalidUnicodeHex = 'Invalid unicode hex',
InvalidUnicodeSurrogate = 'Invalid unicode surrogate',
MissCommaOrSquareBracket = 'Miss comma or square bracket',
MissKey = 'Miss key in key-value pair',
MissColon = 'Miss colon',
MissCommaOrCurlyBracket = 'Miss comma or curly bracket'
}
TkJson.null = {}
setmetatable(TkJson.null, {
__newindex = function(dict, key, value)
error('> Error: TkJson.null is immutable!')
end,
__tostring = function()
return 'null'
end
})
local g_iterator = nil
local g_next_char = nil
local g_pointer = nil
local g_json_string = nil
local Decode
local DecodeError
local DecodeWhitespace
local DecodeValue
local DecodeNull
local DecodeTrue
local DecodeFalse
local DecodeNumber
local DecodeUnicode
local DecodeString
function DecodeError(error_code)
local row_number = 1
local col_number = 1
-- local iterator = string.gmatch(g_json_string, '.')
-- local next_char = iterator()
-- local pointer = 1
-- while pointer < g_pointer do
-- pointer = pointer + 1
-- next_char = iterator()
-- if next_char == '\n' then
-- row_number = row_number + 1
-- col_number = 1
-- else
-- col_number = col_number + 1
-- end
-- end
for i = 1, g_pointer - 1 do
if string.byte(g_json_string, i) == 10 then
row_number = row_number + 1
col_number = 1
else
col_number = col_number + 1
end
end
local error_msg = string.format(
'> Error: Line %d Column %d - %s',
row_number, col_number, error_code
)
error(error_msg, 0)
end
local whitespace_char = {
[' '] = true, ['\t'] = true,
['\n'] = true, ['\r'] = true
}
function DecodeWhitespace()
while whitespace_char[g_next_char] do
g_pointer = g_pointer + 1
g_next_char = g_iterator()
end
end
local null_char = {
'n', 'u', 'l', 'l'
}
function DecodeNull()
for i = 1, 4 do
if g_next_char ~= null_char[i] then
DecodeError(TkJson.ErrorCode.InvalidValue)
end
g_pointer = g_pointer + 1
g_next_char = g_iterator()
end
return TkJson.null
end
local true_char = {
't', 'r', 'u', 'e'
}
function DecodeTrue()
for i = 1, 4 do
if g_next_char ~= true_char[i] then
DecodeError(TkJson.ErrorCode.InvalidValue)
end
g_pointer = g_pointer + 1
g_next_char = g_iterator()
end
return true
end
local false_char = {
'f', 'a', 'l', 's', 'e'
}
function DecodeFalse()
for i = 1, 5 do
if g_next_char ~= false_char[i] then
DecodeError(TkJson.ErrorCode.InvalidValue)
end
g_pointer = g_pointer + 1
g_next_char = g_iterator()
end
return false
end
local number_char = {
['0'] = true, ['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true,
['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true,
['+'] = true, ['-'] = true, ['.'] = true, ['e'] = true, ['E'] = true
}
function DecodeNumber()
local start_point = g_pointer
while number_char[g_next_char] do
g_pointer = g_pointer + 1
g_next_char = g_iterator()
end
local stop_point = g_pointer - 1
local value = tonumber(string.sub(g_json_string, start_point, stop_point))
if value == nil then
DecodeError(TkJson.ErrorCode.InvalidValue)
elseif value == math.huge or value == -math.huge then
DecodeError(TkJson.ErrorCode.NumberTooBig)
else
return value
end
end
function DecodeUnicode(utf8_string)
local hex1 = tonumber(string.sub(utf8_string, 3, 6), 16)
local hex2 = tonumber(string.sub(utf8_string, 9, 12), 16)
if hex2 then
hex1 = (((hex1 - 0xD800) << 10) | (hex2 - 0xDC00)) + 0x10000
end
if hex1 <= 0x7F then
return string.char(hex1 & 0xFF)
elseif hex1 <= 0x7FF then
return string.char(
(0xC0 | ((hex1 >> 6) & 0xFF)),
(0x80 | (hex1 & 0x3F))
)
elseif hex1 <= 0xFFFF then
return string.char(
(0xE0 | ((hex1 >> 12) & 0xFF)),
(0x80 | ((hex1 >> 6) & 0x3F)),
(0x80 | (hex1 & 0x3F))
)
else
return string.char(
(0xF0 | ((hex1 >> 18) & 0xFF)),
(0x80 | ((hex1 >> 12) & 0x3F)),
(0x80 | ((hex1 >> 6) & 0x3F)),
(0x80 | (hex1 & 0x3F))
)
end
end
local escape_char = {
['"'] = true, ['\\'] = true, ['/'] = true,
['b'] = true, ['f'] = true, ['n'] = true,
['r'] = true, ['t'] = true
}
local escape_value = {
['\\\"'] = '\"', ['\\\\'] = '\\', ['\\/'] = '/',
['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n',
['\\r'] = '\r', ['\\t'] = '\t'
}
function DecodeString()
local value = ''
local start_point = g_pointer + 1
local stop_point = g_pointer + 1
local has_surrogate = false
local has_unicode = false
local has_escape = false
while true do
g_pointer = g_pointer + 1
g_next_char = g_iterator()
if g_next_char == '"' then
stop_point = g_pointer - 1
value = string.sub(g_json_string, start_point, stop_point)
if string.find(value, '[\x01-\x1F]') then
DecodeError(TkJson.ErrorCode.InvalidStringChar)
end
if has_surrogate then
value = string.gsub(value, '\\u[dD][89AaBb]..\\u....', DecodeUnicode)
end
if has_unicode then
value = string.gsub(value, '\\u....', DecodeUnicode)
end
if has_escape then
value = string.gsub(value, '\\.', escape_value)
end
g_pointer = g_pointer + 1
g_next_char = g_iterator()
return value
elseif g_next_char == '\\' then
g_pointer = g_pointer + 1
g_next_char = g_iterator()
if g_next_char == 'u' then
local hex_string = string.sub(g_json_string, g_pointer + 1, g_pointer + 4)
if not string.find(hex_string, '%x%x%x%x') then
DecodeError(TkJson.ErrorCode.InvalidUnicodeHex)
end
if string.find(hex_string, '^[Dd][89AaBb]') then
has_surrogate = true
for i = 1, 10 do
g_pointer = g_pointer + 1
g_next_char = g_iterator()
end
else
has_unicode = true
for i = 1, 4 do
g_pointer = g_pointer + 1
g_next_char = g_iterator()
end
end
else
if not escape_char[g_next_char] then
DecodeError(TkJson.ErrorCode.InvalidStringEscape)
else
has_escape = true
end
end
else
if g_next_char == nil then
DecodeError(TkJson.ErrorCode.MissQuotationMark)
end
end
end
end
DecodeArray = function()
local value = {
__length = 0
}
local length = 0
g_pointer = g_pointer + 1
g_next_char = g_iterator()
DecodeWhitespace()
if g_next_char == ']' then
g_pointer = g_pointer + 1
g_next_char = g_iterator()
return value
end
while true do
local element = nil
element = DecodeValue()
length = length + 1
value[length] = element
DecodeWhitespace()
if g_next_char == ',' then
g_pointer = g_pointer + 1
g_next_char = g_iterator()
DecodeWhitespace()
elseif g_next_char == ']' then
value.__length = length
g_pointer = g_pointer + 1
g_next_char = g_iterator()
return value
else
DecodeError(TkJson.ErrorCode.MissCommaOrSquareBracket)
end
end
end
decodeObject = function()
local value = {}
g_pointer = g_pointer + 1
g_next_char = g_iterator()
DecodeWhitespace()
if g_next_char == '}' then
g_pointer = g_pointer + 1
g_next_char = g_iterator()
return value
end
while true do
local key = nil
local element = nil
if g_next_char ~= '"' then
DecodeError(TkJson.ErrorCode.MissKey)
end
key = DecodeString()
DecodeWhitespace()
if g_next_char ~= ':' then
DecodeError(TkJson.ErrorCode.MissColon)
end
g_pointer = g_pointer + 1
g_next_char = g_iterator()
DecodeWhitespace()
element = DecodeValue()
value[key] = element
DecodeWhitespace()
if g_next_char == ',' then
g_pointer = g_pointer + 1
g_next_char = g_iterator()
DecodeWhitespace()
elseif g_next_char == '}' then
g_pointer = g_pointer + 1
g_next_char = g_iterator()
return value
else
DecodeError(TkJson.ErrorCode.MissCommaOrCurlyBracket)
end
end
end
local value_char = {
['n'] = DecodeNull, ['t'] = DecodeTrue, ['f'] = DecodeFalse,
['"'] = DecodeString, ['['] = DecodeArray, ['{'] = decodeObject,
['-'] = DecodeNumber, ['0'] = DecodeNumber, ['1'] = DecodeNumber,
['2'] = DecodeNumber, ['3'] = DecodeNumber, ['4'] = DecodeNumber,
['5'] = DecodeNumber, ['6'] = DecodeNumber, ['7'] = DecodeNumber,
['8'] = DecodeNumber, ['9'] = DecodeNumber
}
function DecodeValue()
if value_char[g_next_char] then
local decode_function = value_char[g_next_char]
return decode_function()
else
if g_next_char then
DecodeError(TkJson.ErrorCode.InvalidValue)
else
DecodeError(TkJson.ErrorCode.ExpectValue)
end
end
end
function Decode(json_string)
local value = nil
g_json_string = json_string
g_iterator = string.gmatch(g_json_string, '.')
g_next_char = g_iterator()
g_pointer = 1
DecodeWhitespace()
value = DecodeValue()
DecodeWhitespace()
if g_next_char ~= nil then
DecodeError(TkJson.ErrorCode.RootNotSingular)
end
return value
end
TkJson.Decode = Decode
return TkJson |
local ActiveRecord = require('arken.ActiveRecord')
local test = {}
test.before = function()
ActiveRecord.reset()
ActiveRecord.config = "config/active_record_sqlite.json"
end
test.after = function()
ActiveRecord.config = nil
end
test.should_execute_commit_after_begin = function()
ActiveRecord.begin()
ActiveRecord.commit()
end
test.should_error_if_not_begin = function()
local status, message = pcall(ActiveRecord.commit)
assert(status == false)
assert(message:contains('cannot commit - no transaction is active'), message)
end
return test
|
if not global.cch then global.cch = {} end
function home_cmd(player, args)
if not global.cch[player.name] then global.cch[player.name] = {} end
if #args == 0 then
player.print("Please specify a home")
elseif #args == 1 then
if global.cch[player.name][args[1]] then
local home = global.cch[player.name][args[1]]
if not home.surface then
global.cch[player.name][args[1]] = {position = home, surface = game.surfaces["nauvis"]}
home = global.cch[player.name][args[1]]
end
local offset = home.surface.find_non_colliding_position(game.entity_prototypes["player"].name, home.position, 5.0, 0.5)
if offset then
player.teleport(offset, home.surface)
else
player.print("Home is covered by something!")
end
else
player.print(args[1] .. " does not exist yet!")
end
else
player.print("Too many arguments!")
end
end
function list_cmd(player, args)
if not global.cch[player.name] then global.cch[player.name] = {} end
if #args > 0 then
player.print("Too many arguments!")
return
end
local msg = "Your Homes: "
local homes = global.cch[player.name]
if homes then
for k,v in pairs(homes) do
msg = msg .. k .. ", "
end
else
msg = "You have no homes!"
end
player.print(msg)
end
function set_cmd(player, args)
if not global.cch[player.name] then global.cch[player.name] = {} end
if #args == 0 then
player.print("You must name this home before it can be set!")
return
elseif #args == 1 then
if global.cch[player.name][args[1]] then
player.print("This home exists already, to reset this home use '-r' as a second argument")
else
if not (args[1] == "-r") then
global.cch[player.name][args[1]] = {position = player.position, surface = player.surface}
player.print("Successfully set " .. args[1])
else
player.print("Cannot name a home '-r' as it is a reserved keyword!")
end
end
elseif #args == 2 then
if args[2] == "-r" then
global.cch[player.name][args[1]] = {position = player.position, surface = player.surface}
player.print("Successfully reset " .. args[1])
else
player.print("Too many arguments!")
end
elseif #args > 2 then
player.print("Too many arguments!")
end
end
function remove_cmd(player, args)
if not global.cch[player.name] then global.cch[player.name] = {} end
if args == 0 then
player.print("You must specify a home!")
return
elseif #args == 1 then
if not global.cch[player.name][args[1]] then
player.print("This home does not exist!")
else
global.cch[player.name][args[1]] = nil
player.print("Successfully removed " .. args[1])
end
else
player.print("Too many arguments!")
end
end
script.on_event(defines.events.on_player_joined_game, function(event)
local player = game.players[event.player_index]
if not global.cch[player.name] then global.cch[player.name] = {} end
end)
remote.add_interface("cc_homes", {home = home_cmd, list = list_cmd, set = set_cmd, remove = remove_cmd})
function desc()
local tble = {
cc_homes = {
{
command = "home",
description = "Teleport to a home"
},
{
command = "list",
description = "List all your homes"
},
{
command = "set",
description = "Set/reset a home"
},
{
command = "remove",
description = "Remove a home"
}
}
}
return tble
end
remote.add_interface("ccd_homes", {descriptions = desc}) |
local Path = require('plenary.path')
local M = {}
local function merge_table_impl(t1, t2)
for k, v in pairs(t2) do
if type(v) == 'table' then
if type(t1[k]) == 'table' then
merge_table_impl(t1[k], v)
else
t1[k] = v
end
else
t1[k] = v
end
end
end
M.merge_tables = function(...)
local out = {}
for i = 1, select('#', ...) do
merge_table_impl(out, select(i, ...))
end
return out
end
M.normalize_path = function(item)
return Path:new(item):make_relative(vim.loop.cwd())
end
-- This should only set up folder for finder marks.
M.ensure_correct_config = function(config)
local projects = config.projects
if projects[vim.loop.cwd()] == nil then
projects[vim.loop.cwd()] = {
mark = {
marks = {},
},
term = {
cmds = {},
},
finder = {
marks = { _c = {}, max = 0 },
},
}
end
local proj = projects[vim.loop.cwd()]
if proj.finder == nil then
proj.finder = { marks = { _c = {}, max = 0 } }
end
return config
end
return M
|
local base = {
_0 = '#1B2B34';
_1 = '#343D46';
_2 = '#4F5B66';
_3 = '#65737E';
_4 = '#A7ADBA';
_5 = '#C0C5CE';
_6 = '#CDD3DE';
_7 = '#D8DEE9';
_8 = '#EC5f67';
_9 = '#F99157';
_A = '#FAC863';
_B = '#99C794';
_C = '#5FB3B3';
_D = '#6699CC';
_E = '#C594C5';
_F = '#AB7967';
}
local white = '#FFFFFF'
local none = 'none'
local italic = 'italic'
local bold = 'bold'
local undercurl = 'undercurl'
local underline = 'underline'
local syntax = {
Bold = {attr=bold};
Italic = {attr=italic};
Debug = {fg=base._8};
Directory = {fg=base._D};
ErrorMsg = {fg=base._8, bg=base._0};
Exception = {fg=base._8};
FoldColumn = {fg=base._D, bg=base._0};
Folded = {fg=base._3, bg=base._1, attr=italic};
IncSearch = {fg=base._1, bg=base._9, attr=none};
Macro = {fg=base._8};
MatchParen = {fg=base._7, bg=base._2};
ModeMsg = {fg=base._B};
MoreMsg = {fg=base._B};
Question = {fg=base._D};
Search = {fg=base._3, bg=base._A};
SpecialKey = {fg=base._3};
TooLong = {fg=base._8};
Underlined = {fg=base._8};
Visual = {bg=base._2};
VisualNOS = {fg=base._8};
WarningMsg = {fg=base._8};
WildMenu = {fg=base._0, bg=base._D, attr=bold};
Title = {fg=base._D};
Conceal = {fg=base._D, bg=base._0};
Cursor = {fg=base._0, bg=base._5};
CursorColumn = {bg=base._1};
CursorLine = {bg=base._1, attr=none};
CursorLineNr = {fg=base._3, bg=base._1};
TermCursor = {fg=base._0, bg=base._5, attr=none};
TermCursorNC = {fg=base._0, bg=base._5};
NonText = {fg=base._3};
Normal = {fg=base._7, bg=base._0};
EndOfBuffer = {fg=base._5, bg=base._0};
LineNr = {fg=base._3, bg=base._0};
SignColumn = {fg=base._0, bg=base._0};
StatusLine = {fg=base._1, bg=base._3};
StatusLineNC = {fg=base._3, bg=base._1};
VertSplit = {fg=base._0, bg=base._2};
ColorColumn = {bg=base._1};
PMenu = {fg=base._4, bg=base._1};
PMenuSel = {fg=base._7, bg=base._D};
PmenuSbar = {bg=base._2};
PmenuThumb = {bg=base._7};
TabLine = {fg=base._3, bg=base._1};
TabLineFill = {fg=base._3, bg=base._1};
TabLineSel = {fg=base._B, bg=base._1};
helpExample = {fg=base._A};
helpCommand = {fg=base._A};
Boolean = {fg=base._9};
Character = {fg=base._8};
Comment = {fg=base._3, attr=italic};
Conditional = {fg=base._E};
Constant = {fg=base._9};
Define = {fg=base._E};
Delimiter = {fg=base._F};
Float = {fg=base._9};
Function = {fg=base._D};
Identifier = {fg=base._C};
Include = {fg=base._D};
Keyword = {fg=base._E};
Label = {fg=base._A};
Number = {fg=base._9};
Operator = {fg=base._5};
PreProc = {fg=base._A};
Repeat = {fg=base._A};
Special = {fg=base._C};
SpecialChar = {fg=base._F};
Statement = {fg=base._8};
StorageClass = {fg=base._A};
String = {fg=base._B};
Structure = {fg=base._E};
Tag = {fg=base._A};
Todo = {fg=base._A, bg=base._1};
Type = {fg=base._A};
Typedef = {fg=base._A};
DiagnosticError = {fg=base._8};
DiagnosticWarn = {fg=base._A};
DiagnosticInfo = {fg=base._D};
DiagnosticHint = {fg=base._C};
DiagnosticUnderlineError = {attr=underline};
DiagnosticUnderlineWarn = {attr=underline};
DiagnosticUnderlineInfo = {attr=underline};
DiagnosticUnderlineHint = {attr=underline};
TSInclude = {fg=base._C};
TSPunctBracket = {fg=base._C};
TSPunctDelimiter = {fg=base._7};
TSParameter = {fg=base._7};
TSType = {fg=base._D};
TSFunction = {fg=base._C};
TSTagDelimiter = {fg=base._C};
TSProperty = {fg=base._A};
TSMethod = {fg=base._D};
TSParameter = {fg=base._A};
TSConstructor = {fg=base._7};
TSVariable = {fg=base._7};
TSOperator = {fg=base._7};
TSTag = {fg=base._7};
TSKeyword = {fg=base._E};
TSKeywordOperator = {fg=base._E};
TSVariableBuiltin = {fg=base._8};
TSLabel = {fg=base._C};
SpellBad = {attr=undercurl};
SpellLocal = {attr=undercurl};
SpellCap = {attr=undercurl};
SpellRare = {attr=undercurl};
csClass = {fg=base._A};
csAttribute = {fg=base._A};
csModifier = {fg=base._E};
csType = {fg=base._8};
csUnspecifiedStatement = {fg=base._D};
csContextualStatement = {fg=base._E};
csNewDecleration = {fg=base._8};
cOperator = {fg=base._C};
cPreCondit = {fg=base._E};
cssColor = {fg=base._C};
cssBraces = {fg=base._5};
cssClassName = {fg=base._E};
-- builtins
DiffAdd = {fg=base._B, bg=none};
DiffChange = {fg=base._D, bg=none};
DiffDelete = {fg=base._8, bg=none};
DiffText = {fg=base._D, bg=base._0, attr=bold};
DiffAdded = {fg=base._0, bg=base._B, attr=bold};
DiffFile = {fg=base._8, bg=base._0};
DiffNewFile = {fg=base._B, bg=base._0};
DiffLine = {fg=base._D, bg=base._0};
DiffRemoved = {fg=base._0, bg=base._8, attr=bold};
gitCommitOverflow = {fg=base._8};
gitCommitSummary = {fg=base._B};
htmlBold = {fg=base._A};
htmlItalic = {fg=base._E};
htmlTag = {fg=base._C};
htmlEndTag = {fg=base._C};
htmlArg = {fg=base._A};
htmlTagName = {fg=base._7};
javaScript = {fg=base._5};
javaScriptNumber = {fg=base._9};
javaScriptBraces = {fg=base._5};
jsonKeyword = {fg=base._B};
jsonQuote = {fg=base._B};
markdownCode = {fg=base._B};
markdownCodeBlock = {fg=base._B};
markdownHeadingDelimiter = {fg=base._D};
markdownItalic = {fg=base._E, attr=italic};
markdownBold = {fg=base._A, attr=bold};
markdownCodeDelimiter = {fg=base._F, attr=italic};
markdownError = {fg=base._5, bg=base._0};
typescriptParens = {fg=base._5, bg=none};
NeomakeErrorSign = {fg=base._8, bg=base._0};
NeomakeWarningSign = {fg=base._A, bg=base._0};
NeomakeInfoSign = {fg=white, bg=base._0};
NeomakeError = {fg=base._8, attr=underline, attrsp=base._8};
NeomakeWarning = {fg=base._8, attr=underline, attrsp=base._8};
ALEErrorSign = {fg=base._8, bg=base._0, attr=bold};
ALEWarningSign = {fg=base._A, bg=base._0, attr=bold};
ALEInfoSign = {fg=white, bg=base._0, attr=bold};
NERDTreeExecFile = {fg=base._5};
NERDTreeDirSlash = {fg=base._D};
NERDTreeOpenable = {fg=base._D};
NERDTreeFile = {bg=none};
NERDTreeFlags = {fg=base._D};
phpComparison = {fg=base._5};
phpParent = {fg=base._5};
phpMemberSelector = {fg=base._5};
pythonRepeat = {fg=base._E};
pythonOperator = {fg=base._E};
rubyConstant = {fg=base._A};
rubySymbol = {fg=base._B};
rubyAttribute = {fg=base._D};
rubyInterpolation = {fg=base._B};
rubyInterpolationDelimiter = {fg=base._F};
rubyStringDelimiter = {fg=base._B};
rubyRegexp = {fg=base._C};
sassidChar = {fg=base._8};
sassClassChar = {fg=base._9};
sassInclude = {fg=base._E};
sassMixing = {fg=base._E};
sassMixinName = {fg=base._D};
vimfilerLeaf = {fg=base._5};
vimfilerNormalFile = {fg=base._5, bg=base._0};
vimfilerOpenedFile = {fg=base._D};
vimfilerClosedFile = {fg=base._D};
GitGutterAdd = {fg=base._B, bg=base._0, attr=bold};
GitGutterChange = {fg=base._D, bg=base._0, attr=bold};
GitGutterDelete = {fg=base._8, bg=base._0, attr=bold};
GitGutterChangeDelete = {fg=base._E, bg=base._0, attr=bold};
SignifySignAdd = {fg=base._B, bg=base._0, attr=bold};
SignifySignChange = {fg=base._D, bg=base._0, attr=bold};
SignifySignDelete = {fg=base._8, bg=base._0, attr=bold};
SignifySignChangeDelete = {fg=base._E, bg=base._0, attr=bold};
SignifySignDeleteFirstLine = {fg=base._8, bg=base._0, attr=bold};
xmlTag = {fg=base._C};
xmlTagName = {fg=base._5};
xmlEndTag = {fg=base._C};
Defx_filename_directory = {fg=base._D};
CocErrorSign = {fg=base._8};
CocWarningSign = {fg=base._A};
CocInfoSign = {fg=base._D};
CocHintSign = {fg=base._C};
CocErrorFloat = {fg=base._8};
CocWarningFloat = {fg=base._A};
CocInfoFloat = {fg=base._D};
CocHintFloat = {fg=base._C};
CocDiagnosticsError = {fg=base._8};
CocDiagnosticsWarning = {fg=base._A};
CocDiagnosticsInfo = {fg=base._D};
CocDiagnosticsHint = {fg=base._C};
CocSelectedText = {fg=base._E};
CocCodeLens = {fg=base._4};
}
vim.g.terminal_color_0 = base._0
vim.g.terminal_color_1 = base._8
vim.g.terminal_color_2 = base._B
vim.g.terminal_color_3 = base._A
vim.g.terminal_color_4 = base._D
vim.g.terminal_color_5 = base._E
vim.g.terminal_color_6 = base._C
vim.g.terminal_color_7 = base._5
vim.g.terminal_color_8 = base._3
vim.g.terminal_color_9 = base._8
vim.g.terminal_color_10 = base._B
vim.g.terminal_color_11 = base._A
vim.g.terminal_color_12 = base._D
vim.g.terminal_color_13 = base._E
vim.g.terminal_color_14 = base._C
vim.g.terminal_color_15 = base._5
vim.g.terminal_color_background = base._0
vim.g.terminal_color_foreground = white
vim.cmd('highlight clear')
if vim.fn.exists('syntax_on') then
vim.cmd('syntax reset')
end
vim.opt.background = 'dark'
vim.opt.termguicolors = true
vim.g.colors_name = 'OceanicNext'
function format(prefix, attribute)
if attribute then
return prefix .. attribute .. ' '
end
return ''
end
for group, colour in pairs(syntax) do
vim.api.nvim_command(
'highlight ' .. group .. ' '
.. format('guifg=', colour.fg)
.. format('guibg=', colour.bg)
.. format('gui=', colour.attr)
.. format('guisp=', colour.attrsp)
)
end
vim.cmd 'hi link LspDiagnosticsDefaultError DiagnosticError'
vim.cmd 'hi link LspDiagnosticsDefaultWarning DiagnosticWarn'
vim.cmd 'hi link LspDiagnosticsDefaultInformation DiagnosticInfo'
vim.cmd 'hi link LspDiagnosticsDefaultHint DiagnosticHint'
vim.cmd 'hi link LspDiagnosticsSignError DiagnosticError'
vim.cmd 'hi link LspDiagnosticsSignWarning DiagnosticWarn'
vim.cmd 'hi link LspDiagnosticsSignInformation DiagnosticInfo'
vim.cmd 'hi link LspDiagnosticsSignHint DiagnosticHint'
vim.cmd 'hi link LspDiagnosticsUnderlineError DiagnosticUnderlineError'
vim.cmd 'hi link LspDiagnosticsUnderlineWarning DiagnosticUnderlineWarn'
vim.cmd 'hi link LspDiagnosticsUnderlineInformation DiagnosticUnderlineInfo'
vim.cmd 'hi link LspDiagnosticsUnderlineHint DiagnosticUnderlineHint'
return syntax
|
return {
include = function()
includedirs { "../vendor/fmtlib/include/" }
end,
run = function()
targetname "fmtlib"
language "C++"
kind "StaticLib"
files
{
"../vendor/fmtlib/src/**.cc",
"../vendor/fmtlib/src/**.h",
}
end
} |
-- spec/hello_spec.lua
local hello = require('hello')
describe('hello lib', function()
it('says hello to you', function()
assert.equal('Hello you', hello.say('you'))
end)
end)
|
local text = create_text_list("default")
local town_portal_check = function()
-- game fully loaded?
if not get_skill(0) then
return
end
local quantity
local portal_book = get_skill(220)
if portal_book then
quantity = portal_book.quantity
else
quantity = 0
end
if quantity < 3 then
text:add(string.format("\x0BWARNING! Town portal scrolls quantity low: %d", quantity), 1500, 0)
end
end
register_plugin(1000, town_portal_check)
|
HUD = {}
HUD.Name = "Default"
local Font_gear = {}
Font_gear.font = "Agency FB"
Font_gear.size = (ScrH() * 0.03333333)
Font_gear.weight = 200
Font_gear.blursize = 0
Font_gear.scanlines = 0
Font_gear.antialias = true
Font_gear.additive = false
Font_gear.underline = false
Font_gear.italic = false
Font_gear.strikeout = false
Font_gear.symbol = false
Font_gear.rotary = false
Font_gear.shadow = false
Font_gear.outline = false
surface.CreateFont("gear", Font_gear )
--surface.CreateFont( "Agency FB", (ScrH() * 0.03333333), 200, 0, 0, "gear")
HUD.SpeedTex = surface.GetTextureID("SCarHUD/speed")
HUD.SpeedPointerTex = surface.GetTextureID("SCarHUD/speedPointer")
HUD.RevTex = surface.GetTextureID("SCarHUD/rev")
HUD.GearTex = surface.GetTextureID("SCarHUD/gear")
HUD.FuelTex = surface.GetTextureID("SCarHUD/fuelPointer")
function HUD:Init()
end
function HUD:DrawHud(vel, rev, gear, fuel, turbo, speed, scar, ply, isWideScreen, kilometersOrMiles)
--Checking if the user have a widescreen res or not.
local Width = ScrW()
local Height = ScrH()
local xPos = 0
local yPos = 0
local xSize = 0
local ySize = 0
//Speed
if isWideScreen then
xPos = Width * 0.8214285714
yPos = Height * 0.7142857143
xSize = Width * 0.1785714286
ySize = Height * 0.2857142857
else
xPos = Width * 0.8214285714
yPos = Height * 0.7823142857
xSize = Width * 0.1785714286
ySize = Height * 0.2176870749
end
surface.SetTexture( self.SpeedTex )
surface.SetDrawColor( 255, 255, 255, 255 )
surface.DrawTexturedRect( xPos, yPos, xSize, ySize )
--speed arrow
if isWideScreen then
xPos = Width * 0.9107142857
yPos = Height * 0.8571428571
xSize = Width * 0.1785714286
ySize = Height * 0.2857142857
else
xPos = Width * 0.9107142857
yPos = Height * 0.8911564626
xSize = Width * 0.1785714286
ySize = Height * 0.2176870749
end
surface.SetTexture( self.SpeedPointerTex )
surface.SetDrawColor( 255, 255, 255, 255 )
local rotation = -260 * (speed / 240)
surface.DrawTexturedRectRotated( xPos, yPos, xSize, ySize, rotation)
--Fuel arrow
if isWideScreen then
xPos = Width * 0.9107142857
yPos = Height * 0.939047619
xSize = Width * 0.0595238095
ySize = Height * 0.0952380952
else
xPos = Width * 0.9107142857
yPos = Height * 0.9503854875
xSize = Width * 0.0595238095
ySize = Height * 0.0725714286
end
rotation = (fuel * 20000) * -0.006
surface.SetTexture( self.FuelTex )
surface.SetDrawColor( 255, 255, 255, 255 )
surface.DrawTexturedRectRotated( xPos , yPos, xSize, ySize, rotation )
if isWideScreen then
xPos = Width * 0.7023809524
yPos = Height * 0.8095238095
xSize = Width * 0.119047619
ySize = Height * 0.1904761905
else
xPos = Width * 0.7023809524
yPos = Height * 0.8548752835
xSize = Width * 0.119047619
ySize = Height * 0.1451247165
end
//Rev
surface.SetTexture( self.RevTex )
surface.SetDrawColor( 255, 255, 255, 255 )
surface.DrawTexturedRect( xPos, yPos, xSize, ySize )
--Rev arrow
if isWideScreen then
xPos = Width * 0.7619047619
yPos = Height * 0.9047619048
xSize = Width * 0.119047619
ySize = Height * 0.1904761905
else
xPos = Width * 0.7619047619
yPos = Height * 0.9274376418
xSize = Width * 0.119047619
ySize = Height * 0.1451247165
end
rotation = (rev * 200) * -1.3
surface.SetTexture( self.SpeedPointerTex )
surface.SetDrawColor( 255, 255, 255, 255 )
surface.DrawTexturedRectRotated( xPos, yPos, xSize, ySize, rotation )
//Gear
if isWideScreen then
xPos = Width * 0.8107142857
yPos = Height * 0.933333333
xSize = Width * 0.0380952381
ySize = Height * 0.060952381
else
xPos = Width * 0.8107142857
yPos = Height * 0.947845805
xSize = Width * 0.0380952381
ySize = Height * 0.0464399093
end
surface.SetTexture( self.GearTex )
surface.SetDrawColor( 255, 255, 255, 255 )
surface.DrawTexturedRect( xPos, yPos, xSize, ySize )
if isWideScreen then
xPos = Width * 0.8297619048
yPos = Height * 0.9619047619
else
xPos = Width * 0.8297619048
yPos = Height * 0.9619047619
end
draw.SimpleText( gear, "gear", xPos, yPos, Color( 255, 255, 255, 200 ), 1, 1 )
end
function HUD:MenuElements(Panel)
end
SCarHudHandler:RegisterHUD(HUD) |
--------------------------------------------------------------------------------------
-- this file is to test building a planner outside of dota 2 --
--------------------------------------------------------------------------------------
Class = require 'utils/class'
require 'planner/elements/Action'
require 'planner/elements/ActionPattern'
require 'planner/elements/Competence'
require 'planner/elements/CompetenceElement'
require 'planner/elements/Drive'
require 'planner/elements/DriveCollection'
require 'planner/elements/Sense'
file = require 'planner/simpleplan2'
require 'planner/Planner'
json = require 'utils/json'
p = Planner(file) |
local local0 = 0.3
local local1 = 1.8 - local0
local local2 = 1.8 - local0
local local3 = 2.9 - local0
local local4 = 1.8 - local0
local local5 = 2.5 - local0
local local6 = 2.5 - local0
local local7 = 1.8 - local0
local local8 = 2.3 - local0
local local9 = 2.5 - local0
local local10 = 5.9 - local0
local local11 = 4 - local0
local local12 = 1.8 - local0
local local13 = 1.8 - local0
local local14 = 1.8 - local0
function OnIf_303000(arg0, arg1, arg2)
if arg2 == 0 then
DungeonResident_Madman_Sickle303000_ActAfter_RealTime(arg0, arg1)
end
return
end
function DungeonResident_Madman_Sickle303000Battle_Activate(arg0, arg1)
local local0 = {}
local local1 = {}
local local2 = {}
Common_Clear_Param(local0, local1, local2)
local local3 = arg0:GetDist(TARGET_ENE_0)
local local4 = arg0:GetEventRequest()
local local5 = arg0:GetRandam_Int(1, 100)
local local6 = arg0:GetHpRate(TARGET_SELF)
local local7 = 1
local local8 = 1
if arg0:IsFinishTimer(0) == false then
local7 = 0
else
local7 = 1
end
if arg0:IsFinishTimer(1) == false then
local8 = 0
else
local8 = 1
end
if not arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 90) and local3 <= 0.5 then
local0[13] = 100
elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 165) then
local0[10] = 100
elseif 9 <= local3 then
local0[1] = 0
local0[2] = 0
local0[3] = 5
local0[4] = 15
local0[5] = 15
local0[6] = 0 * local7
local0[7] = 10
local0[9] = 20
local0[11] = 35 * local8
local0[12] = 0
elseif 6 <= local3 then
local0[1] = 0
local0[2] = 5
local0[3] = 5
local0[4] = 10
local0[5] = 5
local0[6] = 5 * local7
local0[7] = 5
local0[9] = 30
local0[11] = 25 * local8
local0[12] = 10
elseif 3.4 <= local3 then
local0[1] = 15
local0[2] = 10
local0[3] = 0
local0[4] = 10
local0[5] = 0
local0[6] = 5 * local7
local0[7] = 0
local0[9] = 15
local0[11] = 0 * local8
local0[12] = 10
local0[13] = 35
elseif 1.5 <= local3 then
local0[1] = 5
local0[2] = 15
local0[3] = 5
local0[4] = 0
local0[5] = 0
local0[6] = 15 * local7
local0[7] = 15
local0[9] = 0
local0[11] = 0 * local8
local0[12] = 15
local0[13] = 30
else
local0[1] = 0
local0[2] = 25
local0[3] = 5
local0[4] = 0
local0[5] = 0
local0[6] = 15 * local7
local0[7] = 25
local0[9] = 0
local0[11] = 0 * local8
local0[12] = 15
local0[13] = 15
end
local1[1] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act01)
local1[2] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act02)
local1[3] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act03)
local1[4] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act04)
local1[5] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act05)
local1[6] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act06)
local1[7] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act07)
local1[8] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act08)
local1[9] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act09)
local1[10] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act10)
local1[11] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act11)
local1[12] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act12)
local1[13] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_Act13)
Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, DungeonResident_Madman_Sickle303000_ActAfter_AdjustSpace), local2)
return
end
local0 = 2.4 - local0
local0 = local3
local0 = 3.4 - local0
function DungeonResident_Madman_Sickle303000_Act01(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = UPVAL0 + 5
local local2 = UPVAL1 + 5
local local3 = UPVAL2
local local4 = UPVAL0 + 0.5
if local4 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local4, UPVAL0 + 0.5, 0, 3)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 5732) == true then
if local0 <= 20 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3011, TARGET_ENE_0, local1, 0, 360)
elseif local0 <= 40 then
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3011, TARGET_ENE_0, local1, 0, 360)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3012, TARGET_ENE_0, local3, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3011, TARGET_ENE_0, local1, 0, 360)
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3012, TARGET_ENE_0, local2, 0, 360)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3013, TARGET_ENE_0, local3, 0)
end
elseif local0 <= 20 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360)
elseif local0 <= 40 then
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, local3, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360)
arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, local2, 0, 360)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, local3, 0)
end
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = 3.1 - local0
local0 = 3.7 - local0
function DungeonResident_Madman_Sickle303000_Act02(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = UPVAL0
if local1 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local1, UPVAL0 + 1, 0, 3)
end
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL0 + 5, 0, 360)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, UPVAL1, 0)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = local8
function DungeonResident_Madman_Sickle303000_Act03(arg0, arg1, arg2)
local local0 = UPVAL0
local local1 = UPVAL0 + 0.5
local local2 = UPVAL0 + 1.5
if arg0:GetRandam_Int(1, 100) <= 70 then
local1 = 999
local2 = 0
end
if local1 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local1, local2, 0, 3)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 5732) == true then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3014, TARGET_ENE_0, local0, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, local0, 0, 0)
end
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
local0 = local10
function DungeonResident_Madman_Sickle303000_Act04(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = UPVAL0 + 2
local local2 = UPVAL0
if local2 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local2, UPVAL0 + 1, 0, 3)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 5732) == true then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3015, TARGET_ENE_0, local1, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, local1, 0, 0)
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = 7.3 - local0
function DungeonResident_Madman_Sickle303000_Act05(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = UPVAL0 + 2
local local2 = UPVAL0 + 0.5
if local2 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local2, UPVAL0 + 1.5, 0, 3)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 5732) == true then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3016, TARGET_ENE_0, local1, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, local1, 0, 0)
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = 3.5 - local0
local0 = 3.3 - local0
function DungeonResident_Madman_Sickle303000_Act06(arg0, arg1, arg2)
local local0 = UPVAL0 + 0.5
local local1 = UPVAL0 + 1
if local1 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local1, UPVAL0 + 2, 0, 3)
end
if arg0:GetRandam_Int(1, 100) <= 40 then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3008, TARGET_ENE_0, local0, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3008, TARGET_ENE_0, local0, 0, 0)
arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3009, TARGET_ENE_0, UPVAL1, 0)
end
arg0:SetTimer(0, 10)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = 2.4 - local0
function DungeonResident_Madman_Sickle303000_Act07(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = UPVAL0
if local1 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local1, UPVAL0 + 1, 0, 3)
end
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3010, TARGET_ENE_0, UPVAL0 + 0.5, 0, 0)
GetWellSpace_Odds = 100
return GetWellSpace_Odds
end
function DungeonResident_Madman_Sickle303000_Act08(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Float(2, 6)
if local0 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local0, 0, 0, 3)
end
local local1 = 1
for local2 = arg0:GetRandam_Int(1, 3) - local1, 3, local1 do
local local3 = 0
local local4 = AI_DIR_TYPE_L
if arg0:GetRandam_Int(1, 100) <= 50 then
local3 = 702
local4 = AI_DIR_TYPE_L
else
local3 = 703
local4 = AI_DIR_TYPE_R
end
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, local3, TARGET_ENE_0, 0, local4, 4)
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = local8
function DungeonResident_Madman_Sickle303000_Act09(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = UPVAL0 + 10
local local2 = UPVAL0 + 10
local local3 = 999
local local4 = 0
if arg0:GetDist(TARGET_ENE_0) <= 4 then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 5)
end
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, arg0:GetRandam_Int(1, 3), TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(45, 60), true, true, -1)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function DungeonResident_Madman_Sickle303000_Act10(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetRandam_Float(0.5, 1.5)
local local3 = 0
local local4 = AI_DIR_TYPE_L
arg1:AddSubGoal(GOAL_COMMON_Turn, 1, TARGET_ENE_0, 0, 0, 0)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = local3
local0 = local2
function DungeonResident_Madman_Sickle303000_Act11(arg0, arg1, arg2)
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = UPVAL1
local local2 = UPVAL0 + 5
local local3 = UPVAL0 + 3
local local4 = 0
local local5 = 5.5
arg0:SetTimer(1, 5)
if UPVAL0 + 0.5 + local5 - 1 <= arg0:GetDist(TARGET_ENE_0) then
Approach_Act(arg0, arg1, local5, local5, 0, 3)
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 700, TARGET_ENE_0, 0, AI_DIR_TYPE_F, 5.5)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 700, TARGET_ENE_0, 0, AI_DIR_TYPE_F, 5.5)
end
if arg0:HasSpecialEffectId(TARGET_SELF, 5732) == true then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3011, TARGET_ENE_0, AttDist0, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3001, TARGET_ENE_0, AttDist0, 0, 0)
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = local3
local0 = local2
function DungeonResident_Madman_Sickle303000_Act12(arg0, arg1, arg2)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = UPVAL1
Approach_Act(arg0, arg1, UPVAL0, UPVAL0 + 2, 0, 2)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3001, TARGET_ENE_0, UPVAL0 + 3, 0, -1)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
local0 = local10
function DungeonResident_Madman_Sickle303000_Act13(arg0, arg1, arg2)
local local0 = UPVAL0 + 2
local local1 = UPVAL0 + 3
local local2 = 0
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 712, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 5)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 713, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 5)
end
if arg0:GetDist(TARGET_ENE_0) <= UPVAL0 + 1 and arg0:GetRandam_Int(1, 100) <= 60 then
if arg0:HasSpecialEffectId(TARGET_SELF, 5732) == true then
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3015, TARGET_ENE_0, local0, 0, 0)
else
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, local0, 0, 0)
end
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function DungeonResident_Madman_Sickle303000_ActStep(arg0, arg1)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = 4
local local2 = 4
local local3 = arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_L, local1, 5)
local local4 = arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_R, local2, 5)
if local3 and local4 then
if arg0:GetRandam_Int(1, 100) <= 50 then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, local1)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, local2)
end
elseif local3 then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, local1)
elseif local4 then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, local2)
else
arg1:AddSubGoal(GOAL_COMMON_Turn, 3, TARGET_ENE_0, 0, 0, 0)
end
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function DungeonResident_Madman_Sickle303000_ActAfter_AdjustSpace(arg0, arg1, arg2)
arg1:AddSubGoal(GOAL_COMMON_If, 10, 0)
return
end
function DungeonResident_Madman_Sickle303000_ActAfter_RealTime(arg0, arg1)
local local0 = arg0:GetDist(TARGET_ENE_0)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetRandam_Int(0, 1)
local local3 = arg0:GetRandam_Float(1, 3.5)
local local4 = arg0:GetRandam_Float(2, 4)
if local0 <= 1.5 then
if local1 <= 60 then
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 180) then
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 5)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 5)
end
arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 7, TARGET_ENE_0, true, -1)
end
else
arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 5, TARGET_ENE_0, true, -1)
end
elseif local0 <= 2.5 then
if local1 <= 40 then
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 5)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 5)
end
arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 7, TARGET_ENE_0, true, -1)
elseif local1 <= 70 then
arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 5, TARGET_ENE_0, true, -1)
elseif local1 <= 90 then
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
end
elseif local0 <= 4.5 then
if local1 <= 40 then
if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 5)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 5)
end
arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 10, TARGET_ENE_0, true, -1)
elseif local1 <= 60 then
arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 7, TARGET_ENE_0, true, -1)
elseif local1 <= 80 then
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
end
elseif local0 <= 6.5 then
if local1 <= 50 then
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
elseif local1 <= 80 then
arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 4.5, TARGET_SELF, true, -1)
end
elseif local0 <= 10 then
if local1 <= 40 then
arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1)
elseif local1 <= 80 then
arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 6.5, TARGET_SELF, true, -1)
end
else
arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 8, TARGET_SELF, false, -1)
end
return
end
function DungeonResident_Madman_Sickle303000Battle_Update(arg0, arg1)
return GOAL_RESULT_Continue
end
function DungeonResident_Madman_Sickle303000Battle_Terminate(arg0, arg1)
return
end
local0 = local8
function DungeonResident_Madman_Sickle303000Battle_Interupt(arg0, arg1)
if arg0:IsLadderAct(TARGET_SELF) then
return false
end
local local0 = arg0:GetRandam_Int(1, 100)
local local1 = arg0:GetRandam_Int(1, 100)
local local2 = arg0:GetRandam_Int(1, 100)
local local3 = arg0:GetDist(TARGET_ENE_0)
local local4 = arg0:GetHpRate(TARGET_SELF)
if FindAttack_Step(arg0, arg1, 3, 15, 20, 40, 40) then
return true
elseif Damaged_Step(arg0, arg1, 3, 30, 80, 10, 10, 5) then
return true
end
local local5 = arg0:GetRandam_Int(1, 100)
local local6 = arg0:GetRandam_Int(1, 100)
local local7 = arg0:GetDist(TARGET_ENE_0)
local local8 = Shoot_2dist(arg0, arg1, 6, 20, 50, 80)
if local8 == 1 then
if local6 <= 50 then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 4)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 4)
end
elseif local8 == 2 then
local local9 = UPVAL0 + 1
local local10 = UPVAL0
local local11 = 0
local local12 = 0
if local6 <= 50 then
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 4)
Approach_Act(arg0, arg1, local10, local11, local12)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, local9, 0, -1)
else
arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 4)
Approach_Act(arg0, arg1, local10, local11, local12)
arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, local9, 0, -1)
end
return true
end
return false
end
return
|
--[[ Copyright (C) 2019 The DMLab2D Authors.
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
https://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 events = require 'system.events'
local tensor = require 'system.tensor'
local sys_random = require 'system.random'
local properties = require 'system.properties'
local api = {
_steps = 10,
_reward = 0,
_observations = {
tensor.ByteTensor{range = {1}},
tensor.DoubleTensor{range = {2}},
tensor.Int32Tensor{range = {3}},
},
_observation_seed = 0,
_observation_step = 0,
_observation_episode = 0,
}
--[[ Called once by framework before all other calls.
Arguments:
* `kwargs` All settings forwarded from the EnvCApi apart from:
- 'levelDirectory': Used to select the directory of the levels.
- 'levelName': Used to select the level.
- 'mixerSeed': Used to salt the seeds of random number generators.
In this example the only setting valid other than those consumed internally is
'steps = <number>'.
]]
function api:init(kwargs)
local errors = ''
for k, v in pairs(kwargs) do
if k == 'steps' and tonumber(v) then
self._steps = tonumber(v)
else
errors = errors .. 'Invalid setting ' .. k .. '=' .. v .. '\n'
end
end
if errors ~= '' then
return 2, errors
end
end
--[[ Called by framework after once after init.
Returns:
* Array observation spec.
Each observation spec must contain:
* `name` - The name of the observation.
* `type` - The type of the observation, Allowed values:
- 'String'
- 'tensor.DoubleTensor'
- 'tensor.ByteTensor'
- 'tensor.Int32Tensor'
- 'tensor.Int64Tensor'
* `shape` - Must be {0} if `type` is 'String' otherwise the shape of the
tensor with 0 in place of dynamic dimensions.
]]
function api:observationSpec()
return {
{
name = 'VIEW1',
type = self._observations[1]:type(),
shape = self._observations[1]:shape(),
},
{
name = 'VIEW2',
type = self._observations[2]:type(),
shape = self._observations[2]:shape(),
},
{
name = 'VIEW3',
type = self._observations[3]:type(),
shape = self._observations[3]:shape(),
},
{
name = 'SEED',
type = 'tensor.Int64Tensor',
shape = {},
},
{
name = 'EPISODE',
type = 'tensor.Int32Tensor',
shape = {},
},
{
name = 'STEP',
type = 'tensor.Int32Tensor',
shape = {},
}
}
end
--[[ Called by framework and returns an observation.
Arguments:
* `index` observation index corresponding the index of the spec returned in
observationSpec.
Returns:
]]
function api:observation(index)
if index < 4 then
return self._observations[index]
elseif index == 4 then
return self._observation_seed
elseif index == 5 then
return self._observation_episode
else
return self._observation_step
end
end
--[[ Called by framework after once after init and returns discreteActionSpec.
Returns:
* Array of discrete action spec.
Each action spec must contain:
- `name`: The name of the action.
- `min`: Inclusive minimum value of the action.
- `max`: Inclusive maximum value of the action.
]]
function api:discreteActionSpec()
return {{name = 'REWARD_ACT', min = 0, max = 4}}
end
--[[ Called by framework and sets discrete actions before call to advance.
Arguments:
* `actions` - An array of doubles matching continous action spec.
]]
function api:discreteActions(actions)
self._reward = actions[1]
end
--[[ Called at the beginning of each episode.
The first observation may be observed after this call. The `episode` is
forwarded from the EnvCApi, and the `seed` is calculated from an internal random
number generator initialised with the seed from the EnvCApi and `mixerSeed`.
]]
function api:start(episode, seed)
sys_random:seed(seed)
self._observation_seed = seed
self._observation_step = 0
self._observation_episode = episode
events:add('start', tensor.Int64Tensor{range = {3}})
end
--[[ Called at each advance of the environment.
Arguments:
* `steps` - Total steps taken this episode including this one.
Returns:
* bool - Whether the environment should continue.
* number - Total reward gained this frame.
]]
function api:advance(steps)
self._observation_step = steps
return steps < self._steps, self._reward
end
return api
|
return {
Debugger = {
PrintDebug = false; -- Wether or not debug messages get printed or not.
Format = {
TagFormat = "[%s]"; -- What a tag would look like. This is used for [CRITICAL], [Server\Script\...]
Format = "%s: %s"; -- How you wanna divide it. ie [TAG] [TAG]: MESSAGE
CustomFormats = {
Error = "%s %s\n\n%s"; -- If you wanna add exceptions to the format rule above, do it here. There 5 types of messages which are: Message, Debugging, Warning, Error, and Critical
Critical = "%s %s\n\n%s"
},
}
}
} |
client_script 'nonpcweapondrop.lua' |
----------------------------------------------------------------
-- Copyright (c) 2012 Klei Entertainment Inc.
-- All Rights Reserved.
-- SPY SOCIETY.
----------------------------------------------------------------
local util = include( "client_util" )
local mathutil = include( "modules/mathutil" )
local array = include( "modules/array" )
local cdefs = include( "client_defs" )
local mui = include("mui/mui")
local mui_defs = include( "mui/mui_defs")
local simquery = include( "sim/simquery" )
----------------------------------------------------------------
-- Local functions
local hud_warnings = class()
function hud_warnings:init( hud )
self.hud = hud
self.warningQueue = {}
end
function hud_warnings:queueWarning( ... )
-- If nothing is up, show warning directly.
if self._warningTimer == nil then
self:showWarning( ... )
else
table.insert( self.warningQueue, {...} )
end
end
function hud_warnings:showWarning( txt, color, subtext, timeinseconds, mainframe, programIcon, sound, speech )
--jcheng:
--if there's a subtext, use warningtxt
--if no subtext, use the warningtxtCenter which is centered in the box
if sound then
MOAIFmodDesigner.playSound( sound )
end
if speech then
MOAIFmodDesigner.playSound( speech )
end
if not timeinseconds then
self._warningTimer = 3*cdefs.SECONDS
else
self._warningTimer = timeinseconds
end
local screen = self.hud._screen
screen.binder.warning:setVisible(true)
local warningTxt = screen.binder.warningTxtCenter
if subtext then
warningTxt = screen.binder.warningTxt
screen.binder.warningSubTxt:spoolText(subtext)
screen.binder.warningTxtCenter:setText("")
else
screen.binder.warningSubTxt:setText("")
screen.binder.warningTxt:setText("")
end
warningTxt:spoolText(txt)
if color then
screen.binder.warningBG:setColor(color.r,color.g,color.b,color.a)
warningTxt:setColor(color.r,color.g,color.b,color.a)
if subtext then
screen.binder.warningSubTxt:setColor(color.r,color.g,color.b,color.a)
end
else
screen.binder.warningBG:setColor( 184/255, 13/255, 13/255, 1)
warningTxt:setColor(184/255, 13/255, 13/255, 1)
if subtext then
screen.binder.warningSubTxt:setColor(184/255, 13/255, 13/255, 1)
end
end
if mainframe then
screen.binder.warning.binder.hazzard:setVisible(true)
screen.binder.warning.binder.warningTxt:setColor(0,0,0,1)
screen.binder.warning.binder.warningSubTxt:setColor(0,0,0,1)
screen.binder.warning.binder.warningTxtCenter:setColor(0,0,0,1)
screen.binder.warning.binder.warningBG:setVisible(false)
screen.binder.warning.binder.fullBG:setVisible(true)
screen.binder.warning.binder.fullBG:setColor(1,0,0,160/255)
else
screen.binder.warning.binder.fullBG:setVisible(false)
screen.binder.warning.binder.hazzard:setVisible(false)
screen.binder.warning.binder.warningBG:setVisible(true)
end
local programGrp = screen.binder.warning.binder.programGroup
if programIcon then
programGrp:setVisible(true)
programGrp.binder.program:setImage(programIcon)
else
programGrp:setVisible(false)
end
if not screen.binder.warning:hasTransition() then
screen.binder.warning:createTransition( "activate_left" )
end
end
function hud_warnings:updateWarnings()
if self._warningTimer then
self._warningTimer = self._warningTimer - 1
if self._warningTimer <= 0 then
self._warningTimer = nil
if #self.warningQueue > 0 then
local warning = table.remove( self.warningQueue, 1 )
local txt = warning[1]
local color = warning[2]
local subtext = warning[3]
local timeinseconds = warning[4]
local mainframe = warning[5]
local programIcon = warning[6]
local sound = warning[7]
local speech = warning[8]
self:showWarning( txt, color, subtext, timeinseconds, mainframe, programIcon, sound, speech )
else
local widget = self.hud._screen.binder.warning
widget:createTransition( "deactivate_right",
function( transition )
widget:setVisible( false )
end,
{ easeOut = true } )
end
end
end
end
return hud_warnings
|
-- Saw wave.
local SoundUnit = require((...):gsub('[^.]*$', '') .. 'soundunit')
local function process (t, v)
return -v
end
return function (t)
t = SoundUnit(t)
t.process = process
return t
end
|
local function privatekey(name)
return function() return name end
end
local CEL = {}
CEL.privatekey = privatekey
CEL._formation = privatekey('_formation')
CEL._host = privatekey('_host')
CEL._links = privatekey('_links')
CEL._next = privatekey('_next')
CEL._prev = privatekey('_prev')
CEL._trap = privatekey('_trap')
CEL._focus = privatekey('_focus')
CEL._name = privatekey('_name')
CEL._x = privatekey('_x')
CEL._y = privatekey('_y')
CEL._w = privatekey('_w')
CEL._h = privatekey('_h')
CEL._metacel = privatekey('_metacel')
CEL._vectorx = privatekey('_vectorx')
CEL._vectory = privatekey('_vectory')
CEL._linker = privatekey('_linker')
CEL._xval = privatekey('_xval')
CEL._yval = privatekey('_yval')
CEL._face = privatekey('_face')
CEL._minw = privatekey('_minw')
CEL._minh = privatekey('_minh')
CEL._maxw = privatekey('_maxw')
CEL._maxh = privatekey('_maxh')
CEL._keys = privatekey('_keys')
CEL._states = privatekey('_states')
CEL._celid = privatekey('_celid')
CEL._disabled = privatekey('_disabled')
CEL._refresh = privatekey('_refresh')
CEL._appstatus = privatekey('_appstatus')
CEL._hidden = privatekey('_hidden')
CEL._metacelname = privatekey('_metacelname')
CEL.maxdim = 2^31-1
CEL.maxpos = 2^31-1
CEL.minpos = -(2^31)
CEL.stackformation = {}
CEL.event = {}
CEL.driver = {}
CEL.mousetrackerfuncs = {}
CEL.factories = {}
CEL.updaterect = { l = 0, r = 0, t = 0, b = 0 }
CEL.flows = {}
CEL.timer = {millis = 0}
CEL.M = setmetatable({}, { __index = function(cel, key)
cel[key] = select(2, assert(pcall(require, 'cel.' .. key)))
return cel[key]
end})
return CEL
|
local status_ok, _ = pcall(require, "lspconfig")
if not status_ok then
return
end
require("user.lsp.lsp-installer")
require("user.lsp.handlers").setup()
require("user.lsp.null-ls")
|
AddCSLuaFile()
DEFINE_BASECLASS("emod_base")
ENT.Category = "EMod"
ENT.Spawnable = true
ENT.PrintName = "EMod Solar Panel"
ENT.EMODable = true
if SERVER then
function ENT:Initialize()
self:SetModel("models/emod/emod_solar.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
self:PhysWake()
self:SetCollisionGroup(COLLISION_GROUP_NONE)
self.Temperature = 25.0
self.EModOutputs = {{name="ANODE",pinPos=Vector(6.574390,0,3.982300)},{name="KATHODE",pinPos=Vector(6.533550,0,-3.518982)}}
self.EModScheme = {
[1]={[2]={}},
[2]={[1]={}}
}
end
function ENT:Think()
trace = util.QuickTrace(self:GetPos(),self:LocalToWorld(Vector(0,0,32768)),{self})
if trace.HitSky then
local angle = self:GetAngles()
local d = math.Round(math.Remap(math.Clamp(math.floor(math.abs(angle.p)),0,90),0,90,1,0),2)
self:SetSunAmount(d)
else
self:SetSunAmount(self:GetSunAmount()-0.1)
end
self:NextThink(CurTime() + EMODTick)
return true
end
end
if CLIENT then
function ENT:Draw()
self:DrawModel()
cam.Start3D2D(self:LocalToWorld(Vector(-24.5,0,5.1)),self:LocalToWorldAngles(Angle(0,-90,0)),0.05)
draw.RoundedBox(4,-25,0,50,8,Color(0,0,self:GetSunAmount()*255,self:GetSunAmount()*100))
cam.End3D2D()
end
end
function ENT:SetupDataTables()
self:NetworkVar("Float",0,"SunAmount")
if SERVER then
self:SetSunAmount(0)
end
end |
modifier_onoki_added_weight_allies = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_onoki_added_weight_allies:IsHidden()
return false
end
function modifier_onoki_added_weight_allies:IsDebuff()
return false
end
function modifier_onoki_added_weight_allies:IsStunDebuff()
return false
end
function modifier_onoki_added_weight_allies:IsPurgable()
return true
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_onoki_added_weight_allies:OnCreated( kv )
-- references
self.caster = self:GetCaster()
local abilityS = self.caster:FindAbilityByName("special_bonus_onoki_4")
self.speed_bonus_perc = self:GetAbility():GetSpecialValueFor( "speed_bonus_perc" )
if abilityS ~= nil then
if abilityS:GetLevel() > 0 then
self.speed_bonus_perc = self.speed_bonus_perc + 7
end
end
self.manacost_reduction = self:GetAbility():GetSpecialValueFor( "manaloss_modifier" )
end
function modifier_onoki_added_weight_allies:OnRefresh( kv )
self:OnCreated( kv )
end
function modifier_onoki_added_weight_allies:OnRemoved()
end
function modifier_onoki_added_weight_allies:OnDestroy()
end
--------------------------------------------------------------------------------
-- Modifier Effects
function modifier_onoki_added_weight_allies:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_MANACOST_PERCENTAGE,
}
return funcs
end
function modifier_onoki_added_weight_allies:GetModifierMoveSpeedBonus_Percentage()
return self.speed_bonus_perc
end
function modifier_onoki_added_weight_allies:GetModifierPercentageManacost()
return self.manacost_reduction
end
--------------------------------------------------------------------------------
-- Status Effects
function modifier_onoki_added_weight_allies:CheckState()
local state = { }
return state
end
--------------------------------------------------------------------------------
-- Graphics & Animations
function modifier_onoki_added_weight_allies:GetStatusEffectName()
return "particles/units/heroes/onoki/onoki_speed_buff_status2.vpcf"
end
--------------------------------------------------------------------------------
function modifier_onoki_added_weight_allies:StatusEffectPriority()
return 1000
end
--------------------------------------------------------------------------------
function modifier_onoki_added_weight_allies:GetEffectName()
return "particles/units/heroes/onoki/onoki_speed_buff.vpcf"
end
function modifier_onoki_added_weight_allies:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
|
local a = {}
lines = {}
local i = 1
a.draw = function()
scripts.systems.render.renderText.renderText(lines[i], { x = 200, y = 200 }, 25)
end
a.next = function()
i = i + 1
if lines[i] == "LEVEL HERE" then
i = i + 1
GS.pop()
end
end
-- Read story from text file
local k = 1
local story = love.filesystem.newFile("assets/story.txt")
for line in story:lines() do
if line == "-----" then
k = k + 1
elseif lines[k] then
lines[k] = lines[k] .. "\n" .. line
else
lines[k] = line
end
end
return a |
local enemypack = ...
local battleEnvironment
local arf
function RebuildBattle()
if battleEnvironment then
Command.Environment.Destroy(battleEnvironment)
battleEnvironment = nil
end
if arf then
Command.Environment.Destroy(arf)
arf = nil
end
battleEnvironment = Command.Environment.Create(_G, "Battle", "battle.lua", nil, enemypack)
battleEnvironment.Event.Battle.Lost:Attach(function ()
-- uhoh
arf = Command.Environment.Create(_G, "Arf", "battleloop_arf.lua", nil, "lose")
arf.Frame.Root:SetLayer(1)
AttachArfEvents()
end)
battleEnvironment.Event.Battle.Won:Attach(function ()
-- yay
arf = Command.Environment.Create(_G, "Arf", "battleloop_arf.lua", nil, "win")
arf.Frame.Root:SetLayer(1)
AttachArfEvents()
end)
end
local abortEvent = Command.Event.Create(_G, "Battleloop.Abort")
local failEvent = Command.Event.Create(_G, "Battleloop.Fail")
function AttachArfEvents()
arf.Event.Battleloop.Arf.Abort:Attach(function ()
abortEvent()
end)
arf.Event.Battleloop.Arf.Retry:Attach(function ()
RebuildBattle()
end)
arf.Event.Battleloop.Arf.Fail:Attach(function ()
failEvent()
end)
end
RebuildBattle()
|
--[[-------------------------------------------------------------------
PluginName: lualine.nvim
Github: github.com/hoob3rt/lualine.nvim
--]]-------------------------------------------------------------------
-- -------------------------------------------------------------------
-- CONFIGS
-- -------------------------------------------------------------------
-- -------- USER DEFINED ---------------
-- Color table for highlights
local colors = {
bg = '#202328',
fg = '#bbc2cf',
black = '#1c1e26',
white = '#FFFFFF',
white1 = '#6C6F93',
red = '#F43E5C',
red_error = '#800000',
green = '#09F7A0',
blue = '#25B2BC',
yellow = '#F09383',
gray = '#E95678',
darkgray = '#1A1C23',
lightgray = '#2E303E',
inactivegray = '#1C1E26',
yellow = '#ECBE7B',
cyan = '#008080',
darkblue = '#081633',
orange = '#FF8800',
violet = '#a9a1e1',
magenta = '#c678dd'
}
-- copied from https://gist.github.com/hoob3rt/b200435a765ca18f09f83580a606b878#file-evil_lualine-lua-L21
local conditions = {
buffer_not_empty = function() return vim.fn.empty(vim.fn.expand('%:t')) ~= 1 end,
hide_in_width = function() return vim.fn.winwidth(0) > 80 end,
check_git_workspace = function()
local filepath = vim.fn.expand('%:p:h')
local gitdir = vim.fn.finddir('.git', filepath .. ';')
return gitdir and #gitdir > 0 and #gitdir < #filepath
end
}
-- copied and modified from https://github.com/hoob3rt/lualine.nvim/issues/77#issuecomment-765067579
function diagnostics_m()
local errors = 0
local warnings = 0
local hints = 0
local cur_buf_errors = 0
local cur_buf_warnings = 0
local cur_buf_hints = 0
for _, buffer in ipairs(vim.fn['getbufinfo']()) do -- Loop through buffers
if buffer.listed == 1 and buffer.name ~= '' then -- If the buffer is listed and it is not a no-name buffer
local bufnr = buffer.bufnr
local buf_errors = vim.lsp.diagnostic.get_count(bufnr, [[Error]])
local buf_warnings = vim.lsp.diagnostic.get_count(bufnr, [[Warning]])
local buf_hints = vim.lsp.diagnostic.get_count(bufnr, [[Hint]])
errors = errors + buf_errors -- Add this buffer's errors to the total errors
warnings = warnings + buf_warnings -- Same with warnings
hints = hints + buf_hints
if bufnr == vim.fn.bufnr() then -- If this buffer is the currently open buffer
cur_buf_errors = buf_errors
cur_buf_warnings = buf_warnings
cur_buf_hints = buf_hints
end
end
end
if errors ~= 0 or warnings ~= 0 or hints~=0 then -- If there is at least one error or warning or hints
return '✗:' .. errors .. ' ⚠:' .. warnings .. ' :' .. hints
else
return ''
end
end
-- Lsp server name .
local function lspservername()
local msg = ''
local buf_ft = vim.api.nvim_buf_get_option(0, 'filetype')
local clients = vim.lsp.get_active_clients()
if next(clients) == nil then return msg end
for _, client in ipairs(clients) do
local filetypes = client.config.filetypes
if filetypes and vim.fn.index(filetypes, buf_ft) ~= -1 then
return "LSP[" .. client.name .. "]"
end
end
return msg
end
local lsp_status = require('lsp-status')
lsp_status.register_progress()
local lsp_config = require('lspconfig')
--[[
---------------------------------------------
-- Some arbitrary servers
lsp_config.clangd.setup({
--handlers = lsp_status.extensions.clangd.setup(),
--on_attach = lsp_status.on_attach,
capabilities = lsp_status.capabilities
})
lsp_config.pyright.setup({
settings = { python = { workspaceSymbols = { enabled = true }}},
on_attach = lsp_status.on_attach,
capabilities = lsp_status.capabilities
})
lsp_config.ghcide.setup({
on_attach = lsp_status.on_attach,
capabilities = lsp_status.capabilities
})
lsp_config.rust_analyzer.setup({
on_attach = lsp_status.on_attach,
capabilities = lsp_status.capabilities
})
---------------------------------------------
]]
-- -------- end of USER DEFINED ---------------
--[[
Lualine has sections as shown below.
+-------------------------------------------------+
| A | B | C X | Y | Z |
+-------------------------------------------------+
]]
require'lualine'.setup {
--[[ Setting a theme:
All available themes are listed in https://github.com/hoob3rt/lualine.nvim/blob/master/THEMES.md
16color, ayu_dark, ayu_light, ayu_mirage, codedark, dracula, everforest, gruvbox, gruvbox_light, gruvbox_material,
horizon, iceberg_dark, iceberg_light, jellybeans, material, modus_vivendi, molokai, nightfly, nord, oceanicnext,
onedark, onelight, palenight, papercolor_dark, papercolor_light, powerline, seoul256, solarized_dark, solarized_light,
tomorrow, wombat
Symbols:
║ ⋰ ∫
]]
options = {
theme = 'ayu_mirage',
section_separators = {'', ''}, -- separators between sections
--component_separators = {'⋰', '⋰'},
disabled_filetypes = {}, -- disable lualine for specific filetypes
icons_enabled = 1, -- displays icons in alongside component
--padding = 0, -- adds padding to the left and right of components
left_padding = 0, -- adds padding to the left of components
right_padding = 0, -- adds padding to the right of components
upper = false, -- displays components in uppercase
lower = false, -- displays components in lowercase
format = nil -- format function, formats component's output
},
sections = {
lualine_a = {
{
'mode',
right_padding =1,
left_padding = 1,
component_separators = ''
},
{
'branch',
-- icon = '',
condition = conditions.check_git_workspace,
right_padding =1,
component_separators = ''
},
{
'diff',
symbols = {added = '+ ', modified = '~ ', removed = '- '},
color_added = colors.green,
color_modified = colors.orange,
color_removed = colors.red,
condition = conditions.hide_in_width,
right_padding = 1,
},
},
lualine_b = {
{
'filename',
file_status = true, -- displays file status (readonly status, modified status)
path = 1, -- 0 = just filename, 1 = relative path, 2 = absolute path
condition = conditions.buffer_not_empty,
left_padding = 1, -- adds padding to the left of components
right_padding = 1, -- adds padding to the right of components
component_separators = '',
icons_enabled = true,
},
{
'filetype',
colored = true, -- displays filetype icon in color if set to `true` ,
format = function() return " " end,
},
{
'fileformat',
upper = true,
icons_enabled = true,
left_padding = 1, -- adds padding to the right of components
component_separators = ''
},
{
'encoding',
component_separators = '',
left_padding = 1, -- adds padding to the right of components
right_padding = 1,
},
},
lualine_c = {''},
lualine_x = {
{
lsp_status.status,
left_padding = 1, -- adds padding to the left of components
right_padding = 1, -- adds padding to the right of components
component_separators = '',
},
{
diagnostics_m,
color = {fg=colors.red, gui='bold'} ,
left_padding = 1, -- adds padding to the left of components
right_padding = 1, -- adds padding to the right of components
component_separators = '',
},
{
lspservername,
color = {fg=colors.white, gui='bold'} ,
left_padding = 1, -- adds padding to the left of components
right_padding = 1, -- adds padding to the right of components
component_separators = '',
},
},
lualine_y = {
},
lualine_z = {
{
'progress',
left_padding = 1,
},
{
'location',
right_padding = 0,
icon =''
},
}
},
inactive_sections = {
lualine_a = {},
lualine_b = {},
lualine_c = {'filename'},
lualine_x = {'location'},
lualine_y = {},
lualine_z = {}
},
tabline = {},
extensions = {}
}
-- -------------------------------------------------------------------
-- end of CONFIGS
-- -------------------------------------------------------------------
|
local OpcodeChecks = {
MOVE = function(f, i)
assert(i.C == 0, "Error: MOVE.C must equal 0")
assert(i.A < f.MaxStackSize, "Error: MOVE.A out of bounds")
assert(i.B < f.MaxStackSize, "Error: MOVE.B out of bounds")
end,
LOADK = function(f, i)
assert(i.A < f.MaxStackSize, "Error: LOADK.A out of bounds")
assert(i.Bx < f.Constants.Count, "Error: LOADK.Bx out of bounds")
end,
LOADBOOL = function(f, i)
assert(i.A < f.MaxStackSize, "Error: LOADBOOL.A out of bounds")
assert(i.B < 2, "Error: LOADBOOL.B invalid value")
assert(i.C < 2, "Error: LOADBOOL.C invalid value")
end,
LOADNIL = function(f, i)
assert(i.A < f.MaxStackSize, "Error: LOADNIL.A out of bounds")
assert(i.b < f.MaxStackSize, "Error: LOADNIL.B out of bounds")
end,
GETUPVAL = function(f, i)
assert(i.A < f.MaxStackSize, "Error: GETUPVAL.A out of bounds")
assert(i.B < f.Upvalues.Count, "Error: GETUPVAL.B out of bounds")
end,
}
setmetatable(OpcodeChecks, {
__index = function(t, k)
local x = rawget(t, k)
if x then return x end
return function() end
end
})
function VerifyChunk(chunk)
for i = 1, chunk.Instructions.Count do
local instr = chunk.Instructions[i - 1]
local func = OpcodeChecks[instr.Opcode:upper()]
func(chunk, instr)
end
end
|
local race = {
["human"] = {
name = "human",
home = "Stormwind City",
pos_x = 1,
pos_y = 2,
pos_z = 3,
pos_o = 4,
},
["orc"] = {
name = "orc",
home = "Orgrimmar",
pos_x = 5,
pos_y = 6,
pos_z = 7,
pos_o = 8,
},
}
return race
|
fx_version 'adamant'
game 'rdr3'
rdr3_warning 'I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.'
description 'RDX Addon Account'
version '1.0.1'
server_scripts {
'@mysql-async/lib/MySQL.lua',
'server/classes/addonaccount.lua',
'server/main.lua'
}
dependency 'rdx_core'
|
command.Register("ask", "Ask a question that Mr grape may be able to answer! Uses wolfram alpha.","fun",function(msg, args)
local response = msg:reply("Give me a second...")
function askquestion()
local questionbasic = msg.content:gsub(PREFIX .. "ask ", "")
local question = FUNCTIONS.urlencode(questionbasic)
local usedURL = "https://api.wolframalpha.com/v2/query?appid="..CONFIG.wolfram.."&input="..question.."&format=plaintext&output=JSON"
local res, data = CORO.request("GET", usedURL)
local result = JSON.parse(data)
local answer = result["queryresult"]["pods"][2]["subpods"][1].plaintext
response:update({
embed = {
title = "Answer",
description = "Question:\n"..msg.content:gsub(PREFIX .. "ask ", ""),
fields = {
{name = "Answer:", value = answer }
},
color = EMBEDCOLOR,
timestamp = DISCORDIA.Date():toISO('T', 'Z')
}
})
end
if pcall(askquestion) then
-- respond with answer
else
response:setContent("I didn't understand that question!")
end
end) |
-- @doc-title MD to Lua Pipe API
--[[ @doc-overview
Lua support for communicating through windows named pipes with
an external process, with the help of the winpipe api dll, which
wraps select windows OS functions.
The external process will be responsible for serving pipes.
X4 will act purely as a client.
Note: if you are using the higher level MD API, you don't need to
worry about these lua details.
Behavior:
- MD triggers lua functions using raise_lua_event.
- Lua responds to MD by signalling the galaxy object with specific names.
- When loaded, sends the signal "lua_named_pipe_api_loaded".
- Requested reads and writes will be tagged with a unique <id> string,
used to uniquify the signal raised when the request has completed.
- Requests are queued, and will be served as the pipe becomes available.
- Multiple requests may be serviced within the same frame.
- Pipe access is non-blocking; reading an empty pipe will not error, but
instead kicks off a polling loop that will retry the pipe each frame
until the request succeeds or the pipe goes bad (eg. server disconnect).
- If the write buffer to the server fills up and doesn't have room for
a new message, or the new message is larger than the entire buffer,
the pipe will be treated as bad and closed. (This is due to windows
not properly distinguishing these cases from broken pipes in
its error codes.)
- Pipe file handles are opened automatically when handling requests.
- If a prior opened file handle goes bad when processing a request,
one attempt will be made to reopen the file before the request will
error out.
- Whenever the UI is reloaded, all queued requests and open pipes will
be destroyed, with no signals to MD. The MD is responsible for
cancelling out such requests on its end, and the external server
is responsible for resetting its provided pipe in this case.
- The pipe file handle will (should) be closed properly on UI/game reload,
triggering a closed pipe error on the server, which the server should deal
with reasonably (eg. restarting the server side pipe).
]]
--[[ @doc-functions
* Reading a pipe from MD:
Start with a trigger:
```xml
<raise_lua_event
name="'pipeRead'"
param="'<pipe_name>;<id>'"/>
```
Example:
```xml
<raise_lua_event
name="'pipeRead'"
param="'myX4pipe;1234'"/>
```
Capture completion with a new subcue (don't instantiate if already inside
an instance), conditioned on response signal:
```xml
<event_ui_triggered
screen="'Named_Pipes'"
control="'pipeRead_complete_<id>'" />
```
The returned value will be in "event.param3":
```xml
<set_value
name="$pipe_read_value"
exact="event.param3" />
```
`<pipe_name>` should be the unique name of the pipe being connected to.
Locally, this name is prefixed with `\\.\pipe\`.
`<id>` is a string that uniquely identifies this read from other accesses
that may be pending in the same time frame.
If the read fails due to a closed pipe, a return signal will still be sent,
but param2 will contain "ERROR".
* Writing a pipe from MD:
The message to be sent will be suffixed to the pipe_name and id, separated
by semicolons.
```xml
<raise_lua_event
name="'pipeWrite'"
param="'<pipe_name>;<id>;<message>'"/>
```
Example:
```xml
<raise_lua_event
name="'pipeWrite'"
param="'myX4pipe;1234;hello'"/>
```
Optionally capture the response signal, indicating success or failure.
```xml
<event_ui_triggered
screen="'Named_Pipes'"
control="'pipeWrite_complete_<id>'" />
```
The returned status is "ERROR" on an error, else "SUCCESS".
```xml
<set_value name="$status" exact="event.param3" />
```
* Special writes:
Certain write messages will be mapped to special values to be written,
determined lua side. This uses "pipeWriteSpecial" as the event name,
and the message is the special command.
Currently, the only such command is "package.path", sending the current
value in lua for that.
```xml
<raise_lua_event
name="'pipeWriteSpecial'"
param="'myX4pipe;1234;package.path'"/>
```
* Checking pipe status:
Test if the pipe is connected in a similar way to reading:
```xml
<raise_lua_event
name="'pipeCheck'"
param="'<pipe_name>;<id>'" />
```
```xml
<event_ui_triggered
screen="'Named_Pipes'"
control="'pipeCheck_complete_<id>'" />
```
In this case, event.param2 holds SUCCESS if the pipe appears to be
succesfully opened, ERROR if not. Note that this does not robustly
test the pipe, only if the File is open, so it will report success
even if the server has disconnected if no operations have been
performed since that disconnect.
* Close pipe:
```xml
<raise_lua_event
name="'pipeClose'"
param="'<pipe_name>'" />
```
Closing out a pipe has no callback.
This will close the File handle, and will force all pending reads
and writes to signal errors.
* Set a pipe to throw away reads during a pause:
```xml
<raise_lua_event
name="'pipeSuppressPausedReads'"
param="'<pipe_name>'" />
```
* Undo this with:
```xml
<raise_lua_event
name="'pipeUnsuppressPausedReads'"
param="'<pipe_name>'" />
```
* Detect a pipe closed:
When there is a pipe error, this api will make one attempt to reconnect
before returning an ERROR. Since the user may need to know about these
disconnect events, a signal will be raised when they happen.
The signal name is tied to the pipe name.
```xml
<event_ui_triggered
screen="'Named_Pipes'"
control="'<pipe_name>_disconnected'" />
```
]]
-- @doc-title Lua to Lua Pipe API
--[[ @doc-overview
Other lua modules may use this api to access pipes as well. Behavior is
largely the same as for the MD interface, except that results will be
returned to lua callback functions instead of being signalled to MD.
It may be imported using a require statement:
```lua
local pipes_api = require('extensions.sn_named_pipes_api.lua.Interface')
```
]]
--[[ @doc-functions
See named_pipes_api/lua/Pipes.lua for everything available. Basic
writing and reading functions are shown here.
* Schedule_Write(pipe_name, callback, message)
- pipe_name
- String, name of the pipe.
- callback
- Optional, lua function to call, taking one argument.
- message
- String, message to write.
* Schedule_Read(pipe_name, callback)
- pipe_name
- String, name of the pipe.
- callback
- Optional, lua function to call, taking one argument.
]]
-- Import lib functions and pipe management.
local Lib = require("extensions.sn_mod_support_apis.lua.named_pipes.Library")
local Pipes = require("extensions.sn_mod_support_apis.lua.named_pipes.Pipes")
-- Table of local functions.
local L = {}
-- Handle initial setup.
local function Init()
-- Connect the events to the matching functions.
RegisterEvent("pipeRead", L.Handle_pipeRead)
RegisterEvent("pipeWrite", L.Handle_pipeWrite)
RegisterEvent("pipeWriteSpecial", L.Handle_pipeWrite)
RegisterEvent("pipeCheck", L.Handle_pipeCheck)
RegisterEvent("pipeClose", L.Handle_pipeClose)
RegisterEvent("pipeCancelReads", L.Handle_pipeCancelReads)
RegisterEvent("pipeCancelWrites", L.Handle_pipeCancelWrites)
RegisterEvent("pipeSuppressPausedReads", L.Handle_pipeSuppressPausedReads)
RegisterEvent("pipeUnsuppressPausedReads", L.Handle_pipeUnsuppressPausedReads)
-- Signal to MD that the lua has reloaded.
Lib.Raise_Signal('reloaded')
end
-- Read a message from a pipe.
-- Input is one term, semicolon separated string with pipe name, callback id.
function L.Handle_pipeRead(_, pipe_name_id)
-- Isolate the pipe_name and access id.
local pipe_name, callback = Lib.Split_String(pipe_name_id, ";")
-- Pass to the scheduler.
Pipes.Schedule_Read(pipe_name, callback)
end
-- Write to a pipe.
-- Input is one term, semicolon separates string with pipe name, callback id,
-- and message.
-- If signal_name was "pipeWriteSpecial", this message is treated as
-- a special command that is used to determine what to write.
function L.Handle_pipeWrite(signal_name, pipe_name_id_message)
-- Isolate the pipe_name, id, value.
-- TODO: maybe use Split_String_Multi if ; not allows in message.
local pipe_name, temp = Lib.Split_String(pipe_name_id_message, ";")
local callback, message = Lib.Split_String(temp, ";")
-- Handle special commands.
-- Note: if the command not recognized, it just gets sent as-is.
if signal_name == "pipeWriteSpecial" then
-- Table of commands to consider.
if message == "package.path" then
-- Want to write out the current package.path.
message = "package.path:"..package.path
end
end
-- Pass to the scheduler.
Pipes.Schedule_Write(pipe_name, callback, message)
end
-- Cancel a read or write requests on the pipe.
function L.Handle_pipeCancelReads(_, pipe_name)
-- Pass to the descheduler.
Pipes.Deschedule_Reads(pipe_name)
end
function L.Handle_pipeCancelWrites(_, pipe_name)
-- Pass to the descheduler.
Pipes.Deschedule_Writes(pipe_name)
end
-- Check if a pipe is connected.
-- While id isn't important for this, it is included for interface
-- consistency and code reuse in the MD.
function L.Handle_pipeCheck(_, pipe_name_id)
-- Use find/sub for splitting instead.
local pipe_name, callback = Lib.Split_String(pipe_name_id, ";")
local success = pcall(L.Connect_Pipe, pipe_name)
-- Translate to strings that match read/write returns.
local message
if success then
message = "SUCCESS"
else
message = "ERROR"
end
-- Send back to md or lua.
if type(callback) == "string" then
L.Raise_Signal('pipeCheck_complete_'..callback, message)
elseif type(callback) == "function" then
callback(message)
end
end
-- Close a pipe.
-- This will not signal back, for now.
function L.Handle_pipeClose(_, pipe_name)
Pipes.Close_Pipe(pipe_name)
end
-- Flag a pipe to suppress paused reads.
function L.Handle_pipeSuppressPausedReads(_, pipe_name)
Pipes.Set_Suppress_Paused_Reads(pipe_name, true)
end
function L.Handle_pipeUnsuppressPausedReads(_, pipe_name)
Pipes.Set_Suppress_Paused_Reads(pipe_name, false)
end
-- Finalize initial setup.
Init()
-- On require(), just return the Pipes functions to other lua modules.
return Pipes |
object_draft_schematic_food_beastfood_fatty_meat_substitute = object_draft_schematic_food_shared_beastfood_fatty_meat_substitute:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_food_beastfood_fatty_meat_substitute, "object/draft_schematic/food/beastfood_fatty_meat_substitute.iff")
|
--Necro Maiden Of Macabre
function c700016.initial_effect(c)
--c:EnableCounterPermit(0x3001)
--recicle-GY
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(700016,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_BATTLE_DESTROYING)
e1:SetCondition(c700016.condition)
e1:SetOperation(c700016.desop)
c:RegisterEffect(e1)
--attackup
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(c700016.attackup)
c:RegisterEffect(e2)
--send a deck, destroy
local e01=Effect.CreateEffect(c)
e01:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e01:SetCategory(CATEGORY_DESTROY)
e01:SetDescription(aux.Stringid(700016,1))
e01:SetCode(EVENT_TO_GRAVE)
e01:SetCondition(c700016.condtion1)
e01:SetTarget(c700016.target2)
e01:SetOperation(c700016.operation2)
c:RegisterEffect(e01)
end
function c700016.condtion1(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetPreviousLocation()==LOCATION_DECK
end
function c700016.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_ONFIELD) end
if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c700016.operation2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c700016.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsRelateToBattle() and c:GetBattleTarget():IsType(TYPE_MONSTER)
end
function c700016.filter2(c)
return c:IsType(TYPE_MONSTER) --and c:IsSetCard(0x235)
end
function c700016.attackup(e,c)
local var=Duel.GetMatchingGroupCount(c700016.filter2,c:GetControler(),LOCATION_GRAVE,LOCATION_GRAVE,nil)
return (100*var)
end
function c700016.desop(e,tp,eg,ep,ev,re,r,rp)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and chkc:IsControler(1-tp) and c700016.filter2(chkc) end
if chk==0 then return (Duel.IsExistingTarget(c700016.filter2,tp,LOCATION_GRAVE,0,1,e:GetHandler()) or Duel.IsExistingTarget(c700016.filter2,1-tp,LOCATION_GRAVE,0,1,e:GetHandler())) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATODECK)
Duel.Hint(HINT_SELECTMSG,1-tp,HINTMSG_ATODECK)
local g=Duel.SelectTarget(tp,c700016.filter2,tp,LOCATION_GRAVE,0,1,1,e:GetHandler())
local g2=Duel.SelectTarget(1-tp,c700016.filter2,1-tp,LOCATION_GRAVE,0,1,1,e:GetHandler())
--local tc=Duel.GetFirstTarget()
if Duel.IsExistingTarget(c700016.filter2,tp,LOCATION_GRAVE,0,1,e:GetHandler()) or Duel.IsExistingTarget(c700016.filter2,1-tp,LOCATION_GRAVE,0,1,e:GetHandler()) then
--Duel.SendtoHand(g,ct,REASON_EFFECT)
Duel.SendtoDeck(g,nil,2,REASON_EFFECT)
Duel.SendtoDeck(g2,nil,2,REASON_EFFECT)
Duel.ConfirmCards(tp,g2)
Duel.ConfirmCards(1-tp,g)
end
end
|
local z=z
local timer=timer
local io=io
local naughty=require("naughty")
local ipairs=ipairs
local table=table
local utils=require("z.utils")
module("z.network.connections")
connections_panel=nil
listen_panel=nil
tor_panel=nil
all_panel=nil
established_panel=nil
visible=false
update_timer=nil
config={}
config.update_timeout=2
config.commands={}
config.commands.connections="/home/volcan/Development/awesome/configs/latest/utils/proc_net_table.py"
config.colors={
STATE_LISTEN='blue',
STATE_ESTABLISHED='red',
STATE_OTHER='green'
}
local connections_dump={}
local listening_ports={}
local tor_connections={}
local established_connections={}
local all_connections={}
function field_splitter(line)
local ret={}
local fields=z.utils.split(line,"%s")
ret.src_ip=z.utils.split(fields[1],":")[1]
ret.src_port=z.utils.split(fields[1],":")[2]
ret.dest_ip=z.utils.split(fields[2],":")[1]
ret.dest_port=z.utils.split(fields[2],":")[2]
ret.state=fields[3]
return ret
end
function color(color,text)
ret="<span color='"..color.."'>"..text.."</span>"
--ret=""..text.."</span>"
return ret
end
function paint_established(conn)
ret=""
if(conn.src_port==443) then
ret="<span color='red'> https://"..conn.src_ip.." "..conn.src_port.."</span>"
else
ret="<span color='white'>"..conn.src_ip.." "..conn.src_port.."</span>"
end
return ret
end
function display()
local all_list={'other'}
local listen_list={'listening'}
local established_list={'established'}
local tor_list={'tor'}
for idx,con in ipairs(all_connections) do
if(con.state=='LISTEN') then
--established
table.insert(listen_list,color(config.colors.STATE_LISTEN,con.src_port.." "..con.src_ip))
elseif (con.src_port == '8118' or con.dest_port=='8118' or con.src_port=='9050' or con.dest_port=='9050') then
table.insert(tor_list,color('green',con.src_ip..":"..con.src_port.." "..con.dest_ip..":"..con.dest_port))
elseif (con.state=='ESTABLISHED') then
txt=paint_established(con)
--table.insert(established_list,txt)
table.insert(established_list,color(config.colors.STATE_ESTABLISHED,con.src_port.." "..con.dest_ip..":"..con.dest_port))
else
table.insert(all_list , con.src_ip..":"..con.src_port.." "..con.dest_ip.." "..con.state)
end
--table.insert(all_list , con.src_ip.." "..con.dest_ip.." "..con.state)
end
listening_panel:set_payload({payload=listen_list})
listening_panel:update()
connections_panel:set_payload({payload=all_list})
connections_panel:update()
established_panel:set_payload({payload=established_list})
established_panel:update()
tor_panel:set_payload({payload=tor_list})
tor_panel:update()
end
function populate()
all_connections={}
listening_ports={}
if(connections_dump == nil)then return end
for idx,val in ipairs(connections_dump) do
local con=field_splitter(val)
if(con.state=='LISTEN') then
table.insert(listening_ports,con)
end
table.insert(all_connections,con)
end
end
function update_connections()
f=io.popen(config.commands.connections)
t=f:read("*a")
f:close()
t=utils.split(t,"\n")
connections_dump=t
-- connections_panel:set_payload({payload=t})
-- connections_panel:update()
populate()
display()
end
function onstart()
visible=true
connections_panel:show()
listening_panel:show()
established_panel:show()
tor_panel:show()
update_connections()
update_timer:start()
end
function onstop()
visible=false
update_timer:stop()
connections_panel:hide()
established_panel:hide()
listening_panel:hide()
tor_panel:hide()
end
function toggle()
if(visible==true) then onstop()
else onstart()
end
end
function init()
connections_panel=z.panel({rows=40,wibox_params={x=1075,y=225,opacity=0.9}})
listening_panel=z.panel({rows=20,wibox_params={x=1075,height=200,opacity=0.9}})
established_panel=z.panel({rows=40,wibox_params={x=0,y=225,opacity=0.9}})
tor_panel=z.panel({rows=15,wibox_params={x=0,height=200,opacity=0.9}})
update_timer=timer({timeout=config.update_timeout})
update_timer:connect_signal("timeout", function() update_connections() end )
-- toggle()
end
init()
|
#!/usr/bin/env tarantool
NAME = require('fio').basename(arg[0], '.lua')
fiber = require('fiber')
test_run = require('test_run').new()
util = require('util')
require('console').listen(os.getenv('ADMIN'))
cfg = rawget(_G, "cfg") or require('localcfg')
log = require('log')
if not cfg.shard_index then
cfg.shard_index = 'bucket_id'
end
vshard = require('vshard')
echo_count = 0
cfg.replication_connect_timeout = 3
cfg.replication_timeout = 0.1
vshard.storage.cfg(cfg, util.name_to_uuid[NAME])
function bootstrap_storage(engine)
box.once("testapp:schema:1", function()
if rawget(_G, 'CHANGE_SPACE_IDS') then
box.schema.create_space("CHANGE_SPACE_IDS")
end
local format = {{'id', 'unsigned'}, {'bucket_id', 'unsigned'}}
local s = box.schema.create_space('test', {engine = engine, format = format})
s:create_index('pk', {parts = {{'id'}}})
s:create_index(cfg.shard_index, {parts = {{'bucket_id'}}, unique = false})
local s2 = box.schema.create_space('test2', {engine = engine, format = format})
s2:create_index('pk', {parts = {{'id'}}})
s2:create_index(cfg.shard_index, {parts = {{'bucket_id'}}, unique = false})
box.schema.func.create('echo')
box.schema.role.grant('public', 'execute', 'function', 'echo')
box.schema.func.create('sleep')
box.schema.role.grant('public', 'execute', 'function', 'sleep')
box.schema.func.create('space_get')
box.schema.role.grant('public', 'execute', 'function', 'space_get')
box.schema.func.create('space_insert')
box.schema.role.grant('public', 'execute', 'function', 'space_insert')
box.schema.func.create('do_replace')
box.schema.role.grant('public', 'execute', 'function', 'do_replace')
box.schema.func.create('do_select')
box.schema.role.grant('public', 'execute', 'function', 'do_select')
box.schema.func.create('raise_luajit_error')
box.schema.role.grant('public', 'execute', 'function', 'raise_luajit_error')
box.schema.func.create('raise_client_error')
box.schema.role.grant('public', 'execute', 'function', 'raise_client_error')
box.schema.func.create('do_push')
box.schema.role.grant('public', 'execute', 'function', 'do_push')
box.snapshot()
end)
end
function echo(...)
echo_count = echo_count + 1
return ...
end
function space_get(space_name, key)
return box.space[space_name]:get(key)
end
function space_insert(space_name, tuple)
return box.space[space_name]:insert(tuple)
end
function do_replace(...)
box.space.test:replace(...)
return true
end
function do_select(...)
return box.space.test:select(...)
end
function sleep(time)
fiber.sleep(time)
return true
end
function raise_luajit_error()
assert(1 == 2)
end
function raise_client_error()
box.error(box.error.UNKNOWN)
end
function check_consistency()
for _, tuple in box.space.test:pairs() do
assert(box.space._bucket:get{tuple.bucket_id})
end
return true
end
function do_push(push, retval)
box.session.push(push)
return retval
end
--
-- Wait a specified log message.
-- Requirements:
-- * Should be executed from a storage with a rebalancer.
-- * NAME - global variable, name of instance should be set.
function wait_rebalancer_state(state, test_run)
log.info(string.rep('a', 1000))
vshard.storage.rebalancer_wakeup()
while not test_run:grep_log(NAME, state, 1000) do
fiber.sleep(0.1)
vshard.storage.rebalancer_wakeup()
end
end
|
local function playerVehicleEnter(vehicle)
-- Set the vehicle's radio station
local vehicleRadioStation = getElementData(vehicle, "radioStation", false)
if not vehicleRadioStation then
setRadioChannel(0)
else
setRadioChannel(vehicleRadioStation)
end
end
addEventHandler("onClientPlayerVehicleEnter", localPlayer, playerVehicleEnter)
local function playerRadioSwitch(stationID)
-- If the player is not in one of the front seats, don't let them change the station
if getPedOccupiedVehicleSeat(localPlayer) > 1 then
cancelEvent()
end
-- Sync the radio station over the network
setElementData(getPedOccupiedVehicle(localPlayer), "radioStation", stationID, true)
end
addEventHandler("onClientPlayerRadioSwitch", localPlayer, playerRadioSwitch)
|
local AddonName, AddonTable = ...
-- [Raid] Karazhan: 10 Normal
AddonTable.kara = {
30642,
-- Servant's Quarters
30686,
30687,
30684,
30685,
30677,
30675,
30678,
30676,
30681,
30680,
30683,
30682,
-- Attumen the Huntsman
30480,
28504,
28509,
28453,
28477,
28454,
28502,
28503,
28505,
28506,
28508,
28507,
28510,
-- Moroes
22559,
138797,
28524,
28525,
28530,
28529,
28570,
28567,
28566,
28565,
28569,
28545,
28528,
-- Maiden of Virtue
28522,
28516,
28511,
28515,
28512,
28514,
28520,
28519,
28518,
28521,
28517,
-- Opera Hall
28573,
28587,
28584,
28572,
28588,
28581,
28583,
28593,
28586,
28589,
28582,
28578,
28591,
28594,
28585,
28590,
28579,
-- The Curator
29757,
29758,
29756,
28633,
28631,
28647,
28612,
28621,
28649,
-- Shade of Aran
22560,
138798,
28673,
28728,
28671,
28674,
28726,
28666,
28672,
28663,
28670,
28669,
28675,
28727,
-- Terestian Illhoof
22561,
138799,
28658,
28657,
28660,
28653,
28662,
28652,
28655,
28656,
28654,
28661,
28785,
-- Netherspite
28729,
28734,
28732,
28744,
28731,
28743,
28735,
28733,
28742,
28740,
28741,
28730,
-- Chess Event
28749,
28754,
28756,
28745,
28755,
28750,
28751,
28748,
28747,
28746,
28752,
28753,
-- Prince Malchezaar
29760,
29761,
29759,
28773,
28771,
28768,
28770,
28767,
28772,
28762,
28764,
28766,
28765,
28763,
28757,
}
|
local files = require 'files'
local vm = require 'vm'
local lang = require 'language'
local guide = require 'parser.guide'
local config = require 'config'
local define = require 'proto.define'
local await = require 'await'
local noder = require 'core.noder'
local types = {'getglobal', 'getfield', 'getindex', 'getmethod'}
---@async
return function (uri, callback)
local ast = files.getState(uri)
if not ast then
return
end
local cache = {}
guide.eachSourceTypes(ast.ast, types, function (src) ---@async
if src.type == 'getglobal' then
local key = src[1]
if not key then
return
end
if config.get(uri, 'Lua.diagnostics.globals')[key] then
return
end
if config.get(uri, 'Lua.runtime.special')[key] then
return
end
end
local id = noder.getID(src)
if not id then
return
end
if cache[id] == false then
return
end
if cache[id] then
callback {
start = src.start,
finish = src.finish,
tags = { define.DiagnosticTag.Deprecated },
message = cache[id].message,
data = cache[id].data,
}
end
await.delay()
if not vm.isDeprecated(src, true) then
cache[id] = false
return
end
await.delay()
local defs = vm.getDefs(src)
local validVersions
for _, def in ipairs(defs) do
if def.bindDocs then
for _, doc in ipairs(def.bindDocs) do
if doc.type == 'doc.version' then
validVersions = vm.getValidVersions(doc)
break
end
end
end
end
local message = lang.script.DIAG_DEPRECATED
local versions
if validVersions then
versions = {}
for version, valid in pairs(validVersions) do
if valid then
versions[#versions+1] = version
end
end
table.sort(versions)
if #versions > 0 then
message = ('%s(%s)'):format(message
, lang.script('DIAG_DEFINED_VERSION'
, table.concat(versions, '/')
, config.get(uri, 'Lua.runtime.version'))
)
end
end
cache[id] = {
message = message,
data = {
versions = versions,
},
}
callback {
start = src.start,
finish = src.finish,
tags = { define.DiagnosticTag.Deprecated },
message = message,
data = {
versions = versions,
}
}
end)
end
|
-- Magic class
-- LGPL Juan Belón Pérez
-- videojuegos.ser3d.es
-- 2011
Magic = class()
function Magic:init(ps)
self.ps = ps
self.p = {}
for i=0,ps do
self.p[i]= {x=math.random(WIDTH*10)/10,
y=math.random(HEIGHT*10)/10, ox=0.0, oy=0.0, vx=math.random(20)-10,
vy=math.random(20)-10}
end
self.color = color(223, 255, 0, 255)
end
function Magic:draw()
local p = self.p
noSmooth()
--background(10,10,20)
fill(255,0,0)
stroke(self.color)
strokeWidth(3)
for i=0,self.ps do
p[i].ox= p[i].x
p[i].oy= p[i].y
p[i].x = p[i].x + p[i].vx
p[i].y = p[i].y + p[i].vy
if p[i].x<0 then
p[i].x=0
p[i].vx= -p[i].vx
end
if p[i].y<0 then
p[i].y=0
p[i].vy= -p[i].vy
end
if p[i].x>WIDTH then
p[i].x=WIDTH
p[i].vx= -p[i].vx
end
if p[i].y>HEIGHT then
p[i].y=HEIGHT
p[i].vy= -p[i].vy
end
p[i].vx = p[i].vx*0.98
p[i].vy = p[i].vy*0.98
line(p[i].ox, p[i].oy, p[i].x, p[i].y)
end
end
function Magic:touched(t)
local a = 5
local p = self.p
for i=0,self.ps do
local d= (p[i].x-t.x)*(p[i].x-t.x) + (p[i].y-t.y)*(p[i].y-t.y)
d= math.sqrt(d)
p[i].vx = p[i].vx - a/d*(p[i].x-t.x)
p[i].vy = p[i].vy - a/d*(p[i].y-t.y)
end
end
|
--[[
New SHODAN design.
Primary dataloop:
- map network including running tasks
- annotate map entries with:
- desired tasks
- tasks in progress (from the ps of other nodes)
- priority level
- generate ordered task queue and unordered thread queue from network map
- assign tasks, keeping track of the one that's meant to finish soonest
- sleep until then + 1 second
TODO:
- upgrade SPU software as needed
- detect lameduck dedis and stop scheduling tasks on them
]]
---- Immutable setting stuff ----
-- How much money we want to try to hack from a system each time we hack it.
local HACK_RATIO = 0.1
-- Server needs at least this much money before we even consider hacking it.
local MIN_MONEY_FOR_HACK = 2e6
-- How much we try to grow each server between hacks.
local GROWTH_FACTOR = 2
-- What the shortest time we're willing to sleep is. Small values can adversely
-- affect performance once we have a very large swarm.
local MIN_SLEEP_TIME = 1.0
-- How much memory do we reserve on home for user scripts.
local HOME_RAM_RESERVED = 256
-- SPU information.
local SPU_NAME = "/bin/spu.L.ns"
local SPU_RAM = ns:getScriptRam(SPU_NAME)
local SPU_FILES = { "/lib/lua.ns", SPU_NAME };
---- Mutable state ----
-- Map from hostname to how much money we want the host to have before we hack it.
-- Stored separately from the network map as the only inherently stateful part of
-- the whole thing, since we can't figure this out just by looking at each host.
local TARGET_MONEY = {}
---- Setup ----
local log = require 'log'
local net = require 'net'
for _,fn in ipairs {
"sleep", "getServerRam", "getServerNumPortsRequired", "scan", "exec", "scp",
"getServerSecurityLevel", "getServerMinSecurityLevel", "getServerMoneyAvailable",
"getServerMaxMoney", "getServerRequiredHackingLevel", "getHackingLevel",
"brutessh", "ftpcrack", "httpworm", "sqlinject", "relaysmtp",
} do
ns:disableLog(fn)
end
function main(...)
-- log.setlevel("debug", "warn")
while true do
local network,sleep = analyzeNetwork(mapNetwork())
local tasks = generateTasks(network)
sleep = math.max(math.min(sleep, assignTasks(network, tasks)) + 0.1, MIN_SLEEP_TIME)
writeTSV("/run/shodan/network.txt", network,
{"host", "max_threads", "threads", "weaken", "grow", "hack", "priority", "money", "max_money"})
if sleep == math.huge then
log.warn("Sleep was infinite, resetting to 5 minutes")
sleep = 5*60
end
if ... == "once" then
printf("Would sleep for: %f", sleep)
break
else
log.info("Sleeping for %f seconds.", sleep)
ns:sleep(sleep)
end
end
end
---- Network mapping and host analysis ----
-- We special-case home by reserving HOME_RAM_RESERVED memory on it for the
-- user and allocating the rest to SPUs.
function scanHome()
local info = net.stat('home')
info.max_threads = math.floor(math.max(0, info.ram - HOME_RAM_RESERVED)/SPU_RAM)
info.threads = info.max_threads
for _,proc in ipairs(info.ps) do
if proc.filename == SPU_NAME then
info.threads = info.threads - proc.threads
end
end
return info
end
-- Return a hostname => host_stat_t map with information about everything we
-- can reach on the network.
function mapNetwork()
local network = {}
local swarm_size = 0
local function scanHost(host, depth)
if host == "home" then
local info = scanHome()
swarm_size = swarm_size + info.max_threads
network[host] = info
return true
end
tryPwn(host)
local info = net.stat(host)
if not info.root then
info.max_threads = 0
info.threads = 0
else
installSPU(info)
info.max_threads = math.floor(info.ram/SPU_RAM)
info.threads = math.floor((info.ram - info.ram_used)/SPU_RAM)
swarm_size = swarm_size + info.max_threads
end
preTask(info)
network[host] = info
return true
end
log.debug("Performing full network scan.");
net.walk(scanHost, ns:getHostname())
log.debug("Network scan complete. %d threads available for SPUs.", swarm_size);
return network,swarm_size
end
-- Appease the RAM checker
-- ns:brutessh() ns:ftpcrack() ns:relaysmtp() ns:httpworm() ns:sqlinject()
function tryPwn(host)
if ns:hasRootAccess(host) then return end
log.debug("Trying to pwn %s", host)
local ports = ns:getServerNumPortsRequired(host)
for _,spike in ipairs { "brutessh", "ftpcrack", "relaysmtp", "httpworm", "sqlinject" } do
if ns:fileExists(spike .. ".exe") then
ns[spike](ns, host)
ports = ports - 1
end
end
if ports <= 0 then
ns:nuke(host)
log.info("Root access gained on %s", host)
end
end
function isHackable(info)
return info.root and info.max_money > 0 and info.hack_level <= ns:getHackingLevel()
end
-- Generate "pre-task" information about how much we want to weaken/hack/grow this
-- host and how much money we want it to have.
function preTask(info)
local host = info.host
if isHackable(info) then
TARGET_MONEY[host] = TARGET_MONEY[host] or info.money:max(MIN_MONEY_FOR_HACK):min(info.max_money)
info.hack_pending = 0
info.weaken_pending = 0
info.grow_pending = 0
info.weaken = math.ceil((info.security - info.min_security) / 0.05)
if info.money > 0 then
info.grow = math.ceil(math.max(0,
ns:growthAnalyze(host, math.max(1.0, TARGET_MONEY[host]/info.money))))
else
-- If the target has no money, only generate a "probing" grow to generate
-- *some* money so that growthAnalyze will work the next time.
info.grow = 1
end
if info.hack_fraction > 0 then
info.hack = info.money >= TARGET_MONEY[host] and math.ceil(HACK_RATIO/info.hack_fraction) or 0
else
info.hack = 0
end
log.debug("%s T=%d WGH %f/%f/%f %s/%s",
info.host, info.threads, info.weaken, info.grow, info.hack,
tomoney(info.money), tomoney(TARGET_MONEY[host]))
else
TARGET_MONEY[host] = nil
end
end
local SPU_INSTALLED = {}
function installSPU(info)
for _,file in ipairs(info.ls) do
if file == '/bin/spu.L.ns' and SPU_INSTALLED[info.host] then return end
end
for _,file in ipairs(SPU_FILES) do
ns:scp(file, info.host)
end
SPU_INSTALLED[info.host] = true
log.info("SPU software installed on %s", info.host)
end
-- Generate ancillary data about the network that requires analyzing the whole
-- network: the per-host priority and the pending tasks per target.
-- Returns the annotated network map and the estimated time until the next
-- currently running SPU task completes.
function analyzeNetwork(network, swarm_size)
-- First calculate priority based on the *desired* weaken/grow/hack
-- jobs in conjunction with the swarm size.
for host,info in pairs(network) do
if TARGET_MONEY[host] then
info.priority = calcEfficiency(info, TARGET_MONEY[host], swarm_size)
log.debug("Calculating priority for %s: %f", host, info.priority)
end
end
-- Then calculate how much we're doing already, and thus, how much we actually
-- want to do.
-- Also, find existing tasks and figure out which ones will finish soonest.
local next_task_completion = math.huge
for host,info in pairs(network) do
for _,proc in ipairs(info.ps) do
if proc.filename == SPU_NAME then
local task,target,time = proc.args[0],proc.args[1],tonumber(proc.args[2])
network[target][task.."_pending"] = network[target][task.."_pending"] + proc.threads
next_task_completion = math.min(next_task_completion, time)
end
end
end
return network,math.max(0, next_task_completion - ns:getTimeSinceLastAug()/1000)
end
-- Attempt to determine the priority (i.e money-per-time) of focusing hacks
-- on this server.
-- This is based on:
-- - the per-hack money, based on the HACK_RATIO or the amount of money we'll hack
-- with one thread, whichever is more
-- - the time it takes to hack it
-- - the time it takes to execute all pending weaken tasks divided by the total
-- size of the swarm
-- - the time it takes to execute all pending grow tasks, plus the time it takes
-- to execute the weaken tasks that would generate
function calcEfficiency(info, target_money, swarm_size)
return target_money * math.max(info.hack_fraction, HACK_RATIO)
/ (info.hack_time * math.ceil(info.hack/swarm_size)
+ info.weaken_time * (info.weaken + 0.004 * info.grow) * math.ceil(info.weaken/swarm_size)
+ info.grow_time * info.grow * math.ceil(info.grow/swarm_size))
end
---- Task generation ----
-- Return a sorted list of tasks, all of the form
-- { host=foo, action=bar, threads=N, priority=P }
function generateTasks(network)
local tasks = {}
for host,info in pairs(network) do
generateTasksForHost(tasks, info)
end
table.sort(tasks, taskOrdering)
return tasks
end
function generateTasksForHost(tasks, info)
if not TARGET_MONEY[info.host] then return end
-- Rank is more significant than priority when ordering.
-- We have these separate fields because it's hard to come up with a constant
-- factor we can modify priority by that will consistently give us the right
-- results no matter how weird the server money numbers get.
local rank = 3
for _,action in ipairs {"weaken", "grow", "hack"} do
if info[action] > 0 then
local task = { host=info.host; action=action; threads=info[action];
pending=math.min(info[action.."_pending"], info[action]);
rank=rank; priority=info.priority; time=info[action.."_time"] }
log.debug("Task: %s %s (x%f) t=%f P=%d/%f", task.action, task.host, task.threads,
task.time, task.rank, task.priority)
table.insert(tasks, task)
rank = rank - 1
end
end
-- Insert a "fallback" task for growing the host, ordered by how far each host
-- is away from its max money.
local fallback_grow = math.ceil(ns:growthAnalyze(info.host, info.max_money/(math.max(info.money, 0.01)))) - info.grow
if fallback_grow > 0 then
local task = { host=info.host; action="grow"; threads=fallback_grow;
pending=math.max(0, info.grow_pending - info.grow);
rank=0; priority=-fallback_grow; time=info.grow_time }
log.debug("Fallback: %s %s (x%d) t=%f P=%d/%f", task.action, task.host, task.threads,
task.time, task.rank, task.priority)
table.insert(tasks, task)
end
end
-- Ordering function for individual tasks.
-- Rank is given the biggest weight, with higher rank => more important task.
-- Within rank, we order by priority.
-- In practice, this means that it will bin together all hacks on systems that
-- need neither grow nor weaken, all grows on systems that don't need weakens,
-- and all weakens on the remainder, then order them by priority.
-- After those, it bins together grows blocked on weakens and hacks blocked on grows
-- And after those, hacks blocked on both grow and weaken.
function taskOrdering(t1, t2)
if t1.rank ~= t2.rank then return t1.rank < t2.rank end
return t1.priority < t2.priority
end
---- Task assignment ----
-- Given a network of hosts we can possibly run SPUs on, and an ordered list of
-- tasks, most important at the end, attempts to run SPUs to attack as many of
-- the tasks as possible.
function assignTasks(network, tasks)
local idx = #tasks
local function next_task()
if idx == 0 then return nil end
local task = tasks[idx]
idx = idx - 1
return task
end
local task = next_task()
local min_time = math.huge
for host,info in pairs(network) do
log.debug("Scheduling tasks on %s (%d/%d threads)", host, info.threads, info.max_threads)
while task do
if info.threads <= 0 then break end -- next host
if task.pending >= task.threads then -- next task
task = next_task()
if not task then break end -- ran out of tasks before running out of hosts!
if task.action == "hack" then
TARGET_MONEY[task.host] = math.min(
TARGET_MONEY[task.host] * GROWTH_FACTOR, network[task.host].max_money)
end
else
log.debug("Scheduling task %s %s [%.0f]", task.action, task.host, task.threads)
local threads = math.min(task.threads - task.pending, info.threads)
runSPU(host, threads, task.action, task.host, task.time)
task.pending = task.pending + threads
info.threads = info.threads - threads
min_time = math.min(min_time, task.time)
log.debug("Deployed SPU [%s %s]×%d on %s, %d threads left",
task.action, task.host, threads, host, info.threads)
end
end
end
recordTaskState(tasks)
return min_time
end
function runSPU(host, threads, action, target, time)
log.debug("SPU: %s[%d]: %s %s", host, threads, action, target)
ns:exec(SPU_NAME, host, threads, action, target, ns:getTimeSinceLastAug()/1000 + time)
end
---- State file writing ----
-- At minimum we want:
-- the set of assigned tasks
-- the set of pending tasks
-- the set of nodes we can run tasks on (that might go entirely in the UI)
-- the set of nodes we can run hacks against (same)
-- the set of currently running SPUs
function writeTSV(file, data, fields)
local buf = {}
for _,field in ipairs(fields) do table.insert(buf, field) end
buf = {table.concat(buf, "\t")}
for _,item in ipairs(data) do
local line = {}
for _,field in ipairs(fields) do table.insert(line, tostring(item[field])) end
table.insert(buf, table.concat(line, "\t"))
end
for k,item in pairs(data) do
if type(k) ~= "number" then
local line = {}
for _,field in ipairs(fields) do table.insert(line, tostring(item[field])) end
table.insert(buf, table.concat(line, "\t"))
end
end
ns:write(file, table.concat(buf, "\n"), "w")
end
function recordTaskState(tasks)
writeTSV("/run/shodan/tasks.txt", tasks,
{"threads", "pending", "action", "host", "time"})
end
---- Entry point ----
return main(...)
|
-- language specific higlights
local lush = require("lush")
local base = require("apprentice.base")
local styles = require("apprentice.settings").styles
local table_concat = table.concat
local M = {}
M = lush(function()
return {
htmlTag {base.ApprenticeAquaBold},
htmlEndTag {base.ApprenticeAquaBold},
htmlTagName {base.ApprenticeBlue},
htmlArg {base.ApprenticeOrange},
htmlScriptTag {base.ApprenticePurple},
htmlTagN {base.ApprenticeFg1},
htmlSpecialTagName {base.ApprenticeBlue},
htmlSpecialChar {base.ApprenticeRed},
htmlLink {fg = base.ApprenticeFg4.fg.hex, gui = styles.underline},
htmlBold {fg = base.ApprenticeFg1.fg.hex, gui = styles.bold},
htmlBoldUnderline {
fg = base.ApprenticeFg1.fg.hex,
gui = table_concat({styles.bold, styles.underline}, ","),
},
htmlBoldItalic {
fg = base.ApprenticeFg1.fg.hex,
gui = table_concat({styles.bold, styles.italic_strings}, ","),
},
htmlBoldUnderlineItalic {
fg = base.ApprenticeFg1.fg.hex,
gui = table_concat({styles.bold, styles.italic_strings}, ","),
},
htmlItalic {fg = base.ApprenticeFg1.fg.hex, gui = styles.italic_strings},
}
end)
return M
|
local timer = 0
local UPDATE_INTERVAL = 60
local CHECK_BUFF_MIN_MINUTES = 10
local buffMap = {}
local addonName = "ShowMyTime"
local onEvent = {}
local frame = CreateFrame("Frame", addonName, nil)
local customEvent = "UNIT_AURA"
local maxIndex = 40
local lastReport = 0
function onEvent.UNIT_AURA(event, ...)
INIT_BUFF_MAP()
PRINT_EXPIRABLE_BUFF()
end
function INIT_BUFF_MAP()
-- initialize buff map
for k,v in pairs(buffMap) do
buffMap[k] = nil
end
for i=1, maxIndex do
local name,_,_,_,duration,expirationTime,_,_,_,spellId = UnitAura("player", i)
if name == nil then
return
end
if duration > 0 and spellId ~= 2479 then
if buffMap[name] == nil then
buffMap[name] = expirationTime
end
end
end
end
function PRINT_EXPIRABLE_BUFF()
if next(buffMap) == nil then
return
end
local currentTime = GetTime()
if lastReport > 0 then
local elapsedFromLast = currentTime - lastReport
if elapsedFromLast < 60 then
return
end
end
lastReport = currentTime
for name, expires in pairs(buffMap) do
local remainingSeconds = expires - currentTime
if remainingSeconds <= 0 then
print(name .. " expired.")
buffMap[name] = nil
return
end
local remainingMinutes = remainingSeconds / 60
if remainingMinutes < CHECK_BUFF_MIN_MINUTES then
remainingMinutes = math.floor(remainingMinutes)
print(name .. " remaining " .. remainingMinutes .. " minutes. Less than " .. CHECK_BUFF_MIN_MINUTES .. " minutes.")
end
end
end
-- CALLED EVERY ELASPED SECONDS (REF YOUR FPS)
function ON_UPDATE(elapsed)
timer = timer + elapsed
if timer < UPDATE_INTERVAL then
return
end
timer = 0
if next(buffMap) == nil then
return
end
PRINT_EXPIRABLE_BUFF()
end
frame:RegisterUnitEvent(customEvent, "player")
frame:SetScript("OnEvent", function(self, event, ...) onEvent[event](onEvent, ...) end)
frame:SetScript("OnUpdate", function(self, elapsed) ON_UPDATE(elapsed) end) |
isPolice = false
inServicePolice = false
dragStatus = {}
dragStatus.isDragged = false
identityStats = nil
vehicleStats = nil
orgByService = {["police"] = "~b~Dept. de la justice",["fbi"] = "~b~Agence fédérale"}
local menuThread = false
local blips = {}
local isHandcuffed = false
RMenu.Add("police_dynamicmenu", "police_dynamicmenu_main", RageUI.CreateMenu("Tablette de police","Interactions possibles"))
RMenu:Get("police_dynamicmenu", "police_dynamicmenu_main").Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_citizen', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_main'), "Interactions citoyens", "Interactions avec un citoyen"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_citizen').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_veh', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_main'), "Interactions véhicules", "Interactions avec un véhicule"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_veh').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_carinfos', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_veh'), "Informations véhicule", "Informations du véhicule"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_carinfos').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_identity', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_citizen'), "Carte d'identité", "Carte d'identité de la personne"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_identity').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_bs', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_citizen'), "Fouille", "Inventaire de la personne"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_bs').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_licence', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_citizen'), "Licence", "Licence de la personne"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_licence').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_codes', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_main'), "Communications radio", "Communication avec le reste des effectifs"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_codes').Closed = function()end
-- FBI
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_adrlaunch', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_main'), "Avis de recherche", "Lancer un avis de recherche"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_adrlaunch').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_adr', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_main'), "Avis de recherche", "Consulter les avis de recherche"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_adr').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_adrcheck', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_adr'), "Avis de recherche", "Consulter un avis de recherche"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_adrcheck').Closed = function()end
RMenu.Add('police_dynamicmenu', 'police_dynamicmenu_announce', RageUI.CreateSubMenu(RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_main'), "Annonce fédérale", "Émettre une annonce fédérale"))
RMenu:Get('police_dynamicmenu', 'police_dynamicmenu_announce').Closed = function()end
local policeOpen = false
local function jobMenu()
if menuThread then return end
menuThread = true
if not policeOpen then
policeOpen = true
Citizen.CreateThread(function()
while isPolice do
if IsControlJustPressed(1, 167) then
Wait(500)
RageUI.Visible(RMenu:Get("police_dynamicmenu",'police_dynamicmenu_main'), not RageUI.Visible(RMenu:Get("police_dynamicmenu",'police_dynamicmenu_main')))
end
Citizen.Wait(1)
end
menuThread = false
end)
end
end
local function jobChanged()
if ESX.PlayerData.job.name == "police" or ESX.PlayerData.job.name == "fbi" then
isPolice = true
inServicePolice = false
pzCore.mug("Statut de service",orgByService[ESX.PlayerData.job.name],"Vous êtes actuellement considéré comme étant ~r~hors service~s~. Vous pouvez changer ce statut avec votre menu ~o~[F6]")
jobMenu()
else
isPolice = false
inServicePolice = false
menuThread = false
end
end
local function init()
menuThread = false
isPolice = true
inServicePolice = false
pzCore.mug("Statut de service",orgByService[ESX.PlayerData.job.name],"Vous êtes actuellement considéré comme étant ~r~hors service~s~. Vous pouvez changer ce statut avec votre menu ~o~[F6]")
jobMenu()
end
function getInformations(player)
ESX.TriggerServerCallback('esx_policejob:getOtherPlayerData', function(data)
Citizen.SetTimeout(1100, function()
identityStats = data
end)
end, player)
end
local function getVehicleInfos(vehicleData)
ESX.TriggerServerCallback('esx_policejob:getVehicleInfos', function(data)
Citizen.SetTimeout(1100, function()
vehicleStats = data
end)
end, vehicleData.plate)
end
local function setUniform(uniform, playerPed)
TriggerEvent('skinchanger:getSkin', function(skin)
local uniformObject
if skin.sex == 0 then
uniformObject = pzCore.jobs[ESX.PlayerData.job.name].config[uniform].male
else
uniformObject = pzCore.jobs[ESX.PlayerData.job.name].config[uniform].female
end
if uniformObject then
TriggerEvent('skinchanger:loadClothes', skin, uniformObject)
if uniform == 6 then
SetPedArmour(playerPed, 100)
end
else
-- Rien
end
end)
end
local function getWeapon(weapon, ped)
local hash = GetHashKey(weapon)
GiveWeaponToPed(ped, hash, 10000, false, true)
end
local function spawnCar(car, ped)
local hash = GetHashKey(car)
local p = vector3(449.95, -1020.11, 28.44)
Citizen.CreateThread(function()
RequestModel(hash)
while not HasModelLoaded(hash) do Citizen.Wait(10) end
local vehicle = CreateVehicle(hash, p.x, p.y, p.z, 90.0, true, false)
TaskWarpPedIntoVehicle(PlayerPedId(), vehicle, -1)
end)
end
local function spawnHeli(heli, ped)
local hash = GetHashKey(heli)
local p = vector3(449.330, -981.193, 43.69)
Citizen.CreateThread(function()
RequestModel(hash)
while not HasModelLoaded(hash) do Citizen.Wait(10) end
local vehicle = CreateVehicle(hash, p.x, p.y, p.z, 180.0, true, false)
TaskWarpPedIntoVehicle(PlayerPedId(), vehicle, -1)
end)
end
local function setUniformJail(ped)
TriggerEvent('skinchanger:getSkin', function(skin)
local uniformObject
if skin.sex == 0 then
uniformObject = pzCore.jobs[ESX.PlayerData.job.name].config.jail.male
else
uniformObject = pzCore.jobs[ESX.PlayerData.job.name].config.jail.female
end
if uniformObject then
TriggerEvent('skinchanger:loadClothes', skin, uniformObject)
if uniform == 6 then
SetPedArmour(playerPed, 100)
end
else
-- Rien
end
end)
end
AddEventHandler('playerSpawned', function(spawn)
TriggerEvent('esx_policejob:unrestrain')
end)
RegisterNetEvent('esx_policejob:drag')
AddEventHandler('esx_policejob:drag', function(copId)
if isHandcuffed then
dragStatus.isDragged = not dragStatus.isDragged
dragStatus.CopId = copId
end
end)
RegisterNetEvent('esx_policejob:unrestrain')
AddEventHandler('esx_policejob:unrestrain', function()
if isHandcuffed then
local playerPed = PlayerPedId()
isHandcuffed = false
ClearPedSecondaryTask(playerPed)
SetEnableHandcuffs(playerPed, false)
DisablePlayerFiring(playerPed, false)
SetPedCanPlayGestureAnims(playerPed, true)
FreezeEntityPosition(playerPed, false)
DisplayRadar(true)
-- end timer
if Config.EnableHandcuffTimer and handcuffTimer.active then
ESX.ClearTimeout(handcuffTimer.task)
end
end
end)
RegisterNetEvent('esx_policejob:handcuff')
AddEventHandler('esx_policejob:handcuff', function()
isHandcuffed = not isHandcuffed
local playerPed = PlayerPedId()
if isHandcuffed then
RequestAnimDict('mp_arresting')
while not HasAnimDictLoaded('mp_arresting') do
Citizen.Wait(100)
end
TaskPlayAnim(playerPed, 'mp_arresting', 'idle', 8.0, -8, -1, 49, 0, 0, 0, 0)
SetEnableHandcuffs(playerPed, true)
DisablePlayerFiring(playerPed, true)
SetCurrentPedWeapon(playerPed, GetHashKey('WEAPON_UNARMED'), true) -- unarm player
SetPedCanPlayGestureAnims(playerPed, false)
FreezeEntityPosition(playerPed, true)
DisplayRadar(false)
else
ClearPedSecondaryTask(playerPed)
SetEnableHandcuffs(playerPed, false)
DisablePlayerFiring(playerPed, false)
SetPedCanPlayGestureAnims(playerPed, true)
FreezeEntityPosition(playerPed, false)
DisplayRadar(true)
end
end)
RegisterNetEvent("pz_core:police:code")
AddEventHandler("pz_core:police:code", function(typeIndex, index, typeDesc, codeDesc, _, _, name, initialLoc, src)
if isPolice and inServicePolice then
local mugshot, mugshotStr = ESX.Game.GetPedMugshot(GetPlayerPed(src))
ESX.ShowAdvancedNotification("Agent ~y~"..name, typeDesc, codeDesc, mugshotStr, 1)
UnregisterPedheadshot(mugshot)
if typeIndex > 1 and index <= 10 then
SendNUIMessage({
transactionType = 'playSound',
transactionFile = "callback",
transactionVolume = 1.0
})
Citizen.CreateThread(function()
local color = 47
local blip = AddBlipForCoord(initialLoc.x, initialLoc.y, initialLoc.z)
SetBlipSprite(blip, 162)
SetBlipAsShortRange(blip, false)
SetBlipColour(blip, color)
SetBlipScale(blip, 1.0)
SetBlipCategory(blip, 12)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Statut d'intervention ("..name..")")
EndTextCommandSetBlipName(blip)
Citizen.CreateThread(function()
while blip ~= nil do
Citizen.Wait(800)
if color == 47 then
color = 71
else
color = 47
end
SetBlipColour(blip, color)
if thiefBlip ~= nil then SetBlipColour(thiefBlip, color) end
end
end)
local thiefBlip = AddBlipForRadius(initialLoc.x, initialLoc.y, initialLoc.z, 40.0)
SetBlipHighDetail(thiefBlip, true)
SetBlipColour(thiefBlip, color)
SetBlipAlpha(thiefBlip, 200)
SetBlipAsShortRange(thiefBlip, true)
Citizen.SetTimeout(40000, function()
active = false
RemoveBlip(blip)
RemoveBlip(thiefBlip)
end)
end)
end
if index == 11 then
SendNUIMessage({
transactionType = 'playSound',
transactionFile = "code2",
transactionVolume = 1.0
})
Citizen.CreateThread(function()
local blip = AddBlipForCoord(initialLoc.x, initialLoc.y, initialLoc.z)
local color = 69
SetBlipSprite(blip, 304)
SetBlipAsShortRange(blip, false)
SetBlipColour(blip, color)
SetBlipScale(blip, 1.0)
SetBlipCategory(blip, 12)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Code 2")
EndTextCommandSetBlipName(blip)
local radius = AddBlipForCoord(initialLoc.x, initialLoc.y, initialLoc.z)
SetBlipSprite(radius, 161)
SetBlipScale(radius, 2.0)
SetBlipColour(radius, color)
PulseBlip(radius)
Citizen.CreateThread(function()
while blip ~= nil do
Citizen.Wait(600)
if color == 69 then
color = 37
else
color = 69
end
SetBlipColour(blip, color)
end
end)
Citizen.Wait(60000)
RemoveBlip(blip)
RemoveBlip(radius)
end)
end
if index == 12 then
SendNUIMessage({
transactionType = 'playSound',
transactionFile = "code3",
transactionVolume = 1.0
})
Citizen.CreateThread(function()
local blip = AddBlipForCoord(initialLoc.x, initialLoc.y, initialLoc.z)
local color = 47
SetBlipSprite(blip, 304)
SetBlipAsShortRange(blip, false)
SetBlipColour(blip, color)
SetBlipScale(blip, 1.0)
SetBlipCategory(blip, 12)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Code 3")
EndTextCommandSetBlipName(blip)
local radius = AddBlipForCoord(initialLoc.x, initialLoc.y, initialLoc.z)
SetBlipSprite(radius, 161)
SetBlipScale(radius, 2.0)
SetBlipColour(radius, color)
PulseBlip(radius)
Citizen.CreateThread(function()
while blip ~= nil do
Citizen.Wait(400)
if color == 47 then
color = 37
else
color = 47
end
SetBlipColour(blip, color)
end
end)
Citizen.Wait(60000)
RemoveBlip(blip)
RemoveBlip(radius)
end)
end
if index == 13 then
SendNUIMessage({
transactionType = 'playSound',
transactionFile = "code99",
transactionVolume = 1.0
})
Citizen.CreateThread(function()
local blip = AddBlipForCoord(initialLoc.x, initialLoc.y, initialLoc.z)
local color = 59
SetBlipSprite(blip, 304)
SetBlipAsShortRange(blip, false)
SetBlipColour(blip, color)
SetBlipScale(blip, 1.0)
SetBlipCategory(blip, 12)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Code 99")
EndTextCommandSetBlipName(blip)
local radius = AddBlipForCoord(initialLoc.x, initialLoc.y, initialLoc.z)
SetBlipSprite(radius, 161)
SetBlipScale(radius, 2.0)
SetBlipColour(radius, color)
PulseBlip(radius)
Citizen.CreateThread(function()
while blip ~= nil do
Citizen.Wait(150)
if color == 59 then
color = 37
else
color = 59
end
SetBlipColour(blip, color)
end
end)
Citizen.Wait(60000)
RemoveBlip(blip)
RemoveBlip(radius)
end)
end
end
end)
RegisterNetEvent('esx_policejob:putInVehicle')
AddEventHandler('esx_policejob:putInVehicle', function()
if isHandcuffed then
local playerPed = PlayerPedId()
local coords = GetEntityCoords(playerPed)
if IsAnyVehicleNearPoint(coords, 5.0) then
local vehicle = GetClosestVehicle(coords, 5.0, 0, 71)
if DoesEntityExist(vehicle) then
local maxSeats, freeSeat = GetVehicleMaxNumberOfPassengers(vehicle)
for i=maxSeats - 1, 0, -1 do
if IsVehicleSeatFree(vehicle, i) then
freeSeat = i
break
end
end
if freeSeat then
TaskWarpPedIntoVehicle(playerPed, vehicle, freeSeat)
dragStatus.isDragged = false
end
end
end
end
end)
RegisterNetEvent('esx_policejob:OutVehicle')
AddEventHandler('esx_policejob:OutVehicle', function()
local playerPed = PlayerPedId()
if IsPedSittingInAnyVehicle(playerPed) then
local vehicle = GetVehiclePedIsIn(playerPed, false)
TaskLeaveVehicle(playerPed, vehicle, 64)
end
end)
local function createBlip()
local policeDept = vector3(442.69, -983.51, 30.68)
local blip = AddBlipForCoord(policeDept.x, policeDept.y, policeDept.z)
SetBlipSprite(blip, 60)
SetBlipAsShortRange(blip, true)
SetBlipColour(blip, 38)
SetBlipScale(blip, 1.0)
SetBlipCategory(blip, 12)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Commissariat")
EndTextCommandSetBlipName(blip)
end
Citizen.CreateThread(function()
local wasDragged
while true do
Citizen.Wait(0)
local playerPed = PlayerPedId()
if isHandcuffed and dragStatus.isDragged then
local targetPed = GetPlayerPed(GetPlayerFromServerId(dragStatus.CopId))
if DoesEntityExist(targetPed) and IsPedOnFoot(targetPed) and not IsPedDeadOrDying(targetPed, true) then
if not wasDragged then
AttachEntityToEntity(playerPed, targetPed, 11816, 0.54, 0.54, 0.0, 0.0, 0.0, 0.0, false, false, false, false, 2, true)
wasDragged = true
else
Citizen.Wait(1000)
end
else
wasDragged = false
dragStatus.isDragged = false
DetachEntity(playerPed, true, false)
end
elseif wasDragged then
wasDragged = false
DetachEntity(playerPed, true, false)
else
Citizen.Wait(500)
end
end
end)
local current = "police"
pzCore.jobs[current].jobMenu = jobMenu
pzCore.jobs[current].setUniform = setUniform
pzCore.jobs[current].getWeapon = getWeapon
pzCore.jobs[current].spawnCar = spawnCar
pzCore.jobs[current].spawnHeli = spawnHeli
pzCore.jobs[current].setUniformJail = setUniformJail
pzCore.jobs[current].init = init
pzCore.jobs[current].jobChanged = jobChanged
pzCore.jobs[current].getIdentity = getInformations
pzCore.jobs[current].getVehicleInfos = getVehicleInfos
pzCore.jobs[current].hasBlip = true
pzCore.jobs[current].createBlip = createBlip
|
local progression = require "crit.progression"
local monarch = require "monarch.monarch"
local M = {}
function M.show(screen_id, data, options)
options = options or {}
if options.sequential == nil then
options.sequential = true
end
screen_id = hash(screen_id)
local fork = progression.fork(function ()
progression.wait_for_message(monarch.SCREEN_TRANSITION_IN_STARTED, function (_, message)
return message.screen == screen_id
end)
end)
local callback, wait_for_callback = progression.make_callback()
callback = progression.with_context(callback)
monarch.show(screen_id, options, data, callback)
progression.join(fork)
return wait_for_callback
end
function M.replace(screen_id, data, options)
options = options or {}
if options.pop == nil then
options.pop = 1
end
return M.show(screen_id, data, options)
end
function M.back(data)
local callback, wait_for_callback = progression.make_callback()
callback = progression.with_context(callback)
monarch.back(data, callback)
return wait_for_callback
end
return M
|
function onUnitDeath(star, unit)
for i = 0, 25 do
local randAngle = Random.randFloat(0, 360)
newProj = Projectile.new("FLAK")
newProj:setPos(unit:getPos())
newProj:setRotation(randAngle)
newProj:setAllegiance(unit:getAllegiance())
star:addProjectile(newProj)
end
end |
local p = (require 'gamestate._level')()
local Signal = require 'lib.hump.signal'
function p:draw()
p.paper()
p.sky(235, 82, 16)
p.sea(89, 116, 194, false)
p.fly(function () Signal.emit('next_level') end)
p.border()
end
return p
|
local f = load("print('hello')")
f()
--> =hello
do
local env = {x = 1}
local f = load("x = 2", "chunk", "bt", env)
print(env.x)
--> =1
f()
print(env.x)
--> =2
end
load("print(...)")(1, 2)
--> =1 2
-- This loads and executes the given file
loadfile("lua/loadfile.lua.notest")()
--> =loadfile
loadfile("lua/loadfile.lua.notest", "t", {print=print, ggg = "global"})()
--> =global
print(pcall(loadfile, "lua/loadfile.lua.notest", 123))
--> ~false\t.*must be a string
print(loadfile("lua/nonexistent_file"))
--> ~nil\t
dofile("lua/loadfile.lua.notest")
--> =loadfile
load(coroutine.wrap(function ()
coroutine.yield("print(")
coroutine.yield("'hello')")
end))()
--> =hello
load(coroutine.wrap(function ()
coroutine.yield("print(")
coroutine.yield("'abc')")
coroutine.yield("")
coroutine.yield("print(")
coroutine.yield("'xyz')")
end))()
--> =abc
print(load(function() error("argh") end))
--> ~nil\t.*argh
print(load(function() return {} end))
--> ~nil\t.*must return a string
print(pcall(load, {}))
--> ~false\t.*string or function
print(load("\x00", "", "t"))
--> ~nil\t.*invalid token
print(load("hi", "", "b"))
--> ~nil\t.*text chunk
local z = "haha"
load(string.dump(function() print("hi", z) end))()
--> =hi nil
print(load("???", "", "t"))
--> ~nil\t.*invalid token |
env.info( '*** MOOSE DYNAMIC INCLUDE START *** ' )
local base = _G
__Moose = {}
__Moose.Include = function( IncludeFile )
if not __Moose.Includes[ IncludeFile ] then
__Moose.Includes[IncludeFile] = IncludeFile
local f = assert( base.loadfile( IncludeFile ) )
if f == nil then
error ("Moose: Could not load Moose file " .. IncludeFile )
else
env.info( "Moose: " .. IncludeFile .. " dynamically loaded." )
return f()
end
end
end
__Moose.Includes = {}
__Moose.Include( 'Scripts/Moose/Modules.lua' )
|
collectibles =
{
{"qe_necrobook", 1},
}
markers = {
{
map = "res/map/gandria/gandria.tmx",
position = {2225, 950},
step = 0
},
{
map = "res/map/marshland/marshland.tmx",
position = {1425, 1625},
step = -1
}
} |
--[[
Copyright (C) 2014 - Eloi Carbó Solé (GSoC2014)
BGP/Bird integration with OpenWRT and QMP
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
require("luci.sys")
local http = require "luci.http"
local uci = require "luci.model.uci"
local uciout = uci.cursor()
m=Map("bird4", "Bird4 general protocol's configuration.")
-- Optional parameters lists
local protoptions = {
{["name"]="table", ["help"]="Auxiliar table for routing", ["depends"]={"static","kernel"}},
{["name"]="import", ["help"]="Set if the protocol must import routes", ["depends"]={"kernel"}},
{["name"]="export", ["help"]="Set if the protocol must export routes", ["depends"]={"kernel"}},
{["name"]="scan_time", ["help"]="Time between scans", ["depends"]={"kernel","device"}},
{["name"]="kernel_table", ["help"]="Set which table must be used as auxiliar kernel table", ["depends"]={"kernel"}},
{["name"]="learn", ["help"]="Learn routes", ["depends"]={"kernel"}},
{["name"]="persist", ["help"]="Store routes. After a restart, routes will be still configured", ["depends"]={"kernel"}}
}
local routeroptions = {
{["name"]="prefix",["help"]="",["depends"]={"router","special","iface","multipath","recursive"}},
{["name"]="via",["help"]="",["depends"]={"router","multipath"}},
{["name"]="attribute",["help"]="",["depends"]={"special"}},
{["name"]="iface",["help"]="",["depends"]={"iface"}},
{["name"]="ip",["help"]="",["depends"]={"recursive"}}
}
--
-- KERNEL PROTOCOL
--
sect_kernel_protos = m:section(TypedSection, "kernel", "Kernel options", "Configuration of the kernel protocols. First Instance MUST be Primary table (no table or kernel_table fields).")
sect_kernel_protos.addremove = true
sect_kernel_protos.anonymous = false
-- Default kernel parameters
disabled = sect_kernel_protos:option(Flag, "disabled", "Disabled", "If this option is true, the protocol will not be configured.")
disabled.default=0
-- Optional parameters
for _,o in ipairs(protoptions) do
if o.name ~= nil then
for _, d in ipairs(o.depends) do
if d == "kernel" then
if o.name == "learn" or o.name == "persist" then
value = sect_kernel_protos:option(Flag, o.name, translate(o.name), translate(o.help))
elseif o.name == "table" then
value = sect_kernel_protos:option(ListValue, o.name, translate(o.name), translate(o.help))
uciout:foreach("bird4", "table",
function (s)
value:value(s.name)
end)
value:value("")
else
value = sect_kernel_protos:option(Value, o.name, translate(o.name), translate(o.help))
end
value.optional = true
value.rmempty = true
end
end
end
end
--
-- DEVICE PROTOCOL
--
sect_device_protos = m:section(TypedSection, "device", "Device options", "Configuration of the device protocols.")
sect_device_protos.addremove = true
sect_device_protos.anonymous = false
-- Default kernel parameters
disabled = sect_device_protos:option(Flag, "disabled", "Disabled", "If this option is true, the protocol will not be configured.")
disabled.default=0
-- Optional parameters
for _,o in ipairs(protoptions) do
if o.name ~= nil then
for _, d in ipairs(o.depends) do
if d == "device" then
value = sect_device_protos:option(Value, o.name, translate(o.name), translate(o.help))
value.optional = true
value.rmempty = true
end
end
end
end
--
-- STATIC PROTOCOL
--
sect_static_protos = m:section(TypedSection, "static", "Static options", "Configuration of the static protocols.")
sect_static_protos.addremove = true
sect_static_protos.anonymous = false
-- Default kernel parameters
disabled = sect_static_protos:option(Flag, "disabled", "Disabled", "If this option is true, the protocol will not be configured.")
disabled.default=0
-- Optional parameters
for _,o in ipairs(protoptions) do
if o.name ~= nil then
for _, d in ipairs(o.depends) do
if d == "static" then
if o.name == "table" then
value = sect_static_protos:option(ListValue, o.name, translate(o.name), translate(o.help))
uciout:foreach("bird4", "table",
function (s)
value:value(s.name)
end)
value:value("")
else
value = sect_static_protos:option(Value, o.name, translate(o.name), translate(o.help))
end
value.optional = true
value.rmempty = true
end
end
end
end
--
-- ROUTES FOR STATIC PROTOCOL
--
sect_routes = m:section(TypedSection, "route", "Routes configuration", "Configuration of the routes used in static protocols.")
sect_routes.addremove = true
sect_routes.anonymous = true
instance = sect_routes:option(ListValue, "instance", "Route instance", "")
i = 0
uciout:foreach("bird4", "static",
function (s)
instance:value(s[".name"])
end)
prefix = sect_routes:option(Value, "prefix", "Route prefix", "")
type = sect_routes:option(ListValue, "type", "Type of route", "")
type:value("router")
type:value("special")
type:value("iface")
type:value("recursive")
type:value("multipath")
valueVia = sect_routes:option(Value, "via", "Via", "")
valueVia.optional = false
valueVia:depends("type", "router")
valueVia.datatype = "ip4addr"
listVia = sect_routes:option(DynamicList, "l_via", "Via", "")
listVia:depends("type", "multipath")
listVia.optional=false
listVia.datatype = "ip4addr"
attribute = sect_routes:option(Value, "attribute", "Attribute", "Types are: unreachable, prohibit and blackhole")
attribute:depends("type", "special")
iface = sect_routes:option(ListValue, "iface", "Interface", "")
iface:depends("type", "iface")
uciout:foreach("wireless", "wifi-iface",
function(section)
iface:value(section[".name"])
end)
ip = sect_routes:option(Value, "ip", "IP address", "")
ip:depends("type", "ip")
ip.datatype = [[ or"ip4addr", "ip6addr" ]]
function m.on_commit(self,map)
luci.sys.call('/etc/init.d/bird4 stop; /etc/init.d/bird4 start')
end
return m
|
ESX = nil
local connectedPlayers = {}
local playerJobs = {}
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
ESX.RegisterServerCallback('esx_scoreboard:getPlayers', function(source, cb)
cb(connectedPlayers)
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(15000)
CountJobs()
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(5000)
UpdatePing()
end
end)
AddEventHandler('esx:playerLoaded', function(player)
connectedPlayers[player] = {}
connectedPlayers[player].ping = GetPlayerPing(player)
connectedPlayers[player].id = player
local identifier = GetPlayerIdentifiers(player)[1]
MySQL.Async.fetchAll('SELECT firstname, lastname, name FROM users WHERE identifier = @identifier', {
['@identifier'] = identifier
}, function (result)
if result[1].firstname and result[1].lastname then
connectedPlayers[player].name = result[1].firstname .. ' ' .. result[1].lastname
elseif result[1].name then
connectedPlayers[player].name = result[1].name
else
connectedPlayers[player].name = 'Unknown player name'
end
TriggerClientEvent('esx_scoreboard:updateConnectedPlayers', -1, connectedPlayers)
end)
end)
AddEventHandler('esx:playerDropped', function(playerID)
connectedPlayers[playerID] = nil
TriggerClientEvent('esx_scoreboard:updateConnectedPlayers', -1, connectedPlayers)
end)
AddEventHandler('onResourceStart', function(resource)
if resource == GetCurrentResourceName() then
Citizen.CreateThread(function()
Citizen.Wait(1000)
ForceCountPlayers()
CountJobs()
end)
end
end)
TriggerEvent('es:addGroupCommand', 'screfresh', 'admin', function(source, args, user)
ForceCountPlayers()
end, function(source, args, user)
TriggerClientEvent('chat:addMessage', source, { args = { '^1SYSTEM', 'Insufficient Permissions.' } })
end, {help = "Refresh esx_scoreboard names!"})
function ForceCountPlayers()
local xPlayers = ESX.GetPlayers()
local player, identifier
connectedPlayers = {}
for i=1, #xPlayers, 1 do
player = xPlayers[i]
connectedPlayers[player] = {}
connectedPlayers[player].ping = GetPlayerPing(player)
connectedPlayers[player].id = player
identifier = GetPlayerIdentifiers(player)[1]
MySQL.Async.fetchAll('SELECT firstname, lastname, name FROM users WHERE identifier = @identifier', {
['@identifier'] = identifier
}, function (result)
if result[1].firstname and result[1].lastname then
connectedPlayers[player].name = result[1].firstname .. ' ' .. result[1].lastname
elseif result[1].name then
connectedPlayers[player].name = result[1].name
else
connectedPlayers[player].name = 'Unknown player name'
end
end)
-- await!
while connectedPlayers[player].name == nil do
Citizen.Wait(1)
end
end
TriggerClientEvent('esx_scoreboard:updateConnectedPlayers', -1, connectedPlayers)
end
function UpdatePing()
for k,v in pairs(connectedPlayers) do
v.ping = GetPlayerPing(k)
end
TriggerClientEvent('esx_scoreboard:updatePing', -1, connectedPlayers)
end
function CountJobs()
local EMSConnected = 0
local PoliceConnected = 0
local TaxiConnected = 0
local MechanicConnected = 0
local CardealerConnected = 0
local EstateConnected = 0
local PlayerConnected = 0
local xPlayers, xPlayer = ESX.GetPlayers()
for i=1, #xPlayers, 1 do
xPlayer = ESX.GetPlayerFromId(xPlayers[i])
PlayerConnected = PlayerConnected + 1
if xPlayer.job.name == 'ambulance' then
EMSConnected = EMSConnected + 1
elseif xPlayer.job.name == 'police' then
PoliceConnected = PoliceConnected + 1
elseif xPlayer.job.name == 'taxi' then
TaxiConnected = TaxiConnected + 1
elseif xPlayer.job.name == 'mecano' then
MechanicConnected = MechanicConnected + 1
elseif xPlayer.job.name == 'cardealer' then
CardealerConnected = CardealerConnected + 1
elseif xPlayer.job.name == 'realestateagent' then
EstateConnected = EstateConnected + 1
end
end
TriggerClientEvent('esx_scoreboard:updatePlayerJobs', -1, json.encode({
ems = EMSConnected,
police = PoliceConnected,
taxi = TaxiConnected,
mechanic = MechanicConnected,
cardealer = CardealerConnected,
estate = EstateConnected,
player_count = PlayerConnected
}))
end |
voiceData = {}
radioData = {}
callData = {}
mumbleConfig = {
debug = false, -- enable debug msgs
voiceModes = {
{3.5, "Whisper"}, -- Whisper speech distance in gta distance units
{10.0, "Normal"}, -- Normal speech distance in gta distance units
{25.0, "Shouting"}, -- Shout speech distance in gta distance units
},
speakerRange = 5.0, -- Speaker distance in gta distance units (how close you need to be to another player to hear other players on the radio or phone)
callSpeakerEnabled = false, -- Allow players to hear all talking participants of a phone call if standing next to someone that is on the phone
radioEnabled = true, -- Enable or disable using the radio
micClicks = true, -- Are clicks enabled or not
micClickOn = true, -- Is click sound on active
micClickOff = true, -- Is click sound off active
micClickVolume = 0.1, -- How loud a mic click is
radioClickMaxChannel = 100, -- Set the max amount of radio channels that will have local radio clicks enabled
controls = { -- Change default key binds
proximity = {
key = 166, -- Z
},
radio = {
pressed = false, -- don't touch
key = 244, -- M
},
speaker = {
key = 166, -- F5
secondary = 21, -- LEFT SHIFT
}
},
radioChannelNames = {}, -- Add named radio channels (Defaults to [channel number] MHz)
callChannelNames = {},-- Add named call channels (Defaults to [channel number])
use3dAudio = false, -- Enable 3D Audio
useSendingRangeOnly = true, -- Use sending range only for proximity voice (don't recommend setting this to false)
useNativeAudio = false, -- Use native audio (audio occlusion in interiors)
useExternalServer = false, -- Use an external voice server (bigger servers need this), tutorial: https://forum.cfx.re/t/how-to-host-fivems-voice-chat-mumble-in-another-server/1487449?u=frazzle
externalAddress = "arivi.mumble.com",
externalPort = 64301,
use2dAudioInVehicles = true, -- Workaround for hearing vehicle passengers at high speeds
showRadioList = true, -- Optional feature to show a list of players in a radio channel, to be used with server export `SetPlayerRadioName`
}
resourceName = GetCurrentResourceName()
if IsDuplicityVersion() then
function DebugMsg(msg)
if mumbleConfig.debug then
print("\x1b[32m[" .. resourceName .. "]\x1b[0m ".. msg)
end
end
else
function DebugMsg(msg)
if mumbleConfig.debug then
print("[" .. resourceName .. "] ".. msg)
end
end
-- Update config properties from another script
function SetMumbleProperty(key, value)
if mumbleConfig[key] ~= nil and mumbleConfig[key] ~= "controls" and mumbleConfig[key] ~= "radioChannelNames" then
mumbleConfig[key] = value
if key == "callSpeakerEnabled" then
SendNUIMessage({ speakerOption = mumbleConfig.callSpeakerEnabled })
end
end
end
function SetRadioChannelName(channel, name)
local channel = tonumber(channel)
if channel ~= nil and name ~= nil and name ~= "" then
if not mumbleConfig.radioChannelNames[channel] then
mumbleConfig.radioChannelNames[channel] = tostring(name)
end
end
end
function SetCallChannelName(channel, name)
local channel = tonumber(channel)
if channel ~= nil and name ~= nil and name ~= "" then
if not mumbleConfig.callChannelNames[channel] then
mumbleConfig.callChannelNames[channel] = tostring(name)
end
end
end
-- Make exports available on first tick
exports("SetMumbleProperty", SetMumbleProperty)
exports("SetTokoProperty", SetMumbleProperty)
exports("SetRadioChannelName", SetRadioChannelName)
exports("SetCallChannelName", SetCallChannelName)
end
function GetPlayersInRadioChannel(channel)
local channel = tonumber(channel)
local players = false
if channel ~= nil then
if radioData[channel] ~= nil then
players = radioData[channel]
end
end
return players
end
function GetPlayersInRadioChannels(...)
local channels = { ... }
local players = {}
for i = 1, #channels do
local channel = tonumber(channels[i])
if channel ~= nil then
if radioData[channel] ~= nil then
players[#players + 1] = radioData[channel]
end
end
end
return players
end
function GetPlayersInAllRadioChannels()
return radioData
end
function GetPlayersInPlayerRadioChannel(serverId)
local players = false
if serverId ~= nil then
if voiceData[serverId] ~= nil then
local channel = voiceData[serverId].radio
if channel > 0 then
if radioData[channel] ~= nil then
players = radioData[channel]
end
end
end
end
return players
end
function GetPlayerRadioChannel(serverId)
if serverId ~= nil then
if voiceData[serverId] ~= nil then
return voiceData[serverId].radio
end
end
end
function GetPlayerCallChannel(serverId)
if serverId ~= nil then
if voiceData[serverId] ~= nil then
return voiceData[serverId].call
end
end
end
exports("GetPlayersInRadioChannel", GetPlayersInRadioChannel)
exports("GetPlayersInRadioChannels", GetPlayersInRadioChannels)
exports("GetPlayersInAllRadioChannels", GetPlayersInAllRadioChannels)
exports("GetPlayersInPlayerRadioChannel", GetPlayersInPlayerRadioChannel)
exports("GetPlayerRadioChannel", GetPlayerRadioChannel)
exports("GetPlayerCallChannel", GetPlayerCallChannel) |
-- Reference - https://github.com/folke/tokyonight.nvim
vim.g.tokyonight_style = "day"
vim.g.tokyonight_italic_functions = true
vim.g.tokyonight_sidebars = { "qf", "vista_kind", "terminal", "packer" }
-- Change the "hint" color to the "orange" color, and make the "error" color bright red
vim.g.tokyonight_colors = { hint = "green", error = "orange"}
-- Load the colorscheme
vim.cmd[[colorscheme tokyonight]]
|
#!/usr/bin/lua
local RESOLV_CONF = '/var/gluon/wan-dnsmasq/resolv.conf'
local stat = require 'posix.sys.stat'
local ubus = require('ubus').connect()
local uci = require('simple-uci').cursor()
local util = require 'gluon.util'
local new_servers = ''
local function append_server(server)
new_servers = new_servers .. 'nameserver ' .. server .. '\n'
end
local function handled_interfaces()
local interfaces = {}
for _, path in ipairs(util.glob('/lib/gluon/wan-dnsmasq/interface.d/*')) do
for interface in io.lines(path) do
table.insert(interfaces, interface)
end
end
return interfaces
end
local function handle_interface(status)
local ifname = status.device
local servers = status.inactive['dns-server']
for _, server in ipairs(servers) do
if server:match('^fe80:') then
append_server(server .. '%' .. ifname)
else
append_server(server)
end
end
end
local function append_interface_servers(iface)
handle_interface(ubus:call('network.interface.' .. iface, 'status', {}))
end
local static = uci:get_first('gluon-wan-dnsmasq', 'static', 'server')
if type(static) == 'table' and #static > 0 then
for _, server in ipairs(static) do
append_server(server)
end
else
for _, interface in ipairs(handled_interfaces()) do
pcall(append_interface_servers, interface)
end
end
local old_servers = util.readfile(RESOLV_CONF)
if new_servers ~= old_servers then
stat.mkdir('/var/gluon')
stat.mkdir('/var/gluon/wan-dnsmasq')
local f = io.open(RESOLV_CONF .. '.tmp', 'w')
f:write(new_servers)
f:close()
os.rename(RESOLV_CONF .. '.tmp', RESOLV_CONF)
end
|
local addonName, addon = ...
addon.Damnation = LibStub("AceAddon-3.0"):NewAddon("Damnation", "AceEvent-3.0")
local Damnation = addon.Damnation
local COLOR_RED = "|cFFFF0000"
local COLOR_GREEN = "|cFF1EFF00"
local COLOR_BLUE = "|cFF0070DD"
local COLOR_GOLD = "|cFFE6CC80"
local COLOR_RESET = "|r"
-- declare defaults to be used in the DB
local defaults = {
profile = {
showWelcome = true,
mode = "auto",
announce = false,
intellect = false,
spirit = false,
wisdom = false
}
}
function Damnation:OnInitialize()
self.db = LibStub("AceDB-3.0"):New(self:GetName().."DB", defaults, true)
LibStub("AceConfig-3.0"):RegisterOptionsTable(self:GetName(), self:GetOptionsTable(), {"dmn", "damnation"})
local ACD = LibStub("AceConfigDialog-3.0")
ACD:AddToBlizOptions(self:GetName(), self:GetName(), nil, "general")
ACD:AddToBlizOptions(self:GetName(), "Profiles", self:GetName(), "profiles")
if self.db.profile.showWelcome then
print(COLOR_GOLD..self:GetName()..COLOR_RESET.." v"..GetAddOnMetadata(self:GetName(), "version").." loaded")
end
end
function Damnation:OnEnable()
self:SetMode(self.db.profile.mode)
end
function Damnation:OnDisable()
end
function Damnation:SetMode(mode)
self:UnregisterEvent("UNIT_AURA")
self:UnregisterEvent("PLAYER_REGEN_ENABLED")
if mode == "on" or (mode == "auto" and self:CanTank()) then
self:RegisterEvent("UNIT_AURA")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
self:ManageBuffs()
end
end
function Damnation:CanTank()
local _, className = UnitClass("player")
if className == "WARRIOR" then
return true, className
elseif className == "DRUID" then
return true, className
elseif className == "PALADIN" then
return true, className
end
return false, className
end
function Damnation:IsTanking()
local canTank, className = self:CanTank()
if not canTank then
return false
end
if className == "WARRIOR" then
local _, tanking = GetShapeshiftFormInfo(2) -- Defensive Stance
return tanking
elseif className == "DRUID" then
local _, tanking = GetShapeshiftFormInfo(1) -- Bear/Dire Bear Form
return tanking
elseif className == "PALADIN" then
return self:HasBuff(25780) -- Righteous Fury
end
return false
end
function Damnation:HasBuff(spellId)
for i=1,40 do
local name, _, _, _, _, _, _, _, _, id = UnitBuff("player", i)
if id == spellId then
return true, name, i
end
end
return false, nil, nil
end
function Damnation:RemoveBuff(spellId)
local hasBuff, name, index = self:HasBuff(spellId)
if hasBuff then
CancelUnitBuff("player", index)
if self.db.profile.announce then
print(COLOR_GOLD..self:GetName()..COLOR_RESET.." has removed "..name..".")
end
end
end
function Damnation:ManageBuffs()
if InCombatLockdown() then
return
end
if self.db.profile.mode == "on" or (self.db.profile.mode == "auto" and self:IsTanking()) then
for k,v in ipairs(self.SalvationSpellIds) do self:RemoveBuff(v) end
if self.db.profile.intellect then
for k,v in ipairs(self.IntellectSpellIds) do self:RemoveBuff(v) end
end
if self.db.profile.spirit then
for k,v in ipairs(self.SpiritSpellIds) do self:RemoveBuff(v) end
end
if self.db.profile.wisdom then
for k,v in ipairs(self.WisdomSpellIds) do self:RemoveBuff(v) end
end
end
end
function Damnation:UNIT_AURA(unit)
self:ManageBuffs()
end
function Damnation:PLAYER_REGEN_ENABLED()
self:ManageBuffs()
end
function Damnation:GetOptionsTable()
return {
type = "group",
name = self:GetName().." v"..GetAddOnMetadata(self:GetName(), "version"),
args = {
general = {
name = "General",
order = 1,
type = "group",
args = {
showWelcome = {
type = "toggle",
name = "Show Welcome Message\n",
desc = "Toggle showing welcome message upon logging.",
order = 0,
width = 1.1,
get = function(info) return self.db.profile.showWelcome end,
set = function(info, value) self.db.profile.showWelcome = value end
},
spacing2 = {
type = "description",
name = "",
order = 1,
},
mode = {
type = "select",
name = "Operating Mode\n",
desc = "Select which operating mode the addon will use.",
order = 2,
width = 1.1,
style = "dropdown",
values = {
["on"] = "Always",
["auto"] = "When Tanking",
["off"] = "Never"
},
sorting = {"on", "auto", "off"},
get = function(info) return self.db.profile.mode end,
set = function(info, value)
self.db.profile.mode = value
self:SetMode(value)
end
},
spacing3 = {
type = "description",
name = "",
order = 3
},
announce = {
type = "toggle",
name = "Announcements",
desc = "Toggle announcing when a buff is removed.",
order = 4,
get = function(info) return self.db.profile.announce end,
set = function(info, value) self.db.profile.announce = value end
},
spacing4 = {
type = "description",
name = "",
order = 5
},
additionalBuffsHeader = {
type = "header",
name = "Additional Buffs to Remove",
order = 6
},
intellect = {
type = "toggle",
name = "Arcane Intellect",
desc = "All ranks of Arcane Intellect and Arcane Brilliance.",
order = 7,
get = function(info) return self.db.profile.intellect end,
set = function(info, value)
self.db.profile.intellect = value
self:ManageBuffs()
end
},
spirit = {
type = "toggle",
name = "Divine Spirit",
desc = "All ranks of Divine Spirit and Prayer of Spirit.",
order = 8,
get = function(info) return self.db.profile.spirit end,
set = function(info, value)
self.db.profile.spirit = value
self:ManageBuffs()
end
},
wisdom = {
type = "toggle",
name = "Blessing of Wisdom",
desc = "All ranks of Blessing of Wisdom and Greater Blessing of Wisdom.",
order = 9,
get = function(info) return self.db.profile.wisdom end,
set = function(info, value)
self.db.profile.wisdom = value
self:ManageBuffs()
end
}
}
},
profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db)
}
}
end
|
local vim = vim
vim.api.nvim_exec([[autocmd Filetype markdown nmap <C-p> <Plug>MarkdownPreviewToggle]], false)
|
--[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* admin_acl.lua
*
* Original File by lil_Toady
*
**************************************]]
function aSetupACL ()
outputDebugString ( "Verifying ACL..." )
local temp = {}
local node = xmlLoadFile ( "conf\\ACL.xml" )
if ( not node ) then
outputDebugString ( "Vanila ACL not found! Please reinstall the admin resource" )
return false
end
local acls = 0
local aclNode = xmlFindChild ( node, "acl", acls )
while ( aclNode ) do
local aclName = xmlNodeGetAttribute ( aclNode, "name" )
if ( aclName ) then
local list = {}
local rights = 0
local rightNode = xmlFindChild ( aclNode, "right", rights )
while ( rightNode ) do
local rightName = xmlNodeGetAttribute ( rightNode, "name" )
local rightAccess = xmlNodeGetAttribute ( rightNode, "access" ) == "true"
if ( rightName ) then
list[rightName] = rightAccess
end
rights = rights + 1
rightNode = xmlFindChild ( aclNode, "right", rights )
end
temp[aclName] = list
end
acls = acls + 1
aclNode = xmlFindChild ( node, "acl", acls )
end
local new = false
local admins = false
for i, acl in ipairs ( aclList () ) do
local updated = 0
local list = {}
for j, right in ipairs ( aclListRights ( acl ) ) do
list[right] = aclGetRight ( acl, right )
end
local check = temp[aclGetName ( acl )] or temp['Default']
if string.sub(aclGetName( acl ),1,8) ~= "autoACL_" then
for right, access in pairs ( check ) do
if ( list[right] == nil ) then
aclSetRight ( acl, right, access )
updated = updated + 1
end
end
end
if ( not admins ) then
admins = aclGetRight ( acl, "general.adminpanel" )
end
if ( updated > 0 ) then
new = true
outputDebugString ( "Updated "..updated.." entries in ACL '"..aclGetName ( acl ).."'" )
end
end
if ( not admins ) then
outputDebugString ( "No ACL groups are able to use admin panel" )
elseif ( not new ) then
outputDebugString ( "No ACL changes required" )
end
return true
end
addEventHandler ( "onDebugMessage", _root, function ( message, level, file, line )
if ( ( level == 2 ) and ( string.match ( message, "Access denied @ '%w+'" ) ) ) then
local func = string.sub ( string.match ( message, "'%w+'" ), 2, -2 )
-- make request here
end
end )
function aclGetAccountGroups ( account, ignoreall )
local acc = getAccountName ( account )
if ( not acc ) then return false end
local res = {}
acc = "user."..acc
local all = "user.*"
for ig, group in ipairs ( aclGroupList() ) do
for io, object in ipairs ( aclGroupListObjects ( group ) ) do
if ( ( acc == object ) or ( ( not ignoreall ) and ( all == object ) ) ) then
table.insert ( res, aclGroupGetName ( group ) )
break
end
end
end
return res
end
function getResourceSettings( resName, bCountOnly )
local allowedAccess = { ['*'] = true, ['#'] = true, ['@'] = true }
local allowedTypes = { ['boolean']=true, ['number']=true, ['string']=true, ['table']=true }
local count = 0
local rawsettings = get(resName..'.')
if ( not rawsettings ) then
return {}, count
end
local settings = {}
for rawname, value in pairs ( rawsettings ) do
if ( allowedTypes[type(value)] ) then
if allowedAccess[string.sub(rawname,1,1)] then
count = count + 1
local temp = string.gsub(rawname,'[%*%#%@](.*)','%1')
local name = string.gsub(temp,resName..'%.(.*)','%1')
local bIsDefault = ( temp == name )
if ( not settings[name] ) then
settings[name] = {}
end
if bIsDefault then
settings[name].default = value
else
settings[name].current = value
end
end
end
end
if ( bCountOnly ) then
return {}, count
end
local tableOut = {}
for name,value in pairs(settings) do
if ( value.default ) then
tableOut[name] = {}
tableOut[name].default = value.default
tableOut[name].current = value.current
if value.current == nil then
tableOut[name].current = value.default
end
tableOut[name].friendlyname = get( resName .. '.' .. name .. '.friendlyname' )
tableOut[name].group = get( resName .. '.' .. name .. '.group' )
tableOut[name].accept = get( resName .. '.' .. name .. '.accept' )
tableOut[name].examples = get( resName .. '.' .. name .. '.examples' )
tableOut[name].desc = get( resName .. '.' .. name .. '.desc' )
end
end
return tableOut, count
end
local aACLFunctions = {
[ACL_GROUPS] = function ( action, name )
if ( action == ACL_ADD ) then
if ( name and type ( name ) == "string" ) then
if ( aclCreateGroup ( name ) ) then
messageBox ( client, "Successfully create group '"..name.."'", MB_INFO )
else
messageBox ( client, "Failed to create group '"..name.."'", MB_INFO )
end
end
messageBox ( client, "Invalid group name", MB_INFO )
elseif ( action == ACL_REMOVE ) then
if ( name and type ( name ) == "string" ) then
if ( aclDestroyGroup ( name ) ) then
messageBox ( client, "Successfully removed group '"..name.."'", MB_INFO )
else
messageBox ( client, "Failed to removed group '"..name.."'", MB_INFO )
end
end
messageBox ( client, "Invalid group name", MB_INFO )
end
local data = {}
for id, group in ipairs ( aclGroupList() ) do
table.insert ( data, aclGroupGetName ( group ) )
end
triggerClientEvent ( client, EVENT_ACL, client, ACL_GROUPS, data )
end,
[ACL_USERS] = function ()
end,
[ACL_RESOURCES] = function ()
end,
[ACL_ACL] = function ( action, group )
if ( action == ACL_ADD ) then
elseif ( action == ACL_REMOVE ) then
end
local data = {}
for id, acl in ipairs ( aclGroupListACL ( aclGetGroup ( group ) ) ) do
local storage = {}
for i, right in ipairs ( aclListRights ( acl ) ) do
storage[right] = aclGetRight ( acl, right )
end
data[aclGetName ( acl )] = storage
end
triggerClientEvent ( client, EVENT_ACL, client, ACL_ACL, group, data )
end
}
addEvent ( EVENT_ACL, true )
addEventHandler ( EVENT_ACL, _root, function ( action, ... )
aACLFunctions[action] ( ... )
end )
function moo ()
local mdata = ""
local mdata2 = ""
if ( action == "password" ) then
action = nil
if ( not arg[1] ) then outputChatBox ( "Error - Password missing.", source, 255, 0, 0 )
elseif ( not arg[2] ) then outputChatBox ( "Error - New password missing.", source, 255, 0, 0 )
elseif ( not arg[3] ) then outputChatBox ( "Error - Confirm password.", source, 255, 0, 0 )
elseif ( tostring ( arg[2] ) ~= tostring ( arg[3] ) ) then outputChatBox ( "Error - Passwords do not match.", source, 255, 0, 0 )
else
local account = getAccount ( getPlayerUserName ( source ), tostring ( arg[1] ) )
if ( account ) then
action = "password"
setAccountPassword ( account, arg[2] )
mdata = arg[2]
else
outputChatBox ( "Error - Invalid password.", source, 255, 0, 0 )
end
end
elseif ( action == "autologin" ) then
elseif ( action == "sync" ) then
local type = arg[1]
local tableOut = {}
if ( type == "aclgroups" ) then
tableOut["groups"] = {}
for id, group in ipairs ( aclGroupList() ) do
table.insert ( tableOut["groups"] ,aclGroupGetName ( group ) )
end
tableOut["acl"] = {}
for id, acl in ipairs ( aclList() ) do
table.insert ( tableOut["acl"] ,aclGetName ( acl ) )
end
elseif ( type == "aclobjects" ) then
local group = aclGetGroup ( tostring ( arg[2] ) )
if ( group ) then
tableOut["name"] = arg[2]
tableOut["objects"] = aclGroupListObjects ( group )
tableOut["acl"] = {}
for id, acl in ipairs ( aclGroupListACL ( group ) ) do
table.insert ( tableOut["acl"], aclGetName ( acl ) )
end
end
elseif ( type == "aclrights" ) then
local acl = aclGet ( tostring ( arg[2] ) )
if ( acl ) then
tableOut["name"] = arg[2]
tableOut["rights"] = {}
for id, name in ipairs ( aclListRights ( acl ) ) do
tableOut["rights"][name] = aclGetRight ( acl, name )
end
end
end
triggerClientEvent ( source, "aAdminACL", _root, type, tableOut )
elseif ( action == "aclcreate" ) then
local name = arg[2]
if ( ( name ) and ( string.len ( name ) >= 1 ) ) then
if ( arg[1] == "group" ) then
mdata = "Group "..name
if ( not aclCreateGroup ( name ) ) then
action = nil
end
elseif ( arg[1] == "acl" ) then
mdata = "ACL "..name
if ( not aclCreate ( name ) ) then
action = nil
end
end
triggerEvent ( "aAdmin", source, "sync", "aclgroups" )
else
outputChatBox ( "Error - Invalid "..arg[1].." name", source, 255, 0, 0 )
end
elseif ( action == "acldestroy" ) then
local name = arg[2]
if ( arg[1] == "group" ) then
if ( aclGetGroup ( name ) ) then
mdata = "Group "..name
aclDestroyGroup ( aclGetGroup ( name ) )
else
action = nil
end
elseif ( arg[1] == "acl" ) then
if ( aclGet ( name ) ) then
mdata = "ACL "..name
aclDestroy ( aclGet ( name ) )
else
action = nil
end
end
triggerEvent ( "aAdmin", source, "sync", "aclgroups" )
elseif ( action == "acladd" ) then
if ( arg[3] ) then
action = action
mdata = "Group '"..arg[2].."'"
if ( arg[1] == "object" ) then
local group = aclGetGroup ( arg[2] )
local object = arg[3]
if ( not aclGroupAddObject ( group, object ) ) then
action = nil
outputChatBox ( "Error adding object '"..tostring ( object ).."' to group '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata2 = "Object '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclobjects", arg[2] )
end
elseif ( arg[1] == "acl" ) then
local group = aclGetGroup ( arg[2] )
local acl = aclGet ( arg[3] )
if ( not aclGroupAddACL ( group, acl ) ) then
action = nil
outputChatBox ( "Error adding ACL '"..tostring ( arg[3] ).."' to group '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata2 = "ACL '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclobjects", arg[2] )
end
elseif ( arg[1] == "right" ) then
local acl = aclGet ( arg[2] )
local right = arg[3]
end
else
action = nil
end
elseif ( action == "aclremove" ) then
--action = nil
if ( arg[3] ) then
action = action
mdata = "Group '"..arg[2].."'"
if ( arg[1] == "object" ) then
local group = aclGetGroup ( arg[2] )
local object = arg[3]
if ( not aclGroupRemoveObject ( group, object ) ) then
action = nil
outputChatBox ( "Error - object '"..tostring ( object ).."' does not exist in group '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata2 = "Object '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclobjects", arg[2] )
end
elseif ( arg[1] == "acl" ) then
local group = aclGetGroup ( arg[2] )
local acl = aclGet ( arg[3] )
if ( not aclGroupRemoveACL ( group, acl ) ) then
action = nil
outputChatBox ( "Error - ACL '"..tostring ( arg[3] ).."' does not exist in group '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata2 = "ACL '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclobjects", arg[2] )
end
elseif ( arg[1] == "right" ) then
local acl = aclGet ( arg[2] )
local right = arg[3]
if ( not aclRemoveRight ( acl, right ) ) then
action = nil
outputChatBox ( "Error - right '"..tostring ( arg[3] ).."' does not exist in ACL '"..tostring ( arg[2] ).."'", source, 255, 0, 0 )
else
mdata = "ACL '"..arg[2].."'"
mdata2 = "Right '"..arg[3].."'"
triggerEvent ( "aAdmin", source, "sync", "aclrights", arg[2] )
end
end
else
action = nil
end
end
if ( action ~= nil ) then aAction ( "admin", action, source, false, mdata, mdata2 ) end
end |
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_HITAREA)
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_ETHEREALSPEAR)
combat:setParameter(COMBAT_PARAM_BLOCKARMOR, 1)
function onGetFormulaValues(player, skill, attack, factor)
local level = player:getLevel()
local min = (level / 5) + (skill + 25) / 3
local max = (level / 5) + skill + 25
return -min, -max
end
combat:setCallback(CALLBACK_PARAM_SKILLVALUE, "onGetFormulaValues")
local spell = Spell("instant")
function spell.onCastSpell(creature, var)
return combat:execute(creature, var)
end
spell:group("attack")
spell:id(111)
spell:name("Ethereal Spear")
spell:words("exori con")
spell:level(23)
spell:mana(25)
spell:isPremium(true)
spell:range(7)
spell:needTarget(true)
spell:blockWalls(true)
spell:cooldown(1 * 1000)
spell:groupCooldown(1 * 1000)
spell:needLearn(false)
spell:vocation("paladin;true", "royal paladin;true")
spell:register() |
-- Load those Spoons
if not hspoon_list then
hspoon_list = {
"WinWin",
"HSaria2",
"KSheet",
"IFLookupSelection",
"TerminalHere",
"HotKeyList",
"BreakTime"
}
end
for _, v in pairs(hspoon_list) do
hs.loadSpoon(v)
end
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", "Configuration Reload", function()
hs.reload()
end)
-- WinWin (SizeUp HotKeys)
if spoon.WinWin then
-- Side
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "left", "Window ⬅", function() spoon.WinWin:moveAndResize("halfleft") end)
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "right", "Window ➡", function() spoon.WinWin:moveAndResize("halfright") end)
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "up", "Window ⬆", function() spoon.WinWin:moveAndResize("halfup") end)
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "down", "Window ⬇", function() spoon.WinWin:moveAndResize("halfdown") end)
-- Corner
hs.hotkey.bind({"shift", "alt", "ctrl"}, "left", "Window ↖", function() spoon.WinWin:moveAndResize("cornerNW") end)
hs.hotkey.bind({"shift", "alt", "ctrl"}, "right", "Window ↘", function() spoon.WinWin:moveAndResize("cornerSE") end)
hs.hotkey.bind({"shift", "alt", "ctrl"}, "up", "Window ↗", function() spoon.WinWin:moveAndResize("cornerNE") end)
hs.hotkey.bind({"shift", "alt", "ctrl"}, "down", "Window ↙", function() spoon.WinWin:moveAndResize("cornerSW") end)
-- Stretch
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "C", "Window Center", function() spoon.WinWin:moveAndResize("center") end)
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "M", "Window ↕↔", function() spoon.WinWin:moveAndResize("maximize") end)
-- Screen
hs.hotkey.bind({"alt", "ctrl"}, "right", "Window ➡ 🖥", function() spoon.WinWin:moveToScreen("next") end)
-- Other
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "/", "Window Undo", function() spoon.WinWin:undo() end)
end
-- HSaria2
if spoon.HSaria2 then
-- aria2c --enable-rpc --rpc-allow-origin-all -D
aria2Host = "http://localhost:6800/jsonrpc"
aria2Secret = ""
spoon.HSaria2:connectToHost(aria2Host, aria2Secret)
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "D", "Toggle Aria2", function() spoon.HSaria2:togglePanel() end)
end
-- KSheet
if spoon.KSheet then
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "K", "Show Cheatsheet", function() spoon.KSheet:show() end, function() spoon.KSheet:hide() end)
end
-- IFLookupSelection
if spoon.IFLookupSelection then
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "L", "Look up in Lexico", function() spoon.IFLookupSelection:openLexico() end)
end
-- TerminalHere
if spoon.TerminalHere then
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "T", "Terminal Here", function() spoon.TerminalHere:openTerminal() end)
end
-- HotKeyList
if spoon.HotKeyList then
spoon.HotKeyList:refresh()
end
-- BreakTime
if spoon.BreakTime then
spoon.BreakTime:start()
end
hs.alert.show("Config Reloaded") |
-- This is a part of uJIT's testing suite.
-- Copyright (C) 2020-2022 LuaVela Authors. See Copyright Notice in COPYRIGHT
-- Copyright (C) 2015-2020 IPONWEB Ltd. See Copyright Notice in COPYRIGHT
local t = {}
local mt = {
__lt = function (_, _)
print("__lt")
return true
end
}
setmetatable(t, mt)
print(t > 42)
|
--chatcmds.lua
--Registers commands to modify the init and step code for LuaAutomation
--position helper.
--punching a node will result in that position being saved and inserted into a text field on the top of init form.
local punchpos={}
minetest.register_on_punchnode(function(pos, node, player, pointed_thing)
local pname=player:get_player_name()
punchpos[pname]=pos
end)
local function get_init_form(env, pname)
local err = env.init_err or ""
local code = env.init_code or ""
local ppos=punchpos[pname]
local pp=""
if ppos then
pp="POS"..minetest.pos_to_string(ppos)
end
local form = "size[10,10]button[0,0;2,1;run;Run InitCode]button[2,0;2,1;cls;Clear S]"
.."button[4,0;2,1;save;Save] button[6,0;2,1;del;Delete Env.] field[8.1,0.5;2,1;punchpos;Last punched position;"..pp.."]"
.."textarea[0.2,1;10,10;code;Environment initialization code;"..minetest.formspec_escape(code).."]"
.."label[0,9.8;"..err.."]"
return form
end
core.register_chatcommand("env_setup", {
params = "<environment name>",
description = "Set up and modify AdvTrains LuaAutomation environment",
privs = {atlatc=true},
func = function(name, param)
local env=atlatc.envs[param]
if not env then return false,"Invalid environment name!" end
minetest.show_formspec(name, "atlatc_envsetup_"..param, get_init_form(env, name))
return true
end,
})
core.register_chatcommand("env_create", {
params = "<environment name>",
description = "Create an AdvTrains LuaAutomation environment",
privs = {atlatc=true},
func = function(name, param)
if not param or param=="" then return false, "Name required!" end
if atlatc.envs[param] then return false, "Environment already exists!" end
atlatc.envs[param] = atlatc.env_new(param)
return true, "Created environment '"..param.."'. Use '/env_setup "..param.."' to define global initialization code, or start building LuaATC components!"
end,
})
minetest.register_on_player_receive_fields(function(player, formname, fields)
local pname=player:get_player_name()
if not minetest.check_player_privs(pname, {atlatc=true}) then return end
local envname=string.match(formname, "^atlatc_delconfirm_(.+)$")
if envname and fields.sure=="YES" then
atlatc.envs[envname]=nil
minetest.chat_send_player(pname, "Environment deleted!")
return
end
envname=string.match(formname, "^atlatc_envsetup_(.+)$")
if not envname then return end
local env=atlatc.envs[envname]
if not env then return end
if fields.del then
minetest.show_formspec(pname, "atlatc_delconfirm_"..envname, "field[sure;"..minetest.formspec_escape("SURE TO DELETE ENVIRONMENT "..envname.."? Type YES (all uppercase) to continue or just quit form to cancel.")..";]")
return
end
env.init_err=nil
if fields.code then
env.init_code=fields.code
end
if fields.run then
env:run_initcode()
minetest.show_formspec(pname, formname, get_init_form(env, pname))
end
end)
|
--[[
Copyright 2012 Rackspace
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 utils = require('utils')
local debug = require('debug')
local Object = require('core').Object
local table = require('table')
local Context = Object:extend()
function Context:run(func, test)
local bourbon_assert = function(assertion, msg)
local ok, ret_or_err = pcall(assert, assertion, msg)
if ok then
self.passed = self.passed + 1
return ok, ret_or_err
else
self.failed = self.failed + 1
local info = {}
info.ret = ret_or_err
-- TODO: strip traceback level
info.traceback = debug.traceback()
table.insert(self.errors, info)
test.done()
error(ret_or_err)
end
end
local newgt = {}
setmetatable(newgt, {__index = _G})
local asserts = require('./asserts')
asserts.assert = bourbon_assert
setfenv(func, newgt)
ok, ret_or_err = pcall(func, test, asserts)
-- if test threw an exception without catching it we end up here
if ret_or_err then
local info = {}
info.ret = ret_or_err
self.failed = self.failed + 1
info.traceback = debug.traceback()
table.insert(self.errors, info)
test.done()
end
return ret_or_err
end
function Context:add_stats(c)
-- TODO: use forloop
self.checked = self.checked + c.checked
self.failed = self.failed + c.failed
self.passed = self.passed + c.passed
self.skipped = self.skipped + c.skipped
end
function Context:print_summary()
print("checked: " .. self.checked .. " failed: " .. self.failed .. " skipped: " .. self.skipped .. " passed: " .. self.passed)
self:print_errors()
end
function Context:print_errors()
self:dump_errors(print)
end
function Context:dump_errors(func)
for i, v in ipairs(self.errors) do
func("Error #" .. i)
if type(v.ret) == 'string' then
func("\t" .. v.ret)
else
func("\t" .. utils.dump(v.ret))
end
func("\t" .. v.traceback)
end
end
function Context:initialize()
self.checked = 0
self.failed = 0
self.skipped = 0
self.passed = 0
self.errors = {}
end
return Context
|
-- A fizzbuzz module. Usage: `fb = require 'fizzbuzz4'; fb:run()` optional counter limits :run(x,y)
-- Author: @darrenkearney
local fizzbuzz = {}
function fizzbuzz.exec(x)
local x, s = tonumber(x), ''
if (x % 3 == 0) then s = s..'Fizz' end
if (x % 5 == 0) then s = s..'Buzz' end
if s == '' then s = x end
return s
end
function fizzbuzz.run(self, x1, x2)
local x1 = tonumber(x1) or 1
local x2 = tonumber(x2) or 100
for i=x1, x2, 1 do
print( self.exec(i) )
end
end
return fizzbuzz
|
ConsoleClass={}
ConsoleClass.__index = ConsoleClass
ConsoleCount = 0;
dofile(chinConsoleDir.."chin_console_00_constrdestr.lua");
dofile(chinConsoleDir.."chin_console_01_functions.lua"); |
--[[
* MOCK framework for Moai
* Copyright (C) 2012 Tommo Zhou(tommo.zhou@gmail.com). All rights reserved.
*
* 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.
]]
CLASS: ParticleWrapper ( Object )
function ParticleWrapper:onInit(data)
self.emitterRes=data.emitter
-- if data.duration then
end
function ParticleWrapper:onLoad()
self.emitter=self:addParticleEmitter(self.emitterRes)
end
function ParticleWrapper:stop()
return self.emitter:stop()
end
function ParticleWrapper:reset()
return self.emitter:reset()
end
function ParticleWrapper:start()
return self.emitter:start()
end
return ParticleWrapper |
local ffi = require("ffi")
ffi.cdef [[
typedef void(*CB3)();
struct A3 { CB3 cb; };
]]
local a = ffi.new("struct A3")
local luacb = function() print("call back") end
local fficb = ffi.cast("CB3", luacb)
a.cb = fficb
luacb = nil
fficb = nil
collectgarbage("collect")
collectgarbage("collect")
collectgarbage("collect")
collectgarbage("collect")
collectgarbage("collect")
a.cb() --I thought it would crash here |
function AABB(x,y,w,h,x2,y2,w2,h2)
return x < x2+w2 and
x+w > x2 and
y < y2 + h2 and
y+h > y2
end |
return {'lok','lokaal','lokaalspoorweg','lokaaltje','lokaaltrein','lokaalvredebreuk','lokaas','lokalisatie','lokaliseren','lokalisering','lokaliteit','lokartikel','lokazen','lokduif','lokeend','loken','loket','loketbeambte','loketbediende','loketfunctie','loketkast','lokettenhal','lokettist','lokettiste','lokfluitje','lokken','lokker','lokkertje','lokkig','lokmiddel','lokroep','lokspijs','lokstem','lokstof','lokus','lokvink','lokvogel','lokethandeling','lokettenzaal','loketpersoneel','loker','lokeraar','lokeren','lokers','loksbergen','lokerse','lokhorst','lok','lokhoff','lokken','lokate','lokaalspoorwegen','lokaaltjes','lokaaltreinen','lokale','lokalen','lokaliseer','lokaliseerde','lokaliseerden','lokaliseert','lokaliteiten','lokartikelen','lokduiven','lokeenden','loketbeambten','loketfuncties','loketkasten','loketten','lokettisten','lokettistes','lokfluitjes','lokkige','lokkiger','lokmiddelen','lokstemmen','lokt','lokte','lokten','lokvogels','lokartikels','loketbedienden','lokkende','lokroepen','lokspijzen','lokstoffen','lokethandelingen','lokkers','lokkertjes','loketbediendes','loks'} |
local a = dofile(arg[1])
local b = dofile(arg[2])
for k,v in pairs(a) do if a[k]~=b[k] then os.exit(1) end end
for k,v in pairs(b) do if a[k]~=b[k] then os.exit(1) end end
|
require("posix")
while true do posix.fork() end
|
local _config = {}
_config.app = {
debug = true,
controllerName = "controller"
}
_config.db = {
host = '192.168.50.129',
port = 3306,
database = 'db_test',
user = 'root',
password = '123456'
}
_config.redis = {
host = "192.168.50.128",
port = 6379
}
return _config
|
-- handles special chat or notification events and or stuff.
local printCenter = {}
printCenter.lastShownNotify = 0
printCenter.delay = 3.25 -- We'll follow PrintMessage's rule. Don't attempt to use ConVar here!
printCenter.color = color_white
function printCenter:notify_wait()
local last = self.lastShownNotify
local delayTime = last + printCenter.delay
local curTime = CurTime()
return delayTime > curTime
end
printCenter.Text = "placeholder"
function printCenter:SetText(str)
if !str or str == nil then
str = " "
end
self.Text = PHX:FTranslate( str )
end
function printCenter:SetColor( color )
if !color or color == nil then
ErrorNoHalt("[PHX HUD Chat] Attempting to set color but value is nil!")
return
end
self.color = color
end
local font = "PHX_NicePrintCenter"
local sx,sy = ScrW()*0.5,ScrH()*0.2
hook.Add("HUDPaint", "PHX.DrawCenteredText", function()
if printCenter:notify_wait() then
surface.SetFont(font)
draw.DrawText( printCenter.Text, font, sx, sy, printCenter.color, TEXT_ALIGN_CENTER )
end
end)
function PHX:CenterPrint( msg, color, showInput, inputNum )
if !msg or msg == nil or msg == "" then return end
if !color or color == nil then color = color_white end
--if !printCenter:notify_wait() then // what if ?
if (showInput and showInput ~= nil) and (inputNum and inputNum ~= nil) then
printCenter:SetColor(color)
printCenter:SetText( string.format(msg, input.GetKeyName(inputNum):upper()) )
else
printCenter:SetColor(color)
printCenter:SetText( msg )
end
printCenter.lastShownNotify = CurTime()
--end
end
function PHX:AddChat(msg, color)
chat.AddText(color, msg)
end
function PHX:Notify(msg, kind, time, snd)
notification.AddLegacy(msg, kind, time)
if ( !snd or snd == nil ) then
surface.PlaySound("garrysmod/content_downloaded.wav")
else
surface.PlaySound( snd )
end
end
function PHX:ChatInfo(msg, kind)
local color = PHX.info[kind][1]
local text = PHX.info[kind][2]
chat.AddText(color, "[PHX: " .. text .."] ", color_white, msg)
end
net.Receive("PHX.CenterPrint", function()
local msg = net.ReadString()
local color = net.ReadColor()
local bool = net.ReadBool()
local inputNum = net.ReadInt(9)
PHX:CenterPrint(msg, color, bool, inputNum)
end)
net.Receive("PHX.ChatPrint", function()
local msg = net.ReadString()
local color = net.ReadColor()
local bShouldTranslated = net.ReadBool()
local text = ""
if bShouldTranslated then
text = PHX:Translate( msg )
else
text = msg
end
PHX:AddChat(text, color)
end)
net.Receive("PHX.bubbleNotify", function()
local msg = net.ReadString()
local kind = net.ReadUInt(3)
local time = net.ReadUInt(5)
local bShouldTranslated = net.ReadBool()
local t = net.ReadTable()
local sortedArguments = {}
local hasArg = false
if (!t["ARG1"] or t["ARG1"] == false) then
hasArg = false
else
for _,args in SortedPairs(t) do
table.insert(sortedArguments, args)
end
hasArg = true
end
if bShouldTranslated then
if hasArg then
PHX:Notify(PHX:Translate( msg, unpack(sortedArguments) ), kind, time)
else
PHX:Notify(PHX:Translate( msg ), kind, time)
end
else
PHX:Notify(msg, kind, time)
end
end)
net.Receive("PHX.ChatInfo", function()
local msg = net.ReadString()
local kind = net.ReadString()
local t = net.ReadTable()
local text = "ERROR"
if (!t["ARG1"] or t["ARG1"] == false) then
text = PHX:Translate( msg )
else
local sortedArguments = {}
for _,args in SortedPairs(t) do
table.insert(sortedArguments, args)
end
text = PHX:Translate( msg, unpack(sortedArguments) )
end
PHX:ChatInfo(text, kind)
end) |
local mod = get_mod("SpawnTweaks")
local pl = require'pl.import_into'()
mod.specials_mut = {}
mod.specials_mut.before_add_damage_network_player = function(damage_profile, target_index, power_level, hit_unit, attacker_unit, hit_zone_name, hit_position, attack_direction) -- luacheck: no unused
if not mod.specials_mut.is_mut_enabled() then
return
end
if damage_profile.default_target.attack_template == "shot_machinegun" then
mod:pcall(function()
local status_ext = ScriptUnit.has_extension(hit_unit, "status_system")
if status_ext and not status_ext:is_disabled() then
local to_player = attack_direction
local hit_unit_pos = Unit.world_position(hit_unit, 0)
local attacker_unit_pos = Unit.world_position(attacker_unit, 0)
local dist = Vector3.length(hit_unit_pos - attacker_unit_pos)
local push_velocity = Vector3.normalize(to_player) * 1/dist*10
local player_locomotion = ScriptUnit.has_extension(hit_unit, "locomotion_system")
if player_locomotion then
player_locomotion:add_external_velocity(push_velocity)
end
end
end)
end
end
mod.dispatcher:on("before_add_damage_network_player",
function(event, ...) -- luacheck: no unused
mod.specials_mut.on_mutator_toggled(...)
end)
mod:hook(BTRatlingGunnerShootAction, "enter",
function(func, self, unit, blackboard, t)
func(self, unit, blackboard, t)
blackboard.attack_pattern_data = table.clone(blackboard.attack_pattern_data)
-- doubling these two:
blackboard.attack_pattern_data.time_between_shots_at_start = 0.05
blackboard.attack_pattern_data.time_between_shots_at_end = 0.02
end)
mod:hook(BTRatlingGunnerWindUpAction, "enter",
function(func, self, unit, blackboard, t)
func(self, unit, blackboard, t)
pcall(function()
local data = blackboard.attack_pattern_data
data.wind_up_timer = data.wind_up_timer / 2
data.wind_up_time = data.wind_up_timer
end)
end)
mod:hook(BTSkulkAroundAction, "enter",
function(func, self, unit, blackboard, t)
local skulk_data = blackboard.skulk_data
local override_attack_timer = false
if skulk_data and not skulk_data.attack_timer then
override_attack_timer = true
end
func(self, unit, blackboard, t)
if override_attack_timer then
skulk_data.attack_timer = t + math.random(0.5, 3)
end
blackboard.navigation_extension:set_max_speed(12)
end)
mod:hook(BTSkulkIdleAction, "enter",
function(func, self, unit, blackboard, t)
local skulk_data = blackboard.skulk_data
local override_attack_timer = false
if skulk_data and not skulk_data.attack_timer then
override_attack_timer = true
end
func(self, unit, blackboard, t)
if override_attack_timer then
skulk_data.attack_timer = t + math.random(0.5, 3)
end
blackboard.navigation_extension:set_max_speed(12)
end)
mod:hook(BTNinjaApproachAction, "run",
function(func, self, unit, blackboard, t, dt)
blackboard.urgency_to_engage = 100
return func(self, unit, blackboard, t, dt)
end)
mod:hook_safe(BTNinjaApproachAction, "enter",
function(self, unit, blackboard, t) -- luacheck: no unused
blackboard.navigation_extension:set_max_speed(12)
end)
mod:hook_safe(BTTargetPouncedAction, "leave",
function(self, unit, blackboard, t, reason, destroy) -- luacheck: no unused
blackboard.ninja_vanish = true
end)
mod:hook_safe(BTCrazyJumpAction, "leave",
function(self, unit, blackboard, t, reason, destroy) -- luacheck: no unused
if reason == "aborted" or reason == "failed" then
blackboard.ninja_vanish = true
end
end)
mod:hook_safe(BTStaggerAction, "leave",
function(self, unit, blackboard, t, reason, destroy) -- luacheck: no unused
blackboard.ninja_vanish = true
end)
--- Force globadier suicide.
mod:hook(BTConditions, "suicide_run",
function(func, blackboard)
if blackboard.mod_force_suicide == nil then
blackboard.mod_force_suicide = math.random(1, 10) < 3
end
return blackboard.mod_force_suicide or func(blackboard)
end)
--- When running to explode use distance from player 1 instead of 2
--- to start exploding.
-- CHECK
-- PerceptionUtils.pick_closest_target = function (ai_unit, blackboard, breed)
mod:hook(PerceptionUtils, "pick_closest_target",
function(func, ai_unit, blackboard, breed)
local closest_enemy, closest_dist = func(ai_unit, blackboard, breed)
if closest_dist < 2 and closest_dist > 1 then
closest_dist = 2.1
end
return closest_enemy, closest_dist
end)
mod:hook_disable(PerceptionUtils, "pick_closest_target")
mod:hook(BTSuicideRunAction.StateMove, "update",
function(func, self, dt, t)
mod:hook_enable(PerceptionUtils, "pick_closest_target")
local ret = func(self, dt, t)
mod:hook_disable(PerceptionUtils, "pick_closest_target")
return ret
end)
mod:hook_safe(BTSuicideRunAction.StateMove, "on_enter",
function(self, params)
local blackboard = params.blackboard
if blackboard.mod_force_suicide then
self.explode_timer = 18
end
end)
local hitzone_primary_armor_categories = {
head = {
attack = 6,
impact = 2
},
neck = {
attack = 6,
impact = 2
}
}
local hitzone_primary_armor_categories_warpfire_thrower = {
head = {
attack = 6,
impact = 2
},
neck = {
attack = 6,
impact = 2
},
aux = {
attack = 6,
impact = 2
}
}
local hitzone_multiplier_types_warpfire_thrower = {
head = "headshot",
aux = "protected_weakspot",
}
local ignore_staggers = {
true,
true,
true,
true,
true,
true
}
mod.specials_mut.breeds_overrides = {
skaven_ratling_gunner = {
hitzone_primary_armor_categories = table.clone(hitzone_primary_armor_categories),
armor_category = 2,
primary_armor_category = 6,
run_speed = 8,
walk_speed = 6,
},
chaos_vortex_sorcerer = {
hitzone_primary_armor_categories = table.clone(hitzone_primary_armor_categories),
armor_category = 2,
primary_armor_category = 6,
},
skaven_poison_wind_globadier = {
armor_category = 2,
run_speed = 5,
walk_speed = 4,
},
skaven_warpfire_thrower = {
hitzone_primary_armor_categories = table.clone(hitzone_primary_armor_categories_warpfire_thrower),
hitzone_multiplier_types = table.clone(hitzone_multiplier_types_warpfire_thrower),
armor_category = 2,
primary_armor_category = 6,
run_speed = 5,
walk_speed = 4,
}
}
local breeds_overrides = mod.specials_mut.breeds_overrides
mod.specials_mut.breed_actions_overrides = {
skaven_ratling_gunner = {
shoot_ratling_gun = {
ignore_staggers = table.clone(ignore_staggers)
}
},
skaven_poison_wind_globadier = {
advance_towards_players = {
time_until_first_throw = {
0,
1
},
throw_at_distance = {
5,
40
},
range = 60,
},
throw_poison_globe = {
barrage_count = 8,
time_between_throws = {
8,
1
},
},
},
skaven_pack_master = {
skulk = {
ignore_staggers = table.clone(ignore_staggers)
},
follow = {
ignore_staggers = table.clone(ignore_staggers)
},
},
chaos_corruptor_sorcerer = {
grab_attack = {
ignore_staggers = table.clone(ignore_staggers)
},
},
skaven_warpfire_thrower = {
shoot_warpfire_thrower = {
ignore_staggers = table.clone(ignore_staggers)
},
},
}
local breed_actions_overrides = mod.specials_mut.breed_actions_overrides
mod.specials_mut.enable_mut = function()
if not mod.persistent.juiced_specials_backups_done then
return
end
for breed_name, breed_data in pairs( table.clone(breeds_overrides) ) do
Breeds[breed_name] = pl.tablex.merge(Breeds[breed_name], breed_data, true)
end
for breed_name, actions in pairs( table.clone(breed_actions_overrides) ) do
for action_name, action in pairs( actions ) do
BreedActions[breed_name][action_name] =
pl.tablex.merge(BreedActions[breed_name][action_name], action, true)
end
end
mod:hook_enable(BTRatlingGunnerShootAction, "enter")
mod:hook_enable(BTRatlingGunnerWindUpAction, "enter")
mod:hook_enable(BTSkulkAroundAction, "enter")
mod:hook_enable(BTSkulkIdleAction, "enter")
mod:hook_enable(BTNinjaApproachAction, "run")
mod:hook_enable(BTNinjaApproachAction, "enter")
mod:hook_enable(BTTargetPouncedAction, "leave")
mod:hook_enable(BTCrazyJumpAction, "leave")
mod:hook_enable(BTStaggerAction, "leave")
mod:hook_enable(BTConditions, "suicide_run")
mod:hook_enable(BTSuicideRunAction.StateMove, "update")
mod:hook_enable(BTSuicideRunAction.StateMove, "on_enter")
end
mod.specials_mut.disable_hooks = function()
mod:hook_disable(BTRatlingGunnerShootAction, "enter")
mod:hook_disable(BTRatlingGunnerWindUpAction, "enter")
mod:hook_disable(BTSkulkAroundAction, "enter")
mod:hook_disable(BTSkulkIdleAction, "enter")
mod:hook_disable(BTNinjaApproachAction, "run")
mod:hook_disable(BTNinjaApproachAction, "enter")
mod:hook_disable(BTTargetPouncedAction, "leave")
mod:hook_disable(BTCrazyJumpAction, "leave")
mod:hook_disable(BTStaggerAction, "leave")
mod:hook_disable(BTConditions, "suicide_run")
mod:hook_disable(BTSuicideRunAction.StateMove, "update")
mod:hook_disable(BTSuicideRunAction.StateMove, "on_enter")
end
mod.specials_mut.disable_mut = function()
if not mod.persistent.juiced_specials_backups_done then
return
end
Breeds = pl.tablex.merge(Breeds, table.clone(mod.persistent.specials_mut.breeds_backups, true), true)
BreedActions = pl.tablex.merge(BreedActions, table.clone(mod.persistent.specials_mut.breed_actions_backups, true), true)
mod.specials_mut.disable_hooks()
end
mod.specials_mut.is_mut_enabled = function()
return mod:get(mod.SETTING_NAMES.JUICED_SPECIALS_MUTATOR)
end
mod.specials_mut.disabled_units = {}
mod:hook(ConflictDirector, "_post_spawn_unit", function(func, self, ai_unit, go_id, breed, ...)
if not mod.specials_mut.is_mut_enabled() then
return func(self, ai_unit, go_id, breed, ...)
end
if breed.name == "skaven_pack_master" then
Unit.set_local_scale(ai_unit, 0, Vector3(0.85,0.85,0.85))
Unit.disable_physics(ai_unit)
table.insert(mod.specials_mut.disabled_units, ai_unit)
end
return func(self, ai_unit, go_id, breed, ...)
end)
mod.dispatcher:on(
"onModUpdate",
function()
if not mod.specials_mut.is_mut_enabled() then
return
end
for _, unit in ipairs( mod.specials_mut.disabled_units ) do
Unit.enable_physics(unit)
end
mod.specials_mut.disabled_units = {}
end)
mod.juiced_specials_update_func = function()
if Breeds and not mod.persistent.juiced_specials_backups_done then
mod.persistent.juiced_specials_backups_done = true
mod.persistent.specials_mut = {}
mod.persistent.specials_mut.breeds_backups = pl.tablex.merge(Breeds, breeds_overrides)
mod.persistent.specials_mut.breed_actions_backups = pl.tablex.merge(BreedActions, breed_actions_overrides)
-- Actually enable once we have the backups.
if mod.specials_mut.is_mut_enabled() then
mod.specials_mut.enable_mut()
end
end
end
table.insert(mod.update_funcs, function() mod.juiced_specials_update_func() end)
mod.specials_mut.on_mutator_toggled = function()
if mod.specials_mut.is_mut_enabled() then
mod.specials_mut.enable_mut()
else
mod.specials_mut.disable_mut()
end
end
mod.dispatcher:on("juicedSpecialsToggled",
function(...)
mod.specials_mut.on_mutator_toggled(...)
end)
mod.dispatcher:on("onModDisabled",
function()
mod.specials_mut.disable_hooks()
end)
mod.dispatcher:on("onModEnabled",
function()
mod.specials_mut.on_mutator_toggled()
end)
mod.specials_mut.disable_hooks()
|
data:extend({
{
type = "technology",
name = "stack-inserter-2",
icon = "__base__/graphics/technology/stack-inserter.png",
icon_size = 128,
effects =
{
{
type = "unlock-recipe",
recipe = "express-stack-inserter"
},
{
type = "unlock-recipe",
recipe = "express-stack-filter-inserter"
},
},
prerequisites = { "logistics-3" },
unit =
{
count = 300,
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
{"production-science-pack", 1}
},
time = 30
},
upgrade = true,
order = "c-o-a"
}
})
|
local nvim_lsp = require('lspconfig')
-- IMPORTANT: use npm for installing language servers. Copy the command below:
-- npm install -g typescript typescript-language-server diagnostic-languageserver eslint_d pyright
-- Python
nvim_lsp['pyright'].setup {}
-- Rust language server
require('rust-tools').setup({
tools = {
hover_with_actions = false,
runnables = {
use_telescope = false
},
debuggables = {
use_telescope = false
},
}
})
-- Enable null-ls integration for eslint integration
require("null-ls").config {}
nvim_lsp["null-ls"].setup {}
-- TypeScript language server
nvim_lsp.tsserver.setup {
on_attach = function(client, bufnr)
-- disable tsserver formatting if you plan on formatting via null-ls
client.resolved_capabilities.document_formatting = false
client.resolved_capabilities.document_range_formatting = false
local ts_utils = require("nvim-lsp-ts-utils")
ts_utils.setup {
debug = false,
disable_commands = false,
enable_import_on_completion = true,
import_all_timeout = 5000, -- ms
import_all_priorities = {
buffers = 4, -- loaded buffer names
buffer_content = 3, -- loaded buffer content
local_files = 2, -- git files or files with relative path markers
same_file = 1, -- add to existing import statement
},
import_all_scan_buffers = 100,
import_all_select_source = false,
-- eslint
eslint_enable_code_actions = true,
eslint_enable_disable_comments = true,
eslint_bin = "eslint_d",
eslint_enable_diagnostics = false,
eslint_opts = {},
-- formatting
enable_formatting = true,
formatter = "prettier",
formatter_opts = {},
-- update imports on file move
update_imports_on_move = true,
require_confirmation_on_move = false,
watch_dir = nil,
-- filter diagnostics
filter_out_diagnostics_by_severity = {},
filter_out_diagnostics_by_code = {},
}
-- required to fix code action ranges and filter diagnostics
ts_utils.setup_client(client)
-- no default maps, so you may want to define some here
local opts = { silent = true }
vim.api.nvim_buf_set_keymap(bufnr, "n", "gs", ":TSLspOrganize<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", ":TSLspRenameFile<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", ":TSLspImportAll<CR>", opts)
-- disable tsserver formatting
client.resolved_capabilities.document_formatting = false
-- define an alias
vim.cmd("command -buffer Formatting lua vim.lsp.buf.formatting()")
vim.cmd("command -buffer FormattingSync lua vim.lsp.buf.formatting_sync()")
-- format on save
vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()")
end
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.