content
stringlengths 5
1.05M
|
---|
local awful = require('awful')
local wibox = require('wibox')
local gears = require('gears')
local clickable_container = require('widget.action-center.clickable-container')
local dpi = require('beautiful').xresources.apply_dpi
local watch = require('awful.widget.watch')
local mat_list_item = require('widget.material.list-item')
local HOME = os.getenv('HOME')
local PATH_TO_ICONS = HOME .. '/.config/awesome/widget/action-center/icons/'
local action_status = false
-- Imagebox
local button_widget =
wibox.widget {
{
id = 'icon',
image = PATH_TO_ICONS .. 'toggled-off' .. '.svg',
widget = wibox.widget.imagebox,
resize = true
},
layout = wibox.layout.align.horizontal
}
-- Update imagebox
local update_imagebox = function()
if action_status then
button_widget.icon:set_image(PATH_TO_ICONS .. 'toggled-on' .. '.svg')
else
button_widget.icon:set_image(PATH_TO_ICONS .. 'toggled-off' .. '.svg')
end
end
-- Check status
local check_action_status = function()
awful.spawn.easy_async_with_shell('rfkill list bluetooth', function(stdout)
if stdout:match('Soft blocked: yes') ~= nil then
action_status = false
else
action_status = true
end
-- Update imagebox
update_imagebox()
end)
end
-- Power on Commands
local power_on_cmd = [[
rfkill unblock bluetooth
echo 'power on' | bluetoothctl
notify-send 'Initializing bluetooth Service...'
]]
-- Power off Commands
local power_off_cmd = [[
echo 'power off' | bluetoothctl
rfkill block bluetooth
notify-send 'Bluetooth device disabled'
]]
local toggle_action = function()
if action_status then
action_status = false
awful.spawn.easy_async_with_shell(power_off_cmd, function(stdout) end, false)
else
action_status = true
awful.spawn.easy_async_with_shell(power_on_cmd, function(stdout) end, false)
end
-- Update imagebox
update_imagebox()
end
-- Button
local widget_button = clickable_container(wibox.container.margin(button_widget, dpi(7), dpi(7), dpi(7), dpi(7)))
widget_button:buttons(
gears.table.join(
awful.button(
{},
1,
nil,
function()
toggle_action()
end
)
)
)
-- Tootltip
awful.tooltip {
objects = {widget_button},
mode = 'outside',
align = 'right',
timer_function = function()
if action_status == true then
return 'Bluetooth Enabled'
else
return 'Bluetooth Disabled'
end
end,
preferred_positions = {'right', 'left', 'top', 'bottom'}
}
-- Status Checker
watch('rfkill list bluetooth', 5,
function(_, stdout)
if stdout:match('Soft blocked: yes') == nil then
action_status = true
button_widget.icon:set_image(PATH_TO_ICONS .. 'toggled-on' .. '.svg')
else
action_status = false
button_widget.icon:set_image(PATH_TO_ICONS .. 'toggled-off' .. '.svg')
end
collectgarbage('collect')
end)
-- Action Name
local action_name = wibox.widget {
text = 'Bluetooth Connection',
font = 'SF Pro Display 11',
align = 'left',
widget = wibox.widget.textbox
}
-- Heirarchy
local widget_content = wibox.widget {
{
action_name,
layout = wibox.layout.fixed.horizontal,
},
nil,
{
widget_button,
layout = wibox.layout.fixed.horizontal,
},
layout = wibox.layout.align.horizontal,
}
-- Wrapping
local action_widget = wibox.widget {
wibox.widget {
widget_content,
widget = mat_list_item
},
layout = wibox.layout.fixed.vertical
}
-- Update/Check status on startup
check_action_status()
-- Return widget
return action_widget
|
--===========================================================================--
-- --
-- System.Collections.IIndexedListSorter --
-- --
--===========================================================================--
--===========================================================================--
-- Author : [email protected] --
-- URL : http://github.com/kurapica/PLoop --
-- Create Date : 2016/02/04 --
-- Update Date : 2018/03/16 --
-- Version : 1.0.0 --
--===========================================================================--
PLoop(function(_ENV)
namespace "System.Collections"
export {
ceil = math.ceil,
floor = math.floor,
log = math.log,
random = math.random,
tinsert = table.insert,
tremove = table.remove,
tsort = table.sort,
pcall = pcall,
assert = assert,
}
local function formatParams(self, start, stop)
local count = self.Count or #self
if start < 0 then start = count + start + 1 end
if stop < 0 then stop = count + stop + 1 end
if start > stop then start, stop = stop, start end
if start < 1 then start = 1 end
if self[stop] == nil then stop = count end
return start, stop, count
end
-- For quick sort
local function partition(self, low, high, compare)
local rnd = low + random(high - low)
self[rnd], self[high] = self[high], self[rnd]
local i = low
local pivot = self[high]
for j = low, high - 1 do
if not compare(pivot, self[j]) then
self[i], self[j] = self[j], self[i]
i = i + 1
end
end
self[i], self[high] = self[high], self[i]
return i
end
local function quickSort(self, low, high, compare)
if low < high then
local p = partition(self, low, high, compare)
quickSort(self, low, p - 1, compare)
quickSort(self, p + 1, high, compare)
end
end
-- For heap sort
local function shiftDown(self, base, start, stop, compare)
local left = (start - base + 1) * 2 + base - 1
local right = left + 1
while left <= stop do
local root = start
if compare(self[root], self[left]) then root = left end
if right <= stop and compare(self[root], self[right]) then root = right end
if root == start then return end
self[start], self[root] = self[root], self[start]
start = root
left = (start - base + 1) * 2 + base - 1
right = left + 1
end
end
-- For merge sort
local function mergeResult(self, start, mid, stop, compare, cache)
-- Shrink the merge range
local right = mid + 1
local rval = self[right]
local lval = self[mid]
while start <= mid and not compare(rval, self[start]) do start = start + 1 end
while stop > mid and not compare(self[stop], lval) do stop = stop - 1 end
if start > mid or stop <= mid then return end
-- Merge
local MIN_GALLOP = 7
if mid - start <= stop - mid - 1 then
-- merge to left
local left = 1
for i = start, mid do cache[left] = self[i] left = left + 1 end
left = 1
local leftStop = mid - start + 1
local ok, err = pcall(
function ()
local lval = cache[left]
local rval = self[right]
local gallopMode = false
local leftWin = 0
local rightWin = 0
while left <= leftStop and right <= stop do
if gallopMode then
if compare(rval, lval) then
local k = 1
local pos = right + 2^k - 1
while pos <= stop and compare(self[pos], lval) do
k = k + 1
pos = right + 2^k - 1
end
pos = right + 2^(k - 1)
k = right
while right < pos do
self[start] = self[right]
start = start + 1
right = right + 1
end
while right <= stop do
rval = self[right]
if compare(rval, lval) then
self[start] = rval
start = start + 1
right = right + 1
else
break
end
end
if right - k + 1 < MIN_GALLOP then gallopMode = false end
self[start] = lval
start = start + 1
left = left + 1
lval = cache[left]
rval = self[right]
else
local k = 1
local pos = left + 2^k - 1
while pos <= leftStop and not compare(rval, cache[pos]) do
k = k + 1
pos = left + 2^k - 1
end
pos = left + 2^(k - 1)
k = left
while left < pos do
self[start] = cache[left]
start = start + 1
left = left + 1
end
while left <= leftStop do
lval = cache[left]
if not compare(rval, lval) then
self[start] = lval
start = start + 1
left = left + 1
else
break
end
end
if left - k + 1 < MIN_GALLOP then gallopMode = false end
self[start] = rval
start = start + 1
right = right + 1
lval = cache[left]
rval = self[right]
end
else
if compare(rval, lval) then
rightWin = rightWin + 1
leftWin = 0
self[start] = rval
start = start + 1
right = right + 1
rval = self[right]
else
leftWin = leftWin + 1
rightWin = 0
self[start] = lval
start = start + 1
left = left + 1
lval = cache[left]
end
if rightWin >= MIN_GALLOP or leftWin >= MIN_GALLOP then
gallopMode = true
leftWin = 0
rightWin = 0
end
end
end
end
)
for i = left, leftStop do
self[start] = cache[i]
start = start + 1
end
assert(ok, err)
else
-- merge to right
right = 1
for i = stop, mid + 1, -1 do cache[right] = self[i] right = right + 1 end
right = 1
local rightStop = stop - mid
local left = mid
local ok, err = pcall(
function ()
local lval = self[left]
local rval = cache[right]
local gallopMode = false
local leftWin = 0
local rightWin = 0
while left >= start and right <= rightStop do
if gallopMode then
if compare(rval, lval) then
local k = 1
local pos = left - (2^k - 1)
while pos >= start and compare(rval, self[pos]) do
k = k + 1
pos = left - (2^k - 1)
end
pos = left - 2^(k - 1)
k = left
while left > pos do
self[stop] = self[left]
stop = stop - 1
left = left - 1
end
while left >= start do
lval = self[left]
if compare(rval, lval) then
self[stop] = lval
stop = stop - 1
left = left - 1
else
break
end
end
if k - left + 1 < MIN_GALLOP then gallopMode = false end
self[stop] = rval
stop = stop - 1
right = right + 1
lval = self[left]
rval = cache[right]
else
local k = 1
local pos = right + 2^k - 1
while pos <= rightStop and not compare(cache[pos], lval) do
k = k + 1
pos = right + 2^k - 1
end
pos = right + 2^(k - 1)
while right < pos do
self[stop] = cache[right]
stop = stop - 1
right = right + 1
end
while right <= rightStop do
rval = cache[right]
if not compare(rval, lval) then
self[stop] = rval
stop = stop - 1
right = right + 1
else
break
end
end
if right - k + 1 < MIN_GALLOP then gallopMode = false end
self[stop] = lval
stop = stop - 1
left = left - 1
lval = self[left]
rval = cache[right]
end
else
if compare(rval, lval) then
leftWin = leftWin + 1
rightWin = 0
self[stop] = lval
stop = stop - 1
left = left - 1
lval = self[left]
else
rightWin = rightWin + 1
leftWin = 0
self[stop] = rval
stop = stop - 1
right = right + 1
rval = cache[right]
end
if rightWin >= MIN_GALLOP or leftWin >= MIN_GALLOP then
gallopMode = true
leftWin = 0
rightWin = 0
end
end
end
end
)
for i = right, rightStop do
self[stop] = cache[i]
stop = stop - 1
end
assert(ok, err)
end
end
local function mergeSort(self, start, stop, compare, cache, minRun)
if start < stop then
if stop - start + 1 <= minRun then return self:InsertionSort(compare, start, stop) end
local mid = floor((start + stop) / 2)
mergeSort(self, start, mid, compare, cache, minRun)
mergeSort(self, mid + 1, stop, compare, cache, minRun)
mergeResult(self, start, mid, stop, compare, cache)
end
end
-----------------------------------------------------------
-- extend method --
-----------------------------------------------------------
--- Reverse the indexed list
__Arguments__{ Integer/1, Integer/-1 }
function IIndexedList:Reverse(start, stop)
start, stop = formatParams(self, start, stop)
local i = start
local j = stop
while i < j do
self[i], self[j] = self[j], self[i]
i = i + 1
j = j - 1
end
return self
end
--- Apply insertion sort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:InsertionSort(compare, start, stop)
start, stop = formatParams(self, start, stop)
for i = start + 1, stop do
local j = i - 1
local val = self[i]
while j >= start and compare(val, self[j]) do
self[j + 1] = self[j]
j = j - 1
end
self[j + 1] = val
end
return self
end
--- Apply bubble sort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:BubbleSort(compare, start, stop)
start, stop = formatParams(self, start, stop)
local swaped = true
local i, j
while stop > start and swaped do
swaped = false
i = start
j = stop
while i < stop do
if compare(self[i+1], self[i]) then
self[i], self[i+1] = self[i+1], self[i]
swaped = true
end
if compare(self[j], self[j - 1]) then
self[j], self[j - 1] = self[j - 1], self[j]
swaped = true
end
j = j - 1
i = i + 1
end
-- Reduce the Check range
start = start + 1
stop = stop - 1
end
return self
end
--- Apply selection sort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:SelectionSort(compare, start, stop)
start, stop = formatParams(self, start, stop)
for i = start, stop - 1 do
local min = i
for j = i + 1, stop do
if compare(self[j], self[min]) then min = j end
end
self[i], self[min] = self[min], self[i]
end
return self
end
--- Apply comb sort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:CombSort(compare, start, stop)
start, stop = formatParams(self, start, stop)
local gap = stop - start + 1
local shrink = 1.3
local swaped = true
repeat
gap = floor(gap / shrink)
if gap < 1 then gap = 1 end
local i = start
local j = i + gap
swaped = false
while j <= stop do
if compare(self[j], self[i]) then
self[j], self[i] = self[i], self[j]
swaped = true
end
i = i + 1
j = j + 1
end
until gap == 1 and not swaped
return self
end
--- Apply merge sort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:MergeSort(compare, start, stop)
start, stop = formatParams(self, start, stop)
local count = stop - start + 1
local minRun = ceil(count / 2^(floor( log(count) / log(2) ) - 5))
mergeSort(self, start, stop, compare, {}, minRun)
return self
end
--- Apply quick sort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:QuickSort(compare, start, stop)
start, stop = formatParams(self, start, stop)
quickSort(self, start, stop, compare)
return self
end
--- Apply heap sort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:HeapSort(compare, start, stop)
start, stop = formatParams(self, start, stop)
for n = floor((stop - start + 1) / 2), 1, -1 do
shiftDown(self, start, start - 1 + n, stop, compare)
end
for n = stop, start + 1, -1 do
self[n], self[start] = self[start], self[n]
shiftDown(self, start, start, n - 1, compare)
end
return self
end
--- Apply timsort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:TimSort(compare, start, stop)
start, stop = formatParams(self, start, stop)
local count = stop - start + 1
if count == 0 then return end
-- Calc minrun
local minRun = ceil(count / 2^(floor( log(count) / log(2) ) - 5))
-- Use insertion sort on less element list
if count <= minRun then return self:InsertionSort(compare, start, stop) end
-- Run stack
local runStack = {}
local runLenStack = {}
local stackHeight = 0
local mergeTemp = {}
-- Scan the list
local i = start + 1
local ascending = nil
local descending = nil
local val = self[start]
local mergeStack
local validateStack = function()
if stackHeight >= 3 and runLenStack[stackHeight - 2] <= runLenStack[stackHeight - 1] + runLenStack[stackHeight] then
if runLenStack[stackHeight - 2] < runLenStack[stackHeight] then
return mergeStack(stackHeight - 2, stackHeight - 1)
else
return mergeStack(stackHeight - 1, stackHeight)
end
end
if stackHeight >= 2 and runLenStack[stackHeight - 1] <= runLenStack[stackHeight] then
return mergeStack(stackHeight - 1, stackHeight)
end
end
mergeStack = function(i, j)
mergeResult(self, runStack[i], runStack[j] - 1, runStack[j] + runLenStack[j] - 1, compare, mergeTemp)
runLenStack[i] = runLenStack[i] + runLenStack[j]
tremove(runStack, j)
tremove(runLenStack, j)
stackHeight = stackHeight - 1
return validateStack()
end
local pushStack = function (runStart, runEnd, desc)
if runEnd - runStart + 1 < minRun and runEnd < stop then
runEnd = runStart + minRun - 1
if runEnd > stop then runEnd = stop end
desc = true
end
if desc then self:InsertionSort(compare, runStart, runEnd) end
tinsert(runStack, runStart)
tinsert(runLenStack, runEnd - runStart + 1)
stackHeight = stackHeight + 1
validateStack()
return runEnd + 1
end
while i <= stop do
if compare(self[i], val) then
if ascending then
i = pushStack(ascending, i - 1)
ascending = nil
elseif not descending then
descending = i - 1
end
else
if descending then
i = pushStack(descending, i - 1, true)
descending = nil
elseif not ascending then
ascending = i - 1
end
end
val = self[i]
i = i + 1
end
if ascending then pushStack(ascending, stop)
elseif descending then pushStack(descending, stop, true)
elseif runStack[stackHeight] + runLenStack[stackHeight] - 1 < stop then pushStack(stop, stop) end
while stackHeight > 1 do mergeStack(stackHeight - 1, stackHeight) end
return self
end
--- Apply default sort on the indexed list
__Arguments__{ Callable/"x,y=>x<y", Integer/1, Integer/-1 }
function IIndexedList:Sort(func, start, stop)
if start == 1 and (stop == -1 or stop == self.Count) then tsort(self, func) return self end
return self:TimSort(func, start, stop)
end
end)
|
--
-- @copyright (c) 2015 Upstart Illustration LLC. All rights reserved.
--
require("ad.Constants")
local NetworkModule = require("ad.AdNetworkModule")
local iAdNetwork = Class(NetworkModule)
function iAdNetwork.new(self, init)
function self.getName()
return "iAd"
end
function self.getAdNetwork()
return AdNetwork.iAd
end
function self.getConfig()
return {}
end
end
return iAdNetwork
|
color(6)
local JSON = require("Libraries.JSON")
local function log(...)
local t = table.concat({...}," ")
cprint(...)
print(t)
flip()
end
log("Reading files list..")
local docs = fs.getDirectoryItems("D:/DOCS/")
local dnames = {}
log("Reading files...")
for id,name in ipairs(docs) do
docs[id] = fs.read("D:/DOCS/"..name)
dnames[id] = name
end
log("Decoding...")
color(5)
for id, jdata in ipairs(docs) do
log(dnames[id])
docs[id] = JSON:decode(jdata)
end
color(6)
color(12)
log("DONE")
|
plyr = game.Players.yfc
local mode = 0
dist = 25
me = Workspace.yfc.Head
script.Parent = me.Parent
local part = Instance.new("Part")
part.Parent = me
part.BrickColor = BrickColor.new("Bright blue")
part.Transparency = 0.5
part.Anchored = false
part.CanCollide = false
part.Size = Vector3.new(1, 1, 1)
part:BreakJoints()
local mesh = Instance.new("SpecialMesh")
mesh.Parent = part
mesh.MeshType = "Sphere"
mesh.Scale = Vector3.new(dist*2, dist*2, dist*2)
local weld = Instance.new("Weld")
weld.Parent = part
weld.Part0 = part
weld.Part1 = me
function cmds(msg)
if msg == "mode:sit" then
mode = 1
part.BrickColor = BrickColor.new("Bright neon")
end
if msg == "mode:kill" then
part.BrickColor = BrickColor.new("Bright red")
mode = 0
end
if msg == "mode:fly" then
mode = 2
part.BrickColor = BrickColor.new("Bright yellow")
end
if msg == "mode:jump" then
mode = 3
part.BrickColor = BrickColor.new("Bright green")
end
if msg == "mode:kick" then
mode = 4
part.BrickColor = BrickColor.new("New Yeller")
end
if string.sub(msg, 1, 4) == "mag:" then
said = string.lower(string.sub(msg, 5))
dist = said
mesh.Scale = Vector3.new(dist*2, dist*2, dist*2)
end
end
while true do
plyr.Chatted:connect(cmds)
for _, v in pairs(game.Players:GetChildren()) do
if not v.Character then return end
if (v.Character.Torso.Position - me.Position).magnitude < dist then
if v.Name ~= me.Parent.Name then
if mode == 0 then
v.Character:BreakJoints()
end
if mode == 1 then
v.Character.Humanoid.Sit = true
end
if mode == 2 then
v.Character.Torso.CFrame = v.Character.Torso.CFrame + Vector3.new(0, 500, 0)
end
if mode == 3 then
v.Character.Humanoid.Jump = true
end
if mode == 4 then
for i = 0, 1, 0.1 do
v.Character.Torso.CFrame = v.Character.Torso.CFrame + Vector3.new(math.rad(860*i), 0, 0)
wait()
end
end
end
end
end
wait(0.3)
end --lego
|
local Map = require "maps.map"
local EHouse = Map:new()
function EHouse:new(o, control)
o = o or Map:new(o, control)
setmetatable(o, self)
self.__index = self
return o
end
function EHouse:create()
Map.create(self)
end
function EHouse:enter()
Map.enter(self)
end
function EHouse:exit()
Map.exit(self)
end
function EHouse:diary(event, x, y, character_name, object_name)
Map.diary(self, event, x, y, character_name, object_name)
if character_name == 'player' and event == 'interact' then
self.control.data.read_stash_diary = true
end
end
return EHouse
|
--- -----------------------------------------------------------------------------
--- __
--- /\ \
--- \ \ \____ ___ _ __ __
--- \ \ '__`\ / __`\ /\`'__\ /'__`\
--- \ \ \L\ \/\ \L\ \\ \ \/ /\ __/
--- \ \_,__/\ \____/ \ \_\ \ \____\
--- \/___/ \/___/ \/_/ \/____/
---
--- -----------------------------------------------------------------------------
local help=[[
bore == best or rest
(c) 2022, Tim Menzies, BSD 2-clause license.
USAGE:
lua bore.lua [OPTIONS]
OPTIONS:
-Dump stack dump on error = false
-Format S format string = %5.2f
-best F best space = .15
-cohen F Cohen's delta = .35
-data N data file = etc/data/auto93.csv
-furthest F far = .9
-help show help = false
-seed I random seed = 10019
-todo S start-up action = nothing
]]
--- -----------------------------------------------------------------------------
--- __ _ _
--- / _| _ _ _ __ ___ | |_ (_) ___ _ __ ___
--- | |_ | | | || '_ \ / __|| __|| | / _ \ | '_ \ / __|
--- | _|| |_| || | | || (__ | |_ | || (_) || | | |\__ \
--- |_| \__,_||_| |_| \___| \__||_| \___/ |_| |_||___/
---
local b4={}; for k,_ in pairs(_ENV) do b4[k]=k end
local big = 1E32
local tiny = 1E-32
local the = {}
local function atom(x)
if type(x)~="string" then return x end
x = x:match"^%s*(.-)%s*$"
if x=="true" then return true elseif x=="false" then return false end
return tonumber(x) or x end
local function atoms(x, t)
t={}; for y in x:gmatch(sep or"([^,]+)") do t[1+#t]=atom(y) end; return t end
local function cli(txt, t)
t={}
txt:gsub("\n [-]([^%s]+)[^\n]*%s([^%s]+)",function(key,x)
for n,flag in ipairs(arg) do
if flag:sub(1,1)=="-" and key:find("^"..flag:sub(2)..".*") then
x = x=="false" and true or x=="true" and "false" or arg[n+1] end end
t[key] = atom(x) end)
return t end
local fmt = string.format
local function sort(t,f) table.sort(t,f); return t end
local function slots(t, u)
u={}; for k,v in pairs(t) do l=tostring(k); if l:sub(1,1)~="_" then u[1+#u]=k end end;
return sort(u) end
local function main(the, help, demos)
if the.help then print(help) else
for _,todo in pairs(the.todo=="all" and slots(demos) or {the.todo}) do
math.randomseed(the.seed)
if type(demos[todo])=="function" then demos[todo]() end end end
os.exit(demos.fails) end
local function map(t,f, u)
u={};for k,v in pairs(t) do u[1+#u]=f(v) end; return u end
local function tablep(t) return type(t)=="table" end
local function o(t, seen)
seen = seen or {}
if not tablep(t) then return tostring(t) end
if seen[t] then return "..." end
seen[t]=t
local key=function(k) return fmt(":%s %s",k,o(t[k],seen)) end
local u= #t>0 and map(t,function(x) return o(x,seen) end) or map(slots(t),key)
return '{'..table.concat(u," ").."}" end
local function oo(t) print(o(t)) end
local function rows(file, x,prep)
file = io.input(file)
return function()
x=io.read(); if x then return atoms(x) else io.close(file) end end end
local function sum(t,f, n)
n=0; for _,v in pairs(t) do n=n+f(v) end; return n end
local function tree(t, seen, pre, txt, v)
pre, seen = pre or "", seen or {}
if not tablep(t) then return print(fmt("%s%s",pre,t)) end
if seen[t] then return print(fmt("%s...",pre)) end
seen[t]=t
for _,k in pairs(slots(t)) do
v= t[k]
if tablep(v)
then print(fmt("%s%s", pre,k)); tree(v,seen,pre .. " ")
else print(fmt("%s%s = %s",pre,k,v)) end end end
--- -----------------------------------------------------------------------------
--- _
--- ___ | | __ _ ___ ___ ___ ___
--- / __|| | / _` |/ __|/ __| / _ \/ __|
--- | (__ | || (_| |\__ \\__ \| __/\__ \
--- \___||_| \__,_||___/|___/ \___||___/
local as=setmetatable
local function obj( t)
t={__tostring=o}; t.__index=t
return as(t, {__call=function(_,...) return t.new(_,...) end}) end
--- ____ ____ _
--- | | | |
--- |___ |__| |___
local function col(at,txt, i)
i = {n=0, at=at or 0, txt=txt or "", has={}}
i.w = i.txt:find"-$" and -1 or 1
return i end
local function add(self,x,inc)
if x~="?" then
inc = inc or 1
self.n = self.n + inc
self:add(x,inc) end
return self end
--- _ _ _ _ _ _
--- |\ | | | |\/|
--- | \| |__| | |
local Num=obj{}
function Num:new(at,x, new)
new = as(col(at,x),Num)
new.mu, new.m2, new.lo, new.hi = 0, 0, big, -big
return new end
function Num:add(x,_, d)
d = x - self.mu
self.mu = self.mu + d/self.n
self.m2 = self.m2 + d*(x - self.mu)
self.sd = (self.n<2 or self.m2<0) and 0 or (self.m2/(self.n-1))^.5
if x > self.hi then self.hi = x end
if x < self.lo then self.lo = x end end
function Num:norm(x)
return self.hi-self.lo<tiny and 0 or (x-self.lo)/(self.hi-self.lo) end
function Num:heaven(x, heaven)
return ((self.w>0 and 1 or 0) - self:norm(x))^the.p end
--- ____ _ _ _ _
--- [__ \_/ |\/|
--- ___] | | |
local Sym=obj{}
function Sym:new(at,x,inc, new)
new=as(col(at,x),Sym); new.most=0; return new end
function Sym:add(x,inc)
self.has[x] = inc + (self.has[x] or 0)
if self.has[x] > self.most then self.most,self.mode=self.has[x],x end end
function Sym:div()
local function plogp(n, p) p=n/self.n; return p*math.log(p,2) end
return -sum(self.has, plogp) end
--- ____ _ _ _ ___
--- [__ |_/ | |__]
--- ___] | \_ | |
local Skip=obj{}
function Skip:new(at,x) return as(col(at,x),Skip) end
function Skip:add(x,inc) return x end
--- ____ ____ _ ____
--- | | | | [__
--- |___ |__| |___ ___]
local Cols=obj{}
function Cols:new(headers, self,col,here)
self = as({all={}, x={}, y={}}, Cols)
for at,x in pairs(headers) do
if x:find":$" then self.all[at] = Skip(at,x) else
col = (x:find"^[A-Z]" and Num or Sym)(at,x)
self.all[at] = col
here = x:find"[+-]$" and self.y or self.x
here[1+#here] = col end end
return self end
function Cols:add(t)
for _,col in pairs(self.all) do col:add(t[col.at]) end
return t end
function Cols:clone(rows, new)
new = new or Cols(map(self.cols.all, function(x) return x.txt end))
for _,row in pairs(rows or {}) do new:add(row) end
return {rows=rows,cols=new} end
--- ___ ____ ___ ____
--- | \ |__| | |__|
--- |__/ | | | | |
local Data=obj{}
function Data:new(inits, new)
new = as({rows={},heavens=Num()},Data)
if type(inits)=="string" then for row in csv(inits) do new:add(row) end end
if type(inits)=="table" then for _,row in pairs(inits) do new:add(row) end end
return new end
function Data:add(t, n)
if self.cols then self:addData(t) else
self.cols = Cols(t)
self.best = self.cols:clone()
self.rest = self.cols:clone() end end
function Data:addData(t, n)
self.rows[1+#self.rows] = self.cols:add(t)
n = self.heavens.norm( self.heavens.add(self.heaven(t)))
(n>=the.best and self.best or self.rest):add(t) end
function Data:heaven(t)
heaven = function(col) return col:heaven(t[col.at]) end
return (sum(self.cols.y,heaven)/#self.cols.y)^(1/the.p) end
--- -----------------------------------------------------------------------------
--- _
--- __| | ___ _ __ ___ ___ ___
--- / _` | / _ \| '_ ` _ \ / _ \ / __|
--- | (_| || __/| | | | | || (_) |\__ \
--- \__,_| \___||_| |_| |_| \___/ |___/
---
local Demos = {fails=0}
local function asserts(test, msg)
print(test and "PASS: "or "FAIL: ",msg or "")
if not test then
Demos.fails = Demos.fails+1
if the.Dump then assert(test,msg) end end end
function Demos.the() oo(the) end
function Demos.col() oo(col(10,"Mpg-")) end
function Demos.num( n) n=Num();
for x=1,1000 do add(n,x) end; print(n) end
function Demos.sym( s)
s=Sym(); for _,x in pairs{1,1,1,1,2,2,3} do add(s,x) end
asserts(s:div() - 1.376 < 0.005, "entropy") end
function Demos.cols( c)
print(Cols({"Clndrs", "Weight", "Hp:", "Lbs-",
"Acc+", "Model", "origin", "Mpg+"}))
end
the = cli(help)
main(the, help, Demos)
|
-- Чертов файл должен быть шаредным, так как шаред грузится до SERVER
-- А если грузиться поздно, то скрипты, зависимые от ggram, эррорят
if CLIENT then return end
local function loadBots(path, iDeep)
iDeep = iDeep or 0
local files,dirs = file.Find(path .. "/*","LUA")
for _,f in ipairs(files) do
if f == "_init.lua" then
print("GG загрузка бота " .. path)
include(path .. "/" .. f)
break
end
end
for _,d in ipairs(iDeep > 0 and dirs or {}) do
loadBots(path .. "/" .. d, iDeep - 1)
end
end
local function loadExtensions(path)
local files = file.Find(path .. "/*","LUA")
for _,f in ipairs(files) do
local fpath = path .. "/" .. f
print("GG загрузка " .. fpath)
include(fpath)
end
end
include("ggram/core.lua")
loadExtensions("ggram/extensions")
loadBots("ggram/bots", 1)
|
dofile( "./wago.lua" )
local JSON = (loadfile "./json.lua")()
function table.show(t, name, indent)
local cart -- a container
local autoref -- for self references
--[[ counts the number of elements in a table
local function tablecount(t)
local n = 0
for _, _ in pairs(t) do n = n+1 end
return n
end
]]
-- (RiciLake) returns true if the table is empty
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "__AURA__"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
--[[
Author: Julio Manuel Fernandez-Diaz
Date: January 12, 2007
(For Lua 5.1)
Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount()
Formats tables with cycles recursively to any depth.
The output is returned as a string.
References to other tables are shown as values.
Self references are indicated.
The string returned is "Lua code", which can be procesed
(in the case in which indent is composed by spaces or "--").
Userdata and function keys and values are shown as strings,
which logically are exactly not equivalent to the original code.
This routine can serve for pretty formating tables with
proper indentations, apart from printing them:
print(table.show(t, "t")) -- a typical use
Heavily based on "Saving tables with cycles", PIL2, p. 113.
Arguments:
t is the table.
name is the name of the table (optional)
indent is a first indentation (optional).
--]]
function table.show(t, name, indent)
local cart -- a container
local autoref -- for self references
--[[ counts the number of elements in a table
local function tablecount(t)
local n = 0
for _, _ in pairs(t) do n = n+1 end
return n
end
]]
-- (RiciLake) returns true if the table is empty
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "lua_table"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
local t = StringToTable(arg[1], false)
print(table.show(t))
|
--- 模块功能:UI窗口管理
-- @module uiWin
-- @author openLuat
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.25
module(...,package.seeall)
--窗口管理栈
local stack = {}
--当前分配的窗口ID
local winid = 0
local function allocid()
winid = winid + 1
return winid
end
local function loseFocus()
if stack[#stack] and stack[#stack]["onLoseFocus"] then
stack[#stack]["onLoseFocus"]()
end
end
--- 新增一个窗口
-- @table wnd,窗口的元素以及消息处理函数表
-- @return number,窗口ID
-- @usage uiWin.add({onUpdate = refresh})
function add(wnd)
---必须注册更新接口
assert(wnd.onUpdate)
if type(wnd) ~= "table" then
assert("unknown uiwin type "..type(wnd))
end
--上一个窗口执行失去焦点的处理函数
loseFocus()
--为新窗口分配窗口ID
wnd.id = allocid()
--新窗口请求入栈
sys.publish("UIWND_ADD",wnd)
return wnd.id
end
--- 移除一个窗口
-- @number winId,窗口ID
-- @return nil
-- @usage uiWin.remove(winId)
function remove(winId)
sys.publish("UIWND_REMOVE",winId)
end
function removeAll()
sys.publish("UIWND_REMOVEALL")
end
function update()
sys.publish("UIWND_UPDATE")
end
local function onAdd(wnd)
table.insert(stack,wnd)
stack[#stack].onUpdate()
end
local function onRemove(winid)
local istop,k,v
for k,v in ipairs(stack) do
if v.id == winid then
istop = (k==#stack)
table.remove(stack,k)
if #stack~=0 and istop then
stack[#stack].onUpdate()
end
return
end
end
end
local function onRemoveAll()
local k,v
for k,v in ipairs(stack) do
table.remove(stack,k)
end
end
local function onUpdate()
if stack[#stack] and stack[#stack].onUpdate then
stack[#stack].onUpdate()
end
end
--key:自定义功能键
--value:自定义功能键的状态
local function onKey(key,value)
if stack[#stack] and stack[#stack].onKey then
stack[#stack].onKey(key,value)
end
end
--- 判断一个窗口是否处于最前显示
-- @number winId,窗口ID
-- @return bool,true表示最前显示,其余表示非最前显示
-- @usage uiWin.isActive(winId)
function isActive(winId)
if stack[#stack] and stack[#stack].id then
return stack[#stack].id==winId
end
end
sys.subscribe("UIWND_ADD",onAdd)
sys.subscribe("UIWND_REMOVE",onRemove)
sys.subscribe("UIWND_REMOVEALL",onRemoveAll)
sys.subscribe("UIWND_UPDATE",onUpdate)
sys.subscribe("UIWND_TOUCH",onTouch)
sys.subscribe("UIWND_KEY",onKey)
|
--[[
RobloxPlayerScript - This script loads the CameraScript and ControlScript modules
2018 PlayerScripts Update - AllYourBlox
--]]
local CameraScript = require(script:WaitForChild("CameraScript"))
local ControlScript = require(script:WaitForChild("ControlScript"))
|
local events = require "kong.core.events"
-- if message_t.collection == "oauth2_credentials" then
return {
[events.TYPES.ENTITY_UPDATED] = function(message_t)
ngx.log(ngx.ERR, "updated")
end,
[events.TYPES.ENTITY_DELETED] = function(message_t)
ngx.log(ngx.ERR, "deleted")
end,
[events.TYPES.ENTITY_CREATED] = function(message_t)
ngx.log(ngx.ERR, "created")
end,
[events.TYPES["MEMBER-JOIN"]] = function(message_t)
ngx.log(ngx.ERR, "JOIN")
end,
[events.TYPES["MEMBER-LEAVE"]] = function(message_t)
ngx.log(ngx.ERR, "LEAVE")
end,
[events.TYPES["MEMBER-FAILED"]] = function(message_t)
ngx.log(ngx.ERR, "FAILED")
end,
[events.TYPES["MEMBER-UPDATE"]] = function(message_t)
ngx.log(ngx.ERR, "UPDATE")
end,
[events.TYPES["MEMBER-REAP"]] = function(message_t)
ngx.log(ngx.ERR, "REAP")
end
}
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
function get_agent(g, a)
if torch.type(g) == 'CombatGame' then
local c = 0
for i = 1, g.nagents do
if (not g.agents[i].team) or g.agents[i].team == 'team1' then
c = c + 1
if c == a then
return g.agents[i]
end
end
end
error('can not find agent ' .. a)
else
return g.agents[a]
end
end
function set_current_agent(g, a)
g.agent = get_agent(g, a)
end
function merge_stat(stat, s)
for k, v in pairs(s) do
if type(v) == 'number' then
stat[k] = (stat[k] or 0) + v
elseif type(v) == 'table' then
if v.op == 'join' then
if stat[k] then
local sz = stat[k].data:size()
sz[1] = sz[1] + v.data:size(1)
stat[k].data:resize(sz)
stat[k].data:narrow(1, sz[1]-v.data:size(1)+1, v.data:size(1)):copy(v.data)
else
stat[k] = {data = v.data:clone()}
end
end
else
-- it must be tensor
if stat[k] then
stat[k]:add(v)
else
stat[k] = v:clone()
end
end
end
end
function sample_multinomial(p)
-- for some reason multinomial fails sometimes
local s, sample = pcall(
function()
return torch.multinomial(p, 1)
end)
if s == false then
sample = torch.multinomial(torch.ones(p:size()),1)
end
return sample
end
function tensor_to_words(input, show_prob)
for i = 1, input:size(1) do
local line = i .. ':'
for j = 1, input:size(2) do
line = line .. '\t' .. g_ivocab[input[i][j]]
end
if show_prob then
for h = 1, g_opts.nhop do
line = line .. '\t' .. string.format('%.2f', g_modules[h]['prob'].output[1][i])
end
end
print(line)
end
end
function format_stat(stat)
local a = {}
for n in pairs(stat) do table.insert(a, n) end
table.sort(a)
local str = ''
for i,n in ipairs(a) do
if string.find(n,'count_') then
str = str .. n .. ': ' .. string.format("%2.4g",stat[n]) .. ' '
end
end
str = str .. '\n'
for i,n in ipairs(a) do
if string.find(n,'reward_') then
str = str .. n .. ': ' .. string.format("%2.4g",stat[n]) .. ' '
end
end
str = str .. '\n'
for i,n in ipairs(a) do
if string.find(n,'success_') then
str = str .. n .. ': ' .. string.format("%2.4g",stat[n]) .. ' '
end
end
str = str .. '\n'
str = str .. 'bl_cost: ' .. string.format("%2.4g",stat['bl_cost']) .. ' '
str = str .. 'reward: ' .. string.format("%2.4g",stat['reward']) .. ' '
str = str .. 'success: ' .. string.format("%2.4g",stat['success']) .. ' '
str = str .. 'active: ' .. string.format("%2.4g",stat['step_active']) .. ' '
str = str .. 'epoch: ' .. stat['epoch']
return str
end
function print_tensor(a)
local str = ''
for s = 1, a:size(1) do str = str .. string.format("%2.4g",a[s]) .. ' ' end
return str
end
function format_helpers(gname)
local str = ''
if not gname then
for i,j in pairs(g_factory.helpers) do
str = str .. i .. ' :: '
str = str .. 'mapW: ' .. print_tensor(j.mapW) .. ' ||| '
str = str .. 'mapH: ' .. print_tensor(j.mapH) .. ' ||| '
str = str .. 'wpct: ' .. print_tensor(j.waterpct) .. ' ||| '
str = str .. 'bpct: ' .. print_tensor(j.blockspct) .. ' ||| '
str = str .. '\n'
end
else
local j = g_factory.helpers[gname]
str = str .. gname .. ' :: '
str = str .. 'mapW: ' .. print_tensor(j.mapW) .. ' ||| '
str = str .. 'mapH: ' .. print_tensor(j.mapH) .. ' ||| '
str = str .. 'wpct: ' .. print_tensor(j.waterpct) .. ' ||| '
str = str .. 'bpct: ' .. print_tensor(j.blockspct) .. ' ||| '
str = str .. '\n'
end
return str
end
function g_load_model()
if g_opts.load ~= '' then
if paths.filep(g_opts.load) == false then
print('WARNING: Failed to load from ' .. g_opts.load)
return
end
local f = torch.load(g_opts.load)
g_paramx:copy(f.paramx)
g_log = f.log
g_plot_stat = {}
for i = 1, #g_log do
g_plot_stat[i] = {g_log[i].epoch, g_log[i].reward, g_log[i].success, g_log[i].bl_cost}
end
if f['optim_state'] then g_optim_state = f['optim_state'] end
print('model loaded from ', g_opts.load)
end
end
function g_save_model()
if g_opts.save ~= '' then
f = {opts=g_opts, paramx=g_paramx, log=g_log}
if g_optim_state then f['optim_state'] = g_optim_state end
torch.save(g_opts.save, f)
print('model saved to ', g_opts.save)
end
end
function plot_reward()
local x = torch.zeros(#g_log)
for i = 1, #g_log do
x[i] = g_log[i].reward
end
gnuplot.plot(x)
end
|
Speedrun = Speedrun or { }
local Speedrun = Speedrun
-------------------
---- Raid List ----
-------------------
Speedrun.raidList = {
[638] = {
name = "AA",
id = 638,
timerSteps = {},
},
[636] = {
name = "HRC",
id = 636,
timerSteps = {},
},
[639] = {
name = "SO",
id = 639,
timerSteps = {},
},
[725] = {
name = "MoL",
id = 725,
timerSteps = {},
},
[975] = {
name = "HoF",
id = 975,
timerSteps = {},
},
[1000] = {
name = "AS",
id = 1000,
timerSteps = {},
},
[1051] = {
name = "CR",
id = 1051,
timerSteps = {},
},
[1121] = {
name = "SS",
id = 1121,
timerSteps = {},
},
[1196] = {
name = "KA",
id = 1196,
timerSteps = {},
},
[1082] = {
name = "BRP",
id = 1082,
timerSteps = {},
},
[677] = {
name = "MA",
id = 677,
timerSteps = {},
},
[635] = {
name = "DSA",
id = 635,
timerSteps = {},
},
[1227] = {
name = "VH",
id = 1227,
timerSteps = {},
},
}
-- Speedrun.arenaList = {
-- [677] = {
-- name = "MA",
-- id = 677,
-- timerSteps = {},
-- },
-- [1227] = {
-- name = "VH",
-- id = 1227,
-- timerSteps = {},
-- },
-- }
-----------------------
---- Custom Timers ----
-----------------------
Speedrun.customTimerSteps = {
[638] = { --AA
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = "",
[7] = "",
[8] = ""
},
[636] = { --HRC
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = ""
},
[639] = { --SO
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = "",
[7] = "",
[8] = ""
},
[725] = { --MoL
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = ""
},
[975] = { --HoF
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = "",
[7] = "",
[8] = "",
[9] = "",
[10] = ""
},
[1000] = { --AS
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = ""
},
[1051] = { --CR
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = ""
},
[1121] = { --SS
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = ""
},
[1196] = { --KA
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = ""
},
[1082] = { --BRP
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = "",
[7] = "",
[8] = "",
[9] = "",
[10] = "",
[11] = "",
[12] = "",
[13] = "",
[14] = "",
[15] = "",
[16] = "",
[17] = "",
[18] = "",
[19] = "",
[20] = "",
[21] = "",
[22] = "",
[23] = "",
[24] = "",
[25] = ""
},
[677] = { --MA
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = "",
[7] = "",
[8] = "",
[9] = ""
},
[635] = { --DSA
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = "",
[7] = "",
[8] = "",
[9] = "",
[10] = ""
},
[1227] = { --Vateshran Hollows
[1] = "",
[2] = "",
[3] = "",
[4] = "",
[5] = "",
[6] = "",
[7] = ""
},
}
-- Speedrun.customArenaSteps = {
-- [677] = { --MA
-- [1] = "",
-- [2] = "",
-- [3] = "",
-- [4] = "",
-- [5] = "",
-- [6] = "",
-- [7] = "",
-- [8] = "",
-- [9] = ""
-- },
-- [1227] = { --Vateshran Hollows
-- [1] = "",
-- [2] = "",
-- [3] = "",
-- [4] = "",
-- [5] = "",
-- [6] = "",
-- [7] = ""
-- },
-- }
-------------------
---- Step List ----
-------------------
Speedrun.stepList = {
[638] = { --AA
[1] = zo_strformat(SI_SPEEDRUN_AA_BEGIN_LIGHTNING),
[2] = zo_strformat(SI_SPEEDRUN_AA_FINISH_LIGHTNING),
[3] = zo_strformat(SI_SPEEDRUN_AA_BEGIN_STONE),
[4] = zo_strformat(SI_SPEEDRUN_AA_FINISH_STONE),
[5] = zo_strformat(SI_SPEEDRUN_AA_BEGIN_VARLARIEL),
[6] = zo_strformat(SI_SPEEDRUN_AA_FINISH_VARLARIEL),
[7] = zo_strformat(SI_SPEEDRUN_AA_BEGIN_MAGE),
[8] = zo_strformat(SI_SPEEDRUN_AA_FINISH_MAGE),
},
[636] = { --HRC
[1] = zo_strformat(SI_SPEEDRUN_HRC_BEGIN_RAKOTU),
[2] = zo_strformat(SI_SPEEDRUN_HRC_FINISH_RAKOTU),
[3] = zo_strformat(SI_SPEEDRUN_HRC_BEGIN_SECOND),
[4] = zo_strformat(SI_SPEEDRUN_HRC_FINISH_SECOND),
[5] = zo_strformat(SI_SPEEDRUN_HRC_BEGIN_WARRIOR),
[6] = zo_strformat(SI_SPEEDRUN_HRC_FINISH_WARRIOR),
},
[639] = { --SO
[1] = zo_strformat(SI_SPEEDRUN_SO_BEGIN_MANTIKORA),
[2] = zo_strformat(SI_SPEEDRUN_SO_FINISH_MANTIKORA),
[3] = zo_strformat(SI_SPEEDRUN_SO_BEGIN_TROLL),
[4] = zo_strformat(SI_SPEEDRUN_SO_FINISH_TROLL),
[5] = zo_strformat(SI_SPEEDRUN_SO_BEGIN_OZARA),
[6] = zo_strformat(SI_SPEEDRUN_SO_FINISH_OZARA),
[7] = zo_strformat(SI_SPEEDRUN_SO_BEGIN_SERPENT),
[8] = zo_strformat(SI_SPEEDRUN_SO_FINISH_SERPENT),
},
[725] = { --MoL
[1] = zo_strformat(SI_SPEEDRUN_MOL_BEGIN_ZHAJ),
[2] = zo_strformat(SI_SPEEDRUN_MOL_FINISH_ZHAJ),
[3] = zo_strformat(SI_SPEEDRUN_MOL_BEGIN_TWINS),
[4] = zo_strformat(SI_SPEEDRUN_MOL_FINISH_TWINS),
[5] = zo_strformat(SI_SPEEDRUN_MOL_BEGIN_RAKKHAT),
[6] = zo_strformat(SI_SPEEDRUN_MOL_FINISH_RAKKHAT),
},
[975] = { --HoF
[1] = zo_strformat(SI_SPEEDRUN_HOF_BEGIN_DYNO),
[2] = zo_strformat(SI_SPEEDRUN_HOF_FINISH_DYNO),
[3] = zo_strformat(SI_SPEEDRUN_HOF_BEGIN_FACTOTUM),
[4] = zo_strformat(SI_SPEEDRUN_HOF_FINISH_FACTOTUM),
[5] = zo_strformat(SI_SPEEDRUN_HOF_BEGIN_SPIDER),
[6] = zo_strformat(SI_SPEEDRUN_HOF_FINISH_SPIDER),
[7] = zo_strformat(SI_SPEEDRUN_HOF_BEGIN_COMMITEE),
[8] = zo_strformat(SI_SPEEDRUN_HOF_FINISH_COMMITEE),
[9] = zo_strformat(SI_SPEEDRUN_HOF_BEGIN_ASSEMBLY),
[10] = zo_strformat(SI_SPEEDRUN_HOF_FINISH_ASSEMBLY),
},
[1000] = { --AS
[1] = zo_strformat(SI_SPEEDRUN_AS_BEGIN_OLMS),
[2] = zo_strformat(SI_SPEEDRUN_AS_90_PERCENT),
[3] = zo_strformat(SI_SPEEDRUN_AS_75_PERCENT),
[4] = zo_strformat(SI_SPEEDRUN_AS_50_PERCENT),
[5] = zo_strformat(SI_SPEEDRUN_AS_25_PERCENT),
[6] = zo_strformat(SI_SPEEDRUN_AS_KILL_OLMS),
},
[1051] = { --CR
[1] = zo_strformat(SI_SPEEDRUN_CR_BEGIN_ZMAJA),
[2] = zo_strformat(SI_SPEEDRUN_CR_SIRORIA_APPEAR),
[3] = zo_strformat(SI_SPEEDRUN_CR_RELEQUEN_APPEAR),
[4] = zo_strformat(SI_SPEEDRUN_CR_GALENWE_APPEAR),
[5] = zo_strformat(SI_SPEEDRUN_CR_SHADOW_APPEAR),
[6] = zo_strformat(SI_SPEEDRUN_CR_KILL_SHADOW),
},
[1121] = { --SS
[1] = zo_strformat(SI_SPEEDRUN_SS_BEGIN_FIRST),
[2] = zo_strformat(SI_SPEEDRUN_SS_KILL_FIRST),
[3] = zo_strformat(SI_SPEEDRUN_SS_BEGIN_SECOND),
[4] = zo_strformat(SI_SPEEDRUN_SS_KILL_SECOND),
[5] = zo_strformat(SI_SPEEDRUN_SS_BEGIN_LAST),
[6] = zo_strformat(SI_SPEEDRUN_SS_KILL_LAST),
},
[1196] = { --KA
[1] = zo_strformat(SI_SPEEDRUN_KA_BEGIN_YANDIR),
[2] = zo_strformat(SI_SPEEDRUN_KA_KILL_YANDIR),
[3] = zo_strformat(SI_SPEEDRUN_KA_BEGIN_VROL),
[4] = zo_strformat(SI_SPEEDRUN_KA_KILL_VROL),
[5] = zo_strformat(SI_SPEEDRUN_KA_BEGIN_FALGRAVN),
[6] = zo_strformat(SI_SPEEDRUN_KA_KILL_FALGRAVN),
-- [7] = "",
},
[1082] = { --BRP
[1] = "1.1",
[2] = "1.2",
[3] = "1.3",
[4] = "1.4",
[5] = "1st Complete",
[6] = "2.1",
[7] = "2.2",
[8] = "2.3",
[9] = "2.4",
[10] = "2nd Complete",
[11] = "3.1",
[12] = "3.2",
[13] = "3.3",
[14] = "3.4",
[15] = "3rd Complete",
[16] = "4.1",
[17] = "4.2",
[18] = "4.3",
[19] = "4.4",
[20] = "4th Complete",
[21] = "5.1",
[22] = "5.2",
[23] = "5.3",
[24] = "5.4",
[25] = "5th Complete",
},
[677] = { --MA
[1] = zo_strformat(SI_SPEEDRUN_ARENA_FIRST),
[2] = zo_strformat(SI_SPEEDRUN_ARENA_SECOND),
[3] = zo_strformat(SI_SPEEDRUN_ARENA_THIRD),
[4] = zo_strformat(SI_SPEEDRUN_ARENA_FOURTH),
[5] = zo_strformat(SI_SPEEDRUN_ARENA_FIFTH),
[6] = zo_strformat(SI_SPEEDRUN_ARENA_SIXTH),
[7] = zo_strformat(SI_SPEEDRUN_ARENA_SEVENTH),
[8] = zo_strformat(SI_SPEEDRUN_ARENA_EIGHTH),
[9] = zo_strformat(SI_SPEEDRUN_ARENA_NINTH), --zo_strformat(SI_SPEEDRUN_ARENA_COMPLETE),
},
[635] = { --DSA
[1] = zo_strformat(SI_SPEEDRUN_ARENA_FIRST),
[2] = zo_strformat(SI_SPEEDRUN_ARENA_SECOND),
[3] = zo_strformat(SI_SPEEDRUN_ARENA_THIRD),
[4] = zo_strformat(SI_SPEEDRUN_ARENA_FOURTH),
[5] = zo_strformat(SI_SPEEDRUN_ARENA_FIFTH),
[6] = zo_strformat(SI_SPEEDRUN_ARENA_SIXTH),
[7] = zo_strformat(SI_SPEEDRUN_ARENA_SEVENTH),
[8] = zo_strformat(SI_SPEEDRUN_ARENA_EIGHTH),
[9] = zo_strformat(SI_SPEEDRUN_ARENA_NINTH),
[10] = zo_strformat(SI_SPEEDRUN_ARENA_TENTH),
-- [11] = zo_strformat(SI_SPEEDRUN_ARENA_COMPLETE),
},
[1227] = { --Vateshran Hollows
[1] = "Boss 1",
[2] = "Boss 2",
[3] = "Boss 3",
[4] = "Boss 4",
[5] = "Boss 5",
[6] = "Boss 6",
[7] = "Maebroogha |t20:20:esoui\\art\\icons\\poi\\poi_groupboss_incomplete.dds|t",
},
}
--------------------
---- Score List ----
--------------------
Speedrun.scoreReasonList = {
[0] = {
name = "No Bonus",
id = RAID_POINT_REASON_MIN_VALUE,
times = 0,
total = 0,
},
[1] = {
name = "Small adds:",
id = RAID_POINT_REASON_KILL_NORMAL_MONSTER,
times = 0,
total = 0,
},
[2] = {
name = "Large adds:",
id = RAID_POINT_REASON_KILL_BANNERMEN,
times = 0,
total = 0,
},
[3] = {
name = "Elite adds:",
id = RAID_POINT_REASON_KILL_CHAMPION,
times = 0,
total = 0,
},
[4] = {
name = "Miniboss",
id = RAID_POINT_REASON_KILL_MINIBOSS,
times = 0,
total = 0,
},
[5] = {
name = "Boss",
id = RAID_POINT_REASON_KILL_BOSS,
times = 0,
total = 0,
},
[6] = {
name = "Bonus Low (increased difficulty)",
id = RAID_POINT_REASON_BONUS_ACTIVITY_LOW,
times = 0,
total = 0,
},
[7] = {
name = "Bonus Medium (increased difficulty)",
id = RAID_POINT_REASON_BONUS_ACTIVITY_MEDIUM,
times = 0,
total = 0,
},
[8] = {
name = "Bonus High (HM)",
id = RAID_POINT_REASON_BONUS_ACTIVITY_HIGH,
times = 0,
total = 0,
},
[9] = {
name = "Revives & Resurrections",
id = RAID_POINT_REASON_LIFE_REMAINING,
times = 0,
total = 0,
},
[10] = {
name = "Bonus Point One",
id = RAID_POINT_REASON_BONUS_POINT_ONE,
times = 0,
total = 0,
},
[11] = {
name = "Bonus Point Two",
id = RAID_POINT_REASON_BONUS_POINT_TWO,
times = 0,
total = 0,
},
[12] = {
name = "Bonus Point Three",
id = RAID_POINT_REASON_BONUS_POINT_THREE,
times = 0,
total = 0,
},
[13] = {
name = "Remaining Sigils Bonus x1",
id = RAID_POINT_REASON_SOLO_ARENA_PICKUP_ONE,
times = 0,
total = 0,
},
[14] = {
name = "Remaining Sigils Bonus x2",
id = RAID_POINT_REASON_SOLO_ARENA_PICKUP_TWO,
times = 0,
total = 0,
},
[15] = {
name = "Remaining Sigils Bonus x3",
id = RAID_POINT_REASON_SOLO_ARENA_PICKUP_THREE,
times = 0,
total = 0,
},
[16] = {
name = "Remaining Sigils Bonus x4",
id = RAID_POINT_REASON_SOLO_ARENA_PICKUP_FOUR,
times = 0,
total = 0,
},
[17] = {
name = "Completion Bonus (Stage / Trial)",
id = RAID_POINT_REASON_MAX_VALUE,
times = 0,
total = 0,
},
}
|
local packer = require("polarmutex.util.packer")
local config = {
profile = {
enable = true,
threshold = 0, -- the amount in ms that a plugins load time must be over for it to be included in the profile
},
display = {
open_fn = function()
return require("packer.util").float({ border = "single" })
end,
},
-- list of plugins that should be taken from ~/projects
-- this is NOT packer functionality!
local_plugins = {},
}
local function plugins(use)
-- Packer can manage itself as an optional plugin
use({ "wbthomason/packer.nvim", opt = true })
use({ "nvim-lua/plenary.nvim", module = "plenary" })
use({ "nvim-lua/popup.nvim", module = "popup" })
use({
"lewis6991/impatient.nvim",
config = function()
require("impatient")
end,
})
-- LSP
use({
"neovim/nvim-lspconfig",
config = function()
require("polarmutex.config.lsp")
end,
requires = {
"nvim-lua/lsp-status.nvim",
"folke/lua-dev.nvim",
"jose-elias-alvarez/null-ls.nvim",
"jose-elias-alvarez/nvim-lsp-ts-utils",
"onsails/lspkind-nvim",
},
})
use({
"folke/trouble.nvim",
event = "BufReadPre",
cmd = { "TroubleToggle", "Trouble" },
config = function()
require("trouble").setup({ auto_open = false })
end,
})
use({ "mfussenegger/nvim-jdtls" })
-- Lsp Completion
use({
"hrsh7th/nvim-cmp",
config = function()
require("polarmutex.config.completion")
end,
requires = {
"hrsh7th/cmp-buffer",
"hrsh7th/cmp-path",
"hrsh7th/cmp-nvim-lua",
"hrsh7th/cmp-nvim-lsp",
"hrsh7th/cmp-emoji",
"saadparwaiz1/cmp_luasnip",
},
})
use({ "L3MON4D3/LuaSnip" })
-- Tree Sitter
use({
"nvim-treesitter/nvim-treesitter",
--run = ":TSUpdate",
requires = {
"nvim-treesitter/playground",
"nvim-treesitter/nvim-treesitter-textobjects",
},
config = function()
require("polarmutex.config.treesitter")
end,
})
use({ "polarmutex/contextprint.nvim" })
use({
"b3nj5m1n/kommentary",
opt = true,
keys = { "gc", "gcc" },
config = function()
require("polarmutex.config.comments")
end,
requires = "JoosepAlviste/nvim-ts-context-commentstring",
})
-- Fuzzy Finder / File / Buffer Nav
use({
"nvim-telescope/telescope.nvim",
config = function()
require("polarmutex.config.telescope")
end,
--keys = { "<leader><space>", "<leader>fz", "<leader>pp" },
requires = {
"nvim-telescope/telescope-project.nvim",
"nvim-lua/popup.nvim",
"nvim-lua/plenary.nvim",
"nvim-telescope/telescope-symbols.nvim",
"nvim-telescope/telescope-fzy-native.nvim",
},
})
use({
"ThePrimeagen/harpoon",
config = function()
require("polarmutex.config.harpoon")
end,
})
--use({
-- "ggandor/lightspeed.nvim",
-- event = "BufReadPost",
-- config = function()
-- require("polarmutex.config.lightspeed")
-- end,
--})
-- Git
use({
"lewis6991/gitsigns.nvim",
event = "BufReadPre",
requires = { "nvim-lua/plenary.nvim" },
config = function()
require("polarmutex.config.gitsigns")
end,
})
use({
"TimUntersberger/neogit",
cmd = "Neogit",
config = function()
require("polarmutex.config.neogit")
end,
})
use({
"sindrets/diffview.nvim",
cmd = { "DiffviewOpen", "DiffviewClose", "DiffviewToggleFiles", "DiffviewFocusFiles" },
config = function()
require("diffview").setup({})
end,
})
use({ "ThePrimeagen/git-worktree.nvim" })
use({ "ruifm/gitlinker.nvim" })
use({
"pwntester/octo.nvim",
config = function()
require("polarmutex.config.octo")
end,
})
-- Key Mappings
use({
"folke/which-key.nvim",
event = "VimEnter",
config = function()
require("polarmutex.config.which-key")
end,
})
-- Debugging
use({
"mfussenegger/nvim-dap",
config = function()
require("nvim-dap-virtual-text").setup()
require("polarmutex.config.dap")
end,
requires = {
"mfussenegger/nvim-dap-python",
"mfussenegger/nvim-lua-debugger",
"theHamsta/nvim-dap-virtual-text",
"nvim-telescope/telescope-dap.nvim",
},
})
-- statusline
use({
"nvim-lualine/lualine.nvim",
requires = { "kyazdani42/nvim-web-devicons", opt = true },
config = function()
require("polarmutex.config.statusline")
end,
})
-- Dashboard
use({
"goolord/alpha-nvim",
requires = { "kyazdani42/nvim-web-devicons" },
config = function()
require("polarmutex.config.dashboard")
end,
})
-- Undo
use({ "mbbill/undotree", cmd = "UndotreeToggle" })
use({
"RRethy/vim-illuminate",
event = "CursorHold",
module = "illuminate",
config = function()
vim.g.Illuminate_delay = 1000
end,
})
-- Session
use({
"folke/persistence.nvim",
event = "VimEnter",
module = "persistence",
config = function()
require("persistence").setup()
end,
})
-- Theme
use({
"kyazdani42/nvim-web-devicons",
module = "nvim-web-devicons",
config = function()
require("nvim-web-devicons").setup({ default = true })
end,
})
use({
"norcalli/nvim-colorizer.lua",
config = function()
require("polarmutex.config.colorizer")
end,
})
use({
"norcalli/nvim-terminal.lua",
ft = "terminal",
config = function()
require("terminal").setup()
end,
})
use({
"lukas-reineke/indent-blankline.nvim",
event = "BufReadPre",
config = function()
require("polarmutex.config.blankline")
end,
})
use({
"karb94/neoscroll.nvim",
keys = { "<C-u>", "<C-d>", "gg", "G" },
config = function()
require("polarmutex.config.scroll")
end,
})
use({
"edluffy/specs.nvim",
after = "neoscroll.nvim",
config = function()
require("polarmutex.config.specs")
end,
})
-- Increment / Decrement
use({
"monaqa/dial.nvim",
config = function()
require("polarmutex.config.dial")
end,
})
-- Beancount
use({
"polarmutex/beancount.nvim",
})
--delibrate practice
use({ "ThePrimeagen/vim-be-good" })
-- utilities
use({ "tweekmonster/startuptime.vim", cmd = "StartupTime" })
use({
"folke/todo-comments.nvim",
cmd = { "TodoTrouble", "TodoTelescope" },
event = "BufReadPost",
config = function()
require("todo-comments").setup()
end,
})
end
return packer.setup(config, plugins)
|
GM.Name = "BaseWars"
GM.Author = "Q2F2, Ghosty, Trixter, Liquid, Tenrys, User4992"
GM.Website = "http://hexahedron.pw/, http://hexahedronic.github.io/"
GM.Credits = [[
Thanks to the following people:
Q2F2/Orbitei - Main backend dev.
Ghosty - Main frontend dev.
Trixter - Frontend + Several entities.
Liquid/Ling - Misc dev, good friend.
Tenrys - Misc dev, good friend also.
Pyro-Fire - Owner of LagNation, ideas ect.
Devenger - Twitch Weaponry 2
User4992 - Fixes for random stuff.
This GM has been built from scratch with no traces of the original BaseWars existing.
]]
GM.Copyright = [[
Copyright (c) 2015-2017 Hexahedronic et al
]]
GM.Translators = [[
Thank you to the following translators:
Tenrys - French
_Fami - French
!_oplexz - Russian
Trixter - Russian
Ghosty - Spanish
Liquid - Dutch
Dennis - German
Archerity - Korean
See GAMEMODE.Credits for the original English ver creators.
]]
-- Shared colors, feel free to add any here
NiceGreen = Color(100, 250, 125)
NiceBlue = Color(100, 125, 250)
Grey = Color(200, 200, 200)
White = Color(255, 255, 255)
Pink = Color(255, 105, 180)
-- Starting!
BaseWars = BaseWars or {}
BaseWars.SpawnList = BaseWars.SpawnList or {}
function BaseWars.NewCAT(name, icon)
local cat = {}
cat.__inf = {}
cat.__inf.name = name
cat.__inf.icon = icon
return cat
end
-- Ignore this, Lua refresh compat
if BaseWars.Factions and table.Count(BaseWars.Factions.FactionTable) > 0 then
__BASEWARS_FACTION_BACKUP = table.Copy(BaseWars.Factions.FactionTable)
end
if BaseWars.Bounty and table.Count(BaseWars.Bounty.BountyTable) > 0 then
__BASEWARS_BOUNTY_BACKUP = table.Copy(BaseWars.Bounty.BountyTable)
end
-- Thanks to whoever posted this, can't remember source.
function ents.FindInCone(cone_origin, cone_direction, cone_radius, cone_angle)
local entities = ents.FindInSphere(cone_origin, cone_radius)
local result = {}
cone_direction:Normalize()
local cos = math.cos(cone_angle)
for _, entity in ipairs(entities) do
local pos = entity:GetPos()
local dir = pos - cone_origin
dir:Normalize()
local dot = cone_direction:Dot(dir)
if dot > cos then
table.insert(result, entity)
end
end
return result
end
function BaseWars.IsXmasTime(day)
local Month = tonumber(os.date("%m"))
local Day = tonumber(os.date("%d"))
return Month == 12 and (not day or (Day == 24 or Day == 25))
end
local DefaultData = {
__index = {
Model = "models/props_c17/FurnitureToilet001a.mdl",
Price = 0,
ClassName = "prop_physics",
ShouldFreeze = true,
}
}
function BaseWars.GSL(t)
if t.Drug then
t.Model = "models/props_junk/PopCan01a.mdl"
end
if not t.Limit then
t.Limit = BaseWars.Config.DefaultLimit
end
if t.VehicleName then
t.ShouldFreeze = false
end
return setmetatable(t, DefaultData)
end
BASEWARS_NOTIFICATION_ADMIN = color_white
BASEWARS_NOTIFICATION_ERROR = Color(255, 0, 0, 255)
BASEWARS_NOTIFICATION_MONEY = Color(0, 255, 0, 255)
BASEWARS_NOTIFICATION_RAID = Color(255, 255, 0, 255)
BASEWARS_NOTIFICATION_GENRL = Color(255, 0, 255, 255)
BASEWARS_NOTIFICATION_DRUG = Color(0, 255, 255, 255)
function GM:PlayerIsRaidable(ply)
if BaseWars.Config.Raid.NeededPrinters < 1 then return end
local Ents = ents.GetAll()
local Raids = 0
for k, v in ipairs(Ents) do
local Owner = v:CPPIGetOwner()
if not BaseWars.Ents:ValidPlayer(Owner) or Owner ~= ply then continue end
local Raidable = v.IsValidRaidable
if Raidable then Raids = Raids + 1 end
end
if Raids >= BaseWars.Config.Raid.NeededPrinters then return true end
return false, BaseWars.LANG.NoPrinters
end
function BaseWars.GetRaidables(ply)
local list = {}
for k, v in ipairs(ents.FindByClass"bw_*") do
local own = v:CPPIGetOwner()
if BaseWars.Ents:ValidPlayer(own) and (own == ply or (own:InFaction(ply:GetFaction()) and ply:InFaction())) then
list[#list+1] = {e = v, r = v.IsValidRaidable or false, o = own}
end
end
return list
end
local tag = "BaseWars.UTIL"
BaseWars.UTIL = {}
local colorRed = Color(255, 0, 0)
local colorBlue = Color(0, 0, 255)
local colorWhite = Color(255, 255, 255)
function BaseWars.UTIL.Log(...)
MsgC(SERVER and colorRed or colorBlue, "[BaseWars] ", colorWhite, ...)
MsgN("")
end
function BaseWars.UTIL.TimerAdv(name, spacing, reps, tickf, endf)
timer.Create(name, spacing * reps, 1, endf)
timer.Create(name .. ".Tick", spacing, reps, tickf)
end
function BaseWars.UTIL.TimerAdvDestroy(name)
timer.Destroy(name)
timer.Destroy(name .. ".Tick")
end
function BaseWars.UTIL.TimeParse(len)
local len = math.abs(math.floor(len))
local h = math.floor(len / 60 / 60)
local m = math.floor(len / 60 - h * 60)
local s = math.floor(len - m * 60 - h * 60 * 60)
return string.format("%.2d:%.2d:%.2d", h, m, s)
end
local function Pay(ply, amt, name, own)
ply:Notify(string.format(own and BaseWars.LANG.PayOutOwner or BaseWars.LANG.PayOut, BaseWars.NumberFormat(amt), name), BASEWARS_NOTIFICATION_GENRL)
ply:GiveMoney(amt)
end
function BaseWars.UTIL.PayOut(ent, attacker, full, ret)
if not BaseWars.Ents:Valid(ent) or not BaseWars.Ents:ValidPlayer(attacker) then return 0 end
if not ent.CurrentValue then ErrorNoHalt("ERROR! NO CURRENT VALUE! CANNOT PAY OUT!\n") return 0 end
local Owner = BaseWars.Ents:ValidOwner(ent)
local Val = ent.CurrentValue * (not full and not ret and BaseWars.Config.DestroyReturn or 1)
if Val ~= Val or Val == math.huge then
ErrorNoHalt("NAN OR INF RETURN DETECTED! HALTING!\n")
ErrorNoHalt("...INFINITE MONEY GLITCH PREVENTED!!!\n")
return 0 end
if ret then return Val end
local Name = ent.PrintName or ent:GetClass()
if ent.IsPrinter then Name = BaseWars.LANG.Level .. " " .. ent:GetLevel() .. " " .. Name end
if attacker == Owner then
Pay(Owner, Val, Name, true)
return 0 end
local Members = attacker:FactionMembers()
local TeamAmt = table.Count(Members)
local Involved = Owner and TeamAmt + 1 or TeamAmt
local Fraction = math.floor(Val / Involved)
if TeamAmt > 1 then
for k, v in next, Members do
Pay(v, Fraction, Name)
end
else
Pay(attacker, Fraction, Name)
end
if Owner then
Pay(Owner, Fraction, Name, true)
end
return Val
end
function BaseWars.UTIL.RefundAll(ply, ret)
if not ply and not ret then BaseWars.UTIL.Log("FULL SERVER REFUND IN PROGRESS!!!") end
local RetTbl = {}
if ret then
for k, v in next, player.GetAll() do
RetTbl[v:SteamID64()] = 0
end
end
for k, v in next, ents.GetAll() do
if not BaseWars.Ents:Valid(v) then continue end
local Owner = BaseWars.Ents:ValidOwner(v)
if not Owner or (ply and ply ~= Owner) then continue end
if not v.CurrentValue then continue end
if not ret then
BaseWars.UTIL.PayOut(v, Owner, true, ret)
v:Remove()
else
RetTbl[Owner:SteamID64()] = RetTbl[Owner:SteamID64()] + BaseWars.UTIL.PayOut(v, Owner, true, ret)
end
end
return RetTbl
end
function BaseWars.UTIL.WriteCrashRollback(recover)
if recover then
if file.Exists("server_crashed.dat", "DATA") then
BaseWars.UTIL.Log("Server crash detected, converting data rollbacks into refund files!")
else
return
end
local Files = file.Find("basewars_crashrollback/*_save.txt", "DATA")
for k, v in next, Files do
local FileName = v:gsub("_save.txt", "")
local FileData = file.Read("basewars_crashrollback/" .. v, "DATA")
file.Write("basewars_crashrollback/" .. FileName .. "_load.txt", FileData)
end
return end
local RefundTable = BaseWars.UTIL.RefundAll(nil, true)
for k, v in next, RefundTable do
if not file.IsDir("basewars_crashrollback", "DATA") then file.CreateDir("basewars_crashrollback") end
file.Write("basewars_crashrollback/" .. tostring(k) .. "_save.txt", v)
end
file.Write("server_crashed.dat", "")
end
function BaseWars.UTIL.RefundFromCrash(ply)
local UID = ply:SteamID64()
local FileName = "basewars_crashrollback/" .. UID .. "_load.txt"
if file.Exists(FileName, "DATA") then
local Money = file.Read(FileName, "DATA")
Money = tonumber(Money)
ply:ChatPrint(BaseWars.LANG.WelcomeBackCrash)
ply:ChatPrint(string.format(BaseWars.LANG.Refunded, BaseWars.NumberFormat(Money)))
BaseWars.UTIL.Log("Refunding ", ply, " for server crash previously.")
ply:GiveMoney(Money)
file.Delete(FileName)
end
end
function BaseWars.UTIL.ClearRollbackFile(ply)
local UID = ply:SteamID64()
local FileName = "basewars_crashrollback/" .. UID .. "_save.txt"
if file.Exists(FileName, "DATA") then file.Delete(FileName) end
end
function BaseWars.UTIL.SafeShutDown()
BaseWars.UTIL.RefundAll()
local Files = file.Find("basewars_crashrollback/*_save.txt", "DATA")
for k, v in next, Files do
file.Delete("basewars_crashrollback/" .. v)
end
file.Delete("server_crashed.dat")
end
function BaseWars.UTIL.FreezeAll()
for k, v in next, ents.GetAll() do
if not BaseWars.Ents:Valid(v) then continue end
local Phys = v:GetPhysicsObject()
if not BaseWars.Ents:Valid(Phys) then continue end
Phys:EnableMotion(false)
end
end
function BaseWars.UTIL.GetPre122Data(ply)
local path = IsValid(ply) and ply:SteamID64() or ply
if not path then return end
return {
money = tonumber(file.Read("basewars_money/" .. path .. "/money.txt", "DATA") or "") or 0,
karma = tonumber(file.Read("basewars_karma/" .. path .. "/karma.txt", "DATA") or "") or 0,
level = tonumber(file.Read("basewars_playerlevel/" .. path .. "/level.txt", "DATA") or "") or 0,
xp = tonumber(file.Read("basewars_playerlevel/" .. path .. "/xp.txt", "DATA") or "") or 0,
time = tonumber(file.Read("basewars_time/" .. path .. "/time.txt", "DATA") or "") or 0,
}
end
function BaseWars.UTIL.RevertPlayerData(ply)
local old_data = BaseWars.UTIL.GetPre122Data(ply)
if not old_data then return end
ply:SetMoney(old_data.money)
ply:SetKarma(old_data.karma)
ply:SetLevel(old_data.level)
ply:SetXP(old_data.xp)
PlayTime:SetGlobalTimeFile(ply, old_data.time)
end
function BaseWars.NumberFormat(num)
local t = BaseWars.LANG.Numbers
for i = 1, #t do
local Div = t[i][1]
local Str = t[i][2]
if num >= Div or num <= -Div then
return string.Comma(math.Round(num / Div, 1)) .. " " .. Str
end
end
return string.Comma(math.Round(num, 1))
end
local ValidChatHudTag = {
["color"] = true,
["hsv"] = true,
["texture"] = true,
}
function ParseChatHudTags(str)
if CLIENT and not chathud then return str end
local isChatHudTag = str:match("<(.-)>") and true or false
if isChatHudTag then
local ChatHudTag = str:match("<(.-)>")
local EndPos = string.find(ChatHudTag, "=")
if EndPos then
local ChatHudTagName = string.sub(ChatHudTag, 1, EndPos - 1)
if ValidChatHudTag[ChatHudTagName] then
str = string.Replace(str, "<" .. ChatHudTag .. ">", ""):Trim()
end
end
end
local isEndChatHudTag = str:match("</(.-)>") and true or false
if isEndChatHudTag then
local ChatHudTag = str:match("</(.-)>")
if ValidChatHudTag[ChatHudTag] then
str = string.Replace(str, "</" .. ChatHudTag .. ">", ""):Trim()
end
end
local stillHasTags = str:match("<(.-)>") and true or false
if stillHasTags then
local ChatHudTag = str:match("<(.-)>")
local EndPos = string.find(ChatHudTag, "=")
if EndPos then
local ChatHudTagName = string.sub(ChatHudTag, 1, EndPos - 1)
if ValidChatHudTag[ChatHudTagName] then
str = ParseChatHudTags(str)
end
end
end
return str
end
local PlayersCol = Color(125, 125, 125, 255)
team.SetUp(1, "No Faction", PlayersCol)
function GM:PlayerNoClip(ply)
local Admin = ply:IsAdmin()
if SERVER then
-- Second argument doesn't work??
local State = ply:GetMoveType() == MOVETYPE_NOCLIP
if aowl and not Admin and State and not ply.__is_being_physgunned then
return true
end
end
return Admin and not ply:InRaid() and (not aowl or ply.Unrestricted or ply:GetNWBool("Unrestricted"))
end
local function BlockInteraction(ply, ent, ret)
if ent then
if not BaseWars.Ents:Valid(ent) then return false end
local Classes = BaseWars.Config.PhysgunBlockClasses
local class = ent:GetClass()
if class:find("_door") or class:find("func_") then return false end
if Classes[class] then return false end
local Owner = ent.CPPIGetOwner and ent:CPPIGetOwner()
if BaseWars.Ents:ValidPlayer(ply) and ply:InRaid() then return false end
if BaseWars.Ents:ValidPlayer(Owner) and Owner:InRaid() then return false end
elseif ply:InRaid() then
return false
end
return ret == nil or ret
end
local function IsAdmin(ply, ent, ret)
if BlockInteraction(ply, ent, ret) == false then return false end
return ply:IsAdmin()
end
function GM:PhysgunPickup(ply, ent)
local Ret = self.BaseClass:PhysgunPickup(ply, ent)
if ent:IsVehicle() then return IsAdmin(ply, ent, Ret) end
ent.beingPhysgunned = ent.beingPhysgunned or {}
local found = false
for k, v in ipairs(ent.beingPhysgunned) do
if v == ply then found = true break end
end
if not found then
ent.beingPhysgunned[#ent.beingPhysgunned + 1] = ply
end
return BlockInteraction(ply, ent, Ret)
end
function GM:PhysgunDrop(ply, ent)
if ent.beingPhysgunned then
for k, v in ipairs(ent.beingPhysgunned) do
if v == ply then table.remove(ent.beingPhysgunned, k) break end
end
end
return self.BaseClass:PhysgunDrop(ply, ent)
end
function GM:CanPlayerUnfreeze(ply, ent, phys)
local Ret = self.BaseClass:CanPlayerUnfreeze(ply, ent, phys)
return BlockInteraction(ply, ent, Ret)
end
local stupidStuff = {
["precision"] = true,
["inflator"] = true,
["paint"] = true,
["color"] = true,
["fading_door"] = true,
["material"] = true,
}
function GM:CanTool(ply, tr, tool)
local ent = tr.Entity
if ent == game.GetWorld() then ent = nil end
local Ret = self.BaseClass:CanTool(ply, tr, tool)
if BaseWars.Config.BlockedTools[tool] then return IsAdmin(ply, ent, Ret) end
if BaseWars.Ents:Valid(ent) and ent:GetClass():find("bw_") then return IsAdmin(ply, ent, Ret) end
if SERVER and not stupidStuff[tool] then
local Pos = tr.HitPos
local HitString = math.floor(Pos.x) .. "," .. math.floor(Pos.y) .. "," .. math.floor(Pos.z)
BaseWars.UTIL.Log("TOOL EVENT: ", ply, " -> ", tool, " on pos [", HitString, "]")
end
return BlockInteraction(ply, ent, Ret)
end
function GM:PlayerSpawnObject(ply, model, ...)
local Ret = self.BaseClass:PlayerSpawnObject(ply, model, ...)
return BlockInteraction(ply, nil, Ret)
end
function GM:CanDrive()
-- I'm sick of this
return false
end
function GM:OnPhysgunReload()
-- Stop crashing our server
return false
end
function GM:CanProperty(ply, prop, ent, ...)
local Ret = self.BaseClass:CanProperty(ply, prop, ent, ...)
if not IsValid(ent) then return Ret end
local Class = ent:GetClass()
if prop == "persist" then return false end
if prop == "ignite" then return false end
if prop == "extinguish" then return IsAdmin(ply, ent, Ret) end
if prop == "remover" and Class:find("bw_") then return IsAdmin(ply, ent, Ret) end
return BlockInteraction(ply, ent, Ret)
end
function GM:GravGunPunt(ply, ent)
local Ret = self.BaseClass:GravGunPunt(ply, ent)
if not IsValid(ent) then return Ret end
local Class = ent:GetClass()
if ent:IsVehicle() then return false end
if Class == "prop_physics" then return BaseWars.Config.AllowPropPunt end
return BlockInteraction(ply, ent, Ret)
end
local NoSounds = {
"vo/engineer_no01.mp3",
"vo/engineer_no02.mp3",
"vo/engineer_no03.mp3",
}
function GM:PlayerSpawnProp(ply, model)
local Ret = self.BaseClass:PlayerSpawnProp(ply, model)
local EscapedModel = model:lower():gsub("\\","/"):gsub("//", "/"):Trim()
if BaseWars.Config.ModelBlacklist[EscapedModel] then
ply:EmitSound(NoSounds[math.random(1, #NoSounds)], 140)
return end
Ret = (Ret == nil or Ret)
if Ret then
BaseWars.UTIL.Log("PROP EVENT: ", ply, " -> ", EscapedModel)
end
return Ret == nil or Ret
end
|
local function recordExists(sid64, callback)
local strQuery = string.format("SELECT id FROM litlogs_players WHERE sid64 = '%s';", sid64)
LitLogs.Query(strQuery, function(data)
local exists = (istable(data) and data[1] and isnumber(data[1].id)) and true or false
callback(exists)
end)
end
hook.Add("PlayerInitialSpawn", "LitLogs::PlayerStore", function(ply)
timer.Simple(10, function() -- delay because the rpname darkrpvar isn't set instantly in this hook
if not IsValid(ply) then return end
local name = LitLogs.EscapeSQL(ply:getDarkRPVar("rpname") or ply:Nick())
local sid64 = ply:SteamID64()
local ip = ply:IPAddress():Split(":")[1]
recordExists(sid64, function(exists)
local strQuery
if not exists then
strQuery = string.format("INSERT INTO litlogs_players (sid64, lastname, lastip) VALUES ('%s', '%s', '%s');",
sid64, name, ip)
else
strQuery = string.format("UPDATE litlogs_players SET lastname = '%s', lastip = '%s' WHERE sid64 = '%s';",
name, ip, sid64)
end
LitLogs.Query(strQuery)
end)
end)
end)
|
local octopait = {
_LICENSE = [[
MIT LICENSE
Copyright (c) 2019 Chris / Systemlogoff
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.
]],
}
--[[ Notes ]]-------------------------------------------------------------------
-- Load libraries and media
gui = {}
gui.pixels = require 'pixels'
gui.pixels:load(4)
local image = nil
local preview_image = false
local adj_level = 0.5
local function bitnum(table)
if #table ~= 8 then return 0 end
local num = 0
if table[1] == 1 then num = num + 128 end
if table[2] == 1 then num = num + 64 end
if table[3] == 1 then num = num + 32 end
if table[4] == 1 then num = num + 16 end
if table[5] == 1 then num = num + 8 end
if table[6] == 1 then num = num + 4 end
if table[7] == 1 then num = num + 2 end
if table[8] == 1 then num = num + 1 end
return num
end
local startup_menu = love.graphics.newImage("res/menu.png")
local superchip = true
--[[ Notes ]]-------------------------------------------------------------------
-- Run once items.
function love.load()
end
--[[ Notes ]]-------------------------------------------------------------------
-- Draw behind all hump gamestates
function love.draw() -- This is the main love.draw if no draws are being done in your class, should never be noticed.
love.graphics.setColor(1,1,1,1)
gui.pixels:drawGameArea()
if image then
local dem = {image:getWidth(), image:getHeight()}
local width = 64
local height = 32
if superchip then
width = 128
height = 64
end
love.graphics.rectangle("fill", 0, 0, 128, 64)
if dem[1] > 128 then
if dem[1] > dem[2] then
love.graphics.draw(image,0,0,0,1/(dem[1]/width))--,1/(dem[2]/64))
else
love.graphics.draw(image,0,0,0,1/(dem[2]/height),1/(dem[2]/height))
end
else
love.graphics.draw(image)
end
else
love.graphics.draw(startup_menu)
end
if preview_image then
love.graphics.rectangle("fill", 0, 0, 128, 64)
love.graphics.setColor(0,0,0,1)
local cx = 0; local cy = 0
for i=1, #imagetable do
if imagetable[i] == 1 then
love.graphics.rectangle("fill", cx, cy, 1, 1)
end
cx = cx + 1
if i % 128 == 0 then
cx = 0
cy = cy + 1
end
end
love.graphics.setColor(1,1,1,1)
end
gui.pixels:endDrawGameArea()
end
--[[ Notes ]]-------------------------------------------------------------------
-- Global Hotkeys
function love.keypressed(key, scancode, isrepeat)
if key == "c" then
if image then
preview_image = false
window_convert()
else
window_noimage()
end
end
if key == "d" then
image = nil
end
if key == "m" then
window_adjust()
end
if key == "p" then
if image then
convertimage()
preview_image = not preview_image
else
window_noimage()
end
end
if key == "escape" or key == "q" then
window_quit()
end
end
--[[ Notes ]]-------------------------------------------------------------------
function love.update(dt)
gui.pixels:update(dt)
end
function love.filedropped(file)
local title = "Image Type"
local message = "What mode are you making your Chip8 game in?"
local buttons = {"Schip. (128x64)", "Std. (64x32)", escapebutton = 1}
local pressedbutton = love.window.showMessageBox(title, message, buttons)
if pressedbutton == 1 then
superchip = true
elseif pressedbutton == 2 then
superchip = false
end
file:open("r")
data2 = file:read()
print("Content of " .. file:getFilename() .. ' is')
--print(data2)
print("End of file")
data = love.filesystem.newFileData( data2, "img.png", "file" )
image = love.graphics.newImage( data )
file:close()
end
function window_convert()
local title = "Convert This Image?"
local message = "Convert this image and send the conversion to your clipboard?"
local buttons = {"Schip. (128x64)", "Std. (64x32)", "Cancel", escapebutton = 1}
local pressedbutton = love.window.showMessageBox(title, message, buttons)
if pressedbutton == 1 then
print("SCHIP")
convertimage()
to_clipboard()
elseif pressedbutton == 2 then
print("Standard")
convertimage_std()
to_clipboard()
elseif pressedbutton == 3 then
print("Canceled!")
end
end
function window_adjust()
local title = "Adjust Black/White Levels"
local message = "Adjust the limit of how grey a color has to be to be black.\nNot really needed if you already have drawn your image with only black/white colors."
local buttons = {"10%","20%","30%","40%","50% (Default)","60%","70%","80%","90%", escapebutton = 5}
local pressedbutton = love.window.showMessageBox(title, message, buttons)
if pressedbutton == 1 then
adj_level = 0.1
elseif pressedbutton == 2 then
adj_level = 0.2
elseif pressedbutton == 3 then
adj_level = 0.3
elseif pressedbutton == 4 then
adj_level = 0.4
elseif pressedbutton == 5 then
adj_level = 0.5
elseif pressedbutton == 6 then
adj_level = 0.6
elseif pressedbutton == 7 then
adj_level = 0.7
elseif pressedbutton == 8 then
adj_level = 0.8
elseif pressedbutton == 9 then
adj_level = 0.9
end
end
function window_quit()
if love.window.getFullscreen() == true then
love.window.setFullscreen(false)
end
local title = "Exit?"
local message = "Do you want to exit the program?"
local buttons = {"No", "Yes", escapebutton = 2}
local pressedbutton = love.window.showMessageBox(title, message, buttons, "warning", true)
if pressedbutton == 2 then
love.event.quit( )
elseif pressedbutton == 1 then
print("No")
end
end
function window_noimage()
local errortitle = "WARNING - No Image Loaded"
local errormessage = "There is no image loaded. Please load an image by dropping a file on the main window."
love.window.showMessageBox(errortitle, errormessage, "error")
end
function convertimage()
capture = gui.pixels.canvas:newImageData( 1, 1, 0, 0, 128, 64 ) -- Capture the displayed image
imagetable = {} -- create a table to hold it
local i = 1
for y=0, 64-1 do
for x=0, 128-1 do -- Loop though all the pixels in the frame
r, g, b, a = capture:getPixel( x,y )
--print(r, g, b, a)
imagetable[#imagetable+1] = ((r+b+g)/3) -- store as the average color
end
end
--print(#imagetable, imagetable[3]) -- Display count
for i=1, #imagetable do -- Convert the image to 0/1 depending on how grey it is.
local blackorwhite = 0
if imagetable[i] <= adj_level then
blackorwhite = 1
end
imagetable[i] = blackorwhite
end
-- Sanity Test
local string=""
for i=1, #imagetable do
string = string .. imagetable[i]
if i % 128 == 0 then
string = string .. "\n"
end
end
--print(string)
clip = ""
for tile=0, 127 do
string = ""
for i=1, 8 do
ox = (i-1) * 128
tj = math.floor(tile/16) * (7*128)
local lineseg = {
imagetable[(1+tj+(8*tile))+ox],
imagetable[(2+tj+(8*tile))+ox],
imagetable[(3+tj+(8*tile))+ox],
imagetable[(4+tj+(8*tile))+ox],
imagetable[(5+tj+(8*tile))+ox],
imagetable[(6+tj+(8*tile))+ox],
imagetable[(7+tj+(8*tile))+ox],
imagetable[(8+tj+(8*tile))+ox],
--print("Derp", (8+tj+(8*tile))+ox)
}
string = string .. bitnum(lineseg) .. " "
end
--print(": tile_" .. tile)
--print(string)
clip = clip .. string .. "\n"
--print(tile, (math.floor(tile / 16)))
end
end
function convertimage_std()
capture = gui.pixels.canvas:newImageData( 1, 1, 0, 0, 128, 64 ) -- Capture the displayed image
imagetable = {} -- create a table to hold it
local i = 1
for y=0, 32-1 do
for x=0, 64-1 do -- Loop though all the pixels in the frame
r, g, b, a = capture:getPixel( x,y )
--print(r, g, b, a)
imagetable[#imagetable+1] = ((r+b+g)/3) -- store as the average color
end
end
--print(#imagetable, imagetable[3]) -- Display count
for i=1, #imagetable do -- Convert the image to 0/1 depending on how grey it is.
local blackorwhite = 0
if imagetable[i] <= adj_level then
blackorwhite = 1
end
imagetable[i] = blackorwhite
end
-- Sanity Test
local string=""
for i=1, #imagetable do
string = string .. imagetable[i]
if i % 64 == 0 then
string = string .. "\n"
end
end
print(string)
clip = ""
for tile=0, 31 do
string = ""
for i=1, 8 do
ox = (i-1) * 64
tj = math.floor(tile/8) * (7*64)
local lineseg = {
imagetable[(1+tj+(8*tile))+ox],
imagetable[(2+tj+(8*tile))+ox],
imagetable[(3+tj+(8*tile))+ox],
imagetable[(4+tj+(8*tile))+ox],
imagetable[(5+tj+(8*tile))+ox],
imagetable[(6+tj+(8*tile))+ox],
imagetable[(7+tj+(8*tile))+ox],
imagetable[(8+tj+(8*tile))+ox],
--print("Derp", (8+tj+(8*tile))+ox)
}
string = string .. bitnum(lineseg) .. " "
end
--print(": tile_" .. tile)
--print(string)
clip = clip .. string .. "\n"
--print(tile, (math.floor(tile / 16)))
end
end
function to_clipboard()
love.system.setClipboardText( tostring(clip) )
end
|
module(..., package.seeall) --sputnik.authentication.simple
-----------------------------------------------------------------------------
-- This is the reference implementation for an authentication module,
-- implementing all of the core functionality that Sputnik will expect from
-- a drop-in-replacement
-----------------------------------------------------------------------------
local errors = require("sputnik.auth.errors")
local Simple = {}
local Simple_mt = {__metatable = {}, __index = Simple}
-- Utility functions
local function load_users(sputnik, name)
local node = sputnik:get_node(name)
return node.content.USERS, node.raw_values.content
end
local function get_salted_hash(time, salt, password)
return md5.sumhexa(time .. salt .. password)
end
local function user_token(user, salt, hash)
return md5.sumhexa(user .. salt .. "Sputnik")
end
-----------------------------------------------------------------------------
-- Creates a new instance of the authentication module for use in Sputnik
--
-- @param sputnik a sputnik instance to use for storage .
-- @param params a table of configuration paramaters (the actual set
-- of parameters is implementation-specific.
-----------------------------------------------------------------------------
function new(sputnik, params)
-- Set up default parameters
params = params or {}
params.node = params.node or "sputnik/passwords"
params.password_salt = params.password_salt or sputnik.config.PASSWORD_SALT
params.token_salt = params.token_salt or sputnik.config.TOKEN_SALT
params.recent = params.recent or (14 * 24 * 60 * 60)
local obj = setmetatable({}, Simple_mt)
obj.sputnik = sputnik
obj.node = params.node
obj.password_salt = params.password_salt
obj.token_salt = params.token_salt
obj.noauto = params.NO_AUTO_REGISTRATION
obj.recent = params.recent
obj.users = load_users(obj.sputnik, obj.node)
return obj
end
------------------------------------------------------------------
-- Returns whether or not a given username exists in the
-- authentication system, without any further information
--
-- @param username the username to query
-- @return exists whether or not the username exists in the system
function Simple:user_exists(username)
if type(username) ~= "string" then return false end
username=username:lower()
return type(self.users[username]) == "table"
end
------------------------------------------------------------------
-- Returns a token for the specified timestamp. This is provided
-- for use outside the authentication system
--
-- @param timestamp - the timestamp to use when generating token
-- @return token a hashed token representing the given timestamp
function Simple:timestamp_token(timestamp)
return md5.sumhexa(timestamp .. self.token_salt)
end
------------------------------------------------------------------
-- Attempt to authenticate a given user with a given password
--
-- @param user the username to authenticate
-- @param password the raw password to authenticate with
-- @return user the name of the authenticated user
-- @return token a hashed token for the user
function Simple:authenticate(username, password)
username = username:lower()
local entry = self.users[username]
if entry then
local hash = get_salted_hash(entry.creation_time, self.password_salt, password)
if hash == entry.hash then
return entry.display, user_token(username, self.token_salt, entry.hash)
else
return nil, errors.wrong_password(username)
end
else
return nil, errors.no_such_user(username)
end
end
------------------------------------------------------------------
-- Validate an existing authentication token. This is used for
-- allowing authentication via cookies
--
-- @param user the username the token belong to
-- @param token the actual token hash
-- @return user the name of the authenticated user
function Simple:validate_token(username, token)
username = username:lower()
local entry = self.users[username]
if self:user_exists(username) then
if user_token(username, self.token_salt, entry.hash) == token then
return entry.display
else
return false, errors.wrong_password(username)
end
else
return false, errors.no_such_user(username)
end
end
------------------------------------------------------------------
-- Returns whether or not a given user is a new user, defined
-- by the "recent" configuration parameter.
-- @param user the username to query
-- @return isRecent a boolean value indicating if the user's
-- account was created in the specified time frame
function Simple:user_is_recent(username)
username = username:lower()
local entry = self.users[username]
if entry then
local now = os.time()
local min = now - self.recent
return (tonumber(entry.creation_time) > min)
else
return nil, errors.no_such_user(username)
end
end
------------------------------------------------------------------
-- Adds a user/password pair to the password file
--
-- @param user the username to add
-- @param password the raw password
-- @return success a boolean value indicating if the add was
-- successful.
-- @return err an error message if the add was not successful
function Simple:add_user(username, password, metadata)
local now = os.time()
local users, raw_users = load_users(self.sputnik, self.node)
if self:user_exists(username) then
return nil, user_already_exist(username)
end
metadata = metadata or {}
metadata.creation_time = now
metadata.display = username
metadata.hash = get_salted_hash(now, self.password_salt, password)
username = username:lower()
if username == "admin" then
metadata.is_admin = "true"
end
users[username] = metadata
local user_as_string = string.format("USERS[%q]={", username)
for k,v in pairs(metadata) do
user_as_string = user_as_string..string.format(" %s=%q,", k, v)
end
user_as_string = user_as_string.."}"
local password_node = self.sputnik:get_node(self.node)
local params = {
content = (raw_users or "USERS={}\n").."\n"..user_as_string,
}
password_node = self.sputnik:update_node_with_params(password_node, params)
password_node = self.sputnik:save_node(password_node, nil, username,
"Added new user: " .. username, {minor="yes"})
self.users = load_users(self.sputnik, self.node)
return true
end
-----------------------------------------------------------------------------
-- Retrieves a piece of metadata for a specific user
--
-- @param username the username to query
-- @param key the metadata key to query
-- @return data the value of the metadata or nil
function Simple:get_metadata(username, key)
if not username or username=="" then return nil end
username=username:lower()
if self.users[username] then
return self.users[username][key]
else
return errors.no_such_user(username)
end
end
-- vim:ts=3 ss=3 sw=3 expandtab
|
---
-- Stub out problematic Lua functions while tests are running.
---
local testing = select(1, ...)
testing.onBeforeTest(function()
end)
testing.onAfterTest(function()
end)
|
util.AddNetworkString("openDonMenu")
util.AddNetworkString("sendRequest")
util.AddNetworkString("sendNotify")
local function donNotify(ply, txt)
net.Start("sendNotify")
net.WriteString(txt)
net.Send(ply)
end
local cmd = "!donate"
local packages = {
["Premium Lifetime"] = function(ply)
query("INSERT INTO donations (uniqueid, name, premium) VALUES ('"..ply:SteamID().."', '"..ply:Nick().."', '1')", function(res)
if (res) then
return true
end
end)
end,
["Platinum Lifetime"] = function(ply)
query("INSERT INTO donations (uniqueid, name, platinum) VALUES ('"..ply:SteamID().."', '"..ply:Nick().."', '1')", function(res)
if (res) then
return true
end
end)
end,
["Diamond Lifetime"] = function(ply)
query("INSERT INTO donations (uniqueid, name, diamond) VALUES ('"..ply:SteamID().."', '"..ply:Nick().."', '1')", function(res)
if (res) then
return true
end
end)
end
}
hook.Add("PlayerSay", "OpenOurDonateMenu", function(ply, text)
if (string.sub(text, 1, (string.len(cmd))) == cmd) then
net.Start("openDonMenu")
net.Send(ply)
end
end)
net.Receive("sendRequest", function(len, ply)
local key = net.ReadString()
if (!key) then donNotify(ply, "No key supplied!") return end
key = escape(key)
query("SELECT * FROM donations WHERE steamid = '"..ply:SteamID().."' AND redeemed = '0' AND unique_key = '"..key.."'", function(res)
if (#res != 0) then
local p = res[1]['package']
local rp = packages[p]
if (!rp) then donNotify(ply, "Package not found, contact a Server Director or Owner!") return end
local s = rp(ply)
if (s) then
query("UPDATE donations SET redeemed = '1' WHERE steamid ='"..ply:SteamID().."' AND unique_key = '"..key.."'", function(res)
if (res) then
donNotify(ply, "Successfully redeemed, thanks for donating!")
end
end)
end
else
donNotify(ply, "No key found for that SteamID, or it is already redeemed!")
end
end)
end)
|
module(..., package.seeall)
css = [=[
/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.2.2
*/
/*reset.css*/body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}ol,ul {list-style:none;}caption,th {text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;}
/*fonts.css*/body{font:13px arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}table {font-size:inherit;font:100%;}select, input, textarea {font:99% arial,helvetica,clean,sans-serif;}pre, code {font:115% monospace;*font-size:100%;}body * {line-height:1.22em;}
/*grids.css*/body{text-align:center;}#ft{clear:both;}#doc,#doc2,#doc3,.yui-t1,.yui-t2,.yui-t3,.yui-t4,.yui-t5,.yui-t6,.yui-t7{margin:auto;text-align:left;width:57.69em;*width:56.3em;min-width:750px;}#doc2{width:73.074em;*width:71.313em;min-width:950px;}#doc3{margin:auto 10px;width:auto;}.yui-b{position:relative;}.yui-b{_position:static;}#yui-main .yui-b{position:static;}#yui-main{width:100%;}.yui-t1 #yui-main,.yui-t2 #yui-main,.yui-t3 #yui-main{float:right;margin-left:-25em;}.yui-t4 #yui-main,.yui-t5 #yui-main,.yui-t6 #yui-main{float:left;margin-right:-25em;}.yui-t1 .yui-b{float:left;width:12.3207em;*width:12.0106em;}.yui-t1 #yui-main .yui-b{margin-left:13.3207em;*margin-left:13.0106em;}.yui-t2 .yui-b{float:left;width:13.8456em;*width:13.512em;}.yui-t2 #yui-main .yui-b{margin-left:14.8456em;*margin-left:14.512em;}.yui-t3 .yui-b{float:left;width:23.0759em;*width:22.52em;}.yui-t3 #yui-main .yui-b{margin-left:24.0759em;*margin-left:23.52em;}.yui-t4 .yui-b{float:right;width:13.8456em;*width:13.512em;}.yui-t4 #yui-main .yui-b{margin-right:14.8456em;*margin-right:14.512em;}.yui-t5 .yui-b{float:right;width:18.4608em;*width:18.016em;}.yui-t5 #yui-main .yui-b{margin-right:19.4608em;*margin-right:19.016em;}.yui-t6 .yui-b{float:right;width:23.0759em;*width:22.52em;}.yui-t6 #yui-main .yui-b{margin-right:24.0759em;*margin-right:23.52em;}.yui-t7 #yui-main .yui-b{display:block;margin:0 0 1em 0;}#yui-main .yui-b{float:none;width:auto;}.yui-g .yui-u,.yui-g .yui-g,.yui-gc .yui-u,.yui-gc .yui-g .yui-u,.yui-ge .yui-u,.yui-gf .yui-u{float:right;display:inline;}.yui-g div.first,.yui-gc div.first,.yui-gc div.first div.first,.yui-gd div.first,.yui-ge div.first,.yui-gf div.first{float:left;}.yui-g .yui-u,.yui-g .yui-g{width:49.1%;}.yui-g .yui-g .yui-u,.yui-gc .yui-g .yui-u{width:48.1%;}.yui-gb .yui-u,.yui-gc .yui-u,.yui-gd .yui-u{float:left;margin-left:2%;*margin-left:1.895%;width:32%;}.yui-gb div.first,.yui-gc div.first,.yui-gd div.first{margin-left:0;}.yui-gc div.first,.yui-gd .yui-u{width:66%;}.yui-gd div.first{width:32%;}.yui-ge .yui-u{width:24%;}.yui-ge div.first,.yui-gf .yui-u{width:74.2%;}.yui-gf div.first{width:24%;}.yui-ge div.first{width:74.2%;}#bd:after,.yui-g:after,.yui-gb:after,.yui-gc:after,.yui-gd:after,.yui-ge:after,.yui-gf:after{content:".";display:block;height:0;clear:both;visibility:hidden;}#bd,.yui-g,.yui-gb,.yui-gc,.yui-gd,.yui-ge,.yui-gf{zoom:1;}
]=]
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
return function (main, ...)
-- Inject the global process table
_G.process = require('process').globalProcess()
-- Seed Lua's RNG
do
local math = require('math')
local os = require('os')
math.randomseed(os.time())
end
-- Load Resolver
do
local dns = require('dns')
dns.loadResolver()
end
-- EPIPE ignore
do
if jit.os ~= 'Windows' then
local sig = uv.new_signal()
uv.signal_start(sig, 'sigpipe')
uv.unref(sig)
end
end
local args = {...}
local success, err = xpcall(function ()
-- Call the main app
main(unpack(args))
-- Start the event loop
uv.run()
end, debug.traceback)
if success then
-- Allow actions to run at process exit.
require('hooks'):emit('process.exit')
uv.run()
else
_G.process.exitCode = -1
require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n")
end
-- When the loop exits, close all unclosed uv handles.
uv.walk(function (handle)
if handle and not handle:is_closing() then handle:close() end
end)
uv.run()
-- Send the exitCode to luvi to return from C's main.
return _G.process.exitCode
end
|
{data={name="", author="Magnus siiftun1857 Frankline"}, blocks={
{1881000, {3.478, 0}},
{1881001, {3.478, 10}},
{1881001, {3.478, -10}},
{1881002, {-6.522, 10}, -1.571},
{1881002, {-6.522, -10}, 1.571},
{1881004, {3.478, -20}, bindingId=0},
{1881004, {3.478, 20}, bindingId=0},
{1881002, {-6.522, 20}, 1.571},
{1881002, {-6.522, -20}, -1.571}}}
|
do
local function f(x) return f(x) + 1 + 1 end
(nil)(f)
end
|
local gameData = {
score = 0,
timeScale = 1,
powerups = {
{ -- solid ground effect
minScore = 4, --score at which is starts spawning
chance = 0.2, --probability of being spawned at any given score
lifespan = 5, --how long until despawn if not collected (seconds)
effectDuration = 10, --how long the powerup is effective when applied
entity = "nodes/powerups/solidground", --the entity to spawn when collected (must have a .create method and :init, :deinit etc)
},
{ -- slow motion effect
minScore = 2, --score at which is starts spawning
chance = 0.2, --probability of being spawned at any given score
lifespan = 5, --how long until despawn if not collected (seconds)
effectDuration = 3, --how long the powerup is effective when applied
entity = "nodes/powerups/slowmotion", --the entity to spawn when collected (must have a .create method and :init, :deinit etc)
},
{ -- fast motion effect
minScore = 10, --score at which is starts spawning
chance = 0.3, --probability of being spawned at any given score
lifespan = 5, --how long until despawn if not collected (seconds)
effectDuration = 3, --how long the powerup is effective when applied
entity = "nodes/powerups/fastmotion", --the entity to spawn when collected (must have a .create method and :init, :deinit etc)
}
}
}
function gameData:init()
self.score = 0
self.timeScale = 1
end
return gameData
|
sptbl["brown"] = {
files = {
module = "brown.c",
header = "brown.h",
example = "ex_brown.c",
},
func = {
create = "sp_brown_create",
destroy = "sp_brown_destroy",
init = "sp_brown_init",
compute = "sp_brown_compute",
},
params = {
},
modtype = "module",
description = [[Brownian noise generator.
]],
ninputs = 0,
noutputs = 1,
inputs = {
},
outputs = {
{
name = "out",
description = "Brownian noise output."
},
}
}
|
--[[
背包界面
2016_07_06 Ravioyla
]]
local BagLayer = class("BagLayer", function(scene)
local bagLayer = display.newLayer(cc.c4b(0, 0, 0, 125))
return bagLayer
end)
local ShopDetailFrame = appdf.req(appdf.CLIENT_SRC.."plaza.models.ShopDetailFrame")
BagLayer.CBT_GEM = 1
BagLayer.CBT_CARD = 2
BagLayer.CBT_ITEM = 3
BagLayer.CBT_GIFT = 4
BagLayer.BT_GEM = 100
BagLayer.BT_CARD = BagLayer.BT_GEM+200
BagLayer.BT_ITEM = BagLayer.BT_CARD+200
BagLayer.BT_GIFT = BagLayer.BT_ITEM+200
-- 进入场景而且过渡动画结束时候触发。
function BagLayer:onEnterTransitionFinish()
self._scene:showPopWait()
self._shopDetailFrame:onQuerySend()
return self
end
-- 退出场景而且开始过渡动画时候触发。
function BagLayer:onExitTransitionStart()
return self
end
function BagLayer:ctor(scene, gameFrame)
local this = self
self._scene = scene
self:registerScriptHandler(function(eventType)
if eventType == "enterTransitionFinish" then -- 进入场景而且过渡动画结束时候触发。
self:onEnterTransitionFinish()
elseif eventType == "exitTransitionStart" then -- 退出场景而且开始过渡动画时候触发。
self:onExitTransitionStart()
elseif eventType == "exit" then
if self._shopDetailFrame:isSocketServer() then
self._shopDetailFrame:onCloseSocket()
end
if nil ~= self._shopDetailFrame._gameFrame then
self._shopDetailFrame._gameFrame._shotFrame = nil
self._shopDetailFrame._gameFrame = nil
end
end
end)
--按钮回调
self._btcallback = function(ref, type)
if type == ccui.TouchEventType.ended then
this:onButtonClickedEvent(ref:getTag(),ref)
end
end
local cbtlistener = function (sender,eventType)
this:onSelectedEvent(sender:getTag(),sender,eventType)
end
--网络回调
local bagCallBack = function(result,message)
this:onBagCallBack(result,message)
end
--网络处理
self._shopDetailFrame = ShopDetailFrame:create(self,bagCallBack)
self._shopDetailFrame._gameFrame = gameFrame
if nil ~= gameFrame then
gameFrame._shotFrame = self._shopDetailFrame
end
self._select = BagLayer.CBT_GEM
--显示队列
self._showList = {}
--数据队列
self._gemList = {}
self._cardList = {}
self._itemList = {}
self._giftList = {}
local frame = cc.SpriteFrameCache:getInstance():getSpriteFrame("sp_top_bg.png")
if nil ~= frame then
local sp = cc.Sprite:createWithSpriteFrame(frame)
sp:setPosition(yl.WIDTH/2,yl.HEIGHT-51)
self:addChild(sp)
end
display.newSprite("Bag/title_bag.png")
:move(yl.WIDTH/2,yl.HEIGHT - 51)
:addTo(self)
ccui.Button:create("bt_return_0.png","bt_return_1.png")
:move(75,yl.HEIGHT-51)
:addTo(self)
:addTouchEventListener(function(ref, type)
if type == ccui.TouchEventType.ended then
this._scene:onKeyBack()
end
end)
frame = cc.SpriteFrameCache:getInstance():getSpriteFrame("sp_public_frame_0.png")
if nil ~= frame then
local sp = cc.Sprite:createWithSpriteFrame(frame)
sp:setPosition(yl.WIDTH/2,320)
self:addChild(sp)
end
display.newSprite("Bag/frame_1.png")
:move(806,320)
:addTo(self)
display.newSprite("Bag/frame_2.png")
:move(178,320)
:addTo(self)
--宝石
ccui.CheckBox:create("Bag/cbt_0_0.png","","Bag/cbt_0_1.png","","")
:move(190,470)
:addTo(self)
:setSelected(true)
:setTag(BagLayer.CBT_GEM)
:addEventListener(cbtlistener)
--卡片
ccui.CheckBox:create("Bag/cbt_1_0.png","","Bag/cbt_1_1.png","","")
:move(190,470-104)
:addTo(self)
:setSelected(false)
:setTag(BagLayer.CBT_CARD)
:addEventListener(cbtlistener)
--道具
ccui.CheckBox:create("Bag/cbt_2_0.png","","Bag/cbt_2_1.png","","")
:move(190,470-104*2)
:addTo(self)
:setSelected(false)
:setTag(BagLayer.CBT_ITEM)
:addEventListener(cbtlistener)
--礼物
ccui.CheckBox:create("Bag/cbt_3_0.png","","Bag/cbt_3_1.png","","")
:move(190,470-104*3)
:addTo(self)
:setSelected(false)
:setTag(BagLayer.CBT_GIFT)
:addEventListener(cbtlistener)
self._scrollView = ccui.ScrollView:create()
:setContentSize(cc.size(938,458))
:setAnchorPoint(cc.p(0.5, 0.5))
:setPosition(cc.p(806, 320))
:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
:setBounceEnabled(true)
:setScrollBarEnabled(false)
:addTo(self)
end
--按键监听
function BagLayer:onButtonClickedEvent(tag,sender)
local beginPos = sender:getTouchBeganPosition()
local endPos = sender:getTouchEndPosition()
if math.abs(endPos.x - beginPos.x) > 30
or math.abs(endPos.y - beginPos.y) > 30 then
print("BagLayer:onButtonClickedEvent ==> MoveTouch Filter")
return
end
print("***** button clicked-"..tag.." ******")
if (tag>BagLayer.BT_GEM) and (tag<BagLayer.BT_CARD) then
GlobalUserItem.useItem = self._gemList[tag-BagLayer.BT_GEM]
self:getParent():getParent():onChangeShowMode(yl.SCENE_BAGDETAIL)
elseif (tag>BagLayer.BT_CARD) and (tag<BagLayer.BT_ITEM) then
GlobalUserItem.useItem = self._cardList[tag-BagLayer.BT_CARD]
self:getParent():getParent():onChangeShowMode(yl.SCENE_BAGDETAIL)
elseif (tag>BagLayer.BT_ITEM) and (tag<BagLayer.BT_GIFT) then
GlobalUserItem.useItem = self._itemList[tag-BagLayer.BT_ITEM]
self:getParent():getParent():onChangeShowMode(yl.SCENE_BAGDETAIL)
elseif (tag>BagLayer.BT_GIFT) and (tag<BagLayer.BT_GIFT+200) then
showToast(self,"手机端暂不支持礼物道具,请前往PC客户端使用!",2);
end
end
function BagLayer:onSelectedEvent(tag,sender,eventType)
if self._select == tag then
self:getChildByTag(tag):setSelected(true)
return
end
self._select = tag
for i=1,4 do
if i ~= tag then
self:getChildByTag(i):setSelected(false)
end
end
--刷新界面
self:onClearShowList()
self:onUpdateShowList()
end
--操作结果
function BagLayer:onBagCallBack(result,message)
print("======== BagLayer:onBagCallBack ========")
self._scene:dismissPopWait()
if message ~= nil and message ~= "" and result ~= 5 then
showToast(self,message,2);
end
if result==yl.SUB_GP_QUERY_BACKPACKET_RESULT then
if #message == 0 then
showToast(self, "背包为空", 2)
return
end
self._gemList = {}
self._cardList = {}
self._itemList = {}
self._giftList = {}
for i=1,#message do
local item = message[i]
if math.floor(item._index/100) == 0 then
table.insert(self._giftList,item)
elseif math.floor(item._index/100) == 1 then
table.insert(self._gemList,item)
elseif math.floor(item._index/100) == 2 then
table.insert(self._cardList,item)
elseif math.floor(item._index/100) == 3 then
table.insert(self._itemList,item)
end
end
--刷新界面
self:onClearShowList()
self:onUpdateShowList()
end
end
--清除当前显示
function BagLayer:onClearShowList()
for i=1,#self._showList do
self._showList[i]:removeFromParent()
end
self._showList = nil
self._showList = {}
end
--更新当前显示
function BagLayer:onUpdateShowList()
local theList = {}
local tag = 0
if self._select == BagLayer.CBT_GEM then
theList = self._gemList
tag = BagLayer.BT_GEM
elseif self._select == BagLayer.CBT_CARD then
theList = self._cardList
tag = BagLayer.BT_CARD
elseif self._select == BagLayer.CBT_ITEM then
theList = self._itemList
tag = BagLayer.BT_ITEM
elseif self._select == BagLayer.CBT_GIFT then
theList = self._giftList
tag = BagLayer.BT_GIFT
end
--计算scroll滑动高度
local scrollHeight = 0
if #theList<19 then
scrollHeight = 458
self._scrollView:setInnerContainerSize(cc.size(938, 458+20))
else
scrollHeight = 155*math.floor((#theList+math.floor(#theList%6))/6)
self._scrollView:setInnerContainerSize(cc.size(938, scrollHeight+20))
end
for i=1,#theList do
local item = theList[i]
self._showList[i] = cc.LayerColor:create(cc.c4b(100, 100, 100, 0), 143, 143)
:move(80+math.floor((i-1)%6)*154-143/2,scrollHeight-(80+math.floor((i-1)/6)*154)-143/2+20)
:addTo(self._scrollView)
ccui.Button:create("Bag/frame_3.png","Bag/frame_3.png")
:setContentSize(cc.size(143, 143))
:move(143/2,143/2)
:setTag(tag+i)
:addTo(self._showList[i])
:setSwallowTouches(false)
:addTouchEventListener(self._btcallback)
local frame = cc.SpriteFrameCache:getInstance():getSpriteFrame("icon_public_"..item._index..".png")
if nil ~= frame then
local sp = cc.Sprite:createWithSpriteFrame(frame)
sp:setPosition(71.5, 71.5)
self._showList[i]:addChild(sp)
end
cc.LabelAtlas:_create(""..item._count, "Bag/num_0.png", 20, 25, string.byte("0"))
:setAnchorPoint(cc.p(1.0,0.5))
:move(128,25)
:addTo(self._showList[i])
end
end
return BagLayer
|
if SERVER then util.AddNetworkString("Element.ShockBeam") end
local ELEMENT = Element.New()
function ELEMENT:Initialize()
self:SetDamageType(DMG_SHOCK)
self:SetWeakAgainst(ELEMENT_GRASS, ELEMENT_ROCK, ELEMENT_SHOCK)
self:SetStrongAgainst(ELEMENT_AIR, ELEMENT_WATER)
self:SetImmuneAgainst(0)
end
function ELEMENT:OnInteractWith(target, other, dmg_info)
if not target:HasDebuff(DEBUFF_SOAKED) then return end
local nearby_ents = ents.FindInSphere(dmg_info:GetDamagePosition(), 60)
local found_ents, found_count = {}, 0
for i, ent in ipairs(nearby_ents) do
if ent:GetClass() == "yawd_npc_base" and ent:HasDebuff(DEBUFF_SOAKED) then
local shock_dmg = DamageInfo()
local center = ent:GetPos() + ent:OBBCenter()
shock_dmg:SetDamageType(DMG_SHOCK)
shock_dmg:SetDamage(35)
shock_dmg:SetAttacker(dmg_info:GetAttacker())
shock_dmg:SetInflictor(ent)
shock_dmg:SetDamagePosition(center)
ent:TakeDamageInfo(shock_dmg)
found_count = found_count + 1
found_ents[found_count] = {ent, center}
end
end
if found_count ~= 0 then
net.Start("Element.ShockBeam")
net.WriteEntity(target)
net.WriteUInt(found_count, 8)
for i, info in ipairs(found_ents) do
net.WriteEntity(ent)
end
net.Broadcast()
end
end
if CLIENT then
local beams = {}
local spark_col = Color(191, 0, 255, 255, 150)
local lightningMaterial = Material("sprites/lgtning")
net.Receive("Element.ShockBeam", function()
local start_ent = net.ReadEntity()
for i = 1, net.ReadUInt(8) do
local end_ent = net.ReadEntity()
table.insert(beams, {start_ent, end_ent, CurTime()})
end
end)
hook.Add("PreDrawTranslucentRenderables", "Element.DrawShockBeams", function(a, b)
if a or b or #beams == 0 then return end
render.OverrideBlend(true, BLEND_SRC_COLOR, BLEND_SRC_ALPHA, BLENDFUNC_ADD, BLEND_ONE, BLEND_ZERO, BLENDFUNC_ADD)
render.SetMaterial(lightningMaterial)
for i = #beams, 1, -1 do
local info = beams[i]
local start_ent = info[1]
if not start_ent:IsValid() then
table.remove(beams, i)
return
end
local end_ent = info[2]
if not end_ent:IsValid() then
table.remove(beams, i)
return
end
local life_start = info[3]
local uv = math.random()
local start_pos = start_ent:GetPos() + start_ent:OBBCenter()
local end_pos = end_ent:GetPos() + end_ent:OBBCenter()
local diff = end_pos - start_pos
local mag = diff:Length()
local dir = diff:GetNormalized()
render.StartBeam(5)
render.AddBeam(start_pos, 20, uv * 1, spark_col)
render.AddBeam(start_pos + dir * (mag * 0.25), 20, uv * 2, spark_col)
render.AddBeam(start_pos + dir * (mag * 0.50), 20, uv * 3, spark_col)
render.AddBeam(start_pos + dir * (mag * 0.75), 20, uv * 4, spark_col)
render.AddBeam(end_pos, 20, uv * 5, spark_col)
render.EndBeam()
if CurTime() > life_start + 0.25 then
table.remove(beams, i)
end
end
render.OverrideBlend(false)
end)
end
ELEMENT_SHOCK = Element.Register(ELEMENT)
|
require 'lfs'
-- Ensure the test is launched within the specs/ folder
assert(string.match(lfs.currentdir(), "specs")~=nil, "You must run this test in specs folder")
local initial_dir = lfs.currentdir()
-- Go to specs folder
while (not string.match(lfs.currentdir(), "/specs$")) do
lfs.chdir("..")
end
local specs_dir = lfs.currentdir()
lfs.chdir("..")-- one more directory and it is lib root
-- Include Dataframe lib
dofile("init.lua")
-- Go back into initial dir
lfs.chdir(initial_dir)
describe("Dataframe class", function()
it("Counts missing values", function()
local a = Dataframe(specs_dir.."/data/full.csv")
assert.are.same(a:count_na{as_dataframe = false}, {["Col A"]= 0, ["Col B"]= 0, ["Col C"]=1, ["Col D"]=1})
end)
it("Fills missing value(s) for a given column(s)",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
assert.has.error(function() a:fill_na("Random column") end)
a:fill_na("Col A", 1)
assert.are.same(a:count_na{as_dataframe = false},
{["Col A"]= 0, ["Col B"]= 0, ["Col C"]=1})
a:fill_na("Col C", 1)
assert.are.same(a:count_na{as_dataframe = false}, {["Col A"]= 0, ["Col B"]= 0, ["Col C"]=0})
assert.are.same(a:get_column("Col C"), {8, 1, 9})
end)
it("Fills all Dataframe's missing values", function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a.dataset['Col A'][3] = nil
local cnt, tot = a:count_na{as_dataframe = false}
assert.are.same(cnt, {["Col A"]= 1, ["Col B"]= 0, ["Col C"]=1})
assert.are.same(tot, 2)
a:fill_all_na(-1)
assert.are.same(a:count_na{as_dataframe = false}, {["Col A"]= 0, ["Col B"]= 0, ["Col C"]=0})
assert.are.same(a:get_column('Col A'), {1,2,-1})
end)
it("The count_na should #1 return a Dataframe by default", function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
local ret = a:count_na()
assert.are.same(torch.type(ret), "Dataframe")
assert.are.same(ret:size(), 3, "3 columns should render 3 rows")
end)
end)
|
--- Legacy code written by AxisAngles to simulate particles with Guis
-- @module ParticleEngine
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local RunService = game:GetService("RunService")
local GetRemoteEvent = require("GetRemoteEvent")
local sin = math.sin
local sqrt = math.sqrt
local atan2 = math.atan2
local v2 = Vector2.new
local v3 = Vector3.new
local ud2 = UDim2.new
local ParticleEngineClient = {}
-- 3000 if you have a good computer
ParticleEngineClient._maxParticles = 400
-- Speed of wind to simulate
ParticleEngineClient._windSpeed = 10
local function newFrame(name)
local frame = Instance.new("Frame")
frame.BorderSizePixel = 0
frame.Name = name
frame.Archivable = false
return frame
end
function ParticleEngineClient:Init(screen)
self._remoteEvent = GetRemoteEvent("ParticleEventDistributor")
self._screen = screen or error("No screen")
self._player = Players.LocalPlayer or error("No LocalPlayer")
self._remoteEvent.OnClientEvent:Connect(function(...)
self:ParticleNew(...)
end)
self._lastUpdateTime = tick()
self._particleCount = 0
self._particles = {}
self._particleFrames = {}
for i=1, self._maxParticles do
self._particleFrames[i] = newFrame("_particle")
end
RunService.Heartbeat:Connect(function()
debug.profilebegin("ParticleUpdate")
self:_update()
debug.profileend()
end)
return self
end
--- Removes a particle
function ParticleEngineClient:Remove(p)
if self._particles[p] then
self._particles[p] = nil
self._particleCount = self._particleCount - 1
end
end
-- Adds a new particle
-- @param p PropertiesTable
--[[
{
Position = Vector3
-- Optional
Global = Bool
Velocity = Vector3
Gravity = Vector3
WindResistance = Number
LifeTime = Number
Size = Vector2
Bloom = Vector2
Transparency = Number
Color = Color3
Occlusion = Bool
RemoveOnCollision = function(BasePart Hit, Vector3 Position))
Function = function(Table ParticleProperties, Number dt, Number t)
}
--]]
function ParticleEngineClient:Add(p)
if self._particles[p] then
return
end
p.Position = p.Position or Vector3.new()
p.Velocity = p.Velocity or Vector3.new()
p.Size = p.Size or v2(0.2,0.2)
p.Bloom = p.Bloom or v2()
p.Gravity = p.Gravity or Vector3.new()
p.Color = p.Color or Color3.new(1,1,1)
p.Transparency = p.Transparency or 0.5
if p.Global then
local func = p.Function
local removeOnCollision = p.RemoveOnCollision
p.Global = nil
p.Function = nil
p.RemoveOnCollision = p.RemoveOnCollision and true or nil
self._remoteEvent:FireServer(p)
p.Function = func
p.RemoveOnCollision = removeOnCollision
end
p.LifeTime = p.LifeTime and p.LifeTime+tick()
if self._particleCount > self._maxParticles then
self._particles[next(self._particles)] = nil
else
self._particleCount = self._particleCount + 1
end
self._particles[p] = p
end
-- @param p Position
local function particleWind(t, p)
local xy,yz,zx=p.x+p.y,p.y+p.z,p.z+p.x
return v3(
(sin(yz+t*2)+sin(yz+t))/2+sin((yz+t)/10)/2,
(sin(zx+t*2)+sin(zx+t))/2+sin((zx+t)/10)/2,
(sin(xy+t*2)+sin(xy+t))/2+sin((xy+t)/10)/2
)
end
-- @param p ParticleProperties
-- @param dt ChangeInTime
function ParticleEngineClient:_updatePosVel(p, dt, t)
p.Position = p.Position + p.Velocity*dt
local wind
if p.WindResistance then
wind = (particleWind(t, p.Position)*self._windSpeed - p.Velocity)*p.WindResistance
else
wind = v3()
end
p.Velocity = p.Velocity + (p.Gravity + wind)*dt
end
--- Handles both priority and regular particles
-- @return boolean alive, true if still fine
function ParticleEngineClient:_updateParticle(particle, t, dt)
if particle.LifeTime - t <= 0 then
return false
end
-- Call this first, so any changes are reflected immediately
if particle.Function then
particle.Function(particle, dt, t)
end
local lastPos = particle.Position
self:_updatePosVel(particle, dt, t)
if not particle.RemoveOnCollision then
return true
end
local displacement = particle.Position - lastPos
local distance = displacement.Magnitude
if distance > 999 then
displacement = displacement * (999/distance)
end
local ray = Ray.new(lastPos, displacement)
local hit, position, normal, material = Workspace:FindPartOnRay(ray, self._player.Character, true)
if not hit then
return true
end
if type(particle.RemoveOnCollision) == "function" then
if not particle.RemoveOnCollision(particle, hit, position, normal, material) then
return false
end
else
return false
end
return true
end
function ParticleEngineClient:_update()
local t = tick()
local dt = t - self._lastUpdateTime
self._lastUpdateTime = t
local toRemove = {}
-- Update particles
for particle in pairs(self._particles) do
if not self:_updateParticle(particle, t, dt) then
toRemove[particle] = true
end
end
-- Remove tagged particles
for particle in pairs(toRemove) do
self:Remove(particle)
end
-- Update render
self:_updateRender()
end
function ParticleEngineClient:_updateRender()
local camera = Workspace.CurrentCamera
self:_updateScreenInfo(camera)
local cameraInverse = camera.CFrame:inverse()
local cameraPosition = camera.CFrame.p
local frameIndex, frame = next(self._particleFrames)
for particle in pairs(self._particles) do
if self:_particleRender(cameraPosition, cameraInverse, frame, particle) then
frame.Parent = self._screen
frameIndex, frame = next(self._particleFrames, frameIndex)
end
end
-- Cleanup remaining frames that are parented
while frameIndex and frame.Parent do
frame.Parent = nil
frameIndex, frame = next(self._particleFrames, frameIndex)
end
end
-- @param f frame
-- @param cameraInverse The inverse camera cframe
function ParticleEngineClient:_particleRender(cameraPosition, cameraInverse, frame, particle)
local rp = cameraInverse*particle.Position
local lsp = particle._lastScreenPosition
if not (rp.z < -1 and lsp) then
if rp.z > 0 then
particle._lastScreenPosition = nil
else
local sp = rp/rp.z
particle._lastScreenPosition = Vector2.new(
(0.5-sp.x/self._planeSizeX)*self._screenSizeX,
(0.5+sp.y/self._planeSizeY)*self._screenSizeY)
end
return false
end
local sp = rp/rp.z
local b = particle.Bloom
local bgt = particle.Transparency
local px = (0.5-sp.x/self._planeSizeX)*self._screenSizeX
local py = (0.5+sp.y/self._planeSizeY)*self._screenSizeY
local preSizeY = -particle.Size.y/rp.z*self._screenSizeY/self._planeSizeY
local sx = -particle.Size.x/rp.z*self._screenSizeY/self._planeSizeY + b.x
local rppx,rppy = px-lsp.x,py-lsp.y
local sy = preSizeY+sqrt(rppx*rppx+rppy*rppy) + b.y
particle._lastScreenPosition = v2(px, py)
if particle.Occlusion then
local vec = particle.Position-cameraPosition
local mag = vec.Magnitude
if mag > 999 then
vec = vec * (999/mag)
end
if Workspace:FindPartOnRay(Ray.new(cameraPosition, vec), self._player.Character, true) then
return false
end
end
frame.Position = ud2(0, (px+lsp.x-sx)/2, 0, (py+lsp.y-sy)/2)
frame.Size = ud2(0, sx, 0,sy)
frame.Rotation = 90+atan2(rppy,rppx)*57.295779513082
frame.BackgroundColor3 = particle.Color
frame.BackgroundTransparency = bgt+(1-bgt)*(1 - preSizeY/sy)
return true
end
function ParticleEngineClient:_updateScreenInfo(camera)
self._screenSizeX = self._screen.AbsoluteSize.x
self._screenSizeY = self._screen.AbsoluteSize.y
self._planeSizeY = 2*math.tan(camera.FieldOfView*0.0087266462599716)
self._planeSizeX = self._planeSizeY*self._screenSizeX/self._screenSizeY
end
return ParticleEngineClient
|
log(DEBUG, "---- UTILITIES TEST BEGIN ----")
log(DEBUG, "Testing vector3")
local v = Vector3(1, 5, 3)
assert(v.x == 1 and v.y == 5 and v.z == 3)
log(DEBUG, "Testing vector4")
v = Vector4(1, 5, 3, 6)
assert(v.x == 1 and v.y == 5 and v.z == 3 and v.w == 6)
log(DEBUG, "Testing tovec3")
v = tovec3({ 5, 10, 15 })
assert(v.x == 5 and v.y == 10 and v.z == 15)
log(DEBUG, "Testing tovec4")
v = tovec4({ 5, 10, 15, 20 })
assert(v.x == 5 and v.y == 10 and v.z == 15 and v.w == 20)
log(DEBUG, "Testing sign")
assert(sign(-0.1) == -1)
assert(sign(0.2) == 1)
assert(sign(0) == 0)
log(DEBUG, "Testing angle normalization")
assert(normalizeAngle(370, 180) == 10)
log(DEBUG, "---- UTILITIES TEST END ----")
|
-----------------
---- Globals ----
-----------------
DebuffMe = DebuffMe or {}
local DebuffMe = DebuffMe
DebuffMe.name = "DebuffMe"
DebuffMe.version = "1.6.0"
DebuffMe.flag_immunity = false
DebuffMe.altarEndTime = 0
DebuffMe.CustomDataList = {
name = {},
id = {},
abbreviation = {},
}
---------------------------
---- Variables Default ----
---------------------------
DebuffMe.Default = {
OffsetX = 0,
OffsetY = 0,
Debuff_Show = { [1] = 2,
[2] = 4,
[3] = 3,
[4] = 5},
AlwaysShowAlert = false,
FontSize = 36,
Spacing = 10,
SlowMode = false,
CustomDataList = {
name = {},
id = {},
abbreviation = {},
},
thresholdHP = 1,
}
------------------
---- FONCTION ----
------------------
local function GetFormattedAbilityNameWithID(id) --Fix to LUI extended conflict thank you Solinur and Wheels
local name = DebuffMe.CustomAbilityNameWithID[id] or zo_strformat(SI_ABILITY_NAME, GetAbilityName(id))
return name
end
function DebuffMe.DoesDebuffEquals(ID1, ID2)
if GetFormattedAbilityNameWithID(ID1) == GetFormattedAbilityNameWithID(ID2) then
return true
else
return false
end
end
function DebuffMe.Calcul(index)
local Debuff_Choice = DebuffMe.Debuff_Show[index]
local currentTimeStamp = GetGameTimeMilliseconds() / 1000
DebuffID = tonumber(DebuffMe.TransitionTable[Debuff_Choice])
local Timer = 0
DebuffMe.flag_immunity = false
for i=1, GetNumBuffs("reticleover") do --check all debuffs
local _, _, timeEnding, _, _, _, _, _, _, _, abilityId, _, castByPlayer = GetUnitBuffInfo("reticleover",i)
if Debuff_Choice == 2 then --if taunt
if castByPlayer == true then
if DebuffMe.DoesDebuffEquals(abilityId, DebuffID) then
Timer = timeEnding - currentTimeStamp
end
end
else
if DebuffMe.DoesDebuffEquals(abilityId, DebuffID) then
if Timer <= timeEnding - currentTimeStamp then --ignore conflict when more than one player is applying the same debuff
Timer = timeEnding - currentTimeStamp
end
end
end
end
--------------------
-- SPECIAL TIMERS --
--------------------
----------------
-- IMMUNITIES --
----------------
if Timer <= 0 and Debuff_Choice == 2 then --check target taunt immunity
for i=1,GetNumBuffs("reticleover") do
local _, _, timeEnding, _, _, _, _, _, _, _, abilityId, _, _ = GetUnitBuffInfo("reticleover",i)
if DebuffMe.DoesDebuffEquals(abilityId, 52788) then
Timer = timeEnding - currentTimeStamp
DebuffMe.flag_immunity = true
end
end
end
if Timer <= 0 and Debuff_Choice == 6 then --check target offbalance immunity
for i=1,GetNumBuffs("reticleover") do
local _, _, timeEnding, _, _, _, _, _, _, _, abilityId, _, _ = GetUnitBuffInfo("reticleover",i)
if DebuffMe.DoesDebuffEquals(abilityId, 134599) then
Timer = timeEnding - currentTimeStamp
DebuffMe.flag_immunity = true
end
end
end
if Timer <= 0 and Debuff_Choice == 16 then --check target major vulnerability immunity
for i=1,GetNumBuffs("reticleover") do
local _, _, timeEnding, _, _, _, _, _, _, _, abilityId, _, _ = GetUnitBuffInfo("reticleover",i)
if DebuffMe.DoesDebuffEquals(abilityId, 132831) then
Timer = timeEnding - currentTimeStamp
DebuffMe.flag_immunity = true
end
end
end
-------------------
-- VULNERABILITY --
-------------------
if Timer <= 4 and Debuff_Choice == 7 then --check minor vulnerability from shock
for i=1,GetNumBuffs("reticleover") do
local _, _, timeEnding, _, _, _, _, _, _, _, abilityId, _, _ = GetUnitBuffInfo("reticleover",i)
if DebuffMe.DoesDebuffEquals(abilityId, 68359) then
Timer = timeEnding - currentTimeStamp
end
end
end
if Timer <= 8 and Debuff_Choice == 7 then --check minor vulnerability from nb gap closer
for i=1,GetNumBuffs("reticleover") do
local _, _, timeEnding, _, _, _, _, _, _, _, abilityId, _, _ = GetUnitBuffInfo("reticleover",i)
if DebuffMe.DoesDebuffEquals(abilityId, 124806) then
if Timer <= timeEnding - currentTimeStamp then
Timer = timeEnding - currentTimeStamp
end
end
end
end
if Timer <= 4 and Debuff_Choice == 8 then --check minor main from chilled
for i=1,GetNumBuffs("reticleover") do
local _, _, timeEnding, _, _, _, _, _, _, _, abilityId, _, _ = GetUnitBuffInfo("reticleover",i)
if DebuffMe.DoesDebuffEquals(abilityId, 68368) then
Timer = timeEnding - currentTimeStamp
end
end
end
---------------------
-- MINOR LIFESTEAL --
---------------------
if Debuff_Choice == 10 and Timer <= DebuffMe.altarEndTime - currentTimeStamp then --check minor lifesteal from altar
for i=1,GetNumBuffs("reticleover") do
local _, _, _, _, _, _, _, _, _, _, abilityId, _, _ = GetUnitBuffInfo("reticleover",i)
if DebuffMe.DoesDebuffEquals(abilityId, 80020) then --altar
Timer = DebuffMe.altarEndTime - currentTimeStamp
end
end
end
---------------------
-- CONVERT TO TEXT --
---------------------
local TimerTXT = ""
if Timer <= 0 then
if index == 1 then --no abbreviation if main debuff
TimerTXT = "0"
else
TimerTXT = DebuffMe.Abbreviation[Debuff_Choice]
end
else
if index == 1 then --no decimal point if main debuff
TimerTXT = tostring(string.format("%.0f", Timer))
else
if DebuffMe.SlowMode == true then
TimerTXT = tostring(string.format("%.0f", Timer))
else
TimerTXT = tostring(string.format("%.1f", Timer))
end
end
end
return TimerTXT
end
function DebuffMe.SetFontSize(label, size)
local path = "EsoUI/Common/Fonts/univers67.otf"
local outline = "soft-shadow-thick"
label:SetFont(path .. "|" .. size .. "|" .. outline)
end
----------------
---- UPDATE ----
----------------
function DebuffMe.AltarTimer(_, changeType, _, _, _, _, endTime, _, _, _, _, _, _, _, _, abilityId, _)
if changeType == COMBAT_UNIT_TYPE_PLAYER and abilityId == 39489 or 41967 or 41958 then
local currentTimeStamp = endTime - GetGameTimeMilliseconds() / 1000
if currentTimeStamp > 0 then
DebuffMe.altarEndTime = endTime
end
end
end
function DebuffMe.SetText(index, txt)
if index == 1 then
DebuffMeAlertMiddle:SetText(txt)
elseif index == 2 then
DebuffMeAlertLeft:SetText(txt)
elseif index == 3 then
DebuffMeAlertTop:SetText(txt)
elseif index == 4 then
DebuffMeAlertRight:SetText(txt)
end
end
function DebuffMe.SetHidden(index, hide)
if index == 1 then
DebuffMeAlertMiddle:SetHidden(hide)
elseif index == 2 then
DebuffMeAlertLeft:SetHidden(hide)
elseif index == 3 then
DebuffMeAlertTop:SetHidden(hide)
elseif index == 4 then
DebuffMeAlertRight:SetHidden(hide)
end
end
function DebuffMe.SetColor(index, immun)
if index == 1 then
if immun then
DebuffMeAlertMiddle:SetColor(unpack{1,0,0})
else
DebuffMeAlertMiddle:SetColor(unpack{1,1,1}) --FFFFFF
end
elseif index == 2 then
if immun then
DebuffMeAlertLeft:SetColor(unpack{1,0,0})
else
DebuffMeAlertLeft:SetColor(unpack{0,(170/255),1}) --00AAFF
end
elseif index == 3 then
if immun then
DebuffMeAlertTop:SetColor(unpack{1,0,0})
else
DebuffMeAlertTop:SetColor(unpack{(56/255),(195/255),0}) --38C300
end
elseif index == 4 then
if immun then
DebuffMeAlertRight:SetColor(unpack{1,0,0})
else
DebuffMeAlertRight:SetColor(unpack{(236/255),(60/255),0}) --EC3C00
end
end
end
function DebuffMe.Update()
local currentTargetHP, maxTargetHP, effmaxTargetHP = GetUnitPower("reticleover", POWERTYPE_HEALTH)
local TXT = ""
DebuffMeAlert:SetHidden(false)
if maxTargetHP > DebuffMe.savedVariables.thresholdHP * 1000000 then --only if target got more than 1M hp
for index = 1, #DebuffMe.Debuff_Show do
if DebuffMe.Debuff_Show[index] ~= 1 then
TXT = DebuffMe.Calcul(index)
DebuffMe.SetText(index, TXT)
DebuffMe.SetHidden(index, false)
DebuffMe.SetColor(index, DebuffMe.flag_immunity)
else
DebuffMe.SetHidden(index, true)
end
end
else
DebuffMeAlert:SetHidden(true)
end
end
function DebuffMe.EventRegister()
EVENT_MANAGER:UnregisterForUpdate(DebuffMe.name .. "Update")
if IsUnitInCombat("player") then
if DebuffMe.SlowMode then
EVENT_MANAGER:RegisterForUpdate(DebuffMe.name .. "Update", 333, DebuffMe.Update)
else
EVENT_MANAGER:RegisterForUpdate(DebuffMe.name .. "Update", 100, DebuffMe.Update)
end
else
DebuffMeAlert:SetHidden(not DebuffMe.savedVariables.AlwaysShowAlert)
end
end
--------------
---- INIT ----
--------------
function DebuffMe.InitUI()
DebuffMeAlert:SetHidden(true)
DebuffMeAlert:ClearAnchors()
if (DebuffMe.savedVariables.OffsetX ~= 0) and (DebuffMe.savedVariables.OffsetY ~= 0) then --recover last position
DebuffMeAlert:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, DebuffMe.savedVariables.OffsetX, DebuffMe.savedVariables.OffsetY)
else --initial position (center)
DebuffMeAlert:SetAnchor(CENTER, GuiRoot, CENTER, DebuffMe.savedVariables.OffsetX, DebuffMe.savedVariables.OffsetY)
end
DebuffMeAlertLeft:SetAnchor(CENTER, DebuffMeAlertMiddle, CENTER, -8*DebuffMe.savedVariables.Spacing, DebuffMe.savedVariables.Spacing)
DebuffMeAlertTop:SetAnchor(CENTER, DebuffMeAlertMiddle, CENTER, 0, -6*DebuffMe.savedVariables.Spacing)
DebuffMeAlertRight:SetAnchor(CENTER, DebuffMeAlertMiddle, CENTER, 8*DebuffMe.savedVariables.Spacing, DebuffMe.savedVariables.Spacing)
DebuffMe.SetFontSize(DebuffMeAlertMiddle, (DebuffMe.savedVariables.FontSize * 0.9))
DebuffMe.SetFontSize(DebuffMeAlertLeft, DebuffMe.savedVariables.FontSize)
DebuffMe.SetFontSize(DebuffMeAlertTop, DebuffMe.savedVariables.FontSize)
DebuffMe.SetFontSize(DebuffMeAlertRight, DebuffMe.savedVariables.FontSize)
end
function DebuffMe.GetSavedFor1_4()
DebuffMe.Debuff_Show[1] = DebuffMe.savedVariables.Debuff_M
DebuffMe.Debuff_Show[2] = DebuffMe.savedVariables.Debuff_L
DebuffMe.Debuff_Show[3] = DebuffMe.savedVariables.Debuff_T
DebuffMe.Debuff_Show[4] = DebuffMe.savedVariables.Debuff_R
DebuffMe.savedVariables.Debuff_Show = DebuffMe.Debuff_Show
DebuffMe.savedVariables.Debuff_M = nil
DebuffMe.savedVariables.Debuff_L = nil
DebuffMe.savedVariables.Debuff_T = nil
DebuffMe.savedVariables.Debuff_R = nil
end
function DebuffMe.AddCustomDataList()
--remove from base table
while #DebuffMe.DebuffList >= 19 do
for i = 19, #DebuffMe.DebuffList do
table.remove(DebuffMe.DebuffList, i)
table.remove(DebuffMe.TransitionTable, i)
table.remove(DebuffMe.Abbreviation, i)
table.remove(DebuffMe.CustomAbilityNameWithID, DebuffMe.TransitionTable[i])
end
end
for i = 1, #DebuffMe.CustomDataList.name do
table.insert( DebuffMe.DebuffList, DebuffMe.CustomDataList.name[i]) --name
table.insert( DebuffMe.TransitionTable, DebuffMe.CustomDataList.id[i]) --id
table.insert( DebuffMe.CustomAbilityNameWithID, DebuffMe.CustomDataList.id[i],
GetAbilityName(DebuffMe.CustomDataList.id[i])) --namewithid
table.insert( DebuffMe.Abbreviation, DebuffMe.CustomDataList.abbreviation[i]) --abbreviation
end
if RemoveDebuff_dropdown ~= nil then
RemoveDebuff_dropdown:UpdateChoices()
end
if RightDebuff_dropdown ~= nil then
RightDebuff_dropdown:UpdateChoices()
end
if LeftDebuff_dropdown ~= nil then
LeftDebuff_dropdown:UpdateChoices()
end
if MainDebuff_dropdown ~= nil then
MainDebuff_dropdown:UpdateChoices()
end
if TopDebuff_dropdown ~= nil then
TopDebuff_dropdown:UpdateChoices()
end
end
--function DebuffMe.Test()
--end
function DebuffMe:Initialize()
--Saved Variables
DebuffMe.savedVariables = ZO_SavedVars:New("DebuffMeVariables", 1, nil, DebuffMe.Default)
--Custom table
DebuffMe.CustomDataList = DebuffMe.savedVariables.CustomDataList
DebuffMe.AddCustomDataList()
--Settings
DebuffMe.CreateSettingsWindow()
--UI
DebuffMe.InitUI()
--Variables
DebuffMe.Debuff_Show = DebuffMe.savedVariables.Debuff_Show
DebuffMe.SlowMode = DebuffMe.savedVariables.SlowMode
if DebuffMe.savedVariables.Debuff_M ~= nil and DebuffMe.savedVariables.Debuff_L ~= nil
and DebuffMe.savedVariables.Debuff_T ~= nil and DebuffMe.savedVariables.Debuff_R ~= nil then
--get the previous values
DebuffMe.GetSavedFor1_4()
end
--Events
EVENT_MANAGER:RegisterForEvent(DebuffMe.name, EVENT_RETICLE_TARGET_CHANGED, DebuffMe.EventRegister)
EVENT_MANAGER:RegisterForEvent(DebuffMe.name, EVENT_PLAYER_ACTIVATED, DebuffMe.EventRegister)
EVENT_MANAGER:RegisterForEvent(DebuffMe.name, EVENT_PLAYER_COMBAT_STATE, DebuffMe.EventRegister)
local altarID = {39489, 41967, 41958}
for i = 1, #altarID do
EVENT_MANAGER:RegisterForEvent(DebuffMe.name .. "Altar" .. i, EVENT_EFFECT_CHANGED, DebuffMe.AltarTimer)
EVENT_MANAGER:AddFilterForEvent(DebuffMe.name .. "Altar" .. i, EVENT_EFFECT_CHANGED, REGISTER_FILTER_ABILITY_ID, altarID[i])
end
--Dev Part
--SLASH_COMMANDS["/flotest"] = function() DebuffMe.Test() end
EVENT_MANAGER:UnregisterForEvent(DebuffMe.name, EVENT_ADD_ON_LOADED)
end
function DebuffMe.SaveLoc()
DebuffMe.savedVariables.OffsetX = DebuffMeAlert:GetLeft()
DebuffMe.savedVariables.OffsetY = DebuffMeAlert:GetTop()
end
function DebuffMe.OnAddOnLoaded(event, addonName)
if addonName ~= DebuffMe.name then return end
DebuffMe:Initialize()
end
EVENT_MANAGER:RegisterForEvent(DebuffMe.name, EVENT_ADD_ON_LOADED, DebuffMe.OnAddOnLoaded)
|
local _G = require "_G"
local error = _G.error
local luatype = _G.type
local pairs = _G.pairs
local require = _G.require
local select = _G.select --[[VERBOSE]] local verbose = require "oil.verbose"
local TypeCheckers = {}
local module = {
Exception = require "oil.Exception",
TypeCheckers = TypeCheckers,
}
function module.results(...)
if ... == nil then error(select(2, ...), 2) end
return ...
end
function module.illegal(value, description, except)
error(module.Exception{
"$value is a illegal $valuekind",
error = except or "badvalue",
value = value,
valuekind = description,
}, 2)
end
function module.type(value, expected, description, except)
local actual = luatype(value)
if actual == expected then
return true
else
local checker = TypeCheckers[expected]
if checker then
if checker(value) then return true end
else
for pattern, checker in pairs(TypeCheckers) do
local result = expected:match(pattern)
if result then
result = checker(value, result)
if result
then return result
else break
end
end
end
end
end
error(module.Exception{
"$value is a illegal $valuekind ($expectedtype expected, got $actualtype)",
error = except or "badvalue",
expectedtype = expected,
actualtype = actual,
value = value,
valuekind = description,
}, 2)
end
return module
|
--[[
LPEGLJ
lpvm.lua
Virtual machine
Copyright (C) 2014 Rostislav Sacek.
based on LPeg v0.12 - PEG pattern matching for Lua
Lua.org & PUC-Rio written by Roberto Ierusalimschy
http://www.inf.puc-rio.br/~roberto/lpeg/
** 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.
**
** [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
--]]
local ffi = require"ffi"
local lpcap = require"vendor/lpeglj/lpcap"
local lpprint = require"vendor/lpeglj/lpprint" --only for debug purpose
local band, rshift, lshift = bit.band, bit.rshift, bit.lshift
-- {======================================================
-- Virtual Machine
-- =======================================================
-- Interpret the result of a dynamic capture: false -> fail;
-- true -> keep current position; number -> next position.
-- Return new subject position. 'fr' is stack index where
-- is the result; 'curr' is current subject position; 'limit'
-- is subject's size.
local IAny = 0 -- if no char, fail
local IChar = 1 -- if char != val, fail
local ISet = 2 -- if char not in val, fail
local ITestAny = 3 -- in no char, jump to 'offset'
local ITestChar = 4 -- if char != val, jump to 'offset'
local ITestSet = 5 -- if char not in val, jump to 'offset'
local ISpan = 6 -- read a span of chars in val
local IBehind = 7 -- walk back 'val' characters (fail if not possible)
local IRet = 8 -- return from a rule
local IEnd = 9 -- end of pattern
local IChoice = 10 -- stack a choice; next fail will jump to 'offset'
local IJmp = 11 -- jump to 'offset'
local ICall = 12 -- call rule at 'offset'
local IOpenCall = 13 -- call rule number 'offset' (must be closed to a ICall)
local ICommit = 14 -- pop choice and jump to 'offset'
local IPartialCommit = 15 -- update top choice to current position and jump
local IBackCommit = 16 -- "fails" but jump to its own 'offset'
local IFailTwice = 17 -- pop one choice and then fail
local IFail = 18 -- go back to saved state on choice and jump to saved offset
local IGiveup = 19 -- internal use
local IFullCapture = 20 -- complete capture of last 'off' chars
local IOpenCapture = 21 -- start a capture
local ICloseCapture = 22
local ICloseRunTime = 23
local Cclose = 0
local Cposition = 1
local Cconst = 2
local Cbackref = 3
local Carg = 4
local Csimple = 5
local Ctable = 6
local Cfunction = 7
local Cquery = 8
local Cstring = 9
local Cnum = 10
local Csubst = 11
local Cfold = 12
local Cruntime = 13
local Cgroup = 14
local maxstack = 100
local maxcapturedefault = 100
local maxmemo = 1000
local usememoization = false
local FAIL = -1
local LRFAIL = -1
local VOID = -2
ffi.cdef[[
typedef
struct {
int p;
int s;
int caplevel;
int pA;
int X;
int valuetabletop;
int memos;
} STACK;
typedef
struct {
int s;
int siz;
int idx;
int kind;
} CAPTURE;
]]
local function resdyncaptures(fr, curr, limit, checkstreamlen)
local typ = type(fr)
if not fr then -- false value?
return FAIL -- and fail
elseif typ == 'boolean' then -- true?
return curr -- keep current position
else
local res = fr -- new position
if res < curr or (limit and res > limit) or (not limit and checkstreamlen and not checkstreamlen(res - 2)) then
error("invalid position returned by match-time capture", 0)
end
return res
end
assert(false)
end
-- Add capture values returned by a dynamic capture to the capture list
-- 'base', nested inside a group capture. 'fd' indexes the first capture
-- value, 'n' is the number of values (at least 1).
local function adddyncaptures(s, base, index, n, fd, valuetable)
-- Cgroup capture is already there
assert(base[index].kind == Cgroup and base[index].siz == 0)
local ind = #valuetable + 1
valuetable[ind] = 0
base[index].idx = ind -- make it an anonymous group
base[index + 1] = {}
for i = 1, n do -- add runtime captures
base[index + i].kind = Cruntime
base[index + i].siz = 1 -- mark it as closed
ind = #valuetable + 1
valuetable[ind] = fd[i + 1]
base[index + i].idx = ind -- stack index of capture value
base[index + i].s = s
base[index + i + 1] = {}
end
base[index + n + 1].kind = Cclose -- close group
base[index + n + 1].siz = 1
base[index + n + 1].s = s
base[index + n + 2] = {}
end
-- Opcode interpreter
local function match(stream, last, o, s, op, valuetable, ...)
local arg = { ... }
local argcount = select('#', ...)
local len = #o
local ptr = ffi.cast('const unsigned char*', o)
s = s - 1
local stackptr = 0 -- point to first empty slot in stack
local captop = 0 -- point to first empty slot in captures
local STACK = ffi.new("STACK[?]", maxstack)
local CAPTURE = ffi.new("CAPTURE[?]", maxcapturedefault)
local CAPTURESTACK = { { capture = CAPTURE, captop = captop, maxcapture = maxcapturedefault } }
local capturestackptr = #CAPTURESTACK
local maxcapture = maxcapturedefault
local stacklimit = maxstack
local L = {}
local Memo1, Memo2 = {}, {}
local memoind = 0
local maxpointer = 2 ^ math.ceil(math.log(op.size) / math.log(2))
local p = 0 -- current instruction
STACK[stackptr].s = VOID
STACK[stackptr].p = FAIL
STACK[stackptr].X = VOID
STACK[stackptr].memos = VOID
stackptr = stackptr + 1
local streambufsize = 2 ^ 8
local streambufsizemask = streambufsize - 1 -- faster modulo
local streambufs = {}
local streambufoffset = 0
local streamstartbuffer = 0
local streambufferscount = 0
local function deletestreambuffers()
local min = math.huge
for i = stackptr - 1, 1, -1 do
local val = STACK[i].s
if val >= 0 then
min = math.min(val, min)
end
end
for i = captop - 1, 0, -1 do
local val = CAPTURE[i].s
if val >= 0 then
min = math.min(val, min)
end
end
for i = streamstartbuffer + 1, streambufoffset, streambufsize do
if i + streambufsize < min then
streambufs[i] = nil
streambufferscount = streambufferscount - 1
else
streamstartbuffer = i - 1
break
end
end
end
local function addstreamdata(s, last)
local len = #s
local srcoffset = 0
if streambufferscount > 128 then
deletestreambuffers()
end
repeat
local offset = bit.band(streambufoffset, streambufsizemask)
if offset > 0 then
local index = streambufoffset - offset + 1
local count = math.min(len, streambufsize - offset)
ffi.copy(streambufs[index] + offset, s:sub(srcoffset + 1, srcoffset + 1 + count), count)
len = len - count
srcoffset = srcoffset + count
streambufoffset = streambufoffset + count
end
if len > 0 then
local index = streambufoffset - (bit.band(streambufoffset, streambufsizemask)) + 1
local buf = ffi.new('unsigned char[?]', streambufsize)
streambufferscount = streambufferscount + 1
streambufs[index] = buf
local count = math.min(len, streambufsize)
ffi.copy(buf, s:sub(srcoffset + 1, srcoffset + 1 + count), count)
len = len - count
srcoffset = srcoffset + count
streambufoffset = streambufoffset + count
end
until len == 0
end
local function getstreamchar(s)
local offset = bit.band(s, streambufsizemask)
local index = s - offset + 1
return streambufs[index][offset]
end
local function getstreamstring(st, en) -- TODO Optimalize access
local str = {}
if last and en < 0 then
en = streambufoffset + en + 1
end
for i = st - 1, en - 1 do
--assert(checkstreamlen(i)) --TODO Range test
str[#str + 1] = string.char(getstreamchar(i))
end
return table.concat(str)
end
local function checkstreamlen(s)
local str
while true do
if s < streambufoffset then
return true
else
if last then
return false
end
local min = math.huge
for i = stackptr - 1, 1, -1 do
local val = STACK[i].caplevel
if val >= 0 then
min = math.min(val, min)
end
end
local range = (min < math.huge) and min or captop
local n, out, outindex = lpcap.getcapturesruntime(CAPTURE, getstreamstring, range, valuetable, unpack(arg, 1, argcount))
if n > 0 then
for i = 0, captop - n do
ffi.copy(CAPTURE + i, CAPTURE + i + n, ffi.sizeof('CAPTURE'))
end
for i = stackptr - 1, 1, -1 do
local val = STACK[i].caplevel
if val >= 0 then
STACK[i].caplevel = STACK[i].caplevel - n
end
end
captop = captop - n
end
str, last = coroutine.yield(1, unpack(out, 1, outindex))
addstreamdata(str)
end
end
end
local function doublecapture()
maxcapture = maxcapture * 2
local NEWCAPTURE = ffi.new("CAPTURE[?]", maxcapture)
ffi.copy(NEWCAPTURE, CAPTURE, ffi.sizeof('CAPTURE') * captop)
CAPTURE = NEWCAPTURE
CAPTURESTACK[capturestackptr].capture = CAPTURE
CAPTURESTACK[capturestackptr].maxcapture = maxcapture
end
local function pushcapture()
CAPTURE[captop].idx = op.p[p].offset
CAPTURE[captop].kind = band(op.p[p].val, 0x0f)
captop = captop + 1
p = p + 1
if captop >= maxcapture then
doublecapture()
end
end
local function fail()
-- pattern failed: try to backtrack
local X
repeat -- remove pending calls
stackptr = stackptr - 1
s = STACK[stackptr].s
X = STACK[stackptr].X
if usememoization and s == FAIL and STACK[stackptr].memos ~= VOID then
Memo1[STACK[stackptr].pA + STACK[stackptr].memos * maxpointer] = FAIL
Memo2[STACK[stackptr].pA + STACK[stackptr].memos * maxpointer] = FAIL
end
if X == LRFAIL then
CAPTURESTACK[capturestackptr] = nil
capturestackptr = capturestackptr - 1
CAPTURE = CAPTURESTACK[capturestackptr].capture
maxcapture = CAPTURESTACK[capturestackptr].maxcapture
L[STACK[stackptr].pA + s * maxpointer] = nil
end
until s ~= FAIL and X ~= LRFAIL
p = STACK[stackptr].p
if p ~= FAIL then
for i = #valuetable, STACK[stackptr].valuetabletop + 1, -1 do
table.remove(valuetable)
end
if X ~= VOID then
s = X
capturestackptr = capturestackptr - 1
CAPTURE = CAPTURESTACK[capturestackptr].capture
captop = CAPTURESTACK[capturestackptr].captop
maxcapture = CAPTURESTACK[capturestackptr].maxcapture
local capture = L[STACK[stackptr].pA + STACK[stackptr].s * maxpointer].capturecommit
while captop + capture.captop >= maxcapture do
doublecapture()
end
ffi.copy(CAPTURE + captop, capture.capture, capture.captop * ffi.sizeof('CAPTURE'))
captop = captop + capture.captop
CAPTURESTACK[capturestackptr + 1] = nil
L[STACK[stackptr].pA + STACK[stackptr].s * maxpointer] = nil
else
captop = STACK[stackptr].caplevel
end
end
end
local function doublestack()
if stackptr >= maxstack then
error("too many pending calls/choices", 0)
end
stacklimit = stacklimit * 2
stacklimit = (stacklimit > maxstack) and maxstack or stacklimit
local NEWSTACK = ffi.new("STACK[?]", stacklimit)
ffi.copy(NEWSTACK, STACK, ffi.sizeof('STACK') * stackptr)
STACK = NEWSTACK
end
if stream then
addstreamdata(o)
len = nil
o = nil
ptr = nil
end
while true do
--[[ Only for debug
io.write(("s: |%s| stck:%d, caps:%d \n"):format(s + 1, stackptr, captop))
if p ~= FAIL then
lpprint.printinst(op.p, p, valuetable)
lpprint.printcaplist(CAPTURE, captop, valuetable)
end
--]]
if p == FAIL then return -1 end
local code = op.p[p].code
if code == IEnd then
CAPTURE[captop].kind = Cclose
CAPTURE[captop].s = -1
return 0, lpcap.getcaptures(CAPTURE, o, getstreamstring, s + 1, valuetable, ...)
elseif code == IRet then
if STACK[stackptr - 1].X == VOID then
stackptr = stackptr - 1
p = STACK[stackptr].p
if usememoization and STACK[stackptr].memos ~= VOID then
local dif = captop - STACK[stackptr].caplevel
local caps
if dif > 0 then
caps = ffi.new("CAPTURE[?]", dif)
ffi.copy(caps, CAPTURE + captop - dif, dif * ffi.sizeof('CAPTURE'))
end
local val = { s, dif, caps }
Memo1[STACK[stackptr].pA + STACK[stackptr].memos * maxpointer] = val
Memo2[STACK[stackptr].pA + STACK[stackptr].memos * maxpointer] = val
end
else
local X = STACK[stackptr - 1].X
if X == LRFAIL or s > X then
STACK[stackptr - 1].X = s
p = STACK[stackptr - 1].pA
s = STACK[stackptr - 1].s
local lambda = L[p + s * maxpointer]
lambda.X = STACK[stackptr - 1].X
STACK[stackptr - 1].caplevel = captop
STACK[stackptr - 1].valuetabletop = #valuetable
CAPTURESTACK[capturestackptr].captop = captop
lambda.capturecommit = CAPTURESTACK[capturestackptr]
captop = 0
CAPTURE = ffi.new("CAPTURE[?]", maxcapturedefault)
CAPTURESTACK[capturestackptr] = { capture = CAPTURE, captop = captop, maxcapture = maxcapturedefault }
maxcapture = maxcapturedefault
else
stackptr = stackptr - 1
p = STACK[stackptr].p
s = STACK[stackptr].X
for i = #valuetable, STACK[stackptr].valuetabletop + 1, -1 do
table.remove(valuetable)
end
local lambda = L[STACK[stackptr].pA + STACK[stackptr].s * maxpointer]
capturestackptr = capturestackptr - 1
CAPTURE = CAPTURESTACK[capturestackptr].capture
captop = CAPTURESTACK[capturestackptr].captop
maxcapture = CAPTURESTACK[capturestackptr].maxcapture
local capture = lambda.capturecommit
while captop + capture.captop >= maxcapture do
doublecapture()
end
ffi.copy(CAPTURE + captop, capture.capture, capture.captop * ffi.sizeof('CAPTURE'))
captop = captop + capture.captop
CAPTURESTACK[capturestackptr + 1] = nil
L[STACK[stackptr].pA + STACK[stackptr].s * maxpointer] = nil
end
end
elseif code == IAny then
if o and (s < len) or checkstreamlen(s) then
p = p + 1
s = s + 1
else
fail()
end
elseif code == ITestAny then
if o and (s < len) or checkstreamlen(s) then
p = p + 1
else
p = p + op.p[p].offset
end
elseif code == IChar then
if o and (s < len and ptr[s] == op.p[p].val) or (checkstreamlen(s) and getstreamchar(s) == op.p[p].val) then
p = p + 1
s = s + 1
else
fail()
end
elseif code == ITestChar then
if o and (s < len and ptr[s] == op.p[p].val) or (checkstreamlen(s) and getstreamchar(s) == op.p[p].val) then
p = p + 1
else
p = p + op.p[p].offset
end
elseif code == ISet then
local c = o and ptr[s] or (checkstreamlen(s) and getstreamchar(s))
local set = valuetable[op.p[p].val]
if (o and s < len or checkstreamlen(s)) and band(set[rshift(c, 5)], lshift(1, band(c, 31))) ~= 0 then
p = p + 1
s = s + 1
else
fail()
end
elseif code == ITestSet then
local c = o and ptr[s] or (checkstreamlen(s) and getstreamchar(s))
local set = valuetable[op.p[p].val]
if (o and (s < len) or checkstreamlen(s)) and band(set[rshift(c, 5)], lshift(1, band(c, 31))) ~= 0 then
p = p + 1
else
p = p + op.p[p].offset
end
elseif code == IBehind then
local n = op.p[p].val
if n > s then
fail()
else
s = s - n
p = p + 1
end
elseif code == ISpan then
while o and (s < len) or checkstreamlen(s) do
local c = o and ptr[s] or getstreamchar(s)
local set = valuetable[op.p[p].val]
if band(set[rshift(c, 5)], lshift(1, band(c, 31))) == 0 then
break
end
s = s + 1
end
p = p + 1
elseif code == IJmp then
p = p + op.p[p].offset
elseif code == IChoice then
if stackptr == stacklimit then
doublestack()
end
STACK[stackptr].X = VOID
STACK[stackptr].p = p + op.p[p].offset
STACK[stackptr].s = s
STACK[stackptr].caplevel = captop
STACK[stackptr].valuetabletop = #valuetable
stackptr = stackptr + 1
p = p + 1
elseif code == ICall then
if stackptr == stacklimit then
doublestack()
end
local k = bit.band(op.p[p].val, 0xffff)
if k == 0 then
local pA = p + op.p[p].offset
local memo = Memo1[pA + s * maxpointer]
if usememoization and memo and type(memo) == 'table' then
s = memo[1]
local dif = memo[2]
if dif > 0 then
while captop + dif >= maxcapture do
doublecapture()
end
local caps = memo[3]
ffi.copy(CAPTURE + captop, caps, dif * ffi.sizeof('CAPTURE'))
captop = captop + dif
end
p = p + 1
else
STACK[stackptr].X = VOID
STACK[stackptr].s = FAIL
STACK[stackptr].p = p + 1 -- save return address
STACK[stackptr].pA = pA
STACK[stackptr].memos = s
STACK[stackptr].caplevel = captop
stackptr = stackptr + 1
p = pA
if usememoization then
if not memo then
memoind = memoind + 1
if memoind > maxmemo then
memoind = 0
Memo1 = Memo2
Memo2 = {}
end
elseif memo == FAIL then
fail()
end
end
end
else
local pA = p + op.p[p].offset
local X = L[pA + s * maxpointer]
if not X then
CAPTURESTACK[capturestackptr].captop = captop
local capture = ffi.new("CAPTURE[?]", maxcapturedefault)
capturestackptr = capturestackptr + 1
CAPTURESTACK[capturestackptr] = { capture = capture, captop = captop, maxcapture = maxcapturedefault }
CAPTURE = capture
maxcapture = maxcapturedefault
captop = 0
L[pA + s * maxpointer] = { X = LRFAIL, k = k, cs = capturestackptr }
STACK[stackptr].p = p + 1
STACK[stackptr].pA = pA
STACK[stackptr].s = s
STACK[stackptr].X = LRFAIL
stackptr = stackptr + 1
p = pA
elseif X.X == LRFAIL or k < X.k then
fail()
else
local capture = X.capturecommit
while captop + capture.captop >= maxcapture do
doublecapture()
end
ffi.copy(CAPTURE + captop, capture.capture, capture.captop * ffi.sizeof('CAPTURE'))
captop = captop + capture.captop
p = p + 1
s = X.X
end
end
elseif code == ICommit then
stackptr = stackptr - 1
p = p + op.p[p].offset
elseif code == IPartialCommit then
STACK[stackptr - 1].s = s
STACK[stackptr - 1].caplevel = captop
STACK[stackptr - 1].valuetabletop = #valuetable
p = p + op.p[p].offset
elseif code == IBackCommit then
stackptr = stackptr - 1
s = STACK[stackptr].s
captop = STACK[stackptr].caplevel
for i = #valuetable, STACK[stackptr].valuetabletop + 1, -1 do
table.remove(valuetable)
end
p = p + op.p[p].offset
elseif code == IFailTwice then
stackptr = stackptr - 1
fail()
elseif code == IFail then
fail()
elseif code == ICloseRunTime then
for i = 0, stackptr - 1 do -- invalidate memo
STACK[i].memos = VOID
end
local cs = {}
cs.s = o
cs.stream = getstreamstring
cs.ocap = CAPTURE
cs.ptop = arg
cs.ptopcount = argcount
local out = { outindex = 0, out = {} }
local n = lpcap.runtimecap(cs, captop, s + 1, out, valuetable) -- call function
captop = captop - n
local res = resdyncaptures(out.out[1], s + 1, len and len + 1, checkstreamlen) -- get result
if res == FAIL then -- fail?
fail()
else
s = res - 1 -- else update current position
n = out.outindex - 1 -- number of new captures
if n > 0 then -- any new capture?
captop = captop + n + 2
while captop >= maxcapture do
doublecapture()
end
-- add new captures to 'capture' list
adddyncaptures(s + 1, CAPTURE, captop - n - 2, n, out.out, valuetable)
end
p = p + 1
end
elseif code == ICloseCapture then
local s1 = s + 1
assert(captop > 0)
-- if possible, turn capture into a full capture
if CAPTURE[captop - 1].siz == 0 and
s1 - CAPTURE[captop - 1].s < 255 then
CAPTURE[captop - 1].siz = s1 - CAPTURE[captop - 1].s + 1
p = p + 1
else
CAPTURE[captop].siz = 1
CAPTURE[captop].s = s + 1
pushcapture()
end
elseif code == IOpenCapture then
CAPTURE[captop].siz = 0
CAPTURE[captop].s = s + 1
pushcapture()
elseif code == IFullCapture then
CAPTURE[captop].siz = band(rshift(op.p[p].val, 4), 0x0F) + 1 -- save capture size
CAPTURE[captop].s = s + 1 - band(rshift(op.p[p].val, 4), 0x0F)
pushcapture()
else
assert(false)
end
end
end
local function setmax(val)
maxstack = val
if maxstack < 100 then
maxstack = 100
end
end
local function enablememoization(val)
usememoization = val
end
-- ======================================================
return {
match = match,
setmax = setmax,
enablememoization = enablememoization
}
|
local Players = game:GetService("Players")
local playerState = require(script.Parent.playerState)
return (function(state,action)
state = state or {}
if action.player then
local newPlayerState = {}
for _,player in pairs(Players:GetPlayers()) do
local playerKey = "player_"..player.UserId
if player == action.player then -- we need to rebuild this player state
newPlayerState[playerKey] = playerState(state[playerKey], action)
else -- this state is untouched
newPlayerState[playerKey] = state[playerKey]
end
end
return newPlayerState
end
return state
end)
|
local ComponentDataArray = {}
ECS.ComponentDataArray = ComponentDataArray
function ComponentDataArray.Create( iterator, length, componentName )
assert(iterator~=nil, "iterator should not be nil!")
assert(length~=nil, "length should not be nil!")
assert(componentName~=nil, "componentName should not be nil!")
local array = {
m_Iterator=iterator,
m_Length=length,
m_ComponentTypeName=componentName,
m_Data = {},
m_Cache = {
CachedPtr=nil, CachedBeginIndex=0, CachedEndIndex=0, CachedSizeOf=0, IsWriting=false
},
}
ComponentDataArray.InitMetaTable(array)
return array
end
local get_fun = function ( t, index )
if index < 1 or index > t.m_Length then
return nil
end
if index < t.m_Cache.CachedBeginIndex or index >= t.m_Cache.CachedEndIndex then
t.m_Iterator:MoveToEntityIndexAndUpdateCache(index, t.m_Cache, false)
end
return ECS.ChunkDataUtility.ReadComponentFromArray(t.m_Cache.CachedPtr, index, t.m_ComponentTypeName, t.m_Data)
end
local set_fun = function ( t, k )
end
local get_len = function ( t )
print('Cat:ComponentDataArray.lua[39] t.m_Length', t.m_Length)
return t.m_Length
end
function ComponentDataArray.InitMetaTable( array )
local meta_tbl = {}
meta_tbl.__index = get_fun
meta_tbl.__len = get_len
setmetatable(array, meta_tbl)
end
-- function ComponentDataArray:GetChunkArray( startIndex, maxCount )
-- local count
-- local ptr = GetUnsafeChunkPtr(startIndex, maxCount, count, true)
-- local arr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(ptr, count, Allocator.Invalid)
-- return arr
-- end
return ComponentDataArray
|
local luarpc = require("luarpc")
local port1 = 0
if arg[1] then
port1 = arg[1]
else
print("Choose a port for server 1")
port1 = io.read("*n")
end
local IP = "0.0.0.0" -- IP default val
if arg[2] then
IP = arg[2]
end
-- interface file
local idl = io.open("interface.txt", "r"):read("*a")
local p1 = luarpc.createProxy(IP, port1, idl)
--local ans = p1:boo(10)
--print("The ans 1 is " .. ans[1])
--local t,p = p1:boo(10)
--print("t: ".. t .. " and p: " .. p)
-- local p2 = luarpc.createProxy(IP, port2, idl)
local r, s = p1:foo(3, "alo", {nome = "Aaa", idade = 20, peso = 55.0}, 1)
-- local t, p = p2:boo(10)
|
local class = require 'ext.class'
local table = require 'ext.table'
local math = require 'ext.math'
local Binary = require 'symmath.op.Binary'
local symmath
local mul = class(Binary)
mul.precedence = 3
mul.name = '*'
mul.nameForExporterTable = {}
mul.nameForExporterTable.LaTeX = '' -- implicit mul, no symbol, but export/LaTeX.lua's symmath.op.mul exporter already has custom code, so you don't need this...
--[[
-- auto flatten any muls
-- this is useful for find/replace, since otherwise the API user has to simplify() everything to get it to match what the CAS produces
-- the problem is, this modifies in-place, which breaks our cardinal rule (and a lot of our code)
function mul:init(...)
mul.super.init(self, ...)
self:flatten()
end
--]]
function mul:flatten()
for i=#self,1,-1 do
if mul:isa(self[i]) then
local x = table.remove(self, i)
for j=#x,1,-1 do
table.insert(self, i, x[j]:clone():flatten())
end
end
end
return self
end
function mul:flattenAndClone()
for i=#self,1,-1 do
local ch = self[i]
if mul:isa(ch) then
local expr = {table.unpack(self)}
table.remove(expr, i)
for j=#ch,1,-1 do
local chch = ch[j]
table.insert(expr, i, chch)
end
return mul(table.unpack(expr))
end
end
end
function mul:isFlattened()
for i,ch in ipairs(self) do
if mul:isa(ch) then return false end
end
return true
end
function mul:evaluateDerivative(deriv, ...)
symmath = symmath or require 'symmath'
local add = symmath.op.add
local sums = table()
for i=1,#self do
local terms = table()
for j=1,#self do
if i == j then
terms:insert(deriv(self[j]:clone(), ...))
else
terms:insert(self[j]:clone())
end
end
if #terms == 1 then
sums:insert(terms[1])
else
sums:insert(mul(terms:unpack()))
end
end
if #sums == 1 then
return sums[1]
else
return add(sums:unpack())
end
end
mul.removeIfContains = require 'symmath.commutativeRemove'
--local function print(...) return printbr(...) end
-- now that we've got matrix multilpication, this becomes more difficult...
-- non-commutative objects (matrices) need to be compared in-order
-- commutative objects can be compared in any order
function mul.match(a, b, matches)
symmath = symmath or require 'symmath'
local Wildcard = symmath.Wildcard
local Constant = symmath.Constant
local SingleLine = symmath.export.SingleLine
local Verbose = symmath.export.Verbose
--print("mul.match(a="..Verbose(a)..", b="..Verbose(b)..", matches={"..(matches or table()):mapi(Verbose):concat', '..'}) begin')
matches = matches or table()
-- if 'b' is a mul then fall through
-- this part is only for wildcard matching of the whole expression
if not mul:isa(b) -- if the wildcard is a mul then we want to test it here
and b.wildcardMatches
then
if not b:wildcardMatches(a, matches) then return false end
--print(" matching entire expr "..SingleLine(b).." to "..SingleLine(a))
return (matches[1] or true), table.unpack(matches, 2, table.maxn(matches))
end
if getmetatable(a) ~= getmetatable(b) then return false end
-- NOTICE, this shallow copy means that the metatables are lost, so don't use "a" or "b" as expressions (unless you reset its metatable)
local a = table(a)
local b = table(b)
-- compare things order-independent, remove as you go
-- skip wildcards, do those last
for i=#a,1,-1 do
local ai = a[i]
-- non-commutative compare...
if not ai.mulNonCommutative then
-- table.find uses == uses __eq which ... should ... only pick j if it is mulNonCommutative as well (crossing fingers, it's based on the equality implementation)
--local j = b:find(ai)
local j
for _j=1,#b do
local bj = b[_j]
if not Wildcard:isa(bj)
-- if bj does match then this will fill in the appropriate match and return 'true'
-- if it fails to match then it won't fill in the match and will return false
and ai:match(bj, matches)
then
j = _j
break
end
end
if j then
--print(' mul.match: removing matched terms...')
--print(a[i])
--print(b[j])
a:remove(i)
b:remove(j)
end
end
end
--print("mul.match: what's left after matching commutative non-wildcards:")
--print('a:', a:mapi(SingleLine):concat', ')
--print('b:', b:mapi(SingleLine):concat', ')
-- now compare what's left in-order (since it's non-commutative)
-- skip wildcards, do those last
local function checkWhatsLeft(a, b, matches, indent)
indent=(indent or 0) + 1
local tab = (' '):rep(indent)
-- save the original here
-- upon success, merge the new matches back into the original argument
local origMatches = matches
matches = matches or table()
a = table(a)
b = table(b)
--print(tab.."checking match of what's left with "..#a.." elements")
if #a == 0 and #b == 0 then
--print(tab.."matches - returning true")
return matches[1] or true, table.unpack(matches, 2, table.maxn(matches))
end
-- #a == 0 is fine if b is full of nothing but wildcards
if #b == 0 and #a > 0 then
--print(tab.."has remaining elements -- returning false")
return false
end
-- TODO bi isn't necessarily a wildcard -- it could be an 'mulNonCommutative' term (though nothing does this for multiplication yet)
if #a == 0 and #b ~= 0 then
-- TODO verify that the matches are equal
for _,bi in ipairs(b) do
if not Wildcard:isa(bi) then
--print(tab.."expected bi to be a Wildcard, found "..SingleLine(bi))
return false
end
if bi.atLeast and bi.atLeast > 0 then
--print(tab.."remaining Wildcard expected an expression when none are left, failing")
return false
end
if matches[bi.index] then
--print(tab.."matches["..bi.index.."] tried to set to Constant(1), but it already exists as "..SingleLine(matches[bi.index]).." -- failing")
if matches[bi.index] ~= Constant(1) then
return false
end
else
--print(tab.."setting matches["..bi.index.."] to Constant(1)")
matches[bi.index] = Constant(1)
end
end
end
if not Wildcard:isa(b[1]) then
local a1 = a:remove(1)
local b1 = b:remove(1)
--print(tab.."isn't a wildcard -- recursive call of match on what's left")
-- hmm, what if there's a sub-expression that has wildcard
-- then we need matches
-- then we need to push/pop matches
local firstsubmatch = table()
if not a1:match(b1, firstsubmatch) then
--print(tab.."first match didn't match - failing")
return false
end
for i=1,table.maxn(firstsubmatch) do
if firstsubmatch[i] ~= nil then
if matches[i] ~= nil then
if matches[i] ~= firstsubmatch[i] then
--print(tab.."first submatches don't match previous matches - index "..i.." "..SingleLine(matches[i]).." vs "..SingleLine(firstsubmatch[i]).." - failing")
return false
end
else
--print(tab.."index "..b.index)
--print(tab.."a1: "..SingleLine(a1))
--print(tab.."a: "..a:mapi(SingleLine):concat', ')
--print(tab.."matching mul subexpr from first match "..SingleLine(a1).." index "..b.index.." to "..a:mapi(SingleLine):concat', ')
matches[i] = firstsubmatch[i]
end
end
end
local restsubmatch = table()
if not checkWhatsLeft(a, b, restsubmatch, indent) then
--print(tab.."first match didn't match - failing")
return false
end
for i=1,table.maxn(restsubmatch) do
if restsubmatch[i] ~= nil then
if matches[i] ~= nil then
if matches[i] ~= restsubmatch[i] then
--print(tab.."first submatches don't match previous matches - index "..i.." "..SingleLine(matches[i]).." vs "..SingleLine(firstsubmatch[i]).." - failing")
return false
end
else
--print(tab.."matching mul subexpr from first match "..SingleLine(a1).." index "..b.index.." to "..a:mapi(SingleLine):concat', ')
matches[i] = restsubmatch[i]
end
end
end
-- overlay match matches on what we have already matched so far
-- also write them back to the original argument since we are returning true
for k,v in pairs(matches) do origMatches[k] = v end
return matches[1] or true, table.unpack(matches, 2, table.maxn(matches))
end
--print(tab.."before checking remaining terms, our matches is: "..table.mapi(matches, SingleLine):concat', ')
-- now if we have a wildcard ... try all 0-n possible matches of it
local b1 = b:remove(1)
for matchSize=math.min(#a, b1.atMost or math.huge),(b1.atLeast or 0),-1 do
--print(tab.."checking matches of size "..matchSize)
for a in a:permutations() do
a = table(a)
--print(tab.."checking a permutation "..a:mapi(SingleLine):concat', ')
local b1match = matchSize == 0 and Constant(1)
or matchSize == 1 and a[1]
or setmetatable(a:sub(1, matchSize), mul)
--print(tab.."b1match "..SingleLine(b1match))
local matchesForThisSize = table(matches)
--print(tab.."matchesForThisSize["..b1.index.."] was "..(matchesForThisSize[b1.index] and SingleLine(matchesForThisSize[b1.index]) or 'nil'))
-- this is going to get into a situation of comparing all possible permutations of what's left
-- TODO get rid of this whole recursion system, and just use a permutation iterator
-- then keep trying to match wildcards against what is left until things work
-- you know, with nested wildcard/nonwildcards, we might as well just do this for everything.
if b1match:match(b1, matchesForThisSize) then
--print(tab.."matchesForThisSize["..b1.index.."] is now "..SingleLine(matchesForThisSize[b1.index]))
local suba = a:sub(matchSize+1)
--print(tab.."calling recursively on "..#suba.." terms: "..table.mapi(suba, SingleLine):concat', ')
local didMatch = checkWhatsLeft(suba, b, matchesForThisSize, indent)
--print(tab.."returned results from the sub-checkWhatsLeft : "..table.mapi(results, SingleLine):concat', ')
if didMatch then
--print(tab.."returning that list for matchSize="..matchSize.."...")
-- also write them back to the original argument since we are returning true
for k,v in pairs(matchesForThisSize) do origMatches[k] = v end
return matchesForThisSize[1] or true, table.unpack(matchesForThisSize, 2, table.maxn(matchesForThisSize))
end
--print(tab.."continuing...")
else
--print(tab..Verbose(b1)..':match('..SingleLine(b1match)..') failed')
--print(tab.."the next wildcard had already been matched to "..SingleLine(matchesForThisSize[b1.index]).." when we tried to match it to "..SingleLine(b1match))
end
-- otherwise keep checking
end
end
-- all sized matches failed? return false
--print(tab.."all sized matches failed - failing")
return false
end
-- now what's left in b[i] should all be wildcards
-- we just have to assign them between the a's
-- but if we want mul match to return wildcards of +0 then we can't just rely on a 1-or-more rule
-- for that reason,
return checkWhatsLeft(a,b, matches)
--return (matches[1] or true), table.unpack(matches, 2, table.maxn(matches))
end
-- copy of op/add.wildcardMatches, just like match()
function mul:wildcardMatches(a, matches)
symmath = symmath or require 'symmath'
local Constant = symmath.Constant
local Wildcard = symmath.Wildcard
local add = symmath.op.add
local pow = symmath.op.pow
local SingleLine = symmath.export.SingleLine
local Verbose = symmath.export.Verbose
--print("mul.wildcardMatches(self="..Verbose(self)..", a="..Verbose(a)..", matches={"..matches:mapi(Verbose):concat', '..'})')
-- 'a' is the 'a' in Expression.match(a,b)
-- 'b' is 'self'
local nonWildcards = table()
local wildcards = table()
for _,w in ipairs(self) do
-- TODO what about when add/mul have no sub-wildcards?
if w.wildcardMatches
and w:hasChild(function(x) return Wildcard:isa(x) end)
then
wildcards:insert(w)
else
nonWildcards:insert(w)
end
end
--print("mul.wildcardMatches children: "..table.mapi(self, Verbose):concat', ')
--print("mul.wildcardMatches wildcard children: "..table.mapi(wildcards, Verbose):concat', ')
--print("mul.wildcardMatches non-wildcard children: "..table.mapi(nonWildcards, Verbose):concat', ')
-- Constant(0):match(2 * Wildcard(1))
-- 2 is a non-wildcard, Wildcard(1) is a wildcard
-- but as long as we're inside mul, we just need to match a wildcard to 0
if Constant.isValue(a, 0)
-- make sure we have a single wildcard in the mix
and (#nonWildcards == 0 or #wildcards > 0)
then
local zeroMatches = table(matches)
local failed
-- make sure the matches can match to zero (i.e. no 'dependsOn=x')
for _,w in ipairs(wildcards) do
if not a:match(w, zeroMatches) then
failed = true
break
else
--print("mul.wildcardMatches did match "..a.." to "..w.." with matches "..table.map(zeroMatches, function(v,k,t) return k..'='..v, #t+1 end):concat', ')
end
end
if not failed then
-- wildcardMatches has to write back to 'matches'
for k,v in pairs(zeroMatches) do matches[k] = v end
return matches[1] or true, table.unpack(matches, 2, table.maxn(matches))
end
-- else if we failed then fall through
-- and most likely fail in the next 'return false'
end
if #nonWildcards > 1 then
--print("mul.wildcardMatches too many non-wildcards - failing")
return false
end
local defaultValue = Constant(1)
local matchExpr = a
if #nonWildcards == 1
and #wildcards > 0
then
--print("mul.wildcardMatches matchExpr "..require 'symmath.export.SingleLine'(a))
-- TODO what if we are doing x:match(W{1,atLeast=1} * W{2}) ?
local submatches = table(matches)
if not a:match(nonWildcards[1], submatches) then
--print("mul.wildcardMatches single remaining mul sub-term didn't match first non-wildcard - failing")
--[[
(a = Constant(4)) : match ( b = mul(Constant (2), Wildcard(1)) )
calls (b = mul(Constant (2), Wildcard(1))) : wildcardMatches ( (a = Constant(4)) )
has 1 non-wildcard: Constant(2)
and 1 wildcard: Wildcard(1)
now if (a = Constant(4)) matches (nw[1] = Constant(2)) then the next condition hits
and we continue on with our matched expresssion set to the operator identity of Constant(1)
but if it doesn't match ...
... what if we can just factor one out of the other?
this is a question of the scope of the function:
how much is this tree matching, and how much is this unknown substitution?
tree matching? fail here.
unknown-substitution? set the match to the fraction of
--]]
--[[ unknown-substitution
-- this does fix Constant(4):match(Constant(2) * Wildcard(1))
-- but this causes op/div's pattern matching to a / (b + sqrt(c))
-- to successfully match a nil value
-- TODO this is breaking a lot of integral tests as well
if symmath.matchMulUnknownSubstitution
and #wildcards > 0
then
matchExpr = (a / nonWildcards[1])()
submatches = table(matches)
if matchExpr:match(wildcards[1], submatches) then
for k,v in pairs(matches) do matches[k] = nil end
for k,v in pairs(submatches) do matches[k] = v end
for i=2,#wildcards do defaultValue:match(wildcadrs[i], matches) end
--for i=1,#wildcards do
-- print('wildcards['..wildcards[i].index..'] = '..symmath.export.SingleLine(matches[wildcards[i].index]))
--end
return matches[1] or true, table.unpack(matches, 2, table.maxn(matches))
end
end
--]]
return false
else
-- a:match(nonWildcards[1]) success so keep the matches:
for k,v in pairs(matches) do matches[k] = nil end
for k,v in pairs(submatches) do matches[k] = v end
-- success, so matches have been written
-- a matches nonWildcards[1]
matchExpr = defaultValue
end
end
-- if any of these wildcards needed a term then fail
-- (that will be handled in the mul.match fallthrough
-- which is why mul.match should not call this -- only other non-mul Expressions' .match())
local totalAtLeast = 0
for _,w in ipairs(wildcards) do
if w.atLeast and w.atLeast > 0 then
totalAtLeast = totalAtLeast + w.atLeast
if totalAtLeast > 1 then
--print("mul.wildcardMatches: wildcard needs at least 1, and we have none left - failing")
return false
end
end
end
-- when matching wildcards, make sure to match any with 'atLeast' first
if totalAtLeast == 1 then
for i,w in ipairs(wildcards) do
-- TODO make this work for sub-expressions?
if w.atLeast and w.atLeast > 0 then
if i > 1 then
--print("mul.wildcardMatches moving wildcard with 'atleast' from "..i.." to 1")
table.remove(wildcards, i)
table.insert(wildcards, 1, w)
end
break
end
end
end
-- match all wildcards to zero
local function checkWildcardPermutation(wildcards, matches)
-- match all wildcards to zero
-- test first, so we don't half-set the 'matches' before failing (TODO am I doing this elsewhere in :match()?)
-- TODO w.index IS NOT GUARANTEED, if we have (x):match(W(1) + W(2) * W(3)) and add and mul have wildcardMatches
-- in that case, you need to handle all possible sub-wildcardMatches specifically
--print("mul.wildcardMatches: testing against previous matches table...")
for i,w in ipairs(wildcards) do
local cmpExpr = i == 1 and matchExpr or defaultValue
--print("mul.wildcardMatches: comparing lhs "..Verbose(cmpExpr))
if mul:isa(w) then
error"match() doesn't work with unflattened mul's"
elseif Wildcard:isa(w)
or add:isa(w)
or pow:isa(w)
then
-- check before going through with it
if not cmpExpr:match(w, table(matches)) then
return false
end
else
error("found match(mul(unknown))")
end
end
-- finally set all matches to zero and return 'true'
for i,w in ipairs(wildcards) do
local cmpExpr = i == 1 and matchExpr or defaultValue
if Wildcard:isa(w) then
--print('mul.wildcardMatches setting index '..w.index..' to '..require 'symmath.export.SingleLine'(i == 1 and matchExpr or defaultValue))
-- write matches. should already be true.
cmpExpr:match(w, matches)
--matches[w.index] = cmpExpr
elseif add:isa(w) then
-- use the state this time, so it does modify "matches"
cmpExpr:match(w, matches)
elseif pow:isa(w) then
cmpExpr:match(w, matches)
-- elseif mul.is shouldn't happen if all muls are flattened upon construction
elseif mul:isa(w) then
error"match() doesn't work with unflattened mul's"
end
end
return true
end
for wildcards in wildcards:permutations() do
wildcards = table(wildcards)
if checkWildcardPermutation(wildcards, matches) then
--print("mul.wildcardMatches: success")
return matches[1] or true, table.unpack(matches, 2, table.maxn(matches))
end
end
--print("mul.wildcardMatches: found no matching permutations - failing")
return false
end
function mul.__eq(a,b)
if getmetatable(a) ~= getmetatable(b) then return false end
-- compare things order-independent, remove as you go
local a = table(a)
local b = table(b)
for i=#a,1,-1 do
local ai = a[i]
-- non-commutative compare...
if not ai.mulNonCommutative then
local j
for _j=1,#b do
local bj = b[_j]
if ai == bj then
j = _j
break
end
end
if j then
a:remove(i)
b:remove(j)
end
end
end
local n = #a
if n ~= #b then return false end
for i=1,n do
if a[i] ~= b[i] then return false end
end
return true
end
function mul:reverse(soln, index)
-- y = a_1 * ... * a_j(x) * ... * a_n
-- => a_j(x) = y / (a_1 * ... * a_j-1 * a_j+1 * ... * a_n)
for k=1,#self do
if k ~= index then
soln = soln / self[k]:clone()
end
end
return soln
end
function mul:getRealRange()
if self.cachedSet then return self.cachedSet end
local I = self[1]:getRealRange()
if I == nil then
self.cachedSet = nil
return nil
end
for i=2,#self do
local I2 = self[i]:getRealRange()
if I2 == nil then return nil end
I = I * I2
end
self.cachedSet = I
return self.cachedSet
end
-- lim mul = mul lim
function mul:evaluateLimit(x, a, side)
symmath = symmath or require 'symmath'
local Constant = symmath.Constant
local Limit = symmath.Limit
-- TODO handle indeterminate forms here? or outside of limits?
-- right now they are evaluated outside of limits...
return symmath.prune(
mul(
table.mapi(self, function(fi)
return Limit(fi, x, a, side)
end):unpack()
)
)
end
-- goes horribly slow
--[[
a * (b + c) * d * e => (a * b * d * e) + (a * c * d * e)
--]]
function mul:distribute()
symmath = symmath or require 'symmath'
local add = symmath.op.add
local sub = symmath.op.sub
for i,ch in ipairs(self) do
if add:isa(ch) or sub:isa(ch) then
local terms = table()
for j,chch in ipairs(ch) do
local term = self:clone()
term[i] = chch
terms:insert(term)
end
return getmetatable(ch)(table.unpack(terms))
end
end
end
mul.rules = {
-- [[
Expand = {
{apply = function(expand, expr)
local dstr = expr:distribute()
if dstr then
return expand:apply(dstr)
end
end},
},
--]]
-- not sure where this rule should go, or if I already have a copy somewhere ....
Factor = {
-- [[ a^n * b^n => (a * b)^n
-- this is also in mul/Prune/combineMulOfLikePow
-- and the opposite is in pow/Expand/expandMulOfLikePow and pow/Prune/expandMulOfLikePow
-- I'm removing it here after a reorganization of rules because now, with prune() turning expressions into div add mul, this is causing stack overflows
{combineMulOfLikePow = function(factor, expr)
symmath = symmath or require 'symmath'
local pow = symmath.op.pow
for i=1,#expr-1 do
if pow:isa(expr[i]) then
for j=i+1,#expr do
if pow:isa(expr[j]) then
if expr[i][2] == expr[j][2] then
-- powers match, combine
local repl = (expr[i][1] * expr[j][1]) ^ expr[i][2]
expr = expr:clone()
table.remove(expr, j)
expr[i] = repl
if #expr == 1 then expr = expr[1] end
--expr = expr:prune()
--expr = expr:expand()
--expr = expr:prune()
--expr = factor:apply(expr)
return expr
end
end
end
end
end
end},
--]]
--[[
-- hmm ... raise everything to the lowest power?
-- if there are any sqrts, square everything?
-- this is for 2/sqrt(6) => sqrt(2)/sqrt(3)
-- this seems to do more harm than good, esp when summing fractions of sqrts
-- This also looks dangerous, like it would be cancelling negatives somewhere.
{raiseEverythingToLowestPower = function(factor, expr)
symmath = symmath or require 'symmath'
local sqrt = symmath.sqrt
local pow = symmath.op.pow
local div = symmath.op.div
local Constant = symmath.Constant
for i,x in ipairs(expr) do
if pow:isa(x)
and symmath.set.integer:contains(x[1])
and #math.primeFactorization(x[1].value) > 1
and div:isa(x[2])
and Constant.isValue(x[2][2], 2)
and Constant.isValue(x[2][1], -1)
then
return factor:apply(sqrt((expr^2):prune()))
end
end
end},
--]]
-- [[ how about turning p*x^-q/2 into p/x^(q/2) here?
-- still prevents sums of fractions of sqrts ...
{negPowToDivPow = function(factor, expr)
symmath = symmath or require 'symmath'
local pow = symmath.op.pow
local div = symmath.op.div
local Constant = symmath.Constant
for i,x in ipairs(expr) do
if pow:isa(x)
and symmath.set.integer:contains(x[1])
--and #math.primeFactorization(x[1].value) > 1
and div:isa(x[2])
and Constant.isValue(x[2][2], 2)
--[=[
and Constant.isValue(x[2][1], -1)
then
expr = expr:clone()
table.remove(expr, i)
if #expr == 1 then expr = expr[1] end
return factor:apply(expr / symmath.sqrt(x[1]))
--return factor:apply(symmath.sqrt((expr^2):prune()))
end
--]=]
-- [=[
--[==[
and Constant:isa(x[2][1])
and x[2][1].value < 0
and (x[2][1].value % 2) == 1
--]==]
-- [==[ TODO oddNegativeInteger .. or sets based on conditions ...
and symmath.set.oddInteger:contains(x[2][1])
and symmath.set.negativeReal:contains(x[2][1])
--]==]
then
expr = expr:clone()
table.remove(expr, i)
if #expr == 1 then expr = expr[1] end
return factor:apply(expr / x[1]^div(-x[2][1], x[2][2]))
--return factor:apply(symmath.sqrt((expr^2):prune()))
end
--]=]
end
end},
--]]
},
FactorDivision = {
{apply = function(factorDivision, expr)
symmath = symmath or require 'symmath'
local Constant = symmath.Constant
local div = symmath.op.div
-- first time processing we want to simplify()
-- to remove powers and divisions
--expr = expr:simplify()
-- but not recursively ... hmm ...
-- flatten multiplications
local flat = expr:flattenAndClone()
if flat then return factorDivision:apply(flat) end
-- distribute multiplication
local dstr = expr:distribute()
if dstr then return factorDivision:apply(dstr) end
-- [[ same as Prune:
-- push all fractions to the left
for i=#expr,2,-1 do
if div:isa(expr[i])
and Constant:isa(expr[i][1])
and Constant:isa(expr[i][2])
then
table.insert(expr, 1, table.remove(expr, i))
end
end
-- push all Constants to the lhs, sum as we go
local cval = 1
for i=#expr,1,-1 do
if Constant:isa(expr[i]) then
cval = cval * table.remove(expr, i).value
end
end
-- if it's all constants then return what we got
if #expr == 0 then
return Constant(cval)
end
if cval == 0 then
return Constant(0)
end
if cval ~= 1 then
table.insert(expr, 1, Constant(cval))
else
if #expr == 1 then
return factorDivision:apply(expr[1])
end
end
--]]
end},
},
Prune = {
{flatten = function(prune, expr)
-- flatten multiplications
local flat = expr:flattenAndClone()
if flat then return prune:apply(flat) end
end},
-- move unary minuses up
--[[ pruning unm immediately
{moveUnmUp = function(prune, expr)
symmath = symmath or require 'symmath'
local unm = symmath.op.unm
local unmCount = 0
local modified
for i=1,#expr do
local ch = expr[i]
if unm:isa(ch) then
unmCount = unmCount + 1
expr[i] = ch[1]
modified = true
end
end
if modified then
if unmCount % 2 == 1 then
return -prune:apply(expr) -- move unm outside and simplify what's left
elseif unmCount ~= 0 then
return prune:apply(expr) -- got an even number? remove it and simplify this
end
end
end},
--]]
{handleInfAndNan = function(prune, expr)
symmath = symmath or require 'symmath'
local Constant = symmath.Constant
local invalid = symmath.invalid
local inf = symmath.inf
local negativeReal = symmath.set.negativeReal
-- anything * invalid is invalid
for i=1,#expr do
if expr[i] == invalid then
--print("mul by invalid ... makes invalid")
return invalid
end
end
-- inf * anything = inf
-- inf * -anything = -inf
local hasinf
local haszero
local sign = 1
for i=1,#expr do
if expr[i] == inf then
hasinf = true
end
if Constant.isValue(expr[i], 0) then
haszero = true
end
-- TODO recursively call instead of for-loop
-- and TODO if expr[i] is not in positive or negative real then don't simplify it, because it is arbitrary.
-- x * inf cannot be simplified to +inf or -inf.
if negativeReal:contains(expr[i]) then
sign = -sign
end
end
if hasinf then
if haszero then
--print("mul hasinf and hazero ... makes invalid")
return invalid
end
if sign == -1 then
-- use the pruned form, but don't call prune, or it gets an infinite loop
return Constant(-1) * inf
end
return inf
end
end},
{apply = function(prune, expr)
symmath = symmath or require 'symmath'
local Constant = symmath.Constant
local pow = symmath.op.pow
local div = symmath.op.div
-- push all fractions to the left
for i=#expr,2,-1 do
if div:isa(expr[i])
and Constant:isa(expr[i][1])
and Constant:isa(expr[i][2])
then
table.insert(expr, 1, table.remove(expr, i))
end
end
-- [[ and now for Matrix*Matrix multiplication ...
-- do this before the c * 0 = 0 rule
for i=#expr,2,-1 do
local rhs = expr[i]
local lhs = expr[i-1]
local result
if lhs.pruneMul then
result = lhs.pruneMul(lhs, rhs)
elseif rhs.pruneMul then
result = rhs.pruneMul(lhs, rhs)
end
if result then
table.remove(expr, i)
expr[i-1] = result
if #expr == 1 then expr = expr[1] end
return prune:apply(expr)
end
end
--]]
-- push all Constants to the lhs, sum as we go
local cval = 1
for i=#expr,1,-1 do
if Constant:isa(expr[i]) then
cval = cval * table.remove(expr, i).value
end
end
-- if it's all constants then return what we got
if #expr == 0 then
return Constant(cval)
end
if cval == 0 then
return Constant(0)
end
if cval ~= 1 then
table.insert(expr, 1, Constant(cval))
else
if #expr == 1 then
--return prune:apply(expr[1])
-- cheap trick to fix the problem
-- (frac(1,2)*sqrt(3))*(frac(sqrt(2),sqrt(3))) + (-frac(1,2))*(frac(1,3)*-sqrt(2))
-- is requiring two :simplify()'s in order to simplify fully
-- just insert a :tidy() for the time being and things seem to work
return prune:apply(expr[1]:tidy())
end
end
-- [[
local Variable = symmath.Variable
local TensorRef = symmath.Tensor.Ref
-- TODO use the same compare() that's in op/add.lua
local function compare(a, b)
-- Constant
local ca, cb = Constant:isa(a), Constant:isa(b)
if ca and not cb then return true end
if cb and not ca then return false end
if ca and cb then return a.value < b.value end
-- div-of-Constants
local fa = div:isa(a) and Constant:isa(a[1]) and Constant:isa(a[2])
local fb = div:isa(b) and Constant:isa(b[1]) and Constant:isa(b[2])
if fa and not fb then return true end
if fb and not fa then return false end
if fa and fb then
if a[2].value < b[2].value then return true end
if a[2].value > b[2].value then return false end
if a[1].value < b[1].value then return true end
if a[1].value > b[1].value then return false end
return -- a == b
end
-- Variable
local va, vb = Variable:isa(a), Variable:isa(b)
if va and not vb then return true end
if vb and not va then return false end
if va and vb then return a.name < b.name end
-- TensorRef-of-Variable
local ta = TensorRef:isa(a) and Variable:isa(a[1])
local tb = TensorRef:isa(b) and Variable:isa(b[1])
if ta and not tb then return true end
if tb and not ta then return false end
if ta and tb then
local na, nb = #a, #b
if na < nb then return true end
if na > nb then return false end
if a[1].name < b[1].name then return true end
if a[1].name > b[1].name then return false end
for j=2,na do
local na = type(a[j].symbol) == 'number'
local nb = type(b[j].symbol) == 'number'
if na and not nb then return true end
if nb and not na then return false end
return a[j].symbol < b[j].symbol
end
return -- a == b
end
-- pow
local pa = pow:isa(a)
local pb = pow:isa(b)
if pa and not pb then return true end
if pb and not pa then return false end
if pa and pb then
local result = compare(a[1], b[1])
if result ~= nil then return result end
return compare(a[2], b[2])
end
end
for i=1,#expr-1 do
for j=i,#expr-1 do
local k = j + 1
if not compare(expr[j], expr[k]) then
expr[j], expr[k] = expr[k], expr[j]
end
end
end
--]]
-- [[ before combining powers, separate out any -1's from constants
-- this fixes my -2 * 2^(-1/2) simplify bug, but
-- somehow screws up everything
if mul:isa(expr)
and Constant:isa(expr[1])
and expr[1].value < 0
and expr[1].value ~= -1
then
expr[1] = Constant(-expr[1].value)
table.insert(expr, 1, Constant(-1))
end
--]]
-- [[ a^m * a^n => a^(m + n)
do
local function getBasePower(x)
if pow:isa(x) then
return x[1], x[2]
end
-- [[ I have a weird bug where 4 * 2^(-1/2) won't simplify to 2 sqrt(2)
if Constant:isa(x) then
if x.value > 1 then
local sqrtx = math.sqrt(x.value)
if sqrtx == math.floor(sqrtx) then
return Constant(sqrtx), Constant(2)
end
end
end
--]]
-- same with -2 * 2^(-1/2) ... hmm ...
return x, Constant(1)
end
local modified = false
local i = 1
while i <= #expr do
local x = expr[i]
local base, power = getBasePower(x)
if base then
local j = i + 1
while j <= #expr do
local x2 = expr[j]
local base2, power2 = getBasePower(x2)
if base2 == base then
modified = true
table.remove(expr, j)
j = j - 1
power = power + power2
end
j = j + 1
end
if modified then
expr[i] = base ^ power
end
end
i = i + 1
end
if modified then
if #expr == 1 then expr = expr[1] end
return prune:apply(expr)
end
end
--]]
-- [[ after combining powers, re-merge any leading -1's
if mul:isa(expr)
and Constant.isValue(expr[1], -1)
and Constant:isa(expr[2])
then
expr[2] = Constant(-expr[2].value)
table.remove(expr, 1)
end
--]]
end},
-- [[ factor out denominators
-- a * b * (c / d) => (a * b * c) / d
-- generalization:
-- a^m * b^n * (c/d)^p = (a^m * b^n * c^p) / d^p
{factorDenominators = function(prune, expr)
symmath = symmath or require 'symmath'
local Constant = symmath.Constant
local pow = symmath.op.pow
local div = symmath.op.div
local uniqueDenomIndexes = table()
local denoms = table()
local powers = table()
local bases = table()
for i=1,#expr do
-- decompose expressions of the form
-- (base / denom) ^ power
local base = expr[i]
local power = Constant(1)
local denom = Constant(1)
if pow:isa(base) then
base, power = table.unpack(base)
end
if div:isa(base) then
base, denom = table.unpack(base)
end
if not Constant.isValue(denom, 1) then
uniqueDenomIndexes:insert(i)
end
denoms:insert(denom)
powers:insert(power)
bases:insert(base)
end
if #uniqueDenomIndexes > 0 then
local num
if #bases == 1 then
num = bases[1]
if not Constant.isValue(powers[1], 1) then
num = num ^ powers[1]
end
else
num = bases:map(function(base,i)
if Constant.isValue(powers[i], 1) then
return base
else
return base ^ powers[i]
end
end)
assert(#num > 0)
if #num == 1 then
num = num[1]
else
num = mul(num:unpack())
end
end
local denom
if #uniqueDenomIndexes == 1 then
local i = uniqueDenomIndexes[1]
denom = denoms[i]
if not Constant.isValue(powers[i], 1) then
denom = denom^powers[i]
end
elseif #denoms > 1 then
denom = mul(table.unpack(uniqueDenomIndexes:map(function(i)
if Constant.isValue(powers[i], 1) then
return denoms[i]
else
return denoms[i]^powers[i]
end
end)))
end
local expr = num
if not Constant.isValue(denom, 1) then
expr = expr / denom
end
return prune:apply(expr)
end
end},
--]]
-- [[ a^n * b^n => (a * b)^n
--[=[
this rule here passes the unit tests
but it puts Platonic Solids in a simplification loop...
TODO respect mulCommutative
only test to your neighbor
and have a step above for pushing all commutative terms to one side
it turns out this also kills: (x*y)/(x*y)^2 => 1/(x*y)
but this makes work: sqrt(sqrt(sqrt(5) + 1) * sqrt(sqrt(5) - 1)) => 2
but if I only do this for sqrts?
that appeases that particular unit tests.
but even that also kills simplification of sqrt(f) * (g + sqrt(g))
so between the two cases...
looks like I can solve both unit tests if I only apply this to powers-of-adds
so when we find mul -> pow -> add
--]=]
{combineMulOfLikePow_mulPowAdd = function(prune, expr)
symmath = symmath or require 'symmath'
local pow = symmath.op.pow
local div = symmath.op.div
local Constant = symmath.Constant
local add = symmath.op.add
for i=1,#expr-1 do
if pow:isa(expr[i])
--[=[ only for pow-of-sqrts?
and div:isa(expr[i][2])
and Constant.isValue(expr[i][2][1], 1)
and Constant.isValue(expr[i][2][2], 2)
--]=]
-- [=[ only for pow-of-add?
and add:isa(expr[i][1])
--]=]
then
for j=i+1,#expr do
if pow:isa(expr[j])
--[=[ only for pow-of-sqrts?
and div:isa(expr[j][2])
and Constant.isValue(expr[j][2][1], 1)
and Constant.isValue(expr[j][2][2], 2)
--]=]
-- [=[ only for pow-of-add?
and add:isa(expr[j][1])
--]=]
then
if expr[i][2] == expr[j][2] then
-- powers match, combine
local repl = (expr[i][1] * expr[j][1]):prune() ^ expr[i][2]
--repl = repl:prune() -- causes loops
expr = expr:clone()
table.remove(expr, j)
expr[i] = repl
if #expr == 1 then expr = expr[1] end
--expr = prune:apply(expr) -- causes loops
return expr
end
end
end
end
end
end},
--]]
--[[ how about turning c*x^-1/2 into c/sqrt(x) here?
-- still prevents sums of fractions of sqrts ...
{replacePowHalfWithSqrt = function(prune, expr)
local sqrt = symmath.sqrt
local pow = symmath.op.pow
local div = symmath.op.div
local Constant = symmath.Constant
for i,x in ipairs(expr) do
if pow:isa(x)
and symmath.set.integer:contains(x[1])
-- without this we get a stack overflow:
-- but without this, and without the return prune, it fixes 3*1/sqrt(2) not simplifying
and #math.primeFactorization(x[1].value) > 1
and div:isa(x[2])
and Constant.isValue(x[2][2], 2)
and Constant.isValue(x[2][1], -1)
then
expr = expr:clone()
table.remove(expr, i)
if #expr == 1 then expr = expr[1] end
--return prune:apply(expr / sqrt(x[1]))
return expr / sqrt(x[1])
--return factor:apply(sqrt((expr^2):prune()))
end
end
end},
--]]
{logPow = function(prune, expr)
symmath = symmath or require 'symmath'
-- b log(a) => log(a^b)
-- I would like to push this to prevent x log(y) => log(y^x)
-- but I would like to keep -1 * log(y) => log(y^-1)
-- so I'll make a separate rule for that ...
for i=1,#expr do
if symmath.log:isa(expr[i]) then
expr = expr:clone()
local a = table.remove(expr,i)
if #expr == 1 then expr = expr[1] end
return prune:apply(symmath.log(a[1] ^ expr))
end
end
end},
{negLog = function(prune, expr)
symmath = symmath or require 'symmath'
-- -1*log(a) => log(1/a)
if #expr == 2
and expr[1] == symmath.Constant(-1)
and symmath.log:isa(expr[2])
then
return prune:apply(symmath.log(1/expr[2][1]))
end
end},
--[[ move expand rule to prune ...
-- without this, (a^2 * x^2 - a^2):simplify() has :factor() turn it into (a^2 (x + 1) (x - 1))
-- and subsequent :prune() leaves it in this state
-- with this, (1 + 1/x + 2/x) fails to simplify to (1 + 3/x) and we get some infinite loops somewhere
{expand = function(prune, expr)
local dstr = expr:distribute()
if dstr then
-- and don't simplify or you'll get an infinite loop ...
return prune:apply(dstr)
end
end},
--]]
},
Tidy = {
{apply = function(tidy, expr)
symmath = symmath or require 'symmath'
local unm = symmath.op.unm
local Constant = symmath.Constant
-- -x * y * z => -(x * y * z)
-- -x * y * -z => x * y * z
do
local unmCount = 0
for i=1,#expr do
local ch = expr[i]
if unm:isa(ch) then
unmCount = unmCount + 1
expr[i] = ch[1]
end
end
assert(#expr > 1)
if unmCount % 2 == 1 then
return -tidy:apply(expr) -- move unm outside and simplify what's left
elseif unmCount ~= 0 then
return tidy:apply(expr) -- got an even number? remove it and simplify this
end
end
-- (has to be solved post-prune() because tidy's Constant+unm will have made some new ones)
-- 1 * x => x
local first = expr[1]
if Constant:isa(first) and first.value == 1 then
table.remove(expr, 1)
if #expr == 1 then
expr = expr[1]
end
return tidy:apply(expr)
end
--[[
-- TODO incorporate the rule x^a * x^b * ... => x^(a+b+...)
-- but that means separating it out from Prune.apply, and that uses some in-place modification stuff
-- until then, this is me being lazy and hoping for no infinite recursion:
-- hmm, and who could've expected, this is causing stack overflows:
local result = symmath.prune(expr)
for i=1,#result do
result[i] = tidy:apply(result[i])
end
return result
--]]
-- [
return expr
--]]
end},
},
}
-- ExpandPolynomial inherits from Expand
mul.rules.ExpandPolynomial = mul.rules.Expand
return mul
|
Locales['fr'] = {
['robbery_cancelled'] = 'le braquage vas être annulé, vous ne gagnerez rien!',
['robbery_successful'] = 'braquage réussi vous avez gagné ~g~$',
['bank_robbery'] = 'braquage banque',
['press_to_rob'] = 'appuyer sur ~INPUT_CONTEXT~ pour braquer ~b~',
['robbery_of'] = 'braquage de banque: ~r~',
['seconds_remaining'] = '~w~ secondes restantes',
['robbery_cancelled_at'] = '~r~ Braquage annulé à: ~b~',
['robbery_has_cancelled'] = '~r~ le braquage à été annulé: ~b~',
['already_robbed'] = 'cette banque a déjà été braqué. Veuillez attendre: ',
['seconds'] = 'secondes.',
['rob_in_prog'] = '~r~ braquage en cours à: ~b~',
['started_to_rob'] = 'vous avez commencé à braquer ',
['do_not_move'] = ', ne vous éloignez pas!',
['alarm_triggered'] = 'l\'alarme à été déclenché',
['hold_pos'] = 'tenez la position pendant 5min et l\'argent est à vous!',
['robbery_complete'] = '~r~ Braquage terminé.~s~ ~h~ Fuie!',
['robbery_complete_at'] = '~r~ Braquage terminé à: ~b~',
['min_two_police'] = 'Pour braquer il faut minimum autant de policiers: ',
['robbery_already'] = '~r~Un braquage est déjà en cours.',
}
|
--
-- vgScoreboard v1.0
-- Client-side script.
-- By Alberto "ryden" Alonso
--
-- Coded for Valhalla Gaming MTA roleplay server.
-- (Because the MTA default one creates FPS lag spikes).
--
--[[ Configuration ]]--
local SCOREBOARD_WIDTH = 500 -- The scoreboard window width
local SCOREBOARD_HEIGHT = 420 -- The scoreboard window height
local SCOREBOARD_HEADER_HEIGHT = 20 -- Height for the header in what you can see the server info
local SCOREBOARD_TOGGLE_CONTROL = "tab" -- Control/Key to toggle the scoreboard visibility
local SCOREBOARD_PGUP_CONTROL = "mouse_wheel_up" -- Control/Key to move one page up
local SCOREBOARD_PGDN_CONTROL = "mouse_wheel_down"-- Control/Key to move one page down
local SCOREBOARD_DISABLED_CONTROLS = { "next_weapon", -- Controls that are disabled when the scoreboard is showing
"previous_weapon",
"aim_weapon",
"radio_next",
"radio_previous" }
local SCOREBOARD_TOGGLE_TIME = 50 -- Time in miliseconds to make the scoreboard (dis)appear
local SCOREBOARD_POSTGUI = true -- Set to true if it must be drawn over the GUI
local SCOREBOARD_INFO_BACKGROUND = { 0, 0, 0, 150 } -- RGBA color for the info header background
local SCOREBOARD_SERVER_NAME_COLOR = { 15, 177, 253, 160 } -- RGBA color for the server name text
local SCOREBOARD_PLAYERCOUNT_COLOR = { 255, 255, 255, 160 } -- RGBA color for the server player count text
local SCOREBOARD_BACKGROUND = { 0, 0, 0, 140 } -- RGBA color for the background
local SCOREBOARD_BACKGROUND_IMAGE = { 255, 255, 255, 40 } -- RGBA color for the background image
local SCOREBOARD_HEADERS_COLOR = { 200, 200, 200, 160 } -- RGBA color for the headers
local SCOREBOARD_SEPARATOR_COLOR = { 82, 82, 82, 140 } -- RGBA color for the separator line between headers and body content
local SCOREBOARD_SCROLL_BACKGROUND = { 0, 10, 20, 100 } -- RGBA color for the scroll background
local SCOREBOARD_SCROLL_FOREGROUND = { 15, 177, 253, 160 } -- RGBA color for the scroll foreground
local SCOREBOARD_SCROLL_HEIGHT = 20 -- Size for the scroll marker
local SCOREBOARD_COLUMNS_WIDTH = { 0.08, 0.72, 0.16, 0.04 } -- Relative width for each column: id, player name, ping and scroll position
local SCOREBOARD_ROW_GAP = 0 -- Gap between rows
--[[ Uncomment to test with dummies ]]--
--[[
local _getPlayerName = getPlayerName
local _getPlayerPing = getPlayerPing
local _getPlayerNametagColor = getPlayerNametagColor
function getPlayerName ( player )
if getElementType ( player ) == "player" then return _getPlayerName ( player ) end
return getElementData ( player, "name" )
end
function getPlayerPing ( player )
if getElementType ( player ) == "player" then return _getPlayerPing ( player ) end
return getElementData ( player, "ping" )
end
function getPlayerNametagColor ( player )
if getElementType ( player ) == "player" then return _getPlayerNametagColor ( player )
else return unpack(getElementData(player, "color")) end
end
--]]
--[[ Global variables to this context ]]--
local g_isShowing = false -- Marks if the scoreboard is showing
local g_currentWidth = 0 -- Current window width. Used for the fade in/out effect.
local g_currentHeight = 0 -- Current window height. Used for the fade in/out effect.
local g_scoreboardDummy -- Will contain the scoreboard dummy element to gather info from.
local g_windowSize = { guiGetScreenSize () } -- The window size
local g_localPlayer = getLocalPlayer () -- The local player...
local g_currentPage = 0 -- The current scroll page
local g_players -- We will keep a cache of the conected player list
local g_oldControlStates -- To save the old control states before disabling them for scrolling
--[[ Pre-calculate some stuff ]]--
-- Scoreboard position
local SCOREBOARD_X = math.floor ( ( g_windowSize[1] - SCOREBOARD_WIDTH ) / 2 )
local SCOREBOARD_Y = math.floor ( ( g_windowSize[2] - SCOREBOARD_HEIGHT ) / 2 )
-- Scoreboard colors
SCOREBOARD_INFO_BACKGROUND = tocolor ( unpack ( SCOREBOARD_INFO_BACKGROUND ) )
SCOREBOARD_SERVER_NAME_COLOR = tocolor ( unpack ( SCOREBOARD_SERVER_NAME_COLOR ) )
SCOREBOARD_PLAYERCOUNT_COLOR = tocolor ( unpack ( SCOREBOARD_PLAYERCOUNT_COLOR ) )
SCOREBOARD_BACKGROUND = tocolor ( unpack ( SCOREBOARD_BACKGROUND ) )
SCOREBOARD_BACKGROUND_IMAGE = tocolor ( unpack ( SCOREBOARD_BACKGROUND_IMAGE ) )
SCOREBOARD_HEADERS_COLOR = tocolor ( unpack ( SCOREBOARD_HEADERS_COLOR ) )
SCOREBOARD_SCROLL_BACKGROUND = tocolor ( unpack ( SCOREBOARD_SCROLL_BACKGROUND ) )
SCOREBOARD_SCROLL_FOREGROUND = tocolor ( unpack ( SCOREBOARD_SCROLL_FOREGROUND ) )
SCOREBOARD_SEPARATOR_COLOR = tocolor ( unpack ( SCOREBOARD_SEPARATOR_COLOR ) )
-- Columns width in absolute units
for k=1,#SCOREBOARD_COLUMNS_WIDTH do
SCOREBOARD_COLUMNS_WIDTH[k] = math.floor ( SCOREBOARD_COLUMNS_WIDTH[k] * SCOREBOARD_WIDTH )
end
-- Pre-calculate each row horizontal bounding box.
local rowsBoundingBox = { { SCOREBOARD_X, -1 }, { -1, -1 }, { -1, -1 }, { -1, -1 } }
-- ID
rowsBoundingBox[1][2] = SCOREBOARD_X + SCOREBOARD_COLUMNS_WIDTH[1]
-- Name
rowsBoundingBox[2][1] = rowsBoundingBox[1][2]
rowsBoundingBox[2][2] = rowsBoundingBox[2][1] + SCOREBOARD_COLUMNS_WIDTH[2]
-- Ping
rowsBoundingBox[3][1] = rowsBoundingBox[2][2]
rowsBoundingBox[3][2] = rowsBoundingBox[3][1] + SCOREBOARD_COLUMNS_WIDTH[3]
-- Scrollbar
rowsBoundingBox[4][1] = rowsBoundingBox[3][2]
rowsBoundingBox[4][2] = SCOREBOARD_X + SCOREBOARD_WIDTH
--[[ Pre-declare some functions ]]--
local onRender
local fadeScoreboard
local drawBackground
local drawScoreboard
--[[
* clamp
Clamps a value into a range.
--]]
local function clamp ( valueMin, current, valueMax )
if current < valueMin then
return valueMin
elseif current > valueMax then
return valueMax
else
return current
end
end
--[[
* createPlayerCache
Generates a new player cache.
--]]
local function createPlayerCache ( ignorePlayer )
-- Optimize the function in case of not having to ignore a player
if ignorePlayer then
-- Clear the gloal table
g_players = {}
-- Get the list of connected players
local players = getElementsByType ( "player" )
-- Dump them to the global table
for k, player in ipairs(players) do
if ignorePlayer ~= player then
table.insert ( g_players, player )
end
end
else
g_players = getElementsByType ( "player" )
end
--[[ Uncomment to test with dummies ]]--
--[[
for k,v in ipairs(getElementsByType("playerDummy")) do
table.insert(g_players, v)
end
--]]
-- Sort the player list by their ID, giving priority to the local player
table.sort ( g_players, function ( a, b )
local idA = getElementData ( a, "playerid" ) or 0
local idB = getElementData ( b, "playerid" ) or 0
-- Perform the checks to always set the local player at the beggining
if a == g_localPlayer then
idA = -1
elseif b == g_localPlayer then
idB = -1
end
return tonumber(idA) < tonumber(idB)
end )
end
--[[
* onClientResourceStart
Handles the resource start event to create the initial player cache
--]]
addEventHandler ( "onClientResourceStart", getResourceRootElement(getThisResource()), function ()
createPlayerCache ()
end, false )
--[[
* onClientElementDataChange
Handles the element data changes event to update the player cache
if the playerid was changed.
--]]
addEventHandler ( "onClientElementDataChange", root, function ( dataName, dataValue )
if dataName == "playerid" then
createPlayerCache ()
end
end )
--[[
* onClientPlayerQuit
Handles the player quit event to update the player cache.
--]]
addEventHandler ( "onClientPlayerQuit", root, function ()
createPlayerCache ( source )
end )
--[[
* toggleScoreboard
Toggles the visibility of the scoreboard.
--]]
local function toggleScoreboard ( show )
-- Force the parameter to be a boolean
local show = show == true
-- Check if the status has changed
if show ~= g_isShowing then
g_isShowing = show
if g_isShowing and g_currentWidth == 0 and g_currentHeight == 0 then
-- Handle the onClientRender event to start drawing the scoreboard.
addEventHandler ( "onClientPreRender", root, onRender, false )
end
-- Little hack to avoid switching weapons while moving through the scoreboard pages.
if g_isShowing then
g_oldControlStates = {}
for k, control in ipairs ( SCOREBOARD_DISABLED_CONTROLS ) do
g_oldControlStates[k] = isControlEnabled ( control )
toggleControl ( control, false )
end
else
for k, control in ipairs ( SCOREBOARD_DISABLED_CONTROLS ) do
toggleControl ( control, g_oldControlStates[k] )
end
g_oldControlStates = nil
end
end
end
--[[
* onToggleKey
Function to bind to the appropiate key the function to toggle the scoreboard visibility.
--]]
local function onToggleKey ( key, keyState )
-- Check if the scoreboard element has been created
if not g_scoreboardDummy then
local elementTable = getElementsByType ( "scoreboard" )
if #elementTable > 0 then
g_scoreboardDummy = elementTable[1]
else
return
end
end
-- Toggle the scoreboard, and check that it's allowed.
toggleScoreboard ( keyState == "down" and getElementData ( g_scoreboardDummy, "allow" ) )
end
bindKey ( SCOREBOARD_TOGGLE_CONTROL, "both", onToggleKey )
--[[
* onScrollKey
Function to bind to the appropiate key the function to change the current page.
--]]
local function onScrollKey ( direction )
if g_isShowing then
if direction then
g_currentPage = g_currentPage + 1
else
g_currentPage = g_currentPage - 1
if g_currentPage < 0 then
g_currentPage = 0
end
end
end
end
bindKey ( SCOREBOARD_PGUP_CONTROL, "down", function () onScrollKey ( false ) end )
bindKey ( SCOREBOARD_PGDN_CONTROL, "down", function () onScrollKey ( true ) end )
--[[
* onRender
Event handler for onClientPreRender. It will forward the flow to the most appropiate
function: fading-in, fading-out or drawScoreboard.
--]]
onRender = function ( timeshift )
-- Boolean to check if we must draw the scoreboard.
local drawIt = false
if g_isShowing then
-- Check if the scoreboard has been disallowed
if not getElementData ( g_scoreboardDummy, "allow" ) then
toggleScoreboard ( false )
-- If it's showing, check if it got fully faded in. Else, draw it normally.
elseif g_currentWidth < SCOREBOARD_WIDTH or g_currentHeight < SCOREBOARD_HEIGHT then
drawIt = fadeScoreboard ( timeshift, 1 )
else
-- Allow drawing the full scoreboard
drawIt = true
end
else
-- If it shouldn't be showing, make another step to fade it out.
drawIt = fadeScoreboard ( timeshift, -1 )
end
-- Draw the scoreboard if allowed.
if drawIt then
drawScoreboard ()
end
end
--[[
* fadeScoreboard
Makes a step of the fade effect. Gets a multiplier to make it either fading in or out.
--]]
fadeScoreboard = function ( timeshift, multiplier )
-- Get the percentage of the final size that it should grow for this step.
local growth = ( timeshift / SCOREBOARD_TOGGLE_TIME ) * multiplier
-- Apply the growth to the scoreboard size
g_currentWidth = clamp ( 0, g_currentWidth + ( SCOREBOARD_WIDTH * growth ), SCOREBOARD_WIDTH )
g_currentHeight = clamp ( 0, g_currentHeight + ( SCOREBOARD_HEIGHT * growth ), SCOREBOARD_HEIGHT )
-- Check if the scoreboard has collapsed. If so, unregister the onClientRender event.
if g_currentWidth == 0 or g_currentHeight == 0 then
g_currentWidth = 0
g_currentHeight = 0
removeEventHandler ( "onClientPreRender", root, onRender )
return false
else
return true
end
end
--[[
* drawBackground
Draws the scoreboard background.
--]]
drawBackground = function ()
-- Draw the header
local headerHeight = clamp ( 0, SCOREBOARD_HEADER_HEIGHT, g_currentHeight )
dxDrawRectangle ( SCOREBOARD_X, SCOREBOARD_Y,
g_currentWidth, headerHeight,
SCOREBOARD_INFO_BACKGROUND, SCOREBOARD_POSTGUI )
-- Draw the body background
if g_currentHeight > SCOREBOARD_HEADER_HEIGHT then
-- Draw the image
dxDrawImage ( SCOREBOARD_X * 1.17, SCOREBOARD_Y * 1.1 + SCOREBOARD_HEADER_HEIGHT,
g_currentWidth / 1.3, g_currentHeight / 1.05 - SCOREBOARD_HEADER_HEIGHT,
"icon.png", 0, 0, 0, SCOREBOARD_BACKGROUND_IMAGE, SCOREBOARD_POSTGUI )
-- Overlay
dxDrawRectangle ( SCOREBOARD_X, SCOREBOARD_Y + SCOREBOARD_HEADER_HEIGHT,
g_currentWidth, g_currentHeight - SCOREBOARD_HEADER_HEIGHT,
SCOREBOARD_BACKGROUND, SCOREBOARD_POSTGUI )
end
end
--[[
* drawRowBounded
Draws a scoreboard body row with the pre-calculated row bounding boxes.
--]]
local function drawRowBounded ( id, name, ping, colors, font, top )
-- Precalculate some constants
local bottom = clamp ( 0, top + dxGetFontHeight ( 1, font ), SCOREBOARD_Y + g_currentHeight )
local maxWidth = SCOREBOARD_X + g_currentWidth
-- If the row doesn't fit, just avoid any further calculations.
if bottom < top then return end
-- ID
local left = rowsBoundingBox[1][1]
local right = clamp ( 0, rowsBoundingBox[1][2], maxWidth )
if left < right then
dxDrawText ( id, left, top, right, bottom,
colors[1], 1, font, "right", "top",
true, false, SCOREBOARD_POSTGUI )
-- Name
left = rowsBoundingBox[2][1] + 17 -- Grant some padding to the name column
right = clamp ( 0, rowsBoundingBox[2][2], maxWidth )
if left < right then
dxDrawText ( name, left, top, right, bottom,
colors[2], 1, font, "left", "top",
true, false, SCOREBOARD_POSTGUI )
-- Ping
left = rowsBoundingBox[3][1]
right = clamp ( 0, rowsBoundingBox[3][2], maxWidth )
if left < right then
dxDrawText ( ping, left, top, right, bottom,
colors[3], 1, font, "left", "top",
true, false, SCOREBOARD_POSTGUI )
end
end
end
end
--[[
* drawScrollBar
Draws the scroll bar. Position ranges from 0 to 1.
--]]
local function drawScrollBar ( top, position )
-- Get the bounding box
local left = rowsBoundingBox[4][1]
local right = clamp ( 0, rowsBoundingBox[4][2], SCOREBOARD_X + g_currentWidth )
local bottom = clamp ( 0, SCOREBOARD_Y + SCOREBOARD_HEIGHT, SCOREBOARD_Y + g_currentHeight )
-- Make sure that it'd be visible.
if left < right and top < bottom then
-- Draw the background
dxDrawRectangle ( left, top, right - left, bottom - top, SCOREBOARD_SCROLL_BACKGROUND, SCOREBOARD_POSTGUI )
-- Get the current Y position for the scroll marker
local top = top + position * ( SCOREBOARD_Y + SCOREBOARD_HEIGHT - SCOREBOARD_SCROLL_HEIGHT - top )
bottom = clamp ( 0, top + SCOREBOARD_SCROLL_HEIGHT, SCOREBOARD_Y + g_currentHeight )
-- Make sure that it'd be visible
if top < bottom then
dxDrawRectangle ( left, top, right - left, bottom - top, SCOREBOARD_SCROLL_FOREGROUND, SCOREBOARD_POSTGUI )
end
end
end
--[[
* drawScoreboard
Draws the scoreboard contents.
--]]
drawScoreboard = function ()
-- Check that we got the list of players
if not g_players then return end
-- First draw the background
drawBackground ()
-- Get the server information
local serverName = getElementData ( g_scoreboardDummy, "serverName" ) or "MTA server"
local maxPlayers = getElementData ( g_scoreboardDummy, "maxPlayers" ) or 0
serverName = tostring ( serverName )
maxPlayers = tonumber ( maxPlayers )
-- Render the header
-- Calculate the bounding box for the header texts
local left, top, right, bottom = SCOREBOARD_X + 2, SCOREBOARD_Y + 2, SCOREBOARD_X + g_currentWidth - 2, SCOREBOARD_Y + SCOREBOARD_HEADER_HEIGHT - 2
-- Render the server name
dxDrawText ( serverName, left, top, right, bottom,
SCOREBOARD_SERVER_NAME_COLOR, 1, "default-bold", "left", "top",
true, false, SCOREBOARD_POSTGUI )
-- Render the player count
local usagePercent = (#g_players / maxPlayers) * 100
local strPlayerCount = "Players: " .. tostring(#g_players) .. "/" .. tostring(maxPlayers) .. " (" .. math.floor(usagePercent + 0.5) .. "%)"
-- We need to recalculate the left position, to make it not move when fading.
local offset = SCOREBOARD_WIDTH - dxGetTextWidth ( strPlayerCount, 1, "tahoma" ) - 4
left = left + offset
-- Make sure of that it needs to be rendered now
if left < right then
dxDrawText ( strPlayerCount, left, top, right, bottom,
SCOREBOARD_PLAYERCOUNT_COLOR, 1, "tahoma", "left", "top",
true, false, SCOREBOARD_POSTGUI )
end
-- Draw the body.
-- Update the bounding box.
left, top, bottom = SCOREBOARD_X, SCOREBOARD_Y + SCOREBOARD_HEADER_HEIGHT + 2, SCOREBOARD_Y + g_currentHeight - 2
-- Pre-calculate how much height will each row have.
local rowHeight = dxGetFontHeight ( 1, "default-bold" )
-- Draw the headers
drawRowBounded ( "ID", "Player name", "Ping",
{ SCOREBOARD_HEADERS_COLOR, SCOREBOARD_HEADERS_COLOR, SCOREBOARD_HEADERS_COLOR },
"default-bold", top )
-- Add the offset for a new row
top = top + rowHeight + 3
-- Draw the separator
right = clamp ( 0, rowsBoundingBox[3][2] - 5, SCOREBOARD_X + g_currentWidth )
if top < SCOREBOARD_Y + g_currentHeight then
dxDrawLine ( SCOREBOARD_X + 5, top, right, top, SCOREBOARD_SEPARATOR_COLOR, 1, SCOREBOARD_POSTGUI )
end
top = top + 3
-- Create a function to render a player entry
local renderEntry = function ( player )
-- Get the player data
local playerID = getElementData ( player, "playerid" ) or 0
playerID = tostring ( playerID )
local playerName = getPlayerName ( player )
playerName = tostring ( playerName ):gsub( "_", " " )
local playerPing = getPlayerPing ( player )
playerPing = tostring ( playerPing )
local r, g, b = getPlayerNametagColor ( player )
local playerColor = tocolor ( r, g, b, 255 )
-- Create the table of colors
local colors = { playerColor, playerColor, playerColor }
-- Render it!
drawRowBounded ( playerID, playerName, playerPing, colors, "default-bold", top )
end
-- Calculate how much players can fit in the body window.
local playersPerPage = math.floor ( ( SCOREBOARD_Y + SCOREBOARD_HEIGHT - top ) / ( rowHeight + SCOREBOARD_ROW_GAP ) )
-- Get the amount of shifted players per page
local playerShift = math.floor ( playersPerPage / 2 )
-- Get the number of players to skip
local playersToSkip = playerShift * g_currentPage
if (#g_players - playersToSkip) < playersPerPage then
-- Check that they didn't go to an invalid page
if (#g_players - playersToSkip) < playerShift then
g_currentPage = g_currentPage - 1
if g_currentPage < 0 then g_currentPage = 0 end
end
-- Try to always fill pages
playersToSkip = #g_players - playersPerPage + 1
end
-- Check for when there are too few players to fill one page.
if playersToSkip < 0 then
playersToSkip = 0
end
-- For every player in the cache, render a new entry.
for k=playersToSkip + 1, #g_players do
local player = g_players [ k ]
-- Check if it's gonna fit. If it doesn't stop rendering.
if top < bottom - rowHeight - SCOREBOARD_ROW_GAP then
renderEntry ( player )
-- Update the height for the next entry
top = top + rowHeight + SCOREBOARD_ROW_GAP
else break end
end
-- Draw the scrollbar. The maximum players to skip is #g_players - playersPerPage + 1, so when
-- the scoreboard is fully scrolled it will become 1, while when it's not scrolled it will be
-- 0 due to playersToSkip being 0.
drawScrollBar ( SCOREBOARD_Y + SCOREBOARD_HEADER_HEIGHT + rowHeight + 10, playersToSkip / ( #g_players - playersPerPage + 1 ) )
end
--[[
* isVisible
Returns wherever or not the scoreboard is visible
--]]
function isVisible ( )
return g_isShowing
end
|
if (!BM2CONFIG) then return end
if (!BM2CONFIG.RealTimePrice) then
if timer.Exists("BM2REALTIMEAPI") then
timer.Destroy("BM2REALTIMEAPI")
end
end
function BM2CONFIG:RefreshPrice()
http.Fetch("https://blockchain.info/ticker",
function(body, len, headers, code)
local tbl = util.JSONToTable(body)[BM2CONFIG.BitcoinCurrency] or "USD"
BM2CONFIG.BitcoinValue = tbl.buy
end,
function(error)
return chat.AddText(Color(243, 156, 18), "[Bitcoins API]", color_white, " Failed to connect to the API!")
end
)
end
timer.Create("BM2REALTIMEAPI", BM2CONFIG.RefreshRate * 60, 0, function()
BM2CONFIG:RefreshPrice()
end)
concommand.Add("bitcoins_refresh", function()
if (BM2CONFIG.RealTimePrice) then
BM2CONFIG:RefreshPrice()
timer.Simple(0.2, function()
MsgC(Color(243, 156, 18), "[Bitcoins API]", color_white, " New Bitcoin Price : ", Color(243, 156, 18), (BM2CONFIG.BitcoinCurrency or "USD") .. " " .. (BM2CONFIG.BitcoinValue), color_white, " !")
end)
else
MsgC(Color(243, 156, 18), "[Bitcoins API]", color_white, " The realtime Bitcoin Price isn't activated!")
end
end)
|
function widget:GetInfo()
return {
name = "AvoidanceAI",
desc = "attempt to avoid getting into range of nasty things. Meant to be used with return fire state. Version 0,87",
author = "dyth68,esainane",
date = "2020",
license = "PD", -- should be compatible with Spring
layer = 11,
enabled = true
}
end
local UPDATE_FRAME=4
local SneakyStack = {}
local GetGroundHeight = Spring.GetGroundHeight
local GetUnitMaxRange = Spring.GetUnitMaxRange
local GetUnitPosition = Spring.GetUnitPosition
local GetMyAllyTeamID = Spring.GetMyAllyTeamID
local GiveOrderToUnit = Spring.GiveOrderToUnit
local GetUnitsInCylinder = Spring.GetUnitsInCylinder
local GetUnitAllyTeam = Spring.GetUnitAllyTeam
local GetUnitIsDead = Spring.GetUnitIsDead
local GetMyTeamID = Spring.GetMyTeamID
local GetUnitDefID = Spring.GetUnitDefID
local GetTeamUnits = Spring.GetTeamUnits
local GetUnitStates = Spring.GetUnitStates
local Echo = Spring.Echo
local Scythe_ID = UnitDefNames.cloakheavyraid.id
local Widow_ID = UnitDefNames.spiderantiheavy.id
local Gremlin_ID = UnitDefNames.cloakaa.id
local GetSpecState = Spring.GetSpectatingState
local CMD_UNIT_SET_TARGET = 34923
local CMD_UNIT_CANCEL_TARGET = 34924
local CMD_STOP = CMD.STOP
local CMD_ATTACK = CMD.ATTACK
local CMD_ATTACK_MOVE = 16 -- I should figure out where to get this
local sqrt = math.sqrt
local decloakRanges = {
[Scythe_ID] = 75,
[Widow_ID] = 60,
[Gremlin_ID] = 140,
}
local decloakRangeGrace = 50
-- Air tends to change height quite slowly, unless they are already very far up
local airDecloakRangeGrace = 7
local moveDist = 50
-- Check to see if the units we're surrounded by are cancelling each other out.
-- If our impulse ends up being less than this, don't move, just do our best.
local minMoveImpulse = 3/5
local minMoveImpulseSq = minMoveImpulse * minMoveImpulse
local SneakyControllerMT
local SneakyController = {
allyTeamID = GetMyAllyTeamID(),
new = function(index, unitID, unitDefID)
-- Echo("SneakyController added:" .. unitID)
local self = {}
setmetatable(self, SneakyControllerMT)
self.unitID = unitID
self.unitDefID = unitDefID
self.pos = {GetUnitPosition(unitID)}
self.height = Spring.GetUnitHeight(unitID)
self.aiEngaged = false
return self
end,
unset = function(self)
-- Echo("SneakyController removed:" .. self.unitID)
GiveOrderToUnit(self.unitID,CMD_STOP, {}, {""},1)
return nil
end,
checkOneEnemyUnitTooClose = function(self, x,y,z, unitID, unitDefID, enemyUnitID)
if GetUnitAllyTeam(enemyUnitID) == self.allyTeamID then return false end
local baseY = GetGroundHeight(x, z)
local enemyX, enemyY, enemyZ = GetUnitPosition(enemyUnitID)
if enemyY <= -30 then
-- disregard underwater units
return false
end
local enemyHeightAboveGround = enemyY - baseY
-- Don't get spooked by bombers or gunships, unless they're eg blastwings or gnats which really do fly that low, or if they are coming in to land nearby
-- We should be spooked by air if we have a large decloak area, though
if enemyHeightAboveGround > decloakRanges[unitDefID] + airDecloakRangeGrace + self.height then
self.db1 = self.db1 or WG.Debouncer:new(Echo, 30)
if WG.Debug then WG.Debug.Marker(enemyX,enemyY,enemyZ,'Not dodging', enemyHeightAboveGround, 'is beyond our spookpoint of', decloakRanges[unitDefID] + airDecloakRangeGrace, 'note baseY', baseY, 'our y', y, 'our height', Spring.GetUnitHeight(unitID)) end
return false
end
if GetUnitIsDead(enemyUnitID) then return false end
local dist2Sq = (x - enemyX) * (x - enemyX) + (z - enemyZ) * (z - enemyZ)
local dist3Sq = dist2Sq + (y - enemyY) * (y - enemyY)
-- Give a really big impulse if they're getting close
-- We give ourselves a little wiggle room with nominalRange since we're using 3D distance for urgency.
-- If we didn't double the grace, urgency would be at 100% of normal impulse at maximum considered range.
local nominalRange = decloakRanges[unitDefID] + decloakRangeGrace * 2
local nominalRangeSq = nominalRange * nominalRange
-- Impulse equivalent to slightly over 100% of normal impulse at maximum range (see above).
-- Increases up to 300% as they get closer to being right on top of us
-- Squared distance means that the increase to the increase is linear as they get closer.
local urgency = (nominalRangeSq*3) / (dist3Sq+dist3Sq + nominalRangeSq)
local dist = sqrt(dist2Sq)
local impulseX = (x - enemyX) * urgency / dist
local impulseZ = (z - enemyZ) * urgency / dist
if WG.Debug then WG.Debug.Marker(enemyX,enemyY,enemyZ,'This enemy is spooky', dist, 'elmos away, treating with urgency', urgency * 100, '%, adding impulse', impulseX, impulseZ,'given squared nominal range of',nominalRangeSq,', or normal range of',nominalRange,'and squared 3d range of',dist3Sq,'or normal 3d range of',sqrt(dist3Sq)) end
return true, impulseX, impulseZ
end,
isEnemyTooClose = function (self)
local x,y,z = unpack(self.pos)
local unitDefID = self.unitDefID
local units = GetUnitsInCylinder(x, z, decloakRanges[unitDefID] + decloakRangeGrace)
local unitID = self.unitID
local impulseXSum, impulseZSum = 0, 0
local haveImpulse = false
for i=1, #units do
local enemyUnitID = units[i]
local doMove, impulseX, impulseZ = self:checkOneEnemyUnitTooClose(x,y,z, unitID, unitDefID, enemyUnitID)
if doMove then
impulseXSum, impulseZSum = impulseXSum + impulseX, impulseZSum + impulseZ
haveImpulse = true
end
end
if not haveImpulse then return false end
local distSq = impulseXSum * impulseXSum + impulseZSum * impulseZSum
-- If we're surrounded, don't do anything.
if distSq < minMoveImpulseSq then
if WG.Debug then WG.Debug.Marker(x,y,z, "I'm surrounded", distSq, "<", minMoveImpulseSq, "Giving up on dodging.") end
return false
end
-- Regardless of our the urgency being fed in, always move the same distance away from our current position.
local dist = sqrt(distSq)
local awayX = x + impulseXSum * moveDist / dist
local awayZ = z + impulseZSum * moveDist / dist
--Echo("Sneaky order given:" .. self.unitID .. "; from " .. x .. "," .. z .. " to " .. awayX .. "," .. awayZ)
Spring.GiveOrderToUnit(self.unitID,
CMD.INSERT,
{0,CMD_ATTACK_MOVE,CMD.OPT_SHIFT, awayX, y, awayZ},
{"alt"}
)
return true
end,
handle = function(self)
if not (GetUnitStates(self.unitID).movestate == 0 and Spring.GetUnitIsCloaked(self.unitID)) then return end
local cmdQueue = Spring.GetUnitCommands(self.unitID, 2)
if not (#cmdQueue == 0 or (cmdQueue[1].id == CMD_ATTACK_MOVE)) then return end
self.pos = {GetUnitPosition(self.unitID)}
self:isEnemyTooClose()
end
}
SneakyControllerMT = {__index=SneakyController}
function widget:UnitFinished(unitID, unitDefID, unitTeam)
if decloakRanges[unitDefID] and unitTeam==GetMyTeamID() then
SneakyStack[unitID] = SneakyController:new(unitID, unitDefID)
end
end
function widget:UnitDestroyed(unitID)
if not (SneakyStack[unitID]==nil) then
SneakyStack[unitID]=SneakyStack[unitID]:unset()
end
end
function widget:GameFrame(n)
if (n%UPDATE_FRAME==0) then
for _,Scythe in pairs(SneakyStack) do
Scythe:handle()
end
end
end
-- The rest of the code is there to disable the widget for spectators
local function DisableForSpec()
if GetSpecState() then
widgetHandler:RemoveWidget()
end
end
function widget:Initialize()
DisableForSpec()
local units = GetTeamUnits(GetMyTeamID())
for i=1, #units do
local unitDefID = GetUnitDefID(units[i])
if (decloakRanges[unitDefID]) then
if (SneakyStack[units[i]]==nil) then
SneakyStack[units[i]]=SneakyController:new(units[i], unitDefID)
end
end
end
end
function widget:PlayerChanged (playerID)
DisableForSpec()
end
|
--[[
@class InputImageLibrary.story
]]
local require = require(game:GetService("ServerScriptService"):FindFirstChild("LoaderUtils", true).Parent).load(script)
local InputImageLibrary = require("InputImageLibrary")
local Maid = require("Maid")
local UIPaddingUtils = require("UIPaddingUtils")
local UICornerUtils = require("UICornerUtils")
local String = require("String")
local XBOX = {
Enum.KeyCode.ButtonA;
Enum.KeyCode.ButtonB;
Enum.KeyCode.ButtonX;
Enum.KeyCode.ButtonY;
Enum.KeyCode.ButtonL1;
Enum.KeyCode.ButtonL2;
Enum.KeyCode.ButtonR1;
Enum.KeyCode.ButtonR2;
Enum.KeyCode.Menu;
Enum.KeyCode.ButtonSelect;
Enum.KeyCode.DPadLeft;
Enum.KeyCode.DPadRight;
Enum.KeyCode.DPadUp;
Enum.KeyCode.DPadDown;
Enum.KeyCode.Thumbstick1;
Enum.KeyCode.Thumbstick2;
"DPad";
}
local KEYBOARD = {
Enum.KeyCode.Left;
Enum.KeyCode.Right;
Enum.KeyCode.Up;
Enum.KeyCode.Down;
Enum.KeyCode.Space;
Enum.KeyCode.Backspace;
Enum.KeyCode.LeftControl;
Enum.KeyCode.Tab;
Enum.KeyCode.Return;
Enum.KeyCode.Delete;
Enum.KeyCode.Backspace;
Enum.KeyCode.A;
Enum.KeyCode.B;
Enum.KeyCode.C;
Enum.KeyCode.D;
Enum.KeyCode.E;
Enum.KeyCode.F;
Enum.KeyCode.G;
Enum.KeyCode.H;
Enum.KeyCode.I;
Enum.KeyCode.J;
Enum.KeyCode.K;
Enum.KeyCode.L;
Enum.KeyCode.M;
Enum.KeyCode.N;
Enum.KeyCode.O;
Enum.KeyCode.P;
Enum.KeyCode.Q;
Enum.KeyCode.R;
Enum.KeyCode.S;
Enum.KeyCode.T;
Enum.KeyCode.U;
Enum.KeyCode.V;
Enum.KeyCode.W;
Enum.KeyCode.X;
Enum.KeyCode.Y;
Enum.KeyCode.Z;
Enum.KeyCode.Zero;
Enum.KeyCode.One;
Enum.KeyCode.Two;
Enum.KeyCode.Three;
Enum.KeyCode.Four;
Enum.KeyCode.Five;
Enum.KeyCode.Six;
Enum.KeyCode.Seven;
Enum.KeyCode.Eight;
Enum.KeyCode.Nine;
}
local MOUSE = {
Enum.UserInputType.MouseButton1;
Enum.UserInputType.MouseButton3;
Enum.UserInputType.MouseWheel;
Enum.UserInputType.MouseButton2;
Enum.UserInputType.MouseMovement;
}
local function create(keyCode, theme, parent)
local container = Instance.new("Frame")
container.BorderSizePixel = 0
container.Size = UDim2.new(1, 0, 1, 0)
UICornerUtils.fromOffset(8, container)
local padding = UIPaddingUtils.fromUDim(UDim.new(0, 5))
padding.Parent = container
local phaseTextLabel = Instance.new("TextLabel")
phaseTextLabel.Text =String.removePrefix(type(keyCode) == "string" and keyCode or keyCode.Name, "Mouse")
phaseTextLabel.TextSize = 20
phaseTextLabel.TextTruncate = Enum.TextTruncate.AtEnd
phaseTextLabel.Font = Enum.Font.Highway
phaseTextLabel.TextColor3 = Color3.new(0.1, 0.1, 0.1)
phaseTextLabel.Size = UDim2.new(1, 0, 0, 30)
phaseTextLabel.AnchorPoint = Vector2.new(0.5, 0)
phaseTextLabel.Position = UDim2.new(0.5, 0, 0, 0)
phaseTextLabel.TextWrapped = false
phaseTextLabel.BackgroundTransparency = 1
phaseTextLabel.LayoutOrder = 2
phaseTextLabel.Parent = container
local uiListLayout = Instance.new("UIListLayout")
uiListLayout.Parent = container
local sprite = InputImageLibrary:GetScaledImageLabel(keyCode, theme)
sprite.Parent = container
container.Parent = parent
end
local function makeTitle(title, parent)
local titleLabel = Instance.new("TextLabel")
titleLabel.Text = title
titleLabel.TextSize = 24
titleLabel.TextColor3 = Color3.new(0, 0, 0)
titleLabel.TextColor3 = Color3.new(0.1, 0.1, 0.1)
titleLabel.Font = Enum.Font.Highway
titleLabel.Size = UDim2.new(1, -10, 0, 40)
titleLabel.AnchorPoint = Vector2.new(0.5, 0)
titleLabel.Position = UDim2.new(0.5, 0, 0, 0)
titleLabel.TextWrapped = true
titleLabel.BackgroundTransparency = 1
titleLabel.LayoutOrder = 2
titleLabel.Parent = parent
return titleLabel
end
local function makeSection(keycodes, theme, parent)
local container = Instance.new("Frame")
container.BorderSizePixel = 0
container.BackgroundTransparency = 1
container.Size = UDim2.new(1, 0, 1, 0)
local uiGridLayout = Instance.new("UIGridLayout")
uiGridLayout.HorizontalAlignment = Enum.HorizontalAlignment.Center
uiGridLayout.VerticalAlignment = Enum.VerticalAlignment.Top
uiGridLayout.FillDirection = Enum.FillDirection.Horizontal
uiGridLayout.SortOrder = Enum.SortOrder.LayoutOrder
uiGridLayout.CellSize = UDim2.new(0, 100, 0, 130)
uiGridLayout.Parent = container
for _, item in pairs(keycodes) do
create(item, theme, container)
end
container.Parent = parent
container.Size = UDim2.new(1, 0, 0, uiGridLayout.AbsoluteContentSize.y)
return container
end
return function(target)
local maid = Maid.new()
local scrollingFrame = Instance.new("ScrollingFrame")
scrollingFrame.Size = UDim2.new(1, 0, 1, 0)
scrollingFrame.CanvasSize = UDim2.new(1, 0, 5, 0)
scrollingFrame.BackgroundColor3 = Color3.new(1, 1, 1)
scrollingFrame.BackgroundTransparency = 0
scrollingFrame.BorderSizePixel = 0
maid:GiveTask(scrollingFrame)
local uiListLayout = Instance.new("UIListLayout")
uiListLayout.SortOrder = Enum.SortOrder.LayoutOrder
uiListLayout.Parent = scrollingFrame
scrollingFrame.Parent = target
local layoutOrder = 1
local function add(item)
layoutOrder = layoutOrder + 1
item.LayoutOrder = layoutOrder
end
add(makeTitle("Mouse Light", scrollingFrame))
add(makeSection(MOUSE, "Light", scrollingFrame))
add(makeTitle("Mouse Dark", scrollingFrame))
add(makeSection(MOUSE, "Dark", scrollingFrame))
add(makeTitle("XBox Dark", scrollingFrame))
add(makeSection(XBOX, "Dark", scrollingFrame))
add(makeTitle("XBox Light", scrollingFrame))
add(makeSection(XBOX, "Light", scrollingFrame))
add(makeTitle("Keyboard Dark", scrollingFrame))
add(makeSection(KEYBOARD, "Dark", scrollingFrame))
add(makeTitle("Keyboard Light", scrollingFrame))
add(makeSection(KEYBOARD, "Light", scrollingFrame))
return function()
maid:DoCleaning()
end
end
|
package.path = package.path .. ';../protobuf/?.lua'
package.cpath = package.cpath .. ';../protobuf/?.so'
require 'person_pb'
local person= person_pb.Person()
person.id = 1000
person.name = "Alice"
person.email = "[email protected]"
local home = person.Extensions[person_pb.Phone.phones]:add()
home.num = "2147483647"
home.type = person_pb.Phone.HOME
local data = person:SerializeToString()
local msg = person_pb.Person()
msg:ParseFromString(data)
print(msg)
|
--[[
--
--
--
Copyright 2017 Muresan Vlad Mihail
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--
--
--]]
anim = {}
anim.__index = anim
--constructor
-- width of the animation frame
-- height of the animation frame
function anim.create(img,width,height)
local self = {}
self.img = img
self.w = width
self.h = height
self.fx = 0
self.fy = 0
self.frames = {}
self.imgW,self.imgH = img:getDimensions()
self.currFrame = 0
self.currSpeed = 0
self.loop = true
self.stop = false
self.custom = false
self.stopFrame = nil
self.startFrame = 1
self.f = 0
return setmetatable(self,anim)
end
--private function,it should not be called by user
function anim:makeFrame()
if self.f == 0 then
self.f = math.floor(self.imgW / self.w * self.imgH / self.h)
end
self.fx = math.floor(self.imgW / self.w)
for i =1, self.f do
local row = math.floor((i-1)/self.fx)
local column = (i-1)%self.fx
table.insert(self.frames, love.graphics.newQuad(column*self.w,row*self.h,self.w,self.h,self.imgW,self.imgH))
end
end
--Lets say you got an animation from frame eg: 1 through 4. If your current frame reached the end,in this case 4,
--then this func will return true. If the animation is looped you'll get multiple returns of "true" else only once
function anim:reached_end()
if self.currFrame >= self.stopFrame then
return true
else
return false
end
end
--optional: set at what frame from your spritesheet you want to have the animation start at
function anim:setStartFrame(startFrame)
self.startFrame = startFrame
self.currFrame = self.startFrame
end
--optional: set at what frame from your spritesheet you want to have the animation stop at
function anim:setStopFrame(stopFrame)
self.stopFrame = stopFrame
end
--set a start frame eg: 1 and a stop frame eg: 4 then the speed at which the frames should change
function anim:add(startFrame, stopFrame, speed)
self.speed = speed or 0
self:makeFrame()
self.stopFrame = stopFrame or #self.frames
self.startFrame = startFrame or 1
end
--set manually your quads in this case anim:add will not work.
--[[ e.g:
local idle_shoot_quad =
-{
love.graphics.newQuad(36*0,0,36,42,PLAYER_IMG:getDimensions()),
love.graphics.newQuad(36*2,0,36,42,PLAYER_IMG:getDimensions())
}
--]]
function anim:addf(frames, speed)
self.speed = speed
self.custom = true
table.insert(self.frames, frames)
end
--draw your animation
-- x and y are mandatory
function anim:draw(x, y, rot, sx, sy, kx, ky)
rot = rot or 0
sx = sx or 1
sy = sy or 1
kx = kx or 0
ky = ky or 0
if self.frames then
if not self.custom then
love.graphics.draw(self.img,self.frames[self.currFrame],x,y,rot,sx,sy,kx,ky)
else
for i,v in pairs(self.frames) do
love.graphics.draw(self.img,v[self.currFrame],x,y,rot,sx,sy,kx,ky)
end
end
else
love.graphics.draw(self.img, x, y, rot, sx, sy, kx, ky)
end
end
--when you reach a certain frame stop the frame
function anim:stopAt(frame)
if self.currFrame == frame then
self.currFrame = frame
self.stop = true
end
end
function anim:getLength()
return #self.frames
end
--pause the current anim
function anim:pause()
self.stop = true
end
--resume the last frame and continue doing the animation
function anim:resume()
self.stop = false
end
--change your current active frame to something custom. Eg: Your current frame is at 2 this func allows you to change it at eg 10
function anim:setFrame(frame)
self.currFrame = frame
end
--return the current frame
function anim:getFrame()
return self.currFrame
end
--update method: loop = whether or not this anim should be looped
function anim:play(loop)
if not self.stop then
self.loop = loop
self.currSpeed = self.currSpeed + love.timer.getDelta()
--increment the currentFrame when needed
if self.speed > 0 then
if self.currFrame == 0 and self.startFrame >= 1 then
self.currFrame = self.startFrame
end
if self.currSpeed >= self.speed then
self.currFrame = self.currFrame + 1
self.currSpeed = 0
end
--[[
-- Note:
-- When you have no speed attached to your animation that means
-- you want to play only the first quad added in 'add' function
--]]
elseif self.speed == 0 then
self.currFrame = self.startFrame
end
--do we have custom quads?
if not self.custom then
--we dont
if self.stopFrame == nil then
if self.currFrame > #self.frames then
if(self.loop) then
if self.startFrame >= 1 then
self.currFrame = self.startFrame
else
self.currFrame = 1
end
else
self.currFrame = #self.frames
end
end
else
--we got a stopframe
if self.currFrame > self.stopFrame then
if self.loop then
if self.startFrame > 0 then
self.currFrame = self.startFrame
end
else
self.currFrame = self.stopFrame
end
end
end
else
--we do
for i,v in pairs(self.frames) do
if self.currFrame > #v then
if(self.loop) then
self.currFrame = 1
else
self.currFrame = #v
end
end
end
end
end
end
|
-- Actually these regular expressions were obtained from SpamAssassin project, so they are licensed by apache license:
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to you under the Apache License, Version 2.0
-- (the "License"); you may not use this file except in compliance with
-- the License. You may obtain a copy of the License at:
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Rules that are specific for lotto spam messages
local reconf = config['regexp']
local r_lotto_from = 'From=/(?:lottery|News center|congratulation to you|NED INFO|BRITISH NATIONAL HEADQUATERS|MICROSOFT ON LINE SUPPORT TEAM|prize|online notification)/iH'
local r_lotto_subject = 'Subject=/(?:\\xA3\\d|pounds?|FINAL NOTIFICATION|FOR YOUR ATTENTION|File in Your Claims?|ATTN|prize|Claims requirement|amount|confirm|your e-mail address won|congratulations)/iH'
local r_lotto_body = '/(?:won|winning|\\xA3\\d|pounds?|GBP|LOTTERY|awards|prize)/isrP'
local kam_lotto1 = '/(e-?mail address (have emerged a winner|has won|attached to (ticket|reference)|was one of the ten winners)|random selection in our computerized email selection system)/isrP'
local kam_lotto2 = '/((ticket|serial|lucky) number|secret pin ?code|batch number|reference number|promotion date)/isrP'
local kam_lotto3 = '/(won|claim|cash prize|pounds? sterling)/isrP'
local kam_lotto4 = '/(claims (officer|agent)|lottery coordinator|fiduciary (officer|agent)|fiduaciary claims)/isrP'
local kam_lotto5 = '/(freelotto group|Royal Heritage Lottery|UK National (Online)? Lottery|U\\.?K\\.? Grand Promotions|Lottery Department UK|Euromillion Loteria|Luckyday International Lottery|International Lottery)/isrP'
local kam_lotto6 = '/(Dear Lucky Winner|Winning Notification|Attention:Winner|Dear Winner)/isrP'
local kam_lotto7 = 'Subject=/(Your Lucky Day|(Attention:|ONLINE) WINNER)/iH'
reconf['R_LOTTO'] = string.format('((%s) | (%s) | (%s)) & regexp_match_number(3, (%s), (%s), (%s), (%s), (%s), (%s), (%s), (%s), (%s))', reconf['R_UNDISC_RCPT'], reconf['R_BAD_CTE_7BIT'], reconf['R_NO_SPACE_IN_FROM'], r_lotto_from, r_lotto_subject, r_lotto_body, kam_lotto1, kam_lotto2, kam_lotto3, kam_lotto4, kam_lotto5, kam_lotto6)
|
Unit:Using("another_unit") -- will pull in another_unit and all dependencies
-- overridden Init to mark this unit as both lib and bin
function Unit.Init(self)
self.executable = true
self.static_library = true
self.targetname = "simple"
end
-- PatchHeaders not overridden, "./include" will be added as include dir
-- Patch not overridden, targetname will be added as lib to any unit that uses this unit
-- overridden Build to output lib and bin
function Unit.Build(self)
local libsrc = {
PathJoin(self.path, "src/simple.c")
}
local binsrc = {
PathJoin(self.path, "src/main.c")
}
local libobj = Compile(self.settings, libsrc)
local binobj = Compile(self.settings, binsrc)
local lib = StaticLibrary(self.settings, self.targetname, libobj)
local bin = Link(self.settings, "simple", libobj, binobj)
end
|
SMPLRT_DIV = 0x19 --采样率分频,典型值=:0x07(125Hz)
CONFIG = 0x1A -- 低通滤波频率,典型值=:0x06(5Hz)
GYRO_CONFIG = 0x1B -- 陀螺仪自检及测量范围,典型值=:0x18(不自检,2000deg/s)
ACCEL_CONFIG = 0x1C -- 加速计自检、测量范围及高通滤波频率,典型值=:0x01(不自检,2G,5Hz)
ACCEL_XOUT_H = 0x3B -- 存储最近的X轴、Y轴、Z轴加速度感应器的测量值
ACCEL_XOUT_L = 0x3C
ACCEL_YOUT_H = 0x3D
ACCEL_YOUT_L = 0x3E
ACCEL_ZOUT_H = 0x3F
ACCEL_ZOUT_L = 0x40
TEMP_OUT_H = 0x41 -- 存储的最近温度传感器的测量值
TEMP_OUT_L = 0x42
GYRO_XOUT_H = 0x43 -- 存储最近的X轴、Y轴、Z轴陀螺仪感应器的测量值
GYRO_XOUT_L = 0x44
GYRO_YOUT_H = 0x45
GYRO_YOUT_L = 0x46
GYRO_ZOUT_H = 0x47
GYRO_ZOUT_L = 0x48
PWR_MGMT_1 = 0x6B -- 电源管理,典型值=:0x00(正常启用)
WHO_AM_I = 0x75 -- IIC地址寄存器(默认数=值0x68,只读)
id=0
sda=1
scl=2
-- 初始化i2c, 将pin1设置为sda, 将pin2设置为scl
iicSpeed = i2c.setup(id,sda,scl,i2c.SLOW)
print("Running ... AND i2cSpeed is " .. iicSpeed)
-- 用户定义函数:读取地址dev_addr的寄存器reg_addr中的内容。
function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr ,i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
c=i2c.read(id,1)
i2c.stop(id)
return c
end
tmr.alarm(1, 1000, tmr.ALARM_AUTO, function()
-- 读取0x77的寄存器0xAA中的内容。
reg = read_reg(0x68, 0x1C)
print(string.byte(reg))
end)
|
local Spell = { }
Spell.LearnTime = 90
Spell.ApplyFireDelay = 0.16
Spell.Category = HpwRewrite.CategoryNames.Special
Spell.Description = [[
Creates a plenty of harmful
lead things muggles call
"bullets".
]]
Spell.Category = { HpwRewrite.CategoryNames.Special, HpwRewrite.CategoryNames.Fight }
Spell.ShouldSay = false
Spell.ForceAnim = { ACT_VM_PRIMARYATTACK_7 }
Spell.NodeOffset = Vector(694, -598, 0)
Spell.Diff = 0.1
Spell.CanSelfCast = false
if not game.SinglePlayer() then
if SERVER then
util.AddNetworkString("hpwrewrite_hailbullets_handler")
else
net.Receive("hpwrewrite_hailbullets_handler", function()
local ent = net.ReadEntity()
local wand = HpwRewrite:GetWand(ent)
local accuracy = 0.2
if not HpwRewrite.CVars.NoAccuracy:GetBool() then accuracy = net.ReadFloat() end
local spread = math.max(accuracy * 0.1, 0.02)
if wand:IsValid() then
local bullet = { }
bullet.Num = 1
bullet.Src = wand:GetSpellSpawnPosition()
bullet.Dir = ent:GetAimVector()
bullet.Spread = Vector(math.Rand(-spread, spread), math.Rand(-spread - 0.01, spread + 0.01), 0)
bullet.Tracer = 1
bullet.Force = 2
bullet.Damage = math.random(4, 6)
ent:FireBullets(bullet)
end
end)
end
end
function Spell:OnFire(wand)
self.Active = true
self.Diff = math.Rand(0.02, 0.08)
timer.Create("hpwrewrite_hailbullets_handler" .. self.Owner:EntIndex(), 0.35, 1, function()
self.Active = false
end)
end
function Spell:Think(wand)
if CLIENT or not self.Active then return end
if not self.Wait then self.Wait = 0 end
if self.Wait and CurTime() > self.Wait then
local accuracy = 0.2
if not HpwRewrite.CVars.NoAccuracy:GetBool() then accuracy = wand.HpwRewrite.Accuracy end
local spread = math.max(accuracy * 0.1, 0.02)
local bullet = { }
bullet.Num = 1
bullet.Src = wand:GetSpellSpawnPosition()
bullet.Dir = self.Owner:GetAimVector()
bullet.Spread = Vector(spread, spread + 0.01, 0)
bullet.Tracer = 1
bullet.Force = 2
bullet.Damage = math.random(4, 6)
self.Owner:FireBullets(bullet)
sound.Play("weapons/physcannon/energy_sing_flyby" .. math.random(1, 2) .. ".wav", wand:GetPos(), 70, 130)
self.Wait = CurTime() + self.Diff
if not game.SinglePlayer() then
net.Start("hpwrewrite_hailbullets_handler")
net.WriteEntity(self.Owner)
net.WriteFloat(accuracy)
net.Broadcast()
end
end
end
HpwRewrite:AddSpell("Hail of bullets", Spell)
-- Duo
local Spell = { }
Spell.Base = "Hail of bullets"
Spell.LearnTime = 330
Spell.OnlyIfLearned = { "Hail of bullets" }
Spell.ApplyFireDelay = 0.35
Spell.ForceDelay = 0.35
Spell.AutoFire = true
Spell.Description = [[
Creates an endless storm
of bullets from the tip
of your wand. More powerful
than not duo version.
]]
Spell.NodeOffset = Vector(803, -704, 0)
function Spell:OnFire(wand)
self.BaseClass.OnFire(self, wand)
self.Diff = math.Rand(0.02, 0.04)
end
HpwRewrite:AddSpell("Hail of bullets Duo", Spell)
|
function DIALOG()
NODE(0)
SAY("They got balls those Twilight Guardian guys...")
ANSWER("Why is that?",1)
ANSWER("Who cares",2)
NODE(1)
SAY("Well... those terrorists are standing here in the open to recruit more people to cause even more trouble! But I tell you: You can't reach freedom through force. And even if the TG is able to overthrow Reza and his followers, it will only result in another dictatorship. But then under the oh so freedom loving TG.")
ENDDIALOG()
NODE(2)
SAY("Well go then, turn away from truth. It's because of indifferent people like yourself, we got in to this shit in the first place!")
ENDDIALOG()
end
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local item_dir = os.getenv('item_dir')
local warc_file_base = os.getenv('warc_file_base')
local item_type
local item_id_match
if item_type ~= "100discussions" then
item_id = string.match(item_value, '([0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f])')
item_id_match = string.gsub(item_id, '%-', '%%%-')
end
local downloaded = {}
local addedtolist = {}
local profiles = {}
local item_ids = {}
local recheck_urls = {}
for ignore in io.open("ignore-list", "r"):lines() do
downloaded[ignore] = true
end
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
add_item_ids = function(url)
if string.match(url, item_id_match) then
for itemid in string.gmatch(url, '([0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f])') do
item_ids[itemid] = true
end
end
end
check_item_ids = function(url)
for itemid in string.gmatch(url, '([0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f])') do
if item_ids[itemid] == true then
return true
end
end
return false
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
url = string.gsub(url, "friendsreunited.(co[^:]+):80/", "friendsreunited.%1/")
if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((item_type == '100discussions' and string.match(url, item_value.."[0-9][0-9]") and not string.match(url, item_value.."[0-9][0-9][0-9]")) or html == 0 or string.match(url, "^https?://[^/]*friendsreunited%.co[^/]+/[pP]rofile") or check_item_ids(url) == true or string.match(url, "https?://[^/]*assetstorage%.co%.uk") or (item_type ~= "100discussions" and (string.match(url, item_id_match) or string.match(url, "^https?://[^/]*friendsreunited%.co[^/]+/[dD]iscussion/[vV]iew")))) then
if string.match(url, "^https?://[^/]*friendsreunited%.co[^/]+/[pP]rofile/") then
profiles[url] = true
return false
else
add_item_ids(url)
addedtolist[url] = true
return true
end
else
return false
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
downloaded[url] = true
local function check(urla)
local url = string.match(urla, "^([^#]+)")
url = string.gsub(url, "friendsreunited.(co[^:]+):80/", "friendsreunited.%1/")
if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((item_type == '100discussions' and string.match(url, item_value.."[0-9][0-9]") and not string.match(url, item_value.."[0-9][0-9][0-9]")) or string.match(url, "^https?://[^/]*friendsreunited%.co[^/]+/[pP]rofile/") or check_item_ids == true or string.match(url, "https?://[^/]*assetstorage%.co%.uk") or (item_type ~= "100discussions" and (string.match(url, item_id_match) or string.match(url, "^https?://[^/]*friendsreunited%.co[^/]+/[dD]iscussion/[vV]iew")))) then
if string.match(url, "^https?://[^/]*friendsreunited%.co[^/]+/[pP]rofile/") then
profiles[url] = true
elseif string.match(url, "&") then
add_item_ids(url)
table.insert(urls, { url=string.gsub(url, "&", "&") })
addedtolist[url] = true
addedtolist[string.gsub(url, "&", "&")] = true
else
add_item_ids(url)
table.insert(urls, { url=url })
addedtolist[url] = true
end
elseif string.match(url, '[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]') then
recheck_urls[url] = true
end
end
local function checknewurl(newurl)
if string.match(newurl, "^https?://") then
check(newurl)
elseif string.match(newurl, "^//") then
check("http:"..newurl)
elseif string.match(newurl, "^/") then
check(string.match(url, "^(https?://[^/]+)")..newurl)
end
end
local function checknewshorturl(newurl)
if not (string.match(newurl, "^https?://") or string.match(newurl, "^/") or string.match(newurl, "^javascript:") or string.match(newurl, "^mailto:") or string.match(newurl, "^%${")) then
check(string.match(url, "^(https?://.+/)")..newurl)
end
end
for newurl, _ in pairs(recheck_urls) do
check(newurl)
end
if string.match(url, "^https?://[^/]*friendsreunited%.co") then
html = read_file(file)
for newurl in string.gmatch(html, '([^"]+)') do
checknewurl(newurl)
end
for newurl in string.gmatch(html, "([^']+)") do
checknewurl(newurl)
end
for newurl in string.gmatch(html, ">([^<]+)") do
checknewurl(newurl)
end
for newurl in string.gmatch(html, "href='([^']+)'") do
checknewshorturl(newurl)
end
for newurl in string.gmatch(html, 'href="([^"]+)"') do
checknewshorturl(newurl)
end
if string.match(url, "https?://[^/]*friendsreunited%.co[^/]+/[^/]+/Memory/[^%?]*%?nullableid=") then
local newurl = string.gsub(url, "(https?://[^/]*friendsreunited%.co[^/]+)/([^/]+)/Memory/[^%?]*%?nullableid=(.+)", "%1/Media?nullableid=%3&friendly=%2")
if downloaded[newurl] ~= true and addedtolist[newurl] ~= true then
addedtolist[newurl] = true
table.insert(urls, { url=newurl })
end
end
if string.match(url, "https?://[^/]*friendsreunited%.co[^/]+/Memory/[^%?]*%?nullableid=") then
local newurl = string.gsub(url, "(https?://[^/]*friendsreunited%.co[^/]+)/Memory/[^%?]*%?nullableid=", "%1/Media?nullableid=")
if downloaded[newurl] ~= true and addedtolist[newurl] ~= true then
addedtolist[newurl] = true
table.insert(urls, { url=newurl })
end
end
if string.match(url, "page=[0-9]+") then
pagenum = string.match(url, "page=([0-9]+)")
for num=1,pagenum do
check(string.gsub(url, "page="..pagenum, "page="..num))
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url.url, "https://") then
local newurl = string.gsub(url.url, "https://", "http://")
downloaded[newurl] = true
else
downloaded[url.url] = true
end
end
if string.gsub('-', '%-', '%%%-') ~= '%-' then
return wget.actions.ABORT
end
if string.match(url["url"], '/Home/Login') then
io.stdout:write("You have lost your session cookies! ABORTING\n")
io.stdout:flush()
return wget.actions.ABORT
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) or
status_code == 0 then
io.stdout:write("Server returned "..http_stat.statcode.." ("..err.."). Sleeping.\n")
io.stdout:flush()
os.execute("sleep 1")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
if string.match(url["url"], "^https?://[^/]*friendsreunited%.co") or string.match(url["url"], "https?://[^/]*assetstorage%.co%.uk") then
return wget.actions.ABORT
else
return wget.actions.EXIT
end
else
return wget.actions.CONTINUE
end
end
tries = 0
local sleep_time = 0
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
wget.callbacks.finish = function(start_time, end_time, wall_time, numurls, total_downloaded_bytes, total_download_time)
local usersfile = io.open(item_dir..'/'..warc_file_base..'_data.txt', 'w')
local templist = {}
for url, _ in pairs(profiles) do
if templist[url] ~= true then
templist[url] = true
usersfile:write(url.."\n")
end
end
usersfile:close()
end
|
local class = {}
local physics = require( "physics" )
require( "classes.randomlua")
local newRandNum = require( "classes.GenerateRandNum" ).generateRandNum
local gameMath = require( "classes.gameMath" )
local screenSize = require( "libs.screenSize" )
local colours = require( "libs.colours" )
local myApp = require( "libs.myapp" )
local screenW, screenH, halfW, halfH = screenSize.screenW, screenSize.screenH, screenSize.halfW, screenSize.halfH
function class.newAsteroidTrap( levelparams )
local currentLevel = levelparams
local asteroidTrapGroup = display.newGroup()
local asteroidTrapTbl = {}
--create variables that stores the no of traps
local no_of_traps = currentLevel.asteroidTrapDetails.no_of_traps
--add to table the no_of_asteroids_per_trap and no of asteroids spawned per trap
for i = 1, no_of_traps do
asteroidTrapTbl[#asteroidTrapTbl+1] = {no_of_asteroids_per_trap = currentLevel.asteroidTrapDetails.no_of_asteroids_per_trap, no_of_asteroids_spawned_per_trap = 0}
end
--load moving asteroid sprite
local moving_asteroid_sheetoptions = currentLevel.asteroidTrapDetails.moving_asteroid_sheetoptions
local moving_asteroid_sheet = graphics.newImageSheet( currentLevel.asteroidTrapDetails.filename, moving_asteroid_sheetoptions )
local moving_asteroid_sequenceData = currentLevel.asteroidTrapDetails.moving_asteroid_sequenceData
local function asteroidTrapCollisionListener( self, event )
if ( event.phase == "began" ) then
print( self.type .. self.id, ": collision began with " .. event.other.type .. event.other.id )
if event.other.type == 'wall' then
self:setLinearVelocity(0,0)
transition.fadeOut( self, {time=800, onComplete=function()
display.remove(self)
self = nil
end})
elseif event.other.type == 'asteroid trap trigger zone' then
--asteroid trap has sprung and has moved into the triggerzone, hence change it's velocity to chase the circle,
--after a short delay, which lets it move towards the centre of the trigger zone
timer.performWithDelay(currentLevel.asteroidTrapDetails.timerForDirectionChange,
function() self:setLinearVelocity(currentLevel.asteroidTrapDetails.velocities[self.trapid].x_velocitymin,
currentLevel.asteroidTrapDetails.velocities[self.trapid].y_velocitymax)
print('asteroid moving towards circle')
end
)
end
end
end
local function spawnAsteroid( )
for i = 1, #asteroidTrapTbl do
if asteroidTrapTbl[i].no_of_asteroids_spawned_per_trap < asteroidTrapTbl[i].no_of_asteroids_per_trap then
local moving_asteroid_trap = display.newSprite( moving_asteroid_sheet, moving_asteroid_sequenceData )
moving_asteroid_trap.x, moving_asteroid_trap.y = currentLevel.asteroidTrapDetails.coordinates[i].x, currentLevel.asteroidTrapDetails.coordinates[i].y
moving_asteroid_trap.id = asteroidTrapTbl[i].no_of_asteroids_spawned_per_trap + 1 ;print('asteroid trap id:', moving_asteroid_trap.id)
moving_asteroid_trap.trapid = i --each asteroid has a trapid that is the same as the trap it belongs to. i.e. no of traps = 2, asteroid spawned for trap 1 has trapid = 1
moving_asteroid_trap.type = 'asteroid trap'
moving_asteroid_trap:scale(0.75,0.75)
print('asteroid width:'..moving_asteroid_trap.contentWidth..'height:'..moving_asteroid_trap.contentHeight)
physics.addBody(moving_asteroid_trap, "dynamic", {density=1, bounce=0, friction=0.5, radius=(2/3)*moving_asteroid_trap.contentWidth/2})
moving_asteroid_trap.collision = asteroidTrapCollisionListener
moving_asteroid_trap:addEventListener("collision")
asteroidTrapGroup:insert(moving_asteroid_trap)
asteroidTrapTbl[i].moving_asteroid_trap = moving_asteroid_trap
asteroidTrapTbl[i].no_of_asteroids_spawned_per_trap = asteroidTrapTbl[i].no_of_asteroids_spawned_per_trap + 1
end
end
end
--spawn first set of asteroids, dependent on no of traps, i.e. 1 trap, 1 asteroid, 2 traps, 2 asteroids for respective trap
spawnAsteroid()
local function springAsteroidTrap( asteroidToSpring, triggerZone )
local asteroidTrap = asteroidToSpring
local traptriggerZone = triggerZone
--this vector represent the direction from the asteroid to the trigger zone,
--it used to calculate the velocity to move the asteroid to the trigger zone
local VectorX, VectorY = traptriggerZone.x - asteroidTrap.x, traptriggerZone.y - asteroidTrap.y
asteroidTrap:play()
asteroidTrap:setLinearVelocity(VectorX,VectorY)
timer.performWithDelay(500, spawnAsteroid)
end
local function trap_trigger_zone_collisionListener ( self, event )
if ( event.phase == "began" ) then
print( self.type .. self.id, ": collision began with " ..event.other.type .. event.other.id )
if event.other.type == 'circle' then
for i = 1, #asteroidTrapTbl do
local _asteroidTrap = asteroidTrapTbl[i].moving_asteroid_trap
--print('asteroid trapid and trigger zone id:', _asteroidTrap.trapid, self.id)
if _asteroidTrap.trapid == self.id then --triggerzone id matches the asteroid.trapid
local asteroidToSpring = _asteroidTrap
timer.performWithDelay( 500, springAsteroidTrap( asteroidToSpring, self ) )
end
end
end
end
end
--create the trap trigger zones for each trap.
for i = 1, #asteroidTrapTbl do
local trap_trigger_zone = display.newRect( currentLevel.asteroidTrapDetails.triggerZone[i].x, currentLevel.asteroidTrapDetails.triggerZone[i].y,
currentLevel.asteroidTrapDetails.triggerZone[i].width, currentLevel.asteroidTrapDetails.triggerZone[i].height)
trap_trigger_zone.alpha = 0.25
trap_trigger_zone.id = i
trap_trigger_zone.type = 'asteroid trap trigger zone'
physics.addBody(trap_trigger_zone, "static", {density=0.1, bounce=0, friction=0})
trap_trigger_zone.isSensor = true
trap_trigger_zone.collision = trap_trigger_zone_collisionListener
trap_trigger_zone:addEventListener("collision")
asteroidTrapGroup:insert(trap_trigger_zone)
asteroidTrapTbl[i].trap_trigger_zone = trap_trigger_zone
end
return asteroidTrapGroup
end
return class
|
-- The Games module contains the table of all currently running games. Most of its functionality is used by MayorMcMott.lua, and is not necessary
-- to touch, but games.registerGame() is used to add a game instance to that table, and games.deregisterGame() is used to remove it when it ends.
local games = require("Games")
-- Misc has utility functions (luvit took "utils")
local misc = require("Misc")
-- Lua modules work, of course, by abusing tables. All of the functions that are accessed from outside of the module must be named tictactoe.functionName(),
-- which will add them as fields to the table tictactoe; at the end of the file, we return tictactoe.
local tictactoe = {}
-- Because of the way lua works, we need to make all functions local except for startGame, commandHandler, and dmHandler
-- Otherwise, they'll be imported and potentially cause conflicts with other games!
local tictactoeCreateGameInstance, tictactoeCheckGameOver, tictactoeBoard, tictactoeMove, tictactoeExitGame
--#############################################################################################################################################
--# Main Functions #
--#############################################################################################################################################
-- There are three necessary functions for writing a Mottbot game plugin. They can be named anything.
function tictactoe.startGame(message)
--[[tictactoe.startGame is called when a user attempts to start a new game of Tic-Tac-Toe.]]
local playerList = message.mentionedUsers
if #playerList ~= 2 then
message.channel:send("Exactly two players are necessary to play Tic-Tac-Toe!")
return
end
message.channel:send("Starting game...")
local state = tictactoeCreateGameInstance(message.channel, playerList)
games.registerGame(message.channel, "TicTacToe", state, playerList)
message.channel:send("It's Player One's turn!")
end
function tictactoe.commandHandler(message, state)
--[[tictactoe.commandHandler is called when any message is sent in a channel with an active game of Tic-Tac-Toe running.]]
local player = message.author.id
local args = message.content:split(" ")
--!move
if (state["XTurn"] and player == state["X"]) or (not state["XTurn"] and player == state["O"]) then
if args[1] == "!move" then
if #args == 3 then
local result = tictactoeMove(state, args[2], args[3])
if result then
return
else
message.channel:send("Invalid move!")
return
end
else
message.channel:send("Usage: !move x y")
end
return
end
end
--!end
if args[1] == "!end" then
tictactoeExitGame(state)
elseif args[1] == "!board" then
tictactoeBoard(state)
end
end
function tictactoe.dmHandler(message, state)
--[[tictactoe.dmHandler is called when a player currently playing a Tic-Tac-Toe game sends Mottbot a DM. If the player happens to be playing
multiple games, the command will be processed simultaneously by all of them(!). That said, Tic-Tac-Toe is a very simple game and does not
require DMs, so this function is empty.]]
end
--#############################################################################################################################################
--# Game Functions #
--#############################################################################################################################################
function tictactoeCreateGameInstance(channel, playerList)
--[[Create a table containing the game state of the new game]]
local instance = {
GameChannel = channel,
PlayerList = playerList,
X = playerList[1][1],
O = playerList[1][2],
Board = {{"_", "_", "_"},{"_","_","_"},{"_","_","_"}},
XTurn = true
}
return instance
end
function tictactoeCheckGameOver(state)
--[[Checks if the game is over:
If the game has been won, return "X" or "O" depending on who won.
If the game has been tied, return "T".
If the game is still in progress, return nil.]]
local board = state["Board"]
-- Check verticals and diagonals
print("Diagnostics:\n")
print(board[1][1], board[1][2], board[1][3], "\n")
print(board[2][1], board[2][2], board[2][3], "\n")
print(board[3][1], board[3][2], board[3][3], "\n")
for i=1,3 do
if board[i][1] == board[i][2] and board[i][2] == board[i][3] and board[i][1] ~= "_" then
print("Check 1 return", i)
return board[i][1]
elseif board[1][i] == board[2][i] and board[2][i] == board[3][i] and board[i][1] ~= "_" then
print("Check 2 return", i)
return board[1][i]
end
end
-- Check diagonals
if board[1][1] == board[2][2] and board[2][2] == board[3][3] and board[2][2] ~= "_" then print("Check 3 return"); return board[2][2] end
if board[3][1] == board[2][2] and board[2][2] == board[3][1] and board[2][2] ~= "_" then print("Check 4 return"); return board[2][2] end
-- Check board full
local full = true
while full do
for i=1,3 do
for j=1,3 do
if board[i][j] == "_" then
full = false
end
end
end
break
end
if full then return "T" else return nil end
end
--#############################################################################################################################################
--# Commands #
--#############################################################################################################################################
function tictactoeBoard(state)
--[[Output the board to game chat]]
local channel = state["GameChannel"]
local output = "```\n"
print("Output\n")
for row,tbl in pairs(state["Board"]) do
for col,str in pairs(tbl) do
print(row,col,str)
output = output .. str
end
print("\n")
output = output .. "\n"
end
output = output .. "```"
channel:send(output)
end
function tictactoeMove(state, x, y)
--[[Make a move on the game board]]
local pos = {tonumber(x), tonumber(y)}
-- Verify they're both numbers, in range, and that the tile isnt taken
if pos[1] == nil or pos[2] == nil then return false
elseif pos[1] > 3 or pos[1] < 1 or pos[2] > 3 or pos[1] < 1 then return false
elseif state["Board"][pos[2]][pos[1]] ~= "_" then return false
end
-- Make the move
if state["XTurn"] then state["Board"][pos[2]][pos[1]] = "X" else state["Board"][pos[2]][pos[1]] = "O" end
state["XTurn"] = not state["XTurn"]
tictactoeBoard(state)
-- Check for game end
local result = tictactoeCheckGameOver(state)
print(result, "\n")
if result == "X" then
state["GameChannel"]:send("Player One wins!")
tictactoeExitGame(state)
elseif result == "O" then
state["GameChannel"]:send("Player Two wins!")
tictactoeExitGame(state)
elseif result == "T" then
state["GameChannel"]:send("Tie game!")
tictactoeExitGame(state)
end
return true
end
function tictactoeExitGame(state)
--[[Close the game]]
state["GameChannel"]:send("Quitting game...")
games.deregisterGame(state["GameChannel"])
end
return tictactoe
|
local site_vars = require '_deployment.site_vars'
local sugar = require '_deployment.sugar'
return function (str)
local header = str:match("[-][-][-][\n](.-)[\n][-][-][-]")
local content = str:match("[-][-][-][\n].-[\n][-][-][-]\n(.*)")
local dict = {}
for key in header:gmatch("(%w+):") do
local value = header:match(key .. ":%s*(%w+%s*%w+)%s*")
dict[key] = value
end
dict.page_title = dict.title or "Page Title"
dict.title = nil
dict.page_content = sugar(site_vars.apply(content, dict))
dict.__index = dict
return dict
end
|
return {
{
'williamboman/nvim-lsp-installer',
config = function()
require("custom.plugins.lsp-installer").setup()
end
},
{ 'voldikss/vim-floaterm' },
{
'jose-elias-alvarez/null-ls.nvim',
after = "nvim-lspconfig",
config = function()
require("custom.plugins.null-ls").setup()
end
},
{
"folke/trouble.nvim",
requires = "kyazdani42/nvim-web-devicons",
config = function()
require("trouble").setup {
}
end
},
{
"nvim-telescope/telescope-media-files.nvim",
after = "telescope.nvim",
config = function()
require("telescope").setup {
extensions = {
media_files = {
filetypes = { "png", "webp", "jpg", "jpeg" },
find_cmd = "rg", -- find command (defaults to `fd`)
},
},
}
require("telescope").load_extension "media_files"
end,
}
}
|
------------------------------------------------------------------------
--[[ CTCCriterion ]] --
-- CTC Alignment for sequence data where input and labels do not align.
-- Useful for speech recognition on a phoneme/character level basis.
-- Inputs assumed are in the form of seqLength x batch x inputDim.
-- If batchFirst = true then input in the form of batch x seqLength x inputDim.
-- Targets assumed in the form of {{1,2},{3,4}} where {1,2} is for the first
-- element and so forth.
------------------------------------------------------------------------
local CTCCriterion, parent = torch.class('nn.CTCCriterion', 'nn.Criterion')
function CTCCriterion:__init(batchFirst)
require 'warp_ctc'
parent.__init(self)
self.acts = torch.Tensor()
self.batchFirst = batchFirst or false
end
function CTCCriterion:forward(input, target, sizes)
return self:updateOutput(input, target, sizes)
end
function CTCCriterion:updateOutput(input, target, sizes)
assert(sizes,
"You must pass the size of each sequence in the batch as a tensor")
local acts = self.acts
acts:resizeAs(input):copy(input)
if input:dim() == 3 then
if self.batchFirst then
acts = acts:transpose(1, 2)
acts = self:makeContiguous(acts)
end
acts:view(acts, acts:size(1) * acts:size(2), -1)
end
assert(acts:nDimension() == 2)
self.sizes = torch.totable(sizes)
self.gradInput = acts.new():resizeAs(acts):zero()
if input:type() == 'torch.CudaTensor' then
self.output = sumCosts(gpu_ctc(acts, self.gradInput, target, self.sizes))
else
acts = acts:float()
self.gradInput = self.gradInput:float()
self.output = sumCosts(cpu_ctc(acts, self.gradInput, target, self.sizes))
end
return self.output / sizes:size(1)
end
function CTCCriterion:updateGradInput(input, target)
if input:dim() == 2 then -- (seqLen * batchSize) x outputDim
return self.gradInput
end
if self.batchFirst then -- batchSize x seqLen x outputDim
self.gradInput = self.gradInput:view(input:size(2), input:size(1), -1):transpose(1, 2)
else -- seqLen x batchSize x outputDim
self.gradInput:view(self.gradInput, input:size(1), input:size(2), -1)
end
return self.gradInput
end
function CTCCriterion:makeContiguous(input)
if not input:isContiguous() then
self._input = self._input or input.new()
self._input:typeAs(input):resizeAs(input):copy(input)
input = self._input
end
return input
end
--If batching occurs multiple costs are returned. We sum the costs and return.
function sumCosts(list)
local acc
for k, v in ipairs(list) do
if 1 == k then
acc = v
else
acc = acc + v
end
end
return acc
end
|
function Mapfill_tilegen2(Map_ID,Map_Size_X,Map_Size_Y,Map_Size_Z,args)
local Tile_Size = 64
local time = os.clock()
local xrand = 4
if args ~= "" then
xrand = tonumber(args)
end
local sea = Map_Size_Z/2-1
local z = sea
local heights = {[0]=z}
for y=0,Map_Size_Y do
--z = (Map_Size_Z-1)*(y%2) --was to test it ;)
for x=0,Tile_Size do
if heights[x] == nil then heights[x] = z end
local dif = heights[x]-z
if math.abs(dif) > 1 then
if z > heights[x] then
z = z-1
else
z = z+1
end
else
if math.random(1,xrand) == 1 then
local rand = math.random(0,Map_Size_Z)
if rand > z then
z = z+1
else
z = z-1
end
end
end
for iz=0,z-1 do
Map_Block_Change(-1, Map_ID, x,y,iz, 3, 0, 0, 0, 0)
end
if z > sea then
Map_Block_Change(-1, Map_ID, x,y,z, 2, 0, 0, 0, 0)
else
for iz=z,sea do
Map_Block_Change(-1, Map_ID, x,y,iz, 8, 0, 0, 0, 0)
end
Map_Block_Change(-1, Map_ID, x,y,z, 12, 0, 0, 0, 0)
end
heights[x] = z
end
end
time = os.clock()-time
System_Message_Network_Send_2_All(Map_ID, string.format("&eInitial gen took: %sms",time*1000))
time = os.clock()
local Tiles = math.floor(Map_Size_X/Tile_Size)
for ix=0,Tile_Size do
for i=0,Tiles do
for iy=0,Map_Size_Y do
for iz=0,Map_Size_Z do
local eX = (i*Tile_Size)+ix
local Type = Map_Block_Get_Type(Map_ID, ix, iy, iz)
Map_Block_Change(-1, Map_ID, eX, iy+i, iz, Type, 0, 0, 0, 0)
end
end
end
end
time = os.clock()-time
System_Message_Network_Send_2_All(Map_ID, string.format("&ecopying took: %sms",time*1000))
end
function Mapfill_tilegen(...)
print(pcall(Mapfill_tilegen2,...))
end
--Map_Fill(123, "yltgen")
System_Message_Network_Send_2_All(-1, "&etilegen reloaded")
|
local Path = require'plenary.path'
local os_sep = Path.path.sep
local F = require('plenary.functional')
local uv = vim.loop
local m = {}
local get_gitignore = function(basepath)
local gitignore = {}
local valid = false
for _, v in ipairs(basepath) do
local p = Path:new(v .. os_sep .. '.gitignore')
if p:exists() then
valid = true
gitignore[v] = {}
for l in p:iter() do
if l ~= '' then
local el = l:gsub('%#.*', '')
el = el:gsub('%.', '%%.')
el = el:gsub('%*', '%.%*')
if el ~= '' then
table.insert(gitignore[v], el)
end
end
end
end
end
if not valid then return nil end
return gitignore
end
local interpret_gitignore = function(gitignore, bp, entry)
for _, v in ipairs(bp) do
if entry:find(v, 1, true) then
for _, w in ipairs(gitignore[v]) do
if entry:match(w) then return false end
end
end
end
return true
end
local handle_depth = function(base_paths, entry, depth)
for _, v in ipairs(base_paths) do
if entry:find(v, 1, true) then
local cut = entry:sub(#v + 1, -1)
cut = cut:sub(1, 1) == os_sep and cut:sub(2, -1) or cut
local _, count = cut:gsub(os_sep, "")
if depth <= (count + 1) then
return nil
end
end
end
return entry
end
local gen_search_pat = function(pattern)
if type(pattern) == 'string' then
return function(entry)
return entry:match(pattern)
end
elseif type(pattern) == 'table' then
return function(entry)
for _, v in ipairs(pattern) do
if entry:match(v) then return true end
end
return false
end
end
end
local process_item = function(opts, name, typ, current_dir, next_dir, bp, data, giti, msp)
if opts.hidden or name:sub(1, 1) ~= '.' then
if typ == 'directory' then
local entry = current_dir .. os_sep .. name
if opts.depth then
table.insert(next_dir, handle_depth(bp, entry, opts.depth))
else
table.insert(next_dir, entry)
end
if opts.add_dirs then
if not msp or msp(entry) then
table.insert(data, entry)
if opts.on_insert then opts.on_insert(entry, typ) end
end
end
else
local entry = current_dir .. os_sep .. name
if not giti or interpret_gitignore(giti, bp, entry) then
if not msp or msp(entry) then
table.insert(data, entry)
if opts.on_insert then opts.on_insert(entry, typ) end
end
end
end
end
end
--- m.scan_dir
-- Search directory recursive and syncronous
-- @param path: string or table
-- string has to be a valid path
-- table has to be a array of valid paths
-- @param opts: table to change behavior
-- opts.hidden (bool): if true hidden files will be added
-- opts.add_dirs (bool): if true dirs will also be added to the results
-- opts.respect_gitignore (bool): if true will only add files that are not ignored by the git (uses each gitignore found in path table)
-- opts.depth (int): depth on how deep the search should go
-- opts.search_pattern (regex): regex for which files will be added, string or table of strings
-- opts.on_insert(entry): Will be called for each element
-- opts.silent (bool): if true will not echo messages that are not accessible
-- @return array with files
m.scan_dir = function(path, opts)
opts = opts or {}
local data = {}
local base_paths = vim.tbl_flatten { path }
local next_dir = vim.tbl_flatten { path }
local gitignore = opts.respect_gitignore and get_gitignore(base_paths) or nil
local match_seach_pat = opts.search_pattern and gen_search_pat(opts.search_pattern) or nil
for i = table.getn(base_paths), 1, -1 do
if uv.fs_access(base_paths[i], "X") == false then
if not F.if_nil(opts.silent, false, opts.silent) then
print(string.format("%s is not accessible by the current user!", base_paths[i]))
end
table.remove(base_paths, i)
end
end
if table.getn(base_paths) == 0 then return {} end
repeat
local current_dir = table.remove(next_dir, 1)
local fd = uv.fs_scandir(current_dir)
if fd then
while true do
local name, typ = uv.fs_scandir_next(fd)
if name == nil then break end
process_item(opts, name, typ, current_dir, next_dir, base_paths, data, gitignore, match_seach_pat)
end
end
until table.getn(next_dir) == 0
return data
end
--- m.scan_dir_async
-- Search directory recursive and syncronous
-- @param path: string or table
-- string has to be a valid path
-- table has to be a array of valid paths
-- @param opts: table to change behavior
-- opts.hidden (bool): if true hidden files will be added
-- opts.add_dirs (bool): if true dirs will also be added to the results
-- opts.respect_gitignore (bool): if true will only add files that are not ignored by git
-- opts.depth (int): depth on how deep the search should go
-- opts.search_pattern (lua regex): depth on how deep the search should go
-- opts.on_insert function(entry): will be called for each element
-- opts.on_exit function(results): will be called at the end
-- opts.silent (bool): if true will not echo messages that are not accessible
m.scan_dir_async = function(path, opts)
opts = opts or {}
local data = {}
local base_paths = vim.tbl_flatten { path }
local next_dir = vim.tbl_flatten{ path }
local current_dir = table.remove(next_dir, 1)
-- TODO(conni2461): get gitignore is not async
local gitignore = opts.respect_gitignore and get_gitignore() or nil
local match_seach_pat = opts.search_pattern and gen_search_pat(opts.search_pattern) or nil
-- TODO(conni2461): is not async. Shouldn't be that big of a problem but still
-- Maybe obers async pr can take me out of callback hell
for i = table.getn(base_paths), 1, -1 do
if uv.fs_access(base_paths[i], "X") == false then
if not F.if_nil(opts.silent, false, opts.silent) then
print(string.format("%s is not accessible by the current user!", base_paths[i]))
end
table.remove(base_paths, i)
end
end
if table.getn(base_paths) == 0 then return {} end
local read_dir
read_dir = function(err, fd)
if not err then
while true do
local name, typ = uv.fs_scandir_next(fd)
if name == nil then break end
process_item(opts, name, typ, current_dir, next_dir, base_paths, data, gitignore, match_seach_pat)
end
if table.getn(next_dir) == 0 then
if opts.on_exit then opts.on_exit(data) end
else
current_dir = table.remove(next_dir, 1)
uv.fs_scandir(current_dir, read_dir)
end
end
end
uv.fs_scandir(current_dir, read_dir)
end
local gen_permissions = (function()
local conv_to_octal = function(nr)
local octal, i = 0, 1
while nr ~= 0 do
octal = octal + (nr % 8) * i
nr = math.floor(nr / 8)
i = i * 10
end
return octal;
end
local type_tbl = { [1] = 'p', [2] = 'c', [4] = 'd', [6] = 'b', [10] = '.', [12] = 'l', [14] = 's' }
local permissions_tbl = { [0] = '---', '--x', '-w-', '-wx', 'r--', 'r-x', 'rw-', 'rwx' }
local bit_tbl = { 4, 2, 1 }
return function(cache, mode)
if cache[mode] then return cache[mode] end
local octal = string.format('%6d', conv_to_octal(mode))
local l4 = octal:sub(#octal - 3, -1)
local bit = tonumber(l4:sub(1, 1))
local result = type_tbl[tonumber(octal:sub(1, 2))] or '-'
for i = 2, #l4 do
result = result .. permissions_tbl[tonumber(l4:sub(i, i))]
if bit - bit_tbl[i - 1] >= 0 then
result = result:sub(1, -2) .. (bit_tbl[i - 1] == 1 and 'T' or 'S')
bit = bit - bit_tbl[i - 1]
end
end
cache[mode] = result
return result
end
end)()
local gen_size = (function()
local size_types = { '', 'K', 'M', 'G', 'T', 'P', 'E', 'Z' }
return function(size)
-- TODO(conni2461): If type directory we could just return 4.0K
for _, v in ipairs(size_types) do
if math.abs(size) < 1024.0 then
if math.abs(size) > 9 then
return string.format("%3d%s", size, v)
else
return string.format("%3.1f%s", size, v)
end
end
size = size / 1024.0
end
return string.format("%.1f%s", size, 'Y')
end
end)()
local gen_date = (function()
local current_year = os.date('%Y')
return function(mtime)
if current_year ~= os.date('%Y', mtime) then
return os.date('%b %d %Y', mtime)
end
return os.date('%b %d %H:%M', mtime)
end
end)()
local get_username = (function()
if jit and os_sep ~= '\\' then
local ffi = require'ffi'
ffi.cdef[[
typedef unsigned int __uid_t;
typedef __uid_t uid_t;
typedef unsigned int __gid_t;
typedef __gid_t gid_t;
typedef struct {
char *pw_name;
char *pw_passwd;
__uid_t pw_uid;
__gid_t pw_gid;
char *pw_gecos;
char *pw_dir;
char *pw_shell;
} passwd;
passwd *getpwuid(uid_t uid);
]]
return function(tbl, id)
if tbl[id] then return tbl[id] end
local name = ffi.string(ffi.C.getpwuid(id).pw_name)
tbl[id] = name
return name
end
else
return function(tbl, id)
if not tbl then return id end
if tbl[id] then return tbl[id] end
tbl[id] = tostring(id)
return id
end
end
end)()
local get_groupname = (function()
if jit and os_sep ~= '\\' then
local ffi = require'ffi'
ffi.cdef[[
typedef unsigned int __gid_t;
typedef __gid_t gid_t;
typedef struct {
char *gr_name;
char *gr_passwd;
__gid_t gr_gid;
char **gr_mem;
} group;
group *getgrgid(gid_t gid);
]]
return function(tbl, id)
if tbl[id] then return tbl[id] end
local name = ffi.string(ffi.C.getgrgid(id).gr_name)
tbl[id] = name
return name
end
else
return function(tbl, id)
if not tbl then return id end
if tbl[id] then return tbl[id] end
tbl[id] = tostring(id)
return id
end
end
end)()
local get_max_len = function(tbl)
if not tbl then return 0 end
local max_len = 0
for _, v in pairs(tbl) do
if #v > max_len then
max_len = #v
end
end
return max_len
end
local gen_ls = function(data, path, opts)
if not data or table.getn(data) == 0 then return {}, {} end
local check_link = function(per, file)
if per:sub(1, 1) == 'l' then
local resolved = uv.fs_realpath(path .. os_sep .. file)
if not resolved then return file end
if resolved:sub(1, #path) == path then resolved = resolved:sub(#path + 2, -1) end
return string.format('%s -> %s', file, resolved)
end
return file
end
local results, sections = {}, {}
local users_tbl = os_sep ~= '\\' and {} or nil
local groups_tbl = os_sep ~= '\\' and {} or nil
local stats, permissions_cache = {}, {}
for _, v in ipairs(data) do
local stat = uv.fs_lstat(v)
if stat then
stats[v] = stat
get_username(users_tbl, stat.uid)
get_groupname(groups_tbl, stat.gid)
end
end
local insert_in_results = (function()
if not users_tbl and not groups_tbl then
local section_spacing_tbl = { [5] = 2, [6] = 0 }
return function(...)
local args = {...}
local section = {
{ start_index = 01, end_index = 11 }, -- permissions, hardcoded indexes
{ start_index = 12, end_index = 17 }, -- size, hardcoded indexes
}
local cur_index = 19
for k = 5, 6 do
local v = section_spacing_tbl[k]
local end_index = cur_index + #args[k]
table.insert(section, { start_index = cur_index, end_index = end_index })
cur_index = end_index + v
end
table.insert(sections, section)
table.insert(results, string.format('%10s %5s %s %s', args[1], args[2], args[5], check_link(args[1], args[6])))
end
else
local max_user_len = get_max_len(users_tbl)
local max_group_len = get_max_len(groups_tbl)
local section_spacing_tbl = {
[3] = { max = max_user_len, add = 1 },
[4] = { max = max_group_len, add = 2 },
[5] = { add = 2 }, [6] = { add = 0 }
}
local fmt_str = '%10s %5s %-' .. max_user_len .. 's %-' .. max_group_len ..'s %s %s'
return function(...)
local args = {...}
local section = {
{ start_index = 01, end_index = 11 }, -- permissions, hardcoded indexes
{ start_index = 12, end_index = 17 }, -- size, hardcoded indexes
}
local cur_index = 18
for k = 3, 6 do
local v = section_spacing_tbl[k]
local end_index = cur_index + #args[k]
table.insert(section, { start_index = cur_index, end_index = end_index })
if v.max then
cur_index = cur_index + v.max + v.add
else
cur_index = end_index + v.add
end
end
table.insert(sections, section)
table.insert(results,
string.format(fmt_str, args[1], args[2], args[3], args[4], args[5], check_link(args[1], args[6]))
)
end
end
end)()
for name, stat in pairs(stats) do
insert_in_results(
gen_permissions(permissions_cache, stat.mode),
gen_size(stat.size),
get_username(users_tbl, stat.uid),
get_groupname(groups_tbl, stat.gid),
gen_date(stat.mtime.sec),
name:sub(#path + 2, -1)
)
end
if opts and opts.group_directories_first then
local sorted_results = {}
local sorted_sections = {}
for k, v in ipairs(results) do
if v:sub(1, 1) == 'd' then
table.insert(sorted_results, v)
table.insert(sorted_sections, sections[k])
end
end
for k, v in ipairs(results) do
if v:sub(1, 1) ~= 'd' then
table.insert(sorted_results, v)
table.insert(sorted_sections, sections[k])
end
end
return sorted_results, sorted_sections
else
return results, sections
end
end
--- m.ls
-- List directory contents. Will always apply --long option. Use scan_dir for without --long
-- @param path: string
-- string has to be a valid path
-- @param opts: table to change behavior
-- opts.hidden (bool): if true hidden files will be added
-- opts.add_dirs (bool): if true dirs will also be added to the results, default: true
-- opts.respect_gitignore (bool): if true will only add files that are not ignored by git
-- opts.depth (int): depth on how deep the search should go, default: 1
-- opts.group_directories_first (bool): same as real ls
-- @return array with formatted output
m.ls = function(path, opts)
opts = opts or {}
opts.depth = opts.depth or 1
opts.add_dirs = opts.add_dirs or true
local data = m.scan_dir(path, opts)
return gen_ls(data, path, opts)
end
--- m.ls_async
-- List directory contents. Will always apply --long option. Use scan_dir for without --long
-- @param path: string
-- string has to be a valid path
-- @param opts: table to change behavior
-- opts.hidden (bool): if true hidden files will be added
-- opts.add_dirs (bool): if true dirs will also be added to the results, default: true
-- opts.respect_gitignore (bool): if true will only add files that are not ignored by git
-- opts.depth (int): depth on how deep the search should go, default: 1
-- opts.group_directories_first (bool): same as real ls
-- opts.on_exit function(results): will be called at the end (required)
m.ls_async = function(path, opts)
opts = opts or {}
opts.depth = opts.depth or 1
opts.add_dirs = opts.add_dirs or true
local opts_copy = vim.deepcopy(opts)
opts_copy.on_exit = function(data)
if opts.on_exit then opts.on_exit(gen_ls(data, path, opts_copy)) end
end
m.scan_dir_async(path, opts_copy)
end
return m
|
--[[
**
** Srg Utility - Mod deobfuscation mappings
**
** Target mappings:
** - Obfuscated -> Packaged MCP (obf2pkgmcp.srg)
** - Packaged Numeric -> Packaged MCP (pkgnum2pkgmcp.srg)
** - CraftBukkit -> Packaged MCP (cb2pkgmcp.srg)
**
** Target inheritance:
** - Forge inheritance (nms.inheritmap)
** - Bukkit inheritance remapped to Packaged (cb.inheritmap)
**
]]--
--[[---------------
|| Configuration
--]]---------------
local config = {}
-- [Required] Minecraft version to generate mappings for
config.minecraftVersion = "1.6.2"
-- [Required] Forge version to generate mappings for
config.forgeVersion = "9.10.1.871"
-- [Optional] Root directory, used for convenience
config.rootDir = "./"
-- [Required] The directory jars will be downloaded to and confs will be extracted to
config.cacheDir = config.rootDir .. "cache/"
-- [Required] Directory to output all generated mappings to
config.outDir = config.rootDir .. config.minecraftVersion .. ".mod-deobf/"
-- [Optional] Enable/disable verbose mode
config.verbose = true
--[[------------
|| Entrypoint
--]]------------
function main()
downloadJars()
prepareConfDir()
printf("Generating mappings for MC %s / Forge %s...", config.minecraftVersion, config.forgeVersion)
-- Load base mapping from MCP/FML
local obfToNum = nil
if (fs.exists(config.mcpDir .. "joined.srg")) then
verbosePrint("Loading joined.srg...")
obfToNum = MappingFactory.loadSrg(config.mcpDir .. "joined.srg")
else
verbosePrint("Loading client.srg and server.srg...")
obfToNum = MappingFactory.loadSrg(config.mcpDir .. "client.srg", config.mcpDir .. "server.srg")
end
verbosePrint("Loading MCP mappings...")
-- Load MCP package mapping
local packageMapping = MappingFactory.loadMCP(nil, nil, config.mcpDir .. "packages.csv")
-- Load full MCP mapping
local MCPMapping = MappingFactory.loadMCP(config.mcpDir .. "fields.csv", config.mcpDir .. "methods.csv", config.mcpDir .. "packages.csv")
verbosePrint("Transforming mappings...")
verbosePrint("\tTransforming obfuscated -> numeric to obfuscated -> packged numeric")
local obfToPkgNum = obfToNum:clone():transform(nil, packageMapping)
verbosePrint("\tTransforming obfuscated -> numeric to obfuscated -> packaged MCP")
local obfToMcp = obfToNum:clone():transform(nil, MCPMapping)
verbosePrint("\tTransforming obfuscated -> packaged MCP to packaged numeric -> packaged MCP")
local pkgNumToMcp = obfToMcp:clone():transform(obfToPkgNum, nil)
verbosePrint("\tGenerating obfuscated -> bukkit...")
local obfToCb = MappingFactory.compareJars(config.serverJar, config.bukkitJar):filter(obfToNum)
verbosePrint("\tTransforming obfuscated -> bukkit to bukkit -> packaged MCP")
local cbToPkgMcp = obfToCb:clone():reverse():transform(nil, obfToMcp)
verbosePrint("Generating nms inheritance map...")
local nmsInherit = MappingFactory.makeInheritanceMap(config.clientJar, obfToMcp):transform(obfToMcp)
verbosePrint("Generating cb inheritance map...")
local cbInherit = MappingFactory.makeInheritanceMap(config.bukkitJar, cbToPkgMcp):transform(cbToPkgMcp)
verbosePrint("Saving mappings...")
verbosePrint("\tobf2pkgmcp.srg")
obfToMcp:saveToFile(config.outDir .. "obf2pkgmcp.srg")
verbosePrint("\tpkgnum2pkgmcp.srg")
pkgNumToMcp:saveToFile(config.outDir .. "pkgnum2pkgmcp.srg")
verbosePrint("\tcb2pkgmcp.srg")
cbToPkgMcp:saveToFile(config.outDir .. "cb2pkgmcp.srg")
verbosePrint("\tnms.inheritmap")
nmsInherit:saveToFile(config.outDir .. "nms.inheritmap")
verbosePrint("\tcb.inheritmap")
cbInherit:saveToFile(config.outDir .. "cb.inheritmap")
print("Mapping generation complete.")
end
--[[-------------------
|| Utility Functions
--]]-------------------
function verbosePrint(...)
if (config.verbose) then
print(...)
end
end
function printf(fmt, ...)
print(string.format(fmt, ...))
end
-- Checks Conf directory to make sure all necessary files exist, extracting them from the forge zip if necessary
function prepareConfDir()
print("Preparing conf directory...")
config.mcpDir = string.format("%sconf_%s-%s/", config.cacheDir, config.minecraftVersion, config.forgeVersion)
fs.makeDir(config.mcpDir)
local zipFile = zip.open(config.forgeZip)
if (not (fs.exists(config.mcpDir .. "joined.srg") or (fs.exists(config.mcpDir .. "client.srg") and fs.exists(config.mcpDir .. "server.srg")))) then
local joined = zipFile:getEntry("forge/fml/conf/joined.srg")
local client = zipFile:getEntry("forge/fml/conf/client.srg")
local server = zipFile:getEntry("forge/fml/conf/server.srg")
if (joined ~= nil) then
zipFile:extract(joined, config.mcpDir .. "joined.srg")
elseif (client ~= nil and server ~= nil) then
zipFile:extract(client, config.mcpDir .. "client.srg")
zipFile:extract(server, config.mcpDir .. "server.srg")
else
error("Could not find base srg(s).")
end
end
if (not fs.exists(config.mcpDir .. "fields.csv")) then
local entry = zipFile:getEntry("forge/fml/conf/fields.csv")
if (entry ~= nil) then
zipFile:extract(entry, config.mcpDir .. "fields.csv")
else
error("Could not find fields.csv.")
end
end
if (not fs.exists(config.mcpDir .. "methods.csv")) then
local entry = zipFile:getEntry("forge/fml/conf/methods.csv")
if (entry ~= nil) then
zipFile:extract(entry, config.mcpDir .. "methods.csv")
else
error("Could not find methods.csv.")
end
end
if (not fs.exists(config.mcpDir .. "packages.csv")) then
local entry = zipFile:getEntry("forge/fml/conf/packages.csv")
if (entry ~= nil) then
zipFile:extract(entry, config.mcpDir .. "packages.csv")
else
error("Could not find packages.csv.")
end
end
zipFile:close()
end
function downloadJars()
if (not fs.exists(config.cacheDir)) then
fs.makeDir(config.cacheDir)
end
config.clientJar = string.format("%sclient_%s.jar", config.cacheDir, config.minecraftVersion)
config.serverJar = string.format("%sserver_%s.jar", config.cacheDir, config.minecraftVersion)
config.bukkitJar = string.format("%sbukkit_%s.jar", config.cacheDir, config.minecraftVersion)
config.forgeZip = string.format("%sforge_%s-%s.zip", config.cacheDir, config.minecraftVersion, config.forgeVersion)
print("Checking jars...")
if (not fs.exists(config.clientJar)) then
print("\tDownloading minecraft client jar...")
HTTP.download(string.format("http://s3.amazonaws.com/Minecraft.Download/versions/%s/%s.jar", config.minecraftVersion, config.minecraftVersion), config.clientJar)
else
print("\tUsing cached minecraft client jar...")
end
if (not fs.exists(config.serverJar)) then
print("\tDownloading minecraft server jar...")
HTTP.download(string.format("http://s3.amazonaws.com/Minecraft.Download/versions/%s/minecraft_server.%s.jar", config.minecraftVersion, config.minecraftVersion), config.serverJar)
else
print("\tUsing cached minecraft server jar...")
end
if (not fs.exists(config.bukkitJar)) then
print("\tDownloading bukkit server jar...")
HTTP.download(string.format("http://repo.bukkit.org/content/repositories/releases/org/bukkit/minecraft-server/%s/minecraft-server-%s.jar", config.minecraftVersion, config.minecraftVersion), config.bukkitJar)
else
print("\tUsing cached bukkit server jar...")
end
if (not fs.exists(config.forgeZip)) then
print("\tDownloading minecraft forge zip...")
HTTP.download(string.format("http://files.minecraftforge.net/minecraftforge/minecraftforge-src-%s-%s.zip", config.minecraftVersion, config.forgeVersion), config.forgeZip)
else
print("\tUsing cached minecraft forge zip...")
end
end
main()
|
-- solver for bipartite matching in simplex as LP
luasimplex = require("luasimplex")
rsm = require("luasimplex.rsm")
M =
{
--number of variables
nvars = 1,
--number of constraints
nrows = 1,
--objective
c = luasimplex.darray(1,1),
--scale of variables
xl = luasimplex.darray(1,0),
xu = luasimplex.darray(1,1),
--constant in constraints
b = luasimplex.darray(1,1),
--constraints parameters
elements = luasimplex.darray(1,1),
--idx of variables in elements
indexes = luasimplex.iarray(1,1),
--start of constraits in elements
row_starts = luasimplex.iarray(2,1,2),
}
function simplex_init(nr , np , W , gt , margin)
--initialize M
local tmp
M.nvars = nr*np+np+nr
M.nrows = nr+np
M.c = luasimplex.darray(M.nvars)
M.b = luasimplex.darray(M.nrows)
M.xu = luasimplex.darray(M.nvars)
M.xl = luasimplex.darray(M.nvars)
M.row_starts = luasimplex.iarray(M.nrows+1)
M.elements = luasimplex.darray(2*np*nr+np+nr)
M.indexes = luasimplex.iarray(2*np*nr+np+nr)
for i=1,M.nvars do
M.xu[i]=1
M.xl[i]=0
end
M.row_starts[1] = 1
for i = 1,nr do
M.c[np*nr+i] = 0
tmp = i*(np+1)
M.row_starts[i+1] = tmp+1
M.indexes[tmp] = np*nr+i
M.elements[tmp] = -1
M.b[i] = 0
end
-- two limits for nonvisual phrase
--M.xu[np*nr+nr] = 30
for j = 1,np do
M.xl[np*nr+nr+j] = 1
M.c[np*nr+nr+j] = 0
tmp = nr*(np+1)+(nr+1)*j
M.row_starts[nr+j+1] = tmp+1
M.indexes[tmp] = np*nr+nr+j
M.elements[tmp] = -1
M.b[nr+j] = 0
end
for i=1,nr do
for j = 1,np do
M.c[(i-1)*np+j] = -W[{i,j}] - margin--hamming dis
M.indexes[(i-1)*(np+1)+j] = (i-1)*np+j
M.elements[(i-1)*(np+1)+j] = 1
M.indexes[nr*(np+1)+(j-1)*(nr+1)+i] = (i-1)*np+j
M.elements[nr*(np+1)+(j-1)*(nr+1)+i] = 1
end
end
for j = 1,np do
if gt[j] > 0 then
M.c[(gt[j]-1)*np+j] = M.c[(gt[j]-1)*np+j] + 2*margin
end
end
end
-- add hamming distances
-- two adjustment: objective plus sum of gt. weights in objective plus (1-2*y_ij)
function solve_matching(W , gt , margin)
local nr,np = W:size()[1], W:size()[2]
simplex_init(nr , np , W , gt , margin)
local I = luasimplex.new_instance(M.nrows, M.nvars)
rsm.initialise(M, I, {})
objective, x = rsm.solve(M, I, {})
ans = torch.Tensor(gt:size()):fill(0)
for j = 1,np do
if gt[j] > 0 then
objective = objective - margin + W[{gt[j],j}]
end
for i = 1,nr do
if x[(i-1)*np+j] > 0 then
ans[j] = i
end
end
end
--io.stderr:write(("Objective: %g\n"):format(objective))
--io.stderr:write(" x:")
--for i = 1, M.nvars do io.stderr:write((" %g"):format(x[i])) end
--io.stderr:write("\n")
return -objective , ans
end
|
-- Set vim as local variable for lua diagnostics
local vim = vim
-- Formatter config
-- Prettier function for formatter
local prettier = function()
return {
exe = "/Users/cbasar/.nvm/versions/node/v14.15.1/bin/prettier",
args = {
"--stdin-filepath",
"--config-precedence",
"prefer-file",
vim.api.nvim_buf_get_name(0),
"--single-quote"
},
stdin = true
}
end
require("formatter").setup(
{
logging = false,
filetype = {
javascript = {prettier},
json = {prettier},
typescript = {prettier},
html = {prettier},
css = {prettier},
scss = {prettier},
markdown = {prettier},
vue = {prettier},
lua = {
-- luafmt
function()
return {
exe = "/Users/cbasar/.nvm/versions/node/v14.15.1/bin/luafmt",
args = {"--indent-count", 2, "--stdin"},
stdin = true
}
end
}
}
}
)
-- Runs Prettier on save
vim.api.nvim_exec(
[[
augroup FormatAutogroup
autocmd!
autocmd BufWritePost *.js,*.json,*.ts,*.css,*.scss,*.md,*.html,*.lua,*.vue : FormatWrite
augroup END
]],
true
)
-- " Provided by setup function
-- nnoremap <silent> <leader>f :Format<CR>
|
local vim = vim
local ui = {
query_win = 0,
result_win = 0,
}
local buf, win, start_win
--- create_win
ui.create_win = function()
start_win = vim.api.nvim_get_current_win()
vim.api.nvim_command('botright new') -- We open a new vertical window at the far right
win = vim.api.nvim_get_current_win() -- We save our navigation window handle...
buf = vim.api.nvim_get_current_buf() -- ...and it's buffer handle.
vim.api.nvim_buf_set_name(buf, 'SQHeavenResult #' .. buf)
vim.api.nvim_buf_set_option(buf, 'buftype', 'nofile')
vim.api.nvim_buf_set_option(buf, 'swapfile', false)
vim.api.nvim_buf_set_option(buf, 'bufhidden', 'wipe')
vim.api.nvim_buf_set_option(buf, 'filetype', 'nvim-sqheaven-resultset')
-- For better UX we will turn off line wrap and turn on current line highlight.
vim.api.nvim_win_set_option(win, 'wrap', false)
vim.api.nvim_win_set_option(win, 'cursorline', true)
end
--- redraw
ui.redraw = function (result)
vim.api.nvim_buf_set_option(buf, 'modifiable', true)
vim.api.nvim_buf_set_lines(buf, 0, -1, false, result)
vim.api.nvim_buf_set_option(buf, 'modifiable', false)
vim.api.nvim_set_current_win(ui.query_win)
end
--- motion
ui.motion = function(bufnr, mode)
local b_line, b_col, e_line, e_col, _
b_line, b_col = unpack(vim.api.nvim_buf_get_mark(bufnr, '('))
e_line, e_col = unpack(vim.api.nvim_buf_get_mark(bufnr, ')'))
b_col = b_col + 1
e_col = e_col + 2
return {
from = {b_line, b_col},
to = {e_line, e_col},
bufnr = bufnr
}
end
--- show_win
ui.show_win = function()
if win and vim.api.nvim_win_is_valid(win) then
vim.api.nvim_set_current_win(win)
else
ui.create_win()
end
end
ui.change_query_file = function(file)
vim.api.nvim_set_current_win(ui.query_win)
vim.api.nvim_command('edit'..file)
end
--- start
ui.start = function(file)
vim.api.nvim_command('tabnew'..file)
ui.query_win = vim.api.nvim_get_current_win()
end
return ui
|
-- Returns the group ID of the specified interior. For example, regular interiors have group 0, subway interiors have group 1. There are a few other groups too.
-- @module native
-- @submodule interior
-- @see GET_INTERIOR_GROUP_ID
-- @usage int GET_INTERIOR_GROUP_ID(int interiorID);
-- @param interiorID int
-- @return int
function GetInteriorGroupId(interiorID) end
-- @todo
-- @module native
-- @submodule interior
-- @see GET_OFFSET_FROM_INTERIOR_IN_WORLD_COORDS
-- @usage Vector3 GET_OFFSET_FROM_INTERIOR_IN_WORLD_COORDS(int interiorID, float x, float y, float z);
-- @param interiorID int
-- @param x float
-- @param y float
-- @param z float
-- @return Vector3
function GetOffsetFromInteriorInWorldCoords(interiorID, x, y, z) end
-- @todo
-- @module native
-- @submodule interior
-- @see IS_INTERIOR_SCENE
-- @usage BOOL IS_INTERIOR_SCENE();
-- @return BOOL
function IsInteriorScene() end
-- Return if interior is valid.
-- @module native
-- @submodule interior
-- @see IS_VALID_INTERIOR
-- @usage BOOL IS_VALID_INTERIOR(int interiorID);
-- @param interiorID int
-- @return BOOL
function IsValidInterior(interiorID) end
-- @todo
-- @module native
-- @submodule interior
-- @see CLEAR_ROOM_FOR_ENTITY
-- @usage void CLEAR_ROOM_FOR_ENTITY(Entity entity);
-- @param entity Entity
-- @return void
function ClearRoomForEntity(entity) end
-- Does anyone know what this does? I know online modding isn't generally supported especially by the owner of this db, but I first thought this could be used to force ourselves into someones apartment, but I see now that isn't possible.
-- @module native
-- @submodule interior
-- @see FORCE_ROOM_FOR_ENTITY
-- @usage void FORCE_ROOM_FOR_ENTITY(Entity entity, int interiorID, Hash roomHashKey);
-- @param entity Entity
-- @param interiorID int
-- @param roomHashKey Hash
-- @return void
function ForceRoomForEntity(entity, interiorID, roomHashKey) end
-- Gets the room hash key from the room that the specified entity is in. Each room in every interior has a unique key. Returns 0 if the entity is outside.
-- @module native
-- @submodule interior
-- @see GET_ROOM_KEY_FROM_ENTITY
-- @usage Hash GET_ROOM_KEY_FROM_ENTITY(Entity entity);
-- @param entity Entity
-- @return Hash
function GetRoomKeyFromEntity(entity) end
-- Seems to do the exact same as INTERIOR::GET_ROOM_KEY_FROM_ENTITY
-- @module native
-- @submodule interior
-- @see GET_KEY_FOR_ENTITY_IN_ROOM
-- @usage Hash GET_KEY_FOR_ENTITY_IN_ROOM(Entity entity);
-- @param entity Entity
-- @return Hash
function GetKeyForEntityInRoom(entity) end
-- Returns the handle of the interior that the entity is in. Returns 0 if outside.
-- @module native
-- @submodule interior
-- @see GET_INTERIOR_FROM_ENTITY
-- @usage int GET_INTERIOR_FROM_ENTITY(Entity entity);
-- @param entity Entity
-- @return int
function GetInteriorFromEntity(entity) end
-- Returns interior ID from specified coordinates. If coordinates are outside, then it returns 0. Example for VB.NET Dim interiorID As Integer = Native.Function.Call(Of Integer)(Hash.GET_INTERIOR_AT_COORDS, X, Y, Z)
-- @module native
-- @submodule interior
-- @see GET_INTERIOR_AT_COORDS
-- @usage int GET_INTERIOR_AT_COORDS(float x, float y, float z);
-- @param x float
-- @param y float
-- @param z float
-- @return int
function GetInteriorAtCoords(x, y, z) end
-- @todo
-- @module native
-- @submodule interior
-- @see ADD_PICKUP_TO_INTERIOR_ROOM_BY_NAME
-- @usage void ADD_PICKUP_TO_INTERIOR_ROOM_BY_NAME(Pickup pickup, char* roomName);
-- @param pickup Pickup
-- @param roomName char*
-- @return void
function AddPickupToInteriorRoomByName(pickup, roomName) end
-- Does something similar to INTERIOR::DISABLE_INTERIOR. You don't fall through the floor but everything is invisible inside and looks the same as when INTERIOR::DISABLE_INTERIOR is used. Peds behaves normally inside.
-- @module native
-- @submodule interior
-- @see UNPIN_INTERIOR
-- @usage void UNPIN_INTERIOR(int interiorID);
-- @param interiorID int
-- @return void
function UnpinInterior(interiorID) end
-- @todo
-- @module native
-- @submodule interior
-- @see IS_INTERIOR_READY
-- @usage BOOL IS_INTERIOR_READY(int interiorID);
-- @param interiorID int
-- @return BOOL
function IsInteriorReady(interiorID) end
-- Returns the interior ID representing the requested interior at that location (if found?). The supplied interior string is not the same as the one used to load the interior. Use: INTERIOR::UNPIN_INTERIOR(INTERIOR::GET_INTERIOR_AT_COORDS_WITH_TYPE(x, y, z, interior)) Interior types include: "V_Michael", "V_Franklins", "V_Franklinshouse", etc.. you can find them in the scripts. Not a very useful native as you could just use GET_INTERIOR_AT_COORDS instead and get the same result, without even having to specify the interior type.
-- @module native
-- @submodule interior
-- @see GET_INTERIOR_AT_COORDS_WITH_TYPE
-- @usage int GET_INTERIOR_AT_COORDS_WITH_TYPE(float x, float y, float z, char* interiorType);
-- @param x float
-- @param y float
-- @param z float
-- @param interiorType char*
-- @return int
function GetInteriorAtCoordsWithType(x, y, z, interiorType) end
-- @todo
-- @module native
-- @submodule interior
-- @see GET_INTERIOR_FROM_COLLISION
-- @usage int GET_INTERIOR_FROM_COLLISION(float x, float y, float z);
-- @param x float
-- @param y float
-- @param z float
-- @return int
function GetInteriorFromCollision(x, y, z) end
-- @todo
-- @module native
-- @submodule interior
-- @see REFRESH_INTERIOR
-- @usage void REFRESH_INTERIOR(int interiorID);
-- @param interiorID int
-- @return void
function RefreshInterior(interiorID) end
-- Example: This removes the interior from the strip club and when trying to walk inside the player just falls: INTERIOR::DISABLE_INTERIOR(118018, true);
-- @module native
-- @submodule interior
-- @see DISABLE_INTERIOR
-- @usage void DISABLE_INTERIOR(int interiorID, BOOL toggle);
-- @param interiorID int
-- @param toggle BOOL
-- @return void
function DisableInterior(interiorID, toggle) end
-- @todo
-- @module native
-- @submodule interior
-- @see IS_INTERIOR_DISABLED
-- @usage BOOL IS_INTERIOR_DISABLED(int interiorID);
-- @param interiorID int
-- @return BOOL
function IsInteriorDisabled(interiorID) end
-- Does something similar to INTERIOR::DISABLE_INTERIOR
-- @module native
-- @submodule interior
-- @see CAP_INTERIOR
-- @usage void CAP_INTERIOR(int interiorID, BOOL toggle);
-- @param interiorID int
-- @param toggle BOOL
-- @return void
function CapInterior(interiorID, toggle) end
-- @todo
-- @module native
-- @submodule interior
-- @see IS_INTERIOR_CAPPED
-- @usage BOOL IS_INTERIOR_CAPPED(int interiorID);
-- @param interiorID int
-- @return BOOL
function IsInteriorCapped(interiorID) end
|
local native = peripheral
function getNames()
local tResults = {}
for n,sSide in ipairs( rs.getSides() ) do
if native.isPresent( sSide ) then
table.insert( tResults, sSide )
if native.getType( sSide ) == "modem" and not native.call( sSide, "isWireless" ) then
local tRemote = native.call( sSide, "getNamesRemote" )
for n,sName in ipairs( tRemote ) do
table.insert( tResults, sName )
end
end
end
end
return tResults
end
function isPresent( _sSide )
if type( _sSide ) ~= "string" then
error( "bad argument #1 (expected string, got " .. type( _sSide ) .. ")", 2 )
end
if native.isPresent( _sSide ) then
return true
end
for n,sSide in ipairs( rs.getSides() ) do
if native.getType( sSide ) == "modem" and not native.call( sSide, "isWireless" ) then
if native.call( sSide, "isPresentRemote", _sSide ) then
return true
end
end
end
return false
end
function getType( _sSide )
if type( _sSide ) ~= "string" then
error( "bad argument #1 (expected string, got " .. type( _sSide ) .. ")", 2 )
end
if native.isPresent( _sSide ) then
return native.getType( _sSide )
end
for n,sSide in ipairs( rs.getSides() ) do
if native.getType( sSide ) == "modem" and not native.call( sSide, "isWireless" ) then
if native.call( sSide, "isPresentRemote", _sSide ) then
return native.call( sSide, "getTypeRemote", _sSide )
end
end
end
return nil
end
function getMethods( _sSide )
if type( _sSide ) ~= "string" then
error( "bad argument #1 (expected string, got " .. type( _sSide ) .. ")", 2 )
end
if native.isPresent( _sSide ) then
return native.getMethods( _sSide )
end
for n,sSide in ipairs( rs.getSides() ) do
if native.getType( sSide ) == "modem" and not native.call( sSide, "isWireless" ) then
if native.call( sSide, "isPresentRemote", _sSide ) then
return native.call( sSide, "getMethodsRemote", _sSide )
end
end
end
return nil
end
function call( _sSide, _sMethod, ... )
if type( _sSide ) ~= "string" then
error( "bad argument #1 (expected string, got " .. type( _sSide ) .. ")", 2 )
end
if type( _sSide ) ~= "string" then
error( "bad argument #2 (expected string, got " .. type( _sMethod ) .. ")", 2 )
end
if native.isPresent( _sSide ) then
return native.call( _sSide, _sMethod, ... )
end
for n,sSide in ipairs( rs.getSides() ) do
if native.getType( sSide ) == "modem" and not native.call( sSide, "isWireless" ) then
if native.call( sSide, "isPresentRemote", _sSide ) then
return native.call( sSide, "callRemote", _sSide, _sMethod, ... )
end
end
end
return nil
end
function wrap( _sSide )
if type( _sSide ) ~= "string" then
error( "bad argument #1 (expected string, got " .. type( _sSide ) .. ")", 2 )
end
if peripheral.isPresent( _sSide ) then
local tMethods = peripheral.getMethods( _sSide )
local tResult = {}
for n,sMethod in ipairs( tMethods ) do
tResult[sMethod] = function( ... )
return peripheral.call( _sSide, sMethod, ... )
end
end
return tResult
end
return nil
end
function find( sType, fnFilter )
if type( sType ) ~= "string" then
error( "bad argument #1 (expected string, got " .. type( sType ) .. ")", 2 )
end
if fnFilter ~= nil and type( fnFilter ) ~= "function" then
error( "bad argument #2 (expected function, got " .. type( fnFilter ) .. ")", 2 )
end
local tResults = {}
for n,sName in ipairs( peripheral.getNames() ) do
if peripheral.getType( sName ) == sType then
local wrapped = peripheral.wrap( sName )
if fnFilter == nil or fnFilter( sName, wrapped ) then
table.insert( tResults, wrapped )
end
end
end
return table.unpack( tResults )
end
|
local crypto_onetimeauth_sig = [[
int %s(unsigned char *out, const unsigned char *in,
unsigned long long inlen, const unsigned char *k)
]]
local crypto_onetimeauth_verify_sig = [[
int %s(const unsigned char *h, const unsigned char *in,
unsigned long long inlen, const unsigned char *k)
]]
local crypto_onetimeauth_init_sig = [[
int %s(void *state,
const unsigned char *key)
]]
local crypto_onetimeauth_update_sig = [[
int %s(void *state,
const unsigned char *in,
unsigned long long inlen)
]]
local crypto_onetimeauth_final_sig = [[
int %s(void *state,
unsigned char *out)
]]
local crypto_onetimeauth_keygen_sig = [[
void %s(unsigned char *out)
]]
local crypto_onetimeauth_statebytes_sig = [[
size_t %s(void)
]]
local signatures = {
['crypto_onetimeauth'] = crypto_onetimeauth_sig,
['crypto_onetimeauth_verify'] = crypto_onetimeauth_verify_sig,
['crypto_onetimeauth_init'] = crypto_onetimeauth_init_sig,
['crypto_onetimeauth_update'] = crypto_onetimeauth_update_sig,
['crypto_onetimeauth_final'] = crypto_onetimeauth_final_sig,
['crypto_onetimeauth_keygen'] = crypto_onetimeauth_keygen_sig,
['crypto_onetimeauth_statebytes'] = crypto_onetimeauth_statebytes_sig,
['crypto_onetimeauth_poly1305'] = crypto_onetimeauth_sig,
['crypto_onetimeauth_poly1305_verify'] = crypto_onetimeauth_verify_sig,
['crypto_onetimeauth_poly1305_init'] = crypto_onetimeauth_init_sig,
['crypto_onetimeauth_poly1305_update'] = crypto_onetimeauth_update_sig,
['crypto_onetimeauth_poly1305_final'] = crypto_onetimeauth_final_sig,
['crypto_onetimeauth_poly1305_keygen'] = crypto_onetimeauth_keygen_sig,
['crypto_onetimeauth_poly1305_statebytes'] = crypto_onetimeauth_statebytes_sig,
}
return signatures
|
--- Dialog component class.
-- This is the base class for all in-game dialogs. If you want to
-- create an in-game dialog derive from this class, create an instance and
-- add it to @{SceneObject}. Example:
--
-- class 'MyDialog' (DialogComponent)
--
-- function MyDialog:__init()
-- DialogComponent.__init(self, self, vec2(scene.gameWidth / 2 - 15, 1), 30, 8);
-- self.i = 0;
-- end
--
-- function MyDialog:onRegister()
-- self:setTitlePlayer();
-- self:setMessage("Hi, Jake");
-- end
--
-- function MyDialog:onUnregister()
-- end
--
-- function MyDialog:okPressed()
-- if self.i == 0 then
-- self:setTitleAlly("Jake", "common1/portrait_jake.png");
-- self:setMessage("Hi, player");
-- elseif self.i == 1 then
-- self:setTitlePlayer();
-- self:setMessage("Bye");
-- else
-- self:endDialog();
-- end
-- self.i = self.i + 1;
-- end
--
-- local dialog = SceneObject();
-- dialog:addComponent(MyDialog());
-- scene:addObject(dialog);
--
-- @classmod DialogComponent
--- DialogComponent constructor.
-- @param self
-- @param self
-- @tparam vec2 pos Dialog center position
-- @number width Dialog width, in units
-- @number height Dialog height, in units
-- @function DialogComponent
function DialogComponent:__init(self, self, pos, width, height)
end
--- Change dialog title and avatar to player.
function DialogComponent:setTitlePlayer()
end
--- Change dialog title and avatar to an ally.
-- @string name Ally name
-- @string image Ally avatar path
function DialogComponent:setTitleAlly(name, image)
end
--- Change dialog title and avatar to an enemy.
-- @string name Enemy name
-- @string image Enemy avatar path
function DialogComponent:setTitleEnemy(name, image)
end
--- Set dialog message.
-- @string message
function DialogComponent:setMessage(message)
end
--- End the dialog.
-- Shorthand for:
-- self.parent:removeFromParent();
function DialogComponent:endDialog()
end
--- Called when user presses "ok" in the dialog.
function DialogComponent:okPressed()
end
--- Allow fast completions.
-- When true the user doesn't have to wait until each dialog message is
-- typed, he can press "ok" and skip ahead.
-- @tfield[opt=true] bool fastComplete
|
local floor = math.floor
local insert = table.insert
local Cursor = required("Cursor")
local DrawCommands = required("DrawCommands")
local LayoutManager = required("LayoutManager")
local Mouse = required("Mouse")
local Stats = required("Stats")
local Style = required("Style")
local Window = required("Window")
local Text = {}
function Text.begin(label, options)
local stat_handle = Stats.begin("Text", "Slab")
options = options == nil and {} or options
options.colour = options.colour == nil and Style.text_color or options.colour
options.pad = options.pad == nil and 0.0 or options.pad
options.is_selectable = options.is_selectable == nil and false or options.is_selectable
options.is_selectable_text_only = options.is_selectable_text_only == nil and false or options.is_selectable_text_only
options.is_selected = options.is_selected == nil and false or options.is_selected
options.add_item = options.add_item == nil and true or options.add_item
options.hover_color = options.hover_color == nil and Style.TextHoverBgColor or options.hover_color
options.url = options.url == nil and nil or options.url
if options.url ~= nil then
options.is_selectable_text_only = true
options.colour = Style.TextURLColor
end
local w = Text.get_width(label)
local h = Style.Font:getHeight()
local pad_x = options.pad
LayoutManager.add_control(w + pad_x, h)
local colour = options.colour
local result = false
local win_id = Window.get_item_id(label)
local x, y = Cursor.get_position()
local mouse_x, mouse_y = Window.get_mouse_position()
local is_obstructed = Window.is_obstructed_at_mouse()
if not is_obstructed and x <= mouse_x and mouse_x <= x + w and y <= mouse_y and mouse_y <= y + h then
Window.set_hot_item(win_id)
end
local win_x, win_y, win_w, win_h = Window.get_bounds()
local check_x = options.is_selectable_text_only and x or win_x
local check_w = options.is_selectable_text_only and w or win_w
local hovered =
not is_obstructed and check_x <= mouse_x and mouse_x <= check_x + check_w + pad_x and y <= mouse_y and
mouse_y <= y + h
if options.is_selectable or options.is_selected then
if hovered or options.is_selected then
DrawCommands.rectangle("fill", check_x, y, check_w + pad_x, h, options.hover_color)
end
if hovered then
if options.select_on_hover then
result = true
else
if Mouse.is_clicked(1) then
result = true
end
end
end
end
if hovered and options.url ~= nil then
Mouse.set_cursor("hand")
if Mouse.is_clicked(1) then
love.system.openURL(options.url)
end
end
DrawCommands.print(label, floor(x + pad_x * 0.5), floor(y), colour, Style.Font)
if options.url ~= nil then
DrawCommands.line(x + pad_x, y + h, x + w, y + h, 1.0, colour)
end
Cursor.set_item_bounds(x, y, w + pad_x, h)
Cursor.advance_y(h)
if options.add_item then
Window.add_item(x, y, w + pad_x, h, win_id)
end
Stats.finish(stat_handle)
return result
end
function Text.begin_formatted(label, options)
local stat_handle = Stats.begin("textf", "Slab")
local win_w, win_h = Window.get_borderless_size()
options = options == nil and {} or options
options.colour = options.colour == nil and Style.text_color or options.colour
options.w = options.w == nil and win_w or options.w
options.align = options.align == nil and "left" or options.align
if Window.is_auto_size() then
options.w = WIDTH
end
local width, wrapped = Style.Font:getWrap(label, options.w)
local h = #wrapped * Style.Font:getHeight()
LayoutManager.add_control(width, h)
local x, y = Cursor.get_position()
DrawCommands.printf(label, floor(x), floor(y), width, options.align, options.colour, Style.Font)
Cursor.set_item_bounds(floor(x), floor(y), width, h)
Cursor.advance_y(h)
Window.reset_content_size()
Window.add_item(floor(x), floor(y), width, h)
Stats.finish(stat_handle)
end
function Text.begin_object(object, options)
local stat_handle = Stats.begin("TextObject", "Slab")
local win_w, win_h = Window.get_borderless_size()
options = options == nil and {} or options
options.colour = options.colour == nil and Style.text_color or options.colour
local w, h = object:getDimensions()
LayoutManager.add_control(w, h)
local x, y = Cursor.get_position()
DrawCommands.Text(object, floor(x), floor(y), options.colour)
Cursor.set_item_bounds(floor(x), floor(y), w, h)
Cursor.advance_y(y)
Window.reset_content_size()
Window.add_item(floor(x), floor(y), w, h)
Stats.finish(stat_handle)
end
function Text.get_width(label)
return Style.Font:getWidth(label)
end
function Text.get_height()
return Style.Font:getHeight()
end
function Text.get_size(label)
return Style.Font:getWidth(label), Style.Font:getHeight()
end
function Text.get_size_wrap(label, width)
local w, lines = Style.Font:getWrap(label, width)
return w, #lines * Text.get_height()
end
function Text.get_lines(label, width)
local w, lines = Style.Font:getWrap(label, width)
local start = 0
for i, v in ipairs(lines) do
if #v == 0 then
lines[i] = "\n"
else
local offset = start + #v + 1
local ch = string.sub(label, offset, offset)
if ch == "\n" then
lines[i] = lines[i] .. "\n"
end
end
start = start + #lines[i]
end
if string.sub(label, #label, #label) == "\n" then
insert(lines, "")
end
if #lines == 0 then
insert(lines, "")
end
return lines
end
function Text.create_object()
return love.graphics.newText(Style.Font)
end
return Text
|
SCarHudHandler = {}
SCarHudHandler.Huds = {}
SCarHudHandler.HudsNameTrans = {}
SCarHudHandler.NrOfHuds = 0
SCarHudHandler.CurrentHud = nil
SCarHudHandler.isWideScreen = false
SCarHudHandler.vel = 0
SCarHudHandler.mph = 0
SCarHudHandler.kmh = 0
SCarHudHandler.showGear = ""
SCarHudHandler.CurGear = 0
SCarHudHandler.rev = 40
SCarHudHandler.revScale = 40
SCarHudHandler.isRevving = false
SCarHudHandler.curRev = 40
SCarHudHandler.forwardMaxSpeed = 300
SCarHudHandler.reverseMaxSpeed = 300
SCarHudHandler.fuel = 1
SCarHudHandler.neutral = false
SCarHudHandler.isOn = false
SCarHudHandler.isScarSeat = 0
SCarHudHandler.SCar = nil
SCarHudHandler.FuncRes = false
SCarHudHandler.ply = nil
SCarHudHandler.veh = nil
SCarHudHandler.LastSelection = 1
SCarHudHandler.LastSelectionName = ""
SCarHudHandler.retry = true
SCarHudHandler.UseTurbo = false
SCarHudHandler.TurboPercent = 0
SCarHudHandler.LastTurboUse = false
SCarHudHandler.ContineousTurbo = false
SCarHudHandler.TDur = 0
SCarHudHandler.TurboDelay = 0
SCarHudHandler.TurboDuration = 0
SCarHudHandler.StartTurboTime = 0
SCarHudHandler.speed = 0
SCarHudHandler.xSize = 0
SCarHudHandler.ySize = 0
SCarHudHandler.xPos = 0
SCarHudHandler.yPos = 0
SCarHudHandler.CamData = {}
SCarHudHandler.maxs = Vector(0,0,0)
SCarHudHandler.mins = Vector(0,0,0)
SCarHudHandler.length = 0
SCarHudHandler.height = 0
SCarHudHandler.origin = Vector(0,0,0)
SCarHudHandler.ang = Angle(0,0,0)
function SCarHudHandler:Init()
local huds = {}
huds = file.Find( "scarhud/*.lua" , "LUA")
for _, plugin in ipairs( huds ) do
include( "scarhud/" .. plugin )
end
self:ReadFromFile()
end
function SCarHudHandler:SaveToFile()
file.Write( "scarhud.txt", self.LastSelectionName.."\n")
end
function SCarHudHandler:Refresh()
self.NrOfHuds = 0
self:Init()
end
function SCarHudHandler:ReadFromFile()
local canDo = false
canDo = file.Exists( "scarhud.txt", "DATA" )
if canDo then
local cont = file.Read( "scarhud.txt" )
cont = file.Read( "scarhud.txt", "DATA" )
if cont == nil then
SCarsReportError("SCar hud file exists but it has no real content? Writing default SCar hud file!", 150)
file.Write( "scarhud.txt", "Default" )
cont = file.Read( "scarhud.txt", "DATA" )
if cont == nil then
SCarsReportError("Writing the default SCar hud file and reading it didn't work. Not allowed to read/write files?", 255)
return
end
end
local data = string.Explode(string.char(10), cont)
if !self.HudsNameTrans[data[1]] && self.retry == true then
self.retry = false
SCarsReportError("AAReading SCar hud file failed! Trying to solve..")
file.Write( "scarhud.txt", "Default" )
self:ReadFromFile()
elseif !self:SetActiveHudByName( data[1] ) then
SCarHudHandler.LastSelection = 1
SCarHudHandler.LastSelectionName = ""
self.CurrentHud = self.Huds[1]
if self.CurrentHud.Init then
self.CurrentHud:Init()
end
end
else
if self.retry == true then
self.retry = false
file.Write( "scarhud.txt", "Default" )
self:ReadFromFile()
else
SCarsReportError("Could not read SCar hud settings file!", 250)
end
end
end
function SCarHudHandler:SetActiveHudByName( name )
if self.HudsNameTrans[name] then
SCarHudHandler.LastSelectionName = name
SCarHudHandler.LastSelection = self.HudsNameTrans[SCarHudHandler.LastSelectionName]
self.CurrentHud = self.Huds[SCarHudHandler.LastSelection]
if self.CurrentHud.Init then
self.CurrentHud:Init()
end
return true
end
return false
end
function SCarHudHandler:RefreshMenu( Panel )
local CPanel = controlpanel.Get( "SCarHud" )
if ( !CPanel ) then return end
CPanel:ClearControls()
SCarHudHandler.BuildMenu( CPanel )
end
function SCarHudHandler.BuildMenu( Panel )
local self = SCarHudHandler
local Text = vgui.Create("DLabel")
Text:SetPos(5,0)
Text:SetFont("Default")
Text:SetText("Selected: "..self.LastSelectionName)
Text:SetColor(Color(255,255,255,255))
Panel:AddItem(Text)
local hudList = vgui.Create( "DListView" )
hudList:SetSize( 100, 185 )
hudList:SetMultiSelect(false)
hudList:AddColumn("Huds") -- Add column
hudList.OnClickLine = function(parent, line, isselected)
local val = line:GetValue(1)
if SCarHudHandler.LastSelectionName != val then
SCarHudHandler.LastSelectionName = val
SCarViewManager:SaveToFile()
SCarViewManager:RefreshMenu( Panel )
if SCarViewManager.Cams[SCarViewManager.CurCam].Init then
SCarViewManager.Cams[SCarViewManager.CurCam]:Init()
end
self:SetActiveHudByName(val)
SCarHudHandler:SaveToFile()
SCarHudHandler:RefreshMenu( Panel )
end
end
for i = 1, self.NrOfHuds do
hudList:AddLine( self.Huds[i].Name )
end
Panel:AddItem(hudList)
if self.Huds[SCarHudHandler.LastSelection].MenuElements then
self.Huds[SCarHudHandler.LastSelection]:MenuElements( Panel )
end
end
function SCarHudHandler:RegisterHUD(hud)
self.NrOfHuds = self.NrOfHuds + 1
if !hud.Name then
hud.Name = "No Name"
end
self.Huds[self.NrOfHuds] = hud
self.HudsNameTrans[hud.Name] = self.NrOfHuds
end
function SCarHudHandler:GetHudByName( name )
for i = 1, self.NrOfHuds do
if self.Huds[i].Name == name then
return self.Huds[i]
end
end
end
function SCarHudHandler:SelectHud( name )
self:GetHudByName( name )
end
function SCarHudHandler:GetTableOfTitles( )
local names = {}
for i = 1, self.NrOfHuds do
names[i] = self.Huds[i].Name
end
return nrOfNames, names
end
function SCarHudHandler:UpdateHUD()
local self = SCarHudHandler
if !LocalPlayer() or !LocalPlayer():Alive() then return end
if LocalPlayer():GetActiveWeapon() == "Camera" then return end
if GetViewEntity():GetClass() == "gmod_cameraprop" then return end
self.ply = LocalPlayer()
self.veh = self.ply:GetVehicle()
self.isScarSeat = 0
self.SCar = nil
self.FuncRes = false
if IsValid(self.veh) then
self.isScarSeat = self.veh:GetNetworkedInt( "SCarSeat" )
self.SCar = self.veh:GetNetworkedEntity("SCarEnt")
end
if self.SCar and self.SCar.HudPaintAdd then
self.FuncRes = self.SCar:HudPaintAdd(self.isScarSeat)
end
if !self.FuncRes and self.isScarSeat == 1 and IsValid(self.SCar) then
--Checking if the user have a widescreen res or not.
self.isWideScreen = true
if (ScrW() / ScrH()) <= (4 / 3) then
self.isWideScreen = false
end
self.vel = self.veh:GetVelocity():Length()
self.mph = self.vel / 23.33
self.kmh = self.vel / 14.49
self.showGear = " "
if self.CurGear == -1 then
self.showGear = "R"
elseif self.CurGear == -2 then
self.showGear = "B"
elseif self.CurGear == -3 then
self.showGear = "H"
else
self.showGear = tostring(self.CurGear + 1)
end
--Calculating Rev
self.rev = ((self.vel % self.revScale) / self.revScale)
if self.isRevving == true then
self.curRev = math.Approach( self.curRev, 1 , 0.58333 * FrameTime() )
elseif self.neutral == true or self.isOn == false then --Neutral (no throttle)
self.curRev = math.Approach( self.curRev, 0 , 0.3 * FrameTime() )
elseif self.CurGear >= 0 then
self.curRev = math.Approach( self.curRev, self.rev , ((self.rev - self.curRev) * 0.1) )
if self.vel > self.forwardMaxSpeed then
self.curRev = 1
end
elseif self.CurGear == -1 then
self.rev = ( self.vel / self.reverseMaxSpeed )
self.curRev = math.Approach( self.curRev, self.rev , ((self.rev - self.curRev) * 0.1) )
if self.vel > self.reverseMaxSpeed then
self.rev = 1
end
else
self.curRev = math.Approach( self.curRev, 0 , 0.3 * FrameTime() )
end
self.curRev = math.Clamp( self.curRev, 0, 1)
--------Turbo
if self.ContineousTurbo == true then
if self.UsingTurbo == true then
self.TurboPercent = (self.TDur - CurTime()) / self.TurboDuration
else
self.TurboPercent = 1-(self.TDur - CurTime()) / self.TurboDelay
end
else
if self.UsingTurbo == true then
self.TurboPercent = (1 - self.TurboDelay) * ((self.StartTurboTime - CurTime()) / self.TurboDuration)
else
self.TurboPercent = self.TurboDelay + (1-((self.StartTurboTime - CurTime()) / self.TurboDuration)) * (1-self.TurboDelay)
end
end
self.TurboPercent = math.Clamp(self.TurboPercent,0,1)
if SCarClientData["scar_kmormiles"] == true then
self.speed = self.kmh
else
self.speed = self.mph
end
self.CurrentHud:DrawHud(self.vel, self.curRev, self.showGear, self.fuel, self.TurboPercent, self.speed, self.SCar, self.ply, self.isWideScreen, SCarClientData["scar_kmormiles"])
if SCarClientData["scar_rearviewmirror_use"] then
self.xSize = ScrW() * (SCarClientData["scar_rearviewmirror_sizex"] * 0.01)
self.ySize = ScrH() * (SCarClientData["scar_rearviewmirror_sizey"] * 0.01)
self.xPos = (ScrW() - self.xSize) * (SCarClientData["scar_rearviewmirror_posx"] * 0.01)
self.yPos = (ScrH() - self.ySize) * (SCarClientData["scar_rearviewmirror_posy"] * 0.01)
draw.RoundedBox( 0, self.xPos, self.yPos, self.xSize, self.ySize , Color(0,0,0,255) )
self.xSize = self.xSize - 4
self.ySize = self.ySize - 4
self.xPos = self.xPos + 2
self.yPos = self.yPos + 2
self.maxs = self.SCar:OBBMaxs()
self.mins = self.SCar:OBBMins()
self.length = (self.maxs.x - self.mins.x) * -0.47
self.height = (self.maxs.z - self.mins.z) * 0.2
self.origin = self.SCar:LocalToWorld(self.SCar:OBBCenter()) + self.SCar:GetForward() * self.length + self.SCar:GetUp() * self.height
self.ang = self.SCar:GetAngles()
self.ang:RotateAroundAxis( self.ang:Up(), 180)
self.SCar:SetDoDraw( false )
self.CamData.angles = self.ang
self.CamData.origin = self.origin
self.CamData.x = self.xPos
self.CamData.y = self.yPos
self.CamData.w = self.xSize
self.CamData.h = self.ySize
render.RenderView( self.CamData )
self.SCar:SetDoDraw( true )
end
end
end
hook.Add( "HUDPaint", "DrawSCarHUD", SCarHudHandler.UpdateHUD )
function SCarHudHandler.Hide( Element )
if SCarHudHandler.isScarSeat >= 1 then
if (Element=="CHudHealth") or (Element=="CHudBattery") or (Element=="CHudAmmo") or (Element=="CHudSecondaryAmmo")then
return false
end
end
end
hook.Add("HUDShouldDraw", "HideCrapScarHud", SCarHudHandler.Hide)
--UserMessages
local function GetUseNosFromServer( data )
SCarHudHandler.UsingTurbo = data:ReadBool()
if SCarHudHandler.UsingTurbo == true then
SCarHudHandler.TDur = CurTime() + SCarHudHandler.TurboDuration
elseif SCarHudHandler.UsingTurbo == false then
SCarHudHandler.TDur = CurTime() + SCarHudHandler.TurboDelay
end
end
usermessage.Hook( "SCarGetUseNosFromServer", GetUseNosFromServer )
local function SCarGetUseContNosFromServer( data )
SCarHudHandler.ContineousTurbo = data:ReadBool()
end
usermessage.Hook( "SCarGetUseContNosFromServer", SCarGetUseContNosFromServer )
local function GetNosTimeFromServer( data )
SCarHudHandler.TurboDuration = data:ReadFloat()
SCarHudHandler.StartTurboTime = SCarHudHandler.TurboDuration + CurTime()
end
usermessage.Hook( "GetNosTimeFromServer", GetNosTimeFromServer )
local function GetNosRegenTimeFromServer( data )
SCarHudHandler.TurboDelay = data:ReadFloat()
end
usermessage.Hook( "GetNosRegenTimeFromServer", GetNosRegenTimeFromServer )
local function GetGearFromServer( data )
SCarHudHandler.CurGear = data:ReadShort()
end
usermessage.Hook( "SCarGetGearFromServer", GetGearFromServer )
local function GetEngineRevFromServer( data )
SCarHudHandler.revScale = data:ReadLong()
end
usermessage.Hook( "SCarGetEngineRevFromServer", GetEngineRevFromServer )
local function GetEngineRevReverseFromServer( data )
SCarHudHandler.reverseMaxSpeed = data:ReadLong()
end
usermessage.Hook( "SCarGetEngineRevReverseFromServer", GetEngineRevReverseFromServer )
local function GetEngineRevForwardFromServer( data )
SCarHudHandler.forwardMaxSpeed = data:ReadLong()
end
usermessage.Hook( "SCarGetEngineRevForwardFromServer", GetEngineRevForwardFromServer )
local function GetFuelFromServer( data )
SCarHudHandler.fuel = data:ReadLong() / 20000
end
usermessage.Hook( "SCarGetFuelFromServer", GetFuelFromServer )
local function GetNeutralFromServer( data )
SCarHudHandler.neutral = data:ReadBool()
end
usermessage.Hook( "SCarGetNeutralFromServer", GetNeutralFromServer )
local function GetRevvingFromServer( data )
SCarHudHandler.isRevving = data:ReadBool()
end
usermessage.Hook( "SCarGetRevvingFromServer", GetRevvingFromServer )
local function GetIsOnFromServer( data )
SCarHudHandler.isOn = data:ReadBool()
end
usermessage.Hook( "SCarGetIsOnFromServer", GetIsOnFromServer )
|
luafft = require "luafft"
local signal = {}
local size = next_possible_size(2*2048+1)
local frequency = 1024
local length = size / frequency
--size = next_size(size)
--Populates a list with random real numbers in complex format
function populate(list)
for i=1,size do
list[i] = complex.new(math.sin(2* i/frequency * 2*math.pi) + math.sin(10* i/frequency * 2*math.pi), 0)--complex.new(math.random(), 0)
end
end
--displays the fourier spectrum
function display(spectrum)
for i=1,#spectrum/2 do print(string.format("%.1f Hz\t%1.1f",(i-1)/length, (spectrum[i]:abs()))) end
end
--displays a single list with whatever it contains
function print_list(list)
for i,v in ipairs(list) do print(i,v) end
end
--devide a list with a certain constant factor
function devide(list, factor)
for i,v in ipairs(list) do list[i] = list[i] / factor end
end
--create a signal with two sine waves
populate(signal)
--carry out fast fourier transformation and store result in "spec"
local spec = fft(signal, false)
--now carry out inverse fast fourier transformation and store result in "reconstructed"
reconstructed = fft(spec, true)
--After retransformation, we need to devide by the data size
devide(reconstructed, size)
devide(spec, size/2)
--Displays the fourier spectrum of the audio signal
display(spec)
|
AddCSLuaFile()
ENT.WeaponTypes.Javelin = {
Name = "mechassault.weapon.javelin",
Type = "Missile",
Function = "FireJavelin",
Cooldown = 2.5,
FireRate = 0.1,
Class = {
"ma2_proj_javelin_lvl1",
"ma2_proj_javelin_lvl2",
"ma2_proj_javelin_lvl3"
},
MaxLevel = 3
}
function ENT:FireJavelin(tbl, level, attachments)
if SERVER then
local index = self:GetCurrentWeapon()
local aborted = false
local target = self:GetTargetLock() -- Cache early so we re-use the same target in the timer section
for k, v in ipairs(attachments) do
timer.Simple((k - 1) * tbl.FireRate, function()
if aborted then
return
end
local attachment = self:GetAttachment(v)
local ent = ents.Create(tbl.Class[level])
ent:SetPos(attachment.Pos)
ent:SetAngles(attachment.Ang)
ent:SetOwner(self)
ent.Player = self:GetPlayer()
ent:Spawn()
ent:Activate()
if IsValid(target) then
ent:SetTracked(target)
else
ent:SetTargetPos(self:GetAimTrace().HitPos)
end
if not self:TakeAmmo(index) then
aborted = true
end
end)
end
end
self:SetNextAttack(CurTime() + (#attachments * tbl.FireRate) + tbl.Cooldown)
end
|
---
--- plugin configuration information dao
--- Copyright (c) GoGo Easy Team & Jacobs Lei
--- Author: Jacobs Lei
--- Date: 2018/4/6
--- Time: 下午4:05
local tonumber = tonumber
local tostring = tostring
local _M = {}
---
--- load plugin information from storage by plugin name
-- @param plugin_name
-- @param store
--
function _M.load_plugin_by_plugin_name(plugin_name, store)
local flag,plugins, err = store:query({
sql = "select * from `c_plugin` where `plugin_name` = ?",
params = {plugin_name}
})
if err then
ngx.log(ngx.ERR, "Load `enable` of plugin[" .. plugin_name .. "], error: ", err)
return false, nil
end
if plugins and type(plugins) == "table" and #plugins > 0 then
-- mysql query 默认返回的是一个array, 此处根据plugin_name查询只返回一个plugin
-- 如果直接返回 plugin 其实是array,后续使用会误解,所以此处直接返回 plugin[1]
return true, plugins[1]
end
return false,nil
end
--- update the plugin enable or not by plugin's name
-- @param store
-- @param plugin_name
-- @param enable
--
function _M.update_plugin_enable(store,plugin_name, enable)
ngx.log(ngx.ERR, "update the plugin[" .. plugin_name .."]'s enable[".. enable .."]")
if not plugin_name or type(plugin_name) ~= "string" then
ngx.log(ngx.ERR, "update the plugin[" .. plugin_name .."]'s enable[".. enable .."] false")
return false
end
if not enable or not tonumber (enable) then
ngx.log(ngx.ERR, "update the plugin[" .. plugin_name .."]'s enable[".. enable .."] false")
return false
end
local result = store:update({
sql = "update c_plugin set `enable` = ? where `plugin_name`=? ",
params = {enable,plugin_name }
})
ngx.log(ngx.ERR, "update the plugin[" .. plugin_name .."]'s enable[".. enable .."]'s result:" .. tostring(result))
return result
end
---
--- 获取所有非内建 plugin
-- @param store
--
function _M.load_plugin(store)
local flag,plugins, err = store:query({
sql = "select * from c_plugin where is_built_in = 0"
})
if err then
ngx.log(ngx.ERR, "load_plugin error: ", err)
return false, nil
end
if plugins and type(plugins) == "table" and #plugins > 0 then
return true, plugins
end
return true,nil
end
return _M
|
-- NOTE: the serialization here is ONLY intended for communication between threads
-- in a running process, NOT for saving to disk...!!
local ffi = require 'ffi'
local comms = {}
local tostring_types = {number=true, boolean=true, ['nil']=true}
local ptr_meta = {
__serialize = function(self, buf)
local ptr_buf = ffi.new('void*[1]', self.ptr)
local stringed = ffi.string(ptr_buf, ffi.sizeof 'void*')
if self.lib then
buf[#buf+1] = string.format('ptr(%q, %q, %q)', stringed, self.type, self.lib)
else
buf[#buf+1] = string.format('ptr(%q, %q)', stringed, self.type)
end
end;
}
function comms.ptr(ptr, type, lib)
return setmetatable({ptr=ptr, type=type, lib=lib}, ptr_meta)
end
local function append_value(buf, value, tables)
local vtype = type(value)
if vtype == 'string' then
buf[#buf+1] = string.format('%q', value)
return
end
if tostring_types[vtype]
or (vtype == 'cdata' and (ffi.istype('int64_t', value) or ffi.istype('uint64_t', value))) then
buf[#buf+1] = tostring(value)
return
end
local m = getmetatable(value)
if type(m) == 'table' and m.__serialize then
m.__serialize(value, buf)
return
end
if vtype == 'table' then
if tables[value] then
error('cannot serialize table with cycles')
end
tables[value] = true
buf[#buf+1] = '{'
for k, v in pairs(value) do
buf[#buf+1] = '['
append_value(buf, k, tables)
buf[#buf+1] = ']='
append_value(buf, v, tables)
buf[#buf+1] = ';'
end
buf[#buf+1] = '}'
tables[value] = nil
return
end
error('unable to serialize:' .. tostring(value))
end
function comms.serialize(...)
local buf = {}
for i = 1, select('#', ...) do
if i > 1 then
buf[#buf+1] = ', '
end
append_value(buf, select(i, ...), {})
end
return table.concat(buf)
end
local function ptr(stringed, type, lib)
if lib then
require(lib)
end
return ffi.cast(type, ffi.cast('void**', stringed)[0])
end
function comms.deserialize(serialized)
return assert(loadstring('local ptr=...;return ' .. serialized))(ptr)
end
return comms
|
loadstring(game:HttpGet("https://raw.githubusercontent.com/Storm99999/Plasmaploit/main/Protected.lua"))()
|
require("gameData/dataInterfaceBase");
require("hall/matchHall/gameMatchHall/data/matchHallDataInterface");
require("hall/matchHall/gameMatchHall/data/matchRecordDataInterface");
--[[
比赛信息中间层
--]]
MatchIsolater = class(DataInterfaceBase);
MatchIsolater.Delegate = {
-- 比赛列表
onGetMatchList = "onGetMatchList";
onResponseMatchDetail = "onResponseMatchDetail";
onResponseMatchBasicInfo = "onResponseMatchBasicInfo";
-- 报名
onSignupMatchSuccess = "onSignupMatchSuccess";
onUpdateMatchState = "onUpdateMatchState";
onSignupMatchFailed = "onSignupMatchFailed";
onTimeToEnterMatch = "onTimeToEnterMatch";
-- 退赛
onExitMatchSuccess = "onExitMatchSuccess";
onExitMatchFailed = "onExitMatchFailed";
-- 邀请好友
onGetFriendInviteList = "onGetFriendInviteList";
-- 等待界面
onRefreshMatchWatingTime = "onRefreshMatchWatingTime";
onMatchReconnected = "onMatchReconnected";
};
MatchIsolater.getInstance = function ( )
if not MatchIsolater.s_instance then
MatchIsolater.s_instance = new (MatchIsolater);
end
return MatchIsolater.s_instance;
end
MatchIsolater.ctor = function ( self )
MatchHallDataInterface.getInstance():setObserver(self);
end
MatchIsolater.dtor = function ( self )
MatchHallDataInterface.getInstance():clearObserver(self);
end
--[[
@brief 设置当前比赛详情
@param matchData (table) 比赛详情
--]]
MatchIsolater.setMatchData = function ( self, matchData )
MatchHallDataInterface.getInstance():setMatchData(matchData or {});
end
--[[
@brief 获取当前比赛详情
@return (table) 比赛详情
--]]
MatchIsolater.getMatchData = function ( self )
return MatchHallDataInterface.getInstance():getMatchData();
end
--[[
@brief 设置当前比赛类型
@param matchType (number) 比赛类型
GameConstant.NORMAL_IMMEDIATE_MATCH = 0 快速赛
GameConstant.FIXED_TIME_MATCH = 3 定时赛
--]]
MatchIsolater.setCurMatchType = function ( self, matchType )
MatchHallDataInterface.getInstance():setCurMatchType(matchType);
end
--[[
@brief 获取当前比赛类型
@return (number) 比赛类型
GameConstant.NORMAL_IMMEDIATE_MATCH = 0 快速赛
GameConstant.FIXED_TIME_MATCH = 3 定时赛
--]]
MatchIsolater.getCurMatchType = function ( self )
return MatchHallDataInterface.getInstance():getCurMatchType();
end
--[[
@brief 设置当前比赛状态
@param status (number) 比赛状态
1 报名成功等待界面
2 轮结束等待界面
3 比赛游戏结束
4 游戏中
5 无状态
--]]
MatchIsolater.setMatchStatus = function ( self, status )
MatchHallDataInterface.getInstance():setMatchStatus(status);
end
--[[
@brief 获取当前比赛状态
@return (number) 比赛状态
1 报名成功等待界面
2 轮结束等待界面
3 比赛游戏结束
4 游戏中
5 无状态
--]]
MatchIsolater.getMatchStatus = function ( self )
return MatchHallDataInterface.getInstance():getMatchStatus();
end
--[[
@brief 当前比赛是否支持举报
@return boolean
--]]
MatchIsolater.getCurMatchIsSupportReport = function(self)
return MatchHallDataInterface.getInstance():getCurMatchIsSupportReport();
end
--[[
@brief 设置报名比赛id
@param matchId (number) 比赛id
@note 设置该值,进入比赛列表时,会自动报名该比赛。用完请赋值nil
--]]
MatchIsolater.setSignMatchId = function ( self, matchId )
MatchHallDataInterface.getInstance():setSignMatchId(matchId);
end
--[[
@brief 获取报名比赛id
@return (number) 比赛id
--]]
MatchIsolater.getSignMatchId = function ( self )
return MatchHallDataInterface.getInstance():getSignMatchId();
end
--[[
@brief 设置比赛跳转信息
@param jumpInfo (table) 比赛跳转信息
--]]
MatchIsolater.setMatchJumpInfo = function(self, jumpInfo)
MatchHallDataInterface.getInstance():setMatchJumpInfo(jumpInfo)
end
--[[
@brief 获取比赛跳转信息
@return (table) 比赛跳转信息
--]]
MatchIsolater.getMatchJumpInfo = function(self)
return MatchHallDataInterface.getInstance():getMatchJumpInfo()
end
--[[
@brief 设置是否从房间接收广播进入比赛
@param flag (boolean) true为是,false为否
--]]
MatchIsolater.setIsRoomToMatch = function(self, flag)
MatchHallDataInterface.getInstance():setIsRoomToMatch(flag);
end
--[[
@brief 获取是否从房间接收广播进入比赛
@return (boolean) 是否从房间接收广播进入比赛, true为是,false为否
--]]
MatchIsolater.getIsRoomToMatch = function(self)
return MatchHallDataInterface.getInstance():getIsRoomToMatch();
end
--[[
@brief 设置比赛列表过滤的游戏id(用作房间列表往比赛列表跳转)
@param gameId (number) 游戏id
--]]
MatchIsolater.setFilterGameId = function (self, gameId)
MatchHallDataInterface.getInstance():setFilterGameId(gameId);
end
--[[
@brief 获取比赛列表过滤的游戏id
@return (number) 游戏id
--]]
MatchIsolater.getFilterGameId = function (self)
return MatchHallDataInterface.getInstance():getFilterGameId();
end
--[[
@brief 设置比赛分享模板,弃用
@param template (table) 分享模板
--]]
MatchIsolater.setShareTemplate = function ( self, template )
-- do nothing
end
--[[
@brief 获取比赛分享模板
@return (table) 分享模板 主要用于比赛分享 + 子游戏分享
t = {
[key] = {
share_icon 分享Icon
share_url 分享url
desc 分享内容
}
}
key --> eg: match_win、match_failed、game_win、game_failed、free_failed 等等
--]]
MatchIsolater.getShareTemplate = function ( self )
return MatchHallDataInterface.getInstance():getShareTemplate();
end
--[[
@brief 设置下一场比赛的类型,比赛结束报名下一场的时候用
@param type (number) 比赛类型
GameConstant.NORMAL_IMMEDIATE_MATCH = 0 快速赛
GameConstant.FIXED_TIME_MATCH = 3 定时赛
--]]
MatchIsolater.setNextMatchType = function ( self, type)
MatchHallDataInterface.getInstance():setNextMatchType(type);
end
--[[
@brief 获取下一场比赛类型
@return (number) 比赛类型
GameConstant.NORMAL_IMMEDIATE_MATCH = 0 快速赛
GameConstant.FIXED_TIME_MATCH = 3 定时赛
--]]
MatchIsolater.getNextMatchType = function ( self )
return MatchHallDataInterface.getInstance():getNextMatchType();
end
--[[
@brief 设置比赛缓存的玩家分数信息
@param info (table) 玩家分数信息
info = {
[1] = {
mid 玩家mid
score 玩家分数
},
...
}
--]]
MatchIsolater.setMatchScoreInfo = function ( self, info )
MatchHallDataInterface.getInstance():setMatchScoreInfo(info);
end
--[[
@brief 获取比赛缓存的玩家分数信息
@return (table) 玩家分数信息
t = {
[1] = {
mid 玩家mid
score 玩家分数
},
...
}
--]]
MatchIsolater.getMatchScoreInfo = function (self)
return MatchHallDataInterface.getInstance():getMatchScoreInfo();
end
--[[
@brief 设置比赛阶段信息
@param info (table) 比赛阶段信息
info = {
stageInfo = {
[1] = {
name 阶段名称
number 晋级人数
rounds = { 阶段包含轮数
1,2,3,...
}
},
...
}
daliInfo = {
TillWeedoutNum 截止人数
promotionNum 晋级人数
}
}
--]]
MatchIsolater.setMatchStageInfo = function ( self, info)
MatchHallDataInterface.getInstance():setMatchStageInfo(info);
end
--[[
@brief 获取比赛阶段信息
@return (table) 比赛阶段信息
info = {
stageInfo = {
[1] = {
name 阶段名称
number 晋级人数
rounds = { 阶段包含轮数
1,2,3,...
}
},
...
}
daliInfo = {
TillWeedoutNum 截止人数
promotionNum 晋级人数
}
}
--]]
MatchIsolater.getMatchStageInfo = function ( self )
return MatchHallDataInterface.getInstance():getMatchStageInfo();
end
--[[
@note 兼容旧接口,不要再调用此接口
--]]
MatchIsolater.getClosestDSMatch = function ( self, matchType, gameId )
return self:getClosestMatchCanSiginup({type = matchType, gameid = gameId});
end
--[[
@brief 获取最近一场定时赛,报名下一场用
@param data (table) 比赛数据
--]]
MatchIsolater.getClosestMatchCanSiginup = function ( self, data )
return MatchHallDataInterface.getInstance():getClosestMatchCanSiginup(data);
end
--[[
@brief 根据比赛ID判断是否为邀请赛
@param matchId (number) 比赛ID
--]]
MatchIsolater.checkInvitationalById = function ( self, matchId)
return MatchHallDataInterface.getInstance():checkInvitationalById(matchId);
end
--[[
@brief 设置比赛是否刚开始
@param flag (boolean) true为是,false为否
--]]
MatchIsolater.setIsJustStart = function ( self, flag )
MatchHallDataInterface.getInstance():setIsJustStart(flag);
end
--[[
@brief 获取比赛是否刚开始
@return (boolean) true为是,false为否
--]]
MatchIsolater.getIsJustStart = function ( self )
return MatchHallDataInterface.getInstance():getIsJustStart();
end
-- ==========================比赛大厅 begin====================================
--[[
@brief 报名比赛
@param matchInfo (table) 比赛数据,即比赛列表数据项
--]]
MatchIsolater.signupMatch = function ( self, matchInfo )
MatchHallDataInterface.getInstance():signupMatch(matchInfo);
end
--[[
@brief 报名成功回调,直接进入等待界面
@param info (table) 报名成功返回数据
info = {
num 当前报名人数
totalNum 最低报名人数
turnMoney 银币变化
totalMoney 总银币
totalDiamond 总钻石
userInfo 用户当前信息(json格式,银币钻石水晶数量更新尽量用此字段,方便以后扩展)
}
--]]
MatchIsolater.onSignupMatchSuccess = function ( self, info )
self:notify(MatchIsolater.Delegate.onSignupMatchSuccess, info);
end
--[[
@brief 报名成功,未进入等待界面
@param info (table) 报名成功返回数据
info = {
type 物品类型
count 物品数量
extenalMoney 玩家银币(组合报名相关字段,已无用)
userInfo 用户当前信息(json格式,银币钻石水晶数量更新尽量用此字段,方便以后扩展)
}
--]]
MatchIsolater.onUpdateMatchState = function ( self, info )
self:notify(MatchIsolater.Delegate.onUpdateMatchState, info);
end
--[[
@brief 报名失败
@param info (table) 报名失败返回数据
info = {
code 错误码
matchId 比赛id
gameId 游戏id
}
错误码
MatchHallDataInterface.FATAL_ERROR = 0 服务器内部异常
MatchHallDataInterface.MATCH_NOT_EXSITS = 1 比赛信息错误
MatchHallDataInterface.NOT_ENOUGH_ENTRY_FEE = 2 银币小于报名费用
MatchHallDataInterface.MATH_IS_PLAYING = 3 比赛已经开始且不属于重连
MatchHallDataInterface.ALREADY_SIGN_UP = 4 玩家已經報名
MatchHallDataInterface.NOT_REACH_TIME = 5 没到时间
MatchHallDataInterface.SIGN_UP_ERROR = 6 收到该错误码时,啥都不用处理
MatchHallDataInterface.MATCH_OVER_MAX_USER = 7 超过比赛报名最大人数
--]]
MatchIsolater.onSignupMatchFailed = function ( self, info )
self:notify(MatchIsolater.Delegate.onSignupMatchFailed, info);
end
--[[
@brief 够钟比赛,允许进入等待界面
@param info (table) 返回数据
info = {
matchId 比赛id
matchName 比赛名称
min 提前几分钟入场
startTime 命令接收时间
}
--]]
MatchIsolater.onTimeToEnterMatch = function (self, data)
self:notify(MatchIsolater.Delegate.onTimeToEnterMatch, data);
end
--[[
@brief 请求退赛
@param data (table) 比赛数据,即比赛列表数据项
--]]
MatchIsolater.requestExitMatch = function ( self, data )
MatchHallDataInterface.getInstance():requestExitMatch(data);
end
--[[
@brief 请求退赛成功
@param matchInfo (table) 比赛数据,即比赛列表数据项
@param packetInfo (table) 返回数据
info = {
returnMoney 退还银币
totalMoney 总银币
totalDiamond 总钻石
hasProp 是否有道具
type 道具类型,hasProp为true时存在
count 道具数量,hasProp为true时存在
userInfo 用户当前信息(json格式,银币钻石水晶数量更新尽量用此字段,方便以后扩展)
}
@param flag (boolean) 无用,必为true
--]]
MatchIsolater.onExitMatchSuccess = function ( self, matchInfo, packetInfo, flag )
self:notify(MatchIsolater.Delegate.onExitMatchSuccess, matchInfo, packetInfo, flag);
end
--[[
@brief 请求退赛失败
@param info (table) 返回数据
info = {
errorType 错误码
matchId 比赛id,与客户端无关
gameId 游戏id
realMatchId 比赛id
}
错误码
0 游戏已经开始,而且该玩家处理比赛中,退出失败
1 该玩家未报名或者已经被淘汰,退出成功(不退报名费)
2 其他错误原因,退出成功(不退还报名费)
3 用户不存在
4 比赛即将开始,不允许退赛
--]]
MatchIsolater.onExitMatchFailed = function ( self,info)
self:notify(MatchIsolater.Delegate.onExitMatchFailed,info);
end
--[[
@brief 比赛重连
@param info (table) 返回数据
info = {
matchId 比赛id,与客户端无关
gameId 游戏id
readMatchId 比赛id
gameType 游戏类型
isPlayIng 是否在玩牌中
}
--]]
MatchIsolater.onMatchReconnected = function(self,info)
self:notify(MatchIsolater.Delegate.onMatchReconnected,info);
end
--[[
@brief 请求比赛列表
@return (table) 比赛列表
t = {
[1] = {
requestnum 最低开赛人数
type 比赛类型(0:快速赛,3:定时赛)
mname 比赛名称
id 比赛id
gameid 游戏id
allowwaittime 允许提前进入时间
micon 比赛icon
iconweight 比赛icon权重,从小到大优先级
applynum 报名人数
allapplynum 报名总人数 带上了机器人人数
matchpartitions 分场
fee = { 报名费,为空则免费报名
[1] = { 列表项
type 类型
num 数量
desc 描述
index 序号
},
...
}
status 比赛状态
champion 冠军奖励信息
stime 开始时间
etime 结束时间
isfhmatch 是否复活赛
configid 比赛配置ID
looptype 比赛循环周期 1:单场 2:多场
loopinterval 比赛循环间隔(单位为分钟)
loopendtime 比赛循环截至时间(一天多场)
firstbegintime 首次开赛时间,用于循环赛显示
rewardUrl 比赛奖励图
rewardDescribe 比赛奖励描述
matchtags = { 比赛标签(用于筛选)
1,2,3,... 标签id
}
invitetype 邀请赛类型 0:邀请赛 1:集团赛
matchentrycode 比赛验证码
matchentryinfo 比赛验证码获取方式
advicon 比赛运营icon
adIcon 广告图
listSort 列表排序ID,从1开始,0或空最后
threshold 报名门槛 0为不设置
thresholdType 报名门槛类型 0:金币(银币) 1:金条
},
...
}
比赛状态
GameConstant.NOT_SIGN_UP = 0 未报名
GameConstant.HAVE_SIGN_UP = 1 已报名/已报名未开赛
GameConstant.ALLOW_JOIN_IN = 2 允许进入
GameConstant.MATCH_HAVE_START = 3 比赛已经开始
GameConstant.SIGN_UP_AND_ALLOW_JOIN_IN = 4 报名并且比赛可以进入
GameConstant.SIGN_UP_BUT_HAVE_START = 5 报名但比赛已经开始
--]]
MatchIsolater.requestMatchList = function ( self )
return MatchHallDataInterface.getInstance():requestMatchList();
end
--[[
@brief 请求比赛列表回调
@param info (table) 比赛列表
--]]
MatchIsolater.onGetMatchList = function ( self, info)
self:notify(MatchIsolater.Delegate.onGetMatchList, info);
end
--[[
@brief 请求比赛详细信息
@param matchId (number) 比赛id
--]]
MatchIsolater.requestMatchDetail = function ( self, matchId, groupId)
MatchHallDataInterface.getInstance():requestMatchDetail(number.valueOf(matchId), groupId);
end
--[[
@brief 请求比赛详细信息回调
@param info (table) 比赛详细信息
info = {
matchid 比赛id
desc 规则描述
awardcount 比赛奖励数量
estimateduration 预估比赛时长(分钟)
awardsmap = { 奖励映射
"","",..
}
icon = { 奖励图片列表
["1"] = "", 图片url
["2"] = "",
...
}
award = { 奖励列表
[1] = { 列表项
rank 排名描述
sort 排名
desc 奖励描述
},
...
}
}
--]]
MatchIsolater.onResponseMatchDetail = function ( self, info,matchId )
self:notify(MatchIsolater.Delegate.onResponseMatchDetail, info,matchId);
end
--[[
@brief 清空比赛详情
@param matchId (number) 比赛id
--]]
MatchIsolater.cleanMatchDetailByMatchId = function(self, matchId)
MatchHallDataInterface.getInstance():cleanMatchDetailByMatchId(matchId);
end
--[[
@brief 请求比赛基础信息
@param matchId (number) 比赛id
--]]
MatchIsolater.requestMatchBasicInfo = function ( self, matchId )
MatchHallDataInterface.getInstance():requestMatchBasicInfo(matchId);
end
--[[
@brief 请求比赛基础信息回调
@param info (table) 比赛数据,即比赛列表数据项
--]]
MatchIsolater.onResponseMatchBasicInfo = function ( self, info )
self:notify(MatchIsolater.Delegate.onResponseMatchBasicInfo, info);
end
--[[
@brief 请求好友列表
--]]
MatchIsolater.requestFriendInviteList = function ( self )
MatchHallDataInterface.getInstance():requestFriendInviteList();
end
--[[
@brief 请求好友列表回调
@param info (table) 好友列表
info = {
[1] = {
nick 昵称
mid mid
cid cid
},
...
}
--]]
MatchIsolater.onGetFriendsInviteList = function ( self, info )
self:notify(MatchIsolater.Delegate.onGetFriendInviteList, info);
end
-- 请求邀请好友
--[[
@brief 请求邀请好友
@param cidList (table) cid列表
cidList = {
[1] = {
cid 被邀请cid
},
...
}
@param param (table) 邀请数据
param = {
mid 邀请方mid
nick 邀请方昵称
sendtime 发送时间
match_id 比赛id
match_name 比赛名称
match_entyfee 比赛报名费("报名费1,报名费2,...")
match_ccsq 兼容老版本
match_coin 兼容老版本
}
--]]
MatchIsolater.requestInviteFriends = function ( self, cidList, param )
MatchHallDataInterface.getInstance():requestInviteFriends(cidList, param);
end
--[[
@brief 刷新等待界面倒计时,CommonGameController.onResume调用
--]]
MatchIsolater.onRefreshMatchWatingTime = function (self)
self:notify(MatchIsolater.Delegate.onRefreshMatchWatingTime);
end
-- ==========================比赛大厅 end ====================================
-- ========================== 大师分 begin ====================================
--[[
@brief 获取玩家大师分
@return (number) 玩家大师分
--]]
MatchIsolater.getMyMasterPoint = function ( self )
return MatchRecordDataInterface.getInstance():getMyMasterPoint();
end
--[[
@brief 更新玩家大师分
@param masterpoint (number) 玩家大师分
--]]
MatchIsolater.setMyMasterPoint = function ( self, masterpoint )
MatchRecordDataInterface.getInstance():setMyMasterPoint(masterpoint);
end
-- ========================== 大师分 end ====================================
-- ============================ 分享 begin ====================================
--[[
@brief 设置比赛结算时分享图片
@param matchconfigid (number) 比赛配置id
@param shareImagePath (string) 下载后的图片路径
--]]
MatchIsolater.setMatchOverShareImageInfo = function(self, matchconfigid, shareImagePath)
self.m_matchOverShareImageInfo = {
matchconfigid = matchconfigid;
shareImagePath = shareImagePath;
};
end
--[[
@brief 判断图片是否下载完成了
@param matchconfigid (number) 比赛配置id
@return (boolean) 是否下载完成
@return (string) 图片地址,如果不为"",则代表下载成功,如果为"", 则代表下载失败。
--]]
MatchIsolater.isShareImageDownloadFinish = function(self, matchconfigid)
if string.isEmpty(matchconfigid) then
return true, ""; --如果configId为"",则认为下载失败
elseif not table.isEmpty(self.m_matchOverShareImageInfo) and self.m_matchOverShareImageInfo.matchconfigid == matchconfigid then
return true, self.m_matchOverShareImageInfo.shareImagePath;
else
return false;
end
end
-- ============================ 分享 end ====================================
-- ============================ 重连 begin ====================================
--[[
@brief 设置上次连接是否在比赛中
@param value (boolean) true:比赛中 false:不在比赛中
@note 用于判断比赛中途断线,重连回来比赛已经结束的情况,比赛开始设置为true,比赛结束和退赛设为false
--]]
MatchIsolater.setLastConnectInMatch = function(self, value)
MatchHallDataInterface.getInstance():setLastConnectInMatch(value);
end
-- ============================ 重连 end ====================================
|
return game:DefineFastFlag("DontRotateCharacterWhenInputSunk", false)
|
local INFO = require 'Data.info'
local M = {}
M.CONTROL = require 'Core.Simulation.control'
M.VARS = require 'Core.Simulation.vars'
M['onStart'] = function(nested, params)
for i = 1, #nested do
local name = nested[i].name
local params = nested[i].params
local type = UTF8.upper(INFO.getType(name))
pcall(function() M[type][name](params) end)
end
end
return M
|
local assets =
{
Asset("ANIM", "anim/sch_hat.zip"),
Asset("ATLAS", "images/inventoryimages/sch_hat.xml"),
Asset("IMAGE", "images/inventoryimages/sch_hat.tex"),
}
local prefabs =
{
}
local ARMOR_LEVEL = 999999999999999999999999999999999999999999999999999999999999999999999 ------ (-_-') -- Oh Hellyeah
local function levelexp(inst, data)
local max_exp = 1000
local exp = math.min(inst.hat_level, max_exp)
--[[
if inst.hat_level >= 1000 then
inst.components.talker:Say("[Armor Exp]".. (inst.hat_level))
end
]]
if inst.hat_level >= 0 and inst.hat_level < 100 then
inst.components.talker:Say("[ Armor Level ] : [ 1 ]\n[ Defense ] : [ 45% ]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 100 and inst.hat_level < 200 then
inst.components.talker:Say("[ Armor Level ] : [ 2 ]\n[ Defense ] : [ 50% ]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 200 and inst.hat_level < 300 then
inst.components.talker:Say("[ Armor Level ] : [ 3 ]\n[ Defense ] : [ 55%]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 300 and inst.hat_level < 400 then
inst.components.talker:Say("[ Armor Level ] : [ 4 ]\n[ Defense ] : [ 60% ]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 400 and inst.hat_level < 500 then
inst.components.talker:Say("[ Armor Level ] : [ 5 ]\n[ Defense ] : [ 65% ]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 500 and inst.hat_level < 600 then
inst.components.talker:Say("[ Armor Level ] : [ 6 ]\n[ Defense ] : [ 70% ]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 600 and inst.hat_level < 700 then
inst.components.talker:Say("[ Armor Level ] : [ 7 ]\n[ Defense ] : [ 75% ]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 700 and inst.hat_level < 800 then
inst.components.talker:Say("[ Armor Level ] : [ 8 ]\n[ Defense ] : [ 80% ]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 800 and inst.hat_level < 900 then
inst.components.talker:Say("[ Armor Level ] : [ 9 ]\n[ Defense ] : [ 85% ]\n[ Level Exp ] : ".. (inst.hat_level))
elseif inst.hat_level >= 900 then
inst.components.talker:Say("[ Armor Level ] : [ MAX ]\n[ Defense ] : [ 90% ]")
end
end
local function CheckArmor(inst, data)
if not inst.NoCharge then
if inst.hat_level >= 0 and inst.hat_level < 100 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.45)
elseif inst.hat_level >= 100 and inst.hat_level < 200 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.50)
elseif inst.hat_level >= 200 and inst.hat_level < 300 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.55)
elseif inst.hat_level >= 300 and inst.hat_level < 400 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.60)
elseif inst.hat_level >= 400 and inst.hat_level < 500 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.65)
elseif inst.hat_level >= 500 and inst.hat_level < 600 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.70)
elseif inst.hat_level >= 600 and inst.hat_level < 700 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.75)
elseif inst.hat_level >= 700 and inst.hat_level < 800 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.80)
elseif inst.hat_level >= 800 and inst.hat_level < 900 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.85)
elseif inst.hat_level >= 900 then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.90)
end
end
if inst.NoCharge then
inst.components.armor:InitCondition(ARMOR_LEVEL, 0.15)
end
end
local function OnTakeFuel(inst, data)
print("Fuel Taken")
inst.NoCharge = false
CheckArmor(inst)
end
local function OnDurability(inst, data)
if inst.components.fueled:IsEmpty() then
inst.NoCharge = true CheckArmor(inst)
inst.components.talker:Say("[ Armor Need Charge ]\n[ Defense ] : [ 15% ]")
elseif not inst.components.fueled:IsEmpty() then
inst.NoCharge = false
CheckArmor(inst)
end
end
local function OnGetItemFromPlayer(inst, giver, item)
local max_fuel = 700
local min_fuel = 0
local hat_armor = inst.components.fueled.currentfuel
local mx2 = math.floor(max_fuel - min_fuel)
local cur2 = math.floor(hat_armor - min_fuel)
local armorhat = ""..math.floor(cur2*700/mx2).."%/700%"
if item.prefab == "sch_dark_soul" then
inst.components.talker:Say("[ Soul Fuel ]\n[ Hat Exp Point ] : [ +25 ]\n[ Current Fuel ] : "..(armorhat))
inst.components.fueled:DoDelta(25)
inst.hat_level = inst.hat_level + 25
CheckArmor(inst) inst.NoCharge = false
end
if item:HasTag("LUXURYFUEL") then
inst.components.talker:Say("[ Luxury Fuel ]\n[ Hat Exp Point ] : [ +50 ]\n[ Current Fuel ] : "..(armorhat))
inst.components.fueled:DoDelta(50)
inst.hat_level = inst.hat_level + 50
CheckArmor(inst) inst.NoCharge = false
end
end
local function IsEmptyToUse(inst, owner)
local current = inst.components.fueled:GetPercent()
if current <= 0 then
inst.components.talker:Say("Hat need Fuel")
end
if inst.FuelRegen then
inst.FuelRegen:Cancel()
inst.FuelRegen = nil
end
end
local function StartRegent(inst, owner)
local max_fuel = 700
local min_fuel = 0
local hat_armor = inst.components.fueled.currentfuel
local mx2 = math.floor(max_fuel - min_fuel)
local cur2 = math.floor(hat_armor - min_fuel)
local armorhat = ""..math.floor(cur2*700/mx2).."%/700%"
inst.FuelRegen = inst:DoPeriodicTask(20, function(inst)
local current = inst.components.fueled:GetPercent() + 0.1
if current > 1 then
inst.components.talker:Say("Armor Charge is Full")
inst.components.fueled:SetPercent(1)
IsEmptyToUse(inst)
CheckArmor(inst)
inst.NoCharge = false
else
inst.components.fueled:SetPercent(current)
inst.hat_level = inst.hat_level + 2
inst.components.talker:Say("[ Armor Charge ] : "..(armorhat))
end
end)
end
local function OnStopUsingItem(inst, data)
local hat = inst.components.inventory ~= nil and inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD) or nil
if hat ~= nil and data.statename ~= "hide" then
hat.components.useableitem:StopUsingItem()
end
end
local function OnEquiped(inst, owner)
owner.AnimState:OverrideSymbol("swap_hat", "sch_hat", "swap_hat")
owner.AnimState:Show("HAT")
owner.AnimState:Hide("HAIR_HAT")
owner.AnimState:Show("HAIR_NOHAT")
owner.AnimState:Show("HAIR")
CheckArmor(inst)
if not inst.NoCharge then
local max_fuel = 700
local min_fuel = 0
local hat_armor = inst.components.fueled.currentfuel
local mx2 = math.floor(max_fuel - min_fuel)
local cur2 = math.floor(hat_armor - min_fuel)
local armorhat = ""..math.floor(cur2*700/mx2).."%/700%"
inst.components.talker:Say("[ Hat Armor Charge ] : "..(armorhat))
inst:DoTaskInTime(3, levelexp)
end
if not inst.components.fueled:IsEmpty() then
inst.FuelConsume = inst:DoPeriodicTask(3, function(inst) inst.components.fueled:DoDelta(-1) end)
else
if inst.FuelConsume then
inst.FuelConsume:Cancel()
inst.FuelConsume = nil
end
end
local attractor = owner.components.birdattractor
if attractor then
attractor.spawnmodifier:SetModifier(inst, TUNING.BIRD_SPAWN_MAXDELTA_FEATHERHAT, "maxbirds")
attractor.spawnmodifier:SetModifier(inst, TUNING.BIRD_SPAWN_DELAYDELTA_FEATHERHAT.MIN, "mindelay")
attractor.spawnmodifier:SetModifier(inst, TUNING.BIRD_SPAWN_DELAYDELTA_FEATHERHAT.MAX, "maxdelay")
local birdspawner = TheWorld.components.birdspawner
if birdspawner ~= nil then
birdspawner:ToggleUpdate(true)
end
end
-- inst:ListenForEvent("newstate", OnStopUsingItem, owner)
end
local function OnUnEquiped(inst, owner)
owner.AnimState:ClearOverrideSymbol("swap_hat")
owner.AnimState:Hide("HAT")
owner.AnimState:Hide("HAIR_HAT")
owner.AnimState:Show("HAIR_NOHAT")
owner.AnimState:Show("HAIR")
if inst.FuelConsume then
inst.FuelConsume:Cancel()
inst.FuelConsume = nil
end
local attractor = owner.components.birdattractor
if attractor then
attractor.spawnmodifier:RemoveModifier(inst)
local birdspawner = TheWorld.components.birdspawner
if birdspawner ~= nil then
birdspawner:ToggleUpdate(true)
end
end
-- inst:RemoveEventCallback("newstate", OnStopUsingItem, owner)
end
local function OnUseItem(inst)
local owner = inst.components.inventoryitem.owner
if owner then
owner.sg:GoToState("hide")
inst.AnimState:PlayAnimation("anim")
end
end
local function OnChosen(inst,owner)
return owner.prefab == "schwarzkirsche"
end
local function onsave(inst, data)
data.hat_level = inst.hat_level
end
local function onpreload(inst, data)
if data then
if data.hat_level then
inst.hat_level = data.hat_level
levelexp(inst)
end
end
end
local function fn()
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddNetwork()
inst.entity:AddAnimState()
inst.entity:SetPristine()
inst.entity:AddSoundEmitter()
MakeInventoryPhysics(inst)
MakeHauntableLaunch(inst)
inst.AnimState:SetBank("sweet_cookie")
inst.AnimState:SetBuild("sch_hat")
inst.AnimState:PlayAnimation("anim")
inst:AddTag("hats")
inst:AddTag("schhat")
inst:AddTag("ArmoredHat")
inst:AddTag("schwarzhat")
inst:AddTag("Headband")
if not TheWorld.ismastersim then
return inst
end
inst.entity:AddMiniMapEntity()
inst.MiniMapEntity:SetIcon( "sch_hat.tex" )
inst:AddComponent("inspectable")
inst.components.inspectable:RecordViews()
--[[
inst:AddComponent("useableitem")
inst.components.useableitem:SetOnUseFn(OnUseItem)
]]
inst:AddComponent("inventoryitem")
inst.components.inventoryitem.imagename = "sch_hat"
inst.components.inventoryitem.atlasname = "images/inventoryimages/sch_hat.xml"
inst:AddComponent("insulator")
inst.components.insulator:SetInsulation(TUNING.INSULATION_LARGE)
-- inst.components.insulator:SetWinter()
inst.components.insulator:SetSummer()
inst:AddComponent("waterproofer")
inst.components.waterproofer:SetEffectiveness(TUNING.WATERPROOFNESS_MED)
inst:AddComponent("armor")
inst:AddComponent("equippable")
inst.components.equippable.equipslot = EQUIPSLOTS.HEAD
inst.components.equippable:SetOnEquip(OnEquiped)
inst.components.equippable:SetOnUnequip(OnUnEquiped)
inst.components.equippable.dapperness = TUNING.DAPPERNESS_MED_LARGE
inst.components.equippable.insulated = true
inst:AddComponent("periodicspawner")
inst.components.periodicspawner:SetPrefab("spore_small")
inst.components.periodicspawner:SetRandomTimes(20, 1, true)
inst:AddComponent("talker")
inst.components.talker.fontsize = 22
inst.components.talker.font = TALKINGFONT
inst.components.talker.colour = Vector3(1, 0.8, 0.95, 1)
inst.components.talker.offset = Vector3(0,-500,0)
inst.components.talker.symbol = "swap_object"
inst:AddComponent("fueled")
inst.components.fueled.maxfuel = 700
inst.components.fueled.fueltype = FUELTYPE.LUXURYGEMS
inst.components.fueled.accepting = true
inst.components.fueled:StopConsuming()
inst.components.fueled:SetTakeFuelFn(OnTakeFuel)
inst.components.fueled:SetDepletedFn(OnDurability)
inst.components.fueled:InitializeFuelLevel(700)
inst:AddComponent("trader")
inst.components.trader:SetAcceptTest(function(inst, item) return item.prefab == "sch_dark_soul" or item:HasTag("LUXURYFUEL") end)
inst.components.trader.onaccept = OnGetItemFromPlayer
inst.components.trader.deleteitemonaccept = true
inst:ListenForEvent("equipped", IsEmptyToUse)
inst:ListenForEvent("unequipped", StartRegent)
inst:AddComponent("characterspecific")
inst.components.characterspecific:SetOwner("schwarzkirsche")
inst.components.characterspecific:SetStorable(true)
inst.components.characterspecific:SetComment("I can't hold this!")
inst:AddComponent("chosenpeople")
inst.components.chosenpeople:SetChosenFn(OnChosen)
inst.hat_level = 0
inst.OnSave = onsave
inst.OnPreLoad = onpreload
inst:ListenForEvent("levelup", levelexp)
return inst
end
return Prefab("common/inventory/sch_hat", fn, assets, prefabs)
|
--- Models persistent player data
Soul = serializable.define('Soul', function()
return {
name = "",
previous_characters = { },
current_character = nil
}
end)
--- Attach a soul to given player (called when players join)
-- Calls find_or_create and moves the player to the appropriate position
function Soul.attach(player)
local soul = Soul.find_or_create(player)
-- don't materialize unless we at least have an astral plane
local astral_plane = Site.get(stm.data.astral_plane)
if not astral_plane then return soul end
if soul:get_char() then
soul:move_to_character()
else
soul:confine_to_astral_plane()
end
return soul
end
function Soul.on_die_or_respawn(player)
local soul = Soul.find_or_create(player)
soul:excarnate()
end
--- Find or a create a Soul instance for this player
-- Always returns the same Soul instance for a given player name
function Soul.find_or_create(player)
stm.data.souls = stm.data.souls or { }
local name = player:get_player_name()
if stm.data.souls[name] then return Soul.get(stm.data.souls[name]) end
local soul = Soul.new({ name = name })
Soul.register(soul)
stm.data.souls[name] = soul.id
return soul
end
--- Create a new character and spawn the player into the simulation
function Soul:incarnate()
local race = stm.pick_from_hash(Race.all())
local site = stm.find_one(Site.all(), function(x) return x.is_municipality end)
local pos = nil
if site then pos = site:get_position() end
local result = Character.new({ soul = self.id, race = race.id, materialized = true, pos = pos })
self.current_character = result.id
Character.register(result)
self:move_to_character()
-- TODO: set player model to match the new character
return result
end
--- Kill any existing character for this soul and remove player from simulation
function Soul:excarnate()
local char = self:get_char()
if char then
char:die()
char.materialized = false
end
self:confine_to_astral_plane()
self.current_character = nil
-- TODO set player model to an amorphous soul-like thing
-- TODO move player to astral plane
end
--- Move excarnated souls back to the astral plane if they leave it
function Soul:confine_to_astral_plane()
local astral_plane = Site.get(stm.data.astral_plane)
if not astral_plane:contains(self:get_player():getpos()) then
self:get_player():setpos(astral_plane:get_position())
end
end
function Soul:move_to_character()
self:get_player():setpos(self:get_char():get_position())
end
function Soul:simulate(dt)
if not self.current_character then
self:confine_to_astral_plane()
end
end
function Soul:get_char()
return Character.get(self.current_character)
end
function Soul:get_player()
return minetest.get_player_by_name(self.name)
end
if minetest and minetest.register_on_joinplayer then
minetest.register_on_joinplayer(Soul.attach)
minetest.register_on_dieplayer(Soul.on_die_or_respawn)
minetest.register_on_respawnplayer(Soul.on_die_or_respawn)
minetest.register_chatcommand('incarnate', { func = function(name)
local soul = Soul.attach(minetest.get_player_by_name(name))
if not soul:get_char() then soul:incarnate() end
end})
end
|
-- Natural Selection 2 Competitive Mod
-- Source located at - https://github.com/xToken/CompMod
-- lua\CompMod\Mixins\NanoShieldMixin\shared.lua
-- - Dragon
function NanoShieldMixin:ComputeDamageOverrideMixin(attacker, damage, damageType, time)
if self.nanoShielded == true then
if self.NanoShieldDamageReductionOverride then
return damage * self:NanoShieldDamageReductionOverride(), damageType
end
return damage * kNanoShieldDamageReductionDamage, damageType
end
return damage
end
local ClearNanoShield = GetUpValue(NanoShieldMixin.OnDestroy, "ClearNanoShield")
function NanoShieldMixin:DeactivateNanoShield()
ClearNanoShield(self, true)
end
|
-- TODO: TOML and git specific parsers
local M = {
general = require('configfiles.parsers.general').parser,
git = require('configfiles.parsers.general').parser,
toml = require('configfiles.parsers.general').parser,
}
return M
|
local file = ...
local ok, err = require("fs").makeDir(file)
if not ok and err then error(err, 0) end
|
local ecs = require "ecs"
--main.c always calls this
ecs.progress_cb(function () end)
local MetaType = ecs.lookup_fullpath("flecs.meta.MetaType")
--This works
local strc = ecs.struct("STRC", "{int32_t x;int64_t w;}")
ecs.set(ecs.Singleton, strc, {x = 2, w = 400})
local f = ecs.get(ecs.Singleton, strc)
assert(f.x == 2)
assert(f.w == 400)
local meta = ecs.get(strc, MetaType)
print("size: ".. meta.size)
assert(meta.size == 16)
local array = ecs.array("ARR", "int32_t", 6)
ecs.set(ecs.Singleton, array, { 6, 5, 4, 2, 1 })
meta = ecs.get(array, MetaType)
assert(meta.size == 4 * 6)
assert(meta.alignment == 4)
local array2 = ecs.array("ARR2", "STRC", 6)
meta = ecs.get(array2, MetaType)
print("size: ".. meta.size)
assert(meta.size == 16 * 6)
assert(meta.alignment == 8)
|
package("xtensor-blas")
set_kind("library", {headeronly = true})
set_homepage("https://github.com/xtensor-stack/xtensor-blas/")
set_description("BLAS extension to xtensor")
set_license("BSD-3-Clause")
add_urls("https://github.com/xtensor-stack/xtensor-blas/archive/refs/tags/$(version).tar.gz",
"https://github.com/xtensor-stack/xtensor-blas.git")
add_versions("0.19.1", "c77cc4e2297ebd22d0d1c6e8d0a6cf0975176afa8cb99dbfd5fb2be625a0248f")
add_versions("0.20.0", "272f5d99bb7511a616bfe41b13a000e63de46420f0b32a25fa4fb935b462c7ff")
add_configs("vendor", {description = "Set BLAS vendor.", default = "openblas", type = "string", values = {"mkl", "openblas"}})
add_deps("cmake")
add_deps("xtensor")
on_load("windows", "linux", function (package)
package:add("deps", package:config("vendor"))
end)
on_install("windows", "linux", function (package)
import("package.tools.cmake").install(package)
end)
on_test(function (package)
assert(package:check_cxxsnippets({test = [[
#include <xtensor/xarray.hpp>
#include <xtensor-blas/xlinalg.hpp>
void test() {
xt::xarray<double> t1arg_0 = {{0, 1, 2},
{3, 4, 5},
{6, 7, 8}};
auto t1res = xt::linalg::matrix_power(t1arg_0, 2);
}
]]}, {configs = {languages = "c++14"}}))
end)
|
project "without_docking"
kind "ConsoleApp"
language "C++"
cppdialect "C++11"
warnings "off"
files {
"../common/sdl2*.*",
"../common/opengl*.*",
"*.cpp"
}
includedirs {
".",
"../../include",
"../common"
}
defines "_CONSOLE"
using { "horus", "sdl" }
distcopy(mytarget())
|
--[=[
Structured exceptions for Lua and TCP protocol error handling.
Written by Cosmin Apreutesei. Public Domain.
Structured exceptions are an enhancement over string exceptions, adding
selective catching and providing a context for the failure to help with
recovery or logging. They're most useful in network protocols.
errors.error base class for errors
errors.error:init() stub: called after the error is created
errors.errortype([classname], [super]) -> eclass create/get an error class
eclass(...) -> e create an error object
errors.new(classname,... | e) -> e create/wrap/pass-through an error object
errors.is(v[, classes]) -> true|false check an error object type
errors.raise([level, ]classname,... | e) (create and) raise an error
errors.catch([classes], f, ...) -> true,... | false,e pcall `f` and catch errors
errors.pcall(f, ...) -> ... pcall that stores traceback in `e.traceback`
errors.check(v, ...) -> v | raise(...) assert with specifying an error class
errors.protect(classes, f, [oncaught]) -> protected_f turn raising `f` into a `nil,e` function
eclass:__call(...) -> e error class constructor
eclass:__tostring() -> s to make `error(e)` work
eclass.addtraceback add a traceback to errors
e.message formatted error message
e.traceback traceback at error site
In the API `classes` can be given as either 'classname1 ...' or {class1->true}.
When given in table form, you must include all the superclasses in the table
since they are not added automatically!
errors.raise() passes its varargs to errors.new() which passes them to
eclass() which passes them to eclass:__call() which interprets them
as follows: `[err_obj, err_obj_options..., ][format, format_args...]`.
So if the first arg is a table it is converted to the final error object.
Any following table args are merged with this object. Any following args
after that are passed to string.format() and the result is placed in
err_obj.message (if `message` was not already set). All args are optional.
]=]
--prototype-based dynamic inheritance with __call constructor (from glue).
local function object(super, o)
o = o or {}
o.__index = super
o.__call = super and super.__call
o.__tostring = super and super.__tostring
return setmetatable(o, o)
end
local lua_error = error
local classes = {} --{name -> class}
local class_sets = {} --{'name1 name2 ...' -> {class->true}}
local error --base error class, defined below.
local function errortype(classname, super, default_error_message)
local class = classname and classes[classname]
if not class then
super = type(super) == 'string' and assert(classes[super]) or super or error
class = object(super, {classname = classname, iserror = true,
default_error_message = default_error_message or classname .. ' error'})
if classname then
classes[classname] = class
class_sets = {}
end
end
return class
end
error = errortype'error'
error.init = function() end
local function iserror(e)
return type(e) == 'table' and e.iserror
end
local function newerror(arg, ...)
if type(arg) == 'string' then
local class = classes[arg] or errortype(arg)
return class(...)
end
return arg
end
local function class_table(s)
if type(s) == 'string' then
local t = class_sets[s]
if not t then
t = {}
class_sets[s] = t
for s in s:gmatch'[^%s,]+' do
local class = classes[s]
while class do
t[class] = true
class = class.__index
end
end
end
return t
else
assert(type(s) == 'table')
return s --if given as table, must contain superclasses too!
end
end
local function iserrorof(e, classes)
if not iserror(e) then return false end
if not classes then return true end
return class_table(classes)[e.__index] or false
end
local function merge_option_tables(e, arg1, ...)
if type(arg1) == 'table' then
for k,v in pairs(arg1) do e[k] = v end
return merge_option_tables(e, ...)
else
e.message = e.message or (arg1 and string.format(arg1, ...) or nil)
return e
end
end
function error:__call(arg1, ...)
local e
if type(arg1) == 'table' then
e = merge_option_tables(object(self, arg1), ...)
else
e = object(self, {message = arg1 and string.format(arg1, ...) or nil})
end
e:init()
return e
end
function error:__tostring()
local s = self.traceback or self.message or self.default_error_message
if self.errorcode then
s = s .. ' ['..self.errorcode..']'
end
return s
end
local function raise(level, ...)
if type(level) == 'number' then
lua_error(newerror(...), level)
else
lua_error((newerror(level, ...)))
end
end
local function pass(classes, ok, ...)
if ok then return true, ... end
local e = ...
if iserrorof(e, classes) then
return false, e
end
lua_error(e, 3)
end
local function onerror(e)
if iserror(e) then
if e.addtraceback then
e.traceback = debug.traceback(e.message, 2)
end
else
return debug.traceback(tostring(e), 2)
end
return e
end
local function zpcall(f, ...)
return xpcall(f, onerror, ...)
end
local function catch(classes, f, ...)
return pass(classes, zpcall(f, ...))
end
local function check(class, v, ...)
if v then return v, ... end
raise(class, ...)
end
local function pass(oncaught, ok, ...)
if ok then return ... end
if oncaught then oncaught(...) end
return nil, ...
end
local function protect(classes, f, oncaught)
return function(...)
return pass(oncaught, catch(classes, f, ...))
end
end
local errors = {
error = error,
errortype = errortype,
new = newerror,
is = iserrorof,
raise = raise,
catch = catch,
pcall = zpcall,
check = check,
protect = protect,
}
--[=[-------------------------------------------------------------------------
TCP protocol error handling
errors.tcp_protocol_errors(protocol_name) -> check_io, checkp, check, protect
check[p|_io](self, val, format, format_args...) -> val
This is an error-handling discipline to use when writing TCP-based
protocols. Instead of using standard `assert()` and `pcall()`, use `check()`,
`checkp()` and `check_io()` to raise errors inside protocol methods and then
wrap those methods in `protect()` to catch those errors and have the method
return `nil, err` instead of raising for those types of errors.
You should distinguish between multiple types of errors:
- Invalid API usage, i.e. bugs on this side, which should raise (but shouldn't
happen in production). Use `assert()` for those.
- Response validation errors, i.e. bugs on the other side which shouldn't
raise but they put the connection in an inconsistent state so the connection
must be closed. Use `checkp()` short of "check protocol" for those. Note that
if your protocol is not meant to work with a hostile or unstable peer, you
can skip the `checkp()` checks entirely because they won't guard against
anything and just bloat the code.
- Request or response content validation errors, which can be user-corrected
so mustn't raise and mustn't close the connection. Use `check()` for those.
- I/O errors, i.e. network failures which can be temporary and thus make the
request retriable (in a new connection, this one must be closed), so they
must be distinguishable from other types of errors. Use `check_io()` for
those. On the call side then check the error class for implementing retries.
Following this protocol should easily cut your network code in half, increase
its readability (no more error-handling noise) and its reliability (no more
confusion about when to raise and when not to or forgetting to handle an error).
Your connection object must have a `tcp` field with a tcp:close() method
to be called by check_io() and checkp() (but not by check()) on failure.
Note that protect() only catches errors raised by check*(), other Lua errors
pass through and the connection isn't closed either.
Note that the sock API does not currently distinguish usage errors from
network errors, so calling eg. `check_io(self, self.tcp:connect())` will
catch usage errors as network errors. This must be fixed in sock, eg. with
a third return value `retry` indicating that the error is a network error,
then we can make check_io() take that into account and call check()
internally if `retry` is false.
]=]
local tcp_error = errors.errortype'tcp'
function tcp_error:init()
if self.tcp then
self.tcp:close(0)
self.tcp = nil
end
end
local function check_io(self, v, ...)
if v then return v, ... end
errors.raise(tcp_error({
tcp = self and self.tcp,
addtraceback = self and self.tracebacks,
}, ...))
end
errors.tcp_protocol_errors = function(protocol)
local protocol_error = errors.errortype(protocol, nil, protocol .. ' protocol error')
local content_error = errors.errortype(nil, nil, protocol .. ' error')
protocol_error.init = tcp_error.init
local function checker(create_error)
return function(self, v, ...)
if v then return v, ... end
errors.raise(create_error({
tcp = self and self.tcp,
addtraceback = self and self.tracebacks,
}, ...))
end
end
local checkp = checker(protocol_error)
local check = checker(content_error)
local classes = {[tcp_error]=1, [protocol_error]=1, [content_error]=1}
local function protect(f, oncaught)
return errors.protect(classes, f, oncaught)
end
return check_io, checkp, check, protect
end
--self test ------------------------------------------------------------------
if not ... then
local check_io, checkp, check, protect = errors.tcp_protocol_errors'test'
local t = {tcp = {close = function(self) self.closed = true end}, tracebacks = false}
t.test0 = protect(function(t) check(t) end)
t.test1 = protect(function(t) checkp(t, nil, 'see %d', 123) end)
t.test2 = protect(function(t) check_io(t, nil, 'see %d', 321) end)
t.test3 = protect(function(t) checkp(t) end)
print(t:test0())
assert(not t.tcp.closed)
print(t:test1())
assert(t.tcp.closed)
print(t:test2())
print(t:test3())
local e1 = errors.errortype'e1'
local e2 = errors.errortype('e2', 'e1')
local e3 = errors.errortype'e3'
local ok, e = errors.catch('e2 e3', function()
local ok, e = errors.catch('e1', function()
errors.raise('e2', 'imma e2')
end)
print'should not get here'
end)
if not ok then
print('caught', e.classname, e.message)
end
errors.raise(e)
end
return errors
|
-- gmod version 2021.08.23
--ulxSTC:CreatUITamplete( "SandBox_Default", "sandbox" )
surface.CreateFont( "CommandButtonDefault", {
font = "Helvetica",
size = 18,
weight = 800
} )
surface.CreateFont( "ScoreboardDefault", {
font = "Helvetica",
size = 22,
weight = 800
} )
surface.CreateFont( "ScoreboardDefaultTitle", {
font = "Helvetica",
size = 32,
weight = 800
} )
if shortcut_Scoreboard then shortcut_Scoreboard:Remove() end
shortcut_Scoreboard = nil
--
-- This defines a new panel type for the player row. The player row is given a player
-- and then from that point on it pretty much looks after itself. It updates player info
-- in the think function, and removes itself when the player leaves the server.
local SelectedPlayers = {}
local PLAYER_LINE = {
Init = function( self )
self.PlayerPanel = self:Add( "Panel" )
self.PlayerPanel:Dock( FILL )
self.CommandPanel = self:Add( "Panel" )
self.CommandPanel:Dock( RIGHT )
self.CommandPanel:SetWidth( 0 )
self.CommandPanel.Paint = function(self, w, h) draw.RoundedBox( 4, 0, 0, w, h, Color( 0, 0, 0, 255 ) ) end
self.AvatarButton = self.PlayerPanel:Add("DButton", self.PlayerPanel)
self.AvatarButton:Dock( LEFT )
self.AvatarButton:SetSize( 32, 32 )
self.AvatarButton.DoClick = function() self.Player:ShowProfile() end
self.Avatar = vgui.Create( "AvatarImage", self.AvatarButton )
self.Avatar:SetSize( 32, 32 )
self.Avatar:SetMouseInputEnabled( false )
local MyColor = Color(0,0,0,0)
self.PlayerSelect = self.PlayerPanel:Add("DButton")
self.PlayerSelect:Dock( FILL )
self.PlayerSelect:SetText("")
self.PlayerSelect.IsSelected = false
self.PlayerSelect.DoClick = function() self:PlayerSelectionClicked(self.Player) end
MyColor = Color(0,0,0,0)
self.PlayerSelect.Paint = function(self, w, h) draw.RoundedBox( 4, 0, 0, w, h, MyColor ) end
self.PlayerSelect.SetColor = function(color)
MyColor = color or Color(0,0,0,0)
end
self.Name = vgui.Create("DLabel", self.PlayerSelect)
self.Name:Dock( FILL )
self.Name:SetFont( "ScoreboardDefault" )
self.Name:SetTextColor( Color( 93, 93, 93 ) )
self.Name:DockMargin( 8, 0, 0, 0 )
self.Name:SetMouseInputEnabled( false )
self.Mute = self.PlayerPanel:Add( "DImageButton" )
self.Mute:SetSize( 32, 32 )
self.Mute:Dock( RIGHT )
self.Ping = self.PlayerPanel:Add( "DLabel" )
self.Ping:SetWidth( 50 )
self.Ping:Dock( RIGHT )
self.Ping:SetFont( "ScoreboardDefault" )
self.Ping:SetTextColor( Color( 93, 93, 93 ) )
self.Ping:SetContentAlignment( 5 )
self.Deaths = self.PlayerPanel:Add( "DLabel" )
self.Deaths:Dock( RIGHT )
self.Deaths:SetWidth( 50 )
self.Deaths:SetFont( "ScoreboardDefault" )
self.Deaths:SetTextColor( Color( 93, 93, 93 ) )
self.Deaths:SetContentAlignment( 5 )
self.Kills = self.PlayerPanel:Add( "DLabel" )
self.Kills:Dock( RIGHT )
self.Kills:SetWidth( 50 )
self.Kills:SetFont( "ScoreboardDefault" )
self.Kills:SetTextColor( Color( 93, 93, 93 ) )
self.Kills:SetContentAlignment( 5 )
self:Dock( TOP )
self:DockPadding( 3, 3, 3, 3 )
self:SetHeight( 32 + 3 * 2 )
self:DockMargin( 2, 0, 2, 2 )
end,
PlayerSelectionClicked = function(self, ply, bool, rotate)
self.PlayerSelect.IsSelected = self.PlayerSelect.IsSelected or false
if bool != nil and not rotate then
if bool then -- select all or unselect all
self:SelectPlayers(ply)
else
self:RemovePlayers(ply)
end
self.PlayerSelect.IsSelected = bool
elseif rotate then -- rotate selection
if self.PlayerSelect.IsSelected then
self:RemovePlayers(ply)
else
self:SelectPlayers(ply)
end
self.PlayerSelect.IsSelected = !self.PlayerSelect.IsSelected
else -- select or unselect self
if self.PlayerSelect.IsSelected then
self:RemovePlayers(ply)
else
self:SelectPlayers(ply)
end
self.PlayerSelect.IsSelected = !self.PlayerSelect.IsSelected
hook.Run("ULXSHORTCUT_PlayerSelectionClicked", self.PlayerSelect.IsSelected)
end
end,
SelectPlayers = function( self, ply )
table.insert(SelectedPlayers, ply)
self.PlayerSelect.SetColor( Color( 101, 149, 255, 255 ) )
self.Name:SetTextColor( Color( 255, 255, 255 ) )
self.PlayerSelect:SetIcon( "icon16/tick.png" )
self.Name:SetText( " " .. self.PName )
surface.PlaySound( "UI/buttonclick.wav" )
end,
RemovePlayers = function( self, ply )
table.RemoveByValue(SelectedPlayers, ply)
self.PlayerSelect.SetColor( Color( 0, 0, 0, 0 ) )
self.Name:SetTextColor( Color( 93, 93, 93 ) )
self.PlayerSelect:SetIcon( nil )
self.Name:SetText( self.PName )
surface.PlaySound( "UI/buttonclickrelease.wav" )
end,
RefreshCommandPanel = function( self )
self.CommandPanel:Clear()
self.CommandPanel:SetWidth(0)
if #ulxSTC:GetAllCommandHK() == 0 then
self:AddCommandPanel( ulxSTC:Str( "Make_New" ), ulxSTC.HKEditor.Open, Color(255,255,255,255), "icon16/add.png", 1, true )
else
for k, v in pairs(ulxSTC:GetAllCommandHK()) do
local panel = self:AddCommandPanel( v.name, v.cmd, v.color, v.icon, k, false, self.Player )
panel.DoRightClick = function(self)
self.Options = DermaMenu()
--self.Options:AddOption( "\"" .. v.name .. "\" 실행", function() ulxSTC:RunCommandByHKNum( k, self.Player, nil ) end ):SetIcon( "icon16/resultset_first.png" )
self.Options:AddOption( ulxSTC:Str( "Edit_Shortcut", v.name ), function() ulxSTC.HKEditor:Open( v, k ) end):SetIcon( "icon16/pencil.png" )
self.Options:AddOption( ulxSTC:Str( "Delete_Shortcut", v.name ), function() ulxSTC:RemoveCommandHKByName( v.name ) end):SetIcon( "icon16/bin.png" )
self.Options:AddOption( ulxSTC:Str( "Make_New_Shortcut" ), ulxSTC.HKEditor.Open ):SetIcon( "icon16/add.png" )
self.Options:AddOption( ulxSTC:Str( "CopyToClipboard" ), function() ulxSTC:CopyHKListToClipboard() end ):SetIcon( "icon16/page_copy.png" )
self.Options:AddOption( ulxSTC:Str( "SetListTo" ), function() ulxSTC.HKEditor:Open( nil, nil, true ) end ):SetIcon( "icon16/page_save.png" )
self.Options:Open()
end
end
end
if self.CommandPanel:GetWide() > 900/2 then
SCORE_BOARD_SIZE_W = 900 + ( self.CommandPanel:GetWide() - 900/2 )
SCORE_BOARD_SIZE_T = ScrH() - 200
SCORE_BOARD_POS_X = ScrW()/2 - (900 + ( self.CommandPanel:GetWide() - 900/2 ))/2
SCORE_BOARD_POS_Y = 100
else
SCORE_BOARD_SIZE_W = 900
SCORE_BOARD_SIZE_T = ScrH() - 200
SCORE_BOARD_POS_X = ScrW() / 2 -450
SCORE_BOARD_POS_Y = 100
end
shortcut_Scoreboard:SetSize( SCORE_BOARD_SIZE_W, SCORE_BOARD_SIZE_T )
shortcut_Scoreboard:SetPos( SCORE_BOARD_POS_X, SCORE_BOARD_POS_Y )
end,
AddCommandPanel = function( self, name, module, color, icon, num, new )
local num = num or 1
local comBack = vgui.Create( "DButton", self.CommandPanel )
local name = name or ""
local color = color or Color(255,255,255,255)
local icon = icon or "icon16/add.png"
surface.SetFont( "CommandButtonDefault" )
local w, h = surface.GetTextSize( name )
comBack:SetSize( 32 + w + 10, 32 )
comBack:Dock( RIGHT )
comBack:SetIcon( icon )
comBack:SetText( " " .. name)
comBack:SetFont("CommandButtonDefault")
local left = false
local right = false
if num == 1 then
right = true
end
if num == #ulxSTC:GetAllCommandHK() then
left = true
end
comBack.HKModule = module
comBack.HKColor = color
comBack.Paint = function(self, w, h)
draw.RoundedBoxEx( 4, 0, 0, w, h, self.HKColor, left, right, left, right )
end
self.CommandPanel:SetWidth( 32 + w + 10 + self.CommandPanel:GetWide() )
comBack.DoClick = function()
if new then
module()
else
local selectedPlayer = {}
if self.PlayerSelect.IsSelected then
for k, v in pairs(player.GetAll()) do
if v.scoreBoardPanel.PlayerSelect.IsSelected then
table.insert(selectedPlayer, v)
end
end
end
if table.IsEmpty( selectedPlayer ) then
table.Empty(selectedPlayer)
table.insert(selectedPlayer, self.Player)
end
ulxSTC:RunCommandByHKNum( num, selectedPlayer, InstantArgs )
end
end
comBack.OnCursorEntered = function()
comBack.HKColor = Color(comBack.HKColor.r, comBack.HKColor.g, comBack.HKColor.b, 100)
self.BGAlpha = 150
end
comBack.OnCursorExited = function()
comBack.HKColor = color
self.BGAlpha = 255
end
return comBack
end,
GetPlayerData = function(self)
return self.Player
end,
Setup = function( self, pl )
self.Player = pl
self.Avatar:SetPlayer( pl )
self:Think( self )
self:RefreshCommandPanel()
pl.scoreBoardPanel = self
--local friend = self.Player:GetFriendStatus()
--MsgN( pl, " Friend: ", friend )
end,
Think = function( self )
if ( !IsValid( self.Player ) ) then
if istable(SelectedPlayers) then
local removedValue = table.RemoveByValue(SelectedPlayers, self.Player) -- remove NULL player
--print("removed Null player")
end
self:SetZPos( 9999 ) -- Causes a rebuild
self:Remove()
return
end
if ( self.PName == nil || self.PName != self.Player:Nick() ) then
self.PName = self.Player:Nick()
self.Name:SetText( self.PName )
end
if ( self.NumKills == nil || self.NumKills != self.Player:Frags() ) then
self.NumKills = self.Player:Frags()
self.Kills:SetText( self.NumKills )
end
if ( self.NumDeaths == nil || self.NumDeaths != self.Player:Deaths() ) then
self.NumDeaths = self.Player:Deaths()
self.Deaths:SetText( self.NumDeaths )
end
if ( self.NumPing == nil || self.NumPing != self.Player:Ping() ) then
self.NumPing = self.Player:Ping()
self.Ping:SetText( self.NumPing )
end
--
-- Change the icon of the mute button based on state
--
if ( self.Muted == nil || self.Muted != self.Player:IsMuted() ) then
self.Muted = self.Player:IsMuted()
if ( self.Muted ) then
self.Mute:SetImage( "icon32/muted.png" )
else
self.Mute:SetImage( "icon32/unmuted.png" )
end
self.Mute.DoClick = function( s ) self.Player:SetMuted( !self.Muted ) end
self.Mute.OnMouseWheeled = function( s, delta )
self.Player:SetVoiceVolumeScale( self.Player:GetVoiceVolumeScale() + ( delta / 100 * 5 ) )
s.LastTick = CurTime()
end
self.Mute.PaintOver = function( s, w, h )
if ( !IsValid( self.Player ) ) then return end
local a = 255 - math.Clamp( CurTime() - ( s.LastTick or 0 ), 0, 3 ) * 255
if ( a <= 0 ) then return end
draw.RoundedBox( 4, 0, 0, w, h, Color( 0, 0, 0, a * 0.75 ) )
draw.SimpleText( math.ceil( self.Player:GetVoiceVolumeScale() * 100 ) .. "%", "DermaDefaultBold", w / 2, h / 2, Color( 255, 255, 255, a ), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
end
end
--
-- Connecting players go at the very bottom
--
if ( self.Player:Team() == TEAM_CONNECTING ) then
self:SetZPos( 2000 + self.Player:EntIndex() )
return
end
--
-- This is what sorts the list. The panels are docked in the z order,
-- so if we set the z order according to kills they'll be ordered that way!
-- Careful though, it's a signed short internally, so needs to range between -32,768k and +32,767
--
self:SetZPos( ( self.NumKills * -50 ) + self.NumDeaths + self.Player:EntIndex() )
end,
Paint = function( self, w, h )
if ( !IsValid( self.Player ) ) then
return
end
--
-- We draw our background a different colour based on the status of the player
--
if ( self.Player:Team() == TEAM_CONNECTING ) then
draw.RoundedBox( 4, 0, 0, w, h, Color( 200, 200, 200, (self.BGAlpha or 255) - 55 ) )
return
end
if ( !self.Player:Alive() ) then
draw.RoundedBox( 4, 0, 0, w, h, Color( 230, 200, 200, self.BGAlpha or 255 ) )
return
end
if ( self.Player:IsAdmin() ) then
draw.RoundedBox( 4, 0, 0, w, h, Color( 230, 255, 230, self.BGAlpha or 255 ) )
return
end
draw.RoundedBox( 4, 0, 0, w, h, Color( 230, 230, 230, self.BGAlpha or 255 ) )
end
}
--
-- Convert it from a normal table into a Panel Table based on DPanel
--
PLAYER_LINE = vgui.RegisterTable( PLAYER_LINE, "DPanel" )
--
-- Here we define a new panel table for the scoreboard. It basically consists
-- of a header and a scrollpanel - into which the player lines are placed.
--
local SCORE_BOARD = {
Init = function(self)
self.Header = self:Add( "Panel" )
self.Header:Dock( TOP )
self.Header:SetHeight( 100 )
self.Name = self.Header:Add("DLabel")
self.Name:SetFont( "ScoreboardDefaultTitle" )
self.Name:SetTextColor( color_white )
self.Name:Dock( TOP )
self.Name:SetHeight( 40 )
self.Name:SetContentAlignment( 5 )
self.Name:SetExpensiveShadow( 2, Color( 0, 0, 0, 200 ) )
self.AllPlayerPanel = self:Add( "Panel" )
self.AllPlayerPanel:Dock( TOP )
self.AllPlayerPanel:SetHeight( 32 )
self.AllPlayerPanel:DockMargin( 0, 0, 0, 5)
local selectCount = 0
local MyColor = Color( 151, 199, 255, 255 )
self.AllPlayerSelect = self.AllPlayerPanel:Add("DButton") -- All select or unselect
self.AllPlayerSelect:DockMargin( 5,0,0,0 )
self.AllPlayerSelect:Dock( LEFT )
self.AllPlayerSelect:SetWide( 150 )
self.AllPlayerSelect:SetText( ulxSTC:Str( "Select_All" ) )
self.AllPlayerSelect:SetFont("CommandButtonDefault")
self.AllPlayerSelect:SetIcon( "icon16/tick.png" )
self.AllPlayerSelect.IsSelected = false
self.AllPlayerSelect.DoClick = function()
self.AllPlayerSelect.IsSelected = !self.AllPlayerSelect.IsSelected
self:SelectAllPlayers(self.AllPlayerSelect.IsSelected)
if self.AllPlayerSelect.IsSelected then
self.AllPlayerSelect.SetColor(Color( 255, 199, 151, 255 ))
self.AllPlayerSelect:SetText( ulxSTC:Str( "De_Select_All" ) )
selectCount = #player.GetAll()
self.AllPlayerSelect:SetIcon( "icon16/cross.png" )
else
self.AllPlayerSelect.SetColor(Color( 151, 199, 255, 255 ))
self.AllPlayerSelect:SetText( ulxSTC:Str( "Select_All" ) )
selectCount = 0
self.AllPlayerSelect:SetIcon( "icon16/tick.png" )
end
end
self.AllPlayerSelect.Paint = function(self, w, h) draw.RoundedBox( 4, 0, 0, w, h, MyColor ) end
self.AllPlayerSelect.SetColor = function(color)
MyColor = color or Color(0,0,0,0)
end
self.AllPlayerSelectMirror = self.AllPlayerPanel:Add("DButton") -- Mirror select
self.AllPlayerSelectMirror:DockMargin( 5,0,0,0 )
self.AllPlayerSelectMirror:Dock( LEFT )
self.AllPlayerSelectMirror:SetWide( 150 )
self.AllPlayerSelectMirror:SetText( ulxSTC:Str( "Mirror" ) )
self.AllPlayerSelectMirror:SetFont("CommandButtonDefault")
self.AllPlayerSelectMirror:SetIcon( "icon16/arrow_switch.png" )
self.AllPlayerSelectMirror.IsSelected = false
self.AllPlayerSelectMirror.DoClick = function()
selectCount = math.abs(selectCount - #player.GetAll())
self.AllPlayerSelectMirror.IsSelected = !self.AllPlayerSelectMirror.IsSelected
self:SelectAllPlayers(self.AllPlayerSelectMirror.IsSelected, true)
if selectCount < 0 then selectCount = 0 end
if selectCount > 0 then
self.AllPlayerSelect.SetColor(Color( 255, 199, 151, 255 ))
self.AllPlayerSelect:SetText( ulxSTC:Str( "De_Select_All" ) )
self.AllPlayerSelect:SetIcon( "icon16/cross.png" )
self.AllPlayerSelect.IsSelected = true
else
self.AllPlayerSelect.SetColor(Color( 151, 199, 255, 255 ))
self.AllPlayerSelect:SetText( ulxSTC:Str( "Select_All" ) )
self.AllPlayerSelect:SetIcon( "icon16/tick.png" )
self.AllPlayerSelect.IsSelected = false
end
end
self.AllPlayerSelectMirror.Paint = function(self, w, h) draw.RoundedBox( 4, 0, 0, w, h, Color(255,255,255) ) end
hook.Add("ULXSHORTCUT_PlayerSelectionClicked", "AllPlayerSelect", function(bo)
if selectCount < 0 then selectCount = 0 end
if bo then
selectCount = selectCount + 1
else
selectCount = selectCount - 1
end
if selectCount > 0 then
self.AllPlayerSelect.SetColor(Color( 255, 199, 151, 255 ))
self.AllPlayerSelect:SetText( ulxSTC:Str( "De_Select_All" ) )
self.AllPlayerSelect:SetIcon( "icon16/cross.png" )
self.AllPlayerSelect.IsSelected = true
else
self.AllPlayerSelect.SetColor(Color( 151, 199, 255, 255 ))
self.AllPlayerSelect:SetText( ulxSTC:Str( "Select_All" ) )
self.AllPlayerSelect:SetIcon( "icon16/tick.png" )
self.AllPlayerSelect.IsSelected = false
end
--PrintTable(SelectedPlayers)
end)
--self.NumPlayers = self.Header:Add( "DLabel" )
--self.NumPlayers:SetFont( "ScoreboardDefault" )
--self.NumPlayers:SetTextColor( color_white )
--self.NumPlayers:SetPos( 0, 100 - 30 )
--self.NumPlayers:SetSize( 300, 30 )
--self.NumPlayers:SetContentAlignment( 4 )
--[[self.CommandsB = self:Add("Panel")
self.CommandsB:Dock( BOTTOM )
self.CommandsB:SetHeight( 100 )]]
--[[self.MadeBy = self.AllPlayerPanel:Add( "Panel" )
self.MadeBy:Dock( LEFT )
self.MadeBy:SetWidth( 200 )
self.MadeBy.Paint = function(self, w, h) draw.RoundedBox( 4, 0, 0, w, h, Color( 0, 0, 0, 255 ) ) end]]
local Name = self.AllPlayerPanel:Add("DLabel")
Name:SetFont( "DermaDefault" )
Name:SetTextColor( color_white )
Name:DockMargin( 5,0,0,0 )
Name:Dock( LEFT )
--Name:SetHeight( 40 )
Name:SetWidth( 300 )
Name:SetContentAlignment( 1 )
Name:SetText( "'Ulx Shortcut " .. ulxSTC.CurVersionString .. "' | Made by MINBIRD" )
Name:SetAlpha( 150 )
self.Scores = self:Add("DScrollPanel")
self.Scores:Dock( FILL )
end,
SelectAllPlayers = function( self, bool, rotate )
local plyrs = player.GetAll()
for id, pl in pairs(plyrs) do
pl.scoreBoardPanel:PlayerSelectionClicked(pl,bool,rotate)
end
end,
Paint = function( self, w, h )
end,
PerformLayout = function( self )
SCORE_BOARD_SIZE_W = SCORE_BOARD_SIZE_W or 900
SCORE_BOARD_SIZE_T = SCORE_BOARD_SIZE_T or ScrH() - 200
SCORE_BOARD_POS_X = SCORE_BOARD_POS_X or ScrW() / 2 -450
SCORE_BOARD_POS_Y = SCORE_BOARD_POS_Y or 100
self:SetSize( SCORE_BOARD_SIZE_W, SCORE_BOARD_SIZE_T )
self:SetPos( SCORE_BOARD_POS_X, SCORE_BOARD_POS_Y )
end,
Think = function( self, w, h )
self.Name:SetText( GetHostName() ) -- GetHostName()
--
-- Loop through each player, and if one doesn't have a score entry - create it.
--
local plyrs = player.GetAll()
for id, pl in pairs( plyrs ) do
if ( IsValid( pl.ScoreEntry ) ) then continue end
pl.ScoreEntry = vgui.CreateFromTable( PLAYER_LINE, pl.ScoreEntry )
pl.ScoreEntry:Setup( pl )
pl.ScoreEntry:RefreshCommandPanel()
pl.Margin = vgui.Create( "Panel", pl.ScoreEntry )
pl.Margin:Dock( RIGHT )
pl.Margin:SetWidth( 30 )
self.Scores:AddItem( pl.ScoreEntry )
end
end
}
SCORE_BOARD = vgui.RegisterTable( SCORE_BOARD , "EditablePanel" )
local SCORE_BOARD_SIZE_W = 900
local SCORE_BOARD_SIZE_T = ScrH() - 200
local SCORE_BOARD_POS_X = ScrW() / 2 -450
local SCORE_BOARD_POS_Y = 100
hook.Add("InitPostEntity", "ULXSHORTCUT_INIT", function()
function GAMEMODE:ScoreboardShow()
if ( !IsValid( shortcut_Scoreboard ) ) then
shortcut_Scoreboard = vgui.CreateFromTable( SCORE_BOARD )
end
shortcut_Scoreboard:Show()
shortcut_Scoreboard:MakePopup()
shortcut_Scoreboard:SetKeyboardInputEnabled( false )
shortcut_Scoreboard:MoveToFront()
end
--[[---------------------------------------------------------
Name: gamemode:ScoreboardHide( )
Desc: Hides the scoreboard
-----------------------------------------------------------]]
function GAMEMODE:ScoreboardHide()
if ( IsValid( shortcut_Scoreboard ) ) then
shortcut_Scoreboard:Hide()
end
end
end)
hook.Add("ULXSHORTCUT_COMMANDHK_ONCHANGE", "RefreshCommandPanel", function()
local plyrs = player.GetAll()
for k, pl in pairs(plyrs) do
pl.ScoreEntry:RefreshCommandPanel()
end
end)
|
-- time_local, request must exist
informat = {
"ip", "-", "#remote_user", "time_local", "request",
"status", "#body_bytes_sent", "request_time", "#http_referer",
"#http_user_agent", "#http_x_forwarded_for",
}
delete_request_field = true
time_local_format = "iso8601"
-- format time_local to iso8601
-- request: GET /pingback/storage?event=UPLOAD&hdfs_src=/pathtosrc&hdfs_dst=/hdfspath HTTP/1.1
-- auto add request_method GET
-- auto add request_uri /pingback/storage
-- auto add request_qs TABLE, event=UPLOAD, hdfs_src=/pathtosrc, hdfs_dst=/hdfspath
-- move method/uri/field in querystring to fields
request_map = {
["uri"] = "__uri__",
["querystring"] = "__query__",
["ip"] = "ip", -- ip in querystring has a higher priority
["event"] = "event",
}
request_type = {
["status"] = "i",
["request_time"] = 'f',
["uri"] = {"prefix", "/host"}
}
-- if transform_param_fields is not nil, pass the selected fields to transform
-- the third value transform return must be nil
-- transform_param_fields = {}
-- return timestamp, type, field-table
transform = function(fields)
return time, nil, fields
end
|
pico-8 cartridge // http://www.pico-8.com
version 18
__lua__
--system
function getrender()
local render = {}
render.__index = render
local system_type = "render"
setmetatable(render, {
__index = system, -- this is what makes the inheritance work
__call = function (cls, ...)
local self = setmetatable({}, cls)
self:_init(...)
return self
end,
})
function render:_init()
system._init(self, system_type) -- call the base class constructor
end
function render:render()
foreach(self.entitys,
function(e)
local trf = e:get("transform")
local s = e:get("sprite")
spr(
s:get_start_pix(),
trf:get_x(),
trf:get_y(),
s:get_size_w(),
s:get_size_h(),
s:get_flip_x(),
s:get_flip_y()
)
end
)
end
return render
end
|
--[[
SF coroutine library by Mijyuoon.
]]
--- Coroutine library. Allows for co-operative threading.
-- @shared
local coroutine_lib, _ = SF.Libraries.Register("coroutine")
--- Creates and returns a coroutine thread object from the given function.
-- @class function
-- @param func Function to run inside the coroutine.
-- @return Coroutine object representing the given function.
function coroutine_lib.create(func)
SF.CheckType(func, "function")
return coroutine.create(func)
end
--- Resumes a given coroutine
-- @class function
-- @param coro Coroutine to resume.
-- @param ... Arguments that are passed to coroutine function.
-- @return Arguments that were passed to yield() function.
function coroutine_lib.resume(coro, ...)
SF.CheckType(coro, "thread")
return coroutine.resume(coro, ...)
end
--- Gets the status of a given coroutine. Either 'suspended', 'running' or 'dead'.
-- @class function
-- @param coro Coroutine to check.
-- @return Status of coroutine.
function coroutine_lib.status(coro)
SF.CheckType(coro, "thread")
return coroutine.status(coro)
end
--- Yields active coroutine, halting it in place ready for the next resume.
-- @class function
-- @param ... Arguments to return from coroutine function.
function coroutine_lib.yield(...)
coroutine.yield(...)
end
--- Returns a function that, when run, resumes the coroutine representing the given function.
-- @class function
-- @param func Function to run inside the coroutine.
-- @return Function that resumes the coroutine when run.
function coroutine_lib.wrap(func)
SF.CheckType(func, "function")
return coroutine.wrap(func)
end
|
ITEM.name = "Gas Can"
ITEM.model = "models/props_junk/gascan001a.mdl"
ITEM.width = 1
ITEM.height = 2
ITEM:hook("use", function(item)
item.player:EmitSound("items/battery_pickup.wav")
end)
ITEM.functions._use = {
name = "Use",
tip = "useTip",
icon = "icon16/world.png",
onRun = function(item)
local client = item.player
local data = {}
data.start = client:GetShootPos()
data.endpos = data.start + client:GetAimVector()*96
data.filter = client
local trace = util.TraceLine(data)
local ent = trace.Entity
if (ent and IsValid(ent) and ent.spawnedVehicle) then
local percent = 0
ent:fillGas(300)
percent = (ent:getNetVar("gas") / ent.maxGas)*100
client:notify(L("vehicleGasFilled", client, percent))
return true
else
client:notify(L("vehicleGasLook", client))
end
return false
end,
onCanRun = function(item)
return (!item:getData("spawned"))
end
}
|
require 'torch'
require 'nn'
require 'VanillaRNN'
require 'LSTM'
local utils = require 'util.utils'
local LM, parent = torch.class('nn.LanguageModel', 'nn.Module')
function LM:__init(kwargs)
self.idx_to_token = utils.get_kwarg(kwargs, 'idx_to_token')
self.token_to_idx = {}
self.vocab_size = 0
for idx, token in pairs(self.idx_to_token) do
self.token_to_idx[token] = idx
self.vocab_size = self.vocab_size + 1
end
self.model_type = utils.get_kwarg(kwargs, 'model_type')
self.wordvec_dim = utils.get_kwarg(kwargs, 'wordvec_size')
self.rnn_size = utils.get_kwarg(kwargs, 'rnn_size')
self.num_layers = utils.get_kwarg(kwargs, 'num_layers')
self.dropout = utils.get_kwarg(kwargs, 'dropout')
self.batchnorm = utils.get_kwarg(kwargs, 'batchnorm')
local V, D, H = self.vocab_size, self.wordvec_dim, self.rnn_size
self.net = nn.Sequential()
self.rnns = {}
self.bn_view_in = {}
self.bn_view_out = {}
self.net:add(nn.LookupTable(V, D))
for i = 1, self.num_layers do
local prev_dim = H
if i == 1 then prev_dim = D end
local rnn
if self.model_type == 'rnn' then
rnn = nn.VanillaRNN(prev_dim, H)
elseif self.model_type == 'lstm' then
rnn = nn.LSTM(prev_dim, H)
end
rnn.remember_states = true
table.insert(self.rnns, rnn)
self.net:add(rnn)
if self.batchnorm == 1 then
local view_in = nn.View(1, 1, -1):setNumInputDims(3)
table.insert(self.bn_view_in, view_in)
self.net:add(view_in)
self.net:add(nn.BatchNormalization(H))
local view_out = nn.View(1, -1):setNumInputDims(2)
table.insert(self.bn_view_out, view_out)
self.net:add(view_out)
end
if self.dropout > 0 then
self.net:add(nn.Dropout(self.dropout))
end
end
-- After all the RNNs run, we will have a tensor of shape (N, T, H);
-- we want to apply a 1D temporal convolution to predict scores for each
-- vocab element, giving a tensor of shape (N, T, V). Unfortunately
-- nn.TemporalConvolution is SUPER slow, so instead we will use a pair of
-- views (N, T, H) -> (NT, H) and (NT, V) -> (N, T, V) with a nn.Linear in
-- between. Unfortunately N and T can change on every minibatch, so we need
-- to set them in the forward pass.
self.view1 = nn.View(1, 1, -1):setNumInputDims(3)
self.view2 = nn.View(1, -1):setNumInputDims(2)
self.net:add(self.view1)
self.net:add(nn.Linear(H, V))
self.net:add(self.view2)
end
function LM:updateOutput(input)
local N, T = input:size(1), input:size(2)
self.view1:resetSize(N * T, -1)
self.view2:resetSize(N, T, -1)
for _, view_in in ipairs(self.bn_view_in) do
view_in:resetSize(N * T, -1)
end
for _, view_out in ipairs(self.bn_view_out) do
view_out:resetSize(N, T, -1)
end
return self.net:forward(input)
end
function LM:backward(input, gradOutput, scale)
return self.net:backward(input, gradOutput, scale)
end
function LM:parameters()
return self.net:parameters()
end
function LM:resetStates()
for i, rnn in ipairs(self.rnns) do
rnn:resetStates()
end
end
function LM:encode_string(s)
local encoded = torch.LongTensor(#s)
for i = 1, #s do
local token = s:sub(i, i)
local idx = self.token_to_idx[token]
assert(idx ~= nil, 'Got invalid idx')
encoded[i] = idx
end
return encoded
end
function LM:decode_string(encoded)
assert(torch.isTensor(encoded) and encoded:dim() == 1)
local s = ''
for i = 1, encoded:size(1) do
local idx = encoded[i]
local token = self.idx_to_token[idx]
s = s .. token
end
return s
end
--[[
Sample from the language model. Note that this will reset the states of the
underlying RNNs.
Inputs:
- init: String of length T0
- max_length: Number of characters to sample
Returns:
- sampled: (1, max_length) array of integers, where the first part is init.
--]]
function LM:sample(kwargs)
local T = utils.get_kwarg(kwargs, 'length', 100)
local start_text = utils.get_kwarg(kwargs, 'start_text', '')
local verbose = utils.get_kwarg(kwargs, 'verbose', 0)
local sample = utils.get_kwarg(kwargs, 'sample', 1)
local temperature = utils.get_kwarg(kwargs, 'temperature', 1)
local sampled = torch.LongTensor(1, T)
self:resetStates()
local scores, first_t
if #start_text > 0 then
if verbose > 0 then
print('Seeding with: "' .. start_text .. '"')
end
local x = self:encode_string(start_text):view(1, -1)
local T0 = x:size(2)
sampled[{{}, {1, T0}}]:copy(x)
scores = self:forward(x)[{{}, {T0, T0}}]
first_t = T0 + 1
else
if verbose > 0 then
print('Seeding with uniform probabilities')
end
local w = self.net:get(1).weight
scores = w.new(1, 1, self.vocab_size):fill(1)
first_t = 1
end
for t = first_t, T do
if sample == 0 then
local _, next_char = scores:max(3)
next_char = next_char[{{}, {}, 1}]
else
local probs = torch.div(scores, temperature):double():exp():squeeze()
probs:div(torch.sum(probs))
next_char = torch.multinomial(probs, 1):view(1, 1)
end
sampled[{{}, {t, t}}]:copy(next_char)
scores = self:forward(next_char)
end
self:resetStates()
return self:decode_string(sampled[1])
end
|
--[[ misc_Orbs.lua - Author: HellSpawn
********************************
* *
* The LUA++ Scripting Project *
* *
********************************
This software is provided as free and open source by the
staff of The LUA++ Scripting Project, in accordance with
the AGPL license. This means we provide the software we have
created freely and it has been thoroughly tested to work for
the developers, but NO GUARANTEE is made it will work for you
as well. Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
~~End of License Agreement
-- LUA++ staff, March 26, 2008. ]]
--Falcon Watch lower area to roof--
function Falcon_Orb(pGameObject, Event, pMisc)
pMisc:Teleport(530, -592.200012, 4070.199951, 143.257993)
end
RegisterGameObjectEvent(184501, 2, "Falcon_Orb")
--Falcon Watch Roof to lower area--
function Falconroof_Orb(pGameObject, Event, pMisc)
pMisc:Teleport(530, -588.900024, 4070.800049, 4.724170)
end
RegisterGameObjectEvent(184500, 2, "Falconroof_Orb")
--Duskwither Spire lower area to roof
function Duskwither_Orb(pGameObject, Event, pMisc)
pMisc:Teleport(530, 9330.629883, -7811.870117, 136.569000)
end
RegisterGameObjectEvent(184911, 2, "Duskwither_Orb")
--Duskwither Spire roof to lower area
function Duskwitherroof_Orb(pGameObject, Event, pMisc)
pMisc:Teleport(530, 9334.351563, -7880.743164, 74.910004)
end
RegisterGameObjectEvent(184912, 2, "Duskwitherroof_Orb")
|
local Replication = {}
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local client
local remoteEvent
local remoteFunction
local Ragdoll = require(script.Parent.Ragdoll)
function Replication.OnFired(enabled: boolean, character: Model, motors: Array | nil, pointOfContact: CFrame | nil, randomness: number)
local clientCharacter = client.Character
if not clientCharacter then
return
end
-- We have this check in place, in the case where someone calls :Destroy() or :Disable() when the original character no longer exists and there is a new one.
if clientCharacter ~= character then
return
end
if enabled then
Ragdoll.SetupCharacter(character, pointOfContact, randomness)
else
Ragdoll.ResetCharacter(character, motors)
end
return
end
function Replication.Fire(player: Player, enabled: boolean, character: Model, ...)
if enabled then
remoteFunction:InvokeClient(player, enabled, character, ...)
return Ragdoll.DisableMotors(character)
else
remoteEvent:FireClient(player, enabled, character, ...)
end
end
function Replication:init()
if RunService:IsServer() then
remoteEvent = Instance.new("RemoteEvent")
remoteEvent.Name = "RagdollRemoteEvent"
remoteFunction = Instance.new("RemoteFunction")
remoteFunction.Name = "RagdollRemoteFunction"
remoteEvent.Parent = script
remoteFunction.Parent = script
else
client = Players.LocalPlayer
remoteEvent = script:WaitForChild("RagdollRemoteEvent")
remoteFunction = script:WaitForChild("RagdollRemoteFunction")
remoteEvent.OnClientEvent:Connect(self.OnFired)
remoteFunction.OnClientInvoke = self.OnFired
end
return Replication
end
return Replication:init()
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
rarevehicle6 = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "podracer longtail deed",
directObjectTemplate = "object/tangible/tcg/series3/vehicle_deed_podracer_longtail.iff",
craftingValues = {
},
customizationStringNames = {},
customizationValues = {}
}
addLootItemTemplate("rarevehicle6", rarevehicle6)
|
---@class WeeklyRewards
C_WeeklyRewards = {}
---@return boolean isCurrentPeriod
function C_WeeklyRewards.AreRewardsForCurrentRewardPeriod() end
---@return boolean canClaimRewards
function C_WeeklyRewards.CanClaimRewards() end
---@param id number
function C_WeeklyRewards.ClaimReward(id) end
function C_WeeklyRewards.CloseInteraction() end
---@param type WeeklyRewardChestThresholdType @ [OPTIONAL]
---@overload fun()
---@return WeeklyRewardActivityInfo activities
function C_WeeklyRewards.GetActivities(type) end
---@param type WeeklyRewardChestThresholdType
---@param index number
---@return WeeklyRewardActivityEncounterInfo info
function C_WeeklyRewards.GetActivityEncounterInfo(type, index) end
---@return ConquestWeeklyProgress weeklyProgress
function C_WeeklyRewards.GetConquestWeeklyProgress() end
---@param id number
---@return string, string hyperlink, upgradeHyperlink
function C_WeeklyRewards.GetExampleRewardItemHyperlinks(id) end
---@param itemDBID string
---@return string hyperlink
function C_WeeklyRewards.GetItemHyperlink(itemDBID) end
---@param mythicPlusLevel number
---@return boolean, number|nil, number|nil hasSeasonData, nextMythicPlusLevel, itemLevel
function C_WeeklyRewards.GetNextMythicPlusIncrease(mythicPlusLevel) end
---@return boolean hasAvailableRewards
function C_WeeklyRewards.HasAvailableRewards() end
---@return boolean hasGeneratedRewards
function C_WeeklyRewards.HasGeneratedRewards() end
---@return boolean isInteracting
function C_WeeklyRewards.HasInteraction() end
---@class ConquestProgressBarDisplayType
local ConquestProgressBarDisplayType = {}
ConquestProgressBarDisplayType.FirstChest = 0
ConquestProgressBarDisplayType.AdditionalChest = 1
ConquestProgressBarDisplayType.Seasonal = 2
---@class ConquestWeeklyProgress
---@field progress number
---@field maxProgress number
---@field displayType ConquestProgressBarDisplayType
---@field unlocksCompleted number
---@field maxUnlocks number
---@field sampleItemHyperlink string
local ConquestWeeklyProgress = {}
---@class WeeklyRewardActivityEncounterInfo
---@field encounterID number
---@field bestDifficulty number
---@field uiOrder number
---@field instanceID number
local WeeklyRewardActivityEncounterInfo = {}
---@class WeeklyRewardActivityInfo
---@field type WeeklyRewardChestThresholdType
---@field index number
---@field threshold number
---@field progress number
---@field id number
---@field level number
---@field claimID number|nil
---@field rewards table
local WeeklyRewardActivityInfo = {}
---@class WeeklyRewardActivityRewardInfo
---@field type CachedRewardType
---@field id number
---@field quantity number
---@field itemDBID string|nil
local WeeklyRewardActivityRewardInfo = {}
|
local json = require("JSON")
local filename = "/locker/work/201602-csrx/arch/20160429/pwg/conf-20160429-wgc.js"
local f = assert(io.open(filename, "r"))
local t = f:read("*all")
f:close()
local foo = json:decode([[
{"name" : "lol", "age" : -1.5e6, "foo" : ["bar", true, null]}
]])
print(foo.age) -- -1500000
print(foo.name) -- lol
print(foo.foo[1]) -- bar
print(foo.foo[2]) -- true
print(foo.foo[3]) -- null
print(foo.foo[3] == json.null) -- true
foo.foo = "omg :D"
print(json:encode(foo)) -- {"name":"lol","age":-1500000,"foo":"omg :D"}
local srx = json:decode(t)
|
jog.get_stamina = function(playername)
if jog.players[playername] then
return jog.players[playername].stamina
else
return nil
end
end
jog.set_stamina = function(playername, stamina)
if jog.players[playername] then
jog.players[playername].stamina = stamina
return true
else
return false
end
end
jog.get_max_stamina = function(playername)
if jog.players[playername] then
return jog.players[playername].max_stamina
else
return nil
end
end
jog.set_max_stamina = function(playername, max_stamina)
if jog.players[playername] then
jog.players[playername].max_stamina = max_stamina
return true
else
return false
end
end
|
require "torch"
require "nn"
require "image"
require "optim"
require "model"
require "DataLoader"
local utils = require "utils"
local cmd = torch.CmdLine()
-- Options
cmd:option("-checkpoint", "checkpoints/checkpoint_final.t7")
cmd:option("-split", "", "train, val, or test. leaving blank runs all splits.")
cmd:option("-cuda", 1)
local opt = cmd:parse(arg)
assert(opt.checkpoint ~= "", "Need a trained network file to load.")
assert(opt.split == "" or opt.split == "train" or opt.split == "val" or opt.split == "test")
-- Set up GPU
opt.dtype = "torch.FloatTensor"
if opt.cuda == 1 then
require "cunn"
opt.dtype = "torch.CudaTensor"
end
-- Initialize model and criterion
utils.printTime("Initializing model")
local checkpoint = torch.load(opt.checkpoint)
local model = checkpoint.model
model:type(opt.dtype)
local criterion = nn.ClassNLLCriterion():type(opt.dtype)
-- Initialize DataLoader to receive batch data
utils.printTime("Initializing DataLoader")
local loader = DataLoader(checkpoint.opt)
--[[
Inputs:
- model: a CNN
- split: "train", "val", or "test"
Outputs:
- loss: average loss per item in this split
- accuracy: accuracy on this split
- confusion: an optim.ConfusionMatrix object
Performs image classification using a given nn module.
]]--
function test(model, split)
assert(split == "train" or split == "val" or split == "test")
collectgarbage()
utils.printTime("Starting evaluation on the %s split" % split)
-- Turn off Dropout
model:evaluate()
local confusion = optim.ConfusionMatrix(checkpoint.opt.numClasses)
local evalData = {
predictedLabels = {},
trueLabels = {},
loss = {}
}
local numIterations = math.ceil(loader.splits[split].count / checkpoint.opt.batchSize)
for i = 1, numIterations do
local batch = loader:nextBatch(split, false)
if opt.cuda == 1 then
batch.data = batch.data:cuda()
batch.labels = batch.labels:cuda()
end
local scores = model:forward(batch.data) -- batchSize x numClasses
local _, predictedLabels = torch.max(scores, 2)
table.insert(evalData.predictedLabels, predictedLabels:double())
table.insert(evalData.trueLabels, batch.labels:reshape(batch:size(), 1):double())
local loss = criterion:forward(scores, batch.labels)
table.insert(evalData.loss, loss)
collectgarbage()
end
evalData.predictedLabels = torch.cat(evalData.predictedLabels, 1)
evalData.trueLabels = torch.cat(evalData.trueLabels, 1)
confusion:batchAdd(evalData.predictedLabels, evalData.trueLabels)
local loss = torch.mean(torch.Tensor(evalData.loss))
local accuracy = torch.sum(torch.eq(evalData.predictedLabels, evalData.trueLabels)) / evalData.trueLabels:size()[1]
return loss, accuracy, confusion
end
if opt.split == "" then
for _, split in pairs({"train", "val", "test"}) do
local _, acc, _ = test(model, split)
utils.printTime("Accuracy on the %s split: %f" % {split, acc})
end
else
local _, acc, _ = test(model, opt.split)
utils.printTime("Accuracy on the %s split: %f" % {opt.split, acc})
end
|
minetest.register_node("nc_luxgate:vessicleNull",{
description = "-NULL-",
drawtype = "nodebox",
pointable = false,
diggable = false,
tiles = {"portalhole.png^[makealpha:250,255,201"},
light_source = 4,
walkable = false,
pointable = true,
node_box = {
type = "fixed",
fixed = {
{-0.125, 0, 0.001, 0.125, 0.3125, 0},
}
},
groups = {crumbly = 1, luxg = 1, luxv = 1},
on_construct = function(pos)
local val = luxgate.core.whosthere(pos)
return (val > 0) or minetest.remove_node(pos)
end,
on_destruct = function(pos)
minetest.after(1, function()
if(minetest.get_node(pos).name == "nc_luxgate:vessicle")then
local pos2 = minetest.find_node_near(pos,1,"nc_luxgate:frame_lam",false)
local meta = minetest.get_meta(pos2)
local srcs = {x = pos.x, y = pos.y, z = pos.z, v = luxgate.core.whosthere(pos)}
for n = 1, #luxgate.vests, 1 do
if(minetest.serialize(luxgate.vests[n]) == minetest.serialize(srcs))then
return meta:set_string("gindex",n)
elseif(n == #luxgate.vests and minetest.serialize(luxgate.vests[n]) ~= minetest.serialize(srcs))then
return meta:set_string("gindex",n+1), table.insert(luxgate.vests, srcs)
else end
end
end
end)
end
})
minetest.register_node("nc_luxgate:vessicle",{
description = "-NULL-",
diggable = false,
pointable = false,
drawtype = "nodebox",
tiles = {"portalhole.png^[makealpha:250,255,201"},
light_source = 9,
walkable = false,
node_box = {
type = "fixed",
fixed = {
{-0.125, 0, 0.001, 0.125, 0.3125, 0},
}
},
groups = {crumbly = 1, luxv = 1},
on_construct = function(pos)
luxgate.core.shitpost(pos) -- Register self to table.
end,
})
-- -- -- -- -- -- Frame nodes -- -- -- -- -- --
minetest.register_node("nc_luxgate:frame_ohm",{
description = "Omega Gate Frame",
diggable = false,
pointable = false,
tiles = {"canvas2.png", "ohm_anim.png", "ohm_anim.png", "ohm_anim.png", "ohm_anim.png", "ohm_anim.png"},
groups = {luxg = 1},
})
minetest.register_node("nc_luxgate:frame_lam",{
description = "Lambda Gate Frame",
diggable = false,
tiles = {{name ="lam_anim.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1},
{
type = "sheet_2d",
frames_w = 1,
frames_h = 13,
frame_length = 0.1,
}
}},
groups = { luxg = 1,cracky =1},
on_construct = function(pos)
local node = minetest.get_node(pos).name
minetest.get_meta(pos):set_string("infotext","Node:".. node .. " | ".." Dist; "..0)
end,
on_punch = function(pos, node, puncher)
if(puncher:get_player_control().sneak == false)then
local ves = minetest.find_node_near(pos,4,"nc_luxgate:vessicle",false)
local nves = minetest.find_node_near(pos,4,"nc_luxgate:vessicleNull",false)
if(ves and luxgate.core.holdmycalc(ves) >= 16)then
local meta = minetest.get_meta(ves)
meta:set_int("power",(meta:get_int("power") + luxgate.core.xenithcore(ves)))
elseif(nves and luxgate.core.holdmycalc(nves) >= 10)then
minetest.set_node(nves,{name = "nc_luxgate:vessicle"})
local meta = minetest.get_meta(nves)
meta:set_int("power",luxgate.core.xenithcore(nves) - 10)
else end
elseif(puncher:get_player_control().sneak == true)then
local ves = minetest.find_node_near(pos,4,"nc_luxgate:vessicle",false)
local meta = minetest.get_meta(pos)
meta:set_int("gindex",meta:get_int("gindex") + 1 )
if(meta:get_int("gindex") > #luxgate.vests)then
meta:set_int("gindex",1)
else end
if(type(luxgate.vests[meta:get_int("gindex")]) == "table")then
local ps = luxgate.core.decode(luxgate.vests[meta:get_int("gindex")])[1]
local dpos = {x = ps[1], y = ps[2], z = ps[3]}
local nam;
if(minetest.get_node(dpos).name == "ignore")then
nam = "ignore"
elseif(minetest.get_node(dpos).name == "nc_luxgate:vessicle")then
nam = "vessicle"
elseif(minetest.get_node(dpos).name == "nc_luxgate:vessicleNull")then
nam = "Depl Vessicle"
else nam = "ERROR" end
if(ves)then
meta:set_string("infotext","Node:".. nam .. " | ".." Dist; "..vector.distance(ves,dpos))
--luxgate.log(meta:get_int("gindex"))
else end
else meta:set_string("infotext","Node: REDACTED") end
else end
end
})
minetest.register_node("nc_luxgate:frame_e",{
description = "Gate frame Extension",
drawtype = "nodebox",
paramtype = "light",
diggable = false,
pointable = false,
paramtype2 = "facedir",
groups = { luxg = 1,crumbly = 1},
node_box = {
type = "fixed",
fixed = {
{-0.375, -0.5, -0.375, 0.375, 0.5, 0.375},
}
},
tiles = {"canvas2.png"},
on_punch = function(pos)
luxgate.particles.suffusion(pos)
end
})
minetest.register_node("nc_luxgate:frame_v",{
description = "Gate frame Vane",
diggable = false,
pointable = false,
drawtype = "nodebox",
paramtype = "light",
paramtype2 = "facedir",
groups = { luxg = 1,crumbly = 1},
tiles = {"canvas2.png"},
node_box = {
type = "fixed",
fixed = {
{-0.375, -0.5, -0.375, 0.375, -0.4375, 0.375},
{-0.4375, -0.4375, -0.375, 0.3125, -0.375, 0.375},
{-0.5, -0.375, -0.375, 0.25, -0.3125, 0.375},
{-0.5625, -0.3125, -0.375, 0.1875, -0.25, 0.375},
{-0.625, -0.25, -0.375, 0.125, -0.1875, 0.375},
{-0.6875, -0.1875, -0.375, 0.0625, -0.125, 0.375},
{-0.75, -0.125, -0.375, 0, -0.0625, 0.375},
{-0.8125, -0.0625, -0.375, -0.0625, 0, 0.375},
{-0.875, 0, -0.375, -0.125, 0.0625, 0.375},
{-0.9375, 0.0625, -0.375, -0.1875, 0.125, 0.375},
{-1, 0.125, -0.375, -0.25, 0.1875, 0.375},
{-1.0625, 0.1875, -0.375, -0.3125, 0.25, 0.375},
{-1.125, 0.25, -0.375, -0.375, 0.3125, 0.375},
{-1.1875, 0.3125, -0.375, -0.4375, 0.375, 0.375},
{-1.25, 0.375, -0.375, -0.5, 0.4375, 0.375},
{-1.3125, 0.4375, -0.375, -0.5625, 0.5, 0.375},
}
}
})
minetest.register_node("nc_luxgate:block_ilmenite",{
description = "ilmenite block",
paramtype = "light",
tiles = {"block_ilmenite.png"},
groups = { luxg = 1,crumbly = 1, paramag = 1},
sounds = nodecore.sounds("nc_luxgate_ilmenite2"),
})
minetest.register_node("nc_luxgate:cobble_ilmenite",{
description = "ilmenite block",
paramtype = "light",
tiles = {"block_ilmenite.png^nc_terrain_cobble.png"},
groups = { luxg = 1,crumbly = 1, paramag = 1},
sounds = nodecore.sounds("nc_luxgate_ilmenite2"),
on_punch = function(pos)
luxgate.particles.cyclicAMP(pos,"shard_anim.png",1.2, 4)
end
})
minetest.register_node("nc_luxgate:ulvstone",{
description = "Ulvstone",
tiles = {"canvas2.png"},
groups = { luxg = 1,crumbly = 2, ulv = 1, writable = 1},
sounds = nodecore.sounds("nc_luxgate_ilmenite2"),
})
minetest.register_node("nc_luxgate:ulvstone_i",{
description = "Ulvstone",
pointable = false,
diggable = false,
paramtype = "light",
tiles = {"canvas2t.png"},
groups = { luxg = 1,crumbly = 1, ulv = 1},
sounds = nodecore.sounds("nc_luxgate_ilmenite2"),
})
minetest.register_node("nc_luxgate:ulvstone_c",{
description = "Ulvstone",
pointable = false,
diggable = false,
paramtype = "light",
tiles =
{"canvas2.png",
"canvasvertex2.png",
"canvas2.png",
"canvas2.png",
"canvas2.png",
"canvas2.png",},
paramtype2 = "facedir",
groups = { luxg = 1,crumbly = 1, ulv = 1},
sounds = nodecore.sounds("nc_luxgate_ilmenite2"),
})
minetest.register_node("nc_luxgate:ulvstone_v",{
description = "Ulvstone",
pointable = false,
diggable = false,
paramtype = "light",
tiles = {"canvasvertex.png"},
paramtype2 = "facedir",
groups = { luxg = 1,crumbly = 1, ulv = 1},
sounds = nodecore.sounds("nc_luxgate_ilmenite2"),
})
minetest.register_craftitem("nc_luxgate:shard_ilmenite", {
description = "ilmenite shard",
inventory_image = "shard_ilmenite.png",
wield_image = "shard_ilmenite.png",
wield_scale = {x = 1.25, y = 1.25, z = 1.75},
sounds = nodecore.sounds("nc_luxgate_ilmenite"),
groups = { luxg = 1,paramag = 1}
})
nodecore.register_craft({
label = "macerate ilmenite block to cobble",
action = "pummel",
nodes = {
{match = "nc_luxgate:block_ilmenite", replace = "nc_luxgate:cobble_ilmenite"}
},
toolgroups = { luxg = 1,cracky = 2},
})
nodecore.register_craft({
label = "pound ilmenite cobble into a solid node",
action = "pummel",
nodes = {
{match = "nc_luxgate:cobble_ilmenite", replace = "nc_luxgate:block_ilmenite"}
},
toolgroups = { luxg = 1,thumpy = 3},
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.