repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
imashkan/ABCYAGOP | plugins/btc.lua | 289 | 1375 | -- See https://bitcoinaverage.com/api
local function getBTCX(amount,currency)
local base_url = 'https://api.bitcoinaverage.com/ticker/global/'
-- Do request on bitcoinaverage, the final / is critical!
local res,code = https.request(base_url..currency.."/")
if code ~= 200 then return nil end
local data = json:decode(res)
-- Easy, it's right there
text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid
-- If we have a number as second parameter, calculate the bitcoin amount
if amount~=nil then
btc = tonumber(amount) / tonumber(data.ask)
text = text.."\n "..currency .." "..amount.." = BTC "..btc
end
return text
end
local function run(msg, matches)
local cur = 'EUR'
local amt = nil
-- Get the global match out of the way
if matches[1] == "!btc" then
return getBTCX(amt,cur)
end
if matches[2] ~= nil then
-- There is a second match
amt = matches[2]
cur = string.upper(matches[1])
else
-- Just a EUR or USD param
cur = string.upper(matches[1])
end
return getBTCX(amt,cur)
end
return {
description = "Bitcoin global average market value (in EUR or USD)",
usage = "!btc [EUR|USD] [amount]",
patterns = {
"^!btc$",
"^!btc ([Ee][Uu][Rr])$",
"^!btc ([Uu][Ss][Dd])$",
"^!btc (EUR) (%d+[%d%.]*)$",
"^!btc (USD) (%d+[%d%.]*)$"
},
run = run
}
| gpl-2.0 |
anoidgit/Preference-Selection-with-Neural-Network | utils/Logger.lua | 2 | 3281 | --[[ Logger is a class used for maintaining logs in a log file.
--]]
local Logger = torch.class('Logger')
--[[ Construct a Logger object.
Parameters:
* `logFile` - Outputs logs to a file under this path instead of stdout. ['']
* `disableLogs` - If = true, output nothing. [false]
* `logLevel` - Outputs logs at this level and above. Possible options are: DEBUG, INFO, WARNING and ERROR. ['INFO']
]]
function Logger:__init(logFile, disableLogs, logLevel, openMode)
logFile = logFile or ''
disableLogs = disableLogs or false
logLevel = logLevel or 'INFO'
if disableLogs then
self:setVisibleLevel('ERROR')
else
self:setVisibleLevel(logLevel)
end
openMode = openMode or 'a'
if string.len(logFile) > 0 then
self.logFile = io.open(logFile, openMode)
else
self.logFile = nil
end
self.LEVELS = { DEBUG = 0, INFO = 1, WARNING = 2, ERROR = 3 }
self.level = self.level or 'INFO'
end
--[[ Log a message at a specified level.
Parameters:
* `message` - the message to log.
* `level` - the desired message level. ['INFO']
]]
function Logger:log(message, level)
level = level or 'INFO'
local timeStamp = os.date('%x %X')
local msgFormatted = string.format('[%s %s] %s', timeStamp, level, message)
if self:_isVisible(level) then
print (msgFormatted)
end
if self.logFile and self:_isVisible(level) then
self.logFile:write(msgFormatted .. '\n')
self.logFile:flush()
end
end
--[[ Log a message at 'INFO' level.
Parameters:
* `message` - the message to log. Supports formatting string.
]]
function Logger:info(...)
self:log(self:_format(...), 'INFO')
end
--[[ Log a message at 'WARNING' level.
Parameters:
* `message` - the message to log. Supports formatting string.
]]
function Logger:warning(...)
self:log(self:_format(...), 'WARNING')
end
--[[ Log a message at 'ERROR' level.
Parameters:
* `message` - the message to log. Supports formatting string.
]]
function Logger:error(...)
self:log(self:_format(...), 'ERROR')
end
--[[ Log a message at 'DEBUG' level.
Parameters:
* `message` - the message to log. Supports formatting string.
]]
function Logger:debug(...)
self:log(self:_format(...), 'DEBUG')
end
--[[ Log a message as exactly it is.
Parameters:
* `message` - the message to log. Supports formatting string.
]]
function Logger:writeMsg(...)
local msg = self:_format(...)
if self:_isVisible('WARNING') then
io.write(msg)
end
if self.logFile and self:_isVisible('WARNING') then
self.logFile:write(msg)
self.logFile:flush()
end
end
--[[ Set the visible message level. Lower level messages will be muted.
Parameters:
* `level` - 'DEBUG', 'INFO', 'WARNING' or 'ERROR'.
]]
function Logger:setVisibleLevel(level)
assert (level == 'DEBUG' or level == 'INFO' or
level == 'WARNING' or level == 'ERROR')
self.level = level
end
-- Private function for comparing level against visible level.
-- `level` - 'DEBUG', 'INFO', 'WARNING' or 'ERROR'.
function Logger:_isVisible(level)
self.level = self.level or 'INFO'
return self.LEVELS[level] >= self.LEVELS[self.level]
end
function Logger:_format(...)
if #table.pack(...) == 1 then
return ...
else
return string.format(...)
end
end
--[[ Deconstructor. Close the log file.
]]
function Logger:shutDown()
if self.logFile then
self.logFile:close()
end
end
| gpl-3.0 |
AndyBursh/Factorio-Stdlib | spec/area/position_spec.lua | 1 | 4703 | require 'spec/defines'
require 'stdlib/area/position'
describe('Position Spec', function()
it('should validate position construction', function()
assert.same({x = -4, y = 21}, Position.construct(-4, 21))
end)
it('should validate position copies', function()
local pos = { x = -4, y = 5 }
local copy = Position.copy(pos)
assert.same(pos, copy)
-- Verify that the copy does not match the original, after the original is modified
pos.y = 10
assert.is_not.same(pos, copy)
end)
it('should validate position offsets', function()
local pos = {1, -4}
assert.same({x = 5, y = 5}, Position.offset(pos, 4, 9))
assert.same({x = 1, y = -4}, Position.offset(pos, 0, 0))
assert.same({x = 0, y = 0}, Position.offset(pos, -1, 4))
end)
it('should validate position addition', function()
local pos1 = {1, -4}
local pos2 = {x = -5, y = 25}
assert.same({x = -4, y = 21}, Position.add(pos1, pos2))
end)
it('should validate position subtraction', function()
local pos1 = {1, -4}
local pos2 = {x = -5, y = 25}
assert.same({x = 6, y = -29}, Position.subtract(pos1, pos2))
end)
it('should validate position translation', function()
local pos = {1, -4}
assert.same({x = 1, y = -5}, Position.translate(pos, defines.direction.north, 1))
assert.same({x = 1, y = -6}, Position.translate(pos, defines.direction.south, -2))
assert.same({x = 2, y = -4}, Position.translate(pos, defines.direction.east, 1))
assert.same({x = -2, y = -4}, Position.translate(pos, defines.direction.west, 3))
assert.same({x = 2, y = -3}, Position.translate(pos, defines.direction.southeast, 1))
assert.same({x = 0, y = -3}, Position.translate(pos, defines.direction.southwest, 1))
assert.same({x = 2, y = -5}, Position.translate(pos, defines.direction.northeast, 1))
assert.same({x = 0, y = -5}, Position.translate(pos, defines.direction.northwest, 1))
end)
it('should validate position area expansion', function()
local pos = { x = 1, y = -4}
assert.same(pos, Position.expand_to_area(pos, 0).left_top)
assert.same(pos, Position.expand_to_area(pos, 0).right_bottom)
local expanded_area = {left_top = { x = -1, y = -6}, right_bottom = { x = 3, y = -2 }}
assert.same(expanded_area, Position.expand_to_area(pos, 2))
end)
it('should validate position to_table conversion', function()
local pos = {1, -4}
assert.same({x = 1, y = -4}, Position.to_table(pos, 0, 0))
assert.has_error(function() Position.to_table() end)
end)
it('should validate the distance squared between two positions', function()
local pos_a = {1, -4}
local pos_b = {3, -2}
assert.same(8, Position.distance_squared(pos_a, pos_b))
assert.same(8, Position.distance_squared(pos_b, pos_a))
end)
it('should validate the distance between two positions', function()
local pos_a = {5, -5}
local pos_b = {10, 0}
assert.same(math.sqrt(50), Position.distance(pos_a, pos_b))
assert.same(math.sqrt(50), Position.distance(pos_b, pos_a))
end)
it('should validate the manhatten distance between two positions', function()
local pos_a = {5, -5}
local pos_b = {10, 0}
assert.same(10, Position.manhattan_distance(pos_a, pos_b))
assert.same(10, Position.manhattan_distance(pos_b, pos_a))
local pos_a = {1, -4}
local pos_b = {3, -2}
assert.same(4, Position.manhattan_distance(pos_a, pos_b))
assert.same(4, Position.manhattan_distance(pos_b, pos_a))
end)
it('should validate position strings', function()
local pos = {1, -4}
assert.same("Position {x = 1, y = -4}", Position.tostring(pos))
assert.has_error(function() Position.tostring() end)
end)
it('compares shallow equality in positions', function()
local pos1 = {1, -4}
local pos2 = pos1
assert.is_true(Position.equals(pos1, pos2))
assert.is_false(Position.equals(pos1, nil))
assert.is_false(Position.equals(nil, pos2))
assert.is_false(Position.equals(nil, nil))
end)
it('compares positions', function()
local pos1 = {1, -4}
local pos2 = { x = 3, y = -2}
local pos3 = {-1, -4}
local pos4 = { x = 1, y = -4}
assert.is_true(Position.equals(pos1, pos1))
assert.is_false(Position.equals(pos1, pos2))
assert.is_false(Position.equals(pos1, pos3))
assert.is_true(Position.equals(pos1, pos4))
end)
end)
| isc |
Anarchid/Zero-K | LuaUI/Fonts/FreeSansBold_14.lua | 25 | 33857 | -- $Id: FreeSansBold_14.lua 3171 2008-11-06 09:06:29Z det $
local fontSpecs = {
srcFile = [[FreeSansBold.ttf]],
family = [[FreeSans]],
style = [[Bold]],
yStep = 15,
height = 14,
xTexSize = 512,
yTexSize = 256,
outlineRadius = 2,
outlineWeight = 100,
}
local glyphs = {}
glyphs[32] = { --' '--
num = 32,
adv = 4,
oxn = -2, oyn = -3, oxp = 3, oyp = 2,
txn = 1, tyn = 1, txp = 6, typ = 6,
}
glyphs[33] = { --'!'--
num = 33,
adv = 5,
oxn = -1, oyn = -2, oxp = 6, oyp = 13,
txn = 21, tyn = 1, txp = 28, typ = 16,
}
glyphs[34] = { --'"'--
num = 34,
adv = 7,
oxn = -2, oyn = 4, oxp = 8, oyp = 13,
txn = 41, tyn = 1, txp = 51, typ = 10,
}
glyphs[35] = { --'#'--
num = 35,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 12,
txn = 61, tyn = 1, txp = 73, typ = 16,
}
glyphs[36] = { --'$'--
num = 36,
adv = 8,
oxn = -2, oyn = -4, oxp = 10, oyp = 13,
txn = 81, tyn = 1, txp = 93, typ = 18,
}
glyphs[37] = { --'%'--
num = 37,
adv = 12,
oxn = -2, oyn = -3, oxp = 15, oyp = 12,
txn = 101, tyn = 1, txp = 118, typ = 16,
}
glyphs[38] = { --'&'--
num = 38,
adv = 10,
oxn = -2, oyn = -3, oxp = 12, oyp = 13,
txn = 121, tyn = 1, txp = 135, typ = 17,
}
glyphs[39] = { --'''--
num = 39,
adv = 3,
oxn = -2, oyn = 4, oxp = 5, oyp = 13,
txn = 141, tyn = 1, txp = 148, typ = 10,
}
glyphs[40] = { --'('--
num = 40,
adv = 5,
oxn = -2, oyn = -5, oxp = 7, oyp = 13,
txn = 161, tyn = 1, txp = 170, typ = 19,
}
glyphs[41] = { --')'--
num = 41,
adv = 5,
oxn = -2, oyn = -5, oxp = 6, oyp = 13,
txn = 181, tyn = 1, txp = 189, typ = 19,
}
glyphs[42] = { --'*'--
num = 42,
adv = 5,
oxn = -2, oyn = 3, oxp = 7, oyp = 13,
txn = 201, tyn = 1, txp = 210, typ = 11,
}
glyphs[43] = { --'+'--
num = 43,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 9,
txn = 221, tyn = 1, txp = 233, typ = 13,
}
glyphs[44] = { --','--
num = 44,
adv = 4,
oxn = -2, oyn = -5, oxp = 5, oyp = 5,
txn = 241, tyn = 1, txp = 248, typ = 11,
}
glyphs[45] = { --'-'--
num = 45,
adv = 5,
oxn = -2, oyn = 0, oxp = 7, oyp = 7,
txn = 261, tyn = 1, txp = 270, typ = 8,
}
glyphs[46] = { --'.'--
num = 46,
adv = 4,
oxn = -2, oyn = -2, oxp = 5, oyp = 5,
txn = 281, tyn = 1, txp = 288, typ = 8,
}
glyphs[47] = { --'/'--
num = 47,
adv = 4,
oxn = -2, oyn = -3, oxp = 6, oyp = 12,
txn = 301, tyn = 1, txp = 309, typ = 16,
}
glyphs[48] = { --'0'--
num = 48,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 321, tyn = 1, txp = 333, typ = 17,
}
glyphs[49] = { --'1'--
num = 49,
adv = 8,
oxn = -2, oyn = -2, oxp = 8, oyp = 12,
txn = 341, tyn = 1, txp = 351, typ = 15,
}
glyphs[50] = { --'2'--
num = 50,
adv = 8,
oxn = -2, oyn = -2, oxp = 10, oyp = 13,
txn = 361, tyn = 1, txp = 373, typ = 16,
}
glyphs[51] = { --'3'--
num = 51,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 381, tyn = 1, txp = 393, typ = 17,
}
glyphs[52] = { --'4'--
num = 52,
adv = 8,
oxn = -2, oyn = -2, oxp = 10, oyp = 12,
txn = 401, tyn = 1, txp = 413, typ = 15,
}
glyphs[53] = { --'5'--
num = 53,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 12,
txn = 421, tyn = 1, txp = 433, typ = 16,
}
glyphs[54] = { --'6'--
num = 54,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 441, tyn = 1, txp = 453, typ = 17,
}
glyphs[55] = { --'7'--
num = 55,
adv = 8,
oxn = -2, oyn = -2, oxp = 10, oyp = 12,
txn = 461, tyn = 1, txp = 473, typ = 15,
}
glyphs[56] = { --'8'--
num = 56,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 481, tyn = 1, txp = 493, typ = 17,
}
glyphs[57] = { --'9'--
num = 57,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 1, tyn = 22, txp = 13, typ = 38,
}
glyphs[58] = { --':'--
num = 58,
adv = 5,
oxn = -1, oyn = -2, oxp = 6, oyp = 10,
txn = 21, tyn = 22, txp = 28, typ = 34,
}
glyphs[59] = { --';'--
num = 59,
adv = 5,
oxn = -1, oyn = -5, oxp = 6, oyp = 10,
txn = 41, tyn = 22, txp = 48, typ = 37,
}
glyphs[60] = { --'<'--
num = 60,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 9,
txn = 61, tyn = 22, txp = 73, typ = 34,
}
glyphs[61] = { --'='--
num = 61,
adv = 8,
oxn = -2, oyn = -2, oxp = 10, oyp = 8,
txn = 81, tyn = 22, txp = 93, typ = 32,
}
glyphs[62] = { --'>'--
num = 62,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 9,
txn = 101, tyn = 22, txp = 113, typ = 34,
}
glyphs[63] = { --'?'--
num = 63,
adv = 9,
oxn = -2, oyn = -2, oxp = 10, oyp = 13,
txn = 121, tyn = 22, txp = 133, typ = 37,
}
glyphs[64] = { --'@'--
num = 64,
adv = 14,
oxn = -2, oyn = -4, oxp = 16, oyp = 13,
txn = 141, tyn = 22, txp = 159, typ = 39,
}
glyphs[65] = { --'A'--
num = 65,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 13,
txn = 161, tyn = 22, txp = 175, typ = 37,
}
glyphs[66] = { --'B'--
num = 66,
adv = 10,
oxn = -1, oyn = -2, oxp = 12, oyp = 13,
txn = 181, tyn = 22, txp = 194, typ = 37,
}
glyphs[67] = { --'C'--
num = 67,
adv = 10,
oxn = -2, oyn = -3, oxp = 12, oyp = 13,
txn = 201, tyn = 22, txp = 215, typ = 38,
}
glyphs[68] = { --'D'--
num = 68,
adv = 10,
oxn = -1, oyn = -2, oxp = 12, oyp = 13,
txn = 221, tyn = 22, txp = 234, typ = 37,
}
glyphs[69] = { --'E'--
num = 69,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 13,
txn = 241, tyn = 22, txp = 253, typ = 37,
}
glyphs[70] = { --'F'--
num = 70,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 13,
txn = 261, tyn = 22, txp = 273, typ = 37,
}
glyphs[71] = { --'G'--
num = 71,
adv = 11,
oxn = -2, oyn = -3, oxp = 12, oyp = 13,
txn = 281, tyn = 22, txp = 295, typ = 38,
}
glyphs[72] = { --'H'--
num = 72,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 13,
txn = 301, tyn = 22, txp = 315, typ = 37,
}
glyphs[73] = { --'I'--
num = 73,
adv = 4,
oxn = -2, oyn = -2, oxp = 5, oyp = 13,
txn = 321, tyn = 22, txp = 328, typ = 37,
}
glyphs[74] = { --'J'--
num = 74,
adv = 8,
oxn = -2, oyn = -3, oxp = 9, oyp = 13,
txn = 341, tyn = 22, txp = 352, typ = 38,
}
glyphs[75] = { --'K'--
num = 75,
adv = 10,
oxn = -1, oyn = -2, oxp = 13, oyp = 13,
txn = 361, tyn = 22, txp = 375, typ = 37,
}
glyphs[76] = { --'L'--
num = 76,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 13,
txn = 381, tyn = 22, txp = 393, typ = 37,
}
glyphs[77] = { --'M'--
num = 77,
adv = 12,
oxn = -2, oyn = -2, oxp = 13, oyp = 13,
txn = 401, tyn = 22, txp = 416, typ = 37,
}
glyphs[78] = { --'N'--
num = 78,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 13,
txn = 421, tyn = 22, txp = 435, typ = 37,
}
glyphs[79] = { --'O'--
num = 79,
adv = 11,
oxn = -2, oyn = -3, oxp = 13, oyp = 13,
txn = 441, tyn = 22, txp = 456, typ = 38,
}
glyphs[80] = { --'P'--
num = 80,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 13,
txn = 461, tyn = 22, txp = 473, typ = 37,
}
glyphs[81] = { --'Q'--
num = 81,
adv = 11,
oxn = -2, oyn = -3, oxp = 13, oyp = 13,
txn = 481, tyn = 22, txp = 496, typ = 38,
}
glyphs[82] = { --'R'--
num = 82,
adv = 10,
oxn = -1, oyn = -2, oxp = 12, oyp = 13,
txn = 1, tyn = 43, txp = 14, typ = 58,
}
glyphs[83] = { --'S'--
num = 83,
adv = 9,
oxn = -2, oyn = -3, oxp = 11, oyp = 13,
txn = 21, tyn = 43, txp = 34, typ = 59,
}
glyphs[84] = { --'T'--
num = 84,
adv = 9,
oxn = -2, oyn = -2, oxp = 11, oyp = 13,
txn = 41, tyn = 43, txp = 54, typ = 58,
}
glyphs[85] = { --'U'--
num = 85,
adv = 10,
oxn = -1, oyn = -3, oxp = 12, oyp = 13,
txn = 61, tyn = 43, txp = 74, typ = 59,
}
glyphs[86] = { --'V'--
num = 86,
adv = 9,
oxn = -2, oyn = -2, oxp = 12, oyp = 13,
txn = 81, tyn = 43, txp = 95, typ = 58,
}
glyphs[87] = { --'W'--
num = 87,
adv = 13,
oxn = -2, oyn = -2, oxp = 16, oyp = 13,
txn = 101, tyn = 43, txp = 119, typ = 58,
}
glyphs[88] = { --'X'--
num = 88,
adv = 9,
oxn = -2, oyn = -2, oxp = 12, oyp = 13,
txn = 121, tyn = 43, txp = 135, typ = 58,
}
glyphs[89] = { --'Y'--
num = 89,
adv = 9,
oxn = -2, oyn = -2, oxp = 12, oyp = 13,
txn = 141, tyn = 43, txp = 155, typ = 58,
}
glyphs[90] = { --'Z'--
num = 90,
adv = 9,
oxn = -2, oyn = -2, oxp = 11, oyp = 13,
txn = 161, tyn = 43, txp = 174, typ = 58,
}
glyphs[91] = { --'['--
num = 91,
adv = 5,
oxn = -2, oyn = -5, oxp = 7, oyp = 13,
txn = 181, tyn = 43, txp = 190, typ = 61,
}
glyphs[92] = { --'\'--
num = 92,
adv = 4,
oxn = -3, oyn = -3, oxp = 7, oyp = 12,
txn = 201, tyn = 43, txp = 211, typ = 58,
}
glyphs[93] = { --']'--
num = 93,
adv = 5,
oxn = -2, oyn = -5, oxp = 6, oyp = 13,
txn = 221, tyn = 43, txp = 229, typ = 61,
}
glyphs[94] = { --'^'--
num = 94,
adv = 8,
oxn = -2, oyn = 1, oxp = 10, oyp = 12,
txn = 241, tyn = 43, txp = 253, typ = 54,
}
glyphs[95] = { --'_'--
num = 95,
adv = 8,
oxn = -3, oyn = -5, oxp = 11, oyp = 1,
txn = 261, tyn = 43, txp = 275, typ = 49,
}
glyphs[96] = { --'`'--
num = 96,
adv = 5,
oxn = -2, oyn = 6, oxp = 5, oyp = 13,
txn = 281, tyn = 43, txp = 288, typ = 50,
}
glyphs[97] = { --'a'--
num = 97,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 10,
txn = 301, tyn = 43, txp = 313, typ = 56,
}
glyphs[98] = { --'b'--
num = 98,
adv = 9,
oxn = -2, oyn = -3, oxp = 11, oyp = 13,
txn = 321, tyn = 43, txp = 334, typ = 59,
}
glyphs[99] = { --'c'--
num = 99,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 10,
txn = 341, tyn = 43, txp = 353, typ = 56,
}
glyphs[100] = { --'d'--
num = 100,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 361, tyn = 43, txp = 373, typ = 59,
}
glyphs[101] = { --'e'--
num = 101,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 10,
txn = 381, tyn = 43, txp = 393, typ = 56,
}
glyphs[102] = { --'f'--
num = 102,
adv = 5,
oxn = -2, oyn = -2, oxp = 7, oyp = 13,
txn = 401, tyn = 43, txp = 410, typ = 58,
}
glyphs[103] = { --'g'--
num = 103,
adv = 9,
oxn = -2, oyn = -6, oxp = 10, oyp = 10,
txn = 421, tyn = 43, txp = 433, typ = 59,
}
glyphs[104] = { --'h'--
num = 104,
adv = 9,
oxn = -2, oyn = -2, oxp = 10, oyp = 13,
txn = 441, tyn = 43, txp = 453, typ = 58,
}
glyphs[105] = { --'i'--
num = 105,
adv = 4,
oxn = -2, oyn = -2, oxp = 5, oyp = 13,
txn = 461, tyn = 43, txp = 468, typ = 58,
}
glyphs[106] = { --'j'--
num = 106,
adv = 4,
oxn = -2, oyn = -6, oxp = 5, oyp = 13,
txn = 481, tyn = 43, txp = 488, typ = 62,
}
glyphs[107] = { --'k'--
num = 107,
adv = 8,
oxn = -2, oyn = -2, oxp = 10, oyp = 13,
txn = 1, tyn = 64, txp = 13, typ = 79,
}
glyphs[108] = { --'l'--
num = 108,
adv = 4,
oxn = -2, oyn = -2, oxp = 5, oyp = 13,
txn = 21, tyn = 64, txp = 28, typ = 79,
}
glyphs[109] = { --'m'--
num = 109,
adv = 12,
oxn = -2, oyn = -2, oxp = 14, oyp = 10,
txn = 41, tyn = 64, txp = 57, typ = 76,
}
glyphs[110] = { --'n'--
num = 110,
adv = 9,
oxn = -2, oyn = -2, oxp = 10, oyp = 10,
txn = 61, tyn = 64, txp = 73, typ = 76,
}
glyphs[111] = { --'o'--
num = 111,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 10,
txn = 81, tyn = 64, txp = 93, typ = 77,
}
glyphs[112] = { --'p'--
num = 112,
adv = 9,
oxn = -2, oyn = -6, oxp = 11, oyp = 10,
txn = 101, tyn = 64, txp = 114, typ = 80,
}
glyphs[113] = { --'q'--
num = 113,
adv = 9,
oxn = -2, oyn = -6, oxp = 10, oyp = 10,
txn = 121, tyn = 64, txp = 133, typ = 80,
}
glyphs[114] = { --'r'--
num = 114,
adv = 5,
oxn = -2, oyn = -2, oxp = 8, oyp = 10,
txn = 141, tyn = 64, txp = 151, typ = 76,
}
glyphs[115] = { --'s'--
num = 115,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 10,
txn = 161, tyn = 64, txp = 173, typ = 77,
}
glyphs[116] = { --'t'--
num = 116,
adv = 5,
oxn = -2, oyn = -3, oxp = 7, oyp = 12,
txn = 181, tyn = 64, txp = 190, typ = 79,
}
glyphs[117] = { --'u'--
num = 117,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 10,
txn = 201, tyn = 64, txp = 213, typ = 77,
}
glyphs[118] = { --'v'--
num = 118,
adv = 8,
oxn = -2, oyn = -2, oxp = 10, oyp = 10,
txn = 221, tyn = 64, txp = 233, typ = 76,
}
glyphs[119] = { --'w'--
num = 119,
adv = 11,
oxn = -2, oyn = -2, oxp = 13, oyp = 10,
txn = 241, tyn = 64, txp = 256, typ = 76,
}
glyphs[120] = { --'x'--
num = 120,
adv = 8,
oxn = -2, oyn = -2, oxp = 10, oyp = 10,
txn = 261, tyn = 64, txp = 273, typ = 76,
}
glyphs[121] = { --'y'--
num = 121,
adv = 8,
oxn = -2, oyn = -6, oxp = 10, oyp = 10,
txn = 281, tyn = 64, txp = 293, typ = 80,
}
glyphs[122] = { --'z'--
num = 122,
adv = 7,
oxn = -2, oyn = -2, oxp = 9, oyp = 10,
txn = 301, tyn = 64, txp = 312, typ = 76,
}
glyphs[123] = { --'{'--
num = 123,
adv = 5,
oxn = -2, oyn = -5, oxp = 7, oyp = 13,
txn = 321, tyn = 64, txp = 330, typ = 82,
}
glyphs[124] = { --'|'--
num = 124,
adv = 4,
oxn = -1, oyn = -5, oxp = 5, oyp = 13,
txn = 341, tyn = 64, txp = 347, typ = 82,
}
glyphs[125] = { --'}'--
num = 125,
adv = 5,
oxn = -1, oyn = -5, oxp = 7, oyp = 13,
txn = 361, tyn = 64, txp = 369, typ = 82,
}
glyphs[126] = { --'~'--
num = 126,
adv = 8,
oxn = -2, oyn = -1, oxp = 10, oyp = 7,
txn = 381, tyn = 64, txp = 393, typ = 72,
}
glyphs[127] = { --''--
num = 127,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 401, tyn = 64, txp = 410, typ = 78,
}
glyphs[128] = { --''--
num = 128,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 421, tyn = 64, txp = 430, typ = 78,
}
glyphs[129] = { --'?'--
num = 129,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 441, tyn = 64, txp = 450, typ = 78,
}
glyphs[130] = { --''--
num = 130,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 461, tyn = 64, txp = 470, typ = 78,
}
glyphs[131] = { --''--
num = 131,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 481, tyn = 64, txp = 490, typ = 78,
}
glyphs[132] = { --''--
num = 132,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 1, tyn = 85, txp = 10, typ = 99,
}
glyphs[133] = { --'
'--
num = 133,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 21, tyn = 85, txp = 30, typ = 99,
}
glyphs[134] = { --''--
num = 134,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 41, tyn = 85, txp = 50, typ = 99,
}
glyphs[135] = { --''--
num = 135,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 61, tyn = 85, txp = 70, typ = 99,
}
glyphs[136] = { --''--
num = 136,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 81, tyn = 85, txp = 90, typ = 99,
}
glyphs[137] = { --''--
num = 137,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 101, tyn = 85, txp = 110, typ = 99,
}
glyphs[138] = { --''--
num = 138,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 121, tyn = 85, txp = 130, typ = 99,
}
glyphs[139] = { --''--
num = 139,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 141, tyn = 85, txp = 150, typ = 99,
}
glyphs[140] = { --''--
num = 140,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 161, tyn = 85, txp = 170, typ = 99,
}
glyphs[141] = { --'?'--
num = 141,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 181, tyn = 85, txp = 190, typ = 99,
}
glyphs[142] = { --''--
num = 142,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 201, tyn = 85, txp = 210, typ = 99,
}
glyphs[143] = { --'?'--
num = 143,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 221, tyn = 85, txp = 230, typ = 99,
}
glyphs[144] = { --'?'--
num = 144,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 241, tyn = 85, txp = 250, typ = 99,
}
glyphs[145] = { --''--
num = 145,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 261, tyn = 85, txp = 270, typ = 99,
}
glyphs[146] = { --''--
num = 146,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 281, tyn = 85, txp = 290, typ = 99,
}
glyphs[147] = { --''--
num = 147,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 301, tyn = 85, txp = 310, typ = 99,
}
glyphs[148] = { --''--
num = 148,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 321, tyn = 85, txp = 330, typ = 99,
}
glyphs[149] = { --''--
num = 149,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 341, tyn = 85, txp = 350, typ = 99,
}
glyphs[150] = { --''--
num = 150,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 361, tyn = 85, txp = 370, typ = 99,
}
glyphs[151] = { --''--
num = 151,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 381, tyn = 85, txp = 390, typ = 99,
}
glyphs[152] = { --''--
num = 152,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 401, tyn = 85, txp = 410, typ = 99,
}
glyphs[153] = { --''--
num = 153,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 421, tyn = 85, txp = 430, typ = 99,
}
glyphs[154] = { --''--
num = 154,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 441, tyn = 85, txp = 450, typ = 99,
}
glyphs[155] = { --''--
num = 155,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 461, tyn = 85, txp = 470, typ = 99,
}
glyphs[156] = { --''--
num = 156,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 481, tyn = 85, txp = 490, typ = 99,
}
glyphs[157] = { --'?'--
num = 157,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 1, tyn = 106, txp = 10, typ = 120,
}
glyphs[158] = { --''--
num = 158,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 21, tyn = 106, txp = 30, typ = 120,
}
glyphs[159] = { --''--
num = 159,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 41, tyn = 106, txp = 50, typ = 120,
}
glyphs[160] = { --' '--
num = 160,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 61, tyn = 106, txp = 70, typ = 120,
}
glyphs[161] = { --'¡'--
num = 161,
adv = 5,
oxn = -2, oyn = -5, oxp = 6, oyp = 10,
txn = 81, tyn = 106, txp = 89, typ = 121,
}
glyphs[162] = { --'¢'--
num = 162,
adv = 8,
oxn = -2, oyn = -4, oxp = 10, oyp = 11,
txn = 101, tyn = 106, txp = 113, typ = 121,
}
glyphs[163] = { --'£'--
num = 163,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 121, tyn = 106, txp = 133, typ = 122,
}
glyphs[164] = { --'¤'--
num = 164,
adv = 8,
oxn = -2, oyn = -1, oxp = 10, oyp = 11,
txn = 141, tyn = 106, txp = 153, typ = 118,
}
glyphs[165] = { --'¥'--
num = 165,
adv = 8,
oxn = -2, oyn = -2, oxp = 10, oyp = 12,
txn = 161, tyn = 106, txp = 173, typ = 120,
}
glyphs[166] = { --'¦'--
num = 166,
adv = 4,
oxn = -1, oyn = -5, oxp = 5, oyp = 13,
txn = 181, tyn = 106, txp = 187, typ = 124,
}
glyphs[167] = { --'§'--
num = 167,
adv = 8,
oxn = -2, oyn = -5, oxp = 10, oyp = 13,
txn = 201, tyn = 106, txp = 213, typ = 124,
}
glyphs[168] = { --'¨'--
num = 168,
adv = 5,
oxn = -2, oyn = 6, oxp = 7, oyp = 13,
txn = 221, tyn = 106, txp = 230, typ = 113,
}
glyphs[169] = { --'©'--
num = 169,
adv = 10,
oxn = -3, oyn = -3, oxp = 13, oyp = 13,
txn = 241, tyn = 106, txp = 257, typ = 122,
}
glyphs[170] = { --'ª'--
num = 170,
adv = 5,
oxn = -2, oyn = 1, oxp = 7, oyp = 13,
txn = 261, tyn = 106, txp = 270, typ = 118,
}
glyphs[171] = { --'«'--
num = 171,
adv = 8,
oxn = -1, oyn = -1, oxp = 9, oyp = 9,
txn = 281, tyn = 106, txp = 291, typ = 116,
}
glyphs[172] = { --'¬'--
num = 172,
adv = 8,
oxn = -2, oyn = -1, oxp = 10, oyp = 8,
txn = 301, tyn = 106, txp = 313, typ = 115,
}
glyphs[173] = { --''--
num = 173,
adv = 6,
oxn = -2, oyn = -2, oxp = 7, oyp = 12,
txn = 321, tyn = 106, txp = 330, typ = 120,
}
glyphs[174] = { --'®'--
num = 174,
adv = 10,
oxn = -3, oyn = -3, oxp = 13, oyp = 13,
txn = 341, tyn = 106, txp = 357, typ = 122,
}
glyphs[175] = { --'¯'--
num = 175,
adv = 5,
oxn = -2, oyn = 6, oxp = 7, oyp = 13,
txn = 361, tyn = 106, txp = 370, typ = 113,
}
glyphs[176] = { --'°'--
num = 176,
adv = 8,
oxn = 0, oyn = 3, oxp = 9, oyp = 12,
txn = 381, tyn = 106, txp = 390, typ = 115,
}
glyphs[177] = { --'±'--
num = 177,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 11,
txn = 401, tyn = 106, txp = 413, typ = 120,
}
glyphs[178] = { --'²'--
num = 178,
adv = 5,
oxn = -2, oyn = 1, oxp = 7, oyp = 13,
txn = 421, tyn = 106, txp = 430, typ = 118,
}
glyphs[179] = { --'³'--
num = 179,
adv = 5,
oxn = -2, oyn = 1, oxp = 7, oyp = 13,
txn = 441, tyn = 106, txp = 450, typ = 118,
}
glyphs[180] = { --'´'--
num = 180,
adv = 5,
oxn = -1, oyn = 6, oxp = 7, oyp = 13,
txn = 461, tyn = 106, txp = 469, typ = 113,
}
glyphs[181] = { --'µ'--
num = 181,
adv = 9,
oxn = -2, oyn = -6, oxp = 11, oyp = 10,
txn = 481, tyn = 106, txp = 494, typ = 122,
}
glyphs[182] = { --'¶'--
num = 182,
adv = 8,
oxn = -2, oyn = -5, oxp = 10, oyp = 13,
txn = 1, tyn = 127, txp = 13, typ = 145,
}
glyphs[183] = { --'·'--
num = 183,
adv = 4,
oxn = -2, oyn = 0, oxp = 5, oyp = 7,
txn = 21, tyn = 127, txp = 28, typ = 134,
}
glyphs[184] = { --'¸'--
num = 184,
adv = 5,
oxn = -2, oyn = -6, oxp = 7, oyp = 2,
txn = 41, tyn = 127, txp = 50, typ = 135,
}
glyphs[185] = { --'¹'--
num = 185,
adv = 5,
oxn = -2, oyn = 1, oxp = 6, oyp = 12,
txn = 61, tyn = 127, txp = 69, typ = 138,
}
glyphs[186] = { --'º'--
num = 186,
adv = 5,
oxn = -2, oyn = 1, oxp = 7, oyp = 13,
txn = 81, tyn = 127, txp = 90, typ = 139,
}
glyphs[187] = { --'»'--
num = 187,
adv = 8,
oxn = -1, oyn = -1, oxp = 9, oyp = 9,
txn = 101, tyn = 127, txp = 111, typ = 137,
}
glyphs[188] = { --'¼'--
num = 188,
adv = 12,
oxn = -2, oyn = -3, oxp = 14, oyp = 13,
txn = 121, tyn = 127, txp = 137, typ = 143,
}
glyphs[189] = { --'½'--
num = 189,
adv = 12,
oxn = -2, oyn = -3, oxp = 14, oyp = 13,
txn = 141, tyn = 127, txp = 157, typ = 143,
}
glyphs[190] = { --'¾'--
num = 190,
adv = 12,
oxn = -2, oyn = -3, oxp = 14, oyp = 13,
txn = 161, tyn = 127, txp = 177, typ = 143,
}
glyphs[191] = { --'¿'--
num = 191,
adv = 9,
oxn = -2, oyn = -5, oxp = 10, oyp = 10,
txn = 181, tyn = 127, txp = 193, typ = 142,
}
glyphs[192] = { --'À'--
num = 192,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 16,
txn = 201, tyn = 127, txp = 215, typ = 145,
}
glyphs[193] = { --'Á'--
num = 193,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 15,
txn = 221, tyn = 127, txp = 235, typ = 144,
}
glyphs[194] = { --'Â'--
num = 194,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 16,
txn = 241, tyn = 127, txp = 255, typ = 145,
}
glyphs[195] = { --'Ã'--
num = 195,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 16,
txn = 261, tyn = 127, txp = 275, typ = 145,
}
glyphs[196] = { --'Ä'--
num = 196,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 16,
txn = 281, tyn = 127, txp = 295, typ = 145,
}
glyphs[197] = { --'Å'--
num = 197,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 16,
txn = 301, tyn = 127, txp = 315, typ = 145,
}
glyphs[198] = { --'Æ'--
num = 198,
adv = 14,
oxn = -2, oyn = -2, oxp = 16, oyp = 13,
txn = 321, tyn = 127, txp = 339, typ = 142,
}
glyphs[199] = { --'Ç'--
num = 199,
adv = 10,
oxn = -2, oyn = -6, oxp = 12, oyp = 13,
txn = 341, tyn = 127, txp = 355, typ = 146,
}
glyphs[200] = { --'È'--
num = 200,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 16,
txn = 361, tyn = 127, txp = 373, typ = 145,
}
glyphs[201] = { --'É'--
num = 201,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 16,
txn = 381, tyn = 127, txp = 393, typ = 145,
}
glyphs[202] = { --'Ê'--
num = 202,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 16,
txn = 401, tyn = 127, txp = 413, typ = 145,
}
glyphs[203] = { --'Ë'--
num = 203,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 16,
txn = 421, tyn = 127, txp = 433, typ = 145,
}
glyphs[204] = { --'Ì'--
num = 204,
adv = 4,
oxn = -2, oyn = -2, oxp = 5, oyp = 16,
txn = 441, tyn = 127, txp = 448, typ = 145,
}
glyphs[205] = { --'Í'--
num = 205,
adv = 4,
oxn = -2, oyn = -2, oxp = 7, oyp = 16,
txn = 461, tyn = 127, txp = 470, typ = 145,
}
glyphs[206] = { --'Î'--
num = 206,
adv = 4,
oxn = -2, oyn = -2, oxp = 7, oyp = 16,
txn = 481, tyn = 127, txp = 490, typ = 145,
}
glyphs[207] = { --'Ï'--
num = 207,
adv = 4,
oxn = -2, oyn = -2, oxp = 7, oyp = 16,
txn = 1, tyn = 148, txp = 10, typ = 166,
}
glyphs[208] = { --'Ð'--
num = 208,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 13,
txn = 21, tyn = 148, txp = 35, typ = 163,
}
glyphs[209] = { --'Ñ'--
num = 209,
adv = 10,
oxn = -2, oyn = -2, oxp = 12, oyp = 16,
txn = 41, tyn = 148, txp = 55, typ = 166,
}
glyphs[210] = { --'Ò'--
num = 210,
adv = 11,
oxn = -2, oyn = -3, oxp = 13, oyp = 16,
txn = 61, tyn = 148, txp = 76, typ = 167,
}
glyphs[211] = { --'Ó'--
num = 211,
adv = 11,
oxn = -2, oyn = -3, oxp = 13, oyp = 16,
txn = 81, tyn = 148, txp = 96, typ = 167,
}
glyphs[212] = { --'Ô'--
num = 212,
adv = 11,
oxn = -2, oyn = -3, oxp = 13, oyp = 16,
txn = 101, tyn = 148, txp = 116, typ = 167,
}
glyphs[213] = { --'Õ'--
num = 213,
adv = 11,
oxn = -2, oyn = -3, oxp = 13, oyp = 16,
txn = 121, tyn = 148, txp = 136, typ = 167,
}
glyphs[214] = { --'Ö'--
num = 214,
adv = 11,
oxn = -2, oyn = -3, oxp = 13, oyp = 16,
txn = 141, tyn = 148, txp = 156, typ = 167,
}
glyphs[215] = { --'×'--
num = 215,
adv = 8,
oxn = -1, oyn = -2, oxp = 10, oyp = 9,
txn = 161, tyn = 148, txp = 172, typ = 159,
}
glyphs[216] = { --'Ø'--
num = 216,
adv = 11,
oxn = -2, oyn = -3, oxp = 13, oyp = 13,
txn = 181, tyn = 148, txp = 196, typ = 164,
}
glyphs[217] = { --'Ù'--
num = 217,
adv = 10,
oxn = -1, oyn = -3, oxp = 12, oyp = 16,
txn = 201, tyn = 148, txp = 214, typ = 167,
}
glyphs[218] = { --'Ú'--
num = 218,
adv = 10,
oxn = -1, oyn = -3, oxp = 12, oyp = 16,
txn = 221, tyn = 148, txp = 234, typ = 167,
}
glyphs[219] = { --'Û'--
num = 219,
adv = 10,
oxn = -1, oyn = -3, oxp = 12, oyp = 16,
txn = 241, tyn = 148, txp = 254, typ = 167,
}
glyphs[220] = { --'Ü'--
num = 220,
adv = 10,
oxn = -1, oyn = -3, oxp = 12, oyp = 16,
txn = 261, tyn = 148, txp = 274, typ = 167,
}
glyphs[221] = { --'Ý'--
num = 221,
adv = 9,
oxn = -2, oyn = -2, oxp = 12, oyp = 16,
txn = 281, tyn = 148, txp = 295, typ = 166,
}
glyphs[222] = { --'Þ'--
num = 222,
adv = 9,
oxn = -1, oyn = -2, oxp = 11, oyp = 13,
txn = 301, tyn = 148, txp = 313, typ = 163,
}
glyphs[223] = { --'ß'--
num = 223,
adv = 9,
oxn = -2, oyn = -3, oxp = 11, oyp = 13,
txn = 321, tyn = 148, txp = 334, typ = 164,
}
glyphs[224] = { --'à'--
num = 224,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 341, tyn = 148, txp = 353, typ = 164,
}
glyphs[225] = { --'á'--
num = 225,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 361, tyn = 148, txp = 373, typ = 164,
}
glyphs[226] = { --'â'--
num = 226,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 381, tyn = 148, txp = 393, typ = 164,
}
glyphs[227] = { --'ã'--
num = 227,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 401, tyn = 148, txp = 413, typ = 164,
}
glyphs[228] = { --'ä'--
num = 228,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 421, tyn = 148, txp = 433, typ = 164,
}
glyphs[229] = { --'å'--
num = 229,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 441, tyn = 148, txp = 453, typ = 164,
}
glyphs[230] = { --'æ'--
num = 230,
adv = 12,
oxn = -2, oyn = -3, oxp = 14, oyp = 10,
txn = 461, tyn = 148, txp = 477, typ = 161,
}
glyphs[231] = { --'ç'--
num = 231,
adv = 8,
oxn = -2, oyn = -6, oxp = 10, oyp = 10,
txn = 481, tyn = 148, txp = 493, typ = 164,
}
glyphs[232] = { --'è'--
num = 232,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 1, tyn = 169, txp = 13, typ = 185,
}
glyphs[233] = { --'é'--
num = 233,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 21, tyn = 169, txp = 33, typ = 185,
}
glyphs[234] = { --'ê'--
num = 234,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 41, tyn = 169, txp = 53, typ = 185,
}
glyphs[235] = { --'ë'--
num = 235,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 61, tyn = 169, txp = 73, typ = 185,
}
glyphs[236] = { --'ì'--
num = 236,
adv = 4,
oxn = -2, oyn = -2, oxp = 5, oyp = 13,
txn = 81, tyn = 169, txp = 88, typ = 184,
}
glyphs[237] = { --'í'--
num = 237,
adv = 4,
oxn = -2, oyn = -2, oxp = 7, oyp = 13,
txn = 101, tyn = 169, txp = 110, typ = 184,
}
glyphs[238] = { --'î'--
num = 238,
adv = 4,
oxn = -2, oyn = -2, oxp = 7, oyp = 13,
txn = 121, tyn = 169, txp = 130, typ = 184,
}
glyphs[239] = { --'ï'--
num = 239,
adv = 4,
oxn = -2, oyn = -2, oxp = 7, oyp = 13,
txn = 141, tyn = 169, txp = 150, typ = 184,
}
glyphs[240] = { --'ð'--
num = 240,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 161, tyn = 169, txp = 173, typ = 185,
}
glyphs[241] = { --'ñ'--
num = 241,
adv = 9,
oxn = -2, oyn = -2, oxp = 10, oyp = 13,
txn = 181, tyn = 169, txp = 193, typ = 184,
}
glyphs[242] = { --'ò'--
num = 242,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 201, tyn = 169, txp = 213, typ = 185,
}
glyphs[243] = { --'ó'--
num = 243,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 221, tyn = 169, txp = 233, typ = 185,
}
glyphs[244] = { --'ô'--
num = 244,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 241, tyn = 169, txp = 253, typ = 185,
}
glyphs[245] = { --'õ'--
num = 245,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 261, tyn = 169, txp = 273, typ = 185,
}
glyphs[246] = { --'ö'--
num = 246,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 281, tyn = 169, txp = 293, typ = 185,
}
glyphs[247] = { --'÷'--
num = 247,
adv = 8,
oxn = -2, oyn = -3, oxp = 10, oyp = 9,
txn = 301, tyn = 169, txp = 313, typ = 181,
}
glyphs[248] = { --'ø'--
num = 248,
adv = 9,
oxn = -2, oyn = -3, oxp = 11, oyp = 10,
txn = 321, tyn = 169, txp = 334, typ = 182,
}
glyphs[249] = { --'ù'--
num = 249,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 341, tyn = 169, txp = 353, typ = 185,
}
glyphs[250] = { --'ú'--
num = 250,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 361, tyn = 169, txp = 373, typ = 185,
}
glyphs[251] = { --'û'--
num = 251,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 381, tyn = 169, txp = 393, typ = 185,
}
glyphs[252] = { --'ü'--
num = 252,
adv = 9,
oxn = -2, oyn = -3, oxp = 10, oyp = 13,
txn = 401, tyn = 169, txp = 413, typ = 185,
}
glyphs[253] = { --'ý'--
num = 253,
adv = 8,
oxn = -2, oyn = -6, oxp = 10, oyp = 13,
txn = 421, tyn = 169, txp = 433, typ = 188,
}
glyphs[254] = { --'þ'--
num = 254,
adv = 9,
oxn = -2, oyn = -6, oxp = 11, oyp = 13,
txn = 441, tyn = 169, txp = 454, typ = 188,
}
glyphs[255] = { --'ÿ'--
num = 255,
adv = 8,
oxn = -2, oyn = -6, oxp = 10, oyp = 13,
txn = 461, tyn = 169, txp = 473, typ = 188,
}
fontSpecs.glyphs = glyphs
return fontSpecs
| gpl-2.0 |
Neopallium/lua-pb | spec/helper.lua | 5 | 1140 | -- sudo luarocks install lpeg
-- sudo luarocks install struct
inspect = require 'spec.inspect'
telescope = require 'telescope'
local function compare_tables(t1, t2)
local ty1 = type(t1)
local ty2 = type(t2)
if ty1 ~= ty2 then return false end
-- non-table types can be directly compared
if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end
-- as well as tables which have the metamethod __eq
local mt = getmetatable(t1)
for k1,v1 in pairs(t1) do
local v2 = t2[k1]
if v2 == nil or not compare_tables(v1,v2) then return false end
end
for k2,v2 in pairs(t2) do
local v1 = t1[k2]
if v1 == nil or not compare_tables(v1,v2) then return false end
end
return true
end
telescope.make_assertion("tables", function(_, a, b)
return "Expected table to be " .. inspect(b) .. ", but was " .. inspect(a)
end, function(a, b)
return compare_tables(a, b)
end)
telescope.make_assertion("length", function(_, a, b)
if not a then return "Expected table but got nil" end
return "Expected table length to be " .. b .. ", but was " .. #a
end, function(a, b)
if not a then return false end
return #a == b
end)
| mit |
Anarchid/Zero-K | effects/stumpy.lua | 25 | 5377 | -- stompollute
-- stumpmuzzle
-- stompshells
-- stompollute_smog
-- stompdust
return {
["stompollute"] = {
boom = {
air = true,
class = [[CExpGenSpawner]],
count = 10,
ground = true,
water = true,
properties = {
delay = [[0 i0.25]],
explosiongenerator = [[custom:STOMPOLLUTE_SMOG]],
pos = [[-0, 0, 0]],
},
},
},
["stumpmuzzle"] = {
groundflash = {
circlealpha = 1,
circlegrowth = 0,
flashalpha = 0.9,
flashsize = 60,
ttl = 4,
color = {
[1] = 1,
[2] = 0.5,
[3] = 0,
},
},
muzzleflash = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 1,
colormap = [[1 0.7 0.2 0.01 1 0.7 0.2 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 15,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 10,
particlelife = 7,
particlelifespread = 0,
particlesize = 1,
particlesizespread = 3,
particlespeed = 3,
particlespeedspread = 3,
pos = [[0, -3, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[plasma]],
},
},
muzzlesmoke = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.8,
colormap = [[1 1 1 0.01 1 1 1 0.01 1 1 1 0.01 0 0 0 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 5,
particlelifespread = 0,
particlesize = 1,
particlesizespread = 1,
particlespeed = 0,
particlespeedspread = 1,
pos = [[0, 3, 0]],
sizegrowth = 5,
sizemod = 1.0,
texture = [[exp00_5]],
},
},
},
["stompshells"] = {
shells = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
colormap = [[1 1 1 1 1 1 1 1]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, -0.5, 0]],
numparticles = 1,
particlelife = 25,
particlelifespread = 0,
particlesize = 3,
particlesizespread = 0,
particlespeed = 4,
particlespeedspread = 0,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[shell]],
},
},
},
["stompollute_smog"] = {
pollute = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.9,
colormap = [[0.3 0.3 0.3 0.8 0 0 0 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 30,
particlelifespread = 0,
particlesize = 0.3,
particlesizespread = 0.3,
particlespeed = 3,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 0.2,
sizemod = 1.0,
texture = [[smokesmall]],
},
},
},
["stompdust"] = {
muzzleflash = {
air = true,
class = [[CSimpleParticleSystem]],
count = 0,
ground = true,
water = true,
properties = {
airdrag = 0.8,
colormap = [[0.72 0.61 0.41 1 0 0 0 0.01]],
directional = false,
emitrot = 90,
emitrotspread = 10,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 20,
particlelife = 30,
particlelifespread = 0,
particlesize = 1,
particlesizespread = 2,
particlespeed = 6,
particlespeedspread = 6,
pos = [[0, 0, 0]],
sizegrowth = 1,
sizemod = 1.0,
texture = [[smokesmall]],
},
},
},
}
| gpl-2.0 |
Janpot/fantastiq | lib/lua/addJob.lua | 1 | 1777 | local key_nextId,
key_index = unpack(KEYS)
local timestamp,
priority,
runAt = unpack(ARGV)
local jobDatas = {select(4, unpack(ARGV))}
timestamp = tonumber(timestamp)
runAt = tonumber(runAt)
priority = tonumber(priority)
local unique = fantastiq.getConfig('unique')
local jobKeys = {}
if unique then
local uniqueKey = fantastiq.getConfig('uniqueKey')
if uniqueKey then
for i, jobData in ipairs(jobDatas) do
local parsed = cjson.decode(jobData)
if type(parsed) ~= 'table' then
return redis.error_reply('Job requires a key')
end
local key = parsed[uniqueKey]
if not key then
return redis.error_reply('Job requires a key')
end
if type(key) ~= 'string' then
return redis.error_reply('Invalid key')
end
jobKeys[i] = key
end
else
for i, jobData in ipairs(jobDatas) do
jobKeys[i] = jobData
end
end
end
local jobIds = {}
for i, jobData in ipairs(jobDatas) do
local existing
if unique then
existing = redis.call('HGET', key_index, jobKeys[i])
end
if existing then
jobIds[i] = existing
else
local nextId = redis.call('INCR', key_nextId)
local jobId = string.format('%013X', nextId)
if jobKeys[i] then
redis.call('HSET', key_index, jobKeys[i], jobId)
end
jobIds[i] = jobId
local jobDetails = {
id = jobId,
priority = priority,
data = jobData,
created = timestamp,
attempts = 0,
key = jobKeys[i]
}
if runAt > timestamp then
jobDetails['runAt'] = runAt
fantastiq.updateJobState(jobDetails, 'delayed')
else
fantastiq.updateJobState(jobDetails, 'inactive')
end
fantastiq.setJobDetails(jobId, jobDetails)
end
end
return jobIds
| mit |
LightenPan/skynet-yule | service/sharedatad.lua | 23 | 2745 | local skynet = require "skynet"
local sharedata = require "sharedata.corelib"
local table = table
local NORET = {}
local pool = {}
local pool_count = {}
local objmap = {}
local function newobj(name, tbl)
assert(pool[name] == nil)
local cobj = sharedata.host.new(tbl)
sharedata.host.incref(cobj)
local v = { value = tbl , obj = cobj, watch = {} }
objmap[cobj] = v
pool[name] = v
pool_count[name] = { n = 0, threshold = 16 }
end
local function collectobj()
while true do
skynet.sleep(600 * 100) -- sleep 10 min
collectgarbage()
for obj, v in pairs(objmap) do
if v == true then
if sharedata.host.getref(obj) <= 0 then
objmap[obj] = nil
sharedata.host.delete(obj)
end
end
end
end
end
local CMD = {}
local env_mt = { __index = _ENV }
function CMD.new(name, t)
local dt = type(t)
local value
if dt == "table" then
value = t
elseif dt == "string" then
value = setmetatable({}, env_mt)
local f = load(t, "=" .. name, "t", value)
assert(skynet.pcall(f))
setmetatable(value, nil)
elseif dt == "nil" then
value = {}
else
error ("Unknown data type " .. dt)
end
newobj(name, value)
end
function CMD.delete(name)
local v = assert(pool[name])
pool[name] = nil
pool_count[name] = nil
assert(objmap[v.obj])
objmap[v.obj] = true
sharedata.host.decref(v.obj)
for _,response in pairs(v.watch) do
response(true)
end
end
function CMD.query(name)
local v = assert(pool[name])
local obj = v.obj
sharedata.host.incref(obj)
return v.obj
end
function CMD.confirm(cobj)
if objmap[cobj] then
sharedata.host.decref(cobj)
end
return NORET
end
function CMD.update(name, t)
local v = pool[name]
local watch, oldcobj
if v then
watch = v.watch
oldcobj = v.obj
objmap[oldcobj] = true
sharedata.host.decref(oldcobj)
pool[name] = nil
pool_count[name] = nil
end
CMD.new(name, t)
local newobj = pool[name].obj
if watch then
sharedata.host.markdirty(oldcobj)
for _,response in pairs(watch) do
response(true, newobj)
end
end
end
local function check_watch(queue)
local n = 0
for k,response in pairs(queue) do
if not response "TEST" then
queue[k] = nil
n = n + 1
end
end
return n
end
function CMD.monitor(name, obj)
local v = assert(pool[name])
if obj ~= v.obj then
return v.obj
end
local n = pool_count[name].n
pool_count[name].n = n + 1
if n > pool_count[name].threshold then
n = n - check_watch(v.watch)
pool_count[name].threshold = n * 2
end
table.insert(v.watch, skynet.response())
return NORET
end
skynet.start(function()
skynet.fork(collectobj)
skynet.dispatch("lua", function (session, source ,cmd, ...)
local f = assert(CMD[cmd])
local r = f(...)
if r ~= NORET then
skynet.ret(skynet.pack(r))
end
end)
end)
| mit |
Mutos/SoC-Test-001 | dat/missions/empire/shipping/es02.lua | 4 | 7648 | --[[
Empire VIP Rescue
Author: bobbens
minor edits by Infiltrator
- Mission fixed to suit big systems (Anatolis, 11/02/2011)
Rescue a VIP stranded on a disabled ship in a system while FLF and Dvaered
are fighting.
Stages:
0) Go to sector.
1) Board ship and rescue VIP.
2) Rescued VIP, returning to base.
3) VIP died or jump out of system without VIP --> mission failure.
]]--
include "dat/scripts/numstring.lua"
lang = naev.lang()
if lang == "es" then
-- not translated atm
else -- default english
-- Mission details
bar_desc = "Commander Soldner is waiting for you."
misn_title = "Empire VIP Rescue"
misn_reward = "%s credits"
misn_desc = {}
misn_desc[1] = "Rescue the VIP from a transport ship in the %s system."
misn_desc[2] = "Return to %s in the %s system with the VIP."
-- Fancy text messages
title = {}
title[1] = "Commander Soldner"
title[2] = "Disabled Ship"
title[3] = "Mission Success"
title[4] = "Mission Failure"
text = {}
text[1] = [[You meet up once more with Commander Soldner at the bar.
"Hello again, %s. Still interested in doing another mission? This one will be more dangerous."]]
text[2] = [[Commander Soldner nods and continues, "We've had reports that a transport vessel came under attack while transporting a VIP. They managed to escape, but the engine ended up giving out in the %s system. The ship is now disabled and we need someone to board the ship and rescue the VIP. There have been many FLF ships detected near the sector, but we've managed to organise a Dvaered escort for you."
"You're going to have to fly to the %s system, find and board the transport ship to rescue the VIP, and then fly back. The sector is most likely going to be hot. That's where your Dvaered escorts will come in. Their mission will be to distract and neutralise all possible hostiles. You must not allow the transport ship to be destroyed before you rescue the VIP. His survival is vital."]]
text[3] = [["Be careful with the Dvaered; they can be a bit blunt, and might accidentally destroy the transport ship. If all goes well, you'll be paid %d credits when you return with the VIP. Good luck, pilot."]]
text[4] = [[The ship's hatch opens and immediately an unconscious VIP is brought aboard by his bodyguard. Looks like there is no one else aboard.]]
text[5] = [[You land at the starport. It looks like the VIP has already recovered. He thanks you profusely before heading off. You proceed to pay Commander Soldner a visit. He seems to be happy, for once.
"It seems like you managed to pull it off. I had my doubts at first, but you've proven to be a very skilled pilot. I'll be putting in a good word with the Dvaered for you. Hopefully they'll start offering you work too. We have nothing more for you now, but check in periodically in case something comes up for you."]]
msg = {}
msg[1] = "MISSION FAILED: VIP is dead."
msg[2] = "MISSION FAILED: You abandoned the VIP."
end
include "dat/missions/empire/common.lua"
function create ()
-- Target destination
destsys = system.get( "Slaccid" )
ret,retsys = planet.getLandable( "Halir" )
if ret== nil then
misn.finish(false)
end
-- Must claim system
if not misn.claim( destsys ) then
misn.finish(false)
end
-- Add NPC.
misn.setNPC( "Soldner", "empire/unique/soldner" )
misn.setDesc( bar_desc )
end
function accept ()
-- Intro text
if not tk.yesno( title[1], string.format( text[1], player.name() ) ) then
misn.finish()
end
-- Accept the mission
misn.accept()
-- Set marker
misn_marker = misn.markerAdd( destsys, "low" )
-- Mission details
misn_stage = 0
reward = 75000
misn.setTitle(misn_title)
misn.setReward( string.format(misn_reward, numstring(reward)) )
misn.setDesc( string.format(misn_desc[1], destsys:name() ))
-- Flavour text and mini-briefing
tk.msg( title[1], string.format( text[2], destsys:name(), destsys:name() ) )
tk.msg( title[1], string.format( text[3], reward ) )
misn.osdCreate(misn_title, {misn_desc[1]:format(destsys:name())})
-- Set hooks
hook.land("land")
hook.enter("enter")
hook.jumpout("jumpout")
-- Initiate mission variables (A.)
prevsys = system.cur()
end
function land ()
landed = planet.cur()
if landed == ret then
-- Successfully rescued the VIP
if misn_stage == 2 then
-- VIP gets off
misn.cargoRm(vip)
-- Rewards
player.pay(reward)
emp_modReputation( 5 ) -- Bump cap a bit
faction.modPlayerSingle("Empire",5);
faction.modPlayerSingle("Dvaered",5);
-- Flavour text
tk.msg( title[3], text[5] )
misn.finish(true)
-- Mister VIP is dead
elseif misn_stage == 3 then
-- What a disgrace you are, etc...
tk.msg( title[4], text[6] )
emp_modReputation( 5 ) -- Bump cap a bit
misn.finish(true)
end
end
end
function enter ()
sys = system.cur()
if misn_stage == 0 and sys == destsys then
-- Put the VIP a ways off of the player but near the jump.
enter_vect = jump.pos(sys, prevsys)
m,a = enter_vect:polar()
enter_vect:setP( m-3000, a )
p = pilot.add( "Trader Gawain", "dummy", enter_vect )
for _,v in ipairs(p) do
v:setPos( enter_vect )
v:setVel( vec2.new( 0, 0 ) ) -- Clear velocity
v:disable()
v:setHilight(true)
v:setVisplayer(true)
v:setFaction( "Empire" )
hook.pilot( v, "board", "board" )
hook.pilot( v, "death", "death" )
end
-- FLF Spawn around the Gawain
p = pilot.add( "FLF Med Force", nil, enter_vect )
for k,v in ipairs(p) do
v:setHostile()
end
-- To make it more interesting a vendetta will solely target the player.
p = pilot.add( "FLF Vendetta", nil, enter_vect )[1]
p:control()
p:setHostile()
p:attack( player.pilot() )
-- Now Dvaered
-- They will jump together with you in the system at the jumppoint. (A.)
p = pilot.add( "Dvaered Med Force", nil, prevsys )
for k,v in ipairs(p) do
v:setFriendly()
end
-- Add more ships on a timer to make this messy
hook.timer(rnd.rnd( 3000, 5000 ) , "delay_flf")
-- Pass to next stage
misn_stage = 1
-- Can't run away from combat
elseif misn_stage == 1 then
-- Notify of mission failure
player.msg( msg[2] )
misn.finish(false)
end
end
function jumpout ()
-- Storing the system the player jumped from.
prevsys = system.cur()
end
function delay_flf ()
if misn_stage ~= 0 then
return
end
-- More ships to pressure player from behind
p = pilot.add( "FLF Sml Force", nil, prevsys )
for k,v in ipairs(p) do
v:setHostile()
end
end
function board ()
-- VIP boards
vip = misn.cargoAdd( "VIP", 0 )
tk.msg( title[2], text[4] )
-- Update mission details
misn_stage = 2
misn.markerMove( misn_marker, retsys )
misn.setDesc( string.format(misn_desc[2], ret:name(), retsys:name() ))
misn.osdCreate(misn_title, {misn_desc[2]:format(ret:name(),retsys:name())})
-- Force unboard
player.unboard()
end
function death ()
if misn_stage == 1 then
-- Notify of death
player.msg( msg[1] )
-- Update mission details
misn_stage = 3
misn.finish(false)
end
end
function abort ()
-- If aborted you'll also leave the VIP to fate. (A.)
player.msg( msg[2] )
misn.finish(false)
end
| gpl-3.0 |
mansour2911/tigr-anti-spam | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-3.0 |
bell07/minetest-smart_inventory | libs/cache.lua | 1 | 4508 | local filter = smart_inventory.filter
local cache = {}
cache.cgroups = {} -- cache groups
cache.itemgroups = {} -- raw item groups for recipe checks
cache.citems = {}
-----------------------------------------------------
-- Add an Item to the cache
-----------------------------------------------------
function cache.add_item(def)
-- special handling for doors. In inventory the item should be displayed instead of the node_a/node_b
local item_def
if def.groups and def.groups.door then
if def.door then
item_def = minetest.registered_items[def.door.name]
elseif def.drop and type(def.drop) == "string" then
item_def = minetest.registered_items[def.drop]
else
item_def = def
end
if not item_def then
minetest.log("[smart_inventory] Buggy door found: "..def.name)
item_def = def
end
else
item_def = def
end
-- already in cache. Skip duplicate processing
if cache.citems[item_def.name] then
return
end
-- fill raw groups cache for recipes
for group, value in pairs(item_def.groups) do
cache.itemgroups[group] = cache.itemgroups[group] or {}
cache.itemgroups[group][item_def.name] = item_def
end
local entry = {
name = item_def.name,
in_output_recipe = {},
in_craft_recipe = {},
cgroups = {}
}
cache.citems[item_def.name] = entry
-- classify the item
for _, flt in pairs(filter.registered_filter) do
local filter_result = flt:check_item_by_def(def)
if filter_result then
if filter_result == true then
cache.assign_to_group(flt.name, item_def, flt)
else
if type(filter_result) ~= "table" then
if tonumber(filter_result) ~= nil then
filter_result = {[flt.name..":"..filter_result] = true}
else
filter_result = {[filter_result] = true}
end
end
for key, val in pairs(filter_result) do
local filter_entry = tostring(key)
if val ~= true then
filter_entry = filter_entry..":"..tostring(val)
end
cache.assign_to_group(filter_entry, item_def, flt)
end
end
end
end
end
-----------------------------------------------------
-- Add a item to cache group
-----------------------------------------------------
function cache.assign_to_group(group_name, itemdef, flt)
-- check and build filter chain
local abs_group
local parent_ref
local parent_stringpos
for rel_group in group_name:gmatch("[^:]+") do
-- get parent relation and absolute path
if abs_group then
parent_ref = cache.cgroups[abs_group]
parent_stringpos = string.len(abs_group)+2
abs_group = abs_group..":"..rel_group
else
abs_group = rel_group
end
if flt:is_valid(abs_group) then
-- check if group is new, create it
if not cache.cgroups[abs_group] then
if parent_ref then
parent_ref.childs[abs_group] = string.sub(group_name, parent_stringpos)
end
local group = {
name = abs_group,
items = {},
parent = parent_ref,
childs = {},
}
group.group_desc = flt:get_description(group)
group.keyword = flt:get_keyword(group)
cache.cgroups[abs_group] = group
end
-- set relation
cache.cgroups[abs_group].items[itemdef.name] = itemdef
cache.citems[itemdef.name].cgroups[abs_group] = cache.cgroups[abs_group]
end
end
end
-----------------------------------------------------
-- Hook / Event for further initializations of the cache is filled
-----------------------------------------------------
cache.registered_on_cache_filled = {}
function cache.register_on_cache_filled(func, ...)
assert(type(func) == "function", "register_on_cache_filled needs a function")
table.insert(cache.registered_on_cache_filled, { func = func, opt = {...}})
end
local function process_on_cache_filled()
for _, hook in ipairs(cache.registered_on_cache_filled) do
hook.func(unpack(hook.opt))
end
end
-----------------------------------------------------
-- Fill the cache at init
-----------------------------------------------------
local function fill_cache()
local shape_filter = filter.get("shape")
for _, def in pairs(minetest.registered_items) do
-- build groups and items cache
if def.description and def.description ~= "" and
(not def.groups.not_in_creative_inventory or shape_filter:check_item_by_def(def)) then
cache.add_item(def)
end
end
-- call hooks
minetest.after(0, process_on_cache_filled)
end
minetest.after(0, fill_cache)
-----------------------------------------------------
-- return the reference to the mod
-----------------------------------------------------
return cache
| lgpl-3.0 |
mohammad4569/matrix | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
satanevil/eski-creed | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
Anarchid/Zero-K | LuaUI/Widgets/gui_chili_chatbubbles.lua | 8 | 16654 | function widget:GetInfo()
return {
name = "Chili Chat Bubbles",
desc = "Shows Chat bubbles",
author = "jK",
date = "2009 & 2010",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = false,
}
end
include("Widgets/COFCTools/ExportUtilities.lua")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local GetSpectatingState = Spring.GetSpectatingState
local GetTimer = Spring.GetTimer
local DiffTimers = Spring.DiffTimers
local Chili
local color2incolor
local colorAI = {} -- color for AI team indexed by botname
local msgTypeToColor = {
player_to_allies = {0,1,0,1},
player_to_player_received = {0,1,1,1},
player_to_player_sent = {0,1,1,1},
player_to_specs = {1,1,0.5,1},
player_to_everyone = {1,1,1,1},
spec_to_specs = {1,1,0.5,1},
spec_to_allies = {1,1,0.5,1},
spec_to_everyone = {1,1,1,1},
--shameful copy-paste -- TODO rewrite pattern matcher to remove this duplication
replay_spec_to_specs = {1,1,0.5,1},
replay_spec_to_allies = {1,1,0.5,1},
replay_spec_to_everyone = {1,1,1,1},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local vsx,vsy = 0,0
local _window_id = 0
local windows = {}
--[[
local window_margin = 5
local window_width = 400
local window_timeout = 10
--]]
--options_section = 'Interface'
options_path = 'Settings/HUD Panels/Chat/Bubbles'
options_order = {'setavatar','filterGlobalChat', 'filterAutohostMsg', 'text_height', 'window_margin', 'window_width', 'window_height', 'window_timeout', 'firstbubble_y',}
options = {
setavatar = {
name = 'Set An Avatar',
desc = 'Avatar to show next to your bubble. Requires the Avatar widget',
type = 'button',
OnChange = function() Spring.SendCommands{"luaui enablewidget Avatars", "setavatar"} end,
path = 'Settings/HUD Panels/Chat',
},
filterGlobalChat = {
name = 'Filter Global Chat',
desc = 'Filter out messages made in global chat',
type = 'bool',
value = true,
},
filterAutohostMsg = {
name = 'Filter Autohost Messages',
desc = 'Filter out messages from autohost',
type = 'bool',
value = true,
},
text_height = {
name = 'Font Size (10-18)',
type = 'number',
value = 12,
min=10,max=18,step=1,
},
window_margin = {
name = 'Margin (0 - 10)',
desc = 'Margin between bubbles',
type = 'number',
min = 0,
max = 10,
value = 0,
},
window_width = {
name = 'Width (200 - 600)',
desc = '',
type = 'number',
min = 200,
max = 600,
value = 260,
},
window_height = {
name = 'Height 60-120',
desc = '',
type = 'number',
min = 40,
max = 120,
value = 60,
},
window_timeout = {
name = 'Timeout (5 - 50)',
desc = '',
type = 'number',
min = 5,
max = 50,
value = 20,
},
firstbubble_y = {
name = 'Screen Height of First Bubble',
desc = 'How high up the first bubble should start on the right of the screen.',
type = 'number',
min = 0,
max = 600,
value = 120,
},
}
local windows_fading = {}
-- map points
local windows_points = {}
local avatar_fallback = "LuaUI/Configs/Avatars/Crystal_personal.png"
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local playerNameToIDlist = {}
local function MyPlayerNameToID(name)
local buf = playerNameToIDlist[name]
if (not buf) then
local players = Spring.GetPlayerList(true)
for i=1,#players do
local pid = players[i]
local pname = Spring.GetPlayerInfo(pid, false)
playerNameToIDlist[pname] = pid
end
return playerNameToIDlist[name]
else
return buf
end
end
local function newWindowID()
_window_id = _window_id + 1
return _window_id
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Update()
local w = windows[1]
local time_now = GetTimer()
if (w)and(DiffTimers(time_now, w.custom_timeadded) > options.window_timeout.value) then
table.remove(windows,1)
windows_fading[#windows_fading+1] = w
end
local deleted = 0
for i=1,#windows_fading do
w = windows_fading[i]
if (w.x > vsx) then
deleted = deleted + 1
windows_fading[i] = nil
-- cleanup points
local id = w.window_id
if windows_points[id] then
windows_points[id] = nil
end
w:Dispose()
end
w:SetPos(w.x + 10, w.y) -- this is where it moves the window off the screen
end
if (deleted > 0) then
local num = #windows_fading - deleted
local i = 1
repeat
w = windows_fading[i]
if (not w) then
table.remove(windows_fading,i)
i = i - 1
end
i = i + 1
until (i>num);
end
end
function PushWindow(window)
if window then
window:Realign() --// else `window.height` wouldn't give the desired value
windows[#windows+1] = window
end
local w = windows[1]
w:SetPos(w.x, options.firstbubble_y.value)
for i=2,#windows do
windows[i]:SetPos(w.x, w.y + (w.height + options.window_margin.value))
w = windows[i]
if w.y > vsy then -- overflow, get rid of top window
windows[1]:Dispose()
table.remove(windows, 1)
PushWindow()
return
end
end
end
-- last message
local last_type = nil
local last_a = nil
local last_b = nil
local last_c = nil
local last_timeadded = GetTimer()
-- returns true if current message is same as last one
-- TODO: graphical representation
function DuplicateMessage(type, a, b, c)
local samemessage = false
if type == last_type and a == last_a and b == last_b and c == last_c then
if DiffTimers(GetTimer(), last_timeadded) < options.window_timeout.value then
samemessage = true
end
end
if not samemessage then
last_type = type
last_a = a
last_b = b
last_c = c
last_timeadded = GetTimer()
end
return samemessage
end
function widget:AddChatMessage(msg)
local playerID = msg.player and msg.player.id
local type = msg.msgtype
local text = msg.argument or ''
if DuplicateMessage("chat", playerID, msg.argument, type) then
return
end
local playerName,active,isSpec,teamID
local teamcolor
local avatar = nil
if type == 'autohost' then
active = false
playerName = "Autohost"
isSpec = true
teamID = 0
else
if msg.player and msg.player.isAI then
teamcolor = colorAI[msg.playername]
playerName = msg.playername
active = true
else
playerName,active,isSpec,teamID,allyTeamID,pingTime,cpuUsage,country,rank, customKeys = Spring.GetPlayerInfo(playerID)
teamcolor = {Spring.GetTeamColor(teamID)}
if (customKeys ~= nil) and (customKeys.avatar~=nil) then
avatar = "LuaUI/Configs/Avatars/" .. customKeys.avatar .. ".png"
end
end
end
if (not active or isSpec) then
teamcolor = {1,1,1,0.7}
end
local bubbleColor = msgTypeToColor[type] or {1,1,1,1}
local textColor = color2incolor(teamcolor)
if type == 'player_to_player_received' or type == 'player_to_player_sent' then
text = "Private: " .. text
end
local pp = nil
if WG.alliedCursorsPos then
local cur = WG.alliedCursorsPos[playerID]
if cur ~= nil then
pp = {cur[1], cur[2], cur[3], cur[4]}
end
end
local w = Chili.Window:New{
parent = Chili.Screen0;
x = vsx-options.window_width.value;
y = options.firstbubble_y.value;
width = options.window_width.value;
height = options.window_height.value;
--minWidth = options.window_width.value;
--minHeight = options.window_height.value;
autosize = true;
resizable = false;
draggable = false;
skinName = "BubbleBlack";
color = bubbleColor;
padding = {12, 12, 12, 12};
custom_timeadded = GetTimer(),
window_id = newWindowID(),
OnClick = {function()
local _, _, meta, _ = Spring.GetModKeyState()
if meta then
WG.crude.OpenPath('Settings/HUD Panels/Chat') --click + space will shortcut to option-menu
WG.crude.ShowMenu() --make epic Chili menu appear.
return true
end
if pp ~= nil then
SetCameraTarget(pp[1], 0, pp[2],1)
end
end},
}
function w:HitTest(x,y)
return self
end
Chili.Image:New{
parent = w;
file = ((WG.Avatar and WG.Avatar.GetAvatar(playerName)) or avatar) or avatar_fallback; --get avatar from "api_avatar.lua" or from server, or use the default avatar
--file2 = (type=='s') and "LuaUI/Images/tech_progressbar_empty.png";
width = options.window_height.value-24;
height = options.window_height.value-24;
}
--[[
local verb = " says:"
if (type == 'a') then
verb = " says to allies:"
elseif (type == 's') then
verb = " says to spectators:"
elseif (type == 'p') then
verb = " whispers to you:"
elseif (type == 'l') then
verb = " says:"
end
local l = Chili.Label:New{
parent = w;
caption = playerName .. verb;
--caption = "<" .. playerName .. ">";
x = options.window_height.value - 24;
y = 2;
width = w.clientWidth - (options.window_height.value - 24) - 5;
height = 14;
valign = "ascender";
align = "left";
autosize = false;
font = {
size = 12;
shadow = true;
}
}
]]--
Chili.TextBox:New{
parent = w;
text = textColor .. playerName .. ":\008 " .. color2incolor(bubbleColor) .. text .. "\008";
x = options.window_height.value - 24;
y = 2;
width = w.clientWidth - (options.window_height.value - 24) - 5;
valign = "ascender";
align = "left";
font = {
size = options.text_height.value;
shadow = true;
}
}
PushWindow(w)
end
function widget:AddConsoleMessage(msg)
if not GetSpectatingState() then
if (msg.source == 'spec' or msg.source == "enemy") and options.filterGlobalChat.value then
return
end
end
if msg.msgtype == 'other' then return end
if msg.msgtype == 'autohost' and options.filterAutohostMsg.value then
return
end
widget:AddChatMessage(msg)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local lastPoint = nil
function widget:AddMapPoint(player, caption, px, py, pz)
if DuplicateMessage("point", player, caption) then
-- update point for camera target
local w = windows[#windows]
if w then
local index = w.window_id
windows_points[index].x = px
windows_points[index].y = py
windows_points[index].z = pz
end
return
end
local playerName,active,isSpec,teamID = Spring.GetPlayerInfo(player, false)
local teamcolor = {Spring.GetTeamColor(teamID)}
if (not active or isSpec) then
teamcolor = {1,0,0,1}
end
local custom_timeadded = GetTimer()
local window_id = newWindowID()
windows_points[window_id] = {x = px, y = py, z = pz}
local w = Chili.Window:New{
parent = Chili.Screen0;
x = vsx-options.window_width.value;
y = options.firstbubble_y.value;
width = options.window_width.value;
height = options.window_height.value;
autosize = true;
resizable = false;
--draggable = false;
skinName = "BubbleBlack";
color = {1,0.2,0.2,1};
padding = {12, 12, 12, 12};
custom_timeadded = custom_timeadded,
window_id = window_id,
draggable = false,
-- OnMouseDown is needed for OnClick
OnMouseDown = {function(self) return true end}, --capture click (don't allow window to pass the click). this prevent user from accidentally clicking on the ground while clicking on the window.
OnClick = {function(self)
local p = windows_points[window_id]
SetCameraTarget(p.x, p.y, p.z,1)
end},
}
function w:HitTest(x,y) -- FIXME: chili hacked to allow OnClick on window
return self
end
Chili.Image:New{
parent = w;
file = 'LuaUI/Images/Crystal_Clear_action_flag.png';
width = options.window_height.value-24;
height = options.window_height.value-24;
}
local text = color2incolor(teamcolor) .. playerName .. "\008 added point" .. (caption and (": " .. caption) or '')
local l = Chili.TextBox:New{
parent = w;
text = text;
x = options.window_height.value - 24;
y = 2;
width = w.clientWidth - (options.window_height.value - 24) - 5;
valign = "ascender";
align = "left";
font = {
size = options.text_height.value;
shadow = true;
}
}
PushWindow(w)
end
function widget:MapDrawCmd(playerID, cmdType, px, py, pz, caption)
if (cmdType == 'point') then
widget:AddMapPoint(playerID,caption, px,py,pz)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:AddWarning(text)
if DuplicateMessage("warning", text) then return end
teamcolor = {1,0.5,0,1}
local w = Chili.Window:New{
parent = Chili.Screen0;
x = vsx-options.window_width.value;
y = options.firstbubble_y.value;
width = options.window_width.value;
height = options.window_height.value;
resizable = false;
draggable = false;
skinName = "BubbleBlack";
color = teamcolor;
padding = {12, 12, 12, 12};
custom_timeadded = GetTimer(),
window_id = newWindowID(),
}
Chili.Image:New{
parent = w;
file = 'LuaUI/Images/Crystal_Clear_app_error.png';
width = options.window_height.value-24;
height = options.window_height.value-24;
}
Chili.Label:New{
parent = w;
caption = text;
x = options.window_height.value - 24;
width = w.clientWidth - (options.window_height.value - 24) - 5;
height = "90%";
valign = "center";
align = "left";
font = {
color = {1, 0.5, 0, 1},
size = options.text_height.value;
shadow = true;
}
}
PushWindow(w)
end
function widget:TeamDied(teamID)
local player = Spring.GetPlayerList(teamID)[1]
-- chicken team has no players (normally)
if player then
local playerName = Spring.GetPlayerInfo(player, false)
widget:AddWarning(playerName .. ' died')
end
end
--[[
function widget:TeamChanged(teamID)
--// ally changed
local playerName = Spring.GetPlayerInfo(Spring.GetPlayerList(teamID)[1], false)
widget:AddWarning(playerName .. ' allied')
end
--]]
local function SetupAITeamColor() --Copied from gui_chili_chat2_1.lua
-- register any AIs
-- Copied from gui_chili_crudeplayerlist.lua
local teamsSorted = Spring.GetTeamList()
for i=1,#teamsSorted do
local teamID = teamsSorted[i]
if teamID ~= Spring.GetGaiaTeamID() then
local isAI = select(4,Spring.GetTeamInfo(teamID, false))
if isAI then
local name = select(2,Spring.GetAIInfo(teamID))
colorAI[name] = {Spring.GetTeamColor(teamID)}
end
end --if teamID ~= Spring.GetGaiaTeamID()
end --for each team
end
function widget:PlayerChanged(playerID)
local playerName,active,isSpec,teamID = Spring.GetPlayerInfo(playerID, false)
local _,_,isDead = Spring.GetTeamInfo(teamID, false)
if (isSpec) then
if not isDead then
widget:AddWarning(playerName .. ' resigned')
end
elseif (Spring.GetDrawFrame()>120) then --// skip `changed status` message flood when entering the game
widget:AddWarning(playerName .. ' changed status')
end
end
function widget:PlayerRemoved(playerID, reason)
local playerName = Spring.GetPlayerInfo(playerID, false)
if reason == 0 then
widget:AddWarning(playerName .. ' timed out')
elseif reason == 1 then
widget:AddWarning(playerName .. ' quit')
elseif reason == 2 then
widget:AddWarning(playerName .. ' got kicked')
else
widget:AddWarning(playerName .. ' left (unknown reason)')
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:SetConfigData()
end
function widget:GetConfigData()
end
function widget:Shutdown()
for i=1,#windows do
local w = windows[i]
w:Dispose()
end
for i=1,#windows_fading do
local w = windows_fading[i]
w:Dispose()
end
windows = nil
windows_fading = nil
end
function widget:ViewResize(vsx_, vsy_)
vsx = vsx_
vsy = vsy_
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
if (not WG.Chili) then
widgetHandler:RemoveWidget()
return
end
Chili = WG.Chili
color2incolor = Chili.color2incolor
SetupAITeamColor()
widget:ViewResize(Spring.GetViewGeometry())
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Configs/StartBoxes/Vernal 3way 0.6.1.lua | 6 | 1347 | return {
[0] = {
boxes = {{
{2124, 665},
{2150, 671},
{2179, 718},
{2207, 747},
{2233, 788},
{2271, 834},
{2282, 868},
{2281, 899},
{2261, 917},
{2224, 922},
{2191, 927},
{2162, 941},
{2142, 957},
{2121, 968},
{2096, 958},
{2066, 938},
{2034, 904},
{1986, 858},
{1960, 831},
{1951, 796},
{1958, 764},
{1998, 728},
{2054, 692},
}},
startpoints = {
{2115, 814},
},
nameLong = "North",
nameShort = "N",
},
[1] = {
boxes = {{
{4558, 3531},
{4521, 3540},
{4463, 3545},
{4420, 3547},
{4374, 3525},
{4363, 3494},
{4385, 3438},
{4382, 3372},
{4411, 3334},
{4468, 3313},
{4536, 3305},
{4582, 3287},
{4606, 3293},
{4632, 3311},
{4649, 3366},
{4662, 3415},
{4654, 3466},
{4644, 3509},
{4619, 3535},
{4589, 3529},
}},
startpoints = {
{4517, 3423},
},
nameLong = "South-East",
nameShort = "SE",
},
[2] = {
boxes = {{
{970, 4123},
{1000, 4062},
{1023, 4033},
{1065, 4034},
{1104, 4077},
{1148, 4114},
{1180, 4127},
{1195, 4179},
{1157, 4266},
{1142, 4337},
{1107, 4361},
{1062, 4349},
{1028, 4342},
{937, 4294},
{919, 4248},
{944, 4185},
}},
startpoints = {
{1055, 4212},
},
nameLong = "South-West",
nameShort = "SW",
},
},
{ 2, 3 }
| gpl-2.0 |
haste/oUF | elements/pvpclassificationindicator.lua | 3 | 3692 | --[[
# Element: PvPClassificationIndicator
Handles the visibility and updating of an indicator based on the unit's PvP classification.
## Widget
PvPClassificationIndicator - A `Texture` used to display PvP classification.
## Notes
This element updates by changing the texture.
## Options
.useAtlasSize - Makes the element use preprogrammed atlas' size instead of its set dimensions (boolean)
## Examples
-- Position and size
local PvPClassificationIndicator = self:CreateTexture(nil, 'OVERLAY')
PvPClassificationIndicator:SetSize(24, 24)
PvPClassificationIndicator:SetPoint('CENTER')
-- Register it with oUF
self.PvPClassificationIndicator = PvPClassificationIndicator
--]]
local _, ns = ...
local oUF = ns.oUF
-- sourced from FrameXML/CompactUnitFrame.lua
local ICONS = {
[Enum.PvpUnitClassification.FlagCarrierHorde or 0] = "nameplates-icon-flag-horde",
[Enum.PvpUnitClassification.FlagCarrierAlliance or 1] = "nameplates-icon-flag-alliance",
[Enum.PvpUnitClassification.FlagCarrierNeutral or 2] = "nameplates-icon-flag-neutral",
[Enum.PvpUnitClassification.CartRunnerHorde or 3] = "nameplates-icon-cart-horde",
[Enum.PvpUnitClassification.CartRunnerAlliance or 4] = "nameplates-icon-cart-alliance",
[Enum.PvpUnitClassification.AssassinHorde or 5] = "nameplates-icon-bounty-horde",
[Enum.PvpUnitClassification.AssassinAlliance or 6] = "nameplates-icon-bounty-alliance",
[Enum.PvpUnitClassification.OrbCarrierBlue or 7] = "nameplates-icon-orb-blue",
[Enum.PvpUnitClassification.OrbCarrierGreen or 8] = "nameplates-icon-orb-green",
[Enum.PvpUnitClassification.OrbCarrierOrange or 9] = "nameplates-icon-orb-orange",
[Enum.PvpUnitClassification.OrbCarrierPurple or 10] = "nameplates-icon-orb-purple",
}
local function Update(self, event, unit)
if(unit ~= self.unit) then return end
local element = self.PvPClassificationIndicator
--[[ Callback: PvPClassificationIndicator:PreUpdate(unit)
Called before the element has been updated.
* self - the PvPClassificationIndicator element
* unit - the unit for which the update has been triggered (string)
--]]
if(element.PreUpdate) then
element:PreUpdate(unit)
end
local class = UnitPvpClassification(unit)
local icon = ICONS[class]
if(icon) then
element:SetAtlas(icon, element.useAtlasSize)
element:Show()
else
element:Hide()
end
--[[ Callback: PvPClassificationIndicator:PostUpdate(unit, class)
Called after the element has been updated.
* self - the PvPClassificationIndicator element
* unit - the unit for which the update has been triggered (string)
* class - the pvp classification of the unit (number?)
--]]
if(element.PostUpdate) then
return element:PostUpdate(unit, class)
end
end
local function Path(self, ...)
--[[Override: PvPClassificationIndicator.Override(self, event, ...)
Used to completely override the internal update function.
* self - the parent object
* event - the event triggering the update (string)
* ... - the arguments accompanying the event
--]]
return (self.PvPClassificationIndicator.Override or Update) (self, ...)
end
local function ForceUpdate(element)
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
end
local function Enable(self)
local element = self.PvPClassificationIndicator
if(element) then
element.__owner = self
element.ForceUpdate = ForceUpdate
self:RegisterEvent('UNIT_CLASSIFICATION_CHANGED', Path)
return true
end
end
local function Disable(self)
local element = self.PvPClassificationIndicator
if(element) then
element:Hide()
self:UnregisterEvent('UNIT_CLASSIFICATION_CHANGED', Path)
end
end
oUF:AddElement('PvPClassificationIndicator', Path, Enable, Disable)
| mit |
Anarchid/Zero-K | scripts/pw_techlab.lua | 8 | 2577 | include 'constants.lua'
local base = piece "base"
local wheel1 = piece "wheel1"
local wheel2 = piece "wheel2"
local slider = piece "slider"
local sliderturret = piece "sliderturret"
local armabase = piece "armabase"
local armbbase = piece "armbbase"
local armcbase = piece "armcbase"
local armdbase = piece "armdbase"
local armebase = piece "armebase"
local armfbase = piece "armfbase"
local arma = piece "arma"
local armb = piece "armb"
local armc = piece "armc"
local armd = piece "armd"
local arme = piece "arme"
local armf = piece "armf"
local armapick = piece "armapick"
local armbpick = piece "armdpick"
local armcpick = piece "armcpick"
local armdpick = piece "armdpick"
local armepick = piece "armepick"
local armfpick = piece "armfpick"
local anglea = -0.05
local angleb = -0.08
local anglec = -0.1
local speeda = 0.3
local speedb = 0.5
local function armmove(piece1, piece2, piece3)
while(true) do
Turn(piece1, z_axis, anglea, speeda)
Turn(piece2, z_axis, angleb, speeda)
Turn(piece3, z_axis, anglec, speeda)
WaitForTurn(piece1, z_axis)
WaitForTurn(piece2, z_axis)
WaitForTurn(piece3, z_axis)
Turn(piece1, z_axis, anglea, speedb)
Turn(piece2, z_axis, angleb, speedb)
Turn(piece3, z_axis, anglec, speedb)
WaitForTurn(piece1, z_axis)
WaitForTurn(piece2, z_axis)
WaitForTurn(piece3, z_axis)
Turn(piece1, z_axis, 0, speedb)
Turn(piece2, z_axis, 0, speedb)
Turn(piece3, z_axis, 0, speedb)
Sleep (math.random(200,2000))
end
end
local function moveslider()
while(true) do
Move(slider, z_axis, math.random(-5.8,5.8)*5.8, 10)
WaitForMove(slider, z_axis)
Sleep (50)
end
end
function script.Create()
if Spring.GetUnitRulesParam(unitID, "planetwarsDisable") == 1 or GG.applyPlanetwarsDisable then
return
end
StartThread(armmove, armabase, arma, armapick)
StartThread(armmove, armbbase, armb, armbpick)
StartThread(armmove, armcbase, armc, armcpick)
StartThread(armmove, armdbase, armd, armdpick)
StartThread(armmove, armebase, arme, armepick)
StartThread(armmove, armfbase, armf, armfpick)
StartThread(moveslider)
Spin(sliderturret, y_axis, 2, 0.2)
Spin(wheel1, x_axis, 0.5, 0.01)
Spin(wheel2, x_axis, -0.5, 0.01)
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity < .5 then
Explode(base, SFX.NONE)
Explode(sliderturret, SFX.NONE)
Explode(slider, SFX.NONE)
return 1
else
Explode(base, SFX.SHATTER)
--Explode(sliderturret, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(sliderturret, SFX.SHATTER)
Explode(slider, SFX.FALL)
return 2
end
end
| gpl-2.0 |
wesnoth/wesnoth | data/ai/micro_ais/mai-defs/recruiting.lua | 4 | 1340 | local function handle_default_recruitment(cfg)
-- Also need to delete/add the default recruitment CA
if cfg.action == 'add' then
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[recruitment]")
elseif cfg.action == 'delete' then
-- We need to add the recruitment CA back in
-- This works even if it was not removed, it simply overwrites the existing CA
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="recruitment",
engine="cpp",
name="ai_default_rca::aspect_recruitment_phase",
max_score=180000,
score=180000
}
)
end
end
function wesnoth.micro_ais.recruit_rushers(cfg)
local optional_keys = { high_level_fraction = 'float', randomness = 'float' }
local CA_parms = {
ai_id = 'mai_rusher_recruit',
{ ca_id = "move", location = '../../lua/ca_recruit_rushers.lua', score = cfg.ca_score or 180000 }
}
handle_default_recruitment(cfg)
return {}, optional_keys, CA_parms
end
function wesnoth.micro_ais.recruit_random(cfg)
local optional_keys = { skip_low_gold_recruiting = 'boolean', probability = 'tag' }
local CA_parms = {
ai_id = 'mai_random_recruit',
{ ca_id = "move", location = 'ca_recruit_random.lua', score = cfg.ca_score or 180000 }
}
handle_default_recruitment(cfg)
return {}, optional_keys, CA_parms
end
| gpl-2.0 |
Anarchid/Zero-K | gamedata/buildoptions.lua | 6 | 1135 | local buildOpts = {
[[staticmex]],
[[energysolar]],
[[energyfusion]],
[[energysingu]],
[[energywind]],
[[energygeo]],
[[staticstorage]],
[[energypylon]],
[[staticcon]],
[[staticrearm]],
[[factoryshield]],
[[factorycloak]],
[[factoryveh]],
[[factoryplane]],
[[factorygunship]],
[[factoryhover]],
[[factoryamph]],
[[factoryspider]],
[[factoryjump]],
[[factorytank]],
[[factoryship]],
[[plateshield]],
[[platecloak]],
[[plateveh]],
[[plateplane]],
[[plategunship]],
[[platehover]],
[[plateamph]],
[[platespider]],
[[platejump]],
[[platetank]],
[[plateship]],
[[striderhub]],
[[staticradar]],
[[staticheavyradar]],
[[staticshield]],
[[staticjammer]],
[[turretmissile]],
[[turretlaser]],
[[turretimpulse]],
[[turretemp]],
[[turretriot]],
[[turretheavylaser]],
[[turretgauss]],
[[turretantiheavy]],
[[turretheavy]],
[[turrettorp]],
[[turretaalaser]],
[[turretaaclose]],
[[turretaafar]],
[[turretaaflak]],
[[turretaaheavy]],
[[staticantinuke]],
[[staticarty]],
[[staticheavyarty]],
[[staticmissilesilo]],
[[staticnuke]],
[[mahlazer]],
[[raveparty]],
[[zenith]],
}
return buildOpts
| gpl-2.0 |
erfan1292/1234 | plugins/lock-forward.lua | 18 | 1291 | do
local function pre_process(msg)
local hash = 'mate:'..msg.to.id
if redis:get(hash) and msg.fwd_from and not is_momod(msg) then
channel_kick_user('channel#id'..msg.to.id,'user#id'..msg.from.id, ok_cb, false)
return "forward has been locked"
end
return msg
end
local function run(msg, matches)
channel_id = msg.to.id
if matches[1] == 'lock' and is_momod(msg) then
local hash = 'mate:'..msg.to.id
redis:set(hash, true)
return "Forward has been locked"
elseif matches[1] == 'unlock' and is_momod(msg) then
local hash = 'mate:'..msg.to.id
redis:del(hash)
return "Forward has been unlocked"
end
if matches[1] == 'status' then
local hash = 'mate:'..msg.to.id
if redis:get(hash) then
return "forward is locked"
else
return "forward is not locked"
end
end
end
return {
patterns = {
'^[/!#](lock) forward$',
'^[/!#](unlock) forward$',
'^[/!#]forward (status)$',
},
run = run,
pre_process = pre_process
}
end
--fix for channel by @WaderTGTeam
--Tnx to WaderTG Team
| gpl-2.0 |
alireza1998/supergroup | plugins/media.lua | 297 | 1590 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
selfighter/cardpeek | dot_cardpeek_dir/scripts/calypso/c250n502.lua | 17 | 4335 | --
-- This file is part of Cardpeek, the smartcard reader utility.
--
-- Copyright 2009 by 'L1L1' and 2013-2014 by 'kalon33'
--
-- Cardpeek is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Cardpeek is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Cardpeek. If not, see <http://www.gnu.org/licenses/>.
--
---------------------------------------------------------------------
-- Most of the data and coding ideas in this file
-- was contributed by 'Pascal Terjan', based on location
-- data from 'Nicolas Derive'.
---------------------------------------------------------------------
require('lib.strict')
require('etc.grenoble-tag_stops')
require('etc.grenoble-tag_lines')
SERVICE_PROVIDERS = {
[3] = "TAG"
}
TRANSPORT_LIST = {
[1] = "Tram"
}
TRANSITION_LIST = {
[1] = "Entry",
[2] = "Exit",
[4] = "Inspection",
[6] = "Interchange (entry)",
[7] = "Interchange (exit)"
}
function navigo_process_events(ctx)
local EVENTS
local RECORD
local REF
local rec_index
local code_value
local code_transport
local code_transition
local code_transport_string
local code_transition_string
local code_string
local service_provider_value
local location_id_value
local route_number_value
local route_string
local sector_id
local station_id
local location_string
EVENTS = ui.tree_find_node(ctx,"Event logs, parsed");
if EVENTS==nil then
log.print(log.WARNING,"No event found in card")
return 0
end
for rec_index=1,16 do
RECORD = ui.tree_find_node(EVENTS,"record",rec_index)
if RECORD==nil then break end
REF = ui.tree_find_node(RECORD,"EventServiceProvider")
service_provider_value = bytes.tonumber(ui.tree_get_value(REF))
ui.tree_set_alt_value(REF,SERVICE_PROVIDERS[service_provider_value])
REF = ui.tree_find_node(RECORD,"EventCode")
code_value = bytes.tonumber(ui.tree_get_value(REF))
code_transport = bit.SHR(code_value,4)
code_transport_string = TRANSPORT_LIST[code_transport]
if code_transport_string==nil then code_transport_string = code_transport end
code_transition = bit.AND(code_value,0xF)
code_transition_string = TRANSITION_LIST[code_transition]
if (code_transition_string==nil) then code_transition_string = code_transition end
ui.tree_set_alt_value(REF,code_transport_string.." - "..code_transition_string)
if service_provider_value == 3 and code_transport <=1 then
REF = ui.tree_find_node(RECORD,"EventLocationId")
location_id_value = bytes.tonumber(ui.tree_get_value(REF))
-- sector_id = bit.SHR(location_id_value,9)
-- station_id = bit.AND(bit.SHR(location_id_value,4),0x1F)
-- if STOPS_LIST[sector_id]~=nil then
-- location_string = "secteur "..STOPS_LIST[sector_id]['name'].." - station "
-- if STOPS_LIST[sector_id][station_id]==nil then
-- location_string = location_string .. station_id
-- else
-- location_string = location_string .. STOPS_LIST[sector_id][station_id]
-- end
-- else
-- location_string = "secteur "..sector_id.." - station "..station_id
-- end
-- end
if STOPS_LIST[location_id_value]~=nil then
location_string = STOPS_LIST[location_id_value]
else
location_string = location_id_value
end
ui.tree_set_alt_value(REF,location_string)
REF = ui.tree_find_node(RECORD,"EventRouteNumber")
route_number_value = bytes.tonumber(ui.tree_get_value(REF))
if LINES_LIST[route_number_value]["name"] then
route_string = LINES_LIST[route_number_value]["name"]
else
-- route_string = route_number_value
route_string = LINES_LIST[route_number_value]["name"]
end
ui.tree_set_alt_value(REF,route_string)
end
end
end
navigo_process_events(CARD)
| gpl-3.0 |
LORgames/premake-core | modules/vstudio/tests/cs2005/test_output_props.lua | 14 | 1371 | --
-- tests/actions/vstudio/cs2005/test_output_props.lua
-- Test the target output settings of a Visual Studio 2005+ C# project.
-- Copyright (c) 2012-2013 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("vstudio_cs2005_output_props")
local dn2005 = p.vstudio.dotnetbase
local project = p.project
--
-- Setup and teardown
--
local wks, prj
function suite.setup()
p.action.set("vs2005")
wks, prj = test.createWorkspace()
language "C#"
end
local function prepare()
local cfg = test.getconfig(prj, "Debug")
dn2005.outputProps(cfg)
end
--
-- Check handling of the output directory.
--
function suite.outputDirectory_onTargetDir()
targetdir "../build"
prepare()
test.capture [[
<OutputPath>..\build\</OutputPath>
]]
end
--
-- Check handling of the intermediates directory.
--
function suite.intermediateDirectory_onVs2008()
p.action.set("vs2008")
prepare()
test.capture [[
<OutputPath>bin\Debug\</OutputPath>
<IntermediateOutputPath>obj\Debug\</IntermediateOutputPath>
]]
end
function suite.intermediateDirectory_onVs2010()
p.action.set("vs2010")
prepare()
test.capture [[
<OutputPath>bin\Debug\</OutputPath>
<BaseIntermediateOutputPath>obj\Debug\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath>
]]
end
| bsd-3-clause |
Em30-tm-lua/team | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
AndyBursh/Factorio-Stdlib | stdlib/area/area.lua | 4 | 8419 | --- Area module
-- @module Area
require 'stdlib/core'
require 'stdlib/area/position'
Area = {}
--- Creates an area from the 2 positions p1 and p2
-- @param x1 x-position of left_top, first point
-- @param y1 y-position of left_top, first point
-- @param x2 x-position of right_bottom, second point
-- @param y2 y-position of right_bottom, second point
-- @return Area tabled area
function Area.construct(x1, y1, x2, y2)
return { left_top = Position.construct(x1, y1), right_bottom = Position.construct(x2, y2) }
end
--- Returns the size of the space contained in the 2d area </br>
-- <b>Deprecated</b>, Area.area is misleading. See: Area.size
-- @param area the area
-- @return size of the area
function Area.area(area)
return Area.size(area)
end
--- Returns the size of the space contained in the 2d area
-- @param area the area
-- @return size of the area
function Area.size(area)
fail_if_missing(area, "missing area value")
area = Area.to_table(area)
local left_top = Position.to_table(area.left_top)
local right_bottom = Position.to_table(area.right_bottom)
local dx = math.abs(left_top.x - right_bottom.x)
local dy = math.abs(left_top.y - right_bottom.y)
return dx * dy
end
--- Tests if a position {x, y} is inside (inclusive) of area
-- @param area the area
-- @param pos the position to check
-- @return true if the position is inside of the area
function Area.inside(area, pos)
fail_if_missing(pos, "missing pos value")
fail_if_missing(area, "missing area value")
pos = Position.to_table(pos)
area = Area.to_table(area)
local left_top = Position.to_table(area.left_top)
local right_bottom = Position.to_table(area.right_bottom)
return pos.x >= left_top.x and pos.y >= left_top.y and pos.x <= right_bottom.x and pos.y <= right_bottom.y
end
--- Shrinks the size of an area by the given amount
-- @param area the area
-- @param amount to shrink each edge of the area inwards by
-- @return the shrunk area
function Area.shrink(area, amount)
fail_if_missing(area, "missing area value")
fail_if_missing(amount, "missing amount value")
if amount < 0 then error("Can not shrunk area by a negative amount (see Area.expand)!", 2) end
area = Area.to_table(area)
local left_top = Position.to_table(area.left_top)
local right_bottom = Position.to_table(area.right_bottom)
return {left_top = {x = left_top.x + amount, y = left_top.y + amount}, right_bottom = {x = right_bottom.x - amount, y = right_bottom.y - amount}}
end
--- Expands the size of an area by the given amount
-- @param area the area
-- @param amount to expand each edge of the area outwards by
-- @return the expanded area
function Area.expand(area, amount)
fail_if_missing(area, "missing area value")
fail_if_missing(amount, "missing amount value")
if amount < 0 then error("Can not expand area by a negative amount (see Area.shrink)!", 2) end
area = Area.to_table(area)
local left_top = Position.to_table(area.left_top)
local right_bottom = Position.to_table(area.right_bottom)
return {left_top = {x = left_top.x - amount, y = left_top.y - amount}, right_bottom = {x = right_bottom.x + amount, y = right_bottom.y + amount}}
end
--- Calculates the center of the area and returns the position
-- @param area the area
-- @return area to find the center for
function Area.center(area)
fail_if_missing(area, "missing area value")
area = Area.to_table(area)
local dist_x = area.right_bottom.x - area.left_top.x
local dist_y = area.right_bottom.y - area.left_top.y
return {x = area.left_top.x + (dist_x / 2), y = area.left_top.y + (dist_y / 2)}
end
--- Offsets the area by the {x, y} values
-- @param area the area
-- @param pos the {x, y} amount to offset the area
-- @return offset area by the position values
function Area.offset(area, pos)
fail_if_missing(area, "missing area value")
fail_if_missing(pos, "missing pos value")
area = Area.to_table(area)
return {left_top = Position.add(area.left_top, pos), right_bottom = Position.add(area.right_bottom, pos)}
end
--- Converts an area to the integer representation, by taking the floor of the left_top and the ceiling of the right_bottom
-- @param area the area
-- @return the rounded integer representation
function Area.round_to_integer(area)
fail_if_missing(area, "missing area value")
area = Area.to_table(area)
local left_top = Position.to_table(area.left_top)
local right_bottom = Position.to_table(area.right_bottom)
return {left_top = {x = math.floor(left_top.x), y = math.floor(left_top.y)},
right_bottom = {x = math.ceil(right_bottom.x), y = math.ceil(right_bottom.y)}}
end
--- Iterates an area.
-- @usage
---for x,y in Area.iterate({{0, -5}, {3, -3}}) do
-----...
---end
-- @param area the area
-- @return iterator
function Area.iterate(area)
fail_if_missing(area, "missing area value")
local iterator = {idx = 0}
function iterator.iterate(area)
local rx = area.right_bottom.x - area.left_top.x + 1
local dx = iterator.idx % rx
local dy = math.floor(iterator.idx / rx)
iterator.idx = iterator.idx + 1
if (area.left_top.y + dy) > area.right_bottom.y then
return
end
return (area.left_top.x + dx), (area.left_top.y + dy)
end
return iterator.iterate, Area.to_table(area), 0
end
--- Iterates an area in a spiral inner-most to outer-most fashion.
---<p><i>Example:</i></p>
---<pre>
---for x, y in Area.spiral_iterate({{-2, -1}, {2, 1}}) do
---- print("(" .. x .. ", " .. y .. ")")
---end
--- prints: (0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1) (2, -1) (2, 0) (2, 1) (-2, 1) (-2, 0) (-2, -1)
---</pre>
-- iterates in the order depicted:<br/>
-- 
-- @param area the area
-- @return iterator
function Area.spiral_iterate(area)
fail_if_missing(area, "missing area value")
area = Area.to_table(area)
local rx = area.right_bottom.x - area.left_top.x + 1
local ry = area.right_bottom.y - area.left_top.y + 1
local half_x = math.floor(rx / 2)
local half_y = math.floor(ry / 2)
local center_x = area.left_top.x + half_x
local center_y = area.left_top.y + half_y
local x = 0
local y = 0
local dx = 0
local dy = -1
local iterator = {list = {}, idx = 1}
for i = 1, math.max(rx, ry) * math.max(rx, ry) do
if -(half_x) <= x and x <= half_x and -(half_y) <= y and y <= half_y then
table.insert(iterator.list, {x, y})
end
if x == y or (x < 0 and x == -y) or (x > 0 and x == 1 - y) then
local temp = dx
dx = -(dy)
dy = temp
end
x = x + dx
y = y + dy
end
function iterator.iterate(area)
if #iterator.list < iterator.idx then return end
local x, y = unpack(iterator.list[iterator.idx])
iterator.idx = iterator.idx + 1
return (center_x + x), (center_y + y)
end
return iterator.iterate, Area.to_table(area), 0
end
--- Creates a new area, a modified copy of the original, such that left and right x, up and down y are normalized, where left.x < right.x, left.y < right.y order
-- @param area the area to adjust
-- @return a adjusted area, always { left_top = {x = ..., y = ...}, right_bottom = {x = ..., y = ...} }
function Area.adjust(area)
fail_if_missing(area, "missing area value")
area = Area.to_table(area)
local left_top = Position.copy(area.left_top)
local right_bottom = Position.copy(area.right_bottom)
if right_bottom.x < left_top.x then
local x = left_top.x
left_top.x = right_bottom.x
right_bottom.x = x
end
if right_bottom.y < left_top.y then
local y = left_top.y
left_top.y = right_bottom.y
right_bottom.y = y
end
return Area.construct(left_top.x, left_top.y, right_bottom.x, right_bottom.y)
end
--- Converts an area in the array format to an array in the table format
-- @param area_arr the area to convert
-- @return a converted area, { left_top = area_arr[1], right_bottom = area_arr[2] }
function Area.to_table(area_arr)
fail_if_missing(area_arr, "missing area value")
if #area_arr == 2 then
return { left_top = Position.to_table(area_arr[1]), right_bottom = Position.to_table(area_arr[2]) }
end
return area_arr
end
return Area
| isc |
imashkan/ABCYAGOP | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
delram/yago | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
Wiladams/lj2procfs | lj2procfs/string-util.lua | 2 | 3822 | --string-util.lua
local ffi = require("ffi")
local fun = require("lj2procfs.fun")
local floor = math.floor;
local F = {}
function F.startswith(s, prefix)
return string.find(s, prefix, 1, true) == 1
end
-- returns true if string 's' ends with string 'send'
function F.endswith(s, send)
return #s >= #send and string.find(s, send, #s-#send+1, true) and true or false
end
local function gsplit(s,sep)
--print('gsplit: ', #sep, string.byte(sep[0]))
return coroutine.wrap(function()
if s == '' or sep == '' then coroutine.yield(s) return end
local lasti = 1
for v,i in s:gmatch('(.-)'..sep..'()') do
coroutine.yield(v)
lasti = i
end
coroutine.yield(s:sub(lasti))
end)
end
local function iunpack(i,s,v1)
local function pass(...)
local v1 = i(s,v1)
if v1 == nil then return ... end
return v1, pass(...)
end
return pass()
end
function F.split(s,sep)
return iunpack(gsplit(s,sep))
end
local function accumulate(t,i,s,v)
for v in i,s,v do
t[#t+1] = v
end
return t
end
function F.tsplit(s,sep)
return accumulate({}, gsplit(s,sep))
end
function F.tsplitbool(s, sep)
local tbl={}
for v in gsplit(s,sep) do
tbl[v] = true;
end
return tbl
end
function F.trim(s)
local from = s:match"^%s*()"
return from > #s and "" or s:match(".*%S", from)
end
-- a nil generator.
-- good for cases when there's no data
local function nil_gen(param, state)
return nil
end
local function delim_gen(param, idx)
local len = 0;
while ((idx+len) < param.nelems) do
--print("wchar: ", string.char(ffi.cast(param.basetypeptr, param.data)[idx + len]))
if ffi.cast(param.basetypeptr, param.data)[idx + len] ~= param.separator then
len = len + 1;
else
break
end
end
if len == 0 then
return nil;
end
return idx + len + 1, ffi.cast(param.basetypeptr, param.data)+idx, len
end
local function array_gen(param, idx)
if idx >= param.nelems then
return nil;
end
return idx+1, ffi.cast(param.basetypeptr, param.data)+idx, 1
end
function F.striter(params)
if not params then
return nil_gen, params, nil
end
if not params.data then
return nil_gen, params, nil
end
params.datalength = params.datalength or #params.data
if params.basetype then
if type(params.basetype)== "string" then
params.basetype = ffi.typeof(params.basetype)
end
end
params.basetype = params.basetype or ffi.typeof("char")
params.basetypeptr = ffi.typeof("const $ *", params.basetype)
params.basetypesize = ffi.sizeof(params.basetype)
params.nelems = math.floor(params.datalength / params.basetypesize)
if params.separator ~= nil then
return delim_gen, params, 0
else
return array_gen, params, 0
end
return nil_gen, nil, nil
end
function F.mstriter(data, separator, datalength)
return fun.map(function(ptr,len) return ffi.string(ptr, len) end,
striter({data = data, datalength = datalength, separator=separator, basetype="char"}))
end
-- an iterator over a string, with embedded
-- '\0' bytes delimiting strings
function F.mstrziter(data, datalength)
datalength = datalength or #data
return fun.map(function(ptr,len) return ffi.string(ptr, len) end,
striter({data = data, datalength = datalength, separator=0, basetype="char"}))
end
-- given a unicode string which contains
-- null terminated strings
-- return individual ansi strings
function F.wmstrziter(data, datalength)
local maxLen = 255;
local idx = -1;
local nameBuff = ffi.new("char[256]")
local function closure()
idx = idx + 1;
local len = 0;
while len < maxLen do
print("char: ", string.char(lpBuffer[idx]))
if data[idx] == 0 then
break
end
nameBuff[len] = data[idx];
len = len + 1;
idx = idx + 1;
end
if len == 0 then
return nil;
end
return ffi.string(nameBuff, len);
end
return closure;
end
return F
| mit |
helingping/Urho3D | Source/ThirdParty/LuaJIT/dynasm/dasm_arm64.lua | 33 | 34807 | ------------------------------------------------------------------------------
-- DynASM ARM64 module.
--
-- Copyright (C) 2005-2016 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "arm",
description = "DynASM ARM64 module",
version = "1.4.0",
vernum = 10400,
release = "2015-10-18",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, setmetatable, rawget = assert, setmetatable, rawget
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub
local concat, sort, insert = table.concat, table.sort, table.insert
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local ror, tohex = bit.ror, bit.tohex
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM", "IMM6", "IMM12", "IMM13W", "IMM13X", "IMML",
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
------------------------------------------------------------------------------
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n <= 0x000fffff then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
if n <= 0x000fffff then
insert(actlist, pos+1, n)
n = map_action.ESC * 0x10000
end
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end
local n = next_global
if n > 2047 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=20,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=20,next_global-1 do
out:write(" ", prefix, t[i], ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=20,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
-- Ext. register name -> int. name.
local map_archdef = { xzr = "@x31", wzr = "@w31", lr = "x30", }
-- Int. register name -> ext. name.
local map_reg_rev = { ["@x31"] = "xzr", ["@w31"] = "wzr", x30 = "lr", }
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
return map_reg_rev[s] or s
end
local map_shift = { lsl = 0, lsr = 1, asr = 2, }
local map_extend = {
uxtb = 0, uxth = 1, uxtw = 2, uxtx = 3,
sxtb = 4, sxth = 5, sxtw = 6, sxtx = 7,
}
local map_cond = {
eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7,
hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14,
hs = 2, lo = 3,
}
------------------------------------------------------------------------------
local parse_reg_type
local function parse_reg(expr)
if not expr then werror("expected register name") end
local tname, ovreg = match(expr, "^([%w_]+):(@?%l%d+)$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local ok31, rt, r = match(expr, "^(@?)([xwqdshb])([123]?[0-9])$")
if r then
r = tonumber(r)
if r <= 30 or (r == 31 and ok31 ~= "" or (rt ~= "w" and rt ~= "x")) then
if not parse_reg_type then
parse_reg_type = rt
elseif parse_reg_type ~= rt then
werror("register size mismatch")
end
return r, tp
end
end
werror("bad register name `"..expr.."'")
end
local function parse_reg_base(expr)
if expr == "sp" then return 0x3e0 end
local base, tp = parse_reg(expr)
if parse_reg_type ~= "x" then werror("bad register type") end
parse_reg_type = false
return shl(base, 5), tp
end
local parse_ctx = {}
local loadenv = setfenv and function(s)
local code = loadstring(s, "")
if code then setfenv(code, parse_ctx) end
return code
end or function(s)
return load(s, "", nil, parse_ctx)
end
-- Try to parse simple arithmetic, too, since some basic ops are aliases.
local function parse_number(n)
local x = tonumber(n)
if x then return x end
local code = loadenv("return "..n)
if code then
local ok, y = pcall(code)
if ok then return y end
end
return nil
end
local function parse_imm(imm, bits, shift, scale, signed)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm)
return 0
end
end
local function parse_imm12(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
if shr(n, 12) == 0 then
return shl(n, 10)
elseif band(n, 0xff000fff) == 0 then
return shr(n, 2) + 0x00400000
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM12", 0, imm)
return 0
end
end
local function parse_imm13(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
local r64 = parse_reg_type == "x"
if n and n % 1 == 0 and n >= 0 and n <= 0xffffffff then
local inv = false
if band(n, 1) == 1 then n = bit.bnot(n); inv = true end
local t = {}
for i=1,32 do t[i] = band(n, 1); n = shr(n, 1) end
local b = table.concat(t)
b = b..(r64 and (inv and "1" or "0"):rep(32) or b)
local p0, p1, p0a, p1a = b:match("^(0+)(1+)(0*)(1*)")
if p0 then
local w = p1a == "" and (r64 and 64 or 32) or #p1+#p0a
if band(w, w-1) == 0 and b == b:sub(1, w):rep(64/w) then
local s = band(-2*w, 0x3f) - 1
if w == 64 then s = s + 0x1000 end
if inv then
return shl(w-#p1-#p0, 16) + shl(s+w-#p1, 10)
else
return shl(w-#p0, 16) + shl(s+#p1, 10)
end
end
end
werror("out of range immediate `"..imm.."'")
elseif r64 then
waction("IMM13X", 0, format("(unsigned int)(%s)", imm))
actargs[#actargs+1] = format("(unsigned int)((unsigned long long)(%s)>>32)", imm)
return 0
else
waction("IMM13W", 0, imm)
return 0
end
end
local function parse_imm6(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
if n >= 0 and n <= 63 then
return shl(band(n, 0x1f), 19) + (n >= 32 and 0x80000000 or 0)
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM6", 0, imm)
return 0
end
end
local function parse_imm_load(imm, scale)
local n = parse_number(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n and m >= 0 and m < 0x1000 then
return shl(m, 10) + 0x01000000 -- Scaled, unsigned 12 bit offset.
elseif n >= -256 and n < 256 then
return shl(band(n, 511), 12) -- Unscaled, signed 9 bit offset.
end
werror("out of range immediate `"..imm.."'")
else
waction("IMML", 0, imm)
return 0
end
end
local function parse_fpimm(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
local m, e = math.frexp(n)
local s, e2 = 0, band(e-2, 7)
if m < 0 then m = -m; s = 0x00100000 end
m = m*32-16
if m % 1 == 0 and m >= 0 and m <= 15 and sar(shl(e2, 29), 29)+2 == e then
return s + shl(e2, 17) + shl(m, 13)
end
werror("out of range immediate `"..imm.."'")
else
werror("NYI fpimm action")
end
end
local function parse_shift(expr)
local s, s2 = match(expr, "^(%S+)%s*(.*)$")
s = map_shift[s]
if not s then werror("expected shift operand") end
return parse_imm(s2, 6, 10, 0, false) + shl(s, 22)
end
local function parse_lslx16(expr)
local n = match(expr, "^lsl%s*#(%d+)$")
n = tonumber(n)
if not n then werror("expected shift operand") end
if band(n, parse_reg_type == "x" and 0xffffffcf or 0xffffffef) ~= 0 then
werror("bad shift amount")
end
return shl(n, 17)
end
local function parse_extend(expr)
local s, s2 = match(expr, "^(%S+)%s*(.*)$")
if s == "lsl" then
s = parse_reg_type == "x" and 3 or 2
else
s = map_extend[s]
end
if not s then werror("expected extend operand") end
return (s2 == "" and 0 or parse_imm(s2, 3, 10, 0, false)) + shl(s, 13)
end
local function parse_cond(expr, inv)
local c = map_cond[expr]
if not c then werror("expected condition operand") end
return shl(bit.bxor(c, inv), 12)
end
local function parse_load(params, nparams, n, op)
if params[n+2] then werror("too many operands") end
local pn, p2 = params[n], params[n+1]
local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$")
if not p1 then
if not p2 then
local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local base, tp = parse_reg_base(reg)
if tp then
waction("IMML", 0, format(tp.ctypefmt, tailr))
return op + base
end
end
end
werror("expected address operand")
end
local scale = shr(op, 30)
if p2 then
if wb == "!" then werror("bad use of '!'") end
op = op + parse_reg_base(p1) + parse_imm(p2, 9, 12, 0, true) + 0x400
elseif wb == "!" then
local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$")
if not p1a then werror("bad use of '!'") end
op = op + parse_reg_base(p1a) + parse_imm(p2a, 9, 12, 0, true) + 0xc00
else
local p1a, p2a = match(p1, "^([^,%s]*)%s*(.*)$")
op = op + parse_reg_base(p1a)
if p2a ~= "" then
local imm = match(p2a, "^,%s*#(.*)$")
if imm then
op = op + parse_imm_load(imm, scale)
else
local p2b, p3b, p3s = match(p2a, "^,%s*([^,%s]*)%s*,?%s*(%S*)%s*(.*)$")
op = op + shl(parse_reg(p2b), 16) + 0x00200800
if parse_reg_type ~= "x" and parse_reg_type ~= "w" then
werror("bad index register type")
end
if p3b == "" then
if parse_reg_type ~= "x" then werror("bad index register type") end
op = op + 0x6000
else
if p3s == "" or p3s == "#0" then
elseif p3s == "#"..scale then
op = op + 0x1000
else
werror("bad scale")
end
if parse_reg_type == "x" then
if p3b == "lsl" and p3s ~= "" then op = op + 0x6000
elseif p3b == "sxtx" then op = op + 0xe000
else
werror("bad extend/shift specifier")
end
else
if p3b == "uxtw" then op = op + 0x4000
elseif p3b == "sxtw" then op = op + 0xc000
else
werror("bad extend/shift specifier")
end
end
end
end
else
if wb == "!" then werror("bad use of '!'") end
op = op + 0x01000000
end
end
return op
end
local function parse_load_pair(params, nparams, n, op)
if params[n+2] then werror("too many operands") end
local pn, p2 = params[n], params[n+1]
local scale = shr(op, 30) == 0 and 2 or 3
local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$")
if not p1 then
if not p2 then
local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local base, tp = parse_reg_base(reg)
if tp then
waction("IMM", 32768+7*32+15+scale*1024, format(tp.ctypefmt, tailr))
return op + base + 0x01000000
end
end
end
werror("expected address operand")
end
if p2 then
if wb == "!" then werror("bad use of '!'") end
op = op + 0x00800000
else
local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$")
if p1a then p1, p2 = p1a, p2a else p2 = "#0" end
op = op + (wb == "!" and 0x01800000 or 0x01000000)
end
return op + parse_reg_base(p1) + parse_imm(p2, 7, 15, scale, true)
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
local function branch_type(op)
if band(op, 0x7c000000) == 0x14000000 then return 0 -- B, BL
elseif shr(op, 24) == 0x54 or band(op, 0x7e000000) == 0x34000000 or
band(op, 0x3b000000) == 0x18000000 then
return 0x800 -- B.cond, CBZ, CBNZ, LDR* literal
elseif band(op, 0x7e000000) == 0x36000000 then return 0x1000 -- TBZ, TBNZ
elseif band(op, 0x9f000000) == 0x10000000 then return 0x2000 -- ADR
elseif band(op, 0x9f000000) == band(0x90000000) then return 0x3000 -- ADRP
else
assert(false, "unknown branch type")
end
end
------------------------------------------------------------------------------
local map_op, op_template
local function op_alias(opname, f)
return function(params, nparams)
if not params then return "-> "..opname:sub(1, -3) end
f(params, nparams)
op_template(params, map_op[opname], nparams)
end
end
local function alias_bfx(p)
p[4] = "#("..p[3]:sub(2)..")+("..p[4]:sub(2)..")-1"
end
local function alias_bfiz(p)
parse_reg(p[1])
if parse_reg_type == "w" then
p[3] = "#-("..p[3]:sub(2)..")%32"
p[4] = "#("..p[4]:sub(2)..")-1"
else
p[3] = "#-("..p[3]:sub(2)..")%64"
p[4] = "#("..p[4]:sub(2)..")-1"
end
end
local alias_lslimm = op_alias("ubfm_4", function(p)
parse_reg(p[1])
local sh = p[3]:sub(2)
if parse_reg_type == "w" then
p[3] = "#-("..sh..")%32"
p[4] = "#31-("..sh..")"
else
p[3] = "#-("..sh..")%64"
p[4] = "#63-("..sh..")"
end
end)
-- Template strings for ARM instructions.
map_op = {
-- Basic data processing instructions.
add_3 = "0b000000DNMg|11000000pDpNIg|8b206000pDpNMx",
add_4 = "0b000000DNMSg|0b200000DNMXg|8b200000pDpNMXx|8b200000pDpNxMwX",
adds_3 = "2b000000DNMg|31000000DpNIg|ab206000DpNMx",
adds_4 = "2b000000DNMSg|2b200000DNMXg|ab200000DpNMXx|ab200000DpNxMwX",
cmn_2 = "2b00001fNMg|3100001fpNIg|ab20601fpNMx",
cmn_3 = "2b00001fNMSg|2b20001fNMXg|ab20001fpNMXx|ab20001fpNxMwX",
sub_3 = "4b000000DNMg|51000000pDpNIg|cb206000pDpNMx",
sub_4 = "4b000000DNMSg|4b200000DNMXg|cb200000pDpNMXx|cb200000pDpNxMwX",
subs_3 = "6b000000DNMg|71000000DpNIg|eb206000DpNMx",
subs_4 = "6b000000DNMSg|6b200000DNMXg|eb200000DpNMXx|eb200000DpNxMwX",
cmp_2 = "6b00001fNMg|7100001fpNIg|eb20601fpNMx",
cmp_3 = "6b00001fNMSg|6b20001fNMXg|eb20001fpNMXx|eb20001fpNxMwX",
neg_2 = "4b0003e0DMg",
neg_3 = "4b0003e0DMSg",
negs_2 = "6b0003e0DMg",
negs_3 = "6b0003e0DMSg",
adc_3 = "1a000000DNMg",
adcs_3 = "3a000000DNMg",
sbc_3 = "5a000000DNMg",
sbcs_3 = "7a000000DNMg",
ngc_2 = "5a0003e0DMg",
ngcs_2 = "7a0003e0DMg",
and_3 = "0a000000DNMg|12000000pDNig",
and_4 = "0a000000DNMSg",
orr_3 = "2a000000DNMg|32000000pDNig",
orr_4 = "2a000000DNMSg",
eor_3 = "4a000000DNMg|52000000pDNig",
eor_4 = "4a000000DNMSg",
ands_3 = "6a000000DNMg|72000000DNig",
ands_4 = "6a000000DNMSg",
tst_2 = "6a00001fNMg|7200001fNig",
tst_3 = "6a00001fNMSg",
bic_3 = "0a200000DNMg",
bic_4 = "0a200000DNMSg",
orn_3 = "2a200000DNMg",
orn_4 = "2a200000DNMSg",
eon_3 = "4a200000DNMg",
eon_4 = "4a200000DNMSg",
bics_3 = "6a200000DNMg",
bics_4 = "6a200000DNMSg",
movn_2 = "12800000DWg",
movn_3 = "12800000DWRg",
movz_2 = "52800000DWg",
movz_3 = "52800000DWRg",
movk_2 = "72800000DWg",
movk_3 = "72800000DWRg",
-- TODO: this doesn't cover all valid immediates for mov reg, #imm.
mov_2 = "2a0003e0DMg|52800000DW|320003e0pDig|11000000pDpNg",
mov_3 = "2a0003e0DMSg",
mvn_2 = "2a2003e0DMg",
mvn_3 = "2a2003e0DMSg",
adr_2 = "10000000DBx",
adrp_2 = "90000000DBx",
csel_4 = "1a800000DNMCg",
csinc_4 = "1a800400DNMCg",
csinv_4 = "5a800000DNMCg",
csneg_4 = "5a800400DNMCg",
cset_2 = "1a9f07e0Dcg",
csetm_2 = "5a9f03e0Dcg",
cinc_3 = "1a800400DNmcg",
cinv_3 = "5a800000DNmcg",
cneg_3 = "5a800400DNmcg",
ccmn_4 = "3a400000NMVCg|3a400800N5VCg",
ccmp_4 = "7a400000NMVCg|7a400800N5VCg",
madd_4 = "1b000000DNMAg",
msub_4 = "1b008000DNMAg",
mul_3 = "1b007c00DNMg",
mneg_3 = "1b00fc00DNMg",
smaddl_4 = "9b200000DxNMwAx",
smsubl_4 = "9b208000DxNMwAx",
smull_3 = "9b207c00DxNMw",
smnegl_3 = "9b20fc00DxNMw",
smulh_3 = "9b407c00DNMx",
umaddl_4 = "9ba00000DxNMwAx",
umsubl_4 = "9ba08000DxNMwAx",
umull_3 = "9ba07c00DxNMw",
umnegl_3 = "9ba0fc00DxNMw",
umulh_3 = "9bc07c00DNMx",
udiv_3 = "1ac00800DNMg",
sdiv_3 = "1ac00c00DNMg",
-- Bit operations.
sbfm_4 = "13000000DN12w|93400000DN12x",
bfm_4 = "33000000DN12w|b3400000DN12x",
ubfm_4 = "53000000DN12w|d3400000DN12x",
extr_4 = "13800000DNM2w|93c00000DNM2x",
sxtb_2 = "13001c00DNw|93401c00DNx",
sxth_2 = "13003c00DNw|93403c00DNx",
sxtw_2 = "93407c00DxNw",
uxtb_2 = "53001c00DNw",
uxth_2 = "53003c00DNw",
sbfx_4 = op_alias("sbfm_4", alias_bfx),
bfxil_4 = op_alias("bfm_4", alias_bfx),
ubfx_4 = op_alias("ubfm_4", alias_bfx),
sbfiz_4 = op_alias("sbfm_4", alias_bfiz),
bfi_4 = op_alias("bfm_4", alias_bfiz),
ubfiz_4 = op_alias("ubfm_4", alias_bfiz),
lsl_3 = function(params, nparams)
if params and params[3]:byte() == 35 then
return alias_lslimm(params, nparams)
else
return op_template(params, "1ac02000DNMg", nparams)
end
end,
lsr_3 = "1ac02400DNMg|53007c00DN1w|d340fc00DN1x",
asr_3 = "1ac02800DNMg|13007c00DN1w|9340fc00DN1x",
ror_3 = "1ac02c00DNMg|13800000DNm2w|93c00000DNm2x",
clz_2 = "5ac01000DNg",
cls_2 = "5ac01400DNg",
rbit_2 = "5ac00000DNg",
rev_2 = "5ac00800DNw|dac00c00DNx",
rev16_2 = "5ac00400DNg",
rev32_2 = "dac00800DNx",
-- Loads and stores.
["strb_*"] = "38000000DwL",
["ldrb_*"] = "38400000DwL",
["ldrsb_*"] = "38c00000DwL|38800000DxL",
["strh_*"] = "78000000DwL",
["ldrh_*"] = "78400000DwL",
["ldrsh_*"] = "78c00000DwL|78800000DxL",
["str_*"] = "b8000000DwL|f8000000DxL|bc000000DsL|fc000000DdL",
["ldr_*"] = "18000000DwB|58000000DxB|1c000000DsB|5c000000DdB|b8400000DwL|f8400000DxL|bc400000DsL|fc400000DdL",
["ldrsw_*"] = "98000000DxB|b8800000DxL",
-- NOTE: ldur etc. are handled by ldr et al.
["stp_*"] = "28000000DAwP|a8000000DAxP|2c000000DAsP|6c000000DAdP",
["ldp_*"] = "28400000DAwP|a8400000DAxP|2c400000DAsP|6c400000DAdP",
["ldpsw_*"] = "68400000DAxP",
-- Branches.
b_1 = "14000000B",
bl_1 = "94000000B",
blr_1 = "d63f0000Nx",
br_1 = "d61f0000Nx",
ret_0 = "d65f03c0",
ret_1 = "d65f0000Nx",
-- b.cond is added below.
cbz_2 = "34000000DBg",
cbnz_2 = "35000000DBg",
tbz_3 = "36000000DTBw|36000000DTBx",
tbnz_3 = "37000000DTBw|37000000DTBx",
-- Miscellaneous instructions.
-- TODO: hlt, hvc, smc, svc, eret, dcps[123], drps, mrs, msr
-- TODO: sys, sysl, ic, dc, at, tlbi
-- TODO: hint, yield, wfe, wfi, sev, sevl
-- TODO: clrex, dsb, dmb, isb
nop_0 = "d503201f",
brk_0 = "d4200000",
brk_1 = "d4200000W",
-- Floating point instructions.
fmov_2 = "1e204000DNf|1e260000DwNs|1e270000DsNw|9e660000DxNd|9e670000DdNx|1e201000DFf",
fabs_2 = "1e20c000DNf",
fneg_2 = "1e214000DNf",
fsqrt_2 = "1e21c000DNf",
fcvt_2 = "1e22c000DdNs|1e624000DsNd",
-- TODO: half-precision and fixed-point conversions.
fcvtas_2 = "1e240000DwNs|9e240000DxNs|1e640000DwNd|9e640000DxNd",
fcvtau_2 = "1e250000DwNs|9e250000DxNs|1e650000DwNd|9e650000DxNd",
fcvtms_2 = "1e300000DwNs|9e300000DxNs|1e700000DwNd|9e700000DxNd",
fcvtmu_2 = "1e310000DwNs|9e310000DxNs|1e710000DwNd|9e710000DxNd",
fcvtns_2 = "1e200000DwNs|9e200000DxNs|1e600000DwNd|9e600000DxNd",
fcvtnu_2 = "1e210000DwNs|9e210000DxNs|1e610000DwNd|9e610000DxNd",
fcvtps_2 = "1e280000DwNs|9e280000DxNs|1e680000DwNd|9e680000DxNd",
fcvtpu_2 = "1e290000DwNs|9e290000DxNs|1e690000DwNd|9e690000DxNd",
fcvtzs_2 = "1e380000DwNs|9e380000DxNs|1e780000DwNd|9e780000DxNd",
fcvtzu_2 = "1e390000DwNs|9e390000DxNs|1e790000DwNd|9e790000DxNd",
scvtf_2 = "1e220000DsNw|9e220000DsNx|1e620000DdNw|9e620000DdNx",
ucvtf_2 = "1e230000DsNw|9e230000DsNx|1e630000DdNw|9e630000DdNx",
frintn_2 = "1e244000DNf",
frintp_2 = "1e24c000DNf",
frintm_2 = "1e254000DNf",
frintz_2 = "1e25c000DNf",
frinta_2 = "1e264000DNf",
frintx_2 = "1e274000DNf",
frinti_2 = "1e27c000DNf",
fadd_3 = "1e202800DNMf",
fsub_3 = "1e203800DNMf",
fmul_3 = "1e200800DNMf",
fnmul_3 = "1e208800DNMf",
fdiv_3 = "1e201800DNMf",
fmadd_4 = "1f000000DNMAf",
fmsub_4 = "1f008000DNMAf",
fnmadd_4 = "1f200000DNMAf",
fnmsub_4 = "1f208000DNMAf",
fmax_3 = "1e204800DNMf",
fmaxnm_3 = "1e206800DNMf",
fmin_3 = "1e205800DNMf",
fminnm_3 = "1e207800DNMf",
fcmp_2 = "1e202000NMf|1e202008NZf",
fcmpe_2 = "1e202010NMf|1e202018NZf",
fccmp_4 = "1e200400NMVCf",
fccmpe_4 = "1e200410NMVCf",
fcsel_4 = "1e200c00DNMCf",
-- TODO: crc32*, aes*, sha*, pmull
-- TODO: SIMD instructions.
}
for cond,c in pairs(map_cond) do
map_op["b"..cond.."_1"] = tohex(0x54000000+c).."B"
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
local function parse_template(params, template, nparams, pos)
local op = tonumber(sub(template, 1, 8), 16)
local n = 1
local rtt = {}
parse_reg_type = false
-- Process each character.
for p in gmatch(sub(template, 9), ".") do
local q = params[n]
if p == "D" then
op = op + parse_reg(q); n = n + 1
elseif p == "N" then
op = op + shl(parse_reg(q), 5); n = n + 1
elseif p == "M" then
op = op + shl(parse_reg(q), 16); n = n + 1
elseif p == "A" then
op = op + shl(parse_reg(q), 10); n = n + 1
elseif p == "m" then
op = op + shl(parse_reg(params[n-1]), 16)
elseif p == "p" then
if q == "sp" then params[n] = "@x31" end
elseif p == "g" then
if parse_reg_type == "x" then
op = op + 0x80000000
elseif parse_reg_type ~= "w" then
werror("bad register type")
end
parse_reg_type = false
elseif p == "f" then
if parse_reg_type == "d" then
op = op + 0x00400000
elseif parse_reg_type ~= "s" then
werror("bad register type")
end
parse_reg_type = false
elseif p == "x" or p == "w" or p == "d" or p == "s" then
if parse_reg_type ~= p then
werror("register size mismatch")
end
parse_reg_type = false
elseif p == "L" then
op = parse_load(params, nparams, n, op)
elseif p == "P" then
op = parse_load_pair(params, nparams, n, op)
elseif p == "B" then
local mode, v, s = parse_label(q, false); n = n + 1
local m = branch_type(op)
waction("REL_"..mode, v+m, s, 1)
elseif p == "I" then
op = op + parse_imm12(q); n = n + 1
elseif p == "i" then
op = op + parse_imm13(q); n = n + 1
elseif p == "W" then
op = op + parse_imm(q, 16, 5, 0, false); n = n + 1
elseif p == "T" then
op = op + parse_imm6(q); n = n + 1
elseif p == "1" then
op = op + parse_imm(q, 6, 16, 0, false); n = n + 1
elseif p == "2" then
op = op + parse_imm(q, 6, 10, 0, false); n = n + 1
elseif p == "5" then
op = op + parse_imm(q, 5, 16, 0, false); n = n + 1
elseif p == "V" then
op = op + parse_imm(q, 4, 0, 0, false); n = n + 1
elseif p == "F" then
op = op + parse_fpimm(q); n = n + 1
elseif p == "Z" then
if q ~= "#0" and q ~= "#0.0" then werror("expected zero immediate") end
n = n + 1
elseif p == "S" then
op = op + parse_shift(q); n = n + 1
elseif p == "X" then
op = op + parse_extend(q); n = n + 1
elseif p == "R" then
op = op + parse_lslx16(q); n = n + 1
elseif p == "C" then
op = op + parse_cond(q, 0); n = n + 1
elseif p == "c" then
op = op + parse_cond(q, 1); n = n + 1
else
assert(false)
end
end
wputpos(pos, op)
end
function op_template(params, template, nparams)
if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 3 positions.
if secpos+3 > maxsecpos then wflush() end
local pos = wpos()
local lpos, apos, spos = #actlist, #actargs, secpos
local ok, err
for t in gmatch(template, "[^|]+") do
ok, err = pcall(parse_template, params, t, nparams, pos)
if ok then return end
secpos = spos
actlist[lpos+1] = nil
actlist[lpos+2] = nil
actlist[lpos+3] = nil
actargs[apos+1] = nil
actargs[apos+2] = nil
actargs[apos+3] = nil
end
error(err, 0)
end
map_op[".template__"] = op_template
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1])
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION", num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = map_coreop })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| mit |
Em30-tm-lua/team | libs/redis.lua | 566 | 1214 | local Redis = require 'redis'
local FakeRedis = require 'fakeredis'
local params = {
host = os.getenv('REDIS_HOST') or '127.0.0.1',
port = tonumber(os.getenv('REDIS_PORT') or 6379)
}
local database = os.getenv('REDIS_DB')
local password = os.getenv('REDIS_PASSWORD')
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
else
if password then
redis:auth(password)
end
if database then
redis:select(database)
end
end
return redis
| gpl-2.0 |
satanevil/eski-creed | libs/redis.lua | 566 | 1214 | local Redis = require 'redis'
local FakeRedis = require 'fakeredis'
local params = {
host = os.getenv('REDIS_HOST') or '127.0.0.1',
port = tonumber(os.getenv('REDIS_PORT') or 6379)
}
local database = os.getenv('REDIS_DB')
local password = os.getenv('REDIS_PASSWORD')
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
else
if password then
redis:auth(password)
end
if database then
redis:select(database)
end
end
return redis
| gpl-2.0 |
Anarchid/Zero-K | scripts/cloakarty.lua | 4 | 4230 | include "constants.lua"
local base, waist, dish, torso, center, sidecenter, barrel, flare = piece ('base', 'waist', 'dish', 'torso', 'center', 'sidecenter', 'barrel', 'flare')
local thigh = {piece 'lthigh', piece 'rthigh'}
local knee = {piece 'lknee' , piece 'rknee' }
local shin = {piece 'lshin' , piece 'rshin' }
local ankle = {piece 'lankle', piece 'rankle'}
local heel = {piece 'lheel' , piece 'rheel' }
local toe = {piece 'ltoe' , piece 'rtoe' }
local SIG_Aim = 1
local SIG_Walk = 2
local isAiming = false
-- future-proof running animation against balance tweaks
local runspeed = 1.0 * (UnitDefs[unitDefID].speed / 48)
local function GetSpeedMod()
return (GG.att_MoveChange[unitID] or 1)
end
local function Walk()
for i = 1, 2 do
Turn (thigh[i], y_axis, 0, math.rad(135))
Turn (thigh[i], z_axis, 0, math.rad(135))
Turn (ankle[i], x_axis, 0, math.rad(135))
Turn (ankle[i], z_axis, 0, math.rad(135))
end
Signal(SIG_Walk)
SetSignalMask(SIG_Walk)
local side = 1
while true do
local speedmod = GetSpeedMod()
local truespeed = runspeed * speedmod
Turn (shin[side], x_axis, math.rad(65), math.rad(230)*truespeed)
Turn (ankle[side], x_axis, math.rad(30), math.rad(230)*truespeed)
Turn (thigh[side], x_axis, math.rad(-45), math.rad(135)*truespeed)
Turn (thigh[3-side], x_axis, math.rad(45), math.rad(135)*truespeed)
if not isAiming then
Turn (torso, x_axis, math.rad(20 - 5*side), math.rad(45)*truespeed)
Turn (torso, y_axis, math.rad(30 - 20*side), math.rad(45)*truespeed)
end
Move (waist, y_axis, 1.0, 12*truespeed)
WaitForMove (waist, y_axis)
Turn (shin[side], x_axis, math.rad(0), math.rad(420)*truespeed)
Turn (ankle[side], x_axis, math.rad(0), math.rad(420)*truespeed)
Turn (ankle[3-side], x_axis, math.rad(-30), math.rad(90)*truespeed)
Move (waist, y_axis, -2.0, 8*truespeed)
WaitForTurn (thigh[side], x_axis)
side = 3 - side
end
end
local function StopWalk()
Signal(SIG_Walk)
Move (waist, y_axis, 0, 16)
for i = 1, 2 do
Turn (ankle[i], x_axis, 0, math.rad(400))
Turn (thigh[i], x_axis, 0, math.rad(230))
Turn (shin[i], x_axis, 0, math.rad(230))
Turn (thigh[i], y_axis, 0, math.rad(135))
Turn (thigh[i], z_axis, 0, math.rad(135))
Turn (ankle[i], z_axis, 0, math.rad(135))
end
if not isAiming then
Turn (torso, y_axis, 0, math.rad(45))
Turn (torso, x_axis, 0, math.rad(45))
end
end
function script.StartMoving()
StartThread (Walk)
end
function script.StopMoving()
StartThread (StopWalk)
end
function script.Create()
StartThread (GG.Script.SmokeUnit, unitID, {torso, flare})
end
function script.AimFromWeapon(num)
return center
end
function script.QueryWeapon(num)
return flare
end
local function RestoreAfterDelay()
SetSignalMask (SIG_Aim)
Sleep (5000)
isAiming = false
Turn (dish, y_axis, 0, math.rad(20))
Turn (torso, x_axis, 0, math.rad(20))
end
function script.AimWeapon(num, heading, pitch)
Signal(SIG_Aim)
SetSignalMask(SIG_Aim)
isAiming = true
Turn (dish, y_axis, heading, math.rad(250))
Turn (torso, x_axis, -pitch, math.rad(200))
WaitForTurn (dish, y_axis)
WaitForTurn (torso, x_axis)
StartThread(RestoreAfterDelay)
return true
end
function script.FireWeapon()
EmitSfx(flare, GG.Script.UNIT_SFX1)
EmitSfx(flare, GG.Script.UNIT_SFX2)
end
function script.EndBurst()
Turn (torso, y_axis, math.rad(20))
Move (barrel, z_axis, -6.25)
WaitForTurn (torso, y_axis)
WaitForMove (barrel, z_axis)
Sleep (500)
Turn (torso, y_axis, 0, math.rad(60))
Move (barrel, z_axis, 0, 2)
end
function script.BlockShot(num, targetID)
if Spring.ValidUnitID(targetID) then
local distMult = (Spring.GetUnitSeparation(unitID, targetID) or 0)/860
return GG.OverkillPrevention_CheckBlock(unitID, targetID, 135.1, 120 * distMult, false, false, true)
end
return false
end
local explodables = {dish, barrel, thigh[2], waist, shin[2]}
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
local brutal = (severity > 0.5)
for i = 1, #explodables do
if math.random() < severity then
Explode (explodables[i], SFX.FALL + (brutal and (SFX.SMOKE + SFX.FIRE) or 0))
end
end
if not brutal then
return 1
else
Explode (torso, SFX.SHATTER)
return 2
end
end
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/luaui/widgets/gui_persistent_build_spacing.lua | 1 | 1107 | function widget:GetInfo()
return {
name = "Persistent Build Spacing",
desc = "Recalls last build spacing set for each building and game [v2.0]",
author = "Niobium & DrHash",
date = "Sep 6, 2011",
license = "GNU GPL, v3 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
-- Config
local defaultSpacing = 0
-- Globals
local lastCmdID = nil
local buildSpacing = {}
-- Speedups
local spGetActiveCommand = Spring.GetActiveCommand
local spGetBuildSpacing = Spring.GetBuildSpacing
local spSetBuildSpacing = Spring.SetBuildSpacing
-- Callins
function widget:Update()
local _, cmdID = spGetActiveCommand()
if cmdID and cmdID < 0 then
if cmdID ~= lastCmdID then
spSetBuildSpacing(buildSpacing[-cmdID] or defaultSpacing)
lastCmdID = cmdID
end
buildSpacing[-cmdID] = spGetBuildSpacing()
end
end
function widget:GetConfigData()
return { buildSpacing = buildSpacing }
end
function widget:SetConfigData(data)
buildSpacing = data.buildSpacing or {}
end | gpl-2.0 |
Anarchid/Zero-K | LuaRules/Gadgets/game_map_border.lua | 5 | 7068 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Map Border",
desc = "Implements a circular map border.",
author = "GoogleFrog",
date = "5 June 2021",
license = "GNU GPL, v2 or later",
layer = 100,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local MAPSIDE_BORDER_FILE = "mapconfig/map_border_config.lua"
local GAMESIDE_BORDER_FILE = "LuaRules/Configs/MapBorder/" .. (Game.mapName or "") .. ".lua"
local IterableMap = VFS.Include("LuaRules/Gadgets/Include/IterableMap.lua")
local spSetMapSquareTerrainType = Spring.SetMapSquareTerrainType
local spSetSquareBuildingMask = Spring.SetSquareBuildingMask
local spGetUnitPosition = Spring.GetUnitPosition
local vecDistSq = Spring.Utilities.Vector.DistSq
local MAP_WIDTH = Game.mapSizeX
local MAP_HEIGHT = Game.mapSizeZ
local MASK_SCALE = 1 / (2 * Game.squareSize)
local MOBILE_UPDATE_FREQ = 2 * 30
local OUT_OF_BOUNDS_UPDATE_FREQ = 3
local UP_IMPULSE = 0.25
local SIDE_IMPULSE = 1.5
local RAMP_DIST = 180
local NEAR_DIST = 500
local impulseMultipliers = {
[0] = 4, -- Fixedwing
[1] = 1, -- Gunship
[2] = 1.2, -- Ground/Sea
}
-- Configurable with originX, originZ, radius in GG.map_CircularMapBorder as a table.
local circularMapX = MAP_WIDTH/2
local circularMapZ = MAP_HEIGHT/2
local circularMapRadius = math.min(MAP_WIDTH/2, MAP_HEIGHT/2)
local circularMapRadiusSq, circularMapNearRadiusSq = 0, 0 -- Set later
local mobileUnits = IterableMap.New()
local outOfBoundsUnits = IterableMap.New()
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function IsInBounds(x, z)
-- returns whether (x,z) is inside the playable area.
return vecDistSq(x, z, circularMapX, circularMapZ) <= circularMapRadiusSq
end
local function IsNearBorderOrOutOfBounds(x, z)
-- returns whether (x,z) is within NEAR_DIST (500) of a border.
return vecDistSq(x, z, circularMapX, circularMapZ) > circularMapNearRadiusSq
end
local function GetClosestBorderPoint(x, z)
-- returns position on border closest to (x,z)
local vx = x - circularMapX
local vz = z - circularMapZ
local norm = math.sqrt(vx*vx + vz*vz)
vx, vz = vx / norm, vz / norm
return circularMapX + circularMapRadius*vx, circularMapZ + circularMapRadius*vz
end
local function LoadMapBorder()
local gameConfig = VFS.FileExists(GAMESIDE_BORDER_FILE) and VFS.Include(GAMESIDE_BORDER_FILE) or false
local mapConfig = VFS.FileExists(MAPSIDE_BORDER_FILE) and VFS.Include(MAPSIDE_BORDER_FILE) or false
local config = gameConfig or mapConfig or false
if not config then
return false
end
IsInBounds = config.IsInBounds or IsInBounds
IsNearBorderOrOutOfBounds = config.IsNearBorderOrOutOfBounds or IsNearBorderOrOutOfBounds
GetClosestBorderPoint = config.GetClosestBorderPoint or GetClosestBorderPoint
circularMapX = config.originX or circularMapX
circularMapZ = config.originZ or circularMapZ
circularMapRadius = config.radius or circularMapRadius
circularMapRadiusSq = circularMapRadius^2
circularMapNearRadiusSq = (circularMapRadius > NEAR_DIST and (circularMapRadius - NEAR_DIST)^2) or 0
return true
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function SetupTypemapAndMask()
for x = 0, MAP_WIDTH - 8, 8 do
for z = 0, MAP_HEIGHT - 8, 8 do
if not IsInBounds(x, z) then
spSetMapSquareTerrainType(x, z, GG.IMPASSIBLE_TERRAIN)
if x%16 == 0 and z%16 == 0 then
spSetSquareBuildingMask(x * MASK_SCALE, z * MASK_SCALE, 0)
end
end
end
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Unit Handling
local function CheckMobileUnit(unitID, moveType)
local x, _, z = spGetUnitPosition(unitID)
if (moveType == 2 and not IsInBounds(x, z)) or (moveType~= 2 and IsNearBorderOrOutOfBounds(x, z)) then
IterableMap.Add(outOfBoundsUnits, unitID, moveType)
return true -- remove from mobileUnits
end
end
local function HandleOutOFBoundsUnit(unitID, moveType)
local ux, _, uz = spGetUnitPosition(unitID)
if IsInBounds(ux, uz) then
if moveType ~= 2 and IsNearBorderOrOutOfBounds(ux, uz) then
return -- Keep track of aircraft near border.
end
IterableMap.Add(mobileUnits, unitID, moveType)
return true -- Remove from outOfBoundsUnits
end
local bx, bz = GetClosestBorderPoint(ux, uz)
local vx = bx - ux
local vz = bz - uz
local norm = math.sqrt(vx*vx + vz*vz)
vx, vz = vx / norm, vz / norm
local mag = (impulseMultipliers[moveType] or 1)
if norm < RAMP_DIST then
if moveType == 2 then
-- Ground units only go down to half magnitude, to help with unsticking.
mag = mag * (0.5 + 0.5 * norm / RAMP_DIST)
else
mag = mag * norm / RAMP_DIST
end
end
GG.AddGadgetImpulseRaw(unitID, vx*mag*SIDE_IMPULSE, UP_IMPULSE, vz*mag*SIDE_IMPULSE, true, true)
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Gagdet API
function gadget:GameFrame(n)
IterableMap.ApplyFraction(mobileUnits, MOBILE_UPDATE_FREQ, n%MOBILE_UPDATE_FREQ, CheckMobileUnit)
IterableMap.ApplyFraction(outOfBoundsUnits, OUT_OF_BOUNDS_UPDATE_FREQ, n%OUT_OF_BOUNDS_UPDATE_FREQ, HandleOutOFBoundsUnit)
end
function gadget:UnitCreated(unitID, unitDefID, teamID)
local moveType = Spring.Utilities.getMovetypeByID(unitDefID)
if not moveType then
-- Don't handle static structures.
return
end
IterableMap.Add(mobileUnits, unitID, moveType)
end
function gadget:UnitDestroyed(unitID, unitDefID, teamID)
if not Spring.Utilities.getMovetypeByID(unitDefID) then
-- Don't handle static structures.
return
end
IterableMap.Remove(mobileUnits, unitID)
IterableMap.Remove(outOfBoundsUnits, unitID)
end
function gadget:Initialize()
if not LoadMapBorder() then
gadgetHandler:RemoveGadget()
return
end
SetupTypemapAndMask()
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
local teamID = Spring.GetUnitTeam(unitID)
gadget:UnitCreated(unitID, unitDefID, teamID)
end
GG.map_AllowPositionTerraform = IsInBounds
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
| gpl-2.0 |
Anarchid/Zero-K | scripts/spidercrabe.lua | 6 | 11432 | include 'constants.lua'
include 'reliableStartMoving.lua'
--------------------------------------------------------------------------------
-- pieces
--------------------------------------------------------------------------------
local base = piece 'base'
local ground = piece 'ground'
local turret = piece 'turret'
local blight = piece 'blight'
local canon = piece 'canon'
local barrel1 = piece 'barrel1'
local barrel2 = piece 'barrel2'
local flare1 = piece 'flare1'
local flare2 = piece 'flare2'
local flare3 = piece 'flare3'
local flare4 = piece 'flare4'
local flare5 = piece 'flare5'
local flare6 = piece 'flare6'
local flare7 = piece 'flare7'
local rocket = piece 'rocket'
local leg1 = piece 'leg1' -- front right
local leg2 = piece 'leg2' -- back right
local leg3 = piece 'leg3' -- back left
local leg4 = piece 'leg4' -- front left
local gflash = piece 'gflash'
local smokePiece = {base, turret}
local CMD_RAW_MOVE = Spring.Utilities.CMD.RAW_MOVE
local CMD_MOVE = CMD.MOVE
--------------------------------------------------------------------------------
-- constants
--------------------------------------------------------------------------------
local restore_delay = 3000
local SIG_MOVE = 2
local SIG_AIM1 = 4
local SIG_AIM2 = 8
local PACE = 2.4
local legRaiseSpeed = math.rad(45)*PACE
local legRaiseAngle = math.rad(20)
local legLowerSpeed = math.rad(50)*PACE
local legForwardSpeed = math.rad(40)*PACE
local legForwardAngle = -math.rad(20)
local legBackwardSpeed = math.rad(35)*PACE
local legBackwardAngle = math.rad(45)
local legBackwardAngleMinor = math.rad(10)
--------------------------------------------------------------------------------
-- vars
--------------------------------------------------------------------------------
local armored = false
local nocurl = true
local movingData = {}
local gun_0 = 0
-- four-stroke tetrapedal walkscript
local function Walk()
while true do
-- Spring.Echo("left fore and right back move, left back and right fore anchor")
Turn(leg4, z_axis, legRaiseAngle, legRaiseSpeed) -- LF leg up
Turn(leg4, y_axis, legForwardAngle, legForwardSpeed) -- LF leg forward
--Turn(leg3, z_axis, 0, legLowerSpeed) -- LB leg down
Turn(leg3, y_axis, legBackwardAngle, legBackwardSpeed) -- LB leg back
--Turn(leg1, z_axis, 0, legLowerSpeed) -- RF leg down
Turn(leg1, y_axis, -legBackwardAngleMinor, legBackwardSpeed) -- RF leg back
Turn(leg2, z_axis, -legRaiseAngle, legRaiseSpeed) -- RB leg up
Turn(leg2, y_axis, 0, legForwardSpeed) -- RB leg forward
WaitForTurn(leg4, z_axis)
WaitForTurn(leg4, y_axis)
Sleep(0)
-- Spring.Echo("lower left fore and right back")
Turn(leg4, z_axis, 0, legLowerSpeed) -- LF leg down
Turn(leg2, z_axis, 0, legLowerSpeed) -- RB leg down
Sleep(0)
WaitForTurn(leg4, z_axis)
-- Spring.Echo("left back and right fore move, left fore and right back anchor")
--Turn(leg4, z_axis, 0, legLowerSpeed) -- LF leg down
Turn(leg4, y_axis, legBackwardAngleMinor, legBackwardSpeed) -- LF leg back
Turn(leg3, z_axis, legRaiseAngle, legRaiseSpeed) -- LB leg up
Turn(leg3, y_axis, 0, legForwardSpeed) -- LB leg forward
Turn(leg1, z_axis, -legRaiseAngle, legRaiseSpeed) -- RF leg up
Turn(leg1, y_axis, -legForwardAngle, legForwardSpeed) -- RF leg forward
--Turn(leg2, z_axis, 0, legLowerSpeed) -- RB leg down
Turn(leg2, y_axis, -legBackwardAngle, legBackwardSpeed) -- RB leg back
WaitForTurn(leg1, z_axis)
WaitForTurn(leg1, y_axis)
Sleep(0)
-- Spring.Echo("lower left back and right fore")
Turn(leg3, z_axis, 0, legLowerSpeed) -- LB leg down
Turn(leg1, z_axis, 0, legLowerSpeed) -- RF leg down
Sleep(0)
WaitForTurn(leg3, z_axis)
end
end
local function Curl()
if nocurl or armored then
return
end
--Spring.Echo("Initiating curl")
SetSignalMask(SIG_MOVE)
Sleep(200)
while Spring.GetUnitIsStunned(unitID) do
Sleep (100)
end
Sleep(100)
--Spring.Echo("slowing down", Spring.GetGameFrame())
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", 0.2)
GG.UpdateUnitAttributes(unitID)
Move(canon, y_axis, 5, 1.5)
Move(base, y_axis, -5, 2.5)
Move(base, z_axis, -1, 2.5)
Turn(leg1, y_axis, math.rad(45), math.rad(35))
Turn(leg4, y_axis, math.rad(-45), math.rad(35))
Turn(leg2, y_axis, math.rad(-45), math.rad(35))
Turn(leg3, y_axis, math.rad(45), math.rad(35))
Turn(leg1, z_axis, math.rad(45), math.rad(35))
Turn(leg4, z_axis, math.rad(-45), math.rad(35))
Turn(leg2, z_axis, math.rad(40), math.rad(35))
Turn(leg3, z_axis, math.rad(-40), math.rad(35))
-- preturn (makes sure the legs turn in the right direction)
Turn(leg2, x_axis, math.rad(90), math.rad(95))
Turn(leg3, x_axis, math.rad(90), math.rad(95))
Turn(leg1, x_axis, math.rad(-90), math.rad(95))
Turn(leg4, x_axis, math.rad(-90), math.rad(95))
Sleep(100)
Turn(leg2, x_axis, math.rad(180), math.rad(95))
Turn(leg3, x_axis, math.rad(180), math.rad(95))
Turn(leg1, x_axis, math.rad(180), math.rad(95))
Turn(leg4, x_axis, math.rad(180), math.rad(95))
WaitForTurn(leg1, x_axis)
WaitForTurn(leg2, x_axis)
WaitForTurn(leg3, x_axis)
WaitForTurn(leg4, x_axis)
Spring.SetUnitArmored(unitID,true)
armored = true
end
local function ResetLegs()
--Spring.Echo("Resetting legs", Spring.GetGameFrame())
Turn(leg1, y_axis, 0, math.rad(35))
Turn(leg2, y_axis, 0, math.rad(35))
Turn(leg3, y_axis, 0, math.rad(35))
Turn(leg4, y_axis, 0, math.rad(35))
Turn(leg1, z_axis, 0, math.rad(25))
Turn(leg2, z_axis, 0, math.rad(25))
Turn(leg3, z_axis, 0, math.rad(25))
Turn(leg4, z_axis, 0, math.rad(25))
-- preturn (makes sure the legs turn in the right direction)
Turn(leg2, x_axis, math.rad(90), math.rad(95))
Turn(leg3, x_axis, math.rad(90), math.rad(95))
Turn(leg1, x_axis, math.rad(-90), math.rad(95))
Turn(leg4, x_axis, math.rad(-90), math.rad(95))
Sleep(100)
Turn(leg1, x_axis, 0, math.rad(95))
Turn(leg2, x_axis, 0, math.rad(95))
Turn(leg3, x_axis, 0, math.rad(95))
Turn(leg4, x_axis, 0, math.rad(95))
end
local function Uncurl()
--Spring.Echo("Initiating uncurl", Spring.GetGameFrame())
local cmdID, _, cmdTag, cp_1, cp_2, cp_3, cp_4, cp_5, cp_6 = Spring.GetUnitCurrentCommand(unitID)
if cmdID == CMD_RAW_MOVE or cmdID == CMD_MOVE then
Sleep(100)
else
Sleep(700)
end
ResetLegs()
Move(canon, y_axis, 0, 2.5)
Move(base, y_axis, 0, 2.5)
Move(base, z_axis, 0, 2.5)
--Spring.Echo("disabling armor", Spring.GetGameFrame())
armored = false
Spring.SetUnitArmored(unitID,false)
WaitForTurn(leg1, x_axis)
WaitForTurn(leg2, x_axis)
WaitForTurn(leg3, x_axis)
WaitForTurn(leg4, x_axis)
--Spring.Echo("speeding up", Spring.GetGameFrame())
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", 1)
GG.UpdateUnitAttributes(unitID)
end
local function BlinkingLight()
while GetUnitValue(COB.BUILD_PERCENT_LEFT) do
Sleep(3000)
end
while true do
EmitSfx(blight, 1024+2)
Sleep(2100)
end
end
local function CurlDelay() --workaround for crabe getting stuck in fac
while GetUnitValue(COB.BUILD_PERCENT_LEFT) > 0 do
Sleep(330)
end
Sleep(2000)
nocurl = false
end
local function Motion()
Signal(SIG_MOVE)
SetSignalMask(SIG_MOVE)
Sleep(100)
Uncurl()
Walk()
end
function script.StartMoving()
movingData.moving = true
--Spring.Utilities.UnitEcho(unitID, "A " .. ((armored and "T") or "F"))
StartThread(Motion)
movingData.thresholdSpeed = 0.02
end
function script.StopMoving()
Signal(SIG_MOVE)
movingData.thresholdSpeed = 0.3
movingData.moving = false
--Spring.Utilities.UnitEcho(unitID, "P " .. ((armored and "T") or "F"))
StartThread(Curl)
end
function script.Create()
--set ARMORED to false
Hide(flare1)
Hide(flare2)
Hide(flare3)
Hide(flare4)
Hide(flare5)
Hide(flare6)
Hide(flare7)
StartThread(GG.StartStopMovingControl, unitID, script.StartMoving, script.StopMoving, 0.3, false, movingData, 4, true)
--StartThread(MotionControl)
StartThread(GG.Script.SmokeUnit, unitID, smokePiece)
--StartThread(BlinkingLight)
if Spring.GetUnitIsStunned(unitID) then
StartThread(CurlDelay)
else
nocurl = false
StartThread(Curl)
end
end
local function RockSelf(anglex, anglez)
Turn(base, z_axis, -anglex, math.rad(50))
Turn(base, x_axis, anglez, math.rad(50))
WaitForTurn(base, z_axis)
WaitForTurn(base, x_axis)
Turn(base, z_axis, 0, math.rad(20))
Turn(base, x_axis, 0, math.rad(20))
end
local spGetUnitSeparation = Spring.GetUnitSeparation
function script.BlockShot(num, targetID)
if Spring.ValidUnitID(targetID) then
-- TTL at max range determined to be 60f empirically
-- at projectile speed 290 elmo/s and 600 range, but
-- add a few extra frames because that was on flat
-- terrain and spiders like uneven terrain where the
-- TTL can be a bit larger due to vertical difference
local framesETA = 65 * (spGetUnitSeparation(unitID, targetID) or 0) / 600
return GG.OverkillPrevention_CheckBlock(unitID, targetID, 600.1, framesETA, false, false, true)
end
return false
end
function script.RockUnit(anglex, anglez)
StartThread(RockSelf, math.rad(anglex), math.rad(anglez))
end
local function RestoreAfterDelay1()
Sleep(3000)
Turn(turret, y_axis, 0, math.rad(70))
Turn(canon, x_axis, 0, math.rad(50))
end
local function RestoreAfterDelay2()
Sleep(3000)
Turn(rocket, y_axis, 0, math.rad(70))
Turn(rocket, x_axis, 0, math.rad(50))
end
function script.AimWeapon(num, heading, pitch)
if num == 1 then
Signal(SIG_AIM1)
SetSignalMask(SIG_AIM1)
Turn(turret, y_axis, heading, math.rad(70))
Turn(canon, x_axis, -pitch, math.rad(50))
WaitForTurn(turret, y_axis)
WaitForTurn(canon, x_axis)
StartThread(RestoreAfterDelay1)
return true
elseif num == 2 then
Signal(SIG_AIM2)
SetSignalMask(SIG_AIM2)
Turn(rocket, y_axis, math.rad(heading), math.rad(190))
Turn(rocket, x_axis, 0, math.rad(150))
WaitForTurn(rocket, y_axis)
WaitForTurn(rocket, x_axis)
StartThread(RestoreAfterDelay2)
return true
end
end
function script.FireWeapon(num)
if num == 1 then
Move(barrel1, z_axis, -1.2)
EmitSfx(flare1, 1024+0)
EmitSfx(gflash, 1024+1)
Move(barrel2, z_axis, -1.2)
Sleep(150)
Move(barrel1, z_axis, 0, 3)
Move(barrel2, z_axis, 0, 3)
elseif num == 2 then
gun_0 = gun_0 + 1
if gun_0 == 3 then
gun_0 = 0
end
end
end
function script.AimFromWeapon(num)
if num == 1 then return turret
else return rocket end
end
function script.QueryWeapon(num)
if num == 1 then return flare1
else
if gun_0 == 0 then return flare2
elseif gun_0 == 1 then return flare3
else return flare4 end
end
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity <= .25 then
Explode(base, SFX.NONE)
return 1
elseif (severity <= .50) then
Explode(base, SFX.NONE)
Explode(leg1, SFX.NONE)
Explode(leg2, SFX.NONE)
Explode(leg3, SFX.NONE)
Explode(leg4, SFX.NONE)
return 1
elseif (severity <= .99) then
Explode(leg1, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(leg2, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(leg3, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(leg4, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(turret, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
return 2
else
Explode(leg1, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(leg2, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(leg3, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(leg4, SFX.FALL + SFX.SMOKE + SFX.FIRE)
Explode(turret, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(canon, SFX.FALL + SFX.SMOKE + SFX.FIRE)
return 2
end
end
| gpl-2.0 |
aJns/tililoggeri | parse_functions.lua | 1 | 3092 | local parse_functions = {}
local utils = require "pl.utils"
local stringx = require "pl.stringx"
--parse the file for transactions
function parse_functions.parse_file(instructions, filename, parsed_lines)
local file = io.open(filename, "r")
if not file then
print("Couldn't open ", filename)
return false
end
local lines = {}
for line in file:lines() do
table.insert(lines, line)
end
file:close()
for key,value in pairs(lines) do
--remove empty lines, \13 equals \n
if value == "\13" then
lines[key] = nil
else
--split the lines at "tabs" (\9 equals \t)
--and discard unnecessary lines
splitline = {}
splitline = utils.split(value, "\9")
if (splitline[1] == instructions.remove[1] or
splitline[1] == instructions.remove[2]) then
lines[key] = nil
else
lines[key] = splitline
end
end
end
--building the "parsed_lines" table by matching the keyline
--keys with their corresponding values
for i,line in pairs(lines) do
parsed_line = {}
for j,key in pairs(instructions.keyline) do
parsed_line[key] = line[j]
end
table.insert(parsed_lines,parsed_line)
end
return true
end
--format the parsed lines in to a more usable transactions list,
--removing unnecessary columns and setting types
function parse_functions.format_transactions(instructions, parsed_lines)
local format = instructions.format
local transactions = {}
for i,line in pairs(parsed_lines) do
local transaction = {}
for fkey,column in pairs(format) do
for key,value in pairs(line) do
if column == key then
if fkey == "date" then
transaction[fkey] = get_date(value, format.dateformat)
elseif fkey == "amount" then transaction[fkey] = stringx.replace(value, ",", ".") else
transaction[fkey] = value
end
end
end
end
transaction.original = require "pl.tablex".deepcopy(line)
transaction.stringID = get_stringID(line, instructions.keyline)
table.insert(transactions,transaction)
end
return transactions
end
function get_date(date_string, dateformat)
local date = require "pl.Date"{}
local split_date = utils.split(date_string, dateformat.separator, "plain")
for i,value in pairs(dateformat.order) do
if value == "d" then
date:day(tonumber(split_date[i]))
elseif value == "M" then
date:month(tonumber(split_date[i]))
elseif value == "y" then
date:year(tonumber(split_date[i]))
end
end
return date
end
function get_stringID(transaction, keyline)
local stringID = ""
for i, key in ipairs(keyline) do
stringID = stringID .. transaction[key]
end
return stringID
end
return parse_functions
| gpl-3.0 |
Drauthius/monstrous-bosses | src/employee.lua | 1 | 9784 | --[[
Copyright (C) 2015 Albert Diserholt
This file is part of Monstrous Bosses.
Monstrous Bosses is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Monstrous Bosses is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Monstrous Bosses. If not, see <http://www.gnu.org/licenses/>.
--]]
local anim8 = require("lib.anim8")
local cron = require("lib.cron")
local GameObject = require("src.gameobject")
local Employee = GameObject:subclass("Employee")
Employee.static.energyBar = love.graphics.newImage("gfx/energybar.png")
Employee.static.greenBar = love.graphics.newImage("gfx/greenbar.png")
Employee.static.energyBarBlinkSheet = love.graphics.newImage("gfx/energybar_blink.png")
Employee.static.energyBarBlinkGrid = anim8.newGrid(60, 18, Employee.energyBarBlinkSheet:getDimensions())
Employee.static.greenArrow = love.graphics.newImage("gfx/greenarrow.png")
Employee.static.redArrow = love.graphics.newImage("gfx/redarrow.png")
Employee.static.spriteSheet = love.graphics.newImage("gfx/employees.png")
Employee.static.spriteGrid = anim8.newGrid(64, 148, Employee.spriteSheet:getWidth(), Employee.spriteSheet:getHeight(), 0, 0, 1)
-- Resistances are in percent (100% = no effort) per station type (computer=1,
-- printer=2, paperwork=3)
Employee.static.types = {
{ -- Red
id = 1,
energyRestoration = 2,
resistances = { 70, 70, 50 },
minWorkTime = 5,
slackingChance = 20,
},
{ -- Purple
id = 2,
energyRestoration = 4,
resistances = { 30, 70, 30 },
minWorkTime = 3,
slackingChance = 40,
},
{ -- Blue
id = 3,
energyRestoration = 5,
resistances = { 50, 50, 20 },
minWorkTime = 4,
slackingChance = 50,
},
{ -- Green
id = 4,
energyRestoration = 4,
resistances = { 70, 30, 30 },
minWorkTime = 3,
slackingChance = 40,
},
{ -- White
id = 5,
energyRestoration = 6,
resistances = { 20, 20, 20 },
minWorkTime = 2,
slackingChance = 60,
},
}
Employee.static.changePerArrow = 3
function Employee:initialize(x, y, toX, toY, employeeType)
GameObject.initialize(self, x, y)
self.walkTo = { x = toX or x, y = toY or y }
self.walkingSpeed = love.math.random(100, 200)
self:setEnergy(love.math.random(45, 65))
self.energyChange = 0
self.type = Employee.types[employeeType or love.math.random(1, #Employee.types)]
self.size.w = Employee.spriteGrid.frameWidth
self.size.h = Employee.spriteGrid.frameHeight
self.slackingCheckInterval = love.math.random(5,10)/10 -- How often (in seconds) to evaluate slacking
local c = self.type.id
self.walkingAnimation = anim8.newAnimation(Employee.spriteGrid(c,1, c,2, c,1, c,3, c,4, c,3), self.walkingSpeed/700)
self.workingAnimation = anim8.newAnimation(Employee.spriteGrid(c,8, c,9, c,8, c,10), 0.2)
-- Hella-ugly, but hey.
self.eyeAnimation = anim8.newAnimation(Employee.spriteGrid(c,5, c,6, c,7, c,7, c,6, c,5, c,1), 0.04, "pauseAtEnd")
self.blinkTimer = cron.after(0, function() end)
self.energyBarBlink = anim8.newAnimation(Employee.energyBarBlinkGrid('1-3',1, '3-1',1), 0.1)
end
function Employee:setEnergy(energy)
self.energy = energy
end
function Employee:getEnergy()
return self.energy
end
function Employee:isExhausted()
return self.energy <= 0 and self.exhaustedTimer ~= nil
end
function Employee:isWorking()
return self.working
end
function Employee:setWorking(isWorking, station)
if self:isExhausted() then
self.working = false
else
self.working = isWorking
self.lastWorkChange = love.timer.getTime()
if isWorking then
self.idleTimer = nil
end
end
if self.station ~= nil then
self.station:unassign(self)
end
self.station = station
if self.station ~= nil then
self.station:assign(self)
self.workingAnimation.flippedH = self.station:isFlipped()
self.walkingAnimation.flippedH = self.workingAnimation.flippedH
end
end
function Employee:startDragging()
self:setWorking(false, nil)
self.dragging = true
-- Stop walking
self.walkTo = nil
end
function Employee:stopDragging()
self.dragging = false
end
function Employee:startSlacking()
self:setWorking(false, self.station)
self.idleTimer = cron.after(love.math.random(3,6), function() end)
end
function Employee:update(dt)
GameObject.update(self, dt)
local startingEnergy = self:getEnergy()
if self.dragging then
self.pos.x = love.mouse.getX() - 15
self.pos.y = love.mouse.getY() - 15
end
if self.exhaustedTimer and self.exhaustedTimer <= love.timer.getTime() then
self.exhaustedTimer = nil
end
if self:isWorking() then
local afterResistance = self.station:getEnergyConsumption() * ((100 - self.type.resistances[self.station.type.id])/100)
self:setEnergy(self:getEnergy() - afterResistance * dt)
if self:getEnergy() <= 0 then
self:setEnergy(0)
self.energyBarBlink:gotoFrame(1)
self.exhaustedTimer = love.timer.getTime() + 5
self:setWorking(false, self.station)
else
-- Random chance that some slacking will occur.
local workedFor = love.timer.getTime() - self.lastWorkChange
if workedFor > self.type.minWorkTime then
if love.math.random(1, 100) <= self.type.slackingChance then
self:startSlacking()
else
self.lastWorkChange = self.lastWorkChange + self.slackingCheckInterval
end
end
end
elseif not self:isExhausted() then
self:setEnergy(self:getEnergy() + self.type.energyRestoration*dt)
if self:getEnergy() >= 100 then
love.event.push("gameover")
end
if self.walkTo ~= nil and (self.walkTo.x ~= self.pos.x or self.walkTo.y ~= self.pos.y) then
self.walkingAnimation:resume()
local movement = self.walkingSpeed * dt
for _,v in ipairs({ "x", "y" }) do
if self.walkTo[v] > self.pos[v] then
if v == "x" then self.walkingAnimation.flippedH = true end
self.pos[v] = self.pos[v] + movement
elseif self.walkTo[v] < self.pos[v] then
if v == "x" then self.walkingAnimation.flippedH = false end
self.pos[v] = self.pos[v] - movement
end
if math.abs(self.walkTo[v] - self.pos[v]) <= 2 then
self.pos[v] = self.walkTo[v]
end
end
else
self.walkingAnimation:pauseAtStart()
end
end
if self.idleTimer ~= nil and self.idleTimer:update(dt) then
self.idleTimer = nil
if not self.dragging and not self:isExhausted() and not self:isWorking() then
self:setWorking(false, nil) -- Release station.
self.walkTo = {
x = love.math.random(Employee.idleArea.x1, Employee.idleArea.x2),
y = love.math.random(Employee.idleArea.y1, Employee.idleArea.y2)
}
end
end
self.walkingAnimation:update(dt)
self.workingAnimation:update(dt)
self.eyeAnimation:update(dt)
self.eyeAnimation.flippedH = self.walkingAnimation.flippedH
self.energyBarBlink:update(dt)
if self.blinkTimer:update(dt) then
self.eyeAnimation:gotoFrame(1)
self.eyeAnimation:resume()
self.blinkTimer = cron.after(love.math.random(2, 5), function() end)
end
self.energyChange = (self:getEnergy() - startingEnergy) / dt
end
function Employee:draw()
do -- Body
local animation = self.walkingAnimation
if self:isWorking() then
animation = self.workingAnimation
end
love.graphics.setColor(255, 255, 255, 255)
animation:draw(Employee.spriteSheet, self.pos.x, self.pos.y)
if self:isActive() then
love.graphics.setColor(0, 255, 0, 100)
animation:draw(Employee.spriteSheet, self.pos.x, self.pos.y)
end
end
do -- Eye
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setStencil(function()
-- Only draw the head
love.graphics.rectangle("fill", self.pos.x, self.pos.y, self.size.w, self.size.h/4)
end)
self.eyeAnimation:draw(Employee.spriteSheet, self.pos.x, self.pos.y)
if self:isActive() then
love.graphics.setColor(0, 255, 0, 100)
self.eyeAnimation:draw(Employee.spriteSheet, self.pos.x, self.pos.y)
end
love.graphics.setStencil()
end
GameObject.draw(self)
do -- Draw energy bar
local barOffset = 3 -- Number of pixels until the bar starts/ends
local x = self.pos.x + (self.size.w - Employee.energyBar:getWidth())/2
local y, w, h = self.pos.y - 5, Employee.energyBar:getWidth(), 10
local fill = math.max(0, (w - 2*barOffset) / 100 * self:getEnergy())
love.graphics.setColor(255, 255, 255, 255)
love.graphics.draw(Employee.energyBar, x, y)
love.graphics.setStencil(function()
love.graphics.rectangle("fill", x + barOffset, y, fill, h)
end)
love.graphics.draw(Employee.greenBar, x, y)
love.graphics.setStencil()
if not self:isExhausted() then
local arrowOffset = 3
if self:isWorking() then
local arrowWidth = Employee.redArrow:getWidth()
for i=1,3 do
love.graphics.setColor(255, 255, 255,
math.max(0, math.min(255,
(-self.energyChange - Employee.changePerArrow*(i-1)) / Employee.changePerArrow * 255)))
love.graphics.draw(Employee.redArrow, x - i*arrowWidth - arrowOffset, y)
end
else
local arrowWidth = Employee.greenArrow:getWidth()
for i=1,3 do
love.graphics.setColor(255, 255, 255,
math.max(0, math.min(255,
(self.energyChange - Employee.changePerArrow*(i-1)) / Employee.changePerArrow * 255)))
love.graphics.draw(Employee.greenArrow, x + w + arrowOffset + (i-1)*arrowWidth, y)
end
if self:getEnergy() >= 90 then
love.graphics.setColor(50, 255, 50, 255)
self.energyBarBlink:draw(Employee.energyBarBlinkSheet, x - 5, y - 5)
end
end
else
self.energyBarBlink:draw(Employee.energyBarBlinkSheet, x - 5, y - 5)
end
end
end
return Employee
| gpl-3.0 |
MrPolicy/HodTG | plugins/helplock.lua | 1 | 1877 |
do
function run(msg, matches)
if not is_momod(msg) then
return "Only For Moderators!"
end
return [[
📂دستورات قفل های تنضیمات📂
🔻مشاهده دستورات
🔹!help
🔸🔸🔸🔸🔸🔸🔸🔸🔸
🔻قفل لینک و لغو قفل
🔹!lock links
🔹!unlock links
🔻قفل ارسال شماره تماس و لغو قفل
🔹!lock contacts
🔹!unlock contacts
🔻قفل حساسیت اسپم و لغو قفل
🔹!lock flood
🔹!unlock flood
🔻قفل اسپم و لغو قفل
🔹!lock spam
🔹!unlock spam
🔻قفل تایپ عربی و لغو قفل
🔹!lock arabic
🔹!unlock arabic
🔻قفل اضافه کردن اعضا و لغو قفل
🔹!lock Member
🔹!unlock Member
🔻قفل اعلانات و لغو قفل
🔹!lock Tgservice
🔹!unlock Tgservice
🔻قفل استیکر و لغو قفل
🔹!lock sticker
🔹!unlock sticker
🔻قفل برچسب و لغو قفل
🔹!lock tag
🔹!unlock tag
🔻قفل ایموجی و لغو قفل
🔹!lock emoji
🔹!unlock emoji
🔻قفل تایپ انگلیسی و لغو قفل
🔹!lock english
🔹!unlock english
🔻قفل فوروارد و لغو قفل
🔹!lock forward
🔹unlock forward
🔻قفل ریپلی و لغو قفل
🔹!lock reply
🔹!unlock reply
🔻قفل یوزرنیم و لغو قفل
🔹!lock username
🔹!unlock username
🔻قفل رسانه و لغو قفل
🔹!lock media
🔹unlock media
🔻قفل فحاشی و لغو قفل
🔹!lock fosh
🔹!unlock fosh
🔻قفل ورود ربات و لغو قفل
🔹!lock bots
🔹!unlock bots
]]
end
return {
description = "Shows bot version",
usage = "ver: Shows bot version",
patterns = {
"^<code>[Hh]elplock$",
"^[/!#][Hh]elplock$"
},
run = run
}
end | gpl-2.0 |
wesnoth/wesnoth | data/ai/lua/ca_castle_switch.lua | 4 | 11110 | -------- Castle Switch CA --------------
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local M = wesnoth.map
local CS_leader_score
-- Note that CS_leader and CS_leader_target are also needed by the recruiting CA, so they must be stored in 'data'
local high_score = 195000
local low_score = 15000
local function get_reachable_enemy_leaders(unit, avoid_map)
-- We're cheating a little here and also find hidden enemy leaders. That's
-- because a human player could make a pretty good educated guess as to where
-- the enemy leaders are likely to be while the AI does not know how to do that.
local potential_enemy_leaders = AH.get_live_units { canrecruit = 'yes',
{ "filter_side", { { "enemy_of", {side = wesnoth.current.side} } } }
}
local enemy_leaders = {}
for _,e in ipairs(potential_enemy_leaders) do
-- Cannot use AH.find_path_with_avoid() here as there might be enemies all around the enemy leader
if (not avoid_map:get(e.x, e.y)) then
wesnoth.interface.handle_user_interact()
local path, cost = wesnoth.paths.find_path(unit, e.x, e.y, { ignore_units = true, ignore_visibility = true })
if cost < AH.no_path then
table.insert(enemy_leaders, e)
end
end
end
return enemy_leaders
end
local function other_units_on_keep(leader)
-- if we're on a keep, wait until there are no movable non-leader units on the castle before moving off
local leader_score = high_score
if wesnoth.terrain_types[wesnoth.current.map[leader]].keep then
local castle = AH.get_locations_no_borders {
{ "and", {
x = leader.x, y = leader.y, radius = 200,
{ "filter_radius", { terrain = 'C*,K*,C*^*,K*^*,*^K*,*^C*' } }
}}
}
local should_wait = false
for i,loc in ipairs(castle) do
local unit = wesnoth.units.get(loc[1], loc[2])
if unit and (unit.side == wesnoth.current.side) and (not unit.canrecruit) and (unit.moves > 0) then
should_wait = true
break
end
end
if should_wait then
leader_score = low_score
end
end
return leader_score
end
local ca_castle_switch = {}
function ca_castle_switch:evaluation(cfg, data, filter_own, recruiting_leader)
-- @recruiting_leader is passed from the recuit_rushers CA for the leader_takes_villages evaluation
-- evaluation. If it is set, we do the castle switch evaluation only for that leader
local start_time, ca_name = wesnoth.ms_since_init() / 1000., 'castle_switch'
if AH.print_eval() then AH.print_ts(' - Evaluating castle_switch CA:') end
if ai.aspects.passive_leader then
-- Turn off this CA if the leader is passive
return 0
end
local leaders
if recruiting_leader then
-- Note that doing this might set the stored castle switch information to a different leader.
-- This is fine though, the order in which these are done is not particularly important.
leaders = { recruiting_leader }
else
leaders = AH.get_units_with_moves({
side = wesnoth.current.side,
canrecruit = 'yes',
formula = '(movement_left = total_movement) and (hitpoints = max_hitpoints)',
{ "and", filter_own }
}, true)
end
local non_passive_leader
for _,l in pairs(leaders) do
if (not AH.is_passive_leader(ai.aspects.passive_leader, l.id)) then
non_passive_leader = l
break
end
end
if not non_passive_leader then
-- CA is irrelevant if no leader or the leader may have moved from another CA
data.CS_leader, data.CS_leader_target = nil, nil
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
-- Also need to check that the stored leader has not been killed
if data.CS_leader and not data.CS_leader.valid then
data.CS_leader, data.CS_leader_target = nil, nil
end
local avoid_map = AH.get_avoid_map(ai, nil, true)
if data.CS_leader and wesnoth.sides[wesnoth.current.side].gold >= AH.get_cheapest_recruit_cost(data.CS_leader)
and ((not recruiting_leader) or (recruiting_leader.id == data.CS_leader.id))
then
-- If the saved score is the low score, check whether there are still other units on the keep
if (CS_leader_score == low_score) then
CS_leader_score = other_units_on_keep(data.CS_leader)
end
-- make sure move is still valid
local path, cost = AH.find_path_with_avoid(data.CS_leader, data.CS_leader_target[1], data.CS_leader_target[2], avoid_map)
local next_hop = AH.next_hop(data.CS_leader, nil, nil, { path = path, avoid_map = avoid_map })
if next_hop and next_hop[1] == data.CS_leader_target[1]
and next_hop[2] == data.CS_leader_target[2]
then
return CS_leader_score
else
data.CS_leader, data.CS_leader_target = nil, nil
end
end
-- Look for the best keep
local overall_best_score = 0
for _,leader in ipairs(leaders) do
local best_score, best_loc, best_turns, best_path = 0, {}, 3, nil
local keeps = AH.get_locations_no_borders {
terrain = 'K*,K*^*,*^K*', -- Keeps
{ "not", { {"filter", {}} }}, -- That have no unit
{ "not", { radius = 6, {"filter", { canrecruit = 'yes',
{ "filter_side", { { "enemy_of", {side = wesnoth.current.side} } } }
}} }}, -- That are not too close to an enemy leader
{ "not", {
x = leader.x, y = leader.y, terrain = 'K*,K*^*,*^K*',
radius = 3,
{ "filter_radius", { terrain = 'C*,K*,C*^*,K*^*,*^K*,*^C*' } }
}}, -- That are not close and connected to a keep the leader is on
{ "filter_adjacent_location", {
terrain = 'C*,K*,C*^*,K*^*,*^K*,*^C*'
}} -- That are not one-hex keeps
}
if #keeps < 1 then
-- Skip if there aren't extra keeps to evaluate
-- In this situation we'd only switch keeps if we were running away
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
local enemy_leaders = get_reachable_enemy_leaders(leader, avoid_map)
for i,loc in ipairs(keeps) do
-- Only consider keeps within 2 turns movement
wesnoth.interface.handle_user_interact()
local path, cost = AH.find_path_with_avoid(leader, loc[1], loc[2], avoid_map)
local score = 0
-- Prefer closer keeps to enemy
local turns = math.ceil(cost/leader.max_moves)
if turns <= 2 then
score = 1/turns
for j,e in ipairs(enemy_leaders) do
score = score + 1 / M.distance_between(loc[1], loc[2], e.x, e.y)
end
if score > best_score then
best_score = score
best_loc = loc
best_turns = turns
best_path = path
end
end
end
-- If we're on a keep,
-- don't move to another keep unless it's much better when uncaptured villages are present
if best_score > 0 and wesnoth.terrain_types[wesnoth.current.map[leader]].keep then
local close_unowned_village = (wesnoth.map.find {
wml.tag['and']{
x = leader.x,
y = leader.y,
radius = leader.max_moves
},
gives_income = true,
owner_side = 0
})[1]
if close_unowned_village then
local score = 1/best_turns
for j,e in ipairs(enemy_leaders) do
-- count all distances as three less than they actually are
score = score + 1 / (M.distance_between(leader.x, leader.y, e.x, e.y) - 3)
end
if score > best_score then
best_score = 0
end
end
end
if best_score > 0 then
local next_hop = AH.next_hop(leader, nil, nil, { path = best_path, avoid_map = avoid_map })
if next_hop and ((next_hop[1] ~= leader.x) or (next_hop[2] ~= leader.y)) then
-- See if there is a nearby village that can be captured without delaying progress
local close_villages = wesnoth.map.find( {
wml.tag["and"]{ x = next_hop[1], y = next_hop[2], radius = leader.max_moves },
gives_income = true,
owner_side = 0 })
local cheapest_unit_cost = AH.get_cheapest_recruit_cost(leader)
for i,loc in ipairs(close_villages) do
wesnoth.interface.handle_user_interact()
local path_village, cost_village = AH.find_path_with_avoid(leader, loc[1], loc[2], avoid_map)
if cost_village <= leader.moves then
local dummy_leader = leader:clone()
dummy_leader.x = loc[1]
dummy_leader.y = loc[2]
local path_keep, cost_keep = wesnoth.paths.find_path(dummy_leader, best_loc[1], best_loc[2], avoid_map)
local turns_from_keep = math.ceil(cost_keep/leader.max_moves)
if turns_from_keep < best_turns
or (turns_from_keep == 1 and wesnoth.sides[wesnoth.current.side].gold < cheapest_unit_cost)
then
-- There is, go there instead
next_hop = loc
break
end
end
end
end
local leader_score = other_units_on_keep(leader)
best_score = best_score + leader_score
if (best_score > overall_best_score) then
overall_best_score = best_score
CS_leader_score = leader_score
data.CS_leader = leader
data.CS_leader_target = next_hop
end
end
end
if (overall_best_score > 0) then
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return CS_leader_score
end
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
function ca_castle_switch:execution(cfg, data, filter_own)
if AH.print_exec() then AH.print_ts(' Executing castle_switch CA') end
if AH.show_messages() then wesnoth.wml_actions.message { speaker = data.leader.id, message = 'Switching castles' } end
AH.robust_move_and_attack(ai, data.CS_leader, data.CS_leader_target, nil, { partial_move = true })
data.CS_leader, data.CS_leader_target = nil, nil
end
return ca_castle_switch
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Utilities/json.lua | 8 | 15666 | -----------------------------------------------------------------------------
-- JSON4Lua: JSON encoding / decoding support for the Lua language.
-- json Module.
-- Author: Craig Mason-Jones
-- Homepage: http://json.luaforge.net/
-- Version: 0.9.20
-- This module is released under the The GNU General Public License (GPL).
-- Please see LICENCE.txt for details.
--
-- USAGE:
-- This module exposes two functions:
-- encode(o)
-- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string.
-- decode(json_string)
-- Returns a Lua object populated with the data encoded in the JSON string json_string.
--
-- REQUIREMENTS:
-- compat-5.1 if using Lua 5.0
--
-- CHANGELOG
-- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix).
-- Fixed Lua 5.1 compatibility issues.
-- Introduced json.null to have null values in associative arrays.
-- encode() performance improvement (more than 50%) through table.concat rather than ..
-- Introduced decode ability to ignore /**/ comments in the JSON string.
-- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Imports and dependencies
-----------------------------------------------------------------------------
local math = math
local string = string
local table = table
local base = _G
-----------------------------------------------------------------------------
-- Module declaration
-----------------------------------------------------------------------------
Spring.Utilities.json = {}
setfenv(1,Spring.Utilities.json)
-- Public functions
-- Private functions
local decode_scanArray
local decode_scanComment
local decode_scanConstant
local decode_scanNumber
local decode_scanObject
local decode_scanString
local decode_scanWhitespace
local encodeString
local isArray
local isEncodable
-----------------------------------------------------------------------------
-- PUBLIC FUNCTIONS
-----------------------------------------------------------------------------
--- Encodes an arbitrary Lua object / variable.
-- @param v The Lua object / variable to be JSON encoded.
-- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
function encode (v)
-- Handle nil values
if v==nil then
return "null"
end
local vtype = base.type(v)
-- Handle strings
if vtype=='string' then
return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
end
-- Handle booleans
if vtype=='number' or vtype=='boolean' then
return base.tostring(v)
end
-- Handle tables
if vtype=='table' then
local rval = {}
-- Consider arrays separately
local bArray, maxCount = isArray(v)
if bArray then
for i = 1,maxCount do
table.insert(rval, encode(v[i]))
end
else -- An object, not an array
for i,j in base.pairs(v) do
if isEncodable(i) and isEncodable(j) then
table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
end
end
end
if bArray then
return '[' .. table.concat(rval,',') ..']'
else
return '{' .. table.concat(rval,',') .. '}'
end
end
-- Handle null values
if vtype=='function' and v==null then
return 'null'
end
base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
end
--- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
-- @param s The string to scan.
-- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
-- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
-- and the position of the first character after
-- the scanned JSON object.
function decode(s, startPos)
startPos = startPos and startPos or 1
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
local curChar = string.sub(s,startPos,startPos)
-- Object
if curChar=='{' then
return decode_scanObject(s,startPos)
end
-- Array
if curChar=='[' then
return decode_scanArray(s,startPos)
end
-- Number
if string.find("+-0123456789.e", curChar, 1, true) then
return decode_scanNumber(s,startPos)
end
-- String
if curChar==[["]] or curChar==[[']] then
return decode_scanString(s,startPos)
end
if string.sub(s,startPos,startPos+1)=='/*' then
return decode(s, decode_scanComment(s,startPos))
end
-- Otherwise, it must be a constant
return decode_scanConstant(s,startPos)
end
--- The null function allows one to specify a null value in an associative array (which is otherwise
-- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
function null()
return null -- so json.null() will also return null ;-)
end
-----------------------------------------------------------------------------
-- Internal, PRIVATE functions.
-- Following a Python-like convention, I have prefixed all these 'PRIVATE'
-- functions with an underscore.
-----------------------------------------------------------------------------
--- Scans an array from JSON into a Lua object
-- startPos begins at the start of the array.
-- Returns the array and the next starting position
-- @param s The string being scanned.
-- @param startPos The starting position for the scan.
-- @return table, int The scanned array as a table, and the position of the next character to scan.
function decode_scanArray(s,startPos)
local array = {} -- The return value
local stringLen = string.len(s)
base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
startPos = startPos + 1
-- Infinite loop for array elements
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
local curChar = string.sub(s,startPos,startPos)
if (curChar==']') then
return array, startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
object, startPos = decode(s,startPos)
table.insert(array,object)
until false
end
--- Scans a comment and discards the comment.
-- Returns the position of the next character following the comment.
-- @param string s The JSON string to scan.
-- @param int startPos The starting position of the comment
function decode_scanComment(s, startPos)
base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
local endPos = string.find(s,'*/',startPos+2)
base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
return endPos+2
end
--- Scans for given constants: true, false or null
-- Returns the appropriate Lua type, and the position of the next character to read.
-- @param s The string being scanned.
-- @param startPos The position in the string at which to start scanning.
-- @return object, int The object (true, false or nil) and the position at which the next character should be
-- scanned.
function decode_scanConstant(s, startPos)
local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
local constNames = {"true","false","null"}
for i,k in base.pairs(constNames) do
--print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
return consts[k], startPos + string.len(k)
end
end
base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
end
--- Scans a number from the JSON encoded string.
-- (in fact, also is able to scan numeric +- eqns, which is not
-- in the JSON spec.)
-- Returns the number, and the position of the next character
-- after the number.
-- @param s The string being scanned.
-- @param startPos The position at which to start scanning.
-- @return number, int The extracted number and the position of the next character to scan.
function decode_scanNumber(s,startPos)
local endPos = startPos+1
local stringLen = string.len(s)
local acceptableChars = "+-0123456789.e"
while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
and endPos<=stringLen
) do
endPos = endPos + 1
end
local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON object into a Lua object.
-- startPos begins at the start of the object.
-- Returns the object and the next starting position.
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return table, int The scanned object as a table and the position of the next character to scan.
function decode_scanObject(s,startPos)
local object = {}
local stringLen = string.len(s)
local key, value
base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
startPos = startPos + 1
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
local curChar = string.sub(s,startPos,startPos)
if (curChar=='}') then
return object,startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
-- Scan the key
key, startPos = decode(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
startPos = decode_scanWhitespace(s,startPos+1)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
value, startPos = decode(s,startPos)
object[key]=value
until false -- infinite loop while key-value pairs are found
end
--- Scans a JSON string from the opening inverted comma or single quote to the
-- end of the string.
-- Returns the string extracted as a Lua string,
-- and the position of the next non-string character
-- (after the closing inverted comma or single quote).
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return string, int The extracted string as a Lua string, and the next character to parse.
function decode_scanString(s,startPos)
base.assert(startPos, 'decode_scanString(..) called without start position')
local startChar = string.sub(s,startPos,startPos)
base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
local escaped = false
local endPos = startPos + 1
local bEnded = false
local stringLen = string.len(s)
repeat
local curChar = string.sub(s,endPos,endPos)
if not escaped then
if curChar==[[\]] then
escaped = true
else
bEnded = curChar==startChar
end
else
-- If we're escaped, we accept the current character come what may
escaped = false
end
endPos = endPos + 1
base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
until bEnded
local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON string skipping all whitespace from the current start position.
-- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
-- @param s The string being scanned
-- @param startPos The starting position where we should begin removing whitespace.
-- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
-- was reached.
function decode_scanWhitespace(s,startPos)
local whitespace=" \n\r\t"
local stringLen = string.len(s)
while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
startPos = startPos + 1
end
return startPos
end
--- Encodes a string to be JSON-compatible.
-- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
-- @param s The string to return as a JSON encoded (i.e. backquoted string)
-- @return The string appropriately escaped.
function encodeString(s)
s = string.gsub(s,'\\','\\\\')
s = string.gsub(s,'"','\\"')
s = string.gsub(s,"'","\\'")
s = string.gsub(s,'\n','\\n')
s = string.gsub(s,'\t','\\t')
return s
end
-- Determines whether the given Lua type is an array or a table / dictionary.
-- We consider any table an array if it has indexes 1..n for its n items, and no
-- other data in the table.
-- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
-- @param t The table to evaluate as an array
-- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
-- the second returned value is the maximum
-- number of indexed elements in the array.
function isArray(t)
--
-- CA modification (to reduce the size of the strings -> save network bandwidth)
--
local array_count = #t
local table_count = 0
for _ in base.pairs(t) do
table_count = table_count + 1
end
return (array_count == table_count), array_count
--[[
-- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
-- (with the possible exception of 'n')
local maxIndex = 0
for k,v in base.pairs(t) do
if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
if (not isEncodable(v)) then return false end -- All array elements must be encodable
maxIndex = math.max(maxIndex,k)
else
if (k=='n') then
if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
else -- Else of (k=='n')
if isEncodable(v) then return false end
end -- End of (k~='n')
end -- End of k,v not an indexed pair
end -- End of loop across all pairs
return true, maxIndex
--]]
end
--- Determines whether the given Lua object / table / variable can be JSON encoded. The only
-- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
-- In this implementation, all other types are ignored.
-- @param o The object to examine.
-- @return boolean True if the object should be JSON encoded, false if it should be ignored.
function isEncodable(o)
local t = base.type(o)
return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
end
| gpl-2.0 |
lxl1140989/dmsdk | feeds/luci/libs/px5g/lua/px5g/util.lua | 170 | 1148 | --[[
* px5g - Embedded x509 key and certificate generator based on PolarSSL
*
* Copyright (C) 2009 Steven Barth <steven@midlink.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License, version 2.1 as published by the Free Software Foundation.
]]--
local nixio = require "nixio"
local table = require "table"
module "px5g.util"
local preamble = {
key = "-----BEGIN RSA PRIVATE KEY-----",
cert = "-----BEGIN CERTIFICATE-----",
request = "-----BEGIN CERTIFICATE REQUEST-----"
}
local postamble = {
key = "-----END RSA PRIVATE KEY-----",
cert = "-----END CERTIFICATE-----",
request = "-----END CERTIFICATE REQUEST-----"
}
function der2pem(data, type)
local b64 = nixio.bin.b64encode(data)
local outdata = {preamble[type]}
for i = 1, #b64, 64 do
outdata[#outdata + 1] = b64:sub(i, i + 63)
end
outdata[#outdata + 1] = postamble[type]
outdata[#outdata + 1] = ""
return table.concat(outdata, "\n")
end
function pem2der(data)
local b64 = data:gsub({["\n"] = "", ["%-%-%-%-%-.-%-%-%-%-%-"] = ""})
return nixio.bin.b64decode(b64)
end | gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armscab.lua | 1 | 3186 | return {
armscab = {
acceleration = 0.01799999922514,
brakerate = 0.034000001847744,
buildcostenergy = 28000,
buildcostmetal = 1100,
buildpic = "ARMSCAB.DDS",
buildtime = 40000,
canmove = true,
category = "ALL TANK MOBILE WEAPON NOTSUB NOTSHIP NOTAIR NOTHOVER SURFACE",
corpse = "DEAD",
damagemodifier = 0.5,
description = "Mobile Anti-missile Defense",
energymake = 200,
energystorage = 1000,
explodeas = "LARGE_BUILDINGEX",
footprintx = 3,
footprintz = 3,
idleautoheal = 5,
idletime = 1800,
maxdamage = 780,
maxslope = 10,
maxvelocity = 1.7,
maxwaterdepth = 0,
movementclass = "TKBOT3",
name = "Scarab",
nochasecategory = "ALL",
objectname = "ARMSCAB",
radardistance = 50,
seismicsignature = 0,
selfdestructas = "LARGE_BUILDING",
sightdistance = 450,
smoothanim = true,
turnrate = 473,
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "0.0 -0.208756103516 6.21000671387",
collisionvolumescales = "55.2154541016 21.362487793 50.6700134277",
collisionvolumetype = "Box",
damage = 468,
description = "Scarab Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 3,
footprintz = 3,
height = 20,
hitdensity = 100,
metal = 934,
object = "ARMSCAB_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 234,
description = "Scarab Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 3,
footprintz = 3,
height = 4,
hitdensity = 100,
metal = 374,
object = "3X3D",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "kbarmmov",
},
select = {
[1] = "kbarmsel",
},
},
weapondefs = {
armscab_weapon = {
areaofeffect = 420,
avoidfriendly = false,
collidefriendly = false,
coverage = 1600,
craterboost = 0,
cratermult = 0,
energypershot = 6500,
explosiongenerator = "custom:FLASH4",
firestarter = 100,
flighttime = 120,
impulseboost = 0.12300000339746,
impulsefactor = 0.12300000339746,
interceptor = 1,
metalpershot = 150,
model = "amdrocket",
name = "Rocket",
noselfdamage = true,
range = 72000,
reloadtime = 2,
smoketrail = true,
soundhit = "xplomed4",
soundstart = "Rockhvy1",
stockpile = true,
stockpiletime = 90,
tolerance = 4000,
tracks = true,
turnrate = 99000,
weaponacceleration = 75,
weapontimer = 5,
weapontype = "StarburstLauncher",
weaponvelocity = 3000,
damage = {
default = 500,
},
},
},
weapons = {
[1] = {
badtargetcategory = "VTOL",
def = "ARMSCAB_WEAPON",
onlytargetcategory = "NOTSUB",
},
},
},
}
| gpl-2.0 |
agilul/software-renderer-love2d | main.lua | 1 | 4177 | -- Copyright 2016 Yat Hin Wong
vector = require "vector"
matrix = require "matrix"
function love.load()
imgWidth, imgHeight = 600, 600
love.window.setMode(imgWidth, imgHeight)
screenCenter = vector(imgWidth/2, imgHeight/2)
love.mouse.setPosition(screenCenter.x, screenCenter.y)
love.mouse.setVisible(false)
-- loads the vertex list of a Newell teapot
local index = 1
teapot = {}
for line in love.filesystem.lines("teapot") do
local _, _, x, y, z = string.find(line, "(%-?%d+%.%d+),(%-?%d+%.%d+),(%-?%d+%.%d+)")
teapot[index] = vector(x, y, z)
index = index + 1
end
forwardVec = vector(0, 0, -1)
upVec = vector(0, 1, 0)
leftVec = upVec:cross(forwardVec)
cameraMatrix = matrix.createIdentityMatrix()
cameraMatrix[4][2] = 5
cameraMatrix[4][3] = 10
worldToCamera = matrix.inverse(cameraMatrix)
-- creates a perspective projection matrix with FoV, near and far planes
projMatrix = matrix.createProjectionMatrix(90, 0.1, 100)
instructions = true
instructionsTimeout = 10
end
function love.update(dt)
if love.keyboard.isDown("escape") then
love.event.quit()
end
local rotationVec, rotationAngle = vector(1, 0, 0), 0
local dMousePos = vector(love.mouse.getPosition()) - screenCenter
love.mouse.setPosition(imgWidth/2, imgHeight/2)
-- yaw
if math.abs(dMousePos.x) > 0 then
rotationVec = upVec
rotationAngle = -dMousePos.x * dt / 30
end
cameraMatrix = matrix.multiply(matrix.createRotationMatrix(rotationVec, rotationAngle), cameraMatrix)
-- pitch
if math.abs(dMousePos.y) > 0 then
rotationVec = leftVec
rotationAngle = -dMousePos.y * dt / 30
end
cameraMatrix = matrix.multiply(matrix.createRotationMatrix(rotationVec, rotationAngle), cameraMatrix)
-- roll
if love.keyboard.isDown("q") then
rotationVec = forwardVec
rotationAngle = 1 * dt
elseif love.keyboard.isDown("e") then
rotationVec = forwardVec
rotationAngle = -1 * dt
end
cameraMatrix = matrix.multiply(matrix.createRotationMatrix(rotationVec, rotationAngle), cameraMatrix)
-- panning controls
local translateVec = vector(0, 0, 0)
if love.keyboard.isDown("w") or love.keyboard.isDown("up") then
translateVec = translateVec - upVec * dt
elseif love.keyboard.isDown("s") or love.keyboard.isDown("down") then
translateVec = translateVec + upVec * dt
end
if love.keyboard.isDown("a") or love.keyboard.isDown("left") then
translateVec = translateVec + leftVec * dt
elseif love.keyboard.isDown("d") or love.keyboard.isDown("right") then
translateVec = translateVec - leftVec * dt
end
if love.keyboard.isDown("r") then
translateVec = translateVec - forwardVec * dt
elseif love.keyboard.isDown("f") then
translateVec = translateVec + forwardVec * dt
end
translateVec:normalizeInplace()
cameraMatrix = matrix.multiply(matrix.createTranslationMatrix(translateVec), cameraMatrix)
-- move by moving the rest
-- http://futurama.wikia.com/wiki/Dark_matter_engine
worldToCamera = matrix.inverse(cameraMatrix)
-- transforms the world from 3D space to 2D screen
points = {}
index = 0
for i, v in ipairs(teapot) do
local cameraVert = v:multVecMatrix(worldToCamera)
if cameraVert * forwardVec > 0 then
local projected = cameraVert:multVecMatrix(projMatrix)
if projected.x >= -1 and projected.x <= 1 and projected.y >= -1 and projected.y <= 1 then
local screen_x = math.min(imgWidth - 1, math.floor((projected.x + 1) * 0.5 * imgWidth))
local screen_y = math.min(imgHeight - 1, math.floor((projected.y + 1) * 0.5 * imgHeight))
points[index] = {screen_x, screen_y}
index = index + 1
end
end
end
if instructions then
if instructionsTimeout < 0 then
instructions = false
end
instructionsTimeout = instructionsTimeout - dt
end
end
function love.draw()
love.graphics.setPointSize(2)
love.graphics.points(points);
if instructions then
love.graphics.setColor(255, 255, 255)
love.graphics.printf("WASD to move up/left/down/right\nF/R to move forward/backward\nMouse to yaw/pitch\nQ/E to roll\nESC to exit", 0, 0, imgWidth, "left", 0, 2)
end
end
| mit |
helingping/Urho3D | Source/Urho3D/LuaScript/pkgs/ToCppHook.lua | 9 | 7914 | --
-- Copyright (c) 2008-2017 the Urho3D project.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
local toWrite = {}
local currentString = ''
local out
local WRITE, OUTPUT = write, output
function output(s)
out = _OUTPUT
output = OUTPUT -- restore
output(s)
end
function write(a)
if out == _OUTPUT then
currentString = currentString .. a
if string.sub(currentString,-1) == '\n' then
toWrite[#toWrite+1] = currentString
currentString = ''
end
else
WRITE(a)
end
end
function post_output_hook(package)
local result = table.concat(toWrite)
local function replace(pattern, replacement)
local k = 0
local nxt, currentString = 1, ''
repeat
local s, e = string.find(result, pattern, nxt, true)
if e then
currentString = currentString .. string.sub(result, nxt, s-1) .. replacement
nxt = e + 1
k = k + 1
end
until not e
result = currentString..string.sub(result, nxt)
end
replace("\t", " ")
replace([[#ifndef __cplusplus
#include "stdlib.h"
#endif
#include "string.h"
#include "tolua++.h"]], [[//
// Copyright (c) 2008-2017 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Precompiled.h"
#include <toluapp/tolua++.h>
#include "LuaScript/ToluaUtils.h"
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
#endif]])
if not _extra_parameters["Urho3D"] then
replace([[#include "LuaScript/ToluaUtils.h"]], [[#include <Urho3D/LuaScript/ToluaUtils.h>]])
end
-- Special handling for vector to table conversion which would simplify the implementation of the template functions
result = string.gsub(result, "ToluaIs(P?O?D?)Vector([^\"]-)\"c?o?n?s?t? ?P?O?D?Vector<([^*>]-)%*?>\"", "ToluaIs%1Vector%2\"%3\"")
result = string.gsub(result, "ToluaPush(P?O?D?)Vector([^\"]-)\"c?o?n?s?t? ?P?O?D?Vector<([^*>]-)%*?>\"", "ToluaPush%1Vector%2\"%3\"")
result = string.gsub(result, "@1%(", "(\"\",") -- is_pointer overload uses const char* as signature
result = string.gsub(result, "@2%(", "(0.f,") -- is_arithmetic overload uses double as signature
WRITE(result)
WRITE([[
#if __clang__
#pragma clang diagnostic pop
#endif]])
end
_push_functions['Component'] = "ToluaPushObject"
_push_functions['Resource'] = "ToluaPushObject"
_push_functions['UIElement'] = "ToluaPushObject"
-- Is Urho3D Vector type.
function urho3d_is_vector(t)
return t:find("Vector<") ~= nil
end
-- Is Urho3D PODVector type.
function urho3d_is_podvector(t)
return t:find("PODVector<") ~= nil
end
local old_get_push_function = get_push_function
local old_get_to_function = get_to_function
local old_get_is_function = get_is_function
function is_pointer(t)
return t:find("*>")
end
function is_arithmetic(t)
for _, type in pairs({ "char", "short", "int", "unsigned", "long", "float", "double", "bool" }) do
_, pos = t:find(type)
if pos ~= nil and t:sub(pos + 1, pos + 1) ~= "*" then return true end
end
return false
end
function overload_if_necessary(t)
return is_pointer(t) and "@1" or (is_arithmetic(t) and "@2" or "")
end
function get_push_function(t)
if not urho3d_is_vector(t) then
return old_get_push_function(t)
end
local T = t:match("<.*>")
if not urho3d_is_podvector(t) then
return "ToluaPushVector" .. T
else
return "ToluaPushPODVector" .. T .. overload_if_necessary(T)
end
end
function get_to_function(t)
if not urho3d_is_vector(t) then
return old_get_to_function(t)
end
local T = t:match("<.*>")
if not urho3d_is_podvector(t) then
return "ToluaToVector" .. T
else
return "ToluaToPODVector" .. T .. overload_if_necessary(T)
end
end
function get_is_function(t)
if not urho3d_is_vector(t) then
return old_get_is_function(t)
end
local T = t:match("<.*>")
if not urho3d_is_podvector(t) then
return "ToluaIsVector" .. T
else
return "ToluaIsPODVector" .. T .. overload_if_necessary(T)
end
end
function get_property_methods_hook(ptype, name)
if ptype == "get_set" then
local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2)
return "Get"..Name, "Set"..Name
end
if ptype == "is_set" then
local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2)
return "Is"..Name, "Set"..Name
end
if ptype == "has_set" then
local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2)
return "Has"..Name, "Set"..Name
end
if ptype == "no_prefix" then
local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2)
return Name, "Set"..Name
end
end
-- Rudimentary checker to prevent function overloads being declared in a wrong order
-- The checker assumes function overloads are declared in group one after another within a same pkg file
-- The checker only checks for single argument function at the moment, but it can be extended to support more when it is necessary
local overload_checker = {name="", has_number=false}
function pre_call_hook(self)
if table.getn(self.args) ~= 1 then return end
if overload_checker.name ~= self.name then
overload_checker.name = self.name
overload_checker.has_number = false
end
local t = self.args[1].type
if overload_checker.has_number then
if t:find("String") or t:find("char*") then warning(self:inclass() .. ":" .. self.name .. " has potential binding problem: number overload becomes dead code if it is declared before string overload") end
else
overload_checker.has_number = t ~= "bool" and is_arithmetic(t)
end
end
| mit |
Anarchid/Zero-K | LuaUI/Widgets/gui_icon_sets.lua | 12 | 3482 | function widget:GetInfo() return {
name = "Icon Sets",
desc = "Manages alternate icon/buildpic sets.",
author = "Sprung",
license = "PD",
layer = 1,
enabled = true,
} end
options_path = 'Settings/Graphics/Unit Visibility/Radar Icons'
options_order = { 'coniconchassis', 'ships' }
options = {
coniconchassis = {
name = 'Show constructor chassis',
desc = 'Do constructor icons show chassis? Conveys more information but reduces visibility somewhat.',
type = 'bool',
value = false,
noHotkey = true,
OnChange = function(self)
if not self.value then
Spring.SetUnitDefIcon(UnitDefNames["cloakcon"].id, "builder")
Spring.SetUnitDefIcon(UnitDefNames["shieldcon"].id, "builder")
Spring.SetUnitDefIcon(UnitDefNames["vehcon"].id, "builder")
Spring.SetUnitDefIcon(UnitDefNames["tankcon"].id, "builder")
Spring.SetUnitDefIcon(UnitDefNames["amphcon"].id, "builder")
Spring.SetUnitDefIcon(UnitDefNames["jumpcon"].id, "builder")
Spring.SetUnitDefIcon(UnitDefNames["spidercon"].id, "builder")
Spring.SetUnitDefIcon(UnitDefNames["hovercon"].id, "builder")
Spring.SetUnitDefIcon(UnitDefNames["shipcon"].id, "builder")
else
Spring.SetUnitDefIcon(UnitDefNames["cloakcon"].id, "kbotbuilder")
Spring.SetUnitDefIcon(UnitDefNames["shieldcon"].id, "walkerbuilder")
Spring.SetUnitDefIcon(UnitDefNames["vehcon"].id, "vehiclebuilder")
Spring.SetUnitDefIcon(UnitDefNames["tankcon"].id, "tankbuilder")
Spring.SetUnitDefIcon(UnitDefNames["amphcon"].id, "amphbuilder")
Spring.SetUnitDefIcon(UnitDefNames["jumpcon"].id, "jumpjetbuilder")
Spring.SetUnitDefIcon(UnitDefNames["spidercon"].id, "spiderbuilder")
Spring.SetUnitDefIcon(UnitDefNames["hovercon"].id, "hoverbuilder")
if options.ships.value then
Spring.SetUnitDefIcon(UnitDefNames["shipcon"].id, "shipbuilder_alt")
else
Spring.SetUnitDefIcon(UnitDefNames["shipcon"].id, "shipbuilder")
end
end
end,
},
ships = {
name = 'Use standard ship icons',
desc = 'Do ships use the standarized chassis-role icons instead of hull shape pictograms?',
type = 'bool',
value = false,
noHotkey = true,
OnChange = function(self)
if not self.value then
Spring.SetUnitDefIcon(UnitDefNames["shipscout"].id, "shipscout")
Spring.SetUnitDefIcon(UnitDefNames["shiptorpraider"].id, "shiptorpraider")
Spring.SetUnitDefIcon(UnitDefNames["shipriot"].id, "shipriot")
Spring.SetUnitDefIcon(UnitDefNames["shipskirm"].id, "shipskirm")
Spring.SetUnitDefIcon(UnitDefNames["shipassault"].id, "shipassault")
Spring.SetUnitDefIcon(UnitDefNames["shiparty"].id, "shiparty")
Spring.SetUnitDefIcon(UnitDefNames["shipaa"].id, "shipaa")
if options.coniconchassis.value then
Spring.SetUnitDefIcon(UnitDefNames["shipcon"].id, "shipbuilder")
end
else
Spring.SetUnitDefIcon(UnitDefNames["shipscout"].id, "shipscout_alt")
Spring.SetUnitDefIcon(UnitDefNames["shiptorpraider"].id, "shipraider_alt")
Spring.SetUnitDefIcon(UnitDefNames["shipriot"].id, "shipriot_alt")
Spring.SetUnitDefIcon(UnitDefNames["shipskirm"].id, "shipskirm_alt")
Spring.SetUnitDefIcon(UnitDefNames["shipassault"].id, "shipassault_alt")
Spring.SetUnitDefIcon(UnitDefNames["shiparty"].id, "shiparty_alt")
Spring.SetUnitDefIcon(UnitDefNames["shipaa"].id, "shipaa_alt")
if options.coniconchassis.value then
Spring.SetUnitDefIcon(UnitDefNames["shipcon"].id, "shipbuilder_alt")
end
end
end,
},
}
| gpl-2.0 |
Anarchid/Zero-K | units/factoryveh.lua | 4 | 3291 | return { factoryveh = {
unitname = [[factoryveh]],
name = [[Rover Assembly]],
description = [[Produces Rovers]],
acceleration = 0,
brakeRate = 0,
buildCostMetal = Shared.FACTORY_COST,
buildDistance = Shared.FACTORY_PLATE_RANGE,
builder = true,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 11,
buildingGroundDecalSizeY = 11,
buildingGroundDecalType = [[factoryveh_aoplane.dds]],
buildoptions = {
[[vehcon]],
[[vehscout]],
[[vehraid]],
[[vehsupport]],
[[vehriot]],
[[vehassault]],
[[vehcapture]],
[[veharty]],
[[vehheavyarty]],
[[vehaa]],
},
buildPic = [[factoryveh.png]],
canMove = true,
canPatrol = true,
category = [[SINK UNARMED]],
collisionVolumeOffsets = [[0 -8 -25]],
collisionVolumeScales = [[120 44 44]],
collisionVolumeType = [[ellipsoid]],
selectionVolumeOffsets = [[0 0 10]],
selectionVolumeScales = [[120 70 112]],
selectionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
ploppable = 1,
sortName = [[2]],
default_spacing = 8,
solid_factory = 3,
aimposoffset = [[0 0 -35]],
midposoffset = [[0 0 -10]],
modelradius = [[70]],
unstick_help = 1,
selectionscalemult = 1,
factorytab = 1,
shared_energy_gen = 1,
parent_of_plate = [[plateveh]],
},
energyUse = 0,
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 8,
footprintZ = 8,
iconType = [[facvehicle]],
idleAutoHeal = 5,
idleTime = 1800,
levelGround = false,
maxDamage = 4000,
maxSlope = 15,
maxVelocity = 0,
maxWaterDepth = 0,
moveState = 1,
noAutoFire = false,
objectName = [[factoryveh.dae]],
script = [[factoryveh.lua]],
selfDestructAs = [[LARGE_BUILDINGEX]],
showNanoSpray = false,
sightDistance = 273,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = Shared.FACTORY_BUILDPOWER,
yardMap = "oooooooo oooooooo oooooooo yccccccy yccccccy yccccccy yccccccy yccccccy",
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 8,
footprintZ = 8,
object = [[factoryveh_d.dae]],
collisionVolumeOffsets = [[0 0 -20]],
collisionVolumeScales = [[110 35 75]],
collisionVolumeType = [[box]],
},
HEAP = {
blocking = false,
footprintX = 7,
footprintZ = 7,
object = [[debris4x4c.s3o]],
},
},
} }
| gpl-2.0 |
roger-zhao/ardupilot-3.2 | Tools/CHDK-Scripts/kap_uav.lua | 183 | 28512 | --[[
KAP UAV Exposure Control Script v3.1
-- Released under GPL by waterwingz and wayback/peabody
http://chdk.wikia.com/wiki/KAP_%26_UAV_Exposure_Control_Script
@title KAP UAV 3.1
@param i Shot Interval (sec)
@default i 15
@range i 2 120
@param s Total Shots (0=infinite)
@default s 0
@range s 0 10000
@param j Power off when done?
@default j 0
@range j 0 1
@param e Exposure Comp (stops)
@default e 6
@values e -2.0 -1.66 -1.33 -1.0 -0.66 -0.33 0.0 0.33 0.66 1.00 1.33 1.66 2.00
@param d Start Delay Time (sec)
@default d 0
@range d 0 10000
@param y Tv Min (sec)
@default y 0
@values y None 1/60 1/100 1/200 1/400 1/640
@param t Target Tv (sec)
@default t 5
@values t 1/100 1/200 1/400 1/640 1/800 1/1000 1/1250 1/1600 1/2000
@param x Tv Max (sec)
@default x 3
@values x 1/1000 1/1250 1/1600 1/2000 1/5000 1/10000
@param f Av Low(f-stop)
@default f 4
@values f 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param a Av Target (f-stop)
@default a 7
@values a 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param m Av Max (f-stop)
@default m 13
@values m 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param p ISO Min
@default p 1
@values p 80 100 200 400 800 1250 1600
@param q ISO Max1
@default q 2
@values q 100 200 400 800 1250 1600
@param r ISO Max2
@default r 3
@values r 100 200 400 800 1250 1600
@param n Allow use of ND filter?
@default n 1
@values n No Yes
@param z Zoom position
@default z 0
@values z Off 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
@param c Focus @ Infinity Mode
@default c 0
@values c None @Shot AFL MF
@param v Video Interleave (shots)
@default v 0
@values v Off 1 5 10 25 50 100
@param w Video Duration (sec)
@default w 10
@range w 5 300
@param u USB Shot Control?
@default u 0
@values u None On/Off OneShot PWM
@param b Backlight Off?
@default b 0
@range b 0 1
@param l Logging
@default l 3
@values l Off Screen SDCard Both
--]]
props=require("propcase")
capmode=require("capmode")
-- convert user parameter to usable variable names and values
tv_table = { -320, 576, 640, 736, 832, 896, 928, 960, 992, 1024, 1056, 1180, 1276}
tv96target = tv_table[t+3]
tv96max = tv_table[x+8]
tv96min = tv_table[y+1]
sv_table = { 381, 411, 507, 603, 699, 761, 795 }
sv96min = sv_table[p+1]
sv96max1 = sv_table[q+2]
sv96max2 = sv_table[r+2]
av_table = { 171, 192, 218, 265, 285, 322, 347, 384, 417, 446, 477, 510, 543, 576 }
av96target = av_table[a+1]
av96minimum = av_table[f+1]
av96max = av_table[m+1]
ec96adjust = (e - 6)*32
video_table = { 0, 1, 5, 10, 25, 50, 100 }
video_mode = video_table[v+1]
video_duration = w
interval = i*1000
max_shots = s
poff_if_done = j
start_delay = d
backlight = b
log_mode= l
focus_mode = c
usb_mode = u
if ( z==0 ) then zoom_setpoint = nil else zoom_setpoint = (z-1)*10 end
-- initial configuration values
nd96offset=3*96 -- ND filter's number of equivalent f-stops (f * 96)
infx = 50000 -- focus lock distance in mm (approximately 55 yards)
shot_count = 0 -- shot counter
blite_timer = 300 -- backlight off delay in 100mSec increments
old_console_timeout = get_config_value( 297 )
shot_request = false -- pwm mode flag to request a shot be taken
-- check camera Av configuration ( variable aperture and/or ND filter )
if n==0 then -- use of nd filter allowed?
if get_nd_present()==1 then -- check for ND filter only
Av_mode = 0 -- 0 = ND disabled and no iris available
else
Av_mode = 1 -- 1 = ND disabled and iris available
end
else
Av_mode = get_nd_present()+1 -- 1 = iris only , 2=ND filter only, 3= both ND & iris
end
function printf(...)
if ( log_mode == 0) then return end
local str=string.format(...)
if (( log_mode == 1) or (log_mode == 3)) then print(str) end
if ( log_mode > 1 ) then
local logname="A/KAP.log"
log=io.open(logname,"a")
log:write(os.date("%Y%b%d %X ")..string.format(...),"\n")
log:close()
end
end
tv_ref = { -- note : tv_ref values set 1/2 way between shutter speed values
-608, -560, -528, -496, -464, -432, -400, -368, -336, -304,
-272, -240, -208, -176, -144, -112, -80, -48, -16, 16,
48, 80, 112, 144, 176, 208, 240, 272, 304, 336,
368, 400, 432, 464, 496, 528, 560, 592, 624, 656,
688, 720, 752, 784, 816, 848, 880, 912, 944, 976,
1008, 1040, 1072, 1096, 1129, 1169, 1192, 1225, 1265, 1376 }
tv_str = {
">64",
"64", "50", "40", "32", "25", "20", "16", "12", "10", "8.0",
"6.0", "5.0", "4.0", "3.2", "2.5", "2.0", "1.6", "1.3", "1.0", "0.8",
"0.6", "0.5", "0.4", "0.3", "1/4", "1/5", "1/6", "1/8", "1/10", "1/13",
"1/15", "1/20", "1/25", "1/30", "1/40", "1/50", "1/60", "1/80", "1/100", "1/125",
"1/160", "1/200", "1/250", "1/320", "1/400", "1/500", "1/640", "1/800", "1/1000","1/1250",
"1/1600","1/2000","1/2500","1/3200","1/4000","1/5000","1/6400","1/8000","1/10000","hi" }
function print_tv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #tv_ref) and (val > tv_ref[i]) do i=i+1 end
return tv_str[i]
end
av_ref = { 160, 176, 208, 243, 275, 304, 336, 368, 400, 432, 464, 480, 496, 512, 544, 592, 624, 656, 688, 720, 752, 784 }
av_str = {"n/a","1.8", "2.0","2.2","2.6","2.8","3.2","3.5","4.0","4.5","5.0","5.6","5.9","6.3","7.1","8.0","9.0","10.0","11.0","13.0","14.0","16.0","hi"}
function print_av(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #av_ref) and (val > av_ref[i]) do i=i+1 end
return av_str[i]
end
sv_ref = { 370, 397, 424, 456, 492, 523, 555, 588, 619, 651, 684, 731, 779, 843, 907 }
sv_str = {"n/a","80","100","120","160","200","250","320","400","500","640","800","1250","1600","3200","hi"}
function print_sv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #sv_ref) and (val > sv_ref[i]) do i=i+1 end
return sv_str[i]
end
function pline(message, line) -- print line function
fg = 258 bg=259
end
-- switch between shooting and playback modes
function switch_mode( m )
if ( m == 1 ) then
if ( get_mode() == false ) then
set_record(1) -- switch to shooting mode
while ( get_mode() == false ) do
sleep(100)
end
sleep(1000)
end
else
if ( get_mode() == true ) then
set_record(0) -- switch to playback mode
while ( get_mode() == true ) do
sleep(100)
end
sleep(1000)
end
end
end
-- focus lock and unlock
function lock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if ( focus_mode == 2 ) then -- method 1 : set_aflock() command enables MF
if (chdk_version==120) then
set_aflock(1)
set_prop(props.AF_LOCK,1)
else
set_aflock(1)
end
if (get_prop(props.AF_LOCK) == 1) then printf(" AFL enabled") else printf(" AFL failed ***") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOn") == -1 then
call_event_proc("PT_MFOn")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOn") == -1 then
call_event_proc("MFOn")
end
end
if (get_prop(props.FOCUS_MODE) == 0 ) then -- MF not set - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(1) == 0 ) then set_aflock(1) end -- as a fall back, try setting AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 1) then printf(" MF enabled") else printf(" MF enable failed ***") end
end
sleep(1000)
set_focus(infx)
sleep(1000)
end
end
function unlock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if (focus_mode == 2 ) then -- method 1 : AFL
if (chdk_version==120) then
set_aflock(0)
set_prop(props.AF_LOCK,0)
else
set_aflock(0)
end
if (get_prop(props.AF_LOCK) == 0) then printf(" AFL unlocked") else printf(" AFL unlock failed") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOff") == -1 then
call_event_proc("PT_MFOff")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOff") == -1 then
call_event_proc("MFOff")
end
end
if (get_prop(props.FOCUS_MODE) == 1 ) then -- MF not reset - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(0) == 0 ) then set_aflock(0) end -- fall back so reset AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 0) then printf(" MF disabled") else printf(" MF disable failed") end
end
sleep(100)
end
end
-- zoom position
function update_zoom(zpos)
local count = 0
if(zpos ~= nil) then
zstep=((get_zoom_steps()-1)*zpos)/100
printf("setting zoom to "..zpos.." percent step="..zstep)
sleep(200)
set_zoom(zstep)
sleep(2000)
press("shoot_half")
repeat
sleep(100)
count = count + 1
until (get_shooting() == true ) or (count > 40 )
release("shoot_half")
end
end
-- restore camera settings on shutdown
function restore()
set_config_value(121,0) -- USB remote disable
set_config_value(297,old_console_timeout) -- restore console timeout value
if (backlight==1) then set_lcd_display(1) end -- display on
unlock_focus()
if( zoom_setpoint ~= nil ) then update_zoom(0) end
if( shot_count >= max_shots) and ( max_shots > 1) then
if ( poff_if_done == 1 ) then -- did script ending because # of shots done ?
printf("power off - shot count at limit") -- complete power down
sleep(2000)
post_levent_to_ui('PressPowerButton')
else
set_record(0) end -- just retract lens
end
end
-- Video mode
function check_video(shot)
local capture_mode
if ((video_mode>0) and(shot>0) and (shot%video_mode == 0)) then
unlock_focus()
printf("Video mode started. Button:"..tostring(video_button))
if( video_button ) then
click "video"
else
capture_mode=capmode.get()
capmode.set('VIDEO_STD')
press("shoot_full")
sleep(300)
release("shoot_full")
end
local end_second = get_day_seconds() + video_duration
repeat
wait_click(500)
until (is_key("menu")) or (get_day_seconds() > end_second)
if( video_button ) then
click "video"
else
press("shoot_full")
sleep(300)
release("shoot_full")
capmode.set(capture_mode)
end
printf("Video mode finished.")
sleep(1000)
lock_focus()
return(true)
else
return(false)
end
end
-- PWM USB pulse functions
function ch1up()
printf(" * usb pulse = ch1up")
shot_request = true
end
function ch1mid()
printf(" * usb pulse = ch1mid")
if ( get_mode() == false ) then
switch_mode(1)
lock_focus()
end
end
function ch1down()
printf(" * usb pulse = ch1down")
switch_mode(0)
end
function ch2up()
printf(" * usb pulse = ch2up")
update_zoom(100)
end
function ch2mid()
printf(" * usb pulse = ch2mid")
if ( zoom_setpoint ~= nil ) then update_zoom(zoom_setpoint) else update_zoom(50) end
end
function ch2down()
printf(" * usb pulse = ch2down")
update_zoom(0)
end
function pwm_mode(pulse_width)
if pulse_width > 0 then
if pulse_width < 5 then ch1up()
elseif pulse_width < 8 then ch1mid()
elseif pulse_width < 11 then ch1down()
elseif pulse_width < 14 then ch2up()
elseif pulse_width < 17 then ch2mid()
elseif pulse_width < 20 then ch2down()
else printf(" * usb pulse width error") end
end
end
-- Basic exposure calculation using shutter speed and ISO only
-- called for Tv-only and ND-only cameras (cameras without an iris)
function basic_tv_calc()
tv96setpoint = tv96target
av96setpoint = nil
local min_av = get_prop(props.MIN_AV)
-- calculate required ISO setting
sv96setpoint = tv96setpoint + min_av - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max2 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max2 -- clamp at max2 ISO if so
tv96setpoint = math.max(bv96meter+sv96setpoint-min_av,tv96min) -- recalculate required shutter speed down to Tv min
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - min_av -- recalculate required shutter speed and hope for the best
end
end
-- Basic exposure calculation using shutter speed, iris and ISO
-- called for iris-only and "both" cameras (cameras with an iris & ND filter)
function basic_iris_calc()
tv96setpoint = tv96target
av96setpoint = av96target
-- calculate required ISO setting
sv96setpoint = tv96setpoint + av96setpoint - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max1 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max1 -- clamp at first ISO limit
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint < av96min ) then -- check if new setting is goes below lowest f-stop
av96setpoint = av96min -- clamp at lowest f-stop
sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- recalculate ISO setting
if (sv96setpoint > sv96max2 ) then -- check if the result is above max2 ISO
sv96setpoint = sv96max2 -- clamp at highest ISO setting if so
tv96setpoint = math.max(bv96meter+sv96setpoint-av96setpoint,tv96min) -- recalculate required shutter speed down to tv minimum
end
end
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate required shutter speed
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
tv96setpoint = tv96max -- clamp at maximum shutter speed if so
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint > av96max ) then -- check if new setting is goes above highest f-stop
av96setpoint = av96max -- clamp at highest f-stop
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate shutter speed needed and hope for the best
end
end
end
end
-- calculate exposure for cams without adjustable iris or ND filter
function exposure_Tv_only()
insert_ND_filter = nil
basic_tv_calc()
end
-- calculate exposure for cams with ND filter only
function exposure_NDfilter()
insert_ND_filter = false
basic_tv_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_tv_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- calculate exposure for cams with adjustable iris only
function exposure_iris()
insert_ND_filter = nil
basic_iris_calc()
end
-- calculate exposure for cams with both adjustable iris and ND filter
function exposure_both()
insert_ND_filter = false -- NOTE : assume ND filter never used automatically by Canon firmware
basic_iris_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_iris_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- ========================== Main Program =================================
set_console_layout(1 ,1, 45, 14 )
printf("KAP 3.1 started - press MENU to exit")
bi=get_buildinfo()
printf("%s %s-%s %s %s %s", bi.version, bi.build_number, bi.build_revision, bi.platform, bi.platsub, bi.build_date)
chdk_version= tonumber(string.sub(bi.build_number,1,1))*100 + tonumber(string.sub(bi.build_number,3,3))*10 + tonumber(string.sub(bi.build_number,5,5))
if ( tonumber(bi.build_revision) > 0 ) then
build = tonumber(bi.build_revision)
else
build = tonumber(string.match(bi.build_number,'-(%d+)$'))
end
if ((chdk_version<120) or ((chdk_version==120)and(build<3276)) or ((chdk_version==130)and(build<3383))) then
printf("CHDK 1.2.0 build 3276 or higher required")
else
if( props.CONTINUOUS_AF == nil ) then caf=-999 else caf = get_prop(props.CONTINUOUS_AF) end
if( props.SERVO_AF == nil ) then saf=-999 else saf = get_prop(props.SERVO_AF) end
cmode = capmode.get_name()
printf("Mode:%s,Continuous_AF:%d,Servo_AF:%d", cmode,caf,saf)
printf(" Tv:"..print_tv(tv96target).." max:"..print_tv(tv96max).." min:"..print_tv(tv96min).." ecomp:"..(ec96adjust/96).."."..(math.abs(ec96adjust*10/96)%10) )
printf(" Av:"..print_av(av96target).." minAv:"..print_av(av96minimum).." maxAv:"..print_av(av96max) )
printf(" ISOmin:"..print_sv(sv96min).." ISO1:"..print_sv(sv96max1).." ISO2:"..print_sv(sv96max2) )
printf(" MF mode:"..focus_mode.." Video:"..video_mode.." USB:"..usb_mode)
printf(" AvM:"..Av_mode.." int:"..(interval/1000).." Shts:"..max_shots.." Dly:"..start_delay.." B/L:"..backlight)
sleep(500)
if (start_delay > 0 ) then
printf("entering start delay of ".. start_delay.." seconds")
sleep( start_delay*1000 )
end
-- enable USB remote in USB remote moded
if (usb_mode > 0 ) then
set_config_value(121,1) -- make sure USB remote is enabled
if (get_usb_power(1) == 0) then -- can we start ?
printf("waiting on USB signal")
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
else sleep(1000) end
printf("USB signal received")
end
-- switch to shooting mode
switch_mode(1)
-- set zoom position
update_zoom(zoom_setpoint)
-- lock focus at infinity
lock_focus()
-- disable flash and AF assist lamp
set_prop(props.FLASH_MODE, 2) -- flash off
set_prop(props.AF_ASSIST_BEAM,0) -- AF assist off if supported for this camera
set_config_value( 297, 60) -- set console timeout to 60 seconds
if (usb_mode > 2 ) then repeat until (get_usb_power(2) == 0 ) end -- flush pulse buffer
next_shot_time = get_tick_count()
script_exit = false
if( get_video_button() == 1) then video_button = true else video_button = false end
set_console_layout(2 ,0, 45, 4 )
repeat
if( ( (usb_mode < 2 ) and ( next_shot_time <= get_tick_count() ) )
or ( (usb_mode == 2 ) and (get_usb_power(2) > 0 ) )
or ( (usb_mode == 3 ) and (shot_request == true ) ) ) then
-- time to insert a video sequence ?
if( check_video(shot_count) == true) then next_shot_time = get_tick_count() end
-- intervalometer timing
next_shot_time = next_shot_time + interval
-- set focus at infinity ? (maybe redundant for AFL & MF mode but makes sure its set right)
if (focus_mode > 0) then
set_focus(infx)
sleep(100)
end
-- check exposure
local count = 0
local timeout = false
press("shoot_half")
repeat
sleep(50)
count = count + 1
if (count > 40 ) then timeout = true end
until (get_shooting() == true ) or (timeout == true)
-- shoot in auto mode if meter reading invalid, else calculate new desired exposure
if ( timeout == true ) then
release("shoot_half")
repeat sleep(50) until get_shooting() == false
shoot() -- shoot in Canon auto mode if we don't have a valid meter reading
shot_count = shot_count + 1
printf(string.format('IMG_%04d.JPG',get_exp_count()).." : shot in auto mode, meter reading invalid")
else
-- get meter reading values (and add in exposure compensation)
bv96raw=get_bv96()
bv96meter=bv96raw-ec96adjust
tv96meter=get_tv96()
av96meter=get_av96()
sv96meter=get_sv96()
-- set minimum Av to larger of user input or current min for zoom setting
av96min= math.max(av96minimum,get_prop(props.MIN_AV))
if (av96target < av96min) then av96target = av96min end
-- calculate required setting for current ambient light conditions
if (Av_mode == 1) then exposure_iris()
elseif (Av_mode == 2) then exposure_NDfilter()
elseif (Av_mode == 3) then exposure_both()
else exposure_Tv_only()
end
-- set up all exposure overrides
set_tv96_direct(tv96setpoint)
set_sv96(sv96setpoint)
if( av96setpoint ~= nil) then set_av96_direct(av96setpoint) end
if(Av_mode > 1) and (insert_ND_filter == true) then -- ND filter available and needed?
set_nd_filter(1) -- activate the ND filter
nd_string="NDin"
else
set_nd_filter(2) -- make sure the ND filter does not activate
nd_string="NDout"
end
-- and finally shoot the image
press("shoot_full_only")
sleep(100)
release("shoot_full")
repeat sleep(50) until get_shooting() == false
shot_count = shot_count + 1
-- update shooting statistic and log as required
shot_focus=get_focus()
if(shot_focus ~= -1) and (shot_focus < 20000) then
focus_string=" foc:"..(shot_focus/1000).."."..(((shot_focus%1000)+50)/100).."m"
if(focus_mode>0) then
error_string=" **WARNING : focus not at infinity**"
end
else
focus_string=" foc:infinity"
error_string=nil
end
printf(string.format('%d) IMG_%04d.JPG',shot_count,get_exp_count()))
printf(" meter : Tv:".. print_tv(tv96meter) .." Av:".. print_av(av96meter) .." Sv:"..print_sv(sv96meter).." "..bv96raw ..":"..bv96meter)
printf(" actual: Tv:".. print_tv(tv96setpoint).." Av:".. print_av(av96setpoint).." Sv:"..print_sv(sv96setpoint))
printf(" AvMin:".. print_av(av96min).." NDF:"..nd_string..focus_string )
if ((max_shots>0) and (shot_count >= max_shots)) then script_exit = true end
shot_request = false -- reset shot request flag
end
collectgarbage()
end
-- check if USB remote enabled in intervalometer mode and USB power is off -> pause if so
if ((usb_mode == 1 ) and (get_usb_power(1) == 0)) then
printf("waiting on USB signal")
unlock_focus()
switch_mode(0)
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
switch_mode(1)
lock_focus()
if ( is_key("menu")) then script_exit = true end
printf("USB wait finished")
sleep(100)
end
if (usb_mode == 3 ) then pwm_mode(get_usb_power(2)) end
if (blite_timer > 0) then
blite_timer = blite_timer-1
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(0) end
end
if( error_string ~= nil) then
draw_string( 16, 144, string.sub(error_string.." ",0,42), 258, 259)
end
wait_click(100)
if( not( is_key("no_key"))) then
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(1) end
blite_timer=300
if ( is_key("menu") ) then script_exit = true end
end
until (script_exit==true)
printf("script halt requested")
restore()
end
--[[ end of file ]]--
| gpl-3.0 |
PichotM/DarkRP | gamemode/modules/sleep/sv_sleep.lua | 5 | 7842 | -- very old sleep module
local KnockoutTime = 5
local function ResetKnockouts(player)
player.SleepRagdoll = nil
player.KnockoutTimer = 0
end
hook.Add("PlayerSpawn", "Knockout", ResetKnockouts)
local function stopSleep(ply)
if ply.Sleeping then
DarkRP.toggleSleep(ply, "force")
end
end
local function onRagdollArrested(arrestee, _, arrester)
DarkRP.toggleSleep(arrestee, "force")
-- onArrestStickUsed
local canArrest, message = hook.Call("canArrest", DarkRP.hooks, arrester, arrestee)
if not canArrest then
if message then DarkRP.notify(arrester, 1, 5, message) end
return
end
arrestee:arrest(nil, arrester)
DarkRP.notify(arrestee, 0, 20, DarkRP.getPhrase("youre_arrested_by", arrester:Nick()))
if arrester.SteamName then
DarkRP.log(arrester:Nick() .. " (" .. arrester:SteamID() .. ") arrested " .. arrestee:Nick(), Color(0, 255, 255))
end
end
local hookCanSleep = {canSleep = function(_, ply, force)
if not ply:Alive() then return false, DarkRP.getPhrase("must_be_alive_to_do_x", "/sleep") end
if (not ply.KnockoutTimer or ply.KnockoutTimer + KnockoutTime >= CurTime()) and not force then return false, DarkRP.getPhrase("have_to_wait", math.ceil((ply.KnockoutTimer + KnockoutTime) - CurTime()), "/sleep") end
if ply:IsFrozen() then return false, DarkRP.getPhrase("unable", "/sleep", DarkRP.getPhrase("frozen")) end
return true
end}
function DarkRP.toggleSleep(player, command)
if player:InVehicle() then return end
local canSleep, message = hook.Call("canSleep", hookCanSleep, player, command == "force")
if not canSleep then
DarkRP.notify(player, 1, 4, message ~= nil and message or DarkRP.getPhrase("unable", GAMEMODE.Config.chatCommandPrefix .. "sleep", ""))
return ""
end
if not player.SleepSound then
player.SleepSound = CreateSound(player, "npc/ichthyosaur/water_breath.wav")
end
local timerName = player:EntIndex() .. "SleepExploit"
if player.Sleeping and IsValid(player.SleepRagdoll) then
local frozen = player:IsFrozen()
player.OldHunger = player:getDarkRPVar("Energy")
player.SleepSound:Stop()
local ragdoll = player.SleepRagdoll
local health = player:Health()
local armor = player:Armor()
player:Spawn()
player:SetHealth(health)
player:SetArmor(armor)
player:SetPos(ragdoll:GetPos())
local model = ragdoll:GetModel()
-- TEMPORARY WORKAROUND
if string.lower(model) == "models/humans/corpse1.mdl" then
model = "models/player/corpse1.mdl"
end
player:SetModel(model)
player:SetAngles(Angle(0, ragdoll:GetPhysicsObjectNum(10) and ragdoll:GetPhysicsObjectNum(10):GetAngles().Yaw or 0, 0))
player:UnSpectate()
player:StripWeapons()
ragdoll:Remove()
ragdoll.OwnerINT = 0
if player.WeaponsForSleep and player:GetTable().BeforeSleepTeam == player:Team() then
for k,v in pairs(player.WeaponsForSleep) do
local wep = player:Give(v[1])
player:RemoveAllAmmo()
player:SetAmmo(v[2], v[3], false)
player:SetAmmo(v[4], v[5], false)
wep:SetClip1(v[6])
wep:SetClip2(v[7])
end
local cl_defaultweapon = player:GetInfo("cl_defaultweapon")
if ( player:HasWeapon( cl_defaultweapon ) ) then
player:SelectWeapon( cl_defaultweapon )
end
player:GetTable().BeforeSleepTeam = nil
player.WeaponsForSleep = nil
else
gamemode.Call("PlayerLoadout", player)
end
if frozen then
player:UnLock()
player:Lock()
end
SendUserMessage("blackScreen", player, false)
if command == true then
player:arrest()
end
player.Sleeping = false
if player:getDarkRPVar("Energy") then
player:setSelfDarkRPVar("Energy", player.OldHunger)
player.OldHunger = nil
end
if player:isArrested() then
GAMEMODE:SetPlayerSpeed(player, GAMEMODE.Config.arrestspeed, GAMEMODE.Config.arrestspeed)
end
timer.Remove(timerName)
else
if IsValid(player:GetObserverTarget()) then return "" end
for k,v in pairs(ents.FindInSphere(player:GetPos(), 30)) do
if v:GetClass() == "func_door" then
DarkRP.notify(player, 1, 4, DarkRP.getPhrase("unable", "sleep", "func_door exploit"))
return ""
end
end
if not player:isArrested() then
player.WeaponsForSleep = {}
for k,v in pairs(player:GetWeapons()) do
player.WeaponsForSleep[k] = {v:GetClass(), player:GetAmmoCount(v:GetPrimaryAmmoType()),
v:GetPrimaryAmmoType(), player:GetAmmoCount(v:GetSecondaryAmmoType()), v:GetSecondaryAmmoType(),
v:Clip1(), v:Clip2()}
--[[{class, ammocount primary, type primary, ammo count secondary, type secondary, clip primary, clip secondary]]
end
end
local ragdoll = ents.Create("prop_ragdoll")
ragdoll:SetPos(player:GetPos())
ragdoll:SetAngles(Angle(0,player:GetAngles().Yaw,0))
local model = player:GetModel()
-- TEMPORARY WORKAROUND
if string.lower(model) == "models/player/corpse1.mdl" then
model = "models/Humans/corpse1.mdl"
end
ragdoll:SetModel(model)
ragdoll:Spawn()
ragdoll:Activate()
ragdoll:SetVelocity(player:GetVelocity())
ragdoll.OwnerINT = player:EntIndex()
ragdoll.PhysgunPickup = false
ragdoll.CanTool = false
ragdoll.onArrestStickUsed = fp{onRagdollArrested, player}
player:StripWeapons()
player:Spectate(OBS_MODE_CHASE)
player:SpectateEntity(ragdoll)
player.IsSleeping = true
player.SleepRagdoll = ragdoll
player.KnockoutTimer = CurTime()
player:GetTable().BeforeSleepTeam = player:Team()
--Make sure noone can pick it up:
ragdoll:CPPISetOwner(player)
SendUserMessage("blackScreen", player, true)
player.SleepSound = CreateSound(ragdoll, "npc/ichthyosaur/water_breath.wav")
player.SleepSound:PlayEx(0.10, 100)
player.Sleeping = true
timer.Create(timerName, 0.3, 0, function()
if not IsValid(player) then timer.Remove(timerName) return end
if player:GetObserverTarget() ~= ragdoll then
if IsValid(ragdoll) then
ragdoll:Remove()
end
stopSleep(player)
player.SleepSound:Stop()
end
end)
end
return ""
end
DarkRP.defineChatCommand("sleep", DarkRP.toggleSleep)
DarkRP.defineChatCommand("wake", DarkRP.toggleSleep)
DarkRP.defineChatCommand("wakeup", DarkRP.toggleSleep)
hook.Add("OnPlayerChangedTeam", "SleepMod", stopSleep)
local function DamageSleepers(ent, dmginfo)
local attacker = dmginfo:GetAttacker()
local amount = dmginfo:GetDamage()
local ownerint = ent.OwnerINT
if not ownerint or ownerint == 0 then return end
for k,v in pairs(player.GetAll()) do
if v:EntIndex() ~= ownerint then continue end
if attacker == game.GetWorld() then
amount = 10
dmginfo:ScaleDamage(0.1)
end
v:SetHealth(v:Health() - amount)
if v:Health() <= 0 and v:Alive() then
DarkRP.toggleSleep(v, "force")
-- reapply damage to properly kill the player
v:StripWeapons()
v:TakeDamageInfo(dmginfo)
end
end
end
hook.Add("EntityTakeDamage", "Sleepdamage", DamageSleepers)
| mit |
iamgreaser/iceball | pkg/base/ent/tool_marker.lua | 4 | 4292 | --[[
This file is part of Ice Lua Components.
Ice Lua Components is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Lua Components is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Ice Lua Components. If not, see <http://www.gnu.org/licenses/>.
]]
return function (plr)
local this = {} this.this = this
this.plr = plr
this.mdl = mdl_marker_inst
this.gui_x = 0.15
this.gui_y = 0.32
this.gui_scale = 0.1
this.gui_pick_scale = 2.0
this.mode = 0
this.x1, this.y1, this.z1 = nil, nil, nil
this.x2, this.y2, this.z2 = nil, nil, nil
this.xp, this.yp, this.zp = nil, nil, nil
this.mspeed_mul = MODE_PSPEED_SPADE
function this.get_model()
return this.mdl
end
function this.reset()
--
end
this.reset()
function this.free()
--
end
function this.restock()
--
end
function this.focus()
--
end
function this.unfocus()
--
end
function this.need_restock()
return false
end
function this.key(key, state, modif)
if state then
if key == BTSK_COLORUP then
this.mode = (this.mode - 1) % 4
elseif key == BTSK_COLORDOWN then
this.mode = (this.mode + 1) % 4
end
end
end
function this.click(button, state)
if state then
if plr.tools[plr.tool+1] ~= this then return end
if button == 1 then
if plr.blx1 then
this.x1, this.y1, this.z1 = plr.blx1, plr.bly1, plr.blz1
this.xp, this.yp, this.zp = plr.x, plr.y, plr.z
end
end
else
if plr.tools[plr.tool+1] ~= this then
this.x1, this.y1, this.z1 = nil, nil, nil
this.x2, this.y2, this.z2 = nil, nil, nil
this.xp, this.yp, this.zp = nil, nil, nil
return
end
if button == 1 then
if this.x1 and this.x2 then
common.net_send(nil, common.net_pack("BBHHHHHHBBBB", PKT_BUILD_BOX,
this.mode, this.x1, this.y1, this.z1, this.x2, this.y2, this.z2,
plr.blk_color[1], plr.blk_color[2], plr.blk_color[3]))
end
this.x1, this.y1, this.z1 = nil, nil, nil
this.x2, this.y2, this.z2 = nil, nil, nil
this.xp, this.yp, this.zp = nil, nil, nil
end
end
end
function this.tick(sec_current, sec_delta)
local xlen,ylen,zlen
xlen,ylen,zlen = common.map_get_dims()
if plr.tools[plr.tool+1] ~= this then return end
if this.x1 then
--
this.x2 = math.floor(this.x1 + plr.x - this.xp + 0.5)
this.y2 = math.floor(this.y1 + plr.y - this.yp + 0.5)
this.z2 = math.floor(this.z1 + plr.z - this.zp + 0.5)
end
end
function this.textgen()
local cr,cg,cb
cr,cg,cb = 128,128,128
local col = (cr*256+cg)*256+cb+0xFF000000
return col, ""..this.mode
end
function this.render(px,py,pz,ya,xa,ya2)
ya = ya - math.pi/2
if plr.blx1 and (plr.alive or plr.respawning) and map_block_get(plr.blx2, plr.bly2, plr.blz2) then
mdl_test_inst.render_global(
plr.blx1+0.5, plr.bly1+0.5, plr.blz1+0.5,
rotpos*0.01, rotpos*0.004, 0.0, 0.1+0.01*math.sin(rotpos*0.071))
mdl_test_inst.render_global(
(plr.blx1*2+plr.blx2)/3+0.5,
(plr.bly1*2+plr.bly2)/3+0.5,
(plr.blz1*2+plr.blz2)/3+0.5,
-rotpos*0.01, -rotpos*0.004, 0.0, 0.1+0.01*math.sin(-rotpos*0.071))
end
if this.x1 and this.x2 then
local x,y,z
local x1,y1,z1,x2,y2,z2
x1, y1, z1 = this.x1, this.y1, this.z1
x2, y2, z2 = this.x2, this.y2, this.z2
if x1 > x2 then x1, x2 = x2, x1 end
if y1 > y2 then y1, y2 = y2, y1 end
if z1 > z2 then z1, z2 = z2, z1 end
local f = function (x,y,z)
local xp = (x==x1 or x==x2)
local yp = (y==y1 or y==y2)
local zp = (z==z1 or z==z2)
return (xp and (yp or zp)) or (yp and zp)
end
for x=x1,x2 do for z=z1,z2 do
for y=y1,y2 do
if f(x,y,z) then
mdl_test_inst.render_global(
x+0.5, y+0.5, z+0.5,
0, 0, 0, 1.0)
end
end
end end
end
this.mdl.render_global(
px, py, pz, ya, xa, ya2, 1)
end
return this
end
| gpl-3.0 |
LanceJenkinZA/prosody-modules | mod_broadcast/mod_broadcast.lua | 32 | 1043 | local is_admin = require "core.usermanager".is_admin;
local allowed_senders = module:get_option_set("broadcast_senders", {});
local from_address = module:get_option_string("broadcast_from");
local jid_bare = require "util.jid".bare;
function send_to_online(message)
local c = 0;
for hostname, host_session in pairs(hosts) do
if host_session.sessions then
for username in pairs(host_session.sessions) do
c = c + 1;
message.attr.to = username.."@"..hostname;
module:send(message);
end
end
end
return c;
end
function send_message(event)
local stanza = event.stanza;
local from = stanza.attr.from;
if is_admin(from) or allowed_senders:contains(jid_bare(from)) then
if from_address then
stanza = st.clone(stanza);
stanza.attr.from = from_address;
end
local c = send_to_online(stanza);
module:log("debug", "Broadcast stanza from %s to %d online users", from, c);
return true;
else
module:log("warn", "Broadcasting is not allowed for %s", from);
end
end
module:hook("message/bare", send_message);
| mit |
Anarchid/Zero-K | LuaUI/Widgets/cmd_area_attack_tweak.lua | 5 | 10529 | function widget:GetInfo()
return {
name = "Area Attack Tweak",
desc = "CTRL+Attack splits targets. AA automatically drops ground targets.",
author = "msafwan",
date = "May 22, 2012",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
VFS.Include("LuaRules/Configs/customcmds.h.lua")
local SPLIT_ATTACK_SINGLE = false
local defaultCommands = {
[CMD.ATTACK] = true,
[CMD.AREA_ATTACK] = true,
[CMD.FIGHT] = true,
[CMD.PATROL] = true,
[CMD.GUARD] = true,
[CMD.MANUALFIRE] = true,
[CMD_REARM] = true,
[CMD_FIND_PAD] = true,
[CMD.MOVE] = true,
[CMD_RAW_MOVE] = true,
[CMD_RAW_BUILD] = true,
[CMD_UNIT_SET_TARGET] = true,
[CMD_UNIT_SET_TARGET_CIRCLE] = true,
-- [CMD.REMOVE] = true,
-- [CMD.INSERT] = true,
}
local unitsSplitAttackQueue = {nil} --just in case user press SHIFT after doing split attack, we need to remove these queue
local handledCount = 0
function widget:CommandNotify(id, params, options) --ref: gui_tacticalCalculator.lua by msafwan, and central_build_AI.lua by Troy H. Creek
if not defaultCommands[id] or options.internal then --only process user's command
return false
end
if Spring.GetSelectedUnitsCount() == 0 then --skip whole thing if no selection
return false
end
local units
if SPLIT_ATTACK_SINGLE and handledCount > 0 then
--This remove all but 1st attack order from CTRL+Area_attack if user choose to append new order to unit (eg: SHIFT+move),
--this is to be consistent with bomber_command (rearm-able bombers), which only shoot 1st target and move on to next order.
--Known limitation: not able to remove order if user queued faster than network delay (it need to see unit's current command queue)
units = Spring.GetSelectedUnits()
local unitID, attackList
for i=1,#units do
unitID = units[i]
attackList = GetAndRemoveHandledHistory(unitID)
if attackList and options.shift then
RevertAllButOneAttackQueue(unitID,attackList)
end
end
end
if (id == CMD.ATTACK or id == CMD_UNIT_SET_TARGET or id == CMD_UNIT_SET_TARGET_CIRCLE) then
local cx, cy, cz, cr = params[1], params[2], params[3], params[4]
if (cr or 0) == 0 then --not area command
return false
end
if (cx == nil or cy == nil or cz == nil) then --outside of map
return false
end
--The following code filter out ground unit from dedicated AA, and
--split target among selected unit if user press CTRL+Area_attack
local cx2, cy2, cz2 = params[4], params[5], params[6]
units = units or Spring.GetSelectedUnits()
local targetUnits
if cz2 then
targetUnits = Spring.GetUnitsInRectangle(math.min(cx,cx2), math.min(cz,cz2), math.max(cx,cx2), math.max(cz,cz2))
else
targetUnits = Spring.GetUnitsInCylinder(cx, cz, cr)
end
local antiAirUnits,normalUnits = GetAAUnitList(units)
local airTargets, allTargets = ReturnAllAirTarget(targetUnits, Spring.GetUnitAllyTeam(units[1]),(#antiAirUnits>1)) -- get all air target for selected area-command
if #allTargets>0 then --skip if no target
return ReIssueCommandsToUnits(antiAirUnits,airTargets,normalUnits,allTargets,id,options)
end
end
return false
end
if SPLIT_ATTACK_SINGLE then
function widget:UnitGiven(unitID)
GetAndRemoveHandledHistory(unitID)
end
function widget:UnitDestroyed(unitID)
GetAndRemoveHandledHistory(unitID)
end
--------------------------------------------------------------------------------
function GetAndRemoveHandledHistory(unitID)
if unitsSplitAttackQueue[unitID] then
local attackList = unitsSplitAttackQueue[unitID]
unitsSplitAttackQueue[unitID] = nil
handledCount = handledCount - 1
return attackList
end
return nil
end
end
function RevertAllButOneAttackQueue(unitID,attackList)
local queue = Spring.GetCommandQueue(unitID, -1)
if queue then
local toRemoveCount = 0
local queueToRemove = {}
for j=1,#queue do
command = queue[j]
if command.id == CMD.ATTACK and attackList[command.params[1] ] then
if toRemoveCount > 0 then --skip first queue
queueToRemove[toRemoveCount] = command.tag
end
toRemoveCount = toRemoveCount + 1
end
end
Spring.GiveOrderToUnit (unitID,CMD.REMOVE, queueToRemove, 0)
end
end
function ReturnAllAirTarget(targetUnits, selectedAlly,checkAir)
local filteredTargets = {}
local nonFilteredTargets = {}
for i=1, #targetUnits,1 do --see if targets can fly and if they are enemy or ally.
local unitID = targetUnits[i]
local enemyAllyID = Spring.GetUnitAllyTeam(unitID)
if (selectedAlly ~= enemyAllyID) then --differentiate between selected unit, targeted units, and enemyteam. Filter out ally and owned units
if checkAir then
local unitDefID = Spring.GetUnitDefID(unitID)
local unitDef = UnitDefs[unitDefID]
if not unitDef then
if GetDotsFloating(unitID) then --check & remember floating radar dots in new table.
filteredTargets[#filteredTargets +1] = unitID
end
else
if unitDef["canFly"] then --check & remember flying units in new table
filteredTargets[#filteredTargets +1] = unitID
end
end
end
nonFilteredTargets[#nonFilteredTargets +1] = unitID --also copy all target to a non-filtered table
end
end
return filteredTargets, nonFilteredTargets
end
function GetAAUnitList(units)
local antiAirUnits = {nil}
local normalUnits = {nil}
for i=1, #units,1 do --catalog AA and non-AA
local unitID = units[i]
local unitDefID = Spring.GetUnitDefID(unitID)
if unitDefID then
local unitDef_primaryWeapon = UnitDefs[unitDefID].weapons[1]
if (unitDef_primaryWeapon~= nil) then
local primaryWeapon_target = UnitDefs[unitDefID].weapons[1].onlyTargets
local exclusiveAA = (primaryWeapon_target["fixedwing"] and primaryWeapon_target["gunship"]) and
not (primaryWeapon_target["sink"] or primaryWeapon_target["land"] or primaryWeapon_target["sub"])
--[[
Spring.Echo(UnitDefs[unitDefID].weapons[1].onlyTargets)
for name,content in pairs(UnitDefs[unitDefID].weapons[1].onlyTargets) do
Spring.Echo(name)
Spring.Echo(content)
end
--]]
if (exclusiveAA) then
antiAirUnits[#antiAirUnits +1]= unitID
else
normalUnits[#normalUnits +1]= unitID
end
else
normalUnits[#normalUnits +1]= unitID
end
end
end
return antiAirUnits, normalUnits
end
function ReIssueCommandsToUnits(antiAirUnits,airTargets,normalUnits,allTargets,cmdID,options)
local isHandled = false
if options.ctrl then -- split attacks between units
--split between AA and ground,
IssueSplitedCommand(antiAirUnits,airTargets,cmdID,options)
IssueSplitedCommand(normalUnits,allTargets,cmdID,options)
isHandled = true
else -- normal queue
if #antiAirUnits>1 then
--split between AA and ground,
IssueCommand(antiAirUnits,airTargets,cmdID,options)
IssueCommand(normalUnits,allTargets,cmdID,options)
isHandled = true
else
isHandled = false --nothing need to be done, let spring handle
end
end
return isHandled
end
--------------------------------------------------------------------------------
function IssueCommand(selectedUnits,allTargets,cmdID,options)
if #allTargets>=1 then
local attackCommandListAll = PrepareCommandArray(allTargets, cmdID, options,1) -- prepare a normal queue (like regular SHIFT)
Spring.GiveOrderArrayToUnitArray (selectedUnits, attackCommandListAll)
end
end
function IssueSplitedCommand(selectedUnits,allTargets,cmdID,options)
if #allTargets>=1 then
if SPLIT_ATTACK_SINGLE then
local targetsUnordered = {}
if cmdID==CMD.ATTACK then --and not CMD_UNIT_SET_TARGET. Note: only CMD.ATTACK support split attack queue, and in such case we also need to remember the queue so we can revert later if user decided to do SHIFT+Move
for i=1,#allTargets do
targetsUnordered[allTargets[i] ] = true
end
for i=1, #selectedUnits do
unitsSplitAttackQueue[selectedUnits[i] ] = targetsUnordered --note: all units in this loop was refer to same table to avoid duplication
handledCount = handledCount + 1
end
end
end
for i=1, #selectedUnits do
-- local noAttackQueue = queueException[Spring.GetUnitDefID(selectedUnits[i])]
local attackCommandListAll = PrepareCommandArray(allTargets, cmdID, options,i,true,noAttackQueue) --prepare a shuffled queue for target splitting
Spring.GiveOrderArrayToUnitArray ({selectedUnits[i]}, attackCommandListAll)
end
end
end
--------------------------------------------------------------------------------
function GetDotsFloating (unitID) --ref: gui_vertLineAid.lua by msafwan
local x, y, z = Spring.GetUnitPosition(unitID)
if x == nil then
return false
end
local isFloating = false
local groundY = Spring.GetGroundHeight(x,z)
local surfaceY = math.max (groundY, 0) --//select water, or select terrain height depending on which is higher.
if (y-surfaceY) >= 100 then --//mark unit as flying if it appears to float far above surface, if this fail then player can force attack it with single-(non-area)-attack or scout its ID first.
isFloating = true
end
return isFloating
end
function PrepareCommandArray (targetUnits, cmdID, options,indx,shuffle)
indx = LoopAroundIndex(indx, #targetUnits)
local stepSkip = 1
if shuffle then
stepSkip = (#targetUnits%(2))*-1 +3
--stepSkip is 3 if #targetUnits is EVEN number (eg: 4,6,8), or 2 if #targetUnits is ODD (eg: 3,5,7)
--this will shuffle the target sequence appropriately
end
local attackCommandList = {}
local j = 1
attackCommandList[j] = {cmdID,{targetUnits[indx],},{((options.shift and "shift") or nil),}}
if cmdID == CMD.ATTACK then
for i=1, #targetUnits-1, 1 do
j= j + 1
indx = indx + stepSkip --stepSkip>1 will shuffle the queue
indx = LoopAroundIndex(indx, #targetUnits)
attackCommandList[j] = {cmdID,{targetUnits[indx],},{"shift",}} --every unit get to attack every target
end
end
return attackCommandList
end
--------------------------------------------------------------------------------
function LoopAroundIndex(indx, maxIndex)
----
-- Example:
-- if maxIndex is 3 and input indx is 1,2,3,4,5,6
-- the following 3 line of code will convert indx into: 1,2,3,1,2,3 (which will avoid "index out-of-bound" case)
indx = indx - 1
indx = indx%(maxIndex)
indx = indx + 1
-- also: if indx is (maxIndex + extraValue), then it would convert into: (1 + extraValue).
return indx
end
| gpl-2.0 |
Mutos/SoC-Test-001 | dat/factions/spawn/frontier.lua | 4 | 1786 | include("dat/factions/spawn/common.lua")
-- @brief Spawns a small patrol fleet.
function spawn_patrol ()
local pilots = {}
local r = rnd.rnd()
if r < 0.5 then
scom.addPilot( pilots, "Frontier Lancelot", 30 );
elseif r < 0.8 then
scom.addPilot( pilots, "Frontier Hyena", 20 );
scom.addPilot( pilots, "Frontier Lancelot", 30 );
else
scom.addPilot( pilots, "Frontier Hyena", 20 );
scom.addPilot( pilots, "Frontier Ancestor", 25 );
end
return pilots
end
-- @brief Spawns a medium sized squadron.
function spawn_squad ()
local pilots = {}
local r = rnd.rnd()
if r < 0.5 then
scom.addPilot( pilots, "Frontier Lancelot", 30 );
scom.addPilot( pilots, "Frontier Phalanx", 55 );
else
scom.addPilot( pilots, "Frontier Lancelot", 30 );
scom.addPilot( pilots, "Frontier Lancelot", 30 );
scom.addPilot( pilots, "Frontier Ancestor", 25 );
end
return pilots
end
-- @brief Creation hook.
function create ( max )
local weights = {}
-- Create weights for spawn table
weights[ spawn_patrol ] = 100
weights[ spawn_squad ] = 0.33*max
-- Create spawn table base on weights
spawn_table = scom.createSpawnTable( weights )
-- Calculate spawn data
spawn_data = scom.choose( spawn_table )
return scom.calcNextSpawn( 0, scom.presence(spawn_data), max )
end
-- @brief Spawning hook
function spawn ( presence, max )
local pilots
-- Over limit
if presence > max then
return 5
end
-- Actually spawn the pilots
pilots = scom.spawn( spawn_data )
-- Calculate spawn data
spawn_data = scom.choose( spawn_table )
return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots
end
| gpl-3.0 |
alireza1998/supergroup | bot/bot.lua | 1 | 6651 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"9gag",
"eur",
"echo",
"btc",
"get",
"giphy",
"google",
"gps",
"help",
"id",
"images",
"img_google",
"location",
"media",
"plugins",
"channels",
"set",
"stats",
"time",
"version",
"weather",
"xkcd",
"youtube" },
sudo_users = {159887854},
disabled_channels = {}
}
serialize_to_file(config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
halolpd/vlc | share/lua/playlist/france2.lua | 113 | 2115 | --[[
$Id$
Copyright © 2008 the VideoLAN team
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "jt.france2.fr/player/" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "class=\"editiondate\"" ) then
_,_,editiondate = string.find( line, "<h1>(.-)</h1>" )
end
if string.match( line, "mms.*%.wmv" ) then
_,_,video = string.find( line, "mms(.-%.wmv)" )
video = "mmsh"..video
table.insert( p, { path = video; name = editiondate } )
end
if string.match( line, "class=\"subjecttimer\"" ) then
oldtime = time
_,_,time = string.find( line, "href=\"(.-)\"" )
if oldtime then
table.insert( p, { path = video; name = name; duration = time - oldtime; options = { ':start-time='..tostring(oldtime); ':stop-time='..tostring(time) } } )
end
name = vlc.strings.resolve_xml_special_chars( string.gsub( line, "^.*>(.*)<..*$", "%1" ) )
end
end
if oldtime then
table.insert( p, { path = video; name = name; options = { ':start-time='..tostring(time) } } )
end
return p
end
| gpl-2.0 |
nnesse/b2l-tools | lgi/tests/gobject.lua | 2 | 9233 | --[[--------------------------------------------------------------------------
LGI testsuite, GObject.Object test suite.
Copyright (c) 2010, 2011 Pavel Holejsovsky
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
--]]--------------------------------------------------------------------------
local lgi = require 'lgi'
local core = require 'lgi.core'
local check = testsuite.check
local checkv = testsuite.checkv
-- Basic GObject testing
local gobject = testsuite.group.new('gobject')
function gobject.env_base()
local GObject = lgi.GObject
local obj = GObject.Object()
check(type(core.object.env(obj)) == 'table')
check(core.object.env(obj) == core.object.env(obj))
check(next(core.object.env(obj)) == nil)
end
function gobject.env_persist()
local Gtk = lgi.Gtk
local window = Gtk.Window()
local label = Gtk.Label()
local env = core.object.env(label)
window:_method_add(label)
label = nil
collectgarbage()
label = window:get_child()
check(env == core.object.env(label))
end
function gobject.object_new()
local GObject = lgi.GObject
local o = GObject.Object()
o = nil
collectgarbage()
end
function gobject.initunk_new()
local GObject = lgi.GObject
local o = GObject.InitiallyUnowned()
-- Simulate sink by external container
o:ref_sink()
o:unref()
o = nil
collectgarbage()
end
function gobject.native()
local GObject = lgi.GObject
local o = GObject.Object()
local p = o._native
check(type(p) == 'userdata')
check(GObject.Object(p) == o)
end
function gobject.gtype_create()
local GObject = lgi.GObject
local Gio = lgi.Gio
local m = GObject.Object.new(Gio.ThemedIcon, { name = 'icon' })
check(Gio.ThemedIcon:is_type_of(m))
end
function gobject.subclass_derive1()
local GObject = lgi.GObject
local Derived = GObject.Object:derive('LgiTestDerived1')
local der = Derived()
check(Derived:is_type_of(der))
check(not Derived:is_type_of(GObject.Object()))
end
function gobject.subclass_derive2()
local GObject = lgi.GObject
local Derived = GObject.Object:derive('LgiTestDerived2')
local Subderived = Derived:derive('LgiTestSubDerived2')
local der = Derived()
check(Derived:is_type_of(der))
check(not Subderived:is_type_of(der))
local sub = Subderived()
check(Subderived:is_type_of(sub))
check(Derived:is_type_of(sub))
check(GObject.Object:is_type_of(sub))
end
function gobject.subclass_override1()
local GObject = lgi.GObject
local Derived = GObject.Object:derive('LgiTestOverride1')
local state = 0
local obj
function Derived:do_constructed()
obj = self
state = state + 1
end
function Derived:do_dispose()
state = state + 2
end
check(state == 0)
local der = Derived()
check(der == obj)
check(state == 1)
der = nil
obj = nil
collectgarbage()
check(state == 3)
end
function gobject.subclass_override2()
local GObject = lgi.GObject
local state = 0
local Derived = GObject.Object:derive('LgiTestOverride2')
function Derived:do_constructed()
self.priv.id = 1
state = state + 1
end
function Derived:do_dispose()
state = state + 2
GObject.Object.do_dispose(self)
end
function Derived:custom_method()
state = state + 8
self.priv.id = self.priv.id + 4
end
local Subderived = Derived:derive('LgiTestOverrideSub2')
function Subderived:do_constructed()
Derived.do_constructed(self)
self.priv.id = self.priv.id + 2
state = state + 4
end
check(state == 0)
local sub = Subderived()
check(state == 5)
check(sub.priv.id == 3)
sub:custom_method()
check(state == 13)
check(sub.priv.id == 7)
sub = nil
collectgarbage()
check(state == 15)
end
function gobject.subclass_derive3()
local GObject = lgi.GObject
local history = {}
local Derived = GObject.InitiallyUnowned:derive('LgiTestDerived3')
function Derived:_class_init()
history[#history + 1] = 'class_init'
check(self == Derived)
collectgarbage()
end
function Derived:_init()
history[#history + 1] = 'init'
collectgarbage()
end
function Derived:do_constructed()
history[#history + 1] = 'constructed'
Derived._parent.do_constructed(self)
collectgarbage()
end
-- function Derived:do_dispose()
-- history[#history + 1] = 'dispose'
-- Derived._parent.do_dispose(self)
-- end
local obj = Derived()
check(history[1] == 'class_init')
check(history[2] == 'init')
check(history[3] == 'constructed')
obj = nil
collectgarbage()
-- check(history[4] == 'dispose')
end
function gobject.iface_virtual()
local Gio = lgi.Gio
local file = Gio.File.new_for_path('hey')
check(file:is_native() == file:do_is_native())
check(file:get_basename() == file:do_get_basename())
end
function gobject.iface_impl()
local GObject = lgi.GObject
local Gio = lgi.Gio
local FakeFile = GObject.Object:derive('LgiTestFakeFile1', { Gio.File })
function FakeFile:do_get_basename()
return self.priv.basename
end
function FakeFile:set_basename(basename)
self.priv.basename = basename
end
local fakefile = FakeFile()
fakefile:set_basename('fakename')
check(fakefile:get_basename() == 'fakename')
end
function gobject.treemodel_impl()
local GObject = lgi.GObject
local Gtk = lgi.Gtk
local Model = GObject.Object:derive('LgiTestModel1', { Gtk.TreeModel })
function Model:do_get_n_columns()
return 2
end
function Model:do_get_column_type(index)
return index == 0 and GObject.Type.STRING or GObject.Type.INT
end
function Model:do_get_iter(path)
local iter = Gtk.TreeIter()
iter.user_data = path._native
return iter
end
function Model:do_get_value(iter, column)
return GObject.Value(self:get_column_type(column), 1)
end
local model = Model()
check(model:get_n_columns() == 2)
check(model:get_column_type(0) == GObject.Type.STRING)
check(model:get_column_type(1) == GObject.Type.INT)
local p = Gtk.TreePath.new_from_string('0')
local i = model:get_iter(p)
check(i.user_data == p._native)
check(model[Gtk.TreeIter()][1] == '1')
check(model[Gtk.TreeIter()][2] == 1)
end
-- Lua 5.3 and 5.1 seems to have some problem with aggressive GC settings used
-- here and completing this test takes literally ages, so skip it. Enable only if explicitely asked for.
if rawget(_G, '_LGI_ENABLE_ALL_TESTS') then
function gobject.ctor_gc()
local Gtk = lgi.Gtk
local oldpause = collectgarbage('setpause', 10)
local oldstepmul = collectgarbage('setstepmul', 10000)
for i = 1, 1000 do
local window = Gtk.Window {
width = 800,
height = 600,
title = "Test",
}
end
collectgarbage('setpause', oldpause)
collectgarbage('setstepmul', oldstepmul)
end
end
function gobject.subclass_prop1()
local GObject = lgi.GObject
local Derived = GObject.Object:derive('LgiTestDerivedProp1')
Derived._property.string = GObject.ParamSpecString(
'string', 'Nick string', 'Blurb string', 'string-default',
{ 'READABLE', 'WRITABLE', 'CONSTRUCT' }
)
local der = Derived()
checkv(der.string, 'string-default', 'string')
der.string = 'assign'
checkv(der.string, 'assign', 'string')
checkv(der.priv.string, 'assign', 'string')
end
function gobject.subclass_prop_inherit()
local GObject = lgi.GObject
local Gio = lgi.Gio
local FakeMonitor = GObject.Object:derive(
'LgiTestFakeMonitor1', { Gio.Initable, Gio.NetworkMonitor })
FakeMonitor._property.network_available =
GObject.ParamSpecBoolean('network-available',
'LgiTestFakeMonitor1NetworkAvailable',
'Whether the network is available.',
false, { GObject.ParamFlags.READABLE })
function FakeMonitor:do_init(cancellable)
self.priv.inited = true
return true
end
local fakemonitor = FakeMonitor()
-- Gio.Initable is invoked automatically by lgi after object
-- construction.
check(fakemonitor.priv.inited)
-- If the object is not constructed yet, it defaults to false
check(fakemonitor:get_network_available() == false)
check(fakemonitor.network_available == false)
fakemonitor.priv.network_available = true
check(fakemonitor.network_available == true)
check(fakemonitor:get_network_available() == true)
fakemonitor.priv.network_available = false
check(fakemonitor.network_available == false)
check(fakemonitor:get_network_available() == false)
end
function gobject.subclass_prop_getset()
local GObject = lgi.GObject
local Derived = GObject.Object:derive('LgiTestDerivedPropGetSet')
Derived._property.str = GObject.ParamSpecString(
'str', 'Nick string', 'Blurb string', 'string-default',
{ 'READABLE', 'WRITABLE', 'CONSTRUCT' }
)
local propval
function Derived._property_set:str(new_value)
propval = new_value
end
function Derived._property_get:str()
return propval
end
local der = Derived()
checkv(der.str, 'string-default', 'string')
der.str = 'assign'
checkv(der.str, 'assign', 'string')
checkv(propval, 'assign', 'string')
end
| gpl-2.0 |
AndyBursh/Factorio-Stdlib | spec/area/tile_spec.lua | 1 | 3115 | require 'spec/defines'
require 'stdlib/area/tile'
describe('Tile Spec', function()
it('should give the correct tile coordinates for a position', function()
assert.same(0, Tile.from_position({0, 34}).x)
assert.same(34, Tile.from_position({0, 34}).y)
assert.same(-67, Tile.from_position({-66.4521, 255.001}).x)
assert.same(255, Tile.from_position({-66.4521, 255.001}).y)
end)
it('should give the correct tile area for a tile position', function()
assert.same(1, Tile.to_area({1, 2}).left_top.x)
assert.same(2, Tile.to_area({1, 2}).left_top.y)
assert.same(2, Tile.to_area({1, 2}).right_bottom.x)
assert.same(3, Tile.to_area({1, 2}).right_bottom.y)
end)
it('should ensure adjacent tiles are found correctly', function()
local surface = { get_tile = function(x, y) if x % 2 == 0 then return { name = 'water' } end return { name = 'sand' } end }
assert.same(4, #Tile.adjacent(surface, {1, 1}))
assert.same(4, #Tile.adjacent(surface, {1, 1}, false))
assert.same(8, #Tile.adjacent(surface, {1, 1}, true))
local adj = Tile.adjacent(surface, {1, 1})
assert.same(adj[1], {x = 1, y = 2})
assert.same(adj[2], {x = 2, y = 1})
assert.same(adj[3], {x = 1, y = 0})
assert.same(adj[4], {x = 0, y = 1})
assert.same(2, #Tile.adjacent(surface, {1, 1}, false, 'water'))
end)
it('should ensure indexes are stable and deterministic', function()
assert.same(0, Tile.get_index({x = 0, y = 0}))
local set = {}
for x = 0, 31 do
for y = 0, 31 do
local idx = Tile.get_index({x = x, y = y})
assert.is_nil(set[idx])
set[idx] = true
assert.truthy(idx < 1024 and idx >= 0)
end
end
assert.same(0, Tile.get_index({x = 0, y = 0}))
end)
it('should verify getting and setting data', function()
_G.global = {}
_G.game = { surfaces = { nauvis = { index = 0 } } }
local tile_pos = { x = 4, y = -6 }
local surface = "nauvis"
assert.is_nil(Tile.get_data(surface, tile_pos))
-- verify Tile.get_data sets the default_value
assert.is_nil(Tile.get_data(surface, { x = 256, y = -256 }))
assert.same({}, Tile.get_data(surface, { x = 256, y = -256 }, {}))
assert.same({}, Tile.get_data(surface, { x = 256, y = -256 }))
local data = { foo = 'bar' }
assert.is_nil(Tile.set_data(surface, tile_pos, data))
assert.same(data, Tile.get_data(surface, tile_pos))
-- Verify mutated data is not lost
data.foo = 'baz'
assert.same(data, Tile.get_data(surface, tile_pos))
--Verify multiple tiles can store data
for i = 1, 64 do
local tile_pos = { x = 4 - i, y = -6 + i }
local data = { count = i }
Tile.set_data(surface, tile_pos, data)
assert.same(data, Tile.get_data(surface, tile_pos))
end
assert.same(data, Tile.get_data(surface, tile_pos))
end)
end)
| isc |
Hello23-Ygopro/ygopro-duel-masters | expansions/script/c24002017.lua | 1 | 1171 | --King Nautilus
local dm=require "expansions.utility_dmtcg"
local scard,sid=dm.GetID()
function scard.initial_effect(c)
dm.EnableCreatureAttribute(c)
--double breaker
dm.EnableBreaker(c,DM_ABILITY_DOUBLE_BREAKER)
--cannot be blocked
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(DM_ABILITY_CANNOT_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetRange(DM_LOCATION_BATTLE)
e1:SetTargetRange(1,1)
e1:SetCondition(dm.SelfAttackingCondition)
e1:SetValue(dm.CannotBeBlockedValue(dm.CannotBeBlockedLessPowerValue))
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_GRANT)
e2:SetRange(DM_LOCATION_BATTLE)
e2:SetTargetRange(DM_LOCATION_BATTLE,DM_LOCATION_BATTLE)
e2:SetTarget(aux.TargetBoolFunction(Card.IsDMRace,DM_RACE_LIQUID_PEOPLE))
e2:SetLabelObject(e1)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(DM_ABILITY_UNBLOCKABLE)
e3:SetRange(DM_LOCATION_BATTLE)
e3:SetTargetRange(DM_LOCATION_BATTLE,DM_LOCATION_BATTLE)
e3:SetTarget(aux.TargetBoolFunction(Card.IsDMRace,DM_RACE_LIQUID_PEOPLE))
c:RegisterEffect(e3)
end
scard.duel_masters_card=true
| gpl-3.0 |
LanceJenkinZA/prosody-modules | mod_statistics/top.lua | 32 | 6810 | module("prosodytop", package.seeall);
local array = require "util.array";
local it = require "util.iterators";
local curses = require "curses";
local stats = require "stats".stats;
local time = require "socket".gettime;
local sessions_idle_after = 60;
local stanza_names = {"message", "presence", "iq"};
local top = {};
top.__index = top;
local status_lines = {
"Prosody $version - $time up $up_since, $total_users users, $cpu busy";
"Connections: $total_c2s c2s, $total_s2sout s2sout, $total_s2sin s2sin, $total_component component";
"Memory: $memory_lua lua, $memory_allocated process ($memory_used in use)";
"Stanzas in: $message_in_per_second message/s, $presence_in_per_second presence/s, $iq_in_per_second iq/s";
"Stanzas out: $message_out_per_second message/s, $presence_out_per_second presence/s, $iq_out_per_second iq/s";
};
function top:draw()
self:draw_status();
self:draw_column_titles();
self:draw_conn_list();
self.statuswin:refresh();
self.listwin:refresh();
--self.infowin:refresh()
self.stdscr:move(#status_lines,0)
end
-- Width specified as cols or % of unused space, defaults to
-- title width if not specified
local conn_list_columns = {
{ title = "ID", key = "id", width = "8" };
{ title = "JID", key = "jid", width = "100%" };
{ title = "STANZAS IN>", key = "total_stanzas_in", align = "right" };
{ title = "MSG", key = "message_in", align = "right", width = "4" };
{ title = "PRES", key = "presence_in", align = "right", width = "4" };
{ title = "IQ", key = "iq_in", align = "right", width = "4" };
{ title = "STANZAS OUT>", key = "total_stanzas_out", align = "right" };
{ title = "MSG", key = "message_out", align = "right", width = "4" };
{ title = "PRES", key = "presence_out", align = "right", width = "4" };
{ title = "IQ", key = "iq_out", align = "right", width = "4" };
{ title = "BYTES IN", key = "bytes_in", align = "right" };
{ title = "BYTES OUT", key = "bytes_out", align = "right" };
};
function top:draw_status()
for row, line in ipairs(status_lines) do
self.statuswin:mvaddstr(row-1, 0, (line:gsub("%$([%w_]+)", self.data)));
self.statuswin:clrtoeol();
end
-- Clear stanza counts
for _, stanza_type in ipairs(stanza_names) do
self.prosody[stanza_type.."_in_per_second"] = 0;
self.prosody[stanza_type.."_out_per_second"] = 0;
end
end
local function padright(s, width)
return s..string.rep(" ", width-#s);
end
local function padleft(s, width)
return string.rep(" ", width-#s)..s;
end
function top:resized()
self:recalc_column_widths();
--self.stdscr:clear();
self:draw();
end
function top:recalc_column_widths()
local widths = {};
self.column_widths = widths;
local total_width = curses.cols()-4;
local free_width = total_width;
for i = 1, #conn_list_columns do
local width = conn_list_columns[i].width or "0";
if not(type(width) == "string" and width:sub(-1) == "%") then
width = math.max(tonumber(width), #conn_list_columns[i].title+1);
widths[i] = width;
free_width = free_width - width;
end
end
for i = 1, #conn_list_columns do
if not widths[i] then
local pc_width = tonumber((conn_list_columns[i].width:gsub("%%$", "")));
widths[i] = math.floor(free_width*(pc_width/100));
end
end
return widths;
end
function top:draw_column_titles()
local widths = self.column_widths;
self.listwin:attron(curses.A_REVERSE);
self.listwin:mvaddstr(0, 0, " ");
for i, column in ipairs(conn_list_columns) do
self.listwin:addstr(padright(column.title, widths[i]));
end
self.listwin:addstr(" ");
self.listwin:attroff(curses.A_REVERSE);
end
local function session_compare(session1, session2)
local stats1, stats2 = session1.stats, session2.stats;
return (stats1.total_stanzas_in + stats1.total_stanzas_out) >
(stats2.total_stanzas_in + stats2.total_stanzas_out);
end
function top:draw_conn_list()
local rows = curses.lines()-(#status_lines+2)-5;
local cutoff_time = time() - sessions_idle_after;
local widths = self.column_widths;
local top_sessions = array.collect(it.values(self.active_sessions)):sort(session_compare);
for index = 1, rows do
session = top_sessions[index];
if session then
if session.last_update < cutoff_time then
self.active_sessions[session.id] = nil;
else
local row = {};
for i, column in ipairs(conn_list_columns) do
local width = widths[i];
local v = tostring(session[column.key] or ""):sub(1, width);
if #v < width then
if column.align == "right" then
v = padleft(v, width-1).." ";
else
v = padright(v, width);
end
end
table.insert(row, v);
end
if session.updated then
self.listwin:attron(curses.A_BOLD);
end
self.listwin:mvaddstr(index, 0, " "..table.concat(row));
if session.updated then
session.updated = false;
self.listwin:attroff(curses.A_BOLD);
end
end
else
-- FIXME: How to clear a line? It's 5am and I don't feel like reading docs.
self.listwin:move(index, 0);
self.listwin:clrtoeol();
end
end
end
function top:update_stat(name, value)
self.prosody[name] = value;
end
function top:update_session(id, jid, stats)
self.active_sessions[id] = stats;
stats.id, stats.jid, stats.stats = id, jid, stats;
stats.total_bytes = stats.bytes_in + stats.bytes_out;
for _, stanza_type in ipairs(stanza_names) do
self.prosody[stanza_type.."_in_per_second"] = (self.prosody[stanza_type.."_in_per_second"] or 0) + stats[stanza_type.."_in"];
self.prosody[stanza_type.."_out_per_second"] = (self.prosody[stanza_type.."_out_per_second"] or 0) + stats[stanza_type.."_out"];
end
stats.total_stanzas_in = stats.message_in + stats.presence_in + stats.iq_in;
stats.total_stanzas_out = stats.message_out + stats.presence_out + stats.iq_out;
stats.last_update = time();
stats.updated = true;
end
function new(base)
setmetatable(base, top);
base.data = setmetatable({}, {
__index = function (t, k)
local stat = stats[k];
if stat and stat.tostring then
if type(stat.tostring) == "function" then
return stat.tostring(base.prosody[k]);
elseif type(stat.tostring) == "string" then
local v = base.prosody[k];
if v == nil then
return "?";
end
return (stat.tostring):format(v);
end
end
return base.prosody[k];
end;
});
base.active_sessions = {};
base.statuswin = curses.newwin(#status_lines, 0, 0, 0);
base.promptwin = curses.newwin(1, 0, #status_lines, 0);
base.promptwin:addstr("");
base.promptwin:refresh();
base.listwin = curses.newwin(curses.lines()-(#status_lines+2)-5, 0, #status_lines+1, 0);
base.listwin:syncok();
base.infowin = curses.newwin(5, 0, curses.lines()-5, 0);
base.infowin:mvaddstr(1, 1, "Hello world");
base.infowin:border(0,0,0,0);
base.infowin:syncok();
base.infowin:refresh();
base:resized();
return base;
end
return _M;
| mit |
iamgreaser/iceball | pkg/gm/portalgun/gun_portal.lua | 1 | 7684 | --[[
This file is derived from code from Ice Lua Components.
Ice Lua Components is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Lua Components is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Ice Lua Components. If not, see <http://www.gnu.org/licenses/>.
]]
local thisid = ...
local function set_color(new_r, new_g, new_b)
return function(r,g,b)
if r == 0 and g == 0 and b == 0 then
return new_r, new_g, new_b
else
return r, g, b
end
end
end
if client then
local base_model = model_load({
kv6 = {
bdir = DIR_PORTALGUN,
name = "portalgun.kv6",
scale = 1.0/128.0,
},
}, {"kv6"})
weapon_models[thisid] = {
base_model({filt = set_color(0, 92, 172)}),
base_model({filt = set_color(240, 92, 28)})
}
end
weapon_names[thisid] = "Portal Gun"
return function (plr)
local this = tpl_gun(plr, {
dmg = {
head = 0,
body = 0,
legs = 0,
},
block_damage = 0,
ammo_clip = 10,
ammo_reserve = 50,
time_fire = 1/3,
time_reload = 1/3,
recoil_x = 0.0001,
recoil_y = -0.05,
model = client and weapon_models[thisid][1],
name = "Portal Gun",
})
function this.reload()
-- Close both portals
plr.portal_list[1] = nil
net_send(nil, common.net_pack("BBBhhhbbbbbb", PKT_PORTALGUN_SET,
0, 1, cx, cy, cz,
dx, dy, dz, 0, 0, 0))
plr.portal_list[2] = nil
net_send(nil, common.net_pack("BBBhhhbbbbbb", PKT_PORTALGUN_SET,
0, 2, cx, cy, cz,
dx, dy, dz, 0, 0, 0))
end
local s_tick = this.tick
function this.tick(sec_current, sec_delta, ...)
this.ammo_clip = 10
return s_tick(sec_current, sec_delta, ...)
end
function this.textgen()
local col = 0xFFC0C0C0
return col, ((plr.portal_list[1] and "0") or "-")..
" "..((plr.portal_list[2] and "0") or "-")
end
function this.click(button, state)
if button == 1 or button == 3 then
-- LMB
if button == 1 then
this.cfg.model = client and weapon_models[thisid][1]
else
this.cfg.model = client and weapon_models[thisid][2]
end
if this.ammo_clip > 0 then
if state then
this.portal_select = (button==1 and 1) or 2
end
this.firing = state
else
-- Shouldn't happen!
this.firing = false
client.wav_play_global(wav_pin, plr.x, plr.y, plr.z)
plr.reload_msg.visible = true
plr.reload_msg.static_alarm{name='reloadviz',
time=0.5, on_trigger=function() plr.reload_msg.visible = false end}
end
elseif button == 2 then
-- RMB
if hold_to_zoom then
plr.zooming = state and not this.reloading
else
if state and not this.reloading then
plr.zooming = not plr.zooming
end
end
end
end
function this.prv_fire(sec_current)
local xlen, ylen, zlen
xlen, ylen, zlen = common.map_get_dims()
if client then
client.wav_play_global(this.cfg.shot_sound, plr.x, plr.y, plr.z)
bcase_part_mdl = bcase_part_mdl or new_particle_model(250, 215, 0)
particles_add(new_particle{
x = plr.x,
y = plr.y,
z = plr.z,
vx = math.sin(plr.angy - math.pi / 4) / 2 + math.random() * 0.25,
vy = 0.1 + math.random() * 0.25,
vz = math.cos(plr.angy - math.pi / 4) / 2 + math.random() * 0.25,
model = bcase_part_mdl,
size = 8,
lifetime = 2
})
end
net_send(nil, common.net_pack("BBB", PKT_PLR_GUN_SHOT, 0, 1))
-- TODO: Better spread
-- spread
local angy = plr.angy + (this.cfg.spread * (math.random() - 0.5))
local angx = plr.angx + (this.cfg.spread * (math.random() - 0.5))
local sya = math.sin(angy)
local cya = math.cos(angy)
local sxa = math.sin(angx)
local cxa = math.cos(angx)
local fwx,fwy,fwz
fwx,fwy,fwz = sya*cxa, sxa, cya*cxa
-- tracer
if client then
tracer_add(plr.x, plr.y, plr.z, angy, angx)
end
-- perform a trace
portal_traces_enabled = false
local d,cx1,cy1,cz1,cx2,cy2,cz2
d,cx1,cy1,cz1,cx2,cy2,cz2
= trace_map_ray_dist(plr.x+sya*0.4,plr.y,plr.z+cya*0.4, fwx,fwy,fwz, this.cfg.range)
d = d or this.cfg.range
portal_traces_enabled = true
-- see if there's anyone we can kill
local hurt_idx = nil
local hurt_part = nil
local hurt_part_idx = 0
local hurt_dist = d*d
local i,j
for i=1,players.max do
local p = players[i]
if p and p ~= plr and p.alive then
local dx = p.x-plr.x
local dy = p.y-plr.y+0.1
local dz = p.z-plr.z
for j=1,3 do
local dot, dd = isect_line_sphere_delta(dx,dy,dz,fwx,fwy,fwz)
if dot and dot < 0.55 and dd < hurt_dist then
hurt_idx = i
hurt_dist = dd
hurt_part_idx = j
hurt_part = ({"head","body","legs"})[j]
break
end
dy = dy + 1.0
end
end
end
--[==[
if hurt_idx then
if server then
--[[
players[hurt_idx].gun_damage(
hurt_part, this.cfg.dmg[hurt_part], plr)
]]
else
--[[
net_send(nil, common.net_pack("BBB"
, PKT_PLR_GUN_HIT, hurt_idx, hurt_part_idx))
]]
plr.show_hit()
end
end
]==]
if client then
--[[
net_send(nil, common.net_pack("BBB"
, PKT_PLR_GUN_HIT, 0, 0))
]]
if cx2 and cy2 <= ylen-2 and cx2 >= 0 and cx2 < xlen and cz2 >= 0 and cz2 < zlen then
print("Portal hit ("..cx2..", "..cy2..", "..cz2..") type "..this.portal_select)
local dx,dy,dz = cx2-cx1, cy2-cy1, cz2-cz1
dx = math.floor(dx + 0.5)
dy = math.floor(dy + 0.5)
dz = math.floor(dz + 0.5)
print("Direction ("..dx..", "..dy..", "..dz..")")
-- Check if valid...
local valid = true
-- CHECK: Ensure back is all solid, front is all clear
local cx = math.floor(cx2)
local cy = math.floor(cy2)
local cz = math.floor(cz2)
if valid then
local i,j,k
for i=-1,1 do
for j=-1,1 do
for k=-1,0 do
if not valid then break end
local x = cx+k*dx+i*dy+j*dz
local y = cy+k*dy+i*dz+j*dx
local z = cz+k*dz+i*dx+j*dy
if k == 0 then
if map_block_get(x,y,z) == nil then valid = false end
else
if map_block_get(x,y,z) ~= nil then valid = false end
end
end
end
end
end
if valid and dy == 0 and (dx ~= 0 or dz ~= 0) then
plr.show_hit()
plr.portal_list[this.portal_select] = {cx, cy, cz, dx, dy, dz, 0, -1, 0}
if plr.portal_list[3-this.portal_select] then
plr.portal_list[3-this.portal_select].va = nil
end
net_send(nil, common.net_pack("BBBhhhbbbbbb", PKT_PORTALGUN_SET,
0, this.portal_select, cx, cy, cz,
dx, dy, dz, 0, -1, 0))
elseif valid and dy ~= 0 and (dx == 0 and dz == 0) then
local sx, sz = 0, 0
if math.abs(fwx) > math.abs(fwz) then
sx = (fwx < 0 and -1) or 1
else
sz = (fwz < 0 and -1) or 1
end
sx = sx * dy
sz = sz * dy
plr.show_hit()
plr.portal_list[this.portal_select] = {cx, cy, cz, dx, dy, dz, sx, 0, sz}
if plr.portal_list[3-this.portal_select] then
plr.portal_list[3-this.portal_select].va = nil
end
net_send(nil, common.net_pack("BBBhhhbbbbbb", PKT_PORTALGUN_SET,
0, this.portal_select, cx, cy, cz,
dx, dy, dz, sx, 0, sz))
end
end
end -- if hurt_idx
-- apply recoil
-- attempting to emulate classic behaviour provided i have it right
plr.recoil(sec_current, this.cfg.recoil_y, this.cfg.recoil_x)
end
return this
end
| gpl-3.0 |
Anarchid/Zero-K | LuaRules/Gadgets/cmd_transfer_unit.lua | 13 | 1909 | function gadget:GetInfo()
return {
name = "Command Transfer Unit",
desc = "Adds a command to transfer units between teams.",
author = "GoogleFrog",
date = "8 September 2017",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true,
}
end
include("LuaRules/Configs/customcmds.h.lua")
if gadgetHandler:IsSyncedCode() then
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
-- Speedups
local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
-- Configuration
local transferCmdDesc = {
id = CMD_TRANSFER_UNIT,
type = CMDTYPE.NUMBER,
name = 'Transfer Unit',
action = 'transferunit',
hidden = true,
}
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
-- Command Handling
function gadget:CommandFallback(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) -- Only calls for custom commands
if not (cmdID == CMD_TRANSFER_UNIT) then
return false
end
local newTeamID = cmdParams and cmdParams[1]
if newTeamID and (teamID ~= newTeamID) and (Spring.AreTeamsAllied(teamID, newTeamID) or (teamID == Spring.GetGaiaTeamID())) then
Spring.TransferUnit(unitID, newTeamID, teamID ~= Spring.GetGaiaTeamID())
end
return true, true
end
function gadget:Initialize()
for _, unitID in pairs(Spring.GetAllUnits()) do
gadget:UnitCreated(unitID, Spring.GetUnitDefID(unitID))
end
end
function gadget:UnitCreated(unitID, unitDefID, teamID)
spInsertUnitCmdDesc(unitID, transferCmdDesc)
end
end
| gpl-2.0 |
fegimanam/LNT | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
NUTIEisBADYT/NUTIEisBADYTS-PD2-Modpack | Low Violence Mode/lvm.lua | 1 | 1148 | if RequiredScript == "lib/managers/enemymanager" then
EnemyManager._MAX_NR_CORPSES = 0
EnemyManager.MAX_MAGAZINES = 0
local old_init = EnemyManager.init
function EnemyManager:init(...)
old_init(self, ...)
self._corpse_disposal_upd_interval = 0
self._shield_disposal_upd_interval = 0
self._shield_disposal_lifetime = 0
self._MAX_NR_SHIELDS = 0
end
local old_limit = EnemyManager.corpse_limit
function EnemyManager:corpse_limit(...)
local limit = old_limit(self, ...)
if limit and limit > 0 then
limit = 0
end
return limit
end
end
if RequiredScript == "lib/managers/gameplaycentralmanager" then
local old_init = GamePlayCentralManager.init
function GamePlayCentralManager:init(...)
old_init(self, ...)
self._block_bullet_decals = true
self._block_blood_decals = true
end
function GamePlayCentralManager:_play_bullet_hit(...)
return
end
function GamePlayCentralManager:play_impact_flesh(...)
return
end
function GamePlayCentralManager:sync_play_impact_flesh(...)
return
end
end
if RequiredScript == "lib/units/enemies/cop/copdamage" then
function CopDamage:_spawn_head_gadget(...)
return
end
end | mit |
alireza1998/supergroup | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
mohammad4569/matrix | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
delram/yago | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
mamaddeveloper/DeveloperMMD_bot | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
Anarchid/Zero-K | gamedata/weapondefs_post.lua | 5 | 14277 | -- $Id: weapondefs_post.lua 3171 2008-11-06 09:06:29Z det $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: weapondefs_post.lua
-- brief: weaponDef post processing
-- author: Dave Rodgers
--
-- Copyright (C) 2008.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
VFS.FileExists = VFS.FileExists or function() return false end -- unitdef exporter compatibility
--[[ This lets mutators add a bit of weapondefs_post processing without
losing access to future gameside updates to weapondefs_post. ]]
local MODSIDE_POSTS_FILEPATH = 'gamedata/weapondefs_mod.lua'
if VFS.FileExists(MODSIDE_POSTS_FILEPATH, VFS.GAME) then
VFS.Include(MODSIDE_POSTS_FILEPATH, nil, VFS.GAME)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Spring.Echo("Loading WeaponDefs_posts")
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Dynamic Comms
--
VFS.Include('gamedata/modularcomms/weapondefgen.lua')
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Per-unitDef weaponDefs
--
local function isbool(x) return (type(x) == 'boolean') end
local function istable(x) return (type(x) == 'table') end
local function isnumber(x) return (type(x) == 'number') end
local function isstring(x) return (type(x) == 'string') end
--------------------------------------------------------------------------------
local function ProcessUnitDef(udName, ud)
local wds = ud.weapondefs
if (not istable(wds)) then
return
end
-- add this unitDef's weaponDefs
for wdName, wd in pairs(wds) do
if (isstring(wdName) and istable(wd)) then
local fullName = udName .. '_' .. wdName
WeaponDefs[fullName] = wd
wd.filename = ud.filename
end
end
-- convert the weapon names
local weapons = ud.weapons
if (istable(weapons)) then
for i = 1, 16 do
local w = weapons[i]
if (istable(w)) then
if (isstring(w.def)) then
local ldef = string.lower(w.def)
local fullName = udName .. '_' .. ldef
local wd = WeaponDefs[fullName]
if (istable(wd)) then
w.name = fullName
end
end
w.def = nil
end
end
end
-- convert the death explosions
if (isstring(ud.explodeas)) then
local fullName = udName .. '_' .. string.lower(ud.explodeas)
if (WeaponDefs[fullName]) then
ud.explodeas = fullName
end
end
if (isstring(ud.selfdestructas)) then
local fullName = udName .. '_' .. string.lower(ud.selfdestructas)
if (WeaponDefs[fullName]) then
ud.selfdestructas = fullName
end
end
end
--------------------------------------------------------------------------------
-- Process the unitDefs
local UnitDefs = DEFS.unitDefs
for udName, ud in pairs(UnitDefs) do
if (isstring(udName) and istable(ud)) then
ProcessUnitDef(udName, ud)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- customParams is never nil
for _, weaponDef in pairs(WeaponDefs) do
weaponDef.customparams = weaponDef.customparams or {}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Apply remaim_time
for name, weaponDef in pairs(WeaponDefs) do
if not (weaponDef.customparams.reaim_time or string.find(name, "chicken")) then
weaponDef.customparams.reaim_time = 5
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Set shield starting power to 100%
for name, weaponDef in pairs(WeaponDefs) do
if weaponDef.shieldpower and (weaponDef.shieldpower < 2000) then
weaponDef.shieldstartingpower = weaponDef.shieldpower
weaponDef.customparams.shieldstartingpower = weaponDef.shieldstartingpower
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Set lenient fire tolerance
for _, weaponDef in pairs(WeaponDefs) do
if not weaponDef.firetolerance then
weaponDef.firetolerance = 32768 -- Full 180 degrees on either side.
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Preserve crater sizes for new engine
-- https://github.com/spring/spring/commit/77c8378b04907417a62c25218d69ff323ba74c8d
for _, weaponDef in pairs(WeaponDefs) do
if (not weaponDef.craterareaofeffect) then
weaponDef.craterareaofeffect = tonumber(weaponDef.areaofeffect or 0) * 1.5
end
end
-- New engine seems to have covertly increased the effect of cratermult
for _, weaponDef in pairs(WeaponDefs) do
weaponDef.cratermult = (weaponDef.cratermult or 1) * 0.3
end
-- https://github.com/spring/spring/commit/dd7d1f79c3a9b579f874c210eb4c2a8ae7b72a16
for _, weaponDef in pairs(WeaponDefs) do
if ((weaponDef.weapontype == "LightningCannon") and (not weaponDef.beamttl)) then
weaponDef.beamttl = 10
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Disable sweepfire until we know how to use it
for _, weaponDef in pairs(WeaponDefs) do
weaponDef.sweepfire = false
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Disable burnblow for LaserCannons because overshoot is not a problem for any
-- of them and is important for some.
for _, weaponDef in pairs(WeaponDefs) do
if weaponDef.weapontype == "LaserCannon" then
weaponDef.burnblow = false
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local modOptions
if (Spring.GetModOptions) then
modOptions = Spring.GetModOptions()
end
if (modOptions and modOptions.damagemult and modOptions.damagemult ~= 1) then
local damagemult = modOptions.damagemult
for _, weaponDef in pairs(WeaponDefs) do
if (weaponDef.damage and weaponDef.name and not string.find(weaponDef.name, "Disintegrator")) then
for damagetype, amount in pairs(weaponDef.damage) do
weaponDef.damage[damagetype] = amount * damagemult
end
end
end
end
if (modOptions and modOptions.cratermult and modOptions.cratermult ~= 1) then
local cratermult = modOptions.cratermult
for _, weaponDef in pairs(WeaponDefs) do
if weaponDef.cratermult then
weaponDef.cratermult = weaponDef.cratermult * cratermult
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Set myGravity for ballistic weapons because maps cannot be trusted. Standard is 120,
-- gravity of 150 can cause high things (such as HLT) to be unhittable.
Game = Game or {} -- unitdef exporter compatibility
Game.gameSpeed = Game.gameSpeed or 30
local defaultMyGravity = 120 / (Game.gameSpeed^2)
for _, weaponDef in pairs(WeaponDefs) do
--[[ There are other weapons that follow gravity,
for example expired missiles and torpedoes
who fall out of water, but these disobey the
tag and always use map gravity anyway ]]
local supportsMyGravity =
(weaponDef.weapontype == "Cannon") or
(weaponDef.weapontype == "AircraftBomb")
if supportsMyGravity and (not weaponDef.mygravity) then -- setting myGravity = 0.0 will use map gravity anyway
weaponDef.mygravity = defaultMyGravity
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- because the way lua access to unitdefs and weapondefs is setup is insane
--
for _, weaponDef in pairs(WeaponDefs) do
if not weaponDef.customparams then
weaponDef.customparams = {}
end
if weaponDef.mygravity then
weaponDef.customparams.mygravity = weaponDef.mygravity -- For attack AOE widget
end
if weaponDef.flighttime then
weaponDef.customparams.flighttime = weaponDef.flighttime
end
if weaponDef.weapontimer then
weaponDef.customparams.weapontimer = weaponDef.weapontimer
end
if weaponDef.weaponvelocity then
weaponDef.customparams.weaponvelocity = weaponDef.weaponvelocity -- For attack AOE widget
end
if weaponDef.dyndamageexp and (weaponDef.dyndamageexp > 0) then
weaponDef.customparams.dyndamageexp = weaponDef.dyndamageexp
end
if weaponDef.flighttime and (weaponDef.flighttime > 0) then
weaponDef.customparams.flighttime = weaponDef.flighttime
end
end
for _, weaponDef in pairs(WeaponDefs) do
local name = weaponDef.name
if name:find('fake') or name:find('Fake') or name:find('Bogus') or name:find('NoWeapon') then
weaponDef.customparams.fake_weapon = 1
end
end
-- Set defaults for napalm (area damage)
local area_damage_defaults = VFS.Include("gamedata/unitdef_defaults/area_damage_defs.lua")
for name, wd in pairs (WeaponDefs) do
local cp = wd.customparams
if cp.area_damage then
if not cp.area_damage_dps then cp.area_damage_dps = area_damage_defaults.dps end
if not cp.area_damage_radius then cp.area_damage_radius = area_damage_defaults.radius end
if not cp.area_damage_duration then cp.area_damage_duration = area_damage_defaults.duration end
if not cp.area_damage_plateau_radius then cp.area_damage_plateau_radius = area_damage_defaults.plateau_radius end
if not cp.area_damage_is_impulse then cp.area_damage_is_impulse = area_damage_defaults.is_impulse end
if not cp.area_damage_range_falloff then cp.area_damage_range_falloff = area_damage_defaults.range_falloff end
if not cp.area_damage_time_falloff then cp.area_damage_time_falloff = area_damage_defaults.time_falloff end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- default noSelfDamage
--
for _, weaponDef in pairs(WeaponDefs) do
weaponDef.noselfdamage = (weaponDef.noselfdamage ~= false)
end
-- remove experience bonuses
for _, weaponDef in pairs(WeaponDefs) do
weaponDef.ownerExpAccWeight = 0
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Workaround for http://springrts.com/mantis/view.php?id=4104
--
for _, weaponDef in pairs(WeaponDefs) do
if weaponDef.texture1 == "largelaserdark" then
weaponDef.texture1 = "largelaserdark_long"
weaponDef.tilelength = (weaponDef.tilelength and weaponDef.tilelength*4) or 800
end
if weaponDef.texture1 == "largelaser" then
weaponDef.texture1 = "largelaser_long"
weaponDef.tilelength = (weaponDef.tilelength and weaponDef.tilelength*4) or 800
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Take over the handling of shield energy drain from the engine.
for _, weaponDef in pairs(WeaponDefs) do
if weaponDef.shieldpowerregenenergy and weaponDef.shieldpowerregenenergy > 0 then
weaponDef.customparams = weaponDef.customparams or {}
weaponDef.customparams.shield_rate = weaponDef.shieldpowerregen
weaponDef.customparams.shield_drain = weaponDef.shieldpowerregenenergy
weaponDef.shieldpowerregen = 0
weaponDef.shieldpowerregenenergy = 0
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Set hardStop for defered lighting and to reduce projectile count
for _, weaponDef in pairs(WeaponDefs) do
if weaponDef.weapontype == "LaserCannon" and weaponDef.hardstop == nil then
weaponDef.hardstop = true
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Reduce rounding error in damage
for _, weaponDef in pairs(WeaponDefs) do
if weaponDef.impactonly then
weaponDef.edgeeffectiveness = 1
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- ???
for _, weaponDef in pairs(WeaponDefs) do
if weaponDef.paralyzetime and not weaponDef.paralyzer then
weaponDef.customparams.extra_paratime = weaponDef.paralyzetime
end
if not weaponDef.predictboost then
weaponDef.predictboost = 1
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- Fix the canAttack tag
--
do
local function RawCanAttack (ud)
if (ud.weapons) then
for i, weapon in pairs(ud.weapons) do
local wd = WeaponDefs[weapon.name:lower()]
if wd.weapontype ~= "Shield" and not wd.interceptor then
return true
end
end
end
if (ud.kamikaze) then
return not ud.yardmap
end
return false
end
local function CanAttack (ud)
local isFac = ud.yardmap and ud.buildoptions
if isFac or RawCanAttack(ud) then
return true
end
return false
end
for name, ud in pairs(UnitDefs) do
if not ud.canattack then
ud.canattack = CanAttack(ud)
end
end
end
| gpl-2.0 |
LuaDist2/ldoc | tests/styles/priority_queue.lua | 7 | 2392 | --------------------------------------------------------------------------------
--- Queue of objects sorted by priority.
-- @module lua-nucleo.priority_queue
-- This file is a part of lua-nucleo library. Note that if you wish to spread
-- the description after tags, then invoke with `not_luadoc=true`.
-- The flags here are `ldoc -X -f backtick priority_queue.lua`, which
-- also expands backticks.
-- @copyright lua-nucleo authors (see file `COPYRIGHT` for the license)
--------------------------------------------------------------------------------
local arguments,
method_arguments
= import 'lua-nucleo/args.lua'
{
'arguments',
'method_arguments'
}
local lower_bound_gt
= import 'lua-nucleo/algorithm.lua'
{
'lower_bound_gt'
}
--------------------------------------------------------------------------------
local table_insert, table_remove = table.insert, table.remove
--------------------------------------------------------------------------------
--- Priority Queue
-- @factory priority_queue
local make_priority_queue
do
local PRIORITY_KEY = 1
local VALUE_KEY = 2
local insert = function(self, priority, value)
method_arguments(
s
"number", priority
)
assert(value ~= nil, "value can't be nil") -- value may be of any type, except nil
local queue = self.queue_
local k = lower_bound_gt(queue, PRIORITY_KEY, priority)
table_insert(queue, k, { [PRIORITY_KEY] = priority, [VALUE_KEY] = value })
end
local front = function(self)
method_arguments(
self
)
local queue = self.queue_
local front_elem = queue[#queue]
if front_elem == nil then
return nil
end
return front_elem[PRIORITY_KEY], front_elem[VALUE_KEY]
end
--- pop last value.
-- @return priority
-- @return value
local pop = function(self)
method_arguments(
self
)
local front_elem = table_remove(self.queue_)
if front_elem == nil then
return nil
end
return front_elem[PRIORITY_KEY], front_elem[VALUE_KEY]
end
--- construct a `priority_queue`.
-- @constructor
make_priority_queue = function()
--- @export
return
{
insert = insert;
front = front;
pop = pop;
--
queue_ = { };
}
end
end
return
{
make_priority_queue = make_priority_queue;
}
| mit |
Anarchid/Zero-K | LuaUI/Widgets/unit_dynamic_avoidance_ex.lua | 6 | 129695 |
function widget:GetInfo()
return {
name = "Dynamic Avoidance System",
desc = "Avoidance AI behaviour for constructors, cloakies, ground-combat units and gunships.\n\nNote: Customize the settings by Space+Click on unit-state icons.",
author = "msafwan (based on articles by Siome Goldenstein, Edward Large, Dimitris Metaxas)",
date = "March 8, 2014", --clean up June 25, 2013
license = "GNU GPL, v2 or later",
layer = 20,
enabled = false -- loaded by default?
}
end
--------------------------------------------------------------------------------
-- Functions:
local spGetTeamUnits = Spring.GetTeamUnits
local spGetAllUnits = Spring.GetAllUnits
local spGetTeamResources = Spring.GetTeamResources
local spGetGroundHeight = Spring.GetGroundHeight
local spGiveOrderToUnit =Spring.GiveOrderToUnit
local spGiveOrderArrayToUnitArray = Spring.GiveOrderArrayToUnitArray
local spGetMyTeamID = Spring.GetMyTeamID
local spIsUnitAllied = Spring.IsUnitAllied
local spGetUnitPosition =Spring.GetUnitPosition
local spGetUnitVelocity = Spring.GetUnitVelocity
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitSeparation = Spring.GetUnitSeparation
local spGetUnitDirection =Spring.GetUnitDirection
local spGetUnitsInRectangle =Spring.GetUnitsInRectangle
local spGetVisibleUnits = Spring.GetVisibleUnits
local spGetCommandQueue = Spring.GetCommandQueue
local spGetGameSeconds = Spring.GetGameSeconds
local spGetFeaturePosition = Spring.GetFeaturePosition
local spGetPlayerInfo = Spring.GetPlayerInfo
local spGetUnitIsCloaked = Spring.GetUnitIsCloaked
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitLastAttacker = Spring.GetUnitLastAttacker
local spGetUnitHealth = Spring.GetUnitHealth
local spGetUnitWeaponState = Spring.GetUnitWeaponState
local spGetUnitShieldState = Spring.GetUnitShieldState
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetGameFrame = Spring.GetGameFrame
local spSendCommands = Spring.SendCommands
local spGetSelectedUnits = Spring.GetSelectedUnits
local spGetUnitIsDead = Spring.GetUnitIsDead
local spValidUnitID = Spring.ValidUnitID
local spValidFeatureID = Spring.ValidFeatureID
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local CMD_STOP = CMD.STOP
local CMD_ATTACK = CMD.ATTACK
local CMD_GUARD = CMD.GUARD
local CMD_INSERT = CMD.INSERT
local CMD_REMOVE = CMD.REMOVE
local CMD_OPT_INTERNAL = CMD.OPT_INTERNAL
local CMD_OPT_SHIFT = CMD.OPT_SHIFT
local CMD_RECLAIM = CMD.RECLAIM
local CMD_RESURRECT = CMD.RESURRECT
local CMD_REPAIR = CMD.REPAIR
--local spRequestPath = Spring.RequestPath
local mathRandom = math.random
--local spGetUnitSensorRadius = Spring.GetUnitSensorRadius
--------------------------------------------------------------------------------
-- Constant:
-- Switches:
local turnOnEcho =0 --1:Echo out all numbers for debugging the system, 2:Echo out alert when fail. (default = 0)
local activateAutoReverseG=1 --integer:[0,1], activate a one-time-reverse-command when unit is about to collide with an enemy (default = 1)
local activateImpatienceG=0 --integer:[0,1], auto disable auto-reverse & half the 'distanceCONSTANT' after 6 continuous auto-avoidance (3 second). In case the unit stuck (default = 0)
-- Graph constant:
local distanceCONSTANTunitG = 410 --increase obstacle awareness over distance. (default = 410 meter, ie: ZK's stardust range)
local useLOS_distanceCONSTANTunit_G = true --this replace "distanceCONSTANTunitG" obstacle awareness (push) strenght with unit's LOS, ie: unit with different range suit better. (default = true, for tuning: use false)
local safetyMarginCONSTANTunitG = 0.175 --obstacle graph windower (a "safety margin" constant). Shape the obstacle graph so that its fatter and more sloppier at extremities: ie: probably causing unit to prefer to turn more left or right (default = 0.175 radian)
local smCONSTANTunitG = 0.175 -- obstacle graph offset (a "safety margin" constant). Offset the obstacle effect: to prefer avoid torward more left or right??? (default = 0.175 radian)
local aCONSTANTg = {math.pi/4 , math.pi/2} -- attractor graph; scale the attractor's strenght. Less equal to a lesser turning toward attraction(default = math.pi/10 radian (MOVE),math.pi/4 (GUARD & ATTACK)) (max value: math.pi/2 (because both contribution from obstacle & target will sum to math.pi)).
local obsCONSTANTg = {math.pi/4, math.pi/2} -- obstacle graph; scale the obstacle's strenght. Less equal to a lesser turning away from avoidance(default = math.pi/10 radian (MOVE), math.pi/4 (GUARD & ATTACK)).
--aCONSTANTg Note: math.pi/4 is equal to about 45 degrees turning (left or right). aCONSTANTg is the maximum amount of turning toward target and the actual turning depend on unit's direction. Activated by 'graphCONSTANTtrigger[1]'
--an antagonist to aCONSTANg (obsCONSTANTg or obstacle graph) also use math.pi/4 (45 degree left or right) but actual maximum value varies depend on number of enemy, but already normalized. Activated by 'graphCONSTANTtrigger[2]'
local windowingFuncMultG = 1 --? (default = 1 multiplier)
local normalizeObsGraphG = true --// if 'true': normalize turn angle to a maximum of "obsCONSTANTg", if 'false': allow turn angle to grow as big as it can (depend on number of enemy, limited by "maximumTurnAngleG").
local stdDecloakDist_fG = 75 --//a decloak distance size for Scythe is put as standard. If other unit has bigger decloak distance then it will be scalled based on this
-- Obstacle/Target competetive interaction constant:
local cCONSTANT1g = {0.01,1,2} --attractor constant; effect the behaviour. ie: selection between 4 behaviour state. (default = 0.01x (All), 1x (Cloakies),2x (alwaysAvoid)) (behaviour:(MAINTAIN USER's COMMAND)|(IGNORE USER's COMMAND|(IGNORE USER's COMMAND))
local cCONSTANT2g = {0.01,1,2} --repulsor constant; effect behaviour. (default = 0.01x (All), 1x (Cloakies),2x (alwaysAvoid)) (behaviour:(MAINTAIN USER's COMMAND)|(IGNORE USER's COMMAND|(IGNORE USER's COMMAND))
local gammaCONSTANT2and1g = {0.05,0.05,0.05} -- balancing constant; effect behaviour. . (default = 0.05x (All), 0.05x (Cloakies))
local alphaCONSTANT1g = {500,0.4,0.4} -- balancing constant; effect behaviour. (default = 500x (All), 0.4x (Cloakies)) (behaviour:(MAINTAIN USER's COMMAND)|(IGNORE USER's COMMAND))
--Move Command constant:
local halfTargetBoxSize_g = {400, 0, 185, 50} --aka targetReachBoxSizeTrigger, set the distance from a target which widget should de-activate (default: MOVE = 400m (ie:800x800m box/2x constructor range), RECLAIM/RESURRECT=0 (always flee), REPAIR=185 (1x constructor's range), GUARD = 50 (arbitrary))
local cMD_DummyG = 248 --a fake command ID to flag an idle unit for pure avoidance. (arbitrary value, change if it overlap with existing command)
local cMD_Dummy_atkG = 249 --same as cMD_DummyG except to differenciate between idle & attacking
--Angle constant:
--http://en.wikipedia.org/wiki/File:Degree-Radian_Conversion.svg
local noiseAngleG =0.1 --(default is pi/36 rad); add random angle (range from 0 to +-math.pi/36) to the new angle. To prevent a rare state that contribute to unit going straight toward enemy
local collisionAngleG= 0.1 --(default is pi/6 rad) a "field of vision" (range from 0 to +-math.pi/366) where auto-reverse will activate
local fleeingAngleG= 0.7 --(default is pi/4 rad) angle of enemy with respect to unit (range from 0 to +-math.pi/4) where unit is considered as facing a fleeing enemy (to de-activate avoidance to perform chase). Set to 0 to de-activate.
local maximumTurnAngleG = math.pi --(default is pi rad) safety measure. Prevent overturn (eg: 360+xx degree turn)
--pi is 180 degrees
--Update constant:
local cmd_then_DoCalculation_delayG = 0.25 --elapsed second (Wait) before issuing new command (default: 0.25 second)
-- Distance or velocity constant:
local timeToContactCONSTANTg= cmd_then_DoCalculation_delayG --time scale for move command; to calculate collision calculation & command lenght (default = 0.5 second). Will change based on user's Ping
local safetyDistanceCONSTANT_fG=205 --range toward an obstacle before unit auto-reverse (default = 205 meter, ie: half of ZK's stardust range) reference:80 is a size of BA's solar
local extraLOSRadiusCONSTANTg=205 --add additional distance for unit awareness over the default LOS. (default = +205 meter radius, ie: to 'see' radar blip).. Larger value measn unit detect enemy sooner, else it will rely on its own LOS.
local velocityScalingCONSTANTg=1.1 --scale command lenght. (default= 1 multiplier) *Small value cause avoidance to jitter & stop prematurely*
local velocityAddingCONSTANTg=50 --add or remove command lenght (default = 50 elmo/second) *Small value cause avoidance to jitter & stop prematurely*
--Weapon Reload and Shield constant:
local reloadableWeaponCriteriaG = 0.5 --second at which reload time is considered high enough to be a "reload-able". eg: 0.5second
local criticalShieldLevelG = 0.5 --percent at which shield is considered low and should activate avoidance. eg: 50%
local minimumRemainingReloadTimeG = 0.9 --seconds before actual reloading finish which avoidance should de-activate (note: overriden by 1/4 of weapon's reload time if its bigger). eg: 0.9 second before finish (or 7 second for spiderantiheavy)
local thresholdForArtyG = 459 --elmo (weapon range) before unit is considered an arty. Arty will never set enemy as target and will always avoid. default: 459elmo (1 elmo smaller than Rocko range)
local maximumMeleeRangeG = 101 --elmo (weapon range) before unit is considered a melee. Melee will target enemy and do not avoid at halfTargetBoxSize_g[1]. default: 101elmo (1 elmo bigger than Sycthe range)
local secondPerGameFrameG = 1/30 --engine depended second-per-frame (for calculating remaining reload time). eg: 0.0333 second-per-frame or 0.5sec/15frame
--Command Timeout constants:
local commandTimeoutG = 2 --multiply by 1.1 second
local consRetreatTimeoutG = 15 --multiply by 1.1 second, is overriden by epicmenu option
--NOTE:
--angle measurement and direction setting is based on right-hand coordinate system, but Spring uses left-hand coordinate system.
--So, math.sin is for x, and math.cos is for z, and math.atan2 input is x,z (is swapped with respect to the usual x y convention).
--those swap conveniently translate left-hand coordinate system into right-hand coordinate system.
--------------------------------------------------------------------------------
--Variables:
local unitInMotionG={} --store unitID
local skippingTimerG={0,0,echoTimestamp=0, networkDelay=0, averageDelay = 0.3, storedDelay = {}, index = 1, sumOfAllNetworkDelay=0, sumCounter=0} --variable: store the timing for next update, and store values for calculating average network delay.
local commandIndexTableG= {} --store latest widget command for comparison
local myTeamID_gbl=-1
local myPlayerID=-1
local gaiaTeamID = Spring.GetGaiaTeamID()
local attackerG= {} --for recording last attacker
local commandTTL_G = {} --for recording command's age. To check for expiration. Note: Each table entry is indexed by unitID
local iNotLagging_gbl = true --//variable: indicate if player(me) is lagging in current game. If lagging then do not process anything.
local selectedCons_Meta_gbl = {} --//variable: remember which Constructor is selected by player.
local waitForNetworkDelay_gbl = nil
local issuedOrderTo_G = {}
local allyClusterInfo_gbl = {coords={},age=0}
--------------------------------------------------------------------------------
--Methods:
---------------------------------Level 0
options_path = 'Settings/Unit Behaviour/Dynamic Avoidance' --//for use 'with gui_epicmenu.lua'
options_order = {'enableCons','enableCloaky','enableGround','enableGunship','enableReturnToBase','consRetreatTimeoutOption', 'cloakyAlwaysFlee','enableReloadAvoidance','retreatAvoidance','dbg_RemoveAvoidanceSplitSecond', 'dbg_IgnoreSelectedCons'}
options = {
enableCons = {
name = 'Enable for constructors',
type = 'bool',
value = true,
desc = 'Enable constructor\'s avoidance feature (WILL NOT include Commander).\n\nConstructors will avoid enemy while having move order. Constructor also return to base when encountering enemy during area-reclaim or area-ressurect command, and will try to avoid enemy while having build or repair or reclaim queue except when hold-position is issued.\n\nTips: order area-reclaim to the whole map, work best for cloaked constructor, but buggy for flying constructor. Default:On',
},
enableCloaky = {
name = 'Enable for cloakies',
type = 'bool',
value = true,
desc = 'Enable cloakies\' avoidance feature.\n\nCloakable bots will avoid enemy while having move order. Cloakable will also flee from enemy when idle except when hold-position state is used.\n\nTips: is optimized for Sycthe- your Sycthe will less likely to accidentally bump into enemy unit. Default:On',
},
enableGround = {
name = 'Enable for ground units',
type = 'bool',
value = true,
desc = 'Enable for ground units (INCLUDE Commander).\n\nAll ground unit will avoid enemy while being outside camera view and/or while reloading except when hold-position state is used.\n\nTips:\n1) is optimized for masses of Thug or Knight.\n2) You can use Guard to make your unit swarm the guarded unit in presence of enemy.\nDefault:On',
},
enableGunship = {
name = 'Enable for gunships',
type = 'bool',
value = false,
desc = 'Enable gunship\'s avoidance behaviour .\n\nGunship will avoid enemy while outside camera view and/or while reloading except when hold-position state is used.\n\nTips: to create a hit-&-run behaviour- set the fire-state options to hold-fire (can be buggy). Default:Off',
},
-- enableAmphibious = {
-- name = 'Enable for amphibious',
-- type = 'bool',
-- value = true,
-- desc = 'Enable amphibious unit\'s avoidance feature (including Commander, and submarine). Unit avoid enemy while outside camera view OR when reloading, but units with hold position state is excluded..',
-- },
enableReloadAvoidance = {
name = "Jink during attack",
type = 'bool',
value = true,
desc = "Unit with slow reload will randomly jink to random direction when attacking. NOTE: This have no benefit and bad versus fast attacker or fast weapon but have high chance of dodging versus slow ballistic weapon. Default:On",
},
enableReturnToBase = {
name = "Find base",
type = 'bool',
value = true,
desc = "Allow constructor to return to base when having area-reclaim or area-ressurect command, else it will return to center of the circle when retreating. \n\nTips: build 3 new buildings at new location to identify as base, unit will automatically select nearest base. Default:On",
},
consRetreatTimeoutOption = {
name = 'Constructor retreat auto-expire:',
type = 'number',
value = 3,
desc = "Amount in second before constructor retreat command auto-expire (is deleted), and then constructor will return to its previous area-reclaim command.\n\nTips: small value is better.",
min=3,max=15,step=1,
OnChange = function(self)
consRetreatTimeoutG = self.value
Spring.Echo(string.format ("%.1f", 1.1*consRetreatTimeoutG) .. " second")
end,
},
cloakyAlwaysFlee = {
name = 'Cloakies always flee',
type = 'bool',
value = false,
desc = 'Force cloakies & constructor to always flee from enemy when idle except if they are under hold-position state. \n\nNote: Unit can wander around and could put themselves in danger. Default:Off',
},
retreatAvoidance = {
name = 'Retreating unit always flee',
type = 'bool',
value = true,
desc = 'Force retreating unit to always avoid the enemy (Note: this require the use of RETREAT functionality provided by cmd_retreat.lua widget a.k.a unit retreat widget). Default:On',
},
dbg_RemoveAvoidanceSplitSecond = {
name = 'Debug: Constructor instant retreat',
type = 'bool',
value = true,
desc = "Widget to issue a retreat order first before issuing an avoidance (to reduce chance of avoidance putting constructor into more danger).\n\nDefault:On.",
advanced = true,
},
dbg_IgnoreSelectedCons ={
name = 'Debug: Ignore current selection',
type = 'bool',
value = false,
desc = "Selected constructor(s) will be ignored by widget.\nNote: there's a second delay before unit is ignored/re-acquire after selection/de-selection.\n\nDefault:Off",
--advanced = true,
},
}
function widget:Initialize()
skippingTimerG.echoTimestamp = spGetGameSeconds()
myPlayerID=Spring.GetMyPlayerID()
local _, _, spec = Spring.GetPlayerInfo(myPlayerID, false)
if spec then widgetHandler:RemoveWidget() return false end
myTeamID_gbl= spGetMyTeamID()
if (turnOnEcho == 1) then Spring.Echo("myTeamID_gbl(Initialize)" .. myTeamID_gbl) end
end
function widget:PlayerChanged(playerID)
if Spring.GetSpectatingState() then widgetHandler:RemoveWidget() end
end
--execute different function at different timescale
function widget:Update()
-------retrieve global table, localize global table
local commandIndexTable=commandIndexTableG
local unitInMotion = unitInMotionG
local skippingTimer = skippingTimerG
local attacker = attackerG
local commandTTL = commandTTL_G
local selectedCons_Meta = selectedCons_Meta_gbl
local cmd_then_DoCalculation_delay = cmd_then_DoCalculation_delayG
local myTeamID = myTeamID_gbl
local waitForNetworkDelay = waitForNetworkDelay_gbl
local allyClusterInfo = allyClusterInfo_gbl
-----
if iNotLagging_gbl then
local now=spGetGameSeconds()
--REFRESH UNIT LIST-- *not synced with avoidance*
if (now >= skippingTimer[1]) then --wait until 'skippingTimer[1] second', then do "RefreshUnitList()"
if (turnOnEcho == 1) then Spring.Echo("-----------------------RefreshUnitList") end
unitInMotion, attacker, commandTTL, selectedCons_Meta =RefreshUnitList(attacker, commandTTL) --create unit list
allyClusterInfo["age"]=allyClusterInfo["age"]+1 --indicate that allyClusterInfo is 1 cycle older
local projectedDelay=ReportedNetworkDelay(myPlayerID, 1.1) --create list every 1.1 second OR every (0+latency) second, depending on which is greater.
skippingTimer[1]=now+projectedDelay --wait until next 'skippingTimer[1] second'
--check if under lockdown for overextended time
if waitForNetworkDelay then
if now - waitForNetworkDelay[1] > 4 then
for unitID,_ in pairs(issuedOrderTo_G) do
issuedOrderTo_G[unitID] = nil
end
waitForNetworkDelay = nil
end
end
if (turnOnEcho == 1) then Spring.Echo("-----------------------RefreshUnitList") end
end
--GATHER SOME INFORMATION ON UNITS-- *part 1, start*
if (now >=skippingTimer[2]) and (not waitForNetworkDelay) then --wait until 'skippingTimer[2] second', and wait for 'LUA message received', and wait for 'cycle==1', then do "DoCalculation()"
if (turnOnEcho == 1) then Spring.Echo("-----------------------DoCalculation") end
local infoForDoCalculation = { unitInMotion,commandIndexTable, attacker,
selectedCons_Meta,myTeamID,
skippingTimer, now, commandTTL,
waitForNetworkDelay,allyClusterInfo
}
local outputTable,isAvoiding =DoCalculation(infoForDoCalculation)
commandIndexTable = outputTable["commandIndexTable"]
commandTTL = outputTable["commandTTL"]
waitForNetworkDelay = outputTable["waitForNetworkDelay"]
allyClusterInfo = outputTable["allyClusterInfo"]
if isAvoiding then
skippingTimer.echoTimestamp = now -- --prepare delay statistic to measure new delay (aka: reset stopwatch), --same as "CalculateNetworkDelay("restart", , )"^/
else
skippingTimer[2] = now + cmd_then_DoCalculation_delay --wait until 'cmd_then_DoCalculation_delayG'. The longer the better. The delay allow reliable unit direction to be derived from unit's motion
end
if (turnOnEcho == 1) then Spring.Echo("-----------------------DoCalculation") end
end
if (turnOnEcho == 1) then
Spring.Echo("unitInMotion(Update):")
Spring.Echo(unitInMotion)
end
end
-------return global table
allyClusterInfo_gbl = allyClusterInfo
commandIndexTableG=commandIndexTable
unitInMotionG = unitInMotion
skippingTimerG = skippingTimer
attackerG = attacker
commandTTL_G = commandTTL
selectedCons_Meta_gbl = selectedCons_Meta
waitForNetworkDelay_gbl = waitForNetworkDelay
-----
end
function widget:GameProgress(serverFrameNum) --//see if player are lagging behind the server in the current game. If player is lagging then trigger a switch, (this switch will tell the widget to stop processing units).
local myFrameNum = spGetGameFrame()
local frameNumDiff = serverFrameNum - myFrameNum
if frameNumDiff > 120 then --// 120 frame means: a 4 second lag. Consider me is lagging if my frame differ from server by more than 4 second.
iNotLagging_gbl = false
else --// consider me not lagging if my frame differ from server's frame for less than 4 second.
iNotLagging_gbl = true
end
end
function widget:UnitDestroyed(unitID, unitDefID, unitTeam)
if commandTTL_G[unitID] then --empty watch list for this unit when unit die
commandTTL_G[unitID] = nil
end
if commandIndexTableG[unitID] then
commandIndexTableG[unitID] = nil
end
if myTeamID_gbl==unitTeam and issuedOrderTo_G[unitID] then
CountdownNetworkDelayWait(unitID)
end
end
function widget:UnitGiven(unitID, unitDefID, newTeam,oldTeam)
if oldTeam == myTeamID_gbl then
if commandTTL_G[unitID] then --empty watch list for this unit is shared away
commandTTL_G[unitID] = nil
end
if commandIndexTableG[unitID] then
commandIndexTableG[unitID] = nil
end
end
if myTeamID_gbl==oldTeam and issuedOrderTo_G[unitID] then
CountdownNetworkDelayWait(unitID)
end
end
function widget:UnitCommand(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions)
if myTeamID_gbl==unitTeam and issuedOrderTo_G[unitID] then
if (CMD.INSERT == cmdID and cmdParams[2] == CMD_RAW_MOVE) and
cmdParams[4] == issuedOrderTo_G[unitID][1] and
cmdParams[5] == issuedOrderTo_G[unitID][2] and
cmdParams[6] == issuedOrderTo_G[unitID][3] then
CountdownNetworkDelayWait(unitID)
end
end
end
---------------------------------Level 0 Top level
---------------------------------Level1 Lower level
-- return a refreshed unit list, else return a table containing NIL
function RefreshUnitList(attacker, commandTTL)
local stdDecloakDist = stdDecloakDist_fG
local thresholdForArty = thresholdForArtyG
local maximumMeleeRange = maximumMeleeRangeG
----------------------------------------------------------
local allMyUnits = spGetTeamUnits(myTeamID_gbl)
local arrayIndex=0
local relevantUnit={}
local selectedUnits = (spGetSelectedUnits()) or {}
local selectedUnits_Meta = {}
local selectedCons_Meta = {}
for i = 1, #selectedUnits, 1 do
local unitID = selectedUnits[i]
selectedUnits_Meta[unitID]=true
end
local metaForVisibleUnits = {}
local visibleUnits=spGetVisibleUnits(myTeamID_gbl)
for _, unitID in ipairs(visibleUnits) do --memorize units that is in view of camera
metaForVisibleUnits[unitID]="yes" --flag "yes" for visible unit (in view) and by default flag "nil" for out of view unit
end
for _, unitID in ipairs(allMyUnits) do
if unitID~=nil then --skip end of the table
-- additional hitchiking function: refresh attacker's list
attacker = RetrieveAttackerList (unitID, attacker)
-- additional hitchiking function: refresh WATCHDOG's list
commandTTL = RefreshWatchdogList (unitID, commandTTL)
--
local unitDefID = spGetUnitDefID(unitID)
local unitDef = UnitDefs[unitDefID]
local unitSpeed =unitDef["speed"]
local decloakScaling = math.max((unitDef["decloakDistance"] or 0),stdDecloakDist)/stdDecloakDist
local unitInView = metaForVisibleUnits[unitID] --transfer "yes" or "nil" from meta table into a local variable
local _,_,inbuild = spGetUnitIsStunned(unitID)
if (unitSpeed>0) and (not inbuild) then
local unitType = 0 --// category that control WHEN avoidance is activated for each unit. eg: Category 2 only enabled when not in view & when guarding units. Used by 'GateKeeperOrCommandFilter()'
local fixedPointType = 1 --//category that control WHICH avoidance behaviour to use. eg: Category 2 priotize avoidance and prefer to ignore user's command when enemy is close. Used by 'CheckWhichFixedPointIsStable()'
if (unitDef.isBuilder or unitDef["canCloak"]) and not unitDef.customParams.commtype then --include only constructor and cloakies, and not com
unitType =1 --//this unit-type will do avoidance even in camera view
local isBuilder_ignoreTrue = false
if unitDef.isBuilder then
isBuilder_ignoreTrue = (options.dbg_IgnoreSelectedCons.value == true and selectedUnits_Meta[unitID] == true) --is (epicMenu force-selection-ignore is true? AND unit is a constructor?)
if selectedUnits_Meta[unitID] then
selectedCons_Meta[unitID] = true --remember selected Constructor
end
end
if (unitDef.isBuilder and options.enableCons.value==false) or (isBuilder_ignoreTrue) then --//if ((Cons epicmenu option is false) OR (epicMenu force-selection-ignore is true)) AND it is a constructor, then... exclude (this) Cons
unitType = 0 --//this unit-type excluded from avoidance
end
if unitDef["canCloak"] then --only cloakies + constructor that is cloakies
fixedPointType=2 --//use aggressive behaviour (avoid more & more likely to ignore the users)
if options.enableCloaky.value==false or (isBuilder_ignoreTrue) then --//if (Cloaky option is false) OR (epicMenu force-selection-ignore is true AND unit is a constructor) then exclude Cloaky
unitType = 0
end
end
--elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) and not unitDef["canSubmerge"] then --include all ground unit, but excluding com & amphibious
elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) then --include all ground unit, including com
unitType =2 --//this unit type only have avoidance outside camera view & while reloading (in camera view)
if options.enableGround.value==false then --//if Ground unit epicmenu option is false then exclude Ground unit
unitType = 0
end
elseif (unitDef.hoverAttack== true) then --include gunships
unitType =3 --//this unit-type only have avoidance outside camera view & while reloading (in camera view)
if options.enableGunship.value==false then --//if Gunship epicmenu option is false then exclude Gunship
unitType = 0
end
-- elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) and unitDef["canSubmerge"] then --include all amphibious unit & com
-- unitType =4 --//this unit type only have avoidance outside camera view
-- if options.enableAmphibious.value==false then --//if Gunship epicmenu option is false then exclude Gunship
-- unitType = 0
-- end
end
if (unitType>0) then
local unitShieldPower, reloadableWeaponIndex,reloadTime,range,weaponType= -1, -1,-1,-1,-1
unitShieldPower, reloadableWeaponIndex,reloadTime,range = CheckWeaponsAndShield(unitDef)
arrayIndex=arrayIndex+1
if range < maximumMeleeRange then
weaponType = 0
elseif range< thresholdForArty then
weaponType = 1
else
weaponType = 2
end
relevantUnit[arrayIndex]={unitID = unitID, unitType = unitType, unitSpeed = unitSpeed, fixedPointType = fixedPointType, decloakScaling = decloakScaling,weaponInfo = {unitShieldPower = unitShieldPower, reloadableWeaponIndex = reloadableWeaponIndex,reloadTime = reloadTime,range=range}, isVisible = unitInView, weaponType = weaponType}
end
end
if (turnOnEcho == 1) then --for debugging
Spring.Echo("unitID(RefreshUnitList)" .. unitID)
Spring.Echo("unitDef[humanName](RefreshUnitList)" .. unitDef["humanName"])
Spring.Echo("((unitDef[builder] or unitDef[canCloak]) and unitDef[speed]>0)(RefreshUnitList):")
Spring.Echo((unitDef.isBuilder or unitDef["canCloak"]) and unitDef["speed"]>0)
end
end
end
relevantUnit["count"]=arrayIndex -- store the array's lenght
if (turnOnEcho == 1) then
Spring.Echo("allMyUnits(RefreshUnitList): ")
Spring.Echo(allMyUnits)
Spring.Echo("relevantUnit(RefreshUnitList): ")
Spring.Echo(relevantUnit)
end
return relevantUnit, attacker, commandTTL, selectedCons_Meta
end
-- detect initial enemy separation to detect "fleeing enemy" later
function DoCalculation(passedInfo)
local unitInMotion = passedInfo[1]
local attacker = passedInfo[3]
local selectedCons_Meta = passedInfo[4]
-----
local isAvoiding = nil
local persistentData = {
commandIndexTable= passedInfo[2],
myTeamID= passedInfo[5],
skippingTimer = passedInfo[6],
now = passedInfo[7],
commandTTL=passedInfo[8],
waitForNetworkDelay=passedInfo[9],
allyClusterInfo= passedInfo[10],
}
local gateKeeperOutput = {
cQueueTemp=nil,
allowExecution=nil,
reloadAvoidance=nil,
}
local idTargetOutput = {
targetCoordinate = nil,
newCommand = nil,
boxSizeTrigger = nil,
graphCONSTANTtrigger = nil,
fixedPointCONSTANTtrigger = nil,
case = nil,
targetID = nil,
}
if unitInMotion["count"] and unitInMotion["count"]>0 then --don't execute if no unit present
for i=1, unitInMotion["count"], 1 do
local unitID= unitInMotion[i]["unitID"] --get unitID for commandqueue
if not spGetUnitIsDead(unitID) and (spGetUnitTeam(unitID)==persistentData["myTeamID"]) then --prevent execution if unit died during transit
local cQueue = spGetCommandQueue(unitID,-1)
gateKeeperOutput = GateKeeperOrCommandFilter(cQueue,persistentData, unitInMotion[i]) --filter/alter unwanted unit state by reading the command queue
if gateKeeperOutput["allowExecution"] then
--cQueue = cQueueTemp --cQueueTemp has been altered for identification, copy it to cQueue for use in DoCalculation() phase (note: command is not yet issued)
--local boxSizeTrigger= unitInMotion[i][2]
idTargetOutput=IdentifyTargetOnCommandQueue(cQueue,persistentData,gateKeeperOutput,unitInMotion[i]) --check old or new command
if selectedCons_Meta[unitID] and idTargetOutput["boxSizeTrigger"]~= 4 then --if unitIsSelected and NOT using GUARD 'halfboxsize' (ie: is not guarding) then:
idTargetOutput["boxSizeTrigger"] = 1 -- override all reclaim/ressurect/repair's deactivation 'halfboxsize' with the one for MOVE command (give more tolerance when unit is selected)
end
local reachedTarget = TargetBoxReached(unitID, idTargetOutput) --check if widget should ignore command
if ((idTargetOutput["newCommand"] and gateKeeperOutput["cQueueTemp"][1].id==CMD_RAW_MOVE) or gateKeeperOutput["cQueueTemp"][2].id==CMD_RAW_MOVE) and (unitInMotion[i]["isVisible"]~= "yes") then --if unit is issued a move Command and is outside user's view. Note: is using cQueueTemp because cQueue can be NIL
reachedTarget = false --force unit to continue avoidance despite close to target (try to circle over target until seen by user)
elseif (idTargetOutput["case"] == "none") then
reachedTarget = true --do not process unhandled command. This fix a case of unwanted behaviour when ZK's SmartAI issued a fight command on top of Avoidance's order and cause conflicting behaviour.
elseif (not gateKeeperOutput["reloadAvoidance"] and idTargetOutput["case"] == 'attack') then
reachedTarget = true --do not process direct attack command. Avoidance is not good enough for melee unit
end
if reachedTarget then --if reached target
if not idTargetOutput["newCommand"] then
spGiveOrderToUnit(unitID,CMD_REMOVE,{cQueue[1].tag,},0) --remove previously given (avoidance) command if reached target
end
persistentData["commandIndexTable"][unitID]=nil --empty the commandIndex (command history)
else --execute when target not reached yet
local losRadius = GetUnitLOSRadius(idTargetOutput["case"],unitInMotion[i]) --get LOS. also custom LOS for case=="attack" & weapon range >0
local isMeleeAttacks = (idTargetOutput["case"] == 'attack' and unitInMotion[i]["weaponType"] == 0)
local excludedEnemyID = (isMeleeAttacks) and idTargetOutput["targetID"]
local surroundingUnits = GetAllUnitsInRectangle(unitID, losRadius, attacker,excludedEnemyID) --catalogue enemy
if surroundingUnits["count"]~=0 then --execute when enemy exist
--local unitType =unitInMotion[i]["unitType"]
--local unitSSeparation, losRadius = CatalogueMovingObject(surroundingUnits, unitID, lastPosition, unitType, losRadius) --detect initial enemy separation & alter losRadius when unit submerged
local unitSSeparation, losRadius = CatalogueMovingObject(surroundingUnits, unitID, losRadius) --detect initial enemy separation & alter losRadius when unit submerged
local impatienceTrigger = GetImpatience(idTargetOutput,unitID, persistentData)
if (turnOnEcho == 1) then
Spring.Echo("unitsSeparation(DoCalculation):")
Spring.Echo(unitsSeparation)
end
local avoidanceCommand,orderArray= InsertCommandQueue(unitID,cQueue,gateKeeperOutput["cQueueTemp"],idTargetOutput["newCommand"],persistentData)--delete old widget command, update commandTTL, and send constructor to base for retreat
if avoidanceCommand or (not options.dbg_RemoveAvoidanceSplitSecond.value) then
if idTargetOutput["targetCoordinate"][1] == -1 then --no target
idTargetOutput["targetCoordinate"] = UseNearbyAllyAsTarget(unitID,persistentData) --eg: when retreating to nearby ally
end
local newX, newZ = AvoidanceCalculator(losRadius,surroundingUnits,unitSSeparation,impatienceTrigger,persistentData,idTargetOutput,unitInMotion[i]) --calculate move solution
local newY=spGetGroundHeight(newX,newZ)
--Inserting command queue:--
if (cQueue==nil or #cQueue<2) and gateKeeperOutput["cQueueTemp"][1].id == cMD_DummyG then --if #cQueueSyncTest is less than 2 mean unit has widget's mono-command, and cMD_DummyG mean its idle & out of view:
orderArray[#orderArray+1]={CMD_INSERT, {0, CMD_RAW_MOVE, CMD.OPT_SHIFT, newX, newY, newZ}, {"alt"}} -- using SHIFT prevent unit from returning to old position. NOTE: we NEED to use insert here (rather than use direct move command) because in high-ping situation (where user's command do not register until last minute) user's command will get overriden if both widget's and user's command arrive at same time.
else
orderArray[#orderArray+1]={CMD_INSERT, {0, CMD_RAW_MOVE, CMD_OPT_INTERNAL, newX, newY, newZ}, {"alt"}} --spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_RAW_MOVE, CMD_OPT_INTERNAL, newX, newY, newZ}, {"alt"}), insert new command (Note: CMD_OPT_INTERNAL is used to mark that this command is widget issued and need not special treatment. ie: It won't get repeated if Repeat state is used.)
end
local lastIndx = persistentData["commandTTL"][unitID][1] --commandTTL[unitID]'s table lenght
persistentData["commandTTL"][unitID][lastIndx+1] = {countDown = commandTimeoutG, widgetCommand= {newX, newZ}} --//remember this command on watchdog's commandTTL table. It has 4x*RefreshUnitUpdateRate* to expire
persistentData["commandTTL"][unitID][1] = lastIndx+1 --refresh commandTTL[unitID]'s table lenght
persistentData["commandIndexTable"][unitID]["widgetX"]=newX --update the memory table. So that next update can use to check if unit has new or old (widget's) command
persistentData["commandIndexTable"][unitID]["widgetZ"]=newZ
--end--
end
local orderCount = #orderArray
if orderCount >0 then
spGiveOrderArrayToUnitArray ({unitID},orderArray)
isAvoiding = true
if persistentData["waitForNetworkDelay"] then
persistentData["waitForNetworkDelay"][2] = persistentData["waitForNetworkDelay"][2] + 1
else
persistentData["waitForNetworkDelay"] = {spGetGameSeconds(),1}
end
local moveOrderParams = orderArray[orderCount][2]
issuedOrderTo_G[unitID] = {moveOrderParams[4], moveOrderParams[5], moveOrderParams[6]}
end
end
end --reachedTarget
end --GateKeeperOrCommandFilter(cQueue, unitInMotion[i]) ==true
end --if spGetUnitIsDead(unitID)==false
end
end --if unitInMotion[1]~=nil
return persistentData,isAvoiding --send separation result away
end
function CountdownNetworkDelayWait(unitID)
issuedOrderTo_G[unitID] = nil
if waitForNetworkDelay_gbl then
waitForNetworkDelay_gbl[2] = waitForNetworkDelay_gbl[2] - 1
if waitForNetworkDelay_gbl[2]==0 then
waitForNetworkDelay_gbl = nil
-----------------
local skippingTimer = skippingTimerG --is global table
local cmd_then_DoCalculation_delay = cmd_then_DoCalculation_delayG
local now =spGetGameSeconds()
skippingTimer.networkDelay = now - skippingTimer.echoTimestamp --get the delay between previous Command and the latest 'LUA message Receive'
--Method 2: use rolling average
skippingTimer.storedDelay[skippingTimer.index] = skippingTimer.networkDelay --store network delay value in a rolling table
skippingTimer.index = skippingTimer.index+1 --table index ++
if skippingTimer.index > 11 then --roll the table/wrap around, so that the index circle the table. The 11-th sequence is for storing the oldest value, 1-st to 10-th sequence is for the average
skippingTimer.index = 1
end
skippingTimer.averageDelay = skippingTimer.averageDelay + skippingTimer.networkDelay/10 - (skippingTimer.storedDelay[skippingTimer.index] or 0.3)/10 --add new delay and minus old delay, also use 0.3sec as the old delay if nothing is stored yet.
--
skippingTimer[2] = now + cmd_then_DoCalculation_delay --wait until 'cmd_then_DoCalculation_delayG'. The longer the better. The delay allow reliable unit direction to be derived from unit's motion
skippingTimerG = skippingTimer
end
end
end
function ReportedNetworkDelay(playerIDa, defaultDelay)
local _,_,_,_,_,totalDelay = Spring.GetPlayerInfo(playerIDa, false)
if totalDelay==nil or totalDelay<=defaultDelay then return defaultDelay --if ping is too low: set the minimum delay
else return totalDelay --take account for lag + wait a little bit for any command to properly update
end
end
---------------------------------Level1
---------------------------------Level2 (level 1's call-in)
function RetrieveAttackerList (unitID, attacker)
local unitHealth,_,_,_,_ = spGetUnitHealth(unitID)
if attacker[unitID] == nil then --if attacker table is empty then fill with default value
attacker[unitID] = {id = nil, countDown = 0, myHealth = unitHealth}
end
if attacker[unitID].countDown >0 then attacker[unitID].countDown = attacker[unitID].countDown - 1 end --count-down until zero and stop
if unitHealth< attacker[unitID].myHealth then --if underattack then find out the attackerID
local attackerID = spGetUnitLastAttacker(unitID)
if attackerID~=nil then --if attackerID is found then mark the attackerID for avoidance
attacker[unitID].countDown = attacker[unitID].countDown + 3 --//add 3xUnitRefresh-rate (~3.3second) to attacker's TTL
attacker[unitID].id = attackerID
end
end
attacker[unitID].myHealth = unitHealth --refresh health data
return attacker
end
function RefreshWatchdogList (unitID, commandTTL)
if commandTTL[unitID] == nil then --if commandTTL table is empty then insert an empty table
commandTTL[unitID] = {1,} --Note: first entry is table lenght
else --//if commandTTL is not empty then perform check and update its content appropriately. Its not empty when widget has issued a new command
--//Method2: work by checking for cQueue after the command has expired. No latency could be as long as command's expiration time so it solve Method1's issue.
local returnToReclaimOffset = 1 --
for i=commandTTL[unitID][1], 2, -1 do --iterate downward over commandTTL, empty last entry when possible. Note: first table entry is the table's lenght, so we iterate down to only index 2
if commandTTL[unitID][i] ~= nil then
if commandTTL[unitID][i].countDown >0 then
commandTTL[unitID][i].countDown = commandTTL[unitID][i].countDown - (1*returnToReclaimOffset) --count-down until zero and stop. Each iteration is minus 1 and then exit loop after 1 enty, or when countDown==0 remove command and then go to next entry and minus 2 and exit loop.
break --//exit the iteration, do not go to next iteration until this entry expire first...
elseif commandTTL[unitID][i].countDown <=0 then --if commandTTL is found to reach ZERO then remove the command, assume a 'TIMEOUT', then remove *this* watchdog entry
local cQueue = spGetCommandQueue(unitID, 1) --// get unit's immediate command
local cmdID, _, cmdTag, firstParam, _, secondParam = Spring.GetUnitCurrentCommand(unitID)
if cmdID and
( firstParam == commandTTL[unitID][i].widgetCommand[1]) and
(secondParam == commandTTL[unitID][i].widgetCommand[2]) then --//if current command is similar to the one once issued by widget then delete it
spGiveOrderToUnit(unitID, CMD_REMOVE, {cmdTag}, 0)
end
commandTTL[unitID][i] = nil --empty watchdog entry
commandTTL[unitID][1] = i-1 --refresh table lenght
returnToReclaimOffset = 2 --when the loop iterate back to a reclaim command: remove 2 second from its countdown (accelerate expiration by 2 second). This is for aesthetic reason and didn't effect system's mechanic. Since constructor always retreat with 2 command (avoidance+return to base), remove the countdown from the avoidance.
end
end
end
end
return commandTTL
end
function CheckWeaponsAndShield (unitDef)
--global variable
local reloadableWeaponCriteria = reloadableWeaponCriteriaG --minimum reload time for reloadable weapon
----
local unitShieldPower, reloadableWeaponIndex =-1, -1 --assume unit has no shield and no reloadable/slow-loading weapons
local fastWeaponIndex = -1 --temporary variables
local fastestReloadTime, fastReloadRange = 999,-1
for currentWeaponIndex, weapons in ipairs(unitDef.weapons) do --reference: gui_contextmenu.lua by CarRepairer
local weaponsID = weapons.weaponDef
local weaponsDef = WeaponDefs[weaponsID]
if weaponsDef.name and not (weaponsDef.name:find('fake') or weaponsDef.name:find('noweapon')) then --reference: gui_contextmenu.lua by CarRepairer
if weaponsDef.isShield then
unitShieldPower = weaponsDef.shieldPower --remember the shield power of this unit
else --if not shield then this is conventional weapon
local reloadTime = weaponsDef.reload
if reloadTime < fastestReloadTime then --find the weapon with the smallest reload time
fastestReloadTime = reloadTime
fastReloadRange = weaponsDef.range
fastWeaponIndex = currentWeaponIndex --remember the index of the fastest weapon.
end
end
end
end
if fastestReloadTime > reloadableWeaponCriteria then --if the fastest reload cycle is greater than widget's update cycle, then:
reloadableWeaponIndex = fastWeaponIndex --remember the index of that fastest loading weapon
if (turnOnEcho == 1) then --debugging
Spring.Echo("reloadableWeaponIndex(CheckWeaponsAndShield):")
Spring.Echo(reloadableWeaponIndex)
Spring.Echo("fastestReloadTime(CheckWeaponsAndShield):")
Spring.Echo(fastestReloadTime)
end
end
return unitShieldPower, reloadableWeaponIndex,fastestReloadTime,fastReloadRange
end
function GateKeeperOrCommandFilter (cQueue,persistentData, unitInMotionSingleUnit)
local allowExecution = false
local reloadAvoidance = false -- indicate to way way downstream processes whether avoidance is based on weapon reload/shieldstate
if cQueue~=nil then --prevent ?. Forgot...
local isReloading = CheckIfUnitIsReloading(unitInMotionSingleUnit) --check if unit is reloading/shieldCritical
local unitID = unitInMotionSingleUnit["unitID"]
local holdPosition= (Spring.Utilities.GetUnitMoveState(unitID) == 0)
local unitType = unitInMotionSingleUnit["unitType"]
local unitInView = unitInMotionSingleUnit["isVisible"]
local retreating = false
if options.retreatAvoidance.value and WG.retreatingUnits then
retreating = (WG.retreatingUnits[unitID]~=nil or spGetUnitRulesParam(unitID,"isRetreating")==1)
end
--if ((unitInView ~= "yes") or isReloading or (unitType == 1 and options.cloakyAlwaysFlee.value)) then --if unit is out of user's vision OR is reloading OR is cloaky, and:
if (cQueue[1] == nil or #cQueue == 1) then --if unit is currently idle OR with-singular-mono-command (eg: automated move order or auto-attack), then:
--if (not holdPosition) then --if unit is not "hold position", then:
local idleOrIsDodging = (cQueue[1] == nil) or (#cQueue == 1 and cQueue[1].id == CMD_RAW_MOVE and (not cQueue[2] or cQueue[2].id~=false)) --is idle completely, or is given widget's CMD_RAW_MOVE and not spontaneous engagement signature (note: CMD_RAW_MOVE or any other command will not end with CMD_STOP when issued by widget)
local dummyCmd
if idleOrIsDodging then
cQueue={{id = cMD_DummyG, params = {-1 ,-1,-1}, options = {}}, {id = CMD_STOP, params = {-1 ,-1,-1}, options = {}}, nil} --select cMD_DummyG if unit is to flee without need to return to old position,
elseif cQueue[1].id < 0 then
cQueue[2] = {id = CMD_STOP, params = {-1 ,-1,-1}, options = {}} --automated build (mono command issued by CentralBuildAI widget). We append CMD_STOP so it look like normal build command.
else
cQueue={{id = cMD_Dummy_atkG, params = {-1 ,-1,-1}, options = {}}, {id = CMD_STOP, params = {-1 ,-1,-1}, options = {}}, nil} --select cMD_Dummy_atkG if unit is auto-attack & reloading (as in: isReloading + (no command or mono command)) and doesn't mind being bound to old position
end
--flag unit with a FAKE COMMAND. Will be used to initiate avoidance on idle unit & non-viewed unit. Note: this is not real command, its here just to trigger avoidance.
--Note2: negative target only deactivate attraction function, but avoidance function is still active & output new coordinate if enemy is around
--end
end
--end
if cQueue[1]~=nil then --prevent idle unit from executing the system (prevent crash), but idle unit with FAKE COMMAND (cMD_DummyG) is allowed.
local isStealthOrConsUnit = (unitType == 1)
local isNotViewed = (unitInView ~= "yes")
local isCommonConstructorCmd = (cQueue[1].id == CMD_REPAIR or cQueue[1].id < 0 or cQueue[1].id == CMD_RESURRECT)
local isReclaimCmd = (cQueue[1].id == CMD_RECLAIM)
local isMoveCommand = (cQueue[1].id == CMD_RAW_MOVE)
local isNormCommand = (isCommonConstructorCmd or isMoveCommand) -- ALLOW unit with command: repair (40), build (<0), reclaim (90), ressurect(125), move(10),
--local isStealthOrConsUnitTypeOrIsNotViewed = isStealthOrConsUnit or (unitInView ~= "yes" and unitType~= 3)--ALLOW only unit of unitType=1 OR (all unitTypes that is outside player's vision except gunship)
local isStealthOrConsUnitTypeOrIsNotViewed = isStealthOrConsUnit or isNotViewed--ALLOW unit of unitType=1 (cloaky, constructor) OR all unitTypes that is outside player's vision
local _1stAttackSignature = (cQueue[1].id == CMD_ATTACK)
local _1stGuardSignature = (cQueue[1].id == CMD_GUARD)
local _2ndAttackSignature = false --attack command signature
local _2ndGuardSignature = false --guard command signature
if #cQueue >=2 then --check if the command-queue is masked by widget's previous command, but the actual originality check will be performed by TargetBoxReached() later.
_2ndAttackSignature = (cQueue[1].id == CMD_RAW_MOVE and cQueue[2].id == CMD_ATTACK)
_2ndGuardSignature = (cQueue[1].id == CMD_RAW_MOVE and cQueue[2].id == CMD_GUARD)
end
local isAbundanceResource = (spGetTeamResources(persistentData["myTeamID"], "metal") > 10)
local isReloadingAttack = (isReloading and (((_1stAttackSignature or _2ndAttackSignature) and options.enableReloadAvoidance.value) or (cQueue[1].id == cMD_DummyG or cQueue[1].id == cMD_Dummy_atkG))) --any unit with attack command or was idle that is Reloading
local isGuardState = (_1stGuardSignature or _2ndGuardSignature)
local isAttackingState = (_1stAttackSignature or _2ndAttackSignature)
local isForceCloaked = spGetUnitIsCloaked(unitID) and (unitType==2 or unitType==3) --any unit with type 3 (gunship) or type 2 (ground units except cloaky) that is cloaked.
local isRealIdle = cQueue[1].id == cMD_DummyG --FAKE (IDLE) COMMAND
local isStealthOrConsUnitAlwaysFlee = isStealthOrConsUnit and options.cloakyAlwaysFlee.value
if ((isNormCommand or (isReclaimCmd and isAbundanceResource)) and isStealthOrConsUnitTypeOrIsNotViewed and not holdPosition) or --execute on: unit with generic mobility command (or reclaiming during abundance resource): for UnitType==1 unit (cloaky, constructor) OR for any unit outside player view... & which is not holding position
(isRealIdle and (isNotViewed or isStealthOrConsUnitAlwaysFlee) and not holdPosition) or --execute on: any unit that is really idle and out of view... & is not hold position
(isReloadingAttack and not holdPosition) or --execute on: any unit which is reloading... & is not holding position
-- (isAttackingState and isStealthOrConsUnitAlwaysFlee and not holdPosition) or --execute on: always-fleeing cloaky unit that about to attack... & is not holding position
(isGuardState and not holdPosition) or --execute on: any unit which is guarding another unit... & is not hold position
(isForceCloaked and isMoveCommand and not holdPosition) or --execute on: any normal unit being cloaked and is moving... & is not hold position.
(retreating and not holdPosition) --execute on: any retreating unit
then
local isReloadAvoidance = (isReloadingAttack and not holdPosition)
if isReloadAvoidance or #cQueue>=2 then --check cQueue for lenght to prevent STOP command from short circuiting the system (code downstream expect cQueue of length>=2)
if isReloadAvoidance or cQueue[2].id~=false then --prevent a spontaneous enemy engagement from short circuiting the system
allowExecution = true --allow execution
reloadAvoidance = isReloadAvoidance
end --if cQueue[2].id~=false
if (turnOnEcho == 1) then Spring.Echo(cQueue[2].id) end --for debugging
end --if #cQueue>=2
end --if ((cQueue[1].id==40 or cQueue[1].id<0 or cQueue[1].id==90 or cQueue[1].id==10 or cQueue[1].id==125) and (unitInMotion[i][2]==1 or unitInMotion[i].isVisible == nil)
end --if cQueue[1]~=nil
end --if cQueue~=nil
local output = {
cQueueTemp = cQueue,
allowExecution = allowExecution,
reloadAvoidance = reloadAvoidance,
}
return output --disallow/allow execution
end
--check if widget's command or user's command
function IdentifyTargetOnCommandQueue(cQueueOri,persistentData,gateKeeperOutput,unitInMotionSingleUnit) --//used by DoCalculation()
local unitID = unitInMotionSingleUnit["unitID"]
local commandIndexTable = persistentData["commandIndexTable"]
local newCommand=true -- immediately assume user's command
local output
--------------------------------------------------
if commandIndexTable[unitID]==nil then --memory was empty, so fill it with zeros or non-significant number
commandIndexTable[unitID]={widgetX=-2, widgetZ=-2 , patienceIndexA=0}
else
local a = -1
local c = -1
local b = math.modf(commandIndexTable[unitID]["widgetX"])
local d = math.modf(commandIndexTable[unitID]["widgetZ"])
if cQueueOri[1] then
a = math.modf(dNil(cQueueOri[1].params[1])) --using math.modf to remove trailing decimal (only integer for matching). In case high resolution cause a fail matching with server's numbers... and use dNil incase wreckage suddenly disappear.
c = math.modf(dNil(cQueueOri[1].params[3])) --dNil: if it is a reclaim or repair order (no z coordinate) then replace it with -1 (has similar effect to the "nil")
end
newCommand= (a~= b and c~=d)--compare current command with in memory
if (turnOnEcho == 1) then --debugging
Spring.Echo("unitID(IdentifyTargetOnCommandQueue)" .. unitID)
Spring.Echo("commandIndexTable[unitID][widgetX](IdentifyTargetOnCommandQueue):" .. commandIndexTable[unitID]["widgetX"])
Spring.Echo("commandIndexTable[unitID][widgetZ](IdentifyTargetOnCommandQueue):" .. commandIndexTable[unitID]["widgetZ"])
Spring.Echo("newCommand(IdentifyTargetOnCommandQueue):")
Spring.Echo(newCommand)
Spring.Echo("cQueueOri[1].params[1](IdentifyTargetOnCommandQueue):" .. cQueueOri[1].params[1])
Spring.Echo("cQueueOri[1].params[2](IdentifyTargetOnCommandQueue):" .. cQueueOri[1].params[2])
Spring.Echo("cQueueOri[1].params[3](IdentifyTargetOnCommandQueue):" .. cQueueOri[1].params[3])
if cQueueOri[2]~=nil then
Spring.Echo("cQueue[2].params[1](IdentifyTargetOnCommandQueue):")
Spring.Echo(cQueueOri[2].params[1])
Spring.Echo("cQueue[2].params[3](IdentifyTargetOnCommandQueue):")
Spring.Echo(cQueueOri[2].params[3])
end
end
end
if newCommand then --if user's new command
output = ExtractTarget (1,gateKeeperOutput["cQueueTemp"],unitInMotionSingleUnit)
commandIndexTable[unitID]["patienceIndexA"]=0 --//reset impatience counter
else --if widget's previous command
output = ExtractTarget (2,gateKeeperOutput["cQueueTemp"],unitInMotionSingleUnit)
end
output["newCommand"] = newCommand
persistentData["commandIndexTable"] = commandIndexTable --note: table is referenced by memory, so it will update even without return value
return output --return target coordinate
end
--ignore command set on this box
function TargetBoxReached (unitID, idTargetOutput)
----Global Constant----
local halfTargetBoxSize = halfTargetBoxSize_g
-----------------------
local boxSizeTrigger = idTargetOutput["boxSizeTrigger"]
local targetCoordinate = idTargetOutput["targetCoordinate"]
local currentX,_,currentZ = spGetUnitPosition(unitID)
local targetX = dNil(targetCoordinate[1]) -- use dNil if target asynchronously/spontaneously disappear: in that case it will replace "nil" with -1
local targetZ =targetCoordinate[3]
if targetX==-1 then
return false
end --if target is invalid (-1) then assume target not-yet-reached, return false (default state), and continue avoidance
local xDistanceToTarget = math.abs(currentX -targetX)
local zDistanceToTarget = math.abs(currentZ -targetZ)
if (turnOnEcho == 1) then
Spring.Echo("unitID(TargetBoxReached)" .. unitID)
Spring.Echo("currentX(TargetBoxReached)" .. currentX)
Spring.Echo("currentZ(TargetBoxReached)" .. currentZ)
Spring.Echo("cx(TargetBoxReached)" .. targetX)
Spring.Echo("cz(TargetBoxReached)" .. targetZ)
Spring.Echo("(xDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger] and zDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger])(TargetBoxReached):")
Spring.Echo((xDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger] and zDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger]))
end
local withinTargetBox = (xDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger] and zDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger])
return withinTargetBox --command outside this box return false
end
-- get LOS
function GetUnitLOSRadius(case,unitInMotionSingleUnit)
----Global Constant----
local extraLOSRadiusCONSTANT = extraLOSRadiusCONSTANTg
-----------------------
local fastestWeapon = unitInMotionSingleUnit["weaponInfo"]
local unitID =unitInMotionSingleUnit["unitID"]
local unitDefID= spGetUnitDefID(unitID)
local unitDef= UnitDefs[unitDefID]
local losRadius =550 --arbitrary (scout LOS)
if unitDef~=nil then --if unitDef is not empty then use the following LOS
losRadius= unitDef.losRadius --in normal case use real LOS
losRadius= losRadius + extraLOSRadiusCONSTANT --add extra detection range for beyond LOS (radar)
if case=="attack" then --if avoidance is for attack enemy: use special LOS
local unitFastestReloadableWeapon = fastestWeapon["reloadableWeaponIndex"] --retrieve the quickest reloadable weapon index
if unitFastestReloadableWeapon ~= -1 then
local weaponRange = fastestWeapon["range"] --retrieve weapon range
losRadius = math.max(weaponRange*0.75, losRadius) --select avoidance's detection-range to 75% of weapon range or maintain to losRadius, select which is the biggest (Note: big LOSradius mean big detection but also big "distanceCONSTANTunit_G" if "useLOS_distanceCONSTANTunit_G==true", thus bigger avoidance circle)
end
end
if unitDef.isBuilder then
losRadius = losRadius + extraLOSRadiusCONSTANT --add additional/more detection range for constructors for quicker reaction vs enemy radar dot
end
end
return losRadius
end
--return a table of surrounding enemy
function GetAllUnitsInRectangle(unitID, losRadius, attacker,excludedEnemyID)
local x,y,z = spGetUnitPosition(unitID)
local unitDefID = spGetUnitDefID(unitID)
local unitDef = UnitDefs[unitDefID]
local iAmConstructor = unitDef.isBuilder
local iAmNotCloaked = not spGetUnitIsCloaked(unitID) --unitID is "this" unit (our unit)
local unitsInRectangle = spGetUnitsInRectangle(x-losRadius, z-losRadius, x+losRadius, z+losRadius)
local relevantUnit={}
local arrayIndex=0
--add attackerID into enemy list
relevantUnit, arrayIndex = AddAttackerIDToEnemyList (unitID, losRadius, relevantUnit, arrayIndex, attacker)
--
for _, rectangleUnitID in ipairs(unitsInRectangle) do
local isAlly= spIsUnitAllied(rectangleUnitID)
if (rectangleUnitID ~= unitID) and not isAlly and rectangleUnitID~=excludedEnemyID then --filter out ally units and self and exclusive-exclusion
local rectangleUnitTeamID = spGetUnitTeam(rectangleUnitID)
if (rectangleUnitTeamID ~= gaiaTeamID) then --filter out gaia (non aligned unit)
local recUnitDefID = spGetUnitDefID(rectangleUnitID)
local registerEnemy = false
if recUnitDefID~=nil and (iAmConstructor and iAmNotCloaked) then --if enemy is in LOS & I am a visible constructor: then
local recUnitDef = UnitDefs[recUnitDefID] --retrieve enemy definition
local enemyParalyzed,_,_ = spGetUnitIsStunned (rectangleUnitID)
local disarmed = spGetUnitRulesParam(rectangleUnitID,"disarmed")
if recUnitDef["weapons"][1]~=nil and not enemyParalyzed and (not disarmed or disarmed ~= 1) then -- check enemy for weapons and paralyze effect
registerEnemy = true --register the enemy only if it armed & wasn't paralyzed
end
else --if enemy is detected (in LOS or RADAR), and iAm a generic units OR any cloaked constructor then:
if iAmNotCloaked then --if I am not cloaked
local enemyParalyzed,_,_ = Spring.GetUnitIsStunned (rectangleUnitID)
if not enemyParalyzed then -- check for paralyze effect
registerEnemy = true --register enemy if it's not paralyzed
end
else --if I am cloaked (constructor or cloakies), then:
registerEnemy = true --register all enemy (avoid all unit)
end
end
if registerEnemy then
arrayIndex=arrayIndex+1
relevantUnit[arrayIndex]=rectangleUnitID --register enemy
end
end
end
end
relevantUnit["count"] = arrayIndex
return relevantUnit
end
--allow a unit to recognize fleeing enemy; so it doesn't need to avoid them
function CatalogueMovingObject(surroundingUnits, unitID,losRadius)
local unitsSeparation={}
if (surroundingUnits["count"] and surroundingUnits["count"]>0) then --don't catalogue anything if no enemy exist
local unitDepth = 99
local sonarDetected = false
local halfLosRadius = losRadius/2
--if unitType == 4 then --//if unit is amphibious, then:
_,unitDepth,_ = spGetUnitPosition(unitID) --//get unit's y-axis. Less than 0 mean submerged.
--end
local unitXvel,_,unitZvel = spGetUnitVelocity(unitID)
local unitSpeed = math.sqrt(unitXvel*unitXvel+unitZvel*unitZvel)
for i=1,surroundingUnits["count"],1 do --//iterate over all enemy list.
local unitRectangleID=surroundingUnits[i]
if (unitRectangleID ~= nil) then
local recXvel,_,recZvel = spGetUnitVelocity(unitRectangleID)
recXvel = recXvel or 0
recZvel = recZvel or 0
local recSpeed = math.sqrt(recXvel*recXvel+recZvel*recZvel)
local relativeAngle = GetUnitRelativeAngle (unitID, unitRectangleID)
local unitDirection,_,_ = GetUnitDirection(unitID)
local unitSeparation = spGetUnitSeparation (unitID, unitRectangleID, true)
if math.abs(unitDirection- relativeAngle)< (collisionAngleG) or (recSpeed>3*unitSpeed) then --unit inside the collision angle? or is super fast? remember unit currrent saperation for comparison again later
unitsSeparation[unitRectangleID]=unitSeparation
else --unit outside the collision angle? set to an arbitrary 9999 which mean "do not need comparision, always avoid"
unitsSeparation[unitRectangleID]=9999
end
if unitDepth <0 then --//if unit is submerged, then:
--local enemySonarRadius = (spGetUnitSensorRadius(unitRectangleID,"sonar") or 0)
local enemyDefID = spGetUnitDefID(unitRectangleID)
local unitDefsSonarContent = 9999 --//set to very large so that any un-identified contact is assumed as having sonar (as threat).
if UnitDefs[enemyDefID]~=nil then
unitDefsSonarContent = UnitDefs[enemyDefID].sonarRadius
end
local enemySonarRadius = (unitDefsSonarContent or 0)
if enemySonarRadius > halfLosRadius then --//check enemy for sonar
sonarDetected = true
end
end
end
end
if (not sonarDetected) and (unitDepth < 0) then --//if enemy doesn't have sonar but Iam still submerged, then:
losRadius = halfLosRadius --// halven the unit's 'avoidance' range. Don't need to avoid enemy if enemy are blind.
end
end
if (turnOnEcho == 1) then
Spring.Echo("unitSeparation(CatalogueMovingObject):")
Spring.Echo(unitsSeparation)
end
return unitsSeparation, losRadius
end
function GetImpatience(idTargetOutput,unitID, persistentData)
local newCommand = idTargetOutput["newCommand"]
local commandIndexTable = persistentData["commandIndexTable"]
local impatienceTrigger=1 --zero will de-activate auto reverse
if commandIndexTable[unitID]["patienceIndexA"]>=6 then impatienceTrigger=0 end --//if impatience index level 6 (after 6 time avoidance) then trigger impatience. Impatience will deactivate/change some values downstream
if not newCommand and activateImpatienceG==1 then
commandIndexTable[unitID]["patienceIndexA"]=commandIndexTable[unitID]["patienceIndexA"]+1 --increase impatience index if impatience system is activate
end
if (turnOnEcho == 1) then Spring.Echo("commandIndexTable[unitID][patienceIndexA] (GetImpatienceLevel) " .. commandIndexTable[unitID]["patienceIndexA"]) end
persistentData["commandIndexTable"] = commandIndexTable --Note: this will update since its referenced by memory
return impatienceTrigger
end
function UseNearbyAllyAsTarget(unitID, persistentData)
local x,y,z = -1,-1,-1
if WG.OPTICS_cluster then
local allyClusterInfo = persistentData["allyClusterInfo"]
local myTeamID = persistentData["myTeamID"]
if (allyClusterInfo["age"]>= 3) then --//only update after 4 cycle:
allyClusterInfo["age"]= 0
allyClusterInfo["coords"] = {}
local allUnits = spGetAllUnits()
local unorderedUnitList = {}
for i=1, #allUnits, 1 do --//convert unit list into a compatible format for the Clustering function below
local unitID_list = allUnits[i]
if spIsUnitAllied(unitID_list, unitID) then
local x,y,z = spGetUnitPosition(unitID_list)
local unitDefID_list = spGetUnitDefID(unitID_list)
local unitDef = UnitDefs[unitDefID_list]
local unitSpeed =unitDef["speed"]
if (unitSpeed>0) then --//if moving units
if (unitDef.isBuilder) and not unitDef.customParams.commtype then --if constructor
--intentionally empty. Not include builder.
elseif unitDef.customParams.commtype then --if COMMANDER,
unorderedUnitList[unitID_list] = {x,y,z} --//store
elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) then --if all ground unit, amphibious, and ships (except commander)
unorderedUnitList[unitID_list] = {x,y,z} --//store
elseif (unitDef.hoverAttack== true) then --if gunships
--intentionally empty. Not include gunships.
end
else --if buildings
unorderedUnitList[unitID_list] = {x,y,z} --//store
end
end
end
local cluster, _ = WG.OPTICS_cluster(unorderedUnitList, 600,3, myTeamID,300) --//find clusters with atleast 3 unit per cluster and with at least within 300-elmo from each other
for index=1 , #cluster do
local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0
for unitIndex=1, #cluster[index] do
local unitID_list = cluster[index][unitIndex]
local x,y,z= unorderedUnitList[unitID_list][1],unorderedUnitList[unitID_list][2],unorderedUnitList[unitID_list][3] --// get stored unit position
sumX= sumX+x
sumY = sumY+y
sumZ = sumZ+z
unitCount=unitCount+1
end
meanX = sumX/unitCount --//calculate center of cluster
meanY = sumY/unitCount
meanZ = sumZ/unitCount
allyClusterInfo["coords"][#allyClusterInfo["coords"]+1] = {meanX, meanY, meanZ} --//record cluster position
end
end --//end cluster detection
local nearestCluster = -1
local nearestDistance = 99999
local coordinateList = allyClusterInfo["coords"]
local px,_,pz = spGetUnitPosition(unitID)
for i=1, #coordinateList do
local distance = Distance(coordinateList[i][1], coordinateList[i][3] , px, pz)
if distance < nearestDistance then
nearestDistance = distance
nearestCluster = i
end
end
if nearestCluster > 0 then
x,y,z = coordinateList[nearestCluster][1],coordinateList[nearestCluster][2],coordinateList[nearestCluster][3]
end
persistentData["allyClusterInfo"] = allyClusterInfo --update content
end
if x == -1 then
local nearbyAllyUnitID = Spring.GetUnitNearestAlly (unitID, 600)
if nearbyAllyUnitID ~= nearbyAllyUnitID then
x,y,z = spGetUnitPosition(nearbyAllyUnitID)
end
end
return {x,y,z}
end
function AvoidanceCalculator(losRadius,surroundingUnits,unitsSeparation,impatienceTrigger,persistentData,idTargetOutput,unitInMotionSingleUnit)
local newCommand = idTargetOutput["newCommand"]
local skippingTimer = persistentData["skippingTimer"]
local unitID = unitInMotionSingleUnit["unitID"]
local unitSpeed = unitInMotionSingleUnit["unitSpeed"]
local graphCONSTANTtrigger = idTargetOutput["graphCONSTANTtrigger"]
local fixedPointCONSTANTtrigger = idTargetOutput["fixedPointCONSTANTtrigger"]
local targetCoordinate = idTargetOutput["targetCoordinate"]
local decloakScaling = unitInMotionSingleUnit["decloakScaling"]
if (unitID~=nil) and (targetCoordinate ~= nil) then --prevent idle/non-existent/ unit with invalid command from using collision avoidance
local aCONSTANT = aCONSTANTg --attractor constant (amplitude multiplier)
local obsCONSTANT =obsCONSTANTg --repulsor constant (amplitude multiplier)
local unitDirection, _, wasMoving = GetUnitDirection(unitID) --get unit direction
local targetAngle = 0
local fTarget = 0
local fTargetSlope = 0
----
aCONSTANT = aCONSTANT[graphCONSTANTtrigger[1]] --//select which 'aCONSTANT' value
obsCONSTANT = obsCONSTANT[graphCONSTANTtrigger[2]]*decloakScaling --//select which 'obsCONSTANT' value to use & increase obsCONSTANT value when unit has larger decloakDistance than reference unit (Scythe).
fTarget = aCONSTANT --//maximum value is aCONSTANT
fTargetSlope = 1 --//slope is negative or positive
if targetCoordinate[1]~=-1 then --if target coordinate contain -1 then disable target for pure avoidance
targetAngle = GetTargetAngleWithRespectToUnit(unitID, targetCoordinate) --get target angle
fTarget = GetFtarget (aCONSTANT, targetAngle, unitDirection)
fTargetSlope = GetFtargetSlope (aCONSTANT, targetAngle, unitDirection, fTarget)
--local targetSubtendedAngle = GetTargetSubtendedAngle(unitID, targetCoordinate) --get target 'size' as viewed by the unit
end
local sumAllUnitOutput = {
wTotal = nil,
dSum = nil,
fObstacleSum = nil,
dFobstacle = nil,
nearestFrontObstacleRange = nil,
normalizingFactor = nil,
}
--count every enemy unit and sum its contribution to the obstacle/repulsor variable
sumAllUnitOutput=SumAllUnitAroundUnitID (obsCONSTANT,unitDirection,losRadius,surroundingUnits,unitsSeparation,impatienceTrigger,graphCONSTANTtrigger,unitInMotionSingleUnit,skippingTimer)
--calculate appropriate behaviour based on the constant and above summation value
local wTarget, wObstacle = CheckWhichFixedPointIsStable (fTargetSlope, fTarget, fixedPointCONSTANTtrigger,sumAllUnitOutput)
--convert an angular command into a coordinate command
local newX, newZ= ToCoordinate(wTarget, wObstacle, fTarget, unitDirection, losRadius, impatienceTrigger, skippingTimer, wasMoving, newCommand,sumAllUnitOutput, unitInMotionSingleUnit)
if (turnOnEcho == 1) then
Spring.Echo("unitID(AvoidanceCalculator)" .. unitID)
Spring.Echo("targetAngle(AvoidanceCalculator) " .. targetAngle)
Spring.Echo("unitDirection(AvoidanceCalculator) " .. unitDirection)
Spring.Echo("fTarget(AvoidanceCalculator) " .. fTarget)
Spring.Echo("fTargetSlope(AvoidanceCalculator) " .. fTargetSlope)
--Spring.Echo("targetSubtendedAngle(AvoidanceCalculator) " .. targetSubtendedAngle)
Spring.Echo("wTotal(AvoidanceCalculator) " .. wTotal)
Spring.Echo("dSum(AvoidanceCalculator) " .. dSum)
Spring.Echo("fObstacleSum(AvoidanceCalculator) " .. fObstacleSum)
Spring.Echo("dFobstacle(AvoidanceCalculator) " .. dFobstacle)
Spring.Echo("nearestFrontObstacleRange(AvoidanceCalculator) " .. nearestFrontObstacleRange)
Spring.Echo("wTarget(AvoidanceCalculator) " .. wTarget)
Spring.Echo("wObstacle(AvoidanceCalculator) " .. wObstacle)
Spring.Echo("newX(AvoidanceCalculator) " .. newX)
Spring.Echo("newZ(AvoidanceCalculator) " .. newZ)
end
return newX, newZ --return move coordinate
end
end
-- maintain the visibility of original command
-- reference: "unit_tactical_ai.lua" -ZeroK gadget by Google Frog
function InsertCommandQueue(unitID,cQueue,cQueueGKPed,newCommand,persistentData)
------- localize global constant:
local consRetreatTimeout = consRetreatTimeoutG
local commandTimeout = commandTimeoutG
------- end global constant
local now = persistentData["now"]
local commandTTL = persistentData["commandTTL"]
local commandIndexTable = persistentData["commandIndexTable"]
local orderArray={nil,nil,nil,nil,nil,nil}
local queueIndex=1
local avoidanceCommand = true
if not newCommand then --if widget's command then delete it
if not cQueue or not cQueue[1] then --happen when unit has NIL command (this), and somehow is same as widget's command (see: IdentifyTargetOnCommandQueue), and somehow unit currently has mono-command (see: CheckUserOverride)
if turnOnEcho==2 then
Spring.Echo("UnitIsDead (InsertCommandQueue):")
Spring.Echo(Spring.GetUnitIsDead(unitID))
Spring.Echo("ValidUnitID (InsertCommandQueue):")
Spring.Echo(Spring.ValidUnitID(unitID))
Spring.Echo("WidgetX (InsertCommandQueue):")
Spring.Echo(commandIndexTable[unitID]["widgetX"])
Spring.Echo("WidgetZ (InsertCommandQueue):")
Spring.Echo(commandIndexTable[unitID]["widgetZ"])
end
else
orderArray[1] = {CMD_REMOVE, {cQueue[1].tag}, {}} --spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[1].tag}, {} ) --delete previous widget command
local lastIndx = commandTTL[unitID][1] --commandTTL[unitID]'s table lenght
commandTTL[unitID][lastIndx] = nil --//delete the last watchdog entry (the "not newCommand" means that previous widget's command haven't changed yet (nothing has interrupted this unit, same is with commandTTL), and so if command is to delete then it is good opportunity to also delete its timeout info at *commandTTL* too). Deleting this entry mean that this particular command will no longer be checked for timeout.
commandTTL[unitID][1] = lastIndx -1 --refresh table lenght
-- Technical note: emptying commandTTL[unitID][#commandTTL[unitID]] is not technically required (not emptying it only make commandTTL countdown longer, but a mistake in emptying a commandTTL could make unit more prone to stuck when fleeing to impassable coordinate.
queueIndex=2 --skip index 1 of stored command. Skip widget's command
end
end
if (#cQueue>=queueIndex+1) then --if is queue={reclaim, area reclaim,stop}, or: queue={move,reclaim, area reclaim,stop}, or: queue={area reclaim, stop}, or:queue={move, area reclaim, stop}.
if (cQueue[queueIndex].id==CMD_REPAIR or cQueue[queueIndex].id==CMD_RECLAIM or cQueue[queueIndex].id==CMD_RESURRECT) then --if first (1) queue is reclaim/ressurect/repair
if cQueue[queueIndex+1].id==CMD_RECLAIM or cQueue[queueIndex+1].id==CMD_RESURRECT then --if second (2) queue is also reclaim/ressurect
--if (not Spring.ValidFeatureID(cQueue[queueIndex+1].params[1]-Game.maxUnits) or (not Spring.ValidFeatureID(cQueue[queueIndex+1].params[1]))) and not Spring.ValidUnitID(cQueue[queueIndex+1].params[1]) then --if it was an area command
if (cQueue[queueIndex+1].params[4]~=nil) then --second (2) queue is area reclaim. area command should has no "nil" on params 1,2,3, & 4
orderArray[#orderArray+1] = {CMD_REMOVE, {cQueue[queueIndex].tag}, {}} -- spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[queueIndex].tag}, {} ) --delete latest reclaiming/ressurecting command (skip the target:wreck/units). Allow command reset
local coordinate = (FindSafeHavenForCons(unitID, now)) or (cQueue[queueIndex+1])
orderArray[#orderArray+1] = {CMD_INSERT, {0, CMD_RAW_MOVE, CMD_OPT_INTERNAL, coordinate.params[1], coordinate.params[2], coordinate.params[3]}, {"alt"}} --spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_RAW_MOVE, CMD_OPT_INTERNAL, coordinate.params[1], coordinate.params[2], coordinate.params[3]}, {"alt"} ) --divert unit to the center of reclaim/repair command OR to any heavy concentration of ally (haven)
local lastIndx = commandTTL[unitID][1] --commandTTL[unitID]'s table lenght
commandTTL[unitID][lastIndx +1] = {countDown = consRetreatTimeout, widgetCommand= {coordinate.params[1], coordinate.params[3]}} --//remember this command on watchdog's commandTTL table. It has 15x*RefreshUnitUpdateRate* to expire
commandTTL[unitID][1] = lastIndx +1--refresh table lenght
avoidanceCommand = false
end
elseif cQueue[queueIndex+1].id==CMD_REPAIR then --if second (2) queue is also repair
--if (not Spring.ValidFeatureID(cQueue[queueIndex+1].params[1]-Game.maxUnits) or (not Spring.ValidFeatureID(cQueue[queueIndex+1].params[1]))) and not Spring.ValidUnitID(cQueue[queueIndex+1].params[1]) then --if it was an area command
if (cQueue[queueIndex+1].params[4]~=nil) then --area command should has no "nil" on params 1,2,3, & 4
orderArray[#orderArray+1] = {CMD_REMOVE, {cQueue[queueIndex].tag}, {}} --spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[queueIndex].tag}, {} ) --delete current repair command, (skip the target:units). Reset the repair command
end
elseif (cQueue[queueIndex].params[4]~=nil) then --if first (1) queue is area reclaim (an area reclaim without any wreckage to reclaim). area command should has no "nil" on params 1,2,3, & 4
local coordinate = (FindSafeHavenForCons(unitID, now)) or (cQueue[queueIndex])
orderArray[#orderArray+1] = {CMD_INSERT, {0, CMD_RAW_MOVE, CMD_OPT_INTERNAL, coordinate.params[1], coordinate.params[2], coordinate.params[3]}, {"alt"}} --spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_RAW_MOVE, CMD_OPT_INTERNAL, coordinate.params[1], coordinate.params[2], coordinate.params[3]}, {"alt"} ) --divert unit to the center of reclaim/repair command
local lastIndx = commandTTL[unitID][1] --commandTTL[unitID]'s table lenght
commandTTL[unitID][lastIndx+1] = {countDown = commandTimeout, widgetCommand= {coordinate.params[1], coordinate.params[3]}} --//remember this command on watchdog's commandTTL table. It has 2x*RefreshUnitUpdateRate* to expire
commandTTL[unitID][1] = lastIndx +1--refresh table lenght
avoidanceCommand = false
end
end
end
if (turnOnEcho == 1) then
Spring.Echo("unitID(InsertCommandQueue)" .. unitID)
Spring.Echo("newCommand(InsertCommandQueue):")
Spring.Echo(newCommand)
Spring.Echo("cQueue[1].params[1](InsertCommandQueue):" .. cQueue[1].params[1])
Spring.Echo("cQueue[1].params[3](InsertCommandQueue):" .. cQueue[1].params[3])
if cQueue[2]~=nil then
Spring.Echo("cQueue[2].params[1](InsertCommandQueue):")
Spring.Echo(cQueue[2].params[1])
Spring.Echo("cQueue[2].params[3](InsertCommandQueue):")
Spring.Echo(cQueue[2].params[3])
end
end
persistentData["commandTTL"] = commandTTL ----return updated memory tables used to check for command's expiration age.
return avoidanceCommand, orderArray --return whether new command is to be issued
end
---------------------------------Level2
---------------------------------Level3 (low-level function)
--check if unit is vulnerable/reloading
function CheckIfUnitIsReloading(unitInMotionSingleUnitTable)
---Global Constant---
local criticalShieldLevel =criticalShieldLevelG
local minimumRemainingReloadTime =minimumRemainingReloadTimeG
local secondPerGameFrame =secondPerGameFrameG
------
--local unitType = unitInMotionSingleUnitTable["unitType"] --retrieve stored unittype
local shieldIsCritical =false
local weaponIsEmpty = false
local fastestWeapon = unitInMotionSingleUnitTable["weaponInfo"]
--if unitType ==2 or unitType == 1 then
local unitID = unitInMotionSingleUnitTable["unitID"] --retrieve stored unitID
local unitShieldPower = fastestWeapon["unitShieldPower"] --retrieve registered full shield power
if unitShieldPower ~= -1 then
local _, currentPower = spGetUnitShieldState(unitID)
if currentPower~=nil then
if currentPower/unitShieldPower <criticalShieldLevel then
shieldIsCritical = true
end
end
end
local unitFastestReloadableWeapon = fastestWeapon["reloadableWeaponIndex"] --retrieve the quickest reloadable weapon index
local fastestReloadTime = fastestWeapon["reloadTime"] --in second
if unitFastestReloadableWeapon ~= -1 then
-- local unitSpeed = unitInMotionSingleUnitTable["unitSpeed"]
-- local distancePerSecond = unitSpeed
-- local fastUnit_shortRange = unitSpeed > fastestWeapon["range"] --check if unit can exit range easily if *this widget* evasion is activated
-- local unitValidForReloadEvasion = true
-- if fastUnit_shortRange then
-- unitValidForReloadEvasion = fastestReloadTime > 2.5 --check if unit will have enough time to return from *this widget* evasion
-- end
-- if unitValidForReloadEvasion then
local weaponReloadFrame = spGetUnitWeaponState(unitID, unitFastestReloadableWeapon, "reloadFrame") --Somehow the weapon table actually start at "0", so minus 1 from actual value
local currentFrame, _ = spGetGameFrame()
local remainingTime = (weaponReloadFrame - currentFrame)*secondPerGameFrame --convert to second
-- weaponIsEmpty = (remainingTime > math.max(minimumRemainingReloadTime,fastestReloadTime*0.25))
weaponIsEmpty = (remainingTime > minimumRemainingReloadTime)
if (turnOnEcho == 1) then --debugging
Spring.Echo(unitFastestReloadableWeapon)
Spring.Echo(fastestWeapon["range"])
end
-- end
end
--end
return (weaponIsEmpty or shieldIsCritical)
end
-- debugging method, used to quickly remove nil
function dNil(x)
if x==nil then
x=-1
end
return x
end
function ExtractTarget (queueIndex, cQueue,unitInMotionSingleUnit) --//used by IdentifyTargetOnCommandQueue()
local unitID = unitInMotionSingleUnit["unitID"]
local targetCoordinate = {nil,nil,nil}
local fixedPointCONSTANTtrigger = unitInMotionSingleUnit["fixedPointType"]
local unitVisible = (unitInMotionSingleUnit["isVisible"]== "yes")
local weaponRange = unitInMotionSingleUnit["weaponInfo"]["range"]
local weaponType = unitInMotionSingleUnit["weaponType"]
local boxSizeTrigger=0 --an arbitrary constant/variable, which trigger some other action/choice way way downstream. The purpose is to control when avoidance must be cut-off using custom value (ie: 1,2,3,4) for specific cases.
local graphCONSTANTtrigger = {}
local case=""
local targetID=nil
------------------------------------------------
if (cQueue[queueIndex].id==CMD_RAW_MOVE or cQueue[queueIndex].id<0) then --move or building stuff
local targetPosX, targetPosY, targetPosZ = -1, -1, -1 -- (-1) is default value because -1 represent "no target"
if cQueue[queueIndex].params[1]~= nil and cQueue[queueIndex].params[2]~=nil and cQueue[queueIndex].params[3]~=nil then --confirm that the coordinate exist
targetPosX, targetPosY, targetPosZ = cQueue[queueIndex].params[1], cQueue[queueIndex].params[2],cQueue[queueIndex].params[3]
-- elseif cQueue[queueIndex].params[1]~= nil then --check whether its refering to a nanoframe
-- local nanoframeID = cQueue[queueIndex].params[1]
-- targetPosX, targetPosY, targetPosZ = spGetUnitPosition(nanoframeID)
-- if (turnOnEcho == 2)then Spring.Echo("ExtractTarget, MoveCommand: is using nanoframeID") end
else
if (turnOnEcho == 2)then
local defID = spGetUnitDefID(unitID)
local ud = UnitDefs[defID or -1]
if ud then
Spring.Echo("Dynamic Avoidance move/build target is nil: fallback to no target " .. ud.humanName)--certain command has negative id but nil parameters. This is unknown command. ie: -32
else
Spring.Echo("Dynamic Avoidance move/build target is nil: fallback to no target")
end
end
end
boxSizeTrigger=1 --//avoidance deactivation 'halfboxsize' for MOVE command
graphCONSTANTtrigger[1] = 1 --use standard angle scale (take ~10 cycle to do 180 flip, but more predictable)
graphCONSTANTtrigger[2] = 1
if #cQueue >= queueIndex+1 then --this make unit retreating (that don't have safe haven coordinate) after reclaiming/ressurecting to have no target (and thus will retreat toward random position).
if cQueue[queueIndex+1].id==CMD_RECLAIM or cQueue[queueIndex+1].id==CMD_RESURRECT then --//reclaim command has 2 stage: 1 is move back to base, 2 is going reclaim. If detected reclaim or ressurect at 2nd queue then identify as area reclaim
if (cQueue[queueIndex].params[1]==cQueue[queueIndex+1].params[1]
and cQueue[queueIndex].params[2]==cQueue[queueIndex+1].params[2] --if retreat position equal to area reclaim/resurrect center (only happen if no safe haven coordinate detected)
and cQueue[queueIndex].params[3]==cQueue[queueIndex+1].params[3]) or
(cQueue[queueIndex].params[1]==cQueue[queueIndex+1].params[2]
and cQueue[queueIndex].params[2]==cQueue[queueIndex+1].params[3] --this 2nd condition happen when there is wreck to reclaim and the first params is the featureID.
and cQueue[queueIndex].params[3]==cQueue[queueIndex+1].params[4])
then --area reclaim will have no "nil", and will equal to retreat coordinate when retreating to center of area reclaim.
targetPosX, targetPosY, targetPosZ = -1, -1, -1 --//if area reclaim under the above condition, then avoid forever in presence of enemy, ELSE if no enemy (no avoidance): it reach retreat point and resume reclaiming
boxSizeTrigger=1 --//avoidance deactivation 'halfboxsize' for MOVE command
end
end
end
targetCoordinate={targetPosX, targetPosY, targetPosZ } --send away the target for move command
case = 'movebuild'
elseif cQueue[queueIndex].id==CMD_RECLAIM or cQueue[queueIndex].id==CMD_RESURRECT then --reclaim or ressurect
-- local a = Spring.GetUnitCmdDescs(unitID, Spring.FindUnitCmdDesc(unitID, 90), Spring.FindUnitCmdDesc(unitID, 90))
-- Spring.Echo(a[queueIndex]["name"])
local wreckPosX, wreckPosY, wreckPosZ = -1, -1, -1 -- -1 is default value because -1 represent "no target"
local areaMode = false
local foundMatch = false
--Method 1: set target to individual wreckage, else (if failed) revert to center of current area-command or to no target.
-- [[
local posX, posY, posZ = GetUnitOrFeaturePosition(cQueue[queueIndex].params[1])
if posX then
foundMatch=true
wreckPosX, wreckPosY, wreckPosZ = posX, posY, posZ
targetID = cQueue[queueIndex].params[1]
end
if foundMatch then --next: check if this is actually an area reclaim/ressurect
if cQueue[queueIndex].params[4] ~= nil then --area reclaim should has no "nil" on params 1,2,3, & 4 and in this case params 1 contain featureID/unitID because its the 2nd part of the area-reclaim command that reclaim wreck/target
areaMode = true
wreckPosX, wreckPosY,wreckPosZ = cQueue[queueIndex].params[2], cQueue[queueIndex].params[3],cQueue[queueIndex].params[4]
end
elseif cQueue[queueIndex].params[4] ~= nil then --1st part of the area-reclaim command (an empty area-command)
areaMode = true
wreckPosX, wreckPosY,wreckPosZ = cQueue[queueIndex].params[1], cQueue[queueIndex].params[2],cQueue[queueIndex].params[3]
else --have no unit match but have no area coordinate either, but is RECLAIM command, something must be wrong:
if (turnOnEcho == 2)then Spring.Echo("Dynamic Avoidance reclaim targetting failure: fallback to no target") end
end
--]]
targetCoordinate={wreckPosX, wreckPosY,wreckPosZ} --use wreck/center-of-area-command as target
--graphCONSTANTtrigger[1] = 2 --use bigger angle scale for initial avoidance: after that is a MOVE command to the center or area-command which uses standard angle scale (take ~4 cycle to do 180 flip, but more chaotic)
--graphCONSTANTtrigger[2] = 2
graphCONSTANTtrigger[1] = 1 --use standard angle scale (take ~10 cycle to do 180 flip, but more predictable)
graphCONSTANTtrigger[2] = 1
boxSizeTrigger=2 --use deactivation 'halfboxsize' for RECLAIM/RESURRECT command
if not areaMode then --signature for discrete RECLAIM/RESURRECT command.
boxSizeTrigger = 1 --change to deactivation 'halfboxsize' similar to MOVE command if user queued a discrete reclaim/ressurect command
--graphCONSTANTtrigger[1] = 1 --override: use standard angle scale (take ~10 cycle to do 180 flip, but more predictable)
--graphCONSTANTtrigger[2] = 1
end
case = 'reclaimressurect'
elseif cQueue[queueIndex].id==CMD_REPAIR then --repair command
local unitPosX, unitPosY, unitPosZ = -1, -1, -1 -- (-1) is default value because -1 represent "no target"
local targetUnitID=cQueue[queueIndex].params[1]
if spValidUnitID(targetUnitID) then --if has unit ID
unitPosX, unitPosY, unitPosZ = spGetUnitPosition(targetUnitID)
targetID = targetUnitID
elseif cQueue[queueIndex].params[1]~= nil and cQueue[queueIndex].params[2]~=nil and cQueue[queueIndex].params[3]~=nil then --if no unit then use coordinate
unitPosX, unitPosY,unitPosZ = cQueue[queueIndex].params[1], cQueue[queueIndex].params[2],cQueue[queueIndex].params[3]
else
if (turnOnEcho == 2)then Spring.Echo("Dynamic Avoidance repair targetting failure: fallback to no target") end
end
targetCoordinate={unitPosX, unitPosY,unitPosZ} --use ally unit as target
boxSizeTrigger=3 --change to deactivation 'halfboxsize' similar to REPAIR command
graphCONSTANTtrigger[1] = 1
graphCONSTANTtrigger[2] = 1
case = 'repair'
elseif (cQueue[1].id == cMD_DummyG) or (cQueue[1].id == cMD_Dummy_atkG) then
targetCoordinate = {-1, -1,-1} --no target (only avoidance)
boxSizeTrigger = nil --//value not needed; because 'halfboxsize' for a "-1" target always return "not reached" (infinite avoidance), calculation is skipped (no nil error)
graphCONSTANTtrigger[1] = 1 --//this value doesn't matter because 'cMD_DummyG' don't use attractor (-1 disabled the attractor calculation, and 'fixedPointCONSTANTtrigger' behaviour ignore attractor). Needed because "fTarget" is tied to this variable in "AvoidanceCalculator()".
graphCONSTANTtrigger[2] = 1
fixedPointCONSTANTtrigger = 3 --//use behaviour that promote avoidance/ignore attractor
case = 'cmddummys'
elseif cQueue[queueIndex].id == CMD_GUARD then
local unitPosX, unitPosY, unitPosZ = -1, -1, -1 -- (-1) is default value because -1 represent "no target"
local targetUnitID = cQueue[queueIndex].params[1]
if spValidUnitID(targetUnitID) then --if valid unit ID, not fake (if fake then will use "no target" for pure avoidance)
local unitDirection = 0
unitDirection, unitPosY,_ = GetUnitDirection(targetUnitID) --get target's direction in radian
unitPosX, unitPosZ = ConvertToXZ(targetUnitID, unitDirection, 200) --project a target at 200m in front of guarded unit
targetID = targetUnitID
else
if (turnOnEcho == 2)then Spring.Echo("Dynamic Avoidance guard targetting failure: fallback to no target") end
end
targetCoordinate={unitPosX, unitPosY,unitPosZ} --use ally unit as target
boxSizeTrigger = 4 --//deactivation 'halfboxsize' for GUARD command
graphCONSTANTtrigger[1] = 2 --//use more aggressive attraction because it GUARD units. It need big result.
graphCONSTANTtrigger[2] = 1 --//(if 1) use less aggressive avoidance because need to stay close to units. It need not stray.
case = 'guard'
elseif cQueue[queueIndex].id == CMD_ATTACK then
local targetPosX, targetPosY, targetPosZ = -1, -1, -1 -- (-1) is default value because -1 represent "no target"
boxSizeTrigger = nil --//value not needed when target is "-1" which always return "not reached" (a case where boxSizeTrigger is not used)
graphCONSTANTtrigger[1] = 1 --//this value doesn't matter because 'CMD_ATTACK' don't use attractor (-1 already disabled the attractor calculation, and 'fixedPointCONSTANTtrigger' ignore attractor). Needed because "fTarget" is tied to this variable in "AvoidanceCalculator()".
graphCONSTANTtrigger[2] = 2 --//use more aggressive avoidance because it often run just once or twice. It need big result.
fixedPointCONSTANTtrigger = 3 --//use behaviour that promote avoidance/ignore attractor (incase -1 is not enough)
if unitVisible and weaponType~=2 then --not arty
local enemyID = cQueue[queueIndex].params[1]
local x,y,z = spGetUnitPosition(enemyID)
if x then
targetPosX, targetPosY, targetPosZ = x,y,z --set target to enemy
targetID = enemyID
-- if weaponType==0 then --melee unit set bigger targetReached box.
-- boxSizeTrigger = 1 --if user initiate an attack while avoidance is necessary (eg: while reloading), then set deactivation 'halfboxsize' for MOVE command (ie: 400m range)
-- elseif weaponType==1 then
boxSizeTrigger = 2 --set deactivation 'halfboxsize' for RECLAIM/RESURRECT command (ie: 0m range/ always flee)
-- end
fixedPointCONSTANTtrigger = 1 --//use general behaviour that balance between target & avoidance
end
end
targetCoordinate={targetPosX, targetPosY, targetPosZ} --set target to enemy unit or none
case = 'attack'
else --if queue has no match/ is empty: then use no-target. eg: A case where undefined command is allowed into the system, or when engine delete the next queues of a valid command and widget expect it to still be there.
targetCoordinate={-1, -1, -1}
--if for some reason command queue[2] is already empty then use these backup value as target:
boxSizeTrigger = nil --//value not needed when target is "-1" which always return "not reached" (a case where boxSizeTrigger is not used)
graphCONSTANTtrigger[1] = 1 --//needed because "fTarget" is tied to this variable in "AvoidanceCalculator()". This value doesn't matter because -1 already skip attractor calculation & 'fixedPointCONSTANTtrigger' already ignore attractor values.
graphCONSTANTtrigger[2] = 1
fixedPointCONSTANTtrigger = 3
case = 'none'
end
local output = {
targetCoordinate = targetCoordinate,
boxSizeTrigger = boxSizeTrigger,
graphCONSTANTtrigger = graphCONSTANTtrigger,
fixedPointCONSTANTtrigger = fixedPointCONSTANTtrigger,
case = case,
targetID = targetID,
}
return output
end
function AddAttackerIDToEnemyList (unitID, losRadius, relevantUnit, arrayIndex, attacker)
if attacker[unitID].countDown > 0 then
local separation = spGetUnitSeparation (unitID,attacker[unitID].id, true)
if separation ~=nil then --if attackerID is still a valid id (ie: enemy did not disappear) then:
if separation> losRadius then --only include attacker that is outside LosRadius because anything inside LosRadius is automatically included later anyway
arrayIndex=arrayIndex+1
relevantUnit[arrayIndex]= attacker[unitID].id --//add attacker as a threat
end
end
end
return relevantUnit, arrayIndex
end
function GetUnitRelativeAngle (unitIDmain,unitID2,unitIDmainX,unitIDmainZ,unitID2X,unitID2Z)
local x,z = unitIDmainX,unitIDmainZ
local rX, rZ=unitID2X,unitID2Z --use inputted position
if not x then --empty?
x,_,z = spGetUnitPosition(unitIDmain) --use standard position
end
if not rX then
rX, _, rZ= spGetUnitPosition(unitID2)
end
local cX, _, cZ = rX-x, _, rZ-z
local cXcZ = math.sqrt(cX*cX + cZ*cZ) --hypothenus for xz direction
local relativeAngle = math.atan2 (cX/cXcZ, cZ/cXcZ) --math.atan2 accept trigonometric ratio (ie: ratio that has same value as: cos(angle) & sin(angle). Cos is ratio between x and hypothenus, and Sin is ratio between z and hypothenus)
return relativeAngle
end
function GetTargetAngleWithRespectToUnit(unitID, targetCoordinate)
local x,_,z = spGetUnitPosition(unitID)
local tx, tz = targetCoordinate[1], targetCoordinate[3]
local dX, dZ = tx- x, tz-z
local dXdZ = math.sqrt(dX*dX + dZ*dZ) --hypothenus for xz direction
local targetAngle = math.atan2(dX/dXdZ, dZ/dXdZ) --math.atan2 accept trigonometric ratio (ie: ratio that has same value as: cos(angle) & sin(angle))
return targetAngle
end
--attractor's sinusoidal wave function (target's sine wave function)
function GetFtarget (aCONSTANT, targetAngle, unitDirection)
local fTarget = -1*aCONSTANT*math.sin(unitDirection - targetAngle)
return fTarget
end
--attractor's graph slope at unit's direction
function GetFtargetSlope (aCONSTANT, targetAngle, unitDirection, fTarget)
local unitDirectionPlus1 = unitDirection+0.05
local fTargetPlus1 = -1*aCONSTANT*math.sin(unitDirectionPlus1 - targetAngle)
local fTargetSlope=(fTargetPlus1-fTarget) / (unitDirectionPlus1 -unitDirection)
return fTargetSlope
end
--target angular size
function GetTargetSubtendedAngle(unitID, targetCoordinate)
local tx,tz = targetCoordinate[1],targetCoordinate[3]
local x,_,z = spGetUnitPosition(unitID)
local unitDefID= spGetUnitDefID(unitID)
local unitDef= UnitDefs[unitDefID]
local unitSize =32--arbitrary value, size of a com
if(unitDef~=nil) then unitSize = unitDef.xsize*8 end --8 is the actual Distance per square, times the unit's square
local targetDistance= Distance(tx,tz,x,z)
local targetSubtendedAngle = math.atan(unitSize*2/targetDistance) --target is same size as unit's. Usually target do not has size at all, because they are simply move command on ground
return targetSubtendedAngle
end
--sum the contribution from all enemy unit
function SumAllUnitAroundUnitID (obsCONSTANT,unitDirection,losRadius,surroundingUnits,unitsSeparation,impatienceTrigger,graphCONSTANTtrigger,unitInMotionSingleUnit,skippingTimer)
local thisUnitID = unitInMotionSingleUnit["unitID"]
local safetyMarginCONSTANT = safetyMarginCONSTANTunitG -- make the slopes in the extremeties of obstacle graph more sloppy (refer to "non-Linear Dynamic system approach to modelling behavior" -SiomeGoldenstein, Edward Large, DimitrisMetaxas)
local smCONSTANT = smCONSTANTunitG --?
local distanceCONSTANT = distanceCONSTANTunitG
local useLOS_distanceCONSTANT = useLOS_distanceCONSTANTunit_G
local normalizeObsGraph = normalizeObsGraphG
local cmd_then_DoCalculation_delay = cmd_then_DoCalculation_delayG
----
local wTotal=0
local fObstacleSum=0
local dFobstacle=0
local dSum=0
local nearestFrontObstacleRange =999
local normalizingFactor = 1
if (turnOnEcho == 1) then Spring.Echo("unitID(SumAllUnitAroundUnitID)" .. thisUnitID) end
if (surroundingUnits["count"] and surroundingUnits["count"]>0) then --don't execute if no enemy unit exist
local graphSample={}
if normalizeObsGraph then --an option (default OFF) allow the obstacle graph to be normalized for experimenting purposes
for i=1, 180+1, 1 do
graphSample[i]=0 --initialize content 360 points
end
end
local thisXvel,_,thisZvel = spGetUnitVelocity(thisUnitID)
local thisX,_,thisZ = spGetUnitPosition(thisUnitID)
local delay_1 = skippingTimer.averageDelay/2
local delay_2 = cmd_then_DoCalculation_delay
local thisXvel_delay2,thisZvel_delay2 = GetDistancePerDelay(thisXvel,thisZvel, delay_2)
local thisXvel_delay1,thisZvel_delay1 = GetDistancePerDelay(thisXvel,thisZvel,delay_1) --convert per-frame velocity into per-second velocity, then into elmo-per-averageNetworkDelay
for i=1,surroundingUnits["count"], 1 do
local unitRectangleID=surroundingUnits[i]
if (unitRectangleID ~= nil)then --excluded any nil entry
local recX_delay1,recZ_delay1,unitSeparation_1,_,_,unitSeparation_2 = GetTargetPositionAfterDelay(unitRectangleID, delay_1,delay_2,thisXvel_delay1,thisZvel_delay1,thisXvel_delay2,thisZvel_delay2,thisX,thisZ)
if unitsSeparation[unitRectangleID]==nil then unitsSeparation[unitRectangleID]=9999 end --if enemy spontaneously appear then set the memorized separation distance to 9999; maybe previous polling missed it and to prevent nil
if (turnOnEcho == 1) then
Spring.Echo("unitSeparation <unitsSeparation[unitRectangleID](SumAllUnitAroundUnitID)")
Spring.Echo(unitSeparation <unitsSeparation[unitRectangleID])
end
if unitSeparation_2 - unitsSeparation[unitRectangleID] < 30 then --see if the enemy in collision front is maintaining distance/fleeing or is closing in
local relativeAngle = GetUnitRelativeAngle (thisUnitID, unitRectangleID,thisX,thisZ,recX_delay1,recZ_delay1) -- obstacle's angular position with respect to our coordinate
local subtendedAngle = GetUnitSubtendedAngle (thisUnitID, unitRectangleID, losRadius,unitSeparation_1) -- obstacle & our unit's angular size
distanceCONSTANT=distanceCONSTANTunitG --reset distance constant
if useLOS_distanceCONSTANT then
distanceCONSTANT= losRadius --use unit's LOS instead of constant so that longer range unit has bigger avoidance radius.
end
--get obstacle/ enemy/repulsor wave function
if impatienceTrigger==0 then --impatienceTrigger reach zero means that unit is impatient
distanceCONSTANT=distanceCONSTANT/2
end
local ri, wi, di,diff1 = GetRiWiDi (unitDirection, relativeAngle, subtendedAngle, unitSeparation_1, safetyMarginCONSTANT, smCONSTANT, distanceCONSTANT,obsCONSTANT)
local fObstacle = ri*wi*di
--get second obstacle/enemy/repulsor wave function to calculate slope
local ri2, wi2, di2, diff2= GetRiWiDi (unitDirection, relativeAngle, subtendedAngle, unitSeparation_1, safetyMarginCONSTANT, smCONSTANT, distanceCONSTANT, obsCONSTANT, true)
local fObstacle2 = ri2*wi2*di2
--create a snapshot of the entire graph. Resolution: 360 datapoint
local dI = math.exp(-1*unitSeparation_1/distanceCONSTANT) --distance multiplier
local hI = windowingFuncMultG/ (math.cos(2*subtendedAngle) - math.cos(2*subtendedAngle+ safetyMarginCONSTANT))
if normalizeObsGraph then
for i=-90, 90, 1 do --sample the entire 360 degree graph
local differenceInAngle = (unitDirection-relativeAngle)+i*math.pi/180
local rI = (differenceInAngle/ subtendedAngle)*math.exp(1- math.abs(differenceInAngle/subtendedAngle))
local wI = obsCONSTANT* (math.tanh(hI- (math.cos(differenceInAngle) -math.cos(2*subtendedAngle +smCONSTANT)))+1) --graph with limiting window
graphSample[i+90+1]=graphSample[i+90+1]+ (rI*wI*dI)
--[[ <<--can uncomment this and comment the 2 "normalizeObsGraph" switch above for debug info
Spring.Echo((rI*wI*dI) .. " (rI*wI*dI) (SumAllUnitAroundUnitID)")
if i==0 then
Spring.Echo("CENTER")
end
--]]
end
end
--get repulsor wavefunction's slope
local fObstacleSlope = GetFObstacleSlope(fObstacle2, fObstacle, diff2, diff1)
--sum all repulsor's wavefunction from every enemy/obstacle within this loop
wTotal, dSum, fObstacleSum,dFobstacle, nearestFrontObstacleRange= DoAllSummation (wi, fObstacle, fObstacleSlope, di,wTotal, unitDirection, unitSeparation_1, relativeAngle, dSum, fObstacleSum,dFobstacle, nearestFrontObstacleRange)
end
end
end
if normalizeObsGraph then
local biggestValue=0
for i=1, 180+1, 1 do --find maximum value from graph
if biggestValue<graphSample[i] then
biggestValue = graphSample[i]
end
end
if biggestValue > obsCONSTANT then
normalizingFactor = obsCONSTANT/biggestValue --normalize graph value to a determined maximum
else
normalizingFactor = 1 --don't change the graph if the graph never exceed maximum value
end
end
end
local output = {
wTotal = wTotal,
dSum = dSum,
fObstacleSum = fObstacleSum,
dFobstacle = dFobstacle,
nearestFrontObstacleRange = nearestFrontObstacleRange,
normalizingFactor = normalizingFactor,
}
return output --return obstacle's calculation result
end
--determine appropriate behaviour
function CheckWhichFixedPointIsStable (fTargetSlope, fTarget, fixedPointCONSTANTtrigger,sumAllUnitOutput)
local dFobstacle = sumAllUnitOutput["dFobstacle"]
local dSum = sumAllUnitOutput["dSum"]
local wTotal = sumAllUnitOutput["wTotal"]
local fObstacleSum = sumAllUnitOutput["fObstacleSum"]
--local alphaCONSTANT1, alphaCONSTANT2, gammaCONSTANT1and2, gammaCONSTANT2and1 = ConstantInitialize(fTargetSlope, dFobstacle, dSum, fTarget, fObstacleSum, wTotal, fixedPointCONSTANTtrigger)
local cCONSTANT1 = cCONSTANT1g
local cCONSTANT2 = cCONSTANT2g
local gammaCONSTANT1and2
local gammaCONSTANT2and1 = gammaCONSTANT2and1g
local alphaCONSTANT1 = alphaCONSTANT1g
local alphaCONSTANT2 --always between 1 and 0
--------
cCONSTANT1 = cCONSTANT1[fixedPointCONSTANTtrigger]
cCONSTANT2 = cCONSTANT2[fixedPointCONSTANTtrigger]
gammaCONSTANT2and1 = gammaCONSTANT2and1[fixedPointCONSTANTtrigger]
alphaCONSTANT1 = alphaCONSTANT1[fixedPointCONSTANTtrigger]
--calculate "gammaCONSTANT1and2, alphaCONSTANT2, and alphaCONSTANT1"
local pTarget= Sgn(fTargetSlope)*math.exp(cCONSTANT1*math.abs(fTarget))
local pObstacle = Sgn(dFobstacle)*math.exp(cCONSTANT1*math.abs(fObstacleSum))*wTotal
gammaCONSTANT1and2 = math.exp(-1*cCONSTANT2*pTarget*pObstacle)/math.exp(cCONSTANT2)
alphaCONSTANT2 = math.tanh(dSum)
alphaCONSTANT1 = alphaCONSTANT1*(1-alphaCONSTANT2)
--
local wTarget=0
local wObstacle=1
if (turnOnEcho == 1) then
Spring.Echo("fixedPointCONSTANTtrigger(CheckWhichFixedPointIsStable)" .. fixedPointCONSTANTtrigger)
Spring.Echo("alphaCONSTANT1(CheckWhichFixedPointIsStable)" .. alphaCONSTANT1)
Spring.Echo ("alphaCONSTANT2(CheckWhichFixedPointIsStable)" ..alphaCONSTANT2)
Spring.Echo ("gammaCONSTANT1and2(CheckWhichFixedPointIsStable)" ..gammaCONSTANT1and2)
Spring.Echo ("gammaCONSTANT2and1(CheckWhichFixedPointIsStable)" ..gammaCONSTANT2and1)
end
if (alphaCONSTANT1 < 0) and (alphaCONSTANT2 <0) then --state 0 is unstable, unit don't move
wTarget = 0
wObstacle =0
if (turnOnEcho == 1) then
Spring.Echo("state 0")
Spring.Echo ("(alphaCONSTANT1 < 0) and (alphaCONSTANT2 <0)")
end
end
if (gammaCONSTANT1and2 > alphaCONSTANT1) and (alphaCONSTANT2 >0) then --state 1: unit flee from obstacle and forget target
wTarget =0
wObstacle =-1
if (turnOnEcho == 1) then
Spring.Echo("state 1")
Spring.Echo ("(gammaCONSTANT1and2 > alphaCONSTANT1) and (alphaCONSTANT2 >0)")
end
end
if(gammaCONSTANT2and1 > alphaCONSTANT2) and (alphaCONSTANT1 >0) then --state 2: unit forget obstacle and go for the target
wTarget= -1
wObstacle =0
if (turnOnEcho == 1) then
Spring.Echo("state 2")
Spring.Echo ("(gammaCONSTANT2and1 > alphaCONSTANT2) and (alphaCONSTANT1 >0)")
end
end
if (alphaCONSTANT1>0) and (alphaCONSTANT2>0) then --state 3: mixed contribution from target and obstacle
if (alphaCONSTANT1> gammaCONSTANT1and2) and (alphaCONSTANT2>gammaCONSTANT2and1) then
if (gammaCONSTANT1and2*gammaCONSTANT2and1 < 0.0) then
--function from latest article. Set repulsor/attractor balance
wTarget= math.sqrt((alphaCONSTANT2*(alphaCONSTANT1-gammaCONSTANT1and2))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1))
wObstacle= math.sqrt((alphaCONSTANT1*(alphaCONSTANT2-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1))
-- wTarget= math.sqrt((alphaCONSTANT2*(alphaCONSTANT1-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1))
-- wObstacle= math.sqrt((alphaCONSTANT1*(alphaCONSTANT2-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1))
if (turnOnEcho == 1) then
Spring.Echo("state 3")
Spring.Echo ("(gammaCONSTANT1and2*gammaCONSTANT2and1 < 0.0)")
end
end
if (gammaCONSTANT1and2>0) and (gammaCONSTANT2and1>0) then
--function from latest article. Set repulsor/attractor balance
wTarget= math.sqrt((alphaCONSTANT2*(alphaCONSTANT1-gammaCONSTANT1and2))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1))
wObstacle= math.sqrt((alphaCONSTANT1*(alphaCONSTANT2-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1))
-- wTarget= math.sqrt((alphaCONSTANT2*(alphaCONSTANT1-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1))
-- wObstacle= math.sqrt((alphaCONSTANT1*(alphaCONSTANT2-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1))
wTarget= wTarget*-1
if (turnOnEcho == 1) then
Spring.Echo("state 4")
Spring.Echo ("(gammaCONSTANT1and2>0) and (gammaCONSTANT2and1>0)")
end
end
end
else
if (turnOnEcho == 1) then
Spring.Echo ("State not listed")
end
end
if (turnOnEcho == 1) then
Spring.Echo ("wTarget (CheckWhichFixedPointIsStable)" ..wTarget)
Spring.Echo ("wObstacle(CheckWhichFixedPointIsStable)" ..wObstacle)
end
return wTarget, wObstacle --return attractor's and repulsor's multiplier
end
--convert angular command into coordinate, plus other function
function ToCoordinate(wTarget, wObstacle, fTarget, unitDirection, losRadius, impatienceTrigger, skippingTimer, wasMoving, newCommand,sumAllUnitOutput, unitInMotionSingleUnit)
local safetyDistanceCONSTANT=safetyDistanceCONSTANT_fG
local timeToContactCONSTANT=timeToContactCONSTANTg
local activateAutoReverse=activateAutoReverseG
---------
local thisUnitID = unitInMotionSingleUnit["unitID"]
local unitSpeed = unitInMotionSingleUnit["unitSpeed"]
local nearestFrontObstacleRange = sumAllUnitOutput["nearestFrontObstacleRange"]
local fObstacleSum = sumAllUnitOutput["fObstacleSum"]
local normalizingFactor = sumAllUnitOutput["normalizingFactor"]
if (nearestFrontObstacleRange> losRadius) then nearestFrontObstacleRange = 999 end --if no obstacle infront of unit then set nearest obstacle as far as LOS to prevent infinite velocity.
local newUnitAngleDerived= GetNewAngle(unitDirection, wTarget, fTarget, wObstacle, fObstacleSum, normalizingFactor) --derive a new angle from calculation for move solution
local velocity=unitSpeed*(math.max(timeToContactCONSTANT, skippingTimer.averageDelay + timeToContactCONSTANT)) --scale-down/scale-up command lenght based on system delay (because short command will make unit move in jittery way & avoidance stop prematurely). *NOTE: select either preset velocity (timeToContactCONSTANT==cmd_then_DoCalculation_delayG) or the one taking account delay measurement (skippingTimer.networkDelay + cmd_then_DoCalculation_delay), which one is highest, times unitSpeed as defined by UnitDefs.
local networkDelayDrift = 0
if wasMoving then --unit drift contributed by network lag/2 (divide-by-2 because averageDelay is a roundtrip delay and we just want the delay of stuff measured on screen), only calculated when unit is known to be moving (eg: is using lastPosition to determine direction), but network lag value is not accurate enough to yield an accurate drift prediction.
networkDelayDrift = unitSpeed*(skippingTimer.averageDelay/2)
-- else --if initially stationary then add this backward motion (as 'hax' against unit move toward enemy because of avoidance due to firing/reloading weapon)
-- networkDelayDrift = -1*unitSpeed/2
end
local maximumVelocity = (nearestFrontObstacleRange- safetyDistanceCONSTANT)/timeToContactCONSTANT --calculate the velocity that will cause a collision within the next "timeToContactCONSTANT" second.
activateAutoReverse=activateAutoReverse*impatienceTrigger --activate/deactivate 'autoReverse' if impatience system is used
local doReverseNow = false
if (maximumVelocity <= velocity) and (activateAutoReverse==1) and (not newCommand) then
--velocity = -unitSpeed --set to reverse if impact is imminent & when autoReverse is active & when isn't a newCommand. NewCommand is TRUE if its on initial avoidance. We don't want auto-reverse on initial avoidance (we rely on normal avoidance first, then auto-reverse if it about to collide with enemy).
doReverseNow = true
end
if (turnOnEcho == 1) then
Spring.Echo("maximumVelocity(ToCoordinate)" .. maximumVelocity)
Spring.Echo("activateAutoReverse(ToCoordinate)" .. activateAutoReverse)
Spring.Echo("unitDirection(ToCoordinate)" .. unitDirection)
end
local newX, newZ= ConvertToXZ(thisUnitID, newUnitAngleDerived,velocity, unitDirection, networkDelayDrift,doReverseNow) --convert angle into coordinate form
return newX, newZ
end
function Round(num) --Reference: http://lua-users.org/wiki/SimpleRound
under = math.floor(num)
upper = math.floor(num) + 1
underV = -(under - num)
upperV = upper - num
if (upperV > underV) then
return under
else
return upper
end
end
local safeHavenLastUpdate = 0
local safeHavenCoordinates = {}
function FindSafeHavenForCons(unitID, now)
local myTeamID = myTeamID_gbl
----
if options.enableReturnToBase.value==false or WG.OPTICS_cluster == nil then --//if epicmenu option 'Return To Base' is false then return nil
return nil
end
--Spring.Echo((now - safeHavenLastUpdate))
if (now - safeHavenLastUpdate) > 4 then --//only update NO MORE than once every 4 second:
safeHavenCoordinates = {} --//reset old content
local allMyUnits = spGetTeamUnits(myTeamID)
local unorderedUnitList = {}
for i=1, #allMyUnits, 1 do --//convert unit list into a compatible format for the Clustering function below
local unitID_list = allMyUnits[i]
local x,y,z = spGetUnitPosition(unitID_list)
local unitDefID_list = spGetUnitDefID(unitID_list)
local unitDef = UnitDefs[unitDefID_list]
local unitSpeed =unitDef["speed"]
if (unitSpeed>0) then --//if moving units
if (unitDef.isBuilder or unitDef["canCloak"]) and not unitDef.customParams.commtype then --if cloakies and constructor, and not com (ZK)
--intentionally empty. Not include cloakies and builder.
elseif unitDef.customParams.commtype then --if COMMANDER,
unorderedUnitList[unitID_list] = {x,y,z} --//store
elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) then --if all ground unit, amphibious, and ships (except commander)
--unorderedUnitList[unitID_list] = {x,y,z} --//store
elseif (unitDef.hoverAttack== true) then --if gunships
--intentionally empty. Not include gunships.
end
else --if buildings
unorderedUnitList[unitID_list] = {x,y,z} --//store
end
end
local cluster, _ = WG.OPTICS_cluster(unorderedUnitList, 600,3, myTeamID,300) --//find clusters with atleast 3 unit per cluster and with at least within 300-meter from each other
for index=1 , #cluster do
local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0
for unitIndex=1, #cluster[index] do
local unitID_list = cluster[index][unitIndex]
local x,y,z= unorderedUnitList[unitID_list][1],unorderedUnitList[unitID_list][2],unorderedUnitList[unitID_list][3] --// get stored unit position
sumX= sumX+x
sumY = sumY+y
sumZ = sumZ+z
unitCount=unitCount+1
end
meanX = sumX/unitCount --//calculate center of cluster
meanY = sumY/unitCount
meanZ = sumZ/unitCount
safeHavenCoordinates[(#safeHavenCoordinates or 0)+1] = {meanX, meanY, meanZ} --//record cluster position
end
safeHavenLastUpdate = now
end --//end cluster detection
local currentSafeHaven = {params={}} --// initialize table using 'params' to be consistent with 'cQueue' content
local nearestSafeHaven = {params={}} --// initialize table using 'params' to be consistent with 'cQueue' content
local nearestSafeHavenDistance = 999999
nearestSafeHaven, currentSafeHaven = NearestSafeCoordinate (unitID, safeHavenCoordinates, nearestSafeHavenDistance, nearestSafeHaven, currentSafeHaven)
if nearestSafeHaven.params[1]~=nil then --//if nearest safe haven found then go there
return nearestSafeHaven
elseif currentSafeHaven.params[1]~=nil then --//elseif only current safe haven is available then go here
return currentSafeHaven
else --//elseif no safe haven detected then return nil
return nil
end
end
---------------------------------Level3
---------------------------------Level4 (lower than low-level function)
function GetUnitOrFeaturePosition(id) --copied from cmd_commandinsert.lua widget (by dizekat)
if id<=Game.maxUnits and spValidUnitID(id) then
return spGetUnitPosition(id)
elseif spValidFeatureID(id-Game.maxUnits) then
return spGetFeaturePosition(id-Game.maxUnits) --featureID is always offset by maxunit count
end
return nil
end
function GetUnitDirection(unitID) --give unit direction in radian, 2D
local dx, dz = 0,0
local isMoving = true
local _,currentY = spGetUnitPosition(unitID)
dx,_,dz= spGetUnitVelocity(unitID)
if (dx == 0 and dz == 0) then --use the reported vector if velocity failed to reveal any vector
dx,_,dz= spGetUnitDirection(unitID)
isMoving = false
end
local dxdz = math.sqrt(dx*dx + dz*dz) --hypothenus for xz direction
local unitDirection = math.atan2(dx/dxdz, dz/dxdz)
if (turnOnEcho == 1) then
Spring.Echo("direction(GetUnitDirection) " .. unitDirection*180/math.pi)
end
return unitDirection, currentY, isMoving
end
function ConvertToXZ(thisUnitID, newUnitAngleDerived, velocity, unitDirection, networkDelayDrift,doReverseNow)
--localize global constant
local velocityAddingCONSTANT=velocityAddingCONSTANTg
local velocityScalingCONSTANT=velocityScalingCONSTANTg
--
local x,_,z = spGetUnitPosition(thisUnitID)
local distanceToTravelInSecond=velocity*velocityScalingCONSTANT+velocityAddingCONSTANT*Sgn(velocity) --add multiplier & adder. note: we multiply "velocityAddingCONSTANT" with velocity Sign ("Sgn") because we might have reverse speed (due to auto-reverse)
local newX = 0
local newZ = 0
if doReverseNow then
local reverseDirection = unitDirection+math.pi --0 degree + 180 degree = reverse direction
newX = distanceToTravelInSecond*math.sin(reverseDirection) + x
newZ = distanceToTravelInSecond*math.cos(reverseDirection) + z
else
newX = distanceToTravelInSecond*math.sin(newUnitAngleDerived) + x -- issue a command on the ground to achieve a desired angular turn
newZ = distanceToTravelInSecond*math.cos(newUnitAngleDerived) + z
end
if (unitDirection ~= nil) and (networkDelayDrift~=0) then --need this check because argument #4 & #5 can be empty (for other usage). Also used in ExtractTarget for GUARD command.
local distanceTraveledDueToNetworkDelay = networkDelayDrift
newX = distanceTraveledDueToNetworkDelay*math.sin(unitDirection) + newX -- translate move command abit further forward; to account for lag. Network Lag makes move command lags behind the unit.
newZ = distanceTraveledDueToNetworkDelay*math.cos(unitDirection) + newZ
end
newX = math.min(newX,Game.mapSizeX)
newX = math.max(newX,0)
newZ = math.min(newZ,Game.mapSizeZ)
newZ = math.max(newZ,0)
if (turnOnEcho == 1) then
Spring.Echo("x(ConvertToXZ) " .. x)
Spring.Echo("z(ConvertToXZ) " .. z)
Spring.Echo("newX(ConvertToXZ) " .. newX)
Spring.Echo("newZ(ConvertToXZ) " .. newZ)
end
return newX, newZ
end
function GetTargetPositionAfterDelay(targetUnitID, delay1,delay2,thisXvel_delay1,thisZvel_delay1,thisXvel_delay2,thisZvel_delay2,thisX,thisZ)
local recXvel,_,recZvel = spGetUnitVelocity(targetUnitID)
local recX,_,recZ = spGetUnitPosition(targetUnitID)
recXvel = recXvel or 0
recZvel = recZvel or 0
local recXvel_delay2, recZvel_delay2 = GetDistancePerDelay(recXvel,recZvel, delay2)
recXvel_delay2 = recXvel_delay2 - thisXvel_delay2 --calculate relative elmo-per-delay
recZvel_delay2 = recZvel_delay2 - thisZvel_delay2
local recX_delay2 = recX + recXvel_delay2 --predict obstacle's offsetted position after a delay has passed
local recZ_delay2 = recZ + recZvel_delay2
local unitSeparation_2 = Distance(recX_delay2,recZ_delay2,thisX,thisZ)
local recXvel_delay1, recZvel_delay1 = GetDistancePerDelay(recXvel,recZvel,delay1)
recXvel_delay1 = recXvel_delay1 - thisXvel_delay1 --calculate relative elmo-per-averageNetworkDelay
recZvel_delay1 = recZvel_delay1 - thisZvel_delay1
local recX_delay1 = recX + recXvel_delay1 --predict obstacle's offsetted position after network delay has passed
local recZ_delay1 = recZ + recZvel_delay1
local unitSeparation_1 = Distance(recX_delay1,recZ_delay1,thisX,thisZ) --spGetUnitSeparation (thisUnitID, unitRectangleID, true) --get 2D distance
return recX_delay1,recZ_delay1,unitSeparation_1,recX_delay2,recZ_delay2,unitSeparation_2
end
--get enemy angular size with respect to unit's perspective
function GetUnitSubtendedAngle (unitIDmain, unitID2, losRadius,unitSeparation)
local unitSize2 =32 --a commander size for an unidentified enemy unit
local unitDefID2= spGetUnitDefID(unitID2)
local unitDef2= UnitDefs[unitDefID2]
if (unitDef2~=nil) then
unitSize2 = unitDef2.xsize*8 --8 unitDistance per each square times unitDef's square, a correct size for an identified unit
end
local unitDefID= spGetUnitDefID(unitIDmain)
local unitDef= UnitDefs[unitDefID]
local unitSize = unitDef.xsize*8 --8 is the actual Distance per square
if (not unitDef["canCloak"]) and (unitDef2~=nil) then --non-cloaky unit view enemy size as its weapon range (this to make it avoid getting into range)
unitSize2 = unitDef2.maxWeaponRange
end
if (unitDef["canCloak"]) then --cloaky unit use decloak distance as body size (to avoid getting too close)
unitSize = unitDef["decloakDistance"]
end
local separationDistance = unitSeparation
--if (unitID2~=nil) then separationDistance = spGetUnitSeparation (unitIDmain, unitID2, true) --actual separation distance
--else separationDistance = losRadius -- GetUnitLOSRadius(unitIDmain) --as far as unit's reported LOSradius
--end
local unit2SubtendedAngle = math.atan((unitSize + unitSize2)/separationDistance) --convert size and distance into radian (angle)
return unit2SubtendedAngle --return angular size
end
--calculate enemy's wavefunction
function GetRiWiDi (unitDirection, relativeAngle, subtendedAngle, separationDistance, safetyMarginCONSTANT, smCONSTANT, distanceCONSTANT, obsCONSTANT, isForSlope)
unitDirection = unitDirection + math.pi --temporarily add a half of a circle to remove the negative part which could skew with circle-arithmetic
relativeAngle = relativeAngle + math.pi
local differenceInAngle = relativeAngle - unitDirection --relative difference
if differenceInAngle > math.pi then --select difference that is smaller than half a circle
differenceInAngle = differenceInAngle - 2*math.pi
elseif differenceInAngle < -1*math.pi then
differenceInAngle = 2*math.pi + differenceInAngle
end
if isForSlope then
differenceInAngle = differenceInAngle + 0.05
end
--Spring.Echo("differenceInAngle(GetRiWiDi) ".. differenceInAngle*180/math.pi)
local rI = (differenceInAngle/ subtendedAngle)*math.exp(1- math.abs(differenceInAngle/subtendedAngle)) -- ratio of enemy-direction over the size-of-the-enemy
local hI = windowingFuncMultG/ (math.cos(2*subtendedAngle) - math.cos(2*subtendedAngle+ safetyMarginCONSTANT))
local wI = obsCONSTANT* (math.tanh(hI- (math.cos(differenceInAngle) -math.cos(2*subtendedAngle +smCONSTANT)))+1) --graph with limiting window. Tanh graph multiplied by obsCONSTANT
local dI = math.exp(-1*separationDistance/distanceCONSTANT) --distance multiplier
return rI, wI, dI, differenceInAngle
end
--calculate wavefunction's slope
function GetFObstacleSlope (fObstacle2, fObstacle, diff2, diff1)
--local fObstacleSlope= (fObstacle2 -fObstacle)/((unitDirection+0.05)-unitDirection)
local fObstacleSlope= (fObstacle2 -fObstacle)/(diff2-diff1)
return fObstacleSlope
end
--sum the wavefunction from all enemy units
function DoAllSummation (wi, fObstacle, fObstacleSlope, di,wTotal, unitDirection, unitSeparation, relativeAngle, dSum, fObstacleSum, dFobstacle, nearestFrontObstacleRange)
--sum all wavefunction variable, send and return summation variable
wTotal, dSum, fObstacleSum, dFobstacle=SumRiWiDiCalculation (wi, fObstacle, fObstacleSlope, di,wTotal, dSum, fObstacleSum, dFobstacle)
--detect any obstacle 60 degrees (pi/6) to the side of unit, set as nearest obstacle unit (prevent head on collision)
if (unitSeparation< nearestFrontObstacleRange) and math.abs(unitDirection- relativeAngle)< (fleeingAngleG) then
nearestFrontObstacleRange = unitSeparation end
return wTotal, dSum, fObstacleSum, dFobstacle, nearestFrontObstacleRange --return summation variable
end
--
function GetNewAngle (unitDirection, wTarget, fTarget, wObstacle, fObstacleSum, normalizingFactor)
fObstacleSum = fObstacleSum*normalizingFactor --downscale value depend on the entire graph's maximum (if normalization is used)
local angleFromTarget = math.abs(wTarget)*fTarget
local angleFromObstacle = math.abs(wObstacle)*fObstacleSum
--Spring.Echo(math.modf(angleFromObstacle))
local angleFromNoise = Sgn((-1)*angleFromObstacle)*(noiseAngleG)*GaussianNoise() --(noiseAngleG)*(GaussianNoise()*2-1) --for random in negative & positive direction
local unitAngleDerived= angleFromTarget + (-1)*angleFromObstacle + angleFromNoise --add attractor amplitude, add repulsive amplitude, and add noise between -ve & +ve noiseAngle. NOTE: somehow "angleFromObstacle" have incorrect sign (telling unit to turn in opposite direction)
if math.abs(unitAngleDerived) > maximumTurnAngleG then --to prevent excess in avoidance causing overflow in angle changes (maximum angle should be pi, but useful angle should be pi/2 eg: 90 degree)
--Spring.Echo("Dynamic Avoidance warning: total angle changes excess")
unitAngleDerived = Sgn(unitAngleDerived)*maximumTurnAngleG
end
unitDirection = unitDirection+math.pi --temporarily remove negative hemisphere so that arithmetic with negative angle won't skew the result
local newUnitAngleDerived= unitDirection +unitAngleDerived --add derived angle into current unit direction plus some noise
newUnitAngleDerived = newUnitAngleDerived - math.pi --readd negative hemisphere
if newUnitAngleDerived > math.pi then --add residual angle (angle > 2 circle) to respective negative or positive hemisphere
newUnitAngleDerived = newUnitAngleDerived - 2*math.pi
elseif newUnitAngleDerived < -1*math.pi then
newUnitAngleDerived = newUnitAngleDerived + 2*math.pi
end
if (turnOnEcho == 1) then
-- Spring.Echo("unitAngleDerived (getNewAngle)" ..unitAngleDerived*180/math.pi)
-- Spring.Echo("newUnitAngleDerived (getNewAngle)" .. newUnitAngleDerived*180/math.pi)
-- Spring.Echo("angleFromTarget (getNewAngle)" .. angleFromTarget*180/math.pi)
-- Spring.Echo("angleFromObstacle (getNewAngle)" .. angleFromObstacle*180/math.pi)
-- Spring.Echo("fTarget (getNewAngle)" .. fTarget)
--Spring.Echo("fObstacleSum (getNewAngle)" ..fObstacleSum)
--Spring.Echo("unitAngleDerived(GetNewAngle) " .. unitAngleDerived)
--Spring.Echo("newUnitAngleDerived(GetNewAngle) " .. newUnitAngleDerived)
end
return newUnitAngleDerived --sent out derived angle
end
function NearestSafeCoordinate (unitID, safeHavenCoordinates, nearestSafeHavenDistance, nearestSafeHaven, currentSafeHaven)
local x,_,z = spGetUnitPosition(unitID)
local unitDefID = spGetUnitDefID(unitID)
local unitDef = UnitDefs[unitDefID]
--local movementType = unitDef.moveData.name
for j=1, #safeHavenCoordinates, 1 do --//iterate over all possible retreat point (bases with at least 3 units in a cluster)
local distance = Distance(safeHavenCoordinates[j][1], safeHavenCoordinates[j][3] , x, z)
local pathOpen = false
local validX = 0
local validZ = 0
local positionToCheck = {{0,0},{1,1},{-1,-1},{1,-1},{-1,1},{0,1},{0,-1},{1,0},{-1,0}}
for i=1, 9, 1 do --//randomly select position around 100-meter from the center for 5 times before giving up, if given up: it imply that this position is too congested for retreating.
--local xDirection = mathRandom(-1,1)
--local zDirection = mathRandom(-1,1)
local xDirection = positionToCheck[i][1]
local zDirection = positionToCheck[i][2]
validX = safeHavenCoordinates[j][1] + (xDirection*100 + xDirection*mathRandom(0,100))
validZ = safeHavenCoordinates[j][3] + (zDirection*100 + zDirection*mathRandom(0,100))
local units = spGetUnitsInRectangle( validX-40, validZ-40, validX+40, validZ+40 )
if units == nil or #units == 0 then --//if this box is empty then return this area as accessible.
pathOpen = true
break
end
end
if distance > 300 and distance < nearestSafeHavenDistance and pathOpen then
nearestSafeHavenDistance = distance
nearestSafeHaven.params[1] = validX
nearestSafeHaven.params[2] = safeHavenCoordinates[j][2]
nearestSafeHaven.params[3] = validZ
elseif distance < 300 then --//theoretically this will run once because units can only be at 1 cluster at 1 time or not at any cluster at all
currentSafeHaven.params[1] = validX
currentSafeHaven.params[2] = safeHavenCoordinates[j][2]
currentSafeHaven.params[3] = validZ
end
end
return nearestSafeHaven, currentSafeHaven
end
---------------------------------Level4
---------------------------------Level5
function SumRiWiDiCalculation (wi, fObstacle, fObstacleSlope, di, wTotal, dSum, fObstacleSum, dFobstacle)
wTotal = wTotal +wi
fObstacleSum= fObstacleSum +(fObstacle)
dFobstacle= dFobstacle + (fObstacleSlope)
--Spring.Echo(dFobstacle)
dSum= dSum +di
return wTotal, dSum, fObstacleSum, dFobstacle
end
--Gaussian noise, Box-Muller method
--from http://www.dspguru.com/dsp/howtos/how-to-generate-white-gaussian-noise
--output value from -1 to +1 with bigger chance of getting 0
function GaussianNoise()
local v1
local v2
local s = 0
repeat
local u1=math.random() --U1=[0,1]
local u2=math.random() --U2=[0,1]
v1= 2 * u1 -1 -- V1=[-1,1]
v2=2 * u2 - 1 -- V2=[-1,1]
s=v1 * v1 + v2 * v2
until (s<1)
local x=math.sqrt(-2 * math.log(s) / s) * v1
return x
end
function Sgn(x)
if x == 0 then
return 0
end
local y= x/(math.abs(x))
return y
end
function Distance(x1,z1,x2,z2)
local dis = math.sqrt((x1-x2)*(x1-x2)+(z1-z2)*(z1-z2))
return dis
end
function GetDistancePerDelay(velocityX, velocityZ, delaySecond)
return velocityX*30*delaySecond,velocityZ*30*delaySecond --convert per-frame velocity into per-second velocity, then into elmo-per-delay
end
---------------------------------Level5
--REFERENCE:
--1
--Non-linear dynamical system approach to behavior modeling --Siome Goldenstein, Edward Large, Dimitris Metaxas
--Dynamic autonomous agents: game applications -- Siome Goldenstein, Edward Large, Dimitris Metaxas
--2
--"unit_tactical_ai.lua" -ZeroK gadget by Google Frog
--3
--"Initial Queue" widget, "Allows you to queue buildings before game start" (unit_initial_queue.lua), author = "Niobium",
--4
--"unit_smart_nanos.lua" widget, "Enables auto reclaim & repair for idle nano turrets , author = Owen Martindell
--5
--"Chili Crude Player List", "Player List",, author=CarRepairer
--6
--Gaussian noise, Box-Muller method, http://www.dspguru.com/dsp/howtos/how-to-generate-white-gaussian-noise
--http://springrts.com/wiki/Lua_Scripting
--7
--"gui_contextmenu.lua" -unit stat widget, by CarRepairer/WagonRepairer
--8
--"unit_AA_micro.lua" -widget that micromanage AA, weaponsState example, by Jseah
--9
--"cmd_retreat.lua" -Place 'retreat zones' on the map and order units to retreat to them at desired HP percentages, by CarRepairer (OPT_INTERNAL function)
--"gui_epicmenu.lua" --"Extremely Powerful Ingame Chili Menu.", by Carrepairer
--"gui_chili_integral_menu.lua" --Chili Integral Menu, by Licho, KingRaptor, Google Frog
--10
--Thanks to versus666 for his endless playtesting and creating idea for improvement & bug report (eg: messy command queue case, widget overriding user's command case, "avoidance may be bad for gunship" case, avoidance depending on detected enemy sonar, constructor's retreat timeout, selection effect avoidance, ect)
--11
-- Ref: http://en.wikipedia.org/wiki/Moving_average#Simple_moving_average (rolling average)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--Feature Tracking:
-- Constructor under area reclaim will return to center of area command when sighting an enemy
-- Attacked will mark last attacker and avoid them even when outside LOS for 3 second
-- Unit outside user view will universally auto-avoidance, but remain still when seen
-- Hold position prevent universal auto-avoidance when not seen, also prevent auto-retreat when unit perform auto-attack
-- Unit under attack command will perform auto-retreat when reloading or shield < 50% regardless of hold-position state
-- Cloakable unit will universally auto-avoid when moving...
-- Area repair will cause unit auto-avoid from point to point (unit to repair); this is contrast to area reclaim.
-- Area Reclaim/ressurect tolerance < area repair tolerance < move tolerance (unit within certain radius of target will ignore enemy/not avoid)
-- Individual repair/reclaim command queue has same tolerance as area repair tolerance
-- ???
| gpl-2.0 |
MTDdk/FrameworkBenchmarks | frameworks/Lua/openresty/app.lua | 25 | 2311 | local mysql = mysql
local encode = encode
local random = math.random
local min = math.min
local insert = table.insert
local sort = table.sort
local template = require'resty.template'
local ngx = ngx
local ngx_print = ngx.print
template.caching(false)
-- Compile template, disable cache, enable plain text view to skip filesystem loading
local view = template.compile([[<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>{% for _,f in ipairs(fortunes) do %}<tr><td>{{ f.id }}</td><td>{{ f.message }}</td></tr>{% end %}</table></body></html>]], nil, true)
local mysqlconn = {
host = os.getenv("DBIP"),
port = 3306,
database = "hello_world",
user = "benchmarkdbuser",
password = "benchmarkdbpass"
}
local _M = {}
function _M.db()
local db = mysql:new()
assert(db:connect(mysqlconn))
ngx_print(encode(db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]))
db:set_keepalive(0, 256)
end
function _M.queries()
local db = mysql:new()
assert(db:connect(mysqlconn))
local num_queries = tonumber(ngx.var.arg_queries) or 1
-- May seem like a stupid branch, but since we know that
-- at a benchmark it will always be taken one way,
-- it doesn't matter. For me, after a small warmup, the performance
-- is identical to a version without the branch
-- http://wiki.luajit.org/Numerical-Computing-Performance-Guide
if num_queries < 2 then
ngx_print(encode({db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]}))
else
local worlds = {}
num_queries = min(500, num_queries)
for i=1, num_queries do
worlds[#worlds+1] = db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]
end
ngx_print( encode(worlds) )
end
db:set_keepalive(0, 256)
end
function _M.fortunes()
local db = mysql:new()
assert(db:connect(mysqlconn))
local fortunes = db:query('SELECT * FROM Fortune')
insert(fortunes, {
id = 0,
message = "Additional fortune added at request time."
})
sort(fortunes, function(a, b)
return a.message < b.message
end)
local res = view{fortunes=fortunes}
ngx.header['Content-Length'] = #res
ngx_print(res)
db:set_keepalive(0, 256)
end
return _M
| bsd-3-clause |
The-HalcyonDays/darkstar | scripts/zones/Castle_Oztroja/npcs/_47u.lua | 17 | 1254 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47u (Handle)
-- Notes: Opens door _474 from behind
-- @pos -60 24 -77 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID() - 1;
local DoorA = GetNPCByID(DoorID):getAnimation();
if(player:getZPos() < -72) then
if(DoorA == 9 and npc:getAnimation() == 9) then
npc:openDoor(6.5);
-- Should be a ~1 second delay here before the door opens
GetNPCByID(DoorID):openDoor(4.5);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Buburimu_Peninsula/npcs/Song_Runes.lua | 34 | 1922 | -----------------------------------
-- Area: Buburimu Peninsula
-- NPC: Song Runes
-- Finishes Quest: The Old Monument
-----------------------------------
package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Buburimu_Peninsula/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("TheOldMonument_Event") == 3) then
count = trade:getItemCount();
gil = trade:getGil();
if (trade:hasItemQty(917,1) == true and count == 1 and gil == 0) then
player:tradeComplete();
player:completeQuest(JEUNO,THE_OLD_MONUMENT);
player:addItem(634,1);
player:messageSpecial(ITEM_OBTAINED, 634);
player:addTitle(RESEARCHER_OF_CLASSICS);
player:addFame(BASTOK,BAS_FAME*10);
player:addFame(SANDORIA,SAN_FAME*10);
player:addFame(WINDURST,WIN_FAME*10);
player:setVar("TheOldMonument_Event",0);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("TheOldMonument_Event") == 2) then
player:startEvent(0x0000);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0000) then
player:setVar("TheOldMonument_Event",3);
end
end;
| gpl-3.0 |
otservme/global1053 | data/movements/scripts/the queen of the banshees quest/theSecondSealPearl.lua | 2 | 1157 | local function doCheckPearls(pearlPos, itemid)
local Tile = Position(pearlPos):getTile()
if Tile then
local thing = Tile:getItemById(itemid)
if thing and thing:isItem() then
thing:remove()
Position(pearlPos):sendMagicEffect(CONST_ME_MAGIC_RED)
return true
else
return false
end
end
end
local config = {
[1] = {pos = {x = 32173, y = 31871, z = 15}, pId = 2143},
[2] = {pos = {x = 32180, y = 31871, z = 15}, pId = 2144}
}
function onStepIn(cid, item, position, lastPosition)
local player = Player(cid)
local pearls = 0
if not player then
return false
end
if player:getStorageValue(50019) < 1 then
for i = 1, 2 do
if doCheckPearls(config[i].pos, config[i].pId) then
pearls = pearls + 1
end
end
if pearls == 2 then
player:teleportTo({x = player:getPosition().x, y = player:getPosition().y-6, z = 15}, false)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
else
player:teleportTo(lastPosition, true)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
end
else
player:teleportTo(lastPosition, true)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
end
return true
end | gpl-2.0 |
The-HalcyonDays/darkstar | scripts/zones/LaLoff_Amphitheater/mobs/Ark_Angel_GK.lua | 27 | 1373 | -----------------------------------
-- Area: LaLoff Amphitheater
-- NPC: Ark Angel GK
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-----------------------------------
-- TODO: Allegedly has a 12 hp/sec regen. Determine if true, and add to onMobInitialize if so.
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
-- TODO: Call Wyvern onMobEngage
local mobid = mob:getID()
for member = mobid-6, mobid+1 do
if (GetMobAction(member) == 16) then
GetMobByID(member):updateEnmity(target);
end
end
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
-- TODO: Allegedly resummons wyvern 30 seconds after death. Verify and implement if true.
-- TODO: Allegedly uses Meikyo Shisui every 90 seconds. Verify and implement if true.
-- TODO: AA GK actively seeks to skillchain to Light off of his own WSs under MS, or other AA's WSs.
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob,killer)
end;
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/AlTaieu/npcs/Auroral_Updraft.lua | 9 | 1769 | -----------------------------------
-- Area: Al'Taieu
-- NPC: Auroral Updraft
-- Type: Standard NPC
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/AlTaieu/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Auroral_Offset = 16912902;
local npcID = npc:getID();
if(npcID == Auroral_Offset) then
player:startEvent(0x0096);
elseif(npcID == Auroral_Offset+1) then
player:startEvent(0x009B);
elseif(npcID == Auroral_Offset+2) then
player:startEvent(0x009B);
elseif(npcID == Auroral_Offset+3) then
player:startEvent(0x009B);
elseif(npcID == Auroral_Offset+4) then
player:startEvent(0x009B);
elseif(npcID == Auroral_Offset+5) then
player:startEvent(0x009B);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x009B) and option == 1 then
player:setPos(-25,-1 ,-620 ,208 ,33);
elseif(csid == 0x0096) and option == 1 then
player:setPos(611.931, 132.787, 773.427, 192, 32); -- To Sealion's Den {R}
end
end;
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Nashmau/npcs/Wata_Khamazom.lua | 34 | 1438 | -----------------------------------
-- Area: Nashmau
-- NPC: Wata Khamazom
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,WATAKHAMAZOM_SHOP_DIALOG);
stock = {0x4300,44, -- Shortbow
0x4301,536, -- Self Bow
0x4302,7920, -- Wrapped Bow
0x4308,492, -- Longbow
0x430A,21812, -- Great Bow
0x43A6,4, -- Wooden Arrow
0x43A8,8, -- Iron Arrow
0x43A9,18, -- Silver Arrow
0x43AA,140, -- Fire Arrow
0x43B8,6, -- Crossbow Bolt
0x4752,248} -- Throwing Tomahawk
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/globals/spells/curaga.lua | 13 | 1210 | -----------------------------------------
-- Spell: Curaga
-- Restores HP of all party members within area of effect.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local minCure = 60;
local divisor = 1;
local constant = 20;
local power = getCurePowerOld(caster);
if(power > 170) then
divisor = 35.6666;
constant = 87.62;
elseif(power > 110) then
divisor = 2;
constant = 47.5;
end
local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,false);
final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100));
--Applying server mods....
final = final * CURE_POWER;
local diff = (target:getMaxHP() - target:getHP());
if(final > diff) then
final = diff;
end
target:addHP(final);
target:wakeUp();
caster:updateEnmityFromCure(target,final);
spell:setMsg(367);
return final;
end; | gpl-3.0 |
SkotisVarvikas/TES3MP-Stuffs | VampiresAndWerewolves/VampiresAndWerewolves.lua | 1 | 9167 | require("color")
Methods = {}
local vampirismCostItemId = "gold_001" -- ID of the item
local vampirismCostCureItemId = "" -- ID of the cure item
local vampirismCostCount = "100000" -- amount of the item
local vampirismCostCureCount = "" -- amount of the cure item
local vampirismCostText = "This process will be instant and will cost you 100.000 gold." -- text to display regarding the item and count, cannot be made dynamic with current tools in a simple way
local vampirismCostCureText = "This process will be instant. The cure will cost you nothing" -- same as before
local vampirismGUIID = 695874 -- GUI ID for transformation texboxes, do not touch
local vampirismCureGUIID = 695875 -- no touchies
local vampirismLevelReq = 0 -- optional level requirement; keep it at 0 if no requirement is desired (unless you have players being level 0 for some reason)
local allowCure = true -- allow curing?
local allowVampirism = true -- allow infection?
local displayGlobalTransformationMessage = true -- whether or not to display the transformation message to the whole server
Methods.IsVampire = function(pid)
local isVampire
for index, item in pairs(Players[pid].data.spellbook) do
if tableHelper.containsKeyValue(Players[pid].data.spellbook, "spellId", "vampire attributes", true) then
isVampire = true
else
isVampire = false
end
end
return isVampire
end
Methods.OnLogin = function(pid)
local message = ""
local vampireClan
local isVampire = false
local consoleAddSpell
local consoleStartScript
isVampire = VaW.IsVampire(pid)
if isVampire == true then
for index, item in pairs(Players[pid].data.spellbook) do
if tableHelper.containsKeyValue(Players[pid].data.spellbook, "spellId", "vampire berne specials", true) then
vampireClan = "berne"
elseif tableHelper.containsKeyValue(Players[pid].data.spellbook, "spellId", "vampire aundae specials", true) then
vampireClan = "aundae"
elseif tableHelper.containsKeyValue(Players[pid].data.spellbook, "spellId", "vampire quarra specials", true) then
vampireClan = "quarra"
else
vampireClan = "none"
end
end
if vampireClan ~= "none" then
consoleAddSpell = "player->addspell \"vampire blood " .. vampireClan .. "\""
consoleStartScript = "startscript, \"vampire_" .. vampireClan .. "_PC\""
else
local logmessage = "VaW: WARNING! PLAYER PID" .. pid .. " IS VAMPIRE WITH NO CLAN\n"
tes3mp.LogMessage(0, message)
end
myMod.RunConsoleCommandOnPlayer(pid, consoleAddSpell)
myMod.RunConsoleCommandOnPlayer(pid, consoleStartScript)
end
end
Methods.Initialize = function(pid)
local level = tonumber(Players[pid].data.stats.level)
local message
local isVampire
if allowVampirism == true then
isVampire = VaW.IsVampire(pid)
if isVampire == false then
if level < vampirismLevelReq then
message = color.Red .. "Insufficient level. Required: " .. vampirismLevelReq .. "\n" .. color.Default
tes3mp.SendMessage(pid, message, false)
else
VaW.ShowCostBox(pid)
end
else
message = color.Red .. "You are already a vampire.\n" .. color.Default
tes3mp.SendMessage(pid, message, false)
end
else
message = color.Crimson .. "You cannot transform into a vampire this way.\n" .. color.Default
tes3mp.SendMessage(pid, message, false)
end
end
Methods.InitializeCure = function(pid)
local message
local isVampire
isVampire = VaW.IsVampire(pid)
if allowCure == true then
if isVampire == true then
VaW.ShowCureBox(pid)
else
message = color.Red .. "You are not a vampire.\n" .. color.Default
tes3mp.SendMessage(pid, message, false)
end
else
message = color.Crimson .. "You cannot cure the disease this way.\n" .. color.Default
tes3mp.SendMessage(pid, message, false)
end
end
Methods.ShowCostBox = function(pid)
local label = "Select your vampire clan.\n"
if vampirismCostItemId ~= "" then
label = label .. vampirismCostText
end
local buttonData = " Aundae ; Berne ; Quarra ; Cancel "
tes3mp.CustomMessageBox(pid, vampirismGUIID, label, buttonData)
end
Methods.ShowCureBox = function(pid)
local label = "Are you sure you want to cure yourself?.\n"
if vampirismCostCureItemId ~= "" then
label = label .. vampirismCostCureText
end
local buttonData = "Yes;No"
tes3mp.CustomMessageBox(pid, vampirismCureGUIID, label, buttonData)
end
Methods.OnGUIAction = function(pid, idGui, data)
if idGui == vampirismGUIID then
if tonumber(data) == 0 then -- Aundae
VaW.BuyVampirism(pid,1)
return true
elseif tonumber(data) == 1 then -- Berne
VaW.BuyVampirism(pid,2)
return true
elseif tonumber(data) == 2 then -- Quarra
VaW.BuyVampirism(pid,3)
return true
elseif tonumber(data) == 3 then -- Cancel
return true
end
elseif idGui == vampirismCureGUIID then
if tonumber(data) == 0 then -- Cure
VaW.Cure(pid)
return true
elseif tonumber(data) == 1 then -- Cancel
return true
end
end
end
Methods.BuyVampirism = function(pid, clan)
local message
local itemCount
local itemIndex
local canTransform = true
local clanName
local playerName = tes3mp.GetName(pid)
if clan == 1 then
clanName = "Aundae"
elseif clan == 2 then
clanName = "Berne"
elseif clan == 3 then
clanName = "Quarra"
end
if vampirismCostItemId ~= "" then
for index, item in pairs(Players[pid].data.inventory) do
if tableHelper.containsKeyValue(Players[pid].data.inventory, "refId", vampirismCostItemId, true) then
itemIndex = tableHelper.getIndexByNestedKeyValue(Players[pid].data.inventory, "refId", vampirismCostItemId)
itemCount = Players[pid].data.inventory[itemIndex].count
else
itemCount = 0
end
end
if tonumber(itemCount) < tonumber(vampirismCostCount) then
canTransform = false
end
end
if canTransform == true then
if costItem ~= "" then
Players[pid].data.inventory[itemIndex].count = Players[pid].data.inventory[itemIndex].count - tonumber(vampirismCostCount)
if Players[pid].data.inventory[itemIndex].count == 0 then
Players[pid].data.inventory[itemIndex] = nil
end
end
message = color.Red .. "Transformation complete. You are now part of the " .. clanName .. " clan.\n" .. color.Default
tes3mp.SendMessage(pid, message, false)
if displayGlobalTransformationMessage == true then
message = color.DarkSalmon .. playerName .. " has joined the " .. clanName .. " vampire clan.\n" .. color.Default
tes3mp.SendMessage(pid, message, true)
end
Players[pid]:LoadInventory()
Players[pid]:LoadEquipment()
Players[pid]:Save()
VaW.Transform(pid,clan)
else
message = color.IndianRed .. "Item(s) missing.\n" .. color.Default
tes3mp.SendMessage(pid, message, false)
end
end
Methods.Transform = function(pid, clan)
local consoleAddSpell
local consoleStartScript
local consoleSetPCVamp
local vampireClan
if clan == 1 then
vampireClan = "aundae"
elseif clan == 2 then
vampireClan = "berne"
elseif clan == 3 then
vampireClan = "quarra"
end
consoleSetPCVamp = "set PCVampire to 0"
consoleAddSpell = "player->addspell \"vampire blood " .. vampireClan .. "\""
consoleStartScript = "startscript, \"vampire_" .. vampireClan .. "_PC\""
myMod.RunConsoleCommandOnPlayer(pid, consoleSetPCVamp)
myMod.RunConsoleCommandOnPlayer(pid, consoleAddSpell)
myMod.RunConsoleCommandOnPlayer(pid, consoleStartScript)
myMod.OnPlayerSpellbook(pid)
end
Methods.Cure = function(pid)
local consoleCure
local consoleSetPCVamp
local message
local playerName = tes3mp.GetName(pid)
consoleCure = "startscript, \"Vampire_Cure_PC\""
consoleSetPCVamp = "set PCVampire to 0"
myMod.RunConsoleCommandOnPlayer(pid, consoleCure)
--myMod.RunConsoleCommandOnPlayer(pid, consoleSetPCVamp) -- NO WORKIES, SETS VARIABLE TOO FAST
message = color.Green .. "You no longer feel the thirst for blood. You've been cured!\n" .. color.Default
tes3mp.SendMessage(pid, message, false)
if displayGlobalTransformationMessage == true then
message = color.DarkGreen .. playerName .. " has cured their vampirism.\n" .. color.Default
tes3mp.SendMessage(pid, message, true)
end
myMod.OnPlayerSpellbook(pid)
end
return Methods
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Port_San_dOria/npcs/Laucimercen.lua | 36 | 1377 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Laucimercen
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x233);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Ifrits_Cauldron/npcs/qm4.lua | 8 | 1475 | -----------------------------------
-- Area: Ifrit's Cauldron
-- NPC: ???
-- Involved in Mission: Bastok 6-2
-- @pos 171 0 -25 205
-----------------------------------
package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Ifrits_Cauldron/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getCurrentMission(BASTOK) == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 2) then
if(GetMobAction(17616897) == 0 and GetMobAction(17616898) == 0 and trade:hasItemQty(646,1) and trade:getItemCount() == 1) then
player:tradeComplete();
SpawnMob(17616897):updateClaim(player);
SpawnMob(17616898):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/globals/abilities/corsairs_roll.lua | 11 | 2168 | -----------------------------------
-- Ability: Corsair's Roll
-- Increases the amount of experience points earned by party members within area of effect
-- Optimal Job: Corsair
-- Lucky Number: 5
-- Unlucky Number: 9
-- Level: 5
--
-- Die Roll |Exp Bonus%
-- -------- -----------
-- 1 |10%
-- 2 |11%
-- 3 |11%
-- 4 |12%
-- 5 |20%
-- 6 |13%
-- 7 |15%
-- 8 |16%
-- 9 |8%
-- 10 |17%
-- 11 |24%
-- 12+ |-6%
--
-- Bust for Corsair set as subjob is also -6%.
-- Corsair set as subjob is 7% on Lucky roll (5) and 1% on Unlucky roll (9).
-- The EXP bonus afforded by Corsair's Roll does not apply within Abyssea.
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = getCorsairRollEffect(ability:getID());
if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbilityRoll
-----------------------------------
function onUseAbilityRoll(caster,target,ability,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {10, 11, 11, 12, 20, 13, 15, 16, 8, 17, 24, 6};
local effectpower = effectpowers[total];
if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_CORSAIRS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_EXP_BONUS) == false) then
ability:setMsg(423);
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/globals/spells/sleep_ii.lua | 11 | 1077 | -----------------------------------------
-- Spell: Sleep II
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local duration = 90;
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
local typeEffect = EFFECT_SLEEP_II;
local pINT = caster:getStat(MOD_INT);
local mINT = target:getStat(MOD_INT);
local dINT = (pINT - mINT);
local resm = applyResistanceEffect(caster,spell,target,dINT,ENFEEBLING_MAGIC_SKILL,0,typeEffect);
if(resm < 0.5) then
spell:setMsg(85);--resist message
return typeEffect;
end
duration = duration * resm;
if(target:addStatusEffect(typeEffect,2,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
return typeEffect;
end; | gpl-3.0 |
mjanicek/rembulan | rembulan-tests/src/test/resources/benchmarksgame/nbody.lua-2.lua | 4 | 3439 | -- The Computer Language Benchmarks Game
-- http://benchmarksgame.alioth.debian.org/
-- contributed by Mike Pall
-- modified by Geoff Leyland
local sqrt = math.sqrt
local PI = 3.141592653589793
local SOLAR_MASS = 4 * PI * PI
local DAYS_PER_YEAR = 365.24
local bodies = {
{ -- Sun
x = 0,
y = 0,
z = 0,
vx = 0,
vy = 0,
vz = 0,
mass = SOLAR_MASS
},
{ -- Jupiter
x = 4.84143144246472090e+00,
y = -1.16032004402742839e+00,
z = -1.03622044471123109e-01,
vx = 1.66007664274403694e-03 * DAYS_PER_YEAR,
vy = 7.69901118419740425e-03 * DAYS_PER_YEAR,
vz = -6.90460016972063023e-05 * DAYS_PER_YEAR,
mass = 9.54791938424326609e-04 * SOLAR_MASS
},
{ -- Saturn
x = 8.34336671824457987e+00,
y = 4.12479856412430479e+00,
z = -4.03523417114321381e-01,
vx = -2.76742510726862411e-03 * DAYS_PER_YEAR,
vy = 4.99852801234917238e-03 * DAYS_PER_YEAR,
vz = 2.30417297573763929e-05 * DAYS_PER_YEAR,
mass = 2.85885980666130812e-04 * SOLAR_MASS
},
{ -- Uranus
x = 1.28943695621391310e+01,
y = -1.51111514016986312e+01,
z = -2.23307578892655734e-01,
vx = 2.96460137564761618e-03 * DAYS_PER_YEAR,
vy = 2.37847173959480950e-03 * DAYS_PER_YEAR,
vz = -2.96589568540237556e-05 * DAYS_PER_YEAR,
mass = 4.36624404335156298e-05 * SOLAR_MASS
},
{ -- Neptune
x = 1.53796971148509165e+01,
y = -2.59193146099879641e+01,
z = 1.79258772950371181e-01,
vx = 2.68067772490389322e-03 * DAYS_PER_YEAR,
vy = 1.62824170038242295e-03 * DAYS_PER_YEAR,
vz = -9.51592254519715870e-05 * DAYS_PER_YEAR,
mass = 5.15138902046611451e-05 * SOLAR_MASS
}
}
local function advance(bodies, nbody, dt)
for i=1,nbody do
local bi = bodies[i]
local bix, biy, biz, bimass = bi.x, bi.y, bi.z, bi.mass
local bivx, bivy, bivz = bi.vx, bi.vy, bi.vz
for j=i+1,nbody do
local bj = bodies[j]
local dx, dy, dz = bix-bj.x, biy-bj.y, biz-bj.z
local mag = sqrt(dx*dx + dy*dy + dz*dz)
mag = dt / (mag * mag * mag)
local bm = bj.mass*mag
bivx = bivx - (dx * bm)
bivy = bivy - (dy * bm)
bivz = bivz - (dz * bm)
bm = bimass*mag
bj.vx = bj.vx + (dx * bm)
bj.vy = bj.vy + (dy * bm)
bj.vz = bj.vz + (dz * bm)
end
bi.vx = bivx
bi.vy = bivy
bi.vz = bivz
bi.x = bix + dt * bivx
bi.y = biy + dt * bivy
bi.z = biz + dt * bivz
end
end
local function energy(bodies, nbody)
local e = 0
for i=1,nbody do
local bi = bodies[i]
local vx, vy, vz, bim = bi.vx, bi.vy, bi.vz, bi.mass
e = e + (0.5 * bim * (vx*vx + vy*vy + vz*vz))
for j=i+1,nbody do
local bj = bodies[j]
local dx, dy, dz = bi.x-bj.x, bi.y-bj.y, bi.z-bj.z
local distance = sqrt(dx*dx + dy*dy + dz*dz)
e = e - ((bim * bj.mass) / distance)
end
end
return e
end
local function offsetMomentum(b, nbody)
local px, py, pz = 0, 0, 0
for i=1,nbody do
local bi = b[i]
local bim = bi.mass
px = px + (bi.vx * bim)
py = py + (bi.vy * bim)
pz = pz + (bi.vz * bim)
end
b[1].vx = -px / SOLAR_MASS
b[1].vy = -py / SOLAR_MASS
b[1].vz = -pz / SOLAR_MASS
end
local N = tonumber(arg and arg[1]) or 1000
local nbody = #bodies
offsetMomentum(bodies, nbody)
io.write( string.format("%0.9f",energy(bodies, nbody)), "\n")
for i=1,N do advance(bodies, nbody, 0.01) end
io.write( string.format("%0.9f",energy(bodies, nbody)), "\n")
| apache-2.0 |
The-HalcyonDays/darkstar | scripts/globals/items/inferno_sword.lua | 16 | 1030 | -----------------------------------------
-- ID: 16594
-- Item: Inferno Sword
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = 163;
if (dmg < 0) then
message = 167;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Port_San_dOria/npcs/Diraulate.lua | 36 | 1375 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Diraulate
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x245);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/The_Shrine_of_RuAvitau/npcs/Grounds_Tome.lua | 34 | 1144 | -----------------------------------
-- Area: Shrine of Ru'Avitau
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_SHRINE_OF_RUAVITAU,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,749,750,751,752,753,754,0,0,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,749,750,751,752,753,754,0,0,0,0,GOV_MSG_SHRINE_OF_RUAVITAU);
end;
| gpl-3.0 |
godly-devotion/Baka-MPlayer-old | Baka MPlayer/bin/Debug/libquvi-scripts/0.9/media/guardian.lua | 3 | 2964 | -- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local Guardian = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = Guardian.can_parse_url(qargs),
domains = table.concat({'theguardian.com', 'guardian.co.uk'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
local p = Guardian.fetch(qargs)
qargs.duration_ms = Guardian.parse_duration(p)
qargs.title = (p:match('"og:title" content="(.-)"') or '')
:gsub('%s+%-%s+video','')
qargs.id = (p:match('prop8%s+=%s+["\'](.-)["\']') or '')
:match('(%d+)') or ''
qargs.thumb_url = p:match('"thumbnail" content="(.-)"')
or p:match('"og:image" content="(.-)"') or ''
qargs.streams = Guardian.iter_streams(p)
return qargs
end
--
-- Utility functions
--
function Guardian.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^https?$')
and t.host and (t.host:lower():match('theguardian%.com$')
or t.host:lower():match('guardian%.co%.uk$'))
and t.path and (t.path:lower():match('/video/')
or t.path:lower():match('/audio/'))
then
return true
else
return false
end
end
function Guardian.fetch(qargs)
local p = quvi.http.fetch(qargs.input_url).data
local e = p:match('<div class="expired">.-<p>(.-)</p>.-</div>') or ''
if #e >0 then error(e) end
return p
end
function Guardian.iter_streams(p)
local u = p:match("%s+file.-:%s+'(.-)'")
or error('no match: media stream URL')
local S = require 'quvi/stream'
local s = S.stream_new(u)
s.video.height = tonumber(p:match('itemprop="height" content="(%d+)"') or 0)
s.video.width = tonumber(p:match('itemprop="width" content="(%d+)"') or 0)
return {s}
end
function Guardian.parse_duration(p)
local n = tonumber(p:match('duration%:%s+"?(%d+)"?') or 0) * 1000
if n ==0 then
local m,s = p:match('T(%d+)M(%d+)S')
n = (tonumber(m)*60 + tonumber(s)) * 1000
end
return n
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
| gpl-2.0 |
rrpgfirecast/firecast | Plugins/Sheets/Ficha L5R 4e/output/rdkObjs/templateArmas.lfm.lua | 1 | 13571 | require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");
local function constructNew_templateArmas()
local obj = GUI.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("templateArmas");
obj:setHeight(30);
obj.btnArma = GUI.fromHandle(_obj_newObject("button"));
obj.btnArma:setParent(obj);
obj.btnArma:setAlign("right");
obj.btnArma:setText("𝐢");
obj.btnArma:setWidth(30);
obj.btnArma:setName("btnArma");
obj.btnArma:setMargins({right=2});
obj.popArma = GUI.fromHandle(_obj_newObject("popup"));
obj.popArma:setParent(obj);
obj.popArma:setName("popArma");
obj.popArma:setWidth(440);
obj.popArma:setHeight(260);
obj.popArma:setBackOpacity(0);
obj.popArma:setDrawContainer(false);
lfm_setPropAsString(obj.popArma, "autoScopeNode", "true");
obj.rectangle1 = GUI.fromHandle(_obj_newObject("rectangle"));
obj.rectangle1:setParent(obj.popArma);
obj.rectangle1:setAlign("client");
obj.rectangle1:setColor("#0e0e0e");
obj.rectangle1:setPadding({top=10, left=10, bottom=10, right=10});
obj.rectangle1:setXradius(10);
obj.rectangle1:setYradius(10);
obj.rectangle1:setCornerType("bevel");
obj.rectangle1:setName("rectangle1");
obj.label1 = GUI.fromHandle(_obj_newObject("label"));
obj.label1:setParent(obj.rectangle1);
obj.label1:setFontColor("white");
obj.label1:setAlign("top");
obj.label1:setField("nomeArma");
obj.label1:setMargins({bottom=5});
lfm_setPropAsString(obj.label1, "fontStyle", "bold");
obj.label1:setFontFamily("Constantia");
obj.label1:setFontSize(26);
obj.label1:setHeight(30);
obj.label1:setName("label1");
obj.horzLine1 = GUI.fromHandle(_obj_newObject("horzLine"));
obj.horzLine1:setParent(obj.rectangle1);
obj.horzLine1:setAlign("top");
obj.horzLine1:setMargins({bottom=5});
obj.horzLine1:setStrokeColor("#424242");
obj.horzLine1:setName("horzLine1");
obj.layout1 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout1:setParent(obj.rectangle1);
obj.layout1:setHeight(30);
obj.layout1:setAlign("top");
obj.layout1:setName("layout1");
obj.layout2 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout2:setParent(obj.layout1);
obj.layout2:setWidth(210);
obj.layout2:setAlign("left");
obj.layout2:setName("layout2");
obj.label2 = GUI.fromHandle(_obj_newObject("label"));
obj.label2:setParent(obj.layout2);
obj.label2:setText("Perícia:");
obj.label2:setWidth(50);
obj.label2:setAlign("left");
obj.label2:setMargins({right=2});
obj.label2:setName("label2");
obj.label2:setFontFamily("Cambria");
obj.label2:setFontColor("white");
lfm_setPropAsString(obj.label2, "fontStyle", "bold");
obj.edit1 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit1:setParent(obj.layout2);
obj.edit1:setField("periArma");
obj.edit1:setAlign("client");
obj.edit1:setMargins({right=2});
obj.edit1:setName("edit1");
obj.edit1:setFontFamily("Cambria");
obj.edit1:setTransparent(true);
obj.edit1:setFontColor("#cdcdcd");
obj.dataLink1 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink1:setParent(obj.layout2);
obj.dataLink1:setDefaultValue("—");
obj.dataLink1:setField("periArma");
obj.dataLink1:setName("dataLink1");
obj.layout3 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout3:setParent(obj.layout1);
obj.layout3:setWidth(210);
obj.layout3:setAlign("left");
obj.layout3:setName("layout3");
obj.label3 = GUI.fromHandle(_obj_newObject("label"));
obj.label3:setParent(obj.layout3);
obj.label3:setText("Ataque:");
obj.label3:setWidth(50);
obj.label3:setAlign("left");
obj.label3:setMargins({right=2});
obj.label3:setName("label3");
obj.label3:setFontFamily("Cambria");
obj.label3:setFontColor("white");
lfm_setPropAsString(obj.label3, "fontStyle", "bold");
obj.edit2 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit2:setParent(obj.layout3);
obj.edit2:setField("atkArma");
obj.edit2:setAlign("client");
obj.edit2:setName("edit2");
obj.edit2:setFontFamily("Cambria");
obj.edit2:setTransparent(true);
obj.edit2:setFontColor("#cdcdcd");
obj.dataLink2 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink2:setParent(obj.layout3);
obj.dataLink2:setDefaultValue("—");
obj.dataLink2:setField("atkArma");
obj.dataLink2:setName("dataLink2");
obj.layout4 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout4:setParent(obj.rectangle1);
obj.layout4:setHeight(30);
obj.layout4:setAlign("top");
obj.layout4:setName("layout4");
obj.layout5 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout5:setParent(obj.layout4);
obj.layout5:setWidth(210);
obj.layout5:setAlign("left");
obj.layout5:setName("layout5");
obj.label4 = GUI.fromHandle(_obj_newObject("label"));
obj.label4:setParent(obj.layout5);
obj.label4:setText("Dano:");
obj.label4:setWidth(40);
obj.label4:setAlign("left");
obj.label4:setMargins({right=2});
obj.label4:setName("label4");
obj.label4:setFontFamily("Cambria");
obj.label4:setFontColor("white");
lfm_setPropAsString(obj.label4, "fontStyle", "bold");
obj.edit3 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit3:setParent(obj.layout5);
obj.edit3:setField("danoArma");
obj.edit3:setAlign("client");
obj.edit3:setMargins({right=2});
obj.edit3:setName("edit3");
obj.edit3:setFontFamily("Cambria");
obj.edit3:setTransparent(true);
obj.edit3:setFontColor("#cdcdcd");
obj.dataLink3 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink3:setParent(obj.layout5);
obj.dataLink3:setDefaultValue("—");
obj.dataLink3:setField("danoArma");
obj.dataLink3:setName("dataLink3");
obj.layout6 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout6:setParent(obj.layout4);
obj.layout6:setWidth(210);
obj.layout6:setAlign("left");
obj.layout6:setName("layout6");
obj.label5 = GUI.fromHandle(_obj_newObject("label"));
obj.label5:setParent(obj.layout6);
obj.label5:setText("Quantidade:");
obj.label5:setWidth(75);
obj.label5:setAlign("left");
obj.label5:setMargins({right=2});
obj.label5:setName("label5");
obj.label5:setFontFamily("Cambria");
obj.label5:setFontColor("white");
lfm_setPropAsString(obj.label5, "fontStyle", "bold");
obj.edit4 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit4:setParent(obj.layout6);
obj.edit4:setField("quantArma");
obj.edit4:setAlign("client");
obj.edit4:setType("number");
obj.edit4:setName("edit4");
obj.edit4:setFontFamily("Cambria");
obj.edit4:setTransparent(true);
obj.edit4:setFontColor("#cdcdcd");
obj.dataLink4 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink4:setParent(obj.layout6);
obj.dataLink4:setDefaultValue("0");
obj.dataLink4:setField("quantArma");
obj.dataLink4:setName("dataLink4");
obj.textEditor1 = GUI.fromHandle(_obj_newObject("textEditor"));
obj.textEditor1:setParent(obj.rectangle1);
obj.textEditor1:setField("descriArma");
obj.textEditor1:setAlign("client");
obj.textEditor1:setFontFamily("Cambria");
obj.textEditor1:setTransparent(true);
obj.textEditor1:setMargins({top=10});
obj.textEditor1:setName("textEditor1");
obj.dataLink5 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink5:setParent(obj.rectangle1);
obj.dataLink5:setField("descriArma");
obj.dataLink5:setDefaultValue("Descrição.");
obj.dataLink5:setName("dataLink5");
obj.button1 = GUI.fromHandle(_obj_newObject("button"));
obj.button1:setParent(obj);
obj.button1:setAlign("right");
obj.button1:setText("🞭");
obj.button1:setWidth(30);
obj.button1:setName("button1");
obj.edit5 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit5:setParent(obj);
obj.edit5:setField("nomeArma");
obj.edit5:setAlign("client");
obj.edit5:setMargins({right=2});
lfm_setPropAsString(obj.edit5, "fontStyle", "bold");
obj.edit5:setFontColor("white");
obj.edit5:setName("edit5");
obj.edit5:setFontFamily("Cambria");
obj.edit5:setTransparent(true);
obj.dataLink6 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink6:setParent(obj);
obj.dataLink6:setDefaultValue("—");
obj.dataLink6:setField("nomeArma");
obj.dataLink6:setName("dataLink6");
obj._e_event0 = obj.btnArma:addEventListener("onClick",
function (_)
local pop = self:findControlByName("popArma");
if pop ~= nil then
pop:setNodeObject(self.sheet);
pop:showPopupEx("left", self.btnArma);
else
showMessage("Ops, bug... Nao encontrei o popup para exibir");
end;
end, obj);
obj._e_event1 = obj.button1:addEventListener("onClick",
function (_)
NDB.deleteNode(sheet);
end, obj);
function obj:_releaseEvents()
__o_rrpgObjs.removeEventListenerById(self._e_event1);
__o_rrpgObjs.removeEventListenerById(self._e_event0);
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.btnArma ~= nil then self.btnArma:destroy(); self.btnArma = nil; end;
if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end;
if self.label1 ~= nil then self.label1:destroy(); self.label1 = nil; end;
if self.layout4 ~= nil then self.layout4:destroy(); self.layout4 = nil; end;
if self.edit4 ~= nil then self.edit4:destroy(); self.edit4 = nil; end;
if self.label3 ~= nil then self.label3:destroy(); self.label3 = nil; end;
if self.label4 ~= nil then self.label4:destroy(); self.label4 = nil; end;
if self.textEditor1 ~= nil then self.textEditor1:destroy(); self.textEditor1 = nil; end;
if self.edit5 ~= nil then self.edit5:destroy(); self.edit5 = nil; end;
if self.dataLink4 ~= nil then self.dataLink4:destroy(); self.dataLink4 = nil; end;
if self.layout5 ~= nil then self.layout5:destroy(); self.layout5 = nil; end;
if self.label2 ~= nil then self.label2:destroy(); self.label2 = nil; end;
if self.dataLink1 ~= nil then self.dataLink1:destroy(); self.dataLink1 = nil; end;
if self.edit3 ~= nil then self.edit3:destroy(); self.edit3 = nil; end;
if self.dataLink3 ~= nil then self.dataLink3:destroy(); self.dataLink3 = nil; end;
if self.layout6 ~= nil then self.layout6:destroy(); self.layout6 = nil; end;
if self.label5 ~= nil then self.label5:destroy(); self.label5 = nil; end;
if self.popArma ~= nil then self.popArma:destroy(); self.popArma = nil; end;
if self.dataLink6 ~= nil then self.dataLink6:destroy(); self.dataLink6 = nil; end;
if self.layout3 ~= nil then self.layout3:destroy(); self.layout3 = nil; end;
if self.dataLink5 ~= nil then self.dataLink5:destroy(); self.dataLink5 = nil; end;
if self.horzLine1 ~= nil then self.horzLine1:destroy(); self.horzLine1 = nil; end;
if self.edit2 ~= nil then self.edit2:destroy(); self.edit2 = nil; end;
if self.dataLink2 ~= nil then self.dataLink2:destroy(); self.dataLink2 = nil; end;
if self.layout1 ~= nil then self.layout1:destroy(); self.layout1 = nil; end;
if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end;
if self.layout2 ~= nil then self.layout2:destroy(); self.layout2 = nil; end;
if self.edit1 ~= nil then self.edit1:destroy(); self.edit1 = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
return obj;
end;
function newtemplateArmas()
local retObj = nil;
__o_rrpgObjs.beginObjectsLoading();
__o_Utils.tryFinally(
function()
retObj = constructNew_templateArmas();
end,
function()
__o_rrpgObjs.endObjectsLoading();
end);
assert(retObj ~= nil);
return retObj;
end;
local _templateArmas = {
newEditor = newtemplateArmas,
new = newtemplateArmas,
name = "templateArmas",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "",
description=""};
templateArmas = _templateArmas;
Firecast.registrarForm(_templateArmas);
return _templateArmas;
| apache-2.0 |
The-HalcyonDays/darkstar | scripts/zones/LaLoff_Amphitheater/npcs/qm1_2.lua | 12 | 2354 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: Shimmering Circle (BCNM Entrances)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
package.loaded["scripts/globals/bcnm"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-- Death cutscenes:
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,0,0); -- hume
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,3,0); -- elvaan
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,5,0); -- divine might
-- param 1: entrance #
-- param 2: fastest time
-- param 3: unknown
-- param 4: clear time
-- param 5: zoneid
-- param 6: exit cs (0-4 AA, 5 DM, 6-10 neo AA, 11 neo DM)
-- param 7: skip (0 - no skip, 1 - prompt, 2 - force)
-- param 8: 0
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(TradeBCNM(player,player:getZoneID(),trade,npc))then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(EventTriggerBCNM(player,npc))then
return;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if(EventUpdateBCNM(player,csid,option,2))then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if(EventFinishBCNM(player,csid,option))then
return;
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Mhaura/npcs/Panoru-Kanoru.lua | 34 | 1081 | ----------------------------------
-- Area: Mhaura
-- NPC: Panoru-Kanoru
-- Type: Item Deliverer
-- @pos 5.241 -4.035 93.891 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, PANORU_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/PsoXja/npcs/_092.lua | 8 | 1608 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _092 (Stone Gate)
-- Notes: Spawns Gargoyle when triggered
-- @pos -330.000 14.074 -261.600 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local X=player:getXPos();
if (npc:getAnimation() == 9) then
if(X >= 339)then
if(GetMobAction(16814083) == 0) then
local Rand = math.random(1,10);
if (Rand <=9) then -- Spawn Gargoyle
player:messageSpecial(TRAP_ACTIVATED);
SpawnMob(16814083,120):updateClaim(player); -- Gargoyle
else
player:messageSpecial(TRAP_FAILS);
npc:openDoor(30);
end
else
player:messageSpecial(DOOR_LOCKED);
end
elseif(X <= 338)then
player:startEvent(0x001A);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if(csid == 0x001A and option == 1) then
player:setPos(260,-0.25,-20,254,111);
end
end; | gpl-3.0 |
APItools/monitor | lua/controllers/api_docs_controller.lua | 2 | 1588 | local http = require 'http'
local h = require 'controller_helpers'
local inspect = require 'inspect'
local m = require 'model_helpers'
local Service = require 'models.service'
local ngxex = require 'ngxex'
local get_code_from_host = function(code)
return string.match(code, "^https?://(.*)-[^./]+")
end
local api_docs = { skip_csrf = true }
api_docs.proxy = function(params)
local headers = ngx.req.get_headers()
local custom_headers = {}
local standard_headers = {}
for k,v in pairs(headers) do
local match = k:match('x-apidocs-.*', 1)
if match then
custom_headers[k] = v
else
standard_headers[k] = v
end
end
local service, url = Service:find_by_endpoint_code(get_code_from_host(custom_headers['x-apidocs-url']))
local path = tostring(custom_headers['x-apidocs-path'])
standard_headers.host = string.match(url, "^.+://([^/]+)")
-- normalize trailing and leading slashes
if url:sub(#url) == '/' then
url = url:sub(0, #url-1)
end
if path:sub(0,1) ~= '/' then
path = '/' .. path
end
url = url .. path
if custom_headers['x-apidocs-query'] then
url = url .. '?' .. custom_headers['x-apidocs-query']
end
local body, status, headers = http.simple({
method = custom_headers['x-apidocs-method'],
url = url,
headers = standard_headers
}, ngxex.req_get_all_body_data())
for name, value in pairs(headers) do
ngx.header[name] = value
end
ngx.print( body )
ngx.exit( status or ngx.HTTP_OK )
end
return api_docs
| mit |
The-HalcyonDays/darkstar | scripts/zones/Cape_Teriggan/mobs/Tegmine.lua | 20 | 1982 | ----------------------------------
-- Area: Cape Teriggan
-- NM: Tegmine
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID());
end;
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(mob,target,damage)
-- Wiki says nothing about proc rate, going with 80% for now.
-- I remember it going off every hit when I fought him.
local chance = 80;
local LV_diff = target:getMainLvl() - mob:getMainLvl();
if (target:getMainLvl() > mob:getMainLvl()) then
chance = chance - 5 * LV_diff;
chance = utils.clamp(chance, 5, 95);
end
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT);
if (INT_diff > 20) then
INT_diff = 20 + (INT_diff - 20) / 2;
end
local dmg = INT_diff+LV_diff+damage/2;
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(mob, ELE_WATER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(mob,target,ELE_WATER,0);
dmg = adjustForTarget(target,dmg,ELE_WATER);
if (dmg < 0) then
dmg = 10
end
dmg = finalMagicNonSpellAdjustments(mob,target,ELE_WATER,dmg);
return SUBEFFECT_WATER_DAMAGE,163,dmg;
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
-- UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random((7200),(7800))); -- 120 to 130 min
end; | gpl-3.0 |
rrpgfirecast/firecast | Plugins/Sheets/Ficha Shadowrun 5E/output/rdkObjs/Shadowrun5E/06.Powers.Spells.lfm.lua | 1 | 6324 | require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");
local function constructNew_frmSpells()
local obj = GUI.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("frmSpells");
obj:setWidth(475);
obj:setHeight(25);
obj:setMargins({top=1});
obj.rectangle1 = GUI.fromHandle(_obj_newObject("rectangle"));
obj.rectangle1:setParent(obj);
obj.rectangle1:setAlign("client");
obj.rectangle1:setColor("#212121");
obj.rectangle1:setName("rectangle1");
obj.edit1 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit1:setParent(obj.rectangle1);
obj.edit1:setLeft(0);
obj.edit1:setTop(0);
obj.edit1:setWidth(150);
obj.edit1:setHeight(25);
obj.edit1:setField("spell_name");
obj.edit1:setName("edit1");
obj.edit2 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit2:setParent(obj.rectangle1);
obj.edit2:setLeft(150);
obj.edit2:setTop(0);
obj.edit2:setWidth(100);
obj.edit2:setHeight(25);
obj.edit2:setField("spell_type");
obj.edit2:setHorzTextAlign("center");
obj.edit2:setName("edit2");
obj.edit3 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit3:setParent(obj.rectangle1);
obj.edit3:setLeft(250);
obj.edit3:setTop(0);
obj.edit3:setWidth(50);
obj.edit3:setHeight(25);
obj.edit3:setField("spell_range");
obj.edit3:setHorzTextAlign("center");
obj.edit3:setType("number");
obj.edit3:setName("edit3");
obj.edit4 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit4:setParent(obj.rectangle1);
obj.edit4:setLeft(300);
obj.edit4:setTop(0);
obj.edit4:setWidth(50);
obj.edit4:setHeight(25);
obj.edit4:setField("spell_duration");
obj.edit4:setHorzTextAlign("center");
obj.edit4:setType("number");
obj.edit4:setName("edit4");
obj.edit5 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit5:setParent(obj.rectangle1);
obj.edit5:setLeft(350);
obj.edit5:setTop(0);
obj.edit5:setWidth(50);
obj.edit5:setHeight(25);
obj.edit5:setField("spell_drain");
obj.edit5:setHorzTextAlign("center");
obj.edit5:setType("number");
obj.edit5:setName("edit5");
obj.edit6 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit6:setParent(obj.rectangle1);
obj.edit6:setLeft(400);
obj.edit6:setTop(0);
obj.edit6:setWidth(50);
obj.edit6:setHeight(25);
obj.edit6:setField("spell_karma");
obj.edit6:setHorzTextAlign("center");
obj.edit6:setType("number");
obj.edit6:setName("edit6");
obj.button1 = GUI.fromHandle(_obj_newObject("button"));
obj.button1:setParent(obj.rectangle1);
obj.button1:setLeft(450);
obj.button1:setTop(0);
obj.button1:setWidth(25);
obj.button1:setHeight(25);
obj.button1:setText("X");
obj.button1:setName("button1");
obj.dataLink1 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink1:setParent(obj.rectangle1);
obj.dataLink1:setField("spell_karma");
obj.dataLink1:setName("dataLink1");
obj._e_event0 = obj.button1:addEventListener("onClick",
function (_)
Dialogs.confirmOkCancel("Tem certeza que quer apagar esse objeto?",
function (confirmado)
if confirmado then
NDB.deleteNode(sheet);
end;
end);
end, obj);
obj._e_event1 = obj.dataLink1:addEventListener("onChange",
function (_, field, oldValue, newValue)
if sheet==nil then return end;
local node = NDB.getRoot(sheet);
local objetos = NDB.getChildNodes(node.spellList);
local karma = 0;
for i=1, #objetos, 1 do
karma = karma + (tonumber(objetos[i].spell_karma) or 0);
end;
node.spells_karma = karma;
end, obj);
function obj:_releaseEvents()
__o_rrpgObjs.removeEventListenerById(self._e_event1);
__o_rrpgObjs.removeEventListenerById(self._e_event0);
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.edit3 ~= nil then self.edit3:destroy(); self.edit3 = nil; end;
if self.edit5 ~= nil then self.edit5:destroy(); self.edit5 = nil; end;
if self.edit2 ~= nil then self.edit2:destroy(); self.edit2 = nil; end;
if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end;
if self.edit4 ~= nil then self.edit4:destroy(); self.edit4 = nil; end;
if self.edit6 ~= nil then self.edit6:destroy(); self.edit6 = nil; end;
if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end;
if self.edit1 ~= nil then self.edit1:destroy(); self.edit1 = nil; end;
if self.dataLink1 ~= nil then self.dataLink1:destroy(); self.dataLink1 = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
return obj;
end;
function newfrmSpells()
local retObj = nil;
__o_rrpgObjs.beginObjectsLoading();
__o_Utils.tryFinally(
function()
retObj = constructNew_frmSpells();
end,
function()
__o_rrpgObjs.endObjectsLoading();
end);
assert(retObj ~= nil);
return retObj;
end;
local _frmSpells = {
newEditor = newfrmSpells,
new = newfrmSpells,
name = "frmSpells",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "",
description=""};
frmSpells = _frmSpells;
Firecast.registrarForm(_frmSpells);
return _frmSpells;
| apache-2.0 |
The-HalcyonDays/darkstar | scripts/zones/Port_Bastok/npcs/Dulsie.lua | 17 | 1326 | -----------------------------------
-- Area: Port Bastok
-- NPC: Dulsie
-- Adventurer's Assistant
-- Working 100%
-------------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/settings");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(0x218,1) and trade:getItemCount() == 1) then
player:startEvent(0x0008);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0007);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0008) then
player:tradeComplete();
player:addGil(GIL_RATE*50);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*50);
end
end; | gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Decarabia.lua | 19 | 1255 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NPC: Marquis Decarabia
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger");
if(mob:isInBattlefieldList() == false) then
mob:addInBattlefieldList();
Animate_Trigger = Animate_Trigger + 1;
SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger);
if(Animate_Trigger == 32767) then
SpawnMob(17330911); -- 142
SpawnMob(17330912); -- 143
SpawnMob(17330183); -- 177
SpawnMob(17330184); -- 178
activateAnimatedWeapon(); -- Change subanim of all animated weapon
end
end
if(Animate_Trigger == 32767) then
killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE);
end
end; | gpl-3.0 |
lovetoys/preset | src/conf.lua | 1 | 1487 |
function love.conf(t)
t.title = "game" -- The title of the window the game is in (string)
t.author = "" -- The author of the game (string)
t.url = "" -- The website of the game (string)
t.identity = nil -- The name of the save directory (string)
t.version = "11.2" -- The LÖVE version this game was made for (string)
t.console = false -- Attach a console (boolean, Windows only)
t.window.width = 0 -- The window width (number)
t.window.height = 0 -- The window height (number)
t.window.fullscreen = true -- Enable fullwindow (boolean)
t.window.vsync = true -- Enable vertical sync (boolean)
t.window.fsaa = 0 -- The number of FSAA-buffers (number)
t.modules.joystick = true -- Enable the joystick module (boolean)
t.modules.audio = true -- Enable the audio module (boolean)
t.modules.keyboard = true -- Enable the keyboard module (boolean)
t.modules.event = true -- Enable the event module (boolean)
t.modules.image = true -- Enable the image module (boolean)
t.modules.graphics = true -- Enable the graphics module (boolean)
t.modules.timer = true -- Enable the timer module (boolean)
t.modules.mouse = true -- Enable the mouse module (boolean)
t.modules.sound = true -- Enable the sound module (boolean)
t.modules.physics = true -- Enable the physics module (boolean)
end
| mit |
The-HalcyonDays/darkstar | scripts/zones/Temenos/mobs/Enhanced_Ahriman.lua | 17 | 1287 | -----------------------------------
-- Area: Temenos Central 1floor
-- NPC: Enhanced_Ahriman
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if(IsMobDead(16929050)==true)then
mob:addStatusEffect(EFFECT_REGAIN,7,3,0);
mob:addStatusEffect(EFFECT_REGEN,50,3,0);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if(IsMobDead(16929046)==true and IsMobDead(16929047)==true and IsMobDead(16929048)==true and IsMobDead(16929049)==true and IsMobDead(16929050)==true and IsMobDead(16929051)==true)then
GetNPCByID(16928768+71):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+71):setStatus(STATUS_NORMAL);
GetNPCByID(16928770+471):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
The-HalcyonDays/darkstar | scripts/zones/Northern_San_dOria/npcs/Narcheral.lua | 23 | 3760 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Narcheral
-- Starts and Finishes Quest: Messenger from Beyond, Prelude of Black and White (Finish), Pieuje's Decision (Finish)
-- @zone 231
-- @pos 129 -11 126
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA, MESSENGER_FROM_BEYOND) == QUEST_ACCEPTED) then
if(trade:hasItemQty(1096,1) and trade:getItemCount() == 1) then -- Trade Tavnazia Pass
player:startEvent(0x02b2); -- Finish quest "Messenger from Beyond"
end
elseif(player:getQuestStatus(SANDORIA,PRELUDE_OF_BLACK_AND_WHITE) == QUEST_ACCEPTED) then
if(trade:hasItemQty(1097,1) and trade:hasItemQty(12995,1) and trade:getItemCount() == 2) then -- Trade Yagudo Holy Water & Moccasins
player:startEvent(0x02b3); -- Finish quest "Prelude of Black and White"
end
elseif(player:getQuestStatus(SANDORIA,PIEUJE_S_DECISION) == QUEST_ACCEPTED) then
if(trade:hasItemQty(13842,1) and trade:getItemCount() == 1) then -- Trade Tavnazian Mask
player:startEvent(0x02b4); -- Finish quest "Pieuje's Decision"
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
messengerFromBeyond = player:getQuestStatus(SANDORIA,MESSENGER_FROM_BEYOND);
-- Checking levels and jobs for af quest
mLvl = player:getMainLvl();
mJob = player:getMainJob();
if(messengerFromBeyond == QUEST_AVAILABLE and mJob == 3 and mLvl >= AF1_QUEST_LEVEL) then
player:startEvent(0x02b1); -- Start quest "Messenger from Beyond"
else
player:startEvent(0x02b0); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x02b1) then
player:addQuest(SANDORIA,MESSENGER_FROM_BEYOND);
elseif(csid == 0x02b2) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17422);
else
player:addItem(17422);
player:messageSpecial(ITEM_OBTAINED,17422); -- Blessed Hammer
player:tradeComplete();
player:addFame(SANDORIA,SAN_FAME*AF1_FAME);
player:completeQuest(SANDORIA,MESSENGER_FROM_BEYOND);
end
elseif(csid == 0x02b3) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14091); -- Healer's Duckbills
else
player:addItem(14091);
player:messageSpecial(ITEM_OBTAINED,14091); -- Healer's Duckbills
player:tradeComplete();
player:addFame(SANDORIA,SAN_FAME*AF2_FAME);
player:completeQuest(SANDORIA,PRELUDE_OF_BLACK_AND_WHITE);
end
elseif(csid == 0x02b4) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12640); -- Healer's Briault
else
player:addTitle(PARAGON_OF_WHITE_MAGE_EXCELLENCE);
player:setVar("pieujesDecisionCS",0);
player:addItem(12640);
player:messageSpecial(ITEM_OBTAINED,12640); -- Healer's Briault
player:tradeComplete();
player:addFame(SANDORIA,SAN_FAME*AF3_FAME);
player:completeQuest(SANDORIA,PIEUJE_S_DECISION);
end
end
end; | gpl-3.0 |
rrpgfirecast/firecast | Plugins/Sheets/Gerenciador de Campanha/output/rdkObjs/GerenciadorDeCampanha/02.npcs.lfm.lua | 2 | 7686 | require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");
local function constructNew_frmGerenciadorNPCs()
local obj = GUI.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("frmGerenciadorNPCs");
obj:setAlign("client");
obj:setTheme("dark");
obj:setMargins({top=1});
obj.scrollBox1 = GUI.fromHandle(_obj_newObject("scrollBox"));
obj.scrollBox1:setParent(obj);
obj.scrollBox1:setAlign("client");
obj.scrollBox1:setName("scrollBox1");
obj.rectangle1 = GUI.fromHandle(_obj_newObject("rectangle"));
obj.rectangle1:setParent(obj.scrollBox1);
obj.rectangle1:setLeft(0);
obj.rectangle1:setTop(0);
obj.rectangle1:setWidth(1320);
obj.rectangle1:setHeight(20);
obj.rectangle1:setColor("Black");
obj.rectangle1:setName("rectangle1");
obj.button1 = GUI.fromHandle(_obj_newObject("button"));
obj.button1:setParent(obj.rectangle1);
obj.button1:setLeft(40);
obj.button1:setTop(0);
obj.button1:setWidth(20);
obj.button1:setHeight(20);
obj.button1:setText("N");
obj.button1:setName("button1");
obj.label1 = GUI.fromHandle(_obj_newObject("label"));
obj.label1:setParent(obj.rectangle1);
obj.label1:setLeft(0);
obj.label1:setTop(0);
obj.label1:setWidth(1320);
obj.label1:setHeight(20);
obj.label1:setText("LISTA DE NPCs CONHECIDOS");
obj.label1:setHorzTextAlign("center");
obj.label1:setName("label1");
obj.rclListaNPCs = GUI.fromHandle(_obj_newObject("recordList"));
obj.rclListaNPCs:setParent(obj.rectangle1);
obj.rclListaNPCs:setName("rclListaNPCs");
obj.rclListaNPCs:setField("listaNPCs");
obj.rclListaNPCs:setTemplateForm("frmGerenciador02_SELECT");
obj.rclListaNPCs:setLeft(0);
obj.rclListaNPCs:setTop(20);
obj.rclListaNPCs:setWidth(1320);
obj.rclListaNPCs:setHeight(45);
obj.rclListaNPCs:setSelectable(true);
obj.rclListaNPCs:setLayout("horizontal");
obj.rclListaNPCs:setMinQt(1);
obj.boxNPCs = GUI.fromHandle(_obj_newObject("dataScopeBox"));
obj.boxNPCs:setParent(obj.scrollBox1);
obj.boxNPCs:setName("boxNPCs");
obj.boxNPCs:setVisible(false);
obj.boxNPCs:setLeft(0);
obj.boxNPCs:setTop(0);
obj.boxNPCs:setWidth(1320);
obj.boxNPCs:setHeight(615);
obj.button2 = GUI.fromHandle(_obj_newObject("button"));
obj.button2:setParent(obj.boxNPCs);
obj.button2:setLeft(0);
obj.button2:setTop(0);
obj.button2:setWidth(20);
obj.button2:setHeight(20);
obj.button2:setText("+");
obj.button2:setName("button2");
obj.button3 = GUI.fromHandle(_obj_newObject("button"));
obj.button3:setParent(obj.boxNPCs);
obj.button3:setLeft(20);
obj.button3:setTop(0);
obj.button3:setWidth(20);
obj.button3:setHeight(20);
obj.button3:setText("O");
obj.button3:setName("button3");
obj.rclNPCs = GUI.fromHandle(_obj_newObject("recordList"));
obj.rclNPCs:setParent(obj.boxNPCs);
obj.rclNPCs:setLeft(0);
obj.rclNPCs:setTop(65);
obj.rclNPCs:setWidth(1320);
obj.rclNPCs:setHeight(550);
obj.rclNPCs:setLayout("horizontalTiles");
obj.rclNPCs:setMinQt(1);
obj.rclNPCs:setName("rclNPCs");
obj.rclNPCs:setField("npcs");
obj.rclNPCs:setTemplateForm("frmGerenciador02_NPC");
obj._e_event0 = obj.button1:addEventListener("onClick",
function (_)
self.rclListaNPCs:append();
end, obj);
obj._e_event1 = obj.rclListaNPCs:addEventListener("onSelect",
function (_)
local node = self.rclListaNPCs.selectedNode;
self.boxNPCs.node = node;
self.boxNPCs.visible = (node ~= nil);
end, obj);
obj._e_event2 = obj.rclListaNPCs:addEventListener("onEndEnumeration",
function (_)
if self.rclListaNPCs.selectedNode == nil and sheet ~= nil then
local nodes = ndb.getChildNodes(sheet.listaNPCs);
if #nodes > 0 then
self.rclListaNPCs.selectedNode = nodes[1];
end;
end;
end, obj);
obj._e_event3 = obj.button2:addEventListener("onClick",
function (_)
self.rclNPCs:append();
end, obj);
obj._e_event4 = obj.button3:addEventListener("onClick",
function (_)
self.rclNPCs:sort();
end, obj);
obj._e_event5 = obj.rclNPCs:addEventListener("onCompare",
function (_, nodeA, nodeB)
local mod1 = nodeA.relacao;
local mod2 = nodeB.relacao;
local modR = utils.compareStringPtBr(mod1, mod2);
if modR==0 then
mod1 = nodeA.nome;
mod2 = nodeB.nome;
modR = utils.compareStringPtBr(mod1, mod2);
end;
return modR;
end, obj);
function obj:_releaseEvents()
__o_rrpgObjs.removeEventListenerById(self._e_event5);
__o_rrpgObjs.removeEventListenerById(self._e_event4);
__o_rrpgObjs.removeEventListenerById(self._e_event3);
__o_rrpgObjs.removeEventListenerById(self._e_event2);
__o_rrpgObjs.removeEventListenerById(self._e_event1);
__o_rrpgObjs.removeEventListenerById(self._e_event0);
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end;
if self.button3 ~= nil then self.button3:destroy(); self.button3 = nil; end;
if self.boxNPCs ~= nil then self.boxNPCs:destroy(); self.boxNPCs = nil; end;
if self.rclListaNPCs ~= nil then self.rclListaNPCs:destroy(); self.rclListaNPCs = nil; end;
if self.scrollBox1 ~= nil then self.scrollBox1:destroy(); self.scrollBox1 = nil; end;
if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end;
if self.label1 ~= nil then self.label1:destroy(); self.label1 = nil; end;
if self.button2 ~= nil then self.button2:destroy(); self.button2 = nil; end;
if self.rclNPCs ~= nil then self.rclNPCs:destroy(); self.rclNPCs = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
return obj;
end;
function newfrmGerenciadorNPCs()
local retObj = nil;
__o_rrpgObjs.beginObjectsLoading();
__o_Utils.tryFinally(
function()
retObj = constructNew_frmGerenciadorNPCs();
end,
function()
__o_rrpgObjs.endObjectsLoading();
end);
assert(retObj ~= nil);
return retObj;
end;
local _frmGerenciadorNPCs = {
newEditor = newfrmGerenciadorNPCs,
new = newfrmGerenciadorNPCs,
name = "frmGerenciadorNPCs",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "",
description=""};
frmGerenciadorNPCs = _frmGerenciadorNPCs;
Firecast.registrarForm(_frmGerenciadorNPCs);
return _frmGerenciadorNPCs;
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.