content stringlengths 5 1.05M |
|---|
vim.opt_local.isfname:append('@-@')
|
local Promise = require(script.Parent.Parent.Parent.Promise)
local SinglePromiseEvent = {}
SinglePromiseEvent.__index = SinglePromiseEvent
function SinglePromiseEvent.new(executor)
local self = setmetatable({
_listener = nil,
}, SinglePromiseEvent)
local function fire()
if self._listener then
coroutine.wrap(self._listener)()
end
end
self._promise = Promise.defer(function(resolve)
resolve(Promise.new(executor(fire)):andThen(function()
self._listener = nil
end))
end)
return self
end
function SinglePromiseEvent:Connect(callback)
assert(self._listener == nil, "SinglePromiseEvent is already used up")
assert(self._promise:getStatus() == "Started", "SinglePromiseEvent is already used up")
self._listener = callback
return {
Disconnect = function()
self._promise:cancel()
self._listener = nil
end
}
end
return SinglePromiseEvent |
-- Phoenix Project © 2016
SWEP.VElements = {
["mag"] = { type = "Model", model = "models/arxweapon/ventil_magazin.mdl", bone = "a_mag", rel = "", pos = Vector(-2.597, 2, 4), angle = Angle(0, 0, -94.676), size = Vector(1.1, 1.404, 1.1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["ventil"] = { type = "Model", model = "models/arxweapon/ventil_pustishka.mdl", bone = "a_fg42", rel = "", pos = Vector(-4.676, 1.7, 0.518), angle = Angle(0, 0, -90), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {[1] = 1} }
}
SWEP.WElements = {
["ventil"] = { type = "Model", model = "models/arxweapon/ventil_pustishka.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(5.599, 0.518, -1.8), angle = Angle(-174.157, 180, 0), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.Gun = ("m9k_mrp_ventil") -- must be the name of your swep but NO CAPITALS!
SWEP.Category = "Metro 2033 RP"
SWEP.Author = "Darsenvall"
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.Instructions = ""
SWEP.MuzzleAttachment = "1" -- Should be "1" for CSS models or "muzzle" for hl2 models
SWEP.PrintName = "Valve" -- Weapon name (Shown on HUD)
SWEP.Slot = 2 -- Slot in the weapon selection menu
SWEP.SlotPos = 28 -- Position in the slot
SWEP.DrawAmmo = true -- Should draw the default HL2 ammo counter
SWEP.DrawWeaponInfoBox = false -- Should draw the weapon info box
SWEP.BounceWeaponIcon = false -- Should the weapon icon bounce?
SWEP.DrawCrosshair = true -- Set false if you want no crosshair from hip
SWEP.Weight = 30 -- Rank relative ot other weapons. bigger is better
SWEP.AutoSwitchTo = true -- Auto switch to if we pick it up
SWEP.AutoSwitchFrom = true -- Auto switch from if you pick up a better weapon
SWEP.XHair = true -- Used for returning crosshair after scope. Must be the same as DrawCrosshair
SWEP.BoltAction = false -- Is this a bolt action rifle?
SWEP.HoldType = "ar2" -- how others view you carrying the weapon
-- normal melee melee2 fist knife smg ar2 pistol rpg physgun grenade shotgun crossbow slam passive
-- you're mostly going to use ar2, smg, shotgun or pistol. rpg and crossbow make for good sniper rifles
SWEP.ViewModelFOV = 62
SWEP.ViewModelFlip = true
SWEP.ViewModel = "models/weapons/v_rif_fg42.mdl"
SWEP.WorldModel = "models/weapons/w_pistol.mdl"
SWEP.ShowWorldModel = false
SWEP.Base = "bobs_scoped_base"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.Primary.Sound = Sound("ventil/ventil_base_shot.mp3") -- script that calls the primary fire sound
SWEP.Primary.RPM = 15 -- This is in Rounds Per Minute
SWEP.Primary.ClipSize = 8 -- Size of a clip
SWEP.Primary.DefaultClip = 0 -- Bullets you start with
SWEP.Primary.KickUp = 1 -- Maximum up recoil (rise)
SWEP.Primary.KickDown = .6 -- Maximum down recoil (skeet)
SWEP.Primary.KickHorizontal = .5 -- Maximum up recoil (stock)
SWEP.Primary.Automatic = false -- Automatic/Semi Auto
SWEP.Primary.Ammo = "SniperPenetratedRound" -- pistol, 357, smg1, ar2, buckshot, slam, SniperPenetratedRound, AirboatGun
-- Pistol, buckshot, and slam always ricochet. Use AirboatGun for a light metal peircing shotgun pellets
SWEP.Secondary.ScopeZoom = 3
SWEP.Secondary.UseACOG = false -- Choose one scope type
SWEP.Secondary.UseMilDot = false -- I mean it, only one
SWEP.Secondary.UseSVD = true -- If you choose more than one, your scope will not show up at all
SWEP.Secondary.UseParabolic = false
SWEP.Secondary.UseElcan = false
SWEP.Secondary.UseGreenDuplex = false
SWEP.Secondary.UseAimpoint = false
SWEP.Secondary.UseMatador = false
SWEP.data = {}
SWEP.data.ironsights = 1
SWEP.ScopeScale = 0.7
SWEP.ReticleScale = 0.6
SWEP.Primary.NumShots = 1 --how many bullets to shoot, use with shotguns
SWEP.Primary.Damage = 45 --base damage, scaled by game
SWEP.Primary.Spread = .09 --define from-the-hip accuracy 1 is terrible, .0001 is exact)
SWEP.Primary.IronAccuracy = .0012 -- has to be the same as primary.spread
-- enter iron sight info and bone mod info below
SWEP.IronSightsPos = Vector (2.275, -2.9708, 0.5303)
SWEP.IronSightsAng = Vector (0, 0, 0)
SWEP.SightsPos = Vector (2.275, -2.9708, 0.5303)
SWEP.SightsAng = Vector (0, 0, 0)
SWEP.RunSightsPos = Vector(-3.04, 0, 0.36)
SWEP.RunSightsAng = Vector(-4.926, -35.176, 0)
SWEP.ViewModelBoneMods = {
["R_Forearm"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0.5), angle = Angle(0, 0, 0) },
["a_trigger"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(-17.963, -23.519, -23.149), angle = Angle(0, 0, 0) },
["a_fg42"] = { scale = Vector(0.148, 0.148, 0.148), pos = Vector(1, 0, 0.5), angle = Angle(0, 0, 0) },
["a_bolt"] = { scale = Vector(0.203, 0.203, 0.203), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["a_mag"] = { scale = Vector(0.148, 0.148, 0.148), pos = Vector(0.925, 0, 0.5), angle = Angle(0, 0, 0) }
} |
TTS.Admin.commands.Register( 'gag' )
:SetDescription('Gag')
:SetRequiredAttrs({ 'player', 'length', 'idrule' })
:SetOptionalAttrs({ 'reason' })
:SetLogType('gag', ':user_id-0 выдал гаг :user_id-1 на :length :idrule (:reason)')
:SetPermissions({ 'ap-locks', 'gag' })
:SetSingleTarget( true )
:SetDeclinatio({
{
'%str',
' выдал гаг ',
'%str',
' на ',
'%length',
' ',
'%idrule',
' ',
'%reason'
},{
'%str',
' выдала гаг ',
'%str',
' на ',
'%length',
' ',
'%idrule',
' ',
'%reason'
}
})
:Execute(function(caller, target, length, idrule, reason)
-- print(target)
-- PrintTable(second_target)
-- print(caller, target, length, reason)
TTS.Admin.Methods.GiveLock('gag', caller, target, length, idrule, reason)
return true
end)
if true then return end
TTS.Admin.commands.Register( 'ungag' )
:SetDescription('Ungag')
:SetRequiredAttrs({ 'player' })
:SetOptionalAttrs({ 'reason' })
:SetLogType('ungag', ':user_id-0 cнял гаг с :user_id-1 (:reason)')
:SetPermissions({ 'ap-locks', 'gag' })
:SetSingleTarget( true )
:SetDeclinatio({
{
'%str',
' cнял гаг с ',
'%str',
'%reason'
},{
'%str',
' cняла гаг с ',
'%str',
'%reason'
}
})
:Execute(function(caller, target, length, reason)
-- print(target)
-- PrintTable(second_target)
print(caller, target, length, reason)
end)
|
local LoadingView = {}
function LoadingView:Start()
local ref = self.gameObject:GetComponent(typeof(CS.SGK.UIReference));
self.progressBar = ref:Get("progress", typeof(CS.UnityEngine.UI.Slider));
self.messageLabel = ref:Get("message", typeof(CS.UnityEngine.UI.Text));
self.loading = ref:Get("LoadingView");
self.DlgErrornum = 0
self.ErrorView = nil
self.Itemnum = 0
self.ItemView = nil
self.showDlgMsgTab = {}
self.showDlgMsgList = {}--提示框
self.showDlgMsgView = nil
self.capacityChangeView = nil
local BG = ref:Get("BG", typeof(SGK.LuaBehaviour));
if BG then
BG.enabled = true;
end
end
function LoadingView:Update()
if self.showDlgMsgTab then
for k,v in pairs(self.showDlgMsgTab) do
if v and v.item and v.nextTime and v.cancelText then
if v.nextTime > module.Time.now() then
v.cancelText.text = v.desc.."("..math.ceil(v.nextTime - module.Time.now())..")"
else
if v.fun then
v.fun()
end
self:loadShowDlgMsg(v.item)
self.showDlgMsgTab[k] = nil
end
end
end
end
end
function LoadingView:showDlgMsg(data)
local tempObj = SGK.ResourcesManager.Load("prefabs/base/ShowDlgFrame.prefab")
local obj = nil;
local NGUIRoot = UnityEngine.GameObject.FindWithTag("UITopRoot")
if NGUIRoot then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj, NGUIRoot.gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UGUIRootTop") then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UnityEngine.GameObject.FindWithTag("UGUIRootTop").gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UGUIRoot") then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UnityEngine.GameObject.FindWithTag("UGUIRoot").gameObject.transform)
else
obj = CS.UnityEngine.GameObject.Instantiate(tempObj)
end
local TipsView = CS.SGK.UIReference.Setup(obj)
self.showDlgMsgView = TipsView
TipsView.Dialog.Content.confirmBtn.gameObject:SetActive(data.confirm ~= nil)
TipsView.Dialog.Content.cancelBtn.gameObject:SetActive(data.cancel ~= nil)
if data.cancel == nil then
TipsView.Dialog.Content.confirmBtn.gameObject.transform.localPosition = Vector3(0,-90,0)
else
TipsView.Dialog.Content.confirmBtn.gameObject.transform.localPosition = Vector3(178,-90,0)
end
TipsView.Dialog.Content.confirmBtn[CS.UGUIClickEventListener].onClick = (function ()
data.confirm()
if data.time then
self.showDlgMsgTab[TipsView] = nil
end
self:loadShowDlgMsg(TipsView)
end)
TipsView.Dialog.Content.cancelBtn[CS.UGUIClickEventListener].onClick = (function ()
data.cancel()
if data.time then
self.showDlgMsgTab[TipsView] = nil
end
self:loadShowDlgMsg(TipsView)
end)
TipsView.Dialog.Close[CS.UGUIClickEventListener].onClick = (function ()
-- if data.cancel then
-- data.cancel()
-- elseif data.confirm then
-- data.confirm()
-- end
if not data.NotExit then
if data.time then
self.showDlgMsgTab[TipsView] = nil
end
self:loadShowDlgMsg(TipsView)
end
end)
TipsView.mask[CS.UGUIClickEventListener].onClick = (function ()
if not data.NotExit then
if data.time then
self.showDlgMsgTab[TipsView] = nil
end
self:loadShowDlgMsg(TipsView)
end
end)
if data.desc then
TipsView.Dialog.Content.desc[UI.Text].text = data.desc
TipsView.Dialog.Content.desc.gameObject:SetActive(true)
end
TipsView.Dialog.Content.describe[UI.Text].alignment = data.alignment ~= nil and data.alignment or UnityEngine.TextAnchor.MiddleCenter
TipsView.Dialog.Content.confirmBtn.confirmBtnLab[UnityEngine.UI.Text].text = data.txtConfirm ~= nil and data.txtConfirm or "确定"
TipsView.Dialog.Content.cancelBtn.cancelBtnLab[UnityEngine.UI.Text].text = data.txtCancel ~= nil and data.txtCancel or "取消"
TipsView.Dialog.Content.describe[UnityEngine.UI.Text].text = data.msg ~= nil and data.msg or ""
TipsView.Dialog.Title[UI.Text].text = data.title ~= nil and utils.SGKTools.get_title_frame(data.title) or utils.SGKTools.get_title_frame("提示")
if data.confirmInfo then
TipsView.Dialog.Content.confirmInfo:SetActive(true)
TipsView.Dialog.Content.confirmInfo[UI.Text].text = data.confirmInfo
end
if data.time and data.time > 0 then
self.showDlgMsgTab[TipsView] = {
item = TipsView,
nextTime = module.Time.now() + data.time,
cancelText = TipsView.Dialog.Content.cancelBtn.cancelBtnLab[UnityEngine.UI.Text],
fun = data.cancel,
desc = TipsView.Dialog.Content.cancelBtn.cancelBtnLab[UnityEngine.UI.Text].text
}
if not data.cancel then
self.showDlgMsgTab[TipsView].cancelText = TipsView.Dialog.Content.confirmBtn.confirmBtnLab[UnityEngine.UI.Text]
self.showDlgMsgTab[TipsView].desc = TipsView.Dialog.Content.confirmBtn.confirmBtnLab[UnityEngine.UI.Text].text
self.showDlgMsgTab[TipsView].fun = data.confirm
end
end
return obj
end
function LoadingView:showDlgError(parent,msg,type)
parent = nil
if utils.SGKTools.GameObject_null(self.ErrorView) then
local tempObj = SGK.ResourcesManager.Load("prefabs/base/ErrorTipsFrame.prefab")
local obj = nil;
if utils.SGKTools.GameObject_null(parent) == false then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj, parent.gameObject.transform)
else
local NGUIRoot = UnityEngine.GameObject.FindWithTag("UITopRoot")
if NGUIRoot then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj, NGUIRoot.gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UGUIRootTop") then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UnityEngine.GameObject.FindWithTag("UGUIRootTop").gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UGUIRoot") then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UnityEngine.GameObject.FindWithTag("UGUIRoot").gameObject.transform)
else
obj = CS.UnityEngine.GameObject.Instantiate(tempObj)
end
end
self.ErrorView = CS.SGK.UIReference.Setup(obj)
end
self.DlgErrornum = self.DlgErrornum + 1
self.ErrorView.Group[1][CS.UGUISpriteSelector].index = type or 0
self.ErrorView.Group[1].desc[UnityEngine.UI.Text].text = msg
--print(self.ErrorView.Group[1].desc[UnityEngine.RectTransform].sizeDelta.y)
--self.ErrorView.Group[1][UnityEngine.RectTransform].sizeDelta = CS.UnityEngine.Vector2(685,30 + self.ErrorView.Group[1].desc[UnityEngine.RectTransform].sizeDelta.y)
local descObj = CS.UnityEngine.GameObject.Instantiate(self.ErrorView.Group[1].gameObject, self.ErrorView.Group.gameObject.transform)
local descView = CS.SGK.UIReference.Setup(descObj)
descView:SetActive(true)
descView[UnityEngine.CanvasGroup]:DOFade(0,1):OnComplete(function( ... )
CS.UnityEngine.GameObject.Destroy(descObj)
self.DlgErrornum = self.DlgErrornum -1
if self.DlgErrornum == 0 then
CS.UnityEngine.GameObject.Destroy(self.ErrorView.gameObject)
self.ErrorView = nil
end
end):SetDelay(2)
end
local curr_Id_List = {} --该次获得物品列表
local ItemViewStatus = nil
function LoadingView:CreateGetItemTips(id,count,Type,uuid,fun,flag)
-- ERROR_LOG("=====",self.ItemView,id,count,Type,uuid,fun,flag)
uuid = uuid ~=0 and uuid
fun = fun ~=0 and fun
if self.ItemView then
self:GetItemTips(id,count,Type,uuid,fun,flag)
return
end
assert(self.ItemView == nil);
curr_Id_List = {}
if self.item_tips_queue then
table.insert(self.item_tips_queue, {id,count,Type,uuid,fun});
return;
end
self.item_tips_queue = {};
table.insert(self.item_tips_queue, {id,count,Type,uuid,fun});
SGK.ResourcesManager.LoadAsync(self.gameObject:GetComponent(typeof(SGK.LuaBehaviour)), "prefabs/Tips/GetAndFinishTip.prefab", function(tempObj)
if not tempObj then
OperationQueueNext();
return;
end
local _item_tips_queue={}
for k,v in pairs(self.item_tips_queue) do
_item_tips_queue[k]=v
end
self.item_tips_queue = nil;
local obj = nil
if utils.SceneStack.CurrentSceneName() == 'battle' then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UnityEngine.GameObject.FindWithTag("UGUIRoot").gameObject.transform)
else
if UnityEngine.GameObject.FindWithTag("UITopRoot") then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UnityEngine.GameObject.FindWithTag("UITopRoot").gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UGUIRootTop") then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UnityEngine.GameObject.FindWithTag("UGUIRootTop").gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UGUIRoot") then
obj = CS.UnityEngine.GameObject.Instantiate(tempObj,UnityEngine.GameObject.FindWithTag("UGUIRoot").gameObject.transform)
else
obj = CS.UnityEngine.GameObject.Instantiate(tempObj)
end
end
self.ItemView = CS.SGK.UIReference.Setup(obj)
self.ItemView[SGK.LuaBehaviour]:Call("OnClearItemTip",function ()
if fun then
fun()
else
ERROR_LOG("fun is nil ")
end
self.ItemView = nil
OperationQueueNext();
end)
CS.UGUIClickEventListener.Get(self.ItemView.Btns.SetBtn.gameObject).onClick = function (obj)
if self.ItemView then
self.ItemView[SGK.LuaBehaviour]:Call("SetItemClick")
end
end
CS.UGUIClickEventListener.Get(self.ItemView.view.mask.gameObject).onClick = function (obj)
if self.ItemView then
self.ItemView[SGK.LuaBehaviour]:Call("GetItemClick")
end
end
--屏蔽 恭喜获得界面 5秒自动关闭
self.ItemView.tips:SetActive(false)
-- local delay = 6
-- for i=delay,1,-1 do
-- self.ItemView.transform:DOScale(Vector3.one, i):OnComplete(function()
-- self.ItemView.tips[UI.Text].text = string.format("%ss后关闭",delay-i)
-- end)
-- end
-- self.ItemView.transform:DOScale(Vector3.one,delay):OnComplete(function()
-- if not self.DontClose and self.ItemView then
-- self.ItemView[SGK.LuaBehaviour]:Call("DestroyGetAndFinishTipItem")
-- end
-- end)
self.ItemView.gameObject:SetActive(true)
self.UpdateReward=false
--self.DontClose=false
for _,v in pairs(_item_tips_queue) do
self:GetItemTips(v[1],v[2],v[3],v[4],v[5],v[6]);
end
ItemViewStatus = nil
end)
end
local LocalItemList = {}
function LoadingView:GetItemTips(id,count,Type,uuid,fun,flag)
-- ERROR_LOG(id,count,Type,uuid,fun,flag)
if self.ItemView == nil then
uuid = uuid or 0
fun = fun or 0
LocalItemList = LocalItemList or {}
table.insert(LocalItemList,{id,count,Type,uuid,fun,flag})
if ItemViewStatus == "loading" then
return
else
ItemViewStatus = "loading"
if LocalItemList[1] then
local _id,_count,_Type,_uuid,_fun,_flag = table.unpack(LocalItemList[1])
table.remove(LocalItemList,1)
return OperationQueuePush(LoadingView.CreateGetItemTips, self,_id,_count,_Type,_uuid,_fun,_flag)
end
end
else
if LocalItemList[1] then
local _id,_count,_Type,_uuid,_fun,_flag = table.unpack(LocalItemList[1])
table.remove(LocalItemList,1)
self:GetItemTips(_id,_count,_Type,_uuid,_fun,_flag)
end
end
if id ==11000 then--角色经验变化
self.ItemView.gameObject:SetActive(true)
self.ItemView[SGK.LuaBehaviour]:Call("ShowCharacterExpChange",{count,Type})
return
end
if not id and not count and not Type then--任务完成
if self.ItemView then
self.ItemView.gameObject:SetActive(true)
self.ItemView[SGK.LuaBehaviour]:Call("ShowFinishQuestTextImage",nil)
end
return
end
if not self.UpdateReward then
self.UpdateReward=true
--self.DontClose=true
self.ItemView[SGK.LuaBehaviour]:Call("ShowGetItemTextImage")
end
if Type==utils.ItemHelper.TYPE.HERO and count >=10 then
self.ItemView[SGK.LuaBehaviour]:Call("ShowHeroToFrameTip",nil)
Type=utils.ItemHelper.TYPE.ITEM
end
--特殊处理一次获得相同英雄
if Type==utils.ItemHelper.TYPE.HERO and curr_Id_List[id] then
id = id +10000
count = 10
self.ItemView[SGK.LuaBehaviour]:Call("ShowHeroToFrameTip",nil)
Type=utils.ItemHelper.TYPE.ITEM
end
curr_Id_List[id] = true
self.ItemView[SGK.LuaBehaviour]:Call("UpdateShowItem",Type,id,count,uuid)
end
function LoadingView:loadShowDlgMsg(view)
if view ~= nil then
CS.UnityEngine.GameObject.Destroy(view.gameObject)
self.showDlgMsgView = nil
end
if self.showDlgMsgView == nil and #self.showDlgMsgList > 0 then
self:showDlgMsg(self.showDlgMsgList[1])
table.remove(self.showDlgMsgList,1)
end
end
function LoadingView:OnClickIcon(item,tab)
local parent = nil
if UnityEngine.GameObject.FindWithTag("UITopRoot") then
parent=UnityEngine.GameObject.FindWithTag("UITopRoot").gameObject
elseif UnityEngine.GameObject.FindWithTag("UGUIRootTop") then
parent=UnityEngine.GameObject.FindWithTag("UGUIRootTop").gameObject
elseif UnityEngine.GameObject.FindWithTag("UGUIRoot") then
parent=UnityEngine.GameObject.FindWithTag("UGUIRoot").gameObject
end
if item then
local type = item.type--道具 41 其他
if type == utils.ItemHelper.TYPE.HERO then
if item.func and item.func~=0 then
item.func()
else
utils.SGKTools.HeroShow(item.id)
end
elseif type == utils.ItemHelper.TYPE.SUIT then
if item.func and item.func~=0 then
item.func()
else
DialogStack.PushPrefStact("dataBox/suitsManualFrame", {suitId = item.id,hideSuits = true})
end
else
if item.ItemType and item.ItemType~=0 then
type=item.ItemType
end
if type== 0 then
type=utils.ItemHelper.TYPE.EQUIPMENT
elseif type== 1 then
type= utils.ItemHelper.TYPE.INSCRIPTION
end
local _tab=setmetatable({InItemBag=tab[0],count=tab[1],type=type}, {__index=item})
if item.func and item.func~=0 then
item.func()
else
DialogStack.PushPrefStact("ItemDetailFrame",_tab,parent)
end
end
else--头像点击
if tab.func and tab.func~=0 then
tab.func()
else
utils.SGKTools.HeroShow(tab.icon and tonumber(tab.icon) or 11000)
end
end
end
function LoadingView:showCapacityChange(from,to)
-- print("战力变化", from,to)
if from == to then
return;
end
if SceneStack.GetBattleStatus() then
return;
end
if self.capacityChangeView and not utils.SGKTools.GameObject_null(self.capacityChangeView.gameObject) and not utils.SGKTools.GameObject_null(self.capacityChangeView.rotateNum.gameObject) and self.capacityChangeView.rotateNum[SGK.RotateNumber] then
self.capacityChangeView.rotateNum[SGK.RotateNumber]:Change(from, to);
else
local prefabs = SGK.ResourcesManager.Load("prefabs/base/CapacityTip.prefab")
local obj = nil
if UnityEngine.GameObject.FindWithTag("UGUITopRoot") then
obj = CS.UnityEngine.GameObject.Instantiate(prefabs,UnityEngine.GameObject.FindWithTag("UGUITopRoot").gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UGUIRootTop") then
obj = CS.UnityEngine.GameObject.Instantiate(prefabs,UnityEngine.GameObject.FindWithTag("UGUIRootTop").gameObject.transform)
elseif UnityEngine.GameObject.FindWithTag("UGUIRoot") then
obj = CS.UnityEngine.GameObject.Instantiate(prefabs,UnityEngine.GameObject.FindWithTag("UGUIRoot").gameObject.transform)
else
obj = CS.UnityEngine.GameObject.Instantiate(prefabs);
end
self.capacityChangeView = CS.SGK.UIReference.Setup(obj);
self.capacityChangeView[UnityEngine.CanvasGroup]:DOFade(1, 0.1);
self.capacityChangeView.rotateNum[SGK.RotateNumber].OnComplete = function()
self.capacityChangeView[UnityEngine.CanvasGroup]:DOFade(0, 0.1):SetDelay(0.5):OnComplete(function ()
CS.UnityEngine.GameObject.Destroy(obj);
end);
self.capacityChangeView[UnityEngine.AudioSource]:Stop()
self.capacityChangeView = nil;
end
self.capacityChangeView.rotateNum[SGK.RotateNumber]:Change(from, to);
self.capacityChangeView[UnityEngine.AudioSource]:Play()
end
end
function LoadingView:listEvent()
return {
"LOADING_PROGRESS_UPDATE",
"LOADING_PROGRESS_MESSAGE",
"LOADING_PROGRESS_DONE",
"showDlgError",
"showDlgMsg",
"GetItemTips",
"OnClickItemIcon",
"showCapacityChange",
}
end
function LoadingView:onEvent(event, percent, msg)
if event == "LOADING_PROGRESS_UPDATE" then
SceneService:SetPercent(percent, msg);
elseif event == "LOADING_PROGRESS_MESSAGE" then
-- self.loading.gameObject:SetActive(true)
self.messageLabel.text = msg
elseif event == "LOADING_PROGRESS_DONE" then
self.progressBar.value = 1
SceneService:FinishLoading();
elseif event == "showDlgError" then
self:showDlgError(percent[1],percent[2],percent[3])
elseif event == "GetItemTips" then
self:GetItemTips(percent[1],percent[2],percent[3],percent[4],msg,percent[5])
elseif event == "showDlgMsg" then
if percent then
self.showDlgMsgList[#self.showDlgMsgList + 1] = percent
self:loadShowDlgMsg()
end
elseif event == "OnClickItemIcon" then
self:OnClickIcon(percent,msg)
elseif event == "showCapacityChange" then
self:showCapacityChange(percent[1], percent[2])
end
end
function LoadingView:RELOAD()
UnityEngine.PlayerPrefs.SetString("gameURL", "")
SceneService:Reload();
end
return LoadingView;
|
-----------------------------------
-- Area: Riverne - Site A01
-- Mob: Carmine Dobsonfly
-----------------------------------
local ID = require("scripts/zones/Riverne-Site_A01/IDs");
require("scripts/globals/status");
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(tpz.mobMod.SUPERLINK, ID.mob.CARMINE_DOBSONFLY_OFFSET);
mob:SetMagicCastingEnabled(false); -- does not cast spells while idle
end;
function onMobEngaged(mob,target)
mob:SetMagicCastingEnabled(true);
end;
function onMobDisengage(mob)
mob:SetMagicCastingEnabled(false);
end;
function onMobDeath(mob, player, isKiller)
end;
function onMobDespawn(mob)
-- each dead dobsonfly should stay despawned until all 10 are killed. then they respawn as a group.
local allFliesDead = true;
for i = ID.mob.CARMINE_DOBSONFLY_OFFSET, ID.mob.CARMINE_DOBSONFLY_OFFSET + 9 do
if (GetMobByID(i):isAlive()) then
allFliesDead = false;
end
end
if (allFliesDead) then
local respawnTime = math.random(75600,86400);
for i = ID.mob.CARMINE_DOBSONFLY_OFFSET, ID.mob.CARMINE_DOBSONFLY_OFFSET + 9 do
DisallowRespawn(i, false);
GetMobByID(i):setRespawnTime(respawnTime);
end
else
DisallowRespawn(mobID, true);
end
end;
|
return Def.ActorFrame {
CurrentSongChangedMessageCommand=function(self)
local song = GAMESTATE:GetCurrentSong();
if song then
-- self:setaux(0);
self:playcommand("TweenOn");
elseif not song and self:GetZoomX() == 1 then
-- self:setaux(1);
self:playcommand("TweenOff");
end;
end;
-- Def.Quad {
-- InitCommand=cmd(y,-14;zoomto,164,2;fadeleft,8/164;faderight,8/164);
-- OnCommand=cmd(diffuse,Color("Black");diffusealpha,0;linear,0.35;diffusealpha,0.5);
-- };
-- Def.Quad {
-- InitCommand=cmd(y,24*(5)-10;zoomto,164,2;fadeleft,8/164;faderight,8/164);
-- OnCommand=cmd(diffuse,Color("Black");diffusealpha,0;linear,0.35;diffusealpha,0.5);
-- };
Def.StepsDisplayList {
Name="StepsDisplayListRow";
CursorP1 = Def.ActorFrame {
InitCommand=cmd(x,-80;player,PLAYER_1);
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_1 then
self:visible(true);
(cmd(zoom,0;bounceend,0.3;zoom,1))(self);
end;
end;
PlayerUnjoinedMessageCommand=function(self, params)
if params.Player == PLAYER_1 then
self:visible(true);
(cmd(bouncebegin,0.3;zoom,0))(self);
end;
end;
LoadActor(THEME:GetPathG("_StepsDisplayListRow","Cursor")) .. {
InitCommand=cmd(diffuse,PlayerColor(PLAYER_1);x,8;zoom,0.75);
};
LoadActor(THEME:GetPathG("_StepsDisplayListRow","arrow")) .. {
InitCommand=cmd(x,20;diffuse,PlayerColor(PLAYER_1));
OnCommand=cmd(thump,1;effectmagnitude,1,1.25,1;effectclock,'beat';);
};
LoadFont("Common Normal") .. {
Text="P1";
InitCommand=cmd(x,6;diffuse,0,0,0,1;shadowlength,1);
OnCommand=cmd(zoomy,0.25;zoomx,0.15);
};
};
CursorP2 = Def.ActorFrame {
InitCommand=cmd(x,80;player,PLAYER_2);
PlayerJoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:visible(true);
(cmd(zoom,0;bounceend,0.3;zoom,1))(self);
end;
end;
PlayerUnjoinedMessageCommand=function(self, params)
if params.Player == PLAYER_2 then
self:visible(true);
(cmd(bouncebegin,0.3;zoom,0))(self);
end;
end;
LoadActor("P2_cursor.png") .. {
InitCommand=cmd(x,65;y,-2;draworder,1;zoom,0.85);
};
};
CursorP1Frame = Def.Actor{
ChangeCommand=cmd(stoptweening);
InitCommand=cmd(diffusealpha,0);
};
CursorP2Frame = Def.Actor{
ChangeCommand=cmd(stoptweening);
};
};
}; |
object_draft_schematic_armor_component_armor_core_assault_basic = object_draft_schematic_armor_component_shared_armor_core_assault_basic:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_armor_component_armor_core_assault_basic, "object/draft_schematic/armor/component/armor_core_assault_basic.iff")
|
--[[
Launchcontrol Extension for VLC
Copyright 2017 Funjack
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--]]
--[[ Config ]]--
local clientConfig = {
url = "http://127.0.0.1:6969",
latency = 0,
positionMin = 0,
positionMax = 100,
speedMin = 20,
speedMax = 100,
}
--[[ VLC extension hooks ]]--
function descriptor()
return {
title = "Launchcontrol 0.0.4",
version = "0.0.4",
author = "Funjack",
url = "https://github.com/funjack/launchcontrol/",
shortdesc = "Launchcontrol",
description = [[
Extension that will scan for haptic scripts on playback. The haptics will
be loaded into a Launchcontrol server and played in sync. Actions like
pausing playback or seeking to a new postion are relayed to the
Launchcontrol server.
]],
capabilities = {"menu", "input-listener", "playing-listener"},
icon = icon_string,
}
end
function activate()
vlc.msg.dbg("[Launchcontrol] Get ready for the Launch")
-- file is already open when we activate
if vlc.input.item() then
input_changed()
end
vlc.msg.dbg("[Launchcontrol] Activated")
end
function close()
vlc.msg.dbg("[Launchcontrol] Close")
vlc.deactivate()
end
function deactivate()
vlc.msg.dbg("[Launchcontrol] Stopped")
end
function menu()
vlc.msg.dbg("[Launchcontrol] Menu")
return {
"Configure",
"Test connection",
}
end
function meta_changed()
return false
end
function trigger_menu(id)
-- Config
if id == 1 then
gui_config()
end
-- Test connection
if id == 2 then
launch_play("{0.50:4,1.00:0,2.50:4,3.00:0}", "text/prs.kiiroo")
end
end
function input_changed()
vlc.msg.dbg("[Launchcontrol] Input changed")
-- vlc.input.item() must be the first call, it will conflict/hang with
-- http_client
local item = vlc.input.item()
launch_stop()
if item then
local uri = item:uri()
if uri then
vlc.msg.dbg("[Launchcontrol] Searching script for "..uri)
local data, mediaType = read_script(uri)
if data then
vlc.msg.dbg("[Launchcontrol] Found "..mediaType.." script!")
launch_play(data, mediaType)
launch_skip_to_current_time()
end
end
end
end
function playing_changed(status)
vlc.msg.dbg("[Launchcontrol] Playing changed "..status)
if status == 2 then launch_resume() end
if status == 3 then launch_pause() end
end
--[[ GUI ]]--
function gui_config()
local d = vlc.dialog("Launchcontrol Config")
local userInput = {}
d:add_label("<b>Connection</b>", 1, 1, 3, 1)
d:add_label("Address:", 1, 2, 1, 1)
userInput["url"] = d:add_text_input(clientConfig["url"], 2, 2, 2, 1)
d:add_label("Latency (ms):", 1, 3, 1, 1)
userInput["latency"] = d:add_text_input(clientConfig["latency"], 2, 3, 2, 1)
d:add_label("<b>Position boundries</b>", 1, 4, 3, 1)
d:add_label("Lowest:", 1, 5, 1, 1)
userInput["positionMin"] = d:add_text_input(clientConfig["positionMin"], 2, 5, 2, 1)
d:add_label("Highest:", 1, 6, 1, 1)
userInput["positionMax"] = d:add_text_input(clientConfig["positionMax"], 2, 6 ,2 ,1)
d:add_label("<b>Speed limits</b>", 1, 7, 3, 1)
d:add_label("Slowest:", 1, 8, 1, 1)
userInput["speedMin"] = d:add_text_input(clientConfig["speedMin"], 2, 8, 2, 1)
d:add_label("Fastest:", 1, 9, 1, 1)
userInput["speedMax"] = d:add_text_input(clientConfig["speedMax"], 2, 9, 2, 1)
d:add_label("", 1, 10, 1, 1)
d:add_button("OK", function() update_config(userInput) d:delete() end, 2, 10, 1, 1)
d:add_button("Cancel", function() d:delete() end, 3, 10, 1, 1)
d:show()
end
--[[ Actions ]]--
--- Update config
function update_config(userInput)
local uri = userInput["url"]:get_text()
if uri then clientConfig["url"] = uri end
local latency = tonumber(userInput["latency"]:get_text())
if latency then clientConfig["latency"] = latency end
local positionMin = tonumber(userInput["positionMin"]:get_text())
if positionMin then clientConfig["positionMin"] = positionMin end
local positionMax = tonumber(userInput["positionMax"]:get_text())
if positionMax then clientConfig["positionMax"] = positionMax end
local speedMin = tonumber(userInput["speedMin"]:get_text())
if speedMin then clientConfig["speedMin"] = speedMin end
local speedMax = tonumber(userInput["speedMax"]:get_text())
if speedMax then clientConfig["speedMax"] = speedMax end
end
--- Skip to the current time code.
function launch_skip_to_current_time()
local input = vlc.object.input()
if input then
-- XXX will change in future versions form sec to microsec.
time = math.floor(vlc.var.get(input, "time")*1000)
launch_skip(time)
end
end
--- read_script detects and reads script file for movie.
function read_script(file)
local baseFilename = remove_extension(file)
for _, scriptType in ipairs(scriptTypes) do
for _, extension in ipairs(scriptType["extensions"]) do
local url = baseFilename.."."..extension
local path = local_path(url)
if path then
vlc.msg.dbg("[Launchcontrol] testing for local file: "..path)
end
local data
if path then
data = read_file(path)
-- FIXME: Disable network source as vlc.stream seems to be racey and
-- cause crashes.
--else
-- FIXME: VLC stream returns UI errors for each try
-- data = read_stream(url)
end
if data and data ~= "" then
return data, scriptType["mediaType"]
end
end
end
return nil
end
--[[ Utils ]]--
--- remove_extension removes the file extension from path or url
function remove_extension(file)
local dotSplit = {}
for p in string.gmatch(file, "[^\\.]+") do
table.insert(dotSplit, p)
end
if #dotSplit > 1 then
table.remove(dotSplit)
end
return table.concat(dotSplit, ".")
end
--- read_stream
function read_stream(url)
local s, err = vlc.stream(url)
if s then
local data = ""
local line = s:readline()
while line do
data = data..line
line = s:readline()
end
return data
end
vlc.msg.dbg("[Launchcontrol] could not open file: "..err)
return nil
end
--- local_path returns a path if the file in url is local
function local_path(url)
local u = url_parse(url)
if (not u["protocol"]) or u["protocol"] == "file" then
path = vlc.strings.decode_uri(u["path"])
-- on windows remove / in front of driveletter
return string.match(path, "^/(%a:/.+)$") or path
end
return nil
end
--- read_file reads an entire file
function read_file(file)
local f = io.open(file, "rb")
if f then
local data = f:read("*a")
f:close()
return data
end
return nil
end
--- url_parse parses an url with either strings or net
function url_parse(url)
if vlc.strings.url_parse then
return vlc.strings.url_parse(url)
else
return vlc.net.url_parse(url)
end
end
--[[ Launch client ]]--
scriptTypes = {
{
name = "funscript",
extensions = {"funscript"},
mediaType = "application/prs.funscript+json",
},
{
name = "raw",
extensions = {"launch"},
mediaType = "application/prs.launchraw+json",
},
{
name = "kiiroo",
extensions = {"kiiroo"},
mediaType = "text/prs.kiiroo",
},
{
name = "feelme",
extensions = {"meta"},
mediaType = "application/prs.kiiroo+json",
},
{
name = "realtouch",
extensions = {"realtouch", "ott"},
mediaType = "text/prs.realtouch",
},
{
name = "vorze",
extensions = {"vorze"},
mediaType = "text/prs.vorze",
},
{
name = "json",
extensions = {"json"},
mediaType = "application/json",
},
{
name = "text",
extensions = {"txt"},
mediaType = "text/plain",
},
{
name = "csv",
extensions = {"csv"},
mediaType = "text/csv",
},
}
--- Play by sending data as specified mediatype.
-- @param data Raw script data.
-- @param mediaType Mimetype of the script in data
function launch_play(data, mediaType)
url = clientConfig["url"].."/v1/play?"
params = {
"latency="..clientConfig["latency"],
"positionmin="..clientConfig["positionMin"],
"positionmax="..clientConfig["positionMax"],
"speedmin="..clientConfig["speedMin"],
"speedmax="..clientConfig["speedMax"],
}
http_post(url..table.concat(params, "&"), mediaType, data)
end
--- Stop playback.
function launch_stop()
http_get(clientConfig["url"].."/v1/stop")
end
--- Pause playback.
function launch_pause()
http_get(clientConfig["url"].."/v1/pause")
end
--- Resume playback.
function launch_resume()
http_get(clientConfig["url"].."/v1/resume")
launch_skip_to_current_time()
end
--- Skip jumps to a timecode
-- @param time Time position in script to jump to in ms.
function launch_skip(time)
http_get(clientConfig["url"].."/v1/skip?p="..time.."ms")
end
--[[ HTTP Client ]]--
--- HTTP GET
function http_get(url)
return http_request("GET", url)
end
--- HTTP POST
-- @param url URL
-- @param contenttype Type in data
-- @param data Data to send
function http_post(url, contenttype, data)
local cHdr = "Content-Type: "..contenttype
return http_request("POST", url, cHdr, data)
end
function http_request(method, url, headers, body)
local u = url_parse(url)
if u["protocol"] ~= "http" then return false end
local host, path, port = u["host"], u["path"], u["port"]
local header = {
string.upper(method).." "..path.." HTTP/1.0",
"Host: "..host,
}
if body then table.insert(header, "Content-Length: "..#body) end
if headers then
if type(headers) == "table" then
for v in headers do
table.insert(header, v)
end
else
table.insert(header, headers)
end
end
-- header break
table.insert(header, "")
table.insert(header, "")
local request = table.concat(header, "\r\n")
if body then
request = request..body
end
--return status, response
return http_execute(host, port, request)
end
function http_execute(host, port, request)
local fd = vlc.net.connect_tcp(host, tonumber(port))
if not fd then return false end
local pollfds = {}
pollfds[fd] = vlc.net.POLLIN
vlc.net.send(fd, request)
vlc.net.poll(pollfds)
local chunk = vlc.net.recv(fd, 2048)
local response = ""
local headerStr, header, body
local status
while chunk do
response = response..chunk
if not header then
headerStr, body = response:match("(.-\r?\n)\r?\n(.*)")
if headerStr then
response = body
header = http_parse_header(headerStr)
status = tonumber(header["statuscode"])
end
end
vlc.net.poll(pollfds)
chunk = vlc.net.recv(fd, 1024)
end
vlc.net.close(fd)
return status, response
end
function http_parse_header(data)
local header = {}
for name, s, val in string.gmatch(data, "([^%s:]+)(:?)%s([^\n]+)\r?\n") do
if s == "" then
header['statuscode'] = tonumber(string.sub(val, 1 , 3))
else
header[name] = val
end
end
return header
end
icon_string = "\137\80\78\71\13\10\26\10\0\0\0\13\73\72\68\82\0\0\0\32\0\0\0\32\8\6\0\0\0\115\122\122\244\0\0\0\6\98\75\71\68\0\228\0\150\0\148\42\235\73\127\0\0\0\9\112\72\89\115\0\0\11\19\0\0\11\19\1\0\154\156\24\0\0\0\7\116\73\77\69\7\225\4\27\13\36\6\115\7\195\25\0\0\0\25\116\69\88\116\67\111\109\109\101\110\116\0\67\114\101\97\116\101\100\32\119\105\116\104\32\71\73\77\80\87\129\14\23\0\0\1\141\73\68\65\84\88\195\189\151\81\110\194\48\12\134\29\175\90\197\99\159\144\246\100\229\6\168\23\224\10\200\231\172\118\3\196\5\184\66\84\237\2\60\79\20\135\7\136\88\105\25\113\211\244\151\42\129\19\236\207\142\235\82\3\211\229\159\190\155\41\78\204\164\192\8\192\59\238\25\155\239\6\64\244\62\117\0\8\158\119\12\206\185\209\101\107\109\0\49\57\0\60\243\35\248\233\116\234\45\86\85\245\128\104\154\104\223\133\34\123\112\206\13\2\7\5\187\115\14\0\33\28\199\108\242\204\236\137\200\223\155\239\229\69\68\158\153\253\72\147\166\1\108\54\155\183\193\195\245\103\111\76\97\227\118\89\107\163\105\173\181\177\158\99\183\229\19\198\222\122\90\241\142\1\240\253\49\168\42\192\204\64\68\47\215\137\8\152\121\230\10\60\169\174\235\81\8\34\130\186\174\251\70\153\99\14\200\237\30\15\131\38\64\12\130\101\235\129\145\169\23\163\87\227\122\94\0\196\100\104\76\202\72\36\41\123\21\128\230\24\52\123\11\205\185\30\143\199\183\19\81\147\189\26\32\4\176\214\194\225\112\232\217\183\219\173\58\248\228\81\188\223\239\239\45\112\1\145\75\207\182\8\64\255\255\140\73\242\80\36\13\17\196\101\6\209\40\121\89\130\136\128\136\64\81\150\89\1\76\251\211\14\140\221\249\60\250\57\232\254\27\147\165\2\68\4\210\117\128\136\128\136\32\93\247\239\83\50\91\15\200\69\18\94\73\18\1\62\87\43\232\62\126\111\78\86\229\242\0\95\235\245\114\143\227\156\138\61\61\31\154\47\70\109\219\70\251\87\1\228\72\80\245\110\152\163\186\87\49\209\167\2\90\159\6\188\0\0\0\0\73\69\78\68\174\66\96\130"
--[[ vim: set expandtab shiftwidth=2 tabstop=2 : ]]--
|
return {
{title = "Flower Image", scene = "samples/flower_image_sample"},
{title = "Flower SheetImage", scene = "samples/flower_sheetimage_sample", openAnime = "crossFade", closeAnime = "crossFade"},
{title = "Flower MovieClip", scene = "samples/flower_movieclip_sample", openAnime = "popIn", closeAnime = "popOut"},
{title = "Flower MapImage", scene = "samples/flower_mapimage_sample", openAnime = "slideLeft", closeAnime = "slideRight"},
{title = "Flower NineImage", scene = "samples/flower_nineimage_sample", openAnime = "slideLeft", closeAnime = "slideRight"},
{title = "Flower Label", scene = "samples/flower_label_sample", openAnime = "slideRight", closeAnime = "slideLeft"},
{title = "Flower Group", scene = "samples/flower_group_sample", openAnime = "slideRight", closeAnime = "slideLeft"},
{title = "Flower Graphics", scene = "samples/flower_graphics_sample", openAnime = "slideRight", closeAnime = "slideLeft"},
{title = "Flower Scene", scene = "samples/flower_scene_sample", openAnime = "slideTop", closeAnime = "slideBottom"},
{title = "Flower Touch", scene = "samples/flower_touch_sample", openAnime = "slideBottom", closeAnime = "slideTop"},
{title = "Flower Input", scene = "samples/flower_input_sample", openAnime = "change", closeAnime = "change"},
{title = "Flower Animation", scene = "samples/flower_animation_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Flower Interceptor", scene = "samples/flower_interceptor_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Flower Logger", scene = "samples/flower_logger_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Flower Particle", scene = "samples/flower_particle_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Tiled Basic 1", scene = "samples/tiled_basic_1_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Tiled Basic 2", scene = "samples/tiled_basic_2_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Tiled Isometric 1", scene = "samples/tiled_iso_1_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Tiled Map Editor", scene = "samples/tiled_map_editor_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Tiled RPG 1", scene = "samples/tiled_rpg_1_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Dungeon 1", scene = "samples/dungeon_1_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Dungeon 2", scene = "samples/dungeon_2_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Dungeon 3", scene = "samples/dungeon_3_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget Button", scene = "samples/widget_button_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget CheckBox", scene = "samples/widget_checkbox_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget Joystick", scene = "samples/widget_joystick_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget Panel", scene = "samples/widget_panel_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget TextLabel", scene = "samples/widget_textlabel_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget TextBox", scene = "samples/widget_textbox_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget TextInput", scene = "samples/widget_textinput_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget MsgBox", scene = "samples/widget_msgbox_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget DialogBox", scene = "samples/widget_dialogbox_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget ListBox", scene = "samples/widget_listbox_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget Layout", scene = "samples/widget_layout_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget ViewGroup", scene = "samples/widget_viewgroup_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget ScrollGroup", scene = "samples/widget_scrollgroup_sample", openAnime = "slideLeft", closeAnime = "fade"},
{title = "Widget ScrollView 1", scene = "samples/widget_scrollview_1_sample", openAnime = "slideRight", closeAnime = "fade"},
{title = "Widget ScrollView 2", scene = "samples/widget_scrollview_2_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget PanelView", scene = "samples/widget_panelview_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Widget TextView", scene = "samples/widget_textview_sample", openAnime = "popIn", closeAnime = "popOut"},
{title = "Widget ListView", scene = "samples/widget_listview_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Spine Skeletal Animation", scene = "samples/spine_boy_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Spine Atlas", scene = "samples/spine_boy_atlas_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Spine Skins", scene = "samples/spine_goblins_sample", openAnime = "fade", closeAnime = "fade"},
{title = "FSM", scene = "samples/fsm_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Audio", scene = "samples/audio_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Performance Test1", scene = "samples/performance1_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Performance Test2", scene = "samples/performance2_sample", openAnime = "fade", closeAnime = "fade"},
{title = "Task Library", scene = "samples/tasker_sample", openAnime = "fade", closeAnime = "fade"},
}
|
tilemap=require('tilemap')
require('maptool')
require('camera')
--地图在屏幕上显示的左上角x,y坐标
tilemap._X,tilemap._Y=-80,-180
tilemap._rot=0
tilemap._sx=1
tilemap._sy=1
quadtable={}
player={}
player.X=400
player.Y=300
player.rot=0
player.sx=1
player.sy=1
speed=300
function love.load()
image=love.graphics.newImage("assets/" .. tilemap["tilesets"][1].name ..tilemap["properties"]["format"])
makeQuad(tilemap)
player.img=love.graphics.newImage("assets/player.png")
mainfont = love.graphics.newFont( 20 )
--这里的边界实际相当于(地图左时角x坐标,地图左时角y坐标,地图右下角x坐标,地图右下角y坐标)
--因为后面整体向左,和向上偏移了,所以减了偏移
camera:setBounds(tilemap._X-player.X,tilemap._Y-player.Y,880-player.X,780-player.Y)
end
function love.draw()
camera:set()
drawMap(tilemap,image)
love.graphics.draw(player.img,player.X,player.Y,
player.rot,player.sx,player.sy,player.
--设置图片的中心
img:getWidth() / 2,player.img:getHeight() / 2)
camera:unset()
love.graphics.setFont(mainfont);
love.graphics.print("player.X=" .. player.X .. " player.Y=" .. player.Y,20,20)
end
function love.update(dt)
--平移
if(love.keyboard.isDown("up")) then
player.Y=player.Y-speed*dt
end
if(love.keyboard.isDown("down")) then
player.Y=player.Y+speed*dt
end
if(love.keyboard.isDown("left")) then
player.X=player.X-speed*dt
end
if(love.keyboard.isDown("right")) then
player.X=player.X+speed*dt
end
--旋转
if(love.keyboard.isDown("j")) then
player.rot=player.rot-0.5
end
if(love.keyboard.isDown("l")) then
player.rot=player.rot+0.5
end
--缩放
if (love.keyboard.isDown("i")) then
player.sx=player.sx+0.1
player.sy=player.sy+0.1
end
if (love.keyboard.isDown("k")) then
player.sx=player.sx-0.1
player.sy=player.sy-0.1
end
--设置摄相机的偏移
camera:setOffset(player.X-400, player.Y-300)
end
function love.keypressed(key)
end
--鼠标事件
function love.mousepressed(x,y,button)
if button=="wd" then
player.sx=player.sx-0.1
player.sy=player.sy-0.1
end
if button=="wu" then
player.sx=player.sx+0.1
player.sy=player.sy+0.1
end
end
|
----------------------------------------------------------------------------
--- A notification square icon.
--
-- This widget is a specialized `wibox.widget.imagebox` with the following extra
-- features:
--
-- * Honor the `beautiful` notification variables.
-- * Restrict the size avoid huge notifications
-- * Provides some strategies to handle small icons
-- * React to the `naughty.notification` object icon changes.
--
--
--
--
--
-- @usage
-- local notif = naughty.notification {
-- title = "A notification",
-- message = "This notification has actions!",
-- icon = beautiful.awesome_icon,
-- }
--
-- wibox.widget {
-- notification = notif,
-- widget = naughty.widget.icon,
-- }
--
-- @author Emmanuel Lepage Vallee <elv1313@gmail.com>
-- @copyright 2017 Emmanuel Lepage Vallee
-- @widgetmod naughty.widget.icon
-- @see wibox.widget.imagebox
----------------------------------------------------------------------------
local imagebox = require("wibox.widget.imagebox")
local gtable = require("gears.table")
local beautiful = require("beautiful")
local gsurface = require("gears.surface")
local dpi = require("beautiful.xresources").apply_dpi
local icon = {}
-- The default way to resize the icon.
-- @beautiful beautiful.notification_icon_resize_strategy
-- @param number
function icon:fit(_, width, height)
-- Until someone complains, adding a "leave blank space" isn't supported
if not self._private.image then return 0, 0 end
local maximum = math.min(width, height)
local strategy = self._private.resize_strategy or "resize"
local optimal = math.min(beautiful.notification_icon_size or dpi(48), maximum)
local w = self._private.image:get_width()
local h = self._private.image:get_height()
if strategy == "resize" then
return math.min(w, optimal, maximum), math.min(h, optimal, maximum)
else
return optimal, optimal
end
end
function icon:draw(_, cr, width, height)
if not self._private.image then return end
if width == 0 or height == 0 then return end
-- Let's scale the image so that it fits into (width, height)
local strategy = self._private.resize_strategy or "resize"
local w = self._private.image:get_width()
local h = self._private.image:get_height()
local aspect = width / w
local aspect_h = height / h
if aspect > aspect_h then aspect = aspect_h end
if aspect < 1 or (strategy == "scale" and (w < width or h < height)) then
cr:scale(aspect, aspect)
end
local x, y = 0, 0
if (strategy == "center" and aspect < 1) or strategy == "resize" then
x = math.floor((width - w*aspect) / 2)
y = math.floor((height - h*aspect) / 2)
elseif strategy == "center" and aspect > 1 then
x = math.floor((width - w) / 2)
y = math.floor((height - h) / 2)
end
cr:set_source_surface(self._private.image, x, y)
cr:paint()
end
--- The attached notification.
-- @property notification
-- @tparam naughty.notification notification
-- @propemits true false
function icon:set_notification(notif)
if self._private.notification == notif then return end
if self._private.notification then
self._private.notification:disconnect_signal("destroyed",
self._private.icon_changed_callback)
end
local icn = gsurface.load_silently(notif.icon)
if icn then
self:set_image(icn)
end
self._private.notification = notif
notif:connect_signal("property::icon", self._private.icon_changed_callback)
self:emit_signal("property::notification", notif)
end
local valid_strategies = {
scale = true,
center = true,
resize = true,
}
--- How small icons are handled.
--
-- Valid values are:
--
-- * **scale**: Scale the icon up to the optimal size.
-- * **center**: Keep the icon size and draw it in the center
-- * **resize**: Change the size of the widget itself (*default*).
--
-- Note that the size upper bound is defined by
-- `beautiful.notification_icon_size`.
--
--
--
--
--
--
-- @property resize_strategy
-- @tparam string resize_strategy
-- @propemits true false
-- @usebeautiful beautiful.notification_icon_resize_strategy The fallback when
-- there is no specified strategy.
-- @usebeautiful beautiful.notification_icon_size The size upper bound.
function icon:set_resize_strategy(strategy)
assert(valid_strategies[strategy], "Invalid strategy")
self._private.resize_strategy = strategy
self:emit_signal("widget::redraw_needed")
self:emit_signal("property::resize_strategy", strategy)
end
function icon:get_resize_strategy()
return self._private.resize_strategy
or beautiful.notification_icon_resize_strategy
or "resize"
end
--- Create a new naughty.widget.icon.
-- @tparam table args
-- @tparam naughty.notification args.notification The notification.
-- @constructorfct naughty.widget.icon
local function new(args)
args = args or {}
local tb = imagebox()
gtable.crush(tb, icon, true)
function tb._private.icon_changed_callback()
local icn = gsurface.load_silently(tb._private.notification.icon)
if icn then
tb:set_image(icn)
end
end
if args.notification then
tb:set_notification(args.notification)
end
return tb
end
--
--- Get a widget index.
-- @param widget The widget to look for
-- @param[opt] recursive Also check sub-widgets
-- @param[opt] ... Additional widgets to add at the end of the path
-- @return The index
-- @return The parent layout
-- @return The path between self and widget
-- @method index
-- @baseclass wibox.widget
--- Get or set the children elements.
-- @property children
-- @tparam table children The children.
-- @baseclass wibox.widget
--- Get all direct and indirect children widgets.
-- This will scan all containers recursively to find widgets
-- Warning: This method it prone to stack overflow id the widget, or any of its
-- children, contain (directly or indirectly) itself.
-- @property all_children
-- @tparam table children The children.
-- @baseclass wibox.widget
--- Set a declarative widget hierarchy description.
-- See [The declarative layout system](../documentation/03-declarative-layout.md.html)
-- @param args An array containing the widgets disposition
-- @method setup
-- @baseclass wibox.widget
--- Force a widget height.
-- @property forced_height
-- @tparam number|nil height The height (`nil` for automatic)
-- @baseclass wibox.widget
--- Force a widget width.
-- @property forced_width
-- @tparam number|nil width The width (`nil` for automatic)
-- @baseclass wibox.widget
--- The widget opacity (transparency).
-- @property opacity
-- @tparam[opt=1] number opacity The opacity (between 0 and 1)
-- @baseclass wibox.widget
--- The widget visibility.
-- @property visible
-- @param boolean
-- @baseclass wibox.widget
--- The widget buttons.
--
-- The table contains a list of `awful.button` objects.
--
-- @property buttons
-- @param table
-- @see awful.button
-- @baseclass wibox.widget
--- Add a new `awful.button` to this widget.
-- @tparam awful.button button The button to add.
-- @method add_button
-- @baseclass wibox.widget
--- Emit a signal and ensure all parent widgets in the hierarchies also
-- forward the signal. This is useful to track signals when there is a dynamic
-- set of containers and layouts wrapping the widget.
-- @tparam string signal_name
-- @param ... Other arguments
-- @baseclass wibox.widget
-- @method emit_signal_recursive
--- When the layout (size) change.
-- This signal is emitted when the previous results of `:layout()` and `:fit()`
-- are no longer valid. Unless this signal is emitted, `:layout()` and `:fit()`
-- must return the same result when called with the same arguments.
-- @signal widget::layout_changed
-- @see widget::redraw_needed
-- @baseclass wibox.widget
--- When the widget content changed.
-- This signal is emitted when the content of the widget changes. The widget will
-- be redrawn, it is not re-layouted. Put differently, it is assumed that
-- `:layout()` and `:fit()` would still return the same results as before.
-- @signal widget::redraw_needed
-- @see widget::layout_changed
-- @baseclass wibox.widget
--- When a mouse button is pressed over the widget.
-- @signal button::press
-- @tparam table self The current object instance itself.
-- @tparam number lx The horizontal position relative to the (0,0) position in
-- the widget.
-- @tparam number ly The vertical position relative to the (0,0) position in the
-- widget.
-- @tparam number button The button number.
-- @tparam table mods The modifiers (mod4, mod1 (alt), Control, Shift)
-- @tparam table find_widgets_result The entry from the result of
-- @{wibox.drawable:find_widgets} for the position that the mouse hit.
-- @tparam wibox.drawable find_widgets_result.drawable The drawable containing
-- the widget.
-- @tparam widget find_widgets_result.widget The widget being displayed.
-- @tparam wibox.hierarchy find_widgets_result.hierarchy The hierarchy
-- managing the widget's geometry.
-- @tparam number find_widgets_result.x An approximation of the X position that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.y An approximation of the Y position that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.width An approximation of the width that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.height An approximation of the height that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.widget_width The exact width of the widget
-- in its local coordinate system.
-- @tparam number find_widgets_result.widget_height The exact height of the widget
-- in its local coordinate system.
-- @see mouse
-- @baseclass wibox.widget
--- When a mouse button is released over the widget.
-- @signal button::release
-- @tparam table self The current object instance itself.
-- @tparam number lx The horizontal position relative to the (0,0) position in
-- the widget.
-- @tparam number ly The vertical position relative to the (0,0) position in the
-- widget.
-- @tparam number button The button number.
-- @tparam table mods The modifiers (mod4, mod1 (alt), Control, Shift)
-- @tparam table find_widgets_result The entry from the result of
-- @{wibox.drawable:find_widgets} for the position that the mouse hit.
-- @tparam wibox.drawable find_widgets_result.drawable The drawable containing
-- the widget.
-- @tparam widget find_widgets_result.widget The widget being displayed.
-- @tparam wibox.hierarchy find_widgets_result.hierarchy The hierarchy
-- managing the widget's geometry.
-- @tparam number find_widgets_result.x An approximation of the X position that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.y An approximation of the Y position that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.width An approximation of the width that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.height An approximation of the height that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.widget_width The exact width of the widget
-- in its local coordinate system.
-- @tparam number find_widgets_result.widget_height The exact height of the widget
-- in its local coordinate system.
-- @see mouse
-- @baseclass wibox.widget
--- When the mouse enter a widget.
-- @signal mouse::enter
-- @tparam table self The current object instance itself.
-- @tparam table find_widgets_result The entry from the result of
-- @{wibox.drawable:find_widgets} for the position that the mouse hit.
-- @tparam wibox.drawable find_widgets_result.drawable The drawable containing
-- the widget.
-- @tparam widget find_widgets_result.widget The widget being displayed.
-- @tparam wibox.hierarchy find_widgets_result.hierarchy The hierarchy
-- managing the widget's geometry.
-- @tparam number find_widgets_result.x An approximation of the X position that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.y An approximation of the Y position that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.width An approximation of the width that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.height An approximation of the height that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.widget_width The exact width of the widget
-- in its local coordinate system.
-- @tparam number find_widgets_result.widget_height The exact height of the widget
-- in its local coordinate system.
-- @see mouse
-- @baseclass wibox.widget
--- When the mouse leave a widget.
-- @signal mouse::leave
-- @tparam table self The current object instance itself.
-- @tparam table find_widgets_result The entry from the result of
-- @{wibox.drawable:find_widgets} for the position that the mouse hit.
-- @tparam wibox.drawable find_widgets_result.drawable The drawable containing
-- the widget.
-- @tparam widget find_widgets_result.widget The widget being displayed.
-- @tparam wibox.hierarchy find_widgets_result.hierarchy The hierarchy
-- managing the widget's geometry.
-- @tparam number find_widgets_result.x An approximation of the X position that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.y An approximation of the Y position that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.width An approximation of the width that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.height An approximation of the height that
-- the widget is visible at on the surface.
-- @tparam number find_widgets_result.widget_width The exact width of the widget
-- in its local coordinate system.
-- @tparam number find_widgets_result.widget_height The exact height of the widget
-- in its local coordinate system.
-- @see mouse
-- @baseclass wibox.widget
--
--- Disconnect from a signal.
-- @tparam string name The name of the signal.
-- @tparam function func The callback that should be disconnected.
-- @method disconnect_signal
-- @baseclass gears.object
--- Emit a signal.
--
-- @tparam string name The name of the signal.
-- @param ... Extra arguments for the callback functions. Each connected
-- function receives the object as first argument and then any extra
-- arguments that are given to emit_signal().
-- @method emit_signal
-- @baseclass gears.object
--- Connect to a signal.
-- @tparam string name The name of the signal.
-- @tparam function func The callback to call when the signal is emitted.
-- @method connect_signal
-- @baseclass gears.object
--- Connect to a signal weakly.
--
-- This allows the callback function to be garbage collected and
-- automatically disconnects the signal when that happens.
--
-- **Warning:**
-- Only use this function if you really, really, really know what you
-- are doing.
-- @tparam string name The name of the signal.
-- @tparam function func The callback to call when the signal is emitted.
-- @method weak_connect_signal
-- @baseclass gears.object
return setmetatable(icon, {__call = function(_, ...) return new(...) end})
|
local _M = {}
local show_n_lines = 5
local function get_source(info)
local defined_in_file = 1 == info.source:find '@'
if not defined_in_file then return '\n' end
local from_no = info.currentline - show_n_lines
local to_no = info.currentline + show_n_lines
local number_len = #tostring(to_no)
local result = { '\n' }
local line_number = 1
for line in io.lines(info.source:sub(2)) do
if line_number >= from_no and line_number <= to_no then
local prefix = string.rep(' ', 4)
local line_number_s = string.format('%' .. number_len .. 'd', line_number)
if line_number == info.currentline then prefix = ' => ' end
table.insert(result, prefix .. line_number_s .. ': ' .. line)
end
line_number = line_number + 1
end
return table.concat(result, '\n') .. '\n'
end
function _M:whereami()
local info = self.binding.info
-- Don't show context of executable resty-repl started
if info.short_src:find('bin/resty%-repl') then return end
local heading = '\n' ..
'From: ' .. info.short_src .. ' @ line ' .. info.currentline
return heading .. get_source(info)
end
function _M.new(binding)
return setmetatable({ binding = binding }, { __index = _M })
end
return _M
|
local t = Def.ActorFrame{
GridSelectedMessageCommand=function(self)
self:stoptweening()
SOUND:StopMusic()
self:sleep(0.4)
self:queuecommand("PlayMusic")
end,
PlayMusicCommand=function(self)
local song = GAMESTATE:GetCurrentSong()
if song then
SOUND:PlayMusicPart( song:GetMusicPath(), song:GetSampleStart(), song:GetSampleLength(), 0, 1, false, false, false, song:GetTimingData() )
end
end,
}
return t |
local cjson = require('cjson').new()
local cqueues = require 'cqueues'
local tcheck = require 'tcheck'
local xerror = require 'tulip.xerror'
cjson.encode_escape_forward_slash(false)
local function stdout_logger(t)
io.write(cjson.encode(t) .. '\n')
end
local function make_file_logger(path)
local fd = xerror.must(io.open(path, 'w+'))
return function(t)
fd:write(cjson.encode(t) .. '\n')
fd:flush()
end
end
local function log_middleware(req, res, nxt)
local date = os.date('!%FT%T%z')
local start = cqueues.monotime()
nxt()
local dur = cqueues.monotime() - start
local status = tonumber(res.headers:get(':status'))
local path = req.url.path
local rid = req.locals.request_id
req.app:log(status >= 500 and 'e' or 'i', {
pkg = 'log', date = date,
path = path, status = status,
request_id = rid, full_url = tostring(req.url),
authority = req.authority, remote_addr = req.remote_addr,
http_version = req.proto, method = req.method,
duration = string.format('%.3f', dur),
bytes_written = res.bytes_written,
type = 'web request',
})
end
local function log_wmiddleware(msg, nxt)
local date = os.date('!%FT%T%z')
local start = cqueues.monotime()
nxt()
local dur = cqueues.monotime() - start
-- if a msg.error field is set on the message, it is logged as an
-- error.
msg.app:log(msg.error and 'e' or 'i', {
pkg = 'log', date = date,
queue = msg.queue, attempt = msg.attempts,
msgid = msg.id, duration = string.format('%.3f', dur),
payload = msg.raw_payload,
type = 'worker message', error = msg.error,
})
end
local M = {}
-- The log package registers a logging backend in JSON format.
--
-- Config:
--
-- * level: string|number = the minimum log level to output. If set to a
-- string, it should be either 'debug', 'error', 'info', or 'warning'
-- or the first letter of those words. Can also be a number. The mapping
-- of string level to number is: debug=1, info=10, warning=100 and
-- error=1000.
-- * file: string = path to a file to log to. If not set, will log to
-- io.output().
--
-- Fields:
--
-- App.log_level: string|number
--
-- Sets the minimum log level to consider for all logging backends.
-- Once the app is activated (in the call to app:run), if the level is
-- a string, it is converted to a number.
--
-- Middleware:
--
-- * tulip.pkg.log
--
-- Registered if the tulip.pkg.middleware package is registered. Logs
-- web requests.
--
-- Wmiddleware:
--
-- * tulip.pkg.log
--
-- Registered if the tulip.pkg.wmiddleware package is registered. Logs
-- processed worker messages.
--
function M.register(cfg, app)
tcheck({'table', 'tulip.App'}, cfg, app)
app.log_level = cfg.level
if cfg.file then
app:register_logger('tulip.pkg.log', make_file_logger(cfg.file))
else
app:register_logger('tulip.pkg.log', stdout_logger)
end
if app:has_package('tulip.pkg.middleware') then
app:register_middleware('tulip.pkg.log', log_middleware)
end
if app:has_package('tulip.pkg.wmiddleware') then
app:register_wmiddleware('tulip.pkg.log', log_wmiddleware)
end
end
return M
|
local jsonutil = require 'stuart.util.json'
--[[
Helper methods for loading models from files.
--]]
local M = {}
-- Returns URI for path/data using the Hadoop filesystem
function M.dataPath(path)
return path .. '/data'
end
--[[
* Load metadata from the given path.
* @return (class name, version, metadata)
--]]
function M.loadMetadata(sc, path)
local firstLine = sc:textFile(M.metadataPath(path)):first()
local metadata = jsonutil.decode(firstLine)
return metadata.class, metadata.version, metadata
end
-- Returns URI for path/metadata using the Hadoop filesystem
function M.metadataPath(path)
return path .. '/metadata'
end
return M
|
--[[
Countdown State
Author: Colton Ogden
cogden@cs50.harvard.edu
Counts down visually on the screen (3,2,1) so that the player knows the
game is about to begin. Transitions to the PlayState as soon as the
countdown is complete.
]]
CountdownState = Class{__includes = BaseState}
-- takes 1 second to count down each time
COUNTDOWN_TIME = 0.75
function CountdownState:init()
self.count = 3
self.timer = 0
end
--[[
Keeps track of how much time has passed and decreases count if the
timer has exceeded our countdown time. If we have gone down to 0,
we should transition to our PlayState.
]]
function CountdownState:update(dt)
self.timer = self.timer + dt
if self.timer > COUNTDOWN_TIME then
self.timer = self.timer % COUNTDOWN_TIME
self.count = self.count - 1
if self.count == 0 then
GStateMachine:change('play')
end
end
end
function CountdownState:render()
love.graphics.setFont(HugeFont)
love.graphics.printf(tostring(self.count), 0, 120, Config.defaults.VIRTUAL_WIDTH, 'center')
end |
object_tangible_collection_rock_glowing_08 = object_tangible_collection_shared_rock_glowing_08:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_rock_glowing_08, "object/tangible/collection/rock_glowing_08.iff") |
object_tangible_collection_col_dust_durni_09 = object_tangible_collection_shared_col_dust_durni_09:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_col_dust_durni_09, "object/tangible/collection/col_dust_durni_09.iff") |
data:extend(
{
{
type = "item",
name = "substation-mk2",
icon_size = 32,
icon = "__FactorioExtended-Power__/graphics/icons/substation-mk2.png",
flags = {"goes-to-quickbar"},
subgroup = "fb-energy-transfer",
order = "a[substation-mk2]-e",
place_result = "substation-mk2",
stack_size = 50
},
{
type = "item",
name = "substation-mk3",
icon_size = 32,
icon = "__FactorioExtended-Power__/graphics/icons/substation-mk3.png",
flags = {"goes-to-quickbar"},
subgroup = "fb-energy-transfer",
order = "a[substation-mk3]-f",
place_result = "substation-mk3",
stack_size = 50
}
}) |
local timer_seconds = THEME:GetMetric(Var "LoadingScreen","TimerSeconds");
return Def.ActorFrame {
InitCommand=function(self) self:xy(SCREEN_CENTER_X,SCREEN_CENTER_Y) end,
-- Fade
Def.Quad {
InitCommand=function(self) self:scaletoclipped(SCREEN_WIDTH,SCREEN_HEIGHT) end;
OnCommand=function(self)
self:diffuse(Color.Black):diffusealpha(0):linear(0.5):diffusealpha(0.25):sleep(timer_seconds/2):linear(timer_seconds/2-0.5):diffusealpha(0.8)
end;
},
Def.Quad {
InitCommand=function(self) self:zoomto(SCREEN_WIDTH,SCREEN_HEIGHT) end;
OnCommand=function(self) self:diffuse(Color.Black) end;
},
LoadActor("_sound") .. {
OnCommand=function(self) self:queuecommand("Sound") end;
SoundCommand=function(self) self:play() end;
};
LoadActor(THEME:GetPathG("ScreenGameOver","gameover"))..{
OnCommand=function(self) self:zoomx(1.1):diffusealpha(0):sleep(1):decelerate(0.6):diffusealpha(1):zoomx(1) end;
},
Def.BitmapText {
Font="_Medium";
Text=ScreenString("Play again soon!");
InitCommand=function(self) self:y(120) end;
OnCommand=function(self) self:diffusealpha(0):sleep(3):linear(0.3):diffusealpha(1) end;
},
Def.Quad {
InitCommand=function(self) self:zoomto(SCREEN_WIDTH,SCREEN_HEIGHT) end;
OnCommand=function(self) self:diffuse(Color.Black):linear(1):diffusealpha(0) end;
},
}
|
-- $Id$
--
-- All rights reserved. Part of the ALua project.
-- Detailed information regarding ALua's license can be found
-- in the LICENSE file.
--
module("alua.task", package.seeall)
require("alua.channel")
-- Mailbox for scheduled messages (created below)
local tasks
local function dispatch()
local tmp = {}
local t = tasks:receive()
while t do
tmp[#tmp+1] = t
t = tasks:receive()
end
for _, t in ipairs(tmp) do
t.func(unpack(t.args))
end
end
--
-- Select the codec based on the connection type.
--
function schedule(f, ...)
if f then
tasks:send({func = f, args = {...}})
end
end
-- Create the mailbox
tasks = alua.channel.create("mailbox", {name = "task:mailbox"},
{read = dispatch})
assert(tasks, "cannot create task queue")
|
ngx.header['Access-Control-Allow-Origin'] = '*'
ngx.header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
ngx.header['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'
ngx.header['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range';
ngx.req.read_body()
local request_body = ngx.req.get_body_data()
local arg = ngx.req.get_uri_args()
local namespace = arg['namespace']
local handle = io.popen("/opt/kube-linter-parser.sh " .. namespace)
local result = handle:read("*a")
ngx.say(result) |
--
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Dataloader for MPII+LSP
--
local image = require 'image'
local paths = require 'paths'
local t = require 'datasets/posetransforms'
-------------------------------------------------------------------------------
-- Helper Functions
-------------------------------------------------------------------------------
local getTransform = t.getTransform
local transform = t.transform
local crop = t.crop2
local drawGaussian = t.drawGaussian
local shuffleLR = t.shuffleLR
local flip = t.flip
local colorNormalize = t.colorNormalize
-------------------------------------------------------------------------------
-- Create dataset Class
-------------------------------------------------------------------------------
local M = {}
local MpiiLeedsDataset = torch.class('resnet.MpiiLeedsDataset', M)
function MpiiLeedsDataset:__init(imageInfo, opt, split)
assert(imageInfo[split], split)
self.imageInfo = imageInfo[split]
self.split = split
-- Some arguments
self.inputRes = opt.inputRes
self.outputRes = opt.outputRes
-- Options for augmentation
self.scaleFactor = opt.scaleFactor
self.rotFactor = opt.rotFactor
self.dataset = opt.dataset
self.nStack = opt.nStack
self.meanstd = torch.load('gen/mpii-lsp/meanstd.t7')
self.nGPU = opt.nGPU
self.batchSize = opt.batchSize
self.minusMean = opt.minusMean
self.gsize = opt.gsize
self.bg = opt.bg
end
function MpiiLeedsDataset:get(i, scaleFactor)
local scaleFactor = scaleFactor or 1
local dataset = self.imageInfo.data['dataset'][i]
local imgpath = self.imageInfo.data['images'][i]
if dataset == 'LEEDS' then
imgpath = paths.concat('data/lsp/', imgpath)
else
imgpath = paths.concat('data/mpii/images', imgpath)
end
local img = image.load(imgpath)
-- Generate samples
local pts = self.imageInfo.labels['part'][i]
local c = self.imageInfo.labels['center'][i]
local s = self.imageInfo.labels['scale'][i]*(410/256)*scaleFactor
-- For single-person pose estimation with a centered/scaled figure
local nParts = pts:size(1)
local inp = crop(img, c, s, 0, self.inputRes)
local out = self.bg == 'true' and torch.zeros(nParts+1, self.outputRes, self.outputRes)
or torch.zeros(nParts, self.outputRes, self.outputRes)
for i = 1,nParts do
if pts[i][1] > 0 then -- Checks that there is a ground truth annotation
drawGaussian(out[i], transform(torch.add(pts[i],1), c, s, 0, self.outputRes), self.gsize)
end
end
if self.bg == 'true' then
out[nParts+1], _ = torch.max(out:sub(1, nParts, 1, self.outputRes, 1, self.outputRes), 1)
end
-- Data augmentation
inp, out = self.augmentation(self, inp, out)
collectgarbage()
return {
input = inp,
target = out,
center = c,
scale = s,
width = img:size(3),
height = img:size(2),
imgPath = paths.concat('data/mpii/images', self.imageInfo.data['images'][i])
}
end
function MpiiLeedsDataset:size()
local nSamples = self.imageInfo.labels.nsamples - (self.imageInfo.labels.nsamples%self.nGPU)
nSamples = nSamples - nSamples%self.batchSize
return nSamples
end
function MpiiLeedsDataset:preprocess()
return function(img)
if img:max() > 2 then
img:div(255)
end
return self.minusMean == 'true' and colorNormalize(img, self.meanstd) or img
end
end
function MpiiLeedsDataset:augmentation(input, label)
-- Augment data (during training only)
if self.split == 'train' then
local s = torch.randn(1):mul(self.scaleFactor):add(1):clamp(1-self.scaleFactor,1+self.scaleFactor)[1]
local r = torch.randn(1):mul(self.rotFactor):clamp(-2*self.rotFactor,2*self.rotFactor)[1]
-- Color
input[{1, {}, {}}]:mul(torch.uniform(0.8, 1.2)):clamp(0, 1)
input[{2, {}, {}}]:mul(torch.uniform(0.8, 1.2)):clamp(0, 1)
input[{3, {}, {}}]:mul(torch.uniform(0.8, 1.2)):clamp(0, 1)
-- Scale/rotation
if torch.uniform() <= .6 then r = 0 end
local inp,out = self.inputRes, self.outputRes
input = crop(input, torch.Tensor({(inp+1)/2,(inp+1)/2}), inp*s/200, r, inp)
label = crop(label, torch.Tensor({(out+1)/2,(out+1)/2}), out*s/200, r, out)
-- Flip
if torch.uniform() <= .5 then
input = flip(input)
label = flip(shuffleLR(label, self.dataset))
end
end
return input, label
end
return M.MpiiLeedsDataset
|
variant = variant or 'debug';
local cc = require 'forge.cc' {
identifier = 'cc_${platform}_${architecture}';
platform = operating_system();
bin = root( ('%s/bin'):format(variant) );
lib = root( ('%s/lib'):format(variant) );
obj = root( ('%s/obj'):format(variant) );
include_directories = {
root();
};
library_directories = {
root( ('%s/lib'):format(variant) );
};
defines = {
variant == 'debug' and '_DEBUG' or 'NDEBUG';
};
architecture = 'native';
assertions = variant ~= 'shipping';
debug = variant ~= 'shipping';
debuggable = variant ~= 'shipping';
exceptions = true;
fast_floating_point = variant ~= 'debug';
incremental_linking = variant == 'debug';
link_time_code_generation = variant == 'shipping';
minimal_rebuild = variant == 'debug';
optimization = variant ~= 'debug';
run_time_checks = variant == 'debug';
runtime_library = variant == 'debug' and 'static_debug' or 'static_release';
run_time_type_info = true;
stack_size = 1048576;
standard = 'c++11';
string_pooling = variant == 'shipping';
strip = false;
warning_level = 3;
warnings_as_errors = true;
};
-- Bump the C++ standard to c++14 when building on Windows as that is the
-- closest standard supported by Microsoft Visual C++.
local settings = cc.settings;
if settings.platform == 'windows' then
settings.standard = 'c++14';
end
buildfile 'unittest-cpp.forge';
cc:all {
'tests/all',
'UnitTest++/all'
};
|
function doMove()
-- Left movement
if love.keyboard.isDown('left') then
x = x - speed
if enableWindowMove == true then
winX = winX - speed
end
if enableAccel == true then
speed = speed + accelAmount
end
end
-- Right movement
if love.keyboard.isDown('right') then
x = x + speed
if enableWindowMove == true then
winX = winX + speed
end
if enableAccel == true then
speed = speed + accelAmount
end
end
if enableVert == true then
-- Up movement
if love.keyboard.isDown('up') then
y = y - speed
if enableWindowMove == true then
winY = winY - speed
end
if enableAccel == true then
speed = speed + accelAmount
end
end
-- Down movement
if love.keyboard.isDown('down') then
y = y + speed
if enableWindowMove == true then
winY = winY + speed
end
if enableAccel == true then
speed = speed + accelAmount
end
end
end
end |
local song_prop_funcs= {
prof_favor_inc= function(pn)
change_favor(pn_to_profile_slot(pn), gamestate_get_curr_song(), 1)
end,
prof_favor_dec= function(pn)
change_favor(pn_to_profile_slot(pn), gamestate_get_curr_song(), -1)
end,
mach_favor_inc= function(pn)
change_favor("ProfileSlot_Machine", gamestate_get_curr_song(), 1)
end,
mach_favor_dec= function(pn)
change_favor("ProfileSlot_Machine", gamestate_get_curr_song(), -1)
end,
censor= function()
add_to_censor_list(gamestate_get_curr_song())
end,
save_column_scores= function(pn)
save_column_scores(pn)
end,
end_credit= function()
SOUND:PlayOnce("Themes/_fallback/Sounds/Common Start.ogg")
end_credit_now()
end
}
function interpret_common_song_props_code(pn, code)
if song_prop_funcs[code] then
song_prop_funcs[code](pn)
return true
end
return false
end
|
local betonMarker = 0
local betonCreatedMarkers = {}
local betonRota = {
{ 2288.396484375, -2071.4833984375, 13.385972976685 , false },--1
{ 2205.9013671875, -2154.52734375, 13.3828125 , false },--1
{ 2092.5908203125, -2107.5712890625, 13.32084941864 , false },--1
{ 1971.5078125, -2107.2705078125, 13.3828125 , false },--1
{ 1931.333984375, -2164.271484375, 13.3828125 , false },--1
{ 1690.599609375, -2164.2314453125, 16.697750091553 , false },--1
{ 1532.4345703125, -1978.1787109375, 22.722690582275 , false },--1
{ 1511.212890625, -1869.720703125, 13.3828125 , false },--1
{ 1362.921875, -1865.8037109375, 13.3828125 , false },--1
{ 1139.9951171875, -1849.484375, 13.3828125 , false },--1
{ 1019.521484375, -1793.720703125, 13.785205841064 , false },--1
{ 825.544921875, -1766.87890625, 13.399476051331 , false },--1
{ 624.078125, -1726.6025390625, 13.952794075012 , false },--1{ 0, 0, 0 , false },--1
{ 370.0927734375, -1699.34765625, 7.0395479202271 , false },--1
{ 165.4970703125, -1570.3642578125, 12.297170639038 , false },--1
{ 37.0888671875, -1521.47265625, 5.2314605712891 , false },--1
{ -124.7646484375, -1459.384765625, 2.6953125 , false },--1
{ -145.578125, -1308.6767578125, 2.6953125 , false },--1
{ -102.466796875, -1148.580078125, 1.5627844333649 , false },--1
{ -69.046875, -1121.4638671875, 1.078125 , true},--25
}
local betony , betonz = -2055.0732421875, 13.546875 -- y ve z
local beton1x = 2330.8447265625 -- x1
local beton2x = 2330.8447265625 -- x2
local beton3x = 2330.8447265625 -- x3 3 tane alma noktası koydum rinadaki gibi y ve z ayrı
function betonBasla(cmd)
if getElementData(getLocalPlayer(), "beton:yukaldi") == false or getElementData(getLocalPlayer(), "beton:yukaldi") == nil then
local x , y , z = getElementPosition( localPlayer )
if getDistanceBetweenPoints3D( beton1x , betony , betonz , x , y , z ) > 10 and getDistanceBetweenPoints3D( beton2x , betony , betonz , x , y , z ) > 10 and getDistanceBetweenPoints3D( beton3x , betony , betonz , x , y , z ) > 10 then
outputChatBox("[!]#ffffff Bir yükleme noktasına yakın değilsin!",255,0,0,true)
return
end
local carlicense = getElementData(localPlayer, "license.car")
if carlicense == 0 then
outputChatBox("[!]#ffffff Bu mesleği yapabilmek için ehliyetinizin olması gerekmektedir!",255,0,0,true)
return end
local oyuncuArac = getPedOccupiedVehicle(getLocalPlayer())
local oyuncuAracModel = getElementModel(oyuncuArac)
if oyuncuAracModel == 524 then
if getPedOccupiedVehicleSeat(getLocalPlayer()) ~= 0 then return end
setElementData(getLocalPlayer(), "beton:yukaldi", true)
updatebetonRota()
addEventHandler("onClientMarkerHit", resourceRoot, betonRotaMarkerHit)
outputChatBox("[!]#ffffff Yükünü aldın, belirtilen rotayı takip edebilirsin!",0,153,255,true)
else
outputChatBox( "[!]#ffffff Gerekli araç modeline sahip değilsiniz!" ,255,0,0,true )
end
else
outputChatBox("[!] #FFFFFFZaten mesleğe başladınız!", 255, 0, 0, true)
end
end
addCommandHandler("cimentoyukle", betonBasla)
function updatebetonRota()
betonMarker = betonMarker + 1
for i,v in ipairs(betonRota) do
if i == betonMarker then
if not v[4] == true then
local rotaMarker = createMarker(v[1], v[2], v[3], "checkpoint", 4, 255, 0, 0, 255, getLocalPlayer())
table.insert(betonCreatedMarkers, { rotaMarker, false })
elseif v[4] == true and v[5] == true then
local bitMarker = createMarker(v[1], v[2], v[3], "checkpoint", 4, 255, 255, 0, 255, getLocalPlayer())
table.insert(betonCreatedMarkers, { bitMarker, true, true })
elseif v[4] == true then
local malMarker = createMarker(v[1], v[2], v[3], "checkpoint", 4, 255, 255, 0, 255, getLocalPlayer())
table.insert(betonCreatedMarkers, { malMarker, true, false })
end
end
end
end
function betonRotaMarkerHit(hitPlayer, matchingDimension)
if hitPlayer == getLocalPlayer() then
local hitVehicle = getPedOccupiedVehicle(hitPlayer)
if hitVehicle then
local hitVehicleModel = getElementModel(hitVehicle)
if hitVehicleModel == 524 then
for _, marker in ipairs(betonCreatedMarkers) do
if source == marker[1] and matchingDimension then
if marker[2] == false then
destroyElement(source)
updatebetonRota()
elseif marker[2] == true and marker[3] == false then
local hitVehicle = getPedOccupiedVehicle(hitPlayer)
setElementFrozen(hitPlayer, true) -- markerdan sonra ilk yazdığında bişey çıkmadı
setElementFrozen(hitVehicle, true)
toggleAllControls(false, true, false)
outputChatBox("[!] #FFFFFFAracınızdaki mallar indiriliyor, lütfen bekleyiniz.", 0, 0, 255, true)
setElementData(getLocalPlayer(), "beton:yukaldi", false)
setTimer(
function(thePlayer, hitVehicle, hitMarker)
destroyElement(hitMarker)
setElementFrozen(hitVehicle, false)
setElementFrozen(thePlayer, false)
toggleAllControls(true)
triggerServerEvent( "beton:paraver" , localPlayer )
for i,v in ipairs(betonCreatedMarkers) do
destroyElement(v[1])
end
betonCreatedMarkers = {}
betonMarker = 0 -- oldu
end, 10, 1, hitPlayer, hitVehicle, source
)
end
end
end
end
end
end
end
function betonBitir()
local pedVeh = getPedOccupiedVehicle(getLocalPlayer())
local pedVehModel = getElementModel(pedVeh)
local betonSoforlugu = getElementData(getLocalPlayer(), "beton:yukaldi")
if pedVeh then
if pedVehModel == 524 then
if betonSoforlugu then
setElementData(getLocalPlayer(), "beton:yukaldi", false)
for i,v in ipairs(betonCreatedMarkers) do
destroyElement(v[1])
end
betonCreatedMarkers = {}
betonMarker = 0
removeEventHandler("onClientMarkerHit", resourceRoot, betonRotaMarkerHit)
end
end
end
end
addCommandHandler("cimentobitir", betonBitir)
function betonAntiYabanci(thePlayer, seat, door)
local vehicleModel = getElementModel(source)
if vehicleModel == 524 then
if thePlayer == getLocalPlayer() and seat ~= 0 then
setElementFrozen(thePlayer, true)
setElementFrozen(thePlayer, false)
outputChatBox("[!] #FFFFFFMeslek aracına binemezsiniz.", 255, 0, 0, true)
cancelEvent()
end
end
end
addEventHandler("onClientVehicleStartEnter", getRootElement(), betonAntiYabanci)
addEventHandler("onClientResourceStart" , root , function()
setElementData(getLocalPlayer(), "beton:yukaldi", false)
end) |
DefineClass.Factory = {
__parents = { "ResourceProducer", "ElectricityConsumer", "Workplace",},
}
DefineClass.ElectronicsFactory = {
__parents = { "Factory" },
resource_produced1 = "Electronics",
}
function ElectronicsFactory.OnCalcProduction_Electronics(producer, amount_to_produce)
return MulDivRound(producer.parent.performance, amount_to_produce, 100)
end
DefineClass.MachinePartsFactory = {
__parents = { "Factory" },
resource_produced1 = "MachineParts",
}
function MachinePartsFactory.OnCalcProduction_MachineParts(producer, amount_to_produce)
return MulDivRound(producer.parent.performance, amount_to_produce, 100)
end
DefineClass.PolymerPlant = {
__parents = { "Factory", "LifeSupportConsumer"},
properties = {
{ template = true, category = "Consumption", name = T(681, "Water"), id = "water_consumption", editor = "number", default = 5000, scale = const.ResourceScale, read_only = false, modifiable = true, min = 0, },
{ template = true, category = "Consumption", name = T(682, "Oxygen"), id = "air_consumption", editor = "number", default = 0, scale = const.ResourceScale, read_only = true , modifiable = true, min = 0, },
{ template = true, category = "Consumption", name = T(683, "Power Consumption"), id = "electricity_consumption", editor = "number", default = 1000, modifiable = true, min = 0, },
},
resource_produced1 = "Polymers",
stockpile_spots1 = { "Resourcepile" },
}
function PolymerPlant.OnCalcProduction_Polymers(producer, amount_to_produce)
return MulDivRound(producer.parent.performance, amount_to_produce, 100)
end
|
--[[
DualPriority
A dual-threaded priority call queue for Lua.
Usage:
Once the API has been required, setup the number of queues needed (queues can be added during runtime)
Adding queues is as easy as typing "queue.add(priority)". The priority is the level of priority to use (lower is more prioritized)
To initialize the queue, run in a seperate thread "queue.run()"
Includes:
Error-handling - "seq-catch" catches errors that functions in a queue raise and safely logs them
Fluidity - dynamically change the priorities of queues and the priorities of their functions
Cancelling - stop the queue from running after the current function has finished
Notes:
I (wriaith) created this to improve performance issues with my new scripts. I will most likely by improving this design in the future.
--]]
local queue = { };
do
local tray = { };
local queue_disable = false;
local order = { };
do
function order.new(priority)
local stack = {
sequence = { },
};
function stack.add(index, fn, ...)
table.insert(stack.sequence, index or #stack.sequence + 1, { fn, {...} });
end
function stack.rm(index)
table.remove(stack.sequence, index);
end
function stack.mov(index, newindex)
local order = stack.sequence[index];
table.remove(stack.sequence, index);
table.insert(stack.sequence, newindex, order);
end
return stack;
end
end
local function errorCall(message)
print("seq catch: " .. message);
end
function queue.new(priority)
local order = order.new(priority or 1);
table.insert(tray, priority or 1, order);
return order;
end
function queue.get(priority)
return tray[priority];
end
function queue.rm(priority)
table.remove(tray, priority);
end
function queue.mov(priority, newPriority)
local order = tray[priority];
table.remove(tray, priority);
table.insert(tray, newPriority, order);
end
function queue.run()
queue_disable = false;
while not queue_disable do
local stack = tray[1];
if (stack) then
if (#stack.sequence > 0) then
local current = stack.sequence[1];
table.remove(stack.sequence, 1);
local fn, args = current[1], current[2];
local function mainfn()
fn(unpack(args));
end
xpcall(mainfn, errorCall);
else
table.remove(tray, 1);
end
else
break;
end
wait(1 / 7e7);
end
end
function queue.stop()
queue_disable = true;
end
end
return queue;
|
--
-- Copyright 2021 Andreas MATTHIAS
--
-- This work may be distributed and/or modified under the
-- conditions of the LaTeX Project Public License, either version 1.3c
-- of this license or (at your option) any later version.
-- The latest version of this license is in
-- http://www.latex-project.org/lppl.txt
-- and version 1.3c or later is part of all distributions of LaTeX
-- version 2008 or later.
--
-- This work has the LPPL maintenance status `maintained'.
--
-- The Current Maintainer of this work is Andreas MATTHIAS.
--
--- This class represents a certain page of a PDF file.
-- @classmod Page
local Page = {}
-- Loading of sub-modules.
local function require_sub(mod, name)
local m = require(name)
for k, v in pairs(m) do
mod[k] = v
end
end
require_sub(Page, 'flare-keyval')
require_sub(Page, 'flare-obj')
require_sub(Page, 'flare-annot')
require_sub(Page, 'flare-dest')
require_sub(Page, 'flare-action')
local pkg = require('flare-pkg')
local types = require('flare-types')
local pdfarray = types.pdfarray
local pdfdictionary = types.pdfdictionary
local luatex = require ('flare-luatex')
--- Constructor
-- @section Constructor
--- Creates a `Page` object.
-- A `Page` object represents a certain PDF page and is connected
-- to a LaTeX document via `doc.
-- @table doc LaTeX document (@{Doc})
-- @return New `Page` object
function Page:new (doc)
local t = {}
setmetatable(t, self)
self.__index = self
self.doc = doc
self.doc:newPicture()
self.page = self.doc.pageCounter
self.GinKV = {}
self.FlareKV = {}
self.IdentityCTM = self:makeCTM(1, 0, 0, 1, 0, 0)
self.ctm = self.IdentityCTM
return t
end
--- File I/O
-- @section fileIO
--- Opens a PDF file for reading.
-- @string filename File name
function Page:openFile()
self.pdf = pdfe.open(self:findFile())
pdfe.unencrypt(self.pdf, self.userpassword, nil)
local status = pdfe.getstatus(self.pdf)
if status < 0 then
pkg.error(
string.format('PDF is password protected'))
end
end
--- Returns the full path of a PDF file using `kpse` library.
-- File name may be specified with or without file name extension `.pdf`.
-- @string filename File name
-- @return File name
function Page:findFile()
local kpse_type = 'graphic/figure'
local filename_kpse =
kpse.find_file(self.GinKV.filename, kpse_type) or
kpse.find_file(self.GinKV.filename .. '.pdf', kpse_type)
if not filename_kpse then
pkg.error(string.format("File '%s' not found", self.GinKV.filename))
end
return filename_kpse
end
--- CTM and Positioning
-- @section CTM
--- Returns the current CTM.
-- This is the CTM being active just before inserting the PDF image.
--
-- Note that scaling of a PDF image can be done in two different ways:
--
-- * Using `pdf.setmatrix()`.
-- * Using options `width`, `height`, and `depth` of `\useimageresource`.
--
-- Both methods are used by LaTeX: The very first `scale` option of
-- `\includegraphics` is implemented using the second method while
-- all further `scale` options are implemented using the first method.
--
-- LuaTeX provides `pdf.getmatrix()` to get the CTM. But this works only
-- when using the first method for scaling. The second method of scaling
-- is not reachable by `pdf.getmatrix()`.
--
-- Therefore we need to catch the very first `scale` option of
-- `\includegraphics` manually, define the transformation matrix of this scaling
-- operation, and add it to the CTM. Eventually this calculated CTM can be used
-- to transform coordinate points given in any PDF annotation of this page.
--
-- This is the calculation of the CTM:
--
-- ⎡ s 0 0 ⎤ ⎡ a b 0 ⎤ ⎡ sa sb 0 ⎤
-- ⎢ 0 s 0 ⎥ ⎢ c d 0 ⎥ = ⎢ sc sd 0 ⎥
-- ⎣ 0 0 1 ⎦ ⎣ h v 1 ⎦ ⎣ h v 1 ⎦
--
-- a, b, c, d ... returned by `pdf.getmatrix()`
-- h, v ... returned by `pdf.getpos()`
-- s ... very first `scale` option of `\includegraphics`
--
-- **Note:** This implementation is flawed and doesn't work correctly
-- because `h` and `v` are the current TeX coordinates which do not
-- always coincide with the current PDF coordinates.
--
-- However, it seems to work correctly under following conditions:
--
-- * Using option `scale` of `\includegraphics` zero or more times.
-- * Using option `angle` of `\includegraphics` zero or one(!) time.
--
-- Everything else fails. Especially:
--
-- * Using options `width`, `height`, `x`, `y`, `origin`, ... of `\includegraphics`.
-- * Using `\scalebox`.
-- * Using `\rotatebox`.
--
-- @return CTM dictionary
function Page:getCTM()
local a, b, c, d = pdf.getmatrix()
local h, v = pdf.getpos()
h, v = self:sp2bp(h), self:sp2bp(v)
local s = self.GinKV.scale or 1
return { a = a*s, b = b*s,
c = c*s, d = d*s,
e = h, f = v }
end
--- Sets CTM.
-- @number a
-- @number b
-- @number c
-- @number d
-- @number e
-- @number f
function Page:makeCTM(a, b, c, d, e, f)
return {a = a, b = b, c = c, d = d, e = e, f = f}
end
--- Applies CTM on point `(x, y)`.
-- ⎡ a b 0 ⎤
-- [x y 1] ⎢ c d 0 ⎥ = [ax+cy+e bx+dy+f 1]
-- ⎣ e f 1 ⎦
-- @table ctm CTM
-- @number x X-coordinate
-- @number y Y-coordinate
-- @return Transformed x-coordinate
-- @return Transformed y-coordinate
function Page:applyCTM(ctm, x, y)
local xn = ctm.a * x + ctm.c * y + ctm.e
local yn = ctm.b * x + ctm.d * y + ctm.f
return xn, yn
end
--- Converts a pdfe rectangle into a lua table.
-- @pdfe rect Pdfe rectangle
-- @return Table
function Page:rect2tab(rect)
return {
['llx'] = rect[1],
['lly'] = rect[2],
['urx'] = rect[3],
['ury'] = rect[4],
}
end
--- Returns the MediaBox of the current PDF page.
-- @return Table (rectangle of mediabox)
function Page:getMediaBox()
local mediabox = pdfe.getpage(self.pdf, self.GinKV.page).MediaBox
return self:rect2tab(mediabox)
end
--- Returns a table to be used for creating TeX nodes.
-- @table mediabox Rectangle of mediabox
-- @table annotbox Rectangle of annotation
-- @return Table
function Page:getTeXPos(mediabox, annotbox)
local scale = self.scale or 1
local angle = self.angle or 0
angle = angle % 360
local phi = math.rad(angle)
local cosphi, sinphi = math.cos(phi), math.sin(phi)
if angle % 90 ~= 0 then
pkg.warning(
string.format(
'Warning: Rotation by %s degree not supported.', self.angle))
end
local x1 = annotbox.llx - mediabox.llx
local y1 = annotbox.lly - mediabox.lly
local x2 = annotbox.urx - mediabox.llx
local y2 = annotbox.ury - mediabox.lly
local mh = mediabox.ury - mediabox.lly
local mw = mediabox.urx - mediabox.llx
local L, nx1, nx2
L = 0
if angle == 0 then
nx1, ny1 = x1, y1
nx2, ny2 = x2, y2
elseif angle == 90 then
nx1, ny1 = -y2 + mh, x1
nx2, ny2 = -y1 + mh, x2
elseif angle == 180 then
nx1, ny1 = -x2 + mw, -y2 + mh
nx2, ny2 = -x1 + mw, -y1 + mh
elseif angle == 270 then
nx1, ny1 = y1, -x2 + mw
nx2, ny2 = y2, -x1 + mw
end
return {
['width'] = (nx2 - nx1) * scale,
['height'] = (ny2 - ny1) * scale,
['hshift'] = nx1 * scale,
['vshift'] = ny1 * scale,
}
end
--- Cache
-- @section Cache
--- Writes data to the cache.
-- @string key key
-- @param val value
function Page:writeToCache(key, val)
self.doc:writeToCache(key, val)
end
--- Reads data from the cache.
-- @string key key
-- @return Value
function Page:readFromCache(key)
return self.doc:readFromCache(key)
end
--- Returns data from the cache for page object with number `page_obj_old`.
-- @string key key
-- @number page_obj_old page object number
-- @return Value
function Page:readFromCacheWithPageObj(key, page_obj_old)
return self.doc:readFromCacheWithPageObj(key, page_obj_old)
end
--- Writes an object number of an annotation to the cache.
-- The object number is one from the existing (old) PDF file.
-- @number objnum object number
function Page:writeToCache_AnnotObjOld(objnum)
self.doc:writeToCache_AnnotObjOld(self.annotId, objnum)
end
--- Writes an object number of an annotation to the cache.
-- The object number is one from the newly created PDF file.
-- @number objnum object number
function Page:writeToCache_AnnotObjNew(objnum)
self.doc:writeToCache_AnnotObjNew(self.annotId, objnum)
end
--- Returns the new object number of an annotation from the cache.
-- The new object number corresponds to `annot_obj_old`
-- of the existing (old) PDF file.
-- @number annot_obj_old old annotation object number
-- @return New annotation object number
function Page:findFromCache_AnnotObjNew(annot_obj_old)
return self.doc:findFromCache_AnnotObjNew(annot_obj_old)
end
--- Caches all relevant data. To be called during TeX shipout.
function Page:cacheData()
self:writeToCache('ctm', self:getCTM())
self:writeToCache('filename', self.GinKV.filename)
self:writeToCache('page', self.GinKV.page)
self:writeToCache('page_obj_old', self:getPageObjNum(self.GinKV.page))
self:writeToCache('page_obj_new', pdf.getpageref(self.page))
end
--- Auxiliary
-- @section Auxiliary
--- Removes trailing and leading whitespace.
-- @string str String
-- @return String
function Page:trim(str)
if type(str) == 'string' then
return str:match("^%s*(.-)%s*$")
else
return str
end
end
--- Converts from `sp` (scaled points) to `bp` (big points).
-- @number num Number
-- @return Number
function Page:sp2bp(num)
return num / 65536 * 72 / 72.27
end
--- Converts from `bp` (big points) to `sp` (scaled points).
-- @number num Number
-- @return Number
function Page:bp2sp(num)
return num * 65536 / 72 * 72.27
end
return Page
|
--# assume global class CUSTOM_LORDS_MODEL
--# assume global class CUSTOM_LORDS_ATTRIBUTE_PANEL
--# assume global class CUSTOM_LORDS_TRAIT_FRAME
--# assume global class CUSTOM_LORDS_ART_PANEL
--# assume global class CUSTOM_LORDS_OPTIONS_FRAME
--# type global CUSTOM_LORDS_EVENT =
--# "LORD_TYPES_CHANGE" | "SELECTED_LORD_TYPE_CHANGE" | "SKILL_SETS_CHANGE" |
--# "SELECTED_SKILL_SET_CHANGE" | "AVAILABLE_TRAITS_CHANGE" | "SELECTED_TRAITS_CHANGE" |
--# "ATTRIBUTE_VALUE_CHANGE" | "SELECTED_ART_ID_VALUE_CHANGE"
--# assume global CLC_BETA: boolean |
ACF.RegisterWeaponClass("GL", {
Name = "Grenade Launcher",
Description = "Small and light, grenade launchers allow you to fire huge amounts of explosives into an area at the cost of poor accuracy and small magazine size.",
Sound = "acf_base/weapons/grenadelauncher.mp3",
Model = "models/launcher/40mmgl.mdl",
MuzzleFlash = "gl_muzzleflash_noscale",
DefaultAmmo = "HE",
IsScalable = true,
IsBoxed = true,
Mass = 101,
Spread = 0.28,
Cyclic = 250,
Round = {
MaxLength = 10,
PropLength = 1,
},
Preview = {
FOV = 75,
},
Caliber = {
Base = 40,
Min = 25,
Max = 40,
},
MagSize = {
Min = 80,
Max = 50,
},
MagReload = {
Min = 7.5,
Max = 10,
},
})
ACF.RegisterWeapon("40mmGL", "GL", {
Caliber = 40,
})
ACF.RegisterWeapon("40mmCL", "GL", {
Caliber = 40,
})
ACF.SetCustomAttachment("models/launcher/40mmgl.mdl", "muzzle", Vector(19), Angle(0, 0, -180))
ACF.AddHitboxes("models/launcher/40mmgl.mdl", {
Breech = {
Pos = Vector(0, 0, -1.25),
Scale = Vector(20, 5, 6),
Sensitive = true
},
Barrel = {
Pos = Vector(14, 0, 0.1),
Scale = Vector(12, 2, 2)
}
})
|
--[[
this file is going to be for mining out entire tunnels/mineshafts, in 64*64/4*L/R format
]]--
--[[
2 large chests are behind the starting position of the turtle.
--]]
--[[
==TODO=={
* torch and fuel source definition
}
]]--
--</headers>
function autodetect
sides = {"front","back","left","right","top","bottom"}
local i
for i=1,6 do
testside = sides[i]
if peripheral.isPresent(testside)
return testside
end
end
end
length = tonumber(arg[1])
./tunnel_erentar length --mine main shaft
function sidexcavate
for i=1,(length/4) do
-- first branch to left --
turtle.turnLeft() --
turtle.turnLeft() --
turtle.forward() --
turtle.forward() --
turtle.turnLeft --
./tunnel_erentar 64 --
-- </> --
end }
end
sidexcavate()
turtle.turnLeft()
turtle.forward()
turtle.turnRight() --turtle is now at the middle of the last tunnel
turtle.forward()
turtle.forward()
turtle.forward()
sidexcavate()
|
local mod = DBM:NewMod(1836, "DBM-Party-Legion", 11, 860)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 17077 $"):sub(12, -3))
mod:SetCreatureID(114462)
mod:SetEncounterID(1964)
mod:SetZone()
--mod:SetUsedIcons(1)
--mod:SetHotfixNoticeRev(14922)
--mod.respawnTime = 30
mod.noNormal = true
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_SUCCESS 234416",
"SPELL_AURA_APPLIED 227254",
"SPELL_AURA_REMOVED 227254",
"SPELL_PERIODIC_DAMAGE 227465",
"SPELL_PERIODIC_MISSED 227465",
"UNIT_SPELLCAST_SUCCEEDED boss1"
)
local warnAdds = mod:NewSpellAnnounce(227267, 2)--if not cast too often make special warning?
local warnEvo = mod:NewSpellAnnounce(227254, 1)
local warnEvoOver = mod:NewEndAnnounce(227254, 2)
local specWarnPowerDischarge = mod:NewSpecialWarningMove(227465, nil, nil, nil, 1, 2)
local timerSummonAddCD = mod:NewNextTimer(9.7, 227267, nil, nil, nil, 1)
local timerPowerDischargeCD = mod:NewCDTimer(12.2, 227279, nil, nil, nil, 3)
local timerEvoCD = mod:NewNextTimer(70, 227254, nil, nil, nil, 6)
local timerEvo = mod:NewBuffActiveTimer(20, 227254, nil, nil, nil, 6)
--local berserkTimer = mod:NewBerserkTimer(300)
local countdownEvo = mod:NewCountdown(70, 227254)
function mod:OnCombatStart(delay)
timerSummonAddCD:Start(6-delay)
timerPowerDischargeCD:Start(13.5)
timerEvoCD:Start(68-delay)
countdownEvo:Start(68)
end
function mod:OnCombatEnd()
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 234416 then
warnAdds:Show()
timerSummonAddCD:Start()
end
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if spellId == 227254 then
timerSummonAddCD:Stop()
timerPowerDischargeCD:Stop()
warnEvo:Show()
timerEvo:Start()
countdownEvo:Start(20)
end
end
function mod:SPELL_AURA_REMOVED(args)
local spellId = args.spellId
if spellId == 227254 then
warnEvoOver:Show()
timerEvoCD:Start()
countdownEvo:Start()
end
end
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 227465 and destGUID == UnitGUID("player") and self:AntiSpam(2, 1) then
specWarnPowerDischarge:Show()
specWarnPowerDischarge:Play("runaway")
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, spellGUID)
local spellId = tonumber(select(5, strsplit("-", spellGUID)), 10)
if spellId == 227278 then
timerPowerDischargeCD:Start()
end
end
|
package.path = package.path .. ";lualinqmutable.lua"
package.path = package.path .. ";lualinq.lua"
local lualinqmutable = require ("lualinqmutable")
local lualinq = require ("lualinq")
local array = {}
local dictionary = {
a = {
{ name="john", surname="snow" },
{ name="elizabeth", surname="taylor" },
},
b = {
{ name="melvin", surname="kelvin" },
},
c = {
d = {
{ name="edward", surname="stark" },
}
}
}
local charset = {} do -- [0-9a-zA-Z]
for c = 48, 57 do table.insert(charset, string.char(c)) end
for c = 65, 90 do table.insert(charset, string.char(c)) end
for c = 97, 122 do table.insert(charset, string.char(c)) end
end
local function randomString(length)
if not length or length <= 0 then return '' end
math.randomseed(os.clock()^5)
return randomString(length - 1) .. charset[math.random(1, #charset)]
end
local _insert = table.insert
local _random = math.random
math.randomseed(os.time())
for n = 1, 100000 do
_insert(array, _random(100))
if n < 25000 then
_insert(dictionary.a, { name = randomString(5), surname = randomString(7)})
elseif n < 45000 then
_insert(dictionary.b, { name = randomString(7), surname = randomString(9)})
else
_insert(dictionary.c.d, { name = randomString(4), surname = randomString(6)})
end
end
local function profileCall(name, expression)
local time = os.clock()
expression()
time = os.clock() - time
print((name .. " results: %.3f seconds"):format(time))
end
profileCall("lualinq.from:where:distinct:toArray", function()
local r = lualinq.from(array)
:where(function(n) return n >= 50 end)
:distinct()
:toArray()
end)
profileCall("lualinqmutable.from:where:distinct:toArray", function()
local r = lualinqmutable.from(array)
:where(function(n) return n >= 50 end)
:distinct()
:toArray()
end)
profileCall("lualinq.from:selectMany(from:concat:where:select:toArray):toArray", function()
local r = lualinq.from(dictionary)
:selectMany(function(v)
return lualinq.from(v.value)
:concat(lualinq.from(v.value.d))
:where(function(v) return v.surname ~= nil end)
:select(function(v) return v.name .. " " .. v.surname end)
:toArray()
end)
:toArray()
end)
profileCall("lualinqmutable.from:selectMany(from:concat:where:select:toArray):toArray", function()
local r = lualinqmutable.from(dictionary)
:selectMany(function(v)
return lualinqmutable.from(v.value)
:concat(lualinqmutable.from(v.value.d))
:where(function(v) return v.surname ~= nil end)
:select(function(v) return v.name .. " " .. v.surname end)
:toArray()
end)
:toArray()
end)
|
local swayboi = false
local camerabeat = false
function update (elapsed)
local currentBeat = (songPos / 1000)*(bpm/60)
if lockzoom then
setCamZoom(1)
end
if swayboi then
for i=0,7 do
setActorX(_G['defaultStrum'..i..'X'] + 8 * math.sin((currentBeat + i*0.25) * math.pi), i)
setActorY(_G['defaultStrum'..i..'Y'] + 3 * math.cos((currentBeat + i*0.50) * math.pi), i)
end
end
end
function beatHit (beat)
if camerabeat then
setCamZoom(0.1)
end
end
function stepHit (step)
if step == 1 then
end
if step == 127 then
swayboi = true
camerabeat = true
for i=0,7 do
tweenPosXAngle(i, _G['defaultStrum'..i..'X'], 0, 0.6, 'setDefault')
setActorY(_G['defaultStrum'..i..'Y'],i)
end
end
if step == 639 then
camerabeat = false
swayboi = false
end
if step == 751 then
camerabeat = true
swayboi = true
end
end |
require("advancedLua")
local component = require("component")
local computer = require("computer")
local image = require("image")
local buffer = require("doubleBuffering")
local GUI = require("GUI")
local fs = require("filesystem")
local unicode = require("unicode")
local MineOSPaths = require("MineOSPaths")
local MineOSCore = require("MineOSCore")
local MineOSInterface = require("MineOSInterface")
----------------------------------------------------------------------------------------------------------------
local resourcesPath = MineOSCore.getCurrentScriptDirectory()
local modulesPath = resourcesPath .. "Modules/"
local localization = MineOSCore.getLocalization(resourcesPath .. "Localizations/")
local mainContainer, window = MineOSInterface.addWindow(GUI.tabbedWindow(1, 1, 80, 25))
----------------------------------------------------------------------------------------------------------------
window.contentContainer = window:addChild(GUI.container(1, 4, window.width, window.height - 3))
local function loadModules()
local fileList = fs.sortedList(modulesPath, "name", false)
for i = 1, #fileList do
local loadedFile, reason = loadfile(modulesPath .. fileList[i])
if loadedFile then
local pcallSuccess, reason = pcall(loadedFile, mainContainer, window, localization)
if pcallSuccess then
window.tabBar:addItem(reason.name).onTouch = function()
reason.onTouch()
MineOSInterface.mainContainer:drawOnScreen()
end
else
error("Failed to call loaded module \"" .. tostring(fileList[i]) .. "\": " .. tostring(reason))
end
else
error("Failed to load module \"" .. tostring(fileList[i]) .. "\": " .. tostring(reason))
end
end
end
window.onResize = function(width, height)
window.tabBar.width = width
window.backgroundPanel.width = width
window.backgroundPanel.height = height - 3
window.contentContainer.width = width
window.contentContainer.height = window.backgroundPanel.height
window.tabBar:getItem(window.tabBar.selectedItem).onTouch()
end
----------------------------------------------------------------------------------------------------------------
loadModules()
window.onResize(80, 25)
|
-- MIT License
--
-- Copyright (c) 2020 moo-sama
--
-- 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 PATH = (...):gsub("%.init$", "")
local O = require(PATH .. '.oop')
local ucoroutine = require(PATH .. '.ucoroutine')
local current_timeline
-- Error Handling --
local ucoroutine_traceback = ucoroutine.traceback
function ucoroutine.traceback()
if current_timeline then return ucoroutine_traceback(1)
else return ucoroutine_traceback(3) end
end
function ucoroutine.errorevent()
if current_timeline then
current_timeline._status = "Dead"
while current_timeline._caller do
local caller = current_timeline._caller
current_timeline._caller = nil
current_timeline = caller
end
current_timeline = nil
end
end
local function tl_assert(test, level, msg)
if type(level) == "string" then
msg = level
level = 0
end
if not test then
error(msg, level + 1)
end
return test
end
-- Timeline --
TL = O.Class("Timeline", function(C, MT)
C._status = "Suspended"
C._is_paused = false
MT.Event = { }
MT.Trigger = { }
function C:_yield () coroutine.yield() end
function C:_resume()
if coroutine.status(self._coroutine) ~= "dead" then
return ucoroutine.resume(self._coroutine, unpack(self._args))
end
return true
end
function C:Step()
if self._status ~= "Dead" and not self._is_paused then
self._caller = current_timeline
current_timeline = self
local branch_count = #self._branches
self._status = "Running"
self:_resume()
self._status = "Delegating"
for i = 1, branch_count do
self._branches[i]:Step()
end
for i = #self._branches, 1, -1 do
if self._branches[i]:GetStatus() == "Dead" then
table.remove(self._branches, i)
end
end
if #self._branches == 0 and coroutine.status(self._coroutine) == "dead" then
self._status = "Dead"
else
self._status = "Suspended"
end
current_timeline = self._caller
self._caller = nil
end
return self:IsDone()
end
function C:IsRunning () return self._status == "Running" or self._status == "Delegating" end
function C:IsDone () return self._status == "Dead" end
function C:GetStatus () return self._status end
function C:HasResults() return #self._results > 0 end
function C:GetResults() return unpack(self._results) end
function C:Branches() return ipairs(self._branches) end
function C:Pause()
self._is_paused = true
if self:IsRunning() then
TL.Step()
end
end
function C:Unpause()
self._is_paused = false
end
function C:IsPaused() return self._is_paused end
function C:Branch(run, ...)
local b = TL(run, ...)
self._branches[#self._branches + 1] = b
return b
end
function C:KillBranches()
for i = 1, #self._branches do
self._branches[i]:Die()
self._branches[i] = nil
end
end
function C:Die()
self:KillBranches()
if self:IsRunning() then
self._status = "Dead"
TL.Step()
else
self._status = "Dead"
end
end
return function(self, run, ...)
if type(run) ~= "function" then
local success = false
if type(run) == "table" then
success = getmetatable(run).__call
end
assert(success, "attempt to pass uncallable value to timeline constructor")
end
self._coroutine = ucoroutine.create(run)
self._args = { ... }
self._results = { }
self._branches = { }
end
end)
package.loaded['timeline'] = TL
-- Utility --
local delta_time = 0
local frame = 0
local time = 0
function TL.GetDT () return delta_time end
function TL.GetFrame() return frame end
function TL.GetTime () return time end
local loop_count = 0
function TL.CheckInfiniteLoop(...)
loop_count = loop_count + 1
if loop_count > 100000 then
error("infinite loop detected, try calling TL.Step()")
end
if select("#", ...) == 0 then return true
else return ... end
end
local background_timelines = { }
function TL.Do(run, ...)
local tl = TL(run, ...)
background_timelines[#background_timelines + 1] = tl
return tl
end
function TL.Require(modl)
local path = modl:gsub("%.", "/")
local chunk
for searcher in package.path:gmatch("([^;]*);?") do
local cpath = searcher:gsub("?", path)
chunk = loadfile(cpath)
if chunk then break end
end
if not chunk then
chunk = loadfile("../" .. path .. ".lua")
end
assert(chunk, "cannot find module '" .. modl .. "'")
return TL(chunk, modl)
end
-- Timeline Peeper --
local TimelinePeeper = O.Class("TimelinePeeper", TL, function(C)
local _PEEK_FINISHED = { }
function C:_yield()
error(_PEEK_FINISHED)
end
local function peep_coalesce(tl, success, ...)
tl:KillBranches()
if not success then
if ... == _PEEK_FINISHED then
tl._did_pass = false
return
else
error(tl, ...)
end
end
tl._did_pass = true
for i = 1, select("#", ...) do tl._results[i] = select(i, ...) end
end
function C:_set(run, ...)
for i = 1, #self._results do self._results[i] = nil end
for i = 1, #self._args do self._args [i] = nil end
for i = 1, select("#", ...) do self._args [i] = select(i, ...) end
self._run = run
self._status = "Suspended"
self._is_finished = false
end
return function(self)
self._coroutine = ucoroutine.create(function()
while true do
coroutine.yield()
peep_coalesce(self, xpcall(self._run, debug.traceback, unpack(self._args)))
end
end)
self._args = { }
self._results = { }
self._branches = { }
end
end)
local peeper_stack = { TimelinePeeper(), _index = 0 }
local function get_peeper()
return peeper_stack[peeper_stack._index + 1]
end
function TL.DidPeekTrigger() return get_peeper()._did_pass end
function TL.GetPeekResults() return get_peeper():GetResults() end
function TL.Peek(run, ...)
peeper_stack._index = peeper_stack._index + 1
if not peeper_stack[peeper_stack._index] then
peeper_stack[peeper_stack._index] = TimelinePeeper()
end
local peeper = peeper_stack[peeper_stack._index]
peeper:_set(run, ...)
peeper:Step()
peeper_stack._index = peeper_stack._index - 1
return TL.DidPeekTrigger(), TL.GetPeekResults()
end
function TL.Assert(msg)
assert(current_timeline, msg or "cannot call this function outside of a Timeline")
end
function TL.Step()
TL.Event.Step()
end
function TL.Branch(...)
return TL.Event.Branch(...)
end
function TL.Current()
return current_timeline
end
-- Events --
function TL.Event.Step()
TL.Assert()
TL.Current():_yield()
end
function TL.Event.Kill(n)
n = n or 0
TL.Assert()
assert(n <= 0, "TL.Event.Kill only accepts negative numbers or 0")
local t = current_timeline
while n > 0 do
t = assert(t._caller, "attempt to kill a timeline outside of the stack")
n = n - 1
end
t:Die()
end
function TL.Event.Die()
TL.Assert()
TL.Current():Die()
end
function TL.Event.Branch(run, ...)
TL.Assert()
local current = TL.Current()
local branch = current:Branch(run, ...)
branch:Step()
return branch
end
function TL.Event.Wait(t)
local t0 = TL.GetTime()
while TL.GetTime() - t0 < t do
TL.CheckInfiniteLoop()
TL.Step()
end
return t
end
function TL.Event.Suspend(steps)
local i = 0
while i <= steps do
TL.Step()
i = i + 1
end
end
function TL.Trigger.OnTimelineDone(t)
assert(t ~= TL.Current(), "attempt to wait for the currently running timeline")
while not t:IsDone() do TL.Step() end
return t:GetResults()
end
function TL.Trigger.OnBranchesDone(t)
t = t or TL.Current()
while next(t._branches) do TL.Step() end
end
-- Input Events --
local function new_on_trigger(name, narg)
return function(...)
while true do
for a, b, c, d in TL.Trigger[name]("All") do
local arg = select(narg, a, b, c, d)
for i = 1, select("#", ...) do
if arg == select(i, ...) then
return arg
end
end
end
TL.Step()
end
end
end
TL.Trigger.OnKeyPress = new_on_trigger("KeyPressed", 2)
TL.Trigger.OnMousePress = new_on_trigger("MousePressed", 3)
TL.Trigger.OnKeyRelease = new_on_trigger("KeyReleased", 2)
TL.Trigger.OnMouseRelease = new_on_trigger("MouseReleased", 3)
local function new_on_trigger_joystick(name, narg)
return function(joystick, ...)
while true do
for jstick, b, c, d in TL.Trigger[name]("All") do
local arg = select(narg, jstick, b, c, d)
for i = 1, select("#", ...) do
if arg == select(i, ...) then
return arg
end
end
end
end
end
end
TL.Trigger.OnGamepadPress = new_on_trigger_joystick("GamepadPressed", 2)
TL.Trigger.OnJoystickPress = new_on_trigger_joystick("JoystickPressed", 2)
TL.Trigger.OnGamepadRelease = new_on_trigger_joystick("GamepadReleased", 2)
TL.Trigger.OnJoystickRelease = new_on_trigger_joystick("JoystickReleased", 2)
-- LOVE Events --
local inputs = { Size = 0 }
local function get_next_input(list)
list.Size = list.Size + 1
if not list[list.Size] then
list[list.Size] = { Type = nil, nil, nil, nil }
end
return list[list.Size]
end
local function push_input_trigger(typ, ...)
local input = get_next_input(inputs)
input.Type = typ
for i = #input, 1, -1 do input[i] = nil end
for i = 1, select("#", ...) do input[i] = select(i, ...) end
end
local triggers = { "KeyPressed", "KeyReleased", "MousePressed", "MouseReleased", "MouseMoved",
"WheelMoved", "TouchPressed", "TouchReleased", "TouchMoved", "GamepadPressed",
"GamepadReleased", "GamepadAxis", "JoystickPressed", "JoystickReleased", "JoystickAxis",
"JoystickHat", "JoystickAdded", "JoystickRemoved", "TextInput", "Visible", "Resize",
"MouseFocus", "Focus" }
local function new_input_trigger(names)
if type(names) == "string" then names = { names } end
local function iterate()
for j = 1, #names do
for i = 1, inputs.Size do
local input = inputs[i]
if input.Type == names[j] then
if #names > 1 then coroutine.yield(names[j], unpack(input))
else coroutine.yield(unpack(input)) end
end
end
end
end
local function trigger(all)
while TL.CheckInfiniteLoop() do
for j = 1, #names do
for i = inputs.Size, 1, -1 do
local input = inputs[i]
if input.Type == names[j] then
if all == "All" then return ucoroutine.wrap(iterate)
else
if #names > 1 then return names[j], unpack(input)
else return unpack(input) end
end
end
end
end
TL.Step()
end
end
return trigger
end
do
for i = 1, #triggers do
TL[triggers[i]:lower()] = function(...)
push_input_trigger(triggers[i], ...)
end
TL.Trigger[triggers[i]] = new_input_trigger(triggers[i])
end
TL.Trigger. MouseActivity = new_input_trigger({ "MousePressed", "MouseReleased", "MouseMoved",
"WheelMoved" })
TL.Trigger. WindowActivity = new_input_trigger({ "MouseFocus", "Focus", "Resize", "Visible" })
TL.Trigger.JoystickActivity = new_input_trigger({ "JoystickPressed", "JoystickReleased",
"JoystickAdded", "JoystickRemoved",
"JoystickAxis", "JoystickHat" })
TL.Trigger. GamepadActivity = new_input_trigger({ "GamepadPressed", "GamepadReleased",
"GamepadAxis" })
TL.Trigger. KeyActivity = new_input_trigger({ "KeyPressed", "KeyReleased", "TextInput" })
end
function TL.update(dt)
for i = 1, #background_timelines do
background_timelines[i]:Step()
end
for i = #background_timelines, 1, -1 do
if background_timelines[i]:GetStatus() == "Dead" then
table.remove(background_timelines, i)
end
end
time = time + dt
delta_time = dt
frame = frame + 1
inputs.Size = 0
loop_count = 0
end
function TL.Attach()
for i = 1, #triggers do
local lname = triggers[i]:lower()
local old = love[lname]
if old then
love[lname] = function(...)
TL[lname](...)
old(...)
end
else
love[lname] = TL[lname]
end
end
local love_update = love.update or function()end
function love.update(...)
love_update(...)
TL.update(...)
end
end
return TL |
--[[!
\file
\brief Este es un módulo que da soporta a la orientación a objetos en lua.
(polimorfismo y herencia).
Ejemplos.
\code
-- Crear una clase foo y una instancia de esta.
foo = class();
local newInstance = foo();
\endcode
\code
-- Lo mismo que el anterior ejemplo pero indicando un inicializador de clase...
foo = class();
function foo:init(...) print("inicializando instancia de foo con los valores " .. table.concat(...,' '); end;
local newInstance = foo(1, 2, 3, 4);
\endcode
\code
-- Ahora creamos una clase bar que herede de foo.
-- Si no creamos un inicializador para esta clase, habrá uno por defecto que inicializará la
superclase (llamará a foo.init)
bar = class(foo);
bar(); -- output: inicializando instancia de foo...
\endcode
\code
-- Si especificamos un inicializador de clase, tenemos que preocuparnos de inicializar la
-- superclase.
bar = class(foo);
function bar:init()
self:super(1, 2, 3, 4); -- output: inicializando instancia de foo con los valores 1 2 3 4
print("inicializando instancia de bar");
end;
\endcode
-- Para comprobar si una variable es una clase, se puede usar la función isvalidclass
\code
bar = class();
print(isvalidclass(bar));
\endcode
-- Podemos comprobar si un objeto es una instanciación de una clase.
\code
bar = class();
instance = bar();
print(instance:isinstanceof(bar));
\endcode
]]
loadModule("util/assertutils");
function class(BaseClass)
localizedAssert((BaseClass == nil) or isvalidclass(BaseClass), "Invalid base class", 2);
local newClass = {};
local newClassMetatable = {};
newClass.__index = newClass;
-- Esto es para proteger a las instancias de la nueva clase, que no se les pueda
-- asignar nuevas metatablas
newClass.__metatable = newClass;
if BaseClass then
newClassMetatable.__index = BaseClass;
newClass.__base = BaseClass;
end;
-- Proteger a la nueva clase para que no se pueda establecer una nueva
-- metatabla y al mismo tiempo, que getmetatable(newClass) == newClassMetatable
newClassMetatable.__metatable = newClassMetatable;
-- "Constructor" de clase.
newClassMetatable.__call =
function(t, ...)
local newInstance = {};
setmetatable(newInstance, t);
-- Inicializar la nueva instancia.
newInstance:init(...);
return newInstance;
end;
-- Inicializador de una instancia de la clase por defecto.
if not newClass.__base then
newClass.init =
function(this, ...)
end;
else
newClass.init =
function(this, ...)
--Inicializar la superclase (si hereda de alguna)
newClass.super();
end;
end;
-- Inicializador de superclase.
newClass.super =
function(this, ...)
local baseClass = localizedAssert(newClass.__base, "There is no superclass", 2);
baseClass.init(this, ...);
end;
-- Clonador de instancias por defecto.
newClass.clone =
function(this, ...)
local other = {};
-- hacer una copia de los valores de la instancia a la tabla
for index, value in pairs(this) do other[index] = value; end;
setmetatable(other, newClass);
-- no hace falta invocar al constructor.
return other;
end;
-- Comprobar si un objeto es una instancia de una clase heredada por esta.
newClass.isinstanceof =
function(this, otherClass)
localizedAssert(type(otherClass) == "table", "Invalid class", 2);
local theClass = newClass;
while (theClass ~= otherClass) and theClass.__base do
theClass = theClass.__base;
end;
return theClass == otherClass;
end;
setmetatable(newClass, newClassMetatable);
return newClass;
end;
--[[!
@return Devuelve un valor booleano indicando si la variable pasada como parámetro es
una clase válida (instanciable, inicializable y clonable)
]]
function isvalidclass(class)
return (type(class)=="table") and getmetatable(class) and
(type(getmetatable(class).__call)=="function") and (type(class.init)=="function") and
(type(class.super)=="function") and (type(class.clone)=="function") and
(type(class.isinstanceof)=="function");
end;
--[[!
@return Devuelve un valor booleano indicando si la variable pasada como parámetro es
un objeto válido; Es una instancia de una clase válida.
]]
function isvalidobject(object)
return getmetatable(object) and isvalidclass(getmetatable(object));
end;
--[[!
@return Devuelve un valor booleano indicando si este objeto es un objeto válido y es una
instancia de la clase indicada o de un clase que hereda de esta.
]]
function isinstanceof(object, class)
return isvalidobject(object) and object:isinstanceof(class);
end;
--[[!
Comprueba si un valor hace referencia a una clase.
@param funcname Es el nombre de la función.
@param level Especifíca la posición del error en la pila de llamadas
@param value Es la variable que se quiere verificar si es una clase valida.
@param argnum Es el cardinal del argumento
]]
function checkIsClass(funcname, level, value, argnum)
localizedAssert((type(funcname) == "string") and (type(level) == "number") and (type(argnum) == "number") and (argnum > 0),
"Bad arguments to \"checkIsClass\"", level);
if not isvalidclass(value) then
error("Argument mismatch in function \"" .. funcname .. "\" at argument " .. argnum .. "; class expected, but got " .. tostring(value), level+1);
end;
end;
--[[!
Comprueba si un valor hace referencia a una instancia de una clase.
@param funcname Es el nombre de la función.
@param level Especifíca la posición del error en la pila de llamadas
@param value Es la variable que se quiere verificar si es un objeto válido.
@param argnum Es el cardinal del argumento
]]
function checkIsObject(funcname, level, value, argnum)
localizedAssert((type(funcname) == "string") and (type(level) == "number") and (type(argnum) == "number") and (argnum > 0),
"Bad arguments to \"checkIsObject\"", level);
if not isvalidobject(value) then
error("Argument mismatch in function \"" .. funcname .. "\" at argument " .. argnum .. "; object expected, but got " .. tostring(value), level+1);
end;
end;
--[[!
Comprueba si un valor hace referencia a una instancia de la clase indicada, o es una
instancia de una clase que hereda de esta.
@param funcname Es el nombre de la función.
@param level Especifíca la posición del error en la pila de llamadas
@param value Es la variable que se quiere verificar si es un objeto válido y es una instancia de la
clase.
@param argnum Es el cardinal del argumento
@param class Es la clase.
@param classname Es el nombre de la clase (para añadir información adicional en caso de error)
]]
function checkIsInstanceOf(funcname, level, value, argnum, class, classname)
localizedAssert((type(funcname) == "string") and (type(level) == "number") and (type(argnum) == "number") and (argnum > 0) and isvalidclass(class) and (type(classname) == "string"),
"Bad arguments to \"checkIsInstanceOf\"", level);
if not isinstanceof(value, class) then
error("Argument mismatch in function \"" .. funcname .. "\" at argument " .. argnum .. "; an instance of " .. classname .. " class expected, but got " .. tostring(value), level+1);
end;
end;
|
local M = {}
function M.setup()
-- Duh.
vim.cmd[[colorscheme tokyonight]]
end
return M
|
local core = require 'core.completion'
local files = require 'files'
local catch = require 'catch'
EXISTS = {'EXISTS'}
local function eq(a, b)
if a == EXISTS and b ~= nil then
return true
end
local tp1, tp2 = type(a), type(b)
if tp1 ~= tp2 then
return false
end
if tp1 == 'table' then
local mark = {}
for k in pairs(a) do
if not eq(a[k], b[k]) then
return false
end
mark[k] = true
end
for k in pairs(b) do
if not mark[k] then
return false
end
end
return true
end
return a == b
end
local function include(a, b)
if a == EXISTS and b ~= nil then
return true
end
local tp1, tp2 = type(a), type(b)
if tp1 ~= tp2 then
return false
end
if tp1 == 'table' then
for k in pairs(a) do
if not eq(a[k], b[k]) then
return false
end
end
return true
end
return a == b
end
rawset(_G, 'TEST', true)
Cared = {
['label'] = true,
['kind'] = true,
['textEdit'] = true,
['additionalTextEdits'] = true,
['deprecated'] = true,
}
IgnoreFunction = false
ContinueTyping = false
function TEST(script)
return function (expect)
---@diagnostic disable: await-in-sync
local newScript, catched = catch(script, '?')
files.setText('', newScript)
local inputPos = catched['?'][1][1]
if ContinueTyping then
local triggerCharacter = script:sub(inputPos - 1, inputPos - 1)
core.completion('', inputPos, triggerCharacter)
end
local triggerCharacter = script:sub(inputPos, inputPos)
local result = core.completion('', inputPos, triggerCharacter)
if not expect then
assert(result == nil)
return
end
assert(result ~= nil)
result.enableCommon = nil
for _, item in ipairs(result) do
if item.id then
local r = core.resolve(item.id)
for k, v in pairs(r or {}) do
item[k] = v
end
end
for k in pairs(item) do
if not Cared[k] then
item[k] = nil
end
end
if item.description then
item.description = tostring(item.description)
end
end
if IgnoreFunction then
for i = #result, 1, -1 do
local item = result[i]
if item.label:find '%('
and not item.label:find 'function' then
result[i] = result[#result]
result[#result] = nil
end
end
end
assert(result)
result.complete = nil
if expect.include then
expect.include = nil
assert(include(expect, result))
else
assert(eq(expect, result))
end
files.remove('')
end
end
require 'completion.common'
require 'completion.continue'
|
local task = redis.call('LPOP', KEYS[1])
if not task then
return nil
end
local task_key = string.format("%s:active:%s:%s:%s", ARGV[1], ARGV[2], ARGV[3], task)
redis.pcall('SADD', KEYS[2], task_key)
redis.pcall('SET',
task_key,
task,
"EX", ARGV[4])
return task
|
-------------------------------------------------------------------------------
-- Mob Framework Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allow to pretend you have written it.
--
--! @file data_storage.lua
--! @brief generic functions used in many different places
--! @copyright Sapier
--! @author Sapier
--! @date 2013-02-04
--!
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
--! @defgroup gen_func Generic functions
--! @brief functions for various tasks
--! @ingroup framework_int
--! @{
-------------------------------------------------------------------------------
-- name: mobf_global_data_store(value)
--
--! @brief save data and return unique identifier
--
--! @param value to save
--
--! @return unique identifier
-------------------------------------------------------------------------------
local mobf_global_data_identifier = 0
local mobf_global_data = {}
mobf_global_data.cleanup_index = 0
mobf_global_data.last_cleanup = mobf_get_current_time()
function mobf_global_data_store(value)
local current_id = mobf_global_data_identifier
mobf_global_data_identifier = mobf_global_data_identifier + 1
mobf_global_data[current_id] = {
value = value,
added = mobf_get_current_time(),
}
return current_id
end
-------------------------------------------------------------------------------
-- name: mobf_global_data_store(value)
--
--! @brief pop data from global store
--
--! @param id to pop
--
--! @return stored value
-------------------------------------------------------------------------------
function mobf_global_data_get(id)
local dataid = tonumber(id)
if dataid == nil or
mobf_global_data[dataid] == nil then
dbg_mobf.generic_lvl1("MOBF: data not found, id: " .. dump(dataid))
return nil
end
local retval = mobf_global_data[dataid].value
mobf_global_data[dataid] = nil
return retval
end
-------------------------------------------------------------------------------
-- name: mobf_global_data_cleanup()
--
--! @brief periodic cleanup handler
--
-------------------------------------------------------------------------------
function mobf_global_data_cleanup()
if mobf_global_data.last_cleanup + 500 <
mobf_get_current_time() then
for i=1,50,1 do
if mobf_global_data[mobf_global_data.cleanup_index] ~= nil then
if mobf_global_data[mobf_global_data.cleanup_index].added <
mobf_get_current_time() - 300 then
mobf_global_data[mobf_global_data.cleanup_index] = nil
end
mobf_global_data.cleanup_index = mobf_global_data.cleanup_index +1
if mobf_global_data.cleanup_index > #mobf_global_data then
mobf_global_data.cleanup_index = 0
break
end
end
end
mobf_global_data.last_cleanup = mobf_get_current_time()
end
end
--!@} |
---------------------------------------------------
-- Lunar Cry
-- Fenrir gives accuracy and evasion down status effects to target.
---------------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------------
function onMobSkillCheck(target, mob, skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local moon = VanadielMoonPhase()
local buffvalue = 1
if (moon > 90) then
buffvalue = 31
elseif (moon > 75) then
buffvalue = 26
elseif (moon > 60) then
buffvalue = 21
elseif (moon > 40) then
buffvalue = 16
elseif (moon > 25) then
buffvalue = 11
elseif (moon > 10) then
buffvalue = 6
end
target:addStatusEffect(tpz.effect.ACCURACY_DOWN, buffvalue, 0, 180)
target:addStatusEffect(tpz.effect.EVASION_DOWN, 32-buffvalue, 0, 180)
skill:setMsg(tpz.msg.basic.SKILL_ENFEEB_2)
return 0
end
|
--------------------------------
-- @module Layer
-- @extend Node
-- @parent_module cc
--------------------------------
-- @function [parent=#Layer] create
-- @param self
-- @return Layer#Layer ret (return value: cc.Layer)
--------------------------------
-- @function [parent=#Layer] getDescription
-- @param self
-- @return string#string ret (return value: string)
--- @rdcklinux
--------------------------------
-- @function [parent=#Layer] addChild
-- @param self
-- @param Sprite#Sprite sprite, Sprite
--------------------------------
-- @function [parent=#Layer] getPosition
-- @param self
-- @return { x, y }
--------------------------------
-- @function [parent=#Layer] setPosition
-- @param self
-- @param #number x
-- @param #number y
--------------------------------
-- @function [parent=#Layer] registerScriptHandler
-- @param self
-- @param #function NodeEvent
--------------------------------
-- @function [parent=#Layer] getEventDispatcher
-- @param self
-- @return EventDispatcher#EventDispatcher EventDispatcher
return nil
|
-- Treesitter
-- An advanced, incremental alternative to syntax parsing for programming
-- languages.
require "nvim-treesitter.configs".setup {
ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers), or a list of languages
-- ignore_install = {"javascript"}, -- List of parsers to ignore installing
highlight = {
enable = true, -- false will disable the whole extension
-- disable = {"c", "rust"}, -- list of language that will be disabled
-- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- Using this option may slow down your editor, and you may see some duplicate highlights.
-- Instead of true it can also be a list of languages
additional_vim_regex_highlighting = true
}
}
-- Add Org Mode module for Tree Sitter
local parser_config = require "nvim-treesitter.parsers".get_parser_configs()
parser_config.org = {
install_info = {
url = "https://github.com/milisims/tree-sitter-org",
files = {"src/parser.c", "src/scanner.cc"}
},
filetype = "org"
}
|
minetest.register_chatcommand("protection_memoize_clear", {
description = "Clears the protection cache",
privs = { server = true },
func = function()
protection_memoize.invalidate_all()
return true, "Invalidated protection cache"
end
})
minetest.register_chatcommand("protection_memoize_enable", {
description = "Enables the protection cache",
privs = { server = true },
func = function()
protection_memoize.enabled = true
return true, "protection memoization enabled"
end
})
minetest.register_chatcommand("protection_memoize_disable", {
description = "Disables the protection cache",
privs = { server = true },
func = function()
protection_memoize.enabled = false
return true, "protection memoization disabled"
end
})
|
music = "shyzu.ogg"
function start()
out = Portal:new{x=2, y=6}
female = Object:new{x=2, y=3, anim_set="shyzu_female", person=true, direction=DIRECTION_SOUTH}
end
function stop()
end
function update(step)
if (out:update()) then
change_areas("shyzu", 8, 16, DIRECTION_SOUTH)
end
end
function activate(activator, activated)
if (activated == female.id) then
local _d = getObjectDirection(female.id)
setObjectDirection(female.id, player_dir(female))
doDialogue("Female: Ages ago a meteor landed where this village now stands...\nFemale: Something in its makeup has kept evil away to this day.\n", true)
setObjectDirection(female.id, _d)
end
end
function collide(id1, id2)
end
|
--
-- DICOM Web Viewer (DWV) lua script for integration in a Conquest PACS server.
--
-- Usage:
-- 1. copy this file onto your web server
-- 2. in the 'dicom.ini' of your web server, create the dwv viewer:
-- >> [dwv-simple]
-- >> source = dwv-mobile.lua
-- And set it as the default viewer:
-- >> [webdefaults]
-- >> ...
-- >> viewer = dwv-simple
-- 3. copy the DWV distribution files in a 'dwv' folder
-- in the web folder of your web server. It should be accessible
-- via '[server address]/dwv'.
--
-- This script relies on the 'kFactorFile', 'ACRNemaMap' and 'Dictionary'
-- variables being set correctly.
-- Get ids
local patientid = string.gsub(series2, ':.*$', '')
local seriesuid = string.gsub(series2, '^.*:', '')
-- Functions declaration
function getstudyuid()
local a, b, s
s = servercommand('get_param:MyACRNema')
b = newdicomobject()
b.PatientID = patientid
b.SeriesInstanceUID = seriesuid
b.StudyInstanceUID = ''
a = dicomquery(s, 'SERIES', b)
return a[0].StudyInstanceUID
end
function queryimages()
local images, imaget, b, s
s = servercommand('get_param:MyACRNema')
b = newdicomobject()
b.PatientID = patientid
b.SeriesInstanceUID = seriesuid
b.SOPInstanceUID = ''
images = dicomquery(s, 'IMAGE', b)
imaget={}
for k=0,#images-1 do
imaget[k+1]={}
imaget[k+1].SOPInstanceUID = images[k].SOPInstanceUID
end
table.sort(imaget, function(a,b) return a.SOPInstanceUID < b.SOPInstanceUID end)
return imaget
end
-- Main
local studyuid = getstudyuid()
local images = queryimages()
-- create the url lua array
local urlRoot = webscriptadress
urlRoot = urlRoot .. '?requestType=WADO&contentType=application/dicom'
urlRoot = urlRoot .. '&seriesUID=' .. seriesuid
urlRoot = urlRoot .. '&studyUID=' .. studyuid
local urls = {}
for i=1, #images do
urls[i] = urlRoot .. '&objectUID=' .. images[i].SOPInstanceUID
end
-- Generate html
HTML('Content-type: text/html\n\n')
-- paths with extra /dwv
print([[
<!DOCTYPE html>
<html>
<head>
<title>DICOM Web Viewer</title>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="/dwv/css/style.css">
]])
print([[
<style type="text/css" >
body { margin: 10px; padding: 0; }
.layerContainer { margin: auto; text-align: center; }
.imageLayer { left: 0px; }
.dropBox { margin: 20px auto; }
.inline { display: inline-block !important; }
</style>
<link type="text/css" rel="stylesheet" href="/dwv/ext/jquery-mobile/jquery.mobile-1.4.5.min.css" />
<link type="text/css" rel="stylesheet" href="/dwv/ext/nprogress/nprogress.css" />
<style type="text/css" >
.ui-popup .ui-controlgroup { background-color: #252525; }
.colourLi > .ui-input-text { text-align: center; }
.colourLi > .ui-input-text input { min-height: 2em; width: 7em; display:inline-block }
.lwColourLi > .ui-input-text { text-align: center; }
.lwColourLi > .ui-input-text input { min-height: 2em; width: 7em; display:inline-block }
.ffColourLi > .ui-input-text { text-align: center; }
.ffColourLi > .ui-input-text input { min-height: 2em; width: 7em; display:inline-block }
/* jquery-mobile strip not visible enough */
.table-stripe tbody tr:nth-child(odd) td,
.table-stripe tbody tr:nth-child(odd) th {
background-color: #eeeeee; /* non-RGBA fallback */
background-color: rgba(0,0,0,0.1);
}
</style>
<link type="text/css" rel="stylesheet" href="/dwv/ext/jquery-mobile/jquery.mobile-1.4.5.min.css">
]])
print([[
<!-- Third party (dwv) -->
<script type="text/javascript" src="/dwv/ext/modernizr/modernizr.js"></script>
<script type="text/javascript" src="/dwv/ext/i18next/i18next.min.js"></script>
<script type="text/javascript" src="/dwv/ext/i18next/i18nextXHRBackend.min.js"></script>
<script type="text/javascript" src="/dwv/ext/i18next/i18nextBrowserLanguageDetector.min.js"></script>
<script type="text/javascript" src="/dwv/ext/konva/konva.min.js"></script>
<script type="text/javascript" src="/dwv/ext/magic-wand/magic-wand.js"></script>
<script type="text/javascript" src="/dwv/ext/jszip/jszip.min.js"></script>
]])
print([[
<!-- Third party (viewer) -->
<script type="text/javascript" src="/dwv/ext/jquery/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="/dwv/ext/jquery-mobile/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript" src="/dwv/ext/nprogress/nprogress.js"></script>
<script type="text/javascript" src="/dwv/ext/flot/jquery.flot.min.js"></script>
]])
print([[
<!-- Decoders -->
<script type="text/javascript" src="/dwv/decoders/pdfjs/jpx.js"></script>
<script type="text/javascript" src="/dwv/decoders/pdfjs/util.js"></script>
<script type="text/javascript" src="/dwv/decoders/pdfjs/arithmetic_decoder.js"></script>
<script type="text/javascript" src="/dwv/decoders/pdfjs/jpg.js"></script>
<script type="text/javascript" src="/dwv/decoders/rii-mango/lossless-min.js"></script>
]])
print([[
<!-- Local -->
<script type="text/javascript" src="/dwv/dwv-0.23.0-beta.min.js"></script>
<!-- Launch the app -->
<script type="text/javascript" src="/dwv/viewers/mobile/appgui.js"></script>
]])
print([[
<script type="text/javascript">
// start app function
function startApp() {
// translate page
dwv.i18nPage();
// main application
var myapp = new dwv.App();
myapp.init({
"containerDivId": "dwv",
"fitToWindow": true,
"tools": ["Scroll", "WindowLevel", "ZoomAndPan", "Draw", "Livewire", "Filter", "Floodfill"],
"filters": ["Threshold", "Sharpen", "Sobel"],
"shapes": ["Arrow", "Ruler", "Protractor", "Rectangle", "Roi", "Ellipse", "FreeHand"],
"gui": ["tool", "load", "help", "undo", "version", "tags", "drawList"],
"loaders": ["File", "Url"],
"isMobile": true,
"skipLoadUrl": true
});
var size = dwv.gui.getWindowSize();
$(".layerContainer").height(size.height);
]])
-- create javascript url array
print([[
var inputUrls = [
]])
for i=1, #images do
print(' "'..urls[i]..'",')
end
print([[
];
]])
-- load data
print([[
if( inputUrls && inputUrls.length > 0 ) myapp.loadURLs(inputUrls);
}; // end startApp
]])
print([[
// check browser support
dwv.browser.check();
// initialise i18n
dwv.i18nInitialise("en","/dwv");
]])
print([[
// status flags
var domContentLoaded = false;
var i18nInitialised = false;
// launch when both DOM and i18n are ready
function launchApp() {
if ( domContentLoaded && i18nInitialised ) {
startApp();
}
}
// DOM ready?
$(document).ready( function() {
domContentLoaded = true;
launchApp();
});
// i18n ready?
dwv.i18nOnInitialised( function () {
// call next once the overlays are loaded
var onLoaded = function (data) {
dwv.gui.info.overlayMaps = data;
i18nInitialised = true;
launchApp();
};
// load overlay map info
$.getJSON( dwv.i18nGetLocalePath("overlays.json"), onLoaded )
.fail( function () {
console.log("Using fallback overlays.");
$.getJSON( dwv.i18nGetFallbackLocalePath("overlays.json"), onLoaded );
});
});
]])
print([[
</script>
]])
print([[
</head>
<body>
<!-- Main page -->
<div data-role="page" data-theme="b" id="main">
<!-- pageHeader #dwvversion -->
<div id="pageHeader" data-role="header">
<h1>DWV <span class="dwv-version"></span></h1>
<a href="#help_page" data-icon="carat-r" class="ui-btn-right"
data-transition="slide" data-i18n="basics.help">Help</a>
</div><!-- /pageHeader -->
<!-- DWV -->
<div id="dwv">
<div id="pageMain" data-role="content" style="padding:2px;">
<!-- Toolbar -->
<div class="toolbar"></div>
<!-- Open popup -->
<div data-role="popup" id="popupOpen">
<a href="#" data-rel="back" data-role="button" data-icon="delete"
data-iconpos="notext" class="ui-btn-right" data-i18n="basics.close">Close</a>
<div style="padding:10px 20px;">
<h3 data-i18n="basics.open">Open</h3>
<div id="dwv-loaderlist"></div>
</div>
</div><!-- /popup -->
<!-- Layer Container -->
<div class="layerContainer">
<div class="dropBox"></div>
<canvas class="imageLayer">Only for HTML5 compatible browsers...</canvas>
<div class="drawDiv"></div>
<div class="infoLayer">
<div class="infotl info"></div>
<div class="infotc infoc"></div>
<div class="infotr info"></div>
<div class="infocl infoc"></div>
<div class="infocr infoc"></div>
<div class="infobl info"></div>
<div class="infobc infoc"></div>
<div class="infobr info"></div>
</div><!-- /infoLayer -->
</div><!-- /layerContainer -->
<!-- History -->
<div class="history" title="History" style="display:none;"></div>
</div><!-- /content -->
<div data-role="footer">
<div data-role="navbar" class="toolList">
</div><!-- /navbar -->
</div><!-- /footer -->
</div><!-- /page main -->
</div><!-- /dwv -->
<!-- Tags page -->
<div data-role="page" data-theme="b" id="tags_page">
<div data-role="header">
<a href="#main" data-icon="back" data-transition="slide"
data-direction="reverse" data-i18n="basics.back">Back</a>
<h1 data-i18n="basics.dicomTags">DICOM Tags</h1>
</div><!-- /header -->
<div data-role="content">
<!-- Tags -->
<div id="dwv-tags" title="Tags"></div>
</div><!-- /content -->
</div><!-- /page tags_page-->
<!-- Draw list page -->
<div data-role="page" data-theme="b" id="drawList_page">
<div data-role="header">
<a href="#main" data-icon="back" data-transition="slide"
data-direction="reverse" data-i18n="basics.back">Back</a>
<h1 data-i18n="basics.drawList">Draw list</h1>
</div><!-- /header -->
<div data-role="content">
<!-- DrawList -->
<div id="dwv-drawList" title="Draw list"></div>
</div><!-- /content -->
</div><!-- /page draw-list_page-->
<!-- Help page -->
<div data-role="page" data-theme="b" id="help_page">
<div data-role="header">
<a href="#main" data-icon="back" data-transition="slide"
data-direction="reverse" data-i18n="basics.back">Back</a>
<h1 data-i18n="basics.help">Help</h1>
</div><!-- /header -->
<div data-role="content">
<!-- Help -->
<div id="dwv-help" title="Help"></div>
</div><!-- /content -->
</div><!-- /page help_page-->
</body>
</html>
]])
|
-- Don't show any numbers inside terminals
vim.cmd [[ au TermOpen term://* setlocal nonumber norelativenumber | setfiletype terminal ]]
-- File extension specific tabbing
vim.cmd [[ autocmd Filetype python setlocal expandtab tabstop=4 shiftwidth=4 softtabstop=4 ]] |
-- lua script that can be added to an object in Tabletop Simulator to load spirits generated with this tool.
function onLoad() LoadData() end
local data = nil
local json_url = nil
function LoadData() startLuaCoroutine(self, "LoadDataCo") end
function LoadDataCo()
if (json_url == nil) then
local table = self.UI.getXmlTable()
while table == nil or table[1] == nil or table[1].children == nil or
table[1].children[1] == nil do
Wt(0.5)
table = self.UI.getXmlTable()
end
json_url = self.UI.getXmlTable()[1].children[1].value
end
local url = json_url
if url == nil then return end
local function starts_with(str, start) return str:sub(1, #start) == start end
if starts_with(url, 'https://') or starts_with(url, 'http://') then
local function webRequestCallback(webReturn)
data = JSON.decode(webReturn.text)
startLuaCoroutine(self, "HandleSpiritsCo")
end
WebRequest.get(url, function(a) webRequestCallback(a) end)
else
broadcastToAll(
'Only URLs starting with "http://" or "https://" ares supported',
{r = 1, g = 0, b = 0})
-- havn't found out a way to open a local file. Propably securety resons...
-- local function read_file(path)
-- local file = io.open(path, "rb") -- r read mode and b binary mode
-- if not file then return nil end
-- local content = file:read "*a" -- *a or *all reads the whole file
-- file:close()
-- return content
-- end
-- local content = read_file(url)
-- data = content
-- startLuaCoroutine(self, "HandleSpiritsCo")
end
return 1
end
function UpdateUrl(player, value, id) json_url = value end
function HandleSpiritsCo()
local loeadedData = data
if data == nil then return end
local ui = self.UI.getXmlTable()
local list = {}
ui[1].children[3].children[1].children = list
ui[1].children[1].value = json_url
local numberOfEntrys = 0
local customAssets = UI.getCustomAssets()
if customAssets == nil then customAssets = {} end
for key, value in pairs(loeadedData) do
local backFace = value[2].CustomDeck[next(value[2].CustomDeck)].BackURL
-- backFace = Next(pairs(value[2].CustomDeck))--.value.BackURL
local found = false
for key2, value2 in pairs(customAssets) do
if value2.name == key then
found = true
value2.url = backFace
end
end
if found == false then
customAssets[#customAssets + 1] = {name = key, url = backFace}
end
numberOfEntrys = numberOfEntrys + 1
local currentElement = {
tag = "Panel",
attributes = {
childForceExpandHeight = true,
childAlignment = "UpperLeft",
height = 200
},
children = {
{
tag = "Button",
attributes = {
onClick = "LoadSpirit",
id = key,
height = 50,
width = 110,
offsetXY = "0 75"
},
value = key
}, {
tag = "Image",
attributes = {
image = key,
type = "Filled",
height = 150,
width = 110,
offsetXY = "0 -25"
}
}
}
}
list[#list + 1] = currentElement
end
self.setTable("spiritData", loeadedData)
UI.setCustomAssets(customAssets)
Wt(0.5)
ui[1].children[3].children[1].attributes.height = numberOfEntrys * 200
self.UI.setXmlTable(ui)
print("All Spirits loaded")
return 1
end
function LoadSpirit(object_pick, player_color, arg1)
local pos = self.getPosition()
-- the offset is only for the spirit, the power cards look good at there position
local offset = {x = 4, y = -1.3}
local value = self.getTable("spiritData")[arg1]
t = {
position = {x = pos.x + offset.x, y = pos.y + 3, z = pos.z + offset.y},
rotation = {x = 0, y = 180, z = 180},
json = JSON.encode(value[1])
}
t.json = spawnObjectJSON(t)
t = {
position = {x = pos.x, y = pos.y + 5, z = pos.z},
json = JSON.encode(value[2])
}
spawnObjectJSON(t)
end
function Wt(some)
local Time = os.clock() + some
while os.clock() < Time do coroutine.yield(0) end
end
|
#!/usr/local/bin/lua
print("Hello World!") |
local name, _FishMaster = ...;
_FishMaster.settings.audio = {
name = function()
return "Sound";
end,
type = "group",
order = 1,
args = {
override = {
name = "Override audio",
type = "toggle",
order = 1,
set = function(info, val)
FishMaster.db.char.audio.enabled = val;
end,
get = function(info)
return FishMaster.db.char.audio.enabled
end,
width = "full",
},
effects = {
name = "Sound effects",
type = "toggle",
order = 2,
set = function(info, val)
FishMaster.db.char.audio.effects = val;
end,
get = function(info)
return FishMaster.db.char.audio.effects
end,
width = "normal",
},
music = {
name = "Music",
type = "toggle",
order = 3,
set = function(info, val)
FishMaster.db.char.audio.music = val;
end,
get = function(info)
return FishMaster.db.char.audio.music
end,
width = "normal",
},
ambient = {
name = "Ambient Sounds",
type = "toggle",
order = 4,
set = function(info, val)
FishMaster.db.char.audio.ambient = val;
end,
get = function(info)
return FishMaster.db.char.audio.ambient
end,
width = "normal",
},
dialog = {
name = "Dialog",
type = "toggle",
order = 5,
set = function(info, val)
FishMaster.db.char.audio.ambient = val;
end,
get = function(info)
return FishMaster.db.char.audio.ambient
end,
width = "normal",
},
volumes = {
type = "group",
name = "Audio",
inline = true,
order = 6,
width = "half",
args = {
masterVolume = {
name = function()
return "Master volume";
end,
type = "range",
min = 0,
max = 1,
step = .01,
order = 1,
width = "normal",
isPercent = true,
set = function(info, val)
FishMaster.db.char.audio.masterVolume = val;
end,
get = function(info)
return FishMaster.db.char.audio.masterVolume
end
},
sound = {
name = function()
return "Sound";
end,
type = "range",
min = 0,
max = 1,
step = .01,
order = 2,
isPercent = true,
set = function(info, val)
FishMaster.db.char.audio.sound = val;
end,
get = function(info)
return FishMaster.db.char.audio.sound
end
},
music = {
name = function()
return "Music";
end,
type = "range",
min = 0,
max = 1,
step = .01,
order = 3,
isPercent = true,
set = function(info, val)
FishMaster.db.char.audio.music = val;
end,
get = function(info)
return FishMaster.db.char.audio.music
end
},
ambience = {
name = function()
return "Ambience";
end,
type = "range",
min = 0,
max = 1,
step = .01,
order = 4,
isPercent = true,
set = function(info, val)
FishMaster.db.char.audio.ambience = val;
end,
get = function(info)
return FishMaster.db.char.audio.ambience
end
},
Dialog = {
name = function()
return "Dialog";
end,
type = "range",
min = 0,
max = 1,
step = .01,
order = 5,
isPercent = true,
set = function(info, val)
FishMaster.db.char.audio.dialog = val;
end,
get = function(info)
return FishMaster.db.char.audio.dialog
end
},
}
}
}
} |
local smelting_interval = 1
local smelting_chance = 1
local forming_interval = 1
local forming_chance = 1
minetest.register_alias("smelting_slag", "ks_terrain:dolomite_gravel")
-- register smelting abms for bauxite
minetest.register_abm({
neighbors = {"group:smelter"},
nodenames = {"ks_terrain:dolomite_with_bauxite"},
interval = smelting_interval,
chance = smelting_chance,
action = function(pos, node, active_object_count, active_object_count_wider)
local pos = {x = pos.x, y = pos.y, z = pos.z}
local pos_top = {x = pos.x, y = pos.y+1, z = pos.z}
minetest.set_node(pos, {name = "smelting_slag"})
minetest.set_node(pos_top, {name = "ks_metals:alumina_dust"})
end
})
minetest.register_abm({
neighbors = {"group:igniter"},
nodenames = {"ks_metals:alumina"},
interval = forming_interval,
chance = forming_chance,
action = function(pos, node, active_object_count, active_object_count_wider)
local pos = {x = pos.x, y = pos.y, z = pos.z}
minetest.set_node(pos, {name = "ks_metals:aluminium"})
end
})
|
-- This is a server sided input library for void.
-- This library assists with input issues on void.
local RunService = game:GetService("RunService")
assert(RunService:IsServer(), "Please run binder on the server. No reason to use it on the client!")
local api = {}
api.__index = api
type AmongUsInputReader = {
containerPart: BasePart?,
_useDefaultHead: boolean,
_inputs: {},
_onKeyDown: BindableEvent,
_onKeyUp: BindableEvent,
bindKey: (self: any, player: Player, keycode: Enum.KeyCode) -> {
keyEvents: {onKeyDown: RBXScriptSignal, onKeyUp: RBXScriptSignal},
onDestroy: () -> nil,
timeKeyDown: number,
isKeyDown: boolean,
destroyed: boolean,
_proximityPrompt: ProximityPrompt
},
unbindKey: (self: any, player: Player, keycode: Enum.KeyCode) -> nil
}
function api.new(useDefaultHead: boolean?, containerPart: BasePart?): AmongUsInputReader
return setmetatable({
containerPart = (not useDefaultHead) and containerPart,
_useDefaultHead = useDefaultHead or true,
_onKeyDown = Instance.new("BindableEvent"),
_onKeyUp = Instance.new("BindableEvent"),
_inputs = {}
}, api)
end
function api:bindKey(player: Player, keycode: Enum.KeyCode)
for _, v in pairs(player.Character.Head:GetChildren()) do
if v:IsA("ProximityPrompt") and (v.Name == "_onKeyPressed" .. tostring(keycode)) then
v:Destroy()
end
end
if self._inputs[player] == nil then
self._inputs[player] = {}
end
local containerPart = (self._useDefaultHead and player.Character and player.Character:FindFirstChild("Head")) or (not self._useDefaultHead) and self.containerPart
if not containerPart then
error("No containerPart found!!! useDefaultHead: "..self._useDefaultHead.." Container part: "..(self.containerPart and self.containerPart:GetFullName() or ""))
end
local isKeyDown = false
local timeKeyDown = 0
local input = Instance.new("ProximityPrompt")
local bindable = Instance.new("BindableEvent")
local bindable2 = Instance.new("BindableEvent")
input.Name = "_onKeyPressed" .. tostring(keycode)
input.Exclusivity = Enum.ProximityPromptExclusivity.AlwaysShow
input.KeyboardKeyCode = keycode
input.Style = Enum.ProximityPromptStyle.Custom
input.HoldDuration = math.huge
input.PromptButtonHoldBegan:Connect(function(playerWhoTriggered: Player)
if playerWhoTriggered == player then
bindable:Fire(player, keycode)
self._onKeyDown:Fire(player, keycode)
isKeyDown = true
self._inputs[player][keycode].isKeyDown = true
end
end)
input.PromptButtonHoldEnded:Connect(function(playerWhoTriggered: Player)
if playerWhoTriggered == player then
bindable2:Fire(player, keycode, timeKeyDown)
self._onKeyUp:Fire(player, keycode, timeKeyDown)
isKeyDown = false
timeKeyDown = 0
self._inputs[player][keycode].isKeyDown = false
end
end)
local conn
conn = RunService.Heartbeat:Connect(function(dt: number)
if isKeyDown then
timeKeyDown += dt
end
self._inputs[player][keycode].timeKeyDown = timeKeyDown
if not input:IsDescendantOf(workspace) and self._inputs[player][keycode].destroyed == false then
pcall(function()
input.Parent = containerPart
end)
isKeyDown = false
timeKeyDown = 0
return
end
end)
input.Parent = containerPart
self._inputs[player][keycode] = {
keyEvents = {onKeyDown = bindable.Event, onKeyUp = bindable2.Event},
onDestroy = function()
if conn then
conn:Disconnect()
conn = nil
end
input:Destroy()
bindable:Destroy()
bindable2:Destroy()
self._inputs[player][keycode].destroyed = true
end,
timeKeyDown = timeKeyDown,
isKeyDown = isKeyDown,
destroyed = false,
_proximityPrompt = input
}
return self._inputs[player][keycode]
end
function api:unbindKey(player: Player, keycode: Enum.KeyCode)
if self._inputs[player] and self._inputs[player][keycode] then
self._inputs[player][keycode].onDestroy()
end
end
return api
|
if GameHelpers.Combat == nil then
GameHelpers.Combat = {}
end
---@alias GameHelpersCombatGetCharactersFilter string|'"None"'|'"Player"'|'"Ally"'|'"Enemy"'|'"Neutral"'
---@alias GameHelpersCombatGetCharactersFilterCallback fun(character:EsvCharacter, combatId:integer, teamId:integer, initiative:integer, stillInCombat:boolean):boolean
---@param id integer
---@param filter GameHelpersCombatGetCharactersFilter|GameHelpersCombatGetCharactersFilterCallback|nil Used to filter returned charaters. Allies/Enemies/Neutral are the alignment relation towards the player party. If a function is supplied instead, a character is only included if the function returns true.
---@return EsvCharacter[]
function GameHelpers.Combat.GetCharacters(id, filter)
local combat = Ext.GetCombat(id)
if combat then
local objects = {}
for i,v in pairs(combat:GetAllTeams()) do
if filter then
local t = type(filter)
if t == "function" then
local b,result = xpcall(filter, debug.traceback, v.Character, v.CombatId, v.TeamId, v.Initiative, v.StillInCombat)
if not b then
Ext.PrintError(result)
elseif result == true then
objects[#objects+1] = v.Character
end
elseif t == "string" then
if filter == "Player" and v.Character.IsPlayer then
objects[#objects+1] = v.Character
elseif filter == "Ally" and GameHelpers.Character.IsAllyOfParty(v.Character.MyGuid) then
objects[#objects+1] = v.Character
elseif filter == "Enemy" and GameHelpers.Character.IsEnemyOfParty(v.Character.MyGuid) then
objects[#objects+1] = v.Character
elseif filter == "Neutral" and GameHelpers.Character.IsNeutralToParty(v.Character.MyGuid) then
objects[#objects+1] = v.Character
elseif filter == "None" then
objects[#objects+1] = v.Character
end
end
else
objects[#objects+1] = v.Character
end
end
local i = 0
local count = #objects
return function ()
i = i + 1
if i <= count then
return objects[i]
end
end
return objects
end
return nil
end |
--Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
object_tangible_ship_crafted_capacitor_shared_advanced_capacitor_battery = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_advanced_capacitor_battery.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:advanced_capacitor_battery",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:advanced_capacitor_battery",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3843288645,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_advanced_capacitor_battery, "object/tangible/ship/crafted/capacitor/shared_advanced_capacitor_battery.iff")
object_tangible_ship_crafted_capacitor_shared_advanced_recharge_module = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_advanced_recharge_module.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:advanced_recharge_module",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:advanced_recharge_module",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 4282694391,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_advanced_recharge_module, "object/tangible/ship/crafted/capacitor/shared_advanced_recharge_module.iff")
object_tangible_ship_crafted_capacitor_shared_base_capacitor = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_base_capacitor.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/eqp_music_red_ball_jet_organ.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {"cert_ordnance_level1"},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@base_weapon_capacitor:base",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@base_weapon_capacitor:base",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3064505654,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_base_capacitor, "object/tangible/ship/crafted/capacitor/shared_base_capacitor.iff")
object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:base_capacitor_subcomponent",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:base_capacitor_subcomponent",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 4258529862,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent, "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff")
object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk1 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk1.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:base_capacitor_subcomponent_mk1",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:base_capacitor_subcomponent_mk1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1484781854,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk1, "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk1.iff")
object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk2 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:base_capacitor_subcomponent_mk2",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:base_capacitor_subcomponent_mk2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2204651913,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk2, "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff")
object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk3 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:base_capacitor_subcomponent_mk3",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:base_capacitor_subcomponent_mk3",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3395630596,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk3, "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff")
object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk4 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:base_capacitor_subcomponent_mk4",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:base_capacitor_subcomponent_mk4",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 830872848,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk4, "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff")
object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk5 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:base_capacitor_subcomponent_mk5",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:base_capacitor_subcomponent_mk5",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2022406813,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_base_capacitor_subcomponent_mk5, "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff")
object_tangible_ship_crafted_capacitor_shared_basic_capacitor = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_basic_capacitor.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {"cert_ordnance_level1"},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_n:base_capacitor",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:base_capacitor",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1364868080,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_basic_capacitor, "object/tangible/ship/crafted/capacitor/shared_basic_capacitor.iff")
object_tangible_ship_crafted_capacitor_shared_capacitor_mk1 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_capacitor_mk1.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {"cert_ordnance_level1"},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:capacitor_mk1",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:capacitor_mk1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 277361603,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_capacitor_mk1, "object/tangible/ship/crafted/capacitor/shared_capacitor_mk1.iff")
object_tangible_ship_crafted_capacitor_shared_capacitor_mk2 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_capacitor_mk2.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {"cert_ordnance_level3"},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:capacitor_mk2",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:capacitor_mk2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3416234836,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_capacitor_mk2, "object/tangible/ship/crafted/capacitor/shared_capacitor_mk2.iff")
object_tangible_ship_crafted_capacitor_shared_capacitor_mk3 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_capacitor_mk3.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {"cert_ordnance_level5"},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:capacitor_mk3",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:capacitor_mk3",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2190671065,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_capacitor_mk3, "object/tangible/ship/crafted/capacitor/shared_capacitor_mk3.iff")
object_tangible_ship_crafted_capacitor_shared_capacitor_mk4 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_capacitor_mk4.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {"cert_ordnance_level7"},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:capacitor_mk4",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:capacitor_mk4",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2037503949,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_capacitor_mk4, "object/tangible/ship/crafted/capacitor/shared_capacitor_mk4.iff")
object_tangible_ship_crafted_capacitor_shared_capacitor_mk5 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_capacitor_mk5.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {"cert_ordnance_level9"},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:capacitor_mk5",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:capacitor_mk5",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 813477952,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_capacitor_mk5, "object/tangible/ship/crafted/capacitor/shared_capacitor_mk5.iff")
object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk1 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk1.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:energy_saver_battery_mk1",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:energy_saver_battery_mk1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 598079079,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk1.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk1, "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk1.iff")
object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk2 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk2.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:energy_saver_battery_mk2",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:energy_saver_battery_mk2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 4172439280,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk2, "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk2.iff")
object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk3 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk3.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:energy_saver_battery_mk3",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:energy_saver_battery_mk3",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2982099325,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk3, "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk3.iff")
object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk4 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk4.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:energy_saver_battery_mk4",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:energy_saver_battery_mk4",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1247548009,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk4, "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk4.iff")
object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk5 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk5.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:energy_saver_battery_mk5",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:energy_saver_battery_mk5",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 55670244,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_energy_saver_battery_mk5, "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk5.iff")
object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk1 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk1.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:extended_life_battery_mk1",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:extended_life_battery_mk1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1281522685,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk1.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk1, "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk1.iff")
object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk2 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk2.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:extended_life_battery_mk2",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:extended_life_battery_mk2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2541081450,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk2, "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk2.iff")
object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk3 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk3.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:extended_life_battery_mk3",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:extended_life_battery_mk3",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3732452583,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk3, "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk3.iff")
object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk4 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk4.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:extended_life_battery_mk4",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:extended_life_battery_mk4",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 630956019,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk4, "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk4.iff")
object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk5 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk5.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:extended_life_battery_mk5",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:extended_life_battery_mk5",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1821833342,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_extended_life_battery_mk5, "object/tangible/ship/crafted/capacitor/shared_extended_life_battery_mk5.iff")
object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk1 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk1.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:heavy_battery_mk1",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:heavy_battery_mk1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1987626722,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk1.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk1, "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk1.iff")
object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk2 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk2.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:heavy_battery_mk2",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:heavy_battery_mk2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2909761141,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk2, "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk2.iff")
object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk3 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk3.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:heavy_battery_mk3",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:heavy_battery_mk3",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3831630328,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk3, "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk3.iff")
object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk4 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk4.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:heavy_battery_mk4",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:heavy_battery_mk4",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 528556780,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk4, "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk4.iff")
object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk5 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk5.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:heavy_battery_mk5",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:heavy_battery_mk5",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1452033377,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_heavy_battery_mk5, "object/tangible/ship/crafted/capacitor/shared_heavy_battery_mk5.iff")
object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk1 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk1.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:quick_recharge_battery_mk1",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:quick_recharge_battery_mk1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1831490574,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk1.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk1, "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk1.iff")
object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk2 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk2.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:quick_recharge_battery_mk2",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:quick_recharge_battery_mk2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3057515673,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk2.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk2, "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk2.iff")
object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk3 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk3.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:quick_recharge_battery_mk3",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:quick_recharge_battery_mk3",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 4281375508,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk3.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk3, "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk3.iff")
object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk4 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk4.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:quick_recharge_battery_mk4",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:quick_recharge_battery_mk4",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 80982016,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk4.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk4, "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk4.iff")
object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk5 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk5.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:quick_recharge_battery_mk5",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:quick_recharge_battery_mk5",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1306449805,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent.iff", "object/tangible/ship/crafted/capacitor/shared_base_capacitor_subcomponent_mk5.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_quick_recharge_battery_mk5, "object/tangible/ship/crafted/capacitor/shared_quick_recharge_battery_mk5.iff")
object_tangible_ship_crafted_capacitor_shared_standard_capacitor_battery = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_standard_capacitor_battery.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:standard_capacitor_battery",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:standard_capacitor_battery",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3218110775,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_standard_capacitor_battery, "object/tangible/ship/crafted/capacitor/shared_standard_capacitor_battery.iff")
object_tangible_ship_crafted_capacitor_shared_standard_recharge_module = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/crafted/capacitor/shared_standard_recharge_module.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ship_component_capacitor_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 1073741830,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space_crafting_d:standard_recharge_module",
gameObjectType = 1073741830,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space_crafting_n:standard_recharge_module",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 4261874664,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/components/base/shared_ship_subcomponent_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_crafted_capacitor_shared_standard_recharge_module, "object/tangible/ship/crafted/capacitor/shared_standard_recharge_module.iff")
|
AddEvent("OnPlayerSkydiveCrash", function()
CallRemoteEvent("parachute:disable")
end) |
local Vector = require("src/helper/Vector")
local
Asteroid, Body, Color, DrawableCircle, Drawable, JustSpawned, Particle, SpawnMe = Component.load(
{"Asteroid", "Body", "Color", "DrawableCircle", "Drawable", "JustSpawned", "Particle", "SpawnMe"}
)
local AsteroidSpawnSystem = class("AsteroidSpawnSystem", System)
function AsteroidSpawnSystem:initialize()
System.initialize(self)
self.timer = 0
self.spawntime = 1
end
function AsteroidSpawnSystem.spawnAsteroid(position, size, motionVector, impulse, image, particleImage)
local world = stack:current().world
local engine = stack:current().engine
-- Create a new entity with a (future) physics body.
local asteroid = Entity()
asteroid:add(SpawnMe(size, position, motionVector, nil, impulse))
-- Add drawing stuff
-- asteroid:add(DrawableCircle(size, false))
-- asteroid:add(Color(255, 255, 0))
-- Add image
local imageW, imageH = image:getWidth(), image:getHeight()
local drawable = Drawable(image, 3, nil, nil, imageW / 2, imageH / 2)
asteroid:add(drawable)
asteroid:add(Asteroid(size))
asteroid:add(JustSpawned())
if particleImage then
asteroid:add(Particle(particleImage, 10000, Vector(0, 0), {0.05, 0.5}))
end
engine:addEntity(asteroid)
return asteroid
end
function AsteroidSpawnSystem:update(dt)
self.timer = self.timer + dt
if self.timer > self.spawntime then
self.timer = self.timer - self.spawntime
local x, y = math.random(-200, 200), math.random(-200, 200)
-- Spawn the asteroids at least -+50 left/right outside the viewport.
if x < 0 then
x = x - 50
else
x = x + 1970
end
-- Spawn the asteroids at least -+50 top/down outside the viewport.
if y < 0 then
y = y - 50
else
y = y + 1130
end
local position = Vector(x, y)
-- Target any random place within the viewport (excluding the outer 100 coordinate square).
local target = Vector(math.random(100, 1820), math.random(100, 980))
local motionVector = target:subtract(position)
local velocity = math.random(100, 200)
motionVector = motionVector:getUnit()
motionVector = motionVector:multiply(velocity)
local randomType = math.random(1, 3)
local image, type, particleImage
if randomType == 1 then
image = resources.images.explodyboi
particleImage = resources.images.explodyparticle
type = "explodiboy"
elseif randomType == 2 then
image = resources.images.stoneboi
particleImage = resources.images.explodyparticle
type = "stoneboi"
elseif randomType == 3 then
image = resources.images.waterboi
particleImage = resources.images.explodyparticle
type = "waterboi"
end
local size = math.random(15, 25)
local asteroid = AsteroidSpawnSystem.spawnAsteroid(position, size, motionVector, nil, image, particleImage)
asteroid:get("Asteroid").type = type
end
end
function AsteroidSpawnSystem:requires()
return {}
end
return AsteroidSpawnSystem
|
function getPlayerDiamound(player)
local diamantes = 0
local count = getElementData(player, "VDBG.Diamantes" )
if player and count then
diamantes = count
end
return diamantes or 0
end
function givePlayerDiamound(player,amount)
local login = getElementData ( player, "AccountData:Username")
if login and amount then
triggerServerEvent ( "givePlayerDiamound", resourceRoot, login, amount )
end
end
function takePlayerDiamound (player,amount)
local login = getElementData ( player, "AccountData:Username")
if login and amount then
triggerServerEvent ( "takePlayerDiamound", resourceRoot, login, amount )
end
end
function hasPlayerDiamound(player, amount)
amount = tonumber( amount ) or 0
local count = getPlayerDiamound(player)
if player and count >= amount then
return true
end
return false
end |
function getPlayerDiamound(login)
local diamantes = 0
for _, p in pairs ( getElementsByType ( "player" ) ) do
if ( getAccountName ( getPlayerAccount ( p ) ) == login ) then
count = getElementData(p, "VDBG.Diamantes" )
diamantes = count
foundPlayer = true;
break;
end
end
if ( not foundPlayer ) then
local q = exports["VDBGSQL"]:db_query ( "SELECT diamantes FROM accountdata WHERE Username=?", login );
if (q and q[1] and q[1].diamantes ) then
local m = tonumber ( q[1].diamantes )
diamantes = m
end
end
return diamantes or 0
end
function givePlayerDiamound(login,amount)
local foundPlayer = false;
for _, p in pairs ( getElementsByType ( "player" ) ) do
if ( getAccountName ( getPlayerAccount ( p ) ) == login ) then
count = getElementData(p, "VDBG.Diamantes" )
setElementData(p, "VDBG.Diamantes", count + amount )
['VDBGSQL']:db_exec("UPDATE accountdata SET diamantes=? WHERE Username=?", count + amount, login )
foundPlayer = true;
break;
end
end
if ( not foundPlayer ) then
local q = exports["VDBGSQL"]:db_query ( "SELECT diamantes FROM accountdata WHERE Username=?", login );
if (q and q[1] and q[1].diamantes ) then
local m = tonumber ( q[1].diamantes ) + amount
exports['VDBGSQL']:db_exec("UPDATE accountdata SET diamantes=? WHERE Username=?", m, login )
end
end
end
addEvent( "givePlayerDiamound", true )
addEventHandler( "givePlayerDiamound", resourceRoot, givePlayerDiamound )
function takePlayerDiamound (login,amount)
local foundPlayer = false;
for _, p in pairs ( getElementsByType ( "player" ) ) do
if ( getAccountName ( getPlayerAccount ( p ) ) == login ) then
count = getElementData(p, "VDBG.Diamantes" )
setElementData(p, "VDBG.Diamantes", count - amount )
foundPlayer = true;
break;
end
end
if ( not foundPlayer ) then
local q = exports["VDBGSQL"]:db_query ( "SELECT diamantes FROM accountdata WHERE Username=?", login );
if (q and q[1] and q[1].diamantes ) then
local m = tonumber ( q[1].diamantes ) - amount
exports['VDBGSQL']:db_exec("UPDATE accountdata SET diamantes=? WHERE Username=?", m, login )
end
end
end
addEvent( "takePlayerDiamound", true )
addEventHandler( "takePlayerDiamound", resourceRoot, takePlayerDiamound )
function hasPlayerDiamound(login, amount)
amount = tonumber( amount ) or 0
local count = getPlayerDiamound(login)
if login and count >= amount then
return true
end
return false
end
function updateDiamante(login,cart)
local amount = 1
if tostring(cart) == "pack_diamante_1" then
amount = 1000
elseif tostring(cart) == "pack_diamante_2" then
amount = 2000
elseif tostring(cart) == "pack_diamante_3" then
amount = 3000
end
outputConsole("teste")
givePlayerDiamound ( login, amount )
end |
local dkjson = require "dkjson"
local _M = {}
function _M.new()
return setmetatable({}, { __index = _M })
end
function _M.encode(_, data)
return dkjson.encode(data)
end
function _M.decode(_, string)
local data, _, err = dkjson.decode(string)
return data, err
end
return _M
|
-- coding: utf-8
local Shared = ...
local op = Shared.OpCodes
local Msg, ErrMsg, pack, ExpandEnv = Shared.Msg, Shared.ErrMsg, Shared.pack, Shared.ExpandEnv
local MacroDirs = Shared.MacroDirs
local F = far.Flags
local type = type
local string_find, string_sub = string.find, string.sub
local band, bor = bit.band, bit.bor
local MacroCallFar = Shared.MacroCallFar
local gmeta = { __index=_G }
local LastMessage = {}
local LoadCounter = 0
--------------------------------------------------------------------------------
local TrueAreaNames = {
[F.MACROAREA_OTHER] = "Other",
[F.MACROAREA_SHELL] = "Shell",
[F.MACROAREA_VIEWER] = "Viewer",
[F.MACROAREA_EDITOR] = "Editor",
[F.MACROAREA_DIALOG] = "Dialog",
[F.MACROAREA_SEARCH] = "Search",
[F.MACROAREA_DISKS] = "Disks",
[F.MACROAREA_MAINMENU] = "MainMenu",
[F.MACROAREA_MENU] = "Menu",
[F.MACROAREA_HELP] = "Help",
[F.MACROAREA_INFOPANEL] = "Info",
[F.MACROAREA_QVIEWPANEL] = "QView",
[F.MACROAREA_TREEPANEL] = "Tree",
[F.MACROAREA_FINDFOLDER] = "FindFolder",
[F.MACROAREA_USERMENU] = "UserMenu",
[F.MACROAREA_AUTOCOMPLETION] = "AutoCompletion",
--~ [F.MACROAREA_SHELLAUTOCOMPLETION] = "ShellAutoCompletion",
--~ [F.MACROAREA_DIALOGAUTOCOMPLETION] = "DialogAutoCompletion",
--~ [F.MACROAREA_GRABBER] = "Grabber",
--~ [F.MACROAREA_DESKTOP] = "Desktop",
[F.MACROAREA_COMMON] = "Common",
}
local AllAreaNames = {}
for k,v in pairs(TrueAreaNames) do
local str = v:lower()
AllAreaNames[k] = str
AllAreaNames[str] = k
end
local SomeAreaNames = {
"other", "viewer", "editor", "dialog", "menu", "help", "dialogautocompletion",
"grabber", "desktop", "common" -- "common" должен идти последним
}
local function GetTrueAreaName(Mode) return TrueAreaNames[Mode] end
local function GetAreaName(Mode) return AllAreaNames[Mode] end
local function GetAreaCode(Area) return AllAreaNames[Area:lower()] end
--------------------------------------------------------------------------------
local MCODE_F_CHECKALL = op.MCODE_F_CHECKALL
local MCODE_F_GETOPTIONS = op.MCODE_F_GETOPTIONS
local MCODE_F_MACROSETTINGS = op.MCODE_F_MACROSETTINGS
Shared.OnlyEditorViewerUsed = band(MacroCallFar(MCODE_F_GETOPTIONS),0x3) ~= 0
local Areas
local LoadedMacros
local LoadMacrosDone
local LoadingInProgress
local EnumState = {}
local Events
local EventGroups = {"dialogevent","editorevent","editorinput","exitfar","viewerevent", "consoleinput"}
local AddedMenuItems
local AddedPrefixes
local IdSet
local LoadedPanelModules
local ContentColumns
package.nounload = {lpeg=true}
local initial_modules = {}
local function FixInitialModules()
for k in pairs(package.loaded) do initial_modules[k]=true end
end
local function CheckFileName (mask, name)
return far.ProcessName(F.PN_CMPNAMELIST, mask, name, F.PN_SKIPPATH)
end
local StringToFlags, FlagsToString do
local MacroFlagsByInt = {
[0x00000001] = "EnableOutput",
[0x00000002] = "NoSendKeysToPlugins",
[0x00000008] = "RunAfterFARStart",
[0x00000010] = "EmptyCommandLine",
[0x00000020] = "NotEmptyCommandLine",
[0x00000040] = "EVSelection",
[0x00000080] = "NoEVSelection",
[0x00000100] = "Selection",
[0x00000200] = "PSelection",
[0x00000400] = "NoSelection",
[0x00000800] = "NoPSelection",
[0x00001000] = "NoFilePanels",
[0x00002000] = "NoFilePPanels",
[0x00004000] = "NoPluginPanels",
[0x00008000] = "NoPluginPPanels",
[0x00010000] = "NoFolders",
[0x00020000] = "NoPFolders",
[0x00040000] = "NoFiles",
[0x00080000] = "NoPFiles",
}
local MacroFlagsByStr={}
for k,v in pairs(MacroFlagsByInt) do MacroFlagsByStr[v:lower()]=k end
function StringToFlags (str, filename)
local flags = 0
if type(str) == "string" then
for word in str:gmatch("[^ |]+") do
local f = MacroFlagsByStr[word:lower()]
if f then
flags = bor(flags, f)
else
local line1 = filename or "<not a file>"
local btn = filename and "OK;Edit" or "OK"
if 2 == ErrMsg(line1.."\nInvalid macro flag: "..word, nil, btn) then
editor.Editor(filename,nil,nil,nil,nil,nil,nil,1,nil,65001)
end
end
end
end
return flags
end
-- assume 52 bits at most
function FlagsToString (flags)
local str, bit = "", 1
while flags >= bit do
if band(flags,bit) ~= 0 then
local s = MacroFlagsByInt[bit]
if s then
if str ~= "" then str = str.." " end
str = str..s
end
end
bit = bit * 2
end
return str
end
end
local function AddId (trg, src)
trg.id = "<no id>"
if type(src.id)=="string" then
local lstr = string.lower(src.id)
if not IdSet[lstr] then
IdSet[lstr] = true
trg.id = src.id
end
end
end
local function EV_Handler (macros, filename, ...)
-- Get current priorities.
local indexes,priorities = {},{}
for i,m in ipairs(macros) do
indexes[i],priorities[i] = i, -1
if (not m.filemask) or (filename and CheckFileName(m.filemask, filename)) then
if m.condition then
local pr = m.condition(...)
if pr then
if type(pr)=="number" then priorities[i] = pr<0 and 0 or pr>100 and 100 or pr
else priorities[i] = m.priority
end
end
else
priorities[i] = m.priority
end
end
end
-- Sort by current priorities (stable sort).
table.sort(indexes, function(i,j)
return priorities[i]>priorities[j] or priorities[i]==priorities[j] and i<j
end)
-- Execute.
for _,i in ipairs(indexes) do
if priorities[i] < 0 then break end
local ret = macros[i].action(...)
if ret then
if macros==Events.dialogevent or macros==Events.editorinput or macros==Events.commandline then
return ret
elseif macros==Events.consoleinput then
if ret ~= 0 then return ret end
end
end
end
end
function export.ProcessEditorEvent (EditorID, Event, Param)
return EV_Handler(Events.editorevent, editor.GetFileName(EditorID), EditorID, Event, Param)
end
local function export_ProcessViewerEvent (ViewerID, Event, Param)
return EV_Handler(Events.viewerevent, viewer.GetFileName(ViewerID), ViewerID, Event, Param)
end
local function export_ExitFAR (unload)
return EV_Handler(Events.exitfar, nil, not not unload)
end
local function export_ProcessDialogEvent (Event, Param)
return EV_Handler(Events.dialogevent, nil, Event, Param)
end
local function export_ProcessEditorInput (Rec)
return EV_Handler(Events.editorinput, editor.GetFileName(nil), Rec)
end
local function export_ProcessConsoleInput (Rec)
return EV_Handler(Events.consoleinput, nil, Rec)
end
local function export_GetContentFields (colnames)
for _,m in ipairs(ContentColumns) do
if m.GetContentFields(colnames) then return true end
end
end
local function export_GetContentData (filename, colnames)
local tOut = {}
for _,m in ipairs(ContentColumns) do
if m.filemask==nil or CheckFileName(m.filemask, filename) then
local data = m.GetContentData(filename, colnames)
if type(data) == "table" then
for i in ipairs(colnames) do
tOut[i] = tOut[i] or (type(data[i])=="string" and data[i])
end
end
end
end
return tOut
end
local ExpandKey do -- измеренное время исполнения на ключе "CtrlAltShiftF12" = ??? (Lua); 2.3uS (LuaJIT);
local t={}
ExpandKey = function (key)
local ctrl,alt,rest
key = key:lower()
local start = 1
for _=1,3 do
local from,to,word = string_find(key, "^([lr]?ctrl)", start)
if from then ctrl = ctrl or word
else
from,to,word = string_find(key, "^([lr]?alt)", start)
if from then alt = alt or word
else
from,to,word = string_find(key, "^(shift)", start)
if from then rest = rest or word
else break
end
end
end
start = to+1
end
rest = (rest or "")..string_sub(key, start)
ctrl, alt = ctrl or "", alt or ""
if ctrl=="ctrl" then
if alt=="alt" then
t[1] = "lctrllalt"..rest; t[2] = "lctrlralt"..rest
t[3] = "rctrllalt"..rest; t[4] = "rctrlralt"..rest
return t,4
else
t[1] = "lctrl"..alt..rest
t[2] = "rctrl"..alt..rest
return t,2
end
else
if alt=="alt" then
t[1] = ctrl.."lalt"..rest
t[2] = ctrl.."ralt"..rest
return t,2
else
t[1] = ctrl..alt..rest
return t,1
end
end
end
end
local function AddRegularMacro (srctable, FileName)
if not (type(srctable)=="table" and type(srctable.area)=="string") then
return
end
local macro = {}
macro.area = srctable.area
macro.key = type(srctable.key)=="string" and srctable.key or "none"
if not macro.key:find("%S") then macro.key = "none" end
local keyregex = macro.key:match("^/(.+)/$")
if keyregex then
local ok
ok, macro.keyregex = pcall(regex.new, "^("..keyregex..")$", "i")
if not ok then
ErrMsg("Invalid regex: "..macro.key)
return
end
end
if type(srctable.action)=="function" then
macro.action = srctable.action
elseif type(srctable.code)=="string" then
local isMoonScript = srctable.language=="moonscript"
if srctable.code:sub(1,1) == "@" then
macro.code = srctable.code
macro.language = isMoonScript and "moonscript" or "lua"
else
local f, msg = (isMoonScript and require("moonscript").loadstring or loadstring)(srctable.code)
if f then
macro.action = f
else
if FileName then ErrMsg(FileName..":\n"..msg, isMoonScript and "MoonScript"); end
return
end
end
else
return
end
local arFound = {} -- prevent multiple inclusions, i.e. area="Editor Editor"
for a in srctable.area:lower():gmatch("%S+") do
local arTable = Areas[a]
if arTable and not arFound[a] then
if macro.keyregex then
arTable[1] = arTable[1] or {}
table.insert(arTable[1], macro)
else
local keyFound = {} -- prevent multiple inclusions
for k in macro.key:lower():gmatch("%S+") do
local t,n = ExpandKey(k)
for i=1,n do
local normkey = t[i]
if not keyFound[normkey] then
arTable[normkey] = arTable[normkey] or {}
table.insert(arTable[normkey], macro)
keyFound[normkey] = true
end
end
end
end
arFound[a] = true
end
end
if next(arFound) then
macro.flags = StringToFlags(srctable.flags, FileName)
if type(srctable.description)=="string" then macro.description=srctable.description end
if type(srctable.condition)=="function" then macro.condition=srctable.condition end
if type(srctable.filemask)=="string" then macro.filemask=srctable.filemask end
local priority = srctable.priority
if type(priority)=="number" then
macro.priority = priority>100 and 100 or priority<0 and 0 or priority
end
priority = srctable.sortpriority
if type(priority)=="number" then
macro.sortpriority = priority>100 and 100 or priority<0 and 0 or priority
end
macro.selected = srctable.selected and true
AddId(macro, srctable)
if FileName then
macro.FileName = FileName
else
macro.guid = srctable.guid
macro.callback = srctable.callback
macro.callbackId = srctable.callbackId
macro.language = srctable.language
end
macro.data = {}
for k,v in pairs(srctable) do macro.data[k]=v; end
macro.index = #LoadedMacros+1
LoadedMacros[macro.index] = macro
return macro
end
end
local CharNames = { ["."]="Dot", ["<"]="Less", [">"]="More", ["|"]="Pipe", ["/"]="Slash",
[":"]="Colon", ["?"]="Question", ["*"]="Asterisk", ['"']="Quote" }
local function AddRecordedMacro (srctable, filename)
local area = srctable.area:lower()
if not (area and Areas[area]) then return end
local arTable = Areas[area]
local key = srctable.key
-- check correspondence between (a) filename and (b) area_key
if ("%s_%s"):format(area, (key:gsub(".",CharNames))):lower() ~=
filename:gsub("^.*/",""):sub(1,-5):lower() then return
end
if srctable.code and srctable.code:sub(1,1) ~= "@" then
local f, msg = loadstring(srctable.code)
if not f then ErrMsg(msg) return end
end
local macro = { FileName=filename }
local t,n = ExpandKey(key)
for i=1,n do
local normkey = t[i]
arTable[normkey] = arTable[normkey] or {}
arTable[normkey].recorded = macro
end
for _,v in ipairs{"area","key","action","code","description"} do macro[v]=srctable[v] end
macro.flags = StringToFlags(srctable.flags, filename)
if type(macro.description)~="string" then macro.description=nil end
macro.index = #LoadedMacros+1
LoadedMacros[macro.index] = macro
end
local AddEvent_fields = {"group","action","description","priority","condition","filemask"}
local function AddEvent (srctable, FileName)
local group = type(srctable)=="table" and type(srctable.group)=="string" and srctable.group:lower()
if not (group and Events[group]) then return end
if type(srctable.action)~="function" then return end
local macro={}
table.insert(Events[group], macro)
for _,v in ipairs(AddEvent_fields) do macro[v]=srctable[v] end
macro.FileName = FileName
if type(macro.description)~="string" then macro.description=nil end
if type(macro.condition)~="function" then macro.condition=nil end
if type(macro.filemask)~="string" then macro.filemask=nil end
if type(macro.priority)~="number" then macro.priority=50
elseif macro.priority>100 then macro.priority=100 elseif macro.priority<0 then macro.priority=0
end
AddId(macro, srctable)
macro.index = #LoadedMacros+1
LoadedMacros[macro.index] = macro
return macro
end
local function AddMenuItem (srctable, FileName)
if type(srctable)=="table" and
type(srctable.menu)=="string" and
type(srctable.guid)=="string" and
(type(srctable.text)=="function" or type(srctable.text)=="string") and
type(srctable.action)=="function"
then
local item = {}
item.guid = win.Uuid(srctable.guid)
if item.guid and #item.guid==16 and not AddedMenuItems[item.guid] then
item.flags = {}
for w in srctable.menu:lower():gmatch("%S+") do
if w=="plugins" or w=="disks" or w=="config" then item.flags[w]=true end
end
if type(srctable.area)=="string" then
for w in srctable.area:lower():gmatch("%S+") do
if w == "common" then
item.flags[w]=true
else
local code = GetAreaCode(w)
if code then item.flags[code]=true end
end
end
end
local text = srctable.text
item.text = type(text)=="function" and text or function() return text end
item.action = srctable.action
item.description = type(srctable.description)=="string" and srctable.description or ""
item.FileName = FileName
item.index = #AddedMenuItems + 1
AddedMenuItems[item.index] = item
AddedMenuItems[item.guid] = item
return true
end
end
return false
end
local function AddPrefixes (srctable, FileName)
local result = 0
if type(srctable)=="table" and
type(srctable.prefixes)=="string" and
type(srctable.action)=="function"
then
for prefix in srctable.prefixes:lower():gmatch("[^:]+") do
if prefix:match("^%S+$") and not AddedPrefixes[prefix] then
local item = {
prefix = prefix,
action = srctable.action,
description = type(srctable.description)=="string" and srctable.description or "",
FileName = FileName
}
AddedPrefixes[prefix] = item
AddedPrefixes[1] = AddedPrefixes[1]..":"..prefix
result = result + 1
end
end
end
return result
end
local function AddPanelModule (srctable, FileName)
if type(srctable) == "table" and type(srctable.Info) == "table" then
local guid = srctable.Info.Guid
if type(guid) == "string" and #guid == 16 then
if not LoadedPanelModules[guid] then
if FileName then srctable.FileName=FileName; end
LoadedPanelModules[guid] = srctable
table.insert(LoadedPanelModules, srctable)
end
end
end
end
local function AddContentColumns (srctable, FileName)
if type(srctable) == "table"
and type(srctable.GetContentFields) == "function"
and type(srctable.GetContentData) == "function"
then
if type(srctable.filemask)~="string" then srctable.filemask=nil; end
if type(srctable.description)~="string" then srctable.description=nil; end
if FileName then srctable.FileName=FileName; end
table.insert(ContentColumns, srctable)
end
end
local function EnumMacros (strArea, resetEnum)
local area = strArea:lower()
if Areas[area] then
if EnumState.area ~= area or resetEnum then
EnumState.area, EnumState.index = area, 0
end
while true do
EnumState.index = EnumState.index + 1
local macro = LoadedMacros[EnumState.index]
if macro then
if not macro.disabled and macro.area and macro.area:lower():find(area) then
LastMessage = pack(macro.key, macro.description or "")
return LastMessage
end
else
EnumState.index = 0
break
end
end
end
end
local function GetMoonscriptLineNumber (filename, line)
local line_tables = require("moonscript.line_tables")
local errors = require("moonscript.errors")
local cache = {}
local table = line_tables["@"..filename]
if table then
return errors.reverse_line_number(filename, table, line, cache)
end
end
-- ...nager\unicode_far\CommonProfile\Macros\scripts\test1.lua:9:
-- attempt to perform arithmetic on a nil value
local function ErrMsgLoad (msg, filename, isMoonScript, mode)
local title = isMoonScript and mode=="compile" and "MoonScript" or "LuaMacro"
if type(msg)~="string" and type(msg)~="number" then
ErrMsg(filename..":\n<non-string error message>", title, nil, "w")
return
end
if mode=="run" then
local found = false
local fname,line = msg:match("^(.-):(%d+):")
if fname then
line = tonumber(line)
if string_sub(fname,1,3) ~= "..." then
found = true
else
fname = string_sub(fname,4)
-- for k=1,5 do
-- if fname:utf8valid() then break end
-- fname = string_sub(fname,2)
-- end
fname = fname:gsub("/", "\\")
local middle = fname:match([=[^[^\\]*\[^\\]+\]=])
if middle then
local from = string_find(filename:lower(), middle:lower(), 1, true)
if from then
fname = string_sub(filename,1,from-1) .. fname
local attr = win.GetFileAttr(fname)
found = attr and not attr:find("d")
end
end
end
end
if found then
if 2 == ErrMsg(msg, title, "OK;Edit", "wl") then
if isMoonScript then line = GetMoonscriptLineNumber(fname,line) end
editor.Editor(fname,nil,nil,nil,nil,nil,nil,line or 1,nil,65001)
end
else
ErrMsg(msg, title, "OK", "wl")
end
else
if 2 == far.Message(msg, title, "OK;Edit", "wl") then
local pattern = isMoonScript and "%[(%d+)%] >>" or "^[^\n]-:(%d+):"
local line = tonumber(msg:match(pattern))
if line and isMoonScript and mode=="run" then line = GetMoonscriptLineNumber(filename,line) end
editor.Editor(filename,nil,nil,nil,nil,nil,nil,line or 1,nil,65001)
end
end
end
local function LoadMacros (unload, paths)
if LoadingInProgress then return end
LoadingInProgress = true
if LoadMacrosDone then
local ok, msg = xpcall(function() return export_ExitFAR(true) end,
function(msg) return debug.traceback(msg,2) end)
if not ok then
msg = string.gsub(msg, "\t", " ")
ErrMsg(msg)
end
LoadMacrosDone = false
end
export.ExitFAR = nil
export.ProcessDialogEvent = nil
export.ProcessEditorInput = nil
export.ProcessViewerEvent = nil
export.ProcessConsoleInput = nil
export.GetContentFields = nil
export.GetContentData = nil
local allAreas = band(MacroCallFar(MCODE_F_GETOPTIONS),0x3) == 0
local numerrors=0
local newAreas = {}
Events = {}
EnumState = {}
LoadedMacros = {}
AddedMenuItems = {}
AddedPrefixes = { [1]="" }
IdSet = {}
LoadedPanelModules = {}
ContentColumns = {}
if Shared.panelsort then Shared.panelsort.DeleteSortModes() end
local AreaNames = allAreas and AllAreaNames or SomeAreaNames
for _,name in pairs(AreaNames) do newAreas[name]={} end
for _,name in ipairs(EventGroups) do Events[name]={} end
for k in pairs(package.loaded) do
if initial_modules[k]==nil and not package.nounload[k] then
package.loaded[k]=nil
end
end
-- Copy macros loaded by MCTL_ADDMACRO to save them from destruction.
if Areas then
local IdUpdated = {}
for a,areatable in pairs(Areas) do
for k,macroarray in pairs(areatable) do
for _,m in ipairs(macroarray) do
if m.guid and not m.disabled then
newAreas[a][k] = newAreas[a][k] or {}
table.insert(newAreas[a][k], m)
if not IdUpdated[m] then
IdUpdated[m] = true
m.index = #LoadedMacros+1
LoadedMacros[m.index] = m
end
end
end
end
end
end
Areas = newAreas
if not unload then
LoadCounter = LoadCounter + 1
local DummyFunc = function() end
if 0 == band(MacroCallFar(MCODE_F_GETOPTIONS),0x10) then -- not ReadOnlyConfig
for _,v in ipairs {"scripts", "modules", "lib32", "lib64"} do
win.CreateDir(MacroDirs.MainPath.."/"..v)
end
--win.CreateDir(win.GetEnv("HOME").."/.config/far2l/Menus")
end
local moonscript = require "moonscript"
local FuncList1 = {"Macro", "Event", "MenuItem", "CommandLine", "PanelModule", "ContentColumns"}
local FuncList2 = {"NoMacro","NoEvent","NoMenuItem","NoCommandLine","NoPanelModule","NoContentColumns"}
local function LoadRegularFile (FindData, FullPath, macroinit)
if FindData.FileAttributes:find("d") then return end
if macroinit and #FullPath==#macroinit and far.LStricmp(FullPath,macroinit)==0 then
return
end
local isMoonScript = string_find(FullPath, "[nN]", -1)
local f, msg = (isMoonScript and moonscript.loadfile or loadfile)(FullPath)
if not f then
numerrors=numerrors+1
ErrMsgLoad(msg,FullPath,isMoonScript,"compile")
return
end
local env = {
Macro = function(t) return not not AddRegularMacro(t,FullPath) end;
Event = function(t) return not not AddEvent(t,FullPath) end;
MenuItem = function(t) return AddMenuItem(t,FullPath) end;
CommandLine = function(t) return AddPrefixes(t,FullPath) end;
PanelModule = function(t) return AddPanelModule(t,FullPath) end;
ContentColumns = function(t) return AddContentColumns(t,FullPath) end;
}
for _,name in ipairs(FuncList2) do env[name]=DummyFunc; end
setmetatable(env,gmeta)
setfenv(f, env)
local ok, msg = xpcall(function() return f(FullPath, LoadCounter) end, debug.traceback)
if ok then
for _,name in ipairs(FuncList1) do env[name]=nil; end
for _,name in ipairs(FuncList2) do env[name]=nil; end
else
numerrors=numerrors+1
msg = string.gsub(msg,"\n\t","\n ")
ErrMsgLoad(msg,FullPath,isMoonScript,"run")
end
end
local tempRecordedMacro
local function ReadRecordedMacro (m)
if tempRecordedMacro == nil then
if type(m) == "table" then
local t_action, t_code = type(m.action), type(m.code)
tempRecordedMacro = type(m.area)=="string" and type(m.key)=="string" and
(t_action=="function" and t_code=="nil" or t_action=="nil" and t_code=="string") and m
else
tempRecordedMacro = false
end
end
end
local function LoadRecordedFile (FindData, FullPath)
if FindData.FileAttributes:find("d") then return end
local f, msg = loadfile(FullPath)
if not f then
numerrors=numerrors+1; ErrMsg(msg); return
end
local env = setmetatable({ Macro=ReadRecordedMacro }, gmeta)
setfenv(f, env)
tempRecordedMacro = nil
local ok, msg = xpcall(f, debug.traceback)
if ok then
if tempRecordedMacro then
env.Macro = nil
AddRecordedMacro(tempRecordedMacro, FullPath)
end
else
msg = msg:gsub("\n\t","\n ")
numerrors=numerrors+1; ErrMsg(msg)
end
end
paths = paths and ExpandEnv(paths) or MacroDirs.MainPath.."/scripts;"..MacroDirs.LoadPathList
for p in paths:gmatch("[^;]+") do
p = far.ConvertPath(p, F.CPM_FULL) -- needed for relative paths
local macroinit = p:gsub("/*$", "/_macroinit.lua")
local info = win.GetFileInfo(macroinit)
if info and not info.FileAttributes:find("d") then
LoadRegularFile(info, macroinit, nil)
else
macroinit = nil
end
far.RecursiveSearch (p, "*.lua,*.moon", LoadRegularFile, bor(F.FRS_RECUR,F.FRS_SCANSYMLINK), macroinit)
end
far.RecursiveSearch (MacroDirs.MainPath.."/internal", "*.lua", LoadRecordedFile, 0)
export.ExitFAR = Events.exitfar[1] and export_ExitFAR
export.ProcessDialogEvent = Events.dialogevent[1] and export_ProcessDialogEvent
export.ProcessEditorInput = Events.editorinput[1] and export_ProcessEditorInput
export.ProcessViewerEvent = Events.viewerevent[1] and export_ProcessViewerEvent
export.ProcessConsoleInput = Events.consoleinput[1] and export_ProcessConsoleInput
if ContentColumns[1] then
export.GetContentFields = export_GetContentFields
export.GetContentData = export_GetContentData
end
LoadMacrosDone = true
end
LoadingInProgress = nil
return numerrors==0
end
local function InitMacroSystem()
LoadMacros(true)
end
local function WriteOneMacro (dir, macro, keyname, delete)
local fname = ("%s/%s_%s.lua"):format(dir, macro.area, (keyname:gsub(".", CharNames)))
local attr = win.GetFileAttr(fname)
if attr then
win.SetFileAttr(fname, "")
win.DeleteFile(fname)
end
if delete then return end
-- operation "write"
local fp = io.open(fname, "w")
if fp then
fp:write(([[
Macro {
description=%q;
area=%q; key=%q;
flags=%q;
code=%q;
}
]]):format(macro.description, macro.area, macro.key, FlagsToString(macro.flags), macro.code))
fp:close()
macro.FileName = fname
end
end
local function WriteMacros()
if 0 ~= band(MacroCallFar(MCODE_F_GETOPTIONS),0x10) then return end -- ReadOnlyConfig
local dir = MacroDirs.MainPath.."/internal"
if not win.CreateDir(dir, true) then return end
for areaname,area in pairs(Areas) do
for keyname,macroarray in pairs(area) do
local macro = macroarray.recorded
if macro and macro.needsave then
WriteOneMacro(dir, macro, macro.key, macro.disabled)
macro.needsave = nil
if macro.disabled then
macroarray.recorded = nil
end
end
end
end
return true
end
local function GetFromMenu (menuitems, area, key)
for _,item in ipairs(menuitems) do
local descr = item.macro.description
if not descr or descr=="" then
descr = Msg.UtNoDescription_Index:format(item.macro.index)
end
item.text = descr
item.selected = item.macro.selected
end
table.sort(menuitems,
function(item1,item2)
local p1,p2 = item1.priority, item2.priority
local s1,s2 = item1.macro.sortpriority or 50, item2.macro.sortpriority or 50
return p1>p2 or p1==p2 and (s1>s2 or s1==s2 and far.LStricmp(item1.text, item2.text) < 0)
end)
local pos_sep
for i,item in ipairs(menuitems) do
if item.priority < menuitems[1].priority then
pos_sep = i; break
end
end
local bkeys = { {BreakKey="A+F4"} }
for i,item in ipairs(menuitems) do
local ch = i<10 and tostring(i) or i<36 and string.char(i+55)
if ch then
local pos = pos_sep and i>=pos_sep and i+1 or i
item.text = ch..". "..item.text
table.insert(bkeys, {BreakKey=ch, pos=pos})
if i>=10 then table.insert(bkeys, {BreakKey=ch:lower(), pos=pos}) end
end
end
if pos_sep then
table.insert(menuitems, pos_sep, {separator=true, text=Msg.UtLowPriority})
end
local props = {
Title = ("%s: %s | %s"):format(Msg.UtExecuteMacroTitle, area, key),
Bottom = Msg.UtExecuteMacroBottom,
Flags = { FMENU_WRAPMODE=1, FMENU_CHANGECONSOLETITLE=1 },
Id = win.Uuid("165AA6E3-C89B-4F82-A0C5-C309243FD21B") }
while true do
local item, pos = far.Menu(props, menuitems, bkeys)
if not item then
return
elseif item.macro then
return item.macro
elseif item.BreakKey == "A+F4" then
props.SelectIndex = pos
local m = menuitems[pos].macro
if m.FileName then
local startline = m.action and debug.getinfo(m.action,"S").linedefined
editor.Editor(m.FileName,nil,nil,nil,nil,nil,nil,startline,nil,65001)
end
elseif item.pos then
return menuitems[item.pos].macro
end
end
end
local function GetMacro (argMode, argKey, argUseCommon, argCheckOnly)
if LoadingInProgress then return end
local area = GetAreaName(argMode)
if not area then return end -- трюк используется в CheckForEscSilent() в Фаре
local key = argKey:lower()
do
local alt
local from,to,ctrl = string_find(key, "^(r?ctrl)")
if ctrl=="ctrl" then ctrl="lctrl" end
local start = to and to+1 or 1
from,to,alt = string_find(key, "^(r?alt)", start)
if alt=="alt" then alt="lalt" end
start = to and to+1 or start
key = (ctrl or "") .. (alt or "") .. string_sub(key, start)
end
local Names = { area, argUseCommon and area~="common" and "common" or nil }
-- First, check "keyboard-recorded" macros, they have the highest priority.
for _,areaname in ipairs(Names) do
local areatable = Areas[areaname]
if areatable and areatable[key] then
local m = areatable[key].recorded
if m and not m.disabled and (argCheckOnly or MacroCallFar(MCODE_F_CHECKALL,argMode,m.flags,nil,nil)) then
return m, areaname, true
end
end
end
-- Create collector table: keys are macros, values are indexes into CInfo.
-- For each macro, CInfo stores 2 consecutive values: dynamic priority and found area.
local Collector, CInfo = {}, {}
-- Filter macros by filemask and flags. Put the "successful" ones in the collector.
local filename = area=="editor" and editor.GetFileName() or area=="viewer" and viewer.GetFileName()
local function ExamineMacro (m, areaname)
local check = not (filename and m.filemask) or CheckFileName(m.filemask, filename)
if check and MacroCallFar(MCODE_F_CHECKALL, GetAreaCode(area), m.flags, m.callback, m.callbackId) then
if not Collector[m] then
local n = #CInfo + 1
Collector[m] = n
CInfo[n] = m.priority or 50
CInfo[n+1] = areaname
end
end
end
for _,areaname in ipairs(Names) do
local areatable = Areas[areaname]
if areatable then
local macros = areatable[key]
if macros then
for _,m in ipairs(macros) do
if not m.disabled then
if argCheckOnly then return m, areaname end
ExamineMacro(m, areaname)
end
end
end
local macros_regex = areatable[1]
if macros_regex then
for _,m in ipairs(macros_regex) do
if not m.disabled and m.keyregex:match(key) then
if argCheckOnly then return m, areaname end
ExamineMacro(m, areaname)
end
end
end
end
end
if not next(Collector) then return end
-- Filter macros by condition() where available; update dynamic priorities.
-- Calculate maximal priority and number of macros left in the container.
local max_priority = -1
local nummacros = 0
for m,p in pairs(Collector) do
if m.condition then
local pr = m.condition(argKey, m.data) -- unprotected call
if pr then
if type(pr)=="number" then
CInfo[p] = pr>100 and 100 or pr<0 and 0 or pr
end
else
Collector[m] = nil
end
end
if Collector[m] then
nummacros = nummacros + 1
if max_priority < CInfo[p] then max_priority = CInfo[p] end
end
end
if nummacros == 0 then return end
-- If only 1 macro is left, do return it.
if nummacros == 1 then
local m = next(Collector)
return m, CInfo[Collector[m]+1]
end
-- Make an array with highest priority macros.
local macrolist = {}
local nindex = nil
for m,p in pairs(Collector) do
macrolist[#macrolist+1] = { macro=m; priority=CInfo[p] }
if CInfo[p] == max_priority then
nindex = nindex and -1 or #macrolist
end
end
if nindex > 0 then
local m = macrolist[nindex].macro
return m, CInfo[Collector[m]+1]
end
-- Make order of macros in the menu consistent
table.sort(macrolist, function(m1,m2) return Collector[m1.macro] < Collector[m2.macro] end)
local m = GetFromMenu(macrolist, GetTrueAreaName(argMode), argKey)
if m then return m, CInfo[Collector[m]+1] end
return {}, nil
end
local function GetMacroWrapper (argMode, argKey, argUseCommon)
local macro,area,kb_macro = GetMacro(argMode, argKey, argUseCommon, true)
if macro then
kb_macro = not not kb_macro -- convert to boolean
LastMessage = pack(GetAreaCode(area), macro.code or "", macro.description or "", macro.flags, kb_macro)
return LastMessage
end
end
local function ProcessRecordedMacro (Mode, Key, code, flags, description)
local Area = GetTrueAreaName(Mode)
local area, key = Area:lower(), Key:lower()
local keys,numkeys = ExpandKey(Key)
if code == "" then -- удаление
for i=1,numkeys do
local k = keys[i]
local m = Areas[area][k] and Areas[area][k].recorded or
Areas["common"][k] and Areas["common"][k].recorded
if m then
m.disabled,m.needsave = true,true
break
end
end
return
end
local macro = {
area=Area, key=Key, code=code, flags=flags, description=description,
needsave=true
}
local existing = Areas[area][keys[1]] and Areas[area][keys[1]].recorded
macro.index = existing and existing.index or #LoadedMacros+1
LoadedMacros[macro.index] = macro
for i=1,numkeys do
local k = keys[i]
Areas[area][k] = Areas[area][k] or {}
Areas[area][k].recorded = macro
end
end
local function AddMacroFromFAR (mode, key, lang, code, flags, description, guid, callback, callbackId, priority)
local area = GetTrueAreaName(mode)
local m = AddRegularMacro { area=area, key=key, code=code, flags=flags, description=description,
guid=guid, callback=callback, callbackId=callbackId, language=lang, priority=priority }
local action = m and m.action
if action then
local env = setmetatable({}, gmeta)
setfenv(action, env)
end
return not not m
end
local function DelMacro (guid, callbackId) -- MCTL_DELMACRO
for _,areatable in pairs(Areas) do
for _,macroarray in pairs(areatable) do
for _,m in ipairs(macroarray) do
if m.guid and m.guid==guid and m.callbackId==callbackId and not m.disabled then
m.disabled = true
return true
end
end
end
end
end
local function RunStartMacro()
if not LoadMacrosDone then return end
local mode = far.MacroGetArea()
local opt = band(MacroCallFar(MCODE_F_GETOPTIONS),0x3)
local mtable = opt==1 and Areas.editor or opt==2 and Areas.viewer or Areas.shell
for k=1,2 do
if k==2 then mtable = Areas.common end
for _,macros in pairs(mtable) do
local m = macros.recorded
if m and not m.disabled and m.flags and band(m.flags,0x8)~=0 and not m.autostartdone then
m.autostartdone=true
if MacroCallFar(MCODE_F_CHECKALL, mode, m.flags) then
Shared.keymacro.PostNewMacro(m, m.flags, nil, true)
end
end
for _,m in ipairs(macros) do
if not m.disabled and m.flags and band(m.flags,0x8)~=0 and not m.autostartdone then
m.autostartdone=true
if MacroCallFar(MCODE_F_CHECKALL, mode, m.flags) then
if not m.condition or m.condition(nil, m.data) then
Shared.keymacro.PostNewMacro(m, m.flags, nil, true)
end
end
end
end
end
end
return true
end
local function GetMacroCopy (index)
if LoadedMacros[index] then
local t={}
for k,v in pairs(LoadedMacros[index]) do t[k]=v end
return t
end
return nil
end
local function EnumScripts (ScriptType)
local ScriptOrigin = {
CustomSortModes = Shared.panelsort.GetCustomSortModes(),
Event = LoadedMacros,
Macro = LoadedMacros,
MenuItem = AddedMenuItems,
CommandLine = AddedPrefixes,
PanelModule = LoadedPanelModules,
ContentColumns = ContentColumns,
}
local ScriptFilter = {
Event = function (index) return LoadedMacros[index].group end,
Macro = function (index) return LoadedMacros[index].area end,
MenuItem = function (index) return type(index) == "number" end,
CommandLine = function (index) return index ~= 1 end,
PanelModule = function (index) return type(index) == "number" end,
}
local function copy(source)
local t={}
for k,v in pairs(source) do
if type(v) == "table" and k ~= "data" then
v = copy(v)
end
t[k]=v
end
return t
end
local origin = ScriptOrigin[ScriptType]
if not origin then
error("Wrong argument: " .. tostring(ScriptType))
end
local index
return function()
while true do
index = next(origin, index)
if not index then return nil end
local filter = ScriptFilter[ScriptType]
if not filter or filter(index) then
return copy(origin[index]), index
end
end
end
end
local function EditUnsavedMacro (index)
local m = LoadedMacros[index]
if m and m.code then
local flags, code, descr = MacroCallFar(MCODE_F_MACROSETTINGS, m.key, m.flags, m.code, m.description or "")
if flags then
m.flags, m.code, m.description = flags, code, descr
end
end
end
return {
AddMacroFromFAR = AddMacroFromFAR,
CheckFileName = CheckFileName,
DelMacro = DelMacro,
EditUnsavedMacro = EditUnsavedMacro,
EnumMacros = EnumMacros,
EnumScripts = EnumScripts,
FixInitialModules = FixInitialModules,
FlagsToString = FlagsToString,
GetAreaCode = GetAreaCode,
GetMacro = GetMacro,
GetMacroCopy = GetMacroCopy,
GetMacroWrapper = GetMacroWrapper,
GetMenuItems = function() return AddedMenuItems end,
GetMoonscriptLineNumber = GetMoonscriptLineNumber,
GetPrefixes = function() return AddedPrefixes end,
GetTrueAreaName = GetTrueAreaName,
InitMacroSystem = InitMacroSystem,
LoadingInProgress = function() return LoadingInProgress end,
LoadMacros = LoadMacros,
ProcessRecordedMacro = ProcessRecordedMacro,
RunStartMacro = RunStartMacro,
UnloadMacros = InitMacroSystem,
WriteMacros = WriteMacros,
GetPanelModules = function() return LoadedPanelModules end
}
|
local page = 1
local pages = {
{
header="Credits",
body="darkness #1\nfeatures audio from the film 5 Centimeters per Second\n\ndarkness #3\nfeatures a photograph of Earth that I can no longer track down the source of :(\n\ndarkness #6\nfeatures video from YouTube user maxxlover's channel\n\ndarkness #8\nfeatures visual art from xkcd#1190, \"Time\"\n\ndarkness #10\nfeatures the song \"13 Ghosts II\" by nine inch nails\n\ndarkness #12\nfeatures a melody inspired by bt's \"The Antikythera Mechanism\""
},
{
header="Credits: darknesss #14–17 (Connection)",
body="Luizsan – contributed primary visual art\n\nMahendor – composed Connection's main theme\n\nLumisauVA – voice acted in Chapter 4\n\nkbts87 – contributed visual art to Chapter 3\n\nEvocait – contributed visual art to Chapter 4"
},
{
header="Credits: darkness #19 (Your Drifting Mind)",
body="Evocait – contributed primary visual art\n\nanairis_q – provided voice acting"
},
{
header="Thanks",
body="I wish to thank the many creative humans whose works have shaped my human outlook and my artistic output, including:\n\nMakoto Shinkai, Charlie Kaufman, Greta Gerwig, Wong Kar-wai\n\nSylvia Plath, Kazuo Ishiguro, Milan Kundera,\nMark Z. Danielewski, _why\n\nBill Watterson, Randall Munroe\n\nbt, Benn Jordan, Laura Shigihara, Trent Reznor, Frédéric Chopin\n\nMeine Meinung, Caliko, Mahendor\n\nGiant Sparrow, Kojima Productions, Unburnt Witch,\nRyan and Amy Green"
},
{
header="Thanks",
body="If you've made it this far, thanks for staying with me,\nhere in the darkness, for a while.\n\nIt means the world to me."
}
}
local Cancel = function(self)
self:finishtweening():smooth(0.5):diffuse(0,0,0,1):queuecommand("Transition")
end
local ChangePage = function(self)
self:GetChild("Header"):finishtweening():smooth(0.2):diffuse(0,0,0,1):sleep(0.2):queuecommand("Refresh")
self:GetChild("Body"):finishtweening():smooth(0.2):diffuse(0,0,0,1):sleep(0.2):queuecommand("Refresh")
end
local af = Def.ActorFrame{
InitCommand=function(self) self:diffuse(0,0,0,1) end,
OnCommand=function(self) self:smooth(1):diffuse(1,1,1,1) end,
InputEventCommand=function(self, event)
if event.type == "InputEventType_FirstPress" then
if event.GameButton=="Start" or event.GameButton=="MenuRight" then
if pages[page+1] then
page = page + 1
ChangePage(self)
else
Cancel(self)
end
elseif event.GameButton=="MenuLeft" then
if pages[page-1] then
page = page - 1
ChangePage(self)
end
elseif event.GameButton=="Back" then
Cancel(self)
end
end
end,
TransitionCommand=function(self)
SCREENMAN:GetTopScreen():StartTransitioningScreen("SM_GoToNextScreen")
end
}
af[#af+1] = Def.BitmapText{
Name="Header",
Text=pages[1].header,
File=THEME:GetPathB("ScreenHereInTheDarkness", "overlay/_shared/helvetica neue/_helvetica neue 20px.ini"),
InitCommand=function(self) self:vertalign(top):xy(_screen.cx, 30):zoom(1.2) end,
RefreshCommand=function(self) self:settext(pages[page].header):smooth(0.25):diffuse(1,1,1,1) end
}
af[#af+1] = Def.BitmapText{
Name="Body",
Text=pages[1].body,
File=THEME:GetPathB("ScreenHereInTheDarkness", "overlay/_shared/helvetica neue/_helvetica neue 20px.ini"),
InitCommand=function(self) self:align(0,0):xy(_screen.cx-240, 80):wrapwidthpixels(480/0.85):zoom(0.85) end,
RefreshCommand=function(self) self:settext(pages[page].body):smooth(0.25):diffuse(1,1,1,1) end
}
return af |
cli_args = {}
local optionless = {
"--help",
"--datadir",
}
local shorts = {
['-h'] = '--help',
['-hh'] = '--helpinfo',
['-k'] = '--keyfile',
['-d'] = '--datafile',
['-D'] = '--datadir',
['-m'] = '--mode',
['-f'] = '--file',
['-l'] = '--length',
['-p'] = '--pattern',
}
local in_table = function(query, tbl)
for i=1, #tbl do
if tbl[i] == query then
return true
end
end
return false
end
local argparse = function()
cli_args['progname'] = arg[0]
local current_flag = '(none)'
-- Translate short to long
local narg = {}
for i=1, #arg do
for short, long in pairs(shorts) do
if arg[i] == short then
narg[i] = long
end
end
if narg[i] == nil then
narg[i] = arg[i]
end
end
arg = narg
for i=1, #arg do
-- Set main flags
if string.sub(arg[i], 1, 2) == '--' and not in_table(arg[i], optionless) then
current_flag = string.sub(arg[i], 3)
-- Allow number parsing...
if tonumber(arg[i + 1]) then
cli_args[current_flag] = tonumber(arg[i + 1])
else
cli_args[current_flag] = arg[i + 1]
end
i = i + 1
-- Set optionless flags
elseif string.sub(arg[i], 1, 2) == '--' then
current_flag = string.sub(arg[i], 3)
cli_args[current_flag] = true
end
end
end
argparse()
|
return {
tag = 'window',
summary = 'Check if the window is created.',
description = 'Returns whether the desktop window is currently created.',
arguments = {},
returns = {
{
name = 'present',
type = 'boolean',
description = 'Whether a window is created.'
}
},
notes = 'Most of the `lovr.graphics` functionality will only work if a window is created.',
related = {
'lovr.graphics.createWindow',
'lovr.conf'
}
}
|
-- Copyright 2016 Google Inc, NYU.
--
-- 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.
-- Simply a nn wrapper around tfluids.setWallBcs.
--
-- The inputs must be batched.
local nn = require('nn')
local SetWallBcs, parent = torch.class('tfluids.SetWallBcs', 'nn.Module')
function SetWallBcs:__init()
parent.__init(self)
self.gradInput = {torch.Tensor(), torch.Tensor()}
self.mask = torch.Tensor()
end
function SetWallBcs:updateOutput(input)
assert(torch.type(input) == 'table' and #input == 2)
local U = input[1]
local flags = input[2]
self.output:resizeAs(U)
self.output:copy(U)
-- Create a 0 mask (i.e. solid velocities will be set to zero). Doing it this
-- way means that we can reuse this mask during BPROP.
self.mask:resizeAs(U):fill(1)
tfluids.setWallBcsForward(self.mask, flags)
-- TODO(tompson): if we ever switch to using non-zero obstacle velocities
-- this "mask strategy" will not work.
self.output:cmul(self.mask)
return self.output
end
function SetWallBcs:updateGradInput(input, gradOutput)
-- Assume updateOutput has been called.
local U = input[1]
local flags = input[2]
self.gradInput[1]:resizeAs(gradOutput):fill(0)
self.gradInput[2]:resizeAs(flags):fill(0) -- Fill with 0.
-- A trick: the forward call just zeros out velocities based on the flag
-- grid. Therefore we can simply copy the gradOutput and treat it as an
-- input velocity and call the forward function.
self.gradInput[1]:addcmul(1, self.mask, gradOutput)
return self.gradInput
end
function SetWallBcs:accGradParameters(input, gradOutput, scale)
-- No learnable parameters.
end
function SetWallBcs:accUpdateGradParameters(input, gradOutput, lr)
-- No learnable parameters.
end
function SetWallBcs:type(type)
parent.type(self, type)
for i = 1, #self.gradInput do
self.gradInput[i] = self.gradInput[i]:type(type)
end
return self
end
function SetWallBcs:clearState()
parent.clearState(self)
-- The parent clearState call will (for some reason) completely clear the
-- gradInput table, so we have to re-allocate the tensors.
self.gradInput = {torch.Tensor(), torch.Tensor()}
for i = 1, #self.gradInput do
self.gradInput[i] = self.gradInput[i]:type(torch.type(self.output))
end
self.mask:set()
end
|
require('Comment').setup({
---Add a space b/w comment and the line
---@type boolean|fun():boolean
padding = true,
---Whether the cursor should stay at its position
---NOTE: This only affects NORMAL mode mappings and doesn't work with dot-repeat
---@type boolean
sticky = true,
---Lines to be ignored while comment/uncomment.
---Could be a regex string or a function that returns a regex string.
---Example: Use '^$' to ignore empty lines
---@type string|fun():string
ignore = nil,
---LHS of toggle mappings in NORMAL + VISUAL mode
---@type table
toggler = {
---Line-comment toggle keymap
line = 'gcc',
---Block-comment toggle keymap
block = 'gbc',
},
---LHS of operator-pending mappings in NORMAL + VISUAL mode
---@type table
opleader = {
---Line-comment keymap
line = 'gc',
---Block-comment keymap
block = 'gb',
},
---LHS of extra mappings
---@type table
extra = {
---Add comment on the line above
above = 'gcO',
---Add comment on the line below
below = 'gco',
---Add comment at the end of line
eol = 'gcA',
},
---Create basic (operator-pending) and extended mappings for NORMAL + VISUAL mode
---NOTE: If `mappings = false` then the plugin won't create any mappings
---@type boolean|table
mappings = {
---Operator-pending mapping
---Includes `gcc`, `gbc`, `gc[count]{motion}` and `gb[count]{motion}`
---NOTE: These mappings can be changed individually by `opleader` and `toggler` config
basic = true,
---Extra mapping
---Includes `gco`, `gcO`, `gcA`
extra = true,
---Extended mapping
---Includes `g>`, `g<`, `g>[count]{motion}` and `g<[count]{motion}`
extended = false,
},
---Pre-hook, called before commenting the line
---@type fun(ctx: Ctx):string
pre_hook = nil,
---Post-hook, called after commenting is done
---@type fun(ctx: Ctx)
post_hook = nil,
})
|
local app = app
local Env = require "Env"
local Class = require "Base.Class"
local ChainBase = require "Chain.Base"
local HeaderSection = require "Chain.HeaderSection"
local FooterSection = require "Chain.FooterSection"
local EmptySection = require "Chain.EmptySection"
local Busy = require "Busy"
local ply = app.SECTION_PLY
-- Patch Class
local Patch = Class {}
Patch:include(ChainBase)
function Patch:init(args)
ChainBase.init(self, args)
self:setClassName("Chain.Patch")
local unit = args.unit or app.logError("%s.init: unit is missing.", self)
self.unit = unit
if args.band then
self.pChain = unit.pUnit:getBand(args.band - 1)
else
self.pChain = unit.pUnit -- expected type is CustomUnit
end
self.stopCount = 1
self:disableSelection()
self.headerSection = HeaderSection(self.title, self.subTitle, 0)
self.footerSection = FooterSection(self.channelCount)
self:subscribe("contentChanged", self.footerSection)
self:appendSection(self.headerSection)
self:appendSection(self.footerSection)
self:insertEmptySection()
self:setSelection(self.emptySection, "expanded", 0)
self:enableSelection()
end
function Patch:getRootChain()
return self.unit:getRootChain()
end
function Patch:getOutputSource(i)
return self.unit:getOutputSource(i)
end
function Patch:getOutputDisplayName(channel)
return self.unit:getOutputDisplayName(channel)
end
function Patch:insertEmptySection()
if self.emptySection then return end
self.emptySection = EmptySection(4 * ply)
self:insertSection(self.emptySection, 2)
end
function Patch:clear()
local Utils = require "Utils"
Busy.start("Clearing: %s", Utils.shorten(self.unit.title, 42))
self:removeAllUnits()
Busy.stop()
end
function Patch:mnemonic()
local n = self:length()
if n == 0 then
return "empty"
elseif n == 1 then
return self:getUnit(1).mnemonic
else
local u1 = self:getUnit(1).mnemonic
local u2 = self:getUnit(n).mnemonic
return u1 .. ".." .. u2
end
end
function Patch:start()
if self.stopCount > 0 then
self.stopCount = self.stopCount - 1
if self.stopCount == 0 then
self.started = true
for _, unit in pairs(self.units) do unit:start() end
end
end
end
function Patch:stop()
if self.stopCount == 0 then
self.stopCount = 1
self.started = false
for _, unit in pairs(self.units) do unit:stop() end
else
self.stopCount = self.stopCount + 1
end
end
function Patch:serialize()
local t = {
lastPresetPath = self.lastPresetPath,
lastPresetFilename = self.lastPresetFilename,
firmwareVersion = app.FIRMWARE_VERSION,
instanceKey = self:getInstanceKey()
}
t.units = self:serializeUnits()
t.selection = self:serializeSelection()
return t
end
function Patch:deserialize(t)
self:startDeserialization()
self:setLastPreset(t.lastPresetPath, t.lastPresetFilename)
if t.instanceKey then self:setInstanceKey(t.instanceKey) end
self:deserializeUnits(t.units)
self:deserializeSelection(t.selection)
self:finishDeserialization()
end
-- reset the patch to its blank state
function Patch:releaseResources()
self:unsubscribe("contentChanged", self.footerSection)
self:removeAllUnits()
end
function Patch:enable(soft)
self:notifyUnits("enable", soft)
end
function Patch:disable(soft)
self:notifyUnits("disable", soft)
end
function Patch:upReleased(shifted)
if shifted then return false end
self:hide()
return true
end
function Patch:homeReleased()
self:hide()
return true
end
return Patch
|
local util = require("tests.test_util")
describe("treesitter rust", function()
it("parses all symbols correctly", function()
util.test_file_symbols("treesitter", "./tests/treesitter/rust_test.rs", {
{
kind = "Module",
name = "mod_1",
level = 0,
lnum = 1,
col = 0,
children = {
{
kind = "Enum",
name = "Enum_1",
level = 1,
lnum = 2,
col = 4,
},
{
kind = "Function",
name = "Fn_1",
level = 1,
lnum = 4,
col = 4,
},
{
kind = "Struct",
name = "MyStruct",
level = 1,
lnum = 6,
col = 4,
},
{
kind = "Interface",
name = "MyTrait",
level = 1,
lnum = 8,
col = 4,
children = {
{
kind = "Function",
name = "TraitFn",
level = 2,
lnum = 9,
col = 8,
},
},
},
{
kind = "Class",
name = "MyStruct",
level = 1,
lnum = 12,
col = 4,
children = {
{
kind = "Function",
name = "StructFn",
level = 2,
lnum = 13,
col = 8,
},
},
},
{
kind = "Class",
name = "MyStruct > Display",
level = 1,
lnum = 16,
col = 4,
children = {
{
kind = "Function",
name = "fmt",
level = 2,
lnum = 17,
col = 8,
},
},
},
},
},
})
end)
end)
|
local gl = require('galaxyline')
local status_line = {}
local colors = {}
colors.fg = function ()
if vim.g.vscode_style == "dark" then return '#ffffff' else return "#343434" end
end
colors.bg = function ()
if vim.g.vscode_style == "dark" then return '#252526' else return "#f3f3f3" end
end
colors.green = function ()
if vim.g.vscode_style == "dark" then return '#619955' else return "#008000" end
end
colors.bluegreen = function ()
if vim.g.vscode_style == "dark" then return '#4ec9b0' else return "#16825d" end
end
colors.yellow = function ()
if vim.g.vscode_style == "dark" then return '#ffaf00' else return "#795e26" end
end
colors.pink = function ()
if vim.g.vscode_style == "dark" then return '#c586c0' else return "#af00db" end
end
colors.yelloworrange = function ()
return "#d7ba7d"
end
colors.blue = function ()
return "#0a7aca"
end
colors.red = function ()
return "#f44747"
end
colors.lightblue = function ()
return "#5CB6F8"
end
status_line.setup = function ()
local condition = require('galaxyline.condition')
local gls = gl.section
gl.short_line_list = {'NvimTree', 'vista','dbui','packer'}
gls.left[1] = {
FirstElement = {
provider = function() return ' ' end,
highlight = {colors.bg,colors.bg}
},
}
gls.left[2] = {
ViMode = {
provider = function()
local mode_text = {
n = "NORMAL",
i = "INSERT",
V = "VISUAL",
R = "REPLACE",
c = "COMMAND"
}
return mode_text[vim.fn.mode()]
end,
separator = ' ',
separator_highlight = {colors.bg,colors.bg},
highlight = {colors.blue,colors.bg, "bold"},
},
}
gls.left[3] = {
GitIcon = {
provider = function() return '' end,
condition = condition.check_git_workspace,
separator = ' ',
separator_highlight = {colors.bg,colors.bg},
highlight = {colors.pink,colors.bg},
}
}
gls.left[4] = {
GitBranch = {
provider = 'GitBranch',
condition = condition.check_git_workspace,
separator = ' ',
separator_highlight = {colors.bg,colors.bg},
highlight = {colors.pink,colors.bg},
},
}
gls.left[5] = {
ShowLspClient = {
provider = 'GetLspClient',
condition = function ()
local tbl = {['dashboard'] = true,['']=true}
if tbl[vim.bo.filetype] then
return false
end
return true
end,
separator = ' ',
separator_highlight = {colors.bg,colors.bg},
highlight = {colors.bluegreen,colors.bg}
}
}
gls.left[6] = {
DiagnosticError = {
provider = 'DiagnosticError',
icon = ' ',
highlight = {colors.red,colors.bg}
}
}
gls.left[7] = {
DiagnosticWarn = {
provider = 'DiagnosticWarn',
icon = ' ',
highlight = {colors.yellow,colors.bg},
}
}
gls.left[8] = {
DiagnosticHint = {
provider = 'DiagnosticHint',
icon = ' ',
highlight = {colors.pink,colors.bg},
}
}
gls.left[9] = {
DiagnosticInfo = {
provider = 'DiagnosticInfo',
icon = ' ',
highlight = {colors.lightblue,colors.bg},
}
}
-- Right Side
gls.right[1] = {
FileSize = {
provider = 'FileSize',
condition = condition.buffer_not_empty,
highlight = {colors.fg,colors.bg}
}
}
gls.right[2] = {
LineInfo = {
provider = 'LineColumn',
highlight = {colors.fg,colors.bg},
},
}
gls.right[3] = {
PerCent = {
provider = 'LinePercent',
highlight = {colors.fg,colors.bg},
}
}
gls.right[4] = {
FileEncode = {
provider = 'FileEncode',
condition = condition.hide_in_width,
separator = ' ',
separator_highlight = {colors.bg,colors.bg},
highlight = {colors.fg,colors.bg}
}
}
gls.right[5] = {
FileFormat = {
provider = 'FileFormat',
condition = condition.hide_in_width,
separator = ' ',
separator_highlight = {colors.bg,colors.bg},
highlight = {colors.fg,colors.bg}
}
}
gls.right[6] ={
FileIcon = {
provider = 'FileIcon',
condition = condition.buffer_not_empty,
separator = ' ',
separator_highlight = {colors.bg,colors.bg},
highlight = {require('galaxyline.provider_fileinfo').get_file_icon_color,colors.bg},
},
}
gls.right[7] = {
FileName = {
provider = 'FileName',
condition = condition.buffer_not_empty,
highlight = {colors.green,colors.bg},
}
}
gls.short_line_left[1] = {
BufferType = {
provider = 'FileTypeName',
highlight = {colors.blue,colors.bg, "bold"}
}
}
gls.short_line_left[2] = {
SFileName = {
provider = 'SFileName',
condition = condition.buffer_not_empty,
highlight = {colors.bg,colors.bg}
}
}
gls.short_line_right[1] = {
BufferIcon = {
provider= 'BufferIcon',
highlight = {colors.bg,colors.bg}
}
}
end
return status_line
|
local api = vim.api
local fn = vim.fn
local cmd = vim.cmd
local sprior
local sgroup
local sname
local Sign = {}
function Sign:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
obj.items = {}
return obj
end
function Sign:place(lnum, bufnr)
bufnr = bufnr or api.nvim_get_current_buf()
if type(lnum) == 'table' then
local lnum_off_i = 1
local function place(p_list)
local ids = fn.sign_placelist(p_list)
for i = 1, #ids do
self.items[lnum[lnum_off_i]] = ids[i]
lnum_off_i = lnum_off_i + 1
end
end
local count, cycle = 0, 100
local place_list = {}
for _, l in ipairs(lnum) do
table.insert(place_list, {
id = 0,
group = sgroup,
name = sname,
buffer = bufnr,
lnum = l,
priority = sprior
})
count = count + 1
if count % cycle == 0 then
place(place_list)
count = 0
place_list = {}
end
end
if count > 0 then
place(place_list)
end
else
local id = fn.sign_place(0, sgroup, sname, bufnr, {lnum = lnum, priority = sprior})
self.items[lnum] = id
end
end
function Sign:unplace(lnum, bufnr)
bufnr = bufnr or api.nvim_get_current_buf()
if type(lnum) == 'table' then
local count, cycle = 0, 100
local unplace_list = {}
for _, l in ipairs(lnum) do
local id = self.items[l]
if id then
table.insert(unplace_list, {id = id, group = sgroup, buffer = bufnr})
self.items[l] = nil
count = count + 1
if count % cycle == 0 then
fn.sign_unplacelist(unplace_list)
count = 0
unplace_list = {}
end
end
end
if count > 0 then
fn.sign_unplacelist(unplace_list)
end
else
local id = self.items[lnum]
if id then
fn.sign_unplace(sgroup, {buffer = bufnr, id = id})
self.items[lnum] = nil
end
end
end
function Sign:list()
return self.items
end
function Sign:toggle(lnum, bufnr)
bufnr = bufnr or api.nvim_get_current_buf()
if type(lnum) == 'table' then
local p_lnum_list, up_lnum_list = {}, {}
for _, l in pairs(lnum) do
if self.items[l] then
table.insert(up_lnum_list, l)
else
table.insert(p_lnum_list, l)
end
end
self:place(p_lnum_list, bufnr)
self:unplace(up_lnum_list, bufnr)
else
if self.items[lnum] then
self:unplace(lnum, bufnr)
else
self:place(lnum, bufnr)
end
end
end
function Sign:reset(bufnr)
bufnr = bufnr or api.nvim_get_current_buf()
local p_lnum_list = {}
local signs = self.items
self:clear(bufnr)
for lnum in pairs(signs) do
table.insert(p_lnum_list, lnum)
end
self:place(p_lnum_list, bufnr)
end
function Sign:clear(bufnr)
self.items = {}
bufnr = bufnr or api.nvim_get_current_buf()
fn.sign_unplace(sgroup, {buffer = bufnr})
end
local function init()
sprior = 20
sgroup = 'BqfSignGroup'
sname = 'BqfSign'
cmd('hi default BqfSign ctermfg=14 guifg=Cyan')
fn.sign_define('BqfSign', {text = ' ^', texthl = 'BqfSign'})
end
init()
return Sign
|
gameNpcs.setOrder = function(npcName)
local npc = gameNpcs.characters[npcName]
local image = npc.image
local type = npc.type
local x = npc.x
local y = npc.y
local character = gameNpcs.orders
local order = table.randomKey(recipes)
--TFM.chatMessage('O escolhido é: '..npcName)
character.orderList[npcName] = {order = order, fulfilled = {}}
character.canOrder[npcName] = nil
do
local counter = 0
local orderPaperList = '' -- orders to show in the restaurant
player_removeImages(character.trashImages)
for i, v in next, character.orderList do
orderPaperList = orderPaperList .. i..'\n\n'
character.trashImages[#character.trashImages+1] = addImage(bagItems[v.order].png, "_1000", 14455, 1560+counter*28)
counter = counter + 1
end
ui.addTextArea(4444441, '<font size="10">'..orderPaperList, nil, 14495, 1580, nil, nil, 1, 1, 0)
end
local images = character.orderList[npcName].fulfilled
for _, player in next, jobs['chef'].working do
images[player] = {
icons = {
addImage('171c7ac4232.png', type.."1000", x, y-20, player),
addImage(bagItems[order].png, type.."1000", x+25, y-20, player),
},
completed = false,
}
end
local orderTime = math.random(60*2.5, 60*3)
addTimer(function(time)
if time == orderTime then
local images = character.orderList[npcName].fulfilled
for player, k in next, images do
if not k.completed then
player_removeImages(k.icons)
end
end
character.orderList[npcName] = nil
gameNpcs.setOrder(table.randomKey(character.canOrder))
character.canOrder[npcName] = true
end
end, 1000, orderTime)
end |
local function new()
local accelerometer
local joysticks = love.joystick.getJoysticks()
for i, joystick in ipairs(joysticks) do
if joystick:getName() == "Android Accelerometer" then
accelerometer = joystick
end
end
local function get_axis_x()
return accelerometer:getAxis(1)
end
local function get_axis_y()
return accelerometer:getAxis(2)
end
return {
get_x = get_axis_x,
get_y = get_axis_y,
}
end
return new
|
if mods['pyrawores'] and mods['pyhightech'] then
data:extend({
{
type = "technology",
name = "electric-boiler-mk1",
--prerequisites = {"automation"},
icon = "__electric_water_boiler__/graphics/icons/boiler1.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk1"
},
},
unit =
{
count = 10,
ingredients = {
{"automation-science-pack", 1}
},
time = 15
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk2",
prerequisites = {"electric-boiler-mk1"},
icon = "__electric_water_boiler__/graphics/icons/boiler2.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk1-2"
},
},
unit =
{
count = 50,
ingredients = {
{"automation-science-pack", 5}
},
time = 13,
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk3",
prerequisites = {"electric-boiler-mk2"},
icon = "__electric_water_boiler__/graphics/icons/boiler3.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk3"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk2-2"
},
},
unit =
{
count = 80,
ingredients = {
{"automation-science-pack", 13},
{"logistic-science-pack", 13}
},
time = 17
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk4",
prerequisites = {"electric-boiler-mk3"},
icon = "__electric_water_boiler__/graphics/icons/boiler4.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk4"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk3-2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk5"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk5-2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk4-2"
},
},
unit =
{
count = 75,
ingredients = {
{"automation-science-pack", 12},
{"logistic-science-pack", 12},
{"chemical-science-pack", 7}
},
time = 25
},
upgrade = true,
order = "[boiler]-1"
},
})
elseif mods['pyrawores'] then
data:extend({
{
type = "technology",
name = "electric-boiler-mk1",
--prerequisites = {"automation"},
icon = "__electric_water_boiler__/graphics/icons/boiler1.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk1"
},
},
unit =
{
count = 10,
ingredients = {
{"automation-science-pack", 1}
},
time = 15
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk2",
prerequisites = {"electric-boiler-mk1"},
icon = "__electric_water_boiler__/graphics/icons/boiler2.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk1-2"
},
},
unit =
{
count = 50,
ingredients = {
{"automation-science-pack", 5}
},
time = 13,
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk3",
prerequisites = {"electric-boiler-mk2"},
icon = "__electric_water_boiler__/graphics/icons/boiler3.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk3"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk2-2"
},
},
unit =
{
count = 80,
ingredients = {
{"automation-science-pack", 13},
{"logistic-science-pack", 13}
},
time = 17
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk4",
prerequisites = {"electric-boiler-mk3"},
icon = "__electric_water_boiler__/graphics/icons/boiler4.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk4"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk3-2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk5"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk5-2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk4-2"
},
},
unit =
{
count = 75,
ingredients = {
{"automation-science-pack", 12},
{"logistic-science-pack", 12},
{"chemical-science-pack", 7}
},
time = 25
},
upgrade = true,
order = "[boiler]-1"
},
})
elseif mods['pyhightech'] then
data:extend({
{
type = "technology",
name = "electric-boiler-mk1",
--prerequisites = {"automation"},
icon = "__electric_water_boiler__/graphics/icons/boiler1.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk1"
},
},
unit =
{
count = 10,
ingredients = {
{"automation-science-pack", 1}
},
time = 15
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk2",
prerequisites = {"electric-boiler-mk1"},
icon = "__electric_water_boiler__/graphics/icons/boiler2.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk1-2"
},
},
unit =
{
count = 50,
ingredients = {
{"automation-science-pack", 5}
},
time = 13,
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk3",
prerequisites = {"electric-boiler-mk2"},
icon = "__electric_water_boiler__/graphics/icons/boiler3.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk3"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk2-2"
},
},
unit =
{
count = 80,
ingredients = {
{"automation-science-pack", 13},
{"logistic-science-pack", 13}
},
time = 17
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk4",
prerequisites = {"electric-boiler-mk3"},
icon = "__electric_water_boiler__/graphics/icons/boiler4.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk4"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk3-2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk4-2"
},
},
unit =
{
count = 75,
ingredients = {
{"automation-science-pack", 12},
{"logistic-science-pack", 12},
{"chemical-science-pack", 7}
},
time = 25
},
upgrade = true,
order = "[boiler]-1"
},
})
else
data:extend({
{
type = "technology",
name = "electric-boiler-mk1",
prerequisites = {"automation"},
icon = "__electric_water_boiler__/graphics/icons/boiler1.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk1"
},
},
unit =
{
count = 50,
ingredients = {
{"automation-science-pack", 2},
{"logistic-science-pack", 1}
},
time = 5
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk2",
prerequisites = {"electric-boiler-mk1"},
icon = "__electric_water_boiler__/graphics/icons/boiler2.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk1-2"
},
},
unit =
{
count = 50,
ingredients = {
{"automation-science-pack", 7},
{"logistic-science-pack", 6}
},
time = 13,
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk3",
prerequisites = {"electric-boiler-mk2"},
icon = "__electric_water_boiler__/graphics/icons/boiler3.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk3"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk2-2"
},
},
unit =
{
count = 80,
ingredients = {
{"automation-science-pack", 13},
{"logistic-science-pack", 13},
{"chemical-science-pack", 10}
},
time = 17
},
upgrade = true,
order = "[boiler]-1"
},
{
type = "technology",
name = "electric-boiler-mk4",
prerequisites = {"electric-boiler-mk3"},
icon = "__electric_water_boiler__/graphics/icons/boiler4.png",
icon_size = 64,
effects =
{
{
type = "unlock-recipe",
recipe = "electric-boiler-mk4"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk3-2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk5"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk5-2"
},
{
type = "unlock-recipe",
recipe = "electric-boiler-mk4-2"
},
},
unit =
{
count = 50,
ingredients = {
{"automation-science-pack", 27},
{"logistic-science-pack", 21},
{"chemical-science-pack", 15},
{"production-science-pack", 10},
},
time = 25
},
upgrade = true,
order = "[boiler]-1"
},
})
end
|
local select, tostring = select, tostring;
local io_write = io.write;
module "logger"
local function format(format, ...)
local n, maxn = 0, #arg;
return (format:gsub("%%(.)", function (c) if c ~= "%" and n <= maxn then n = n + 1; return tostring(arg[n]); end end));
end
local function format(format, ...)
local n, maxn = 0, select('#', ...);
local arg = { ... };
return (format:gsub("%%(.)", function (c) if n <= maxn then n = n + 1; return tostring(arg[n]); end end));
end
function init(name)
return function (level, message, ...)
io_write(level, "\t", format(message, ...), "\n");
end
end
return _M;
|
LevelLoadingScreenGuiScript.old__init = LevelLoadingScreenGuiScript.old__init or LevelLoadingScreenGuiScript.init
function LevelLoadingScreenGuiScript:init(scene_gui, res, progress, base_layer)
self:old__init(scene_gui, res, progress, base_layer)
local title_text = "ESPERE"--managers.localization:text("debug_loading_level"))
self._level_title_text:set_text(title_text)
end |
--@brief 包含基础文件
local function loadBaseRequire()
require("EngineCore/config");
require("coreex/systemex");
require("coreex/coreex");
require("coreex/drawingex");
require("uiex/uiex")
require("uilibs/richText")
require("common/nativeEvent");
require("hall/gameData/regionConfigDataInterface");
require("globalConfig");
require("statesConfig");
require("audioConfig");
require("util/TableLib");
require("util/StringLib");
require("util/NumberLib");
require("util/log");
require("util/toolKit");
require("common/soundModule");
require("globalConstant");
require("netWork/ServerConfig");
require("common/httpModule");
require("hall/onlineSocket/onlineSocketManager");
require("hall/onlineSocket/globalSocketSleepManager");
require("common/timeoutModule");
require("animation/animFrameNew");
require("gameData/clientInfo");
require("gameBaseex/gameBaseex");
require("hall/hallConfig");
require("hall/common/gameManager");
require("libs/json_wrap");
end
--@brief 测试期间请使用 测试umeng 账号
local function isTestUmeng()
--local umengMetaValue = NativeEvent.getInstance():getMetaData();
-- Log.v("isTestUmeng" ,"umengMetaValue:" , umengMetaValue);
-- if _DEBUG then
-- local platform =sys_get_string("platform") or "";
-- if platform == kPlatformAndroid then
-- if umengMetaValue == kTestUmeng then
-- return false;
-- else
-- NativeEvent.getInstance():CloseStartScreen();
-- Toast.setDefaultDisplayTime(60 * 1000);
-- Toast.getInstance():showText("请在测试期间使用测试umeng 账号",50,30,kAlginLeft,"",26,255,255,255);
-- return true;
-- end
-- end
-- end
end
--@brief 初始化信息
local function init()
--基础文件包含
loadBaseRequire();
--初始化system
System.onInit();
--音频、日志、字符串设置
kEffectPlayer:setSoundFileMap(EffectsFileMap);
GameString.load("string","zh");
GameString.load("hall/php/stringPhpError", "zh");
TableView.setDefaultMaxClickOffset(10);
dict_set_int("log", "socket", _DEBUG and 1 or 0); --引擎socket日志开关,0--关、1--开。
local Framerate = require("framerate");
Framerate.show_fps(_DEBUG);
System.setToErrorLuaInWin32Enable(_DEBUG);
System.setAlertErrorEnable(_DEBUG);
System.setSocketLogEnable(_DEBUG);
System.setAndroidLogLuaErrorEnable(_DEBUG);
if not _DEBUG then
Application.instance():set_log_level(Application.LOG_NONE)
end
System.setLayoutWidth(1280);
System.setLayoutHeight(720);
socket_set_conn_timeout(kSocketRoom, 5000)
System.setImageFilterPicker( function() return kFilterLinear end);
System.setDefaultFontNameAndSize("simhei", 30);--设置系统字体大小
System.startTextureThreshold(); --设置纹理内存阀值
UIConfig.setScrollViewScrollBarWidth(0);
UIConfig.setScrollerUnitTurningFactor(0.10);--设置viewpager滑动宽度
Toast.setDefaultDisplayTime(2500);
Toast.setDefaultFontNameAndSize("simhei",30);
Toast.setDefaultColor(200,175,115);
Toast.setDefaultImage("hall/common/loading_bg.png");
Toast.setDefaultImageGridSpace(18,18,18,18);
ToolKit.lastLuaErrorCheck();
RegionConfigDataInterface.getInstance():setDebugSwitch(_DEBUG);
--检查umeng值是否正确
if isTestUmeng() then
return true;
end
--获取手机信息
kClientInfo:isVirtual();
kClientInfo:getPhoneInfo();
GameManager.initInstance();
--@brief 进入闪屏页
local function startSplashScreen()
if kPlatformWin32 == (sys_get_string("platform") or "") then
mainHandle_toHall()
else
require("hall/holidaysBg/data/holidaysBgDataInterface")
if HolidaysBgDataInterface.getInstance():isShowSplashScreen() then
kGameManager:startChangeScene(States.HolidaysBg, ScreenOrientationManager.eScreenOrien.LANDSCAPE, {1280,720}, false);
else
mainHandle_toHall()
end
end
end
-- 方便测试,自定义增加用户界面(先关闭,后续有需要再打开吧)
if _DEBUG and kPlatformWin32 == (sys_get_string("platform") or "") then
--win32情况下每一帧都进行3次垃圾回收
System.startCollectGarbage();
local t = {
callback = function(self,guid)
if type(guid) == "string" and guid ~= "" then
s_guid = guid;
kClientInfo:getPhoneInfo();
end
startSplashScreen()
end
};
new(require("guidMakePop"), t, t.callback);
else
startSplashScreen()
end
end
--1.此方法里面里面只能调用库里的方法,请不要引用其他任何的类
--2.程序第一次启动时,会去解压asset/games/hall.zip包
-- (添加成zip包的原因之一可以使apk的文件更小;注意内置多个游戏时,需要打成一个包,一是减少文件大小,二是解压速度更快)
--3.当程序apk版本有变化时,也会去解压asset/games/hall.zip
local function update_android()
local platformAndroid = "android";
local platform = sys_get_string("platform") or "";
local isUnZip = false; --标明是否需要解压
-- step 1:读取文件,获取是否已解压标识 0:未解压 1:已解压
dict_load("updateDidfinish");
isUnZip = (dict_get_int("updateDidfinish","updateStatus",0)==0);
print_string("解压状态 A updateStatus = " .. (isUnZip and "0" or "1") );
--step 2:判断安装方式 0 无变化 , 1 apk升级覆盖安装, 2 apk相同版本覆盖安装,3 apk 降级覆盖安装
local replaceInstall = dict_get_int("android_app_info","replaceInstall",0);
print_string("解压状态 B replaceInstall = " .. replaceInstall);
if replaceInstall >=1 then
--如果有变化
dict_set_int("android_app_info","replaceInstall",0);
if replaceInstall == 1 then
elseif replaceInstall == 2 or replaceInstall == 3 then
--android 中删除所有的lua代码
local storage_update_root_path = sys_get_string("storage_update_root");
local ret = os.rmdir(storage_update_root_path);
print_string("解压状态 删除 storage_update_root_path = " .. storage_update_root_path);
print_string("解压状态 C delete storage_update_root ret = " .. (ret and "true" or "false"));
end
end
isUnZip = isUnZip or (replaceInstall >=1);
--step 3:检查license文件
if not isUnZip then
--[[增强判断,在Android下有一种情况:当用户清除了数据,但是刚好update目录下有更新包,
程序启动时,引擎会加压更新包,结果更新下来发现有gameConfig文件,结果程序还是不能用的情况
]]
local fileName=(dict_get_string("android_app_info","files_path") or "") .. "/update/scripts/common/license.lua";
local _ret , _errMsg=loadfile(fileName);
isUnZip=(not _ret);--没找到文件需要解压
print_string("解压状态 D loadfile license ret = " .. (_ret and "true" or "false") );
end
-- 2.3.0 2.3.0
-- 2.3.0 2.3.0.0
-- 2.3.0.0 2.3.0
local function isSameApkVersion(oldApkVersionName, currentApkVersionName)
if oldApkVersionName == currentApkVersionName then
return true;
end
oldApkVersionName = string.gsub(oldApkVersionName, "%.", "");
currentApkVersionName = string.gsub(currentApkVersionName, "%.", "");
local intOldApkVersionName = tonumber(oldApkVersionName) or 0;
local intCurrentApkVersionName = tonumber(currentApkVersionName) or 0;
local big = math.max(intOldApkVersionName, intCurrentApkVersionName);
local small = math.min(intOldApkVersionName, intCurrentApkVersionName);
if big % small == 0 then
return true;
else
return false;
end
end
--step 4:检查hall/gameConfig文件中的_dependApkVersion是否和apkVersion一致
if not isUnZip then
local currentApkVersionName=dict_get_string("android_app_info","version_name") or "1.0.0";
local oldApkVersionName="0";
local fileName = (dict_get_string("android_app_info","files_path") or "") .. "/update/scripts/hall/gameConfig.lua";
local fun , errMsg=loadfile(fileName);
if fun then
fun();
oldApkVersionName = _dependApkVersion or "0";
end
-- currentApkVersionName == oldApkVersionName 不要使用== 防止2.3.0 2.3.0.0 不相同的情况出现
isUnZip = not isSameApkVersion(currentApkVersionName, oldApkVersionName);--3.版本号不一致需要解压
print_string("解压状态 E currentApkVersionName:" .. currentApkVersionName .. "_oldApkVersionName:".. oldApkVersionName);
end
if isUnZip then
--开始进行解压
dict_set_int("updateDidfinish","updateStatus",0);
dict_save("updateDidfinish");
local startTime=os.clock();
dict_set_string("LuaCallEvent","LuaCallEvent","unzipNewGames");--unzipNewGames zips
call_native("OnLuaCall");
--将解压标记置为true
dict_set_int("updateDidfinish","updateStatus",1);
dict_save("updateDidfinish");
local endTime=os.clock();
print_string("解压状态 F cost:" .. (endTime-startTime));
--解压完成,删除update目录
os.rmdir(sys_get_string("storage_update_zip") or "");
mainHandle_releaseRes();
to_lua("main.lua");
return true;
else
return false;
end
end
--@brief IOS更新包解压后重启虚拟机
--@note 接口方法, ios会直接回调这个方法
function onUnziped()
mainHandle_releaseRes();
--解压完成,删除update目录
os.rmdir(sys_get_string("storage_update_zip") or "");
to_lua("main.lua");
end
--@brief 进入大厅
function mainHandle_toHall()
local local_server_config = require("local_server_config");
if local_server_config.isSwitchOpen() then
local_server_config.connect_local_server( tonumber(s_guid) );
else
OnlineSocketManager.getInstance():openSocket();
if ServerConfig.getInstance():getDefendAttackSwitch() then
--如果本地配置的防攻击开关是开启的话,则去确认下本次启动开关的情况
ServerConfig.getInstance():requestDefendAttackConfig();
end
kGameManager:startGame(GameType.HALL);
local gameVersion = kGameManager:getGameVersion(GameType.HALL);
dict_set_string(kDFQPGame , kGameVersion ,gameVersion);
dict_save(kDFQPGame);
end
end
-- 添加一个总是显现的按钮,用于重启虚拟机
function mainHandle_restartVM()
mainHandle_releaseRes();
Sound.pauseMusic();
System.setLayoutWidth(1280);
System.setLayoutHeight(720);
to_lua("main.lua");
end
--@brief 释放资源
function mainHandle_releaseRes()
socket_room_close(-1);
res_delete_group(-1);
anim_delete_group(-1);
prop_delete_group(-1);
drawing_delete_all();
Clock.instance():cancel_all();
end
--@brief 入口函数
function mainHandle(width,height)
mainHandle_releaseRes();
math.randomseed(tostring(os.time()):reverse():sub(1, 6));
local platformAndroid = "android";
local platformIOS = "ios";
local platform = sys_get_string("platform") or "";
--if platform == platformAndroid then
-- local isUpdating = update_android();
-- if isUpdating then
-- return;
-- end
--end
local function deleteUnusableFilesWhenIosReplaceInstall()
if "ios" == (sys_get_string("platform") or "") then
local IosReplaceInstallLogic = require("hall/update/iosReplaceInstallLogic");
IosReplaceInstallLogic.deleteUnusableFilesWhenReplaceInstall();
end
end
--ios覆盖安装,删除无用文件
deleteUnusableFilesWhenIosReplaceInstall();
init();
end |
local M = {}
local function setup_edit()
require("Comment").setup({ mappings = { extra = false } })
require("todo-comments").setup({
keywords = {
FIX = {
icon = " ", -- icon used for the sign, and in search results
color = "error", -- can be a hex color, or a named color (see below)
alt = { "FIXME", "BUG", "FIXIT", "ISSUE", "fixme", "bug", "fixit", "issue" }, -- a set of other keywords that all map to this FIX keywords
-- signs = false, -- configure signs for some keywords individually
},
TODO = { icon = " ", color = "info", alt = { "todo" } },
HACK = { icon = " ", color = "warning" },
WARN = { icon = " ", color = "warning", alt = { "WARNING", "warn" } },
PERF = { icon = " ", alt = { "OPTIM", "PERFORMANCE", "OPTIMIZE" } },
NOTE = { icon = " ", color = "hint", alt = { "INFO", "info", "note" } },
},
})
require("neogen").setup({ enabled = true })
require("nvim-autopairs").setup({})
end
local function setup_search()
require("hlslens").setup({
calm_down = true,
nearest_only = true,
nearest_float_when = "always",
virt_priority = 1,
})
require("bqf").setup({ auto_reload = true, auto_resize_height = true })
end
local function setup_treesitter(opt)
local parser_config = require("nvim-treesitter.parsers").get_parser_configs()
parser_config.org = {
install_info = {
url = "https://github.com/milisims/tree-sitter-org",
revision = "main",
files = { "src/parser.c", "src/scanner.cc" },
},
filetype = "org",
}
require("nvim-treesitter.configs").setup({
ensure_installed = opt.ts_syntaxes,
highlight = {
enable = true,
-- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- Using this option may slow down your editor, and you may see some duplicate highlights.
-- Instead of true it can also be a list of languages
additional_vim_regex_highlighting = { "org" },
},
incremental_selection = { enable = true },
indent = { enable = true },
rainbow = {
enable = true,
extended_mode = true,
},
})
end
M.setup = function(opt)
opt = vim.tbl_deep_extend("keep", opt or {}, {})
setup_edit()
setup_search()
setup_treesitter(opt)
end
return M
|
//________________________________
//
// NS2 Combat Mod
// Made by JimWest and MCMLXXXIV, 2012
//
//________________________________
// combat_GUIUpgradeChamberDisplay.lua
local HotReload = CombatGUIUpgradeChamberDisplay
if(not HotReload) then
CombatGUIUpgradeChamberDisplay = {}
ClassHooker:Mixin("CombatGUIUpgradeChamberDisplay")
end
function CombatGUIUpgradeChamberDisplay:OnLoad()
ClassHooker:SetClassCreatedIn("GUIUpgradeChamberDisplay", "lua/GUIUpgradeChamberDisplay.lua")
_addHookToTable(self:PostHookClassFunction("GUIUpgradeChamberDisplay", "Initialize", "Initialize_Hook"))
end
// Hide the chamber GUI
function CombatGUIUpgradeChamberDisplay:Initialize_Hook(self)
self.background:SetIsVisible(false)
end
if (not HotReload) then
CombatGUIUpgradeChamberDisplay:OnLoad()
end |
local cjson = require("cjson")
local cjson_s = require("cjson.safe")
local inspect = require("inspect")
local string = string
local ipairs = ipairs
local pairs = pairs
local type = type
-- BEGIN Nginx test harness
local ngx = {}
function ngx.log(level, message)
print(level .. ": " .. message)
end
ngx.DEBUG = "DEBUG"
ngx.ERR = "ERROR"
ngx.HTTP_FORBIDDEN = "403"
ngx.HTTP_INTERNAL_SERVER_ERROR = "500"
ngx.HTTP_OK = "200"
function ngx.exit() os.exit() end
ngx.status = ''
-- END Nginx test harness
-- initialize the resty-keycloak instance
-- TODO: resolve all of the different ways the config file (keycloak.json) path could be provided to the extension. The config data needs to be loaded early.
local keycloak = {
_VERSION = "0.0.1"
}
-- default configuration
local keycloak_default_config = {
public_access_scope = "read-public",
}
-- this hash maps HTTP method to Keycloak scope
-- these scopes can be added to resources in Keycloak to limit authz rules to HTTP methods
local keycloak_scope_for_method = {
GET = "view",
HEAD = "view",
OPTIONS = "view",
DELETE = "write",
PATCH = "write",
POST = "write",
PUT = "write",
CONNECT = "debug",
TRACE = "debug",
}
-----------
-- Utility Functions
-- searches a table t for a value v
-- returns boolean
local function keycloak_table_has_value(t,v)
for ti,tv in pairs(t) do
if tv == v then return true end
end
return false
end
-----------
-- Private Functions
-- converts HTTP method into Keycloak scope or "extended" if unknown
-- eg. GET => read
local function keycloak_request_method_to_scope(method)
assert(type(method) == "string")
local scope = "extended" -- this scope is returned for unknown HTTP methods (eg. WebDAV)
-- if we have mapped the HTTP request method to a Keycloak scope, use that
if keycloak_scope_for_method[method] ~= nil then
scope = keycloak_scope_for_method[method]
end
return scope
end
local function keycloak_resource_set()
return {
"e06a803c-0da4-414d-a29d-269b1fbf8501",
"ffb605ca-5d5d-4f57-b24e-e5536d370e7b",
"87ea36a2-27a7-4b7b-b939-62a11bb5c5ad"
}
end
local function keycloak_resource(resource_id)
assert(type(resource_id) == "string")
local resources = {}
resources['e06a803c-0da4-414d-a29d-269b1fbf8501'] = {
name = "/",
owner = {
id = "31c4c56d-3fdf-43a1-ba84-ac5c1bd7d4f1"
},
ownerManagedAccess = false,
displayName = "Site root",
attributes = { },
_id = "e06a803c-0da4-414d-a29d-269b1fbf8501",
uris = { "/*", "/" },
resource_scopes = {
{ name = "read-public" },
{ name = "view" }
},
scopes = {
{ name = "read-public" },
{ name = "view" }
}
}
resources["ffb605ca-5d5d-4f57-b24e-e5536d370e7b"] = {
name = "/groupone/secrets/",
owner = {
id = "31c4c56d-3fdf-43a1-ba84-ac5c1bd7d4f1"
},
ownerManagedAccess = true,
displayName = "Group One Secrets",
attributes = { },
_id = "ffb605ca-5d5d-4f57-b24e-e5536d370e7b",
uris = { "/groupone/secrets/*", "/groupone/secrets/" },
resource_scopes = { }
}
resources["87ea36a2-27a7-4b7b-b939-62a11bb5c5ad"] = {
name = "Group Secrets",
owner = {
id = "31c4c56d-3fdf-43a1-ba84-ac5c1bd7d4f1"
},
ownerManagedAccess = true,
attributes = { },
_id = "87ea36a2-27a7-4b7b-b939-62a11bb5c5ad",
uris = { "/*/secrets/*", "/*/secrets/" },
resource_scopes = { }
}
return resources[resource_id]
end
local function keycloak_get_resources()
local resource_set = keycloak_resource_set()
local resources = {}
local count = 0
for k,resource_id in ipairs(resource_set) do
resources[resource_id] = keycloak_resource(resource_id)
count = count +1
end
return resources,count
end
local function keycloak_resources()
local resources,count = keycloak_get_resources()
assert(type(resources) == "table")
return resources,count
end
-- return the match depth or nil if not found
local function keycloak_uri_path_match(subject, test)
local subject = subject or ""
local test = test or ""
-- check for simple exact match
if subject == test then
return string.len(test)
end
-- if the pattern has no wildcards, stop here
if string.find(test, "[?*]") == nil then
return nil
end
-- shortcut "whole site" glob
if test == '/*' then
return 1
end
-- wildcard match depth is the number of characters matched without wildcard expansion
local test_depth = string.len(string.gsub(test,"[?*]",""))
-- Convert globs to lua patterns
-- ... escape all .
test = string.gsub(test, "%.", "\\.")
-- ... replace all ? with .
test = string.gsub(test, "%?", '.')
-- ... replace all * with .+
test = string.gsub(test, "%*", ".+")
-- get the beginning and end positions in the subject string that match the test
local start_match, end_match = string.find(subject, test)
-- it's only a match if it's the whole string (1 to length)
if start_match == 1 and end_match == string.len(subject) then
-- match successful, return the number of non-wildcard characters in the test as a "match quality rating"
return test_depth
else
-- match failed
return nil
end
end
local function keycloak_resource_scope_hash_to_lookup_table(scope_hash)
assert(type(scope_hash) == "table")
local lookup_table = {}
for _,scope in ipairs(scope_hash) do
lookup_table[scope.name] = true
end
return lookup_table
end
local function keycloak_resource_scopes_include_request_methods(resource_scopes)
for _,scope in pairs(resource_scopes) do -- for each associated scope...
-- check if this scope in the table of method scopes
if keycloak_table_has_value(keycloak_scope_for_method,scope) ~= nil then
return true
end
end
return false
end
-- return the resource_id for the deepest match of uris for the given uri
-- returns nil if none found
local function keycloak_resourceid_for_request(request_uri,request_method)
local request_uri = request_uri or ngx.var.request_uri
local request_method = request_method or ngx.req.get_method()
local request_method_scope = keycloak_request_method_to_scope(request_method)
local resources,resources_count = keycloak_resources()
assert(type(resources) == "table")
ngx.log(ngx.DEBUG, "request_uri:" .. request_uri .. " request_method:" .. request_method .. " method_scope:" .. request_method_scope .. " resource count:" .. resources_count)
-- initialize "best match"
local found_depth = 0
local found = nil -- this will be replaced by the ID of the closest uri match
for resource_id,resource in pairs(resources) do
ngx.log(ngx.DEBUG, "Trying resource: \"" .. resource.name .. "\"")
local resource_scopes = keycloak_resource_scope_hash_to_lookup_table(resource.resource_scopes)
-- search for any method scopes (scopes mapped to HTTP methods)
-- if there are any associated method scopes, the request method must match
local resource_has_method_scopes = keycloak_resource_scopes_include_request_methods(resource_scopes)
local resource_scopes_include_request_method = false
if resource_has_method_scopes then
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\" has method scopes.")
-- check if the request scope is in the associated resource scopes
if resource_scopes[request_method_scope] ~= nil then
resource_scopes_include_request_method = true
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": found matching scope: " .. request_method_scope)
else
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": no matching scopes.")
end
else
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\" no method scopes.")
end
-- only test the resource URIs if the request method matches the resource scope
-- or the resource doesn't list any associated scopes
if resource_scopes_include_request_method or (resource_has_method_scopes == false) then
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": passed scope check, testing " .. #resource.uris .. " resource URI patterns: " .. table.concat(resource.uris, ","))
for _,uri in ipairs(resource.uris) do
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": testing pattern:" .. uri .. " against request:" .. request_uri)
local match_depth = keycloak_uri_path_match(request_uri,uri) or 0
if match_depth > 0 then
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": URI pattern \"" .. uri .. "\" matches at depth " .. match_depth)
if match_depth > found_depth then
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": URI pattern \"" .. uri .. "\" is deeper (" .. match_depth .. ") than previous match (" .. found_depth .. ")")
found_depth = match_depth
found = resource_id
else
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": URI pattern \"" .. uri .. "\" is shallower (" .. match_depth .. ") than previous match (" .. found_depth .. ")")
end
else
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": URI pattern \"" .. uri .. "\" does not match")
end
end
else
ngx.log(ngx.DEBUG, "Resource: \"" .. resource.name .. "\": skipping URI check: disqualified by method scope.")
end
end
return found,found_depth
end
-----------
-- Public Functions
--[[
Converts a table (possibly nested) into a string for display or debug logging
table (table) : from keycloak_realm_discovery_endpoints
depth (interger): indent level (default = 0)
returns a human-readble string representation of the table input
--]]
function keycloak.dumpTable(table, depth)
local depth = depth or 0
local debug_out = ""
for k,v in pairs(table) do
if (type(v) == "table") then
debug_out = debug_out .. string.rep(" ", depth) .. k .. ":" .. "\n"
keycloak.dumpTable(v, depth+1)
else
debug_out = debug_out .. string.rep(" ", depth) .. ": " .. tostring(v) .. "\n"
end
end
return debug_out
end
-----------
-- Bless keycloak table as object
keycloak.__index = keycloak
print(keycloak_resourceid_for_request("/groupone/secrets/", "POST"))
|
---------------------------------------------------------------------------------------------------
-- Common module
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local actions = require("user_modules/sequences/actions")
local sslCommon = require("test_scripts/Security/SSLHandshakeFlow/common")
local utils = require("user_modules/utils")
local test = require("user_modules/dummy_connecttest")
local events = require('events')
local constants = require('protocol_handler/ford_protocol_constants')
--[[ General configuration parameters ]]
config.defaultProtocolVersion = 2
config.SecurityProtocol = "DTLS"
config.application1.registerAppInterfaceParams.fullAppID = "spt"
constants.FRAME_SIZE["P2"] = 1400
--[[ Variables ]]
local m = actions
local failedTCs = { }
m.cloneTable = utils.cloneTable
m.spairs = utils.spairs
m.cprint = utils.cprint
m.wait = utils.wait
m.printTable = utils.printTable
--[[ Common Functions ]]
function m.updatePreloadedPT(pAppPolicy, pFuncGroup)
local function pPTUpdateFunc(pPT)
pPT.policy_table.functional_groupings["Base-4"].encryption_required = pFuncGroup
pPT.policy_table.app_policies["spt"] = utils.cloneTable(pPT.policy_table.app_policies.default)
pPT.policy_table.app_policies["spt"].encryption_required = pAppPolicy
end
m.preloadedPTUpdate(pPTUpdateFunc)
end
function m.getAddCommandParams(pCmdId)
return {
cmdID = pCmdId,
menuParams = {
position = pCmdId,
menuName = "Command_" .. pCmdId
}
}
end
function m.unprotectedRpcInUnprotectedModeSuccess()
local cid = m.getMobileSession():SendRPC("AddCommand", m.getAddCommandParams(1))
m.getHMIConnection():ExpectRequest("UI.AddCommand", m.getAddCommandParams(1))
:Do(function(_, data)
m.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", { })
end)
m.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
m.getMobileSession():ExpectNotification("OnHashChange")
end
function m.switchRPCServiceToProtected()
local serviceId = 7
m.getMobileSession():StartSecureService(serviceId)
m.getMobileSession():ExpectHandshakeMessage()
m.getMobileSession():ExpectControlMessage(serviceId, {
frameInfo = m.frameInfo.START_SERVICE_ACK,
encryption = true
})
end
function m.spairs(pTbl)
local keys = {}
for k in pairs(pTbl) do
keys[#keys+1] = k
end
local function getStringKey(pKey)
if type(pKey) == "number" then
return tostring(string.format("%03d", pKey))
end
return pKey
end
table.sort(keys, function(a, b) return getStringKey(a) < getStringKey(b) end)
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], pTbl[keys[i]]
end
end
end
function m.cleanSessions()
for i = 1, m.getAppsCount() do
test.mobileSession[i]:StopRPC()
:Do(function(_, d)
utils.cprint(35, "Mobile session " .. d.sessionId .. " deleted")
test.mobileSession[i] = nil
end)
end
utils.wait()
end
function m.ignitionOff()
config.ExitOnCrash = false
local timeout = 5000
local function removeSessions()
for i = 1, m.getAppsCount() do
test.mobileSession[i] = nil
end
end
local event = events.Event()
event.matches = function(event1, event2) return event1 == event2 end
EXPECT_EVENT(event, "SDL shutdown")
:Do(function()
removeSessions()
StopSDL()
config.ExitOnCrash = true
end)
m.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications", { reason = "SUSPEND" })
m.getHMIConnection():ExpectNotification("BasicCommunication.OnSDLPersistenceComplete")
:Do(function()
m.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications",{ reason = "IGNITION_OFF" })
for i = 1, m.getAppsCount() do
m.getMobileSession(i):ExpectNotification("OnAppInterfaceUnregistered", { reason = "IGNITION_OFF" })
end
end)
m.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered", { unexpectedDisconnect = false })
:Times(m.getAppsCount())
local isSDLShutDownSuccessfully = false
m.getHMIConnection():ExpectNotification("BasicCommunication.OnSDLClose")
:Do(function()
utils.cprint(35, "SDL was shutdown successfully")
isSDLShutDownSuccessfully = true
RAISE_EVENT(event, event)
end)
:Timeout(timeout)
local function forceStopSDL()
if isSDLShutDownSuccessfully == false then
utils.cprint(35, "SDL was shutdown forcibly")
RAISE_EVENT(event, event)
end
end
RUN_AFTER(forceStopSDL, timeout + 500)
end
function m.reRegisterAppSuccess(pAppId)
if not pAppId then pAppId = 1 end
local mobSession = m.getMobileSession(pAppId)
mobSession:StartService(7)
:Do(function()
local params = utils.cloneTable(m.getConfigAppParams(pAppId))
local corId = mobSession:SendRPC("RegisterAppInterface", params)
m.getHMIConnection():ExpectNotification("BasicCommunication.OnAppRegistered", {
application = { appName = m.getConfigAppParams(pAppId).appName }
})
mobSession:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" })
:Do(function()
mobSession:ExpectNotification("OnPermissionsChange")
end)
end)
end
local preconditionsOrig = m.preconditions
function m.preconditions(ptUpdateFunc)
preconditionsOrig(ptUpdateFunc)
sslCommon.initSDLCertificates("./files/Security/client_credential.pem")
end
function m.subscribeToVD()
local cid = m.getMobileSession():SendRPC("SubscribeVehicleData", { speed = true })
m.getHMIConnection():ExpectRequest("VehicleInfo.SubscribeVehicleData", { speed = true })
:Do(function(_, data)
m.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {
speed = { dataType = "VEHICLEDATA_SPEED", resultCode = "SUCCESS" }})
end)
m.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS"})
end
function m.printFailedTCs()
for tc, msg in m.spairs(failedTCs) do
local e = string.find(msg, "\n")
if e > 80 then e = 80 end
m.cprint(35, string.format("%03d", tc), string.sub(msg, 1, e - 1) .. " ...")
end
end
function m.getExp(pApp, pFG)
local app = pApp
local fg = nil
if pFG == true and pApp ~= false then fg = true end
return app, fg
end
function m.getTransitions(pStates, pStart, pFinish)
local out = {}
local n = 0
for i = 1, #pStates do
for j = 1, #pStates do
n = n + 1
if n >= pStart and n <= pFinish then
table.insert(out, { from = i, to = j })
end
end
end
return out
end
function m.updatePreloadedPTSpecific(pRpcConfig, pAppPolicy, pFuncGroups)
local function pPTUpdateFunc(pTbl)
local pt = pTbl.policy_table
for fg, item in pairs(pRpcConfig) do
pt.functional_groupings[fg] = { rpcs = { } }
if item.isEncFlagDefined == true then
pt.functional_groupings[fg].encryption_required = pFuncGroups[fg]
end
for _, rpc in pairs(item.rpcs) do
pt.functional_groupings[fg].rpcs[rpc] = {
hmi_levels = { "NONE", "BACKGROUND", "FULL", "LIMITED" }
}
end
end
pt.functional_groupings["Base-4"].encryption_required = nil
pt.app_policies["default"].encryption_required = pAppPolicy
pt.app_policies["default"].groups = {}
for fg in m.spairs(pRpcConfig) do
table.insert(pt.app_policies["default"].groups, fg)
end
end
m.preloadedPTUpdate(pPTUpdateFunc)
end
function m.checkOnPermissionsChange(pRpcConfig, pExpApp, pExpRPC, pActPayload, pTC)
local function isItemInArray(pItem, pArray)
for _, i in pairs(pArray) do
if i == pItem then return true end
end
return false
end
local function getRPCs(pIsEncFlagDefined)
local out = {}
for _, item in pairs(pRpcConfig) do
for _, rpc in pairs(item.rpcs) do
if not (pIsEncFlagDefined ~= nil and pIsEncFlagDefined ~= item.isEncFlagDefined )
and not isItemInArray(rpc, out) then
table.insert(out, rpc)
end
end
end
return out
end
local msg = ""
-- check 'encryption' flag on Top level
if pActPayload.requireEncryption ~= pExpApp then
msg = msg .. "Expected 'requireEncryption' on a Top level " .. "'" .. tostring(pExpApp) .. "'"
.. ", actual " .. "'" .. tostring(pActPayload.requireEncryption) .. "'\n"
end
-- check 'encryption' flag value for expected RPCs on Item level
for _, rpc in pairs(getRPCs()) do
local permItem = nil
for _, v in pairs(pActPayload.permissionItem) do
if v.rpcName == rpc then permItem = v end
end
if permItem == nil then
msg = msg .. "Expected " .. rpc .. " is not found on an Item level\n"
else
local encAct = permItem.requireEncryption
local encExp = pExpRPC
if isItemInArray(rpc, getRPCs(false)) then encExp = nil end
if encAct ~= encExp then
msg = msg .. "Expected 'requireEncryption' on an Item level for '" .. rpc .. "': "
.. "'" .. tostring(encExp) .. "'"
.. ", actual " .. "'" .. tostring(encAct) .. "'\n"
end
end
end
-- check absence of unexpected RPCs on Item level
for _, item in pairs(pActPayload.permissionItem) do
if not isItemInArray(item.rpcName, getRPCs()) then
msg = msg .. "Unexpected " .. item.rpcName .. " is found on an Item level\n"
end
end
if string.len(msg) > 0 then
if pTC then failedTCs[pTC] = msg end
return false, string.sub(msg, 1, -2)
end
return true
end
local policyTableUpdate_Orig = m.policyTableUpdate
function m.policyTableUpdateSpecific(pRpcConfig, pNotifQty, pUpdateFunc, pExpApp, pExpRPC, pTC)
local function expNotificationFunc()
m.defaultExpNotificationFunc()
m.getMobileSession():ExpectNotification("OnPermissionsChange")
:ValidIf(function(e, data)
if e.occurences == 1 and pNotifQty ~= 0 then
return m.checkOnPermissionsChange(pRpcConfig, pExpApp, pExpRPC, data.payload, pTC)
end
return true
end)
:Times(pNotifQty)
end
policyTableUpdate_Orig(pUpdateFunc, expNotificationFunc)
m.wait(1000)
end
function m.policyTableUpdate(pUpdateFunc, expNotificationFunc)
m.getMobileSession():ExpectNotification("OnPermissionsChange")
policyTableUpdate_Orig(pUpdateFunc, expNotificationFunc)
end
return m
|
--[[
-- Copyright(c) 2018-2025, All Rights Reserved
-- Created: 2018/12/21
--
-- @file wireless.lua
-- @brief wifi网络接口封装
-- @version 0.1
-- @history 修改历史
-- \n 2018/12/21 0.1 创建文件
-- @warning 没有警告
--]]
local l_sys = require("l_sys")
local util = require("base.util")
local cjson = require("cjson")
local util_ex = require("base.util_ex")
local imsg = require("ipc.imsg")
local l_wireless = nil
if 'win' ~= l_sys.platform then
l_wireless = require("l_wireless") -- 模拟软件不用加载
end
local wireless = {}
-- 检查时间间隔 10S~60S
local time_interval = 30000 -- 计数单位毫秒[ms]
-- 上一次检查的时间点
local check_tc = 0
local cfg = {
mode = 'ap', -- 'ap', 'sta'
ssid = '',
passwd = '',
dhcp = true,
ip = '',
netmask = '',
gateway = ''
}
wireless.set_ap = function ()
cfg.mode = 'ap'
print('wireless set:', cfg.mode, cfg.ssid, cfg.passwd)
end
wireless.set_sta = function (ssid, passwd, dhcp, ip, netmask, gateway)
cfg.mode = 'sta'
cfg.ssid = ssid
cfg.passwd = passwd
cfg.dhcp = true
print('wireless set:', cfg.mode, cfg.ssid, cfg.passwd)
print('wireless set:', cfg.dhcp, cfg.ip, cfg.netmask, cfg.gateway)
end
wireless.setup = function (cf)
-- cf 的结构参见 ipc.cfg.default_v 中 wireless定义
if 'ap' == cf.type then
wireless.set_ap()
else
wireless.set_sta(cf.ssid, cf.passwd)
end
end
wireless.setup_json = function (json)
local ret, cf = pcall(cjson.decode, json)
if ret then
wireless.setup(cf)
end
end
local switch2ap = function ()
print('wireless switch2ap start...')
l_wireless.mode_switch2ap()
print('wireless switch2ap over.')
end
local switch2sta = function (ssid,psk)
local content = "ctrl_interface=/var/run/wpa_supplicant\n".."update_config=1\n".."network={\nssid=\""..ssid.."\"\npsk=\""..psk.."\"\n}"
local f = assert(io.open("/opt/configfile/wpa_0_8.conf",'w'))
f:write(content)
f:close()
print('wireless switch2sta start...')
l_wireless.mode_switch2sta()
-- print('wireless switch2sta over.')
l_wireless.sta_dhcpc_start()
end
local sta_conn_wifi = function ()
print('sta connect to:', cfg.ssid)
l_wireless.sta_wpa_cli_start()
print('sta_get_scan_result')
local scan = l_wireless.sta_get_scan_result()
if util.t_is_empty(scan) then
return
end
local ssid = cfg.ssid
local passwd = cfg.passwd
local flags = ''
local b_conn = false
for k, v in ipairs(scan) do
--util_ex.printf(k, v['ssid'], v)
if ssid == v['ssid'] then
b_conn = true
if 'string' == type(v['flags']) then
flags = v['flags']
--util_ex.printf('find wifi:', v)
break
else
print('wifi flags error!')
end
end
end
if b_conn then
l_wireless.sta_connect2ap(ssid, passwd, flags)
else
print('no find wifi ssid', ssid)
end
end
local sta_list_wifi = function ()
l_wireless.sta_wpa_cli_start()
-- print('sta_get_scan_result')
local scan = l_wireless.sta_get_scan_result()
if util.t_is_empty(scan) then
return
end
for k, v in ipairs(scan) do
print(v['ssid'].." ")
end
end
wireless.check_proc = function (tc)
-- 从配置消息中取数据, 一直取到最后一个配置消息
local json = ''
while true do
local ret, msg, lparam = imsg.get(imsg.update_wifi)
if ret then
json = lparam
else
break
end
end
if '' ~= json then
print('wireless.setup_json', json)
wireless.setup_json(json)
check_tc = time_interval -- 有配置更新, 立即处理检查
end
if nil == l_wireless then
return -- 模拟软件, 不处理wifi
end
check_tc = check_tc + tc
if check_tc < time_interval then
return -- 不在时间间隔范围
end
-- 计数归0, 并执行一次检查
check_tc = 0
local mode = l_wireless.mode_probe()
if mode ~= cfg.mode then
if 'ap' == cfg.mode then
if mode == 'sta' then
l_wireless.sta_wpa_cli_cleanup()
end
switch2ap()
l_sys.sleep(2000)
else
switch2sta(cfg.ssid,cfg.passwd)
l_sys.sleep(2000)
end
end
if 'ap' ~= cfg.mode then
--显示wifi列表 用于测试
--sta_list_wifi()
-- sta 模式, 检查是否连接到指定的wifi
local status, ssid = l_wireless.sta_get_linkstatus()
if 0 == status then
-- 没有连接,
-- wpa_supplicant 服务程序会自动连接 /opt/configfile/wpa_0_8.conf 中保存的wifi
print("----- 0 -------")
elseif 1 == status then
-- 已经连接 但没得到ssid信息
print("----- 1 -------")
else
print("----- 2 -------")
print("connected ssid = "..ssid.."\n")
end
else
--print('wireless is ap mode')
end
end
--用于测试
wireless.test = function (mode)
local t_mode
local status, ssid
if mode == 'ap' then
print("switch to ap mode --------------\n")
switch2ap()
else
print("switch to sta mode --------------\n")
switch2sta(cfg.ssid,cfg.passwd)
end
l_sys.sleep(6000)
t_mode = l_wireless.mode_probe()
print("t_mode = ",t_mode)
if t_mode == 'ap' then
print("ap mode ------------")
end
if t_mode == 'sta' then
print("sta mode ***********")
status, ssid = l_wireless.sta_get_linkstatus()
print("connected ssid = "..ssid.."\n")
end
end
--[[ test
--wireless.set_ap()
wireless.set_sta('HUAWEI-7NLNPF_5G', 'qwertyuiop1234567890') -- 可能为错误的ssid,或密码
local count = 1000
while 0 < count do
wireless.check_proc() -- 一直检查wifi连接状态,及是否需要变更
l_sys.sleep(1000)
count = count -1
end
--]]
return wireless
|
local utils = require 'utils'
local ms = require 'memscan'
-- Utility functions
local globals = df.global
local global_addr = dfhack.internal.getAddress
local os_type = dfhack.getOSType()
local rdelta = dfhack.internal.getRebaseDelta()
local vbias = 0
if os_type == 'windows' then vbias = -4 end
local lines = {}
local complete = true
local function header(name)
table.insert(lines, '')
table.insert(lines, '['..name..']')
end
local function value(name,addr)
local line
if not addr then
complete = false
line = name..'=0x0'
elseif addr < 0x10000 then
line = string.format('%s=0x%04x',name,addr)
else
line = string.format('%s=0x%08x',name,addr)
end
table.insert(lines, line)
end
local function address(name,bias,base,field,...)
local addr
if base == globals then
addr = global_addr(field)
bias = bias - rdelta
if addr and select('#',...) > 0 then
_,addr = df.sizeof(ms.field_ref(base,field,...))
end
elseif base._kind == 'class-type' then
-- field_offset crashes with classes due to vtable problems,
-- so we have to create a real temporary object here.
local obj = df.new(base)
if obj then
local _,a1 = df.sizeof(obj)
local _,a2 = df.sizeof(ms.field_ref(obj,field,...))
addr = a2-a1
obj:delete()
end
else
addr = ms.field_offset(base,field,...)
end
if addr then
addr = addr + bias
end
value(name, addr)
end
local function offset(name,base,...)
address(name,0,base,...)
end
local function vector(name,base,...)
address(name,vbias,base,...)
end
-- List of actual values
header('addresses')
vector('translation_vector',globals,'world','raws','language','translations')
vector('language_vector',globals,'world','raws','language','words')
vector('creature_vector',globals,'world','units','all')
vector('active_creature_vector',globals,'world','units','active')
offset('dwarf_race_index',globals,'ui','race_id')
vector('squad_vector',globals,'world','squads','all')
offset('current_year',globals,'cur_year')
offset('cur_year_tick',globals,'cur_year_tick')
offset('dwarf_civ_index',globals,'ui','civ_id')
vector('races_vector',globals,'world','raws','creatures','all')
vector('reactions_vector',globals,'world','raws','reactions')
vector('historical_figures_vector',globals,'world','history','figures')
vector('fake_identities_vector',globals,'world','assumed_identities','all')
offset('fortress_entity',globals,'ui','main','fortress_entity')
vector('historical_entities_vector',globals,'world','entities','all')
vector('itemdef_weapons_vector',globals,'world','raws','itemdefs','weapons')
vector('itemdef_trap_vector',globals,'world','raws','itemdefs','trapcomps')
vector('itemdef_toy_vector',globals,'world','raws','itemdefs','toys')
vector('itemdef_tool_vector',globals,'world','raws','itemdefs','tools')
vector('itemdef_instrument_vector',globals,'world','raws','itemdefs','instruments')
vector('itemdef_armor_vector',globals,'world','raws','itemdefs','armor')
vector('itemdef_ammo_vector',globals,'world','raws','itemdefs','ammo')
vector('itemdef_siegeammo_vector',globals,'world','raws','itemdefs','siege_ammo')
vector('itemdef_glove_vector',globals,'world','raws','itemdefs','gloves')
vector('itemdef_shoe_vector',globals,'world','raws','itemdefs','shoes')
vector('itemdef_shield_vector',globals,'world','raws','itemdefs','shields')
vector('itemdef_helm_vector',globals,'world','raws','itemdefs','helms')
vector('itemdef_pant_vector',globals,'world','raws','itemdefs','pants')
vector('itemdef_food_vector',globals,'world','raws','itemdefs','food')
vector('colors_vector',globals,'world','raws','language','colors')
vector('shapes_vector',globals,'world','raws','language','shapes')
offset('base_materials',globals,'world','raws','mat_table','builtin')
vector('inorganics_vector',globals,'world','raws','inorganics')
vector('plants_vector',globals,'world','raws','plants','all')
vector('material_templates_vector',globals,'world','raws','material_templates')
vector('all_syndromes_vector',globals,'world','raws','syndromes','all')
offset('world_data',globals,'world','world_data')
vector('active_sites_vector',df.world_data,'active_site')
offset('world_site_type',df.world_site,'type')
vector('weapons_vector',globals,'world','items','other','WEAPON')
vector('shields_vector',globals,'world','items','other', 'SHIELD')
vector('quivers_vector',globals,'world','items','other', 'QUIVER')
vector('crutches_vector',globals,'world','items','other', 'CRUTCH')
vector('backpacks_vector',globals,'world','items','other', 'BACKPACK')
vector('ammo_vector',globals,'world','items','other', 'AMMO')
vector('flasks_vector',globals,'world','items','other', 'FLASK')
vector('pants_vector',globals,'world','items','other', 'PANTS')
vector('armor_vector',globals,'world','items','other', 'ARMOR')
vector('shoes_vector',globals,'world','items','other', 'SHOES')
vector('helms_vector',globals,'world','items','other', 'HELM')
vector('gloves_vector',globals,'world','items','other', 'GLOVES')
vector('artifacts_vector',globals,'world','artifacts','all')
header('offsets')
offset('word_table',df.language_translation,'words')
value('string_buffer_offset', 0x0000)
header('word_offsets')
offset('base',df.language_word,'word')
offset('noun_singular',df.language_word,'forms','Noun')
offset('noun_plural',df.language_word,'forms','NounPlural')
offset('adjective',df.language_word,'forms','Adjective')
offset('verb',df.language_word,'forms','Verb')
offset('present_simple_verb',df.language_word,'forms','Verb3rdPerson')
offset('past_simple_verb',df.language_word,'forms','VerbPast')
offset('past_participle_verb',df.language_word,'forms','VerbPassive')
offset('present_participle_verb',df.language_word,'forms','VerbGerund')
offset('words',df.language_name,'words')
offset('word_type',df.language_name,'parts_of_speech')
offset('language_id',df.language_name,'language')
header('general_ref_offsets')
--WARNING below value should be: "general_ref::vtable","1","0x8","0x4","vmethod","getType","general_ref_type",""
value('ref_type',0x8)
offset('artifact_id',df.general_ref_artifact,'artifact_id')
offset('item_id',df.general_ref_item,'item_id')
header('race_offsets')
offset('name_singular',df.creature_raw,'name',0)
offset('name_plural',df.creature_raw,'name',1)
offset('adjective',df.creature_raw,'name',2)
offset('baby_name_singular',df.creature_raw,'general_baby_name',0)
offset('baby_name_plural',df.creature_raw,'general_baby_name',1)
offset('child_name_singular',df.creature_raw,'general_child_name',0)
offset('child_name_plural',df.creature_raw,'general_child_name',1)
vector('pref_string_vector',df.creature_raw,'prefstring')
vector('castes_vector',df.creature_raw,'caste')
vector('pop_ratio_vector',df.creature_raw,'pop_ratio')
vector('materials_vector',df.creature_raw,'material')
offset('flags',df.creature_raw,'flags')
vector('tissues_vector',df.creature_raw,'tissue')
header('caste_offsets')
offset('caste_name',df.caste_raw,'caste_name')
offset('caste_descr',df.caste_raw,'description')
offset('caste_trait_ranges',df.caste_raw,'personality','a')
offset('caste_phys_att_ranges',df.caste_raw,'attributes','phys_att_range')
offset('caste_att_rates',df.caste_raw,'attributes','phys_att_rates')
offset('caste_att_caps',df.caste_raw,'attributes','phys_att_cap_perc')
offset('adult_size',df.caste_raw,'misc','adult_size')
offset('flags',df.caste_raw,'flags')
vector('extracts',df.caste_raw,'extracts','extract_matidx')
offset('skill_rates',df.caste_raw,'skill_rates')
offset('body_info',df.caste_raw,'body_info')
header('hist_entity_offsets')
vector('squads',df.historical_entity,'squads')
vector('positions',df.historical_entity,'positions','own')
vector('assignments',df.historical_entity,'positions','assignments')
offset('assign_hist_id',df.entity_position_assignment,'histfig')
offset('assign_position_id',df.entity_position_assignment,'position_id')
offset('position_id',df.entity_position,'id')
offset('position_name',df.entity_position,'name')
offset('position_female_name',df.entity_position,'name_female')
offset('position_male_name',df.entity_position,'name_male')
header('hist_figure_offsets')
offset('hist_race',df.historical_figure,'race')
offset('hist_name',df.historical_figure,'name')
offset('id',df.historical_figure,'id')
offset('hist_fig_info',df.historical_figure,'info')
offset('reputation',df.historical_figure_info,'reputation')
offset('current_ident',df.historical_figure_info.T_reputation,'cur_identity')
offset('fake_name',df.assumed_identity,'name')
offset('fake_birth_year',df.assumed_identity,'birth_year')
offset('fake_birth_time',df.assumed_identity,'birth_second')
header('item_offsets')
offset('item_def',df.item_ammost,'subtype') --currently same for all
offset('id',df.item,'id')
vector('general_refs',df.item,'general_refs')
offset('stack_size',df.item_actual,'stack_size')
offset('wear',df.item_actual,'wear')
offset('mat_type',df.item_crafted,'mat_type')
offset('mat_index',df.item_crafted,'mat_index')
offset('quality',df.item_crafted,'quality')
header('item_subtype_offsets')
offset('sub_type',df.itemdef,'subtype')
offset('name',df.itemdef_armorst,'name')
offset('name_plural',df.itemdef_armorst,'name_plural')
offset('adjective',df.itemdef_armorst,'name_preplural')
header('item_filter_offsets')
offset('item_subtype',df.item_filter_spec,'item_subtype')
offset('mat_class',df.item_filter_spec,'material_class')
offset('mat_type',df.item_filter_spec,'mattype')
offset('mat_index',df.item_filter_spec,'matindex')
header('weapon_subtype_offsets')
offset('single_size',df.itemdef_weaponst,'two_handed')
offset('multi_size',df.itemdef_weaponst,'minimum_size')
offset('ammo',df.itemdef_weaponst,'ranged_ammo')
offset('melee_skill',df.itemdef_weaponst,'skill_melee')
offset('ranged_skill',df.itemdef_weaponst,'skill_ranged')
header('armor_subtype_offsets')
offset('chest_armor_properties',df.itemdef_armorst,'props')
offset('pants_armor_properties',df.itemdef_pantsst,'props')
offset('other_armor_properties',df.itemdef_helmst,'props')
offset('layer',df.armor_properties,'layer')
offset('mat_name',df.itemdef_armorst,'material_placeholder')
header('material_offsets')
offset('solid_name',df.material_common,'state_name','Solid')
offset('liquid_name',df.material_common,'state_name','Liquid')
offset('gas_name',df.material_common,'state_name','Gas')
offset('powder_name',df.material_common,'state_name','Powder')
offset('paste_name',df.material_common,'state_name','Paste')
offset('pressed_name',df.material_common,'state_name','Pressed')
offset('inorganic_materials_vector',df.inorganic_raw,'material')
offset('flags',df.material_common,'flags')
header('plant_offsets')
offset('name',df.plant_raw,'name')
offset('name_plural',df.plant_raw,'name_plural')
offset('name_leaf_plural',df.plant_raw,'leaves_plural')
offset('name_seed_plural',df.plant_raw,'seed_plural')
vector('materials_vector',df.plant_raw,'material')
offset('flags',df.plant_raw,'flags')
header('descriptor_offsets')
offset('color_name',df.descriptor_color,'name')
offset('shape_name_plural',df.descriptor_shape,'name_plural')
header('health_offsets')
offset('parent_id',df.body_part_raw,'con_part_id')
vector('layers_vector',df.body_part_raw,'layers')
offset('number',df.body_part_raw,'number')
vector('names_vector',df.body_part_raw,'name_singular')
vector('names_plural_vector',df.body_part_raw,'name_plural')
offset('layer_tissue',df.body_part_layer_raw,'tissue_id')
offset('layer_global_id',df.body_part_layer_raw,'layer_id')
offset('tissue_name',df.tissue_template,'tissue_name_singular')
offset('tissue_flags',df.tissue_template,'flags')
header('dwarf_offsets')
offset('first_name',df.unit,'name','first_name')
offset('nick_name',df.unit,'name','nickname')
offset('last_name',df.unit,'name','words')
offset('custom_profession',df.unit,'custom_profession')
offset('profession',df.unit,'profession')
offset('race',df.unit,'race')
offset('flags1',df.unit,'flags1')
offset('flags2',df.unit,'flags2')
offset('flags3',df.unit,'flags3')
offset('caste',df.unit,'caste')
offset('sex',df.unit,'sex')
offset('id',df.unit,'id')
offset('animal_type',df.unit,'training_level')
offset('civ',df.unit,'civ_id')
vector('specific_refs',df.unit,'specific_refs')
offset('squad_id',df.unit,'military','squad_id')
offset('squad_position',df.unit,'military','squad_position')
offset('recheck_equipment',df.unit,'military','pickup_flags')
offset('mood',df.unit,'mood')
offset('birth_year',df.unit,'relations','birth_year')
offset('birth_time',df.unit,'relations','birth_time')
offset('current_job',df.unit,'job','current_job')
offset('physical_attrs',df.unit,'body','physical_attrs')
vector('body_size',df.unit,'appearance','body_modifiers')
offset('curse',df.unit,'curse','name')
offset('curse_add_flags1',df.unit,'curse','add_tags1')
offset('turn_count',df.unit,'curse','time_on_site')
vector('souls',df.unit,'status','souls')
vector('states',df.unit,'status','misc_traits')
offset('labors',df.unit,'status','labors')
vector('thoughts',df.unit,'status','recent_events')
offset('happiness',df.unit,'status','happiness')
offset('hist_id',df.unit,'hist_figure_id')
offset('artifact_name',df.unit,'status','artifact_name')
vector('active_syndrome_vector',df.unit,'syndromes','active')
offset('syn_sick_flag',df.unit_syndrome,'flags')
offset('unit_health_info',df.unit,'health')
offset('counters1',df.unit,'counters','winded')
offset('counters2',df.unit, 'counters','pain')
offset('counters3',df.unit, 'counters2','paralysis')
offset('limb_counters',df.unit,'status2','limbs_stand_max')
offset('blood',df.unit,'body','blood_max')
offset('body_component_info',df.unit,'body','components')
--change the layer_status_vector to this:
vector('layer_status_vector',df.body_component_info,'layer_status')
--once dfhack is updated to a commit later than f51c7d9ceab971222dfc87ac62546a414dbc6886
--vector('layer_status_vector',df.body_component_info,'body_layer_338')
vector('wounds_vector',df.unit,'body','wounds')
offset('mood_skill',df.unit,'job','mood_skill')
vector('used_items_vector',df.unit,'used_items')
offset('affection_level',df.unit_item_use,'affection_level')
vector('inventory',df.unit,'inventory')
offset('inventory_item_mode',df.unit_inventory_item,'mode')
offset('inventory_item_bodypart',df.unit_inventory_item,'body_part_id')
header('syndrome_offsets')
vector('cie_effects',df.syndrome,'ce')
offset('cie_first_perc',df.creature_interaction_effect_phys_att_changest,'phys_att_perc') --same for mental
--prior to commit 1bbd3a87077a573484b60e551dd388fae20fdd7c these are unknown
--offset('cie_phys',df.creature_interaction_effect_phys_att_changest,'phys_att_unk')
--offset('cie_ment',df.creature_interaction_effect_ment_att_changest,'ment_att_unk')
offset('cie_phys',df.creature_interaction_effect_phys_att_changest,'phys_att_add')
offset('cie_ment',df.creature_interaction_effect_ment_att_changest,'ment_att_add')
vector('syn_classes_vector',df.syndrome,'syn_class')
header('unit_wound_offsets')
vector('parts',df.unit_wound,'parts')
offset('id',df.unit_wound.T_parts,'body_part_id')
offset('layer',df.unit_wound.T_parts,'layer_idx')
offset('general_flags',df.unit_wound,'flags')
offset('flags1',df.unit_wound.T_parts,'flags1')
offset('flags2',df.unit_wound.T_parts,'flags2')
offset('effects_vector',df.unit_wound.T_parts,'effect_type')
offset('bleeding',df.unit_wound.T_parts,'bleeding')
offset('pain',df.unit_wound.T_parts,'pain')
offset('cur_pen',df.unit_wound.T_parts,'cur_penetration_perc')
offset('max_pen',df.unit_wound.T_parts,'max_penetration_perc')
header('soul_details')
offset('name',df.unit_soul,'name')
offset('mental_attrs',df.unit_soul,'mental_attrs')
vector('skills',df.unit_soul,'skills')
vector('preferences',df.unit_soul,'preferences')
offset('traits',df.unit_soul,'traits')
header('job_details')
offset('id',df.job,'job_type')
offset('mat_type',df.job,'mat_type')
offset('mat_index',df.job,'mat_index')
offset('mat_category',df.job,'material_category')
value('on_break_flag',df.misc_trait_type.OnBreak)
offset('sub_job_id',df.job,'reaction_name')
offset('reaction',df.reaction,'name')
offset('reaction_skill',df.reaction,'skill')
header('squad_offsets')
offset('id',df.squad,'id')
offset('name',df.squad,'name')
offset('alias',df.squad,'alias')
vector('members',df.squad,'positions')
offset('carry_food',df.squad,'carry_food')
offset('carry_water',df.squad,'carry_water')
vector('ammunition',df.squad,'ammunition')
offset('quiver',df.squad_position,'quiver')
offset('backpack',df.squad_position,'backpack')
offset('flask',df.squad_position,'flask')
vector('armor_vector',df.squad_position,'uniform','body')
vector('helm_vector',df.squad_position,'uniform','head')
vector('pants_vector',df.squad_position,'uniform','pants')
vector('gloves_vector',df.squad_position,'uniform','gloves')
vector('shoes_vector',df.squad_position,'uniform','shoes')
vector('shield_vector',df.squad_position,'uniform','shield')
vector('weapon_vector',df.squad_position,'uniform','weapon')
offset('uniform_item_filter',df.squad_uniform_spec,'item_filter')
offset('uniform_indv_choice',df.squad_uniform_spec,'indiv_choice')
-- Final creation of the file
local out = io.open('therapist.ini', 'w')
out:write('[info]\n')
-- TODO: add an api function to retrieve the checksum
out:write('checksum=<<fillme>>\n')
out:write('version_name='..dfhack.getDFVersion()..'\n')
out:write('complete='..(complete and 'true' or 'false')..'\n')
for i,v in ipairs(lines) do
out:write(v..'\n')
end
out:write[[
[valid_flags_2]
size=0
[invalid_flags_1]
size=10
1\name=a zombie
1\value=0x00001000
2\name=a skeleton
2\value=0x00002000
3\name=a merchant
3\value=0x00000040
4\name=outpost liason or diplomat
4\value=0x00000800
5\name=an invader or hostile
5\value=0x00020000
6\name=an invader or hostile
6\value=0x00080000
7\name=an invader or hostile
7\value=0x000C0000
8\name=part of a merchant caravan
8\value=0x00000080
9\name="Dead, Jim."
9\value=0x00000002
10\name=marauder
10\value=0x00000010
[invalid_flags_2]
size=5
1\name="killed, Jim."
1\value=0x00000080
2\name=from the Underworld. SPOOKY!
2\value=0x00040000
3\name=resident
3\value=0x00080000
4\name=visitor_uninvited
4\value=0x00400000
5\name=visitor
5\value=0x00800000
[invalid_flags_3]
size=1
1\name=a ghost
1\value=0x00001000
]]
out:close() |
object_mobile_selonian_female_06 = object_mobile_shared_selonian_female_06:new {
}
ObjectTemplates:addTemplate(object_mobile_selonian_female_06, "object/mobile/selonian_female_06.iff")
|
-- This file is generated by proto-gen-lua. DO NOT EDIT.
-- The protoc version is 'v3.19.2'
-- The proto-gen-lua version is 'Develop'
local protobuf = require "protobuf.protobuf"
local registry = require "protobuf.registry"
local google_protobuf_any_pb = require "google.protobuf.any_pb"
local google_protobuf_source_context_pb = require "google.protobuf.source_context_pb"
local google_protobuf_type_pb_desc = require "google.protobuf.type_pb_desc"
local google_protobuf_type_pb = {}
---@alias google_protobuf_type_pb.Syntax
---| 'google_protobuf_type_pb.Syntax.SYNTAX_PROTO2' # = 0
---| 'google_protobuf_type_pb.Syntax.SYNTAX_PROTO3' # = 1
---@class google_protobuf_type_pb.Type : protobuf.Message
---@field name string
---@field fields google_protobuf_type_pb.Field[]
---@field oneofs string[]
---@field options google_protobuf_type_pb.Option[]
---@field source_context google_protobuf_source_context_pb.SourceContext
---@field syntax google_protobuf_type_pb.Syntax
---@alias google_protobuf_type_pb.Field.Kind
---| 'google_protobuf_type_pb.Field.Kind.TYPE_UNKNOWN' # = 0
---| 'google_protobuf_type_pb.Field.Kind.TYPE_DOUBLE' # = 1
---| 'google_protobuf_type_pb.Field.Kind.TYPE_FLOAT' # = 2
---| 'google_protobuf_type_pb.Field.Kind.TYPE_INT64' # = 3
---| 'google_protobuf_type_pb.Field.Kind.TYPE_UINT64' # = 4
---| 'google_protobuf_type_pb.Field.Kind.TYPE_INT32' # = 5
---| 'google_protobuf_type_pb.Field.Kind.TYPE_FIXED64' # = 6
---| 'google_protobuf_type_pb.Field.Kind.TYPE_FIXED32' # = 7
---| 'google_protobuf_type_pb.Field.Kind.TYPE_BOOL' # = 8
---| 'google_protobuf_type_pb.Field.Kind.TYPE_STRING' # = 9
---| 'google_protobuf_type_pb.Field.Kind.TYPE_GROUP' # = 10
---| 'google_protobuf_type_pb.Field.Kind.TYPE_MESSAGE' # = 11
---| 'google_protobuf_type_pb.Field.Kind.TYPE_BYTES' # = 12
---| 'google_protobuf_type_pb.Field.Kind.TYPE_UINT32' # = 13
---| 'google_protobuf_type_pb.Field.Kind.TYPE_ENUM' # = 14
---| 'google_protobuf_type_pb.Field.Kind.TYPE_SFIXED32' # = 15
---| 'google_protobuf_type_pb.Field.Kind.TYPE_SFIXED64' # = 16
---| 'google_protobuf_type_pb.Field.Kind.TYPE_SINT32' # = 17
---| 'google_protobuf_type_pb.Field.Kind.TYPE_SINT64' # = 18
---@alias google_protobuf_type_pb.Field.Cardinality
---| 'google_protobuf_type_pb.Field.Cardinality.CARDINALITY_UNKNOWN' # = 0
---| 'google_protobuf_type_pb.Field.Cardinality.CARDINALITY_OPTIONAL' # = 1
---| 'google_protobuf_type_pb.Field.Cardinality.CARDINALITY_REQUIRED' # = 2
---| 'google_protobuf_type_pb.Field.Cardinality.CARDINALITY_REPEATED' # = 3
---@class google_protobuf_type_pb.Field : protobuf.Message
---@field kind google_protobuf_type_pb.Field.Kind
---@field cardinality google_protobuf_type_pb.Field.Cardinality
---@field number number
---@field name string
---@field type_url string
---@field oneof_index number
---@field packed boolean
---@field options google_protobuf_type_pb.Option[]
---@field json_name string
---@field default_value string
---@class google_protobuf_type_pb.Enum : protobuf.Message
---@field name string
---@field enumvalue google_protobuf_type_pb.EnumValue[]
---@field options google_protobuf_type_pb.Option[]
---@field source_context google_protobuf_source_context_pb.SourceContext
---@field syntax google_protobuf_type_pb.Syntax
---@class google_protobuf_type_pb.EnumValue : protobuf.Message
---@field name string
---@field number number
---@field options google_protobuf_type_pb.Option[]
---@class google_protobuf_type_pb.Option : protobuf.Message
---@field name string
---@field value google_protobuf_any_pb.Any
google_protobuf_type_pb.Syntax = {}
google_protobuf_type_pb.Syntax._FullName = ".google.protobuf.Syntax"
google_protobuf_type_pb.Syntax._Descriptor = "google_protobuf_type_pb_desc.enum_type[1]"
google_protobuf_type_pb.Syntax.SYNTAX_PROTO2 = 0
google_protobuf_type_pb.Syntax.SYNTAX_PROTO3 = 1
google_protobuf_type_pb.Syntax[0] = ".google.protobuf.Syntax.SYNTAX_PROTO2"
google_protobuf_type_pb.Syntax[1] = ".google.protobuf.Syntax.SYNTAX_PROTO3"
registry.RegistEnum(google_protobuf_type_pb.Syntax)
---@type fun():google_protobuf_type_pb.Type
google_protobuf_type_pb.Type = protobuf.Message(google_protobuf_type_pb_desc.message_type[1])
google_protobuf_type_pb.Type._FullName = ".google.protobuf.Type"
google_protobuf_type_pb.Type._Descriptor = "google_protobuf_type_pb_desc.message_type[1]"
registry.RegistMessage(google_protobuf_type_pb.Type)
google_protobuf_type_pb.Field.Kind = {}
google_protobuf_type_pb.Field.Kind._FullName = ".google.protobuf.Field.Kind"
google_protobuf_type_pb.Field.Kind._Descriptor = "google_protobuf_type_pb_desc.message_type[2].enum_type[1]"
google_protobuf_type_pb.Field.Kind.TYPE_UNKNOWN = 0
google_protobuf_type_pb.Field.Kind.TYPE_DOUBLE = 1
google_protobuf_type_pb.Field.Kind.TYPE_FLOAT = 2
google_protobuf_type_pb.Field.Kind.TYPE_INT64 = 3
google_protobuf_type_pb.Field.Kind.TYPE_UINT64 = 4
google_protobuf_type_pb.Field.Kind.TYPE_INT32 = 5
google_protobuf_type_pb.Field.Kind.TYPE_FIXED64 = 6
google_protobuf_type_pb.Field.Kind.TYPE_FIXED32 = 7
google_protobuf_type_pb.Field.Kind.TYPE_BOOL = 8
google_protobuf_type_pb.Field.Kind.TYPE_STRING = 9
google_protobuf_type_pb.Field.Kind.TYPE_GROUP = 10
google_protobuf_type_pb.Field.Kind.TYPE_MESSAGE = 11
google_protobuf_type_pb.Field.Kind.TYPE_BYTES = 12
google_protobuf_type_pb.Field.Kind.TYPE_UINT32 = 13
google_protobuf_type_pb.Field.Kind.TYPE_ENUM = 14
google_protobuf_type_pb.Field.Kind.TYPE_SFIXED32 = 15
google_protobuf_type_pb.Field.Kind.TYPE_SFIXED64 = 16
google_protobuf_type_pb.Field.Kind.TYPE_SINT32 = 17
google_protobuf_type_pb.Field.Kind.TYPE_SINT64 = 18
google_protobuf_type_pb.Field.Kind[0] = ".google.protobuf.Field.Kind.TYPE_UNKNOWN"
google_protobuf_type_pb.Field.Kind[1] = ".google.protobuf.Field.Kind.TYPE_DOUBLE"
google_protobuf_type_pb.Field.Kind[2] = ".google.protobuf.Field.Kind.TYPE_FLOAT"
google_protobuf_type_pb.Field.Kind[3] = ".google.protobuf.Field.Kind.TYPE_INT64"
google_protobuf_type_pb.Field.Kind[4] = ".google.protobuf.Field.Kind.TYPE_UINT64"
google_protobuf_type_pb.Field.Kind[5] = ".google.protobuf.Field.Kind.TYPE_INT32"
google_protobuf_type_pb.Field.Kind[6] = ".google.protobuf.Field.Kind.TYPE_FIXED64"
google_protobuf_type_pb.Field.Kind[7] = ".google.protobuf.Field.Kind.TYPE_FIXED32"
google_protobuf_type_pb.Field.Kind[8] = ".google.protobuf.Field.Kind.TYPE_BOOL"
google_protobuf_type_pb.Field.Kind[9] = ".google.protobuf.Field.Kind.TYPE_STRING"
google_protobuf_type_pb.Field.Kind[10] = ".google.protobuf.Field.Kind.TYPE_GROUP"
google_protobuf_type_pb.Field.Kind[11] = ".google.protobuf.Field.Kind.TYPE_MESSAGE"
google_protobuf_type_pb.Field.Kind[12] = ".google.protobuf.Field.Kind.TYPE_BYTES"
google_protobuf_type_pb.Field.Kind[13] = ".google.protobuf.Field.Kind.TYPE_UINT32"
google_protobuf_type_pb.Field.Kind[14] = ".google.protobuf.Field.Kind.TYPE_ENUM"
google_protobuf_type_pb.Field.Kind[15] = ".google.protobuf.Field.Kind.TYPE_SFIXED32"
google_protobuf_type_pb.Field.Kind[16] = ".google.protobuf.Field.Kind.TYPE_SFIXED64"
google_protobuf_type_pb.Field.Kind[17] = ".google.protobuf.Field.Kind.TYPE_SINT32"
google_protobuf_type_pb.Field.Kind[18] = ".google.protobuf.Field.Kind.TYPE_SINT64"
registry.RegistEnum(google_protobuf_type_pb.Field.Kind)
google_protobuf_type_pb.Field.Cardinality = {}
google_protobuf_type_pb.Field.Cardinality._FullName = ".google.protobuf.Field.Cardinality"
google_protobuf_type_pb.Field.Cardinality._Descriptor = "google_protobuf_type_pb_desc.message_type[2].enum_type[2]"
google_protobuf_type_pb.Field.Cardinality.CARDINALITY_UNKNOWN = 0
google_protobuf_type_pb.Field.Cardinality.CARDINALITY_OPTIONAL = 1
google_protobuf_type_pb.Field.Cardinality.CARDINALITY_REQUIRED = 2
google_protobuf_type_pb.Field.Cardinality.CARDINALITY_REPEATED = 3
google_protobuf_type_pb.Field.Cardinality[0] = ".google.protobuf.Field.Cardinality.CARDINALITY_UNKNOWN"
google_protobuf_type_pb.Field.Cardinality[1] = ".google.protobuf.Field.Cardinality.CARDINALITY_OPTIONAL"
google_protobuf_type_pb.Field.Cardinality[2] = ".google.protobuf.Field.Cardinality.CARDINALITY_REQUIRED"
google_protobuf_type_pb.Field.Cardinality[3] = ".google.protobuf.Field.Cardinality.CARDINALITY_REPEATED"
registry.RegistEnum(google_protobuf_type_pb.Field.Cardinality)
---@type fun():google_protobuf_type_pb.Field
google_protobuf_type_pb.Field = protobuf.Message(google_protobuf_type_pb_desc.message_type[2])
google_protobuf_type_pb.Field._FullName = ".google.protobuf.Field"
google_protobuf_type_pb.Field._Descriptor = "google_protobuf_type_pb_desc.message_type[2]"
registry.RegistMessage(google_protobuf_type_pb.Field)
---@type fun():google_protobuf_type_pb.Enum
google_protobuf_type_pb.Enum = protobuf.Message(google_protobuf_type_pb_desc.message_type[3])
google_protobuf_type_pb.Enum._FullName = ".google.protobuf.Enum"
google_protobuf_type_pb.Enum._Descriptor = "google_protobuf_type_pb_desc.message_type[3]"
registry.RegistMessage(google_protobuf_type_pb.Enum)
---@type fun():google_protobuf_type_pb.EnumValue
google_protobuf_type_pb.EnumValue = protobuf.Message(google_protobuf_type_pb_desc.message_type[4])
google_protobuf_type_pb.EnumValue._FullName = ".google.protobuf.EnumValue"
google_protobuf_type_pb.EnumValue._Descriptor = "google_protobuf_type_pb_desc.message_type[4]"
registry.RegistMessage(google_protobuf_type_pb.EnumValue)
---@type fun():google_protobuf_type_pb.Option
google_protobuf_type_pb.Option = protobuf.Message(google_protobuf_type_pb_desc.message_type[5])
google_protobuf_type_pb.Option._FullName = ".google.protobuf.Option"
google_protobuf_type_pb.Option._Descriptor = "google_protobuf_type_pb_desc.message_type[5]"
registry.RegistMessage(google_protobuf_type_pb.Option)
return google_protobuf_type_pb
|
--[[
Utillity functions for handling command-line parameters.
They each take a list of possible arguments(like lua's arg table),
a name for the argument(without the -- prefix), and a default value.
If the argument is found, a value of the correct type(boolean, string or number),
and the index in the arg table is returned. If it's not found, the default value
(if any) is returned.
]]
local args_parse = {}
-- Decode a flag(boolean) argument. e.g.: --foo, --no_foo
function args_parse.get_arg_flag(args, arg_name, default)
local flag_str = "--"..arg_name
local no_flag_str = "--no_"..arg_name
for i,arg in ipairs(args) do
if arg==flag_str then
return true, i
elseif arg==no_flag_str then
return false, i
end
end
return default
end
-- decode a string argument. e.g.: --foo=test, --foo="hello world"
function args_parse.get_arg_str(args, arg_name, default)
local normal_pattern = "^%-%-"..arg_name.."=(.*)$"
local quote_pattern = "^%-%-"..arg_name.."=\"(.*)\"$"
for i,arg in ipairs(args) do
local str = arg:match(quote_pattern) or arg:match(normal_pattern)
if str then
return str, i
end
end
return default
end
-- helper to convert empty string to false
function args_parse.empty_str_to_false(str)
return (str~="" and str)
end
-- helper function that automatically removes an argument once it has been matched
-- should work with: get_arg_num, get_arg_str, get_arg_flag
function args_parse.remove_if_match(fn, args, ...)
local ret, match_i = fn(args, ...)
if match_i and tonumber(match_i) then
table.remove(args, match_i)
end
return ret, match_i
end
-- decode a numeric argument. e.g.: --foo=123, foo=0xCAFE
function args_parse.get_arg_num(args, arg_name, default)
local num_pattern = "^%-%-"..arg_name.."=(.*)$"
for i,arg in ipairs(args) do
local num_str = arg:match(num_pattern)
if num_str and (num_str:sub(1,2):lower()=="0x") and tonumber(num_str:sub(3), 16) then
return tonumber(num_str:sub(3), 16), i
elseif num_str and tonumber(num_str) then
return tonumber(num_str), i
end
end
return default
end
--get list of loose arguments(starting without --)
function args_parse.get_loose_args(args)
local loose = {}
for _,arg_str in ipairs(args) do
if not arg_str:match("^%-%-") then
table.insert(loose, arg_str)
end
end
if #loose > 0 then
return loose
end
end
function args_parse.terminate(reason)
-- reset the terminal colors, print red message, and stop
io.stderr:write("\027[0m\027[31m", reason, "\027[0m\n")
os.exit(1)
end
-- utillity function to return a simple logger function with a log level that can be specified in the arguments
-- lua usage:
--local log,logf = args_parse.logger_from_args(args, "error", "warning", "info", "debug")
--logf("info", "Hello world at unix timestamp: %d!", os.time())
-- supported arguments:
--log=stderr # set default log type to stderrr
--log=file.txt # set default log output to file.txt
--log=disabled # disable all log output(unless enabled)
--log_append # append to the default log
--log_error=stderr # log error log level to stderr
--log_warning=stdout # log warning log level to stdout
--log_debug=debug.txt # log debug log level to file debug.txt
--log_debug_append # append to log debug log file
--no_log_info # disable info log level
--log_debug2 # enable debug2 log level
function args_parse.logger_from_args(args, ...)
local default_log_type_str = args_parse.empty_str_to_false(args_parse.get_arg_str(args, "log"))
local default_log_file = io.stderr
if default_log_type_str == "stderr" then
default_log_file = io.stderr
elseif default_log_type_str == "stdout" then
default_log_file = io.stdout
elseif default_log_type_str and (default_log_type_str~="disabled") then
local append = args_parse.get_arg_flag(args, "default_log_append")
local file = io.open(default_log_type_str, (append and "a") or "w")
if not file then
return args_parse.terminate("Invalid log type or can't open file:", default_log_type_str)
end
default_log_file = file
end
local log_levels = {}
for i, log_level in ipairs({...}) do
local log_entry = {name=log_level, enabled=not (default_log_type_str=="disabled"), file=default_log_file}
log_levels[i] = log_entry
log_levels[log_level] = log_entry
end
for _,log_entry in ipairs(log_levels) do
local log_type_str = args_parse.empty_str_to_false(args_parse.get_arg_str(args, "log_"..log_entry.name))
if log_type_str=="stderr" then
log_entry.file = io.stderr
elseif log_type_str=="stdout" then
log_entry.file = io.stdout
elseif log_type_str=="disabled" then
log_entry.enabled = false
elseif log_type_str then
local append = args_parse.get_arg_flag(args, "log_"..log_entry.name.."_append")
local file = io.open(log_type_str, (append and "a") or "w")
if not file then
return args_parse.terminate("Invalid log type or can't open file:", log_type_str)
end
log_entry.file = file
end
local log_bool = args_parse.get_arg_flag(args, "log_"..log_entry.name)
if log_bool ~= nil then
log_entry.enabled = log_bool
end
end
local function log(log_level, ...)
local log_fmt = "[%s %s]:\t %s\n"
local date_fmt = "%H:%M:%S"
local log_entry = assert(log_levels[log_level], "Bad log level specified")
local arg_str = {}
for _,arg in pairs({...}) do
arg_str[#arg_str+1] = tostring(arg)
end
arg_str = table.concat(arg_str, "\t")
if log_entry.enabled then
log_entry.file:write(log_fmt:format(log_entry.name, os.date(date_fmt), arg_str))
end
return arg_str
end
local function logf(log_level, fmt, ...)
return log(log_level, fmt:format(...))
end
return log,logf,log_levels
end
return args_parse
|
-- add target
target("pdcurses")
-- make as a static library
set_kind("static")
-- add includes directory
add_includedirs("pdcurses", {public = true})
-- add the common source files
add_files("pdcurses/pdcurses/*.c", "pdcurses/win32/*.c")
-- add defines
add_defines("PDC_WIDE")
-- set languages
set_languages("c89")
|
--[[ LICENSE HEADER
MIT Licensing
Copyright © 2017 Jordan Irwin
See: LICENSE.txt
--]]
local worldpath = core.get_worldpath()
local ownedpath = worldpath .. '/owned'
-- Spawns an entity & writes meta data to world directory
local function spawn(entity)
end
|
format_version = "1.0"
rtc_bindings = {
{ source = "/environment/system_sample_rate", dest = "/global_rtc/init_instance" },
{ source = "/environment/instance_id", dest = "/global_rtc/init_instance" },
}
global_rtc = {
init_instance = function(source_property_path, instance_id)
local new_no = jbox.make_native_object_rw("Instance", {instance_id})
jbox.store_property("/custom_properties/instance", new_no);
end,
}
sample_rate_setup = {
native = {
22050,
44100,
48000,
88200,
96000,
192000
},
}
rt_input_setup = {
notify = {
"/custom_properties/builtin_onoffbypass",
"/custom_properties/GrowthRate",
"/custom_properties/Barrier",
"/custom_properties/InputScale",
"/custom_properties/Amplitude",
"/custom_properties/Smoothing",
"/custom_properties/Smooth",
"/custom_properties/Zero",
"/audio_inputs/audioIn/connected",
"/cv_inputs/cvIn/connected",
"/audio_outputs/audioOut/connected",
"/cv_outputs/cvOut/connected",
}
} |
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
local Clockwork = Clockwork;
local COMMAND = Clockwork.command:New("PluginLoad");
COMMAND.tip = "CmdPluginLoad";
COMMAND.text = "CmdPluginLoadDesc";
COMMAND.flags = CMD_DEFAULT;
COMMAND.access = "s";
COMMAND.arguments = 1;
-- Called when the command has been run.
function COMMAND:OnRun(player, arguments)
local plugin = Clockwork.plugin:FindByID(arguments[1]);
if (!plugin) then
Clockwork.player:Notify(player, {"PluginNotValid"});
return;
end;
local unloadTable = Clockwork.command:FindByID("PluginLoad");
local loadTable = Clockwork.command:FindByID("PluginLoad");
if (!Clockwork.plugin:IsDisabled(plugin.name)) then
local wasSuccess = Clockwork.plugin:SetUnloaded(plugin.name, false);
local recipients = {};
if (wasSuccess) then
Clockwork.player:NotifyAll({"PlayerLoadedPlugin", player:Name(), plugin.name});
for k, v in pairs(cwPlayer.GetAll()) do
if (v:HasInitialized()) then
if (Clockwork.player:HasFlags(v, loadTable.access)
or Clockwork.player:HasFlags(v, unloadTable.access)) then
recipients[#recipients + 1] = v;
end;
end;
end;
if (#recipients > 0) then
Clockwork.datastream:Start(recipients, "SystemPluginSet", {plugin.name, false});
end;
else
Clockwork.player:Notify(player, {"PluginCouldNotBeLoaded"});
end;
else
Clockwork.player:Notify(player, {"PluginDependsOnAnother"});
end;
end;
COMMAND:Register(); |
-- robot.lua
local controls = require("controls")
local lcd = require("lcd")
local wpilib = require("wpilib")
local pairs = pairs
module(..., package.seeall)
local TELEOP_LOOP_LAG = 0.005
-- Declarations
local watchdogEnabled = false
local feedWatchdog, enableWatchdog, disableWatchdog
local teleop
local controlMap
local driveX, driveY, wristControl, intakeControl
local robotDrive
local leftDriveMotor, rightDriveMotor, wristMotor, intakeMotor
-- End Declarations
function run()
lcd.print(1, "Ready")
lcd.update()
-- Main loop
while true do
if wpilib.IsDisabled() then
-- TODO: run disabled function
disableWatchdog()
repeat wpilib.Wait(0.01) until not wpilib.IsDisabled()
enableWatchdog()
elseif wpilib.IsAutonomous() then
-- TODO: autonomous
disableWatchdog()
repeat wpilib.Wait(0.01) until not wpilib.IsAutonomous() or not wpilib.IsEnabled()
enableWatchdog()
else
teleop()
disableWatchdog()
repeat wpilib.Wait(0.01) until not wpilib.IsOperatorControl() or not wpilib.IsEnabled()
enableWatchdog()
end
end
end
function teleop()
disableWatchdog()
while wpilib.IsOperatorControl() and wpilib.IsEnabled() do
lcd.print(1, "Running!")
lcd.update()
-- Read controls
controls.update(controlMap)
-- Drive
robotDrive:ArcadeDrive(driveY, driveX)
-- Arm
wristMotor:Set(wristControl)
if clawSwitch:Get() then
intakeMotor:Set(intakeControl)
else
intakeMotor:Set(0.0)
end
wpilib.Wait(TELEOP_LOOP_LAG)
end
end
-- Inputs/Outputs
-- Don't forget to add to declarations at the top!
leftDriveMotor = wpilib.Victor(4, 10)
rightDriveMotor = wpilib.Victor(4, 9)
wristMotor = wpilib.Victor(4, 7)
intakeMotor = wpilib.Victor(4, 8)
clawSwitch = wpilib.DigitalInput(4, 1)
-- End Inputs/Outputs
-- Controls
driveX, driveY = 0, 0
intakeSpeed = 0
robotDrive = wpilib.RobotDrive(leftDriveMotor, rightDriveMotor)
robotDrive:SetInvertedMotor(wpilib.RobotDrive_kFrontLeftMotor, true)
robotDrive:SetInvertedMotor(wpilib.RobotDrive_kFrontRightMotor, true)
robotDrive:SetInvertedMotor(wpilib.RobotDrive_kRearLeftMotor, true)
robotDrive:SetInvertedMotor(wpilib.RobotDrive_kRearRightMotor, true)
controlMap =
{
-- Joystick 1
{
["x"] = function(axis) driveX = axis end,
["y"] = function(axis) driveY = axis end,
},
-- Joystick 2
{
["y"] = function(axis) wristControl = axis end,
update=function(stick)
if stick:GetRawButton(1) then
intakeControl = 0.6
elseif stick:GetRawButton(2) or stick:GetRawButton(3) or stick:GetRawButton(4) or stick:GetRawButton(5) then
intakeControl = -1
else
intakeControl = 0
end
end,
},
-- Joystick 3
{
},
-- Joystick 4 (eStop Module)
{
},
-- Cypress Module
cypress={},
}
-- End Controls
-- Watchdog shortcuts
if watchdogEnabled then
wpilib.GetWatchdog():SetExpiration(0.25)
function feedWatchdog()
local dog = wpilib.GetWatchdog()
dog:Feed()
end
function enableWatchdog()
local dog = wpilib.GetWatchdog()
dog:SetEnabled(true)
end
function disableWatchdog()
local dog = wpilib.GetWatchdog()
dog:SetEnabled(false)
end
else
local dog = wpilib.GetWatchdog()
dog:SetEnabled(false)
feedWatchdog = function() end
enableWatchdog = function() end
disableWatchdog = function() end
end
-- vim: ft=lua et ts=4 sts=4 sw=4
|
--クラインアント
--Kleinant
--Scripted by Eerie Code
function c45778242.initial_effect(c)
--increase stats
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetCondition(c45778242.atkcon)
e1:SetTarget(aux.TargetBoolFunction(Card.IsRace,RACE_CYBERS))
e1:SetValue(500)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e2)
--destroy replace
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_DESTROY_REPLACE)
e3:SetTarget(c45778242.reptg)
e3:SetOperation(c45778242.repop)
c:RegisterEffect(e3)
end
function c45778242.atkcon(e)
local tp=e:GetHandlerPlayer()
return Duel.GetTurnPlayer()==tp and e:GetHandler():IsSummonType(SUMMON_TYPE_NORMAL)
end
function c45778242.repfilter(c)
return (c:IsFaceup() or c:IsLocation(LOCATION_HAND)) and c:IsRace(RACE_CYBERS) and not c:IsStatus(STATUS_DESTROY_CONFIRMED)
end
function c45778242.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return not c:IsReason(REASON_REPLACE) and c:IsLocation(LOCATION_MZONE) and c:IsFaceup()
and Duel.IsExistingMatchingCard(c45778242.repfilter,tp,LOCATION_MZONE+LOCATION_HAND,0,1,c) end
if Duel.SelectYesNo(tp,aux.Stringid(45778242,0)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESREPLACE)
local g=Duel.SelectMatchingCard(tp,c45778242.repfilter,tp,LOCATION_MZONE+LOCATION_HAND,0,1,1,c)
Duel.SetTargetCard(g)
g:GetFirst():SetStatus(STATUS_DESTROY_CONFIRMED,true)
return true
else return false end
end
function c45778242.repop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
g:GetFirst():SetStatus(STATUS_DESTROY_CONFIRMED,false)
Duel.Destroy(g,REASON_EFFECT+REASON_REPLACE)
end
|
cc.exports.XGVersionUpdate = {
VersionCode = 2,
} |
module 'character'
CLASS: EventParticle ( CharacterActionEvent )
:MODEL{
Field 'particle': asset( 'particle_system' )
}
CLASS: TrackParticle ( CharacterActionTrack )
:MODEL{}
|
local canvas = {}
canvas.__index = canvas
function canvas.new(name, x, y, width, height)
local self = setmetatable({}, canvas)
self.position = {x, y}
self.target = love.graphics.newCanvas(width, height)
self.name = name
return self
end
function canvas:renderTo(func)
if self.name == "right" then
return
end
self.target:renderTo(assert:type(func, "function"))
end
function canvas:draw()
if self.name == "right" then
return
end
local x, y = unpack(self.position)
love.graphics.setColor(1, 1, 1, 1)
love.graphics.draw(self.target, x, y)
end
function canvas:getWidth()
return self.target:getWidth()
end
function canvas:getHeight()
return self.target:getHeight()
end
return canvas
|
-- MISCELLANEOUS
-- The update rate, i.e. run every UpdateRate calls to Update method.
-- Set to 1 to update every call.
-- Setting to e.g. 10 means to run every 10th call.
-- Smaller means more responsive, but also means more processor usage.
UpdateRate = 4
|
// ======= Copyright (c) 2003-2012, Unknown Worlds Entertainment, Inc. All rights reserved. =====
//
// lua\EventTester.lua
//
// Created by: Brian Cronin (brianc@unknownworlds.com)
//
// EventTester is a tool to help ensure gameplay events are triggered during play testing.
// Gameplay code is scanned during load for function calls to "TEST_EVENT()".
// These event names are sent to Clients when event testing is enabled and displayed
// as a list. As these functions are called, the event name is "checked off" the list.
//
// ========= For more information, visit us at http://www.unknownworlds.com =====================
local testEvents = { }
local eventTestingEnabled = false
local kEventTestingEnabled =
{
enabled = "boolean"
}
Shared.RegisterNetworkMessage("EventTestingEnabled", kEventTestingEnabled)
local kMaxEventNameLength = 128
local kEventTested =
{
name = "string (" .. kMaxEventNameLength .. ")",
timesTested = "integer"
}
Shared.RegisterNetworkMessage("EventTested", kEventTested)
if Server then
local function SyncEventTestingEnabled(client, enabled)
if client then
Server.SendNetworkMessage(client, "EventTestingEnabled", { enabled = enabled }, true)
else
Server.SendNetworkMessage("EventTestingEnabled", { enabled = enabled }, true)
end
end
local function SyncEventTested(client, eventName, timesTested)
if client then
Server.SendNetworkMessage(client, "EventTested", { name = eventName, timesTested = timesTested }, true)
else
Server.SendNetworkMessage("EventTested", { name = eventName, timesTested = timesTested }, true)
end
end
local function SyncEventTestingState(client)
SyncEventTestingEnabled(client, eventTestingEnabled)
if eventTestingEnabled then
for name, timesTested in pairs(testEvents) do
SyncEventTested(client, name, timesTested)
end
end
end
function SetEventTestingEnabled(setEnabled)
if eventTestingEnabled ~= setEnabled then
eventTestingEnabled = setEnabled
SyncEventTestingState()
end
end
local function SharedTestEvent(eventName)
if eventTestingEnabled then
testEvents[eventName] = (testEvents[eventName] and testEvents[eventName] + 1) or 1
SyncEventTested(nil, eventName, testEvents[eventName])
end
end
function TEST_EVENT(eventName)
SharedTestEvent(eventName)
end
local function OnEventTested(client, message)
SharedTestEvent(message.name)
end
Server.HookNetworkMessage("EventTested", OnEventTested)
local function OnClientConnect(client)
SyncEventTestingState(client)
end
Event.Hook("ClientConnect", OnClientConnect)
elseif Client then
local function SetGUIEventTesterEnabled(enabled, testEvents)
local eventTester = GetGUIManager():CreateGUIScriptSingle("GUIEventTester")
eventTester:SetTestEvents(testEvents)
eventTester:SetIsVisible(enabled)
end
local function OnEventTestingEnabled(message)
if eventTestingEnabled ~= message.enabled then
eventTestingEnabled = message.enabled
SetGUIEventTesterEnabled(eventTestingEnabled, testEvents)
end
end
Client.HookNetworkMessage("EventTestingEnabled", OnEventTestingEnabled)
local function OnEventTested(message)
testEvents[message.name] = message.timesTested
local eventTester = GetGUIManager():CreateGUIScriptSingle("GUIEventTester")
eventTester:SetTestEvents(testEvents)
end
Client.HookNetworkMessage("EventTested", OnEventTested)
function TEST_EVENT(eventName)
// The Client doesn't send the number of times tested.
if eventTestingEnabled then
Client.SendNetworkMessage("EventTested", { name = eventName, timesTested = 0 }, true)
end
end
local function SetUIOpacity(opacity)
GetGUIManager():CreateGUIScriptSingle("GUIEventTester"):SetOpacity(tonumber(opacity))
end
Event.Hook("Console_test_events_opacity", SetUIOpacity)
elseif Predict then
/**
* Do nothing while predicting.
*/
function TEST_EVENT(eventName)
end
end
function GetEventTestingEnabled()
return eventTestingEnabled
end
local function OnScriptLoaded(fileName)
local file = io.open("game://" .. fileName, "r")
if file then
local fileStr = file:read("*all")
io.close(file)
for eventName in string.gmatch(fileStr, "TEST_EVENT%(\".-\"%)") do
local cleanEventName = string.match(eventName, "\".-\"")
cleanEventName = string.gsub(cleanEventName, "\"", "")
if string.len(cleanEventName) > kMaxEventNameLength then
Shared.Message(cleanEventName " is too long. " .. kMaxEventNameLength .. " is the max length.")
else
testEvents[cleanEventName] = 0
end
end
end
end
local scriptLoad = Script.Load
function Script.Load(fileName, reload)
scriptLoad(fileName, reload)
OnScriptLoaded(fileName)
end |
term = {}
number1 = 4111 + math.random(5888)
number2 = 2111 + math.random(number1 - 3000)
result = number1 - number2
term[1] = math.random(1000) + 700;
term[2] = math.random(number2 - 2000) + 300;
term[3] = math.random( 1000) + 1500;
term[4] = math.random(number2 - 1000) + 900;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.