content
string |
|---|
-- (Super)MultiFurnace Controller (did I mention, it's SUPER!?)
-- This app is designed to wrap up to 4 of kepler155c's furni.lua (multiFurni) arrays and divide up workload,
-- it functions as a straight drop-in for furni.lua and no other adjustments are required to make it work.
-- Additionally, you get the ability to target any one multiFurni array for smelting when creating the machine recipe in Milo
-- Further uses for this direct targeting can be limited-scope auto-smelting, using anywhere from 1/2 to 1/4 of your total
-- capacity to auto-smelt, leaving the rest of the cluster available for you when you want it, great for multi-user bases!
-- Plug this turtle into a modem on your Milo network, and another modem leading to 2-4 turtles running furni.lua (or even furniController.lua for chained setups)
-- Slots are as follows:
-- 1: Master Furnace Input
-- 2: Master Furnace Fuel Input
-- 3: Master Furnace Output
-- 4: Optional (Options: "fuel"/"input"/"output"/nil (Default: nil [ignore]))
-- 5-8: Furnace Inputs for 2 to 4 furni.lua arrays (slots mapped in order ascending, T1_Input=4, T2_Input=5, etc)
-- 9-12: Furnace Fuels for 2 to 4 furni.lua arrays
-- 13-16: Furnace Outputs for 2 to 4 furni.lua arrays
-- Only user option, slot 4, what to use it for?
local useSlot4 = nil
-- Begin main program code
-- Find modem with -only- turtles attached (these should be our furni/furniController arrays)
local devModem = ""
for _, modem in ipairs({peripheral.find("modem")}) do
if #modem.getNamesRemote() > 1 then -- We're only looking for 2 or more devices on a network segment, ignore anything less
local nTurtles = 0
for _, dev in ipairs(modem.getNamesRemote()) do
if modem.getTypeRemote(dev) == "turtle" then nTurtles = nTurtles + 1 end
end
if nTurtles == #modem.getNamesRemote() then
devModem = modem
break
end
end
end
if devModem ~= "" then
print("Found turtle-only modem, detected", #devModem.getNamesRemote(), "turtles", (#devModem.getNamesRemote() > 4 and "(Max 4 will be mapped)" or "(All will be mapped)"))
else
print("Did not find a modem with only turtles connected. Please check your networking cables/modems and devices, then try again.")
return -- We don't have a modem, halt
end
local devTurtles = {}
for _, dev in ipairs(devModem.getNamesRemote()) do
if #devTurtles >= 4 then break end
devTurtles[#devTurtles+1] = peripheral.wrap(dev)
print("Mapping", devTurtles[#devTurtles].getLabel(), "("..dev..")", "as device", #devTurtles)
devTurtles[#devTurtles].inputSlot = #devTurtles + 4 -- Set the input for this device on second row
devTurtles[#devTurtles].fuelSlot = #devTurtles + 8 -- Set the fuel for this device on third row
devTurtles[#devTurtles].outputSlot = #devTurtles + 12 -- Set the output for this device on fourth row
if devTurtles[#devTurtles].isOn() then
print("Resynchronizing", devTurtles[#devTurtles].getLabel())
devTurtles[#devTurtles].reboot()
else
print("Powering", devTurtles[#devTurtles].getLabel(), "on")
devTurtles[#devTurtles].turnOn()
end
end
local function listInventory() -- Supplement a local .list()-like function
local tList = {}
for i = 1, 16 do
local slotData = turtle.getItemDetail(i) -- DWGFJTLR
if slotData ~= nil then
slotData.maxStack=turtle.getItemCount(i) + turtle.getItemSpace(i)
tList[i] = slotData
end
end
return tList
end
local function manageLocalResources()
--print("Input found")
local itemCount = turtle.getItemCount(1) / #devTurtles
if itemCount < 1 then itemCount = 1 end -- Patch for single items fed into master slot
if turtle.getItemCount(1) > 0 then -- Input
for _, dev in ipairs(devTurtles) do
if turtle.select(1) and ((turtle.compareTo(dev.inputSlot) and turtle.getItemSpace(dev.inputSlot) > 0) or turtle.getItemCount(dev.inputSlot) == 0) then -- Move Input
turtle.transferTo(dev.inputSlot, itemCount)
end
if useSlot4 == "input" and turtle.select(4) and ((turtle.compareTo(dev.inputSlot) and turtle.getItemSpace(dev.inputSlot) > 0) or turtle.getItemCount(dev.inputSlot) == 0) then -- Move Input
turtle.transferTo(dev.inputSlot, itemCount)
end --Slot 4 input
end
end
if turtle.select(2) and turtle.getSelectedSlot() == 2 then -- Fuel
for _, dev in ipairs(devTurtles) do
if turtle.compareTo(dev.fuelSlot) or turtle.getItemCount(dev.fuelSlot) == 0 then turtle.transferTo(dev.fuelSlot,64) end -- Move fuel into slot
end
end
if useSlot4 == "fuel" and turtle.select(4) and turtle.getSelectedSlot() == 4 then -- Fuel
for _, dev in ipairs(devTurtles) do
if turtle.compareTo(dev.fuelSlot) or turtle.getItemCount(dev.fuelSlot) == 0 then turtle.transferTo(dev.fuelSlot,64) end -- Move fuel into slot
end
end -- Slot 4 fuel
for _, dev in ipairs(devTurtles) do
if turtle.getItemCount(3) == 0 and turtle.getItemCount(dev.outputSlot) > 0 then
turtle.select(dev.outputSlot)
turtle.transferTo(3, 64)
elseif turtle.getItemCount(dev.outputSlot) > 0 and turtle.select(3) and turtle.compareTo(dev.outputSlot) then -- Move output
--turtle.setStatus("moving")
turtle.select(dev.outputSlot)
turtle.transferTo(3, 64)
end
if useSlot4 == "output" then -- Slot 4 output
if turtle.getItemCount(4) == 0 and turtle.getItemCount(dev.outputSlot) > 0 then
turtle.select(dev.outputSlot)
turtle.transferTo(4, 64)
elseif turtle.getItemCount(dev.outputSlot) > 0 and turtle.select(4) and turtle.compareTo(dev.outputSlot) then
turtle.select(dev.outputSlot)
turtle.transferTo(4, 64)
end
end
end
end
local function manageRemoteResources()
local localList = listInventory()
for _, dev in ipairs(devTurtles) do
local devList = dev.list()
--print(textutils.serialize(devList))
if devList[2] == nil then
if localList[dev.fuelSlot] ~= nil then
turtle.setStatus("fueling")
dev.pullItems(devModem.getNameLocal(), dev.fuelSlot, 64, 2)
end
else
if localList[dev.fuelSlot] ~= nil and localList[dev.fuelSlot].name == devList[2].name then
turtle.setStatus("fueling")
dev.pullItems(devModem.getNameLocal(), dev.fuelSlot, 64, 2)
end
end
if devList[1] == nil then
if localList[dev.inputSlot] ~= nil then
turtle.setStatus("pushing")
dev.pullItems(devModem.getNameLocal(), dev.inputSlot, 64, 1)
end
else
if localList[dev.inputSlot] ~= nil and localList[dev.inputSlot].name == devList[1].name then
turtle.setStatus("pushing")
dev.pullItems(devModem.getNameLocal(), dev.inputSlot, 64, 1)
end
end -- Move input
if devList[3] ~= nil then
if localList[dev.outputSlot] == nil then
turtle.setStatus("pulling")
dev.pushItems(devModem.getNameLocal(), 3, 64, dev.outputSlot)
end
else
if localList[dev.outputSlot] ~= nil then
if devList[3] ~= nil and localList[dev.outputSlot].name == devList[3].name then
turtle.setStatus("pulling")
dev.pushItems(devModem.getNameLocal(), 3, 64, dev.outputSlot)
end
end
end
end
end
while true do -- Main Loop
local turtleList = listInventory()
if turtleList[1] ~= nil or turtleList[13] ~= nil or turtleList[14] ~= nil or turtleList[15] ~= nil or turtleList[16] ~= nil or ((useSlot4 == "input" or useSlot4 == "fuel") and turtleList[4] ~= nil) then
manageLocalResources()
end
manageRemoteResources()
turtle.setStatus("sleeping")
sleep(1)
end
|
local PANEL = {}
AccessorFunc( PANEL, "m_strName", "Name" )
AccessorFunc( PANEL, "m_strPath", "Path" )
AccessorFunc( PANEL, "m_strFilter", "FileTypes" )
AccessorFunc( PANEL, "m_strBaseFolder", "BaseFolder" )
AccessorFunc( PANEL, "m_strCurrentFolder", "CurrentFolder" )
AccessorFunc( PANEL, "m_strSearch", "Search" )
AccessorFunc( PANEL, "m_bModels", "Models" )
AccessorFunc( PANEL, "m_bOpen", "Open" )
function PANEL:Init()
self:SetPath( "GAME" )
self.Divider = self:Add( "DHorizontalDivider" )
self.Divider:Dock( FILL )
self.Divider:SetLeftWidth( 160 )
self.Divider:SetDividerWidth( 4 )
self.Divider:SetLeftMin( 100 )
self.Divider:SetRightMin( 100 )
self.Tree = self.Divider:Add( "DTree" )
self.Divider:SetLeft( self.Tree )
self.Tree.DoClick = function( _, node )
local folder = node:GetFolder()
if ( !folder ) then return end
self:SetCurrentFolder( folder )
end
end
function PANEL:SetName( strName )
if ( strName ) then
self.m_strName = tostring( strName )
else
self.m_strName = nil
end
if ( !self.bSetup ) then return end
self:SetupTree()
end
function PANEL:SetBaseFolder( strBase )
self.m_strBaseFolder = tostring( strBase )
if ( !self.bSetup ) then return end
self:SetupTree()
end
function PANEL:SetPath( strPath )
self.m_strPath = tostring( strPath )
if ( !self.bSetup ) then return end
self:SetupTree()
end
function PANEL:SetSearch( strSearch )
if ( !strSearch || strSearch == "" ) then
strSearch = "*"
end
self.m_strSearch = tostring( strSearch )
if ( !self.bSetup ) then return end
self:SetupTree()
end
function PANEL:SetFileTypes( strTypes )
self.m_strFilter = tostring( strTypes || "*.*" )
if ( !self.bSetup ) then return end
if ( self.m_strCurrentFolder ) then
self:ShowFolder( self.m_strCurrentFolder )
end
end
function PANEL:SetModels( bUseModels )
self.m_bModels = tobool( bUseModels )
if ( !self.bSetup ) then return end
self:SetupFiles()
if ( self.m_strCurrentFolder ) then
self:ShowFolder( self.m_strCurrentFolder )
end
end
function PANEL:SetCurrentFolder( strDir )
strDir = tostring( strDir )
strDir = string.Trim( strDir, "/" )
if ( self.m_strBaseFolder && !string.StartWith( strDir, self.m_strBaseFolder ) ) then
strDir = string.Trim( self.m_strBaseFolder, "/" ) .. "/" .. string.Trim( strDir, "/" )
end
self.m_strCurrentFolder = strDir
if ( !self.bSetup ) then return end
self:ShowFolder( strDir )
end
function PANEL:SetOpen( bOpen, bAnim )
bOpen = tobool( bOpen )
self.m_bOpen = bOpen
if ( !self.bSetup ) then return end
self.FolderNode:SetExpanded( bOpen, !bAnim )
self.m_bOpen = bOpen
self:SetCookie( "Open", bOpen && "1" || "0" )
end
function PANEL:Paint( w, h )
DPanel.Paint( self, w, h )
if ( !self.bSetup ) then
self.bSetup = self:Setup()
end
end
function PANEL:SetupTree()
local name = self.m_strName
if ( !name ) then name = string.Trim( string.match( self.m_strBaseFolder, "/.+$" ) || self.m_strBaseFolder, "/" ) end
local children = self.Tree.RootNode.ChildNodes
if ( IsValid( children ) ) then
children:Clear()
end
self.FolderNode = self.Tree.RootNode:AddFolder( name, self.m_strBaseFolder, self.m_strPath, false, self.m_strSearch )
self.Tree.RootNode.ChildExpanded = function( node, bExpand )
DTree_Node.ChildExpanded( node, bExpand )
self.m_bOpen = tobool( self.FolderNode.m_bExpanded )
self:SetCookie( "Open", self.m_bOpen && "1" || "0" )
end
self.FolderNode:SetExpanded( self.m_bOpen, true )
self:SetCookie( "Open", self.m_bOpen && "1" || "0" )
self:ShowFolder()
return true
end
function PANEL:SetupFiles()
if ( IsValid( self.Files ) ) then self.Files:Remove() end
if ( self.m_bModels ) then
self.Files = self.Divider:Add( "DIconBrowser" )
self.Files:SetManual( true )
self.Files:SetBackgroundColor( Color( 234, 234, 234 ) )
else
self.Files = self.Divider:Add( "DListView" )
self.Files:SetMultiSelect( false )
self.FileHeader = self.Files:AddColumn( "Files" ).Header
self.Files.DoDoubleClick = function( pnl, _, line )
self:OnDoubleClick( string.Trim( self:GetCurrentFolder() .. "/" .. line:GetColumnText( 1 ), "/" ), line )
end
self.Files.OnRowSelected = function( pnl, _, line )
self:OnSelect( string.Trim( self:GetCurrentFolder() .. "/" .. line:GetColumnText( 1 ), "/" ), line )
end
self.Files.OnRowRightClick = function( pnl, _, line )
self:OnRightClick( string.Trim( self:GetCurrentFolder() .. "/" .. line:GetColumnText( 1 ), "/" ), line )
end
end
self.Divider:SetRight( self.Files )
if ( self.m_strCurrentFolder && self.m_strCurrentFolder != "" ) then
self:ShowFolder( self.m_strCurrentFolder )
end
return true
end
function PANEL:Setup()
if ( !self.m_strBaseFolder ) then return false end
return self:SetupTree() && self:SetupFiles()
end
function PANEL:ShowFolder( path )
if ( !IsValid( self.Files ) ) then return end
self.Files:Clear()
if ( IsValid( self.FileHeader ) ) then
self.FileHeader:SetText( path || "Files" )
end
if ( !path ) then return end
local filters = self.m_strFilter
if ( !filters || filters == "" ) then
filters = "*.*"
end
for _, filter in pairs( string.Explode( " ", filters ) ) do
local files = file.Find( string.Trim( path .. "/" .. ( filter || "*.*" ), "/" ), self.m_strPath )
if ( !istable( files ) ) then continue end
for _, v in pairs( files ) do
if ( self.m_bModels ) then
local icon = self.Files:Add( "SpawnIcon" )
icon:SetModel( path .. "/" .. v )
icon.DoClick = function( pnl )
if ( pnl.LastClickTime && SysTime() - pnl.LastClickTime < 0.3 ) then
self:OnDoubleClick( path .. "/" .. v, icon )
else
self:OnSelect( path .. "/" .. v, icon )
end
pnl.LastClickTime = SysTime()
end
icon.DoRightClick = function()
self:OnRightClick( path .. "/" .. v, icon )
end
else
self.Files:AddLine( v )
end
end
end
end
function PANEL:SortFiles( desc )
if ( !self:GetModels() ) then
self.Files:SortByColumn( 1, tobool( desc ) )
end
end
function PANEL:GetFolderNode()
return self.FolderNode
end
function PANEL:Clear()
DPanel.Clear( self )
self.m_strBaseFolder, self.m_strCurrentFolder, self.m_strFilter, self.m_strName, self.m_strSearch, self.Divider.m_pRight = nil
self.m_bOpen, self.m_bModels, self.m_strPath = false, false, "GAME"
self.bSetup = nil
self:Init()
end
function PANEL:LoadCookies()
self:SetOpen( self:GetCookieNumber( "Open" ), true )
end
function PANEL:OnSelect( path, pnl )
-- For override
end
function PANEL:OnDoubleClick( path, pnl )
-- For override
end
function PANEL:OnRightClick( path, pnl )
-- For override
end
function PANEL:GenerateExample( class, sheet, w, h )
local browser = vgui.Create( class, frame )
browser:Dock( FILL )
browser:DockMargin( 5, 0, 5, 5 )
browser:SetPath( "GAME" ) -- The access path i.e. GAME, LUA, DATA etc.
browser:SetBaseFolder( "data" ) -- The root folder
browser:SetOpen( true ) -- Open the tree to show sub-folders
function browser:OnSelect( path, pnl ) -- Called when a file is clicked
-- Do something
end
sheet:AddSheet( class, browser, nil, true, true )
end
derma.DefineControl( "DFileBrowser", "A tree and list-based file browser", PANEL, "DPanel" )
|
WorldManager = WorldManager or BaseClass(BaseHotUpdate)
function WorldManager:__init()
if WorldManager.Instance then
ErrorLog("[WorldManager] Attemp to create a singleton twice !")
end
WorldManager.Instance = self
end
function WorldManager:__delete()
WorldManager.Instance = nil
end
function WorldManager:GetCWorld()
return C_World:GetInstWorld()
end
function WorldManager:MailToUser(role_id, c_mailcontentparam)
C_MailRoute:MailToUser(C_LuaToCFun:IntToUid_Inline(role_id), 0, c_mailcontentparam)
end
function WorldManager:BroadcastMsg(msg)
C_LuaToCFun:BroadcastMsg(msg)
end
function WorldManager:WriteLog(log)
C_LuaToCFun:WriteLog(log)
end
-- 服务器启动完成
function WorldManager:OnServerStart()
IS_SERVER_STARTING = false
end
function WorldManager:OnWorldUpdate(interval, now_second)
MemManager.Instance:Update(interval, now_second)
end
|
--- Returns Get/Convert and Check functions for the given Enum
-- EnumItems can also be Strings, Integer
-- See: https://developer.roblox.com/en-us/articles/Enumeration
local t = require(script.Parent.t)
local IsValidEnumValue = t.union(
t.EnumItem,
t.integer,
t.string
)
local function EnumType(enum)
assert(t.Enum(enum))
local enumItems = {}
local enumIntegers = {}
local enumNames = {}
for _, enumItem in ipairs(enum:GetEnumItems()) do
enumItems[enumItem] = enumItem
enumIntegers[enumItem.Value] = enumItem
enumNames[enumItem.Name] = enumItem
end
local function Get(value)
if t.EnumItem(value) then
return enumItems[value]
elseif t.integer(value) then
return enumIntegers[value]
elseif t.string(value) then
return enumNames[value]
end
return nil
end
local function Check(value)
local enumValueSuccess, enumValueMessage
= IsValidEnumValue(value)
if enumValueSuccess == false then
return false, enumValueMessage
end
local enumItem = Get(value)
if enumItem then
return true, enumItem
end
local message = "invalid object"
if t.EnumItem(value) then
message = "invalid EnumItem: " .. value.Name
elseif t.integer(value) then
message = "invalid enum value: " .. tostring(value)
elseif t.string(value) then
message = "invalid string: " .. value
end
return false, message
end
local function CheckAndGet(value)
local checkSuccess, checkMessage
= Check(value)
if checkSuccess == false then
return false, checkMessage
end
return checkMessage
end
return {
Get = Get,
Check = Check,
CheckAndGet = CheckAndGet,
}
end
-- caching
local enumTypes = {}
return function(enum)
assert(t.Enum(enum))
local enumType = enumTypes[enum]
if enumType then
return enumType
end
enumType = EnumType(enum)
enumTypes[enum] = enumType
return enumType
end
|
-- This file was @generated by Tarmac. It is not intended for manual editing.
return {
icons = {
activity = "rbxassetid://7072977617",
airplay = "rbxassetid://7072977798",
["alert-circle"] = "rbxassetid://7072978559",
["alert-octagon"] = "rbxassetid://7072978894",
["alert-triangle"] = "rbxassetid://7072980286",
["align-center"] = "rbxassetid://7072980488",
["align-justify"] = "rbxassetid://7072980642",
["align-left"] = "rbxassetid://7072980796",
["align-right"] = "rbxassetid://7072980973",
anchor = "rbxassetid://7072981218",
aperture = "rbxassetid://7072981376",
archive = "rbxassetid://7072981580",
["arrow-down"] = "rbxassetid://7072982593",
["arrow-down-circle"] = "rbxassetid://7072981875",
["arrow-down-left"] = "rbxassetid://7072982054",
["arrow-down-right"] = "rbxassetid://7072982242",
["arrow-left"] = "rbxassetid://7072983528",
["arrow-left-circle"] = "rbxassetid://7072983289",
["arrow-right"] = "rbxassetid://7072705339",
["arrow-right-circle"] = "rbxassetid://7072705277",
["arrow-up"] = "rbxassetid://7072983757",
["arrow-up-circle"] = "rbxassetid://7072705395",
["arrow-up-left"] = "rbxassetid://7072705464",
["arrow-up-right"] = "rbxassetid://7072705511",
["at-sign"] = "rbxassetid://7072705637",
award = "rbxassetid://7072705696",
["bar-chart"] = "rbxassetid://7072705810",
["bar-chart-2"] = "rbxassetid://7072705757",
battery = "rbxassetid://7072705915",
["battery-charging"] = "rbxassetid://7072705871",
bell = "rbxassetid://7072706001",
["bell-off"] = "rbxassetid://7072705964",
bluetooth = "rbxassetid://7072706050",
bold = "rbxassetid://7072706123",
book = "rbxassetid://7072706216",
["book-open"] = "rbxassetid://7072706165",
bookmark = "rbxassetid://7072706263",
box = "rbxassetid://7072706318",
briefcase = "rbxassetid://7072706351",
calendar = "rbxassetid://7072706388",
camera = "rbxassetid://7072706467",
["camera-off"] = "rbxassetid://7072706425",
cast = "rbxassetid://7072706505",
check = "rbxassetid://7072706620",
["check-circle"] = "rbxassetid://7072706536",
["check-square"] = "rbxassetid://7072706576",
["chevron-down"] = "rbxassetid://7072706663",
["chevron-left"] = "rbxassetid://7072706703",
["chevron-right"] = "rbxassetid://7072706745",
["chevron-up"] = "rbxassetid://7072706796",
["chevrons-down"] = "rbxassetid://7072706838",
["chevrons-left"] = "rbxassetid://7072706889",
["chevrons-right"] = "rbxassetid://7072706959",
["chevrons-up"] = "rbxassetid://7072707021",
chrome = "rbxassetid://7072707083",
circle = "rbxassetid://7072707153",
clipboard = "rbxassetid://7072707198",
clock = "rbxassetid://7072707248",
cloud = "rbxassetid://7072707488",
["cloud-drizzle"] = "rbxassetid://7072707291",
["cloud-lightning"] = "rbxassetid://7072707328",
["cloud-off"] = "rbxassetid://7072707378",
["cloud-rain"] = "rbxassetid://7072707410",
["cloud-snow"] = "rbxassetid://7072707452",
code = "rbxassetid://7072707514",
codepen = "rbxassetid://7072707555",
codesandbox = "rbxassetid://7072707588",
coffee = "rbxassetid://7072707647",
columns = "rbxassetid://7072707678",
command = "rbxassetid://7072707704",
compass = "rbxassetid://7072707731",
copy = "rbxassetid://7072707790",
["corner-down-left"] = "rbxassetid://7072707837",
["corner-down-right"] = "rbxassetid://7072707873",
["corner-left-down"] = "rbxassetid://7072707920",
["corner-left-up"] = "rbxassetid://7072707972",
["corner-right-down"] = "rbxassetid://7072708038",
["corner-right-up"] = "rbxassetid://7072708086",
["corner-up-left"] = "rbxassetid://7072708139",
["corner-up-right"] = "rbxassetid://7072708207",
cpu = "rbxassetid://7072708278",
crop = "rbxassetid://7072715283",
crosshair = "rbxassetid://7072715317",
database = "rbxassetid://7072715353",
delete = "rbxassetid://7072715407",
diskette = "rbxassetid://7072729672",
divide = "rbxassetid://7072715593",
["divide-circle"] = "rbxassetid://7072715480",
["divide-square"] = "rbxassetid://7072715517",
["dollar-sign"] = "rbxassetid://7072715646",
download = "rbxassetid://7072715769",
["download-cloud"] = "rbxassetid://7072715724",
droplet = "rbxassetid://7072715827",
edit = "rbxassetid://7072715962",
["edit-2"] = "rbxassetid://7072715877",
["edit-3"] = "rbxassetid://7072715920",
electricity = "rbxassetid://7072727506",
["electricity-off"] = "rbxassetid://7072727374",
["external-link"] = "rbxassetid://7072716017",
eye = "rbxassetid://7072716095",
["eye-off"] = "rbxassetid://7072984146",
["fast-forward"] = "rbxassetid://7072716155",
feather = "rbxassetid://7072716196",
figma = "rbxassetid://7072716233",
file = "rbxassetid://7072716417",
["file-minus"] = "rbxassetid://7072716296",
["file-plus"] = "rbxassetid://7072716346",
["file-text"] = "rbxassetid://7072716382",
film = "rbxassetid://7072716468",
filter = "rbxassetid://7072716507",
flag = "rbxassetid://7072716549",
folder = "rbxassetid://7072716775",
["folder-minus"] = "rbxassetid://7072716603",
["folder-plus"] = "rbxassetid://7072716655",
framer = "rbxassetid://7072716827",
frown = "rbxassetid://7072716874",
gift = "rbxassetid://7072984974",
["git-branch"] = "rbxassetid://7072985221",
["git-commit"] = "rbxassetid://7072717139",
["git-merge"] = "rbxassetid://7072717190",
["git-pull-request"] = "rbxassetid://7072717235",
github = "rbxassetid://7072717281",
gitlab = "rbxassetid://7072717318",
globe = "rbxassetid://7072717348",
grid = "rbxassetid://7072717393",
["hard-drive"] = "rbxassetid://7072717436",
hash = "rbxassetid://7072717475",
headphones = "rbxassetid://7072717514",
heart = "rbxassetid://7072717560",
["help-circle"] = "rbxassetid://7072717605",
hexagon = "rbxassetid://7072717639",
home = "rbxassetid://7072717697",
image = "rbxassetid://7072717759",
inbox = "rbxassetid://7072717806",
info = "rbxassetid://7072717857",
italic = "rbxassetid://7072717909",
key = "rbxassetid://7072717958",
layers = "rbxassetid://7072718011",
layout = "rbxassetid://7072718072",
["life-buoy"] = "rbxassetid://7072718122",
link = "rbxassetid://7072718226",
["link-2"] = "rbxassetid://7072718185",
list = "rbxassetid://7072718266",
loader = "rbxassetid://7072718307",
lock = "rbxassetid://7072718362",
["log-in"] = "rbxassetid://7072718412",
["log-out"] = "rbxassetid://7072718459",
mail = "rbxassetid://7072718524",
map = "rbxassetid://7072718631",
["map-pin"] = "rbxassetid://7072718576",
maximize = "rbxassetid://7072718726",
["maximize-2"] = "rbxassetid://7072718683",
meh = "rbxassetid://7072718776",
menu = "rbxassetid://7072718840",
["message-circle"] = "rbxassetid://7072985918",
["message-square"] = "rbxassetid://7072718943",
mic = "rbxassetid://7072719066",
["mic-off"] = "rbxassetid://7072986489",
minimize = "rbxassetid://7072719185",
["minimize-2"] = "rbxassetid://7072719125",
minus = "rbxassetid://7072719338",
["minus-circle"] = "rbxassetid://7072719240",
["minus-square"] = "rbxassetid://7072719290",
monitor = "rbxassetid://7072719383",
moon = "rbxassetid://7072719446",
["more-horizontal"] = "rbxassetid://7072719490",
["more-vertical"] = "rbxassetid://7072719531",
["mouse-pointer"] = "rbxassetid://7072719587",
move = "rbxassetid://7072719634",
music = "rbxassetid://7072719671",
navigation = "rbxassetid://7072719750",
["navigation-2"] = "rbxassetid://7072719710",
octagon = "rbxassetid://7072719805",
package = "rbxassetid://7072719866",
paperclip = "rbxassetid://7072719929",
pause = "rbxassetid://7072720054",
["pause-circle"] = "rbxassetid://7072719997",
["pen-tool"] = "rbxassetid://7072986821",
percent = "rbxassetid://7072987072",
phone = "rbxassetid://7072720576",
["phone-call"] = "rbxassetid://7072720243",
["phone-forwarded"] = "rbxassetid://7072720287",
["phone-incoming"] = "rbxassetid://7072720343",
["phone-missed"] = "rbxassetid://7072720397",
["phone-off"] = "rbxassetid://7072720448",
["phone-outgoing"] = "rbxassetid://7072720508",
["pie-chart"] = "rbxassetid://7072720623",
play = "rbxassetid://7072720722",
["play-circle"] = "rbxassetid://7072720676",
plus = "rbxassetid://7072720870",
["plus-circle"] = "rbxassetid://7072720786",
["plus-square"] = "rbxassetid://7072720824",
pocket = "rbxassetid://7072720922",
power = "rbxassetid://7072720961",
printer = "rbxassetid://7072721007",
radio = "rbxassetid://7072721039",
["refresh-ccw"] = "rbxassetid://7072721083",
["refresh-cw"] = "rbxassetid://7072721134",
["repeat"] = "rbxassetid://7072721188",
rewind = "rbxassetid://7072721231",
["rotate-ccw"] = "rbxassetid://7072721274",
["rotate-cw"] = "rbxassetid://7072721335",
rss = "rbxassetid://7072721390",
save = "rbxassetid://7072721454",
scissors = "rbxassetid://7072721511",
search = "rbxassetid://7072721559",
send = "rbxassetid://7072721598",
server = "rbxassetid://7072721644",
settings = "rbxassetid://7072721682",
share = "rbxassetid://7072721777",
["share-2"] = "rbxassetid://7072721734",
shield = "rbxassetid://7072721855",
["shield-off"] = "rbxassetid://7072721821",
["shopping-bag"] = "rbxassetid://7072721904",
["shopping-cart"] = "rbxassetid://7072721954",
shuffle = "rbxassetid://7072722071",
sidebar = "rbxassetid://7072722188",
["skip-back"] = "rbxassetid://7072722377",
["skip-forward"] = "rbxassetid://7072722426",
slack = "rbxassetid://7072722471",
slash = "rbxassetid://7072722603",
sliders = "rbxassetid://7072987508",
smartphone = "rbxassetid://7072722824",
smile = "rbxassetid://7072722883",
speaker = "rbxassetid://7072722921",
square = "rbxassetid://7072722963",
star = "rbxassetid://7072723006",
["stop-circle"] = "rbxassetid://7072723057",
sun = "rbxassetid://7072723105",
sunrise = "rbxassetid://7072723138",
sunset = "rbxassetid://7072723184",
tablet = "rbxassetid://7072723236",
tag = "rbxassetid://7072723282",
target = "rbxassetid://7072723337",
terminal = "rbxassetid://7072723389",
thermometer = "rbxassetid://7072723437",
["thumbs-down"] = "rbxassetid://7072723488",
["thumbs-up"] = "rbxassetid://7072723542",
["toggle-left"] = "rbxassetid://7072723598",
["toggle-right"] = "rbxassetid://7072723637",
tool = "rbxassetid://7072723685",
trash = "rbxassetid://7072723769",
["trash-2"] = "rbxassetid://7072723727",
trello = "rbxassetid://7072723812",
["trending-down"] = "rbxassetid://7072723858",
["trending-up"] = "rbxassetid://7072723932",
triangle = "rbxassetid://7072723974",
truck = "rbxassetid://7072724026",
tv = "rbxassetid://7072724072",
type = "rbxassetid://7072724114",
umbrella = "rbxassetid://7072724162",
underline = "rbxassetid://7072724193",
unlock = "rbxassetid://7072724229",
upload = "rbxassetid://7072724296",
["upload-cloud"] = "rbxassetid://7072724260",
user = "rbxassetid://7072724538",
["user-check"] = "rbxassetid://7072724349",
["user-minus"] = "rbxassetid://7072724399",
["user-plus"] = "rbxassetid://7072724441",
["user-x"] = "rbxassetid://7072724480",
users = "rbxassetid://7072988037",
video = "rbxassetid://7072988443",
["video-off"] = "rbxassetid://7072988214",
voicemail = "rbxassetid://7072988652",
volume = "rbxassetid://7072724984",
["volume-1"] = "rbxassetid://7072724847",
["volume-2"] = "rbxassetid://7072724897",
["volume-x"] = "rbxassetid://7072724946",
watch = "rbxassetid://7072725030",
wifi = "rbxassetid://7072725120",
["wifi-off"] = "rbxassetid://7072725070",
wind = "rbxassetid://7072725176",
x = "rbxassetid://7072725342",
["x-circle"] = "rbxassetid://7072725208",
["x-octagon"] = "rbxassetid://7072725256",
["x-square"] = "rbxassetid://7072725299",
["zoom-in"] = "rbxassetid://7072725467",
["zoom-out"] = "rbxassetid://7072725530",
},
}
|
local current = (...)
local load
load = function(path)
local succ, loaded = pcall(require, path)
if not (succ) then
local LC_PATH = current .. '.' .. path
succ, loaded = pcall(require, LC_PATH)
if not (succ) then
LC_PATH = current:gsub("%.[^%..]+$", "") .. '.' .. path
succ, loaded = pcall(require, LC_PATH)
if not (succ) then
error(loaded)
end
end
end
return loaded
end
local codes = load('localeCodes')
local exec
exec = function(command)
local handle = assert(io.popen(command))
local result = handle:read('*all')
handle:close()
return result
end
local split
split = function(input, separator)
if separator == nil then
separator = "%s"
end
local t = { }
local i = 1
for str in string.gmatch(input, "([^" .. separator .. "]+)") do
t[i] = str
i = i + 1
end
return t
end
local shortLocale
shortLocale = function(loc)
loc = loc:gsub('_.+$', '')
return loc
end
local getters = {
linux = function(x)
x = exec('locale')
local splitted = split(x, '\n')
local env = { }
for _, d in pairs(splitted) do
d = split(d, '=')
local g = ""
pcall(function()
g = d[2]:gsub('"', '')
env[d[1]] = g
end)
end
local loc = env.LC_ALL or env.LC_MESSAGES or env.LANG or env.LANGUAGE
return shortLocale(loc)
end,
android = function()
return shortLocale(exec('getprop persist.sys.language'))
end,
windows = function()
local wmic = exec('wmic get os locale')
local codeString = wmic:gsub('Locale', '')
local code = tonumber(codeString, 16)
local loc = codes[code]
return shortLocale(loc)
end,
osx = function()
return shortLocale(exec('defaults read -g AppleLocal'))
end,
ios = function()
return shortLocale(exec('defaults read -g AppleLocal'))
end
}
local cache
local getLocale
getLocale = function(fallback)
if cache then
return cache
end
local platform
if love and love.system and love.system.getOS then
platform = love.system.getOS()
else
error('Locale detection currently works only in LÖVE!')
end
local _exp_0 = platform
if "Linux" == _exp_0 then
cache = getters.linux()
elseif "Android" == _exp_0 then
cache = getters.android()
elseif "OS X" == _exp_0 then
cache = getters.osx()
elseif "Windows" == _exp_0 then
cache = getters.windows()
elseif "iOS" == _exp_0 then
cache = getters.ios()
else
cache = fallback
end
return cache
end
return getLocale
|
vim.g.python3_host_prog = config_dir .. "providers/python3/.venv/bin/python3"
vim.g.python_host_prog = config_dir .. "providers/python2/.venv/bin/python2"
|
local bytes = require('lib.bytes')
local detection = require('lib.attacks.detection')
local english = require('lib.english')
local pkcs7 = require('lib.padding.pkcs7')
local toolbox = require('lib.toolbox')
function figure_out_block_size(oracle)
--[[ Given an oracle, determines the block size it is using for encryption.
--
-- oracle: Function, encryption oracle.
-- return:
-- - Integer, block size.
--]]
local gcd = 0
for i = 1,60 do
gcd = toolbox.gcd(gcd, #oracle(toolbox.replicate_to_match({string.byte('A')}, i)))
end
return gcd
end
function figure_out_enc_pattern_and_len(oracle, ipattern)
--[[ Figures out what ipattern encrypts to under the given oracle, which
-- operates in ECB mode.
--
-- oracle: Function, encryption oracle.
-- ipattern: Array of bytes, of length block_size of the oracle.
-- return:
-- - Array of bytes, the encryption of ipattern.
-- - Integer, length of the hidden data.
--]]
local block_size = #ipattern
local attack = string.rep(bytes.bytearray2string(ipattern), 4)
local required_count = 3
while true do
local enc = bytes.bytearray2string(oracle(bytes.string2bytearray(attack)))
local current_count = 0
for i = 1,#enc-block_size,block_size do
if enc:sub(i, i+block_size-1) == enc:sub(i+block_size, i+2*block_size-1) then
current_count = current_count + 1
end
end
if (current_count >= required_count) then
for i = 1,#enc-2*block_size+1,block_size do
if enc:sub(i, i+block_size-1) == enc:sub(i+block_size, i+2*block_size-1) then
print("Starting enc pattern from: " .. i)
return bytes.string2bytearray(enc:sub(i, i+block_size-1)),
#enc - i - 4*block_size + 1
end
end
end
end
end
function encrypt_until_match_occurs(oracle, input, pattern)
--[[ Encrypts until oracle(input) contains pattern. Returns that
-- oracle(input).
--
-- oracle: Function, encryption oracle.
-- input: Byte array, input to the oracle.
-- pattern: Byte array, pattern to match.
-- return:
-- - Byte array, corresponding oracle(input).
--]]
local pattern_str = bytes.bytearray2string(pattern)
while true do
local enc = bytes.bytearray2string(oracle(input))
for pos = 1,#enc-#pattern+1,#pattern do
if enc:sub(pos, pos+#pattern-1) == pattern_str then
return bytes.string2bytearray(enc)
end
end
end
end
unknown_str_expected = "ALLOHa brothers!!!"
enc_or, dec_or = toolbox.new_encryption_oracle_aes_ecb(bytes.string2bytearray(unknown_str_expected),
{random_prepend = true,
prepend_range = {1,100}})
-- 1. Figure out block size.
local block_size = figure_out_block_size(enc_or)
-- 2. Detect whether it is using ECB.
local is_ecb = detection.detect_ecb(enc_or)
if not is_ecb then
return
end
-- 3. Initialize variables.
local attack_length = block_size * 3
local unknown_str = ""
local identification_pattern = bytes.string2bytearray(string.rep('\x00', block_size))
local enc_pattern, unknown_str_len = figure_out_enc_pattern_and_len(enc_or, identification_pattern)
assert(#enc_pattern == block_size)
print("enc_pattern: " .. bytes.bytearray2hex(enc_pattern))
print("len="..#unknown_str_expected .. " got="..unknown_str_len)
-- 4. Brute valid chars first.
-- Find out what \x0\x0\x0...\x0 encrypts to.
-- Attack with \x0\x0\x0...\x0 AAAAAo
local brute_order = {}
for i = 0,255 do
if english.is_valid_char(string.char(i)) then
table.insert(brute_order, i)
end
end
for i = 0,255 do
if not english.is_valid_char(string.char(i)) then
table.insert(brute_order, i)
end
end
-- 5. Recover unknown string byte by byte.
iter = 1
while iter <= unknown_str_len do
-- Setup an attack string and its encryption.
local num_a = ((-#unknown_str - 1) % block_size + block_size) %
block_size
local attack_str = bytes.bytearray2string(identification_pattern) ..
string.rep('A', num_a)
print("Attack_length " .. #attack_str)
local attack_bytes = bytes.string2bytearray(attack_str)
local enc = bytes.bytearray2string(encrypt_until_match_occurs(enc_or, attack_bytes, enc_pattern))
-- Figure out where the AAAA... pattern starts.
local start_pos = 1
while enc:sub(start_pos, start_pos+block_size - 1) ~= bytes.bytearray2string(enc_pattern) do
start_pos = start_pos + block_size
end
-- Figure out which block to consider.
local block_start_pos = start_pos + block_size +
math.floor(#unknown_str / block_size) * block_size
local block = enc:sub(block_start_pos, block_start_pos + block_size - 1)
for brute_ind = 1,256 do
local brute_ch = brute_order[brute_ind]
local try_str = attack_str .. unknown_str .. string.char(brute_ch)
assert(#try_str % block_size == 0)
local try_bytes = bytes.string2bytearray(try_str)
local try_enc = bytes.bytearray2string(encrypt_until_match_occurs(enc_or, try_bytes, enc_pattern))
-- Find out where the pattern \x00 \x00 starts in the try string.
local try_start_pos = 1
while try_enc:sub(try_start_pos, try_start_pos+block_size - 1) ~= bytes.bytearray2string(enc_pattern) do
try_start_pos = try_start_pos + block_size
end
-- Get the corresponding block.
assert(#try_str - block_size == block_size +
math.floor(#unknown_str / block_size) * block_size)
local try_block = try_enc:sub(try_start_pos + #try_str - block_size,
try_start_pos + #try_str - 1)
if try_block == block then
print("Found a char " .. brute_ch .. " " .. string.char(brute_ch))
-- If this is part of padding.
if (brute_ch == 1) then
unknown_str_len = #unknown_str
print("HERE! " .. unknown_str_len .. " iter=" .. iter)
else
unknown_str = unknown_str .. string.char(brute_ch)
end
break
end
end
iter = iter + 1
end
print("UNKNOWN STRING = " .. unknown_str)
print("Checking correctness...")
assert(unknown_str == unknown_str_expected, "Wrong answer!")
print("OK!")
|
#!/usr/bin/env tarantool
print[[
--------------------------------------------------------------------------------
-- #267: Bad exception catching
--------------------------------------------------------------------------------
]]
box.cfg{
logger="tarantool.log",
slab_alloc_arena=0.1,
}
function pcalltest()
local ERRMSG = "module 'some_invalid_module' not found"
local status, msg = pcall(require, 'some_invalid_module')
if status == false and msg ~= nil and msg:match(ERRMSG) ~= nil then
return 'pcall is ok'
else
return 'pcall is broken'
end
end
local status, msg = xpcall(pcalltest, function(msg)
print('error handler:', msg)
end)
print('pcall inside xpcall:', status, msg)
local status, msg = pcall(function() error('some message') end)
print('pcall with Lua error():', status, msg:match('some message'))
local status, msg = pcall(function()
box.error(box.error.ILLEGAL_PARAMS, 'some message')
end)
print('pcall with box.error():', status, msg)
print('pcall with no return:', select('#', pcall(function() end)))
print('pcall with multireturn:', pcall(function() return 1, 2, 3 end))
os.exit(0)
|
-- ensure.lua: tools to ensure correct code behaviour
-- This file is a part of lua-nucleo library
-- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license)
local error, tostring, pcall, type, pairs, select, next
= error, tostring, pcall, type, pairs, select, next
local math_min, math_max, math_abs = math.min, math.max, math.abs
local string_char = string.char
local tdeepequals,
tstr,
taccumulate,
tnormalize
= import 'lua-nucleo/table.lua'
{
'tdeepequals',
'tstr',
'taccumulate',
'tnormalize'
}
local assert_is_number
= import 'lua-nucleo/typeassert.lua'
{
'assert_is_number'
}
local make_checker
= import 'lua-nucleo/checker.lua'
{
'make_checker'
}
-- TODO: Write tests for this one
local ensure = function(msg, value, ...)
if not value then
error(
"ensure failed: " .. msg
.. ((...) and (": " .. (tostring(...) or "?")) or ""),
2
)
end
return value, ...
end
-- TODO: Write tests for this one
local ensure_equals = function(msg, actual, expected)
return
(actual ~= expected)
and error(
"ensure_equals failed: " .. msg
.. ": actual `" .. tostring(actual)
.. "', expected `" .. tostring(expected)
.. "'",
2
)
or actual -- NOTE: Should be last to allow false and nil values.
end
-- TODO: Write tests for this one
local ensure_tequals = function(msg, actual, expected)
if type(expected) ~= "table" then
error(
"ensure_tequals failed: " .. msg
.. ": bad expected type, must be `table', got `"
.. type(expected) .. "'",
2
)
end
if type(actual) ~= "table" then
error(
"ensure_tequals failed: " .. msg
.. ": bad actual type, expected `table', got `"
.. type(actual) .. "'",
2
)
end
-- TODO: Employ tdiff() (when it would be written)
-- TODO: Use checker to get info on all bad keys!
for k, expected_v in pairs(expected) do
local actual_v = actual[k]
if actual_v ~= expected_v then
error(
"ensure_tequals failed: " .. msg
.. ": bad actual value at key `" .. tostring(k)
.. "': got `" .. tostring(actual_v)
.. "', expected `" .. tostring(expected_v)
.. "'",
2
)
end
end
for k, actual_v in pairs(actual) do
if expected[k] == nil then
error(
"ensure_tequals failed: " .. msg
.. ": unexpected actual value at key `" .. tostring(k)
.. "': got `" .. tostring(actual_v)
.. "', should be nil",
2
)
end
end
return actual
end
local ensure_tdeepequals = function(msg, actual, expected)
-- Heavy! Use ensure_tequals if possible
if not tdeepequals(actual, expected) then
-- TODO: Bad! Improve error reporting (use tdiff)
error(
"ensure_tdeepequals failed: " .. msg .. ":"
.. "\n actual: " .. tstr(actual)
.. "\nexpected: " .. tstr(expected),
2
)
end
end
-- TODO: ?! Improve and generalize!
local strdiff_msg
do
-- TODO: Generalize?
local string_window = function(str, pos, window_radius)
return str:sub(
math_max(1, pos - window_radius),
math_min(pos + window_radius, #str)
)
end
-- TODO: Uncomment and move to proper tests
--[=[
assert(string_window("abCde", 3, 0) == [[C]])
assert(string_window("abCde", 3, 1) == [[bCd]])
assert(string_window("abCde", 3, 2) == [[abCde]])
assert(string_window("abCde", 3, 3) == [[abCde]])
--]=]
local nl_byte = ("\n"):byte()
strdiff_msg = function(actual, expected, window_radius)
window_radius = window_radius or 10
local result = false
--print(("%q"):format(expected))
--print(("%q"):format(actual))
if type(actual) ~= "string" or type(expected) ~= "string" then
result = "(bad input)"
else
local nactual, nexpected = #actual, #expected
local len = math_min(nactual, nexpected)
local lineno, lineb = 1, 1
for i = 1, len do
local ab, eb = expected:byte(i), actual:byte(i)
--print(string_char(eb), string_char(ab))
if ab ~= eb then
-- TODO: Do not want to have \n-s here. Too low level?!
result = "different at byte " .. i .. " (line " .. lineno .. ", offset " .. lineb .. "):\n\n expected |"
.. string_window(expected, i, window_radius)
.. "|\nvs. actual |"
.. string_window(actual, i, window_radius)
.. "|\n\n"
break
end
if eb == nl_byte then
lineno, lineb = lineno + 1, 1
end
end
if nactual > nexpected then
result = (result or "different: ") .. "actual has " .. (nactual - nexpected) .. " extra characters"
elseif nactual < nexpected then
result = (result or "different:" ) .. "expected has " .. (nexpected - nactual) .. " extra characters"
end
end
return result or "(identical)"
end
end
--------------------------------------------------------------------------------
local ensure_strequals = function(msg, actual, expected, ...)
if actual == expected then
return actual, expected, ...
end
error(
"ensure_strequals: " .. msg .. ":\n"
.. strdiff_msg(actual, expected)
.. "\nactual:\n" .. tostring(actual)
.. "\nexpected:\n" .. tostring(expected)
)
end
--------------------------------------------------------------------------------
local ensure_error = function(msg, expected_message, res, actual_message, ...)
if res ~= nil then
error(
"ensure_error failed: " .. msg
.. ": failure expected, got non-nil result: `" .. tostring(res) .. "'",
2
)
end
-- TODO: Improve error reporting
ensure_strequals(msg, actual_message, expected_message)
end
--------------------------------------------------------------------------------
local ensure_error_with_substring = function(msg, substring, res, err)
if res ~= nil then
error(
"ensure_error_with_substring failed: " .. msg
.. ": failure expected, got non-nil result: `" .. tostring(res) .. "'",
2
)
end
if not err:find(substring) and substring ~= err then
error(
"ensure_error_with_substring failed: " .. msg
.. ": can't find expected substring `" .. tostring(substring)
.. "' in error message:\n" .. err
)
end
end
--------------------------------------------------------------------------------
-- TODO: Uncomment and move to proper tests
--[[
ensure_error("ok", "a", nil, "a")
ensure_error("bad1", "a", nil, "a", nil)
ensure_error("bad2", "a", nil, "b")
ensure_error("bad3", "a", true, "a")
--]]
-- TODO: Write tests for this one
local ensure_fails_with_substring = function(msg, fn, substring)
local res, err = pcall(fn)
if res ~= false then
error("ensure_fails_with_substring failed: " .. msg .. ": call was expected to fail, but did not")
end
if type(err) ~= "string" then
error("ensure_fails_with_substring failed: " .. msg .. ": call failed with non-string error")
end
if not err:find(substring) then
error(
"ensure_fails_with_substring failed: " .. msg
.. ": can't find expected substring `" .. tostring(substring)
.. "' in error message:\n" .. err
)
end
end
--------------------------------------------------------------------------------
-- We want 99.9% probability of success
-- Would not work for high-contrast weights. Use for tests only.
local ensure_aposteriori_probability = function(num_runs, weights, stats, max_acceptable_diff)
ensure_equals("total sum check", taccumulate(stats), num_runs)
local apriori_probs = tnormalize(weights)
local aposteriori_probs = tnormalize(stats)
for k, apriori in pairs(apriori_probs) do
local aposteriori = assert_is_number(aposteriori_probs[k])
ensure("apriori must be positive", apriori > 0)
ensure("aposteriori must be non-negative", aposteriori >= 0)
-- TODO: Lame check. Improve it.
local diff = math_abs(apriori - aposteriori) / apriori
if diff > max_acceptable_diff then
error(
"inacceptable apriori-aposteriori difference key: `" .. tostring(k) .. "'"
.. " num_runs: " .. num_runs
.. " apriori: " .. apriori
.. " aposteriori: " .. aposteriori
.. " actual_diff: " .. diff
.. " max_diff: " .. max_acceptable_diff
)
end
aposteriori_probs[k] = nil -- To check there is no extra data below.
end
ensure_equals("no extra data", next(aposteriori_probs), nil)
end
local ensure_returns = function(msg, num, expected, ...)
local checker = make_checker()
-- Explicit check to separate no-return-values from all-nils
if num ~= select("#", ...) then
checker:fail(
"return value count mismatch: expected "
.. num .. " actual " .. select("#", ...)
)
end
for i = 1, num do
if not tdeepequals(expected[i], (select(i, ...))) then
-- TODO: Enhance error reporting (especially for tables and long strings)
checker:fail(
"return value #" .. i .. " mismatch: "
.. "actual `" .. tostring((select(i, ...)))
.. "', expected `" .. tostring(expected[i])
.. "'"
)
end
end
if not checker:good() then
error(
checker:msg(
"return values check failed: " .. msg .. "\n -- ",
"\n -- "
),
2
)
end
return ...
end
return
{
ensure = ensure;
ensure_equals = ensure_equals;
ensure_tequals = ensure_tequals;
ensure_tdeepequals = ensure_tdeepequals;
ensure_strequals = ensure_strequals;
ensure_error = ensure_error;
ensure_error_with_substring = ensure_error_with_substring;
ensure_fails_with_substring = ensure_fails_with_substring;
ensure_aposteriori_probability = ensure_aposteriori_probability;
ensure_returns = ensure_returns;
}
|
--[[
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local triggers = {}
local mattata = require('mattata')
local redis = require('libs.redis')
function triggers:init()
triggers.commands = mattata.commands(self.info.username):command('triggers'):command('trigger'):command('custom').table
triggers.help = '/triggers - Allows admins to view and delete existing word triggers. Aliases: /trigger, /custom.'
end
function triggers:on_new_message(message)
if message.command or message.is_media or self.is_ai then
return false
end
local matches = redis:hgetall('triggers:' .. message.chat.id)
if not next(matches) == 0 then
return false
end
for trigger, value in pairs(matches) do
if message.text:lower():match(trigger:lower()) then
local trail
if trigger:lower() == 'ayy' and value:lower() == 'lmao' then
trail = message.text:lower():match('(ayy+)'):gsub('^ay', '')
value = 'lma' .. string.rep('o', trail:len())
elseif trigger:lower() == 'lmao' and value:lower() == 'ayy' then
trail = message.text:lower():match('(lmao+)'):gsub('^lma', '')
value = 'ay' .. string.rep('y', trail:len())
end
if value:len() > 4096 then
value = value:sub(1, 4093) .. '...'
end
if value:match('%b{}') then
for k, v in pairs(message.from) do
if type(v) == 'string' then
message.from[k] = v:gsub('%%', '%%%%')
end
end
for k, v in pairs(message.chat) do
if type(v) == 'string' then
message.chat[k] = v:gsub('%%', '%%%%')
end
end
local last_name = message.from.last_name or ''
local username = message.from.username and '@' .. message.from.username or ''
value = value:gsub('{name}', message.from.name):gsub('{firstname}', message.from.first_name):gsub('{userid}', message.from.id):gsub('{lastname}', last_name):gsub('{username}', username)
if message.chat.type == 'supergroup' then
value = value:gsub('{title}', message.chat.title):gsub('{chatid}', message.chat.id)
local user_count = ''
if value:match('{usercount}') then
user_count = mattata.get_chat_members_count(message.chat.id).result
end
local invite_link = redis:hget('chat:' .. message.chat.id .. ':info', 'link') or ''
local chat_username = message.chat.username and '@' .. message.chat.username or ''
value = value:gsub('{usercount}', user_count):gsub('{invitelink}', invite_link):gsub('{chatusername}', chat_username)
end
end
if not message.is_edited then
local success = mattata.send_message(message.chat.id, value)
if success then
redis:set('bot:' .. message.chat.id .. ':' .. message.message_id, success.result.message_id)
end
return success
else
local message_id = redis:get('bot:' .. message.chat.id .. ':' .. message.message_id)
if message_id then
return mattata.edit_message_text(message.chat.id, message_id, value)
end
end
end
end
return
end
function triggers.get_trigger(chat_id, trigger)
local get = redis:hget('triggers:' .. chat_id, trigger)
if not get then
return 'This trigger doesn\'t exist!'
end
return get
end
function triggers.get_confirmation_keyboard(chat_id, trigger, page)
if not redis:hget('triggers:' .. chat_id, trigger) then
return false
end
return mattata.inline_keyboard():row(
mattata.row()
:callback_data_button(
mattata.symbols.back .. ' Back',
'triggers:' .. chat_id .. ':back:' .. page
)
:callback_data_button(
'Delete',
'triggers:' .. chat_id .. ':delete:' .. trigger
)
)
end
function triggers.get_triggers(chat_id)
local all = redis:hgetall('triggers:' .. chat_id)
if not next(all) then
return false
end
local output = {}
for trigger, _ in pairs(all) do
table.insert(output, trigger)
end
return output
end
function triggers.get_keyboard(chat_id, page, columns, per_page)
page = page or 1
local toggleable = triggers.get_triggers(chat_id)
if not toggleable then
return false
end
local page_count = math.floor(#toggleable / per_page)
if page_count < #toggleable / per_page then
page_count = page_count + 1
end
if page < 1 then
page = page_count
elseif page > page_count then
page = 1
end
local start_res = (page * per_page) - (per_page - 1)
local end_res = start_res + (per_page - 1)
if end_res > #toggleable then
end_res = #toggleable
end
local trigger_pos = 0
local output = {}
for _, v in pairs(toggleable) do
trigger_pos = trigger_pos + 1
if trigger_pos >= start_res and trigger_pos <= end_res then
table.insert(output, v)
end
end
local keyboard = {
['inline_keyboard'] = {
{}
}
}
local columns_per_page = math.floor(#output / columns)
if columns_per_page < (#output / columns) then
columns_per_page = columns_per_page + 1
end
local rows_per_page = math.floor(#output / columns_per_page)
if rows_per_page < (#output / columns_per_page) then
rows_per_page = rows_per_page + 1
end
local current_row = 1
local count = 0
for n in pairs(output) do
count = count + 1
if count == (rows_per_page * current_row) + 1 then
current_row = current_row + 1
table.insert(keyboard.inline_keyboard, {})
end
table.insert(keyboard.inline_keyboard[current_row], {
['text'] = output[n],
['callback_data'] = string.format(
'triggers:%s:%s:%s', chat_id,
output[n], page
)
})
end
if page_count > 1 then
table.insert(keyboard.inline_keyboard, {{
['text'] = mattata.symbols.back .. ' Previous',
['callback_data'] = string.format(
'triggers:%s:page:%s',
chat_id,
page - 1
)
}, {
['text'] = string.format(
'%s/%s',
page,
page_count
),
['callback_data'] = 'triggers:nil'
}, {
['text'] = 'Next ' .. mattata.symbols.next,
['callback_data'] = string.format(
'triggers:%s:page:%s',
chat_id,
page + 1
)
}})
end
if count <= 0 then
return false
end
return keyboard
end
function triggers.on_callback_query(_, callback_query, message)
if not callback_query.data:match('^.-:.-:.-$') then
return
end
local chat_id, callback_type, page = callback_query.data:match('^(.-):(.-):(.-)$')
if not mattata.is_group_admin(chat_id, callback_query.from.id) then
return mattata.answer_callback_query(callback_query.id, 'You are not allowed to use this!')
end
if callback_type == 'back' or callback_type == 'page' then
local success = mattata.edit_message_text(
message.chat.id,
message.message_id,
'Please select a trigger:',
nil, false,
triggers.get_keyboard(
chat_id,
tonumber(page), 2, 10
)
)
if not success then
return mattata.edit_message_text(
message.chat.id,
message.message_id,
'All triggers saved for this chat have already been deleted!'
)
end
return mattata.answer_callback_query(callback_query.id)
elseif callback_type == 'delete' then
local all = redis:hgetall('triggers:' .. chat_id)
if not next(all) then
return mattata.answer_callback_query(callback_query.id, 'All triggers saved for this chat have already been deleted!')
end
local selected = all[page]
if not selected then
return mattata.answer_callback_query(callback_query.id, 'This trigger no longer exists!')
end
redis:hdel('triggers:' .. chat_id, page)
return mattata.answer_callback_query(callback_query.id, 'That trigger has been deleted from my database!')
elseif callback_type == 'back' then
return mattata.edit_message_reply_markup(
message.chat.id,
message.message_id,
nil,
triggers.get_keyboard(
chat_id,
tonumber(page), 2, 10
)
)
end
local keyboard = triggers.get_confirmation_keyboard(
chat_id,
callback_type,
page
)
local value = triggers.get_trigger(chat_id, callback_type)
value = mattata.escape_html(value)
local success = mattata.edit_message_text(
message.chat.id,
message.message_id,
'<b>' .. callback_type .. '</b> is set to trigger <em>' .. value .. '</em>', 'html', false,
keyboard
)
if not success then
return mattata.edit_message_text(
message.chat.id,
message.message_id,
'All triggers saved for this chat have already been deleted!'
)
end
end
function triggers.on_message(_, message)
local keyboard = triggers.get_keyboard(message.chat.id, 1, 2, 10)
if not keyboard then
return mattata.send_reply(message, 'This chat does\'t have any triggers saved in my database! Use /addtrigger <trigger> <value> to add one!')
end
return mattata.send_message(message.chat.id, 'Please select a trigger:', nil, true, false, nil, keyboard)
end
return triggers
|
local tbl1 = {}
tbl1["key"] = 22
tbl1["key"] = tbl1["key"] + "11"
for k, v in pairs(tbl1) do
print(k .. " => " .. v)
end
print(tbl1.key)
print(tbl1["key"])
local tbl2 = {"apple", "pear", "orange", "grape"}
for k, v in pairs(tbl2) do
print(k .. " => " .. v)
end
local tbl3 = {}
for i = 1, 10 do
tbl3[i] = i
end
for k, v in pairs(tbl3) do
print(k .. " => " .. v)
end
|
tigris.include("wool.lua")
tigris.include("milk.lua")
tigris.include_dir("mobs")
|
function Client_PresentSettingsUI(rootParent)
UI.CreateLabel(rootParent).SetText('Players get a fort every ' .. Mod.Settings.TurnsToGetFort .. ' turns');
end
|
-- Generated by CSharp.lua Compiler
local System = System
local SlipeSharedGameWorld
System.import(function (out)
SlipeSharedGameWorld = Slipe.Shared.GameWorld
end)
System.namespace("Slipe.Server.GameWorld", function (namespace)
-- <summary>
-- Class representing an Object in MTA
-- </summary>
namespace.class("WorldObject", function (namespace)
local __ctor1__, __ctor2__, __ctor3__
__ctor1__ = function (this, element)
SlipeSharedGameWorld.SharedWorldObject.__ctor__[1](this, element)
end
-- <summary>
-- Creates a world object at a certain position
-- </summary>
__ctor2__ = function (this, model, position)
SlipeSharedGameWorld.SharedWorldObject.__ctor__[3](this, model, position:__clone__())
end
-- <summary>
-- Creats a world object using all of the createObject parameters
-- </summary>
__ctor3__ = function (this, model, position, rotation, isLowLOD)
SlipeSharedGameWorld.SharedWorldObject.__ctor__[2](this, model, position:__clone__(), rotation:__clone__(), isLowLOD)
end
return {
__inherits__ = function (out)
return {
out.Slipe.Shared.GameWorld.SharedWorldObject
}
end,
__ctor__ = {
__ctor1__,
__ctor2__,
__ctor3__
},
__metadata__ = function (out)
return {
methods = {
{ ".ctor", 0x106, __ctor1__, out.Slipe.MtaDefinitions.MtaElement },
{ ".ctor", 0x206, __ctor2__, System.Int32, System.Numerics.Vector3 },
{ ".ctor", 0x406, __ctor3__, System.Int32, System.Numerics.Vector3, System.Numerics.Vector3, System.Boolean }
},
class = { 0x6, System.new(out.Slipe.Shared.Elements.DefaultElementClassAttribute, 2, 4 --[[ElementType.Object]]) }
}
end
}
end)
end)
|
local Class = require( "belove.libraries.Class" )
-- =============================================================================
-- BQuad
-- =============================================================================
local BQuad = Class( "BQuad" )
function BQuad:load( quad, pivot )
self.quad = quad --> Quad
self.pivot = pivot --> Vector
end
return BQuad
|
--- === cp.ui.Toolbar ===
---
--- Toolbar Module.
local require = require
local axutils = require "cp.ui.axutils"
local Button = require "cp.ui.Button"
local Do = require "cp.rx.go.Do"
local Element = require "cp.ui.Element"
local prop = require "cp.prop"
local Toolbar = Element:subclass("cp.ui.Toolbar")
--- cp.ui.Toolbar.matches(element) -> boolean
--- Function
--- Checks if the `element` is a `Button`, returning `true` if so.
---
--- Parameters:
--- * element - The `hs.axuielement` to check.
---
--- Returns:
--- * `true` if the `element` is a `Button`, or `false` if not.
function Toolbar.static.matches(element)
return Element.matches(element) and element:attributeValue("AXRole") == "AXToolbar"
end
--- cp.ui.Toolbar(parent, uiFinder) -> cp.ui.Toolbar
--- Constructor
--- Creates a new `Toolbar` instance, given the specified `parent` and `uiFinder`
---
--- Parameters:
--- * parent - The parent object.
--- * uiFinder - The `cp.prop` or `function` that finds the `hs.axuielement` that represents the `Toolbar`.
---
--- Returns:
--- * The new `Toolbar` instance.
function Toolbar:initialize(parent, uiFinder)
Element.initialize(self, parent, uiFinder)
if prop.is(parent.UI) then
self.UI:monitor(parent.UI)
end
if prop.is(parent.isShowing) then
self.isShowing:monitor(parent.isShowing)
end
end
--- cp.ui.Toolbar.selectedTitle <cp.prop: string; read-only>
--- Field
--- The title of the first selected item, if available.
function Toolbar.lazy.prop:selectedTitle()
return self.UI:mutate(function(original)
local ui = original()
local selected = ui and ui:attributeValue("AXSelectedChildren")
if selected and #selected > 0 then
return selected[1]:attributeValue("AXTitle")
end
end)
end
--- cp.ui.Toolbar.overflowButton <cp.ui.Button>
--- Field
--- The "overflow" button which appears if there are more toolbar items
--- available than can be fit on screen.
function Toolbar.lazy.value:overflowButton()
return Button(self, self.UI:mutate(function(original)
local ui = original()
return ui and ui:attributeValue("AXOverflowButton")
end))
end
--- cp.ui.Toolbar:doSelect(title) -> Statement
--- Method
--- Returns a `Statement` that will select the toolbar item with the specified title.
---
--- Parameters:
--- * title - The title to select, if present.
---
--- Returns:
--- * A `Statement` that when executed returns `true` if the item was found and selected, otherwise `false`.
function Toolbar:doSelect(title)
return Do(self:doShow())
:Then(function()
local ui = self:UI()
local selectedTitle = self:selectedTitle()
if selectedTitle ~= title then
local button = ui and axutils.childWith(ui, "AXTitle", title)
if button then
button:doAXPress()
return true
end
end
return false
end)
end
function Toolbar.lazy.method:doShow()
return self:parent():doShow()
end
function Toolbar.lazy.method:doHide()
return self:parent():doHide()
end
return Toolbar
|
if not modules then modules = { } end modules ['s-mod-00'] = {
version = 1.000,
comment = "companion to mult-aux.mkiv",
author = "Wolfgang Schuster",
copyright = "Wolfgang Schuster",
license = "GNU General Public License"
}
thirddata = thirddata or { }
thirddata.correspondence = thirddata.correspondence or { }
local concat, toks, settings_to_array, settings_to_hash = table.concat, tex.toks, utilities.parsers.settings_to_array, utilities.parsers.settings_to_hash
local correspondence = thirddata.correspondence
local constants = interfaces.constants
local variables = interfaces.variables
local c_titlestyle = constants.titlestyle
local c_titlecolor = constants.titlecolor
local c_textcolor = constants.textcolor
local c_textstyle = constants.textstyle
local c_separator = constants.separator
local v_correspondence = variables.correspondence
local v_letter = variables.letter
local v_memo = variables.memo
local v_resume = variables.resume
local v_frames = variables.frames
local v_stop = variables.stop
local v_layer = variables.layer
local v_section = variables.section
local v_color = variables.color
local v_singlesided = variables.singlesided
local v_reset = variables.reset
local v_line = variables.line
local v_top = variables.top
local v_bottom = variables.bottom
local v_off = variables.off
local v_right = variables.right
local v_page = variables.page
local v_paper = variables.paper
local v_text = variables.text
local v_start = variables.start
local v_list = variables.list
-- list for the elements to be shown
correspondence.data = { }
function correspondence.elements_define(environment,name,list)
local index = concat({environment,name},":")
local list = settings_to_array(list)
correspondence.data[index] = list
end
function correspondence.elements_access(environment,name)
local index = concat({environment,name},":")
local list = correspondence.data[index]
local entries = ""
if list and list ~= "" then
entries = concat(list,",")
end
context(entries)
end
-- create synonyms for the default styles
local patterns = {
[v_letter] = { "letter-imp-%s.mkiv", "letter-imp-%s.tex", "letter-%s.mkiv", "letter-%s.tex" },
[v_memo] = { "memo-imp-%s.mkiv", "memo-imp-%s.tex", "memo-%s.mkiv", "memo-%s.tex" },
[v_resume] = { "resume-imp-%s.mkiv", "resume-imp-%s.tex", "resume-%s.mkiv", "resume-%s.tex" },
[v_frames] = { "frames-imp-%s.mkiv", "frames-imp-%s.tex", "frames-%s.mkiv", "frames-%s.tex" },
}
local function action(name,foundname)
context.startreadingfile()
context.pushendofline()
context.unprotect()
context.input(foundname)
context.protect()
context.popendofline()
context.stopreadingfile()
end
function correspondence.file(environment,name)
local environment = environment
local name = name
commands.uselibrary {
name = name,
patterns = patterns[environment],
action = action,
}
end
-- moved from TeX to Lua because it’s easier with the lists for the sections and layers
function correspondence.place(environment,settings)
local bodyfont = settings.bodyfont
local whitespace = settings.whitespace
local interlinespace = settings.interlinespace
local language = settings.language
local backgroundcolor = settings.backgroundcolor
context.unprotect()
context(toks.t_correspondence_before)
context.page()
-- page layout is controlled with the \setup…layout commands
context.setuplayout{ method = v_correspondence }
-- disable headers and footers
context.setupheader{ state = v_stop }
context.setupfooter{ state = v_stop }
-- required for the manual, manual changes for the elements can be done with the “style” key
if bodyfont ~= "" then
context.setupbodyfont{bodyfont}
end
-- can be moved to the section elements because it’s only usefull for the content
if whitespace ~= "" then
context.setupwhitespace{whitespace}
end
-- feature
if interlinespace ~= "" then
context.setupinterlinespace{interlinespace}
end
-- I prefer to set this with \setup…options
if language ~= "" then
context.mainlanguage{language}
end
-- colored background is behind all other layers
if backgroundcolor ~= "" then
context.setupbackgrounds({ v_paper },{ background = v_color, backgroundcolor = backgroundcolor })
end
-- layers
local layer = { }
for index, element in next, correspondence.data[concat({environment,v_layer},":")] or { } do
layer[index] = concat({environment,element},":")
end
local overlays = {
"correspondence:backgroundimage",
"correspondence:background",
concat(layer,","),
}
context.setupbackgrounds({ v_page },{ background = concat(overlays,",") })
-- letters are always singlesided because the layout controlled by the module
context.setuppagenumbering{ alternative = v_singlesided, location = "" }
context.setupsubpagenumber{ way = v_text, state = v_start }
context.resetsubpagenumber()
-- sections
for _, element in next, correspondence.data[concat({environment,v_section},":")] or { } do
context.correspondence_section_place({environment},{element})
end
context.page()
context.resetsubpagenumber()
-- make sure the normal layout is restored
context.setuplayout{v_reset}
context(toks.t_correspondence_after)
context.protect()
end
correspondence.letter = { }
local function reference_a(environment,value)
local environment = environment
local value = value
local style = nil
context.vbox( function()
style = concat({environment,value},":")
context.setevalue("currentcorrespondencestyle",style)
context.framed( { frame = v_off, location = v_bottom, align = v_right, offset = "0pt" }, function()
context.usecorrespondencestylestyleandcolor(c_titlestyle,c_titlecolor)
context.setupinterlinespace()
context.lettertext(value)
context.par()
end )
context.framed( { frame = v_off, location = v_top, align = v_right, offset = "0pt" }, function()
context.usecorrespondencestylestyleandcolor(c_textstyle,c_textcolor)
context.setupinterlinespace()
context.correspondenceparameter(value)
context.par()
end )
end )
end
function correspondence.letter.reference_a(environment,list)
local environment = environment
local list = settings_to_array(list)
local style = nil
if #list == 1 then
local value = list[1]
context.rightaligned( function() reference_a(environment,value) end )
else
context.maxaligned( function()
for index, value in next, list do
if value == "" or value == v_line then
-- ignore empty entries and the “line” keyword
else
if index ~= 1 then context.hfill() end
reference_a(environment,value)
end
end
end )
end
end
function correspondence.letter.reference_b(environment,list)
local environment = environment
local list = settings_to_array(list)
local style = nil
context.vtop( function()
for _, value in next, list do
if value == "" then
-- ignore empty entries in the list
elseif value == v_line then
context.blank{v_line}
else
context.hbox( function()
style = concat({environment,value},":")
context.setevalue("currentcorrespondencestyle",style)
context.begingroup()
context.usecorrespondencestylestyleandcolor(c_titlestyle,c_titlecolor)
context.lettertext(value)
context.correspondencestyleparameter(c_separator)
context.endgroup()
context.begingroup()
context.usecorrespondencestylestyleandcolor(c_textstyle,c_textcolor)
context.correspondenceparameter(value)
context.endgroup()
end )
end
end
end )
end
function correspondence.letter.reference_c(environment,list)
local environment = environment
local list = settings_to_array(list)
local style = nil
for _, value in next, list do
if value == "" or value == v_line then
-- ignore empty entries and the “line” keyword
else
style = concat({environment,value},":")
context.setvalue("currentcorrespondencestyle",style)
context.usecorrespondencestylestyleandcolor(c_textstyle,c_textcolor)
context.correspondenceparameter(value)
end
end
end
function correspondence.letter.reference_d(environment,list)
local environment = environment
local list = settings_to_array(list)
local style = nil
context.vtop( function()
context.starttabulate( { "|l|l|" }, { before = "", after = "" } )
for _, value in next, list do
if value == "" then
-- ignore empty entries in the list
elseif value == v_line then
context.TB()
else
style = concat({environment,value},":")
context.NC()
context.setvalue("currentcorrespondencestyle",style)
context.usecorrespondencestylestyleandcolor(c_titlestyle,c_titlecolor)
context.lettertext(value)
context.correspondencestyleparameter(c_separator)
context.NC()
context.setvalue("currentcorrespondencestyle",style)
context.usecorrespondencestylestyleandcolor(c_textstyle,c_textcolor)
context.correspondenceparameter(value)
context.NC()
context.NR()
end
end
context.stoptabulate()
end )
end
function correspondence.letter.reference_e(environment,list)
local environment = environment
local list = settings_to_array(list)
local style, settings = nil
context.leftaligned( function()
for _, value in next, list do
if value == "" or value == v_line then
-- ignore empty entries and the “line” keyword
else
context.unprotect()
context.correspondence_style_width( environment, value, function() reference_a(environment,value) end )
context.protect()
end
end
end )
end
function correspondence.description_split(list)
local format, items = nil, nil
if string.find(list,":") then
format, items = string.splitup(list,":")
if format ~= v_list then
items = list
end
else
items = list
end
-- the macros are empty be default, change this only when necessary
context.unprotect()
if format then context.setvalue("m_correspondence_description_format",format) end
if items then context.setvalue("m_correspondence_description_items" ,items ) end
context.protect()
end
|
Config = {}
Config.Debug = GetConvarInt('spanser_immersion_debug', 0)
|
local level = {}
function level.load(filename)
local result = {}
local f = assert(io.open(filename, "r"))
local count = 0
while true do
local levelLine = {}
local line = f:read("*line")
if line == nil then break end
for i = 1, #line do
local c = line:sub(i,i)
levelLine[#levelLine+1]=c
end
count = count + 1
result[#result+1] = levelLine
end
f:close()
return result
end
return level
|
require("prototypes.item.item")
require("prototypes.entity.armoured-draisine")
require("prototypes.entity.rail-car")
require("prototypes.recipe.recipe")
|
slot0 = {
[Vector3] = 1,
[Quaternion] = 2,
[Vector2] = 3,
[Color] = 4,
[Vector4] = 5,
[Ray] = 6,
[Bounds] = 7,
[Touch] = 8,
[LayerMask] = 9,
[RaycastHit] = 10,
[int64] = 11,
[uint64] = 12
}
function slot1()
slot1 = getmetatable
return function (slot0)
if slot0(slot0) == nil then
return 0
end
return slot1[slot1] or 0
end
end
function AddValueType(slot0, slot1)
slot0[slot0] = slot1
end
GetLuaValueType = slot1()
return
|
--
-- from src/tarai.c
--
-- int tarai(int, int, int) to tarai
-- tarai to tak(*)
--
-- *) https://en.wikipedia.org/wiki/Tak_(function)
--
local function tarai(x, y, z)
if x <= y then return y end
return tarai(tarai(x-1,y,z), tarai(y-1,z,x), tarai(z-1,x,y))
end
local function tak(x, y, z)
if x <= y then return z end
return tak(tak(x-1,y,z), tak(y-1,z,x), tak(z-1,x,y))
end
return {
tarai = tarai,
tak = tak
}
|
print "Hello, World"
|
data:extend({
{
type = "sound",
name = "ping-sound",
variations =
{
{
filename = "__Map Ping__/sound/Ping1.ogg",
volume = 0.75
},
{
filename = "__Map Ping__/sound/Ping2.ogg",
volume = 0.75
},
{
filename = "__Map Ping__/sound/Ping3.ogg",
volume = 0.75
},
},
}
})
|
-----------------------------------
-- Ability: Afflatus Solace
-- Inspires you to draw strength from the healing spells you cast.
-- Obtained: White Mage Level 40
-- Recast Time: 1:00
-- Duration: 2 hours
-----------------------------------
require("scripts/globals/status")
-----------------------------------
function onAbilityCheck(player,target,ability)
return 0,0
end
function onUseAbility(player,target,ability)
target:delStatusEffect(tpz.effect.AFFLATUS_SOLACE)
target:delStatusEffect(tpz.effect.AFFLATUS_MISERY)
target:addStatusEffect(tpz.effect.AFFLATUS_SOLACE,8,0,7200)
end
|
local ffi = require("ffi")
dofile("../common/ffi_util.inc")
ffi.cdef[[
typedef enum enum_i { FOO_I = -1, II = 10 } enum_i;
typedef enum enum_u { FOO_U = 1, UU = 10 } enum_u;
enum_i call_ei_i(int a) asm("call_i");
enum_u call_eu_i(int a) asm("call_i");
int call_i_ei(enum_i a) asm("call_i");
int call_i_eu(enum_u a) asm("call_i");
]]
local C = ffi.load("../clib/ctest")
do
local t = ffi.new("enum_i[100]")
for i=0,99 do t[i] = "II" end
for i=0,99 do assert(t[i] == "II") end
for i=0,99 do assert(t[i] >= "II") end
for i=0,99 do t[i] = -10 end
for i=0,99 do assert(t[i] == -10) end
for i=0,99 do assert(t[i] ~= 2147483648) end
for i=1,99 do assert(t[i] == t[i-1]) end
assert(t[0]+1 == -9)
assert(t[0] ~= "BB")
fails(function() return t[0] > "BB" end)
local u = ffi.new("enum_u[100]")
for i=0,99 do u[i] = "UU" end
for i=0,99 do assert(u[i] == "UU") end
for i=0,99 do assert(u[i] >= "UU") end
for i=0,99 do u[i] = 4294967296-10 end
for i=0,99 do assert(u[i] == 4294967296-10) end
for i=0,99 do assert(u[i] ~= -10) end
for i=1,99 do assert(u[i] == u[i-1]) end
assert(u[0]+1 == 4294967296-9)
for i=0,99 do assert(t[i] ~= u[i]) end
end
do
for i=0,99 do assert(C.call_ei_i(9) == "II") end
for i=0,99 do assert(C.call_eu_i(9) == "UU") end
for i=0,99 do assert(C.call_i_ei("II") == 11) end
for i=0,99 do assert(C.call_i_eu("UU") == 11) end
end
do
local f = ffi.cast("bool (*)(enum_i)", function(e) return e == "II" end)
assert(f("II"))
assert(not f(0))
end
|
local _0_0 = nil
do
local name_23_0_ = "conjure.client.janet.netrepl.server"
local loaded_23_0_ = package.loaded[name_23_0_]
local module_23_0_ = nil
if ("table" == type(loaded_23_0_)) then
module_23_0_ = loaded_23_0_
else
module_23_0_ = {}
end
module_23_0_["aniseed/module"] = name_23_0_
module_23_0_["aniseed/locals"] = (module_23_0_["aniseed/locals"] or {})
module_23_0_["aniseed/local-fns"] = (module_23_0_["aniseed/local-fns"] or {})
package.loaded[name_23_0_] = module_23_0_
_0_0 = module_23_0_
end
local function _1_(...)
_0_0["aniseed/local-fns"] = {require = {a = "conjure.aniseed.core", config = "conjure.client.janet.netrepl.config", log = "conjure.log", net = "conjure.net", trn = "conjure.client.janet.netrepl.transport", ui = "conjure.client.janet.netrepl.ui"}}
return {require("conjure.aniseed.core"), require("conjure.client.janet.netrepl.config"), require("conjure.log"), require("conjure.net"), require("conjure.client.janet.netrepl.transport"), require("conjure.client.janet.netrepl.ui")}
end
local _2_ = _1_(...)
local a = _2_[1]
local config = _2_[2]
local log = _2_[3]
local net = _2_[4]
local trn = _2_[5]
local ui = _2_[6]
do local _ = ({nil, _0_0, nil})[2] end
local state = nil
do
local v_23_0_ = (_0_0["aniseed/locals"].state or {conn = nil})
_0_0["aniseed/locals"]["state"] = v_23_0_
state = v_23_0_
end
local with_conn_or_warn = nil
do
local v_23_0_ = nil
local function with_conn_or_warn0(f, opts)
local conn = a.get(state, "conn")
if conn then
return f(conn)
else
return ui.display({"# No connection"})
end
end
v_23_0_ = with_conn_or_warn0
_0_0["aniseed/locals"]["with-conn-or-warn"] = v_23_0_
with_conn_or_warn = v_23_0_
end
local display_conn_status = nil
do
local v_23_0_ = nil
do
local v_23_0_0 = nil
local function display_conn_status0(status)
local function _3_(conn)
return ui.display({("# " .. conn["raw-host"] .. ":" .. conn.port .. " (" .. status .. ")")}, {["break?"] = true})
end
return with_conn_or_warn(_3_)
end
v_23_0_0 = display_conn_status0
_0_0["display-conn-status"] = v_23_0_0
v_23_0_ = v_23_0_0
end
_0_0["aniseed/locals"]["display-conn-status"] = v_23_0_
display_conn_status = v_23_0_
end
local disconnect = nil
do
local v_23_0_ = nil
do
local v_23_0_0 = nil
local function disconnect0()
local function _3_(conn)
if not (conn.sock):is_closing() then
do end (conn.sock):read_stop()
do end (conn.sock):shutdown()
do end (conn.sock):close()
end
display_conn_status("disconnected")
return a.assoc(state, "conn", nil)
end
return with_conn_or_warn(_3_)
end
v_23_0_0 = disconnect0
_0_0["disconnect"] = v_23_0_0
v_23_0_ = v_23_0_0
end
_0_0["aniseed/locals"]["disconnect"] = v_23_0_
disconnect = v_23_0_
end
local handle_message = nil
do
local v_23_0_ = nil
local function handle_message0(err, chunk)
local conn = a.get(state, "conn")
if err then
return display_conn_status(err)
elseif not chunk then
return disconnect()
else
local function _3_(msg)
log.dbg("receive", msg)
local cb = table.remove(a["get-in"](state, {"conn", "queue"}))
if cb then
return cb(msg)
end
end
return a["run!"](_3_, conn.decode(chunk))
end
end
v_23_0_ = handle_message0
_0_0["aniseed/locals"]["handle-message"] = v_23_0_
handle_message = v_23_0_
end
local send = nil
do
local v_23_0_ = nil
do
local v_23_0_0 = nil
local function send0(msg, cb)
log.dbg("send", msg)
local function _3_(conn)
table.insert(a["get-in"](state, {"conn", "queue"}), 1, (cb or false))
return (conn.sock):write(trn.encode(msg))
end
return with_conn_or_warn(_3_)
end
v_23_0_0 = send0
_0_0["send"] = v_23_0_0
v_23_0_ = v_23_0_0
end
_0_0["aniseed/locals"]["send"] = v_23_0_
send = v_23_0_
end
local handle_connect_fn = nil
do
local v_23_0_ = nil
local function handle_connect_fn0(cb)
local function _3_(err)
local conn = a.get(state, "conn")
if err then
display_conn_status(err)
return disconnect()
else
do end (conn.sock):read_start(vim.schedule_wrap(handle_message))
send("Conjure")
return display_conn_status("connected")
end
end
return vim.schedule_wrap(_3_)
end
v_23_0_ = handle_connect_fn0
_0_0["aniseed/locals"]["handle-connect-fn"] = v_23_0_
handle_connect_fn = v_23_0_
end
local connect = nil
do
local v_23_0_ = nil
do
local v_23_0_0 = nil
local function connect0(host, port)
local host0 = (host or config.connection["default-host"])
local port0 = (port or config.connection["default-port"])
local resolved_host = net.resolve(host0)
local conn = {["raw-host"] = host0, decode = trn.decoder(), host = resolved_host, port = port0, queue = {}, sock = vim.loop.new_tcp()}
if a.get(state, "conn") then
disconnect()
end
a.assoc(state, "conn", conn)
return (conn.sock):connect(resolved_host, port0, handle_connect_fn())
end
v_23_0_0 = connect0
_0_0["connect"] = v_23_0_0
v_23_0_ = v_23_0_0
end
_0_0["aniseed/locals"]["connect"] = v_23_0_
connect = v_23_0_
end
return nil
|
local runCheck = require('./index')
require('tap')(function (test)
test("HTTP", function (expect)
runCheck({
id = 30,
target = "luvit.io",
module = "http",
timeout = 10000,
}, {
url = "http://luvit.io/",
body_matches = {
title = "title>([^<]+)",
},
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 301)
assert(data.id == 30)
assert(data.bytes > 0 and data.bytes < 1024)
assert(data.port == 80)
assert(data.body_match_title == "301 Moved Permanently")
assert(data.ip == "23.253.227.83")
assert(data.tt_firstbyte)
assert(data.duration)
end))
end)
test("HTTPS", function (expect)
runCheck({
id = 31,
target = "luvit.io",
module = "http",
timeout = 10000,
}, {
url = "https://luvit.io/",
body = "title>([^<]+)",
body_matches = {
title = "title>([^<]+)",
},
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 200)
assert(data.id == 31)
assert(data.bytes > 1024)
assert(data.port == 443)
assert(data.body_match_title == "Luvit.io")
assert(data.body_match == "Luvit.io")
assert(data.ip == "23.253.227.83")
assert(data.tt_firstbyte)
assert(data.tt_ssl)
assert(data.duration)
assert(data.cert_end)
assert(data.cert_end_in)
assert(data.cert_start)
assert(data.cert_issuer)
assert(data.cert_subject)
end))
end)
test("Basic Auth", function (expect)
runCheck({
id = 32,
target = "httpbin.org",
module = "http",
timeout = 10000,
}, {
url = "http://httpbin.org/basic-auth/creationix/iluvit",
auth_user = "creationix",
auth_password = "iluvit",
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 200)
end))
end)
test("HTTP Hidden Basic Auth", function (expect)
runCheck({
id = 33,
target = "httpbin.org",
module = "http",
timeout = 10000,
}, {
url = "http://httpbin.org/hidden-basic-auth/creationix/iluvit",
auth_user = "creationix",
auth_password = "iluvit",
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 200)
end))
end)
test("Digest Auth", function (expect)
runCheck({
id = 34,
target = "httpbin.org",
module = "http",
timeout = 10000,
}, {
url = "http://httpbin.org/digest-auth/auth/creationix/iluvit",
auth_user = "creationix",
auth_password = "iluvit",
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 200)
end))
end)
test("Digest Auth-int", function (expect)
runCheck({
id = 35,
target = "httpbin.org",
module = "http",
timeout = 10000,
}, {
url = "http://httpbin.org/digest-auth/auth-int/creationix/iluvit",
auth_user = "creationix",
auth_password = "iluvit",
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 200)
end))
end)
test("Digest Auth other", function (expect)
runCheck({
id = 36,
target = "httpbin.org",
module = "http",
timeout = 10000,
}, {
url = "http://httpbin.org/digest-auth/other/creationix/iluvit",
auth_user = "creationix",
auth_password = "iluvit",
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 200)
end))
end)
test("custom headers", function (expect)
runCheck({
id = 37,
target = "httpbin.org",
module = "http",
timeout = 10000,
}, {
url = "http://httpbin.org/headers",
headers = {
["X-Custom-Header"]= "yes!",
},
body = '"X-Custom-Header": *"([^"]*)"',
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 200)
assert(data.body_match == 'yes!')
end))
end)
test("post body", function (expect)
runCheck({
id = 38,
target = "httpbin.org",
module = "http",
timeout = 10000,
}, {
method = "POST",
url = "http://httpbin.org/post",
payload = "Hello World\n",
body = '"data": *"([^"]*)"',
}, expect(function (err, data)
p(err, data)
assert(not err, err)
assert(data.code == 200)
assert(data.body_match == 'Hello World\\n')
end))
end)
end)
|
---------------------------------------------
-- Filamented Hold
-- Reduces the attack speed of enemies within a fan-shaped area originating from the caster.
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target, mob, skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = tpz.effect.SLOW
skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, 2500, 0, 120))
return typeEffect
end
|
PdkController.initViewSiganl = function (slot0)
slot5 = slot0
slot0.model.currentUserChangedSignal.add(slot2, slot0.model.currentUserChangedSignal, slot0.onCurrentUserChanged)
slot5 = slot0
slot0.model.autoDicChangedSignal.add(slot2, slot0.model.autoDicChangedSignal, slot0.onAutoDicChanged)
slot5 = slot0
slot0.model.gameStateChangedSignal.add(slot2, slot0.model.gameStateChangedSignal, slot0.onGameStateChanged)
slot5 = slot0
slot0.model.canOutCardChangedSignal.add(slot2, slot0.model.canOutCardChangedSignal, slot0.onCanOutCardChanged)
slot5 = slot0
slot0.model.usersIsOutCardDicChangedSignal.add(slot2, slot0.model.usersIsOutCardDicChangedSignal, slot0.onUsersIsOutCardDicChanged)
slot5 = slot0
slot0.model.myTableUserDatasDicChangedSignal.add(slot2, slot0.model.myTableUserDatasDicChangedSignal, slot0.onMyTableUserDatasDicChanged)
slot5 = slot0
slot0.model.canOutDataDicValueChangedSignal.add(slot2, slot0.model.canOutDataDicValueChangedSignal, slot0.onCanOutDataDicValueChanged)
slot5 = slot0
slot0.model.winnerViewIdChangedSignal.add(slot2, slot0.model.winnerViewIdChangedSignal, slot0.onWinnerViewIdChanged)
slot5 = slot0
slot0.model.outCardInfoChangedSignal.add(slot2, slot0.model.outCardInfoChangedSignal, slot0.onOutCardInfoChanged)
slot5 = slot0
slot0.model.myCardsChangedSignal.add(slot2, slot0.model.myCardsChangedSignal, slot0.onMyCardsChanged)
slot5 = slot0
slot0.model.canOnceOutAllCardsChangedSignal.add(slot2, slot0.model.canOnceOutAllCardsChangedSignal, slot0.onCanOnceOutAllCardsChanged)
slot5 = slot0
slot0.model.leaveCardsCountDicChangedSignal.add(slot2, slot0.model.leaveCardsCountDicChangedSignal, slot0.onLeaveCardsCountDicChanged)
slot5 = slot0
slot0.model.isHoldBtnStartAtBeginChangedSignal.add(slot2, slot0.model.isHoldBtnStartAtBeginChangedSignal, slot0.onIsHoldBtnStartAtBeginChanged)
slot5 = slot0
slot0.model.isHoldBtnStartAtResultChangedSignal.add(slot2, slot0.model.isHoldBtnStartAtResultChangedSignal, slot0.onIsHoldBtnStartAtResultChanged)
slot5 = slot0
slot0.model.isShowingMatchFloatChangedSignal.add(slot2, slot0.model.isShowingMatchFloatChangedSignal, slot0.onIsShowingMatchFloatChanged)
slot5 = slot0
slot0.model.isShowingFailedChangedSignal.add(slot2, slot0.model.isShowingFailedChangedSignal, slot0.onIsShowingFailedChanged)
slot5 = slot0
slot0.model.isShowingWinChangedSignal.add(slot2, slot0.model.isShowingWinChangedSignal, slot0.onIsShowingWinChanged)
end
PdkController.onGameStateChanged = function (slot0)
slot3 = slot0
slot0.updateIsShowAutoIcon(slot2)
slot3 = slot0
slot0.updateIsShowCantOutTxt(slot2)
slot3 = slot0
slot0.updateIsShowBtnStart(slot2)
slot3 = slot0
slot0.updateStateViewDic(slot2)
slot3 = slot0
slot0.updateCanOutCard(slot2)
slot3 = slot0
slot0.updateIsShowHandCard(slot2)
slot3 = slot0
slot0.updateIsShowWarningSpine(slot2)
end
PdkController.onCurrentUserChanged = function (slot0)
slot3 = slot0
slot0.updateIsShowAutoIcon(slot2)
slot3 = slot0
slot0.updateIsShowCantOutTxt(slot2)
slot3 = slot0
slot0.updateStateViewDic(slot2)
slot3 = slot0
slot0.updateCanOutCard(slot2)
end
PdkController.onAutoDicChanged = function (slot0)
slot3 = slot0
slot0.updateStateViewDic(slot2)
slot3 = slot0
slot0.updateIsShowAutoIcon(slot2)
slot3 = slot0
slot0.updateCanOnceOutAllCards(slot2)
end
PdkController.onCanOutCardChanged = function (slot0)
slot3 = slot0
slot0.updateStateViewDic(slot2)
slot3 = slot0
slot0.updateIsShowCantOutTxt(slot2)
slot3 = slot0
slot0.updateCanOnceOutAllCards(slot2)
end
PdkController.onUsersIsOutCardDicChanged = function (slot0)
slot3 = slot0
slot0.updateStateViewDic(slot2)
end
PdkController.onMyTableUserDatasDicChanged = function (slot0)
slot3 = slot0
slot0.updateStateViewDic(slot2)
slot3 = slot0
slot0.updateIsShowBtnStart(slot2)
end
PdkController.onCanOutDataDicValueChanged = function (slot0)
return
end
PdkController.onWinnerViewIdChanged = function (slot0)
slot3 = slot0
slot0.updateStateViewDic(slot2)
end
PdkController.onOutCardInfoChanged = function (slot0)
slot3 = slot0
slot0.updateCanOnceOutAllCards(slot2)
end
PdkController.onMyCardsChanged = function (slot0)
slot3 = slot0
slot0.updateCanOnceOutAllCards(slot2)
end
PdkController.onIsHoldBtnStartAtBeginChanged = function (slot0)
slot3 = slot0
slot0.updateIsShowBtnStart(slot2)
end
PdkController.onIsHoldBtnStartAtResultChanged = function (slot0)
slot3 = slot0
slot0.updateIsShowBtnStart(slot2)
end
PdkController.onIsShowingMatchFloatChanged = function (slot0)
slot3 = slot0
slot0.updateIsShowBtnStart(slot2)
end
PdkController.onIsShowingWinChanged = function (slot0)
slot3 = slot0
slot0.updateIsShowBtnStart(slot2)
end
PdkController.onIsShowingFailedChanged = function (slot0)
slot3 = slot0
slot0.updateIsShowBtnStart(slot2)
end
PdkController.onCanOnceOutAllCardsChanged = function (slot0)
slot3 = slot0
slot0.updateStateViewDic(slot2)
end
PdkController.onLeaveCardsCountDicChanged = function (slot0)
slot3 = slot0
slot0.updateIsShowWarningSpine(slot2)
end
PdkController.updateIsShowAutoIcon = function (slot0)
slot3 = slot0.model
slot1 = slot0.model.getAutoDic(slot2) or {}
slot4 = slot0.model
slot4 = {}
if slot0.model.getGameState(slot3) == PDK_GAMESTATE_PLAY then
slot4[PDK_VIEW_CHAIRID_ME] = slot1[PDK_VIEW_CHAIRID_ME]
slot4[PDK_VIEW_CHAIRID_RIGHT] = slot1[PDK_VIEW_CHAIRID_RIGHT]
slot4[PDK_VIEW_CHAIRID_LEFT] = slot1[PDK_VIEW_CHAIRID_LEFT]
slot4.isShowBtnAuto = not slot1[PDK_VIEW_CHAIRID_ME]
end
slot9 = true
slot0.model.setIsShowAutoIconDic(slot6, slot0.model, slot4)
end
PdkController.updateIsShowCantOutTxt = function (slot0)
slot1 = nil
slot4 = slot0.model
if slot0.model.getGameState(slot3) == PDK_GAMESTATE_PLAY then
slot4 = slot0.model
if slot0.model.getCurrentUser(slot3) == PDK_VIEW_CHAIRID_ME then
slot4 = slot0.model
slot1 = not slot0.model.getCanOutCard(slot3)
end
else
slot1 = false
end
slot6 = true
slot0.model.setIsShowCantOutTxt(slot3, slot0.model, slot1)
end
PdkController.updateStateViewDic = function (slot0)
slot1 = {}
slot2 = {}
slot5 = slot0.model
if slot0.model.getGameState(slot4) == PDK_GAMESTATE_PLAY then
slot6 = slot0.model
if slot0.model.getCurrentUser(slot5) == PDK_VIEW_CHAIRID_ME then
slot8 = slot4
if not slot0.isAutoState(slot6, slot0) then
slot7 = slot0.model
if slot0.model.getCanOutCard(slot6) then
slot7 = slot0.model
if not slot0.model.getCanOnceOutAllCards(slot6) then
slot1[slot4] = "turnView"
end
end
end
else
slot1[slot4] = "turnView"
end
slot7 = slot0.model
if slot0.model.getUsersIsOutCardDic(slot6) then
for slot9 = PDK_VIEW_CHAIRID_ME, PDK_VIEW_CHAIRID_LEFT, 1 do
if slot4 ~= slot9 then
if slot5[slot9] == -1 then
slot1[slot9] = "yaoBuQi"
elseif slot5[slot9] == 1 then
slot1[slot9] = "outPukeSheet"
end
end
end
end
elseif slot3 == PDK_GAMESTATE_END then
slot6 = slot0
if slot0.isRoundWinner(slot5) then
slot1[PDK_VIEW_CHAIRID_ME] = "outPukeSheet"
end
slot1[PDK_VIEW_CHAIRID_LEFT] = "outPukeSheet"
slot1[PDK_VIEW_CHAIRID_RIGHT] = "outPukeSheet"
elseif slot3 == PDK_GAMESTATE_READY then
slot6 = slot0.model
if slot0.model.getMyTableUserDatasDic(slot5) then
for slot8 = PDK_VIEW_CHAIRID_ME, PDK_VIEW_CHAIRID_LEFT, 1 do
if slot4[slot8] and slot4[slot8].cbUserStatus == US_READY then
slot1[slot8] = "ok"
end
end
end
end
slot7 = slot1
slot0.model.setStateViewDic(slot5, slot0.model)
end
PdkController.updateIsShowBtnStart = function (slot0)
slot6 = Hero
slot2 = slot0.model.getIsShowingWin(gameMgr)
slot3 = slot0.model.getIsShowingFailed(slot0.model)
slot4 = slot0.model.getIsShowingMatchFloat(slot0.model)
slot5 = slot0.model.getIsHoldBtnStartAtResult(slot0.model)
slot8 = slot0.model
slot6 = slot0.model.getIsHoldBtnStartAtBegin(slot0.model)
slot7 = false
if gameMgr.getUserData(slot2, Hero.getDwUserID(slot5)) ~= nil and slot1.cbUserStatus ~= US_PLAYING and slot8 ~= US_READY and not slot2 and not slot3 and not slot4 and not slot5 and not slot6 then
slot7 = true
end
slot12 = true
slot0.model.setIsShowBtnStart(slot9, slot0.model, slot7)
end
PdkController.updateIsShowHandCard = function (slot0)
slot6 = true
slot0.model.setIsShowHandCard(slot0.model, slot0.model, slot0.model.getGameState(slot0.model.setIsShowHandCard) == PDK_GAMESTATE_PLAY or slot1 == PDK_GAMESTATE_END)
end
PdkController.updateIsShowWarningSpine = function (slot0)
slot3 = slot0.model
slot2 = {}
if slot0.model.getLeaveCardsCountDic(slot2) then
slot5 = slot0.model
if slot0.model.getGameState(slot4) == PDK_GAMESTATE_PLAY then
for slot6 = PDK_VIEW_CHAIRID_ME, PDK_VIEW_CHAIRID_LEFT, 1 do
if slot1[slot6] == 1 then
slot2[slot6] = true
end
end
end
end
slot5 = slot0.model
slot9 = slot2
slot0.model.setIsShowWarningSpineDic(slot4, slot0.model.nilEmptyTable(slot7, slot0.model))
end
PdkController.updateCanOutCard = function (slot0)
slot3 = slot0.model
if slot0.model.getGameState(slot2) == PDK_GAMESTATE_PLAY then
slot3 = slot0.model
if slot0.model.getCurrentUser(slot2) ~= PDK_VIEW_CHAIRID_ME then
slot4 = false
slot0.model.setCanOutCard(slot2, slot0.model)
return
end
end
slot3 = slot0
if not slot0.isTurnWinner(slot2) then
slot3 = slot0
if slot0.isFirstHand(slot2) then
slot4 = true
slot0.model.setCanOutCard(slot2, slot0.model)
elseif slot0.model._serverCanOut == 1 then
slot4 = true
slot0.model.setCanOutCard(slot2, slot0.model)
else
slot4 = false
slot0.model.setCanOutCard(slot2, slot0.model)
end
end
end
PdkController.updateCanOnceOutAllCards = function (slot0)
slot3 = slot0.model
if slot0.model.getMyCards(slot2) then
slot4 = slot0.model
if not slot0.model.getCanOutCard(slot3) then
slot5 = false
slot0.model.setCanOnceOutAllCards(slot3, slot0.model)
return
end
end
slot3 = slot0.analyzeCardInfo(slot3, slot0).ct
slot6 = slot0
if slot0.isAutoState(slot1) or slot3 == nil or slot3 == PDK_CT_ERROR then
slot7 = false
slot0.model.setCanOnceOutAllCards(slot5, slot0.model)
return
end
slot8 = {
dot = 0,
ct = PDK_CT_BOMB_CARD
}
slot4 = slot0.findCanFollowCard(slot5, slot0, slot1)
if slot3 ~= PDK_CT_BOMB_CARD and slot4 and slot4.boomDic then
slot8 = false
slot0.model.setCanOnceOutAllCards(slot6, slot0.model)
return
end
slot5 = false
slot8 = slot0
if not slot0.isTurnWinner(slot7) then
slot8 = slot0
if slot0.isFirstHand(slot7) then
slot5 = true
else
slot8 = slot0.model
if slot0.model.getOutCardInfo(slot7).ct == slot2.ct then
if slot6.dot < slot2.dot then
slot5 = true
end
elseif slot6.ct ~= PDK_CT_BOMB_CARD and slot2.ct == PDK_CT_BOMB_CARD then
slot5 = true
end
end
end
slot9 = slot5
slot0.model.setCanOnceOutAllCards(slot7, slot0.model)
end
PdkController.lockUpViewDic = function (slot0)
slot1 = {
stateViewDic = {}
}
for slot5 = PDK_VIEW_CHAIRID_ME, PDK_VIEW_CHAIRID_LEFT, 1 do
slot1.stateViewDic[slot5] = true
end
slot6 = true
slot0.model.setLockViewDic(slot3, slot0.model, slot1)
end
return
|
local M = {}
local bufferline_config = {}
M.config = function()
bufferline_config = {
active = true,
keymap = {
normal_mode = {
["<S-l>"] = ":BufferNext<CR>",
["<S-h>"] = ":BufferPrevious<CR>",
},
},
}
end
M.setup = function()
local keymap = require "keymappings"
keymap.append_to_defaults(bufferline_config.keymap)
end
return M
|
shell.run("/zOS/System/Boot.lua")
|
--- @class GCSoundPatch
--- CSoundPatch class.
--- Created with Global.CreateSound
local GCSoundPatch = {}
--- Adjust the pitch, alias the speed at which the sound is being played.
--- This invokes the GM:EntityEmitSound.
--- @param pitch number @The pitch can range from 0-255.
--- @param deltaTime number @The time to fade from previous to the new pitch.
function GCSoundPatch:ChangePitch(pitch, deltaTime)
end
--- Adjusts the volume of the sound played.
--- Appears to only work while the sound is being played.
--- @param volume number @The volume ranges from 0 to 1.
--- @param deltaTime number @Time to fade the volume from previous to new value from.
function GCSoundPatch:ChangeVolume(volume, deltaTime)
end
--- Fades out the volume of the sound from the current volume to 0 in the given amount of seconds.
--- @param seconds number @Fade time.
function GCSoundPatch:FadeOut(seconds)
end
--- Returns the DSP ( Digital Signal Processor ) effect for the sound.
--- @return number @The DSP effects of the sound
function GCSoundPatch:GetDSP()
end
--- Returns the current pitch.
--- @return number @The current pitch, can range from 0-255.
function GCSoundPatch:GetPitch()
end
--- Returns the current sound level.
--- @return number @The current sound level, see Enums/SNDLVL.
function GCSoundPatch:GetSoundLevel()
end
--- Returns the current volume.
--- @return number @The current volume, ranging from 0 to 1.
function GCSoundPatch:GetVolume()
end
--- Returns whenever the sound is being played.
--- @return boolean @Is playing or not
function GCSoundPatch:IsPlaying()
end
--- Starts to play the sound. This will reset the sound's volume and pitch to their default values. See CSoundPatch:PlayEx
function GCSoundPatch:Play()
end
--- Same as CSoundPatch:Play but with 2 extra arguments allowing to set volume and pitch directly.
--- @param volume number @The volume ranges from 0 to 1.
--- @param pitch number @The pitch can range from 0-255.
function GCSoundPatch:PlayEx(volume, pitch)
end
--- Sets the DSP (Digital Signal Processor) effect for the sound. Similar to Player:SetDSP but for individual sounds.
--- 🦟 **BUG**: [This will only apply if the sound is not playing.](https://github.com/Facepunch/garrysmod-issues/issues/4086)
--- @param dsp number @The DSP effect to set
function GCSoundPatch:SetDSP(dsp)
end
--- Sets the sound level in decibel.
--- @param level number @The sound level in decibel
function GCSoundPatch:SetSoundLevel(level)
end
--- Stops the sound from being played.
--- 🦟 **BUG**: [This will not work if the entity attached to this sound patch (specified by Global.CreateSound) is invalid.](https://github.com/Facepunch/garrysmod-issues/issues/3260)
function GCSoundPatch:Stop()
end
|
--orgy
train=require(307227743)
gr={}
for _, p in pairs(game.Players:GetPlayers()) do
table.insert(gr, p)
if #gr==3 then
print"orgy time"
for i=1, 3 do
gr[i]:LoadCharacter()
end
wait()
train(gr[1].Character, gr[2].Character, gr[3].Character)
gr={}
end
end
|
function startscreeninit()
startstatedelay = 30
-- Play the menu music
playmusic(16)
end
function startscreenupdate()
if startstatedelay < 0 then
if btn(1) then
gamestate__numplayers, gamestate__playstate, gamestate__startstate = 1, true, false
resetplaystate()
end
if btn(0) then
gamestate__storystate, gamestate__startstate = true, false
end
else
startstatedelay -= 1
end
end
function startscreendraw()
print("get dis money", 40, 15, 11);
print("community edition", 31, 25, 8);
if gametime % 12 < 6 then
spr(0, 62, 42)
else
spr(1, 62, 42)
end
-- Reset our pallet
pal()
print("\x8b story", 26, 62, 7);
print("start \x91", 71, 62, 7);
print ("total cash: $" .. totalcash, 35, 85, 11)
print ("a game by aaron turner", 23, 95, 12)
print ("get the full game at", 25, 105, 7)
print ("https://getdismoney.com", 20, 115, 12)
end
|
-- [===[
local a
local b, c = true, "f\0o"
-- Comment
--[[ Long ]] --[==[
comment.
]==]
do
local x = 1
local y = 1.
local z = .1
local n = 0x0.8p-1
local y = (a:b[[]])
local s = "\0\1\2\3\4\5\6\7\8\9\10\11\12\13\\\01499\15\16\17\18\19\"\20\21\22\23¤\24\25\26\27\28\29\30\31~ëÓ§\255`\0011\1\z
\xff\u{b4}"
local x = 1 + 2 + 3
local y = (1 - 2) - 3
local z = 1 - (2 - 3)
do foo() ; o:m() end
while false or true do
foo()
end
repeat
local x = x + foo()
until x - -7 == 8
for i = 1, 9 do foo(i) end
for i, v in ipairs(t) do bar(i, v) end
local function foo() end
local function foo(a, ...) return end
function a:b(x, ...) return ... end
a[x] = function(i, j) if i then return end return 5 end
g = a[x]()
local a = 1 + 2 + 3
local b = "1".."2".."3"
local c = 1 + 4^3^2 * 5
local s = a .. b
local s = 1. .. x
local s = 1.1 .. x
local x = a and b and c or q and w or 5
t.k1.k2 = x
;(t.k1).k2 = x
;(t1 or t2).k = x
;(t1 or t2).k, (t3 or t4).k = x, y
if x or y then foo() end
if x then
foo()
elseif y then
bar()
else
baz()
end
local t = {x=5, ["y"]=(a or b), f=function(...)return"bark"end}
local m = -8
local n = not false or false
local l = #t + 1
local b = not not not true
local s1 = "\"''a''b''c''\""
local s2 = '\'""a""b""c""\''
print(a .. ... .. 3.75 .. 400)
local s = (""):rep(9)
local n = ({9})[1]
local v = (...)[1]
local b = (function(n) return n>1 end)(9)
;;;;
-- Special number notations.
local n = - -5
local n = -1/0
local n = - -1 / 0
local n = - (-1/0)
local n = 5 - 1/0
local n = - - (-0)
-- [[ Lua 5.2+
goto foo
do goto foo end
::foo::
local a = x & y
local b = x ~ y
local c = x | y
local d = x << y
local e = x >> y
local f = x // y
local g = ~x
local foo = ((y & 0x7) << 4) | 0xFF00
while 1 do
break
unreachable()
end
--]]
-- [[ Lua 5.4+
local x<close>
local y<close>, z<const> = 1, 2
--]]
end
-- Minify tests.
do
local longNameA = global -- Watchers: 3
local longNameB = longNameA -- Watchers: 5
local global = global -- Watchers: 4
local longNameC = longNameB -- Watchers: 3
local getGlobal = e -- Watchers: 2
local longNameD = longNameB -- Watchers: 1
local longNameE = longNameA -- Watchers: 0
function globalFunc(x) local x = x end
local upvalue = 0
local function f(arg1, arg2)
local assign1, assign2 = 0, 0
local decl, func
decl = 0
func = function()end
for loop1, loop2 in ipairs(t) do
func(upvalue, arg1,arg2, assign1,assign2, decl, loop1,loop2)
end
end
-- [[ Lua 5.2+
local _ENV = _ENV
local function getEnv()
return _ENV
end
--]]
end
--]===]
return
|
local notify = require'notify'
return function(message, level)
notify(message, level, {
title = 'lir.nvim',
timeout = 500
})
end
|
-- the size of the dungeon in cells
local dungeon_size = {
["fine"] = 11,
["dimin"] = 13,
["tiny"] = 17,
["small"] = 21,
["medium"] = 27,
["large"] = 35,
["huge"] = 43,
["gargant"] = 55,
["colossal"] = 71,
}
return setmetatable({
dungeon_size = dungeon_size,
}, {})
|
__MANY2ONEFILES={}
function requireLuaString(str)
if not package.loaded[str] then
package.loaded[str] = true
local res = load(__MANY2ONEFILES[str])
res = res(str)
if res ~= nil then
package.loaded[str] = res
end
end
return package.loaded[str]
end
__MANY2ONEFILES['req']="local _G = G\
\
local M = {}\
_ENV = M\
\
_G.c=10"
requireLuaString('req')
a = 4
print(a+b)
print(c)
|
local L = Grid2Options.L
Grid2Options:RegisterStatusOptions("combat", "combat", function(self, status, options)
self:MakeStatusStandardOptions(status, options)
self:MakeSpacerOptions(options, 30)
options.useEmptyIcon = {
type = "toggle",
order = 150,
width = "full",
name = L["Use Empty Icon"],
desc = L["Displays an invisible Icon."],
get = function(info) return status.dbx.useEmptyIcon end,
set = function(info, v)
status.dbx.useEmptyIcon = v or nil
if status.enabled then
status:UpdateDB()
status:UpdateAllUnits()
end
end,
}
end, {
titleIcon = [[Interface\CharacterFrame\UI-StateIcon]],
titleIconCoords = {0.55, 0.93, 0.07, 0.42},
})
Grid2Options:RegisterStatusOptions("combat-mine", "combat", function(self, status, options)
self:MakeStatusStandardOptions(status, options)
self:MakeSpacerOptions(options, 30)
options.useEmptyIcon = {
type = "toggle",
order = 150,
width = "full",
name = L["Use Empty Icon"],
desc = L["Displays an invisible Icon."],
get = function(info) return status.dbx.useEmptyIcon end,
set = function(info, v)
status.dbx.useEmptyIcon = v or nil
if status.enabled then
status:UpdateDB()
status:UpdateAllUnits()
end
end,
}
end, {
titleIcon = [[Interface\CharacterFrame\UI-StateIcon]],
titleIconCoords = {0.55, 0.93, 0.07, 0.42},
})
|
local _utils = require("nui.utils")._
local defaults = require("nui.utils").defaults
local is_type = require("nui.utils").is_type
local event = require("nui.utils.autocmd").event
local Popup = require("nui.popup")
local function parse_lines(lines)
local data = {
lines = {},
total_lines = 0,
max_line_length = 0,
}
for index, line in ipairs(lines) do
data.total_lines = data.total_lines + 1
line._index = index
if line.type == "item" then
table.insert(data.lines, line)
local line_length = vim.api.nvim_strwidth(line.text)
if data.max_line_length < line_length then
data.max_line_length = line_length
end
elseif line.type == "separator" then
table.insert(data.lines, line)
end
end
return data
end
local function calculate_buf_lines(menu)
local buf_lines = {}
local border_props = menu.border.border_props
local default_char = is_type("table", border_props.char) and border_props.char.top or ""
local default_text_align = is_type("table", border_props.text) and border_props.text.top_align or "left"
local separator_char = defaults(menu.menu_props.separator.char, default_char)
local separator_text_align = defaults(menu.menu_props.separator.text_align, default_text_align)
local max_length = menu.popup_props.size.width
local separator_max_length = max_length - vim.api.nvim_strwidth(separator_char) * 2
for _index, line in ipairs(menu.menu_props.lines) do
if line.type == "item" then
local text = _utils.truncate_text(line.text, max_length)
table.insert(buf_lines, text)
elseif line.type == "separator" then
local text = _utils.align_text(
_utils.truncate_text(line.text, separator_max_length),
separator_text_align,
separator_max_length,
separator_char
)
table.insert(buf_lines, separator_char .. text .. separator_char)
end
end
return buf_lines
end
local default_keymap = {
close = { "<Esc>", "<C-c>" },
focus_next = { "j", "<Down>", "<Tab>" },
focus_prev = { "k", "<Up>", "<S-Tab>" },
submit = { "<CR>" },
}
local function parse_keymap(keymap)
local result = defaults(keymap, {})
for name, default_keys in pairs(default_keymap) do
if is_type("nil", result[name]) then
result[name] = default_keys
elseif is_type("string", result[name]) then
result[name] = { result[name] }
end
end
return result
end
---@param direction "'next'" | "'prev'"
---@param current_index nil | number
local function focus_item(menu, direction, current_index)
if not menu.popup_state.mounted then
return
end
local curr_index = defaults(current_index, menu.menu_state.curr_index)
local next_index = nil
if direction == "next" then
if curr_index == menu.menu_props.total_lines then
next_index = 1
else
next_index = curr_index + 1
end
elseif direction == "prev" then
if curr_index == 1 then
next_index = menu.menu_props.total_lines
else
next_index = curr_index - 1
end
end
if menu.menu_props.lines[next_index].type == "separator" then
return focus_item(menu, direction, next_index)
end
if next_index then
vim.api.nvim_win_set_cursor(menu.winid, { next_index, 0 })
end
end
local function init(class, popup_options, options)
local props = vim.tbl_extend("force", {
separator = defaults(options.separator, {}),
keymap = parse_keymap(options.keymap),
}, parse_lines(
options.lines
))
local state = {
curr_index = nil,
}
for _, line in ipairs(props.lines) do
if line.type == "item" then
state.curr_index = line._index
break
end
end
local width = math.max(
math.min(props.max_line_length, defaults(options.max_width, 999)),
defaults(options.min_width, 16)
)
local height = math.max(
math.min(props.total_lines, defaults(options.max_height, 999)),
defaults(options.min_height, 1)
)
popup_options = vim.tbl_deep_extend("force", {
enter = true,
size = {
width = width,
height = height,
},
win_options = {
cursorline = true,
scrolloff = 1,
sidescrolloff = 0,
},
}, popup_options)
local self = class.super.init(class, popup_options)
self.menu_props = props
self.menu_state = state
props.buf_lines = calculate_buf_lines(self)
props.on_submit = function()
local curr_index = self.menu_state.curr_index
local item = self.menu_props.lines[curr_index]
self:unmount()
if options.on_submit then
options.on_submit(item)
end
end
props.on_close = function()
self:unmount()
if options.on_close then
options.on_close()
end
end
props.on_focus_next = function()
focus_item(self, "next")
end
props.on_focus_prev = function()
focus_item(self, "prev")
end
return self
end
local Menu = setmetatable({
name = "Menu",
super = Popup,
}, {
__index = Popup.__index,
})
---@param text nil | string
function Menu.separator(text)
return {
type = "separator",
text = defaults(text, ""),
}
end
---@param item string | table
---@param props table | nil
function Menu.item(item, props)
local object = is_type("string", item) and defaults(props, {}) or item
if is_type("string", item) then
object.text = item
end
object.type = "item"
return object
end
function Menu:init(popup_options, options)
return init(self, popup_options, options)
end
function Menu:mount()
self.super.mount(self)
local props = self.menu_props
self:on(event.CursorMoved, function()
local index = vim.api.nvim_win_get_cursor(self.winid)[1]
self.menu_state.curr_index = index
end, {})
for _, key in pairs(props.keymap.focus_next) do
self:map("n", key, props.on_focus_next, { noremap = true, nowait = true })
end
for _, key in pairs(props.keymap.focus_prev) do
self:map("n", key, props.on_focus_prev, { noremap = true, nowait = true })
end
for _, key in pairs(props.keymap.close) do
self:map("n", key, props.on_close, { noremap = true, nowait = true })
end
for _, key in pairs(props.keymap.submit) do
self:map("n", key, props.on_submit, { noremap = true, nowait = true })
end
vim.api.nvim_buf_set_lines(self.bufnr, 0, #self.menu_props.buf_lines, false, self.menu_props.buf_lines)
vim.api.nvim_buf_set_option(self.bufnr, "readonly", true)
vim.api.nvim_buf_set_option(self.bufnr, "modifiable", false)
vim.api.nvim_win_set_cursor(self.winid, { self.menu_state.curr_index, 0 })
end
local MenuClass = setmetatable({
__index = Menu,
}, {
__call = init,
__index = Menu,
})
return MenuClass
|
//________________________________
//
// NS2 CustomEntitesMod
// Made by JimWest 2012
//
//________________________________
// modified from WorlToolTop
Script.Load("lua/ExtraEntitiesMod/LogicMixin.lua")
class 'LogicWorldTooltip' (Entity)
LogicWorldTooltip.kMapName = "logic_worldtooltip"
local networkVars = {
tooltipText = string.format("string (%d)", 256),
enabled = "boolean",
shownOnce = "boolean",
}
AddMixinNetworkVars(LogicMixin, networkVars)
function LogicWorldTooltip:OnCreate()
Entity.OnCreate(self)
end
function LogicWorldTooltip:OnInitialized()
self.tooltipText = self.tooltip
if Server then
InitMixin(self, LogicMixin)
end
self.shownPlayers = {}
self:SetUpdates(false)
end
function LogicWorldTooltip:Reset()
self.shownPlayers = {}
end
function LogicWorldTooltip:GetTooltipText(player)
if self.enabled then
local showOk = true
local playerId = player:GetId()
if self.shownOnce then
for i, shownPlayerId in ipairs(self.shownPlayers) do
if shownPlayerId == playerId then
showOk = false
break
end
end
end
if showOk then
local string = Locale.ResolveString(self.tooltipText)
table.insertunique(self.shownPlayers, playerId )
return SubstituteBindStrings(string)
else
return nil
end
end
end
function LogicWorldTooltip:OnLogicTrigger()
self:OnTriggerAction()
end
Shared.LinkClassToMap("LogicWorldTooltip", LogicWorldTooltip.kMapName, networkVars)
|
local Llama = {
Dictionary = require(script.Dictionary);
List = require(script.List);
Set = require(script.Set);
equalObjects = require(script.equalObjects);
isEmpty = require(script.isEmpty);
None = require(script.None);
}
return Llama
|
local onlooker_barrage_pin_map = require("qnFiles/qnPlist/games/onlooker_barrage_pin");
local onlooker_barrage_item=
{
name="onlooker_barrage_item",type=0,typeName="View",time=0,x=0,y=0,width=200,height=60,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,
{
name="bg_props",type=1,typeName="Image",time=0,x=0,y=0,width=200,height=54,visible=0,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignLeft,file=onlooker_barrage_pin_map['bg_props.png'],gridLeft=32,gridRight=32,gridTop=25,gridBottom=25,
{
name="props",type=1,typeName="Image",time=0,x=15,y=-5,width=57,height=60,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignRight,file="isolater/prop/default_icon.png"
}
},
{
name="bg_mine",type=1,typeName="Image",time=0,x=0,y=0,width=200,height=48,visible=0,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignLeft,file=onlooker_barrage_pin_map['bg_mine.png'],gridLeft=6,gridRight=6,gridTop=20,gridBottom=20
},
{
name="info",type=4,typeName="Text",time=0,x=15,y=0,width=170,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,fontSize=30,textAlign=kAlignCenter,colorRed=255,colorGreen=255,colorBlue=255,string=[[这是弹幕123]],colorA=1
}
}
return onlooker_barrage_item;
|
---@class PrivateChannel
---@field client Client
---@field parent Container|Client
---@field createdAt number
---@field id SnowflakeId
---@field timestamp string
---@field mentionString string
---@field type enums.channelType
---@field messages WeakCache
---@field name string
---@field recipient User
local PrivateChannel = {
-- [[Snowflake Methods]] --
---Returns `Snowflake.id`
---@param self Snowflake
---@return SnowflakeId
__hash = function(self) end,
---Returns a unique `Date` object that represents when this object was created by Discord.
---Equivalent to `Date.fromSnowflake(Snowflake.id)`
---@param self Snowflake
---@return Date
getDate = function(self) end,
-- [[TextChannel Methods]] --
---Indicates in the channel that the client's user "is typing".
---@param self TextChannel
---@return boolean
broadcastTyping = function(self) end,
---Returns the first message found in the channel, if any exist.
---This is not cached. An HTTP request is made each time this method is called.
---@param self TextChannel
---@return Message
getFirstMessage = function(self) end,
---Returns the last message found in the channel, if any exist.
---This is not cached. An HTTP request is made each time this method is called.
---@param self TextChannel
---@return Message
getLastMessage = function(self) end,
---Gets a message object by ID.
---@param self TextChannel
---@param id SnowflakeId
getMessage = function(self, id) end,
---Returns a newly constructed cache of between 1 and 100 (default = 50) messages in the channel.
---While the cache will never automatically gain or lose objects, they may be updated by gateway events.
---@param self TextChannel
---@param limit number
---@return SecondaryCache
getMessages = function(self, limit) end,
---Returns a newly constructed cache of between 1 and 100 (default = 50) messages in the channel after the specified id.
---While the cache will never automatically gain or lose objects, they may be updated by gateway events.
---@param self TextChannel
---@param id SnowflakeId
---@param limit number
---@return SecondaryCache
getMessagesAfter = function(self, id, limit) end,
---Returns a newly constructed cache of between 1 and 100 (default = 50) messages in the channel around the specified id.
---While the cache will never automatically gain or lose objects, they may be updated by gateway events.
---@param self TextChannel
---@param id SnowflakeId
---@param limit number
---@return SecondaryCache
getMessagesAround = function(self, id, limit) end,
---Returns a newly constructed cache of between 1 and 100 (default = 50) messages in the channel before the specified id.
---While the cache will never automatically gain or lose objects, they may be updated by gateway events.
---@param self TextChannel
---@param id SnowflakeId
---@param limit number
---@return SecondaryCache
getMessagesBefore = function(self, id, limit) end,
---Returns a newly constructed cache of up to 50 messages that are pinned in the channel.
---While the cache will never automatically gain or lose objects, they may be updated by gateway events.
---@param self TextChannel
---@return SecondaryCache
getPinnedMessages = function(self) end,
---Sends a message to the channel. If `content` is a string, then it is sent as-is.
---If it is a table, more advanced formatting is allowed.
---@param self TextChannel
---@param content string
---@return Message
send = function(self, content) end,
---Sends a message to the channel with content formatted according to `string.format(content, ...)`.
---@param self TextChannel
---@param content string
---@return Message
sendf = function(self, content, ...) end,
-- [[PrivateChannel Methods]] --
---Closes the channel. This does not delete the channel.
---To re-open the channel, use `User:getPrivateChannel`.
---@param self PrivateChannel
---@return boolean
close = function(self) end,
}
return PrivateChannel
|
-- Controllers
local list_tasks = require "src.controller.list_tasks"
-- Utils
local date = require "date.date"
local utils = require "src.utils"
local print_task = utils.print_task
local todate = utils.todate
return function(parser)
local list_tasks_command = parser:command("list-tasks")
list_tasks_command:summary("List tasks between a time range")
list_tasks_command
:option("-b --before", "Starting a number of days before today")
:convert(tonumber)
:count("0-1")
list_tasks_command
:option("-f --from", "From the given date")
:convert(todate)
:count("0-1")
list_tasks_command
:option("-t --to", "To the given date")
:convert(todate)
:count("0-1")
list_tasks_command:action(function(args, name)
local tasks, err
if not args.before and (not args.from or not args.to) then
print(list_tasks_command:get_usage())
return
end
if args.before then
local start_date = date():adddays(-args.before)
tasks, err = list_tasks(start_date, date())
end
if args.from and args.to then
tasks, err = list_tasks(args.from, args.to)
end
if err then
print(err)
return 1
end
print("id|project|start_time|end_time|description")
print("------------------------------------------")
for _, task in ipairs(tasks) do
print_task(task)
end
end)
end
|
return function()
it("should load successfully", function()
require(script.Parent)
end)
end
|
#!/usr/bin/env lua
--
-- The contents of this file are subject to the Mozilla Public
-- License Version 1.1 (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.mozilla.org/MPL/
--
-- Software distributed under the License is distributed on an "AS
-- IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-- implied. See the License for the specific language governing
-- rights and limitations under the License.
--
-- The Original Code is State Machine Compiler (SMC).
--
-- The Initial Developer of the Original Code is Charles W. Rapp.
-- Portions created by Charles W. Rapp are
-- Copyright (C) 2000 - 2003 Charles W. Rapp.
-- All Rights Reserved.
--
-- Contributor(s):
-- Port to Lua by Francois Perrad, francois.perrad@gadz.org
--
-- Function
-- Main
--
-- Description
-- This routine starts the finite state machine running.
--
-- RCS ID
-- $Id: checkstring.lua,v 1.2 2010/11/21 18:49:09 fperrad Exp $
--
-- CHANGE LOG
-- $Log: checkstring.lua,v $
-- Revision 1.2 2010/11/21 18:49:09 fperrad
-- refactor Lua generation (compat 5.2)
--
-- Revision 1.1 2007/01/03 15:40:45 fperrad
-- + Added Lua examples 1 - 3.
--
--
--
local AppClass = require 'AppClass'
local arg = {...}
local retcode = 0
if #arg < 1 then
io.stderr:write "No string to check.\n"
retcode = 2
elseif #arg > 1 then
io.stderr:write "Only one argument is accepted.\n"
retcode = 3
else
local appobject = AppClass.new()
local str = arg[1]
local result
if appobject:CheckString(str) then
result = 'acceptable'
else
result = 'not acceptable'
retcode = 1
end
print(string.format('The string "%s" is %s.', str, result))
end
os.exit(retcode)
|
--- Everything is global, so that it will be available in the REPL
--- For use in REPL, not used here
util = require("utils")
sp_to_p = util.sp_to_p
sp_to_in = util.sp_to_in
node_type = util.node_type
node_subtype = util.node_subtype
link_nodes = util.link_nodes
make_glyph = util.make_glyph
make_glue = util.make_glue
make_glue_spec = util.make_glue_spec
make_rule = util.make_rule
make_penalty = util.make_penalty
fil = util.fil
fill = util.fill
filll = util.filll
is_whitespace = util.is_whitespace
is_linefeed = util.is_linefeed
is_nobreak = util.is_nobreak
is_command_terminator = util.is_command_terminator
copy_table = util.copy_table
read_string = util.read_string
read_group = util.read_group
walk_table = util.walk_table
show_node = util.show_node
walk_list = util.walk_list
--- For use here
repl = require("repl")
repl = repl.repl
reader = require("reader")
push_reader = reader.push_reader
commands = require("commands")
pages = require("pages")
build_pages = pages.build_pages
build_page = pages.build_page
main = require("main")
main_loop = main.main_loop
format = require("format")
main_text_tbl = format.main_text_tbl
push_tbl = format.push_tbl
--- Do the job
function do_job()
push_reader("file:text.txt")
push_tbl(main_text_tbl)
main_loop()
build_pages()
end
do_job()
--- Enter REPL for exploration
--- repl()
|
Signal = Signal or require "libs.hump.signal"
local Class = require "libs.hump.class"
local socket = require "socket"
local IRC = Class {}
local utils = require "utils"
function IRC:init(settings)
self.settings = settings
if self.settings.dummy then
return
end
self.joined = false
self.names = {}
self.commands = {}
-- TOPIC in channel
self.commands["332"] = function(receive)
local nick, channel, topic = receive:match(":[%w%d%p]+ TOPIC ([%w%d%p]+) (#[%w%d%p]+) :(.+)")
Signal.emit("process_topic", nick, channel, topic)
end
-- TOPICWHOTIME (Ignore)
self.commands["333"] = function(receive) end
-- NAMES list in channel
self.commands["353"] = function(receive)
local channel, names = receive:match(":[%w%d%p]+ 353 [%w%d%p]+ . (#[%w%d%p]+) :(.+)")
print(channel, names, receive)
-- accumulate names until we get a 366
self.names[channel] = self.names[channel] or ""
self.names[channel] = self.names[channel] .. " " .. names
if self.settings.verbose then
Signal.emit("message", self.settings.channel, names)
end
end
-- End of NAMES list in channel
self.commands["366"] = function(receive)
local channel = receive:match(":[%w%d%p]+ 366 [%w%d%p]+ (#[%w%d%p]+) :.+")
local names = self.names[channel]
if names then
Signal.emit("process_names", channel, names)
-- clear out the accumulated names
self.names[channel] = nil
end
end
-- End of MOTD, safe to JOIN
self.commands["376"] = function(receive)
self.socket:send("JOIN " .. self.settings.channel .. "\r\n\r\n")
self.joined = true
return true
end
self.commands["433"] = function(receive)
self.socket:send("NICK " .. self.settings.nick .. "_\r\n\r\n")
end
-- Client joins channel
self.commands["JOIN"] = function(receive)
local nick, channel = receive:match(":([%w%d%p]+)![%w%d%p]+ JOIN :(#[%w%d%p]+)")
if nick and channel then
Signal.emit("process_join", nick, channel)
end
end
-- Ignore
self.commands["MODE"] = function(receive) end
-- Client changes nickname
self.commands["NICK"] = function(receive)
local old_nick, new_nick = receive:match(":([%w%d%p]+)![%w%d%p]+ NICK :(.+)")
Signal.emit("process_nick", old_nick, new_nick)
end
-- Client leaves channel
self.commands["PART"] = function(receive)
local nick, channel = receive:match(":([%w%d%p]+)![%w%d%p]+ PART (#[%w%d%p]+)")
if nick and channel then
Signal.emit("process_part", nick, channel)
end
end
-- Message
self.commands["PRIVMSG"] = function(receive)
local line = nil
local channel = channel
-- :Xkeeper!xkeeper@netadmin.badnik.net PRIVMSG #fart :gas
local nick, channel, line = receive:match(":([%w%d%p]+)![%w%d%p]+ PRIVMSG ([%w%d%p]+) :(.+)")
print(":".. nick .. " PRIVMSG " .. channel .. " :" .. line)
if line then
if channel:find("#") then
Signal.emit("process_message", nick, line, channel)
else
Signal.emit("process_query", nick, line, channel)
end
end
if self.settings.verbose then
Signal.emit('message', self.settings.channel, receive)
end
end
-- Client quits
self.commands["QUIT"] = function(receive)
local nick, message = receive:match(":([%w%d%p]+)![%w%d%p]+ QUIT :(.+)")
Signal.emit("process_quit", nick, message, time)
end
-- Unhandled responses
self.commands["UNHANDLED"] = function(receive, command)
local message = "unhandled response: " .. command .. ": " .. receive
print(self.settings.channel, message)
if self.settings.verbose then
Signal.emit("message", self.settings.channel, message)
end
end
end
-- XXX: stupid
function IRC:quit()
if self.settings.dummy then
return
end
self.socket:send("QUIT :Goodbye, cruel world!\r\n\r\n")
self.socket:close()
end
function IRC:join_channel(channel)
self.socket:send("JOIN " .. channel .. "\r\n\r\n")
end
function IRC:change_nick(nick)
self.socket:send("NICK " .. nick .. "\r\n\r\n")
end
function IRC:part_channel(channel)
self.socket:send("PART " .. channel .. "\r\n\r\n")
end
function IRC:request_names(channel)
self.socket:send("NAMES " .. channel .. "\r\n\r\n")
end
function IRC:request_topic(channel)
self.socket:send("TOPIC " .. channel .. "\r\n\r\n")
end
function IRC:handle_receive(receive, time)
-- Respond to PING
if receive:find("PING :([%wx]+)") == 1 then
self.socket:send("PONG :" .. receive:sub(receive:find("PING :") + 6) .. "\r\n\r\n")
print("PONG")
return true
end
local command = receive:match(":[%w%d%p]+ ([%u%d]+) .+")
if self.commands[command] then
return self.commands[command](receive)
else
return self.commands["UNHANDLED"](receive, command)
end
print(self.settings.channel, "response: " .. command .. ": " .. receive)
return true
end
function IRC:connect()
if self.settings.dummy then
return
end
local function connect_socket(params)
print("Connecting to " .. params.server .. ":" .. params.port .. "/" .. params.channel .. " as " .. params.nick)
local s = socket.tcp()
s:connect(socket.dns.toip(params.server), params.port)
-- USER username hostname servername :realname
s:send("USER " .. string.format("%s %s %s :%s\r\n\r\n", params.nick, params.nick, params.nick, params.fullname or "inhumanity"))
s:send("NICK " .. params.nick .. "\r\n\r\n")
return s
end
self.socket = connect_socket(self.settings)
self.joined = false
if self.socket == nil then
return self:connect()
end
Signal.register('message', function(channel, content, response_code)
if response_code then
content = response_code .. ": " .. content
end
self.socket:send("PRIVMSG " .. channel .. " :" .. content .. "\r\n\r\n")
print("PRIVMSG " .. channel .. " :" .. content)
end)
self.start = socket.gettime()
return true
end
function IRC:update(dt)
if self.settings.dummy then
return
end
local ready = socket.select({self.socket}, nil, 0.01)
local time = socket.gettime() - self.start
-- process incoming, reply as needed
if ready[self.socket] then
local receive = self.socket:receive('*l')
if self.settings.verbose then print(receive) end
if receive == nil then
print("Timed out.. attempting to reconnect!")
return self:connect()
end
self:handle_receive(receive, time)
end
return true
end
function IRC:run()
if self.settings.dummy then
return
end
self:connect()
while true do
if not self:update() then
return
end
end
end
return IRC
|
require("busted.runner")()
describe("#sdk SDK.Utils.Table", function()
-- before_each initialization
local Table
before_each(function()
Table = require("sdk/utils/table")
end)
describe("Compare()", function()
describe("when both tables have the same reference", function()
TestReturnTrue(function()
local t = {}
return Table.Compare(t, t)
end)
end)
describe("when both tables with nested ones are the same", function()
TestReturnTrue(function()
local a = { first = {}, second = { third = {} } }
local b = { first = {}, second = { third = {} } }
return Table.Compare(a, b)
end)
end)
describe("when one of the tables is nil", function()
it("should return false", function()
local t = {}
assert.is_false(Table.Compare(nil, t))
assert.is_false(Table.Compare(t, nil))
end)
end)
describe("when one of the tables is not a table type", function()
it("should return false", function()
local t = {}
assert.is_false(Table.Compare("table", t))
assert.is_false(Table.Compare(t, "table"))
end)
end)
describe("when both tables with nested ones are not the same", function()
TestReturnFalse(function()
local a = { first = {}, second = { third = {} } }
local b = { first = {}, second = { third = { "fourth" } } }
return Table.Compare(a, b)
end)
end)
end)
describe("Count()", function()
describe("when the passed parameter is not a table", function()
TestReturnFalse(function()
return Table.Count("test")
end)
end)
describe("when the table with default indexes", function()
it("should return the number of elements", function()
local t = { one = 1, two = 2, three = 3, four = 4, five = 5 }
assert.is_equal(5, Table.Count(t))
end)
end)
describe("when the table with custom indexes", function()
it("should return the number of elements", function()
local t = { 1, 2, 3, 4, 5 }
assert.is_equal(5, Table.Count(t))
end)
end)
end)
describe("HasValue()", function()
describe("when the passed parameter is not a table", function()
TestReturnFalse(function()
return Table.HasValue("test")
end)
end)
describe("when the table with default indexes", function()
describe("and the element is in the table", function()
TestReturnTrue(function()
local t = { one = 1, two = 2, three = 3, four = 4, five = 5 }
return Table.HasValue(t, 3)
end)
end)
describe("and the element is not in the table", function()
TestReturnFalse(function()
local t = { one = 1, two = 2, three = 3, four = 4, five = 5 }
return Table.HasValue(t, 6)
end)
end)
end)
describe("when the table with custom indexes", function()
describe("and the element is in the table", function()
TestReturnTrue(function()
local t = { 1, 2, 3, 4, 5 }
return Table.HasValue(t, 3)
end)
end)
describe("and the element is not in the table", function()
TestReturnFalse(function()
local t = { one = 1, two = 2, three = 3, four = 4, five = 5 }
return Table.HasValue(t, 6)
end)
end)
end)
end)
describe("KeyByValue()", function()
describe("when the passed parameter is not a table", function()
TestReturnFalse(function()
return Table.KeyByValue("test")
end)
end)
describe("when the valid table and value passed", function()
it("should return the key", function()
local t = { one = 1, two = 2, three = 3, four = 4, five = 5 }
assert.is_equal("two", Table.KeyByValue(t, 2))
end)
end)
end)
describe("Merge()", function()
it("should return two combined simple tables", function()
local a = { a = "a", b = "b", c = "c" }
local b = { d = "d", e = "e", a = "f" }
assert.is_same({ a = "f", b = "b", c = "c", d = "d", e = "e" }, Table.Merge(a, b))
end)
it("should return two combined simple ipaired tables", function()
local a = { "a", "b", "c" }
local b = { "d", "e", "f" }
assert.is_same({ "a", "b", "c", "d", "e", "f" }, Table.Merge(a, b))
end)
end)
describe("NextValue()", function()
describe("when there is a next value", function()
it("should return the next value", function()
local t = { "a", "b", "c" }
assert.is_equal("c", Table.NextValue(t, "b"))
end)
end)
describe("when there is no next value", function()
it("should return the first value", function()
local t = { "a", "b", "c" }
assert.is_equal("a", Table.NextValue(t, "c"))
end)
end)
end)
describe("SortAlphabetically()", function()
describe("when the passed parameter is not a table", function()
TestReturnFalse(function()
return Table.SortAlphabetically("test")
end)
end)
describe("when both tables with nested ones are the same", function()
it("should return true", function()
local test = { "one", "two", "three", "four", "five" }
local expected = { "five", "four", "one", "three", "two" }
local result = Table.SortAlphabetically(test)
assert.is_equal(#expected, #result)
for k, v in pairs(result) do
assert.is_equal(expected[k], v)
end
end)
end)
end)
end)
|
local metadep = {}
function metadep.inject_num_assign(name, num)
inject_statement(aster.Assign{{aster.Id{name}}, {aster.Number{num}}})
end
return metadep
|
return {
summary = 'The base object.',
description = [[
This is not a real object, but describes the behavior shared by all objects. Think of it as the
superclass of all LÖVR objects.
In addition to the methods here, all objects have a `__tostring` metamethod that returns the
name of the object's type. So to check if a LÖVR object is an instance of "Blob", you can do
`tostring(object) == 'Blob'`.
]]
}
|
local gen_code = require 'Q/UTILS/lua/gen_code'
local plpath = require "pl.path"
local srcdir = "../gen_src/"
local incdir = "../gen_inc/"
if ( not plpath.isdir(srcdir) ) then plpath.mkdir(srcdir) end
if ( not plpath.isdir(incdir) ) then plpath.mkdir(incdir) end
local operator_file = assert(arg[1], "operator file not provided")
assert(plpath.isfile(operator_file))
local operators = dofile(operator_file)
local in1_qtypes = { 'I2', 'I4', 'I8', }
local num_produced = 0
for _, operator in ipairs(operators) do
print("Working on operator " .. operator)
local sp_fn_name = operator .. "_specialize"
local sp_fn = assert(require(sp_fn_name),
"specializer not found " .. sp_fn_name)
for i, in1_qtype in ipairs(in1_qtypes) do
local status, subs = pcall(
sp_fn, in1_qtype, optargs)
if ( status ) then
assert(type(subs) == "table")
-- for k, v in pairs(subs) do print(k, v) end
gen_code.doth(subs, incdir)
gen_code.dotc(subs, srcdir)
print("Produced ", subs.fn)
num_produced = num_produced + 1
else
print("error in specializer " .. subs)
end
end
end
assert(num_produced > 0)
print("Number of files Produced = ", num_produced)
|
-- This file is subject to copyright - contact swampservers@gmail.com for more information.
-- INSTALL: CINEMA
SWEP.PrintName = "Infinity Gauntlet"
SWEP.Instructions = "*snap*"
SWEP.Slot = 0
SWEP.SlotPos = 0
SWEP.DrawAmmo = true
SWEP.m_WeaponDeploySpeed = 9
SWEP.ViewModel = "models/swamp/v_infinitygauntlet.mdl"
SWEP.WorldModel = "models/swamp/v_infinitygauntlet.mdl"
SWEP.ViewModelFlip = false
--SWEP.ViewModelFOV = 60
SWEP.Spawnable = true
SWEP.Primary.ClipSize = 0
SWEP.Primary.DefaultClip = 1
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "infinitygauntlet"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.Instructions = "Hold left mouse button to snap. wait time is based on target's health."
SWEP.TargetCone = 15
--NOMINIFY
if (CLIENT) then
language.Add("infinitygauntlet_ammo", "Comedy Stones")
end
hook.Add("Initialize", "InfinityGauntletAmmo", function()
game.AddAmmoType({
name = "infinitygauntlet",
dmgtype = DMG_DISSOLVE,
})
end)
function SWEP:Initialize()
end
local meta = FindMetaTable("Player")
function meta:Fizzle(attacker, inflictor, damage)
if SERVER then
if (self:InVehicle()) then
self:ExitVehicle()
end
local dmginfo = DamageInfo()
dmginfo:SetDamage(damage or 200)
dmginfo:SetDamageType(DMG_DISSOLVE)
dmginfo:SetAttacker(attacker or game.GetWorld())
dmginfo:SetDamageForce(Vector(0, 0, 1))
dmginfo:SetInflictor(inflictor or game.GetWorld())
self:TakeDamageInfo(dmginfo)
end
end
function SWEP:Equip(ply)
end
function SWEP:EquipAmmo(ply)
end
function SWEP:Snap(target)
self:GetOwner():SetAnimation(PLAYER_ATTACK1)
if (SERVER) then
self:GetOwner():EmitSound("gauntlet/snap.wav", 100)
util.ScreenShake(self:GetOwner():GetPos(), 1, 2, 0.2, 300)
end
if (IsValid(target)) then
target:Fizzle(self:GetOwner(), self)
self:GetOwner():RemoveAmmo(1, "infinitygauntlet")
self:TimerSimple(0.5, function()
if (SERVER and self:Ammo1() <= 0) then
if IsValid(self) then
self:Remove()
end
end
end)
end
end
function SWEP:CanTarget(v)
if (not v:IsPlayer()) then return false end
if (not v:Alive()) then return false end
if (v == self:GetOwner()) then return false end
if (not self:GetTargetNearness(v)) then return false end
if v:IsProtected(self.Owner) then return false end
return true
end
function SWEP:GetTargetNearness(v)
local ply = self:GetOwner()
local mins, maxs = v:GetCollisionBounds()
local otherpos = v:LocalToWorld(v:OBBCenter())
local ofs = v:InVehicle() and Vector(0, 0, -maxs.z / 2) or Vector()
otherpos = otherpos + ofs
local a = ply:GetAimVector()
local b = (otherpos - ply:GetShootPos()):GetNormalized()
local dis = otherpos:Distance(ply:GetShootPos()) / 20
local cn = math.deg(math.acos(a:Dot(b)))
if (cn > self.TargetCone) then return end
if (dis * 20 > 1000) then return end --2000
return cn + dis
end
function SWEP:FindTarget()
local eyetrace = self.Owner:GetEyeTrace()
local target = {nil, 10000}
local ply = self:GetOwner()
local allply = Ents.player
local tracepos = ply:GetEyeTrace().HitPos
for k, v in pairs(allply) do
local mins, maxs = v:GetCollisionBounds()
local otherpos = v:LocalToWorld(v:OBBCenter())
local ofs = v:InVehicle() and Vector(0, 0, -maxs.z / 2) or Vector()
otherpos = otherpos + ofs
if (not self:CanTarget(v)) then continue end
local near = self:GetTargetNearness(v)
if (near and near < target[2]) then
local tr = util.TraceLine({
start = ply:GetShootPos(),
endpos = otherpos,
filter = {ply, v}
})
local tr2 = util.TraceLine({
start = ply:GetShootPos(),
endpos = v:EyePos() + ofs,
filter = {ply, v}
})
local wmins, wmaxs = mins + v:GetPos() + ofs, maxs + v:GetPos() + ofs
if (tr.Hit and tr.HitPos:WithinAABox(wmins, wmaxs)) then
tr.Hit = false
end
if (tr2.Hit and tr2.HitPos:WithinAABox(wmins, wmaxs)) then
tr2.Hit = false
end
if (not tr.Hit or not tr2.Hit) then
target = {v, near}
end
end
end
if (target[1]) then return target[1] end
end
hook.Add("PreDrawHalos", "InfinityGauntletHalo", function()
if (LocalPlayer():UsingWeapon("weapon_gauntlet")) then
local wep = LocalPlayer():GetWeapon("weapon_gauntlet")
local ply = wep:FindTarget()
if (IsValid(ply)) then
local tb = {ply}
if (ply.GetActiveWeapon and IsValid(ply:GetActiveWeapon())) then
tb[2] = ply:GetActiveWeapon()
end
halo.Add(tb, Color(128, 0, 255), 2, 2, 2, true, true)
end
end
end)
function SWEP:CanPrimaryAttack()
return self:GetOwner():GetAmmoCount("infinitygauntlet") > 0
end
if (SERVER) then end
function SWEP:PrimaryAttack()
local target = self:FindTarget()
if (not self:CanPrimaryAttack()) then return end
if (SERVER) then
SuppressHostEvents(self:GetOwner())
end
if (IsValid(target)) then
self:Snap(target)
self:SetNextPrimaryFire(CurTime() + 0.5)
else
--running this every tick on failure is pretty stupid, sorry
self:SetNextPrimaryFire(CurTime() + 0.15)
end
if (SERVER) then
SuppressHostEvents()
end
end
function SWEP:SecondaryAttack()
end
function SWEP:Reload()
end
function SWEP:Deploy()
self:SetHoldType("fist")
end
function SWEP:CreateWorldModel()
if not IsValid(self.WModel) then
self.WModel = ClientsideModel(self.WorldModel, RENDERGROUP_OPAQUE)
self.WModel:SetNoDraw(true)
self.WModel:SetBodygroup(1, 1)
end
return self.WModel
end
function SWEP:DrawWorldModel()
if (not IsValid(self:GetOwner())) then
local pos = self:GetPos()
local ang = Angle(0, 0, 0)
self.Spin = self.Spin or math.Rand(0, 360)
ang:RotateAroundAxis(Vector(0, 0, 1), self.Spin + CurTime() * 90)
ang:RotateAroundAxis(ang:Right(), 15)
ang:RotateAroundAxis(ang:Forward(), 15)
pos = pos + ang:Right() * 12
pos = pos + ang:Forward() * -24
pos = pos + Vector(0, 0, math.sin(CurTime() * 2) * 2)
local wm = self:CreateWorldModel()
wm:SetModelScale(3.5)
wm:SetRenderOrigin(pos)
wm:SetRenderAngles(ang)
wm:DrawModel()
return
end
local wm = self:CreateWorldModel()
local bone = self.Owner:LookupBone("ValveBiped.Bip01_L_Hand") or 0
local opos = self:GetPos()
local oang = self:GetAngles()
local bp, ba = self.Owner:GetBonePosition(bone)
if (bp) then
opos = bp
end
if (ba) then
oang = ba
end
wm:SetModelScale(3.5)
opos = opos + oang:Right() * -18
opos = opos + oang:Forward() * -19
opos = opos + oang:Up() * 3.5
oang:RotateAroundAxis(oang:Right(), 210)
oang:RotateAroundAxis(oang:Forward(), -50)
oang:RotateAroundAxis(oang:Up(), 210)
wm:SetRenderOrigin(opos)
wm:SetRenderAngles(oang)
wm:DrawModel()
end
function SWEP:OnRemove()
if self.WModel then
self.WModel:Remove()
end
end
|
object_tangible_quest_menagerie_terminal_08 = object_tangible_quest_shared_menagerie_terminal_08:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_menagerie_terminal_08, "object/tangible/quest/menagerie_terminal_08.iff")
|
kSYN_PAUSE = 0b1
kSYN_RUN = 0b10
kSYN_WIN = 0b100
kSYN_END = 0b1000
function synch_init()
current = 0
beamline_origin = vec(-8,80)
synch_beamline = make_beamline(beamline_origin)
synch_beamline:set_elements("_____C_____M_____M_____M_____M_____M_____M_____M_____M_____M_____M_____M_____M_____C_____________")
bunch_width = 0
bunch_length = 0
bunch_emittance = 0
bunch_mean_pos = vec()
initial_kick_x = 40
initial_emittance = 0.1
bunch_v = initial_kick_x * FSPEED
synch_turn = 1
synch_nprotons = 150
synch_protons = make_particle_list()
synch_protons:add_parts(generate_particles(vec(5,80),synch_nprotons, 5, true, kRED))
synch_protons:update(function(p)
p:kick(vec(initial_kick_x, rnd(2 * initial_kick_x * initial_emittance) - (initial_kick_x * initial_emittance)))
p:update(0)
bunch_mean_pos = vadd(bunch_mean_pos, p.pos)
bunch_width += abs(p.pos.y - beamline_origin.y)
bunch_length += abs(p.pos.x - 5)
bunch_emittance += abs(p.dpdt.y)
end)
bunch_width /= synch_protons:num()
bunch_length /= synch_protons:num()
bunch_emittance /= synch_protons:num()
bunch_mean_pos = vscale(1/synch_protons:num(),bunch_mean_pos)
last_bunch_mean_pos = vcopy(bunch_mean_pos)
player_proton = make_particle(vec(5,80), nil, kSPR_PROTON_R)
player_proton:kick(vec(initial_kick_x,rnd(2 * initial_kick_x * initial_emittance) - (initial_kick_x * initial_emittance)))
player_proton:update(0)
player_proton:update(0)
SYN_STATE=kSYN_RUN
GAME_STATES[STATE][2] = false
end
function synch_update()
if (btnp(4)) synch_init()
if(SYN_STATE&kSYN_RUN == kSYN_RUN) then
read_input()
--Shift everything back, to do another turn
local beamline_turn_length = synch_beamline:last_magnet().x + 20
if((synch_turn < 10) and (player_proton.pos.x > beamline_turn_length)) then
player_proton.pos.x -= synch_beamline:last_magnet().x + 16
synch_protons:update(function(p)
p.pos.x -= synch_beamline:last_magnet().x + 16
end)
synch_turn += 1
end
if (btnp(1)) SYN_STATE = SYN_STATE^^kSYN_PAUSE
printh("state: "..SYN_STATE)
if (SYN_STATE&kSYN_PAUSE != kSYN_PAUSE) then
local bf = synch_beamline:bfield(player_proton.pos)
local x_kick = 0
if((player_proton.pos.x < 52) and (player_proton:next_pos(FSPEED).x > 52)) then
x_kick = 20
end
player_proton:kick(vec(x_kick, - player_proton.dpdt.x * bf))
player_proton:update(FSPEED)
bunch_width = 0
bunch_length = 0
bunch_emittance = 0
bunch_mean_pos = vec()
synch_protons:update(function(p)
local bf = synch_beamline:bfield(p.pos)
bunch_width += abs(p.pos.y - beamline_origin.y)
bunch_length += abs(p.pos.x - last_bunch_mean_pos.x)
bunch_emittance += abs(p.dpdt.y)
local x_kick = 0
if((p.pos.x < 52) and (p:next_pos(FSPEED).x > 52)) then
x_kick = 20
end
p:kick(vec(x_kick, - p.dpdt.x * bf))
-- p:kick(vscale(0.01 / vmag2(vatob(p.pos,last_bunch_mean_pos)),
-- vec(sign(p.pos.x -last_bunch_mean_pos.x),
-- sign(p.pos.y -last_bunch_mean_pos.y))))
p:update(FSPEED)
bunch_mean_pos = vadd(bunch_mean_pos, p.pos)
end)
bunch_width /= synch_protons:num()
bunch_length /= synch_protons:num()
bunch_emittance /= synch_protons:num()
bunch_mean_pos = vscale(1/synch_protons:num(),bunch_mean_pos)
bunch_v = (bunch_mean_pos.x - last_bunch_mean_pos.x) * FSPEED
last_bunch_mean_pos = vcopy(bunch_mean_pos)
end
if(abs(player_proton.pos.y - beamline_origin.y) >= 16) then
SYN_STATE = kSYN_END
end
if(player_proton.pos.x > (synch_beamline:last_magnet().x + 64)) then
SYN_STATE = kSYN_WIN
end
synch_protons:remove_if(function(p) return (abs(p.pos.y - beamline_origin.y) >= 18) end)
end
camera(player_proton.pos.x - 16, 0)
end
function synch_draw()
if(SYN_STATE==kSYN_END) then
print("BEAM LOSS!", 0,24)
return
end
if(SYN_STATE==kSYN_WIN) then
cls()
print("Success!", 12, 64, kGREEN)
show_debug()
return
end
cls() --clear screen
synch_beamline:draw_pipe()
synch_protons:draw()
player_proton:spr(player_proton.spr_id, kDBLUE)
synch_beamline:draw_elements()
--lets just show the focussing forces
player_proton.last_impulse.x = 0
draw_impulse_arrow(player_proton, 5, kYELLOW)
local testp = make_moveable(player_proton.pos)
testp.dpdt = vcopy(player_proton.dpdt)
if(SYN_STATE&kSYN_PAUSE == kSYN_PAUSE) then
for Tf = 0, 200 do
testp:update(FSPEED/2)
local bf = synch_beamline:bfield(testp.pos)
testp:kick(vec(0, - testp.dpdt.x * bf))
testp:pset(kGREEN)
if(abs(testp.pos.y - beamline_origin.y) >= 18) then
break
end
if((testp.pos.x - player_proton.pos.x) > 100) then
break
end
end
end
if(DEBUG_LEVEL > 0) then
show_debug()
end
-- draw_grid()
end
function read_input()
local delta = 0.1
local magdelta = 0
if (btnp(2)) magdelta += delta --up
if (btnp(3)) magdelta -= delta --down
current = clamp(current + magdelta,-5,5)
synch_beamline:set_current(current)
end
function show_debug()
vpprint("\131/\148: change focussing current",0,117,kSLATE)
-- vpprint("restart: \142",0,32,kGREEN)
vpprint("\145: toggle time \142: restart",0,123,kSLATE)
vpprint("beam loss: "..flr(100*(synch_nprotons - synch_protons:num())/(1 + synch_nprotons)).."%",
0,8, kGREEN)
vpprint("foc.cur.: "..current,0,16,kGREEN)
vpprint("bch width: "..(flr(bunch_width*10)/10), 68, 8, kGREEN)
vpprint("bch length: "..(flr(bunch_length*10)/10), 68, 16, kGREEN)
vpprint("bch emit: "..(flr(bunch_emittance*10)/10),68,24,kGREEN)
vpprint("bch vx: "..(flr(bunch_v*10)/10),68,32,kGREEN)
vpprint("pv: "..v2s(player_proton.dpdt), 0,40)
vpprint("turn: "..synch_turn, 0,24)
end
|
buffer = Procedural.TextureBuffer(128)
Procedural.Cell(buffer):setDensity(4):setRegularity(234):process()
Procedural.Threshold(buffer):process()
tests:addTextureBuffer(buffer)
dotfile = tests:getDotFile("texture_28", "Threshold_Demo")
dotfile:set("Cell", "texture_cell_smooth", "Threshold", "texture_threshold")
|
-- connect all the libs
Pow=require "shared.lib.powlov.pow"
Img=require "shared.res.img"
Flux=Pow.flux
Entity=Pow.entity
BaseEntity=Pow.baseEntity
-- shortcuts
Debug=Pow.debug
log=Pow.debug.log
draw=love.graphics.draw
Inspect=Pow.inspect
serialize=Pow.pack
deserialize=Pow.unpack
_str=serialize
_obj=deserialize
_ets=Entity.toString
_ref=Entity.get_reference
_rnd=love.math.random
_frm=Pow.get_frame
-- resolve entity from reference dto
-- defined for client and server separatedly
_deref=nil
-- number default representation
_n=function(number)
if number==nil then return "nil" end
return string.format("%0.2f", number)
end
-- easy way to print coords
_xy=function(x,y)
return _n(x)..",".._n(y)
end
nop=function()
end
_strc=function(s)
local result=_str(s)
result=Pow.allen.substitute("\n","")
result=Pow.allen.substitute("\\n","")
result=Pow.allen.substitute("\9","")
result=Pow.allen.substitute("\\9","")
-- todo: replace \n \9
return result
end
|
require('rollisch.nvim-web-devicons')
require('rollisch.indent_blankline')
require('rollisch.treesitter')
require('rollisch.telescope')
require('rollisch.completion')
require('rollisch.lsp')
|
local K, C = unpack(select(2, ...))
local Module = K:NewModule("Minimap", "AceHook-3.0", "AceEvent-3.0", "AceTimer-3.0")
local _G = _G
local string_sub = string.sub
local C_Timer_After = _G.C_Timer.After
local CreateFrame = _G.CreateFrame
local GameTimeFrame = _G.GameTimeFrame
local GarrisonLandingPageMinimapButton = _G.GarrisonLandingPageMinimapButton
local GetMinimapZoneText = _G.GetMinimapZoneText
local GetZonePVPInfo = _G.GetZonePVPInfo
local GuildInstanceDifficulty = _G.GuildInstanceDifficulty
local hooksecurefunc = _G.hooksecurefunc
local InCombatLockdown = _G.InCombatLockdown
local Minimap = _G.Minimap
local MiniMapChallengeMode = _G.MiniMapChallengeMode
local MiniMapInstanceDifficulty = _G.MiniMapInstanceDifficulty
local MiniMapMailFrame = _G.MiniMapMailFrame
local QueueStatusMinimapButton = _G.QueueStatusMinimapButton
local UIParent = _G.UIParent
function Module:GetLocationTextColors()
local pvpType = GetZonePVPInfo()
if pvpType == "arena" then
return 0.84, 0.03, 0.03
elseif pvpType == "friendly" then
return 0.05, 0.85, 0.03
elseif pvpType == "contested" then
return 0.9, 0.85, 0.05
elseif pvpType == "hostile" then
return 0.84, 0.03, 0.03
elseif pvpType == "sanctuary" then
return 0.035, 0.58, 0.84
elseif pvpType == "combat" then
return 0.84, 0.03, 0.03
else
return 0.9, 0.85, 0.05
end
end
function Module:OnMouseWheelScroll(d)
if d > 0 then
_G.MinimapZoomIn:Click()
elseif d < 0 then
_G.MinimapZoomOut:Click()
end
end
function Module:ZoneTextUpdate()
if not C["Minimap"].Enable then
return
end
Minimap.Location:SetText(string_sub(GetMinimapZoneText(), 1, 46))
Minimap.Location:SetTextColor(Module:GetLocationTextColors())
Minimap.Location:FontTemplate(nil, 13)
end
local function PositionTicketButtons()
HelpOpenTicketButton:ClearAllPoints()
HelpOpenTicketButton:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", 0, 0)
HelpOpenWebTicketButton:ClearAllPoints()
HelpOpenWebTicketButton:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", 0, 0)
end
local isResetting
local function ResetZoom()
Minimap:SetZoom(0)
MinimapZoomIn:Enable() -- Reset enabled state of buttons
MinimapZoomOut:Disable()
isResetting = false
end
local function SetupZoomReset()
if C["Minimap"].ResetZoom and not isResetting then
isResetting = true
C_Timer_After(C["Minimap"].ResetZoomTime, ResetZoom)
end
end
hooksecurefunc(Minimap, "SetZoom", SetupZoomReset)
function Module:UpdateSettings()
if InCombatLockdown() then
return self:RegisterEvent("PLAYER_REGEN_ENABLED", "OnEvent")
end
local SetMinimapSize = C["Minimap"].Enable and C["Minimap"].Size or 170
if C["Minimap"].Enable then
Minimap:SetSize(SetMinimapSize, SetMinimapSize)
end
local MinimapFrameHolder = _G.MinimapFrameHolder
if MinimapFrameHolder then
MinimapFrameHolder:SetWidth(Minimap:GetWidth())
end
if Minimap.Location then
Minimap.Location:SetWidth(SetMinimapSize)
Minimap.Location:Hide()
end
-- Stop here if KkthnxUI Minimap is disabled.
if not C["Minimap"].Enable then
return
end
if GarrisonLandingPageMinimapButton then
if not C["Minimap"].GarrisonLandingPage then
-- ugly hack to keep the keybind functioning
GarrisonLandingPageMinimapButton:SetParent(K.UIFrameHider)
GarrisonLandingPageMinimapButton:UnregisterAllEvents()
GarrisonLandingPageMinimapButton:Show()
GarrisonLandingPageMinimapButton.Hide = GarrisonLandingPageMinimapButton.Show
else
GarrisonLandingPageMinimapButton:ClearAllPoints()
GarrisonLandingPageMinimapButton:SetPoint("BOTTOMLEFT", Minimap, "BOTTOMLEFT", 0, 0)
GarrisonLandingPageMinimapButton:SetScale(0.8)
if GarrisonLandingPageTutorialBox then
GarrisonLandingPageTutorialBox:SetScale(0.8)
GarrisonLandingPageTutorialBox:SetClampedToScreen(true)
end
end
end
if GameTimeFrame then
if not C["Minimap"].Calendar then
GameTimeFrame:Hide()
else
GameTimeFrame:SetParent(Minimap)
GameTimeFrame:SetScale(0.6)
GameTimeFrame:ClearAllPoints()
GameTimeFrame:SetPoint("TOPRIGHT", Minimap, "TOPRIGHT", -3, -3)
GameTimeFrame:SetHitRectInsets(0, 0, 0, 0)
GameTimeFrame:GetNormalTexture():SetTexCoord(0, 1, 0, 1)
GameTimeFrame:SetNormalTexture("Interface\\Addons\\KkthnxUI\\Media\\Textures\\Calendar.blp")
GameTimeFrame:SetPushedTexture(nil)
GameTimeFrame:SetHighlightTexture(nil)
local GameTimeFont = GameTimeFrame:GetFontString()
GameTimeFont:ClearAllPoints()
GameTimeFont:SetPoint("CENTER", 0, -6)
GameTimeFont:SetFontObject("KkthnxUIFont")
GameTimeFont:SetFont(select(1, GameTimeFont:GetFont()), 20, select(3, GameTimeFont:GetFont()))
GameTimeFont:SetShadowOffset(0, 0)
end
end
if MiniMapMailFrame then
MiniMapMailFrame:ClearAllPoints()
MiniMapMailFrame:SetPoint("BOTTOM", Minimap, "BOTTOM", 0, 4)
MiniMapMailFrame:SetScale(1.2)
end
if QueueStatusMinimapButton then
QueueStatusMinimapButton:ClearAllPoints()
QueueStatusMinimapButton:SetPoint("BOTTOMRIGHT", Minimap, "BOTTOMRIGHT", 2, -2)
end
if MiniMapInstanceDifficulty and GuildInstanceDifficulty then
MiniMapInstanceDifficulty:ClearAllPoints()
MiniMapInstanceDifficulty:SetPoint("TOPLEFT", Minimap, "TOPLEFT", 0, 0)
MiniMapInstanceDifficulty:SetScale(0.9)
GuildInstanceDifficulty:ClearAllPoints()
GuildInstanceDifficulty:SetPoint("TOPLEFT", Minimap, "TOPLEFT", 0, 0)
GuildInstanceDifficulty:SetScale(0.9)
end
if MiniMapChallengeMode then
MiniMapChallengeMode:ClearAllPoints()
MiniMapChallengeMode:SetPoint("TOPLEFT", Minimap, "TOPLEFT", 8, -8)
end
if StreamingIcon then
StreamingIcon:ClearAllPoints()
StreamingIcon:SetPoint("BOTTOM", Minimap, "BOTTOM", 0, -10)
StreamingIcon:SetScale(0.9)
StreamingIcon:SetFrameStrata("BACKGROUND")
end
if HelpOpenTicketButton and HelpOpenWebTicketButton then
PositionTicketButtons()
end
end
function Module:ADDON_LOADED(_, addon)
if addon == "Blizzard_TimeManager" then
TimeManagerClockButton:Kill()
elseif addon == "Blizzard_FeedbackUI" then
FeedbackUIButton:Kill()
end
end
function Module:OnEvent(event)
if event == "PLAYER_ENTERING_WORLD" then
self:ZoneTextUpdate()
elseif event == "PLAYER_REGEN_ENABLED" then
self:UpdateSettings()
end
end
function Module:WhoPingsMyMap()
local f = CreateFrame("Frame", nil, Minimap)
f:SetAllPoints()
f.text = f:CreateFontString(nil, "OVERLAY")
f.text:FontTemplate(nil, 13)
f.text:SetPoint("TOP", f, "TOP", 0, -20)
local anim = f:CreateAnimationGroup()
anim:SetScript("OnPlay", function() f:SetAlpha(1) end)
anim:SetScript("OnFinished", function() f:SetAlpha(0) end)
anim.fader = anim:CreateAnimation("Alpha")
anim.fader:SetFromAlpha(1)
anim.fader:SetToAlpha(0)
anim.fader:SetDuration(3)
anim.fader:SetSmoothing("OUT")
anim.fader:SetStartDelay(3)
K:RegisterEvent("MINIMAP_PING", function(_, unit)
local class = select(2, UnitClass(unit))
local r, g, b = K.ColorClass(class)
local name = GetUnitName(unit)
anim:Stop()
f.text:SetText(name)
f.text:SetTextColor(r, g, b)
anim:Play()
end)
end
function Module:OnEnable()
self:UpdateSettings()
if not C["Minimap"].Enable then
Minimap:SetMaskTexture(186178)
Minimap:SetBlipTexture("Interface\\MiniMap\\ObjectIconsAtlas")
return
end
local UIHider = K.UIFrameHider
-- Support for other mods
function GetMinimapShape()
return "SQUARE"
end
local MinimapFrameHolder = CreateFrame("Frame", "MinimapFrameHolder", Minimap)
MinimapFrameHolder:SetPoint("TOPRIGHT", UIParent, "TOPRIGHT", -4, -4)
MinimapFrameHolder:SetWidth(Minimap:GetWidth())
MinimapFrameHolder:SetHeight(Minimap:GetHeight())
Minimap:ClearAllPoints()
Minimap:SetPoint("CENTER", MinimapFrameHolder, "CENTER", 0, 0)
Minimap:SetMaskTexture(C["Media"].Blank)
Minimap:SetQuestBlobRingAlpha(0)
Minimap:SetArchBlobRingAlpha(0)
Minimap:CreateBorder()
Minimap:CreateInnerShadow(nil, 0.4)
Minimap:SetScale(1.0)
Minimap:SetBlipTexture("Interface\\AddOns\\KkthnxUI\\Media\\MiniMap\\Blip-Nandini-New")
Minimap:HookScript("OnEnter", function(self)
if K.PerformanceFrame then
K.PerformanceFrame:Hide()
end
self.Location:Show()
end)
Minimap:HookScript("OnLeave", function(self)
if K.PerformanceFrame then
K.PerformanceFrame:Show()
end
self.Location:Hide()
end)
Minimap.Location = Minimap:CreateFontString(nil, "OVERLAY")
Minimap.Location:SetWidth(C["Minimap"].Size)
Minimap.Location:FontTemplate(nil, 13)
Minimap.Location:SetPoint("TOP", 0, -4)
Minimap.Location:SetJustifyH("CENTER")
Minimap.Location:SetJustifyV("MIDDLE")
Minimap.Location:Hide()
-- New dungeon finder eye in MoP
QueueStatusMinimapButton:SetHighlightTexture("")
if QueueStatusMinimapButton.Highlight then -- bugged out in MoP
QueueStatusMinimapButton.Highlight:SetTexture(nil)
QueueStatusMinimapButton.Highlight:SetAlpha(0)
end
_G.MinimapBorder:SetParent(UIHider)
_G.MinimapBorderTop:SetParent(UIHider)
_G.MiniMapMailBorder:SetParent(UIHider)
_G.MinimapNorthTag:SetParent(UIHider)
_G.MiniMapTracking:SetParent(UIHider)
_G.MiniMapTrackingButton:SetParent(UIHider)
_G.MinimapZoneTextButton:SetParent(UIHider)
_G.MinimapZoomIn:SetParent(UIHider)
_G.MinimapZoomOut:SetParent(UIHider)
_G.MiniMapMailIcon:SetTexture("Interface\\Addons\\KkthnxUI\\Media\\Textures\\Mail")
-- Hide the BlopRing on Minimap
MinimapCluster:EnableMouse(false)
Minimap:SetArchBlobRingScalar(0)
Minimap:SetQuestBlobRingScalar(0)
if QueueStatusMinimapButtonBorder then
QueueStatusMinimapButtonBorder:SetTexture(nil)
QueueStatusMinimapButtonBorder:SetAlpha(0)
end
_G.MiniMapWorldMapButton:SetParent(K.UIFrameHider)
MiniMapInstanceDifficulty:SetParent(Minimap)
GuildInstanceDifficulty:SetParent(Minimap)
MiniMapChallengeMode:SetParent(Minimap)
if TimeManagerClockButton then
TimeManagerClockButton:Kill()
end
if FeedbackUIButton then
FeedbackUIButton:Kill()
end
K.Mover(MinimapFrameHolder, "Minimap", "Minimap", {"TOPRIGHT", UIParent, "TOPRIGHT", -4, -4}, Minimap:GetWidth(), Minimap:GetHeight())
Minimap:EnableMouseWheel(true)
Minimap:SetScript("OnMouseWheel", Module.OnMouseWheelScroll)
self:RegisterEvent("PLAYER_ENTERING_WORLD", "OnEvent")
self:RegisterEvent("ZONE_CHANGED_NEW_AREA", "ZoneTextUpdate")
self:RegisterEvent("ZONE_CHANGED", "ZoneTextUpdate")
self:RegisterEvent("ZONE_CHANGED_INDOORS", "ZoneTextUpdate")
self:RegisterEvent("ADDON_LOADED")
self:UpdateSettings()
self:WhoPingsMyMap()
end
|
local M = {}
--- Gets a copy of the config that would be used by lspconfig. Without side effects.
--@returns a fresh config
function M.extract_config(name)
-- needed so we can restore the initial state at the end
local was_config_set = require("lspconfig/configs")[name]
local was_package_loaded = package.loaded["lspconfig/" .. name]
-- gets or requires config
local config = require("lspconfig")[name].document_config
-- restore the initial state
if not was_config_set then
require("lspconfig/configs")[name] = nil
end
if not was_package_loaded then
package.loaded["lspconfig/" .. name] = nil
end
return vim.deepcopy(config)
end
--- Prints message with warning highlights
function M.print_warning(msg)
vim.api.nvim_echo({ { msg, "WarningMsg" } }, true, {})
end
--- Gets lsp server install directory
--@returns string
function M.install_path(lang)
return vim.fn.stdpath "data" .. "/lsp/" .. lang
end
--- Check if on Windows or not
--@returns true if it is windows os, false otherwise
function M.is_windows()
if vim.fn.has "win32" == 1 then
return true
end
return false
end
--- Combine commands to single string
--@return string
function M.concat(t, autoseparate)
local separator = " "
if autoseparate == true then
if M.is_windows() then
separator = " &"
else
separator = "; "
end
end
return table.concat(t, separator)
end
--- Sets the shell to be used as bash, if not on windows
-- or OS is linux/mac, cmd.exe if on windows while executing the command
function M.do_term_open(terminal_task, term_options)
vim.cmd "new"
local shell = vim.o.shell
local shellcmdflag = vim.o.shellcmdflag
local shellquote = vim.o.shellquote
local shellxquote = vim.o.shellxquote
if M.is_windows() == false then
vim.o.shell = "/bin/bash"
else
vim.o.shell = "powershell.exe"
vim.o.shellcmdflag = "-NoProfile -c"
vim.o.shellquote = '\\"'
vim.o.shellxquote = ""
end
if M.is_windows() == true then
vim.fn.termopen([[$ErrorActionPreference = "Stop"
]] .. terminal_task, term_options)
else
vim.fn.termopen("set -e\n" .. terminal_task, term_options)
end
vim.o.shell = shell
vim.o.shellcmdflag = shellcmdflag
vim.o.shellquote = shellquote
vim.o.shellxquote = shellxquote
vim.cmd "startinsert"
end
return M
|
--[[
Modified (@fondlez):
- added: A.requires() for namespace with multiple modules. Order matters.
- changed: made safe and flexible by becoming addon-scoped.
- changed: fully commented for future clarity.
Original credit: @shirsig, author of "aux-addon"
--]]
-- Customize for every addon by re-assigning the addon global to the local "A".
local A = FonzAppraiser
-- Global imports.
local _G, setfenv, setmetatable = getfenv(0), setfenv, setmetatable
-- Dictionaries.
local environments, interfaces = {}, {}
-- Null function
local function pass() end
-- Creates a metatable that indexes the global environment.
local environment_mt = {__index=_G}
local function create_module(name)
-- Creates an "environment" table with shortcuts to the global environment
-- and a null function. Queries will search the global environment.
local environment = setmetatable({_G=_G, pass=pass}, environment_mt)
local exports = {}
-- Creates a module interface, "M", as a write-only sub-table where
-- key-value updates write to the parent table and an exports table.
environment.M = setmetatable({}, {
__metatable=false,
__newindex=function(_, k, v)
environment[k], exports[k] = v, v
end,
})
-- Adds an internal shortcut to the parent table (similar to '_G' for global).
environment._M = environment
-- Names and inserts the "environment" to a dictionary of environments.
environments[name] = environment
-- Names and inserts an "interface" - a read-only table where queries will
-- search the exports table - to a dictionary of interfaces.
interfaces[name] = setmetatable({}, {__metatable=false, __index=exports,
__newindex=pass})
end
function A.module(name)
-- Creates a named module if not already present, where a module is actually
-- a table from a dictionary and containing a special key called "M"
-- for updates.
local defined = not not environments[name]
if not defined then
create_module(name)
end
-- Sets the named module's table as the caller's environment.
-- Note. 0 = global, 1 = current function, 2 = caller.
setfenv(2, environments[name])
-- Returns whether the module was already defined.
return defined
end
function A.require(name)
-- Creates a named module if not already present.
if not interfaces[name] then
create_module(name)
end
-- Returns the interface of a named module.
return interfaces[name]
end
function A.requires(...)
-- Checks that all arguments already exist as a named interface.
-- Creating new modules is not permitted through this function.
for _, name in ipairs(arg) do
if not interfaces[name] then return end
end
-- Creates a read-only metatable that searches for a key across all the
-- named input interfaces.
-- Returns the first value found. Therefore, the order of the named inputs
-- matters.
local aggregate_mt = {
__metatable=false,
__newindex=pass,
__index=function(_, key)
for _, name in ipairs(arg) do
local value = interfaces[name][key]
if value ~= nil then return value end --nil check intentional
end
end
}
-- Returns a searchable table as a "namespace" across named interfaces.
return setmetatable({}, aggregate_mt)
end
|
T.xcode4_workspace = { }
local suite = T.xcode4_workspace
--[[suite.--]]local CONSTANT_PROJECT_NAME = "MyProject"
local sln, prj
function suite.teardown()
sln = nil
prj = nil
end
function suite.setup()
_ACTION = "xcode4"
sln = solution "MySolution"
configurations { "Debug", "Release" }
platforms {}
prj = project (CONSTANT_PROJECT_NAME) --"MyProject"
language "C++"
kind "ConsoleApp"
uuid "AE61726D-187C-E440-BD07-2556188A6565"
end
local function get_buffer()
premake.bake.buildconfigs()
premake.xcode.workspace_generate(sln)
local buffer = io.endcapture()
return buffer
end
function suite.xmlDeclarationPresent()
local buffer = get_buffer()
test.string_contains(buffer, '<%?xml version="1%.0" encoding="UTF%-8"%?>')
end
function suite.workspace_detailsEnclosedByVersionOneWorkSpaceTag()
local buffer = get_buffer()
test.string_contains(buffer,'<Workspace%s+version = "1%.0">.*</Workspace>')
end
function suite.workspace_addsProjectInFileRefTags()
local buffer = get_buffer()
test.string_contains(buffer,'<Workspace%s+version = "1%.0">%s+<FileRef.*</FileRef>%s+</Workspace>')
end
function suite.workspace_fileRefFormat_locationAndGroup()
local buffer = get_buffer()
test.string_contains(buffer,'.*<FileRef%s+location = "group:.*">%s+</FileRef>')
end
function suite.workspace_fileRefFormat_projectNameAndExtension()
local buffer = get_buffer()
test.string_contains(buffer,'.*<FileRef%s+location = "group:'
.. CONSTANT_PROJECT_NAME .. '.xcodeproj'
..'">%s+</FileRef>')
end
function suite.pathPrefixAndProjectName_pathIsSameDir_noPrefixAdded()
local buffer = get_buffer()
test.string_contains(buffer,'.*<FileRef%s+location = "group:'
.. CONSTANT_PROJECT_NAME .. '.xcodeproj'
..'">%s+</FileRef>')
end
function suite.pathPrefixAndProjectName_pathIsPathIsDifferentDir_pathPostfixSlashAdded()
prj.location = "foo"
local buffer = get_buffer()
test.string_contains(buffer,'.*<FileRef%s+location = "group:'
.. prj.location .. '/'.. CONSTANT_PROJECT_NAME .. '.xcodeproj'
..'">%s+</FileRef>')
end
|
return {
tllach = {
acceleration = 0.045,
brakerate = 0.24,
buildcostenergy = 10802,
buildcostmetal = 704,
builddistance = 180,
builder = true,
buildpic = "tllach.dds",
buildtime = 25000,
canguard = true,
canhover = true,
canmove = true,
canpatrol = true,
canreclamate = 1,
canstop = 1,
category = "ALL MEDIUM MOBILE SURFACE UNDERWATER",
corpse = "dead",
defaultmissiontype = "Standby",
description = "Tech Level 2",
downloadable = 1,
energymake = 10,
energystorage = 10,
energyuse = 1,
explodeas = "BIG_UNITEX",
footprintx = 3,
footprintz = 3,
idleautoheal = 5,
idletime = 1800,
losemitheight = 22,
maneuverleashlength = 640,
mass = 704,
maxdamage = 1191,
maxslope = 16,
maxvelocity = 1.8,
maxwaterdepth = 0,
metalmake = 0.3,
metalstorage = 30,
mobilestandorders = 1,
movementclass = "HOVER3",
name = "Construction Hovercraft",
noautofire = false,
objectname = "tllach",
radaremitheight = 25,
reclaimspeed = 100,
repairspeed = 100,
script = "tllchover.cob",
selfdestructas = "BIG_UNIT",
shownanospray = false,
sightdistance = 310,
standingmoveorder = 1,
steeringmode = 1,
turninplace = 0,
turninplaceanglelimit = 140,
turninplacespeedlimit = 1.3992,
turnrate = 400,
unitname = "tllach",
workertime = 200,
buildoptions = {
[1] = "tllmedfusion",
[2] = "tllcoldfus",
[3] = "tllmohogeo",
[4] = "tllgeo_armored",
[5] = "tllamex",
[6] = "tllammaker",
[7] = "tllemstor",
[8] = "tllhp",
[9] = "tllahp",
[10] = "tllevp",
[11] = "tllnanotc1",
[12] = "tllrichter",
[13] = "tlltarg",
[14] = "tllgate",
[15] = "tllemp",
[16] = "tllantinuke",
[17] = "tllsilo",
[18] = "tlllrpt",
[19] = "tlllrpt",
[20] = "tllhydre",
[21] = "tlluwfusion",
--[22] = "",
[23] = "tllwmmohoconv",
[24] = "tllhpns",
[25] = "tllahpns",
[26] = "tllsy",
[27] = "tllasy",
[28] = "tllesy",
[29] = "tllfnanotc1",
[30] = "tllfgate",
},
customparams = {
buildpic = "tllach.dds",
faction = "TLL",
},
featuredefs = {
dead = {
blocking = true,
damage = 926,
description = "Construction Hovercraft Wreckage",
featuredead = "heap",
footprintx = 3,
footprintz = 3,
metal = 157,
object = "tllach_dead",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
heap = {
blocking = false,
damage = 1157,
description = "Construction Hovercraft Debris",
footprintx = 3,
footprintz = 3,
metal = 84,
object = "3x3a",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
},
nanocolor = {
[1] = 0.482,
[2] = 0.482,
[3] = 0.132,
},
sfxtypes = {
pieceexplosiongenerators = {
[1] = "piecetrail0",
[2] = "piecetrail1",
[3] = "piecetrail2",
[4] = "piecetrail3",
[5] = "piecetrail4",
[6] = "piecetrail6",
},
},
sounds = {
build = "nanlath1",
canceldestruct = "cancel2",
repair = "repair1",
underattack = "warning1",
working = "reclaim1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "hovmdok2",
},
select = {
[1] = "hovmdsl2",
},
},
},
}
|
require 'cunn'
local iproc = require 'iproc'
local gm = {}
gm.Image = require 'graphicsmagick.Image'
local data_augmentation = require 'data_augmentation'
local pairwise_transform_utils = {}
function pairwise_transform_utils.random_half(src, p, filters)
if torch.uniform() < p then
local filter = filters[torch.random(1, #filters)]
return iproc.scale(src, src:size(3) * 0.5, src:size(2) * 0.5, filter)
else
return src
end
end
function pairwise_transform_utils.crop_if_large(src, max_size, mod)
local tries = 4
if src:size(2) > max_size and src:size(3) > max_size then
assert(max_size % 4 == 0)
local rect
for i = 1, tries do
local yi = torch.random(0, src:size(2) - max_size)
local xi = torch.random(0, src:size(3) - max_size)
if mod then
yi = yi - (yi % mod)
xi = xi - (xi % mod)
end
rect = iproc.crop(src, xi, yi, xi + max_size, yi + max_size)
-- ignore simple background
if rect:float():std() >= 0 then
break
end
end
return rect
else
return src
end
end
function pairwise_transform_utils.crop_if_large_pair(x, y, scale_y, max_size, mod)
local tries = 4
if y:size(2) > max_size and y:size(3) > max_size then
assert(max_size % 4 == 0)
local rect_x, rect_y
for i = 1, tries do
local yi = torch.random(0, y:size(2) - max_size)
local xi = torch.random(0, y:size(3) - max_size)
if mod then
yi = yi - (yi % mod)
xi = xi - (xi % mod)
end
rect_y = iproc.crop(y, xi, yi, xi + max_size, yi + max_size)
rect_x = iproc.crop(x, xi / scale_y, yi / scale_y, xi / scale_y + max_size / scale_y, yi / scale_y + max_size / scale_y)
-- ignore simple background
if rect_y:float():std() >= 0 then
break
end
end
return rect_x, rect_y
else
return x, y
end
end
function pairwise_transform_utils.preprocess(src, crop_size, options)
local dest = src
local box_only = false
if options.data.filters then
if #options.data.filters == 1 and options.data.filters[1] == "Box" then
box_only = true
end
end
if box_only then
local mod = 2 -- assert pos % 2 == 0
dest = pairwise_transform_utils.crop_if_large(dest, math.max(crop_size * 2, options.max_size), mod)
dest = data_augmentation.color_noise(dest, options.random_color_noise_rate)
dest = data_augmentation.overlay(dest, options.random_overlay_rate)
dest = data_augmentation.unsharp_mask(dest, options.random_unsharp_mask_rate)
dest = iproc.crop_mod4(dest)
else
dest = pairwise_transform_utils.random_half(dest, options.random_half_rate, options.downsampling_filters)
dest = pairwise_transform_utils.crop_if_large(dest, math.max(crop_size * 2, options.max_size))
dest = data_augmentation.blur(dest, options.random_blur_rate,
options.random_blur_size,
options.random_blur_sigma_min,
options.random_blur_sigma_max)
dest = data_augmentation.color_noise(dest, options.random_color_noise_rate)
dest = data_augmentation.overlay(dest, options.random_overlay_rate)
dest = data_augmentation.unsharp_mask(dest, options.random_unsharp_mask_rate)
dest = data_augmentation.shift_1px(dest)
end
return dest
end
function pairwise_transform_utils.preprocess_user(x, y, scale_y, size, options)
x, y = pairwise_transform_utils.crop_if_large_pair(x, y, scale_y, options.max_size, scale_y)
x = data_augmentation.erase(x,
options.random_erasing_rate,
options.random_erasing_n,
options.random_erasing_rect_min,
options.random_erasing_rect_max)
x, y = data_augmentation.pairwise_rotate(x, y,
options.random_pairwise_rotate_rate,
options.random_pairwise_rotate_min,
options.random_pairwise_rotate_max)
local scale_min = math.max(options.random_pairwise_scale_min, size / (1 + math.min(x:size(2), x:size(3))))
local scale_max = math.max(scale_min, options.random_pairwise_scale_max)
x, y = data_augmentation.pairwise_scale(x, y,
options.random_pairwise_scale_rate,
scale_min,
scale_max)
x, y = data_augmentation.pairwise_negate(x, y, options.random_pairwise_negate_rate)
x, y = data_augmentation.pairwise_negate_x(x, y, options.random_pairwise_negate_x_rate)
x = iproc.crop_mod4(x)
y = iproc.crop_mod4(y)
return x, y
end
function pairwise_transform_utils.active_cropping(x, y, lowres_y, size, scale, p, tries)
assert("x:size == y:size", x:size(2) * scale == y:size(2) and x:size(3) * scale == y:size(3))
assert("crop_size % scale == 0", size % scale == 0)
local r = torch.uniform()
local t = "float"
if x:type() == "torch.ByteTensor" then
t = "byte"
end
if p < r then
local xi = 0
local yi = 0
if x:size(3) > size + 1 then
xi = torch.random(0, x:size(3) - (size + 1)) * scale
end
if x:size(2) > size + 1 then
yi = torch.random(0, x:size(2) - (size + 1)) * scale
end
local yc = iproc.crop(y, xi, yi, xi + size, yi + size)
local xc = iproc.crop(x, xi / scale, yi / scale, xi / scale + size / scale, yi / scale + size / scale)
return xc, yc
else
local xcs = torch.LongTensor(tries, y:size(1), size, size)
local lcs = torch.LongTensor(tries, lowres_y:size(1), size, size)
local rects = {}
local r = torch.LongTensor(2, tries)
r[1]:random(1, x:size(3) - (size + 1)):mul(scale)
r[2]:random(1, x:size(2) - (size + 1)):mul(scale)
for i = 1, tries do
local xi = r[1][i]
local yi = r[2][i]
local xc = iproc.crop_nocopy(y, xi, yi, xi + size, yi + size)
local lc = iproc.crop_nocopy(lowres_y, xi, yi, xi + size, yi + size)
xcs[i]:copy(xc)
lcs[i]:copy(lc)
rects[i] = {xi, yi}
end
xcs:csub(lcs)
xcs:cmul(xcs)
local v, l = xcs:reshape(xcs:size(1), xcs:nElement() / xcs:size(1)):transpose(1, 2):sum(1):topk(1, true)
local best_xi = rects[l[1][1]][1]
local best_yi = rects[l[1][1]][2]
local yc = iproc.crop(y, best_xi, best_yi, best_xi + size, best_yi + size)
local xc = iproc.crop(x, best_xi / scale, best_yi / scale, best_xi / scale + size / scale, best_yi / scale + size / scale)
return xc, yc
end
end
function pairwise_transform_utils.flip_augmentation(x, y, lowres_y, x_noise)
local xs = {}
local ns = {}
local ys = {}
local ls = {}
for j = 1, 2 do
-- TTA
local xi, yi, ri, ni
if j == 1 then
xi = x
ni = x_noise
yi = y
ri = lowres_y
else
xi = x:transpose(2, 3):contiguous()
if x_noise then
ni = x_noise:transpose(2, 3):contiguous()
end
yi = y:transpose(2, 3):contiguous()
if lowres_y then
ri = lowres_y:transpose(2, 3):contiguous()
end
end
local xv = iproc.vflip(xi)
local nv
if x_noise then
nv = iproc.vflip(ni)
end
local yv = iproc.vflip(yi)
local rv
if ri then
rv = iproc.vflip(ri)
end
table.insert(xs, xi)
if ni then
table.insert(ns, ni)
end
table.insert(ys, yi)
if ri then
table.insert(ls, ri)
end
table.insert(xs, xv)
if nv then
table.insert(ns, nv)
end
table.insert(ys, yv)
if rv then
table.insert(ls, rv)
end
table.insert(xs, iproc.hflip(xi))
if ni then
table.insert(ns, iproc.hflip(ni))
end
table.insert(ys, iproc.hflip(yi))
if ri then
table.insert(ls, iproc.hflip(ri))
end
table.insert(xs, iproc.hflip(xv))
if nv then
table.insert(ns, iproc.hflip(nv))
end
table.insert(ys, iproc.hflip(yv))
if rv then
table.insert(ls, iproc.hflip(rv))
end
end
return xs, ys, ls, ns
end
local function lowres_model()
local seq = nn.Sequential()
seq:add(nn.SpatialAveragePooling(2, 2, 2, 2))
seq:add(nn.SpatialUpSamplingNearest(2))
return seq:cuda()
end
local g_lowres_model = nil
local g_lowres_gpu = nil
function pairwise_transform_utils.low_resolution(src)
--[[
-- I am not sure that the following process is thraed-safe
g_lowres_model = g_lowres_model or lowres_model()
if g_lowres_gpu == nil then
--benchmark
local gpu_time = sys.clock()
for i = 1, 10 do
g_lowres_model:forward(src:cuda()):byte()
end
gpu_time = sys.clock() - gpu_time
local cpu_time = sys.clock()
for i = 1, 10 do
gm.Image(src, "RGB", "DHW"):
size(src:size(3) * 0.5, src:size(2) * 0.5, "Box"):
size(src:size(3), src:size(2), "Box"):
toTensor("byte", "RGB", "DHW")
end
cpu_time = sys.clock() - cpu_time
--print(gpu_time, cpu_time)
if gpu_time < cpu_time then
g_lowres_gpu = true
else
g_lowres_gpu = false
end
end
if g_lowres_gpu then
return g_lowres_model:forward(src:cuda()):byte()
else
return gm.Image(src, "RGB", "DHW"):
size(src:size(3) * 0.5, src:size(2) * 0.5, "Box"):
size(src:size(3), src:size(2), "Box"):
toTensor("byte", "RGB", "DHW")
end
--]]
if src:size(1) == 1 then
return gm.Image(src, "I", "DHW"):
size(src:size(3) * 0.5, src:size(2) * 0.5, "Box"):
size(src:size(3), src:size(2), "Box"):
toTensor("byte", "I", "DHW")
else
return gm.Image(src, "RGB", "DHW"):
size(src:size(3) * 0.5, src:size(2) * 0.5, "Box"):
size(src:size(3), src:size(2), "Box"):
toTensor("byte", "RGB", "DHW")
end
end
return pairwise_transform_utils
|
fx_version 'adamant'
games { 'gta5' }
client_scripts {
'config.lua',
'client/client.lua',
}
server_scripts {
'config.lua',
'server/update.lua',
}
--
-- NUI
--
ui_page 'nui/dist/index.html'
files {
'nui/dist/index.html',
'nui/dist/app.css',
'nui/dist/app.js',
'nui/dist/img/radio.png',
}
--
-- Dependencies
--
dependencies {
'tokovoip_script',
}
--
-- About
--
name "encore_radio"
description "Radio script for TokoVoip."
author "CharlesHacks#9999"
version "1.0.0"
license "MIT"
|
--quartz
minetest.register_node(minetest.get_current_modname()..":quartz_block", {
description = "Quartz Block",
tiles = {"quartz_block.png"},
})
minetest.register_node(minetest.get_current_modname()..":quartz_slab", {
description = "Quartz Slab",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_slab1", {
description = "Quartz Slab",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {-0.5, 0, -0.5, 0.5, 0.5, 0.5},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_pillar", {
description = "Quartz Pillar",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {
{-0.25, -0.5, -0.25, 0.25, 0.5, 0.25},
},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_wall1", {
description = "Quartz Wall",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.25, 0.5, 0.5, 0.25},
},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_wall2", {
description = "Quartz Wall",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {
{-0.25, -0.5, -0.5, 0.25, 0.5, 0.5},
},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_wall3_1", {
description = "Quartz Wall",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {
{0, -0.5, -0.5, 0.5, 0.5, 0.5},
},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_wall3_2", {
description = "Quartz Wall",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0, 0.5, 0.5},
},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_wall4_1", {
description = "Quartz Wall",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, 0, 0.5, 0.5, 0.5},
},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_wall4_2", {
description = "Quartz Wall",
drawtype = "nodebox",
tiles = {"quartz_block.png"},
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.5, 0},
},
},
})
minetest.register_node(minetest.get_current_modname()..":quartz_welcome", {
description = "Quartz Welcome",
tiles = {"quartz_block.png^welcome_text.png"},
})
minetest.register_node(minetest.get_current_modname()..":quartz_play", {
description = "Quartz Play",
tiles = {"quartz_block.png^play_text.png"},
on_rightclick = function(pos, node, player, itemstack, pointed_thing)
bnb_core.start(player)
end
})
minetest.register_node(minetest.get_current_modname()..":quartz_shop", {
description = "Quartz Shop",
tiles = {"quartz_block.png^shop_text.png"},
on_rightclick = function(pos, node, player, itemstack, pointed_thing)
bnb_core.tp_shop(player)
end
})
minetest.register_node(minetest.get_current_modname()..":quartz_finished", {
description = "Quartz Finished",
tiles = {"quartz_block.png^finished_text.png"},
on_rightclick = function(pos, node, player, itemstack, pointed_thing)
--local complete = bnb_core.finished()
--bnb_core.complete(complete, player)
bnb_core.finished(player)
end
})
minetest.register_node(minetest.get_current_modname()..":quartz_build", {
description = "Quartz Build",
tiles = {"quartz_block.png^build_text.png"},
on_rightclick = function(pos, node, player, itemstack, pointed_thing)
bnb_core.tp_build(player)
end
})
--lantern
minetest.register_node(minetest.get_current_modname()..":light_block", {
description = "Light Block",
tiles = {"light.png"},
light_source = 14,
})
--funcs
local register_ore = function(name, desc)
minetest.register_node(minetest.get_current_modname()..":"..name.."_ore", {
description = desc.." Ore",
tiles = {"stone.png^"..name.."_ore.png"},
})
end
local register_stone = function(name, desc)
minetest.register_node(minetest.get_current_modname()..":"..name, {
description = desc.." Stone",
tiles = {name..".png"},
})
end
local register_liquid = function(name, desc)
minetest.register_node(minetest.get_current_modname()..":"..name, {
description = desc,
tiles = {name..".png"},
})
end
local register_dirt = function(name, desc, texture)
minetest.register_node(minetest.get_current_modname()..":"..name, {
description = desc,
tiles = texture,
})
end
local register_sand = function(name, desc)
minetest.register_node(minetest.get_current_modname()..":"..name, {
description = desc,
tiles = {name..".png"},
})
end
local register_block = function(name, desc)
minetest.register_node(minetest.get_current_modname()..":"..name.."_block", {
description = desc,
tiles = {name.."_block.png"},
})
end
local register_wool = function(name, desc)
minetest.register_node(minetest.get_current_modname()..":"..name .. "_wool", {
description = desc.." Wool",
tiles = {name .. "_wool.png"},
light_source = 1,
})
end
local register_glass = function(name, desc, extra)
minetest.register_node(minetest.get_current_modname()..":"..name .. "_stained_glass", {
description = desc.. " Stained Glass",
drawtype = "glasslike",
use_texture_alpha = "blend",
tiles = {name .. "_wool.png^[opacity:210".. extra},
light_source = 1,
paramtype = "light",--suggested by wuzzy
})
end
--logs
local register_log = function(name, desc)
minetest.register_node(minetest.get_current_modname()..":"..name.."_log", {
description = desc.." Log",
tiles = {"log_"..name.."_top.png", "log_"..name.."_top.png", "log_"..name..".png"}
})
end
local register_plank = function (name, desc)
minetest.register_node(minetest.get_current_modname()..":"..name.."_plank", {
description = desc.." Plank",
tiles = {name.."_plank.png"}
})
end
--signs
local register_sign = function(name, desc, tilez)
minetest.register_node(minetest.get_current_modname()..":sign_"..name, {
description = desc,
tiles = tilez,
light_source = 1,
})
end
--wool signs
register_sign("magenta_w", "Magenta W Sign", {"magenta_wool.png", "magenta_wool.png", "magenta_wool.png^font_w.png"})
register_sign("orange_o", "Orange O Sign", {"orange_wool.png", "orange_wool.png", "orange_wool.png^font_o.png"})
register_sign("cyan_o", "Cyan O Sign", {"cyan_wool.png", "cyan_wool.png", "cyan_wool.png^font_o.png"})
register_sign("green_l", "Green L Sign", {"green_wool.png", "green_wool.png", "green_wool.png^font_l.png"})
--log signs
register_sign("pine_w", "Pine W Sign", {"log_pine_top.png", "log_pine_top.png", "log_pine.png^font_w.png"})
register_sign("oak_o", "Oak O Sign", {"log_oak_top.png", "log_oak_top.png", "log_oak.png^font_o.png"})
register_sign("beech_o", "Beech O Sign", {"log_beech_top.png", "log_beech_top.png", "log_beech.png^font_o.png"})
register_sign("teak_d", "Teak D Sign", {"log_teak_top.png", "log_teak_top.png", "log_teak.png^font_d.png"})
--signs for planks
register_sign("pine_plank_p", "Pine Plank P Sign", {"pine_plank.png", "pine_plank.png", "pine_plank.png^font_p.png"})
register_sign("oak_plank_l", "Oak Plank L Sign", {"oak_plank.png", "oak_plank.png", "oak_plank.png^font_l.png"})
register_sign("beech_plank_a", "Beech Plank A Sign", {"beech_plank.png", "beech_plank.png", "beech_plank.png^font_a.png"})
register_sign("teak_plank_n", "Teak Plank N Sign", {"teak_plank.png", "teak_plank.png", "teak_plank.png^font_n.png"})
register_sign("ash_plank_k", "Ash Plank K Sign", {"ash_plank.png", "ash_plank.png", "ash_plank.png^font_k.png"})
register_sign("pine_plank_s", "Pine Plank S Sign", {"pine_plank.png", "pine_plank.png", "pine_plank.png^font_s.png"})
--wool signs
register_sign("pink_g", "Pink G Sign", {"pink_wool.png", "pink_wool.png", "pink_wool.png^font_g.png"})
register_sign("brown_l", "Brown L Sign", {"brown_wool.png", "brown_wool.png", "brown_wool.png^font_l.png"})
register_sign("red_a", "Red A Sign", {"red_wool.png", "red_wool.png", "red_wool.png^font_a.png"})
register_sign("magenta_s", "Magenta S Sign", {"magenta_wool.png", "magenta_wool.png", "magenta_wool.png^font_s.png"})
register_sign("violet_s", "Violet S Sign", {"violet_wool.png", "violet_wool.png", "violet_wool.png^font_s.png"})
--ore signs
register_sign("coal_o", "Coal O Sign", {"stone.png^coal_ore.png", "stone.png^coal_ore.png", "stone.png^coal_ore.png^font_o.png"})
register_sign("copper_r", "Copper R Sign", {"stone.png^copper_ore.png", "stone.png^copper_ore.png", "stone.png^copper_ore.png^font_r.png"})
register_sign("mese_e", "Mese E Sign", {"stone.png^mese_ore.png", "stone.png^mese_ore.png", "stone.png^mese_ore.png^font_e.png"})
register_sign("diamond_s", "Diamond S Sign", {"stone.png^diamond_ore.png", "stone.png^diamond_ore.png", "stone.png^diamond_ore.png^font_s.png"})
--blocks signs
register_sign("coal_b", "Coal B Sign", {"coal_block.png", "coal_block.png", "coal_block.png^font_b.png"})
register_sign("copper_l", "Copper L Sign", {"copper_block.png", "copper_block.png", "copper_block.png^font_l.png"})
register_sign("mese_o", "Mese O Sign", {"mese_block.png", "mese_block.png", "mese_block.png^font_o.png"})
register_sign("diamond_c", "Diamond C Sign", {"diamond_block.png", "diamond_block.png", "diamond_block.png^font_c.png"})
register_sign("gold_k", "Gold K Sign", {"gold_block.png", "gold_block.png", "gold_block.png^font_k.png"})
register_sign("iron_s", "Iron S Sign", {"iron_block.png", "iron_block.png", "iron_block.png^font_s.png"})
--stones signs
register_sign("stone_s", "Stone S Sign", {"stone.png", "stone.png", "stone.png^font_s.png"})
register_sign("polished_stone_t", "Polished Stone T Sign", {"polished_stone.png", "polished_stone.png", "polished_stone.png^font_t.png"})
register_sign("brick_stone_o", "Brick Stone O Sign", {"brick_stone.png", "brick_stone.png", "brick_stone.png^font_o.png"})
register_sign("desert_stone_n", "Desert Stone N Sign", {"desert_stone.png", "desert_stone.png", "desert_stone.png^font_n.png"})
register_sign("polished_desert_stone_e", "Polished Desert Stone E Sign", {"polished_desert_stone.png", "polished_desert_stone.png", "polished_desert_stone.png^font_e.png"})
register_sign("desert_brick_stone_s", "Desert Brick Stone S Sign", {"desert_brick_stone.png", "desert_brick_stone.png", "desert_brick_stone.png^font_s.png"})
--liquids signs
register_sign("water_f", "Water F Sign", {"water.png", "water.png", "water.png^font_f.png"})
register_sign("lava_l", "Lava L Sign", {"lava.png", "lava.png", "lava.png^font_l.png"})
register_sign("river_water_u", "River Water U Sign", {"river_water.png", "river_water.png", "river_water.png^font_u.png"})
register_sign("lava_i", "Lava I Sign", {"lava.png", "lava.png", "lava.png^font_i.png"})
register_sign("water_d", "Water D Sign", {"water.png", "water.png", "water.png^font_d.png"})
register_sign("river_water_s", "River Water S Sign", {"river_water.png", "river_water.png", "river_water.png^font_s.png"})
--dirts signs
register_sign("dirt_d", "Dirt D Sign", {"dirt.png", "dirt.png", "dirt.png^font_d.png"})
register_sign("dirt_with_grass_i", "Dirt With Grass I Sign", {"grass.png", "dirt.png", "dirt.png^grass_side.png^font_i.png"})
register_sign("dirt_with_snow_r", "Dirt With Snow R Sign", {"snow.png", "dirt.png", "dirt.png^snow_side.png^font_r.png"})
register_sign("dry_dirt_with_dry_grass_t", "Dry Dirt With Dry Grass T Sign", {"dry_grass.png", "dry_dirt.png", "dry_dirt.png^dry_grass_side.png^font_t.png"})
register_sign("dry_dirt_s", "Dry Dirt S Sign", {"dry_dirt.png", "dry_dirt.png", "dry_dirt.png^font_s.png"})
--sand signs
register_sign("sand_s", "Sand S Sign", {"sand.png", "sand.png", "sand.png^font_s.png"})
register_sign("silver_sand_a", "Silver Sand A Sign", {"silver_sand.png", "silver_sand.png", "silver_sand.png^font_a.png"})
register_sign("sand_n", "Sand N Sign", {"sand.png", "sand.png", "sand.png^font_n.png"})
register_sign("silver_sand_d", "Silver Sand D Sign", {"silver_sand.png", "silver_sand.png", "silver_sand.png^font_d.png"})
--shops
local register_shop = function(item, desc, overlay, extra)
if not extra then
extra = ""
end
minetest.register_node(minetest.get_current_modname()..":shop_"..item, {
description = desc,
tiles = {"blue_wool.png", "blue_wool.png", "[combine:128x128:0,0=(blue_wool.png^shopping_cart.png\\^[resize\\:128x128):48,56="..overlay.."\\^[resize\\:32x32"..extra},
light_source = 1,
})
end
local wools = {
{"red", "Red"},
{"blue", "Blue"},
{"grey", "Grey", "^[colorize:#000F:70"},
{"black", "Black"},
{"brown", "Brown"},
{"cyan", "Cyan"},
{"dark_green", "Dark Green"},
{"green", "Green"},
{"light_grey", "Light Grey"},
{"magenta", "Magenta"},
{"orange", "Orange"},
{"pink", "Pink"},
{"violet", "Violet"},
{"white", "White"},
{"yellow", "Yellow"},
}
for _, wool in ipairs(wools) do
--normal wools
register_wool(wool[1], wool[2])
register_shop(wool[1].."_wool", wool[2].."Wool Shop", wool[1].."_wool.png")
--glasses
if not wool[3] then
wool[3] = ""
end
register_glass(wool[1], wool[2], wool[3])
register_shop(wool[1].."_stained_glass", wool[2].." Stained Glass Shop", wool[1].."_wool.png", "\\^[opacity\\:210")
end
local woods = {
{"oak", "Oak"},
{"pine", "Pine"},
{"beech", "Beech"},
{"ash", "Ash"},
{"teak", "Teak"}
}
for _,wood in ipairs(woods) do
register_log(wood[1], wood[2])
register_shop(wood[1].."_log", wood[2].." Log Shop", "log_"..wood[1]..".png")
register_plank(wood[1], wood[2])
register_shop(wood[1].."_plank", wood[2].." Plank Shop", wood[1].."_plank.png")
end
local ores = {
{"coal", "Coal"},
{"copper", "Copper"},
{"diamond", "Diamond"},
{"gold", "Gold"},
{"iron", "Iron"},
{"mese", "Mese"},
{"tin", "Tin"},
}
for _,ore in ipairs(ores) do
register_ore(ore[1], ore[2])
register_shop(ore[1].."_ore", ore[2].." Ore Shop", "(stone.png^"..ore[1].."_ore.png)")
register_block(ore[1], ore[2])
register_shop(ore[1].."_block", ore[2].." Block Shop", ore[1].."_block.png")
end
local stones = {
{"stone", "Normal"},
{"brick_stone", "Brick"},
{"polished_stone", "Polished"},
{"desert_stone", "Desert"},
{"desert_brick_stone", "Desert Brick"},
{"polished_desert_stone", "Desert Polished"},
}
for _,stone in ipairs(stones) do
register_stone(stone[1], stone[2])
register_shop(stone[1], stone[2].." Stone Shop", stone[1]..".png")
end
local liquids = {
{"water", "Water"},
{"river_water", "River Water"},
{"lava", "Lava"},
}
for _,liquid in ipairs(liquids) do
register_liquid(liquid[1], liquid[2])
register_shop(liquid[1], liquid[2].." Shop", liquid[1]..".png")
end
local dirts = {
{"dirt", "Dirt", {"dirt.png"}},
{"dirt_with_grass", "Dirt With Grass", {"grass.png", "dirt.png", "dirt.png^grass_side.png"}},
{"dry_dirt", "Dry Dirt", {"dry_dirt.png"}},
{"dry_dirt_with_dry_grass", "Dry Dirt With Dry Grass", {"dry_grass.png", "dry_dirt.png", "dry_dirt.png^dry_grass_side.png"}},
{"dirt_with_snow", "Dirt With Snow", {"snow.png", "dirt.png", "dirt.png^snow_side.png"}},
}
for _,dirt in ipairs(dirts) do
register_dirt(dirt[1], dirt[2], dirt[3])
local sidetexture = dirt[3][3] or dirt[3][1]
register_shop(dirt[1], dirt[2].." Shop", "("..sidetexture..")")
end
local sands = {
{"sand", "Sand"},
{"silver_sand", "Silver Sand"},
}
for _,sand in ipairs(sands) do
register_sand(sand[1], sand[2])
register_shop(sand[1], sand[2].." Shop", sand[1]..".png")
end
--make it so when you look at a shop, it adds the name of the node it is selling to your hud
local name
minetest.register_globalstep(function(dtime)
for _,player in ipairs(minetest.get_connected_players()) do
local pos = player:get_pos()
pos.y = pos.y + player:get_properties().eye_height
local look_dir = player:get_look_dir()
look_dir = vector.multiply(look_dir, 6)--make distance bigger cuz wuzzy comaplained
local pos2 = vector.add(pos, look_dir)
local ray = minetest.raycast(pos, pos2, false, false)
if not ray then return end
for pointed_thing in ray do
if pointed_thing.type == "node" then
local node = minetest.get_node(pointed_thing.under)
local node_pos = pointed_thing.under
local node_name = node.name
if node_name:find("bnb_nodes:shop_") then
name = node_name:gsub("bnb_nodes:shop_", ""):gsub("_", " ")
local n = player:hud_add({
hud_elem_type = "text",
position = {x = 0.1, y = 0.8},
offset = {x = 0, y = 0},
text = "Selling: "..name,
alignment = {x = 0, y = 0},
scale = {x = 1, y = 1},
number = 0xe6482e,
})
minetest.after(0.1, function()
player:hud_remove(n)
end)
return
elseif node_pos.x >= bnb_core.building_min.x and node_pos.x <= bnb_core.building_max.x and node_pos.z >= bnb_core.building_min.z and node_pos.z <= bnb_core.building_max.z and node_pos.y >= bnb_core.building_min.y and node_pos.y <= bnb_core.building_max.y then
name = node_name:gsub("bnb_nodes:", ""):gsub("_", " ")
local n = player:hud_add({
hud_elem_type = "text",
position = {x = 0.1, y = 0.8},
offset = {x = 0, y = 0},
text = "Building: "..name,
alignment = {x = 0, y = 0},
scale = {x = 1, y = 1},
number = 0xe6482e,
})
minetest.after(0.1, function()
player:hud_remove(n)
end)
return
elseif node_pos.x >= bnb_core.demo_min.x and node_pos.x <= bnb_core.demo_max.x and node_pos.z >= bnb_core.demo_min.z and node_pos.z <= bnb_core.demo_max.z and node_pos.y >= bnb_core.demo_min.y and node_pos.y <= bnb_core.demo_max.y then
name = node_name:gsub("bnb_nodes:", ""):gsub("_", " ")
local n = player:hud_add({
hud_elem_type = "text",
position = {x = 0.1, y = 0.8},
offset = {x = 0, y = 0},
text = "Demo: "..name,
alignment = {x = 0, y = 0},
scale = {x = 1, y = 1},
number = 0xe6482e,
})
minetest.after(0.1, function()
player:hud_remove(n)
end)
return
end
end
end
end
end)
|
--Set color dialog script.
--When form load.
function ud_set_color_fm_load(self)
self.color = ""
return 1
end
--When form show.
function ud_set_color_fm_show(self)
local ui = self:GetUI()
self.Left = (ui.Width - self.Width) / 2
self.Top = (ui.Height - self.Height) / 2
local color = self.color
local red = 0
local green = 0
local blue = 0
local alpha = 0
local comma1 = string.find(color, ",")
if comma1 ~= nil then
local comma2 = string.find(color, ",", comma1 + 1)
if comma2 ~= nil then
local comma3 = string.find(color, ",", comma2 + 1)
if comma3 ~= nil then
red = k_number(string.sub(color, 1, comma1))
green = k_number(string.sub(color, comma1 + 1, comma2))
blue = k_number(string.sub(color, comma2 + 1, comma3))
alpha = k_number(string.sub(color, comma3 + 1))
end
end
end
self.red_nm.Text = k_string(red)
self.green_nm.Text = k_string(green)
self.blue_nm.Text = k_string(blue)
self.alpha_nm.Text = k_string(alpha)
self.color_lb.BackColor = color
return 1
end
--When ok button clicked.
function ok_bn_click(self)
local ui = self:GetUI()
local form = self:FindForm()
local color = form.color
form:Close()
k_send_signal(form, "set_color_signal", "ok", color)
ui:Delete(form)
return 1
end
--When cancel button clicked.
function cancel_bn_click(self)
local ui = self:GetUI()
local form = self:FindForm()
form:Close()
k_send_signal(form, "set_color_signal", "cancel")
ui:Delete(form)
return 1
end
--Update color value.
function update_color(form)
local red = k_number(form.red_nm.Text)
local green = k_number(form.green_nm.Text)
local blue = k_number(form.blue_nm.Text)
local alpha = k_number(form.alpha_nm.Text)
if red < 0 or red > 255 then
return 0
end
if green < 0 or green > 255 then
return 0
end
if blue < 0 or blue > 255 then
return 0
end
if alpha < 0 or alpha > 255 then
return 0
end
local color = k_string(red) .. "," .. k_string(green) .. "," .. k_string(blue) .. "," .. k_string(alpha)
form.color_lb.BackColor = color
form.color = color
return 1
end
--Edit red changed.
function red_nm_changed(self)
local form = self:FindForm()
update_color(form)
return 1
end
--Edit green changed.
function green_nm_changed(self)
local form = self:FindForm()
update_color(form)
return 1
end
--Edit blue changed.
function blue_nm_changed(self)
local form = self:FindForm()
update_color(form)
return 1
end
--Edit alpha changed.
function alpha_nm_changed(self)
local form = self:FindForm()
update_color(form)
return 1
end
|
return {
ACTIONFAIL =
{
SHAVE =
{
AWAKEBEEFALO = "DANGER! TARGET IS AWAKE",
GENERIC = "THAT IS NOT A VALID SHAVE TARGET",
NOBITS = "THERE IS NO STUBBLE TO SHAVE",
},
STORE =
{
GENERIC = "IT IS AT CAPACITY",
NOTALLOWED = "THAT INPUT IS NOT ALLOWED",
},
},
ACTIONFAIL_GENERIC = "ACTION NOT AVAILABLE IN CURRENT CONTEXT",
ANNOUNCE_CHARGE = "**SYSTEM OVERLOAD**",
ANNOUNCE_DISCHARGE = "SYSTEMS NOMINAL",
ANNOUNCE_ADVENTUREFAIL = "ABORT, RETRY, FAIL?",
ANNOUNCE_BEES = "BEES!",
ANNOUNCE_BOOMERANG = "ERROR: CATCH FAILED",
ANNOUNCE_CHARLIE = "THREAT DETECTED",
ANNOUNCE_CHARLIE_ATTACK = "ERROR: UNKNOWN ATTACKER",
ANNOUNCE_COLD = "MECHANISMS ARE FREEZING",
ANNOUNCE_CRAFTING_FAIL = "INSUFFICIENT RESOURCES",
ANNOUNCE_DEERCLOPS = "WARNING: LARGE ATTACKER INCOMING",
ANNOUNCE_DUSK = "WARNING: NIGHT APPROACHING",
ANNOUNCE_EAT =
{
GENERIC = "DELICIOUS",
PAINFUL = "THAT WAS NOT FOOD",
SPOILED = "SPOILED FOOD IS STILL FOOD",
STALE = "STALE FOOD IS JUST AS GOOD",
},
ANNOUNCE_ENTER_DARK = "OPTICAL SENSORS DEACTIVATED",
ANNOUNCE_ENTER_LIGHT = "OPTICAL SENSORS ACTIVE",
ANNOUNCE_FREEDOM = "ENGAGE FREEDOM PROTOCOL",
ANNOUNCE_HIGHRESEARCH = "INFORMATION OVERLOAD",
ANNOUNCE_HOUNDS = "SOMETHING IS COMING",
ANNOUNCE_HUNGRY = "FUEL RESERVES LOW",
ANNOUNCE_HUNT_BEAST_NEARBY = "DISTANCE TO LIFEFORM: MINIMAL",
ANNOUNCE_HUNT_LOST_TRAIL = "END OF TRAIL",
ANNOUNCE_INV_FULL = "ITEM EXCEEDS CARRYING CAPACITY",
ANNOUNCE_KNOCKEDOUT = "CPU REBOOTED",
ANNOUNCE_LOWRESEARCH = "MATERIAL HAS LOW INFORMATIONAL CONTENT",
ANNOUNCE_MOSQUITOS = "MOSQUITOS!",
ANNOUNCE_NODANGERSLEEP = "WARNING: THREAT DETECTED. SLEEP MODE DEACTIVATED.",
ANNOUNCE_NODAYSLEEP = "SLEEP MODE UNAVAILABLE DURING DAY",
ANNOUNCE_NODAYSLEEP_CAVE = "SLEEP MODE UNAVAILABLE DURING DAY",
ANNOUNCE_NOHUNGERSLEEP = "CAN NOT SLEEP ON AN EMPTY NUTRIENT PROCESSOR.",
ANNOUNCE_NO_TRAP = "ANALYSIS COMPLETE. SITUATION STABLE.",
ANNOUNCE_PECKED = "OUCH",
ANNOUNCE_QUAKE = "SHAKING EARTH DETECTED",
ANNOUNCE_RESEARCH = "INFORMATION ADDED",
ANNOUNCE_THORNS = "DAMAGE DETECTED",
ANNOUNCE_TORCH_OUT = "TORCH EXHAUSTED",
ANNOUNCE_TRAP_WENT_OFF = "IT'S A TRAP",
ANNOUNCE_UNIMPLEMENTED = "ALERT: OBJECT NOT FUNCTIONING TO SPECIFICATION.",
ANNOUNCE_WORMHOLE = "MY INPUTS ARE FULL OF SLIME",
ANNOUNCE_CANFIX = "\nI CAN FIX THIS.",
ANNOUNCE_ACCOMPLISHMENT= "WHY AM I DOING THIS?",
ANNOUNCE_ACCOMPLISHMENT_DONE = "TASK COMPLETE",
BATTLECRY =
{
GENERIC = "I WILL DESTROY YOU",
PREY = "EXTERMINATE",
},
COMBAT_QUIT =
{
GENERIC = "COMBAT ROUTINE FAILED",
},
DESCRIBE =
{
WORMLIGHT = "MAGIC LIGHT BERRY.",
WORM =
{
PLANT = "THAT PLANT SEEMS SUSPICIOUS.",
DIRT = "WARNING. LIFE DETECTED.",
WORM = "THREAT IMMINENT.",
},
EEL = "I TOOK IT FROM IT'S HOME. THIS IS FUNNY TO ME!",
EEL_COOKED = "THE FLAMES HELP CONDENSE THE ENERGY.",
UNAGI = "A FANCIER FUEL PACK.",
EYETURRET = "I HAVE TAMED MIGHTY BEASTS TO FIGHT FOR ME.",
EYETURRET_ITEM = "I NEED TO SET THIS UP PROPERLY.",
MINOTAURHORN = "I HAVE TAKEN A TROPHY TO PROVE MY MIGHT.",
MINOTAURCHEST = "CHEST HAS POINTY EARS.",
THULECITE_PIECES = "WITH THIS I CAN CREATE MORE THULECITE.",
POND_ALGAE = "LOOK AT IT STRUGGLE TO LIVE.",
GREENSTAFF = "HAHAHA! SUCH A POWERFUL TOOL.",
POTTEDFERN = "MAYBE THIS WILL HELP LURE VICTIMS TO MY BASE.",
SLURPER = "IT VIOLATED MY SMELLING MODULE.",
SLURPER_PELT = "A MEATSACK",
ARMORSLURPER = "FURRY INSULATION FOR MY WIRES.",
ORANGEAMULET = "A WIRELESS ARM MODULE.",
YELLOWSTAFF = "THESE GEMS WORK WELL WITH STICKS.",
YELLOWGEM = "IT IS RATHER HEAVY.",
ORANGEGEM = "IT SHIMMERS IN MY HANDS.",
TELEBASE =
{
VALID = "IT IS READY FOR USE.",
GEMS = "I MUST PROVIDE POWER TO MY CREATION.",
},
GEMSOCKET =
{
VALID = "POWER == ON",
GEMS = "IT REQUIRES A BATTERY.",
},
STAFFLIGHT = "SUCH POWER!!",
RESEARCHLAB4 = "WITH THIS EXTRA POWER I HAVE... MORE POWER!",
ANCIENT_ALTAR =
{
WORKING = "ERROR: CAUSALITY COMPROMISED",
BROKEN = "ERROR: PSUDOSCIENCE UNWORKABLE",
},
ANCIENT_ALTAR_BROKEN = "ERROR: PSUDOSCIENCE UNWORKABLE",
ANCIENT_STATUE = "A NIGHTMARE INDICATOR",
LICHEN = "A SLOW GROWING SYMBIOTE",
CUTLICHEN = "THIS WILL CRUMBLE AWAY SOON.",
CAVE_BANANA = "MORE CARBON",
CAVE_BANANA_COOKED = "THESE FOOD THINGS ARE SO TEDIUOUS",
CAVE_BANANA_TREE = "LIFE FINDS A WAY, UNFORTUNATELY",
ROCKY = "MY SHELL IS NICER",
HOUNDSTOOTH="MASTICATING EDGE",
ARMORSNURTLESHELL="HOUSING MODULE",
BAT="FLYING RAT",
BATBAT = "AHHAHA! FREE POWER!",
BATWING="FLYING MECHANISM",
BATWING_COOKED="BROKEN FLYING MECHANISM",
BEDROLL_FURRY="COMFORT IS AN ILLUSION",
BUNNYMAN="ITS METABOLISM OFFENDS ME",
FLOWER_CAVE="POWER SOURCE: UNKNOWN",
FLOWER_CAVE_DOUBLE="POWER SOURCE: UNKNOWN",
FLOWER_CAVE_TRIPLE="POWER SOURCE: UNKNOWN",
GUANO="MORE POOP. SIGH.",
LANTERN="LIGHT THE WAY, FRIEND",
LIGHTBULB="BIOLUMINESCENCE IS GROSS",
MANRABBIT_TAIL="FUZZY BUNNY NUMBER ONE",
MUSHTREE_TALL="IT IS USEFULLY BRIGHT",
MUSHTREE_MEDIUM="SHINY RED",
MUSHTREE_SMALL="SHINY GREEN",
RABBITHOUSE="THAT IS ONE LARGE CARROT",
SLURTLE="HE HAS A SHELL LIKE ME",
SLURTLE_SHELLPIECES="THEY DON'T FIT BACK TOGETHER",
SLURTLEHAT="THIS MAKES ME HAPPY",
SLURTLEHOLE="THEY DON'T WEAR THEIR SHELLS IN THERE",
SLURTLESLIME="NOT LOGICAL.",
SNURTLE="DIFFERENT SHELL, SAME SLUG",
SPIDER_HIDER="AN ARMOURED SPIDER",
SPIDER_SPITTER="A PROJECTILE SPIDER",
SPIDERHOLE="SPIDERS DETECTED",
STALAGMITE="ROCKS CONTAINING ROCKS",
STALAGMITE_FULL="ROCKS CONTAINING ROCKS",
STALAGMITE_LOW="ROCKS CONTAINING ROCKS",
STALAGMITE_MED="ROCKS CONTAINING ROCKS",
STALAGMITE_TALL="ROCK WITH ROCKS",
STALAGMITE_TALL_FULL="ROCK WITH ROCKS",
STALAGMITE_TALL_LOW="ROCK WITH ROCKS",
STALAGMITE_TALL_MED="ROCK WITH ROCKS",
TURF_CARPETFLOOR = "GROUND PARTS",
TURF_CHECKERFLOOR = "GROUND PARTS",
TURF_DIRT = "GROUND PARTS",
TURF_FOREST = "GROUND PARTS",
TURF_GRASS = "GROUND PARTS",
TURF_MARSH = "GROUND PARTS",
TURF_ROAD = "GROUND PARTS",
TURF_ROCKY = "GROUND PARTS",
TURF_SAVANNA = "GROUND PARTS",
TURF_WOODFLOOR = "GROUND PARTS",
TURF_CAVE="GROUND PARTS",
TURF_FUNGUS="GROUND PARTS",
TURF_SINKHOLE="GROUND PARTS",
TURF_UNDERROCK="GROUND PARTS",
TURF_MUD="GROUND PARTS",
POWCAKE = "IT NEVER GOES BAD",
CAVE_ENTRANCE =
{
GENERIC="DESCENT BLOCKED. HOW TO PROCEED?",
OPEN = "DESCEND?",
},
CAVE_EXIT = "SOLAR ARRAY NEED REFUELING.",
BOOMERANG = "REUSABLE PROJECTILE.",
MAXWELLPHONOGRAPH = "IT IS A MUSICAL SLAVE.",
ABIGAIL = "UNDEAD ALERT",
PIGGUARD = "HOSTILE DETECTED.",
ADVENTURE_PORTAL = "HE IS NOT MUCH OF A CONVERSATIONALIST",
AMULET = "ANOMALY DETECTED",
ANIMAL_TRACK = "LIFEFORM DETECTED",
ARMORGRASS = "THIS WILL ADD EXTRA PROTECTION TO MY METAL CASING.",
ARMORMARBLE = "EXTRA HEAVY DUTY CASING.",
ARMORWOOD = "UPGRADED ARMOUR",
ARMOR_SANITY = "I WILL PROTECT MYSELF WITH NOTHINGNESS",
ASH =
{
GENERIC = "OUTPUT OF FIRE PROGRAM.",
REMAINS_EYE_BONE = "OUTPUT OF EYEBONE TELEPORTATION PROGRAM.",
REMAINS_THINGIE = "OUTPUT OF FIRE PROGRAM. INPUT UNDETERMINED.",
},
AXE = "A TOOL FOR CHOPPING DOWN LIVING MATTER",
BABYBEEFALO =
{
GENERIC = "IT IS STILL INITIALIZING",
SLEEPING = "REST FUNCTION ACTIVATED",
},
BACKPACK = "UPGRADED STORAGE MODULE",
BACONEGGS = "UPGRADED FOOD MATERIAL",
BANDAGE = "TEMPORARY MAINTENANCE DEVICE.",
BASALT = "INSUFFICIENT DESTRUCTIVE ABILITIES",
BEARDHAIR = "DISGUSTING",
BEDROLL_STRAW = "SLEEP( 1000 )",
BEE =
{
GENERIC = "A MINDLESS DRONE. I LIKE HIM.",
HELD = "ITS VIBRATIONS ARE COMFORTING",
},
BEEBOX =
{
FULLHONEY = "HONEY LEVELS ARE HIGH",
GENERIC = "WORK HARDER, BEES",
NOHONEY = "NO HONEY DETECTED",
SOMEHONEY = "HONEY LEVELS ARE LOW",
},
BEEFALO =
{
FOLLOWER = "FOLLOW ME WITHOUT QUESTION.",
GENERIC = "IT STINKS OF MEAT",
NAKED = "I HAVE HUMILIATED IT. GOOD.",
SLEEPING = "IT BEGS TO BE TIPPED OVER",
},
BEEFALOHAT = "THERE ARE TRACES OF FECAL MATTER EMBEDDED IN THE FIBERS",
BEEFALOWOOL = "EXTRUDED BEEFALO DISGUSTINGNESS",
BEEHAT = "THE MESH IS SMALLER THAN BEE STINGERS",
BEEHIVE = "HOW INDUSTRIOUS",
BEEMINE = "IMPROVISED STINGING DEVICE",
BEEMINE_MAXWELL = "AGGRESSIVE LIFEFORMS WITHIN",
BERRIES = "THEY REMIND ME OF BLOOD",
BERRIES_COOKED = "THEY HAVE LOST STRUCTURAL INTEGRITY",
BERRYBUSH =
{
BARREN = "THE SYSTEM IS DOWN",
GENERIC = "PERIODIC CALORIE DISPENSER",
PICKED = "IT IS REBOOTING",
},
BIRDCAGE =
{
GENERIC = "I WILL IMPRISON THE FLESHLINGS",
OCCUPIED = "NOW I HAVE YOU",
SLEEPING = "WAKE UP, FLESHLING",
},
BIRDTRAP = "STUPID BIRDS. HA.",
BIRD_EGG = "I HATE YOU, EGG",
BIRD_EGG_COOKED = "THIS IS SUPPOSED TO BE AN IMPROVEMENT",
BISHOP = "REVEREND AUTOMATON",
BLOWDART_FIRE = "A WEAPON OF MINOR DESTRUCTION",
BLOWDART_SLEEP = "THESE CREATURES ARE SO MANIPULABLE",
BLOWDART_PIPE = "ACCELERATES SHARP OBJECTS TO DANGEROUS SPEEDS",
BLUEAMULET = "THIS WILL MAKE A GREAT HEATSINK.",
BLUEGEM = "IT IS SLIGHTLY COLD",
BLUEPRINT = "KNOWLEDGE WAITING TO BE ABSORBED.",
BLUE_CAP = "MEDICINAL FUNGUS",
BLUE_CAP_COOKED = "MODIFIED FUNGUS",
BLUE_MUSHROOM =
{
GENERIC = "BLUE FUNGUS",
INGROUND = "IT IS HIDING",
PICKED = "I TOOK IT.",
},
BOARDS = "THEY ARE FLATTER NOW",
BOAT = "BOAT",
BONESTEW = "UPGRADED FOOD MATERIAL",
BUGNET = "HARVEST INSECTS",
BUSHHAT = "HOW DEMEANING",
BUTTER = "THIS IS IMPROBABLE",
BUTTERFLY =
{
GENERIC = "IT THINKS IT IS SO PRETTY",
HELD = "SQUISH",
},
BUTTERFLYMUFFIN = "UPGRADED FOOD MATERIAL",
BUTTERFLYWINGS = "IRRIDESCENT",
CAMPFIRE =
{
EMBERS = "WARNING: FIRE LEVEL CRITICAL",
GENERIC = "A TEMPORARY ENCAMPMENT",
HIGH = "WARNING: FIRE IS RAMBUNCTIOUS",
LOW = "WARNING: FIRE LEVEL LOW",
NORMAL = "IT REMINDS ME OF SOMETHING",
OUT = "NO FIRE DETECTED",
},
CANE = "ASSISTED LOCOMOTION DEVICE",
CARROT = "NUTRITIOUS",
CARROT_COOKED = "IT IS FLOPPY NOW",
CARROT_PLANTED = "ROBOT NEEDS FOOD",
CARROT_SEEDS = "IT'S LIKE SOURCE CODE FOR PLANTS",
CAVE_FERN = "YOUR CHARMS WILL NOT WORK ON ME, PLANT.",
CHARCOAL = "COMPRESSED DEAD MATTER. WHAT IS NOT TO LIKE?",
CHESSJUNK1 = "EX-AUTOMATON",
CHESSJUNK2 = "EX-AUTOMATON",
CHESSJUNK3 = "EX-AUTOMATON",
CHESTER = "THIS EXTERNAL STORAGE UNIT APPEARS TO BE SENTIENT",
CHESTER_EYEBONE = "IT IS THE DRM KEY FOR THE STORAGE UNIT",
COOKEDMANDRAKE = "I WIN",
COOKEDMEAT = "FIRE MAKES THINGS BETTER",
COOKEDMONSTERMEAT = "IT IS STILL SOMEWHAT INCOMPATIBLE",
COOKEDSMALLMEAT = "IT TASTES LIKE BURNT REVENGE",
COOKPOT =
{
COOKING_LONG = "MORE TIME IS REQUIRED",
COOKING_SHORT = "IT IS ALMOST COMPLETE",
DONE = "THE COOKING PROCESS IS DONE",
EMPTY = "I CAN REFINE MEATS AND VEGETABLES INTO MORE ROBUST FORMS",
},
CORN = "SAY(CORNY_JOKE)",
CORN_COOKED = "EMPTY CALORIES",
CORN_SEEDS = "IT'S LIKE SOURCE CODE FOR PLANTS",
CROW =
{
GENERIC = "IT IS SMARTER THAN MOST HUMANS",
HELD = "NOT SO SMART NOW, ARE YOU?",
},
CUTGRASS = "PLANT MATTER",
CUTREEDS = "HOLLOW PLANT MATTER",
CUTSTONE = "I HAVE IMPROVED THE ROCKS",
DEADLYFEAST = "POISON DETECTED",
DEERCLOPS = "DANGER! THREAT INCOMING!",
DEERCLOPS_EYEBALL = "A GIANT ORGANIC LENS",
DEPLETED_GRASS =
{
GENERIC = "AN EXPIRED TUFT OF GRASS",
},
DIRTPILE = "UNKNOWN PILE FORMAT",
DIVININGROD =
{
COLD = "SIGNAL STRENGTH: LOW",
GENERIC = "IT WANTS ITS MOTHER",
HOT = "SIGNAL STRENGTH: EXTREMELY HIGH",
WARM = "SIGNAL STRENGTH: MEDIUM",
WARMER = "SIGNAL STRENGTH: HIGH",
},
DIVININGRODBASE =
{
GENERIC = "PURPOSE OF USE UNCLEAR.",
READY = "FINAL INPUT IS LARGE KEY, THEN ROD WILL FUNCTION.",
UNLOCKED = "ROD IS FULLY OPERATIONAL.",
},
DIVININGRODSTART = "ROD COULD BE USEFUL TOOL.",
DRAGONFRUIT = "IT HAS HEALING PROPERTIES",
DRAGONFRUIT_COOKED = "I SHOULD EAT THIS SOON",
DRAGONFRUIT_SEEDS = "IT'S LIKE SOURCE CODE FOR PLANTS",
DRAGONPIE = "UPGRADED FOOD MATERIAL",
DRUMSTICK = "LIVING THINGS ARE MADE OF FASCINATING PARTS",
DRUMSTICK_COOKED = "A TASTE SENSATION",
DUG_BERRYBUSH = "IT WOULD BE MORE USEFUL IN THE GROUND",
DUG_GRASS = "IT WOULD BE MORE USEFUL IN THE GROUND",
DUG_MARSH_BUSH = "IT WOULD BE MORE USEFUL IN THE GROUND",
DUG_SAPLING = "IT WOULD BE MORE USEFUL IN THE GROUND",
DURIAN = "GOOD THING I LACK A NOSE",
DURIAN_COOKED = "STILL NOT GOOD",
DURIAN_SEEDS = "IT'S LIKE SOURCE CODE FOR PLANTS",
EARMUFFSHAT = "I WILL UTILIZE THEIR FURRINESS",
EGGPLANT = "IT HAS AN ILLOGICAL NAME",
EGGPLANT_COOKED = "FANCY",
EGGPLANT_SEEDS = "IT'S LIKE SOURCE CODE FOR PLANTS",
EVERGREEN =
{
BURNING = "SOON THERE WILL BE NOTHING LEFT",
BURNT = "I WIN. GOOD.",
CHOPPED = "THE NATURAL WORLD IS OVERRATED",
GENERIC = "TARGET ACQUIRED",
},
EVERGREEN_SPARSE =
{
BURNING = "SOON THERE WILL BE NOTHING LEFT",
BURNT = "I WIN. GOOD.",
CHOPPED = "THE NATURAL WORLD IS OVERRATED",
GENERIC = "PATHETIC TREE DROPS NO BABIES",
},
EYEPLANT = "EXTERNAL SIGHT MODULES.",
FARMPLOT =
{
GENERIC = "IT IS NOT CURRENTLY ACTIVE",
GROWING = "LIFE IS INEFFICIENT",
NEEDSFERTILIZER = "ITS RESOURCES ARE EXHAUSTED",
},
FEATHERHAT = "I STILL CAN NOT FLY",
FEATHER_CROW = "IT HAS BEEN SEPARATED FROM ITS BIRD",
FEATHER_ROBIN = "IT HAS BEEN SEPARATED FROM ITS BIRD",
FEATHER_ROBIN_WINTER = "IT HAS BEEN SEPARATED FROM ITS BIRD",
FEM_PUPPET = "SHE APPEARS TO BE TRAPPED.",
FIREFLIES =
{
GENERIC = "BIOLUMINESCENT INSECTS",
HELD = "THEY ARE VERY LIGHT",
},
FIREHOUND = "IT LIVES TO BURN",
FIREPIT =
{
EMBERS = "WARNING: FIRE LEVEL CRITICAL",
GENERIC = "WARMTH AND LIGHT",
HIGH = "WARNING: FIRE LEVEL EXCEEDS DESIGN PARAMETERS",
LOW = "WARNING: FIRE LEVEL LOW",
NORMAL = "THIS FIRE IS FULLY OPERATIONAL",
OUT = "IT NEEDS TO BE REBOOTED",
},
FIRESTAFF = "THIS STAFF HAS BEEN OPTIMIZED FOR COMBUSTION.",
FISH = "IT HAS RUN OUT OF LIFE. I WIN.",
FISHINGROD = "I DO NOT LIKE WATER",
FISHSTICKS = "UPGRADED FOOD MATERIAL",
FISHTACOS = "UPGRADED FOOD MATERIAL",
FISH_COOKED = "REQUIRES CHIPS",
FLINT = "THIS ROCK IS SHARPER THAN MOST",
FLOWER = "MY APPRECIATION FOR BEAUTY IS LIMITED",
FLOWERHAT = "AT LEAST THEY ARE DEAD",
FLOWER_EVIL = "HEY THERE, FLOWERS. WANNA... KILL ALL HUMANS?",
FOLIAGE = "I ENDED A LIFE. YAY.",
FOOTBALLHAT = "PADDING FOR MY PROCESSING UNIT",
FROG =
{
DEAD = "I WIN",
GENERIC = "POTENTIAL BUNWICH",
SLEEPING = "I SHOULD HARVEST IT",
},
FROGGLEBUNWICH = "UPGRADED FOOD MATERIAL",
FROGLEGS = "REPLACEMENT PARTS FOR FROGS",
FROGLEGS_COOKED = "THEY ARE MORE NUTRITIOUS NOW",
FRUITMEDLEY = "UPGRADED FOOD MATERIAL",
GEARS = "OH NO. WHAT HAVE I DONE TO YOU?",
GHOST = "ERROR: UNKNOWN",
GOLDENAXE = "GOLD IS MORE DURABLE?",
GOLDENPICKAXE = "GOLD IS MORE DURABLE?",
GOLDENPITCHFORK = "GOLD IS MORE DURABLE?",
GOLDENSHOVEL = "GOLD IS MORE DURABLE?",
GOLDNUGGET = "I APPRECIATE ITS CONDUCTIVITY",
GRASS =
{
BARREN = "FERTILIZATION REQUIRED",
BURNING = "OOPS",
GENERIC = "IT LOOKS COMBUSTIBLE",
PICKED = "IT WILL RETURN SOON",
},
GREEN_CAP = "CULINARY FUNGUS",
GREEN_CAP_COOKED = "MODIFIED FUNGUS",
GREEN_MUSHROOM =
{
GENERIC = "GREEN FUNGUS",
INGROUND = "IT IS HIDING",
PICKED = "I TOOK IT.",
},
GUNPOWDER = "PUTS THE POW IN POWDER",
HAMBAT = "TASTE IRONY AND DIE, FLESHLINGS.",
HAMMER = "DECONSTRUCTION",
HEALINGSALVE = "KILL MICROLIFE TO SAVE MACROLIFE",
HEATROCK =
{
COLD = "LACKS ALL THERMAL ENERGY",
GENERIC = "A DECEPTIVELY SIMPLE DEVICE",
HOT = "TEMPERATURE AT MAXIMUM",
WARM = "IT WARMS MY COLD CHASSIS",
},
HOME = "WHO WROTE THAT?",
HOMESIGN = "YOU ARE HERE.",
HONEY = "IT IS A GOOD LUBRICANT FOR MY GEARS",
HONEYCOMB = "ONE UNIT OF BEE STORAGE",
HONEYHAM = "UPGRADED FOOD MATERIAL",
HONEYNUGGETS = "UPGRADED FOOD MATERIAL",
HORN = "UNHYGIENIC",
HOUND = "IT LIVES TO EAT",
HOUNDBONE = "EXOSKELETON FOR INSIDES. PROVIDES STRUCTURAL INTEGRITY.",
HOUNDMOUND = "SOMETHING DANGEROUS RESIDES HERE",
ICEBOX = "CARRY ON, MY FRIGID BROTHER",
ICEHOUND = "IT LIVES TO FREEZE",
INSANITYROCK =
{
ACTIVE = "MY MAPPING MODULE SHOWS NO RECORD OF THIS OBSTRUCTION.",
INACTIVE = "IT APPEARS TO BE MOSTLY UNDERGROUND",
},
JAMMYPRESERVES = "UPGRADED FOOD MATERIAL",
KABOBS = "UPGRADED FOOD MATERIAL",
KILLERBEE =
{
GENERIC = "IT HAS A STINGER AND A BAD ATTITUDE",
HELD = "WARNING: KILLER BEE IN POCKET",
},
KNIGHT = "HORSE AUTOMATON",
KOALEFANT_SUMMER = "POSSESSES AMPLE ENERGY RESERVES",
KOALEFANT_WINTER = "IT RADIATES WITH MEAT WARMTH",
KRAMPUS = "STOP! THIEF!",
KRAMPUS_SACK = "STORAGE MODULE 2.0",
LEIF = "WARNING: MOTILE TREE",
LEIF_SPARSE = "WARNING: MOTILE TREE",
LIGHTNING_ROD =
{
CHARGED = "BACKUP POWER",
GENERIC = "SURGE PROTECTION",
},
LITTLE_WALRUS = "PATHETIC",
LIVINGLOG = "EVEN WORSE THAN A NORMAL LOG",
LOCKEDWES = "SILENT HUMAN TRAPPED BY STATUES",
LOG =
{
BURNING = "IT IS AFLAME",
GENERIC = "LOG(1) = 0",
},
LUREPLANT = "AWW, IT'S JUST AS EVIL AS I AM.",
LUREPLANTBULB = "THE POWER TO START LIFE.",
MALE_PUPPET = "HE APPEARS TO BE TRAPPED.",
MANDRAKE =
{
DEAD = "I HAVE KILLED IT. GOOD.",
GENERIC = "IT IS A PLANT",
PICKED = "WHAT DO YOU WANT?",
},
MANDRAKESOUP = "UPGRADED FOOD MATERIAL",
MANDRAKE_COOKED = "I HAVE KILLED IT TWICE. HA.",
MARBLE = "I SHOULD BUILD A STATUE OF MYSELF.",
MARBLEPILLAR = "CRUMBLING REMAINS. HAH.",
MARBLETREE = "LOOKS LIKE A VERY TOUGH TREE.",
MARSH_BUSH =
{
BURNING = "THORNS BURNED.",
GENERIC = "BRAMBLES.",
PICKED = "BRAMBLES FIGHT BACK.",
},
MARSH_PLANT = "IT IS AN UNINTERESTING PLANT",
MARSH_TREE =
{
BURNING = "SPIKY TREE IGNITED",
BURNT = "THE SPIKY TREE IS NO MORE",
CHOPPED = "SPIKY TREE DEFEATED",
GENERIC = "A SPIKY TREE",
},
MAXWELL = "HE IS UNKNOWN",
MAXWELLHEAD = "IT APPEARS TO BE SOME SORT OF PROJECTION.",
MAXWELLLIGHT = "THEY SENSE MY PRESENCE.",
MAXWELLLOCK = "KEY RECEPTACLE.",
MAXWELLTHRONE = "MADE FOR SITTING.",
MEAT = "I WILL ENJOY THIS",
MEATBALLS = "UPGRADED FOOD MATERIAL",
MEATRACK =
{
DONE = "I HAVE NEW PROTEINS",
DRYING = "MEATSACKS TAKE TIME TO DRY",
GENERIC = "I SHOULD HANG EXPIRED MEATSACKS HERE",
},
MEAT_DRIED = "DEHYDRATED PROTEINS",
MERM = "ANIMATED SEAFOOD",
MERMHEAD = "THE FISHBEAST IS MORE IDIOTIC LOOKING THAN USUAL.",
MERMHOUSE = "OUTDATED ABODE",
MINERHAT = "SUPPORTS HANDS-FREE OPERATION",
MONKEY = "AN EVEN DUMBER HUMANOID.",
MONKEYBARREL = "WHAT A PITIFUL HOME.",
MONSTERLASAGNA = "UPGRADED FOOD MATERIAL",
MONSTERMEAT = "IT IS INCOMPATIBLE WITH MY CHEMICAL ENGINE",
MONSTERMEAT_DRIED = "DEHYDRATED PROTEINS",
MOSQUITO =
{
GENERIC = "IT STEALS LIFE FROM OTHERS",
HELD = "FILLED WITH DISGUSTING FLUIDS",
},
MOSQUITOSACK = "MOSQUITO HARD DRIVE",
MOUND =
{
DUG = "WORMS AND ICHOR",
GENERIC = "MEATLINGS ARE SO SUPERSTITIOUS",
},
NIGHTLIGHT = "UNKNOWN LIGHT SOURCE",
NIGHTMAREFUEL = "DEBUGGING RESIDUE",
NIGHTSWORD = "I CAN HACK THIS WORLD",
NITRE = "SOME ROCKS ARE BETTER THAN OTHERS",
ONEMANBAND = "AN EXTERNAL SOUND MODULE UPGRADE.",
PANDORASCHEST = "CONTENTS PROBABILITIES ARE UNCERTAIN",
PANFLUTE = "I CAN REBOOT FLESHLINGS WITH THIS",
PAPYRUS = "I PREFER DOT MATRIX PAPER",
PENGUIN = "BIRD CANNOT FLY?",
PERD = "THAT IS AN UNUSUALLY LARGE BIRD",
PEROGIES = "UPGRADED FOOD MATERIAL",
PETALS = "I HAVE DESTROYED SOMETHING BEAUTIFUL. HA.",
PETALS_EVIL = "IT WASN'T BEAUTIFUL, BUT I STILL DESTROYED IT. HA.",
PICKAXE = "MINING IMPLEMENT DETECTED",
PIGGYBACK = "UPGRADED STORAGE MODULE V2.0",
PIGHEAD = "THAT PIG WILL FEEL SILLY WHEN HE NOTICES HE HAS LOST HIS HEAD MODULE.",
PIGHOUSE =
{
FULL = "OCCUPIED",
GENERIC = "THE FURNITURE IS ALL PIG-SHAPED",
LIGHTSOUT = "THE OCCUPANT MUST BE SLEEPING",
},
PIGKING = "THAT APPEARS TO BE THE DOMINANT PIG",
PIGMAN =
{
DEAD = "OOPS",
FOLLOWER = "DO MY BIDDING",
GENERIC = "THEY EXHIBIT MINIMAL INTELLIGENCE",
GUARD = "DEFENSIVE STANCE DETECTED.",
WEREPIG = "ERROR: ANOMALY!",
},
PIGSKIN = "THESE FLESHLINGS ARE DISGUSTING",
PIGTENT = "TENT",
PIGTORCH = "IT GIVES HIM PURPOSE",
PINECONE =
{
GENERIC = "HOW DOES THE TREE FIT IN THERE?",
PLANTED = "SOON THE TREE WILL GROW.",
},
PITCHFORK = "I ENJOY ITS POINTY PARTS",
PLANTMEAT = "A SURPRISINGLY HIGH AMOUNT OF PROTEIN.",
PLANTMEAT_COOKED = "I MADE IT BETTER.",
PLANT_NORMAL =
{
GENERIC = "IT LOOKS EDIBLE",
GROWING = "GO FASTER, PLANT",
READY = "IT IS AT PEAK NUTRITIONAL VALUE",
},
POMEGRANATE = "IT IS DIFFICULT TO PEEL",
POMEGRANATE_COOKED = "DELECTABLE",
POMEGRANATE_SEEDS = "IT'S LIKE SOURCE CODE FOR PLANTS",
POND = "ERROR. STAY AWAY.",
POOP = "THESE ANIMALS ARE DISGUSTING",
PUMPKIN = "IT HAS A PLEASING SHAPE",
PUMPKINCOOKIE = "I HAVE FLATTENED THE SHAPE",
PUMPKIN_COOKED = "DELICIOUS",
PUMPKIN_LANTERN = "IT HAS AN EERIE LIGHT",
PUMPKIN_SEEDS = "IT'S LIKE SOURCE CODE FOR PLANTS",
PURPLEAMULET = "I HAVE CREATED THE PERFECT AMULET.",
PURPLEGEM = "IT IS STRANGE",
RABBIT =
{
GENERIC = "IT IS PERFORMING A SEARCH ALGORITHM",
HELD = "I HOLD ITS TINY LIFE IN MY HANDS",
},
RABBITHOLE = "THEY ARE ALL CONNECTED VIA UNDERGROUND TUNNELS",
RAINOMETER = "WELCOME, BROTHER.",
RATATOUILLE = "UPGRADED FOOD MATERIAL",
RAZOR = "EXFOLIATE!",
REDGEM = "IT IS SLIGHTLY WARM",
RED_CAP = "POISONOUS FUNGUS",
RED_CAP_COOKED = "MODIFIED FUNGUS",
RED_MUSHROOM =
{
GENERIC = "RED FUNGUS",
INGROUND = "IT IS HIDING",
PICKED = "I TOOK IT.",
},
REEDS =
{
BURNING = "TOO HOT",
GENERIC = "USEFUL MATERIALS DETECTED",
PICKED = "REGROWTH REQUIRED",
},
RELIC =
{
GENERIC = "I HAVE NO NEED OF THIS.",
BROKEN = "UNFUNCTIONAL.",
},
RUBBLE = "A DISMANTELD RELIC.",
RESEARCHLAB = "MOTHER?",
RESEARCHLAB2 = "HELLO, FRIEND",
RESEARCHLAB3 = "PERHAPS IT IS TOO POWERFUL.",
RESURRECTIONSTATUE = "WHO IS THAT?",
RESURRECTIONSTONE = "DO YOU BELIEVE IN MAGIC?",
ROBIN =
{
GENERIC = "GREETINGS, RED BIRD",
HELD = "SQUASH!",
},
ROBIN_WINTER =
{
GENERIC = "A FOOLISH BIRD",
HELD = "JUST A FEATHERY BLOB",
},
ROBOT_PUPPET = "BROTHER! WHAT HAVE THEY DONE TO YOU?",
ROCK_LIGHT =
{
GENERIC = "A PIT OF CRUSTED LAVA",
OUT = "IT NEEDS TO BE REBOOTED",
LOW = "WARNING: LAVAL LEVEL LOW",
NORMAL = "THIS LAVA PIT IS FULLY OPERATIONAL",
},
ROCK = "LUMPY",
ROCKS = "I WILL REFINE THESE INTO HIGH TECHNOLOGY",
ROOK = "ROOK AUTOMATON",
ROPE = "IT IS LESS USEFUL THAN IT APPEARS",
ROTTENEGG = "I AM GLAD I CAN NOT SMELL",
SANITYROCK =
{
ACTIVE = "IT IS CARVED WITH PERFECTION.",
INACTIVE = "SEEMS SMALLER THAN PREVIOUS DATA INDICATES",
},
SAPLING =
{
BURNING = "RESOURCES WASTED",
GENERIC = "POTENTIAL CONSTRUCTION MATERIAL",
PICKED = "IT IS RECHARGING",
},
SEEDS = "IT'S LIKE SOURCE CODE FOR PLANTS",
SEEDS_COOKED = "THEY CAN NO LONGER GERMINATE",
SEWING_KIT = "IT JOINS COMPONENTS OF FIBRE TOGETHER",
SHOVEL = "IT HAS MANY USES",
SILK = "SPIDER INNARDS",
SKELETON = "HAH, IT DIED. CLASSIC HUMAN MISTAKE.",
SKULLCHEST = "THIS MAKES ME LAUGH",
SMALLBIRD =
{
GENERIC = "IT LOOKS PATHETIC",
HUNGRY = "IT REQUIRES INPUT",
STARVING = "IT IS ALMOST OUT OF FUEL",
},
SMALLMEAT = "IT TASTES LIKE REVENGE",
SMALLMEAT_DRIED = "DEHYDRATED PROTEINS",
SPEAR = "BRING IT, FLESHLINGS",
SPIDER =
{
DEAD = "I WIN",
GENERIC = "THREAT DETECTED",
SLEEPING = "IT IS VULNERABLE",
},
SPIDERDEN = "SPIDER SOURCE DETECTED",
SPIDEREGGSACK = "SPIDER POTENTIAL = 6",
SPIDERGLAND = "I HARVESTED ITS ORGANS",
SPIDERHAT = "IT WIRELESSLY TRANSMITS THOUGHTS TO SPIDERS",
SPIDERQUEEN = "THE SPIDERS LIVE UNDER A SYSTEM OF MONARCHY",
SPIDER_WARRIOR =
{
DEAD = "I WIN",
GENERIC = "HEIGHTENED THREAT DETECTED",
SLEEPING = "THREAT SUSPENDED",
},
SPOILED_FOOD = "EVEN I CAN NOT PROCESS THAT",
STATUEHARP = "SOMEONE FORGOT TO INSTALL THE HEAD MODULE.",
STATUEMAXWELL = "HIGH LEVELS OF EVIL DETECTED.",
STINGER = "WARNING: TOXINS PRESENT",
STRAWHAT = "THIS WILL COVER MY PROCESSING UNIT",
STUFFEDEGGPLANT = "UPGRADED FOOD MATERIAL",
SUNKBOAT = "UNABLE TO UTILISE.",
SWEATERVEST = "VEST HAS HIGH DAPPERNESS QUOTIENT",
TAFFY = "STICKY AND SWEET. LOW NUTRITIONAL VALUE DETECTED.",
TALLBIRD = "IT LOOKS TERRITORIAL",
TALLBIRDEGG = "IS IT STILL ALIVE?",
TALLBIRDEGG_COOKED = "IT IS NO LONGER ALIVE",
TALLBIRDEGG_CRACKED =
{
COLD = "IT REQUIRES WARMTH",
GENERIC = "CRACK DETECTED",
HOT = "IT CAN NOT VENT EXCESS HEAT",
LONG = "LIFE IS AN ANNOYINGLY SLOW PROCESS",
SHORT = "SOMETHING IS EMERGING",
},
TALLBIRDNEST =
{
GENERIC = "I WANT THAT EGG",
PICKED = "IT IS EMPTY",
},
TEENBIRD =
{
GENERIC = "ANGST DETECTED",
HUNGRY = "IT NEEDS FOOD",
STARVING = "IT IS STARTING TO BEHAVE IRRATIONALLY",
},
TELEPORTATO_BASE =
{
ACTIVE = "SOON I WILL BE FREE OF THIS FILTHY REALM",
GENERIC = "WHAT PRIMITIVE TECHNOLOGY",
LOCKED = "SOMETHING IS MISSING STILL",
PARTIAL = "I AM CERTAIN THIS WILL WORK",
},
TELEPORTATO_BOX = "THIS WOULD PROBABLY BLOW MY CIRCUITS",
TELEPORTATO_CRANK = "I'M MADE OF TOUGHER STUFF",
TELEPORTATO_POTATO = "REMINDS ME OF MY MOTHER",
TELEPORTATO_RING = "HOW DELIGHTFULLY INORGANIC",
TELESTAFF = "I WILL CALL IT THE MINION_MOVER_3000.",
TENT = "I CAN REBOOT IN THERE",
TENTACLE = "BIOLOGY IS DISGUSTING",
TENTACLESPIKE = "THIS IS VISCIOUSLY VISCOUS",
TENTACLESPOTS = "NOT FOR THE SQUEAMISH",
TENTACLE_PILLAR = "DOES NOT LOOK BETTER FROM THIS END",
TENTACLE_PILLAR_ARM = "DANGER! DANGER!",
TENTACLE_GARDEN = "SENSORS DETECT SOMETHING BENEATH",
TOPHAT = "SOPHISTICATED",
TORCH = "PRIMITIVE LIGHT SOURCE",
TRAP = "I AM ADEPT AT WEAVING",
TRAP_TEETH = "THIS WILL PUNCTURE MY ENEMIES' FEET",
TRAP_TEETH_MAXWELL = "TECHNOLOGY TURNED AGAINST ME",
TREASURECHEST = "EXTERNAL STORAGE UNIT",
TREECLUMP = "CLUMP",
TRINKET_1 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_10 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_11 = "HIS NAME IS HAL. HE IS MY FRIEND.",
TRINKET_12 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_2 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_3 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_4 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_5 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_6 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_7 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_8 = "USELESS JUNK FROM A BYGONE AGE",
TRINKET_9 = "USELESS JUNK FROM A BYGONE AGE",
TRUNKVEST_SUMMER = "TEMPERATURE CONTROL HOUSING",
TRUNKVEST_WINTER = "IMPROVED TEMPERATURE CONTROL HOUSING",
TRUNK_COOKED = "MEAT RENDERED INACTIVE. EXCELLENT.",
TRUNK_SUMMER = "CABLE UNPLUGGED",
TRUNK_WINTER = "CABLE IS MORE DISGUSTING AND HAIRY THAN NORMAL",
TURF_CARPETFLOOR = "CARPET GROUND",
TURF_CHECKERFLOOR = "MARBLE GROUND",
TURF_DIRT = "THE GROUND",
TURF_FOREST = "THE GROUND",
TURF_GRASS = "THE GROUND",
TURF_MARSH = "THE GROUND",
TURF_ROAD = "ROAD PIECE",
TURF_ROCKY = "THE GROUND",
TURF_SAVANNA = "THE GROUND",
TURF_WOODFLOOR = "WOOD GROUND",
TURKEYDINNER = "FESTIVE",
TWIGS = "STICKS",
UMBRELLA = "THIS WILL KEEP ME RUST-FREE.",
WAFFLES = "UPGRADED FOOD MATERIAL",
WALL_HAY = "THAT SEEMS SUBOPTIMAL",
WALL_HAY_ITEM = "NOT VERY GOOD DEFENSES",
WALL_STONE = "THAT MAKES ME FEEL SAFE",
WALL_STONE_ITEM = "STONE DEFENSES",
WALL_RUINS = "OLD BUT STILL FUNCTIONAL",
WALL_RUINS_ITEM = "POCKET STONER DEFENSE",
WALL_WOOD = "I AM SOMEWHAT REASSURED",
WALL_WOOD_ITEM = "WOODEN DEFENSES",
WALRUS = "I DON'T LIKE THE LOOK OF HIM",
WALRUSHAT = "SMELLS LIKE MAMMAL",
WALRUS_CAMP =
{
EMPTY = "WHERE ARE THEY?",
GENERIC = "I HEAR A FAINT OORKING",
},
WALRUS_TUSK = "IT WASN'T MUCH HELP TO ITS ORIGINAL OWNER",
WASPHIVE = "A BEAUTIFUL EXAMPLE OF EFFICIENCY",
WETGOOP = "UPGRADED FOOD MATERIAL",
WINTERHAT = "THIS WILL KEEP MY PROCESSOR FROM FREEZING",
WINTEROMETER = "HELLO, FRIEND.",
WORMHOLE =
{
GENERIC = "I WANT TO STEP ON IT",
OPEN = "THIS MEAT TUBE WILL SERVE MY PURPOSES",
},
ARMORRUINS = "ANCIENT SHEATHING",
BISHOP_NIGHTMARE = "THERE SEEMS TO BE A BUG IN ITS BELIEF CIRCUITS",
GREENAMULET = "ERROR: UNKNOWN", --Reduce cost of crafting
GREENGEM = "PRESSURE AND IMPURITIES HAVE PRODUCED PLEASING PERFECTION",
KNIGHT_NIGHTMARE = "REPROGRAMMING REQUIRED",
MINOTAUR = "THIS MEAT HAS A POINTY END", --Monster in labyrinth
MULTITOOL_AXE_PICKAXE = "A PRACTICAL TOOL", --Works as axe and pickaxe
NIGHTMARELIGHT = "AN ANCIENT OPTICAL WAVELENGTH EMITTER", --Lights that activate during nightmare.
NIGHTMARE_TIMEPIECE = --Keeps track of the nightmare cycle
{
WARN = "CYCLE MINIMUM HAS PASSED", --Before nightmare
WAXING = "INCREMENTAL INCREASE DETECTED", --Nightmare Phase first 33%
STEADY = "LEVELS ARE HIGH AND MONOTONIC", --Nightmare 33% - 66%
WANING = "THE CYCLE IS SUBSIDING", --Nightmare 66% +
DAWN = "LEVELS ARE LOW AND DIMINISHING", --After nightmare
CALM = "AT CYCLE MINIMUM", --calm phase
NOMAGIC = "FLUCTUATIONS AT UNDETECTIBLE LEVELS", --Place with no nightmare cycle.
},
ORANGESTAFF = "TEMPORAL DISPLACEMENT TECHNOLOGY", --Teleports player.
ROOK_NIGHTMARE = "LOOSE WIRING DETECTED",
RELIC = "I HAVE NO NEED OF THIS.", --Fixed relic
RUINS_RUBBLE = "REQUIRES RECONDITIONING", --Broken relic
RUINS_BAT = "A HIGH VELOCITY MASS INFLUENCE DEVICE",
RUINSHAT = "A HEAD-MOUNTED DYNAMIC DAMAGE MITIGATION DEVICE",
SPIDER_DROPPER = "VERTICAL SPIDER SOURCE DETECTED", --White spider that comes from the roof
THULECITE = "A MOST AESTHETICALLY PLEASING MINERAL",
YELLOWAMULET = "INCANDECENCE AT 5200000000000000Hz", --Emits light, player walks faster.
ACCOMPLISHMENT_SHRINE = "I AM GOOD AT REPEATING TASKS",
LIVINGTREE = "NATURE NEVER CEASES TO ANNOY ME",
ICESTAFF = "ITS MOLECULES ARE BARELY MOVING",
},
DESCRIBE_GENERIC = "ERROR: UNKNOWN",
DESCRIBE_TOODARK = "INSUFFICIENT ILLUMINATION",
EAT_FOOD =
{
TALLBIRDEGG_CRACKED = "TRACES OF BEAK DETECTED",
},
}
|
pcall(require, 'impatient')
vim.g.did_load_filetypes = 1
vim.g.loaded_matchparen = 1
vim.g.loaded_zipPlugin = 1
vim.g.loaded_zip = 1
vim.g.mapleader = ' '
vim.g.maplocalleader = ' '
local backupdir = vim.fn.stdpath('data') .. '/backup'
local swapdir = vim.fn.stdpath('data') .. '/swap'
local undodir = vim.fn.stdpath('data') .. '/undo'
vim.fn.mkdir(backupdir, 'p')
vim.fn.mkdir(swapdir, 'p')
vim.fn.mkdir(undodir, 'p')
vim.opt.backupdir = backupdir
vim.opt.directory = swapdir
vim.opt.undodir = undodir
-- Ignore compiled files
vim.opt.wildignorecase = true
vim.opt.wildignore = {"__pycache__", "*.o", "*~", "*.pyc", "*pycache*"}
vim.opt.wildmode = {"longest", "list", "full"}
-- Cool floating window popup menu for completion on command line
vim.opt.pumblend = 17
vim.opt.wildmode = vim.opt.wildmode - "list"
vim.opt.wildmode = vim.opt.wildmode + {"longest", "full"}
vim.opt.wildoptions = "pum"
vim.opt.showmode = false
vim.opt.showcmd = true
vim.opt.cmdheight = 1 -- Height of the command bar
vim.opt.incsearch = true -- Makes search act like search in modern browsers
vim.opt.showmatch = true -- show matching brackets when text indicator is over them
vim.opt.relativenumber = true -- Show line numbers
vim.opt.number = true -- But show the actual number for the line we're on
vim.opt.ignorecase = true -- Ignore case when searching...
vim.opt.smartcase = true -- ... unless there is a capital letter in the query
vim.opt.hidden = true -- I like having buffers stay around
vim.opt.cursorline = true -- Highlight the current line
vim.opt.equalalways = true
vim.opt.splitright = true -- Prefer windows splitting to the right
vim.opt.splitbelow = true -- Prefer windows splitting to the bottom
vim.opt.updatetime = 300 -- Make updates happen faster
vim.opt.redrawtime = 10000 -- for syntax loading on large files
vim.opt.hlsearch = true -- I wouldn't use this without my DoNoHL function
vim.opt.scrolloff = 10 -- Make it so there are always ten lines below my cursor
-- Tabs
vim.opt.autoindent = true
vim.opt.cindent = true
vim.opt.wrap = false
vim.opt.tabstop = 4
vim.opt.shiftwidth = 4
vim.opt.softtabstop = 4
vim.opt.expandtab = true
vim.opt.breakindent = true
vim.opt.showbreak = string.rep(" ", 3) -- Make it so that long lines wrap smartly
vim.opt.linebreak = true
vim.opt.foldmethod = "marker"
vim.opt.foldlevel = 3
vim.opt.modelines = 1
vim.opt.belloff = "all" -- Just turn the dang bell off
vim.opt.clipboard = "unnamedplus"
vim.opt.inccommand = "split"
vim.opt.shada = {"!", "'1000", "<50", "s10", "h"}
vim.opt.mouse = "n"
-- Helpful related items:
-- 1. :center, :left, :right
-- 2. gw{motion} - Put cursor back after formatting motion.
--
-- TODO: w, {v, b, l}
vim.opt.formatoptions = vim.opt.formatoptions - "a" -- Auto formatting is BAD.
- "t" -- Don't auto format my code. I got linters for that.
+ "c" -- In general, I like it when comments respect textwidth
+ "q" -- Allow formatting comments w/ gq
- "o" -- O and o, don't continue comments
+ "r" -- But do continue when pressing enter.
+ "n" -- Indent past the formatlistpat, not underneath it.
+ "j" -- Auto-remove comments if possible.
- "2" -- I'm not in gradeschool anymore
-- set joinspaces
vim.opt.joinspaces = false -- Two spaces and grade school, we're done
-- set fillchars=eob:~
vim.opt.fillchars = {eob = "~"}
-- invisible characters to use on ':set list'
vim.opt.list = true
vim.opt.listchars = {tab = '› ', eol = '¬', nbsp = '.', trail = '•', extends = '#'}
require 'sh.filetypes'
require 'sh.mappings'
require 'sh.plugins'
|
local function isBlunt(item)
if not item:isWeapon() then return false end
for k,v in ipairs(item.subtype.attacks) do
if v.edged then return false end
end
return true
end
local function activateArtifactChanges()
local eventful=require('plugins.eventful')
eventful.enableEvent(eventful.eventType['ITEM_CREATED'],4)
eventful.onItemCreated.fantasticArtifactP=function(item_id)
local item=df.item.find(item_id)
--check if item is eligible for this particular function
if item.flags.artifact and (item:isWeapon() or item:getEffectiveArmorLevel()<2) then
local matInfo
--check if blunt or not; if blunt, set matInfo (defined above) to the blunt artifact mat, else sharp/armor artifact mat
if isBlunt(item) then
matinfo=dfhack.matinfo.find('ARTIFACT_BLUNT_P')
else
matinfo=dfhack.matinfo.find('ARTIFACT_SHARP_ARMOR_P')
end
item:setMaterial(matInfo.type)
item:setMaterialIndex(matinfo.index)
end
end
end
activateArtifactChanges()
|
local Engine = Xile.class()
Xile.Engine = Engine
Engine.__call = function(self,...) return self:item(...) end
local List = Xile.List
local from = Xile.from
function Engine:init(engineCache)
local _system = {update=List(),draw=List(),touched=List(),collide=List()}
local _sysqry = from(_system):keys()
local _cache = engineCache
local entity_update = function(sender,e)
_cache:update(sender)
end
local isSystem = function(system)
return Xile.type.is(system,Xile.System)
end
local isEntity = function(entity)
return Xile.type.is(entity,Xile.Entity)
end
local addSystem = function(system)
_sysqry:each(function(k)
local sys = _system[k]
if system[k] ~= nil and sys:contains(system) == false then
sys:add(system)
end
end)
system:attach(self)
end
local removeSystem = function(system)
system:detach(self)
_sysqry:each(function(k)
local sys = _system[k]
if system[k] ~= nil and sys:contains(system) == true then
sys:remove(system)
end
end)
end
local addEntity = function(entity)
_cache:add(entity)
end
local removeEntity = function(entity)
_cache:remove(entity)
end
self.add = function(self,...)
local arg = {...}
from(arg):each(function(entity_or_system)
if isEntity(entity_or_system) == true then
addEntity(entity_or_system)
elseif isSystem(entity_or_system) == true then
addSystem(entity_or_system)
end
end)
return self
end
self.remove = function(self,...)
local arg = {...}
from(arg):each(function(entity_or_system)
if isEntity(entity_or_system) == true then
removeEntity(entity_or_system)
elseif isSystem(entity_or_system) == true then
removeSystem(entity_or_system)
end
end)
return self
end
self.item = function(self,...)
return _cache(...)
end
_sysqry:extend(function(k)
local system = _system[k]
return k,function(self,...)
local sys
for i=1, system:count() do
sys = system:item(i)
sys[k](sys,...)
end
end
end,self)
end
|
--
-- codeblocks_cbp.lua
-- Generate a Code::Blocks C/C++ project.
-- Copyright (c) 2009 Jason Perkins and the Premake project
--
function premake.codeblocks_cbp(prj)
-- alias the C/C++ compiler interface
local cc = premake.gettool(prj)
_p('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>')
_p('<CodeBlocks_project_file>')
_p(1,'<FileVersion major="1" minor="6" />')
-- write project block header
_p(1,'<Project>')
_p(2,'<Option title="%s" />', premake.esc(prj.name))
_p(2,'<Option pch_mode="2" />')
_p(2,'<Option compiler="%s" />', _OPTIONS.cc)
-- build a list of supported target platforms; I don't support cross-compiling yet
local platforms = premake.filterplatforms(prj.solution, cc.platforms, "Native")
for i = #platforms, 1, -1 do
if premake.platforms[platforms[i]].iscrosscompiler then
table.remove(platforms, i)
end
end
-- write configuration blocks
_p(2,'<Build>')
for _, platform in ipairs(platforms) do
for cfg in premake.eachconfig(prj, platform) do
_p(3,'<Target title="%s">', premake.esc(cfg.longname))
_p(4,'<Option output="%s" prefix_auto="0" extension_auto="0" />', premake.esc(cfg.buildtarget.fullpath))
_p(4,'<Option object_output="%s" />', premake.esc(cfg.objectsdir))
-- identify the type of binary
local types = { WindowedApp = 0, ConsoleApp = 1, StaticLib = 2, SharedLib = 3 }
_p(4,'<Option type="%d" />', types[cfg.kind])
_p(4,'<Option compiler="%s" />', _OPTIONS.cc)
if (cfg.kind == "SharedLib") then
_p(4,'<Option createDefFile="0" />')
_p(4,'<Option createStaticLib="%s" />', iif(cfg.flags.NoImportLib, 0, 1))
end
-- begin compiler block --
_p(4,'<Compiler>')
for _,flag in ipairs(table.join(cc.getcflags(cfg), cc.getcxxflags(cfg), cc.getdefines(cfg.defines), cfg.buildoptions)) do
_p(5,'<Add option="%s" />', premake.esc(flag))
end
if not cfg.flags.NoPCH and cfg.pchheader then
_p(5,'<Add option="-Winvalid-pch" />')
_p(5,'<Add option="-include "%s"" />', premake.esc(cfg.pchheader))
end
for _,v in ipairs(cfg.includedirs) do
_p(5,'<Add directory="%s" />', premake.esc(v))
end
_p(4,'</Compiler>')
-- end compiler block --
-- begin linker block --
_p(4,'<Linker>')
for _,flag in ipairs(table.join(cc.getldflags(cfg), cfg.linkoptions)) do
_p(5,'<Add option="%s" />', premake.esc(flag))
end
for _,v in ipairs(premake.getlinks(cfg, "all", "directory")) do
_p(5,'<Add directory="%s" />', premake.esc(v))
end
for _,v in ipairs(premake.getlinks(cfg, "all", "basename")) do
_p(5,'<Add library="%s" />', premake.esc(v))
end
_p(4,'</Linker>')
-- end linker block --
-- begin resource compiler block --
if premake.findfile(cfg, ".rc") then
_p(4,'<ResourceCompiler>')
for _,v in ipairs(cfg.includedirs) do
_p(5,'<Add directory="%s" />', premake.esc(v))
end
for _,v in ipairs(cfg.resincludedirs) do
_p(5,'<Add directory="%s" />', premake.esc(v))
end
_p(4,'</ResourceCompiler>')
end
-- end resource compiler block --
-- begin build steps --
if #cfg.prebuildcommands > 0 or #cfg.postbuildcommands > 0 then
_p(4,'<ExtraCommands>')
for _,v in ipairs(cfg.prebuildcommands) do
_p(5,'<Add before="%s" />', premake.esc(v))
end
for _,v in ipairs(cfg.postbuildcommands) do
_p(5,'<Add after="%s" />', premake.esc(v))
end
_p(4,'</ExtraCommands>')
end
-- end build steps --
_p(3,'</Target>')
end
end
_p(2,'</Build>')
-- begin files block --
local pchheader
if (prj.pchheader) then
pchheader = path.getrelative(prj.location, prj.pchheader)
end
for _,fname in ipairs(prj.files) do
_p(2,'<Unit filename="%s">', premake.esc(fname))
if path.isresourcefile(fname) then
_p(3,'<Option compilerVar="WINDRES" />')
elseif path.iscfile(fname) and prj.language == "C++" then
_p(3,'<Option compilerVar="CC" />')
end
if not prj.flags.NoPCH and fname == pchheader then
_p(3,'<Option compilerVar="%s" />', iif(prj.language == "C", "CC", "CPP"))
_p(3,'<Option compile="1" />')
_p(3,'<Option weight="0" />')
_p(3,'<Add option="-x c++-header" />')
end
_p(2,'</Unit>')
end
-- end files block --
_p(2,'<Extensions />')
_p(1,'</Project>')
_p('</CodeBlocks_project_file>')
_p('')
end
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Administrator.
--- DateTime: 18-9-18 下午4:03
---
tree = {}
tree[1] = {x = 0, y = 0, links = {2}}
tree[2] = {x = 48, y = 0, stats = {'4% Increased HP', 'hp_multiplier', 0.04}, links = {3}}
tree[3] = {x = 96, y = 0, stats = {'6% Increased HP', 'hp_multiplier', 0.06}, links = {4}}
tree[4] = {x = 144, y = 0, stats = {'4% Increased HP', 'hp_multiplier', 0.04}}
local ui_input = {text = "Hello"}
local chk = {text = "check"}
local slider = {value = 0.5,min = -2,max = 2}
--- @class SkillTree : GameObject
SkillTree = Object:extend()
function SkillTree:new()
self.area = Area(self)
self.tree = table.copy(tree)
p_print(tree)
self.nodes = {}
self.lines = {}
--self.timer = Timer()
self.main_canvas = love.graphics.newCanvas(gw,gh)
--camera.x = gw/2
--camera.y = gh/2
for id,node in ipairs(self.tree) do
for _,linked_node_id in ipairs(node.links or {}) do
table.insert(self.tree[linked_node_id],id)
end
end
for id, node in ipairs(self.tree) do table.insert(self.nodes, Node(id, node.x, node.y)) end
for id, node in ipairs(self.tree) do
if node.links then
for _, linked_node_id in ipairs(node.links) do
table.insert(self.lines, Line(id, linked_node_id))
end
end
end
--- gooi
gooi.newButton({group = "SkillTree",text = "返回菜单", x = gw*sw - 80,y = gh*sh - 40})
:center()
:bg({1,1,1,0.1})
:onRelease(
function()
gotoRoom("StageMain","StageMain")
gooi.setGroupEnabled("StageTree",false)
gooi.setGroupVisible("StageTree",false)
gooi.setGroupEnabled("StageMain",true)
gooi.setGroupVisible("StageMain",true)
end
)
end
function SkillTree:update(dt)
for _, node in ipairs(self.nodes) do
node:update(dt)
end
for _, line in ipairs(self.lines) do
line:update(dt)
end
if love.mouse.isDown(1) then
local mx,my = camera:getMousePosition(sw,sh,0,0,sw * gw,sh * gh)
local dx,dy = mx - self.previous_mx,my - self.previous_my
--- when camera scale, x,y position should / scale
camera:move(-dx/sw,-dy/sh)
end
self.previous_mx,self.previous_my = camera:getMousePosition(sw,sh,0,0,sw * gw,sh * gh)
if input:pressed("zoom_in") then
timer:tween(0.2,camera,{scale = camera.scale + 0.4},'in-out-cubic')
end
if input:pressed("zoom_out") then
timer:tween(0.2,camera,{scale = camera.scale - 0.4},'in-out-cubic')
end
end
function SkillTree:draw()
love.graphics.setCanvas(self.main_canvas)
love.graphics.clear()
local font = Fonts.unifont
love.graphics.setFont(font)
love.graphics.print({{1,0,0},"科技树"},gw*sw/2 - 20,0,0,sw,sh)
camera:attach()
--- sp
love.graphics.setColor(Color.skill_point)
if self.area then self.area:draw() end
---- draw line
for _, line in ipairs(self.lines) do
line:draw()
end
for _, node in ipairs(self.nodes) do
node:draw()
end
--- draw node
for _,node in ipairs(self.nodes) do
if node.hot and tree[node.id].stats then
local stats = tree[node.id].stats
--- get max text width
local max_text_width = 0
for i=1,#stats,3 do
if font:getWidth(stats[i]) > max_text_width then
max_text_width = font:getWidth(stats[i])
end
end
--- draw rectangle
local mx,my = camera:getMousePosition(sw*camera.scale,sh*camera.scale,0,0,sw * gw,sh * gh)
--local mx,my = love.mouse.getPosition()
mx,my = mx/sw,my/sh
--p_print(mx,my)
love.graphics.setColor(1,0,0,0.8)
love.graphics.rectangle('fill',mx,my
,16 + max_text_width,font:getHeight() + #stats/3 * font:getHeight())
--- draw text
love.graphics.setColor(Color.default)
for i = 1,#stats,3 do
love.graphics.print(stats[i]
,math.floor(mx + 8),math.floor(my + font:getHeight()/2 + math.floor(i/3) * font:getHeight()))
end
end
end
camera:detach()
love.graphics.print('科技 : ' .. skill_points.left,0,0)
love.graphics.setColor(1,1,1)
love.graphics.setCanvas()
--love.graphics.setBlendMode('alpha','premultiplied')
love.graphics.draw(self.main_canvas,0,0,0,sw,sh)
love.graphics.print({{1,0,0},mx,{0,1,1},my},gw/2,gh/2)
gooi.draw("SkillTree")
end
function SkillTree:canNodeBeBought(id)
for _,linked_node_id in ipairs(self.tree[id]) do
if fn.any(bought_node_indexes,linked_node_id) then return true end
end
end
function SkillTree:keypressed(key)
p_print("key pressed")
end
|
--
-- Please see the license.txt file included with this distribution for
-- attribution and copyright information.
--
function onInit()
powergroup.onValueChanged = onGroupChanged;
end
function update(bLocked)
displaygroup.setReadOnly(bLocked);
powergroup.setReadOnly(bLocked);
if bLocked then
displaygroup.setFrame(nil);
powergroup.setFrame(nil);
else
displaygroup.setFrame("fielddark", 7, 5, 7, 5);
powergroup.setFrame("fielddark", 7, 5, 7, 5);
end
end
function onGroupChanged(sGroup)
local nodeItem = getDatabaseNode();
local sGroup = powergroup.getValue()
for _,nodePower in pairs(DB.getChildren(nodeItem, "powers")) do
DB.setValue(nodePower, "group", "string", sGroup);
end
end
|
--[[
Copyright (C) Udorn (Blackhand)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
vendor.ScannerItemModel = {}
vendor.ScannerItemModel.prototype = {}
vendor.ScannerItemModel.metatable = {__index = vendor.ScannerItemModel.prototype}
local L = vendor.Locale.GetInstance()
local log = vendor.Debug:new("ScannerItemModel")
-- the identifiers of the supported columns
vendor.ScannerItemModel.TEXTURE = 1
vendor.ScannerItemModel.NAME = 2
vendor.ScannerItemModel.COUNT = 3
vendor.ScannerItemModel.BID = 5
vendor.ScannerItemModel.BUYOUT = 6
vendor.ScannerItemModel.REASON = 7
vendor.ScannerItemModel.ITEM_LEVEL = 8
-- the several sort functions
local SORT_FUNCS = {
[vendor.ScannerItemModel.COUNT] = {
[true] = function(a, b)
return a.count < b.count
end,
[false] = function(a, b)
return a.count > b.count
end
},
[vendor.ScannerItemModel.NAME] = {
[true] = function(a, b)
return a.name < b.name
end,
[false] = function(a, b)
return a.name > b.name
end
},
[vendor.ScannerItemModel.ITEM_LEVEL] = {
[true] = function(a, b)
return a.itemLevel < b.itemLevel
end,
[false] = function(a, b)
return a.itemLevel > b.itemLevel
end
},
[vendor.ScannerItemModel.BID] = {
[true] = function(a, b)
return (math.max(a.minBid, a.bidAmount) / a.count) < (math.max(b.minBid, b.bidAmount) / b.count)
end,
[false] = function(a, b)
return (math.max(a.minBid, a.bidAmount) / a.count) > (math.max(b.minBid, b.bidAmount) / b.count)
end
},
[vendor.ScannerItemModel.BUYOUT] = {
[true] = function(a, b)
local ab = a.buyout / a.count
if (ab == 0) then
ab = 999999999
end
local bb = b.buyout / b.count
if (bb == 0) then
bb = 999999999
end
return (ab < bb)
end,
[false] = function(a, b)
local ab = a.buyout / a.count
if (ab == 0) then
ab = 999999999
end
local bb = b.buyout / b.count
if (bb == 0) then
bb = 999999999
end
return (ab > bb)
end
},
[vendor.ScannerItemModel.REASON] = {
[true] = function(a, b)
return a.reasonSort < b.reasonSort
end,
[false] = function(a, b)
return a.reasonSort > b.reasonSort
end
}
}
--[[
Checks whether the list has to be sorted and does it in case.
--]]
local function _EnsureSorting(self)
if (not self.sorted) then
table.sort(self.index, self.sortFunc)
self.sorted = true
self.updateCount = self.updateCount + 1
end
end
--[[
Inits the table of descriptors.
--]]
local function _InitDescriptors(self)
self.descriptors = {
[vendor.ScannerItemModel.TEXTURE] = {type = "texture", title = L["Texture"], order = 1},
[vendor.ScannerItemModel.NAME] = {type = "text", align = "LEFT", weight = 35, minWidth = 60, sortable = true, title = L["Name"], order = 2},
[vendor.ScannerItemModel.COUNT] = {type = "number", align = "CENTER", weight = 10, minWidth = 20, sortable = true, title = L["Itms."], order = 4},
[vendor.ScannerItemModel.BID] = {type = "text", align = "RIGHT", weight = 20, minWidth = 70, sortable = true, title = L["Bid"], order = 6},
[vendor.ScannerItemModel.BUYOUT] = {type = "text", align = "RIGHT", weight = 20, minWidth = 70, sortable = true, title = L["Buyout"], order = 7},
[vendor.ScannerItemModel.REASON] = {type = "text", align = "LEFT", weight = 60, minWidth = 100, sortable = true, title = L["Reason"], order = 5},
[vendor.ScannerItemModel.ITEM_LEVEL] = {type = "text", align = "CENTER", weight = 10, minWidth = 50, sortable = true, title = L["ItmLev"], order = 3}
}
end
local function _Updated(self)
log:Debug("_Updated")
self.sorted = false
self.updateCount = self.updateCount + 1
log:Debug("notify")
for _,listener in pairs(self.updateListeners) do
listener.func(listener.arg)
end
log:Debug("_Updated exit")
end
--[[
Creates a new instance.
--]]
function vendor.ScannerItemModel:new(ignoreSnipers)
local instance = setmetatable({}, self.metatable)
instance.selectedIndex = {}
instance.index = {}
instance.rejected = {}
instance.updateCount = 0
instance.updateListeners = {}
instance.sniperIds = {}
instance.ignoreSnipers = ignoreSnipers
instance.player = UnitName("player")
_InitDescriptors(instance)
instance:Sort(vendor.ScannerItemModel.BUYOUT, true)
return instance
end
--[[
Adds a new item to the model.
--]]
function vendor.ScannerItemModel.prototype:AddItem(itemLink, itemLinkKey, name, texture, timeLeft, count, minBid, minIncrement, buyout, bidAmount, owner, reason, sniperId, index, quality, highBidder, reasonSort)
log:Debug("AddItem enter reason [%s] sniperId [%s] buyout [%s] quality [%s] ignoreSnipers [%s]", reason, sniperId, buyout, quality, self.ignoreSnipers)
local colorizedName = vendor.Format.ColorizeQuality(name, quality)
local info = {itemLinkKey = itemLinkKey, itemLink = itemLink, texture = texture, name = name, timeLeft = timeLeft, count = count, minBid = minBid, minIncrement = minIncrement, buyout = buyout or 0, bidAmount = bidAmount or 0, reason = reason or "", sniperId = sniperId, index = index, colorizedName = colorizedName, highBidder = highBidder, reasonSort = reasonSort or reason or "", owner = owner}
info.itemLevel = select(4, GetItemInfo(itemLink)) or 0
if (self.ignoreSnipers or (not sniperId or self.sniperIds[sniperId])) then
table.insert(self.index, info)
_Updated(self)
else
table.insert(self.rejected, info)
end
end
--[[
ItemModel function for returning the desired descriptor.
--]]
function vendor.ScannerItemModel.prototype:GetColumnDescriptor(id)
return self.descriptors[id]
end
--[[
Returns the number of items available.
--]]
function vendor.ScannerItemModel.prototype:Size()
return #self.index
end
function vendor.ScannerItemModel.prototype:GetItemLink(row)
_EnsureSorting(self)
if (row > #self.index) then
return
end
local info = self.index[row]
return info.itemLink
end
--[[
Returns the value(s) for the given row and column id.
--]]
function vendor.ScannerItemModel.prototype:GetValues(row, id)
_EnsureSorting(self)
if (row > #self.index) then
return
end
local info = self.index[row]
if (id == vendor.ScannerItemModel.TEXTURE) then
return info.texture, info.itemLink, info.count
elseif (id == vendor.ScannerItemModel.NAME) then
return info.colorizedName
elseif (id == vendor.ScannerItemModel.ITEM_LEVEL) then
return info.itemLevel
elseif (id == vendor.ScannerItemModel.COUNT) then
return info.count
elseif (id == vendor.ScannerItemModel.REASON) then
return info.reason
elseif (id == vendor.ScannerItemModel.BID) then
local bid = math.max(info.minBid, info.bidAmount)
local msg
if (info.count > 1) then
msg = vendor.Format.FormatMoneyValues(bid / info.count, bid, true)
else
msg = vendor.Format.FormatMoney(bid / info.count, true)
end
if (info.highBidder) then
msg = YOU.." "..msg
end
return msg
elseif (id == vendor.ScannerItemModel.BUYOUT) then
local msg
if (info.buyout > 0) then
if (info.count > 1) then
msg = vendor.Format.FormatMoneyValues(info.buyout / info.count, info.buyout, true)
else
msg = vendor.Format.FormatMoney(info.buyout / info.count, true)
end
end
return msg
else
error("unknown id: "..(id or "NA"));
end
return nil
end
--[[
Returns the auction data for the given row as
itemLinkKey, itemLink, texture, name, timeLeft, count, minBid, minIncrement, buyout, bidAmount, reason, sniperId, index
--]]
function vendor.ScannerItemModel.prototype:Get(row)
local info = self.index[row]
return info.itemLinkKey, info.itemLink, info.texture, info.name, info.timeLeft, info.count, info.minBid, info.minIncrement, info.buyout, info.bidAmount, info.reason, info.sniperId, info.index
end
--[[
Sorts according to the given column.
--]]
function vendor.ScannerItemModel.prototype:Sort(id, ascending)
vendor.Vendor:Debug("Sort id: %d ascending: %s", id, ascending)
local sortable = self.descriptors[id].sortable
if (sortable) then
self.sortFunc = SORT_FUNCS[id][ascending]
self.sorted = false
self.sortId = id
self.ascending = ascending
_EnsureSorting(self)
end
end
--[[
Toggles the sort state for the given type. If it's currently not
the sorting criteria, then it will be activated and set to ascending.
--]]
function vendor.ScannerItemModel.prototype:ToggleSort(id)
vendor.Vendor:Debug("ToggleSort id: %d", id)
if (id == self.sortId) then
self:Sort(id, not self.ascending)
else
self:Sort(id, true)
end
end
--[[
Returns the sorted id and whether it's ascending.
--]]
function vendor.ScannerItemModel.prototype:GetSortInfo()
return self.sortId, self.ascending
end
--[[
Selects the given item.
--]]
function vendor.ScannerItemModel.prototype:SelectItem(row, isSelected)
_EnsureSorting(self)
if (row <= #self.index) then
self.index[row].selected = isSelected
self.updateCount = self.updateCount + 1
end
end
--[[
Returns whether the given item was selected.
--]]
function vendor.ScannerItemModel.prototype:IsSelected(row)
if (row <= #self.index) then
return self.index[row].selected
end
return false
end
--[[
Returns the map with the indices of the selected items.
--]]
function vendor.ScannerItemModel.prototype:GetSelectedItems()
_EnsureSorting(self)
if (self.updateCount ~= self.selectedUpdateCount) then
wipe(self.selectedIndex)
for i=1,#self.index do
if (self.index[i].selected) then
table.insert(self.selectedIndex, i)
end
end
self.selectedUpdateCount = self.updateCount
end
return self.selectedIndex
end
--[[
Registers a function that will be called, if the model has been updated.
--]]
function vendor.ScannerItemModel.prototype:RegisterUpdateListener(func, arg)
table.insert(self.updateListeners, {func = func, arg = arg})
end
--[[
Remove all known items.
--]]
function vendor.ScannerItemModel.prototype:Clear()
wipe(self.index)
wipe(self.rejected)
_Updated(self)
end
--[[
Selects whether auctions of the given sniper should be visible. By default
a sniper is estimated to be invisible.
--]]
function vendor.ScannerItemModel.prototype:SetSniperVisibility(sniperId, isVisible)
log:Debug("SetSniperVisibility sniperId [%s] isVisible [%s]", sniperId, isVisible)
if (isVisible and not self.sniperIds[sniperId]) then
log:Debug("go visbible rejected [%s]", #self.rejected)
-- sniper switches to visible
self.sniperIds[sniperId] = true
for i=#self.rejected, 1, -1 do
local info = self.rejected[i]
if (sniperId == info.sniperId) then
table.remove(self.rejected, i)
table.insert(self.index, info)
_Updated(self)
end
end
elseif (not isVisible and self.sniperIds[sniperId]) then
log:Debug("go invisbible items [%s]", #self.index)
-- sniper switches to not visible
self.sniperIds[sniperId] = nil
for i=#self.index, 1, -1 do
local info = self.index[i]
if (sniperId == info.sniperId) then
table.remove(self.index, i)
table.insert(self.rejected, info)
_Updated(self)
end
end
end
end
--[[
Removes the given rows from the model
--]]
function vendor.ScannerItemModel.prototype:RemoveRows(rows)
table.sort(rows)
for i=#rows,1,-1 do
table.remove(self.index, rows[i])
end
_Updated(self)
end
--[[
Returns any highlight id for the given row.
--]]
function vendor.ScannerItemModel.prototype:GetHighlight(row)
local highlight
if (self.index) then
_EnsureSorting(self)
--local idx = self.index[row].idx
local info = self.index[row]
--local key, time, timeLeft, count, minBid, minIncrement, buyoutPrice, bidAmount, owner, highBidder = self.scanSet:Get(idx)
log:Debug("GetHighlight highBidder [%s] owner [%s]", info.highBidder, info.owner)
if (info.owner == self.player) then
log:Debug("owner highlight")
highlight = self.ownerHighlight
elseif (info.highBidder and (info.highBidder == true or info.highBidder == "1" or info.highBidder == 1)) then
log:Debug("return highlight [%s]", self.playerHasBidHighlight)
highlight = self.playerHasBidHighlight
end
end
log:Debug("return highlight [%s]", highlight)
return highlight
end
function vendor.ScannerItemModel.prototype:MakeUnique()
log:Debug("MakeUnique")
-- sort by buyout
local oldSortFunc = self.sortFunc
self.sortFunc = SORT_FUNCS[vendor.ScannerItemModel.BUYOUT][true]
self.sorted = nil
_EnsureSorting(self)
-- make table unique
local index = self.index
local n = #index
log:Debug("n [%s]", n)
for i=n,1,-1 do
local info = index[i]
local key = info.itemLinkKey
for j=i-1,1,-1 do
if (vendor.Items:MatchItemLinkKeys(key, index[j].itemLinkKey)) then
info = nil
break
end
end
if (not info) then
log:Debug("remove [%s]", i)
tremove(index, i)
end
end
-- restore previous sorting
self.sorted = nil
self.sortFunc = oldSortFunc
_Updated(self)
end
|
-- Stencilshadows
-- we generate a l3dshadowmodel from a given l3dmodel or l3dprimtive
-- l3dmodels must always have closed geometry
function addshadow(sun,hostl3d,alwaysvisible)
-- create the models in the second to last layer
-- it is important that shadowmodels are drawn
-- after regular geometry.
local shadow = l3dshadowmodel.new("shadow",
l3dset.get(0):layer(l3dlist.l3dlayercount()-2),sun,hostl3d)
-- shadow might be nil, in case the hostl3d was not a closed
-- mesh, or too many triangle/vertices
-- Unclosed meshes can also happen when you used
-- "multi-materials" in 3dsmax export, or when
-- different element's vertices overlap each other closely.
if (not shadow) then return end
-- and we link the model to the host
shadow:parent(hostl3d)
-- Be aware now that the shadowmodel is now only rendered when
-- the host is visible. Which might not be correct in cases
-- where the shadow volume is very long.
-- Therefore we can make sure the shadowmesh is alwas rendered
-- with enabling "novistest".
shadow:novistest(alwaysvisible)
hostl3d.l3dshadow = l3dshadow
end
-- do scene setup here
-- do not use layer(15), which is last one, for your stuff however!
-- as we want to use that one for drawing the shadows
-- you can also use it draw geometry "on top" of shadow
function buildscene ()
globalspace = dspacehash.new()
quad = scenenode.new("floor")
quad.l3d = l3dprimitive.newquadcentered("quad",15,15)
quad.l3d:linkinterface(quad)
quad.l3d:color(.2,.8,0,1)
quad.l3d:rfLitSun(true)
quad.geom = dgeomplane.new(0,0,1,0,globalspace)
cam = actornode.new("cam",8*.6,8*.6,9*.6)
cam.l3d = l3dcamera.default()
cam.l3d:linkinterface(cam)
cam:lookat(0,0,0, 0,0,1)
sun = actornode.new("sun",-20,-10,25)
sun.l3d = l3dlight.new("sun")
sun.l3d:linkinterface(sun)
sun.l3d:makesun()
sun.l3d:ambient(.3,.3,.3,1)
sun.l3d:diffuse(.7,.7,.7,1)
objects = {}
local function makebody(p)
local ac = actornode.new("obj")
ac.body = dbody.new()
ac.body:autodisable(true)
ac:link(ac.body)
if p.w then
ac.l3d = l3dprimitive.newbox("box",p.w,p.h,p.d)
ac.geom = dgeombox.new(p.w,p.h,p.d,globalspace)
ac.body:massbox(p.mass or 1, p.w, p.h, p.d,true)
else
ac.l3d = l3dprimitive.newsphere("sp",p.rad)
ac.geom = dgeomsphere.new(p.rad,globalspace)
ac.body:masssphere(p.mass or 1, p.rad,true)
end
ac.geom:maxcontacts(8)
ac.geom:body(ac.body)
ac.l3d:linkinterface(ac)
ac.l3d:rfLitSun(true)
local r,g,b = UtilFunctions.color3hsv(p.hue or 0,1,1)
ac.l3d:color(r,g,b,1)
ac.body:pos(p.x,p.y,p.z)
ac.body:addforce(p.fx or 0, p.fy or 0, p.fz or 0)
-- now lets add shadowmodel to the l3dprimitive
-- in our sample it's mostly okay to not set the
-- always visible flag
addshadow(sun.l3d,ac.l3d)
objects[#objects+1] = ac
if p.disabled then
ac.body:state(false)
end
end
makebody{rad=.4, x=0, y=4, z=.4, hue=0, fy=-6, mass=40}
local s = .4
for z=0.0,s*4,s do
for x=-2+z*.5,2-z*.5,s+.1 do
makebody{w=s,h=s,d=s, x=x,y=-1,z=z+s*.5,
hue= x/4+1, disabled=true}
end
end
dworld.autodisablesteps(1)
dworld.surfacebitsofterp(0,false)
dworld.surfacebitsoftcfm(0,false)
dworld.surfacemu(0,1.5)
dworld.cfm(.001)
dworld.erp(.6)
dworld.iterations(16)
dworld.contactsurfacelayer(.01)
dworld.gravity(0,0,-.01)
collectgarbage "collect"
end
buildscene()
Timer.set("tutorial",function ()
if not globalspace then return end
dworld.jointempty()
dworld.collidetest(globalspace)
dworld.makecontacts()
dworld.quickstep(1)
end,33)
Keyboard.setKeyBinding("r",buildscene)
Keyboard.setKeyBinding("s",
function ()
render.drawshadowvolumes(
not render.drawshadowvolumes()
)
end
)
-- set all stencil values to 127
-- we use 127 because stencil shadows do + and - and
-- it could be that some systems do not support wrapping
-- (ie 0-1 becomes 255)
-- so we start with 127 and are fairly safe
-- note that most hardware will support wrapped operations
view = UtilFunctions.simplerenderqueue()
view.rClear:stencilvalue(127)
-- now we want to do regular drawing but apply the stencil
-- shadows at the end before last layers are drawn
--
-- the default renderqueue looks like this
-- rClear (rcmdclear)
-- clears color,stencil and depth values for the viewport
-- rDrawbg (rcmddrawbg)
-- draws background stuff (skybox, images whatever)
-- rLayers[1 .. l3dlist.l3dlayercount()] for each l3dlayer
-- .stencil (rcmdstencil)
-- sets up stencil functions, only l3dnodes with
-- rfStenciltest(true) will be affected
-- .drawlayer (rcmddrawlayer)
-- renders the corresponding l3dlayerid with material sorting
-- enabled. [1] will render layer(0),
-- as internal values start at 0
-- .drawprt (rcmddrawprt)
-- renders the corresponding particle effects that are set to
-- be drawn in this layer
-- by default all particles are rendered in the last layer.
--
-- we use the stencilsetup for the layer that already exists in the
-- renderqueue
local ffxstencil = view.rLayers[l3dlist.l3dlayercount()].stencil
ffxstencil:scEnabled(true)
-- The l3dshadowmodel works in a fashion that any region in the
-- shadow will have a value that is not equal to the original
-- value (127). So we setup stenciltest to draw only in the
-- shadowed areas
ffxstencil:scFunction(comparemode.notequal(),comparemode.notequal(),
127,255)
-- we dont actually want to change stencil values, while drawing
-- so set everythin to keep
ffxstencil:scOperation(0,operationmode.keep(),
operationmode.keep(),operationmode.keep())
-- now draw a fullscreen quad into the view, that will darken
-- all areas in the shadow
local fullscrn = rcmddrawmesh.new()
-- enable stenciltest, so we only draw in shadow pixels
fullscrn:rfStenciltest(true)
-- we want to darken the areas in the shadow
-- so we set blendmode to modulate
fullscrn:rfBlend(true)
fullscrn:rsBlendmode(blendmode.modulate())
-- we set the color to slightly less than white
-- blendmode.modulate will do viewpixel * quad's colorpixel
-- so 0.8 will mean 80% of original brightness inside the shadow
fullscrn:color(0.4,0.4,0.4,1)
-- and finally we add it after the stencil command
-- into the view's renderqueue
-- if we would not have passed ffxstencil, the quad would be drawn
-- at the end of the queue, however want to keep the possibility to
-- render stuff unshadowed
view:rcmdadd(fullscrn,ffxstencil)
-- we can use "local" for fullscrn here, because
-- rcmdadd prevents garbage collection of any active rendercommands
|
-- #####################
-- stimulants
-- #####################
print("Loading mod: stimulants...")
dofile(minetest.get_modpath("stimulants").."/cannabis.lua")
dofile(minetest.get_modpath("stimulants").."/wine.lua")
|
return {
author = "Jet",
name = "StringUtility",
description = "Adds a bunch of new features for strings.",
version = "1.0.0"
}
|
function game.get_ammo_list()
local last_ammo_name = game.GetAmmoName(1)
local ammo_table = { last_ammo_name }
while last_ammo_name != nil do
last_ammo_name = game.GetAmmoName(table.insert(ammo_table, last_ammo_name))
end
return ammo_table
end
-- A function to check whether all of the arguments in vararg are valid (via IsValid).
function util.validate(...)
local validate = { ... }
if #validate <= 0 then return false end
for k, v in ipairs(validate) do
if !IsValid(v) then
return false
end
end
return true
end
-- A function to print C-style formatted strings.
function printf(str, ...)
print(Format(str, ...))
end
function util.to_b(value)
return (tonumber(value) == 1 or value == true or value == 'true')
end
function util.wait_for_ent(ent_index, callback, delay, wait_time)
local entity = Entity(ent_index)
if !IsValid(entity) then
local timer_name = CurTime()..'_ent_wait'
timer.Create(timer_name, delay or 0, wait_time or 100, function()
local entity = Entity(ent_index)
if IsValid(entity) then
callback(entity)
timer.Remove(timer_name)
end
end)
else
callback(entity)
end
end
function util.list_to_string(callback, separator, ...)
if !isfunction(callback) then
callback = function(obj) return tostring(obj) end
end
if !isstring(separator) then
separator = ', '
end
local list = { ... }
local result = ''
for k, v in ipairs(list) do
local text = callback(v)
if isstring(text) then
result = result..text
end
if k < #list then
result = result..separator
end
end
return result
end
function util.player_list_to_string(player_list)
local nlist = #player_list
if nlist > 1 and nlist == #_player.GetAll() then
return 'ui.chat.everyone'
end
return util.list_to_string(function(obj) return (IsValid(obj) and obj:name()) or 'Unknown Player' end, nil, unpack(player_list))
end
function util.remove_newlines(str)
local pieces = str:split()
local to_ret = ''
local skip = ''
for k, v in ipairs(pieces) do
if skip != '' then
to_ret = to_ret..v
if v == skip then
skip = ''
end
continue
end
if v == '"' then
skip = '"'
to_ret = to_ret..v
continue
end
if v == '\n' or v == '\t' then
continue
end
to_ret = to_ret..v
end
return to_ret
end
function txt(text)
local lines = (text or ''):chomp('\n'):split('\n')
local lowest_indent
local output = ''
for k, v in ipairs(lines) do
if v:match('^[%s]+$') then continue end
local indent = v:match('^([%s]+)')
if !indent then continue end
if !lowest_indent then lowest_indent = indent end
if indent:len() < lowest_indent:len() then
lowest_indent = indent
end
end
for k, v in ipairs(lines) do
output = output..v:trim_start(lowest_indent)..'\n'
end
return output:chomp(' '):chomp('\n')
end
function get_player_name(player)
return IsValid(player) and player:name() or 'Console'
end
function util.vector_obstructed(vec1, vec2, filter)
local trace = util.TraceLine({
start = vec1,
endpos = vec2,
filter = filter
})
return trace.Hit
end
function util.door_is_opened(entity)
if entity:is_door() then
local data = entity:GetSaveTable()
if data.m_toggle_state then
return data.m_toggle_state == 0
elseif data.m_eDoorState then
return data.m_eDoorState != 0
end
end
return false
end
local operators = {
equal = function(a, b)
return a == b
end,
unequal = function(a, b)
return a != b
end,
less = function(a, b)
return a < b
end,
greater = function(a, b)
return a > b
end,
less_equal = function(a, b)
return a <= b
end,
greater_equal = function(a, b)
return a >= b
end,
['and'] = function(a, b)
return a and b
end,
['or'] = function(a, b)
return a or b
end,
['not'] = function(a, b)
return !a
end
}
local operators_symbol = {
less = '<',
greater = '>',
less_equal = '<=',
greater_equal = '>=',
equal = '==',
unequal = '!=',
['and'] = '&&',
['or'] = '||',
['not'] = '!'
}
function util.process_operator(op, a, b)
return operators[op](a, b)
end
function util.get_operators()
local list = {}
for k, v in pairs(operators) do
table.insert(list, k)
end
return list
end
function util.get_logical_operators()
local list = {
equal = '==',
unequal = '!=',
['and'] = '&&',
['or'] = '||',
['not'] = '!'
}
return list
end
function util.get_relational_operators()
local list = {
less = '<',
greater = '>',
less_equal = '<=',
greater_equal = '>=',
equal = '==',
unequal = '!='
}
return list
end
function util.get_equal_operators()
local list = {
equal = '==',
unequal = '!='
}
return list
end
function util.operator_to_symbol(op)
return operators_symbol[op]
end
--- Similar to <=> operator in other languages.
-- @returns [Number, -1 if a < b, 0 if a == b, and 1 if a > b]
function compare(a, b)
if a > b then return 1 end
if a == b then return 0 end
return -1
end
--- Print traceback to current function call.
-- @return [Array string pieces of the traceback]
function print_traceback(suppress, ...)
local trace_text = debug.traceback(...)
trace_text = trace_text
:gsub('stack traceback:\n', '\n')
:gsub(': in main chunk', '')
:gsub(': in function', ': in')
:gsub('\n%s+', '\n')
:gsub('^\n', '')
local pieces = trace_text:split('\n')
pieces[1] = '' -- remove the actual call to debug.traceback
if !suppress then
for k, v in ipairs(pieces) do
if v and v != '' then
Msg(' ')
MsgC(Color(0, 255, 255), 'from '..v)
Msg('\n')
end
end
end
return pieces
end
--- Prints an error using ErrorNoHalt but without character limit.
-- @see[ErrorNoHalt]
function long_error(...)
local text = table.concat({...})
local len = string.len(text)
local pieces = {}
if len > 200 then
for i = 1, len / 200 do
table.insert(pieces, text:sub((i - 1) * 200 + 1, math.min(i * 200, len)))
end
else
pieces = { text }
end
for k, v in ipairs(pieces) do
ErrorNoHalt(v)
end
if text:ends('\n') then
print ''
end
end
--- Print an error message followed by a complete stack traceback.
function error_with_traceback(msg)
long_error(msg..'\n')
print_traceback()
end
local env = table.Copy(_G)
local unsafe = w'debug require setfenv getfenv File _G _R RunString CompileString rawget rawset rawequal setmetatable coroutine module package newproxy'
for k, v in ipairs(unsafe) do
env[v] = nil
end
env['string']['dump'] = nil
function include_sandboxed(f)
local c = CompileString(file.Read(f, 'LUA'), f)
debug.setfenv(c, env)
return c()
end
|
-- Copyright: 2015-2020, Björn Ståhl
-- License: 3-Clause BSD
-- Reference: http://durden.arcan-fe.com
--
-- Description: The display- set of functions tracks connected displays
-- and respond to plug/unplug events. They are also responsible for the
-- creation of tiler- window managers and manual or automatic migration
-- between window managers and their corresponding display.
--
-- default PPCM, particularly some capture devices that tamper with EDID.
if VPPCM > 240 then
VPPCM = 32
end
local SIZE_UNIT = 38.4;
local displays = {};
local profiles = {};
local ignored = {};
local display_listeners = {};
-- there's no other way to detect the presence of LWA mode at the moment
-- (which is just stupid since some functions have different semantics)
local arcan_nested = VRES_AUTORES ~= nil;
-- set on display_init, used to slowly refactor / decouple display.lua from
-- durden so that it can be added as a built-in instead
local wm_alloc_function;
local display_event_buffer = {};
local set_view_range;
local display_log, fmt = suppl_add_logfn("display");
local function disp_string(disp)
return string.format("id=%d:name=%s:maphint=%d:w=%d:h=%d:backlight=%d:ppcm=%f",
disp.id and disp.id or -1, disp.name and disp.name or "broken",
disp.maphint and disp.maphint or -1,
disp.w and disp.w or -1,
disp.h and disp.h or -1,
disp.backlight and disp.backlight or -1,
disp.ppcm and disp.ppcm or -1
);
end
-- always return a valid string, for debug log tagging
local function get_disp_name(name)
if (type(name) == "string") then
return name;
elseif (type(name) == "number") then
return tostring(number);
else
return "invalid";
end
end
local function get_disp(name)
local found, foundi;
for k,v in ipairs(displays) do
if (type(name) == "string" and v.name == name) then
found = v;
foundi = k;
break;
elseif (type(name) == "number" and v.id == name) then
found = v;
foundi = k;
end
end
return found, foundi;
end
local function tryload(v)
local res = system_load(v, 0);
if (not res) then
warning("parsing error loading display map: " .. v);
return;
end
local okstate, map = pcall(res);
if (not okstate or type(map) ~= "table") then
warning("execution error loading map: " .. v);
return;
end
if (type(map.name) ~= "string" or
type(map.ident) ~= "string") then
warning("bad obligatory fields in map: " .. v);
return;
end
local rv = {
name = map.name,
ident = map.ident,
tag = map.tag
};
-- copy and sanity check optional fields
if (type(map.ppcm) == "number" and map.ppcm < 200 and map.ppcm > 10) then
rv.ppcm = map.ppcm;
end
if (type(map.wm) == "string") then
if (map.wm == "tiler" or map.wm == "ignore") then
rv.wm = map.wm;
end
end
if (type(map.backlight) == "number" and map.backlight > 0.0) then
rv.backlight = map.backlight;
end
if (type(map.width) == "number" and map.width > 0) then
rv.width = map.width;
end
if (type(map.height) == "number" and map.height > 0) then
rv.height = map.height;
end
return rv;
end
function display_scanprofiles()
profiles = {};
local lst = glob_resource("devmaps/display/*.lua", APPL_RESOURCE);
if (not lst) then
return;
end
table.sort(lst);
for k,v in ipairs(lst) do
local res = tryload("devmaps/display/" .. v);
if (res) then
table.insert(profiles, res);
end
end
end
display_scanprofiles();
function display_maphint(disp)
if (type(disp) == "string") then
disp = get_disp(disp);
end
if (type(disp) ~= "table") then
return HINT_NONE;
end
return bit.bor(disp.maphint, (disp.primary and HINT_PRIMARY or 0));
end
local function autohome_spaces(ndisp)
local migrated = false;
for i, disp in ipairs(displays) do
local tiler = disp.tiler;
if (tiler and tiler ~= ndisp.tiler) then
for i=1,10 do
if (tiler.spaces[i] and tiler.spaces[i].home and
tiler.spaces[i].home == ndisp.name) then
tiler.spaces[i]:migrate(ndisp.tiler);
migrated = true;
display_log(fmt("autohome:%s:%d:%s", tiler.name, i, ndisp.name));
end
end
end
end
end
local function set_mouse_scalef()
local sf = gconfig_get("mouse_scalef");
mouse_cursor_sf(sf * displays[displays.main].tiler.scalef,
sf * displays[displays.main].tiler.scalef);
end
-- execute [cb] in the attachment context of [tiler], needed with
-- rendertargets as images created has a default attachment unless
-- one is explicitly set
function display_tiler_action(tiler, cb)
for i,v in ipairs(displays) do
if (v.tiler == tiler) then
local save = displays.main;
set_context_attachment(v.rt);
cb();
set_context_attachment(displays[save].rt);
return;
end
end
end
-- same as for display_tiler_action, just a different lookup function
function display_action(disp, cb)
local save = displays.main;
if (type(disp) == "number") then
set_context_attachment(disp);
else
set_context_attachment(disp.rt);
end
cb();
set_context_attachment(displays[save].rt);
end
local function switch_active_display(ind)
if (displays[ind] == nil or not valid_vid(displays[ind].rt)) then
return;
end
displays[displays.main].tiler:deactivate();
displays[ind].tiler:activate();
displays.main = ind;
set_context_attachment(displays[ind].rt);
mouse_querytarget(displays[ind].rt);
display_log(fmt("active_display:%d", ind));
set_mouse_scalef();
end
function display_output_table(name)
local disp
local outtbl = {
width = VRESH,
height = VRESW
}
if not name then
disp = displays[displays.main];
else
disp = get_disp(name);
end
if disp then
outtbl.width = disp.w
outtbl.height = disp.h
outtbl.refresh = disp.refresh
end
return outtbl;
end
local function set_best_mode(disp, desw, desh)
-- fixme, enumerate list of modes and pick one that has a fitting
-- resolution and refresh
local list = video_displaymodes(disp.id);
if (not list or #list == 0) then
display_log(fmt(
"mode_error:message=no_mode:display=%s", tostring(disp.id)));
return;
end
if (not desw or not desh) then
desw = disp.w;
desh = disp.h;
end
-- just score based on match against w/h
table.sort(list, function(a, b)
local dx = desw - a.width;
local dy = desh - a.height;
local ea = math.sqrt((dx * dx) + (dy * dy));
local dx = desw - b.width;
local dy = desh - b.height;
local eb = math.sqrt((dx * dx) + (dy * dy));
-- same resolution? take the matching refresh, not the highest as that would
-- excluding have a device- profile override
if (ea == eb) then
return math.abs(disp.refresh - a.refresh) > math.abs(disp.refresh - b.refresh);
end
return ea < eb;
end);
display_log(
fmt("mode_set:display=%d:width=%d:height=%d:refresh=%d",
disp.id, list[1].width, list[1].height, list[1].refresh)
);
video_displaymodes(disp.id, list[1].modeid);
end
local function get_ppcm(pw_cm, ph_cm, dw, dh)
return (math.sqrt(dw * dw + dh * dh) /
math.sqrt(pw_cm * pw_cm + ph_cm * ph_cm));
end
function display_count()
return #displays;
end
-- "hard" fullscreen- mode where the window canvas is mapped directly to
-- the display without going through the detour of a rendertarget. Note that
-- this is not as close as we can go yet, but requires more platform support
-- and loses the ability to apply a shader.
--
-- The 'real' version would require not only a mode-switch but:
--
-- * track producer state and mark that we need a scanout capable buffer
-- (which depend on the buffer format and so on) handle and wrap- shmif
-- vbuf-only drawing into such a buffer. This can already
--
-- * for kms-, have arcan directly wrap the shmif- part into a DMAbuf and
-- send that as the scanout for cases.
--
-- * use more native post-processing for ICC-/ gamma correction
--
function display_fullscreen(name, vid, modesw, mapv)
local disp = get_disp(name);
if (not disp) then
return;
end
-- invalid vid == switch back, do so by reactivating rendertarget
-- updates and possible switch back to the last known mode
if not valid_vid(vid) then
display_log("fullscreen:off");
for i, j in ipairs(displays) do
if (valid_vid(j.rt)) then
rendertarget_forceupdate(j.rt, -1);
end
end
map_video_display(disp.map_rt, disp.id, display_maphint(disp));
if (disp.last_m and disp.fs_modesw) then
video_displaymodes(disp.id, disp.last_m.modeid);
end
disp.monitor_vid = nil;
disp.monitor_sprops = nil;
if (disp.fs_mode) then
local ws = disp.tiler.spaces[disp.tiler.space_ind];
if (type(ws[disp.fs_mode]) == "function") then
ws[disp.fs_mode](ws);
end
disp.fs_mode = nil;
end
-- otherwise enter fullscreen, switch each rendertarget to a configurable
-- 'in background' refresh rate to permit other effects etc. to be running
-- but at a lower rate than the focused vid
else
display_log(fmt("fullscreen:%d", disp.id));
for i,j in ipairs(displays) do
if (valid_vid(j.rt)) then
rendertarget_forceupdate(j.rt, gconfig_get("display_fs_rtrate"));
end
end
disp.monitor_vid = vid;
local ws = disp.tiler.spaces[disp.tiler.space_ind];
disp.fs_mode = ws.mode;
map_video_display(vid, disp.id, display_maphint(disp));
end
-- will be applied in tick as we don't know what render state we are called from
disp.fs_modesw = modesw;
end
local function find_profile(name)
for k,v in ipairs(profiles) do
if (string.match(name, v.ident)) then
return v;
end
end
end
-- parse and decode display information from the edid block, possible that
-- we should allow an edid override here as well - though linux etc. provide
-- that at a lower level
local function display_data(id)
local data, hash = video_displaydescr(id);
local model = "unknown";
local serial = "unknown";
if (not data) then
return;
end
-- data should typically be EDID, if it is 128 bytes long we assume it is
if (string.len(data) == 128 or string.len(data) == 256) then
for i,ofs in ipairs({54, 72, 90, 108}) do
if (string.byte(data, ofs+1) == 0x00 and
string.byte(data, ofs+2) == 0x00 and
string.byte(data, ofs+3) == 0x00) then
if (string.byte(data, ofs+4) == 0xff) then
serial = string.sub(data, ofs+5, ofs+5+12);
elseif (string.byte(data, ofs+4) == 0xfc) then
model = string.sub(data, ofs+5, ofs+5+12);
end
end
end
end
local strip = function(s)
local outs = {};
local len = string.len(s);
for i=1,len do
local ch = string.sub(s, i, i);
if string.match(ch, '[a-zA-Z0-9]') then
table.insert(outs, ch);
end
end
return table.concat(outs, "");
end
return strip(model), strip(serial);
end
local function get_name(id)
local name;
local ok = false;
-- start with some fail-safe name
if (id == 0) then
name = "default_";
else
-- first mapping nonsense has previously made it easier (?!)
-- getting a valid EDID in some cases, might need to move this
-- workaround to the platform layer though
name = "unknown_" .. tostring(id);
map_video_display(displays[1].map_rt, id, HINT_NONE);
end
-- try and extract display name/serial from the EDID
local model, serial = display_data(id);
if (model) then
name = string.split(model, '\r')[1] .. "/" .. serial;
ok = true;
else
display_log(fmt("id=%d:error=%s", id, "no_edid"));
end
return name, ok;
end
local function display_byname(name, id, w, h, ppcm)
local name, got_name = get_name(id);
-- EDID resolving might have failed for some reason, if we have an orphan
-- display and no other - chances are there was some bug from power
-- save/suspend type action. In that case, just 'assume' the display from
-- the previously known ID.
local res = {
w = w,
h = h,
rw = w,
rh = h,
ppcm = ppcm,
id = id,
name = name,
shader = gconfig_get("display_shader"),
maphint = HINT_NONE,
refresh = 60,
backlight = 1.0,
view_range = set_view_range,
zoom = {
level = 1.0,
x = 0,
y = 0
},
wm = "tiler"
};
local pref = "disp_" .. string.hexenc(res.name) .. "_";
local keys = match_keys(pref .. "%");
for i,v in ipairs(keys) do
local ind = string.find(v, "=");
if (ind) then
local key = string.sub(string.sub(v, 1, ind-1), string.len(pref) + 1);
local val = string.sub(v, ind+1);
if (key == "ppcm") then
if (tonumber(val)) then
res.ppcm = tonumber(val);
end
elseif (key == "map") then
if (tonumber(val)) then
res.maphint = tonumber(val);
end
elseif (key == "shader") then
res.shader = val;
elseif (key == "bg") then
res.bg = val;
elseif (key == "primary") then
res.primary = tonumber(val) == 1;
elseif (key == "w") then
res.w = tonumber(val);
elseif (key == "h") then
res.h = tonumber(val);
elseif (key == "refresh") then
res.refresh = tonumber(val);
elseif (key == "backlight") then
res.backlight = tonumber(val);
else
warning("unknown stored display setting with key " .. key);
end
end
end
-- profile takes precedence over cached database key
local prof = find_profile(name);
if (prof) then
if (prof.width) then
res.w = prof.width;
end
if (prof.height) then
res.h = prof.height;
end
if (prof.refresh) then
res.refresh = prof.refresh;
end
if (prof.ppcm) then
res.ppcm = prof.ppcm;
res.ppcm_override = prof.ppcm;
end
if (prof.backlight) then
res.backlight = math.clamp(prof.backlight, 0.1, 1.0);
end
res.tag = prof.tag;
res.wm = prof.wm;
end
-- distinguish between real-width and effective-width (rotation)
res.rw = res.w;
res.rh = res.h;
return res;
end
-- assume that we somehow lost state and have a valid display, rebuild it
-- with the contents of the provided table
local function display_apply(display)
display_override_density(display.name, display.ppcm);
display_reorient(display.name, display.maphint);
display_shader(display.name, display.shader);
if (display.bg and display.tiler) then
display.tiler:set_background(bg);
end
end
function display_manager_shutdown()
local ktbl = {};
for i,v in ipairs(displays) do
local pref = "disp_" .. string.hexenc(v.name) .. "_";
if (v.ppcm_override) then
ktbl[pref .. "ppcm"] = v.ppcm;
end
if (v.maphint) then
ktbl[pref .. "map"] = v.maphint;
end
if (v.shader) then
ktbl[pref .. "shader"] = v.shader;
-- MISSING: pack/unpack shader arguments
end
if (v.backlight) then
ktbl[pref .. "backlight"] = v.backlight;
end
ktbl[pref .. "bg"] = v.background and v.background or "";
if (v.rw) then
ktbl[pref .. "w"] = v.rw;
end
if (v.rh) then
ktbl[pref .. "h"] = v.rh;
end
if (v.refresh) then
ktbl[pref .. "refresh"] = v.refresh;
end
ktbl[pref .. "primary"] = v.primary and 1 or 0;
end
store_key(ktbl);
end
local function reorient_ddisp(disp, hint)
-- is an explicit map hint set? then toggle the bits but preserve
-- other ones like CROP or FILL or PRIMARY
local mfl = bit.bor(HINT_ROTATE_CW_90, HINT_ROTATE_CCW_90);
if (hint ~= nil) then
local valid = bit.bor(HINT_ROTATE_CW_90, HINT_ROTATE_CCW_90);
valid = bit.bor(valid, HINT_YFLIP);
hint = bit.band(valid, hint);
local mask = bit.band(disp.maphint, bit.bnot(valid));
disp.maphint = bit.bor(mask, hint);
-- otherwise invert the current one
else
if (bit.band(disp.maphint, mfl) > 0) then
disp.maphint = bit.band(disp.maphint, bit.bnot(mfl));
else
disp.maphint = bit.bor(disp.maphint, HINT_ROTATE_CW_90);
end
end
local neww = disp.rw;
local newh = disp.rh;
if (bit.band(disp.maphint, mfl) > 0) then
neww = disp.rh;
newh = disp.rw;
end
-- if the dimensions have changed, we should tell the tilers to reorg.
if (neww ~= disp.w or newh ~= disp.h) then
disp.w = neww;
disp.h = newh;
display_action(disp, function()
disp.tiler:resize(neww, newh);
disp.tiler:update_scalef(disp.tiler.scalef);
end);
-- and this might have rebuilt the rendertarget as a new one, so switch
-- the query target that the mouse will check for picking on
if (active_display(true) == disp.rt) then
mouse_querytarget(disp.rt);
end
end
map_video_display(disp.map_rt, disp.id, display_maphint(disp));
end
function display_set_backlight(name, ctrl, ind)
local disp = get_disp(name);
if (not disp) then
return;
end
if not (ctrl and ctrl >= 0 and ind and ind >= 0) then
disp.ledctrl = nil;
disp.ledid = nil;
return;
end
disp.ledctrl = ctrl;
disp.ledid = ind;
led_intensity(ctrl, ind, 255.0 * disp.backlight);
end
local function modestr(tbl)
return string.format(
"%d*%d (%.2f+%.2f mm) @ %.2f hz",
tbl.width, tbl.height, tbl.phy_width_mm, tbl.phy_height_mm, tbl.refresh);
end
local function display_added(id)
local modes = video_displaymodes(id);
-- "safe" defaults
local dw = VRESW;
local dh = VRESH;
local ppcm = VPPCM;
local subpx = "RGB";
-- map resolved display modes, assume [1] is the preferred one
if (modes and #modes > 0 and modes[1].width > 0) then
for i,v in ipairs(modes) do
display_log(fmt(
"status=modedata:id=%s:mode=%d:modestr=%s", id, i, modestr(v)));
end
dw = modes[1].width;
dh = modes[1].height;
local wmm = modes[1].phy_width_mm;
local hmm = modes[1].phy_height_mm;
subpx = modes[1].subpixel_layout;
subpx = subpx == "unknown" and "RGB" or subpx;
if (wmm > 0 and hmm > 0) then
ppcm = get_ppcm(0.1*wmm, 0.1*hmm, dw, dh);
end
else
display_log(fmt("status=error:id=%d:message=no modes on display", id));
end
local ddisp;
-- if this 'fails', name will be some generated default as we know we have a
-- new display we just wasn't able to extract it from EDID because
-- all-identifiers-are-broken-fsck-hardware(TM), so as a mitigation to those
-- bugs, pick the first orphan display and assume it was just some ACPI issue
-- or similar nightmare. A softer version for this might also be useful by
-- throwing in a timer so that we first map something to the display, give
-- it enough time to propagate, and then re-query EDID.
local name, name_ok = get_name(id);
if not name_ok then
for i,v in ipairs(displays) do
if (v.orphan) then
name = v.name
display_log(fmt("id=%d:status=warning:fail_assume_adopt:name=%s", i, name));
break
end
end
end
ddisp = display_add(name, dw, dh, ppcm, id);
if (not ddisp) then
display_log(fmt("status=error:id=%d:message=display_add failed", id));
return;
end
ddisp.id = id;
-- load possible overrides since before, note that this is slightly
-- inefficient as it will force rebuild of underlying rendertargets
-- etc. but it beats have to cover a number of corner cases / races
ddisp.ppcm = ppcm;
ddisp.subpx = subpx;
-- get the current state of the color ramps and attach to the disp-
-- table, for both internal and external 'gamma' correction.
if (not ddisp.ramps) then
ddisp.ramps = video_displaygamma(ddisp.id);
ddisp.active_ramps = ddisp.ramps;
end
display_log(disp_string(ddisp));
display_apply(ddisp);
map_video_display(ddisp.map_rt, id, display_maphint(ddisp));
if (ddisp.bg) then
ddisp.tiler:set_background(ddisp.bg);
end
for k,v in ipairs(display_listeners) do
v("added", name, ddisp.tiler, id);
end
end
local last_rescan = CLOCK;
function display_event_handler(action, id)
if (displays.simple) then
return;
end
if not wm_alloc_function then
table.insert(display_event_buffer, {action, id});
return;
end
display_log(fmt("id=%d:event=%s",
id and id or -1, action and action or ""));
-- display subsystem and input subsystem are connected when it comes
-- to platform specific actions e.g. virtual terminal switching, assume
-- keystate change between display resets.
if (action == "reset") then
dispatch_meta_reset();
iostatem_reset_flag();
return;
end
if (action == "added") then
display_added(id);
-- remove on a previous display is more like tagging it as orphan
-- as it may reappear later
elseif (action == "removed") then
local ddisp = display_remove(id);
if (ddisp) then
for k,v in ipairs(display_listeners) do
v("removed", name, ddisp.tiler, id);
end
end
elseif (action == "changed") then
active_display():message("rescanning GPUs on hotlug");
-- prevent hotplug storms (such as plugging in a dock or kvm switch)
-- from causing multiple rescans and the stalls that entail
if (last_rescan ~= CLOCK) then
video_displaymodes();
last_rescan = CLOCK;
end
end
end
--
-- a facility to monitor when a display is added or lost as some
-- global effects need to know about this in order to build fbos etc.
--
function display_add_listener(fcon)
table.insert(display_listeners, fcon);
for i,v in ipairs(displays) do
fcon("added", v.name, v.tiler, v.id);
end
end
function display_all_mode(mode)
for i,v in ipairs(displays) do
video_display_state(v.id, mode);
end
end
set_view_range =
function(disp, x, y, factor)
disp.zoom.level = math.clamp(factor, 1.0, 100.0);
-- just normal mapping again
if disp.zoom.level == 1.0 then
image_set_txcos_default(disp.rt);
map_video_display(disp.map_rt, disp.id, display_maphint(disp));
return;
end
disp.zoom.x = math.clamp(x, 0.0, 1.0);
disp.zoom.y = math.clamp(y, 0.0, 1.0);
-- just uniform
local base = 1.0 / factor;
local s1 = disp.zoom.x * base;
local t1 = disp.zoom.y * base;
local s2 = s1 + base;
local t2 = t1 + base;
-- optional step, align against sampling grid s1 - (math.fmod s1, base)
-- clamp against edge
if (s2 > 1.0) then
s1 = s1 - (s2 - 1.0);
s2 = 1.0;
end
if (t2 > 1.0) then
t1 = t1 - (t2 - 1.0);
t2 = 1.0;
end
-- and synch
local txcos = {s1, t1, s2, t1, s2, t2, s1, t2};
image_set_txcos(disp.rt, txcos);
map_video_display(disp.map_rt, disp.id, display_maphint(disp));
end
function display_manager_init(alloc_fn)
wm_alloc_function = alloc_fn;
-- Since we won't get an 'added / removed' event for this display, the defaults
-- and possible profile override needs to be activated manually. This should
-- really be reworked to have the same path for everything, the problem lies
-- with how the platform is setup in Arcan, which in turn ties back to openGL
-- setup without a working display.
local name = get_name(0);
local ddisp = display_byname(name, 0, VRESW, VRESH, VPPCM);
-- this might come from a preset profile, so sweep the available display maps
-- and pick the one with the best fit
set_best_mode(ddisp);
-- virtual-display to-fix: there is an issue here when the system starts
-- without any connected display or when the first display happens to be
-- a VR display that should be ignored. What should be done is to create
-- a virtual-display and bind a tiler to that, then allow a display to
-- grab the orphaned virtual one.
ddisp.tiler = wm_alloc_function(ddisp);
displays[1] = ddisp;
displays.simple = gconfig_get("display_simple");
displays.main = 1;
ddisp.tiler.name = "default";
-- simple mode does not permit us to do much of the fun stuff, like
-- different color etc. correction shaders or rotate/fit/.. it's
-- essentially just for low powered nested use
if (not displays.simple) then
rendertarget_forceupdate(WORLDID, 0);
if (not arcan_nested) then
delete_image(WORLDID);
end
ddisp.rt = ddisp.tiler:set_rendertarget(true);
ddisp.map_rt = ddisp.rt;
map_video_display(ddisp.map_rt, 0, 0);
shader_setup(ddisp.map_rt, "display", ddisp.shader, ddisp.name);
switch_active_display(1);
reorient_ddisp(ddisp, ddisp.maphint);
mouse_querytarget(ddisp.rt);
end
-- any deferred events from display events arriving before the caller
-- has called init gets re-injected, this can also be used to test some
-- of the hotplug behaviors
for _,v in ipairs(display_event_buffer) do
display_event_handler(unpack(v))
end
display_event_buffer = {};
return ddisp.tiler;
end
function display_attachment()
if (displays.simple) then
return nil;
else
return displays[1].rt;
end
end
function display_override_density(name, ppcm)
local disp, dispi = get_disp(name);
if (not disp) then
return;
end
-- it might be that the selected display is not currently the main one
display_action(disp, function()
disp.ppcm = ppcm;
disp.ppcm_override = ppcm;
disp.tiler:update_scalef(ppcm / SIZE_UNIT, {ppcm = ppcm});
set_mouse_scalef();
end);
end
-- override the default shader setting to packval, that can be expanded
-- upon display identification and shader setup
function display_shader_uniform(name, uniform, packval)
-- print("update uniform persistance", name, uniform, packval);
end
function display_shader(name, key)
local disp, dispi = get_disp(name);
if (not disp or not valid_vid(disp.rt)) then
return;
end
-- special path, the engine can optimize if we use the "DEFAULT" shader
if (key == "basic") then
image_shader(disp.rt, 'DEFAULT');
disp.shader = key;
elseif (key) then
warning("shader" .. key);
shader_setup(disp.rt, "display", key, disp.name);
--set_key("disp_" .. hexenc(disp.name) .. "_shader", key);
disp.shader = key;
end
map_video_display(disp.map_rt, disp.id, disp.maphint);
return disp.shader;
end
function display_add(name, width, height, ppcm, id)
local found = get_disp(name);
local new = nil;
local maphint = HINT_NONE;
local backlight = 1.0;
name = string.gsub(name, ":", "/");
width = math.clamp(width, width, MAX_SURFACEW);
height = math.clamp(height, height, MAX_SURFACEH);
-- for each workspace, check if they are homed to the display
-- being added, and, if space exists, migrate
if (found) then
display_log(fmt("add_match:name=%s", string.hexenc(name)));
found.orphan = false;
image_resize_storage(found.rt, found.w, found.h);
display_apply(found);
else
nd = display_byname(name, id, width, height, ppcm);
if (nd.wm == "ignore") then
table.insert(ignored, nd);
return;
end
-- make sure all resources are created in the global scope
set_context_attachment(WORLDID);
nd.tiler = wm_alloc_function(nd);
table.insert(displays, nd);
nd.ind = #displays;
new = nd.tiler;
-- this will rebuild tiler with all its little things attached to rt
-- we hide it as we explicitly map to a display and do not want it
-- visible in the WORLDID domain, eating fillrate.
nd.rt = nd.tiler:set_rendertarget(true);
nd.map_rt = nd.rt;
hide_image(nd.rt);
-- in the real case, we'd switch to the last known resolution
-- and then set the display to match the rendertarget
found = nd;
set_context_attachment(displays[displays.main].rt);
end
-- this also takes care of spaces that are saved as preferring a certain disp.
autohome_spaces(found);
if (found.last_m) then
display_ressw(name, found.last_m);
end
return found, new;
end
-- linear search all spaces in all displays except disp and
-- return the first empty one that is found
local function find_free_display(disp)
for i,v in ipairs(displays) do
if (not v.orphan and v ~= disp) then
for j=1,10 do
if (v.tiler:empty_space(j)) then
return v;
end
end
end
end
end
-- sweep all used workspaces of the display and find new parents
local function autoadopt_display(disp)
local set = {}
for i=1,10 do
if disp.tiler:empty_space(i) then
table.insert(set, i)
end
end
if #set == 0 then
return
end
display_log(fmt(
"attempt_adopt:orphans=%d:source=%d:name=%s", #set, disp.id, disp.name));
for _,v in ipairs(set) do
local ddisp = find_free_display(disp);
-- chances are all displays are lost
if (not ddisp) then
display_log("adopt_cancelled:no_free_display");
return;
end
-- perform the migration, but remember the display
local space = disp.tiler.spaces[v];
if (space) then
space:migrate(ddisp.tiler);
space.home = disp.name;
end
end
end
-- allow external tools to register ignored devices by tag
function display_bytag(tag, yield)
for _,v in ipairs(ignored) do
if (v.tag == tag and not v.leased) then
yield(v);
end
end
end
function display_lease(name)
display_log(fmt("lease:name=%s", get_disp_name(name)));
for k,v in ipairs(ignored) do
if (v.name == name) then
if (not v.leased) then
display_log(fmt("leased:name=%s", get_disp_name(name)));
v.leased = true;
return v;
else
display_log(fmt("lease_error:name=%s",get_disp_name(name)));
end
end
end
end
function display_release(name)
display_log(fmt("release:name=%s", get_disp_name(name)));
for k,v in ipairs(ignored) do
if (v.name == name) then
if (v.leased) then
display_log(fmt("released:name=%s", get_disp_name(name)));
v.leased = false;
return;
else
display_log(fmt(("release_error:name=" .. get_disp_name(name))));
end
end
end
end
function display_remove_add(id)
local found, foundi = get_disp(id)
if not found then
return
end
display_remove(id)
display_added(id)
end
function display_remove(id)
local found, foundi = get_disp(id);
-- there is still the chance that some other tool manually managed the
-- display, this is used in the case of a VR modelviewer, for instance.
if (not found) then
for i,v in ipairs(ignored) do
if v.id == id then
if (v.handler) then
display_log(fmt("remove_masked:id=%d", id));
v:handler("remove");
end
table.remove(ignored,i);
return;
end
end
display_log(fmt("remove:error:unknown=%s", get_disp_name(name)));
return;
end
-- mark as orphan and reduce memory footprint by resizing the rendertarget
display_log(fmt("orphan:id=%d:name=%s", id, get_disp_name(name)));
found.orphan = true;
image_resize_storage(found.rt, 32, 32);
hide_image(found.rt);
-- try and have another display adopt
if (gconfig_get("ws_autoadopt") and autoadopt_display(found)) then
found.orphan = false;
end
-- if it was the main display we lost, cycle to the next one so that gets
-- set as main
if (foundi == displays.main) then
display_cycle_active(ws);
end
return found;
end
-- special little hook in LWA mode that handles resize requests from
-- parent. We treat that as a 'normal' resolution switch.
function VRES_AUTORES(w, h, vppcm, flags, source)
local disp = displays[1];
display_log(fmt(
"autores:id=0:w=%d:h=%d:ppcm=%f:flags=%d:source=%d",
w, h, vppcm, flags, source)
);
for k,v in ipairs(displays) do
if (v.id == source) then
disp = v;
break;
end
end
if (gconfig_get("lwa_autores")) then
if (displays.simple) then
resize_video_canvas(w, h);
disp.tiler:resize(w, h, true);
else
display_action(disp, function()
if (video_displaymodes(source, w, h)) then
map_video_display(disp.map_rt, 0, disp.maphint);
resize_video_canvas(w, h);
image_set_txcos_default(disp.rt);
disp.tiler:resize(w, h);
disp.tiler:update_scalef(disp.ppcm / SIZE_UNIT, {ppcm = disp.ppcm});
end
end);
end
end
end
function display_ressw(name, mode)
local disp = get_disp(name);
if (not disp) then
warning("display_ressww(), invalid display reference for "
.. tostring(name));
return;
end
-- track this so we can recover if the display is lost, readded and homed to def
disp.last_m = mode;
if (not disp.ppcm_override) then
disp.ppcm = get_ppcm(0.1 * mode.phy_width_mm,
0.1 * mode.phy_height_mm, mode.width, mode.height);
end
display_action(disp, function()
disp.w = mode.width;
disp.h = mode.height;
disp.rw = disp.w;
disp.rh = disp.h;
video_displaymodes(disp.id, mode.modeid);
if (valid_vid(disp.rt)) then
image_set_txcos_default(disp.rt);
map_video_display(disp.map_rt, disp.id, display_maphint(disp));
end
disp.tiler:resize(mode.width, mode.height) --, true);
disp.tiler:update_scalef(disp.ppcm / SIZE_UNIT, {ppcm = disp.ppcm});
set_mouse_scalef();
end);
if (disp.maphint) then
display_reorient(name, disp.maphint);
end
-- as the dimensions have changed
if (active_display(true) == disp.rt) then
mouse_querytarget(disp.rt);
end
end
function display_cycle_active(ind)
if (type(ind) == "boolean") then
switch_active_display(displays.main);
return;
elseif (type(ind) == "number") then
switch_active_display(ind);
return;
end
local nd = displays.main;
repeat
nd = (nd + 1 > #displays) and 1 or (nd + 1);
until (nd == displays.main or not
(displays[nd].orphan or displays[nd].disabled));
switch_active_display(nd);
end
function display_migrate_wnd(wnd, dstname)
local dsp2 = get_disp(dstname);
if (not dsp2) then
return;
end
wnd:migrate(dsp2.tiler, {ppcm = dsp2.ppcm,
width = dsp2.tiler.width, height = dsp2.tiler.height});
end
-- migrate the ownership of a single workspace to another display
function display_migrate_ws(tiler, dstname)
local dsp2 = get_disp(dstname);
if (not dsp2) then
return;
end
if (#tiler.spaces[tiler.space_ind].children > 0) then
tiler.spaces[tiler.space_ind]:migrate(dsp2.tiler,
{ppcm = dsp2.ppcm,
width = dsp2.tiler.width, height = dsp2.tiler.height
});
tiler:tile_update();
dsp2.tiler:tile_update();
end
end
function display_reorient(name, hint)
if (displays.simple) then
return;
end
local disp = get_disp(name);
if (not disp) then
warning("display_reorient on missing display:" .. tostring(name));
return;
end
reorient_ddisp(disp, hint);
end
function display_simple()
return displays.simple;
end
function display_share(disp, args, recfn)
if (not valid_vid(disp.rt)) then
return;
end
if (disp.share_slot) then
delete_image(disp.share_slot);
disp.share_slot = nil;
else
-- this one can't handle resolution switching and we ignore audio for the
-- time being or we'd need to do a lot of attachment tracking
local isp = image_storage_properties(disp.rt);
disp.share_slot = alloc_surface(isp.width, isp.height, true);
local indir = null_surface(isp.width, isp.height);
show_image(indir);
image_sharestorage(disp.rt, indir);
define_recordtarget(disp.share_slot,
recfn, args, {indir}, {}, RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, -1,
function(src, status)
end
);
end
end
-- the active displays is the rendertarget that will (initially) create new
-- windows, though they can be migrated immediately afterwards. This is because
-- both mouse_ implementation and new object attachment points are a global
-- state.
function active_display(rt, raw)
if (raw) then
return displays[displays.main];
end
if (not displays[displays.main]) then
return;
end
if (rt) then
return displays[displays.main].rt;
else
return displays[displays.main].tiler;
end
end
local function save_active_display()
return displays.main;
end
--
-- These iterators are primarily for archetype handlers and similar where we
-- need "all windows regardless of display". Don't break- out of this or
-- things may get the wrong attachment later.
--
local function aditer(rawdisp, showorph, showdis)
local tbl = {};
for i,v in ipairs(displays) do
if ((not v.orphan or showorph) and (not v.disabled or showdis)) then
table.insert(tbl, {i, v});
end
end
local c = #tbl;
local i = 0;
local save = displays.main;
return function()
i = i + 1;
if (i <= c) then
switch_active_display(tbl[i][1]);
return rawdisp and tbl[i][2] or tbl[i][2].tiler;
else
switch_active_display(save);
return nil;
end
end
end
function all_tilers_iter()
return aditer(false);
end
function all_displays_iter()
return aditer(true);
end
function all_spaces_iter()
local tbl = {};
for i,v in ipairs(displays) do
for k,l in pairs(v.tiler.spaces) do
table.insert(tbl, {i,l});
end
end
local c = #tbl;
local i = 0;
local save = displays.main;
return function()
i = i + 1;
if (i <= c) then
switch_active_display(tbl[i][1]);
return tbl[i][2];
else
switch_active_display(save);
return nil;
end
end
end
function all_windows(atype, noswitch)
local tbl = {};
for i,v in ipairs(displays) do
for j,k in ipairs(v.tiler.windows) do
table.insert(tbl, {i, k});
end
end
local i = 0;
local c = #tbl;
local save = displays.main;
return function()
i = i + 1;
while (i <= c) do
if (not atype or (atype and tbl[i][2].atype == atype)) then
if (not noswitch) then
switch_active_display(tbl[i][1]);
end
return tbl[i][2];
else
i = i + 1;
end
end
if (not noswitch) then
switch_active_display(save);
end
return nil;
end
end
function displays_alive(filter)
local res = {};
for k,v in ipairs(displays) do
if (not (v.orphan or v.disabled) and (not filter or k ~= displays.main)) then
table.insert(res, v.name);
end
end
return res;
end
function display_tick()
for k,v in ipairs(displays) do
if (not v.orphan) then
v.tiler:tick();
end
-- periodically check source for dedicated fullscreen mode
if (not displays.simple and v.monitor_vid) then
-- on death, set "BADID" (which will revert mapping to normal rt)
if (not valid_vid(v.monitor_vid, TYPE_FRAMESERVER)) then
display_fullscreen(v.name, BADID);
else
local isp = image_storage_properties(v.monitor_vid);
-- deferred resize- propagation due to cost of mode switch, this could probably
-- be even more conservative, though resolution switches in the source will
-- cause a visual glitch for the 'incorrect' frames.
if (not v.monitor_sprops or isp.width ~= v.monitor_sprops.width or
isp.height ~= v.monitor_sprops.height) then
v.monitor_sprops = isp;
if (v.fs_modesw) then
set_best_mode(v, isp.width, isp.height);
end
-- remap so crop-center works
end
end
end
end
end
|
local Binding = require("prox.input.Binding")
local pmath = require("prox.math")
local MultiBinding = class("prox.input.MultiBinding", Binding)
function MultiBinding:initialize(bindings)
Binding.initialize(self)
self._bindings = {}
if bindings then
for i,v in ipairs(bindings) do
table.insert(self._bindings, v)
end
end
end
function MultiBinding:wasPressed(...)
for i,v in ipairs(self._bindings) do
if v:wasPressed(...) then return true end
end
return false
end
function MultiBinding:wasReleased(...)
for i,v in ipairs(self._bindings) do
if v:wasReleased(...) then return true end
end
return false
end
function MultiBinding:isDown(...)
for i,v in ipairs(self._bindings) do
if v:isDown(...) then return true end
end
return false
end
function MultiBinding:getAxis(name)
local value = 0
for i,v in ipairs(self._bindings) do
value = value + v:getAxis(name)
end
return prox.math.cap(value, -1 ,1)
end
return MultiBinding
|
remmer_dune_scavenger = Creature:new {
objectName = "@mob/creature_names:remmer_dune_scavenger",
socialGroup = "remmer",
faction = "",
level = 20,
chanceHit = 0.33,
damageMin = 180,
damageMax = 190,
baseXp = 1609,
baseHAM = 4500,
baseHAMmax = 5500,
armor = 0,
resists = {115,5,125,135,-1,5,5,-1,-1},
meatType = "meat_carnivore",
meatAmount = 30,
hideType = "hide_bristley",
hideAmount = 15,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.25,
ferocity = 5,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/mobile/remmer_hue.iff"},
hues = { 16, 17, 18, 19, 20, 21, 22, 23 },
scale = 0.9,
lootGroups = {},
weapons = {"creature_spit_small_red"},
conversationTemplate = "",
attacks = {
{"posturedownattack",""},
{"stunattack",""}
}
}
CreatureTemplates:addCreatureTemplate(remmer_dune_scavenger, "remmer_dune_scavenger")
|
include( "class" )
local KLEIRenderSceneClass = class()
local function smootherstep( edge0, edge1, t )
if (t <= edge0) then
return 0.0
elseif t >= edge1 then
return 1.0
else
t = (t - edge0) / (edge1 - edge0)
return t*t*t*(t*(t*6 - 15) + 10)
end
end
function KLEIRenderSceneClass:init()
local settings = savefiles.getSettings( "settings" ).data
--Render tables
self._gameTbl = {}
self._hudTbl = {}
self._mouseCursor = {}
--Render parameters
self._GausianBlur = settings.enableBloom and 1.0 or 0
self._DaltonizationType = 0
self._UIEasePulseTimers = {}
self.easeDriver = function()
local ease = 0
for i,timer in ipairs( self._UIEasePulseTimers ) do
--controls the ease-in and ease-out of the pulse
local pp = timer:getTime()
local pl = timer:getPeriod()
--local ramp = math.min( 1.0, 1.0 - math.pow( math.cos( 2 * math.pi * pp / pl ), 3.0) );
--local ramp = math.cos( 10*2*math.pi * pp / pl )/2 + 0.5
local ramp = smootherstep( 0.0, 1.0, pp/pl )
ease = ease + ramp
end
ease = math.min( ease, 1.0 )
self._Stage1PP._pp:getUniforms():setUniformFloat( 'ease', ease )
end
self.easeFinishedFunc = function( timer, executed )
for i,v in ipairs(self._UIEasePulseTimers) do
if v == timer then
table.remove( self._UIEasePulseTimers, i )
if #self._UIEasePulseTimers == 0 then
self:setup()
end
return
end
end
assert(false)
end
end
function KLEIRenderSceneClass:initRT( msaaSamples )
self:setMSAA( msaaSamples )
local post_process_manager = include( "post_process_manager" )
self._Stage1PP = post_process_manager.create() --Actual post process effect is selected later
self._Stage2PP = post_process_manager.create() --Actual post process effect is selected later
self._RT = CreateRenderTarget( VIEWPORT_WIDTH, VIEWPORT_HEIGHT )
self._RT:setClearColor( 0, 0, 0, 0 )
--If Stage1 is not PASSTHOUGH this is needed
self._PPRT = CreateRenderTarget( VIEWPORT_WIDTH, VIEWPORT_HEIGHT )
self._PPRT:setRenderTable( { self._Stage1PP:getRenderable() } )
--If Stage2 is not PASSTHROUGH these are needed
--First pass of the bloom effect is to downsample the main RT into a 1/4 sized texture
self._DSPP = post_process_manager.create() --Input to the downsample is the main RT or PPRT, this is selected later
self._DSRT = CreateRenderTarget( VIEWPORT_WIDTH / 2, VIEWPORT_HEIGHT / 2 )
self._DSRT:setRenderTable( { self._DSPP:getRenderable() } ) --Post process the main RT through the downsample
--Second pass of the bloom effect is the vertical portion of the seperable gaussian blur
self._VGPP = post_process_manager.vertical_gaussian( self._DSRT ) --Input to the vertical_gaussian is the downsampled buffer
self._VGRT = CreateRenderTarget( VIEWPORT_WIDTH / 2, VIEWPORT_HEIGHT / 2 )
self._VGRT:setRenderTable( { self._VGPP:getRenderable() } ) --Post process the downsample through the vertical gaussian
--Third pass of the bloom effect is the vertical portion of the seperable gaussian blur
self._HGPP = post_process_manager.horizontal_gaussian( self._VGRT ) --Input to the horizontal gaussian in the vertical gaussian
self._HGRT = CreateRenderTarget( VIEWPORT_WIDTH / 2, VIEWPORT_HEIGHT / 2 )
self._HGRT:setRenderTable( { self._HGPP:getRenderable() } ) --Post process the vertical gaussian through the horizontal gaussian
end
function KLEIRenderSceneClass:resizeRenderTargets()
for _,info in pairs(self._gameTbl) do
if info[1] and info[1].init and not info.CONST then
if info.MSAA then
info[1]:init( VIEWPORT_WIDTH, VIEWPORT_HEIGHT, nil, nil, nil, self._msaaSampleCount or 0 )
else
info[1]:init( VIEWPORT_WIDTH, VIEWPORT_HEIGHT )
end
end
end
if self._RT then
self._RT:init( VIEWPORT_WIDTH, VIEWPORT_HEIGHT )
end
if self._PPRT then
self._PPRT:init( VIEWPORT_WIDTH, VIEWPORT_HEIGHT )
end
if self._DSRT then
self._DSRT:init( VIEWPORT_WIDTH / 2, VIEWPORT_HEIGHT / 2 )
end
if self._VGRT then
self._VGRT:init( VIEWPORT_WIDTH / 2, VIEWPORT_HEIGHT / 2 )
end
if self._HGRT then
self._HGRT:init( VIEWPORT_WIDTH / 2, VIEWPORT_HEIGHT / 2 )
end
end
function KLEIRenderSceneClass:setGameRenderTable( tbl )
self._gameTbl = tbl or {}
self:setup()
end
function KLEIRenderSceneClass:setHudRenderTable( tbl )
self._hudTbl = tbl or {}
self:setup()
end
function KLEIRenderSceneClass:setMouseCursor( renderable )
self._mouseCursor = { renderable }
end
function KLEIRenderSceneClass:setDaltonizationType( mode )
assert( mode == 0 or mode == 1 or mode == 2 or mode == 3 )
self._DaltonizationType = mode
self:setup()
end
function KLEIRenderSceneClass:setGaussianBlur( blur )
self._GausianBlur = blur or 0
self:setup()
end
function KLEIRenderSceneClass:setDesaturation( func )
self._desatFunc = func
self:setup()
end
function KLEIRenderSceneClass:setMSAA( sampleCount )
if (sampleCount or 0) <= 1 then
sampleCount = 0
end
if self._msaaSampleCount ~= sampleCount then
self._msaaSampleCount = sampleCount
self:resizeRenderTargets()
end
end
function KLEIRenderSceneClass:setPixelate( x_width, y_width )
if x_width and y_width then
self._PixelateInfo = { width=x_width, height=y_width }
else
self._PixelateInfo = nil
end
end
function KLEIRenderSceneClass:pulseUIFuzz( period )
local timer = MOAITimer.new ()
timer:setSpan ( period )
timer:setMode ( MOAITimer.NORMAL )
timer:setListener ( MOAITimer.EVENT_TIMER_END_SPAN, self.easeFinishedFunc )
timer:start()
table.insert( self._UIEasePulseTimers, timer )
self._EaseType = 0
self:setup()
end
function KLEIRenderSceneClass:setAscii( ease )
self._AsciiEase = ease
self:setup()
end
local Stage1Options =
{
PASSTHROUGH = 0x1,
PIXELATE = 0x2,
--SHUTTER = 0x3,
ASCII = 0x4,
FUZZ = 0x5,
DALTONIZE = 0x6,
DALTONIZE_ASCII = 0x7,
DALTONIZE_FUZZ = 0x8,
}
local Stage2Options =
{
PASSTHROUGH = 0x9,
BLOOM = 0xA,
DESATURATION = 0xB,
BLOOM_DESATURATION = 0xC,
}
function KLEIRenderSceneClass:setup()
local renderTable
local Stage1 = Stage1Options.PASSTHROUGH
if self._PixelateInfo then --Pixelate
Stage1 = Stage1Options.PIXELATE
elseif self._DaltonizationType > 0 and #self._UIEasePulseTimers > 0 and self._EaseType == 0 then --Daltonize and Fuzz
Stage1 = Stage1Options.DALTONIZE_FUZZ
elseif self._DaltonizationType > 0 and self._AsciiEase then --Daltonize and Ascii
Stage1 = Stage1Options.DALTONIZE_ASCII
elseif self._DaltonizationType > 0 then --Only daltonization
Stage1 = Stage1Options.DALTONIZE
elseif #self._UIEasePulseTimers > 0 and self._EaseType == 0 then --Fuzz only
Stage1 = Stage1Options.FUZZ
elseif self._AsciiEase then --Ascii only
Stage1 = Stage1Options.ASCII
end
local Stage2 = Stage2Options.PASSTHROUGH
if self._GausianBlur ~= 0 and self._desatFunc then
Stage2 = Stage2Options.BLOOM_DESATURATION
elseif self._GausianBlur ~= 0 then
Stage2 = Stage2Options.BLOOM
elseif self._desatFunc then
Stage2 = Stage2Options.DESATURATION
end
self._RT:setRenderTable( { self._gameTbl, self._hudTbl } )
local renderTable
if Stage1 == Stage1Options.PASSTHROUGH and Stage2 == Stage2Options.PASSTHROUGH then
self._Stage1PP:passthrough( self._RT )
renderTable = { self._RT, self._Stage1PP:getRenderable(), self._mouseCursor }
else
if Stage1 == Stage1Options.PASSTHROUGH then
self._Stage1PP:passthrough( self._RT )
elseif Stage1 == Stage1Options.PIXELATE then
self._Stage1PP:pixelate( self._RT, function(shader) shader:setUniformVector2( "Size", self._PixelateInfo.width, self._PixelateInfo.height ) end )
elseif Stage1 == Stage1Options.ASCII then
self._Stage1PP:ascii( self._RT, self._AsciiEase )
elseif Stage1 == Stage1Options.FUZZ then
self._Stage1PP:fuzz( self._RT, self.easeDriver )
elseif Stage1 == Stage1Options.DALTONIZE then
self._Stage1PP:daltonize( self._RT, self._DaltonizationType )
elseif Stage1 == Stage1Options.DALTONIZE_ASCII then
self._Stage1PP:daltonize_ascii( self._RT, self._DaltonizationType, self._AsciiEase )
elseif Stage1 == Stage1Options.DALTONIZE_FUZZ then
self._Stage1PP:daltonize_fuzz( self._RT, self._DaltonizationType, self.easeDriver )
else
assert(false)
end
local Stage1T = self._PPRT
local Stage1P = { self._RT, self._PPRT }
if Stage1 == Stage1Options.PASSTHROUGH then
Stage1T = self._RT
Stage1P = { self._RT }
end
if Stage2 == Stage2Options.PASSTHROUGH then
assert(Stage1 ~= Stage1Options.PASSTHROUGH )
renderTable = {
self._RT, --Push _RT, process its render table, Pop _RT
self._Stage1PP:getRenderable(), --execute Stage1
self._mouseCursor, --mouse cursor
}
elseif Stage2 == Stage2Options.BLOOM then
self._DSPP:downsample( Stage1T )
self._Stage2PP:bloom_merge( Stage1T, self._HGRT, self._GausianBlur )
renderTable = {
Stage1P, --execute Stage1P, outputs to Stage1T
self._DSRT, --Push _DSRT, downsample _PPRT, Pop _DSRT
self._VGRT, --Push _VGRT, vertical gaussian _DSRT, Pop _VGRT
self._HGRT, --Push _HGRT, horizontal gaussian _VGRT, Pop _HGRT
self._Stage2PP:getRenderable(), --bloom merge
self._mouseCursor, --mouse cursor
}
elseif Stage2 == Stage2Options.DESATURATION then
self._Stage2PP:desaturation( Stage1T, self._desatFunc )
renderTable = {
Stage1P, --execute Stage1P, outputs to Stage1T
self._Stage2PP:getRenderable(), --desaturation
self._mouseCursor, --mouse cursor
}
elseif Stage2 == Stage2Options.BLOOM_DESATURATION then
self._DSPP:downsample( Stage1T )
self._Stage2PP:bloom_merge_desaturation(Stage1T, self._HGRT, self._GausianBlur, self._desatFunc )
renderTable = {
Stage1P, --execute Stage1P, outputs to Stage1T
self._DSRT, --Push _DSRT, downsample _PPRT, Pop _DSRT
self._VGRT, --Push _VGRT, vertical gaussian _DSRT, Pop _VGRT
self._HGRT, --Push _HGRT, horizontal gaussian _VGRT, Pop _HGRT
self._Stage2PP:getRenderable(), --bloom merge desaturation
self._mouseCursor, --mouse cursor
}
else
assert(false)
end
end
MOAIRenderMgr.setRenderTable( renderTable )
end
return KLEIRenderSceneClass
|
project "optick"
kind "StaticLib"
language "C++"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
defines
{
"OPTICK_EXPORTS",
"OPTICK_ENABLE_GPU_D3D12=1",
"OPTICK_ENABLE_GPU_VULKAN=0",
"_SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING"
}
files
{
"src/**.h",
"src/**.cpp"
}
includedirs
{
"src"
}
vpaths
{
["api"] = {
"src/optick.h",
"src/optick.config.h",
},
}
links
{
"dxgi",
}
filter "system:windows"
systemversion "latest"
cppdialect "C++17"
staticruntime "On"
filter "system:linux"
pic "On"
systemversion "latest"
cppdialect "C++17"
staticruntime "On"
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
|
-- Copyright (c) 2018 Redfern, Trevor <trevorredfern@gmail.com>
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
describe("array_assertions", function()
it("can check if an array includes an item", function()
local t = {1,2,3,4,5,6,7}
assert.array_includes(1, t)
assert.is_not.array_includes(10, t)
end)
it("can specify if an array is empty", function()
local empty = {}
local not_empty = {1, 2, 3}
assert.empty_array(empty)
assert.is_not.empty_array(not_empty)
end)
end)
|
local mock = require('luassert.mock')
local ruby_code_actions = require('ruby-code-actions')
local insert_frozen_string_literal_generator =
ruby_code_actions.generators.insert_frozen_string_literal_generator
local autocorrect_with_rubocop_generator =
ruby_code_actions.generators.autocorrect_with_rubocop_generator
local strings = ruby_code_actions.strings
local non_selection_context = {
bufname = "my-bufname",
bufnr = 1,
content = {"puts \"starting\"", "", "puts \"hello world\""},
range = {col = 1, end_col = 1, end_row = 1, row = 1},
row = 1
}
local visual_selection_context = {
bufname = "my-bufname",
bufnr = 1,
content = {"puts \"starting\"", "", "puts \"hello world\""},
range = {col = 1, end_col = 1, end_row = 2, row = 1},
row = 1
}
local choice_by_title = function(choices, title)
for _, action in ipairs(choices) do
if action.title == title then return action end
end
return nil
end
describe("insert_frozen_string_literal_generator", function()
it(
"returns nothing if the first line of the context is the frozen string literal comment",
function()
local context = {
content = {
strings.frozen_string_literal_comment, "",
"puts 'hello world'"
}
}
assert.is_nil(insert_frozen_string_literal_generator(context))
end)
it(
"returns an action if the first line of the context is not the frozen string literal comment",
function()
local context = {content = {"puts 'hello world'"}}
local choices = insert_frozen_string_literal_generator(context)
assert.is_table(choice_by_title(choices,
strings.frozen_string_literal))
end)
it("inserts the frozen string literal comment when the action is called",
function()
local api = mock(vim.api, true)
local first_line = "puts 'hello world'"
local context = {content = {first_line}, bufnr = 9}
local choices = insert_frozen_string_literal_generator(context)
local action = choice_by_title(choices,
"🥶Add frozen string literal comment").action
action()
assert.stub(api.nvim_buf_set_lines).was_called_with(9, 0, 1, false, {
strings.frozen_string_literal_comment, "", first_line
})
mock.revert(api)
end)
it("works if the action title is overridden", function()
local api = mock(vim.api, true)
local first_line = "puts 'hello world'"
local new_title = "brrrr..."
require('ruby-code-actions').strings.frozen_string_literal = new_title
local context = {content = {first_line}, bufnr = 9}
local choices = insert_frozen_string_literal_generator(context)
local action = choice_by_title(choices, new_title).action
action()
assert.stub(api.nvim_buf_set_lines).was_called_with(9, 0, 1, false, {
strings.frozen_string_literal_comment, "", first_line
})
mock.revert(api)
end)
end)
describe("autocorrect_with_rubocop_generator", function()
describe("unsafely correcting a file", function()
local title = strings.unsafe_autocorrect_with_rubocop
it("is an available action when no lines are selected", function()
local choices = autocorrect_with_rubocop_generator(
non_selection_context)
assert.is_table(choice_by_title(choices, title))
end)
it("is not an available action when lines are selected", function()
local choices = autocorrect_with_rubocop_generator(
visual_selection_context)
assert.is_nil(choice_by_title(choices, title))
end)
it(
"invokes rubocop to unsafely autocorrect and re-open the current buffer when the action is called",
function()
local api = mock(vim.api, true)
local overrideables =
mock(ruby_code_actions.overrideables, true)
local choices = autocorrect_with_rubocop_generator(
non_selection_context)
local action = choice_by_title(choices, title).action
action()
assert.stub(overrideables.system).was_called_with(
"rubocop -A my-bufname")
assert.stub(api.nvim_command).was_called_with("edit")
mock.revert(api)
mock.revert(overrideables)
end)
end)
describe("safely correcting a file", function()
local title = strings.safe_autocorrect_with_rubocop
it("is an available action when no lines are selected", function()
local choices = autocorrect_with_rubocop_generator(
non_selection_context)
assert.is_table(choice_by_title(choices, title))
end)
it("is not an available action when lines are selected", function()
local choices = autocorrect_with_rubocop_generator(
visual_selection_context)
assert.is_nil(choice_by_title(choices, title))
end)
it(
"invokes rubocop to safely autocorrect and re-open the current buffer when the action is called",
function()
local api = mock(vim.api, true)
local overrideables =
mock(ruby_code_actions.overrideables, true)
local choices = autocorrect_with_rubocop_generator(
non_selection_context)
local action = choice_by_title(choices, title).action
action()
assert.stub(overrideables.system).was_called_with(
"rubocop -a my-bufname")
assert.stub(api.nvim_command).was_called_with("edit")
mock.revert(api)
mock.revert(overrideables)
end)
end)
describe("autocorrecting line(s)", function()
it(
"calls rubocop to autocorrect the current line and replace it when the action is called with no selection",
function()
local title = "🤖Autocorrect line with Rubocop"
local api = mock(vim.api, true)
local overrideables =
mock(ruby_code_actions.overrideables, true)
overrideables.readfile.returns("puts \"starting\"")
overrideables.tempname.returns("temp-file-name")
overrideables.readfile.returns({"puts 'starting'"})
local choices = autocorrect_with_rubocop_generator(
non_selection_context)
local action = choice_by_title(choices, title).action
action()
assert.stub(api.nvim_buf_set_lines).was_called_with(1, 0, 1,
false, {
"puts 'starting'"
})
assert.stub(overrideables.reindent).was_called_with(1, 1)
mock.revert(api)
mock.revert(overrideables)
end)
it(
"calls rubocop to autocorrect selected lines and replace them when the action is called with a selection",
function()
local title = "🤖Autocorrect lines with Rubocop"
local cmd = mock(vim.cmd, false)
local api = mock(vim.api, true)
local overrideables =
mock(ruby_code_actions.overrideables, true)
overrideables.readfile.returns({
"puts \"starting\"", "", "puts \"hello world\""
})
overrideables.tempname.returns("temp-file-name")
overrideables.readfile.returns({
"puts 'starting'", "", "puts 'hello world'"
})
local choices = autocorrect_with_rubocop_generator(
visual_selection_context)
local action = choice_by_title(choices, title).action
action()
assert.stub(api.nvim_buf_set_lines).was_called_with(1, 0, 2,
false, {
"puts 'starting'", "", "puts 'hello world'"
})
assert.stub(overrideables.reindent).was_called_with(1, 3)
mock.revert(cmd)
mock.revert(api)
mock.revert(overrideables)
end)
end)
end)
|
toggleControl( 'action', false ) -- yay, that key has no purpose either way
local scoreboardRows = {}
local scoreboardGrid
local updateInterval = 1000 --ms
local indent = ' '
local playerCount
local localPlayer = getLocalPlayer()
local rootElement = getRootElement()
local players = {}
local columns = {
{name="ID #"},
{name="name",size=0.55},
{name="ping"}
}
function addToScoreboard(player)
local player = player or source
if (isElement(player)) then
local id = getElementData(player, "playerid")
if not id then
setTimer(addToScoreboard, 100, 1, player)
else
players[id] = player
updatePlayers()
end
end
end
function removeFromScoreboard()
local id = getElementData(source, "playerid")
players[id] = nil
updatePlayers()
end
function updatePlayers()
guiGridListClear(scoreboardGrid)
scoreboardRows = {}
-- add all players
local row = guiGridListAddRow(scoreboardGrid)
scoreboardRows[localPlayer] = row
guiGridListSetItemText(scoreboardGrid, row, 1, tostring(getElementData(localPlayer, "playerid")), false, true)
guiGridListSetItemText(scoreboardGrid, row, 2, getPlayerName(localPlayer), false, false)
guiGridListSetItemText(scoreboardGrid, row, 3, tostring(getPlayerPing(localPlayer)), false, true)
for i = 1, 128 do
if players[i] and players[i] ~= localPlayer then
local player = players[i]
local row = guiGridListAddRow(scoreboardGrid)
scoreboardRows[player] = row
guiGridListSetItemText(scoreboardGrid, row, 1, tostring(i), false, true)
guiGridListSetItemText(scoreboardGrid, row, 2, getPlayerName(player), false, false)
guiGridListSetItemText(scoreboardGrid, row, 3, tostring(getPlayerPing(player)), false, true)
end
end
guiGridListSetSelectedItem(scoreboardGrid, 0, 1)
end
function updatePlayerNick(old, new)
guiGridListSetItemText(scoreboardGrid, scoreboardRows[source], 2, new, false, false)
end
function refreshScoreboardPings()
for i,player in ipairs(getElementsByType("player")) do
if (isElement(player)) then
guiGridListSetItemText(scoreboardGrid, scoreboardRows[player], 3, tostring(getPlayerPing(player)), false, false)
end
end
guiSetText(playerCount, #getElementsByType("player"))
end
function updateScoreboard()
refreshScoreboardPings()
guiSetText(playerCount, "Players: " .. #getElementsByType("player"))
guiGridListSetSelectedItem(scoreboardGrid, 0, 1)
end
function refreshScoreboard()
if guiGetVisible(scoreboardGrid) and not isCursorShowing() then
updateScoreboard()
end
end
function showScoreboardCursor(key,keystate,show)
showCursor(show)
setControlState( 'fire', false )
setControlState( 'weapon_aim', false )
end
function toggleScoreboard(state)
if state == nil then state = not guiGetVisible(scoreboardGrid) end
if state == true then
showCursor(false)
updateScoreboard()
bindKey("mouse2","down",showScoreboardCursor,true)
bindKey("mouse2","up",showScoreboardCursor,false)
if isControlEnabled( 'fire' ) then
setElementData(getLocalPlayer(), "scoreboard:reload", true)
toggleControl( 'fire', false )
end
guiBringToFront(scoreboardGrid)
elseif state == false then
showCursor(false)
unbindKey("mouse2","down",showScoreboardCursor)
unbindKey("mouse2","up",showScoreboardCursor)
if getElementData(getLocalPlayer(), "scoreboard:reload") then
setElementData(getLocalPlayer(), "scoreboard:reload", false)
toggleControl( 'fire', true )
end
end
guiSetVisible(scoreboardGrid,state)
end
function toggleScoreboardPressed(key,keystate,state)
toggleScoreboard(state)
end
addEventHandler("onClientResourceStart", getResourceRootElement(),
function ()
scoreboardGrid = guiCreateGridList(0.15,0.2,0.7,0.6,true)
guiSetAlpha(scoreboardGrid,0.7)
guiSetVisible(scoreboardGrid,false)
guiGridListSetSortingEnabled(scoreboardGrid,false)
local rmbLabel = guiCreateLabel(0, 0, 0, 0, "(Hold right mouse button to enable scrolling)",false,scoreboardGrid)
local scoreX, scoreY = guiGetSize(scoreboardGrid, false)
local labelWidth = guiLabelGetTextExtent(rmbLabel)
local labelHeight = guiLabelGetFontHeight(rmbLabel)
guiSetPosition(rmbLabel, (scoreX - labelWidth)/6, scoreY - labelHeight - 10, false)
guiSetSize(rmbLabel, labelWidth, labelHeight, false)
guiSetAlpha(rmbLabel, .8)
guiLabelSetColor(rmbLabel, 200, 200, 255)
playerCount = guiCreateLabel(0, 0, 0, 0, "Players: ",false,scoreboardGrid)
labelWidth = guiLabelGetTextExtent(playerCount)
labelHeight = guiLabelGetFontHeight(playerCount)
guiSetPosition(playerCount, (scoreX - labelWidth)/1.25, scoreY - labelHeight - 10, false)
guiSetSize(playerCount, labelWidth, labelHeight, false)
guiSetAlpha(playerCount, .8)
guiLabelSetColor(playerCount, 200, 200, 255)
bindKey("tab","down",toggleScoreboardPressed,true)
bindKey("tab","up",toggleScoreboardPressed,false)
addCommandHandler("scoreboard", toggleScoreboard)
setTimer(refreshScoreboard, updateInterval, 0)
updateScoreboard()
--scoreboard update event handlers
addEventHandler("onClientPlayerJoin", rootElement, addToScoreboard)
addEventHandler("onClientPlayerQuit", rootElement, removeFromScoreboard)
addEventHandler("onClientPlayerChangeNick", rootElement, updatePlayerNick)
addEventHandler("onClientClick", scoreboardGrid,
function()
if guiGetVisible(scoreboardGrid) then
guiGridListSetSelectedItem(scoreboardGrid, scoreboardRows[localPlayer], 1)
end
end
)
-- add all columns
for key, value in pairs(columns) do
guiGridListAddColumn(scoreboardGrid,value.name,value.size or 0.1)
end
-- add all players
for key, value in ipairs(getElementsByType("player")) do
addToScoreboard(value)
end
updatePlayers()
end
)
|
-- @.filter.lua
--
@.filter = function(collection, predicate, selfArg, reject)
local t = {}
for k, v in _.iter(collection) do
local check = callIteratee(predicate, selfArg, v, k, collection)
if reject then
if not check then
_.push(t, v)
end
else
if check then
_.push(t, v)
end
end
end
return t
end
|
local wk = require("which-key")
wk.setup {
layout = {
spacing = 4
},
triggers = {"<leader>"}
}
wk.register({
d = 'kill line to null register',
e = {
name = '+Edit...',
p = '`packages.lua` file',
s = '`settings.lua` file',
m = '`keymaps.lua` file',
},
p = {
name = '+Packages...',
s = 'synchronize'
},
t = {
name = '+Toggle...',
w = 'line wrapping',
b = 'scrollbar',
l = 'display whitespace',
},
r = {
n = 'Rename symbol'
}
}, { prefix = "<leader>"})
|
function PackIEEE754SP(number)
if number == 0 then
return string.char(0x00, 0x00, 0x00, 0x00)
elseif number ~= number then
return string.char(0xFF, 0xFF, 0xFF, 0xFF)
else
local sign = 0x00
if number < 0 then
sign = 0x80
number = -number
end
local mantissa, exponent = math.frexp(number)
exponent = exponent + 0x7F
if exponent <= 0 then
mantissa = math.ldexp(mantissa, exponent - 1)
exponent = 0
elseif exponent > 0 then
if exponent >= 0xFF then
return string.char(sign + 0x7F, 0x80, 0x00, 0x00)
elseif exponent == 1 then
exponent = 0
else
mantissa = mantissa * 2 - 1
exponent = exponent - 1
end
end
mantissa = math.floor(math.ldexp(mantissa, 23) + 0.5)
return string.char(
sign + math.floor(exponent / 2),
(exponent % 2) * 0x80 + math.floor(mantissa / 0x10000),
math.floor(mantissa / 0x100) % 0x100,
mantissa % 0x100)
end
end
function UnpackIEEE754SP(packed)
local b1, b2, b3, b4 = string.byte(packed, 1, 4)
local exponent = (b1 % 0x80) * 0x02 + math.floor(b2 / 0x80)
local mantissa = math.ldexp(((b2 % 0x80) * 0x100 + b3) * 0x100 + b4, -23)
if exponent == 0xFF then
if mantissa > 0 then
return 0 / 0
else
mantissa = math.huge
exponent = 0x7F
end
elseif exponent > 0 then
mantissa = mantissa + 1
else
exponent = exponent + 1
end
if b1 >= 0x80 then
mantissa = -mantissa
end
return math.ldexp(mantissa, exponent - 0x7F)
end
local function PackIEEE754DP(number)
if number == 0 then
return string.char(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
elseif number ~= number then
return string.char(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF)
else
local sign = 0x00
if number < 0 then
sign = 0x80
number = -number
end
local mantissa, exponent = math.frexp(number)
exponent = exponent + 0x3ff
if exponent <= 0 then
mantissa = math.ldexp(mantissa, exponent - 1)
exponent = 0
elseif exponent > 0 then
if exponent >= 0x800 then
return string.char(sign + 0x7F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
elseif exponent == 1 then
exponent = 0
else
mantissa = mantissa * 2 - 1
exponent = exponent - 1
end
end
mantissa = math.floor(math.ldexp(mantissa, 52) + 0.5)
return string.char(
sign + math.floor(exponent / 2^4),
(exponent % (2^4)) * 0x10 + math.floor(mantissa / 0x1000000000000),
math.floor(mantissa / 0x10000000000) % 0x100,
math.floor(mantissa / 0x100000000) % 0x100,
math.floor(mantissa / 0x1000000) % 0x100,
math.floor(mantissa / 0x10000) % 0x100,
math.floor(mantissa / 0x100) % 0x100,
math.floor(mantissa) % 0x100)
end
end
local function UnpackIEEE754DP(packed)
local b1, b2, b3, b4, b5, b6, b7, b8 = string.byte(packed, 1, 8)
local exponent = ((b1 % 0x80) * 0x10 + math.floor(b2 / 0x10))
local mantissa = math.ldexp(((((((b2 % 0x10) * 0x100 + b3) * 0x100 + b4) * 0x100 + b5) * 0x100 + b6) * 0x100 + b7)*0x100 + b8, -52)
if exponent == 0x800 then
if mantissa > 0 then
return 0 / 0
else
mantissa = math.huge
exponent = 0x800-1
end
elseif exponent > 0 then
mantissa = mantissa + 1
else
exponent = exponent + 1
end
if b1 >= 0x80 then
mantissa = -mantissa
end
return math.ldexp(mantissa, exponent - 0x3ff)
end
return {encodeSP=PackIEEE754SP, decodeSP=UnpackIEEE754SP, encodeDP=PackIEEE754DP, decodeDP=UnpackIEEE754DP}
|
local function delay(x)
return (function() return x end)
end
local function set_filter_infotext(data, meta)
local infotext = data.wise_desc.." Filter-Injector"
if meta:get_int("slotseq_mode") == 2 then
infotext = infotext .. " (slot #"..meta:get_int("slotseq_index").." next)"
end
meta:set_string("infotext", infotext)
end
local function set_filter_formspec(data, meta)
local itemname = data.wise_desc.." Filter-Injector"
local formspec
if data.digiline then
formspec = "size[8,2.7]"..
"item_image[0,0;1,1;pipeworks:"..data.name.."]"..
"label[1,0;"..minetest.formspec_escape(itemname).."]"..
"field[0.3,1.5;8.0,1;channel;Channel;${channel}]"..
fs_helpers.cycling_button(meta, "button[0,2;4,1", "slotseq_mode",
{"Sequence slots by Priority",
"Sequence slots Randomly",
"Sequence slots by Rotation"})..
fs_helpers.cycling_button(meta, "button[4,2;4,1", "exmatch_mode",
{"Exact match - off",
"Exact match - on "})
else
local exmatch_button = ""
if data.stackwise then
exmatch_button =
fs_helpers.cycling_button(meta, "button[4,3.5;4,1", "exmatch_mode",
{"Exact match - off",
"Exact match - on "})
end
formspec = "size[8,8.5]"..
"item_image[0,0;1,1;pipeworks:"..data.name.."]"..
"label[1,0;"..minetest.formspec_escape(itemname).."]"..
"label[0,1;Prefer item types:]"..
"list[context;main;0,1.5;8,2;]"..
fs_helpers.cycling_button(meta, "button[0,3.5;4,1", "slotseq_mode",
{"Sequence slots by Priority",
"Sequence slots Randomly",
"Sequence slots by Rotation"})..
exmatch_button..
"list[current_player;main;0,4.5;8,4;]" ..
"listring[]"
end
meta:set_string("formspec", formspec)
end
-- todo SOON: this function has *way too many* parameters
local function grabAndFire(data,slotseq_mode,exmatch_mode,filtmeta,frominv,frominvname,frompos,fromnode,filterfor,fromtube,fromdef,dir,fakePlayer,all)
local sposes = {}
for spos,stack in ipairs(frominv:get_list(frominvname)) do
local matches
if filterfor == "" then
matches = stack:get_name() ~= ""
else
matches = stack:get_name() == filterfor.name
end
if matches then table.insert(sposes, spos) end
end
if #sposes == 0 then return false end
if slotseq_mode == 1 then
for i = #sposes, 2, -1 do
local j = math.random(i)
local t = sposes[j]
sposes[j] = sposes[i]
sposes[i] = t
end
elseif slotseq_mode == 2 then
local headpos = filtmeta:get_int("slotseq_index")
table.sort(sposes, function (a, b)
if a >= headpos then
if b < headpos then return true end
else
if b >= headpos then return false end
end
return a < b
end)
end
for _, spos in ipairs(sposes) do
local stack = frominv:get_stack(frominvname, spos)
local doRemove = stack:get_count()
if fromtube.can_remove then
doRemove = fromtube.can_remove(frompos, fromnode, stack, dir)
elseif fromdef.allow_metadata_inventory_take then
doRemove = fromdef.allow_metadata_inventory_take(frompos, frominvname,spos, stack, fakePlayer)
end
-- stupid lack of continue statements grumble
if doRemove > 0 then
if slotseq_mode == 2 then
local nextpos = spos + 1
if nextpos > frominv:get_size(frominvname) then
nextpos = 1
end
filtmeta:set_int("slotseq_index", nextpos)
set_filter_infotext(data, filtmeta)
end
local item
local count
if all then
count = math.min(stack:get_count(), doRemove)
if filterfor.count and filterfor.count > 1 then
if exmatch_mode ~= 0 and filterfor.count > count then
return false
else
count = math.min(filterfor.count, count)
end
end
else
count = 1
end
if fromtube.remove_items then
-- it could be the entire stack...
item = fromtube.remove_items(frompos, fromnode, stack, dir, count)
else
item = stack:take_item(count)
frominv:set_stack(frominvname, spos, stack)
if fromdef.on_metadata_inventory_take then
fromdef.on_metadata_inventory_take(frompos, frominvname, spos, item, fakePlayer)
end
end
local pos = vector.add(frompos, vector.multiply(dir, 1.4))
local start_pos = vector.add(frompos, dir)
local item1 = pipeworks.tube_inject_item(pos, start_pos, dir, item)
return true-- only fire one item, please
end
end
return false
end
local function punch_filter(data, filtpos, filtnode, msg)
local filtmeta = minetest.get_meta(filtpos)
local filtinv = filtmeta:get_inventory()
local owner = filtmeta:get_string("owner")
local fakePlayer = {
get_player_name = delay(owner),
is_fake_player = ":pipeworks",
} -- TODO: use a mechanism as the wielder one
local dir = minetest.facedir_to_right_dir(filtnode.param2)
local frompos = vector.subtract(filtpos, dir)
local fromnode = minetest.get_node(frompos)
if not fromnode then return end
local fromdef = minetest.registered_nodes[fromnode.name]
if not fromdef then return end
local fromtube = fromdef.tube
if not (fromtube and fromtube.input_inventory) then return end
local slotseq_mode
local exact_match
local filters = {}
if data.digiline then
local t_msg = type(msg)
if t_msg == "table" then
local slotseq = msg.slotseq
local t_slotseq = type(slotseq)
if t_slotseq == "number" and slotseq >= 0 and slotseq <= 2 then
slotseq_mode = slotseq
elseif t_slotseq == "string" then
slotseq = string.lower(slotseq)
if slotseq == "priority" then
slotseq_mode = 0
elseif slotseq == "random" then
slotseq_mode = 1
elseif slotseq == "rotation" then
slotseq_mode = 2
end
end
local exmatch = msg.exmatch
local t_exmatch = type(exmatch)
if t_exmatch == "number" and exmatch >= 0 and exmatch <= 1 then
exact_match = exmatch
elseif t_exmatch == "boolean" then
exact_match = exmatch and 1 or 0
end
local slotseq_index = msg.slotseq_index
if type(slotseq_index) == "number" then
-- This should allow any valid index, but I'm not completely sure what
-- constitutes a valid index, so I'm only allowing resetting it to 1.
if slotseq_index == 1 then
filtmeta:set_int("slotseq_index", slotseq_index)
set_filter_infotext(data, filtmeta)
end
end
if slotseq_mode ~= nil then
filtmeta:set_int("slotseq_mode", slotseq_mode)
end
if exact_match ~= nil then
filtmeta:set_int("exmatch_mode", exact_match)
end
if slotseq_mode ~= nil or exact_match ~= nil then
set_filter_formspec(data, filtmeta)
end
if msg.nofire then
return
end
if type(msg.name) == "string" then
table.insert(filters, {name = msg.name, count = tonumber(msg.count) or 1})
else
for _, filter in ipairs(msg) do
local t_filter = type(filter)
if t_filter == "table" then
if type(filter.name) == "string" then
table.insert(filters, {name = filter.name, count = tonumber(filter.count) or 1})
end
elseif t_filter == "string" then
local filterstack = ItemStack(filter)
local filtername = filterstack:get_name()
local filtercount = filterstack:get_count()
if filtername ~= "" then table.insert(filters, {name = filtername, count = filtercount}) end
end
end
end
elseif t_msg == "string" then
local filterstack = ItemStack(msg)
local filtername = filterstack:get_name()
local filtercount = filterstack:get_count()
if filtername ~= "" then table.insert(filters, {name = filtername, count = filtercount}) end
end
else
for _, filterstack in ipairs(filtinv:get_list("main")) do
local filtername = filterstack:get_name()
local filtercount = filterstack:get_count()
if filtername ~= "" then table.insert(filters, {name = filtername, count = filtercount}) end
end
end
if #filters == 0 then table.insert(filters, "") end
if slotseq_mode == nil then
slotseq_mode = filtmeta:get_int("slotseq_mode")
end
if exact_match == nil then
exact_match = filtmeta:get_int("exmatch_mode")
end
local frommeta = minetest.get_meta(frompos)
local frominv = frommeta:get_inventory()
if fromtube.before_filter then fromtube.before_filter(frompos) end
for _, frominvname in ipairs(type(fromtube.input_inventory) == "table" and fromtube.input_inventory or {fromtube.input_inventory}) do
local done = false
for _, filterfor in ipairs(filters) do
if grabAndFire(data, slotseq_mode, exact_match, filtmeta, frominv, frominvname, frompos, fromnode, filterfor, fromtube, fromdef, dir, fakePlayer, data.stackwise) then
done = true
break
end
end
if done then break end
end
if fromtube.after_filter then fromtube.after_filter(frompos) end
end
for _, data in ipairs({
{
name = "filter",
wise_desc = "Itemwise",
stackwise = false,
},
{
name = "mese_filter",
wise_desc = "Stackwise",
stackwise = true,
},
{ -- register even if no digilines
name = "digiline_filter",
wise_desc = "Digiline",
stackwise = true,
digiline = true,
},
}) do
local node = {
description = data.wise_desc.." Filter-Injector",
tiles = {
"pipeworks_"..data.name.."_top.png",
"pipeworks_"..data.name.."_top.png",
"pipeworks_"..data.name.."_output.png",
"pipeworks_"..data.name.."_input.png",
"pipeworks_"..data.name.."_side.png",
"pipeworks_"..data.name.."_top.png",
},
paramtype2 = "facedir",
groups = {snappy = 2, choppy = 2, oddly_breakable_by_hand = 2, mesecon = 2},
legacy_facedir_simple = true,
sounds = default.node_sound_wood_defaults(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
set_filter_formspec(data, meta)
set_filter_infotext(data, meta)
local inv = meta:get_inventory()
inv:set_size("main", 8*2)
end,
after_place_node = function (pos, placer)
minetest.get_meta(pos):set_string("owner", placer:get_player_name())
pipeworks.after_place(pos)
end,
after_dig_node = pipeworks.after_dig,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
if not pipeworks.may_configure(pos, player) then return 0 end
return stack:get_count()
end,
allow_metadata_inventory_take = function(pos, listname, index, stack, player)
if not pipeworks.may_configure(pos, player) then return 0 end
return stack:get_count()
end,
allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
if not pipeworks.may_configure(pos, player) then return 0 end
return count
end,
can_dig = function(pos, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:is_empty("main")
end,
tube = {connect_sides = {right = 1}},
}
if data.digiline then
node.groups.mesecon = nil
if not minetest.get_modpath("digilines") then
node.groups.not_in_creative_inventory = 1
end
node.on_receive_fields = function(pos, formname, fields, sender)
if not pipeworks.may_configure(pos, sender) then return end
fs_helpers.on_receive_fields(pos, fields)
if fields.channel then
minetest.get_meta(pos):set_string("channel", fields.channel)
end
local meta = minetest.get_meta(pos)
--meta:set_int("slotseq_index", 1)
set_filter_formspec(data, meta)
set_filter_infotext(data, meta)
end
node.digiline = {
effector = {
action = function(pos, node, channel, msg)
local meta = minetest.get_meta(pos)
local setchan = meta:get_string("channel")
if setchan ~= channel then return end
punch_filter(data, pos, node, msg)
end,
},
}
else
node.on_receive_fields = function(pos, formname, fields, sender)
if not pipeworks.may_configure(pos, sender) then return end
fs_helpers.on_receive_fields(pos, fields)
local meta = minetest.get_meta(pos)
meta:set_int("slotseq_index", 1)
set_filter_formspec(data, meta)
set_filter_infotext(data, meta)
end
node.mesecons = {
effector = {
action_on = function(pos, node)
punch_filter(data, pos, node)
end,
},
}
node.on_punch = function (pos, node, puncher)
punch_filter(data, pos, node)
end
end
minetest.register_node("pipeworks:"..data.name, node)
end
minetest.register_craft( {
output = "pipeworks:filter 2",
recipe = {
{ "default:steel_ingot", "default:steel_ingot", "homedecor:plastic_sheeting" },
{ "group:stick", "default:mese_crystal", "homedecor:plastic_sheeting" },
{ "default:steel_ingot", "default:steel_ingot", "homedecor:plastic_sheeting" }
},
})
minetest.register_craft( {
output = "pipeworks:mese_filter 2",
recipe = {
{ "default:steel_ingot", "default:steel_ingot", "homedecor:plastic_sheeting" },
{ "group:stick", "default:mese", "homedecor:plastic_sheeting" },
{ "default:steel_ingot", "default:steel_ingot", "homedecor:plastic_sheeting" }
},
})
if minetest.get_modpath("digilines") then
minetest.register_craft( {
output = "pipeworks:digiline_filter 2",
recipe = {
{ "default:steel_ingot", "default:steel_ingot", "homedecor:plastic_sheeting" },
{ "group:stick", "digilines:wire_std_00000000", "homedecor:plastic_sheeting" },
{ "default:steel_ingot", "default:steel_ingot", "homedecor:plastic_sheeting" }
},
})
end
|
casesWindow = guiCreateWindow(0.43, 0.40, 0.15, 0.19, "AUR ~ Cases", true)
guiWindowSetSizable(casesWindow, false)
guiSetAlpha(casesWindow, 1.00)
guiSetVisible(casesWindow, false)
casesLabel = guiCreateLabel(0.00, 0.18, 1.00, 0.22, "You have 5 cases", true, casesWindow)
guiLabelSetHorizontalAlign(casesLabel, "center", false)
guiLabelSetVerticalAlign(casesLabel, "center")
close = guiCreateButton(0.05, 0.75, 0.90, 0.18, "Close", true, casesWindow)
open = guiCreateButton(0.05, 0.52, 0.90, 0.18, "Use", true, casesWindow)
function toggle(c)
local vis = (not guiGetVisible(casesWindow))
showCursor(vis)
guiSetVisible(casesWindow, vis)
-- Set the number of cases
if (c) then
guiSetText(casesLabel, "You have "..tostring(c).." cases")
end
end
addEvent("AURcases.t", true)
addEventHandler('AURcases.t', root, toggle)
function buttons(b)
if (b ~= "left") then
return false
end
if (source == close) then
toggle()
elseif (source == open) then
triggerServerEvent("AURcases.openPrize", resourceRoot)
guiSetEnabled(open, false)
setTimer(guiSetEnabled, 1000, 1, open, true)
end
end
addEventHandler("onClientGUIClick", close, buttons, false)
addEventHandler("onClientGUIClick", open, buttons, false)
|
object_tangible_furniture_all_outbreak_lung_vat = object_tangible_furniture_all_shared_outbreak_lung_vat:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_all_outbreak_lung_vat, "object/tangible/furniture/all/outbreak_lung_vat.iff")
|
object_tangible_collection_plant_07 = object_tangible_collection_shared_plant_07:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_plant_07, "object/tangible/collection/plant_07.iff")
|
--[[
SIMPLOO - Simple Lua Object Orientation
The MIT License (MIT)
Copyright (c) 2016 maurits.tv
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.
]]
----
---- init.lua
----
simploo = {}
----
---- config.lua
----
simploo.config = {}
--
-- Production Mode
--
-- Description: This setting disables non essential parts simploo in order to improve performance on production environments.
-- Be aware that certain usage and safety checks are disabled as well so keep this disable when developing and testing.
-- Default: false
--
simploo.config["production"] = false
--
-- Expose Syntax
--
-- Description: Expose all syntax related functions as globals instead of having to call simploo.syntax.<fn> explicitly.
-- You can also manually enable or disable the simploo syntax globals in sections of your code by calling simploo.syntax.init() and simploo.syntax.destroy().
-- Default: true
--
simploo.config["exposeSyntax"] = true
--
-- Class Hotswapping
--
-- Description: When defining a class a 2nd time, automatically update all the earlier instances of a class with newly added members. Will slightly increase class instantiation time and memory consumption.
-- Default: false
--
simploo.config["classHotswap"] = false
--
-- Global Namespace Table
--
-- Description: the global table in which simploo writes away all classes
-- Default: _G
--
-- TODO
-- simploo.config["globalNamespaceTable"] = _G
----
---- util.lua
----
local util = {}
simploo.util = util
function util.duplicateTable(tbl, skipKeys, lookup)
local copy = {}
for k, v in pairs(tbl) do
if type(v) == "table" then
if skipKeys and skipKeys[k] == false then
copy[k] = v -- Specified to skip copying explicitly
else
lookup = lookup or {}
lookup[tbl] = copy
if lookup[v] then
copy[k] = lookup[v] -- we already copied this table. reuse the copy.
else
copy[k] = util.duplicateTable(v, skipKeys and skipKeys[k] --[[ allows to use a multi-dimentional table so skip keys ]], lookup) -- not yet copied. copy it.
end
end
else
copy[k] = rawget(tbl, k)
end
end
if debug then -- bypasses __metatable metamethod if debug library is available
local mt = debug.getmetatable(tbl)
if mt then
debug.setmetatable(copy, mt)
end
else -- too bad.. gonna try without it
local mt = getmetatable(tbl)
if mt then
setmetatable(copy, mt)
end
end
return copy
end
function util.addGcCallback(object, callback)
if not _VERSION or _VERSION == "Lua 5.1" then
local proxy = newproxy(true)
local mt = getmetatable(proxy) -- Lua 5.1 doesn't allow __gc on tables. This function is a hidden lua feature which creates an empty userdata object instead, which allows the usage of __gc.
mt.MetaName = "SimplooGC" -- This is used internally when printing or displaying info.
mt.__class = object -- Store a reference to our object, so the userdata object lives as long as the object does.
mt.__gc = function(self)
-- Lua < 5.1 flips out when errors happen inside a userdata __gc, so we catch and print them!
local success, error = pcall(function()
callback(object)
end)
if not success then
print(string.format("ERROR: class %s: error __gc function: %s", tostring(object), tostring(error)))
end
end
rawset(object, "__gc", proxy)
else
local mt = getmetatable(object)
mt.__gc = function(self)
-- Lua doesn't really do anything with errors happening inside __gc (doesn't even print them in my test)
-- So we catch them by hand and print them!
local success, error = pcall(function()
callback(object)
end)
if not success then
print(string.format("ERROR: %s: error __gc function: %s", tostring(self), tostring(error)))
end
end
return
end
end
function util.setFunctionEnvironment(fn, env)
if setfenv then -- Lua 5.1
setfenv(fn, env)
else -- Lua 5.2
if debug and debug.getupvalue and debug.setupvalue then
-- Lookup the _ENV local inside the function
local localId = 0
local localName, localValue
repeat
localId = localId + 1
localName, localValue = debug.getupvalue(fn, localId)
if localName == "_ENV" then
-- Assign the new environment to the _ENV local
debug.setupvalue(fn, localId, env)
break
end
until localName == nil
else
error("error: the debug.setupvalue and debug.getupvalue functions are required in Lua 5.2 in order to support the 'using' keyword")
end
end
end
----
---- hooks.lua
----
local hook = {}
hook.hooks = {}
simploo.hook = hook
function hook:add(hookName, callbackFn)
table.insert(self.hooks, {hookName, callbackFn})
end
function hook:fire(hookName, ...)
local args = {...}
for _, v in pairs(self.hooks) do
if v[1] == hookName then
local ret = {v[2](unpack(args))}
-- Overwrite the original value, but do pass it on to the next hook if any
if ret[0] then
args = ret
end
end
end
return unpack(args)
end
----
---- instancer.lua
----
local instancer = {}
simploo.instancer = instancer
instancer.classFormats = {}
instancer.metafunctions = {"__index", "__newindex", "__tostring", "__call", "__concat", "__unm", "__add", "__sub", "__mul", "__div", "__mod", "__pow", "__eq", "__lt", "__le"}
function instancer:initClass(classFormat)
-- Call the beforeInitClass hook
local classFormat = simploo.hook:fire("beforeInstancerInitClass", classFormat) or classFormat
-- Store class format
instancer.classFormats[classFormat.name] = classFormat
-- Create instance
local classInstance = {}
local function classIsGlobal(obj)
return obj == classInstance
-- return obj and string.sub(tostring(obj), 0, 7 + 6) == "SimplooObject" and obj.className and obj == _G[obj.className]
end
-- Base variables
classInstance.className = classFormat.name
classInstance.members = {}
classInstance.instance = false
classInstance.privateCallDepth = 0
-- Setup a lua environment for all usings, which we can apply to all members later
local usingsEnv = {}
do
-- Assign all usings to the environment
for _, usingData in pairs(classFormat.usings) do
instancer:usingsToTable(usingData["path"], usingsEnv, _G, usingData["alias"])
end
-- Assign the metatable. Doing this after usingsToTable so it doesn't write to _G
local global = _G
setmetatable(usingsEnv, {
__index = function(self, key) return global[key] end,
__newindex = function(self, key, value) global[key] = value end
})
end
-- Copy members from provided parents in the class format
for _, parentName in pairs(classFormat.parents) do
-- Retrieve parent from an earlier defined class that's global, or from the usings table.
local parentInstance = _G[parentName] or usingsEnv[parentName]
if not parentInstance then
error(string.format("class %s: could not find parent %s", classInstance.className, parentName))
end
-- Get the full parent name, because for usings it might not be complete
local fullParentName = parentInstance.className
-- Add parent classInstance to child
local newMember = {}
newMember.owner = classInstance
newMember.value = parentInstance
newMember.modifiers = {}
classInstance.members[parentName] = newMember
classInstance.members[self:classNameFromFullPath(parentName)] = newMember
-- Add variables from parents to child
for parentMemberName, _ in pairs(parentInstance.members) do
local parentMember = parentInstance.members[parentMemberName]
parentMember.ambiguous = classInstance.members[parentMemberName] and true or false -- mark as ambiguous when a member already exists (which means that during inheritance 2 parents had a member with the same name)
if not simploo.config["production"] then
if type(parentMember.value) == "function" then
local newMember = simploo.util.duplicateTable(parentMember, {owner = false}) -- Don't copy the owner! that reference should stay the same
-- When not in production, we have to add a wrapper around each inherited function to fix up private access.
-- This function resolves unjustified private access errors you call a function that uses a parent's private variables, from a child class.
-- It basically passes the parent object as 'self', instead of the child object, so when the __index/__newindex metamethods check access, the member owner == self.
newMember.value = function(caller, ...)
return parentMember.value(caller.members[parentMemberName].owner, ...)
end
classInstance.members[parentMemberName] = newMember
else
-- Assign the member by reference
classInstance.members[parentMemberName] = parentMember
end
else
-- Assign the member by reference, always
classInstance.members[parentMemberName] = parentMember
end
end
end
-- Init own members from class format
for memberName, memberData in pairs(classFormat.members) do
local newMember = {}
newMember.owner = classInstance
newMember.modifiers = memberData.modifiers
newMember.value = memberData.value
-- When not in production, add code that tracks invocation depth from the root instance
-- This allows us to detect when you try to access private variables directly from an instance.
if not simploo.config["production"] then
if type(newMember.value) == "function" then
newMember.valueOriginal = newMember.value
newMember.value = function(self, ...)
if not self or not self.privateCallDepth then
error("Method called incorrectly, 'self' was not passed. https://stackoverflow.com/questions/4911186/difference-between-and-in-lua")
end
self.privateCallDepth = self.privateCallDepth + 1
local ret = {newMember.valueOriginal(self, ...)}
self.privateCallDepth = self.privateCallDepth - 1
return unpack(ret)
end
end
end
classInstance.members[memberName] = newMember
end
-- Add default constructor, finalizer and declarer methods if not yet exists
for _, memberName in pairs({"__construct", "__finalize", "__declare"}) do
if not classInstance.members[memberName] then
local newMember = {}
newMember.owner = classInstance
newMember.value = function() end
newMember.modifiers = {}
classInstance.members[memberName] = newMember
else
-- Already exists, but remove all modifiers just in case
classInstance.members[memberName].modifiers = {}
end
end
-- Assign the usings environment to all members
for memberName, memberData in pairs(classInstance.members) do
if type(memberData.value) == "function" then
simploo.util.setFunctionEnvironment(memberData.value, usingsEnv)
if memberData.valueOriginal then
simploo.util.setFunctionEnvironment(memberData.valueOriginal, usingsEnv)
end
end
end
-- Add base methods
do
function classInstance:clone()
-- TODO: Do not deep copy members that are static, because they will not be used anyway
local clone = simploo.util.duplicateTable(self)
return clone
end
local function markAsInstanceRecursively(instance)
instance.instance = true
for parentName, parentInstance in pairs(instance:get_parents()) do
parentInstance.instance = true
markAsInstanceRecursively(parentInstance)
end
end
function classInstance:new(...)
-- Clone and construct new instance
local copy = classInstance:clone()
markAsInstanceRecursively(copy)
for memberName, memberData in pairs(copy.members) do
if memberData.modifiers.abstract then
error(string.format("class %s: can not instantiate because it has unimplemented abstract members", copy.className))
end
end
simploo.util.addGcCallback(copy, function()
if copy.members["__finalize"].owner == copy then
copy:__finalize()
end
end)
if copy.members["__construct"].owner == copy then -- If the class has a constructor member that it owns (so it is not a reference to the parent constructor)
if self and self == classInstance then -- The :new() syntax was used, because 'self' is the same as the original class instance
copy:__construct(...)
else -- The .new() syntax was used, because 'self' is not a class. 'self' is now actually first argument that was passed, so we need to pass it along
copy:__construct(self, ...)
end
end
-- If our hook returns a different object, use that instead.
local copy = simploo.hook:fire("afterInstancerInstanceNew", copy) or copy
-- Encapsulate the instance with a wrapper object to prevent private vars from being accessable.
return copy
end
function classInstance:get_name()
return self.className
end
function classInstance:get_class()
return _G[self.className]
end
function classInstance:instance_of(className)
for _, parentName in pairs(classFormat.parents) do
if self[parentName]:instance_of(className) then
return true
end
end
return self.className == className
end
function classInstance:get_parents()
local t = {}
for _, parentName in pairs(classFormat.parents) do
t[parentName] = self[parentName]
end
return t
end
end
-- Add meta ethods
local meta = {}
do
function meta:__index(key)
if not self.members[key] then
return
end
if not simploo.config["production"] then
if self.members[key].ambiguous then
error(string.format("class %s: call to member %s is ambiguous as it is present in both parents", tostring(self), key))
end
if self.members[key].modifiers.private and self.members[key].owner ~= self then
error(string.format("class %s: accessing private member %s", tostring(self), key))
end
if self.members[key].modifiers.private and self.privateCallDepth == 0 then
error(string.format("class %s: accessing private member %s from outside", tostring(self), key))
end
end
if self.members[key].modifiers.static and not self == classInstance then
return _G[self.className][key]
end
return self.members[key].value
end
function meta:__newindex(key, value)
if not self.members[key] then
return
end
if not simploo.config["production"] then
if self.members[key].modifiers.const then
error(string.format("class %s: can not modify const variable %s", tostring(self), key))
end
if self.members[key].modifiers.private and self.members[key].owner ~= self then
error(string.format("class %s: accessing private member %s", tostring(self), key))
end
if self.members[key].modifiers.private and self.privateCallDepth == 0 then
error(string.format("class %s: accessing private member %s from outside", tostring(self), key))
end
end
if self.members[key].modifiers.static and not self == classInstance then
_G[self.className][key] = value
return
end
self.members[key].value = value
end
function meta:__tostring()
-- We disable the metamethod on ourselfs, so we can tostring ourselves without getting into an infinite loop.
-- And rawget doesn't work because we want to call a metamethod on ourself, not a normal method.
local mt = getmetatable(self)
local fn = mt.__tostring
mt.__tostring = nil
-- Grap the definition string.
local str = string.format("SimplooObject: %s <%s> {%s}", self:get_name(), self == classInstance and "class" or "instance", tostring(self):sub(8))
if self.__tostring then
str = self:__tostring() or str
end
-- Enable our metamethod again.
mt.__tostring = fn
-- Return string.
return str
end
function meta:__call(...)
if self == classInstance then
return self:new(...)
elseif self.instance then
if self.members["__construct"].owner == self then
return self:__construct(...)
end
end
end
end
-- Add support for meta methods as class members.
for _, metaName in pairs(instancer.metafunctions) do
local fnOriginal = meta[metaName]
if classInstance.members[metaName] then
meta[metaName] = function(self, ...)
local fnTmp = meta[metaName]
meta[metaName] = fnOriginal
local ret = {(fnOriginal and fnOriginal(self, ...)) or (self.members[metaName] and self.members[metaName].value and self.members[metaName].value(self, ...)) or nil}
meta[metaName] = fnTmp
return unpack(ret)
end
end
end
setmetatable(classInstance, meta)
-- Initialize the instance for use as a class
self:registerClassInstance(classInstance)
simploo.hook:fire("afterInstancerInitClass", classFormat, classInstance)
return classInstance
end
-- Sets up a global instance of a class instance in which static member values are stored
function instancer:registerClassInstance(classInstance)
_G[classInstance.className] = classInstance
self:namespaceToTable(classInstance.className, _G, classInstance)
if classInstance.members["__declare"] and classInstance.members["__declare"].owner == classInstance then
classInstance:__declare()
end
end
-- Inserts a namespace like string into a nested table
-- E.g: ("a.b.C", t, "Hi") turns into:
-- t = {a = {b = {C = "Hi"}}}
function instancer:namespaceToTable(namespaceName, targetTable, assignValue)
local firstword, remainingwords = string.match(namespaceName, "(%w+)%.(.+)")
if firstword and remainingwords then
targetTable[firstword] = targetTable[firstword] or {}
self:namespaceToTable(remainingwords, targetTable[firstword], assignValue)
else
targetTable[namespaceName] = assignValue
end
end
-- Resolve a using-declaration
-- Looks in searchTable for namespaceName and assigns it to targetTable.
-- Supports the following formats:
-- > a.b.c -- Everything inside that namespace
-- > a.b.c.Foo -- Specific class inside namespace
function instancer:usingsToTable(name, targetTable, searchTable, alias)
local firstchunk, remainingchunks = string.match(name, "(%w+)%.(.+)")
if searchTable[firstchunk] then
self:usingsToTable(remainingchunks, targetTable, searchTable[firstchunk], alias)
else
-- Wildcard add all from this namespace
if name == "*" then
-- Assign everything found in the table
for k, v in pairs(searchTable) do
if alias then
-- Resolve the namespace in the alias, and store the class inside this
self:namespaceToTable(alias, targetTable, {[k] = v})
else
-- Just assign the class directly
targetTable[k] = v
end
end
else -- Add single class
if not searchTable[name] then
error(string.format("failed to resolve using %s", name))
end
if not searchTable[name].className then
error(string.format("resolved %s, but the table found is not a class", name))
end
if searchTable[name].className then
-- Assign a single class
targetTable[alias or name] = searchTable[name]
end
end
end
end
-- Get the class name from a full path
function instancer:classNameFromFullPath(fullPath)
return string.match(fullPath, ".*(.+)")
end
----
---- parser.lua
----
local parser = {}
simploo.parser = parser
parser.instance = false
parser.modifiers = {"public", "private", "protected", "static", "const", "meta", "abstract"}
-- Parses the simploo class syntax into the following table format:
--
-- {
-- name = "ExampleClass",
-- parents = {"ExampleParent1", "ExampleParent2"},
-- functions = {
-- exampleFunction = {value = function() ... end, modifiers = {public = true, static = true, ...}}
-- }
-- variables = {
-- exampleVariablt = {value = 0, modifiers = {public = true, static = true, ...}}
-- }
-- }
function parser:new()
local object = {}
object.className = ""
object.classParents = {}
object.classMembers = {}
object.classUsings = {}
object.onFinishedData = false
object.onFinished = function(self, output)
self.onFinishedData = output
end
function object:setOnFinished(fn)
if self.onFinishedData then
-- Directly call the finished function if we already have a result available
fn(self, self.onFinishedData)
else
self.onFinished = fn
end
end
function object:class(className, classOperation)
self.className = className
for k, v in pairs(classOperation or {}) do
if self[k] then
self[k](self, v)
else
error("unknown class operation " .. k)
end
end
end
function object:extends(parentsString)
for className in string.gmatch(parentsString, "([^,^%s*]+)") do
table.insert(self.classParents, className)
end
end
function object:register(classContent)
if classContent then
self:addMemberRecursive(classContent)
end
local output = {}
output.name = self.className
output.parents = self.classParents
output.members = self.classMembers
output.usings = self.classUsings
self:onFinished(output)
end
-- Recursively compile and pass through all members and modifiers found in a tree like structured table.
-- All modifiers applicable to the member inside a branch of this tree are defined in the __modifiers key.
function object:addMemberRecursive(memberTable, activeModifiers)
for _, modifier in pairs(activeModifiers or {}) do
table.insert(memberTable["__modifiers"], 1, modifier)
end
for memberName, memberValue in pairs(memberTable) do
local isModifierMember = memberName == "__modifiers"
local containsModifierMember = (type(memberValue) == "table" and memberValue["__modifiers"])
if not isModifierMember and not containsModifierMember then
self:addMember(memberName, memberValue, memberTable["__modifiers"])
elseif containsModifierMember then
self:addMemberRecursive(memberValue, memberTable["__modifiers"])
end
end
end
-- Adds a member to the class definition
function object:addMember(memberName, memberValue, modifiers)
if memberValue == simploo.syntax.null then
memberValue = nil
end
self["classMembers"][memberName] = {
value = memberValue,
modifiers = {}
}
for _, modifier in pairs(modifiers or {}) do
self["classMembers"][memberName].modifiers[modifier] = true
end
end
function object:namespace(namespace)
self.className = namespace .. "." .. self.className
end
function object:using(using)
table.insert(self.classUsings, using)
end
local meta = {}
local modifierStack = {}
-- This method catches and stacks modifier definition when using native lua syntax.
function meta:__index(key)
table.insert(modifierStack, key)
return self
end
-- This method catches assignments of members using native lua syntax.
function meta:__newindex(key, value)
self:addMember(key, value, modifierStack)
modifierStack = {}
end
-- When using the normal syntax, the class method will be called with the members table as argument.
-- This method passes through that call.
function meta:__call(classContent)
self:register(classContent)
end
return setmetatable(object, meta)
end
----
---- syntax.lua
----
local syntax = {}
syntax.null = "NullVariable_WgVtlrvpP194T7wUWDWv2mjB" -- Parsed into nil value when assigned to member variables
simploo.syntax = syntax
local activeNamespace = false
local activeUsings = {}
function syntax.class(className, classOperation)
if simploo.parser.instance then
error(string.format("starting new class named %s when previous class named %s has not yet been registered", className, simploo.parser.instance.className))
end
simploo.parser.instance = simploo.parser:new(onFinished)
simploo.parser.instance:setOnFinished(function(self, parserOutput)
-- Set parser instance to nil first, before calling the instancer
-- That means that if the instancer errors out, at least the bugging instance is cleared and not gonna be used again.
simploo.parser.instance = nil
if simploo.instancer then
-- Create a class instance
local newClass = simploo.instancer:initClass(parserOutput)
-- Add the newly created class to the 'using' list, so that any other classes in this namespace don't have to reference to it using the full path.
syntax.using(newClass:get_name())
end
end)
simploo.parser.instance:class(className, classOperation)
if activeNamespace and activeNamespace ~= "" then
simploo.parser.instance:namespace(activeNamespace)
end
if activeUsings then
for _, v in pairs(activeUsings) do
simploo.parser.instance:using(v)
end
end
return simploo.parser.instance
end
function syntax.extends(parents)
if not simploo.parser.instance then
error("calling extends without calling class first")
end
simploo.parser.instance:extends(parents)
return simploo.parser.instance
end
function syntax.namespace(namespaceName)
if not namespaceName then
return activeNamespace
end
local returnNamespace = simploo.hook:fire("onSyntaxNamespace", namespaceName)
activeNamespace = returnNamespace or namespaceName
activeUsings = {}
end
function syntax.using(namespaceName)
-- Save our previous namespace and usings, incase our hook call loads new classes in other namespaces
local previousNamespace = activeNamespace
local previousUsings = activeUsings
-- Clear active namespace and usings
activeNamespace = false
activeUsings = {}
-- Fire the hook, you can load other namespaces or classes in this hook because we saved ours above.
local returnNamespace = simploo.hook:fire("onSyntaxUsing", namespaceName)
-- Restore the previous namespace and usings
activeNamespace = previousNamespace
activeUsings = previousUsings
-- Add the new using to our table
table.insert(activeUsings, {
path = returnNamespace or namespaceName,
alias = nil
})
end
function syntax.as(newPath)
if activeUsings[#activeUsings] then
activeUsings[#activeUsings]["alias"] = newPath
end
end
do
local overwrittenGlobals = {}
function syntax.init()
-- Add syntax things
for k, v in pairs(syntax) do
if k ~= "init" and k ~= "destroy" then
-- Backup existing globals that we may overwrite
if _G[k] then
overwrittenGlobals[k] = _G[k]
end
_G[k] = v
end
end
end
function syntax.destroy()
for k, v in pairs(syntax) do
if k ~= "init" and k ~= "destroy" then
_G[k] = nil
-- Restore existing globals
if overwrittenGlobals[k] then
_G[k] = overwrittenGlobals[k]
end
end
end
end
-- Add modifiers as global functions
for _, modifierName in pairs(simploo.parser.modifiers) do
syntax[modifierName] = function(body)
body["__modifiers"] = body["__modifiers"] or {}
table.insert(body["__modifiers"], modifierName)
return body
end
end
if simploo.config["exposeSyntax"] then
syntax.init()
end
end
----
---- hotswap.lua
----
local hotswap = {}
simploo.hotswap = hotswap
-- Separate global to prevent simploo reloading from cleaning the instances list.
-- Using a weak table so that we don't prevent all instances from being garbage collected.
local activeInstances = _G["simploo.instances"] or setmetatable({}, {__mode = "v"})
_G["simploo.instances"] = activeInstances
function hotswap:init()
simploo.hook:add("afterInstancerInitClass", function(classFormat, globalInstance)
hotswap:swap(globalInstance:get_class(), globalInstance)
end)
simploo.hook:add("afterInstancerInstanceNew", function(instance)
table.insert(activeInstances, instance)
end)
end
function hotswap:swap(newInstance)
for _, instance in pairs(activeInstances) do
if instance.className == newInstance.className then
hotswap:syncMembers(instance, newInstance)
end
end
end
function hotswap:syncMembers(currentInstance, newInstance)
-- Add members that do not exist in the current instance.
for newMemberName, newMember in pairs(newInstance.members) do
local contains = false
for prevMemberName, prevMember in pairs(currentInstance.members) do
if prevMemberName == newMemberName then
contains = true
end
end
if not contains then
local newMember = simploo.util.duplicateTable(newMember)
newMember.owner = currentInstance
currentInstance.members[newMemberName] = newMember
end
end
-- Remove members from the current instance that are not in the new instance.
for prevMemberName, prevMember in pairs(currentInstance.members) do
local exists = false
for newMemberName, newMember in pairs(newInstance.members) do
if prevMemberName == newMemberName then
exists = true
end
end
if not exists then
currentInstance.members[prevMemberName] = nil
end
end
end
if simploo.config["classHotswap"] then
hotswap:init()
end
|
--string ext
function string.split(str, split)
local splitlist = {}
string.gsub(str, '[^'..split..']+', function(w) table.insert(splitlist, w) end )
return splitlist
end
function string.coventable(table)
return require "pb/serpent".block(table)
end
|
local Draw = { }
local p = module.load("sutynkatarina", "spell/Passive");
local q = module.load("sutynkatarina", "spell/q");
local w = module.load("sutynkatarina", "spell/w");
local e = module.load("sutynkatarina", "spell/e");
local r = module.load("sutynkatarina", "spell/r");
local menu = module.load("sutynkatarina", "menu");
Draw.Draw_Q = function()
if (menu.Draw.drawq:get()) then
if (q.isready()) then
graphics.draw_circle(player.pos, q.range, 2, graphics.argb(255, 0, 255, 0), 100)
else
graphics.draw_circle(player.pos, q.range, 2, graphics.argb(255, 255, 0, 0), 100)
end
end
end
Draw.Draw_W = function()
if (menu.Draw.draww:get()) then
if (w.isready()) then
graphics.draw_circle(player.pos, w.range, 2, graphics.argb(255, 0, 255, 0), 100)
else
graphics.draw_circle(player.pos, w.range, 2, graphics.argb(255, 255, 0, 0), 100)
end
end
end
Draw.Draw_E = function()
if (menu.Draw.drawe:get()) then
if (e.isready()) then
graphics.draw_circle(player.pos, e.range, 2, graphics.argb(255, 0, 255, 0), 100)
else
graphics.draw_circle(player.pos, e.range, 2, graphics.argb(255, 255, 0, 0), 100)
end
end
end
Draw.Draw_R = function()
if (menu.Draw.drawr:get()) then
if (r.isready()) then
graphics.draw_circle(player.pos, r.range, 2, graphics.argb(255, 0, 255, 0), 100)
else
graphics.draw_circle(player.pos, r.range, 2, graphics.argb(255, 255, 0, 0), 100)
end
end
end
Draw.Draw_Human = function()
--
end
return Draw
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.