content stringlengths 5 1.05M |
|---|
object_tangible_loot_creature_loot_collections_shattered_shard_unknown_05 = object_tangible_loot_creature_loot_collections_shared_shattered_shard_unknown_05:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_shattered_shard_unknown_05, "object/tangible/loot/creature/loot/collections/shattered_shard_unknown_05.iff")
|
currCursor = 0
function fsOptions()
BIOSAPIS["sendMonitorSignal"]("set", "Welcome to BLOXOS setup master.\n")
BIOSAPIS["sendMonitorSignal"]("add", "Please select what filesystem should be installed: \n")
BIOSAPIS["sendMonitorSignal"]("add", "SMF (standard)")
if currCursor == 0 then
BIOSAPIS["sendMonitorSignal"]("add", "\n")
else
BIOSAPIS["sendMonitorSignal"]("add", " < \n")
end
BIOSAPIS["sendMonitorSignal"]("add", "HUF")
if currCursor == 1 then
BIOSAPIS["sendMonitorSignal"]("add", "\n")
else
BIOSAPIS["sendMonitorSignal"]("add", " < \n")
end
end
fsOptions()
while true do
clicked = BIOSAPIS["detectUserInput"]()
print(clicked)
if clicked == "arrUp" or clicked == "arrDown" then
if currCursor == 1 then
print('run for up')
currCursor = 0
fsOptions()
elseif clicked == "enter" then
break
elseif currCursor == 0 then
print('run for down')
currCursor = 1
fsOptions()
end
end
wait(0.5)
end
HDDmodule.exactAddContent(true, 2)
return currCursor
|
return {
id = 1201201,
bgm = "story-masazhusai",
stages = {
{
stageIndex = 1,
failCondition = 1,
timeCount = 180,
passCondition = 1,
backGroundStageID = 1,
totalArea = {
-75,
20,
90,
70
},
playerArea = {
-75,
20,
42,
68
},
enemyArea = {},
mainUnitPosition = {
{
Vector3(-105, 0, 58),
Vector3(-105, 0, 78),
Vector3(-105, 0, 38)
},
[-1] = {
Vector3(15, 0, 58),
Vector3(15, 0, 78),
Vector3(15, 0, 38)
}
},
fleetCorrdinate = {
-80,
0,
75
},
waves = {
{
triggerType = 1,
waveIndex = 100,
preWaves = {},
triggerParams = {
timeout = 0.5
}
},
{
triggerType = 0,
waveIndex = 201,
conditionType = 1,
preWaves = {
100
},
triggerParams = {
round = {
equal = {
1
}
}
},
spawn = {
{
monsterTemplateID = 900008,
moveCast = true,
delay = 1,
score = 0,
corrdinate = {
0,
0,
55
},
bossData = {
hpBarNum = 50,
icon = "aisaikesi"
},
phase = {
{
switchParam = 1,
switchTo = 1,
index = 0,
switchType = 1,
setAI = 10001
},
{
index = 1,
switchType = 1,
switchTo = 2,
switchParam = 3,
addWeapon = {
950152,
950153,
950154
}
},
{
switchType = 1,
switchTo = 3,
index = 2,
switchParam = 3,
setAI = 99990,
removeWeapon = {},
addWeapon = {
950157,
950159
}
},
{
switchType = 1,
switchTo = 4,
index = 3,
switchParam = 3,
setAI = 10001,
removeWeapon = {
950159
},
addWeapon = {
950158
},
addBuff = {}
},
{
index = 4,
switchType = 1,
switchTo = 5,
switchParam = 3,
removeWeapon = {
950158
},
addWeapon = {
950155,
950156
},
removeBuff = {},
addBuff = {}
},
{
switchType = 1,
switchTo = 6,
index = 5,
switchParam = 3,
setAI = 99990,
addWeapon = {
950157,
950159
}
},
{
switchType = 1,
switchTo = 7,
index = 6,
switchParam = 1,
setAI = 10001,
removeWeapon = {
950157,
950159
}
},
{
index = 7,
switchType = 1,
switchTo = 8,
switchParam = 5,
addWeapon = {}
},
{
index = 8,
switchParam = 4,
switchTo = 9,
switchType = 1,
removeWeapon = {
950155,
950156
},
addWeapon = {
950151
}
},
{
index = 9,
switchType = 1,
switchTo = 202,
switchParam = 3,
addWeapon = {
950155
}
},
{
index = 202,
switchType = 1,
switchTo = 1,
switchParam = 3,
removeWeapon = {
950151
}
}
}
}
}
},
{
triggerType = 0,
waveIndex = 202,
conditionType = 1,
preWaves = {
201
},
triggerParams = {
round = {
more = 1
}
},
spawn = {
{
monsterTemplateID = 900008,
reinforceDelay = 5,
delay = 1,
moveCast = true,
corrdinate = {
0,
0,
55
},
bossData = {
hpBarNum = 50,
icon = "aisaikesi"
},
phase = {
{
switchParam = 1,
switchTo = 1,
index = 0,
switchType = 1,
setAI = 10001
},
{
index = 1,
switchType = 1,
switchTo = 2,
switchParam = 3,
addWeapon = {
950152,
950153,
950154
}
},
{
switchType = 1,
switchTo = 3,
index = 2,
switchParam = 3,
setAI = 99990,
removeWeapon = {},
addWeapon = {
950157,
950159
}
},
{
switchType = 1,
switchTo = 4,
index = 3,
switchParam = 3,
setAI = 10001,
removeWeapon = {
950159
},
addWeapon = {
950158
},
addBuff = {}
},
{
index = 4,
switchType = 1,
switchTo = 5,
switchParam = 3,
removeWeapon = {
950158
},
addWeapon = {
950155,
950156
},
removeBuff = {},
addBuff = {}
},
{
switchType = 1,
switchTo = 6,
index = 5,
switchParam = 3,
setAI = 99990,
addWeapon = {
950157,
950159
}
},
{
switchType = 1,
switchTo = 7,
index = 6,
switchParam = 1,
setAI = 10001,
removeWeapon = {
950157,
950159
}
},
{
index = 7,
switchType = 1,
switchTo = 8,
switchParam = 5,
addWeapon = {}
},
{
index = 8,
switchParam = 4,
switchTo = 9,
switchType = 1,
removeWeapon = {
950155,
950156
},
addWeapon = {
950151
}
},
{
index = 9,
switchType = 1,
switchTo = 202,
switchParam = 3,
addWeapon = {
950155
}
},
{
index = 202,
switchType = 1,
switchTo = 1,
switchParam = 3,
removeWeapon = {
950151
}
}
}
}
},
reinforcement = {
{
monsterTemplateID = 909011,
moveCast = true,
delay = 0,
corrdinate = {
50,
0,
35
},
buffList = {
8001,
8002
}
},
{
monsterTemplateID = 909011,
moveCast = true,
delay = 0,
corrdinate = {
50,
0,
75
},
buffList = {
8001,
8002
}
}
}
},
{
triggerType = 8,
key = true,
waveIndex = 900,
preWaves = {
202
},
triggerParams = {}
}
}
}
},
fleet_prefab = {}
}
|
---
--- Created by heyqule.
--- DateTime: 03/27/2021 3:16 PM
--- require('__enemyracemanager__/lib/global_config')
---
local Table = require('__stdlib__/stdlib/utils/table')
local ErmDebugHelper = require('__enemyracemanager__/lib/debug_helper')
local ErmConfig = require('__enemyracemanager__/lib/global_config')
local ErmMapProcessor = require('__enemyracemanager__/lib/map_processor')
local SurfaceProcessor = {}
function SurfaceProcessor.init_globals()
global.enemy_surfaces = global.enemy_surfaces or {}
end
function SurfaceProcessor.assign_race(surface, race_name)
local races = ErmConfig.get_enemy_races()
local max_num = Table.size(races)
if max_num == 0 then
return
end
local race = nil
if race_name then
for k, v in pairs(races) do
if v == race_name then
race = v
break
end
end
else
race = races[math.random(1, max_num)]
end
global.enemy_surfaces[surface.name] = race
end
function SurfaceProcessor.remove_race(surface)
if global.enemy_surfaces[surface.name] ~= nil then
global.enemy_surfaces[surface.name] = nil
end
end
function SurfaceProcessor.rebuild_race()
if global.enemy_surfaces == nil then
return
end
for surface_index, race in pairs(global.enemy_surfaces) do
if game.surfaces[surface_index] == nil or (race ~= MOD_NAME and game.active_mods[race] == nil) then
SurfaceProcessor.remove_race(game.surfaces[surface_index])
end
end
for _, surface in pairs(game.surfaces) do
if global.enemy_surfaces[surface.name] == nil then
SurfaceProcessor.assign_race(game.surfaces[surface.index])
end
end
end
function SurfaceProcessor.numeric_to_name_conversion()
local tmpSurfaces = {}
for surface_index, race in pairs(global.enemy_surfaces) do
tmpSurfaces[game.surfaces[surface_index].name] = race
end
global.enemy_surfaces = tmpSurfaces
end
return SurfaceProcessor |
default_config = {
scale = 3,
fullscreen = 0,
vsync = true,
sfx_volume = 1.0,
music_volume = 0.5,
keys = {
up = "up", down = "down", left = "left", right = "right", jump = "s", shoot = "d", action = "a"
},
joykeys = {
jump = 1, shoot = 3, action = 2, pause = 8
}
}
keynames = {"up","down","left","right","jump","shoot","action"}
joykeynames = {"jump","shoot","action","pause"}
highscores = { {}, {}, {} }
stats = { 0, 0, 0, 0, 0, 0 }
keystate = {
up = false, down = false, left = false, right = false,
jump = false, shoot = false, action = false,
oldaxis1 = 0, oldaxis2 = 0
}
function loadConfig()
-- Read default settings first
config = {}
for i,v in pairs(default_config) do
if type(v) == "table" then
config[i] = {}
for j,w in pairs(v) do
config[i][j] = w
end
else
config[i] = v
end
end
if love.filesystem.exists("settings") then
local data = love.filesystem.read("settings")
local file = TSerial.unpack(data)
for i,v in pairs(file) do
config[i] = v
end
end
-- Avoid crash if fullscreen is a boolean from old version
if type(config.fullscreen) == "boolean" then
config.fullscreen = 0
end
end
function loadHighscores()
if love.filesystem.exists("highscores") then
local data = love.filesystem.read("highscores")
local file = TSerial.unpack(data)
for i=1,3 do
if file[i] then
highscores[i] = file[i]
end
end
end
end
function loadStats()
if love.filesystem.exists("stats") then
local data = love.filesystem.read("stats")
stats = TSerial.unpack(data)
end
end
function saveConfig()
local data = TSerial.pack(config)
love.filesystem.write("settings", data)
end
function saveHighscores()
local data = TSerial.pack(highscores)
love.filesystem.write("highscores", data)
end
function saveStats()
local data = TSerial.pack(stats)
love.filesystem.write("stats", data)
end
function setMode()
if config.fullscreen == 0 then
love.window.setMode(WIDTH*config.scale, HEIGHT*config.scale, {fullscreen=false, vsync=config.vsync})
love.graphics.setScissor()
elseif config.fullscreen > 0 and config.fullscreen <= 3 then
love.window.setMode(0,0, {fullscreen=true, vsync=config.vsync})
love.window.setMode(love.graphics.getWidth(), love.graphics.getHeight(), {fullscreen=true, vsync=config.vsync})
end
fs_translatex = (love.graphics.getWidth()-WIDTH*config.scale)/2
fs_translatey = (love.graphics.getHeight()-HEIGHT*config.scale)/2
end
function toggleVSync()
config.vsync = not config.vsync
setMode()
end
function defaultKeys()
for i,v in pairs(default_config.keys) do
config.keys[i] = v
end
end
function defaultJoyKeys()
for i,v in pairs(default_config.joykeys) do
config.joykeys[i] = v
end
end
|
function pi()
N = 14 * 5000
NM = N - 14
a = {}
d = 0
e = 0
g = 0
h = 0
f = 10000
cnt = 1
c = NM
while c > 0 do
d = math.mod(d, f)
e = d
b = c - 1
while b > 0 do
g = 2 * b - 1
if c ~= NM then
if a[b] == nil then
a[b] = 0
end
d = d * b + f * a[b]
else
d = d * b + f * (f / 5)
end
a[b] = math.mod(d, g)
d = d / g
b = b - 1
end
io.write(string.format("%04d", e + d / f))
if math.mod(cnt, 16) == 0 then
print("")
end
cnt = cnt + 1
c = c - 14;
end
end
print(pi())
|
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local accMgr = require "manager.accMgr"
local config = require "login.config"
local mysql = require "include.mysql"
local CDb = require "include.db"
local function check_string(str)
if not str then str = "" end
return ngx.quote_sql_str(tostring(str))
end
local _M = function(args)
local db = CDb:new(config.user_db)
if not args or not args.cid then return false,"wrong parameter3" end
local uid = nil
local cid = check_string(args.cid)
local cn = check_string(args.cn)
local info = check_string(args.info)
local con = mysql:new(config.user_db.ip,config.user_db.port,config.user_db.user,config.user_db.pw,config.user_db.db)
local sql = "SELECT * FROM " .. config.user_db.table .. " WHERE cid=" .. cid
local result,errmsg = con:query(sql)
if not result or #result > 1 then
return false,"query failed from account table==>" .. errmsg
end
if #result == 0 then
sql = "INSERT INTO " .. config.user_db.table .. "(cid,cn,info) VALUES (" .. cid .. "," .. cn .. "," .. info .. ")"
local result,errmsg = con:query(sql)
if not result then
return false,"query failed from account table==>" .. errmsg
end
uid = result.insert_id
else
uid = result[1].uid
cn = result[1].cn
info = result[1].info
end
--ngx.log(ngx.ERR,"cid:",cid," uid:",uid)
con:close()
accMgr:login(uid,cid,cn,info)
local ret = {
uid = uid,
verifycode = accMgr:get_verifycode(uid)
}
return true,ret
end
return _M |
do
local ROLL_USAGE = "!roll d<sides>|<count> d<sides>"
local DEFAULT_SIDES = 100
local DEFAULT_NUMBER_OF_DICE = 1
local MAX_NUMBER_OF_DICE = 100
function run(msg, matches)
local str = matches[1]
local sides = DEFAULT_SIDES
local number_of_dice = DEFAULT_NUMBER_OF_DICE
if str:find("!roll%s+d%d+%s*$") then
sides = tonumber(str:match("[^d]%d+%s*$"))
elseif str:find("!roll%s+%d+d%d+%s*$") then
number_of_dice = tonumber(str:match("%s+%d+"))
sides = tonumber(str:match("%d+%s*$"))
end
if number_of_dice > MAX_NUMBER_OF_DICE then
number_of_dice = MAX_NUMBER_OF_DICE
end
local padding = #string.format("%d", sides)
local results = ""
local fmt = "%s %0"..padding.."d"
for i=1,number_of_dice do
results = string.format(fmt, results, math.random(sides))
end
return string.format("Rolling %dd%d:\n%s", number_of_dice, sides, results)
end
return {
description = "Roll some dice!",
usage = ROLL_USAGE,
patterns = {
"^!roll%s*.*"
},
run = run
}
end
|
cc = cc or {}
---Controller object
---@class Controller
local Controller = {}
cc.Controller = Controller
--------------------------------
---Activate receives key event from external key. e.g. back,menu.<br>
---Controller receives only standard key which contained within enum Key by default.<br>
---warning The API only work on the android platform for support diversified game controller.<br>
---param externalKeyCode External key code.<br>
---param receive True if external key event on this controller should be receive, false otherwise.
---@param externalKeyCode int
---@param receive bool
---@return Controller
function Controller:receiveExternalKeyEvent(externalKeyCode, receive) end
--------------------------------
---Gets the name of this Controller object.
---@return string
function Controller:getDeviceName() end
--------------------------------
---Indicates whether the Controller is connected.
---@return bool
function Controller:isConnected() end
--------------------------------
---Gets the Controller id.
---@return int
function Controller:getDeviceId() end
--------------------------------
---Changes the tag that is used to identify the controller easily.<br>
---param tag A integer that identifies the controller.
---@param tag int
---@return Controller
function Controller:setTag(tag) end
--------------------------------
---Returns a tag that is used to identify the controller easily.<br>
---return An integer that identifies the controller.
---@return int
function Controller:getTag() end
--------------------------------
---Start discovering new controllers.<br>
---warning The API has an empty implementation on Android.
---@return Controller
function Controller:startDiscoveryController() end
--------------------------------
---Stop the discovery process.<br>
---warning The API has an empty implementation on Android.
---@return Controller
function Controller:stopDiscoveryController() end
--------------------------------
---Gets a Controller object with device ID.<br>
---param deviceId A unique identifier to find the controller.<br>
---return A Controller object.
---@param deviceId int
---@return Controller
function Controller:getControllerByDeviceId(deviceId) end
--------------------------------
---Gets a Controller object with tag.<br>
---param tag An identifier to find the controller.<br>
---return A Controller object.
---@param tag int
---@return Controller
function Controller:getControllerByTag(tag) end
return Controller |
-- Copyright 2018-2020 Lienol <lawlienol@gmail.com>
module("luci.controller.kodexplorer", package.seeall)
local http = require "luci.http"
local api = require "luci.model.cbi.kodexplorer.api"
function index()
if not nixio.fs.access("/etc/config/kodexplorer") then return end
entry({"admin", "nas"}, firstchild(), "NAS", 44).dependent = false
entry({"admin", "nas", "kodexplorer"}, cbi("kodexplorer/settings"), _("KodExplorer"), 3).dependent = true
entry({"admin", "nas", "kodexplorer", "check"}, call("action_check")).leaf = true
entry({"admin", "nas", "kodexplorer", "download"}, call("action_download")).leaf = true
entry({"admin", "nas", "kodexplorer", "status"}, call("act_status")).leaf = true
end
local function http_write_json(content)
http.prepare_content("application/json")
http.write_json(content or {code = 1})
end
function act_status()
local e = {}
e.nginx_status = luci.sys.call("ps -w | grep nginx | grep kodexplorer | grep -v grep > /dev/null") == 0
e.php_status = luci.sys.call("ps -w | grep php | grep kodexplorer | grep -v grep > /dev/null") == 0
http_write_json(e)
end
function action_check()
local json = api.to_check()
http_write_json(json)
end
function action_download()
local json = nil
local task = http.formvalue("task")
if task == "extract" then
json = api.to_extract(http.formvalue("file"))
elseif task == "move" then
json = api.to_move(http.formvalue("file"))
else
json = api.to_download(http.formvalue("url"))
end
http_write_json(json)
end
|
local iron = require('iron')
iron.core.add_repl_definitions {
cpp = {
cling = {
command = {'cling', '-std=c++17'}
}
},
lua = {
croissant = {
command = {'croissant'}
}
},
fennel = {
fennel = {
command = {'fennel'}
}
}
}
iron.core.set_config {
preferred = {
python = 'ptipython',
haskell = 'intero',
lisp = 'sbcl',
ocaml = 'utop',
scheme = 'csi',
lua = 'croissant',
-- ruby = 'irb',
-- elixir = 'iex',
}
}
|
--// Sledbuild scoreboard + some stuff //--
local function CreatePlayerInfo( pl )
local pinfo = { pl:Nick(),
pl:Frags(),
pl:Deaths(),
pl:GetNWInt( "_SPEED" ),
pl:GetNWInt( "_CTS" ),
pl:GetNWInt( "_GTS" ),
pl:Ping()
}
return pinfo
end
local function GetScoreboardTable()
local STable = {}
for id, pl in pairs( player.GetAll() ) do
local tid = pl:Team()
if !STable[tid] then
STable[tid] = {}
STable[tid].Color = team.GetColor( team )
STable[tid].Players = {}
end
local PlayerInfo = CreatePlayerInfo( pl )
local insertPos = #STable[tid].Players + 1
for idx, info in pairs( STable[tid].Players ) do
if ( PlayerInfo[6] > info[6] ) then
insertPos = idx
break
elseif( PlayerInfo[6] == info[6] ) then
if ( PlayerInfo[5] > info[5] ) then
insertPos = idx
break
end
end
end
table.insert( STable[tid].Players, insertPos, PlayerInfo )
end
for tid, tinfo in pairs( STable ) do for pid, pinfo in pairs( tinfo.Players ) do
pinfo[4] = tostring( pinfo[4] / 10 ).." km/h"
pinfo[5] = tostring( pinfo[5] / 10 ).." km/h"
pinfo[6] = tostring( pinfo[6] / 10 ).." km/h"
end end
return STable
end
function HUDDrawScoreBoard( startX, startY, bWidth )
local Captions = { {"Name",37}, {"Won",7}, {"Lost",7}, {"Speed",13}, {"Top Speed",13}, {"Record",13}, {"Lag",10} }
local STable = GetScoreboardTable()
local bHeight = 0
// Get the font height
surface.SetFont( "Trebuchet18" )
local txWidth, txHeight = surface.GetTextSize( "W" )
local RowHeight = txHeight + 4
txWidth, txHeight = nil, nil
// Column width definitions
local ColWidths = {}
for k, v in pairs( Captions ) do
local tcol = {}
tcol.width = math.floor( ( v[2]/100 ) * ( bWidth ) )
tcol.start = 0
if #ColWidths > 0 then
for _, i in pairs( ColWidths ) do
tcol.start = tcol.start + i.width
end
end
ColWidths[k] = tcol
end
// Scoreboard table creation
local SBT = {}
// - The row with the captions
local CaptionRow = {}
CaptionRow.TYPE = "Captions"
CaptionRow.Color = BGCOLOR
CaptionRow.TColor = Color( 255, 255, 255, 255 )
CaptionRow.Cols = {}
for k, v in pairs( Captions ) do
table.insert( CaptionRow.Cols, v[1] )
end
table.insert( SBT, #SBT+1, CaptionRow )
CaptionRow = nil
// - The rows with the players
for tid, tinfo in pairs( STable ) do
local tcolorn = Color( 250, 250, 250, CELLALPHA )
local tcolorh = Color( 230, 230, 250, CELLALPHA )
for pid, pinfo in pairs( tinfo.Players ) do
local trow = {}
trow.TYPE = "Player"
trow.Color = tcolorn
if ( ( #SBT % 2 ) == 0 ) then
trow.Color = tcolorh
end
if tid == 2 then
trow.TColor = Color(80,80,255,255)
else
trow.TColor = Color(255,80,80,255)
end
trow.Cols = pinfo
table.insert( SBT, #SBT+1, trow )
end
end
// Draw the Scoreboard table
bHeight = #SBT * RowHeight + 10
//SetDrawColor( BGCOLOR )
//surface.DrawRect( startX, startY, bWidth, bHeight )
startY = startY + 5
local ry = 0
for rid, row in pairs( SBT ) do
ry = startY + (rid - 1) * RowHeight
SetDrawColor( row.Color )
surface.DrawRect( startX, ry, bWidth, RowHeight )
for cid, col in pairs( row.Cols ) do
local rx = startX + ColWidths[cid].start
local rw = ColWidths[cid].width
local txWidth, txHeight = surface.GetTextSize( tostring( col or "ERROR" ) )
rx = rx + ( rw / 2 ) - ( txWidth / 2 )
surface.SetFont( "Trebuchet18" )
SetTextColor( row.TColor )
surface.SetTextPos( math.floor( rx ), math.floor( ry ) + 2 )
surface.DrawText( col )
end
end
SetDrawColor( HIGHLIGHT )
SetDrawColor( BGCOLOR )
surface.DrawRect( startX, ry + RowHeight, bWidth, 10 )
for _, col in pairs( ColWidths ) do
if col.start > startX then
surface.DrawLine( startX + col.start, startY, startX + col.start, startY + bHeight )
end
end
SetDrawColor( BGCOLOR )
surface.DrawOutlinedRect( startX, startY, bWidth, bHeight )
surface.SetDrawColor( 255, 255, 255, 127 )
surface.DrawOutlinedRect( startX-1, startY-1, bWidth+2, bHeight+2 )
end
|
dice = require('dice')
math.randomseed(os.time())
weapon = dice:new('1d6') -- 1d6
-- Subtraction or addition modifies the bonus of the rolls
weapon = weapon + 4 -- 1d6+4
weapon = weapon - 2 -- 1d6+2
-- Multiplcation modifies the number of dice
weapon = weapon * 2 -- 3d6+2
-- Division modifies the number of faces on the dice
weapon = weapon / -2 -- 3d4+2
-- Exponential modifies the rerolls (positive number removes low rolls, negative number removes high rolls)
weapon = weapon ^ 1 -- 3d4+2^+1
-- Modulo division modifies the dice sets (returns multiple results)
weapon = weapon % 2 --(3d4+1^+1)x3
-- To string operations returns a dice notation string
print(weapon) --(3d4+2^+1)x3
-- Concat operations is a tricky concept to explain. Concating the dice with the following strings
-- '++', '--', '^^', '+', '-', '^' or a combination of both disables or enables plurality of bonus/rerolls
-- if a double operation sign is used, then the effect will be MULTIPLIED TO ALL dice
-- if a single operation sign is used, then the effect will apply as normal
-- Let us create a new weapon to demonstrate this with bonuses
weapon = dice:new('3d1+2')
-- Time to show how it is calculated
print(weapon:roll()) -- 1 + 1 + (1+2) RESULT=5
-- Enable plurality for bonus
weapon = weapon .. '++' -- 3d1++2
-- Calculation is much different now!
print(weapon:roll()) -- (1+2) + (1+2) + (1+2) RESULT=9
-- Reset back to normal
weapon = weapon .. '+' --Plurality is now disabled for bonus
-- Alternatively instead of '++' and '+' you may opt to use '--' and '-' instead.
-- Both signs enable/disable plurality for bonus
-- Another new weapon to demonstrate plurality for rerolls
weapon = dice:new('2d6^+1')
-- Rolls 2 dice and one extra
print(weapon:roll()) -- (5) (3) (1) -- Out of the 3 dice, remove the lowest roll -> (1) RESULT=8
-- Enable plurality for rerolls
weapon = weapon .. '^^'
-- Now rolls 2 dice and two extra
print(weapon:roll()) -- (2) (6) (4) (2) -- Out of the 4 dice, remove the two lowest rolls -> (2) (2) RESULT=10
|
return {
encode = function(s)
local result = ''
local i = 1
while i <= #s do
local c = s:sub(i, i)
local _, _, run = s:find('(' .. c .. '+)', i)
result = result .. ((#run > 1) and #run or '') .. c
i = i + #run
end
return result
end,
decode = function(s)
local result = ''
for length, c in s:gmatch('(%d*)(.)') do
if length == '' then length = 1 end
result = result .. c:rep(length)
end
return result
end
}
|
if not modules then modules = { } end modules ['char-ini'] = {
version = 1.001,
comment = "companion to char-ini.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
-- todo: make two files, one for format generation, one for format use
-- todo: move some to char-utf
-- we can remove the tag range starting at 0xE0000 (special applications)
local utfchar, utfbyte, utfvalues, ustring, utotable = utf.char, utf.byte, utf.values, utf.ustring, utf.totable
local concat, unpack, tohash, insert = table.concat, table.unpack, table.tohash, table.insert
local next, tonumber, type, rawget, rawset = next, tonumber, type, rawget, rawset
local format, lower, gsub = string.format, string.lower, string.gsub
local P, R, S, Cs = lpeg.P, lpeg.R, lpeg.S, lpeg.Cs
if not characters then require("char-def") end
local lpegpatterns = lpeg.patterns
local lpegmatch = lpeg.match
local utf8byte = lpegpatterns.utf8byte
local utf8character = lpegpatterns.utf8character
local utfchartabletopattern = lpeg.utfchartabletopattern
local allocate = utilities.storage.allocate
local mark = utilities.storage.mark
local setmetatableindex = table.setmetatableindex
local trace_defining = false trackers.register("characters.defining", function(v) characters_defining = v end)
local report_defining = logs.reporter("characters")
--[[ldx--
<p>This module implements some methods and creates additional datastructured
from the big character table that we use for all kind of purposes:
<type>char-def.lua</type>.</p>
<p>We assume that at this point <type>characters.data</type> is already
loaded!</p>
--ldx]]--
-- todo: in 'char-def.lua' assume defaults:
--
-- directtions = l
-- cjkwd = a
-- linebreak = al
characters = characters or { }
local characters = characters
local data = characters.data
if data then
mark(data) -- why does this fail
else
report_defining("fatal error: 'char-def.lua' is not loaded")
os.exit()
end
--[[ldx--
<p>This converts a string (if given) into a number.</p>
--ldx]]--
local pattern = (P("0x") + P("U+")) * ((R("09","AF")^1 * P(-1)) / function(s) return tonumber(s,16) end)
lpegpatterns.chartonumber = pattern
local function chartonumber(k)
if type(k) == "string" then
local u = lpegmatch(pattern,k)
if u then
return utfbyte(u)
else
return utfbyte(k) or 0
end
else
return k or 0
end
end
local function charfromnumber(k)
if type(k) == "number" then
return utfchar(k) or ""
else
local u = lpegmatch(pattern,k)
if u then
return utfchar(u)
else
return k
end
end
end
--~ print(chartonumber(97), chartonumber("a"), chartonumber("0x61"), chartonumber("U+61"))
characters.tonumber = chartonumber
characters.fromnumber = charfromnumber
local private = {
description = "PRIVATE SLOT",
}
local ranges = allocate()
characters.ranges = ranges
setmetatableindex(data, function(t,k)
local tk = type(k)
if tk == "string" then
k = lpegmatch(pattern,k) or utfbyte(k)
if k then
local v = rawget(t,k)
if v then
return v
else
tk = "number" -- fall through to range
end
else
return private
end
end
if tk == "number" and k < 0xF0000 then
for r=1,#ranges do
local rr = ranges[r]
if k >= rr.first and k <= rr.last then
local extender = rr.extender
if extender then
local v = extender(k)
t[k] = v
return v
end
end
end
end
return private -- handy for when we loop over characters in fonts and check for a property
end)
local variant_selector_metatable = {
category = "mn",
cjkwd = "a",
direction = "nsm",
linebreak = "cm",
}
-- This saves a bit of memory and also serves as example.
local f_variant = string.formatters["VARIATION SELECTOR-0x%04X"]
insert(characters.ranges,{
first = 0xFE00,
last = 0xFE0F,
name = "variant selector",
extender = function(k)
local t = {
description = f_variant(k - 0xFE00 + 0x0001),
unicodeslot = k,
}
setmetatable(t,variant_selector_metatable)
return t
end,
})
insert(characters.ranges,{
first = 0xE0100,
last = 0xE01EF,
name = "variant selector extension",
extender = function(k)
local t = {
description = f_variant(k - 0xE0100 + 0x0011),
unicodeslot = k,
}
setmetatable(t,variant_selector_metatable)
return t
end,
})
local blocks = allocate {
["aegeannumbers"] = { first = 0x10100, last = 0x1013F, description = "Aegean Numbers" },
["ahom"] = { first = 0x11700, last = 0x1173F, description = "Ahom" },
["alchemicalsymbols"] = { first = 0x1F700, last = 0x1F77F, description = "Alchemical Symbols" },
["alphabeticpresentationforms"] = { first = 0x0FB00, last = 0x0FB4F, otf="latn", description = "Alphabetic Presentation Forms" },
["anatolianhieroglyphs"] = { first = 0x14400, last = 0x1467F, description = "Anatolian Hieroglyphs" },
["ancientgreekmusicalnotation"] = { first = 0x1D200, last = 0x1D24F, otf="grek", description = "Ancient Greek Musical Notation" },
["ancientgreeknumbers"] = { first = 0x10140, last = 0x1018F, otf="grek", description = "Ancient Greek Numbers" },
["ancientsymbols"] = { first = 0x10190, last = 0x101CF, otf="grek", description = "Ancient Symbols" },
["arabic"] = { first = 0x00600, last = 0x006FF, otf="arab", description = "Arabic" },
["arabicextendeda"] = { first = 0x008A0, last = 0x008FF, description = "Arabic Extended-A" },
["arabicmathematicalalphabeticsymbols"] = { first = 0x1EE00, last = 0x1EEFF, description = "Arabic Mathematical Alphabetic Symbols" },
["arabicpresentationformsa"] = { first = 0x0FB50, last = 0x0FDFF, otf="arab", description = "Arabic Presentation Forms-A" },
["arabicpresentationformsb"] = { first = 0x0FE70, last = 0x0FEFF, otf="arab", description = "Arabic Presentation Forms-B" },
["arabicsupplement"] = { first = 0x00750, last = 0x0077F, otf="arab", description = "Arabic Supplement" },
["armenian"] = { first = 0x00530, last = 0x0058F, otf="armn", description = "Armenian" },
["arrows"] = { first = 0x02190, last = 0x021FF, description = "Arrows" },
["avestan"] = { first = 0x10B00, last = 0x10B3F, description = "Avestan" },
["balinese"] = { first = 0x01B00, last = 0x01B7F, otf="bali", description = "Balinese" },
["bamum"] = { first = 0x0A6A0, last = 0x0A6FF, description = "Bamum" },
["bamumsupplement"] = { first = 0x16800, last = 0x16A3F, description = "Bamum Supplement" },
["basiclatin"] = { first = 0x00000, last = 0x0007F, otf="latn", description = "Basic Latin" },
["bassavah"] = { first = 0x16AD0, last = 0x16AFF, description = "Bassa Vah" },
["batak"] = { first = 0x01BC0, last = 0x01BFF, description = "Batak" },
["bengali"] = { first = 0x00980, last = 0x009FF, otf="beng", description = "Bengali" },
["blockelements"] = { first = 0x02580, last = 0x0259F, otf="bopo", description = "Block Elements" },
["bopomofo"] = { first = 0x03100, last = 0x0312F, otf="bopo", description = "Bopomofo" },
["bopomofoextended"] = { first = 0x031A0, last = 0x031BF, otf="bopo", description = "Bopomofo Extended" },
["boxdrawing"] = { first = 0x02500, last = 0x0257F, description = "Box Drawing" },
["brahmi"] = { first = 0x11000, last = 0x1107F, description = "Brahmi" },
["braillepatterns"] = { first = 0x02800, last = 0x028FF, otf="brai", description = "Braille Patterns" },
["buginese"] = { first = 0x01A00, last = 0x01A1F, otf="bugi", description = "Buginese" },
["buhid"] = { first = 0x01740, last = 0x0175F, otf="buhd", description = "Buhid" },
["byzantinemusicalsymbols"] = { first = 0x1D000, last = 0x1D0FF, otf="byzm", description = "Byzantine Musical Symbols" },
["carian"] = { first = 0x102A0, last = 0x102DF, description = "Carian" },
["caucasianalbanian"] = { first = 0x10530, last = 0x1056F, description = "Caucasian Albanian" },
["chakma"] = { first = 0x11100, last = 0x1114F, description = "Chakma" },
["cham"] = { first = 0x0AA00, last = 0x0AA5F, description = "Cham" },
["cherokee"] = { first = 0x013A0, last = 0x013FF, otf="cher", description = "Cherokee" },
["cherokeesupplement"] = { first = 0x0AB70, last = 0x0ABBF, description = "Cherokee Supplement" },
["cjkcompatibility"] = { first = 0x03300, last = 0x033FF, otf="hang", description = "CJK Compatibility" },
["cjkcompatibilityforms"] = { first = 0x0FE30, last = 0x0FE4F, otf="hang", description = "CJK Compatibility Forms" },
["cjkcompatibilityideographs"] = { first = 0x0F900, last = 0x0FAFF, otf="hang", description = "CJK Compatibility Ideographs" },
["cjkcompatibilityideographssupplement"] = { first = 0x2F800, last = 0x2FA1F, otf="hang", description = "CJK Compatibility Ideographs Supplement" },
["cjkradicalssupplement"] = { first = 0x02E80, last = 0x02EFF, otf="hang", description = "CJK Radicals Supplement" },
["cjkstrokes"] = { first = 0x031C0, last = 0x031EF, otf="hang", description = "CJK Strokes" },
["cjksymbolsandpunctuation"] = { first = 0x03000, last = 0x0303F, otf="hang", description = "CJK Symbols and Punctuation" },
["cjkunifiedideographs"] = { first = 0x04E00, last = 0x09FFF, otf="hang", description = "CJK Unified Ideographs", catcode = "letter" },
["cjkunifiedideographsextensiona"] = { first = 0x03400, last = 0x04DBF, otf="hang", description = "CJK Unified Ideographs Extension A" },
["cjkunifiedideographsextensionb"] = { first = 0x20000, last = 0x2A6DF, otf="hang", description = "CJK Unified Ideographs Extension B" },
["cjkunifiedideographsextensionc"] = { first = 0x2A700, last = 0x2B73F, description = "CJK Unified Ideographs Extension C" },
["cjkunifiedideographsextensiond"] = { first = 0x2B740, last = 0x2B81F, description = "CJK Unified Ideographs Extension D" },
["cjkunifiedideographsextensione"] = { first = 0x2B820, last = 0x2CEAF, description = "CJK Unified Ideographs Extension E" },
["combiningdiacriticalmarks"] = { first = 0x00300, last = 0x0036F, description = "Combining Diacritical Marks" },
["combiningdiacriticalmarksextended"] = { first = 0x01AB0, last = 0x01AFF, description = "Combining Diacritical Marks Extended" },
["combiningdiacriticalmarksforsymbols"] = { first = 0x020D0, last = 0x020FF, description = "Combining Diacritical Marks for Symbols" },
["combiningdiacriticalmarkssupplement"] = { first = 0x01DC0, last = 0x01DFF, description = "Combining Diacritical Marks Supplement" },
["combininghalfmarks"] = { first = 0x0FE20, last = 0x0FE2F, description = "Combining Half Marks" },
["commonindicnumberforms"] = { first = 0x0A830, last = 0x0A83F, description = "Common Indic Number Forms" },
["controlpictures"] = { first = 0x02400, last = 0x0243F, description = "Control Pictures" },
["coptic"] = { first = 0x02C80, last = 0x02CFF, otf="copt", description = "Coptic" },
["copticepactnumbers"] = { first = 0x102E0, last = 0x102FF, description = "Coptic Epact Numbers" },
["countingrodnumerals"] = { first = 0x1D360, last = 0x1D37F, description = "Counting Rod Numerals" },
["cuneiform"] = { first = 0x12000, last = 0x123FF, otf="xsux", description = "Cuneiform" },
["cuneiformnumbersandpunctuation"] = { first = 0x12400, last = 0x1247F, otf="xsux", description = "Cuneiform Numbers and Punctuation" },
["currencysymbols"] = { first = 0x020A0, last = 0x020CF, description = "Currency Symbols" },
["cypriotsyllabary"] = { first = 0x10800, last = 0x1083F, otf="cprt", description = "Cypriot Syllabary" },
["cyrillic"] = { first = 0x00400, last = 0x004FF, otf="cyrl", description = "Cyrillic" },
["cyrillicextendeda"] = { first = 0x02DE0, last = 0x02DFF, otf="cyrl", description = "Cyrillic Extended-A" },
["cyrillicextendedb"] = { first = 0x0A640, last = 0x0A69F, otf="cyrl", description = "Cyrillic Extended-B" },
["cyrillicsupplement"] = { first = 0x00500, last = 0x0052F, otf="cyrl", description = "Cyrillic Supplement" },
["deseret"] = { first = 0x10400, last = 0x1044F, otf="dsrt", description = "Deseret" },
["devanagari"] = { first = 0x00900, last = 0x0097F, otf="deva", description = "Devanagari" },
["devanagariextended"] = { first = 0x0A8E0, last = 0x0A8FF, description = "Devanagari Extended" },
["digitsarabicindic"] = { first = 0x00660, last = 0x00669, math = true },
-- ["digitsbengali"] = { first = 0x009E6, last = 0x009EF, math = true },
["digitsbold"] = { first = 0x1D7CE, last = 0x1D7D8, math = true },
-- ["digitsdevanagari"] = { first = 0x00966, last = 0x0096F, math = true },
["digitsdoublestruck"] = { first = 0x1D7D8, last = 0x1D7E2, math = true },
-- ["digitsethiopic"] = { first = 0x01369, last = 0x01371, math = true },
["digitsextendedarabicindic"] = { first = 0x006F0, last = 0x006F9, math = true },
-- ["digitsgujarati"] = { first = 0x00AE6, last = 0x00AEF, math = true },
-- ["digitsgurmukhi"] = { first = 0x00A66, last = 0x00A6F, math = true },
-- ["digitskannada"] = { first = 0x00CE6, last = 0x00CEF, math = true },
-- ["digitskhmer"] = { first = 0x017E0, last = 0x017E9, math = true },
-- ["digitslao"] = { first = 0x00ED0, last = 0x00ED9, math = true },
["digitslatin"] = { first = 0x00030, last = 0x00039, math = true },
-- ["digitsmalayalam"] = { first = 0x00D66, last = 0x00D6F, math = true },
-- ["digitsmongolian"] = { first = 0x01810, last = 0x01809, math = true },
["digitsmonospace"] = { first = 0x1D7F6, last = 0x1D80F, math = true },
-- ["digitsmyanmar"] = { first = 0x01040, last = 0x01049, math = true },
["digitsnormal"] = { first = 0x00030, last = 0x00039, math = true },
-- ["digitsoriya"] = { first = 0x00B66, last = 0x00B6F, math = true },
["digitssansserifbold"] = { first = 0x1D7EC, last = 0x1D805, math = true },
["digitssansserifnormal"] = { first = 0x1D7E2, last = 0x1D7EC, math = true },
-- ["digitstamil"] = { first = 0x00030, last = 0x00039, math = true }, -- no zero
-- ["digitstelugu"] = { first = 0x00C66, last = 0x00C6F, math = true },
-- ["digitsthai"] = { first = 0x00E50, last = 0x00E59, math = true },
-- ["digitstibetan"] = { first = 0x00F20, last = 0x00F29, math = true },
["dingbats"] = { first = 0x02700, last = 0x027BF, description = "Dingbats" },
["dominotiles"] = { first = 0x1F030, last = 0x1F09F, description = "Domino Tiles" },
["duployan"] = { first = 0x1BC00, last = 0x1BC9F, description = "Duployan" },
["earlydynasticcuneiform"] = { first = 0x12480, last = 0x1254F, description = "Early Dynastic Cuneiform" },
["egyptianhieroglyphs"] = { first = 0x13000, last = 0x1342F, description = "Egyptian Hieroglyphs" },
["elbasan"] = { first = 0x10500, last = 0x1052F, description = "Elbasan" },
["emoticons"] = { first = 0x1F600, last = 0x1F64F, description = "Emoticons" },
["enclosedalphanumerics"] = { first = 0x02460, last = 0x024FF, description = "Enclosed Alphanumerics" },
["enclosedalphanumericsupplement"] = { first = 0x1F100, last = 0x1F1FF, description = "Enclosed Alphanumeric Supplement" },
["enclosedcjklettersandmonths"] = { first = 0x03200, last = 0x032FF, description = "Enclosed CJK Letters and Months" },
["enclosedideographicsupplement"] = { first = 0x1F200, last = 0x1F2FF, description = "Enclosed Ideographic Supplement" },
["ethiopic"] = { first = 0x01200, last = 0x0137F, otf="ethi", description = "Ethiopic" },
["ethiopicextended"] = { first = 0x02D80, last = 0x02DDF, otf="ethi", description = "Ethiopic Extended" },
["ethiopicextendeda"] = { first = 0x0AB00, last = 0x0AB2F, description = "Ethiopic Extended-A" },
["ethiopicsupplement"] = { first = 0x01380, last = 0x0139F, otf="ethi", description = "Ethiopic Supplement" },
["generalpunctuation"] = { first = 0x02000, last = 0x0206F, description = "General Punctuation" },
["geometricshapes"] = { first = 0x025A0, last = 0x025FF, math = true, description = "Geometric Shapes" },
["geometricshapesextended"] = { first = 0x1F780, last = 0x1F7FF, description = "Geometric Shapes Extended" },
["georgian"] = { first = 0x010A0, last = 0x010FF, otf="geor", description = "Georgian" },
["georgiansupplement"] = { first = 0x02D00, last = 0x02D2F, otf="geor", description = "Georgian Supplement" },
["glagolitic"] = { first = 0x02C00, last = 0x02C5F, otf="glag", description = "Glagolitic" },
["gothic"] = { first = 0x10330, last = 0x1034F, otf="goth", description = "Gothic" },
["grantha"] = { first = 0x11300, last = 0x1137F, description = "Grantha" },
["greekandcoptic"] = { first = 0x00370, last = 0x003FF, otf="grek", description = "Greek and Coptic" },
["greekextended"] = { first = 0x01F00, last = 0x01FFF, otf="grek", description = "Greek Extended" },
["gujarati"] = { first = 0x00A80, last = 0x00AFF, otf="gujr", description = "Gujarati" },
["gurmukhi"] = { first = 0x00A00, last = 0x00A7F, otf="guru", description = "Gurmukhi" },
["halfwidthandfullwidthforms"] = { first = 0x0FF00, last = 0x0FFEF, description = "Halfwidth and Fullwidth Forms" },
["hangulcompatibilityjamo"] = { first = 0x03130, last = 0x0318F, otf="jamo", description = "Hangul Compatibility Jamo" },
["hanguljamo"] = { first = 0x01100, last = 0x011FF, otf="jamo", description = "Hangul Jamo" },
["hanguljamoextendeda"] = { first = 0x0A960, last = 0x0A97F, description = "Hangul Jamo Extended-A" },
["hanguljamoextendedb"] = { first = 0x0D7B0, last = 0x0D7FF, description = "Hangul Jamo Extended-B" },
["hangulsyllables"] = { first = 0x0AC00, last = 0x0D7AF, otf="hang", description = "Hangul Syllables" },
["hanunoo"] = { first = 0x01720, last = 0x0173F, otf="hano", description = "Hanunoo" },
["hatran"] = { first = 0x108E0, last = 0x108FF, description = "Hatran" },
["hebrew"] = { first = 0x00590, last = 0x005FF, otf="hebr", description = "Hebrew" },
["highprivateusesurrogates"] = { first = 0x0DB80, last = 0x0DBFF, description = "High Private Use Surrogates" },
["highsurrogates"] = { first = 0x0D800, last = 0x0DB7F, description = "High Surrogates" },
["hiragana"] = { first = 0x03040, last = 0x0309F, otf="kana", description = "Hiragana" },
["ideographicdescriptioncharacters"] = { first = 0x02FF0, last = 0x02FFF, description = "Ideographic Description Characters" },
["imperialaramaic"] = { first = 0x10840, last = 0x1085F, description = "Imperial Aramaic" },
["inscriptionalpahlavi"] = { first = 0x10B60, last = 0x10B7F, description = "Inscriptional Pahlavi" },
["inscriptionalparthian"] = { first = 0x10B40, last = 0x10B5F, description = "Inscriptional Parthian" },
["ipaextensions"] = { first = 0x00250, last = 0x002AF, description = "IPA Extensions" },
["javanese"] = { first = 0x0A980, last = 0x0A9DF, description = "Javanese" },
["kaithi"] = { first = 0x11080, last = 0x110CF, description = "Kaithi" },
["kanasupplement"] = { first = 0x1B000, last = 0x1B0FF, description = "Kana Supplement" },
["kanbun"] = { first = 0x03190, last = 0x0319F, description = "Kanbun" },
["kangxiradicals"] = { first = 0x02F00, last = 0x02FDF, description = "Kangxi Radicals" },
["kannada"] = { first = 0x00C80, last = 0x00CFF, otf="knda", description = "Kannada" },
["katakana"] = { first = 0x030A0, last = 0x030FF, otf="kana", description = "Katakana" },
["katakanaphoneticextensions"] = { first = 0x031F0, last = 0x031FF, otf="kana", description = "Katakana Phonetic Extensions" },
["kayahli"] = { first = 0x0A900, last = 0x0A92F, description = "Kayah Li" },
["kharoshthi"] = { first = 0x10A00, last = 0x10A5F, otf="khar", description = "Kharoshthi" },
["khmer"] = { first = 0x01780, last = 0x017FF, otf="khmr", description = "Khmer" },
["khmersymbols"] = { first = 0x019E0, last = 0x019FF, otf="khmr", description = "Khmer Symbols" },
["khojki"] = { first = 0x11200, last = 0x1124F, description = "Khojki" },
["khudawadi"] = { first = 0x112B0, last = 0x112FF, description = "Khudawadi" },
["lao"] = { first = 0x00E80, last = 0x00EFF, otf="lao", description = "Lao" },
["latinextendeda"] = { first = 0x00100, last = 0x0017F, otf="latn", description = "Latin Extended-A" },
["latinextendedadditional"] = { first = 0x01E00, last = 0x01EFF, otf="latn", description = "Latin Extended Additional" },
["latinextendedb"] = { first = 0x00180, last = 0x0024F, otf="latn", description = "Latin Extended-B" },
["latinextendedc"] = { first = 0x02C60, last = 0x02C7F, otf="latn", description = "Latin Extended-C" },
["latinextendedd"] = { first = 0x0A720, last = 0x0A7FF, otf="latn", description = "Latin Extended-D" },
["latinextendede"] = { first = 0x0AB30, last = 0x0AB6F, description = "Latin Extended-E" },
["latinsupplement"] = { first = 0x00080, last = 0x000FF, otf="latn", description = "Latin-1 Supplement" },
["lepcha"] = { first = 0x01C00, last = 0x01C4F, description = "Lepcha" },
["letterlikesymbols"] = { first = 0x02100, last = 0x0214F, math = true, description = "Letterlike Symbols" },
["limbu"] = { first = 0x01900, last = 0x0194F, otf="limb", description = "Limbu" },
["lineara"] = { first = 0x10600, last = 0x1077F, description = "Linear A" },
["linearbideograms"] = { first = 0x10080, last = 0x100FF, otf="linb", description = "Linear B Ideograms" },
["linearbsyllabary"] = { first = 0x10000, last = 0x1007F, otf="linb", description = "Linear B Syllabary" },
["lisu"] = { first = 0x0A4D0, last = 0x0A4FF, description = "Lisu" },
["lowercasebold"] = { first = 0x1D41A, last = 0x1D433, math = true },
["lowercaseboldfraktur"] = { first = 0x1D586, last = 0x1D59F, math = true },
["lowercasebolditalic"] = { first = 0x1D482, last = 0x1D49B, math = true },
["lowercaseboldscript"] = { first = 0x1D4EA, last = 0x1D503, math = true },
["lowercasedoublestruck"] = { first = 0x1D552, last = 0x1D56B, math = true },
["lowercasefraktur"] = { first = 0x1D51E, last = 0x1D537, math = true },
["lowercasegreekbold"] = { first = 0x1D6C2, last = 0x1D6DB, math = true },
["lowercasegreekbolditalic"] = { first = 0x1D736, last = 0x1D74F, math = true },
["lowercasegreekitalic"] = { first = 0x1D6FC, last = 0x1D715, math = true },
["lowercasegreeknormal"] = { first = 0x003B1, last = 0x003CA, math = true },
["lowercasegreeksansserifbold"] = { first = 0x1D770, last = 0x1D789, math = true },
["lowercasegreeksansserifbolditalic"] = { first = 0x1D7AA, last = 0x1D7C3, math = true },
["lowercaseitalic"] = { first = 0x1D44E, last = 0x1D467, math = true },
["lowercasemonospace"] = { first = 0x1D68A, last = 0x1D6A3, math = true },
["lowercasenormal"] = { first = 0x00061, last = 0x0007A, math = true },
["lowercasesansserifbold"] = { first = 0x1D5EE, last = 0x1D607, math = true },
["lowercasesansserifbolditalic"] = { first = 0x1D656, last = 0x1D66F, math = true },
["lowercasesansserifitalic"] = { first = 0x1D622, last = 0x1D63B, math = true },
["lowercasesansserifnormal"] = { first = 0x1D5BA, last = 0x1D5D3, math = true },
["lowercasescript"] = { first = 0x1D4B6, last = 0x1D4CF, math = true },
["lowsurrogates"] = { first = 0x0DC00, last = 0x0DFFF, description = "Low Surrogates" },
["lycian"] = { first = 0x10280, last = 0x1029F, description = "Lycian" },
["lydian"] = { first = 0x10920, last = 0x1093F, description = "Lydian" },
["mahajani"] = { first = 0x11150, last = 0x1117F, description = "Mahajani" },
["mahjongtiles"] = { first = 0x1F000, last = 0x1F02F, description = "Mahjong Tiles" },
["malayalam"] = { first = 0x00D00, last = 0x00D7F, otf="mlym", description = "Malayalam" },
["mandaic"] = { first = 0x00840, last = 0x0085F, otf="mand", description = "Mandaic" },
["manichaean"] = { first = 0x10AC0, last = 0x10AFF, description = "Manichaean" },
["mathematicalalphanumericsymbols"] = { first = 0x1D400, last = 0x1D7FF, math = true, description = "Mathematical Alphanumeric Symbols" },
["mathematicaloperators"] = { first = 0x02200, last = 0x022FF, math = true, description = "Mathematical Operators" },
["meeteimayek"] = { first = 0x0ABC0, last = 0x0ABFF, description = "Meetei Mayek" },
["meeteimayekextensions"] = { first = 0x0AAE0, last = 0x0AAFF, description = "Meetei Mayek Extensions" },
["mendekikakui"] = { first = 0x1E800, last = 0x1E8DF, description = "Mende Kikakui" },
["meroiticcursive"] = { first = 0x109A0, last = 0x109FF, description = "Meroitic Cursive" },
["meroitichieroglyphs"] = { first = 0x10980, last = 0x1099F, description = "Meroitic Hieroglyphs" },
["miao"] = { first = 0x16F00, last = 0x16F9F, description = "Miao" },
["miscellaneousmathematicalsymbolsa"] = { first = 0x027C0, last = 0x027EF, math = true, description = "Miscellaneous Mathematical Symbols-A" },
["miscellaneousmathematicalsymbolsb"] = { first = 0x02980, last = 0x029FF, math = true, description = "Miscellaneous Mathematical Symbols-B" },
["miscellaneoussymbols"] = { first = 0x02600, last = 0x026FF, math = true, description = "Miscellaneous Symbols" },
["miscellaneoussymbolsandarrows"] = { first = 0x02B00, last = 0x02BFF, math = true, description = "Miscellaneous Symbols and Arrows" },
["miscellaneoussymbolsandpictographs"] = { first = 0x1F300, last = 0x1F5FF, description = "Miscellaneous Symbols and Pictographs" },
["miscellaneoustechnical"] = { first = 0x02300, last = 0x023FF, math = true, description = "Miscellaneous Technical" },
["modi"] = { first = 0x11600, last = 0x1165F, description = "Modi" },
["modifiertoneletters"] = { first = 0x0A700, last = 0x0A71F, description = "Modifier Tone Letters" },
["mongolian"] = { first = 0x01800, last = 0x018AF, otf="mong", description = "Mongolian" },
["mro"] = { first = 0x16A40, last = 0x16A6F, description = "Mro" },
["multani"] = { first = 0x11280, last = 0x112AF, description = "Multani" },
["musicalsymbols"] = { first = 0x1D100, last = 0x1D1FF, otf="musc", description = "Musical Symbols" },
["myanmar"] = { first = 0x01000, last = 0x0109F, otf="mymr", description = "Myanmar" },
["myanmarextendeda"] = { first = 0x0AA60, last = 0x0AA7F, description = "Myanmar Extended-A" },
["myanmarextendedb"] = { first = 0x0A9E0, last = 0x0A9FF, description = "Myanmar Extended-B" },
["nabataean"] = { first = 0x10880, last = 0x108AF, description = "Nabataean" },
["newtailue"] = { first = 0x01980, last = 0x019DF, description = "New Tai Lue" },
["nko"] = { first = 0x007C0, last = 0x007FF, otf="nko", description = "NKo" },
["numberforms"] = { first = 0x02150, last = 0x0218F, description = "Number Forms" },
["ogham"] = { first = 0x01680, last = 0x0169F, otf="ogam", description = "Ogham" },
["olchiki"] = { first = 0x01C50, last = 0x01C7F, description = "Ol Chiki" },
["oldhungarian"] = { first = 0x10C80, last = 0x10CFF, description = "Old Hungarian" },
["olditalic"] = { first = 0x10300, last = 0x1032F, otf="ital", description = "Old Italic" },
["oldnortharabian"] = { first = 0x10A80, last = 0x10A9F, description = "Old North Arabian" },
["oldpermic"] = { first = 0x10350, last = 0x1037F, description = "Old Permic" },
["oldpersian"] = { first = 0x103A0, last = 0x103DF, otf="xpeo", description = "Old Persian" },
["oldsoutharabian"] = { first = 0x10A60, last = 0x10A7F, description = "Old South Arabian" },
["oldturkic"] = { first = 0x10C00, last = 0x10C4F, description = "Old Turkic" },
["opticalcharacterrecognition"] = { first = 0x02440, last = 0x0245F, description = "Optical Character Recognition" },
["oriya"] = { first = 0x00B00, last = 0x00B7F, otf="orya", description = "Oriya" },
["ornamentaldingbats"] = { first = 0x1F650, last = 0x1F67F, description = "Ornamental Dingbats" },
["osmanya"] = { first = 0x10480, last = 0x104AF, otf="osma", description = "Osmanya" },
["pahawhhmong"] = { first = 0x16B00, last = 0x16B8F, description = "Pahawh Hmong" },
["palmyrene"] = { first = 0x10860, last = 0x1087F, description = "Palmyrene" },
["paucinhau"] = { first = 0x11AC0, last = 0x11AFF, description = "Pau Cin Hau" },
["phagspa"] = { first = 0x0A840, last = 0x0A87F, otf="phag", description = "Phags-pa" },
["phaistosdisc"] = { first = 0x101D0, last = 0x101FF, description = "Phaistos Disc" },
["phoenician"] = { first = 0x10900, last = 0x1091F, otf="phnx", description = "Phoenician" },
["phoneticextensions"] = { first = 0x01D00, last = 0x01D7F, description = "Phonetic Extensions" },
["phoneticextensionssupplement"] = { first = 0x01D80, last = 0x01DBF, description = "Phonetic Extensions Supplement" },
["playingcards"] = { first = 0x1F0A0, last = 0x1F0FF, description = "Playing Cards" },
["privateusearea"] = { first = 0x0E000, last = 0x0F8FF, description = "Private Use Area" },
["psalterpahlavi"] = { first = 0x10B80, last = 0x10BAF, description = "Psalter Pahlavi" },
["rejang"] = { first = 0x0A930, last = 0x0A95F, description = "Rejang" },
["ruminumeralsymbols"] = { first = 0x10E60, last = 0x10E7F, description = "Rumi Numeral Symbols" },
["runic"] = { first = 0x016A0, last = 0x016FF, otf="runr", description = "Runic" },
["samaritan"] = { first = 0x00800, last = 0x0083F, description = "Samaritan" },
["saurashtra"] = { first = 0x0A880, last = 0x0A8DF, description = "Saurashtra" },
["sharada"] = { first = 0x11180, last = 0x111DF, description = "Sharada" },
["shavian"] = { first = 0x10450, last = 0x1047F, otf="shaw", description = "Shavian" },
["shorthandformatcontrols"] = { first = 0x1BCA0, last = 0x1BCAF, description = "Shorthand Format Controls" },
["siddham"] = { first = 0x11580, last = 0x115FF, description = "Siddham" },
["sinhala"] = { first = 0x00D80, last = 0x00DFF, otf="sinh", description = "Sinhala" },
["sinhalaarchaicnumbers"] = { first = 0x111E0, last = 0x111FF, description = "Sinhala Archaic Numbers" },
["smallformvariants"] = { first = 0x0FE50, last = 0x0FE6F, description = "Small Form Variants" },
["sorasompeng"] = { first = 0x110D0, last = 0x110FF, description = "Sora Sompeng" },
["spacingmodifierletters"] = { first = 0x002B0, last = 0x002FF, description = "Spacing Modifier Letters" },
["specials"] = { first = 0x0FFF0, last = 0x0FFFF, description = "Specials" },
["sundanese"] = { first = 0x01B80, last = 0x01BBF, description = "Sundanese" },
["sundanesesupplement"] = { first = 0x01CC0, last = 0x01CCF, description = "Sundanese Supplement" },
["superscriptsandsubscripts"] = { first = 0x02070, last = 0x0209F, description = "Superscripts and Subscripts" },
["supplementalarrowsa"] = { first = 0x027F0, last = 0x027FF, math = true, description = "Supplemental Arrows-A" },
["supplementalarrowsb"] = { first = 0x02900, last = 0x0297F, math = true, description = "Supplemental Arrows-B" },
["supplementalarrowsc"] = { first = 0x1F800, last = 0x1F8FF, math = true, description = "Supplemental Arrows-C" },
["supplementalmathematicaloperators"] = { first = 0x02A00, last = 0x02AFF, math = true, description = "Supplemental Mathematical Operators" },
["supplementalpunctuation"] = { first = 0x02E00, last = 0x02E7F, description = "Supplemental Punctuation" },
["supplementalsymbolsandpictographs"] = { first = 0x1F900, last = 0x1F9FF, description = "Supplemental Symbols and Pictographs" },
["supplementaryprivateuseareaa"] = { first = 0xF0000, last = 0xFFFFF, description = "Supplementary Private Use Area-A" },
["supplementaryprivateuseareab"] = { first = 0x100000,last = 0x10FFFF, description = "Supplementary Private Use Area-B" },
["suttonsignwriting"] = { first = 0x1D800, last = 0x1DAAF, description = "Sutton SignWriting" },
["sylotinagri"] = { first = 0x0A800, last = 0x0A82F, otf="sylo", description = "Syloti Nagri" },
["syriac"] = { first = 0x00700, last = 0x0074F, otf="syrc", description = "Syriac" },
["tagalog"] = { first = 0x01700, last = 0x0171F, otf="tglg", description = "Tagalog" },
["tagbanwa"] = { first = 0x01760, last = 0x0177F, otf="tagb", description = "Tagbanwa" },
["tags"] = { first = 0xE0000, last = 0xE007F, description = "Tags" },
["taile"] = { first = 0x01950, last = 0x0197F, otf="tale", description = "Tai Le" },
["taitham"] = { first = 0x01A20, last = 0x01AAF, description = "Tai Tham" },
["taiviet"] = { first = 0x0AA80, last = 0x0AADF, description = "Tai Viet" },
["taixuanjingsymbols"] = { first = 0x1D300, last = 0x1D35F, description = "Tai Xuan Jing Symbols" },
["takri"] = { first = 0x11680, last = 0x116CF, description = "Takri" },
["tamil"] = { first = 0x00B80, last = 0x00BFF, otf="taml", description = "Tamil" },
["telugu"] = { first = 0x00C00, last = 0x00C7F, otf="telu", description = "Telugu" },
["thaana"] = { first = 0x00780, last = 0x007BF, otf="thaa", description = "Thaana" },
["thai"] = { first = 0x00E00, last = 0x00E7F, otf="thai", description = "Thai" },
["tibetan"] = { first = 0x00F00, last = 0x00FFF, otf="tibt", description = "Tibetan" },
["tifinagh"] = { first = 0x02D30, last = 0x02D7F, otf="tfng", description = "Tifinagh" },
["tirhuta"] = { first = 0x11480, last = 0x114DF, description = "Tirhuta" },
["transportandmapsymbols"] = { first = 0x1F680, last = 0x1F6FF, description = "Transport and Map Symbols" },
["ugaritic"] = { first = 0x10380, last = 0x1039F, otf="ugar", description = "Ugaritic" },
["unifiedcanadianaboriginalsyllabics"] = { first = 0x01400, last = 0x0167F, otf="cans", description = "Unified Canadian Aboriginal Syllabics" },
["unifiedcanadianaboriginalsyllabicsextended"] = { first = 0x018B0, last = 0x018FF, description = "Unified Canadian Aboriginal Syllabics Extended" },
["uppercasebold"] = { first = 0x1D400, last = 0x1D419, math = true },
["uppercaseboldfraktur"] = { first = 0x1D56C, last = 0x1D585, math = true },
["uppercasebolditalic"] = { first = 0x1D468, last = 0x1D481, math = true },
["uppercaseboldscript"] = { first = 0x1D4D0, last = 0x1D4E9, math = true },
["uppercasedoublestruck"] = { first = 0x1D538, last = 0x1D551, math = true },
["uppercasefraktur"] = { first = 0x1D504, last = 0x1D51D, math = true },
["uppercasegreekbold"] = { first = 0x1D6A8, last = 0x1D6C1, math = true },
["uppercasegreekbolditalic"] = { first = 0x1D71C, last = 0x1D735, math = true },
["uppercasegreekitalic"] = { first = 0x1D6E2, last = 0x1D6FB, math = true },
["uppercasegreeknormal"] = { first = 0x00391, last = 0x003AA, math = true },
["uppercasegreeksansserifbold"] = { first = 0x1D756, last = 0x1D76F, math = true },
["uppercasegreeksansserifbolditalic"] = { first = 0x1D790, last = 0x1D7A9, math = true },
["uppercaseitalic"] = { first = 0x1D434, last = 0x1D44D, math = true },
["uppercasemonospace"] = { first = 0x1D670, last = 0x1D689, math = true },
["uppercasenormal"] = { first = 0x00041, last = 0x0005A, math = true },
["uppercasesansserifbold"] = { first = 0x1D5D4, last = 0x1D5ED, math = true },
["uppercasesansserifbolditalic"] = { first = 0x1D63C, last = 0x1D655, math = true },
["uppercasesansserifitalic"] = { first = 0x1D608, last = 0x1D621, math = true },
["uppercasesansserifnormal"] = { first = 0x1D5A0, last = 0x1D5B9, math = true },
["uppercasescript"] = { first = 0x1D49C, last = 0x1D4B5, math = true },
["vai"] = { first = 0x0A500, last = 0x0A63F, description = "Vai" },
["variationselectors"] = { first = 0x0FE00, last = 0x0FE0F, description = "Variation Selectors" },
["variationselectorssupplement"] = { first = 0xE0100, last = 0xE01EF, description = "Variation Selectors Supplement" },
["vedicextensions"] = { first = 0x01CD0, last = 0x01CFF, description = "Vedic Extensions" },
["verticalforms"] = { first = 0x0FE10, last = 0x0FE1F, description = "Vertical Forms" },
["warangciti"] = { first = 0x118A0, last = 0x118FF, description = "Warang Citi" },
["yijinghexagramsymbols"] = { first = 0x04DC0, last = 0x04DFF, otf="yi", description = "Yijing Hexagram Symbols" },
["yiradicals"] = { first = 0x0A490, last = 0x0A4CF, otf="yi", description = "Yi Radicals" },
["yisyllables"] = { first = 0x0A000, last = 0x0A48F, otf="yi", description = "Yi Syllables" },
}
characters.blocks = blocks
function characters.blockrange(name)
local b = blocks[name]
if b then
return b.first, b.last
else
return 0, 0
end
end
setmetatableindex(blocks, function(t,k) -- we could use an intermediate table if called often
return k and rawget(t,lower(gsub(k,"[^a-zA-Z]","")))
end)
local otfscripts = utilities.storage.allocate()
characters.otfscripts = otfscripts
setmetatableindex(otfscripts,function(t,unicode)
for k, v in next, blocks do
local first, last = v.first, v.last
if unicode >= first and unicode <= last then
local script = v.otf or "dflt"
for u=first,last do
t[u] = script
end
return script
end
end
-- pretty slow when we're here
t[unicode] = "dflt"
return "dflt"
end)
local splitter = lpeg.splitat(S(":-"))
function characters.getrange(name) -- used in font fallback definitions (name or range)
local range = blocks[name]
if range then
return range.first, range.last, range.description, range.gaps
end
name = gsub(name,'"',"0x") -- goodie: tex hex notation
local start, stop = lpegmatch(splitter,name)
if start and stop then
start, stop = tonumber(start,16) or tonumber(start), tonumber(stop,16) or tonumber(stop)
if start and stop then
return start, stop, nil
end
end
local slot = tonumber(name,16) or tonumber(name)
return slot, slot, nil
end
local categorytags = allocate {
lu = "Letter Uppercase",
ll = "Letter Lowercase",
lt = "Letter Titlecase",
lm = "Letter Modifier",
lo = "Letter Other",
mn = "Mark Nonspacing",
mc = "Mark Spacing Combining",
me = "Mark Enclosing",
nd = "Number Decimal Digit",
nl = "Number Letter",
no = "Number Other",
pc = "Punctuation Connector",
pd = "Punctuation Dash",
ps = "Punctuation Open",
pe = "Punctuation Close",
pi = "Punctuation Initial Quote",
pf = "Punctuation Final Quote",
po = "Punctuation Other",
sm = "Symbol Math",
sc = "Symbol Currency",
sk = "Symbol Modifier",
so = "Symbol Other",
zs = "Separator Space",
zl = "Separator Line",
zp = "Separator Paragraph",
cc = "Other Control",
cf = "Other Format",
cs = "Other Surrogate",
co = "Other Private Use",
cn = "Other Not Assigned",
}
local detailtags = allocate {
sl = "small letter",
bl = "big letter",
im = "iteration mark",
pm = "prolonged sound mark"
}
characters.categorytags = categorytags
characters.detailtags = detailtags
-- sounds : voiced unvoiced semivoiced
--~ special : cf (softhyphen) zs (emspace)
--~ characters: ll lm lo lt lu mn nl no pc pd pe pf pi po ps sc sk sm so
local is_character = allocate ( tohash {
"lu","ll","lt","lm","lo",
"nd","nl","no",
"mn",
"nl","no",
"pc","pd","ps","pe","pi","pf","po",
"sm","sc","sk","so"
} )
local is_letter = allocate ( tohash {
"ll","lm","lo","lt","lu"
} )
local is_command = allocate ( tohash {
"cf","zs"
} )
local is_spacing = allocate ( tohash {
"zs", "zl","zp",
} )
local is_mark = allocate ( tohash {
"mn", "ms",
} )
local is_punctuation = allocate ( tohash {
"pc","pd","ps","pe","pi","pf","po",
} )
-- to be redone: store checked characters
characters.is_character = is_character
characters.is_letter = is_letter
characters.is_command = is_command
characters.is_spacing = is_spacing
characters.is_mark = is_mark
characters.is_punctuation = is_punctuation
local mti = function(t,k)
if type(k) == "number" then
local c = data[k].category
return c and rawget(t,c)
else
-- avoid auto conversion in data.characters lookups
end
end
setmetatableindex(characters.is_character, mti)
setmetatableindex(characters.is_letter, mti)
setmetatableindex(characters.is_command, mti)
setmetatableindex(characters.is_spacing, mti)
setmetatableindex(characters.is_punctuation,mti)
-- todo: also define callers for the above
-- linebreak: todo: hash
--
-- normative : BK CR LF CM SG GL CB SP ZW NL WJ JL JV JT H2 H3
-- informative : XX OP CL CP QU NS EX SY IS PR PO NU AL ID IN HY BB BA SA AI B2 HL CJ RI
--
-- comments taken from standard:
characters.linebreaks = {
-- non-tailorable line breaking classes
["bk"] = "mandatory break", -- nl, ps : cause a line break (after)
["cr"] = "carriage return", -- cr : cause a line break (after), except between cr and lf
["lf"] = "line feed", -- lf : cause a line break (after)
["cm"] = "combining mark", -- combining marks, control codes : prohibit a line break between the character and the preceding character
["nl"] = "next line", -- nel : cause a line break (after)
["sg"] = "surrogate", -- surrogates :do not occur in well-formed text
["wj"] = "word joiner", -- wj : prohibit line breaks before and after
["zw"] = "zero width space", -- zwsp : provide a break opportunity
["gl"] = "non-breaking (glue)", -- cgj, nbsp, zwnbsp : prohibit line breaks before and after
["sp"] = "space", -- space : enable indirect line breaks
-- break opportunities
["b2"] = "break opportunity before and after", -- em dash : provide a line break opportunity before and after the character
["ba"] = "break after", -- spaces, hyphens : generally provide a line break opportunity after the character
["bb"] = "break before", -- punctuation used in dictionaries : generally provide a line break opportunity before the character
["hy"] = "hyphen", -- hyphen-minus : provide a line break opportunity after the character, except in numeric context
["cb"] = "contingent break opportunity", -- inline objects : provide a line break opportunity contingent on additional information
-- characters prohibiting certain breaks
["cl"] = "close punctuation", -- “}”, “❳”, “⟫” etc. : prohibit line breaks before
["cp"] = "close parenthesis", -- “)”, “]” : prohibit line breaks before
["ex"] = "exclamation/interrogation", -- “!”, “?”, etc. : prohibit line breaks before
["in"] = "inseparable", -- leaders : allow only indirect line breaks between pairs
["ns"] = "nonstarter", -- “‼”, “‽”, “⁇”, “⁉”, etc. : allow only indirect line breaks before
["op"] = "open punctuation", -- “(“, “[“, “{“, etc. : prohibit line breaks after
["qu"] = "quotation", -- quotation marks : act like they are both opening and closing
-- numeric context
["is"] = "infix numeric separator", -- . , : prevent breaks after any and before numeric
["nu"] = "numeric", -- digits : form numeric expressions for line breaking purposes
["po"] = "postfix numeric", -- %, ¢ : do not break following a numeric expression
["pr"] = "prefix numeric", -- $, £, ¥, etc. : do not break in front of a numeric expression
["sy"] = "symbols allowing break after", -- / : prevent a break before, and allow a break after
-- other characters
["ai"] = "ambiguous (alphabetic or ideographic)", -- characters with ambiguous east asian width : act like al when the resolved eaw is n; otherwise, act as id
["al"] = "alphabetic", -- alphabets and regular symbols : are alphabetic characters or symbols that are used with alphabetic characters
["cj"] = "conditional japanese starter", -- small kana : treat as ns or id for strict or normal breaking.
["h2"] = "hangul lv syllable", -- hangul : form korean syllable blocks
["h3"] = "hangul lvt syllable", -- hangul : form korean syllable blocks
["hl"] = "hebrew letter", -- hebrew : do not break around a following hyphen; otherwise act as alphabetic
["id"] = "ideographic", -- ideographs : break before or after, except in some numeric context
["jl"] = "hangul l jamo", -- conjoining jamo : form korean syllable blocks
["jv"] = "hangul v jamo", -- conjoining jamo : form korean syllable blocks
["jt"] = "hangul t jamo", -- conjoining jamo : form korean syllable blocks
["ri"] = "regional indicator", -- regional indicator symbol letter a .. z : keep together, break before and after from others
["sa"] = "complex context dependent (south east asian)", -- south east asian: thai, lao, khmer : provide a line break opportunity contingent on additional, language-specific context analysis
["xx"] = "unknown", -- most unassigned, private-use : have as yet unknown line breaking behavior or unassigned code positions
}
-- east asian width:
--
-- N A H W F Na
characters.bidi = allocate {
l = "Left-to-Right",
lre = "Left-to-Right Embedding",
lro = "Left-to-Right Override",
r = "Right-to-Left",
al = "Right-to-Left Arabic",
rle = "Right-to-Left Embedding",
rlo = "Right-to-Left Override",
pdf = "Pop Directional Format",
en = "European Number",
es = "European Number Separator",
et = "European Number Terminator",
an = "Arabic Number",
cs = "Common Number Separator",
nsm = "Non-Spacing Mark",
bn = "Boundary Neutral",
b = "Paragraph Separator",
s = "Segment Separator",
ws = "Whitespace",
on = "Other Neutrals",
}
--[[ldx--
<p>At this point we assume that the big data table is loaded. From this
table we derive a few more.</p>
--ldx]]--
if not characters.fallbacks then
characters.fallbacks = {
[0x0308] = 0x00A8, [0x00A8] = 0x0308, -- dieresiscmb dieresis
[0x0304] = 0x00AF, [0x00AF] = 0x0304, -- macroncmb macron
[0x0301] = 0x00B4, [0x00B4] = 0x0301, -- acutecomb acute
[0x0327] = 0x00B8, [0x00B8] = 0x0327, -- cedillacmb cedilla
[0x0302] = 0x02C6, [0x02C6] = 0x0302, -- circumflexcmb circumflex
[0x030C] = 0x02C7, [0x02C7] = 0x030C, -- caroncmb caron
[0x0306] = 0x02D8, [0x02D8] = 0x0306, -- brevecmb breve
[0x0307] = 0x02D9, [0x02D9] = 0x0307, -- dotaccentcmb dotaccent
[0x030A] = 0x02DA, [0x02DA] = 0x030A, -- ringcmb ring
[0x0328] = 0x02DB, [0x02DB] = 0x0328, -- ogonekcmb ogonek
[0x0303] = 0x02DC, [0x02DC] = 0x0303, -- tildecomb tilde
[0x030B] = 0x02DD, [0x02DD] = 0x030B, -- hungarumlautcmb hungarumlaut
[0x0305] = 0x203E, [0x203E] = 0x0305, -- overlinecmb overline
[0x0300] = 0x0060, [0x0060] = 0x0333, -- gravecomb grave
}
-- not done (would mess up mapping):
--
-- 0X0301/0X0384 0X0314/0X1FFE 0X0313/0X1FBD 0X0313/0X1FBF 0X0342/0X1FC0
-- 0X3099/0X309B 0X309A/0X309C 0X0333/0X2017 0X0345/0X037A
end
if storage then
storage.register("characters/fallbacks", characters.fallbacks, "characters.fallbacks") -- accents and such
end
characters.directions = { }
setmetatableindex(characters.directions,function(t,k)
local d = data[k]
if d then
local v = d.direction
if v then
t[k] = v
return v
end
end
t[k] = false -- maybe 'l'
return v
end)
characters.mirrors = { }
setmetatableindex(characters.mirrors,function(t,k)
local d = data[k]
if d then
local v = d.mirror
if v then
t[k] = v
return v
end
end
t[k] = false
return v
end)
characters.textclasses = { }
setmetatableindex(characters.textclasses,function(t,k)
local d = data[k]
if d then
local v = d.textclass
if v then
t[k] = v
return v
end
end
t[k] = false
return v
end)
--[[ldx--
<p>Next comes a whole series of helper methods. These are (will be) part
of the official <l n='api'/>.</p>
--ldx]]--
-- we could make them virtual: characters.contextnames[n]
function characters.contextname(n) return data[n] and data[n].contextname or "" end
function characters.adobename (n) return data[n] and data[n].adobename or "" end
function characters.description(n) return data[n] and data[n].description or "" end
-------- characters.category (n) return data[n] and data[n].category or "" end
function characters.category(n,verbose)
local c = data[n].category
if not c then
return ""
elseif verbose then
return categorytags[c]
else
return c
end
end
-- -- some day we will make a table .. not that many calls to utfchar
--
-- local utfchar = utf.char
-- local utfbyte = utf.byte
-- local utfbytes = { }
-- local utfchars = { }
--
-- table.setmetatableindex(utfbytes,function(t,k) local v = utfchar(k) t[k] = v return v end)
-- table.setmetatableindex(utfchars,function(t,k) local v = utfbyte(k) t[k] = v return v end)
local function toutfstring(s)
if type(s) == "table" then
return utfchar(unpack(s)) -- concat { utfchar( unpack(s) ) }
else
return utfchar(s)
end
end
utf.tostring = toutfstring
local categories = allocate() characters.categories = categories -- lazy table
setmetatableindex(categories, function(t,u) if u then local c = data[u] c = c and c.category or u t[u] = c return c end end)
-- todo: overloads (these register directly in the tables as number and string) e.g. for greek
-- todo: for string do a numeric lookup in the table itself
local lccodes = allocate() characters.lccodes = lccodes -- lazy table
local uccodes = allocate() characters.uccodes = uccodes -- lazy table
local shcodes = allocate() characters.shcodes = shcodes -- lazy table
local fscodes = allocate() characters.fscodes = fscodes -- lazy table
setmetatableindex(lccodes, function(t,u) if u then local c = data[u] c = c and c.lccode or (type(u) == "string" and utfbyte(u)) or u t[u] = c return c end end)
setmetatableindex(uccodes, function(t,u) if u then local c = data[u] c = c and c.uccode or (type(u) == "string" and utfbyte(u)) or u t[u] = c return c end end)
setmetatableindex(shcodes, function(t,u) if u then local c = data[u] c = c and c.shcode or (type(u) == "string" and utfbyte(u)) or u t[u] = c return c end end)
setmetatableindex(fscodes, function(t,u) if u then local c = data[u] c = c and c.fscode or (type(u) == "string" and utfbyte(u)) or u t[u] = c return c end end)
local lcchars = allocate() characters.lcchars = lcchars -- lazy table
local ucchars = allocate() characters.ucchars = ucchars -- lazy table
local shchars = allocate() characters.shchars = shchars -- lazy table
local fschars = allocate() characters.fschars = fschars -- lazy table
setmetatableindex(lcchars, function(t,u) if u then local c = data[u] c = c and c.lccode c = c and toutfstring(c) or (type(u) == "number" and utfchar(u)) or u t[u] = c return c end end)
setmetatableindex(ucchars, function(t,u) if u then local c = data[u] c = c and c.uccode c = c and toutfstring(c) or (type(u) == "number" and utfchar(u)) or u t[u] = c return c end end)
setmetatableindex(shchars, function(t,u) if u then local c = data[u] c = c and c.shcode c = c and toutfstring(c) or (type(u) == "number" and utfchar(u)) or u t[u] = c return c end end)
setmetatableindex(fschars, function(t,u) if u then local c = data[u] c = c and c.fscode c = c and toutfstring(c) or (type(u) == "number" and utfchar(u)) or u t[u] = c return c end end)
local decomposed = allocate() characters.decomposed = decomposed -- lazy table
local specials = allocate() characters.specials = specials -- lazy table
setmetatableindex(decomposed, function(t,u) -- either a table or false
if u then
local c = data[u]
local s = c and c.decomposed or false -- could fall back to specials
t[u] = s
return s
end
end)
setmetatableindex(specials, function(t,u) -- either a table or false
if u then
local c = data[u]
local s = c and c.specials or false
t[u] = s
return s
end
end)
local specialchars = allocate() characters.specialchars = specialchars -- lazy table
local descriptions = allocate() characters.descriptions = descriptions -- lazy table
setmetatableindex(specialchars, function(t,u)
if u then
local c = data[u]
local s = c and c.specials
if s then
local tt, ttn = { }, 0
for i=2,#s do
local si = s[i]
local c = data[si]
if is_letter[c.category] then
ttn = ttn + 1
tt[ttn] = utfchar(si)
end
end
c = concat(tt)
t[u] = c
return c
else
if type(u) == "number" then
u = utfchar(u)
end
t[u] = u
return u
end
end
end)
setmetatableindex(descriptions, function(t,k)
-- 0.05 - 0.10 sec
for u, c in next, data do
local d = c.description
if d then
d = gsub(d," ","")
d = lower(d)
t[d] = u
end
end
local d = rawget(t,k)
if not d then
t[k] = k
end
return d
end)
function characters.unicodechar(asked)
local n = tonumber(asked)
if n then
return n
elseif type(asked) == "string" then
return descriptions[asked] or descriptions[gsub(asked," ","")]
end
end
-- function characters.lower(str)
-- local new, n = { }, 0
-- for u in utfvalues(str) do
-- n = n + 1
-- new[n] = lcchars[u]
-- end
-- return concat(new)
-- end
--
-- function characters.upper(str)
-- local new, n = { }, 0
-- for u in utfvalues(str) do
-- n = n + 1
-- new[n] = ucchars[u]
-- end
-- return concat(new)
-- end
--
-- function characters.shaped(str)
-- local new, n = { }, 0
-- for u in utfvalues(str) do
-- n = n + 1
-- new[n] = shchars[u]
-- end
-- return concat(new)
-- end
----- tolower = Cs((utf8byte/lcchars)^0)
----- toupper = Cs((utf8byte/ucchars)^0)
----- toshape = Cs((utf8byte/shchars)^0)
local tolower = Cs((utf8character/lcchars)^0) -- no need to check spacing
local toupper = Cs((utf8character/ucchars)^0) -- no need to check spacing
local toshape = Cs((utf8character/shchars)^0) -- no need to check spacing
lpegpatterns.tolower = tolower -- old ones ... will be overloaded
lpegpatterns.toupper = toupper -- old ones ... will be overloaded
lpegpatterns.toshape = toshape -- old ones ... will be overloaded
-- function characters.lower (str) return lpegmatch(tolower,str) end
-- function characters.upper (str) return lpegmatch(toupper,str) end
-- function characters.shaped(str) return lpegmatch(toshape,str) end
-- local superscripts = allocate() characters.superscripts = superscripts
-- local subscripts = allocate() characters.subscripts = subscripts
-- if storage then
-- storage.register("characters/superscripts", superscripts, "characters.superscripts")
-- storage.register("characters/subscripts", subscripts, "characters.subscripts")
-- end
-- end
if not characters.splits then
local char = allocate()
local compat = allocate()
local splits = {
char = char,
compat = compat,
}
characters.splits = splits
-- [0x013F] = { 0x004C, 0x00B7 }
-- [0x0140] = { 0x006C, 0x00B7 }
for unicode, data in next, characters.data do
local specials = data.specials
if specials and #specials > 2 then
local kind = specials[1]
if kind == "compat" then
compat[unicode] = { unpack(specials,2) }
elseif kind == "char" then
char [unicode] = { unpack(specials,2) }
end
end
end
if storage then
storage.register("characters/splits", splits, "characters.splits")
end
end
if not characters.lhash then
local lhash = allocate() characters.lhash = lhash -- nil if no conversion
local uhash = allocate() characters.uhash = uhash -- nil if no conversion
local shash = allocate() characters.shash = shash -- nil if no conversion
for k, v in next, characters.data do
-- if k < 0x11000 then
local l = v.lccode
if l then
-- we have an uppercase
if type(l) == "number" then
lhash[utfchar(k)] = utfchar(l)
elseif #l == 2 then
lhash[utfchar(k)] = utfchar(l[1]) .. utfchar(l[2])
-- else
-- inspect(v)
end
else
local u = v.uccode
if u then
-- we have an lowercase
if type(u) == "number" then
uhash[utfchar(k)] = utfchar(u)
elseif #u == 2 then
uhash[utfchar(k)] = utfchar(u[1]) .. utfchar(u[2])
-- else
-- inspect(v)
end
end
end
local s = v.shcode
if s then
if type(s) == "number" then
shash[utfchar(k)] = utfchar(s)
elseif #s == 2 then
shash[utfchar(k)] = utfchar(s[1]) .. utfchar(s[2])
-- else
-- inspect(v)
end
end
-- end
end
if storage then
storage.register("characters/lhash", lhash, "characters.lhash")
storage.register("characters/uhash", uhash, "characters.uhash")
storage.register("characters/shash", shash, "characters.shash")
end
end
local lhash = characters.lhash mark(lhash)
local uhash = characters.uhash mark(uhash)
local shash = characters.shash mark(shash)
local utf8lowercharacter = utfchartabletopattern(lhash) / lhash
local utf8uppercharacter = utfchartabletopattern(uhash) / uhash
local utf8shapecharacter = utfchartabletopattern(shash) / shash
local utf8lower = Cs((utf8lowercharacter + utf8character)^0)
local utf8upper = Cs((utf8uppercharacter + utf8character)^0)
local utf8shape = Cs((utf8shapecharacter + utf8character)^0)
lpegpatterns.utf8lowercharacter = utf8lowercharacter -- one character
lpegpatterns.utf8uppercharacter = utf8uppercharacter -- one character
lpegpatterns.utf8shapecharacter = utf8shapecharacter -- one character
lpegpatterns.utf8lower = utf8lower -- string
lpegpatterns.utf8upper = utf8upper -- string
lpegpatterns.utf8shape = utf8shape -- string
function characters.lower (str) return lpegmatch(utf8lower,str) end
function characters.upper (str) return lpegmatch(utf8upper,str) end
function characters.shaped(str) return lpegmatch(utf8shape,str) end
-- local str = [[
-- ÀÁÂÃÄÅàáâãäå àáâãäåàáâãäå ÀÁÂÃÄÅÀÁÂÃÄÅ AAAAAAaaaaaa
-- ÆÇæç æçæç ÆÇÆÇ AECaec
-- ÈÉÊËèéêë èéêëèéêë ÈÉÊËÈÉÊË EEEEeeee
-- ÌÍÎÏÞìíîïþ ìíîïþìíîïþ ÌÍÎÏÞÌÍÎÏÞ IIIIÞiiiiþ
-- Ðð ðð ÐÐ Ðð
-- Ññ ññ ÑÑ Nn
-- ÒÓÔÕÖòóôõö òóôõöòóôõö ÒÓÔÕÖÒÓÔÕÖ OOOOOooooo
-- Øø øø ØØ Oo
-- ÙÚÛÜùúûü ùúûüùúûü ÙÚÛÜÙÚÛÜ UUUUuuuu
-- Ýýÿ ýýÿ ÝÝŸ Yyy
-- ß ß SS ss
-- Ţţ ţţ ŢŢ Tt
-- ]]
--
-- local lower = characters.lower print(lower(str))
-- local upper = characters.upper print(upper(str))
-- local shaped = characters.shaped print(shaped(str))
--
-- local c, n = os.clock(), 10000
-- for i=1,n do lower(str) upper(str) shaped(str) end -- 2.08 => 0.77
-- print(os.clock()-c,n*#str*3)
-- maybe: (twice as fast when much ascii)
--
-- local tolower = lpeg.patterns.tolower
-- local lower = string.lower
--
-- local allascii = R("\000\127")^1 * P(-1)
--
-- function characters.checkedlower(str)
-- return lpegmatch(allascii,str) and lower(str) or lpegmatch(tolower,str) or str
-- end
function characters.lettered(str,spacing)
local new, n = { }, 0
if spacing then
local done = false
for u in utfvalues(str) do
local c = data[u].category
if is_letter[c] then
if done and n > 1 then
n = n + 1
new[n] = " "
done = false
end
n = n + 1
new[n] = utfchar(u)
elseif spacing and is_spacing[c] then
done = true
end
end
else
for u in utfvalues(str) do
if is_letter[data[u].category] then
n = n + 1
new[n] = utfchar(u)
end
end
end
return concat(new)
end
--[[ldx--
<p>Requesting lower and uppercase codes:</p>
--ldx]]--
function characters.uccode(n) return uccodes[n] end -- obsolete
function characters.lccode(n) return lccodes[n] end -- obsolete
function characters.shape(n)
local shcode = shcodes[n]
if not shcode then
return n, nil
elseif type(shcode) == "table" then
return shcode[1], shcode[#shcode]
else
return shcode, nil
end
end
-- -- some day we might go this route, but it does not really save that much
-- -- so not now (we can generate a lot using mtx-unicode that operates on the
-- -- database)
--
-- -- category cjkwd direction linebreak
--
-- -- adobename comment contextcommand contextname description fallback lccode
-- -- mathclass mathfiller mathname mathspec mathstretch mathsymbol mirror
-- -- range shcode specials uccode uccodes unicodeslot
--
-- local data = {
-- ['one']={
-- common = {
-- category="cc",
-- direction="bn",
-- linebreak="cm",
-- },
-- vector = {
-- [0x0000] = {
-- description="NULL",
-- group='one',
-- unicodeslot=0x0000,
-- },
-- {
-- description="START OF HEADING",
-- group='one',
-- unicodeslot=0x0001,
-- },
-- }
-- }
-- }
--
-- local chardata, groupdata = { }, { }
--
-- for group, gdata in next, data do
-- local common, vector = { __index = gdata.common }, gdata.vector
-- for character, cdata in next, vector do
-- chardata[character] = cdata
-- setmetatable(cdata,common)
-- end
-- groupdata[group] = gdata
-- end
-- characters.data, characters.groups = chardata, groupdata
-- [0xF0000]={
-- category="co",
-- cjkwd="a",
-- description="<Plane 0x000F Private Use, First>",
-- direction="l",
-- unicodeslot=0xF0000,
-- },
-- [0xFFFFD]={
-- category="co",
-- cjkwd="a",
-- description="<Plane 0x000F Private Use, Last>",
-- direction="l",
-- unicodeslot=0xFFFFD,
-- },
-- [0x100000]={
-- category="co",
-- cjkwd="a",
-- description="<Plane 0x0010 Private Use, First>",
-- direction="l",
-- unicodeslot=0x100000,
-- },
-- [0x10FFFD]={
-- category="co",
-- cjkwd="a",
-- description="<Plane 0x0010 Private Use, Last>",
-- direction="l",
-- unicodeslot=0x10FFFD,
-- },
if not characters.superscripts then
local superscripts = allocate() characters.superscripts = superscripts
local subscripts = allocate() characters.subscripts = subscripts
local fractions = allocate() characters.fractions = fractions
-- skipping U+02120 (service mark) U+02122 (trademark)
for k, v in next, data do
local specials = v.specials
if specials then
local what = specials[1]
if what == "super" then
if #specials == 2 then
superscripts[k] = specials[2]
elseif trace_defining then
report_defining("ignoring %s %a, char %c, description %a","superscript",ustring(k),k,v.description)
end
elseif what == "sub" then
if #specials == 2 then
subscripts[k] = specials[2]
elseif trace_defining then
report_defining("ignoring %s %a, char %c, description %a","subscript",ustring(k),k,v.description)
end
elseif what == "fraction" then
if #specials > 1 then
fractions[k] = { unpack(specials,2) }
elseif trace_defining then
report_defining("ignoring %s %a, char %c, description %a","fraction",ustring(k),k,v.description)
end
end
end
end
-- print(table.serialize(superscripts, "superscripts", { hexify = true }))
-- print(table.serialize(subscripts, "subscripts", { hexify = true }))
-- print(table.serialize(fractions, "fractions", { hexify = true }))
if storage then
storage.register("characters/superscripts", superscripts, "characters.superscripts")
storage.register("characters/subscripts", subscripts, "characters.subscripts")
storage.register("characters/fractions", fractions, "characters.fractions")
end
end
function characters.showstring(str)
local list = utotable(str)
for i=1,#list do
report_defining("split % 3i : %C",i,list[i])
end
end
-- code moved to char-tex.lua
return characters
|
------------------------------------------------------------
------------------------------------------------------------
---- Author: Dylan 'Itokoyamato' Thuillier ----
---- ----
---- Email: itokoyamato@hotmail.fr ----
---- ----
---- Resource: tokovoip_script ----
---- ----
---- File: c_utils.lua ----
------------------------------------------------------------
------------------------------------------------------------
--------------------------------------------------------------------------------
-- Utils: Data system functions
--------------------------------------------------------------------------------
local playersData = {};
function setPlayerData(playerServerId, key, data, shared)
if (not key or data == nil) then return end
if (not playersData[playerServerId]) then
playersData[playerServerId] = {};
end
playersData[playerServerId][key] = {data = data, shared = shared};
if (shared) then
TriggerServerEvent("Tokovoip:setPlayerData", playerServerId, key, data, shared);
end
end
RegisterNetEvent("Tokovoip:setPlayerData");
AddEventHandler("Tokovoip:setPlayerData", setPlayerData);
function getPlayerData(playerServerId, key)
if (not playersData[playerServerId] or playersData[playerServerId][key] == nil) then return false; end
return playersData[playerServerId][key].data;
end
function refreshAllPlayerData(toEveryone)
TriggerServerEvent("Tokovoip:refreshAllPlayerData", toEveryone);
end
RegisterNetEvent("onClientPlayerReady");
AddEventHandler("onClientPlayerReady", refreshAllPlayerData);
function doRefreshAllPlayerData(serverData)
for playerServerId, playerData in pairs(serverData) do
for key, data in pairs(playerData) do
playersData[playerServerId][key] = {data = data, shared = true};
end
end
for playerServerId, playerData in pairs(playersData) do
for key, data in pairs(playerData) do
if (not serverData[playerServerId]) then
playersData[playerServerId] = nil;
elseif (serverData[playerServerId][key] == nil) then
playersData[playerServerId][key] = nil;
end
end
end
end
RegisterNetEvent("Tokovoip:doRefreshAllPlayerData");
AddEventHandler("Tokovoip:doRefreshAllPlayerData", doRefreshAllPlayerData);
--------------------------------------------------------------------------------
-- Utils: Drawing functions
--------------------------------------------------------------------------------
function drawTxt(x,y ,width,height,scale, text, r,g,b,a)
SetTextFont(0);
SetTextProportional(0);
SetTextScale(scale, scale);
SetTextColour(r, g, b, a);
SetTextDropShadow(0, 0, 0, 0,255);
SetTextEdge(1, 0, 0, 0, 255);
SetTextDropShadow();
SetTextOutline();
SetTextEntry("STRING");
AddTextComponentString(text);
DrawText(x - width / 2, y - height / 2 + 0.005);
end
function draw3dtext(text, posX, posY, posZ, r, g, b, a)
local _, x, y = World3dToScreen2d(posX, posY, posZ);
local localPos = GetEntityCoords(GetPlayerPed(localPlayer));
local dist = GetDistanceBetweenCoords(localPos, posX, posY, posZ);
local maxDist = 100;
local size = 0.2;
local scale = size - size * (dist / maxDist);
local offsetX = 0.07 + 0.0235 * (dist / maxDist);
local offsetY = 0.07 + 0.0235 * (dist / maxDist);
if (dist < maxDist) then
if (x and y) then
drawTxt(x + offsetX, y + offsetY, 0.185,0.206, scale, text, r, g, b, a);
end
end
end
--------------------------------------------------------------------------------
-- Utils: Table functions
--------------------------------------------------------------------------------
function table.val_to_str (v)
if ("string" == type(v)) then
v = string.gsub(v, "\n", "\\n");
if (string.match(string.gsub(v, "[^'\"]", ""), '^"+$')) then
return ("'"..v.."'");
end
return ('"'..string.gsub(v, '"', '\\"')..'"');
else
return ("table" == type(v) and table.tostring(v) or tostring(v));
end
end
function table.key_to_str (k)
if ("string" == type(k) and string.match(k, "^[_%a][_%a%d]*$")) then
return (k);
else
return ("["..table.val_to_str(k).."]");
end
end
function table.tostring(tbl)
local result, done = {}, {};
for k, v in ipairs(tbl) do
table.insert(result, table.val_to_str(v));
done[k] = true;
end
for k, v in pairs(tbl) do
if (not done[k]) then
table.insert(result, table.key_to_str(k).."="..table.val_to_str(v));
end
end
return ("{"..table.concat(result, ",").."}");
end
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
--------------------------------------------------------------------------------
-- Utils: Printing functions
--------------------------------------------------------------------------------
function notification(str)
end
local functionSeen={}
function printFunctions(t,i)
functionSeen[t]=true;
local s={};
local n=0;
for k in pairs(t) do
n=n+1 s[n]=k;
end
table.sort(s);
for k,v in ipairs(s) do
Citizen.Trace(i.." "..v.."\n");
v=t[v];
if (type(v)=="table" and not functionSeen[v]) then
printFunctions(v,i.."\t");
end
end
end
function printAllFunctions()
printFunctions(_G,"")
end
--------------------------------------------------------------------------------
-- Utils: Random functions
--------------------------------------------------------------------------------
function escape(str)
return str:gsub( "%W", "");
end
function getPlayers()
local players = {};
for i = 0, 256 do
if (NetworkIsPlayerActive(i)) then
players[#players + 1] = i;
end
end
return (players);
end
Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
|
print("movie.play()")
movie.play("SMW.smv") -- should test with relative path
if emu.registerafter then
count = 0
emu.registerafter(function()
count = count + 1
if count == 300 then
if movie.replay then
movie.replay()
else
print("movie.replay is not available")
end
end
if count == 900 then
print("movie.close()")
movie.close()
end
end)
end
|
InputConfig({ name = "Aquellex" })
KeyMap({
[Key.W] = Button.Up,
[Key.A] = Button.Left,
[Key.S] = Button.Down,
[Key.D] = Button.Right,
[Key.C] = Button.Select,
[Key.V] = Button.Start,
[Key.G] = Button.B,
[Key.H] = Button.A
})
GlobalKeyMap({
[Key.Tab] = Action.RetroPlug.NextInstance
})
|
-- indent-blankline character.
vim.g.indent_blankline_char = "▏"
-- Disable indent-blankline on these pages.
vim.g.indent_blankline_filetype_exclude = { "help", "terminal", "dashboard", "packer"}
vim.g.indent_blankline_buftype_exclude = { "terminal", 'lsp-installer', 'lspinfo' }
vim.g.indent_blankline_show_trailing_blankline_indent = false
vim.g.indent_blankline_show_first_indent_level = true
|
-- local function ChatDropMoney( ply, text )
-- -- //// Do /commands privatly, !commands publicly //
-- -- local _cmd = "dropmoney";
-- -- local _bSlash = string.StartWith( text, "/" .. _cmd )
-- -- local _bExclaim = string.StartWith( text, "!" .. _cmd )
-- -- local _argstbl = string.Explode( " ", text )
-- -- if ( _bSlash || _bExclaim ) then
-- -- // Heres where you can call your data.
-- -- local _arg = _argstbl[2];
-- -- local money = tonumber(_arg, 10)
-- -- GM.Inv:PlayerDropMoney( ply, money, true )
-- -- return"";
-- -- end
-- end
-- hook.Add("PlayerSay", "vrzn.ChatCommands", ChatMakeWanted ) |
-- ./lua-5.3.5/src/lua fac.lua
function factorial(n)
if n == 0 then
return 1
end
return n * factorial(n - 1)
end
print(factorial(4))
|
local player = Var "Player"
if SL[ToEnumShortString(player)].ActiveModifiers.HideCombo then
return Def.Actor{ InitCommand=function(self) self:visible(false) end }
end
local ShowComboAt = THEME:GetMetric("Combo", "ShowComboAt")
local af = Def.ActorFrame{
InitCommand=function(self)
self:draworder(101)
end,
OnCommand=function(self)
if SL.Global.GameMode == "StomperZ" then self:y(-20) end
end,
ComboCommand=function(self, params)
local CurrentCombo = params.Misses or params.Combo
-- if the combo has reached (or surpassed) the threshold to be shown, display the AF, otherwise hide it
self:visible( CurrentCombo ~= nil and CurrentCombo >= ShowComboAt )
end,
}
if not SL[ToEnumShortString(player)].ActiveModifiers.HideComboExplosions then
-- load the combo milestones actors into the Player combo; they will
-- listen for the appropriate Milestone command from the engine
af[#af+1] = LoadActor( THEME:GetPathG("Combo","100Milestone") )..{ Name="OneHundredMilestone" }
af[#af+1] = LoadActor( THEME:GetPathG("Combo","1000Milestone") )..{ Name="OneThousandMilestone" }
end
af[#af+1] = LoadFont("_wendy combo")..{
Name="Number",
OnCommand=function(self)
self:shadowlength(1):vertalign(middle):zoom(0.75)
end,
ComboCommand=function(self, params)
local CurrentCombo = params.Misses or params.Combo
self:settext( CurrentCombo or "" )
if (SL.Global.GameMode ~= "ECFA" and params.FullComboW1) or (SL.Global.GameMode == "ECFA" and (params.FullComboW1 or params.FullComboW2)) then
-- blue combo
self:playcommand("ChangeColor", {Color1="#C8FFFF", Color2="#6BF0FF"})
elseif (SL.Global.GameMode ~= "ECFA" and params.FullComboW2) or (SL.Global.GameMode == "ECFA" and params.FullComboW3) then
-- gold combo
self:playcommand("ChangeColor", {Color1="#FDFFC9", Color2="#FDDB85"})
elseif (SL.Global.GameMode ~= "ECFA" and params.FullComboW3) or (SL.Global.GameMode == "ECFA" and params.FullComboW4) then
-- green combo
self:playcommand("ChangeColor", {Color1="#C9FFC9", Color2="#94FEC1"})
elseif params.Combo then
-- normal (white) combo
self:stopeffect():diffuse( Color.White )
else
-- miss (red) combo
self:stopeffect():diffuse( Color.Red )
end
end,
ChangeColorCommand=function(self, params)
self:diffuseshift():effectperiod(0.8)
self:effectcolor1( color(params.Color1) )
self:effectcolor2( color(params.Color2) )
end
}
return af |
function setTime(Split, Player)
if Split[2] == 'on' then
Root:ForEachWorld(
function (World)
local thisWorld = World:GetName()
isStopped[thisWorld] = true
savedTime[thisWorld] = nil
if Split[3] ~= nil then
World:SetTimeOfDay(Split[3])
end
print( thisWorld .. ": time stopped at " .. World:GetTimeOfDay() )
end
)
elseif Split[2] == 'off' then
Root:ForEachWorld(
function(World)
local thisWorld = World:GetName()
if isStopped[thisWorld] == true then
isStopped[thisWorld] = false
print(thisWorld .. ": time resumed" )
end
end
)
elseif Split[2] == "overview" and Split[3] == nil then
Player:SendMessage( "------------------------------------------" )
Root:ForEachWorld(
function(World)
local thisWorld = World:GetName()
if isStopped[thisWorld] then
Player:SendMessage( thisWorld .. ": " .. cChatColor.Rose .. "stopped at " .. savedTime[thisWorld] )
else
Player:SendMessage( thisWorld .. ": " .. cChatColor.Green .. "running at " .. World:GetTimeOfDay() )
end
end
)
Player:SendMessage( "------------------------------------------" )
else
setTimeWorld(Split, Player)
end
return true
end
function setTimeWorld(Split, Player)
Root:ForEachWorld(
function(World)
local thisWorld = World:GetName()
if thisWorld == Split[2] then
if Split[3] == 'on' then
isStopped[Split[2]] = true
savedTime[Split[2]] = nil
if Split[4] ~= nil then
World:SetTimeOfDay(Split[4])
end
print(Split[2] .. ": time stopped at " .. World:GetTimeOfDay() )
end
if Split[3] == 'off' then
isStopped[thisWorld] = false
end
end
end
)
end
|
local ADDON, Addon = ...
local Mod = Addon:NewModule('Gossip')
local npcBlacklist = {
[107435] = true, [112697] = true, [112699] = true, -- Suspicous Noble
[101462] = true, -- Reaves
}
local cosRumorNPC = 107486
local function GossipNPCID()
local guid = UnitGUID("npc")
local npcid = guid and select(6, strsplit("-", guid))
return tonumber(npcid)
end
local function IsStaticPopupShown()
for index = 1, STATICPOPUP_NUMDIALOGS do
local frame = _G["StaticPopup"..index]
if frame and frame:IsShown() then
return true
end
end
return false
end
function Mod:CoSRumor()
local clue = GetGossipText()
local shortClue = Addon.Locale:Rumor(clue)
if not shortClue then
AngryKeystones_Data.rumors[clue] = true
end
if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
SendChatMessage(shortClue or clue, "INSTANCE_CHAT")
elseif IsInGroup(LE_PARTY_CATEGORY_HOME) then
SendChatMessage(shortClue or clue, "PARTY")
else
SendChatMessage(shortClue or clue, "SAY")
end
end
function Mod:RumorCleanup()
local new = {}
for clue,_ in pairs(AngryKeystones_Data.rumors) do
if not Addon.Locale:Rumor(clue) then
new[clue] = true
end
end
AngryKeystones_Data.rumors = new
end
function Mod:GOSSIP_SHOW()
local npcId = GossipNPCID()
if Addon.Config.cosRumors and Addon.Locale:HasRumors() and npcId == cosRumorNPC and GetNumGossipOptions() == 0 then
self:CoSRumor()
CloseGossip()
end
local scenarioType = select(10, C_Scenario.GetInfo())
if Addon.Config.autoGossip and scenarioType == LE_SCENARIO_TYPE_CHALLENGE_MODE and not npcBlacklist[npcId] then
local options = {GetGossipOptions()}
for i = 1, GetNumGossipOptions() do
if options[i*2] == "gossip" then
local popupWasShown = IsStaticPopupShown()
SelectGossipOption(i)
local popupIsShown = IsStaticPopupShown()
if popupIsShown then
if not popupWasShown then
StaticPopup1Button1:Click()
CloseGossip()
end
else
CloseGossip()
end
break
end
end
end
end
local function PlayCurrent()
if select(10, C_Scenario.GetInfo()) == LE_SCENARIO_TYPE_CHALLENGE_MODE and Addon.Config.hideTalkingHead then
local frame = TalkingHeadFrame
if (frame.finishTimer) then
frame.finishTimer:Cancel()
frame.finishTimer = nil
end
frame:Hide()
end
end
function Mod:Blizzard_TalkingHeadUI()
hooksecurefunc("TalkingHeadFrame_PlayCurrent", PlayCurrent)
end
function Mod:Startup()
if not AngryKeystones_Data then AngryKeystones_Data = {} end
if not AngryKeystones_Data.rumors then AngryKeystones_Data.rumors = {} end
if Addon.Config.cosRumors then self:RumorCleanup() end
self:RegisterEvent("GOSSIP_SHOW")
self:RegisterAddOnLoaded("Blizzard_TalkingHeadUI")
end
|
-- This file is automatically generated, do not edit!
-- Jewel data (c) Grinding Gear Games
return {
jewels = {
["小型星团珠宝"] = {
size = "Small",
sizeIndex = 0,
minNodes = 2,
maxNodes = 3,
smallIndicies = { 0, 4, 2 },
notableIndicies = { 4 },
socketIndicies = { 4 },
totalIndicies = 6,
skills = {
["affliction_maximum_life"] = {
name = "生命",
icon = "Art/2DArt/SkillIcons/passives/IncreasedMaximumLifeNode.png",
tag = "affliction_maximum_life",
stats = { "最大生命提高 4%" },
enchant = {
"增加的小天赋获得:最大生命提高 4%",
},
},
["affliction_maximum_energy_shield"] = {
name = "能量护盾",
icon = "Art/2DArt/SkillIcons/passives/EnergyShieldNode.png",
tag = "affliction_maximum_energy_shield",
stats = { "最大能量护盾提高 6%" },
enchant = {
"增加的小天赋获得:最大能量护盾提高 6%",
},
},
["affliction_maximum_mana"] = {
name = "魔力",
icon = "Art/2DArt/SkillIcons/passives/MaxManaNode.png",
tag = "affliction_maximum_mana",
stats = { "最大魔力提高 6%" },
enchant = {
"增加的小天赋获得:最大魔力提高 6%",
},
},
["affliction_armour"] = {
name = "护甲",
icon = "Art/2DArt/SkillIcons/passives/ArmourNode.png",
tag = "affliction_armour",
stats = { "护甲提高 15%" },
enchant = {
"增加的小天赋获得:护甲提高 15%",
},
},
["affliction_evasion"] = {
name = "闪避值",
icon = "Art/2DArt/SkillIcons/passives/EvasionNode.png",
tag = "affliction_evasion",
stats = { "闪避值提高 15%" },
enchant = {
"增加的小天赋获得:闪避值提高 15%",
},
},
["affliction_chance_to_block_attack_damage"] = {
name = "格挡攻击伤害几率",
icon = "Art/2DArt/SkillIcons/passives/BlockAttackDmgNode.png",
tag = "affliction_chance_to_block",
stats = { "1% 攻击伤害格挡率" },
enchant = {
"增加的小天赋获得:1% 攻击伤害格挡率",
},
},
["affliction_chance_to_block_spell_damage"] = {
name = "格挡法术伤害几率",
icon = "Art/2DArt/SkillIcons/passives/BlockSpellDmgNode.png",
tag = "affliction_chance_to_block",
stats = { "1% 法术伤害格挡几率" },
enchant = {
"增加的小天赋获得:1% 法术伤害格挡几率",
},
},
["affliction_fire_resistance"] = {
name = "火焰抗性",
icon = "Art/2DArt/SkillIcons/passives/FireResistNode.png",
tag = "affliction_fire_resistance",
stats = { "+15% 火焰抗性" },
enchant = {
"增加的小天赋获得:+15% 火焰抗性",
},
},
["affliction_cold_resistance"] = {
name = "冰霜抗性",
icon = "Art/2DArt/SkillIcons/passives/ColdResistNode.png",
tag = "affliction_cold_resistance",
stats = { "+15% 冰霜抗性" },
enchant = {
"增加的小天赋获得:+15% 冰霜抗性",
},
},
["affliction_lightning_resistance"] = {
name = "闪电抗性",
icon = "Art/2DArt/SkillIcons/passives/LightningResistNode.png",
tag = "affliction_lightning_resistance",
stats = { "+15% 闪电抗性" },
enchant = {
"增加的小天赋获得:+15% 闪电抗性",
},
},
["affliction_chaos_resistance"] = {
name = "混沌抗性",
icon = "Art/2DArt/SkillIcons/passives/ChaosResistNode.png",
tag = "affliction_chaos_resistance",
stats = { "+12% 混沌抗性" },
enchant = {
"增加的小天赋获得:+12% 混沌抗性",
},
},
["affliction_chance_to_dodge_attacks"] = {
name = "躲避攻击几率",
icon = "Art/2DArt/SkillIcons/passives/DodgeAtksNode.png",
tag = "affliction_chance_to_dodge_attacks",
stats = { "1% 的几率躲避攻击击中" },
enchant = {
"增加的小天赋获得:1% 的几率躲避攻击击中",
},
},
["affliction_strength"] = {
name = "力量",
icon = "Art/2DArt/SkillIcons/passives/plusstrength.png",
tag = "affliction_strength",
stats = { "+10 力量" },
enchant = {
"增加的小天赋获得:+10 力量",
},
},
["affliction_dexterity"] = {
name = "敏捷",
icon = "Art/2DArt/SkillIcons/passives/plusdexterity.png",
tag = "affliction_dexterity",
stats = { "+10 敏捷" },
enchant = {
"增加的小天赋获得:+10 敏捷",
},
},
["affliction_intelligence"] = {
name = "智慧",
icon = "Art/2DArt/SkillIcons/passives/plusintelligence.png",
tag = "affliction_intelligence",
stats = { "+10 智慧" },
enchant = {
"增加的小天赋获得:+10 智慧",
},
},
},
},
["中型星团珠宝"] = {
size = "Medium",
sizeIndex = 1,
minNodes = 4,
maxNodes = 6,
smallIndicies = { 0, 6, 8, 4, 10, 2 },
notableIndicies = { 6, 10, 2, 0 },
socketIndicies = { 6 },
totalIndicies = 12,
skills = {
["affliction_fire_damage_over_time_multiplier"] = {
name = "持续火焰伤害加成",
icon = "Art/2DArt/SkillIcons/passives/FireDamageOverTimeNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltFireDamageMastery.png",
tag = "affliction_fire_damage_over_time_multiplier",
stats = { "+4% 火焰持续伤害加成" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:+4% 火焰持续伤害加成",
},
},
["affliction_chaos_damage_over_time_multiplier"] = {
name = "持续混沌伤害加成",
icon = "Art/2DArt/SkillIcons/passives/ChaosDamageOverTimeNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltChaosDamageMastery.png",
tag = "affliction_chaos_damage_over_time_multiplier",
stats = { "+4% 混沌持续伤害加成" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:+4% 混沌持续伤害加成",
},
},
["affliction_physical_damage_over_time_multiplier"] = {
name = "持续物理伤害加成",
icon = "Art/2DArt/SkillIcons/passives/PhysicalDamageOverTimeNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltBloodMastery.png",
tag = "affliction_physical_damage_over_time_multiplier",
stats = { "+4% 物理持续伤害加成" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:+4% 物理持续伤害加成",
},
},
["affliction_cold_damage_over_time_multiplier"] = {
name = "持续冰霜伤害加成",
icon = "Art/2DArt/SkillIcons/passives/ColdDamageOverTimeNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltColdDamageMastery.png",
tag = "affliction_cold_damage_over_time_multiplier",
stats = { "+4% 冰霜持续伤害加成" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:+4% 冰霜持续伤害加成",
},
},
["affliction_damage_over_time_multiplier"] = {
name = "持续伤害加成",
icon = "Art/2DArt/SkillIcons/passives/DamageOverTimeNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltDamageOverTimeMultiplierMastery.png",
tag = "affliction_damage_over_time_multiplier",
stats = { "+4% 持续伤害加成" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:+4% 持续伤害加成",
},
},
["affliction_effect_of_non-damaging_ailments"] = {
name = "非伤害型异常状态效果",
icon = "Art/2DArt/SkillIcons/passives/IncreasedNonDamageAilmentNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltNonDamagingAilmentsMastery.png",
tag = "affliction_effect_of_non-damaging_ailments",
stats = { "非伤害型异常状态效果提高 10%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:非伤害型异常状态效果提高 10%",
},
},
["affliction_aura_effect"] = {
name = "光环效果",
icon = "Art/2DArt/SkillIcons/passives/AuraEffectNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryAuras.png",
tag = "affliction_aura_effect",
stats = { "你技能的非诅咒类光环效果提高 3%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:你技能的非诅咒类光环效果提高 3%",
},
},
["affliction_curse_effect"] = {
name = "诅咒效果",
icon = "Art/2DArt/SkillIcons/passives/CurseEffectNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryCurse.png",
tag = "affliction_curse_effect",
stats = { "你所施放诅咒的效果提高 3%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:你所施放诅咒的效果提高 3%",
},
},
["affliction_damage_while_you_have_a_herald"] = {
name = "捷状态下的伤害",
icon = "Art/2DArt/SkillIcons/passives/DmgHeraldSkillsNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltDamageWithHeraldMastery.png",
tag = "affliction_damage_while_you_have_a_herald",
stats = { "受捷影响时,伤害提高 10%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:受捷影响时,伤害提高 10%",
},
},
["affliction_minion_damage_while_you_have_a_herald"] = {
name = "捷状态下的召唤生物伤害",
icon = "Art/2DArt/SkillIcons/passives/MinionDmgHeraldSkillsNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMinionDamageHeraldMastery.png",
tag = "affliction_minion_damage_while_you_have_a_herald",
stats = { "你受捷影响时,召唤生物的伤害提高 10%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:你受捷影响时,召唤生物的伤害提高 10%",
},
},
["affliction_warcry_buff_effect"] = {
name = "增助攻击伤害",
icon = "Art/2DArt/SkillIcons/passives/IncreasedWarcryNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltWarcryMastery.png",
tag = "affliction_warcry_buff_effect",
stats = { "增助攻击的伤害提高 20%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:增助攻击的伤害提高 20%",
},
},
["affliction_critical_chance"] = {
name = "暴击率",
icon = "Art/2DArt/SkillIcons/passives/IncreaseCritChanceNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupCrit.png",
tag = "affliction_critical_chance",
stats = { "攻击与法术暴击率提高 15%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:攻击与法术暴击率提高 15%",
},
},
["affliction_minion_life"] = {
name = "召唤生物生命",
icon = "Art/2DArt/SkillIcons/passives/IncreaseMinionLifeNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupMinions.png",
tag = "affliction_minion_life",
stats = { "召唤生物的最大生命提高 12%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:召唤生物的最大生命提高 12%",
},
},
["affliction_area_damage"] = {
name = "范围伤害",
icon = "Art/2DArt/SkillIcons/passives/AreaDmgNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltAreaDamageMastery.png",
tag = "affliction_area_damage",
stats = { "范围伤害提高 10%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:范围伤害提高 10%",
},
},
["affliction_projectile_damage"] = {
name = "投射物伤害",
icon = "Art/2DArt/SkillIcons/passives/ProjectileDmgNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryProjectiles.png",
tag = "affliction_projectile_damage",
stats = { "投射物伤害提高 10%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:投射物伤害提高 10%",
},
},
["affliction_trap_and_mine_damage"] = {
name = "陷阱和地雷伤害",
icon = "Art/2DArt/SkillIcons/passives/TrapAndMineDmgNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryTraps.png",
tag = "affliction_trap_and_mine_damage",
stats = { "陷阱伤害提高 12%", "地雷伤害提高 12%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:陷阱伤害提高 12%",
"增加的小天赋获得:地雷伤害提高 12%",
},
},
["affliction_totem_damage"] = {
name = "图腾伤害",
icon = "Art/2DArt/SkillIcons/passives/TotemDmgNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryTotem.png",
tag = "affliction_totem_damage",
stats = { "图腾伤害提高 12%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:图腾伤害提高 12%",
},
},
["affliction_brand_damage"] = {
name = "烙印伤害",
icon = "Art/2DArt/SkillIcons/passives/BrandDmgNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryBrand.png",
tag = "affliction_brand_damage",
stats = { "烙印伤害提高 12%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:烙印伤害提高 12%",
},
},
["affliction_channelling_skill_damage"] = {
name = "吟唱技能伤害",
icon = "Art/2DArt/SkillIcons/passives/DmgWhenChannelSkillsNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryChannelling.png",
tag = "affliction_channelling_skill_damage",
stats = { "持续吟唱技能伤害提高 12%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:持续吟唱技能伤害提高 12%",
},
},
["affliction_flask_duration"] = {
name = "药剂持续时间",
icon = "Art/2DArt/SkillIcons/passives/FlaskDurationnode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryFlasks.png",
tag = "affliction_flask_duration",
stats = { "药剂效果的持续时间延长 6%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:药剂效果的持续时间延长 6%",
},
},
["affliction_life_and_mana_recovery_from_flasks"] = {
name = "药剂回复生命和魔力",
icon = "Art/2DArt/SkillIcons/passives/LifeManaFlasksrecoverynode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryFlasks.png",
tag = "affliction_life_and_mana_recovery_from_flasks",
stats = { "药剂回复的生命提高 10%", "药剂回复的魔力提高 10%" },
enchant = {
"其中 1 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:药剂回复的生命提高 10%",
"增加的小天赋获得:药剂回复的魔力提高 10%",
},
},
},
},
["大型星团珠宝"] = {
size = "Large",
sizeIndex = 2,
minNodes = 8,
maxNodes = 12,
smallIndicies = { 0, 4, 6, 8, 10, 2, 7, 5, 9, 3, 11, 1 },
notableIndicies = { 6, 4, 8, 10, 2 },
socketIndicies = { 4, 8, 6 },
totalIndicies = 12,
skills = {
["affliction_axe_and_sword_damage"] = {
name = "斧剑伤害",
icon = "Art/2DArt/SkillIcons/passives/NodeAxeandSwordDamage.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupSwordAndAxe.png",
tag = "affliction_axe_and_sword_damage",
stats = { "斧类攻击造成的击中和异常状态伤害提高 12%", "剑类攻击造成的击中和异常状态伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:斧类攻击造成的击中和异常状态伤害提高 12%",
"增加的小天赋获得:剑类攻击造成的击中和异常状态伤害提高 12%",
},
},
["affliction_mace_and_staff_damage"] = {
name = "锤杖伤害",
icon = "Art/2DArt/SkillIcons/passives/NodeMaceandStaffDamage.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupMaceAndStaff.png",
tag = "affliction_mace_and_staff_damage",
stats = { "长杖攻击造成的击中和异常状态伤害提高 12%", "锤类或短杖攻击造成的击中和异常状态伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:锤类或短杖攻击造成的击中和异常状态伤害提高 12%",
"增加的小天赋获得:长杖攻击造成的击中和异常状态伤害提高 12%",
},
},
["affliction_dagger_and_claw_damage"] = {
name = "匕爪伤害",
icon = "Art/2DArt/SkillIcons/passives/NodeDaggerandClawDamage.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltDaggerClawDamageMastery.png",
tag = "affliction_dagger_and_claw_damage",
stats = { "爪类攻击造成的击中和异常状态伤害提高 12%", "匕首攻击造成的击中和异常状态伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:匕首攻击造成的击中和异常状态伤害提高 12%",
"增加的小天赋获得:爪类攻击造成的击中和异常状态伤害提高 12%",
},
},
["affliction_bow_damage"] = {
name = "弓类伤害",
icon = "Art/2DArt/SkillIcons/passives/NodeBowDamage.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupBow.png",
tag = "affliction_bow_damage",
stats = { "弓类的伤害提高 12%", "弓类技能的持续伤害效果提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:弓类的伤害提高 12%",
"增加的小天赋获得:弓类技能的持续伤害效果提高 12%",
},
},
["affliction_wand_damage"] = {
name = "法杖伤害",
icon = "Art/2DArt/SkillIcons/passives/NodeWandDamage.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupWand.png",
tag = "affliction_wand_damage",
stats = { "法杖攻击造成的击中和异常状态伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:法杖攻击造成的击中和异常状态伤害提高 12%",
},
},
["affliction_damage_with_two_handed_melee_weapons"] = {
name = "双手近战武器伤害",
icon = "Art/2DArt/SkillIcons/passives/NodeTwoHandedMeleeDamage.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupTwoHands.png",
tag = "affliction_damage_with_two_handed_melee_weapons",
stats = { "双手武器的攻击伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:双手武器的攻击伤害提高 12%",
},
},
["affliction_attack_damage_while_dual_wielding_"] = {
name = "双持攻击伤害",
icon = "Art/2DArt/SkillIcons/passives/NodeDualWieldingDamage.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupDualWield.png",
tag = "affliction_attack_damage_while_dual_wielding_",
stats = { "双持武器时,攻击伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:双持武器时,攻击伤害提高 12%",
},
},
["affliction_attack_damage_while_holding_a_shield"] = {
name = "持盾攻击伤害",
icon = "Art/2DArt/SkillIcons/passives/NodeHoldingShieldDamage.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupShield.png",
tag = "affliction_attack_damage_while_holding_a_shield",
stats = { "持盾牌时造成的攻击伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:持盾牌时造成的攻击伤害提高 12%",
},
},
["affliction_attack_damage_"] = {
name = "攻击伤害",
icon = "Art/2DArt/SkillIcons/passives/IncreasedAttackDamageNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltAttackDamageMastery.png",
tag = "affliction_attack_damage_",
stats = { "攻击伤害提高 10%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:攻击伤害提高 10%",
},
},
["affliction_spell_damage"] = {
name = "法术伤害",
icon = "Art/2DArt/SkillIcons/passives/IncreasedSpellDamageNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupCast.png",
tag = "affliction_spell_damage",
stats = { "法术伤害提高 10%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:法术伤害提高 10%",
},
},
["affliction_elemental_damage"] = {
name = "元素伤害",
icon = "Art/2DArt/SkillIcons/passives/ElementalDamagenode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryElementalDamage.png",
tag = "affliction_elemental_damage",
stats = { "元素伤害提高 10%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:元素伤害提高 10%",
},
},
["affliction_physical_damage"] = {
name = "物理伤害",
icon = "Art/2DArt/SkillIcons/passives/PhysicalDamagenode2.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryPhysicalDamage.png",
tag = "affliction_physical_damage",
stats = { "物理伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:物理伤害提高 12%",
},
},
["affliction_fire_damage"] = {
name = "火焰伤害",
icon = "Art/2DArt/SkillIcons/passives/FireDamagenode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupFire.png",
tag = "affliction_fire_damage",
stats = { "火焰伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:火焰伤害提高 12%",
},
},
["affliction_lightning_damage"] = {
name = "闪电伤害",
icon = "Art/2DArt/SkillIcons/passives/LightningDamagenode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupLightning.png",
tag = "affliction_lightning_damage",
stats = { "闪电伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:闪电伤害提高 12%",
},
},
["affliction_cold_damage"] = {
name = "冰霜伤害",
icon = "Art/2DArt/SkillIcons/passives/ColdDamagenode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupCold.png",
tag = "affliction_cold_damage",
stats = { "冰霜伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:冰霜伤害提高 12%",
},
},
["affliction_chaos_damage"] = {
name = "混沌伤害",
icon = "Art/2DArt/SkillIcons/passives/ChaosDamagenode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryChaos.png",
tag = "affliction_chaos_damage",
stats = { "混沌伤害提高 12%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:混沌伤害提高 12%",
},
},
["affliction_minion_damage"] = {
name = "召唤生物伤害",
icon = "Art/2DArt/SkillIcons/passives/IncreasedMinionDamageNode.png",
masteryIcon = "Art/2DArt/SkillIcons/passives/AltMasteryGroupMinions.png",
tag = "affliction_minion_damage",
stats = { "召唤生物的伤害提高 10%" },
enchant = {
"其中 2 个增加的天赋为【珠宝槽】",
"增加的小天赋获得:召唤生物的伤害提高 10%",
},
},
},
},
},
notableSortOrder = {
["恢宏壁垒"] = 11179,
["先遣卫士"] = 11180,
["角斗战法"] = 11181,
["领军之将"] = 11182,
["威力结界"] = 11183,
["持久结界"] = 11184,
["勇毅斗士"] = 11185,
["睚眦必报"] = 11186,
["防御老手"] = 11187,
["钢铁斗士"] = 11188,
["凌迟"] = 11189,
["规律主宰"] = 11190,
["力量倍增"] = 11191,
["狂风扫荡"] = 11192,
["恶毒穿刺"] = 11193,
["阴冷誓言"] = 11194,
["坚守战场"] = 11195,
["重装上阵"] = 11196,
["统御之主"] = 11197,
["鹤立鸡群"] = 11198,
["勇毅先驱"] = 11199,
["如臂使指"] = 11200,
["心无旁骛"] = 11201,
["沉着应战"] = 11202,
["血仇必报"] = 11203,
["碎颅斗士"] = 11204,
["直攻要害"] = 11205,
["罪恶滔天"] = 11206,
["放大器"] = 11207,
["凶蛮回荡"] = 11208,
["风暴之眼"] = 11209,
["苦难根基"] = 11210,
["逃之夭夭"] = 11211,
["独断宣言"] = 11212,
["无垠之力"] = 11213,
["横扫千军"] = 11214,
["凝聚"] = 11215,
["翻天横扫"] = 11216,
["胁迫如山"] = 11217,
["先祖回音"] = 11218,
["先祖降临"] = 11219,
["先祖之力"] = 11220,
["先祖护佑"] = 11221,
["激荡狂灵"] = 11222,
["不眠哨卫"] = 11223,
["先祖指引"] = 11224,
["先祖教化"] = 11225,
["活力专注"] = 11226,
["猛烈灌注"] = 11227,
["不动专注"] = 11228,
["持久专注"] = 11229,
["精确专注"] = 11230,
["坚忍专注"] = 11231,
["巫灵斗士"] = 11232,
["奥术专家"] = 11233,
["完美无暇"] = 11234,
["钉刺调和"] = 11235,
["斋戒"] = 11236,
["弥补之源"] = 11237,
["特别预备"] = 11238,
["僵化灵药"] = 11239,
["暴民思维"] = 11240,
["恶狼哭号"] = 11241,
["恶灵之嚎"] = 11242,
["按图索骥"] = 11243,
["内奸"] = 11244,
["警戒之号"] = 11245,
["野蛮嚎叫"] = 11246,
["鲜血之腥"] = 11247,
["飘雪穿云"] = 11248,
["恶化创伤"] = 11249,
["霸主"] = 11250,
["万象之力"] = 11251,
["千斤坠"] = 11252,
["螺旋之风"] = 11253,
["回风之剑"] = 11254,
["疫病弥漫"] = 11255,
["弧光箭"] = 11256,
["淬火箭头"] = 11257,
["侧舷炮"] = 11258,
["混元震天"] = 11259,
["趁机发难"] = 11260,
["风暴之手"] = 11261,
["战场主宰"] = 11262,
["武艺专精"] = 11263,
["好整以暇"] = 11264,
["优雅处刑"] = 11265,
["恶名昭著"] = 11266,
["凶骇武士"] = 11267,
["韵律战法"] = 11268,
["连打带跑"] = 11269,
["无尽杀戮"] = 11270,
["破法"] = 11271,
["技如长虹"] = 11272,
["疾雨摧花"] = 11273,
["又快又狠"] = 11274,
["截心击"] = 11275,
["金刚拳"] = 11276,
["武艺精湛"] = 11277,
["灾殃"] = 11278,
["破坏者"] = 11279,
["充能备战"] = 11280,
["毁灭引擎"] = 11281,
["怒火盛宴"] = 11282,
["弥补之印"] = 11283,
["咒法之墙"] = 11284,
["奥术英姿"] = 11285,
["施法熟手"] = 11286,
["掷象功"] = 11287,
["奥法蠕虫"] = 11288,
["精华疾攻"] = 11289,
["心灵枯竭"] = 11290,
["狂虐者"] = 11291,
["腐蚀元素"] = 11292,
["多利亚尼之训"] = 11293,
["心神错乱"] = 11294,
["棱光之心"] = 11295,
["毁天灭地"] = 11296,
["火焰之主"] = 11297,
["燃烬之烟"] = 11298,
["焚化炉"] = 11299,
["暴风雪"] = 11300,
["风暴痛饮"] = 11301,
["瘫痪"] = 11302,
["超级聚能"] = 11303,
["大雪漫天"] = 11304,
["冻彻心扉"] = 11305,
["冷血杀手"] = 11306,
["残酷之触"] = 11307,
["不动之恶"] = 11308,
["莫名之赐"] = 11309,
["黑暗构想"] = 11310,
["渎神雅量"] = 11311,
["邪恶烟云"] = 11312,
["复兴"] = 11313,
["寸草不生"] = 11314,
["腐烂之爪"] = 11315,
["屠夫呼唤"] = 11316,
["魔侍凋零"] = 11605,
["肿胀灵枢"] = 11317,
["恶毒撕咬"] = 11318,
["原初之缚"] = 11319,
["还击"] = 11320,
["煽风点火"] = 11321,
["汤镬"] = 11322,
["熊熊燃烧"] = 11323,
["火焰缠身"] = 11324,
["多彩之色"] = 11325,
["撕裂"] = 11326,
["累累伤痕"] = 11327,
["老痕新伤"] = 11328,
["降蛊"] = 11329,
["低容忍"] = 11330,
["缓慢折磨"] = 11331,
["永恒苦难"] = 11332,
["旧神启迪"] = 11333,
["凌虐酷刑"] = 11334,
["大出血"] = 11335,
["放血"] = 11336,
["解剖疗法"] = 11337,
["梳洗之刑"] = 11338,
["邪恶复兴"] = 11339,
["循环湮灭"] = 11340,
["力量萃取"] = 11341,
["惊怖酷刑"] = 11342,
["寒冰导体"] = 11343,
["绝妙镇压"] = 11344,
["惊寒降临"] = 11345,
["深寒"] = 11346,
["千里冰封"] = 11347,
["天雷轰顶"] = 11348,
["风暴骑手"] = 11349,
["霹雳雷震"] = 11350,
["邪恶之眼"] = 11351,
["死亡私语"] = 11352,
["禁断之言"] = 11353,
["黑暗篇章"] = 11354,
["牺牲制造者"] = 11355,
["恐惧之主"] = 11356,
["死亡之愿"] = 11357,
["传令者"] = 11358,
["末日使者"] = 11359,
["祭仪领袖"] = 11360,
["赋能使者"] = 11361,
["黑暗使者"] = 11362,
["毁灭使徒"] = 11363,
["持久印象"] = 11364,
["自圆其说"] = 11365,
["欢欣预兆"] = 11366,
["纯粹苦痛"] = 11367,
["门徒"] = 11368,
["致命行军"] = 11369,
["受福重生"] = 11370,
["由死复生"] = 11371,
["饕餮群魔"] = 11372,
["保镖"] = 11373,
["追随"] = 11374,
["流线作业"] = 11375,
["呼啸飞箭"] = 11376,
["以眼还眼"] = 11377,
["连发"] = 11378,
["空气力学"] = 11379,
["开凿"] = 11380,
["探索符文"] = 11381,
["非凡瞩目"] = 11382,
["忠诚钢印"] = 11383,
["神圣征服"] = 11384,
["宏伟计划"] = 11385,
["高枕无忧"] = 11386,
["破坏专家"] = 11387,
["游击战"] = 11388,
["扩张"] = 11389,
["奥术烟花"] = 11390,
["惊奇破坏"] = 11391,
["谨慎操纵"] = 11392,
["巅峰状态"] = 11393,
["整顿"] = 11394,
["血肉盛宴"] = 11395,
["崇高感"] = 11396,
["活力振奋"] = 11397,
["乱中有静"] = 11398,
["肾上腺素"] = 11399,
["肌肉之墙"] = 11400,
["正念"] = 11401,
["液化启迪"] = 11402,
["坦率"] = 11403,
["激进理念"] = 11404,
["心意已决"] = 11405,
["闪光理念"] = 11406,
["天人化生"] = 11407,
["天才"] = 11408,
["即兴演出"] = 11409,
["倔强学徒"] = 11410,
["品味片刻"] = 11411,
["无中生有"] = 11412,
["勇毅者"] = 11413,
["折回冲刺"] = 11414,
["能量留存"] = 11415,
["钢铁之心"] = 11416,
["棱光之壳"] = 11417,
["穷兵黩武"] = 11418,
["天衣无缝"] = 11419,
["屠龙猎手"] = 11420,
["持久冷静"] = 11421,
["棱光之舞"] = 11422,
["万物滋生"] = 11423,
["不可触及"] = 11424,
["变换之影"] = 11425,
["准备就绪"] = 11426,
["自信斗士"] = 11427,
["灵活哨兵"] = 11428,
["恶毒守卫"] = 11429,
["秘法结界"] = 11430,
["刻板援军"] = 11431,
["法师猎人"] = 11432,
["骚乱平息"] = 11433,
["顽强壁垒"] = 11434,
["高空钢丝"] = 11435,
["优雅形体"] = 11436,
["突进时刻"] = 11437,
["遁入虚无"] = 11438,
["熔岩者印记"] = 11439,
["火冥功"] = 11440,
["纯粹之力"] = 11441,
["铁匠"] = 11442,
["不可燃烧"] = 11443,
["深冬潜者"] = 11444,
["冬眠者"] = 11445,
["天生狡诈"] = 11446,
["炼金师"] = 11447,
["防护冻结"] = 11448,
["非凡才能"] = 11449,
["充能器"] = 11450,
["天赋禀异"] = 11451,
["贤者"] = 11452,
["绝缘"] = 11453,
["混沌降生"] = 11454,
["防护毒素"] = 11455,
["腐烂抗力"] = 11456,
["受福"] = 11457,
["腐朽学徒"] = 11458,
["旱魃"] = 12303,
["呼风唤雪"] = 12304,
["风暴之诱"] = 12305,
["苦痛永存"] = 12306,
["开发要害"] = 12307,
["自制"] = 12308,
["决不妥协"] = 12309,
["崇高之形"] = 12310,
["夏日都统"] = 12366,
["冬日都统"] = 12367,
["理智都统"] = 12368,
},
keystones = {
"奇塔弗门徒",
"独行使者",
"造化自然",
"苦难秘辛",
"万物皆动",
"百战老兵",
"空明之掌",
"深渊斗士",
},
}
|
-- Load the p4 module.
local p4api = require 'p4.p4api'
--*******************************************************************************
-- Copyright (c) 2007-2008, Perforce Software, Inc. All rights reserved.
-- Portions Copyright (c) 1999, Mike Meyer. All rights reserved.
-- Portions Copyright (c) 2004-2007, Robert Cowham. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--*******************************************************************************
--
-- P4Integration objects hold details about the integrations that have
-- been performed on a particular revision. Used primarily with the
-- P4Revision class
--
local IntegrationMetatable = {}
IntegrationMetatable.__index = IntegrationMetatable
function IntegrationMetatable:__tostring()
return string.format("Integration (how = %s, file = %s, srev = %s, erev = %s)", self.how, self.file, self.srev, self.erev)
end
function P4.Integration( how, file, srev, erev )
local self = {}
self.how = how
self.file = file
self.srev = srev
self.erev = erev
return setmetatable(self, IntegrationMetatable)
end
--
-- Each P4Revision object holds details about a particular revision
-- of a file. It may also contain the history of any integrations
-- to/from the file
--
local RevisionMetatable = {}
RevisionMetatable.__index = RevisionMetatable
function RevisionMetatable:integration( how, file, srev, erev )
local rec = P4.Integration( how, file, srev, erev )
self.integrations[ #self.integrations + 1 ] = rec
return rec
end
-- iterator over the collection calling a provided function
-- Python's poor man version of the Ruby block
function RevisionMetatable:each_integration()
local i = 0
return function()
i = i + 1
return self.integrations[i]
end
end
function RevisionMetatable:__tostring()
return string.format("Revision (depotFile = %s, rev = %d, change = %s, action = %s, type = %s, time = %d, user = %s, client = %s, %d integrations)",
self.depotFile, self.rev or -1, self.change or "", self.action or "", self.type or "",
self.time or -1, self.user or "", self.client or "", #self.integrations)
end
function P4.Revision( depotFile )
local self = {}
self.depotFile = depotFile
self.integrations = {}
self.rev = nil
self.change = nil
self.action = nil
self.type = nil
self.time = nil
self.user = nil
self.client = nil
self.desc = nil
self.digest = nil
self.fileSize = nil
return setmetatable(self, RevisionMetatable)
end
local DepotFileMetatable =
{
new_revision = function(self)
local r = P4.Revision(self.depotFile)
table.insert(self.revisions, r)
return r
end,
each_revision = function(self)
local i = 0
return function()
i = i + 1
return self.revisions[i]
end
end,
__tostring = function(self)
return string.format("DepotFile (depotFile = %s, %d revisions)", self.depotFile, #self.revisions )
end
}
DepotFileMetatable.__index = DepotFileMetatable
--
-- Each DepotFile entry contains details about one depot file.
--
function P4.DepotFile(name)
return setmetatable(
{
depotFile = name,
revisions = {},
},
DepotFileMetatable)
end
--
-- Resolver class used in p4.run_resolve()
--
-- The default simply checks that p4.input is set to sensible value
--
local defaultResolver =
{
resolve = function(self, mergeInfo)
if mergeInfo.merge_hint == "e" then
print "Standard resolver encountered merge conflict, skipping resolve"
return "s"
else
return mergeInfo.merge_hint
end
end
}
local oldP4 = p4api.P4
function p4api.P4()
local out = oldP4()
local out_mt = getmetatable(out)
out_mt.__getattr = function(self, key)
if key:sub(1, 4) == 'run_' then
return function(self, ...) return self:run(key:sub(5), ...) end
elseif key:sub(1, 7) == 'delete_' then
return function(self, ...) return self:run(key:sub(8), '-d', ...) end
elseif key:sub(1, 6) == 'fetch_' then
return function(self, ...) return self:run(key:sub(7), '-o', ...)[1] end
elseif key:sub(1, 5) == 'save_' then
return function(self, ...)
local args = {...}
self.input = args[1]
table.remove(args, 1)
return self:run(key:sub(6), '-i', args)
end
elseif key:sub(1, 6) == 'parse_' then
return function(self, ...) return self:parse_spec(key:sub(7), ...) end
elseif key:sub(1, 6) == 'format_' then
return function(self, ...) return self:format_spec(key:sub(8), ...) end
end
end
out_mt.last_gui_settings = function(self)
for line in io.lines(os.getenv("HOMEDRIVE") .. os.getenv("HOMEPATH") .. "/.p4qt/settings") do
local connection = line:match('^PrevConnection=(.+)')
if connection then
connection = connection:gsub('(%%)(..)',
function(value1, value2) return string.char(tonumber(value2, 16)) end)
local settings = {}
for setting in (connection .. ', '):gmatch('(.-), ') do
settings[#settings + 1] = setting
end
if #settings == 3 then
self.port, self.user, self.client = unpack(settings)
return true
else
return false
end
end
end
end
--
-- run_filelog: convert "p4 filelog" responses into objects with useful
-- methods
--
-- Requires tagged output to be of any real use. If tagged output it not
-- enabled then you just get the raw data back
--
out_mt.run_filelog = function( self, ... )
local raw = self:run( 'filelog', ... )
if not self.tagged then
-- untagged mode returns simple strings, which breaks the code below
return raw
end
local result = {}
for _, h in ipairs(raw) do
local r
local df
if type(h) == 'table' then
df = P4.DepotFile( h.depotFile )
for n, rev in ipairs(h.rev) do repeat
-- Create a new revision of this file ready for populating
r = df:new_revision()
-- Populate the base attributes of each revision
r.rev = rev
r.change = h.change[ n ]
r.action = h.action[ n ]
r.type = h.type[ n ]
r.time = h.time[ n ]
r.user = h.user[ n ]
r.client = h.client[ n ]
r.desc = h.desc[ n ]
if h.digest then
r.digest = h.digest[ n ]
end
if h.fileSize then
r.fileSize = h.fileSize[ n ]
end
-- Now if there are any integration records for this revision,
-- add them in too
if not h.how or n > #h.how or not h.how[n] then
break
else
for m, how in ipairs(h.how[ n ]) do
file = h.file[ n ][ m ]
srev = h.srev[ n ][ m ]:gsub('^#', '')
erev = h.erev[ n ][ m ]:gsub('^#', '')
if srev == "none" then
srev = 0
else
srev = tonumber( srev )
end
if erev == "none" then
erev = 0
else
erev = tonumber( erev )
end
r:integration( how, file, srev, erev )
end
end
until true end
else
r = h
end
result[#result + 1] = df
end
return result
end
-- Simple interface to make login easier
out_mt.run_login = function(self, ...)
self.input = self.password
return self:run("login", ...)
end
-- Simple interface to allow setting of the password
out_mt.run_password = function(self, oldpass, newpass)
if oldpass and #oldpass > 0 then
self.input = { oldpass, newpass, newpass }
else
self.input = { newpass, newpass }
end
return self:run( "password" )
end
-- Simplified submit - if any arguments is a dict, assume it to be the changeform
out_mt.run_submit = function(self, ...)
local nargs = {...}
for n, arg in ipairs(nargs) do
if type(arg) == "table" then
self.input = arg
table.remove(nargs, n)
table.insert(nargs, '-i')
break
end
end
return self:run("submit", nargs)
end
out_mt.run_print = function(self, ...)
local raw, err = self:run('print', ...)
if raw then
table.remove(raw, 1)
end
return raw, err
end
out_mt.run_resolve = function(self, ...)
local args = {...}
local myResolver = defaultResolver
for n, arg in ipairs(args) do
if type(arg) == 'table' then
if arg.resolver then
myResolver = arg.resolver
break
end
end
end
local savedResolver = self.resolver
self.resolver = myResolver
result, err = self:run("resolve", args)
self.resolver = savedResolver
return result, err
end
return out
end
|
local export_httprequest = exports["httprequest-client"]
function PerformHttpRequest(url, cb, method, data, headers)
export_httprequest:PerformHttpRequest(url, cb, method, data, headers)
end
|
local com = require("component")
local event = require("event")
local p = com.particle
local function spawn(pname, x, y, z, pvx, pvy, pvz)
if type(pvx) == "number" then
if type(pvy) == "number" and type(pvz) == "number" then
return p.spawn(pname, x, y, z, pvx, pvy, pvz)
else
return p.spawn(pname, x, y, z, pvx)
end
else
return p.spawn(pname, x, y, z)
end
end
local function draw(image, pcoords, pname, pv, step, doubleHeight)
pcoords = pcoords or {}
local px, py, pz = table.unpack(pcoords)
px = px or 0
py = py or 0
pz = pz or 0
pname = pname or "flame"
local pvx, pvy, pvz
if type(pv) == "number" then
pvx = pv
elseif type(pv) == "table" then
pvx, pvy, pvz = table.unpack(pv)
end
local x = 0
for line in image:gmatch("[^\n]+") do
x = x + step * 2
local z = 0
for c in line:gmatch(".") do
z = z + step
if c == "#" then
for i = 1, 5, 1 do
spawn(pname, x + px, py, z + pz, pvx, pvy, pvz)
if doubleHeight then
spawn(pname, x + px + step, py, z + pz, pvx, pvy, pvz)
end
end
end
end
end
end
return draw
|
local adam = require("adam.adam")
local actions = require("adam.actions")
local entity_adam = require("example.crowd.entity_adam")
local M = {}
local all_enemy_adam_instances = {}
local get_distance_to_target = adam.actions(
actions.vmath.set_xyz("delta_vector", actions.value("player_position", "x"), actions.value("player_position", "y"), nil, true),
actions.vmath.subtract("delta_vector", actions.value("position"), true),
actions.vmath.set_xyz("delta_vector", nil, nil, 0, true),
actions.vmath.length("delta_vector", "distance", true),
actions.vmath.normalize("delta_vector", true)
)
local get_move_vector = adam.actions(
actions.vmath.set_xyz("move_vector", actions.value("delta_vector", "x"), actions.value("delta_vector", "y"), nil, true),
actions.vmath.multiply("move_vector", actions.value("speed"), true),
actions.vmath.length(actions.value("move_vector"), "move_speed", true)
)
-- @tparam my_adam_instance AdamInstance
local temp_dist = vmath.vector3(0)
local function check_collisions_operator(comp_vector, my_position, my_adam_instance)
local diameter = my_adam_instance:get_value("radius") * 2
comp_vector.x = 0
comp_vector.y = 0
for i = 1, #all_enemy_adam_instances do
-- check all other enemies
local enemy = all_enemy_adam_instances[i]
if enemy ~= my_adam_instance then
local other_pos = enemy:get_value("position")
-- distance vector
temp_dist.x = other_pos.x - my_position.x
temp_dist.y = other_pos.y - my_position.y
local dist = vmath.length(temp_dist)
-- normalize
if dist > 0 then
temp_dist.x = temp_dist.x / dist
temp_dist.y = temp_dist.y / dist
if dist < diameter then
comp_vector.x = comp_vector.x + (-temp_dist.x + (math.random() - 0.5)/5)
comp_vector.y = comp_vector.y + (-temp_dist.y + (math.random() - 0.5)/5)
end
end
end
-- if we moving, other not - add compensation move vector to other
-- if both stay or move - add half compensation to both
end
return comp_vector
end
local check_collisions = adam.actions(
actions.math.operator("comp_vector", actions.value("position"), check_collisions_operator, true),
actions.vmath.normalize("comp_vector", true),
actions.vmath.multiply("comp_vector", 10, true),
actions.vmath.add("move_vector", actions.value("comp_vector"), true),
actions.vmath.length(actions.value("move_vector"), "move_speed", true)
)
M.create_adam = function(game_object, player_object)
local initial = adam.state(
entity_adam.initial,
actions.fsm.get_adam(actions.value("player_adam_id"), "player_adam"),
-- link on position vector
actions.fsm.get_value(actions.value("player_adam"), "position", "player_position")
)
local idle = adam.state(
entity_adam.on_idle,
get_distance_to_target,
actions.vmath.set_xyz("move_vector", 0, 0, nil, true),
check_collisions,
actions.logic.compare(actions.value("distance"), 130, nil, "move_away", "move_to", true),
actions.logic.compare(actions.value("move_speed"), 0, nil, nil, "move", true)
)
local move = adam.state(
actions.vmath.set_xyz("move_vector", 0, 0, nil, true),
check_collisions,
entity_adam.on_move_entity,
actions.logic.compare(actions.value("move_speed"), 0, "idle", nil, nil, true)
)
local move_to = adam.state(
get_distance_to_target,
get_move_vector,
check_collisions,
entity_adam.on_move_entity,
actions.logic.compare(actions.value("distance"), 250, "idle", "idle", nil, true)
)
local move_away = adam.state(
get_distance_to_target,
get_move_vector,
actions.vmath.multiply(actions.value("move_vector"), -1, true),
check_collisions,
entity_adam.on_move_entity,
actions.logic.compare(actions.value("distance"), 200, "idle", nil, "idle", true)
)
local enemy_adam = adam.new(initial,
{
{initial, idle},
-- {idle, move_to, "move_to"},
{idle, move, "move"},
{idle, move_away, "move_away"},
{move, idle, "idle"},
{move_to, idle, "idle"},
{move_away, idle, "idle"},
},
{
move_speed = 0,
move_koef = 1,
z_pos = 0,
speed = 5,
radius = 20,
distance = 0,
comp_vector = vmath.vector3(0),
move_vector = vmath.vector3(0),
position = vmath.vector3(0),
target_object = player_object,
is_flip = false,
anim_run = "enemy_run",
anim_idle = "enemy_idle",
player_adam_id = "player",
player_adam = false,
player_position = true,
delta_vector = vmath.vector3(0)
}
)
enemy_adam:bind(game_object)
enemy_adam:start()
table.insert(all_enemy_adam_instances, enemy_adam)
return enemy_adam
end
return M
|
-- Nmap Scripting Engine
-- required packages for this script
--
-- ICS Discovery Tools Releases
-- ICS Security Workspace(plcscan.org)
---
local bin = require "bin"
local nmap = require "nmap"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
description = [[
discover Siemens SIMATIC S7 1200 PLC.
Based on TIA Portal software.
]]
author = "ICS Security Workspace(plcscan.org)"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
categories = {"discovery","intrusive"}
--
-- @usage
-- nmap -sP --script s71200-enumerate-old.nse -p 102 <host/s>
--
-- @output
--102/tcp open Siemens S7 1200 Ethernet Controller
--| s71200-enumerate-old.nse:
--| Basic Hardware: 6ES7 212-1HE31-0XB0
--|_ Firmware Version: V3.0
--
function set_nmap(host, port)
port.state = "open"
port.version.name = "iso-tsap"
port.version.product = "Siemens S7 1200 Ethernet Controller"
nmap.set_port_version(host, port)
nmap.set_port_state(host, port, "open")
end
function send_receive(socket, query)
local sendstatus, senderr = socket:send(query)
if(sendstatus == false) then
return "Error Sending pack"
end
local rcvstatus,response = socket:receive()
if(rcvstatus == false) then
return "Error Reading pack"
end
return response
end
portrule = shortport.port_or_service(102, "iso-tsap", "tcp")
action = function(host,port)
-- soft handshake Methods one
local connectpack = bin.pack("H","030000231ee00000000600c1020600c20f53494d415449432d524f4f542d4553c0010a")
-- soft handshake Methods two
-- local connectpack = bin.pack("H","0300001611e00000000800c1020600c2020600c0010a")
-- send local connection packet(IE NIC and session)
local gethwinfo = bin.pack("H","030000e502f080720100d631000004ca00000001"..
"00000120360000011d00040000000000a1000000"..
"d3821f0000a38169001515536572766572536573"..
"73696f6e5f31433943333932a3822100152c313a"..
"3a3a362e303a3a5443502f4950202d3e2042726f"..
"6164636f6d204e65744c696e6b2028544d29202e"..
"2e2ea38228001500a38229001500a3822a001516"..
"4846504654385246375052474837595f34313831"..
"3731a3822b000401a3822c001201c9c392a3822d"..
"001500a1000000d3817f0000a381690015155375"..
"62736372697074696f6e436f6e7461696e6572a2"..
"a20000000072010000")
local response
local output = stdnse.output_table()
local sock = nmap.new_socket()
local constatus,conerr = sock:connect(host,port)
if not constatus then
stdnse.print_debug(1,
'Error establishing connection for %s - %s', host,conerr
)
return nil
end
response = send_receive(sock, connectpack)
local s7, length_hex = bin.unpack("C", response, 4)
if ( length_hex == 0x23 ) then
s7, output["Connectstatus"] = "S7 Connect ok"
response = send_receive(sock, gethwinfo)
local s7, protocol_id = bin.unpack("C", response, 1)
if ( #response > 80 and protocol_id == 0x03 ) then
local s, e = string.find(response, "6ES7")
local o, d = string.find(response, "V")
local offset = 15
output["Basic Hardware"] = string.sub(response, s, e + offset)
output["Firmware Version"] = string.sub(response, o, d + 3)
set_nmap(host, port)
sock:close()
return output
end
sock:close()
end
end |
--[[
ReaScript Name: Mousewheel gain
Author: LKC
REAPER: 5.52
Version: 1.0
About:
Changes gain of selected items with scroll of mouse
Instructions: First you must have at least on item selected. Then assign this script to some relative command (mousewheel/osc).
The use your scroll or whatever to change gain of selected items. If none is selected, gain change will be applied only to item
under mouse cursor.
]]
--[[
* Changelog:
* v1.0 (2017-10-14)
+ Initial Release
]]
--[[ ----- DEBUGGING ===>
]]-- <=== DEBUGGING -----
--UTILITIES
function Msg(param)
reaper.ShowConsoleMsg(tostring(param).."\n")
end
function run()
is_new,name,sec,cmd,rel,res,val = reaper.get_action_context()
selected_count = reaper.CountSelectedMediaItems(0)
if selected_count <= 1 then
--reaper.Main_OnCommand(40529,0) --select item under mouse leaving other items selected
reaper.Main_OnCommand(40528,0) --select item under mouse
end
if selected_count > 0 then
for i = 0, selected_count - 1 do
if is_new then
--reaper.ShowConsoleMsg(name .. "\nrel: " .. rel .. "\nres: " .. res .. "\nval = " .. val .. "\n")
local item = reaper.GetSelectedMediaItem( 0,i )
if item ~= nil then
vol = reaper.GetMediaItemInfo_Value(item, "D_VOL")
--reaper.ShowConsoleMsg(vol.."\n")
if val > 0 then --if positive value
local new_vol = vol*1.2
reaper.SetMediaItemInfo_Value(item, "D_VOL", new_vol )
else --if it's negative value
local new_vol = vol/1.2
reaper.SetMediaItemInfo_Value( item, "D_VOL", new_vol )
end
end
end
end
end
--reaper.Main_OnCommand(40441,0) --rebuild peaks
end
reaper.Undo_BeginBlock()
reaper.PreventUIRefresh( 1 )
run() -- run script
reaper.PreventUIRefresh( -1 )
reaper.Undo_EndBlock("LKC - Mousewheel Gain", -1)
reaper.UpdateArrange()
|
local ffi = require 'ffi'
local audio = {}
audio.loaders = {}
function audio.load(path)
local failures
for i, loader in ipairs(audio.loaders) do
local attempt, message = loader(path)
if attempt ~= nil then
return attempt
else
failures = failures or {}
failures[#failures+1] = message
end
end
return nil, failures and table.concat(failures, '\n') or 'failed to read audio data'
end
local default_loaders = {
require 'radish.audio.loaders.ogg_vorbis';
require 'radish.audio.loaders.dumb';
require 'radish.audio.loaders.game_music_emu';
require 'radish.audio.loaders.mpg123'; -- false positives?
}
for i, loader in ipairs(default_loaders) do
if loader then
audio.loaders[#audio.loaders + 1] = loader
end
end
return audio
|
map_gameplay = {}
function map_gameplay:enter()
-- TODO reload the entire map when we re-enter the world
map_gameplay.level_map = Sti("assets/maps/test_map.lua", {'bump'})
map_gameplay.level_world = Bump.newWorld(32)
setupMap(map_gameplay.level_map, map_gameplay.level_world)
game_data.level_score = 0 --reset the score for this level
game_data.level_kills = 0 -- not used
game_data.player:reset() -- give the player back their health
--game_data.bullet_list = {} -- empty out the agents in the field
--game_data.enemy_list = {}
game_data.item_list = {}
map_gameplay.events_list = {}
game_data.player:setXYT(500, 500, 0) -- this should get replaced
map_gameplay.spawner = MapSpawner(map_gameplay.level_map, map_gameplay.level_world, game_data.current_level)
game_data.player:setupBump(map_gameplay.level_world)
game_data.player:setupMap(map_gameplay.level_map)
end
function map_gameplay:update(dt)
--lovebird.update()
screen:update(dt)
if (not game_data.gameplay_paused) then
map_gameplay.level_map:update(dt)
local dx,dy = game_data.player.coord.x - camera.x, game_data.player:getY() - camera.y
--camera:move(dx/2, dy/2)
camera:lockPosition(game_data.player.coord.x, game_data.player.coord.y, camera.smoother)
for key, item in pairs(game_data.item_list) do
item:update(dt)
end
-- updatee other odds and ends
checkMapCollisions()
map_gameplay.spawner:update(dt)
updateHud(dt)
checkEndLevel(1)
map_gameplay:checkEvents()
end
end
-- Drawing time
function map_gameplay:draw()
camera:attach()
love.graphics.setColor(1,1,1, .7)
love.graphics.draw(background)
screen:apply(dt)
--game_data.player:draw()
-- Draw the Enemies
for index, enemy in pairs(game_data.enemy_list) do
--enemy:draw()
end
-- Draw the bullets
for index, bullet in pairs(game_data.bullet_list) do
--bullet:draw()
end
-- Draw the items
for index, item in pairs(game_data.item_list) do
item:draw()
end
drawBoundaries()
--map:draw()
local tx = camera.x - love.graphics.getWidth() / 2
local ty = camera.y - love.graphics.getHeight() / 2
camera:detach()
map_gameplay.level_map:draw(-tx, -ty, camera.scale, camera.scale)
love.graphics.setColor(COLORS.red)
map_gameplay.level_map:bump_draw(-tx, -ty, camera.scale, camera.scale)
drawHUD()
if game_data.mode == "server" then
drawServerDebug()
elseif game_data.mode == "single" then
--drawDebugInfo()
end
drawDebugInfo()
end
function map_gameplay:checkEvents()
map_gameplay.events_list = {}
for _, trigger in pairs(map_gameplay.level_map.layers.triggers.objects) do
if trigger.properties.active == true then
if trigger.shape == "rectangle" then
if PointWithinRectangle(trigger.x, trigger.y, trigger.width, trigger.height, game_data.player:getX(), game_data.player:getY()) then
print("Inside a Trigger ", trigger.properties.trigger_name)
trigger.properties.active = false
table.insert(map_gameplay.events_list, trigger.properties.trigger_name)
end
end
end
end
end
function map_gameplay:keypressed(key)
if key == "e" then
game_data.current_enemy_number = game_data.current_enemy_number + 1
--table.insert(game_data.enemy_list, game_data.current_enemy_number, Enemy(500,500))
local tmp_enemy = Enemy(love.math.random(500), love.math.random(500))
tmp_enemy.id = game_data.current_enemy_number
game_data.enemy_list[game_data.current_enemy_number] = tmp_enemy
end
if key == "q" then
game_data.current_enemy_number = game_data.current_enemy_number + 1
--table.insert(game_data.enemy_list, game_data.current_enemy_number, Enemy(500,500))
local tmp_enemy = EnemyFighter(love.math.random(500), love.math.random(500))
tmp_enemy.id = game_data.current_enemy_number
table.instert(game_data.enemy_list, tmp_enemy)
end
if game_data.mode == "single" then
local result = game_data.player:keypressed(key)
end
if key == "s" then
print("saving")
local tmp_save_data = {}
tmp_save_data.score = game_data.score
print(SaveData.save(tmp_save_data, "savefile"))
end
if key == "i" then
table.insert(game_data.item_list, Item(100, 100))
end
if key == "p" then
game_data.gameplay_paused = not game_data.gameplay_paused
end
if key == "escape" then
Gamestate.switch(main_menu)
end
if key == "]" then
game_data.player:setXYandBump(300,500)
end
if key == "[" then
for idx_item, item in pairs(game_data.item_list) do
print(idx_item, item)
end
end
end
function checkEndLevel(level_number)
if game_data.player:dead() then
print("Player has died")
Gamestate.switch(death_screen)
end
if map_gameplay.spawner:completed() then
if save_data.level_stats[game_data.current_level] == nil then -- create a new entry to save level data
save_data.level_stats[game_data.current_level] = {}
end
save_data.level_stats[game_data.current_level].completed = true
save_data.level_stats[game_data.current_level].kills = game_data.level_kills -- change to get from the spawner
save_data.level_stats[game_data.current_level].score = game_data.level_score
game_data.current_level = game_data.current_level + 1
Gamestate.switch(after_action, game_data.current_level - 1, game_data.level_score, game_data.level_kills)
end
end
function checkMapCollisions()
local start_time_col = love.timer.getTime()
local num_checks = 0
local bullet_list = map_gameplay.level_map.layers.bullet_layer.objects
local items_col, len = map_gameplay.level_world:getItems()
for ii, kk in pairs(items_col) do
print(ii, kk)
end
for idx_bullet, bullet in pairs(bullet_list) do
local bullet_x, bullet_y = bullet:getXY()
-- for each collision that a bullet has
for idx_collisions, collision in pairs(bullet:getCollisions()) do
if collision.other.layer ~= nil then -- this means that we are colliding with an object from the tilemap
print("Tile colisions ", bullet)
bullet:cleanup() --remove the bullet from the bump world
bullet_list[idx_bullet] = nil -- remove the bullet from the list
break
end
end
local entity_list = map_gameplay.level_map.layers.sprite_layer.objects
for idx_entity, entity in pairs(entity_list) do
num_checks = num_checks + 1
-- there was a hit
--print("collisions hit ", entity, bullet.team)
if entity.team ~= bullet.team and entity.coord:distanceToPoint(bullet_x, bullet_y) < entity.hitbox + bullet.size then
bullet:cleanup() -- TODO: THIS CAN BREAK IF THE BULLET ALSO HITS A WALL
bullet_list[idx_bullet] = nil
-- there is a hit
print("Entity Collision ", bullet)
Sounds.hit_2:clone():play()
if entity:damage(bullet.damage) then -- the bullet killed the enemy
if entity == game_data.player then
print("Platerere deado")
else
entity_list[idx_entity] = nil
entity:cleanup()
screen:shake(50)
game_data.level_score = game_data.level_score + entity.difficulty
game_data.level_kills = game_data.level_kills + 1
table.insert(game_data.item_list, Item(entity:getXY()))
end
end
end
end
print("End of Check ", bullet)
end
for idx_item, item in pairs(game_data.item_list) do
num_checks = num_checks + 1
if item.coord:distanceToCoord(game_data.player.coord) < item.size + game_data.player.size then
game_data.item_list[idx_item] = nil
game_data.level_score = game_data.level_score + 1
game_data.coins = game_data.coins + 1
end
end
local end_time_col = love.timer.getTime()
--print("Checks " .. num_checks) -- print out the number of checks that had to happen in checkCollisions()
end
function drawBoundaries()
love.graphics.setColor(1,1,1)
love.graphics.polygon('line', 0,0, game_data.map_properties.width,0, game_data.map_properties.width,game_data.map_properties.height, 0,game_data.map_properties.height)
end
return gameplay |
local colorList = require("datatypes.BrickColor.list")
local mt = {}
mt.__type = "BrickColor"
function mt:__tostring()
return self.Name
end
function mt:__eq(other)
return self.Number == other.Number
end
function mt:__index(index)
error(string.format("%s is not a valid member of BrickColor", tostring(index)), 2)
end
--- Creates a new `BrickColor`.
local function new(number)
assert(type(number) == "number", "arg #1 to BrickColor.new must be a number")
local self = {}
local colorData = colorList[number]
if not colorData then
colorData = colorList[194]
number = 194
end
self.Number = number
self.Name = colorData[1]
self.Color = colorData[2]
setmetatable(self, mt)
return self
end
return {
new = new,
} |
log("5dim_transport")
regroup.group.insert_subgroups("transport", {
"ground30",
"ground50"
}, "belt")
regroup.group.subgroups("transport", {
"pipe-to-ground30",
"pipe-to-ground50",
})
regroup.group.subgroups("machine",{
"storage"
})
regroup.group.insert({
["transport"] = {
["belt"] = {
"5d-mk4-transport-belt",
"5d-mk5-transport-belt"
},
["ground"] = {
"5d-mk4-transport-belt-to-ground",
"5d-mk5-transport-belt-to-ground"
},
["ground30"] = {
"5d-mk1-transport-belt-to-ground-30",
"5d-mk2-transport-belt-to-ground-30",
"5d-mk3-transport-belt-to-ground-30",
"5d-mk4-transport-belt-to-ground-30",
"5d-mk5-transport-belt-to-ground-30"
},
["ground50"] = {
"5d-mk1-transport-belt-to-ground-50",
"5d-mk2-transport-belt-to-ground-50",
"5d-mk3-transport-belt-to-ground-50",
"5d-mk4-transport-belt-to-ground-50",
"5d-mk5-transport-belt-to-ground-50"
},
["splitter"] = {
"5d-mk4-splitter",
"5d-mk5-splitter"
},
["pipe"] = {
"5d-pipe-mk2",
"5d-pipe-mk3"
},
["pipe-to-ground"] = {
"5d-pipe-to-ground-mk2",
"5d-pipe-to-ground-mk3",
},
["pipe-to-ground30"] = {
"5d-pipe-to-ground-mk1-30",
"5d-pipe-to-ground-mk2-30",
"5d-pipe-to-ground-mk3-30"
},
["pipe-to-ground50"] = {
"5d-pipe-to-ground-mk1-50",
"5d-pipe-to-ground-mk2-50",
"5d-pipe-to-ground-mk3-50"
}
},
["machine"] = {
["storage"] = {
"5d-iron-chest-mk2",
"5d-iron-chest-mk2-2",
"5d-iron-chest-mk2-3"
}
}
}) |
previous_score = 0
previous_stable_score = 0
stable_score = 0
-- score digits are sometimes updated high to low
-- make sure we have the same score for 2 frames in a row before updating the score
function correct_score()
if data.score == previous_score then
stable_score = data.score
end
previous_score = data.score
local delta = stable_score - previous_stable_score
previous_stable_score = stable_score
return delta * 10
end
|
return {
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.08
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.092
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.104
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.12
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.132
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.144
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.16
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.172
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.184
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.2
}
}
}
},
init_effect = "",
name = "威光",
time = 8,
color = "yellow",
picture = "",
desc = "受到伤害提高",
stack = 1,
id = 10932,
icon = 10932,
last_effect = "Darkness",
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "injureRatio",
number = 0.08
}
}
}
}
|
local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local lib14a = require('read14a')
local utils = require('utils')
example =[[
1. script run formatMifare
2. script run formatMifare -k aabbccddeeff -n 112233445566 -a FF0780
]]
author = "Iceman"
usage = "script run formatMifare -k <key>"
desc =[[
This script will generate 'hf mf wrbl' commands for each block to format a Mifare card.
Alla datablocks gets 0x00
As default the script sets the keys A/B to 0xFFFFFFFFFFFF
and the access bytes will become 0x78,0x77,0x88
The GDB will become 0x00
The script will skip the manufactoring block 0.
Arguments:
-h - this help
-k <key> - the current six byte key with write access
-n <key> - the new key that will be written to the card
-a <access> - the new access bytes that will be written to the card
]]
local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds
local DEBUG = true -- the debug flag
local CmdString = 'hf mf wrbl %d B %s %s'
local numBlocks = 64
local numSectors = 16
---
-- A debug printout-function
function dbg(args)
if not DEBUG then
return
end
if type(args) == "table" then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print("###", args)
end
end
---
-- This is only meant to be used when errors occur
function oops(err)
print("ERROR: ",err)
end
---
-- Usage help
function help()
print(desc)
print("Example usage")
print(example)
end
--
-- Exit message
function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
--
-- Read information from a card
function GetCardInfo()
result, err = lib14a.read1443a(false)
if not result then
print(err)
return
end
print(("Found: %s"):format(result.name))
core.clearCommandBuffer()
if 0x18 == result.sak then --NXP MIFARE Classic 4k | Plus 4k
-- IFARE Classic 4K offers 4096 bytes split into forty sectors,
-- of which 32 are same size as in the 1K with eight more that are quadruple size sectors.
numSectors = 40
elseif 0x08 == result.sak then -- NXP MIFARE CLASSIC 1k | Plus 2k
-- 1K offers 1024 bytes of data storage, split into 16 sector
numSectors = 16
elseif 0x09 == result.sak then -- NXP MIFARE Mini 0.3k
-- MIFARE Classic mini offers 320 bytes split into five sectors.
numSectors = 5
elseif 0x10 == result.sak then -- NXP MIFARE Plus 2k
numSectors = 32
elseif 0x01 == sak then -- NXP MIFARE TNP3xxx 1K
numSectors = 16
else
print("I don't know how many sectors there are on this type of card, defaulting to 16")
end
--[[
The mifare Classic 1k card has 16 sectors of 4 data blocks each.
The first 32 sectors of a mifare Classic 4k card consists of 4 data blocks and the remaining
8 sectors consist of 16 data blocks.
--]]
-- Defaults to 16 * 4 = 64 - 1 = 63
numBlocks = numSectors * 4 - 1
if numSectors > 32 then
numBlocks = 32*4+ (numSectors-32)*16 -1
end
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local OldKey
local NewKey
local Accessbytes
-- Arguments for the script
for o, a in getopt.getopt(args, 'hk:n:a:') do
if o == "h" then return help() end
if o == "k" then OldKey = a end
if o == "n" then NewKey = a end
if o == "a" then Accessbytes = a end
end
-- validate input args.
OldKey = OldKey or 'FFFFFFFFFFFF'
if #(OldKey) ~= 12 then
return oops( string.format('Wrong length of write key (was %d) expected 12', #OldKey))
end
NewKey = NewKey or 'FFFFFFFFFFFF'
if #(NewKey) ~= 12 then
return oops( string.format('Wrong length of new key (was %d) expected 12', #NewKey))
end
--Accessbytes = Accessbytes or '787788'
Accessbytes = Accessbytes or 'FF0780'
if #(Accessbytes) ~= 6 then
return oops( string.format('Wrong length of accessbytes (was %d) expected 12', #Accessbytes))
end
GetCardInfo()
-- Show info
print( string.format('Estimating number of blocks: %d', numBlocks))
print( string.format('Old key: %s', OldKey))
print( string.format('New key: %s', NewKey))
print( string.format('New Access: %s', Accessbytes))
print( string.rep('--',20) )
-- Set new block data
local EMPTY_BL = string.rep('00',16)
local EMPTY_SECTORTRAIL = string.format('%s%s%s%s',NewKey,Accessbytes,'00',NewKey)
dbg( string.format('New sector-trailer : %s',EMPTY_SECTORTRAIL))
dbg( string.format('New emptyblock: %s',EMPTY_BL))
dbg('')
-- Ask
local dialogResult = utils.confirm("Do you want to erase this card")
if dialogResult == false then
return ExitMsg('Quiting it is then. Your wish is my command...')
end
print( string.rep('--',20) )
-- main loop
for block=0,numBlocks,1 do
local reminder = (block+1) % 4
local cmd
if reminder == 0 then
cmd = CmdString:format(block, OldKey , EMPTY_SECTORTRAIL)
else
cmd = CmdString:format(block, OldKey , EMPTY_BL)
end
if block ~= 0 then
print(cmd)
--core.console(cmd)
end
if core.ukbhit() then
print("aborted by user")
break
end
end
end
main(args) |
-- Loading MySQL Class
require "resources/essentialmode/lib/MySQL"
MySQL:open("127.0.0.1", "gta5_gamemode_essential", "root", "space031")
local max_number_weapons = 6 --maximum number of weapons that the player can buy. Weapons given at spawn doesn't count.
local cost_ratio = 100 --Ratio for withdrawing the weapons. This is price/cost_ratio = cost.
RegisterServerEvent('CheckMoneyForWea')
AddEventHandler('CheckMoneyForWea', function(weapon,price)
TriggerEvent('es:getPlayerFromId', source, function(user)
if (tonumber(user.money) >= tonumber(price)) then
local player = user.identifier
local nb_weapon = 0
local executed_query = MySQL:executeQuery("SELECT * FROM user_weapons WHERE identifier = '@username'",{['@username'] = player})
local result = MySQL:getResults(executed_query, {'weapon_model'}, "identifier")
if result then
for k,v in ipairs(result) do
nb_weapon = nb_weapon + 1
end
end
print(nb_weapon)
if (tonumber(max_number_weapons) > tonumber(nb_weapon)) then
-- Pay the shop (price)
user:removeMoney((price))
MySQL:executeQuery("INSERT INTO user_weapons (identifier,weapon_model,withdraw_cost) VALUES ('@username','@weapon','@cost')",
{['@username'] = player, ['@weapon'] = weapon, ['@cost'] = (price)/cost_ratio})
-- Trigger some client stuff
TriggerClientEvent('FinishMoneyCheckForWea',source)
TriggerClientEvent("es_freeroam:notify", source, "CHAR_MP_ROBERTO", 1, "Roberto", false, "MURDER TIME. FUN TIME!\n")
else
TriggerClientEvent('ToManyWeapons',source)
TriggerClientEvent("es_freeroam:notify", source, "CHAR_MP_ROBERTO", 1, "Roberto", false, "You have reached the weapon limit ! (max: "..max_number_weapons..")\n")
end
else
-- Inform the player that he needs more money
TriggerClientEvent("es_freeroam:notify", source, "CHAR_MP_ROBERTO", 1, "Roberto", false, "You don't have enough cash !\n")
end
end)
end)
RegisterServerEvent("weaponshop:playerSpawned")
AddEventHandler("weaponshop:playerSpawned", function(spawn)
TriggerEvent('es:getPlayerFromId', source, function(user)
TriggerEvent('weaponshop:GiveWeaponsToPlayerSpawn', source)
end)
end)
RegisterServerEvent("weaponshop:GiveWeaponsToPlayerSpawn")
AddEventHandler("weaponshop:GiveWeaponsToPlayerSpawn", function(player)
TriggerEvent('es:getPlayerFromId', player, function(user)
local playerID = user.identifier
local delay = nil
local executed_query = MySQL:executeQuery("SELECT * FROM user_weapons WHERE identifier = '@username'",{['@username'] = playerID})
local result = MySQL:getResults(executed_query, {'weapon_model','withdraw_cost'}, "identifier")
delay = 2000
if(result)then
for k,v in ipairs(result) do
TriggerClientEvent("giveWeapon", player, v.weapon_model, delay)
end
--TriggerClientEvent("es_freeroam:notify", source, "CHAR_MP_ROBERTO", 1, "Roberto", false, "Here are your weapons !\n")
end
end)
end)
RegisterServerEvent("weaponshop:GiveWeaponsToPlayer")
AddEventHandler("weaponshop:GiveWeaponsToPlayer", function(player)
TriggerEvent('es:getPlayerFromId', player, function(user)
local playerID = user.identifier
local delay = nil
local executed_query = MySQL:executeQuery("SELECT * FROM user_weapons WHERE identifier = '@username'",{['@username'] = playerID})
local result = MySQL:getResults(executed_query, {'weapon_model','withdraw_cost'}, "identifier")
delay = 2000
if(result)then
for k,v in ipairs(result) do
if (tonumber(user.money) >= tonumber(v.withdraw_cost)) then
TriggerClientEvent("giveWeapon", player, v.weapon_model, delay)
user:removeMoney((v.withdraw_cost))
else
TriggerClientEvent("es_freeroam:notify", source, "CHAR_MP_ROBERTO", 1, "Roberto", false, "You don't have enough cash !\n")
return
end
end
--TriggerClientEvent("es_freeroam:notify", source, "CHAR_MP_ROBERTO", 1, "Roberto", false, "Here are your weapons !\n")
end
end)
end)
RegisterServerEvent("weaponshop:loseWeapons")
AddEventHandler("weaponshop:loseWeapons", function()
local playerID = getPlayerID(source)
local executed_query = MySQL:executeQuery("DELETE FROM user_weapons WHERE identifier = '@username'",{['@username'] = playerID})
end)
-- get's the player id without having to use bugged essentials
function getPlayerID(source)
local identifiers = GetPlayerIdentifiers(source)
local player = getIdentifiant(identifiers)
return player
end
-- gets the actual player id unique to the player,
-- independent of whether the player changes their screen name
function getIdentifiant(id)
for _, v in ipairs(id) do
return v
end
end |
require "brains/spiderbrain"
require "stategraphs/SGspider"
local hiderassets =
{
Asset("ANIM", "anim/ds_spider_basic.zip"),
Asset("ANIM", "anim/ds_spider_caves.zip"),
Asset("SOUND", "sound/spider.fsb"),
}
local spitterassets =
{
Asset("ANIM", "anim/ds_spider_basic.zip"),
Asset("ANIM", "anim/ds_spider2_caves.zip"),
Asset("SOUND", "sound/spider.fsb"),
}
local dropperassets =
{
Asset("ANIM", "anim/ds_spider_basic.zip"),
Asset("ANIM", "anim/ds_spider_warrior.zip"),
Asset("ANIM", "anim/spider_white.zip"),
Asset("SOUND", "sound/spider.fsb"),
}
local prefabs =
{
"spidergland",
"monstermeat",
"silk",
"spider_web_spit",
}
local function Retarget(inst)
return FindEntity(inst, TUNING.SPIDER_WARRIOR_TARGET_DIST, function(guy)
return (guy:HasTag("character") or guy:HasTag("pig"))
and inst.components.combat:CanTarget(guy)
and not (inst.components.follower and inst.components.follower.leader == guy)
end)
end
local function FindTargets(guy)
return (guy:HasTag("character") or guy:HasTag("pig"))
and inst.components.combat:CanTarget(guy)
and not (inst.components.follower and inst.components.follower.leader == guy)
end
local function keeptargetfn(inst, target)
return target
and target.components.combat
and target.components.health
and not target.components.health:IsDead()
and not (inst.components.follower and inst.components.follower.leader == target)
end
local function ShouldSleep(inst)
return GetClock():IsDay()
and not (inst.components.combat and inst.components.combat.target)
and not (inst.components.homeseeker and inst.components.homeseeker:HasHome() )
and not (inst.components.burnable and inst.components.burnable:IsBurning() )
and not (inst.components.follower and inst.components.follower.leader)
end
local function ShouldWake(inst)
return GetClock():IsNight()
or (inst.components.combat and inst.components.combat.target)
or (inst.components.homeseeker and inst.components.homeseeker:HasHome() )
or (inst.components.burnable and inst.components.burnable:IsBurning() )
or (inst.components.follower and inst.components.follower.leader)
or (inst:HasTag("spider_warrior") and FindEntity(inst, TUNING.SPIDER_WARRIOR_WAKE_RADIUS, function(...) return FindTargets(inst, ...) end ))
end
local function DoReturn(inst)
if inst.components.homeseeker and inst.components.homeseeker.home and inst.components.homeseeker.home.components.childspawner then
inst.components.homeseeker.home.components.childspawner:GoHome(inst)
end
end
local function StartDay(inst)
if inst:IsAsleep() then
DoReturn(inst)
end
end
local function OnEntitySleep(inst)
if GetClock():IsDay() then
DoReturn(inst)
end
end
local function SummonFriends(inst, attacker)
local den = GetClosestInstWithTag("spiderden",inst, TUNING.SPIDER_SUMMON_WARRIORS_RADIUS)
if den and den.components.combat and den.components.combat.onhitfn then
den.components.combat.onhitfn(den, attacker)
end
end
local function OnAttacked(inst, data)
inst.components.combat:SetTarget(data.attacker)
inst.components.combat:ShareTarget(data.attacker, 30, function(dude)
return dude:HasTag("spider")
and not dude.components.health:IsDead()
and dude.components.follower
and dude.components.follower.leader == inst.components.follower.leader
end, 10)
end
local function WeaponDropped(inst)
inst:Remove()
end
local function MakeWeapon(inst)
if inst.components.inventory then
local weapon = CreateEntity()
weapon.entity:AddTransform()
MakeInventoryPhysics(weapon)
weapon:AddComponent("weapon")
weapon.components.weapon:SetDamage(TUNING.SPIDER_SPITTER_DAMAGE_RANGED)
weapon.components.weapon:SetRange(inst.components.combat.attackrange, inst.components.combat.attackrange+4)
weapon.components.weapon:SetProjectile("spider_web_spit")
weapon:AddComponent("inventoryitem")
weapon.persists = false
weapon.components.inventoryitem:SetOnDroppedFn(function() WeaponDropped(weapon) end)
weapon:AddComponent("equippable")
inst.weapon = weapon
inst.components.inventory:Equip(inst.weapon)
inst.components.inventory:Unequip(EQUIPSLOTS.HANDS)
end
end
local function create_common()
local inst = CreateEntity()
inst:ListenForEvent( "daytime", function(i, data) StartDay( inst ) end, GetWorld())
inst.OnEntitySleep = OnEntitySleep
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
inst.entity:AddLightWatcher()
local shadow = inst.entity:AddDynamicShadow()
shadow:SetSize( 1.5, .5 )
inst.Transform:SetFourFaced()
----------
inst:AddTag("monster")
inst:AddTag("hostile")
inst:AddTag("scarytoprey")
inst:AddTag("canbetrapped")
MakeCharacterPhysics(inst, 10, .5)
inst:AddTag("spider")
inst.AnimState:SetBank("spider")
inst.AnimState:PlayAnimation("idle")
-- locomotor must be constructed before the stategraph!
inst:AddComponent("locomotor")
inst.components.locomotor:SetSlowMultiplier( 1 )
inst.components.locomotor:SetTriggersCreep(false)
inst.components.locomotor.pathcaps = { ignorecreep = true }
inst:SetStateGraph("SGspider")
inst:AddComponent("lootdropper")
inst.components.lootdropper:AddRandomLoot("monstermeat", 1)
inst.components.lootdropper:AddRandomLoot("silk", .5)
inst.components.lootdropper:AddRandomLoot("spidergland", .5)
inst.components.lootdropper.numrandomloot = 1
inst:AddComponent("follower")
---------------------
MakeMediumBurnableCharacter(inst, "body")
MakeMediumFreezableCharacter(inst, "body")
inst.components.burnable.flammability = TUNING.SPIDER_FLAMMABILITY
---------------------
------------------
inst:AddComponent("health")
------------------
inst:AddComponent("combat")
inst.components.combat.hiteffectsymbol = "body"
inst.components.combat:SetKeepTargetFunction(keeptargetfn)
inst.components.combat:SetOnHit(SummonFriends)
inst.components.combat:SetHurtSound("dontstarve/creatures/cavespider/hit_response")
------------------
inst:AddComponent("sleeper")
inst.components.sleeper:SetResistance(2)
inst.components.sleeper:SetSleepTest(ShouldSleep)
inst.components.sleeper:SetWakeTest(ShouldWake)
------------------
inst:AddComponent("knownlocations")
------------------
inst:AddComponent("eater")
inst.components.eater:SetCarnivore()
inst.components.eater:SetCanEatHorrible()
inst.components.eater.strongstomach = true -- can eat monster meat!
------------------
inst:AddComponent("inspectable")
------------------
inst:AddComponent("sanityaura")
inst.components.sanityaura.aura = -TUNING.SANITYAURA_SMALL
local brain = require "brains/spiderbrain"
inst:SetBrain(brain)
inst:ListenForEvent("attacked", OnAttacked)
--inst:ListenForEvent("dusktime", function() StartNight(inst) end, GetWorld())
return inst
end
local function create_hider()
local inst = create_common()
inst.AnimState:SetBank("spider_hider")
inst.AnimState:SetBuild("DS_spider_caves")
--inst:AddTag("spider_warrior")
inst.components.health:SetMaxHealth(TUNING.SPIDER_HIDER_HEALTH)
inst:AddTag("spider_hider")
inst.components.combat:SetDefaultDamage(TUNING.SPIDER_HIDER_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.SPIDER_HIDER_ATTACK_PERIOD)
inst.components.combat:SetRetargetFunction(1, Retarget)
inst.components.locomotor.walkspeed = TUNING.SPIDER_HIDER_WALK_SPEED
inst.components.locomotor.runspeed = TUNING.SPIDER_HIDER_RUN_SPEED
inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED
return inst
end
local function create_spitter()
local inst = create_common()
inst.AnimState:SetBank("spider_spitter")
inst.AnimState:SetBuild("DS_spider2_caves")
inst:AddTag("spider_spitter")
inst:AddComponent("inventory")
inst.components.health:SetMaxHealth(TUNING.SPIDER_SPITTER_HEALTH)
inst.components.combat:SetDefaultDamage(TUNING.SPIDER_SPITTER_DAMAGE_MELEE)
inst.components.combat:SetAttackPeriod(TUNING.SPIDER_SPITTER_ATTACK_PERIOD + math.random()*2)
inst.components.combat:SetRange(TUNING.SPIDER_SPITTER_ATTACK_RANGE, TUNING.SPIDER_SPITTER_HIT_RANGE)
inst.components.combat:SetRetargetFunction(2, Retarget)
inst.components.locomotor.walkspeed = TUNING.SPIDER_SPITTER_WALK_SPEED
inst.components.locomotor.runspeed = TUNING.SPIDER_SPITTER_RUN_SPEED
inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED
MakeWeapon(inst)
return inst
end
local function create_dropper()
local inst = create_common()
inst.AnimState:SetBuild("spider_white")
inst:AddTag("spider_warrior")
inst.components.health:SetMaxHealth(TUNING.SPIDER_WARRIOR_HEALTH)
inst.components.combat:SetDefaultDamage(TUNING.SPIDER_WARRIOR_DAMAGE)
inst.components.combat:SetAttackPeriod(TUNING.SPIDER_WARRIOR_ATTACK_PERIOD + math.random()*2)
inst.components.combat:SetRange(TUNING.SPIDER_WARRIOR_ATTACK_RANGE, TUNING.SPIDER_WARRIOR_HIT_RANGE)
inst.components.combat:SetRetargetFunction(2, Retarget)
inst.components.locomotor.walkspeed = TUNING.SPIDER_WARRIOR_WALK_SPEED
inst.components.locomotor.runspeed = TUNING.SPIDER_WARRIOR_RUN_SPEED
inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED
return inst
end
return Prefab("cave/monsters/spider_hider", create_hider, hiderassets, prefabs),
Prefab("cave/monsters/spider_spitter", create_spitter, spitterassets, prefabs),
Prefab("cave/monsters/spider_dropper", create_dropper, dropperassets, prefabs)
|
local PANEL = class.create("ColorSelector", "Panel")
PANEL:ACCESSOR("ColorButton", "m_pColorButton")
function PANEL:ColorSelector()
self:super()
self.COLORPICKER = self:Add("ColorPicker")
self.COLORPICKER:Dock(DOCK_FILL)
self.COLORPICKER:DockPadding(0,0,0,0)
self.COLORPICKER:DockMargin(0,0,0,0)
self.COLORPICKER:SetBorderColor(color_blank)
self.OPTIONS = self:Add("Panel")
self.OPTIONS:Dock(DOCK_BOTTOM)
self.OPTIONS:SetHeight(28)
self.OPTIONS:DockPadding(0,0,0,0)
self.OPTIONS:DockMargin(0,0,0,0)
self.OPTIONS:SetBorderColor(color_blank)
self.OKAY = self.OPTIONS:Add("ButtonIcon")
self.OKAY:SetImage("textures/gui/disk.png")
self.OKAY:Dock(DOCK_RIGHT)
self.OKAY:SetText("Save")
self.OKAY:SetWidth(64)
self.OKAY.OnClick = function(this)
self:SetVisible(false)
if self.m_pColorButton and self.m_pColorButton.SetColor then
self.m_pColorButton:SetColor(self.COLORPICKER:GetColor())
end
end
self.CANCEL = self.OPTIONS:Add("ButtonIcon")
self.CANCEL:SetImage("textures/gui/cancel.png")
self.CANCEL:Dock(DOCK_RIGHT)
self.CANCEL:SetText("Cancel")
self.CANCEL:SetWidth(76)
self.CANCEL.OnClick = function(this)
self:SetVisible(false)
end
end
function PANEL:SetColor(col)
self.COLORPICKER:SetColor(col)
end
function PANEL:GetColor()
return self.COLORPICKER:GetColor()
end
|
AuctionatorIncrementalScanFrameMixin = {}
local INCREMENTAL_SCAN_EVENTS = {
"AUCTION_HOUSE_BROWSE_RESULTS_ADDED",
"AUCTION_HOUSE_BROWSE_RESULTS_UPDATED"
}
function AuctionatorIncrementalScanFrameMixin:OnLoad()
Auctionator.Debug.Message("AuctionatorIncrementalScanFrameMixin:OnLoad")
self:RegisterForEvents()
end
function AuctionatorIncrementalScanFrameMixin:RegisterForEvents()
Auctionator.Debug.Message("AuctionatorIncrementalScanFrameMixin:RegisterForEvents()")
FrameUtil.RegisterFrameForEvents(self, INCREMENTAL_SCAN_EVENTS)
end
function AuctionatorIncrementalScanFrameMixin:UnregisterForEvents()
Auctionator.Debug.Message("AuctionatorIncrementalScanFrameMixin:UnregisterForEvents()")
FrameUtil.UnregisterFrameForEvents(self, INCREMENTAL_SCAN_EVENTS)
end
function AuctionatorIncrementalScanFrameMixin:OnEvent(event, ...)
if event == "AUCTION_HOUSE_BROWSE_RESULTS_UPDATED" then
self.prices = {} -- New search results so reset prices
self:AddPrices(C_AuctionHouse.GetBrowseResults())
self:NextStep()
elseif event == "AUCTION_HOUSE_BROWSE_RESULTS_ADDED" then
self:AddPrices(...)
self:NextStep()
end
end
function AuctionatorIncrementalScanFrameMixin:AddPrices(results)
Auctionator.Debug.Message("AuctionatorIncrementalScanFrameMixin:AddPrices()", results)
for _, resultInfo in ipairs(results) do
local itemKey = Auctionator.Utilities.ItemKeyFromBrowseResult(resultInfo)
if self.prices[itemKey] == nil then
self.prices[itemKey] = { resultInfo.minPrice }
else
table.insert(self.prices[itemKey], resultInfo.minPrice)
end
end
end
function AuctionatorIncrementalScanFrameMixin:NextStep()
if not C_AuctionHouse.HasFullBrowseResults() then
C_AuctionHouse.RequestMoreBrowseResults()
else
Auctionator.Database.ProcessScan(self.prices)
self.prices = {} --Already processed, so clear
end
end
|
-----------------------------------
-- Area: Port Bastok
-- NPC: Silver Owl
-- Type: Tenshodo Merchant
-- !pos -99.155 4.649 23.292 236
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Port_Bastok/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:hasKeyItem(tpz.ki.TENSHODO_MEMBERS_CARD)) then
if (player:sendGuild(60420, 1, 23, 4)) then
player:showText(npc,ID.text.TENSHODO_SHOP_OPEN_DIALOG);
end
else
player:startEvent(150,1)
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
-- [[ CONSTANTS ]] --
-- These are constants. These are values that may be very useful to use to accomplish a specific task
-- These have no direct involvement with making patterns, hence they belong here and not in "common"
-- Defining some mathematical constants
math.tau = math.pi * 2
math.e = math.exp(1)
math.phi = (1 + 5 ^ 0.5) / 2
SQRT_TWO = math.sqrt(2)
SQRT_THREE = math.sqrt(3)
-- Open Hexagon players, if certain things are causing issues for you please change this value
-- to the refresh rate of your monitor.
REFRESH_RATE = 60
FPS = 60
-- Taken from Omegasphere
-- These are constants to use when you want the rotation speed to match the horizontal speed of
-- curving walls.
CURVE_ROTATION_MULTIPLIER = 10.471975
CURVE_ROTATION_FOCUS = 2.0436
-- [[ ENUMERATORS ]] --
-- These are enumerators. They translate integers into more English vocabulary, making them much
-- easier to memorize over pure integers.
-- Use an enumator such as "EnumeratorName.VALUE" (e.g. KeyCode.LEFT)
-- An enumerator that defines basic movement values for onInput
Movement = {
LEFT = -1,
NONE = 0,
RIGHT = 1
}
-- An enumerator that defines all of the mouse buttons known by the SFML Mouse Button enumerator.
MouseButton = {
LEFT = 0,
RIGHT = 1,
MIDDLE = 2,
XBUTTON_ONE = 3,
XBUTTON_TWO = 4,
BUTTON_COUNT = 5
}
-- An enumerator that defines all of the keycodes that is known by the SFML Key enumerator.
-- Taken from Spyro Oshisaure's Keyboard Helper. Modified by Synth Morxemplum
KeyCode = {
UNKNOWN = -1,
-- Alphabet
A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11,
M = 12, N = 13, O = 14, P = 15, Q = 16, R = 17, S = 18, T = 19, U = 20, V = 21, W = 22,
X = 23, Y = 24, Z = 25,
-- Numbers
ZERO = 26, ONE = 27, TWO = 28, THREE = 29, FOUR = 30, FIVE = 31, SIX = 32, SEVEN = 33,
EIGHT = 34, NINE = 35,
ESCAPE = 36,
LEFT_CONTROL = 37,
LEFT_SHIFT = 38,
LEFT_ALT = 39,
LEFT_SYSTEM = 40,
RIGHT_CONTROL = 41,
RIGHT_SHIFT = 42,
RIGHT_ALT = 43,
RIGHT_SYSTEM = 44,
MENU = 45,
LEFT_BRACKET = 46,
RIGHT_BRACKET = 47,
SEMICOLON = 48,
COMMA = 49,
PERIOD = 50,
QUOTE = 51,
SLASH = 52,
BACKSLASH = 53,
TILDE = 54,
EQUAL = 55,
DASH = 56,
SPACE = 57,
RETURN = 58, ENTER = 58, -- Using both names just in case
BACKSPACE = 59,
TAB = 60,
PAGE_UP = 61,
PAGE_DOWN = 62,
END = 63,
HOME = 64,
INSERT = 65,
DELETE = 66,
ADD = 67,
SUBTRACT = 68,
MULTIPLY = 69,
DIVIDE = 70,
-- Arrow keys
LEFT = 71, RIGHT = 72, UP = 73, DOWN = 74,
-- Numpad
NUMPAD_ZERO = 75, NUMPAD_ONE = 76, NUMPAD_TWO = 77, NUMPAD_THREE = 78,
NUMPAD_FOUR = 79, NUMPAD_FIVE = 80, NUMPAD_SIX = 81, NUMPAD_SEVEN = 82,
NUMPAD_EIGHT = 83, NUMPAD_NINE = 84,
-- Function keys
F1 = 85, F2 = 86, F3 = 87, F4 = 88, F5 = 89, F6 = 90, F7 = 91, F8 = 92, F9 = 93,
F10 = 94, F11 = 95, F12 = 96, F13 = 97, F14 = 98, F15 = 99,
PAUSE = 100,
KEY_COUNT = 101
}
-- [[ UTILITY FUNCTIONS ]] --
-- Additional functions that help simplify certain calculations, including complex mathematical calculations
-- Ordered alphabetically
-- Checks to see if the current version of the game is equal to or greater than the version specified
-- Useful if you are developing a level in a beta branch or GitHub build.
function atRequiredVersion(mMinimumMajor, mMinimumMinor, mMinimumMicro)
return u_getVersionMajor() >= mMinimumMajor and
u_getVersionMinor() >= mMinimumMinor and
u_getVersionMicro() >= mMinimumMicro
end
-- Converts Beats Per Minute (BPM) into period in Frames Per Beat (FPB)
function BPMtoFPB(bpm)
return (FPS * 60)/bpm
end
-- Converts Beats Per Minute (BPM) into period in Seconds Per Beat (SPB)
function BPMtoSPB(bpm)
return 60/bpm
end
-- Clamps a number "input" between two values. The value can not go
-- below min_val and can not go above max_val.
function clamp(input, min_val, max_val)
if input < min_val then
input = min_val
elseif input > max_val then
input = max_val
end
return input
end
-- Helper function for "fromHSV()", which translates from Hue and Saturation
-- to RGB values.
local function fromHS(h, s)
-- Find a color from hue and saturation.
h = (h % 360)/60
local i, f, g, t
i, f = math.modf(h)
g = 1 - f -- For descending gradients
t = 1 - s -- Minimum color intensity based on saturation
f, g = s * f + t, s * g + t -- Apply saturation
if i == 0 then return 1, f, t
elseif i == 1 then return g, 1, t
elseif i == 2 then return t, 1, f
elseif i == 3 then return t, g, 1
elseif i == 4 then return f, t, 1
elseif i == 5 then return 1, t, g
end
return 1, 1, 1 -- Fallback
end
-- Converts HSV color values to RGB color values in a 0 - 255 range (alpha not included).
function fromHSV(h, s, v)
-- All parameters are optional. Hue defaults to 0, Saturation anf value default to 1
h, s, v = type(h) == 'number' and h or 0, type(s) == 'number' and clamp(s, 0, 1) or 1, type(v) == 'number' and clamp(v, 0, 1) or 1
local r, g, b = fromHS(h, s)
r = math.floor(r * v * 255)
g = math.floor(g * v * 255)
b = math.floor(b * v * 255)
return r, g, b
end
-- Returns coordinates (x, y) adjusted with the level rotation using polar coordinate math.
function getAbsolutePosition(x, y)
local r, a = (x ^ 2 + y ^ 2) ^ 0.5, math.atan(y)
a = a + math.rad(l_getRotation())
return r * math.cos(a), r * math.sin(a)
end
-- Takes a number and returns it's sign value.
-- Negatives return -1, positives return 1, and zero returns 0.
function getSign(x)
return x > 0 and 1 or x == 0 and 0 or -1
end
-- A data structure that stores results for prime numbers as a way to "cache" results.
-- This helps make isPrime run faster by knocking out calculations that were already done.
local prime_memoization = {[2] = true, [3] = true, [5] = true, [7] = true, [11] = true, [13] = true}
-- Checks whether an integer is a prime number or not
-- More cursed but more concise and memory efficient
function isPrime(integer)
return integer % 1 == 0 and (prime_memoization[integer] or (function ()
local divisor = 2
while (divisor ^ 2 <= integer) do
if (integer % divisor == 0) then
return false
end
divisor = divisor + 1
end
prime_memoization[integer] = true
return true
end)()) or false
end
-- Inverse linear interpolation function. Takes two number values, initial
-- and final, and then a third number "value". Returns the percentage of
-- "value" between initial and final.
function inverseLerp(initial, final, value)
return (value - initial) / (final - initial)
end
-- Linear interpolation function. Takes number value initial and returns a
-- value that is (i * 100) percent to final value.
-- i is a number value between 0 and 1
function lerp(initial, final, i)
return (1 - i) * initial + i * final
end
-- Prints a table to the console. This includes all key value pairs, and recursively prints out any
-- tables of additional dimensions
-- Formatting of table contents are done with the "whitespace" character.
function printTable(luaTable, whitespace)
whitespace = whitespace or ""
if (type(luaTable) ~= "table") then return end
for k, v in pairs(luaTable) do
print(whitespace..tostring(k), v)
if (type(v) == "table" and v ~= luaTable) then
tablePrint(v, whitespace.."\t")
end
end
end
-- Returns a random value between minimum and maximum, but is a floating point
-- number.
function randomFloat(minimum, maximum)
return u_rndReal() * (maximum - minimum) + minimum
end
-- Takes in a number value and follows true rounding rules.
-- Decimals < .5 will round down, while >= .5 will round up.
function roundFloat(floatingNumber)
return math.floor(floatingNumber + 0.5)
end
-- "Shuffles" an array by swapping elements randomly across a table.
function shuffle(t)
for i = #t, 3, -1 do
local j = u_rndIntUpper(i - 1)
t[i], t[j] = t[j], t[i]
end
end
-- Takes in a number value and rounds the number to places decimal
-- places. Very useful to avoid floating point error.
function simplifyFloat(number, places)
return roundFloat(number * (10 ^ places)) / (10 ^ places)
end
--[[ EASING FUNCTIONS ]]--
-- These are easing functions, which are a special subset of math functions that help with specific transitions.
-- These output values from 0 to 1, and work best when paired with linear interpolation (lerp).
-- All formulas are referenced from easings.net.
-- Sine
function easeInSine(x)
return 1 - math.cos((clamp(x, 0, 1) * math.pi) / 2)
end
function easeInOutSine(x)
return (1 - math.cos(math.pi * clamp(x, 0, 1))) / 2
end
function easeOutSine(x)
return math.sin((clamp(x, 0, 1) * math.pi) / 2)
end
-- Quadratic
function easeInQuad(x)
x = clamp(x, 0, 1)
return x * x
end
function easeInOutQuad(x)
x = clamp(x, 0, 1)
return x < 0.5 and (2 * x * x) or (1 - (-2 * x + 2) ^ 2 / 2)
end
function easeOutQuad(x)
x = 1 - clamp(x, 0, 1)
return 1 - x * x
end
-- Cubic
function easeInCubic(x)
x = clamp(x, 0, 1)
return x * x * x
end
function easeInOutCubic(x)
x = clamp(x, 0, 1)
return x < 0.5 and (4 * x * x * x) or (1 - (-2 * x + 2) ^ 3 / 2)
end
function easeOutCubic(x)
x = 1 - clamp(x, 0, 1)
return 1 - x * x * x
end
-- Quartic
function easeInQuart(x)
x = clamp(x, 0, 1)
return x * x * x * x
end
function easeInOutQuart(x)
x = clamp(x, 0, 1)
return x < 0.5 and (8 * x * x * x * x) or (1 - (-2 * x + 2) ^ 4 / 2)
end
function easeOutQuart(x)
x = 1 - clamp(x, 0, 1)
return 1 - x * x * x * x
end
-- Quintic
function easeInQuint(x)
x = clamp(x, 0, 1)
return x * x * x * x * x
end
function easeInOutQuint(x)
x = clamp(x, 0, 1)
return x < 0.5 and (16 * x * x * x * x * x) or (1 - (-2 * x + 2) ^ 5 / 2)
end
function easeOutQuint(x)
x = 1 - clamp(x, 0, 1)
return 1 - x * x * x * x * x
end
-- Exponential
function easeInExpo(x)
x = clamp(x, 0, 1)
return x == 0 and 0 or 2 ^ (10 * x - 10)
end
function easeInOutExpo(x)
x = clamp(x, 0, 1)
return x < 0.5 and (x == 0 and 0 or 2 ^ (20 * x - 10) / 2) or (x == 1 and 1 or (2 - 2 ^ (-20 * x + 10)) / 2)
end
-- Easings.net has this formula WRONG. This is the actual formula right here.
function easeOutExpo(x)
x = clamp(x, 0, 1)
return x == 1 and 1 or -2 ^ (-10 * x) + 1
end
-- Circle
function easeInCirc(x)
x = clamp(x, 0, 1)
return 1 - math.sqrt(1 - x * x)
end
function easeInOutCirc(x)
x = 2 * clamp(x, 0, 1)
return x < 1 and (1 - math.sqrt(1 - x * x)) / 2 or (math.sqrt(1 - (2 - x) ^ 2) + 1) / 2
end
function easeOutCirc(x)
x = 1 - clamp(x, 0, 1)
return math.sqrt(1 - x * x)
end
-- Back Functions
local BACK_CONST_ONE = 1.70158
local BACK_CONST_TWO = BACK_CONST_ONE * 1.525
local BACK_CONST_THREE = BACK_CONST_ONE + 1
function easeInBack(x)
x = clamp(x, 0, 1)
return BACK_CONST_THREE * x * x * x - BACK_CONST_ONE * x * x
end
function easeInOutBack(x)
x = 2 * clamp(x, 0, 1)
return x < 1 and (x * x * ((BACK_CONST_TWO + 1) * x - BACK_CONST_TWO)) / 2 or ((x - 2) ^ 2 * ((BACK_CONST_TWO + 1) * (x - 2) + BACK_CONST_TWO) + 2) / 2
end
function easeOutBack(x)
x = clamp(x, 0, 1) - 1
return 1 + BACK_CONST_THREE * x * x * x + BACK_CONST_ONE * x * x
end
-- Elastic
local ELASTIC_CONST_ONE = math.tau / 3
local ELASTIC_CONST_TWO = ELASTIC_CONST_ONE / 1.5
function easeInElastic(x)
x = 10 * clamp(x, 0, 1)
return x == 0 and 0 or (x == 10 and 1 or -(2 ^ (x - 10)) * math.sin((x - 10.75) * ELASTIC_CONST_ONE))
end
function easeInOutElastic(x)
x = 20 * clamp(x, 0, 1)
return x < 10 and (x == 0 and 0 or -(2 ^ (x - 10)) * math.sin((x - 11.125) * ELASTIC_CONST_TWO) / 2) or (x == 20 and 1 or 2 ^ (-x + 10) * math.sin((x - 11.125) * ELASTIC_CONST_TWO) / 2 + 1)
end
function easeOutElastic(x)
x = 10 * clamp(x, 0, 1)
return x == 0 and 0 or (x == 10 and 1 or 2 ^ (-x) * math.sin((x - 0.75) * ELASTIC_CONST_ONE) + 1)
end
-- Bounce
-- Okay. Easings.net has this completely wrong here. Their implementation is garbage.
-- This is a much better implementation (Thanks Oshisaure)
function easeInBounce(x, bounceFactor)
bounceFactor = bounceFactor or 1 -- Optional parameter
x = clamp(x, 0, 1)
return x == 0 and 0 or math.abs(math.cos(bounceFactor * (1 - 1 / x) * math.pi) * math.sin(x * math.pi / 2) ^ 2)
end
function easeInOutBounce(x)
x = clamp(x, 0, 1)
return x < 0.5 and easeInBounce(x) or easeOutBounce(x)
end
function easeOutBounce(x, bounceFactor)
x = clamp(x, 0, 1)
return x == 1 and 1 or -easeInBounce(1 - x, bounceFactor) + 1
end
-- From: https://stackoverflow.com/questions/12394841/
function ArrayRemoveIf(t, fnRemove)
local j, n = 1, #t
for i=1,n do
if (not fnRemove(t, i, j)) then
-- Move i's kept value to j's position, if it's not already there.
if (i ~= j) then
t[j] = t[i]
t[i] = nil
end
j = j + 1 -- Increment position of where we'll place the next kept value.
else
t[i] = nil
end
end
return t
end
function getBPMToBeatPulseDelay(bpm)
return 3600 / bpm
end
function getMusicDMSyncFactor()
return u_getDifficultyMult() ^ 0.12
end
|
Task.Wait()
Events.Broadcast("Minimap.AddItem",script.parent,"CE4C796C320F612C:TestMiniMapImage",nil)
|
local API = {}
API.FindDepthOfFieldObject = function()
local allSmartObjects = World.FindObjectsByType("SmartObject")
for _,obj in ipairs(allSmartObjects) do
local objProperties = obj:GetSmartProperties()
local propCount = 0
for key, value in pairs (objProperties) do
--print("[" .. obj.name .. "] smart property: " .. key)
if key == "Depth Blur Radius"
or key == "Focus Object"
or key == "Focal Distance" then
propCount = propCount + 1
end
end
if propCount == 3 then
return obj
end
end
end
return API
|
local ffi = require("ffi")
local pkt = require("packet")
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local stats = require "stats"
local pipe = require "pipe"
local percg = require "proto.percg"
local percc1 = require "proto.percc1"
local eth = require "proto.ethernet"
local pcap = require "pcap"
local perc_constants = require "examples.perc.constants"
local monitor = require "examples.perc.monitor"
local ipc = require "examples.perc.ipc"
local Link1 = require "examples.perc.perc_link"
local CONTROL_PACKET_SIZE = perc_constants.CONTROL_PACKET_SIZE
local ff64 = 0xFFFFFFFFFFFFFFFF
control2Mod = {}
ffi.cdef [[
typedef struct {
double currentRate, nextRate;
double changeTime;
bool valid;
} rateInfo;
]]
-- handles flow start messages from applications - to send first control, assign a free queue for data
-- handles flow completion message from "data slave", sends exit packet to free up bandwidth, reclaims queue
-- receives control packets on rx queue, computes new bottleneck info and sends out new packets
-- adjusts rates of data queues based on rxd control packets
-- TODO(lav)
-- can we make it even simpler, example rx some packets, modify them to get
-- packets to send (or drop), and add new packets for new flows.
-- and tx
-- then fetch new flows list and completed flows list.
function control2Mod.warn(str)
if perc_constants.WARN_CONTROL then
print("control2.lua warn: " .. str)
end
end
function control2Mod.log(str)
if perc_constants.LOG_CONTROL then
print(str)
end
end
function control2Mod.postProcessTiming(pkt, now, monitorPipe)
-- if this is a packet about to be sent out from source
-- check for old time in payload
local nowUs = now * 1e6
local startTimeUs = pkt.payload.uint64[0]
local complement = pkt.payload.uint64[1]
assert(bit.band(ff64, startTimeUs) == complement)
assert(startTimeUs > 0)
-- sample RTTs of some packets
if monitorPipe ~= nil and nowUs % 100 < monitor.constControlSamplePc then
local diff = nowUs - startTimeUs
--print("Pkt took " .. tostring(diff) .. " us.")
monitorPipe:send(
ffi.new("genericMsg",
{["valid"]= 1234,
["time"]= now,
["msgType"]= monitor.typeControlPacketRtt,
["i1"]= diff}))
end
pkt.payload.uint64[0] = nowUs
pkt.payload.uint64[1] = bit.band(ff64, nowUs)
-- compare with new time and log RTT
-- if this is a packet about to be sent out from receiver
-- do nothing
end
function control2Mod.postProcessTimingNew(pkt, now)
-- if this is a packet about to be sent out from source
-- check for old time in payload
-- compare with new time and log RTT
-- if this is a packet about to be sent out from receiver
-- do nothing
local nowUs = now * 1e6
local startTimeUs = pkt.payload.uint64[0]
-- TODO(lav): assertion fails probably cuz we get a used packet
-- assert(startTimeUs == 0)
--local diff = now - startTime
pkt.payload.uint64[0] = nowUs
pkt.payload.uint64[1] = bit.band(ff64, nowUs)
print("Pkt stamped with " .. tostring(nowUs) .. " us.")
end
function control2Mod.percc1ProcessAndGetRate(pkt)
local tmp = pkt.percg:getDestination()
pkt.percg:setDestination(pkt.percg:getSource())
pkt.percg:setSource(tmp)
-- get maxHops, then smallest index, two rates
local maxHops = pkt.percc1:getHop()
if (pkt.percc1:getIsForward() ~= percc1.IS_FORWARD) then
maxHops = pkt.percc1:getMaxHops()
end
local bnInfo = pkt.percc1:getBottleneckInfo(maxHops)
local bnRate1, bnRate2 = bnInfo.bnRate1, bnInfo.bnRate2
local bnBitmap = bnInfo.bnBitmap
-- control2Mod.log("At end host "
-- .. "\n bottleneck rates are " .. bnRate1 .. " and " .. bnRate2
-- .. "\n maxHops was " .. maxHops
-- .. "\n bottleneck links are ..")
-- for i=1,maxHops do
-- if bnBitmap[i] == 1 then control2Mod.log(i .. " ") end
-- end
-- control2Mod.log(" setting rates etc. now")
assert(bnRate1 ~= nil)
assert(bnRate2 ~= nil)
assert(bnBitmap ~= nil)
-- then set rate at each index
-- and unsat/ sat at each index
--pkt.percg:setRatesAndLabelGivenBottleneck(rate, hop, maxHops)
for i=1,maxHops do
pkt.percc1:setOldLabel(i, pkt.percc1:getNewLabel(i))
pkt.percc1:setOldRate(i, pkt.percc1:getNewRate(i))
if bnBitmap[i] ~= 1 then
pkt.percc1:setNewLabel(i, percc1.LABEL_SAT)
pkt.percc1:setNewRate(i, bnRate1)
-- control2Mod.log("setting new rate of " .. i
-- .. " to " .. bnRate1)
else
pkt.percc1:setNewLabel(i, percc1.LABEL_UNSAT)
pkt.percc1:setNewRate(i, bnRate2)
-- control2Mod.log("setting new rate of " .. i
-- .. " to " .. bnRate2)
end
end -- for i=1,maxHops
pkt.percc1:setMaxHops(maxHops) -- and hop is the same
if (pkt.percc1:getIsForward() ~= percc1.IS_FORWARD) then
--control2Mod.log("marking packet as forward")
pkt.percc1:setIsForward(percc1.IS_FORWARD)
else
--control2Mod.log("marking packet as reverse")
pkt.percc1:setIsForward(percc1.IS_NOT_FORWARD)
end -- if (pkt.percc1:getIsForward() ..
return bnRate1
end
function initializePercc1Packet(buf)
buf:getPercc1Packet():fill{
pktLength = CONTROL_PACKET_SIZE,
percgSource = 0,
percgDestination = 1, -- TO CHANGE
percgFlowId = 0, -- TO CHANGE
percgIsData = percg.PROTO_CONTROL,
percc1IsForward = percc1.IS_FORWARD,
percc1IsExit = percc1.IS_NOT_EXIT,
percc1Hop = 0,
percc1MaxHops = 0,
ethSrc = 0,
ethDst = "10:11:12:13:14:15",
ethType = eth.TYPE_PERCG}
end
function control2Mod.controlSlave(dev, pipes, readyInfo, monitorPipe)
local thisCore = dpdk.getCore()
control2Mod.log("Running control slave on core " .. thisCore)
local egressLink = Link1:new()
local mem = memory.createMemPool()
local lastRxTime = 0
local lastTxTime = 0
local rxQueue = dev:getRxQueue(perc_constants.CONTROL_RXQUEUE)
assert(rxQueue ~= nil)
local txQueue = dev:getTxQueue(perc_constants.CONTROL_TXQUEUE)
assert(txQueue ~= nil)
local freeQueues = {}
-- what I really need is just flow id -> queue and queue -> config + flowId
local queues = {}
local queueRates = ffi.new("rateInfo[?]", 129)
-- all but tx 1 for data
for i=1, perc_constants.MAX_QUEUES do
if i ~= perc_constants.CONTROL_TXQUEUE
and i ~= perc_constants.ACK_TXQUEUE
and i ~= perc_constants.DROP_QUEUE then
table.insert(freeQueues, i)
end
queueRates[i].currentRate = 1
queueRates[i].nextRate = -1
queueRates[i].changeTime = -1
queueRates[i].valid = false
end
local pendingChangeRate = {}
local bufs = memory.bufArray()
-- to rx packets and modify and tx
local newBufs = mem:bufArray(
perc_constants.NEW_FLOWS_PER_CONTROL_LOOP)
-- for packets sent out for new flows
-- only 2 mbufs at a time since I'm
-- not expecting more than two new flows in a ~150us loop
local noNewPackets = 0
local lastPeriodic = dpdk.getTime()
local numLoopsSinceStart = 0
local lastLoggedDpdkLoopStartTime = 0
local numTxNewControlPacketsSinceLog = 0
local numTxOngoingControlPacketsSinceLog = 0
local numRxControlPacketsSinceLog = 0
ipc.waitTillReady(readyInfo)
control2Mod.log("ready to start control2")
while dpdk.running() do
local dpdkLoopStartTime = dpdk.getTime()
numLoopsSinceStart = numLoopsSinceStart + 1
if monitorPipe ~= nil and numLoopsSinceStart % monitor.constControlNumLoops == 0 then
monitorPipe:send(
ffi.new("genericMsg",
{["valid"]= 1234,
["time"]= dpdkLoopStartTime,
["msgType"]= monitor.typeControlStatsPerDpdkLoop,
["d1"]= (dpdkLoopStartTime
- lastLoggedDpdkLoopStartTime),
["d2"]= numTxNewControlPacketsSinceLog,
["i1"]= numTxOngoingPacketsSinceLog,
["i2"]= numRxControlPacketsSinceLog}))
numTxNewControlPacketsSinceLog = 0
numTxOngoingControlPacketsSinceLog = 0
numRxControlPacketsSinceLog = 0
lastLoggedDpdkLoopStartTime = dpdkLoopStartTime
end
-- log actual data rates of all active queues every PERIOD
if dpdkLoopStartTime > lastPeriodic + perc_constants.LOG_EVERY_N_SECONDS then
lastPeriodic = dpdkLoopStartTime
for flowId, queueNo in pairs(queues) do
assert(queueRates[queueNo].valid)
local rateInfo = queueRates[queueNo]
local dTxQueue = dev:getTxQueue(queueNo)
local configuredRate = rateInfo.currentRate
local actualRate = dTxQueue:getTxRate()
if monitorPipe ~= nil then
monitorPipe:send(
ffi.new("genericMsg",
{["i1"]= flowId,
["d1"]= configuredRate,
["d2"]= actualRate,
["valid"]= 1234,
["msgType"]= monitor.typeFlowTxRateConfigured,
["time"]= lastPeriodic,
["loop"]= numLoopsSinceStart
}))
end
end
end
-- echoes received packets
do
local rx = rxQueue:tryRecv(bufs, 128)
numRxControlPacketsSinceLog = numRxControlPacketsSinceLog + rx
local now = dpdk.getTime()
for i = 1, rx do
local pkt = bufs[i]:getPercc1Packet()
pkt.percc1:doNtoh()
-- if (i==1) then
-- print(readyInfo.id .. " got packet addressed to ethDst "
-- .. pkt.eth:getDst()) end
-- ingress link processing for reverse packets
if pkt.percc1:getIsForward() == percc1.IS_NOT_FORWARD then
control2Mod.log("\nRx-ing FlowId " .. pkt.percg:getFlowId()
.. " before ingress processing "
.. "\n" .. pkt.percg:getString()
.. "\n " .. pkt.percc1:getString())
egressLink:processPercc1Packet(pkt)
control2Mod.log("\nRx-ing FlowId " .. pkt.percg:getFlowId()
.. " after ingress processing "
.. "\n" .. pkt.percg:getString()
.. "\n " .. pkt.percc1:getString())
end
local tmp = pkt.eth:getDst()
pkt.eth:setDst(pkt.eth:getSrc())
pkt.eth:setSrc(tmp)
-- handle differently at receiver and source
-- receiver simply processes and echoes, FIN or not
if pkt.percc1:getIsForward() == percc1.IS_FORWARD then
local flowId = pkt.percg:getFlowId()
assert(flowId >= 100)
--control2Mod.log("rx control gets pkt for flow " .. pkt.percg:getFlowId())
control2Mod.percc1ProcessAndGetRate(pkt)
if (pkt.percc1:getIsExit() == percc1.IS_EXIT) then
local ethType = pkt.eth:getType()
control2Mod.log("Flow " .. flowId
.. " " .. readyInfo.id
.. " received exit packet (marked fwd)"
.. " ethType is " .. ethType .. " vs DROP "
.. eth.TYPE_DROP
.. " leave unchanged and echo back")
end
else
local flowId = pkt.percg:getFlowId()
assert(flowId >= 100)
-- source doesn't reply to FIN
-- will set FIN for flows that ended
-- will update rates otherwise
if pkt.percc1:getIsExit() == percc1.IS_EXIT then -- receiver echoed fin
control2Mod.log("tx control gets exit pkt for flow " .. pkt.percg:getFlowId())
control2Mod.log("Flow " .. flowId
.. " " .. readyInfo.id .. " received exit packet (marked not fwd)"
.. " ethType is " .. pkt.eth:getType()
.. " set to DROP " .. eth.TYPE_DROP)
pkt.eth:setType(eth.TYPE_DROP)
elseif queues[flowId] == nil then -- flow ended
control2Mod.log("tx control gets regular pkt for no-more-data flow " .. pkt.percg:getFlowId())
control2Mod.percc1ProcessAndGetRate(pkt)
control2Mod.postProcessTiming(pkt, now, monitorPipe)
assert(pkt.percc1:getIsForward() == percc1.IS_FORWARD)
pkt.percc1:setIsExit(percc1.IS_EXIT)
else -- flow hasn't ended yet, update rates
control2Mod.log("tx control gets regular pkt for have-more-data flow " .. pkt.percg:getFlowId())
local rate1 = control2Mod.percc1ProcessAndGetRate(pkt)
control2Mod.postProcessTiming(pkt, now, monitorPipe)
if monitorPipe ~= nil then
monitorPipe:send(
ffi.new("genericMsg",
{["i1"]= flowId,
["d1"]= rate1,
["valid"]= 1234,
["msgType"]= monitor.typeGetFlowBottleneckRate,
["time"]= now,
["loop"]= numLoopsSinceStart
}))
end
assert(pkt.percc1:getIsForward() == percc1.IS_FORWARD)
assert(rate1 ~= nil)
local queueNo = queues[flowId]
control2Mod.log("flow was assigned queue " .. queueNo)
assert(queueNo ~= nil)
local rateInfo = queueRates[queueNo]
-- should setup with queue
-- initilize to current = 0, next, changeTime = nil
assert(queueRates[queueNo].valid)
assert(rateInfo.currentRate >= 0)
if rate1 ~= rateInfo.currentRate then
if rate1 < rateInfo.currentRate then
control2Mod.log("Flow " .. flowId
.. " received bottleneck rate " .. rate1
.. " is smaller than current " .. rateInfo.currentRate
.. " actually " .. dev:getTxQueue(queueNo):getTxRate())
rateInfo.currentRate = rate1
rateInfo.nextRate = -1
rateInfo.changeTime = -1
local dTxQueue = dev:getTxQueue(queueNo)
local configuredRate = rate1
if rate1 > percc1.RATE_TEN_GBPS then
rateInfo.currentRate = 500
configuredRate = 500
control2Mod.warn("received bottleneck rate > link cap, set to 500 Mb/s")
end
dTxQueue:setRate(configuredRate)
if monitorPipe ~= nil then
monitorPipe:send(
ffi.new("genericMsg",
{["i1"]= flowId,
["d1"]= configuredRate,
["valid"]= 1234,
["msgType"]= monitor.typeSetFlowTxRate,
["time"]= now,
["loop"]= numLoopsSinceStart
}))
end
else -- rate1 > rateInfo[0].currentRate
control2Mod.log(" new rate " .. rate1 .. " is bigger than current " .. rateInfo.currentRate)
if rateInfo.nextRate == -1 then
rateInfo.nextRate = rate1
rateInfo.changeTime = now + 100e-6
control2Mod.log("Flow " .. flowId
.. " received bottleneck rate " .. rate1
.. " is bigger than current rate."
.. " No next rate scheduled, setting next rate to " .. rate1
.. ", change at " .. rateInfo.changeTime .. "s ")
elseif rateInfo.nextRate == rate1 then
control2Mod.log(" next rate is the same as new rate, do nothing")
elseif rateInfo.nextRate >= 0 and rate1 < rateInfo.nextRate then
control2Mod.log("Flow " .. flowId
.. " received bottleneck rate " .. rate1
.. " is bigger than current rate "
.. " and smaller than next rate " .. rateInfo.nextRate)
rateInfo.nextRate = rate1
-- leave changeTime as is
else -- rate1 > rateInfo.nextRate
control2Mod.log("Flow " .. flowId
.. " received bottleneck rate " .. rate1
.. " is bigger than current rate "
.. " also bigger than next rate " .. rateInfo.nextRate
.. ", change at " .. now + 100e-6 .. "s ")
rateInfo.nextRate = rate1
rateInfo.changeTime = now + 100e-6
-- reset changeTime
end -- if rate1 < current else if etc. etc.
end
end -- if rate1 is different from current (rate update?)
end -- if pkt.percg.getIsExit ..(fin/ last/ echo?)
assert(pkt.percc1:getIsForward() == percc1.IS_FORWARD
or pkt.eth:getType() == eth.TYPE_DROP)
end -- if packet is forward .. (receiver/ source?)
-- egress link processing after sending out forward packets
if (pkt.eth:getType() ~= eth.TYPE_DROP and
pkt.percc1:getIsForward() == percc1.IS_FORWARD) then
control2Mod.log("\nTx-ing FlowId " .. pkt.percg:getFlowId()
.. " before egress processing "
.. "\n" .. pkt.percg:getString()
.. "\n " .. pkt.percc1:getString())
egressLink:processPercc1Packet(pkt)
control2Mod.log("\nTx-ing FlowId " .. pkt.percg:getFlowId()
.. " after egress processing "
.. "\n" .. pkt.percg:getString()
.. "\n " .. pkt.percc1:getString())
end
pkt.percc1:doHton()
end -- for i = 1, rx
txQueue:sendN(bufs, rx)
numTxOngoingControlPacketsSinceLog = numTxOngoingControlPacketsSinceLog + rx
end -- do ECHOES RECEIVED PACKETS
do -- MAKES NEW PACKETS
-- makes new packets
local now = dpdk.getTime()
local msgs = ipc.fastAcceptMsgs(
pipes, "fastPipeAppToControlStart",
"pFacStartMsg", 20)
if next(msgs) ~= nil then
newBufs:alloc(CONTROL_PACKET_SIZE)
-- get two mbufs from the pool,
-- these were initialized, freed once
-- so fields should have default values
noNewPackets = 0
control2Mod.log("make new packets")
local numNew = 0
for msgNo, msg in pairs(msgs) do
-- control2Mod.log("msg.flow " .. msg.flow .. ", msg.size " .. msg.size .. ", msg.destination " .. msg.destination)
-- get a queue and queueRates state
assert(next(freeQueues) ~= nil) -- TODO()
if next(freeQueues) ~= nil then
local flowId = msg.flow
assert(flowId ~= nil)
assert(flowId >= 100)
assert(queues[flowId] == nil)
local queue = table.remove(freeQueues)
assert(queue ~= nil)
queues[flowId] = queue
queueRates[queue].valid = true
queueRates[queue].currentRate = 1
local configuredRate = queueRates[queue].currentRate
local dTxQueue = dev:getTxQueue(queue)
dTxQueue:setRate(configuredRate)
if monitorPipe ~= nil then
monitorPipe:send(
ffi.new("genericMsg",
{["i1"]= flowId,
["d1"]= configuredRate,
["valid"]= 1234,
["msgType"]= monitor.typeSetFlowTxRate,
["time"]= now,
["loop"]= numLoopsSinceStart
}))
end
control2Mod.log("assigned a rateInfo struct for " .. flowId)
-- newBufs has only so many mbufs
assert(numNew <=
perc_constants.NEW_FLOWS_PER_CONTROL_LOOP)
numNew = numNew + 1
-- tell data thread
control2Mod.log("telling data thread to start flow"
.. msg.flow .. " of size "
.. msg.size .. " packets "
.." from queue " .. queue)
ipc.sendFcdStartMsg(pipes, msg.flow,
msg.destination,
msg.size, queue)
-- TODO(lav): remove after fixing the uninit. mbuf bug
initializePercc1Packet(newBufs[numNew]) -- re-initialized
local pkt = newBufs[numNew]:getPercc1Packet()
pkt.percg:setSource(readyInfo.id)
-- sanity checking that fields have default values
assert(pkt.percc1:getNumUnsat(1) == 0)
assert(pkt.percc1:getNumUnsat(2) == 0)
assert(flowId >= 100)
pkt.percg:setFlowId(flowId)
pkt.percg:setDestination(msg.destination)
pkt.eth:setDst(0x111111111111)
control2Mod.postProcessTimingNew(pkt, now)
-- egress link processing after sending out
-- forward packets
if (pkt.eth:getType() ~= eth.TYPE_DROP and
pkt.percc1:getIsForward() == percc1.IS_FORWARD) then
control2Mod.log("\nTx-ing #1! FlowId "
.. pkt.percg:getFlowId()
.. " before egress processing "
.. "\n" .. pkt.percg:getString()
.. "\n "
.. pkt.percc1:getString())
egressLink:processPercc1Packet(pkt)
control2Mod.log("\nTx-ing #1! FlowId "
.. pkt.percg:getFlowId()
.. " after egress processing "
.. "\n" .. pkt.percg:getString()
.. "\n "
.. pkt.percc1:getString())
end
pkt.percc1:doHton()
-- everything else is default for new packet
end -- if next(freeQueues)..
end -- for msgNo, msg..
txQueue:sendN(newBufs, numNew)
numTxNewControlPacketsSinceLog = numTxNewControlPacketsSinceLog + numNew
control2Mod.log("Sent " .. numNew .. " new packets")
else
noNewPackets = noNewPackets + 1
if (noNewPackets % 100000 == 0) then
control2Mod.log("No new packets: " .. noNewPackets .. " at time " .. dpdk.getTime())
end
end -- if msgs ~= nil
end
do -- DEALLOCATE QUEUES
-- deallocates queues for completed flows
local msgs =
ipc.fastAcceptMsgs(
pipes, "fastPipeDataToControlFinAck",
"pFdcFinAckMsg", 20) --ipc.acceptFdcEndMsgs(pipes)
if next(msgs) ~= nil then
control2Mod.log("deallocate queues from completed flows")
for msgNo, msg in pairs(msgs) do
local flowId = msg.flow
assert(flowId >= 100)
local queueNo = queues[flowId]
assert(queueNo ~= nil)
queueRates[queueNo].valid = false
queueRates[queueNo].currentRate = 1
queueRates[queueNo].nextRate = -1
queueRates[queueNo].changeTime = -1
table.insert(freeQueues, queueNo)
queues[flowId] = nil
if monitorPipe ~= nil then
monitorPipe:send(
ffi.new("genericMsg",
{["i1"]= flowId,
["d1"]= 0, -- aka deallocate
["valid"]= 1234,
["msgType"]= monitor.typeSetFlowTxRate,
["time"]= now,
["loop"]= numLoopsSinceStart
}))
end
-- TODO(lav) : too many nows, maybe number them
ipc.sendFcaFinAckMsg(pipes, msg.flow, msg.size,
msg.endTime)
--ipc.sendFcaFinMsg(pipes, msg.flow, msg.endTime)
-- control2Mod.log("deallocated queue " .. queueNo .. " for flow " .. flowId)
end
end
end -- do DEALLOCATE QUEUES
do -- CHANGE RATES
-- change rates of active flows if it's time
local now = dpdk.getTime()
for flowId, queueNo in pairs(queues) do
assert(queueRates[queueNo].valid)
if queueRates[queueNo].changeTime ~= -1
and queueRates[queueNo].changeTime <= now then
control2Mod.log("change rates for flow " .. flowId
.. ", queue " .. queueNo
.. " from " ..
queueRates[queueNo].currentRate
.. " to "
.. queueRates[queueNo].nextRate)
queueRates[queueNo].currentRate
= queueRates[queueNo].nextRate
queueRates[queueNo].nextRate = -1
queueRates[queueNo].changeTime = -1
local configuredRate = queueRates[queueNo].currentRate
if configuredRate > percc1.RATE_TEN_GBPS then
queueRates[queueNo].currentRate = 500
configuredRate = 500
control2Mod.warn("had received bottleneck rate > link cap, set to 500 Mb/s")
end
local dTxQueue = dev:getTxQueue(queueNo)
dTxQueue:setRate(configuredRate)
if monitorPipe ~= nil then
monitorPipe:send(
ffi.new("genericMsg",
{["i1"]= flowId,
["d1"]= configuredRate,
["valid"]= 1234,
["msgType"]= monitor.typeSetFlowTxRate,
["time"]= now,
["loop"]= numLoopsSinceStart
}))
end
end -- if rateInfo[0].changeTime ~= nil ..
end -- for queueNo, ..
end
end -- while dpdk.running()
dpdk.sleepMillis(5000)
end
return control2Mod
|
-- FreeBSD types
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local function init(types)
local abi = require "syscall.abi"
local t, pt, s, ctypes = types.t, types.pt, types.s, types.ctypes
local ffi = require "ffi"
local bit = require "syscall.bit"
local h = require "syscall.helpers"
local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2
local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn
= h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn
local ntohl, ntohl, ntohs, htons, octal = h.ntohl, h.ntohl, h.ntohs, h.htons, h.octal
local c = require "syscall.freebsd.constants"
local mt = {} -- metatables
local addtypes = {
}
local addstructs = {
fiodgname_arg = "struct fiodgname_arg",
}
for k, v in pairs(addtypes) do addtype(types, k, v) end
for k, v in pairs(addstructs) do addtype(types, k, v, lenmt) end
-- 32 bit dev_t, 24 bit minor, 8 bit major, but minor is a cookie and neither really used just legacy
local function makedev(major, minor)
if type(major) == "table" then major, minor = major[1], major[2] end
local dev = major or 0
if minor then dev = bit.bor(minor, bit.lshift(major, 8)) end
return dev
end
mt.device = {
index = {
major = function(dev) return bit.bor(bit.band(bit.rshift(dev.dev, 8), 0xff)) end,
minor = function(dev) return bit.band(dev.dev, 0xffff00ff) end,
device = function(dev) return tonumber(dev.dev) end,
},
newindex = {
device = function(dev, major, minor) dev.dev = makedev(major, minor) end,
},
__new = function(tp, major, minor)
return ffi.new(tp, makedev(major, minor))
end,
}
addtype(types, "device", "struct {dev_t dev;}", mt.device)
mt.stat = {
index = {
dev = function(st) return t.device(st.st_dev) end,
mode = function(st) return st.st_mode end,
ino = function(st) return tonumber(st.st_ino) end,
nlink = function(st) return st.st_nlink end,
uid = function(st) return st.st_uid end,
gid = function(st) return st.st_gid end,
rdev = function(st) return t.device(st.st_rdev) end,
atime = function(st) return st.st_atim.time end,
ctime = function(st) return st.st_ctim.time end,
mtime = function(st) return st.st_mtim.time end,
birthtime = function(st) return st.st_birthtim.time end,
size = function(st) return tonumber(st.st_size) end,
blocks = function(st) return tonumber(st.st_blocks) end,
blksize = function(st) return tonumber(st.st_blksize) end,
flags = function(st) return st.st_flags end,
gen = function(st) return st.st_gen end,
type = function(st) return bit.band(st.st_mode, c.S_I.FMT) end,
todt = function(st) return bit.rshift(st.type, 12) end,
isreg = function(st) return st.type == c.S_I.FREG end,
isdir = function(st) return st.type == c.S_I.FDIR end,
ischr = function(st) return st.type == c.S_I.FCHR end,
isblk = function(st) return st.type == c.S_I.FBLK end,
isfifo = function(st) return st.type == c.S_I.FIFO end,
islnk = function(st) return st.type == c.S_I.FLNK end,
issock = function(st) return st.type == c.S_I.FSOCK end,
iswht = function(st) return st.type == c.S_I.FWHT end,
},
}
-- add some friendlier names to stat, also for luafilesystem compatibility
mt.stat.index.access = mt.stat.index.atime
mt.stat.index.modification = mt.stat.index.mtime
mt.stat.index.change = mt.stat.index.ctime
local namemap = {
file = mt.stat.index.isreg,
directory = mt.stat.index.isdir,
link = mt.stat.index.islnk,
socket = mt.stat.index.issock,
["char device"] = mt.stat.index.ischr,
["block device"] = mt.stat.index.isblk,
["named pipe"] = mt.stat.index.isfifo,
}
mt.stat.index.typename = function(st)
for k, v in pairs(namemap) do if v(st) then return k end end
return "other"
end
addtype(types, "stat", "struct stat", mt.stat)
mt.flock = {
index = {
type = function(self) return self.l_type end,
whence = function(self) return self.l_whence end,
start = function(self) return self.l_start end,
len = function(self) return self.l_len end,
pid = function(self) return self.l_pid end,
sysid = function(self) return self.l_sysid end,
},
newindex = {
type = function(self, v) self.l_type = c.FCNTL_LOCK[v] end,
whence = function(self, v) self.l_whence = c.SEEK[v] end,
start = function(self, v) self.l_start = v end,
len = function(self, v) self.l_len = v end,
pid = function(self, v) self.l_pid = v end,
sysid = function(self, v) self.l_sysid = v end,
},
__new = newfn,
}
addtype(types, "flock", "struct flock", mt.flock)
mt.dirent = {
index = {
fileno = function(self) return tonumber(self.d_fileno) end,
reclen = function(self) return self.d_reclen end,
namlen = function(self) return self.d_namlen end,
type = function(self) return self.d_type end,
name = function(self) return ffi.string(self.d_name, self.d_namlen) end,
toif = function(self) return bit.lshift(self.d_type, 12) end, -- convert to stat types
},
__len = function(self) return self.d_reclen end,
}
mt.dirent.index.ino = mt.dirent.index.fileno -- alternate name
-- TODO previously this allowed lower case values, but this static version does not
-- could add mt.dirent.index[tolower(k)] = mt.dirent.index[k] but need to do consistently elsewhere
for k, v in pairs(c.DT) do
mt.dirent.index[k] = function(self) return self.type == v end
end
addtype(types, "dirent", "struct dirent", mt.dirent)
mt.fdset = {
index = {
fds_bits = function(self) return self.__fds_bits end,
},
}
addtype(types, "fdset", "fd_set", mt.fdset)
mt.cap_rights = {
-- TODO
}
addtype(types, "cap_rights", "cap_rights_t", mt.cap_rights)
-- TODO see Linux notes. Also maybe can be shared with BSDs, have not checked properly
-- TODO also remove WIF prefixes.
mt.wait = {
__index = function(w, k)
local _WSTATUS = bit.band(w.status, octal("0177"))
local _WSTOPPED = octal("0177")
local WTERMSIG = _WSTATUS
local EXITSTATUS = bit.band(bit.rshift(w.status, 8), 0xff)
local WIFEXITED = (_WSTATUS == 0)
local tab = {
WIFEXITED = WIFEXITED,
WIFSTOPPED = bit.band(w.status, 0xff) == _WSTOPPED,
WIFSIGNALED = _WSTATUS ~= _WSTOPPED and _WSTATUS ~= 0
}
if tab.WIFEXITED then tab.EXITSTATUS = EXITSTATUS end
if tab.WIFSTOPPED then tab.WSTOPSIG = EXITSTATUS end
if tab.WIFSIGNALED then tab.WTERMSIG = WTERMSIG end
if tab[k] then return tab[k] end
local uc = 'W' .. k:upper()
if tab[uc] then return tab[uc] end
end
}
function t.waitstatus(status)
return setmetatable({status = status}, mt.wait)
end
mt.siginfo = {
index = {
signo = function(s) return s.si_signo end,
errno = function(s) return s.si_errno end,
code = function(s) return s.si_code end,
pid = function(s) return s.si_pid end,
uid = function(s) return s.si_uid end,
status = function(s) return s.si_status end,
addr = function(s) return s.si_addr end,
value = function(s) return s.si_value end,
trapno = function(s) return s._fault._trapno end,
timerid = function(s) return s._timer._timerid end,
overrun = function(s) return s._timer._overrun end,
mqd = function(s) return s._mesgq._mqd end,
band = function(s) return s._poll._band end,
},
newindex = {
signo = function(s, v) s.si_signo = v end,
errno = function(s, v) s.si_errno = v end,
code = function(s, v) s.si_code = v end,
pid = function(s, v) s.si_pid = v end,
uid = function(s, v) s.si_uid = v end,
status = function(s, v) s.si_status = v end,
addr = function(s, v) s.si_addr = v end,
value = function(s, v) s.si_value = v end,
trapno = function(s, v) s._fault._trapno = v end,
timerid = function(s, v) s._timer._timerid = v end,
overrun = function(s, v) s._timer._overrun = v end,
mqd = function(s, v) s._mesgq._mqd = v end,
band = function(s, v) s._poll._band = v end,
},
__len = lenfn,
}
addtype(types, "siginfo", "siginfo_t", mt.siginfo)
-- sigaction, standard POSIX behaviour with union of handler and sigaction
addtype_fn(types, "sa_sigaction", "void (*)(int, siginfo_t *, void *)")
mt.sigaction = {
index = {
handler = function(sa) return sa.__sigaction_u.__sa_handler end,
sigaction = function(sa) return sa.__sigaction_u.__sa_sigaction end,
mask = function(sa) return sa.sa_mask end,
flags = function(sa) return tonumber(sa.sa_flags) end,
},
newindex = {
handler = function(sa, v)
if type(v) == "string" then v = pt.void(c.SIGACT[v]) end
if type(v) == "number" then v = pt.void(v) end
sa.__sigaction_u.__sa_handler = v
end,
sigaction = function(sa, v)
if type(v) == "string" then v = pt.void(c.SIGACT[v]) end
if type(v) == "number" then v = pt.void(v) end
sa.__sigaction_u.__sa_sigaction = v
end,
mask = function(sa, v)
if not ffi.istype(t.sigset, v) then v = t.sigset(v) end
sa.sa_mask = v
end,
flags = function(sa, v) sa.sa_flags = c.SA[v] end,
},
__new = function(tp, tab)
local sa = ffi.new(tp)
if tab then for k, v in pairs(tab) do sa[k] = v end end
if tab and tab.sigaction then sa.sa_flags = bit.bor(sa.flags, c.SA.SIGINFO) end -- this flag must be set if sigaction set
return sa
end,
}
addtype(types, "sigaction", "struct sigaction", mt.sigaction)
return types
end
return {init = init}
|
Mock = { calls = {}, return_values = {} }
-- we store all calls and requested return values indexed
-- by the mock object, we don't want to hold onto references
-- when they should be garbage collected to make the tables
-- be weak
setmetatable(Mock.calls, { __mode="k" })
setmetatable(Mock.return_values, { __mode="k" })
function Mock.__call(mock, ...)
Mock.calls[mock] = Mock.calls[mock] or {}
local calls = Mock.calls[mock]
calls[#calls+1] = {...}
local return_values = Mock.return_values[mock]
if return_values and return_values[#calls] then
return unpack(return_values[#calls])
end
end
function Mock.__index(mock, key)
local new_mock = Mock:new()
rawset(mock, key, new_mock)
return new_mock
end
function Mock:new()
local mock = { returns = self.returns, then_returns = self.returns }
setmetatable(mock, self)
return mock
end
function Mock:returns(...)
if getmetatable(self) ~= Mock then
error("returns must be called with : operator", 2)
end
local return_values = Mock.return_values[self] or {}
return_values[#return_values+1] = {...}
Mock.return_values[self] = return_values
return self
end
matchers = matchers or {}
function matchers.was_called(target, value)
if getmetatable(target) ~= Mock then
return false, "target must be a Mock"
end
local calls = Mock.calls[target] or {}
if #calls ~= value then
return false, "expecting "..tostring(value).." calls, actually "..#calls
end
return true
end
function matchers.was_called_with(target, ...)
if getmetatable(target) ~= Mock then
return false, "target must be a Mock"
end
local calls = Mock.calls[target] or {}
if #calls ~= 1 then
return false, "expecting "..tostring(1).." call, actually "..#calls
end
local params = calls[1] or {}
local args = {...}
if #args ~= #params then
return false, "expecting "..#args.." parameters, actually "..#params
end
for i=1,#args do
if args[i] ~= params[i] then
return false, "expecting parameter #"..tostring(i).." to be "..tostring(args[i]).." actually "..tostring(params[i])
end
end
return true
end
|
function Array(self, ...)
local args = {...}
local max = select('#', ...)
self.length = max
for i = 1, max do
self[i - 1] = args[i]
end
end
Array.__js = true
function Array:from(arrayLike, mapFn)
if arrayLike[Symbol.iterator] then
arrayLike = arrayLike[Symbol.iterator](arrayLike)
if arrayLike == nil or arrayLike.next == nil then
error("Result of the Symbol.iterator method is not an iterable")
end
elseif arrayLike.next == nil then
error("Array.from argument is not iterable")
end
local target = {}
while true do
local result = arrayLike.next()
if result.done then
break
end
if mapFn then
result.value = mapFn(result.value)
end
table.insert(target, result.value)
end
return Reflect:__new(Array, Reflect:unpack(target))
end
Array.prototype[Symbol.iterator] = function(self)
local i = -1
return {
next = function()
i = i + 1
return {
value = self[i],
done = i >= self.length
}
end
}
end
function Array.prototype:forEach(callback)
for i = 0, self.length - 1 do
callback:call(nil, self[i], i, self)
end
end
function Array.prototype:map(callback)
local target = {}
for i = 0, self.length - 1 do
target[i + 1] = callback:call(nil, self[i], i, self)
end
return Reflect:__new(Array, Reflect:unpack(target))
end
function Array.prototype:filter(callback)
local target = {}
local n = 1
for i = 0, self.length - 1 do
if callback:call(nil, self[i], i, self) then
target[n] = self[i]
n = n + 1
end
end
return Reflect:__new(Array, Reflect:unpack(target))
end
function Array.prototype:reduce(callback, initialValue)
for i = 0, self.length - 1 do
initialValue = callback:call(nil, initialValue, self[i], i, self)
end
return initialValue
end
function Array.prototype:every(callback)
for i = 0, self.length - 1 do
if not callback:call(nil, self[i], i, self) then
return false
end
end
return true
end
function Array.prototype:some(callback)
for i = 0, self.length - 1 do
if callback:call(nil, self[i], i, self) then
return true
end
end
return false
end
function Array.prototype:indexOf(value)
for i = 0, self.length - 1 do
if self[i] == value then
return i
end
end
return -1
end
function Array.prototype:includes(value)
for i = 0, self.length - 1 do
if self[i] == value then
return true
end
end
return false
end
function Array.prototype:unshift(...)
for k, v in pairs({...}) do
table.insert(self, k - 1, v)
self.length = self.length + 1
end
end
local function shiftArrayElements(self, at, by)
for i = at, self.length - 1 do
self[i] = self[i + by]
end
end
function Array.prototype:fill(value, start, endn)
for i = (start or 0), (endn or self.length) do
self[i] = value
end
return self
end
function Array.prototype:pop()
self.length = self.length - 1
local element = self[self.length]
self[self.length] = nil
return element
end
function Array.prototype:push(...)
for _, v in pairs({...}) do
self[self.length] = v
self.length = self.length + 1
end
return self.length
end
function Array.prototype:reverse()
local i, j = 0, self.length - 1
while i < j do
self[i], self[j] = self[j], self[i]
i = i + 1
j = j - 1
end
return self
end
function Array.prototype:shift()
local element = self[0]
shiftArrayElements(self, 0, 1)
self.length = self.length - 1
return element
end
-- function Array.prototype:splice(start, deleteCount, ...)
-- local items = {...}
-- local itemsN = table.maxn(items)
-- local offset = itemsN - (deleteCount or 0)
-- for i = start, self.length do
-- self[i] = self[i + offset]
-- end
-- end
|
local utils = {}
local digest = require('digest')
local fiber = require('fiber')
local math = require('math')
local validator = require('authman.validator')
function utils.now()
return math.floor(fiber.time())
end
function utils.format(string, tab)
return (string:gsub('($%b{})', function(word) return tab[word:sub(3, -2)] or word end))
end
function utils.format_update(tuple)
local fields = {}
for number, value in pairs(tuple) do
table.insert(fields, {'=', number, value})
end
return fields
end
function utils.dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. utils.dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
function utils.base64_encode(string)
return string.gsub(
digest.base64_encode(string), '\n', ''
)
end
function utils.lower(string)
if validator.string(string) then
return string:lower()
end
return string
end
return utils |
routines={};
DEGREES=0.017453292519943295769236907684886;
function wait(howlong)
if(howlong==0) then
return
end
setWaitFrames(howlong);
coroutine.yield();
end
function run()
local id=getID();
if(routines[id]) then
coroutine.resume(routines[id]);
end
end
function register(f)
routines[getNewest()]=coroutine.create(f);
end
function fire(a,b,c)
cfire(a,b);
if(c==nil) then
return
end
register(c);
end
function cleanup()
routines[getID()]=nil;
end
NO_SPRITE=-1;
SPR_MED_CIR_BULLET=NO_SPRITE+1;
SPR_ARROW=SPR_MED_CIR_BULLET+1;
SPR_PLAYER=SPR_ARROW+1;
SPR_APPLE=SPR_PLAYER+1;
N_SPRITES=SPR_APPLE+1;
ENEMY=0
PLAYER_BULLET=ENEMY+1;
PLAYER=PLAYER_BULLET+1;
ENEMY_BULLET=PLAYER+1;
SPECIAL_OBJECT=ENEMY_BULLET+1;
N_OBJECT_CLASSES=SPECIAL_OBJECT+1; |
-- local predicates = require('./src/predicates')
-- local func = require('./src/func')
-- local reactive = require "./src/reactive"
function show(list)
if type(list) ~= 'table' then
return print('show failed, list is not a table')
end
-- local str
-- for i, v in ipairs(list) do
-- str
-- end
print(table.unpack(list))
return
end
-- function mysplit(inputstr, sep)
-- if sep == nil then
-- sep = "%s"
-- end
-- local t={} ; i=1
-- for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
-- t[i] = str
-- i = i + 1
-- end
-- return t
-- end
-- show(mysplit('a.b.c', '.'))
-- local str = "a.[0].c"
-- local splitted = mysplit(str, '.')
-- print(splitted[2])
-- if string.find(splitted[2], "%[") then
-- print ("dem arrayz")
-- else
-- print ("nope")
-- end
-- function hasDots(path)
-- if predicates.isString(path) == false then
-- return false, 'path is not a string'
-- end
-- local startIndex = string.find(path, '%.')
-- return predicates.isNumber(startIndex)
-- end
-- TODO: make more verbose, perhaps splitting and checking
-- first and last character to be [ and ], including middle
-- to be a number. For now, just checking [.
-- function isArrayAccessor(path)
-- if predicates.isString(path) == false then
-- return false, 'path is not a string'
-- end
-- local startIndex = string.find(path, '%[')
-- return predicates.isNumber(startIndex)
-- end
-- print(hasDots('.'))
-- print(hasDots('some.cow.man'))
-- print(hasDots(' another cow eats'))
-- print(string.find('.', '%.'))
-- print(string.find('some.cow.man', '%.'))
-- print(string.find(' another cow eats', '%.'))
-- print(isArrayAccessor('[0]'))
-- print(isArrayAccessor('0'))
-- print(isArrayAccessor('someLargerPropName'))
-- print(isArrayAccessor('someLarger2PropName'))
-- local account = {
-- id = 'some id',
-- person = {
-- firstName = 'Jesse',
-- address = {
-- street = '123 cow st',
-- city = 'moogle town',
-- state = 'va'
-- },
-- numbers = {
-- '1234567890',
-- '8005551234'
-- }
-- }
-- }
-- local path = 'person.address.city'
-- local paths = mysplit(path, '.')
-- local holder = account
-- for i, v in ipairs(paths) do
-- holder = holder[v]
-- print(v)
-- end
-- print("holder:", holder)
-- local curry = require './src/func'.curry
-- local function add(a, b)
-- return a + b
-- end
-- -- print(add(1, 1))
-- local addCurry = curry(add)
-- print(addCurry(20)(40))
-- print(addCurry(20, 40))
-- print("result:", result)
-- print(addCurry(1)(1))
-- print("-----")
-- print(addCurry(1, 1))
-- local arg = {}
-- local function dem(...)
-- local arg={...}
-- print(arg[1])
-- print("show:", show(arg))
-- end
-- dem(1, "a", {sup = 'man'})
-- local subject = reactive.getSubject()
-- local sub = subject:subscribe(
-- function(item) print("**next:", item) end,
-- function(error) print("**error:", error) end,
-- function(done) print("**done:", done) end
-- )
-- local sub2 = subject:subscribe(
-- function(item) print("^^next2:", item) end,
-- function(error) print("^^error2:", error) end,
-- function(done) print("^^done2:", done) end
-- )
-- subject:next("uno")
-- subject:next("dos")
-- sub:dispose()
-- subject:next("tres")
-- subject:error("t3h boom")
-- subject:complete("we done")
-- subject:next("how in the")
-- cow = {'uno', 'dos', 'tres'}
-- for i, v in ipairs(cow) do
-- if i >= 3 then
-- print("i:", i, "v:", v)
-- end
-- end
-- local difference2 = require "./src/list".difference2
-- local names = {'Jesse', 'Brandy', 'Cow'}
-- local wat = {'Cow'}
-- local result = difference2(names)(wat)
-- print("result")
-- show(result)
-- local result2 = difference2(wat)(names)
-- print("result2")
-- show(result2)
-- local fill = require './src/array'.fill
-- SpiceGirls = {}
-- show(fill('ziggyZigAh')(1)(3)(SpiceGirls))
-- local get = require './src/object'.get
-- turtle = {
-- firstName = 'Raphael',
-- type = {
-- name = 'ninja',
-- weapons = {
-- {
-- name = 'Sai',
-- damage = 4
-- },
-- {
-- name = 'Fist',
-- damage = 2
-- }
-- }
-- }
-- }
-- print(get('type.weapons[1].damage')(turtle))
-- local isNil = require 'luafp.predicates'.isNil
-- print(isNil(nil)) -- true
-- print(isNil('cow')) -- false
-- local isBoolean = require './src/predicates'.isBoolean
-- print(isBoolean(nil)) -- false
-- print(isBoolean()) -- false
-- print(isBoolean('cow')) -- false
-- print(isBoolean('')) -- false
-- print(isBoolean(true)) -- true
-- print(isBoolean(false)) -- true
-- local isNumber = require './src/predicates'.isNumber
-- print(isNumber(1))
-- print(isNumber(1.23))
-- print(isNumber(1.0))
-- print(isNumber('1'))
-- local isString = require './src/predicates'.isString
-- print(isString('sup')) -- true
-- print(isString('')) -- true
-- print(isString(1)) -- false
-- local isFunction = require './src/predicates'.isFunction
-- print(isFunction(function() return true end))
-- local cow = function() return true end
-- print(isFunction(cow))
-- local thing = {}
-- thing.sup = function() return true end
-- print(isFunction(thing.sup))
-- print(isFunction({}))
-- local isThread = require './src/predicates'.isThread
-- function blade()
-- print("blood")
-- coroutine.yeild()
-- print("is")
-- coroutine.yeild()
-- print("pumpin'")
-- end
-- co = coroutine.create(blade)
-- print(isThread(blade))
-- print(isThread(co))
-- local isEmptyString = require 'luafp.predicates'.isEmptyString
-- print(isEmptyString('')) -- true
-- print(isEmptyString("")) -- true
-- print(isEmptyString('cow')) -- false
-- print(isEmptyString(nil)) -- false
-- print(isEmptyString(5)) -- false
-- function _has(name, tbl)
-- return tbl[name] ~= nil
-- end
-- function has(name, tbl)
-- local result, err = pcall(_has, name, tbl)
-- print("result:", result)
-- print("err:", err)
-- return true
-- end
-- function unsafeHas(name, tbl)
-- return tbl[name] ~= nil
-- end
-- function has(name, tbl)
-- if name == nil then return false end
-- local ok, errorOrHas = pcall(unsafeHas, name, tbl)
-- if ok then
-- return errorOrHas
-- else
-- return false
-- end
-- end
-- function unsafeGet(name, tbl)
-- return tbl[name]
-- end
-- function get(name, tbl)
-- if name == nil then return nil end
-- local ok, errorOrValue = pcall(unsafeGet, name, tbl)
-- if ok then
-- return errorOrValue
-- else
-- return nil
-- end
-- end
-- cow = {firstName = "Jesse"}
-- chicken = {}
-- print(has('firstName', cow))
-- print(has('firstName', chicken))
-- print(has('firstName', nil))
-- print(has(nil, cow))
-- print(" ")
-- print(get('firstName', cow))
-- print(get('firstName', chicken))
-- print(get('firstName', nil))
-- print(get(nil, cow))
-- print(" ")
-- local object = require 'luafp.object'
-- print(object.has('firstName', cow))
-- print(object.has('firstName', chicken))
-- print(object.has('firstName', nil))
-- print(object.has(nil, cow))
-- print(" ")
-- print(object.get('firstName', cow))
-- print(object.get('firstName', chicken))
-- print(object.get('firstName', nil))
-- print(object.get(nil, cow))
-- local curry = require 'luafp.func'.curry
-- function add(a, b)
-- print("add, a:", a, ", b:", b)
-- return a + b
-- end
-- curryAdd = curry(add)
-- -- print(add(1, 2))
-- print(curryAdd(1, 2))
-- print(curryAdd(1)(2))
-- print(curryAdd(1)(nil)(nil))
-- function add(a, b)
-- print("add, a:", a, ", b:", b)
-- return a + b
-- end
-- local fx = require('fx')
-- local f = fx.curry( 2, add )
-- print(f(1, 3))
-- local Maybe = require 'luafp.maybe'
-- local Just = Maybe.Just
-- local Nothing = Maybe.Nothing
-- local just1 = Just(1)
-- print(just1)
-- print(just1.value)
-- print(just1:getOrElse('cow'))
-- print(just1:matchWith({
-- Just = function(tbl) return tbl.value end,
-- Nothing = function() return 'nothing' end
-- }))
-- print(Just(1) == Just(1))
-- print(Just(1) == 1)
-- print(Just(1) == Nothing())
-- print("Just:hasInstance(just1):", Just:hasInstance(just1))
-- print(" ")
-- local nothing = Nothing()
-- print(nothing)
-- print(nothing.value)
-- print(nothing:getOrElse('cow'))
-- print(nothing:matchWith({
-- Just = function(tbl) return tbl.value end,
-- Nothing = function() return 'nothing' end
-- }))
-- print(Nothing() == Nothing())
-- print("Nothing:hasInstance(nothing):", Nothing:hasInstance(nothing))
-- print("Just:hasInstance(nothing):", Just:hasInstance(nothing))
-- print("Nothing:hasInstance(just1):", Nothing:hasInstance(just1))
-- print(" ")
-- function add1(o)
-- return o + 1
-- end
-- local just2 = Just(2)
-- print(just2)
-- print(just2:map(add1))
-- local nothing2 = Nothing()
-- print(nothing2)
-- print(nothing2:map(add1))
-- print(" ")
-- function breakIt()
-- return Nothing()
-- end
-- local just2 = Just(2)
-- print(just2)
-- -- print(just2:map(add1):map(breakIt))
-- print(just2:map(add1):chain(breakIt))
-- print(" ")
-- function addJust1(value)
-- return Just(value + 1)
-- end
-- function subtractJust5(value)
-- return Just(value - 5)
-- end
-- print(just2:chain(addJust1):chain(subtractJust5))
-- print(" ")
-- print(" ** orElse ** ")
-- function getError(o)
-- return Just('error')
-- end
-- print(Just(1):orElse(getError))
-- print(Nothing():orElse(getError))
local Result = require 'luafp.Result'
local Ok = Result.Ok
local Error = Result.Error
print(Ok(1) == Ok(2))
-- print(Result.Ok(1))
-- print(Result.Error('boom'))
-- print(Result.Ok({1, 2}))
-- print(Result.Ok({firstName="Jesse", lastName="Warden"}))
-- print(" ")
-- function add1(o)
-- return o + 1
-- end
-- print(Result.Ok(1):map(add1))
-- print(Result.Error('boom'):map(add1))
-- print(" ")
-- print(Ok(1):getOrElse('cow boom'))
-- print(Error('boom'):getOrElse('cow boom'))
-- print(" ")
-- function addBoom(o)
-- return o .. ' b00m!'
-- end
-- print(Ok(1):orElse('aw man'):mapError(addBoom))
-- print(Error('ka'):mapError(addBoom))
-- print(" ")
-- print(Ok(1):matchWith({
-- Error = function(tbl) return tbl.value end,
-- Ok = function(tbl) return tbl.value end
-- }))
-- print(Error('dat boom tho'):matchWith({
-- Error = function(tbl) return tbl.value end,
-- Ok = function(tbl) return tbl.value end
-- }))
-- print(" ")
-- function tryHardStuff1()
-- return Ok(1)
-- end
-- function tryHardStuff2(o)
-- return Ok(o + 1)
-- end
-- function tryHardStuff3(o)
-- return Error('boom done')
-- end
-- print(Ok(1):chain(tryHardStuff1):chain(tryHardStuff2))
-- print(Error('wat'):chain(tryHardStuff1):chain(tryHardStuff2))
-- print(Ok(1):chain(tryHardStuff1):chain(tryHardStuff2):chain(tryHardStuff3))
-- print(" ")
-- function itsOk()
-- return "we good"
-- end
-- function itsBoom()
-- return error('holy pow')
-- end
-- function itsYourBoom()
-- return error('holy pow', 2)
-- end
-- print(Result:try(itsOk))
-- print(Result:try(itsBoom))
-- print(Result:try(itsYourBoom))
-- local curry = require 'luafp.func'.curry
-- local function add(a, b)
-- return a + b
-- end
-- print(add(1, nil))
-- function getIt(f)
-- local info = debug.getinfo(f, 'u')
-- return function()
-- print(info.nparams)
-- end
-- end
-- function sup(man)
-- return true
-- end
-- local wat = getIt(sup)
-- wat() |
-----------------------------------
-- Area: Port Bastok
-- NPC: Ehrhard
-- Involved in Quest: Stamp Hunt
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local StampHunt = player:getQuestStatus(BASTOK,tpz.quest.id.bastok.STAMP_HUNT);
if (StampHunt == QUEST_ACCEPTED and player:getMaskBit(player:getCharVar("StampHunt_Mask"),5) == false) then
player:startEvent(121);
else
player:startEvent(47);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 121) then
player:setMaskBit(player:getCharVar("StampHunt_Mask"),"StampHunt_Mask",5,true);
end
end;
|
Elona.Skill = {
Gained = function(skillName)
return ("You have learned a new ability, %s."):format(skillName)
end,
Default = {
OnDecrease = function(entity, skillName)
return ("%s%s %s skill falls off."):format(_.name(entity), _.his_owned(entity), skillName)
end,
OnIncrease = function(entity, skillName)
return ("%s%s %s skill increases."):format(_.name(entity), _.his_owned(entity), skillName)
end,
},
}
|
--[[
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local itunes = {}
local mattata = require('mattata')
local https = require('ssl.https')
local url = require('socket.url')
local json = require('dkjson')
local redis = require('libs.redis')
function itunes:init()
itunes.commands = mattata.commands(self.info.username):command('itunes').table
itunes.help = '/itunes <query> - Searches iTunes for the given search query and returns the most relevant result.'
end
function itunes.get_output(jdat, language)
local output = {}
if jdat.results[1].trackViewUrl
and jdat.results[1].trackName
then
table.insert(
output,
'<b>' .. language['itunes']['1'] .. '</b> <a href=\'' .. jdat.results[1].trackViewUrl .. '\'>' .. mattata.escape_html(jdat.results[1].trackName) .. '</a>'
)
end
if jdat.results[1].artistViewUrl
and jdat.results[1].artistName
then
table.insert(
output,
'<b>' .. language['itunes']['2'] .. '</b> <a href="' .. jdat.results[1].artistViewUrl .. '">' .. mattata.escape_html(jdat.results[1].artistName) .. '</a>'
)
end
if jdat.results[1].collectionViewUrl
and jdat.results[1].collectionName
then
table.insert(
output,
'<b>' .. language['itunes']['3'] .. '</b> <a href="' .. jdat.results[1].collectionViewUrl .. '">' .. mattata.escape_html(jdat.results[1].collectionName) .. '</a>'
)
end
if jdat.results[1].trackNumber
and jdat.results[1].trackCount
then
table.insert(
output,
'<b>' .. language['itunes']['4'] .. '</b> ' .. jdat.results[1].trackNumber .. '/' .. jdat.results[1].trackCount
)
end
if jdat.results[1].discNumber
and jdat.results[1].discCount
then
table.insert(
output,
'<b>' .. language['itunes']['5'] .. '</b> ' .. jdat.results[1].discNumber .. '/' .. jdat.results[1].discCount
)
end
return table.concat(
output,
'\n'
)
end
function itunes:on_inline_query(inline_query)
local input = mattata.input(inline_query.query)
if not input
then
return
end
local jstr, res = https.request('https://itunes.apple.com/search?term=' .. url.escape(input))
if res ~= 200
then
return
end
local jdat = json.decode(jstr)
if not jdat.results[1]
then
return
end
local count = 0
local results = {}
local temp = {}
for k, v in pairs(jdat.results)
do
if v.artworkUrl100
and not temp[v.artworkUrl100]
then
count = count + 1
table.insert(
results,
mattata.inline_result()
:type('photo')
:id(count)
:photo_url(
v.artworkUrl100
:gsub('%/100x100bb%.jpg', '/10000x10000bb.jpg')
)
:thumb_url(v.artworkUrl100)
)
temp[v.artworkUrl100] = true
end
end
return mattata.answer_inline_query(
inline_query.id,
results
)
end
function itunes:on_callback_query(callback_query, message, configuration, language)
if not message.reply
then
return mattata.answer_callback_query(
callback_query.id,
language['itunes']['6'],
true
)
end
local input = mattata.input(message.reply.text)
if callback_query.data == 'artwork'
then
local jstr, res = https.request('https://itunes.apple.com/search?term=' .. url.escape(input))
if res ~= 200
then
return false
end
local jdat = json.decode(jstr)
if not jdat.results[1]
then
return false
end
if jdat.results[1].artworkUrl100
then
local artwork = jdat.results[1].artworkUrl100:gsub('%/100x100bb%.jpg', '/10000x10000bb.jpg')
-- Get the highest quality artwork available.
mattata.send_photo(
message.chat.id,
artwork
)
return mattata.edit_message_text(
message.chat.id,
message.message_id,
language['itunes']['7']
)
end
end
end
function itunes:on_message(message, configuration, language)
local input = mattata.input(message.text)
if not input
then
local success = mattata.send_force_reply(
message,
language['itunes']['8']
)
if success
then
redis:set(
string.format(
'action:%s:%s',
message.chat.id,
success.result.message_id
),
'/itunes'
)
end
return
end
mattata.send_chat_action(message.chat.id)
local jstr, res = https.request('https://itunes.apple.com/search?term=' .. url.escape(input))
if res ~= 200
then
return mattata.send_reply(
message,
language['errors']['connection']
)
end
local jdat = json.decode(jstr)
if not jdat.results[1]
then
return mattata.send_reply(
message,
language['errors']['results']
)
end
return mattata.send_message(
message.chat.id,
itunes.get_output(
jdat,
language
),
'html',
true,
false,
message.message_id,
mattata.inline_keyboard():row(
mattata.row():callback_data_button(
language['itunes']['9'],
'itunes:artwork'
)
)
)
end
return itunes |
package("libomp")
set_homepage("https://openmp.llvm.org/")
set_description("LLVM's OpenMP runtime library.")
set_urls("https://github.com/llvm/llvm-project/releases/download/llvmorg-$(version)/openmp-$(version).src.tar.xz")
add_versions("10.0.1", "d19f728c8e04fb1e94566c8d76aef50ec926cd2f95ef3bf1e0a5de4909b28b44")
add_versions("11.1.0", "d187483b75b39acb3ff8ea1b7d98524d95322e3cb148842957e9b0fbb866052e")
add_versions("12.0.1", "60fe79440eaa9ebf583a6ea7f81501310388c02754dbe7dc210776014d06b091")
add_configs("shared", {description = "Build shared library.", default = true, type = "boolean"})
add_deps("cmake")
add_links("omp")
if is_plat("macosx") then
add_extsources("brew::libomp")
elseif is_plat("linux") then
add_extsources("apt::libomp-dev")
add_syslinks("pthread", "dl")
end
on_install("macosx", "linux", "cross", function (package)
local configs = {"-DLIBOMP_INSTALL_ALIASES=OFF"}
local shared = package:config("shared")
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (shared and "ON" or "OFF"))
table.insert(configs, "-DLIBOMP_ENABLE_SHARED=" .. (shared and "ON" or "OFF"))
import("package.tools.cmake").install(package, configs)
end)
on_test(function (package)
assert(package:has_cfuncs("omp_get_thread_num", {includes = "omp.h"}))
end)
|
sensorID = "status" -- a sensor identifier for this device
tgtHost = "iot.eclipse.org" -- target host (broker)
tgtPort = 1883 -- target port (broker listening on)
mqttUserID = "MQTT_USER_ID" -- account to use to log into the broker
mqttPass = "MQTT_USER_PASSWORD" -- broker account password
mqttTimeOut = 120 -- connection timeout
dataInt = 1 -- data transmission interval in seconds
topicQueue = "/readEsp8266"-- the MQTT topic queue to use
pin = 1
local nmea = require "nmea"
-- Subscribe to a topic
function subscribe()
print("subscribed")
mqttBroker:subscribe("/control/#",0, function(conn) end)
end
-- Reconnect to MQTT when we receive an "offline" message.
function reconn()
print("Disconnected, reconnecting....")
conn()
end
-- Establish a connection to the MQTT broker with the configured parameters.
function conn()
print("Making connection to MQTT broker")
mqttBroker:connect(tgtHost, tgtPort, 0, 1,function(client)
print ("connected")
subscribe()
gps()
end, function(client, reason) print("failed reason: " .. reason) end)
end
function performTask(topic,data)
if(topic == "/control/led" and data == "OFF")
then
gpio.mode(pin, gpio.OUTPUT,gpio.PULLUP)
gpio.write(pin, gpio.HIGH)
elseif(topic == "/control/led" and data == "ON")
then
gpio.mode(pin, gpio.OUTPUT,gpio.PULLUP)
gpio.write(pin, gpio.LOW)
elseif(topic == "/control/led" and data == "RESET")
then
node.restart()
elseif(topic == "/control/led" and data == "STATUS")
then
status = gpio.read(pin)
print("status" .. status)
if status == 0
then
mqttBroker:publish(topicQueue, "led_pin:on", 2, 0,function(client) -- publish
print("published")
end)
elseif status == 1
then
mqttBroker:publish(topicQueue, "led_pin:off", 2, 0,function(client)-- publish
print("published")
end)
else
print("Do Nothing")
end
end
end
function makeConn()
-- Instantiate a global MQTT client object
print("Instantiating mqttBroker")
mqttBroker = mqtt.Client(sensorID, mqttTimeOut, mqttUserID, mqttPass, 1)
-- Set up the event callbacks
print("Setting up callbacks")
mqttBroker:on("connect", function(client) print ("connected") end)
mqttBroker:on("offline", reconn)
-- Recieve the Msg from Broker
mqttBroker:on("message", function(conn, topic, data)
print("MQTT Message Received...")
print("Topic: " .. topic)
if data ~= nil then
print("Message: " .. data)
-- Perform Speific Task based on Topic & Data
performTask(topic,data)
end
end)
-- Connect to the Broker
conn()
end
function gps()
-- setup GPS Reciever
uart.setup(0, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
handleGPS()
end
function handleGPS()
print("GPS Data")
uart.on("data", 255,
function(data)
print("receive from uart:", data)
-- repeat
-- local data1 = split(data,",")
-- local result = nmea.decode(data1)
-- print("decoded data : ")
mqttBroker:publish(topicQueue, data, 2, 0)
-- for k,v in pairs(result)
-- do
-- print(k.." => "..v)
-- mqttBroker:publish(topicQueue, k .. "=" .. v, 2, 0) -- publish
-- end
-- until false
-- print("decoded")
if data=="quit" then
uart.on("data") -- unregister callback function
end
end, 0)
end
|
require("@vue/compiler-dom")
require("@vue/runtime-dom")
require("@vue/shared")
local compileCache = Object:create(nil)
function compileToFunction(template, options)
if not isString(template) then
if template.nodeType then
template = template.innerHTML
else
__DEV__ and warn(template)
return NOOP
end
end
local key = template
-- [ts2lua]compileCache下标访问可能不正确
local cached = compileCache[key]
if cached then
return cached
end
if template[0+1] == '#' then
local el = document:querySelector(template)
if __DEV__ and not el then
warn()
end
-- [ts2lua]lua中0和空字符串也是true,此处el需要确认
template = (el and {el.innerHTML} or {})[1]
end
local = compile(template, extend({hoistStatic=true, onError=function(err)
if __DEV__ then
local message = nil
local codeFrame = err.loc and generateCodeFrame(template, err.loc.start.offset, err.loc.tsvar_end.offset)
-- [ts2lua]lua中0和空字符串也是true,此处codeFrame需要确认
warn((codeFrame and {} or {message})[1])
else
error(err)
end
end
}, options))
-- [ts2lua]lua中0和空字符串也是true,此处__GLOBAL__需要确认
local render = (__GLOBAL__ and {Function(code)()} or {Function('Vue', code)(runtimeDom)})[1]
-- [ts2lua]compileCache下标访问可能不正确
return compileCache[key] = render
end
registerRuntimeCompiler(compileToFunction)
undefined |
---[[---------------------------------------]]---
-- doomrc.lua - Load Doom Nvim doomrc --
-- Author: NTBBloodbath --
-- License: MIT --
---[[---------------------------------------]]---
function Check_BFC()
-- /home/user/.config/doom-nvim/doomrc
if Fn.filereadable(Doom_root .. '/doomrc') then
Doom_bfc = true
else
Doom_bfc = false
end
end
local function default_BFC_values()
Doom = {
-- Autosave
-- false : Disable autosave
-- true : Enable autosave
-- @default = false
autosave = false,
-- Format on save
-- false : Disable format on save
-- true : Enable format on save
-- @default = false
fmt_on_save = false,
-- Autosave sessions
-- false : Disable session autosave
-- true : Enable session autosave
-- @default = false
autosave_sessions = false,
-- Autoload sessions
-- false : Disable session autoload
-- true : Enable session autosave
-- @default = false
autoload_last_session = false,
-- Preserve last editing position
-- false : Disable preservation of last editing position
-- true : Enable preservation of last editing position
-- @default = false
preserve_edit_pos = false,
-- Default indent size
-- @default = 4
indent = 4,
-- Show indent lines
-- @default = true
show_indent = true,
-- Expand tabs
-- Specifies if spaces or tabs must be used
-- false : spaces
-- true : tabs
-- @default = true
expand_tabs = true,
-- Set numbering
-- false : Shows absolute number lines
-- true : Shows relative number lines
-- @default = true
relative_num = true,
-- Set max cols
-- Defines the column to show a vertical marker
-- @default = 80
max_columns = 80,
-- Enable guicolors
-- Enables gui colors on GUI versions of Neovim
-- @default = true
enable_guicolors = true,
-- Sidebar sizing
-- Specifies the default width of Tree Explorer and Tagbar
-- @default = 25
sidebar_width = 25,
-- Tagbar left
-- Sets Tagbar buffer to the left when enabled
-- @default = true
tagbar_left = true,
-- Show hidden files
-- @default = true
show_hidden = true,
-- Default colorscheme
-- @default = doom-one
colorscheme = 'doom-one',
-- Background color
-- @default = dark
colorscheme_bg = 'dark',
-- Checkupdates on start
-- @default = false
check_updates = false,
-- Disabled plugins
-- @default = {'lazygit', 'minimap', 'restclient'}
-- example:
-- disabled_plugins = {'emmet-vim'}
disabled_plugins = { 'lazygit', 'minimap', 'restclient' },
-- Disabled plugins modules
-- @default = {'git', 'lsp', 'web'}
-- example:
-- disabled_modules = {'web'}
disabled_modules = { 'git', 'lsp', 'web' },
-- Install custom plugins
-- @default = {}
-- examples:
-- plugins without options:
-- custom_plugins = {'andweeb/presence.nvim'}
-- plugins with options:
-- custom_plugins = {
-- {
-- 'repo': 'andweeb/presence.nvim',
-- 'enabled': true,
-- }
-- }
custom_plugins = {},
-- Set the parsers for TreeSitter
-- @default = {}
-- example:
-- ts_parsers = {'python', 'javascript'}
ts_parsers = {},
-- Set the Terminal direction
-- Available directions:
-- - vertical
-- - horizontal
-- - window
-- - float
-- @default = 'horizontal'
terminal_direction = 'horizontal',
-- Set the Terminal width
-- Applies only to float direction
-- @default = 70
terminal_width = 70,
-- Set the Terminal height
-- Applies to all directions except window
-- @default = 20
terminal_height = 20,
-- Conceal level
-- Set Neovim conceal level
-- 0 : Disable indentline and show all
-- 1 : Conceal some functions and show indentlines
-- 2 : Concealed text is completely hidden unless it has a custom replacement
-- character defined
-- 3 : Concealed text is completely hidden
conceallevel = 0,
-- Logging level
-- 0 : No logging
-- 1 : All errors, no echo (default)
-- 2 : All errors and messages, no echo
-- 3 : All errors and messages, echo
-- @default = 1
logging = 3,
}
end
function Load_BFC()
-- /home/user/.config/doom-nvim/doomrc
if Fn.filereadable(Doom_root .. '/doomrc') then
Try({
function()
Cmd('luafile ' .. Doom_root .. '/doomrc')
Log_message('+', 'Loading the BFC ...', 2)
end,
Catch({
function(_)
Log_message('!', 'Error while loading the BFC', 1)
end,
}),
})
else
Log_message('+', 'No BFC file found, falling to defaults', 2)
default_BFC_values()
end
end
|
data.raw["assembling-machine"]["steel-furnace-mk2"].crafting_categories = {"smelting", "smelting-pratical"}
data.raw["assembling-machine"]["steel-furnace-mk3"].crafting_categories = {"smelting", "smelting-pratical"}
data.raw["assembling-machine"]["steel-furnace-mk4"].crafting_categories = {"smelting", "smelting-pratical"}
data.raw["assembling-machine"]["steel-furnace-mk5"].crafting_categories = {"smelting", "smelting-pratical"}
data.raw["item"]["iron-chunks"].stack_size = 500
data.raw["item"]["copper-chunks"].stack_size = 500
local a = false
data:extend(
{
{
type = "recipe",
name = "iron-pratical",
category = "smelting-pratical",
energy_required = 10,
enabled = a,
ingredients =
{
{type="item", name="iron-chunks", amount=20},
},
result = "iron-pratical",
},
{
type = "recipe",
name = "copper-pratical",
category = "smelting-pratical",
energy_required = 10,
enabled = a,
ingredients =
{
{type="item", name="copper-chunks", amount=20},
},
result = "copper-pratical",
},
{
type = "recipe",
name = "iron-to-copper",
category = "smelting-pratical",
icon = "__MiningStation__/graphics/icons/iron-to-copper.png",
energy_required = 22,
enabled = a,
ingredients =
{
{type="item", name="iron-pratical", amount=1},
},
result = "copper-pratical",
},
{
type = "recipe",
name = "copper-to-iron",
category = "smelting-pratical",
icon = "__MiningStation__/graphics/icons/copper-to-iron.png",
energy_required = 22,
enabled = a,
ingredients =
{
{type="item", name="copper-pratical", amount=1},
},
result = "iron-pratical",
},
{
type = "recipe",
name = "titanium-pratical",
category = "smelting-pratical",
energy_required = 22,
enabled = a,
ingredients =
{
{type="item", name="iron-pratical", amount=10},
},
result = "titanium-pratical",
},
{
type = "recipe",
name = "silver-pratical",
category = "smelting-pratical",
energy_required = 22,
enabled = a,
ingredients =
{
{type="item", name="copper-pratical", amount=10},
},
result = "silver-pratical",
},
{
type = "recipe",
name = "tin-pratical",
category = "smelting-pratical",
subgroup = "ms-pratical-back",
energy_required = 16,
order = "a-a",
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="iron-pratical", amount=2},
},
result = "tin-ore",
},
{
type = "recipe",
name = "zinc-pratical",
category = "smelting-pratical",
subgroup = "ms-pratical-back",
order = "a-b",
energy_required = 16,
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="iron-pratical", amount=3},
},
result = "zinc-ore",
},
{
type = "recipe",
name = "lead-pratical",
category = "smelting-pratical",
subgroup = "ms-pratical-back2",
energy_required = 22,
order = "a-a",
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="copper-pratical", amount=2},
},
result = "lead-ore",
},
{
type = "recipe",
name = "gold-pratical",
category = "smelting-pratical",
subgroup = "ms-pratical-back2",
order = "a-b",
energy_required = 22,
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="copper-pratical", amount=4},
},
result = "gold-ore",
},
{
type = "recipe",
name = "nickel-pratical",
category = "smelting-pratical",
subgroup = "ms-pratical-back",
energy_required = 26,
order = "a-c",
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="iron-pratical", amount=5},
},
result = "nickel-ore",
},
{
type = "recipe",
name = "aluminium-pratical",
category = "smelting-pratical",
subgroup = "ms-pratical-back2",
order = "a-c",
energy_required = 26,
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="copper-pratical", amount=4},
},
result = "bauxite-ore",
},
{
type = "recipe",
name = "titanium-pratical-back",
category = "smelting-pratical",
subgroup = "ms-pratical-back",
energy_required = 32,
order = "a-d",
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="titanium-pratical", amount=1},
},
result = "rutile-ore",
results_count = 1
},
{
type = "recipe",
name = "silver-pratical-back",
category = "smelting-pratical",
subgroup = "ms-pratical-back2",
order = "a-d",
energy_required = 32,
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="silver-pratical", amount=1},
},
result = "silver-ore",
},
{
type = "recipe",
name = "tungsten-pratical",
category = "smelting-pratical",
subgroup = "ms-pratical-back",
energy_required = 35,
order = "a-e",
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="titanium-pratical", amount=3},
},
result = "tungsten-ore",
},
{
type = "recipe",
name = "cobalt-pratical",
category = "smelting-pratical",
subgroup = "ms-pratical-back2",
order = "a-e",
energy_required = 35,
enabled = a,
ingredients =
{
{"sand", 1},
{type="item", name="silver-pratical", amount=2},
},
result = "cobalt-ore",
},
}
)
data:extend(
{
{
type = "recipe",
name = "ms-go-iron",
category = "smelting-pratical",
subgroup = "ms-ore-pratical",
icon = "__bobores__/graphics/icons/iron-ore.png",
order = "a-a",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "iron-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "iron-chunks", amount = 20},
}
},
{
type = "recipe",
name = "ms-go-copper",
category = "smelting-pratical",
subgroup = "ms-ore-pratical-copper",
icon = "__base__/graphics/icons/copper-ore.png",
order = "a-a",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "copper-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "copper-chunks", amount = 20},
}
},
{
type = "recipe",
name = "ms-go-tin",
category = "smelting-pratical",
subgroup = "ms-ore-pratical",
icon = "__bobores__/graphics/icons/tin-ore.png",
order = "a-b",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "tin-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "iron-pratical", amount = 1},
}
},
{
type = "recipe",
name = "ms-go-lead",
category = "smelting-pratical",
subgroup = "ms-ore-pratical-copper",
icon = "__bobores__/graphics/icons/lead-ore.png",
order = "a-b",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "lead-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "copper-pratical", amount = 1},
}
},
{
type = "recipe",
name = "ms-go-zinc",
category = "smelting-pratical",
subgroup = "ms-ore-pratical",
icon = "__bobores__/graphics/icons/zinc-ore.png",
order = "a-c",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "tin-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "iron-pratical", amount = 2},
}
},
{
type = "recipe",
name = "ms-go-gold",
category = "smelting-pratical",
subgroup = "ms-ore-pratical-copper",
icon = "__bobores__/graphics/icons/gold-ore.png",
order = "a-c",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "gold-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "copper-pratical", amount = 2},
}
},
{
type = "recipe",
name = "ms-go-nickel",
category = "smelting-pratical",
subgroup = "ms-ore-pratical",
icon = "__bobores__/graphics/icons/nickel-ore.png",
order = "a-d",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "nickel-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "iron-pratical", amount = 4},
}
},
{
type = "recipe",
name = "ms-go-bauxite",
category = "smelting-pratical",
subgroup = "ms-ore-pratical-copper",
icon = "__bobores__/graphics/icons/bauxite-ore.png",
order = "a-d",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "bauxite-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "copper-pratical", amount = 3},
}
},
{
type = "recipe",
name = "ms-go-titanium",
category = "smelting-pratical",
subgroup = "ms-ore-pratical",
icon = "__bobores__/graphics/icons/rutile-ore.png",
order = "a-e",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "rutile-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "iron-pratical", amount = 7},
}
},
{
type = "recipe",
name = "ms-go-silver",
category = "smelting-pratical",
subgroup = "ms-ore-pratical-copper",
icon = "__bobores__/graphics/icons/silver-ore.png",
order = "a-e",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "silver-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "copper-pratical", amount = 7},
}
},
{
type = "recipe",
name = "ms-go-tungsten",
category = "smelting-pratical",
subgroup = "ms-ore-pratical",
icon = "__bobores__/graphics/icons/tungsten-ore.png",
order = "a-f",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "tungsten-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "iron-pratical", amount = 12},
}
},
{
type = "recipe",
name = "ms-go-cobalt",
category = "smelting-pratical",
subgroup = "ms-ore-pratical-copper",
icon = "__bobores__/graphics/icons/cobalt-ore.png",
order = "a-f",
energy_required = 7,
enabled = a,
ingredients =
{
{type = "item", name = "cobalt-ore", amount = 1},
},
results = {
{type = "item", name = "stone", amount = 1},
{type = "item", name = "copper-pratical", amount = 12},
}
},
{
type = "recipe",
name = "ms-go-i",
category = "smelting-pratical",
subgroup = "ms-pratical-back",
order = "a-a-a",
energy_required = 5,
enabled = a,
ingredients =
{
{type = "item", name = "iron-pratical", amount = 1},
},
results = {
{type = "item", name = "iron-chunks", amount = 18},
}
},
{
type = "recipe",
name = "ms-go-c",
category = "smelting-pratical",
subgroup = "ms-pratical-back2",
order = "a-a-a",
energy_required = 5,
enabled = a,
ingredients =
{
{type = "item", name = "copper-pratical", amount = 1},
},
results = {
{type = "item", name = "copper-chunks", amount = 18},
}
},
}
) |
function test()
local a = false
local b = not a
return b
end
jit("compile", test)
local res = test()
assert(res == not false)
--[[
function <../tests/27_OP_NOT.lua:1,5> (4 instructions at 0x20d6500)
0 params, 2 slots, 0 upvalues, 2 locals, 0 constants, 0 functions
1 [2] LOADBOOL 0 0 0
2 [3] NOT 1 0
3 [4] RETURN 1 2
4 [5] RETURN 0 1
constants (0) for 0x20d6500:
locals (2) for 0x20d6500:
0 a 2 5
1 b 3 5
upvalues (0) for 0x20d6500:
]]
--[[
ra = R(1);
rb = R(0);
res = l_isfalse(rb);
setbvalue(ra, res);
]] |
-- the actor table is the most basic object in our system as all things must do something
Actor = { next_action = nil }
function Actor:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
-- given an object, execute self.next_action "against" it
function Actor.act(o)
-- perform self.next_action?
end
|
-----------------------------------
-- Area: Port San d'Oria
-- NPC: Apstaule
-- Not used cutscenes: 541
-----------------------------------
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
local count = trade:getItemCount()
local AuctionParcel = trade:hasItemQty(594, 1)
if (AuctionParcel == true and count == 1) then
local TheBrugaireConsortium = player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.THE_BRUGAIRE_CONSORTIUM)
if (TheBrugaireConsortium == 1) then
player:tradeComplete()
player:startEvent(540)
player:setCharVar("TheBrugaireConsortium-Parcels", 21)
end
end
end
function onTrigger(player, npc)
player:startEvent(542)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
--- Neovim LSP
local map = vim.api.nvim_set_keymap
local lspconfig = require'lspconfig'
local lspfuzzy = require'lspfuzzy'
local function init_lspkind()
require('lspkind').init({
-- enables text annotations
-- default: true
with_text = true,
-- default symbol map
-- can be either 'default' or
-- 'codicons' for codicon preset (requires vscode-codicons font installed)
-- default: 'default'
preset = 'codicons',
-- override preset symbols
--
-- default: {}
symbol_map = {
Text = "",
Method = "",
Function = "",
Constructor = "",
Field = "ﰠ",
Variable = "",
Class = "ﴯ",
Interface = "",
Module = "",
Property = "ﰠ",
Unit = "塞",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "פּ",
Event = "",
Operator = "",
TypeParameter = ""
},
})
end
local function setup_keymappings()
opts = { noremap = true }
silentOpts = { noremap = true, silent=true }
vim.cmd [[
augroup lsp_document_highlight
autocmd! * <buffer>
autocmd CursorHold * lua vim.lsp.diagnostic.show_line_diagnostics({focusable=false})
autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
augroup END
]]
map('n', '[g', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
map('n', ']g', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
map('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
map('n', 'gD', "<cmd>lua require'lsp.peek'.Peek('definition')<CR>", opts)
map('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
map('n', 'gI', "<cmd>lua require'lsp.peek'.Peek('implementation')<CR>", opts)
map('n', 'gt', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
map('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
map('n', '<Leader>cfi', '<cmd>lua vim.lsp.buf.ingoing_calls()<CR>', opts)
map('n', '<Leader>cfo', '<cmd>lua vim.lsp.buf.outgoing_calls()<CR>', opts)
map('n', '<Leader>cft', ':Telescope lsp_dynamic_workspace_symbols<CR>', opts)
map('n', '<Leader>cfm', ':Telescope lsp_document_symbols<CR>', opts)
map('n', '<leader>crn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
map('n', '<F2>', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
map('n', 'gh', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
map('n', '<leader>ch', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
map('i', '<C-\\>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
map('n', '<leader>cal', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
map('v', '<leader>cas', '<cmd>lua vim.lsp.buf.range_code_action()<CR>', opts)
map('n', '<leader>csf', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
map('v', '<leader>csf', '<cmd>lua vim.lsp.buf.range_formatting()<CR>', opts)
map('n', '<leader>cd', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
map('n', '<leader>cD', ':Telescope lsp_workspace_diagnostics<CR>', opts)
end
local function setup_snippet()
local t = function(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
local check_back_space = function()
local col = vim.fn.col('.') - 1
return col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') ~= nil
end
-- Use (s-)tab to:
--- move to prev/next item in completion menuone
--- jump to prev/next snippet's placeholder
_G.tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-n>"
elseif vim.fn['vsnip#available'](1) == 1 then
return t "<Plug>(vsnip-expand-or-jump)"
elseif check_back_space() then
return t "<Tab>"
else
return vim.fn['compe#complete']()
end
end
_G.s_tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-p>"
elseif vim.fn['vsnip#jumpable'](-1) == 1 then
return t "<Plug>(vsnip-jump-prev)"
else
-- If <S-Tab> is not working in your terminal, change it to <C-h>
return t "<S-Tab>"
end
end
vim.api.nvim_set_keymap("i", "<Tab>", "v:lua.tab_complete()", {expr = true})
vim.api.nvim_set_keymap("s", "<Tab>", "v:lua.tab_complete()", {expr = true})
vim.api.nvim_set_keymap("i", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
vim.api.nvim_set_keymap("s", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
vim.cmd [[
inoremap <silent><expr> <C-Space> compe#complete()
inoremap <silent><expr> <CR> compe#confirm('<CR>')
inoremap <silent><expr> <C-e> compe#close('<C-e>')
inoremap <silent><expr> <C-f> compe#scroll({ 'delta': +4 })
inoremap <silent><expr> <C-d> compe#scroll({ 'delta': -4 })
]]
-- map('i', '<C-Space>', '<cmd>lua vim.lsp.buf.completion()<CR>', opts)
end
local on_attach = function(_, bufnr)
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Make the LSP client use FZF instead of the quickfix list
lspfuzzy.setup {}
init_lspkind()
setup_keymappings()
setup_snippet()
end
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
local lsp_installer = require'nvim-lsp-installer'
lsp_installer.on_server_ready(function(server)
-- Specify the default options which we'll use to setup all servers
local default_opts = {
on_attach = on_attach,
capabilities = capabilities,
}
-- Now we'll create a server_opts table where we'll specify our custom LSP server configuration
local server_opts = {
-- Provide settings that should only apply to the "eslintls" server
["eslintls"] = function()
default_opts.settings = {
format = {
enable = true,
},
}
end,
}
-- Use the server's custom settings, if they exist, otherwise default to the default options
local server_options = server_opts[server.name] and server_opts[server.name]() or default_opts
server:setup(server_options)
end)
-- Enable the following language servers
local servers = { 'tsserver', 'jdtls', 'pyright', 'omnisharp' }
for _, lsp in pairs(servers) do
local server_is_found, server = lsp_installer.get_server(name)
if server_is_found then
if not server:is_installed() then
print("Installing " .. name)
server:install()
end
end
end
|
-- create_room
return function(connector, box_name, name)
local room = {}
local room_name = box_name.."/"..name
local method_handler_map = {}
local is_exited = false
connector.enter_room(room_name)
room.on = function(method_name, method_handler)
local method_handlers = method_handler_map[method_name]
connector.on(room_name.."/"..method_name, method_handler)
if method_handlers == nil then
method_handlers = {}
method_handler_map[method_name] = method_handlers
end
table.insert(method_handlers, method_handler)
end
room.off = function(method_name, method_handler)
connector.off(room_name.."/"..method_name, method_handler)
if method_handler == nil then
method_handler_map[method_name] = nil
else
local method_handlers = method_handler_map[method_name]
for index, value in pairs(method_handlers) do
if value == method_handler then
table.remove(method_handlers, index)
break
end
end
if table.getn(method_handlers) == 0 then
connector.off(method_name)
end
end
end
room.send = function(method_name, data, callback)
if is_exited ~= true then
connector.send(room_name.."/"..method_name, data, callback);
end
end
room.exit = function()
if is_exited ~= true then
connector.exit_room(room_name)
for method_name, method_handlers in pairs(method_handler_map) do
for index, method_handler in pairs(method_handlers) do
connector.off(method_name, method_handlers)
end
end
method_handler_map = nil
is_exited = true
end
end
return room
end |
local Native = require('lib.native.native')
---@class ItemStringField
local ItemStringField = {
ModelUsed = Native.ConvertItemStringField(0x6966696C), --ITEM_SF_MODEL_USED
}
return ItemStringField
|
-- Test primality by trial division
function isPrime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
-- Take decimal number, return binary string
function dec2bin (n)
local bin, bit = ""
while n > 0 do
bit = n % 2
n = math.floor(n / 2)
bin = bit .. bin
end
return bin
end
-- Take decimal number, return population count as number
function popCount (n)
local bin, count = dec2bin(n), 0
for pos = 1, bin:len() do
if bin:sub(pos, pos) == "1" then count = count + 1 end
end
return count
end
-- Print pernicious numbers in range if two arguments provided, or
function pernicious (x, y) -- the first 'x' if only one argument.
if y then
for n = x, y do
if isPrime(popCount(n)) then io.write(n .. " ") end
end
else
local n, count = 0, 0
while count < x do
if isPrime(popCount(n)) then
io.write(n .. " ")
count = count + 1
end
n = n + 1
end
end
print()
end
-- Main procedure
pernicious(25)
pernicious(888888877, 888888888)
|
return {
version = "1.1",
luaversion = "5.1",
orientation = "orthogonal",
width = 32,
height = 32,
tilewidth = 16,
tileheight = 16,
properties = {},
tilesets = {
{
name = "tiles",
firstgid = 1,
tilewidth = 64,
tileheight = 64,
spacing = 0,
margin = 0,
image = "../../../../tools/tiled/dont_starve/tiles.png",
imagewidth = 512,
imageheight = 128,
properties = {},
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "BG_TILES",
x = 0,
y = 0,
width = 32,
height = 32,
visible = true,
opacity = 1,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 7, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 7, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
{
type = "objectgroup",
name = "FG_OBJECTS",
visible = true,
opacity = 1,
properties = {},
objects = {
{
name = "",
type = "campfire",
shape = "rectangle",
x = 256,
y = 48,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "campfire",
shape = "rectangle",
x = 240,
y = 464,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "campfire",
shape = "rectangle",
x = 112,
y = 128,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "campfire",
shape = "rectangle",
x = 112,
y = 400,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "campfire",
shape = "rectangle",
x = 400,
y = 400,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "spawnpoint",
shape = "rectangle",
x = 271,
y = 235,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "campfire",
shape = "rectangle",
x = 400,
y = 128,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 176,
y = 64,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 336,
y = 384,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 320,
y = 112,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 112,
y = 288,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 16,
y = 144,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 240,
y = 192,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "rabbithole",
shape = "rectangle",
x = 108,
y = 154,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "rabbithole",
shape = "rectangle",
x = 396,
y = 154,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 165,
y = 116,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "sapling",
shape = "rectangle",
x = 28,
y = 458,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 348,
y = 506,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "firepit",
shape = "rectangle",
x = 444,
y = 282,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "sapling",
shape = "rectangle",
x = 332,
y = 266,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 464,
y = 357,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "rabbithole",
shape = "rectangle",
x = 108,
y = 426,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 436,
y = 373,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 334,
y = 487,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "sapling",
shape = "rectangle",
x = 412,
y = 234,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 300,
y = 346,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "firepit",
shape = "rectangle",
x = 44,
y = 282,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 348,
y = 90,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "rabbithole",
shape = "rectangle",
x = 396,
y = 426,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "sapling",
shape = "rectangle",
x = 124,
y = 74,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "torch",
shape = "rectangle",
x = 204,
y = 290,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "grass",
shape = "rectangle",
x = 140,
y = 330,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "skeleton",
shape = "rectangle",
x = 227,
y = 288,
width = 0,
height = 0,
visible = true,
properties = {}
},
{
name = "",
type = "backpack",
shape = "rectangle",
x = 216,
y = 311,
width = 0,
height = 0,
visible = true,
properties = {
["scenario"] = "packloot_nightmare"
}
},
{
name = "",
type = "diviningrodstart",
shape = "rectangle",
x = 173,
y = 204,
width = 0,
height = 0,
visible = true,
properties = {}
}
}
}
}
}
|
--
-- Adapted from
-- Tweener's easing functions (Penner's Easing Equations)
-- and http://code.google.com/p/tweener/ (jstweener javascript version)
--
--[[
Disclaimer for Robert Penner's Easing Equations license:
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright © 2001 Robert Penner
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
-- For all easing functions:
-- t = elapsed time
-- b = begin
-- c = change == ending - beginning
-- d = duration (total time)
-- file was auto-formatted and converted to be more Luau friendly
local function linear(t, b, c, d)
return c * t / d + b
end
local function inQuad(t, b, c, d)
t = t / d
return c * math.pow(t, 2) + b
end
local function outQuad(t, b, c, d)
t = t / d
return -c * t * (t - 2) + b
end
local function inOutQuad(t, b, c, d)
t = t / d * 2
if t < 1 then
return c / 2 * math.pow(t, 2) + b
else
return -c / 2 * ((t - 1) * (t - 3) - 1) + b
end
end
local function outInQuad(t, b, c, d)
if t < d / 2 then
return outQuad(t * 2, b, c / 2, d)
else
return inQuad((t * 2) - d, b + c / 2, c / 2, d)
end
end
local function inCubic(t, b, c, d)
t = t / d
return c * math.pow(t, 3) + b
end
local function outCubic(t, b, c, d)
t = t / d - 1
return c * (math.pow(t, 3) + 1) + b
end
local function inOutCubic(t, b, c, d)
t = t / d * 2
if t < 1 then
return c / 2 * t * t * t + b
else
t = t - 2
return c / 2 * (t * t * t + 2) + b
end
end
local function outInCubic(t, b, c, d)
if t < d / 2 then
return outCubic(t * 2, b, c / 2, d)
else
return inCubic((t * 2) - d, b + c / 2, c / 2, d)
end
end
local function inQuart(t, b, c, d)
t = t / d
return c * math.pow(t, 4) + b
end
local function outQuart(t, b, c, d)
t = t / d - 1
return -c * (math.pow(t, 4) - 1) + b
end
local function inOutQuart(t, b, c, d)
t = t / d * 2
if t < 1 then
return c / 2 * math.pow(t, 4) + b
else
t = t - 2
return -c / 2 * (math.pow(t, 4) - 2) + b
end
end
local function outInQuart(t, b, c, d)
if t < d / 2 then
return outQuart(t * 2, b, c / 2, d)
else
return inQuart((t * 2) - d, b + c / 2, c / 2, d)
end
end
local function inQuint(t, b, c, d)
t = t / d
return c * math.pow(t, 5) + b
end
local function outQuint(t, b, c, d)
t = t / d - 1
return c * (math.pow(t, 5) + 1) + b
end
local function inOutQuint(t, b, c, d)
t = t / d * 2
if t < 1 then
return c / 2 * math.pow(t, 5) + b
else
t = t - 2
return c / 2 * (math.pow(t, 5) + 2) + b
end
end
local function outInQuint(t, b, c, d)
if t < d / 2 then
return outQuint(t * 2, b, c / 2, d)
else
return inQuint((t * 2) - d, b + c / 2, c / 2, d)
end
end
local function inSine(t, b, c, d)
return -c * math.cos(t / d * (math.pi / 2)) + c + b
end
local function outSine(t, b, c, d)
return c * math.sin(t / d * (math.pi / 2)) + b
end
local function inOutSine(t, b, c, d)
return -c / 2 * (math.cos(math.pi * t / d) - 1) + b
end
local function outInSine(t, b, c, d)
if t < d / 2 then
return outSine(t * 2, b, c / 2, d)
else
return inSine((t * 2) - d, b + c / 2, c / 2, d)
end
end
local function inExpo(t, b, c, d)
if t == 0 then
return b
else
return c * math.pow(2, 10 * (t / d - 1)) + b - c * 0.001
end
end
local function outExpo(t, b, c, d)
if t == d then
return b + c
else
return c * 1.001 * (-math.pow(2, -10 * t / d) + 1) + b
end
end
local function inOutExpo(t, b, c, d)
if t == 0 then
return b
end
if t == d then
return b + c
end
t = t / d * 2
if t < 1 then
return c / 2 * math.pow(2, 10 * (t - 1)) + b - c * 0.0005
else
t = t - 1
return c / 2 * 1.0005 * (-math.pow(2, -10 * t) + 2) + b
end
end
local function outInExpo(t, b, c, d)
if t < d / 2 then
return outExpo(t * 2, b, c / 2, d)
else
return inExpo((t * 2) - d, b + c / 2, c / 2, d)
end
end
local function inCirc(t, b, c, d)
t = t / d
return (-c * (math.sqrt(1 - math.pow(t, 2)) - 1) + b)
end
local function outCirc(t, b, c, d)
t = t / d - 1
return (c * math.sqrt(1 - math.pow(t, 2)) + b)
end
local function inOutCirc(t, b, c, d)
t = t / d * 2
if t < 1 then
return -c / 2 * (math.sqrt(1 - t * t) - 1) + b
else
t = t - 2
return c / 2 * (math.sqrt(1 - t * t) + 1) + b
end
end
local function outInCirc(t, b, c, d)
if t < d / 2 then
return outCirc(t * 2, b, c / 2, d)
else
return inCirc((t * 2) - d, b + c / 2, c / 2, d)
end
end
local function inElastic(t, b, c, d, a, p)
if t == 0 then
return b
end
t = t / d
if t == 1 then
return b + c
end
if not p then
p = d * 0.3
end
local s
if not a or a < math.abs(c) then
a = c
s = p / 4
else
s = p / (2 * math.pi) * math.asin(c / a)
end
t = t - 1
return -(a * math.pow(2, 10 * t) * math.sin((t * d - s) * (2 * math.pi) / p)) + b
end
-- a: amplitud
-- p: period
local function outElastic(t, b, c, d, a, p)
if t == 0 then
return b
end
t = t / d
if t == 1 then
return b + c
end
if not p then
p = d * 0.3
end
local s
if not a or a < math.abs(c) then
a = c
s = p / 4
else
s = p / (2 * math.pi) * math.asin(c / a)
end
return a * math.pow(2, -10 * t) * math.sin((t * d - s) * (2 * math.pi) / p) + c + b
end
-- p = period
-- a = amplitud
local function inOutElastic(t, b, c, d, a, p)
if t == 0 then
return b
end
t = t / d * 2
if t == 2 then
return b + c
end
if not p then
p = d * (0.3 * 1.5)
end
if not a then
a = 0
end
local s
if not a or a < math.abs(c) then
a = c
s = p / 4
else
s = p / (2 * math.pi) * math.asin(c / a)
end
if t < 1 then
t = t - 1
return -0.5 * (a * math.pow(2, 10 * t) * math.sin((t * d - s) * (2 * math.pi) / p)) + b
else
t = t - 1
return a * math.pow(2, -10 * t) * math.sin((t * d - s) * (2 * math.pi) / p) * 0.5 + c + b
end
end
-- a: amplitud
-- p: period
local function outInElastic(t, b, c, d, a, p)
if t < d / 2 then
return outElastic(t * 2, b, c / 2, d, a, p)
else
return inElastic((t * 2) - d, b + c / 2, c / 2, d, a, p)
end
end
local function inBack(t, b, c, d, s)
if not s then
s = 1.70158
end
t = t / d
return c * t * t * ((s + 1) * t - s) + b
end
local function outBack(t, b, c, d, s)
if not s then
s = 1.70158
end
t = t / d - 1
return c * (t * t * ((s + 1) * t + s) + 1) + b
end
local function inOutBack(t, b, c, d, s)
if not s then
s = 1.70158
end
s = s * 1.525
t = t / d * 2
if t < 1 then
return c / 2 * (t * t * ((s + 1) * t - s)) + b
else
t = t - 2
return c / 2 * (t * t * ((s + 1) * t + s) + 2) + b
end
end
local function outInBack(t, b, c, d, s)
if t < d / 2 then
return outBack(t * 2, b, c / 2, d, s)
else
return inBack((t * 2) - d, b + c / 2, c / 2, d, s)
end
end
local function outBounce(t, b, c, d)
t = t / d
if t < 1 / 2.75 then
return c * (7.5625 * t * t) + b
elseif t < 2 / 2.75 then
t = t - (1.5 / 2.75)
return c * (7.5625 * t * t + 0.75) + b
elseif t < 2.5 / 2.75 then
t = t - (2.25 / 2.75)
return c * (7.5625 * t * t + 0.9375) + b
else
t = t - (2.625 / 2.75)
return c * (7.5625 * t * t + 0.984375) + b
end
end
local function inBounce(t, b, c, d)
return c - outBounce(d - t, 0, c, d) + b
end
local function inOutBounce(t, b, c, d)
if t < d / 2 then
return inBounce(t * 2, 0, c, d) * 0.5 + b
else
return outBounce(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b
end
end
local function outInBounce(t, b, c, d)
if t < d / 2 then
return outBounce(t * 2, b, c / 2, d)
else
return inBounce((t * 2) - d, b + c / 2, c / 2, d)
end
end
local function port(f)
return function(alpha)
return f(alpha, 0, 1, 1)
end
end
return {
linear = port(linear),
quad_in = port(inQuad),
quad_out = port(outQuad),
quad_in_out = port(inOutQuad),
quad_out_in = port(outInQuad),
cubic_in = port(inCubic),
cubic_out = port(outCubic),
cubic_in_out = port(inOutCubic),
cubic_out_in = port(outInCubic),
quart_in = port(inQuart),
quart_out = port(outQuart),
quart_in_out = port(inOutQuart),
quart_out_in = port(outInQuart),
quint_in = port(inQuint),
quint_out = port(outQuint),
quint_in_out = port(inOutQuint),
quint_out_in = port(outInQuint),
sine_in = port(inSine),
sine_out = port(outSine),
sine_in_out = port(inOutSine),
sine_out_in = port(outInSine),
expo_in = port(inExpo),
expo_out = port(outExpo),
expo_in_out = port(inOutExpo),
expo_out_in = port(outInExpo),
circ_in = port(inCirc),
circ_out = port(outCirc),
circ_in_out = port(inOutCirc),
circ_out_in = port(outInCirc),
elastic_in = port(inElastic),
elastic_out = port(outElastic),
elastic_in_out = port(inOutElastic),
elastic_out_in = port(outInElastic),
back_in = port(inBack),
back_out = port(outBack),
back_in_out = port(inOutBack),
back_out_in = port(outInBack),
bounce_in = port(inBounce),
bounce_out = port(outBounce),
bounce_in_out = port(inOutBounce),
bounce_out_in = port(outInBounce),
}
|
object_mobile_dressed_tatooine_opening_brok = object_mobile_shared_dressed_tatooine_opening_brok:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_tatooine_opening_brok, "object/mobile/dressed_tatooine_opening_brok.iff")
|
---------------------------------------------------------------------------------------------------------
-- Distributed request arguments helper for Tundrawolf
-- Author: aimingoo@wandoujia.com
-- Copyright (c) 2015.11
--
-- parse request body_data and merge into search arguments object
---------------------------------------------------------------------------------------------------------
local JSON_decode = require('cjson').decode
-- mix/copy fields from ref to self
-- *) code from lib/Distributed.lua
local function mix(self, ref, expanded)
if ref == nil then return self end
if type(ref) == 'function' then return expanded and ref or nil end
if type(ref) ~= 'table' then return ref end
self = (type(self) == 'table') and self or {}
for key, value in pairs(ref) do
self[key] = mix(self[key], value, expanded)
end
return self
end
local decoder = {
["application/json"] = function(dataString)
local ok, result = pcall(JSON_decode, dataString)
if ok then return result end
end,
["application/x-www-form-urlencoded"] = function(dataString)
return ngx.decode_args(dataString)
end
}
local defaultContentType = "application/x-www-form-urlencoded";
local tryDefaultDecoder = function(dataString) -- try decode as urlencoded
local maxNameLength = 25 -- argName max-length is 25-1
for i = 1, math.min(dataString:len(), maxNameLength) do
if dataString:byte(i) == 61 then -- char '='
return decoder[defaultContentType](dataString)
end
end
end
local function parseRequestData()
local uri_args = ngx.req.get_uri_args()
if ngx.var.request_method == 'GET' then return uri_args end -- or ngx.var.args
-- local contentType = ngx.header['content_type'] -- error, will access response header
-- Context-Type in RFC, it's "a single type/subtype, followed by optional parameters", parameter schema: *( ";" parameter )
-- *) @see http://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.14.17
-- *) @see http://greenbytes.de/tech/webdav/rfc2616.html#media.types
local contentType, mixin = ngx.var.content_type, true
local arr = split(contentType, '%s*;%s*')
if #arr > 1 then
contentType = table.remove(arr, 1)
local parameter = ngx.decode_args(table.concat(arr, '&'))
if parameter.mixin then
mixin = tostring(parameter.mixin):lower() ~= 'false' -- else 'true' or otherwise default
end
end
local decode = not contentType and tryDefaultDecoder or decoder[string.lower(contentType)]
if not decode then return uri_args end
ngx.req.read_body()
if not ngx.var.request_body then return uri_args end
local args = decode(ngx.var.request_body)
return mixin and mix(uri_args, args) or args
end
return {
parse = parseRequestData
} |
--Dx Functions
local dxDrawImage = dxDrawImageExt
local dxDrawText = dxDrawText
local dxDrawRectangle = dxDrawRectangle
local dxSetRenderTarget = dxSetRenderTarget
local dxGetTextWidth = dxGetTextWidth
local dxSetBlendMode = dxSetBlendMode
local dxCreateRenderTarget = dxCreateRenderTarget
--DGS Functions
local dgsSetType = dgsSetType
local dgsGetType = dgsGetType
local dgsSetParent = dgsSetParent
local dgsSetData = dgsSetData
local applyColorAlpha = applyColorAlpha
local dgsTranslate = dgsTranslate
local dgsAttachToTranslation = dgsAttachToTranslation
local dgsAttachToAutoDestroy = dgsAttachToAutoDestroy
local calculateGuiPositionSize = calculateGuiPositionSize
local dgsCreateTextureFromStyle = dgsCreateTextureFromStyle
--Utilities
local triggerEvent = triggerEvent
local createElement = createElement
local assert = assert
local tonumber = tonumber
local loadstring = loadstring
local type = type
local setmetatable = setmetatable
local setfenv = setfenv
local lerp = math.lerp
local tableSort = table.sort
local tableInsert = table.insert
local tableRemove = table.remove
local tableRemoveItemFromArray = table.removeItemFromArray
local utf8Len = utf8.len
sortFunctions = {}
self = false
mouseButtonOrder = {
left=1,
middle=2,
right=3,
}
--[[
Selection Mode
1-> Row Selection
2-> Column Selection
3-> Cell Selection
]]
function dgsCreateGridList(x,y,w,h,relative,parent,columnHeight,bgColor,columnTextColor,columnColor,rownorc,rowhovc,rowselc,bgImage,columnImage,rownori,rowhovi,rowseli)
local __x,__y,__w,__h = tonumber(x),tonumber(y),tonumber(w),tonumber(h)
if not __x then error(dgsGenAsrt(x,"dgsCreateGridList",1,"number")) end
if not __y then error(dgsGenAsrt(y,"dgsCreateGridList",2,"number")) end
if not __w then error(dgsGenAsrt(w,"dgsCreateGridList",3,"number")) end
if not __h then error(dgsGenAsrt(h,"dgsCreateGridList",4,"number")) end
local style = styleSettings.gridlist
local relative = relative or false
local scbThick = style.scrollBarThick
local columnHeight = tonumber(columnHeight) or style.columnHeight
local rownorc = rownorc or style.rowColor[1]
local rowhovc = rowhovc or style.rowColor[2]
local rowselc = rowselc or style.rowColor[3]
local rownori = rownori or dgsCreateTextureFromStyle(style.rowImage[1])
local rowhovi = rowhovi or dgsCreateTextureFromStyle(style.rowImage[2])
local rowseli = rowseli or dgsCreateTextureFromStyle(style.rowImage[3])
local gridlist = createElement("dgs-dxgridlist")
dgsSetType(gridlist,"dgs-dxgridlist")
dgsSetParent(gridlist,parent,true,true)
dgsElementData[gridlist] = {
autoSort = true,
backgroundOffset = style.backgroundOffset,
bgImage = bgImage or dgsCreateTextureFromStyle(style.bgImage),
bgColor = bgColor or style.bgColor,
colorcoded = false,
clip = true,
columnColor = columnColor or style.columnColor,
columnData = {},
columnHeight = columnHeight,
columnImage = columnImage or dgsCreateTextureFromStyle(style.columnImage),
columnMoveOffset = 0,
columnMoveOffsetTemp = 0,
columnTextColor = columnTextColor or style.columnTextColor,
columnTextPosOffset = {0,0},
columnTextSize = style.columnTextSize,
columnOffset = style.columnOffset,
columnRelative = true,
columnShadow = false,
defaultColumnOffset = style.defaultColumnOffset,
enableNavigation = true,
font = style.font or systemFont,
guiCompat = false,
itemClick = {},
lastSelectedItem = {1,1},
leading = 0,
mode = false,
mouseSelectButton = {true,false,false},
mouseWheelScrollBar = false,--false:vertical; true:horizontal
moveHardness = {0.1,0.9},
moveType = 0, --0 for wheel, 1 For scroll bar
multiSelection = false,
nextRenderSort = false,
preSelect = {},
rowColor = {rownorc,rowhovc,rowselc}, --Normal/Hover/Selected
rowData = {},
rowHeight = style.rowHeight,
rowImage = {rownori,rowhovi,rowseli}, --Normal/Hover/Selected
rowMoveOffset = 0,
rowMoveOffsetTemp = 0,
rowTextSize = style.rowTextSize,
rowTextColor = style.rowTextColor,
rowTextPosOffset = {0,0},
rowSelect = {},
rowShadow = false,
scrollBarThick = scbThick,
scrollBarLength = {},
scrollBarState = {nil,nil},
scrollFloor = {false,false},--move offset ->int or float
scrollSize = 60, --60 pixels
sectionColumnOffset = style.sectionColumnOffset,
sectionFont = systemFont,
selectedColumn = -1,
selectionMode = 1,
sortColumn = false,
sortEnabled = true,
defaultSortFunctions = {"greaterUpper","greaterLower"},
}
dgsGridListSetSortFunction(gridlist,sortFunctions_upper)
dgsAttachToTranslation(gridlist,resourceTranslation[sourceResource or resource])
dgsElementData[gridlist].configNextFrame = false
calculateGuiPositionSize(gridlist,__x,__y,relative,__w,__h,relative,true)
local aSize = dgsElementData[gridlist].absSize
local abx,aby = aSize[1],aSize[2]
local columnRender,rowRender
if abx*columnHeight ~= 0 then
columnRender,err = dxCreateRenderTarget(abx,columnHeight,true,gridlist)
if columnRender ~= false then
dgsAttachToAutoDestroy(columnRender,gridlist,-1)
else
outputDebugString(err)
end
end
if abx*(aby-columnHeight-scbThick) ~= 0 then
rowRender,err = dxCreateRenderTarget(abx,aby-columnHeight-scbThick,true,gridlist)
if rowRender ~= false then
dgsAttachToAutoDestroy(rowRender,gridlist,-2)
else
outputDebugString(err)
end
end
dgsSetData(gridlist,"renderTarget",{columnRender,rowRender})
local scrollbar1 = dgsCreateScrollBar(abx-scbThick,0,scbThick,aby-scbThick,false,false,gridlist)
dgsSetData(scrollbar1,"attachedToParent",gridlist)
local scrollbar2 = dgsCreateScrollBar(0,aby-scbThick,abx-scbThick,scbThick,true,false,gridlist)
dgsSetData(scrollbar2,"attachedToParent",gridlist)
dgsSetVisible(scrollbar1,false)
dgsSetVisible(scrollbar2,false)
dgsSetData(scrollbar1,"length",{0,true})
dgsSetData(scrollbar2,"length",{0,true})
dgsSetData(scrollbar1,"multiplier",{1,false})
dgsSetData(scrollbar2,"multiplier",{1,false})
dgsSetData(scrollbar1,"minLength",10)
dgsSetData(scrollbar2,"minLength",10)
addEventHandler("onDgsElementScroll",scrollbar1,checkGLScrollBar,false)
addEventHandler("onDgsElementScroll",scrollbar2,checkGLScrollBar,false)
dgsSetData(gridlist,"scrollbars",{scrollbar1,scrollbar2})
dgsSetData(gridlist,"FromTo",{1,0})
triggerEvent("onDgsCreate",gridlist,sourceResource)
return gridlist
end
function dgsGridListSetSelectionMode(gridlist,mode)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetSelectionMode",1,"dgs-dxgridlist")) end
if mode == 1 or mode == 2 or mode == 3 then
return dgsSetData(gridlist,"selectionMode",mode)
end
return false
end
function dgsGridListGetSelectionMode(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetSelectionMode",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].selectionMode
end
function dgsGridListSetMultiSelectionEnabled(gridlist,multiSelection)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetMultiSelectionEnabled",1,"dgs-dxgridlist")) end
return dgsSetData(gridlist,"multiSelection",multiSelection and true or false)
end
function dgsGridListGetMultiSelectionEnabled(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetMultiSelectionEnabled",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].multiSelection
end
function dgsGridListGetNavigationEnabled(gridlist,state)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetNavigationEnabled",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].enableNavigation
end
function dgsGridListSetNavigationEnabled(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetNavigationEnabled",1,"dgs-dxgridlist")) end
return dgsSetData(gridlist,"enableNavigation",state)
end
function dgsGridListResetScrollBarPosition(gridlist,vertical,horizontal)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListResetScrollBarPosition",1,"dgs-dxgridlist")) end
local scrollbars = dgsElementData[gridlist].scrollbars
if not vertical then
dgsScrollBarSetScrollPosition(scrollbars[1],0)
end
if not horizontal then
dgsScrollBarSetScrollPosition(scrollbars[2],0)
end
return true
end
function dgsGridListGetScrollBar(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetScrollBar",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].scrollbars
end
function dgsGridListGetScrollPosition(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetScrollPosition",1,"dgs-dxgridlist")) end
local scb = dgsElementData[gridlist].scrollbars
return dgsScrollBarGetScrollPosition(scb[1]),dgsScrollBarGetScrollPosition(scb[2])
end
function dgsGridListSetScrollPosition(gridlist,vertical,horizontal)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetScrollPosition",1,"dgs-dxgridlist")) end
if vertical and not (type(vertical) == "number" and vertical>= 0 and vertical <= 100) then error(dgsGenAsrt(vertical,"dgsGridListSetScrollPosition",2,"nil/number","0~100")) end
if horizontal and not (type(horizontal) == "number" and horizontal>= 0 and horizontal <= 100) then error(dgsGenAsrt(horizontal,"dgsGridListSetScrollPosition",3,"nil/number","0~100")) end
local scb = dgsElementData[gridlist].scrollbars
local state1,state2 = true,true
if vertical then
state1 = dgsScrollBarSetScrollPosition(scb[1],vertical)
end
if horizontal then
state2 = dgsScrollBarSetScrollPosition(scb[2],horizontal)
end
return state1 and state2
end
--Make compatibility for GUI
function dgsGridListGetHorizontalScrollPosition(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetHorizontalScrollPosition",1,"dgs-dxgridlist")) end
local scb = dgsElementData[gridlist].scrollbars
return dgsScrollBarGetScrollPosition(scb[2])
end
function dgsGridListSetHorizontalScrollPosition(gridlist,horizontal)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetHorizontalScrollPosition",1,"dgs-dxgridlist")) end
if not (type(horizontal) == "number" and horizontal>= 0 and horizontal <= 100) then error(dgsGenAsrt(horizontal,"dgsGridListSetHorizontalScrollPosition",2,"nil/number","0~100")) end
local scb = dgsElementData[gridlist].scrollbars
return dgsScrollBarSetScrollPosition(scb[2],horizontal)
end
function dgsGridListGetVerticalScrollPosition(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetVerticalScrollPosition",1,"dgs-dxgridlist")) end
local scb = dgsElementData[gridlist].scrollbars
return dgsScrollBarGetScrollPosition(scb[1])
end
function dgsGridListSetVerticalScrollPosition(gridlist,vertical)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetVerticalScrollPosition",1,"dgs-dxgridlist")) end
if not (type(vertical) == "number" and vertical>= 0 and vertical <= 100) then error(dgsGenAsrt(vertical,"dgsGridListSetVerticalScrollPosition",2,"nil/number","0~100")) end
local scb = dgsElementData[gridlist].scrollbars
return dgsScrollBarSetScrollPosition(scb[1],vertical)
end
function dgsAttachToGridList(element,gridlist,r,c)
if not isElement(element) then error(dgsGenAsrt(element,"dgsAttachToGridList",1,"element")) end
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsAttachToGridList",2,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsAttachToGridList",3,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsAttachToGridList",4,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
dgsDetachElements(element)
dgsSetParent(element,gridlist)
rData[r][c][10] = rData[r][c][10] or {}
tableInsert(rData[r][c][10],element)
return dgsSetData(element,"attachedToGridList",{gridlist,r,c})
end
return false
end
function dgsGetAttachedGridList(element)
if not isElement(element) then error(dgsGenAsrt(element,"dgsGetAttachedGridList",1,"element")) end
local attachData = dgsElementData[element].attachedToGridList
if attachData then
return attachData[1],attachData[2],attachData[3]
end
return false,false,false
end
function dgsDetachFromGridList(element)
if not isElement(element) then error(dgsGenAsrt(element,"dgsDetachFromGridList",1,"element")) end
local attachData = dgsElementData[element].attachedToGridList
if not attachData then return false end
local gridlist,r,c = attachData[1],attachData[2],attachData[3]
local rData = dgsElementData[gridlist].rowData
if rData[r] and rData[r][c] then
rData[r][c][10] = rData[r][c][10] or {}
tableRemoveItemFromArray(rData[r][c][10],element)
end
return dgsSetData(element,"attachedToGridList",nil)
end
-----------------------------Sort
sortFunctions.greaterUpper = function(...)
local arg = {...}
local column = dgsElementData[self].sortColumn
return arg[1][column][1] < arg[2][column][1]
end
sortFunctions.greaterLower = function(...)
local arg = {...}
local column = dgsElementData[self].sortColumn
return arg[1][column][1] > arg[2][column][1]
end
sortFunctions.numGreaterUpper = function(...)
local arg = {...}
local column = dgsElementData[self].sortColumn
local a = tonumber(arg[1][column][1]) or arg[1][column][1]
local b = tonumber(arg[2][column][1]) or arg[2][column][1]
return a < b
end
sortFunctions.numGreaterLower = function(...)
local arg = {...}
local column = dgsElementData[self].sortColumn
local a = tonumber(arg[1][column][1]) or arg[1][column][1]
local b = tonumber(arg[2][column][1]) or arg[2][column][1]
return a > b
end
sortFunctions.longerUpper = function(...)
local arg = {...}
local column = dgsElementData[self].sortColumn
return utf8Len(arg[1][column][1]) < utf8Len(arg[2][column][1])
end
sortFunctions.longerLower = function(...)
local arg = {...}
local column = dgsElementData[self].sortColumn
return utf8Len(arg[1][column][1]) > utf8Len(arg[2][column][1])
end
function dgsGridListSetSortFunction(gridlist,str)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetSortFunction",1,"dgs-dxgridlist")) end
local fnc,err
if type(str) == "string" then
fnc,err = loadstring(str)
if not fnc then error("Bad Argument @'dgsGridListSetSortFunction' at argument 1, failed to load the function:\n"..err) end
local newfenv = {}
setmetatable(newfenv, {__index = _G})
newfenv.self = gridlist
newfenv.dgsElementData = dgsElementData
setfenv(fnc,newfenv)
elseif type(str) == "function" then
fnc = str
local newfenv = {}
setmetatable(newfenv, {__index = _G})
newfenv.self = gridlist
newfenv.dgsElementData = dgsElementData
setfenv(fnc,newfenv)
end
if dgsElementData[gridlist].autoSort then
dgsElementData[gridlist].nextRenderSort = true
end
return dgsSetData(gridlist,"sortFunction",fnc)
end
function dgsGridListSetAutoSortEnabled(gridlist,state)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetAutoSortEnabled",1,"dgs-dxgridlist")) end
local state = state and true or false
return dgsSetData(gridlist,"autoSort",state)
end
function dgsGridListGetAutoSortEnabled(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetAutoSortEnabled",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].autoSort
end
function dgsGridListSetSortEnabled(gridlist,state)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetSortEnabled",1,"dgs-dxgridlist")) end
local state = state and true or false
return dgsSetData(gridlist,"sortEnabled",state)
end
function dgsGridListGetSortEnabled(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetSortEnabled",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].sortEnabled
end
function dgsGridListSetSortColumn(gridlist,sortColumn)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetSortColumn",1,"dgs-dxgridlist")) end
local columnData = dgsElementData[gridlist].columnData
if columnData then
if dgsElementData[gridlist].autoSort then
dgsElementData[gridlist].nextRenderSort = true
end
return dgsSetData(gridlist,"sortColumn",sortColumn)
end
return false
end
function dgsGridListGetSortColumn(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetSortColumn",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].sortColumn
end
function dgsGridListSort(gridlist,sortColumn)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSort",1,"dgs-dxgridlist")) end
local sortColumn = tonumber(sortColumn) or dgsElementData[gridlist].sortColumn
if sortColumn then
local rowData = dgsElementData[gridlist].rowData
local sortFunction = dgsElementData[gridlist].sortFunction
tableSort(rowData,sortFunction)
dgsElementData[gridlist].rowData = rowData
return true
end
return false
end
function dgsGridListScrollTo(gridlist,row,column,smoothMove)
if dgsElementData[gridlist].configNextFrame then configGridList(gridlist) end
if row then
local eleData = dgsElementData[gridlist]
local rowData = eleData.rowData
local rowCounts = #rowData
if row >=1 and row <= #rowData then
local scb = eleData.scrollbars[2]
local rowHeight = eleData.rowHeight
local leading = eleData.leading
local rowHeightLeadingTemp = rowHeight+leading
local sy = eleData.absSize[2]
local columnHeight = eleData.columnHeight
local scbThickH = dgsElementData[scb].visible and eleData.scrollBarThick or 0
local gridListRange = sy-scbThickH-columnHeight
local rowMoveOffset = eleData.rowMoveOffset
local rowBeforeHeight = (row-1)*rowHeightLeadingTemp
local rowFullHeight = rowBeforeHeight+rowHeight
if rowBeforeHeight+rowMoveOffset < 0 then
local scrollPos = rowBeforeHeight/(rowCounts*rowHeightLeadingTemp-gridListRange)*100
dgsGridListSetScrollPosition(gridlist,scrollPos)
elseif rowFullHeight+rowMoveOffset > gridListRange then
local scrollPos = (rowFullHeight-gridListRange)/(rowCounts*rowHeightLeadingTemp-gridListRange)*100
dgsGridListSetScrollPosition(gridlist,scrollPos)
end
end
end
if column then
local eleData = dgsElementData[gridlist]
local columnData = eleData.columnData
local columnCounts = #columnData
if column >=1 and column <= #columnData then
local scb = eleData.scrollbars[1]
local sx = eleData.absSize[1]
local columnOffset = eleData.columnOffset
local scbThickV = dgsElementData[scb].visible and eleData.scrollBarThick or 0
local gridListRange = sx-scbThickV
local columnMoveOffset = eleData.columnMoveOffset
local columnFullWidth = dgsGridListGetColumnAllWidth(gridlist,column,false)
local columnBeforeWidth = columnFullWidth-dgsGridListGetColumnWidth(gridlist,column,false)
local allWidth = dgsGridListGetColumnAllWidth(gridlist,#columnData)
if columnBeforeWidth+columnMoveOffset+columnOffset < 0 then
local scrollPos = columnBeforeWidth/(allWidth-gridListRange)*100
dgsGridListSetScrollPosition(gridlist,_,scrollPos)
elseif columnFullWidth+columnMoveOffset+columnOffset > sx then
local scrollPos = (columnFullWidth-gridListRange)/(allWidth-gridListRange)*100
dgsGridListSetScrollPosition(gridlist,_,scrollPos)
end
end
end
end
-----------------------------Column
--[[
columnData Struct:
1 2 N
column1 column2 columnN
{{text1,Width,AllWidthFront,Alignment,color,colorcoded,sizex,sizey,font}, {text1,Width,AllWidthFront,alignment,color,colorcoded,sizex,sizey,font}, {text1,Width,AllWidthFront,alignment,color,colorcoded,sizex,sizey,font}, ...}
]]
function dgsGridListAddColumn(gridlist,name,len,pos,alignment)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListAddColumn",1,"dgs-dxgridlist")) end
if not (type(len) == "number") then error(dgsGenAsrt(len,"dgsGridListAddColumn",3,"number")) end
local eleData = dgsElementData[gridlist]
local columnData = eleData.columnData
local columnDataCount = #columnData
local _name
pos = tonumber(pos) or columnDataCount+1
pos = pos > columnDataCount+1 and columnDataCount+1 or pos
local aSize = eleData.absSize
local sx,sy = aSize[1],aSize[2]
local scrollBarThick = eleData.scrollBarThick
local multiplier = eleData.columnRelative and sx-scrollBarThick or 1
local oldLen = 0
if columnDataCount > 0 then
oldLen = columnData[columnDataCount][3]+columnData[columnDataCount][2]
end
if type(name) == "table" then
_name = name
name = dgsTranslate(gridlist,name,sourceResource)
end
local columnTable = {
tostring(name),
len,
oldLen,
HorizontalAlign[alignment] or "left",
_translationText = _name,
}
tableInsert(columnData,pos,columnTable)
local columnTextSize = eleData.columnTextSize
local columnTextColor = eleData.columnTextColor
local colorcoded = eleData.colorcoded
for i=pos+1,columnDataCount+1 do
columnData[i] = {
columnData[i][1],
columnData[i][2],
dgsGridListGetColumnAllWidth(gridlist,i-1),
columnData[i][4],
columnTextColor,
colorcoded,
columnTextSize[1],
columnTextSize[2],
eleData.font,
}
end
dgsSetData(gridlist,"columnData",columnData)
local rowData = dgsElementData[gridlist].rowData
local rowTxtColor = eleData.rowTextColor
local colorcoded = eleData.colorcoded
local scale = eleData.rowTextSize
local font = eleData.font
for i=1,#rowData do
rowData[i][pos]= {
"",
rowTxtColor,
colorcoded,
scale[1],
scale[2],
font,
}
end
dgsElementData[gridlist].configNextFrame = true
return pos
end
function dgsGridListSetColumnFont(gridlist,c,font,affectRow)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetColumnFont",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetColumnFont",2,"number","1~"..cLen, cNInRange and "Out Of Range")) end
local c = c-c%1
if not (fontBuiltIn[font] or dgsGetType(font) == "dx-font") then error(dgsGenAsrt(font,"dgsGridListSetColumnFont",3,"dx-font/string",_,"invalid font")) end
cData[c][9] = font
if affectRow then
local rowData = eleData.rowData
for i=1,#rowData do
rowData[i][c][6] = font
end
end
return true
end
function dgsGridListGetColumnFont(gridlist,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetColumnFont",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetColumnFont",2,"number","1~"..cLen, cNInRange and "Out Of Range")) end
local c = c-c%1
return cData[c][9]
end
function dgsGridListSetColumnAlignment(gridlist,column,alignment)
assert(dgsGetType(gridlist) == "dgs-dxgridlist","Bad argument @dgsGridListSetColumnAlignment at argument 1, expect dgs-dxgridlist got "..dgsGetType(gridlist))
assert(HorizontalAlign[alignment],"Bad argument @dgsGridListSetColumnAlignment at argument 2, except a string among left/center/right got "..type(alignment).."(value:"..tostring(alignment)..")")
end
function dgsGridListGetColumnAlignment(gridlist,column)
assert(dgsGetType(gridlist) == "dgs-dxgridlist","Bad argument @dgsGridListGetColumnAlignment at argument 1, expect dgs-dxgridlist got "..dgsGetType(gridlist))
end
function dgsGridListGetColumnTextSize(gridlist,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetColumnTextSize",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetColumnTextSize",2,"number","1~"..cLen, cNInRange and "Out Of Range")) end
local c = c-c%1
return cData[c][7],cData[c][8]
end
function dgsGridListSetColumnTextSize(gridlist,column,sizeX,sizeY)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetColumnTextSize",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetColumnTextSize",2,"number","1~"..cLen, cNInRange and "Out Of Range")) end
local c = c-c%1
if not (type(sizeX) == "number") then error(dgsGenAsrt(sizeX,"dgsGridListSetColumnTextSize",3,"number")) end
columnData[column][7] = sizeX
columnData[column][8] = sizeY or sizeX
return true
end
function dgsGridListSetColumnRelative(gridlist,relative,transformColumn)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetColumnRelative",1,"dgs-dxgridlist")) end
if not (type(relative) == "boolean") then error(dgsGenAsrt(relative,"dgsGridListSetColumnRelative",2,"bool")) end
local relative = relative and true or false
local transformColumn = transformColumn == false and true or false
dgsSetData(gridlist,"columnRelative",relative)
if transformColumn then
local columnData = dgsElementData[gridlist].columnData
local w,h = dgsGetSize(v,false)
if relative then
for k,v in ipairs(columnData) do
columnData[k][2] = columnData[k][2]/w
columnData[k][3] = columnData[k][3]/w
end
else
for k,v in ipairs(columnData) do
columnData[k][2] = columnData[k][2]*w
columnData[k][3] = columnData[k][3]*w
end
end
end
return true
end
function dgsGridListSetColumnTitle(gridlist,c,name)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetColumnTitle",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetColumnTitle",2,"number","1~"..cLen, cNInRange and "Out Of Range")) end
local c = c-c%1
if cData[c] then
if type(name) == "table" then
cData[c]._translationText = name
name = dgsTranslate(gridlist,name,sourceResource)
else
cData[c]._translationText = nil
end
cData[c][1] = name
dgsSetData(gridlist,"columnData",cData)
end
end
function dgsGridListGetColumnTitle(gridlist,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetColumnTitle",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetColumnTitle",2,"number","1~"..cLen, cNInRange and "Out Of Range")) end
local c = c-c%1
return columnData[c][1]
end
function dgsGridListGetColumnRelative(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetColumnRelative",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].columnRelative
end
function dgsGridListGetColumnCount(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetColumnCount",1,"dgs-dxgridlist")) end
return #(dgsElementData[gridlist].columnData or {})
end
function dgsGridListRemoveColumn(gridlist,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListRemoveColumn",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListRemoveColumn",2,"number","1~"..cLen, cNInRange and "Out Of Range")) end
local c = c-c%1
local oldLen = cData[c][3]
tableRemove(cData,c)
local lastColumnLen = 0
for i=1,cLen do
if i >= c then
cData[i][3] = cData[i][3]-oldLen
lastColumnLen = cData[i][3]+cData[i][2]
end
end
dgsElementData[gridlist].configNextFrame = true
return true
end
function dgsGridListSetColumnHeight(gridlist,columnHeight)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetColumnHeight",1,"dgs-dxgridlist")) end
if not (type(columnHeight) == "number" and columnHeight >= 0) then error(dgsGenAsrt(gridlist,"dgsGridListSetColumnHeight",2,"number","≥0")) end
dgsSetData(gridlist,"columnHeight",columnHeight)
end
function dgsGridListGetColumnHeight(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetColumnHeight",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].columnHeight
end
function dgsGridListSetColumnWidth(gridlist,c,width,relative)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetColumnWidth",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetColumnWidth",2,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c = c-c%1
if not (type(width) == "number") then error(dgsGenAsrt(c,"dgsGridListSetColumnWidth",3,"number")) end
local rlt = eleData.columnRelative
relative = relative == nil and rlt or false
local scbThick = eleData.scrollBarThick
local columnSize = eleData.absSize[1]-scbThick
if rlt then
width = relative and width or width/columnSize
else
width = relative and width*columnSize or width
end
local differ = width-cData[c][2]
cData[c][2] = width
local lastColumnLen = 0
for i=1,cLen do
if i > c then
cData[i][3] = cData[i][3]+differ
lastColumnLen = cData[i][3]+cData[i][2]
end
end
dgsElementData[gridlist].configNextFrame = true
return true
end
function dgsGridListAutoSizeColumn(gridlist,c,additionalLength,relative)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListAutoSizeColumn",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListAutoSizeColumn",2,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c = c-c%1
if not (additionalLength == nil or type(additionalLength) == "number") then error(dgsGenAsrt(c,"dgsGridListAutoSizeColumn",3,"number")) end
if not additionalLength then relative = false end
local font = cData[c][9] or eleData.font
local wid = dxGetTextWidth(columnData[c][1],cData[c][7],font)
local wid = wid+(relative and additionalLength*wid or (additionalLength or 0)+wid)
return dgsGridListSetColumnWidth(gridlist,c,wid,false)
end
--[[
mode Fast(true)/Slow(false)
--]]
function dgsGridListGetColumnAllWidth(gridlist,c,relative,mode)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetColumnAllWidth",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetColumnAllWidth",2,"number","0~"..cLen,cNInRange and "Out Of Range")) end
local c = c-c%1
local columnSize = eleData.absSize[1]-eleData.scrollBarThick
local rlt = eleData.columnRelative
if c > 0 then
if mode then
local data = cData[c][3]+cData[c][2]
if relative then
return rlt and data or data/columnSize
else
return rlt and data*columnSize or data
end
else
local dataLength = 0
for i=1,cLen do
dataLength = dataLength + cData[i][2]
if i == c then
if relative then
return rlt and dataLength or dataLength/columnSize
else
return rlt and dataLength*columnSize or dataLength
end
end
end
end
elseif c == 0 then
return 0
end
return false
end
function dgsGridListGetColumnWidth(gridlist,c,relative)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetColumnWidth",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData = eleData.columnData
local cLen = #cData
if cLen == 0 then return false end
local cIsNum = type(c) == "number"
local cNInRange = cIsNum and not (c >=1 and c <= cLen)
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetColumnWidth",2,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c = c-c%1
local columnSize = eleData.absSize[1]-eleData.scrollBarThick
local rlt = eleData.columnRelative
local data = cData[c][2]
if relative then
return rlt and data or data/columnSize
else
return rlt and data*columnSize or data
end
end
function dgsGridListGetEnterColumn(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetEnterColumn",1,"dgs-dxgridlist")) end
return dgsElementData[gridlist].selectedColumn
end
function dgsGridListClearColumn(gridlist,notResetSelected,notResetScrollBar)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListClearColumn",1,"dgs-dxgridlist")) end
local scrollbars = dgsElementData[gridlist].scrollbars
local rowData = dgsElementData[gridlist].rowData
if not notResetScrollBar then
dgsSetData(scrollbars[2],"length",{0,true})
dgsSetData(scrollbars[2],"position",0)
dgsSetVisible(scrollbars[2],false)
end
if not notResetSelected then
dgsGridListSetSelectedItem(gridlist,-1)
end
for i=1,#rowData do
for a=1,#rowData[i] do
rowData[i][a] = nil
end
end
dgsSetData(gridlist,"columnData",{})
dgsSetData(gridlist,"rowData",rowData)
configGridList(gridlist)
return true
end
-----------------------------Row
--[[
rowData Struct:
-4 -3 -2 -1 0 1 2 ...
columnOffset bgImage hoverable selectable bgColor column1 column2 ...
{
{ columnOffset, {normal,hovering,selected}, true/false, true/false, {normal,hovering,selected}, {text,color,colorcoded,scalex,scaley,font,{image,color,imagex,imagey,imagew,imageh,relative},unhoverable,unselectable,attachedElement}, {text,color,colorcoded,scalex,scaley,font,{image,color,imagex,imagey,imagew,imageh,relative},unhoverable,unselectable,attachedElement }, ... },
{ columnOffset, {normal,hovering,selected}, true/false, true/false, {normal,hovering,selected}, {text,color,colorcoded,scalex,scaley,font,{image,color,imagex,imagey,imagew,imageh,relative},unhoverable,unselectable,attachedElement}, {text,color,colorcoded,scalex,scaley,font,{image,color,imagex,imagey,imagew,imageh,relative},unhoverable,unselectable,attachedElement }, ... },
{ columnOffset, {normal,hovering,selected}, true/false, true/false, {normal,hovering,selected}, {text,color,colorcoded,scalex,scaley,font,{image,color,imagex,imagey,imagew,imageh,relative},unhoverable,unselectable,attachedElement}, {text,color,colorcoded,scalex,scaley,font,{image,color,imagex,imagey,imagew,imageh,relative},unhoverable,unselectable,attachedElement }, ... },
{ the same as preview table },
}
table[i](i<=0) isn't counted in #table
]]
function dgsGridListAddRow(gridlist,r,...)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListAddRow",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local columnData = eleData.columnData
if not (#columnData > 0) then error("Bad argument @dgsGridListAddRow, no columns in the grid list") end
local args = {...}
local rowData = eleData.rowData
r = tonumber(r) or #rowData+1
local rowTable = {
[-4] = eleData.defaultColumnOffset,
[-3] = eleData.rowImage,
[-2] = true,
[-1] = true,
[0] = eleData.rowColor,
}
local rowTxtColor = eleData.rowTextColor
local colorcoded = eleData.colorcoded
local scale = eleData.rowTextSize
for i=1,#eleData.columnData do
local text,_text = args[i]
if type(text) == "table" then
_text = text
text = dgsTranslate(gridlist,text,sourceResource)
end
rowTable[i] = {
tostring(text or ""),
rowTxtColor,
colorcoded,
scale[1],
scale[2],
font,
_translationText=_text,
}
end
tableInsert(rowData,r,rowTable)
dgsElementData[gridlist].configNextFrame = true
return r
end
function dgsGridListInsertRowAfter(gridlist,r,...)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListInsertRowAfter",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local columnData = eleData.columnData
assert(#columnData > 0 ,"Bad argument @dgsGridListInsertRowAfter, no columns in the grid list")
return dgsGridListAddRow(gridlist,r+1,...)
end
function dgsGridListAddRows(gridlist,r,t,isRawData)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListAddRows",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local columnData = eleData.columnData
if not (#columnData > 0) then error("Bad argument @dgsGridListAddRows, no columns in the grid list") end
if not (type(t) == "table") then error(dgsGenAsrt(t,"dgsGridListAddRows",3,"table")) end
local rowData = eleData.rowData
r = tonumber(r) or #rowData
if isRawData then
for i=1,#t do
tableInsert(rowData,r+i,t[i]) --This will skip language check
end
else
for i=1,#t do
local rowTable = {
[-4] = eleData.defaultColumnOffset,
[-3] = eleData.rowImage,
[-2] = true,
[-1] = true,
[0] = eleData.rowColor,
}
local rowTxtColor = eleData.rowTextColor
local colorcoded = eleData.colorcoded
local scale = eleData.rowTextSize
for col=1,#eleData.columnData do
local text,_text = t[i][col]
if type(text) == "table" then
_text = text
text = dgsTranslate(gridlist,text,sourceResource)
end
rowTable[col] = {
tostring(text or ""),
rowTxtColor,
colorcoded,
scale[1],
scale[2],
font,
_translationText=_text,
}
end
tableInsert(rowData,r+i,rowTable)
end
end
dgsElementData[gridlist].configNextFrame = true
return true
end
function dgsGridListGetRowCount(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetRowCount",1,"dgs-dxgridlist")) end
return #dgsElementData[gridlist].rowData
end
function dgsGridListGetRowSelectable(gridlist,r)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetRowSelectable",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetRowSelectable",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
return rData[r] and rData[r][-1] or false
end
function dgsGridListSetRowSelectable(gridlist,r,state)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetRowSelectable",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetRowSelectable",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
if rData[r] then
rData[r][-1] = state and true or false
return true
end
return false
end
function dgsGridListGetRowHoverable(gridlist,r)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetRowHoverable",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetRowHoverable",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
return rData[r] and rData[r][-2] or false
end
function dgsGridListSetRowHoverable(gridlist,r,state)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetRowHoverable",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetRowHoverable",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
if rData[r] then
rData[r][-2] = state and true or false
return true
end
return false
end
function dgsGridListGetRowBackGroundColor(gridlist,r)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetRowBackGroundColor",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetRowBackGroundColor",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
if rData[r] then
return unpack(rData[r][0] or {})
end
return false
end
function dgsGridListSetRowBackGroundColor(gridlist,r,nClr,sClr,cClr)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetRowBackGroundColor",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetRowBackGroundColor",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
if rData[r] then
rData[r][0] = {nClr or white,sClr or nClr,cClr or nClr}
return true
end
return false
end
function dgsGridListGetRowBackGroundImage(gridlist,r)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetRowBackGroundImage",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetRowBackGroundImage",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
return unpack(rData[r][-3])
end
function dgsGridListSetRowBackGroundImage(gridlist,r,nImg,sImg,cImg)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetRowBackGroundImage",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetRowBackGroundImage",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
if nImg ~= nil then
local imgType = dgsGetType(nImg)
if not (imgType == "texture" or imgType == "shader") then error(dgsGenAsrt(nImg,"dgsGridListSetRowBackGroundImage",3,"material")) end
end
if sImg ~= nil then
local imgType = dgsGetType(sImg)
if not (imgType == "texture" or imgType == "shader") then error(dgsGenAsrt(sImg,"dgsGridListSetRowBackGroundImage",4,"material")) end
end
if cImg ~= nil then
local imgType = dgsGetType(cImg)
if not (imgType == "texture" or imgType == "shader") then error(dgsGenAsrt(cImg,"dgsGridListSetRowBackGroundImage",5,"material")) end
end
rData[r][-3] = {nImg,sImg,cImg}
return true
end
function dgsGridListSetRowAsSection(gridlist,row,enabled,enableMouseClickAndSelect)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetRowAsSection",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetRowAsSection",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
if enabled then
rData[r][-4] = eleData.sectionColumnOffset
if not enableMouseClickAndSelect then
rData[r][-2] = false
rData[r][-1] = false
else
rData[r][-2] = true
rData[r][-1] = true
end
else
rData[r][-4] = eleData.defaultColumnOffset
rData[r][-2] = true
rData[r][-1] = true
end
rData[r][-5] = enabled and true or false --Enable Section Mode
return dgsSetData(gridlist,"rowData",rData)
end
function dgsGridListRemoveRow(gridlist,r)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListRemoveRow",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local rData = eleData.rowData
local rLen = #rData
if rLen == 0 then return false end
local rIsNum = type(r) == "number"
local rNInRange = rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListRemoveRow",2,"number","1~"..rLen, rNInRange and "Out Of Range")) end
local r = r-r%1
tableRemove(rowData,r)
dgsElementData[gridlist].configNextFrame = true
return true
end
function dgsGridListClearRow(gridlist,notResetSelected,notResetScrollBar)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListClearRow",1,"dgs-dxgridlist")) end
local scrollbars = dgsElementData[gridlist].scrollbars
if not notResetScrollBar then
dgsSetData(scrollbars[1],"length",{0,true})
dgsSetData(scrollbars[1],"position",0)
dgsSetVisible(scrollbars[1],false)
end
if not notResetSelected then
dgsGridListSetSelectedItem(gridlist,-1)
end
dgsSetData(gridlist,"rowData",{})
configGridList(gridlist)
return true
end
-----------------------------Item
function dgsGridListSetItemData(gridlist,r,c,data,...)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetItemData",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetItemData",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetItemData",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if select("#",...) == 0 then
rData[r][c][-1] = data
return true
else
rData[r][c][-2] = rData[r][c][-2] or {}
rData[r][c][-2][data] = ...
return true
end
return false
end
function dgsGridListGetItemData(gridlist,r,column,key)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetItemData",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetItemData",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetItemData",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if not key then
return rData[r][c][-1]
else
return (rData[r][c][-2] or {})[key] or false
end
return false
end
function dgsGridListSetItemFont(gridlist,r,c,font)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetItemFont",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetItemFont",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetItemFont",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
if not (fontBuiltIn[font] or dgsGetType(font) == "dx-font") then error(dgsGenAsrt(font,"dgsGridListSetItemFont",4,"dx-font/string",_,"invalid font")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
rData[r][c][6] = font
return true
end
return false
end
function dgsGridListGetItemFont(gridlist,r,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetItemFont",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetItemFont",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetItemFont",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
return rData[r][c][6]
end
return false
end
function dgsGridListSetItemTextSize(gridlist,r,c,sizeX,sizeY)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetItemTextSize",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetItemTextSize",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetItemTextSize",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
if not (type(sizeX) == "number") then error(dgsGenAsrt(sizeX,"dgsGridListSetItemTextSize",4,"number")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
rData[r][c][4] = sizeX
rData[r][c][5] = sizeY or sizeX
return true
end
return false
end
function dgsGridListGetItemTextSize(gridlist,r,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetItemTextSize",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetItemTextSize",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetItemTextSize",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
return rData[r][c][4],rData[r][c][5]
end
return false
end
function dgsGridListSetItemSelectable(gridlist,r,c,state)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetItemSelectable",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetItemSelectable",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetItemSelectable",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r] then
rData[r][c][9] = not state or nil
return true
end
return false
end
function dgsGridListGetItemSelectable(gridlist,r,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetItemSelectable",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetItemSelectable",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetItemSelectable",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r] then
return rData[r][c][9] == false
end
return false
end
function dgsGridListSetItemHoverable(gridlist,r,c,state)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetItemHoverable",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetItemHoverable",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetItemHoverable",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
rData[r][c][8] = not state
return true
end
return false
end
function dgsGridListGetItemHoverable(gridlist,r,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetItemHoverable",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetItemHoverable",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetItemHoverable",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
return rData[r][c][8] == false
end
return false
end
function dgsGridListClear(gridlist,clearRow,clearColumn)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListClear",1,"dgs-dxgridlist")) end
clearRow = clearRow ~= false
clearColumn = clearColumn and true or false
if clearRow then
dgsGridListClearRow(gridlist)
end
if clearColumn then
dgsGridListClearColumn(gridlist)
end
return true
end
function dgsGridListSetItemImage(gridlist,r,c,image,color,offx,offy,w,h,relative)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetItemImage",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetItemImage",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetItemImage",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
local imageData = rData[r][c][7] or {}
imageData[1] = image or imageData[1] or nil
imageData[2] = color or imageData[2] or white
imageData[3] = offx or imageData[3] or 0
imageData[4] = offy or imageData[4] or 0
imageData[5] = w or imageData[5] or relative and 1 or dgsGridListGetColumnWidth(gridlist,c,false)
imageData[6] = h or imageData[6] or relative and 1 or eleData.rowHeight
imageData[7] = relative or false
rData[r][c][7] = imageData
return true
end
return false
end
function dgsGridListRemoveItemImage(gridlist,r,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListRemoveItemImage",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListRemoveItemImage",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListRemoveItemImage",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
rData[r][c][7] = nil
return true
end
return false
end
function dgsGridListGetItemImage(gridlist,row,column)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetItemImage",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetItemImage",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetItemImage",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
return unpack(rData[r][c][7] or {})
end
return false
end
function dgsGridListSetItemText(gridlist,row,column,text,isSection)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetItemText",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListSetItemText",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListSetItemText",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
if type(text) == "table" then
rData[r][c]._translationText = text
text = dgsTranslate(gridlist,text,sourceResource)
else
rData[r][c]._translationText = nil
end
rData[r][c][1] = tostring(text)
if isSection then
dgsGridListSetRowAsSection(gridlist,row,true)
end
return true
end
return false
end
function dgsGridListGetItemText(gridlist,r,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetItemText",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen),rIsNum and not (r >=1 and r <= rLen)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetItemText",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetItemText",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
if rData[r][c] then
return rData[r][c][1]
end
return false
end
function dgsGridListGetSelectedItem(gridlist)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetSelectedItem",1,"dgs-dxgridlist")) end
local r,data = next(dgsElementData[gridlist].rowSelect or {})
local c,bool = next(data or {})
return r or -1,c or -1
end
function dgsGridListGetSelectedItems(gridlist,isOrigin)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetSelectedItems",1,"dgs-dxgridlist")) end
local items = dgsElementData[gridlist].rowSelect
if isOrigin then return items end
local selectionMode = dgsElementData[gridlist].selectionMode
local columndata = dgsElementData[gridlist].columnData
local rowData = dgsElementData[gridlist].rowData
local newSelectTable = {}
local cnt = 0
if not next(items) then return {} end
if selectionMode == 1 then
for r,val in pairs(items) do
for c=1,#columndata do
cnt = cnt+1
newSelectTable[cnt] = {row=r,column=c}
end
end
return newSelectTable
elseif selectionMode == 2 then
for r=1,#rowData do
for c,val in pairs(items[1]) do
cnt = cnt+1
newSelectTable[cnt] = {row=r,column=c}
end
end
return newSelectTable
elseif selectionMode == 3 then
for r,val in pairs(items) do
for c,_ in pairs(val) do
cnt = cnt+1
newSelectTable[cnt] = {row=r,column=c}
end
end
return newSelectTable
end
return {}
end
function dgsGridListSetSelectedItems(gridlist,tab,isOrigin)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetSelectedItems",1,"dgs-dxgridlist")) end
if not (type(tab) == "table") then error(dgsGenAsrt(tab,"dgsGridListSetSelectedItems",2,"table")) end
local originSel
if isOrigin == true then
originSel = {}
local selectionMode = dgsElementData[gridlist].selectionMode
if selectionMode == 1 then
for k,v in ipairs(tab) do
originSel[v.row] = {true}
end
elseif selectionMode == 2 then
originSel[1] = {}
for k,v in ipairs(tab) do
originSel[1][v.column] = true
end
elseif selectionMode == 3 then
for k,v in ipairs(tab) do
originSel[v.row] = originSel[v.row] or {}
originSel[v.row][v.column] = true
end
end
end
dgsSetData(gridlist,"rowSelect",originSel or tab)
triggerEvent("onDgsGridListSelect",gridlist,tab,_)
return true
end
function dgsGridListGetSelectedCount(gridlist,r,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetSelectedCount",1,"dgs-dxgridlist")) end
local r,c = r or -1,c or -1
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cIsNum,rIsNum = type(c) == "number",type(r) == "number"
local cNInRange,rNInrange = cIsNum and not (c >=1 and c <= cLen or c == -1),rIsNum and not (r >=1 and r <= rLen or r == -1)
if not (rIsNum and not rNInRange) then error(dgsGenAsrt(r,"dgsGridListGetSelectedCount",2,"number","-1,1~"..rLen,rNInRange and "Out Of Range")) end
if not (cIsNum and not cNInRange) then error(dgsGenAsrt(c,"dgsGridListGetSelectedCount",3,"number","-1,1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
local selectedItems = dgsGridListGetSelectedItems(gridlist)
if r == -1 then
if c == -1 then
return #selectedItems
else
local cnt = 0
for i=1,#selectedItems do
if selectedItems[i].column == c then
cnt = cnt + 1
end
end
return cnt
end
else
if c == -1 then
local cnt = 0
for i=1,#selectedItems do
if selectedItems[i].row == r then
cnt = cnt + 1
end
end
return cnt
else
for i=1,#selectedItems do
if selectedItems[i].row == r and selectedItems[i].column == c then
return 1
end
end
return 0
end
end
end
function dgsGridListSetSelectedItem(gridlist,r,c,scrollTo,isOrigin)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetSelectedItem",1,"dgs-dxgridlist")) end
local r,c = r or -1,c or -1
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cNInRange,rNInrange = not (c >=1 and c <= cLen or c == -1),not (r >=1 and r <= rLen or r == -1)
if rNInRange then error(dgsGenAsrt(r,"dgsGridListSetSelectedItem",2,"number","-1,1~"..rLen,rNInRange and "Out Of Range")) end
if cNInRange then error(dgsGenAsrt(c,"dgsGridListSetSelectedItem",3,"number","-1,1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
local old1,old2
if eleData.multiSelection then
old1 = eleData.rowSelect
else
data = eleData.rowSelect
if not next(data) then
old1 = -1
old2 = -1
else
for k,v in pairs(data) do
old1 = k
old2 = v
break
end
end
end
local selectionMode = eleData.selectionMode
if selectionMode == 1 then
tab = {[r]={}}
tab[r][1] = true
dgsSetData(gridlist,"rowSelect",tab)
elseif selectionMode == 2 then
local tab = {}
tab[1] = {[c]=true}
dgsSetData(gridlist,"rowSelect",tab)
elseif selectionMode == 3 then
dgsSetData(gridlist,"rowSelect",{[r]={[c]=true}})
end
if eleData.multiSelection then
triggerEvent("onDgsGridListSelect",gridlist,r,c,old1)
else
triggerEvent("onDgsGridListSelect",gridlist,r or -1,c or -1,old1 or -1,old2 or -1)
end
eleData.itemClick = {r,c}
if scrollTo then
dgsGridListScrollTo(gridlist,r,c)
end
return true
end
function dgsGridListSelectItem(gridlist,r,c,state)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSelectItem",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cNInRange,rNInrange = not (c >=1 and c <= cLen),not (r >=1 and r <= rLen)
if rNInRange then error(dgsGenAsrt(r,"dgsGridListSelectItem",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if cNInRange then error(dgsGenAsrt(c,"dgsGridListSelectItem",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
local selectedItem = eleData.rowSelect
if rData[r][c] then
if not eleData.multiSelection then
selectedItem = {}
end
local selectionMode = eleData.selectionMode
if selectionMode == 1 then
selectedItem[r] = selectedItem[r] or {}
selectedItem[r][1] = state or nil
if not next(selectedItem[r]) then
selectedItem[r] = nil
end
elseif selectionMode == 2 then
selectedItem[1] = selectedItem[1] or {}
selectedItem[1][column] = state or nil
if not next(selectedItem[1]) then
selectedItem[1] = nil
end
elseif selectionMode == 3 then
selectedItem[r] = selectedItem[r] or {}
selectedItem[r][column] = state or nil
if not next(selectedItem[r]) then
selectedItem[r] = nil
end
end
triggerEvent("onDgsGridListSelect",gridlist,r,column)
eleData.rowSelect = selectedItem
return true
end
return false
end
function dgsGridListItemIsSelected(gridlist,r,c)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListItemIsSelected",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cNInRange,rNInrange = not (c >=1 and c <= cLen),not (r >=1 and r <= rLen)
if rNInRange then error(dgsGenAsrt(r,"dgsGridListItemIsSelected",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if cNInRange then error(dgsGenAsrt(c,"dgsGridListItemIsSelected",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
local selectedItem = eleData.rowSelect
if rData[r][c] then
local selectionMode = eleData.selectionMode
if selectionMode == 1 then
selectedItem[r] = selectedItem[r] or {}
return selectedItem[r][1] and true or false
elseif selectionMode == 2 then
selectedItem[1] = selectedItem[1] or {}
return selectedItem[1][c] and true or false
elseif selectionMode == 3 then
selectedItem[r] = selectedItem[r] or {}
return selectedItem[r][c] and true or false
end
end
return false
end
function dgsGridListSetItemColor(gridlist,r,c,...)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListSetItemColor",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cNInRange,rNInrange = not (c >=1 and c <= cLen or c == -1),not (r >=1 and r <= rLen or c == -1)
if rNInRange then error(dgsGenAsrt(r,"dgsGridListSetItemColor",2,"number","-1,1~"..rLen,rNInRange and "Out Of Range")) end
if cNInRange then error(dgsGenAsrt(c,"dgsGridListSetItemColor",3,"number","-1,1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
--Deal with the color
local colors
local argLen = select("#",...)
local args = {...}
if argLen == 0 then
error(dgsGenAsrt(args[1],"dgsGridListSetItemColor",2,"table/number"))
elseif argLen == 1 and type(args[1]) == "table" then
colors = args[1]
elseif argLen >= 3 then
if not (type(args[1]) == "number") then error(dgsGenAsrt(args[1],"dgsGridListSetItemColor",2,"number")) end
if not (type(args[2]) == "number") then error(dgsGenAsrt(args[2],"dgsGridListSetItemColor",3,"number")) end
if not (type(args[3]) == "number") then error(dgsGenAsrt(args[3],"dgsGridListSetItemColor",4,"number")) end
if not (not args[4] or type(args[4]) == "number") then error(dgsGenAsrt(args[4],"dgsGridListSetItemColor",5,"nil/number")) end
local clr = tocolor(...)
colors = {clr,clr,clr}
end
if r == -1 then
if c == -1 then
for i=1,rLen do
for j=1,cLen do
rData[i][j][2] = colors
end
end
else
for i=1,rLen do
rData[i][c][2] = colors
end
end
else
if c == -1 then
for j=1,cLen do
rData[r][j][2] = colors
end
else
rData[r][c][2] = colors
end
end
return false
end
function dgsGridListGetItemColor(gridlist,r,c,notSplitColor)
if dgsGetType(gridlist) ~= "dgs-dxgridlist" then error(dgsGenAsrt(gridlist,"dgsGridListGetItemColor",1,"dgs-dxgridlist")) end
local eleData = dgsElementData[gridlist]
local cData,rData = eleData.columnData,eleData.rowData
local cLen,rLen = #cData,#rData
if cLen == 0 or rLen == 0 then return false end
local cNInRange,rNInrange = not (c >=1 and c <= cLen),not (r >=1 and r <= rLen)
if rNInRange then error(dgsGenAsrt(r,"dgsGridListGetItemColor",2,"number","1~"..rLen,rNInRange and "Out Of Range")) end
if cNInRange then error(dgsGenAsrt(c,"dgsGridListGetItemColor",3,"number","1~"..cLen,cNInRange and "Out Of Range")) end
local c,r = c-c%1,r-r%1
return notSplitColor and rData[r][c][2] or fromcolor(rData[r][c][2])
end
function checkGLScrollBar(scb,new,old)
local gridlist = dgsGetParent(source)
if dgsGetType(gridlist) == "dgs-dxgridlist" then
local eleData = dgsElementData[gridlist]
local scrollbars = eleData.scrollbars
local sx,sy = eleData.absSize[1],eleData.absSize[2]
local scbThick = eleData.scrollBarThick
if source == scrollbars[1] then
local scbThickH = dgsElementData[scrollbars[2]].visible and scbThick or 0
local rowLength = #eleData.rowData*(eleData.rowHeight+eleData.leading)
local temp = -new*(rowLength-sy+scbThickH+eleData.columnHeight)/100
if temp <= 0 then
local temp = eleData.scrollFloor[1] and temp-temp%1 or temp
dgsSetData(gridlist,"rowMoveOffset",temp)
end
triggerEvent("onDgsElementScroll",gridlist,source,new,old)
elseif source == scrollbars[2] then
local scbThickV = dgsElementData[scrollbars[1]].visible and scbThick or 0
local columnCount = dgsGridListGetColumnCount(gridlist)
local columnWidth = dgsGridListGetColumnAllWidth(gridlist,columnCount)
local columnOffset = eleData.columnOffset
local temp = -new*(columnWidth-sx+scbThickV+columnOffset)/100
if temp <= 0 then
local temp = eleData.scrollFloor[2] and temp-temp%1 or temp
dgsSetData(gridlist,"columnMoveOffset",temp)
end
triggerEvent("onDgsElementScroll",gridlist,source,new,old)
end
end
end
function dgsGridListUpdateRowMoveOffset(gridlist,rowMoveOffset)
local eleData = dgsElementData[gridlist]
local rowMoveOffset = rowMoveOffset or eleData.rowMoveOffsetTemp
local rowHeight = eleData.rowHeight
local rowHeightLeadingTemp = rowHeight + eleData.leading
local scrollbar = eleData.scrollbars[2]
local scbThickH = dgsElementData[scrollbar].visible and eleData.scrollBarThick or 0
local h = eleData.absSize[2]
local columnHeight = eleData.columnHeight
local rowCount = #eleData.rowData
if eleData.mode then
local temp1 = rowMoveOffset/rowHeightLeadingTemp
local whichRowToStart = -(temp1-temp1%1)+1
local temp2 = (h-columnHeight-scbThickH+rowHeight)/rowHeightLeadingTemp
local whichRowToEnd = whichRowToStart+(temp2-temp2%1)-2
eleData.FromTo = {whichRowToStart > 0 and whichRowToStart or 1,whichRowToEnd <= rowCount and whichRowToEnd or rowCount}
else
local temp1 = (rowMoveOffset+rowHeight)/rowHeightLeadingTemp
local whichRowToStart = -(temp1-temp1%1)+1
local temp2 = (h-columnHeight-scbThickH+rowHeight*2)/rowHeightLeadingTemp
local whichRowToEnd = whichRowToStart+(temp2-temp2%1)-1
eleData.FromTo = {whichRowToStart > 0 and whichRowToStart or 1,whichRowToEnd <= rowCount and whichRowToEnd or rowCount}
end
end
function configGridList(gridlist)
local eleData = dgsElementData[gridlist]
local scrollbar = eleData.scrollbars
local sx,sy = eleData.absSize[1],eleData.absSize[2]
local columnHeight,rowHeight,leading = eleData.columnHeight,eleData.rowHeight,eleData.leading
local scbThick = eleData.scrollBarThick
local columnCount = dgsGridListGetColumnCount(gridlist)
local columnWidth = dgsGridListGetColumnAllWidth(gridlist,columnCount,false,true)
local rowLength = #eleData.rowData*(rowHeight+leading)
local scbX,scbY = sx-scbThick,sy-scbThick
local oriScbStateV,oriScbStateH = dgsElementData[scrollbar[1]].visible,dgsElementData[scrollbar[2]].visible
local scbStateV,scbStateH
if columnWidth > sx then
scbStateH = true
elseif columnWidth < sx-scbThick then
scbStateH = false
end
if rowLength > sy-columnHeight then
scbStateV = true
elseif rowLength < sy-columnHeight-scbThick then
scbStateV = false
end
if scbStateH == nil then
scbStateH = scbStateV
end
if scbStateV == nil then
scbStateV = scbStateH
end
local forceState = eleData.scrollBarState
if forceState[1] ~= nil then
scbStateV = forceState[1]
end
if forceState[2] ~= nil then
scbStateH = forceState[2]
end
local scbThickV,scbThickH = scbStateV and scbThick or 0,scbStateH and scbThick or 0
local relSizX,relSizY = sx-scbThickV,sy-scbThickH
local rowShowRange = relSizY-columnHeight
local columnShowRange = relSizX
if scbStateH and scbStateH ~= oriScbStateH then
dgsSetData(scrollbar[2],"position",0)
end
if scbStateV and scbStateV ~= oriScbStateV then
dgsSetData(scrollbar[1],"position",0)
end
dgsSetVisible(scrollbar[1],scbStateV and true or false)
dgsSetVisible(scrollbar[2],scbStateH and true or false)
dgsSetPosition(scrollbar[1],scbX,0,false)
dgsSetPosition(scrollbar[2],0,scbY,false)
dgsSetSize(scrollbar[1],scbThick,relSizY,false)
dgsSetSize(scrollbar[2],relSizX,scbThick,false)
local scroll1 = dgsElementData[scrollbar[1]].position
local scroll2 = dgsElementData[scrollbar[2]].position
dgsSetData(gridlist,"rowMoveOffset",-scroll1*(rowLength-rowShowRange)/100)
local scbLengthVrt = eleData.scrollBarLength[1]
local higLen = 1-(rowLength-rowShowRange)/rowLength
higLen = higLen >= 0.95 and 0.95 or higLen
dgsSetData(scrollbar[1],"length",scbLengthVrt or {higLen,true})
local verticalScrollSize = eleData.scrollSize/(rowLength-rowShowRange)
dgsSetData(scrollbar[1],"multiplier",{verticalScrollSize,true})
local scbLengthHoz = dgsElementData[gridlist].scrollBarLength[2]
local widLen = 1-(columnWidth-columnShowRange)/columnWidth
widLen = widLen >= 0.95 and 0.95 or widLen
dgsSetData(scrollbar[2],"length",scbLengthHoz or {widLen,true})
local horizontalScrollSize = eleData.scrollSize*5/(columnWidth-columnShowRange)
dgsSetData(scrollbar[2],"multiplier",{horizontalScrollSize,true})
local rentarg = eleData.renderTarget
if rentarg then
if isElement(rentarg[1]) then destroyElement(rentarg[1]) end
if isElement(rentarg[2]) then destroyElement(rentarg[2]) end
if not eleData.mode then
local columnRender,rowRender
if relSizX*columnHeight ~= 0 then
columnRender,err = dxCreateRenderTarget(relSizX,columnHeight,true,gridlist)
if columnRender ~= false then
dgsAttachToAutoDestroy(columnRender,gridlist,-1)
else
outputDebugString(err)
end
end
if relSizX*rowShowRange ~= 0 then
rowRender,err = dxCreateRenderTarget(relSizX,rowShowRange,true,gridlist)
if rowRender ~= false then
dgsAttachToAutoDestroy(rowRender,gridlist,-2)
else
outputDebugString(err)
end
end
dgsSetData(gridlist,"renderTarget",{columnRender,rowRender})
end
end
dgsGridListUpdateRowMoveOffset(gridlist)
eleData.configNextFrame = false
end
addEventHandler("onDgsGridListSelect",resourceRoot,function(rowOrTable,column,oldRowOrTable,oldColumn)
local lastSelected = dgsElementData[source].lastSelectedItem
if type(rowOrTable) == "table" then
local row,columns = next(rowOrTable)
if row then
local column = next(columns)
dgsSetData(source,"lastSelectedItem",{row,column})
end
else
dgsSetData(source,"lastSelectedItem",{rowOrTable == -1 and lastSelected[1] or rowOrTable,column == -1 and lastSelected[2] or column})
end
end)
----------------------------------------------------------------
--------------------------Renderer------------------------------
----------------------------------------------------------------
dgsRenderer["dgs-dxgridlist"] = function(source,x,y,w,h,mx,my,cx,cy,enabled,eleData,parentAlpha,isPostGUI,rndtgt,position,OffsetX,OffsetY,visible)
if eleData.configNextFrame then configGridList(source) end
local bgColor,bgImage = applyColorAlpha(eleData.bgColor,parentAlpha),eleData.bgImage
local columnColor,columnImage = applyColorAlpha(eleData.columnColor,parentAlpha),eleData.columnImage
local font = eleData.font or systemFont
local columnHeight = eleData.columnHeight
if MouseData.enter == source then
colorimgid = 2
if MouseData.clickl == source then
colorimgid = 3
end
MouseData.enterData = false
end
dxSetBlendMode(rndtgt and "modulate_add" or "blend")
if bgImage then
dxDrawImage(x,y+columnHeight,w,h-columnHeight,bgImage,0,0,0,bgColor,isPostGUI,rndtgt)
else
dxDrawRectangle(x,y+columnHeight,w,h-columnHeight,bgColor,isPostGUI)
end
if columnImage then
dxDrawImage(x,y,w,columnHeight,columnImage,0,0,0,columnColor,isPostGUI,rndtgt)
else
dxDrawRectangle(x,y,w,columnHeight,columnColor,isPostGUI)
end
local columnData,rowData = eleData.columnData,eleData.rowData
local columnCount,rowCount = #columnData,#rowData
local sortColumn = eleData.sortColumn
if sortColumn and columnData[sortColumn] then
if eleData.nextRenderSort then
dgsGridListSort(source)
eleData.nextRenderSort = false
end
end
local columnTextColor = eleData.columnTextColor
local columnRelt = eleData.columnRelative
local rowHeight = eleData.rowHeight
local rowTextPosOffset = eleData.rowTextPosOffset
local columnTextPosOffset = eleData.columnTextPosOffset
local leading = eleData.leading
local scbThick = eleData.scrollBarThick
local scrollbars = eleData.scrollbars
local scb1,scb2 = scrollbars[1],scrollbars[2]
local scbThickV,scbThickH = dgsElementData[scb1].visible and scbThick or 0,dgsElementData[scb2].visible and scbThick or 0
local colorcoded = eleData.colorcoded
local shadow = eleData.rowShadow
local rowHeightLeadingTemp = rowHeight+leading
--Smooth Row
local _rowMoveOffset = eleData.rowMoveOffset
local rowMoveOffset = _rowMoveOffset
if eleData.rowMoveOffsetTemp ~= _rowMoveOffset then
local rowMoveHardness = dgsElementData[scb1].moveType == "slow" and eleData.moveHardness[1] or eleData.moveHardness[2]
eleData.rowMoveOffsetTemp = lerp(rowMoveHardness,eleData.rowMoveOffsetTemp,_rowMoveOffset)
local rMoveOffset = eleData.rowMoveOffsetTemp-eleData.rowMoveOffsetTemp%1
dgsGridListUpdateRowMoveOffset(source)
if rMoveOffset-eleData.rowMoveOffsetTemp <= 0.5 and rMoveOffset-eleData.rowMoveOffsetTemp >= -0.5 then
eleData.rowMoveOffsetTemp = rMoveOffset
end
rowMoveOffset = rMoveOffset
end
--Smooth Column
local _columnMoveOffset = eleData.columnMoveOffset
local columnMoveOffset = _columnMoveOffset
if eleData.columnMoveOffsetTemp ~= _columnMoveOffset then
local columnMoveHardness = dgsElementData[scb2].moveType == "slow" and eleData.moveHardness[1] or eleData.moveHardness[2]
eleData.columnMoveOffsetTemp = lerp(columnMoveHardness,eleData.columnMoveOffsetTemp,_columnMoveOffset)
local cMoveOffset = eleData.columnMoveOffsetTemp-eleData.columnMoveOffsetTemp%1
if cMoveOffset-eleData.columnMoveOffsetTemp <= 0.5 and cMoveOffset-eleData.columnMoveOffsetTemp >= -0.5 then
eleData.columnMoveOffsetTemp = cMoveOffset
end
columnMoveOffset = cMoveOffset
end
--
local columnOffset = eleData.columnOffset
local rowTextSx,rowTextSy = eleData.rowTextSize[1],eleData.rowTextSize[2] or eleData.rowTextSize[1]
local columnTextSx,columnTextSy = eleData.columnTextSize[1],eleData.columnTextSize[2] or eleData.columnTextSize[1]
local selectionMode = eleData.selectionMode
local clip = eleData.clip
local mouseInsideGridList = mx >= cx and mx <= cx+w and my >= cy and my <= cy+h-scbThickH
local mouseInsideColumn = mouseInsideGridList and my <= cy+columnHeight
local mouseInsideRow = mouseInsideGridList and my > cy+columnHeight
local defaultSortFunctions = eleData.defaultSortFunctions
eleData.selectedColumn = -1
local sortIcon = eleData.sortFunction == sortFunctions[defaultSortFunctions[1]] and "▼" or (eleData.sortFunction == sortFunctions[defaultSortFunctions[2]] and "▲") or nil
local sortColumn = eleData.sortColumn
local backgroundOffset = eleData.backgroundOffset
local beforeHit = MouseData.hit
if not eleData.mode then
local renderTarget = eleData.renderTarget
local isDraw1,isDraw2 = isElement(renderTarget[1]),isElement(renderTarget[2])
dxSetRenderTarget(renderTarget[1],true)
dxSetBlendMode("modulate_add")
local cpos = {}
local cend = {}
local multiplier = columnRelt and (w-scbThickV) or 1
local tempColumnOffset = columnMoveOffset+columnOffset
local mouseColumnPos = mx-cx
local mouseSelectColumn = -1
local cPosStart,cPosEnd
for id = 1,#columnData do
local data = columnData[id]
local _columnTextColor = data[5] or columnTextColor
local _columnTextColorCoded = data[6] or colorcoded
local _columnTextSx,_columnTextSy = data[7] or columnTextSx,data[8] or columnTextSy
local _columnFont = data[9] or font
local tempCpos = data[3]*multiplier
local _tempStartx = tempCpos+tempColumnOffset
local _tempEndx = _tempStartx+data[2]*multiplier
if _tempStartx <= w and _tempEndx >= 0 then
cpos[id],cend[id] = tempCpos,_tempEndx
cPosStart,cPosEnd = cPosStart or id,id
if isDraw1 then
local _tempStartx = eleData.PixelInt and _tempStartx-_tempStartx%1 or _tempStartx
local textPosL = _tempStartx+columnTextPosOffset[1]
local textPosT = columnTextPosOffset[2]
local textPosR = _tempEndx+columnTextPosOffset[1]
local textPosB = columnHeight+columnTextPosOffset[2]
if sortColumn == id and sortIcon then
local iconWidth = dxGetTextWidth(sortIcon,_columnTextSx*0.8,_columnFont)
local iconTextPosL = textPosL-iconWidth
local iconTextPosR = textPosR-iconWidth
if eleData.columnShadow then
dxDrawText(sortIcon,iconTextPosL,textPosT,iconTextPosR,textPosB,black,_columnTextSx*0.8,_columnTextSy*0.8,_columnFont,"left","center",clip,false,false,false,true)
end
dxDrawText(sortIcon,iconTextPosL-1,textPosT,iconTextPosR-1,textPosB,_columnTextColor,_columnTextSx*0.8,_columnTextSy*0.8,_columnFont,"left","center",clip,false,false,false,true)
end
if eleData.columnShadow then
dxDrawText(data[1],textPosL+1,textPosT+1,textPosR+1,textPosB+1,black,_columnTextSx,_columnTextSy,_columnFont,data[4],"center",clip,false,false,false,true)
end
dxDrawText(data[1],textPosL,textPosT,textPosR,textPosB,_columnTextColor,_columnTextSx,_columnTextSy,_columnFont,data[4],"center",clip,false,false,_columnTextColorCoded,true)
end
if mouseInsideGridList and mouseSelectColumn == -1 then
if mouseColumnPos >= _tempStartx and mouseColumnPos <= _tempEndx then
mouseSelectColumn = id
end
end
end
end
dxSetRenderTarget(renderTarget[2],true)
local preSelectLastFrame = eleData.preSelect
if MouseData.enter == source then -------PreSelect
if mouseInsideRow then
local toffset = (eleData.FromTo[1]*rowHeightLeadingTemp)+rowMoveOffset
local tempID = (my-cy-columnHeight-toffset)/rowHeightLeadingTemp
local sid = (tempID-tempID%1)+eleData.FromTo[1]+1
if sid >= 1 and sid <= rowCount and my-cy-columnHeight < sid*rowHeight+(sid-1)*leading+rowMoveOffset then
eleData.oPreSelect = sid
if rowData[sid][-2] ~= false then
eleData.preSelect = {sid,mouseSelectColumn}
else
eleData.preSelect = {-1,mouseSelectColumn}
end
MouseData.enterData = true
else
eleData.preSelect = {-1,mouseSelectColumn}
end
elseif mouseInsideColumn then
eleData.selectedColumn = mouseSelectColumn
eleData.preSelect = {}
else
eleData.preSelect = {-1,-1}
end
else
eleData.preSelect = {-1,-1}
end
local preSelect = eleData.preSelect
if preSelectLastFrame[1] ~= preSelect[1] or preSelectLastFrame[2] ~= preSelect[2] then
triggerEvent("onDgsGridListHover",source,preSelect[1],preSelect[2],preSelectLastFrame[1],preSelectLastFrame[2])
end
local Select = eleData.rowSelect
local sectionFont = eleData.sectionFont or font
local dgsElementBuffer = {}
local textBufferCnt = 1
local textBuffer = {}
for i=eleData.FromTo[1],eleData.FromTo[2] do
dgsElementBuffer[i] = {}
local lc_rowData = rowData[i]
local image,columnOffset,isSection,color = lc_rowData[-3] or eleData.rowImage,lc_rowData[-4] or eleData.columnOffset,lc_rowData[-5],lc_rowData[0] or eleData.rowColor
if isDraw2 then
local rowpos = i*rowHeight+rowMoveOffset+(i-1)*leading
local rowpos_1 = rowpos-rowHeight
local _x,_y,_sx,_sy = tempColumnOffset+columnOffset,rowpos_1,sW,rowpos
if eleData.PixelInt then
_x,_y,_sx,_sy = _x-_x%1,_y-_y%1,_sx-_sx%1,_sy-_sy%1
end
if not cPosStart or not cPosEnd then break end
dxSetBlendMode("modulate_add")
for id = cPosStart,cPosEnd do
local currentRowData = lc_rowData[id]
local text = currentRowData[1]
local _txtFont = isSection and sectionFont or (currentRowData[6] or font)
local _txtScalex = currentRowData[4] or rowTextSx
local _txtScaley = currentRowData[5] or rowTextSy
local rowState = 1
if selectionMode == 1 then
if i == preSelect[1] then
rowState = 2
end
if Select[i] and Select[i][1] then
rowState = 3
end
elseif selectionMode == 2 then
if id == preSelect[2] then
rowState = 2
end
if Select[1] and Select[1][id] then
rowState = 3
end
elseif selectionMode == 3 then
if i == preSelect[1] and id == preSelect[2] then
rowState = 2
end
if Select[i] and Select[i][id] then
rowState = 3
end
end
local offset = cpos[id]
local _x = _x+offset
local _sx = cend[id]
local _backgroundWidth = columnData[id][2]*multiplier
local _bgX = _x
local backgroundWidth = _backgroundWidth
if id == 1 then
_bgX = _x+backgroundOffset
backgroundWidth = _backgroundWidth-backgroundOffset
elseif backgroundWidth+_x-x >= w or columnCount == id then
backgroundWidth = w-_x+x
end
if #image > 0 then
dxDrawImage(_bgX,_y,backgroundWidth,rowHeight,image[rowState],0,0,0,color[rowState])
else
dxDrawRectangle(_bgX,_y,backgroundWidth,rowHeight,color[rowState])
end
dgsElementBuffer[i][id] = {currentRowData[10],_x,_y}
if text then
local colorcoded = currentRowData[3] == nil and colorcoded or currentRowData[3]
if currentRowData[7] then
local imageData = currentRowData[7]
local imagex = _x+(imageData[7] and imageData[3]*_backgroundWidth or imageData[3])
local imagey = _y+(imageData[7] and imageData[4]*rowHeight or imageData[4])
local imagew = imageData[7] and imageData[5]*_backgroundWidth or imageData[5]
local imageh = imageData[7] and imageData[6]*rowHeight or imageData[6]
if isElement(imageData[1]) then
dxDrawImage(imagex,imagey,imagew,imageh,imageData[1],0,0,0,imageData[2])
else
dxDrawRectangle(imagex,imagey,imagew,imageh,imageData[2])
end
end
local color = type(currentRowData[2]) == "table" and currentRowData[2] or {currentRowData[2],currentRowData[2],currentRowData[2]}
textBuffer[textBufferCnt] = {
currentRowData[1], --Text
_x-_x%1, --startX
_y-_y%1, --startY
_sx-_sx%1, --endX
_sy-_sy%1, --endY
color[rowState],
_txtScalex,
_txtScaley,
_txtFont,
clip,
colorcoded,
columnData[id][4]
}
textBufferCnt = textBufferCnt + 1
end
end
end
end
local textBuffers = #textBuffer
for a=1,textBuffers do
local line = textBuffer[a]
local text = line[1]
local psx,psy,pex,pey = line[2]+rowTextPosOffset[1],line[3]+rowTextPosOffset[2],line[4]+rowTextPosOffset[1],line[5]+rowTextPosOffset[2]
local clr,tSclx,tScly,tFnt,tClip,tClrCode,tHozAlign = line[6],line[7],line[8],line[9],line[10],line[11],line[12]
if shadow then
if tClrCode then
text = text:gsub("#%x%x%x%x%x%x","") or text
end
dxDrawText(text,psx+shadow[1],psy+shadow[2],pex+shadow[1],pey+shadow[2],shadow[3],tSclx,tScly,tFnt,tHozAlign,"center",tClip,false,false,false,true)
end
dxDrawText(line[1],psx,psy,pex,pey,clr,tSclx,tScly,tFnt,tHozAlign,"center",tClip,false,false,tClrCode,true)
end
for rowIndex,row in pairs(dgsElementBuffer) do
for columnIndex,items in pairs(row) do
local offx = items[2]
local offy = items[3]
for a=1,#(items[1] or {}) do
renderGUI(items[1][a],mx,my,enabled,renderTarget[2],{0,0,position[3],position[4]+columnHeight},offx,offy,parentAlpha,visible,checkElement)
end
end
end
dxSetRenderTarget(rndtgt)
dxSetBlendMode("modulate_add")
if isDraw2 then
dxDrawImage(x,y+columnHeight,w-scbThickV,h-columnHeight-scbThickH,renderTarget[2],0,0,0,tocolor(255,255,255,255*parentAlpha),isPostGUI)
end
if isDraw1 then
dxDrawImage(x,y,w-scbThickV,columnHeight,renderTarget[1],0,0,0,tocolor(255,255,255,255*parentAlpha),isPostGUI)
end
elseif columnCount >= 1 then
local whichColumnToStart,whichColumnToEnd = -1,-1
local _rowMoveOffset = (1-eleData.FromTo[1])*rowHeightLeadingTemp
local cpos = {}
local multiplier = columnRelt and (w-scbThickV) or 1
local ypcolumn = cy+columnHeight
local _y,_sx = ypcolumn+_rowMoveOffset,cx+w-scbThickV
local column_x = columnOffset
local allColumnWidth = columnData[columnCount][2]+columnData[columnCount][3]
local scrollbar = eleData.scrollbars[2]
local scrollPos = dgsElementData[scrollbar].position*0.01
local mouseSelectColumn = -1
local does = false
for id = 1,#columnData do
local data = columnData[id]
cpos[id] = data[3]*multiplier
if (data[3]+data[2])*multiplier-columnOffset >= scrollPos*allColumnWidth*multiplier then
if (data[3]+data[2])*multiplier-scrollPos*allColumnWidth*multiplier <= w-scbThickV then
whichColumnToStart = whichColumnToStart ~= -1 and whichColumnToStart or id
whichColumnToEnd = whichColumnToEnd <= whichColumnToStart and whichColumnToStart or id
whichColumnToEnd = id
does = true
end
end
end
if not does then
whichColumnToStart,whichColumnToEnd = columnCount,columnCount
end
column_x = cx-cpos[whichColumnToStart]+columnOffset
dxSetBlendMode(rndtgt and "modulate_add" or "blend")
for i=whichColumnToStart,whichColumnToEnd or columnCount do
local data = columnData[i]
local _columnTextColor = data[5] or columnTextColor
local _columnTextColorCoded = data[6] or colorcoded
local _columnTextSx,_columnTextSy = data[7] or columnTextSx,data[8] or columnTextSy
local _columnFont = data[9] or font
local column_sx = column_x+cpos[i]+data[2]*multiplier-scbThickV
local posx = column_x+cpos[i]
local tPosX = posx-posx%1
local textPosL = tPosX+columnTextPosOffset[1]
local textPosT = cy+columnTextPosOffset[2]
local textPosR = column_sx+columnTextPosOffset[1]
local textPosB = ypcolumn+columnTextPosOffset[2]
if sortColumn == i and sortIcon then
local iconWidth = dxGetTextWidth(sortIcon,_columnTextSx*0.8,_columnFont)
local iconTextPosL = textPosL-iconWidth
local iconTextPosR = textPosR-iconWidth
if eleData.columnShadow then
dxDrawText(sortIcon,iconTextPosL,textPosT,iconTextPosR,textPosB,black,_columnTextSx*0.8,_columnTextSy*0.8,_columnFont,"left","center",clip,false,isPostGUI,false,true)
end
dxDrawText(sortIcon,iconTextPosL-1,textPosT,iconTextPosR-1,textPosB,_columnTextColor,_columnTextSx*0.8,_columnTextSy*0.8,_columnFont,"left","center",clip,false,isPostGUI,false,true)
end
if eleData.columnShadow then
dxDrawText(data[1],textPosL+1,textPos+1,textPosR+1,textPosB+1,black,_columnTextSx,_columnTextSy,_columnFont,data[4],"center",clip,false,isPostGUI,false,true)
end
dxDrawText(data[1],textPosL,textPosT,textPosR,textPosB,_columnTextColor,_columnTextSx,_columnTextSy,_columnFont,data[4],"center",clip,false,isPostGUI,false,true)
if mouseInsideGridList and mouseSelectColumn == -1 then
backgroundWidth = data[2]*multiplier
if backgroundWidth+posx-x >= w or whichColumnToEnd == i then
backgroundWidth = w-posx+x
end
local _tempStartx = posx
local _tempEndx = _tempStartx+backgroundWidth
if mx >= _tempStartx and mx <= _tempEndx then
mouseSelectColumn = i
end
end
end
if MouseData.enter == source then -------PreSelect
if mouseInsideRow then
local tempID = (my-cy-columnHeight)/rowHeightLeadingTemp-1
sid = (tempID-tempID%1)+eleData.FromTo[1]+1
if sid >= 1 and sid <= rowCount and my-cy-columnHeight < sid*rowHeight+(sid-1)*leading+_rowMoveOffset then
eleData.oPreSelect = sid
if rowData[sid][-2] ~= false then
eleData.preSelect = {sid,mouseSelectColumn}
else
eleData.preSelect = {-1,mouseSelectColumn}
end
MouseData.enterData = true
else
eleData.preSelect = {-1,mouseSelectColumn}
end
elseif mouseInsideColumn then
eleData.selectedColumn = mouseSelectColumn
eleData.preSelect = {}
else
eleData.preSelect = {-1,-1}
end
end
local preSelect = eleData.preSelect
local Select = eleData.rowSelect
local sectionFont = eleData.sectionFont or font
local textBuffer = {}
local textBufferCnt = 1
for i=eleData.FromTo[1],eleData.FromTo[2] do
local lc_rowData = rowData[i]
local image = lc_rowData[-3]
local color = lc_rowData[0]
local columnOffset = lc_rowData[-4]
local isSection = lc_rowData[-5]
local rowpos = i*rowHeight+(i-1)*leading
local _x,_y,_sx,_sy = column_x+columnOffset,_y+rowpos-rowHeight,_sx,_y+rowpos
if eleData.PixelInt then
_x,_y,_sx,_sy = _x-_x%1,_y-_y%1,_sx-_sx%1,_sy-_sy%1
end
for id=whichColumnToStart,whichColumnToEnd do
local currentRowData = lc_rowData[id]
local text = currentRowData[1]
local _txtFont = isSection and sectionFont or (currentRowData[6] or font)
local _txtScalex = currentRowData[4] or rowTextSx
local _txtScaley = currentRowData[5] or rowTextSy
local rowState = 1
if selectionMode == 1 then
if i == preSelect[1] then
rowState = 2
end
if Select[i] and Select[i][1] then
rowState = 3
end
elseif selectionMode == 2 then
if id == preSelect[2] then
rowState = 2
end
if Select[1] and Select[1][id] then
rowState = 3
end
elseif selectionMode == 3 then
if i == preSelect[1] and id == preSelect[2] then
rowState = 2
end
if Select[i] and Select[i][id] then
rowState = 3
end
end
local offset = cpos[id]
local _x = _x+offset
local _sx = cpos[id+1] or (columnData[id][2])*multiplier
local backgroundWidth = columnData[id][2]*multiplier
local _bgX = _x
if id == 1 then
_bgX = _x+backgroundOffset
backgroundWidth = backgroundWidth-backgroundOffset
elseif backgroundWidth+_x-x >= w or whichColumnToEnd == id then
backgroundWidth = w-_x+x-scbThickV
end
if #image > 0 then
dxDrawImage(_bgX,_y,backgroundWidth,rowHeight,image[rowState],0,0,0,color[rowState],isPostGUI,rndtgt)
else
dxDrawRectangle(_bgX,_y,backgroundWidth,rowHeight,color[rowState],isPostGUI)
end
if text ~= "" then
local colorcoded = currentRowData[3] == nil and colorcoded or currentRowData[3]
if currentRowData[7] then
local imageData = currentRowData[7]
if isElement(imageData[1]) then
dxDrawImage(_x+imageData[3],_y+imageData[4],imageData[5],imageData[6],imageData[1],0,0,0,imageData[2],rndtgt)
else
dxDrawRectangle(_x+imageData[3],_y+imageData[4],imageData[5],imageData[6],imageData[2])
end
end
local color = type(currentRowData[2]) == "table" and currentRowData[2] or {currentRowData[2],currentRowData[2],currentRowData[2]}
textBuffer[textBufferCnt] = {
currentRowData[1], --Text
_x, --startX
_y, --startY
_sx+_x, --endX
_sy, --endY
color[rowState],
_txtScalex,
_txtScaley,
_txtFont,
clip,
colorcoded,
columnData[id][4]
}
textBufferCnt = textBufferCnt+1
end
end
end
for i=1,#textBuffer do
local line = textBuffer[i]
local text = line[1]
local psx,psy,pex,pey = line[2]+rowTextPosOffset[1],line[3]+rowTextPosOffset[2],line[4]+rowTextPosOffset[1],line[5]+rowTextPosOffset[2]
local clr,tSclx,tScly,tFnt,tClip,tClrCode,tHozAlign = line[6],line[7],line[8],line[9],line[10],line[11],line[12]
if shadow then
if tClrCode then
text = text:gsub("#%x%x%x%x%x%x","") or text
end
dxDrawText(text,psx+shadow[1],psy+shadow[2],pex+shadow[1],pey+shadow[2],shadow[3],tSclx,tScly,tFnt,tHozAlign,"center",tClip,false,isPostGUI,false,true)
end
dxDrawText(line[1],psx,psy,pex,pey,clr,tSclx,tScly,tFnt,tHozAlign,"center",tClip,false,isPostGUI,colorcoded,true)
end
end
dxSetBlendMode(rndtgt and "modulate_add" or "blend")
return rndtgt
end |
local d = require "bw.util.date_helper"
return function()
assert(d.format_now(1) == "0分1秒")
assert(d.format_now(305) == "5分5秒")
assert(d.format_now(24*3600+1) == "1天0小时")
assert(d.format_now(24*3600+3660) == "1天1小时")
assert(d.format_now(29*24*3600+3660) == "29天1小时")
return true
end
|
require("mysqloo")
ocrpdb = mysqloo.connect('HOST', 'USERNAME', 'PASSWORD', 'DATABASE', 3306)
function ocrpdb:onConnected()
print("[OCRP] Successfully connected to database.")
end
function ocrpdb:onConnectionFailed(err)
print("[OCRP] Connection to database failed.")
print("[OCRP] Error: " .. err)
end
ocrpdb:connect()
function runOCRPQuery(sql, callback, errcallback)
local q = ocrpdb:query(sql)
function q:onSuccess(data)
if callback then
callback(data)
end
end
function q:onError(err, sql)
print("Query failed! Attempted: " .. sql)
print("Error: " .. err)
if ocrpdb:status() == mysqloo.DATABASE_NOT_CONNECTED then
ocrpdb:connect()
end
if errcallback then
errcallback(sql, err)
end
end
q:start()
end
timer.Create("OCRP_PushSQLDataTimer", 900, 0, function()
PushSQLData()
PushOrgSQLData()
end)
function PushSQLData()
GAMEMODE.DisconnectSaves = GAMEMODE.DisconnectSaves or {}
if #player.GetAll() == 0 and table.Count(GAMEMODE.DisconnectSaves) == 0 then
return -- nothing to save
end
local columns = {"wallet", "bank", "org_id", "org_notes", "cars", "inv", "skills", "model", "wardrobe", "face", "playtime", "storage", "buddies", "blacklist", "refedby", "nick", "itembank"}
local q = "UPDATE `ocrp_users` SET "
local updates = {}
for _,column in pairs(columns) do
updates[column] = "`" .. column .. "` = CASE "
end
for id,t in pairs(GAMEMODE.DisconnectSaves) do
if not t or table.Count(t) == 0 then continue end -- Don't save blank data. Not sure how this is happening but it has twice already.
if t["wallet"] == nil || t["wallet"] == "" then continue end -- Above line didn't fix it. I'm hoping this will. Wallet should never be nil or "", at the very least it's 0.
for _,column in pairs(columns) do
updates[column] = updates[column] .. "WHEN `STEAM_ID` = '" .. ocrpdb:escape(id) .. "' THEN '" .. ocrpdb:escape(tostring(t[column])) .. "' "
end
end
for _,ply in pairs(player.GetAll()) do
if not ply.Loaded then continue end
if not ply:IsValid() then continue end
local t = {}
t["wallet"] = ply:GetMoney(WALLET)
t["bank"] = ply:GetMoney(BANK)
t["inv"] = ply:CompileString("inv")
t["cars"] = ply:CompileString("car")
t["skills"] = ply:CompileString("skill")
t["wardrobe"] = ply:CompileString("wardrobe")
t["face"] = tostring(ply.OCRPData["Face"])
t["playtime"] = tostring(ply.OCRPData["Playtime"])
t["storage"] = ply:CompileString("storage")
t["buddies"] = ply:CompileString("buddies")
t["nick"] = ply:Nick()
t["refedby"] = ply.OCRPData["RefedBy"] or ""
t["blacklist"] = ply:CompileString("blacklist")
t["org_id"] = ply:GetOrg()
-- Rebuild their model path so we don't accidentally save their job model
t["model"] = ply:Team() == CLASS_CITIZEN and ply:GetModel() or ply.OCRPData["MyModel"]
t["org_notes"] = ""
t["itembank"] = ply:CompileString("itembank")
if ply:GetOrg() > 0 then
local org = OCRP_Orgs[ply:GetOrg()]
for _,member in pairs(org.Members) do
if member.SteamID == ply:SteamID() then
t["org_notes"] = member.Notes or ""
end
end
end
for _,column in pairs(columns) do
updates[column] = updates[column] .. "WHEN `STEAM_ID` = '" .. ocrpdb:escape(ply:SteamID()) .. "' THEN '" .. ocrpdb:escape(tostring(t[column])) .. "' "
end
end
for column,query in pairs(updates) do
q = q .. query .. "END, "
end
q = string.TrimRight(q, " ")
q = string.TrimRight(q, ",")
q = q .. " WHERE "
for id,_ in pairs(GAMEMODE.DisconnectSaves) do
q = q .. "`STEAM_ID` = '" .. id .. "' OR "
end
for _,ply in pairs(player.GetAll()) do
q = q .. "`STEAM_ID` = '" .. ply:SteamID() .. "' OR"
end
q = string.sub(q, 1, q:len()-3)
q = q .. ";"
--file.Write("sql.txt", q)
runOCRPQuery(q, function()
GAMEMODE.DisconnectSaves = {}
print("[OCRP] Pushed all user data to database.")
end)
end
function LoadSQLUser(ply, success_callback)
if not ply:IsValid() then return end
GAMEMODE.DisconnectSaves = GAMEMODE.DisconnectSaves or {}
if GAMEMODE.DisconnectSaves[ply:SteamID()] then -- We cached their info in mem and haven't pushed it to DB yet, so don't bother checking DB
print("[OCRP] Loaded user " .. ply:Nick() .. " from memory.")
local t = GAMEMODE.DisconnectSaves[ply:SteamID()]
ply.OCRPData["Money"]["Bank"] = tonumber(t["bank"])
ply.OCRPData["Money"]["Wallet"] = tonumber(t["wallet"])
ply.OCRPData["Playtime"] = tonumber(t["playtime"])
ply.OCRPData["Face"] = t["face"]
ply.OCRPData["RefedBy"] = t["refedby"]
ply:UnCompileString("inv", t["inv"])
ply:UnCompileString("car", t["cars"])
ply:UnCompileString("skill", t["skills"])
ply:UnCompileString("storage", t["storage"])
ply:UnCompileString("wardrobe", t["wardrobe"])
ply:UnCompileString("blacklist", t["blacklist"])
ply:UnCompileString("buddies", t["buddies"])
ply:UnCompileString("itembank", t["itembank"])
if ply.OCRPData["Face"] == nil or ply.OCRPData["Face"] == "" then
net.Start("OCRP_ShowStartModel")
net.Send(ply)
else
ply:SetModel(t["model"])
end
ply:SetOrg(t["org_id"])
GAMEMODE.DisconnectSaves[ply:SteamID()] = nil
success_callback(ply)
return
end
local q = "SELECT * FROM `ocrp_users` WHERE `STEAM_ID` = '" .. ocrpdb:escape(ply:SteamID()) .. "';"
local failure = function()
if ply:IsValid() then
ply:Kick("An error occured while trying to load your data. Please retry and post on the forums if this problem persists.")
end
end
local success = function(results)
if results and #results >= 1 then
local result = results[1]
ply.OCRPData["Money"]["Bank"] = tonumber(result["bank"])
ply.OCRPData["Money"]["Wallet"] = tonumber(result["wallet"])
ply.OCRPData["Playtime"] = tonumber(result["playtime"])
ply.OCRPData["Face"] = result["face"]
ply.OCRPData["Org"] = result["org_id"]
ply.OCRPData["RefedBy"] = result["refedby"]
ply:UnCompileString("inv", result["inv"])
ply:UnCompileString("car", result["cars"])
ply:UnCompileString("skill", result["skills"])
ply:UnCompileString("storage", result["storage"])
ply:UnCompileString("wardrobe", result["wardrobe"])
ply:UnCompileString("blacklists", result["blacklist"])
ply:UnCompileString("buddies", result["buddies"])
ply:UnCompileString("itembank", result["itembank"])
if ply.OCRPData["Face"] == nil or ply.OCRPData["Face"] == "" then
net.Start("OCRP_ShowStartModel")
net.Send(ply)
else
ply:SetModel(result["model"])
end
ply:SetOrg(result["org_id"])
print("[OCRP] Loaded user " .. ply:Nick() .. " from database.")
success_callback(ply)
else
NewPlayer(ply)
end
end
runOCRPQuery(q, success, failure)
end
function NewPlayer(ply)
ply.OCRPData["Money"]["Wallet"] = 500
ply.OCRPData["Money"]["Bank"] = 4500
ply.OCRPData["Playtime"] = 0
ply:SetOrg(0)
local q = "INSERT INTO `ocrp_users` (STEAM_ID, nick, wallet, bank, playtime, org_id) VALUES ('" .. ocrpdb:escape(ply:SteamID()) .. "', '" .. ocrpdb:escape(ply:Nick()) .. "', '500', '4500', '0', '0');"
runOCRPQuery(q, function()
print("[OCRP] Created new user " .. ply:Nick() .. " in the database.")
net.Start("OCRP_ShowStartModel")
net.Send(ply)
end)
end
function NewOrg(id, name, owner, ownername)
local ownerval = owner .. "|" .. ownername
local q = "INSERT INTO `ocrp_orgs` (orgid, owner, name, lastactivity, perks) VALUES ('" .. id .. "', '" .. ocrpdb:escape(ownerval) .. "', '" .. ocrpdb:escape(name) .. "', '" .. os.time() .. "', '');"
runOCRPQuery(q, function()
print("[OCRP] Created new org " .. name .. " in the database.")
end)
end
function RemoveOrg(id)
local q = "DELETE FROM `ocrp_orgs` WHERE `orgid` = '" .. id .. "';"
runOCRPQuery(q, function()
print("[OCRP] Deleted org with id " .. id .. ".")
end)
local q = "UPDATE `ocrp_users` SET `org_id` = '0', `org_notes` = '' WHERE `org_id` = '" .. id .. "';"
runOCRPQuery(q, function()
print("[OCRP] Removed all members of org with id " .. id .. ".")
end)
end
function GM:ShutDown()
PushSQLData()
PushOrgSQLData()
end
function PushOrgSQLData()
if #player.GetAll() == 0 then return end
if table.Count(OCRP_Orgs) == 0 then return end
local columns = {"orgid", "owner", "name", "applicants", "perks"}
local q = "UPDATE `ocrp_orgs` SET "
local updates = {}
for _,column in pairs(columns) do
updates[column] = "`" .. column .. "` = CASE "
end
for orgid,org in pairs(OCRP_Orgs) do
local t = {}
t["orgid"] = orgid
t["owner"] = org.Owner .. "|" .. org.OwnerName
t["name"] = org.Name
t["applicants"] = CompileOrgString(orgid, "applicants")
t["perks"] = CompileOrgString(orgid, "perks")
for _,column in pairs(columns) do
updates[column] = updates[column] .. "WHEN `orgid` = '" .. orgid .. "' then '" .. ocrpdb:escape(tostring(t[column])) .. "' "
end
end
for column,query in pairs(updates) do
q = q .. query .. "END, "
end
q = string.TrimRight(q, " ")
q = string.TrimRight(q, ",")
q = q .. " WHERE "
for id,_ in pairs(OCRP_Orgs) do
q = q .. "`orgid` = '" .. id .. "' OR "
end
q = string.sub(q, 1, q:len()-3)
q = q .. ";"
runOCRPQuery(q, function()
print("[OCRP] Pushed all org data to database.")
end)
end
function LoadOrgSQLData()
local q = "SELECT * from `ocrp_orgs`;"
local failure = function()
for i=1,5 do
print("[OCRP] An error occurred while trying to load org data from the database. This is a critical error!")
end
end
local success = function(results)
for k,v in pairs(results) do
local t = {}
t.Owner = string.sub(v.owner, 1, string.find(v.owner, "|")-1)
t.OwnerName = string.sub(v.owner, string.find(v.owner, "|")+1, v.owner:len())
t.Name = v.name
t.Applicants = UnCompileOrgString(v.orgid, v.applicants, "applicants")
t.LastOwnerActivity = v.lastactivity
t.Perks = UnCompileOrgString(v.orgid, v.perks, "perks")
t.Members = {}
OCRP_Orgs[v.orgid] = t
end
print("[OCRP] Loaded org data from database.")
local success2 = function(results)
for k,v in pairs(results) do
local t = {}
t.Name = v.nick
t.SteamID = v.STEAM_ID
t.Notes = v.org_notes
t.Playtime = v.playtime
table.insert(OCRP_Orgs[v.org_id].Members, t)
end
print("[OCRP] Loaded org member data from database.")
end
local failure2 = function()
for i=1,5 do
print("[OCRP] An error occurred while trying to load org member data from the database. This is a critical error!")
end
end
local q = "SELECT * FROM `ocrp_users` WHERE org_id > 0;"
runOCRPQuery(q, success2, failure2)
end
runOCRPQuery(q, success, failure)
end
hook.Add("Initialize", "OCRPLoadOrgData", LoadOrgSQLData)
function CompileOrgString(orgid, str)
local compiled = ""
if not orgid or orgid == 0 then return compiled end
local org = OCRP_Orgs[orgid]
if not org then return compiled end
if str == "applicants" then
for k,v in pairs(org.Applicants or {}) do
compiled = compiled .. v.SteamID .. "." .. v.Playtime .. "." .. v.Name .. ";"
end
elseif str == "perks" then
for k,v in pairs(org.Perks or {}) do
compiled = compiled .. tostring(k) .. ";"
end
end
return compiled
end
function UnCompileOrgString(orgid, data, str)
local uncompiled = {}
if not orgid or orgid == 0 then return uncompiled end
if str == "applicants" then
for k,v in pairs(string.Explode(";", data, false)) do
if v == "" then continue end
local appinfo = string.Explode(".", v, false)
local t = {}
t.SteamID = appinfo[1]
t.Playtime = tonumber(appinfo[2])
local i = 3
t.Name = ""
while i <= #appinfo do
t.Name = t.Name .. appinfo[i] .. "."
i = i + 1
end
t.Name = string.sub(t.Name, 1, t.Name:len()-1)
table.insert(uncompiled, t)
end
elseif str == "perks" then
for k,v in pairs(string.Explode(";", data, false)) do
if not GAMEMODE.OCRPPerks[tonumber(v)] then continue end
uncompiled[tonumber(v)] = true
end
end
return uncompiled
end
concommand.Add("ocrp_forcesqlpush", function(ply, cmd, args)
if ply and ply:IsValid() then return end
PushSQLData()
PushOrgSQLData()
end) |
require "shared"
local settings_key_prefix = "a2x1_config_bits" .. "-" .. "data_raw_ammo" .. "-"
-- function __settings_startup__data_raw_ammo(data, order)
-- return data:extend(
-- {
-- {
-- type = "int-setting",
-- name = settings_key_prefix .. "damage",
-- setting_type = "startup",
-- default_value = 500,
-- maximum_value = 100000,
-- minimum_value = 1,
-- localised_name = "Gun Damage",
-- localised_description = "1% Smaller - 100% Default - 100000% Larger",
-- order = tonumber(order .. "1")
-- }
-- }
-- )
-- end
function __data__data_raw_ammo(data, settings)
for k, v in pairs(data.raw["ammo"]) do
--
-- if type(v) == "table" and type(v.ammo_type) == "table" and type(v.ammo_type.action) == "table" then
-- __shared__parse_data_action(v.ammo_type.action, (settings.startup[settings_key_prefix .. "damage"].value or 100))
-- end
if settings.startup["a2x1_config_bits" .. "-" .. "dual_damage"].value then
if v.ammo_type and v.ammo_type.action then
if v.ammo_type.action.action_delivery and v.ammo_type.action.action_delivery.target_effects then
update_target_effects(v.ammo_type.action.action_delivery.target_effects)
else
--
for k1, v1 in pairs(v.ammo_type.action) do
if type(v1) == "table" and v1.action_delivery then
for k2, v2 in pairs(v1.action_delivery) do
if type(v2) == "table" and v2.target_effects then
--
update_target_effects(v2.target_effects)
--
end
end
end
end
end
end
end
end
end
function update_target_effects(target_effects)
local damage_type, damage_amount
for k, v in pairs(target_effects) do
if type(v) == "table" and v.damage then
damage_type = v.damage.type
damage_amount = v.damage.amount
end
end
if damage_type == "physical" then
table.insert(target_effects, {type = "damage", damage = {amount = damage_amount, type = "impact"}})
end
end
|
-- File : sd.lua
-- Who : x-Felix-x
-- Based on: https://github.com/jamores/eth-ws-someip/blob/master/sd.lua
-- What : SD-over-SOMEIP dissector, called heuristically from SOMEIP
-- bitwise ops helpers
local band, bor = bit.band, bit.bor
local lshift, rshift = bit.lshift, bit.rshift
local tohex = bit.tohex
-- SD protocol
p_sd = Proto("sd", "SD")
local f_flags = ProtoField.uint8("sd.flags", "Flags", base.HEX)
local f_res = ProtoField.uint24("sd.res", "Reserved", base.HEX)
local f_ents_len = ProtoField.uint32("sd.len_ent", "LengthEntries", base.HEX)
local f_ents = ProtoField.bytes("sd.ent", "EntriesArray")
local f_opts_len = ProtoField.uint32("sd.len_opt", "LengthOptions", base.HEX)
local f_opts = ProtoField.bytes("sd.opt", "OptionsArray")
p_sd.fields = {f_flags, f_res, f_ents_len, f_ents, f_opts_len, f_opts}
function p_sd.dissector(buf, pinfo, root)
pinfo.cols.protocol = "SOME/IP-SD"
-- create subtree
local subtree = root:add(p_sd, buf(0))
-- add protocol fields to subtree
local offset = 0
-- Flags
subtree:add(f_flags, buf(offset, 1))
offset = offset + 1
-- Reserved
subtree:add(f_res, buf(offset, 3))
offset = offset + 3
-- Entries length
local e_len = buf(offset, 4):uint()
subtree:add(f_ents_len, buf(offset, 4))
offset = offset + 4
-- Entries
--e_tree = subtree:add(f_ents,buf(offset,e_len))
e_tree = subtree:add("EntriesArray")
Dissector.get("sd_entries"):call(buf(offset - 4):tvb(), pinfo, e_tree)
offset = offset + e_len
-- Options length
local o_len = buf(offset, 4):uint()
subtree:add(f_opts_len, buf(offset, 4))
offset = offset + 4
-- Options
--o_tree = subtree:add(f_ents,buf(offset,o_len))
o_tree = subtree:add("OptionsArray")
Dissector.get("sd_options"):call(buf(offset - 4):tvb(), pinfo, o_tree)
offset = offset + o_len
end |
local MRFMM, parent = torch.class('nn.MRFMM', 'nn.Module')
function MRFMM:__init()
parent.__init(self)
self.max_response = nil
end
function MRFMM:implement(mode, target_mrf, tensor_target_mrf, target_mrfnorm, source_x, source_y, input_size, response_size, nInputPlane, nOutputPlane, kW, kH, dW, dH, threshold_conf, strength, gpu_chunck_size_1, gpu_chunck_size_2, backend, gpu)
self.target_mrf = target_mrf:clone()
self.target_mrfnorm = target_mrfnorm:clone()
self.source_x = source_x
self.source_y = source_y
self.input_size = input_size
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.threshold_conf = threshold_conf
self.strength = strength
self.padW = padW or 0
self.padH = padH or self.padW
self.bias = torch.Tensor(nOutputPlane):fill(0)
self.backend = backend
self.gpu = gpu
if self.gpu >= 0 then
if self.backend == 'cudnn' then
self.bias = self.bias:cuda()
else
self.bias = self.bias:cl()
end
end
self.gradTO = torch.Tensor(input_size[1], input_size[2], input_size[3])
self.gradTO_confident = torch.Tensor(input_size[2], input_size[3])
self.response = torch.Tensor(response_size[1], response_size[2], response_size[3])
self.mode = mode -- memory or speed
self.gpu_chunck_size_1 = gpu_chunck_size_1
self.gpu_chunck_size_2 = gpu_chunck_size_2
self.tensor_target_mrfnorm = torch.repeatTensor(target_mrfnorm, 1, self.gpu_chunck_size_2, input_size[3] - (kW - 1))
if self.mode == 'speed' then
if self.backend == 'cudnn' then
self.target_mrf = self.target_mrf:cuda()
self.target_mrfnorm = self.target_mrfnorm:cuda()
self.tensor_target_mrfnorm = self.tensor_target_mrfnorm:cuda()
self.gradTO = self.gradTO:cuda()
self.gradTO_confident = self.gradTO_confident:cuda()
self.response = self.response:cuda()
else
self.target_mrf = self.target_mrf:cl()
self.target_mrfnorm = self.target_mrfnorm:cl()
self.tensor_target_mrfnorm = self.tensor_target_mrfnorm:cl()
self.gradTO = self.gradTO:cl()
self.gradTO_confident = self.gradTO_confident:cl()
self.response = self.response:cl()
end
end
end
local function makeContiguous(self, input, gradOutput)
if not input:isContiguous() then
print('not contiguous, make it so')
self._input = self._input or input.new()
self._input:resizeAs(input):copy(input)
input = self._input
end
if gradOutput then
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
end
return input, gradOutput
end
function MRFMM:updateOutput(input)
input = makeContiguous(self, input)
self.output = input:clone()
return self.output
end
function MRFMM:updateGradInput(input, gradOutput)
input = makeContiguous(self, input)
self.gradTO = self.gradTO:fill(0)
self.gradTO_confident = self.gradTO_confident:fill(0) + 1e-10
local source_mrf, x, y = computeMRFnoTensor(input:float(), self.kW, 1, self.mode == 'memory' and -1 or 1, self.backend)
local source_mrfnorm = torch.Tensor(source_mrf:size()[1])
if self.mode == 'speed' then
if self.backend == 'cudnn' then
source_mrfnorm = torch.sqrt(torch.sum(torch.cmul(source_mrf, source_mrf), 2)):resize(1, y:nElement(), x:nElement())
else
for i_source = 1, source_mrf:size()[1] do
source_mrfnorm[i_source] = torch.sqrt(torch.sum(torch.cmul(source_mrf[i_source], source_mrf[i_source])))
end
source_mrfnorm = source_mrfnorm:resize(1, y:nElement(), x:nElement())
end
else
source_mrfnorm = torch.sqrt(torch.sum(torch.cmul(source_mrf, source_mrf), 2)):resize(1, y:nElement(), x:nElement())
end
local tensor_source_mrfnorm = torch.repeatTensor(source_mrfnorm, self.gpu_chunck_size_1, 1, 1)
if self.gpu >= 0 then
if self.backend == 'cudnn' then
tensor_source_mrfnorm = tensor_source_mrfnorm:cuda()
else
tensor_source_mrfnorm = tensor_source_mrfnorm:cl()
end
end
local nOutputPlane_all = self.nOutputPlane -- hacked for memory safety
local num_chunk = math.ceil(nOutputPlane_all / self.gpu_chunck_size_1)
for i_chunk = 1, num_chunk do
local i_start = (i_chunk - 1) * self.gpu_chunck_size_1 + 1
local i_end = math.min(i_start + self.gpu_chunck_size_1 - 1, nOutputPlane_all)
self.weight = self.target_mrf[{{i_start, i_end}, {1, self.target_mrf:size()[2]}}]
if self.mode == 'memory' then
if self.gpu >= 0 then
if self.backend == 'cudnn' then
self.weight = self.weight:cuda()
else
self.weight = self.weight:cl()
end
end
end
self.nOutputPlane = i_end - i_start + 1
local subBias = self.bias:sub(i_start, i_end)
if self.gpu < 0 then
self.finput = torch.Tensor()
self.fgradInput = torch.Tensor()
end
input.THNN.SpatialConvolutionMM_updateOutput(
input:cdata(),
self.output:cdata(),
self.weight:cdata(),
subBias:cdata(),
self.finput:cdata(),
self.fgradInput:cdata(),
self.kW, self.kH,
self.dW, self.dH,
self.padW, self.padH
)
local temp = self.output
-- normalize w.r.t source_mrfnorm
if i_chunk < num_chunk then
temp = temp:cdiv(tensor_source_mrfnorm)
else
temp = temp:cdiv(tensor_source_mrfnorm[{{1, i_end - i_start + 1}, {1, temp:size()[2]}, {1, temp:size()[3]}}])
end
if self.mode == 'memory' then
temp = temp:float()
end
self.response[{{i_start, i_end}, {1, self.response:size()[2]}, {1, self.response:size()[3]}}] = temp
end
if self.max_response == nil or self.max_response:size()[2] ~= self.response:size()[2] then
local num_chunk_2 = math.ceil(self.response:size()[2] / self.gpu_chunck_size_2)
for i_chunk_2 = 1, num_chunk_2 do
local i_start = (i_chunk_2 - 1) * self.gpu_chunck_size_2 + 1
local i_end = math.min(i_start + self.gpu_chunck_size_2 - 1, self.response:size()[2])
if i_chunk_2 < num_chunk_2 then
self.response[{{1, self.response:size()[1]}, {i_start, i_end}, {1, self.response:size()[3]}}] = self.response[{{1, self.response:size()[1]}, {i_start, i_end}, {1, self.response:size()[3]}}]:cdiv(self.tensor_target_mrfnorm)
else
self.response[{{1, self.response:size()[1]}, {i_start, i_end}, {1, self.response:size()[3]}}] = self.response[{{1, self.response:size()[1]}, {i_start, i_end}, {1, self.response:size()[3]}}]:cdiv(self.tensor_target_mrfnorm[{{1, self.response:size()[1]}, {1, i_end - i_start + 1}, {1, self.response:size()[3]}}])
end
end
local max_response, max_id = torch.max(self.response, 1)
self.max_response = max_response
self.max_id = max_id
end
source_mrf = source_mrf:resize(source_mrf:size()[1], self.nInputPlane, self.kW, self.kH)
self.target_mrf = self.target_mrf:resize(self.target_mrf:size()[1], self.nInputPlane, self.kW, self.kH)
for i_patch = 1, self.source_x:nElement() do
local sel_response = self.max_response[1][self.source_y[i_patch]][self.source_x[i_patch]]
if sel_response >= self.threshold_conf then
local sel_idx = self.max_id[1][self.source_y[i_patch]][self.source_x[i_patch]]
local source_idx = (self.source_y[i_patch] - 1) * x:nElement() + self.source_x[i_patch]
self.gradTO[{{1, self.nInputPlane}, {self.source_y[i_patch], self.source_y[i_patch] + self.kH - 1}, {self.source_x[i_patch], self.source_x[i_patch] + self.kW - 1}}]:add(self.target_mrf[sel_idx] - source_mrf[source_idx])
self.gradTO_confident[{{self.source_y[i_patch], self.source_y[i_patch] + self.kH - 1}, {self.source_x[i_patch], self.source_x[i_patch] + self.kW - 1}}]:add(1)
end
end
self.gradTO:cdiv(torch.repeatTensor(self.gradTO_confident, self.nInputPlane, 1, 1))
self.nOutputPlane = nOutputPlane_all
self.target_mrf = self.target_mrf:resize(self.target_mrf:size()[1], self.nInputPlane * self.kW * self.kH)
if gradOutput:size()[1] == input:size()[1] then
if self.gpu >= 0 then
if self.backend == 'cudnn' then
self.gradInput = gradOutput:clone() + self.gradTO:cuda() * self.strength * (-1)
else
self.gradInput = gradOutput:clone() + self.gradTO:cl() * self.strength * (-1)
end
else
self.gradInput = gradOutput:clone() + self.gradTO * self.strength * (-1)
end
else
self.gradInput = self.gradTO * self.strength * (-1)
end
source_mrf = nil
source_mrfnorm = nil
tensor_source_mrfnorm = nil
collectgarbage()
return self.gradInput
end
function MRFMM:type(type)
self.finput = torch.Tensor()
self.fgradInput = torch.Tensor()
return parent.type(self,type)
end
|
object_intangible_beast_bm_mutated_acklay = object_intangible_beast_shared_bm_mutated_acklay:new {
}
ObjectTemplates:addTemplate(object_intangible_beast_bm_mutated_acklay, "object/intangible/beast/bm_mutated_acklay.iff")
|
local charge = function(...)
local args = {...}
local retArgs = {}
if #args % 2 ~= 0 then
error(("bad argument #%i to '%s' (any of string, table expected; got nil)")
:format(#args + 1, debug.getinfo(1, "n").name or "unknown"), 2)
end
for i = 1, math.max(1, #args), 2 do
local val, cType = args[i], args[i + 1]
local valType, cTypeType = type(val), type(cType)
if cTypeType == "table" then
local shouldError = true
local typeList = ""
for j, v in ipairs(cType) do
shouldError = shouldError and valType ~= v
typeList = typeList .. ", " .. v
end
if shouldError then
error(("bad argument #%i to '%s' (any of %s expected; got %s)")
:format(math.ceil(i / 2)
, debug.getinfo(2, "n").name or "unknown"
, typeList:sub(3, -1)
, valType)
, 3)
end
elseif cTypeType ~= "string" then
error(("bad argument #%i to '%s' (any of string, table expected; got %s)")
:format(i + 1, debug.getinfo(1, "n").name or "unknown", cTypeType), 2)
elseif valType ~= cType then
error(("bad argument #%i to '%s' (%s expected; got %s)")
:format(math.ceil(i / 2), debug.getinfo(2, "n").name or "unknown", cType, valType), 3)
end
retArgs[#retArgs + 1] = val
end
return (unpack and unpack or table.unpack)(retArgs)
end
return charge
|
return {'anus','anussen'} |
local M = {}
---Parses markdown files and returns a table of SymbolInformation[] which is
-- used by the plugin to show the outline.
-- We do this because markdown does not have a LSP.
-- Note that the headings won't have any heirarchy (as of now).
---@return table
function M.handle_markdown()
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
local results = {}
for line, value in ipairs(lines) do
if string.find(value, "^#+") then
if #results > 0 then
results[#results].selectionRange["end"].line = line - 1
results[#results].range["end"].line = line - 1
end
table.insert(results, {
kind = 13,
name = value,
selectionRange = {
start = {character = 1, line = line - 1},
["end"] = {character = 1, line = line - 1}
},
range = {
start = {character = 1, line = line - 1},
["end"] = {character = 1, line = line - 1}
}
})
end
end
return {[1000000]={result=results}}
end
return M
|
spawnpoint 'a_m_y_skater_01' { x = -1048.3, y = -2760.58, z = 4.61 }
spawnpoint 'a_m_y_skater_02' { x = -1052.57, y = -2758.85, z = 4.61 }
spawnpoint 'a_m_y_skater_01' { x = -1050.74, y = -2759.59, z = 4.61 }
spawnpoint 'a_m_y_skater_02' { x = -1049.84, y = -2759.87, z = 4.61 }
-- |
-- lua/rs/GorgeStructureMixin.lua
GorgeStructureMixin = CreateMixin(GorgeStructureMixin)
GorgeStructureMixin.type = "GorgeStructure"
GorgeStructureMixin.kStarveDelay = 60
GorgeStructureMixin.kDieImmediatelyOnStarve = true
GorgeStructureMixin.networkVars =
{
}
GorgeStructureMixin.expectedMixins =
{
Owner = "For tracking gorge owner."
}
GorgeStructureMixin.expectedCallbacks =
{
}
GorgeStructureMixin.optionalCallbacks =
{
}
function GorgeStructureMixin:__initmixin()
PROFILE("GorgeStructureMixin:__initmixin")
assert(Server)
self.timeStarveBegin = 0
self.hasGorgeOwner = true
self.isStarving = false
end
function GorgeStructureMixin:OnStarve()
end
function GorgeStructureMixin:OnStarveEnd()
end
function GorgeStructureMixin:SetOwner(owner)
local hasGorgeOwner = owner and ( owner:isa("Gorge") or (owner:isa("Commander") and owner.previousMapName == Gorge.kMapName) )
if hasGorgeOwner ~= self.hasGorgeOwner then
self.hasGorgeOwner = hasGorgeOwner
if self.hasGorgeOwner then
self:OnStarveEnd()
else
self:OnStarve()
self.timeStarveBegin = Shared.GetTime()
self:AddTimedCallback(GorgeStructureMixin.OnStarveTimeUp, GorgeStructureMixin.kStarveDelay)
end
end
end
function GorgeStructureMixin:GetIsStarving()
return self.isStarving
end
function GorgeStructureMixin:OnStarveTimeUp()
-- Check the time, if we gorged again after this started, but then died again.. we will wait for next callback.
if not self.hasGorgeOwner and GorgeStructureMixin.kDieImmediatelyOnStarve and self.timeStarveBegin + GorgeStructureMixin.kStarveDelay < Shared.GetTime() then
-- time is up, time to die
self:Kill()
end
return false
end
GorgeStructureMixin.OnUpdate = nil
GorgeStructureMixin.OnProcessMove = nil |
pg = pg or {}
pg.enemy_data_statistics_144 = {
[10083007] = {
cannon = 18,
reload = 150,
speed_growth = 0,
cannon_growth = 800,
pilot_ai_template_id = 10001,
air = 0,
rarity = 3,
dodge = 11,
torpedo = 75,
durability_growth = 42500,
antiaircraft = 30,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 3,
hit = 14,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 178,
durability = 1340,
armor_growth = 0,
torpedo_growth = 4800,
luck_growth = 0,
speed = 20,
luck = 0,
id = 10083007,
antiaircraft_growth = 1760,
antisub = 0,
armor = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
540001,
540002
}
},
[10083008] = {
cannon = 17,
reload = 150,
speed_growth = 0,
cannon_growth = 800,
pilot_ai_template_id = 10001,
air = 0,
rarity = 2,
dodge = 11,
torpedo = 75,
durability_growth = 39500,
antiaircraft = 30,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 2,
hit = 14,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 179,
durability = 1280,
armor_growth = 0,
torpedo_growth = 4800,
luck_growth = 0,
speed = 20,
luck = 0,
id = 10083008,
antiaircraft_growth = 1760,
antisub = 0,
armor = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
540003,
540004
}
},
[10083009] = {
cannon = 17,
reload = 150,
speed_growth = 0,
cannon_growth = 800,
pilot_ai_template_id = 10001,
air = 0,
rarity = 2,
dodge = 11,
torpedo = 75,
durability_growth = 39500,
antiaircraft = 30,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 2,
hit = 14,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 180,
durability = 1280,
armor_growth = 0,
torpedo_growth = 4800,
luck_growth = 0,
speed = 20,
luck = 0,
id = 10083009,
antiaircraft_growth = 1760,
antisub = 0,
armor = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
540005,
540006
}
},
[10083101] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 0,
durability_growth = 6800,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
speed = 30,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
hit_growth = 120,
base = 90,
durability = 680,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
antiaircraft_growth = 0,
luck = 0,
battle_unit_type = 20,
id = 10083101,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
}
},
[10083102] = {
cannon = 0,
battle_unit_type = 35,
rarity = 1,
speed_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
luck = 0,
dodge = 0,
wave_fx = "danchuanlanghuaxiao2",
cannon_growth = 0,
speed = 15,
reload_growth = 0,
dodge_growth = 0,
id = 10083102,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
reload = 150,
base = 70,
durability = 260,
armor_growth = 0,
torpedo_growth = 864,
luck_growth = 0,
hit_growth = 120,
armor = 0,
torpedo = 10,
durability_growth = 2550,
antisub = 0,
antiaircraft = 0,
antiaircraft_growth = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
540100
}
},
[10083103] = {
cannon = 50,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 80000,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 95,
durability_growth = 2550,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 1200,
star = 1,
hit = 81,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 15,
base = 80,
durability = 80,
armor_growth = 0,
torpedo_growth = 1080,
luck_growth = 0,
speed = 30,
luck = 0,
id = 10083103,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
540101
}
},
[10083500] = {
cannon = 250,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 70040,
air = 0,
rarity = 6,
dodge = 11,
torpedo = 160,
durability_growth = 0,
antiaircraft = 320,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 6,
hit = 120,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 95,
base = 215,
durability = 26200,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 24,
luck = 0,
id = 10083500,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
540521,
540522,
540523,
540524
}
},
[10091001] = {
cannon = 5,
reload = 150,
speed_growth = 0,
cannon_growth = 300,
rarity = 3,
air = 0,
torpedo = 27,
dodge = 0,
durability_growth = 5000,
antiaircraft = 25,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 3,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 25,
base = 123,
durability = 125,
armor_growth = 0,
torpedo_growth = 3000,
luck_growth = 0,
speed = 15,
armor = 0,
id = 10091001,
antiaircraft_growth = 800,
antisub = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
100219,
535001,
313091
}
},
[10091002] = {
cannon = 10,
reload = 150,
speed_growth = 0,
cannon_growth = 800,
rarity = 3,
air = 0,
torpedo = 22,
dodge = 0,
durability_growth = 7400,
antiaircraft = 45,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 3,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 30,
base = 124,
durability = 210,
armor_growth = 0,
torpedo_growth = 2000,
luck_growth = 0,
speed = 15,
armor = 0,
id = 10091002,
antiaircraft_growth = 1600,
antisub = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
550062,
100349
}
},
[10091003] = {
cannon = 12,
reload = 150,
speed_growth = 0,
cannon_growth = 1500,
rarity = 3,
air = 0,
torpedo = 15,
dodge = 0,
durability_growth = 20000,
antiaircraft = 35,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 3,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 35,
base = 125,
durability = 320,
armor_growth = 0,
torpedo_growth = 1200,
luck_growth = 0,
speed = 15,
armor = 0,
id = 10091003,
antiaircraft_growth = 1000,
antisub = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
100206,
100519,
535002
}
},
[10091004] = {
cannon = 35,
reload = 150,
speed_growth = 0,
cannon_growth = 2000,
rarity = 3,
air = 0,
torpedo = 0,
dodge = 0,
durability_growth = 42000,
antiaircraft = 40,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 3,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 126,
durability = 770,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
id = 10091004,
antiaircraft_growth = 1200,
antisub = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
531033,
531034,
531035
}
},
[10091005] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
rarity = 3,
air = 45,
torpedo = 0,
dodge = 0,
durability_growth = 34000,
antiaircraft = 40,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 3,
hit = 10,
antisub_growth = 0,
air_growth = 1800,
battle_unit_type = 65,
base = 127,
durability = 660,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
id = 10091005,
antiaircraft_growth = 1200,
antisub = 0,
bound_bone = {
cannon = {
{
1.8,
1.14,
0
}
},
torpedo = {
{
1.07,
0.24,
0
}
},
antiaircraft = {
{
1.8,
1.14,
0
}
},
plane = {
{
1.8,
1.14,
0
}
}
},
appear_fx = {
"appearQ"
},
equipment_list = {
550051,
550052,
550053,
550054
}
},
[10091006] = {
cannon = 8,
reload = 150,
speed_growth = 0,
cannon_growth = 800,
rarity = 4,
air = 0,
torpedo = 65,
dodge = 19,
durability_growth = 23500,
antiaircraft = 30,
luck = 0,
reload_growth = 0,
dodge_growth = 270,
hit_growth = 210,
star = 4,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 253,
durability = 560,
armor_growth = 0,
torpedo_growth = 4800,
luck_growth = 0,
speed = 28,
armor = 0,
id = 10091006,
antiaircraft_growth = 1760,
antisub = 0,
bound_bone = {
cannon = {
{
0.6,
0.6,
0
}
},
vicegun = {
{
-0.38,
0.6,
0
}
},
torpedo = {
{
0,
0,
0
}
}
},
smoke = {
{
70,
{
{
"smoke",
{
-0.472,
0.233,
0.467
}
}
}
},
{
40,
{
{
"smoke",
{
0.42,
1.7,
2.07
}
}
}
}
},
equipment_list = {
550011,
550012,
550013
}
},
[10091007] = {
cannon = 12,
reload = 150,
speed_growth = 0,
cannon_growth = 1600,
rarity = 4,
air = 0,
torpedo = 45,
dodge = 17,
durability_growth = 25500,
antiaircraft = 50,
luck = 0,
reload_growth = 0,
dodge_growth = 242,
hit_growth = 210,
star = 4,
hit = 22,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 65,
base = 254,
durability = 700,
armor_growth = 0,
torpedo_growth = 3200,
luck_growth = 0,
speed = 22,
armor = 0,
id = 10091007,
antiaircraft_growth = 3520,
antisub = 0,
bound_bone = {
cannon = {
{
0.6,
0.6,
0
}
},
vicegun = {
{
-0.38,
0.6,
0
}
},
torpedo = {
{
0,
0,
0
}
}
},
smoke = {
{
70,
{
{
"smoke",
{
-0.472,
0.233,
0.467
}
}
}
},
{
40,
{
{
"smoke",
{
0.42,
1.7,
2.07
}
}
}
}
},
equipment_list = {
550021,
550022,
550023,
550024
}
},
[10091008] = {
cannon = 32,
reload = 150,
speed_growth = 0,
cannon_growth = 2400,
rarity = 4,
air = 0,
torpedo = 35,
dodge = 15,
durability_growth = 34000,
antiaircraft = 40,
luck = 0,
reload_growth = 0,
dodge_growth = 214,
hit_growth = 210,
star = 4,
hit = 19,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 70,
base = 255,
durability = 800,
armor_growth = 0,
torpedo_growth = 1920,
luck_growth = 0,
speed = 18,
armor = 0,
id = 10091008,
antiaircraft_growth = 2200,
antisub = 0,
bound_bone = {
cannon = {
{
0.6,
0.6,
0
}
},
vicegun = {
{
-0.38,
0.6,
0
}
},
torpedo = {
{
0,
0,
0
}
}
},
smoke = {
{
70,
{
{
"smoke",
{
-0.472,
0.233,
0.467
}
}
}
},
{
40,
{
{
"smoke",
{
0.42,
1.7,
2.07
}
}
}
}
},
equipment_list = {
550031,
550032,
550033
}
},
[10091009] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
rarity = 4,
air = 45,
torpedo = 0,
dodge = 13,
durability_growth = 54500,
antiaircraft = 45,
luck = 0,
reload_growth = 0,
dodge_growth = 192,
hit_growth = 210,
star = 4,
hit = 16,
antisub_growth = 0,
air_growth = 2880,
battle_unit_type = 80,
base = 256,
durability = 1120,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
id = 10091009,
antiaircraft_growth = 2880,
antisub = 0,
bound_bone = {
cannon = {
{
0.6,
0.6,
0
}
},
vicegun = {
{
-0.38,
0.6,
0
}
},
torpedo = {
{
0,
0,
0
}
}
},
smoke = {
{
70,
{
{
"smoke",
{
-0.472,
0.233,
0.467
}
}
}
},
{
40,
{
{
"smoke",
{
0.42,
1.7,
2.07
}
}
}
}
},
equipment_list = {
550041,
550042,
550043,
550044,
550045,
550046
}
}
}
return
|
id = 'V-57569'
severity = 'medium'
weight = 10.0
title = 'The noexec option must be added to the /tmp partition.'
description = 'Allowing users to execute binaries from world-writable directories such as "/tmp" should never be necessary in normal operation and can expose the system to potential compromise.'
fixtext = 'The "noexec" mount option can be used to prevent binaries from being executed out of "/tmp". Add the "noexec" option to the fourth column of "/etc/fstab" for the line which controls mounting of "/tmp".'
checktext = [=[To verify that binaries cannot be directly executed from the /tmp directory, run the following command:
$ grep '\s/tmp' /etc/fstab
The resulting output will show whether the /tmp partition has the "noexec" flag set. If the /tmp partition does not have the noexec flag set, this is a finding.]=]
function test()
end
function fix()
end
|
local UserInputService = game:GetService("UserInputService")
local replicatedStorage = game:GetService("ReplicatedStorage")
repeat wait() until script.playerModule
local playerModule = require(script.PlayerModule)
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
UserInputService.InputBegan:Connect(function(input, typing)
if not typing then
if input.KeyCode == Enum.KeyCode.F and playerModule.cd1 == false and player.Character.Humanoid:WaitForChild("Animator") then
playerModule.Archway(player)
end
if input.KeyCode == Enum.KeyCode.E and playerModule.cd2 == false and player.Character.Humanoid:WaitForChild("Animator") then
playerModule.Void_Circle(player)
end
if input.KeyCode == Enum.KeyCode.Q and playerModule.cd4 == false and player.Character.Humanoid:WaitForChild("Animator") then
playerModule.FireBall(player)
end
if input.KeyCode == Enum.KeyCode.C and playerModule.cd5 == false and player.Character.Humanoid:WaitForChild("Animator") then
playerModule.JumpKick(player)
end
end
end) |
---@class CS.FairyGUI.BlendModeUtils
---@field public Factors BlendFactor[]
---@type CS.FairyGUI.BlendModeUtils
CS.FairyGUI.BlendModeUtils = { }
---@return CS.FairyGUI.BlendModeUtils
function CS.FairyGUI.BlendModeUtils.New() end
---@param mat CS.UnityEngine.Material
---@param blendMode number
function CS.FairyGUI.BlendModeUtils.Apply(mat, blendMode) end
---@param blendMode number
---@param srcFactor number
---@param dstFactor number
function CS.FairyGUI.BlendModeUtils.Override(blendMode, srcFactor, dstFactor) end
return CS.FairyGUI.BlendModeUtils
|
local function disable_defaults_plugins()
vim.g.loaded_tutor = 1
vim.g.loaded_spec = 1
vim.g.loaded_2html_plugin = 1
vim.g.loaded_getscript = 1
vim.g.loaded_getscriptPlugin = 1
vim.g.loaded_gzip = 1
vim.g.loaded_logipat = 1
vim.g.loaded_logiPat = 1
vim.g.loaded_matchparen = 1
vim.g.loaded_netrw = 1
vim.g.loaded_netrwFileHandlers = 1
vim.g.loaded_netrwPlugin = 1
vim.g.loaded_netrwSettings = 1
vim.g.loaded_rrhelper = 1
vim.g.loaded_spellfile_plugin = 1
vim.g.loaded_sql_completion = 1
vim.g.loaded_syntax_completion = 1
vim.g.loaded_tar = 1
vim.g.loaded_tarPlugin = 1
vim.g.loaded_vimball = 1
vim.g.loaded_vimballPlugin = 1
vim.g.loaded_zip = 1
vim.g.loaded_zipPlugin = 1
vim.g.vimsyn_embed = 1
end
return {disable_defaults_plugins = disable_defaults_plugins}
|
describe("Comment:", function()
local ERRORS = require("expadom.constants").ERRORS
local Comment = require "expadom.Comment"
local utf8 = require("expadom.xmlutils").utf8
local valid_utf8_char = string.char(tonumber("CF",16))..string.char(tonumber("8C",16)) -- "\xCF\x8C", either byte alone is invalid.
-- Repeating it 10 times, so 10 utf8-characters, and 20 bytes.
local valid_utf8 = valid_utf8_char:rep(10)
assert(10 == utf8.len(valid_utf8), "expected data to be valid")
-- Any even number of bytes from the start is VALID.
-- Any uneven number of bytes from the start is INVALID both for
-- the first part as well as for the remainder sequence.
assert(nil == utf8.len(valid_utf8:sub(1,5)), "expected data to be invalid")
assert(nil == utf8.len(valid_utf8:sub(6,-1)), "expected data to be invalid")
local invalid_utf8 = valid_utf8:sub(1,5)
describe("initialization", function()
it("requires a data", function()
assert.has.error(function()
Comment {}
end, "expected data to be a string")
local c = Comment { data = "anything" }
assert.equal("anything", c.data)
end)
end)
describe("properties:", function()
local c
before_each(function()
c = Comment { data = "anything" }
end)
it("reports proper nodeName", function()
assert.equal("#comment", c.nodeName)
end)
it("reports proper nodeValue", function()
assert.equal("anything", c.nodeValue)
end)
describe("data", function()
it("is settable", function()
c.data = "hello"
assert.equal("hello", c.data)
end)
it("doesn't accept non-string data", function()
assert.has.error(function()
c.data = 123
end, "expected data to be a string")
end)
it("doesn't accept invalid utf8", function()
assert.has.error(function()
c.data = invalid_utf8
end, ERRORS.INVALID_CHARACTER_ERR)
end)
end)
describe("length", function()
it("gets set to proper utf8 length", function()
c.data = valid_utf8
assert.equal(20, #c.data) -- in bytes
assert.equal(10, c.length) -- in characters
c.data = ""
assert.equal(0, c.length) -- in characters
end)
end)
end)
describe("methods:", function()
local c
before_each(function()
c = Comment { data = "anything" }
end)
describe("appendData()", function()
it("appends valid data", function()
c.data = valid_utf8
c:appendData(valid_utf8)
assert.equal(20 + 20, #c.data) -- in bytes
assert.equal(10 + 10, c.length) -- in characters
end)
it("fails on invalid type data", function()
c.data = valid_utf8
assert.has.error(function()
c:appendData(invalid_utf8)
end, ERRORS.INVALID_CHARACTER_ERR)
end)
it("fails on invalid utf8 data", function()
c.data = valid_utf8
assert.has.error(function()
c:appendData(invalid_utf8)
end, ERRORS.INVALID_CHARACTER_ERR)
end)
end)
describe("deleteData()", function()
it("deletes data", function()
-- from start
c.data = (valid_utf8_char.." "):rep(5)
c:deleteData(1, 3)
assert.equal(" "..(valid_utf8_char.." "):rep(3), c.data)
-- middle
c.data = (valid_utf8_char.." "):rep(5)
c:deleteData(3, 5)
assert.equal(valid_utf8_char.." "..valid_utf8_char.." ", c.data)
-- end
c.data = (valid_utf8_char.." "):rep(5)
c:deleteData(3, 8)
assert.equal(valid_utf8_char.." ", c.data)
-- beyond end
c.data = (valid_utf8_char.." "):rep(5)
c:deleteData(3, 999)
assert.equal(valid_utf8_char.." ", c.data)
end)
it("fails on invalid offset", function()
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:deleteData(99, 1)
})
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:deleteData(-99, 1)
})
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:deleteData(0, 1)
})
end)
it("fails on invalid count", function()
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:deleteData(2, -1)
})
end)
end)
describe("insertData()", function()
it("inserts data", function()
-- from start
c.data = (valid_utf8_char.." "):rep(5)
c:insertData(1, "abc")
assert.equal("abc"..(valid_utf8_char.." "):rep(5), c.data)
-- middle
c.data = (valid_utf8_char.." "):rep(5)
c:insertData(6, "abc")
assert.equal((valid_utf8_char.." "):rep(2) .. valid_utf8_char .. "abc "..(valid_utf8_char.." "):rep(2), c.data)
-- end
c.data = (valid_utf8_char.." "):rep(5)
c:insertData(10, "abc")
assert.equal((valid_utf8_char.." "):rep(4)..valid_utf8_char.."abc ", c.data)
end)
it("fails on invalid offset", function()
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:insertData(99, "abc")
})
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:insertData(-99, "abc")
})
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:insertData(0, "abc")
})
end)
it("fails on invalid utf8 data", function()
assert.has.error(function()
c:insertData(2, invalid_utf8)
end, ERRORS.INVALID_CHARACTER_ERR)
end)
end)
describe("replaceData()", function()
it("replaces data", function()
-- from start
c.data = (valid_utf8_char.." "):rep(5)
c:replaceData(1, 3, "abc")
assert.equal("abc "..(valid_utf8_char.." "):rep(3), c.data)
-- middle
c.data = (valid_utf8_char.." "):rep(5)
c:replaceData(3, 5, "abc")
assert.equal(valid_utf8_char.." abc "..valid_utf8_char.." ", c.data)
-- end
c.data = (valid_utf8_char.." "):rep(5)
c:replaceData(3, 8, "abc")
assert.equal(valid_utf8_char.." abc", c.data)
-- beyond end
c.data = (valid_utf8_char.." "):rep(5)
c:replaceData(3, 999, "abc")
assert.equal(valid_utf8_char.." abc", c.data)
end)
it("fails on invalid offset", function()
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:replaceData(99, 1, "abc")
})
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:replaceData(-99, 1, "abc")
})
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:replaceData(0, 1, "abc")
})
end)
it("fails on invalid count", function()
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:replaceData(2, -1, "abc")
})
end)
it("fails on invalid utf8 data", function()
assert.has.error(function()
c:replaceData(2, 2, invalid_utf8)
end, ERRORS.INVALID_CHARACTER_ERR)
end)
end)
describe("substringData()", function()
it("returns the substring", function()
-- from start
c.data = (valid_utf8_char.." "):rep(5)
assert.equal(valid_utf8_char.." "..valid_utf8_char, c:substringData(1, 3))
-- middle
c.data = (valid_utf8_char.." "):rep(5)
assert.equal(valid_utf8_char.." "..valid_utf8_char.." "..valid_utf8_char, c:substringData(3, 5))
-- end
c.data = (valid_utf8_char.." "):rep(5)
assert.equal(valid_utf8_char.." ", c:substringData(9, 2))
-- beyond end
c.data = (valid_utf8_char.." "):rep(5)
assert.equal(valid_utf8_char.." ", c:substringData(9, 999))
end)
it("fails on invalid offset", function()
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:substringData(99, 1)
})
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:substringData(-99, 1)
})
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:substringData(0, 1)
})
end)
it("fails on invalid count", function()
assert.same({
nil, ERRORS.INDEX_SIZE_ERR
}, {
c:substringData(2, -1)
})
end)
end)
describe("write()", function()
it("exports data and returns buffer", function()
assert.same({ "<!--anything-->" }, c:write({}))
end)
end)
end)
end)
|
object_tangible_furniture_rustic_cabinet_rustic_s01 = object_tangible_furniture_rustic_shared_cabinet_rustic_s01:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_rustic_cabinet_rustic_s01, "object/tangible/furniture/rustic/cabinet_rustic_s01.iff")
|
LJ4 9 BL registerScriptTapHandler? 6 9 6 93 =K onClicked
MenuItem Menucc |
ITEM.name = "Civil-Approved Purfication Tablets"
ITEM.model = Model("models/mark2580/gtav/garage_stuff/oilbot02.mdl")
ITEM.description = "A plastic jar with large tablets, it has a biohazard symbol labled onto the jar."
ITEM.width = 1
ITEM.height = 1
ITEM.price = 5
ITEM.category = "Crafting"
ITEM.noBusiness = true
ITEM.combine = function(item, targetItem)
local client = item:GetOwner()
local inventory = client:GetCharacter():GetInventory()
if(targetItem.uniqueID == "water_dirty") then
inventory:Add("unionwater", 2)
return true
end
end |
return {
legend = {
{ },
{ "IgnoreSelected" },
{ "Sensor" }
},
label = _("Sensors"),
category = "general"
}
|
local gobonet = {}
local gears = require("gears")
local timer = gears.timer or timer
local mouse = mouse
local awful = require("awful")
local wibox = require("wibox")
local beautiful = require("beautiful")
local spawn = require("awful.spawn")
local core = require("gobo.awesome.gobonet.core")
local wlan_interface
local wired_interface
local function pread(cmd)
local pd = io.popen(cmd, "r")
if not pd then
return ""
end
local data = pd:read("*a")
pd:close()
return data
end
local function read_wifi_level()
local fd = io.open("/proc/net/wireless", "r")
if fd then
fd:read("*l")
fd:read("*l")
local data = fd:read("*l")
fd:close()
if data then
local value = data:match("^%s*[^%s]+:%s+[^%s]+%s*(%d+)")
if value then
return tonumber(value)
end
end
end
end
local function quality_icon(quality)
if quality >= 75 then
return beautiful.wifi_3_icon
elseif quality >= 50 then
return beautiful.wifi_2_icon
elseif quality >= 25 then
return beautiful.wifi_1_icon
else
return beautiful.wifi_0_icon
end
end
local run = awful.spawn and awful.spawn.with_shell or awful.util.spawn_with_shell
local function disconnect()
run("gobonet disconnect")
end
local function forget(essid)
run("gobonet forget '"..essid:gsub("'", "'\\''").."'")
end
local function compact_entries(entries)
local limit = 20
if #entries > limit then
local submenu = {}
for i = limit + 1, #entries do
table.insert(submenu, entries[i])
entries[i] = nil
end
compact_entries(submenu)
table.insert(entries, { "More...", submenu } )
end
end
function gobonet.new()
local widget = wibox.widget.imagebox()
local menu
local wifi_menu_fn
if not wlan_interface then
wlan_interface = pread("gobonet interface")
end
if not wired_interface then
wired_interface = pread("gobonet wired_interface")
-- Outdated GoboNet
if wired_interface:match("^GoboNet") then
wired_interface = nil
end
wired_interface = wired_interface:gsub("\n", "")
-- No wired interface
if wired_interface == "" then
wired_interface = nil
end
end
if not (wlan_interface or wired_interface) then
return widget
end
local is_scanning = function() return false end
local is_connecting = function() return false end
local function animated_operation(args)
local cmd = args.command
local popup_menu = args.popup_menu_when_done or false
if not cmd then return end
local waiting
local is_waiting = function()
if not waiting then return false end
if waiting() ~= true then
return true
end
waiting = nil
return false
end
return function()
if is_waiting() then
return is_waiting
end
do
local done = false
waiting = function()
return done
end
spawn.easy_async(cmd, function()
done = true
end)
end
local frames = args.frames or {
beautiful.wifi_0_icon,
beautiful.wifi_1_icon,
beautiful.wifi_2_icon,
beautiful.wifi_3_icon,
}
local step = 1
local animation_timer = timer({timeout=0.25})
local function animate()
if is_waiting() then
widget:set_image(frames[step])
step = step + 1
if step == #frames + 1 then step = 1 end
else
animation_timer:stop()
if popup_menu then
if menu then
menu:hide()
menu = nil
end
wifi_menu_fn(true)
end
end
end
animation_timer:connect_signal("timeout", animate)
animation_timer:start()
return is_waiting
end
end
local function is_external_scanning()
local pidfilename = os.getenv("HOME").."/.cache/GoboNet/wifi/.connecting.pid"
local pidfd = io.open(pidfilename, "r")
if not pidfd then return false end
local pid = pidfd:read("*l")
pidfd:close()
local statfilename = "/proc/"..pid.."/stat"
local statfd = io.open(statfilename, "r")
if not statfd then
os.remove(pidfilename)
return false
end
statfd:close()
is_scanning = animated_operation { command = "bash -c 'while grep -q gobonet \""..statfilename.."\"; do sleep 0.5; done; rm \""..pidfilename.."\"'" } ()
return true
end
local rescan = animated_operation { command = "gobonet_backend full-scan "..wlan_interface, popup_menu_when_done = true }
local function connect(essid)
return animated_operation { command = "gobonet connect '"..essid:gsub("'", "'\\''").."'" } ()
end
local function autoconnect()
return animated_operation { command = "gobonet autoconnect" } ()
end
local function connect_wired()
return animated_operation { command = "gobonet connect_wired", frames = { beautiful.wired_up_icon, beautiful.wired_down_icon } } ()
end
local last_update = os.time()
local function update()
local prev_update = last_update
last_update = os.time()
if is_scanning() or is_connecting() or is_external_scanning() then
return
end
if wired_interface then
local pok, up, running = pcall(core.up_and_running, wired_interface)
if pok and up and running then
widget:set_image(beautiful.wired_up_icon)
return
end
end
local wifi_level = read_wifi_level()
if not wifi_level then
if wlan_interface then
widget:set_image(beautiful.wifi_down_icon)
else
widget:set_image(beautiful.wired_down_icon)
end
-- A long time elapsed between updates probably means
-- the computer went asleep. Let's try to autoconnect.
if last_update - prev_update > 10 then
is_connecting = autoconnect()
end
else
local quality = (tonumber(wifi_level) / 70) * 100
widget:set_image(quality_icon(quality))
end
end
local coords
wifi_menu_fn = function(auto_popped)
if not auto_popped then
coords = mouse.coords()
end
if menu then
if menu.wibox.visible then
menu:hide()
menu = nil
return
else
menu = nil
end
end
local iwconfig = pread("iwconfig")
local my_essid = iwconfig:match('ESSID:"([^\n]*)"%s*\n')
local scan = ""
if not is_scanning() then
scan = pread("gobonet_backend quick-scan "..wlan_interface)
end
local entries = {}
local curr_entry
for key, value in scan:gmatch("%s*([^:=]+)[:=]([^\n]*)\n") do
if key:match("^Cell ") then
if curr_entry then
table.insert(entries, curr_entry)
end
curr_entry = { [1] = " " .. value:gsub(" ", "") }
elseif key == "ESSID" then
local essid = value:match('^"(.*)"$')
if essid ~= "" then
local label = " " .. essid
curr_entry[1] = label
curr_entry[2] = function() is_connecting = connect(essid) end
end
elseif key == "Quality" then
local cur, max = value:match("^(%d+)/(%d+)")
local quality = (tonumber(cur) / tonumber(max)) * 100
curr_entry.quality = quality
curr_entry[3] = quality_icon(quality)
end
end
if curr_entry then
table.insert(entries, curr_entry)
end
table.sort(entries, function(a,b)
return (a.quality or 0) > (b.quality or 0)
end)
if my_essid then
local disconnect_msg = is_connecting() and " Cancel connecting to " or " Disconnect "
table.insert(entries, 1, { disconnect_msg .. my_essid, function() disconnect() end })
table.insert(entries, 2, { " Forget " .. my_essid, function() forget(my_essid) end })
end
if is_scanning() then
table.insert(entries, { " Scanning..." })
elseif #entries == 0 and not auto_popped then
table.insert(entries, { " Scanning..." })
is_scanning = rescan()
else
table.insert(entries, { " Rescan", function() is_scanning = rescan() end } )
end
if wired_interface then
table.insert(entries, 1, { " Wired network ("..wired_interface..") ", function() connect_wired() end, beautiful.wired_up_icon })
end
local len = 10
for _, entry in ipairs(entries) do
len = math.max(len, (#entry[1] + 1) * 10 )
end
entries.theme = { height = 24, width = len }
compact_entries(entries)
menu = awful.menu.new(entries)
menu:show({ coords = coords })
end
widget:buttons(awful.util.table.join(
awful.button({ }, 1, function() wifi_menu_fn() end ),
awful.button({ }, 3, function() wifi_menu_fn() end )
))
local wifi_timer = timer({timeout=2})
wifi_timer:connect_signal("timeout", update)
update()
wifi_timer:start()
return widget
end
return gobonet
|
require(GetScriptDirectory() .. "/logic")
require(GetScriptDirectory() .. "/ability_item_usage_generic")
local debugmode=false
local npcBot = GetBot()
local Talents ={}
local Abilities ={}
local AbilitiesReal ={}
ability_item_usage_generic.InitAbility(Abilities,AbilitiesReal,Talents)
local AbilityToLevelUp=
{
Abilities[1],
Abilities[3],
Abilities[1],
Abilities[2],
Abilities[1],
Abilities[4],
Abilities[1],
Abilities[2],
Abilities[2],
"talent",
Abilities[2],
Abilities[4],
Abilities[3],
Abilities[3],
"talent",
Abilities[3],
"nil",
Abilities[4],
"nil",
"talent",
"nil",
"nil",
"nil",
"nil",
"talent",
}
local TalentTree={
function()
return Talents[2]
end,
function()
return Talents[4]
end,
function()
return Talents[5]
end,
function()
return Talents[7]
end
}
logic.CheckAbilityBuild(AbilityToLevelUp)
function AbilityLevelUpThink()
ability_item_usage_generic.AbilityLevelUpThink2(AbilityToLevelUp,TalentTree)
end
local cast={} cast.Desire={} cast.Target={} cast.Type={}
local Consider ={}
local CanCast={logic.NCanCast,logic.NCanCast,logic.NCanCast,logic.UCanCast}
local enemyDisabled=logic.enemyDisabled
function GetComboDamage()
return ability_item_usage_generic.GetComboDamage(AbilitiesReal)
end
function GetComboMana()
return ability_item_usage_generic.GetComboMana(AbilitiesReal)
end
Consider[1]=function()
local Radius = AbilitiesReal[1]:GetAOERadius()
if(npcBot.Sniper1==nil)
then
npcBot.Sniper1={}
end
local desire,templocation=Consider1()
if(desire~=0)
then
for _,i in pairs(npcBot.Sniper1)
do
if(DotaTime()>=i.timer+10)
then
table.remove(npcBot.Sniper1,_)
end
if(logic.PointToPointDistance(i.location,templocation))<Radius*1.5 or (DotaTime()-i.timer<=2)
then
desire=0
end
end
end
if(desire==0)
then
return BOT_ACTION_DESIRE_NONE, 0;
else
table.insert(npcBot.Sniper1,{timer=DotaTime(),location=templocation})
return desire,templocation
end
end
function Consider1()
local abilityNumber=1
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local CastRange = ability:GetCastRange();
local Damage = ability:GetAbilityDamage();
local Radius = ability:GetAOERadius()
local CastPoint = ability:GetCastPoint();
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys = npcBot:GetNearbyHeroes(1600,true,BOT_MODE_NONE)
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
local creeps = npcBot:GetNearbyCreeps(1600,true)
local WeakestCreep,CreepHealth=logic.GetWeakestUnit(creeps)
if(npcBot:GetActiveMode() ~= BOT_MODE_RETREAT )
then
if (WeakestEnemy~=nil)
then
if ( CanCast[abilityNumber]( WeakestEnemy ) )
then
if(HeroHealth<=WeakestEnemy:GetActualIncomingDamage(Damage,DAMAGE_TYPE_MAGICAL) or (HeroHealth<=WeakestEnemy:GetActualIncomingDamage(GetComboDamage(),DAMAGE_TYPE_MAGICAL) and npcBot:GetMana()>ComboMana))
then
return BOT_ACTION_DESIRE_HIGH,WeakestEnemy:GetExtrapolatedLocation(CastPoint);
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_FARM ) then
local locationAoE = npcBot:FindAoELocation( true, false, npcBot:GetLocation(), CastRange, Radius, 0, Damage );
if ( locationAoE.count >= 3 ) then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc;
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_TOP or
npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_MID or
npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_BOT or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_TOP or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_MID or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_BOT )
then
local locationAoE = npcBot:FindAoELocation( true, false, npcBot:GetLocation(), CastRange, Radius, 0, 0 );
if ( locationAoE.count >= 4 )
then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc;
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_RETREAT and npcBot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH )
then
for _,npcEnemy in pairs( enemys )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) )
then
if ( CanCast[abilityNumber]( npcEnemy ) )
then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy:GetExtrapolatedLocation(CastPoint);
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROAM or
npcBot:GetActiveMode() == BOT_MODE_TEAM_ROAM or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_ALLY or
npcBot:GetActiveMode() == BOT_MODE_ATTACK)
then
local locationAoE = npcBot:FindAoELocation( true, true, npcBot:GetLocation(), CastRange, Radius, 0, 0 );
if ( locationAoE.count >= 2 ) then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc;
end
local npcEnemy = npcBot:GetTarget();
if ( npcEnemy ~= nil )
then
if ( CanCast[abilityNumber]( npcEnemy ) )
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy:GetExtrapolatedLocation(CastPoint);
end
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
Consider[4]=function()
local abilityNumber=4
local ability=AbilitiesReal[abilityNumber];
if not ability:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
local CastRange = ability:GetCastRange();
local Damage = ability:GetAbilityDamage();
local CastPoint = ability:GetCastPoint();
local allys = npcBot:GetNearbyHeroes( 1200, false, BOT_MODE_NONE );
local enemys2 = npcBot:GetNearbyHeroes(1000,true,BOT_MODE_NONE)
local enemys = GetUnitList(UNIT_LIST_ENEMY_HEROES)
for i,enemy in pairs(enemys)
do
if(GetUnitToUnitDistance(npcBot,enemy)>CastRange)
then
table.remove(enemys,i)
end
end
local WeakestEnemy,HeroHealth=logic.GetWeakestUnit(enemys)
local creeps = npcBot:GetNearbyCreeps(1600,true)
local WeakestCreep,CreepHealth=logic.GetWeakestUnit(creeps)
for _,npcEnemy in pairs( enemys )
do
if ( npcEnemy:IsChanneling() and CanCast[abilityNumber]( npcEnemy ))
then
return BOT_ACTION_DESIRE_HIGH, npcEnemy
end
end
if(npcBot:GetActiveMode() ~= BOT_MODE_RETREAT )
then
if (WeakestEnemy~=nil)
then
if ( CanCast[abilityNumber]( WeakestEnemy ) )
then
if(HeroHealth+WeakestEnemy:GetHealthRegen()*CastPoint<=WeakestEnemy:GetActualIncomingDamage(Damage,DAMAGE_TYPE_MAGICAL))
then
return BOT_ACTION_DESIRE_HIGH,WeakestEnemy;
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_LANING or
npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_TOP or
npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_MID or
npcBot:GetActiveMode() == BOT_MODE_PUSH_TOWER_BOT or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_TOP or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_MID or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_TOWER_BOT)
then
if(ManaPercentage>0.5 or npcBot:GetMana()>ComboMana )
then
if (WeakestEnemy~=nil and #enemys2==0)
then
if ( CanCast[abilityNumber]( WeakestEnemy ) )
then
return BOT_ACTION_DESIRE_LOW,WeakestEnemy;
end
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROAM or
npcBot:GetActiveMode() == BOT_MODE_TEAM_ROAM or
npcBot:GetActiveMode() == BOT_MODE_DEFEND_ALLY or
npcBot:GetActiveMode() == BOT_MODE_ATTACK )
then
local npcEnemy = npcBot:GetTarget();
if ( npcEnemy ~= nil and #enemys2==0)
then
if ( CanCast[abilityNumber]( npcEnemy ) and GetUnitToUnitDistance(npcBot,npcEnemy)>600)
then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy
end
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function AbilityUsageThink()
if ( npcBot:IsUsingAbility() or npcBot:IsChanneling() or npcBot:IsSilenced() )
then
return
end
ComboMana=GetComboMana()
AttackRange=npcBot:GetAttackRange()
ManaPercentage=npcBot:GetMana()/npcBot:GetMaxMana()
HealthPercentage=npcBot:GetHealth()/npcBot:GetMaxHealth()
cast=ability_item_usage_generic.ConsiderAbility(AbilitiesReal,Consider)
if(debugmode==true)
then
ability_item_usage_generic.PrintDebugInfo(AbilitiesReal,cast)
end
ability_item_usage_generic.UseAbility(AbilitiesReal,cast)
end
function CourierUsageThink()
ability_item_usage_generic.CourierUsageThink()
end |
local changes = {}
local function add_change(region, text)
table.insert(changes, { region, text })
end
local function reset()
changes = {}
end
-- cursor is the original cursor before the refactor
local function adjust_cursor(refactor)
local win = refactor.win
local cursor = refactor.cursor
local add_rows = 0
for _, edit in pairs(changes) do
local region = edit[1]
local text = edit[2]
local start = region.start_row
-- this counts occurances of newline not lines in there with spaces
local length = select(2, text:gsub("\n", "\n"))
local diff = region.end_row - region.start_row
if length ~= 0 and diff > length then
length = length - 1
end
length = length - diff
if start < cursor.row then
add_rows = add_rows + length
end
end
local r, _ = cursor:to_vim_win()
local result_row = r + add_rows
vim.schedule(function()
vim.api.nvim_win_set_cursor(win, {
result_row,
refactor.highlight_start_col - 1,
})
end)
reset()
return true, refactor
end
return {
adjust_cursor = adjust_cursor,
reset = reset,
add_change = add_change,
}
|
return function(parent, dir)
local lgi = require 'lgi'
local Gtk = lgi.Gtk
local Gdk = lgi.Gdk
local cairo = lgi.cairo
local Pango = lgi.Pango
local PangoCairo = lgi.PangoCairo
local RADIUS = 150
local N_WORDS = 5
local FONT = 'Serif 18'
local HEART = '♥'
local TEXT = 'I ♥ GTK+'
local window = Gtk.Window {
title = "Rotated Text",
default_width = 4 * RADIUS,
default_height = 2 * RADIUS,
Gtk.Box {
orientation = 'HORIZONTAL',
homogeneous = true,
Gtk.DrawingArea {
id = 'circle',
},
Gtk.Label {
id = 'label',
angle = 45,
label = TEXT,
},
}
}
-- Override background color of circle drawing area.
window.child.circle:override_background_color(
'NORMAL', Gdk.RGBA { red = 1, green = 1, blue = 1, alpha = 1 })
local function fancy_shape_renderer(cr, attr, do_path)
cr:translate(cr:get_current_point())
cr:scale(attr.ink_rect.width / Pango.SCALE,
attr.ink_rect.height / Pango.SCALE)
-- Draw the manually.
cr:move_to(0.5, 0)
cr:line_to(0.9, -0.4)
cr:curve_to(1.1, -0.8, 0.5, -0.9, 0.5, -0.5)
cr:curve_to(0.5, -0.9, -0.1, -0.8, 0.1, -0.4)
cr:close_path()
if not do_path then
cr:set_source_rgb(1, 0, 0)
cr:fill()
end
end
local function create_fancy_attr_list_for_layout(layout)
-- Get font metrics and prepare fancy shape size.
local ascent = layout.context:get_metrics(layout.font_description).ascent
local rect = Pango.Rectangle { x = 0, width = ascent,
y = -ascent, height = ascent }
-- Create attribute list, add specific shape renderer for every
-- occurence of heart symbol.
local attrs = Pango.AttrList()
local start_index, end_index = 1, 1
while true do
start_index, end_index = TEXT:find(HEART, end_index + 1, true)
if not start_index then break end
local attr = Pango.Attribute.shape_new(rect, rect)
attr.start_index = start_index - 1
attr.end_index = end_index
attrs:insert(attr)
end
return attrs
end
function window.child.circle:on_draw(cr)
-- Create a cairo context and set up a transformation matrix so that
-- the user space coordinates for the centered square where we draw
-- are [-RADIUS, RADIUS], [-RADIUS, RADIUS]. We first center, then
-- change the scale.
local device_radius = math.min(self.width, self.height) / 2
cr:translate(device_radius + (self.width - 2 * device_radius) / 2,
device_radius + (self.height - 2 * device_radius) / 2)
cr:scale(device_radius / RADIUS, device_radius / RADIUS)
-- Create a subtle gradient source and use it.
local pattern = cairo.Pattern.create_linear(-RADIUS, -RADIUS,
RADIUS, RADIUS)
pattern:add_color_stop_rgb(0, 0.5, 0, 0)
pattern:add_color_stop_rgb(1, 0, 0, 0.5)
cr:set_source(pattern)
-- Create a Pango.Context and set up our shape renderer.
local context = self:create_pango_context()
context.shape_renderer = fancy_shape_renderer
-- Create a Pango.Layout, set the text, font and attributes.
local layout = Pango.Layout.new(context)
layout.text = TEXT
layout.font_description = Pango.FontDescription.from_string(FONT)
layout.attributes = create_fancy_attr_list_for_layout(layout)
-- Draw the layout N_WORDS times in a circle.
for i = 1, N_WORDS do
-- Inform Pango to re-layout the text with the new transformation
-- matrix.
cr:update_layout(layout)
local width, height = layout:get_pixel_size()
cr:move_to(-width / 2, -RADIUS * 0.9)
cr:show_layout(layout)
-- Rotate for the next turn.
cr:rotate(2 * math.pi / N_WORDS)
end
end
-- Set up fancy stuff on the label.
local label = window.child.label
local layout = label:get_layout()
layout.context.shape_renderer = fancy_shape_renderer
label:set_attributes(create_fancy_attr_list_for_layout(layout))
window:show_all()
return window
end,
"Rotated Text",
table.concat {
[[This demo shows how to use PangoCairo to draw rotated and transformed ]],
[[text. The right pane shows a rotated Gtk.Label widget.
]],
[[In both cases, a custom PangoCairo shape renderer is installed ]],
[[to draw a red heard using cairo drawing operations instead of ]],
[[the Unicode heart character.]]
}
|
--
-- Antitroll things
--
local antitroll = {}
bls.antitroll = antitroll
-- "Kicks" players
function antitroll.kick_player(name)
minetest.show_formspec(name, 'formspeclib:ignore',
'list[___die;haxxor;0,0;0,0]')
minetest.after(0.25, minetest.kick_player, name, 'You appear to be a bot.')
end
minetest.register_chatcommand('crash', {
params = '<name>',
description = 'Kicks players and crashes their client.',
privs = {kick=true},
func = function(name, param)
if not minetest.get_player_by_name(param) then
return false, 'Player "' .. param .. '" doesn\'t exist!'
end
minetest.log('action', name .. ' crash-kicks ' .. param)
antitroll.kick_player(param)
return true, 'Crash-kicked ' .. param .. '.'
end,
})
|
pfDB["zones"]["frFR-tbc"] = {
[3] = "Terres ingrates",
[4] = "Terres foudroyées",
[8] = "Marais des Chagrins",
[9] = "Vallée de Comté-du-nord",
[10] = "Bois de la Pénombre",
[11] = "Les Paluns",
[15] = "Marécage d\'Âprefange",
[17] = "Les Tarides",
[23] = "Fleuve Comté-du-nord",
[24] = "Abbaye de Comté-du-nord",
[25] = "Mont Rochenoire",
[28] = "Maleterres de l\'ouest",
[33] = "Vallée de Strangleronce",
[40] = "Marche de l\'Ouest",
[41] = "Défilé de Deuillevent",
[42] = "Sombre-comté",
[44] = "Les Carmines",
[51] = "Gorge des Vents brûlants",
[54] = "Mine Veine-de-jaspe",
[57] = "Mine de Fondugouffre",
[59] = "Vignoble de Comté-du-nord",
[62] = "Champ de potirons des Saumepuits",
[63] = "La ferme des Champierreux",
[65] = "Reuse Me 3",
[66] = "Reuse Me 6",
[67] = "Reuse Me 5",
[69] = "Comté-du-lac",
[75] = "Pierrêche",
[77] = "Courbenclume",
[80] = "Monts Hurlevent",
[87] = "Comté-de-l’or",
[109] = "Ferme de potirons de Froncebouille",
[111] = "Mine Veine-de-Jango",
[130] = "Forêt des Pins argentés",
[135] = "Repaire des Crins-de-givre",
[139] = "Maleterres de l\'est",
[142] = "Excavations de Baguefer",
[148] = "Sombrivage",
[189] = "Dépôt de Grillacier",
[190] = "Âtreval",
[195] = "École de nécromancie",
[199] = "Champ de Gangrepierre",
[206] = "INUTILISÉ Marche de l\'Ouest",
[210] = "Reuse Me 2",
[222] = "Sabot-de-sang",
[230] = "Le mur de Grisetête",
[247] = "Site de fouilles de Crasseboue",
[252] = "Bastion des Rochenoires",
[254] = "Mont Rochenoire",
[267] = "Contreforts de Hautebrande",
[271] = "Austrivage",
[275] = "Donjon de Fort-de-Durn",
[280] = "Strahnbrande",
[286] = "Champs de Hautebrande",
[287] = "Hautebrande",
[288] = "Mine de Veine-azur",
[309] = "Tombe de Barbe-de-fer",
[317] = "Village Fânécorce",
[322] = "Épaves des Flots noirs",
[331] = "Orneval",
[346] = "Site de fouilles de Martèlorteil",
[349] = "Donjon des Marteaux-hardis",
[357] = "Féralas",
[361] = "Gangrebois",
[374] = "Baie de Lamepoing",
[375] = "Rivage d\'Oeil-mort",
[392] = "Cabestan",
[393] = "Grève des Sombrelances",
[396] = "Puits Sabot-d\'hiver",
[397] = "Puits Corne-tonnerre",
[398] = "Puits Crin-sauvage",
[400] = "Mille pointes",
[406] = "Les Serres-Rocheuses",
[426] = "Retraite de Raynebois",
[433] = "La Falfarren",
[437] = "Camp de bûcherons Chanteguerre",
[450] = "Excavations de Songerrance",
[470] = "Les Pitons du Tonnerre UNUSED",
[473] = "Roche du manteau",
[479] = "Site de fouilles de Cognerouille",
[493] = "Reflet-de-Lune",
[501] = "Épave de Beezil",
[512] = "Sabot-noir",
[618] = "Berceau-de-l\'Hiver",
[716] = "Base de Baguefer",
[803] = "Ferme des Distillambre",
[809] = "Portes de Forgefer",
[810] = "Étang immobile",
[919] = "Étang de Stendel",
[1038] = "Portes des Gueules-de-dragon",
[1098] = "Manoir Mantebrume",
[1100] = "Base des Totems-sinistres",
[1116] = "Bastion de Pennelune",
[1121] = "Île de l\'effroi",
[1137] = "Étendues sauvages",
[1227] = "Baie des Tempêtes",
[1228] = "La grève Fracassée",
[1230] = "Récif Déchiqueté",
[1232] = "Colosse de Crête-du-corbeau",
[1233] = "La crête Lugubre",
[1235] = "Sanctuaire de Chantelombre",
[1445] = "Mont Rochenoire",
[1497] = "Fossoyeuse",
[1519] = "Hurlevent",
[1537] = "Forgefer",
[1583] = "Pic Rochenoire",
[1584] = "Profondeurs de Rochenoire",
[1617] = "Vallée des Héros",
[1638] = "Les Pitons du Tonnerre",
[1837] = "Cavernes Fânécorce",
[1858] = "Roche\'gor",
[1880] = "Taudis de Barbe-de-plumes",
[1881] = "Camp de Croquejarret",
[1897] = "La Terrasse du Faiseur",
[2037] = "Quel\'thalas",
[2102] = "Distillerie Tonnebière",
[2253] = "Pluie-d\'Étoiles",
[2262] = "Comté-de-Darrow",
[2367] = "Contreforts de Hautebrande d\'antan",
[2369] = "Austrivage",
[2370] = "Donjon de Fort-de-Durn",
[2372] = "Champs de Hautebrande",
[2379] = "Mine de Veine-azur",
[2417] = "Défilé des Rochenoires",
[2537] = "Poste Totem-sinistre",
[2540] = "Ravin des Éboulis",
[2617] = "Camp de Fouillevis",
[2817] = "Reuse Me 4",
[2958] = "Avant-poste de Gîtepierre",
[2961] = "Village Loup-de-givre",
[2964] = "Repaire des Haches-d’hiver",
[2978] = "Donjon Loup-de-givre",
[3038] = "Cratère de Fouignard",
[3177] = "Camp de travail Chanteguerre",
[3277] = "Goulet des Chanteguerres",
[3297] = "Cimetière Loup-de-givre",
[3298] = "Col Loup-de-givre",
[3302] = "Cimetière de Gîtepierre",
[3303] = "Cimetière Foudrepique",
[3305] = "Fortin de Gîtepierre",
[3317] = "Village des Vengebroches",
[3320] = "Scierie des Chanteguerres",
[3417] = "Manoir de Trollemort",
[3424] = "Écuries",
[3426] = "Halte de Forteramure",
[3427] = "Campement de Barbe-de-bronze",
[3430] = "Bois des Chants éternels",
[3431] = "Ile de Haut-soleil",
[3432] = "Sanctuaire de Dath\'Remar",
[3433] = "Les Terres fantômes",
[3434] = "Terrasse du scarabée",
[3435] = "Terrasse du général",
[3436] = "Le réservoir",
[3437] = "La chambre des œufs",
[3438] = "Les rayons",
[3439] = "Terrasse des guetteurs",
[3440] = "Terrasse du scarabée",
[3441] = "Terrasse du général",
[3442] = "Le réservoir",
[3443] = "La chambre des œufs",
[3444] = "Les rayons",
[3445] = "Terrasse des guetteurs",
[3455] = "La mer Boréale",
[3457] = "Karazhan",
[3460] = "Grève dorée",
[3461] = "Mouillage des Voiles du soleil",
[3462] = "Brise-clémente",
[3463] = "Porte du Magistère",
[3464] = "Retraite des Pérégrins",
[3465] = "Sanctum septentrional",
[3466] = "Sanctum occidental",
[3467] = "Sanctum oriental",
[3468] = "Havre de Saltheril",
[3469] = "Écurie de Thuron",
[3470] = "Étang des Murmures-sereins",
[3471] = "Le bois vivant",
[3472] = "Côte de Brise-d\'Azur",
[3473] = "Lac Elrendar",
[3474] = "Le bosquet incendié",
[3475] = "Zeb\'Watha",
[3476] = "Tor\'Watha",
[3477] = "Karazhan *INUTILISÉ*",
[3479] = "La Mer voilée",
[3480] = "Terres de Ternesoir",
[3481] = "Flèche de Ternesoir",
[3482] = "La Malebrèche",
[3483] = "Péninsule des Flammes infernales",
[3484] = "La flèche solaire",
[3485] = "Académie de Falthrien",
[3487] = "Lune-d\'argent",
[3488] = "Tranquillien",
[3489] = "Solcouronne",
[3490] = "Brume-d\'or",
[3491] = "Coursevent",
[3492] = "Flèche de Coursevent",
[3493] = "Sanctum du Soleil",
[3494] = "Sanctum de la Lune",
[3495] = "Flèche d\'Aubétoile",
[3496] = "Enclave des Pérégrins",
[3497] = "An\'daroth",
[3498] = "An\'telas",
[3499] = "An\'owyn",
[3500] = "Mortholme",
[3501] = "Ziggourat sanguinolente",
[3502] = "Ziggourat hurlante",
[3503] = "Ile de Shalandis",
[3504] = "Domaine de Toryl",
[3505] = "Mines de Terradiance",
[3506] = "Domaine d\'Andilien",
[3507] = "Collines de la Cognée",
[3508] = "Passage des Amani",
[3509] = "Pic de Frôle-soleil",
[3510] = "Catacombes des Amani",
[3511] = "Tour des damnés",
[3512] = "Zeb\'Sora",
[3513] = "Lac Elrendar",
[3514] = "La Malebrèche",
[3515] = "L\'Elrendar",
[3516] = "Zeb\'Tela",
[3517] = "Zeb\'Nowa",
[3518] = "Nagrand",
[3519] = "Forêt de Terokkar",
[3520] = "Vallée d\'Ombrelune",
[3521] = "Marécage de Zangar",
[3522] = "Les Tranchantes",
[3523] = "Raz-de-Néant",
[3524] = "Ile de Brume-azur",
[3525] = "Ile de Brume-sang",
[3526] = "Val d\'Ammen",
[3527] = "Point d\'impact",
[3528] = "Lac Rivargent",
[3529] = "Fourré des Nidebois",
[3530] = "Ombrecrête",
[3531] = "Allée de la rôdaille",
[3532] = "Allée du Point-du-jour",
[3533] = "Ruines de Lune-d\'argent",
[3534] = "Voie de Feth",
[3535] = "Citadelle des Flammes infernales",
[3536] = "Thrallmar",
[3537] = "RÉUTILISER",
[3538] = "Bastion de l\'Honneur",
[3539] = "L\'escalier du Destin",
[3540] = "Le Néant distordu",
[3541] = "Camp de forge : Mageddon",
[3542] = "Le sentier de la Gloire",
[3543] = "La Grande fissure",
[3544] = "Plaine des éclats",
[3545] = "Citadelle des Flammes infernales",
[3546] = "Armurerie de l\'expédition",
[3547] = "Trône de Kil\'jaeden",
[3548] = "Camp de forge : Rage",
[3549] = "Site d\'invasion : Annihilateur",
[3550] = "Ruines de Borune",
[3551] = "Ruines de Sha\'naar",
[3552] = "Temple de Telhamat",
[3553] = "Bassins d\'Aggonar",
[3554] = "Guet de l\'épervier",
[3555] = "Poste Mag\'har",
[3556] = "Tanière des Haal\'esh",
[3557] = "L\'Exodar",
[3558] = "Chutes de l\'Elrendar",
[3559] = "Collines des Nidebois",
[3560] = "Champs d\'Ammen",
[3561] = "Le Bosquet sacré",
[3562] = "Remparts des Flammes infernales",
[3563] = "Citadelle des Flammes infernales",
[3564] = "Clairière de braise",
[3565] = "Refuge cénarien",
[3566] = "Tanière Aile-de-lune",
[3567] = "Grappe de capsules",
[3568] = "Débris de capsule",
[3569] = "Creux des marées",
[3570] = "Cap des Irécailles",
[3571] = "Village des Bras-hirsutes",
[3572] = "Repaire des Calmepins",
[3573] = "Point d\'accostage d\'Odesyus",
[3574] = "Amarrage de Valaar",
[3575] = "Rivage envasé",
[3576] = "Guet d\'azur",
[3577] = "Camp de Geezle",
[3578] = "Débris de la ménagerie",
[3579] = "Crique du traître",
[3580] = "Pic Vent-sauvage",
[3581] = "Sentier du Vent-sauvage",
[3582] = "Zeth\'Gor",
[3583] = "La côte de Béryl",
[3584] = "Guet du sang",
[3585] = "Bois des Lames",
[3586] = "La bobine vectorielle",
[3587] = "Le piston de distorsion",
[3588] = "Le cryocœur",
[3589] = "Les confins cramoisis",
[3590] = "Repaire des Irécailles",
[3591] = "Ruines de Loreth\'Aran",
[3592] = "Nazzivian",
[3593] = "Axxarien",
[3594] = "Le rivage des Vase-noire",
[3595] = "Le bassin souillé",
[3596] = "Le récif caché",
[3597] = "Passe d\'Ambretoile",
[3598] = "Île Balafre-du-ver",
[3599] = "Le lieu des serres",
[3600] = "L\'enclave des Bras-hirsutes",
[3601] = "Crête des Rageplumes",
[3602] = "La croisée de Kessel",
[3603] = "Camp de Tel\'athion",
[3604] = "Le récit du sang maudit",
[3605] = "Passé d\'Hyjal",
[3606] = "Sommet d\'Hyjal",
[3607] = "Caverne du sanctuaire du Serpent",
[3608] = "Repos du redresseur de torts",
[3609] = "Inutilisé3",
[3610] = "Ruines de la Lame ardente",
[3611] = "Guet des clans",
[3612] = "Île du sang maudit",
[3613] = "Garadar",
[3614] = "Lac Chanteciel",
[3615] = "Trône des éléments",
[3616] = "Ruines du Crâne ricanant",
[3617] = "Colline des Cogneguerre",
[3618] = "Repaire de Gruul",
[3619] = "Crête d\'Auren",
[3620] = "Chutes d\'Auren",
[3621] = "Lac Berceau-de-l\'Eté",
[3622] = "Poste de Berceau-de-l\'Eté",
[3623] = "Point d\'ancrage Aeris",
[3624] = "Camp de forge : Peur",
[3625] = "Camp de forge : Haine",
[3626] = "Telaar",
[3627] = "Faille de Norsevent",
[3628] = "Halaa",
[3629] = "Faille de Sudevent",
[3630] = "Oshu\'gun",
[3631] = "Champs des esprits",
[3632] = "Shamanar",
[3633] = "Terres ancestrales",
[3634] = "Ventejonc",
[3635] = "Inutilisé2",
[3636] = "Plateau élémentaire",
[3637] = "Forteresse Kil\'sorrau",
[3638] = "L\'arène des épreuves",
[3639] = "Île de Brume-argent",
[3640] = "Tourbedague",
[3641] = "Umbretourbe",
[3642] = "Tourbe-farouche",
[3643] = "Enclave des écailles-sanglantes",
[3644] = "Telredor",
[3645] = "Zabra\'jin",
[3646] = "Crête des boues",
[3647] = "Le vallon des pontes",
[3648] = "La Morte-bourbe",
[3649] = "Sporeggar",
[3650] = "Terres Ango\'rosh",
[3651] = "Bastion Ango\'rosh",
[3652] = "Caverne de Funggor",
[3653] = "Lac des Serpents",
[3654] = "La Vidange",
[3655] = "Lac Umbretourbe",
[3656] = "Lac des furoles",
[3657] = "Clairière du portail",
[3658] = "Lac Ventespore",
[3659] = "Le Lagon",
[3660] = "Défilé des lames",
[3661] = "Canyon de Lamecroc",
[3662] = "Communs",
[3663] = "Manoir abandonné",
[3664] = "Chasseresse du soleil",
[3665] = "Place de l\'épervier",
[3666] = "Bassin halaani",
[3667] = "Tourbière taillée",
[3668] = "Ruines de Boha\'mu",
[3669] = "Le Stade",
[3670] = "Le Surplomb",
[3671] = "Colline brisée",
[3672] = "Procession Mag\'hari",
[3673] = "Safari de Nesingwary",
[3674] = "Fourré cénarien",
[3675] = "Tuurem",
[3676] = "Voile Shienor",
[3677] = "Voile Skith",
[3678] = "Voile Shalas",
[3679] = "Skettis",
[3680] = "Vallée de Noirvent",
[3681] = "Halte Aile-de-feu",
[3682] = "Grangol\'var",
[3683] = "Fort des Brise-pierres",
[3684] = "Bastion allérien",
[3685] = "Ruines Mâche-les-os",
[3686] = "Voile Lithic",
[3687] = "Olembas",
[3688] = "Auchindoun",
[3689] = "Voile Reskk",
[3690] = "Lac Noirvent",
[3691] = "Lac Ere\'Noru",
[3692] = "Lac Jorune",
[3693] = "Monts Skethyl",
[3694] = "Crête brumeuse",
[3695] = "Les Collines brisées",
[3696] = "La Barrière",
[3697] = "Le désert des Ossements",
[3698] = "Arène de Nagrand",
[3699] = "Cour du Crâne ricanant",
[3700] = "L\'arène de sang",
[3701] = "Sol de l\'arène",
[3702] = "Arène des Tranchantes",
[3703] = "Shattrath",
[3704] = "Porte du Berger",
[3705] = "Bassin telaari",
[3706] = "La Porte des ténèbres",
[3707] = "Base de l\'Alliance",
[3708] = "Campement de la Horde",
[3709] = "Village elfe de la nuit",
[3710] = "Nordrassil",
[3711] = "Reuse Me",
[3712] = "Zone 52",
[3713] = "La Fournaise du sang",
[3714] = "Les Salles brisées",
[3715] = "Le Caveau de la vapeur",
[3716] = "La Basse-tourbière",
[3717] = "Les enclos aux esclaves",
[3718] = "Poste du Rat des marais",
[3719] = "Ruines de l\'Orbite sanglante",
[3720] = "Ruines des flèches jumelles",
[3721] = "La Désagrégation",
[3722] = "Manaforge Ara",
[3723] = "Ruines Arklon",
[3724] = "Cosmovrille",
[3725] = "Ruines d\'Enkaat",
[3726] = "Manaforge B\'naar",
[3727] = "La Ferraille",
[3728] = "Les champs du vortex",
[3729] = "Le Monceau",
[3730] = "Manaforge Coruu",
[3731] = "La Faille des tempêtes",
[3732] = "Kirin\'Var",
[3733] = "La Tour pourpre",
[3734] = "Manaforge Duro",
[3735] = "Le plateau Vent-du-Vide",
[3736] = "Manaforge Ultris",
[3737] = "Crête céleste",
[3738] = "La Foudreflèche",
[3739] = "Base de forge : Oubli",
[3740] = "Base de forge : Géhenne",
[3741] = "Ruines de Farahlon",
[3742] = "Siège de Socrethar",
[3743] = "Bastion de la Légion",
[3744] = "Village d\'Ombrelune",
[3745] = "Bastion des Marteaux-hardis",
[3746] = "La main de Gul\'dan",
[3747] = "Les Gangrefosses",
[3748] = "La Forgemort",
[3749] = "Citerne de Glissentaille",
[3750] = "Halte de Glissentaille",
[3751] = "Halte du Feu solaire",
[3752] = "Halte Illidari",
[3753] = "Ruines de Baa\'ri",
[3754] = "Autel de Sha\'tar",
[3755] = "L\'escalier de la Fatalité",
[3756] = "Ruines de Karabor",
[3757] = "Terrasse Ata\'mal",
[3758] = "Champs de l\'Aile-du-Néant",
[3759] = "Escarpement de l\'Aile-du-Néant",
[3760] = "La Barrière",
[3761] = "Le Haut chemin",
[3762] = "Passe de Ventejonc",
[3763] = "Crête de Zangar",
[3764] = "La crête du Crépuscule",
[3765] = "Piste de Tranchépine",
[3766] = "Havre d\'Orebor",
[3767] = "Le défilé des lames",
[3768] = "La crête dentelée",
[3769] = "Bastion des Sire-tonnerre",
[3770] = "Canyon de Lamecroc",
[3771] = "Le Bosquet vivant",
[3772] = "Sylvanaar",
[3773] = "Bastion de Flèchelame",
[3774] = "Repaire de Gruul",
[3775] = "Cercle de sang",
[3776] = "Avant-poste de la Masse-sanglante",
[3777] = "Camp de la Masse-sanglante",
[3778] = "Mine de draenéthyste",
[3779] = "La prétention de Trogma",
[3780] = "Convent de l\'Aile noire",
[3781] = "Grishnath",
[3782] = "Voile Lashh",
[3783] = "Voile Vekh",
[3784] = "Camp de forge : Terreur",
[3785] = "Camp de forge : Courroux",
[3786] = "Ogri\'la",
[3787] = "Camp de forge : Colère",
[3788] = "Le Bas chemin",
[3789] = "Labyrinthe des ombres",
[3790] = "Cryptes Auchenaï",
[3791] = "Les salles des Sethekk",
[3792] = "Tombes-mana",
[3793] = "Ravin de Gangrétincelle",
[3794] = "Vallée des ossements",
[3795] = "Le désert Sha\'naari",
[3796] = "Les champs de distorsion",
[3797] = "Crête Tombeciel",
[3798] = "Gorge Haal\'eshi",
[3799] = "Canyon de la Muraille",
[3800] = "Colline de Roncecroc",
[3801] = "Terres Mag\'har",
[3802] = "Crête du Vide",
[3803] = "La Saillie abyssale",
[3804] = "Le front de la Légion",
[3805] = "Zul\'Aman",
[3806] = "Caravane de ravitaillement",
[3807] = "Le Trépas du saccageur",
[3808] = "Poste cénarien",
[3809] = "Rempart du sud",
[3810] = "Rempart du nord",
[3811] = "Avant-poste de Gor\'gaz",
[3812] = "Poste de Brise-échine",
[3813] = "Le Chemin de l\'angoisse",
[3814] = "Caravane de ravitaillement de l\'est",
[3815] = "Halte de l\'expédition",
[3816] = "L\'épave du zeppelin",
[3817] = "Test",
[3818] = "Terres des écailles-sanglantes",
[3819] = "Enclave des sombrecrêtes",
[3820] = "L\'Œil du cyclone",
[3821] = "La Cage de la gardienne",
[3822] = "Halte de l\'éclipse",
[3823] = "Ile des Tribulations",
[3824] = "Ravin de la Masse-sanglante",
[3825] = "Fin des dragons",
[3826] = "Canyon des Crocs-lames",
[3827] = "Le séjour de Vekhaar",
[3828] = "Sylve Ruuan",
[3829] = "Voile Ruuan",
[3830] = "Bois aux corbeaux",
[3831] = "Porte de la mort",
[3832] = "Cime du vortex",
[3833] = "Tranchecrête",
[3834] = "Crête de la folie",
[3835] = "Ravin de Plumepoussière",
[3836] = "Le repaire de Magtheridon",
[3837] = "Bastion des Solfurie",
[3838] = "Montagnes Brise-échine",
[3839] = "Armurerie abandonnée",
[3840] = "Le Temple noir",
[3841] = "Rivage des Sombrecrêtes",
[3842] = "Donjon de la Tempête",
[3844] = "Mok\'Nathal",
[3845] = "Donjon de la Tempête",
[3846] = "L\'Arcatraz",
[3847] = "La Botanica",
[3848] = "L\'Arcatraz",
[3849] = "Le Méchanar",
[3850] = "Pierre-de-Néant",
[3851] = "Comptoir des Terres-médianes",
[3852] = "Point d\'ancrage de Tuluman",
[3854] = "Poste de garde du Protectorat",
[3855] = "Arène du Cercle de sang",
[3856] = "Passage de l\'Elrendar",
[3857] = "Gué d\'Ammen",
[3858] = "Saillie de Tranchépine",
[3859] = "Lac Silmyr",
[3860] = "Clairière de Raastok",
[3861] = "Passe thalassienne",
[3862] = "Goulet bouillonnant",
[3863] = "Landes brisées",
[3864] = "Point d\'ancrage de Bash\'ir",
[3865] = "Éperon de cristal",
[3866] = "Skald",
[3867] = "Goulet des Lames",
[3868] = "Pont de gyro-passerelles",
[3869] = "Tour des mages",
[3870] = "Tour des elfes de sang",
[3871] = "Ruines draeneï",
[3872] = "Ruines des saccageurs gangrenés",
[3873] = "Le Terrain d\'essai",
[3874] = "Écodôme Champlointain",
[3875] = "Écodôme Percheciel",
[3876] = "Écodôme Sudron",
[3877] = "Écodôme Terres-médianes",
[3878] = "Lieu de rassemblement de l\'Ethereum",
[3879] = "Cour de la chapelle",
[3880] = "Puits d\'accès Zéon",
[3881] = "Mine de Trelleum",
[3882] = "Site d\'invasion : Destructeur",
[3883] = "Camp de Boum",
[3884] = "Passage des Brise-échine",
[3885] = "Crête de Toile-néant",
[3886] = "Caravane abandonnée",
[3887] = "Caravane de réfugiés",
[3888] = "Tombe des ombres",
[3889] = "Voile Rhaze",
[3890] = "Tombeau des lumières",
[3891] = "Colline des charognes",
[3892] = "Monticule grouillant",
[3893] = "Cercle d\'observance",
[3894] = "Terres Auchenaï",
[3895] = "Poste de garde cénarien",
[3896] = "Éminence de l\'Aldor",
[3897] = "Terrasse de la Lumière",
[3898] = "Degré des Clairvoyants",
[3899] = "Ville basse",
[3900] = "Site d\'invasion : Suzerain",
[3901] = "Poste allérien",
[3902] = "Camp des Brise-pierres",
[3903] = "Roche\'mok",
[3904] = "Creux maudit",
[3905] = "Réservoir de Glissecroc",
[3906] = "Le Reflux sanglant",
[3907] = "Cap viridien",
[3908] = "Ordeval",
[3909] = "Le Repli perdu",
[3910] = "Bois brumeux",
[3911] = "Rivage paisible",
[3912] = "Passe du Rameau d\'or",
[3913] = "Pierre runique Falithas",
[3914] = "Pierre runique Shan\'dor",
[3915] = "Rivage de Pontgallant",
[3916] = "Bois frôle-lune",
[3917] = "Auchindoun",
[3918] = "Poste de Toshley",
[3919] = "Crête chantante",
[3920] = "Halte du Fracas",
[3921] = "Crête d\'Arklonis",
[3922] = "Avant-poste Flèchelame",
[3923] = "Repaire de Gruul",
[3924] = "Tour Nord-sanglante",
[3925] = "Tour Sud-sanglante",
[3926] = "Les plaines brisées",
[3927] = "Ferme d\'Oronok",
[3928] = "L\'Autel de la damnation",
[3929] = "La voie de la Conquête",
[3930] = "Champs éclipsions",
[3931] = "Terres de la Flèchelame",
[3932] = "Campement Sketh\'lon",
[3933] = "Débris sketh\'lon",
[3934] = "Place centrale",
[3935] = "Allée des sorciers",
[3936] = "Tour de la Forgemort",
[3937] = "Guet des scories",
[3938] = "Sanctum des Étoiles",
[3939] = "Forteresse Gueule-de-dragon",
[3940] = "Le Bassin fétide",
[3941] = "Test",
[3942] = "Point d\'ancrage de Razaan",
[3943] = "Site d\'invasion : Cataclysme",
[3944] = "L\'autel des Ombres",
[3945] = "Défilé de l\'Aile-du-Néant",
[3946] = "Refuge de Wayne",
[3947] = "Les bassins Brûlants",
[3948] = "Test de Brian et Pat",
[3949] = "Champs de magma",
[3950] = "Guet cramoisi",
[3951] = "Bosquet éternel",
[3952] = "Pont Crâne-du-ver",
[3953] = "Saillie ailécaille",
[3954] = "Tunnel Crâne-du-ver",
[3955] = "Bassin des Flammes infernales",
[3956] = "L\'escalier de l\'Ombre",
[3957] = "Avant-poste sha\'tari",
[3958] = "Camp de base sha\'tari",
[3959] = "Temple noir",
[3960] = "Le refuge du Broyeur-d\'âme",
[3961] = "Halte Aile-du-chargrin",
[3962] = "Le cercle de Vim\'gol",
[3963] = "Crête d\'Epine-de-dragon",
[3964] = "Avant-poste de la Garde-ciel",
[3965] = "Mines de l\'Aile-du-Néant",
[3966] = "Campement des Gueules-de-dragon",
[3967] = "Couloir aérien des Gueules-de-dragon",
[3968] = "Ruines de Lordaeron",
[3969] = "Perchoir de Clivenuit",
[3970] = "Perchoir d\'Obsidia",
[3971] = "Perchoir d\'Insidion",
[3972] = "Perchoir d\'Aile-furie",
[3973] = "Le Raie\'odrome de Noirvent",
[3974] = "Voile Harr\'ik",
[3975] = "Repos de Terokk",
[3976] = "Voile Ala\'rak",
[3977] = "Voile Shil\'ak supérieur",
[3978] = "Voile Shil\'ak inférieur",
[4008] = "Transporteur de Shartuul",
[4009] = "Terrain d\'entraînement Illidari",
[4010] = "Bourbe-à-brac",
[4046] = "Poste de Navrecorne",
[4047] = "Point d\'accostage de Nat",
[4049] = "Ferme de Tabetha",
[4067] = "Tour de Pestebois",
[4075] = "Plateau du Puits de soleil",
[4076] = "Reuse Me 7",
[4078] = "Éminence de Tranchépine",
[4080] = "Île de Quel\'Danas",
[4081] = "Le Chasselaube",
[4082] = "Le Sin\'loren",
[4083] = "La Fierté de Lune-d\'argent",
[4084] = "Le Serment de sang",
[4085] = "Zone de rassemblement du Soleil brisé",
[4086] = "Sanctum des Confins du soleil",
[4087] = "Port des Confins du soleil",
[4088] = "Armurerie des Confins du soleil",
[4089] = "Étoile-de-l\'aube",
[4090] = "Place du Point-du-jour",
[4091] = "Côte de Verte-branchie",
[4092] = "La Malebrèche",
[4093] = "La forge du Soleil",
[4094] = "Plateau du Puits de soleil",
[4095] = "Terrasse des Magistères",
[4131] = "Terrasse des Magistères",
[4139] = "Place Parhélion",
[4140] = "La Malebrèche",
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.