content stringlengths 5 1.05M |
|---|
local mod_active = (mods and mods["underground-pipe-pack"]) or (game and game.active_mods["underground-pipe-pack"])
if not mod_active then
return function() end -- mod not enabled, do nothing
end
local variants = {
"one-to-one-forward",
"one-to-two-perpendicular",
"one-to-three-forward",
"one-to-four",
"underground-i",
"underground-L",
"underground-t",
"underground-cross",
}
local tiers = {
{ suffix = "", tech = "advanced-underground-piping" },
{ suffix = "-t2", tech = "advanced-underground-piping-t2" },
{ suffix = "-t3", tech = "advanced-underground-piping-t3" },
{ suffix = "-space", tech = "advanced-underground-piping-space" },
}
local pipe_component_set = {
["pipe"] = true,
["se-space-pipe"] = true,
-- ["swivel-joint"] = true,
-- ["small-pipe-coupler"] = true,
-- ["medium-pipe-coupler"] = true,
-- ["large-pipe-coupler"] = true,
["space-pipe-coupler"] = true,
["underground-pipe-segment-t1"] = true,
["underground-pipe-segment-t2"] = true,
["underground-pipe-segment-t3"] = true,
["underground-pipe-segment-space"] = true,
}
local function is_pipe_component(type, name)
return type == "item" and pipe_component_set[name]
end
local recipe_infos = {}
for _, tier_data in pairs(tiers) do
for _, variant in pairs(variants) do
local name = variant .. tier_data.suffix .. "-pipe"
table.insert(recipe_infos, {
recipe_name = name,
entity_type = "pipe-to-ground",
technology_name = tier_data.tech,
no_percentage_test = is_pipe_component,
})
end
end
table.insert(recipe_infos, {
recipe_name = "4-to-4-pipe",
entity_type = "pipe",
technology_name = "advanced-underground-piping",
no_percentage_test = is_pipe_component,
})
return function(processor_function)
for _, recipe_info in pairs(recipe_infos) do
processor_function(recipe_info)
end
end
|
PlayerInfoMgr = {}
-- ๅๅงๅๅฝๆฐ
function PlayerInfoMgr:Init()
self.PlayerInfoMap = Map:new();
end
function PlayerInfoMgr:GetPlayerInfo( _uid )
return self.PlayerInfoMap:Find(_uid);
end
function PlayerInfoMgr:SetPlayerInfo( _uid, _playerinfo )
if _uid ~= _playerinfo.UID then assert() end;
self.PlayerInfoMap:Insert(_uid, _playerinfo);
end
function PlayerInfoMgr:RemovePlayerInfo( _uid )
self.PlayerInfoMap:Remove(_uid);
end
function PlayerInfoMgr:RemovePLS( pls_sid )
self.PlayerInfoMap:ForEachRemove("PLSID", pls_sid);
end
return PlayerInfoMgr
|
_M={}
local _mt={__index=_M}
function _M.upper(str)
return string.upper( str )
end
return _M |
function bind3(func,arg3)
return function(arg1,arg2)
return func(arg1,arg2,arg3)
end
end
function bind34(func,arg3,arg4)
return function(arg1,arg2)
return func(arg1,arg2,arg3,arg4)
end
end |
--[[
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
]]--
-----------------------------------------
-- Name: ReplicatedTweenService
-- By: cloud_yy
-- Date: Tuesday, July 27 2021
--[[
Description:
A service similar to TweenService but it runs tweens on both server and client, this helps it play nice with systems ran on the server like NPCs or AntiExploit-
while also looking nice and smooth on the client side. This is not a perfect recreation of TweenService but it is good enough.
Documentation:
SERVER
local ReplicatedTweenService = require(ReplicatedTweenService)
Starts ReplicatedTweenService on the server.
local Tween = ReplicatedTweenService.new(Object, Info, Goal)
Tween:Play()
Plays or resumes the tween.
Tween:Pause()
Pauses the tween to be played later.
Tween:Cancel()
Cancels the tween.
Tween:Destroy()
Cleans up/destroys the tween. Should use once a tween is done.
CLIENT
require(ReplicatedTweenService)
Starts Replicated Tweening on the client.
]]--
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local HttpService = game:GetService("HttpService")
local Intents = {New = 1, Sync = 2, Play = 3, Pause = 4, Cancel = 5, Destroy = 6}
local Tweens = {}
local Event
local function InfoToTable(Info)
local Table = {}
Table[1] = Info.Time or 1
Table[2] = Info.EasingStyle or Enum.EasingStyle.Quad
Table[3] = Info.EasingDirection or Enum.EasingDirection.Out
Table[4] = Info.RepeatCount or 0
Table[5] = Info.Reverses or false
Table[6] = Info.DelayTime or 0
return Table
end
local function TableToInfo(Table)
return TweenInfo.new(unpack(Table))
end
local function CreateLocalTween(Id, Object, Info, Goal)
local Tween = TweenService:Create(Object, TableToInfo(Info), Goal)
Tweens[Id] = Tween
end
local ReplicatedTweenService = {}
if RunService:IsServer() then
Event = Instance.new("RemoteEvent",script)
Event.OnServerEvent:Connect(function(Player,Intent)
if Intent == Intents.Sync then
Event:FireClient(Player,Tweens)
end
end)
ReplicatedTweenService.__index = ReplicatedTweenService
function ReplicatedTweenService:Create(Object, Info, Goal)
local self = setmetatable({}, ReplicatedTweenService)
self._id = HttpService:GenerateGUID()
self._tween = TweenService:Create(Object, Info, Goal)
Tweens[self._id] = {Object, InfoToTable(Info), Goal}
Event:FireAllClients(Intents.New, self._id, Object, InfoToTable(Info), Goal)
return self
end
function ReplicatedTweenService:Play()
self._tween:Play()
Event:FireAllClients(Intents.Play, self._id)
end
function ReplicatedTweenService:Pause()
self._tween:Pause()
Event:FireAllClients(Intents.Pause, self._id)
end
function ReplicatedTweenService:Cancel()
self._tween:Cancel()
Event:FireAllClients(Intents.Cancel, self._id)
end
function ReplicatedTweenService:Destroy()
Event:FireAllClients(Intents.Destroy, self._id)
Tweens[self._id] = nil
end
else
Event = script:WaitForChild("RemoteEvent")
Event.OnClientEvent:Connect(function(Intent,...)
local Args = {...}
if Intent == Intents.New then
CreateLocalTween(...)
elseif Intent == Intents.Sync then
for Id,Tween in pairs(Args[1]) do
CreateLocalTween(Id,Tween[1],Tween[2],Tween[3])
end
elseif Intent == Intents.Play then
local Tween = Tweens[Args[1]]
if Tween then
Tween:Play()
end
elseif Intent == Intents.Pause then
local Tween = Tweens[Args[1]]
if Tween then
Tween:Pause()
end
elseif Intent == Intents.Cancel then
local Tween = Tweens[Args[1]]
if Tween then
Tween:Cancel()
end
elseif Intent == Intent.Destroy then
if Tweens[Args[1]] then
Tweens[Args[1]] = nil
end
end
end)
Event:FireServer(Intents.Sync)
end
return ReplicatedTweenService
-- ReplicatedTweenService
-- ยฉ 2021 cloud_yy
|
return function()
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local lib = ReplicatedStorage.lib
local Llama = require(lib.Llama)
local List = Llama.List
local removeValue = List.removeValue
it("should return a new table", function()
local a = {
"cool",
}
local b = removeValue(a, "cool")
expect(b).never.to.equal(a)
expect(b).to.be.a("table")
end)
it("should remove a single value", function()
local a = {
"cool",
"cooler",
"coolest",
"coolest",
}
local b = removeValue(a, "coolest")
expect(#b).to.equal(2)
expect(b[1]).to.equal("cool")
expect(b[2]).to.equal("cooler")
end)
it("should remove multiple values", function()
local a = {
"cool",
"cooler",
"coolest",
"something",
}
local b = removeValue(a, "coolest", "something")
expect(#b).to.equal(2)
expect(b[1]).to.equal("cool")
expect(b[2]).to.equal("cooler")
end)
it("should work even if value does not exist", function()
local a = {
"cool",
"coolor",
}
expect(function()
removeValue(a, "mutability")
end).never.to.throw()
end)
end |
local Escher = require "escher"
local EscherFactory = require "kong.plugins.escher.escher_factory"
describe("escher factory", function()
describe("#create", function()
it("should create a new Escher instance with default parameters", function()
local escher = Escher({
debugInfo = true,
vendorKey = "EMS",
algoPrefix = "EMS",
hashAlgo = "SHA256",
credentialScope = "eu/suite/ems_request",
authHeaderName = "X-Ems-Auth",
dateHeaderName = "X-Ems-Date"
})
assert.are.same(EscherFactory.create(), escher)
end)
end)
end) |
--BRAINWASH the fortress. For when that one lost sheep haunts their thoughts FOREVER.
function brainwashfortress()
--readapted From siren.lua on April 7 2015
function add_thought(unit, emotion, thought)
unit.status.current_soul.personality.emotions:resize(0)
unit.status.current_soul.personality.emotions:insert('#', { new = true, type = emotion, unk2=1, strength=1, thought=thought, subthought=0, severity=0, flags=0, unk7=0, year=df.global.cur_year, year_tick=df.global.cur_year_tick})
unit.status.happiness = 4000
end
--readapted From siren.lua and conscript.lua on April 7 2015
for unitCount,unit in ipairs(df.global.world.units.active) do
if not (unit.flags1.dead == true) then
if unit.civ_id == df.global.ui.civ_id then
add_thought(unit, df.emotion_type.Relief, df.unit_thought_type.Rescued)
print(dfhack.TranslateName(dfhack.units.getVisibleName(unit)))
end
end
end
end
brainwashfortress()
|
--- Provides a collection of basic color names and their RGB values.
-- Plus a function for creating new color objects.
--
-- Colorswatches provides a collection of RGB values keyed by color name.
-- Specialized collections of color names are provided as submodules.
--
-- @module colorswatches
-- @author Matthew M. Burke
-- @copyright 2005-2014
-- @license MIT (see LICENSE file)
--
local colors_mt = {}
local color_mt = {}
colors_mt.__index = colors_mt
color_mt.__index = color_mt
local colors = {}
setmetatable(colors, colors_mt)
--- Creates a new color object. This object
-- has fields *name*, *r*, *g*, and *b*.
-- @function new
-- @tparam string n name of the color
-- @tparam int r red value of the color (0-255)
-- @tparam int g green value of the color (0-255)
-- @tparam int b blue value of the color (0-255)
-- @treturn Color a table representing the color.
colors_mt.new = function(n, r, g, b)
local color = { name = n, r = r, g = g, b = b }
setmetatable(color, color_mt)
return color
end
--- @type Color
--- Returns a string representation of the color including both its name and
-- its RGB values.
-- @function __tostring
-- @treturn string the string representation of the color.
color_mt.__tostring = function(s)
return string.format("color('%s', %d, %d, %d)", s.name, s.r, s.g, s.b)
end
--- Returns the RGB values of the color. They are returned as three separate values.
-- @function rgb
-- @treturn int red value (0-255)
-- @treturn int green (0-255)
-- @treturn int blue (0-255)
color_mt.rgb = function(s)
return s.r, s.g, s.b
end
-- convenience method to define a color and store
-- it in the colors table
local color = function(n, r, g, b)
local c = colors_mt.new(n, r, g, b)
colors[c.name] = c
end
color('white', 255, 255, 255)
color('black', 0, 0, 0)
color('red', 255, 0, 0)
color('green', 0, 255, 0)
color('blue', 0, 0, 255)
color('yellow', 255, 255, 0)
color('cyan', 0, 255, 255)
color('magenta', 255, 0, 255)
return colors
|
local Lustache = require "lustache"
return {
id = function (what)
return Lustache:render ("ardoises:id:{{{what}}}", { what = what })
end,
lock = function (what)
return Lustache:render ("ardoises:lock:{{{what}}}", { what = what })
end,
user = function (user)
return Lustache:render ("ardoises:user:{{{login}}}", user)
end,
repository = function (repository)
return Lustache:render ("ardoises:repository:{{{owner.login}}}/{{{name}}}", repository)
end,
collaborator = function (repository, collaborator)
return Lustache:render ("ardoises:collaborator:{{{repository.owner.login}}}/{{{repository.name}}}/{{{collaborator.login}}}", {
repository = repository,
collaborator = collaborator,
})
end,
editor = function (repository, branch)
return Lustache:render ("ardoises:editor:{{{repository.owner.login}}}/{{{repository.name}}}/{{{branch}}}", {
repository = repository,
branch = branch,
})
end,
tool = function (owner, tool)
return Lustache:render ("ardoises:tool:{{{owner.login}}}/{{{tool.id}}}", {
owner = owner,
tool = tool,
})
end,
}
|
-- GAMESHELL KEYMAP --
-- See here: https://github.com/clockworkpi/Keypad/blob/master/keymaps.png
local keys = {}
-- A, B, X, Y
keys.Y = 'i'
keys.X = 'u'
keys.A = 'j'
keys.B = 'k'
-- D-Pad
keys.DPad_up = 'up'
keys.DPad_down = 'down'
keys.DPad_right = 'right'
keys.DPad_left = 'left'
-- Special Keys
keys.Start = 'return'
keys.Select = 'space'
keys.Volume_down = 'kp-'
keys.Volume_up = 'kp+'
-- Menu
keys.Menu = 'escape'
-- Lightkey
keys.LK1 = 'h'
keys.LK2 = 'y'
--keys.LK3 = keys.lk3 = '' <-- Not usable, is shift
keys.LK4 = 'o'
keys.LK5 = 'l'
keys.LK1_shift = 'home'
keys.LK2_shift = 'pageup'
--keys.LK3_shift = lk3_shift = '' <-- Still not usable...
keys.LK4_shift = 'pagedown'
keys.LK5_shift = 'end'
return keys |
data:extend(
{
{
type = "item",
name = "sodium-hydroxide",
icon = "__Engineersvsenvironmentalist__/graphics/icons/chemicals/sodium-hydroxide.png",
flags = {"goes-to-main-inventory"},
subgroup = "aluminium-processing",
order = "f[sodium-hydroxide]",
stack_size = 1000
},
}
) |
local UIMain = Class(UIPanel)
function UIMain:Awake()
self.super.Awake(self)
Log.Trace("UIMain Awake")
self.title.text = "asdfasd"
self.btn.onClick:AddListener(function()
UIPanelManager.OpenUI(UIPanelDef.MessageBox, {
Title = "ๅ
ๅผ",
Content = "ๅ
ๅผ648ๅคง็คผๅ
",
LeftBtn = {
Title = "็กฎ่ฎค",
Callback = function()
Log.Info("ๅ
ๅผๆๅ")
end
},
RightBtn = {
Title = "ๅๆถ",
Callback = function()
Log.Info("ๅ
ๅผๅๆถ")
end
}
})
end)
end
function UIMain:OnViewShow()
self.vListView:RegisterItemUpdate(function(item, index, lifeCycle)
item.elements.text.text = "item_" ..tostring(index)
-- local height = self.vListView:GetItemRowHeight(index)
-- item.transform:SetSizeHeight(height)
end)
-- self.vListView:RegisterItemRowHeight(function(item, index)
-- return 100 + index * 30
-- end)
self.vListView:SetNum(30)
self.vListView:ReloadAll();
self.vListView:ScrollToIndex(8, 0.5)
self.hListView:RegisterItemUpdate(function(item, index, lifeCycle)
item.elements.text.text = "item_" ..tostring(index)
-- local height = self.hListView:GetItemRowHeight(index)
-- item.transform:SetSizeWidth(height)
end)
-- self.hListView:RegisterItemRowHeight(function(item, index)
-- return 100 + index * 30
-- end)
self.hListView:SetNum(30)
self.hListView:ReloadAll();
self.hListView:ScrollToIndex(8, 0.5)
end
return UIMain |
--************************
--name : SINGLE_DEL_TT_02.lua
--ver : 0.1
--author : Kintama
--date : 2004/09/09
--lang : en
--desc : terminal mission
--npc :
--************************
--changelog:
--2004/09/09(0.1): Added description
--************************
function DIALOG()
NODE(0)
GENDERCHECK()
if (result==1) then
SAY("Runner, do you need something?")
SAY("How may I help you, Runner?")
SAY("Do you need help Runner?")
SAY("Yes sir, Do you have a dilemma?")
SAY("Welcome sir, please ask if you have any questions.")
else
SAY("Yes Runner, how can Tangent help you?")
SAY("Welcome Runner, how can I help you?")
SAY("Yes Runner? How can I be of assistance to you?")
SAY("Ma'am, do you require something?")
SAY("Yes ma'am? How can I help you in your endeavours?")
end
ANSWER("I had a good look through the job Term and you have a delivery job to be done it seems.",1)
ANSWER("Your company has a delivery job that needs to be done, right? Then I am the right person for you.",1)
ANSWER("I am rather interested in your delivery job.",1)
ANSWER("Tangent? I am sorry but I am not into this.",3)
ANSWER("Oh, yes, and goodbye...",3)
NODE(1)
GIVEQUESTITEM(91)
SAY("A research lab of ours has run short on vital weapon parts and is expecting the delivery today. Meet %NPC_NAME(1) at %NPC_WORLD(1) and return once you delivered the parts.")
SAY("Our office at %NPC_WORLD(1) have some important reports to complete and need these specifications as fast as possible. You can meet Mr. %NPC_NAME(1) there, he will take it from there. Return afterwards.")
SAY("These parts are for the failsafe devices in our newest developments. Recent lab damage due to the lack of any failsafes have urged %NPC_NAME(1) to install them quickly. You can meet him at %NPC_WORLD(1).")
SAY("The communication to the Tangent outpost has been disrupted and we need somebody to deliver some vital circuits to %NPC_NAME(1) at %NPC_WORLD(1). That should fix the problem. After that, return to me for your reward.")
ACTIVATEDIALOGTRIGGER(0)
SETNEXTDIALOGSTATE(2)
ENDDIALOG()
NODE(2)
ISMISSIONTARGETACCOMPLISHED(1)
if (result==0) then
SAY("Ahh, I am sorry, but we would be pleased if you would just complete your assignment.")
SAY("Tangent Industries would appreciate it if you just completed the delivery.")
SAY("Are you confused about your mission goals? If not, just continue with your delivery.")
SAY("Please return once you completed your assignment.")
ENDDIALOG()
else
SAY("Well done, Runner. As promised you shall be provided with %REWARD_MONEY() credits as payment for your services.")
SAY("The package has been delivered without any major delay. The promised %REWARD_MONEY() credits have been transferred to your account.")
SAY("We were anticipating your return. Congratulations, thanks to your help there is one less problem for us to deal with. Here is your payment of %REWARD_MONEY() credits.")
SAY("We are content with your services. We hope you will enjoy your reward. Oh, and here are your %REWARD_MONEY() credits payment.")
SAY("Tangent Industries is very pleased with your services. I was permitted to hand out %REWARD_MONEY() credits as a reward.")
SAY("Your delivery job has been completed successfully as I see from our company screens. Please feel free to visit us again, here are your %REWARD_MONEY() credits of payment.") ACTIVATEDIALOGTRIGGER(2)
ACTIVATEDIALOGTRIGGER(2)
ENDDIALOG()
end
NODE(3)
TAKEQUESTITEM(91)
if (result==0) then
SAY("What about our agreement? If you are still interested in the reward, I suggest you complete the assignment.")
SAY("Tangent Industries is not pleased with how you are handling the delivery, please get the package for me immediately.")
SAY("The package is of great interest to us. Come back when you have it.")
SAY("Please do not come back unless you have the package.")
ENDDIALOG()
else
SAY("Tangent is in your debt. Please visit %NPC_NAME(0) and ask him about your reward. Your services have been greatly appreciated.")
SAY("Ahh, the package, finally. Thank you, I am sure you will be pleased with the reward that %NPC_NAME(0)will hand over to you.")
SAY("Please do the delivery a tad faster next time. Thank you, anyway. Please see %NPC_NAME(0) for your payment.")
SAY("Mr %NPC_NAME(0) will have your reward presently if you return to him. I am pleased with your service.")
SAY("Your services have been somewhat disappointing due to your lack of dedication but I am sure %NPC_NAME(0) will still want to pay you.")
ACTIVATEDIALOGTRIGGER(1)
SETNEXTDIALOGSTATE(5)
ENDDIALOG()
end
NODE(4)
SAY("Please feel free to visit Tangent again.")
SAY("Do not forget to visit the job Term if you are interested.")
SAY("Goodbye, citizen.")
ENDDIALOG()
NODE(5)
SAY("What the hell do you want here? I got the packet, now go back to %NPC_NAME(0) to recieve your reward")
SAY("Thanks for delivering this package. Go back to %NPC_NAME(0) to recieve your reward.")
ENDDIALOG()
end |
function quaternion_multiply(x1,y1,z1,w1, x2,y2,z2,w2)
return
w1*x2 + x1*w2 + y1*z2 - z1*y2,
w1*y2 - x1*z2 + y1*w2 + z1*x2,
w1*z2 + x1*y2 - y1*x2 + z1*w2,
w1*w2 - x1*x2 - y1*y2 - z1*z2
--[[
local A = (w1 + x1) * (w2 + x2)
local B = (z1 - y1) * (y2 - z2)
local C = (x1 - w1) * (y2 + z2)
local D = (y1 + z1) * (x2 - w2)
local E = (x1 + z1) * (x2 + y2)
local F = (x1 - z1) * (x2 - y2)
local G = (w1 + y1) * (w2 - z2)
local H = (w1 - y1) * (w2 + z2)
local w = B + ( -E - F + G + H ) * 0.5
local x = A - ( E + F + G + H ) * 0.5
local y = -C + ( E - F + G - H ) * 0.5
local z = -D + ( E - F - G + H ) * 0.5
return x,y,z,w
]]
end
function quaternion_to_xyz( x, y, z, w )
return math.deg( math.atan2( 2 * ( y*w - x*z ), 1 - 2*y*y - 2*z*z ) ),
math.deg( math.asin( 2 * ( x*y + z*w ) ) ),
math.deg( math.atan2( 2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z ) )
end
local function cos_sin_half_angle( a )
local h = math.rad(a) * 0.5
return math.cos(h), math.sin(h)
end
function quaternion_from_angle( a, x, y, z )
local h = math.rad( a * 0.5 )
local cos = math.cos( h )
local sin = math.sin( h )
return sin * x, sin * y, sin * z, cos
end
function quaternion_from_angle_z( a, l )
return quaternion_from_angle( a, 0, 0, l or 1 )
end
function quaternion_from_angle_y( a, l )
return quaternion_from_angle( a, 0, l or 1, 0 )
end
function quaternion_from_angle_x( a, l )
return quaternion_from_angle( a, l or 1, 0, 0 )
end
function quaternion_from_xyz( x, y, z )
local c1 = math.cos(math.rad(x / 2))
local c2 = math.cos(math.rad(y / 2))
local c3 = math.cos(math.rad(z / 2))
local s1 = math.sin(math.rad(x / 2))
local s2 = math.sin(math.rad(y / 2))
local s3 = math.sin(math.rad(z / 2))
return
(s1 * s2 * c3) + (c1 * c2 * s3),
(s1 * c2 * c3) + (c1 * s2 * s3),
(c1 * s2 * c3) - (s1 * c2 * s3),
(c1 * c2 * c3) - (s1 * s2 * s3)
--[[
local cos_x, sin_x = cos_sin_half_angle( x )
local cos_y, sin_y = cos_sin_half_angle( y )
local cos_z, sin_z = cos_sin_half_angle( z )
local cos_x_cos_y = cos_x * cos_y
local sin_x_sin_y = sin_x * sin_y
local sin_x_cos_y = sin_x * cos_y
local cos_x_sin_y = cos_x * sin_y
local qw = cos_x_cos_y * cos_z - sin_x_sin_y * sin_z
local qx = sin_x_sin_y * cos_z + cos_x_cos_y * sin_z
local qy = sin_x_cos_y * cos_z + cos_x_sin_y * sin_z
local qz = cos_x_sin_y * cos_z - sin_x_cos_y * sin_z
return qx, qy, qz, qw
]]
end
function quaternion_conjugate( x, y, z, w )
return -x, -y, -z, w
end
function quaternion_normalize_sqrt( x, y, z, w )
local norm = 1 / ( x*x + y*y + z*z + w*w )
return x * norm, y * norm, z * norm, w * norm
end
function quaternion_normalize( x, y, z, w )
local norm = 1 / math.sqrt( x*x + y*y + z*z + w*w )
return x * norm, y * norm, z * norm, w * norm
end
function quaternion_inverse( x, y, z, w )
return quaternion_normalize_sqrt( quaternion_conjugate( x,y,z,w ) )
end
function quaternion_transform( x, y, z, w, vx, vy, vz )
local qx, qy, qz, qw = quaternion_multiply( x,y,z,w, vx,vy,vz,0 )
return quaternion_multiply( qx,qy,qz,qw, quaternion_inverse( x,y,z,w ) )
end
|
---
-- The 'DisplayObject' class is the base class for all objects that can
-- be placed on the screen.
--
-- @module DisplayObject
local M = Class(EventDispatcher)
---
-- Creates a new display object.
--
-- @function [parent=#DisplayObject] new
-- @param width (number) The width of the display object in pixels.
-- @param height (number) The height of the display object in pixels.
-- @return #DisplayObject
function M:init(width, height)
self.super:init()
self.parent = nil
self.children = {}
self.object = Object.new()
self.object:setSize(width or 0, height or 0)
end
---
-- Determines whether the specified display object is contained in the subtree of
-- this 'DisplayObject' instance.
--
-- @function [parent=#DisplayObject] contains
-- @param self
-- @param child (DisplayObject) The child object to test.
-- @return 'true' if the child object is contained in the subtree of this 'DisplayObject'
-- instance, otherwise 'false'.
function M:contains(child)
for i, v in ipairs(self.children) do
if v == child then
return true
end
end
return false
end
---
-- Returns the display object that contains this display object.
--
-- @function [parent=#DisplayObject] getParent
-- @param self
-- @return The parent display object.
function M:getParent()
return self.parent
end
---
-- Adds a display object as a child to this display object. The child
-- is added as a last child of this 'DisplayObject' instance.
--
-- Display object can have only one parent. Therefore if you add a child
-- object that already has a different display object as a parent, the
-- display object is removed from the child list of the other display
-- object and then added to this display object.
--
-- @function [parent=#DisplayObject] addChild
-- @param self
-- @param child (DisplayObject) The child display object to add.
-- @return A value of 'true' or 'false'.
function M:addChild(child)
if child == nil or self == child then
return false
end
if child.parent == self then
return false
end
child:removeSelf()
table.insert(self.children, child)
child.parent = self
return true
end
---
-- Removes the specified child 'DisplayObject' instance from the child list
-- of this 'DisplayObject' instance.
--
-- @function [parent=#DisplayObject] removeChild
-- @param self
-- @param child (DisplayObject) The child display object to remove.
-- @return A value of 'true' or 'false'.
function M:removeChild(child)
if child == nil or self == child then
return false
end
local index = 0
for i, v in ipairs(self.children) do
if v == child then
index = i
break
end
end
if index <= 0 then
return false
end
table.remove(self.children, index)
child.parent = nil
return true
end
---
-- If the display object has a parent, removes the display object from the
-- child list of its parent display object.
--
-- @function [parent=#DisplayObject] removeSelf
-- @param self
-- @return A value of 'true' or 'false'.
function M:removeSelf()
local parent = self.parent
if parent == nil then
return false
end
return parent:removeChild(self)
end
---
-- Moves the display object to the visual front of its parent.
--
-- @function [parent=#DisplayObject] toFront
-- @param self
-- @return A value of 'true' or 'false'.
function M:toFront()
local parent = self.parent
if parent == nil then
return false
end
if not parent:removeChild(self) then
return false
end
table.insert(parent.children, self)
self.parent = parent
return true
end
---
-- Moves the display object to the visual back of its parent.
--
-- @function [parent=#DisplayObject] toBack
-- @param self
-- @return A value of 'true' or 'false'.
function M:toBack()
local parent = self.parent
if parent == nil then
return false
end
if not parent:removeChild(self) then
return false
end
table.insert(parent.children, 1, self)
self.parent = parent
return true
end
---
-- Sets the width and height of the display object in pixels. (Inner, No transform matrix)
--
-- @function [parent=#DisplayObject] setSize
-- @param self
-- @param width (number) The width of the display object.
-- @param height (number) The height of the display object.
function M:setSize(width, height)
self.object:setSize(width, height)
return self
end
---
-- Returns the width and height of the display object in pixels. (Inner, No transform matrix)
--
-- @function [parent=#DisplayObject] getSize
-- @param self
-- @return The width and height of the display object.
function M:getSize()
return self.object:getSize()
end
---
-- Sets the x coordinates of the display object.
--
-- @function [parent=#DisplayObject] setX
-- @param self
-- @param x (number) The new x coordinate of the display object.
function M:setX(x)
self.object:setX(x)
return self
end
---
-- Returns the x coordinate of the display object.
--
-- @function [parent=#DisplayObject] getX
-- @param self
-- @return The x coordinate of the display object.
function M:getX()
return self.object:getX()
end
---
-- Sets the y coordinates of the display object.
--
-- @function [parent=#DisplayObject] setY
-- @param self
-- @param y (number) The new y coordinate of the display object.
function M:setY(y)
self.object:setY(y)
return self
end
---
-- Returns the y coordinate of the display object.
--
-- @function [parent=#DisplayObject] getY
-- @param self
-- @return The y coordinate of the display object.
function M:getY()
return self.object:getY()
end
---
-- Sets the x and y coordinates of the display object.
--
-- @function [parent=#DisplayObject] setPosition
-- @param self
-- @param x (number) The new x coordinate of the display object.
-- @param y (number) The new y coordinate of the display object.
function M:setPosition(x, y)
self.object:setPosition(x, y)
return self
end
---
-- Returns the x and y coordinates of the display object.
--
-- @function [parent=#DisplayObject] getPosition
-- @param self
-- @return The x and y coordinates of the display object.
function M:getPosition()
return self.object:getPosition()
end
---
-- Sets the rotation of the display object in degrees.
--
-- @function [parent=#DisplayObject] setRotation
-- @param self
-- @param rotation (number) rotation of the display object
function M:setRotation(rotation)
self.object:setRotation(rotation)
return self
end
---
-- Returns the rotation of the display object in degrees.
--
-- @function [parent=#DisplayObject] getRotation
-- @param self
-- @return Rotation of the display object.
function M:getRotation()
return self.object:getRotation()
end
---
-- Sets the horizontal scale of the display object.
--
-- @function [parent=#DisplayObject] setScaleX
-- @param self
-- @param x (number) horizontal scale of the display object
function M:setScaleX(x)
self.object:setScaleX(x)
return self
end
---
-- Returns the horizontal scale of the display object.
--
-- @function [parent=#DisplayObject] getScaleX
-- @param self
-- @return The horizontal scale (percentage) of the display object.
function M:getScaleX()
return self.object:getScaleX()
end
---
-- Sets the vertical scale of the display object.
--
-- @function [parent=#DisplayObject] setScaleY
-- @param self
-- @param y (number) vertical scale of the display object
function M:setScaleY(y)
self.object:setScaleY(y)
return self
end
---
-- Returns the vertical scale of the display object.
--
-- @function [parent=#DisplayObject] getScaleY
-- @param self
-- @return The vertical scale of the display object.
function M:getScaleY()
return self.object:getScaleY()
end
---
-- Sets the horizontal and vertical scales of the display object.
--
-- @function [parent=#DisplayObject] setScale
-- @param self
-- @param x (number) horizontal scale (percentage) of the display object
-- @param y (number) vertical scale (percentage) of the display object
function M:setScale(x, y)
self.object:setScale(x, y or x)
return self
end
---
-- Returns the horizontal and vertical scales of the display object.
--
-- @function [parent=#DisplayObject] getScale
-- @param self
-- @return The horizontal and vertical scales of the display object
function M:getScale()
return self.object:getScale()
end
---
-- Sets the anchor point of the display object in percentage.
--
-- @function [parent=#DisplayObject] setAnchor
-- @param self
-- @param x (number) The horizontal percentage of anchor point.
-- @param y (number) The vertical percentage of anchor point.
function M:setAnchor(x, y)
self.object:setAnchor(x, y or x)
return self
end
---
-- Returns the anchor point of the display object in percentage.
--
-- @function [parent=#DisplayObject] getAnchor
-- @param self
-- @return The anchor point of the display object in percentage.
function M:getAnchor()
return self.object:getAnchor()
end
---
-- Sets the alpha transparency of this display object. 0 means fully transparent and 1 means fully opaque.
--
-- @function [parent=#DisplayObject] setAlpha
-- @param self
-- @param alpha (number) The new alpha transparency of the display object
function M:setAlpha(alpha)
self.object:setAlpha(alpha)
return self
end
---
-- Returns the alpha transparency of this display object.
--
-- @function [parent=#DisplayObject] getAlpha
-- @param self
-- @return The alpha of the display object
function M:getAlpha()
return self.object:getAlpha()
end
---
-- Sets the alignment of this display object.
--
-- @function [parent=#DisplayObject] setAlignment
-- @param self
-- @param align the alignment of display object
function M:setAlignment(align)
self.object:setAlignment(align)
return self
end
---
-- Returns the alignment of this display object.
--
-- @function [parent=#DisplayObject] getAlignment
-- @param self
-- @return the alignment of display object
function M:getAlignment()
return self.object:getAlignment()
end
---
-- Sets whether or not the display object is visible. Display objects that are not visible are also taken
-- into consideration while calculating bounds.
--
-- @function [parent=#DisplayObject] setVisible
-- @param self
-- @param visible (bool) whether or not the display object is visible
function M:setVisible(visible)
self.object:setVisible(visible)
return self
end
---
-- Returns whether or not the display object is visible.
--
-- @function [parent=#DisplayObject] getVisible
-- @param self
-- @return A value of 'true' if display object is visible; 'false' otherwise.
function M:getVisible()
return self.object:getVisible()
end
---
-- Sets whether or not the display object is touchable.
--
-- @function [parent=#DisplayObject] setTouchable
-- @param self
-- @param touchable (bool) whether or not the display object is touchable
function M:setTouchable(touchable)
self.object:setTouchable(touchable)
return self
end
---
-- Returns whether or not the display object is touchable.
--
-- @function [parent=#DisplayObject] getTouchable
-- @param self
-- @return A value of 'true' if display object is touchable; 'false' otherwise.
function M:getTouchable()
return self.object:getTouchable()
end
---
-- Update cache matrix that represents the transformation from the local coordinate system to another.
--
-- @function [parent=#DisplayObject] updateTransformMatrix
-- @param self
-- @param target (optional) The destination space of the transformation, nil for the screen space.
function M:updateTransformMatrix(target)
local o = self.parent
self.object:initTransormMatrix()
while(o and o ~= target) do
self.object:upateTransformMatrix(o.object)
o = o.parent
end
return self
end
---
-- Return a matrix that represents the transformation from the local coordinate system to another.
--
-- @function [parent=#DisplayObject] getTransformMatrix
-- @param self
-- @param target (optional) The destination space of the transformation, nil for the screen space.
-- @return The transformation matrix of the display object to another
function M:getTransformMatrix(target)
self:updateTransformMatrix(target)
return self.object:getTransformMatrix()
end
---
-- Converts the x,y coordinates from the global to the display object's (local) coordinates.
--
-- @function [parent=#DisplayObject] globalToLocal
-- @param self
-- @param x (number) x coordinate of the global coordinate.
-- @param y (number) y coordinate of the global coordinate.
-- @param target (optional) The destination space of the transformation, nil for the screen space.
-- @return x coordinate relative to the display object.
-- @return y coordinate relative to the display object.
function M:globalToLocal(x, y, target)
self:updateTransformMatrix(target)
return self.object:globalToLocal(x, y)
end
---
-- Converts the x,y coordinates from the display object's (local) coordinates to the global coordinates.
--
-- @function [parent=#DisplayObject] localToGlobal
-- @param self
-- @param x (number) x coordinate of the local coordinate.
-- @param y (number) y coordinate of the local coordinate.
-- @param target (optional) The destination space of the transformation, nil for the screen space.
-- @return x coordinate relative to the display area.
-- @return y coordinate relative to the display area.
function M:localToGlobal(x, y, target)
self:updateTransformMatrix(target)
return self.object:localToGlobal(x, y)
end
---
-- Checks whether the given coordinates (in global coordinate system) is in bounds of the display object.
--
-- @function [parent=#DisplayObject] hitTestPoint
-- @param self
-- @param x (number)
-- @param y (number)
-- @param target (DisplayObject) The display object that defines the other coordinate system to transform
-- @return 'true' if the given global coordinates are in bounds of the display object, 'false' otherwise.
function M:hitTestPoint(x, y, target)
if self:getVisible() and self:getTouchable() then
self:updateTransformMatrix(target)
return self.object:hitTestPoint(x, y)
else
return false
end
end
---
-- Returns a area (as x, y, w and h) that encloses the display object as
-- it appears in another display objectโs coordinate system.
--
-- @function [parent=#DisplayObject] getBounds
-- @param self
-- @param target (DisplayObject) The display object that defines the other coordinate system to transform
-- @return area has 4 values as x, y, w and h of bounds
function M:getBounds(target)
self:updateTransformMatrix(target)
return self.object:bounds()
end
---
-- Perform a custom animation of a set of display object properties.
--
-- @function [parent=#DisplayObject] animate
-- @param self
-- @param properties (table) The properties values that the animation will move toward. ['x' 'y' 'rotation' 'scalex' 'scaley' 'alpha']
-- @param duration (number) Determining how long the animation will run in seconds.
-- @param easing (#Easing) The string indicating which easing function to use for transition.
-- The following easing functions can be used:
-- "linear"
-- "inSine" "outSine" "inOutSine"
-- "inQuad" "outQuad" "inOutQuad"
-- "inCubic" "outCubic" "inOutCubic"
-- "inQuart" "outQuart" "inOutQuart"
-- "inQuint" "outQuint" "inOutQuint"
-- "inExpo" "outExpo" "inOutExpo"
-- "inCirc" "outCirc" "inOutCirc"
-- "inBack" "outBack" "inOutBack"
-- "inElastic" "outElastic" "inOutElastic"
-- "inBounce" "outBounce" "inOutBounce"
function M:animate(properties, duration, easing)
local function __animate_listener(d, e)
if d.__animate ~= true then
d:removeEventListener(Event.ENTER_FRAME, __animate_listener, d)
d.__duration = nil
d.__tween = nil
d.__watch = nil
d.__animate = nil
return
end
local elapsed = d.__watch:elapsed()
if elapsed > d.__duration then
elapsed = d.__duration
end
for k, v in pairs(d.__tween) do
if k == "x" then
d:setX(v:easing(elapsed))
elseif k == "y" then
d:setY(v:easing(elapsed))
elseif k == "rotation" then
d:setRotation(v:easing(elapsed))
elseif k == "scalex" then
d:setScaleX(v:easing(elapsed))
elseif k == "scaley" then
d:setScaleY(v:easing(elapsed))
elseif k == "alpha" then
d:setAlpha(v:easing(elapsed))
end
end
if elapsed >= d.__duration then
d:removeEventListener(Event.ENTER_FRAME, __animate_listener, d)
self:dispatchEvent(Event.new(Event.ANIMATE_COMPLETE))
d.__duration = nil
d.__tween = nil
d.__watch = nil
d.__animate = nil
end
end
if self.__animate == true then
self:removeEventListener(Event.ENTER_FRAME, __animate_listener, self)
self:dispatchEvent(Event.new(Event.ANIMATE_COMPLETE))
self.__duration = nil
self.__tween = nil
self.__watch = nil
self.__animate = nil
end
if not properties or type(properties) ~= "table" or not next(properties) then
return self
end
if duration and duration <= 0 then
return self
end
self.__duration = duration or 1
self.__tween = {}
for k, v in pairs(properties) do
local b = nil
if k == "x" then
b = self:getX()
elseif k == "y" then
b = self:getY()
elseif k == "rotation" then
b = self:getRotation()
elseif k == "scalex" then
b = self:getScaleX()
elseif k == "scaley" then
b = self:getScaleY()
elseif k == "alpha" then
b = self:getAlpha()
end
if b ~= nil then
self.__tween[k] = Easing.new(b, v - b, self.__duration, easing)
end
end
if not next(self.__tween) then
self:removeEventListener(Event.ENTER_FRAME, __animate_listener, self)
self.__duration = nil
self.__tween = nil
self.__watch = nil
self.__animate = nil
else
self:addEventListener(Event.ENTER_FRAME, __animate_listener, self)
self.__watch = Stopwatch.new()
self.__animate = true
end
return self
end
---
-- Layout display object and it's children to the screen.
--
-- @function [parent=#DisplayObject] layout
-- @param self
function M:layout()
local x1, y1, x2, y2
for i, v in ipairs(self.children) do
if v:getVisible() then
x1, y1, x2, y2 = self.object:layout(v.object, x1, y1, x2, y2)
v:layout()
end
end
end
---
-- Draw display object to the screen. This method must be subclassing.
--
-- @function [parent=#DisplayObject] __draw
-- @param self
-- @param display (Display) The context of the screen.
function M:__draw(display)
end
---
-- Render display object and it's children to the screen.
--
-- @function [parent=#DisplayObject] render
-- @param self
-- @param display (Display) The context of the screen.
-- @param event (Event) The 'Event' object to be dispatched.
function M:render(display, event)
self:dispatchEvent(event)
if self:getVisible() then
self:__draw(display)
end
for i, v in ipairs(self.children) do
v:render(display, event)
end
end
---
-- Dispatches an event to display object and it's children.
--
-- @function [parent=#DisplayObject] dispatch
-- @param self
-- @param event (Event) The 'Event' object to be dispatched.
function M:dispatch(event)
local children = self.children
for i = #children, 1, -1 do
children[i]:dispatch(event)
end
self:dispatchEvent(event)
end
return M
|
data.raw["item"]["coal"].fuel_value = nil
data.raw["item"]["solid-fuel"].fuel_value = nil
data.raw["item"]["rocket-fuel"].fuel_value = nil
|
--- This lua script prints the content of var1, and sets var2 to be "Hello World, I was set in Lua!"
print (var1)
var2 = "Hello World, I was set in Lua!" |
local utils = require("../miscUtils")
local muteUtils = require("../muteUtils")
local commandHandler = require("../commandHandler")
return {
name = "mute",
description = "Mute a user.",
usage = "mute <ping or id> [length (e.g. 2d4h, 5m, 1w2d3h4m)] [| reason]",
visible = true,
permissions = {"manageRoles"},
run = function(self, message, argString, args, guildSettings, conn)
if argString=="" then
commandHandler.sendUsage(message.channel, guildSettings.prefix, self.name)
return
end
local muteUser = utils.userFromString(args[1], message.client)
if not muteUser then
utils.sendEmbed(message.channel, "User "..args[1].." not found.", "ff0000")
return
end
local muteMember = utils.memberFromString(args[1], message.guild)
local name = utils.name(muteUser, message.guild)
local stringTimes=argString:match(utils.escapePatterns(args[1]).."%s+([^%|]+)") or ""
local length = utils.secondsFromString(stringTimes)
length = length>0 and length or guildSettings.default_mute_length
local valid, reasonInvalid, mutedRole = muteUtils.checkValidMute(muteMember, muteUser, message.guild, guildSettings)
if not valid then
utils.sendEmbed(message.channel, name.." could not be muted because "..reasonInvalid, "ff0000")
return
end
local isMuted = muteUtils.checkIfMuted(muteMember, muteUser, mutedRole, message.guild, conn)
if isMuted then
utils.sendEmbed(message.channel, name.." is already muted.", "ff0000")
return
end
local reason = argString:match("%|%s+(.+)")
reason = reason and " (Reason: "..reason..")" or ""
local muteFooter = commandHandler.strings.muteFooter(guildSettings, length, os.time()+length, (muteMember and true))
local staffLogChannel = guildSettings.staff_log_channel and message.guild:getChannel(guildSettings.staff_log_channel)
local mutedDM = utils.sendEmbed(muteUser:getPrivateChannel(), "You have been muted in **"..message.guild.name.."**."..reason, "00ff00", muteFooter)
local success, err = muteUtils.mute(muteMember, muteUser, mutedRole, message.guild, conn, length)
if not success then
if mutedDM then mutedDM:delete() end
utils.sendEmbed(message.channel, name.." could not be muted: `"..err.."`. Please report this error to the bot developer by sending Yot a direct message.", "ff0000")
return
end
utils.sendEmbed(message.channel, name.." has been muted."..reason, "00ff00", muteFooter)
utils.sendEmbedSafe(staffLogChannel, name.." has been muted."..reason, "00ff00", "Responsible user: "..utils.name(message.author, guild).."\n"..muteFooter)
end,
onEnable = function(self, message, guildSettings)
return true
end,
onDisable = function(self, message, guildSettings)
return true
end,
subcommands = {}
} |
--[=[
Hi-level thread primitives based on pthread and luastate.
Written by Cosmin Apreutesei. Public Domain.
THREADS
thread.new(func, args...) -> th create and start a thread
th:join() -> retvals... wait on a thread to finish
QUEUES
thread.queue([maxlength]) -> q create a synchronized queue
q:length() -> n queue length
q:maxlength() -> n queue max. length
q:push(val[, timeout]) -> true, len add value to the top (*)
q:shift([timeout]) -> true, val, len remove bottom value (*)
q:pop([timeout]) -> true, val, len remove top value (*)
q:peek([index]) -> true, val | false peek into the list without removing (**)
q:free() free queue and its resources
EVENTS
thread.event([initially_set]) -> e create an event
e:set() set the flag
e:clear() reset the flag
e:isset() -> true | false check if the flag is set
e:wait([timeout]) -> true | false wait until the flag is set
e:free() free event
(*) the `timeout` arg is an `os.time()` or `time.time()` timestamp,
not a time period; when a timeout is passed, the function returns
`false, 'timeout'` if the specified timeout expires before the underlying
mutex is locked.
(**) default index is 1 (bottom element); negative indices count from top,
-1 being the top element; returns false if the index is out of range.
THREADS ----------------------------------------------------------------------
thread.new(func, args...) -> th
Create a new thread and Lua state, push `func` and `args` to the Lua state
and execute `func(args...)` in the context of the thread. The return values
of func can be retreived by calling `th:join()` (see below).
* the function's upvalues are not copied to the Lua state along with it.
* args can be of two kinds: copiable types and shareable types.
* copiable types are: nils, booleans, strings, functions without upvalues,
tables without cyclic references or multiple references to the same
table inside.
* shareable types are: pthread threads, mutexes, cond vars and rwlocks,
top level Lua states, threads, queues and events.
Copiable objects are copied over to the Lua state, while shareable
objects are only shared with the thread. All args are kept from being
garbage-collected up until the thread is joined.
The returned thread object must not be discarded and `th:join()`
must be called on it to release the thread resources.
th:join() -> retvals...
Wait on a thread to finish and return the return values of its worker
function. Same rules apply for copying return values as for args.
Errors are propagated to the calling thread.
QUEUES -----------------------------------------------------------------------
thread.queue([maxlength]) -> q
Create a queue that can be safely shared and used between threads.
Elements can be popped from both ends, so it can act as both a LIFO
or a FIFO queue, as needed. When the queue is empty, attempts to
pop from it blocks until new elements are pushed again. When a
bounded queue (i.e. with maxlength) is full, attempts to push
to it blocks until elements are consumed. The order in which
multiple blocked threads wake up is arbitrary.
The queue can be locked and operated upon manually too. Use `q.mutex` to
lock/unlock it, `q.state` to access the elements (they occupy the Lua stack
starting at index 1), and `q.cond_not_empty`, `q.cond_not_full` to
wait/broadcast on the not-empty and not-full events.
Vales are transferred between states according to the rules of [luastate](luastate.md).
EVENTS -----------------------------------------------------------------------
thread.event([initially_set]) -> e
Events are a simple way to make multiple threads block on a flag.
Setting the flag unblocks any threads that are blocking on `e:wait()`.
NOTES ------------------------------------------------------------------------
Creating hi-level threads is slow because Lua modules must be loaded
every time for each thread. For best results, use a thread pool.
On Windows, the current directory is per thread! Same goes for env vars.
]=]
if not ... then require'thread_test'; return; end
local pthread = require'pthread'
local luastate = require'luastate'
local glue = require'glue'
local ffi = require'ffi'
local addr = glue.addr
local ptr = glue.ptr
local M = {}
--shareable objects ----------------------------------------------------------
--objects that implement the shareable interface can be shared
--between Lua states when passing args in and out of Lua states.
local typemap = {} --{ctype_name = {identify=f, decode=f, encode=f}}
--shareable pointers
local function pointer_class(in_ctype, out_ctype)
local class = {}
function class.identify(p)
return ffi.istype(in_ctype, p)
end
function class.encode(p)
return {addr = addr(p)}
end
function class.decode(t)
return ptr(out_ctype or in_ctype, t.addr)
end
return class
end
function M.shared_object(name, class)
if typemap[name] then return end --ignore duplicate registrations
typemap[name] = class
end
function M.shared_pointer(in_ctype, out_ctype)
M.shared_object(in_ctype, pointer_class(in_ctype, out_ctype))
end
M.shared_pointer'lua_State*'
M.shared_pointer('pthread_t', 'pthread_t*')
M.shared_pointer('pthread_mutex_t', 'pthread_mutex_t*')
M.shared_pointer('pthread_rwlock_t', 'pthread_rwlock_t*')
M.shared_pointer('pthread_cond_t', 'pthread_cond_t*')
--identify a shareable object and encode it.
local function encode_shareable(x)
for typename, class in pairs(typemap) do
if class.identify(x) then
local t = class.encode(x)
t.type = typename
return t
end
end
end
--decode an encoded shareable object
local function decode_shareable(t)
return typemap[t.type].decode(t)
end
--encode all shareable objects in a packed list of args
function M._encode_args(t)
t.shared = {} --{i1,...}
for i=1,t.n do
local e = encode_shareable(t[i])
if e then
t[i] = e
--put the indices of encoded objects aside for identification
--and easy traversal when decoding
table.insert(t.shared, i)
end
end
return t
end
--decode all encoded shareable objects in a packed list of args
function M._decode_args(t)
for _,i in ipairs(t.shared) do
t[i] = decode_shareable(t[i])
end
return t
end
--events ---------------------------------------------------------------------
ffi.cdef[[
typedef struct {
int flag;
pthread_mutex_t mutex;
pthread_cond_t cond;
} thread_event_t;
]]
function M.event(set)
local e = ffi.new'thread_event_t'
pthread.mutex(nil, e.mutex)
pthread.cond(nil, e.cond)
e.flag = set and 1 or 0
return e
end
local event = {}
local function set(self, val)
self.mutex:lock()
self.flag = val
self.cond:broadcast()
self.mutex:unlock()
end
function event:set()
set(self, 1)
end
function event:clear()
set(self, 0)
end
function event:isset()
self.mutex:lock()
local ret = self.flag == 1
self.mutex:unlock()
return ret
end
function event:wait(timeout)
self.mutex:lock()
local cont = true
while cont do
if self.flag == 1 then
self.mutex:unlock()
return true
end
cont = self.cond:wait(self.mutex, timeout)
end
self.mutex:unlock()
return false
end
ffi.metatype('thread_event_t', {__index = event})
M.shared_pointer('thread_event_t', 'thread_event_t*')
--queues ---------------------------------------------------------------------
local queue = {}
queue.__index = queue
function M.queue(maxlen)
assert(not maxlen or (math.floor(maxlen) == maxlen and maxlen >= 1),
'invalid queue max. length')
local state = luastate.open() --values will be kept on the state's stack
return setmetatable({
state = state,
mutex = pthread.mutex(),
cond_not_empty = pthread.cond(),
cond_not_full = pthread.cond(),
maxlen = maxlen,
}, queue)
end
function queue:free()
self.cond_not_full:free(); self.cond_not_full = nil
self.cond_not_empty:free(); self.cond_not_empty = nil
self.state:close(); self.state = nil
self.mutex:free(); self.mutex = nil
end
function queue:maxlength()
return self.maxlen
end
local function queue_length(self)
return self.state:gettop()
end
local function queue_isfull(self)
return self.maxlen and queue_length(self) == self.maxlen
end
local function queue_isempty(self)
return queue_length(self) == 0
end
function queue:length()
self.mutex:lock()
local ret = queue_length(self)
self.mutex:unlock()
return ret
end
function queue:isfull()
self.mutex:lock()
local ret = queue_isfull(self)
self.mutex:unlock()
return ret
end
function queue:isempty()
self.mutex:lock()
local ret = queue_isempty(self)
self.mutex:unlock()
return ret
end
function queue:push(val, timeout)
self.mutex:lock()
while queue_isfull(self) do
if not self.cond_not_full:wait(self.mutex, timeout) then
self.mutex:unlock()
return false, 'timeout'
end
end
local was_empty = queue_isempty(self)
self.state:push(val)
local len = queue_length(self)
if was_empty then
self.cond_not_empty:broadcast()
end
self.mutex:unlock()
return true, len
end
local function queue_remove(self, index, timeout)
self.mutex:lock()
while queue_isempty(self) do
if not self.cond_not_empty:wait(self.mutex, timeout) then
self.mutex:unlock()
return false, 'timeout'
end
end
local was_full = queue_isfull(self)
local val = self.state:get(index)
self.state:remove(index)
local len = queue_length(self)
if was_full then
self.cond_not_full:broadcast()
end
self.mutex:unlock()
return true, val, len
end
function queue:pop(timeout)
return queue_remove(self, -1, timeout)
end
--NOTE: this is O(N) where N = self:length().
function queue:shift(timeout)
return queue_remove(self, 1, timeout)
end
function queue:peek(i)
i = i or 1
self.mutex:lock()
local len = queue_length(self)
if i <= 0 then
i = len + i + 1 -- index -1 is top
end
if i < 1 or i > len then
self.mutex:unlock()
return false
end
local val = self.state:get(i)
self.mutex:unlock()
return true, val
end
--queues / shareable interface
function queue:identify()
return getmetatable(self) == queue
end
function queue:encode()
return {
state_addr = addr(self.state),
mutex_addr = addr(self.mutex),
cond_not_full_addr = addr(self.cond_not_full),
cond_not_empty_addr = addr(self.cond_not_empty),
maxlen = self.maxlen,
}
end
function queue.decode(t)
return setmetatable({
state = ptr('lua_State*', t.state_addr),
mutex = ptr('pthread_mutex_t*', t.mutex_addr),
cond_not_full = ptr('pthread_cond_t*', t.cond_not_full_addr),
cond_not_empty = ptr('pthread_cond_t*', t.cond_not_empty_addr),
maxlen = t.maxlen,
}, queue)
end
M.shared_object('queue', queue)
--threads --------------------------------------------------------------------
function M.init_state(state)
state:openlibs()
state:push{[0] = arg[0]} --used to make `glue.bin`
state:setglobal'arg'
if package.loaded.bundle_loader then
local bundle_luastate = require'bundle_luastate'
bundle_luastate.init_bundle(state)
end
end
local thread = {type = 'os_thread', debug_prefix = '!'}
thread.__index = thread
function M.new(func, ...)
local state = luastate.open()
M.init_state(state)
state:push(function(func, args)
local ffi = require'ffi'
local pthread = require'pthread'
local luastate = require'luastate'
local glue = require'glue'
local thread = require'thread'
local cast = ffi.cast
local addr = glue.addr
local function pass(ok, ...)
local retvals = ok and thread._encode_args(glue.pack(...)) or {err = ...}
rawset(_G, '__ret', retvals) --is this the only way to get them out?
end
local function worker()
local t = thread._decode_args(args)
pass(xpcall(func, debug.traceback, glue.unpack(t)))
end
--worker_cb is anchored by luajit along with the function it frames.
local worker_cb = cast('void *(*)(void *)', worker)
return addr(worker_cb)
end)
local args = glue.pack(...)
local encoded_args = M._encode_args(args)
local worker_cb_ptr = ptr(state:call(func, encoded_args))
local pthread = pthread.new(worker_cb_ptr)
return setmetatable({
pthread = pthread,
state = state,
args = args, --keep args to avoid shareables from being collected
}, thread)
end
function thread:join()
self.pthread:join()
self.args = nil --release args
--get the return values of worker function
self.state:getglobal'__ret'
local retvals = self.state:get()
self.state:close()
--propagate the error
if retvals.err then
error(retvals.err, 2)
end
return glue.unpack(M._decode_args(retvals))
end
--threads / shareable interface
function thread:identify()
return getmetatable(self) == thread
end
function thread:encode()
return {
pthread_addr = addr(self.pthread),
state_addr = addr(self.state),
}
end
function M.decode(t)
return setmetatable({
pthread = ptr('pthread_t*', t.thread_addr),
state = ptr('lua_State*', t.state_addr),
}, thread)
end
M.shared_object('thread', thread)
--thread pools ---------------------------------------------------------------
local pool = {}
pool.__index = pool
local function pool_worker(q)
while true do
print('waiting for task', q:length())
local _, task = q:shift()
print'got task'
task()
end
end
function M.pool(n)
local t = {}
t.queue = M.queue(1)
for i = 1, n do
t[i] = M.new(pool_worker, t.queue)
end
return setmetatable(t, pool)
end
function pool:join()
for i = #self, 1, -1 do
self[i]:join()
self[i] = nil
end
self.queue:free()
self.queue = nil
end
function pool:push(task, timeout)
return self.queue:push(task, timeout)
end
return M
|
CollectionatorRecipeCacheFrameMixin = {}
function CollectionatorRecipeCacheFrameMixin:OnLoad()
FrameUtil.RegisterFrameForEvents(self, {
"VARIABLES_LOADED",
"TRADE_SKILL_DATA_SOURCE_CHANGED",
})
end
function CollectionatorRecipeCacheFrameMixin:OnEvent(event, ...)
if event == "VARIABLES_LOADED" then
self:SetupVariables()
elseif event == "TRADE_SKILL_DATA_SOURCE_CHANGED" then
if Auctionator.Config.Get(Auctionator.Config.Options.COLLECTIONATOR_RECIPE_CACHING) then
self:CacheKnownRecipes()
end
end
end
function CollectionatorRecipeCacheFrameMixin:ResetCache()
COLLECTIONATOR_RECIPES_CACHE = {
known = {},
couldKnow = {},
}
self.knownIDs = COLLECTIONATOR_RECIPES_CACHE.known
self.couldKnowIDs = COLLECTIONATOR_RECIPES_CACHE.couldKnow
end
function CollectionatorRecipeCacheFrameMixin:SetupVariables()
if COLLECTIONATOR_RECIPES_CACHE == nil then
self:ResetCache()
end
self.knownIDs = COLLECTIONATOR_RECIPES_CACHE.known
self.couldKnowIDs = COLLECTIONATOR_RECIPES_CACHE.couldKnow
self.realmAndFaction = Collectionator.Utilities.GetRealmAndFaction()
end
function CollectionatorRecipeCacheFrameMixin:CacheSpell(db, spellID)
if db[spellID] == nil then
db[spellID] = {}
end
if tIndexOf(db[spellID], self.realmAndFaction) == nil then
table.insert(db[spellID], self.realmAndFaction)
end
end
function CollectionatorRecipeCacheFrameMixin:CacheKnownRecipes()
local allRecipeIDs = C_TradeSkillUI.GetAllRecipeIDs()
for _, spellID in ipairs(allRecipeIDs) do
if IsPlayerSpell(spellID) then
self.knownIDs[spellID] = true
end
self:CacheSpell(self.couldKnowIDs, spellID)
end
end
|
local MILESTONE_NAME = "STONECRATER_BIGHOLE"
function get_players()
local name = get_entity_name(get_player_id(0))
if (name == "egbert") then
egbert = get_player_id(0)
frogbert = get_player_id(1)
bisou = get_player_id(2)
elseif (name == "frogbert") then
frogbert = get_player_id(0)
bisou = get_player_id(1)
egbert = get_player_id(2)
else
bisou = get_player_id(0)
egbert = get_player_id(1)
frogbert = get_player_id(2)
end
end
function start(game_just_loaded)
play_music("music/stonecrater.mid");
process_outline()
add_wall_group(2, 18, 8, 1, 2, 0)
add_wall_group(2, 7, 7, 1, 1, TILE_GROUP_BUSHES)
add_wall_group(2, 12, 6, 1, 1, TILE_GROUP_BUSHES)
add_wall_group(2, 13, 5, 3, 2, TILE_GROUP_BUSHES)
to_stonecrater5 = Active_Block:new{x=9, y=21, width=6, height=1}
bmps = {}
for i=1,21 do
bmps[i] = load_bitmap("misc_graphics/stonecrater_hole/" .. i .. ".png")
end
if (not milestone_is_complete(MILESTONE_NAME)) then
frame = 1
large_boulder = add_entity("large_boulder", 1, 12.5*TILE_SIZE, 10.5*TILE_SIZE)
start_scene = true
else
add_polygon_entity(
2,
176, 208,
158, 191,
157, 158,
177, 141,
221, 139,
240, 157,
241, 191,
224, 208
)
end
load_sample("sfx/boing.ogg", false)
load_sample("sfx/throw.ogg", false)
load_sample("sfx/ground_cracking.ogg", false)
end
function activate(activator, activated)
if (activated == chest1.id) then
chest1:open()
end
end
local player_count = 0
function count_players(tween, id, elapsed)
player_count = player_count + 1
return true
end
local crack_count = 0
function switch_tile(layer, x, y)
local sheet, num, solid = get_tile(layer, x, y)
set_tile(3, x, y, sheet, num, solid)
end
function switch_tile_layers()
switch_tile(1, 10, 12)
switch_tile(1, 14, 12)
for i=10,14 do
switch_tile(1, i, 13)
switch_tile(1, i, 14)
switch_tile(1, i, 15)
end
end
local num_fell = 0
function inc_fell(tween, id, elapsed)
num_fell = num_fell + 1
return true
end
function hide_entity(tween, id, elapsed)
set_entity_visible(tween.entity, false)
return true
end
function drop(ent)
local x, y = get_entity_position(ent)
play_sample("sfx/throw.ogg", 1, 0, 1)
local t = create_direct_move_tween(ent, x, 14.5*TILE_SIZE, 250)
append_tween(t, { run = hide_entity, entity = ent })
append_tween(t, { run = inc_fell })
new_tween(t)
end
function logic()
if (to_stonecrater5:entity_is_colliding(0)) then
next_player_layer = 2
change_areas("stonecrater5", DIR_S, 24*TILE_SIZE, 3.5*TILE_SIZE)
end
if (not (next_area == nil)) then
next_area = next_area + 1
if (next_area == 10) then
set_milestone_complete(MILESTONE_NAME, true)
next_player_layer = 2
change_areas("caverns1", DIR_S, 27.5*TILE_SIZE, 10.5*TILE_SIZE)
end
elseif (num_fell == 4 and not fell5) then
next_area = 1
fell5 = true
elseif (num_fell == 3 and not fell4) then
fell4 = true
drop(bisou)
elseif (num_fell == 2 and not fell3) then
fell3 = true
drop(egbert)
elseif (num_fell == 1 and not fell2) then
fell2 = true
drop(frogbert)
elseif (finished_cracking_ground and not fell1) then
fell1 = true
drop(large_boulder)
elseif (crack_ground and not finished_cracking_ground) then
crack_count = crack_count + 1
if (crack_count == 4) then
crack_count = 0
frame = frame + 1
if (frame == 5) then
play_sample("sfx/boing.ogg", 1, 0, 1)
set_entity_input_disabled(0, true)
set_entity_animation(egbert, "surprised")
set_entity_animation(frogbert, "surprised")
set_entity_animation(bisou, "surprised")
elseif (frame == 21) then
finished_cracking_ground = true
switch_tile_layers()
end
end
elseif (player_count == 3 and not talked) then
talked = true
set_entity_right(frogbert, true)
set_entity_right(bisou, false)
set_character_role(egbert, "")
set_character_role(frogbert, "")
set_character_role(bisou, "")
simple_speak{
true,
"SC5_FROGBERT_1", "idle", frogbert,
"SC5_BISOU_1", "idle", bisou
}
crack_ground = true
play_sample("sfx/ground_cracking.ogg", 1, 0, 1)
elseif (start_scene and not scene_started) then
scene_started = true
get_players()
set_character_role(egbert, "astar")
set_character_role(frogbert, "astar")
set_character_role(bisou, "astar")
player_count = 0
local t
t = create_astar_tween(egbert, 12.5*TILE_SIZE, 12*TILE_SIZE, true)
append_tween(t, { run = count_players })
new_tween(t)
t = create_astar_tween(frogbert, 11.5*TILE_SIZE, 12*TILE_SIZE, true)
append_tween(t, { run = count_players })
new_tween(t)
t = create_astar_tween(bisou, 13.5*TILE_SIZE, 12*TILE_SIZE, true)
append_tween(t, { run = count_players })
new_tween(t)
end
end
function collide(id1, id2)
end
function uncollide(id1, id2)
end
function action_button_pressed(n)
end
function attacked(attacker, attackee)
end
function stop()
for i=1,20 do
destroy_bitmap("misc_graphics/stonecrater_hole/" .. i .. ".png")
end
destroy_sample("sfx/boing.ogg")
destroy_sample("sfx/throw.ogg")
destroy_sample("sfx/ground_cracking.ogg")
end
function mid_draw_layer(layer)
if (not milestone_is_complete(MILESTONE_NAME)) then
if (layer == 1) then
local top_x, top_y = get_area_top()
draw_bitmap(bmps[frame], 9*TILE_SIZE-top_x, 8*TILE_SIZE-top_y, 0)
end
end
end
|
Locales['en'] = {
['Discord do servidor'] = 'Server discord',
['Site do Servidor'] = 'Server website',
['Servidor'] = 'Server',
}
|
-- vim: nu et ts=2 sts=2 sw=2
local module = {}
local pl = {}
pl.pretty = require("pl.pretty")
pldump = pl.pretty.dump
local phaseMove = {}
local joystick1 = nil
local joystick1Conf = nil
function module.load()
local joysticks = love.joystick.getJoysticks()
joystick1 = joysticks[1]
if joystick1 then
print("Found joystick: "..joystick1:getID())
if joystick1:isGamepad() then
print("Joystick1 is a gamepad.")
else
print("Joystick1 is not a gamepad.")
printf("Joystick1 counts: hats=%d, axes=%d, buttons=%d",
joystick1:getHatCount(), joystick1:getAxisCount(),
joystick1:getButtonCount())
joystick1Conf = {}
local guid = joystick1:getGUID()
print("Joystick GUID: "..guid)
if guid == "79001100000000000000504944564944" then
print("GUID recognized: SNES style.")
joystick1Conf = {
axisLR = 1, axisUD = 5,
buttonA = 2, buttonB = 3, buttonX = 1, buttonY = 4,
buttonR = 6, buttonL = 5, buttonStart = 10, buttonSelect = 9,
}
end
end
else
print("No joystick found.")
end
end
function module.keypressed(key)
if key == "q" then
print("QUITTING")
love.event.quit()
elseif key == "space" then
paused = not paused
elseif key == "f" then
toggleFullscreen()
elseif key == "up" or key == "down" or key == "left" or key == "right" then
phaseMove[key] = true
end
end
function module.gamepadpressed(eventJoystick, eventButton)
print("JB")
-- Only pay attention to joystick1.
if eventJoystick:getID() == joystick1:getID() then
if eventButton == "dpleft" or eventButton == "dpright"
or eventButton == "dpup" or eventButton == "dpdown" then
local direction = strsub(eventButton, 3)
phaseMove[direction] = true
end
end
end
function module.gamepadpressed(eventJoystick, eventButton)
printf("GamepadPressed: %s %s", eventJoystick, eventButton)
end
function module.joystickpressed(eventJoystick, eventButton)
printf("JoystickPressed: %s %s", eventJoystick, eventButton)
local code = ""
if eventButton == joystick1Conf.buttonA then code = "a"
elseif eventButton == joystick1Conf.buttonB then code = "b"
elseif eventButton == joystick1Conf.buttonX then code = "x"
elseif eventButton == joystick1Conf.buttonY then code = "y"
elseif eventButton == joystick1Conf.buttonL then code = "l"
elseif eventButton == joystick1Conf.buttonR then code = "r"
elseif eventButton == joystick1Conf.buttonSelect then code = "select"
elseif eventButton == joystick1Conf.buttonStart then code = "start"
end
if code ~= "" then
print("Joystick button: "..code)
end
end
function module.getMovementCommand()
local x, y = 0, 0
-- Get local reference to phaseMove and then reset it.
local m = phaseMove
phaseMove = {}
scanArrowKeysMove(m)
if joystick1 then
if joystick1:isGamepad() then
scanGamepadMove(m, joystick1)
else
scanJoystickMove(m, joystick1, joystick1Conf)
end
end
if m["left"] then x = x - 1 end
if m["right"] then x = x + 1 end
if m["up"] then y = y - 1 end
if m["down"] then y = y + 1 end
return { x=x, y=y }
end
function scanArrowKeysMove(m)
if love.keyboard.isDown("left") then m["left"] = true end
if love.keyboard.isDown("right") then m["right"] = true end
if love.keyboard.isDown("up") then m["up"] = true end
if love.keyboard.isDown("down") then m["down"] = true end
end
function scanGamepadMove(m, js)
if js:isGamepadDown("dpleft") then m["left"] = true end
if js:isGamepadDown("dpright") then m["right"] = true end
if js:isGamepadDown("dpup") then m["up"] = true end
if js:isGamepadDown("dpdown") then m["down"] = true end
end
function scanJoystickMove(m, js, jsConf)
-- TODO: For loop over hats (if any)
local hatDir = js:getHat(1)
if hatDir and hatDir ~= "" then
if hatDir == "l" then m["left"] = true
elseif hatDir == "r" then m["right"] = true
elseif hatDir == "u" then m["up"] = true
elseif hatDir == "d" then m["down"] = true
elseif hatDir == "lu" then m["left"] = true; m["up"] = true
elseif hatDir == "ld" then m["left"] = true; m["down"] = true
elseif hatDir == "ru" then m["right"] = true; m["up"] = true
elseif hatDir == "rd" then m["right"] = true; m["down"] = true
elseif hatDir == "c" then
-- do nothing if hat is centered
else print("Hat direction unknown: "..hatDir)
end
end
if jsConf and jsConf.axisLR and jsConf.axisUD then
-- TODO: Use threshold instead of +/-1.
axisLR = js:getAxis(jsConf.axisLR)
axisUD = js:getAxis(jsConf.axisUD)
if axisLR == -1 then m["left"] = true end
if axisLR == 1 then m["right"] = true end
if axisUD == -1 then m["up"] = true end
if axisUD == 1 then m["down"] = true end
end
end
return module
|
--[[
Name: "init.lua".
Product: "nexus".
--]]
local function ParticleCollides(particle, position, normal)
util.Decal("Blood", position + normal, position - normal);
end;
-- Called when the effect has initialized.
function EFFECT:Init(data)
local particleEmitter = ParticleEmitter( data:GetOrigin() );
local velocity = data:GetNormal() or ( Vector(0, 0, 1) * math.Rand(32, 64) );
local scale = data:GetScale() or 2;
for i = 1, (16 * scale) do
local startSize = math.Rand(16 * scale, 32 * scale);
local position = Vector( math.Rand(-1, 1), math.Rand(-1, 1), math.Rand(-2, 2) );
local particle = particleEmitter:Add("particle/particle_smokegrenade", data:GetOrigin() + position);
if (particle) then
particle:SetAirResistance( math.Rand(256, 384) );
particle:SetCollideCallback(ParticleCollides);
particle:SetStartAlpha(175);
particle:SetStartSize(startSize * 2);
particle:SetRollDelta( math.Rand(-0.2, 0.2) );
particle:SetEndAlpha( math.Rand(0, 128) );
particle:SetVelocity(velocity);
particle:SetLifeTime(0);
particle:SetLighting(0);
particle:SetGravity( Vector( math.Rand(-8, 8), math.Rand(-8, 8), math.Rand(16, -16) ) );
particle:SetCollide(true);
particle:SetEndSize(startSize);
particle:SetDieTime( math.random(1, 3) );
particle:SetBounce(0.5);
particle:SetColor( math.random(200, 255), math.random(0, 50), math.random(0, 50) );
particle:SetRoll( math.Rand(-180, 180) );
end;
end;
particleEmitter:Finish()
end;
-- Called when the effect should be rendered.
function EFFECT:Render() end;
-- Called each frame.
function EFFECT:Think()
return false;
end; |
if mechanics == nil then
mechanics = {}
end
mechanics.dungeon = {} |
--
-- (C) 2013 Kriss@XIXs.com
--
-- This file is distributed under the terms of the MIT license.
-- http://en.wikipedia.org/wiki/MIT_License
-- Please ping me if you use it for anything cool...
--
local math=require("math")
local table=require("table")
local string=require("string")
local unpack=unpack
local getmetatable=getmetatable
local setmetatable=setmetatable
local type=type
local pairs=pairs
local ipairs=ipairs
local tostring=tostring
local tonumber=tonumber
local require=require
local error=error
--[[#lua.wetgenes.tardis
Time And Relative Dimensions In Space is of course the perfect name for
a library of matrix based math functions.
local tardis=require("wetgenes.tardis")
This tardis is a lua library for manipulating time and space with
numbers. Designed to work as pure lua but with a faster, but less
accurate, f32 core by default.
Recoil in terror as we use two glyph names for classes whilst typing in
random strings of numbers and operators that may or may not contain
tyops.
v# vector [#]
m# matrix [#][#]
q4 quaternion
Each class is a table of # values [1] to [#] the 2d number streams are
formatted the same as opengl (row-major) and metatables are used to
provide methods.
The easy way of remembering the opengl 4x4 matrix layout is that the
translate x,y,z values sit at 13,14,15 and 4,8,12,16 is normally set
to the constant 0,0,0,1 for most transforms.
| 1 5 9 13 |
| 2 6 10 14 |
m4 = | 3 7 11 15 |
| 4 8 12 16 |
The Lua code is normally replaced with a hopefully faster f32 based C
version, Use DISABLE_WETGENES_TARDIS_CORE before requiring this file to
turn it off and get a pure lua library.
This seems to be the simplest (programmer orientated) description of
most of the maths used here so go read it if you want to know what the
funny words mean.
http://www.j3d.org/matrix_faq/matrfaq_latest.html
]]
--module
local tardis={ modname=(...) } ; package.loaded[tardis.modname]=tardis
--[[#lua.wetgenes.tardis.type
name=tardis.type(object)
This will return the type of an object previously registered with class
]]
function tardis.type(it) return it.__type or type(it) end
--[[#lua.wetgenes.tardis.class
metatable=tardis.class(name,class,...)
Create a new metatable for an object class, optionally inheriting from other previously
declared classes.
]]
function tardis.class(name,...)
if tardis[name] then return tardis[name] end
local meta={} -- create new
local sub={...} -- possibly multiple sub classes
if #sub>0 then -- inherit?
for idx=#sub,1,-1 do -- reverse sub class order, so the ones to the left overwrite the ones on the right
for n,v in pairs(sub[idx]) do meta[n]=v end -- each subclass overwrites all values
end
end
meta.__index=meta -- this metatable is its own index
meta.__type=name -- class name
tardis[name]=meta -- save in using name and return table
return meta
end
--[[#lua.wetgenes.tardis.array
Array is the base class for all other tardis classes, it is just a
stream of numbers, probably in a table but possibly a chunk of f32
values in a userdata.
]]
local array=tardis.class("array")
--[[#lua.wetgenes.tardis.array.__tostring
string = array.__tostring(it)
Convert an array to a string this is called by the lua tostring() function,
]]
function array.__tostring(it) -- these classes are all just 1d arrays of numbers
local t={}
t[#t+1]=tardis.type(it)
t[#t+1]="={"
for i=1,#it do
t[#t+1]=tostring(it[i])
if i~=#it then t[#t+1]=", " end
end
t[#t+1]="}"
return table.concat(t)
end
--[[#lua.wetgenes.tardis.array.set
a=a:set(1,2,3,4)
a=a:set({1,2,3,4})
a=a:set({1,2},{3,4})
Assign some numbers to an array, all the above examples will assign
1,2,3,4 to the first four slots in the given array, as you can see we
allow one level of tables. Any class that is based on this array
class can be used instead of an explicit table. So we can use a v2 or v3 or m4 etc etc.
if more numbers are given than the size of the array then they will be
ignored.
]]
function array.set(it,...)
local n=1
for i,v in ipairs{...} do
if not it[n] then return it end -- got all the data we need (#it)
if type(v)=="number" then
it[n]=v
n=n+1
else
for ii=1,#v do local vv=v[ii] -- allow one depth of tables
it[n]=vv
n=n+1
end
end
end
return it
end
--[[#lua.wetgenes.tardis.array.compare
a=a:compare(b)
a=a:compare(1,2,3,4)
Are the numbers in b the same as the numbers in a, this function will
return true if they are and false if they are not.
If the arrays are of different lengths then this will return false.
Numbers to test for can be given explicitly in the arguments and we
follow the same one level of tables rule as we do with array.set so any
class derived from array can be used.
]]
function array.compare(it,...)
local n=1
for i,v in ipairs{...} do
if type(v)=="number" then
if it[n]~=v then return false end
n=n+1
else
for ii=1,#v do local vv=v[ii] -- allow one depth of tables
if it[n]~=vv then return false end
n=n+1
end
end
end
if n<#it then return false end -- array has more numbers than provided for test
return true
end
--[[#lua.wetgenes.tardis.array.product
ma = ma:product(mb)
ma = ma:product(mb,r)
Look at the type and call the appropriate product function, to produce
mb x ma
Note the right to left application and default returning of the
leftmost term for chaining. This seems to make the most sense.
If r is provided then the result is written into r and returned
otherwise ma is modified and returned.
]]
function array.product(a,b,r)
local mta=tardis.type(a)
local mtb=tardis.type(b)
if mta=="v3" and mtb=="m4" then return tardis.v3_product_m4(a,b,r)
elseif mta=="v3" and mtb=="q4" then return tardis.v3_product_q4(a,b,r)
elseif mta=="v4" and mtb=="m4" then return tardis.v4_product_m4(a,b,r)
elseif mta=="m4" and mtb=="m4" then return tardis.m4_product_m4(a,b,r)
elseif mta=="q4" and mtb=="q4" then return tardis.q4_product_q4(a,b,r)
end
error("tardis : "..mta.." product "..mtb.." not supported",2)
end
--[[#lua.wetgenes.tardis.m2
The metatable for a 2x2 matrix class, use the new function to actually create an object.
We also inherit all the functions from tardis.array
]]
local m2=tardis.class("m2",array)
--[[#lua.wetgenes.tardis.m2.new
m2 = tardis.m2.new()
Create a new m2 and optionally set it to the given values, m2 methods
usually return the input m2 for easy function chaining.
]]
function m2.new(...) return setmetatable({0,0,0,0},m2):set(...) end
--[[#lua.wetgenes.tardis.m2.identity
m2 = m2:identity()
Set this m2 to the identity matrix.
]]
function m2.identity(it) return it:set(1,0, 0,1) end
--[[#lua.wetgenes.tardis.m2.determinant
value = m2:determinant()
Return the determinant value of this m2.
]]
function m2.determinant(it)
return ( it[ 1 ]*it[ 2+2 ] )
+( it[ 2 ]*it[ 2+1 ] )
-( it[ 1 ]*it[ 2+1 ] )
-( it[ 2 ]*it[ 2+1 ] )
end
--[[#lua.wetgenes.tardis.m2.minor_xy
value = m2:minor_xy()
Return the minor_xy value of this m2.
]]
function m2.minor_xy(it,x,y)
return it[1+(2-(x-1))+((2-(y-1))*2)]
end
--[[#lua.wetgenes.tardis.m2.transpose
m2 = m2:transpose()
m2 = m2:transpose(r)
Transpose this m2.
If r is provided then the result is written into r and returned
otherwise m2 is modified and returned.
]]
function m2.transpose(it,r)
r=r or it
return r:set(it[1],it[2+1], it[2],it[2+2])
end
--[[#lua.wetgenes.tardis.m2.scale
m2 = m2:scale(s)
m2 = m2:scale(s,r)
Scale this m2 by s.
If r is provided then the result is written into r and returned
otherwise m2 is modified and returned.
]]
function m2.scale(it,s,r)
r=r or it
return r:set(it[1]*s,it[2]*s, it[2+1]*s,it[2+2]*s)
end
--[[#lua.wetgenes.tardis.m2.cofactor
m2 = m2:cofactor()
m2 = m2:cofactor(r)
Cofactor this m2.
If r is provided then the result is written into r and returned
otherwise m2 is modified and returned.
]]
function m2.cofactor(it,r)
r=r or it
local t={}
for iy=1,2 do
for ix=1,2 do
local idx=iy*2+ix-2
if ((ix+iy)%2)==1 then
t[idx]=-m2.minor_xy(it,ix,iy)
else
t[idx]=m2.minor_xy(it,ix,iy)
end
end
end
return r
end
--[[#lua.wetgenes.tardis.m2.adjugate
m2 = m2:adjugate()
m2 = m2:adjugate(r)
Adjugate this m2.
If r is provided then the result is written into r and returned
otherwise m2 is modified and returned.
]]
function m2.adjugate(it,r)
r=r or it
return m2.cofactor(m2.transpose(it,m2.new()),r)
end
--[[#lua.wetgenes.tardis.m2.inverse
m2 = m2:inverse()
m2 = m2:inverse(r)
Inverse this m2.
If r is provided then the result is written into r and returned
otherwise m2 is modified and returned.
]]
function m2.inverse(it,r)
r=r or it
local ood=1/m2.determinant(it)
return m2.scale(m2.cofactor(m2.transpose(it,m2.new())),ood,r)
end
--[[#lua.wetgenes.tardis.m3
The metatable for a 3x3 matrix class, use the new function to actually
create an object.
We also inherit all the functions from tardis.array
]]
local m3=tardis.class("m3",array)
--[[#lua.wetgenes.tardis.m3.new
m3 = tardis.m3.new()
Create a new m3 and optionally set it to the given values, m3 methods
usually return the input m3 for easy function chaining.
]]
function m3.new(...) return setmetatable({0,0,0,0,0,0,0,0,0},m3):set(...) end
--[[#lua.wetgenes.tardis.m3.identity
m3 = m3:identity()
Set this m3 to the identity matrix.
]]
function m3.identity(it) return it:set(1,0,0, 0,1,0, 0,0,1) end
--[[#lua.wetgenes.tardis.m3.determinant
value = m3:determinant()
Return the determinant value of this m3.
]]
function m3.determinant(it)
return ( it[ 1 ]*it[ 3+2 ]*it[ 6+3 ] )
+( it[ 2 ]*it[ 3+3 ]*it[ 6+1 ] )
+( it[ 3 ]*it[ 3+1 ]*it[ 6+2 ] )
-( it[ 1 ]*it[ 3+3 ]*it[ 6+2 ] )
-( it[ 2 ]*it[ 3+1 ]*it[ 6+3 ] )
-( it[ 3 ]*it[ 3+2 ]*it[ 6+1 ] )
end
--[[#lua.wetgenes.tardis.m3.minor_xy
value = m3:minor_xy()
Return the minor_xy value of this m3.
]]
function m3.minor_xy(it,x,y)
local t={}
for ix=1,3 do
for iy=1,3 do
if (ix~=x) and (iy~=y) then
t[#t+1]=it[ix+((iy-1)*3)]
end
end
end
return m2.determinant(t)
end
--[[#lua.wetgenes.tardis.m3.transpose
m3 = m3:transpose()
m3 = m3:transpose(r)
Transpose this m3.
If r is provided then the result is written into r and returned
otherwise m3 is modified and returned.
]]
function m3.transpose(it,r)
r=r or r
return r:set(it[1],it[3+1],it[6+1], it[2],it[3+2],it[6+2], it[3],it[3+3],it[6+3])
end
--[[#lua.wetgenes.tardis.m3.scale
m3 = m3:scale(s)
m3 = m3:scale(s,r)
Scale this m3 by s.
If r is provided then the result is written into r and returned
otherwise m3 is modified and returned.
]]
function m3.scale(it,s,r)
r=r or it
return r:set(it[1]*s,it[2]*s,it[3]*s, it[3+1]*s,it[3+2]*s,it[3+3]*s, it[6+1]*s,it[6+2]*s,it[6+3]*s)
end
--[[#lua.wetgenes.tardis.m3.cofactor
m3 = m3:cofactor()
m3 = m3:cofactor(r)
Cofactor this m3.
If r is provided then the result is written into r and returned
otherwise m3 is modified and returned.
]]
function m3.cofactor(it,r)
r=r or it
local t={}
for iy=1,3 do
for ix=1,3 do
local idx=iy*3+ix-3
if ((ix+iy)%2)==1 then
t[idx]=-m3.minor_xy(it,ix,iy)
else
t[idx]=m3.minor_xy(it,ix,iy)
end
end
end
return r:set(t)
end
--[[#lua.wetgenes.tardis.m3.adjugate
m3 = m3:adjugate()
m3 = m3:adjugate(r)
Adjugate this m3.
If r is provided then the result is written into r and returned
otherwise m3 is modified and returned.
]]
function m3.adjugate(it,r)
r=r or it
return m3.cofactor(m3.transpose(it,m3.new()),r)
end
--[[#lua.wetgenes.tardis.m3.inverse
m3 = m3:inverse()
m3 = m3:inverse(r)
Inverse this m3.
If r is provided then the result is written into r and returned
otherwise m3 is modified and returned.
]]
function m3.inverse(it,r)
r=r or it
local ood=1/m3.determinant(it)
return m3.scale(m3.cofactor(m3.transpose(it,m3.new())),ood,r)
end
--[[#lua.wetgenes.tardis.m4
The metatable for a 4x4 matrix class, use the new function to actually
create an object.
We also inherit all the functions from tardis.array
]]
local m4=tardis.class("m4",array)
--[[#lua.wetgenes.tardis.m4.new
m4 = tardis.m4.new()
Create a new m4 and optionally set it to the given values, m4 methods
usually return the input m4 for easy function chaining.
]]
function m4.new(...) return setmetatable({0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},m4):set(...) end
--[[#lua.wetgenes.tardis.m4.identity
m4 = m4:identity()
Set this m4 to the identity matrix.
]]
function m4.identity(it) return it:set(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1) end
--[[#lua.wetgenes.tardis.m4.determinant
value = m4:determinant()
Return the determinant value of this m4.
]]
function m4.determinant(it)
return (it[ 4 ] * it[ 4+3 ] * it[ 8+2 ] * it[ 12+1 ])-(it[ 3 ] * it[ 4+4 ] * it[ 8+2 ] * it[ 12+1 ])-
(it[ 4 ] * it[ 4+2 ] * it[ 8+3 ] * it[ 12+1 ])+(it[ 2 ] * it[ 4+4 ] * it[ 8+3 ] * it[ 12+1 ])+
(it[ 3 ] * it[ 4+2 ] * it[ 8+4 ] * it[ 12+1 ])-(it[ 2 ] * it[ 4+3 ] * it[ 8+4 ] * it[ 12+1 ])-
(it[ 4 ] * it[ 4+3 ] * it[ 8+1 ] * it[ 12+2 ])+(it[ 3 ] * it[ 4+4 ] * it[ 8+1 ] * it[ 12+2 ])+
(it[ 4 ] * it[ 4+1 ] * it[ 8+3 ] * it[ 12+2 ])-(it[ 1 ] * it[ 4+4 ] * it[ 8+3 ] * it[ 12+2 ])-
(it[ 3 ] * it[ 4+1 ] * it[ 8+4 ] * it[ 12+2 ])+(it[ 1 ] * it[ 4+3 ] * it[ 8+4 ] * it[ 12+2 ])+
(it[ 4 ] * it[ 4+2 ] * it[ 8+1 ] * it[ 12+3 ])-(it[ 2 ] * it[ 4+4 ] * it[ 8+1 ] * it[ 12+3 ])-
(it[ 4 ] * it[ 4+1 ] * it[ 8+2 ] * it[ 12+3 ])+(it[ 1 ] * it[ 4+4 ] * it[ 8+2 ] * it[ 12+3 ])+
(it[ 2 ] * it[ 4+1 ] * it[ 8+4 ] * it[ 12+3 ])-(it[ 1 ] * it[ 4+2 ] * it[ 8+4 ] * it[ 12+3 ])-
(it[ 3 ] * it[ 4+2 ] * it[ 8+1 ] * it[ 12+4 ])+(it[ 2 ] * it[ 4+3 ] * it[ 8+1 ] * it[ 12+4 ])+
(it[ 3 ] * it[ 4+1 ] * it[ 8+2 ] * it[ 12+4 ])-(it[ 1 ] * it[ 4+3 ] * it[ 8+2 ] * it[ 12+4 ])-
(it[ 2 ] * it[ 4+1 ] * it[ 8+3 ] * it[ 12+4 ])+(it[ 1 ] * it[ 4+2 ] * it[ 8+3 ] * it[ 12+4 ])
end
--[[#lua.wetgenes.tardis.m4.minor_xy
value = m4:minor_xy()
Return the minor_xy value of this m4.
]]
function m4.minor_xy(it,x,y)
local t={}
for ix=1,4 do
for iy=1,4 do
if (ix~=x) and (iy~=y) then
t[#t+1]=it[ix+((iy-1)*4)]
end
end
end
return m3.determinant(t)
end
--[[#lua.wetgenes.tardis.m4.transpose
m4 = m4:transpose()
m4 = m4:transpose(r)
Transpose this m4.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.transpose(it,r)
r=r or it
return r:set(it[1],it[4+1],it[8+1],it[12+1], it[2],it[4+2],it[8+2],it[12+2], it[3],it[4+3],it[8+3],it[12+3], it[4],it[4+4],it[8+4],it[12+4])
end
--[[#lua.wetgenes.tardis.m4.scale
m4 = m4:scale(s)
m4 = m4:scale(s,r)
Scale this m4 by s.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.scale(it,s,r)
r=r or it
return r:set(
it[ 1]*s,it[ 2]*s,it[ 3]*s,it[ 4]*s,
it[ 5]*s,it[ 6]*s,it[ 7]*s,it[ 8]*s,
it[ 9]*s,it[10]*s,it[11]*s,it[12]*s,
it[13]*s,it[14]*s,it[15]*s,it[16]*s)
end
--[[#lua.wetgenes.tardis.m4.add
m4 = m4:add(m4b)
m4 = m4:add(m4b,r)
Add m4b this m4.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.add(it,m,r)
r=r or it
return r:set(
it[ 1]+m[ 1],it[ 2]+m[ 2],it[ 3]+m[ 3],it[ 4]+m[ 4],
it[ 5]+m[ 5],it[ 6]+m[ 6],it[ 7]+m[ 7],it[ 8]+m[ 8],
it[ 9]+m[ 9],it[10]+m[10],it[11]+m[11],it[12]+m[12],
it[13]+m[13],it[14]+m[14],it[15]+m[15],it[16]+m[16])
end
--[[#lua.wetgenes.tardis.m4.sub
m4 = m4:sub(m4b)
m4 = m4:sub(m4b,r)
Subtract m4b this m4.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.sub(it,m,r)
r=r or it
return r:set(
it[ 1]-m[ 1],it[ 2]-m[ 2],it[ 3]-m[ 3],it[ 4]-m[ 4],
it[ 5]-m[ 5],it[ 6]-m[ 6],it[ 7]-m[ 7],it[ 8]-m[ 8],
it[ 9]-m[ 9],it[10]-m[10],it[11]-m[11],it[12]-m[12],
it[13]-m[13],it[14]-m[14],it[15]-m[15],it[16]-m[16])
end
--[[#lua.wetgenes.tardis.m4.lerp
m4 = m4:lerp(m4b,s)
m4 = m4:lerp(m4b,s,r)
Lerp from m4 to m4b by s.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.lerp(it,m,s,r)
r=r or m4.new()
r:set(m)
r:sub(it)
r:scale(s)
r:add(it)
return r
end
--[[#lua.wetgenes.tardis.m4.cofactor
m4 = m4:cofactor()
m4 = m4:cofactor(r)
Cofactor this m4.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.cofactor(it,r)
r=r or it
local t={}
for iy=1,4 do
for ix=1,4 do
local idx=iy*4+ix-4
if ((ix+iy)%2)==1 then
t[idx]=-m4.minor_xy(it,ix,iy)
else
t[idx]=m4.minor_xy(it,ix,iy)
end
end
end
return r:set(t)
end
--[[#lua.wetgenes.tardis.m4.adjugate
m4 = m4:adjugate()
m4 = m4:adjugate(r)
Adjugate this m4.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.adjugate(it,r)
r=r or it
return m4.cofactor(m4.transpose(it,m4.new()),r)
end
--[[#lua.wetgenes.tardis.m4.inverse
m4 = m4:inverse()
m4 = m4:inverse(r)
Inverse this m4.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.inverse(it,r)
r=r or it
local ood=1/m4.determinant(it)
return m4.scale(m4.cofactor(m4.transpose(it,m4.new())),ood,r)
end
--[[#lua.wetgenes.tardis.m4.translate
m4 = m4:translate(x,y,z)
m4 = m4:translate(x,y,z,r)
m4 = m4:translate(v3)
m4 = m4:translate(v3,r)
Translate this m4 along its local axis by {x,y,z} or v3.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.translate(it,a,b,c,d)
local v3a,r
if type(a)=="number" then v3a=tardis.v3.new(a,b,c) r=d else v3a=a r=b end
r=r or it
local r1=it[12+1]+v3a[1]*it[1]+v3a[2]*it[5]+v3a[3]*it[9]
local r2=it[12+2]+v3a[1]*it[2]+v3a[2]*it[6]+v3a[3]*it[10]
local r3=it[12+3]+v3a[1]*it[3]+v3a[2]*it[7]+v3a[3]*it[11]
local r4=it[12+4]+v3a[1]*it[4]+v3a[2]*it[8]+v3a[3]*it[12]
return r:set(it[1],it[2],it[3],it[4], it[5],it[6],it[7],it[8], it[9],it[10],it[11],it[12], r1,r2,r3,r4 )
end
--[[#lua.wetgenes.tardis.m4.scale_v3
m4 = m4:scale_v3(x,y,z)
m4 = m4:scale_v3(x,y,z,r)
m4 = m4:scale_v3(v3)
m4 = m4:scale_v3(v3,r)
Scale this m4 by {x,y,z} or v3.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.scale_v3(it,a,b,c,d)
local v3a,r
if type(a)~="number" then v3a=tardis.v3.new(a,b,c) r=d else v3a=a r=b end
r=r or it
local s1=v3a[1]
local s2=v3a[2]
local s3=v3a[3]
return r:set( s1*it[1], s1*it[2], s1*it[3], s1*it[4],
s2*it[5], s2*it[6], s2*it[7], s2*it[8],
s3*it[9], s3*it[10], s3*it[11], s3*it[12],
it[13], it[14], it[15], it[16] )
end
--[[#lua.wetgenes.tardis.m4.scale_v3
v3 = m4:scale_v3(x,y,z)
v3 = m4:scale_v3(x,y,z,r)
v3 = m4:scale_v3(v3)
v3 = m4:scale_v3(v3,r)
Get v3 scale from a scale/rot/trans matrix
If r is provided then the result is written into r and returned
otherwise a new v3 is created and returned.
]]
function m4.get_scale_v3(it,r)
r=r or tardis.v3.new()
return r:set(
math.sqrt(it[1]*it[1]+it[5]*it[5]+it[ 9]*it[ 9]),
math.sqrt(it[2]*it[2]+it[6]*it[6]+it[10]*it[10]),
math.sqrt(it[3]*it[3]+it[7]*it[7]+it[11]*it[11])
)
end
--[[#lua.wetgenes.tardis.m4.setrot
m4 = m4:setrot(degrees,v3a)
Set this matrix to a rotation matrix around the given normal.
]]
function m4.setrot(it,degrees,v3a)
local c=math.cos(-math.pi*degrees/180)
local cc=1-c
local s=math.sin(-math.pi*degrees/180)
local x=v3a[1]
local y=v3a[2]
local z=v3a[3]
local delta=0.001 -- a smallish number
local dd=( (x*x) + (y*y) + (z*z) )
if ( dd < (1-delta) ) or ( dd > (1+delta) ) then -- not even close to a unit vector
local d=math.sqrt(dd)
x=x/d
y=y/d
z=z/d
end
return it:set(
x*x*cc+c , x*y*cc-z*s , x*z*cc+y*s , 0 ,
x*y*cc+z*s , y*y*cc+c , y*z*cc-x*s , 0 ,
x*z*cc-y*s , y*z*cc+x*s , z*z*cc+c , 0 ,
0 , 0 , 0 , 1 )
end
--[[#lua.wetgenes.tardis.m4.rotate
m4 = m4:rotate(degrees,v3a)
m4 = m4:rotate(degrees,v3a,r)
Apply a rotation to this matrix.
If r is provided then the result is written into r and returned
otherwise m4 is modified and returned.
]]
function m4.rotate(it,degrees,v3a,r)
local m4a=m4.new():setrot(degrees,v3a)
return tardis.m4_product_m4(it,m4a,r)
end
--[[#lua.wetgenes.tardis.v2
The metatable for a 2d vector class, use the new function to actually
create an object.
We also inherit all the functions from tardis.array
]]
local v2=tardis.class("v2",array)
--[[#lua.wetgenes.tardis.v2.new
v2 = tardis.v2.new()
Create a new v2 and optionally set it to the given values, v2 methods
usually return the input v2 for easy function chaining.
]]
function v2.new(...) return setmetatable({0,0},v2):set(...) end
--[[#lua.wetgenes.tardis.v2.identity
v2 = v2:identity()
Set this v2 to all zeros.
]]
function v2.identity(it) return it:set(0,0) end
--[[#lua.wetgenes.tardis.v2.lenlen
value = v2:lenlen()
Returns the length of this vector, squared, this is often all you need
for comparisons so lets us skip the sqrt.
]]
function v2.lenlen(it)
return (it[1]*it[1]) + (it[2]*it[2])
end
--[[#lua.wetgenes.tardis.v2.len
value = v2:len()
Returns the length of this vector.
]]
function v2.len(it)
return math.sqrt( (it[1]*it[1]) + (it[2]*it[2]) )
end
--[[#lua.wetgenes.tardis.v2.oo
v2 = v2:oo()
v2 = v2:oo(r)
One Over value. Build the reciprocal of all elements.
If r is provided then the result is written into r and returned
otherwise v2 is modified and returned.
]]
function v2.oo(it,r)
r=r or it
return r:set( 1/it[1] , 1/it[2] )
end
--[[#lua.wetgenes.tardis.v2.scale
v2 = v2:scale(s)
v2 = v2:scale(s,r)
Scale this v2 by s.
If r is provided then the result is written into r and returned
otherwise v2 is modified and returned.
]]
function v2.scale(it,s,r)
r=r or it
return r:set( it[1]*s , it[2]*s )
end
--[[#lua.wetgenes.tardis.v2.normalize
v2 = v2:normalize()
v2 = v2:normalize(r)
Adjust the length of this vector to 1.
If r is provided then the result is written into r and returned
otherwise v2 is modified and returned.
]]
function v2.normalize(it,r)
return v2.scale(it,1/v2.len(it),r)
end
--[[#lua.wetgenes.tardis.v2.add
v2 = v2:add(v2b)
v2 = v2:add(v2b,r)
Add v2b to v2.
If r is provided then the result is written into r and returned
otherwise v2 is modified and returned.
]]
function v2.add(va,vb,r)
r=r or va
return r:set( va[1]+vb[1] , va[2]+vb[2] )
end
--[[#lua.wetgenes.tardis.v2.sub
v2 = v2:sub(v2b)
v2 = v2:sub(v2b,r)
Subtract v2b from v2.
If r is provided then the result is written into r and returned
otherwise v2 is modified and returned.
]]
function v2.sub(va,vb,r)
r=r or va
return r:set( va[1]-vb[1] , va[2]-vb[2] )
end
--[[#lua.wetgenes.tardis.v2.mul
v2 = v2:mul(v2b)
v2 = v2:mul(v2b,r)
Multiply v2 by v2b.
If r is provided then the result is written into r and returned
otherwise v2 is modified and returned.
]]
function v2.mul(va,vb,r)
r=r or va
return r:set( (va[1]*vb[1]) , (va[2]*vb[2]) )
end
--[[#lua.wetgenes.tardis.v2.dot
value = v2:dot(v2b)
Return the dot product of these two vectors.
]]
function v2.dot(va,vb)
return ( (va[1]*vb[1]) + (va[2]*vb[2]) )
end
--[[#lua.wetgenes.tardis.v2.cross
value = v2:cross(v2b)
Extend to 3d then only return z value as x and y are always 0
]]
function v2.cross(va,vb)
return (va[1]*vb[2])-(va[2]*vb[1])
end
--[[#lua.wetgenes.tardis.v3
The metatable for a 3d vector class, use the new function to actually
create an object.
We also inherit all the functions from tardis.array
]]
local v3=tardis.class("v3",array)
--[[#lua.wetgenes.tardis.v3.new
v3 = tardis.v3.new()
Create a new v3 and optionally set it to the given values, v3 methods
usually return the input v3 for easy function chaining.
]]
function v3.new(...) return setmetatable({0,0,0},v3):set(...) end
--[[#lua.wetgenes.tardis.v3.identity
v3 = v3:identity()
Set this v3 to all zeros.
]]
function v3.identity(it) return it:set(0,0,0) end
--[[#lua.wetgenes.tardis.v3.lenlen
value = v3:lenlen()
Returns the length of this vector, squared, this is often all you need
for comparisons so lets us skip the sqrt.
]]
function v3.lenlen(it)
return (it[1]*it[1]) + (it[2]*it[2]) + (it[3]*it[3])
end
--[[#lua.wetgenes.tardis.v3.len
value = v3:len()
Returns the length of this vector.
]]
function v3.len(it)
return math.sqrt( (it[1]*it[1]) + (it[2]*it[2]) + (it[3]*it[3]) )
end
--[[#lua.wetgenes.tardis.v3.oo
v3 = v3:oo()
v3 = v3:oo(r)
One Over value. Build the reciprocal of all elements.
If r is provided then the result is written into r and returned
otherwise v3 is modified and returned.
]]
function v3.oo(it,r)
r=r or it
return r:set( 1/it[1] , 1/it[2] , 1/it[3] )
end
--[[#lua.wetgenes.tardis.v3.scale
v3 = v3:scale(s)
v3 = v3:scale(s,r)
Scale this v3 by s.
If r is provided then the result is written into r and returned
otherwise v3 is modified and returned.
]]
function v3.scale(it,s,r)
r=r or it
return r:set( it[1]*s , it[2]*s , it[3]*s )
end
--[[#lua.wetgenes.tardis.v3.normalize
v3 = v3:normalize()
v3 = v3:normalize(r)
Adjust the length of this vector to 1.
If r is provided then the result is written into r and returned
otherwise v3 is modified and returned.
]]
function v3.normalize(it,r)
return v3.scale(it,1/v3.len(it),r)
end
--[[#lua.wetgenes.tardis.v3.add
v3 = v3:add(v3b)
v3 = v3:add(v3b,r)
Add v3b to v3.
If r is provided then the result is written into r and returned
otherwise v3 is modified and returned.
]]
function v3.add(va,vb,r)
r=r or va
return r:set( va[1]+vb[1] , va[2]+vb[2] , va[3]+vb[3] )
end
--[[#lua.wetgenes.tardis.v3.sub
v3 = v3:sub(v3b)
v3 = v3:sub(v3b,r)
Subtract v3b from v3.
If r is provided then the result is written into r and returned
otherwise v3 is modified and returned.
]]
function v3.sub(va,vb,r)
r=r or va
return r:set( va[1]-vb[1] , va[2]-vb[2] , va[3]-vb[3] )
end
--[[#lua.wetgenes.tardis.v3.mul
v3 = v3:mul(v3b)
v3 = v3:mul(v3b,r)
Multiply v3 by v3b.
If r is provided then the result is written into r and returned
otherwise v3 is modified and returned.
]]
function v3.mul(va,vb,r)
r=r or va
return r:set( (va[1]*vb[1]) , (va[2]*vb[2]) , (va[3]*vb[3]) )
end
--[[#lua.wetgenes.tardis.v3.dot
value = v3:dot(v3b)
Return the dot product of these two vectors.
]]
function v3.dot(va,vb)
return ( (va[1]*vb[1]) + (va[2]*vb[2]) + (va[3]*vb[3]) )
end
--[[#lua.wetgenes.tardis.v3.cross
v2 = v2:dot(v2b)
v2 = v2:dot(v2b,r)
Return the cross product of these two vectors.
If r is provided then the result is written into r and returned
otherwise v3 is modified and returned.
]]
function v3.cross(va,vb,r)
r=r or va
return r:set( (va[2]*vb[3])-(va[3]*vb[2]) , (va[3]*vb[1])-(va[1]*vb[3]) , (va[1]*vb[2])-(va[2]*vb[1]) )
end
--[[#lua.wetgenes.tardis.v4
The metatable for a 4d vector class, use the new function to actually
create an object.
We also inherit all the functions from tardis.array
]]
local v4=tardis.class("v4",array)
--[[#lua.wetgenes.tardis.v4.new
v4 = tardis.v4.new()
Create a new v4 and optionally set it to the given values, v4 methods
usually return the input v4 for easy function chaining.
]]
function v4.new(...) return setmetatable({0,0,0,0},v4):set(...) end
--[[#lua.wetgenes.tardis.v4.identity
v4 = v4:identity()
Set this v4 to all zeros.
]]
function v4.identity(it) return it:set(0,0,0,0) end
--[[#lua.wetgenes.tardis.v4.to_v3
v3 = v4:to_v3()
v3 = v4:to_v3(r)
scale [4] to 1 then throw it away so we have a v3 xyz
If r is provided then the result is written into r and returned
otherwise a new v3 is created and returned.
]]
function v4.to_v3(it,r)
r=r or v3.new()
local oow=1/it[4]
return r:set( it[1]*oow , it[2]*oow , it[3]*oow )
end
--[[#lua.wetgenes.tardis.v4.lenlen
value = v4:lenlen()
Returns the length of this vector, squared, this is often all you need
for comparisons so lets us skip the sqrt.
]]
function v4.lenlen(it)
return (it[1]*it[1]) + (it[2]*it[2]) + (it[3]*it[3]) + (it[4]*it[4])
end
--[[#lua.wetgenes.tardis.v4.len
value = v4:len()
Returns the length of this vector.
]]
function v4.len(it)
return math.sqrt( (it[1]*it[1]) + (it[2]*it[2]) + (it[3]*it[3]) + (it[4]*it[4]) )
end
--[[#lua.wetgenes.tardis.v4.oo
v4 = v4:oo()
v4 = v4:oo(r)
One Over value. Build the reciprocal of all elements.
If r is provided then the result is written into r and returned
otherwise v4 is modified and returned.
]]
function v4.oo(it,r)
r=r or it
return r:set( 1/it[1] , 1/it[2] , 1/it[3] , 1/it[4] )
end
--[[#lua.wetgenes.tardis.v4.scale
v4 = v4:scale(s)
v4 = v4:scale(s,r)
Scale this v4 by s.
If r is provided then the result is written into r and returned
otherwise v4 is modified and returned.
]]
function v4.scale(it,s,r)
r=r or it
return r:set( it[1]*s , it[2]*s , it[3]*s , it[4]*s )
end
--[[#lua.wetgenes.tardis.v4.normalize
v4 = v4:normalize()
v4 = v4:normalize(r)
Adjust the length of this vector to 1.
If r is provided then the result is written into r and returned
otherwise v4 is modified and returned.
]]
function v4.normalize(it,r)
return v4.scale(it,1/v4.len(it),r)
end
--[[#lua.wetgenes.tardis.v4.add
v4 = v4:add(v4b)
v4 = v4:add(v4b,r)
Add v4b to v4.
If r is provided then the result is written into r and returned
otherwise v4 is modified and returned.
]]
function v4.add(va,vb,r)
r=r or va
return r:set( va[1]+vb[1] , va[2]+vb[2] , va[3]+vb[3] , va[4]+vb[4] )
end
--[[#lua.wetgenes.tardis.v4.sub
v4 = v4:sub(v4b)
v4 = v4:sub(v4b,r)
Subtract v4b from v4.
If r is provided then the result is written into r and returned
otherwise v4 is modified and returned.
]]
function v4.sub(va,vb,r)
r=r or va
return r:set( va[1]-vb[1] , va[2]-vb[2] , va[3]-vb[3] , va[4]-vb[4] )
end
--[[#lua.wetgenes.tardis.v4.mul
v4 = v4:mul(v4b)
v4 = v4:mul(v4b,r)
Multiply v4 by v4b.
If r is provided then the result is written into r and returned
otherwise v4 is modified and returned.
]]
function v4.mul(va,vb,r)
r=r or va
return r:set( (va[1]*vb[1]) , (va[2]*vb[2]) , (va[3]*vb[3]) , (va[4]*vb[4]) )
end
--[[#lua.wetgenes.tardis.v4.dot
value = v4:dot(v4b)
Return the dot product of these two vectors.
]]
function v4.dot(va,vb)
return ( (va[1]*vb[1]) + (va[2]*vb[2]) + (va[3]*vb[3]) + (va[4]*vb[4]) )
end
--[[#lua.wetgenes.tardis.q4
The metatable for a quaternion class, use the new function to actually create an object.
We also inherit all the functions from tardis.v4
]]
local q4=tardis.class("q4",v4)
--[[#lua.wetgenes.tardis.q4.new
q4 = tardis.q4.new()
Create a new q4 and optionally set it to the given values, q4 methods
usually return the input q4 for easy function chaining.
]]
function q4.new(...) return setmetatable({0,0,0,0},q4):set(...) end
--[[#lua.wetgenes.tardis.q4.identity
q4 = q4:identity()
Set this q4 to its 0,0,0,1 identity
]]
function q4.identity(it) return it:set(0,0,0,1) end
--[[#lua.wetgenes.tardis.q4.lerp
q4 = q4:lerp(q4b,s)
q4 = q4:lerp(q4b,s,r)
Nlerp from q4 to q4b by s.
If r is provided then the result is written into r and returned
otherwise q4 is modified and returned.
]]
function q4.nlerp(qa,qb,sa,r)
local sb=1-sa
if qa.dot(qb) < 0 then sa=-sa end -- shortest fix
r=r or va
r:set( va[1]*sa+vb[1]*sb , va[2]*sa+vb[2]*sb , va[3]*sa+vb[3]*sb , va[4]*sa+vb[4]*sb )
return r:normalize()
end
--[[#lua.wetgenes.tardis.q4.setrot
q4 = q4:setrot(degrees,v3a)
Set this matrix to a rotation matrix around the given normal.
]]
function q4.setrot(it,degrees,v3a)
local ah=degrees * (math.PI/360)
local sh=math.sin(ah)
return it:set( math.cos(ah) , v3a[1]*sh , v3a[2]*sh , v3a[3]*sh )
end
--[[#lua.wetgenes.tardis.q4.rotate
q4 = q4:rotate(degrees,v3a)
q4 = q4:rotate(degrees,v3a,r)
Apply a rotation to this quaternion.
If r is provided then the result is written into r and returned
otherwise q4 is modified and returned.
]]
function q4.rotate(it,degrees,v3a,r)
local q4a=q4.new():setrot(degrees,v3a)
return tardis.q4_product_q4(it,q4a,r)
end
--[[#lua.wetgenes.tardis.line
A 3d space line class.
[1]position , [2]normal
We also inherit all the functions from tardis.array
]]
local line=tardis.class("line",array)
line.set=nil -- disable
--[[#lua.wetgenes.tardis.line.new
line = tardis.line.new(p,n)
Create a new line and optionally set it to the given values.
]]
function line.new(p,n) return setmetatable({p or v3.new(),n or v3.new()},line) end
--[[#lua.wetgenes.tardis.plane
A 3d space plane class.
[1]position , [2]normal
We also inherit all the functions from tardis.array
]]
local plane=tardis.class("plane",array)
plane.set=nil -- disable
--[[#lua.wetgenes.tardis.plane.new
plane = tardis.plane.new(p,n)
Create a new plane and optionally set it to the given values.
]]
function plane.new(p,n) return setmetatable({p or v3.new(),n or v3.new()},plane) end
function tardis.line_intersect_plane(l,p,r)
r=r or v3.new()
local t=v3.new(p[1]):sub(l[1]) -- the line position relative to the plane
local d=l[2]:dot(p[2]) -- the length of the line until it hits the plane
if d~=0 then -- less errors please
d=t:dot(p[2])/d
end
return r:set( l[1][1]+(l[2][1]*d) , l[1][2]+(l[2][2]*d) , l[1][3]+(l[2][3]*d) ) -- the point of intersection
end
function tardis.q4_to_m4(q,m)
if not m then m=m4.new() end
local w,x,y,z=q[1],q[2],q[3],q[4]
local xx,xy,xz,xw=x*x,x*y,x*z,x*w
local yy,yz,yw= y*y,y*z,y*w
local zz,zw= z*z,z*w
return m:set(
1 - 2 * ( yy + zz ),
2 * ( xy - zw ),
2 * ( xz + yw ),0,
2 * ( xy + zw ),
1 - 2 * ( xx + zz ),
2 * ( yz - xw ),0,
2 * ( xz - yw ),
2 * ( yz + xw ),
1 - 2 * ( xx + yy ),0,
0,0,0,1 )
end
function tardis.q4_product_q4(q4a,q4b,r)
r=r or q4a
local r1 = q4b[1] * q4a[4] + q4b[2] * q4a[3] - q4b[3] * q4a[2] + q4b[4] * q4a[1];
local r2 = -q4b[1] * q4a[3] + q4b[2] * q4a[4] + q4b[3] * q4a[1] + q4b[4] * q4a[2];
local r3 = q4b[1] * q4a[2] - q4b[2] * q4a[1] + q4b[3] * q4a[4] + q4b[4] * q4a[3];
local r4 = -q4b[1] * q4a[1] - q4b[2] * q4a[2] - q4b[3] * q4a[3] + q4b[4] * q4a[4];
return r:set(r1,r2,r3,r4)
end
function tardis.v3_product_q4(v3,q4,r)
r=r or v3
local r1 = q4[2] * v3[3] - q4[3] * v3[2] + q4[4] * v3[1];
local r2 = -q4[1] * v3[3] + q4[3] * v3[1] + q4[4] * v3[2];
local r3 = q4[1] * v3[2] - q4[2] * v3[1] + q4[4] * v3[3];
return r:set(r1,r2,r3)
end
function tardis.v3_product_m4(v3,m4,r)
r=r or v3
local oow=1/( (m4[ 4]*v3[1]) + (m4[ 4+4]*v3[2]) + (m4[ 8+4]*v3[3]) + (m4[12+4] ) )
local r1= oow * ( (m4[ 1]*v3[1]) + (m4[ 4+1]*v3[2]) + (m4[ 8+1]*v3[3]) + (m4[12+1] ) )
local r2= oow * ( (m4[ 2]*v3[1]) + (m4[ 4+2]*v3[2]) + (m4[ 8+2]*v3[3]) + (m4[12+2] ) )
local r3= oow * ( (m4[ 3]*v3[1]) + (m4[ 4+3]*v3[2]) + (m4[ 8+3]*v3[3]) + (m4[12+3] ) )
return r:set(r1,r2,r3)
end
function tardis.v4_product_m4(v4,m4,r)
r=r or v4
local r1= ( (m4[ 1]*v4[1]) + (m4[ 4+1]*v4[2]) + (m4[ 8+1]*v4[3]) + (m4[12+1]*v4[4]) )
local r2= ( (m4[ 2]*v4[1]) + (m4[ 4+2]*v4[2]) + (m4[ 8+2]*v4[3]) + (m4[12+2]*v4[4]) )
local r3= ( (m4[ 3]*v4[1]) + (m4[ 4+3]*v4[2]) + (m4[ 8+3]*v4[3]) + (m4[12+3]*v4[4]) )
local r4= ( (m4[ 4]*v4[1]) + (m4[ 4+4]*v4[2]) + (m4[ 8+4]*v4[3]) + (m4[12+4]*v4[4]) )
return r:set(r1,r2,r3,r4)
end
function tardis.m4_product_m4(m4a,m4b,r)
r=r or m4a
local r1 = (m4b[ 1]*m4a[ 1]) + (m4b[ 2]*m4a[ 4+1]) + (m4b[ 3]*m4a[ 8+1]) + (m4b[ 4]*m4a[12+1])
local r2 = (m4b[ 1]*m4a[ 2]) + (m4b[ 2]*m4a[ 4+2]) + (m4b[ 3]*m4a[ 8+2]) + (m4b[ 4]*m4a[12+2])
local r3 = (m4b[ 1]*m4a[ 3]) + (m4b[ 2]*m4a[ 4+3]) + (m4b[ 3]*m4a[ 8+3]) + (m4b[ 4]*m4a[12+3])
local r4 = (m4b[ 1]*m4a[ 4]) + (m4b[ 2]*m4a[ 4+4]) + (m4b[ 3]*m4a[ 8+4]) + (m4b[ 4]*m4a[12+4])
local r5 = (m4b[ 4+1]*m4a[ 1]) + (m4b[ 4+2]*m4a[ 4+1]) + (m4b[ 4+3]*m4a[ 8+1]) + (m4b[ 4+4]*m4a[12+1])
local r6 = (m4b[ 4+1]*m4a[ 2]) + (m4b[ 4+2]*m4a[ 4+2]) + (m4b[ 4+3]*m4a[ 8+2]) + (m4b[ 4+4]*m4a[12+2])
local r7 = (m4b[ 4+1]*m4a[ 3]) + (m4b[ 4+2]*m4a[ 4+3]) + (m4b[ 4+3]*m4a[ 8+3]) + (m4b[ 4+4]*m4a[12+3])
local r8 = (m4b[ 4+1]*m4a[ 4]) + (m4b[ 4+2]*m4a[ 4+4]) + (m4b[ 4+3]*m4a[ 8+4]) + (m4b[ 4+4]*m4a[12+4])
local r9 = (m4b[ 8+1]*m4a[ 1]) + (m4b[ 8+2]*m4a[ 4+1]) + (m4b[ 8+3]*m4a[ 8+1]) + (m4b[ 8+4]*m4a[12+1])
local r10= (m4b[ 8+1]*m4a[ 2]) + (m4b[ 8+2]*m4a[ 4+2]) + (m4b[ 8+3]*m4a[ 8+2]) + (m4b[ 8+4]*m4a[12+2])
local r11= (m4b[ 8+1]*m4a[ 3]) + (m4b[ 8+2]*m4a[ 4+3]) + (m4b[ 8+3]*m4a[ 8+3]) + (m4b[ 8+4]*m4a[12+3])
local r12= (m4b[ 8+1]*m4a[ 4]) + (m4b[ 8+2]*m4a[ 4+4]) + (m4b[ 8+3]*m4a[ 8+4]) + (m4b[ 8+4]*m4a[12+4])
local r13= (m4b[12+1]*m4a[ 1]) + (m4b[12+2]*m4a[ 4+1]) + (m4b[12+3]*m4a[ 8+1]) + (m4b[12+4]*m4a[12+1])
local r14= (m4b[12+1]*m4a[ 2]) + (m4b[12+2]*m4a[ 4+2]) + (m4b[12+3]*m4a[ 8+2]) + (m4b[12+4]*m4a[12+2])
local r15= (m4b[12+1]*m4a[ 3]) + (m4b[12+2]*m4a[ 4+3]) + (m4b[12+3]*m4a[ 8+3]) + (m4b[12+4]*m4a[12+3])
local r16= (m4b[12+1]*m4a[ 4]) + (m4b[12+2]*m4a[ 4+4]) + (m4b[12+3]*m4a[ 8+4]) + (m4b[12+4]*m4a[12+4])
return r:set(r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16)
end
--
-- build a simple field of view GL projection matrix designed to work in 2d or 3d and keep the numbers
-- easy for 2d positioning.
--
-- setting aspect to 640,480 and fov of 1 would mean at a z depth of 240 (which is y/2) then your view area would be
-- -320 to +320 in the x and -240 to +240 in the y.
--
-- fov is a tan like value (a view size inverse scalar) so 1 would be 90deg, 0.5 would be 45deg and so on
--
-- the depth parameter is only used to limit the range of the zbuffer so it covers 0 to depth
--
-- The following would be a reasonable default for an assumed 640x480 display.
--
-- m4_project23d(w,h,640,480,0.5,1024)
--
-- then at z=480 we would have one to one pixel scale...
-- the total view area volume from there would be -320 +320 , -240 +240 , -480 +(1024-480)
--
-- view_width and view_height must be the current width and height of the display in pixels or nil
-- we use this to work out where to place our view such that it is always visible and keeps its aspect.
--
function tardis.m4_project23d(view_width,view_height,width,height,fov,depth)
local aspect=height/width
local m=m4.new()
local f=depth
local n=1
local win_aspect=((view_height or height)/(view_width or width))
if (win_aspect > (aspect) ) then -- fit width to screen
m[1] = ((aspect)*1)/fov
m[6] = -((aspect)/win_aspect)/fov
else -- fit height to screen
m[1] = win_aspect/fov
m[6] = -1/fov
end
m[11] = -(f+n)/(f-n)
m[12] = -1
m[15] = -2*f*n/(f-n)
return m
end
tardis.f32=require("wetgenes.tardis.core") -- use a "faster?" f32 C core
if not DISABLE_WETGENES_TARDIS_CORE then -- set this global to true before first use to disable use of tardis f32 core
--upgrade the above to hopefully faster C versions working on 16byte aligned userdata arrays of floats
local tcore=tardis.f32
-- allow read/write with magical [] lookups
function array.__len(it) return 1 end
function array.__index(it,n) return array[n] or tcore.read(it,n) end
function array.__newindex(it,n,v) tcore.write(it,n,v) end
function m2.new(...) return tcore.alloc(4* 4,m2):set(...) end
function m3.new(...) return tcore.alloc(4* 9,m3):set(...) end
function m4.new(...) return tcore.alloc(4*16,m4):set(...) end
function m2.__len(it) return 4 end
function m3.__len(it) return 9 end
function m4.__len(it) return 16 end
function m2.__index(it,n) return m2[n] or tcore.read(it,n) end
function m3.__index(it,n) return m3[n] or tcore.read(it,n) end
function m4.__index(it,n) return m4[n] or tcore.read(it,n) end
m2.__newindex=array.__newindex
m3.__newindex=array.__newindex
m4.__newindex=array.__newindex
function v2.new(...) return tcore.alloc(4* 2,v2):set(...) end
function v3.new(...) return tcore.alloc(4* 3,v3):set(...) end
function v4.new(...) return tcore.alloc(4* 4,v4):set(...) end
function q4.new(...) return tcore.alloc(4* 4,q4):set(...) end
function v2.__len(it) return 2 end
function v3.__len(it) return 3 end
function v4.__len(it) return 4 end
function q4.__len(it) return 4 end
function v2.__index(it,n) return v2[n] or tcore.read(it,n) end
function v3.__index(it,n) return v3[n] or tcore.read(it,n) end
function v4.__index(it,n) return v4[n] or tcore.read(it,n) end
function q4.__index(it,n) return q4[n] or tcore.read(it,n) end
v2.__newindex=array.__newindex
v3.__newindex=array.__newindex
v4.__newindex=array.__newindex
q4.__newindex=array.__newindex
-- replace some functions with C code
tardis.m4_product_m4 = tcore.m4_product_m4
tardis.v4_product_m4 = tcore.v4_product_m4
m4.identity = tcore.m4_identity
m4.rotate = tcore.m4_rotate
m4.scale_v3 = tcore.m4_scale_v3
m4.scale = tcore.m4_scale
m4.translate = tcore.m4_translate
end
|
--imports--
local cqueues = require"cqueues"
local util = require"novus.util"
local promise = require"cqueues.promise"
local interposable = require"novus.client.interposable"
local debugger,traceback = debug.debug, debug.traceback
local xpcall = xpcall
local ipairs = ipairs
local insert = table.insert
local sleep = cqueues.sleep
local should_debug = os.getenv"NOVUS_DEBUG" == 1
--start-module--
local _ENV = {}
function client(_ENV) --luacheck:ignore
_ENV = interposable(_ENV)
cqueues.interpose('novus', function(self)
return clients[self]
end)
in_use = {}
function do_loop(id, loop, cli)
while not loop:empty() and cli.alive do
local ok, err = loop:step()
if not ok then util.warn("%s loop.step: " .. err, id)
if id == 'main' then
util.fatal('main loop had error!')
end
end
end
in_use[loop] = nil
util.warn("Terminating loop-%s", id)
end
cqueues.interpose('novus_associate', function(self, client, id)
clients[self] = client
if client.loops[id] ~= nil then
util.fatal("Client-%s has conflicting controller ids; %s is already set.", client.id, id)
end
client.loops[id] = self
end)
cqueues.interpose('novus_start', function(self, id)
local client = clients[self]
if client.loops.main and id ~= 'main' and not in_use[self] then
in_use[self] = true
client.loops.main:wrap(do_loop, id, self, client)
end
end)
cqueues.interpose('novus_dispatch', function(self, s, E, ...)
local cli = clients[self]
local ev = cli and cli.dispatch[E]
return ev and self:wrap(ev, cli, s, E, ...)
end)
local function err_handler(...)
if should_debug then
debugger()
end
return traceback(...)
end
local old_wrap
old_wrap = cqueues.interpose('wrap', function(self, ...)
return old_wrap(self, function(fn, ...)
local s, e = xpcall(fn, err_handler, ...)
if not s then
util.error(e)
end
end, ...)
end)
function promise.race(...)
local promises = {...}
local results
repeat
results = {}
for _, prom in ipairs(promises) do
if prom:status() ~= "pending" then
insert(results, prom)
end
end
sleep()
until #results > 0
return results
end
return _ENV
end
--end-module--
return _ENV |
local mod = DBM:NewMod(1235, "DBM-Party-WoD", 4, 558)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 15007 $"):sub(12, -3))
mod:SetCreatureID(81297, 81305)
mod:SetEncounterID(1749)
mod:SetZone()
mod:SetBossHPInfoToHighest(false)
mod:RegisterCombat("combat")
mod:SetBossHealthInfo(81297)
mod:RegisterEventsInCombat(
"SPELL_AURA_APPLIED 164426 164835 164632",
"SPELL_AURA_REMOVED 164426",
"UNIT_SPELLCAST_SUCCEEDED boss1",
"UNIT_TARGETABLE_CHANGED",
"UNIT_DIED"
)
local warnNokgar = mod:NewSpellAnnounce("ej10433", 3, "Interface\\ICONS\\INV_Misc_Head_Orc_01.blp")
local warnBurningArrows = mod:NewSpellAnnounce(164635, 3)
local warnRecklessProvocation = mod:NewTargetAnnounce(164426, 3)
local warnEnrage = mod:NewSpellAnnounce(164835, 3, nil, "RemoveEnrage|Tank")
local specWarnBurningArrows = mod:NewSpecialWarningSpell(164635, nil, nil, nil, 2)
local specWarnBurningArrowsMove = mod:NewSpecialWarningMove(164635, nil, nil, nil, 1, 2)
local specWarnRecklessProvocation = mod:NewSpecialWarningReflect(164426, nil, nil, nil, 1, 2)
local specWarnRecklessProvocationEnd = mod:NewSpecialWarningEnd(164426)
local specWarnEnrage = mod:NewSpecialWarningDispel(164835, "RemoveEnrage", nil, nil, 1, 2)
local timerRecklessProvocation = mod:NewBuffActiveTimer(5, 164426)
--local timerBurningArrowsCD = mod:NewNextTimer(25, 164635)--25~42 variable (patterned?)
local voiceRecklessProvocation = mod:NewVoice(164426)
local voiceEnrage = mod:NewVoice(164835, "RemoveEnrage")
local voiceBurningArrows = mod:NewVoice(164632)
function mod:SPELL_AURA_APPLIED(args)
if args.spellId == 164426 then
warnRecklessProvocation:Show(args.destName)
specWarnRecklessProvocation:Show(args.destName)
timerRecklessProvocation:Start()
voiceRecklessProvocation:Play("stopattack")
elseif args.spellId == 164835 and self:AntiSpam(2, 1) then
warnEnrage:Show()
specWarnEnrage:Show(args.destName)
voiceEnrage:Play("trannow") --multi sound
elseif args.spellId == 164632 and args:IsPlayer() and self:AntiSpam(2, 2) then
specWarnBurningArrowsMove:Show()
voiceBurningArrows:Play("runaway")
end
end
function mod:SPELL_AURA_REMOVED(args)
if args.spellId == 164426 then
specWarnRecklessProvocationEnd:Show()
end
end
--Not detectable in phase 1. Seems only cleanly detectable in phase 2, in phase 1 boss has no "boss" unitid so cast hidden.
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId)
if spellId == 164635 then
warnBurningArrows:Show()
specWarnBurningArrows:Show()
--timerBurningArrowsCD:Start()
end
end
function mod:UNIT_TARGETABLE_CHANGED()
warnNokgar:Show()
if DBM.BossHealth:IsShown() then
DBM.BossHealth:AddBoss(81305)
end
end
function mod:UNIT_DIED(args)
if not DBM.BossHealth:IsShown() then return end
local cid = self:GetCIDFromGUID(args.destGUID)
if cid == 81297 then
DBM.BossHealth:RemoveBoss(81297)
end
end
|
local packages = script.Parent.Parent.Parent
local synthetic = require(script.Parent.Parent)
local util = require(script.Parent.Parent:WaitForChild("Util"))
local fusion = util.initFusion(require(packages:WaitForChild('fusion')))
local maidConstructor = require(packages:WaitForChild('maid'))
local typographyConstructor = require(packages:WaitForChild('typography'))
local enums = require(script.Parent.Parent:WaitForChild("Enums"))
local effects = require(script.Parent.Parent:WaitForChild("Effects"))
local constructor = {}
function constructor.new(params)
--public states
local public = {
Typography = util.import(params.Typography) or typographyConstructor.new(Enum.Font.SourceSans, 10, 14),
Text = util.import(params.Text) or fusion.State(""),
BackgroundColor = util.import(params.BackgroundColor) or fusion.State(Color3.fromRGB(35,47,52)),
TextColor = util.import(params.TextColor) or fusion.State(Color3.fromHex("#FFFFFF")),
Position = util.import(params.Position) or fusion.State(UDim2.new(0.5,0.5)),
SynthClassName = fusion.Computed(function()
return script.Name
end),
}
local _Padding, _TextSize, _Font = util.getTypographyStates(public.Typography)
--construct
return util.set(fusion.New "TextLabel", public, params, {
AnchorPoint = Vector2.new(0.5,0.5),
AutomaticSize = Enum.AutomaticSize.X,
Size = util.tween(fusion.Computed(function()
local ts = _TextSize:get()
return UDim2.fromOffset(ts, ts)
end)),
Font = fusion.Computed(function()
return public.Typography:get().Font
end),
BackgroundColor3 = util.tween(public.BackgroundColor),
Position = public.Position,
TextColor3 = util.tween(public.TextColor),
Text = public.Text,
[fusion.Children] = {
fusion.New "UICorner" {
CornerRadius = util.cornerRadius,
},
fusion.New 'UIPadding' {
PaddingBottom = _Padding,
PaddingTop = _Padding,
PaddingLeft = fusion.Computed(function()
local offset = _Padding:get().Offset
return UDim.new(0,offset*0.5)
end),
PaddingRight = fusion.Computed(function()
local offset = _Padding:get().Offset
return UDim.new(0,offset*0.5)
end),
},
}
})
end
return constructor |
---------------------------------
--! @file OutPortPullConnector.lua
--! @brief Pullๅ้ไฟกOutPortConnectorๅฎ็พฉ
---------------------------------
--[[
Copyright (c) 2017 Nobuhiko Miyamoto
]]
local OutPortPullConnector= {}
--_G["openrtm.OutPortPullConnector"] = OutPortPullConnector
local OutPortConnector = require "openrtm.OutPortConnector"
local DataPortStatus = require "openrtm.DataPortStatus"
local CdrBufferBase = require "openrtm.CdrBufferBase"
local CdrBufferFactory = CdrBufferBase.CdrBufferFactory
local OutPortProvider = require "openrtm.OutPortProvider"
local OutPortProviderFactory = OutPortProvider.OutPortProviderFactory
local ConnectorListener = require "openrtm.ConnectorListener"
local ConnectorListenerType = ConnectorListener.ConnectorListenerType
-- Pullๅ้ไฟกOutPortConnectorใฎๅๆๅ
-- @param info ใใญใใกใคใซ
-- ใbufferใใจใใ่ฆ็ด ๅใซใใใใกใฎ่จญๅฎใๆ ผ็ด
-- @param provider ใใญใใคใ
-- @param listeners ใณใผใซใใใฏ
-- @param buffer ใใใใก
-- ๆๅฎใใชใๅ ดๅใฏใชใณใฐใใใใกใ็ๆใใ
-- @return Pullๅ้ไฟกOutPortConnector
OutPortPullConnector.new = function(info, provider, listeners, buffer)
local obj = {}
setmetatable(obj, {__index=OutPortConnector.new(info)})
-- ใใผใฟๆธใ่พผใฟ
-- @param data data._dataใๆธใ่พผใฟ
-- @return ใชใฟใผใณใณใผใ(ใใใใกใฎๆธใ่พผใฟ็ตๆใซใใ)
function obj:write(data)
local Manager = require "openrtm.Manager"
local cdr_data = Manager:instance():cdrMarshal(data._data, data._type)
--print(cdr_data)
if self._buffer ~= nil then
self._buffer:write(cdr_data)
else
return DataPortStatus.UNKNOWN_ERROR
end
return DataPortStatus.PORT_OK
end
-- ใณใใฏใฟๅๆญ
-- @return ใชใฟใผใณใณใผใ
function obj:disconnect()
self._rtcout:RTC_TRACE("disconnect()")
self:onDisconnect()
if self._provider ~= nil then
OutPortProviderFactory:instance():deleteObject(self._provider)
self._provider:exit()
end
self._provider = nil
if self._buffer ~= nil then
CdrBufferFactory:instance():deleteObject(self._buffer)
end
self._buffer = nil
return DataPortStatus.PORT_OK
end
-- ใใใใกๅๅพ
-- @return ใใใใก
function obj:getBuffer()
return self._buffer
end
-- ใขใฏใใฃใๅ
function obj:activate()
end
-- ้ใขใฏใใฃใๅ
function obj:deactivate()
end
-- ใใใใกไฝๆ
-- ใชใณใฐใใใใกใ็ๆใใ
-- @param profile ใณใใฏใฟใใญใใกใคใซ
-- @return ใใใใก
function obj:createBuffer(info)
local buf_type = info.properties:getProperty("buffer_type","ring_buffer")
return CdrBufferFactory:instance():createObject(buf_type)
end
-- ใณใใฏใฟๆฅ็ถๆใฎใณใผใซใใใฏๅผใณๅบใ
function obj:onConnect()
if self._listeners ~= nil and self._profile ~= nil then
self._listeners.connector_[ConnectorListenerType.ON_CONNECT]:notify(self._profile)
end
end
-- ใณใใฏใฟๅๆญๆใฎใณใผใซใใใฏๅผใณๅบใ
function obj:onDisconnect()
if self._listeners ~= nil and self._profile ~= nil then
self._listeners.connector_[ConnectorListenerType.ON_DISCONNECT]:notify(self._profile)
end
end
obj._provider = provider
obj._listeners = listeners
obj._buffer = buffer
obj._inPortListeners = nil
obj._value = nil
if obj._buffer == nil then
obj._buffer = obj:createBuffer(info)
end
if obj._provider == nil or obj._buffer == nil then
obj._rtcout:RTC_ERROR("Exeption: in OutPortPullConnector.__init__().")
error("")
end
obj._buffer:init(info.properties:getNode("buffer"))
obj._provider:init(info.properties)
obj._provider:setBuffer(obj._buffer)
obj._provider:setConnector(obj)
obj._provider:setListener(info, obj._listeners)
obj:onConnect()
return obj
end
return OutPortPullConnector
|
-- Copyright (c) 2019 Cable Television Laboratories, Inc.
-- 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.
-- This Wireshark plugin outputs the TPS Telemetry Report & INT packets
-- Declare our protocols
tps_udp_proto = Proto("TPS_INT", "TPS UDP INT Protocol")
tps_trpt_proto = Proto("TRPT_INT", "Transparency Report UDP INT Protocol")
function octet_to_mac(buff)
local addr = ""
for i = 0,5,1
do
local octect = buff(i, 1):uint()
--noinspection StringConcatenationInLoops
addr = addr .. string.format("%02X", octect)
if i < 5
then
--noinspection StringConcatenationInLoops
addr = addr .. ":"
end
end
return addr
end
function tps_int_shim(int_tree, shim_buf)
-- UDP INT Shim Header - 4 bytes
local shim_tree = int_tree:add(shim_buf, "UDP INT Shim Header")
shim_tree:add("Type: " .. shim_buf:bitfield(0, 4))
shim_tree:add("NPT: " .. shim_buf:bitfield(4, 2))
assert(shim_buf:bitfield(6, 2)) -- reserved
local length = shim_buf:bitfield(8, 8)
shim_tree:add(shim_buf(1, 1), "length: " .. length)
assert(shim_buf:bitfield(16, 8)) -- reserved
local next_proto = shim_buf:bitfield(24, 8)
shim_tree:add(shim_buf(3, 1), "next_proto: " .. next_proto)
return length, next_proto
end
function bit_tree_16(tree, buf, tree_label, item_label)
local bit_tree = tree:add(buf(0, 2), tree_label)
bit_tree:add(item_label .. " 0: " .. buf:bitfield(0, 1))
bit_tree:add(item_label .. " 1: " .. buf:bitfield(1, 1))
bit_tree:add(item_label .. " 2: " .. buf:bitfield(2, 1))
bit_tree:add(item_label .. " 3: " .. buf:bitfield(3, 1))
bit_tree:add(item_label .. " 4: " .. buf:bitfield(4, 1))
bit_tree:add(item_label .. " 5: " .. buf:bitfield(5, 1))
bit_tree:add(item_label .. " 6: " .. buf:bitfield(6, 1))
bit_tree:add(item_label .. " 7: " .. buf:bitfield(7, 1))
bit_tree:add(item_label .. " 8: " .. buf:bitfield(8, 1))
bit_tree:add(item_label .. " 9: " .. buf:bitfield(9, 1))
bit_tree:add(item_label .. " 10: " .. buf:bitfield(10, 1))
bit_tree:add(item_label .. " 11: " .. buf:bitfield(11, 1))
bit_tree:add(item_label .. " 12: " .. buf:bitfield(12, 1))
bit_tree:add(item_label .. " 13: " .. buf:bitfield(13, 1))
bit_tree:add(item_label .. " 14: " .. buf:bitfield(14, 1))
bit_tree:add(item_label .. " 15: " .. buf:bitfield(15, 1))
end
function tps_int_hdr(int_tree, tvbr)
local header_tree = int_tree:add(tvbr, "INT Metadata Header")
header_tree:add("Version: " .. tvbr:bitfield(0, 4))
header_tree:add("d: " .. tvbr:bitfield(6, 1))
header_tree:add("e: " .. tvbr:bitfield(7, 1))
header_tree:add("m: " .. tvbr:bitfield(8, 1))
header_tree:add("Per-hop Metadata Length: " .. tvbr:bitfield(19, 5))
header_tree:add(tvbr(3, 1), "Remaining Hop count: " .. tvbr:bitfield(24, 8))
bit_tree_16(header_tree, tvbr(4, 2), "Instructions", "bit")
header_tree:add(tvbr(6, 2), "Domain ID: " .. tvbr:bitfield(48, 16))
bit_tree_16(header_tree, tvbr(8, 2), "DS Instructions", "bit")
bit_tree_16(header_tree, tvbr(10, 2), "DS Flags", "bit")
end
function tps_int_md(int_tree, int_md_buf, total_hops)
-- INT Metadata Stack - 4 bytes
local stack_tree = int_tree:add(int_md_buf, "Metadata Stack")
local int_md_buf_offset = 0
while (total_hops > 0)
do
local tree_bytes = 4
if total_hops == 1 then
tree_bytes = 12
end
local metaTree = stack_tree:add(int_md_buf(int_md_buf_offset, tree_bytes), "Hop " .. total_hops)
local switch_id = int_md_buf(int_md_buf_offset, 4):uint()
metaTree:add(int_md_buf(int_md_buf_offset, 4), "Switch ID: " .. switch_id)
int_md_buf_offset = int_md_buf_offset + 4
if total_hops == 1 then
local device_mac = octet_to_mac(int_md_buf(int_md_buf_offset, 6))
metaTree:add(int_md_buf(int_md_buf_offset, 6), "Originating Device MAC address: " .. device_mac)
int_md_buf_offset = int_md_buf_offset + 6
local pad = int_md_buf(int_md_buf_offset, 2)
assert(pad)
int_md_buf_offset = int_md_buf_offset + 2
end
total_hops = total_hops - 1
end
end
function tps_trpt_hdr(header_tree, tvbr)
header_tree:add(tvbr(0, 1), "Version: " .. tvbr:bitfield(0, 4))
header_tree:add(tvbr(0, 2), "Hardware ID: " .. tvbr:bitfield(4, 6))
header_tree:add(tvbr(1, 2), "Sequence No: " .. tvbr:bitfield(10, 22))
header_tree:add(tvbr(3, 4), "Node ID: " .. tvbr:bitfield(32, 32))
header_tree:add(tvbr(7, 1), "Report Type: " .. tvbr:bitfield(64, 4))
header_tree:add(tvbr(8, 1), "In Type: " .. tvbr:bitfield(68, 4))
header_tree:add(tvbr(9, 1), "Report Length: " .. tvbr:bitfield(72, 8))
header_tree:add(tvbr(10, 1), "MD Length: " .. tvbr:bitfield(80, 8))
header_tree:add(tvbr(11, 1), "d: " .. tvbr:bitfield(104, 1))
header_tree:add(tvbr(11, 1), "q: " .. tvbr:bitfield(105, 1))
header_tree:add(tvbr(11, 1), "f: " .. tvbr:bitfield(106, 1))
header_tree:add(tvbr(11, 1), "i: " .. tvbr:bitfield(107, 1))
bit_tree_16(header_tree, tvbr(12, 2),"Rep MD", "bit")
header_tree:add(tvbr(14, 2), "Domain ID: " .. tvbr(14, 2):bitfield(0, 16))
bit_tree_16(header_tree, tvbr(16, 2), "DS MDB", "bit")
bit_tree_16(header_tree, tvbr(18, 2), "DS MDS", "bit")
header_tree:add(tvbr(20, 4), "Var Opt MD: " .. tvbr:bitfield(160, 32))
end
function int_eth_hdr(trpt_tree, tvbr)
local eth_tree = trpt_tree:add(tvbr, "INT Ethernet Header")
eth_tree:add(tvbr(0,6), "Dest MAC: " .. octet_to_mac(tvbr(0, 6)))
eth_tree:add(tvbr(6,6), "Source MAC: " .. octet_to_mac(tvbr(6, 6)))
local ether_type = tvbr:bitfield(96, 16)
eth_tree:add(tvbr(12,2), "Ether Type: " .. ether_type)
return ether_type
end
function tps_udp_proto.dissector(buffer, pinfo, tree)
pinfo.cols.protocol = "TPS INT"
local shim_buf = buffer(0, 4)
local buf_offset = 4
local tvbr = buffer(buf_offset, 12)
buf_offset = buf_offset + 12
local length = shim_buf:bitfield(8, 8)
local total_hops = length - 6
local buf_bytes = total_hops * 4 + 6 + 2
-- INT Shim Header - 8 bytes
local int_tree = tree:add(tps_udp_proto, buffer(0, 16+buf_bytes), "In-band Network Telemetry (INT)")
local shim_length, next_proto = tps_int_shim(int_tree, shim_buf)
-- INT Metadata Header - 12 bytes
tps_int_hdr(int_tree, tvbr)
-- INT Metadata Stack - 4 bytes
local shim_hops = shim_length - 6
local shim_buf_bytes = total_hops * 4 + 6 + 2
local int_md_buf = buffer(buf_offset, shim_buf_bytes)
buf_offset = buf_offset + buf_bytes
tps_int_md(int_tree, int_md_buf, shim_hops)
if next_proto == 0x11 then
-- UDP
Dissector.get("udp"):call(buffer:range(buf_offset):tvb(), pinfo, tree)
elseif next_proto == 0x06 then
-- TCP
Dissector.get("tcp"):call(buffer:range(buf_offset):tvb(), pinfo, tree)
end
end
function tps_trpt_proto.dissector(buffer, pinfo, tree)
pinfo.cols.protocol = "TRPT/INT"
-- TRPT Header - 24 bytes
local trpt_buf = buffer(buf_offset, 24)
local buf_offset = 24
local trpt_tree = tree:add(tps_trpt_proto, trpt_buf, "Telemetry Report")
tps_trpt_hdr(trpt_tree, trpt_buf)
-- INT Ethernet
Dissector.get("ethertype"):call(buffer:range(buf_offset):tvb(), pinfo, tree)
local trpt_eth_buf = buffer(buf_offset, 14)
buf_offset = buf_offset + 14
local ether_type = int_eth_hdr(tree, trpt_eth_buf)
--buffer(buf_offset, 20)
if ether_type == 0x0800 then
Dissector.get("ip"):call(buffer:range(buf_offset):tvb(), pinfo, tree)
buf_offset = buf_offset + 24
elseif ether_type == 0x86dd then
Dissector.get("ipv6"):call(buffer:range(buf_offset):tvb(), pinfo, tree)
buf_offset = buf_offset + 20
end
end
-- INT protocol example
ip_table = DissectorTable.get("udp.port")
ip_table:add(555, tps_udp_proto)
ip_table:add(556, tps_trpt_proto)
|
require("button")
require("stringfuncs")
require("finger")
require("windialog")
local graph = love.graphics
local wstart = winw*0.03
local hstart = winh*0.1
local wend = winw*0.97
local hend = winh*0.8
local wbox = winw-wstart-(winw-wend)
local hbox = winh-hstart-(winh-hend)
local createblock = function(c)
local t = {
letter = c,
first_letter = c,
word = false,
stone = false,
picked = false,
shuffle = false,
}
-- # = stoned position
-- @ = empty space
if c == "#" then
t.stone = true
elseif c == "@" then
t.letter = " "
t.first_letter = " "
end
return t
end
local blocks = nil
local errmsg = nil
local gw, gh
local set_word_position = function(x, y, dirx, diry, len)
for i=1,len do
if x >= 0 and x < gw and y >= 0 and y < gh then
blocks[y][x].word = true
end
x = x+dirx
y = y+diry
end
end
local loadlines = function(content, i)
if gw ~= nil and gh ~= nil then
local letters
blocks = {}
for y=0,gh-1 do
blocks[y] = {}
letters = split_line_letters(content[i][1])
for x=0,gw-1 do
blocks[y][x] = createblock(letters[x+1])
end
i = i+1
end
else
errmsg = "Game proportions haven't been set yet."
end
return i-1
end
local bs = 40*(winw/winwbase)
local fontblock = graph.newFont("data/font.ttf", bs-4)
local picked = graph.newImage("data/blockpicked.png")
local shuffle = graph.newImage("data/blockshuffle.png")
local norm = graph.newImage("data/blocknormal.png")
local stone = graph.newImage("data/blockstone.png")
local wordback = graph.newImage("data/wordbackground.png")
local show_goals
local drawletter = function(l, x, y)
pushfont()
graph.setFont(fontblock)
local w, h = fontblock:getWidth(l), fontblock:getHeight()
graph.print(l, x+(bs-w)/2, y+(bs-h)/2-2)
popfont()
end
local drawblock = function(b, x, y, shuffle_performed)
if show_goals then
if b.word then
graph.draw(picked, x, y, 0, bs/picked:getWidth(), bs/picked:getHeight())
drawletter(b.first_letter, x, y)
else
graph.draw(norm, x, y, 0, bs/norm:getWidth(), bs/norm:getHeight())
end
elseif b.stone then
graph.draw(stone, x, y, 0, bs/stone:getWidth(), bs/stone:getHeight())
else
if b.picked then
graph.draw(picked, x, y, 0, bs/picked:getWidth(), bs/picked:getHeight())
elseif b.shuffle then
graph.draw(shuffle, x, y, 0, bs/shuffle:getWidth(), bs/shuffle:getHeight())
else
graph.draw(norm, x, y, 0, bs/norm:getWidth(), bs/norm:getHeight())
end
drawletter(b.letter, x, y)
end
end
local drawarea_wordpos = function()
local o = bs/bs
for i=0,gh-1 do
for j=0,gh-1 do
-- because the background for position where is the word's letter placed
-- cannot be translated or moved, you have to draw it separately
if blocks[i][j].word then
pushcolor()
graph.setColor(0, 0, 0, 100)
graph.rectangle("fill", j*bs, i*bs, bs, bs)
popcolor()
end
end
end
end
local drawarea_spec = function(x1, y1, x2, y2)
for i=y1,y2 do
for j=x1,x2 do
drawblock(blocks[i][j], j*bs, i*bs)
end
end
end
local camx, camy
local rw, rh
-- Shuffle variables
local shuffle_performing
local shuffle_hor
local shuffle_LU -- shuffle LEFT, UP (boolean)
local shuffle_pos
local shuffle_time
local shuffle_len
local shuffle_dir -- 1, -1
local shuffle_fast_horizontal = function(x, y, x2, y2)
local tmp = {}
for i=0,gw-1 do
if blocks[y][i].stone == true then return end
tmp[i] = blocks[y][i].letter
end
local d = x2-x
if d > 0 then
for i=d,gw+d-1 do
blocks[y][math.fmod(i, gw)].letter = tmp[i-d]
end
elseif d < 0 then
d = -d
for i=d,gw+d-1 do
blocks[y][i-d].letter = tmp[math.fmod(i, gw)]
end
end
end
local shuffle_fast_vertical = function(x, y, x2, y2)
local tmp = {}
for i=0,gh-1 do
if blocks[i][x].stone == true then return end
tmp[i] = blocks[i][x].letter
end
local d = y2-y
if d > 0 then
for i=d,gh+d-1 do
blocks[math.fmod(i, gh)][x].letter = tmp[i-d]
end
elseif d < 0 then
d = -d
for i=d,gh+d-1 do
blocks[i-d][x].letter = tmp[math.fmod(i, gh)]
end
end
end
local shufflebuf = nil
local shuffle_fast = function(x, y, dirx, diry, length, save)
if dirx ~= 0 then
length = math.fmod(length, gw)
else
length = math.fmod(length, gh)
end
local x2, y2 = x+dirx*length, y+diry*length
if x2 < 0 then
x2 = x2+gw
elseif x2 >= gw then
x2 = x2-gw
end
if y2 < 0 then
y2 = y2+gh
elseif y2 >= gh then
y2 = y2-gh
end
if dirx ~= 0 then
shuffle_fast_horizontal(x, y, x2, y2)
else
shuffle_fast_vertical(x, y, x2, y2)
end
if save then
shufflebuf[#shufflebuf+1] = {
["x"] = x,
["y"] = y,
["dirx"] = dirx,
["diry"] = diry,
["length"] = length
}
end
end
local animation_time = 0.25
local shuffle_animated = function(x1, y1, x2, y2)
local x, y = x2-x1, y2-y1
if x ~= 0 and y ~= 0 then
-- No shuffle possible, because the shuffle must take part
-- in absolute vertical or horizontal direction!
return
end
if x ~= 0 then
-- Horizontal shuffle
shuffle_pos = y1
shuffle_hor = true
shuffle_LU = x < 0
shuffle_len = math.abs(x)
elseif y ~= 0 then
shuffle_pos = x1
shuffle_hor = false
shuffle_LU = y < 0
shuffle_len = math.abs(y)
else
return
end
shuffle_dir = 1
if shuffle_LU then
shuffle_dir = -1
end
shuffle_performing = true
shuffle_time = animation_time
end
local drawshuffled_hor = function()
local o = (math.fmod(shuffle_time, animation_time)/animation_time)*bs
graph.push()
if o == 0 then
o = bs
end
if shuffle_LU then
graph.translate(o-bs, 0)
drawarea_spec(0, shuffle_pos, gw-1, shuffle_pos)
drawblock(blocks[shuffle_pos][0], rw, shuffle_pos*bs)
else
graph.translate(-o, 0)
drawblock(blocks[shuffle_pos][gw-1], 0, shuffle_pos*bs)
graph.translate(bs, 0)
drawarea_spec(0, shuffle_pos, gw-1, shuffle_pos)
end
graph.pop()
end
local drawshuffled_ver = function()
local o = (math.fmod(shuffle_time, animation_time)/animation_time)*bs
graph.push()
if o == 0 then
o = bs
end
if shuffle_LU then
graph.translate(0, o-bs)
drawarea_spec(shuffle_pos, 0, shuffle_pos, gh-1)
drawblock(blocks[0][shuffle_pos], shuffle_pos*bs, rh)
else
graph.translate(0, -o)
drawblock(blocks[gh-1][shuffle_pos], shuffle_pos*bs, 0)
graph.translate(0, bs)
drawarea_spec(shuffle_pos, 0, shuffle_pos, gh-1)
end
graph.pop()
end
local drawarea = function()
graph.push()
graph.translate(camx, camy)
drawarea_wordpos()
if shuffle_performing then
if shuffle_hor then
drawarea_spec(0, 0, gw-1, shuffle_pos-1)
drawarea_spec(0, shuffle_pos+1, gw-1, gh-1)
drawshuffled_hor()
else
drawarea_spec(0, 0, shuffle_pos-1, gh-1)
drawarea_spec(shuffle_pos+1, 0, gw-1, gh-1)
drawshuffled_ver()
end
else
drawarea_spec(0, 0, gw-1, gh-1)
end
graph.pop()
end
local check_grid = function()
for j=0,gh-1 do
for i=0,gw-1 do
if blocks[j][i].word and
blocks[j][i].letter ~= blocks[j][i].first_letter then
return
end
end
end
guistack_pushanimated_removeprev({draw=windialog_draw,update=windialog_update})
end
local update_shuffle = function(dt)
if shuffle_performing then
shuffle_time = shuffle_time-dt
if shuffle_time <= 0 then
shuffle_time = animation_time
shuffle_len = shuffle_len-1
if shuffle_hor then
shuffle_fast(0, shuffle_pos, shuffle_dir, 0, 1, true)
else
shuffle_fast(shuffle_pos, 0, 0, shuffle_dir, 1, true)
end
if shuffle_len <= 0 then
shuffle_performing = false
check_grid()
end
end
end
end
local move_camera = function(x, y)
if x ~= 0 and rw > wbox then
camx = camx+x
if camx > wstart then
camx = wstart
elseif camx < wend-rw then
camx = wend-rw
end
end
if y ~= 0 and rh > hbox then
camy = camy+y
if camy > hstart then
camy = hstart
elseif camy < hend-rh then
camy = hend-rh
end
end
end
local getxy_finger = function(x, y)
if (rw < wbox and (x < camx or x > camx+rw)) or x < wstart or x > wend then
x = -999
end
if (rh < hbox and (y < camy or y > camy+rh)) or y < hstart or y > hend then
y = -999
end
return x-camx, y-camy
end
local canshuffle = function(x, y, dx, dy)
-- can you make shuffle in this way?
while x >= 0 and x < gw and y >= 0 and y < gh do
if blocks[y][x].stone then
return false
end
x = x+dx
y = y+dy
end
return true
end
local markshuffle = function(x, y, dx, dy)
while x >= 0 and x < gw and y >= 0 and y < gh do
blocks[y][x].shuffle = true
x = x+dx
y = y+dy
end
end
local pick_letter = function(x, y)
local l = canshuffle(x, y, -1, 0)
local r = canshuffle(x, y, 1, 0)
local u = canshuffle(x, y, 0, -1)
local d = canshuffle(x, y, 0, 1)
if l and r then
markshuffle(x, y, 1, 0)
markshuffle(x, y, -1, 0)
end
if u and d then
markshuffle(x, y, 0, 1)
markshuffle(x, y, 0, -1)
end
blocks[y][x].picked = true
end
local unpick_letter = function()
-- iterate through grid and delete all marks
for i=0,gh-1 do
for j=0,gw-1 do
blocks[i][j].picked = false
blocks[i][j].shuffle = false
end
end
end
local but_showgoals = nil
local but_showgrid = nil
local but_reset = nil
local fx, fy = -1, -1
local blockx, blocky = -1, -1
function game_click(x, y)
-- first handle game buttons, then the grid manipulation
if button_click(but_reset, x, y) then
return true
elseif show_goals == false and button_click(but_showgoals, x, y) then
return true
elseif show_goals and button_click(but_showgrid, x, y) then
return true
end
-- blocks manipulation
if shuffle_performing == false then
x, y = getxy_finger(x, y)
if x < 0 or y < 0 then
return false
end
blockx = math.floor(x/bs)
blocky = math.floor(y/bs)
end
return true
end
local letterpicked = false
local pickedx, pickedy = -1, -1
local num_shuffles = 0
local min_shuffles
local action_showgoals_onoff = function()
show_goals = not show_goals
end
local action_resetgrid = function()
local s
for i=#shufflebuf,1,-1 do
s = shufflebuf[i]
shuffle_fast(s.x, s.y, -s.dirx, -s.diry, s.length, false)
end
shufflebuf = {}
end
function game_release(x, y)
-- handle game buttons
if button_release(but_reset, x, y) then
return true
elseif show_goals == false and button_release(but_showgoals, x, y) then
return true
elseif show_goals and button_release(but_showgrid, x, y) then
return true
end
-- blocks manipulation
if shuffle_performing == false then
x, y = getxy_finger(x, y)
if x < 0 or y < 0 then
return false
end
x = math.floor(x/bs)
y = math.floor(y/bs)
if x == blockx and y == blocky then
if letterpicked then
letterpicked = false
if blocks[y][x].shuffle then
shuffle_animated(pickedx, pickedy, x, y)
num_shuffles = num_shuffles+1
end
unpick_letter()
pickedx, pickedy = -1, -1
else
pick_letter(x, y)
letterpicked = true
pickedx = x
pickedy = y
end
end
end
return true
end
function game_update(dt)
update_shuffle(dt)
-- first click, get finger position!
if fingerclicked then
fx, fy = finger_position()
game_click(fx, fy)
elseif fingerreleased then
game_release(fx, fy)
end
if finger_isdown() then
-- get current finger position and update the old one
local x, y = finger_position()
local x2, y2 = getxy_finger(x, y)
if x2 > 0 and y2 > 0 then
move_camera(x-fx, y-fy)
end
fx, fy = x, y
end
end
function game_draw()
local x, y, w, h = wstart, hstart, rw, rh
if x < camx then
x = camx
end
if y < camy then
y = camy
end
if rw > wbox then
w = wbox
end
if rh > hbox then
h = hbox
end
graph.setScissor(x, y, w, h)
drawarea()
graph.setScissor()
if show_goals then
button_draw(but_showgrid)
else
button_draw(but_showgoals)
end
button_draw(but_reset)
end
function game_create(filename)
-- Load the content and split words in lines from given file
local content, line = {}
for line in love.filesystem.lines(filename) do
content[#content+1] = split_line_space(line)
end
wordlist = {}
min_shuffles = 0
local i = 1
-- Perform operations with the game
while i <= #content do
if content[i][1] == "proportions" then
gw = tonumber(content[i][2])
gh = tonumber(content[i][3])
elseif content[i][1] == "lines" then
i = loadlines(content, i+1)
elseif content[i][1] == "//" then
-- Comment, ignore this line
elseif content[i][1] == "word" then
-- Word position
set_word_position(tonumber(content[i][2]), tonumber(content[i][3]),
tonumber(content[i][4]), tonumber(content[i][5]), tonumber(content[i][6]))
elseif content[i][1] == "shuffle" then
shuffle_fast(tonumber(content[i][2]), tonumber(content[i][3]),
tonumber(content[i][4]), tonumber(content[i][5]),
tonumber(content[i][6]), false)
min_shuffles = min_shuffles+1
end
i = i+1
end
rw = gw*bs
rh = gh*bs
show_goals = false
shuffle_performing = false
-- shuffle history
shufflebuf = {}
-- if the grid is larger than the window, you can move with camera on it
-- if not, count the camera position and set the grid on the center
-- of the window
if rw < wbox then
camx = wstart+(wbox-rw)/2
else
camx = wstart
end
if rh < hbox then
camy = hstart+(hbox-rh)/2
else
camy = hstart
end
-- and don't forget to create buttons
local offx = 10
local offy = 15
local hcoef = 0.6
but_showgoals = button_new("Show words", fontm, offx, hend+offy,
winw/2-2*offx, (winh-hend)*hcoef, action_showgoals_onoff)
but_showgrid = button_new("Show grid", fontm, offx, hend+offy,
winw/2-2*offx, (winh-hend)*hcoef, action_showgoals_onoff)
but_reset = button_new("Reset grid", fontm, winw/2+offx, hend+offy,
winw/2-2*offx, (winh-hend)*hcoef, action_resetgrid)
end |
slot0 = class("ShoppingCommand", pm.SimpleCommand)
slot0.execute = function (slot0, slot1)
slot4 = slot1:getBody().count
slot5 = pg.shop_template[slot1.getBody().id]
slot7 = getProxy(PlayerProxy).getData(slot6)
slot8 = getProxy(NavalAcademyProxy)
if not slot1.getBody().id then
pg.TipsMgr.GetInstance():ShowTips(i18n("common_shopId_noFound"))
return
end
if slot5.type == DROP_TYPE_WORLD_ITEM and not nowWorld:IsActivate() then
pg.TipsMgr.GetInstance():ShowTips(i18n("world_shop_bag_unactivated"))
return
end
if slot5.type == DROP_TYPE_ITEM then
for slot15, slot16 in pairs(slot11) do
if slot16[1] == 1 then
if slot16[2] == 1 and slot7:GoldMax(slot16[3]) then
pg.TipsMgr.GetInstance():ShowTips(i18n("gold_max_tip_title") .. i18n("resource_max_tip_shop"))
return
end
if slot16[2] == 2 and slot7:OilMax(slot16[3]) then
pg.TipsMgr.GetInstance():ShowTips(i18n("oil_max_tip_title") .. i18n("resource_max_tip_shop"))
return
end
end
end
end
if slot5.type == DROP_TYPE_RESOURCE then
if slot5.effect_args[1] == 1 and slot7:GoldMax(slot5.num * slot4) then
pg.TipsMgr.GetInstance():ShowTips(i18n("gold_max_tip_title") .. i18n("resource_max_tip_shop"))
return
end
if slot5.effect_args[1] == 2 then
if slot5.num == -1 and slot5.genre == ShopArgs.BuyOil then
slot9 = ShopArgs.getOilByLevel(slot7.level)
end
if slot7:OilMax(slot9 * slot4) then
pg.TipsMgr.GetInstance():ShowTips(i18n("oil_max_tip_title") .. i18n("resource_max_tip_shop"))
return
end
end
end
if slot4 == 0 then
return
end
slot10 = getProxy(ShopsProxy).getShopStreet(slot9)
slot11 = false
if slot5.resource_num ~= -1 then
slot12 = slot5.resource_num * slot4
if slot10 and slot5.genre == ShopArgs.ShoppingStreetLimit then
slot11 = true
slot12 = math.ceil(slot10:getGoodsById(slot3).discount / 100 * slot12)
end
elseif slot12 == -1 and slot5.effect_args == ShopArgs.EffectShopStreetLevel then
slot12 = pg.navalacademy_shoppingstreet_template[slot10.level].lv_up_cost[2] * slot4
elseif slot12 == -1 and (slot5.effect_args == ShopArgs.EffectTradingPortLevel or slot5.effect_args == ShopArgs.EffectOilFieldLevel or slot5.effect_args == ShopArgs.EffectClassLevel) then
slot13 = nil
if slot5.effect_args == ShopArgs.EffectTradingPortLevel then
slot13 = slot8._goldVO
elseif slot5.effect_args == ShopArgs.EffectOilFieldLevel then
slot13 = slot8._oilVO
elseif slot5.effect_args == ShopArgs.EffectClassLevel then
slot13 = slot8._classVO
end
slot12 = slot13:bindConfigTable()[slot13:GetLevel()].use[2] * slot4
end
if slot5.limit_args then
for slot16, slot17 in ipairs(slot5.limit_args) do
if type(slot17) == "table" and slot17[1] == "level" and slot7.level < slot17[2] then
pg.TipsMgr.GetInstance():ShowTips(i18n("common_limit_level", slot17[2]))
return
end
end
end
if slot5.discount ~= 0 and CommonCommodity.InCommodityDiscountTime(slot5.id) then
slot12 = slot12 * (100 - slot5.discount) / 100
end
if slot7[id2res(slot5.resource_type)] < slot12 then
slot13 = pg.item_data_statistics[id2ItemId(slot5.resource_type)].name
if slot5.resource_type == 1 then
GoShoppingMsgBox(i18n("switch_to_shop_tip_2", i18n("word_gold")), ChargeScene.TYPE_ITEM, {
{
59001,
slot12 - slot7[id2res(slot5.resource_type)],
slot12
}
})
elseif slot5.resource_type == 4 or slot5.resource_type == 14 then
GoShoppingMsgBox(i18n("switch_to_shop_tip_3", i18n("word_gem")), ChargeScene.TYPE_DIAMOND)
elseif not ItemTipPanel.ShowItemTip(DROP_TYPE_RESOURCE, slot5.resource_type) then
pg.TipsMgr.GetInstance():ShowTips(i18n("buyProp_noResource_error", slot13))
end
return
end
slot13, slot14 = slot0:CheckGiftPackage(slot5)
if not slot13 then
slot14()
return
end
pg.ConnectionMgr.GetInstance():Send(16001, {
id = slot3,
number = slot4
}, 16002, function (slot0)
if slot0.result == 0 then
slot1 = {}
if slot0.type ~= 0 then
if slot0.is_auto_use == 1 then
slot1 = PlayerConst.addTranDrop(slot0.drop_list)
else
slot2 = slot0.num
if slot0.num == -1 and slot0.genre == ShopArgs.BuyOil then
slot2 = ShopArgs.getOilByLevel(slot1:getData().level)
end
slot3 = Item.New({
type = slot0.type,
id = slot0.effect_args[1],
count = slot2 * slot2
})
slot3:sendNotification(GAME.ADD_ITEM, slot3)
table.insert(slot1, slot3)
end
if slot4 == GoldExchangeView.itemid1 or slot4 == GoldExchangeView.itemid2 then
pg.TipsMgr.GetInstance():ShowTips(i18n("common_buy_gold_success", pg.shop_template[slot4].num * pg.TipsMgr.GetInstance().ShowTips))
else
pg.TipsMgr.GetInstance():ShowTips(i18n("common_buy_success"))
end
elseif slot0.type == 0 then
slot3:sendNotification(GAME.EXTEND, {
id = slot4,
count = slot3.sendNotification
})
end
slot1:getData().consume(slot2, {
[id2res(slot0.resource_type)] =
})
if slot0.genre == ShopArgs.BuyOil then
slot2:increaseBuyOilCount()
end
slot1:updatePlayer(slot2)
slot3 = nil
if slot6 then
slot4 = slot7:getShopStreet()
slot3 = slot4.type
slot4:getGoodsById(slot4).reduceBuyCount(slot5)
slot5:UpdateShopStreet(slot4)
if slot1[1].type == DROP_TYPE_ITEM and slot6:isEquipmentSkinBox() then
slot3:sendNotification(GAME.USE_ITEM, {
count = 1,
skip_check = true,
id = slot6.id
})
end
elseif slot0.genre == ShopArgs.ArenaShopLimit then
slot4 = getProxy(ShopsProxy)
slot5 = slot4:getMeritorousShop()
slot6 = slot5:getGoodsById(slot4)
slot6:increaseBuyCount()
slot5:updateGoods(slot6)
slot3 = slot5.type
slot4:updateMeritorousShop(slot5)
elseif slot0.genre == ShopArgs.GiftPackage then
slot7:GetNormalByID(slot7.GetNormalByID):increaseBuyCount()
elseif slot0.genre == ShopArgs.SkinShop then
getProxy(ShipSkinProxy):addSkin(ShipSkin.New({
id = slot0.effect_args[1]
}))
elseif slot0.genre == ShopArgs.SkinShopTimeLimit then
if getProxy(ShipSkinProxy):getSkinById(slot0.effect_args[1]) and slot6:isExpireType() then
slot5:addSkin(ShipSkin.New({
id = slot4,
end_time = slot0.time_second * slot2 + slot6.endTime
}))
elseif not slot6 then
slot5:addSkin(ShipSkin.New({
id = slot4,
end_time = slot0.time_second * slot2 + pg.TimeMgr.GetInstance():GetServerTime()
}))
end
elseif slot0.genre == ShopArgs.guildShop then
slot4 = getProxy(ShopsProxy):getGuildShop()
slot4:getGoodsById(slot4).reduceBuyCount(slot5)
slot5:updateGuildShop(slot4)
elseif slot0.genre == ShopArgs.WorldShop then
nowWorld:UpdateWorldShopGoods({
{
goods_id = slot4,
count = slot2
}
})
end
if slot0.group > 0 then
slot7:updateNormalGroupList(slot0.group, slot0.group_buy_count)
end
if slot0.effect_args == ShopArgs.EffecetShipBagSize then
pg.TipsMgr.GetInstance():ShowTips(i18n("shop_extendship_success"))
end
if slot0.effect_args == ShopArgs.EffecetEquipBagSize then
pg.TipsMgr.GetInstance():ShowTips(i18n("shop_extendequip_success"))
end
if slot0.effect_args == ShopArgs.EffectCommanderBagSize then
pg.TipsMgr.GetInstance():ShowTips(i18n("shop_extendcommander_success"))
end
slot7.awards = (slot0.is_auto_use == 1 and slot1) or {}
slot4(slot3, GAME.SHOPPING_DONE, slot7)
else
print(slot0.result)
pg.TipsMgr.GetInstance():ShowTips(errorTip("", slot0.result))
end
end)
end
slot0.CheckGiftPackage = function (slot0, slot1)
function slot2(slot0)
slot1 = 0
slot2 = 0
slot3 = 0
slot4 = 0
for slot8, slot9 in ipairs(slot0) do
if DROP_TYPE_RESOURCE == slot9[1] then
if slot9[2] == 1 then
slot2 = slot2 + slot9[3]
elseif slot9[2] == 2 then
slot1 = slot1 + slot9[3]
end
elseif DROP_TYPE_EQUIP == slot9[1] then
slot3 = slot3 + slot9[3]
elseif DROP_TYPE_SHIP == slot9[1] then
slot4 = slot4 + slot9[3]
end
end
return slot1, slot2, slot3, slot4
end
if slot1.genre == ShopArgs.GiftPackage then
slot5, slot6, slot7, slot8 = slot2(slot4)
slot9 = getProxy(PlayerProxy):getRawData()
if slot5 > 0 and slot9:OilMax(slot5) then
return false, function ()
pg.TipsMgr.GetInstance():ShowTips(i18n("oil_max_tip_title") .. i18n("resource_max_tip_shop"))
end
end
if slot6 > 0 and slot9.GoldMax(slot9, slot6) then
return false, function ()
pg.TipsMgr.GetInstance():ShowTips(i18n("gold_max_tip_title") .. i18n("resource_max_tip_shop"))
end
end
slot10 = getProxy(EquipmentProxy).getCapacity(slot10)
if slot7 > 0 and slot9:getMaxEquipmentBag() < slot10 + slot7 then
return false, function ()
NoPosMsgBox(i18n("switch_to_shop_tip_noPos"), openDestroyEquip, gotoChargeScene)
end
end
slot11 = getProxy(BayProxy).getShipCount(slot11)
if slot8 > 0 and slot9:getMaxShipBag() < slot11 + slot8 then
return false, function ()
NoPosMsgBox(i18n("switch_to_shop_tip_noDockyard"), openDockyardClear, gotoChargeScene, openDockyardIntensify)
end
end
end
return true
end
return slot0
|
local check = require("jnet.check")
local util = require("jnet.util")
local BITS = 16
local COMPMAX = 1 << BITS
local COMPMASK = COMPMAX - 1
local FORMAT = "%04x"
local net_i = {}
local net_m = { __index = net_i, jnet_type__ = "jnet.net" }
function net_i:promote_(other, netwb)
local mt = getmetatable(self)
if getmetatable(other) == mt then
return other
end
return mt.jnet_promote_new__(other, netwb)
end
function net_i:flip()
local new_bits = util.numeric_clone(self.bits_)
local bit = self.all_ - self.netwb_
local offset = bit % BITS
local index = #new_bits - bit // BITS
new_bits[index] = new_bits[index] ~ (1 << offset)
return self:new_(self.all_, new_bits, self.netwb_)
end
function net_i:longshl_(lhs, amount)
local new_bits = {}
local zeroc_rem = self.all_ - amount
for i = #lhs, 1, -1 do
local zeroc_sub = math.max(0, math.min(BITS, zeroc_rem))
assert(lhs[i] & (COMPMASK ~ ((1 << zeroc_sub) - 1)) == 0, "overflow")
zeroc_rem = zeroc_rem - zeroc_sub
end
local move = amount // BITS
local shift = amount % BITS
for i = #lhs - move + 1, #lhs do
new_bits[i] = 0
end
local carry = 0
for i = 1, #lhs - move do
local shifted = lhs[i + move] << shift
new_bits[i] = (shifted & COMPMASK) | carry
carry = (shifted >> BITS) & COMPMASK
end
return new_bits
end
function net_i:longadd_(lhs, rhs, rsign)
local all_rem = self.all_
local carry = 0
local new_bits = {}
for i = #lhs, 1, -1 do
local all_sub = math.min(BITS, all_rem)
new_bits[i] = lhs[i] + rsign * (rhs[i] + carry)
if new_bits[i] >= (1 << all_sub) then
new_bits[i] = new_bits[i] - rsign * (1 << all_sub)
carry = 1
else
carry = 0
end
all_rem = all_rem - all_sub
end
assert(carry == 0, rsign == 1 and "overflow" or "underflow")
return new_bits
end
function net_m:__add(other)
if type(other) == "number" and other < 0 then
return self - -other
end
other = self:promote_(other, self.netwb_)
assert(getmetatable(other) == getmetatable(self), "other operand is of the wrong type")
assert(self.all_ == other.all_, "other operand is of the wrong bit count")
assert(self.netwb_ == other.netwb_, "other operand is of the wrong network bit count")
return self:new_(self.all_, self:longadd_(self.bits_, other.bits_, 1), self.netwb_)
end
function net_m:__sub(other)
if type(other) == "number" and other < 0 then
return self + -other
end
other = self:promote_(other, self.netwb_)
assert(getmetatable(other) == getmetatable(self), "other operand is of the wrong type")
assert(self.all_ == other.all_, "other operand is of the wrong bit count")
assert(self.netwb_ == other.netwb_, "other operand is of the wrong network bit count")
return self:new_(self.all_, self:longadd_(self.bits_, other.bits_, -1), self.netwb_)
end
function net_m:__div(other)
assert(check.integer(other), "other operand is not an integer")
assert(other >= 0 and other <= self.all_, "other operand is out of range")
return self:new_(self.all_, util.numeric_clone(self.bits_), other)
end
function net_m:__lt(other)
other = self:promote_(other, self.netwb_)
assert(getmetatable(other) == getmetatable(self), "other operand is of the wrong type")
assert(self.all_ == other.all_, "other operand is of the wrong bit count")
for i = 1, #self.bits_ do
if self.bits_[i] < other.bits_[i] then
return true
end
if self.bits_[i] > other.bits_[i] then
return false
end
end
return false
end
function net_m:__eq(other)
other = self:promote_(other, self.netwb_)
assert(getmetatable(other) == getmetatable(self), "other operand is of the wrong type")
assert(self.all_ == other.all_, "other operand is of the wrong bit count")
if self.netwb_ ~= other.netwb_ then
return false
end
for i = 1, #self.bits_ do
if self.bits_[i] ~= other.bits_[i] then
return false
end
end
return true
end
function net_m:__le(other)
other = self:promote_(other, self.netwb_)
return self < other or self == other
end
function net_m:__len()
return self.netwb_
end
function net_m:__pow(other)
assert(check.integer(other), "other operand is not an integer")
assert(other >= -self.all_ and other <= self.all_, "other operand is out of range")
local netwb = self.netwb_ + other
assert(netwb >= 0 and netwb <= self.all_, "resulting network bit count is out of range")
return self:new_(self.all_, util.numeric_clone(self.bits_), netwb)
end
function net_m:__div(other)
assert(check.integer(other), "other operand is not an integer")
assert(other >= 0 and other <= self.all_, "other operand is out of range")
local bits = util.numeric_clone(self.bits_)
local clear_rem = self.all_ - other
for i = #bits, 1, -1 do
local clear_sub = math.max(0, math.min(BITS, clear_rem))
bits[i] = bits[i] & (COMPMASK ~ ((1 << clear_sub) - 1))
clear_rem = clear_rem - clear_sub
end
return self:new_(self.all_, bits, other)
end
function net_m:__mul(other)
if type(other) == "number" and other < 0 then
other = self:promote_(-other, self.all_)
return self - self:new_(self.all_, self:longshl_(other.bits_, self.all_ - self.netwb_), self.netwb_)
end
other = self:promote_(other, self.all_)
return self + self:new_(self.all_, self:longshl_(other.bits_, self.all_ - self.netwb_), self.netwb_)
end
function net_i:first(netwb)
netwb = netwb or self.all_
assert(check.integer(netwb), "argument #1 is not an integer")
assert(netwb >= self.netwb_ and netwb <= self.all_, "argument #1 is out of range")
return self:new_(self.all_, util.numeric_clone(self.bits_), netwb)
end
function net_i:contains(other)
other = self:promote_(other, self.netwb_)
return other >= self:first(other.netwb_) and other <= self:last(other.netwb_)
end
function net_i:last(netwb)
netwb = netwb or self.all_
assert(check.integer(netwb), "argument #1 is not an integer")
assert(netwb >= self.netwb_ and netwb <= self.all_, "argument #1 is out of range")
local bits = util.numeric_clone(self.bits_)
local hostb_rem = self.all_ - self.netwb_
local clear_rem = self.all_ - netwb
for i = #bits, 1, -1 do
local hostb_sub = math.max(0, math.min(BITS, hostb_rem))
local clear_sub = math.max(0, math.min(BITS, clear_rem))
bits[i] = bits[i] | ((1 << hostb_sub) - 1)
bits[i] = bits[i] & (COMPMASK ~ ((1 << clear_sub) - 1))
hostb_rem = hostb_rem - hostb_sub
clear_rem = clear_rem - clear_sub
end
return self:new_(self.all_, bits, netwb)
end
function net_i:bit(bit)
assert(check.integer(bit), "argument #1 is not an integer")
assert(bit >= 0 and bit < self.all_, "argument #1 is out of range")
local offset = bit % BITS
local index = #self.bits_ - bit // BITS
return self.bits_[index] & (1 << offset) > 0
end
local function new(all, bits, netwb)
if type(bits) == "number" then
bits = { bits }
end
assert(check.integer(all), "argument #1 is not an integer")
assert(all >= 1, "argument #1 is out of range")
assert(type(bits) == "table", "argument #2 is not a table")
local expected_length = math.ceil(all / BITS)
assert(#bits == expected_length, "argument #2 is of the wrong length")
assert(check.integer(netwb), "argument #3 is not an integer")
assert(netwb >= 0 and netwb <= all, "argument #3 is out of range")
local all_rem = all
local hostb_rem = all - netwb
for i = expected_length, 1, -1 do
assert(check.integer(bits[i]), "argument #2 has non-integer components")
local all_sub = math.min(BITS, all_rem)
local hostb_sub = math.max(0, math.min(BITS, hostb_rem))
assert(bits[i] < (1 << all_sub) and bits[i] >= 0, "argument #2 has out of range components")
assert(bits[i] & ((1 << hostb_sub) - 1) == 0, "non-zero host bits")
all_rem = all_rem - all_sub
hostb_rem = hostb_rem - hostb_sub
end
return setmetatable({
all_ = all,
bits_ = bits,
netwb_ = netwb,
}, net_m)
end
function net_i:new_(...)
return setmetatable(new(...), getmetatable(self))
end
function net_m:__tostring()
local collect = {}
for i = 1, #self.bits_ do
table.insert(collect, FORMAT:format(self.bits_[i]))
end
local repr = table.concat(collect, ".")
if self.netwb_ < self.all_ then
repr = repr .. "/" .. self.netwb_
end
return repr
end
net_m.jnet_promote_new__ = new
net_m.jnet_base__ = net_m
return {
new = new,
net_m = net_m,
}
|
return {
postgres = {
up = [[
-- If migrating from 1.x, the "path_handling" column does not exist yet.
-- Create it with a default of 'v1' to fill existing rows.
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "routes" ADD "path_handling" TEXT DEFAULT 'v1';
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END;
$$;
]],
},
cassandra = {
up = [[
ALTER TABLE routes ADD path_handling text;
]],
teardown = function(connector)
local coordinator = assert(connector:get_stored_connection())
local cassandra = require "cassandra"
for rows, err in coordinator:iterate("SELECT id, path_handling FROM routes") do
if err then
return nil, err
end
for i = 1, #rows do
local route = rows[i]
if route.path_handling ~= "v0" and route.path_handling ~= "v1" then
local _, err = coordinator:execute(
"UPDATE routes SET path_handling = 'v1' WHERE partition = 'routes' AND id = ?",
{ cassandra.uuid(route.id) }
)
if err then
return nil, err
end
end
end
end
return true
end,
},
}
|
local on = mp.get_opt('images-statusbar') == 'yes'
local msg1 = mp.get_property('options/osd-msg1')
function update_statusbar()
if on == true then
mp.set_property('options/osd-msg1', msg1)
else
mp.set_property('options/osd-msg1', '')
end
end
function toggle_statusbar()
on = not on
update_statusbar()
mp.osd_message('', 0)
end
mp.register_event('file-loaded', update_statusbar)
mp.register_script_message('toggle-statusbar', toggle_statusbar)
|
-------------------------------- ELEMENTS FUNCTIONS ------------------------------
-- Create an element --
function createElement(name, atNumber, type, color)
eI = {}
eI.name = name
eI.type = type
eI.icon = "__Mobile_Factory_Graphics__/graphics/elements/" .. name .. ".png"
eI.icon_size = 89
eI.order = tonumber(atNumber)
if atNumber > 0 then
eI.subgroup = "Elements"
else
eI.subgroup = "Molecules"
end
if type == "fluid" then
eI.default_temperature = 20
eI.max_temperature = 300
eI.base_color = color
eI.flow_color = color
else
eI.stack_size = 100
end
data:extend{eI}
end
-- Create a Recipe --
function createRecipe(name, ingredients, results, subgroup)
eR = {}
eR.name = name
eR.type = "recipe"
eR.icon = "__Mobile_Factory_Graphics__/graphics/e-technology/" .. name .. ".png"
eR.icon_size = 89
eR.category = "Elements"
eR.subgroup = subgroup or "Elements"
eR.main_product = ""
eR.energy_required = 1
eR.enabled = false
eR.ingredients = {}
eR.results = {}
for k, i in pairs(ingredients) do
table.insert(eR.ingredients, {type=i[1], name=i[2], amount=i[3]})
end
for k, r in pairs(results) do
table.insert(eR.results, {type=r[1], name=r[2], amount=r[3]})
end
data:extend{eR}
end
-- Create a Technology --
function createTechnology(name, unit, prerequisites, unlock)
eT = {}
eT.name = name
eT.type = "technology"
eT.icon = "__Mobile_Factory_Graphics__/graphics/e-technology/" .. name .. ".png"
eT.icon_size = 89
eT.prerequisites = prerequisites
eT.unit = {
count=unit[1],
time=unit[2],
ingredients=unit[3]
}
eT.effects = {}
for k, effect in pairs(unlock) do
table.insert(eT.effects, {type="unlock-recipe", recipe=effect})
end
data:extend{eT}
end |
include("dualstick360/globals.lua")
include("dualstick360/utils.lua")
include("utils/stateMachine.lua")
include("dualstick360/player.lua")
include("dualstick360/bullet.lua")
include("dualstick360/enemy.lua")
include("dualstick360/healthpack.lua")
include("dualstick360/level1.lua")
--[[ Initialize the first game objects. Constructs a player and camera ]]
function init()
-- init player
player = Player.new()
player:init()
-- cam
cam = GameObjectManager:createGameObject("Camera")
cam.cc = cam:createCameraComponent()
cam.cc:setPosition(Vec3(0, 0, -100))
cam.lookDir = Vec3(0, 1, 0)
cam.cc:lookAt(cam.lookDir:mulScalar(2.5))
cam.cc:setState(ComponentState.Active)
end
--[[ Update all of our game objects. Checks the condition of our game as well. Called every frame. ]]
function update(deltaTime)
-- move camera
cam.cc:setPosition(Vec3(player.rb:getPosition().x, player.rb:getPosition().y, CAMERA_Z))
hb:setPosition(Vec3((2/3)*CAMERA_Z + cam.cc:getPosition().x + 50, (4/15)*CAMERA_Z + cam.cc:getPosition().y -20, (2/15)*CAMERA_Z))
-- check condition
if player.hp <= 0 then
GAME_OVER = true
end
if BOSS_CONDITION_BEATEN then
GAME_BEATEN = true
end
-- update gameobjects
if not GAME_OVER and not GAME_BEATEN then
player:update(deltaTime)
for _, b in ipairs(player.bullets) do
if (b.isActive) then
b:update(deltaTime)
end
end
for _, e in ipairs(enemyArray) do
for _, b in ipairs(e.bullets) do
if (b.isActive) then
b:update(deltaTime)
end
end
end
else
if GAME_OVER then
DebugRenderer:printText(Vec2(-0.1, 0.5), "GAME OVER")
DebugRenderer:printText(Vec2(-0.15, 0.45), "Press Return to Restart")
elseif GAME_BEATEN then
DebugRenderer:printText(Vec2(-0.1, 0.5), "YOU WON!")
DebugRenderer:printText(Vec2(-0.15, 0.45), "Hooray, that's the game!")
end
player.go:setComponentStates(ComponentState.Inactive)
player.shield.go:setComponentStates(ComponentState.Inactive)
player.shield_l.go:setComponentStates(ComponentState.Inactive)
player.shield_r.go:setComponentStates(ComponentState.Inactive)
if (InputHandler:isPressed(Key.Return)) then
player.go:setComponentStates(ComponentState.Active)
player.hp = PLAYER_HP
player.score = 0
GAME_OVER = false
end
end
createGrid()
-- utils.lua
printTextCalls = 0
printGameplayTextCalls = 0
end
Events.Update:registerListener(update)
--[[ Construct a Physicsworld, initialize first game objects, and build the first level. ]]
local cinfo = WorldCInfo()
cinfo.worldSize = 2000
world = PhysicsFactory:createWorld(cinfo)
world:setCollisionFilter(PhysicsFactory:createCollisionFilter_Simple())
PhysicsSystem:setWorld(world)
init()
build_level_1()
PhysicsSystem:setDebugDrawingEnabled(true) |
-- local variables for API functions. any changes to the line below will be lost on re-generation
local client_log, client_set_event_callback, entity_get_player_name, globals_tickinterval, math_floor, table_concat, ui_get, ui_reference = client.log, client.set_event_callback, entity.get_player_name, globals.tickinterval, math.floor, table.concat, ui.get, ui.reference
local hitgroup_names = {'generic', 'head', 'chest', 'stomach', 'left arm', 'right arm', 'left leg', 'right leg', 'neck', '?', 'gear'}
local ref = {sp = ui_reference("Rage", "Aimbot", "Prefer safe point")}
local enable = ui.new_checkbox("Rage", "Aimbot", "Advanced Shotlogger")
local function time_to_ticks(t)
return math_floor(0.5 + (t / globals_tickinterval()))
end
client_set_event_callback("aim_fire",function(e)
shot_group = hitgroup_names[e.hitgroup + 1] or '?'
flags = {
e.teleported and ' Breaking LC ' or '',
e.interpolated and ' Interpolated ' or '',
e.extrapolated and ' Extrapolated ' or '',
e.boosted and ' Boosted ' or '',
e.high_priority and ' High Priority ' or ''
}
data = {BT = time_to_ticks(e.backtrack),target = entity_get_player_name(e.target),pred_dmg = e.damage,pred_hc = e.hit_chance,pred_group = group}
end)
client_set_event_callback("aim_hit", function(hit)
hit_group = hitgroup_names[hit.hitgroup + 1] or '?'
if ui_get(ref.sp) then sp="True" else sp="false" end
local data_hit = {target = entity_get_player_name(hit.target),dmg = hit.damage,hc = hit.hit_chance,group = group}
if ui_get(enable) then
client_log("[HIT] Target : "..data_hit.target.." | Damage : "..data_hit.dmg.." (Pred : "..data.pred_dmg..")".." | Hit chance : "..data_hit.dmg.." (Pred : "..data.pred_hc ..")".." | HitBox : "..hit_group.." (Pred : "..shot_group..")".. "| Backtrack : "..data.BT.." safepoint : "..sp.." | Flags : " ..table_concat(flags))
end
end)
client_set_event_callback("aim_miss", function(miss)
if ui_get(ref.sp) then sp="True" else sp="false" end
if miss.reason == "?" then reason="Resolver" else reason=miss.reason end
miss_group = hitgroup_names[miss.hitgroup + 1] or '?'
if ui_get(enable) then
client_log("[MISS] Target : "..data.target.." | Pred dmg : " .. data.pred_dmg .. " | Missed Hitbox : "..miss_group.." | Predicted HC : " ..data.pred_hc.."| BT : "..data.BT.." Miss Reason : "..reason.." | Flags : " .. table_concat(flags))
end
end) |
local _hxClasses = {}
Int = (function() _hxClasses.Int = _hx_o({__fields__={__name__=true},__name__={"Int"}}); return _hxClasses.Int end)();
Dynamic = (function() _hxClasses.Dynamic = _hx_o({__fields__={__name__=true},__name__={"Dynamic"}}); return _hxClasses.Dynamic end)();
Float = (function() _hxClasses.Float = _hx_e(); return _hxClasses.Float end)();
Float.__name__ = {"Float"}
Bool = _hx_e();
Class = (function() _hxClasses.Class = _hx_o({__fields__={__name__=true},__name__={"Class"}}); return _hxClasses.Class end)();
Enum = _hx_e();
|
require('plugins')
require('config/notify')
require('config/keybindings')
require('config/colorscheme')
require('config/treesitter')
require('config/lualine')
require('completion')
require('config/go')
require('config/python')
require('rust')
require('config/ruby')
require('config/telescope')
require('config/options')
|
-------------------------------------------------------------------------------
-- Mob Framework Settings Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allowed to pretend you have written it.
--
--! @file init.lua
--! @brief settings gui for mobf
--! @copyright Sapier
--! @author Sapier
--! @date 2014-05-30
--
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
function fgettext(text)
return text
end
--!path of mod
local modpath = minetest.get_modpath("mobf_settings")
dofile (modpath .. DIR_DELIM .. "settings.lua")
|
return function()
local Knit = require(game:GetService("ReplicatedStorage").Knit)
local Streamable = require(Knit.Util.Streamable)
local instanceFolder
local function CreateInstance(name)
local folder = Instance.new("Folder")
folder.Name = name
folder.Archivable = false
folder.Parent = instanceFolder
return folder
end
beforeAll(function()
instanceFolder = Instance.new("Folder")
instanceFolder.Name = "KnitTest"
instanceFolder.Archivable = false
instanceFolder.Parent = workspace
end)
afterEach(function()
instanceFolder:ClearAllChildren()
end)
afterAll(function()
instanceFolder:Destroy()
end)
describe("Streamable", function()
it("should detect instance that is immediately available", function()
local testInstance = CreateInstance("TestImmediate")
local streamable = Streamable.new(instanceFolder, "TestImmediate")
local observed = 0
local cleaned = 0
streamable:Observe(function(_instance, janitor)
observed += 1
janitor:Add(function()
cleaned += 1
end)
end)
task.wait()
testInstance.Parent = nil
task.wait()
testInstance.Parent = instanceFolder
task.wait()
streamable:Destroy()
task.wait()
expect(observed).to.equal(2)
expect(cleaned).to.equal(2)
end)
it("should detect instance that is not immediately available", function()
local streamable = Streamable.new(instanceFolder, "TestImmediate")
local observed = 0
local cleaned = 0
streamable:Observe(function(_instance, janitor)
observed += 1
janitor:Add(function()
cleaned += 1
end)
end)
task.wait(0.1)
local testInstance = CreateInstance("TestImmediate")
task.wait()
testInstance.Parent = nil
task.wait()
testInstance.Parent = instanceFolder
task.wait()
streamable:Destroy()
task.wait()
expect(observed).to.equal(2)
expect(cleaned).to.equal(2)
end)
end)
end |
--[[
Authors: Alberto and Ricardo Romanach
GitHub page: https://github.com/rawii22/PlayerStatus
Notes: In order to understand some terminology in the comments, I'll describe some stuff here.
Scenario 1: non-dedicated non-caves
Scenario 2: non-dedicated with caves
Scenario 3: dedicated non-caves
Scenario 4: dedicated with caves
]]
local Widget = GLOBAL.require("widgets/widget")
local Text = GLOBAL.require("widgets/text")
local json = GLOBAL.json
local pcall = GLOBAL.pcall
local HOSTONLY = GetModConfigData("HOSTONLY")
local TOGGLEKEY = GetModConfigData("TOGGLEKEY")
local SHOWPENALTY = GetModConfigData("SHOWPENALTY")
local SHOWPLAYERNUMS = GetModConfigData("SHOWPLAYERNUMS")
local HIDEOWNSTATS = GetModConfigData("HIDEOWNSTATS")
local STATNUMFORMAT = GetModConfigData("STATNUMFORMAT")
local STATSTEXT = GetModConfigData("ABBREVIATESTATS")
local SCALE = GetModConfigData("SCALE")
local externalPlayerList
local closeMessage = "Press \""..TOGGLEKEY.."\" to close\n"
local playerData
function IsEnabled()
return (HOSTONLY and GLOBAL.TheNet:GetIsServerAdmin()) or not HOSTONLY --for some reason, we cannot use ismastersim, so we must use a TheNet function
end
--This sets up the netvar for sending the player data from the server to clients (including the host when necessary)
--Every player with a "player_classified" will have a whole copy of the player stat list.
AddPrefabPostInit("player_classified", function(player)
player._playerDataString = GLOBAL.net_string(player.GUID, "_playerDataString", "playerdatadirty")
if IsEnabled() then --taking advantage of the ismastersim check in one place
player:ListenForEvent("playerdatadirty", RefreshClientText, player)
end
end)
--creates and formats text properties
AddSimPostInit(function()
if IsEnabled() then
CreateText()
local startPos = CalcBasePos()
playerData:SetPosition(startPos)--(3600,900,0)
playerData:SetHAlign(GLOBAL.ANCHOR_LEFT)
playerData:SetAlpha(.8)
--only set up the periodic tasks on the server side
if GLOBAL.TheWorld.ismastersim then
--Scenario 2 and 4. Each shard will run it's own periodic task. (The IsMaster() and IsSecondary() functions will always return false if caves are not enabled)
if GLOBAL.TheShard:IsMaster() or GLOBAL.TheShard:IsSecondary() then
--In this periodic task, we collect the local player data and SEND it to the opposite shard via json and RPC.
--Originally, we tried sending all the player objects themselves, but those were too ridiculously large. Json was not able to encode all the data.
GLOBAL.TheWorld:DoPeriodicTask(30 * GLOBAL.FRAMES, function()
local r, result = pcall(json.encode, GetPlayerData(GLOBAL.AllPlayers, true))
if not r then print("[Player Status] Could not encode player stat data.") end
if result then
SendModRPCToShard(GetShardModRPC(modname, "SendPlayerList"), nil, nil, nil, result)
end
end)
--Scenario 1 and 3. There is only one server to set up a periodic task for. There's no need for an RPC since there's only one shard
else
GLOBAL.TheWorld:DoPeriodicTask(30 * GLOBAL.FRAMES, function() RefreshText(GetPlayerData(GLOBAL.AllPlayers)) end)
end
end
end
end)
function CreateText()
playerData = Text("stint-ucr", SCALE, GetPlayerData(GLOBAL.AllPlayers))
end
--update the text and then update netvar for clients. This will trigger the netvar's dirty function, RefreshClientText
function RefreshText(data)
playerData:SetString(data)
playerData:SetPosition(CalcBasePos())
for k,player in pairs(GLOBAL.AllPlayers) do
if player.player_classified then
player.player_classified._playerDataString:set(data)
end
end
end
--updates the text widget for clients
function RefreshClientText(player)
local data = player._playerDataString:value()
playerData:SetString(data)
playerData:SetPosition(CalcBasePos())
end
--only run on the host and then sent to the client via netvar in the prefab post init
function GetPlayerData(players, asTable)
local statString = (asTable and "" or closeMessage)
local statTable = {}
for k,player in pairs(players) do
local currentStat = (SHOWPLAYERNUMS and not asTable and k..": " or "")
if HIDEOWNSTATS and player.GUID == GLOBAL.ThePlayer.GUID then
currentStat = currentStat..(SHOWPLAYERNUMS and "[You]" or "")
else
local hungerStats = STATSTEXT.HUNGER.." "..string.gsub(STATNUMFORMAT, "%$(%w+)",
{
current=(player:HasTag("playerghost") and "0" or math.floor(player.components.hunger.current+0.5)),
maximum=player.components.hunger.max,
percent=math.floor((player:HasTag("playerghost") and 0 or player.components.hunger.current)/player.components.hunger.max*100+0.5),
})
local sanityStats = " | "..STATSTEXT.SANITY.." "..string.gsub(STATNUMFORMAT, "%$(%w+)",
{
current=(player:HasTag("playerghost") and "0" or math.floor(player.components.sanity.current+0.5)),
maximum=player.components.sanity.max,
percent=math.floor((player:HasTag("playerghost") and 0 or player.components.sanity.current)/player.components.sanity.max*100+0.5),
})
local healthStats = player.components.health and " | "..STATSTEXT.HEALTH.." "..string.gsub(STATNUMFORMAT, "%$(%w+)",
{
current=(player:HasTag("playerghost") and "0" or math.floor(player.components.health.currenthealth+0.5)),
maximum=math.floor(player.components.health.maxhealth*(1-player.components.health.penalty)+0.5),
percent=math.floor((player:HasTag("playerghost") and 0 or player.components.health.currenthealth)/player.components.health.maxhealth*100+0.5),
}) or ""
--add age stat here later for Wanda users
currentStat = currentStat..player.name.." ("..player.prefab..")"..(player:HasTag("playerghost") and " [DEAD]" or "")
..((player.components.builder.freebuildmode or player.components.health.invincible) and " |" or "")
..(player.components.builder.freebuildmode and " [Free-crafting]" or "")
..(player.components.health.invincible and " [God-mode]" or "").."\n"
..hungerStats
..sanityStats..((SHOWPENALTY and player.components.sanity.penalty > 0) and " (-"..math.floor(player.components.sanity.penalty*100+0.5).."%)" or "")
..healthStats..((SHOWPENALTY and player.components.health.penalty > 0) and " (-"..math.floor(player.components.health.penalty*100+0.5).."%)" or "").."\n"
end
--this is awful, we were lazy
if asTable then
table.insert(statTable, currentStat)
else
statString = statString..currentStat
end
end
return (asTable and statTable or statString)
end
--must use proportions instead of coordinates since we won't know the screen size.
function CalcBasePos()
local screensize = {GLOBAL.TheSim:GetScreenSize()}
local playerDataSize = {playerData:GetRegionSize()}
local marginX = screensize[1] * 0.08 --determined visually
local marginY = screensize[2] * 0.25
return GLOBAL.Vector3(
(screensize[1] - playerDataSize[1]/2 - marginX),
(screensize[2]/2 - playerDataSize[2]/2 + marginY),
0
)
end
--just a bunch of screen positioning math
AddClassPostConstruct("widgets/controls", function(controls)
if IsEnabled() then
local screensize = {GLOBAL.TheSim:GetScreenSize()}
local rootscale = playerData:GetScale()
local OnUpdate_base = controls.OnUpdate
controls.OnUpdate = function(self, dt)
OnUpdate_base(self, dt)
local curscreensize = {GLOBAL.TheSim:GetScreenSize()}
local currentPos = playerData:GetPosition()
local currentScale = playerData:GetScale()
if curscreensize[1] ~= screensize[1] or curscreensize[2] ~= screensize[2] then
local newXScale = curscreensize[1] / screensize[1]
local newYScale = curscreensize[2] / screensize[2]
playerData:SetPosition(currentPos.x * newXScale, currentPos.y * newYScale, 0)
playerData:SetScale(currentScale.x * newXScale, currentScale.y * newYScale, 0)
screensize = curscreensize
end
end
end
end)
--just something that came with the AddKeyUpHandler from some other mod (don't remember which...)
function IsDefaultScreen()
if GLOBAL.TheFrontEnd:GetActiveScreen() and GLOBAL.TheFrontEnd:GetActiveScreen().name and type(GLOBAL.TheFrontEnd:GetActiveScreen().name) == "string" and GLOBAL.TheFrontEnd:GetActiveScreen().name == "HUD" then
return true
else
return false
end
end
GLOBAL.TheInput:AddKeyUpHandler(
TOGGLEKEY:lower():byte(),
function()
if not GLOBAL.IsPaused() and IsDefaultScreen() and IsEnabled() then
if playerData:IsVisible() then
playerData:Hide()
else
playerData:Show()
end
end
end
)
local playerList
--Klei is really nice and provided a way to communicate between shards with the AddShardModRPCHandler mod util.
--shardId is ID of the shard that sent the RPC
--This is what receives the list of players from the opposite shard and combines them in the proper order (overworld first, then cave players) then saves it to the netvar through RefreshText.
AddShardModRPCHandler(modname, "SendPlayerList", function(shardId, namespace, code, externalPlayerListJson)
local r
r, externalPlayerList = pcall(json.decode, externalPlayerListJson)
if not r then print("Could not decode all items: "..tostring(externalPlayerListJson)) end
if externalPlayerList then
-- Only run if the shard calling the RPC is different from current shard
if GLOBAL.TheShard:GetShardId() ~= tostring(shardId) then
local playerStatString = ""
if GLOBAL.TheShard:IsMaster() then
playerStatString = GetPlayerData(GLOBAL.AllPlayers)
for k, player in pairs(externalPlayerList) do
playerStatString = playerStatString..(SHOWPLAYERNUMS and ((#GLOBAL.AllPlayers + k)..": ") or "").."**"..player --the "**" indicates players in caves
end
else
playerStatString = closeMessage
for k, player in pairs(externalPlayerList) do
playerStatString = playerStatString..(SHOWPLAYERNUMS and (k..": ") or "")..player
end
for k, player in pairs(GetPlayerData(GLOBAL.AllPlayers, true)) do
playerStatString = playerStatString..(SHOWPLAYERNUMS and ((#externalPlayerList + k)..": ") or "").."**"..player
end
end
RefreshText(playerStatString)
end
end
end)
-----------ADDITIONAL CONSOLE FUNCTIONS-----------
--for testing. calculated using the points from the config options using Desmos
function GLOBAL.ChangeScale(playercount)
local size = 682.827/playercount + 1.8269
playerData:SetSize(size)
end
--This function first figures out if the target function (fn) needs to be run on another shard (based on playerNum) and then either sends it to the other shard or executes it locally
local function ExecuteOnShardWithPlayer(playerNum, fn, fnstring)
local shardPlayerNum = playerNum
if GLOBAL.TheShard:IsSecondary() then
shardPlayerNum = playerNum - #externalPlayerList --if we're in the caves, subtract the number of people in the overworld
end
if GLOBAL.TheShard:IsMaster() and playerNum > #GLOBAL.AllPlayers then --if called from the overworld, send the function to the caves
SendModRPCToShard(GetShardModRPC(modname, "ShardInjection"), nil, nil, nil, fnstring)
return
elseif GLOBAL.TheShard:IsSecondary() and shardPlayerNum <= 0 then --if called from the caves, send the function to the caves
SendModRPCToShard(GetShardModRPC(modname, "ShardInjection"), nil, nil, nil, fnstring)
return
end
--this will run locally if the target player is in the same shard as the caller
fn(shardPlayerNum)
end
--These functions create a mini local function with the desired code, and then defers to ExecuteOnShardWithPlayer for proper execution.
function GLOBAL.RevivePlayer(playerNum)
local function fn(playerNum)
GLOBAL.AllPlayers[playerNum]:PushEvent("respawnfromghost")
end
ExecuteOnShardWithPlayer(playerNum, fn, "RevivePlayer("..playerNum..")")
end
function GLOBAL.RefillStats(playerNum)
local function fn(playerNum)
if GLOBAL.TheWorld.ismastersim and GLOBAL.AllPlayers[playerNum] and not GLOBAL.AllPlayers[playerNum]:HasTag("playerghost") then
GLOBAL.AllPlayers[playerNum].components.health:SetPenalty(0)
GLOBAL.AllPlayers[playerNum].components.health:SetPercent(1)
GLOBAL.AllPlayers[playerNum].components.sanity:SetPercent(1)
GLOBAL.AllPlayers[playerNum].components.hunger:SetPercent(1)
GLOBAL.AllPlayers[playerNum].components.temperature:SetTemperature(25)
GLOBAL.AllPlayers[playerNum].components.moisture:SetPercent(0)
end
end
ExecuteOnShardWithPlayer(playerNum, fn, "RefillStats("..playerNum..")")
end
function GLOBAL.Godmode(playerNum)
local function fn(playerNum)
GLOBAL.c_godmode(GLOBAL.AllPlayers[playerNum])
end
ExecuteOnShardWithPlayer(playerNum, fn, "Godmode("..playerNum..")")
end
--very dangerous RPC, which is why it's not accessible from the console
AddShardModRPCHandler(modname, "ShardInjection", function(shardId, namespace, code, injection)
-- Only run if the shard calling the RPC is different from current shard
if GLOBAL.TheShard:GetShardId() ~= tostring(shardId) then
GLOBAL.ExecuteConsoleCommand(injection) --just for fun...
end
end) |
identitycontrols = {};
function setCurrent(name)
local idctrl = identitycontrols[name];
if idctrl then
-- Deactivate all identities
for k, v in pairs(identitycontrols) do
v.setCurrent(false);
end
-- Set active
idctrl.setCurrent(true);
end
end
function addIdentity(name, isgm)
local idctrl = identitycontrols[name];
-- Create control if not found
if not idctrl then
createControl("identitylistentry", "ctrl_" .. name);
idctrl = self["ctrl_" .. name];
identitycontrols[name] = idctrl;
idctrl.createLabel(name, isgm);
end
end
function removeIdentity(name)
local idctrl = identitycontrols[name];
if idctrl then
idctrl.destroy();
identitycontrols[name] = nil;
end
end
function renameGmIdentity(name)
for k,v in pairs(identitycontrols) do
if v.gmidentity then
v.rename(name);
identitycontrols[name] = v;
identitycontrols[k] = nil;
return;
end
end
end
function onInit()
GmIdentityManager.registerIdentityList(self);
end
|
local function build_color(r, g, b)
if not r then
r = 0
end
if not g then
g = 0
end
if not b then
b = 0
end
local res = fill_surface(32, 32, r, g, b)
if not res then
return BADID
end
return {"image", res}
end
return function(types)
return {
handler = build_color,
args = {types.FACTORY, types.NUMBER, types.NUMBER, types.NUMBER},
names = {"red", "green", "blue"},
argc = 3,
help = "Returns a single color cell.",
type_helper = {},
}
end
|
vim.cmd([[
augroup general
autocmd!
autocmd TermOpen term://* startinsert
autocmd FocusGained * :checktime
autocmd Filetype lua nnoremap <silent><leader>nv <cmd>lua require'telescope.builtin'.find_files{ cwd = "~/.config/nvim" }<CR>
augroup END
]])
vim.cmd([[
autocmd FileType lua lua require'cmp'.setup.buffer {sources = {{ name = 'nvim_lua' },{ name = 'buffer' }}}
]])
vim.cmd([[
augroup web
autocmd!
autocmd InsertLeave *.css :BLReloadCSS
autocmd FileType html nnoremap <F3> :!http-server . &<CR><CR>
autocmd FileType html nnoremap <F4> :!setsid firefox http://localhost:8080/%<CR><CR>
autocmd VimLeave *.html !killall node
augroup END
]])
vim.cmd([[
augroup rust
autocmd!
autocmd BufNewFile,BufRead *.rs set filetype=rust
autocmd FileType rust nnoremap <F3> :w<CR> :16split term://rustc % && ./%:r<CR>
autocmd FileType rust nnoremap <F4> :w<CR> :16split term://cargo run<CR>
autocmd FileType rust nnoremap <F5> :w<CR> :16split term://cargo run --<Space>
autocmd FileType rust nnoremap <leader><F4> :w<CR> :16split term://cargo run --target x86_64-unknown-linux-musl<CR>
autocmd FileType rust nnoremap <leader>t :call Rust_toggle()<CR>
autocmd FileType rust nnoremap <silent><leader>. a-><space>
augroup END
]])
vim.cmd([[
augroup nim
autocmd!
autocmd BufNewFile,BufRead *.nim set filetype=nim
autocmd FileType nim nnoremap <F3> :w<CR> :16split term://nim c -r %<CR>
autocmd FileType nim nnoremap <F4> :w<CR> :16split term://nimble run *.nimble<CR>
autocmd FileType nim nnoremap <F5> :w<CR> :16split term://nimble run *.nimble
autocmd FileType nim nnoremap <leader>t :call Nim_toggle()<CR>
augroup END
]])
vim.cmd([[
augroup cc
autocmd!
autocmd FileType c,cpp nnoremap <F3> :w<CR> :16split term://make<CR>
autocmd FileType c,cpp nnoremap <leader><F3> :w<CR> :16split term://make -B<CR>
autocmd FileType c,cpp nnoremap <F4> :w<CR> :16split term://make run<CR>
autocmd FileType c,cpp nnoremap <F5> :w<CR> :16split term://make run ARGS=
autocmd FileType c,cpp nnoremap <F6> :w<CR> :16split term://./%:r<CR>
autocmd Filetype c,cpp nnoremap <silent><leader>fm :!clang-format -style="{BasedOnStyle: google, IndentWidth: 4}" -i % <CR><CR>
augroup END
]])
vim.cmd([[
augroup nvim
autocmd!
autocmd FileType lua nnoremap <F5> :source ~/.config/nvim/init.lua<CR>
augroup END
]])
vim.cmd([[
augroup cloj
autocmd!
autocmd FileType clojure nnoremap <F3> :FireplaceConnect 127.0.0.1:
autocmd FileType clojure nnoremap <F4> :16sp term://lein run<CR>
autocmd FileType clojure nnoremap <F5> :16sp term://lein run
autocmd FileType clojure nnoremap <leader>e :%Eval<CR>
autocmd FileType clojure vnoremap <leader>e :Eval<CR>
autocmd FileType clojure nnoremap <leader>dd :Doc <C-R><C-W><CR>
autocmd FileType clojure setlocal lisp
augroup END
]])
vim.cmd([[
augroup vimwik
autocmd!
autocmd FileType vimwiki nnoremap <F3> :Vimwiki2HTMLBrowse<CR>
autocmd FileType vimwiki nnoremap <F4> :VimwikiTable<CR>
autocmd FileType vimwiki nnoremap <F5> :!setsid firefox ~/vimwiki_html/%:r.html<CR><CR>
autocmd FileType vimwiki nnoremap <leader>h1 I= <ESC>A =<ESC>
autocmd FileType vimwiki nnoremap <leader>h2 I== <ESC>A ==<ESC>
autocmd FileType vimwiki nnoremap <leader>h3 I=== <ESC>A ===<ESC>
autocmd FileType vimwiki nnoremap <leader>h4 I==== <ESC>A ====<ESC>
autocmd FileType vimwiki nnoremap <leader>h5 I===== <ESC>A =====<ESC>
augroup END
]])
vim.cmd([[
augroup highlight_yank
autocmd!
au TextYankPost * silent! lua vim.highlight.on_yank{higroup="IncSearch", timeout=500}
augroup END
]])
vim.cmd([[
augroup i3syntax
autocmd!
autocmd BufRead $HOME/.config/i3/config set ft=i3config
augroup END
]])
vim.cmd([[
augroup tex
autocmd!
autocmd FileType tex let b:AutoPairs = AutoPairsDefine({"$": "$"})
autocmd FileType tex nnoremap <F3> :!setsid zathura %:r.pdf<CR><CR>
autocmd FileType tex nnoremap <leader>lor a$\lor$
autocmd FileType tex nnoremap <leader>land a$\land$
autocmd FileType tex nnoremap <leader>neg a$\neg$
augroup END
]])
vim.cmd([[
augroup NvimDap
autocmd!
au FileType dap-repl lua require('dap.ext.autocompl').attach()
augroup END
]])
vim.cmd([[
augroup php
autocmd!
autocmd BufRead *.php set indentexpr =
autocmd BufRead *.php set autoindent
autocmd BufRead *.php set smartindent
augroup END
]])
vim.cmd[[
augroup pypy
autocmd FileType python nnoremap <F4> :16sp term://python %<CR>
autocmd Filetype python nnoremap <silent><leader>fm :!autopep8 -i % <CR><CR>:e %<CR>
augroup END
]]
|
local State = require("Lutron/State/State")
local StateMachine
do
local _class_0
local stateNameIndex, currentStateName
local _base_0 = {
addState = function(self, state)
if state.name == nil then
state.name = stateNameIndex
stateNameIndex = stateNameIndex + 1
end
self.states[state.name] = state
end,
currentState = function(self)
return self.states[currentStateName]
end,
enterState = function(self, name)
self.states[name]:enter(self.states[currentStateName])
self:currentState():exit(self.states[name])
currentStateName = name
end
}
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self, startingState)
if startingState == nil then
startingState = nil
end
self.states = { }
if startingState == nil then
startingState = State(self)
end
self:addState(startingState)
currentStateName = startingState.name
end,
__base = _base_0,
__name = "StateMachine"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
local self = _class_0
stateNameIndex = 1
currentStateName = nil
StateMachine = _class_0
return _class_0
end
|
project "glfw"
kind "StaticLib"
language "C"
staticruntime "on"
targetdir ("bin/%{cfg.buildcfg}")
objdir ("bin-obj/")
filter "system:windows"
systemversion "latest"
files
{
"include/GLFW/glfw2.h",
"include/GLFW/glfw2native.h",
"src/context.c",
"src/egl_context.c",
"src/init.c",
"src/input.c",
"src/monitor.c",
"src/null_init.c",
"src/null_joystick.c",
"src/null_monitor.c",
"src/null_window.c",
"src/osmesa_context.c",
"src/platform.c",
"src/vulkan.c",
"src/wgl_context.c",
"src/win31_init.c",
"src/win31_joystick.c",
"src/win31_module.c",
"src/win31_monitor.c",
"src/win31_thread.c",
"src/win31_time.c",
"src/win31_window.c",
"src/window.c"
}
defines
{
"_GLFW_WIN32",
"_CRT_SECURE_NO_WARNINGS"
}
filter "system:linux"
systemversion "latest"
cppdialect "c++2a"
files
{
"src/context.c",
"src/init.c",
"src/input.c",
"src/monitor.c",
"src/platform.c",
"src/vulkan.c",
"src/window.c",
"src/egl_context.c",
"src/osmesa_context.c",
"src/null_init.c",
"src/null_monitor.c",
"src/null_window.c",
"src/null_joystick.c",
"src/posix_module.c",
"src/posix_time.c",
"src/posix_thread.c",
"src/x11_init.c",
"src/x11_monitor.c",
"src/x11_window.c",
"src/xkb_unicode.c",
"src/glx_context.c",
"src/linux_joystick.c",
"src/posix_poll.c",
}
defines
{
"_GLFW_X11",
"_CRT_SECURE_NO_WARNINGS"
}
filter "configurations:Debug"
defines { "DEBUG" }
symbols "on"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "on"
|
function gadget:GetInfo()
return {
name = "No Self-D on share",
desc = "Prevents self-destruction when a unit changes hands or a player leaves",
author = "quantum, Bluestone",
date = "July 13, 2008",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
if (not gadgetHandler:IsSyncedCode()) then
function gadget:UnitGiven(unitID, unitDefID, unitTeam, oldTeam)
if (Spring.GetUnitSelfDTime(unitID) > 0) then
Spring.GiveOrderToUnit(unitID, CMD.SELFD, {}, {})
end
end
function gadget:PlayerChanged(playerID) --necessary wtfness, probably can remove in 97.0+
end
else
function gadget:PlayerChanged(playerID)
local _,active,spec,teamID = Spring.GetPlayerInfo(playerID)
if active and not spec then return end
local team = Spring.GetPlayerList(teamID)
if team then
-- check team is empty
for _,pID in pairs(team) do
_,active,spec = Spring.GetPlayerInfo(pID)
if active and not spec then
return
end
end
-- cancel any self d orders
local units = Spring.GetTeamUnits(teamID)
for _,unitID in pairs(units) do
if (Spring.GetUnitSelfDTime(unitID) > 0) then
Spring.GiveOrderToUnit(unitID, CMD.SELFD, {}, {})
end
end
end
end
end
|
local Model = require("lapis.db.model").Model
local schema = require("lapis.db.schema")
local types = schema.types
local lapis = require("lapis")
local db = require("lapis.db")
local uuid = require("uuid")
-- Localize
local cwd = (...):gsub('%.[^%.]+$', '') .. "."
local oss_options = require(cwd .. "GameDbUrls").getOptions()
local _M = {
_db_entity = Model:extend(oss_options, "_oss_stats_retention", {
primary_key = "day"
}),
}
function _M.get(theDay)
return _M._db_entity:find({ day = theDay })
end
function _M.getPage(theDay)
local paginated = _M._db_entity:paginated("WHERE day >= ? ORDER BY DAY ASC", theDay, {
per_page = 10,
prepare_results = function(posts)
--Users:include_in(posts, "user_id")
return posts
end
})
local page1 = paginated:get_page(1)
return page1
end
return _M |
--waf_cookie.lua
|
local ctx = reaper.ImGui_CreateContext('Drum Humanizer')
local size = reaper.GetAppVersion():match('OSX') and 12 or 14
local font = reaper.ImGui_CreateFont('sans-serif', size)
reaper.ImGui_AttachFont(ctx, font)
widgets = {}
widgets.multi_component = {
vector = reaper.new_array({ 1.0,1.0,1.0,1.0 })
}
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
local r = reaper
x0 = 3
y0 = 4
hard_velo_max = 110
hard_velo_min = 90
weak_velo_max = 60
weak_velo_min = 40
ppq = 960
nudge = 12
steps = 4
downstroke = true
-- Initialize pattern
_vector = {}-- vec4 = { 1.0,1.0,1.0,1.0 }
take = reaper.MIDIEditor_GetTake(reaper.MIDIEditor_GetActive());
retval, notes, ccs, sysex = reaper.MIDI_CountEvts(take);
math.randomseed(os.clock()*100000000000)
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
-- table.sort(a, function (a, b) return a>b end)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
function humanize(pattern,hard_velo_max,hard_velo_min,weak_velo_max,weak_velo_min)
notesordered = {}
k = 0
-- Get all notes
for j = 0, notes-1 do
retval, sel, muted, startppqposOut, endppqposOut, chan, pitch, vel = reaper.MIDI_GetNote(take, j)
-- Filter for selected notes
if sel == true then
reaper.ShowConsoleMsg(startppqposOut)
reaper.ShowConsoleMsg(' ')
-- reaper.ShowConsoleMsg(sel)
reaper.ShowConsoleMsg('\n')
if pattern[(k % #pattern)+1] then
-- initialize random base velocity
randomval = math.random(hard_velo_min, hard_velo_max);
else
randomval = math.random(weak_velo_min, weak_velo_max);
end
vel = randomval
reaper.MIDI_SetNote(take, j, false, muted, startppqposOut,endppqposOut, chan, pitch, vel, true);
k=k+1
end
end
for key,value in pairs(notesordered)
do
-- initialize random base velocity
randomval = math.random(hard_velo_min, hard_velo_max);
retval, sel, muted, startppqposOut, endppqposOut, chan, pitch, vel = reaper.MIDI_GetNote(take, value)
if sel == true then
reaper.ShowConsoleMsg(startppqposOut)
reaper.ShowConsoleMsg(' ')
reaper.ShowConsoleMsg(value)
reaper.ShowConsoleMsg('\n')
-- vel = randomval-math.random(soff_velo_min, soff_velo_max)*k;
vel = array[(k % #array)+1]
reaper.MIDI_SetNote(take, value, false, muted, startppqposOut,endppqposOut, chan, pitch, vel, true);
k=k+1
end
end
end
function high_velos()
hard_velo_max = 110
hard_velo_min = 90
weak_velo_max = 60
weak_velo_min = 40
end
function low_velos()
hard_velo_max = 70
hard_velo_min = 50
weak_velo_max = 40
weak_velo_min = 20
end
function generate_pattern(array)
pattern = {}
val = true
for i=1,#array do
for j=1,array[i] do
pattern[#pattern+1] = val
end
val = not val
end
end
-- Define Content of ReaImgUi
function frame()
for i = 1,steps do
_vector[i]=1
end
-- Convert to reaper.array
vector = reaper.new_array(_vector)
local rv
reaper.ImGui_Text(ctx, 'Pattern Selection')
reaper.ImGui_Text(ctx, 'Cycles through selected notes and assigns randomized velocity following alternating hard-soft patterns')
if r.ImGui_BeginTabBar(ctx, 'MyTabBar', r.ImGui_TabBarFlags_None()) then
if r.ImGui_BeginTabItem(ctx, '1') then
reaper.ImGui_Text(ctx, 'One Hard')
generate_pattern({1})
r.ImGui_EndTabItem(ctx)
end
if r.ImGui_BeginTabItem(ctx, '1-0') then
reaper.ImGui_Text(ctx, 'One Hard, One Soft (Double Base, Tom rolls)')
generate_pattern({1,1})
r.ImGui_EndTabItem(ctx)
end
if reaper.ImGui_BeginTabItem(ctx, '1-0-1') then
reaper.ImGui_Text(ctx, 'Hard, Soft, Hard (Gallop beats)')
generate_pattern({1,1,1})
r.ImGui_EndTabItem(ctx)
end
if reaper.ImGui_BeginTabItem(ctx, '1-x-1') then
reaper.ImGui_Text(ctx, 'Hard, x-times Soft, Hard')
rv, x0 = reaper.ImGui_InputInt(ctx, 'Weak hits', x0)
generate_pattern({1,x0,1})
r.ImGui_EndTabItem(ctx)
end
if reaper.ImGui_BeginTabItem(ctx, '1-x') then
reaper.ImGui_Text(ctx, 'Hard + x-times Soft (Steady cymbals)')
rv, x0 = reaper.ImGui_InputInt(ctx, 'Weak hits', x0)
generate_pattern({1,x0})
r.ImGui_EndTabItem(ctx)
end
if reaper.ImGui_BeginTabItem(ctx, '1-x-1-y') then
reaper.ImGui_Text(ctx, 'Hard + x-times Soft, Hard + y-times Soft')
rv, x0 = reaper.ImGui_InputInt(ctx, 'Weak hits x', x0)
rv, y0 = reaper.ImGui_InputInt(ctx, 'Weak hits y', y0)
generate_pattern({1,x0,1,y0})
r.ImGui_EndTabItem(ctx)
end
if reaper.ImGui_BeginTabItem(ctx, 'Custom') then
reaper.ImGui_Text(ctx, 'Create custom Hard-Soft pattern.')
rv, steps = reaper.ImGui_InputInt(ctx, 'Pattern steps', steps)
r.ImGui_InputDoubleN(ctx, 'Custom pattern', vector,nil,nil,'%.0f')
generate_pattern(vector)
r.ImGui_EndTabItem(ctx)
end
if reaper.ImGui_Button(ctx, 'HUMANIZE!!!') then
reaper.ShowConsoleMsg(dump(pattern))
humanize(pattern,hard_velo_max,hard_velo_min,weak_velo_max,weak_velo_min)
end
reaper.ImGui_Text(ctx, '')
reaper.ImGui_Text(ctx, 'Velocity Selection')
if reaper.ImGui_Button(ctx, 'High Velos') then
high_velos()
end
reaper.ImGui_SameLine(ctx)
if reaper.ImGui_Button(ctx, 'Low velos') then
low_velos()
end
rv, hard_velo_max = reaper.ImGui_InputInt(ctx, 'Hard Max Velocity', hard_velo_max)
rv, hard_velo_min = reaper.ImGui_InputInt(ctx, 'Hard Min Velocity', hard_velo_min)
rv, weak_velo_max = reaper.ImGui_InputInt(ctx, 'Weak Max Velocity', weak_velo_max)
rv, weak_velo_min = reaper.ImGui_InputInt(ctx, 'Weak Min Velocity', weak_velo_min)
r.ImGui_EndTabBar(ctx)
end
end
-- initalize ReaImGui
function loop()
reaper.ImGui_PushFont(ctx, font)
reaper.ImGui_SetNextWindowSize(ctx, 400, 80, reaper.ImGui_Cond_FirstUseEver())
local visible, open = reaper.ImGui_Begin(ctx, 'Drum Humanizer', true)
if visible then
frame()
reaper.ImGui_End(ctx)
end
reaper.ImGui_PopFont(ctx)
if open then
reaper.defer(loop)
else
reaper.ImGui_DestroyContext(ctx)
end
end
reaper.defer(loop) |
--- Type-checking functions.
-- Functions and definitions for doing a basic lint check on files
-- loaded by LuaRocks.
--module("luarocks.type_check", package.seeall)
local type_check = {}
package.loaded["luarocks.type_check"] = type_check
local cfg = require("luarocks.cfg")
local deps = require("luarocks.deps")
type_check.rockspec_format = "1.1"
local string_1 = { _type = "string" }
local number_1 = { _type = "number" }
local mandatory_string_1 = { _type = "string", _mandatory = true }
-- Syntax for type-checking tables:
--
-- A type-checking table describes typing data for a value.
-- Any key starting with an underscore has a special meaning:
-- _type (string) is the Lua type of the value. Default is "table".
-- _version (string) is the minimum rockspec_version that supports this value. Default is "1.0".
-- _mandatory (boolean) indicates if the value is a mandatory key in its container table. Default is false.
-- For "string" types only:
-- _pattern (string) is the string-matching pattern, valid for string types only. Default is ".*".
-- For "table" types only:
-- _any (table) is the type-checking table for unspecified keys, recursively checked.
-- _more (boolean) indicates that the table accepts unspecified keys and does not type-check them.
-- Any other string keys that don't start with an underscore represent known keys and are type-checking tables, recursively checked.
local rockspec_types = {
rockspec_format = string_1,
package = mandatory_string_1,
version = { _type = "string", _pattern = "[%w.]+-[%d]+", _mandatory = true },
description = {
summary = string_1,
detailed = string_1,
homepage = string_1,
license = string_1,
maintainer = string_1,
},
dependencies = {
platforms = {}, -- recursively defined below
_any = string_1,
},
supported_platforms = {
_any = string_1,
},
external_dependencies = {
platforms = {}, -- recursively defined below
_any = {
program = string_1,
header = string_1,
library = string_1,
}
},
source = {
_mandatory = true,
platforms = {}, -- recursively defined below
url = mandatory_string_1,
md5 = string_1,
file = string_1,
dir = string_1,
tag = string_1,
branch = string_1,
module = string_1,
cvs_tag = string_1,
cvs_module = string_1,
},
build = {
platforms = {}, -- recursively defined below
type = string_1,
install = {
lua = {
_more = true
},
lib = {
_more = true
},
conf = {
_more = true
},
bin = {
_more = true
}
},
copy_directories = {
_any = string_1,
},
_more = true,
_mandatory = true
},
hooks = {
platforms = {}, -- recursively defined below
post_install = string_1,
},
deploy = {
_version = "1.1",
wrap_bin_scripts = { _type = "boolean", _version = "1.1" },
}
}
type_check.rockspec_order = {"rockspec_format", "package", "version",
{ "source", { "url", "tag", "branch", "md5" } },
{ "description", {"summary", "detailed", "homepage", "license" } },
"supported_platforms", "dependencies", "external_dependencies",
{ "build", {"type", "modules", "copy_directories", "platforms"} },
"hooks"}
rockspec_types.build.platforms._any = rockspec_types.build
rockspec_types.dependencies.platforms._any = rockspec_types.dependencies
rockspec_types.external_dependencies.platforms._any = rockspec_types.external_dependencies
rockspec_types.source.platforms._any = rockspec_types.source
rockspec_types.hooks.platforms._any = rockspec_types.hooks
local manifest_types = {
repository = {
_mandatory = true,
-- packages
_any = {
-- versions
_any = {
-- items
_any = {
arch = mandatory_string_1,
modules = { _any = string_1 },
commands = { _any = string_1 },
dependencies = { _any = string_1 },
-- TODO: to be extended with more metadata.
}
}
}
},
modules = {
_mandatory = true,
-- modules
_any = {
-- providers
_any = string_1
}
},
commands = {
_mandatory = true,
-- modules
_any = {
-- commands
_any = string_1
}
},
dependencies = {
-- each module
_any = {
-- each version
_any = {
-- each dependency
_any = {
name = string_1,
constraints = {
_any = {
no_upgrade = { _type = "boolean" },
op = string_1,
version = {
string = string_1,
_any = number_1,
}
}
}
}
}
}
}
}
local function check_version(version, typetbl, context)
local typetbl_version = typetbl._version or "1.0"
if deps.compare_versions(typetbl_version, version) then
if context == "" then
return nil, "Invalid rockspec_format version number in rockspec? Please fix rockspec accordingly."
else
return nil, context.." is not supported in rockspec format "..version.." (requires version "..typetbl_version.."), please fix the rockspec_format field accordingly."
end
end
return true
end
local type_check_table
--- Type check an object.
-- The object is compared against an archetypical value
-- matching the expected type -- the actual values don't matter,
-- only their types. Tables are type checked recursively.
-- @param version string: The version of the item.
-- @param item any: The object being checked.
-- @param typetbl any: The type-checking table for the object.
-- @param context string: A string indicating the "context" where the
-- error occurred (the full table path), for error messages.
-- @return boolean or (nil, string): true if type checking
-- succeeded, or nil and an error message if it failed.
-- @see type_check_table
local function type_check_item(version, item, typetbl, context)
assert(type(version) == "string")
local ok, err = check_version(version, typetbl, context)
if not ok then
return nil, err
end
local item_type = type(item) or "nil"
local expected_type = typetbl._type or "table"
if expected_type == "number" then
if not tonumber(item) then
return nil, "Type mismatch on field "..context..": expected a number"
end
elseif expected_type == "string" then
if item_type ~= "string" then
return nil, "Type mismatch on field "..context..": expected a string, got "..item_type
end
if typetbl._pattern then
if not item:match("^"..typetbl._pattern.."$") then
return nil, "Type mismatch on field "..context..": invalid value "..item.." does not match '"..typetbl._pattern.."'"
end
end
elseif expected_type == "table" then
if item_type ~= expected_type then
return nil, "Type mismatch on field "..context..": expected a table"
else
return type_check_table(version, item, typetbl, context)
end
elseif item_type ~= expected_type then
return nil, "Type mismatch on field "..context..": expected "..expected_type
end
return true
end
local function mkfield(context, field)
if context == "" then
return field
end
return context.."."..field
end
--- Type check the contents of a table.
-- The table's contents are compared against a reference table,
-- which contains the recognized fields, with archetypical values
-- matching the expected types -- the actual values of items in the
-- reference table don't matter, only their types (ie, for field x
-- in tbl that is correctly typed, type(tbl.x) == type(types.x)).
-- If the reference table contains a field called MORE, then
-- unknown fields in the checked table are accepted.
-- If it contains a field called ANY, then its type will be
-- used to check any unknown fields. If a field is prefixed
-- with MUST_, it is mandatory; its absence from the table is
-- a type error.
-- Tables are type checked recursively.
-- @param version string: The version of tbl.
-- @param tbl table: The table to be type checked.
-- @param typetbl table: The type-checking table, containing
-- values for recognized fields in the checked table.
-- @param context string: A string indicating the "context" where the
-- error occurred (such as the name of the table the item is a part of),
-- to be used by error messages.
-- @return boolean or (nil, string): true if type checking
-- succeeded, or nil and an error message if it failed.
type_check_table = function(version, tbl, typetbl, context)
assert(type(version) == "string")
assert(type(tbl) == "table")
assert(type(typetbl) == "table")
local ok, err = check_version(version, typetbl, context)
if not ok then
return nil, err
end
for k, v in pairs(tbl) do
local t = typetbl[k] or typetbl._any
if t then
local ok, err = type_check_item(version, v, t, mkfield(context, k))
if not ok then return nil, err end
elseif typetbl._more then
-- Accept unknown field
else
if not cfg.accept_unknown_fields then
return nil, "Unknown field "..k
end
end
end
for k, v in pairs(typetbl) do
if k:sub(1,1) ~= "_" and v._mandatory then
if not tbl[k] then
return nil, "Mandatory field "..mkfield(context, k).." is missing."
end
end
end
return true
end
local function check_undeclared_globals(globals, typetbl)
local undeclared = {}
for glob, _ in pairs(globals) do
if not (typetbl[glob] or typetbl["MUST_"..glob]) then
table.insert(undeclared, glob)
end
end
if #undeclared == 1 then
return nil, "Unknown variable: "..undeclared[1]
elseif #undeclared > 1 then
return nil, "Unknown variables: "..table.concat(undeclared, ", ")
end
return true
end
--- Type check a rockspec table.
-- Verify the correctness of elements from a
-- rockspec table, reporting on unknown fields and type
-- mismatches.
-- @return boolean or (nil, string): true if type checking
-- succeeded, or nil and an error message if it failed.
function type_check.type_check_rockspec(rockspec, globals)
assert(type(rockspec) == "table")
if not rockspec.rockspec_format then
rockspec.rockspec_format = "1.0"
end
local ok, err = check_undeclared_globals(globals, rockspec_types)
if not ok then return nil, err end
return type_check_table(rockspec.rockspec_format, rockspec, rockspec_types, "")
end
--- Type check a manifest table.
-- Verify the correctness of elements from a
-- manifest table, reporting on unknown fields and type
-- mismatches.
-- @return boolean or (nil, string): true if type checking
-- succeeded, or nil and an error message if it failed.
function type_check.type_check_manifest(manifest, globals)
assert(type(manifest) == "table")
local ok, err = check_undeclared_globals(globals, manifest_types)
if not ok then return nil, err end
return type_check_table("1.0", manifest, manifest_types, "")
end
return type_check
|
Ocean = Class{}
function Ocean:init()
self.width = VIRTUAL_WIDTH
self.height = 200
self.x = 0
self.y = VIRTUAL_HEIGHT - 49
end
function Ocean:collides(obstacle)
if self.x + self.width >= obstacle.x and self.x <= obstacle.x + obstacle.width then
if (self.y) + (self.height) >= obstacle.y and self.y + 2 <= obstacle.y + obstacle.height then
return true
end
end
return false
end |
-- Do not load actual QoS functionality at all, add noop wrapper with annoying messages.
-- After loading this file mod should stop doing anything else.
-- Reset QoS
QoS = {}
local function wrapper(_, arg1)
print("QoS control is disabled for " .. tostring(minetest.get_current_modname()))
print("curl_parallel_limit setting too low for efficient priority control")
return arg1
end
setmetatable(QoS, {
__call = wrapper,
__index = function(self) return wrapper(nil, self) end,
})
QoS.__index = QoS
|
DarkRP.ENTITY.keysLock = DarkRP.stub{
name = "keysLock",
description = "Lock this door or vehicle.",
parameters = {
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.keysUnLock = DarkRP.stub{
name = "keysUnLock",
description = "Unlock this door or vehicle.",
parameters = {
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.addKeysAllowedToOwn = DarkRP.stub{
name = "addKeysAllowedToOwn",
description = "Make this player allowed to co-own the door or vehicle.",
parameters = {
{
name = "ply",
description = "The player to give permission to co-own.",
type = "Player",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.addKeysDoorOwner = DarkRP.stub{
name = "addKeysDoorOwner",
description = "Make this player a co-owner of the door.",
parameters = {
{
name = "ply",
description = "The player to add as co-owner.",
type = "Player",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.removeKeysDoorOwner = DarkRP.stub{
name = "removeKeysDoorOwner",
description = "Remove this player as co-owner",
parameters = {
{
name = "ply",
description = "The player to remove from the co-owners list.",
type = "Player",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.keysOwn = DarkRP.stub{
name = "keysOwn",
description = "Make the player the master owner of the door",
parameters = {
{
name = "ply",
description = "The player set as master owner.",
type = "Player",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.keysUnOwn = DarkRP.stub{
name = "keysUnOwn",
description = "Make this player unown the door/vehicle.",
parameters = {
{
name = "ply",
description = "The player.",
type = "Player",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.setKeysNonOwnable = DarkRP.stub{
name = "setKeysNonOwnable",
description = "Set whether this door or vehicle is ownable or not.",
parameters = {
{
name = "ownable",
description = "Whether the door or vehicle is blocked from ownership.",
type = "boolean",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.setKeysTitle = DarkRP.stub{
name = "setKeysTitle",
description = "Set the title of a door or vehicle.",
parameters = {
{
name = "title",
description = "The title of the door.",
type = "string",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.setDoorGroup = DarkRP.stub{
name = "setDoorGroup",
description = "Set the door group of a door.",
parameters = {
{
name = "group",
description = "The door group.",
type = "string",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.addKeysDoorTeam = DarkRP.stub{
name = "addKeysDoorTeam",
description = "Allow a team to lock/unlock a door..",
parameters = {
{
name = "team",
description = "The team to add to team owners.",
type = "number",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.removeKeysDoorTeam = DarkRP.stub{
name = "removeKeysDoorTeam",
description = "Disallow a team from locking/unlocking a door.",
parameters = {
{
name = "team",
description = "The team to remove from team owners.",
type = "number",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.removeAllKeysDoorTeams = DarkRP.stub{
name = "removeAllKeysDoorTeams",
description = "Disallow all teams from locking/unlocking a door.",
parameters = {
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.removeAllKeysExtraOwners = DarkRP.stub{
name = "removeAllKeysExtraOwners",
description = "Remove all co-owners from a door.",
parameters = {
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.removeAllKeysAllowedToOwn = DarkRP.stub{
name = "removeAllKeysAllowedToOwn",
description = "Disallow all people from owning the door.",
parameters = {
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.ENTITY.removeKeysAllowedToOwn = DarkRP.stub{
name = "removeKeysAllowedToOwn",
description = "Remove a player from being allowed to co-own a door.",
parameters = {
{
name = "ply",
description = "The player to be removed.",
type = "Player",
optional = false
}
},
returns = {
},
metatable = DarkRP.ENTITY
}
DarkRP.PLAYER.keysUnOwnAll = DarkRP.stub{
name = "keysUnOwnAll",
description = "Unown every door and vehicle owned by this player.",
parameters = {
},
returns = {
},
metatable = DarkRP.PLAYER
}
DarkRP.PLAYER.sendDoorData = DarkRP.stub{
name = "sendDoorData",
description = "Internal function. Sends all door data to a player.",
parameters = {
},
returns = {
},
metatable = DarkRP.PLAYER
}
DarkRP.PLAYER.doPropertyTax = DarkRP.stub{
name = "doPropertyTax",
description = "Tax a player based on the amount of doors and vehicles they have.",
parameters = {
},
returns = {
},
metatable = DarkRP.PLAYER
}
DarkRP.PLAYER.initiateTax = DarkRP.stub{
name = "initiateTax",
description = "Internal function, starts the timer that taxes the player every once in a while.",
parameters = {
},
returns = {
},
metatable = DarkRP.PLAYER
}
DarkRP.hookStub{
name = "onKeysLocked",
description = "Called when a door or vehicle was locked.",
parameters = {
{
name = "ent",
description = "The entity that was locked.",
type = "Entity"
}
},
returns = {
}
}
DarkRP.hookStub{
name = "onKeysUnlocked",
description = "Called when a door or vehicle was unlocked.",
parameters = {
{
name = "ent",
description = "The entity that was unlocked.",
type = "Entity"
}
},
returns = {
}
}
DarkRP.hookStub{
name = "playerKeysSold",
description = "When a player sold a door or vehicle.",
parameters = {
{
name = "ply",
description = "The player who sold the door or vehicle.",
type = "Player"
},
{
name = "ent",
description = "The entity that was sold.",
type = "Player"
},
{
name = "GiveMoneyBack",
description = "The amount of money refunded to the player",
type = "number"
}
},
returns = {
}
}
DarkRP.hookStub{
name = "hideSellDoorMessage",
description = "Whether to hide the door/vehicle sold notification",
parameters = {
{
name = "ply",
description = "The player who sold the door or vehicle.",
type = "Player"
},
{
name = "ent",
description = "The entity that was sold.",
type = "Player"
},
},
returns = {
{
name = "hide",
description = "Whether to hide the notification.",
type = "boolean"
}
}
}
DarkRP.hookStub{
name = "getDoorCost",
description = "Get the cost of a door.",
parameters = {
{
name = "ply",
description = "The player who has the intention to purchase the door.",
type = "Player"
},
{
name = "ent",
description = "The door",
type = "Entity"
}
},
returns = {
{
name = "cost",
description = "The price of the door.",
type = "number"
}
}
}
DarkRP.hookStub{
name = "getVehicleCost",
description = "Get the cost of a vehicle.",
parameters = {
{
name = "ply",
description = "The player who has the intention to purchase the vehicle.",
type = "Player"
},
{
name = "ent",
description = "The vehicle",
type = "Entity"
}
},
returns = {
{
name = "cost",
description = "The price of the vehicle.",
type = "number"
}
}
}
DarkRP.hookStub{
name = "playerBuyDoor",
description = "When a player purchases a door.",
parameters = {
{
name = "ply",
description = "The player who is to buy the door.",
type = "Player"
},
{
name = "ent",
description = "The door.",
type = "Entity"
}
},
returns = {
{
name = "allowed",
description = "Whether the player is allowed to buy the door.",
type = "boolean"
},
{
name = "reason",
description = "The reason why a player is not allowed to buy the door, if applicable.",
type = "string"
},
{
name = "surpress",
description = "Whether to show the reason in a notification to the player, return true here to surpress the message.",
type = "boolean"
}
}
}
DarkRP.hookStub{
name = "playerSellDoor",
description = "When a player is about to sell a door.",
parameters = {
{
name = "ply",
description = "The player who is to sell the door.",
type = "Player"
},
{
name = "ent",
description = "The door.",
type = "Entity"
}
},
returns = {
{
name = "allowed",
description = "Whether the player is allowed to sell the door.",
type = "boolean"
},
{
name = "reason",
description = "The reason why a player is not allowed to sell the door, if applicable.",
type = "string"
}
}
}
DarkRP.hookStub{
name = "onAllowedToOwnAdded",
description = "When a player adds a co-owner to a door.",
parameters = {
{
name = "ply",
description = "The player who adds the co-owner.",
type = "Player"
},
{
name = "ent",
description = "The door.",
type = "Entity"
},
{
name = "target",
description = "The target who will be allowed to own the door.",
type = "Player"
}
},
returns = {
{
name = "allowed",
description = "Whether the player is allowed to add this player as co-owner.",
type = "boolean"
}
}
}
DarkRP.hookStub{
name = "onAllowedToOwnRemoved",
description = "When a player removes a co-owner to a door.",
parameters = {
{
name = "ply",
description = "The player who removes the co-owner.",
type = "Player"
},
{
name = "ent",
description = "The door.",
type = "Entity"
},
{
name = "target",
description = "The target who will not be allowed to own the door anymore.",
type = "Player"
}
},
returns = {
{
name = "allowed",
description = "Whether the player is allowed to remove this player as co-owner.",
type = "boolean"
}
}
}
DarkRP.hookStub{
name = "playerBuyVehicle",
description = "When a player purchases a vehicle.",
parameters = {
{
name = "ply",
description = "The player who is to buy the vehicle.",
type = "Player"
},
{
name = "ent",
description = "The vehicle.",
type = "Entity"
}
},
returns = {
{
name = "allowed",
description = "Whether the player is allowed to buy the vehicle.",
type = "boolean"
},
{
name = "reason",
description = "The reason why a player is not allowed to buy the vehicle, if applicable.",
type = "string"
},
{
name = "surpress",
description = "Whether to show the reason in a notification to the player, return true here to surpress the message.",
type = "boolean"
}
}
}
DarkRP.hookStub{
name = "playerSellVehicle",
description = "When a player is about to sell a vehicle.",
parameters = {
{
name = "ply",
description = "The player who is to sell the vehicle.",
type = "Player"
},
{
name = "ent",
description = "The vehicle.",
type = "Entity"
}
},
returns = {
{
name = "allowed",
description = "Whether the player is allowed to sell the vehicle.",
type = "boolean"
},
{
name = "reason",
description = "The reason why a player is not allowed to sell the vehicle, if applicable.",
type = "string"
}
}
}
DarkRP.hookStub{
name = "playerBoughtDoor",
description = "Called when a player has purchased a door.",
parameters = {
{
name = "ply",
description = "The player who has purchased the door.",
type = "Player"
},
{
name = "ent",
description = "The purchased door.",
type = "Entity"
},
{
name = "cost",
description = "The cost of the purchased door.",
type = "number"
}
},
returns = {
}
}
DarkRP.hookStub{
name = "playerBoughtVehicle",
description = "Called when a player has purchased a vehicle.",
parameters = {
{
name = "ply",
description = "The player who has purchased the vehicle.",
type = "Player"
},
{
name = "ent",
description = "The purchased vehicle.",
type = "Entity"
},
{
name = "cost",
description = "The cost of the purchased vehicle.",
type = "number"
}
},
returns = {
}
}
DarkRP.hookStub{
name = "onPaidTax",
description = "Called when a player has paid tax.",
parameters = {
{
name = "ply",
description = "The player who was taxed.",
type = "Player"
},
{
name = "tax",
description = "The percentage of tax taken from his wallet.",
type = "number"
},
{
name = "wallet",
description = "The amount of money the player had before the tax was applied.",
type = "number"
}
},
returns = {
}
}
|
---@module GunMagazine ๆชๆขฐๆจกๅ๏ผๅผนๅคนๅบ็ฑป
---@copyright Lilith Games, Avatar Team
---@author Sharif Ma
local GunMagazine = class('GunMagazine')
---GunMagazine็ฑป็ๆ้ ๅฝๆฐ
---@param _gun GunBase
function GunMagazine:initialize(_gun)
---ๅผนๅคน่ฃ
่ฝฝ็ๆญฆๅจ
self.gun = _gun
---ๅผนๅคน็id
self.id = _gun.magazineUsed
---ๅผนๅคน้
็ฝฎๅๅงๅ
GunBase.static.utility:InitGunMagazineConfig(self)
---ๅผนๅคนๅฉไฝๅญๅผนๆฐ้
self.m_leftAmmo = _gun.gun.AmmoLeft.Value
---ๅผนๅคนไธญๅคไฝ็ๅญๅผน
local moveAmmo = self.m_leftAmmo - self.maxNum
if moveAmmo > 0 then
self.m_leftAmmo = self.maxNum
else
moveAmmo = 0
end
if PlayerGunMgr.hadAmmoList[self.matchAmmo] then
---่ฟไธชๅญๅผนๅจ็ฉๅฎถ่บซไธๅทฒ็ปๆไบ
PlayerGunMgr.hadAmmoList[self.matchAmmo]:PlayerPickAmmo(nil, moveAmmo)
else
---่ฟไธชๅญๅผนๆฏ็ฉๅฎถ้ฆๆฌกๆพๅ็
local ammoObj = WeaponAmmoBase:new(self.matchAmmo, moveAmmo, localPlayer)
PlayerGunMgr.hadAmmoList[self.matchAmmo] = ammoObj
end
---@type WeaponAmmoBase ๅผนๅคนไธญๅญๅผน็ฑป
self.m_ammoInventory = PlayerGunMgr.hadAmmoList[self.matchAmmo]
---ๅผน่ฏ็่ด่ฝฝ็พๅๆฏ
self.m_loadPercentage = 100
---ๆชๆปกๅญๅผนไบๅ
self.m_isFullyLoaded = false
---ๅผนๅคน็ฉบไบไน
self.m_isEmptyLoaded = false
---ๆช้ๅฏไปฅ่ฃ
ๆดๅคๅญๅผนๅ
self.m_canLoad = false
self.m_loadTimeRateTable = {}
self.m_loadTimeRateScale = 1
self.m_maxAmmoRateTable = {}
self.m_maxAmmoRateScale = 0
---ไธไธๅธงๅผนๅคนไธญๅฏไปฅ่ฃ
็ๅญๅผนๆฐ้
self.preMaxAmmo = self.maxNum
self:Update()
end
---ๆฃๆฅๅฝๅๅผนๅคนๆฏๅฆ่ฃ
ๆปกๅญๅผน
function GunMagazine:UpdateFullyLoaded()
self.m_isFullyLoaded = self.m_leftAmmo >= self:GetMaxAmmo()
return self.m_isFullyLoaded
end
---ๆฃๆฅๅฝๅๅผนๅคนไธญๅญๅผนๆฏๅฆ็ฉบไบ
function GunMagazine:UpdateEmptyLoaded()
self.m_isEmptyLoaded = self.m_leftAmmo <= 0
return self.m_isEmptyLoaded
end
---ๆฃๆฅๅฝๅๆฏๅฆๅฏไปฅ่ฃ
ๅผน
function GunMagazine:UpdateCanLoad()
self.m_canLoad = not self.m_isFullyLoaded and self.m_ammoInventory and self.m_ammoInventory.count > 0
return self.m_canLoad
end
---ๆดๆฐๅฝๅ็ๅญๅผน่ด่ฝฝ็พๅๆฏ
function GunMagazine:UpdateLoadPercentage()
self.m_loadPercentage = math.floor(self.m_leftAmmo / self:GetMaxAmmo() * 100)
return self.m_loadPercentage
end
---ๆถ่ไธ้ขๅญๅผน
---@return function
function GunMagazine:Consume()
local function OverrideConsume()
if self.m_leftAmmo > 0 then
self.m_leftAmmo = self.m_leftAmmo - 1
world.S_Event.PlayerPickAmmoEvent:Fire(localPlayer, {[self.matchAmmo] = -1})
return true
else
return false
end
end
return OverrideConsume
end
---่ฃ
ไธๅๅญๅผน
function GunMagazine:LoadOneBullet()
if self.m_canLoad then
self.m_leftAmmo = self.m_leftAmmo + 1
self.m_ammoInventory:PlayerConsumeAmmo(1)
end
---self:Update()
end
---่ฃ
ๆดไธชๅผนๅคน
function GunMagazine:LoadMagazine()
if self.m_canLoad then
local addition = self:GetMaxAmmo() - self.m_leftAmmo
addition = self.m_ammoInventory:PlayerConsumeAmmo(addition)
self.m_leftAmmo = self.m_leftAmmo + addition
self:UpdateFullyLoaded()
end
---self:Update()
end
---ๆชๆขฐๅธ่ฝฝ/ๆดๆขๅ,้่ฆๅฐๆชๆขฐ็ๅญๅผนๆดๆฐๅจ้
ไปถ็่็นไธ
---@param _isBackToBulletInventory boolean ๆชๆขฐ็ๅญๅผนๆฏๅฆๅ้ๅฐๅญๅผนไปๅบไธญ
function GunMagazine:RecordingBulletsLeft(_isBackToBulletInventory)
if _isBackToBulletInventory and self.m_ammoInventory then
self.m_ammoInventory.count = self.m_leftAmmo + self.m_ammoInventory.count
self.m_leftAmmo = 0
end
self:Update()
end
---ๆดๆฐๅฝๆฐ
function GunMagazine:Update()
if self.preMaxAmmo > self:GetMaxAmmo() then
---่ฟไธๅธงๅธไธไบๆฉๅฎนๅผนๅคน,้่ฆๅผบ่กๅๅฐๅฝๅ็ๅญๅผน
if self:GetMaxAmmo() < self.m_leftAmmo then
local deltaAmmo = self.m_leftAmmo - self:GetMaxAmmo()
self.m_leftAmmo = self.m_leftAmmo - deltaAmmo
self.m_ammoInventory.count = self.m_ammoInventory.count + deltaAmmo
end
end
self.preMaxAmmo = self:GetMaxAmmo()
self:UpdateFullyLoaded()
self:UpdateEmptyLoaded()
self:UpdateCanLoad()
self:UpdateLoadPercentage()
---ๅฐๅฝๅ็ๅฉไฝๅญๅผนๆดๆฐๅฐๅบๆฏไธญ็่็นไธ
self.m_ammoInventory = PlayerGunMgr.hadAmmoList[self.matchAmmo]
self.gun.gun.AmmoLeft.Value = self.m_leftAmmo
self.m_loadTimeRateTable = {}
self.m_maxAmmoRateTable = {}
for k, v in pairs(self.gun.m_weaponAccessoryList) do
self.m_loadTimeRateTable[k] = v.magazineLoadTimeRate
self.m_maxAmmoRateTable[k] = v.maxAmmoRate[self.gun.gun_Id]
end
self:RefreshScales()
end
function GunMagazine:RefreshScales()
local factor = 1
factor = 1
for k, v in pairs(self.m_loadTimeRateTable) do
factor = factor * v
end
self.m_loadTimeRateScale = factor
factor = 0
for k, v in pairs(self.m_maxAmmoRateTable) do
factor = factor + v
end
self.m_maxAmmoRateScale = factor
end
function GunMagazine:GetLoadTime()
return self.loadTime * self.m_loadTimeRateScale
end
function GunMagazine:GetMaxAmmo()
return self.m_maxAmmoRateScale + self.maxNum > 0 and self.m_maxAmmoRateScale + self.maxNum or 1
end
function GunMagazine:Destructor()
ClearTable(self)
self = nil
end
return GunMagazine
|
--[[
This class was made special for The Elements of Rainbow discord server
]]
local emb = require("./embed.lua")
local party = {}
party.text = {
[[ะฅะพัั ะฟะพะถะตะปะฐัั, ััะพะฑั ะถะธะทะฝั ะฑัะปะฐ ะฟะพะปะฝะฐ ะฟัะธััะฝัะผะธ ัะพะฑััะธัะผะธ, ะฑะปะตััััะธะผะธ ะธะดะตัะผะธ ะธ ะฝะฐััะพััะธะผะธ ะฟะพะฑะตะดะฐะผะธ! ะัััั ัะฒะพั ะดััะฐ ัะฒะตัะธััั ะพั ะฟะพะทะธัะธะฒะฐ ะธ ั
ะพัะพัะตะณะพ ะฝะฐัััะพะตะฝะธั! ะ ะฒ ัััะดะฝัะต ะผะณะฝะพะฒะตะฝัั ัะฒะพะตะน ะถะธะทะฝะธ ััะดะพะผ ะฒัะตะณะดะฐ ะฑัะดัั ะฝะฐั
ะพะดะธัััั ะดััะทัั ะธ ะฑะปะธะทะบะธะต ัะตะฑะต ะปัะดะธ! ะะพะฝะตัะฝะพ ะถะต ะทะดะพัะพะฒัั ะธ ะดะพะปะณะธั
ะปะตั ะถะธะทะฝะธ. ะ ะฐะดะพััะธ ะธ ัะผะตั
ะฐ, ัะฒะฐะถะตะฝะธั ะดััะทะตะน ะธ ะปัะฑะฒะธ ัะพะดะฝัั
! ะก ะฟัะฐะทะดะฝะธะบะพะผ, ั ะดะฝะตะผ ัะพะถะดะตะฝะธั!]],
[[ะะพัะพะณะพะน ะธะผะตะฝะธะฝะฝะธะบ! ะ ะดะตะฝั ัะฒะพะตะณะพ ัะพะถะดะตะฝะธั ะพั ะฒัะตะณะพ ัะตัะดัะฐ ะถะตะปะฐะตะผ...
ะงัะพะฑั ะทะตะปะตะฝัะน ะผะตััะตะดะตั ัะฒะพะตะน ะถะธะทะฝะธ ะปะตะณะบะพ ะธ ััะฐััะปะธะฒะพ ะฒะตะท ัะตะฑั ะฟะพ ะถะธะทะฝะธ, ะฟัะตะพะดะพะปะตะฒะฐั ะฒัะต ะฟัะตะฟััััะฒะธั ะธ ัััะดะฝะพััะธ, ััะพะฑั ะดะพัะพะณะฐ ัะปะฐ ะฟะพ ัะฒะตัััะตะผั ัะฐะดั ะธ ััะพะฑั ััะดะพะผ ะฑัะปะธ ะฒัะต ัะต, ะฒ ะบะพะผ ัั ะฝัะถะดะฐะตัััั. ะะฐ ัะฒะพะต ะฑะปะฐะณะพะฟะพะปััะธะต ะธ ััะฟะตั
!]],
[[ะะตะฝั ะ ะพะถะดะตะฝะธั, ะฟะพะถะตะปะฐั ัะตะฑะต ะฒัะตะณะพ ะผะฝะพะณะพ, ะผะฝะพะณะพ ะกัะฐัััั, ะะดะพัะพะฒัั, ะฃะดะฐัะธ ! ะะพะปััะพะน ะถะธะทะฝะตะฝะฝะพะน ัะธะปั ะธ ะพะณัะพะผะฝะพะน ัะฝะตัะณะธะธ ัะตะปั, ะฑะพะปััะพะณะพ ะฃัะฟะตั
ะฐ ะฒ ะดะตะปะฐั
, ะดััะตะฒะฝะพะณะพ ัะฟะพะบะพะนััะฒะธั ะฒ ัะฐะทะปะธัะฝัั
ะถะธะทะฝะตะฝะฝัั
ัะธััะฐัะธัั
. ะะตะปะฐั ัะตะฑะต ััะบะพะณะพ ะธ ััะฐะฑะธะปัะฝะพะณะพ ะัะดััะตะณะพ. ะ ะผะฝะพะณะพ ะัะฑะฒะธ.]],
[[ะ ััะพั ะทะฐะผะตัะฐัะตะปัะฝัะน ะดะตะฝั โ ัะฒะพะน ะดะตะฝั ัะพะถะดะตะฝะธั โ ั ะธัะบัะตะฝะฝะต ั
ะพัั ัะตะฑั ะฟะพะทะดัะฐะฒะธัั! ะะพะถะตะปะฐั ั ัะตะฑะต ัะฐะผัั ะผะฐะปะพััั โ ะฟัััั ะฒัะต, ััะพ ั ัะตะฑั ะตััั, ะฟัะธะฝะพัะธั ัะตะฑะต ัะฐะดะพััั, ะฟัััั ะฒัะต, ัะตะณะพ ั ัะตะฑั ะฝะตั, ะฝะต ัะฒะปัะตััั ะดะปั ัะตะฑั ะฝะตะพะฑั
ะพะดะธะผะพัััั, ะฟัััั ะฒัะต, ะพ ัะตะผ ัั ะผะตััะฐะตัั, ััะดะตัะฝัะผ ะพะฑัะฐะทะพะผ ะฟะพัะฒะธััั ะฒ ัะฒะพะตะน ะถะธะทะฝะธ. ะะตะปะฐั ัะตะฑะต ะฑััั ััะฐััะปะธะฒัะผ ัะตะปะพะฒะตะบะพะผ, ัะฐะดะพะฒะฐัััั ะบะฐะถะดะพะผั ะฝะพะฒะพะผั ะดะฝั, ะฝะฐั
ะพะดะธัั ัะดะพะฒะพะปัััะฒะธะต ะฒ ะฟัะพัััั
ะฒะตัะฐั
: ัะฐัะบะต ัััะตะฝะฝะตะณะพ ะบะพัะต, ะปััะฐั
ัะพะปะฝะตัะฝะพะณะพ ัะฒะตัะฐ, ะดัะฝะพะฒะตะฝะธะธ ะฒะตััะฐ, ะฒะทะณะปัะดะฐั
ะดะพัะพะณะธั
ะปัะดะตะน. ะฆะตะฝะธ ัะพ, ััะพ ั ัะตะฑั ะตััั, ะธ ััะดัะฑะฐ ะพะฑัะทะฐัะตะปัะฝะพ ะพะดะฐัะธั ัะตะฑั ะตัะต ะฑะพะปััะต.]],
}
party.shortstring = [[```Markdown
# ะั ะฝะต ัะบะฐะทะฐะปะธ ะธะผั ะฟะพะปัะทะพะฒะฐัะตะปั, ะบะพัะพัะพะณะพ ั
ะพัะธัะต ะฟะพะทะดัะฐะฒะธัั!
```]]
function party:Send(msg)
if string.len(msg.content) < 8 then msg:reply(self.shortstring) return end
local user = string.gsub(msg.content,"!party ","")
local happytext = self.text[math.random(1,#self.text)]
local channel = msg.channel
emb:SendCurrent(channel,"C ะะฝัะผ ะ ะพะถะดะตะฝะธั!",0xff0000,"",{{user..",",happytext,false}},"","",true)
end
return party |
local path = '/home/lib';
local os = require('os');
local codeURL = os.getenv('ROBOSERVER_CODE');
local fileName = '/downloadCode.lua'
os.execute('wget -f ' .. codeURL .. fileName .. ' ' .. path .. fileName);
local dl = require("downloadCode");
dl.downloadAll(path);
local config = require("config");
config.easy(config.path);
require('commandLoop');
|
local hooks = {}
module(..., package.seeall)
-- register
-- Adds a new hook to the global table so it can be broadcast.
-- Returns whether a new hook was registered (same name cannot be registered twice)
function register(hookName)
if (hooks[hookName]) return false end
hooks[hookName] = {}
return true
end
-- unregister
-- Removes a hook from the global table so it cannot be broadcast anymore.
-- Returns whether or not the hook existed and was unregistered.
function unregister(hookName)
if (not (hook[hookName]==nil)) then
hooks[hookName] = nil
return true
end
return false
end
-- add
-- Hooks a function in with a custom function name to a global hook
-- Function will be called whenever the global hook is broadcast.
-- Custom hook name is to allow hooks to be overridden and removed.
-- returns false if the hookName is not registered
function add(hookName, customHookName, callBackFunc)
if (hooks[hookName]) then
hooks[hookName][customHookName] = callBackFunc
else
register(hookName)
hooks[hookName][customHookName] = callBackFuc
print(hookName.." used without being registered!")
end
end
-- remove
-- Unhooks the function with a specific customHookName
-- Returns whether or not the hook existed and was removed.
function remove(hookName, customHookName)
if (hooks[hookName] && hooks[hookName][customHookName]) then
hooks[hookName][customHookName] = nil
return true
end
return false
end
-- broadcast
-- Calls all functions hooked to hookName with {args}
function broadcast(hookName, ...)
if (not hooks[hookName]) then
hook.register(hookName)
print(hookName.." broadcast without being registered!")
end
for k,v in pairs(hooks[hookName]) do
v(...)
end
return true
end
|
-------------------------------------------------------------------------------
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("Grandmaster Vorpil", 555, 546)
if not mod then return end
mod:RegisterEnableMob(18732)
-- mod.engageId = 1911 -- no boss frames
-- mod.respawnTime = 0 -- resets, doesn't respawn
-------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
-5267, -- Draw Shadows
38791, -- Banish
},{
[-5267] = "general",
[38791] = "heroic",
}
end
function mod:OnBossEnable()
self:Log("SPELL_CAST_SUCCESS", "DrawShadows", 33563)
self:Log("SPELL_AURA_APPLIED", "Banish", 38791)
self:Log("SPELL_AURA_REMOVED", "BanishRemoved", 38791)
self:RegisterEvent("PLAYER_REGEN_DISABLED", "CheckForEngage")
self:Death("Win", 18732)
end
function mod:OnEngage()
self:RegisterEvent("PLAYER_REGEN_ENABLED", "CheckForWipe")
self:CDBar(-5267, 44) -- Draw Shadows
end
-------------------------------------------------------------------------------
-- Event Handlers
--
function mod:DrawShadows()
self:Message(-5267, "orange")
self:CDBar(-5267, 41)
end
function mod:Banish(args)
self:TargetMessage(args.spellId, args.destName, "red")
self:TargetBar(args.spellId, 8, args.destName)
end
function mod:BanishRemoved(args)
self:StopBar(args.spellName, args.destName)
end
|
giant_mutant_bark_mite = Creature:new {
objectName = "@mob/creature_names:mutant_bark_mite_giant",
socialGroup = "mite",
faction = "",
level = 16,
chanceHit = 0.31,
damageMin = 170,
damageMax = 180,
baseXp = 1102,
baseHAM = 4100,
baseHAMmax = 5000,
armor = 0,
resists = {5,5,5,110,110,-1,-1,-1,-1},
meatType = "meat_insect",
meatAmount = 30,
hideType = "hide_scaley",
hideAmount = 25,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + HERD + KILLER,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/bark_mite_hue.iff"},
hues = { 16, 17, 18, 19, 20, 21, 22, 23 },
controlDeviceTemplate = "object/intangible/pet/bark_mite_hue.iff",
scale = 3,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"creatureareaattack",""},
{"intimidationattack",""}
}
}
CreatureTemplates:addCreatureTemplate(giant_mutant_bark_mite, "giant_mutant_bark_mite")
|
PROJECT_NAME = path.getname(os.getcwd())
minko.project.library("minko-plugin-" .. PROJECT_NAME)
files {
"src/**.hpp",
"src/**.cpp",
"include/**.hpp"
}
includedirs {
"include",
"src",
"lib/opengl/include",
}
configuration { "android or ios or html5" }
minko.plugin.enable("sensors")
configuration { "windows32 or windows64" }
files {
"lib/libovr/windows/**.cpp"
}
includedirs {
"lib/libovr/windows/src",
"lib/libovr/windows/include",
}
excludes {
"lib/libovr/windows/src/CAPI/D3D1X/CAPI_D3D1X_Util.*",
"lib/libovr/windows/src/CAPI/D3D1X/CAPI_D3D1X_DistortionRenderer.*"
}
defines {
"UNICODE",
"_UNICODE",
"WIN32"
}
configuration { "linux32 or linux64" }
files {
"lib/libovr/linux/**.cpp"
}
includedirs {
"lib/libovr/linux/src",
"lib/libovr/linux/include"
}
configuration { "osx64" }
buildoptions { "-x objective-c++" }
files {
"lib/libovr/osx/**.cpp",
"lib/libovr/osx/src/Util/Util_SystemInfo_OSX.mm"
}
includedirs {
"lib/libovr/osx/src",
"lib/libovr/osx/include",
}
configuration { "not html5" }
excludes {
"include/minko/vr/WebVR.hpp",
"src/minko/vr/WebVR.cpp",
}
configuration { "not android", "not ios", "not html5" }
excludes {
"include/minko/vr/Cardboard.hpp",
"src/minko/vr/Cardboard.cpp",
}
configuration { "html5 or android or ios" }
excludes {
"include/minko/vr/OculusRift.hpp",
"src/minko/vr/OculusRift.cpp",
}
|
modifier_wearable = class({})
function modifier_wearable:CheckState()
local state = {
[MODIFIER_STATE_STUNNED] = true,
[MODIFIER_STATE_NO_HEALTH_BAR] = true,
[MODIFIER_STATE_NO_UNIT_COLLISION] = true,
[MODIFIER_STATE_NOT_ON_MINIMAP] = true,
[MODIFIER_STATE_INVULNERABLE] = true,
[MODIFIER_STATE_UNSELECTABLE] = true,
}
return state
end
function modifier_wearable:IsPurgable()
return false
end
function modifier_wearable:IsStunDebuff()
return false
end
function modifier_wearable:IsPurgeException()
return false
end
function modifier_wearable:IsHidden()
return true
end
function modifier_wearable:OnCreated()
if not IsServer() then return end
self:StartIntervalThink(FrameTime())
self.render_color = nil
end
function modifier_wearable:OnIntervalThink()
local cosmetic = self:GetParent()
local hero = cosmetic:GetOwnerEntity()
if hero == nil then return end
if self.render_color == nil then
if hero:HasModifier("modifier_juggernaut_arcana") then
-- print("Jugg arcana 1, Color wearables!")
self.render_color = true
cosmetic:SetRenderColor(80, 80, 100)
elseif hero:HasModifier("modifier_juggernaut_arcana") and hero:FindModifierByName("modifier_juggernaut_arcana"):GetStackCount() == 1 then
print("Jugg arcana 2, Color wearables!")
self.render_color = true
cosmetic:SetRenderColor(255, 220, 220)
elseif hero:GetUnitName() == "npc_dota_hero_vardor" then
-- print("Vardor, Color wearables!")
self.render_color = true
cosmetic:SetRenderColor(255, 0, 0)
end
end
for _, v in pairs(IMBA_INVISIBLE_MODIFIERS) do
if not hero:HasModifier(v) then
if cosmetic:HasModifier(v) then
cosmetic:RemoveModifierByName(v)
end
else
if not cosmetic:HasModifier(v) then
cosmetic:AddNewModifier(cosmetic, nil, v, {})
break -- remove this break if you want to add multiple modifiers at the same time
end
end
end
for _, v in pairs(IMBA_NODRAW_MODIFIERS) do
if hero:HasModifier(v) then
if not cosmetic.model then
-- print("ADD NODRAW TO COSMETICS")
cosmetic.model = cosmetic:GetModelName()
end
if cosmetic.model and cosmetic:GetModelName() ~= "models/development/invisiblebox.vmdl" then
cosmetic:SetOriginalModel("models/development/invisiblebox.vmdl")
cosmetic:SetModel("models/development/invisiblebox.vmdl")
break
end
else
if cosmetic.model and cosmetic:GetModelName() ~= cosmetic.model then
-- print("REMOVE NODRAW TO COSMETICS")
cosmetic:SetOriginalModel(cosmetic.model)
cosmetic:SetModel(cosmetic.model)
break
end
end
end
if hero:IsOutOfGame() or hero:IsHexed() then
cosmetic:AddNoDraw()
else
cosmetic:RemoveNoDraw()
end
end
|
--A lot of Thanks to iUltimateLP and his mod SimpleTeleporters for inspiration and for the use of His Code and graphics
data:extend(
{
{
type = "energy-shield-equipment",
name= "Personal-Teleporter",
sprite =
{
filename = "__PersonalTeleporter__/graphics/Personal_Teleport_equipment.png",
width = 48,
height = 48,
priority = "medium"
},
shape =
{
width = 3,
height = 3,
type = "full"
},
max_shield_value = 150,
energy_source =
{
type = "electric",
buffer_capacity = "10MJ",
input_flow_limit = "150kW",
usage_priority = "primary-input"
},
energy_per_shield = "30kJ",
categories = {"armor"}
}
}) |
horse_spawn = {
cast = async(function(player)
local magic = 30
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
player:spawn(8, player.x, player.y, 1)
player:setAether("horse_spawn", 30000)
end),
requirements = function(player)
local level = 1
local items = {}
local itemAmounts = {}
local desc = "This spell."
return level, items, itemAmounts, desc
end
}
|
local matcher = require "util.matching"
local typeMatcher = require "util.matching.type"
local propertyInstance = require "util.Component.property_instance"
local groupInstance = require "util.Component.group_instance"
local propertyMethods = {}
function propertyMethods:setMatcher(m)
if type(m) == "function" or matcher.isMatcher(m) then
self.matcher = m
else
self.matcher = matcher(m)
end
end
local property = {}
property.default = {}
local function _create(name, value)
return setmetatable({name = name, value = value, matcher = typeMatcher[type(value)]},
{ __index = propertyMethods, __call = propertyInstance.new })
end
local group, default = {}, {}; local grouptbl = {[group] = true}
function property.create(name, value)
local mt = value and getmetatable(value)
if mt and mt[group] then
local result = setmetatable({name = name},
{ __index = property.create__index, __call = groupInstance.new })
for i, v in pairs(value) do result[i] = _create(i, v) end
return result
else
local prop = _create(name, value)
if mt and mt[default] then
prop.isDefault = true
mt[default] = nil
end
return prop
end
end
function property.create__newindex(tbl, key, val)
rawset(tbl, key, property.create(key, val))
end
function property.create__index(tbl, key)
local p = property.create(key, nil)
rawset(tbl, key, p)
return p
end
-- this should always be called with a new table (maskGroup{...})
function property.maskGroup(tbl)
return setmetatable(tbl, grouptbl)
end
-- this can have its own metatable
function property.maskDefault(val)
local mt = getmetatable(val)
if not mt then
mt = {}
setmetatable(val, mt)
end
mt[default] = true
return val
end
return property
|
-----------------------------------------------------------------------------------------------
-- Client Lua Script for NoisyQ
-- Created by boe2. For questions/comments, mail me at apollo@boe2.be
-----------------------------------------------------------------------------------------------
require "Window"
require "Sound"
local NoisyQ = {}
function NoisyQ:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
self.alarmTypes = {}
self.alarmTypes.Disabled = 0
self.alarmTypes.Once = 1
self.alarmTypes.Repeating = 2
self.settings = {}
self.settings.soundID = 149
self.settings.alarmType = self.alarmTypes.Once
self.settings.confirmAfterQueue = true
self.settings.useCustomVolume = true
self.settings.customeVolumeLevel = 1
self.originalGeneralVolumeLevel = 1
self.originalVoiceVolumeLevel = 1
return o
end
function NoisyQ:Init()
Apollo.RegisterAddon(self)
end
function NoisyQ:OnLoad()
Apollo.CreateTimer("AlarmSoundTimer", 3, true)
Apollo.RegisterSlashCommand("noisyq", "OnNoisyQOn", self)
Apollo.RegisterEventHandler("MatchingJoinQueue", "OnJoinQueue", self)
Apollo.RegisterEventHandler("MatchingLeaveQueue", "OnLeaveQueue", self)
Apollo.RegisterEventHandler("MatchingGameReady", "OnMatchingGameReady", self)
Apollo.RegisterEventHandler("MatchEntered", "OnMatchEntered", self)
Apollo.RegisterTimerHandler("AlarmSoundTimer", "OnAlarmTick", self)
end
function NoisyQ:OnCancel()
self.wndMain:Show(false)
end
function NoisyQ:OnNoisyQOn()
if self.wndMain == nil then
self.wndMain = Apollo.LoadForm("NoisyQ.xml", "NoisyQForm", nil, self)
end
self.wndMain:Show(true)
local askButton = self.wndMain:FindChild("btnAsk")
local onceButton = self.wndMain:FindChild("btnOnce")
local continuousButton = self.wndMain:FindChild("btnContinuous")
local noneButton = self.wndMain:FindChild("btnNothing")
if self.settings.confirmAfterQueue then
self.wndMain:SetRadioSelButton("SoundSelectionGroup", askButton)
elseif self.settings.alarmType == self.alarmTypes.Disabled then
self.wndMain:SetRadioSelButton("SoundSelectionGroup", noneButton)
elseif self.settings.alarmType == self.alarmTypes.Once then
self.wndMain:SetRadioSelButton("SoundSelectionGroup", onceButton)
else
self.wndMain:SetRadioSelButton("SoundSelectionGroup", continuousButton)
end
end
function NoisyQ:OnMatchingGameReady(bInProgress)
self:AlertUser()
self:DismissOptions()
end
function NoisyQ:OnMatchEntered()
self:DismissAlert()
self:DismissOptions()
end
function NoisyQ:OnJoinQueue()
if self.settings.confirmAfterQueue then
if self.wndOptions == nil then
self.wndOptions = Apollo.LoadForm("NoisyQ.xml", "OptionsDialog", nil, self)
end
self.wndOptions:Show(true)
self.wndOptions:ToFront()
end
end
function NoisyQ:OnLeaveQueue()
self:DismissAlert();
self:DismissOptions();
end
function NoisyQ:OnAlarmTick()
if self.wndAlert ~= nil then
if self.wndAlert:IsVisible() then
Sound.Play(self.settings.soundID)
end
end
end
function NoisyQ:OnSave(eLevel)
if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character then
return nil
end
local save = {}
save.settings = self.settings
save.saved = true
return save
end
function NoisyQ:OnRestore(eLevel, tData)
if tData.saved ~= nil then
self.settings = tData.settings
end
end
function NoisyQ:AlertUser()
if self.settings.alarmType ~= self.alarmTypes.Disabled then
self:SetCustomVolumeLevels()
if self.settings.alarmType == self.alarmTypes.Once then
Sound.Play(self.settings.soundID)
elseif self.settings.alarmType == self.alarmTypes.Repeating then
if self.wndAlert == nil then
self.wndAlert = Apollo.LoadForm("NoisyQ.xml", "AlertForm", nil, self)
end
self.wndAlert:Show(true)
self.wndAlert:ToFront()
Apollo.StartTimer("AlarmSoundTimer")
end
end
end
function NoisyQ:DismissAlert()
if self.wndAlert ~= nil then
self.wndAlert:Show(false)
Apollo.StopTimer("AlarmSoundTimer")
end
self:RestoreVolumeLevels()
end
function NoisyQ:DismissOptions()
if self.wndOptions ~= nil then
if self.wndOptions:IsVisible() then
self.wndOptions:Show(false)
end
end
end
function NoisyQ:SetCustomVolumeLevels()
if self.settings.useCustomVolume then
self.originalVolumeLevel = Apollo.GetConsoleVariable("sound.volumeMaster")
self.originalVoiceVolumeLevel = Apollo.GetConsoleVariable("sound.volumeVoice")
Apollo.SetConsoleVariable("sound.volumeMaster", self.settings.customeVolumeLevel)
Apollo.SetConsoleVariable("sound.volumeVoice", self.settings.customeVolumeLevel)
end
end
function NoisyQ:RestoreVolumeLevels()
if self.settings.useCustomVolume then
Apollo.SetConsoleVariable("sound.volumeMaster", self.originalVolumeLevel)
Apollo.SetConsoleVariable("sound.volumeVoice", self.originalVoiceVolumeLevel)
end
end
---------------------------------------------------------------------------------------------------
-- AlertForm Functions
---------------------------------------------------------------------------------------------------
function NoisyQ:OnDismissAlert( wndHandler, wndControl, eMouseButton )
self:DismissAlert()
end
---------------------------------------------------------------------------------------------------
-- OptionsDialog Functions
---------------------------------------------------------------------------------------------------
function NoisyQ:OnAudioPrefSet( wndHandler, wndControl, eMouseButton )
local control = wndControl:GetName()
if control == "btnAudioNone" then
self.settings.alarmType = self.alarmTypes.Disabled
elseif control == "btnAudioOnce" then
self.settings.alarmType = self.alarmTypes.Once
else
self.settings.alarmType = self.alarmTypes.Repeating
end
self:DismissOptions()
end
function NoisyQ:OnRememberChoiceToggle( wndHandler, wndControl, eMouseButton )
self.settings.confirmAfterQueue = not wndControl:IsChecked()
end
---------------------------------------------------------------------------------------------------
-- NoisyQForm Functions
---------------------------------------------------------------------------------------------------
function NoisyQ:OnOKClicked( wndHandler, wndControl, eMouseButton )
self.wndMain:Show(false)
end
function NoisyQ:OnAudioPrefSelected( wndHandler, wndControl, eMouseButton )
local selectedButton = wndControl:GetParent():GetRadioSelButton("SoundSelectionGroup")
if selectedButton ~= nil then
local name = selectedButton:GetName()
self.settings.confirmAfterQueue = name == "btnAsk"
if name == "btnOnce" then
self.settings.alarmType = self.alarmTypes.Once
elseif name == "btnContinuous" then
self.settings.alarmType = self.alarmTypes.Repeating
else
self.settings.alarmType = self.alarmTypes.Disabled
end
end
end
-----------------------------------------------------------------------------------------------
-- NoisyQ Instance
-----------------------------------------------------------------------------------------------
local NoisyQInst = NoisyQ:new()
NoisyQInst:Init()
|
ZOMGBuffsDB = {
["namespaces"] = {
["BlessingsManager"] = {
["profiles"] = {
["Default"] = {
["templates"] = {
["current"] = {
["HUNTER"] = {
"BOM", -- [1]
"BOK", -- [2]
"BOW", -- [3]
"SAN", -- [4]
},
["WARRIOR"] = {
"BOK", -- [1]
"BOM", -- [2]
"SAN", -- [3]
},
["SHAMAN"] = {
"BOW", -- [1]
"BOK", -- [2]
"SAN", -- [3]
"BOM", -- [4]
},
["subclass"] = {
["DEATHKNIGHT"] = {
["m"] = {
"BOM", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
},
["WARRIOR"] = {
["m"] = {
"BOM", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
},
["SHAMAN"] = {
["c"] = {
"BOK", -- [1]
"BOW", -- [2]
"SAN", -- [3]
},
["m"] = {
"BOM", -- [1]
"BOK", -- [2]
"BOW", -- [3]
"SAN", -- [4]
},
},
["DRUID"] = {
["m"] = {
"BOM", -- [1]
"BOK", -- [2]
"SAN", -- [3]
"BOW", -- [4]
},
["t"] = {
"BOK", -- [1]
"BOM", -- [2]
"SAN", -- [3]
"BOW", -- [4]
},
["c"] = {
"BOW", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
},
["PALADIN"] = {
["m"] = {
"BOM", -- [1]
"BOK", -- [2]
"BOW", -- [3]
"SAN", -- [4]
},
["t"] = {
"BOK", -- [1]
"BOW", -- [2]
"SAN", -- [3]
"BOM", -- [4]
},
},
["PRIEST"] = {
["c"] = {
"BOW", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
},
},
["PRIEST"] = {
"BOW", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
["WARLOCK"] = {
"BOW", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
["MAGE"] = {
"BOW", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
["ROGUE"] = {
"BOM", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
["DRUID"] = {
"BOW", -- [1]
"BOK", -- [2]
"SAN", -- [3]
},
["DEATHKNIGHT"] = {
"BOK", -- [1]
"BOM", -- [2]
"SAN", -- [3]
},
["PALADIN"] = {
"BOW", -- [1]
"BOK", -- [2]
"SAN", -- [3]
"BOM", -- [4]
},
},
},
},
},
},
},
["profiles"] = {
["Default"] = {
["enabled"] = false,
["detachedTooltip"] = {
["fontSizePercent"] = 1,
},
},
},
}
|
fprp.PLAYER.addshekel = fprp.stub{
name = "addshekel",
description = "Give shekel to a player.",
parameters = {
{
name = "amount",
description = "The amount of shekel to give to the player. A negative amount means you're substracting shekel.",
type = "number",
optional = false
}
},
returns = {
},
metatable = fprp.PLAYER
}
fprp.PLAYER.payDay = fprp.stub{
name = "payDay",
description = "Give a player their salary.",
parameters = {
},
returns = {
},
metatable = fprp.PLAYER
}
fprp.payPlayer = fprp.stub{
name = "payPlayer",
description = "Make one player give shekel to the other player.",
parameters = {
{
name = "sender",
description = "The player who gives the shekel.",
type = "Player",
optional = false
},
{
name = "receiver",
description = "The player who receives the shekel.",
type = "Player",
optional = false
},
{
name = "amount",
description = "The amount of shekel.",
type = "number",
optional = false
}
},
returns = {
},
metatable = fprp
}
fprp.createshekelBag = fprp.stub{
name = "createshekelBag",
description = "Create a shekel bag.",
parameters = {
{
name = "pos",
description = "The The position where the shekel bag is to be spawned.",
type = "Vector",
optional = false
},
{
name = "amount",
description = "The amount of shekel.",
type = "number",
optional = false
}
},
returns = {
{
name = "shekelbag",
description = "The shekel bag entity.",
type = "Entity"
}
},
metatable = fprp
}
|
local BasePlugin = require "kong.plugins.base_plugin"
local body_filter = require "kong.plugins.response-transformer.body_transformer"
local header_filter = require "kong.plugins.response-transformer.header_transformer"
local is_body_transform_set = header_filter.is_body_transform_set
local is_json_body = header_filter.is_json_body
local table_concat = table.concat
local ResponseTransformerHandler = BasePlugin:extend()
function ResponseTransformerHandler:new()
ResponseTransformerHandler.super.new(self, "response-transformer")
end
function ResponseTransformerHandler:access(conf)
ResponseTransformerHandler.super.access(self)
local ctx = ngx.ctx
ctx.rt_body_chunks = {}
ctx.rt_body_chunk_number = 1
end
function ResponseTransformerHandler:header_filter(conf)
ResponseTransformerHandler.super.header_filter(self)
header_filter.transform_headers(conf, ngx.header)
end
function ResponseTransformerHandler:body_filter(conf)
ResponseTransformerHandler.super.body_filter(self)
if is_body_transform_set(conf) and is_json_body(ngx.header["content-type"]) then
local ctx = ngx.ctx
local chunk, eof = ngx.arg[1], ngx.arg[2]
if eof then
local body = body_filter.transform_json_body(conf, table_concat(ctx.rt_body_chunks))
ngx.arg[1] = body
else
ctx.rt_body_chunks[ctx.rt_body_chunk_number] = chunk
ctx.rt_body_chunk_number = ctx.rt_body_chunk_number + 1
ngx.arg[1] = nil
end
end
end
ResponseTransformerHandler.PRIORITY = 800
ResponseTransformerHandler.VERSION = "0.1.0"
return ResponseTransformerHandler
|
local t = My.Translator.translate
local f = string.format
local shipHail = function(ship, player)
if ship:hasTag("mute") then
return t("generic_comms_ship_static")
elseif ship:isFriendly(player) then
return t("comms_generic_hail_friendly_ship", ship:getCaptain())
elseif ship:isEnemy(player) then
return t("comms_generic_hail_enemy_ship", ship:getCaptain())
else
return t("comms_generic_hail_neutral_ship", ship:getCaptain())
end
end
local stationHail = function(station, player)
if station:hasTag("mute") then
return t("generic_comms_station_static")
elseif player:isDocked(station) then
if station:isFriendly(player) then
return t("comms_generic_hail_friendly_station_docked", station:getCallSign())
else
return t("comms_generic_hail_neutral_station_docked", station:getCallSign())
end
else
if station:isFriendly(player) then
return t("comms_generic_hail_friendly_station", station:getCallSign())
elseif station:isEnemy(player) then
return t("comms_generic_hail_enemy_station", station:getCallSign())
else
return t("comms_generic_hail_neutral_station", station:getCallSign())
end
end
end
local setScannedDescription = function(self, description)
self:setDescriptionForScanState("simple", description)
self:setDescriptionForScanState("full", description)
return self
end
function My.SpaceStation(templateName, factionName)
local station = SpaceStation()
station:setTemplate(templateName)
if factionName ~= nil then station:setFaction(factionName) end
Station:withUpgradeBroker(station)
Station:withComms(station)
station:setHailText(stationHail)
station:addComms(My.Comms.Merchant)
station:addComms(My.Comms.MissionBroker)
station:addComms(My.Comms.UpgradeBroker)
Station:withTags(station)
station:setDescription(t("generic_unknown_station"))
station.setScannedDescription = setScannedDescription
station:setScanningParameters(1, 2)
return station
end
function My.WarpJammer(factionName)
local jammer = WarpJammer()
if factionName ~= nil then jammer:setFaction(factionName) end
Generic:withTags(jammer)
jammer:setDescription(t("generic_unknown_object"))
jammer.setScannedDescription = setScannedDescription
jammer:setScanningParameters(1, 1)
return jammer
end
function My.Artifact(modelName)
local artifact = Artifact()
artifact:setModel(modelName)
Generic:withTags(artifact)
artifact:setDescription(t("generic_unknown_object"))
artifact.setScannedDescription = setScannedDescription
artifact:setScanningParameters(1, 1)
return artifact
end
function My.CpuShip(templateName, factionName)
local ship = CpuShip()
ship:setTemplate(templateName)
if factionName ~= nil then ship:setFaction(factionName) end
Ship:withCaptain(ship, Person:newHuman())
Ship:withComms(ship)
ship:setHailText(shipHail)
ship:addComms(Comms.directions, "directions")
ship:addComms(Comms.whoAreYou)
Ship:withTags(ship)
ship:setDescription(t("generic_unknown_ship"))
ship.setScannedDescription = setScannedDescription
Ship:withOrderQueue(ship)
return ship
end
-- a ship that has been abandoned and serves as decoration
function My.WreckedCpuShip(templateName)
local ship = SpaceStation() -- space stations are immovable
ship:setTemplate(templateName)
ship:setFaction("Abandoned")
Ship:withComms(ship)
ship:setShieldsMax() -- remove all shields
ship:setHullMax(ship:getHullMax() * 0.1)
ship:setHull(ship:getHullMax())
ship:setHeading(math.random(0, 359))
-- TODO: would be nice if player where not able to dock in the first place
ship:setSharesEnergyWithDocked(false)
if isFunction(ship.setRestocksScanProbes) then ship:setRestocksScanProbes(false) end
ship:setRepairDocked(false)
Ship:withTags(ship)
ship:addTag("mute")
ship:setDescription(t("generic_unknown_ship"))
ship.setScannedDescription = setScannedDescription
return ship
end
--- @param contents table
--- @field energy number (optional)
--- @field reputation number (optional)
function My.SupplyDrop(x, y, contents)
local contentText = ""
for content, amount in pairs(contents) do
if amount > 0 then
if Product:isProduct(content) then
contentText = contentText .. f("\n * %d x %s", amount, content:getName())
elseif content == "energy" then
contentText = contentText .. f("\n * %0.0f %s", amount, t("drops_content_energy"))
elseif content == "reputation" then
contentText = contentText .. f("\n * %0.2f %s", amount, t("drops_content_reputation"))
end
end
end
local drop
drop = SupplyDrop():
setFaction("Player"):
setPosition(x, y):
setCallSign(t("drops_name")):
onPickUp(function(_, player)
logInfo("SupplyDrop at " .. drop:getSectorName() .. " was picked up.")
-- this line is unfortunately necessary to avoid the "[convert<ScriptSimpleCallback>::param] Upvalue 1 of function is not a table" error
local msg = t("drops_pickup") .. contentText
player:addCustomMessage("helms", Util.randomUuid(), msg)
player:addToShipLog(msg, "255,127,0")
for content, amount in pairs(contents) do
if amount > 0 then
if Product:isProduct(content) then
player:modifyProductStorage(content, amount)
elseif content == "energy" then
player:setEnergy(player:getEnergy() + amount)
elseif content == "reputation" then
player:addReputationPoints(amount)
end
end
end
end):
setScanningParameters(1, 1)
drop:setDescription(t("generic_unknown_object"))
drop.setScannedDescription = setScannedDescription
drop.getContentText = function() return contentText end
drop:setScannedDescription(t("drops_generic_description_full") .. contentText)
return drop
end
My.fleeToFortress = function(ship)
ship:setHailText(t("comms_generic_flight_hail"))
ship.whoAreYouResponse = t("comms_generic_flight_who_are_you")
ship:removeComms("directions")
ship:forceOrderNow(Order:dock(My.World.fortress, {
onCompletion = function()
ship:destroy()
end,
}))
end
-- isn't it super annoying, when wingmen crash into asteroids?
-- it does not stop them from triggering mines, but this is fine for the enemy and the players should be smart enough to navigate their fleet around.
My.asteroidRadar = function(ship, radius)
radius = radius or 500
Cron.regular(ship:getCallSign() .. "_asteroid_radar", function(self)
if not ship:isValid() then
Cron.abort(self)
else
for _, thing in pairs(ship:getObjectsInRange(radius)) do
if isEeAsteroid(thing) and thing:isValid() then
local x, y = thing:getPosition()
ExplosionEffect():setPosition(x, y):setSize(300)
thing:destroy()
end
end
end
end, 1, math.random())
end
|
numb1 = math.random(9);
numb2 = math.random(10);
if (numb2 == 10) then
value = numb1*10
reply = "answer == '" .. tens[numb1] .. "' ";
ans = "answer = '" .. tens[numb1] .. "' ";
else
value = numb1*10 + numb2;
reply = "answer == '" .. tens[numb1] .. ones[numb2] .. "' ";
ans = "answer = '" .. tens[numb1] .. ones[numb2] .. "' ";
end
|
wind_harpy_tornado_damage_modifier = class({})
function wind_harpy_tornado_damage_modifier:OnCreated( kv )
self.damage = self:GetAbility():GetSpecialValueFor("damage")
end
function wind_harpy_tornado_damage_modifier:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_TOOLTIP,
}
return funcs
end
function wind_harpy_tornado_damage_modifier:OnTooltip( params )
return self.damage
end
function wind_harpy_tornado_damage_modifier:GetAttributes()
return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE
end
function wind_harpy_tornado_damage_modifier:IsHidden()
return false
end
function wind_harpy_tornado_damage_modifier:IsPurgable()
return false
end
function wind_harpy_tornado_damage_modifier:IsPurgeException()
return false
end
function wind_harpy_tornado_damage_modifier:IsStunDebuff()
return false
end
function wind_harpy_tornado_damage_modifier:IsDebuff()
return true
end |
return {'sciencefiction','sciencefictionfilm','sciencefictionroman','sciencefictionschrijver','sciencefictionserie','sciencepark','sciopticon','scientisme','sciencefictionverhaal','scipio','sciarone','scientologen','sciencefictionfilms','sciencefictionromans','sciencefictionschrijvers','scienceparken','sciopticons','scienceparks','sciencefictionverhalen'} |
--RasPegacy v0.1
--Main Node
gl.setup(720, 486)
local curView = " "
--local font = resource.load_font("Exo2.otf")
-- Watch the view.json file to see which display the user wants
local json = require "json"
util.file_watch("view.json", function(content)
Vson = json.decode(content)
VC = Vson.view
curView = VC.top
end)
function node.render()
--future: check for day/night, change background accordingly
--if headlights on? or time of day?
gl.clear(0, 0, 0, 0)
-- Render the menu area
local menu = resource.render_child("menu")
menu:draw(0,0,720,40)
menu:dispose()
-- Render the status bar area
local sbar = resource.render_child("status_bar")
sbar:draw(0, 446, 720, 486)
sbar:dispose()
-- Render the lower node area
local lower = resource.render_child("lower")
lower:draw(0, 300, 720, 445)
lower:dispose()
-- Select which view the user has selected then render that child
if curView == "1" then
local basic = resource.render_child("basic")
basic:draw(0, 40, 720, 300)
basic:dispose()
elseif curView == "2" then
local graph = resource.render_child("graph")
graph:draw(0, 40, 720, 300)
graph:dispose()
elseif curView == "3" then
local blocks = resource.render_child("blocks")
blocks:draw(0, 40, 720, 300)
blocks:dispose()
end
-- Do stuff?
end
|
local out = io.open("../Data/3_0/Misc.lua", "w")
out:write('local data = ...\n')
local evasion = ""
local accuracy = ""
local life = ""
local allyLife = ""
local damage = ""
for i = 0, DefaultMonsterStats.maxRow do
local stats = DefaultMonsterStats[i]
evasion = evasion .. stats.Evasion .. ", "
accuracy = accuracy .. stats.Accuracy .. ", "
life = life .. stats.Life .. ", "
allyLife = allyLife .. stats.AllyLife .. ", "
damage = damage .. stats.Damage .. ", "
end
out:write('-- From DefaultMonsterStats.dat\n')
out:write('data.monsterEvasionTable = { '..evasion..'}\n')
out:write('data.monsterAccuracyTable = { '..accuracy..'}\n')
out:write('data.monsterLifeTable = { '..life..'}\n')
out:write('data.monsterAllyLifeTable = { '..allyLife..'}\n')
out:write('data.monsterDamageTable = { '..damage..'}\n')
local totemMult = ""
local keys = { }
for i = 0, SkillTotemVariations.maxRow do
local var = SkillTotemVariations[i]
if not keys[var.SkillTotemsKey] then
keys[var.SkillTotemsKey] = true
totemMult = totemMult .. "[" .. var.SkillTotemsKey .. "] = " .. MonsterVarieties[var.MonsterVarietiesKey].LifeMultiplier / 100 .. ", "
end
end
out:write('-- From MonsterVarieties.dat combined with SkillTotemVariations.dat\n')
out:write('data.totemLifeMult = { '..totemMult..'}\n')
out:close()
print("Misc data exported.")
|
AddCSLuaFile()
if (CLIENT) then
SWEP.PrintName = "Crowbar"
SWEP.Slot = 1
SWEP.SlotPos = 2
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = false
end
SWEP.Author = "Zenolisk"
SWEP.Instructions = "Primary Fire: Strike"
SWEP.Purpose = "Hitting things."
SWEP.Base = "reb_melee_base"
SWEP.HoldType = "melee"
SWEP.Category = "Rebellion"
SWEP.ViewModelFOV = 65
SWEP.ViewModelFlip = false
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.Primary.Damage = 15
SWEP.Primary.Delay = 0.7
SWEP.Primary.Automatic = true
SWEP.isBlunt = true
SWEP.ViewModel = Model("models/weapons/c_crowbar.mdl")
SWEP.WorldModel = Model("models/weapons/w_crowbar.mdl")
SWEP.weaponLength = 0.5
SWEP.originMod = Vector(0, -3, 4)
SWEP.UseHands = true
|
----------------------------------------------------------------------------------------------------
-- This is a class that defines the type of event.
--
-- <h4>Extends:</h4>
-- <ul>
-- <li><a href="flower.Event.html">Event</a><l/i>
-- </ul>
--
-- @author Makoto
-- @release V3.0.0
----------------------------------------------------------------------------------------------------
-- import
local class = require "flower.class"
local table = require "flower.table"
local Event = require "flower.Event"
-- class
UIEvent = class(Event)
--- UIComponent: Resize Event
UIEvent.RESIZE = "resize"
--- UIComponent: Theme changed Event
UIEvent.THEME_CHANGED = "themeChanged"
--- UIComponent: Style changed Event
UIEvent.STYLE_CHANGED = "styleChanged"
--- UIComponent: Enabled changed Event
UIEvent.ENABLED_CHANGED = "enabledChanged"
--- UIComponent: FocusIn Event
UIEvent.FOCUS_IN = "focusIn"
--- UIComponent: FocusOut Event
UIEvent.FOCUS_OUT = "focusOut"
--- Button: Click Event
UIEvent.CLICK = "click"
--- Button: Click Event
UIEvent.CANCEL = "cancel"
--- Button: Selected changed Event
UIEvent.SELECTED_CHANGED = "selectedChanged"
--- Button: down Event
UIEvent.DOWN = "down"
--- Button: up Event
UIEvent.UP = "up"
--- Slider: value changed Event
UIEvent.VALUE_CHANGED = "valueChanged"
--- Joystick: Event type when you change the position of the stick
UIEvent.STICK_CHANGED = "stickChanged"
--- MsgBox: msgShow Event
UIEvent.MSG_SHOW = "msgShow"
--- MsgBox: msgHide Event
UIEvent.MSG_HIDE = "msgHide"
--- MsgBox: msgEnd Event
UIEvent.MSG_END = "msgEnd"
--- MsgBox: spoolStop Event
UIEvent.SPOOL_STOP = "spoolStop"
--- ListBox: selectedChanged
UIEvent.ITEM_CHANGED = "itemChanged"
--- ListBox: enter
UIEvent.ITEM_ENTER = "itemEnter"
--- ListBox: itemClick
UIEvent.ITEM_CLICK = "itemClick"
--- ScrollGroup: scroll
UIEvent.SCROLL = "scroll"
return UIEvent |
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [Policies]: User consent storage in LocalPT (OnAppPermissionConsent without appID)
-- [HMI API] OnAppPermissionConsent notification
--
-- Description:
-- 1. Used preconditions:
-- SDL and HMI are running
-- <Device> is connected to SDL and consented by the User, <App> is running on that device.
-- <App> is registered with SDL and is present in HMI list of registered aps.
-- Local PT has permissions for <App> that require User`s consent
-- 2. Performed steps: Activate App
--
-- Expected result:
-- 1. HMI->SDL: SDL.ActivateApp {appID}
-- 2. SDL->HMI: SDL.ActivateApp_response{isPermissionsConsentNeeded: true, params}
-- 3. HMI->SDL: GetUserFriendlyMessage{params},
-- 4. SDL->HMI: GetUserFriendlyMessage_response{params}
-- 5. HMI->SDL: GetListOfPermissions{appID}
-- 6. SDL->HMI: GetListOfPermissions_response{}
-- 7. HMI: display the 'app permissions consent' message.
-- 8. The User allows or disallows definite permissions.
-- 9. HMI->SDL: OnAppPermissionConsent {params}
-- 10. PoliciesManager: update "<appID>" subsection of "user_consent_records" subsection of "<device_identifier>" section of "device_data" section in Local PT
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Related_HMI_API/OnAppPermissionConsent.json")
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_trigger_getting_device_consent()
testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC)
end
function Test:Precondition_ExitApplication()
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {appID = self.applications["Test Application"], reason = "USER_EXIT"})
EXPECT_NOTIFICATION("OnHMIStatus", { systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_User_consent_on_activate_app()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName]})
EXPECT_HMIRESPONSE(RequestId,{ isPermissionsConsentNeeded = true })
:Do(function(_,_)
local RequestId1 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage",
{language = "EN-US", messageCodes = {"Notifications", "Location"}})
EXPECT_HMIRESPONSE( RequestId1, {result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
local request_id_list_of_permissions = self.hmiConnection:SendRequest("SDL.GetListOfPermissions", { appID = self.applications[config.application1.registerAppInterfaceParams.appName] })
EXPECT_HMIRESPONSE(request_id_list_of_permissions)
:Do(function(_,data)
local groups = {}
if #data.result.allowedFunctions > 0 then
for i = 1, #data.result.allowedFunctions do
groups[i] = {
name = data.result.allowedFunctions[i].name,
id = data.result.allowedFunctions[i].id,
allowed = true}
end
end
self.hmiConnection:SendNotification("SDL.OnAppPermissionConsent", { appID = self.applications[config.application1.registerAppInterfaceParams.appName], consentedFunctions = groups, source = "GUI"})
EXPECT_NOTIFICATION("OnPermissionsChange")
end)
end)
end)
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
end
function Test:TestStep_check_LocalPT_for_updates()
local is_test_fail = false
self.hmiConnection:SendNotification("SDL.OnPolicyUpdate", {} )
EXPECT_HMICALL("BasicCommunication.PolicyUpdate",{})
:Do(function(_,data)
testCasesForPolicyTableSnapshot:extract_pts({self.applications[config.application1.registerAppInterfaceParams.appName]})
local app_consent_location = testCasesForPolicyTableSnapshot:get_data_from_PTS("device_data."..config.deviceMAC..".user_consent_records."..config.application1.registerAppInterfaceParams.appID..".consent_groups.Location-1")
local app_consent_notifications = testCasesForPolicyTableSnapshot:get_data_from_PTS("device_data."..config.deviceMAC..".user_consent_records."..config.application1.registerAppInterfaceParams.appID..".consent_groups.Notifications")
if(app_consent_location ~= true) then
commonFunctions:printError("Error: consent_groups.Location function for appID should be true")
is_test_fail = true
end
if(app_consent_notifications ~= true) then
commonFunctions:printError("Error: consent_groups.Notifications function for appID should be true")
is_test_fail = true
end
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
testCasesForPolicyTable:Restore_preloaded_pt()
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
local shell = require("shell")
local devfs = require("devfs")
local comp = require("component")
local args, options = shell.parse(...)
if #args < 1 then
io.write("Usage: label [-a] <device> [<label>]\n")
io.write(" -a Device is specified via label or address instead of by path.\n")
return 1
end
local filter = args[1]
local label = args[2]
local proxy, reason
if options.a then
for addr in comp.list() do
if addr:sub(1, filter:len()) == filter then
proxy, reason = comp.proxy(addr)
break
end
local tmp_proxy = comp.proxy(addr)
local tmp_label = devfs.getDeviceLabel(tmp_proxy)
if tmp_label == filter then
proxy = tmp_proxy
break
end
end
else
proxy, reason = devfs.getDevice(args[1])
end
if not proxy then
io.stderr:write(reason..'\n')
return 1
end
if #args < 2 then
local label = devfs.getDeviceLabel(proxy)
if label then
print(label)
else
io.stderr:write("no label\n")
return 1
end
else
devfs.setDeviceLabel(proxy, args[2])
end
|
return {'sok','sokkel','sokkerig','sokophouder','sokkenwol','sokjes','sokkels','sokkeltje','sokkeltjes','sokken','sokophouders','sokje'} |
local propBreakSound = script:GetCustomProperty("BreakSound")
local propBreakEffect = script:GetCustomProperty("BreakEffect")
local BreakSpeed = script:GetCustomProperty("BreakSpeed")
local propGlass = script:GetCustomProperty("Glass"):WaitForObject()
local propDebris = script:GetCustomProperty("Debris"):WaitForObject()
Game.roundStartEvent:Connect(function() script.parent.collision = Collision.FORCE_ON end)
script.parent.beginOverlapEvent:Connect(
function(trigger, obj)
if obj:GetVelocity().size > BreakSpeed then
trigger.collision = Collision.FORCE_OFF
World.SpawnAsset(propBreakEffect, {position = script:GetWorldPosition()}):Play()
World.SpawnAsset(propBreakSound, {position = script:GetWorldPosition()}):Play()
propGlass.visibility = Visibility.FORCE_OFF
propGlass.collision = Collision.FORCE_OFF
propDebris.visibility = Visibility.FORCE_ON
end
end
) |
-- Copyright 2021 Kafka-Tarantool-Loader
--
-- 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.
---
--- Created by ashitov.
--- DateTime: 4/17/20 2:04 PM
---
local repository_utils = require('app.messages.utils.repository_utils')
local t = require('luatest')
local g = t.group('repository_utils.reload_repo_from_files')
g.test_read_simple_configs = function ()
local files = {'test/unit/data/config_files/ADG_INPUT_PROCESSOR.yml',
'test/unit/data/config_files/ADG_KAFKA_CONNECTOR.yml'}
local options = repository_utils.reload_repo_from_files(files)
t.assert_covers(options,{['ADG_INPUT_PROCESSOR_001'] = {
status = 'error' ,
errorCode = 'ADG_INPUT_PROCESSOR_001',
error = 'ERROR: Cannot find parse function'
}})
t.assert_covers(options,{['ADG_KAFKA_CONNECTOR_002'] = {
status = 'error' ,
errorCode = 'ADG_KAFKA_CONNECTOR_002',
error = 'ERROR: Did not receive rows from input processor'
}})
end
g.test_read_empty_configs = function()
local options = repository_utils.reload_repo_from_files({})
t.assert_equals(options,{})
end
g.test_read_not_yaml_configs = function()
local files = {'test/unit/data/simple_files/multiline.txt','test/unit/data/simple_files/singleline.txt'}
local options = repository_utils.reload_repo_from_files(files)
t.assert_equals(options,{})
end |
mature_snorbal_male = Creature:new {
objectName = "@mob/creature_names:mature_snorbal_male",
socialGroup = "snorbal",
faction = "",
level = 32,
chanceHit = 0.4,
damageMin = 305,
damageMax = 320,
baseXp = 3188,
baseHAM = 8600,
baseHAMmax = 10200,
armor = 0,
resists = {135,135,20,-1,-1,-1,-1,20,-1},
meatType = "meat_herbivore",
meatAmount = 545,
hideType = "hide_leathery",
hideAmount = 440,
boneType = "bone_mammal",
boneAmount = 400,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + HERD,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/elder_snorbal_male.iff"},
hues = { 0, 1, 2, 3, 4, 5, 6, 7 },
scale = 1.1,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"posturedownattack",""},
{"stunattack",""}
}
}
CreatureTemplates:addCreatureTemplate(mature_snorbal_male, "mature_snorbal_male")
|
local t = Def.ActorFrame{}
t[#t+1] = LoadActor("Mine_Base");
t[#t+1] = LoadActor("Mine_Fill")..{
InitCommand=cmd(diffuseshift;effectcolor1,color("#FFFFFFFF");effectcolor2,color("#FFFFFF22");effectclock,"bgm";effectperiod,2);
}
t[#t+1] = LoadActor("Mine_Fill")..{
InitCommand=cmd(blend,Blend.Add;diffuseshift;effectcolor1,color("#FFFFFFFF");effectcolor2,color("#FFFFFF22");effectclock,"bgm";effectperiod,2);
}
t[#t+1] = LoadActor("Mine_Border")..{
InitCommand=cmd(spin;effectmagnitude,0,0,36);
}
t[#t+1] = LoadActor("Mine_Overlay");
t[#t+1] = LoadActor("Mine_Light")..{
InitCommand=cmd(blend,Blend.Add;diffuseshift;effectcolor1,color("#FFFFFF55");effectcolor2,color("#FFFFFF00");effectclock,"bgm";zoom,1.15;effectperiod,2);
}
return t |
local tds = require 'tds'
local N = 10000000
require 'torch'
torch.manualSeed(1111)
local timer = torch.Timer()
local perm = torch.randperm(N)
local tbl
if arg[1] == 'lua' then
print('using lua tables!')
tbl = {}
else
print('using tds tables!')
tbl = tds.Vec()
end
print('filling up')
timer:reset()
for i=1,N do
tbl[i] = perm[i]
end
print(' time:', timer:time().real)
print()
print('done, now summing')
timer:reset()
local perm = torch.randperm(N)
local sum = 0
for i=1,N do
sum = sum + tbl[perm[i]]
end
print(sum, #tbl)
print(' time:', timer:time().real)
print()
print('sorting!')
timer:reset()
if arg[1] == 'lua' then
table.sort(
tbl,
function(a, b)
return a < b
end
)
else
tbl:sort(
function(a, b)
return a < b
end
)
end
print(' time:', timer:time().real)
print()
print('now run over it')
timer:reset()
local n = 0
for key, value in ipairs(tbl) do
if n < 10 then
print(key, value)
end
n = n + 1
end
print()
print('size', n)
print(' time:', timer:time().real)
print()
|
DATA = {}
function add4d(f) DATA[#DATA+1] = f end
loadToolData 'street-decoration'
dofile(scriptDirectory..'/tool-four-directions.lua')
|
require 'torch'
require 'image'
torch.setdefaulttensortype('torch.FloatTensor')
----------------------------------------------------------------------
print '==> define parameters'
local histClasses = opt.datahistClasses
local classes = opt.dataClasses
----------------------------------------------------------------------
print '==> construct model'
-- encoder CNN:
nn.DataParallelTable.deserializeNGPUs = 1
model = torch.load(opt.CNNEncoder)
if torch.typename(model) == 'nn.DataParallelTable' then model = model:get(1) end
model:remove(#model.modules) -- remove the classifier
-- SpatialMaxUnpooling requires nn modules...
model:apply(function(module)
if module.modules then
for i,submodule in ipairs(module.modules) do
if torch.typename(submodule):match('cudnn.SpatialMaxPooling') then
module.modules[i] = nn.SpatialMaxPooling(2, 2, 2, 2) -- TODO: make more flexible
end
end
end
end)
-- find pooling modules
local pooling_modules = {}
model:apply(function(module)
if torch.typename(module):match('nn.SpatialMaxPooling') then
table.insert(pooling_modules, module)
end
end)
assert(#pooling_modules == 3, 'There should be 3 pooling modules')
-- kill gradient
-- local grad_killer = nn.Identity()
-- function grad_killer:updateGradInput(input, gradOutput)
-- return self.gradInput:resizeAs(gradOutput):zero()
-- end
-- model:add(grad_killer)
-- decoder:
print(pooling_modules)
function bottleneck(input, output, upsample, reverse_module)
local internal = output / 4
local input_stride = upsample and 2 or 1
local module = nn.Sequential()
local sum = nn.ConcatTable()
local main = nn.Sequential()
local other = nn.Sequential()
sum:add(main):add(other)
main:add(cudnn.SpatialConvolution(input, internal, 1, 1, 1, 1, 0, 0):noBias())
main:add(nn.SpatialBatchNormalization(internal, 1e-3))
main:add(cudnn.ReLU(true))
if not upsample then
main:add(cudnn.SpatialConvolution(internal, internal, 3, 3, 1, 1, 1, 1))
else
main:add(nn.SpatialFullConvolution(internal, internal, 3, 3, 2, 2, 1, 1, 1, 1))
end
main:add(nn.SpatialBatchNormalization(internal, 1e-3))
main:add(cudnn.ReLU(true))
main:add(cudnn.SpatialConvolution(internal, output, 1, 1, 1, 1, 0, 0):noBias())
main:add(nn.SpatialBatchNormalization(output, 1e-3))
other:add(nn.Identity())
if input ~= output or upsample then
other:add(cudnn.SpatialConvolution(input, output, 1, 1, 1, 1, 0, 0):noBias())
other:add(nn.SpatialBatchNormalization(output, 1e-3))
if upsample and reverse_module then
other:add(nn.SpatialMaxUnpooling(reverse_module))
end
end
if upsample and not reverse_module then
main:remove(#main.modules) -- remove BN
return main
end
return module:add(sum):add(nn.CAddTable()):add(cudnn.ReLU(true))
end
--model:add(bottleneck(128, 128))
model:add(bottleneck(128, 64, true, pooling_modules[3])) -- 32x64
model:add(bottleneck(64, 64))
model:add(bottleneck(64, 64))
model:add(bottleneck(64, 16, true, pooling_modules[2])) -- 64x128
model:add(bottleneck(16, 16))
model:add(nn.SpatialFullConvolution(16, #classes, 2, 2, 2, 2))
if cutorch.getDeviceCount() > 1 then
local gpu_list = {}
for i = 1,cutorch.getDeviceCount() do gpu_list[i] = i end
model = nn.DataParallelTable(1):add(model:cuda(), gpu_list)
print(opt.nGPU .. " GPUs being used")
end
-- Loss: NLL
print('defining loss function:')
local normHist = histClasses / histClasses:sum()
local classWeights = torch.Tensor(#classes):fill(1)
for i = 1, #classes do
-- Ignore unlabeled and egoVehicle
if i == 1 then
classWeights[i] = 0
end
if histClasses[i] < 1 then
print("Class " .. tostring(i) .. " not found")
classWeights[i] = 0
else
classWeights[i] = 1 / (torch.log(1.02 + normHist[i]))
end
end
loss = cudnn.SpatialCrossEntropyCriterion(classWeights)
model:cuda()
loss:cuda()
----------------------------------------------------------------------
print '==> here is the model:'
print(model)
-- return package:
return {
model = model,
loss = loss,
}
|
local tableofmaterials = tableofmaterials or {}
local materialused = false
resource.AddWorkshop( "1115073625" )
resource.AddFile( "resource/fonts/prime.ttf" )
resource.AddFile( "models/rgngs_vend1/snack.mdl" )
resource.AddFile( "materials/rgngs_vend1/Material__53.vmt" )
resource.AddFile( "materials/rgngs_vend1/Material__55.vmt" )
resource.AddFile( "materials/rgngs_vend1/Material__67.vmt" )
resource.AddFile( "materials/rgngs_vend1/Material__80.vmt" )
resource.AddFile( "materials/rgngs_vend1/snack.vtf" )
resource.AddFile( "materials/rgngs_vend1/snack_dec.vtf" )
resource.AddFile( "materials/rgngs_vend1/snack_glass.vtf" )
for k, v in pairs( ragistable.config.vendingtable ) do
for key, value in pairs( tableofmaterials ) do
materialused = false
if value == v[4] then
materialused = true
break
end
end
if materialused == true then
table.insert( tableofmaterials, v[4])
materialused = false
end
end
for k, v in pairs( tableofmaterials ) do
resource.AddSingleFile( v )
end |
Ext.Require("Mimicry_d9cac48f-1294-68f8-dd4d-b5ea38eaf2d6", "LLMIME_StatOverrides.lua")
local LeaderLib = Mods["LeaderLib"]
function SaveFacingDirection(uuid)
local character = Ext.GetCharacter(uuid)
local rot = character.Stats.Rotation
Ext.Print("Rotation: ", LeaderLib.Common.Dump(rot))
Osi.LLMIME_Skills_SaveFacingDirection(uuid, rot[7], rot[9])
Ext.Print("[Mimicry:SaveFacingDirection] Saved facing direction for ", uuid)
CharacterStatusText(uuid, "LLMIME_StatusText_FacingDirectionSaved")
end
function ApplyFacingDirection(uuid)
Ext.Print("[Mimicry:ApplyFacingDirection] Applying facing direction for ", uuid)
local dbEntry = Osi.DB_LLMIME_Skills_FacingDirection:Get(uuid, nil, nil)
if dbEntry ~= nil and #dbEntry > 0 then
local rotx = dbEntry[1][2]
local rotz = dbEntry[1][3]
local x,y,z = 0.0,0.0,0.0
if rotx~= nil and rotz ~= nil then
local character = Ext.GetCharacter(uuid)
local pos = character.Stats.Position
local distanceMult = 2.0
local rot = character.Stats.Rotation
local diff = math.abs(rot[7] - rotx) + math.abs(rot[9] - rotz)
Ext.Print("[Mimicry:ApplyFacingDirection] Diff: ", diff)
if diff >= 0.01 then
local forwardVector = {
-rotx * distanceMult,
0,
-rotz * distanceMult,
}
x = pos[1] + forwardVector[1]
z = pos[3] + forwardVector[3]
y = pos[2]
local target = CreateItemTemplateAtPosition("98fa7688-0810-4113-ba94-9a8c8463f830", x, y, z)
CharacterLookAt(uuid, target, 1)
--PlayEffect(uuid, "RS3_FX_Skills_Rogue_Vault_Cast_Overlay_01", "")
Osi.LeaderLib_Timers_StartObjectTimer(target, 250, "LLMIME_Timers_LeaderLib_Commands_RemoveItem", "LeaderLib_Commands_RemoveItem")
Ext.Print("[Mimicry:ApplyFacingDirection] Facing direction: ", x, y, z)
--PlayEffectAtPosition("RS3_FX_Skills_Fire_Haste_Impact_Root_01",x,y,z)
--PlayEffectAtPosition("RS3_FX_Skills_Earth_Cast_Aoe_Voodoo_Root_01",x,y,z)
else
Ext.Print("[Mimicry:ApplyFacingDirection] Skipping rotation since character facing is the same.")
end
else
Ext.PrintError("[Mimicry:ApplyFacingDirection] Failed: Saved rotation is null:\n"..tostring(LeaderLib.Common.Dump(dbEntry)))
end
else
Ext.PrintError("[Mimicry:ApplyFacingDirection] No saved rotation for mime:\n"..tostring(LeaderLib.Common.Dump(dbEntry)))
end
end
local function CloneWeapon(mime,item,slot)
NRD_ItemCloneBegin(item)
local stat = NRD_ItemGetStatsId(item)
local statType = NRD_StatGetType(stat)
if statType == "Weapon" then
-- Damage type fix
-- Deltamods with damage boosts may make the weapon's damage type be all of that type, so overwriting the statType
-- fixes this issue.
local damageTypeString = Ext.StatGetAttribute(stat, "Damage Type")
if damageTypeString == nil then damageTypeString = "Physical" end
local damageTypeEnum = LeaderLib.Data.DamageTypeEnums[damageTypeString]
NRD_ItemCloneSetInt("DamageTypeOverwrite", damageTypeEnum)
end
local clone = NRD_ItemClone()
SetTag(clone, "LLMIME_MIMICKED_WEAPON")
ItemSetOriginalOwner(clone, mime)
--CharacterEquipItem(mime, clone)
NRD_CharacterEquipItem(mime, clone, slot, 0, 0, 0, 1)
ItemSetCanInteract(clone, 0)
ItemSetOnlyOwnerCanUse(clone, 1)
return clone
end
Ext.NewQuery(CloneWeapon, "LLMIME_Ext_QRY_CloneWeapon", "[in](CHARACTERGUID)_Mime, [in](ITEMGUID)_Item, [in](STRING)_Slot, [out](ITEMGUID)_Clone")
local function GetMimeSkillTargetPosition(mimeuuid, caster, x, y, z)
local mime = Ext.GetCharacter(mimeuuid)
--local caster = Ext.GetCharacter(casteruuid)
local pos = mime.Stats.Position
local rot = mime.Stats.Rotation
local dist = GetDistanceToPosition(caster, x, y, z)
local forwardX = -rot[7] * dist
local forwardZ = -rot[9] * dist
--Ext.Print("forwardVector:",Ext.JsonStringify(forwardVector))
local tx = pos[1] + forwardX
local tz = pos[3] + forwardZ
return tx, tz
end
Ext.NewQuery(GetMimeSkillTargetPosition, "LLMIME_Ext_QRY_GetMimeSkillTargetPosition", "[in](CHARACTERGUID)_Mime, [in](CHARACTERGUID)_Caster, [in](REAL)_x, [in](REAL)_y, [in](REAL)_z, [out](REAL)_tx, [out](REAL)_tz")
local brawlerWeaponTags = {
"UNARMED_WEAPON",
"LLMIME_BrawlerFist",
}
local function IsUnarmedWeapon(weapon)
if weapon == nil then return true end
for i,tag in pairs(brawlerWeaponTags) do
if IsTagged(weapon, tag) == 1 then
return true
end
end
local stat = NRD_ItemGetStatsId(weapon)
local statType = NRD_StatGetType(stat)
--Ext.Print("[LLMIME_Ext_QRY_IsUnarmed] weapon ("..weapon..") stat("..stat..")")
if statType == "Weapon" then
if Ext.StatGetAttribute(stat, "AnimType") == "Unarmed" then
return true
end
else
return true
end
return false
end
local function IsUnarmed(character)
local weapon = CharacterGetEquippedItem(character, "Weapon")
local offhand = CharacterGetEquippedItem(character, "Shield")
if weapon == nil and offhand == nil then
return 1
else
if IsUnarmedWeapon(weapon) and IsUnarmedWeapon(offhand) then
return 1
end
end
--Ext.Print("[LLMIME_Ext_QRY_IsUnarmed] weapon("..tostring(weapon)..") offhand("..tostring(offhand)..")")
return 0
end
Ext.NewQuery(IsUnarmed, "LLMIME_Ext_QRY_IsUnarmed", "[in](CHARACTERGUID)_Character, [out](INTEGER)_IsUnarmed")
local function SkillRequiresWeapon(skill)
local useWeaponDamage = Ext.StatGetAttribute(skill, "UseWeaponDamage")
if useWeaponDamage == "Yes" then
return true
end
local requirement = Ext.StatGetAttribute(skill, "Requirement")
if (requirement ~= nil and requirement ~= "None" and requirement ~= "") then
return true
end
return false
end
local function SkillRequiresWeapon_QRY(skill)
if SkillRequiresWeapon(skill) then
return 1
end
return 0
end
Ext.NewQuery(SkillRequiresWeapon_QRY, "LLMIME_Ext_QRY_SkillRequiresWeapon", "[in](STRING)_Skill, [out](INTEGER)_RequiresWeapon")
if Ext.IsDeveloperMode() then
Ext.RegisterConsoleCommand("llmime_testsetup", function(call, ...)
local host = CharacterGetHostCharacter()
CharacterAddSkill(host, "Jump_LLMIME_HiddenApproach", 0)
CharacterAddSkill(host, "Summon_Cat", 0)
CharacterAddSkill(host, "MultiStrike_LLMIME_MimeVault", 0)
CharacterAddSkill(host, "Shout_LLMIME_QuakeSlam", 0)
--CharacterAddSkill(CharacterGetHostCharacter(), "Shout_LLMIME_QuakeSlam", 0)
--CharacterAddSkill(CharacterGetHostCharacter(), "MultiStrike_LLMIME_MimeVault", 0)
if ItemTemplateIsInPartyInventory(host, "EQ_Armor_LLMIME_Mime_Mask_A_8e66ce79-8c8e-4c22-a8ea-5a99977f4ea8", 0) <= 0 then
ItemTemplateAddTo("EQ_Armor_LLMIME_Mime_Mask_A_8e66ce79-8c8e-4c22-a8ea-5a99977f4ea8", host, 1, 0)
NRD_CharacterSetPermanentBoostTalent("S_FTJ_BeachVw_001_08348b3a-bded-4811-92ce-f127aa4310e0", "AttackOfOpportunity", 1)
CharacterAddAttribute("S_FTJ_BeachVw_001_08348b3a-bded-4811-92ce-f127aa4310e0", "Dummy", 0)
end
--CharacterAddAbilityPoint(CharacterGetHostCharacter(), 10)
--CharacterStatusText("S_FTJ_BeachVw_001_08348b3a-bded-4811-92ce-f127aa4310e0", "Test")
--CharacterSetImmortal(CharacterGetHostCharacter(), 1)
end)
end
local DU_Disabling_Statuses = {
"KCE_KNOCKED_DOWN",
"KCE_FROZEN",
"KCE_STUNNED",
"KCE_OSSIFIED",
}
function CanMugTarget(uuid)
-- Divinity Unleashed
if Ext.IsModLoaded("e844229e-b744-4294-9102-a7362a926f71") then
for i,status in pairs(DU_Disabling_Statuses) do
if HasActiveStatus(uuid, status) == 1 then
return true
end
end
end
end |
--- === plugins.finalcutpro.tangent.video ===
---
--- Final Cut Pro Video Inspector for Tangent
local require = require
--local log = require "hs.logger".new "tangentVideo"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local tools = require "cp.tools"
local tableCount = tools.tableCount
local plugin = {
id = "finalcutpro.tangent.video",
group = "finalcutpro",
dependencies = {
["finalcutpro.tangent.common"] = "common",
["finalcutpro.tangent.group"] = "fcpGroup",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Only load plugin if Final Cut Pro is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
--------------------------------------------------------------------------------
-- Setup:
--------------------------------------------------------------------------------
local id = 0x0F730000
local common = deps.common
local fcpGroup = deps.fcpGroup
local buttonParameter = common.buttonParameter
local checkboxParameter = common.checkboxParameter
local checkboxParameterByIndex = common.checkboxParameterByIndex
local doShowParameter = common.doShowParameter
local ninjaButtonParameter = common.ninjaButtonParameter
local popupParameter = common.popupParameter
local popupParameters = common.popupParameters
local popupSliderParameter = common.popupSliderParameter
local sliderParameter = common.sliderParameter
local xyParameter = common.xyParameter
--------------------------------------------------------------------------------
-- VIDEO INSPECTOR:
--------------------------------------------------------------------------------
local video = fcp.inspector.video
local videoGroup = fcpGroup:group(i18n("video") .. " " .. i18n("inspector"))
local BLEND_MODES = video.BLEND_MODES
local CROP_TYPES = video.CROP_TYPES
local STABILIZATION_METHODS = video.STABILIZATION_METHODS
local ROLLING_SHUTTER_AMOUNTS = video.ROLLING_SHUTTER_AMOUNTS
local SPATIAL_CONFORM_TYPES = video.SPATIAL_CONFORM_TYPES
--------------------------------------------------------------------------------
-- Show Inspector:
--------------------------------------------------------------------------------
id = doShowParameter(videoGroup, video, id, i18n("show") .. " " .. i18n("inspector"))
--------------------------------------------------------------------------------
--
-- EFFECTS:
--
--------------------------------------------------------------------------------
local effects = video.effects
local effectsGroup = videoGroup:group(i18n("effects"))
--------------------------------------------------------------------------------
-- Enable/Disable:
--------------------------------------------------------------------------------
id = checkboxParameter(effectsGroup, effects.enabled, id, "toggle")
--------------------------------------------------------------------------------
-- Individual Effects:
--------------------------------------------------------------------------------
local individualEffectsGroup = effectsGroup:group(i18n("individualEffects"))
for i=1, 9 do
id = checkboxParameterByIndex(individualEffectsGroup, effects, video:compositing(), id, i18n("toggle") .. " " .. i, i)
end
--------------------------------------------------------------------------------
--
-- COMPOSITING:
--
--------------------------------------------------------------------------------
local compositing = video:compositing()
local compositingGroup = videoGroup:group(compositing:label())
--------------------------------------------------------------------------------
-- Reset:
--------------------------------------------------------------------------------
id = ninjaButtonParameter(compositingGroup, compositing.reset, id, "reset")
--------------------------------------------------------------------------------
-- Blend Mode (Buttons):
--------------------------------------------------------------------------------
local blendMode = fcp.inspector.video:compositing():blendMode()
local blendModesGroup = compositingGroup:group(i18n("blendModes"))
for i=1, tableCount(BLEND_MODES) do
local v = BLEND_MODES[i]
if v.flexoID ~= nil then
id = popupParameter(blendModesGroup, blendMode, id, fcp:string(v.flexoID), v.i18n)
end
end
--------------------------------------------------------------------------------
-- Blend Mode (Knob):
--------------------------------------------------------------------------------
id = popupSliderParameter(compositingGroup, blendMode.value, id, "blendModes", BLEND_MODES, 1)
--------------------------------------------------------------------------------
-- Opacity:
--------------------------------------------------------------------------------
id = sliderParameter(compositingGroup, compositing:opacity(), id, 0, 100, 0.1, 100)
--------------------------------------------------------------------------------
--
-- TRANSFORM:
--
--------------------------------------------------------------------------------
local transform = video:transform()
local transformGroup = videoGroup:group(transform:label())
--------------------------------------------------------------------------------
-- Enable/Disable:
--------------------------------------------------------------------------------
id = checkboxParameter(transformGroup, transform.enabled, id, "toggle")
--------------------------------------------------------------------------------
-- Toggle UI:
--------------------------------------------------------------------------------
id = buttonParameter(transformGroup, transform.toggle, id, "toggleControls")
--------------------------------------------------------------------------------
-- Reset:
--------------------------------------------------------------------------------
id = ninjaButtonParameter(transformGroup, transform.reset, id, "reset")
--------------------------------------------------------------------------------
-- Position:
--------------------------------------------------------------------------------
local px, py, rotation
id, px, py = xyParameter(transformGroup, transform:position(), id, 0, 1000, 0.1)
--------------------------------------------------------------------------------
-- Rotation:
--------------------------------------------------------------------------------
id, rotation = sliderParameter(transformGroup, transform:rotation(), id, 0, 360, 0.1)
transformGroup:binding(tostring(transform:position()) .. " " .. tostring(transform:rotation()))
:members(px, py, rotation)
--------------------------------------------------------------------------------
-- Scale:
--------------------------------------------------------------------------------
id = sliderParameter(transformGroup, transform:scaleAll(), id, 0, 100, 0.1, 100.0)
id = sliderParameter(transformGroup, transform:scaleX(), id, 0, 100, 0.1, 100.0)
id = sliderParameter(transformGroup, transform:scaleY(), id, 0, 100, 0.1, 100.0)
--------------------------------------------------------------------------------
-- Anchor:
--------------------------------------------------------------------------------
id = xyParameter(transformGroup, transform:anchor(), id, 0, 1000, 0.1)
--------------------------------------------------------------------------------
--
-- CROP:
--
--------------------------------------------------------------------------------
local crop = video:crop()
local cropGroup = videoGroup:group(crop:label())
--------------------------------------------------------------------------------
-- Enable/Disable:
--------------------------------------------------------------------------------
id = checkboxParameter(cropGroup, crop.enabled, id, "toggle")
--------------------------------------------------------------------------------
-- Toggle UI:
--------------------------------------------------------------------------------
id = buttonParameter(cropGroup, crop.toggle, id, "toggleControls")
--------------------------------------------------------------------------------
-- Reset:
--------------------------------------------------------------------------------
id = ninjaButtonParameter(cropGroup, crop.reset, id, "reset")
--------------------------------------------------------------------------------
-- Type (Buttons):
--------------------------------------------------------------------------------
local cropType = fcp.inspector.video:crop():type()
local cropTypesGroup = cropGroup:group(i18n("cropTypes"))
id = popupParameters(cropTypesGroup, cropType, id, CROP_TYPES)
--------------------------------------------------------------------------------
-- Type (Knob):
--------------------------------------------------------------------------------
id = popupSliderParameter(cropGroup, cropType.value, id, "cropTypes", CROP_TYPES, 1)
--------------------------------------------------------------------------------
-- Left / Right / Top / Bottom:
--------------------------------------------------------------------------------
id = sliderParameter(cropGroup, crop:left(), id, 0, 1080, 0.1, 0)
id = sliderParameter(cropGroup, crop:right(), id, 0, 1080, 0.1, 0)
id = sliderParameter(cropGroup, crop:top(), id, 0, 1080, 0.1, 0)
id = sliderParameter(cropGroup, crop:bottom(), id, 0, 1080, 0.1, 0)
--------------------------------------------------------------------------------
--
-- DISTORT:
--
--------------------------------------------------------------------------------
local distort = video:distort()
local distortGroup = videoGroup:group(distort:label())
--------------------------------------------------------------------------------
-- Enable/Disable:
--------------------------------------------------------------------------------
id = checkboxParameter(distortGroup, distort.enabled, id, "toggle")
--------------------------------------------------------------------------------
-- Toggle UI:
--------------------------------------------------------------------------------
id = buttonParameter(distortGroup, distort.toggle, id, "toggleControls")
--------------------------------------------------------------------------------
-- Reset:
--------------------------------------------------------------------------------
id = ninjaButtonParameter(distortGroup, distort.reset, id, "reset")
--------------------------------------------------------------------------------
-- Bottom Left / Bottom Right / Top Right / Top Left:
--------------------------------------------------------------------------------
id = xyParameter(distortGroup, distort:bottomLeft(), id, 0, 1080, 0.1)
id = xyParameter(distortGroup, distort:bottomRight(), id, 0, 1080, 0.1)
id = xyParameter(distortGroup, distort:topRight(), id, 0, 1080, 0.1)
id = xyParameter(distortGroup, distort:topLeft(), id, 0, 1080, 0.1)
--------------------------------------------------------------------------------
--
-- STABILISATION:
--
--------------------------------------------------------------------------------
local stabilization = video:stabilization()
local stabilizationGroup = videoGroup:group(stabilization:label())
--------------------------------------------------------------------------------
-- Enable/Disable:
--------------------------------------------------------------------------------
id = checkboxParameter(stabilizationGroup, stabilization.enabled, id, "toggle")
--------------------------------------------------------------------------------
-- Reset:
--------------------------------------------------------------------------------
id = ninjaButtonParameter(stabilizationGroup, stabilization.reset, id, "reset")
--------------------------------------------------------------------------------
-- Method (Buttons):
--------------------------------------------------------------------------------
local stabilizationMethod = stabilization:method()
local stabilizationMethodGroup = stabilizationGroup:group(i18n("methods"))
id = popupParameters(stabilizationMethodGroup, stabilizationMethod, id, STABILIZATION_METHODS)
--------------------------------------------------------------------------------
-- Method (Knob):
--------------------------------------------------------------------------------
id = popupSliderParameter(stabilizationGroup, stabilization:method().value, id, "method", STABILIZATION_METHODS, 1)
--------------------------------------------------------------------------------
-- Translation Smooth / Rotation Smooth / Scale Smooth / Smoothing:
--------------------------------------------------------------------------------
id = sliderParameter(stabilizationGroup, stabilization:translationSmooth(), id, 0, 4.5, 0.1, 1.5)
id = sliderParameter(stabilizationGroup, stabilization:rotationSmoooth(), id, 0, 4.5, 0.1, 1.5)
id = sliderParameter(stabilizationGroup, stabilization:scaleSmooth(), id, 0, 4.5, 0.1, 1.5)
id = sliderParameter(stabilizationGroup, stabilization:smoothing(), id, 0, 3, 0.1, 1)
--------------------------------------------------------------------------------
--
-- ROLLING SHUTTER:
--
--------------------------------------------------------------------------------
local rollingShutter = video:rollingShutter()
local rollingShutterGroup = videoGroup:group(rollingShutter:label())
--------------------------------------------------------------------------------
-- Enable/Disable:
--------------------------------------------------------------------------------
id = checkboxParameter(rollingShutterGroup, rollingShutter.enabled, id, "toggle")
--------------------------------------------------------------------------------
-- Reset:
--------------------------------------------------------------------------------
id = ninjaButtonParameter(rollingShutterGroup, rollingShutter.reset, id, "reset")
--------------------------------------------------------------------------------
-- Amount (Buttons):
--------------------------------------------------------------------------------
local rollingShutterAmount = rollingShutter:amount()
local rollingShutterAmountGroup = rollingShutterGroup:group(i18n("amounts"))
id = popupParameters(rollingShutterAmountGroup, rollingShutterAmount, id, ROLLING_SHUTTER_AMOUNTS)
--------------------------------------------------------------------------------
-- Amount (Knob):
--------------------------------------------------------------------------------
id = popupSliderParameter(rollingShutterGroup, rollingShutterAmount.value, id, "amount", ROLLING_SHUTTER_AMOUNTS, 1)
--------------------------------------------------------------------------------
--
-- SPATIAL CONFORM:
--
--------------------------------------------------------------------------------
local spatialConform = video:spatialConform()
local spatialConformGroup = videoGroup:group(spatialConform:label())
--------------------------------------------------------------------------------
-- Reset:
--------------------------------------------------------------------------------
id = ninjaButtonParameter(spatialConformGroup, spatialConform.reset, id, "reset")
--------------------------------------------------------------------------------
-- Type (Buttons):
--------------------------------------------------------------------------------
local spatialConformType = spatialConform:type()
local spatialConformTypeGroup = spatialConformGroup:group(i18n("types"))
id = popupParameters(spatialConformTypeGroup, spatialConformType, id, SPATIAL_CONFORM_TYPES)
--------------------------------------------------------------------------------
-- Type (Knob):
--------------------------------------------------------------------------------
popupSliderParameter(spatialConformGroup, spatialConformType.value, id, "type", SPATIAL_CONFORM_TYPES, 1)
end
return plugin
|
-- bradcush/base16-nvim (https://github.com/bradcush/base16-nvim)
-- by Bradley Cushing (https://github.com/bradcush)
-- Github scheme by Defman21
-- Based on existing work with references below
-- base16-vim (https://github.com/chriskempson/base16-vim)
-- by Chris Kempson (http://chriskempson.com)
-- RRethy/nvim-base16 (https://github.com/RRethy/nvim-base16)
-- by Adam P. Regasz-Rethy (https://github.com/RRethy)
-- Base16 color variables
local colors = {
base00 = "#ffffff",
base01 = "#f5f5f5",
base02 = "#c8c8fa",
base03 = "#969896",
base04 = "#e8e8e8",
base05 = "#333333",
base06 = "#ffffff",
base07 = "#ffffff",
base08 = "#ed6a43",
base09 = "#0086b3",
base0A = "#795da3",
base0B = "#183691",
base0C = "#183691",
base0D = "#795da3",
base0E = "#a71d5d",
base0F = "#333333"
}
-- Highlighting for indiividual groups
local hi = function(args)
local hlgroup = args.hlgroup
local guifg = args.guifg
local guibg = args.guibg
local gui = args.gui
local guisp = args.guisp
local cmd = {'hi', hlgroup}
if guifg then table.insert(cmd, 'guifg=' .. guifg) end
if guibg then table.insert(cmd, 'guibg=' .. guibg) end
if gui then table.insert(cmd, 'gui=' .. gui) end
if guisp then table.insert(cmd, 'guisp=' .. guisp) end
vim.cmd(table.concat(cmd, ' '))
end
-- Set specified highlight groups
local setup = function(collections)
-- Setting highlighting and syntax
vim.cmd('highlight clear')
vim.cmd('syntax reset')
vim.g.colors_name = "base16-github"
-- Loop through highlighting collections
for _, collection in pairs(collections) do
for _, group in ipairs(collection) do hi(group) end
end
-- Built-in terminal
vim.g.terminal_color_0 = colors.base00
vim.g.terminal_color_1 = colors.base08
vim.g.terminal_color_2 = colors.base0B
vim.g.terminal_color_3 = colors.base0A
vim.g.terminal_color_4 = colors.base0D
vim.g.terminal_color_5 = colors.base0E
vim.g.terminal_color_6 = colors.base0C
vim.g.terminal_color_7 = colors.base05
vim.g.terminal_color_8 = colors.base03
vim.g.terminal_color_9 = colors.base08
vim.g.terminal_color_10 = colors.base0B
vim.g.terminal_color_11 = colors.base0A
vim.g.terminal_color_12 = colors.base0D
vim.g.terminal_color_13 = colors.base0E
vim.g.terminal_color_14 = colors.base0C
vim.g.terminal_color_15 = colors.base07
end
-- Highlight specified groups
local makeVimCollection = require('vim')
local makeStandardCollection = require('standard')
local makeDiffCollection = require('diff')
local makeGitCollection = require('git')
local makeSpellCollection = require('spell')
local makeNeovimCollection = require('neovim')
local makeUserCollection = require('user')
local makeLspCollection = require('lsp')
local makeTreesitterCollection = require('treesitter')
setup({
vim = makeVimCollection(colors),
standard = makeStandardCollection(colors),
diff = makeDiffCollection(colors),
git = makeGitCollection(colors),
spell = makeSpellCollection(colors),
neovim = makeNeovimCollection(colors),
user = makeUserCollection(colors),
lsp = makeLspCollection(colors),
treesitter = makeTreesitterCollection(colors)
})
|
--local Entity = require("__stdlib__/stdlib/entity/entity")
local Csv =
{
_csvs = {},
__call = function(self, ...)
return self.get(...)
end,
__index = Csv
}
setmetatable(Csv, Csv)
function Csv.get(...)
local filename = ...
return Csv._csvs[filename] or Csv.new(...)
end
function Csv.new(filename)
Csv._csvs[filename] = nil
local CsvFile =
{
filename = filename
}
function CsvFile.log(item, count)
game.write_file(CsvFile.filename, item .. "," .. count, true)
end
Csv._csvs[filename] = CsvFile
return CsvFile
end
return Csv
--[[
function Csv.init(entity, state)
state.filename = ""
Entity.set_data(entity, state)
end
]]
|
hook.Add( "OnEntityCreated", "_simf_trailer_addons_hook_929503203509295983925928529385", function(ent)--maded by SupinePandora43 (ะะฝะดััั
ะฐ!!)
if ( ent:GetClass() == "gmod_sent_vehicle_fphysics_base" ) then--ะผะพะน ะฝะตะฑะพะปััะพะน ัะบัะธะฟั ะฝะฐ ะฟะพะดะดะตัะถะบั Trailers Base for simfphys
timer.Simple( 2, function()
if not IsValid(ent) then return end
if ent:GetModel() == "models/blu/conscript_apc.mdl" then ent:SetCenterposition(Vector(0,-133.6,-27)) end--APC armed
if ent:GetModel() == "models/crsk_autos/tesla/model_x_2015.mdl" then ent:SetCenterposition(Vector(0,-152,20)) ent:SetSkin( 4 ) end --Tesla Model X
if ent:GetModel() == "models/dk_cars/tesla/modelsp90d/p90d.mdl" then ent:SetCenterposition(Vector(135,0,-15)) end --Tesla Model S [DK]
if ent:GetModel() == "models/monowheel.mdl" then ent:SetCenterposition(Vector(0,-40,20)) ent:SetBackFire(true) end --Monowheel Wolfenstein II: TNC Cars
if ent:GetModel() == "models/props_c17/furniturecouch002a.mdl" then ent:SetCenterposition(Vector(-18,0,0)) end --Base Driveable Couch
if ent:GetModel() == "models/dk_cars/rc_toys/monster_truck/gtav_monstertruck.mdl" then ent:SetCenterposition(Vector(28,0,5)) ent:SetSkin( 1 ) ent:SetBodygroup(12,1) end -- DK GTA5 RC Liberator
if ent:GetModel() == "models/tdmcars/del_dmc.mdl" then ent:SetCenterposition(Vector(0,-100,20)) end --Delorean DMC-12
end)
end
end) |
-- 1st param, ipAddress
-- 2nd param, permanent
-- AddIpAddress("127.0.0.1", true); |
fx_version 'adamant'
game 'gta5'
dependencies {
'main',
}
shared_scripts {
'shared/config.lua',
'shared/main.lua',
'shared/users.lua',
'shared/flags.lua',
}
client_scripts {
'client/main.lua',
'client/users.lua',
'client/flags.lua',
}
server_scripts {
'@utils/server/database.lua',
'server/config.lua',
'server/misc.lua',
'server/main.lua',
'server/users.lua',
'server/flags.lua',
'server/queue.lua',
'server/commands.lua',
} |
--- === ClipboardTool ===
---
--- Keep a history of the clipboard for text entries and manage the entries with a context menu
---
--- Originally based on TextClipboardHistory.spoon by Diego Zamboni with additional functions provided by a context menu
--- and on [code by VFS](https://github.com/VFS/.hammerspoon/blob/master/tools/clipboard.lua), but with many changes and some contributions and inspiration from [asmagill](https://github.com/asmagill/hammerspoon-config/blob/master/utils/_menus/newClipper.lua).
---
--- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/ClipboardTool.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/ClipboardTool.spoon.zip)
local obj={}
obj.__index = obj
-- Metadata
obj.name = "ClipboardTool"
obj.version = "0.7"
obj.author = "Alfred Schilken <alfred@schilken.de>"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"
local getSetting = function(label, default) return hs.settings.get(obj.name.."."..label) or default end
local setSetting = function(label, value) hs.settings.set(obj.name.."."..label, value); return value end
--- ClipboardTool.frequency
--- Variable
--- Speed in seconds to check for clipboard changes. If you check too frequently, you will degrade performance, if you check sparsely you will loose copies. Defaults to 0.8.
obj.frequency = 0.8
--- ClipboardTool.hist_size
--- Variable
--- How many items to keep on history. Defaults to 100
obj.hist_size = 100
--- ClipboardTool.max_entry_size
--- Variable
--- maximum size of a text entry
obj.max_entry_size = 4990
--- ClipboardTool.max_size
--- Variable
--- Whether to check the maximum size of an entry. Defaults to `false`.
obj.max_size = getSetting('max_size', false)
--- ClipboardTool.show_copied_alert
--- Variable
--- If `true`, show an alert when a new item is added to the history, i.e. has been copied.
obj.show_copied_alert = true
--- ClipboardTool.honor_ignoredidentifiers
--- Variable
--- If `true`, check the data identifiers set in the pasteboard and ignore entries which match those listed in `ClipboardTool.ignoredIdentifiers`. The list of identifiers comes from http://nspasteboard.org. Defaults to `true`
obj.honor_ignoredidentifiers = true
--- ClipboardTool.paste_on_select
--- Variable
--- Whether to auto-type the item when selecting it from the menu. Can be toggled on the fly from the chooser. Defaults to `false`.
obj.paste_on_select = getSetting('paste_on_select', false)
--- ClipboardTool.logger
--- Variable
--- Logger object used within the Spoon. Can be accessed to set the default log level for the messages coming from the Spoon.
obj.logger = hs.logger.new('ClipboardTool')
--- ClipboardTool.ignoredIdentifiers
--- Variable
--- Types of clipboard entries to ignore, see http://nspasteboard.org. Code from https://github.com/asmagill/hammerspoon-config/blob/master/utils/_menus/newClipper.lua. Default value (don't modify unless you know what you are doing):
--- ```
--- {
--- ["de.petermaurer.TransientPasteboardType"] = true, -- Transient : Textpander, TextExpander, Butler
--- ["com.typeit4me.clipping"] = true, -- Transient : TypeIt4Me
--- ["Pasteboard generator type"] = true, -- Transient : Typinator
--- ["com.agilebits.onepassword"] = true, -- Confidential : 1Password
--- ["org.nspasteboard.TransientType"] = true, -- Universal, Transient
--- ["org.nspasteboard.ConcealedType"] = true, -- Universal, Concealed
--- ["org.nspasteboard.AutoGeneratedType"] = true, -- Universal, Automatic
--- }
--- ```
obj.ignoredIdentifiers = {
["de.petermaurer.TransientPasteboardType"] = true, -- Transient : Textpander, TextExpander, Butler
["com.typeit4me.clipping"] = true, -- Transient : TypeIt4Me
["Pasteboard generator type"] = true, -- Transient : Typinator
["com.agilebits.onepassword"] = true, -- Confidential : 1Password
["org.nspasteboard.TransientType"] = true, -- Universal, Transient
["org.nspasteboard.ConcealedType"] = true, -- Universal, Concealed
["org.nspasteboard.AutoGeneratedType"] = true, -- Universal, Automatic
}
--- ClipboardTool.deduplicate
--- Variable
--- Whether to remove duplicates from the list, keeping only the latest one. Defaults to `true`.
obj.deduplicate = true
--- ClipboardTool.show_in_menubar
--- Variable
--- Whether to show a menubar item to open the clipboard history. Defaults to `true`
obj.show_in_menubar = true
--- ClipboardTool.menubar_title
--- Variable
--- String to show in the menubar if `ClipboardTool.show_in_menubar` is `true`. Defaults to `"\u{1f4ce}"`, which is the [Unicode paperclip character](https://codepoints.net/U+1F4CE)
obj.menubar_title = "\u{1f4ce}"
----------------------------------------------------------------------
-- Internal variable - Chooser/menu object
obj.selectorobj = nil
-- Internal variable - Cache for focused window to work around the current window losing focus after the chooser comes up
obj.prevFocusedWindow = nil
-- Internal variable - Timer object to look for pasteboard changes
obj.timer = nil
local pasteboard = require("hs.pasteboard") -- http://www.hammerspoon.org/docs/hs.pasteboard.html
local hashfn = require("hs.hash").MD5
-- Keep track of last change counter
local last_change = nil;
-- Array to store the clipboard history
local clipboard_history = nil
-- Internal function - persist the current history so it survives across restarts
function _persistHistory()
setSetting("items",clipboard_history)
end
--- ClipboardTool:togglePasteOnSelect()
--- Method
--- Toggle the value of `ClipboardTool.paste_on_select`
function obj:togglePasteOnSelect()
self.paste_on_select = setSetting("paste_on_select", not self.paste_on_select)
hs.notify.show("ClipboardTool", "Paste-on-select is now " .. (self.paste_on_select and "enabled" or "disabled"), "")
end
function obj:toggleMaxSize()
self.max_size = setSetting("max_size", not self.max_size)
hs.notify.show("ClipboardTool", "Max Size is now " .. (self.max_size and "enabled" or "disabled"), "")
end
-- Internal method - process the selected item from the chooser. An item may invoke special actions, defined in the `actions` variable.
function obj:_processSelectedItem(value)
local actions = {
none = function() end,
clear = hs.fnutils.partial(self.clearAll, self),
toggle_paste_on_select = hs.fnutils.partial(self.togglePasteOnSelect, self),
toggle_max_size = hs.fnutils.partial(self.toggleMaxSize, self),
}
if self.prevFocusedWindow ~= nil then
self.prevFocusedWindow:focus()
end
if value and type(value) == "table" then
if value.action and actions[value.action] then
actions[value.action](value)
elseif value.text then
if value.type == "text" then
pasteboard.setContents(value.text)
elseif value.type == "image" then
pasteboard.writeObjects(hs.image.imageFromURL(value.data))
end
-- self:pasteboardToClipboard(value.text)
if (self.paste_on_select) then
hs.eventtap.keyStroke({"cmd"}, "v")
end
end
last_change = pasteboard.changeCount()
end
end
--- ClipboardTool:clearAll()
--- Method
--- Clears the clipboard and history
function obj:clearAll()
pasteboard.clearContents()
clipboard_history = {}
_persistHistory()
last_change = pasteboard.changeCount()
end
--- ClipboardTool:clearLastItem()
--- Method
--- Clears the last added to the history
function obj:clearLastItem()
table.remove(clipboard_history, 1)
_persistHistory()
last_change = pasteboard.changeCount()
end
-- Internal method: deduplicate the given list, and restrict it to the history size limit
function obj:dedupe_and_resize(list)
local res={}
local hashes={}
for i,v in ipairs(list) do
if #res < self.hist_size then
local hash=hashfn(v.content)
if (not self.deduplicate) or (not hashes[hash]) then
table.insert(res, v)
hashes[hash]=true
end
end
end
return res
end
--- ClipboardTool:pasteboardToClipboard(item)
--- Method
--- Add the given string to the history
---
--- Parameters:
--- * item - string to add to the clipboard history
---
--- Returns:
--- * None
function obj:pasteboardToClipboard(item_type, item)
table.insert(clipboard_history, 1, {type=item_type, content=item})
clipboard_history = self:dedupe_and_resize(clipboard_history)
_persistHistory() -- updates the saved history
end
-- Internal method: actions of the context menu, special paste
function obj:pasteAllWithDelimiter(row, delimiter)
if self.prevFocusedWindow ~= nil then
self.prevFocusedWindow:focus()
end
print("pasteAllWithTab row:" .. row)
for ix = row, 1, -1 do
local entry = clipboard_history[ix]
print("pasteAllWithTab ix:" .. ix .. ":" .. entry)
-- pasteboard.setContents(entry)
-- os.execute("sleep 0.2")
-- hs.eventtap.keyStroke({"cmd"}, "v")
hs.eventtap.keyStrokes(entry.content)
-- os.execute("sleep 0.2")
hs.eventtap.keyStrokes(delimiter)
-- os.execute("sleep 0.2")
end
end
-- Internal method: actions of the context menu, delete or rearrange of clips
function obj:manageClip(row, action)
print("manageClip row:" .. row .. ",action:" .. action)
if action == 0 then
table.remove (clipboard_history, row)
elseif action == 2 then
local i = 1
local j = row
while i < j do
clipboard_history[i], clipboard_history[j] = clipboard_history[j], clipboard_history[i]
i = i + 1
j = j - 1
end
else
local value = clipboard_history[row]
local new = row + action
if new < 1 then new = 1 end
if new < row then
table.move(clipboard_history, new, row - 1, new + 1)
else
table.move(clipboard_history, row + 1, new, row)
end
clipboard_history[new] = value
end
self.selectorobj:refreshChoicesCallback()
end
-- Internal method:
function obj:_showContextMenu(row)
print("_showContextMenu row:" .. row)
point = hs.mouse.getAbsolutePosition()
local menu = hs.menubar.new(false)
local menuTable = {
{ title = "Alle Schnipsel mit Tab einfรผgen", fn = hs.fnutils.partial(self.pasteAllWithDelimiter, self, row, "\t") },
{ title = "Alle Schnipsel mit Zeilenvorschub einfรผgen", fn = hs.fnutils.partial(self.pasteAllWithDelimiter, self, row, "\n") },
{ title = "-" },
{ title = "Eintrag entfernen", fn = hs.fnutils.partial(self.manageClip, self, row, 0) },
{ title = "Eintrag an erste Stelle", fn = hs.fnutils.partial(self.manageClip, self, row, -100) },
{ title = "Eintrag nach oben", fn = hs.fnutils.partial(self.manageClip, self, row, -1) },
{ title = "Eintrag nach unten", fn = hs.fnutils.partial(self.manageClip, self, row, 1) },
{ title = "Tabelle invertieren", fn = hs.fnutils.partial(self.manageClip, self, row, 2) },
{ title = "-" },
{ title = "disabled item", disabled = true },
{ title = "checked item", checked = true },
}
menu:setMenu(menuTable)
menu:popupMenu(point)
print(hs.inspect(point))
end
-- Internal function - fill in the chooser options, including the control options
function obj:_populateChooser()
menuData = {}
for k,v in pairs(clipboard_history) do
if (v.type == "text") then
table.insert(menuData, { text = v.content,
type = v.type})
elseif (v.type == "image") then
table.insert(menuData, { text = "ใImage dataใ",
type = v.type,
data = v.content,
image = hs.image.imageFromURL(v.content)})
end
end
if #menuData == 0 then
table.insert(menuData, { text="",
subText="ใClipboard is emptyใ",
action = 'none',
image = hs.image.imageFromName('NSCaution')})
else
table.insert(menuData, { text="ใClear Clipboard Historyใ",
action = 'clear',
image = hs.image.imageFromName('NSTrashFull') })
end
table.insert(menuData, {
text="ใ" .. (self.paste_on_select and "Disable" or "Enable") .. " Paste-on-selectใ",
action = 'toggle_paste_on_select',
image = (self.paste_on_select and hs.image.imageFromName('NSSwitchEnabledOn') or hs.image.imageFromName('NSSwitchEnabledOff'))
})
table.insert(menuData, {
text="ใ" .. (self.max_size and "Disable" or "Enable") .. " max size " .. self.max_entry_size .. "ใ",
action = 'toggle_max_size',
image = (self.max_size and hs.image.imageFromName('NSSwitchEnabledOn') or hs.image.imageFromName('NSSwitchEnabledOff'))
})
self.logger.df("Returning menuData = %s", hs.inspect(menuData))
return menuData
end
--- ClipboardTool:shouldBeStored()
--- Method
--- Verify whether the pasteboard contents matches one of the values in `ClipboardTool.ignoredIdentifiers`
function obj:shouldBeStored()
-- Code from https://github.com/asmagill/hammerspoon-config/blob/master/utils/_menus/newClipper.lua
local goAhead = true
for i,v in ipairs(hs.pasteboard.pasteboardTypes()) do
if self.ignoredIdentifiers[v] then
goAhead = false
break
end
end
if goAhead then
for i,v in ipairs(hs.pasteboard.contentTypes()) do
if self.ignoredIdentifiers[v] then
goAhead = false
break
end
end
end
return goAhead
end
-- Internal method:
function obj:reduceSize(text)
print(#text .. " ? " .. tostring(max_entry_size))
local endingpos = 3000
local lastLowerPos = 3000
repeat
lastLowerPos = endingpos
_, endingpos = string.find(text, "\n\n", endingpos+1)
print("endingpos:" .. endingpos)
until endingpos > obj.max_entry_size
return string.sub(text, 1, lastLowerPos)
end
--- ClipboardTool:checkAndStorePasteboard()
--- Method
--- If the pasteboard has changed, we add the current item to our history and update the counter
function obj:checkAndStorePasteboard()
now = pasteboard.changeCount()
if (now > last_change) then
if (not self.honor_ignoredidentifiers) or self:shouldBeStored() then
current_clipboard = pasteboard.getContents()
self.logger.df("current_clipboard = %s", tostring(current_clipboard))
if (current_clipboard == nil) and (pasteboard.readImage() ~= nil) then
current_clipboard = pasteboard.readImage()
self:pasteboardToClipboard("image", current_clipboard:encodeAsURLString())
if self.show_copied_alert then
hs.alert.show("Copied image")
end
self.logger.df("Adding image (hashed) %s to clipboard history clipboard", hashfn(current_clipboard:encodeAsURLString()))
elseif current_clipboard ~= nil then
local size = #current_clipboard
if obj.max_size and size > obj.max_entry_size then
local answer = hs.dialog.blockAlert("Clipboard", "The maximum size of " .. obj.max_entry_size .. " was exceeded.", "Copy partially", "Copy all", "NSCriticalAlertStyle")
print("answer: " .. answer)
if answer == "Copy partially" then
current_clipboard = self:reduceSize(current_clipboard)
size = #current_clipboard
end
end
if self.show_copied_alert then
hs.alert.show("Copied " .. size .. " chars")
end
self.logger.df("Adding %s to clipboard history", current_clipboard)
self:pasteboardToClipboard("text", current_clipboard)
else
self.logger.df("Ignoring nil clipboard content")
end
else
self.logger.df("Ignoring pasteboard entry because it matches ignoredIdentifiers")
end
last_change = now
end
end
--- ClipboardTool:start()
--- Method
--- Start the clipboard history collector
function obj:start()
obj.logger.level = 0
clipboard_history = self:dedupe_and_resize(getSetting("items", {})) -- If no history is saved on the system, create an empty history
last_change = pasteboard.changeCount() -- keeps track of how many times the pasteboard owner has changed // Indicates a new copy has been made
self.selectorobj = hs.chooser.new(hs.fnutils.partial(self._processSelectedItem, self))
self.selectorobj:choices(hs.fnutils.partial(self._populateChooser, self))
self.selectorobj:rightClickCallback(hs.fnutils.partial(self._showContextMenu, self))
--Checks for changes on the pasteboard. Is it possible to replace with eventtap?
self.timer = hs.timer.new(self.frequency, hs.fnutils.partial(self.checkAndStorePasteboard, self))
self.timer:start()
if self.show_in_menubar then
self.menubaritem = hs.menubar.new()
:setTitle(obj.menubar_title)
:setClickCallback(hs.fnutils.partial(self.toggleClipboard, self))
end
end
--- ClipboardTool:showClipboard()
--- Method
--- Display the current clipboard list in a chooser
function obj:showClipboard()
if self.selectorobj ~= nil then
self.selectorobj:refreshChoicesCallback()
self.prevFocusedWindow = hs.window.focusedWindow()
self.selectorobj:show()
else
hs.notify.show("ClipboardTool not properly initialized", "Did you call ClipboardTool:start()?", "")
end
end
--- ClipboardTool:toggleClipboard()
--- Method
--- Show/hide the clipboard list, depending on its current state
function obj:toggleClipboard()
if self.selectorobj:isVisible() then
self.selectorobj:hide()
else
self:showClipboard()
end
end
--- ClipboardTool:bindHotkeys(mapping)
--- Method
--- Binds hotkeys for ClipboardTool
---
--- Parameters:
--- * mapping - A table containing hotkey objifier/key details for the following items:
--- * show_clipboard - Display the clipboard history chooser
--- * toggle_clipboard - Show/hide the clipboard history chooser
function obj:bindHotkeys(mapping)
local def = {
show_clipboard = hs.fnutils.partial(self.showClipboard, self),
toggle_clipboard = hs.fnutils.partial(self.toggleClipboard, self),
}
hs.spoons.bindHotkeysToSpec(def, mapping)
obj.mapping = mapping
end
return obj
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.