content
stringlengths 5
1.05M
|
|---|
function cAPI.RequestModel(hash)
hash = tonumber(hash)
if not IsModelValid(hash) then
return
end
if not HasModelLoaded(hash) then
RequestModel(hash)
while not HasModelLoaded(hash) do
Citizen.Wait(10)
end
end
end
function cAPI.RequestAnimDict(dictionary)
if not HasAnimDictLoaded(dictionary) then
RequestAnimDict(dictionary)
while not HasAnimDictLoaded(dictionary) do
Citizen.Wait(10)
end
end
end
function cAPI.InFade(timer)
DoScreenFadeOut(timer)
while IsScreenFadingOut() do
Citizen.Wait(1)
end
end
function cAPI.OutFade(timer)
ShutdownLoadingScreen()
DoScreenFadeIn(timer)
while IsScreenFadingIn() do
Citizen.Wait(1)
end
end
-- {x, y, z}
-- function cAPI.SkyCameraAtCoords(coords)
-- local cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", 621.67, 374.08, 873.24, 300.00, 0.00, 0.00, 100.00, false, 0) -- CAMERA COORDS
-- PointCamAtCoord(cam, coords[1], coords[2], coords[3] + 200)
-- SetCamActive(cam, true)
-- cAPI.EndFade(500)
-- RenderScriptCams(true, false, 1, true, true)
-- return cam
-- end
function cAPI.PlaySkyCameraAnimationAtCoords(coords)
local vecPosition = vec3(coords[1], coords[2], coords[3])
RequestCollisionAtCoord(vecPosition)
local cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", 621.67, 374.08, 873.24, 300.00, 0.00, 0.00, 100.00, false, 0) -- CAMERA COORDS
PointCamAtCoord(cam, vecPosition.xy, vecPosition.z + 200)
SetCamActive(cam, true)
local cam3 = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", vecPosition.xy, vecPosition.z + 200, 300.00, 0.00, 0.00, 100.00, false, 0)
PointCamAtCoord(cam3, vecPosition.xy, vecPosition.z + 200)
SetCamActiveWithInterp(cam3, cam, 8000, true, true)
Citizen.Wait(8000)
cam2 = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", coords[1], coords[2], coords[3] + 200, 300.00, 0.00, 0.00, 100.00, false, 0)
PointCamAtCoord(cam2, vecPosition.xy, vecPosition.z + 2)
SetCamActiveWithInterp(cam2, cam3, 5000, true, true)
RenderScriptCams(false, true, 500, true, true)
local _, groundZ, normal = GetGroundZAndNormalFor_3dCoord(vecPosition.x, vecPosition.y, vecPosition.z)
if _ then
vecPosition = vec3(vecPosition.xy, groundZ)
end
SetEntityCoords(PlayerPedId(), vecPosition)
Citizen.Wait(5000)
DestroyAllCams(true)
end
|
local friendMainLayout = require(ViewPath.."hall/community/friend/friendMainLayout");
local community_pin_map = require("qnFiles/qnPlist/hall/community_pin")
local FriendMainLayout = class(CommonGameLayer,false);
local h_index = 0;
local getIndex = function(self)
h_index = h_index + 1;
return h_index;
end
FriendMainLayout.currentLayout =
{
FRIEND = "friendRankLayout",
KNOW = "knowLayout",
NEARBY = "nearByLayout",
}
FriendMainLayout.s_controls = {
tabFriendRank = getIndex();
tabKnow = getIndex();
tabNearby = getIndex();
addFriendBtn = getIndex();
contentView = getIndex();
}
FriendMainLayout.ctor = function(self)
super(self, friendMainLayout);
self:setSize( self.m_root:getSize() );
self.m_ctrls = FriendMainLayout.s_controls;
self.m_clockHandle = Clock.instance():schedule_once(function()
self:__init();
end)
end
FriendMainLayout.dtor = function(self)
self.m_clockHandle:cancel();
self.m_clockHandle = nil;
end
FriendMainLayout.__init = function (self)
self:onTabFriendRankBtnClick();
end
FriendMainLayout.onTabFriendRankBtnClick = function(self)
UBReport.getInstance():report(UBConfig.kHallCommunityRank);
self:__setTabSelect(self.m_ctrls.tabFriendRank);
self.m_friendRankView = self:__addLayerToCenterView(self.m_friendRankView, require("hall/community/widget/friend/friendList/communityRankLayer"))
if self.m_currentLayout ~= FriendMainLayout.currentLayout.FRIEND then
Toast.getInstance():hidden();
LoadingView.getInstance():hidden();
self.m_friendRankView:show();
self.m_currentLayout = FriendMainLayout.currentLayout.FRIEND;
end
CommunityDataInterface.getInstance():setFriendRankLayout(self.m_currentLayout);
end
FriendMainLayout.onTabKnowBtnClick = function(self)
UBReport.getInstance():report(UBConfig.kHallCommunityKnow);
self:__setTabSelect(self.m_ctrls.tabKnow);
self.m_knowView = self:__addLayerToCenterView(self.m_knowView, require("hall/community/widget/friend/knowList/communityKnowLayer"));
if self.m_currentLayout ~= FriendMainLayout.currentLayout.KNOW then
Toast.getInstance():hidden();
LoadingView.getInstance():hidden();
self.m_knowView:show();
self.m_currentLayout = FriendMainLayout.currentLayout.KNOW;
end
CommunityDataInterface.getInstance():setFriendRankLayout(self.m_currentLayout);
end
FriendMainLayout.onTabNearbyBtnClick = function(self)
UBReport.getInstance():report(UBConfig.kHallCommunityNearby);
self:__setTabSelect(self.m_ctrls.tabNearby);
self.m_nearByView = self:__addLayerToCenterView(self.m_nearByView, require("hall/community/widget/friend/nearbyList/communityNearByLayer"));
if self.m_currentLayout ~= FriendMainLayout.currentLayout.NEARBY then
Toast.getInstance():hidden();
LoadingView.getInstance():hidden();
self.m_nearByView:show();
self.m_currentLayout = FriendMainLayout.currentLayout.NEARBY;
end
CommunityDataInterface.getInstance():setFriendRankLayout(self.m_currentLayout);
end
FriendMainLayout.show = function (self)
CommunityDataInterface.getInstance():setFriendRankLayout(self.m_currentLayout);
if self.m_currentLayout == FriendMainLayout.currentLayout.FRIEND then
self.m_friendRankView:show();
elseif self.m_currentLayout == FriendMainLayout.currentLayout.KNOW then
self.m_knowView:show();
elseif self.m_currentLayout == FriendMainLayout.currentLayout.NEARBY then
self.m_nearByView:show();
end
end
FriendMainLayout.__addLayerToCenterView = function(self, memberName, layerClass)
if not memberName then
memberName = new(layerClass);
memberName:setFillParent(true, true);
self:findViewById(self.m_ctrls.contentView):addChild(memberName);
memberName:setDelegate(self);
end
return memberName;
end
--设置tab选中状态
FriendMainLayout.__setTabSelect = function(self, selectTabId)
local tabs = { self.m_ctrls.tabFriendRank,
self.m_ctrls.tabKnow,
self.m_ctrls.tabNearby,
};
local images = {
"tab_friendRank_selected.png","tab_friendRank_select.png",
"tab_know_selected.png","tab_know_select.png",
"tab_nearby_selected.png","tab_nearby_select.png",
};
local views = {
self.m_friendRankView,
self.m_knowView,
self.m_nearByView,
}
for index, tabId in pairs(tabs) do
local tab = self:findViewById(tabId);
local isSelect = tabId == selectTabId;
local imageTitle = isSelect and community_pin_map[images[2*index-1]] or community_pin_map[images[2*index]];
local imageTab = isSelect and community_pin_map["tab_selected.png"] or community_pin_map["tab_selcet.png"];
tab:getChildByName("tab"):setFile(imageTab);
tab:getChildByName("tab"):getChildByName("title"):setFile(imageTitle);
if views[index] then
views[index]:setVisible(isSelect);
end
end
end
FriendMainLayout.onAddFriendBtnClick = function (self)
UBReport.getInstance():report(UBConfig.kHallCommunitySearchAdd);
self:__onShowAddFriendLayout();
end
FriendMainLayout.__onShowAddFriendLayout = function(self)
IBaseDialog.remove("CommunityAddFriendLayer");
IBaseDialog.pushDialog(new(require("hall/community/widget/friend/friendList/communityAddFriendLayer")));
end
FriendMainLayout.s_controlConfig = {
[FriendMainLayout.s_controls.tabFriendRank] = {"topTabView", "tabFriendRank"};
[FriendMainLayout.s_controls.tabKnow] = {"topTabView", "tabKnow"};
[FriendMainLayout.s_controls.tabNearby] = {"topTabView", "tabNearby"};
[FriendMainLayout.s_controls.addFriendBtn] = {"topTabView", "btnAddFriend"};
[FriendMainLayout.s_controls.contentView] = {"centerView", "contentView"};
}
FriendMainLayout.s_controlFuncMap = {
[FriendMainLayout.s_controls.tabFriendRank] = FriendMainLayout.onTabFriendRankBtnClick;
[FriendMainLayout.s_controls.tabKnow] = FriendMainLayout.onTabKnowBtnClick;
[FriendMainLayout.s_controls.tabNearby] = FriendMainLayout.onTabNearbyBtnClick;
[FriendMainLayout.s_controls.addFriendBtn] = FriendMainLayout.onAddFriendBtnClick;
}
return FriendMainLayout;
|
#!/usr/bin/env lua
if ... then
module(..., package.seeall)
end
if not ... then
print('Hello World!')
end
|
local otherfile = require("otherfile")
local util = require("util")
local subdirfile = require("subdir.subdirfile")
local othersubdirfile = require("subdir.othersubdirfile")
local subsubdirfile = require("subdir.subsubdir.subsubdirfile")
return {
otherFileFromDependency1 = otherfile.someFunc,
callUtil = function()
return util.utilf()
end,
otherFileUtil = otherfile.callUtil,
subdirfileResult = subdirfile.subdirfileResult,
othersubdirfileResult = othersubdirfile.othersubdirfileResult,
subsubdirfileResult = subsubdirfile.subsubresult
}
|
local fi = data.raw["item-group"]["food-industry"]
if fi == nil then
data:extend({
{
type = "autoplace-control",
category = "resource",
name = "food-plant",
order = "w",
richness = false,
},
{
type = "fuel-category",
name = "plant",
},
{
type = "fuel-category",
name = "humus"
},
{
type = "item",
name = "fertilizer",
icon = "__Colonists__/graphics/icons/items/fertilizer.png",
icon_size = 32,
flags = {"goes-to-main-inventory"},
subgroup = "colonists-food-items",
order = "w-b-g",
stack_size = 50
},
{
type = "recipe",
name = "fertilizer-from-waste",
category = "chemistry",
energy_required = 3,
ingredients =
{
{type="fluid", name="waste", amount=10}
},
results=
{
{type="item", name="fertilizer", amount=1}
},
icon = "__Colonists__/graphics/icons/items/fertilizer.png",
icon_size = 32,
subgroup="colonists-waste",
enabled = false,
order = "b[fluid-chemistry]-c[solid-fuel-from-light-oil]",
crafting_machine_tint =
{
primary = {r = 0.270, g = 0.122, b = 0.000, a = 0.000}, -- #441f0000
secondary = {r = 0.735, g = 0.546, b = 0.325, a = 0.000}, -- #bb8b5200
tertiary = {r = 0.610, g = 0.348, b = 0.000, a = 0.000}, -- #9b580000
}
},
{
type = "technology",
name = "frying",
icon = "__Colonists__/graphics/technology/frying.png",
icon_size = 128,
prerequisites = {},
effects =
{
},
unit =
{
time = 20,
count = 30,
ingredients =
{
{"science-pack-1", 1}
},
},
order = "w",
},
{
type = "technology",
name = "complex-foods",
icon = "__Colonists__/graphics/technology/complex-foods.png",
icon_size = 128,
prerequisites = {},
effects =
{
},
unit =
{
time = 60,
count = 200,
ingredients =
{
{"science-pack-1", 1},
},
},
order = "w",
},
})
end
|
commandArray = {}
if devicechanged['Bathroom Motion'] == 'On' then
if timeofday['Nighttime'] == true then
commandArray['Bathroom Lights'] = 'On'
end
else
commandArray['Bathroom Lights'] = 'Off'
end
return commandArray
|
require('actors/Module.lua')
Weapon = class('Weapon', Module)
function Weapon:initialize(centerX, centerY, coolDown, projectileClass, quad, source)
super.initialize(self, centerX, centerY, quad)
self.coolDown = coolDown
self.projectileClass = projectileClass
self.source = source
end
function Weapon:fire()
local velX, velY = self:getLinearVelocity()
local x,y=self:getPosition()
local angle = self:getAngle()
self.projectileClass:new(x,y,velX,velY,angle,self:getGroupIndex(),self.quadTree)
passion.audio.play(self.source)
self:pushState('CoolingDown')
end
-- The weapon enters this state after firing
CoolingDown = Weapon:addState('CoolingDown')
function CoolingDown:enterState()
self:after(self.coolDown, 'popState')
end
function CoolingDown:fire() end -- do nothing
|
require "levelprops/triggers/floorbutton"
FloorButtonPeter = FloorButton:extend("FloorButtonPeter")
function FloorButtonPeter:new(...)
FloorButtonPeter.super.new(self, ...)
self:setImage("levelprops/triggers/button", 8)
self.anim:add("down", 8)
self.anim:add("up", 7)
end
function FloorButtonPeter:onOverlap(e, mine, his)
if not e:is(Peter) and not e:is(Tile) and not e.carryingPeter then
return
end
return FloorButtonPeter.super.onOverlap(self, e, mine, his)
end
|
local Countermeasures = ACF.Classes.Countermeasures
ACFM_Flares = {}
ACFM_FlareUID = 0
local Bullets = ACF.Bullets
function ACFM_RegisterFlare(BulletData)
BulletData.FlareUID = ACFM_FlareUID
ACFM_Flares[BulletData.Index] = ACFM_FlareUID
ACFM_FlareUID = ACFM_FlareUID + 1
local FlareObj = Countermeasures.Flare()
FlareObj:Configure(BulletData)
BulletData.FlareObj = FlareObj
ACFM_OnFlareSpawn(BulletData)
end
function ACFM_UnregisterFlare(BulletData)
local FlareObj = BulletData.FlareObj
if FlareObj then
FlareObj.Flare = nil
end
ACFM_Flares[BulletData.Index] = nil
end
function ACFM_OnFlareSpawn(BulletData)
local FlareObj = BulletData.FlareObj
local Missiles = FlareObj:ApplyToAll()
for Missile in pairs(Missiles) do
Missile.GuidanceData.Override = FlareObj
end
end
function ACFM_GetFlaresInCone(Position, Direction, Degrees)
local Result = {}
for Index, UID in pairs(ACFM_Flares) do
local Flare = Bullets[Index]
if not (Flare and Flare.FlareUID and Flare.FlareUID == UID) then
continue
end
if ACFM_ConeContainsPos(Position, Direction, Degrees, Flare.Pos) then
Result[Flare] = true
end
end
return Result
end
function ACFM_GetAnyFlareInCone(Position, Direction, Degrees)
for Index, UID in pairs(ACFM_Flares) do
local Flare = Bullets[Index]
if not (Flare and Flare.FlareUID and Flare.FlareUID == UID) then
continue
end
if ACFM_ConeContainsPos(Position, Direction, Degrees, Flare.Pos) then
return Flare
end
end
end
function ACFM_GetMissilesInCone(Position, Direction, Degrees)
local Result = {}
for Missile in pairs(ACF.ActiveMissiles) do
if not IsValid(Missile) then
continue
end
if ACFM_ConeContainsPos(Position, Direction, Degrees, Missile:GetPos()) then
Result[Missile] = true
end
end
return Result
end
function ACFM_GetMissilesInSphere(Position, Radius)
local Result = {}
local RadiusSqr = Radius * Radius
for Missile in pairs(ACF.ActiveMissiles) do
if not IsValid(Missile) then
continue
end
if Position:DistToSqr(Missile:GetPos()) <= RadiusSqr then
Result[Missile] = true
end
end
return Result
end
-- Tests flare distraction effect upon all undistracted missiles, but does not perform the effect itself. Returns a list of potentially affected missiles.
-- argument is the bullet in the acf bullet table which represents the flare - not the cm_flare object!
function ACFM_GetAllMissilesWhichCanSee(Position)
local Result = {}
for Missile in pairs(ACF.ActiveMissiles) do
local Guidance = Missile.GuidanceData
if not Guidance or Guidance.Override or not Guidance.ViewCone then
continue
end
if ACFM_ConeContainsPos(Missile:GetPos(), Missile:GetForward(), Guidance.ViewCone, Position) then
Result[Missile] = true
end
end
return Result
end
function ACFM_ConeContainsPos(ConePos, ConeDir, Degrees, Position)
local MinimumDot = math.cos(math.rad(Degrees))
local Direction = (Position - ConePos):GetNormalized()
return ConeDir:Dot(Direction) >= MinimumDot
end
function ACFM_ApplyCountermeasures(Missile, Guidance)
if Guidance.Override then return end
for _, CounterMeasure in pairs(Countermeasures) do
if not CounterMeasure.ApplyContinuous then
continue
end
if ACFM_ApplyCountermeasure(Missile, Guidance, CounterMeasure) then
break
end
end
end
function ACFM_ApplySpawnCountermeasures(Missile, Guidance)
if Guidance.Override then return end
for _, CounterMeasure in pairs(Countermeasures) do
if CounterMeasure.ApplyContinuous then
continue
end
if ACFM_ApplyCountermeasure(Missile, Guidance, CounterMeasure) then
break
end
end
end
function ACFM_ApplyCountermeasure(Missile, Guidance, CounterMeasure)
if not CounterMeasure.AppliesTo[Guidance.Name] then return end
local Override = CounterMeasure.ApplyAll(Missile, Guidance)
if Override then
Guidance.Override = Override
return true
end
end
|
-- ======================================================================
-- Report Repair
-- Advent of Code 2020 Day 01 -- Eric Wastl -- https://adventofcode.com
--
-- lua implementation by Dr. Dean Earl Wright III
-- ======================================================================
-- ======================================================================
-- r e p o r t . l u a
-- ======================================================================
-- "A solver for the Advent of Code 2020 Day 01 puzzle"
-- ----------------------------------------------------------------------
-- local
-- ----------------------------------------------------------------------
local Report = {}
-- ----------------------------------------------------------------------
-- constants
-- ----------------------------------------------------------------------
-- ======================================================================
-- Report
-- ======================================================================
-- "Object for Report Repair"
function Report:Report (o)
-- 1. Set the initial values
o = o or {}
o.part2 = o.part2 or false
o.text = o.text or {}
o.numbers = {}
-- 2. Create the object metatable
self.__index = self
setmetatable(o, self)
-- 3. Process text (if any)
if o.text ~= nil and #o.text > 0 then
o:_process_text(o.text)
end
-- 4. Return the populated object
return o
end
function Report:_process_text(text)
-- "Assign values from text
-- 0. Precondition axioms
assert(text ~= nil and #text > 0)
-- 1. Loop for each line of the text
for _, line in ipairs(text) do
-- 2. Add the number to the entries
table.insert(self.numbers, tonumber(line))
end
end
function Report:get_pair(total)
-- "Get a pair of numbers that add to the total"
for _, num in ipairs(self.numbers) do
need = total - num
for _, other in ipairs(self.numbers) do
if other == need and other ~= num then
return num, other
end
end
end
return nil, nil
end
function Report:get_trio(total)
-- "Get a trio of numbers that add to the total"
for _, num in ipairs(self.numbers) do
need = total - num
p1, p2 = self:get_pair(need)
if p1 ~= nil then
return num, p1, p2
end
end
return nil, nil, nil
end
function Report:part_one(args)
-- "Returns the solution for part one"
-- 0. Precondition axioms
local verbose = args.verbose or false
local limit = args.limit or 0
assert(verbose == true or verbose == false)
assert(limit >= 0)
-- 1. Return the solution for part one
n1, n2 = self:get_pair(2020)
if n1 == nil then
return nil
end
return n1 * n2
end
function Report:part_two(args)
-- "Returns the solution for part two"
-- 0. Precondition axioms
local verbose = args.verbose or false
local limit = args.limit or 0
assert(verbose == true or verbose == false)
assert(limit >= 0)
-- 1. Return the solution for part one
n1, n2, n3 = self:get_trio(2020)
if n1 == nil then
return nil
end
return n1 * n2 * n3
end
-- ----------------------------------------------------------------------
-- module initialization
-- ----------------------------------------------------------------------
return Report
-- ======================================================================
-- end r e p o r t . l u a end
-- ======================================================================
|
local M = {}
M.actions = require('lib.actions')
M.open = require("lib.telescope").open
M.setup = function(opts) require('config').setup(opts) end
return M
|
object_tangible_food_foraged_foraged_fruit_s4_generic = object_tangible_food_foraged_shared_foraged_fruit_s4_generic:new {
}
ObjectTemplates:addTemplate(object_tangible_food_foraged_foraged_fruit_s4_generic, "object/tangible/food/foraged/foraged_fruit_s4_generic.iff")
|
local rq_sliders = require('cokeline/sliders')
local rq_utils = require('cokeline/utils')
local vim_echo = vim.api.nvim_echo
local vim_tbl_islist = vim.tbl_islist
local defaults = {
show_if_buffers_are_at_least = 1,
buffers = {
filter_valid = false,
filter_visible = false,
new_buffers_position = 'last',
},
mappings = {
cycle_prev_next = true,
},
rendering = {
max_buffer_width = 999,
slider = rq_sliders.center_current_buffer,
left_sidebar = false,
right_sidebar = false,
},
---@type table<string, Hl>
default_hl = {
focused = {
fg = rq_utils.get_hex('ColorColumn', 'bg'),
bg = rq_utils.get_hex('Normal', 'fg'),
style = 'NONE',
},
unfocused = {
fg = rq_utils.get_hex('Normal', 'fg'),
bg = rq_utils.get_hex('ColorColumn', 'bg'),
style = 'NONE',
},
},
---@type Cmp[]
components = {
{
text = function(buffer) return ' ' .. buffer.devicon.icon end,
hl = {
fg = function(buffer) return buffer.devicon.color end,
},
},
{
text = function(buffer) return buffer.unique_prefix end,
hl = {
fg = rq_utils.get_hex('Comment', 'fg'),
style = 'italic',
},
},
{
text = function(buffer) return buffer.filename .. ' ' end,
},
{
text = '',
delete_buffer_on_left_click = true,
},
{
text = ' ',
}
},
}
---Formats an error message.
---@param msg string
local echoerr = function(msg)
vim_echo({{('[nvim-cokeline]: %s'):format(msg), 'ErrorMsg'}}, true, {})
end
---Updates the `settings` table with options from `preferences`, printing an
---error message if a configuration option in `preferences` is not defined in
---`settings`.
---@param settings table
---@param preferences table
---@param key string | nil
---@return table
local update
update = function(settings, preferences, key)
local updated = settings
for k, v in pairs(preferences) do
local key_tree = key and ('%s.%s'):format(key, k) or k
if settings[k] == nil then
echoerr(('Configuration option "%s" does not exist!'):format(key_tree))
else
updated[k] =
(type(v) == 'table' and not vim_tbl_islist(v) and not k:find('sidebar'))
and update(settings[k], v, key_tree)
or v
end
end
return updated
end
return {
update = function(preferences)
return update(defaults, preferences)
end,
}
|
---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
-- * (c) Maildir Biff Widget, Fredrik Ax
---------------------------------------------------
-- {{{ Grab environment
local io = { popen = io.popen }
local setmetatable = setmetatable
local helpers = require("vicious.helpers")
-- }}}
-- Mdir: provides the number of new and unread messages in Maildir structures/dirs
-- vicious.widgets.mdir
local mdir_all = {}
-- {{{ Maildir widget type
local function worker(format, warg)
if not warg then return end
-- Initialize counters
local count = { new = 0, cur = 0 }
for i=1, #warg do
quoted_path = helpers.shellquote(warg[i])
-- Recursively find new messages
local f = io.popen("find "..quoted_path.." -type f -wholename '*/new/*'")
for line in f:lines() do count.new = count.new + 1 end
f:close()
-- Recursively find "old" messages lacking the Seen flag
local f = io.popen("find "..quoted_path.." -type f -regex '.*/cur/.*2,[^S]*$'")
for line in f:lines() do count.cur = count.cur + 1 end
f:close()
end
return {count.new, count.cur}
end
-- }}}
return setmetatable(mdir_all, { __call = function(_, ...) return worker(...) end })
|
function gui_tick()
spr(18, 0, 152)
write(player_coins, 0xffffff, 9, 153)
spr(19, 152, 152)
write(player_seeds, 0xffffff, 151 - string.len(player_seeds) * 6 + 1, 153)
end
|
version = "v0.3-beta5.2"
|
local M = {}
M.setup = function()
local map = vim.api.nvim_set_keymap
local opts = {noremap = true, silent = true}
-- Buffer
map('n', 'dx', ':SoupBufDel<CR>', opts)
map('n', 'dX', ':SoupBufDel!<CR>', opts)
map('n', 'gb', ':SoupBufGoto<CR>', opts)
map('n', '[b', ':SoupBufPrev<CR>', opts)
map('n', ']b', ':SoupBufNext<CR>', opts)
-- Misc
map('n', '].', ':setl list!<CR>', opts)
map('n', '];', ':noh<CR>', opts)
-- Tab
map('n', 'dc', ':SoupTabClose<CR>', opts)
map('n', '[t', ':SoupTabPrevious<CR>', opts)
map('n', ']t', ':SoupTabNext<CR>', opts)
end
return M
|
--[[
Create a copy of a list where each value is transformed by `callback`
]]
local function map(list, callback)
local new = {}
for i = 1, #list do
new[i] = callback(list[i], i)
end
return new
end
return map
|
local dev = require("eden.core.pack").dev
local M = {}
M.plugins = {
-- Language Servers ---------------------------------------------------------
{
"neovim/nvim-lspconfig",
config = function()
require("eden.modules.protocol.lsp")
end,
requires = {
"williamboman/nvim-lsp-installer",
"nvim-lua/lsp_extensions.nvim",
"ray-x/lsp_signature.nvim",
"nvim-lua/lsp-status.nvim",
},
},
{
"weilbith/nvim-code-action-menu",
cmd = "CodeActionMenu",
},
-- Debug Adaptor ------------------------------------------------------------
{
"mfussenegger/nvim-dap",
config = function()
require("eden.modules.protocol.dap")
end,
requires = {
"theHamsta/nvim-dap-virtual-text",
"rcarriga/nvim-dap-ui",
"jbyuki/one-small-step-for-vimkind",
},
},
-- Treesitter ---------------------------------------------------------------
{
{
"nvim-treesitter/nvim-treesitter",
run = ":TSUpdate",
config = function()
require("eden.modules.protocol.treesitter")
end,
requires = {
{ "romgrk/nvim-treesitter-context", opt = true, disabled = not edn.platform.is_windows },
{ "JoosepAlviste/nvim-ts-context-commentstring", opt = true },
{ "nvim-treesitter/nvim-treesitter-textobjects", opt = true },
{ "windwp/nvim-ts-autotag", opt = true },
},
},
{
"nvim-treesitter/playground",
cmd = { "TSPlaygroundToggle", "TSHighlightCapturesUnderCursor" },
},
{
"code-biscuits/nvim-biscuits",
after = "nvim-treesitter",
config = function()
require("nvim-biscuits").setup({
cursor_line_only = true,
})
edn.keymap("<leader>tb", function()
require("nvim-biscuits").toggle_biscuits()
end)
end,
},
},
}
return M
|
--[[
TTT Role Counter -> Base (ServerSide)
by Tassilo (https://github.com/TASSIA710)
--]]
-- Add network strings
util.AddNetworkString("TTTRoleCounter_NotifyStart")
util.AddNetworkString("TTTRoleCounter_NotifyLeave")
-- == Hook: TTTBeginRound == --
hook.Add("TTTBeginRound", "TTTRoleCounter_TTTBeginRound", function()
-- 1 second delay to allow last minute changes to roles via 3rd party addons
timer.Simple(1, function()
local innocents = 0
local traitors = 0
local detectives = 0
for _, ply in pairs(player.GetAll()) do
if ply:GetRole() == ROLE_TRAITOR then
traitors = traitors + 1
elseif ply:GetRole() == ROLE_DETECTIVE then
detectives = detectives + 1
else
innocents = innocents + 1
end
end
net.Start("TTTRoleCounter_NotifyStart")
net.WriteUInt(innocents, 8)
net.WriteUInt(traitors, 8)
net.WriteUInt(detectives, 8)
net.Broadcast()
end)
end)
-- == Hook: TTTBeginRound == --
-- == Hook: PlayerDisconnected == --
hook.Add("PlayerDisconnected", "TTTRoleCounter_PlayerDisconnected", function(ply)
-- Ignore if round is not active
if GetRoundState() ~= ROUND_ACTIVE then return end
-- Ignore if player was not alive (and ensure compatibility with SpecDM)
if ply.IsGhost then
if not ply:Alive() or ply:IsGhost() then return end
else
if not ply:Alive() then return end
end
-- Broadcast notification
net.Start("TTTRoleCounter_NotifyLeave")
net.WriteUInt(ply:GetRole(), 8)
net.Broadcast()
end)
-- == Hook: PlayerDisconnected == --
|
return Def.ActorFrame{
Def.BitmapText{
Font= "Common Normal", InitCommand= function(self)
self:xy(_screen.cx, _screen.cy):diffuse(fetch_color("text"))
:strokecolor(fetch_color("stroke")):wrapwidthpixels(_screen.w-32)
:settext(
"Online mode is not supported.\n" ..
"Choose a different theme to play online mode.\n" ..
"Porting my music wheel to work in online mode would probably " ..
"require a ton of work and I never play online mode.")
:sleep(10):queuecommand("ChangeScreen")
end,
ChangeScreenCommand= function(self)
trans_new_screen("ScreenAppearanceOptions")
end
}
}
|
VERY_LOW_INT = -99999999
VERY_HIGH_INT = 99999999
ABILITY_STANDARD = 0
ABILITY_PUSH = 1
ABILITY_QUEUE = 2
WARD_OBSERVER = "item_ward_observer"
WARD_SENTRY = "item_ward_sentry"
WARD_DISPENSER = "item_ward_dispenser"
|
local AreEqual, Exists, Replace, IsTrue, IsFalse
local CustomEventTrigger = "CAERDON_PLATE_TESTS_DATA_LOADED"
local Tests
local frame
if IsAddOnLoaded("WoWUnit") then
frame = CreateFrame("frame")
AreEqual, Exists, Replace, IsTrue, IsFalse = WoWUnit.AreEqual, WoWUnit.Exists, WoWUnit.Replace, WoWUnit.IsTrue, WoWUnit.IsFalse
Tests = WoWUnit("Plate Tests", CustomEventTrigger)
frame:RegisterEvent "PLAYER_LOGIN"
frame:SetScript("OnEvent", function(this, event, ...)
if event == "PLAYER_LOGIN" then
local continuableContainer = ContinuableContainer:Create();
-- continuableContainer:AddContinuable(CaerdonItem:CreateFromItemLink("|cff1eff00|Hitem:68751::::::::60:581:::1:6654:2:9:15:28:73:::|h[Imbued Pioneer Bracers]|h|r"));
continuableContainer:ContinueOnLoad(function()
WoWUnit:OnEvent(CustomEventTrigger)
end);
end
end)
else
Tests = {}
end
local beforeTestValue
function Tests:BeforeEach()
beforeTestValue = CaerdonWardrobeConfig.Debug.Enabled
CaerdonWardrobeConfig.Debug.Enabled = true
end
function Tests:AfterEach()
CaerdonWardrobeConfig.Debug.Enabled = beforeTestValue
beforeTestValue = nil
end
|
--[[
@url https://github.com/ConnorWiseman/cannibalism
--]]
eventful = require 'plugins.eventful'
function trim(str)
return str:match'^%s*(.*%S)' or ''
end
eventful.enableEvent(eventful.eventType.UNIT_DEATH, 1)
eventful.onUnitDeath.death_monitor = function(unit_id)
if not dfhack.isWorldLoaded() then
return
end
local unit = df.unit.find(unit_id)
if not unit then
return
end
if not dfhack.units.isDwarf(unit) then
return
end
local unit_name = trim(dfhack.TranslateName(dfhack.units.getVisibleName(unit)))
print("Cannibalism: "..unit_name.." has died!")
for _, part in pairs(df.global.world.items.other.ANY_CORPSE) do
if part.unit_id == unit_id then
if part.flags.dead_dwarf == true then
print("Cannibalism: setting "..unit_name.."'s dead_dwarf flag to false.")
part.flags.dead_dwarf = false
end
end
end
end
print "Cannibalism: mod enabled."
|
effect = body:new {
size = 3,
__type = 'effect',
bodies = {}
}
function effect:draw()
graphics.setColor(color(self.variance + colortimer.time, self.alpha or self.alphafollows and self.alphafollows.var, self.coloreffect))
graphics.rectangle(self.mode, self.x, self.y, self.size, self.size)
end
function effect:update(dt)
self.position:add(self.speed * dt)
self.etc = self.etc + dt
self.delete = self.etc > self.timetogo
end
function neweffects( based_on, times)
--local speedinfluence = based_on.speed * .6
if #effect.bodies > 200 then times = times / 2 end
if #effect.bodies > 1000 then
local n = #effect.bodies
for i = 0, 200 do
effect.bodies[math.random(n)] = nil
end
end
for i = 1,times do
local e = effect:new{
position = based_on.position + {based_on.size * (2 * math.random() - 1),based_on.size * (2 * math.random() - 1)},
variance = based_on.variance,
coloreffect = based_on.coloreffect,
alpha = based_on.alpha,
alphafollows = based_on.alphafollows
}
e.speed = (e.position - based_on.position):normalize():mult(math.random() * v, math.random() * v)
e.timetogo = math.random(50,130) / 100
e.etc = 0
table.insert(effect.bodies, e)
end
end
|
local helpers = require('test.functional.helpers')(after_each)
local eq = helpers.eq
local clear = helpers.clear
local funcs = helpers.funcs
local command = helpers.command
before_each(clear)
describe('setmatches()', function()
it('correctly handles case when both group and pattern entries are numbers',
function()
command('hi def link 1 PreProc')
eq(0, funcs.setmatches({{group=1, pattern=2, id=3, priority=4}}))
eq({{
group='1',
pattern='2',
id=3,
priority=4,
}}, funcs.getmatches())
eq(0, funcs.setmatches({{group=1, pattern=2, id=3, priority=4, conceal=5}}))
eq({{
group='1',
pattern='2',
id=3,
priority=4,
conceal='5',
}}, funcs.getmatches())
eq(0, funcs.setmatches({{group=1, pos1={2}, pos2={6}, id=3, priority=4, conceal=5}}))
eq({{
group='1',
pos1={2},
pos2={6},
id=3,
priority=4,
conceal='5',
}}, funcs.getmatches())
end)
it('fails with -1 if highlight group is not defined', function()
eq(-1, funcs.setmatches({{group=1, pattern=2, id=3, priority=4}}))
eq({}, funcs.getmatches())
eq(-1, funcs.setmatches({{group=1, pos1={2}, pos2={6}, id=3, priority=4, conceal=5}}))
eq({}, funcs.getmatches())
end)
end)
describe('matchadd()', function()
it('correctly works when first two arguments and conceal are numbers at once',
function()
command('hi def link 1 PreProc')
eq(4, funcs.matchadd(1, 2, 3, 4, {conceal=5}))
eq({{
group='1',
pattern='2',
priority=3,
id=4,
conceal='5',
}}, funcs.getmatches())
end)
end)
|
local TRACK_NAME = "Multicam - Selector"
local cameraSwitches = {}
local markerIndex = 0
while true do
local nextMakerIndex, _, position, _, name, _ =
reaper.EnumProjectMarkers(markerIndex)
local camera = string.match(name, "^Multicam %- Switch to camera (%d+)$")
if camera ~= nil then
table.insert(cameraSwitches, {
camera = camera,
position = position,
markerIndex = markerIndex
})
end
if nextMakerIndex == 0 then
break
else
markerIndex = nextMakerIndex
end
end
if #cameraSwitches == 0 then
return reaper.MB("Camera switch makers not found", "Error", 0)
end
local selectorTrack
local numberOfTracks = reaper.GetNumTracks()
for trackIndex = 0, numberOfTracks - 1, 1 do
local track = reaper.GetTrack(0, trackIndex)
local _, trackName = reaper.GetTrackName(track)
if string.match(trackName, string.gsub(TRACK_NAME, "%-", "%%-")) then
selectorTrack = track
break
end
end
if selectorTrack == nil then
if reaper.CountSelectedTracks(0) > 0 then
selectorTrack = reaper.GetSelectedTrack(0, 0)
else
reaper.InsertTrackAtIndex(numberOfTracks, false)
selectorTrack = reaper.GetTrack(0, numberOfTracks)
reaper.GetSetMediaTrackInfo_String(selectorTrack, "P_NAME", TRACK_NAME,
true)
end
end
local currentPosition = reaper.GetProjectLength(0)
for cameraSwitchIndex = #cameraSwitches, 1, -1 do
local cameraSwitch = cameraSwitches[cameraSwitchIndex]
local item = reaper.AddMediaItemToTrack(selectorTrack)
reaper.SetMediaItemInfo_Value(item, "D_POSITION", cameraSwitch.position)
reaper.SetMediaItemInfo_Value(item, "D_LENGTH",
currentPosition - cameraSwitch.position)
reaper.SetMediaItemInfo_Value(item, "D_FADEINLEN", 0)
reaper.SetMediaItemInfo_Value(item, "D_FADEOUTLEN", 0)
local _, chunk = reaper.GetItemStateChunk(item, "", false)
chunk = string.gsub(chunk, ">%s*$", [[
NAME ]] .. cameraSwitch.camera .. "\n" .. [[
FADEFLAG 1
<SOURCE VIDEOEFFECT
<CODE
|
>
>
%1
]])
reaper.SetItemStateChunk(item, chunk, false)
reaper.DeleteProjectMarkerByIndex(0, cameraSwitch.markerIndex)
currentPosition = cameraSwitch.position
end
|
local _, NS = ...
local Widgets = NS.Widgets
function Widgets:CreateButton(parent, text, tooltipText, func)
local button = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
button:GetFontString():SetPoint("CENTER", -1, 0)
button:SetMotionScriptsWhileDisabled(true)
button:RegisterForClicks("AnyUp")
button:SetText(text)
button:SetWidth(max(110, button:GetFontString():GetStringWidth() + 24))
button.tooltipText = tooltipText
button:SetScript("OnClick", func)
button:SetScript("OnEnter", Widgets.OnEnter)
button:SetScript("OnLeave", GameTooltip_Hide)
return button
end
|
-- ------------------------------------------------------------------------------------------
-- ITEMS
local base_accumulator = data.raw['accumulator']['accumulator']
data:extend{
{
type = 'item',
name = 'infinity-accumulator',
stack_size = 50,
icons = {apply_infinity_tint{icon=base_accumulator.icon, icon_size=base_accumulator.icon_size, icon_mipmaps=base_accumulator.icon_mipmaps}},
place_result = 'infinity-accumulator-primary-output',
subgroup = 'im-electricity',
order = 'a'
}
}
register_recipes{'infinity-accumulator'}
-- ------------------------------------------------------------------------------------------
-- ENTITIES
local ia_types = {'primary-input', 'primary-output', 'secondary-input', 'secondary-output', 'tertiary'}
local ia_entity = table.deepcopy(data.raw['electric-energy-interface']['electric-energy-interface'])
ia_entity.minable.result = 'infinity-accumulator'
ia_entity.picture.layers[1] = apply_infinity_tint(ia_entity.picture.layers[1])
ia_entity.picture.layers[1].hr_version = apply_infinity_tint(ia_entity.picture.layers[1].hr_version)
ia_entity.localised_description = {'entity-description.infinity-accumulator'}
local ia_icons = data.raw['item']['infinity-accumulator'].icons
for _,t in pairs(ia_types) do
local ia = table.deepcopy(ia_entity)
ia.name = 'infinity-accumulator-' .. t
ia.icons = ia_icons
ia.energy_source = {type='electric', usage_priority=t, buffer_capacity='500GJ'}
ia.subgroup = 'im-electricity'
ia.order = 'a'
ia.minable.result = 'infinity-accumulator'
ia.placeable_by = {item='infinity-accumulator', count=1}
data:extend{ia}
end
|
--===============================================
--== VARIABLES ==
--===============================================
local creatorCoords = {x = 1275.0, y = -1721.51, z = 53.66}
local guiEnabled = false
local group = {}
--===============================================
--== REGISTERS AND EVENTS ==
--===============================================
RegisterNetEvent('tm1_mafias:openCreator')
AddEventHandler('tm1_mafias:openCreator',function()
EnableGui(true)
end)
RegisterNUICallback('escape', function(data, cb)
EnableGui(false)
end)
RegisterNUICallback('register', function(data, cb)
group = data
TriggerServerEvent('tm1_mafias:createGroup', data.groupName)
EnableGui(false)
Wait (500)
end)
--===============================================
--== THREADING ==
--===============================================
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
DrawMarker(1,creatorCoords.x,creatorCoords.y,creatorCoords.z, 0, 0, 0, 0, 0, 0, 1.5001, 1.5001, 0.6001,100,96,99, 200, 0, 0, 0, 0)
local coords = GetEntityCoords(GetPlayerPed(-1))
if(GetDistanceBetweenCoords(coords, creatorCoords.x,creatorCoords.y,creatorCoords.z, true) <= 1.5) and guiEnabled == false then
drawTxt("PULSA E PARA CREAR UN GRUPO",2, 1, 0.5, 0.8, 0.45,0,255,0,255)
if IsControlJustReleased(0, 38) and guiEnabled == false then
TriggerServerEvent('tm1_mafias:verifyGroup')
end
elseif(GetDistanceBetweenCoords(coords, creatorCoords.x,creatorCoords.y,creatorCoords.z, true) > 1.5) and guiEnabled == true then
EnableGui(false)
end
end
end)
Citizen.CreateThread(function()
while true do
if guiEnabled then
DisableControlAction(0, 1, guiEnabled) -- LookLeftRight
DisableControlAction(0, 2, guiEnabled) -- LookUpDown
DisableControlAction(0, 142, guiEnabled) -- MeleeAttackAlternate
DisableControlAction(0, 106, guiEnabled) -- VehicleMouseControlOverride
if IsDisabledControlJustReleased(0, 142) then -- MeleeAttackAlternate
SendNUIMessage({
type = "click"
})
end
end
Citizen.Wait(0)
end
end)
--===============================================
--== FUNCTIONS ==
--===============================================
function EnableGui(enable)
SetNuiFocus(enable)
guiEnabled = enable
SendNUIMessage({
type = "enableui",
enable = enable
})
end
|
local mod = DBM:NewMod(2099, "DBM-Party-BfA", 9, 1001)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 18026 $"):sub(12, -3))
mod:SetCreatureID(127490)
mod:SetEncounterID(2103)
mod:SetZone()
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_AURA_APPLIED 257028",
"SPELL_CAST_START 256955 256970",
"SPELL_CAST_SUCCESS 257028"
)
--local warnSwirlingScythe = mod:NewTargetAnnounce(195254, 2)
local specWarnCinderflame = mod:NewSpecialWarningDodge(256955, nil, nil, nil, 2, 2)
local specWarnFuselighter = mod:NewSpecialWarningYou(257028, nil, nil, nil, 1, 2)
local yellFuselighter = mod:NewYell(257028, nil, false)
local specWarnFuselighterOther = mod:NewSpecialWarningDispel(257028, "Healer", nil, nil, 1, 2)
local specWarnIgnition = mod:NewSpecialWarningSpell(256970, nil, nil, nil, 1, 2)
--local specWarnGTFO = mod:NewSpecialWarningGTFO(238028, nil, nil, nil, 1, 8)
local timerCinderflameCD = mod:NewCDTimer(20.5, 256955, nil, nil, nil, 3)
local timerFuselighterCD = mod:NewCDTimer(14.7, 257028, nil, nil, nil, 3, nil, DBM_CORE_MAGIC_ICON)--14.7-23, health based?
local timerIgnitionCD = mod:NewCDTimer(32.7, 256970, nil, nil, nil, 5)--Health based?
--mod:AddRangeFrameOption(5, 194966)
function mod:OnCombatStart(delay)
timerIgnitionCD:Start(6.1-delay)
timerFuselighterCD:Start(14.2-delay)--SUCCESS
timerCinderflameCD:Start(18.2-delay)--START
end
function mod:OnCombatEnd()
-- if self.Options.RangeFrame then
-- DBM.RangeCheck:Hide()
-- end
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if spellId == 257028 then
if args:IsPlayer() then
specWarnFuselighter:Show()
specWarnFuselighter:Play("targetyou")
yellFuselighter:Yell()
else
specWarnFuselighterOther:Show(args.destName)
specWarnFuselighterOther:Play("helpdispel")
end
end
end
--mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 256955 then
specWarnCinderflame:Show()
specWarnCinderflame:Play("shockwave")
timerCinderflameCD:Start()
elseif spellId == 256970 then
specWarnIgnition:Show()
specWarnIgnition:Play("firecircle")--Doesn't really say what to do, but at leat accurate description!
timerIgnitionCD:Start()
end
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 257028 then
timerFuselighterCD:Start()
end
end
--[[
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 228007 and destGUID == UnitGUID("player") and self:AntiSpam(2, 4) then
specWarnGTFO:Show()
specWarnGTFO:Play("watchfeet")
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
function mod:UNIT_DIED(args)
local cid = self:GetCIDFromGUID(args.destGUID)
if cid == 124396 then
end
end
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, spellId)
if spellId == 257939 then
end
end
--]]
|
local bit = require 'bit'
local tohex = bit.tohex
local fmt = string.format
local random = math.random
local _M = {}
math.randomseed(ngx.time() + ngx.worker.pid())
function _M.new_span_id()
return fmt("%s%s%s%s%s%s%s%s",
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2))
end
function _M.new_ids()
return fmt("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2),
tohex(random(0, 255), 2)), _M.new_span_id()
end
return _M
|
Classes.ModSettingsClasses = {}
Ext.Require("Shared/Classes/ModSettings/Data/FlagData.lua")
Ext.Require("Shared/Classes/ModSettings/Data/VariableData.lua")
Ext.Require("Shared/Classes/ModSettings/Data/ButtonData.lua")
Ext.Require("Shared/Classes/ModSettings/Data/SettingsData.lua")
Ext.Require("Shared/Classes/ModSettings/ProfileSettings.lua")
Ext.Require("Shared/Classes/ModSettings/ModSettings.lua")
|
return {
postgres = {
up = [[
CREATE TABLE IF NOT EXISTS "cluster_events" (
"id" UUID PRIMARY KEY,
"node_id" UUID NOT NULL,
"at" TIMESTAMP WITH TIME ZONE NOT NULL,
"nbf" TIMESTAMP WITH TIME ZONE,
"expire_at" TIMESTAMP WITH TIME ZONE NOT NULL,
"channel" TEXT,
"data" TEXT
);
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "idx_cluster_events_at" ON "cluster_events" ("at");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "idx_cluster_events_channel" ON "cluster_events" ("channel");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
CREATE OR REPLACE FUNCTION "delete_expired_cluster_events" () RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
DELETE FROM "cluster_events"
WHERE "expire_at" <= CURRENT_TIMESTAMP AT TIME ZONE 'UTC';
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS "delete_expired_cluster_events_trigger" ON "cluster_events";
CREATE TRIGGER "delete_expired_cluster_events_trigger"
AFTER INSERT ON "cluster_events"
FOR EACH STATEMENT
EXECUTE PROCEDURE delete_expired_cluster_events();
CREATE TABLE IF NOT EXISTS "services" (
"id" UUID PRIMARY KEY,
"created_at" TIMESTAMP WITH TIME ZONE,
"updated_at" TIMESTAMP WITH TIME ZONE,
"name" TEXT UNIQUE,
"retries" BIGINT,
"protocol" TEXT,
"host" TEXT,
"port" BIGINT,
"path" TEXT,
"connect_timeout" BIGINT,
"write_timeout" BIGINT,
"read_timeout" BIGINT
);
CREATE TABLE IF NOT EXISTS "routes" (
"id" UUID PRIMARY KEY,
"created_at" TIMESTAMP WITH TIME ZONE,
"updated_at" TIMESTAMP WITH TIME ZONE,
"service_id" UUID REFERENCES "services" ("id"),
"protocols" TEXT[],
"methods" TEXT[],
"hosts" TEXT[],
"paths" TEXT[],
"regex_priority" BIGINT,
"strip_path" BOOLEAN,
"preserve_host" BOOLEAN
);
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "routes_fkey_service" ON "routes" ("service_id");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
CREATE TABLE IF NOT EXISTS "apis" (
"id" UUID PRIMARY KEY,
"created_at" TIMESTAMP WITHOUT TIME ZONE DEFAULT (CURRENT_TIMESTAMP(3) AT TIME ZONE 'UTC'),
"name" TEXT UNIQUE,
"upstream_url" TEXT,
"preserve_host" BOOLEAN NOT NULL,
"retries" SMALLINT DEFAULT 5,
"https_only" BOOLEAN,
"http_if_terminated" BOOLEAN,
"hosts" TEXT,
"uris" TEXT,
"methods" TEXT,
"strip_uri" BOOLEAN,
"upstream_connect_timeout" INTEGER,
"upstream_send_timeout" INTEGER,
"upstream_read_timeout" INTEGER
);
CREATE TABLE IF NOT EXISTS "certificates" (
"id" UUID PRIMARY KEY,
"created_at" TIMESTAMP WITH TIME ZONE DEFAULT (CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'),
"cert" TEXT,
"key" TEXT
);
CREATE TABLE IF NOT EXISTS "snis" (
"id" UUID PRIMARY KEY,
"created_at" TIMESTAMP WITH TIME ZONE DEFAULT (CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'),
"name" TEXT NOT NULL UNIQUE,
"certificate_id" UUID REFERENCES "certificates" ("id")
);
CREATE TABLE IF NOT EXISTS "consumers" (
"id" UUID PRIMARY KEY,
"created_at" TIMESTAMP WITHOUT TIME ZONE DEFAULT (CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'),
"username" TEXT UNIQUE,
"custom_id" TEXT UNIQUE
);
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "username_idx" ON "consumers" (LOWER("username"));
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
CREATE TABLE IF NOT EXISTS "plugins" (
"id" UUID UNIQUE,
"created_at" TIMESTAMP WITHOUT TIME ZONE DEFAULT (CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'),
"name" TEXT NOT NULL,
"consumer_id" UUID REFERENCES "consumers" ("id") ON DELETE CASCADE,
"service_id" UUID REFERENCES "services" ("id") ON DELETE CASCADE,
"route_id" UUID REFERENCES "routes" ("id") ON DELETE CASCADE,
"api_id" UUID REFERENCES "apis" ("id") ON DELETE CASCADE,
"config" JSON NOT NULL,
"enabled" BOOLEAN NOT NULL,
PRIMARY KEY ("id", "name")
);
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "plugins_name_idx" ON "plugins" ("name");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "plugins_consumer_idx" ON "plugins" ("consumer_id");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "plugins_service_id_idx" ON "plugins" ("service_id");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "plugins_route_id_idx" ON "plugins" ("route_id");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "plugins_api_idx" ON "plugins" ("api_id");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
CREATE TABLE IF NOT EXISTS "upstreams" (
"id" UUID PRIMARY KEY,
"created_at" TIMESTAMP WITHOUT TIME ZONE DEFAULT (CURRENT_TIMESTAMP(3) AT TIME ZONE 'UTC'),
"name" TEXT UNIQUE,
"hash_on" TEXT,
"hash_fallback" TEXT,
"hash_on_header" TEXT,
"hash_fallback_header" TEXT,
"hash_on_cookie" TEXT,
"hash_on_cookie_path" TEXT,
"slots" INTEGER NOT NULL,
"healthchecks" JSON
);
CREATE TABLE IF NOT EXISTS "targets" (
"id" UUID PRIMARY KEY,
"created_at" TIMESTAMP WITHOUT TIME ZONE DEFAULT (CURRENT_TIMESTAMP(3) AT TIME ZONE 'UTC'),
"upstream_id" UUID REFERENCES "upstreams" ("id") ON DELETE CASCADE,
"target" TEXT NOT NULL,
"weight" INTEGER NOT NULL
);
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "targets_target_idx" ON "targets" ("target");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
-- TODO: delete on 1.0.0 migrations
CREATE TABLE IF NOT EXISTS "ttls" (
"primary_key_value" TEXT NOT NULL,
"primary_uuid_value" UUID,
"table_name" TEXT NOT NULL,
"primary_key_name" TEXT NOT NULL,
"expire_at" TIMESTAMP WITHOUT TIME ZONE NOT NULL,
PRIMARY KEY ("primary_key_value", "table_name")
);
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS "ttls_primary_uuid_value_idx" ON "ttls" ("primary_uuid_value");
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
CREATE OR REPLACE FUNCTION "upsert_ttl" (v_primary_key_value TEXT, v_primary_uuid_value UUID, v_primary_key_name TEXT, v_table_name TEXT, v_expire_at TIMESTAMP WITHOUT TIME ZONE) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
LOOP
UPDATE ttls
SET expire_at = v_expire_at
WHERE primary_key_value = v_primary_key_value
AND table_name = v_table_name;
IF FOUND then
RETURN;
END IF;
BEGIN
INSERT INTO ttls (primary_key_value, primary_uuid_value, primary_key_name, table_name, expire_at)
VALUES (v_primary_key_value, v_primary_uuid_value, v_primary_key_name, v_table_name, v_expire_at);
RETURN;
EXCEPTION WHEN unique_violation THEN
END;
END LOOP;
END;
$$;
]]
},
cassandra = {
up = [[
CREATE TABLE IF NOT EXISTS cluster_events(
channel text,
at timestamp,
node_id uuid,
id uuid,
data text,
nbf timestamp,
PRIMARY KEY (channel, at, node_id, id)
) WITH default_time_to_live = 86400;
CREATE TABLE IF NOT EXISTS services(
partition text,
id uuid,
created_at timestamp,
updated_at timestamp,
name text,
host text,
path text,
port int,
protocol text,
connect_timeout int,
read_timeout int,
write_timeout int,
retries int,
PRIMARY KEY (partition, id)
);
CREATE INDEX IF NOT EXISTS services_name_idx ON services(name);
CREATE TABLE IF NOT EXISTS routes(
partition text,
id uuid,
created_at timestamp,
updated_at timestamp,
hosts list<text>,
paths list<text>,
methods set<text>,
protocols set<text>,
preserve_host boolean,
strip_path boolean,
service_id uuid,
regex_priority int,
PRIMARY KEY (partition, id)
);
CREATE INDEX IF NOT EXISTS routes_service_id_idx ON routes(service_id);
CREATE TABLE IF NOT EXISTS snis(
partition text,
id uuid,
name text,
certificate_id uuid,
created_at timestamp,
PRIMARY KEY (partition, id)
);
CREATE INDEX IF NOT EXISTS snis_name_idx ON snis(name);
CREATE INDEX IF NOT EXISTS snis_certificate_id_idx
ON snis(certificate_id);
CREATE TABLE IF NOT EXISTS certificates(
partition text,
id uuid,
cert text,
key text,
created_at timestamp,
PRIMARY KEY (partition, id)
);
CREATE TABLE IF NOT EXISTS consumers(
id uuid PRIMARY KEY,
created_at timestamp,
username text,
custom_id text
);
CREATE INDEX IF NOT EXISTS consumers_username_idx ON consumers(username);
CREATE INDEX IF NOT EXISTS consumers_custom_id_idx ON consumers(custom_id);
CREATE TABLE IF NOT EXISTS plugins(
id uuid,
name text,
api_id uuid,
config text,
consumer_id uuid,
created_at timestamp,
enabled boolean,
route_id uuid,
service_id uuid,
PRIMARY KEY (id, name)
);
CREATE INDEX IF NOT EXISTS plugins_name_idx ON plugins(name);
CREATE INDEX IF NOT EXISTS plugins_api_id_idx ON plugins(api_id);
CREATE INDEX IF NOT EXISTS plugins_route_id_idx ON plugins(route_id);
CREATE INDEX IF NOT EXISTS plugins_service_id_idx ON plugins(service_id);
CREATE INDEX IF NOT EXISTS plugins_consumer_id_idx ON plugins(consumer_id);
CREATE TABLE IF NOT EXISTS upstreams(
id uuid PRIMARY KEY,
created_at timestamp,
hash_fallback text,
hash_fallback_header text,
hash_on text,
hash_on_cookie text,
hash_on_cookie_path text,
hash_on_header text,
healthchecks text,
name text,
slots int
);
CREATE INDEX IF NOT EXISTS upstreams_name_idx ON upstreams(name);
CREATE TABLE IF NOT EXISTS targets(
id uuid PRIMARY KEY,
created_at timestamp,
target text,
upstream_id uuid,
weight int
);
CREATE INDEX IF NOT EXISTS targets_upstream_id_idx ON targets(upstream_id);
CREATE INDEX IF NOT EXISTS targets_target_idx ON targets(target);
CREATE TABLE IF NOT EXISTS apis(
id uuid PRIMARY KEY,
created_at timestamp,
hosts text,
http_if_terminated boolean,
https_only boolean,
methods text,
name text,
preserve_host boolean,
retries int,
strip_uri boolean,
upstream_connect_timeout int,
upstream_read_timeout int,
upstream_send_timeout int,
upstream_url text,
uris text
);
CREATE INDEX IF NOT EXISTS apis_name_idx ON apis(name);
]],
},
mysql = {
up = [[
CREATE TABLE `cluster_events` (
`id` varchar(50) PRIMARY KEY,
`node_id` varchar(50) NOT NULL,
`at` timestamp NOT NULL,
`nbf` timestamp,
`expire_at` timestamp NOT NULL,
`channel` text,
`data` text,
INDEX idx_cluster_events_at (`at`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
DROP EVENT IF EXISTS delete_expired_cluster_events_event;
CREATE EVENT delete_expired_cluster_events_event
ON SCHEDULE EVERY 1 HOUR
ON COMPLETION PRESERVE
DO
BEGIN
DELETE
FROM cluster_events
WHERE expire_at <= CURRENT_TIMESTAMP();
END;
CREATE TABLE `services` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp,
`updated_at` timestamp,
`name` text,
`retries` int8,
`protocol` text ,
`host` text ,
`port` int8,
`path` text ,
`connect_timeout` int8,
`write_timeout` int8,
`read_timeout` int8,
`tags` text,
`client_certificate_id` varchar(50),
UNIQUE INDEX `services_name_index` (`name`(50)),
INDEX `services_tags_index` (`tags`(127)),
INDEX `services_client_certificate_id_index` (`client_certificate_id`(50))
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `routes` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp,
`updated_at` timestamp,
`service_id` varchar(50),
`protocols` text,-- #Becareful it is text[] format
`methods` text,-- #Becareful it is text[] format
`hosts` text,-- #Becareful it is text[] format
`paths` text,-- #Becareful it is text[] format
`regex_priority` int8,
`strip_path` bool,
`preserve_host` bool,
`name` text,
`snis` text, -- #Becareful it is text[] format
`sources` text, -- #Becareful it is jsonb[] format
`destinations` text, -- #Becareful it is jsonb[] format
`tags` text,
`https_redirect_status_code` int8,
`headers` text,
UNIQUE INDEX `routes_name_index` (`name`(50)),
INDEX `routes_service_id_index` (`service_id`(50)),
INDEX `routes_tags_index` (`tags`(127)),
CONSTRAINT `routes_service_id_fkey` FOREIGN KEY (`service_id`) REFERENCES `services` (`id`) ON DELETE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `apis` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp NOT NULL,
`name` text ,
`upstream_url` text ,
`preserve_host` bool NOT NULL,
`retries` int2 DEFAULT 5,
`https_only` bool,
`http_if_terminated` bool,
`hosts` text,
`uris` text,
`methods` text,
`strip_uri` bool,
`upstream_connect_timeout` int4,
`upstream_send_timeout` int4,
`upstream_read_timeout` int4,
UNIQUE INDEX `apis_name_unique_index` (`name`(50))
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `certificates` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp NOT NULL,
`cert` text ,
`key` text,
`tags` text,
INDEX `certificates_tags_index` (`tags`(127))
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `snis` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp NOT NULL,
`name` text NOT NULL,
`certificate_id` varchar(50),
`tags` text,
UNIQUE INDEX `snis_name_unique_index` (`name`(50)),
INDEX `snis_tags_index` (`tags`(127)),
INDEX `snis_certificate_id_index` (`certificate_id`(50)),
CONSTRAINT `snis_certificate_id_fkey` FOREIGN KEY (`certificate_id`) REFERENCES `certificates` (`id`) ON DELETE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `consumers` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp NOT NULL,
`username` text ,
`custom_id` text,
`tags` text,
UNIQUE INDEX `consumers_username_unique_index` (`username`(128)),
UNIQUE INDEX `consumers_custom_id_unique_index` (`custom_id`(128)),
INDEX `consumers_tags_index` (`tags`(127))
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `plugins` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp NOT NULL,
`name` text NOT NULL,
`consumer_id` varchar(50),
`service_id` varchar(50),
`route_id` varchar(50),
`api_id` varchar(50),
`config` text NOT NULL, -- #Becareful it is jsonb format
`enabled` bool NOT NULL,
`cache_key` text,
`run_on` text,
`protocols` text,
`tags` text,
UNIQUE INDEX `plugins_cache_key_key` (`cache_key`(50)),
INDEX `plugins_api_id_idx` (`api_id`(50)),
INDEX `plugins_consumer_id_idx` (`consumer_id`(50)),
INDEX `plugins_name_idx` (`name`(50)),
INDEX `plugins_route_id_idx` (`route_id`(50)),
INDEX `plugins_run_on_idx` (`run_on`(50)),
INDEX `plugins_service_id_idx` (`service_id`(50)),
INDEX `plugins_tags_idx` (`tags`(127)),
CONSTRAINT `plugins_api_id_fkey` FOREIGN KEY (`api_id`) REFERENCES `apis` (`id`) ON DELETE CASCADE,
CONSTRAINT `plugins_consumer_id_fkey` FOREIGN KEY (`consumer_id`) REFERENCES `consumers` (`id`) ON DELETE CASCADE,
CONSTRAINT `plugins_route_id_fkey` FOREIGN KEY (`route_id`) REFERENCES `routes` (`id`) ON DELETE CASCADE,
CONSTRAINT `plugins_service_id_fkey` FOREIGN KEY (`service_id`) REFERENCES `services` (`id`) ON DELETE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `upstreams` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp NOT NULL,
`name` text ,
`hash_on` text ,
`hash_fallback` text ,
`hash_on_header` text ,
`hash_fallback_header` text,
`hash_on_cookie` text ,
`hash_on_cookie_path` text ,
`slots` int4 NOT NULL,
`healthchecks` text, -- #Becareful it is jsonb format
`tags` text,
`algorithm` text,
UNIQUE INDEX `upstreams_name_key` (`name`(50)),
INDEX `upstreams_tags_idx` (`tags`(127))
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `targets` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp NOT NULL,
`upstream_id` varchar(50),
`target` text NOT NULL,
`weight` int4 NOT NULL,
`tags` text,
INDEX `targets_target_idx` (`target`(50)),
INDEX `targets_upstream_id_idx` (`upstream_id`(50)),
INDEX `targets_tags_idx` (`tags`(127)),
CONSTRAINT `targets_upstream_id_fkey` FOREIGN KEY (`upstream_id`) REFERENCES `upstreams` (`id`) ON DELETE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `ttls` (
`primary_key_value` varchar(200) NOT NULL,
`primary_uuid_value` varchar(50),
`table_name` varchar(100) NOT NULL,
`primary_key_name` varchar(100) NOT NULL,
`expire_at` timestamp NOT NULL,
PRIMARY KEY(`primary_key_value`, `table_name`),
INDEX `ttls_primary_uuid_value_idx` (`primary_uuid_value`(50))
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `cluster_ca` (
`pk` bool NOT NULL PRIMARY KEY CHECK(pk=true),
`key` text NOT NULL,
`cert` text NOT NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `ca_certificates` (
`id` varchar(50) PRIMARY KEY,
`created_at` timestamp NOT NULL,
`cert` text NOT NULL,
`tags` text,
INDEX `ca_certificates_tags_idx` (`tags`(127)),
UNIQUE INDEX `ca_certificates_cert_unique_index` (`cert`(127))
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `tags` (
`entity_id` varchar(50) PRIMARY KEY,
`entity_name` timestamp NOT NULL,
`tags` text,
INDEX `tags_tags_idx` (`tags`(127)),
INDEX `tags_entity_name_idx` (`entity_name`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
]]
},
}
|
local handheld = require 'handheld'
local stringio = require 'pl.stringio'
local log = require 'log'
log.level = "error"
describe("handheld", function()
it("should parse and run a simple program", function()
local text = [[nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
nop -4
acc +6
]]
local f = stringio.open(text)
local program = handheld.parse(f)
assert.are.equal(9, #program.instructions)
assert.are.equal(1, program.ip)
assert.are.equal(0, program.accumulator)
local result = program:run()
assert.are.equal(8, result)
end)
end)
|
object_mobile_respec_seller_f_1 = object_mobile_shared_respec_seller_f_1:new {
}
ObjectTemplates:addTemplate(object_mobile_respec_seller_f_1, "object/mobile/respec_seller_f_1.iff")
|
game.ReplicatedStorage.RawData.OnServerInvoke = function(player, url)
local res = game:GetService("HttpService"):GetAsync(url)
return res
end
|
the.DialogueSpeed = 0.05
the.DialogueFont = love.graphics.newFont("fonts/coolvetica rg.ttf", 18)
the.DialogueQueue = {}
local function NextOfQueue()
local tbl = the.DialogueQueue[1]
if not tbl then
KillDialogueDisplay()
else
table.remove(the.DialogueQueue,1)
if tbl.type == "text" then
if tbl.side ~= "n" then
if not the.DialogueImagePanel then
the.DialogueImagePanel = loveframes.Create("panel")
the.DialogueImagePanel:SetSize(the.app.width/5, the.app.height/3)
the.DialogueImage = loveframes.Create("image", the.DialogueImagePanel)
the.DialogueImage:SetPos(5, 5)
the.DialogueImage:SetSize(the.app.width/5, the.app.height/3)
end
the.DialogueImage:SetImage(tbl.img or "images/tuky.png")
the.DialogueImage:SetScaleX((the.app.width/5-5) / the.DialogueImage:GetImageWidth())
the.DialogueImage:SetScaleY((the.app.height/3-5) / the.DialogueImage:GetImageHeight())
if tbl.side == "r" then
the.DialogueImagePanel:SetPos(the.app.width*4/5-50, 50)
else
the.DialogueImagePanel:SetPos(50, 50)
end
else
if the.DialogueImagePanel then
the.DialogueImagePanel:SetVisible(false)
the.DialogueImagePanel = nil
end
end
the.DialoguePanel.promise = DisplayText( tbl.str )
elseif tbl.type == "choice" then
if the.DialogueImagePanel then
the.DialogueImagePanel:SetVisible(false)
the.DialogueImagePanel = nil
end
if not the.DialoguePanel then
the.DialoguePanel = loveframes.Create("panel")
the.DialoguePanel.finished = Promise:new()
the.DialoguePanel:SetSize(the.app.width-100, the.app.height / 3 - 50)
the.DialoguePanel:SetPos(50, the.app.height*2/3-50)
end
the.DialoguePanel.promise = DisplayOption( tbl.str, tbl.args )
end
end
end
function DisplayText( str, sound )
if not the.DialoguePanel then return end
local promise = Promise:new()
local cur = 1
local source
if not sound then
local soundtmr = Timer:new()
the.view:add(soundtmr)
soundtmr:every(math.max(the.DialogueSpeed, 0.1), function()
if not the.DialoguePanel or promise ~= the.DialoguePanel.promise then return end
if not the.DialoguePanel.WaitingForInput then playSound('sounds/talk3.wav') end
if the.DialoguePanel.InputReceived then
soundtmr:stop()
the.view:remove(soundtmr)
end
end)
else
source:playSound(sound)
end
promise:andThen(function() NextOfQueue() end)
the.DialoguePanel:SetVisible(true)
if not the.DialogueText then
the.DialogueText = loveframes.Create("text", the.DialoguePanel)
the.DialogueText:SetPos(10,10)
the.DialogueText:SetSize(the.app.width-110, the.app.height / 3 - 60)
the.DialogueText:SetFont(the.DialogueFont)
the.DialogueText:SetShadowColor(200, 200, 200, 255)
else
the.DialogueText:SetText("")
end
local tmr = Timer:new()
the.view:add(tmr)
tmr:every(the.DialogueSpeed, function()
if not the.DialoguePanel or promise ~= the.DialoguePanel.promise then return end
if the.keys:pressed(" ") or the.keys:pressed("enter") then
cur = cur + 5
else
cur = cur + 1
end
the.DialogueText:SetText(string.sub(str, 1, cur))
if cur > string.len(str) then
the.DialoguePanel.WaitingForInput = true
the.DialogueText:SetText(str)
end
if the.DialoguePanel.InputReceived then
if source then
source:stop()
end
the.DialoguePanel.WaitingForInput = false
the.DialoguePanel.InputReceived = false
tmr:stop()
the.view:remove(tmr)
if promise.state == "unfulfilled" then promise:fulfill()
else
KillDialogueDisplay()
end
end
end)
return promise
end
function DisplayOption(str, args)
the.DialoguePanel.MaxOptions = #args
local promise = Promise:new()
local cur = 1
promise:andThen(function() NextOfQueue() end)
the.DialoguePanel:SetVisible(true)
if not the.DialogueText then
the.DialogueText = loveframes.Create("text", the.DialoguePanel)
the.DialogueText:SetPos(10,10)
the.DialogueText:SetSize(the.app.width-110, the.app.height / 3 - 60)
the.DialogueText:SetFont(the.DialogueFont)
the.DialogueText:SetShadowColor(200, 200, 200, 255)
else
the.DialogueText:SetText("")
end
local tmr = Timer:new()
the.view:add(tmr)
tmr:every(the.DialogueSpeed, function()
if not the.DialoguePanel or promise ~= the.DialoguePanel.promise then return end
if the.keys:pressed(" ") or the.keys:pressed("enter") then
cur = cur + 5
else
cur = cur + 1
end
the.DialogueText:SetText(string.sub(str, 1, cur))
if cur > string.len(str) and not the.DialoguePanel.WaitingForInput then
the.DialoguePanel.WaitingForInput = true
the.DialoguePanel.SelectedOption = 1
for i=1, the.DialoguePanel.MaxOptions do
local text = loveframes.Create("text", the.DialoguePanel)
text:SetPos(20, 45 + 20 * (i-1))
text:SetSize(the.app.width-150, 20)
text:SetFont(the.DialogueFont)
text:SetShadowColor(200, 200, 200, 255)
text:SetText(args[i][1])
text.OnMouseEnter = function(object)
the.DialoguePanel.SelectedOption = i
end
text.Update = function(object)
if not the.DialoguePanel or promise ~= the.DialoguePanel.promise then text.visible = false return end
if the.DialoguePanel.SelectedOption == i then
text:SetText({{255,0,0,255}, args[i][1]})
else
text:SetText({{0,0,0,255}, args[i][1]})
end
if not text.done and the.mouse:pressed() and text.hover then
args[i][2]()
the.DialoguePanel.WaitingForInput = false
the.DialoguePanel.InputReceived = false
if promise.state == "unfulfilled" then promise:fulfill()
else KillDialogueDisplay() end
tmr:stop()
the.view:remove(tmr)
text.done = true
end
end
end
end
if the.DialoguePanel.InputReceived then
args[the.DialoguePanel.SelectedOption][2]()
the.DialoguePanel.WaitingForInput = false
the.DialoguePanel.InputReceived = false
if promise.state == "unfulfilled" then promise:fulfill()
else KillDialogueDisplay() end
tmr:stop()
the.view:remove(tmr)
end
end)
local soundtmr = Timer:new()
the.view:add(soundtmr)
soundtmr:every(math.max(the.DialogueSpeed, 0.1), function()
if not the.DialoguePanel or promise ~= the.DialoguePanel.promise then return end
if not the.DialoguePanel.WaitingForInput then playSound('sounds/talk3.wav') end
if the.DialoguePanel.InputReceived then
soundtmr:stop()
the.view:remove(soundtmr)
end
end)
return promise
end
function KillDialogueDisplay()
the.app.LockInput = false
if the.DialoguePanel then
if the.DialoguePanel.finished.state == "unfulfilled" then the.DialoguePanel.finished:fulfill() end
the.DialoguePanel:SetVisible(false)
the.DialoguePanel = nil
if the.DialogueImagePanel then
the.DialogueImagePanel:SetVisible(false)
the.DialogueImagePanel = nil
the.DialogueImage = nil
end
the.DialogueText = nil
the.DialogueQueue = {}
end
end
function DisplayDialogue(str, img, side, sound)
the.app.LockInput = true
if not the.DialoguePanel then
the.DialoguePanel = loveframes.Create("panel")
the.DialoguePanel.finished = Promise:new()
the.DialoguePanel:SetSize(the.app.width-100, the.app.height / 3 - 50)
the.DialoguePanel:SetPos(50, the.app.height*2/3-50)
the.DialoguePanel.Update = function( object )
if the.DialoguePanel then
if the.DialoguePanel.WaitingForInput then
if not the.DialoguePanel.SelectedOption then the.DialoguePanel.SelectedOption = 1 end
if the.keys:justPressed(" ") or the.keys:justPressed("enter") then
the.DialoguePanel.WaitingForInput = false
the.DialoguePanel.InputReceived = true
elseif the.keys:justPressed("down") then
the.DialoguePanel.SelectedOption = math.min(the.DialoguePanel.MaxOptions or 0, the.DialoguePanel.SelectedOption + 1 )
elseif the.keys:justPressed("up") then
the.DialoguePanel.SelectedOption = math.max(1, the.DialoguePanel.SelectedOption - 1)
end
end
end
end
the.DialogueImagePanel = loveframes.Create("panel")
the.DialogueImagePanel:SetSize(the.app.width/5, the.app.height/3)
if side == "r" then
the.DialogueImagePanel:SetPos(the.app.width*4/5-50, 50)
else
the.DialogueImagePanel:SetPos(50, 50)
end
the.DialogueImage = loveframes.Create("image", the.DialogueImagePanel)
the.DialogueImage:SetPos(5, 5)
the.DialogueImage:SetSize(the.app.width/5, the.app.height/3)
the.DialogueImage:SetImage(img or "images/tuky.png")
the.DialogueImage:SetScaleX((the.app.width/5-5) / the.DialogueImage:GetImageWidth())
the.DialogueImage:SetScaleY((the.app.height/3-5) / the.DialogueImage:GetImageHeight())
if side == "n" then
if the.DialogueImagePanel then
the.DialogueImagePanel:SetVisible(false)
the.DialogueImagePanel = nil
end
end
the.DialoguePanel.promise = DisplayText( str, sound )
else
table.insert(the.DialogueQueue, {["str"] = str, ["img"] = img, ["side"] = side, ["type"] = "text", ["sound"] = sound})
end
return the.DialoguePanel.finished
end
function DisplayDialogueOption(str, ...)
local args = {...}
the.app.LockInput = true
if not the.DialoguePanel then
the.DialoguePanel = loveframes.Create("panel")
the.DialoguePanel.finished = Promise:new()
the.DialoguePanel:SetSize(the.app.width-100, the.app.height / 3 - 50)
the.DialoguePanel:SetPos(50, the.app.height*2/3-50)
the.DialoguePanel.promise = DisplayOption( str, args )
if the.DialogueImagePanel then
the.DialogueImagePanel:SetVisible(false)
the.DialogueImagePanel = nil
end
else
table.insert(the.DialogueQueue, {["str"] = str, ["args"] = args, ["type"] = "choice"})
end
return the.DialoguePanel.finished
end
DialogueTest = View:extend{
onNew = function(self)
DisplayDialogue("shit","images/babby.png", "l")
DisplayDialogueOption("take a pick", {"option 1", function() DisplayDialogue("bien", "images/tuky.png", "r") DisplayDialogueOption("y ahora?", {"si", function() DisplayDialogue("bien de nuevo", "images/tuky.png", "r") end}, {"no", function() end}) end}, {"option 2", function() DisplayDialogue("shit","images/babby.png", "r") end}, {"fucking quit", function() end})
end,
onUpdate = function(self)
end
}
|
-- This is weird code... I'm just playing with an idea
function wax.frame(object)
return wax.dimensions(object, "frame")
end
function wax.bounds(object)
return wax.dimensions(object, "bounds")
end
function wax.dimensions(object, varName)
return setmetatable({
object = object,
center = function(self)
local offset = (wax.dimensions(self.object:superview(), varName).width - self.width) / 2
self.x = offset
return self
end,
},
{
__index = function(self, key)
if key == "y" then key = "top"
elseif key == "x" then key = "left"
end
local dimensions = (varName == "frame") and object:frame() or object:bounds()
if key == "left" then return dimensions.x
elseif key == "right" then return dimensions.x + dimensions.width
elseif key == "top" then return dimensions.y
elseif key == "bottom" then return dimensions.y + dimensions.height
elseif key == "height" then return dimensions.height
elseif key == "width" then return dimensions.width
elseif key == "size" then return CGSize(dimensions.width, dimensions.height)
elseif key == "origin" then return CGPoint(dimensions.x, dimensions.y)
else
error("Unknown frame key: " .. key)
end
end,
__newindex = function(self, key, value)
if key == "y" then key = "top"
elseif key == "x" then key = "left"
end
local dimensions = (varName == "frame") and object:frame() or object:bounds()
if key == "left" then dimensions.x = value
elseif key == "right" then dimensions.x = value - dimensions.width
elseif key == "top" then dimensions.y = value
elseif key == "bottom" then dimensions.y = value - dimensions.height
elseif key == "height" then dimensions.height = value
elseif key == "width" then dimensions.width = value
elseif key == "size" then dimensions.width = value.width dimensions.height = value.height
elseif key == "origin" then dimensions.x = value.x dimensions.y = value.y
elseif key == "stretchTop" then
dimensions.height = dimensions.height - (value - dimensions.y)
dimensions.y = value
elseif key == "stretchBottom" then
dimensions.height = dimensions.height + (value - (dimensions.height + dimensions.y))
elseif key == "stretchRight" then
dimensions.width = dimensions.width + (value - (dimensions.width + dimensions.x))
else
error("Unknown frame key: " .. key)
end
if (varName == "frame") then
object:setFrame(dimensions)
else
object:setBounds(dimensions)
end
return self
end
})
end
|
-- $Id: lups.lua 4099 2009-03-16 05:18:45Z jk $
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
--
-- file: api_gfx_lups.lua
-- brief: Lua Particle System
-- authors: jK
-- last updated: Jan. 2008
--
-- Copyright (C) 2007,2008.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
local function GetInfo()
return {
name = "Lups",
desc = "Lua Particle System",
author = "jK",
date = "2008-2014",
license = "GNU GPL, v2 or later",
layer = 1000,
api = true,
enabled = true
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// Error Log Handling
PRIO_MAJOR = 0
PRIO_ERROR = 1
PRIO_LESS = 2
local errorLog = {}
local printErrorsAbove = PRIO_MAJOR
function print(priority,...)
local errorMsg = ""
for i=1,select('#',...) do
errorMsg = errorMsg .. select(i,...)
end
errorLog[#errorLog+1] = {priority=priority,message=errorMsg}
if (priority<=printErrorsAbove) then
Spring.Echo(...)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// locals
local push = table.insert
local pop = table.remove
local StrToLower = string.lower
local pairs = pairs
local ipairs = ipairs
local next = next
local spGetUnitRadius = Spring.GetUnitRadius
local spIsUnitVisible = Spring.IsUnitVisible
local spIsSphereInView = Spring.IsSphereInView
local spGetUnitLosState = Spring.GetUnitLosState
local spGetUnitViewPosition = Spring.GetUnitViewPosition
local spGetUnitDirection = Spring.GetUnitDirection
local spGetHeadingFromVector = Spring.GetHeadingFromVector
local spGetUnitIsActive = Spring.GetUnitIsActive
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spGetGameFrame = Spring.GetGameFrame
local spGetFrameTimeOffset = Spring.GetFrameTimeOffset
local spGetUnitPieceList = Spring.GetUnitPieceList
local spGetSpectatingState = Spring.GetSpectatingState
local spGetLocalAllyTeamID = Spring.GetLocalAllyTeamID
local scGetReadAllyTeam = Script.GetReadAllyTeam
local spGetUnitPieceMap = Spring.GetUnitPieceMap
local spValidUnitID = Spring.ValidUnitID
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetProjectilePosition = Spring.GetProjectilePosition
local spGetUnitVelocity = Spring.GetUnitVelocity
local glUnitPieceMatrix = gl.UnitPieceMatrix
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glTranslate = gl.Translate
local glRotate = gl.Rotate
local glScale = gl.Scale
local glBlending = gl.Blending
local glAlphaTest = gl.AlphaTest
local glDepthTest = gl.DepthTest
local glDepthMask = gl.DepthMask
local glUnitMultMatrix = gl.UnitMultMatrix
local glUnitPieceMultMatrix = gl.UnitPieceMultMatrix
local GL_GREATER = GL.GREATER
local GL_ONE = GL.ONE
local GL_SRC_ALPHA = GL.SRC_ALPHA
local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// hardware capabilities
local GL_VENDOR = 0x1F00
local GL_RENDERER = 0x1F01
local GL_VERSION = 0x1F02
local glVendor = gl.GetString(GL_VENDOR)
local glRenderer = (gl.GetString(GL_RENDERER)):lower()
isNvidia = (glVendor:find("NVIDIA"))
isATI = (glVendor:find("ATI "))
isMS = (glVendor:find("Microsoft"))
isIntel = (glVendor:find("Intel"))
canCTT = (gl.CopyToTexture ~= nil)
canFBO = (gl.DeleteTextureFBO ~= nil)
canRTT = (gl.RenderToTexture ~= nil)
canShader = (gl.CreateShader ~= nil)
canDistortions = false --// check Initialize()
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// widget/gadget handling
local handler = (widget and widgetHandler)or(gadgetHandler)
local GG = (widget and WG)or(GG)
local VFSMODE = (widget and VFS.RAW_FIRST)or(VFS.ZIP_ONLY)
--// locations
local LUPS_LOCATION = 'lups/'
local PCLASSES_DIRNAME = LUPS_LOCATION .. 'ParticleClasses/'
local HEADERS_DIRNAME = LUPS_LOCATION .. 'headers/'
--// helpers
VFS.Include(LUPS_LOCATION .. 'loadconfig.lua',nil,VFSMODE)
--// load some headers
VFS.Include(HEADERS_DIRNAME .. 'general.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'mathenv.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'figures.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'vectors.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'hsl.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'nanoupdate.lua',nil,VFSMODE)
--// load binary insert library
VFS.Include(HEADERS_DIRNAME .. 'tablebin.lua')
local flayer_comp = function( partA,partB )
return ( partA==partB )or
( (partA.layer==partB.layer)and((partA.unit or -1)<(partB.unit or -1)) )or
( partA.layer<partB.layer )
end
--// workaround for broken UnitDraw() callin
local nilDispList
--// global function (fx classes can use it) for easier access to Lups.cfg
function GetLupsSetting(key, default)
local value = LupsConfig[key]
if (value~=nil) then
return value
else
return default
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// some global vars (so the effects can use them)
vsx, vsy, vpx, vpy = Spring.GetViewGeometry() --// screen pos & view pos (view pos only unequal zero if dualscreen+minimapOnTheLeft)
LocalAllyTeamID = 0
thisGameFrame = 0
frameOffset = 0
LupsConfig = {}
local spActivateMaterial = (Spring.UnitRendering and Spring.UnitRendering.ActivateMaterial) or function() end
local spDeactivateMaterial = (Spring.UnitRendering and Spring.UnitRendering.DeactivateMaterial) or function() end
local noDrawUnits = {}
function SetUnitLuaDraw(unitID,nodraw)
if (nodraw) then
noDrawUnits[unitID] = (noDrawUnits[unitID] or 0) + 1
if (noDrawUnits[unitID]==1) then
--if (Game.version=="0.76b1") then
spActivateMaterial(unitID,1)
--Spring.UnitRendering.SetLODLength(unitID,1,-1000)
for pieceID in ipairs(Spring.GetUnitPieceList(unitID) or {}) do
Spring.UnitRendering.SetPieceList(unitID,1,pieceID,nilDispList)
end
--else
-- Spring.UnitRendering.SetUnitLuaDraw(unitID,true)
--end
end
else
noDrawUnits[unitID] = (noDrawUnits[unitID] or 0) - 1
if (noDrawUnits[unitID]==0) then
--if (Game.version=="0.76b1") then
spDeactivateMaterial(unitID,1)
--else
-- Spring.UnitRendering.SetUnitLuaDraw(unitID,false)
--end
noDrawUnits[unitID] = nil
end
end
end
local function DrawUnit(_,unitID,drawMode)
--[[
drawMode:
notDrawing = 0,
normalDraw = 1,
shadowDraw = 2,
reflectionDraw = 3,
refractionDraw = 4
--]]
if (drawMode==1)and(noDrawUnits[unitID]) then
return true
end
return false
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local oldVsx,oldVsy = vsx-1,vsy-1
--// load particle classes
local fxClasses = {}
local DistortionClass
local files = VFS.DirList(PCLASSES_DIRNAME, "*.lua",VFSMODE)
for _,filename in ipairs(files) do
local Class = VFS.Include(filename,nil,VFSMODE)
if (Class) then
if (Class.GetInfo) then
Class.pi = Class.GetInfo()
local sClassName = string.lower(Class.pi.name)
if (fxClasses[sClassName]) then
print(PRIO_LESS,'LUPS: duplicated particle class name "' .. sClassName .. '"')
else
fxClasses[sClassName] = Class
end
else
print(PRIO_ERROR,'LUPS: "' .. Class .. '" is missing GetInfo() ')
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// saves all particles
particles = {}
local particles = particles
local particlesCount = 0
local RenderSequence = {} --// mult-dim table with: [layer][partClass][unitID][fx]
local effectsInDelay = {} --// fxs which use the delay tag, and waiting for their spawn
local partIDCount = 0 --// increasing ID used to identify the particles
--[[
local function DebugPieces(unit,piecenum,level)
local piece = Spring.GetUnitPieceInfo(unit,piecenum)
Spring.Echo( string.rep(" ", level) .. "->" .. piece.name .. " (" .. piecenum .. ")")
for _,pieceChildName in ipairs(piece.children) do
local pieceNum = spGetUnitPieceMap(unit)[pieceChildName]
DebugPieces(unit,pieceNum,level+1)
end
end
--]]
--// the id param is internal don't use it!
function AddParticles(Class,Options ,__id)
if (not Options) then
print(PRIO_LESS,'LUPS->AddFX: no options given');
return -1;
end
--[[
if Options.quality and Options.quality > GetLupsSetting("quality", 3) then
return -1;
end
--]]
if (Options.delay and Options.delay~=0) then
partIDCount = partIDCount+1
newOptions = {}; CopyTable(newOptions,Options); newOptions.delay=nil
effectsInDelay[#effectsInDelay+1] = {frame=thisGameFrame+Options.delay, class=Class, options=newOptions, id=partIDCount};
return partIDCount
end
Class = StrToLower(Class)
local particleClass = fxClasses[Class]
if (not particleClass) then
print(PRIO_LESS,'LUPS->AddFX: couldn\'t find a particle class named "' .. Class .. '"');
return -1;
end
if (Options.unit)and(not spValidUnitID(Options.unit)) then
print(PRIO_LESS,'LUPS->AddFX: unit is already dead/invalid "' .. Class .. '"');
return -1;
end
--// piecename to piecenum conversion (spring >=76b1 only!)
if (Options.unit and Options.piece) then
local pieceMap = spGetUnitPieceMap(Options.unit)
Options.piecenum = pieceMap and pieceMap[Options.piece] --added check. switching spectator view can cause "attempt to index a nil value"
if (not Options.piecenum) then
local udid = Spring.GetUnitDefID(Options.unit)
if (not udid) then
print(PRIO_LESS,"LUPS->AddFX:wrong unitID")
else
print(PRIO_ERROR,"LUPS->AddFX:wrong unitpiece " .. Options.piece .. "(" .. UnitDefs[udid].name .. ")")
end
return -1;
end
end
--Spring.Echo("-------------")
--DebugPieces(Options.unit,1,0)
local newParticles,reusedFxID = particleClass.Create(Options)
if (newParticles) then
particlesCount = particlesCount + 1;
if (__id) then
newParticles.id = __id
else
partIDCount = partIDCount+1
newParticles.id = partIDCount
end
particles[ newParticles.id ] = newParticles
local space = ((not newParticles.worldspace) and newParticles.unit) or (-1)
local fxTable = CreateSubTables(RenderSequence,{newParticles.layer,particleClass,space})
newParticles.fxTable = fxTable
fxTable[#fxTable+1] = newParticles
return newParticles.id;
else
if (reusedFxID) then
return reusedFxID;
else
if (newParticles~=false) then
print(PRIO_LESS,"LUPS->AddFX:FX creation failed");
end
return -1;
end
end
end
function AddParticlesArray(array)
local class = ""
for i=1,#array do
local fxSettings = array[i]
class = fxSettings.class
fxSettings.class = nil
AddParticles(class,fxSettings)
end
end
function GetParticles(particlesID)
return particles[particlesID]
end
function RemoveParticles(particlesID)
local fx = particles[particlesID]
if (fx) then
if (type(fx.fxTable)=="table") then
for j,w in pairs(fx.fxTable) do
if (w.id==particlesID) then
pop(fx.fxTable,j)
end
end
end
fx:Destroy()
if fx.lightID then
if WG and WG['lighteffects'] then
WG['lighteffects'].removeLight(fx.lightID)
end
end
particles[particlesID] = nil
particlesCount = particlesCount-1;
return
else
local status,err = pcall(function()
--//FIXME
for i=1,#effectsInDelay do
if (effectsInDelay[i].id==particlesID) then
table.remove(effectsInDelay,i)
return
end
end
--//
end)
if (not status) then
Spring.Echo("Error (Lups) - "..(#effectsInDelay).." :"..err)
for i=1,#effectsInDelay do
Spring.Echo("->",effectsInDelay[i],type(effectsInDelay[i]))
end
effectsInDelay = {}
end
end
end
function GetStats()
local count = particlesCount
local effects = {}
local layers = 0
for i=-50,50 do
if (RenderSequence[i]) then
local layer = RenderSequence[i];
if (next(layer or {})) then layers=layers+1 end
for partClass,Units in pairs(layer) do
if (not effects[partClass.pi.name]) then
effects[partClass.pi.name] = {0,0} --//[1]:=fx count [2]:=part count
end
for unitID,UnitEffects in pairs(Units) do
for _,fx in pairs(UnitEffects) do
effects[partClass.pi.name][1] = effects[partClass.pi.name][1] + 1
effects[partClass.pi.name][2] = effects[partClass.pi.name][2] + (fx.count or 0)
--count = count+1
end
end
end
end
end
return count,layers,effects
end
function HasParticleClass(ClassName)
local Class = StrToLower(ClassName)
return (fxClasses[Class] and true)or(false)
end
function GetErrorLog(minPriority)
if (minPriority) then
local log = ""
for i=1,#errorLog do
if (errorLog[i].priority<=minPriority) then
log = log .. errorLog[i].message .. "\n"
end
end
if (log~="") then
local sysinfo = "Vendor:" .. glVendor ..
"\nRenderer:" .. glRenderer ..
(((isATI)and("\nisATI: true"))or("")) ..
(((isMS)and("\nisMS: true"))or("")) ..
(((isIntel)and("\nisIntel: true"))or("")) ..
"\ncanFBO:" .. tostring(canFBO) ..
"\ncanRTT:" .. tostring(canRTT) ..
"\ncanCTT:" .. tostring(canCTT) ..
"\ncanShader:" .. tostring(canShader) .. "\n"
log = sysinfo..log
end
return log
else
if (errorlog~="") then
local sysinfo = "Vendor:" .. glVendor ..
"\nRenderer:" .. glRenderer ..
"\nisATI:" .. tostring(isATI) ..
"\nisMS:" .. tostring(isMS) ..
"\nisIntel:" .. tostring(isIntel) ..
"\ncanFBO:" .. tostring(canFBO) ..
"\ncanRTT:" .. tostring(canRTT) ..
"\ncanCTT:" .. tostring(canCTT) ..
"\ncanShader:" .. tostring(canShader) .. "\n"
return sysinfo..errorLog
else
return errorLog
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local anyFXVisible = false
local anyDistortionsVisible = false
local function IsUnitPositionKnown(unitID)
if LocalAllyTeamID < 0 then
return true
end
local targetVisiblityState = Spring.GetUnitLosState(unitID, LocalAllyTeamID, true)
if not targetVisiblityState then
return false
end
local inLos = (targetVisiblityState == 15)
if inLos then
return true
end
local identified = (targetVisiblityState > 2)
if not identified then
return false
end
local unitDefID = Spring.GetUnitDefID(unitID)
if not (unitDefID and UnitDefs[unitDefID]) then
return false
end
return not Spring.Utilities.getMovetype(UnitDefs[unitDefID])
end
local function RadarDotCheck(unitID)
return true
end
local function Draw(extension,layer)
local FxLayer = RenderSequence[layer];
if (not FxLayer) then return end
local BeginDrawPass = "BeginDraw"..extension
local DrawPass = "Draw"..extension
local EndDrawPass = "EndDraw"..extension
for partClass,Units in pairs(FxLayer) do
local beginDraw = partClass[BeginDrawPass]
if (beginDraw) then
beginDraw()
local drawfunc = partClass[DrawPass]
if (not next(Units)) then
FxLayer[partClass]=nil
else
for unitID,UnitEffects in pairs(Units) do
if (not UnitEffects[1]) then
Units[unitID]=nil
else
if (unitID>-1) then
------------------------------------------------------------------------------------
-- render in unit/piece space ------------------------------------------------------
------------------------------------------------------------------------------------
glPushMatrix()
if gadget and not IsUnitPositionKnown(unitID) then
local x, y, z = Spring.GetUnitPosition(unitID)
local a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, a41, a42, a43, a44 = Spring.GetUnitTransformMatrix(unitID)
if a11 then
gl.MultMatrix(a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, x, y, z , a44)
else
glUnitMultMatrix(unitID)
end
else
glUnitMultMatrix(unitID)
end
--// render effects
for i=1,#UnitEffects do
local fx = UnitEffects[i]
if (fx.alwaysVisible or fx.visible) then
if (fx.piecenum) then
--// enter piece space
glPushMatrix()
glUnitPieceMultMatrix(unitID,fx.piecenum)
glScale(1,1,-1)
drawfunc(fx)
glPopMatrix()
--// leave piece space
else
fx[DrawPass](fx)
end
end
end
--// leave unit space
glPopMatrix()
else
------------------------------------------------------------------------------------
-- render in world space -----------------------------------------------------------
------------------------------------------------------------------------------------
for i=1,#UnitEffects do
local fx = UnitEffects[i]
if (fx.alwaysVisible or fx.visible) then
glPushMatrix()
if fx.projectile and not fx.worldspace then
local x,y,z = spGetProjectilePosition(fx.projectile)
glTranslate(x,y,z)
end
drawfunc(fx)
glPopMatrix()
end
end -- for
end -- if
end --if
end --for
end
partClass[EndDrawPass]()
end
end
end
local function DrawDistortionLayers()
glBlending(GL_ONE,GL_ONE)
for i=-50,50 do
Draw("Distortion",i)
end
glBlending(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
end
local function DrawParticlesOpaque()
if ( not anyFXVisible ) then return end
vsx, vsy, vpx, vpy = Spring.GetViewGeometry()
if (vsx~=oldVsx)or(vsy~=oldVsy) then
for _,partClass in pairs(fxClasses) do
if partClass.ViewResize then partClass.ViewResize(vsx, vsy) end
end
oldVsx, oldVsy = vsx, vsy
end
glDepthTest(true)
glDepthMask(true)
for i=-50,50 do
Draw("Opaque",i)
end
glDepthMask(false)
glDepthTest(false)
end
local function DrawParticles()
if ( not anyFXVisible ) then return end
glDepthTest(true)
--// Draw() (layers: -50 upto 0)
glAlphaTest(GL_GREATER, 0)
for i=-50,0 do
Draw("",i)
end
glAlphaTest(false)
--// DrawDistortion()
if (anyDistortionsVisible)and(DistortionClass) then
DistortionClass.BeginDraw()
gl.ActiveFBO(DistortionClass.fbo,DrawDistortionLayers)
DistortionClass.EndDraw()
end
--// Draw() (layers: 1 upto 50)
glAlphaTest(GL_GREATER, 0)
for i=1,50 do
Draw("",i)
end
glAlphaTest(false)
glDepthTest(false)
end
local function DrawParticlesWater()
if ( not anyFXVisible ) then return end
glDepthTest(true)
--// DrawOpaque()
glDepthMask(true)
for i=-50,50 do
Draw("Opaque",i)
end
glDepthMask(false)
--// Draw() (layers: -50 upto 50)
glAlphaTest(GL_GREATER, 0)
for i=-50,50 do
Draw("",i)
end
glAlphaTest(false)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Unit activity
local activeUnit = {}
local activeUnitCheckTime = {}
local unitDrawStatus = {}
local unitDrawStatusCheckTime = {}
local ACTIVE_CHECK_PERIOD = 15
local GetPriorityCheckTime = 0
local GetDynamicLupsCheckTime = 0
local GetPriorityConfig = Spring.GetConfigInt("LupsPriority") or 3
local GetDynamicLupsStatus = Spring.GetConfigInt("DynamicLups") or 0
local CONFIG_CHECK_PERIOD = 15
local function GetUnitIsActive(unitID)
if activeUnitCheckTime[unitID] and activeUnitCheckTime[unitID] > thisGameFrame then
return activeUnit[unitID]
end
activeUnitCheckTime[unitID] = thisGameFrame + ACTIVE_CHECK_PERIOD
activeUnit[unitID] = spGetUnitIsActive(unitID)
return activeUnit[unitID]
end
local function GetUnitDrawStatus(unitID)
if unitDrawStatusCheckTime[unitID] and unitDrawStatusCheckTime[unitID] > thisGameFrame then
return unitDrawStatus[unitID]
end
unitDrawStatusCheckTime[unitID] = thisGameFrame + ACTIVE_CHECK_PERIOD
unitDrawStatus[unitID] = (spGetUnitRulesParam(unitID, "nolupsdraw") == 1) or spGetUnitIsStunned(unitID)
return unitDrawStatus[unitID]
end
local function GetPriority(priority)
if GetPriorityCheckTime and GetPriorityCheckTime > thisGameFrame then
return priority > GetPriorityConfig
end
GetPriorityCheckTime = thisGameFrame + ACTIVE_CHECK_PERIOD
GetPriorityConfig = Spring.GetConfigInt("LupsPriority") or 3
return priority > GetPriorityConfig
end
local function GetDynamicLups()
if GetDynamicLupsCheckTime and GetDynamicLupsCheckTime > thisGameFrame then
return GetDynamicLupsStatus
end
GetDynamicLupsCheckTime = thisGameFrame + CONFIG_CHECK_PERIOD
GetDynamicLupsStatus = Spring.GetConfigInt("DynamicLups",0) or 0
return GetDynamicLupsStatus
end
local function ConvertRange(value)
local OldMax, OldMin, NewMax, NewMin = 50,30,5,1
local OldRange = (OldMax - OldMin)
local NewRange = (NewMax - NewMin)
value = (((value - OldMin) * NewRange) / OldRange) + NewMin
if value < 1 then value = 1 end
--value = (NewMax + NewMin) - value
return math.min(value)
end
local weight = 10
local timecheck = 0
local avgfps = 0
local storedfps = {}
local index = 1
local SAMPLE_RATE = 35
local index = 1
local skipfpscheck = false
for i=1,weight do
storedfps[i] = 200 --dummy value
avgfps = avgfps + storedfps[i]
end
local function GetAvgFPS()
if timecheck and timecheck > thisGameFrame then
return avgfps / weight
end
timecheck = thisGameFrame + SAMPLE_RATE
skipfpscheck = false
if index == weight + 1 then
index = 1
end
local oldfps = storedfps[index]
storedfps[index] = Spring.GetFPS()
avgfps = ((avgfps - oldfps) + storedfps[index])
index = index + 1
return avgfps / weight
end
local function GetReduceEffects(priority)
local avgFPS = GetAvgFPS()
if avgFPS < 68 then
if ConvertRange(avgFPS) < priority then
if not skipfpscheck then
timecheck = thisGameFrame + (SAMPLE_RATE * 4)
skipfpscheck = true
end
return true
end
end
return false
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local DrawWorldPreUnitVisibleFx
local DrawWorldVisibleFx
local DrawWorldReflectionVisibleFx
local DrawWorldRefractionVisibleFx
local DrawWorldShadowVisibleFx
local DrawScreenEffectsVisibleFx
local DrawInMiniMapVisibleFx
local function UpdateAllyTeamStatus()
local spec, specFullView = spGetSpectatingState()
if (specFullView) then
LocalAllyTeamID = scGetReadAllyTeam() or 0
else
LocalAllyTeamID = spGetLocalAllyTeamID() or 0
end
end
function IsPosInLos(x,y,z)
if LocalAllyTeamID == 0 then
UpdateAllyTeamStatus()
end
return LocalAllyTeamID == Script.ALL_ACCESS_TEAM or (LocalAllyTeamID ~= Script.NO_ACCESS_TEAM and Spring.IsPosInLos(x,y,z, LocalAllyTeamID))
end
function IsPosInRadar(x,y,z)
if LocalAllyTeamID == 0 then
UpdateAllyTeamStatus()
end
return LocalAllyTeamID == Script.ALL_ACCESS_TEAM or (LocalAllyTeamID ~= Script.NO_ACCESS_TEAM and Spring.IsPosInRadar(x,y,z, LocalAllyTeamID))
end
function IsPosInAirLos(x,y,z)
if LocalAllyTeamID == 0 then
UpdateAllyTeamStatus()
end
return LocalAllyTeamID == Script.ALL_ACCESS_TEAM or (LocalAllyTeamID ~= Script.NO_ACCESS_TEAM and Spring.IsPosInAirLos(x,y,z, LocalAllyTeamID))
end
function GetUnitLosState(unitID)
if LocalAllyTeamID == 0 then
UpdateAllyTeamStatus()
end
return LocalAllyTeamID == Script.ALL_ACCESS_TEAM or (LocalAllyTeamID ~= Script.NO_ACCESS_TEAM and (Spring.GetUnitLosState(unitID, LocalAllyTeamID) or {}).los) or false
end
local function IsUnitFXVisible(fx)
local unitActive = true
local unitID = fx.unit
local priority = fx.priority or 3
local disableOnLevel = fx.disableabovelevel or nil
if (disableOnLevel and GetPriority(priority+1)==false) then return false end
if GetPriority(priority) then return false end
if GetDynamicLups() == 1 then
if GetReduceEffects(priority) then return false end
end
if fx.onActive then
unitActive = GetUnitIsActive(unitID)
if (unitActive == nil) and GetPriority(5) then --because unitactive returns nil for enemy units, and onActive types are all airjets, we get the unit's velocity, and use that as an approximation to 'active' state --HACKY
local vx, vy, vz = spGetUnitVelocity(unitID)
if (vx~= nil and (vx~= 0 or vz~=0)) then
unitActive=true
end
end
end
if GetUnitDrawStatus(unitID) then
return false
elseif (not fx.onActive) or (unitActive) then
if fx.alwaysVisible then
return true
elseif (fx.Visible) then
return fx:Visible()
else
local unitRadius = (spGetUnitRadius(unitID) or 0) + 40
local r = fx.radius or 0
return Spring.IsUnitVisible(unitID, unitRadius + r, fx.noIconDraw)
end
else
return fx.alwaysVisible
end
end
local function IsProjectileFXVisible(fx)
local priority = fx.priority or 3
if GetPriority(priority) then return false end
if GetDynamicLups() == 1 then
if GetReduceEffects(priority) then return false end
end
if fx.alwaysVisible then
return true
elseif fx.Visible then
return fx:Visible()
else
local proID = fx.projectile
local x,y,z = Spring.GetProjectilePosition(proID)
if (IsPosInLos(x,y,z)and (spIsSphereInView(x,y,z,(fx.radius or 200)+100)) ) then
return true
end
end
end
local function IsWorldFXVisible(fx)
local priority = fx.priority or 3
if GetPriority(priority) then return false end
if GetDynamicLups() == 1 then
if GetReduceEffects(priority) then return false end
end
if fx.alwaysVisible then
return true
elseif (fx.Visible) then
return fx:Visible()
elseif (fx.pos) then
local pos = fx.pos
if (IsPosInLos(pos[1],pos[2],pos[3]))and
(spIsSphereInView(pos[1],pos[2],pos[3],(fx.radius or 200)+100))
then
return true
end
end
end
local function CreateVisibleFxList()
local removeFX = {}
local removeCnt = 1
for _,fx in pairs(particles) do
if ((fx.unit or -1) > -1) then
fx.visible = IsUnitFXVisible(fx)
if (fx.visible) then
if (not anyFXVisible) then anyFXVisible = true end
if (not anyDistortionsVisible) then anyDistortionsVisible = fx.pi.distortion end
end
elseif ((fx.projectile or -1) > -1) then
fx.visible = IsProjectileFXVisible(fx)
if (fx.visible) then
if (not anyFXVisible) then anyFXVisible = true end
if (not anyDistortionsVisible) then anyDistortionsVisible = fx.pi.distortion end
end
else
fx.visible = IsWorldFXVisible(fx)
if (fx.visible) then
if (not anyFXVisible) then anyFXVisible = true end
if (not anyDistortionsVisible) then anyDistortionsVisible = fx.pi.distortion end
elseif (fx.Valid and (not fx:Valid())) then
removeFX[removeCnt] = fx.id
removeCnt = removeCnt + 1
end
end
end
--Spring.Echo("Lups fx cnt", particles.GetIndexMax())
for i=1,removeCnt-1 do
RemoveParticles(removeFX[i])
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function CleanInvalidUnitFX()
local removeFX = {}
local removeCnt = 1
for layerID,layer in pairs(RenderSequence) do
for partClass,Units in pairs(layer) do
for unitID,UnitEffects in pairs(Units) do
if (not UnitEffects[1]) then
Units[unitID] = nil
else
if (unitID>-1) then
if (not spValidUnitID(unitID)) then --// UnitID isn't valid anymore, remove all its effects
for i=1,#UnitEffects do
local fx = UnitEffects[i]
removeFX[removeCnt] = fx.id
removeCnt = removeCnt + 1
end
Units[unitID]=nil
end
end
end
end
end
end
for i=1,removeCnt-1 do
RemoveParticles(removeFX[i])
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// needed to allow to use RemoveParticles in :Update of the particleclasses
local fxRemoveList = {}
function BufferRemoveParticles(id)
fxRemoveList[#fxRemoveList+1] = id
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local lastGameFrame = 0
local function GameFrame(_,n)
thisGameFrame = n
if ((not next(particles)) and (not effectsInDelay[1])) then return end
UpdateAllyTeamStatus()
--// create delayed FXs
if (effectsInDelay[1]) then
local remaingFXs,cnt={},1
for i=1,#effectsInDelay do
local fx = effectsInDelay[i]
if (fx.frame>thisGameFrame) then
remaingFXs[cnt]=fx
cnt=cnt+1
else
AddParticles(fx.class,fx.options, fx.id)
if (fx.frame-thisGameFrame>0) then
particles[fx.id]:Update(fx.frame-thisGameFrame)
end
end
end
effectsInDelay = remaingFXs
end
--// cleanup FX from dead/invalid units
CleanInvalidUnitFX()
--// update FXs
framesToUpdate = thisGameFrame - lastGameFrame
for _,partFx in pairs(particles) do
if (n>=partFx.dieGameFrame) then
--// lifetime ended
if (partFx.repeatEffect) then
if (type(partFx.repeatEffect)=="number") then
partFx.repeatEffect = partFx.repeatEffect - 1
if (partFx.repeatEffect==1) then partFx.repeatEffect = nil end
end
if (partFx.ReInitialize) then
partFx:ReInitialize()
else
partFx.dieGameFrame = partFx.dieGameFrame + partFx.life
end
else
--// we can't remove items from a table we are iterating atm, so just buffer them and remove them later
BufferRemoveParticles(partFx.id)
end
else
--// update particles
if (partFx.Update) then
partFx:Update(framesToUpdate)
end
end
end
--// now we can remove particles
if (#fxRemoveList>0) then
for i=1,#fxRemoveList do
RemoveParticles(fxRemoveList[i])
end
fxRemoveList = {}
end
end
local function Update(_,dt)
--// update frameoffset
frameOffset = spGetFrameTimeOffset()
--// Game Frame Update
local x = spGetGameFrame()
if ((x-lastGameFrame)>=1) then
GameFrame(nil,x)
lastGameFrame = x
end
--// check which fxs are visible
anyFXVisible = false
anyDistortionsVisible = false
if (next(particles)) then
CreateVisibleFxList()
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function CheckParticleClassReq(pi)
return
(canShader or (not pi.shader))and
(canFBO or (not pi.fbo))and
(canRTT or (not pi.rtt))and
(canCTT or (not pi.ctt))and
(canDistortions or (not pi.distortion))and
((not isIntel) or (pi.intel~=0))and
((not isMS) or (pi.ms~=0))
end
local function Initialize()
LupsConfig = LoadConfig("./lups.cfg")
--// set verbose level
local showWarnings = LupsConfig.showwarnings
if showWarnings then
local t = type(showWarnings)
if (t=="number") then
printErrorsAbove = showWarnings
elseif (t=="boolean") then
printErrorsAbove = PRIO_LESS
end
end
--// is distortion is supported?
DistortionClass = fxClasses["postdistortion"]
if DistortionClass then
fxClasses["postdistortion"]=nil --// remove it from default classes
local di = DistortionClass.pi
if (di) and CheckParticleClassReq(di) then
local fine = true
if (DistortionClass.Initialize) then fine = DistortionClass.Initialize() end
if (fine~=nil)and(fine==false) then
print(PRIO_LESS,'LUPS: disabled Distortions');
DistortionClass=nil
end
else
print(PRIO_LESS,'LUPS: disabled Distortions');
DistortionClass=nil
end
end
canDistortions = (DistortionClass~=nil)
--// get list of user disabled fx classes
local disableFX = {}
for i,v in pairs(LupsConfig.disablefx or {}) do
disableFX[i:lower()]=v;
end
local linkBackupFXClasses = {}
--// initialize particle classes
for fxName,fxClass in pairs(fxClasses) do
local fi = fxClass.pi --// .fi = fxClass.GetInfo()
if (not disableFX[fxName]) and (fi) and CheckParticleClassReq(fi) then
local fine = true
if (fxClass.Initialize) then fine = fxClass.Initialize() end
if (fine~=nil)and(fine==false) then
print(PRIO_LESS,'LUPS: "' .. fi.name .. '" FXClass removed (class requested it during initialization)');
fxClasses[fxName]=nil
if (fi.backup and fi.backup~="") then
linkBackupFXClasses[fxName] = fi.backup:lower()
end
if (fxClass.Finalize) then fxClass.Finalize() end
end
else --// unload particle class (not supported by this computer)
print(PRIO_LESS,'LUPS: "' .. fi.name .. '" FXClass removed (hardware doesn\'t support it)');
fxClasses[fxName]=nil
if (fi.backup and fi.backup~="") then
linkBackupFXClasses[fxName] = fi.backup:lower()
end
end
end
if Spring.GetConfigInt("lupsenablerefraction", 0) ~= 1 then
(gadgetHandler or widgetHandler):RemoveCallIn("DrawWorldRefraction")
Spring.Echo("Lups Refraction Pass Disabled")
end
if Spring.GetConfigInt("lupsenablereflection", 0) ~= 1 then
(gadgetHandler or widgetHandler):RemoveCallIn("DrawWorldReflection")
Spring.Echo("Lups Reflection Pass Disabled")
end
--// link backup FXClasses
for className,backupName in pairs(linkBackupFXClasses) do
fxClasses[className]=fxClasses[backupName]
end
--// link Distortion Class
fxClasses["postdistortion"]=DistortionClass
--// update screen geometric
--ViewResize(_,handler:GetViewSizes())
--// make global
GG.Lups = {}
GG.Lups.GetStats = GetStats
GG.Lups.GetErrorLog = GetErrorLog
GG.Lups.AddParticles = AddParticles
GG.Lups.GetParticles = GetParticles
GG.Lups.RemoveParticles = RemoveParticles
GG.Lups.AddParticlesArray = AddParticlesArray
GG.Lups.HasParticleClass = HasParticleClass
GG.Lups.IsPosInLos = IsPosInLos
for fncname,fnc in pairs(GG.Lups) do
handler:RegisterGlobal('Lups_'..fncname,fnc)
end
GG.Lups.Config = LupsConfig
nilDispList = gl.CreateList(function() end)
end
local function Shutdown()
for fncname,fnc in pairs(GG.Lups) do
handler:DeregisterGlobal('Lups_'..fncname)
end
GG.Lups = nil
for _,fxClass in pairs(fxClasses) do
if (fxClass.Finalize) then
fxClass.Finalize()
end
end
gl.DeleteList(nilDispList)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local this = widget or gadget
this.GetInfo = GetInfo
this.Initialize = Initialize
this.Shutdown = Shutdown
this.DrawWorldPreUnit = DrawParticlesOpaque
this.DrawWorld = DrawParticles
this.DrawWorldReflection = DrawParticlesWater
this.DrawWorldRefraction = DrawParticlesWater
this.ViewResize = ViewResize
this.Update = Update
if gadget then
this.DrawUnit = DrawUnit
--this.GameFrame = GameFrame; // doesn't work for unsynced parts >yet<
end
|
modifier_enchantress_untouchable_lua_debuff = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_enchantress_untouchable_lua_debuff:IsHidden()
return false
end
function modifier_enchantress_untouchable_lua_debuff:IsDebuff()
return true
end
function modifier_enchantress_untouchable_lua_debuff:IsStunDebuff()
return false
end
function modifier_enchantress_untouchable_lua_debuff:IsPurgable()
return true
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_enchantress_untouchable_lua_debuff:OnCreated( kv )
-- references
self.slow = self:GetAbility():GetSpecialValueFor( "slow_attack_speed" ) -- special value
self.duration = self:GetAbility():GetSpecialValueFor( "slow_duration" ) -- special value
end
function modifier_enchantress_untouchable_lua_debuff:OnRefresh( kv )
-- references
self.slow = self:GetAbility():GetSpecialValueFor( "slow_attack_speed" ) -- special value
self.duration = self:GetAbility():GetSpecialValueFor( "slow_duration" ) -- special value
end
function modifier_enchantress_untouchable_lua_debuff:OnDestroy( kv )
end
--------------------------------------------------------------------------------
-- Modifier Effects
function modifier_enchantress_untouchable_lua_debuff:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_PRE_ATTACK,
MODIFIER_EVENT_ON_ATTACK,
MODIFIER_EVENT_ON_ATTACK_FINISHED,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
}
return funcs
end
function modifier_enchantress_untouchable_lua_debuff:GetModifierPreAttack( params )
if IsServer() then
-- record the attack that causes slow
if not self.HasAttacked then
self.record = params.record
end
-- check if start attacking another
if params.target~=self:GetCaster() then
self.attackOther = true
end
end
end
function modifier_enchantress_untouchable_lua_debuff:OnAttack( params )
if IsServer() then
if params.record~=self.record then return end
-- let the debuff persists
self:SetDuration(self.duration, true)
self.HasAttacked = true
end
end
function modifier_enchantress_untouchable_lua_debuff:OnAttackFinished( params )
if IsServer() then
if params.attacker~=self:GetParent() then return end
-- destroy if cancel before attacks
if not self.HasAttacked then
self:Destroy()
end
-- destroy if finished attacking other units
if self.attackOther then
self:Destroy()
end
end
end
function modifier_enchantress_untouchable_lua_debuff:GetModifierAttackSpeedBonus_Constant()
if IsServer() then
if self:GetParent():GetAggroTarget()==self:GetCaster() then
return self.slow
else
return 0
end
end
return self.slow
end
--------------------------------------------------------------------------------
-- Graphics & Animations
function modifier_enchantress_untouchable_lua_debuff:GetEffectName()
return "particles/units/heroes/hero_enchantress/enchantress_untouchable.vpcf"
end
function modifier_enchantress_untouchable_lua_debuff:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW
end
|
require 'winapi'
pids = winapi.get_processes()
for _,pid in ipairs(pids) do
local P = winapi.process_from_id(pid)
local name = P:get_process_name(true)
if name then print(pid,name) end
P:close()
end
|
Locales ['en'] = {
['writingcontract'] = '%s plakası için kontrat yazılıyor.',
['soldvehicle'] = 'Aracı sicil numarasıyla sattınız. ~r~%s~s~',
['boughtvehicle'] = 'Aracı sicil numarasıyla satın aldınız. ~g~%s~s~',
['notyourcar'] = 'Bu araç senin değil!',
['nonearby'] = 'Yakında araç bulunamadı.',
['nonearbybuyer'] = 'Yakında alıcı bulunamadı.',
}
|
-- This is part of the "Affair" library.
-- This file handles sending a server's data to the main server list.
-- Luasockets must be installed for this to work. If you have Löve installed, this is already the case.
local http = require("socket.http")
print( "[UNADVERTISE] Attempting to connect" )
local URL = arg[1] or ""
local PORT = arg[2] or ""
print( "[ADVERTISE] Contacting: " .. URL )
local body = ""
body = body .. "port=" .. PORT.. "&"
local result, errCode, errorMsg, status = http.request( URL, body )
if errCode and errCode ~= 200 then
print("[ADVERTISE] Could not un-advertise: " .. errCode, status, "Correct URL?", URL )
end
-- Close this process:
os.exit()
|
data:extend(
{
{
type = "recipe",
name = "biotech-glass-pipe",
ingredients = {{"biotech-glass", 1}},
result = "biotech-glass-pipe",
requester_paste_multiplier = 4
},
{
type = "recipe",
name = "biotech-glass-pipe-to-ground",
ingredients =
{
{"wood", 20},
{"biotech-glass-pipe", 10},
{"biotech-glass", 5}
},
result_count = 2,
result = "biotech-glass-pipe-to-ground",
requester_paste_multiplier = 4
},
}
)
|
local cd_mgr = {}
function cd_mgr:get_cd( )
end
return cd_mgr
|
--[[
Copyright (c) 2016, Andrew Lewis <nerf@judo.za.org>
Copyright (c) 2016, Vsevolod Stakhov <vsevolod@highsecure.ru>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local lutil = require "lua_util"
local rspamd_logger = require "rspamd_logger"
local dkim_sign_tools = require "dkim_sign_tools"
local rspamd_util = require "rspamd_util"
if confighelp then
return
end
local settings = {
allow_envfrom_empty = true,
allow_hdrfrom_mismatch = false,
allow_hdrfrom_mismatch_local = false,
allow_hdrfrom_mismatch_sign_networks = false,
allow_hdrfrom_multiple = false,
allow_username_mismatch = false,
auth_only = true,
domain = {},
path = string.format('%s/%s/%s', rspamd_paths['DBDIR'], 'dkim', '$domain.$selector.key'),
sign_local = true,
selector = 'dkim',
symbol = 'DKIM_SIGNED',
try_fallback = true,
use_domain = 'header',
use_esld = true,
use_redis = false,
key_prefix = 'dkim_keys', -- default hash name
}
local N = 'dkim_signing'
local redis_params
local sign_func = rspamd_plugins.dkim.sign
local function dkim_signing_cb(task)
local ret,p = dkim_sign_tools.prepare_dkim_signing(N, task, settings)
if not ret then
return
end
if settings.use_redis then
local function try_redis_key(selector)
p.key = nil
p.selector = selector
local rk = string.format('%s.%s', p.selector, p.domain)
local function redis_key_cb(err, data)
if err or type(data) ~= 'string' then
rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM key for %s: %s",
rk, err)
else
p.rawkey = data
local sret, _ = sign_func(task, p)
if sret then
task:insert_result(settings.symbol, 1.0)
end
end
end
local rret = rspamd_redis_make_request(task,
redis_params, -- connect params
rk, -- hash key
false, -- is write
redis_key_cb, --callback
'HGET', -- command
{settings.key_prefix, rk} -- arguments
)
if not rret then
rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM key for %s", rk)
end
end
if settings.selector_prefix then
rspamd_logger.infox(rspamd_config, "Using selector prefix %s for domain %s", settings.selector_prefix, p.domain);
local function redis_selector_cb(err, data)
if err or type(data) ~= 'string' then
rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM selector for domain %s: %s", p.domain, err)
else
try_redis_key(data)
end
end
local rret = rspamd_redis_make_request(task,
redis_params, -- connect params
p.domain, -- hash key
false, -- is write
redis_selector_cb, --callback
'HGET', -- command
{settings.selector_prefix, p.domain} -- arguments
)
if not rret then
rspamd_logger.infox(rspamd_config, "cannot make request to load DKIM selector for %s", p.domain)
end
else
if not p.selector then
rspamd_logger.errx(task, 'No selector specified')
return false
end
try_redis_key(p.selector)
end
else
if (p.key and p.selector) then
p.key = lutil.template(p.key, {domain = p.domain, selector = p.selector})
if not rspamd_util.file_exists(p.key) then
rspamd_logger.debugm(N, task, 'file %s does not exists', p.key)
return false
end
local sret, _ = sign_func(task, p)
return sret
else
rspamd_logger.infox(task, 'key path or dkim selector unconfigured; no signing')
return false
end
end
end
local opts = rspamd_config:get_all_opt('dkim_signing')
if not opts then return end
for k,v in pairs(opts) do
if k == 'sign_networks' then
settings[k] = rspamd_map_add(N, k, 'radix', 'DKIM signing networks')
elseif k == 'path_map' then
settings[k] = rspamd_map_add(N, k, 'map', 'Paths to DKIM signing keys')
elseif k == 'selector_map' then
settings[k] = rspamd_map_add(N, k, 'map', 'DKIM selectors')
else
settings[k] = v
end
end
if not (settings.use_redis or settings.path or settings.domain or settings.path_map or settings.selector_map) then
rspamd_logger.infox(rspamd_config, 'mandatory parameters missing, disable dkim signing')
lutil.disable_module(N, "config")
return
end
if settings.use_redis then
redis_params = rspamd_parse_redis_server('dkim_signing')
if not redis_params then
rspamd_logger.errx(rspamd_config, 'no servers are specified, but module is configured to load keys from redis, disable dkim signing')
lutil.disable_module(N, "redis")
return
end
end
rspamd_config:register_symbol({
name = settings['symbol'],
callback = dkim_signing_cb
})
|
ENT.Base = "wac_hc_base"
ENT.Type = "anim"
ENT.Author = wac.author
ENT.Category = wac.aircraft.spawnCategory
ENT.Spawnable = true
ENT.AdminSpawnable = true
ENT.PrintName = "Little Bird AH-6"
ENT.Model = "models/flyboi/littlebird/littlebirda_fb.mdl"
ENT.TopRotor = {
model = "models/flyboi/littlebird/littlebirdrotorm_fb.mdl",
pos = Vector(-10,0,100),
}
ENT.BackRotor = {
dir = -1,
model = "models/flyboi/littlebird/littlebirdt_fb.mdl",
pos = Vector(-217,9,73),
}
ENT.EngineForce = 20
ENT.Weight = 1300
ENT.SmokePos = Vector(-90,0,50)
ENT.FirePos = Vector(-50,0,100)
ENT.Seats = {
{
pos = Vector(22, 15, 49),
exit = Vector(70,70,10),
weapons = {"M134", "Hydra 70"}
},
{
pos = Vector(22, -12, 49),
exit = Vector(70,-70,10),
},
}
ENT.Sounds = {
Start = "wac/heli/h6_start.wav",
Blades = "wac/heli/heli_loop_ext.wav",
Engine = "wac/heli/heli_loop_int.wav",
MissileAlert = "helicoptervehicle/missilenearby.mp3",
MinorAlarm = "helicoptervehicle/minoralarm.mp3",
LowHealth = "helicoptervehicle/lowhealth.mp3",
CrashAlarm = "helicoptervehicle/crashalarm.mp3",
}
ENT.Weapons = {
["M134"] = {
class = "wac_pod_gatling",
info = {
Pods = {
Vector(40,40,30),
Vector(40,-40,30),
},
}
},
["Hydra 70"] = {
class = "wac_pod_hydra",
info = {
Pods = {
Vector(50,50,40),
Vector(50,-50,40),
Sequential = false,
},
}
}
}
|
-- Small CSV helper
-- Source: http://lua-users.org/wiki/LuaCsv
local csv = {}
function csv.parse(line, sep)
local res = {}
local pos = 1
sep = sep or ','
while true do
local c = string.sub(line,pos,pos)
if (c == "") then break end
if (c == '"') then
local txt = ""
repeat
local startp,endp = string.find(line,'^%b""',pos)
txt = txt..string.sub(line,startp+1,endp-1)
pos = endp + 1
c = string.sub(line,pos,pos)
if (c == '"') then txt = txt..'"' end
until (c ~= '"')
table.insert(res,txt)
assert(c == sep or c == "")
pos = pos + 1
else
local startp,endp = string.find(line,sep,pos)
if (startp) then
table.insert(res,string.sub(line,pos,startp-1))
pos = endp + 1
else
table.insert(res,string.sub(line,pos))
break
end
end
end
return res
end
return csv
|
local args = {...}
local direction
-- Print usage
if #args ~= 3 then
print("Usage: harvest <x> <z> <left|right>")
return
else
-- left = 0; right = 1
direction = argument == "right" and 1 or 0
end
function checkItem(item)
for i = 1, 16 do
if turtle.getItemDetail(i) ~= nil and turtle.getItemDetail(i).name == item then
return turtle.select(i)
end
end
return false
end
function checkGrowth()
local _, data = turtle.inspectDown()
return (data ~= nil and data.name == "minecraft:wheat" and data.metadata == 7)
end
function placeSeed()
if checkItem("minecraft:wheat_seeds") then
turtle.placeDown()
end
end
function nextRow(z)
if z % 2 == 0 then
turtle.turnLeft()
turtle.forward()
turtle.turnLeft()
else
turtle.turnRight()
turtle.forward()
turtle.turnRight()
end
end
function turn(z)
if (z) % 2 == 0 then
turtle.turnLeft()
else
turtle.turnRight()
end
end
for z = 1, args[2] do
for x = 1, args[1] do
-- Harvest fully grown wheat
if checkGrowth() then
turtle.digDown()
end
-- Place seed. Only successful if above dirt.
placeSeed()
if x == tonumber(args[1]) then
if z == tonumber(args[2]) then
-- Back up if odd z level
if z % 2 ~= 0 then
for i = 1, x do
turtle.back()
end
end
turn(z + direction - 1)
for _ = 1, z - 1 do
turtle.forward()
end
turn(z + direction - 1)
else
-- Turn facing specified direction to next x row
nextRow(z + direction)
end
else
while not turtle.forward() do
turtle.dig()
end
end
end
end
|
Sharpen = 0
MotionBlur = 0
ViewWobble = 0
TrueViewWobble = 0
DisorientTime = 0
AdrenalineTime = 0
DrainTime = 0
ColorModify = {}
ColorModify[ "$pp_colour_addr" ] = 0
ColorModify[ "$pp_colour_addg" ] = 0
ColorModify[ "$pp_colour_addb" ] = 0
ColorModify[ "$pp_colour_brightness" ] = 0
ColorModify[ "$pp_colour_contrast" ] = 1
ColorModify[ "$pp_colour_colour" ] = 1
ColorModify[ "$pp_colour_mulr" ] = 0
ColorModify[ "$pp_colour_mulg" ] = 1
ColorModify[ "$pp_colour_mulb" ] = 1
GM.HighlightProps = { "prop_physics",
"prop_physics_override",
"prop_physics_respawnable",
"prop_ragdoll" }
GM.ViewDist = 0
GM.HitPos = Vector(0,0,0)
function GM:RenderScreenspaceEffects()
GAMEMODE:DoTrace()
GAMEMODE:ColorModInternal()
GAMEMODE:RenderLaser()
GAMEMODE:DrawLights()
end
function GM:ColorModInternal()
if Sharpen > 0 then
DrawSharpen( Sharpen, 0.5 )
Sharpen = math.Approach( Sharpen, 0, FrameTime() * 0.5 )
end
if MotionBlur > 0 then
DrawMotionBlur( 1 - MotionBlur, 1, 0 )
MotionBlur = math.Approach( MotionBlur, 0, FrameTime() * 0.03 )
end
local approach = FrameTime() * 0.2
ColorModify[ "$pp_colour_mulr" ] = math.Approach( ColorModify[ "$pp_colour_mulr" ], 0, approach )
ColorModify[ "$pp_colour_mulg" ] = math.Approach( ColorModify[ "$pp_colour_mulg" ], 0, approach )
ColorModify[ "$pp_colour_mulb" ] = math.Approach( ColorModify[ "$pp_colour_mulb" ], 0, approach )
ColorModify[ "$pp_colour_colour" ] = math.Approach( ColorModify[ "$pp_colour_colour" ], 1, approach * 1.5 )
ColorModify[ "$pp_colour_contrast" ] = math.Approach( ColorModify[ "$pp_colour_contrast" ], 1, approach )
ColorModify[ "$pp_colour_brightness" ] = math.Approach( ColorModify[ "$pp_colour_brightness" ], 0, approach )
ColorModify[ "$pp_colour_addr" ] = math.Approach( ColorModify[ "$pp_colour_addr" ], 0, approach )
ColorModify[ "$pp_colour_addg" ] = math.Approach( ColorModify[ "$pp_colour_addg" ], 0, approach )
ColorModify[ "$pp_colour_addb" ] = math.Approach( ColorModify[ "$pp_colour_addb" ], 0, approach )
if LocalPlayer():Team() == TEAM_STALKER then
if LocalPlayer():Alive() then
ColorModify[ "$pp_colour_addr" ] = .10
ColorModify[ "$pp_colour_addg" ] = .05
if tobool( GAMEMODE:GetInt( "StalkerEsp", 0 ) ) then
ColorModify[ "$pp_colour_mulr" ] = 0.35
ColorModify[ "$pp_colour_mulg" ] = 0.20
ColorModify[ "$pp_colour_brightness" ] = -0.15
ColorModify[ "$pp_colour_contrast" ] = 1.0
else
ColorModify[ "$pp_colour_mulr" ] = 0.25
ColorModify[ "$pp_colour_mulg" ] = 0.05
ColorModify[ "$pp_colour_brightness" ] = -0.05
ColorModify[ "$pp_colour_contrast" ] = 1.45
end
if DrainTime < CurTime() then
Sharpen = math.Approach( Sharpen, 2.5, FrameTime() * 0.8 )
ColorModify[ "$pp_colour_mulr" ] = 0.70
end
else
// dead stalker
ColorModify[ "$pp_colour_brightness" ] = -0.20
ColorModify[ "$pp_colour_addr" ] = 0.25
ColorModify[ "$pp_colour_mulr" ] = 0.30
ColorModify[ "$pp_colour_addg" ] = 0.05
end
else
local wep = LocalPlayer():GetActiveWeapon()
if IsValid( wep ) and wep:GetClass() == "weapon_ts_scanner" then
ColorModify[ "$pp_colour_mulr" ] = -1.10
ColorModify[ "$pp_colour_mulg" ] = -1.10
ColorModify[ "$pp_colour_mulb" ] = 1.70
ColorModify[ "$pp_colour_addr" ] = -0.10
ColorModify[ "$pp_colour_addg" ] = -0.10
ColorModify[ "$pp_colour_addb" ] = 0
ColorModify[ "$pp_colour_brightness" ] = 0.20
GAMEMODE:DrawStalker( ColorModify[ "$pp_colour_contrast" ] - 1.2 )
elseif IsValid( wep ) and wep:GetClass() == "weapon_ts_spec_scanner" then
ColorModify[ "$pp_colour_mulg" ] = -1.20
ColorModify[ "$pp_colour_addr" ] = -0.05
ColorModify[ "$pp_colour_addg" ] = -0.05
GAMEMODE:DrawStalker( ColorModify[ "$pp_colour_contrast" ] - 1.6 )
end
if not LocalPlayer():Alive() and LocalPlayer():Team() == TEAM_SPECTATOR then
ColorModify[ "$pp_colour_brightness" ] = -0.05
ColorModify[ "$pp_colour_contrast" ] = 0.95
ColorModify[ "$pp_colour_addr" ] = 0.05
end
end
DrawColorModify( ColorModify )
end
net.Receive( "Flay", function( len )
if LocalPlayer():Team() == TEAM_HUMAN then
DisorientTime = CurTime() + 20
ViewWobble = 7.5
MotionBlur = 0.9
Sharpen = 4.5
ColorModify[ "$pp_colour_mulg" ] = 3.5
ColorModify[ "$pp_colour_mulr" ] = 4.5
ColorModify[ "$pp_colour_addr" ] = 0.2
ColorModify[ "$pp_colour_addg" ] = 0.1
ColorModify[ "$pp_colour_colour" ] = -3.0
else
//ViewWobble = 2.5
Sharpen = 2.5
MotionBlur = 0.5
ColorModify[ "$pp_colour_colour" ] = -1.2
end
end )
net.Receive( "Scanner", function( len )
ColorModify[ "$pp_colour_contrast" ] = 1.80
Sharpen = 3.5
if LocalPlayer():Team() == TEAM_SPECTATOR then
ColorModify[ "$pp_colour_contrast" ] = 2.30
ColorModify[ "$pp_colour_mulb" ] = 2.10
ColorModify[ "$pp_colour_mulr" ] = -1.50
end
end )
net.Receive( "Stim", function( len )
local snd = table.Random( GAMEMODE.AutoMedic )
LocalPlayer():EmitSound( snd, 100, 100 )
AdrenalineTime = CurTime() + 12
ColorModify[ "$pp_colour_contrast" ] = 1.20
ColorModify[ "$pp_colour_mulr" ] = 1.20
MotionBlur = 0.8
Sharpen = 3.5
end )
VisionMat = Material( "stalker/vision" )
function GM:DrawStalker( amt )
local ang = Angle( 0, math.Rand( -0.2, 0.2 ), math.Rand( -0.05, 0.05 ) )
cam.Start3D( EyePos() + ( EyeAngles():Forward() * math.Rand( -1.2, 1.2 ) ), EyeAngles() + ang )
for k,v in pairs( team.GetPlayers( TEAM_STALKER ) ) do
if v:Alive() and amt > 0 then
local scale = ( 0.95 - ( math.Clamp( v:GetPos():Distance( LocalPlayer():GetPos() ), 0, 1500 ) / 1500 ) ) * amt
render.SuppressEngineLighting( true )
render.SetBlend( scale )
render.MaterialOverride( VisionMat )
render.SetColorModulation( 1.0, 0.2, 0 )
cam.IgnoreZ( false )
v:SetupBones()
v:DrawModel()
render.SuppressEngineLighting( false )
render.SetColorModulation( 1, 1, 1 )
render.SetBlend( 1.0 )
render.MaterialOverride( 0 )
end
end
cam.End3D()
end
LightMat = Material( "sprites/light_ignorez" )
BeamMat = Material( "effects/lamp_beam" )
function GM:DrawLights()
for k,v in pairs( team.GetPlayers( TEAM_HUMAN ) ) do
if not v.PixVis then
v.PixVis = util.GetPixelVisibleHandle()
end
if v:GetNWBool( "Flashlight", false ) and v != LocalPlayer() then
local id = v:LookupAttachment( "anim_attachment_LH" )
local att = v:GetAttachment( id )
if att then
local vis = util.PixelVisible( att.Pos, 16, v.PixVis )
local norm = ( att.Ang + Angle(0,90,0) ):Forward()
local vnorm = ( att.Pos - EyePos() ):GetNormal()
local dot = vnorm:Dot( norm * -1 )
if dot > 0 and vis > 0 then
local dist = math.Clamp( att.Pos:Distance( EyePos() ), 50, 500 )
local size = math.Clamp( dist * dot, 2, 40 )
local alpha = math.Clamp( ( 500 - dist ) * dot, 0, 255 )
local col = Color( 255, 255, 200, alpha )
cam.Start3D( EyePos(), EyeAngles() )
render.SetMaterial( LightMat )
render.DrawSprite( att.Pos, size, size, col )
render.DrawSprite( att.Pos, size * 0.25, size * 0.25, Color( 255, 255, 255, alpha ) )
cam.End3D()
end
end
end
end
end
ScannerMat = Material( "models/props_combine/stasisshield_sheet" )
SpeccyMat = Material( "effects/combine_binocoverlay" )
function GM:DrawScreenEffects()
local wep = LocalPlayer():GetActiveWeapon()
if IsValid( wep ) and wep:GetClass() == "weapon_ts_scanner" then
render.UpdateScreenEffectTexture()
ScannerMat:SetFloat( "$envmap", 0 )
ScannerMat:SetFloat( "$alpha", 0.5 )
ScannerMat:SetFloat( "$refractamount", 0.003 )
ScannerMat:SetInt( "$ignorez", 1 )
render.SetMaterial( ScannerMat )
render.DrawScreenQuad()
elseif IsValid( wep ) and wep:GetClass() == "weapon_ts_spec_scanner" then
render.UpdateScreenEffectTexture()
SpeccyMat:SetFloat( "$envmap", 0 )
SpeccyMat:SetFloat( "$alpha", 0.5 )
SpeccyMat:SetFloat( "$refractamount", 0.003 )
SpeccyMat:SetInt( "$ignorez", 1 )
render.SetMaterial( SpeccyMat )
render.DrawScreenQuad()
end
end
local matLaser = Material( "sprites/light_glow02_add" )
//local matBeam = Material( "sprites/bluelaser1" )
function GM:RenderLaser()
local lp = LocalPlayer()
for _, v in pairs( player.GetAll() ) do
if v:Team() == TEAM_HUMAN and v:GetNWBool( "PickedLaser", false ) then
local wep = v:GetActiveWeapon()
if IsValid( wep ) and wep.CanDrawLaser then
if wep:CanDrawLaser() then
local look = ( v:EyeAngles() + v:GetPunchAngle() )
local dir = look:Forward()
--[[local vm = v:GetViewModel( 0 )
if not IsValid( vm ) then break end
local tbl = vm:GetAttachment( wep.LaserAttachment )
//local lasforward
--[[if v == lp or ( lp:GetObserverMode() == OBS_MODE_IN_EYE and lp:GetObserverTarget() == v ) then
local ang = tbl.Ang or Angle()
ang:RotateAroundAxis( look:Up(), wep.LaserOffset.p )
ang:RotateAroundAxis( look:Forward(), wep.LaserOffset.r )
ang:RotateAroundAxis( look:Right(), wep.LaserOffset.y )
local forward = ang:Forward()
//lasforward = tbl.Ang:Forward()
forward = forward * wep.LaserScale
dir = dir + forward
end]]
local trace = {}
trace.start = v:GetShootPos()
trace.endpos = trace.start + dir * 9000
trace.filter = { v, weap, lp }
trace.mask = MASK_SOLID
local tr = util.TraceLine( trace )
local dist = math.Clamp( tr.HitPos:Distance( EyePos() ), 0, 500 )
local size = math.Rand( 2, 4 ) + ( dist / 500 ) * 6
local col = Color( 255, 0, 0, 255 )
if v == lp and IsValid( GAMEMODE.TargetEnt ) and GAMEMODE.TargetEnt:IsPlayer() and GAMEMODE.TargetEnt:Team() == TEAM_HUMAN then
size = size + math.Rand( 0.5, 2.0 )
elseif v != lp then
size = math.Rand( 0, 1 ) + ( dist / 500 ) * 6
end
cam.Start3D( EyePos(), EyeAngles() )
local norm = ( EyePos() - tr.HitPos ):GetNormal()
render.SetMaterial( matLaser )
render.DrawQuadEasy( tr.HitPos + norm * size, norm, size, size, col, 0 )
--[[if v == lp then
local start = tbl.Pos + ( lasforward * -5 ) + wep.LaserBeamOffset
render.SetMaterial( matBeam )
for i=0,254 do
render.DrawBeam( start, start + dir * 0.1, 2, 0, 12, Color( 255, 0, 0, 255 - i ) )
start = start + dir * 0.1
end
end]]
cam.End3D()
end
end
end
end
end
function GM:DoTrace()
local lp = LocalPlayer()
if IsValid( lp ) then
if lp:GetObserverMode() > OBS_MODE_NONE and lp:GetObserverMode() != OBS_MODE_ROAMING then
GAMEMODE.TargetEnt = lp:GetObserverTarget()
GAMEMODE.ViewDist = 0
if IsValid( GAMEMODE.TargetEnt ) then
GAMEMODE.HitPos = GAMEMODE.TargetEnt:GetPos()
end
return
end
local dir = ( lp:EyeAngles() + lp:GetPunchAngle() ):Forward()
local trace = {}
trace.start = lp:GetShootPos()
trace.endpos = trace.start + dir * 9000
trace.filter = { lp, lp:GetActiveWeapon(), lp:GetNetworkedEntity( "Scanner" ) }
trace.mask = MASK_SHOT
local tr = util.TraceLine( trace )
GAMEMODE.ViewDist = tr.HitPos:Distance( EyePos() )
GAMEMODE.HitPos = tr.HitPos
GAMEMODE.TargetEnt = tr.Entity
end
end
function GM:PreDrawHalos()
if not GetGlobalBool( "InRound", false ) or not IsValid( GAMEMODE.TargetEnt ) or not LocalPlayer():Alive() then return end
if LocalPlayer():Team() == TEAM_HUMAN or ( LocalPlayer():Team() == TEAM_SPECTATOR and LocalPlayer():Alive() ) then
local dist = math.Clamp( GAMEMODE.ViewDist, 0, 800 )
local scale = 1 - ( dist / 800 )
if GAMEMODE.TargetEnt:IsPlayer() and GAMEMODE.TargetEnt:Team() == TEAM_HUMAN then
local hp = math.Clamp( GAMEMODE.TargetEnt:Health(), 1, 100 )
local sc = hp / 100
halo.Add( { GAMEMODE.TargetEnt, GAMEMODE.TargetEnt:GetActiveWeapon() }, Color( 255 * ( 1 - sc ), 255 * sc, 100 * sc, 255 * scale ), 2 * scale, 2 * scale, 1, 1, false )
elseif GAMEMODE.TargetEnt:GetClass() == "sent_droppedgun" or GAMEMODE.TargetEnt:GetClass() == "sent_tripmine" or GAMEMODE.TargetEnt:GetClass() == "sent_scanner" or GAMEMODE.TargetEnt:GetClass() == "sent_seeker" then
halo.Add( {GAMEMODE.TargetEnt}, Color( 0, 255, 100, 255 * scale ), 2 * scale, 2 * scale, 1, 1, false )
elseif GAMEMODE.TargetEnt:GetClass() == "prop_ragdoll" then
halo.Add( {GAMEMODE.TargetEnt}, Color( 255, 0, 0, 255 * scale ), 2 * scale, 2 * scale, 1, 1, false )
end
elseif LocalPlayer():Team() == TEAM_STALKER then
local dist = math.Clamp( GAMEMODE.ViewDist, 0, 800 )
local scale = 1 - ( dist / 800 )
if GAMEMODE:GetInt( "MenuChoice" ) == 2 and GAMEMODE.TargetEnt:IsPlayer() and GAMEMODE.TargetEnt:Team() == TEAM_HUMAN then
halo.Add( { GAMEMODE.TargetEnt, GAMEMODE.TargetEnt:GetActiveWeapon() }, Color( 255, 255, 255, 255 * scale ), 2 * scale, 2 * scale, 1, 1, false )
elseif table.HasValue( GAMEMODE.HighlightProps, GAMEMODE.TargetEnt:GetClass() ) then
if GAMEMODE.TargetEnt:GetClass() == "prop_ragdoll" then
halo.Add( {GAMEMODE.TargetEnt}, Color( 0, 255, 0, 255 * scale ), 2 * scale, 2 * scale, 1, 1, false )
elseif GAMEMODE.TargetEnt:GetClass() == "sent_scanner" then
halo.Add( {GAMEMODE.TargetEnt}, Color( 255, 0, 0, 255 * scale ), 2 * scale, 2 * scale, 1, 1, false )
else
halo.Add( {GAMEMODE.TargetEnt}, Color( 0, 200, 255, 255 * scale ), 2 * scale, 2 * scale, 1, 1, false )
end
end
end
end
function GM:GetMotionBlurValues( y, x, fwd, spin )
if LocalPlayer():Alive() and LocalPlayer():Health() <= 25 and LocalPlayer():Team() == TEAM_HUMAN then
local scale = LocalPlayer():Health() / 25
fwd = 0.5 - ( scale * 0.5 )
ViewWobble = 0.5 - 0.5 * scale
end
if LocalPlayer():Alive() and LocalPlayer():Health() <= 50 and LocalPlayer():Team() == TEAM_STALKER then
local scale = LocalPlayer():Health() / 50
fwd = 1 - scale
ViewWobble = 0.5 - 0.5 * scale
end
if DisorientTime > CurTime() then
if not LocalPlayer():Alive() then
DisorientTime = 0
end
local scale = ( DisorientTime - CurTime() ) / 20
local newx, newy = RotateAroundCoord( 0, 0, 1.0, scale * 0.05 )
return newy, newx, fwd, spin
end
return y, x, fwd, spin
end
function RotateAroundCoord( x, y, speed, dist )
local newx = x + math.sin( CurTime() * speed ) * dist
local newy = y + math.cos( CurTime() * speed ) * dist
return newx, newy
end
function GM:CalcView( ply, origin, angle, fov )
local vel = ply:GetVelocity()
local ang = ply:EyeAngles()
ViewWobble = math.Approach( ViewWobble, 0, FrameTime() * 0.2 )
TrueViewWobble = math.Approach( TrueViewWobble, ViewWobble, FrameTime() * 0.4 )
if ViewWobble > 0 then
angle.roll = angle.roll + math.sin( CurTime() + GAMEMODE:TimeSeed( 1, -2, 2 ) ) * TrueViewWobble
angle.pitch = angle.pitch + math.sin( CurTime() + GAMEMODE:TimeSeed( 2, -2, 2 ) ) * TrueViewWobble
angle.yaw = angle.yaw + math.sin( CurTime() + GAMEMODE:TimeSeed( 3, -2, 2 ) ) * TrueViewWobble
end
return self.BaseClass:CalcView( ply, origin, angle, fov )
end
|
local _, ADDONSELF = ...
local L = ADDONSELF.L
local RegEvent = ADDONSELF.regevent
local BattleZoneHelper = ADDONSELF.BattleZoneHelper
local RegisterKeyChangedCallback = ADDONSELF.RegisterKeyChangedCallback
if HONOR_THISWEEK == nil then HONOR_THISWEEK = "This Week" end
if HONOR_LASTWEEK == nil then HONOR_LASTWEEK = "Last Week" end
local winratestats = {
HONOR_TODAY,
HONOR_YESTERDAY,
HONOR_THISWEEK,
HONOR_LASTWEEK,
HONOR_LIFETIME,
}
local panelheight = (#winratestats) * 20
local f = CreateFrame("Frame", nil, HonorFrame or PVPFrame, BackdropTemplateMixin and "BackdropTemplate" or nil)
f:SetBackdrop({
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
tile = true,
tileEdge = true,
tileSize = 16,
edgeSize = 24,
insets = { left = 4, right = 4, top = 4, bottom = 4 },
})
-- f:SetBackdropColor(0, 0, 0)
f:SetPoint("TOPLEFT", HonorFrame or PVPFrame, "TOPRIGHT" , -30, -15)
f:SetWidth(260)
f:SetHeight((30 + panelheight + 10) * (BattleZoneHelper.IsBCC and 4 or 3))
local loc = 30 + panelheight
local function nextloc()
loc = loc - 30 - panelheight
return loc
end
local function Today()
return math.floor((time() + time(date("*t", time())) - time(date("!*t", time()))) / 86400)
end
local labels = {}
local function DrawStat(bgid)
local p = CreateFrame("Frame", nil, f, BackdropTemplateMixin and "BackdropTemplate" or nil)
p:SetBackdrop({
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
edgeSize = 16,
})
p:SetPoint("TOPLEFT", f, 15, -15 + nextloc())
p:SetWidth(230)
p:SetHeight(30 + panelheight + 10)
-- p:SetScript("OnMouseUp", function()
-- DEFAULT_CHAT_FRAME.editBox:SetText(DEFAULT_CHAT_FRAME.editBox:GetText() .. BattleZoneHelper.BGID_MAPNAME_MAP[bgid] .. " " .. labels[bgid]:GetText())
-- DEFAULT_CHAT_FRAME.editBox:Show()
-- end)
labels[bgid] = {}
do
local t = p:CreateFontString(nil, "ARTWORK", "GameFontNormal")
t:SetText(BattleZoneHelper.BGID_MAPNAME_MAP[bgid] .. " " .. L["Win rate"])
t:SetPoint("TOPLEFT", p, 10, -10)
end
local l = -10
for i, n in pairs(winratestats) do
local t = p:CreateFontString(nil, "ARTWORK", "GameFontWhite")
t:SetPoint("TOPLEFT", p, 20, -10 + i * (-20))
-- t:SetText(L["Win rate"] .. " " .. n .. ": " )
-- labels[bgid] = t
labels[bgid][n] = t
end
end
local function UpdateStatLabel(l, n, win, total)
local win = win or 0
local total = total or 0
local rate = ""
if total > 0 then
rate = "= " .. NORMAL_FONT_COLOR:WrapTextInColorCode((math.floor(win / total * 10000) / 100) .. "%")
end
l:SetText(n .. ": " .. string.format("%s/%s %s", GREEN_FONT_COLOR:WrapTextInColorCode(win), YELLOW_FONT_COLOR:WrapTextInColorCode(total), rate))
end
local function UpdateStatLabels()
local today = Today()
for bgid, ls in pairs(labels) do
local stat = {}
for _, n in pairs(winratestats) do
stat[n] = {}
end
stat[HONOR_TODAY].win = (BatteInfoStat[bgid][today] or {}).win
stat[HONOR_TODAY].total = (BatteInfoStat[bgid][today] or {}).total
stat[HONOR_YESTERDAY].win = (BatteInfoStat[bgid][today - 1] or {}).win
stat[HONOR_YESTERDAY].total = (BatteInfoStat[bgid][today - 1] or {}).total
stat[HONOR_LIFETIME].win = (BatteInfoStat[bgid] or {}).win
stat[HONOR_LIFETIME].total = (BatteInfoStat[bgid] or {}).total
-- this week
do
local s = {}
s.win = 0
s.total = 0
for i = 0, 6 do
s.win = s.win + ((BatteInfoStat[bgid][today - i] or {}).win or 0)
s.total = s.total + ((BatteInfoStat[bgid][today - i] or {}).total or 0)
end
stat[HONOR_THISWEEK] = s
end
-- last week
do
local s = {}
s.win = 0
s.total = 0
for i = 7, 13 do
s.win = s.win + ((BatteInfoStat[bgid][today - i] or {}).win or 0)
s.total = s.total + ((BatteInfoStat[bgid][today - i] or {}).total or 0)
end
stat[HONOR_LASTWEEK] = s
end
for n, l in pairs(ls) do
UpdateStatLabel(l, n, stat[n].win, stat[n].total)
end
-- local stat = BatteInfoStat[bgid]
end
end
local FACTION_HORDE = 0
local FACTION_ALLIANCE = 1
local function PlayerFaction()
local factionGroup = UnitFactionGroup("player");
if ( factionGroup == "Alliance" ) then
return FACTION_ALLIANCE
else
return FACTION_HORDE
end
end
local scorerecorded = false
RegEvent("PLAYER_ENTERING_WORLD", function()
scorerecorded = false
end)
RegEvent("UPDATE_BATTLEFIELD_STATUS", function()
if scorerecorded then
return
end
local battlefieldWinner = GetBattlefieldWinner()
if battlefieldWinner then
local battleGroundID = BattleZoneHelper.MAPNAME_BGID_MAP[GetRealZoneText()]
local win = battlefieldWinner == PlayerFaction()
if battleGroundID then
local today = Today()
BatteInfoStat[battleGroundID] = BatteInfoStat[battleGroundID] or {}
BatteInfoStat[battleGroundID][today] = BatteInfoStat[battleGroundID][today] or {}
local stats = {BatteInfoStat[battleGroundID], BatteInfoStat[battleGroundID][today]}
for _, stat in pairs(stats) do
stat.win = stat.win or 0
stat.total = stat.total or 0
stat.total = stat.total + 1
if win then
stat.win = stat.win + 1
end
end
scorerecorded = true
end
UpdateStatLabels()
end
end)
RegEvent("ADDON_LOADED", function()
BatteInfoStat = BatteInfoStat or {}
for _, id in pairs(BattleZoneHelper.MAPNAME_BGID_MAP) do
BatteInfoStat[id] = BatteInfoStat[id] or {
start = time(),
}
DrawStat(id)
end
UpdateStatLabels()
RegisterKeyChangedCallback("stat_window", function(v)
if v then
f:Show()
else
f:Hide()
end
end)
end)
|
local lfs = require"lfs"
print(_VERSION)
print(os.getenv("OS") .. " " .. os.getenv("PROCESSOR_ARCHITECTURE") .. " CPUx" .. os.getenv("NUMBER_OF_PROCESSORS"))
--_ENV
_HOME = lfs.currentdir();
print("APP_HOME=", _HOME)
require "config"
require "lua.main"
main()
|
workspace "Commodore64Emulator"
architecture "x64"
configurations {
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
-- Include directories relaative to root folder (solution directory)
IncludeDir = {}
project "Commodore64Emulator"
location "Commodore64Emulator"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files {
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
}
includedirs {
"%{prj.name}/src"
}
|
/*#################################################
### GoldenHUDV3 By chredeur ###
#################################################*/
local vehiclehide = false if GoldenHUDV3.VehicleEnable == true && GoldenHUDV3.Vehicle == "vcmod" then vehiclehide = true end
local HideElementsTable = {
["DarkRP_HUD"] = true,
["DarkRP_ArrestedHUD"] = false,
["DarkRP_EntityDisplay"] = false,
["DarkRP_ZombieInfo"] = true,
["DarkRP_LocalPlayerHUD"] = true,
["DarkRP_Hungermod"] = true,
["DarkRP_Agenda"] = true,
["CHudHealth"] = GoldenHUDV3.EnableAmmoBar,
["CHudBattery"] = GoldenHUDV3.EnableAmmoBar,
["CHudSuitPower"] = GoldenHUDV3.EnableAmmoBar,
["CHudAmmo"] = GoldenHUDV3.EnableAmmoBar,
["CHudSecondaryAmmo"] = GoldenHUDV3.EnableAmmoBar,
["CHudCrosshair"] = false,
["Cookingmod_Hunger"] = GoldenHUDV3.EnableCompatibilityACM,
["Cookingmod_Thirst"] = GoldenHUDV3.EnableCompatibilityACM,
["MedicMod_HUD"] = false,
["MedicMod_DeathPanel"] = false,
["VCMod_Health"] = vehiclehide,
["VCMod_Damage"] = vehiclehide,
["VCMod_ELS_Lights"] = vehiclehide,
["VCMod_ELS_Siren"] = vehiclehide,
["VCMod_Fuel"] = vehiclehide,
["VCMod_Name"] = vehiclehide,
["VCMod_Icons"] = vehiclehide,
}
local hearticon = Material( "golden_hud_v3/heart.png" )
local foodicon = Material( "golden_hud_v3/hamburger.png" )
local armoricon = Material( "golden_hud_v3/shield.png" )
local thirsticon = Material( "golden_hud_v3/water-bottle.png" )
local ammoicon = Material( "golden_hud_v3/ammo.png" )
local gunicon = Material( "golden_hud_v3/gun.png" )
local moneyicon = Material( "golden_hud_v3/money.png" )
local health = 0
local armor = 0
local food = 0
local thirst = 0
local money
hook.Add("HUDPaint","GoldenHudV3", function()
local ply = LocalPlayer()
local armory = 0
local foody = 0
local thirsty = 0
local moneyy = 0
local boxsize = 40
local boxfoody = 0
local boxarmor = 0
local boxthirst = 0
local boxmoney = 0
health = Lerp( FrameTime(), health, ply:Health())
-- Confif Check Armor --
if GoldenHUDV3.ArmorBar then
armor = Lerp( FrameTime(), armor, ply:Armor())
armory = 35
boxsize = boxsize + 35
boxarmor = 35
end
-- Confif Check Food --
if GoldenHUDV3.FoodBar then
food = Lerp( FrameTime(), food, ply:getDarkRPVar("Energy") or 0)
foody = 35
boxsize = boxsize + 35
boxfoody = 35
end
-- Config Check Thirst --
if GoldenHUDV3.EnableCompatibilityACM then
thirst = Lerp( FrameTime(), thirst, ply:getDarkRPVar("Thirst") or 0)
thirsty = 35
boxsize = boxsize + 35
boxthirst = 35
end
-- Config Check Money --
if GoldenHUDV3.MoneyBar then
money = DarkRP.formatMoney(ply:getDarkRPVar("money"))
moneyy = 35
boxsize = boxsize + 35
boxmoney = 35
end
-- Background --
draw.RoundedBox(0, 10, ScrH() - 50 - boxarmor - boxfoody - boxthirst - boxmoney, 360, boxsize, GoldenHUDV3.BackgroundColor)
-- Health --
draw.RoundedBox(0, 14, ScrH() - 45 - armory - foody - thirsty - moneyy, 30, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(0, 50, ScrH() - 45 - armory - foody - thirsty - moneyy, 316, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(5, 55, ScrH() - 40.55 - armory - foody - thirsty - moneyy, 306, 21, GoldenHUDV3.BackgroundHealthColor)
draw.RoundedBox(5, 55, ScrH() - 40.55 - armory - foody - thirsty - moneyy, math.Clamp(health, 0, 100) * 3.06, 21, GoldenHUDV3.HealthColor)
draw.SimpleText(math.Round(health).."%", "GoldenHudV3Font", 202, ScrH() - 44 - armory - foody - thirsty - moneyy, GoldenHUDV3.HeaderTextColor, TEXT_ALIGN_CENTER)
surface.SetMaterial( hearticon )
surface.SetDrawColor(GoldenHUDV3.IconColor)
surface.DrawTexturedRect( 18, ScrH() - 41 - armory - foody - thirsty - moneyy, 22, 22 )
-- Armor --
if GoldenHUDV3.ArmorBar then
draw.RoundedBox(0, 14, ScrH() - 45 - foody - thirsty - moneyy, 30, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(0, 50, ScrH() - 45 - foody - thirsty - moneyy, 316, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(5, 55, ScrH() - 40.55 - foody - thirsty - moneyy, 306, 21, GoldenHUDV3.BackgroundArmorColor)
draw.RoundedBox(5, 55, ScrH() - 40.55 - foody - thirsty - moneyy, math.Clamp(armor, 0, 100) * 3.06, 21, GoldenHUDV3.ArmorColor)
draw.SimpleText(math.Round(armor).."%", "GoldenHudV3Font", 202, ScrH() - 44 - foody - thirsty - moneyy, GoldenHUDV3.HeaderTextColor, TEXT_ALIGN_CENTER)
surface.SetMaterial( armoricon )
surface.SetDrawColor(GoldenHUDV3.IconColor)
surface.DrawTexturedRect( 18, ScrH() - 41 - foody - thirsty - moneyy, 22, 22 )
end
-- Food --
if GoldenHUDV3.FoodBar then
draw.RoundedBox(0, 14, ScrH() - 45 - thirsty - moneyy, 30, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(0, 50, ScrH() - 45 - thirsty - moneyy, 316, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(5, 55, ScrH() - 40.55 - thirsty - moneyy, 306, 21, GoldenHUDV3.BackgroundFoodColor)
draw.RoundedBox(5, 55, ScrH() - 40.55 - thirsty - moneyy, math.Clamp(food, 0, 100) * 3.06, 21, GoldenHUDV3.FoodColor)
draw.SimpleText(math.Round(food).."%", "GoldenHudV3Font", 202, ScrH() - 44 - thirsty - moneyy, GoldenHUDV3.HeaderTextColor, TEXT_ALIGN_CENTER)
surface.SetMaterial( foodicon )
surface.SetDrawColor(GoldenHUDV3.IconColor)
surface.DrawTexturedRect( 18, ScrH() - 41 - thirsty - moneyy, 22, 22 )
end
-- Thirst --
if GoldenHUDV3.EnableCompatibilityACM then
draw.RoundedBox(0, 14, ScrH() - 45 - moneyy, 30, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(0, 50, ScrH() - 45 - moneyy, 316, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(5, 55, ScrH() - 40.55 - moneyy, 306, 21, GoldenHUDV3.BackgroundThirstColor)
draw.RoundedBox(5, 55, ScrH() - 40.55 - moneyy, math.Clamp(thirst, 0, 100) * 3.06, 21, GoldenHUDV3.ThirstColor)
draw.SimpleText(math.Round(thirst).."%", "GoldenHudV3Font", 202, ScrH() - 44 - moneyy, GoldenHUDV3.HeaderTextColor, TEXT_ALIGN_CENTER)
surface.SetMaterial( thirsticon )
surface.SetDrawColor(GoldenHUDV3.IconColor)
surface.DrawTexturedRect( 18, ScrH() - 41 - moneyy, 22, 22 )
end
-- Money --
if GoldenHUDV3.MoneyBar then
draw.RoundedBox(0, 14, ScrH() - 45, 30, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(0, 50, ScrH() - 45, 316, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(5, 55, ScrH() - 40.55, 306, 21, GoldenHUDV3.MoneyColor)
draw.SimpleText(money, "GoldenHudV3Font", 202, ScrH() - 43, GoldenHUDV3.HeaderTextColor, TEXT_ALIGN_CENTER)
surface.SetMaterial( moneyicon )
surface.SetDrawColor(GoldenHUDV3.IconColor)
surface.DrawTexturedRect( 18, ScrH() - 41, 22, 22 )
end
end )
hook.Add("HUDPaint","GoldenHudV3.Ammo", function()
-- Ammo --
if GoldenHUDV3.EnableAmmoBar then
local ply = LocalPlayer()
if ply:InVehicle() then return end
if !IsValid(ply:GetActiveWeapon()) then return end
wep = ply:GetActiveWeapon()
total = ply:GetAmmoCount(wep:GetPrimaryAmmoType())
clip = wep:Clip1()
nicename = wep:GetPrintName()
if clip < 0 or table.HasValue( GoldenHUDV3.BlackListWeapon or "weapon_physcannon", wep:GetClass() ) then return end
if string.len(nicename) > 25 then nicename = string.Left( nicename, 20 ) .. "..." end
-- Background --
draw.RoundedBox(0, ScrW() - 273 , ScrH() - 85, 260, 75, GoldenHUDV3.BackgroundColor)
-- Weapons Name --
draw.RoundedBox(0, ScrW() - 267, ScrH() - 80, 30, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(0, ScrW() - 230, ScrH() - 80, 210, 30, GoldenHUDV3.HeaderColor)
surface.SetMaterial( gunicon )
surface.SetDrawColor(GoldenHUDV3.IconColor)
surface.DrawTexturedRect( ScrW() - 263, ScrH() - 77, 22, 22 )
draw.SimpleText( nicename, "GoldenHudV3Font", ScrW() - 222, ScrH() - 77, GoldenHUDV3.HeaderTextColor, TEXT_ALIGN_LEFT )
-- Weapons Ammo --
draw.RoundedBox(0, ScrW() - 267, ScrH() - 45, 30, 30, GoldenHUDV3.HeaderColor)
draw.RoundedBox(0, ScrW() - 230, ScrH() - 45, 210, 30, GoldenHUDV3.HeaderColor)
surface.SetMaterial( ammoicon )
surface.SetDrawColor(GoldenHUDV3.IconColor)
surface.DrawTexturedRect( ScrW() - 263, ScrH() - 42, 22, 22 )
draw.SimpleText( clip.."/"..total, "GoldenHudV3Font", ScrW() - 222, ScrH() - 43, GoldenHUDV3.HeaderTextColor, TEXT_ALIGN_LEFT )
end
end )
local function HideElements( element )
if HideElementsTable[ element ] then
return false
end
end
hook.Add( "HUDShouldDraw", "HideElements", HideElements )
hook.Add( "HUDDrawTargetID", "ByeTargetIdHUD", function()
return false
end )
|
local db = require("lapis.db")
local schema = require("lapis.db.schema")
local migrations = {}
function migrations.rev_2016_01_16_init()
schema.create_table("pasta", {
{"hash", schema.types.varchar},
{"self_burning", schema.types.boolean},
{"filename", schema.types.varchar},
{"salt", schema.types.varchar},
{"content", schema.types.text},
{"password", schema.types.varchar},
})
schema.create_index("pasta", "hash")
end
function migrations.rev_2016_02_19_init()
db.query("ALTER TABLE pasta ADD PRIMARY KEY (hash);")
end
function migrations.rev_2016_07_17_redirect_to()
schema.add_column("pasta", "redirect_to", schema.types.boolean)
end
return migrations
|
require "30log-global"
Player = class("Player")
function Player:init(character, stance, stanceLimit, x, y, spriteSpeed, spriteTimer)
self.character = character
self.stance = stance
self.stanceLimit = stanceLimit
self.stanceCount = 1
self.x = x
self.y = y
self.spriteSpeed = spriteSpeed
self.spriteTimer = spriteTimer
self.sprite = love.graphics.newImage("Sprites/"..self.character..self.stance..self.stanceCount..".png")
self.width = self.sprite:getWidth()
self.height = self.sprite:getHeight()
self:updateHitbox()
end
function Player:updateStance(stance, stanceLimit)
if love.filesystem.exists("Hitboxes/".."OS"..self.character..self.stance..".txt") then
local offset = love.filesystem.read("Hitboxes/".."OS"..self.character..self.stance..".txt")
self.x = self.x + string.sub(offset, 1, 3)
self.y = self.y + string.sub(offset, 4, 6)
end
self.stance = stance
self.stanceLimit = stanceLimit
self.stanceCount = 0
local spriteLoop = self:incrementSprite()
self:updateHitbox()
if love.filesystem.exists("Hitboxes/".."OS"..self.character..self.stance..".txt") then
local offset = love.filesystem.read("Hitboxes/".."OS"..self.character..self.stance..".txt")
self.x = self.x - string.sub(offset, 1, 3)
self.y = self.y - string.sub(offset, 4, 6)
end
return spriteLoop
end
function Player:incrementSprite()
local spriteLoop = false
self.stanceCount = self.stanceCount + 1
if self.stanceCount > self.stanceLimit then
self.stanceCount = 1
end
local currentHeight = self.y + self.height
self.sprite = love.graphics.newImage("Sprites/"..self.character..self.stance..self.stanceCount..".png")
self.width = self.sprite:getWidth()
self.height = self.sprite:getHeight()
self.y = currentHeight - self.height
if self.stanceCount == self.stanceLimit then
spriteLoop = true
end
return spriteLoop
end
function Player:updateHitbox()
if love.filesystem.exists("Hitboxes/".."HB"..self.character..self.stance..self.stanceCount..".txt") then
local hitbox = love.filesystem.read("Hitboxes/".."HB"..self.character..self.stance..self.stanceCount..".txt")
self.hitX = self.x + string.sub(hitbox, 1, 3)
self.hitY = self.y + string.sub(hitbox, 4, 6)
self.hitWidth = self.width - string.sub(hitbox, 7, 9) - string.sub(hitbox, 1, 3)
self.hitHeight = self.height - string.sub(hitbox, 10, 12) - string.sub(hitbox, 4, 6)
else
self.hitX = self.x
self.hitY = self.y
self.hitWidth = self.width
self.hitHeight = self.height
end
end
function Player:hitTest(enemy)
return self.hitX < enemy.hitX + enemy.hitWidth and enemy.hitX < self.hitX + self.hitWidth and self.hitY < enemy.hitY + enemy.hitHeight and enemy.hitY < self.hitY + self.hitHeight
end
|
--preloader.lua
--local protobuf = require "protobuf"
require "utils"
require "msgcode"
-- print("PRELOAD", ...)
|
local Job = require("flutter-tools.job")
local ui = require("flutter-tools.ui")
local utils = require("flutter-tools.utils")
local devices = require("flutter-tools.devices")
local config = require("flutter-tools.config")
local executable = require("flutter-tools.executable")
local dev_log = require("flutter-tools.log")
local api = vim.api
local M = {}
local state = {
---@type Job
job = nil
}
local function match_error_string(line)
if not line then
return false
end
-- match the error string if no devices are setup
if line:match("No supported devices connected") ~= nil then
-- match the error string returned if multiple devices are matched
return true, "Choose a device"
elseif line:match("More than one device connected") ~= nil then
return true, "Choose a device"
end
end
---@param lines string[]
---@return boolean, string
local function has_recoverable_error(lines)
for _, line in pairs(lines) do
local match, msg = match_error_string(line)
if match then
return match, msg
end
end
return false, nil
end
---Handle output from flutter run command
---@param err boolean
---@param opts table config options for the dev log window
---@return fun(job: Job, data: string): nil
local function on_run_data(err, opts)
return function(_, data)
if err then
ui.notify({data})
end
if not match_error_string(data) then
dev_log.log(data, opts)
end
end
end
local function on_run_exit(result)
local matched_error, msg = has_recoverable_error(result)
if matched_error then
local lines, win_devices, highlights = devices.extract_device_props(result)
ui.popup_create(
{
title = "Flutter run (" .. msg .. ") ",
lines = lines,
highlights = highlights,
on_create = function(buf, _)
vim.b.devices = win_devices
api.nvim_buf_set_keymap(
buf,
"n",
"<CR>",
":lua __flutter_tools_select_device()<CR>",
{silent = true, noremap = true}
)
end
}
)
end
end
local function shutdown()
if state.job then
state.job:close()
state.job = nil
end
devices.close_emulator()
end
function M.run(device)
local cfg = config.get()
local cmd = executable.with("run")
if state.job then
return utils.echomsg("Flutter is already running!")
end
if device and device.id then
cmd = cmd .. " -d " .. device.id
end
ui.notify {"Starting flutter project..."}
state.job =
Job:new {
cmd = cmd,
on_stdout = on_run_data(false, cfg.dev_log),
on_stderr = on_run_data(true, cfg.dev_log),
on_exit = function(_, result)
on_run_exit(result)
shutdown()
end
}:start()
end
---@param cmd string
---@param quiet boolean
local function send(cmd, quiet)
if state.job then
state.job:send(cmd)
elseif not quiet then
utils.echomsg [[Sorry! Flutter is not running]]
end
end
---@param quiet boolean
function M.reload(quiet)
send("r", quiet)
end
---@param quiet boolean
function M.restart(quiet)
if not quiet then
ui.notify({"Restarting..."}, 1500)
end
send("R", quiet)
end
---@param quiet boolean
function M.quit(quiet)
if not quiet then
ui.notify({"Closing flutter application..."}, 1500)
end
send("q", quiet)
end
---@param quiet boolean
function M.visual_debug(quiet)
send("p", quiet)
end
-----------------------------------------------------------------------------//
-- Pub commands
-----------------------------------------------------------------------------//
local function on_pub_get(_, result)
ui.notify(result)
end
---@type Job
local pub_get_job = nil
function M.pub_get()
if not pub_get_job then
pub_get_job =
Job:new {
cmd = executable.with("pub get"),
on_exit = function(err, result)
on_pub_get(err, result)
pub_get_job = nil
end
}:sync()
end
end
return M
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE)
combat:setParameter(COMBAT_PARAM_DISPEL, CONDITION_POISON)
combat:setParameter(COMBAT_PARAM_AGGRESSIVE, false)
local spell = Spell("instant")
function spell.onCastSpell(creature, variant)
return combat:execute(creature, variant)
end
spell:name("Cure Poison")
spell:words("exana pox")
spell:group("healing")
spell:vocation("druid;true", "elder druid;true", "knight;true", "elite knight;true", "paladin;true",
"royal paladin;true", "sorcerer;true", "master sorcerer;true")
spell:id(29)
spell:cooldown(6000)
spell:groupCooldown(1000)
spell:level(10)
spell:mana(30)
spell:isSelfTarget(true)
spell:isAggressive(false)
spell:isPremium(false)
spell:needLearn(false)
spell:register()
|
--
--
-- ----------------------------------------------------------
-- Mosaic | OF Visual Patching Developer Platform
--
-- Copyright (c) 2019 Emanuele Mazza aka n3m3da
--
-- Mosaic is distributed under the MIT License. This gives everyone the
-- freedoms to use Mosaic in any context: commercial or non-commercial,
-- public or private, open or closed source.
--
-- See https://github.com/d3cod3/Mosaic for documentation
-- ----------------------------------------------------------
--
-- LoadImage.lua
--
-- This show how to load image files from disk.
--
-- created by n3m3da | www.d3cod3.org
-- translated from GAmuza examples by ferhoyo https://github.com/ferhoyo
--
-- variables for mouse interaction (DO NOT DELETE)
mouseX = 0
mouseY = 0
img = of.Image()
----------------------------------------------------
function setup()
img:load(SCRIPT_PATH.."/data/highlands.jpg")
end
----------------------------------------------------
function update()
end
----------------------------------------------------
function draw()
of.background(0)
-- center & scale to fit OUTPUT
w = OUTPUT_WIDTH
h = (w/img:getWidth())*img:getHeight()
posX = 0
posY = (OUTPUT_HEIGHT-h)/2
-- draw the image
of.setColor(255)
img:draw(posX,posY,w,h)
end
----------------------------------------------------
function exit()
end
-- input callbacks
----------------------------------------------------
function keyPressed(key)
end
function keyReleased(key)
end
function mouseMoved(x,y)
mouseX = x
mouseY = y
end
function mouseDragged(x,y)
mouseX = x
mouseY = y
end
function mouseReleased(x,y)
end
function mouseScrolled(x,y)
end
|
local export = {}
local data = mw.loadData("Module:utilities/data")
local notneeded = data.notneeded
local neededhassubpage = data.neededhassubpage
-- A helper function to escape magic characters in a string
-- Magic characters: ^$()%.[]*+-?
function export.pattern_escape(text)
if type(text) == "table" then
text = text.args[1]
end
text = mw.ustring.gsub(text, "([%^$()%%.%[%]*+%-?])", "%%%1")
return text
end
function export.plain_gsub(text, pattern, replacement)
local invoked = false
if type(text) == "table" then
invoked = true
if text.args then
local frame = text
local params = {
[1] = {},
[2] = {},
[3] = { allow_empty = true },
}
local args = require("Module:parameters").process(frame.args, params)
text = args[1]
pattern = args[2]
replacement = args[3]
else
error("If the first argument to plain_gsub is a table, it should be a frame object.")
end
else
if not ( type(pattern) == "string" or type(pattern) == "number" ) then
error("The second argument to plain_gsub should be a string or a number.")
end
if not ( type(replacement) == "string" or type(replacement) == "number" ) then
error("The third argument to plain_gsub should be a string or a number.")
end
end
pattern = export.pattern_escape(pattern)
if invoked then
text = mw.ustring.gsub(text, pattern, replacement)
return text
else
return mw.ustring.gsub(text, pattern, replacement)
end
end
--[[
Format the categories with the appropriate sort key. CATEGORIES is a list of
categories.
-- LANG is an object encapsulating a language; if nil, the object for
language code 'und' (undetermined) will be used.
-- SORT_KEY is placed in the category invocation, and indicates how the
page will sort in the respective category. Normally this should be nil,
and a default sort key based on the subpage name (the part after the
colon) will be used.
-- SORT_BASE lets you override the default sort key used when SORT_KEY is
nil. Normally, this should be nil, and a language-specific default sort
key is computed from the subpage name (e.g. for Russian this converts
Cyrillic ё to a string consisting of Cyrillic е followed by U+10FFFF,
so that effectively ё sorts after е instead of the default Wikimedia
sort, which (I think) is based on Unicode sort order and puts ё after я,
the last letter of the Cyrillic alphabet.
-- FORCE_OUTPUT forces normal output in all namespaces. Normally, nothing
is output if the page isn't in the main, Appendix:, Reconstruction: or
Citations: namespaces.
]]
function export.format_categories(categories, lang, sort_key, sort_base, force_output, sc)
local NAMESPACE = mw.title.getCurrentTitle().nsText
if type(lang) == "table" and not lang.getCode then
error("The second argument to format_categories should be a language object.")
end
if force_output or data.allowedNamespaces[NAMESPACE] then
local PAGENAME = mw.title.getCurrentTitle().text
local SUBPAGENAME = mw.title.getCurrentTitle().subpageText
if not lang then
lang = require("Module:languages").getByCode("und")
end
-- Generate a default sort key
sort_base = lang:makeSortKey(sort_base or SUBPAGENAME, sc)
if sort_key and sort_key ~= "" then
-- Gather some statistics regarding sort keys
if mw.ustring.upper(sort_key) == sort_base then
table.insert(categories, "Sort key tracking/redundant")
end
else
sort_key = sort_base
end
-- If the sortkey is empty, remove it.
-- Leave the sortkey if it is equal to PAGENAME, because it still
-- might be different from DEFAULTSORT and therefore have an effect; see
-- [[Wiktionary:Grease pit/2020/April#Module:utilities#format categories]].
if sort_key == "" then
sort_key = nil
end
local out_categories = {}
for key, cat in ipairs(categories) do
out_categories[key] = "[[Category:" .. cat .. (sort_key and "|" .. sort_key or "") .. "]]"
end
return table.concat(out_categories, "")
else
return ""
end
end
-- Used by {{categorize}}
function export.template_categorize(frame)
local NAMESPACE = mw.title.getCurrentTitle().nsText
local format = frame.args["format"]
local args = frame:getParent().args
local langcode = args[1]; if langcode == "" then langcode = nil end
local sort_key = args["sort"]; if sort_key == "" then sort_key = nil end
local categories = {}
if not langcode then
if NAMESPACE == "Template" then return "" end
error("Language code has not been specified. Please pass parameter 1 to the template.")
end
local lang = require("Module:languages").getByCode(langcode)
if not lang then
if NAMESPACE == "Template" then return "" end
error("The language code \"" .. langcode .. "\" is not valid.")
end
local prefix = ""
if format == "pos" then
prefix = lang:getCanonicalName() .. " "
elseif format == "topic" then
prefix = lang:getCode() .. ":"
end
local i = 2
local cat = args[i]
while cat do
if cat ~= "" then
table.insert(categories, prefix .. cat)
end
i = i + 1
cat = args[i]
end
return export.format_categories(categories, lang, sort_key)
end
function export.catfix(lang, sc)
if not lang then
require("Module:debug").track("catfix/no lang")
return nil
elseif type(lang) ~= "table" then
require("Module:debug").track("catfix/lang not table")
return nil
end
local canonicalName = lang:getCanonicalName() or error('The first argument to the function "catfix" should be a language object from Module:languages.')
if sc and not sc.getCode then
error('The second argument to the function "catfix" should be a script object from Module:scripts.')
end
-- To add script classes to links on pages created by category boilerplate templates.
if not sc then
sc = data.catfix_scripts[lang:getCode()]
if sc then
sc = require("Module:scripts").getByCode(sc)
end
end
return "<span id=\"catfix\" style=\"display:none;\" class=\"CATFIX-" .. mw.uri.anchorEncode(canonicalName) .. "\">" ..
require("Module:script utilities").tag_text(" ", lang, sc, nil) ..
"</span>"
end
function export.catfix_template(frame)
local params = {
[1] = {},
[2] = { alias_of = "sc" },
["sc"] = {},
}
local args = require("Module:parameters").process(frame:getParent().args, params)
local lang = require("Module:languages").getByCode(args[1]) or require("Module:languages").err(args[1], 1)
local sc = args.sc
if sc then
sc = require("Module:scripts").getByCode(sc) or error('The script code "' .. sc .. '", provided in the second parameter, is not valid.')
end
return export.catfix(lang, sc)
end
-- Not exporting because it is not used yet.
local function getDateTense(frame)
local name_num_mapping = {["January"] = 1, ["February"] = 2, ["March"] = 3, ["April"] = 4, ["May"] = 5, ["June"] = 6,
["July"] = 7, ["August"] = 8, ["September"] = 9, ["October"] = 10, ["November"] = 11, ["December"] = 12,
[1] = 1, [2] = 2, [3] = 3, [4] = 4, [5] = 5, [6] = 6, [7] = 7, [8] = 8, [9] = 9, [10] = 10, [11] = 11, [12] = 12}
local month = name_num_mapping[frame.args[2]]
local date = os.time({year = frame.args[1], day = frame.args[3], month = month})
local today = os.time() -- 12 AM/PM
local diff = os.difftime(date, today)
local daylength = 24 * 3600
if diff < -daylength / 2 then return "past"
else
if diff > daylength / 2 then return "future"
else return "present" end
end
end
function export.make_id(lang, str)
--[[ If called with invoke, first argument is a frame object.
If called by a module, first argument is a language object. ]]
local invoked = false
if type(lang) == "table" then
if lang.args then
invoked = true
local frame = lang
local params = {
[1] = {},
[2] = {},
}
local args = require("Module:parameters").process(frame:getParent().args, params)
local langCode = args[1]
str = args[2]
local m_languages = require("Module:languages")
lang = m_languages.getByCode(langCode) or m_languages.err(langCode, 1)
elseif not lang.getCanonicalName then
error("The first argument to make_id should be a language object.")
end
end
if not ( type(str) == "string" or type(str) == "number" ) then
error("The second argument to make_id should be a string or a number.")
end
local canonicalName = lang:getCanonicalName()
str = mw.uri.encode(str, "WIKI")
local id = canonicalName .. "-" .. str
if invoked then
return '<li class="senseid" id="' .. id .. '">'
else
return id
end
end
return export
|
debug = false
BUTTON_HEIGHT = 64
blockw = 50
blockh = blockw
nb_block_x = 800/blockw
nb_block_y = 700/blockh
DeletedMapBlock = 0
CameraYAdd = 0
screenw = love.graphics.getWidth()
screenh = love.graphics.getHeight()
screenw2 = screenw / 2
screenh2 = screenh / 2
test = 0
|
local class = require '30log'
local SingletonClass = class("Singleton")
local instance = SingletonClass()
function SingletonClass.new()
error('Cannot instantiate from a Singleton class')
end
function SingletonClass.init() end
function SingletonClass.extend()
error('Cannot extend from a Singleton class')
end
function SingletonClass:getInstance()
return instance
end
return SingletonClass
|
function applyAffect(name,affectid)
whoison.updateStats(name)
local player = minetest.get_player_by_name(name)
local oStage = affects._affectedPlayers[name][affectid].stage
local stageChange = false
minetest.log("action","Applying affect "..affectid.." stage " .. tostring(oStage) .. " on "..name)
-- see if they need advanced into the next stage
if ( affects._affectedPlayers[name][affectid].nextStage < whoison.getTimeOnline(name) ) then
local nextStageNum = affects._affectedPlayers[name][affectid].stage + 1
affects._affectedPlayers[name][affectid].stage = nextStageNum
affects._affectedPlayers[name][affectid].ran = false
minetest.log("action","Advancing "..affectid.." to the next stage for "..name)
if ( #affects._affects[affectid].stages < nextStageNum ) then
minetest.log("action","Affect "..affectid.." has worn off of "..name)
affects.removeAffect(name,affectid)
return
end
affects._affectedPlayers[name][affectid].nextStage = (whoison.getTimeOnline(name) + affects._affects[affectid].stages[nextStageNum].time)
-- apply physics on stage changes
stageChange = true
end
local iStage = affects._affectedPlayers[name][affectid].stage
local stage = affects._affects[affectid].stages[iStage]
local oPhysics = stage.physics
if stageChange == true then
if ( oPhysics ~= nil ) then
physics.adjust_physics(player,oPhysics)
end
end
if ( stage.damage ~= nil ) then
if ( randomChance(stage.damage.chance) ) then
player:set_hp( player:get_hp() - stage.damage.amount )
end
end
if ( stage.emote ~= nil ) then
if ( randomChance(stage.emote.chance) ) then
minetest.chat_send_all(name.." "..stage.emote.action)
end
end
if ( stage.place ~= nil ) then
if ( randomChance(stage.place.chance) ) then
minetest.place_node(player:getpos(),{name=stage.place.node, param1=0, param2=0})
end
end
if ( stage.custom ~= nil ) then
if ( stage.custom.runonce == true and affects._affectedPlayers[name][affectid].ran == true ) then
return
end
if ( randomChance(stage.custom.chance) ) then
affects._affectedPlayers[name][affectid].ran = true
stage.custom.func(name,player,affectid)
end
end
end
|
local mod = get_mod("rwaon_talents")
mod:hook_origin(PlayerCharacterStateLunging, "update", function (self, unit, input, dt, context, t)
local csm = self.csm
local movement_settings_table = PlayerUnitMovementSettings.get_movement_settings_table(unit)
local input_extension = self.input_extension
local status_extension = self.status_extension
local whereabouts_extension = ScriptUnit.extension(unit, "whereabouts_system")
local first_person_extension = self.first_person_extension
local damage_start_time = self.damage_start_time
if CharacterStateHelper.is_colliding_down(unit) then
if self._falling then
self._falling = false
whereabouts_extension:set_landed()
end
whereabouts_extension:set_is_onground()
elseif not self._falling then
self._falling = true
whereabouts_extension:set_fell(self.name)
end
local lunge_data = self._lunge_data
local lunge_events = lunge_data.lunge_events
if lunge_events then
local first_event_data = lunge_events[1]
local start_time = self._start_time
while first_event_data do
if first_event_data.t < t - start_time then
local event_function = first_event_data.event_function
event_function(self)
table.remove(lunge_events, 1)
first_event_data = lunge_events[1]
else
break
end
end
end
if CharacterStateHelper.do_common_state_transitions(status_extension, csm) then
return
end
if CharacterStateHelper.is_using_transport(status_extension) then
csm:change_state("using_transport")
return
end
local world = self.world
if CharacterStateHelper.is_ledge_hanging(world, unit, self.temp_params) then
self._stop = true
csm:change_state("ledge_hanging", self.temp_params)
return
end
if CharacterStateHelper.is_overcharge_exploding(status_extension) then
csm:change_state("overcharge_exploding")
return
end
if CharacterStateHelper.is_pushed(status_extension) then
status_extension:set_pushed(false)
local params = movement_settings_table.stun_settings.pushed
local hit_react_type = status_extension:hit_react_type()
params.hit_react_type = hit_react_type .. "_push"
csm:change_state("stunned", params)
return
end
if CharacterStateHelper.is_block_broken(status_extension) then
status_extension:set_block_broken(false)
local params = movement_settings_table.stun_settings.parry_broken
local hit_react_type = status_extension:hit_react_type()
params.hit_react_type = hit_react_type
csm:change_state("stunned", params)
return
end
if not self._stop then
local damage_data = lunge_data.damage
if damage_data and damage_start_time <= t then
self._stop = self:_update_damage(unit, dt, t, damage_data)
end
local input_service = Managers.input:get_service("Player")
if input_service:get("action_two", true) then
local position = POSITION_LOOKUP[unit]
local forward_direction = Quaternion.forward(first_person_extension:current_rotation())
self:_do_blast(position, forward_direction)
self._stop = true
end
local move_state = self:_update_movement(unit, dt, t, lunge_data)
if move_state == "ledge_hang" then
self._stop = true
csm:change_state("ledge_hanging", self.temp_params)
return
end
if move_state == "stop" and not self._stop then
local position = POSITION_LOOKUP[unit]
local forward_direction = Quaternion.forward(first_person_extension:current_rotation())
self:_do_blast(position, forward_direction)
self._stop = true
end
end
if self._stop then
if not self.csm.state_next and self._falling then
csm:change_state("falling", self.temp_params)
self.temp_params.hit = false
first_person_extension:change_state("falling")
return
else
csm:change_state("walking", self.temp_params)
self.temp_params.hit = false
first_person_extension:change_state("walking")
return
end
end
CharacterStateHelper.look(input_extension, self.player.viewport_name, first_person_extension, status_extension, self.inventory_extension, 0.5)
CharacterStateHelper.update_weapon_actions(t, unit, input_extension, self.inventory_extension, self.health_extension)
self._last_position:store(POSITION_LOOKUP[unit])
end)
mod:hook_origin(PlayerCharacterStateLunging, "_update_damage", function (self, unit, dt, t, damage_data)
local padding = damage_data.depth_padding
local half_width = 0.5 * damage_data.width
local half_height = 0.5 * damage_data.height
local new_pos = POSITION_LOOKUP[unit]
local old_pos = self._last_position:unbox()
local delta_move = new_pos - old_pos
local half_length = Vector3.length(delta_move) * 0.5 + padding
local rot = Quaternion.look(delta_move, Vector3.up())
local first_person_extension = self.first_person_extension
local forward_direction = Quaternion.forward(first_person_extension:current_rotation())
local mid_pos = (new_pos + old_pos) * 0.5 + Vector3(0, 0, half_height) + (damage_data.offset_forward or 0) * forward_direction
local size = Vector3(half_width, half_length, half_height)
local collision_filter = damage_data.collision_filter
local actors, num_actors = PhysicsWorld.immediate_overlap(self.physics_world, "shape", "oobb", "position", mid_pos, "rotation", rot, "size", size, "collision_filter", collision_filter, "use_global_table")
local hit_units = self._hit_units
local buff_extension = self.buff_extension
local network_manager = Managers.state.network
local attacker_unit_id = network_manager:unit_game_object_id(unit)
local attack_direction = Vector3.normalize(delta_move)
local weapon_system = Managers.state.entity:system("weapon_system")
for i = 1, num_actors, 1 do
local hit_actor = actors[i]
local hit_unit = Actor.unit(hit_actor)
if not hit_units[hit_unit] then
hit_units[hit_unit] = true
local hit_unit_id = network_manager:unit_game_object_id(hit_unit)
local hit_unit_pos = POSITION_LOOKUP[hit_unit]
local shield_blocked = nil
local backstab_multiplier = 1
local procced = false
local breed = Unit.get_data(hit_unit, "breed")
local damage_profile_id, power_level, hit_zone_id, ignore_shield, allow_backstab = self:_parse_attack_data(damage_data)
if breed and AiUtils.unit_alive(hit_unit) then
shield_blocked = not ignore_shield and AiUtils.attack_is_shield_blocked(hit_unit, unit)
if allow_backstab then
local owner_to_hit_dir = Vector3.normalize(hit_unit_pos - new_pos)
local hit_unit_direction = Quaternion.forward(Unit.local_rotation(hit_unit, 0))
local hit_angle = Vector3.dot(hit_unit_direction, owner_to_hit_dir)
local behind_target = hit_angle >= 0.55
if behind_target then
backstab_multiplier, procced = buff_extension:apply_buffs_to_value(backstab_multiplier, "backstab_multiplier")
end
end
shield_blocked = self:_calculate_hit_mass(shield_blocked, damage_data, hit_unit, breed)
else
shield_blocked = false
end
if breed and AiUtils.unit_alive(hit_unit) then
local final_stagger_direction = nil
if damage_data.stagger_angles then
local owner_to_hit_dir = Vector3.normalize(hit_unit_pos - new_pos)
local cross = Vector3.cross(Vector3.flat(owner_to_hit_dir), Vector3.flat(forward_direction))
local additional_stagger_angle = Math.random(damage_data.stagger_angles.min, damage_data.stagger_angles.max) * ((cross.z < 0 and -1) or 1)
local new_attack_direction = attack_direction
new_attack_direction.x = math.cos(additional_stagger_angle) * attack_direction.x - math.sin(additional_stagger_angle) * attack_direction.y
new_attack_direction.y = math.sin(additional_stagger_angle) * attack_direction.x + math.cos(additional_stagger_angle) * attack_direction.y
final_stagger_direction = Vector3.normalize(new_attack_direction)
else
final_stagger_direction = attack_direction
end
local damage_source = "career_ability"
local damage_source_id = NetworkLookup.damage_sources[damage_source]
local actual_hit_target_index = nil
local shield_break_procc = false
local boost_curve_multiplier = 0
local is_critical_strike = false
local can_damage = true
local can_stagger = true
weapon_system:send_rpc_attack_hit(damage_source_id, attacker_unit_id, hit_unit_id, hit_zone_id, hit_unit_pos, final_stagger_direction, damage_profile_id, "power_level", power_level, "hit_target_index", actual_hit_target_index, "blocking", shield_blocked, "shield_break_procced", shield_break_procc, "boost_curve_multiplier", boost_curve_multiplier, "is_critical_strike", is_critical_strike, "can_damage", can_damage, "can_stagger", can_stagger)
self._num_impacts = self._num_impacts + 1
local lunge_events = self._lunge_data.lunge_events
if lunge_events then
local impact_event_function = lunge_events.impact
if impact_event_function then
impact_event_function(self)
end
end
if self._lunge_data.first_person_hit_animation_event then
CharacterStateHelper.play_animation_event_first_person(first_person_extension, self._lunge_data.first_person_hit_animation_event)
end
local hit_mass_count_reached = self.max_targets <= self._amount_of_mass_hit or breed.armor_category == 2 or breed.armor_category == 3
if AiUtils.unit_alive(hit_unit) and (damage_data.interrupt_on_first_hit or (hit_mass_count_reached and damage_data.interrupt_on_max_hit_mass)) then
self:_do_blast(new_pos, forward_direction)
return true
end
if AiUtils.unit_alive(hit_unit) and damage_data.do_stagger then
self:_do_blast(new_pos, forward_direction)
end
end
end
end
return false
end)
|
vim.bo[0].shiftwidth = 4
vim.bo[0].softtabstop = 4
vim.bo[0].tabstop = 4
vim.bo[0].expandtab = true
vim.bo[0].commentstring = '# %s'
|
local MpeSim = {}
--[[
Override the native client code to get host player id
Host is now retrieved from stonehearth_mpe.services.server.player.player_service
--]]
MpeSim._old_get_host_player_id = _radiant.sim.get_host_player_id
function MpeSim.get_host_player_id()
return stonehearth_mpe.player:get_host_player_id()
end
return MpeSim
|
return require "lovesnow.snax"
|
-- Configuration
function love.conf(t)
t.version = "0.9.2"
t.title = "Not Zombies"
t.window.width = 1600
t.window.height = 900
t.window.fullscreen = true
t.window.fsaa = 4
t.console = false
end
|
if EffectManager == nil then
EffectManager = {}
end
---@alias LeaderLibEffectManagerTarget UUID|NETID|EsvCharacter|EsvItem|number[]
---@class LeaderLibObjectLoopEffectSaveData
---@field Effect string
---@field Bone string
---@field Handle integer
---@param uuid string
---@param effect string
---@param bone string
---@param handle integer
function EffectManager.SaveObjectEffectData(uuid, effect, bone, handle)
if PersistentVars.ObjectLoopEffects[uuid] == nil then
PersistentVars.ObjectLoopEffects[uuid] = {}
end
table.insert(PersistentVars.ObjectLoopEffects[uuid], {
Effect = effect,
Bone = bone,
Handle = handle
})
end
---@class LeaderLibWorldLoopEffectSaveData
---@field Effect string
---@field Position number[]
---@field Handle integer
---@param target number[]
---@param effect string
---@param bone string
---@param handle integer
function EffectManager.SaveWorldEffectData(target, effect, handle)
local region = SharedData.RegionData.Current
if PersistentVars.WorldLoopEffects[region] == nil then
PersistentVars.WorldLoopEffects[region] = {}
end
table.insert(PersistentVars.WorldLoopEffects[region], {
Effect = effect,
Position = target,
Handle = handle
})
end
---@private
EffectManager.Callbacks = {
LoopEffectStarted = {}
}
---@alias EffectManagerLoopEffectStartedCallback fun(effect:string, target:LeaderLibEffectManagerTarget, handle:integer, bone:string|nil):void
EffectManager.Register = {
---@param callback EffectManagerTagObjectCallback
LoopEffectStarted = function(callback)
table.insert(EffectManager.Callbacks.TagObject, callback)
end
}
---@return EffectManagerStopEffectOptions
local function PrepareOptions(tbl)
local opts = {
IsOptionTable = true
}
if type(tbl) == "table" then
if tbl.IsOptionTable then
return tbl
end
for k,v in pairs(tbl) do
if type(k) == "string" then
opts[k:lower()] = v
else
opts[k] = v
end
end
elseif type(tbl) == "userdata" then
setmetatable(opts, {
__index = function(_,k)
return tbl[k]
end
})
end
return opts
end
---@param target LeaderLibEffectManagerTarget Either an object or a position.
---@param effect string
---@param bone string|nil If playing an effect on an object, this is an optional bone name to use.
function EffectManager.StartLoopEffect(target, effect, bone)
local handle = nil
if type(target) == "table" then
handle = PlayLoopEffectAtPosition(effect, target[1], target[2], target[3])
EffectManager.SaveWorldEffectData(target, effect, handle)
else
bone = bone or ""
local uuid = GameHelpers.GetUUID(target)
handle = PlayLoopEffect(uuid, effect, bone)
EffectManager.SaveObjectEffectData(uuid, effect, bone, handle)
end
InvokeListenerCallbacks(EffectManager.Callbacks.LoopEffectStarted, effect, target, handle, bone)
end
---@param handle integer
function EffectManager.StopLoopEffectByHandle(handle)
StopLoopEffect(handle)
for region,dataTable in pairs(PersistentVars.WorldLoopEffects) do
for i,v in pairs(dataTable) do
if v.Handle == handle then
table.remove(dataTable, i)
end
end
end
for uuid,dataTable in pairs(PersistentVars.ObjectLoopEffects) do
for i,v in pairs(dataTable) do
if v.Handle == handle then
table.remove(dataTable, i)
end
end
end
end
---@class EffectManagerStopEffectOptions:table
---@field target LeaderLibEffectManagerTarget An object or position to filter the search.
---@field all boolean Stops all effects with this name.
---@param effect string|string[]
---@param options EffectManagerStopEffectOptions
function EffectManager.StopLoopEffectByName(effect, options)
options = PrepareOptions(options)
if type(effect) == "table" then
for k,v in pairs(effect) do
EffectManager.StopLoopEffectByName(v, options)
end
return true
end
local t = type(options.target)
if t == "table" then
for region,dataTable in pairs(PersistentVars.WorldLoopEffects) do
for i,v in pairs(dataTable) do
if v.Effect == effect then
StopLoopEffect(v.Handle)
table.remove(dataTable, i)
if not options.all then
return true
end
end
end
end
elseif t == "userdata" or t == "number" or t == "string" then
local uuid = GameHelpers.GetUUID(options.target)
if uuid then
if options.all then
CharacterStopAllEffectsWithName(uuid, effect)
end
local dataTable = PersistentVars.ObjectLoopEffects[uuid]
if dataTable then
local length = 0
for i,v in pairs(dataTable) do
if v.Effect == effect then
StopLoopEffect(v.Handle)
table.remove(dataTable, i)
if not options.all then
break
end
end
end
if #dataTable == 0 then
PersistentVars.ObjectLoopEffects[uuid] = nil
end
end
else
fprint(LOGLEVEL.WARNING, "[LeaderLib:EffectManager:StopLoopEffectByName] Failed to get UUID from target parameter:\n%s", Lib.serpent.block(options))
end
else
for region,dataTable in pairs(PersistentVars.WorldLoopEffects) do
for i,v in pairs(dataTable) do
if v.Effect == effect then
StopLoopEffect(v.Handle)
table.remove(dataTable, i)
if not options.all then
break
end
end
end
end
for uuid,dataTable in pairs(PersistentVars.ObjectLoopEffects) do
for i,v in pairs(dataTable) do
if v.Effect == effect then
StopLoopEffect(v.Handle)
table.remove(dataTable, i)
if not options.all then
break
end
end
end
if #dataTable == 0 then
PersistentVars.ObjectLoopEffects[uuid] = nil
end
end
end
end
function EffectManager.RestoreEffects(region)
--TODO
end
Ext.RegisterOsirisListener("GameStarted", 2, "after", function(region, isEditorMode)
EffectManager.RestoreEffects(region)
end)
-- Ext.RegisterOsirisListener("RegionEnded", 1, "after", function(region)
-- end)
|
AddCSLuaFile( )
DEFINE_BASECLASS("base_anim")
ENT.PrintName = "PotatOS"
ENT.Category = "Aperture Science"
ENT.Spawnable = true
ENT.Editable = true
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.AutomaticFrameAdvance = true
function ENT:Draw()
self:DrawModel()
local pos = self:LocalToWorld(Vector( 1.8, 4.7, 7))
render.SetMaterial(Material("sprites/orangecore2"))
render.DrawSprite(pos, 4, 4, Color( 255, 255, 255, 255))
end
function ENT:SpawnFunction(ply, trace, className)
if not trace.Hit then return end
local ent = ents.Create(className)
if not IsValid(ent) then return end
ent:SetPos(trace.HitPos + trace.HitNormal * 10)
ent:SetAngles(trace.HitNormal:Angle())
ent:Spawn()
ent.Owner = ply
return ent
end
-- no more client side
if CLIENT then return end
function ENT:Initialize()
self:SetModel("models/aperture/potatos_wmodel.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:GetPhysicsObject():Wake()
end
function ENT:Think()
self:NextThink(CurTime() + 1)
if self.Burned then return end
if not self:IsOnFire() then
if not timer.Exists("TA:Timer_PotatoOS_Chat"..self:EntIndex()) then
timer.Create("TA:Timer_PotatoOS_Chat"..self:EntIndex(), 15, 1, function() end)
self:EmitSound("TA:PotatoOSChat")
end
else
self.Burned = true
self:EmitSound("TA:PotatoOSBurn")
end
return true
end
function ENT:OnRemove()
timer.Remove("TA:Timer_PotatoOS_Chat"..self:EntIndex())
end
|
local helpers = require('test.functional.helpers')(after_each)
local eq = helpers.eq
local clear = helpers.clear
local meths = helpers.meths
local redir_exec = helpers.redir_exec
before_each(clear)
describe(':let command', function()
it('correctly lists variables with curly-braces', function()
meths.set_var('v', {0})
eq('\nv [0]', redir_exec('let {"v"}'))
end)
it('correctly lists variables with subscript', function()
meths.set_var('v', {0})
eq('\nv[0] #0', redir_exec('let v[0]'))
eq('\ng:["v"][0] #0', redir_exec('let g:["v"][0]'))
eq('\n{"g:"}["v"][0] #0', redir_exec('let {"g:"}["v"][0]'))
end)
end)
|
TUTORIALS['en'][#TUTORIALS['en'] + 1] = {
name = "Using the Pokedex",
contents = {
{type = CONTENT_TYPES.IMAGE, value = "/images/tutorial/pokedex_use.png"},
{type = CONTENT_TYPES.TEXT, value = "The use of the Pokedex is simple as well as any other item within the game. The necessary first step is to locate the Pokedex in your inventory, as the image above.\n\nYou can use the Pokedex directly on a Pokemon to see his information or use directly on your character to see Pokemon information that you have gathered."},
{type = CONTENT_TYPES.IMAGE, value = "/images/tutorial/pokedex_self.png"},
}
}
|
--[[
The MIT License (MIT)
Copyright (c) 2014 Marcus Ihde
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
local _PACKAGE = (...):match("^(.+)[%./][^%./]+") or ""
local util = require(_PACKAGE..'/util')
local post_shader = {}
post_shader.__index = post_shader
local files = love.filesystem.getDirectoryItems(_PACKAGE .. "/shaders/postshaders")
local shaders = {}
for i,v in ipairs(files) do
local name = _PACKAGE.."/shaders/postshaders".."/"..v
if love.filesystem.getInfo(name).type == "file" and string.sub(v, 1, 1) ~= '.' then
local str = love.filesystem.read(name)
local effect = util.loadShader(name)
local defs = {}
for vtype, extern in str:gmatch("extern (%w+) (%w+)") do
defs[extern] = true
end
local shaderName = name:match(".-([^\\|/]-[^%.]+)$"):gsub("%.glsl", "")
shaders[shaderName] = {effect, defs}
end
end
local function new()
local obj = {effects = {}}
local class = setmetatable(obj, post_shader)
class:refreshScreenSize()
return class
end
function post_shader:refreshScreenSize(w, h)
w, h = w or love.graphics.getWidth(), h or love.graphics.getHeight()
self.back_buffer = love.graphics.newCanvas(w, h)
end
function post_shader:addEffect(shaderName, ...)
self.effects[shaderName] = {...}
end
function post_shader:removeEffect(shaderName)
self.effects[shaderName] = nil
end
function post_shader:toggleEffect(shaderName, ...)
if self.effects[shaderName] ~= nil then
self:removeEffect(shaderName)
else
self:addEffect(shaderName, ...)
end
end
function post_shader:drawWith(canvas)
for shader, args in pairs(self.effects) do
if shader == "bloom" then
self:drawBloom(canvas, args)
elseif shader == "blur" then
self:drawBlur(canvas, args)
elseif shader == "tilt_shift" then
self:drawTiltShift(canvas, args)
else
self:drawShader(shader, canvas, args)
end
end
util.drawCanvasToCanvas(canvas)
end
function post_shader:drawBloom(canvas, args)
shaders['blurv'][1]:send("steps", args[1] or 2.0)
shaders['blurh'][1]:send("steps", args[1] or 2.0)
util.drawCanvasToCanvas(canvas, self.back_buffer, {shader = shaders['blurv'][1]})
util.process(self.back_buffer, {shader = shaders['blurh'][1]})
util.process(self.back_buffer, {shader = shaders['contrast'][1]})
util.process(canvas, {shader = shaders['contrast'][1]})
util.drawCanvasToCanvas(self.back_buffer, canvas, {
blendmode = "add", color = {1, 1, 1, (args[2] or 0.25)}
})
end
function post_shader:drawBlur(canvas, args)
shaders['blurv'][1]:send("steps", args[1] or 0.0)
shaders['blurh'][1]:send("steps", args[2] or args[1] or 0.0)
util.process(canvas, {shader = shaders['blurv'][1], blendmode = "alpha"})
util.process(canvas, {shader = shaders['blurh'][1], blendmode = "alpha"})
end
function post_shader:drawTiltShift(canvas, args)
shaders['blurv'][1]:send("steps", args[1] or 2.0)
shaders['blurh'][1]:send("steps", args[2] or 2.0)
util.drawCanvasToCanvas(canvas, self.back_buffer, {shader = shaders['blurv'][1]})
util.process(self.back_buffer, {shader = shaders['blurh'][1]})
shaders['tilt_shift'][1]:send("imgBuffer", canvas)
util.drawCanvasToCanvas(self.back_buffer, canvas, {shader = shaders['tilt_shift'][1]})
end
function post_shader:drawShader(shaderName, canvas, args)
local current_arg = 1
local effect = shaders[shaderName]
if effect == nil then
print("no shader called "..shaderName)
return
end
for def in pairs(effect[2]) do
if def == "time" then
effect[1]:send("time", love.timer.getTime())
elseif def == "palette" then
effect[1]:send("palette", unpack(process_palette({
args[current_arg],
args[current_arg + 1],
args[current_arg + 2],
args[current_arg + 3]
})))
current_arg = current_arg + 4
elseif def == "tint" then
effect[1]:send("tint", {process_tint(args[1], args[2], args[3])})
current_arg = current_arg + 3
elseif def == "imgBuffer" then
effect[1]:send("imgBuffer", canvas)
else
local value = args[current_arg]
if value ~= nil then
effect[1]:send(def, value)
end
current_arg = current_arg + 1
end
end
util.drawCanvasToCanvas(canvas, self.back_buffer, {shader = effect[1]})
util.drawCanvasToCanvas(self.back_buffer, canvas)
end
function process_tint(r, g, b)
return (r or 1.0), (g or 1.0), (b or 1.0)
end
function process_palette(palette)
for i = 1, #palette do
palette[i] = {process_tint(unpack(palette[i]))}
end
return palette
end
return setmetatable({new = new}, {__call = function(_, ...) return new(...) end})
|
local text = require('text')
local letters = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
}
function to_alpha(num)
local result = ''
while num > 0 do
num = num - 1
local remainder = math.fmod(num, 26)
result = letters[remainder + 1] .. result
num = math.floor((num - remainder) / 26)
end
return result
end
function to_ALPHA(num)
return text.upper(to_alpha(num))
end
function to_emph(el)
return pandoc.walk_block(el, {
Str = function(el)
return pandoc.Emph(pandoc.Str(el.text))
end
})
end
function to_upper(el)
return pandoc.walk_block(el, {
Str = function(el)
return pandoc.Str(text.upper(el.text))
end
})
end
function to_smallcaps(el)
return pandoc.walk_block(el, {
Str = function(el)
return pandoc.SmallCaps(el.text)
end
})
end
function to_roman(num)
local III = pandoc.utils.to_roman_numeral(num)
return text.lower(III)
end
-- print(to_alpha(1))
-- print(to_alpha(2))
-- print(to_alpha(26))
-- print(to_alpha(27))
-- print(to_alpha(28))
local levels = { 0, 0, 0, 0, 0 }
-- local strict = false
-- -- maybe add smallcaps one day
-- -- determine if we're using strict mode
-- function Meta(m)
-- if (m.aglc-headers-strict) then
-- strict = true
-- end
-- end
function big_space()
-- latex fonts don't do character fallback well.
if FORMAT == "latex" then
return pandoc.RawInline("latex", "\\enspace")
else
return pandoc.Str(" ") -- en space
end
end
function Header(el)
if el.level == 1 then
levels[1] = levels[1] + 1
levels[2] = 0
levels[3] = 0
levels[4] = 0
levels[5] = 0
el = to_smallcaps(el)
if el.identifier ~= 'refs' then
table.insert(el.content, 1, pandoc.Str(pandoc.utils.to_roman_numeral(levels[1])))
end
table.insert(el.content, 2, big_space())
return el
end
if el.level == 2 then
levels[2] = levels[2] + 1
levels[3] = 0
levels[4] = 0
levels[5] = 0
el = to_emph(el)
table.insert(el.content, 1, pandoc.Str(to_ALPHA(levels[2])))
table.insert(el.content, 2, big_space())
return el
end
if el.level == 3 then
levels[3] = levels[3] + 1
levels[4] = 0
levels[5] = 0
el = to_emph(el)
table.insert(el.content, 1, pandoc.Str(levels[3]))
table.insert(el.content, 2, big_space())
return el
end
if el.level == 4 then
levels[4] = levels[4] + 1
levels[5] = 0
table.insert(el.content, 1, pandoc.Str('('..to_alpha(levels[4])..')'))
table.insert(el.content, 2, big_space())
return to_emph(el)
end
if el.level == 5 then
levels[5] = levels[5] + 1
table.insert(el.content, 1, pandoc.Str('('..to_roman(levels[5])..')'))
table.insert(el.content, 2, big_space())
return to_emph(el)
end
end
|
Global( "PlayerMana", {} )
function PlayerMana:Init(anID)
self.playerID = anID
self.unitParams = {}
self.mana = 0
self.lastMana = -1
self.eventFunc = self:GetEventFunc()
self.base = copyTable(PlayerBase)
self.base:Init()
self:RegisterEvent(anID)
end
function PlayerMana:ClearLastValues()
self.lastMana = -1
end
function PlayerMana:SubscribeTargetGui(aLitener)
self:ClearLastValues()
self.base:SubscribeTargetGui(self.playerID, aLitener, self.eventFunc)
end
function PlayerMana:UnsubscribeTargetGui()
self.base:UnsubscribeTargetGui()
end
function PlayerMana:SubscribeRaidGui(aLitener)
self:ClearLastValues()
self.base:SubscribeRaidGui(self.playerID, aLitener, self.eventFunc)
end
function PlayerMana:UnsubscribeRaidGui()
self.base:UnsubscribeRaidGui()
end
function PlayerMana:TryDestroy()
if self.base:CanDestroy() then
self:UnRegisterEvent()
return true
end
return false
end
function PlayerMana:UpdateValueIfNeeded()
if self.mana ~= self.lastMana then
self.lastMana = self.mana
local res = self.base.guiRaidListener and self.base.guiRaidListener.listenerMana(self.mana, self.base.guiRaidListener)
res = self.base.guiTargetListener and self.base.guiTargetListener.listenerMana(self.mana, self.base.guiTargetListener)
end
end
function PlayerMana:GetEventFunc()
return function(aParams)
self.mana = unit.GetManaPercentage( aParams.unitId )
--LogInfo("EVENT_UNIT_MANA_PERCENTAGE_CHANGED ", self.playerID)
end
end
function PlayerMana:RegisterEvent(anID)
self.unitParams.unitId = anID
common.RegisterEventHandler(self.eventFunc, "EVENT_UNIT_MANA_PERCENTAGE_CHANGED", self.unitParams)
if g_debugSubsrb then
self.base:reg("mana")
end
end
function PlayerMana:UnRegisterEvent()
common.UnRegisterEventHandler(self.eventFunc, "EVENT_UNIT_MANA_PERCENTAGE_CHANGED", self.unitParams)
if g_debugSubsrb then
self.base:unreg("mana")
end
end
|
object_tangible_quest_rebel_rtp_c3po_medical_supply_source = object_tangible_quest_rebel_shared_rtp_c3po_medical_supply_source:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_rebel_rtp_c3po_medical_supply_source, "object/tangible/quest/rebel/rtp_c3po_medical_supply_source.iff")
|
function requestModel(modelName,cb)
if type(modelName) ~= 'number' then
modelName = tonumber(modelName)
end
local breaker = 0
RequestModel(modelName)
while not HasModelLoaded(modelName) do
Citizen.Wait(1)
breaker = breaker + 1
if breaker >= 100 then
break
end
end
if breaker >= 100 then
cb(false)
else
cb(true)
end
end
exports('requestModel',requestModel)
|
-- Code from: http://lua-users.org/wiki/LuaXml
-----------------------------------------------------------------------------------------
-- LUA only XmlParser from Alexander Makeev
-----------------------------------------------------------------------------------------
XmlParser = {};
function XmlParser:ToXmlString(value)
value = string.gsub (value, "&", "&"); -- '&' -> "&"
value = string.gsub (value, "<", "<"); -- '<' -> "<"
value = string.gsub (value, ">", ">"); -- '>' -> ">"
--value = string.gsub (value, "'", "'"); -- '\'' -> "'"
value = string.gsub (value, "\"", """); -- '"' -> """
-- replace non printable char -> "
"
value = string.gsub(value, "([^%w%&%;%p%\t% ])",
function (c)
return string.format("&#x%X;", string.byte(c))
--return string.format("&#x%02X;", string.byte(c))
--return string.format("&#%02d;", string.byte(c))
end);
return value;
end
function XmlParser:FromXmlString(value)
value = string.gsub(value, "&#x([%x]+)%;",
function(h)
return string.char(tonumber(h,16))
end);
value = string.gsub(value, "&#([0-9]+)%;",
function(h)
return string.char(tonumber(h,10))
end);
value = string.gsub (value, """, "\"");
value = string.gsub (value, "'", "'");
value = string.gsub (value, ">", ">");
value = string.gsub (value, "<", "<");
value = string.gsub (value, "&", "&");
return value;
end
function XmlParser:ParseArgs(s)
local arg = {}
string.gsub(s, "(%w+)=([\"'])(.-)%2", function (w, _, a)
arg[w] = self:FromXmlString(a);
end)
return arg
end
function XmlParser:ParseXmlText(xmlText)
local stack = {}
local top = {Name=nil,Value=nil,Attributes={},ChildNodes={}}
table.insert(stack, top)
local ni,c,label,xarg, empty
local i, j = 1, 1
while true do
ni,j,c,label,xarg, empty = string.find(xmlText, "<(%/?)([%w:]+)(.-)(%/?)>", i)
if not ni then break end
local text = string.sub(xmlText, i, ni-1);
if not string.find(text, "^%s*$") then
top.Value=(top.Value or "")..self:FromXmlString(text);
end
if empty == "/" then -- empty element tag
table.insert(top.ChildNodes, {Name=label,Value=nil,Attributes=self:ParseArgs(xarg),ChildNodes={}})
elseif c == "" then -- start tag
top = {Name=label, Value=nil, Attributes=self:ParseArgs(xarg), ChildNodes={}}
table.insert(stack, top) -- new level
--print("openTag ="..top.Name);
else -- end tag
local toclose = table.remove(stack) -- remove top
--print("closeTag="..toclose.Name);
top = stack[#stack]
if #stack < 1 then
error("XmlParser: nothing to close with "..label)
end
if toclose.Name ~= label then
error("XmlParser: trying to close "..toclose.Name.." with "..label)
end
table.insert(top.ChildNodes, toclose)
end
i = j+1
end
local text = string.sub(xmlText, i);
if not string.find(text, "^%s*$") then
stack[#stack].Value=(stack[#stack].Value or "")..self:FromXmlString(text);
end
if #stack > 1 then
error("XmlParser: unclosed "..stack[stack.n].Name)
end
return stack[1].ChildNodes[1];
end
function XmlParser:ParseXmlFile(xmlFileName)
local hFile,err = io.open(xmlFileName,"r");
if (not err) then
local xmlText=hFile:read("*a"); -- read file content
io.close(hFile);
return self:ParseXmlText(xmlText),nil;
else
return nil,err;
end
end
------------------------------------------------------------------------------------------
--example:
function dump(_class, no_func, depth)
if(not _class) then
print("nil");
return;
end
if(depth==nil) then depth=0; end
local str="";
for n=0,depth,1 do
str=str.."\t";
end
print(str.."["..type(_class).."]");
print(str.."{");
for i,field in pairs(_class) do
if(type(field)=="table") then
print(str.."\t"..tostring(i).." =");
dump(field, no_func, depth+1);
else
if(type(field)=="number") then
print(str.."\t"..tostring(i).."="..field);
elseif(type(field) == "string") then
print(str.."\t"..tostring(i).."=".."\""..field.."\"");
elseif(type(field) == "boolean") then
print(str.."\t"..tostring(i).."=".."\""..tostring(field).."\"");
else
if(not no_func)then
if(type(field)=="function")then
print(str.."\t"..tostring(i).."()");
else
print(str.."\t"..tostring(i).."<userdata=["..type(field).."]>");
end
end
end
end
end
print(str.."}");
end
|
local ObjectManager = require("managers.object.object_manager")
squillLairMenuComponent = { }
function squillLairMenuComponent:fillObjectMenuResponse(pSceneObject, pMenuResponse, pPlayer)
local menuResponse = LuaObjectMenuResponse(pMenuResponse)
if (CreatureObject(pPlayer):hasScreenPlayState(1, "hero_of_tatooine") and not CreatureObject(pPlayer):hasScreenPlayState(2, "hero_of_tatooine")) then
menuResponse:addRadialMenuItem(120, 3, "@quest/hero_of_tatooine/system_messages:search") -- Search
end
end
function squillLairMenuComponent:handleObjectMenuSelect(pObject, pPlayer, selectedID)
if (pPlayer == nil or pObject == nil) then
return 0
end
if (not CreatureObject(pPlayer):hasScreenPlayState(1, "hero_of_tatooine") or CreatureObject(pPlayer):hasScreenPlayState(2, "hero_of_tatooine")) then
return 0
end
if (selectedID == 120) then
if (readData(CreatureObject(pPlayer):getObjectID() .. ":hero_of_tat:searched_squill_lair") == 1) then
CreatureObject(pPlayer):sendSystemMessage("@quest/hero_of_tatooine/system_messages:already_search")
return 0
end
local pInventory = SceneObject(pPlayer):getSlottedObject("inventory")
if (pInventory == nil) then
return 0
end
if (SceneObject(pInventory):isContainerFullRecursive()) then
CreatureObject(pPlayer):sendSystemMessage("@quest/hero_of_tatooine/system_messages:inventory")
return 0
end
local pSkull = giveItem(pInventory, "object/tangible/loot/quest/hero_of_tatooine/squill_skull.iff", -1)
if (pSkull == nil) then
CreatureObject(pPlayer):sendSystemMessage("Error: Unable to generate item.")
return 0
end
CreatureObject(pPlayer):sendSystemMessage("@quest/hero_of_tatooine/system_messages:receive")
writeData(CreatureObject(pPlayer):getObjectID() .. ":hero_of_tat:searched_squill_lair", 1)
end
return 0
end
explosivesCrateMenuComponent = { }
function explosivesCrateMenuComponent:fillObjectMenuResponse(pSceneObject, pMenuResponse, pPlayer)
local menuResponse = LuaObjectMenuResponse(pMenuResponse)
local pInventory = SceneObject(pPlayer):getSlottedObject("inventory")
if (pInventory == nil) then
return 0
end
if (CreatureObject(pPlayer):hasScreenPlayState(1, "hero_of_tatooine_altruism") and not CreatureObject(pPlayer):hasScreenPlayState(2, "hero_of_tatooine_altruism") and
getContainerObjectByTemplate(pInventory, "object/tangible/item/quest/hero_of_tatooine/explosives.iff", true) == nil) then
menuResponse:addRadialMenuItem(120, 3, "@quest/hero_of_tatooine/system_messages:search") -- Search
end
end
function explosivesCrateMenuComponent:handleObjectMenuSelect(pObject, pPlayer, selectedID)
if (pPlayer == nil or pObject == nil) then
return 0
end
if (not CreatureObject(pPlayer):hasScreenPlayState(1, "hero_of_tatooine_altruism") or CreatureObject(pPlayer):hasScreenPlayState(2, "hero_of_tatooine_altruism")) then
return 0
end
if (selectedID == 120) then
local pInventory = SceneObject(pPlayer):getSlottedObject("inventory")
if (pInventory == nil) then
return 0
end
if (SceneObject(pInventory):isContainerFullRecursive()) then
CreatureObject(pPlayer):sendSystemMessage("@quest/hero_of_tatooine/system_messages:altruism_inventory_full")
return 0
end
local pExplosives = giveItem(pInventory, "object/tangible/item/quest/hero_of_tatooine/explosives.iff", -1)
if (pExplosives == nil) then
CreatureObject(pPlayer):sendSystemMessage("@quest/hero_of_tatooine/system_messages:altruism_null_object")
return 0
end
CreatureObject(pPlayer):sendSystemMessage("@quest/hero_of_tatooine/system_messages:altruism_got_object")
SceneObject(pObject):destroyObjectFromWorld()
end
return 0
end
|
require 'commons'
local ADDR = 0x23
local CMD = 0x10
local i2c = i2c
local function read_data()
i2c.start(0)
i2c.address(0, ADDR, i2c.TRANSMITTER)
i2c.write(0, CMD)
i2c.stop(0)
i2c.start(0)
i2c.address(0, ADDR,i2c.RECEIVER)
ftr.sleep(300)
c = i2c.read(0, 2)
i2c.stop(0)
return c
end
return {
init = function(sda, scl)
i2c.setup(0, sda, scl, i2c.SLOW)
i2c.start(0)
local success = i2c.address(0, ADDR, i2c.TRANSMITTER)
i2c.stop(0)
if success then read_data() end
return success
end,
lux = function()
local dataT = read_data()
local UT = dataT:byte(1) * 256 + dataT:byte(2)
return UT*10/12
end
}
|
-- return true = There are others migrations file
-- return false = This is the last migration file
function onUpdateDatabase()
return false
end
|
--[[
Copyright © 2017, Sammeh of Quetzalcoatl
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of JobChange nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Sammeh BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
_addon.name = 'Job Change'
_addon.author = 'Sammeh'
_addon.version = '1.0.3'
_addon.command = 'jc'
-- 1.0.1 first release
-- 1.0.2 added 'reset' command to simply reset to existing job. Changes sub job to a random starting job and back.
-- 1.0.3 Code clean-up
require('tables')
packets = require('packets')
res = require ('resources')
function jobchange(job,main_sub)
windower.add_to_chat(4,"JobChange: Changing "..main_sub.." job to:"..res.jobs[job].ens)
if job and main_sub then
local packet = packets.new('outgoing', 0x100, {
[main_sub:sub(1,1):upper()..main_sub:sub(2)..' Job'] = job,
})
packets.inject(packet)
coroutine.sleep(0.5)
end
end
windower.register_event('addon command', function(command, ...)
local self = windower.ffxi.get_player()
local args = L{...}
local job = ''
if args[1] then
job = args[1]:lower()
end
local main_sub = ''
if command:lower() == 'main' then
main_sub = 'main'
elseif command:lower() == 'sub' then
main_sub = 'sub'
elseif command:lower() == 'reset' then
windower.add_to_chat(4,"JobChange: Resetting Job")
main_sub = 'sub'
job = windower.ffxi.get_player().sub_job:lower()
else
windower.add_to_chat(4,"JobChange Syntax: //jc main|sub JOB -- Chnages main or sub to target JOB")
windower.add_to_chat(4,"JobChange Syntax: //jc reset -- Resets Current Job")
return
end
local conflict = find_conflict(job,self)
local jobid = find_job(job,self)
if jobid then
local npc = find_job_change_npc()
if npc then
if not conflict then
jobchange(jobid,main_sub)
else
local temp_job = find_temp_job(self)
windower.add_to_chat(4,"JobChange: Conflict with "..conflict)
if main_sub == conflict then
jobchange(temp_job,main_sub)
jobchange(jobid,main_sub)
else
jobchange(temp_job,conflict)
jobchange(jobid,main_sub)
end
end
else
windower.add_to_chat(4,"JobChange: Not close enough to a Moogle!")
end
else
windower.add_to_chat(4,"JobChange: Could not change "..command.." to "..job:upper().." ---Mistype|NotUnlocked")
end
end)
function find_conflict(job,self)
if self.main_job == job:upper() then
return "main"
end
if self.sub_job == job:upper() then
return "sub"
end
end
function find_temp_job(self)
local starting_jobs = S { 'WAR', 'MNK', 'WHM', 'BLM', 'RDM', 'THF' }
for i in pairs(starting_jobs) do
if not find_conflict(i,self) then
for index,value in pairs(res.jobs) do
if value.ens == i then
return index
end
end
end
end
end
function find_job(job,self)
local jobLevel = self.jobs[job:upper()]
for index,value in pairs(res.jobs) do
if value.ens:lower() == job and jobLevel > 0 then
return index
end
end
end
function find_job_change_npc()
local info = windower.ffxi.get_info()
if not (info.mog_house or S{'Selbina', 'Mhaura', 'Tavnazian Safehold', 'Nashmau', 'Rabao', 'Kazham', 'Norg'}:contains(res.zones[info.zone].english)) then
windower.add_to_chat(4,'JobChange: Not in a zone with a Change NPC')
return
end
for i, v in pairs(windower.ffxi.get_mob_array()) do
if v.distance < 36 and S{'Moogle', 'Nomad Moogle', 'Green Thumb Moogle'}:contains(v.name) then
return v
end
end
end
|
local olua = require "olua"
local clang = require "clang"
local writer = require 'autoconf-writer'
local format = olua.format
local ignored_type = {}
local visited_type = {}
local refed_type = {}
local type_alias = {}
local type_convs = {}
local module_files = {}
local clang_tu
local M = {}
local logfile = io.open('autobuild/autoconf.log', 'w')
local function log(fmt, ...)
logfile:write(string.format(fmt, ...))
logfile:write('\n')
end
function M.addref(cppcls)
refed_type[cppcls] = true
end
function M.init(path)
local HEADER_PATH = 'autobuild/.autoconf.h'
local clang_args = dofile(path)
local header = io.open(HEADER_PATH, 'w')
header:write(format [[
#ifndef __AUTOCONF_H__
#define __AUTOCONF_H__
${clang_args.HEADERS}
#endif
]])
header:close()
local index = clang.createIndex(false, true)
for i, v in ipairs(clang_args.FLAGS) do
local HOMEDIR = olua.HOMEDIR
clang_args.FLAGS[i] = format(v)
end
clang_tu = index:parse(HEADER_PATH, clang_args.FLAGS)
os.remove(HEADER_PATH)
end
function M:parse(path)
self.module = dofile(path)
assert(not self.module.FILENAME)
assert(not self.module.FILE_PATH)
assert(not self.module.TYPE_FILE_PATH)
self.module.FILENAME = self.module.NAME:gsub('_', '-')
self.module.FILE_PATH = format('autobuild/${self.module.FILENAME}.lua')
self.module.TYPE_FILE_PATH = format('autobuild/${self.module.FILENAME}-types.lua')
module_files[#module_files + 1] = self.module
for cls in pairs(self.module.EXCLUDE_TYPE) do
ignored_type[cls] = false
end
local function toconv(cls)
return 'auto_olua_$$_' .. string.gsub(cls.CPPCLS, '::', '_')
end
for _, v in ipairs(self.module.TYPEDEFS) do
type_convs[v.CPPCLS] = assert(v.CONV, 'no conv function: ' .. v.CPPCLS)
end
for _, cls in pairs(self.module.CLASSES) do
type_convs[cls.CPPCLS] = cls.KIND == 'conv' and toconv(cls) or true
end
self:visit(clang_tu:cursor())
self:check_class()
writer.write_module(setmetatable({
visited_type = visited_type,
ignored_type = ignored_type,
log = log,
}, {__index = self.module}))
end
local function is_ref_class(cls)
if refed_type[cls.CPPCLS] then
return true
elseif cls.SUPERCLS then
return is_ref_class(visited_type[cls.SUPERCLS])
end
end
function M:has_define_class(cls)
local name = string.match(cls.CPPCLS, '[^:]+$')
return string.find(cls.CHUNK or '', 'class +' .. name) ~= nil
end
function M:check_class()
for _, cls in ipairs(self.module.CLASSES) do
if not visited_type[cls.CPPCLS] then
if #cls.FUNC > 0 or #cls.PROP > 0 then
cls.KIND = 'class'
cls.REG_LUATYPE = self:has_define_class(cls)
visited_type[cls.CPPCLS] = cls
ignored_type[cls.CPPCLS] = false
else
error(format("class not found: ${cls.CPPCLS}"))
end
end
end
for _, cls in ipairs(self.module.CLASSES) do
if cls.SUPERCLS and not visited_type[cls.SUPERCLS]then
error(format('super class not found: ${cls.CPPCLS} -> ${cls.SUPERCLS}'))
end
if is_ref_class(cls) then
refed_type[cls.CPPCLS] = true
end
end
end
function M:visit_enum(cur, cppcls)
cppcls = cppcls or self:typename(cur, cur:type())
local cls = self.module.CLASSES[cppcls]
visited_type[cppcls] = cls
ignored_type[cppcls] = false
if cur:kind() ~= 'TypeAliasDecl' then
for _, c in ipairs(cur:children()) do
local VALUE = c:name()
local name = cls.MAKE_LUANAME(VALUE, 'ENUM')
cls.ENUM[name] = {
NAME = name,
VALUE = format('${cls.CPPCLS}::${VALUE}'),
}
end
cls.KIND = 'enum'
type_alias[cls.CPPCLS] = nil
else
cls.KIND = 'enumAlias'
end
end
function M:is_excluded_typeanme(name)
if self.module.EXCLUDE_TYPE[name] then
return true
elseif string.find(name, '<') then
name = string.gsub(name, '<.*>', '')
return self:is_excluded_typeanme(name)
end
end
function M:is_excluded_type(type)
if type:kind() == 'IncompleteArray' then
return true
end
local tn = type:name()
-- remove const and &
-- const T * => T *
-- const T & => T
local rawtn = tn:gsub('^const *', ''):gsub(' *&$', '')
if self:is_excluded_typeanme(rawtn) then
return true
elseif tn ~= type:canonicalType():name() then
return self:is_excluded_type(type:canonicalType())
end
end
function M:typename(cur, type)
if not type then
if cur:kind() == 'Namespace' then
local ns = olua.newarray('::')
while cur and cur:kind() ~= 'TranslationUnit' do
ns:insert(cur:name())
cur = cur:parent()
end
return tostring(ns)
else
return cur:name()
end
end
local tn = type:name()
-- remove const, & and *: const T * => T
local rawtn = tn:match('([%w:_]+) ?[&*]?$')
if not rawtn then
return tn
end
-- typedef std::function<void (Object *)> ClickListener
-- const ClickListener & => const olua::ClickListener &
for _, cu in ipairs(cur:children()) do
if cu:kind() == 'TypeRef' then
local ftn = cu:name():match('([^ ]+)$')
if string.find(ftn, rawtn .. '$') then
tn = tn:gsub(rawtn, ftn)
rawtn = ftn
break
end
end
end
local alias = type_alias[rawtn]
if alias and not type_convs[rawtn] then
local rawalias = string.gsub(alias, '<.+>', '')
if olua.typeinfo(rawalias, nil, true) then
-- old: const olua::ClickListener &
-- new: const std::function<void (Object *)> &
return string.gsub(tn, rawtn, alias)
end
end
return tn
end
local DEFAULT_ARG_TYPES = {
IntegerLiteral = true,
FloatingLiteral = true,
ImaginaryLiteral = true,
StringLiteral = true,
CharacterLiteral = true,
CXXBoolLiteralExpr = true,
CXXNullPtrLiteralExpr = true,
GNUNullExpr = true,
DeclRefExpr = true,
CallExpr = true,
}
function M:has_default_value(cur)
for _, c in ipairs(cur:children()) do
if DEFAULT_ARG_TYPES[c:kind()] then
return true
elseif self:has_default_value(c) then
return true
end
end
end
function M:visit_method(cls, cur)
if cur:isVariadic()
or cur:name():find('^_')
or cur:isCopyConstructor()
or cur:isMoveConstructor()
or cur:name():find('operator *[%-=+/*><!()]?')
or self:is_excluded_type(cur:resultType()) then
return
end
for _, c in ipairs(cur:children()) do
-- attribute(deprecated) ?
if c:kind() == 'UnexposedAttr' then
return
end
end
local fn = cur:name()
local attr = cls.ATTR[fn] or cls.ATTR['*'] or {}
local callback = cls.CALLBACK[fn] or {}
local exps = olua.newarray('')
local declexps = olua.newarray('')
for i, arg in ipairs(cur:arguments()) do
local attrn = (attr['ARG' .. i]) or ''
if not attrn:find('@out') and self:is_excluded_type(arg:type()) then
return
end
end
exps:push(attr.RET and (attr.RET .. ' ') or nil)
exps:push(cur:isStatic() and 'static ' or nil)
local cbkind
if cur:kind() ~= 'Constructor' then
local tn = self:typename(cur, cur:resultType())
if string.find(tn, 'std::function') then
cbkind = 'RET'
if callback.NULLABLE then
exps:push('@nullable ')
end
if callback.LOCAL ~= false then
exps:push('@local ')
end
end
exps:push(tn)
exps:push(olua.typespace(tn))
end
local optional = false
exps:push(fn .. '(')
declexps:push(fn .. '(')
for i, arg in ipairs(cur:arguments()) do
local tn = self:typename(arg, arg:type())
local DISPLAY_NAME = cur:displayName()
local ARGN = 'ARG' .. i
if i > 1 then
exps:push(', ')
declexps:push(', ')
end
if string.find(tn, 'std::function') then
if cbkind then
error(format('has more than one std::function: ${cls.CPPCLS}::${DISPLAY_NAME}'))
end
assert(not cbkind, cls.CPPCLS .. '::' .. cur:displayName())
cbkind = 'ARG'
if callback.NULLABLE then
exps:push('@nullable ')
end
if callback.LOCAL ~= false then
exps:push('@local ')
end
end
if self:has_default_value(arg) and not string.find(attr[ARGN] or '', '@out') then
exps:push('@optional ')
optional = true
else
assert(not optional, cls.CPPCLS .. '::' .. DISPLAY_NAME)
end
exps:push(attr[ARGN] and (attr[ARGN] .. ' ') or nil)
exps:push(tn)
exps:push(olua.typespace(tn))
exps:push(arg:name())
declexps:push(tn)
end
exps:push(')')
declexps:push(')')
local decl = tostring(exps)
if self.module.EXCLUDE_PASS(cls.CPPCLS, fn, decl) then
return
else
if cbkind then
refed_type[cls.CPPCLS] = true
end
return decl, tostring(declexps), cbkind
end
end
function M:visit_var(cls, cur)
if cur:type():isConst() or self:is_excluded_type(cur:type()) then
return
end
local exps = olua.newarray('')
local attr = cls.ATTR[cur:name()] or cls.ATTR['*'] or {}
if attr.OPTIONAL or (self:has_default_value(cur) and attr.OPTIONAL == nil) then
exps:push('@optional ')
end
local tn = self:typename(cur, cur:type())
local cbkind
if string.find(tn, 'std::function') then
cbkind = 'VAR'
exps:push('@nullable ')
local callback = cls.CALLBACK:take(cur:name()) or {}
if callback.LOCAL ~= false then
exps:push('@local ')
end
end
if cur:kind() == 'VarDecl' then
exps:push('static ')
end
exps:push(tn)
exps:push(olua.typespace(tn))
exps:push(cur:name())
local decl = tostring(exps)
if self.module.EXCLUDE_PASS(cls.CPPCLS, cur:name(), decl) then
return
else
if cbkind then
refed_type[cls.CPPCLS] = true
end
local name = cls.MAKE_LUANAME(cur:name(), 'VAR')
cls.VAR[name] = {NAME = name, SNIPPET = decl, CALLBACK_KIND = cbkind}
end
end
function M:visit_class(cur, cppcls)
local filter = {}
cppcls = cppcls or self:typename(cur, cur:type())
local cls = self.module.CLASSES[cppcls]
visited_type[cppcls] = cls
ignored_type[cppcls] = false
cls.KIND = cls.KIND or 'class'
if cur:kind() == 'Namespace' then
cls.REG_LUATYPE = false
end
for _, c in ipairs(cur:children()) do
local kind = c:kind()
local access = c:access()
if access == 'private' or access == 'protected' then
goto continue
elseif kind == 'CXXBaseSpecifier' then
if not cls.SUPERCLS then
cls.SUPERCLS = c:type():name()
end
elseif kind == 'FieldDecl' or kind == 'VarDecl' then
local vn = c:name()
local ct = c:type()
if cls.EXCLUDE_FUNC['*'] or cls.EXCLUDE_FUNC[vn] or vn:find('^_') then
goto continue
end
if ct:isConst() and kind == 'VarDecl' then
if not self:is_excluded_type(ct) then
cls.CONST[vn] = {NAME = vn, TYPENAME = ct:name()}
end
else
self:visit_var(cls, c)
end
elseif kind == 'Constructor' or kind == 'FunctionDecl' or kind == 'CXXMethod' then
local displayName = c:displayName()
local fn = c:name()
if (cls.EXCLUDE_FUNC['*'] or cls.EXCLUDE_FUNC[fn] or filter[displayName]) or
(kind == 'Constructor' and (cls.EXCLUDE_FUNC['new'] or cur:isAbstract())) then
goto continue
end
local func, prototype, cbkind = self:visit_method(cls, c)
if func and not filter[prototype] then
filter[displayName] = true
filter[prototype] = true
local static = c:isStatic()
if kind == 'FunctionDecl' then
func = 'static ' .. func
static = true
end
cls.FUNC[prototype] = {
FUNC = func,
NAME = fn,
STATIC = static,
NUM_ARGS = #c:arguments(),
CALLBACK_KIND = cbkind,
PROTOTYPE = prototype,
}
end
else
self:visit(c)
end
::continue::
end
end
function M:visit(cur)
local kind = cur:kind()
local children = cur:children()
local cls = self:typename(cur, cur:type())
local need_visit = self.module.CLASSES[cls] and not visited_type[cls]
if #children == 0 or string.find(cls, "^std::") then
return
elseif kind == 'Namespace' then
if need_visit then
self:visit_class(cur)
else
for _, c in ipairs(children) do
self:visit(c)
end
end
elseif kind == 'ClassDecl' or kind == 'StructDecl' then
if need_visit then
self:visit_class(cur)
else
if not self.module.EXCLUDE_TYPE[cls] and ignored_type[cls] == nil then
ignored_type[cls] = true
end
for _, c in ipairs(cur:children()) do
self:visit(c)
end
end
elseif kind == 'EnumDecl' then
if need_visit then
self:visit_enum(cur)
end
elseif kind == 'TypeAliasDecl' then
local ut = cur:underlyingType()
if ut:declaration():kind() == 'EnumDecl' then
type_alias[cls] = 'enum ' .. self:typename(cur, ut)
else
type_alias[cls] = self:typename(cur, ut)
end
elseif kind == 'TypedefDecl' then
local c = children[1]
if c and c:kind() == 'UnexposedAttr' then
return
end
local alias = cur:type():name()
local decl = cur:underlyingType():declaration()
local utk = decl:kind()
local name
--[[
namespace test {
typedef enum TAG_ {
} TAG
}
cur:underlyingType():name() => enum TAG_
cur:type():canonicalType():name() => test::TAG_
]]
if utk == 'StructDecl' then
name = self:typename(decl, decl:type())
if need_visit then
self:visit_class(decl, cls)
end
elseif utk == 'EnumDecl' then
if need_visit then
self:visit_enum(decl, cls)
end
name = 'enum ' .. self:typename(decl, decl:type())
else
name = self:typename(cur, cur:underlyingType())
end
type_alias[alias] = type_alias[name] or name
else
for _, c in ipairs(children) do
self:visit(c)
end
end
end
function M.__call(_, path)
local inst = setmetatable({}, {__index = M})
inst:parse(path)
end
function M.__gc()
xpcall(function ()
writer.write_alias_and_log({
visited_type = visited_type,
ignored_type = ignored_type,
refed_type = refed_type,
type_alias = type_alias,
type_convs = type_convs,
module_files = module_files,
log = log,
})
end,
function (message)
print(debug.traceback(message))
end)
end
-------------------------------------------------------------------------------
-- define config module
-------------------------------------------------------------------------------
local function add_command(cls)
local CMD = {}
function CMD.EXCLUDE_FUNC(name)
cls.EXCLUDE_FUNC[name] = true
return CMD
end
function CMD.ATTR(name, attrs)
cls.ATTR[name] = attrs
return CMD
end
function CMD.ENUM(name, value)
cls.ENUM[name] = {NAME = name, VALUE = value}
return CMD
end
function CMD.CONST(name, value, typename)
cls.CONST[name] = {NAME = name, VALUE = value, TYPENAME = typename}
end
function CMD.FUNC(fn, snippet)
cls.EXCLUDE_FUNC[fn] = true
cls.FUNC[fn] = {NAME = fn, SNIPPET = snippet}
return CMD
end
function CMD.CALLBACK(cb)
if not cb.NAME then
cb.NAME = olua.funcname(cb.FUNCS[1])
cls.EXCLUDE_FUNC[cb.NAME] = true
end
assert(#cb.NAME > 0, 'no callback function name')
cls.CALLBACK[cb.NAME] = cb
return CMD
end
function CMD.PROP(name, get, set)
cls.PROP[name] = {NAME = name, GET = get, SET = set}
return CMD
end
function CMD.VAR(name, snippet)
local varname = olua.funcname(snippet)
assert(#varname > 0, 'no variable name')
cls.EXCLUDE_FUNC[varname] = true
cls.VAR[name or varname] = {NAME = name, SNIPPET = snippet}
return CMD
end
function CMD.ALIAS(name, alias)
cls.ALIAS[name] = {NAME = name, ALIAS = alias}
return CMD
end
function CMD.INSERT(names, codes)
names = type(names) == 'string' and {names} or names
for _, n in ipairs(names) do
cls.INSERT[n] = {NAME = n, CODES = codes}
end
return CMD
end
function CMD.__index(_, key)
return cls[key]
end
function CMD.__newindex(_, key, value)
cls[key] = value
end
return setmetatable(CMD, CMD)
end
function M.typemod(name)
local INDEX = 1
local modinst = {
CLASSES = olua.newhash(),
EXCLUDE_TYPE = {},
TYPEDEFS = olua.newhash(),
NAME = name,
}
modinst.EXCLUDE_TYPE = setmetatable({}, {__call = function (_, tn)
modinst.EXCLUDE_TYPE[tn] = true
end})
function modinst.EXCLUDE_PASS()
end
function modinst.include(path)
loadfile(path)(modinst)
end
function modinst.typeconf(classname)
local cls = {
CPPCLS = assert(classname, 'not specify classname'),
LUACLS = modinst.MAKE_LUACLS(classname),
EXCLUDE_FUNC = olua.newhash(),
ATTR = olua.newhash(),
ENUM = olua.newhash(),
CONST = olua.newhash(),
FUNC = olua.newhash(),
CALLBACK = olua.newhash(),
PROP = olua.newhash(),
VAR = olua.newhash(),
ALIAS = olua.newhash(),
INSERT = olua.newhash(),
INDEX = INDEX,
REG_LUATYPE = true,
MAKE_LUANAME = function (n) return n end,
}
INDEX = INDEX + 1
assert(not modinst.CLASSES[classname], 'class conflict: ' .. classname)
modinst.CLASSES[classname] = cls
return add_command(cls)
end
function modinst.typeonly(classname)
local cls = modinst.typeconf(classname)
cls.EXCLUDE_FUNC '*'
return cls
end
function modinst.typedef(info)
modinst.TYPEDEFS[info.CPPCLS] = info
end
function modinst.typeconv(classname)
local cls = modinst.typeconf(classname)
cls.KIND = 'conv'
return cls
end
return modinst
end
return setmetatable(M, M)
|
PROPERTY = {};
PROPERTY.ID = 46;
PROPERTY.Name = "Suburbs House #8";
PROPERTY.Category = "House";
PROPERTY.Description = "A small house in the suburbs.";
PROPERTY.Image = "ev3x_subs78";
PROPERTY.Cost = 2000;
PROPERTY.Doors = {
{Vector(-3654.78125, 12153, 286.25), 'models/props_c17/door01_left.mdl'},
{Vector(-3780, 11754.1875, 286.25), 'models/props_c17/door01_left.mdl'},
{Vector(-3780, 11658.1875, 286.25), 'models/props_c17/door01_left.mdl'}
};
GAMEMODE:RegisterProperty(PROPERTY);
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('RoleAudit_pb', package.seeall)
local ROLEAUDIT = protobuf.Descriptor();
local ROLEAUDIT_SESSIONID_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_LEVEL_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_EXP_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_EXPDETA_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_MAXEXP_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_KILL_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_HIT_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_BATTLEMODE_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_ROOMTYPE_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_DAMAGE_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_CREDITDETA_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_HURTBLOOD_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_WINGAME_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_TOTALUSER_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_POWERDIFF_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_HITRATIO_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_KILLNUM_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_DROPNUM_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_PERFECT_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_SPY_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_SECONDKILL_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_ROUNDNUM_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_ACCURATENUM_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_REMARK_FIELD = protobuf.FieldDescriptor();
local ROLEAUDIT_ACTEXP_FIELD = protobuf.FieldDescriptor();
ROLEAUDIT_SESSIONID_FIELD.name = "sessionId"
ROLEAUDIT_SESSIONID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.sessionId"
ROLEAUDIT_SESSIONID_FIELD.number = 1
ROLEAUDIT_SESSIONID_FIELD.index = 0
ROLEAUDIT_SESSIONID_FIELD.label = 2
ROLEAUDIT_SESSIONID_FIELD.has_default_value = false
ROLEAUDIT_SESSIONID_FIELD.default_value = ""
ROLEAUDIT_SESSIONID_FIELD.type = 9
ROLEAUDIT_SESSIONID_FIELD.cpp_type = 9
ROLEAUDIT_LEVEL_FIELD.name = "level"
ROLEAUDIT_LEVEL_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.level"
ROLEAUDIT_LEVEL_FIELD.number = 2
ROLEAUDIT_LEVEL_FIELD.index = 1
ROLEAUDIT_LEVEL_FIELD.label = 2
ROLEAUDIT_LEVEL_FIELD.has_default_value = false
ROLEAUDIT_LEVEL_FIELD.default_value = 0
ROLEAUDIT_LEVEL_FIELD.type = 5
ROLEAUDIT_LEVEL_FIELD.cpp_type = 1
ROLEAUDIT_EXP_FIELD.name = "exp"
ROLEAUDIT_EXP_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.exp"
ROLEAUDIT_EXP_FIELD.number = 3
ROLEAUDIT_EXP_FIELD.index = 2
ROLEAUDIT_EXP_FIELD.label = 2
ROLEAUDIT_EXP_FIELD.has_default_value = false
ROLEAUDIT_EXP_FIELD.default_value = 0
ROLEAUDIT_EXP_FIELD.type = 5
ROLEAUDIT_EXP_FIELD.cpp_type = 1
ROLEAUDIT_EXPDETA_FIELD.name = "expDeta"
ROLEAUDIT_EXPDETA_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.expDeta"
ROLEAUDIT_EXPDETA_FIELD.number = 4
ROLEAUDIT_EXPDETA_FIELD.index = 3
ROLEAUDIT_EXPDETA_FIELD.label = 2
ROLEAUDIT_EXPDETA_FIELD.has_default_value = false
ROLEAUDIT_EXPDETA_FIELD.default_value = 0
ROLEAUDIT_EXPDETA_FIELD.type = 5
ROLEAUDIT_EXPDETA_FIELD.cpp_type = 1
ROLEAUDIT_MAXEXP_FIELD.name = "maxExp"
ROLEAUDIT_MAXEXP_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.maxExp"
ROLEAUDIT_MAXEXP_FIELD.number = 5
ROLEAUDIT_MAXEXP_FIELD.index = 4
ROLEAUDIT_MAXEXP_FIELD.label = 2
ROLEAUDIT_MAXEXP_FIELD.has_default_value = false
ROLEAUDIT_MAXEXP_FIELD.default_value = 0
ROLEAUDIT_MAXEXP_FIELD.type = 5
ROLEAUDIT_MAXEXP_FIELD.cpp_type = 1
ROLEAUDIT_KILL_FIELD.name = "kill"
ROLEAUDIT_KILL_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.kill"
ROLEAUDIT_KILL_FIELD.number = 6
ROLEAUDIT_KILL_FIELD.index = 5
ROLEAUDIT_KILL_FIELD.label = 2
ROLEAUDIT_KILL_FIELD.has_default_value = false
ROLEAUDIT_KILL_FIELD.default_value = 0
ROLEAUDIT_KILL_FIELD.type = 5
ROLEAUDIT_KILL_FIELD.cpp_type = 1
ROLEAUDIT_HIT_FIELD.name = "hit"
ROLEAUDIT_HIT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.hit"
ROLEAUDIT_HIT_FIELD.number = 7
ROLEAUDIT_HIT_FIELD.index = 6
ROLEAUDIT_HIT_FIELD.label = 2
ROLEAUDIT_HIT_FIELD.has_default_value = false
ROLEAUDIT_HIT_FIELD.default_value = 0
ROLEAUDIT_HIT_FIELD.type = 5
ROLEAUDIT_HIT_FIELD.cpp_type = 1
ROLEAUDIT_BATTLEMODE_FIELD.name = "battleMode"
ROLEAUDIT_BATTLEMODE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.battleMode"
ROLEAUDIT_BATTLEMODE_FIELD.number = 8
ROLEAUDIT_BATTLEMODE_FIELD.index = 7
ROLEAUDIT_BATTLEMODE_FIELD.label = 1
ROLEAUDIT_BATTLEMODE_FIELD.has_default_value = false
ROLEAUDIT_BATTLEMODE_FIELD.default_value = 0
ROLEAUDIT_BATTLEMODE_FIELD.type = 5
ROLEAUDIT_BATTLEMODE_FIELD.cpp_type = 1
ROLEAUDIT_ROOMTYPE_FIELD.name = "roomType"
ROLEAUDIT_ROOMTYPE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.roomType"
ROLEAUDIT_ROOMTYPE_FIELD.number = 9
ROLEAUDIT_ROOMTYPE_FIELD.index = 8
ROLEAUDIT_ROOMTYPE_FIELD.label = 1
ROLEAUDIT_ROOMTYPE_FIELD.has_default_value = false
ROLEAUDIT_ROOMTYPE_FIELD.default_value = 0
ROLEAUDIT_ROOMTYPE_FIELD.type = 5
ROLEAUDIT_ROOMTYPE_FIELD.cpp_type = 1
ROLEAUDIT_DAMAGE_FIELD.name = "damage"
ROLEAUDIT_DAMAGE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.damage"
ROLEAUDIT_DAMAGE_FIELD.number = 10
ROLEAUDIT_DAMAGE_FIELD.index = 9
ROLEAUDIT_DAMAGE_FIELD.label = 1
ROLEAUDIT_DAMAGE_FIELD.has_default_value = false
ROLEAUDIT_DAMAGE_FIELD.default_value = 0
ROLEAUDIT_DAMAGE_FIELD.type = 5
ROLEAUDIT_DAMAGE_FIELD.cpp_type = 1
ROLEAUDIT_CREDITDETA_FIELD.name = "creditDeta"
ROLEAUDIT_CREDITDETA_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.creditDeta"
ROLEAUDIT_CREDITDETA_FIELD.number = 11
ROLEAUDIT_CREDITDETA_FIELD.index = 10
ROLEAUDIT_CREDITDETA_FIELD.label = 1
ROLEAUDIT_CREDITDETA_FIELD.has_default_value = false
ROLEAUDIT_CREDITDETA_FIELD.default_value = 0
ROLEAUDIT_CREDITDETA_FIELD.type = 5
ROLEAUDIT_CREDITDETA_FIELD.cpp_type = 1
ROLEAUDIT_HURTBLOOD_FIELD.name = "hurtBlood"
ROLEAUDIT_HURTBLOOD_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.hurtBlood"
ROLEAUDIT_HURTBLOOD_FIELD.number = 12
ROLEAUDIT_HURTBLOOD_FIELD.index = 11
ROLEAUDIT_HURTBLOOD_FIELD.label = 1
ROLEAUDIT_HURTBLOOD_FIELD.has_default_value = false
ROLEAUDIT_HURTBLOOD_FIELD.default_value = 0
ROLEAUDIT_HURTBLOOD_FIELD.type = 5
ROLEAUDIT_HURTBLOOD_FIELD.cpp_type = 1
ROLEAUDIT_WINGAME_FIELD.name = "winGame"
ROLEAUDIT_WINGAME_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.winGame"
ROLEAUDIT_WINGAME_FIELD.number = 13
ROLEAUDIT_WINGAME_FIELD.index = 12
ROLEAUDIT_WINGAME_FIELD.label = 1
ROLEAUDIT_WINGAME_FIELD.has_default_value = false
ROLEAUDIT_WINGAME_FIELD.default_value = 0
ROLEAUDIT_WINGAME_FIELD.type = 5
ROLEAUDIT_WINGAME_FIELD.cpp_type = 1
ROLEAUDIT_TOTALUSER_FIELD.name = "totalUser"
ROLEAUDIT_TOTALUSER_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.totalUser"
ROLEAUDIT_TOTALUSER_FIELD.number = 14
ROLEAUDIT_TOTALUSER_FIELD.index = 13
ROLEAUDIT_TOTALUSER_FIELD.label = 1
ROLEAUDIT_TOTALUSER_FIELD.has_default_value = false
ROLEAUDIT_TOTALUSER_FIELD.default_value = 0
ROLEAUDIT_TOTALUSER_FIELD.type = 5
ROLEAUDIT_TOTALUSER_FIELD.cpp_type = 1
ROLEAUDIT_POWERDIFF_FIELD.name = "powerDiff"
ROLEAUDIT_POWERDIFF_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.powerDiff"
ROLEAUDIT_POWERDIFF_FIELD.number = 15
ROLEAUDIT_POWERDIFF_FIELD.index = 14
ROLEAUDIT_POWERDIFF_FIELD.label = 1
ROLEAUDIT_POWERDIFF_FIELD.has_default_value = false
ROLEAUDIT_POWERDIFF_FIELD.default_value = 0
ROLEAUDIT_POWERDIFF_FIELD.type = 5
ROLEAUDIT_POWERDIFF_FIELD.cpp_type = 1
ROLEAUDIT_HITRATIO_FIELD.name = "hitRatio"
ROLEAUDIT_HITRATIO_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.hitRatio"
ROLEAUDIT_HITRATIO_FIELD.number = 16
ROLEAUDIT_HITRATIO_FIELD.index = 15
ROLEAUDIT_HITRATIO_FIELD.label = 1
ROLEAUDIT_HITRATIO_FIELD.has_default_value = false
ROLEAUDIT_HITRATIO_FIELD.default_value = 0
ROLEAUDIT_HITRATIO_FIELD.type = 5
ROLEAUDIT_HITRATIO_FIELD.cpp_type = 1
ROLEAUDIT_KILLNUM_FIELD.name = "killNum"
ROLEAUDIT_KILLNUM_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.killNum"
ROLEAUDIT_KILLNUM_FIELD.number = 17
ROLEAUDIT_KILLNUM_FIELD.index = 16
ROLEAUDIT_KILLNUM_FIELD.label = 1
ROLEAUDIT_KILLNUM_FIELD.has_default_value = false
ROLEAUDIT_KILLNUM_FIELD.default_value = 0
ROLEAUDIT_KILLNUM_FIELD.type = 5
ROLEAUDIT_KILLNUM_FIELD.cpp_type = 1
ROLEAUDIT_DROPNUM_FIELD.name = "dropNum"
ROLEAUDIT_DROPNUM_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.dropNum"
ROLEAUDIT_DROPNUM_FIELD.number = 18
ROLEAUDIT_DROPNUM_FIELD.index = 17
ROLEAUDIT_DROPNUM_FIELD.label = 1
ROLEAUDIT_DROPNUM_FIELD.has_default_value = false
ROLEAUDIT_DROPNUM_FIELD.default_value = 0
ROLEAUDIT_DROPNUM_FIELD.type = 5
ROLEAUDIT_DROPNUM_FIELD.cpp_type = 1
ROLEAUDIT_PERFECT_FIELD.name = "perfect"
ROLEAUDIT_PERFECT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.perfect"
ROLEAUDIT_PERFECT_FIELD.number = 19
ROLEAUDIT_PERFECT_FIELD.index = 18
ROLEAUDIT_PERFECT_FIELD.label = 1
ROLEAUDIT_PERFECT_FIELD.has_default_value = false
ROLEAUDIT_PERFECT_FIELD.default_value = 0
ROLEAUDIT_PERFECT_FIELD.type = 5
ROLEAUDIT_PERFECT_FIELD.cpp_type = 1
ROLEAUDIT_SPY_FIELD.name = "spy"
ROLEAUDIT_SPY_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.spy"
ROLEAUDIT_SPY_FIELD.number = 20
ROLEAUDIT_SPY_FIELD.index = 19
ROLEAUDIT_SPY_FIELD.label = 1
ROLEAUDIT_SPY_FIELD.has_default_value = false
ROLEAUDIT_SPY_FIELD.default_value = 0
ROLEAUDIT_SPY_FIELD.type = 5
ROLEAUDIT_SPY_FIELD.cpp_type = 1
ROLEAUDIT_SECONDKILL_FIELD.name = "secondKill"
ROLEAUDIT_SECONDKILL_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.secondKill"
ROLEAUDIT_SECONDKILL_FIELD.number = 21
ROLEAUDIT_SECONDKILL_FIELD.index = 20
ROLEAUDIT_SECONDKILL_FIELD.label = 1
ROLEAUDIT_SECONDKILL_FIELD.has_default_value = false
ROLEAUDIT_SECONDKILL_FIELD.default_value = 0
ROLEAUDIT_SECONDKILL_FIELD.type = 5
ROLEAUDIT_SECONDKILL_FIELD.cpp_type = 1
ROLEAUDIT_ROUNDNUM_FIELD.name = "roundNum"
ROLEAUDIT_ROUNDNUM_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.roundNum"
ROLEAUDIT_ROUNDNUM_FIELD.number = 22
ROLEAUDIT_ROUNDNUM_FIELD.index = 21
ROLEAUDIT_ROUNDNUM_FIELD.label = 1
ROLEAUDIT_ROUNDNUM_FIELD.has_default_value = false
ROLEAUDIT_ROUNDNUM_FIELD.default_value = 0
ROLEAUDIT_ROUNDNUM_FIELD.type = 5
ROLEAUDIT_ROUNDNUM_FIELD.cpp_type = 1
ROLEAUDIT_ACCURATENUM_FIELD.name = "accurateNum"
ROLEAUDIT_ACCURATENUM_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.accurateNum"
ROLEAUDIT_ACCURATENUM_FIELD.number = 23
ROLEAUDIT_ACCURATENUM_FIELD.index = 22
ROLEAUDIT_ACCURATENUM_FIELD.label = 1
ROLEAUDIT_ACCURATENUM_FIELD.has_default_value = false
ROLEAUDIT_ACCURATENUM_FIELD.default_value = 0
ROLEAUDIT_ACCURATENUM_FIELD.type = 5
ROLEAUDIT_ACCURATENUM_FIELD.cpp_type = 1
ROLEAUDIT_REMARK_FIELD.name = "remark"
ROLEAUDIT_REMARK_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.remark"
ROLEAUDIT_REMARK_FIELD.number = 24
ROLEAUDIT_REMARK_FIELD.index = 23
ROLEAUDIT_REMARK_FIELD.label = 1
ROLEAUDIT_REMARK_FIELD.has_default_value = false
ROLEAUDIT_REMARK_FIELD.default_value = ""
ROLEAUDIT_REMARK_FIELD.type = 9
ROLEAUDIT_REMARK_FIELD.cpp_type = 9
ROLEAUDIT_ACTEXP_FIELD.name = "actexp"
ROLEAUDIT_ACTEXP_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit.actexp"
ROLEAUDIT_ACTEXP_FIELD.number = 25
ROLEAUDIT_ACTEXP_FIELD.index = 24
ROLEAUDIT_ACTEXP_FIELD.label = 1
ROLEAUDIT_ACTEXP_FIELD.has_default_value = false
ROLEAUDIT_ACTEXP_FIELD.default_value = 0
ROLEAUDIT_ACTEXP_FIELD.type = 5
ROLEAUDIT_ACTEXP_FIELD.cpp_type = 1
ROLEAUDIT.name = "RoleAudit"
ROLEAUDIT.full_name = ".com.xinqihd.sns.gameserver.proto.RoleAudit"
ROLEAUDIT.nested_types = {}
ROLEAUDIT.enum_types = {}
ROLEAUDIT.fields = {ROLEAUDIT_SESSIONID_FIELD, ROLEAUDIT_LEVEL_FIELD, ROLEAUDIT_EXP_FIELD, ROLEAUDIT_EXPDETA_FIELD, ROLEAUDIT_MAXEXP_FIELD, ROLEAUDIT_KILL_FIELD, ROLEAUDIT_HIT_FIELD, ROLEAUDIT_BATTLEMODE_FIELD, ROLEAUDIT_ROOMTYPE_FIELD, ROLEAUDIT_DAMAGE_FIELD, ROLEAUDIT_CREDITDETA_FIELD, ROLEAUDIT_HURTBLOOD_FIELD, ROLEAUDIT_WINGAME_FIELD, ROLEAUDIT_TOTALUSER_FIELD, ROLEAUDIT_POWERDIFF_FIELD, ROLEAUDIT_HITRATIO_FIELD, ROLEAUDIT_KILLNUM_FIELD, ROLEAUDIT_DROPNUM_FIELD, ROLEAUDIT_PERFECT_FIELD, ROLEAUDIT_SPY_FIELD, ROLEAUDIT_SECONDKILL_FIELD, ROLEAUDIT_ROUNDNUM_FIELD, ROLEAUDIT_ACCURATENUM_FIELD, ROLEAUDIT_REMARK_FIELD, ROLEAUDIT_ACTEXP_FIELD}
ROLEAUDIT.is_extendable = false
ROLEAUDIT.extensions = {}
RoleAudit = protobuf.Message(ROLEAUDIT)
_G.ROLEAUDIT_PB_ROLEAUDIT = ROLEAUDIT
|
data:extend({
{
type = "technology",
name = "vacuum-logistics-4",
icon_size = 128,
icon = "__base__/graphics/technology/logistics.png",
effects =
{
{
type = "unlock-recipe",
recipe = "vacuum-transport-belt"
},
{
type = "unlock-recipe",
recipe = "vacuum-underground-belt"
},
{
type = "unlock-recipe",
recipe = "vacuum-splitter"
}
},
prerequisites = {"logistics-3"},
unit =
{
count = 600,
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
{"production-science-pack", 1}
},
time = 30
},
order = "a-f-d"
}
})
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
SlashCommandAutoComplete = ZO_AutoComplete:Subclass()
function SlashCommandAutoComplete:New(...)
return ZO_AutoComplete.New(self, ...)
end
function SlashCommandAutoComplete:Initialize(editControl, ...)
ZO_AutoComplete.Initialize(self, editControl, ...)
self.possibleMatches = {}
self:SetUseCallbacks(true)
self:SetAnchorStyle(AUTO_COMPLETION_ANCHOR_BOTTOM)
self:SetOwner(SLASH_COMMANDS)
self:SetKeepFocusOnCommit(true)
local function OnAutoCompleteEntrySelected(name, selectionMethod)
editControl:SetText(name)
end
self:RegisterCallback(ZO_AutoComplete.ON_ENTRY_SELECTED, OnAutoCompleteEntrySelected)
ZO_PreHook("ZO_ChatTextEntry_PreviousCommand", function(...)
if not IsShiftKeyDown() and self:IsOpen() then
local index = self:GetAutoCompleteIndex()
if not index or index > 1 then
self:ChangeAutoCompleteIndex(-1)
return true
end
end
end)
ZO_PreHook("ZO_ChatTextEntry_NextCommand", function(...)
if not IsShiftKeyDown() and self:IsOpen() then
local index = self:GetAutoCompleteIndex()
if not index or index < self:GetNumAutoCompleteEntries() then
self:ChangeAutoCompleteIndex(1)
return true --Handled
end
end
end)
local function OnEmoteSlashCommandsUpdated()
self:InvalidateSlashCommandCache()
end
PLAYER_EMOTE_MANAGER:RegisterCallback("EmoteSlashCommandsUpdated", OnEmoteSlashCommandsUpdated)
end
function SlashCommandAutoComplete:InvalidateSlashCommandCache()
self.possibleMatches = {}
end
function SlashCommandAutoComplete:GetAutoCompletionResults(text)
if #text < 3 then
return
end
local startChar = text:sub(1, 1)
if startChar ~= "/" and startChar ~= "]" then
return
end
if text:find(" ", 1, true) then
return
end
if next(self.possibleMatches) == nil then
for command in pairs(SLASH_COMMANDS) do
if #command > 0 then
self.possibleMatches[command:lower()] = command
end
end
if BRACKET_COMMANDS then
for command in pairs(BRACKET_COMMANDS) do
if #command > 0 then
self.possibleMatches[command:lower()] = command
end
end
end
if SERVER_BRACKET_COMMANDS then
for command in pairs(SERVER_BRACKET_COMMANDS) do
if #command > 0 then
self.possibleMatches[command:lower()] = command
end
end
end
local switchLookup = ZO_ChatSystem_GetChannelSwitchLookupTable()
for channelId, switchString in ipairs(switchLookup) do
self.possibleMatches[switchString:lower()] = switchString
end
end
local results = GetTopMatchesByLevenshteinSubStringScore(self.possibleMatches, text, 2, self.maxResults)
if results then
return unpack(results)
end
return nil
end
|
function fuse(together, allpersonas)
local combos = require("data/fusion_combos")[#together.."way"]
local fusebetween = ""
local fusebetweenbackwards = ""
local base_level = 0
local temp = {}
local nextlowest = {}
local common = false
for name, persona in pairs(together) do
if persona.arcana == common then common=true else common=persona.arcana end--Won't work for 3way+
fusebetween = fusebetween .. persona.arcana
fusebetweenbackwards = persona.arcana .. fusebetweenbackwards
base_level = base_level + persona.level
-- if (persona.level > base_level and base_level == 0) or (persona.level < base_level) then
-- base_level = persona.level
-- end
end
base_level = base_level/(#together)+1--This is how it was done in the python fusion script that I had written.
if not (type(common) == 'boolean') then common=false end
print(fusebetween, combos[fusebetween])
if combos[fusebetween] or combos[fusebetweenbackwards] then
for name, persona in pairs(allpersonas) do
if persona.arcana == combos[fusebetween] or persona.arcana == combos[fusebetweenbackwards] then
temp[persona.name] = persona
end
end
nextlowest.level = 100
for name, persona in pairs(temp) do
if not common then
if persona.level > base_level and persona.level < nextlowest.level then
nextlowest = persona
end
else
if persona.level < nextlowest.level then
nextlowest = persona
end
end
end
end
return nextlowest
end
testps = {Pixie={name='Pixie', arcana='Lovers', level=10}, Io={name='Io', arcana='Lovers', level=1}, Cybele={name='Cybele', arcana='Lovers', level=64},Orpheus={name='Orpheus', arcana='Fool', level=1}, JackFrost={name='Jack Frost', arcana='Magician', level=8}, Angel={name='Angel', arcana='Justice', level=4}}
fusing = {testps.Orpheus, testps.Angel}
print(#fusing .. 'way')
result = fuse(fusing, testps)
if result.name then
for key,value in pairs(result) do
print(key, value)
end
else
print("No valid fusion results")
end
|
--[[
说明:
本示例C++源码:
\Source\TPSProject\TutorialObject.cpp
]]--
require "UnLua"
local Screen = require "Tutorials.Screen"
local M = Class()
function M:ReceiveBeginPlay()
local msg =
[[
—— 本示例来自 "Content/Script/Tutorials.09_StaticExport.lua"
]]
Screen.Print(msg)
local tutorial = UE4.FTutorialObject("教程")
msg = string.format("tutorial -> %s\n\ntutorial:GetTitle() -> %s", tostring(tutorial), tutorial:GetTitle())
Screen.Print(msg)
end
return M
|
local Map = require "maps.map"
local Polis = Map:new()
function Polis:new(o, control)
o = o or Map:new(o, control)
setmetatable(o, self)
self.__index = self
return o
end
function Polis:create()
Map.create(self)
end
function Polis:enter()
Map.enter(self)
local door = self.data.objects.cellar_door
if door.properties.locked then
if self.control.data.rat_cellar_open then
door.properties.locked = false
for index, coords in ipairs(door.coords) do
sfml_set_obstacle(false, coords.x, coords.y)
end
end
end
if self.control.data.imps_win then
sfml_remove_character('town_elf')
end
end
function Polis:exit()
Map.exit(self)
end
function Polis:cellar_door(event, x, y, character_name, object_name)
local object = self.data.objects[object_name]
if not object.properties.locked then
Map.cellar_door(self, event, x, y, character_name, object_name)
else
if character_name == 'player' then
if self.control.characters.player.data.stats.ability.wis >= 13 then
sfml_text_box("(Wis 13) There is a trap door hidden under the building. It is barred from the inside.")
end
end
end
end
return Polis
|
-- Take note that if you change the paths here, the paths quoted into the tas-scaffolding's README.md will be no
-- more valid. Do it with caution.
return {
['bk2'] = 'plugins/bizhawk/bk2',
['files'] = 'configuration/files',
['preloads'] = 'plugins/preload/collection',
['savestate'] = 'plugins/preload/savestate',
['screenshot'] = 'plugins/screenshot/configuration',
['tas'] = 'tas',
['tpl_new_file'] = 'assets/templates/new-tas-file.lua',
}
|
object_draft_schematic_food_bantha_surprise = object_draft_schematic_food_shared_bantha_surprise:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_food_bantha_surprise, "object/draft_schematic/food/bantha_surprise.iff")
|
local composer = require( "composer" )
local cards = require('cards')
local scene = composer.newScene()
local bottomHeight = 100
local restHeight = display.contentHeight - bottomHeight
local restCenterY = restHeight * 0.5
local padding = 50
local cornerRadius = 20
local cardSpacing = 50 * 0.5
local sceneGroup
local cardStack
local function newCardFunction(cframe, color)
local rect = display.newRoundedRect(cframe.x, cframe.y, cframe.width, cframe.height, cornerRadius)
rect:setFillColor(color.red, color.green, color.blue)
rect:addEventListener("touch", function(event) cardStack:dragHandler(event) end)
sceneGroup:insert(rect)
-- SMELL: should probably pass cardStack in as param to newCardFunction (like a delegate call in objc)
return rect
end
local function updateXFunction(x, updateTarget)
updateTarget.x = x
end
local config = {
containerSize={width=display.contentWidth, height=display.contentHeight },
edgePadding=50,
cardGap=25
}
local completeMoveFunction = function(updaterObject, updateTo)
transition.to(updaterObject, {x=updateTo, transition=easing.outExpo, onComplete=updaterObject.completeFunction})
end
-- "scene:create()"
function scene:create( event )
sceneGroup = self.view
cardStack = cards.newCardStack(config, newCardFunction, updateXFunction)
cardStack.completeMoveFunction = completeMoveFunction
local card1 = cards.newCard(0, 0.65, 0.97)
cardStack:addCard(card1)
local card2 = cards.newCard(0.8, 0.3, 0.1)
cardStack:addCard(card2)
local card3 = cards.newCard(0.5, 0.5, 0.5)
cardStack:addCard(card3)
end
-- "scene:show()"
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
-- Called when the scene is still off screen (but is about to come on screen).
elseif ( phase == "did" ) then
-- Called when the scene is now on screen.
-- Insert code here to make the scene come alive.
-- Example: start timers, begin animation, play audio, etc.
end
end
-- "scene:hide()"
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
-- Called when the scene is on screen (but is about to go off screen).
-- Insert code here to "pause" the scene.
-- Example: stop timers, stop animation, stop audio, etc.
elseif ( phase == "did" ) then
-- Called immediately after scene goes off screen.
end
end
-- "scene:destroy()"
function scene:destroy( event )
local sceneGroup = self.view
-- Called prior to the removal of scene's view ("sceneGroup").
-- Insert code here to clean up the scene.
-- Example: remove display objects, save state, etc.
end
-- -------------------------------------------------------------------------------
-- Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
-- -------------------------------------------------------------------------------
return scene
|
-- Copyright © 2016 g0ld <g0ld@tuta.io>
-- This work is free. You can redistribute it and/or modify it under the
-- terms of the Do What The Fuck You Want To Public License, Version 2,
-- as published by Sam Hocevar. See the COPYING file for more details.
-- Quest: @Rympex
local sys = require "Libs/syslib"
local game = require "Libs/gamelib"
local Quest = require "Quests/Quest"
local Dialog = require "Quests/Dialog"
local name = 'Ilex Forest'
local description = ' Farfetch Quest'
local dialogs = {
farfetchQuestAccept = Dialog:new({
"have you found it yet"
})
}
local IlexForestQuest = Quest:new()
function IlexForestQuest:new()
local o = Quest.new(IlexForestQuest, name, description, level, dialogs)
o.pokemon = "Caterpie"
o.pokemonId = 1
o.forceCaught = false
return o
end
function IlexForestQuest:isDoable()
if self:hasMap() and not hasItem("Plain Badge") then
return true
end
return false
end
function IlexForestQuest:isDone()
if getMapName() == "Goldenrod City" or getMapName() == "Pokecenter Azalea" or getMapName() == "Pokecenter Goldenrod" or getMapName() == "Azalea Town" then
return true
end
return false
end
function IlexForestQuest:IlexForestStopHouse()
if self:needPokecenter() then
sys.debug("quest", "Going to heal Pokemon.")
return moveToCell(10, 6)
else
sys.debug("quest", "Going to Ilex Forest.")
return moveToCell(0, 6)
end
end
function IlexForestQuest:IlexForest()
if self:needPokecenter() then
sys.debug("quest", "Going to heal Pokemon.")
return moveToCell(10, 74)
elseif isNpcOnCell(12, 58) then
if not dialogs.farfetchQuestAccept.state then
sys.debug("quest", "Going to talk to NPC.")
return talkToNpcOnCell(12, 58)
else
if isNpcOnCell(47, 42) then
sys.debug("quest", "Going to talk to Farfetch'd.")
return talkToNpcOnCell(47, 42)
else
sys.debug("quest", "Going to talk to NPC.")
return talkToNpcOnCell(12, 58)
end
end
elseif not self.forceCaught then
sys.debug("quest", "Going to catch " .. self.pokemon)
return moveToRectangle(16, 43, 48, 63)
else
if not game.hasPokemonWithMove("Cut") then
if self.pokemonId < getTeamSize() then
useItemOnPokemon("HM01 - Cut", self.pokemonId)
log("Pokemon: " .. self.pokemonId .. " Try Learning: HM01 - Cut")
self.pokemonId = self.pokemonId + 1
else
fatal("No pokemon in this team can learn Cut")
end
else
sys.debug("quest", "Going to Goldenrod City.")
return moveToCell(8, 7)
end
end
end
function IlexForestQuest:Route34StopHouse()
sys.debug("quest", "Going to Goldenrod City.")
return moveToCell(4, 2)
end
function IlexForestQuest:Route34()
sys.debug("quest", "Going to Goldenrod City.")
return moveToCell(13, 0)
end
return IlexForestQuest
|
local mock = require('luassert.mock')
describe("Kartograaf", function()
local cut = require('../lua/kartograaf')
describe("map", function()
it("Should call nvim_set_keymap", function()
local maps = {}
maps['i'] = { { 'l', 'r' } }
maps['n'] = maps['i']
local api = mock(vim.api, true)
cut.map(maps)
assert.stub(api.nvim_set_keymap).was_called_with('i', 'l', 'r', { noremap = true })
assert.stub(api.nvim_set_keymap).was_called_with('n', 'l', 'r', { noremap = true })
mock.revert(api)
end)
it("Should map with modifiers", function()
local api = mock(vim.api, true)
cut.map({
n = {
{
mod = 'C',
{ 'l', 'r' },
{ 'a', 'x' }
}
}
}
)
assert.stub(api.nvim_set_keymap).was_called_with('n', '<C-l>', 'r', { noremap = true })
assert.stub(api.nvim_set_keymap).was_called_with('n', '<C-a>', 'x', { noremap = true })
mock.revert(api)
end)
it("Should coalesce options", function()
local mappings = {}
mappings['i'] = {
{
mod = 'M',
options = { a = '1' },
{ 'l', 'r', { b = 2 } }
},
{
mod = 'C',
options = { x = 'y' },
{ 'l', 'r', { w = 5 } }
}
}
local api = mock(vim.api, true)
cut.map(mappings)
assert.stub(api.nvim_set_keymap).was_called_with('i', '<M-l>', 'r', { a = '1', b = 2, noremap = true })
assert.stub(api.nvim_set_keymap).was_called_with('i', '<C-l>', 'r', { x = 'y', w = 5, noremap = true })
mock.revert(api)
end)
it("Should allow explicit modifiers", function()
local mappings = {}
mappings['i'] = {
{
{ '<C-l><C-l>', 'r', }
}
}
local api = mock(vim.api, true)
cut.map(mappings)
assert.stub(api.nvim_set_keymap).was_called_with('i', '<C-l><C-l>', 'r', { noremap = true })
mock.revert(api)
end)
it("Should coalesce mappings", function()
local mappings = {}
mappings['i'] = {
{
prefix = '<leader>',
{ '<leader>t', 'r', }
}
}
local api = mock(vim.api, true)
cut.map(mappings)
assert.stub(api.nvim_set_keymap).was_called_with('i', '<leader><leader>t', 'r', { noremap = true })
mock.revert(api)
end)
it("Should coalesce with modifiers mappings", function()
local mappings = {}
mappings['i'] = {
{
prefix = '<leader>',
mod = 'C',
{ 't', 'r', }
}
}
local api = mock(vim.api, true)
cut.map(mappings)
assert.stub(api.nvim_set_keymap).was_called_with('i', '<leader><C-t>', 'r', { noremap = true })
mock.revert(api)
end)
it("Should allow plain prefix", function()
local mappings = {}
mappings['i'] = {
{
prefix = 'g',
{ 'd', 'r', }
}
}
local api = mock(vim.api, true)
cut.map(mappings)
assert.stub(api.nvim_set_keymap).was_called_with('i', 'gd', 'r', { noremap = true })
mock.revert(api)
end)
it("Should allow setting buffer", function()
local mappings = {
buffer = 456,
i = {
{
prefix = '<leader>',
{ '<leader>l', 'lrx'},
},
},
n = {
options = { silent = true},
{
prefix = '<leader>',
{ '<leader>l', 'lrx'},
},
{
prefix = 'g',
{ 'D', 'rgx'},
},
{
mod = 'C',
{ 'x', 'rx'},
},
{'<C-r><C-r>', [[xyz]]},
}
}
local api = mock(vim.api, true)
cut.map(mappings)
assert.stub(api.nvim_buf_set_keymap).was_called_with(456, 'i', '<leader><leader>l', 'lrx', { noremap = true })
assert.stub(api.nvim_buf_set_keymap).was_called_with(456, 'n', '<leader><leader>l', 'lrx', { noremap = true, silent = true })
assert.stub(api.nvim_buf_set_keymap).was_called_with(456, 'n', '<C-x>', 'rx', { noremap = true, silent = true })
assert.stub(api.nvim_buf_set_keymap).was_called_with(456, 'n', 'gD', 'rgx', { noremap = true, silent = true })
assert.stub(api.nvim_buf_set_keymap).was_called_with(456, 'n', '<C-r><C-r>', 'xyz', { noremap = true, silent = true })
mock.revert(api)
end)
it("Should allow setting buffer at mode level", function()
local mappings = {
buffer = 0,
n = {
options = { silent = true},
buffer = 123,
{
prefix = '<leader>',
{ '<leader>l', 'lrx'},
},
{
prefix = 'g',
{ 'D', 'rgx'},
},
{
mod = 'C',
{ 'x', 'rx'},
},
},
i = {
{ 'xd', 'r'}
}
}
local api = mock(vim.api, true)
cut.map(mappings)
assert.stub(api.nvim_buf_set_keymap).was_called_with(123, 'n', '<leader><leader>l', 'lrx', { noremap = true, silent = true })
assert.stub(api.nvim_buf_set_keymap).was_called_with(123, 'n', '<C-x>', 'rx', { noremap = true, silent = true })
assert.stub(api.nvim_buf_set_keymap).was_called_with(123, 'n', 'gD', 'rgx', { noremap = true, silent = true })
assert.stub(api.nvim_buf_set_keymap).was_called_with(0, 'i', 'xd', 'r', { noremap = true })
mock.revert(api)
end)
it("Should traverse all depths", function()
local maps = {
n = {
options = { a = 'b'},
{ '<Space>', '<Nop>' },
{ '<tab>', 'za' },
{
mod = 'C',
{ 'h', '<C-w>h', { noremap = false } },
{ 'j', '<C-w>j', { expr = true, silent = true} },
{ 'k', '<C-w>k' },
{ 'l', '<C-w>l' },
}
},
i = {
options = { x = 'y'},
{ 'F', 'ab' },
}
}
local api = mock(vim.api, true)
cut.map(maps)
assert.stub(api.nvim_set_keymap).was_called_with('n', '<Space>', '<Nop>', { a = 'b', noremap = true})
assert.stub(api.nvim_set_keymap).was_called_with('n', '<tab>', 'za', { a = 'b', noremap = true})
assert.stub(api.nvim_set_keymap).was_called_with('n', '<C-h>', '<C-w>h', { a = 'b', noremap = false })
assert.stub(api.nvim_set_keymap).was_called_with('n', '<C-j>', '<C-w>j', { a = 'b', noremap = true, expr = true, silent = true })
assert.stub(api.nvim_set_keymap).was_called_with('i', 'F', 'ab', { x = 'y', noremap = true })
mock.revert(api)
end)
it("Should allow double bindings with modifier", function()
local maps = {
debug = true,
n = {
{
mod = 'C',
{ 'h,l', 'rhs' }
}
}
}
local api = mock(vim.api, true)
cut.map(maps)
assert.stub(api.nvim_set_keymap).was_called_with('n', '<C-h><C-l>', 'rhs', { noremap = true })
mock.revert(api)
end)
end)
end)
|
-- See LICENSE for terms
local ChoOrig_ConstructionSite_BuildingUpdate = ConstructionSite.BuildingUpdate
function ConstructionSite:BuildingUpdate(...)
if self.construction_started and g_ConstructionNanitesResearched and self.working then
return ChoOrig_ConstructionSite_BuildingUpdate(self, ...)
end
end
|
--- === cp.apple.finalcutpro.main.EffectsBrowser ===
---
--- Effects Browser Module.
local require = require
-- local log = require "hs.logger".new("EffectsBrowser")
local geometry = require "hs.geometry"
local fnutils = require "hs.fnutils"
local axutils = require "cp.ui.axutils"
local Group = require "cp.ui.Group"
local tools = require "cp.tools"
local just = require "cp.just"
local Table = require "cp.ui.Table"
local ScrollArea = require "cp.ui.ScrollArea"
local CheckBox = require "cp.ui.CheckBox"
local PopUpButton = require "cp.ui.PopUpButton"
local TextField = require "cp.ui.TextField"
local Do = require "cp.rx.go.Do"
local Given = require "cp.rx.go.Given"
local If = require "cp.rx.go.If"
local WaitUntil = require "cp.rx.go.WaitUntil"
local ninjaDoubleClick = tools.ninjaDoubleClick
local EffectsBrowser = Group:subclass("cp.apple.finalcutpro.main.EffectsBrowser")
--- cp.apple.finalcutpro.main.EffectsBrowser.EFFECTS -> string
--- Constant
--- Effects.
EffectsBrowser.static.EFFECTS = "Effects"
--- cp.apple.finalcutpro.main.EffectsBrowser.TRANSITIONS -> string
--- Constant
--- Transitions.
EffectsBrowser.static.TRANSITIONS = "Transitions"
--- cp.apple.finalcutpro.main.EffectsBrowser.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function EffectsBrowser.static.matches(element)
return Group.matches(element) and #element == 4
end
--- cp.apple.finalcutpro.main.EffectsBrowser(parent, type) -> EffectsBrowser
--- Constructor
--- Creates a new `EffectsBrowser` instance.
---
--- Parameters:
--- * parent - The parent object.
--- * type - A string determining whether the Effects Browser is for Effects (`cp.apple.finalcutpro.main.EffectsBrowser.EFFECTS`) or Transitions (`cp.apple.finalcutpro.main.EffectsBrowser.TRANSITIONS`).
---
--- Returns:
--- * A new `EffectsBrowser` object.
function EffectsBrowser:initialize(parent, type)
self._type = type
local UI = parent.mainUI:mutate(function(original)
if self:isShowing() then
return axutils.cache(self, "_ui", function()
return axutils.childMatching(original(), EffectsBrowser.matches)
end,
EffectsBrowser.matches)
end
end)
Group.initialize(self, parent, UI)
end
--- cp.apple.finalcutpro.main.EffectsBrowser:type() -> App
--- Method
--- Type of Effects Browser.
---
--- Parameters:
--- * None
---
--- Returns:
--- * App
function EffectsBrowser:type()
return self._type
end
-----------------------------------------------------------------------
--
-- BROWSER UI:
--
-----------------------------------------------------------------------
--- cp.apple.finalcutpro.main.EffectsBrowser.isShowing <cp.prop: boolean>
--- Variable
--- Is the Effects Browser showing?
function EffectsBrowser.lazy.prop:isShowing()
return self.toggleButton.checked
end
--- cp.apple.finalcutpro.main.EffectsBrowser.toggleButton <cp.ui.RadioButton>
--- Field
--- The Effects Browser Toggle Button.
function EffectsBrowser.lazy.value:toggleButton()
local toolbar = self:app().timeline.toolbar
local type = self:type()
if type == EffectsBrowser.EFFECTS then
return toolbar.browser.effects
elseif type == EffectsBrowser.TRANSITIONS then
return toolbar.browser.transitions
end
end
--- cp.apple.finalcutpro.main.EffectsBrowser:show() -> EffectsBrowser
--- Method
--- Show the Effects Browser.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:show()
self:app().timeline:show()
self.toggleButton:checked(true)
just.doUntil(function() return self:isShowing() end)
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:doShow() -> cp.rx.go.Statement
--- Method
--- Returns a `Statement` that will show the Effects Browser.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`.
function EffectsBrowser.lazy.method:doShow()
local button = self.toggleButton
return Given(self:app().timeline.doShow())
:Then(button:doCheck())
:Then(WaitUntil(button.isShowing))
end
--- cp.apple.finalcutpro.main.EffectsBrowser:hide() -> EffectsBrowser
--- Method
--- Hide the Effects Browser.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:hide()
if self:app().timeline:isShowing() then
self.toggleButton:checked(false)
just.doWhile(function() return self:isShowing() end)
end
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:doShow() -> cp.rx.go.Statement
--- Method
--- Returns a `Statement` that will show the Effects Browser.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`.
function EffectsBrowser.lazy.method:doHide()
local button = self.toggleButton
local app = self:app()
return If(app.timeline.isShowing)
:Then(button:doCheck())
:Then(WaitUntil(button.isShowing):Is(false))
end
-----------------------------------------------------------------------------
--
-- ACTIONS:
--
-----------------------------------------------------------------------------
--- cp.apple.finalcutpro.main.EffectsBrowser:showSidebar() -> EffectsBrowser
--- Method
--- Show Sidebar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:showSidebar()
if not self.sidebar:isShowing() then
self.sidebarToggle:toggle()
end
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:doShowSidebar() -> cp.rx.go.Statement
--- Method
--- Returns a `Statement` that will show the Sidebar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`.
function EffectsBrowser.lazy.method:doShowSidebar()
return If(self.sidebar.isShowing):Is(false):Then(self.sidebarToggle:doCheck())
end
--- cp.apple.finalcutpro.main.EffectsBrowser:hideSidebar() -> EffectsBrowser
--- Method
--- Hide Sidebar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:hideSidebar()
if self.sidebar:isShowing() then
self.sidebarToggle:toggle()
end
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:doHideSidebar() -> cp.rx.go.Statement
--- Method
--- Returns a `Statement` that will hide the Sidebar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`.
function EffectsBrowser.lazy.method:doHideSidebar()
return If(self.sidebar.isShowing):Is(false):Then(self.sidebarToggle:doUncheck())
end
--- cp.apple.finalcutpro.main.EffectsBrowser:toggleSidebar() -> EffectsBrowser
--- Method
--- Toggle Sidebar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:toggleSidebar()
self.sidebarToggle:toggle()
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:doToggleSidebar() -> cp.rx.go.Statement
--- Method
--- A `Statement` to toggle the Sidebar.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement` object.
function EffectsBrowser.lazy.method:doToggleSidebar()
return self.sidebarToggle:doToggle()
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showInstalledEffects() -> EffectsBrowser
--- Method
--- Show Installed Effects.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:showInstalledEffects()
self.group:selectItem(1)
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showInstalledTransitions() -> EffectsBrowser
--- Method
--- Show Installed Transitions.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:showInstalledTransitions()
self:showInstalledEffects()
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showAllEffects() -> EffectsBrowser
--- Method
--- Show All Effects.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:showAllEffects()
self:showSidebar()
self.sidebar:selectRowAt(1)
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showAllTransitions() -> EffectsBrowser
--- Method
--- Show All Transitions.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:showAllTransitions()
return self:showAllEffects()
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showTransitionsCategory(name) -> EffectsBrowser
--- Method
--- Ensures the sidebar is showing and that the selected 'Transitions' category is selected, if available.
---
--- Parameters:
--- * name - The category name, in the current language.
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:showTransitionsCategory(name)
self:showSidebar()
Table.selectRow(self.sidebar:rowsUI(), {name})
return self
end
-- cp.apple.finalcutpro.main.EffectsBrowser:_allRowsUI() -> axuielementObject
-- Method
-- Find the two 'All' rows (Video/Audio).
--
-- Parameters:
-- * None
--
-- Returns:
-- * `axuielementObject` object.
function EffectsBrowser:_allRowsUI()
local all = self:app():string("FFEffectsAll")
--------------------------------------------------------------------------------
-- Find the two 'All' rows (Video/Audio)
--------------------------------------------------------------------------------
return self.sidebar:rowsUI(function(row)
local label = row[1][1]
local value = label and label:attributeValue("AXValue")
return value == all
end)
end
--- cp.apple.finalcutpro.main.EffectsBrowser:videoCategoryRowsUI() -> axuielementObject
--- Method
--- Gets the Video Category Rows UI.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `axuielementObject` object.
function EffectsBrowser:videoCategoryRowsUI()
local video = self:app():string("FFVideo"):upper()
local audio = self:app():string("FFAudio"):upper()
return self:_startEndRowsUI(video, audio)
end
--- cp.apple.finalcutpro.main.EffectsBrowser:audioCategoryRowsUI() -> axuielementObject
--- Method
--- Gets the Audio Category Rows UI.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `axuielementObject` object.
function EffectsBrowser:audioCategoryRowsUI()
local audio = self:app():string("FFAudio"):upper()
return self:_startEndRowsUI(audio, nil)
end
-- cp.apple.finalcutpro.main.EffectsBrowser:_startEndRowsUI(startLabel, endLabel) -> axuielementObject
-- Method
-- Find the two 'All' rows (Video/Audio).
--
-- Parameters:
-- * startLabel - Start label as string.
-- * endLabel - End label as string.
--
-- Returns:
-- * `axuielementObject` object.
function EffectsBrowser:_startEndRowsUI(startLabel, endLabel)
local started, ended = false, false
--------------------------------------------------------------------------------
-- Find the two 'All' rows (Video/Audio)
--------------------------------------------------------------------------------
return self.sidebar:rowsUI(function(row)
local label = row[1][1]
local value = label and label:attributeValue("AXValue")
--log.df("checking row value: %s", value)
local isStartLabel = value == startLabel
if not started and isStartLabel then
started = true
end
if started and value == endLabel then
ended = true
end
return started and not isStartLabel and not ended
end)
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showAllVideoEffects() -> boolean
--- Method
--- Show All Video Effects.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `true` if successful otherwise `false`.
function EffectsBrowser:showAllVideoEffects()
local allRows = self:_allRowsUI()
if allRows and #allRows == 3 then
--------------------------------------------------------------------------------
-- Click 'All Video':
--------------------------------------------------------------------------------
self.sidebar:selectRow(allRows[2])
return true
elseif allRows and #allRows == 2 then
--------------------------------------------------------------------------------
-- Click 'All Video':
--------------------------------------------------------------------------------
self.sidebar:selectRow(allRows[1])
return true
end
return false
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showVideoCategory(name) -> EffectsBrowser
--- Method
--- Ensures the sidebar is showing and that the selected 'Video' category is selected, if available.
---
--- Parameters:
--- * name - The category name, in the current language.
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:showVideoCategory(name)
self:showSidebar()
Table.selectRow(self:videoCategoryRowsUI(), {name})
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showAllAudioEffects() -> boolean
--- Method
--- Show All Audio Effects.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `true` if successful otherwise `false`.
function EffectsBrowser:showAllAudioEffects()
local allRows = self:_allRowsUI()
if allRows and #allRows == 3 then
--------------------------------------------------------------------------------
-- Click 'All Audio':
--------------------------------------------------------------------------------
self.sidebar:selectRow(allRows[3])
return true
elseif allRows and #allRows == 2 then
--------------------------------------------------------------------------------
-- Click 'All Audio':
--------------------------------------------------------------------------------
self.sidebar:selectRow(allRows[2])
return true
end
return false
end
--- cp.apple.finalcutpro.main.EffectsBrowser:showAudioCategory(name) -> self
--- Method
--- Ensures the sidebar is showing and that the selected 'Audio' category is selected, if available.
---
--- Parameters:
--- * `name` - The category name, in the current language.
---
--- Returns:
--- * The browser.
function EffectsBrowser:showAudioCategory(name)
self:showSidebar()
Table.selectRow(self:audioCategoryRowsUI(), {name})
return self
end
function EffectsBrowser:doShowAudioCategory(name)
return Do(self:doShowSidebar())
:Then(function()
Table.selectRow(self:audioCategoryRowsUI(), {name})
end)
:Label("cp.apple.finalcutpro.main.EffectsBrowser:doShowAudioCategory(name)")
end
--- cp.apple.finalcutpro.main.EffectsBrowser:currentItemsUI() -> axuielementObject
--- Method
--- Gets the current items UI.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `axuielementObject` object.
function EffectsBrowser:currentItemsUI()
return self.contents:childrenUI()
end
--- cp.apple.finalcutpro.main.EffectsBrowser:selectedItemsUI() -> axuielementObject
--- Method
--- Gets the selected items UI.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `axuielementObject` object.
function EffectsBrowser.lazy.prop:selectedItemsUI()
return self.contents.selectedChildrenUI
end
--- cp.apple.finalcutpro.main.EffectsBrowser:itemIsSelected(itemUI) -> boolean
--- Method
--- Checks to see if an item is selected.
---
--- Parameters:
--- * itemUI - A `axuielementObject` to check.
---
--- Returns:
--- * `true` if the item is selected, otherwise `false`.
function EffectsBrowser:itemIsSelected(itemUI)
local selectedItems = self:selectedItemsUI()
if selectedItems and #selectedItems > 0 then
for _,selected in ipairs(selectedItems) do
if selected == itemUI then
return true
end
end
end
return false
end
--- cp.apple.finalcutpro.main.EffectsBrowser:applyItem(itemUI) -> EffectsBrowser
--- Method
--- Applies an item by double clicking on it.
---
--- Parameters:
--- * itemUI - The `axuielementObject` of the item you want to apply.
---
--- Returns:
--- * The `EffectsBrowser` object.
function EffectsBrowser:applyItem(itemUI)
if itemUI then
self.contents:showChild(itemUI)
local uiFrame = itemUI:attributeValue("AXFrame")
if uiFrame then
local rect = geometry.rect(uiFrame)
local targetPoint = rect and rect.center
if targetPoint then
ninjaDoubleClick(targetPoint)
end
end
end
return self
end
--- cp.apple.finalcutpro.main.EffectsBrowser:getCurrentTitles() -> table
--- Method
--- Returns the list of titles for all effects/transitions currently visible.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table
function EffectsBrowser:getCurrentTitles()
local contents = self.contents:childrenUI()
if contents ~= nil then
return fnutils.map(contents, function(child)
return child:attributeValue("AXTitle")
end)
end
return nil
end
-----------------------------------------------------------------------------
--
-- UI SECTIONS:
--
-----------------------------------------------------------------------------
--- cp.apple.finalcutpro.main.EffectsBrowser:mainGroupUI() -> <cp.prop: hs.axuielement; read-only>
--- Field
--- Main Group UI.
function EffectsBrowser.lazy.prop:mainGroupUI()
return self.UI:mutate(function(original)
return axutils.cache(self, "_mainGroup",
function()
local ui = original()
return ui and axutils.childWithRole(ui, "AXSplitGroup")
end)
end)
end
--- cp.apple.finalcutpro.main.EffectsBrowser.sidebar <cp.ui.Table>
--- Field
--- The sidebar `Table` object.
function EffectsBrowser.lazy.value:sidebar()
return Table(self, function()
return axutils.childFromLeft(self:mainGroupUI(), 1, ScrollArea.matches)
end)
end
--- cp.apple.finalcutpro.main.EffectsBrowser.contents <cp.ui.ScrollArea>
--- Field
--- The Effects Browser Contents.
function EffectsBrowser.lazy.value:contents()
return ScrollArea(self, function()
return axutils.childFromRight(self:mainGroupUI(), 1, function(element)
return element:attributeValue("AXRole") == "AXScrollArea"
end)
end)
end
--- cp.apple.finalcutpro.main.EffectsBrowser.sidebarToggle <cp.ui.CheckBox>
--- Field
--- The Sidebar Toggle.
function EffectsBrowser.lazy.value:sidebarToggle()
return CheckBox(self, function()
return axutils.childWithRole(self:UI(), "AXCheckBox")
end)
end
--- cp.apple.finalcutpro.main.EffectsBrowser.group <cp.ui.PopUpButton>
--- Field
--- The group `PopUpButton`.
function EffectsBrowser.lazy.value:group()
return PopUpButton(self, function()
return axutils.childWithRole(self:mainGroupUI(), "AXPopUpButton")
end)
end
--- cp.apple.finalcutpro.main.EffectsBrowser.search <cp.ui.PopUpButton>
--- Field
--- The Search `PopUpButton` object.
function EffectsBrowser.lazy.value:search()
return TextField(self, function()
return axutils.childWithRole(self:UI(), "AXTextField")
end)
end
--- cp.apple.finalcutpro.main.EffectsBrowser:saveLayout() -> table
--- Method
--- Saves the current Effects Browser layout to a table.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table containing the current Effects Browser Layout.
function EffectsBrowser:saveLayout()
local layout = {}
if self:isShowing() then
layout.showing = true
layout.sidebarToggle = self.sidebarToggle:saveLayout()
--------------------------------------------------------------------------------
-- Reveal the sidebar temporarily so we can save it:
--------------------------------------------------------------------------------
self:showSidebar()
layout.sidebar = self.sidebar:saveLayout()
self.sidebarToggle:loadLayout(layout.sidebarToggle)
layout.contents = self.contents:saveLayout()
layout.group = self.group:saveLayout()
layout.search = self.search:saveLayout()
end
return layout
end
--- cp.apple.finalcutpro.main.EffectsBrowser:loadLayout(layout) -> none
--- Method
--- Loads a Effects Browser layout.
---
--- Parameters:
--- * layout - A table containing the Effects Browser layout settings - created using `cp.apple.finalcutpro.main.Browser:saveLayout()`.
---
--- Returns:
--- * None
function EffectsBrowser:loadLayout(layout)
if layout and layout.showing then
self:show()
self:showSidebar()
self.sidebar:loadLayout(layout.sidebar)
self.sidebarToggle:loadLayout(layout.sidebarToggle)
self.group:loadLayout(layout.group)
self.search:loadLayout(layout.search)
self.contents:loadLayout(layout.contents)
else
self:hide()
end
end
return EffectsBrowser
|
require 'nn'
require 'nngraph'
require 'optim'
require 'cutorch'
require 'cunn'
require 'image'
require 'cudnn'
cmd = torch.CmdLine()
cmd:text()
cmd:text('Options:')
cmd:option('--imageDir', '/home/jchen16/NEW/data/X10/train/', 'the directory to load')
cmd:option('--labelDir', '/home/jchen16/NEW/data/X10/label/', 'the directory to load')
cmd:option('--ext','.png','only load a specific type of images')
cmd:option('--epoch',100,'the number of iterations trained on the whole dataset')
cmd:option('--learningRate',0.005,'initial learning rate')
cmd:option('--minLR',0.0001,'minimal learning rate')
cmd:option('--dropoutProb', 0.25, 'probability of zeroing a neuron (dropout probability)')
cmd:option('--uniform', 0.05, 'initialize parameters using uniform distribution between -uniform and uniform.')
cmd:option('--CheckPointDir', '/home/jchen16/NEW/code/checkpoint','directory to save network files')
cmd:option('--checkpoint',5,'save checkpoints')
cmd:option('--momentum',0.69,'initial momentum for training')
cmd:option('--clip',5,'max allowed norm ')
cmd:option('--XX',10,'the key parameter to determine the size of image, max is 54')
cmd:option('--RAM',false,'false means load all images to RAM')
cmd:option('--gpu',1,'gpu device to use')
cmd:option('--imageType',1,'1: grayscale, 3: RGB')
cmd:text()
opt = cmd:parse(arg or {})
-- set up gpu
cutorch.setDevice(opt.gpu)
cudnn.benchmark = true
cudnn.fastest = true
--cudnn.verbose = true
XX=opt.XX
-- 1. Get the list of files in the given directory
files = {}
for file in paths.files(opt.imageDir) do
if file:find(opt.ext .. '$') then
table.insert(files, paths.concat(opt.imageDir,file))
end
end
if #files == 0 then
error('given directory doesnt contain any files of type: ' .. opt.ext)
end
table.sort(files, function (a,b) return a < b end)
files_lab ={}
for file in paths.files(opt.labelDir) do
if file:find(opt.ext .. '$') then
table.insert(files_lab, paths.concat(opt.labelDir,file))
end
end
if #files_lab == 0 then
error('given directory doesnt contain any files of type: ' .. opt.ext)
end
table.sort(files_lab, function (a,b) return a < b end)
if not opt.RAM then
-- 2. Load all the files into RAM
-- "images" is a table of tensors of size opt.imageType x W x H
images = {}
for i,file in ipairs(files) do
-- load each image
table.insert(images, image.load(file):float())
end
labels = {}
for i, file in ipairs(files_lab) do
table.insert(labels, image.load(file,1,'byte'))
end
end
-- random data for test
--[[
images={}
labels={}
files={'1','1','1','11','11'}
for kk=1,5 do
table.insert(images,torch.rand(1, 1, 16*XX+92,16*XX+92):float())
table.insert(labels,torch.ByteTensor(1, (16*XX-92),(16*XX-92)):random(1,2))
end
--]]
-- 3. Define the model
--[[
if(images[1]:size(3)~=(16*XX+92)) then
print('dimenstion mismatch')
return
end
--]]
input = nn.Identity()()
L1a=cudnn.SpatialConvolution(opt.imageType, 64, 3, 3, 1, 1, 0, 0)(input)
L1b=cudnn.ReLU(true)(L1a)
L1c=cudnn.SpatialConvolution(64, 64, 3, 3, 1, 1, 0, 0)(L1b)
if opt.dropoutProb>0 then
L1d=nn.SpatialDropout(opt.dropoutProb)(L1c)
L1=cudnn.ReLU(true)(L1d)
else
L1=cudnn.ReLU(true)(L1c)
end
L2a=cudnn.SpatialMaxPooling(2, 2, 2, 2)(L1)
L2b=cudnn.SpatialConvolution(64, 128, 3, 3, 1, 1, 0, 0)(L2a)
L2c=cudnn.ReLU()(L2b)
L2d=cudnn.SpatialConvolution(128, 128, 3, 3, 1, 1, 0, 0)(L2c)
if opt.dropoutProb>0 then
L2e=nn.SpatialDropout(opt.dropoutProb)(L2d)
L2=cudnn.ReLU(true)(L2e)
else
L2=cudnn.ReLU(true)(L2d)
end
L3a=cudnn.SpatialMaxPooling(2, 2, 2, 2)(L2)
L3b=cudnn.SpatialConvolution(128, 256, 3, 3, 1, 1, 0, 0)(L3a)
L3c=cudnn.ReLU(true)(L3b)
L3d=cudnn.SpatialConvolution(256, 256, 3, 3, 1, 1, 0, 0)(L3c)
if opt.dropoutProb>0 then
L3e=nn.SpatialDropout(opt.dropoutProb)(L3d)
L3=cudnn.ReLU(true)(L3e)
else
L3=cudnn.ReLU(true)(L3d)
end
L4a=cudnn.SpatialMaxPooling(2, 2, 2, 2)(L3)
L4b=cudnn.SpatialConvolution(256, 512, 3, 3, 1, 1, 0, 0)(L4a)
L4c=cudnn.ReLU(true)(L4b)
L4d=cudnn.SpatialConvolution(512, 512, 3, 3, 1, 1, 0, 0)(L4c)
if opt.dropoutProb>0 then
L4e=nn.SpatialDropout(opt.dropoutProb)(L4d)
L4=cudnn.ReLU(true)(L4e)
else
L4=cudnn.ReLU(true)(L4d)
end
L5a=cudnn.SpatialMaxPooling(2, 2, 2, 2)(L4)
L5b=cudnn.SpatialConvolution(512, 1024, 3, 3, 1, 1, 0, 0)(L5a)
L5c=cudnn.ReLU(true)(L5b)
L5d=cudnn.SpatialConvolution(1024, 1024, 3, 3, 1, 1, 0, 0)(L5c)
if opt.dropoutProb>0 then
L5e=nn.SpatialDropout(opt.dropoutProb)(L5d)
L5=cudnn.ReLU(true)(L5e)
else
L5=cudnn.ReLU(true)(L5d)
end
Crop4=nn.Narrow(3,4,2*XX-4)(L4)
L4cp=nn.Narrow(4,4,2*XX-4)(Crop4)
L5up=nn.SpatialFullConvolution(1024, 512, 2, 2, 2, 2)(L5)
L6a=nn.JoinTable(1,3)({L5up,L4cp})
L6b=cudnn.SpatialConvolution(1024,512, 3, 3, 1, 1, 0, 0)(L6a)
L6c=cudnn.ReLU(true)(L6b)
L6d=cudnn.SpatialConvolution(512,512, 3, 3, 1, 1, 0, 0)(L6c)
if opt.dropoutProb>0 then
L6e=nn.SpatialDropout(opt.dropoutProb)(L6d)
L6=cudnn.ReLU(true)(L6e)
else
L6=cudnn.ReLU(true)(L6d)
end
Crop3=nn.Narrow(3,16,4*XX-16)(L3)
L3cp=nn.Narrow(4,16,4*XX-16)(Crop3)
L6up=nn.SpatialFullConvolution(512, 256, 2, 2, 2, 2)(L6)
L7a=nn.JoinTable(1,3)({L6up,L3cp})
L7b=cudnn.SpatialConvolution(512,256, 3, 3, 1, 1, 0, 0)(L7a)
L7c=cudnn.ReLU(true)(L7b)
L7d=cudnn.SpatialConvolution(256,256, 3, 3, 1, 1, 0, 0)(L7c)
if opt.dropoutProb>0 then
L7e=nn.SpatialDropout(opt.dropoutProb)(L7d)
L7=cudnn.ReLU(true)(L7e)
else
L7=cudnn.ReLU(true)(L7d)
end
Crop2=nn.Narrow(3,40,8*XX-40)(L2)
L2cp=nn.Narrow(4,40,8*XX-40)(Crop2)
L7up=nn.SpatialFullConvolution(256, 128, 2, 2, 2, 2)(L7)
L8a=nn.JoinTable(1,3)({L7up,L2cp})
L8b=cudnn.SpatialConvolution(256,128, 3, 3, 1, 1, 0, 0)(L8a)
L8c=cudnn.ReLU(true)(L8b)
L8d=cudnn.SpatialConvolution(128,128, 3, 3, 1, 1, 0, 0)(L8c)
if opt.dropoutProb>0 then
L8e=nn.SpatialDropout(opt.dropoutProb)(L8d)
L8=cudnn.ReLU(true)(L8e)
else
L8=cudnn.ReLU(true)(L8d)
end
Crop1=nn.Narrow(3,88,16*XX-88)(L1)
L1cp=nn.Narrow(4,88,16*XX-88)(Crop1)
L8up=nn.SpatialFullConvolution(128, 64, 2, 2, 2, 2)(L8)
L9a=nn.JoinTable(1,3)({L8up,L1cp})
L9b=cudnn.SpatialConvolution(128,64, 3, 3, 1, 1, 0, 0)(L9a)
L9c=cudnn.ReLU(true)(L9b)
L9d=cudnn.SpatialConvolution(64,64, 3, 3, 1, 1, 0, 0)(L9c)
if opt.dropoutProb>0 then
L9e=nn.SpatialDropout(opt.dropoutProb)(L9d)
L9=cudnn.ReLU(true)(L9e)
else
L9=cudnn.ReLU(true)(L9d)
end
L10=cudnn.SpatialConvolution(64, 2, 1, 1, 1, 1, 0, 0)(L9)
--L10a=nn.SpatialConvolution(64, 2, 1, 1, 1, 1, 0, 0)(L9)
--L10b=nn.Transpose({1,2},{2,3})(L10a)
--L10=nn.Reshape((16*XX-92)*(16*XX-92),2)(L10b)
unet = nn.gModule({input},{L10}):cuda()
--cudnn.convert(unet,cudnn):cuda()
local finput, fgradInput
unet:apply(function(m) if torch.type(m) == 'nn.SpatialConvolution' or torch.type(m) == 'nn.SpatialFullConvolution' then
finput = finput or m.finput
fgradInput = fgradInput or m.fgradInput
m.finput = finput
m.fgradInput = fgradInput
end
end)
--criterion = nn.CrossEntropyCriterion():cuda()
criterion = cudnn.SpatialCrossEntropyCriterion():cuda()
collectgarbage()
-- Training
if opt.uniform > 0 then
for k,param in ipairs(unet:parameters()) do
param:uniform(-opt.uniform, opt.uniform)
end
end
parameters,gradParameters = unet:getParameters()
config = {learningRate=opt.learningRate,
momentum=opt.momentum}
--config={learningRate=opt.learningRate, alpha=0.95}
function train()
unet:training()
epoch = epoch or 1
if epoch%opt.checkpoint==0 then
if config.learningRate > opt.minLR then
config.learningRate = config.learningRate * 0.5
end
if config.momentum < 0.9 then
config.momentum = config.momentum + 0.1
end
end
image_index = torch.randperm(#files):long()
for i =1,#files do
local feval = function (x)
if x ~= parameters then parameters:copy(x) end
gradParameters:zero()
local idx = image_index[i]
local input_image, label_image
if not opt.RAM then
input_image = torch.Tensor(1, opt.imageType ,images[idx]:size(2), images[idx]:size(3))
input_image[1] = images[idx]
input_image = input_image:cuda()
label_image = torch.Tensor(1,labels[idx]:size(2), images[idx]:size(3))
lable_image[1] = labels[idx]
label_image = label_image:cuda()
else
local img = image.load(files[idx]:float()
local lab = image.load(files_lab[idx],1,'byte'))
input_image = torch.Tensor(1,img:size(2),img:size(3))
input_image[1] = img:copy()
input_image = input_image:cuda()
label_image = torch.Tensor(1,lab:size(2),lab:size(3))
lable_image[1] = lab:copy()
lable_image = label_image:cuda()
end
--[[
local input_image={}
local label_image={}
if not opt.RAM then
table.insert(input_image,images[idx]:cuda())
table.insert(label_image,labels[idx]:cuda())
else
table.insert(input_image, image.load(files[idx]):float():cuda())
table.insert(label_image, image.load(files_lab[idx],1,'byte'):cuda())
end
--]]
local output_image = unet:forward(input_image)
local err = criterion:forward(output_image, label_image)
local grad_df = criterion:backward(output_image, label_image)
print('Epoch '..epoch..' ('..i..'): Err='..err)
unet:backward(input_image,grad_df)
if opt.clip>0 then
gradParameters:clamp(-opt.clip, opt.clip)
end
return err, gradParameters
end
--optim.rmsprop(feval, parameters, config)
optim.sgd(feval, parameters, config)
-- clean
collectgarbage()
end
if opt.checkpoint>0 and epoch%opt.checkpoint ==0 then
filename=string.format('%s/net_%f.bin',opt.CheckPointDir,epoch);
torch.save(filename,unet);
end
epoch = epoch + 1
end
for iter=1, opt.epoch do
train()
end
-- Traininig by Manual Loop
--[[
lr = opt.learningRate
for k=1, opt.epoch do
image_index = torch.randperm(#images):long()
for i =1, #images do
local idx = image_index[i]
input_image=images[idx]:cuda()
label_image=labels[idx]:cuda()
output_image = unet:forward(input_image)
local err = criterion:forward(output_image, label_image)
local gradCriterion = criterion:backward(output_image, label_image)
unet:zeroGradParameters()
unet:backward(input_image,gradCriterion)
unet:updateParameters(lr)
print(label_image:float())
print('Iter: '..k..' ('..i..'), Loss= '..err)
if i%5==0 then
collectgarbage()
end
end
if (k % opt.checkpoint ==0) then
filename=string.format('%s/net_%f.bin',opt.CheckPointDir,k);
torch.save(filename,unet);
end
end
--]]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.