content
stringlengths 5
1.05M
|
|---|
GLib.UTF8 = {}
local math_floor = math.floor
local string_byte = string.byte
local string_char = string.char
local string_len = string.len
local string_lower = string.lower
local string_find = string.find
local string_format = string.format
local string_gsub = string.gsub
local string_sub = string.sub
local string_upper = string.upper
local table_concat = table.concat
function GLib.UTF8.Byte (char, offset)
if char == "" then return -1 end
offset = offset or 1
local byte = string_byte (char, offset)
local length = 1
if byte >= 128 then
-- multi-byte sequence
if byte >= 240 then
-- 4 byte sequence
length = 4
if #char < 4 then return -1, length end
byte = (byte % 8) * 262144
byte = byte + (string_byte (char, offset + 1) % 64) * 4096
byte = byte + (string_byte (char, offset + 2) % 64) * 64
byte = byte + (string_byte (char, offset + 3) % 64)
elseif byte >= 224 then
-- 3 byte sequence
length = 3
if #char < 3 then return -1, length end
byte = (byte % 16) * 4096
byte = byte + (string_byte (char, offset + 1) % 64) * 64
byte = byte + (string_byte (char, offset + 2) % 64)
elseif byte >= 192 then
-- 2 byte sequence
length = 2
if #char < 2 then return -1, length end
byte = (byte % 32) * 64
byte = byte + (string_byte (char, offset + 1) % 64)
else
-- this is a continuation byte
-- invalid sequence
byte = -1
end
else
-- single byte sequence
end
return byte, length
end
function GLib.UTF8.Char (byte)
local utf8 = ""
if byte < 0 then
utf8 = ""
elseif byte <= 127 then
utf8 = string_char (byte)
elseif byte < 2048 then
utf8 = string_format ("%c%c", 192 + math_floor (byte / 64), 128 + (byte % 64))
elseif byte < 65536 then
utf8 = string_format ("%c%c%c", 224 + math_floor (byte / 4096), 128 + (math_floor (byte / 64) % 64), 128 + (byte % 64))
elseif byte < 2097152 then
utf8 = string_format ("%c%c%c%c", 240 + math_floor (byte / 262144), 128 + (math_floor (byte / 4096) % 64), 128 + (math_floor (byte / 64) % 64), 128 + (byte % 64))
end
return utf8
end
function GLib.UTF8.CharacterToOffset (str, char)
local offset = 1
local iterator = GLib.UTF8.Iterator (str)
local c
for i = 1, char - 1 do
c = iterator ()
if not c then break end
offset = offset + #c
end
return offset
end
function GLib.UTF8.ChunkSplit (str, chunkSize)
local chunks = {}
local chunkStart = 1
while chunkStart <= #str do
if #chunks > 1e5 then
GLib.Error ("UTF8.ChunkSplit : 100,000 chunks??")
break
end
local chunkEnd = GLib.UTF8.GetSequenceStart (str, chunkStart + chunkSize)
if chunkStart >= chunkEnd then
chunkEnd = chunkStart + GLib.UTF8.SequenceLength (str, chunkStart)
end
chunks [#chunks + 1] = string_sub (str, chunkStart, chunkEnd - 1)
chunkStart = chunkEnd
end
return chunks
end
function GLib.UTF8.ContainsSequences (str, offset)
return string_find (str, "[\192-\255]", offset) and true or false
end
function GLib.UTF8.Decompose (str)
local map = {}
local inverseMap = {}
local t = {}
local outputOffset = 1
for c, offset in GLib.UTF8.Iterator (str) do
local decomposition = GLib.Unicode.DecomposeCharacter (c)
t [#t + 1] = decomposition
map [offset] = outputOffset
inverseMap [outputOffset] = offset
outputOffset = outputOffset + #decomposition
end
map [#str + 1] = outputOffset
inverseMap [outputOffset] = #str + 1
return table.concat (t), map, inverseMap
end
function GLib.UTF8.GetGraphemeStart (str, offset)
return GLib.UTF8.GetSequenceStart (str, offset)
end
function GLib.UTF8.GetSequenceStart (str, offset)
if offset <= 0 then return 1 end
if offset > #str then return #str + 1 end
local startOffset = offset
while startOffset >= 1 do
byte = string_byte (str, startOffset)
-- Either a single byte sequence or
-- an improperly started multi byte sequence, in which case it's treated as one byte long
if byte <= 127 then return offset end
-- Start of multibyte sequence
if byte >= 192 then return startOffset end
startOffset = startOffset - 1
end
return startOffset
end
function GLib.UTF8.GraphemeIterator (str, offset)
return GLib.UTF8.Iterator (str, offset)
end
function GLib.UTF8.Iterator (str, offset)
offset = offset or 1
if offset <= 0 then offset = 1 end
return function ()
if offset > #str then return nil, #str + 1 end
-- Inline expansion of GLib.UTF8.SequenceLength (str, offset)
local length
local byte = string_byte (str, offset)
if not byte then length = 0
elseif byte >= 240 then length = 4
elseif byte >= 224 then length = 3
elseif byte >= 192 then length = 2
else length = 1 end
local character = string_sub (str, offset, offset + length - 1)
local lastOffset = offset
offset = offset + length
return character, lastOffset
end
end
function GLib.UTF8.Length (str)
local _, length = string_gsub (str, "[^\128-\191]", "")
return length
end
local function MatchesTransliterationCharacter (character, substring, offset, firstCharacterMatch)
local substringCharacter = GLib.UTF8.NextChar (substring, offset)
if GLib.Unicode.ToLower (character) == GLib.Unicode.ToLower (substringCharacter) then
-- Exact match found
return #substringCharacter
end
-- Some types of characters should not match any ASCII characters
local unicodeCategory = GLib.Unicode.GetCharacterCategory (character)
if not firstCharacterMatch then
if GLib.Unicode.IsCombiningCategory (unicodeCategory) then return 0 end
if GLib.Unicode.IsControlCategory (unicodeCategory) then return 0 end
if GLib.Unicode.IsSeparatorCategory (unicodeCategory) then return 0 end
end
local transliterations = GLib.Unicode.GetTransliterationTable () [character]
if transliterations then
-- Try each possible transliteration
for _, transliteration in ipairs (transliterations) do
local totalMatchLength = 0
local fail = false
-- Attempt to match each character of the transliteration against the substring
for c in GLib.UTF8.Iterator (transliteration) do
-- Check if the end of the substring has been reached (success)
if offset + totalMatchLength > #substring then break end
local matchLength = MatchesTransliterationCharacter (c, substring, offset + totalMatchLength)
if matchLength then
-- Character match succeeded, advance
totalMatchLength = totalMatchLength + matchLength
else
-- Character match failed
fail = true
break
end
end
if not fail then
return totalMatchLength
end
end
end
-- Absorb unmatchable non-ASCII characters
if substringCharacter == " " then return 1 end
if not firstCharacterMatch and
#character > 1 and
not GLib.Unicode.IsLetterCategory (unicodeCategory) then
return 0
end
return nil
end
function GLib.UTF8.MatchTransliteration (str, substring, strOffset)
local str, strMap, strInverseMap = GLib.UTF8.Decompose (str)
local substring = GLib.UTF8.Decompose (substring)
-- Try to start matching the substring against each character of the string
strOffset = strMap [strOffset]
for _, startOffset in GLib.UTF8.Iterator (str, strOffset) do
local stringIterator = GLib.UTF8.Iterator (str, startOffset)
local stringCharacter, stringCharacterOffset = stringIterator ()
local substringOffset = 1
-- Advance through the string and substring whilst matches characters
local firstCharacterMatch = true
while substringOffset <= #substring do
-- Check if the end of the string has been reached
if not stringCharacter then break end
-- Attempt to match the character(s)
local matchLength = MatchesTransliterationCharacter (stringCharacter, substring, substringOffset, firstCharacterMatch)
firstCharacterMatch = false
-- Check if the match failed
if not matchLength then break end
-- Advance
substringOffset = substringOffset + matchLength
stringCharacter, stringCharacterOffset = stringIterator ()
end
if substringOffset > #substring then
-- Match succeeded
-- Fixup offsets
while not strInverseMap [startOffset] do
startOffset = startOffset - 1
end
while not strInverseMap [stringCharacterOffset] do
stringCharacterOffset = stringCharacterOffset + 1
end
return true, strInverseMap [startOffset], strInverseMap [stringCharacterOffset] - 1
end
end
return false, nil, nil
end
function GLib.UTF8.NextChar (str, offset)
offset = offset or 1
if offset <= 0 then offset = 1 end
-- Inline expansion of GLib.UTF8.SequenceLength (str, offset)
local length
local byte = string_byte (str, offset)
if not byte then length = 0
elseif byte >= 240 then length = 4
elseif byte >= 224 then length = 3
elseif byte >= 192 then length = 2
else length = 1 end
return string_sub (str, offset, offset + length - 1), offset + length
end
local lineBreaks =
{
["\r"] = true,
["\n"] = true
}
local function GetWordType (grapheme)
local codePoint = GLib.UTF8.Byte (grapheme)
if string_sub (grapheme, 1, 1) == "_" or GLib.Unicode.IsLetterOrDigitCodePoint (codePoint) then
return GLib.WordType.Alphanumeric
elseif lineBreaks [string_sub (grapheme, 1, 1)] then
return GLib.WordType.LineBreak
elseif GLib.Unicode.IsWhitespaceCodePoint (codePoint) then
return GLib.WordType.Whitespace
end
return GLib.WordType.Other
end
function GLib.UTF8.NextWordBoundary (str, offset)
local iterator = GLib.UTF8.GraphemeIterator (str, offset)
local leftGrapheme, leftOffset = iterator ()
local leftWordType = leftGrapheme and GetWordType (leftGrapheme) or GLib.WordType.None
local rightGrapheme
local rightOffset
local rightWordType
while true do
rightGrapheme, rightOffset = iterator ()
if not rightGrapheme then return rightOffset, leftWordType, GLib.WordType.None end
rightWordType = GetWordType (rightGrapheme)
if leftWordType ~= rightWordType then
return rightOffset, leftWordType, rightWordType
end
leftGrapheme = rightGrapheme
leftOffset = rightOffset
leftWordType = rightWordType
end
end
-- This isn't used anywhere
-- Behaviour is subject to change
function GLib.UTF8.PreviousChar (str, offset)
offset = offset or (#str + 1)
if offset <= 1 then return "", 0 end
local startOffset = GLib.UTF8.GetSequenceStart (str, offset - 1)
local length = GLib.UTF8.SequenceLength (str, startOffset)
return string_sub (str, startOffset, startOffset + length - 1), startOffset
end
function GLib.UTF8.PreviousWordBoundary (str, offset)
local iterator = GLib.UTF8.ReverseGraphemeIterator (str, offset)
local rightGrapheme, rightOffset = iterator ()
local rightWordType = rightGrapheme and GetWordType (rightGrapheme) or GLib.WordType.None
local leftGrapheme
local leftOffset
local leftWordType
while true do
leftGrapheme, leftOffset = iterator ()
if not leftGrapheme then return rightOffset, GLib.WordType.None, rightWordType end
leftWordType = GetWordType (leftGrapheme)
if leftWordType ~= rightWordType then
return rightOffset, leftWordType, rightWordType
end
rightGrapheme = leftGrapheme
rightOffset = leftOffset
rightWordType = leftWordType
end
end
function GLib.UTF8.ReverseGraphemeIterator (str, offset)
return GLib.UTF8.ReverseIterator (str, offset)
end
function GLib.UTF8.ReverseIterator (str, offset)
offset = offset or (#str + 1)
return function ()
if offset <= 1 then return nil, nil end
offset = GLib.UTF8.GetSequenceStart (str, offset - 1)
-- Inline expansion of GLib.UTF8.SequenceLength (str, offset)
local length
local byte = string_byte (str, offset)
if not byte then length = 0
elseif byte >= 240 then length = 4
elseif byte >= 224 then length = 3
elseif byte >= 192 then length = 2
else length = 1 end
return string_sub (str, offset, offset + length - 1), offset
end
end
function GLib.UTF8.SequenceLength (str, offset)
local byte = string_byte (str, offset)
if not byte then return 0
elseif byte >= 240 then return 4
elseif byte >= 224 then return 3
elseif byte >= 192 then return 2
else return 1 end
end
function GLib.UTF8.SplitAt (str, char)
local c, offset = nil, 1
local offsetChar = 1 -- character index corresponding to offset
while c ~= "" do
if offsetChar >= char then
return string_sub (str, 1, offset - 1), string_sub (str, offset)
end
c, offset = GLib.UTF8.NextChar (str, offset)
offsetChar = offsetChar + 1
end
return str
end
function GLib.UTF8.StripCombiningCharacters (str)
return GLib.UTF8.TransformUnicodeString (str,
function (c)
if GLib.Unicode.IsCombiningCharacter (c) then return nil end
return c
end
)
end
function GLib.UTF8.Sub (str, startCharacter, endCharacter)
return GLib.UTF8.SubOffset (str, 1, startCharacter, endCharacter)
end
function GLib.UTF8.SubOffset (str, offset, startCharacter, endCharacter)
if not str then return "" end
if offset < 1 then offset = 1 end
local charactersSkipped = offset - 1
if startCharacter > #str - charactersSkipped then return "" end
if endCharacter then
if endCharacter < startCharacter then return "" end
if endCharacter > #str - charactersSkipped then endCharacter = nil end
end
local iterator = GLib.UTF8.Iterator (str, offset)
local nextCharacter = 1
while nextCharacter < startCharacter do
iterator ()
nextCharacter = nextCharacter + 1
end
local _, startOffset = iterator ()
if not startOffset then return "" end
nextCharacter = nextCharacter + 1
if not endCharacter then
return string_sub (str, startOffset)
end
while nextCharacter <= endCharacter do
iterator ()
nextCharacter = nextCharacter + 1
end
local _, endOffset = iterator ()
if endOffset then
return string_sub (str, startOffset, endOffset - 1)
else
return string_sub (str, startOffset)
end
end
function GLib.UTF8.FromLatin1 (str)
local out = {}
for i = 1, #str do
out [#out + 1] = GLib.UTF8.Char (string_byte (str, i))
end
return table_concat (out)
end
function GLib.UTF8.ToLatin1 (str)
str = GLib.UTF8.Decompose (str)
return GLib.UTF8.TransformUnicodeString (str,
function (c)
codePoint = GLib.UTF8.Byte (c)
if codePoint == -1 or codePoint > 255 then
return "?"
end
return string_char (codePoint)
end
)
end
function GLib.UTF8.ToLower (str)
if not GLib.UTF8.ContainsSequences (str) then return string_lower (str) end
return GLib.UTF8.TransformString (str, GLib.Unicode.ToLower)
end
function GLib.UTF8.ToUpper (str)
if not GLib.UTF8.ContainsSequences (str) then return string_upper (str) end
return GLib.UTF8.TransformString (str, GLib.Unicode.ToUpper)
end
function GLib.UTF8.TransformString (str, f)
local transformed = GLib.StringBuilder ()
for c in GLib.UTF8.Iterator (str) do
c = f (c)
if c then transformed = transformed .. c end
end
return transformed:ToString ()
end
function GLib.UTF8.TransformUnicodeString (str, f)
if not GLib.UTF8.ContainsSequences (str) then return str end
local transformed = GLib.StringBuilder ()
for c in GLib.UTF8.Iterator (str) do
c = f (c)
if c then transformed = transformed .. c end
end
return transformed:ToString ()
end
function GLib.UTF8.Transliterate (str)
local transliterationTable = GLib.Unicode.GetTransliterationTable ()
return GLib.UTF8.TransformString (str,
function (c)
if transliterationTable [c] and transliterationTable [c] [1] then
return transliterationTable [c] [1]
end
return c
end
)
end
function GLib.UTF8.WordIterator (str, offset)
offset = offset or 1
return function ()
local wordBoundaryOffset, leftWordType, rightWordType = GLib.UTF8.NextWordBoundary (str, offset)
local word = string_sub (str, offset, wordBoundaryOffset - 1)
if word == "" then word = nil end
offset = wordBoundaryOffset
return word, leftWordType
end
end
|
-- Creator: Shush
-- Date: 27/5/2020
--------------------
-- BLACK KING BAR --
--------------------
LinkLuaModifier("modifier_item_imba_black_king_bar", "components/items/item_black_king_bar", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_imba_black_king_bar_buff", "components/items/item_black_king_bar", LUA_MODIFIER_MOTION_NONE)
item_imba_black_king_bar = item_imba_black_king_bar or class({})
function item_imba_black_king_bar:GetIntrinsicModifierName()
return "modifier_item_imba_black_king_bar"
end
function item_imba_black_king_bar:OnSpellStart()
-- Ability properties
local caster = self:GetCaster()
local ability = self
local sound_cast = "DOTA_Item.BlackKingBar.Activate"
local modifier_bkb = "modifier_item_imba_black_king_bar_buff"
-- Ability specials
local duration = ability:GetSpecialValueFor("duration")
local max_level = ability:GetSpecialValueFor("max_level")
-- Level up the item if relevant
if ability:GetLevel() < max_level then
ability:SetLevel(ability:GetLevel() + 1)
-- Set level on the caster
caster.bkb_current_level = ability:GetLevel()
end
-- Play cast sound
EmitSoundOn(sound_cast, caster)
-- Apply basic dispel
caster:Purge(false, true, false, false, false)
-- Remove ethereal abilities
for _, modifier_name in pairs(GetEtherealAbilities()) do
if caster:HasModifier(modifier_name) then
caster:RemoveModifierByName(modifier_name)
end
end
-- Give caster the buff
caster:AddNewModifier(caster, ability, modifier_bkb, {duration = duration})
end
---------------------------------------
-- INTRINSIC BLACK KING BAR MODIFIER --
---------------------------------------
modifier_item_imba_black_king_bar = modifier_item_imba_black_king_bar or class({})
function modifier_item_imba_black_king_bar:IsHidden() return true end
function modifier_item_imba_black_king_bar:IsPurgable() return false end
function modifier_item_imba_black_king_bar:RemoveOnDeath() return false end
function modifier_item_imba_black_king_bar:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_item_imba_black_king_bar:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
-- Ability properties
self.caster = self:GetCaster()
self.ability = self:GetAbility()
-- Ability specials
self.bonus_strength = self.ability:GetSpecialValueFor("bonus_strength")
self.bonus_damage = self.ability:GetSpecialValueFor("bonus_damage")
-- Set the item's level according to the caster, if any
if IsServer() then
if self.caster.bkb_current_level and self.ability then
if self.caster.bkb_current_level ~= self.ability:GetLevel() then
self.ability:SetLevel(self.caster.bkb_current_level)
end
end
end
end
function modifier_item_imba_black_king_bar:DeclareFunctions()
local decFuncs = {MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS}
return decFuncs
end
function modifier_item_imba_black_king_bar:GetModifierPreAttack_BonusDamage()
return self.bonus_damage
end
function modifier_item_imba_black_king_bar:GetModifierBonusStats_Strength()
return self.bonus_strength
end
----------------------------------
-- BLACK KING BAR BUFF MODIFIER --
----------------------------------
modifier_item_imba_black_king_bar_buff = modifier_item_imba_black_king_bar_buff or class({})
function modifier_item_imba_black_king_bar_buff:IsHidden() return false end
function modifier_item_imba_black_king_bar_buff:IsPurgable() return false end
function modifier_item_imba_black_king_bar_buff:IsDebuff() return false end
function modifier_item_imba_black_king_bar_buff:GetEffectName()
return "particles/items_fx/black_king_bar_avatar.vpcf"
end
function modifier_item_imba_black_king_bar_buff:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
-- Ability properties
self.ability = self:GetAbility()
-- Ability specials
self.model_scale = self.ability:GetSpecialValueFor("model_scale")
end
function modifier_item_imba_black_king_bar_buff:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_item_imba_black_king_bar_buff:CheckState()
local state = {[MODIFIER_STATE_MAGIC_IMMUNE] = true}
return state
end
function modifier_item_imba_black_king_bar_buff:DeclareFunctions()
local decFuncs = {MODIFIER_PROPERTY_MODEL_SCALE}
end
function modifier_item_imba_black_king_bar_buff:GetModifierModelScale()
return self.model_scale
end
|
local M={}
local tones={
BV= 246,
C = 261,
XC = 277,
D = 294,
XD = 311,
E = 329,
F = 349,
XF = 369,
G = 391,
XG = 415,
A = 440,
XA = 466,
B = 493,
c = 523,
xc = 554,
d = 587,
xd = 622,
e = 659,
f = 698,
xf = 740,
g = 784,
xg = 830,
a = 880,
xa = 932,
b = 987,
z = 0
}
local presets={
"A4A4A4F3c1.A4F3c1A8.e4e4e4f3c1,XG4F3c1A8.a4A3A1a4xg2g.xffxf2z2XA2xd4d2xc2.c1B1c2z2F1XG4F3A1.c4A3c1e8.a4A3A1a4xg2g,xffxf2z2XA2xd4d2xc2.cBc2z2FXG4F3c.A4F3cA8",
"E4.G3E2EA2.E2D2.E4.B3E2Ec2.B2G2.E2B2.e2ED2DBV2.XF2E2",
"C3C1D4C4F4E8.C3C1D4C4G4F8.C3C1c4A4F4E4D8.XA3XA1A4F4G4F8",
"c2A2A4XA2G2G4F2G2A2XA2c2c2c4.c2A2A4XA2G2G4F2A2c2c2F4p2.G2G2G2G2G2A2XA4A2A2A2A2A2XA2c4.c2A2A4XA2G2G4F2A2c2c2F4p2", -- Haenschen klein
"XF2 A2XF2A2XF2 G2E2G2E2 XF2D2A2XF2 E2A2A2 AXF D2D2D2AXF E2E2E2AG XF2D2E2XC2 D4" -- Die Vogelhochzeit
}
local preset=0
local rgb_buf=ws2812.newBuffer(rgb_max,3)
rgb_buf:fill(0,0,0)
local function play(s,p,m,b,i,o)
-- s: tone length p: inter-tone pause m: music string in abc format b: visualize tones with rgb leds
if i == nil then -- init
i=1 -- tone number, for blinking
o=1 -- offset within music string
end
if s==nil then s=125 end
if p==nil then p=20 end
if m==nil then m="" end
local t,q,v,z=m:match("^([xX]?%a[vV]?)(/?)(%d*)([^a-zA-Z0-9]*)",o)
if t == nil then -- end of melody
beep(nil)
if tonumber(cfg.returnmain) then
tmr.alarm(beep_tmr,tonumber(cfg.returnmain),0, function()
modeset("clock")
end)
end
return
end
-- print(t,q,v)
local d=s
if v and v~="" then
if q=="/" then
d=s/v
else
d=s*v
end
end
local f=tones[t]
if not f then f=0 end -- pause if note not found
-- print(f,d)
if b == "1" then
local rgb_dim=cfg.leddim_day or 90
local tp=t:upper():gsub("[XV]","")
local tn=string.find("CDEFGAB",tp)
if tn ~= nil then
rgb_buf:fade(2)
for n=0,4 do
rgb_buf:set((tn+5*n)%rgb_buf:size()+1,rgb_dim*(i%3==0 and 1 or 0),rgb_dim*(i%3==1 and 1 or 0),rgb_dim*(i%3==2 and 1 or 0))
end
rgb_buf:write()
i=i+1
end
end
o=o+#t+#q+#v+#z
beep(f,d, function()
tmr.alarm(beep_tmr, p, 0, function()
play(s,p,m,b,i,o)
end)
end)
end
function M.cmd(p)
play(tonumber(p.s),tonumber(p.p),p.m,p.b)
return ({})
end
function M.key(n)
if n == 1 or n == -1 or n == 0 then
preset = (preset + n + #presets) % #presets
end
local p = presets[preset+1]
play(125,20,p,"1")
end
function M.stop()
beep(nil)
end
M.start=function()
ws2812.init()
rgb_buf:write()
M.key()
end
return M
|
--[[
16747 PS_Tyrannus_Openning01
16748 PS_Tyrannus_Openning02
16749 PS_Tyrannus_Openning03
16750 PS_Tyrannus_Openning04
16751 PS_Tyrannus_Openning05
16752 PS_Tyrannus_Forgemaster01
16753 PS_Tyrannus_Krick01
16754 PS_Tyrannus_Krick02
16755 PS_Tyrannus_Ambush01
16756 PS_Tyrannus_Ambush02
16757 PS_Tyrannus_GauntletStart01
16758 PS_Tyrannus_Prefight01
16759 PS_Tyrannus_Prefight02
16760 PS_Tyrannus_Aggro01
16761 PS_Tyrannus_Slay01
16762 PS_Tyrannus_Slay02
16763 PS_Tyrannus_Death01
16764 PS_Tyrannus_Mark01
16765 PS_Tyrannus_Kite01
16766 PS_Tyrannus_Attack
16767 PS_Tyrannus_Wound
16768 PS_Tyrannus_WoundCrit
------------------------------------------------------------------
Scourgelord Tyrannus yells: Alas, brave, brave adventurers, your meddling has reached its end. Do you hear the clatter of bone and steel coming up the tunnel behind you? That is the sound of your impending demise.
Scourgelord Tyrannus yells: Another shall take his place. You waste your time.
Scourgelord Tyrannus yells: Do not think that I shall permit you entry into my master's sanctum so easily. Pursue me if you dare.
Scourgelord Tyrannus yells: Ha, such an amusing gesture from the rabble. When I have finished with you, my master's blade will feast upon your souls. Die.
Scourgelord Tyrannus yells: Hrmph, fodder. Not even fit to labor in the quarry. Relish these final moments for soon you will be nothing more than mindless undead.
Scourgelord Tyrannus yells: Impossible.... Rimefang.... warn....
Scourgelord Tyrannus yells: Intruders have entered the master's domain. Signal the alarms!
Scourgelord Tyrannus yells: Minions, destroy these interlopers!
Scourgelord Tyrannus yells: Perhaps you should have stayed... in the mountains!
Scourgelord Tyrannus yells: Persistent whelps! You will not reach the entrance of my lord's lair! Soldiers, destroy them!
Scourgelord Tyrannus yells: Power... overwhelming!
Scourgelord Tyrannus yells: Rimefang, destroy this fool!
Scourgelord Tyrannus yells: Rimefang, trap them within the tunnel! BURY THEM ALIVE!
Scourgelord Tyrannus yells: Such a shameful display. You are better off dead.
Scourgelord Tyrannus yells: Worthless gnat! Death is all that awaits you!
Scourgelord Tyrannus yells: Your last waking memory will be of agonizing pain.
Scourgelord Tyrannus yells: Your pursuit shall be in vain, intruders, for the Lich King has placed an army of undead at my command! Behold!
]]--
function Tyrannus_OnCombat (pUnit, Event)
pUnit:SendChatMessage(14, 0, "Alas, brave brave heroes, do you hear the clatter of bone and steel coming up behind you? that is your end!")
pUnit:RegisterEvent("Tyrannus_Forceful", 18000, 0)
punit:RegisterEvent("Tyrannus_Overlord", 20000, 0)
punit:RegisterEvent("Tyrannus_Unholy", 24000, 0)
pUnit:RegisterEvent("Tyrannus_Mark", 16000, 0)
pUnit:RegisterEvent("Tyrannus_Icyblast", 19000, 0)
end
function Tyrannus_Forceful (pUnit, Event)
pUnit:FullCastSpellOnTarget(69155, pUnit:GetMainTank())
end
function Tyrannus_Overlord (pUnit, Event)
pUnit:FullCastSpellOnTarget (69172, pUnit:GetRandomPlayer(0))
end
function Tyrannus_Unholy (pUnit, Event)
pUnit:CastSpell(69167)
pUnit:SendChatMessage(14, 0, "Power... overwhelming!")
pUnit:SendChatMessage(42, 0, "Scourgelord Tyrannus roars and swells with dark might!")
end
function Tyrannus_Mark (pUnit, Event)
pUnit:FullCastSpellOnTarget (69275, pUnit:GetRandomPlayer(0))
pUnit:SendChatMessage(14, 0, "Rimefang, destroy this fool!")
pUnit:RegisterEvent("Tyrannus_Hoarfrost", 16000, 0)
end
function Tyrannus_Hoarfrost (pUnit, Event)
pUnit:FullCastSpellOnTarget (69245, pUnit:GetRandomPlayer(0))
end
function Tyrannus_Icyblast (pUnit, Event)
pUnit:FullCastSpellOnTarget (69238, pUnit:GetRandomPlayer(0))
end
function Tyrannus_OnKillPlr (pUnit, Event)
end
function Tyrannus_OnDeath (pUnit, Event)
pUnit:RemoveEvents()
pUnit:SendChatMessage(14, 0, "Impossible.... Rimefang.... warn....")
end
function Tyrannus_OnLeaveCombat (pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(36658, 1, "Tyrannus_OnCombat")
RegisterUnitEvent(36658, 2, "Tyrannus_OnLeaveCombat")
RegisterUnitEvent(36658, 3, "Tyrannus_OnKillPlr")
RegisterUnitEvent(36658, 4, "Tyrannus_OnDeath")
|
-- $Id$
--
-- All rights reserved. Part of the ALua project.
-- Detailed information regarding ALua's license can be found
-- in the LICENSE file.
--
--
-- This module creates a hashtable optimized to access the keys as array.
--
module("alua.util.khash", package.seeall)
local function put(self, key, value)
local idx = self._indeces[key]
if not idx then
idx = #self._keyserie + 1
self._keyserie[idx] = key
self._indeces[key] = idx
end
self._values[key] = value
end
local function remove(self, key)
local idx = self._indeces[key]
if idx then
local val = self._values[key]
self._indeces[key] = nil
self._values[key] = nil
local lastidx = #self._keyserie
if lastidx == idx then
self._keyserie[idx] = nil
else
local lastkey = self._keyserie[lastidx]
self._keyserie[idx] = lastkey
self._keyserie[lastidx] = nil
self._indeces[lastkey] = idx
end
return key, val
end
end
local function get(self, key)
return self._values[key]
end
local function exists(self, key)
return (self._indeces[key] ~= nil)
end
local function keys(self)
return self._keyserie
end
local function _pairs(self)
return pairs(self._values)
end
local function _ipairs(self)
return ipairs(self._values)
end
local function size(self)
return #self._keyserie
end
local htmeta = {
__index = {
put = put,
get = get,
remove = remove,
keys = keys,
pairs = _pairs,
ipairs = _ipairs,
exists = exists,
size = size,
}
}
function create()
local ht = {
_values = {},
_indeces = {},
_keyserie = {},
}
setmetatable(ht, htmeta)
return ht
end
|
HitConfig = { }
HitConfig[100001]={id=100001,lockLevel=1000,maxFrame=20,hitColor={255,0,0,255},event1=1,eventType1=7,eventId1=200001,event2=1,eventType2=2,eventId2=100004}
HitConfig[100002]={id=100002,lockLevel=1000,maxFrame=20,hitColor={255,0,0,255},event1=1,eventType1=7,eventId1=200001,event2=1,eventType2=2,eventId2=100004}
HitConfig[100003]={id=100003,lockLevel=1000,maxFrame=20,hitColor={255,0,0,255},event1=1,eventType1=7,eventId1=200003,event2=1,eventType2=2,eventId2=100004}
HitConfig[100004]={id=100004,lockLevel=1000,maxFrame=20,hitColor={255,0,0,255},event1=1,eventType1=7,eventId1=200001,event2=1,eventType2=2,eventId2=100004}
HitConfig[100005]={id=100005,lockLevel=1000,maxFrame=20,hitColor={255,0,0,255},event1=1,eventType1=7,eventId1=200001,event2=1,eventType2=2,eventId2=100004}
HitConfig[100006]={id=100006,lockLevel=1000,maxFrame=20,hitColor={255,0,0,255},event1=1,eventType1=7,eventId1=200001,event2=1,eventType2=2,eventId2=100004}
|
// Language files
language.Add("Undone_Translate", "Undone Translate")
|
-- more in depth
point = { x = 10, y = 20 }
print(point["x"])
print(point.x)
|
require('assets/scripts/object')
require('assets/scripts/Utility/uiUtilities')
PauseMenu = Object:new()
function PauseMenu:init()
self:createPanel()
self.pauseMenuPanel:get("UIRect").isEnabled = false
end
function PauseMenu:createPanel()
self.pauseMenuPanel = Game.makeActor {
Name = "PauseMenuPanel",
Transform = {
scale = {1,1,1}
},
UIRect = {
anchorMin = {0, 0},
anchorMax = {1, 1}
}
}
local titleText = "PAUSED"
Game.makeActor {
Name = "PauseTextBackdrop",
Transform = {
scale = {1,1,1},
parent = self.pauseMenuPanel
},
UIRect = {
anchorMin = {0.002, 0.002},
anchorMax = {1.002, 1.5002}
},
Text = {
font = "fonts/arcadianRunes.ttf",
fontSize = 120,
color = {25/255, 14/255, 4/255, 0.8},
string = titleText
}
}
Game.makeActor {
Name = "PauseText",
Transform = {
scale = {1,1,1},
parent = self.pauseMenuPanel
},
UIRect = {
anchorMin = {0, 0},
anchorMax = {1, 1.5}
},
Text = {
font = "fonts/arcadianRunes.ttf",
fontSize = 120,
color = {168/255, 130/255, 97/255, 1},
string = titleText
}
}
self.resumeButton = UIUtilities.makeButton("ResumeButton", self.pauseMenuPanel, "Resume", {0.5, 0.6}, {0.5, 0.6}, "textures/buttonBackground.png", function()
self.pauseMenuPanel:get("UIRect").isEnabled = false
self.level.player.canControl = true
end)
local mainMenuButton = UIUtilities.makeButton("MainMenuButton", self.pauseMenuPanel, "Main Menu", {0.5, 0.5}, {0.5, 0.5}, "textures/buttonBackground.png", function()
Game.loadScene(Config.startScene)
end)
UIUtilities.keepAspectRatio(mainMenuButton , 64)
UIUtilities.keepAspectRatio(self.resumeButton, 64)
end
function PauseMenu:activate()
local rect = self.pauseMenuPanel:get("UIRect")
rect.isEnabled = not rect.isEnabled
end
|
--
-- Author: DoooReyn
-- Date: 2016-01-20 20:59:37
--
local ListView = ccui.ListView
--------------------------------------------------------------
------------Below Are Custom UIListView Parameters------------
--------------------------------------------------------------
ListView._sliderBar = nil --SliderBar objection
ListView._sliderBg = nil --SliderBarBg objection
ListView._slideInTime = 0.2 --Time of slideBar fade In
ListView._slideOutTime = 0.4 --Time of sliderBar fade Out
ListView._scrollBottomCallback = nil --CallFunc when scrolled to bottom
ListView._scrollTopCallback = nil --CallFunc when scrolled to top
ListView._scrollingCallback = nil --CallFunc when scrolling
ListView._sliderBarCallback = nil --CallFunc when scrolling of sliderBar
ListView._isEnableScrollListener = false--Flag of enable scroll listener
ListView._isShowLabel = false --Flag of enable show itemModel's label
local ITEM_MODEL_NAME = 'ItemModel' --Name of itemModel
local ITEM_LABEL_NAME = 'ItemLabel' --Name of itemModel's label
--------------------------------------------------------------
----------Below Are Some UIListView Common Functions----------
--------------------------------------------------------------
function ListView:setScrollBottomCallback (callback)
if callback then
self._scrollBottomCallback = callback
end
end
function ListView:setScrollingCallback(callback)
if callback then
self._scrollingCallback = callback
end
end
function ListView:onEvent(callback)
self:addEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "ON_SELECTED_ITEM_START"
else
event.name = "ON_SELECTED_ITEM_END"
end
event.target = sender
callback(event)
end)
return self
end
function ListView:enableScrollListener ()
if self._isEnableScrollListener then
print('[Info] Listview scroll listener has enabled')
return
end
print('[Info] Enable listview scroll listener succeess')
self._isEnableScrollListener = true
self:onScroll(function(event) end)
end
function ListView:onScroll(callback)
self:addScrollViewEventListener(function(sender, eventType)
local event = {}
if eventType == 0 then
event.name = "SCROLL_TO_TOP"
elseif eventType == 1 then
event.name = "SCROLL_TO_BOTTOM"
if self._scrollBottomCallback then
self._scrollBottomCallback()
end
elseif eventType == 2 then
event.name = "SCROLL_TO_LEFT"
elseif eventType == 3 then
event.name = "SCROLL_TO_RIGHT"
elseif eventType == 4 then
event.name = "SCROLLING"
if self._scrollingCallback then
self._scrollingCallback()
end
if self._sliderBarCallback then
self._sliderBarCallback()
end
elseif eventType == 5 then
event.name = "BOUNCE_TOP"
elseif eventType == 6 then
event.name = "BOUNCE_BOTTOM"
elseif eventType == 7 then
event.name = "BOUNCE_LEFT"
elseif eventType == 8 then
event.name = "BOUNCE_RIGHT"
end
event.target = sender
callback(event)
end)
return self
end
function ListView:clearViewAndRefresh()
-- the same effect as ListView:removeAllChidren()
self:removeAllItems()
self:refreshView()
end
function ListView:refreshViewTop()
self:refreshView()
self:jumpToTop()
end
function ListView:refreshViewBottom()
self:refreshView()
self:jumpToBottom()
end
function ListView:setInnerContainerPosition(pos)
self:getInnerContainer():setPosition(pos)
end
function ListView:getInnerContainerPosition()
return self:getInnerContainer():getPosition()
end
--------------------------------------------------------------
--------Below Is An Implement of UIListView SliderBar---------
--------------------------------------------------------------
function ListView:setSlideInTime (inTime)
self._slideInTime = inTime
end
function ListView:setSlideOutTime(outTime)
self._slideOutTime = outTime
end
function ListView:setSliderBar (bar, barBg)
if not bar then return end
if not barBg then return end
if bar == self._sliderBar then return end --prevent repeating everytime
if barBg == self._sliderBg then return end --prevent repeating everytime
self._sliderBar = bar
self._sliderBg = barBg
self:enableScrollListener()
self:setSliderBarCallback(handler(self, self.updateSliderBarPos))
end
function ListView:setSliderBarCallback (callback)
if callback then
self._sliderBarCallback = callback
end
end
function ListView:updateSliderBarPos ()
local lSize = self:getContentSize()
local iSize = self:getInnerContainer():getContentSize()
local iPos = cc.p(self:getInnerContainer():getPosition())
local sWidth = self._sliderBar:getContentSize().width
local sHeight = self._sliderBar:getContentSize().height
local bHeight = self._sliderBg:getContentSize().height
local of = math.max(iSize.height - lSize.height, 1)
local pc = math.abs(iPos.y) / of
local dist = lSize.height - sHeight
local posY = dist * pc + sHeight / 2
-- print('SlideBar posY = ' .. posY)
self._sliderBar:setPositionY(posY)
end
function ListView:updateSlideBarState ()
if not self._sliderBar then return end
if not self._sliderBg then return end
local iHeight = self:getInnerContainer():getContentSize().height
local bHeight = self._sliderBg:getContentSize().height
if bHeight >= iHeight then
self._sliderBg:setVisible(false)
return
end
-- ListView:isScrollPaused() is a custom function defined and implemented in C++
local isPaused = self:isScrollPaused()
if isPaused and self._sliderBg._isActionEnd then
self._sliderBg._isActionEnd = false
local a1 = cc.FadeOut:create(self._slideOutTime)
local a2 = cc.Hide:create()
local st = cc.Sequence:create(a1,a2)
self._sliderBg:runAction(st)
end
if not isPaused then
self._sliderBg:stopAllActions()
self._sliderBar:stopAllActions()
self._sliderBg:setVisible(true)
self._sliderBg:setOpacity(255)
local a1 = cc.DelayTime:create(self._slideInTime)
local a2 = cc.CallFunc:create(function()
self._sliderBg._isActionEnd = true
end)
local st = cc.Sequence:create(a1, a2)
self._sliderBar:runAction(st)
self._sliderBg:runAction(st:clone())
end
end
--------------------------------------------------------------
------Below Is A Promotion of UIListView Items-Loading--------
--------------------------------------------------------------
function ListView:getVisibleBottomItem ()
local innerSize = self:getInnerContainerSize()
local viewSize = self:getContentSize()
local innerPos = cc.p(self:getInnerContainerPosition())
-- print('innerPos.y = ' .. innerPos.y)
local items = self:getItems()
if next(items) then
for row, item in ipairs(items) do
local itemPos = cc.p(item:getPosition())
if itemPos.y <= math.abs(innerPos.y) then
-- print('itemPos.y = ' .. itemPos.y)
return item, row
end
end
end
return items[#items], #items
end
function ListView:getVisibleCount(itemModel)
local viewSize = self:getContentSize()
local itemSize = itemModel:getContentSize()
local viewMgin = self:getItemsMargin()
local oneHeight = itemSize.height + viewMgin
return math.ceil(viewSize.height / oneHeight)
end
function ListView:packAutoLoadItem(itemModel, isCenterAround)
local viewItem = itemModel:clone()
local packItem = ccui.Layout:create()
packItem:setContentSize(viewItem:getContentSize())
viewItem:setName(ITEM_MODEL_NAME)
if isCenterAround or nil == isCenterAround then
-- call Tools.UIHelper.centerAround() to set child in the center of parent
Tools.UIHelper.centerAround(viewItem, packItem, true)
else
packItem:addChild(viewItem)
end
if self._isShowLabel then
if itemModel._row then
self:addRowLabel(itemModel._row, packItem)
end
end
return packItem
end
function ListView:enableAutoLoad (itemModel, initFunc, releaseFunc)
if not itemModel then return end
if not initFunc then return end
local visibleCount = self:getVisibleCount(itemModel)
self:enableScrollListener()
self:setScrollingCallback(function()
local _, row = self:getVisibleBottomItem()
if row == 1 then row = visibleCount end
local items = self:getItems()
local limit = math.max(1, row - visibleCount)
print('current row = ' .. row)
print('visible cnt = ' .. visibleCount)
if #items > 0 then
for i, item in ipairs(items) do
if i <= row and i >= limit then
--item init here
self:loadItemData(i, item, initFunc)
else
--item release here
self:releaseItemData(i, item, releaseFunc)
end
end
end
end)
end
function ListView:loadItemData (row, item, initFunc)
if item._isInit then
return
end
print('--load item in row--'..row)
item._isInit = true
item._isRelease = false
local realItem = item:getChildByName(ITEM_MODEL_NAME)
realItem:setVisible(true)
if self._isShowLabel then
self:addRowLabel(row, item)
end
if initFunc then
initFunc(row, realItem)
end
end
function ListView:releaseItemData(row, item, releaseFunc)
if item._isRelease then
return
end
print('--release item in row--'..row)
item._isInit = false
item._isRelease = true
item:getChildByName(ITEM_MODEL_NAME):setVisible(false)
if releaseFunc then
releaseFunc(row, item)
end
end
function ListView:addRowLabel (row, item)
--Call Tools.UIHelper.isExistNode() to check if parent has a child called ITEM_LABEL_NAME
--if YES , it returns true.
if Tools.UIHelper.isExistNode(ITEM_LABEL_NAME, item, false) then
return
end
local label = cc.Label:create()
label:setString('Row '..row)
label:setSystemFontSize(32)
label:setName(ITEM_LABEL_NAME)
Tools.UIHelper.centerAround(label, item, true)
return label
end
function ListView:setLabelShown (var)
if self._isShowLabel == var then
return
end
self._isShowLabel = var
end
|
----------------------------------------------------------------------------------
--- Total RP 3
--- Directory
--- ---------------------------------------------------------------------------
--- Copyright 2014 Sylvain Cossement (telkostrasz@telkostrasz.be)
--- Copyright 2014-2019 Morgane "Ellypse" Parize <ellypse@totalrp3.info> @EllypseCelwe
---
--- 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.
----------------------------------------------------------------------------------
---@type TRP3_API
local _, TRP3_API = ...;
local Ellyb = Ellyb(...);
-- imports
local Globals, Events = TRP3_API.globals, TRP3_API.events;
local Utils = TRP3_API.utils;
local loc = TRP3_API.loc;
local isUnitIDKnown = TRP3_API.register.isUnitIDKnown;
local unitIDToInfo, tsize = Utils.str.unitIDToInfo, Utils.table.size;
local handleMouseWheel = TRP3_API.ui.list.handleMouseWheel;
local initList = TRP3_API.ui.list.initList;
local setTooltipForSameFrame = TRP3_API.ui.tooltip.setTooltipForSameFrame;
local isMenuRegistered = TRP3_API.navigation.menu.isMenuRegistered;
local registerMenu, selectMenu, openMainFrame = TRP3_API.navigation.menu.registerMenu, TRP3_API.navigation.menu.selectMenu, TRP3_API.navigation.openMainFrame;
local registerPage, setPage = TRP3_API.navigation.page.registerPage, TRP3_API.navigation.page.setPage;
local setupFieldSet = TRP3_API.ui.frame.setupFieldPanel;
local getUnitIDCharacter = TRP3_API.register.getUnitIDCharacter;
local getUnitIDProfile = TRP3_API.register.getUnitIDProfile;
local hasProfile = TRP3_API.register.hasProfile;
local getCompleteName = TRP3_API.register.getCompleteName;
local TRP3_RegisterListEmpty = TRP3_RegisterListEmpty;
local getProfile = TRP3_API.register.getProfile;
local getIgnoredList, unignoreID, isIDIgnored = TRP3_API.register.getIgnoredList, TRP3_API.register.unignoreID, TRP3_API.register.isIDIgnored;
local getRelationText, getRelationTooltipText = TRP3_API.register.relation.getRelationText, TRP3_API.register.relation.getRelationTooltipText;
local unregisterMenu = TRP3_API.navigation.menu.unregisterMenu;
local displayDropDown, showAlertPopup, showConfirmPopup = TRP3_API.ui.listbox.displayDropDown, TRP3_API.popup.showAlertPopup, TRP3_API.popup.showConfirmPopup;
local showTextInputPopup = TRP3_API.popup.showTextInputPopup;
local deleteProfile, deleteCharacter, getProfileList = TRP3_API.register.deleteProfile, TRP3_API.register.deleteCharacter, TRP3_API.register.getProfileList;
local ignoreID = TRP3_API.register.ignoreID;
local refreshList;
local getCurrentPageID = TRP3_API.navigation.page.getCurrentPageID;
local checkGlanceActivation = TRP3_API.register.checkGlanceActivation;
local getCompanionProfiles = TRP3_API.companions.register.getProfiles;
local getRelationColors = TRP3_API.register.relation.getRelationColors;
local getCompanionNameFromSpellID = TRP3_API.companions.getCompanionNameFromSpellID;
local safeMatch = TRP3_API.utils.str.safeMatch;
local unitIDIsFilteredForMatureContent = TRP3_API.register.unitIDIsFilteredForMatureContent;
local profileIDISFilteredForMatureContent = TRP3_API.register.profileIDISFilteredForMatureContent;
local tContains = tContains;
local GetAutoCompleteRealms = GetAutoCompleteRealms;
local is_classic = Globals.is_classic;
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- Logic
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local REGISTER_LIST_PAGEID = "register_list";
local playerMenu = "main_10_player";
local currentlyOpenedProfilePrefix = TRP3_API.register.MENU_LIST_ID_TAB;
local REGISTER_PAGE = TRP3_API.register.MENU_LIST_ID;
local function openPage(profileID, unitID)
local profile = getProfile(profileID);
local menuID = currentlyOpenedProfilePrefix .. profileID
if isMenuRegistered(menuID) then
local menuItem = TRP3_API.navigation.menu.getMenuItem(menuID)
if unitID then
menuItem.pageContext.unitID = unitID
menuItem.pageContext.openingWithUnitID = true
end
-- If the character already has his "tab", simply open it
selectMenu(menuID);
TRP3_API.navigation.page.getCurrentContext().openingWithUnitID = false
else
-- Else, create a new menu entry and open it.
local tabText = UNKNOWN;
if profile.characteristics and profile.characteristics.FN then
tabText = profile.characteristics.FN;
end
local pageContext = {
-- source isn't used, but useful in to know where you're getting the
-- REGISTER_PROFILE_OPENED event from.
source = "directory",
profile = profile,
profileID = profileID,
unitID = unitID,
openingWithUnitID = unitID ~= nil
}
registerMenu({
id = menuID,
text = tabText,
onSelected = function() setPage("player_main", pageContext ) end,
isChildOf = REGISTER_PAGE,
closeable = true,
icon = is_classic and "Interface\\ICONS\\INV_Helmet_20" or "Interface\\ICONS\\pet_type_humanoid",
pageContext = pageContext,
});
selectMenu(menuID);
TRP3_API.navigation.page.getCurrentContext().openingWithUnitID = false
if (unitID and unitIDIsFilteredForMatureContent(unitID)) or (profileID and profileIDISFilteredForMatureContent(profileID)) then
TRP3_API.popup.showPopup("mature_filtered");
TRP3_MatureFilterPopup.profileID = profileID;
TRP3_MatureFilterPopup.unitID = unitID;
TRP3_MatureFilterPopup.menuID = menuID;
end
end
end
TRP3_API.register.openPageByProfileID = openPage;
local function openCompanionPage(profileID)
local profile = getCompanionProfiles()[profileID];
if isMenuRegistered(currentlyOpenedProfilePrefix .. profileID) then
-- If the character already has his "tab", simply open it
selectMenu(currentlyOpenedProfilePrefix .. profileID);
else
-- Else, create a new menu entry and open it.
local tabText = UNKNOWN;
if profile.data and profile.data.NA then
tabText = profile.data.NA;
end
registerMenu({
id = currentlyOpenedProfilePrefix .. profileID,
text = tabText,
onSelected = function() setPage(TRP3_API.navigation.page.id.COMPANIONS_PAGE, {profile = profile, profileID = profileID, isPlayer = false}) end,
isChildOf = REGISTER_PAGE,
closeable = true,
icon = "Interface\\ICONS\\pet_type_beast",
});
selectMenu(currentlyOpenedProfilePrefix .. profileID);
end
end
TRP3_API.companions.register.openPage = openCompanionPage;
local function openPageByUnitID(unitID)
if unitID == Globals.player_id then
selectMenu(playerMenu);
elseif isUnitIDKnown(unitID) and hasProfile(unitID) then
openPage(hasProfile(unitID), unitID);
end
end
TRP3_API.register.openPageByUnitID = openPageByUnitID;
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local sortingType = 1;
local function switchNameSorting()
sortingType = sortingType == 2 and 1 or 2;
refreshList();
end
local function switchInfoSorting()
sortingType = sortingType == 4 and 3 or 4;
refreshList();
end
local function switchTimeSorting()
sortingType = sortingType == 6 and 5 or 6;
refreshList();
end
local function getNameForSort(name)
name = name:lower()
name = name:gsub("\"", "")
name = name:gsub("'", "")
return name
end
local function nameComparator(elem1, elem2)
return getNameForSort(elem1[2]) < getNameForSort(elem2[2]);
end
local function nameComparatorInverted(elem1, elem2)
return getNameForSort(elem1[2]) > getNameForSort(elem2[2]);
end
local function infoComparator(elem1, elem2)
return elem1[3]:lower() < elem2[3]:lower();
end
local function infoComparatorInverted(elem1, elem2)
return elem1[3]:lower() > elem2[3]:lower();
end
local function timeComparator(elem1, elem2)
if elem1[4] == nil then
return false;
elseif elem2[4] == nil then
return true;
end
return elem1[4] < elem2[4];
end
local function timeComparatorInverted(elem1, elem2)
if elem1[4] == nil then
return false;
elseif elem2[4] == nil then
return true;
end
return elem1[4] > elem2[4];
end
local comparators = {
nameComparator, nameComparatorInverted, infoComparator, infoComparatorInverted, timeComparator, timeComparatorInverted
}
local function getCurrentComparator()
return comparators[sortingType];
end
local ARROW_DOWN = "Interface\\Buttons\\Arrow-Down-Up";
local ARROW_UP = "Interface\\Buttons\\Arrow-Up-Up";
local ARROW_SIZE = 15;
local function getComparatorArrows()
local nameArrow, relationArrow, timeArrow = "", "", "";
if sortingType == 1 then
nameArrow = " |T" .. ARROW_DOWN .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 2 then
nameArrow = " |T" .. ARROW_UP .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 3 then
relationArrow = " |T" .. ARROW_DOWN .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 4 then
relationArrow = " |T" .. ARROW_UP .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 5 then
timeArrow = " |T" .. ARROW_DOWN .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 6 then
timeArrow = " |T" .. ARROW_UP .. ":" .. ARROW_SIZE .. "|t";
end
return nameArrow, relationArrow, timeArrow;
end
local MODE_CHARACTER, MODE_PETS, MODE_IGNORE = 1, 2, 3;
local selectedIDs = {};
local ICON_SIZE = 30;
local currentMode = 1;
local DATE_FORMAT = "%d/%m/%y %H:%M";
local IGNORED_ICON = Utils.str.texture("Interface\\Buttons\\UI-GroupLoot-Pass-Down", 15);
local GLANCE_ICON = Utils.str.texture("Interface\\MINIMAP\\TRACKING\\None", 15);
local NEW_ABOUT_ICON = Utils.str.texture("Interface\\Buttons\\UI-GuildButton-PublicNote-Up", 15);
local MATURE_CONTENT_ICON = Utils.str.texture("Interface\\AddOns\\totalRP3\\resources\\18_emoji.tga", 15);
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI : CHARACTERS
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local characterLines = {};
local function decorateCharacterLine(line, characterIndex)
local profileID = characterLines[characterIndex][1];
local profile = getProfile(profileID);
line.id = profileID;
local name = getCompleteName(profile.characteristics or {}, UNKNOWN, true);
local leftTooltipTitle, leftTooltipText = name, "";
_G[line:GetName().."Name"]:SetText(name);
if profile.characteristics and profile.characteristics.IC then
leftTooltipTitle = Utils.str.icon(profile.characteristics.IC, ICON_SIZE) .. " " .. name;
end
local hasGlance = profile.misc and profile.misc.PE and checkGlanceActivation(profile.misc.PE);
local hasNewAbout = profile.about and not profile.about.read;
local atLeastOneIgnored = false;
_G[line:GetName().."Info2"]:SetText("");
local firstLink;
if profile.link and tsize(profile.link) > 0 then
leftTooltipText = leftTooltipText .. loc.REG_LIST_CHAR_TT_CHAR;
for unitID, _ in pairs(profile.link) do
if not firstLink then
firstLink = unitID;
end
local unitName, unitRealm = unitIDToInfo(unitID);
if isIDIgnored(unitID) then
leftTooltipText = leftTooltipText .. "\n|cffff0000 - " .. unitName .. " ( " .. unitRealm .. " ) - " .. IGNORED_ICON .. " " .. loc.REG_LIST_CHAR_IGNORED;
atLeastOneIgnored = true;
else
leftTooltipText = leftTooltipText .. "\n|cff00ff00 - " .. unitName .. " ( " .. unitRealm .. " )";
end
end
else
leftTooltipText = leftTooltipText .. "|cffffff00" .. loc.REG_LIST_CHAR_TT_CHAR_NO;
end
if profile.time and profile.zone then
local formatDate = date(DATE_FORMAT, profile.time);
leftTooltipText = leftTooltipText .. "\n|r" .. loc.REG_LIST_CHAR_TT_DATE:format(formatDate, profile.zone);
end
-- Middle column : relation
local relation, relationRed, relationGreen, relationBlue = getRelationText(profileID), getRelationColors(profileID);
local color = Utils.color.colorCode(relationRed * 255, relationGreen * 255, relationBlue * 255);
if relation:len() > 0 then
local middleTooltipTitle, middleTooltipText = relation, getRelationTooltipText(profileID, profile);
setTooltipForSameFrame(_G[line:GetName().."ClickMiddle"], "TOPLEFT", 0, 5, middleTooltipTitle, color .. middleTooltipText);
else
setTooltipForSameFrame(_G[line:GetName().."ClickMiddle"]);
end
_G[line:GetName().."Info"]:SetText(color .. relation);
local timeStr = "";
if profile.time then
timeStr = date(DATE_FORMAT, profile.time);
end
_G[line:GetName().."Time"]:SetText(timeStr);
-- Third column : flags
---@type string[]
local rightTooltipTexts, flags = {}, {};
if atLeastOneIgnored then
table.insert(flags, IGNORED_ICON);
table.insert(rightTooltipTexts, IGNORED_ICON .. " " .. loc.REG_LIST_CHAR_TT_IGNORE);
end
if hasGlance then
table.insert(flags, GLANCE_ICON);
table.insert(rightTooltipTexts, GLANCE_ICON .. " " .. loc.REG_LIST_CHAR_TT_GLANCE);
end
if hasNewAbout then
table.insert(flags, NEW_ABOUT_ICON);
table.insert(rightTooltipTexts, NEW_ABOUT_ICON .. " " .. loc.REG_LIST_CHAR_TT_NEW_ABOUT);
end
if profile.hasMatureContent then
table.insert(flags, MATURE_CONTENT_ICON);
table.insert(rightTooltipTexts, MATURE_CONTENT_ICON .. " " .. loc.MATURE_FILTER_TOOLTIP_WARNING);
end
if #rightTooltipTexts > 0 then
setTooltipForSameFrame(_G[line:GetName().."ClickRight"], "TOPLEFT", 0, 5, loc.REG_LIST_FLAGS, table.concat(rightTooltipTexts, "\n"));
else
setTooltipForSameFrame(_G[line:GetName().."ClickRight"]);
end
_G[line:GetName().."Info2"]:SetText(table.concat(flags, " "));
local addon = Globals.addon_name;
if profile.msp then
addon = "Mary-Sue Protocol";
if firstLink and isUnitIDKnown(firstLink) then
local character = getUnitIDCharacter(firstLink);
addon = character.client or "Mary-Sue Protocol";
end
end
_G[line:GetName().."Addon"]:SetText(addon);
_G[line:GetName().."Select"]:SetChecked(selectedIDs[profileID]);
_G[line:GetName().."Select"]:Show();
setTooltipForSameFrame(_G[line:GetName().."Click"], "TOPLEFT", 0, 5, leftTooltipTitle, leftTooltipText .. "\n\n" ..
Ellyb.Strings.clickInstruction(Ellyb.System.CLICKS.CLICK, loc.CM_OPEN) .. "\n" ..
Ellyb.Strings.clickInstruction(
Ellyb.System:FormatKeyboardShortcut(Ellyb.System.MODIFIERS.SHIFT, Ellyb.System.CLICKS.CLICK),
loc.CL_TOOLTIP
));
end
local function getCharacterLines()
local nameSearch = TRP3_RegisterListFilterCharactName:GetText():lower();
local guildSearch = TRP3_RegisterListFilterCharactGuild:GetText():lower();
local realmOnly = TRP3_RegisterListFilterCharactRealm:GetChecked();
local notesOnly = TRP3_RegisterListFilterCharactNotes:GetChecked();
local profileList = getProfileList();
local fullSize = tsize(profileList);
wipe(characterLines);
for profileID, profile in pairs(profileList) do
local nameIsConform, guildIsConform, realmIsConform, notesIsConform = false, false, false, false;
if profile.characteristics and not Ellyb.Tables.isEmpty(profile.characteristics) then
-- Defines if at least one character is conform to the search criteria
for unitID, _ in pairs(profile.link or Globals.empty) do
local unitName, unitRealm = unitIDToInfo(unitID);
if safeMatch(unitName:lower(), nameSearch) then
nameIsConform = true;
end
if unitRealm == Globals.player_realm_id or tContains(GetAutoCompleteRealms(), unitRealm) then
realmIsConform = true;
end
local characterData = AddOn_TotalRP3.Directory.getCharacterDataForCharacterId(unitID);
if characterData and characterData.guild and safeMatch(characterData.guild:lower(), guildSearch) then
guildIsConform = true;
end
local currentNotes = TRP3_API.profile.getPlayerCurrentProfile().notes or {};
if TRP3_Notes and TRP3_Notes[profileID] or currentNotes[profileID] then
notesIsConform = true;
end
end
local completeName = getCompleteName(profile.characteristics or {}, "", true);
if not nameIsConform and safeMatch(completeName:lower(), nameSearch) then
nameIsConform = true;
end
nameIsConform = nameIsConform or nameSearch:len() == 0;
guildIsConform = guildIsConform or guildSearch:len() == 0;
realmIsConform = realmIsConform or not realmOnly;
notesIsConform = notesIsConform or not notesOnly;
if nameIsConform and guildIsConform and realmIsConform and notesIsConform then
tinsert(characterLines, {profileID, completeName, getRelationText(profileID), profile.time});
end
end
end
table.sort(characterLines, getCurrentComparator());
local lineSize = #characterLines;
if lineSize == 0 then
if fullSize == 0 then
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_CHAR_EMPTY);
else
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_CHAR_EMPTY2);
end
end
setupFieldSet(TRP3_RegisterListCharactFilter, loc.REG_LIST_CHAR_FILTER:format(lineSize, fullSize), 200);
local nameArrow, relationArrow, timeArrow = getComparatorArrows();
TRP3_RegisterListHeaderName:SetText(loc.REG_PLAYER .. nameArrow);
TRP3_RegisterListHeaderInfo:SetText(loc.REG_RELATION .. relationArrow);
TRP3_RegisterListHeaderTime:SetText(loc.REG_TIME .. timeArrow);
TRP3_RegisterListHeaderTimeTT:Enable();
TRP3_RegisterListHeaderInfoTT:Enable();
TRP3_RegisterListHeaderNameTT:Enable();
TRP3_RegisterListHeaderInfo2:SetText(loc.REG_LIST_FLAGS);
TRP3_RegisterListHeaderActions:Show();
return characterLines;
end
local MONTH_IN_SECONDS = 2592000;
local function onCharactersActionSelected(value)
-- PURGES
if value == "purge_time" then
local profiles = getProfileList();
local profilesToPurge = {};
for profileID, profile in pairs(profiles) do
if profile.time and time() - profile.time > MONTH_IN_SECONDS then
tinsert(profilesToPurge, profileID);
end
end
if #profilesToPurge == 0 then
showAlertPopup(loc.REG_LIST_ACTIONS_PURGE_TIME_C:format(loc.REG_LIST_ACTIONS_PURGE_EMPTY));
else
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_TIME_C:format(loc.REG_LIST_ACTIONS_PURGE_COUNT:format(#profilesToPurge)), function()
for _, profileID in pairs(profilesToPurge) do
deleteProfile(profileID, true);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
refreshList();
end);
end
elseif value == "purge_unlinked" then
local profiles = getProfileList();
local profilesToPurge = {};
for profileID, profile in pairs(profiles) do
if not profile.link or tsize(profile.link) == 0 then
tinsert(profilesToPurge, profileID);
end
end
if #profilesToPurge == 0 then
showAlertPopup(loc.REG_LIST_ACTIONS_PURGE_UNLINKED_C:format(loc.REG_LIST_ACTIONS_PURGE_EMPTY));
else
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_UNLINKED_C:format(loc.REG_LIST_ACTIONS_PURGE_COUNT:format(#profilesToPurge)), function()
for _, profileID in pairs(profilesToPurge) do
deleteProfile(profileID, true);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
refreshList();
end);
end
elseif value == "purge_ignore" then
local profilesToPurge, characterToPurge = TRP3_API.register.getIDsToPurge();
if #profilesToPurge + #characterToPurge == 0 then
showAlertPopup(loc.REG_LIST_ACTIONS_PURGE_IGNORE_C:format(loc.REG_LIST_ACTIONS_PURGE_EMPTY));
else
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_IGNORE_C:format(loc.REG_LIST_ACTIONS_PURGE_COUNT:format(#profilesToPurge + #characterToPurge)), function()
for _, profileID in pairs(profilesToPurge) do
deleteProfile(profileID, true);
end
for _, unitID in pairs(characterToPurge) do
deleteCharacter(unitID);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
refreshList();
end);
end
elseif value == "purge_all" then
local list = getProfileList();
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_ALL_C:format(tsize(list)), function()
for profileID, _ in pairs(list) do
deleteProfile(profileID, true);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
end);
-- Mass actions
elseif value == "actions_delete" then
showConfirmPopup(loc.REG_LIST_ACTIONS_MASS_REMOVE_C:format(tsize(selectedIDs)), function()
for profileID, _ in pairs(selectedIDs) do
deleteProfile(profileID, true);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
refreshList();
end);
elseif value == "actions_ignore" then
local charactToIgnore = {};
for profileID, _ in pairs(selectedIDs) do
for unitID, _ in pairs(getProfile(profileID).link or Globals.empty) do
charactToIgnore[unitID] = true;
end
end
showTextInputPopup(loc.REG_LIST_ACTIONS_MASS_IGNORE_C:format(tsize(charactToIgnore)), function(text)
for unitID, _ in pairs(charactToIgnore) do
ignoreID(unitID, text);
end
refreshList();
end);
end
end
local function onCharactersActions(self)
local values = {};
tinsert(values, {loc.REG_LIST_ACTIONS_PURGE, {
{loc.REG_LIST_ACTIONS_PURGE_TIME, "purge_time"},
{loc.REG_LIST_ACTIONS_PURGE_UNLINKED, "purge_unlinked"},
{loc.REG_LIST_ACTIONS_PURGE_IGNORE, "purge_ignore"},
{loc.REG_LIST_ACTIONS_PURGE_ALL, "purge_all"},
}});
if tsize(selectedIDs) > 0 then
tinsert(values, {loc.REG_LIST_ACTIONS_MASS:format(tsize(selectedIDs)), {
{loc.REG_LIST_ACTIONS_MASS_REMOVE, "actions_delete"},
{loc.REG_LIST_ACTIONS_MASS_IGNORE, "actions_ignore"},
}});
end
displayDropDown(self, values, onCharactersActionSelected, 0, true);
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI : COMPANIONS
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local companionIDToInfo, getAssociationsForProfile = TRP3_API.utils.str.companionIDToInfo, TRP3_API.companions.register.getAssociationsForProfile;
local deleteCompanionProfile = TRP3_API.companions.register.deleteProfile;
local companionLines = {};
local function decorateCompanionLine(line, index)
local profileID = companionLines[index][1];
local profile = getCompanionProfiles()[profileID];
line.id = profileID;
local hasGlance = profile.PE and checkGlanceActivation(profile.PE);
local hasNewAbout = profile.data and profile.data.read == false;
local name = UNKNOWN;
if profile.data and profile.data.NA then
name = profile.data.NA;
end
_G[line:GetName().."Name"]:SetText(name);
local tooltip = name;
if profile.data and profile.data.IC then
tooltip = Utils.str.icon(profile.data.IC, ICON_SIZE) .. " " .. name;
end
local links, masters = {}, {};
local fulllinks = getAssociationsForProfile(profileID);
for _, companionFullID in pairs(fulllinks) do
local ownerID, companionID = companionIDToInfo(companionFullID);
links[companionID] = 1;
masters[ownerID] = 1;
end
local companionList = "";
for companionID, _ in pairs(links) do
companionList = companionList .. "- |cff00ff00" .. getCompanionNameFromSpellID(companionID) .. "|r\n";
end
local masterList, firstMaster = "", "";
for ownerID, _ in pairs(masters) do
masterList = masterList .. "- |cff00ff00" .. ownerID .. "|r\n";
if firstMaster == "" then
firstMaster = ownerID;
end
end
if isUnitIDKnown(firstMaster) and TRP3_API.register.profileExists(firstMaster) then
firstMaster = getCompleteName(getUnitIDProfile(firstMaster).characteristics or {}, "", true);
end
_G[line:GetName().."Addon"]:SetText(firstMaster);
local secondLine = loc.REG_LIST_PETS_TOOLTIP .. ":\n" .. companionList .. "\n" .. loc.REG_LIST_PETS_TOOLTIP2 .. ":\n" .. masterList;
setTooltipForSameFrame(_G[line:GetName().."Click"], "TOPLEFT", 0, 5, tooltip, secondLine .. "\n\n" ..
Ellyb.Strings.clickInstruction(Ellyb.System.CLICKS.CLICK, loc.CM_OPEN) .. "\n" ..
Ellyb.Strings.clickInstruction(
Ellyb.System:FormatKeyboardShortcut(Ellyb.System.MODIFIERS.SHIFT, Ellyb.System.CLICKS.CLICK),
loc.CL_TOOLTIP
));
setTooltipForSameFrame(_G[line:GetName().."ClickMiddle"]);
-- Third column : flags
---@type string[]
local rightTooltipText, flags = {}, {};
if hasGlance then
table.insert(flags, GLANCE_ICON);
table.insert(rightTooltipText, GLANCE_ICON .. " " .. loc.REG_LIST_CHAR_TT_GLANCE);
end
if hasNewAbout then
table.insert(flags, NEW_ABOUT_ICON);
table.insert(rightTooltipText, NEW_ABOUT_ICON .. " " .. loc.REG_LIST_CHAR_TT_NEW_ABOUT);
end
if #rightTooltipText > 0 then
setTooltipForSameFrame(_G[line:GetName().."ClickRight"], "TOPLEFT", 0, 5, loc.REG_LIST_FLAGS, table.concat(rightTooltipText, "\n"));
else
setTooltipForSameFrame(_G[line:GetName().."ClickRight"]);
end
_G[line:GetName().."Info2"]:SetText(table.concat(flags, " "));
_G[line:GetName().."Select"]:SetChecked(selectedIDs[profileID]);
_G[line:GetName().."Select"]:Show();
_G[line:GetName().."Info"]:SetText("");
_G[line:GetName().."Time"]:SetText("");
end
local function getCompanionLines()
local nameSearch = TRP3_RegisterListPetFilterName:GetText():lower();
local typeSearch = TRP3_RegisterListPetFilterType:GetText():lower();
local masterSearch = TRP3_RegisterListPetFilterMaster:GetText():lower();
local profiles = getCompanionProfiles();
local fullSize = tsize(profiles);
wipe(companionLines);
for profileID, profile in pairs(profiles) do
local nameIsConform, typeIsConform, masterIsConform = false, false, false;
-- Run this test only if there are criterias
if typeSearch:len() > 0 or masterSearch:len() > 0 then
for companionFullID, _ in pairs(profile.links) do
local masterID, companionID = companionIDToInfo(companionFullID);
if safeMatch(companionID:lower(), typeSearch) then
typeIsConform = true;
end
if safeMatch(masterID:lower(), masterSearch) then
masterIsConform = true;
end
end
end
local companionName = UNKNOWN;
if profile.data and profile.data.NA then
companionName = profile.data.NA;
end
if nameSearch:len() ~= 0 and profile.data and profile.data.NA and safeMatch(profile.data.NA:lower(), nameSearch) then
nameIsConform = true;
end
nameIsConform = nameIsConform or nameSearch:len() == 0;
typeIsConform = typeIsConform or typeSearch:len() == 0;
masterIsConform = masterIsConform or masterSearch:len() == 0;
if nameIsConform and typeIsConform and masterIsConform then
tinsert(companionLines, {profileID, companionName, companionName, companionName});
end
end
table.sort(companionLines, getCurrentComparator());
local lineSize = #companionLines;
if lineSize == 0 then
if fullSize == 0 then
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_PETS_EMPTY);
else
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_PETS_EMPTY2);
end
end
setupFieldSet(TRP3_RegisterListPetFilter, loc.REG_LIST_PETS_FILTER:format(lineSize, fullSize), 200);
local nameArrow = getComparatorArrows();
TRP3_RegisterListHeaderName:SetText(loc.REG_COMPANION .. nameArrow);
TRP3_RegisterListHeaderInfo:SetText("");
TRP3_RegisterListHeaderTime:SetText("");
TRP3_RegisterListHeaderTimeTT:Disable();
TRP3_RegisterListHeaderInfoTT:Disable();
TRP3_RegisterListHeaderNameTT:Enable();
TRP3_RegisterListHeaderInfo2:SetText(loc.REG_LIST_FLAGS);
TRP3_RegisterListHeaderActions:Show();
return companionLines;
end
local DO_NOT_FIRE_EVENTS = true;
local function onCompanionActionSelected(value)
if value == "purge_all" then
local list = getCompanionProfiles();
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_ALL_COMP_C:format(tsize(list)), function()
for profileID, _ in pairs(list) do
-- We delete the companion profile without fire events to prevent UI freeze
deleteCompanionProfile(profileID, DO_NOT_FIRE_EVENTS);
end
-- We then fire the event once every profile we needed to delete has been deleted
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
end);
elseif value == "actions_delete" then
showConfirmPopup(loc.REG_LIST_ACTIONS_MASS_REMOVE_C:format(tsize(selectedIDs)), function()
for profileID, _ in pairs(selectedIDs) do
-- We delete the companion profile without fire events to prevent UI freeze
deleteCompanionProfile(profileID, DO_NOT_FIRE_EVENTS);
end
-- We then fire the event once every profile we needed to delete has been deleted
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
end);
end
end
local function onPetsActions(self)
local values = {};
tinsert(values, {loc.REG_LIST_ACTIONS_PURGE, {
{loc.REG_LIST_ACTIONS_PURGE_ALL, "purge_all"},
}});
if tsize(selectedIDs) > 0 then
tinsert(values, {loc.REG_LIST_ACTIONS_MASS:format(tsize(selectedIDs)), {
{loc.REG_LIST_ACTIONS_MASS_REMOVE, "actions_delete"},
}});
end
displayDropDown(self, values, onCompanionActionSelected, 0, true);
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI : IGNORED
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local function decorateIgnoredLine(line, unitID)
line.id = unitID;
_G[line:GetName().."Name"]:SetText(unitID);
_G[line:GetName().."Info"]:SetText("");
_G[line:GetName().."Time"]:SetText("");
_G[line:GetName().."Info2"]:SetText("");
_G[line:GetName().."Addon"]:SetText("");
_G[line:GetName().."Select"]:Hide();
setTooltipForSameFrame(_G[line:GetName().."Click"], "TOPLEFT", 0, 5, unitID, loc.REG_LIST_IGNORE_TT:format(getIgnoredList()[unitID]));
setTooltipForSameFrame(_G[line:GetName().."ClickMiddle"]);
setTooltipForSameFrame(_G[line:GetName().."ClickRight"]);
end
local function getIgnoredLines()
if tsize(getIgnoredList()) == 0 then
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_IGNORE_EMPTY);
end
TRP3_RegisterListHeaderName:SetText(loc.REG_PLAYER);
TRP3_RegisterListHeaderInfo:SetText("");
TRP3_RegisterListHeaderTime:SetText("");
TRP3_RegisterListHeaderTimeTT:Disable();
TRP3_RegisterListHeaderInfoTT:Disable();
TRP3_RegisterListHeaderNameTT:Disable();
TRP3_RegisterListHeaderInfo2:SetText("");
return getIgnoredList();
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI : LIST
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
function refreshList()
local lines;
TRP3_RegisterListEmpty:Hide();
TRP3_RegisterListHeaderActions:Hide();
if currentMode == MODE_CHARACTER then
lines = getCharacterLines();
TRP3_RegisterList.decorate = decorateCharacterLine;
elseif currentMode == MODE_PETS then
lines = getCompanionLines();
TRP3_RegisterList.decorate = decorateCompanionLine;
elseif currentMode == MODE_IGNORE then
lines = getIgnoredLines();
TRP3_RegisterList.decorate = decorateIgnoredLine;
end
if tsize(lines) == 0 then
TRP3_RegisterListEmpty:Show();
end
initList(TRP3_RegisterList, lines, TRP3_RegisterListSlider);
end
local function onLineClicked(self)
if currentMode == MODE_CHARACTER then
assert(self:GetParent().id, "No profileID on line.");
if IsShiftKeyDown() then
TRP3_API.RegisterPlayerChatLinksModule:InsertLink(self:GetParent().id);
else
openPage(self:GetParent().id);
end
elseif currentMode == MODE_PETS then
assert(self:GetParent().id, "No profileID on line.");
if IsShiftKeyDown() then
TRP3_API.ChatLinks:OpenMakeImportablePrompt(loc.CL_COMPANION_PROFILE, function(canBeImported)
TRP3_API.RegisterCompanionChatLinksModule:InsertLink(self:GetParent().id, canBeImported);
end);
else
openCompanionPage(self:GetParent().id);
end
elseif currentMode == MODE_IGNORE then
assert(self:GetParent().id, "No unitID on line.");
unignoreID(self:GetParent().id);
refreshList();
end
end
local function onLineSelected(self)
assert(self:GetParent().id, "No id on line.");
selectedIDs[self:GetParent().id] = self:GetChecked() or nil;
end
local function changeMode(_, value)
currentMode = value;
wipe(selectedIDs);
TRP3_RegisterListCharactFilter:Hide();
TRP3_RegisterListPetFilter:Hide();
TRP3_RegisterListHeaderAddon:SetText("");
if currentMode == MODE_CHARACTER then
TRP3_RegisterListCharactFilter:Show();
TRP3_RegisterListHeaderAddon:SetText(loc.REG_LIST_ADDON);
elseif currentMode == MODE_PETS then
TRP3_RegisterListPetFilter:Show();
TRP3_RegisterListHeaderAddon:SetText(loc.REG_LIST_PET_MASTER);
end
refreshList();
Events.fireEvent(Events.NAVIGATION_TUTORIAL_REFRESH, REGISTER_LIST_PAGEID);
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- Init
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local tabGroup;
local function createTabBar()
local frame = CreateFrame("Frame", "TRP3_RegisterMainTabBar", TRP3_RegisterList);
frame:SetSize(400, 30);
frame:SetPoint("TOPLEFT", 17, 0);
frame:SetFrameLevel(1);
tabGroup = TRP3_API.ui.frame.createTabPanel(frame,
{
{loc.REG_LIST_CHAR_TITLE, 1, 150},
{loc.REG_LIST_PETS_TITLE, 2, 150},
{loc.REG_LIST_IGNORE_TITLE, 3, 150},
},
changeMode
);
end
local TUTORIAL_CHARACTER;
local function createTutorialStructure()
TUTORIAL_CHARACTER = {
{
box = {
x = 20, y = -45, anchor = "TOPLEFT", width = 28, height = 340
},
button = {
x = 0, y = 0, anchor = "CENTER",
text = loc.REG_LIST_CHAR_TUTO_ACTIONS,
arrow = "LEFT"
}
},
{
box = {
x = 50, y = -45, anchor = "TOPLEFT", width = 470, height = 340
},
button = {
x = 0, y = 0, anchor = "CENTER",
text = loc.REG_LIST_CHAR_TUTO_LIST,
textWidth = 400,
arrow = "DOWN"
}
},
{
box = {
x = 20, y = -387, anchor = "TOPLEFT", width = 500, height = 60
},
button = {
x = 0, y = 10, anchor = "CENTER",
text = loc.REG_LIST_CHAR_TUTO_FILTER,
textWidth = 400,
arrow = "UP"
}
}
}
end
local function tutorialProvider()
if currentMode == MODE_CHARACTER then
return TUTORIAL_CHARACTER;
end
end
TRP3_API.events.listenToEvent(TRP3_API.events.WORKFLOW_ON_LOAD, function()
createTutorialStructure();
-- To try, but I'm afraid for performances ...
Events.listenToEvent(Events.REGISTER_DATA_UPDATED, function(unitID, _, dataType)
if getCurrentPageID() == REGISTER_LIST_PAGEID and unitID ~= Globals.player_id and (not dataType or dataType == "characteristics") then
refreshList();
end
end);
Events.listenToEvent(Events.REGISTER_PROFILE_DELETED, function(profileID)
if profileID then
selectedIDs[profileID] = nil;
if isMenuRegistered(currentlyOpenedProfilePrefix .. profileID) then
unregisterMenu(currentlyOpenedProfilePrefix .. profileID);
end
else
for selectedProfileId, _ in pairs(selectedIDs) do
if isMenuRegistered(currentlyOpenedProfilePrefix .. selectedProfileId) then
unregisterMenu(currentlyOpenedProfilePrefix .. selectedProfileId);
end
end
wipe(selectedIDs);
end
if getCurrentPageID() == REGISTER_LIST_PAGEID then
refreshList();
end
end);
registerMenu({
id = REGISTER_PAGE,
closeable = true,
text = loc.REG_REGISTER,
onSelected = function() setPage(REGISTER_LIST_PAGEID); end,
});
registerPage({
id = REGISTER_LIST_PAGEID,
templateName = "TRP3_RegisterList",
frameName = "TRP3_RegisterList",
frame = TRP3_RegisterList,
onPagePostShow = function() tabGroup:SelectTab(1); end,
tutorialProvider = tutorialProvider,
});
TRP3_RegisterListSlider:SetValue(0);
handleMouseWheel(TRP3_RegisterListContainer, TRP3_RegisterListSlider);
local widgetTab = {};
for i=1,14 do
local widget = _G["TRP3_RegisterListLine"..i];
local widgetClick = _G["TRP3_RegisterListLine"..i.."Click"];
local widgetSelect = _G["TRP3_RegisterListLine"..i.."Select"];
widgetSelect:SetScript("OnClick", onLineSelected);
widgetClick:SetScript("OnClick", onLineClicked);
widgetClick:SetHighlightTexture("Interface\\FriendsFrame\\UI-FriendsFrame-HighlightBar-Blue");
widgetClick:SetAlpha(0.75);
table.insert(widgetTab, widget);
end
TRP3_RegisterList.widgetTab = widgetTab;
TRP3_RegisterListFilterCharactNotes:SetChecked(false);
TRP3_RegisterListFilterCharactName:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListFilterCharactGuild:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListFilterCharactRealm:SetScript("OnClick", refreshList);
TRP3_RegisterListFilterCharactNotes:SetScript("OnClick", refreshList);
TRP3_RegisterListCharactFilterButton:SetScript("OnClick", function(_, button)
if button == "RightButton" then
TRP3_RegisterListFilterCharactName:SetText("");
TRP3_RegisterListFilterCharactGuild:SetText("");
TRP3_RegisterListFilterCharactRealm:SetChecked(true);
TRP3_RegisterListFilterCharactNotes:SetChecked(false);
end
refreshList();
end)
setTooltipForSameFrame(TRP3_RegisterListCharactFilterButton, "LEFT", 0, 5, loc.REG_LIST_FILTERS, loc.REG_LIST_FILTERS_TT);
TRP3_RegisterListFilterCharactNameText:SetText(loc.REG_LIST_NAME);
TRP3_RegisterListFilterCharactGuildText:SetText(loc.REG_LIST_GUILD);
TRP3_RegisterListFilterCharactRealmText:SetText(loc.REG_LIST_REALMONLY);
TRP3_RegisterListFilterCharactNotesText:SetText(loc.REG_LIST_NOTESONLY);
TRP3_RegisterListHeaderAddon:SetText(loc.REG_LIST_ADDON);
TRP3_API.ui.frame.setupEditBoxesNavigation({TRP3_RegisterListFilterCharactName, TRP3_RegisterListFilterCharactGuild});
TRP3_RegisterListPetFilterName:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListPetFilterType:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListPetFilterMaster:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListPetFilterButton:SetScript("OnClick", function(_, button)
if button == "RightButton" then
TRP3_RegisterListPetFilterName:SetText("");
TRP3_RegisterListPetFilterType:SetText("");
TRP3_RegisterListPetFilterMaster:SetText("");
end
refreshList();
end)
setTooltipForSameFrame(TRP3_RegisterListPetFilterButton, "LEFT", 0, 5, loc.REG_LIST_FILTERS, loc.REG_LIST_FILTERS_TT);
TRP3_RegisterListPetFilterNameText:SetText(loc.REG_LIST_PET_NAME);
TRP3_RegisterListPetFilterTypeText:SetText(loc.REG_LIST_PET_TYPE);
TRP3_RegisterListPetFilterMasterText:SetText(loc.REG_LIST_PET_MASTER);
TRP3_API.ui.frame.setupEditBoxesNavigation({TRP3_RegisterListPetFilterName, TRP3_RegisterListPetFilterType, TRP3_RegisterListPetFilterMaster});
TRP3_RegisterListHeaderNameTT:SetScript("OnClick", switchNameSorting);
TRP3_RegisterListHeaderInfoTT:SetScript("OnClick", switchInfoSorting);
TRP3_RegisterListHeaderTimeTT:SetScript("OnClick", switchTimeSorting);
setTooltipForSameFrame(TRP3_RegisterListHeaderActions, "TOP", 0, 0, loc.CM_ACTIONS);
TRP3_RegisterListHeaderActions:SetScript("OnClick", function(self)
if currentMode == MODE_CHARACTER then
onCharactersActions(self);
elseif currentMode == MODE_PETS then
onPetsActions(self);
end
end);
createTabBar();
-- Resizing
TRP3_API.events.listenToEvent(TRP3_API.events.NAVIGATION_RESIZED, function(containerwidth, containerHeight)
for _, line in pairs(widgetTab) do
line:SetHeight((containerHeight - 120) * 0.065);
if containerwidth < 690 then
_G[line:GetName() .. "Time"]:SetWidth(2);
else
_G[line:GetName() .. "Time"]:SetWidth(160);
end
if containerwidth < 850 then
_G[line:GetName() .. "Addon"]:SetWidth(2);
else
_G[line:GetName() .. "Addon"]:SetWidth(160);
end
end
if containerwidth < 690 then
TRP3_RegisterListHeaderTime:SetWidth(2);
else
TRP3_RegisterListHeaderTime:SetWidth(160);
end
if containerwidth < 850 then
TRP3_RegisterListHeaderAddon:SetWidth(2);
else
TRP3_RegisterListHeaderAddon:SetWidth(160);
end
end);
end);
TRP3_API.events.listenToEvent(TRP3_API.events.WORKFLOW_ON_LOADED, function()
if TRP3_API.target then
TRP3_API.target.registerButton({
id = "aa_player_a_page",
configText = loc.TF_OPEN_CHARACTER,
onlyForType = TRP3_API.ui.misc.TYPE_CHARACTER,
condition = function(_, unitID)
return unitID == Globals.player_id or (isUnitIDKnown(unitID) and hasProfile(unitID));
end,
onClick = function(unitID)
openMainFrame();
openPageByUnitID(unitID);
end,
adapter = function(buttonStructure, unitID)
buttonStructure.tooltip = loc.REG_PLAYER;
buttonStructure.tooltipSub = "|cffffff00" .. loc.CM_CLICK .. ": |r" .. loc.TF_OPEN_CHARACTER;
buttonStructure.alert = nil;
if unitID ~= Globals.player_id and hasProfile(unitID) then
local profile = getUnitIDProfile(unitID);
if profile.about and not profile.about.read then
buttonStructure.tooltipSub = "|cff00ff00" .. loc.REG_TT_NOTIF .. "\n" .. buttonStructure.tooltipSub;
buttonStructure.alert = true;
end
end
end,
alertIcon = "Interface\\GossipFrame\\AvailableQuestIcon",
icon = Globals.is_classic and "INV_Misc_Book_09" or "inv_inscription_scroll"
});
end
end);
|
-- Copyright 2018 Yahoo Inc.
-- Licensed under the terms of the Apache license. Please see LICENSE.md file
-- distributed with this work for terms.
--[[
This is where we define the metrics for Fili. Metrics are formulas (for
example, formulas of aggregations and post-aggregations that we send down to
Druid). These formulas are constructed by taking Makers (which can be thought
of as operators and operands) and combining them to create metrics.
For example, the ArithmeticMaker defines the operators +, -, /, so you
can think of the ArithmeticMaker as defining the bits _ + _, _ - _, _ * _,
and _ / _.
Meanwhile, the LongSumMaker defines basic longsums in Druid, which can be
thought of as a simple number when building them up with other Makers. So
bits of formulas like x or y.
We can build a metric by "building up" a formula using the ArithmeticMaker and
the LongSumMaker:
LongSumMaker("metric1") + LongSumMaker("metric2")
This is specified in Lua as:
METRICS = {
metric1 = {maker="longSum", druidMetric="metric1"},
metric2 = {maker="longSum", druidMetric="metric2"},
sum = {maker="arithmeticPLUS", dependencies={"metric1", "metric2"}}
}
Naturally of course these can be nested like any formula. So we could add
the following to METRICS above:
METRICS = {
metric1 = {maker="longSum"},
metric2 = {maker="longSum"},
sum = {maker="arithmeticPlus", dependencies={"metric1", "metric2"}}
difference = {maker="arithmeticMinus", {"sum", "metric1"}}
}
So the metric "difference" is the (rather silly) formula:
(LongSum("metric1") + LongSum("metric2")) - LongSum("metric1")
--]]
-------------------------------------------------------------------------------
-- Metrics
--[[
Metrics are formulas built from makers. They're defined
in a table that maps names to metrics. Each metric is itself a table with
the following keys:
longName - A longer, more human friendly name for the metric. Defaults
to the metric name.
description - Short documentation about the metric. Defaults to the
metric name
maker - The name of the maker to use to define the metric.
dependencies - A list of names of Fili metrics that this metric operates
on, if any, only applies for nested metrics
druidMetric - The name of the druid metric that this metric operates
on directly.
--]]
-------------------------------------------------------------------------------
local M = {}
local metrics = {
testMetric = {
maker = "doubleSum",
druidMetric="test_metric"
},
count = {
maker = "count"
},
}
--- set every metric's type to default
for metric_name, metric_content in pairs(metrics) do
metric_content.type = "default"
M[metric_name] = metric_content
end
return M
|
local command = require 'aula.core.command'
command.set('W', 'w')
command.set('W', 'w')
command.set('Wq', 'wq')
command.set('Q', 'q')
command.set('Qa', 'qa')
command.set('QA', 'qa')
|
-- Various email and tell mod support
-- This function takes the position of a vendor and alerts the owner if it has just been emptied
local email_loaded = minetest.get_modpath("email")
local tell_loaded = minetest.get_modpath("tell")
local mail_loaded = minetest.get_modpath("mail")
function fancy_vend.alert_owner_if_empty(pos)
if fancy_vend.no_alerts then return end
local meta = minetest.get_meta(pos)
local settings = fancy_vend.get_vendor_settings(pos)
local owner = meta:get_string("owner")
local alerted = fancy_vend.stb(meta:get_string("alerted") or "false")
local status, errorcode = fancy_vend.get_vendor_status(pos)
-- Message to send
local input_desc = fancy_vend.get_item_description(settings.input_item)
local output_desc = fancy_vend.get_item_description(settings.output_item)
local stock_msg = "Your vendor trading "..
settings.input_item_qty.." "..input_desc..
" for "..settings.output_item_qty.." "..output_desc..
" at position "..minetest.pos_to_string(pos, 0)..
" has just run out of stock."
if not alerted and not status and errorcode == "no_output" then
if mail_loaded then
local inbox = {}
-- load messages
if not mail.apiversion then
-- cheapie's mail mod https://cheapiesystems.com/git/mail/
if not mail.messages[owner] then mail.messages[owner] = {} end
inbox = mail.messages[owner]
elseif mail.apiversion >= 1.1 then
-- webmail fork https://github.com/thomasrudin-mt/mail (per player storage)
inbox = mail.getMessages(owner)
end
-- Instead of filling their inbox with mail, get the last message sent by "Fancy Vend"
-- and append to the message
-- If there is no last message, then create a new one
local message
for _, msg in pairs(inbox) do
if msg.sender == "Fancy Vend" then -- Put a space in the name to avoid impersonation
message = msg
end
end
if message then
-- Set the message as unread
message.unread = true
-- Append to the end
message.body = message.body..stock_msg.."\n"
else
mail.send("Fancy Vend", owner, "You have unstocked vendors!", stock_msg.."\n")
end
-- save messages
if not mail.apiversion then
-- cheapie's mail mod https://cheapiesystems.com/git/mail/
mail.save()
elseif mail.apiversion >= 1.1 then
-- webmail fork https://github.com/thomasrudin-mt/mail
mail.setMessages(owner, inbox)
end
elseif email_loaded then
-- Rubenwardy's Email Mod: https://github.com/rubenwardy/email
email.send_mail("Fancy Vend", owner, stock_msg)
elseif tell_loaded then
-- octacians tell mod https://github.com/octacian/tell
tell.add(owner, "Fancy Vend", stock_msg)
end
meta:set_string("alerted", "true")
end
end
|
------------------------------------------------------
-- ___ _ --
-- | __| |___ _ __ _____ __ _____ _ _ --
-- | _|| / -_) '_ \/ _ \ V V / -_) '_| --
-- |___|_\___| .__/\___/\_/\_/\___|_| --
-- _ _ |_| _ _ _ --
-- | | (_)__ _| |_| |_(_)_ _ __ _ --
-- | |__| / _` | ' \ _| | ' \/ _` | --
-- |____|_\__, |_||_\__|_|_||_\__, | --
-- |___/ |___/ --
------------------------------------------------------
-- Functions --
------------------------------------------------------
-------------------------------------------
-- Floodlight Formspec --
-------------------------------------------
local function get_formspec_flood(power,tilt,rotate)
local rotate = rotate or 0
local tilt = tilt or 0
local per_rot = (math.abs(rotate)/45)*100
local percent = (math.abs(tilt)/20)*100
local final ="size[8,3]"..
ele.formspec.power_meter(power)..
-- rotate
"image[3.5,0.25;2.8,1;elepower_gui_barbg.png^[transformR90]"..
"image[4.43,2.4;0.5,0.5;elepower_lighting_flood_arrow_icon.png^[transformR90]"..
"tooltip[3.5,1.45;2.25,0.4;"..rotate.." Degrees;#30434c;#f9f9f9]"..
--"button[5.15,1.45;0.75,0.75;rot;+]"..
--"tooltip[5.15,1.45;0.75,0.75;+1 Degrees;#30434c;#f9f9f9]"..
--"button[4.35,1.45;0.75,0.75;rot;0]"..
--"tooltip[4.35,1.45;0.75,0.75;Reset;#30434c;#f9f9f9]"..
--"button[3.5,1.45;0.75,0.75;rot;-]"..
--"tooltip[3.5,1.45;0.75,0.75;-1 Degrees;#30434c;#f9f9f9]"..
--"image[3.5,0.25;2.8,1;elepower_lighting_flood_tilt_gauge.png^[transformR90]"..
"scrollbaroptions[min=-45;max=45;smallstep=1;largestep=5;arrows=show]"..
"scrollbar[3.5,1.45;2.25,0.45;horizontal;rot;"..rotate.."]"..
"scrollbaroptions[min=-20;max=20;smallstep=1;largestep=5;arrows=show]"..
"scrollbar[7.25,0;0.4,2.4;vertical;tilt;"..(tilt).."]"..
-- tilt
"image[6.25,0;1,2.8;elepower_gui_barbg.png]"..
"image[6.5,2.45;0.5,0.5;elepower_lighting_flood_arrow_icon.png]"..
"tooltip[7.25,0;1,2.6;"..(tilt).." Degrees;#30434c;#f9f9f9]"
--"button[7.25,0.05;0.75,0.75;tilt;+]"..
--"tooltip[7.25,0.05;0.75,0.75;+1 Degrees;#30434c;#f9f9f9]"..
--"button[7.25,.9;0.75,0.75;tilt;0]"..
--"tooltip[7.25,.9;0.75,0.75;Reset;#30434c;#f9f9f9]"..
--"button[7.25,1.75;0.75,0.75;tilt;-]"..
--"tooltip[7.25,1.75;0.75,0.75;-1 Degrees;#30434c;#f9f9f9]"
if rotate > 0 then
final = final.."image[4.62,0.25;1.4,1;elepower_gui_barbg.png^[lowpart:"..per_rot..":elepower_gui_bar.png^[transformR270]"
elseif rotate < 0 then
final = final.."image[3.5,0.25;1.4,1;elepower_gui_barbg.png^[lowpart:"..per_rot..":elepower_gui_bar.png^[transformR90]"
end
if tilt < 0 then
final = final.."image[6.25,0;1,1.4;elepower_gui_barbg.png^[lowpart:"..percent..":elepower_gui_bar.png]"
elseif tilt > 0 then
final = final.."image[6.25,1.22;1,1.4;elepower_gui_barbg.png^[lowpart:"..percent..":elepower_gui_bar.png^[transformR180]"
end
final = final.."image[3.5,0.25;2.8,1;elepower_lighting_flood_rotate_gauge.png^[transformR90]"
final = final.."image[6.25,0;1,2.8;elepower_lighting_flood_tilt_gauge.png]"
return final
end
-- register flood on_recieve fields
function elepower_lighting.flood_on_recieve_fields(pos, formname, fields, player)
local meta = minetest.get_meta(pos)
if fields.quit then
return
end
if fields.rot then
local split = string.split(fields.rot, ":")
local new_rot = tonumber(split[2])
meta:set_int("rotate",new_rot)
if meta:get_int("on_off") == 1 then
elepower_lighting.remove_flood_light_fill(pos)
elepower_lighting.add_flood_light_fill(pos)
end
end
if fields.tilt then
local split = string.split(fields.tilt, ":")
local new_tilt = tonumber(split[2])
meta:set_int("tilt", new_tilt)
if meta:get_int("on_off") == 1 then
elepower_lighting.remove_flood_light_fill(pos)
elepower_lighting.add_flood_light_fill(pos)
end
end
--minetest.debug(dump(fields))
end
-------------------------------------------
-- Converts node param2 into a primary --
-- axis and the secondary axis, needed --
-- to workout and place light_fill --
-------------------------------------------
function elepower_lighting.p2_to_axis(node_param2)
-- first_key = primary axis, num_key = param2, value = secondary axis/+-
local p2_conv_table = {x = {[0]="z:+1",[2]="z:-1", [4]="y:-1", [6]="y:+1", [8]="y:+1",[10]="y:-1",[20]="z:+1",[22]="z:-1"},
y = {[5]="x:+1",[7]="x:-1", [9]="x:+1",[11]="x:-1",[12]="z:+1",[14]="z:-1",[16]="z:+1",[18]="z:-1"},
z = {[1]="x:+1",[3]="x:-1",[13]="y:-1",[15]="y:+1",[17]="y:+1",[19]="y:-1",[21]="x:-1",[23]="x:+1"}}
local light_strip_axis
for xyz,all_p2 in pairs(p2_conv_table) do
for p2,sec_axis in pairs(all_p2) do
if node_param2 == p2 then
local second_axis_v = string.split(sec_axis, ":")
light_strip_axis = {[xyz] = 1,[second_axis_v[1].."s"] = tonumber(second_axis_v[2])}
break
end
end
end
return light_strip_axis
end
---------------------------------------------
-- Simply adds or removes light_fill --
---------------------------------------------
function elepower_lighting.add_remove_light_fill(pos,light_strip_axis,light_shape,add_remove)
local x = light_strip_axis.x or 0
local y = light_strip_axis.y or 0
local z = light_strip_axis.z or 0
local xs = light_strip_axis.xs or 0
local ys = light_strip_axis.ys or 0
local zs = light_strip_axis.zs or 0
local mt_add_remove = minetest.remove_node
local node_name = "elepower_lighting:light_fill"
local add_node
-- used for adding/setting nodes
if add_remove == 1 then
mt_add_remove = minetest.set_node
node_name = "air"
add_node = {name = "elepower_lighting:light_fill"}
end
if light_shape == "3x1" then
local pos_p = {x=pos.x+x, y=pos.y+y, z=pos.z+z}
local pos_n = {x=pos.x-x, y=pos.y-y, z=pos.z-z}
local poses = {pos_p,pos_n}
for k,p in pairs(poses) do
if minetest.get_node(p).name == node_name then
mt_add_remove(p,add_node)
end
end
elseif light_shape == "3x2" then
local pos_p = {x=pos.x+x, y=pos.y+y, z=pos.z+z}
local pos_n = {x=pos.x-x, y=pos.y-y, z=pos.z-z}
local pos_ps = {x=pos.x+x+xs, y=pos.y+y+ys, z=pos.z+z+zs}
local pos_cs = {x=pos.x+xs, y=pos.y+ys, z=pos.z+zs}
local pos_ns = {x=pos.x-x+xs, y=pos.y-y+ys, z=pos.z-z+zs}
local poses = {pos_p,pos_n,pos_ps,pos_cs,pos_ns}
for k,p in pairs(poses) do
if minetest.get_node(p).name == node_name then
mt_add_remove(p,add_node)
end
end
end
end
---------------------------------------------
-- Add Flood Light Light nodes --
---------------------------------------------
function elepower_lighting.add_flood_light_fill(pos)
local meta = minetest.get_meta(pos)
local node_p2 = minetest.get_node(pos).param2
local rel_x_y
--1st axis = face dir, 2nd axis = relative vertical(tilt)
local face_dir = {["z:+1"] = {[0]="y:+1",[12]="x:+1",[16]="x:-1",[20]="y:-1"}, -- North
["x:+1"] = {[1]="y:+1", [5]="z:+1", [9]="z:-1",[23]="y:-1"}, -- East
["z:-1"] = {[2]="y:+1",[14]="x:+1",[18]="x:-1",[22]="y:-1"}, -- South
["x:-1"] = {[3]="y:+1", [7]="z:-1",[11]="z:-1",[21]="y:-1"}, -- West
["y:+1"] = {[6]="z:+1", [8]="z:-1",[15]="x:+1",[17]="x:-1"}, -- Up
["y:-1"] = {[4]="z:+1",[10]="z:-1",[13]="x:+1",[19]="x:-1"}} -- Down
-- Rotation reference table
local rot_dir = {[0] = {x = "x",x_v = "+1",y = "z",y_v = "+1", z="y"},
[1] = {x = "z",x_v = "-1",y = "x",y_v = "+1", z="y"},
[2] = {x = "x",x_v = "-1",y = "z",y_v = "-1", z="y"},
[3] = {x = "z",x_v = "+1",y = "x",y_v = "-1", z="y"},
[4] = {x = "x",x_v = "+1",y = "y",y_v = "-1",z="z"},
[5] = {x = "y",x_v = "+1",y = "x",y_v = "+1",z="z"},
[6] = {x = "x",x_v = "-1",y = "y",y_v = "+1",z="z"},
[7] = {x = "y",x_v = "-1",y = "x",y_v = "-1",z="z"},
[8] = {x = "x",x_v = "+1",y = "y",y_v = "+1",z="z"},
[9] = {x = "y",x_v = "-1",y = "x",y_v = "+1",z="z"},
[10] = {x = "x",x_v = "-1",y = "y",y_v = "-1",z="z"},
[11] = {x = "y",x_v = "+1",y = "x",y_v = "-1",z="z"},
[12] = {x = "y",x_v = "-1",y = "z",y_v = "+1",z="x"},
[13] = {x = "z",x_v = "-1",y = "y",y_v = "-1",z="x"},
[14] = {x = "y",x_v = "+1",y = "z",y_v = "-1",z="x"},
[15] = {x = "z",x_v = "+1",y = "y",y_v = "+1",z="x"},
[16] = {x = "y",x_v = "+1",y = "z",y_v = "+1",z="x"},
[17] = {x = "z",x_v = "-1",y = "y",y_v = "+1",z="x"},
[18] = {x = "y",x_v = "-1",y = "z",y_v = "-1",z="x"},
[19] = {x = "z",x_v = "+1",y = "y",y_v = "-1",z="x"},
[20] = {x = "x",x_v = "+1",y = "z",y_v = "+1", z="y"},
[21] = {x = "z",x_v = "+1",y = "x",y_v = "-1", z="y"},
[22] = {x = "x",x_v = "-1",y = "z",y_v = "-1", z="y"},
[23] = {x = "z",x_v = "-1",y = "x",y_v = "+1", z="y"},
}
for axis,p2s in pairs(face_dir) do
for p2,rel_vert in pairs(p2s) do
if node_p2 == p2 then
local sep_rel_x_axis = string.split(axis,":")
local sep_rel_y_axis = string.split(rel_vert,":")
rel_x_y = {[sep_rel_x_axis[1].."x"] = sep_rel_x_axis[2],
[sep_rel_y_axis[1].."y"] = sep_rel_y_axis[2],
[sep_rel_y_axis[1].."z"] = sep_rel_y_axis[4],
x = sep_rel_x_axis[1],
x_val = sep_rel_x_axis[2],
y = sep_rel_y_axis[1],
y_val = sep_rel_y_axis[2]
}
rot_x_y = rot_dir[node_p2]
end
end
end
local light_range = 30
local tilt_angle = meta:get_int("tilt")
local rot_angle = meta:get_int("rotate")
local angle = 90 - rot_angle
-- Start of Raycast Calculations --
-- work out rotation find pt on circle - x = cx + r * cos(a) // y = cy + r * sin(a)
-- eg x = rel-x-origin + (light_range*cos((90-rot_angle)*radians)
local x_rel = pos[rot_x_y.x] + (math.floor((30*math.cos(angle*0.0174533))))*tonumber(rot_x_y.x_v)
local y_rel = pos[rot_x_y.y] + (math.floor((30*math.sin(angle*0.0174533))))*tonumber(rot_x_y.y_v)
local pos_rot = {[rot_x_y.x] = x_rel,[rot_x_y.y] = y_rel, [rot_x_y.z] = pos[rot_x_y.z]}
-- work out gradient from angle (math.tan needs radians=degrees*0.0174533...)
local grad = math.tan(tilt_angle*0.0174533)
local y_end = math.floor(light_range*grad)
local xx = (rel_x_y.xx or 0)*light_range
local yx = (rel_x_y.yx or 0)*light_range
local zx = (rel_x_y.zx or 0)*light_range
local xy = (rel_x_y.xy or 0)*y_end
local yy = (rel_x_y.yy or 0)*y_end
local zy = (rel_x_y.zy or 0)*y_end
-- pos_s (start) simply add relative x
local pos_s = {x=pos.x+(xx/light_range),y=pos.y+(yx/light_range),z=pos.z+(zx/light_range)}
-- pos_e (end) add both relative x and relative y
local pos_e = {x=pos_rot.x+xx+xy,y=pos_rot.y+yx+yy,z=pos_rot.z+zx+zy}
meta:set_string("flood_light_pos_s", minetest.serialize(pos_s))
meta:set_string("flood_light_pos_e", minetest.serialize(pos_e))
local ray = minetest.raycast(pos_s,pos_e,false,true)
local ray_next = ray:next()
local end_pos
while ray_next do
local name = minetest.get_node(ray_next.under).name
local node_draw = minetest.registered_items[name].drawtype
if node_draw ~= "plantlike" and
node_draw ~= "firelike" and
node_draw ~= "raillike" and
node_draw ~= "torchlike" and
node_draw ~= "signlike" and
name ~= "elepower_lighting:light_fill" then
local e_pos = ray_next.under
meta:set_string("flood_light_end", minetest.serialize(e_pos))
end_pos = {x=e_pos.x-(xx/light_range),y=e_pos.y-(yx/light_range),z=e_pos.z-(zx/light_range)}
break
end
ray_next = ray:next()
end
local tot = 30
if end_pos then
tot = math.abs(end_pos[rel_x_y.x] - pos[rel_x_y.x])
end
-- Start of light fill calculations
local flood_fill_pos = {}
for i = 1,tot,1 do
local new_pos = table.copy(pos)
-- calculate rotation position
local x_rel = new_pos[rot_x_y.x] + ((math.floor((i*math.cos(angle*0.0174533))))*tonumber(rot_x_y.x_v)) + 1*tonumber(rot_x_y.x_v) -- last + removes offset from carrier "1"
local y_rel = new_pos[rot_x_y.y] + (math.floor((i*math.sin(angle*0.0174533))))*tonumber(rot_x_y.y_v)
local pos_rot = {[rot_x_y.x] = x_rel,[rot_x_y.y] = y_rel, [rot_x_y.z] = new_pos[rot_x_y.z]}
-- adjust for tilt
pos_rot[rel_x_y.x] = (pos_rot[rel_x_y.x] + (1*rel_x_y.x_val)) -- relative X axis
pos_rot[rel_x_y.y] = (pos_rot[rel_x_y.y] + math.ceil((i*rel_x_y.y_val)*grad)) -- relative Y axis
--new_pos.x = new_pos.x+(math.floor(0.85*i))
if minetest.get_node(pos_rot).name == "air" or
minetest.get_node(pos_rot).name == "elepower_lighting:light_fill" then
table.insert(flood_fill_pos,pos_rot)
minetest.set_node(pos_rot,{name = "elepower_lighting:light_fill"})
--minetest.debug(rot_x_y.y..":".. rot_x_y.y_v)
end
end
meta:set_string("flood_fill_pos", minetest.serialize(flood_fill_pos))
end
---------------------------------------------
-- Removes Flood Light Light nodes --
---------------------------------------------
function elepower_lighting.remove_flood_light_fill(pos)
local meta = minetest.get_meta(pos)
local flood_fill_pos = minetest.deserialize(meta:get_string("flood_fill_pos"))
if type(flood_fill_pos) == "table" then
meta:set_string("flood_light_pos_s","")
meta:set_string("flood_light_pos_e","")
meta:set_string("flood_light_end","")
for k,pos in pairs(flood_fill_pos) do
if minetest.get_node(pos).name == "elepower_lighting:light_fill" then
minetest.remove_node(pos)
end
end
end
end
-------------------------------------------
-- A rotate and place that allows lights --
-- to mount into wall sockets --
-- thanks mt forums for below soln idea --
-------------------------------------------
function elepower_lighting.rot_and_place(itemstack, placer, pointed_thing)
local p0 = pointed_thing.under
local p1 = pointed_thing.above
local param2 = 0
if placer then
local placer_pos = placer:get_pos()
if placer_pos then
param2 = minetest.dir_to_facedir(vector.subtract(p1, placer_pos))
end
if p0.x<p1.x then -- -X
param2 = 12 + param2
elseif p0.x>p1.x then -- +X
param2 = 16 + param2
elseif p0.z<p1.z then -- +Z
param2 = 4 + param2
elseif p0.z>p1.z then -- -Z
param2 = 8 + param2
elseif p0.y<p1.y then -- +Y
param2 = param2
elseif p0.y>p1.y then -- -Y
param2 = 20 + param2
end
end
return minetest.item_place(itemstack, placer, pointed_thing, param2)
end
-------------------------------------
-- Light State Function --
-- "Active", "Off", "Out of Power" --
-------------------------------------
function elepower_lighting.status(on_off,storage,usage)
local status = "Active"
if on_off == 0 then
status = "Off"
elseif storage < usage then
status = "Out of Power!"
end
return status
end
------------------------------------
-- Main Lighting timer, what uses --
-- EpU's and allows lights to be --
-- switched on and off --
------------------------------------
function elepower_lighting.light_timer(pos)
local meta = minetest.get_meta(pos)
local on_off = meta:get_int("on_off")
local reg_name = minetest.get_node(pos).name
local node_p2 = minetest.get_node(pos).param2
local name = minetest.registered_items[minetest.get_node(pos).name].description
local light_shape = minetest.registered_items[minetest.get_node(pos).name].ele_light_shape or nil
local capacity = ele.helpers.get_node_property(meta, pos, "capacity")
local storage = ele.helpers.get_node_property(meta, pos, "storage")
local usage = ele.helpers.get_node_property(meta, pos, "usage")
local pow_percent = {capacity = capacity, storage = storage, usage = usage}
local light_strip_axis
local flood_light_change = false
if light_shape ~= "flood" then
light_strip_axis = elepower_lighting.p2_to_axis(node_p2)
elseif light_shape == "flood" then
-- need an overide in the event a wall/tree etc is built infront of an "on" flood light beam
local flood_light_end = minetest.deserialize(meta:get_string("flood_light_end"))
local pos_s = minetest.deserialize(meta:get_string("flood_light_pos_s"))
local pos_e = minetest.deserialize(meta:get_string("flood_light_pos_e"))
local e_pos
local bulb_type = string.match(reg_name, ':(.-)_')
if light_shape == "flood" then
-- change floodlight node for angled/tilted version
local tilt = meta:get_int("tilt") or 0
local rotate = meta:get_int("rotate") or 0
local rpn = "p"
local tpn = "p"
local new_name
if rotate < 0 then
if rotate < -10 then
rpn = "n"
end
rotate = rotate*-1
end
if tilt < 0 then
if tilt < -5 then
tpn = "n"
end
tilt = tilt*-1
end
if rotate > 10 then
rotate = 45
else
rotate = 0
end
if tilt > 5 then
tilt = 20
else
tilt = 0
end
if not string.find(reg_name, "active") then
new_name = "elepower_lighting:"..bulb_type.."_floodlight_x"..rpn..rotate.."_y"..tpn..tilt
else
new_name = "elepower_lighting:"..bulb_type.."_floodlight_x"..rpn..rotate.."_y"..tpn..tilt.."_active"
end
if new_name ~= reg_name then
ele.helpers.swap_node(pos, new_name)
end
end
if pos_s then
local ray = minetest.raycast(pos_s,pos_e,false,true)
local ray_next = ray:next()
while ray_next do
local name = minetest.get_node(ray_next.under).name
local node_draw = minetest.registered_items[name].drawtype
if node_draw ~= "plantlike" and
node_draw ~= "firelike" and
node_draw ~= "raillike" and
node_draw ~= "torchlike" and
node_draw ~= "signlike" and
name ~= "elepower_lighting:light_fill" then
e_pos = ray_next.under
break
end
ray_next = ray:next()
end
if minetest.serialize(e_pos) ~= minetest.serialize(flood_light_end) then
flood_light_change = true
end
end
end
if (storage >= usage and on_off == 1) then
if not string.find(reg_name, "active") or flood_light_change == true then
if flood_light_change == false then
ele.helpers.swap_node(pos, reg_name.."_active")
elseif flood_light_change == true then
elepower_lighting.remove_flood_light_fill(pos)
end
if light_shape == "flood" then
elepower_lighting.add_flood_light_fill(pos)
elseif light_shape then
elepower_lighting.add_remove_light_fill(pos,light_strip_axis,light_shape,1)
end
end
pow_percent.storage = pow_percent.storage - usage
storage = pow_percent.storage
meta:set_int("storage", pow_percent.storage)
else
if string.find(reg_name, "active") then
local name = string.sub(reg_name, 1, -8)
ele.helpers.swap_node(pos, name)
if light_shape then
if light_shape == "flood" then
elepower_lighting.remove_flood_light_fill(pos)
elseif light_shape then
elepower_lighting.add_remove_light_fill(pos,light_strip_axis,light_shape)
end
end
end
end
local status = elepower_lighting.status(on_off,pow_percent.storage,pow_percent.usage)
meta:set_string("infotext", name.." "..status.."\n" .. ele.capacity_text(capacity, storage))
if light_shape == "flood" then
local tilt = meta:get_int("tilt") or 0
local rotate = meta:get_int("rotate") or 0
meta:set_string("formspec", get_formspec_flood(pow_percent,tilt,rotate))
end
return true
end
---------------------------------------------
-- Main Colored Lighting timer, what uses --
-- EpU's and allows lights to be switched --
-- on and off --
---------------------------------------------
elepower_lighting.colors = {{"#ff0500", "Red"},
{"#ff3500", "Dark Orange"},
{"#ff6300", "Orange"},
{"#ff9100", "Light Orange"},
{"#ffc000", "Golden"},
{"#ffef00", "Yellow"},
{"#e1ff00", "Lemon Lime"},
{"#b3ff00", "Lime"},
{"#84ff00", "Lawn Green"},
{"#56ff00", "Bright Green"},
{"#00ff36", "Green"},
{"#00ff65", "Spring Green"},
{"#00ff93", "Sea Green"},
{"#00ffc2", "Aqua"},
{"#00fff0", "Turquoise Blue"},
{"#00dfff", "Sky Blue"},
{"#00b1ff", "Vivid Blue"},
{"#0082ff", "Azure"},
{"#0053ff", "Blue"},
{"#0024ff", "Blue Bonnet"},
{"#0900ff", "Dark Blue"},
{"#3800ff", "Blue Purple"},
{"#6700ff", "Indigo"},
{"#9500ff", "Violet"},
{"#c400ff", "Orchid"},
{"#f200ff", "Magenta"},
{"#ff00dd", "Hot Pink"},
{"#ff00af", "Shocking Pink"},
{"#ff0080", "Pink"},
{"#ff0051", "Apple Red"},
{"#ffffff", "White"},
{"#000000", "Black"}
}
local function get_formspec_panel_color(power,color_mode,color_sync)
local color_m = color_mode
local color_s = color_sync
if tonumber(color_m) then
color_m = "Single Color-"..elepower_lighting.colors[(color_m/8)][2]
else
color_m = color_m:gsub("^%l", string.upper)
end
local final ="size[8,3]"..
"container[0,0.1]"..
ele.formspec.power_meter(power)..
"container_end[]"..
"label[1,-0.05;Current Selection: "..color_m.."]"..
"checkbox[6,-0.25;sync;Synchronize;"..color_s.."]"..
"image_button[1,0.4;2,0.75;elepower_lighting_gui_rainbow_button.png;r_color;Rainbow;false;true;elepower_lighting_gui_rainbow_button.png^[opacity:127]"..
"image_button[1,1.1;2,0.75;elepower_lighting_gui_strobe_button.png;r_color;Strobe;false;true;elepower_lighting_gui_strobe_button.png^[opacity:127]"..
"image_button[1,1.8;2,0.75;elepower_lighting_gui_blue_button.png;r_color;Blues;false;true;elepower_lighting_gui_blue_button.png^[opacity:127]"..
"image_button[1,2.5;2,0.75;elepower_lighting_gui_red_button.png;r_color;Reds;false;true;elepower_lighting_gui_red_button.png^[opacity:127]"
for k,def in pairs(elepower_lighting.colors) do
local image_end = "elepower_lighting_gui_color_button.png^[multiply:"..
def[1]..";f_color;"..((k)*8)..
";false;true;elepower_lighting_gui_color_button.png^[multiply:"..
def[1].."^[opacity:127]]"
final = final.."style[f_color;font_size=0;textcolor="..def[1].."]"
if k <= 8 then
final = final.."image_button["..(3.0+((k-1)*0.6))..",0.4;0.75,0.75;"..image_end
final = final.."tooltip["..(3.0+((k-1)*0.6))..",0.4;0.55,0.65;"..def[2]..";#30434c;#f9f9f9]"
elseif k > 8 and k < 17 then
final = final.."image_button["..(3.0+((k-9)*0.6))..",1.1;0.75,0.75;"..image_end
final = final.."tooltip["..(3.0+((k-9)*0.6))..",1.1;0.55,0.65;"..def[2]..";#30434c;#f9f9f9]"
elseif k > 16 and k < 25 then
final = final.."image_button["..(3.0+((k-17)*0.6))..",1.8;0.75,0.75;"..image_end
final = final.."tooltip["..(3.0+((k-17)*0.6))..",1.8;0.55,0.65;"..def[2]..";#30434c;#f9f9f9]"
else
final = final.."image_button["..(3.0+((k-25)*0.6))..",2.5;0.75,0.75;"..image_end
final = final.."tooltip["..(3.0+((k-25)*0.6))..",2.5;0.55,0.65;"..def[2]..";#30434c;#f9f9f9]"
end
end
return final
end
-- register color on_recieve fields
function elepower_lighting.color_on_recieve_fields(pos, formname, fields, player)
local meta = minetest.get_meta(pos)
if fields.quit then
return
end
if fields.r_color == "Rainbow" then
meta:set_string("color_mode","rainbow")
elseif fields.r_color == "Strobe" then
meta:set_string("color_mode","strobe")
elseif fields.r_color == "Blues" then
meta:set_string("color_mode","blues")
elseif fields.r_color == "Reds" then
meta:set_string("color_mode","reds")
elseif fields.f_color then
meta:set_string("color_mode",fields.f_color)
elseif fields.sync then
meta:set_string("color_sync",tostring(fields.sync))
end
--minetest.debug(dump(fields))
end
function elepower_lighting.light_timer_colored(pos)
local meta = minetest.get_meta(pos)
local on_off = meta:get_int("on_off")
local cycles = meta:get_int("light_color_count")
local color_mode = meta:get_string("color_mode") or "rainbow"
local color_sync = meta:get_string("color_sync") or "false"
local run_bwd = meta:get_string("run_bwd") or "false"
local node = minetest.get_node(pos)
local name = minetest.registered_items[minetest.get_node(pos).name].description
local reg_name = minetest.get_node(pos).name
local capacity = ele.helpers.get_node_property(meta, pos, "capacity")
local storage = ele.helpers.get_node_property(meta, pos, "storage")
local usage = ele.helpers.get_node_property(meta, pos, "usage")
local pow_percent = {capacity = capacity, storage = storage, usage = usage}
local strobe_ok = true
local is_timer = true
if cycles == 5 then --(1 second)
if (storage >= usage and on_off == 1) then
if not string.find(reg_name, "active") and color_mode ~= "strobe" then
ele.helpers.swap_node(pos, reg_name.."_active")
end
pow_percent.storage = pow_percent.storage - usage
storage = pow_percent.storage
meta:set_int("storage", pow_percent.storage)
else
if string.find(reg_name, "active") then
local name = string.sub(reg_name, 1, -8)
ele.helpers.swap_node(pos, name)
strobe_ok = false
end
end
local status = elepower_lighting.status(on_off,pow_percent.storage,pow_percent.usage)
meta:set_string("formspec", get_formspec_panel_color(pow_percent,color_mode,color_sync))
meta:set_string("infotext", name .." "..status.. "\n" .. ele.capacity_text(capacity, storage))
cycles = 0
end
node = minetest.get_node(pos)
if string.find(node.name, "active") or strobe_ok then
if color_mode == "rainbow" then
if color_sync == "true" then
local sync_total = 30
local node_plain_p2 = node.param2 % 8
col_seq = math.ceil(sync_total*((((elepower_lighting.timer/0.2))/sync_total)%1))
node.param2 = node_plain_p2 + ((col_seq*8)-8)
minetest.swap_node(pos, node)
else
node.param2 = node.param2+8
if node.param2 >=240 then
node.param2 = (node.param2 % 32)
end
minetest.swap_node(pos, node)
end
elseif color_mode == "blues" or color_mode == "reds" then
local blues_seq_p2 = {120,128,136,144,152,160,168}
local reds_seq_p2 = {200,208,216,224,232,0}
local node_plain_p2 = node.param2 % 8
local cur_color_p2 = math.floor(node.param2/8)*8
local col_seq = 1
local change = 1
local col_seq_p2 = blues_seq_p2
local sync_total = #blues_seq_p2-1
if color_mode == "reds" then
col_seq_p2 = reds_seq_p2
sync_total = #reds_seq_p2-1
end
if color_sync == "true" then
if math.floor(((elepower_lighting.timer/0.2)/sync_total)%2) == 0 then
--minetest.debug("bwd: ".. (sync_total+1)-math.ceil(sync_total*((((elepower_lighting.timer/0.2))/sync_total)%1)))
col_seq = (sync_total+1)-math.ceil(sync_total*((((elepower_lighting.timer/0.2))/sync_total)%1))
change = 0
meta:set_string("run_bwd", "true")
else
--minetest.debug("fwd: ".. 1+math.ceil(sync_total*((((elepower_lighting.timer/0.2))/sync_total)%1)))
col_seq = 1+math.ceil(sync_total*((((elepower_lighting.timer/0.2))/sync_total)%1))
change = 0
meta:set_string("run_bwd", "false")
end
else
for k,v in pairs(col_seq_p2 ) do
if v == cur_color_p2 then
col_seq = k
end
end
if (col_seq == #col_seq_p2 or run_bwd == "true") and col_seq ~= 1 then
meta:set_string("run_bwd", "true")
change = -1
elseif col_seq == 1 then
meta:set_string("run_bwd", "false")
end
end
--minetest.debug(col_seq+change)
node.param2 = col_seq_p2[col_seq+change] + node_plain_p2
minetest.swap_node(pos, node)
elseif color_mode == "strobe" then
if color_sync == "true" then
local col_seq = math.ceil(math.floor((elepower_lighting.timer/0.2)+0.5)%2)
if col_seq == 1 then
if not string.find(reg_name, "active") then
ele.helpers.swap_node(pos, reg_name.."_active")
end
else
if string.find(reg_name, "active") then
local name = string.sub(reg_name, 1, -8)
ele.helpers.swap_node(pos, name)
end
end
else
if string.find(reg_name, "active") then
local name = string.sub(reg_name, 1, -8)
ele.helpers.swap_node(pos, name)
else
ele.helpers.swap_node(pos, reg_name.."_active")
end
end
elseif type(tonumber(color_mode)) == "number" then
local node_plain_p2 = node.param2 % 8
local cur_color_p2 = math.floor(node.param2/8)*8
if color_mode-8 ~= cur_color_p2 then
node.param2 = color_mode-8 + node_plain_p2
minetest.swap_node(pos, node)
end
else
-- catch error state set to white
local node_plain_p2 = node.param2 % 8
node.param2 = node_plain_p2 + 240
minetest.swap_node(pos, node)
end
end
local timer = minetest.get_node_timer(pos)
if timer:get_timeout() ~= 0.2 then
timer:start(0.2)
is_timer = false
end
meta:set_int("light_color_count",cycles+1)
return is_timer
end
elepower_lighting.timer = 0
minetest.register_globalstep(function(dtime)
-- note counter shouldn't cause an issue until uptime exceeds about 7million yrs
elepower_lighting.timer = elepower_lighting.timer + dtime;
end)
-----------------------------------------
-- Lighting simple functions for basic --
-- node functionality --
-----------------------------------------
-- set light on/off by punch
function elepower_lighting.light_punch(pos,player)
local meta = minetest.get_meta(pos)
local on_off = meta:get_int("on_off") or 1
if on_off == 1 then
on_off = 0
else
on_off = 1
end
meta:set_int("on_off",on_off)
end
-- set lights to on when constructed
function elepower_lighting.light_construct(pos)
local meta = minetest.get_meta(pos)
meta:set_int("on_off",1)
meta:set_string("infotext", "Active")
local is_colored = minetest.registered_items[minetest.get_node(pos).name].palette or nil
if is_colored then
meta:set_string("color_mode","rainbow")
local timer = minetest.get_node_timer(pos)
timer:start(0.2)
end
end
-- Main place function
function elepower_lighting.light_place(itemstack, placer, pointed_thing)
if pointed_thing.type ~= "node" then
return itemstack
end
return elepower_lighting.rot_and_place(itemstack, placer, pointed_thing)
end
-- For lights more than 1x1 cleanup light_fill on destruction
function elepower_lighting.light_strip_cleanup(pos)
local node_p2 = minetest.get_node(pos).param2
local light_shape = minetest.registered_items[minetest.get_node(pos).name].ele_light_shape or nil
local light_strip_axis = elepower_lighting.p2_to_axis(node_p2)
if light_shape == "flood" then
elepower_lighting.remove_flood_light_fill(pos)
else
elepower_lighting.add_remove_light_fill(pos,light_strip_axis,light_shape)
end
end
|
TOOL.Category = "EMod Tools"
TOOL.Name = "E-ToolBox"
TOOL.Tab = "EMod"
TOOL.Information = {
{
name = "left"
},
{
name = "right"
}
}
function TOOL:LeftClick(trace)
if (IsValid(trace.Entity) and trace.Entity:IsPlayer()) then return false end
if (CLIENT) then return true end
if (not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone)) then return false end
local ply = self:GetOwner()
-- Get ToolBox Data here --
-- if ( !data ) then return false end
-- If HitEntity is the same type then update here --
-- CheckLimit here
-- if ( IsValid( pl ) && !pl:CheckLimit( "balloons" ) ) then return end
local ent = ents.Create("emod_light")
if (not IsValid(ent)) then return end
ent:Spawn()
ent:SetPlayer(pl)
ent.Player = pl
if (IsValid(pl)) then
pl:AddCount("emod_highload", ent)
pl:AddCleanup("emod_highload", ent)
end
local min = ent:OBBMins()
ent:SetPos(trace.HitPos - trace.HitNormal * min.z)
undo.Create("ToolBox")
undo.AddEntity(ent)
undo.SetPlayer(ply)
undo.Finish()
return true
end
function TOOL:RightClick(trace)
return self:LeftClick(trace, false)
end
if (SERVER) then
function MakeBalloon(pl, r, g, b, force, Data)
if (IsValid(pl) and not pl:CheckLimit("balloons")) then return end
local balloon = ents.Create("gmod_balloon")
if (not IsValid(balloon)) then return end
duplicator.DoGeneric(balloon, Data)
balloon:Spawn()
duplicator.DoGenericPhysics(balloon, pl, Data)
force = math.Clamp(force, -1E34, 1E34)
balloon:SetColor(Color(r, g, b, 255))
balloon:SetForce(force)
balloon:SetPlayer(pl)
balloon.Player = pl
balloon.r = r
balloon.g = g
balloon.b = b
balloon.force = force
if (IsValid(pl)) then
pl:AddCount("balloons", balloon)
pl:AddCleanup("balloons", balloon)
end
return balloon
end
duplicator.RegisterEntityClass("gmod_balloon", MakeBalloon, "r", "g", "b", "force", "Data")
end
function TOOL:UpdateGhostBalloon(ent, ply)
if (not IsValid(ent)) then return end
local trace = ply:GetEyeTrace()
if (not trace.Hit or IsValid(trace.Entity) and (trace.Entity:IsPlayer() or trace.Entity:GetClass() == "gmod_balloon")) then
ent:SetNoDraw(true)
return
end
local CurPos = ent:GetPos()
local NearestPoint = ent:NearestPoint(CurPos - (trace.HitNormal * 512))
local Offset = CurPos - NearestPoint
local pos = trace.HitPos + Offset
local modeltable = list.Get("BalloonModels")[self:GetClientInfo("model")]
if (modeltable.skin) then
ent:SetSkin(modeltable.skin)
end
ent:SetPos(pos)
ent:SetAngles(Angle(0, 0, 0))
ent:SetNoDraw(false)
end
function TOOL:Think()
-- if ( !IsValid( self.GhostEntity ) || self.GhostEntity.model != self:GetClientInfo( "model" ) ) then
-- local modeltable = list.Get( "BalloonModels" )[ self:GetClientInfo( "model" ) ]
-- if ( !modeltable ) then self:ReleaseGhostEntity() return end
-- self:MakeGhostEntity( modeltable.model, Vector( 0, 0, 0 ), Angle( 0, 0, 0 ) )
-- if ( IsValid( self.GhostEntity ) ) then self.GhostEntity.model = self:GetClientInfo( "model" ) end
-- end
-- self:UpdateGhostBalloon( self.GhostEntity, self:GetOwner() )
end
local ConVarsDefault = TOOL:BuildConVarList()
function TOOL.BuildCPanel(CPanel)
CPanel:AddControl("Header", {
Description = "#tool.balloon.help"
})
end
|
-----------------------------------------
-- ID: 18581
-- Item: Carbuncle's Pole
-- Item Effect: Restores 160-220 HP
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
function onAdditionalEffect(player,target,damage)
local chance = 15
if (chance > math.random(0,99)) then
local dmg = math.random(50,90)
local params = {}
params.bonusmab = 0
params.includemab = false
dmg = addBonusesAbility(player, tpz.magic.ele.LIGHT, target, dmg, params)
dmg = dmg * applyResistanceAddEffect(player,target,tpz.magic.ele.LIGHT,0)
dmg = adjustForTarget(target,dmg,tpz.magic.ele.LIGHT)
dmg = finalMagicNonSpellAdjustments(player,target,tpz.magic.ele.LIGHT,dmg)
local message = tpz.msg.basic.ADD_EFFECT_DMG
if (dmg < 0) then
message = tpz.msg.basic.ADD_EFFECT_HEAL
end
return tpz.subEffect.LIGHT_DAMAGE,message,dmg
else
return 0,0,0
end
end
function onItemCheck(target)
return 0
end
function onItemUse(target)
local hpHeal = math.random(160,220)
local dif = target:getMaxHP() - target:getHP()
if (hpHeal > dif) then
hpHeal = dif
end
target:addHP(hpHeal)
target:messageBasic(tpz.msg.basic.RECOVERS_HP, 0, hpHeal)
end
|
require "utils"
require "trycatch"
require "PiniAPI"
require "cocos.cocos2d.json"
require "BuiltIn_Animation"
math.randomseed(os.time())
ENGINE_LOG = nil
XLSX_CLEAR = nil
REFRESH_BUILD_PATH = nil
local luaj = nil
local Utils = nil
local PiniLib = nil
local fileUtil = nil
local xlsxCache = {}
local ROOT_PATH = nil
local PackageName = nil
local CurrentPlatform = nil
local VM_BLOCK_FOR_ANDROID=nil
PROP_PUSH = function()end
PROP_POP = function()end
if OnPreview then
_G._LOG_ = {}
ROOT_PATH = PiniLuaHelper:buildPath()
ENGINE_LOG = function(text) table.insert(_G._LOG_,text) end
XLSX_CLEAR = function() xlsxCache={} end
REFRESH_BUILD_PATH = function() ROOT_PATH = PiniLuaHelper:buildPath() end
CurrentPlatform = "Preview"
fileUtil = {}
fileUtil["getSuitableFOpen"] = function(e) return e end
else
OnPreview = false
Utils = require("plua.utils")
-- PROP_PUSH = Utils.PROP_PUSH
-- PROP_POP = Utils.PROP_POP
fileUtil = cc.FileUtils:getInstance()
ROOT_PATH = fileUtil:getWritablePath()
CurrentPlatform = cc.Application:getInstance():getTargetPlatform()
if (cc.PLATFORM_OS_ANDROID == CurrentPlatform) then
luaj = require "cocos.cocos2d.luaj"
end
end
local JavaClassName = "org/cocos2dx/lua/AppActivity"
function DeviceNativeCall(func,args,sig)
print(func,args,sig)
local ok,ret = luaj.callStaticMethod(JavaClassName,func,args,sig)
if not ok then
print("luaj error:", ret)
else
print("The ret is:", ret)
end
return ret
end
function AppPackageName()
return DeviceNativeCall("AppPackageName",{},"()Ljava/lang/String;")
end
function OBBDirPath()
return DeviceNativeCall("OBBDirPath",{},"()Ljava/lang/String;")
end
function PINI_IAP_CALLBACK(jsondata)
print(jsondata)
-- DeviceNativeCall("Android_Toast",{ jsondata , 10})
local _data = jsondata:sub(2,#jsondata-1)
local ds = _data:explode(",")
local result = false
for k,v in ipairs(ds) do
ks = v:explode(":")
if ks[1] == '"result"' then
if ks[2]:startsWith("true") then
result = true
end
break
end
end
if result then
pini.XVM:returnValueOnThread( 1, VM_BLOCK_FOR_ANDROID )
_LNXG["결제정보.데이터"] = jsondata
else
pini.XVM:returnValueOnThread( 0, VM_BLOCK_FOR_ANDROID )
end
pini.Timer(pini:GetUUID(),1,function()
local blockId = VM_BLOCK_FOR_ANDROID
VM_BLOCK_FOR_ANDROID = nil
pini.XVM:resume(blockId)
end,false):run()
end
function PINI_IAP_CHECK_CALLBACK(jsondata)
local j = json.decode(jsondata)
pini.XVM:returnValueOnThread( j["result"], VM_BLOCK_FOR_ANDROID )
pini.Timer(pini:GetUUID(),1,function()
local blockId = VM_BLOCK_FOR_ANDROID
VM_BLOCK_FOR_ANDROID = nil
pini.XVM:resume(blockId)
end,false):run()
end
function PINI_IAP_CONSUME_CALLBACK(jsondata)
local j = json.decode(jsondata)
_LNXG["jtext"] = j["jtext"]
_LNXG["jsize"] = j["jsize"]
pini.XVM:returnValueOnThread( j["result"], VM_BLOCK_FOR_ANDROID )
pini.Timer(pini:GetUUID(),1,function()
local blockId = VM_BLOCK_FOR_ANDROID
VM_BLOCK_FOR_ANDROID = nil
pini.XVM:resume(blockId)
end,false):run()
end
function PINI_OBB_DOWNLOAD_RESULT(result)
--DeviceNativeCall("Android_Toast",{ ">>>>>>>>"..tostring(result).."/"..tostring(VM_BLOCK_FOR_ANDROID) , 1})
pini.XVM:returnValue(tonumber(result))
pini.Timer(pini:GetUUID(),1,function()
--DeviceNativeCall("Android_Toast",{ ">>>>>>>>GOGO", 1})
local blockId = VM_BLOCK_FOR_ANDROID
VM_BLOCK_FOR_ANDROID = nil
pini.XVM:resume(blockId)
end,false):run()
end
function LNX_VUNGLE_CALLBACK(length)
if pini.XVM.vungleCallback then
_LNXG["벙글광고표기.길이"] = length
local funcName = pini.XVM.vungleCallback
pini.XVM.vungleCallback = nil
pini.Timer(pini:GetUUID(),0,function()
pini.XVM:call(funcName)
end,false):run()
end
end
try{
function() require(FILES["module/Animation"]) end,
catch {function(error)end}
}
CLICK_WAIT_PRIORITY = 55000
GUI_PRIORITY = 60000
--##########################################################################
-- LanXVM 라이브러리 기능
--##########################################################################
function LNX_NODE(vm,stck)
local id = vm:ARGU("노드","아이디","")
local pos = vm:ARGU("노드","위치","화면중앙")
local size = vm:ARGU("노드","크기","원본크기")
local parent = vm:ARGU("노드","부모","")
local x = vm:ARGU("노드","x",nil)
local y = vm:ARGU("노드","y",nil)
local isPreserve = vm:ARGU("노드","항상표시","아니오")
local angle = vm:ARGU("노드","회전",0)
x = tonumber(x)
y = tonumber(y)
angle = tonumber(angle)
local acp = _LNXG["설정.이미지중심"] or "0.5,0.5"
acp = acp:explode(",")
isPreserve = isPreserve=="예"
local node = nil
node = pini.Node(id)
if node == nil then
return
end
pini:AttachDisplay(node,parent)
node:setAnchorPoint(acp[1] or 0.5,1-(acp[2] or 0.5))
node:setScale(StrEnumToScale(node,size))
if x or y then
node:setPosition(x or 0,y or 0)
else
node:setPosition(StrEnumToPos(node,pos))
end
node:setPreserve(isPreserve)
node:setRotate(angle)
end
function LNX_IMAGE(vm,stck)
local id = vm:ARGU("이미지","아이디","")
local path = vm:ARGU("이미지","파일명","")
local pos = vm:ARGU("이미지","위치","화면중앙")
local effect = vm:ARGU("이미지","효과","")
local effectSec = vm:ARGU("이미지","효과시간",0.25)
local size = vm:ARGU("이미지","크기","원본크기")
local connect = vm:ARGU("이미지","북마크이동","")
local parent = vm:ARGU("이미지","부모","")
local overoll = vm:ARGU("이미지","오버롤","")
local color = vm:ARGU("이미지","색상","255,255,255")
local opacity = vm:ARGU("이미지","투명도","255")
local screenshot = vm:ARGU("이미지","스크린샷노출","예")
local GUI = vm:ARGU("이미지","GUI","아니오")
local x = vm:ARGU("이미지","x",nil)
local y = vm:ARGU("이미지","y",nil)
local flip = vm:ARGU("이미지","반전","")
local isPreserve = vm:ARGU("이미지","항상표시","아니오")
local blendMode = vm:ARGU("이미지","색상모드","기본")
local keep = vm:ARGU("이미지","유지","아니오") == "예"
local angle = vm:ARGU("이미지","회전",0)
local enableAnti = vm:ARGU("이미지","안티","예")
x = tonumber(x)
y = tonumber(y)
angle = tonumber(angle)
local acp = _LNXG["설정.이미지중심"] or "0.5,0.5"
acp = acp:explode(",")
GUI = GUI=="예"
screenshot = screenshot=="예"
isPreserve = isPreserve=="예"
enableAnti = enableAnti=="예"
local flipX = false
local flipY = false
if flip == "좌우" then
flipX = true
elseif flip == "상하" then
flipY = true
elseif flip == "상하좌우" then
flipX = true
flipY = true
end
if path:len() > 0 then
local node = nil
if keep then
node = pini:FindNode(id)
if node == nil or node.type ~= "Sprite" then
node = pini.Sprite(id,path,overoll)
pini:AttachDisplay(node,parent)
else
AnimMgr:stop(node)
node:StopAction();
node:setSprite(path)
node:setVisible(true)
end
else
node = pini.Sprite(id,path,overoll)
if node == nil then
-- Utils.MessageBox("이미지를 로딩할 수 없습니다. \n이미지 이름 : "..path,PROJ_TITLE)
-- if IS_RELEASE == nil then
-- Utils.MessageBox("엔진에 이미지가 정상적으로 포함되어 있다면 '클린 테스트'를 진행해주시기 바랍니다.",PROJ_TITLE)
-- end
return
end
pini:AttachDisplay(node,parent)
end
node:setBlendMode(blendMode)
node:setAnchorPoint(acp[1] or 0.5,1-(acp[2] or 0.5))
node:setScale(StrEnumToScale(node,size))
if x or y then
node:setPosition(x or 0,y or 0)
else
node:setPosition(StrEnumToPos(node,pos))
end
local c = color:explode(",")
if GUI then
node:setZ(9999999)
node.touchPriority = GUI_PRIORITY
end
node:setIncludeScreenShot(screenshot)
node:setColor(tonumber(c[1] or 255),tonumber(c[2] or 255),tonumber(c[3] or 255))
node:setOpacity(tonumber(opacity or 255))
node:setFlip(flipX,flipY)
node:setPreserve(isPreserve)
node:setRotate(angle)
if not OnPreview then
if enableAnti then
node.node:getTexture():setAntiAliasTexParameters()
else
node.node:getTexture():setAliasTexParameters()
end
end
if type(connect)=="string" and connect:len() > 0 then
node.connect = connect
node.onTouchUp = function(location,self)
node = pini:FindNode(self.id)
if node == nil or node.type ~= "Sprite" then
else
pini.XVM:GotoBookmarkNewCall(self.connect)
end
end
pini.TouchManager:registNode(node)
end
if effect:len() > 0 then
if fs_imageEffect[effect] then
fs_imageEffect[effect](node,effectSec)
end
end
end
end
function LNX_TEXT(vm,stck)
local id = vm:ARGU("텍스트","아이디","")
local text1 = vm:ARGU("텍스트","텍스트","")
local text2 = vm:ARGU("텍스트","내용","")
local pos = vm:ARGU("텍스트","위치","화면중앙")
local effect = vm:ARGU("텍스트","효과","")
local effectSec = vm:ARGU("텍스트","효과시간",0)
local font = vm:ARGU("텍스트","글꼴","NanumBarunGothic.ttf")
local size = vm:ARGU("텍스트","크기",20)
local color = vm:ARGU("텍스트","색상","255,255,255")
local opacity = vm:ARGU("텍스트","투명도","255")
local parent = vm:ARGU("텍스트","부모","")
local screenshot = vm:ARGU("텍스트","스크린샷노출","예")
local GUI = vm:ARGU("텍스트","GUI","아니오")
local align = vm:ARGU("텍스트","정렬","중앙")
local x = vm:ARGU("텍스트","x","")
local y = vm:ARGU("텍스트","y","")
local flip = vm:ARGU("텍스트","반전","")
local isPreserve = vm:ARGU("텍스트","항상표시","아니오")
local outline = vm:ARGU("텍스트","외곽선",nil)--"r,g,b,a,w"
local shadow = vm:ARGU("텍스트","그림자",nil)--"r,g,b,a,x,y,w"
local glow = vm:ARGU("텍스트","글로우",nil) -- "r,g,b,a"
--local blendMode = vm:ARGU("텍스트","색상모드","기본")
--텍스트인자를 "내용"으로 바꾸려고하니 기존에 "텍스트"로 작업했던 사람들을 위한 하위호환
text1 = tostring(text1)
text2 = tostring(text2)
local text = text1
if text2 and text2:len() > 0 then
text = text2
end
x = tonumber(x)
y = tonumber(y)
GUI = GUI=="예"
screenshot = screenshot=="예"
isPreserve = isPreserve=="예"
local flipX = false
local flipY = false
if flip == "좌우" then
flipX = true
elseif flip == "상하" then
flipY = true
elseif flip == "상하좌우" then
flipX = true
flipY = true
end
text = tostring(text)
if text:len() > 0 then
local node = pini.Label(id,text,font,size)
local c = color:explode(",")
node:setColor(tonumber(c[1] or 255),tonumber(c[2] or 255),tonumber(c[3] or 255))
node:setOpacity(tonumber(opacity or 255))
node:setFlip(flipX,flipY)
if x or y then
node:setPosition(x or 0,y or 0)
else
node:setPosition(StrEnumToPos(node,pos))
end
if align == "왼쪽" then
node:setAnchorPoint(0,0.5)
elseif align == "중앙" then
node:setAnchorPoint(0.5,0.5)
elseif align == "오른쪽" then
node:setAnchorPoint(1,0.5)
end
if GUI then
node:setZ(9999999)
node.touchPriority = GUI_PRIORITY
end
if outline then
local o = outline:explode(",")
node:setStroke(o[1] or 0,o[2] or 0,o[3] or 0,o[4] or 0,o[5] or 0)
end
if shadow then
local s = shadow:explode(",")
node:setShadow(s[1] or 0,s[2] or 0,s[3] or 0,s[4] or 0,s[5] or 0,-(s[6] or 0),s[7] or 0)
end
if glow then
local g = glow:explode(",")
node:setGlow(g[1] or 0,g[2] or 0,g[3] or 0,g[4] or 0)
end
node:setIncludeScreenShot(screenshot)
node:setPreserve(isPreserve)
pini:AttachDisplay(node,parent)
if effect:len() > 0 then
if fs_imageEffect[effect] then
fs_imageEffect[effect](node,effectSec)
end
end
end
end
function LNX_TEXTINPUT(vm,stck)
local id = vm:ARGU("입력필드","아이디","")
local pos = vm:ARGU("입력필드","위치","화면중앙")
local parent = vm:ARGU("입력필드","부모","")
local x = vm:ARGU("입력필드","x","")
local y = vm:ARGU("입력필드","y","")
local str = vm:ARGU("입력필드","내용","")
local max = vm:ARGU("입력필드","길이제한","0")
local holder = vm:ARGU("입력필드","라벨","무엇을 입력할까요?")
local font = vm:ARGU("입력필드","글꼴","NanumBarunGothic.ttf")
local size = vm:ARGU("입력필드","크기",20)
local password = vm:ARGU("입력필드","패스워드","아니오")
local color = vm:ARGU("입력필드","색상","255,255,255")
local GUI = vm:ARGU("입력필드","GUI","아니오")
GUI = GUI=="예"
x = tonumber(x)
y = tonumber(y)
max = tonumber(max) or 0
password = password == "예"
if max == 0 then
max = nil
end
local node = pini.TextInput(id,holder,str,font,size,GUI)
if x or y then
node:setPosition(x or 0,y or 0)
else
node:setPosition(StrEnumToPos(node,pos))
end
if max then
node:setMaxLength(max)
end
if password then
node:setPasswordMode(password)
end
color = color:explode(",")
node:setColor(color[1] or 0,color[2] or 0,color[3] or 0)
pini:AttachDisplay(node,parent)
end
function LNX_TOINT(vm,stck)
local value = vm:ARGU("수변환","값","")
vm:returnValue(tonumber(value) or 0)
end
function LNX_SLIDERVALUE(vm,stck)
local id = vm:ARGU("슬라이더값","아이디","")
local node = pini:FindNode(id)
if node and node.type=="Slider" then
vm:returnValue(node:getValue())
else
vm:returnValue(0)
end
end
function LNX_SLIDER(vm,stck)
local id = vm:ARGU("슬라이더","아이디","")
local pos = vm:ARGU("슬라이더","위치","화면중앙")
local val = vm:ARGU("슬라이더","값",0)
local read = vm:ARGU("슬라이더","읽기전용","아니오") == "예"
local x = vm:ARGU("슬라이더","x",nil)
local y = vm:ARGU("슬라이더","y",nil)
local img1 = vm:ARGU("슬라이더","빈칸이미지",nil)
local img2 = vm:ARGU("슬라이더","채움이미지",nil)
local img3 = vm:ARGU("슬라이더","앵커이미지",nil)
local parent = vm:ARGU("슬라이더","부모","")
local screenshot = vm:ARGU("슬라이더","스크린샷노출","예")
local GUI = vm:ARGU("슬라이더","GUI","아니오")
x = tonumber(x)
y = tonumber(y)
val = tonumber(val) or 0
id = tostring(id) or ""
if img1 == nil then img1 = "피니/UI/sliderTrack2.png" end
if img2 == nil then img2 = "피니/UI/sliderProgress2.png" end
if img3 == nil then img3 = "피니/UI/sliderThumb.png" end
if id:len() > 0 then
local node = pini.Slider(id,img1,img2,img3)
if node == nil then
Utils.MessageBox("슬라이더를 로딩할 수 없습니다. \n이미지 이름 : "..img1.."\n이미지 이름 : "..img2.."\n이미지 이름 : "..img3,PROJ_TITLE)
if IS_RELEASE == nil then
Utils.MessageBox("엔진에 이미지가 정상적으로 포함되어 있다면 '클린 테스트'를 진행해주시기 바랍니다.",PROJ_TITLE)
end
return
end
node:setValue(val)
pini:AttachDisplay(node,parent)
if read then
node:setEnabled(false)
end
if x or y then
node:setPosition(x or 0,y or 0)
else
node:setPosition(StrEnumToPos(node,pos))
end
node:setIncludeScreenShot(screenshot)
if GUI then
node:setZ(9999999)
node.touchPriority = GUI_PRIORITY
end
end
end
function LNX_GOTOBOOKMARK(vm,stck)
local label = vm:ARGU("북마크이동","북마크","")
if OnPreview then
else
vm:_return()
vm:GotoBookmark(label)
end
end
function LNX_CLEANUP_MEMORY(vm,stck)
if OnPreview then
else
local cache = cc.Director:getInstance():getTextureCache()
if #pini.password == 0 then
cache:removeUnusedTextures()
end
xlsxCache = {}
collectgarbage("collect")
end
end
function LNX_DELDEFAULTARGU(vm,stck)
local macro = vm:ARGU("기본값해제","매크로명","")
local argu = vm:ARGU("기본값해제","인자명","")
_LNXG["___"..macro.."."..argu] = nil
end
function LNX_SETDEFAULTARGU(vm,stck)
local macro = vm:ARGU("기본값","매크로명","")
local argu = vm:ARGU("기본값","인자명","")
local value = vm:ARGU("기본값","값","")
_LNXG["___"..macro.."."..argu] = value
end
function LNX_GET_ENVIRONMENT(vm,stck)
local envType = vm:ARGU("현재환경","종류","")
local targetPlatform = nil
if cc then
targetPlatform = cc.Application:getInstance():getTargetPlatform()
end
if envType == "리모트" then
vm:returnValue(OnPreview and 0 or 1)
elseif envType == "프리뷰" then
vm:returnValue(OnPreview and 1 or 0)
elseif envType == "익스포트" then
vm:returnValue(IS_RELEASE and 1 or 0)
elseif envType == "모바일" then
if targetPlatform then
if targetPlatform == kTargetWindows or targetPlatform == kTargetMacOS then
vm:returnValue(0)
else
vm:returnValue(1)
end
else
vm:returnValue(0)
end
elseif envType == "운영체제" then
local target = "알수없음"
if OnPreview then
target = "윈도우즈"
elseif targetPlatform == kTargetWindows then
target = "윈도우즈"
elseif targetPlatform == kTargetMacOS then
target = "맥OS"
elseif targetPlatform == kTargetAndroid then
target = "안드로이드"
elseif targetPlatform == kTargetIphone or targetPlatform == kTargetIpad then
target = "iOS"
end
vm:returnValue(target)
end
end
function LNX_GET_NODEINFO(vm,stck)
local nodeId = vm:ARGU("노드정보","아이디","")
local _type = vm:ARGU("노드정보","타입","")
local node = pini:FindNode(nodeId)
if node then
local x, y = node:position()
local rot = node:getRotate()
if _type == "X좌표" then
vm:returnValue(x)
elseif _type == "Y좌표" then
vm:returnValue(y)
elseif _type == "회전값" then
vm:returnValue(rot)
end
end
end
function LNX_TOUCHGESTURE(vm,stck)
local id = vm:ARGU("터치제스처","아이디","")
local func = vm:ARGU("터치제스처", "매크로명", "")
pini:scene():registTouchGesture(id,loadstring([[
return function(touchCount,touchType)
local f = "]]..func..[["
_LNXG["터치제스처.터치갯수"] = touchCount
_LNXG["터치제스처.터치타입"] = touchType
pini.XVM:call(f)
end]])())
end
function LNX_REMOVETOUCHGESTURE(vm,stck)
local id = vm:ARGU("터치제스처해제","아이디","")
pini:scene():unregistTouchGesture(id)
end
function LNX_TOUCHAREA(vm,stck)
local id = vm:ARGU("터치영역","아이디","")
local pos = vm:ARGU("터치영역","위치","")
local size = vm:ARGU("터치영역","크기","")
local connect = vm:ARGU("터치영역","북마크이동","")
local x = vm:ARGU("터치영역","x","")
local y = vm:ARGU("터치영역","y","")
local GUI = vm:ARGU("터치영역","GUI","아니오")
GUI = GUI=="예"
x = tonumber(x)
y = tonumber(y)
local op = 0
if OnPreview then
op = 40
end
local s = size:explode(",")
local node = pini.ColorLayer(id,225,30,30,op,s[1] or 0,s[2] or 0)
if x or y then
node:setPosition(x or 0,y or 0)
else
local px,py = unpack(pos:explode(","))
node:setPosition(tonumber(px) or 0,tonumber(py) or 0)
end
node.connect = connect
node.onTouchUp = function(location,self)
pini.XVM:GotoBookmarkNewCall(self.connect)
end
if GUI then
node:setZ(9999999)
node.touchPriority = GUI_PRIORITY
end
pini.TouchManager:registNode(node)
pini:AttachDisplay(node)
end
function LNX_REGIST_VARIABLE_TRIGGER(vm,stck)
local id = vm:ARGU("변수트리거","아이디","")
local variableName = vm:ARGU("변수트리거","변수이름")
local func = vm:ARGU("변수트리거","매크로")
vm:registVariableTrigger(id,variableName,loadstring([[
return function()
local f = "]]..func..[["
local vn = "]]..variableName..[["
pini.Timer(pini:GetUUID(),0,function()
_LNXG["변수트리거.변수이름"] = vn
pini.XVM:call(f)
end,false):run()
end]])())
end
function LNX_UNREGIST_VARIABLE_TRIGGER(vm,stck)
local id = vm:ARGU("변수트리거해제","아이디","")
vm:unregistVariableTrigger(id)
end
function LNX_TEXTINPUT_GET(vm,stck)
local id = vm:ARGU("입력필드가져오기","아이디","")
local node = pini:FindNode(id)
if node then
if node.type == "TextInput" then
vm:returnValue( node:string() )
end
end
end
function LNX_ADS(vm,stck)
local isBanner = vm:ARGU("광고","배너","아니오")
isBanner = isBanner == "예"
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
if isBanner then
DeviceNativeCall("ADS_Banner",{ })
else
DeviceNativeCall("ADS_Fullscreen",{ })
end
end
end
end
function LNX_VUNGLE_INIT(vm, arg)
local appId = vm:ARGU("벙글광고초기화","앱아이디","")
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
DeviceNativeCall("VungleInit", { appId })
end
end
end
function LNX_VUNGLE_SHOW(vm, arg)
local func = vm:ARGU("벙글광고표기", "매크로", "")
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
vm.vungleCallback = func
DeviceNativeCall("VunglePlay", { })
else
_LNXG["벙글광고표기.길이"] = 15.01 -- 고ㅈ값을 리턴합니다.
pini.XVM:call(func)
end
end
end
function LNX_IAP_SETTING(vm, arg)
local publickey = vm:ARGU("결제모듈셋팅","공개키","")
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
print (publickey)
DeviceNativeCall("IAB_Settings",{ publickey })
end
end
end
function LNX_IAP_REQUEST(vm,stck)
local id = vm:ARGU("결제요청","아이템","")
print ("=============0")
vm:returnValue( 0 )
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
if VM_BLOCK_FOR_ANDROID == nil then
print ("=============1")
VM_BLOCK_FOR_ANDROID = vm:stop()
print ("=============2")
DeviceNativeCall("IAB_Buy",{ id })
print ("=============3")
else
print ("LNX_IAP_REQUEST() ignored. because android blocking is progressing")
end
else
end
end
end
function LNX_IAP_CONSUME(vm,stck)
local id = vm:ARGU("결제소비","아이템","")
vm:returnValue( 0 )
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
if VM_BLOCK_FOR_ANDROID == nil then
VM_BLOCK_FOR_ANDROID = vm:stop()
DeviceNativeCall("IAB_Consume",{ id })
else
print ("LNX_IAP_REQUEST() ignored. because android blocking is progressing")
end
else
end
end
end
function LNX_IAP_CHECK(vm, arg)
local id = vm:ARGU("결제확인","아이템","")
vm:returnValue( 0 )
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
if VM_BLOCK_FOR_ANDROID == nil then
VM_BLOCK_FOR_ANDROID = vm:stop()
DeviceNativeCall("IAB_Check",{ id })
else
print ("LNX_IAP_REQUEST() ignored. because android blocking is progressing")
end
else
end
end
end
function LNX_LOCAL_PUSH(vm,stck)
local title = vm:ARGU("로컬푸시","타이틀","")
local text = vm:ARGU("로컬푸시","텍스트","")
local vibrate = vm:ARGU("로컬푸시","진동",0)
local day = vm:ARGU("로컬푸시","일",0)
local hour = vm:ARGU("로컬푸시","시",0)
local min = vm:ARGU("로컬푸시","분",0)
local sec = vm:ARGU("로컬푸시","초",10)
vibrate = tonumber(vibrate) or 0
day = tonumber(day) or 0
hour = tonumber(hour) or 0
min = tonumber(min) or 0
sec = tonumber(sec) or 10
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
DeviceNativeCall("Device_LocalPush",{ title, text, vibrate, day, hour, min, sec })
end
end
end
function LNX_GET_XLSX_DATA(vm,stck)
local path = vm:ARGU("엑셀","파일명")
local sheet = vm:ARGU("엑셀","시트","")
local row = vm:ARGU("엑셀","행","0")
local col = vm:ARGU("엑셀","열","0")
path = tostring(path) or ""
row = tostring(row) or ""
col = tostring(col) or ""
vm:returnValue("")
if path:len() > 0 then
fPath = FILES["etc/"..path]
if fPath then
local path = ROOT_PATH..fPath
if xlsxCache[path] == nil then
local f = io.open(fileUtil:getSuitableFOpen(path), "rb")
if f then
xlsxCache[path] = json.decode(f:read("*all"))
else
xlsxCache[path] = json.decode(fileUtil:getStringFromFile(fPath))
end
end
sheet = tostring(sheet) or ""
data = xlsxCache[path]
if data then
if sheet:len() == 0 then
sheet = data["primary"]
end
if data[sheet] and data[sheet][row] and data[sheet][row][col] then
vm:returnValue(data[sheet][row][col])
end
end
end
end
end
function LNX_FLOOR(vm,stck)
local num = vm:ARGU("소수점버림","수",0)
vm:returnValue(math.floor(num))
end
function LNX_ROUND(vm,stck)
local num = vm:ARGU("반올림","수",0)
vm:returnValue(math.floor(num+0.5))
end
function LNX_VIBRATE(vm,stck)
local sec = vm:ARGU("진동","시간",10)
sec = tonumber(sec) or 10
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
--DeviceNativeCall("Device_Vibrator",{ sec })
end
end
end
function LNX_VALUE_TYPE_CHECK(vm,stck)
local id = vm:ARGU("타입체크","변수명","")
if _LNXG[id] then
if _LNXG[id] == nil then
vm:returnValue( "없음" )
elseif type(_LNXG[id]) == "string" then
vm:returnValue( "문자열" )
elseif type(_LNXG[id]) == "number" then
vm:returnValue( "숫자" )
else
vm:returnValue( "그외" )
end
end
end
function LNX_LOG(vm,stck)
local text = vm:ARGU("로그","텍스트","")
if OnPreview then
-- ENGINE_LOG(text)
else
print(text)
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
DeviceNativeCall("Android_Toast",{ tostring(text) , 1})
end
end
end
function LNX_DELETENODE(vm,stck)
local id = vm:ARGU("삭제","아이디","")
local effect = vm:ARGU("삭제","효과","")
local effectSec = vm:ARGU("삭제","효과시간",0.25)
if id:len() > 0 then
local node = pini:FindNode(id)
if node then
if effect:len() > 0 then
if fs_imageDeleteEffect[effect] then
node:changeId(pini:GetUUID())
fs_imageDeleteEffect[effect](node,effectSec)
pini.Timer(nil,effectSec,function(t)
local node = pini:FindNode(t.userdata.id)
if node then
pini:DetachDisplay(node)
end
end,false,nil,{id=node.id}):run()
local function recursiveEff(node)
local children = node:children()
if children then
for k,v in ipairs(children) do
recursiveEff(v)
fs_imageDeleteEffect["페이드"](v,effectSec)
end
end
end
recursiveEff(node)
end
else
pini:DetachDisplay(node)
end
end
end
end
function LNX_MODAL_NODE(vm,stck)
local id = vm:ARGU("이전터치막기","아이디","")
local touches = pini.Node(id)
touches:setContentSize(99999,99999)
touches.onTouchUp = function(location) end
touches:registOnExit("touch_modal",function(v)
pini:scene():playAllTouchGesture(v.id)
end)
touches.perfectPriority = true
pini.TouchManager:registNode(touches)
pini:AttachDisplay(touches)
pini:scene():pauseAllTouchGesture(id)
end
function LNX_MODAL_KEY(vm,stck)
local id = vm:ARGU("이전키입력막기","아이디","")
local modalkey = pini.Node(id)
modalkey:registOnExit("key_modal",function(v)
pini:scene():playAllKeyboard(v.id)
end)
pini:AttachDisplay(modalkey)
pini:scene():pauseAllKeyboard(id)
end
function build_plaintText_To_extendArgu(_sarg,contents)
local sarg = {}
if #contents > 0 then
for k,v in ipairs(contents:explode("\n")) do
local strs = {}
v:gsub(".",function(c) table.insert(strs,c) end)
local word = ""
local cntUTF = 0
table.insert(sarg,{t=1,v="\n"})
for k,v in ipairs(strs) do
if mode then
word = word..v
if v == ">" then
mode = false
word = word:sub(2,word:len()-1)
local words = word:explode(" ")
local name = words[1]
table.remove(words,1)
local args = words
table.insert(sarg,{t=0,v={name=name,args=args}})
word=""
end
else
if v == "<" and strs[k-1] ~= "<" and strs[k+1] ~= "<" then
table.insert(sarg,{t=1,v=word})
word = "<"
mode = true
else
if string.byte(v) <= 127 then
table.insert(sarg,{t=1,v=v})
else
word = word..v
cntUTF = cntUTF+1
if cntUTF == 3 then
table.insert(sarg,{t=1,v=word})
cntUTF = 0
word = ""
end
end
end
end
end
if word:len() > 0 then
table.insert(sarg,{t=1,v=word})
end
end
end
for k,v in ipairs(_sarg) do
table.insert(sarg,v)
end
return sarg
end
function LNX_MONOLOG(vm,stck)
local forceOn = vm:ARGU("독백","유지","아니오") == "예"
local window = vm:ARGU("독백","대사창","독백")
local contents = vm:ARGU("독백","내용","")
local sec = vm:ARGU("독백","대기시간",0)
local inputwait = vm:ARGU("독백","입력대기","예") == "예"
sec = tonumber(sec) or 0
if sec == 0 then
sec = pini.AutoreadSpeed or 0
end
pini.Dialog:setName(nil)
pini.Dialog:UseConfig(window)
if forceOn == false then
pini.Dialog:Reset()
end
pini.Dialog:WaitConfig(inputwait,sec)
local isAdd = false
local sarg = build_plaintText_To_extendArgu({},contents)
local args_tmp = {}
for k,v in ipairs(sarg) do
if v["t"] == 1 then
table.insert(args_tmp,v["v"])
else
if #args_tmp > 0 then
pini.Dialog:Add(args_tmp)
args_tmp={}
isAdd = true
end
--pini.Dialog:AddMarkup(v)
end
end
if #args_tmp > 0 then
pini.Dialog:Add(args_tmp)
isAdd = true
end
if OnPreview then
else
if isAdd then
pini.Dialog:AddMarkup({name="클릭",args={}})
else
end
end
end
function LNX_DIALOG(vm,stck)
local name = vm:ARGU("대화","이름","")
local forceOn = vm:ARGU("대화","유지","아니오") == "예"
local contents = vm:ARGU("대화","내용","")
local window = vm:ARGU("대화","대사창","대화")
local sec = vm:ARGU("대화","대기시간",0)
local inputwait = vm:ARGU("대화","입력대기","예") == "예"
sec = tonumber(sec) or 0
if sec == 0 then
sec = pini.AutoreadSpeed or 0
end
name = tostring(name)
if name:len() > 0 then
pini.Dialog:setName(name)
else
pini.Dialog:setName(nil)
end
if forceOn == false then
pini.Dialog:Reset()
end
pini.Dialog:UseConfig(window)
pini.Dialog:WaitConfig(inputwait,sec)
local isAdd = false
local sarg = build_plaintText_To_extendArgu({},contents)
local args_tmp = {}
for k,v in ipairs(sarg) do
if v["t"] == 1 then
table.insert(args_tmp,v["v"])
else
if #args_tmp > 0 then
pini.Dialog:Add(args_tmp)
args_tmp={}
isAdd = true
end
--pini.Dialog:AddMarkup(v)
end
end
if #args_tmp > 0 then
pini.Dialog:Add(args_tmp)
isAdd = true
end
if OnPreview then
else
if isAdd then
pini.Dialog:AddMarkup({name="클릭",args={}})
else
end
end
end
function LNX_REMOVEDIALOG(vm,stck)
pini.Dialog:Reset()
end
function LNX_HTTP_REQUEST(vm,stck)
if OnPreview then
vm:returnValue(0)
return
end
--값 = [인터넷연결 주소="" 타입="GET,POST" 인자수="3" 키1="" 값1="" 키2="" 값2="" 키3="" 값3=""]
local request_url = vm:ARGU("인터넷연결","주소")
local request_type = vm:ARGU("인터넷연결","타입")
local request_num = vm:ARGU("인터넷연결","인자수")
local xhr = cc.XMLHttpRequest:new()
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
xhr:open(request_type, request_url)
local arg = "";
for i=1,request_num,1 do
if i > 1 then
arg = arg.."&"
end
local _id = vm:ARGU("인터넷연결","키"..i)
local _val= vm:ARGU("인터넷연결","값"..i)
if _id and _val then
arg = arg.._id..'='..urlencode(_val)
end
end
local callstack = pini.XVM:stop()
local function onReadyStateChange()
if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
local response = xhr.response
vm:returnValue(response)
else
print("xhr.readyState is:", xhr.readyState, "xhr.status is: ",xhr.status)
end
pini.XVM:resume(callstack)
end
xhr:registerScriptHandler(onReadyStateChange)
xhr:send(arg)
end
function LNX_BROWSER_OPEN(vm,stck)
if OnPreview then
return
end
local text = vm:ARGU("브라우저","주소","")
text = tostring(text) or ""
cc.Application:getInstance():openURL(text);
end
function LNX_STRING_SUB(vm,stck)
local text = vm:ARGU("문자열일부","문자열","")
local start = vm:ARGU("문자열일부","시작",0)
local length = vm:ARGU("문자열일부","길이",5)
start = tonumber(start) or 0
length = (tonumber(length) - 1) or 0
text = tostring(text) or ""
vm:returnValue( text:sub(start,start+length) )
end
function LNX_ANIMATION(vm,stck)
local id = vm:ARGU("애니메이션","아이디","")
local t = vm:ARGU("애니메이션","타입","")
if id == "" then
if fs_animation[t] then
local stack
if not OnPreview then
stack = vm:stop()
end
for i,v in pairs(pini._regist_.Display) do
if i:startsWith("PINI") == false then
fs_animation[t][2](vm,v)
v.onAnim = true
end
end
if not OnPreview then
vm:resume(stack)
end
end
else
local node = pini:FindNode(id)
if node and fs_animation[t] then
fs_animation[t][2](vm,node)
node.onAnim = true
end
end
end
function LNX_ANIMATIONSTOP(vm,stck)
local id = vm:ARGU("애니메이션중지","아이디","")
local node = pini:FindNode(id)
if node then
node:StopAction();
AnimMgr:stop(node)
end
end
function LNX_STOP(vm,stck)
if OnPreview then
else
vm:_return()
vm:stop()
end
end
function LNX_WAIT(vm,stck)
if OnPreview then
else
local time = tonumber(vm:ARGU("대기","시간",0))
vm:sleep(time)
end
end
function LNX_ANDROIDSETPUBLICKKEY(vm,stck)
local pkey = vm:ARGU("안드로이드공개키설정","키","")
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
DeviceNativeCall("Extension_SetPublicKey",{pkey})
end
end
end
function LNX_ANDROIDEXTENSION_CHECK(vm,stck)
local isMain = vm:ARGU("확장파일검사","타입","메인") == "메인"
local version = vm:ARGU("확장파일검사","버전","1")
local fileSize = vm:ARGU("확장파일검사","파일크기","0")
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
local _type = "main"
if isMain == false then
_type = "fetch"
end
local ret = DeviceNativeCall("ExtensionFile_IsFileExists",{_type,version,tostring(fileSize)},"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z")
if ret then
vm:returnValue( 1 )
else
vm:returnValue( 0 )
end
end
end
end
function LNX_ANDROIDEXTENSION_DOWNLOAD(vm,stck)
vm:returnValue(1)
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
if VM_BLOCK_FOR_ANDROID == nil then
VM_BLOCK_FOR_ANDROID = vm:stop()
--DeviceNativeCall("Android_Toast",{tostring(VM_BLOCK_FOR_ANDROID),1})
DeviceNativeCall("ExtensionFile_Download",{})
else
print ("LNX_IAP_REQUEST() ignored. because android blocking is progressing")
end
end
end
end
function LNX_ANDROIDEXTENSION_MOUNT(vm,stck)
local isMain = vm:ARGU("확장파일마운트","타입","메인") == "메인"
local version = vm:ARGU("확장파일마운트","버전","1")
if OnPreview then
else
if cc.PLATFORM_OS_ANDROID == CurrentPlatform then
local _type = "main"
if isMain == false then
_type = "fetch"
end
local package = AppPackageName();
local obbpath = OBBDirPath();
print("LNX_ANDROIDEXTENSION_MOUNT >> ",obbpath.."/".._type.."."..version.."."..package..".obb")
table.insert(pini.FindZip,obbpath.."/".._type.."."..version.."."..package..".obb")
--table.insert(pini.FindZip,obbpath.."/extension.prz")
end
end
end
function LNX_CLICKWAIT(vm,stck)
local sec = vm:ARGU("클릭대기","대기시간",0)
sec = tonumber(sec) or 0
if sec == 0 then
sec = pini.AutoreadSpeed or 0
end
if OnPreview ~= true then
callstack = vm:stop()
local node = pini.Node("ClickWait")
node:setContentSize(99999,99999)
node.touchPriority = CLICK_WAIT_PRIORITY
node.callstack = callstack
node.onTouchUp = function(pos,v)
pini:DetachDisplay(v)
pini.XVM:resume(v.callstack)
end
pini.TouchManager:registNode(node)
pini:AttachDisplay(node)
if sec > 0 then
pini.Timer("PINI_ClickWait_Update",0,function(t)
t.userdata.endtime = t.userdata.endtime + t.dt
if t.userdata.endtime > t.userdata.waitsec then
pini.XVM:resume(t.userdata.callstack)
end
end,true,nil,{
endtime = 0,
waitsec = sec,
callstack = callstack
}):run()
end
else
end
end
function LNX_SCREENFILTER(vm,stck)
local id = vm:ARGU("필터","아이디","")
local _type = vm:ARGU("필터","타입","좌우")
local sec = vm:ARGU("필터","시간",0)
--local dir = vm:ARGU("필터","방향",0)
--local pwr = vm:ARGU("필터","강도",14.0)
id = tostring(id) or ""
_type = tostring(_type) or ""
sec = tonumber(sec) or 0
if id:len() > 0 and _type:len() > 0 then
if OnPreview then
local node = pini:FindNode(id)
if node then
node:setColor(30,30,255)
node:setOpacity(200)
else
local node = pini.ColorLayer(id,30,30,255,60,WIN_WIDTH,WIN_HEIGHT)
node:setPosition(0,WIN_HEIGHT)
pini:AttachDisplay(node)
end
else
local node = pini:FindNode(id)
if node == nil then
local currentNodeList = {}
for k,v in pairs(pini._regist_.Display) do
if k:startsWith("PINI") == false then
if v:isVisible() then
table.insert(currentNodeList,v.id)
end
end
end
node = pini.RenderTexture( id, WIN_WIDTH, WIN_HEIGHT, currentNodeList )
pini:AttachDisplay(node)
end
local shader = nil
if _type == "블러" then
local dir = vm:ARGU("필터","방향",0)
local pwr = vm:ARGU("필터","강도",14.0)
pwr = (tonumber(pwr) or 14.0)/1000.0
if dir == "상하" then
shader = pini.Shader(pini:GetUUID(),"filter/gaussianblur_v.vsh", "filter/gaussianblur.fsh")
else
shader = pini.Shader(pini:GetUUID(),"filter/gaussianblur_h.vsh", "filter/gaussianblur.fsh")
end
shader:setUniformFloat("power",pwr)
elseif _type == "흑백" then
shader = pini.Shader(pini:GetUUID(),"filter/grayscale.vsh", "filter/grayscale.fsh")
elseif _type == "세피아" then
shader = pini.Shader(pini:GetUUID(),"filter/sepia.vsh", "filter/sepia.fsh")
elseif _type == "모자이크" then
shader = pini.Shader(pini:GetUUID(),"filter/mosaic.vsh", "filter/mosaic.fsh")
shader:setUniformFloat("pixel",0.01);
elseif _type == "펜선" then
shader = pini.Shader(pini:GetUUID(),"filter/line.vsh", "filter/line.fsh")
elseif _type == "LED" then
local num = vm:ARGU("필터","갯수",100)
num = tonumber(num) or 100
shader = pini.Shader(pini:GetUUID(),"filter/led.vsh", "filter/led.fsh")
shader:setUniformFloat("pixelsNum",num)
elseif _type == "빛샘" then
shader = pini.Shader(pini:GetUUID(),"filter/volumetric.vsh", "filter/volumetric.fsh")
elseif _type == "반전" then
shader = pini.Shader(pini:GetUUID(),"filter/reverse.vsh", "filter/reverse.fsh")
elseif _type == "빛번짐" then
local pwr = vm:ARGU("필터","강도",7.0)
shader = pini.Shader(pini:GetUUID(),"filter/bloom.vsh", "filter/bloom.fsh")
shader:setUniformFloat("power",pwr)
elseif _type == "노이즈" then
local num = vm:ARGU("필터","갯수",400.0)
shader = pini.Shader(pini:GetUUID(),"filter/noise.vsh", "filter/noise.fsh")
shader:setUniformFloat("nums",num)
elseif _type == "실루엣" then
local color = vm:ARGU("필터","색상","0,0,0")
color = color:explode(",")
shader = pini.Shader(pini:GetUUID(),"filter/silhouette.vsh", "filter/silhouette.fsh")
shader:setUniformFloat("_r",tonumber(color[1]) or 0)
shader:setUniformFloat("_g",tonumber(color[2]) or 0)
shader:setUniformFloat("_b",tonumber(color[3]) or 0)
end
if shader then
shader:bind(node)
if sec == 0 then
shader:setUniformFloat("threshold",1)
else
pini.Timer(pini:GetUUID(),0,function(t)
t.userdata.delta = t.userdata.delta + t.dt
t.userdata.threshold = t.userdata.delta / t.userdata.max
local shader = pini:FindShader(t.userdata.sid)
if t.userdata.threshold > 1 then
t:stop()
end
shader:setUniformFloat("threshold",t.userdata.threshold)
end,true,nil,{sid=shader.id,threshold=0,delta=0,max=sec}):run()
end
end
end
end
end
function LNX_REMOVESCREENFILTER(vm,stck)
local id = vm:ARGU("필터삭제","아이디","")
local sec = vm:ARGU("필터삭제","시간",0)
sec = tonumber(sec) or 0
local node = pini:FindNode(id)
if node then
if OnPreview then
if node.type == "ColorLayer" then
pini:DetachDisplay(node)
else
node:setColor(255,255,255)
node:setOpacity(255)
end
elseif node.shaderID then
local shader = pini:FindShader(node.shaderID)
if shader then
if sec == 0 then
if node.type == "RenderTexture" then
pini:DetachDisplay(node)
else
local shader = pini.Shader(pini:GetUUID(),"filter/normal.vsh", "filter/normal.fsh")
shader:bind(node)
end
else
pini.Timer(pini:GetUUID(),0,function(t)
t.userdata.delta = t.userdata.delta - t.dt
t.userdata.threshold = t.userdata.delta / t.userdata.max
if t.userdata.threshold < 0 then
t:stop()
local node = pini:FindNode(t.userdata.nid)
if node then
if node.type == "RenderTexture" then
pini:DetachDisplay(node)
else
local shader = pini.Shader(pini:GetUUID(),"filter/normal.vsh", "filter/normal.fsh")
shader:bind(node)
end
return
end
end
local shader = pini:FindShader(t.userdata.sid)
shader:setUniformFloat("threshold",t.userdata.threshold)
end,true,nil,{nid=id,sid=shader.id,threshold=0,delta=sec,max=sec}):run()
end
end
end
end
end
function LNX_PLAYSOUND(vm,stck)
local id = vm:ARGU("효과음","아이디","")
local path = vm:ARGU("효과음","파일명","")
local loop = vm:ARGU("효과음","반복","아니오")
local vol = vm:ARGU("효과음","볼륨","1")
local sec = vm:ARGU("효과음","시간","0")
if id and id:len() <= 0 then
Utils.MessageBox("효과음의 아이디가 지정되지 않았습니다. \n파일명 : "..path,PROJ_TITLE)
return
end
vol = tonumber(vol) or 0
sec = tonumber(sec) or 0
try{
function()
pini:StopSound(id)
end,
catch {function(error)end}
}
pini:PlaySound(id,path,loop=="예",vol)
if sec > 0 then
local step = (vol or 1) / (sec*20)
pini:SoundVolume( 0 , id )
pini.Timer(pini:GetUUID(),0.05,function(t)
pini:SoundVolume( t.userdata.v , t.userdata.id )
t.userdata.v = t.userdata.v + t.userdata.step
end,true,sec*20+1,{v=0,step=step,id=id}):run()
end
end
local bgm_volume = "1"
function LNX_PLAYBGM(vm,stck)
local path = vm:ARGU("배경음","파일명","")
local brep = vm:ARGU("배경음","반복","예")
local vol = vm:ARGU("배경음","볼륨",nil)
local sec = vm:ARGU("배경음","시간","0")
vol = tonumber(vol or bgm_volume)
pini:PlayBGM(path,brep=="예",vol)
sec = tonumber(sec) or 0
if sec > 0 then
local step = (tonumber(vol) or 1) / (sec*20)
pini:SoundVolume( 0 )
pini.Timer(pini:GetUUID(),0.05,function(t)
pini:SoundVolume( t.userdata.v )
t.userdata.v = t.userdata.v + t.userdata.step
end,true,sec*20+1,{v=0,step=step}):run()
end
end
function LNX_CHANGE_BGM_VOLUME(vm,stck)
local vol = vm:ARGU("배경음볼륨","볼륨","1")
local bgm_volume = tonumber(vol) or 1
pini:SoundVolume(bgm_volume)
end
function LNX_STOPBGM(vm,stck)
local sec = vm:ARGU("배경음끄기","시간","0")
if pini._regist_.BGM then
sec = tonumber(sec) or 0
if sec > 0 then
local sid = pini._regist_.BGM[4]
local vol = pini._regist_.BGM[3]
local step = vol / (sec*20)
pini._regist_.BGM = nil
pini:SoundVolume( vol , sid)
pini.Timer(pini:GetUUID(),0.05,function(t)
pini:SoundVolume( t.userdata.v , t.userdata.sid )
t.userdata.v = t.userdata.v - t.userdata.step
if t.userdata.v <= 0 then
pini:StopSound( t.userdata.sid )
end
end,true,sec*20+1,{v=vol,step=step,sid=sid}):run()
else
pini:StopBGM()
end
end
end
function LNX_STOPSOUND(vm,stck)
local id = vm:ARGU("효과음끄기","아이디","")
local sec = vm:ARGU("효과음끄기","시간","0")
if pini._regist_.Sounds[id] then
sec = tonumber(sec) or 0
if sec > 0 then
local step = 1 / (sec*20)
pini:SoundVolume( 1 , id )
pini.Timer(pini:GetUUID(),0.05,function(t)
pini:SoundVolume( t.userdata.v , t.userdata.id )
t.userdata.v = t.userdata.v - t.userdata.step
if t.userdata.v <= 0 then
pini:StopSound( t.userdata.id )
end
end,true,sec*20+1,{v=1,id=id,step=step}):run()
else
pini:StopSound(id)
end
end
end
function LNX_APP_EXIT(vm,stck)
if OnPreview then
else
if vm.VarFlush then
vm.VarFlush()
end
local director = cc.Director:getInstance()
director:endToLua()
end
end
function LNX_TIMER(vm,stck)
local id = vm:ARGU("타이머","아이디","")
local func = vm:ARGU("타이머","매크로")
local sec = vm:ARGU("타이머","시간","1")
local loopCnt = vm:ARGU("타이머","횟수","0")
loopCnt = tonumber(loopCnt)
if loopCnt == 0 then loopCnt = nil end
pini.Timer(id,sec,function(t,dt)
_LNXG["타이머.시간차"] = dt
pini.XVM:call(t.userdata.call)
end,true,loopCnt,{call=func}):run()
end
function LNX_TIMER_EXIT(vm,stck)
local id = vm:ARGU("타이머종료","아이디","")
pini:StopTimer(id)
end
function LNX_SCREENCLEAN(vm,stck)
pini.Dialog:Clear()
pini:ClearNonPreserveDisplay()
pini.Timer(pini:GetUUID(),0,function()
end,false):run()
end
function LNX_GETSET_VARIABLE(vm,stck)
local id = vm:ARGU("변수","아이디","")
local val = vm:ARGU("변수","값")
if val then
if val ~= _LNXG[id] then
-- 값이 바뀔 경우에 한하여 변수트리거를 작동합니다.
-- for k,v in pairs(vm.variableTriggers) do
-- if v and id == v["variableName"] then
-- v["func"]()
-- end
-- end
end
_LNXG[id] = val;
local L_Saved = id:sub(1,1) == "$"
if L_Saved then
vm:VarSave(id, _LNXG[id])
end
end
vm:returnValue( _LNXG[id] or 0 )
end
function LNX_JSON_PARSE(vm,stck)
local jdata = vm:ARGU("제이슨파싱","원문","")
local key = vm:ARGU("제이슨파싱","키","")
local data = json.decode(jdata) or {}
local d = data
if type(data) == "table" then
keys = key:explode("/")
for k,v in ipairs(keys) do
d = d[v]
if d == nil then
d = 0
break
end
end
if type(d) == "table" then
d = "{배열}"
end
end
vm:returnValue(d)
end
function LNX_IMAGE_LOAD(vm,stck)
local path = vm:ARGU("이미지로딩","파일명","")
pini.Sprite(pini:GetUUID(),path,nil,true)
end
function LNX_MOVIE_PLAYER(vm,stck)
local id = vm:ARGU("비디오","아이디","")
local path = vm:ARGU("비디오","파일명","")
local video = pini.VideoPlayer(id,path)
video:setScale(StrEnumToScale(video,"화면맞춤"))
video:setPosition(StrEnumToPos(video,"화면중앙"))
pini:AttachDisplay(video)
video:play()
end
function LNX_CUSTOMANIMATION(vm,stck)
local name = vm:ARGU("사용자애니메이션","이름","")
local dt = vm:ARGU("사용자애니메이션","프레임시간","0.1")
local start = vm:ARGU("사용자애니메이션","시작","0")
local _end = vm:ARGU("사용자애니메이션","끝",nil)
local loopCnt = vm:ARGU("사용자애니메이션","반복","1")
start = tonumber(start)
_end = tonumber(_end)
loopCnt = tonumber(loopCnt)
dt = tonumber(dt)
if loopCnt == 0 then
loopCnt = nil
end
if AnimMgr:isAnim(name) then
local argValues = {}
local macro = "사용자애니메이션."
for k,v in pairs(_LNXGP) do
if k:startsWith(macro) then
if k:startsWith(macro.."노드") == false then
local _k = k:sub(macro:len()+1,macro:len()+k:len());
argValues[_k] = v
end
end
end
local num = AnimMgr:numNode(name)
for i=1,num,1 do
local nodeName = vm:ARGU("사용자애니메이션","노드"..i,"")
local node = pini:FindNode(nodeName)
local args = "";
for k,v in pairs(argValues) do
AnimMgr:registArgument(nodeName,k,v)
--print(k.." : "..v.." / "..type(v))
args = args..k.."="..v.."&"
end
AnimMgr:run(name,i-1,start,_end,dt,loopCnt,node,args)
end
end
end
function LNX_TRANSITION(vm,stck)
local id = vm:ARGU("전환","아이디","")
local sec = vm:ARGU("전환","시간","")
local scale = vm:ARGU("전환","인자이미지","")
local path = vm:ARGU("전환","이미지","")
local size = vm:ARGU("전환","크기","화면맞춤")
-- 화면 전환 효과는 inGame에서만 작동됨
if OnPreview then
pini:ClearNonPreserveDisplay()
local img = pini.Sprite(id,path)
img:setScale(StrEnumToScale(img,size))
img:setPosition(StrEnumToPos(img,"화면중앙"))
pini:AttachDisplay(img)
else
local stackId = vm:stop()
pini:takeScreenShot(function(sprite)
pini.Dialog:Clear()
pini:ClearNonPreserveDisplay()
-- newSprite = pini.Sprite(id,path,nil,true)
sprite.id = id --pini:GetUUID()
sprite.path = path
local img1 = pini.Sprite("transition1",scale,nil,true)
local img2 = pini.Sprite("transition2",path,nil,true)
local ss = img2:contentSize()
local dx,dy = ss.width / WIN_WIDTH ,ss.height / WIN_HEIGHT
local sx,sy = StrEnumToScale(sprite,size)
sprite:setPosition(WIN_WIDTH/2,WIN_HEIGHT/2)
sprite:setAnchorPoint(0.5,0.5)
sprite:setScale(1,1)
--pini:AttachDisplay(newSprite)
pini:AttachDisplay(sprite)
sprite:release()
local shader = pini.Shader(pini:GetUUID(),"transition.vsh", "transition.fsh")
shader:bind(sprite)
shader:setUniformTexture("u_fadetex", img1)
shader:setUniformTexture("u_disttex", img2)
img2:setScale(StrEnumToScale(img2,size))
img2:setPosition(StrEnumToPos(img2,"화면중앙"))
-- newSprite:setScale(img2.scaleX,img2.scaleY)
-- newSprite:setPosition(img2._x,img2._y)
sprite.scaleX = img2.scaleX
sprite.scaleY = img2.scaleY
sprite._x = img2._x
sprite._y = img2._y
pini.Timer(pini:GetUUID(),0,function(t)
if stackId then
vm:resume(stackId)
stackId = nil
end
t.userdata.delta = t.userdata.delta + t.dt
t.userdata.threshold = t.userdata.delta / t.userdata.max
local shader = pini:FindShader(t.userdata.sid)
shader:setUniformFloat("threshold",t.userdata.threshold)
if t.userdata.threshold > 1 then
t:stop()
shader:fin()
-- local toRemove = pini:FindNode(t.userdata.ssId)
-- pini:DetachDisplay(toRemove)
end
end,true,nil,{sid=shader.id,threshold=0,delta=0,max=sec,ssId=sprite.id}):run()
end)
end
end
function LNX_REGIST_KEYBOARD(vm,stck)
local id = vm:ARGU("키입력","아이디","")
local func = vm:ARGU("키입력","매크로")
pini:scene():registKeyboard(id,loadstring([[
return function(press,keyCode,arg,x,y)
local f = "]]..func..[["
_LNXG["키입력.값"] = keyCode
_LNXG["키입력.누름"] = press
_LNXG["키입력.x"] = x
_LNXG["키입력.y"] = y
pini.XVM:call(f)
end]])())
end
function LNX_SAVEVARFLUSH(vm,stck)
if vm.VarFlush then
vm.VarFlush()
end
end
function LNX_UNREGIST_KEYBOARD(vm,stck)
local id = vm:ARGU("키입력해제","아이디","")
pini:scene():unregistKeyboard(id)
end
function LNX_RANDOM(vm,stck)
local min = vm:ARGU("랜덤","시작",0)
local max = vm:ARGU("랜덤","끝",100)
min = tonumber(min)
max = tonumber(max)
if min > max then
min,max = max,min
end
math.random(min,max)
local ret = 0
if min-max == 0 then
ret = min
else
ret = math.random(min,max)
end
_LNXG["랜덤값"] = ret
vm:returnValue(ret)
end
function LNX_VM_CHECKSAVE(vm,stck)
local number = vm:ARGU("저장체크","번호","")
if OnPreview then
else
try{
function()
local savename = tostring(number)
local savepath = ROOT_PATH.."save/"..savename.."/"
if fileUtil:isDirectoryExist(savepath) then
_LNXG["저장체크.결과"] = 1
local _in = io.open(fileUtil:getSuitableFOpen(savepath.."info"), "rb")
if _in then
local info = json.decode(_in:read("*all"))
_in:close()
_LNXG["저장체크.제목"] = info.name
_LNXG["저장체크.타임"] = info.time
_LNXG["저장체크.데이트"] = info.date
print (info.name,info.time,info.date)
else
_LNXG["저장체크.결과"] = 0
end
else
_LNXG["저장체크.결과"] = 0
end
end,
catch {function(error)
_LNXG["저장체크.결과"] = 0
end}
}
vm:returnValue(_LNXG["저장체크.결과"])
end
end
function LNX_VM_LOAD(vm,stck)
local number = vm:ARGU("불러오기","번호","")
if OnPreview then
else
print("****************LNX_VM_LOAD****************")
-- all clear!
pini.Timer(nil,1,function()
vm:init()
pini:Clear()
PiniLib(vm)
pini.Timer(nil,0.5,function()
------------------------------------
-- lxvm_state file : vm state file
-- loops file : vm looping stack file
-- p file : pini object list file
-- info file : info file
-- k0~n file : keyboard event function bytecode file
-- fns0~n file : vm lua function bytecode
-- vtg0~n file : variable trigger function bytecode
-- t0~n file : timer event function bytecode
-- tu0~n file : node touch up function bytecode
-- td0~n file : node touch down function bytecode
-- tg0~n file : touch gesture function bytecode
print ""
print "(Load called clear point)"
print ""
local loadname = tostring(number)
local loadpath = ROOT_PATH.."save/"..loadname.."/"
if not fileUtil:isDirectoryExist(loadpath) then
return
end
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."lxvm_state"), "rb")
local lxvm_state = json.decode(_in:read())
_in:close()
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."loops"), "rb")
local r = json.decode(_in:read())
_in.close()
lxvm_state["loops"] = r
lxvm_state["vtg"] = {}
local next_fns = {}
for k,v in ipairs(lxvm_state["fns"]) do
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."fns"..(k-1)), "rb")
local r = _in:read("*all")
_in:close()
next_fns[v] = r
end
lxvm_state["fns"] = next_fns
for k,v in ipairs(lxvm_state["vtg"]) do
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."vtg"..(k-1)), "rb")
local r = _in:read("*all")
_in:close()
lxvm_state["vtg"][v[1]] = {v[1], v[2], r}
end
------------------------------------------------------------
------------------------------------------------------------
pini.Backlog:clear()
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."dialog"), "rb")
local r = json.decode(_in:read("*all"))
_in:close()
pini.Dialog.configs = r.config
pini.Dialog:setName(r.name)
pini.Dialog:UseConfig(r.window)
local isRun = false
for k,v in pairs(r.showingWords) do
isRun = true
if v[1] == 1 then
pini.Dialog:Add(v[2])
else
pini.Dialog:AddMarkup(v[2])
end
end
local dialogCallstack = r.callstack
local dialogFrameStopCallstack = r.frameStopCallstack
if isRun then
pini.Dialog:run()
end
-------------------------------------------------------------
-------------------------------------------------------------
_in = io.open(fileUtil:getSuitableFOpen(loadpath.."p"), "rb")
ret = json.decode(_in:read())
_in:close()
local bgm = ret["bgm"] or nil
local node = ret["node"] or {}
local sound = ret["sound"] or {}
local timer = ret["timer"] or {}
local keyboard = ret["keyboard"] or {}
local shaders = ret["shader"] or {}
local gestures = ret["gestures"] or {}
pini.SkipAllowStatus = ret["backlogEnabled"]
pini.Backlog:setConfig(ret["backLogConfig"] or {})
pini:StopBGM()
if bgm then
pini:PlayBGM(bgm[1],bgm[2],bgm[3])
end
for k,v in ipairs(sound) do
pini:PlaySound(v[3],v[2],v[4],v[5])
end
local loaded_node = {}
for k,v in ipairs(node) do
local n = pini[v.type]:gen(v)
table.insert(loaded_node,{n,v.parent,n.drawOrder,v.touchRegisted})
if v.touchRegisted then
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."tu"..(k-1)), "rb")
if _in then
n.onTouchUp = loadstring(_in:read("*all"))
_in:close()
else
end
_in = io.open(fileUtil:getSuitableFOpen(loadpath.."td"..(k-1)), "rb")
if _in then
n.onTouchDown = loadstring(_in:read("*all"))
_in:close()
end
_in = io.open(fileUtil:getSuitableFOpen(loadpath.."tm"..(k-1)), "rb")
if _in then
n.onTouchMiss = loadstring(_in:read("*all"))
_in:close()
end
end
local event = v.exitEvent
v.exitEvent = {}
for h,v in ipairs(event) do
if v["3"] == true then
_in = io.open(fileUtil:getSuitableFOpen(loadpath.."exit"..(k-1).."."..(h-1)), "rb")
if _in then
n:registOnExit(v["1"],loadstring(_in:read("*all")))
_in:close()
end
end
end
end
table.sort(loaded_node,function(a,b) return a[3]<b[3] end)
for k,v in ipairs(loaded_node) do
local n = v[1]
local parent = v[2]
if parent.type == "Scene" then
pini:AttachDisplay(n)
else
pini:AttachDisplay(n,parent.id)
end
if v[4] then
pini.TouchManager:registNode(n)
end
end
for k,v in ipairs(timer) do
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."t"..(k-1)), "rb")
local r = _in:read("*all")
_in:close()
local func = loadstring(r)
local t = pini.Timer(v.id,v.time,func,v.loop,v.count,v.userdata)
if v.playing then
t:run()
end
end
for k,v in ipairs(keyboard) do
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."k"..(k-1)), "rb")
local r = _in:read("*all")
_in:close()
pini:scene():registKeyboard(v["id"],loadstring(r),v["arg"],v["stop"])
end
for k,v in ipairs(gestures) do
local _in = io.open(fileUtil:getSuitableFOpen(loadpath.."tg"..(k-1)), "rb")
local r = _in:read("*all")
_in:close()
pini:scene():registTouchGesture(v["id"],loadstring(r),v["stop"])
end
for k,v in ipairs(shaders) do
print(v.id,v.vsh,v.fsh)
local shader = pini.Shader(v.id,v.vsh,v.fsh)
if v.bind then
shader:bind(pini:FindNode(v.bind))
end
for n,u in pairs(v.uniform)do
shader:setUniformFloat(n,u)
end
end
-------------------------------------------------------------
-------------------------------------------------------------
dialogCallstack, dialogFrameStopCallstack = vm:setState(lxvm_state, dialogCallstack, dialogFrameStopCallstack)
pini.Dialog.callstack = dialogCallstack
pini.Dialog.frameStopCallstack = dialogFrameStopCallstack
pini:clearNodePool()
end,false):run()
end,false):run()
vm:stop()
end
end
function LNX_SAVE(vm,stck)
local number = vm:ARGU("저장","번호","")
local name = vm:ARGU("저장","저장제목","")
if OnPreview then
else
if not fileUtil:isDirectoryExist(ROOT_PATH.."save") then
fileUtil:createDirectory(ROOT_PATH.."save")
end
local savename = tostring(number)
local savepath = ROOT_PATH.."save/"..savename.."/"
if not fileUtil:isDirectoryExist(savepath) then
fileUtil:createDirectory(savepath)
end
pini:takeScreenShot(function(sprite)
local state
local stckTransTable
state, stckTransTable = vm:getState()
print (state["loops"])
local info = {}
info["name"] = name
info["date"] = os.date("%Y-%m-%d %X",os.time())
info["time"] = os.time()
local lxvm_states = {}
local out = io.open(fileUtil:getSuitableFOpen(savepath.."loops"), "wb")
out:write(json.encode(state["loops"]))
out:close()
lxvm_states["vg"] = state["vg"]
lxvm_states["bm"] = state["bm"]
local i=0
lxvm_states["fns"] = {}
for k,v in pairs(state["fns"]) do
table.insert(lxvm_states["fns"], k)
local out = io.open(fileUtil:getSuitableFOpen(savepath.."fns"..i), "wb")
out:write(v)
out:close()
i = i+1
end
local i=0
lxvm_states["vtg"] = {}
for k,v in pairs(state["vtg"]) do
table.insert(lxvm_states["vtg"], {v[1], v[2]})
local out = io.open(fileUtil:getSuitableFOpen(savepath.."vtg"..i), "wb")
out:write(v[3])
out:close()
i = i+1
end
local out = io.open(fileUtil:getSuitableFOpen(savepath.."lxvm_state"), "wb")
out:write(json.encode(lxvm_states))
out:close()
out = io.open(fileUtil:getSuitableFOpen(savepath.."info"), "wb")
out:write(json.encode(info))
out:close()
local dialog = {}
dialog["name"] = pini.Dialog.name
dialog["keep"] = pini.Dialog.keepFlag
dialog["window"] = pini.Dialog.configIdx
dialog["config"] = pini.Dialog.configs
dialog["showingWords"] = pini.Dialog.showingWords
if pini.Dialog.showingDelFlag then
dialog["showingWords"] = {}
end
dialog["callstack"] = stckTransTable[pini.Dialog.callstack]
dialog["frameStopCallstack"] = stckTransTable[pini.Dialog.frameStopCallstack]
out = io.open(fileUtil:getSuitableFOpen(savepath.."dialog"), "wb")
out:write(json.encode(dialog))
out:close()
-----------------------------------------------
-----------------------------------------------
local scene = pini:scene()
local keyboards = scene.keyboards
scene.keyboards = {}
local gestures = scene.touchGestures
scene.touchGestures = {}
i=0
local pin = {}
pin["node"] = {}
for k,v in pairs(pini._regist_.Display) do
if v.id:startsWith("PINI") or (v.parent and v.parent.type ~= "Scene" and v.parent.id:startsWith("PINI")) then
else
table.insert(pin["node"],v)
if v.touchRegisted then
if v.onTouchUp then
local out = io.open(fileUtil:getSuitableFOpen(savepath.."tu"..i), "wb")
out:write(string.dump(v.onTouchUp))
out:close()
end
if v.onTouchDown then
local out = io.open(fileUtil:getSuitableFOpen(savepath.."td"..i), "wb")
out:write(string.dump(v.onTouchDown))
out:close()
end
if v.onTouchMiss then
local out = io.open(fileUtil:getSuitableFOpen(savepath.."tm"..i), "wb")
out:write(string.dump(v.onTouchMiss))
out:close()
end
end
local h=0
for k,v in ipairs(v.exitEvent) do
if v[1]:startsWith("PINI") == false then
local out = io.open(fileUtil:getSuitableFOpen(savepath.."exit"..i.."."..h), "wb")
out:write(string.dump(v[2]))
out:close()
v[3] = true
h = h+1
else
v[3] = false
end
end
i=i+1
end
end
i=0
pin["shader"]={}
for k,v in pairs(pini._regist_.Shaders) do
if v.isDestroyed == false then
local data = {
vsh = v.vsh,
fsh = v.fsh,
id = v.id,
uniform = v.uniform
}
if v.bindNode and v.bindNode.isDestroyed == false then
data["bind"] = v.bindNode.id
end
table.insert(pin["shader"],data)
end
end
i=0
pin["timer"]={}
for k,v in pairs(pini._regist_.Timers) do
if v.id:startsWith("PINI") == false then
table.insert(pin["timer"],{
id=v.id ,
time=v.time ,
loop=v.rep,
playing=v.playing,
count=v.count,
userdata=v.userdata
})
local out = io.open(fileUtil:getSuitableFOpen(savepath.."t"..i), "wb")
out:write(string.dump(v.func))
out:close()
i = i+1
end
end
i=0
pin["keyboard"]={}
for k,v in pairs(keyboards) do
if k:startsWith("PINI") then
else
table.insert(pin["keyboard"],{id=k,arg=v["arg"],stop=v["stop"]})
local out = io.open(fileUtil:getSuitableFOpen(savepath.."k"..i), "wb")
out:write(string.dump(v["func"]))
out:close()
i = i+1
end
end
i=0
pin["gestures"]={}
for k,v in pairs(gestures) do
table.insert(pin["gestures"],{id=k,stop=v["stop"]})
local out = io.open(fileUtil:getSuitableFOpen(savepath.."tg"..i), "wb")
out:write(string.dump(v["func"]))
out:close()
i = i+1
end
pin["sound"] = {}
for k,v in pairs(pini._regist_.Sounds) do
local soundState = ccexp.AudioEngine:getState(v[1])
if soundState ~= -1 then
table.insert(pin["sound"],v)
end
end
pin["bgm"] = pini._regist_.BGM
pin["backlogEnabled"] = pini.SkipAllowStatus
pin["backLogConfig"] = pini.Backlog:config()
out = io.open(fileUtil:getSuitableFOpen(savepath.."p"), "wb")
out:write(json.encode(pin))
out:close()
scene.keyboards = keyboards
scene.touchGestures = gestures
end,"save/"..savename.."/screenshot.png")
end
end
function LNX_SAVE_DELETE(vm,stck)
local number = vm:ARGU("저장삭제","번호","")
if OnPreview then
else
if not fileUtil:isDirectoryExist(ROOT_PATH.."save") then
fileUtil:createDirectory(ROOT_PATH.."save")
end
local savename = tostring(number)
local savepath = ROOT_PATH.."save/"..savename.."/"
if fileUtil:isDirectoryExist(savepath) then
fileUtil:removeDirectory(savepath)
end
end
end
function LNX_DATEINFO(vm,stck)
local _type = vm:ARGU("시간정보","타입","")
local ret = 0
if _type == "현재초" then
ret = os.time()
elseif _type == "년월일" then
ret = os.date("%Y-%m-%d",os.time())
elseif _type == "년월일시분초" then
ret = os.date("%Y-%m-%d %X",os.time())
end
vm:returnValue(ret)
end
-- function LNX_RUN_SCRIPT(vm,stck)
-- local fname = vm:ARGU("스크립트","파일명","")
-- local run = vm:ARGU("스크립트","실행","예") == "예"
-- LXVM:OpenLNX(fname)
-- if run then
-- _VM_LOOP_(fname,_LNXF[fname],stck,nil,nil)
-- end
-- end
function LNX_SCREENSHOT(vm,stck)
local filename = vm:ARGU("스크린샷","파일명","")
pini:takeScreenShot(function(sprite)
vm:returnValue(filename)
end,filename)
end
function LNX_FULLSCREENSWITCH(vm,stck)
local isFullScreen = vm:ARGU("전체화면전환","전체화면","")
isFullScreen = isFullScreen == "예"
if OnPreview then
else
vm:SettingSave("fullscreen",isFullScreen)
end
end
function LNX_SKIP_DIALOG(vm,stck)
-- 대사넘김
dialogTouch = pini:FindNode("PINI_Dialog_touch")
if dialogTouch then
dialogTouch.onTouchUp(nil,dialogTouch)
end
clickTouch = pini:FindNode("ClickWait")
if clickTouch then
clickTouch.onTouchUp(nil,clickTouch)
end
end
function LNX_SWITCH_SKIP_ALLOW(vm,stck)
local isAllow = vm:ARGU("빨리감기","허용","예")
isAllow = isAllow == "예"
pini.SkipAllowStatus = isAllow
if not isAllow then
pini:StopTimer("PINI_CtrlSkip")
end
end
function LNX_START_FASTSKIP(vm,stck)
-- 빨리감기시작
pini.Timer("PINI_FastSkip",0,function(t)
t.userdata.dt = t.userdata.dt+t.dt
if t.userdata.dt > 0.075 then
local dialogTouch = pini:FindNode("PINI_Dialog_touch")
if dialogTouch then
dialogTouch.onTouchUp(nil,dialogTouch)
end
local clickTouch = pini:FindNode("ClickWait")
if clickTouch then
clickTouch.onTouchUp(nil,clickTouch)
end
--if clickTouch== nil and dialogTouch == nil then
t.userdata.dt = 0
--end
end
end,true,nil,{dt=0}):run()
end
function LNX_STOP_FASTSKIP(vm,stck)
-- 빨리감기중단
pini:StopTimer("PINI_FastSkip")
end
function LNX_BACKLOG(vm,stck)
local xPos = vm:ARGU("백로그","x","200")
local yPos = vm:ARGU("백로그","y","600")
local contentWidth = vm:ARGU("백로그","너비","400")
xPos = tonumber(xPos) or 200
yPos = tonumber(yPos) or 600
contentWidth = tonumber(contentWidth) or 400
pini.Backlog:show(xPos, yPos, contentWidth)
end
function LNX_BACKLOG_SETTING(vm,stck)
local lineMargin = vm:ARGU("백로그설정","줄간격")
local fontSize = vm:ARGU("백로그설정","폰트크기")
local fontFace = vm:ARGU("백로그설정","폰트")
local fontColor = vm:ARGU("백로그설정","폰트색상")
local logLimit = vm:ARGU("백로그설정","로그갯수")
local namePos = vm:ARGU("백로그설정","이름위치")
local configs = pini.Backlog:config() or {}
if lineMargin then
configs["lineMargin"] = tonumber(lineMargin) or configs["lineMargin"]
end
if fontSize then
configs["fontSize"] = tonumber(fontSize) or configs["fontSize"]
end
if fontFace then
configs["fontName"] = tostring(fontFace) or configs["fontName"]
end
if fontColor then
local s = fontColor:explode(",")
configs["fontColor"] = {
tonumber(s[1] or configs["fontColor"][1]),
tonumber(s[2] or configs["fontColor"][2]),
tonumber(s[3] or configs["fontColor"][3])
}
end
if logLimit then
configs["logLimit"] = tonumber(logLimit) or configs["logLimit"]
end
if namePos then
configs["namePos"] = tonumber(namePos) or configs["namePos"]
end
pini.Backlog:setConfig(configs)
end
function LNX_BACKLOG_HIDE(vm,stck)
-- 백로그숨김
pini.Backlog:hide()
end
function LNX_BACKLOG_CLEAR(vm,stck)
-- 백로그초기화, 지금까지 누적해온
pini.Backlog:clear()
end
function LNX_START_AUTOREAD(vm,stck)
-- 자동읽기시작
local sec = vm:ARGU("자동읽기시작","대기시간",1.0)
sec = tonumber(sec) or 1.0
if sec < 0.1 then
sec = 0.1
end
pini.AutoreadSpeed = sec
clickWaitNode = pini:FindNode("ClickWait")
if clickWaitNode then
clickWaitNode.onTouchUp(nil, clickWaitNode)
end
pini.Dialog:WaitConfig(true,sec)
dialogTouch = pini:FindNode("PINI_Dialog_touch")
if dialogTouch then
dialogTouch.onTouchUp(nil,dialogTouch)
dialogTimer = pini:FindTimer("PINI_Dialog_Update")
if dialogTimer then
dialogTimer.userdata.waitsec = sec
end
end
end
function LNX_STOP_AUTOREAD(vm,stck)
-- 자동읽기중단
pini:StopTimer("PINI_ClickWait_Update")
pini.Dialog:WaitConfig(true,0)
dialogTouch = pini:FindNode("PINI_Dialog_touch")
if dialogTouch then
dialogTimer = pini:FindTimer("PINI_Dialog_Update")
if dialogTimer then
dialogTimer.userdata.waitsec = 0
end
end
pini.AutoreadSpeed = nil
end
function LNX_HIDE_DIALOG(vm,stck)
-- 대사창끄기
if pini.Dialog.background then
pini.Dialog.background:setVisible(false)
end
if pini.Dialog.nameWindow then
pini.Dialog.nameWindow:setVisible(false)
end
end
function LNX_SHOW_DIALOG(vm,stck)
-- 대사창켜기
if pini.Dialog.background then
pini.Dialog.background:setVisible(true)
end
if pini.Dialog.nameWindow then
pini.Dialog.nameWindow:setVisible(true)
end
end
function LNX_DIALOG_CONFIG(vm,stck)
local id = vm:ARGU("대사창수정","아이디")
local margin = vm:ARGU("대사창수정","여백")
local size = vm:ARGU("대사창수정","영역")
local pos = vm:ARGU("대사창수정","위치")
local lineGap = vm:ARGU("대사창수정","행간")
local effect = vm:ARGU("대사창수정","효과")
local effectSec = vm:ARGU("대사창수정","효과시간")
local appearAnimation = vm:ARGU("대사창수정","나타남애니메이션")
local disappearAnimation = vm:ARGU("대사창수정","사라짐애니메이션")
local color = vm:ARGU("대사창수정","색상")
local image = vm:ARGU("대사창수정","이미지")
local fnt = vm:ARGU("대사창수정","폰트")
local fntcolor = vm:ARGU("대사창수정","폰트색상")
local fntsize = vm:ARGU("대사창수정","폰트크기")
local sound = vm:ARGU("대사창수정","효과음")
local textOutline = vm:ARGU("대사창수정","폰트외곽선") --"r,g,b,a,w"
local textShadow = vm:ARGU("대사창수정","폰트그림자") --"r,g,b,a,x,y,w"
local textGlow = vm:ARGU("대사창수정","폰트글로우") -- "r,g,b,a"
local keyName = vm:ARGU("대사창수정","키입력")
local cursorImg = vm:ARGU("대사창수정","커서이미지")
local cursorSize = vm:ARGU("대사창수정","커서크기")
local cursorColor = vm:ARGU("대사창수정","커서색상")
local cursorAnim = vm:ARGU("대사창수정","커서애니메이션")
local namepos = vm:ARGU("대사창수정","이름창위치")
local namesize = vm:ARGU("대사창수정","이름창영역")
local namecolor = vm:ARGU("대사창수정","이름창색상")
local nameimage = vm:ARGU("대사창수정","이름창이미지")
local namefntsize = vm:ARGU("대사창수정","이름창폰트크기")
local namefntcolor = vm:ARGU("대사창수정","이름창폰트색상")
local namefnt = vm:ARGU("대사창수정","이름창폰트")
local nameOutline = vm:ARGU("대사창수정","이름창폰트외곽선") --"r,g,b,a,w"
local nameShadow = vm:ARGU("대사창수정","이름창폰트그림자") --"r,g,b,a,x,y,w"
local nameGlow = vm:ARGU("대사창수정","이름창폰트글로우") -- "r,g,b,a"
local linkImg = vm:ARGU("대사창수정","연결이미지")
local linkColor = vm:ARGU("대사창수정","연결색상")
local linkWidthFit = vm:ARGU("대사창수정","연결넓이맞춤")
local linkSelectImg = vm:ARGU("대사창수정","연결선택시이미지")
local linkSound = vm:ARGU("대사창수정","연결선택효과음")
local textRate = vm:ARGU("대사창수정","시간")
local textAnimation = vm:ARGU("대사창수정","애니메이션")
if id then
local config = pini.Dialog:config(id) or {
x=10,
y=WIN_HEIGHT-10,
width=WIN_WIDTH-20,
height=250,
background_color={60,60,60,122},
text_color={255,255,255,255},
text_rate = 0.08,
text_outline = nil,
text_outglow = nil,
text_shadow = nil,
text_anim="",
effect="",
effectSec=0.25,
appearAnim = "",
disappearAnim = "",
lineGap=0,
keyName=59,
cursor={
width=20,
height=10,
color={255,255,255,255},
sprite=nil,
anim=""
},
name={
x=10,
y=WIN_HEIGHT-270,
background_color={60,60,60,122},
text_color={255,255,255,255},
text_size=30,
text_align="화면중앙",
text_outline = nil,
text_outglow = nil,
text_shadow = nil,
}
}
if pos then
local s = pos:explode(",")
config["x"] = tonumber(s[1] or config["x"])
config["y"] = tonumber(s[2] or config["y"])
end
if size then
local s = size:explode(",")
config["width"] = tonumber(s[1] or config["width"])
config["height"]= tonumber(s[2] or config["height"])
end
if sound then
config["sound"] = sound or ""
end
if keyName then
config["keyName"] = tonumber(keyName) or 59
end
if lineGap then
config["lineGap"] = tonumber(lineGap) or 0
end
if effect then
config["effect"] = tostring(effect) or ""
end
if effectSec then
config["effectSec"] = tonumber(effectSec) or 0.25
end
if appearAnimation then
config["appearAnim"] = tostring(appearAnimation) or ""
end
if disappearAnimation then
config["disappearAnim"] = tostring(disappearAnimation) or ""
end
if color then
local s = color:explode(",")
config["background_color"] = {
tonumber(s[1] or config["background_color"][1]),
tonumber(s[2] or config["background_color"][2]),
tonumber(s[3] or config["background_color"][3]),
tonumber(s[4] or config["background_color"][4])
}
end
if fntcolor then
local s = fntcolor:explode(",")
config["text_color"] = {
tonumber(s[1] or config["text_color"][1]),
tonumber(s[2] or config["text_color"][2]),
tonumber(s[3] or config["text_color"][3]),
tonumber(s[4] or config["text_color"][4])
}
end
if textRate then
if tonumber(textRate) then
config["text_rate"] = tonumber(textRate)
end
end
if textAnimation then
config["text_anim"] = textAnimation
end
if margin then
local s = margin:explode(",")
config["marginX"] = tonumber(s[1] or config["marginX"])
config["marginY"] = tonumber(s[2] or config["marginY"])
end
config["font"] = fnt or config["font"]
config["path"] = image or config["path"]
config["size"] = tonumber(fntsize or config["size"])
if textOutline then
local s = textOutline:explode(",")
config["text_outline"] = {
tonumber(s[1] or 0),
tonumber(s[2] or 0),
tonumber(s[3] or 0),
tonumber(s[4] or 0),
tonumber(s[5] or 0),
}
end
if textGlow then
local s = textGlow:explode(",")
config["text_outglow"] = {
tonumber(s[1] or 0),
tonumber(s[2] or 0),
tonumber(s[3] or 0),
tonumber(s[4] or 0),
}
end
if textShadow then
local s = textShadow:explode(",")
config["text_shadow"] = {
tonumber(s[1] or 0),
tonumber(s[2] or 0),
tonumber(s[3] or 0),
tonumber(s[4] or 0),
tonumber(s[5] or 0),
tonumber(s[6] or 0),
}
end
--------------------------------------------
-- name window!
--------------------------------------------
config["name"] = config["name"] or {}
local nconfig = config["name"]
if namepos then
local s = namepos:explode(",")
nconfig["x"] = tonumber(s[1] or nconfig["x"])
nconfig["y"] = tonumber(s[2] or nconfig["y"])
end
if namesize then
local s = namesize:explode(",")
nconfig["width"] = tonumber(s[1] or nconfig["width"])
nconfig["height"]= tonumber(s[2] or nconfig["height"])
end
if namecolor then
local s = namecolor:explode(",")
nconfig["background_color"] = {
tonumber(s[1] or nconfig["background_color"][1]),
tonumber(s[2] or nconfig["background_color"][2]),
tonumber(s[3] or nconfig["background_color"][3]),
tonumber(s[4] or nconfig["background_color"][4])
}
end
if namefntcolor then
local s = namefntcolor:explode(",")
nconfig["text_color"] = {
tonumber(s[1] or nconfig["text_color"][1]),
tonumber(s[2] or nconfig["text_color"][2]),
tonumber(s[3] or nconfig["text_color"][3]),
tonumber(s[4] or nconfig["text_color"][4])
}
end
if nameOutline then
local s = nameOutline:explode(",")
nconfig["text_outline"] = {
tonumber(s[1] or 0),
tonumber(s[2] or 0),
tonumber(s[3] or 0),
tonumber(s[4] or 0),
tonumber(s[5] or 0),
}
end
if nameGlow then
local s = nameGlow:explode(",")
nconfig["text_outglow"] = {
tonumber(s[1] or 0),
tonumber(s[2] or 0),
tonumber(s[3] or 0),
tonumber(s[4] or 0),
}
end
if nameShadow then
local s = nameShadow:explode(",")
nconfig["text_shadow"] = {
tonumber(s[1] or 0),
tonumber(s[2] or 0),
tonumber(s[3] or 0),
tonumber(s[4] or 0),
tonumber(s[5] or 0),
tonumber(s[6] or 0),
}
end
nconfig["font"] = namefnt or nconfig["font"]
nconfig["path"] = nameimage or nconfig["path"]
nconfig["text_size"] = tonumber(namefntsize or nconfig["text_size"])
--------------------------------------------
--link block
--------------------------------------------
config["linkBlock"] = config["linkBlock"] or {}
bconfig = config["linkBlock"]
if linkColor then
local s = linkColor:explode(",")
bconfig["color"] = {
tonumber(s[1] or bconfig["color"][1]),
tonumber(s[2] or bconfig["color"][2]),
tonumber(s[3] or bconfig["color"][3]),
tonumber(s[4] or bconfig["color"][4])
}
end
if linkWidthFit then
bconfig["fitWidth"] = linkWidthFit == "예"
end
bconfig["select"] = linkSelectImg or bconfig["select"]
bconfig["unselect"] = linkImg or bconfig["unselect"]
bconfig["linkSound"] = linkSound or bconfig["linkSound"]
--------------------------------------------
--cursor
--------------------------------------------
config["cursor"] = config["cursor"] or {}
cconfig = config["cursor"]
cconfig["sprite"] = cursorImg or cconfig["sprite"]
cconfig["anim"] = cursorAnim or cconfig["anim"]
if cursorColor then
local s = cursorColor:explode(",")
cconfig["color"] = {
tonumber(s[1] or cconfig["color"][1]),
tonumber(s[2] or cconfig["color"][2]),
tonumber(s[3] or cconfig["color"][3]),
tonumber(s[4] or cconfig["color"][4])
}
end
if cursorSize then
local s = cursorSize:explode(",")
cconfig["width"] = tonumber(s[1] or cconfig["width"])
cconfig["height"]= tonumber(s[2] or cconfig["height"])
end
pini.Dialog:SetConfig(id,config);
end
end
PiniLib = function()
pini.XVM = LXVM
-- if OnPreview then
-- LanXVM.unuse_goto = true;
-- end
pini.Dialog:SetConfig("독백",{
x=10,
y=WIN_HEIGHT-10,
width=WIN_WIDTH-20,
height=WIN_HEIGHT-20,
background_color={60,60,60,122},
text_color={255,255,255,255},
text_outline = nil,
text_outglow = nil,
text_shadow = nil,
text_rate=0.02,
effect="",
effectSec=0.25,
appearAnim="",
disappearAnim="",
lineGap=0,
keyName=59,
cursor={
width=20,
height=10,
color={255,255,255,255},
sprite=nil,
anim=""
}
--[[,
linkBlock={
color={255,255,255,255},
select="select.png",
unselect="unselect.png",
fitWidth=true,
anim=pini.Anim.Sequence(pini.Anim.FadeTo(0.5,100),pini.Anim.FadeTo(0.5,255))
}]]
})
pini.Dialog:SetConfig("대화",{
x=10,
y=WIN_HEIGHT-10,
width=WIN_WIDTH-20,
height=250,
background_color={60,60,60,122},
text_color={255,255,255,255},
text_outline = nil,
text_outglow = nil,
text_shadow = nil,
-- path="textArea.png",
text_rate=0.02,
effect="",
effectSec=0.25,
appearAnim="",
disappearAnim="",
lineGap=0,
text_anim="",
keyName=59,
cursor={
width=20,
height=10,
color={255,255,255,255},
sprite=nil,
anim=""
},
name={
x=10,
y=WIN_HEIGHT-270,
background_color={60,60,60,122},
text_color={255,255,255,255},
text_size=30,
text_align="화면중앙",
text_outline = nil,
text_outglow = nil,
text_shadow = nil,
}--[[,
linkBlock={
color={255,255,255,60},
select="select.png",
unselect="unselect.png",
fitWidth=false,
anim=pini.Anim.Sequence(pini.Anim.FadeTo(0.5,100),pini.Anim.FadeTo(0.5,255))
}]]
})
pini.Dialog:UseConfig("대화")
--LNX_SCENE_TRANSITION(LanXVM)
pini.Scene()
end
return PiniLib
|
function load_puzzle()
return {
{0,0,0,0,0},
{0,1,1,1,0},
{0,1,1,1,0},
{0,1,1,1,0},
{0,1,1,1,0},
}
end
|
--[[ HEADLESS RSRT DRIVER
Summary:
The headless RSRT driver implements the minimum required functionality to transmit and receive
data on an RSRT bus.
Remarks:
* On any top-level declaration, the "local" keyword can be removed, degrading performance but
decreasing code size.
* All two-letter symbols are only defined once and can therefore be renamed using find and
replace, if necessary.
Version:
2.0.1
]]
-- =======
-- ALIASES
-- =======
--[[
These aliases are required by the driver below. They are used so frequently, that it is worth
turning them into local symbols.
string_filter implements the default filtering algorithm of matching a string against a prefix.
--]]
-- l0, l1 = string.char, string_filter
local l0,l1=string.char,function(s,p)return s:sub(1,#p)==p end
local a0,a1,a2,a3=computer.pullSignal,computer.uptime,component.list,component.proxy
-- =======
-- DEVICES
-- =======
--[[
These symbols must point to proxies of the devices required by the driver.
dA(event: table) is the deffered event handler, which is called whenever an event is pulled that
shall not be handled now. It should either push the event to another queue, or give a negative
acknowledgment, whatever is more appropriate for the use case.
--]]
-- d0, d1 = redstone, modem
-- dA = deffered_event_handler
local d0,d1=a3(a2("red")()),a3(a2("mod")())
local dA=function()end
-- ===========
-- BIT STREAMS
-- ===========
--[[
The following symbols implement a bit reader and writer adapter for byte streams. They share a
global state that must be initialized prior depending on whether reading or writing shall take
place.
Reading:
b0 is a string of bytes to read.
b1 is the current read offset (usually starts at 0).
b2 is the current remaining bit count (usually starts at 0).
b3 is the current byte (usually starts at 0).
ba(count: int) will read the next count bits into an integer. If more bits are requested than
are available, the result will be zero-padded.
Writing:
b0 is a table of written bytes a string with length 1.
b1 is the current write offset (usually starts at 0).
b2 is the current bit count (usually starts at 0).
b3 is the current byte (usually starts at 0).
bb(x: int, count: int) will write count bits from x, starting from msb.
It is advisable to flush after writing all bits, using bb(0,8-b2). This will pad with zeroes.
After that, the written byte string can be obtained using table.concat(b0).
--]]
-- b0, b1, b2, b3 = <read: string; write: array>, offset, bits, current
-- ba, bb = bit_read(count), bit_write(x, count)
local b0,b1,b2,b3
local ba,bb=function(c)local x=0 while c>0 do if b2==0then b1,b2,b3=b1+1,7,b1<#b0 and b0:byte(b1+1)or 0 else b2=b2-1 end x,c=x<<1|b3>>b2&1,c-1 end return x end,function(x,c)c=c-1while c>=0 do b3,b2,c=b3<<1|x>>c&1,b2+1,c-1if b2==8then b0[b1+1],b1,b2,b3=l0(b3),b1+1,0,0 end end end
-- ===========
-- RSRT DRIVER
-- ===========
--[[
The following symbols implement the actual headless RSRT driver. All of the symbols above are
required dependencies of this code. Symbols ending in capital letters are configuration vars
that either need to be initialized at runtime, or can be statically replaced with their actual
values when packaging the driver.
rF(busy: int, sending: int) is the busy handler. Whenever the busy state changes, that means
driver code detected or will cause a busy wire, it indicates 1, otherwise 0. The sending bit
indicates whether the driver is curently sending.
The state is not set or reset if the driver is not called!
Receiving:
The external code can await the start of a transmission by waiting for a redstone event to
happen that turns the most significant bit of the first RX channel on. Immediately after, it may
call rh() to receive the data. The result will be the received message, or nil on error. If
the busy state is still set after this call, a timeout occured. Events during receive will be
delegated to the dA handler.
Sending:
rf() must be called to announce the transmission start on the wire. If nil is returned, the wire
is busy. Otherwise the wire was acquired and the transmission must start.
rg(message: string) does the transmission after rf() returned non-nil. It returns after the end
of the transmission, and will delegate events to the dA handler if yield timeout prevention
occurs.
--]]
-- ra, rb, rc, rd, re, rf, rg, rh = upscale, downscale, read, write, yield, begin_tx, tx, rx
-- r0, r1 = in_buffer, out_buffer
-- rA, rB, rC, rD, rE, rF = timeout, priority, rx_side, tx_side, channels, busy_handler
local ra,rb,r0,r1,rA,rB,rC,rD,rE,rF=function(x)return x*17 end,function(x)return math.ceil(x/17)end,{[0]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},{[0]=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
local rc,rd=function()local t,i,c=d0.getBundledInput(rC)r0[0]=0 for i=rE,1,-1 do t[i-1]=rb(t[i-1])r0[0],r0[i],c=r0[0]|t[i-1],t[i-1],c or r0[i]~=t[i-1]end return c end,function(x)local i for i=1,rE do r1[i-1]=ra(x[i]or 0)end d0.setBundledOutput(rD,r1)end
local re,rf,rg=function()local t,s=a1(),{a0(rA)}while true do if#s==0or a1()-t>rA then return nil end if l1(s[1],"red")and s[3]==rC and s[6]<rE then if rc()then return true end else dA(s)end s={a0(rA)}end end,function()local d,i={}rc()if r0[0]~=0then rF(1,0)return nil end d[1]=8|rB for i=2,rE do d[i]=0 end rF(1,1)rd(d)rc()if r0[1]~=d[1]then rF(1,0)rd({})return nil end return true end,function(s)b0,b1,b2,b3=l0(#s)..s,0,0,0local d,x,c,t,i,s={},0,0,a1()while b1<#b0 do x,d[1]=0,c|ba(3)for i=2,rE do d[i]=ba(4)x=x|d[i]end if x|d[1]==0then for i=1,rE do d[i]=rb(r1[i-1])end d[1]=d[1]~1 else c=c~8 end rd(d)if a1()-t>=4.8then t,s=a1(),{a0(0)}while#s>0 do dA(s)s={a0(0)}end end end rd({})rF(0,0)rc()end
local rh=function()b0,b1,b2,b3={},0,0,0local c,i=0while true do if not re()then return nil end if r0[0]==0then break end if c~=r0[1]&8then bb(0,rE*4-1)else c=c~8 bb(r0[1]&7,3)for i=2,rE do bb(r0[i],4)end end end bb(0,8-b2)rF(0,0)b0=table.concat(b0)return#b0>b0:byte(1)and b0:sub(2,1+b0:byte(1))end
|
-- Internal custom properties
local PANEL = script:GetCustomProperty("Panel"):WaitForObject()
local DIALOG_TEXT = script:GetCustomProperty("Text"):WaitForObject()
local BACKGROUND = script:GetCustomProperty("Background"):WaitForObject()
-- Constants
local TEXT_LETTER_COLUMN_SIZE = DIALOG_TEXT.fontSize / 2
local TEXT_LETTER_ROW_SIZE = DIALOG_TEXT.fontSize * 2
local ORIGINAL_HEIGHT = PANEL.height
local LOCAL_PLAYER = Game.GetLocalPlayer()
-- Internal variables
local lastTime = time()
local lifespan = 3
local offset = 140
local offsetMounted = 160
local maxDistance = 6000
local player = nil
local isSetup = false
function ResizePanelBasedOnText(text)
local length = string.len(text)
local width = PANEL.width + DIALOG_TEXT.width
local column = width / TEXT_LETTER_COLUMN_SIZE
local row = math.ceil(length / column)
PANEL.height = row * TEXT_LETTER_ROW_SIZE - DIALOG_TEXT.height
end
function IsChatVisible(player)
if player == LOCAL_PLAYER then
return true
end
if player.isDead then
return false
end
local distance = (player:GetWorldPosition() - LOCAL_PLAYER:GetWorldPosition()).size
if distance <= maxDistance then
return true
end
return false
end
function Tick()
if not Object.IsValid(PANEL) then return end
if not Object.IsValid(player) then
if isSetup then
PANEL:Destroy()
end
return
end
local posOffset = offset
if player.isMounted then
posOffset = offsetMounted
end
local playerPos = UI.GetScreenPosition(player:GetWorldPosition() + Vector3.UP * posOffset)
if playerPos and IsChatVisible(player) then
PANEL.visibility = Visibility.INHERIT
PANEL.x = playerPos.x
PANEL.y = playerPos.y
else
PANEL.visibility = Visibility.FORCE_OFF
end
if time() - lastTime > lifespan then
PANEL:Destroy()
end
end
-- Setup
while not player do
player = PANEL.clientUserData.player
Task.Wait()
end
DIALOG_TEXT.text = PANEL.clientUserData.message
ResizePanelBasedOnText(PANEL.clientUserData.message)
if PANEL.clientUserData.color then
BACKGROUND:SetColor(PANEL.clientUserData.color)
BACKGROUND:GetChildren()[1]:SetColor(PANEL.clientUserData.color)
end
isSetup = true
PANEL.visibility = Visibility.INHERIT
|
-- Networking [Server]
-- Kenji
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local networkImplEvent = Instance.new("RemoteEvent")
networkImplEvent.Name = "network"
networkImplEvent.Parent = ReplicatedStorage.kenji
local Networking = {}
local exports = {}
local WEAK_MT = setmetatable({}, {__mode = "k"})
networkImplEvent.OnServerEvent:Connect(function(p, provider, key, ...)
local getProvider = exports[provider]
local getCB = if getProvider then getProvider[key] else nil
if getCB then
local worked, varargs = getCB(p, ...)
if worked == nil then worked = true end
if p then
networkImplEvent:FireClient(p, worked, unpack(varargs or {}))
end
end
end)
local lastNetworkingTable
function Networking.new(container)
-- Networking is actually a singleton because it just fires off a remote event
-- However, we will follow design principles of Kenji here to still ensure
-- better encapsulation
local network = {}
local networkPrivate = {}
networkPrivate.Container = container
function network:FireClient(...)
networkImplEvent:FireClient(...)
end
function network:Export(key, func)
local PRIVATE = WEAK_MT[self]
local container = PRIVATE.Container
local getProvider = exports[container.Name]
if not getProvider then
getProvider = {}
exports[container.Name] = getProvider
end
getProvider[key] = func
end
WEAK_MT[network] = networkPrivate
return network
end
print("Loaded Networking")
return Networking
|
local package, insert, getfenv, require, setmetatable, assert, setfenv, unpack, loadstring, create, resume = package, table.insert, getfenv, require, setmetatable, assert, setfenv, unpack, loadstring, coroutine.create, coroutine.resume;
local supported_files = {'lua'};
local preload, loaded, split, getSplitter = package.preload, package.loaded, function(s, spl)
local result = {};
for str in (s..spl):gmatch('(.-)'..spl) do
insert(result, str);
end;
return result;
end, function(s)
return ((s:find('/') ~= nil) and '/') or ((s:find('\\') ~= nil) and '\\') or '/';
end;
local getName, getExtension = function(path)
return path:match('^.+'..getSplitter(path)..'(.+)$');
end, function(path)
return path:match'^.+(%..+)$';
end;
local c_env, c_require, c_loadstring = getfenv(), require, loadstring;
local bundle = require'luvi'.bundle;
local local_path = args[0];
local name, extension = getName(local_path), getExtension(local_path);
local compiler = ((name == 'luvit.exe') and 0) or ((name == 'luvi.exe') and 1) or ((extension == '.exe') and 2) or 3;
local read = ((compiler == 0) and require'fs'.readFileSync) or ((compiler >= 1) and bundle.readfile);
local stat = ((compiler == 0) and require'fs'.statSync) or ((compiler >= 1) and bundle.stat);
local new_env = function()
local env = {};
for i, v in next, _G do
if (type(v) == 'function') then
local success, result = pcall(setfenv, v, env);
if (success == true) then
v = result;
end;
end;
env[i] = v;
end;
return env;
end;
--environments created via loadstring do not have metatables but ones created from a compiler do
--the loadstring environments created are exactly the same in the same environment
local internal_generator_source = [=[
local generator, loadstring, direct, splitter, read, stat, extend_env, c_require, loaded, preload = ...;
local customRequire = function(libName)
if (loaded[libName] ~= nil) then
return loaded[libName];
elseif (preload[libName] ~= nil) then
return preload[libName]();
end;
local c_env = getfenv();
local limport_data = c_env.limport_data;
local directors = {limport_data.cd; direct..splitter..'libs'; direct;};
for i = 1, #directors do
local pathFile = directors[i]..splitter..libName;
local pathExtension = pathFile..'.lua';
local stats = stat(pathExtension);
if (stats ~= nil) then
local body = assert(read(pathExtension));
local convert = assert(loadstring(body));
local ls_env = getfenv(convert);
local ex_ls_env = extend_env(ls_env, limport_data.global_env, c_env);
ex_ls_env.limport_data = {
ls_env = ls_env;
global_env = limport_data.global_env;
parent_env = c_env;
cd = pathFile;
};
local new_require = generator(direct, splitter, read, stat, extend_env, c_require, loaded, preload);
ex_ls_env.require = setfenv(new_require, ex_ls_env);
local result = {setfenv(convert, ex_ls_env)()};
loaded[libName] = unpack(result);
return unpack(result);
end;
end;
return c_require(libName);
end;
return customRequire;]=];
local loadstring = function(...)
return setfenv(c_loadstring(...), new_env());
end;
local extend_env = function(loadstring_env, global_env, parent_env)
local index = function(self, index)
local global_result = global_env[index];
if (global_result == nil) then
return parent_env[index];
end;
return global_result;
end;
local meta = {__index = index; __newindex = function(self, index, value)
global_env[index] = value;
end};
return setmetatable(loadstring_env, meta);
end;
local generator; generator = function(direct, splitter, read, stat, extend_env, c_require, loaded, preload)
return loadstring(internal_generator_source)(generator, loadstring, direct, splitter, read, stat, extend_env, c_require, loaded, preload);
end;
local singleImport = function(libraryName)
--We want to be able to import entire libraries and single files
local splitter = getSplitter(libraryName);
local all = split(libraryName, splitter);
local isMulti = #all > 1;
if (isMulti == true) then --stuff like
--'ekidona/libs/class' needs to inherit the environment of 'ekidona' in one way or another
--'ekidona/libs/class.lua' needs to be compatiable
--'ekidona/package' and 'ekidona/package.lua' also needs to be compatiable with inheriting 'ekidona's environment
--import names should only accept true pathing
--because import affects the main thread that required the module we need to adjust preload still
local direct = all[#all];
local hasExtension = direct:find('%.') ~= nil;
if (hasExtension == true) then
--Library Names must direct to the actual directory, no fake directories or short hand notations
local stats = stat(libraryName);
if (stats ~= nil and stats.type == 'file') then
--I decided to just say fuck inheriting environments of their respective libraries if you want the library just require it
local extension = getExtension(direct);
local paths = {libraryName, libraryName:gsub(extension, ''), direct, direct:gsub(extension, '')};
local loader = function(...)
local body = assert(read(libraryName));
local convert = assert(loadstring(body));
local result = {setfenv(convert, c_env)(...)};
for i = 1, #paths do
loaded[paths[i]] = unpack(result);
end;
return unpack(result);
end;
for i = 1, #paths do
preload[paths[i]] = loader;
end;
--preload[libraryName], preload[libraryName:gsub(extension, '')], preload[direct], preload[direct:gsub(extension, '')] = loader, loader, loader, loader;
end;
elseif (hasExtension == false) then
--Probably a standard directory search to a file maybe or another folder
--ekidona/libs/package, deps/ekidona, deps/ekidona/libs/class, deps/ekidona/libs/package
--package, ekidona, class, package
local stats = stat(libraryName);
if (stats ~= nil and stats.type == 'directory') then
local full_direct = libraryName..splitter..'init.lua';
local stats_i = stat(full_direct);
local paths = {libraryName, direct};
if (stats_i ~= nil and stats_i.type == 'file') then
local customRequire = generator(libraryName, splitter, read, stat, extend_env, c_require, loaded, preload);
local loader = function(...)
local init_body = assert(read(full_direct));
local convert = assert(loadstring(init_body));
local ls_env = getfenv(convert);
local global_env = new_env();
local ex_ls_env = extend_env(ls_env, global_env, c_env);
ex_ls_env.limport_data = {
ls_env = ls_env;
global_env = global_env;
parent_env = c_env;
cd = libraryName;
};
ex_ls_env.require = setfenv(customRequire, ex_ls_env);
local result = {setfenv(convert, ex_ls_env)(...)};
for i = 1, #paths do
loaded[paths[i]] = unpack(result);
end;
return unpack(result);
end;
for i = 1, #paths do
preload[paths[i]] = loader;
end;
else --Init does not exist
local loader = function(...)
for i = 1, #paths do
loaded[paths[i]] = true;
end;
return true;
end;
for i = 1, #paths do
preload[paths[i]] = loader;
end;
end;
else --Probably a file
for i = 1, #supported_files do
local ext = supported_files[i];
local full_direct = libraryName..'.'..ext;
local stats_s = stat(full_direct);
--assert(success_s and stat_type_s == 'directory', 'Impossible path for second check');
if (stats_s ~= nil and stats_s.type == 'file') then
local paths = {libraryName, full_direct, direct, direct..'.'..ext};
local loader = function(...)
local body = assert(read(full_direct));
local convert = assert(loadstring(body));
local result = {setfenv(convert, c_env)(...)};
for e = 1, #paths do
loaded[paths[e]] = unpack(result);
end;
return unpack(result);
end;
for e = 1, #paths do
preload[paths[e]] = loader;
end;
break;
end;
end;
end;
end;
elseif (isMulti == false) then --stuff like 'ekidona'
local direct = all[1];
local hasExtension = direct:find('%.') ~= nil;
if (hasExtension == true) then
--'ekidona.lua', must be a file
local extension = getExtension(direct);
local no_extension = direct:gsub(extension, '');
local paths = {direct, no_extension};
local loader = function(...)
local body = assert(read(direct));
local convert = assert(loadstring(body));
local result = {setfenv(convert, c_env)(...)};
for i = 1, #paths do
loaded[paths[i]] = unpack(result);
end;
return unpack(result);
end;
for i = 1, #paths do
preload[paths[i]] = loader;
end;
elseif (hasExtension == false) then
--'ekidona', could be a directory or a file
local stats = stat(direct);
--stat requires file extension for file types
--assert(success and stat_type == 'file', 'Impossible path');
if (stats ~= nil and stats.type == 'directory') then
local full_direct = direct..splitter..'init.lua';
local stats_i = stat(full_direct);
if (stats_i ~= nil and stats_i.type == 'file') then --Init exists
local customRequire = generator(direct, splitter, read, stat, extend_env, c_require, loaded, preload);
preload[direct] = function(...)
local init_body = assert(read(full_direct));
local convert = assert(loadstring(init_body));
local ls_env = getfenv(convert);
local global_env = new_env();
local ex_ls_env = extend_env(ls_env, global_env, c_env);
ex_ls_env.limport_data = {
ls_env = ls_env;
global_env = global_env;
parent_env = c_env;
cd = direct;
};
ex_ls_env.require = setfenv(customRequire, ex_ls_env);
return setfenv(convert, ex_ls_env)(...);
end;
else --Init does not exist
preload[direct] = function(...)
return true;
end;
end;
else --We have to check for supported file extensions, must check if is a file
for i = 1, #supported_files do
local ext = supported_files[i];
local full_direct = direct..'.'..ext;
local stats_s = stat(full_direct);
--assert(success_s and stat_type_s == 'directory', 'Impossible path for second check');
if (stats_s ~= nil and stats_s.type == 'file') then
local paths = {direct, full_direct};
local loader = function(...)
local body = assert(read(full_direct));
local convert = assert(loadstring(body));
local result = {setfenv(convert, c_env)(...)};
for e = 1, #paths do
loaded[paths[e]] = unpack(result);
end;
return unpack(result);
end;
for e = 1, #paths do
preload[paths[e]] = loader;
end;
break;
end;
end;
end;
end;
end;
end;
return function(...)
local list = {...};
for i = 1, #list do
local thread = create(singleImport);
assert(resume(thread, list[i]));
end;
end;
|
--[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
return function(loveframes)
---------- module start ----------
-- multichoice object
local newobject = loveframes.NewObject("multichoice", "loveframes_object_multichoice", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize()
self.type = "multichoice"
self.choice = ""
self.text = "Select an option"
self.width = 200
self.height = 25
self.listpadding = 0
self.listspacing = 0
self.buttonscrollamount = 200
self.mousewheelscrollamount = 1500
self.sortfunc = function(a, b) return a < b end
self.haslist = false
self.dtscrolling = true
self.enabled = true
self.internal = false
self.choices = {}
self.listheight = nil
self:SetDrawFunc()
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local parent = self.parent
local base = loveframes.base
local update = self.Update
self:CheckHover()
-- move to parent if there is a parent
if parent ~= base then
self.x = self.parent.x + self.staticx - (parent.offsetx or 0)
self.y = self.parent.y + self.staticy - (parent.offsety or 0)
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local hover = self.hover
local haslist = self.haslist
local enabled = self.enabled
if hover and not haslist and enabled and button == 1 then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
self.haslist = true
self.list = loveframes.objects["multichoicelist"]:new(self)
self.list:SetState(self.state)
loveframes.downobject = self
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
end
--[[---------------------------------------------------------
- func: AddChoice(choice)
- desc: adds a choice to the current list of choices
--]]---------------------------------------------------------
function newobject:AddChoice(choice)
local choices = self.choices
table.insert(choices, choice)
return self
end
--[[---------------------------------------------------------
- func: RemoveChoice(choice)
- desc: removes the specified choice from the object's
list of choices
--]]---------------------------------------------------------
function newobject:RemoveChoice(choice)
local choices = self.choices
for k, v in ipairs(choices) do
if v == choice then
table.remove(choices, k)
break
end
end
return self
end
--[[---------------------------------------------------------
- func: SetChoice(choice)
- desc: sets the current choice
--]]---------------------------------------------------------
function newobject:SetChoice(choice)
self.choice = choice
return self
end
--[[---------------------------------------------------------
- func: SelectChoice(choice)
- desc: selects a choice
--]]---------------------------------------------------------
function newobject:SelectChoice(choice)
local onchoiceselected = self.OnChoiceSelected
self.choice = choice
if self.list then
self.list:Close()
end
if onchoiceselected then
onchoiceselected(self, choice)
end
return self
end
--[[---------------------------------------------------------
- func: SetListHeight(height)
- desc: sets the height of the list of choices
--]]---------------------------------------------------------
function newobject:SetListHeight(height)
self.listheight = height
return self
end
--[[---------------------------------------------------------
- func: SetPadding(padding)
- desc: sets the padding of the list of choices
--]]---------------------------------------------------------
function newobject:SetPadding(padding)
self.listpadding = padding
return self
end
--[[---------------------------------------------------------
- func: SetSpacing(spacing)
- desc: sets the spacing of the list of choices
--]]---------------------------------------------------------
function newobject:SetSpacing(spacing)
self.listspacing = spacing
return self
end
--[[---------------------------------------------------------
- func: GetValue()
- desc: gets the value (choice) of the object
--]]---------------------------------------------------------
function newobject:GetValue()
return self.choice
end
--[[---------------------------------------------------------
- func: GetChoice()
- desc: gets the current choice (same as get value)
--]]---------------------------------------------------------
function newobject:GetChoice()
return self.choice
end
--[[---------------------------------------------------------
- func: GetChoiceIndex()
- desc: gets the current choice index
--]]---------------------------------------------------------
function newobject:GetChoiceIndex()
local choices = self.choices
for i, v in ipairs(choices) do
if self.choice == v then
return i
end
end
end
--[[---------------------------------------------------------
- func: SetText(text)
- desc: sets the object's text
--]]---------------------------------------------------------
function newobject:SetText(text)
self.text = text
return self
end
--[[---------------------------------------------------------
- func: GetText()
- desc: gets the object's text
--]]---------------------------------------------------------
function newobject:GetText()
return self.text
end
--[[---------------------------------------------------------
- func: SetButtonScrollAmount(speed)
- desc: sets the scroll amount of the object's scrollbar
buttons
--]]---------------------------------------------------------
function newobject:SetButtonScrollAmount(amount)
self.buttonscrollamount = amount
return self
end
--[[---------------------------------------------------------
- func: GetButtonScrollAmount()
- desc: gets the scroll amount of the object's scrollbar
buttons
--]]---------------------------------------------------------
function newobject:GetButtonScrollAmount()
return self.buttonscrollamount
end
--[[---------------------------------------------------------
- func: SetMouseWheelScrollAmount(amount)
- desc: sets the scroll amount of the mouse wheel
--]]---------------------------------------------------------
function newobject:SetMouseWheelScrollAmount(amount)
self.mousewheelscrollamount = amount
return self
end
--[[---------------------------------------------------------
- func: GetMouseWheelScrollAmount()
- desc: gets the scroll amount of the mouse wheel
--]]---------------------------------------------------------
function newobject:GetMouseWheelScrollAmount()
return self.mousewheelscrollamount
end
--[[---------------------------------------------------------
- func: SetDTScrolling(bool)
- desc: sets whether or not the object should use delta
time when scrolling
--]]---------------------------------------------------------
function newobject:SetDTScrolling(bool)
self.dtscrolling = bool
return self
end
--[[---------------------------------------------------------
- func: GetDTScrolling()
- desc: gets whether or not the object should use delta
time when scrolling
--]]---------------------------------------------------------
function newobject:GetDTScrolling()
return self.dtscrolling
end
--[[---------------------------------------------------------
- func: Sort(func)
- desc: sorts the object's choices
--]]---------------------------------------------------------
function newobject:Sort(func)
local default = self.sortfunc
if func then
table.sort(self.choices, func)
else
table.sort(self.choices, default)
end
return self
end
--[[---------------------------------------------------------
- func: SetSortFunction(func)
- desc: sets the object's default sort function
--]]---------------------------------------------------------
function newobject:SetSortFunction(func)
self.sortfunc = func
return self
end
--[[---------------------------------------------------------
- func: GetSortFunction(func)
- desc: gets the object's default sort function
--]]---------------------------------------------------------
function newobject:GetSortFunction()
return self.sortfunc
end
--[[---------------------------------------------------------
- func: Clear()
- desc: removes all choices from the object's list
of choices
--]]---------------------------------------------------------
function newobject:Clear()
self.choices = {}
self.choice = ""
self.text = "Select an option"
return self
end
--[[---------------------------------------------------------
- func: SetClickable(bool)
- desc: sets whether or not the object is enabled
--]]---------------------------------------------------------
function newobject:SetEnabled(bool)
self.enabled = bool
return self
end
--[[---------------------------------------------------------
- func: GetEnabled()
- desc: gets whether or not the object is enabled
--]]---------------------------------------------------------
function newobject:GetEnabled()
return self.enabled
end
---------- module end ----------
end
|
local doc = {}
function doc:newSandbox()
local env = {banana = banana.Clone(banana)}
env.banana.RootNamespace = {}
return env,env.banana
end
function doc:sandboxRunCode(code,env,src)
pcall(function()
local fn = CompileString(code,src)
debug.setfenv(fn,env)
fn(env)
end)
end
function doc:getLineFromString(str,line)
local c_line,capturing = 1,line == 1
local out = ""
for char in str:gmatch("(.)") do
if char == "\n" then
if capturing then
if out:sub(-1,-1) == "\r" then out = out:sub(1,-2) end
return out
else
c_line = c_line + 1
if c_line == line then
capturing = true
end
end
elseif capturing then
out = out..char
end
end
return (str:match("[^\r\n]+$")) or ""
end
function doc:getFileData(func,loc)
local debugInfo = debug.getinfo(func)
if debugInfo.short_src then
local fileContents = file.Read(debugInfo.short_src,loc)
if fileContents then
local comment,idx = {},1
while true do
local lineContents = self:getLineFromString(fileContents,idx)
if lineContents:sub(1,3) ~= "-- " then break end
comment[#comment+1] = lineContents
idx = idx + 1
end
local fileData = {
purpose = "",
author = "",
name = "",
state = 3
}
if #comment > 0 then
for i=1,#comment do
local commentStr = comment[i]
if commentStr:match("-- @author .+") then
fileData.author = commentStr:match("-- @author (.+)")
elseif commentStr:match("-- @purpose .+") then
fileData.purpose = fileData.purpose..(commentStr:match("-- @purpose (.+)"))
elseif commentStr:match("-- @name .+") then
fileData.name = commentStr:match("-- @name (.+)")
elseif commentStr:match("-- @state .+") then
local state = commentStr:match("-- @state (.+)")
if state == "SERVER" then
fileData.state = 0
elseif state == "CLIENT" then
fileData.state = 1
elseif state == "SHARED" then
fileData.state = 2
end
end
end
if fileData.purpose == "" then fileData.purpose = "Unknown." end
if fileData.author == "" then fileData.author = "Unknown." end
if fileData.name == "" then fileData.name = "Unknown." end
return fileData
end
end
end
return {
purpose = "Unknown.",
author = "Unknown.",
name = "Unknown.",
state = 3
}
end
function doc:getFunctionCommentData(func,loc)
local debugInfo = debug.getinfo(func)
if debugInfo.short_src and debugInfo.linedefined then
local fileContents = file.Read(debugInfo.short_src,loc)
if fileContents then
local comment,idx = {},1
while true do
local lineContents = self:getLineFromString(fileContents,debugInfo.linedefined-idx)
if lineContents:sub(1,3) ~= "-- " then break end
comment[idx] = lineContents
idx = idx + 1
end
local commentData = {
description = "",
arguments = {},
returns = {}
}
if #comment > 0 then
for i=1,#comment do
local commentStr = comment[#comment - i + 1]
if commentStr:match("^-- @param%d+%s*.+$") then
local paramID,paramType,paramInfo = commentStr:match("^-- @param(%d+)%s*(%S+)%s*(.*)$")
commentData.arguments[tonumber(paramID)] = {
type = paramType,
paramInfo = paramInfo
}
elseif commentStr:match("^-- @return%d+%s*.+$") then
local paramID,paramType,paramInfo = commentStr:match("^-- @return(%d+)%s*(%S+)%s*(.*)$")
commentData.returns[tonumber(paramID)] = {
type = paramType,
paramInfo = paramInfo
}
elseif commentStr:match("^-- @desc%s*.+$") then
commentData.description = commentData.description..(commentStr:match("^-- @desc%s*(.+)$")).."\n"
end
end
end
if commentData.description == "" then
commentData.description = "No description available."
else
commentData.description = commentData.description:sub(1,-2)
end
if #commentData.arguments == 0 then
commentData.arguments = false
end
if #commentData.returns == 0 then
commentData.returns = false
end
return commentData
end
end
return {
description = "No description available.",
arguments = false,
returns = false
}
end
function doc:DocumentFolder(path,loc)
local env,banana = self:newSandbox()
local function recurseFolder(path,loc) -- ends with /
local files,folders = file.Find(path.."*",loc)
for _,fileName in ipairs(files) do
if fileName:sub(-4,-1) == ".lua" then
self:sandboxRunCode(file.Read(path..fileName,loc),env,path..fileName)
end
end
for _,folderName in ipairs(folders) do
recurseFolder(path..folderName.."/",loc)
end
end
recurseFolder(path,loc)
local methods = {}
local seenClasses = {}
local classes = {}
banana.forEachClass(function(class)
for key,var in pairs(class) do
if type(var) == "function" then
if not (banana.IgnoreKeys[key] or banana.Protected[key]) then
if not seenClasses[class:GetInternalClassName()] then
local fdata = self:getFileData(var,loc)
fdata.class = class:GetInternalClassName()
table.insert(classes,fdata)
seenClasses[class:GetInternalClassName()] = true
end
local cdata = self:getFunctionCommentData(var,loc)
table.insert(methods,{
name = class:GetInternalClassName().."->"..key,
description = cdata.description,
arguments = cdata.arguments,
returns = cdata.returns,
class = class:GetInternalClassName()
})
end
end
end
end)
return methods,classes
end
return doc
|
VSTPlugin = MultiOutUGen:new({name="VSTPlugin"})
local Serverdefault = require"sclua.Server".Server()
-- function takes a string that behaves like a file to be read
local function StrStream(strg)
local strptr = 1
local str = strg
local strfile = {}
function strfile:read(len)
local oldstrptr = strptr
strptr = strptr + len
if oldstrptr > #strg then return nil end
return str:sub(oldstrptr,strptr-1)
end
function strfile:next()
return self:read(1)
end
function strfile:readUpTo(del)
local strin = ""
local char = self:next()
if not char then return nil end
while char and char~=del do
strin = strin .. char
char = self:next()
end
return strin
end
function strfile:prGetLine(skipempty)
while true do
local line = self:readUpTo"\n"
if not line then return nil end
if (not skipempty or #line>0) and line:sub(1)~="#" and line:sub(1)~=";" then return line end
end
end
return strfile
end
local function asArray(o)
if type(o)=="table" then
return o
elseif type(o)=="nil" then
return {}
else
error"asArray not valid"
end
end
function VSTPlugin.ar(input, numOut, bypass, params, id, info, auxInput, numAuxOut)
local flags = 0
input = asArray(input)
auxInput = asArray(auxInput)
params = asArray(params)
assert(#params%2==0,"'params': expecting pairs of param index/name + value")
id = id or "nullid"
numOut = numOut or 1
bypass = bypass or 0
numAuxOut = numAuxOut or 0
info = info or 0
return VSTPlugin:MultiNew(concatTables({2, id, info, numOut, numAuxOut, flags, bypass, #input},
input,#params/2, params, #auxInput, auxInput ))
end
local pluginDict = {}
function VSTPlugin:init( theID, theInfo, numOut, numAuxOut, flags, bypass, numInputs ,... )
if theID~="nullid" then self.id = theID end
if theInfo~= 0 then self.info = theInfo end
self.numInputs = numInputs
local inputArray = {}
if numInputs > 0 then
for i=1,numInputs do
local inp = select(i,...)
assert(inp.calcrate == 2, "input not audio rate!!")
inputArray[#inputArray + 1] = inp
end
end
local offset = numInputs + 1
local paramArray = {}
local numParams = select(offset, ...)
if numParams > 0 then
for i=offset + 1, offset + numParams*2 do
paramArray[#paramArray + 1] = select(i,...)
end
end
offset = offset + 1 + (numParams*2)
local auxInputArray = {}
local numAuxInputs = select(offset, ...)
if numAuxInputs > 0 then
for i= offset + 1, offset + numAuxInputs do
local inp = select(i,...)
assert(inp.calcrate == 2, "input not audio rate!!")
auxInputArray[#auxInputArray + 1] = inp
end
end
for i=1, #paramArray, 2 do
local param, value = paramArray[i], paramArray[i+1]
if type(param)~="number" then
if not self.info then
error("cant get param without info!!")
else
local param1 = info.findParamIndex(param)
if not param1 then error("bad parameter "..param.." for plugin "..info.name) end
paramArray[i] = param1
end
end
end
self.inputs = concatTables({numOut, flags, bypass, numInputs}, inputArray, numAuxInputs, auxInputArray, numParams, paramArray)
return self:initOutputs(numOut)
end
function VSTPlugin.clearMsg(remove)
remove = remove==nil
local remint = remove and 1 or 0
return {'/cmd', '/vst_clear', remint};
end
function VSTPlugin.clear(server, remove)
server = server or require"sclua.Server".Server()
-- clear local plugin dictionary
pluginDict[server] = {}
-- clear server plugin dictionary
--remove=true -> also delete temp file
server:listSendMsg(VSTPlugin.clearMsg(remove));
end
local lpath = require"sc.path"
local function resolvePath(path)
local root, temp;
if lpath.is_windows then
--(thisProcess.platform.name == \windows).if {
-- // replace / with \ because of a bug in PathName
-- path = path.tr($/, $\\);
--};
end
--path = path.standardizePath; // expand ~/
--// other methods don't work for folders...
--[[
PathName(path).isAbsolutePath.not.if {
// resolve relative paths to the currently executing file
root = thisProcess.nowExecutingPath;
root.notNil.if {
temp = root.dirname +/+ path;
// no extension: append VST2 platform extension
(path.find(".vst3").isNil && path.find(platformExtension).isNil).if {
temp = temp ++ platformExtension;
};
File.exists(temp).if { ^temp };
}
// otherwise the path is passed to the UGen which tries
// to resolve it to the standard VST search paths.
};
--]]
--assert(lpath.is_abs(path),"relative path not implemented")
return path;
end
local function makeInfo(key, info)
local f = tonumber(info[11]);
local flags = TA():Fill(8,function(i) return bit.band(1,bit.rshift(f,i-1))> 0 end)-- {arg i; ((f >> i) & 1).asBoolean });
return {
parent= parentInfo,
key= key,
path= info[1],--.asString,
name= info[2],--.asString,
vendor= info[3],--.asString,
category= info[4],--.asString,
version= info[5],--.asString,
id= info[6],--.asInteger,
numInputs= info[7],--.asInteger,
numOutputs= info[8],--.asInteger,
numParameters= info[9],--.asInteger,
numPrograms= tonumber(info[10]),--.asInteger,
hasEditor= flags[1],
isSynth= flags[2],
singlePrecision= flags[3],
doublePrecision= flags[4],
midiInput= flags[5],
midiOutput= flags[6],
sysexInput= flags[7],
sysexOutput= flags[8]
}
end
local function trim(cad)
return cad:gsub("^%s*(.-)%s*$","%1") --remove initial and final spaces
end
local function prParseKeyValuePair(line)
local larr = stsplit(line,"=")
for i,v in ipairs(larr) do larr[i] = trim(v) end
return larr
end
local function hex2int(str)
str = str:upper():reverse()
str = {str:byte(1,#str)}
local sum = 0
for i,v in ipairs(str) do
if v >= 65 then
sum = sum + bit.lshift(v - 55, (i-1)*4)
else
sum = sum + bit.lshift(v - 48, (i-1)*4)
end
end
return sum
end
local function prParseCount(line)
local onset = line:find"="
if not onset then error"plugin info: bad data (expecting 'n=<number>'" end
return tonumber(line:sub(onset+1))
end
local info_meta = {
__index = function(t, i)
if i=="numParameters" then
return #t.parameters
elseif i=="numPrograms" then
return #t.programs
elseif i=="findParamIndex" then
return function(name)
return t.prParamIndexMap[name]
end
end
end
}
local function prParseInfo(stream)
local info = setmetatable({},info_meta)
-- default values:
info.numAuxInputs = 0
info.numAuxOutputs = 0
local line,plugin, n, parameters, indexMap, programs, keys
while true do
line = stream:prGetLine(true);
if not line then error"EOF reached" end
if line == "[plugin]" then plugin = true
elseif line == "[parameters]" then
local name, label
line = stream:prGetLine();
n = prParseCount(line)
parameters = {}
indexMap = {}
for i=1,n do
line = stream:prGetLine();
name, label = unpack(stsplit(line,","))
parameters[i] = {name = trim(name), label = trim(label)}
end
info.parameters = parameters
for i,param in ipairs(parameters) do
indexMap[param.name] = i
end
info.prParamIndexMap = indexMap;
elseif line == "[programs]" then
line = stream:prGetLine();
n = prParseCount(line)
programs = {}
for i=1,n do
local name = stream:prGetLine()
programs[i] = {name = name}
end
info.programs = programs
elseif line == "[keys]" then
line = stream:prGetLine();
n = prParseCount(line)
keys = {}
for i=1,n do keys[i] = stream:prGetLine() end
info.key = keys[1]
return info
else
if not plugin then error"plugin info: bad data (%)" end
local key, value = unpack(prParseKeyValuePair(line));
if key == "path" then info[key]=value
elseif key == "name" then info[key]=value
elseif key == "vendor" then info[key]=value
elseif key == "category" then info[key]=value
elseif key == "version" then info[key]=value
elseif key == "sdkVersion" then info[key]=value
elseif key == "sdkversion" then info[key]=value
elseif key == "id" then info[key]=value
elseif key == "inputs" then info.numInputs=tonumber(value)
elseif key == "outputs" then info.numOutputs=tonumber(value)
elseif key == "auxinputs" then info.numAuxInputs=tonumber(value)
elseif key == "auxoutputs" then info.numAuxOutputs=tonumber(value)
elseif key == "flags" then
local f = hex2int(value)
local flags = {}
for i=0,7 do flags[i] = bit.band(1,bit.rshift(f,i)) end
info.hasEditor = flags[0]>0
info.isSynth = flags[1]>0
info.singlePrecision = flags[2]>0
info.doublePrecision = flags[3]>0
info.midiInput = flags[4]>0
info.midiOutput = flags[5]>0
info.sysexInput = flags[6]>0
info.sysexOutput = flags[7]>0
else
prerror("Bad key",key)
end
end
end
end
--[[
local function parseInfo(str)
local data = stsplit(str,"\t")
local key = data[1]
local info = makeInfo(key,TA(data)(2,12))
local nparam = info.numParameters
info.parameterNames = {}
info.parameterLabels = {}
for i=1,info.numParameters do
local onset = 12 + (i-1)*2
table.insert(info.parameterNames,data[onset])
table.insert(info.parameterLabels,data[onset+1])
end
info.programNames = {}
for i=1,info.numPrograms do
local onset = 12 + (nparam * 2) + i - 1;
table.insert(info.programNames, data[onset])
end
return info
end
--]]
local function prParseIni(stream)
local line = stream:prGetLine(true)
if line~="[plugins]" then error"missisng [plugins] header" end
line = stream:prGetLine(true)
local n = prParseCount(line)
local results = {}
for i=1,n do
results[i] = prParseInfo(stream)
end
return results
end
local function prMakeDest(dest)
if not dest then return -1 end
if type(dest)=="string" then return dest end
if type(dest)=="number" then return dest end
error"Bad dest in prMakeDest"
end
local function searchMsg(dir, useDefault, verbose, save, parallel, dest)
--defaults
useDefault = type(useDefault)==nil and true or useDefault
if verbose==nil then verbose = false end
if save==nil then save = true end
if parallel==nil then parallel = true end
-- bool to int
useDefault = useDefault and 1 or 0
verbose = verbose and 1 or 0
save = save and 1 or 0
parallel = parallel and 1 or 0
local flags = 0
for i,v in ipairs{useDefault, verbose, save, parallel} do
flags = bit.bor(flags, bit.lshift(v,i-1))
end
dir = type(dir)=="string" and {dir} or dir
assert(type(dir)=="table" or type(dir)=="nil", "Bad dir type")
if dir == nil then dir = {} end
for i,v in ipairs(dir) do dir[i] = resolvePath(v) end
dest = prMakeDest(dest)
return concatTables({'/cmd', '/vst_search', flags, dest}, dir)
end
local function searchLocal(server, searchPaths, useDefault, verbose, save, parallel, action)
--forkIfNeeded(function()
local tmpPath = os.tmpname()
server:listSendMsg(searchMsg(dir, useDefault, verbose, save, parallel, tmpPath))
server:sync()
local file,err = io.open(tmpPath,"rb")
assert(file,err)
local str = file:read"*a"
file:close()
local ok,err = os.remove(tmpPath)
if not ok then prerror("could not delete tmp file ",err) end
local strf = StrStream(str)
-- print"----------"
-- print(str)
-- print"-----------"
local res = prParseIni(strf)
local dict = pluginDict[server]
for k,info in pairs(res) do
dict[info.key]=info
end
--end)
--[[
while true do
local line = strf:prGetLine(true)
if not line then break end
print(line)
end
local dict = pluginDict[server]
local infos = stsplit(str,"\n")
for i,line in ipairs(infos) do
if not (line=="") then
local info = parseInfo(line)
dict[info.key] = info
end
end
--]]
end
function VSTPlugin.search(server, dir, useDefault, verbose, wait, action, save, parallel)
server = server or require"sclua.Server".Server()
if useDefault==nil then useDefault = true end
if verbose==nil then verbose = true end
if save==nil then save = true end
if parallel==nil then parallel = true end
wait = wait or -1
pluginDict[server] = pluginDict[server] or {}
searchLocal(server, dir, useDefault, verbose, save, parallel, action)
end
function VSTPlugin.getDict(server)
server = require"sclua.Server".Server()
return pluginDict[server]
end
function VSTPlugin.plugins(server)
server = require"sclua.Server".Server()
return pluginDict[server]
end
function VSTPlugin.pluginList(server, sorted)
local dict = VSTPlugin.plugins(server)
local array = {}
for k,v in pairs(dict) do table.insert(array,v) end
if sorted then
table.sort(array,function(a,b) return a.name < b.name end)
end
return array
end
function VSTPlugin.print(server)
local dict = VSTPlugin.pluginList(server, true)
--prtable(dict)
for k,v in ipairs(dict) do
print(v.key,v.vendor,v.path)
end
end
function VSTPlugin.prGetInfo(server, key, wait, action)
local info
local dict = pluginDict[server];
-- if the key already exists, return the info.
-- otherwise probe the plugin and store it under the given key
--dict !? { info = dict[key] } !? { action.value(info) }
--?? { this.probe(server, key, key, wait, action) };
if dict then
info = dict[key]
action(info)
else
return VSTPlugin.probe(server, key, key, wait, action)
end
end
local function prProbeLocal(server, path, key, action)
local info
local dict = pluginDict[server];
local filePath = os.tmpname()
--local filePath = PathName.tmp ++ this.prUniqueID.asString;
-- ask server to write plugin info to tmp file
server:sendMsg('/cmd', '/vst_query', path, filePath);
-- wait for cmd to finish
server:sync();
-- read file (only written if the plugin could be probed)
if lpath.exists(filePath) then
local file,err = io.open(filePath,"rb")
assert(file,err)
local str = file:read"*a"
file:close()
info = parseInfo(str)
dict[info.key] = info
dict[path] = info
if key then dict[key] = info end
else
error("not existing "..filePath)
end
action(info)
local ok,err = os.remove(filePath)
if not ok then prerror("could not delete tmp file ",err) end
end
function VSTPlugin.probe(server, path, key, wait, action)
wait = wait or -1
server = server or Serverdefault;
-- resolve the path
path = resolvePath(path);
-- add dictionary if it doesn't exist yet
--pluginDict[server].isNil.if { pluginDict[server] = IdentityDictionary.new };
--server.isLocal.if { this.prProbeLocal(server, path, key, action); }
--{ this.prProbeRemote(server, path, key, wait, action); };
pluginDict[server] = pluginDict[server] or {}
prProbeLocal(server, path, key, action)
end
-------------------------------------
VSTPluginController = {}
function VSTPluginController:new(synth, id, synthdef, wait)
local o = {}
setmetatable(o, self)
self.__index = self
for i,ugen in ipairs(synthdef.Allugens) do
if ugen.name == "VSTPlugin" then
if ugen.id==id or id==nil then
o:init(synth, i-1, wait)
end
end
end
return o
end
local function msg2string(msg,offset)
local leng = msg[offset]
local arr = {}
for i=1,leng do table.insert(arr,msg[offset+i]) end
return string.char(unpack(arr))
end
function VSTPluginController:init(synth,theIndex,wait)
self.synth = synth
self.synthIndex = theIndex
self.wait = wait
self.loaded = false
--midi = VSTPluginMIDIProxy(this);
self.oscFuncs = {}
local ofc = self:prMakeOscFunc(function( msg)
local index, value, display;
index = msg[3] --.asInteger;
value = msg[4] --.asFloat;
--(msg.size > 5).if {display = this.class.msg2string(msg, 5);};
if #msg>5 then display = msg2string(msg,5) end
-- cache parameter value
self.paramCache[index] = {value, display};
-- notify dependants
--this.changed('/param', index, value, display);
end, '/vst_param')
table.insert(self.oscFuncs,ofc)
ofc = self:prMakeOscFunc(function(msg)
self.program = msg[3] --.asInteger;
-- notify dependants
--this.changed('/program_index', program);
end, '/vst_program_index')
table.insert(self.oscFuncs,ofc)
ofc = self:prMakeOscFunc(function(msg)
local index, name;
index = msg[3] --.asInteger;
name = msg2string(msg, 4);
self.programNames[index] = name;
-- notify dependants
--this.changed('/program', index, name);
end, '/vst_program')
table.insert(self.oscFuncs,ofc)
ofc = self:prMakeOscFunc(function(msg)
local index, value;
index = msg[3] --.asInteger;
value = msg[4] --.asFloat;
if self.parameterAutomated then
self.parameterAutomated(index, value);
end
end, '/vst_auto')
table.insert(self.oscFuncs,ofc)
ofc = self:prMakeOscFunc(function(msg)
-- convert to integers and pass as args to action
--midiReceived.value(*Int32Array.newFrom(msg[3..]));
assert(false)
end, '/vst_midi')
table.insert(self.oscFuncs,ofc)
ofc = self:prMakeOscFunc(function(msg)
--convert to Int8Array and pass to action
--sysexReceived.value(Int8Array.newFrom(msg[3..]));
assert(false)
end, '/vst_sysex')
table.insert(self.oscFuncs,ofc)
OSCFunc.newfilter("/n_end",self.synth.nodeID,function(msg)
prtable(msg)
self:prFree()
end,true)
end
function VSTPluginController:prFree()
-- "VSTPluginController: synth freed!".postln;
for i,v in ipairs(self.oscFuncs) do
OSCFunc.clearfilters(v.path,v.template,v.handleOSCFuncLinda)
end
self:prClear();
--this.changed('/free');
end
function VSTPluginController:sendMsg(cmd, ...)
self.synth.server:sendMsg('/u_cmd', self.synth.nodeID, self.synthIndex, cmd, ...);
end
function VSTPluginController:Msg(cmd, ...)
return self.synth.server:Msg('/u_cmd', self.synth.nodeID, self.synthIndex, cmd, ...);
end
function VSTPluginController:sendMidi(event)
local type = event.type or 0
local channel = event.channel or 0
local data1 = bit.bor(bit.lshift(bit.band(type , 0xf) , 4) , bit.band(channel , 0xf));
local data2 = event.byte2 or 0
local data3 = event.byte3 or 0
local blob = string.char(data1,data2,data3)
self.synth.server:sendBundle(theMetro:ppq2time(event.delta),self:Msg('/midi_msg', {"blob",blob}))
end
function VSTPluginController:set(...)
self:sendMsg("/set",...)
end
function VSTPluginController:program_(i)
assert(i>=0 and i< self:numPrograms(),"program out of range")
forkIfNeeded(function()
self:sendMsg("/program_set",i)
self.synth.server:sync()
self:prQueryParams();
end)
end
function VSTPluginController:prMakeOscFunc(func, path,runonce)
return OSCFunc.newfilter(path,{self.synth.nodeID,self.synthIndex},function(msg)
--print(prOSC(msg))
func(msg[2])
end,runonce)
end
function VSTPluginController:prClear()
self.loaded = false; self.window = false; self.info = nil; self.paramCache = nil; self.programNames = nil; self.program = nil;
end
function VSTPluginController:editor(show) --{ arg show=true;
if show == nil then show=true end
if not self.window then prerror("no editor!")
else
self:sendMsg('/vis', show and 1 or 0)
end
end
function VSTPluginController:open(path, editor, info, action)
if not path then return self end
VSTPlugin.prGetInfo(self.synth.server, path, wait,function(theInfo)
if not theInfo then
error("could not open "..path)
end
self:prClear()
self:prMakeOscFunc(function(msg)
self.loaded = msg[3] --.asBoolean;
self.window = msg[4] --.asBoolean;
if not self.loaded then error("could not open "..path) end
if not theInfo then error("could not open "..path) end
--this.slotPut('info', theInfo); // hack because of name clash with 'info'
self.info = theInfo
self.paramCache = TA():Fill(theInfo.numParameters, {0, nil});
self.program = 0;
-- copy default program names (might change later when loading banks)
self.programNames = {} --deepcopy(theInfo.programNames);
for i,v in ipairs(theInfo.programs) do
self.programNames[i] = v.name
end
self:prQueryParams();
-- post info if wanted
if info then prtable(theInfo) end
if action then action(self, self.loaded); end
--this.changed('/open', path, loaded);
end, '/vst_open',true) --.oneShot;
-- don't set 'info' property yet
self:sendMsg('/open', theInfo.key, editor and 1 or 0);
end)
end
function VSTPluginController:numPrograms()
return self.info and self.info.numPrograms or 0
end
function VSTPluginController:numParameters()
return self.info and self.info.numParameters or 0
end
function VSTPluginController:prQueryParams(wait)
local inittim = lanes.now_secs()
self:prQuery(wait, self:numParameters(), '/param_query');
print("prQueryParams",lanes.now_secs()-inittim)
end
function VSTPluginController:prQueryPrograms(wait)
self:prQuery(wait, self:numPrograms(), '/program_query');
end
function VSTPluginController:prQuery(wait, num, cmd)
forkIfNeeded(function()
local bsiz = 64 --16
local div, mod;
div = math.floor(num/bsiz);
mod = num%bsiz
wait = wait or self.wait;
-- request bsiz parameters/programs at once
for i=1,div do
self:sendMsg(cmd,(i-1)*bsiz, bsiz)
if wait then
error"dont do that"
wait(wait)
else
self.synth.server:sync(nil,true)
end
end
-- request remaining parameters/programs
if mod > 0 then self:sendMsg(cmd, num - mod, mod) end
end)
end
function VSTPluginController:writeProgram(path, action)
path = resolvePath(path);
self:prMakeOscFunc(function(msg)
local success = msg[3]>0
if action then action(self, success) end
end, '/vst_program_write',true)
self:sendMsg('/program_write', path);
end
function VSTPluginController:readProgram(path, action)
path = resolvePath(path);
self:prMakeOscFunc(function(msg)
local success = msg[3]>0
if action then action(self, success) end
self:prQueryParams()
end, '/vst_program_read',true)
self:sendMsg('/program_read', path);
end
--ddd = "key="
--require"sc.utils"
--eee = stsplit(ddd,"=")
--prtable(eee)
|
ys = ys or {}
slot1 = ys.Battle.BattleResourceManager
ys.Battle.BattleCannonBullet = class("BattleCannonBullet", ys.Battle.BattleBullet)
ys.Battle.BattleCannonBullet.__name = "BattleCannonBullet"
ys.Battle.BattleCannonBullet.Ctor = function (slot0, slot1, slot2)
slot0.Battle.BattleCannonBullet.super.Ctor(slot0, slot1, slot2)
end
return
|
local bzutil = require("__bzcarbon__.data-util");
local util = require("util")
if mods.Krastorio2 then
if bzutil.me.use_fullerenes() then
-- Add extra nanotube recipes.
-- This could be moved to data-updates in future if necessary
data:extend({
{
type = "recipe",
name = "imersium-plate-nanotubes",
icons = {
{ icon = data.raw.item["imersium-plate"].icon, icon_size = data.raw.item["imersium-plate"].icon_size},
{ icon = "__bzcarbon__/graphics/icons/nanotube.png", icon_size = 128, scale=0.125, shift= {-8, -8}},
},
category = "smelting",
subgroup = "raw-material",
order = "e00-a2[imersium-plate]",
enabled = false,
energy_required = 32,
ingredients = {
{"nanotubes", 6},
table.unpack(util.table.deepcopy(data.raw.recipe["imersium-plate"].ingredients)),
},
result = "imersium-plate",
result_count = 6,
},
{
type = "recipe",
name = "imersium-beam-nanotubes",
icons = {
{ icon = data.raw.item["imersium-beam"].icon, icon_size = data.raw.item["imersium-beam"].icon_size},
{ icon = "__bzcarbon__/graphics/icons/nanotube.png", icon_size = 128, scale=0.125, shift= {-8, -8}},
},
category = "smelting-crafting",
subgroup = "smelting-crafting",
order = data.raw.item["imersium-beam"].order.."z",
enabled = false,
energy_required = 12,
ingredients = {
{"nanotubes", 4},
table.unpack(util.table.deepcopy(data.raw.recipe["kr-s-c-imersium-beam"].ingredients)),
},
result = "imersium-beam",
result_count = 2,
},
{
type = "recipe",
name = "imersium-gear-wheel-nanotubes",
icons = {
{ icon = data.raw.item["imersium-gear-wheel"].icon, icon_size = data.raw.item["imersium-gear-wheel"].icon_size},
{ icon = "__bzcarbon__/graphics/icons/nanotube.png", icon_size = 128, scale=0.125, shift= {-8, -8}},
},
category = "smelting-crafting",
subgroup = "smelting-crafting",
order = data.raw.item["imersium-gear-wheel"].order.."z",
enabled = false,
energy_required = 12,
ingredients = {
{"nanotubes", 2},
table.unpack(util.table.deepcopy(data.raw.recipe["kr-s-c-imersium-gear-wheel"].ingredients)),
},
result = "imersium-gear-wheel",
result_count = 2,
},
})
bzutil.add_effect("nanotubes", {type="unlock-recipe", recipe="imersium-plate-nanotubes"})
bzutil.add_effect("nanotubes", {type="unlock-recipe", recipe="imersium-beam-nanotubes"})
bzutil.add_effect("nanotubes", {type="unlock-recipe", recipe="imersium-gear-wheel-nanotubes"})
end
end
|
-----------------------------------
--
-- INHIBIT_TP
-- Reduces TP Gain By a % Factor
--
-----------------------------------
function onEffectGain(target, effect)
target:addMod(tpz.mod.INHIBIT_TP, effect:getPower())
end
function onEffectTick(target, effect)
end
function onEffectLose(target, effect)
target:delMod(tpz.mod.INHIBIT_TP, effect:getPower())
end
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Utilities = ReplicatedStorage.Utilities
local Assert = require(Utilities.Assert)
local Functions = require(Utilities.Functions)
local Music = require(ReplicatedStorage.Music)
local Tutorial = require(ReplicatedStorage.Tutorial)
--local BookPouch = require(ReplicatedStorage.BookPouch)
local Profile = {}
Profile.__index = Profile
local vars = {
Tutorial = Tutorial,
-- field -> Class with .new and .Deserialize (returned value should have :Serialize); may also have .DeserializeDataStore
-- The following capitalized fields are public but should be treated as read-only
Music = Music,
-- BookPouch = BookPouch,
-- favoriteBooks = SaveableSet,
-- readBooks = SaveableSet,
}
function Profile.new()
local self = {}
for k, v in pairs(vars) do
self[k] = v.new()
end
return setmetatable(self, Profile)
end
function Profile:Serialize()
local t = {}
for k, v in pairs(self) do
t[k] = v:Serialize()
end
return t
end
function Profile.Deserialize(profile)
for k, class in pairs(vars) do
local v = profile[k]
if v ~= nil then
profile[k] = class.Deserialize(profile[k])
else
profile[k] = class.new()
end
end
return setmetatable(profile, Profile)
end
function Profile.DeserializeDataStore(profile)
for k, class in pairs(vars) do
profile[k] = (class.DeserializeDataStore or class.Deserialize)(profile[k])
end
return setmetatable(profile, Profile)
end
function Profile:Destroy()
for k, class in pairs(vars) do
local v = self[k]
if v.Destroy then
v:Destroy()
end
end
end
-- for _, var in ipairs({"favoriteBooks", "readBooks"}) do
-- --[[Options...
-- profile.FavoriteBooks...
-- :Contains(bookId)
-- :Add(bookId)
-- :Remove(bookId)
-- :GetList()
-- ]]
-- end
-- function Profile:GetFavoriteBooks()
-- return self.favoriteBooks
-- end
-- function Profile:GetReadBooks()
-- return self.readBooks
-- end
return Profile
|
description 'Example of custom dispatch for ballas and vagos gangs'
client_scripts {
'config.lua',
'client.lua'
}
dependency 'essentialmode'
|
local function user_print_name(user)
local text = ''
if user.first_name then
text = user.first_name..' '
end
if user.last_name then
text = text..user.last_name
end
if user.title then
text = user.title
end
return text or user.print_name:gsub('_', ' ')
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = result.peer_id
local chatname = result.title
local text = str2emoji(":busts_in_silhouette:")..' IDs for chat '..chatname
..' ('..chat_id..')\n'
..'There are '..result.members_num..' members'
..'\n---------\n'
i = 0
for k,v in pairs(result.members) do
i = i+1
text = text .. i .. ". " .. user_print_name(v) .. " (" .. v.peer_id .. ")\n"
end
send_large_msg(receiver, text)
end
local function returnidschan(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = cb_extra.peer_id
local chatname = cb_extra.print_name
local text = str2emoji(":busts_in_silhouette:")..' IDs for chat '..chatname
..' ('..string.gsub(chat_id, "channel#id", "")..')\n'
..'\n---------\n'
i = 0
for k,v in pairs(result) do
i = i+1
if v.print_name ~= nil then
text = text .. i .. ". " .. user_print_name(v) .. " (" .. v.peer_id .. ")\n"
else
text = text .. i .. ". " .. "?" .. " (" .. v.peer_id .. ")\n"
end
end
send_large_msg(receiver, text)
end
local function username_id(cb_extra, success, result)
local receiver = cb_extra.receiver
local qusername = cb_extra.qusername
local is_chan = cb_extra.is_chan
local text = str2emoji(":no_entry_sign:")..' User @'..qusername..' does not exist!'
if success then
qusername = result.username
if result.peer_type == 'channel' then
text = str2emoji(":id:")..' ID for group/channel\n'..str2emoji(":busts_in_silhouette:")..' @'..qusername..' : '..result.peer_id
else
text = str2emoji(":id:")..' ID for user\n'..str2emoji(":bust_in_silhouette:")..' @'..qusername..' : '..result.peer_id
end
end
send_large_msg(receiver, text)
end
local function id_by_reply(cb_extra, success, result)
local username
if result.from.username then
username = '@'..result.from.username
else
username = user_print_name(result.from)
end
send_large_msg(cb_extra, str2emoji(":id:")..' ID for user\n'..str2emoji(":bust_in_silhouette:")..' '..username..' : '..result.from.peer_id)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "!id" then
local text = str2emoji(":bust_in_silhouette:")..' Name: '.. user_print_name(msg.from)
text = text..'\n'..str2emoji(":id:")..' ID: ' .. msg.from.id
if is_chat_msg(msg) then
text = text .. "\n"..str2emoji(":busts_in_silhouette:").." You are in group " .. user_print_name(msg.to)
text = text .. " (ID: " .. msg.to.id .. ")"
end
return text
elseif matches[1] == "#id" then
if msg.reply_id then
get_message(msg.reply_id, id_by_reply, get_receiver(msg))
return nil
end
return nil
elseif matches[1] == "chat" then
-- !ids? (chat) (%d+)
if matches[2] then
local group = string.gsub(matches[2], 'chat#id', '')
group = string.gsub(group, 'channel#id', '')
if is_mod(msg.from.id, group) then
local chat = matches[2]
if string.starts(chat, "chat#id") then
return chat_info(chat, returnids, {receiver=receiver})
end
if string.starts(chat, "channel#id") then
return channel_get_users(chat, returnidschan, {peer_id=matches[2], print_name="", receiver=receiver})
end
return str2emoji(":no_entry_sign:").." Invalid ID."
else
return str2emoji(":no_entry_sign:").." You cannot lookup the IDs from that group."
end
else
if not is_chat_msg(msg) then
return str2emoji(":no_entry_sign:").." You are not in a group."
end
local chat = get_receiver(msg)
if not is_chan_msg(msg) then
chat_info(chat, returnids, {receiver=receiver})
else
channel_get_users(chat, returnidschan, {peer_id=msg.to.id, print_name=user_print_name(msg.to), receiver=receiver})
end
end
else
local qusername = string.gsub(matches[1], "@", "")
local chat = get_receiver(msg)
resolve_username(qusername, username_id, {receiver=receiver, qusername=qusername, is_chan=is_chan_msg(msg)})
end
end
return {
description = "Know your id or the id of a chat members.",
usage = {
"!id: Return your ID and the chat id if you are in one.",
"!id <username> : Return the id from username given.",
moderator = {
"!ids chat: Return the IDs of the current chat members.",
"!ids chat chat#id<chat_id>: Return the IDs of the <chat_id> members.",
"!ids chat channel#id<channel_id>: Return the IDs of the <channel_id> (supergroup) members."
}
},
patterns = {
"^!id$",
"^#id$",
"^!ids? (chat) (.*)$",
"^!ids? (chat)$",
"^!id (.*)$"
},
run = run
}
|
#!/usr/bin/lua
--****************************
--Function: Set vlanid related to certain wan
--Usage: Run change_vlan.lua with wan_name and vlanid you want to set. '1' means to add switch_vlan if not find vlanid
--Example: lua change_vlan.lua wan4 1099 1
--****************************
local uci = require "luci.model.uci"
local _uci_real = cursor or _uci_real or uci.cursor()
function get_port_str()
local port_str
local result
_uci_real:foreach("network","switch_vlan",
function(s)
port_str = _uci_real:get("network",s[".name"],"ports")
if port_str then
if result == nil then
port_str = string.match(port_str,"(%d+)t")
result = port_str.."t"
end
end
end)
return result
end
function add_switch(vlanid)
local s_name = _uci_real:add("network","switch_vlan")
local default_port = "4 "..get_port_str()
_uci_real:set("network",s_name,"vlan",vlanid)
_uci_real:set("network",s_name,"device","switch0")
_uci_real:set("network",s_name,"ports",default_port)
end
function set_vlanid(wan,new_vlanid)
local finish = 0
local ifname = _uci_real:get("network",wan,"ifname")
local old_vlanid = tonumber(string.match(ifname,"eth0%p(%d+)"))
if string.find(ifname,"bridge") then
new_ifname = "bridge-eth0."..new_vlanid
else
new_ifname = "eth0."..new_vlanid
end
_uci_real:set("network",wan,"ifname",new_ifname)
_uci_real:foreach("network","switch_vlan",
function(s)
if tonumber(s.vlan) == old_vlanid and finish == 0 then
_uci_real:set("network",s[".name"],"vlan",new_vlanid)
finish = 1
end
end)
if finish == 0 and arg[3] == 1 then
add_switch(new_vlanid)
end
_uci_real:save("network")
_uci_real:commit("network")
end
local wan = arg[1]
local new_vlanid = arg[2]
if _uci_real:get("network",wan) == nil then
print("no "..wan.." in network")
else
set_vlanid(wan,new_vlanid)
end
|
local function body()
print 'body'
end
local co = coroutine.create(body)
coroutine.resume(co)
|
--[[
© 2013 GmodLive private project do not share
without permission of its author (Andrew Mensky vk.com/men232).
--]]
local greenCode = greenCode;
local pairs = pairs;
local math = math;
greenCode.hint = greenCode.kernel:NewLibrary("Hint");
greenCode.hint.stored = {};
if SERVER then
function greenCode.hint:Send( player, text, delay, color, bNoSound, bShowDuplicates )
gc.datastream:Start(player, "Hint", {
text = text, delay = delay, color = color, noSound = bNoSound, showDuplicates = bShowDuplicates
});
end;
function greenCode.hint:SendAll( text, delay, color, bShowDuplicates, bOnlyAdmin )
for k, v in pairs(_player.GetAll()) do
if ( v:HasInitialized() and ( !bOnlyAdmin or v:IsAdmin() ) ) then
self:Send(v, text, delay, color, nil, bShowDuplicates);
end;
end;
end;
else
function greenCode.hint:Add(text, delay, color, bNoSound, bShowDuplicates)
local colorWhite = Color(255, 255, 255, 255);
if ( !color ) then
color = colorWhite;
end;
if ( !text ) then
text = "#Text"
end;
MsgC(color, "[System] "..text.."\n");
if (!bShowDuplicates) then
for k, v in pairs(self.stored) do
if (v.text == text) then
return;
end;
end;
end;
if (table.Count(self.stored) == 10) then
table.remove(self.stored, 10);
end;
if (type(bNoSound) == "string") then
surface.PlaySound(bNoSound);
elseif (bNoSound == nil) then
//surface.PlaySound("hl1/fvox/blip.wav");
surface.PlaySound("ui/buttonrollover.wav");
end;
self.stored[#self.stored + 1] = {
startTime = SysTime(),
velocityX = -5,
velocityY = 0,
targetAlpha = 255,
alphaSpeed = 64,
color = color,
delay = delay,
alpha = 0,
text = text,
y = ScrH() * 0.3,
x = ScrW() + 200
};
end;
local function UpdateHint( index, hintInfo, iCount )
local hintsFont = "gcIntroTextTiny";
local fontWidth, fontHeight = gc.kernel:GetCachedTextSize(
hintsFont, hintInfo.text
);
local height = fontHeight;
//local width = fontWidth;
local alpha = 255;
local x = hintInfo.x;
local y = hintInfo.y;
--[[ Work out the ideal X and Y position for the hint. --]]
local idealY = 25 + (height * (index - 1));
local idealX = ScrW() - 32;
local timeLeft = (hintInfo.startTime - (SysTime() - hintInfo.delay) + 2);
if (timeLeft < 0.7) then
idealX = idealX - 50;
alpha = 0;
end;
if (timeLeft < 0.2) then
idealX = idealX * 2;
end;
local fSpeed = FrameTime() * 15;
y = y + hintInfo.velocityY * fSpeed;
x = x + hintInfo.velocityX * fSpeed;
local distanceY = idealY - y;
local distanceX = idealX - x;
local distanceA = (alpha - hintInfo.alpha);
hintInfo.velocityY = hintInfo.velocityY + distanceY * fSpeed * 1;
hintInfo.velocityX = hintInfo.velocityX + distanceX * fSpeed * 1;
if (math.abs(distanceY) < 2 and math.abs(hintInfo.velocityY) < 0.1) then
hintInfo.velocityY = 0;
end;
if (math.abs(distanceX) < 2 and math.abs(hintInfo.velocityX) < 0.1) then
hintInfo.velocityX = 0;
end;
hintInfo.velocityX = hintInfo.velocityX * (0.95 - FrameTime() * 8);
hintInfo.velocityY = hintInfo.velocityY * (0.95 - FrameTime() * 8);
hintInfo.alpha = hintInfo.alpha + distanceA * fSpeed * 0.1;
hintInfo.x = x;
hintInfo.y = y;
--[[ Remove it if we're finished. --]]
return (timeLeft < 0.1);
end;
function greenCode.hint:Think()
for k, v in pairs(self.stored) do
if ( UpdateHint(k, v, #self.stored) ) then
table.remove(self.stored, k);
end;
end;
end;
-- Called when the local player attempts to see the top hints.
function greenCode.hint:PlayerCanSeeHints()
return true;
end;
function greenCode.hint:HUDPaint()
if (gc.plugin:Call("PlayerCanSeeHints") and #self.stored > 0) then
local hintsFont = "gcIntroTextTiny";
for k, v in pairs(self.stored) do
gc.kernel:DrawInfo(v.text, v.x, v.y, v.color, v.alpha, true, nil, nil, TEXT_ALIGN_RIGHT);
end;
end;
end;
greenCode.datastream:Hook("Hint", function(data)
if (data and type(data) == "table") then
greenCode.hint:Add(
data.text, data.delay, data.color, data.noSound, data.showDuplicates
);
end;
end);
end;
if SERVER then
greenCode.command:Add( "alert", 2, function( player, command, args )
//player:ShowHint( args[1], 5 );
//player:ShowAlert( args[1], Color( 150,255,150,255 ) );
greenCode.hint:SendAll( args[1], 5, Color( 150,255,150,255 ), true, false );
end);
end;
|
----------------------------------------------------------------------------------------------------
--
-- Copyright (c) Contributors to the Open 3D Engine Project.
-- For complete copyright and license terms please see the LICENSE at the root of this distribution.
--
-- SPDX-License-Identifier: Apache-2.0 OR MIT
--
--
--
----------------------------------------------------------------------------------------------------
local LoadCppCanvas =
{
Properties =
{
},
}
function LoadCppCanvas:OnActivate()
self.buttonHandler = UiButtonNotificationBus.Connect(self, self.entityId)
end
function LoadCppCanvas:OnButtonClick()
LyShineExamplesCppExampleBus.Broadcast.CreateCanvas()
end
function LoadCppCanvas:OnDeactivate()
self.buttonHandler:Disconnect()
LyShineExamplesCppExampleBus.Broadcast.DestroyCanvas()
end
return LoadCppCanvas
|
-- TODO: figure out why this don't work
vim.fn.sign_define(
"LspDiagnosticsSignError",
{ texthl = "LspDiagnosticsSignError", text = "", numhl = "LspDiagnosticsSignError" }
)
vim.fn.sign_define(
"LspDiagnosticsSignWarning",
{ texthl = "LspDiagnosticsSignWarning", text = "", numhl = "LspDiagnosticsSignWarning" }
)
vim.fn.sign_define(
"LspDiagnosticsSignHint",
{ texthl = "LspDiagnosticsSignHint", text = "", numhl = "LspDiagnosticsSignHint" }
)
vim.fn.sign_define(
"LspDiagnosticsSignInformation",
{ texthl = "LspDiagnosticsSignInformation", text = "", numhl = "LspDiagnosticsSignInformation" }
)
-- local opts = { border = "single" }
-- TODO revisit this
-- local border = {
-- { "🭽", "FloatBorder" },
-- { "▔", "FloatBorder" },
-- { "🭾", "FloatBorder" },
-- { "▕", "FloatBorder" },
-- { "🭿", "FloatBorder" },
-- { "▁", "FloatBorder" },
-- { "🭼", "FloatBorder" },
-- { "▏", "FloatBorder" },
-- }
-- My font didn't like this :/
-- vim.api.nvim_set_keymap(
-- "n",
-- "gl",
-- '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics({ show_header = false, border = { { "🭽", "FloatBorder" }, { "▔", "FloatBorder" }, { "🭾", "FloatBorder" }, { "▕", "FloatBorder" }, { "🭿", "FloatBorder" }, { "▁", "FloatBorder" }, { "🭼", "FloatBorder" }, { "▏", "FloatBorder" }, } })<CR>',
-- { noremap = true, silent = true }
-- )
-- Set Default Prefix.
-- Note: You can set a prefix per lsp server in the lv-globals.lua file
vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, {
virtual_text = O.lsp.diagnostics.virtual_text,
signs = O.lsp.diagnostics.signs,
underline = O.lsp.document_highlight,
})
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, {
border = O.lsp.popup_border,
})
vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, {
border = O.lsp.popup_border,
})
-- symbols for autocomplete
vim.lsp.protocol.CompletionItemKind = {
" (Text) ",
" (Method)",
" (Function)",
" (Constructor)",
" ﴲ (Field)",
"[] (Variable)",
" (Class)",
" ﰮ (Interface)",
" (Module)",
" 襁 (Property)",
" (Unit)",
" (Value)",
" 練 (Enum)",
" (Keyword)",
" (Snippet)",
" (Color)",
" (File)",
" (Reference)",
" (Folder)",
" (EnumMember)",
" ﲀ (Constant)",
" ﳤ (Struct)",
" (Event)",
" (Operator)",
" (TypeParameter)",
}
--[[ " autoformat
autocmd BufWritePre *.js lua vim.lsp.buf.formatting_sync(nil, 100)
autocmd BufWritePre *.jsx lua vim.lsp.buf.formatting_sync(nil, 100)
autocmd BufWritePre *.lua lua vim.lsp.buf.formatting_sync(nil, 100) ]]
-- Java
-- autocmd FileType java nnoremap ca <Cmd>lua require('jdtls').code_action()<CR>
local function lsp_highlight_document(client)
if O.lsp.document_highlight == false then
return -- we don't need further
end
-- Set autocommands conditional on server_capabilities
if client.resolved_capabilities.document_highlight then
vim.api.nvim_exec(
[[
hi LspReferenceRead cterm=bold ctermbg=red guibg=#464646
hi LspReferenceText cterm=bold ctermbg=red guibg=#464646
hi LspReferenceWrite cterm=bold ctermbg=red guibg=#464646
augroup lsp_document_highlight
autocmd! * <buffer>
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
augroup END
]],
false
)
end
end
local lsp_config = {}
-- Taken from https://www.reddit.com/r/neovim/comments/gyb077/nvimlsp_peek_defination_javascript_ttserver/
function lsp_config.preview_location(location, context, before_context)
-- location may be LocationLink or Location (more useful for the former)
context = context or 15
before_context = before_context or 0
local uri = location.targetUri or location.uri
if uri == nil then
return
end
local bufnr = vim.uri_to_bufnr(uri)
if not vim.api.nvim_buf_is_loaded(bufnr) then
vim.fn.bufload(bufnr)
end
local range = location.targetRange or location.range
local contents = vim.api.nvim_buf_get_lines(
bufnr,
range.start.line - before_context,
range["end"].line + 1 + context,
false
)
local filetype = vim.api.nvim_buf_get_option(bufnr, "filetype")
return vim.lsp.util.open_floating_preview(contents, filetype, { border = O.lsp.popup_border })
end
function lsp_config.preview_location_callback(_, method, result)
local context = 15
if result == nil or vim.tbl_isempty(result) then
print("No location found: " .. method)
return nil
end
if vim.tbl_islist(result) then
lsp_config.floating_buf, lsp_config.floating_win = lsp_config.preview_location(result[1], context)
else
lsp_config.floating_buf, lsp_config.floating_win = lsp_config.preview_location(result, context)
end
end
function lsp_config.PeekDefinition()
if vim.tbl_contains(vim.api.nvim_list_wins(), lsp_config.floating_win) then
vim.api.nvim_set_current_win(lsp_config.floating_win)
else
local params = vim.lsp.util.make_position_params()
return vim.lsp.buf_request(0, "textDocument/definition", params, lsp_config.preview_location_callback)
end
end
function lsp_config.PeekTypeDefinition()
if vim.tbl_contains(vim.api.nvim_list_wins(), lsp_config.floating_win) then
vim.api.nvim_set_current_win(lsp_config.floating_win)
else
local params = vim.lsp.util.make_position_params()
return vim.lsp.buf_request(0, "textDocument/typeDefinition", params, lsp_config.preview_location_callback)
end
end
function lsp_config.PeekImplementation()
if vim.tbl_contains(vim.api.nvim_list_wins(), lsp_config.floating_win) then
vim.api.nvim_set_current_win(lsp_config.floating_win)
else
local params = vim.lsp.util.make_position_params()
return vim.lsp.buf_request(0, "textDocument/implementation", params, lsp_config.preview_location_callback)
end
end
function lsp_config.common_on_attach(client, bufnr)
if O.lsp.on_attach_callback then
O.lsp.on_attach_callback(client, bufnr)
end
lsp_highlight_document(client)
local present, lsp_signature = pcall(require, "lsp_signature")
if not present then
return
end
lsp_signature.on_attach()
end
function lsp_config.get_capabilities()
local present, cmp_lsp = pcall(require, 'cmp_nvim_lsp')
if present then
return cmp_lsp.update_capabilities(vim.lsp.protocol.make_client_capabilities())
else
return vim.lsp.project_nvim.make_client_capabilities()
end
end
function lsp_config.tsserver_on_attach(client, _)
-- lsp_config.common_on_attach(client, bufnr)
client.resolved_capabilities.document_formatting = false
local ts_utils = require("nvim-lsp-ts-utils")
-- defaults
ts_utils.setup({
debug = false,
disable_commands = false,
enable_import_on_completion = false,
import_all_timeout = 5000, -- ms
-- eslint
eslint_enable_code_actions = true,
eslint_enable_disable_comments = true,
-- eslint_bin = O.lang.tsserver.linter,
eslint_config_fallback = nil,
eslint_enable_diagnostics = true,
-- formatting
enable_formatting = O.lang.tsserver.autoformat,
formatter = O.lang.tsserver.formatter.exe,
formatter_config_fallback = nil,
-- parentheses completion
complete_parens = false,
signature_help_in_parens = false,
-- update imports on file move
update_imports_on_move = false,
require_confirmation_on_move = false,
watch_dir = nil,
})
-- required to fix code action ranges
ts_utils.setup_client(client)
-- TODO: keymap these?
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "gs", ":TSLspOrganize<CR>", {silent = true})
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "qq", ":TSLspFixCurrent<CR>", {silent = true})
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", ":TSLspRenameFile<CR>", {silent = true})
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", ":TSLspImportAll<CR>", {silent = true})
end
require("utils.lua").define_augroups({
_general_lsp = {
{ "FileType", "lspinfo", "nnoremap <silent> <buffer> q :q<CR>" },
},
})
-- Use a loop to conveniently both setup defined servers
-- and map buffer local keybindings when the language server attaches
-- local servers = {"pyright", "tsserver"}
-- for _, lsp in ipairs(servers) do nvim_lsp[lsp].setup {on_attach = on_attach} end
return lsp_config
|
--locals
local render_target_first = render.GetScreenEffectTexture(0)
local render_target_second = render.GetScreenEffectTexture(1)
----localized functions
local entity_meta = FindMetaTable("Entity")
local fl_cam_End2D = cam.End2D
local fl_cam_End3D = cam.End3D
local fl_cam_Start2D = cam.Start2D
local fl_cam_Start3D = cam.Start3D
local fl_Entity_DrawModel = entity_meta.DrawModel
local fl_Entity_GetNoDraw = entity_meta.GetNoDraw
local fl_render_Clear = render.Clear
local fl_render_ClearDepth = render.ClearDepth
local fl_render_ClearStencil = render.ClearStencil
local fl_render_CopyRenderTargetToTexture = render.CopyRenderTargetToTexture
local fl_render_DrawScreenQuad = render.DrawScreenQuad
local fl_render_GetRenderTarget = render.GetRenderTarget
local fl_render_PopFilterMag = render.PopFilterMag
local fl_render_PopFilterMin = render.PopFilterMin
local fl_render_PopRenderTarget = render.PopRenderTarget
local fl_render_PushFilterMag = render.PushFilterMag
local fl_render_PushFilterMin = render.PushFilterMin
local fl_render_PushRenderTarget = render.PushRenderTarget
local fl_render_SetBlend = render.SetBlend
local fl_render_SetMaterial = render.SetMaterial
local fl_render_SetRenderTarget = render.SetRenderTarget
local fl_render_SetStencilEnable = render.SetStencilEnable
local fl_render_SetStencilCompareFunction = render.SetStencilCompareFunction
local fl_render_SetStencilFailOperation = render.SetStencilFailOperation
local fl_render_SetStencilPassOperation = render.SetStencilPassOperation
local fl_render_SetStencilReferenceValue = render.SetStencilReferenceValue
local fl_render_SetStencilTestMask = render.SetStencilTestMask
local fl_render_SetStencilWriteMask = render.SetStencilWriteMask
local fl_render_SetStencilZFailOperation = render.SetStencilZFailOperation
local fl_render_SuppressEngineLighting = render.SuppressEngineLighting
local fl_surface_DrawRect = surface.DrawRect
local fl_surface_DrawTexturedRect = surface.DrawTexturedRect
local fl_surface_SetDrawColor = surface.SetDrawColor
local fl_surface_SetMaterial = surface.SetMaterial
--materials
local material_copy = Material("pp/copy")
local material_first = CreateMaterial("pyrition/outline/first", "UnlitGeneric", {
["$basetexture"] = render_target_first:GetName(),
["$vertexalpha"] = 1,
["$vertexcolor"] = 1,
["$translucent"] = 1
})
local material_second = CreateMaterial("pyrition/outline/second", "UnlitGeneric", {
["$basetexture"] = render_target_second:GetName(),
["$vertexalpha"] = 1,
["$vertexcolor"] = 1,
["$translucent"] = 1
})
--local functions
local function draw_entities(entities)
for index, entity in ipairs(entities) do
if IsValid(entity) then
if fl_Entity_GetNoDraw(entity) then continue end
fl_Entity_DrawModel(entity)
end
end
end
local function draw_blurs_depth(entities, r, g, b, a, scr_w, scr_h)
--with a control of 404 fps
--with 70 props of the same group got ~260 fps
--with a control of 380 fps (GPU started getting hot)
--with 41 props of 4 different groups got ~99 fps
local render_target_scene = fl_render_GetRenderTarget()
--prepare our scene to render in
fl_render_CopyRenderTargetToTexture(render_target_first)
fl_render_Clear(r, g, b, 0, false, true)
fl_render_PushFilterMag(TEXFILTER.POINT)
fl_render_PushFilterMin(TEXFILTER.POINT)
--fl_render_SetStencilEnable(true)
fl_render_SuppressEngineLighting(true)
--standard pass stencil
--[[fl_render_SetStencilCompareFunction(STENCIL_ALWAYS)
fl_render_SetStencilFailOperation(STENCIL_KEEP)
fl_render_SetStencilPassOperation(STENCIL_REPLACE)
fl_render_SetStencilReferenceValue(1)
fl_render_SetStencilTestMask(0xFF)
fl_render_SetStencilWriteMask(0xFF)
fl_render_SetStencilZFailOperation(STENCIL_KEEP)]]
--draw the models
fl_cam_Start3D()
draw_entities(entities)
fl_cam_End3D()
--change settings to only draw where its 1
--fl_render_SetStencilCompareFunction(STENCIL_EQUAL)
--fl_render_SetStencilPassOperation(STENCIL_KEEP)
--draw the color layer
--[[fl_cam_Start2D()
fl_surface_SetDrawColor(255, 255, 255)
fl_surface_DrawRect(0, 0, scr_w, scr_h)
fl_cam_End2D()]]
--done with this stencil
--fl_render_SetStencilEnable(false)
--fl_render_SuppressEngineLighting(false)
--store what we drew to the second render target and set our render target back to what it was
fl_render_CopyRenderTargetToTexture(render_target_second)
render.BlurRenderTarget(render_target_second, 2, 2, 1)
fl_render_SetRenderTarget(render_target_scene)
--needed to prevent the "flash bang" bug
--seems that other render libraries can mess with the material's base texture >:(
material_copy:SetTexture("$basetexture", render_target_first)
--redraw the existing scene
fl_render_SetMaterial(material_copy)
fl_render_DrawScreenQuad()
--more stencils!
--[[fl_render_SetStencilEnable(true)
fl_render_SetStencilCompareFunction(STENCIL_EQUAL)
fl_render_SetStencilReferenceValue(0)]]
--draw the model shapes sever times
fl_cam_Start2D()
--fl_surface_SetDrawColor(r, g, b, a)
fl_surface_SetDrawColor(255, 255, 255)
fl_surface_SetMaterial(material_second)
fl_surface_DrawTexturedRect(0, 0, scr_w, scr_h)
--[[for x = outline_min, outline_max, outline_step do
local x_zero = x == 0
for y = outline_min, outline_max, outline_step do
if x_zero and y == 0 then continue end
fl_surface_DrawTexturedRect(x, y, scr_w, scr_h)
end
end]]
fl_cam_End2D()
--fl_render_ClearDepth()
fl_render_PopFilterMag()
fl_render_PopFilterMin()
--fl_render_SetStencilEnable(false)
end
--hooks
hook.Add("PostDrawEffects", "PyritionGFXBlur", function()
local scr_w, scr_h = ScrW(), ScrH()
for index, data in pairs(PYRITION.GFX.Blur) do
draw_blurs_depth(data.entities, 0, 0, 0, 255, scr_w, scr_h)
end
local blurs = {}
local bots = {}
for index, bot in ipairs(player.GetBots()) do if IsValid(bot) and bot:Alive() then table.insert(bots, bot) end end
table.insert(blurs, {entities = bots})
if #blurs == 0 then return end
for index, data in ipairs(blurs) do
draw_blurs_depth(data.entities, 255, 255, 255, 255, scr_w, scr_h)
end
end)
|
BLT.Items.Slider = BLT.Items.Slider or class(BLT.Items.Item)
local Slider = BLT.Items.Slider
Slider.type_name = "Slider"
function Slider:Init()
self.value = self.value or 1
self.size_by_text = false
Slider.super.Init(self)
self.step = self.step or 1
self.value = tonumber(self.value) or 0
self.floats = self.floats or 2
self.filter = "number"
self.min = self.min or 0
self.max = self.max or self.min
local item_width = self.panel:w() * self.control_slice
local slider_width = item_width * 0.66
local text_width = item_width - slider_width
local fgcolor = self:GetForeground()
self._textbox = BLT.Items.TextBoxBase:new(self, {
lines = 1,
btn = "1",
panel = self.panel,
align = "center",
layer = 10,
line = false,
w = text_width,
value = self.value,
})
self._slider = self.panel:panel({
w = slider_width,
name = "slider",
layer = 4,
})
local ch = self._slider:h() - 2
self.circle = self._slider:bitmap({
name = "circle",
w = ch,
h = ch,
y = 1,
texture = "ui/atlas/raid_atlas_menu",
texture_rect = {765, 679, 33, 33},
layer = 3,
color = fgcolor,
})
self.sfg = self._slider:rect({
name = "fg",
x = ch / 2,
w = self._slider:w() * (self.value / self.max),
h = 4,
layer = 2,
color = fgcolor
})
self.sfg:set_center_y(self._slider:h() / 2)
self.sbg = self._slider:rect({
name = "bg",
x = ch / 2,
w = self._slider:w() - ch,
h = 4,
layer = 1,
color = fgcolor:with_alpha(0.25),
})
self.sbg:set_center_y(self._slider:h() / 2)
self._slider:set_right(self._textbox.panel:x())
self._mouse_pos_x, self._mouse_pos_y = 0,0
self._textbox:PostInit()
end
function Slider:SetStep(step)
self.step = step
end
function Slider:_SetValue(value, run_callback, reset_selection, no_format)
value = tonumber(value) or 0
if self.max or self.min then
value = math.clamp(value, self.min, self.max)
end
value = tonumber(not no_format and format or value)
local format = string.format("%." .. self.floats .. "f", value)
local text = self._textbox.panel:child("text")
self.sfg:set_w(self.sbg:w() * ((value - self.min) / (self.max - self.min)))
self._slider:child("circle"):set_center(self.sfg:right(), self.sfg:center_y())
if not no_format then
text:set_text(format)
end
if reset_selection then
text:set_selection(text:text():len())
end
self._before_text = self.value
Slider.super.SetValue(self, value, run_callback)
end
function Slider:SetValue(value, ...)
if not self:alive() then
return false
end
if self.value ~= value then
self._textbox:add_history_point(value)
end
self:_SetValue(value, ...)
return true
end
function Slider:SetValueByPercentage(percent)
self:SetValue(self.min + (self.max - self.min) * percent, true, true)
end
function Slider:MouseMoved(x, y)
Slider.super.MouseMoved(self, x, y)
self._textbox:MouseMoved(x, y)
end
function Slider:MouseReleased(button, x, y)
self._textbox:MouseReleased(button, x, y)
end
function Slider:KeyPressed(o, k)
Slider.super.KeyPressed(self, o, k)
self._textbox:KeyPressed(o, k)
end
function Slider:DoHighlight(highlight)
Slider.super.DoHighlight(self, highlight)
self._textbox:DoHighlight(highlight)
local fgcolor = self:GetForeground(highlight)
if self.sfg then
play_color(self.sfg, fgcolor)
play_color(self.sbg, fgcolor:with_alpha(0.25))
play_color(self.circle, fgcolor)
end
end
function Slider:MousePressed(button, x, y)
Slider.super.MousePressed(self, button, x, y)
self._textbox:MousePressed(button, x, y)
if not self.enabled or not alive(self.panel) then
return
end
local inside = self._slider:inside(x,y)
if inside then
local wheelup = (button == Idstring("mouse wheel up") and 0) or (button == Idstring("mouse wheel down") and 1) or -1
if self.wheel_control and wheelup ~= -1 then
self:SetValue(self.value + ((wheelup == 1) and -self.step or self.step), true, true)
return true
end
if button == Idstring("0") then
self.menu._slider_hold = self
if self.max or self.min then
local slider_bg = self._slider:child("bg")
local where = (x - slider_bg:world_left()) / (slider_bg:world_right() - slider_bg:world_left())
managers.menu_component:post_event("menu_enter")
self:SetValueByPercentage(where)
end
return true
else
return self:CheckMouseRightClick(button, x,y)
end
end
end
function Slider:SetValueByMouseXPos(x)
if not alive(self.panel) then
return
end
local slider_bg = self._slider:child("bg")
self:SetValueByPercentage((x - slider_bg:world_left()) / (slider_bg:world_right() - slider_bg:world_left()))
end
|
data:extend({
{
type = 'custom-input',
name = 'controllinator-debug-pause',
key_sequence = 'F10',
},
{
type = 'custom-input',
name = 'controllinator-debug-step',
key_sequence = 'F11',
},
{
type = 'custom-input',
name = 'controllinator-debug-toggle',
key_sequence = 'F12',
},
{
type = 'custom-input',
name = 'controllinator-toggle-gui',
key_sequence = 'CONTROL + F10'
},
{
type = 'custom-input',
name = 'controllinator-toggle-edit',
key_sequence = 'CONTROL + F11'
},
{
type = 'custom-input',
name = 'controllinator-toggle-new',
key_sequence = 'CONTROL + F12'
}
})
|
-- pre require settings
vim.g.nvim_tree_show_icons = {
files = 0,
folders = 1,
folder_arrows = 1,
git = 0,
}
vim.g.nvim_tree_icons = {
folder = {
default = 'F',
open = 'F',
empty = 'E',
empty_open = 'E',
arrow_open = ".",
arrow_closed = '>'
}
}
vim.g.nvim_tree_quit_on_open = 1
require("packer").startup(function()
-- package manager Packer
-- https://github.com/wbthomason/packer.nvim
use "wbthomason/packer.nvim"
-- fzf
-- https://github.com/junegunn/fzf.vim
use "junegunn/fzf"
use "junegunn/fzf.vim"
-- atom one dark theme
-- https://github.com/navarasu/onedark.nvim
-- use "navarasu/onedark.nvim"
-- use 'monsonjeremy/onedark.nvim'
use 'navarasu/onedark.nvim'
-- nvim tree
-- https://github.com/kyazdani42/nvim-tree.lua
use {
"kyazdani42/nvim-tree.lua"
-- I don't use icons
-- requires = "kyazdani42/nvim-web-devicons"
}
-- bufferline
-- https://github.com/akinsho/bufferline.nvim#close-icons
use {
'akinsho/bufferline.nvim'
}
-- statusline
use {
'nvim-lualine/lualine.nvim'
}
-- tree sitter
use {
'nvim-treesitter/nvim-treesitter', run = ':TSUpdate'
}
-- lsp
use {
'neovim/nvim-lspconfig', 'williamboman/nvim-lsp-installer'
}
use {
'tami5/lspsaga.nvim'
}
use 'hrsh7th/cmp-nvim-lsp'
use 'hrsh7th/cmp-buffer'
use 'hrsh7th/cmp-path'
use 'hrsh7th/cmp-cmdline'
use 'hrsh7th/nvim-cmp'
use 'hrsh7th/cmp-vsnip'
use 'rafamadriz/friendly-snippets'
use 'onsails/lspkind-nvim'
-- telescope
use {
'nvim-telescope/telescope.nvim',
requires = {
{ 'nvim-lua/plenary.nvim' }
}
}
-- git blame
use {
'lewis6991/gitsigns.nvim',
requires = {
'nvim-lua/plenary.nvim'
},
}
end)
require("nvim-tree").setup {
auto_close = true,
git = {
enable = true
},
}
vim.opt.termguicolors = true
require('bufferline').setup {
options = {
buffer_close_icon = 'x',
modified_icon = 'o',
close_icon = 'x',
diagnostics = 'nvim_lsp',
offsets = {{
filetype = 'NvimTree'
}}
}
}
require('nvim-treesitter.configs').setup {
ensure_installed = { "html", "css", "vim", "lua", "javascript", "typescript", "tsx" },
highlight = {
enable = true
},
incremental_selection = {
enable = true,
keymaps = {
init_selection = '<CR>',
node_incremental = '<CR>',
node_decremental = '<BS>',
scope_incremental = '<tab>',
}
},
}
vim.wo.foldmethod = 'expr'
vim.wo.foldexpr = 'nvim_treesitter#foldexpr()'
vim.wo.foldlevel = 20
require('telescope').setup {
file_ignore_patterns = { "node_modules" }
}
-- lualine
require('lualine').setup {
options = {
icons_enabled = false,
theme = 'auto',
component_separators = { left = '', right = ''},
section_separators = { left = '', right = ''},
disabled_filetypes = {},
always_divide_middle = true,
},
sections = {
lualine_a = {'mode'},
lualine_b = {'branch', 'diff', 'diagnostics'},
lualine_c = {
{
'filename',
path = 1
}
},
lualine_x = {'encoding', 'fileformat', 'filetype'},
lualine_y = {'progress'},
lualine_z = {'location'}
},
inactive_sections = {
lualine_a = {},
lualine_b = {},
lualine_c = {'filename'},
lualine_x = {'location'},
lualine_y = {},
lualine_z = {}
},
tabline = {},
extensions = {}
}
require('gitsigns').setup {
current_line_blame = true,
current_line_blame_opts = {
virt_text = true,
delay = 1000,
}
}
-- change gitlens color
vim.cmd[[highlight link GitSignsCurrentLineBlame Comment]]
-- enable atom one dark theme
require('onedark').load()
|
local MandelbrotCheck = function(workX, workY)
return ((workX * workX) + (workY * workY)) < 4.0
end
local GameObject = CS.UnityEngine.GameObject
local Vector3 = CS.UnityEngine.Vector3
local Quaternion = CS.UnityEngine.Quaternion
function TestMandelbrot(sb)
local data = 0.0
local iterations = 4
local width = 64
local height = 64
local _os_t = os.clock
local _ct = _os_t()
for i = 1, iterations do
local left = -2.1
local right = 1.0
local top = -1.3
local bottom = 1.3
local deltaX = (right - left) / width
local deltaY = (bottom - top) / height
local coordinateX = left
for x = 1, width do
local coordinateY = top
for y = 1, height do
local workX = 0
local workY = 0
local counter = 0
--while(counter < 255 and MandelbrotCheck(workX, workY))
while(counter < 255 and CS.Performance.MandelbrotCheck(workX, workY))
do
counter = counter + 1
local newX = (workX * workX) - (workY * workY) + coordinateX
workY = 2 * workX * workY + coordinateY
workX = newX;
end
data = workX + workY
coordinateY = coordinateY + deltaY
end
coordinateX = coordinateX + deltaX
end
end
local _d = _os_t() - _ct
sb:AppendLine("res="..data..", time:".._d*1000);
end
function Test0(sb)
local t = os.clock()
local go = GameObject("t")
local transform = go.transform
for i = 1, 2000000 do
transform.position = transform.position
end
GameObject.Destroy(go)
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test1(sb)
local t = os.clock()
local go = GameObject("t")
local transform = go.transform
for i = 1, 2000000 do
transform:Rotate(Vector3.up, 1)
end
GameObject.Destroy(go)
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test2(sb)
local t = os.clock()
for i = 1, 2000000 do
local v = Vector3(i, i, i)
local x,y,z = v.x, v.y, v.z
end
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test3(sb)
local t = os.clock()
for i = 1, 20000 do
local go = GameObject()
GameObject.Destroy(go)
end
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test4(sb)
local t = os.clock()
local tp = typeof(CS.UnityEngine.SkinnedMeshRenderer)
for i = 1, 20000 do
local go = GameObject()
go:AddComponent(tp)
local c = go:GetComponent(tp)
c.receiveShadows = false
GameObject.Destroy(go)
end
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test5(sb)
local t = os.clock()
for i = 1, 2000000 do
local p = CS.UnityEngine.Input.mousePosition
end
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test6(sb)
local t = os.clock()
for i = 1, 2000000 do
local v = Vector3(i, i, i)
Vector3.Normalize(v)
end
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test7(sb)
local t = os.clock()
for i = 1, 2000000 do
local q1 = Quaternion.Euler(i, i, i)
local q2 = Quaternion.Euler(i * 2, i * 2, i * 2)
Quaternion.Slerp(Quaternion.identity, q1, 0.5)
end
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test8(sb)
local total = 0
local t = os.clock()
for i = 1, 2000000 do
total = total + i - (i / 2) * (i + 3) / (i + 5)
end
sb:AppendLine("res="..total..",time="..(os.clock()-t)*1000)
end
function Test9(sb)
local array = {}
for i = 1, 1024 do
array[i] = i
end
local total = 0
local t = os.clock()
for j = 1, 20000 do
for i = 1, 1024 do
total = total + array[i]
end
end
sb:AppendLine("res="..total..",time="..(os.clock()-t)*1000)
end
function Test10(sb)
local t = os.clock()
local go = GameObject("t")
local transform = go.transform
for i = 1, 2000000 do
CS.Performance.TestFunc1(1, "123", transform)
end
GameObject.Destroy(go)
sb:AppendLine("time="..(os.clock()-t)*1000)
end
function Test11(sb)
local t = os.clock()
local c = function(o, x)
local r = o + x
end
for i = 1, 1000000, 1 do
local a = Vector3(1, 2, 3)
local b = Vector3(4, 5, 6)
c(a,b)
end
sb:AppendLine("time="..(os.clock()-t)*1000)
end
|
CampSprite = class("CampSprite", function (...)
return BuildingBaseSprite:create(...)
end)
CampSprite.type = "UniqueBuilding"
Temple:initBuildingHP(CampSprite)
function CampSprite:onEnter()
self:adjustBarPosition(0, 10)
end
function CampSprite:create(...)
campSprite = CampSprite.new(IMG_BUILDING_CAMP)
campSprite:onEnter()
return campSprite
end
|
local layerBase = require("games/common2/module/layerBase");
require("games/common2/module/playerInfo/playerInfoLogic");
--[[
用户详情信息
]]
local PlayerLayout = class(layerBase);
PlayerLayout.ctor = function(self)
self.m_curSeat = -1;
end
PlayerLayout.dtor = function(self)
PlayerInfoLogic.releaseInstance();
end
PlayerLayout.onPlayerHeadClick = function(self,seat,uid,info,isFast)
local info = GamePlayerManager2.getInstance():getPlayerBySeat(seat);
if info then
if self.m_curSeat ~= seat then
self:removeView(self.m_curSeat);
end
if not self.m_views[seat] then
self:addView(seat,self.m_viewConfig[seat]);
end
local x, y = InteractionInfo.getInstance():getPlayerInfoPos(seat);
self.m_views[seat]:show(x,y,info);
self.m_views[seat]:setPropsData(self:getPropsInfoData());
self.m_curSeat = seat;
end
end
--游戏可重载该方法、不同的游戏展示不同的道具
PlayerLayout.getPropsInfoData = function(self)
local propsData = {
{
PropIsolater.getInstance():getPropInfoByType(203),
PropIsolater.getInstance():getPropInfoByType(202),
PropIsolater.getInstance():getPropInfoByType(201),
PropIsolater.getInstance():getPropInfoByType(200)
}
};
-- 可在游戏自己的xxxgameconfig.lua中定义
return propsData;
end
-- 玩家离开,关闭当前玩家的弹框
PlayerLayout.onLogout = function(self,seat,uid,info,isFast)
local localseat = PlayerSeat.getInstance():getMyLocalSeat();
if localseat ~= seat and self.m_views[seat] then
self:removeView(seat);
end
end
PlayerLayout.onGameOver = function(self,seat,uid,info,isFast)
self:removeView(seat);
end
-- 废弃的接口
PlayerLayout.onHidCurPlayerInfo = function(self)
-- if self.m_views[self.m_curSeat] then
-- self.m_views[self.m_curSeat]:hidden();
-- end
end
------------------------- 加好友-------------------------
-- 初始化layer的配置
PlayerLayout.initViewConfig = function(self)
local gameConfig = table.verify(GameProcessManager2.getInstance():getGameConfig());
local playerNumber = number.valueOf(gameConfig.playerNumer or 3);
local isNeedDrawTimes = gameConfig.isNeedDrawTimes; --是否需要平局信息
self.m_viewConfig = {};
local data = {
path = "games/common2/module/playerInfo/playerInfoView";
pos = {};
viewLayer = "view/kScreen_1280_800/games/common2/room_player_info_layout";
viewConfig = "room_player_info_layout";
config = {
isNeedDrawTimes = isNeedDrawTimes;
};
};
for i = 1, playerNumber do
table.insert(self.m_viewConfig, Copy(data));
end
end
PlayerLayout.s_stateFuncMap = {
[GameMechineConfig.STATUS_NONE] = "onLogout";
[GameMechineConfig.STATUS_LOGOUT] = "onLogout";
[GameMechineConfig.STATUS_GAMEOVER] = "onGameOver";
};
PlayerLayout.s_actionFuncMap = {
[GameMechineConfig.ACTION_NS_HEADCLICK] = "onPlayerHeadClick";
};
return PlayerLayout;
--[[
房间内个人信息模块
功能说明:
显示个人信息、发送互动道具、踢人、加好友、举报
开启了防作弊时,弹框里面的的银币、昵称等信息都隐藏,提示开启了防作弊
特殊逻辑:
个人信息的弹框一次只能显示一个,状态发送了变化并且弹框显示时,需要过滤非当前玩家的消息。
ep:显示了A玩家的个人信息弹框,收到B忘记登出的状态变化时,弹框不应该关闭。
举报功能调用:
1、创建举报模块的layer
local action = GameMechineConfig.ACTION_NS_CREATVIEW;
local data = {viewName = GameMechineConfig.VIEW_REPORT}
MechineManage.getInstance():receiveAction(action,data);
2、显示举报模块
action = GameMechineConfig.ACTION_NS_OPEN_REPORT;
local data = {uid=self.m_player.m_id,whichItem = _whichItem};
MechineManage.getInstance():receiveAction(action,data);
状态监听:
STATUS_NONE/STATUS_LOGOUT:非登陆状态,删除其他玩家的个人信息界面
STATUS_GAMEOVER:结算时关闭界面
动作监听:
ACTION_NS_HEADCLICK:点击了玩家头像,显示个人信息弹框界面
ACTION_NS_ADDFRIENDRESULT:收到加好友结果的消息,隐藏弹框
ACTION_SHOWPROPNIM:互动道具使用成功,隐藏弹框
ACTION_SHOWPROPNIM:互动道具使用成功,隐藏弹框
ACTION_NS_CLOSEPLAYERWND:发送消息,直接关闭弹框
]]
|
Args = {{
Login = '{0}',
Password = '{1}',
Character = '{2}'
}}
function Main()
if(AccountLoginUI and AccountLoginUI:IsVisible()) then
DefaultServerLogin(Args['Login'], Args['Password'])
elseif(CharacterSelectUI and CharacterSelectUI:IsVisible()) then
for charIndex = 0, GetNumCharacters() do
if (GetCharacterInfo(charIndex) == Args['Character']) then
CharacterSelect_SelectCharacter(charIndex)
EnterWorld()
end
end
end
end
Main()
|
Speedometer = {}
Speedometer.visible = false
local DRAW_POST_GUI = false
local SPEED_SECTORS_COUNT = 134
local screenWidth, screenHeight = guiGetScreenSize()
local originalSize = 400
local width, height = Utils.screenScale(250), Utils.screenScale(250)
local screenOffset = Utils.screenScale(20)
local fallbackTo2d = false
local textureShader
local renderTarget
local maskShader
local circleTextures = {}
local imageIndexPrev = 0
local font
local mileageFont
local circleTargetColor = {213, 0, 40}
local assetsTextures = {}
local targetRPM = 0
local rpm = 0
local function getVehicleSpeed()
if not localPlayer.vehicle then
return 0
end
return localPlayer.vehicle.velocity:getLength() * 180
end
local function getVehicleSpeedString()
local speed = getVehicleSpeed()
return string.format("%03d", speed)
end
local function getVehicleMileageString()
local mileage = localPlayer.vehicle:getData("mileage")
if not mileage then
return ""
end
return tostring(mileage) .. " km"
end
local function drawSpeedometer(x, y, width, height)
if localPlayer:getData("dpHUD.hideSpeedometer") then
return
end
-- Круг скорости
dxDrawImage(x, y, width, height, assetsTextures.circle, 0, 0, 0, tocolor(255, 255, 255, 200))
local speed = getVehicleSpeed()
-- "Тряска" оборотов
local randomRPM = math.min(500, speed * 2)
-- Подсчёт оборотов двигателя
targetRPM = Utils.calculateRPM(localPlayer.vehicle) + math.random() * randomRPM - randomRPM / 2
targetRPM = math.max(targetRPM, 0)
-- Плавное изменение оборотов
rpm = rpm + (targetRPM - rpm) * 0.1
local angle = math.max(-270, -rpm / 6000 * 270)
local imageIndex = math.min(math.floor(-angle / 90) + 1, 3)
angle = angle + 90 * (imageIndex - 1)
if imageIndexPrev ~= imageIndex then
maskShader:setValue("sPicTexture", circleTextures[imageIndex])
imageIndexPrev = imageIndex
end
maskShader:setValue("gUVRotAngle", math.rad(angle))
local circleColor = tocolor(circleTargetColor[1], circleTargetColor[2], circleTargetColor[3])
dxDrawImage(x, y, width, height, maskShader, 0, 0, 0, circleColor)
dxDrawImage(x, y, width, height, assetsTextures.numbers)
-- Скорость
local gear = getVehicleCurrentGear(localPlayer.vehicle)
if gear == 0 then
gear = "r"
end
if speed == 0 then
gear = "n"
end
dxDrawImage(x, y, width, height, assetsTextures["gear_" .. gear])
local mileageOffset = 45
dxDrawText(getVehicleMileageString(), x, y + mileageOffset, x + width, y + height + mileageOffset, tocolor(255, 255, 255, 255), 1, mileageFont, "center", "center")
dxDrawText(getVehicleSpeedString(), x, y, x + width, y + height, tocolor(255, 255, 255, 255), 1, font, "center", "bottom")
end
addEventHandler("onClientRender", root, function ()
if not Speedometer.visible then
return
end
if not localPlayer.vehicle then
return
end
if localPlayer.vehicle.controller ~= localPlayer then
return
end
if fallbackTo2d then
drawSpeedometer(screenWidth - width - screenOffset, screenHeight - height - screenOffset, width, height)
else
-- Отрисовка спидометра в renderTarget
dxSetRenderTarget(renderTarget, true)
drawSpeedometer(0, 0, originalSize, originalSize)
dxSetRenderTarget()
textureShader:setValue("sPicTexture", renderTarget)
dxDrawImage(
screenWidth - width - screenOffset,
screenHeight - height - screenOffset,
width,
height,
textureShader,
0, 0, 0,
tocolor(255, 255, 255, 200),
DRAW_POST_GUI
)
end
end)
function Speedometer.start()
if renderTarget then
return false
end
font = dxCreateFont("assets/fonts/speed.ttf", 90, false)
mileageFont = dxCreateFont("assets/fonts/speed.ttf", 22, false)
renderTarget = dxCreateRenderTarget(originalSize, originalSize, true)
textureShader = exports.dpAssets:createShader("texture3d.fx")
maskShader = exports.dpAssets:createShader("mask3d.fx")
local maskTexture = dxCreateTexture("assets/textures/speedometer/mask.png")
for i = 1, 3 do
circleTextures[i] = dxCreateTexture("assets/textures/speedometer/circle"..tostring(i)..".png")
end
maskShader:setValue("sMaskTexture", maskTexture)
maskShader:setValue("gUVRotCenter", 0.5, 0.5)
if not (renderTarget and textureShader) then
fallbackTo2d = true
outputDebugString("Speedometer: Fallback to 2d")
return
end
assetsTextures = {}
assetsTextures.circle = dxCreateTexture("assets/textures/speedometer/circle.png")
assetsTextures.numbers = dxCreateTexture("assets/textures/speedometer/numbers.png")
for i = 1, 5 do
assetsTextures["gear_"..i] = dxCreateTexture("assets/textures/speedometer/" .. i ..".png")
end
assetsTextures["gear_r"] = dxCreateTexture("assets/textures/speedometer/r.png")
assetsTextures["gear_n"] = dxCreateTexture("assets/textures/speedometer/n.png")
end
function Speedometer.setRotation(x, y, z)
if not x or not y then
return false
end
if not z then
z = 0
end
if not textureShader then
return false
end
dxSetShaderTransform(textureShader, x, y, z)
end
function Speedometer.setVisible(visible)
Speedometer.visible = not not visible
if visible then
circleTargetColor = {exports.dpUI:getThemeColor()}
end
end
addEvent("dpUI.updateTheme", false)
addEventHandler("dpUI.updateTheme", root, function ()
circleTargetColor = {exports.dpUI:getThemeColor()}
end)
|
--[[ ============================================================================================================
Author: Rook
Date: February 1, 2015
Called when Butterfly is cast. Removes the evasion from all Butterflies in the player's inventory and replaces
it with a single instance of bonus movespeed.
================================================================================================================= ]]
function item_butterfly_datadriven_on_spell_start(keys)
--Remove all evasion granted by Butterflies in the caster's inventory.
while keys.caster:HasModifier("modifier_item_butterfly_datadriven_evasion") do
keys.caster:RemoveModifierByName("modifier_item_butterfly_datadriven_evasion")
end
keys.caster:EmitSound("DOTA_Item.Butterfly")
keys.ability:ApplyDataDrivenModifier(keys.caster, keys.caster, "modifier_item_butterfly_datadriven_movespeed", nil)
end
--[[ ============================================================================================================
Author: Rook
Date: February 1, 2015
Called when the movespeed active modifier expires. Gives the caster has a stack of evasion for every
Butterfly in their inventory.
================================================================================================================= ]]
function modifier_item_butterfly_datadriven_movespeed_on_destroy(keys)
if not keys.caster:HasModifier("modifier_item_butterfly_datadriven_movespeed") then
--Reset all evasion granted by Butterflies in the caster's inventory before adding it back, just to be sure we end up with the right amount.
while keys.caster:HasModifier("modifier_item_butterfly_datadriven_evasion") do
keys.caster:RemoveModifierByName("modifier_item_butterfly_datadriven_evasion")
end
for i=0, 5, 1 do
local current_item = keys.caster:GetItemInSlot(i)
if current_item ~= nil then
if current_item:GetName() == "item_butterfly_datadriven" then
keys.ability:ApplyDataDrivenModifier(keys.caster, keys.caster, "modifier_item_butterfly_datadriven_evasion", {duration = -1})
end
end
end
end
end
--[[ ============================================================================================================
Author: Rook
Date: February 1, 2015
Called when a Butterfly is acquired. Adds an additional evasion modifier if Butterfly hasn't been cast recently.
================================================================================================================= ]]
function modifier_item_butterfly_datadriven_on_created(keys)
if not keys.caster:HasModifier("modifier_item_butterfly_datadriven_movespeed") then
keys.ability:ApplyDataDrivenModifier(keys.caster, keys.caster, "modifier_item_butterfly_datadriven_evasion", {duration = -1})
end
end
--[[ ============================================================================================================
Author: Rook
Date: February 1, 2015
Called when a Butterfly is dropped, sold, etc.. Remove an evasion modifier if Butterfly hasn't been cast recently.
================================================================================================================= ]]
function modifier_item_butterfly_datadriven_on_destroy(keys)
if not keys.caster:HasModifier("modifier_item_butterfly_datadriven_movespeed") then
keys.caster:RemoveModifierByName("modifier_item_butterfly_datadriven_evasion")
end
end
|
CatalogueClearAll();
CreateNewMetricProject();
local electcat =AddNewCatalogue("Electrical", "");
CatalogueAddType(electcat,'ELECTRICAL_JOINT','WIRE','WIRE_INSULATION','CABLE','ELECTRICAL_CONDUIT', 'ELECTRIC_APPLIANCE','ELECTRIC_LIGHT');
local waccat =AddNewCatalogue("Wires and Cables", electcat );
CatalogueAddType(waccat , 'ELECTRICAL_JOINT','WIRE','WIRE_INSULATION','CABLE','ELECTRICAL_CONDUIT');
local elccat =AddNewCatalogue("Electrical Connections", waccat );
CatalogueAddType(elccat, 'ELECTRICAL_JOINT');
local wijcat =AddNewCatalogue( " Wire Joints", elccat);
CatalogueAddType(wijcat , 'ELECTRICAL_JOINT');
local wirecat =AddNewCatalogue("Wires", waccat);
CatalogueAddType( wirecat, 'WIRE');
local winscat =AddNewCatalogue("Wire Insulations", waccat);
CatalogueAddType(winscat, 'WIRE_INSULATION');
local cabcat =AddNewCatalogue("Cables", waccat);
CatalogueAddType(cabcat, 'CABLE');
local eleconcat =AddNewCatalogue("Electrical Conduits", waccat);
CatalogueAddType(eleconcat, 'ELECTRICAL_CONDUIT');
local theccat =AddNewCatalogue("Thin-Wall Electrical Conduits", eleconcat);
CatalogueAddType(theccat, 'ELECTRICAL_CONDUIT');
local eapcat =AddNewCatalogue("Electric Appliances", electcat );
CatalogueAddType(eapcat, 'ELECTRIC_APPLIANCE','ELECTRIC_LIGHT');
local geacat =AddNewCatalogue( "Generic Electric Appliances", eapcat);
CatalogueAddType(geacat , 'ELECTRIC_APPLIANCE');
local elicat =AddNewCatalogue("Electric Lights", eapcat);
CatalogueAddType(elicat, 'ELECTRIC_LIGHT');
local elisubcat =AddNewCatalogue( "Lights", elicat);
CatalogueAddType(elisubcat , 'ELECTRIC_LIGHT');
local reclight =AddNewCatalogue( "Rectangular Lights", elisubcat);
CatalogueAddType(reclight , 'ELECTRIC_LIGHT');
local vcyllight =AddNewCatalogue( "Vertical Cylindrical Lights", elisubcat);
CatalogueAddType(vcyllight , 'ELECTRIC_LIGHT');
local hcyllight =AddNewCatalogue( "Horizontal Cylindrical Lights", elisubcat);
CatalogueAddType(hcyllight , 'ELECTRIC_LIGHT');
local sphlight =AddNewCatalogue( "Spherical Lights", elisubcat);
CatalogueAddType( sphlight , 'ELECTRIC_LIGHT');
local mats = {};
InputClear();
InputAddPoint(0,0,0);
for tag in CreateElement('ELECTRICAL_JOINT') do
local ele_type = GetElementType(tag);
if ele_type=="ELECTRICAL_JOINT" then
SetProperty(tag,'NAME','Wire Joint')
SetProperty(tag,'ELECTRICAL_JOINT_TYPE',0)
SetProperty(tag,'AUTOSIZE', false)
SetProperty(tag,'OUTSIDE_DIAMETER',0.05)
SetProperty(tag,'WALL_THICKNESS' ,0.001)
SetProperty(tag,'AUTOSIZE', true)
SetProperty(tag,'PART_NUMBER','WJ-001' );
local newprod1 = ProductCreateFromElement(wijcat,tag);
end
end
local wireInsDesc= GetTypeDescription('WIRE_INSULATION');
local mats = {};
table.insert(mats, "S671");
table.insert(mats, "S710");
table.insert(mats, "S740");
table.insert(mats, "S741");
table.insert(mats, "S750");
table.insert(mats, "S780");
table.insert(mats, "S800");
table.insert(mats, "S801");
table.insert(mats, "S675");
local newprod1= "";
InputClear();
InputAddPoint(0,0,0);
for tag in CreateElement('WIRE_INSULATION')
do
local ele_type = GetElementType(tag);
if ele_type=="WIRE_INSULATION" then
SetProperty(tag,'KEYWORD_1',wireInsDesc);
for mati,material in ipairs(mats) do
MaterialClearCollection();
MaterialAddtoCollection("insulationMat",material)
local matName = MaterialGetProperty("insulationMat",'NAME');
SetProperty(tag,'KEYWORD_2',matName);
local winssubcat =AddNewCatalogue( matName.." Wire Insulations", winscat);
CatalogueAddType(winssubcat , 'WIRE_INSULATION');
for ii = 1,10,1 do
local insThk = ii/64;
SetProperty(tag,'NAME',wireInsDesc.."- "..matName.."- "..insThk.." in." );
SetProperty(tag,'PART_NUMBER','WIG-'.. mati.."-"..ii);
SetLayersCount(tag, 1)
SetLayerMaterialID(tag,0,material);
SetLayerThickness(tag,0,insThk*0.0254);
newprod1 = ProductCreateFromElement(winssubcat ,tag);
end
end
end
end
local mats = {};
table.insert(mats, "S90");
table.insert(mats, "S170");
local newprod1= "";
local wireGauges = GetWireGauges();
InputClear();
InputAddPoint(0,0,0);
InputAddPoint(1,0,0);
for tag in CreateElement('WIRE')
do
local ele_type = GetElementType(tag);
if ele_type=="WIRE" then
for mati,material in ipairs(mats) do
MaterialClearCollection();
MaterialAddtoCollection("WireMat",material)
local matName = MaterialGetProperty("WireMat",'NAME');
SetProperty(tag,'KEYWORD_2',matName);
SetProperty(tag,'CORE_MATERIAL',material );
local wiresubcat =AddNewCatalogue( matName.." Wires", wirecat);
CatalogueAddType(wiresubcat , 'WIRE');
local gindex = 0;
for gi,gv in ipairs(wireGauges ) do
local AWGname = gv[1];
local AWGdia = gv[2];
SetProperty(tag,'NAME',GetTypeDescription('WIRE')..'- '.. matName.."- "..AWGname );
SetProperty(tag,'PART_NUMBER','Wire '..AWGname );
SetProperty(tag,'WIRE_GAUGE' ,gindex );
gindex = gindex+1;
newprod1 = ProductCreateFromElement(wiresubcat ,tag);
end
end
end
end
local newprod1= "";
InputClear();
InputAddPoint(0,0,0);
InputAddPoint(1,0,0);
for tag in CreateElement('CABLE') do
local ele_type = GetElementType(tag);
if ele_type=="CABLE" then
SetProperty(tag,'KEYWORD_1','Electrical Cable');
for i=2,10,1 do
SetProperty(tag,'CORES_COUNT',i);
SetProperty(tag,'OUTSIDE_DIAMETER',i*0.005);
SetProperty(tag,'KEYWORD_2',i..' Cores');
SetProperty(tag,'NAME',i..' Cores Cable' );
SetProperty(tag,'PART_NUMBER','CABLE'..i );
RefreshElement(tag);
newprod1 = ProductCreateFromElement(cabcat,tag);
end
end
end
local newprod1= "";
InputClear();
InputAddPoint(0,0,0);
InputAddPoint(1,0,0);
for tag in CreateElement('ELECTRICAL_CONDUIT') do
local ele_type = GetElementType(tag);
if ele_type=="ELECTRICAL_CONDUIT" then
SetProperty(tag,'KEYWORD_1','Electrical Conduit');
SetProperty(tag,'KEYWORD_2','thin-wall');
SetProperty(tag,'OUTSIDE_DIAMETER',0.0179);
SetProperty(tag,'WALL_THICKNESS',0.00107);
SetProperty(tag,'NAME','1/2in in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT16EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.0234);
SetProperty(tag,'WALL_THICKNESS',0.00125);
SetProperty(tag,'NAME','3/4in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT21EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.0295);
SetProperty(tag,'WALL_THICKNESS',0.00145);
SetProperty(tag,'NAME','1in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT27EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.0384);
SetProperty(tag,'WALL_THICKNESS',0.00165);
SetProperty(tag,'NAME','1 1/4in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT35EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.0442);
SetProperty(tag,'WALL_THICKNESS',0.00165);
SetProperty(tag,'NAME','1 1/2in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT41EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.0558);
SetProperty(tag,'WALL_THICKNESS',0.00165);
SetProperty(tag,'NAME','2in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT53EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.073);
SetProperty(tag,'WALL_THICKNESS',0.00183);
SetProperty(tag,'NAME','2 1/2in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT63EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.0889);
SetProperty(tag,'WALL_THICKNESS',0.00183);
SetProperty(tag,'NAME','3in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT78EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.1016);
SetProperty(tag,'WALL_THICKNESS',0.00211);
SetProperty(tag,'NAME','3 1/2in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT91EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
SetProperty(tag,'OUTSIDE_DIAMETER',0.1143);
SetProperty(tag,'WALL_THICKNESS',0.00211);
SetProperty(tag,'NAME','4in. thin-wall Electrical conduit');
SetProperty(tag,'PART_NUMBER','EL_CONDUIT103EMT');
newprod1 = ProductCreateFromElement(theccat,tag);
end
end
local mats = {};
InputClear();
InputAddPoint(0,0,0);
for tag in CreateElement('ELECTRIC_APPLIANCE') do
local ele_type = GetElementType(tag);
if ele_type=="ELECTRIC_APPLIANCE" then
SetProperty(tag,'LENGTH',0.75 );
SetProperty(tag,'WIDTH',0.75 );
SetProperty(tag,'HEIGHT',0.75 );
SetProperty(tag,'NAME','Generic Rectangular Electric Appliance')
SetProperty(tag,'APPLIANCE_TYPE','GENERIC_ELECTRIC_APPLIANCE' );
SetProperty(tag,'PART_NUMBER','EAG-001' );
SetProperty(tag,'SHAPE',0 );
local newprod1 = ProductCreateFromElement(geacat,tag);
SetProperty(tag,'NAME','Generic Vertical Cylindrical Electric Appliance')
SetProperty(tag,'PART_NUMBER','EAG-002' );
SetProperty(tag,'SHAPE',1 );
SetProperty(tag,'DIAMETER',0.75 );
local newprod1 = ProductCreateFromElement(geacat,tag);
SetProperty(tag,'NAME','Generic Horizontal Cylindrical Electric Appliance')
SetProperty(tag,'PART_NUMBER','EAG-003' );
SetProperty(tag,'SHAPE',2 );
local newprod1 = ProductCreateFromElement(geacat,tag);
SetProperty(tag,'NAME','Generic Spherical Electric Appliance')
SetProperty(tag,'PART_NUMBER','EAG-004' );
SetProperty(tag,'SHAPE',3 );
local newprod1 = ProductCreateFromElement(geacat,tag);
end
end
local mats = {};
InputClear();
InputAddPoint(0,0,0);
for tag in CreateElement('ELECTRIC_LIGHT') do
local ele_type = GetElementType(tag);
if ele_type=="ELECTRIC_LIGHT" then
SetProperty(tag,'LIGHT_TYPE',2)
SetProperty(tag,'APPLIANCE_TYPE','GENERIC_LIGHT' );
SetProperty(tag,'LIGHT_SHAPE',1)
SetProperty(tag,'NAME','Rectangular Electric Light, 5 cm x 5 cm x 2 cm')
SetProperty(tag,'SHAPE',0)
SetProperty(tag,'LENGTH',0.05)
SetProperty(tag,'WIDTH',0.05)
SetProperty(tag,'HEIGHT',0.02)
SetProperty(tag,'PART_NUMBER','ELR-001' );
local newprodr0 = ProductCreateFromElement(reclight,tag);
SetProperty(tag,'NAME','Rectangular Electric Light, 10 cm x 10 cm x 5 cm')
SetProperty(tag,'LENGTH',0.1)
SetProperty(tag,'WIDTH',0.1)
SetProperty(tag,'HEIGHT',0.05)
SetProperty(tag,'PART_NUMBER','ELR-002' );
local newprodr1 = ProductCreateFromElement(reclight,tag);
SetProperty(tag,'NAME','Vertical Cylindrical Electric Light, 10 cm dia. x 5 cm')
SetProperty(tag,'SHAPE',1)
SetProperty(tag,'DIAMETER',0.1)
SetProperty(tag,'HEIGHT',0.05)
SetProperty(tag,'PART_NUMBER','ELCV-001' );
local newprodvc0 = ProductCreateFromElement(vcyllight,tag);
SetProperty(tag,'NAME','Vertical Cylindrical Electric Light, 20 cm dia. x 10 cm H')
SetProperty(tag,'DIAMETER',0.2)
SetProperty(tag,'HEIGHT',0.1)
SetProperty(tag,'PART_NUMBER','ELCV-002' );
local newprodvc1 = ProductCreateFromElement(vcyllight,tag);
SetProperty(tag,'SHAPE',2)
SetProperty(tag,'NAME','Horizontal Cylindrical Electric Light, 10 cm dia. x 5 cm L')
SetProperty(tag,'DIAMETER',0.1)
SetProperty(tag,'LENGTH',0.05)
SetProperty(tag,'PART_NUMBER','ELCH-001' );
local newprodhc0 = ProductCreateFromElement(hcyllight,tag);
SetProperty(tag,'NAME','Horizontal Cylindrical Electric Light, 20 cm dia. x 10 cm L')
SetProperty(tag,'DIAMETER',0.2)
SetProperty(tag,'LENGTH',0.1)
SetProperty(tag,'PART_NUMBER','ELCH-002' );
local newprodhc1 = ProductCreateFromElement(hcyllight,tag);
SetProperty(tag,'SHAPE',3)
SetProperty(tag,'NAME','Spherical Electric Light, 5 cm dia.')
SetProperty(tag,'DIAMETER',0.05)
SetProperty(tag,'PART_NUMBER','ELSP-001' );
local newprodsp2 = ProductCreateFromElement(sphlight ,tag);
SetProperty(tag,'NAME','Spherical Electric Light, 10 cm dia.')
SetProperty(tag,'DIAMETER',0.1)
SetProperty(tag,'PART_NUMBER','ELSP-002' );
local newprodsp1 = ProductCreateFromElement(sphlight ,tag);
end
end
CatalogueSave( electcat, "Electrical catalogue");
ListCatalogues();
|
-- features marked as "TODO" - are long-term goals,
-- that will be implemented after other features complete and working as intended.
-- example config for sandbox and exec profile
-- following global identifiers (tables) reserved for system use:
-- loader (used by bash-lua-helper), some helper stuff: loader.workdir - base directory of this config file, loader.path.combine(path1,path2,...) - combine path components
-- config (defined by sandboxer, store some dynamic configuration parameters for current session)
-- profile (defined by sandboxer at post-script, will overwrite same define made here)
-- defaults (some sane defaults for current linux distribution to simplify config file creation and improve it's portability across different linux distributions. see sandboxer.pre.lua for more info)
-- dbus (internal profile for dbus feature support)
-- try not to redefine this identifiers accidentally
-- TODO: add some more checks
-- some tunable defaults:
-- base directory: tunables.basedir
-- you may change this in case of debug.
-- default value is config.ctldir - automatically generated sandbox directory unique to config file, located in /tmp (or $TMPDIR if set).
-- base directory for all internal sandbox control stuff, used by sandboxer system,
-- this directory will be automatically created, populated and cleaned up by sandboxer system.
-- this directory MUST be unique for each sandbox config file, and should be placed on tmpfs.
-- this directry may be automatically cleaned up on sandbox shutdown, so do not store any persistent stuff here.
-- example:
-- tunables.basedir=config.ctldir -- default
-- tunables.basedir=loader.path.combine(loader.workdir,"basedir-"..config.sandbox_uid)
-- chroot construction dir: tunables.chrootdir
-- used by builtin defaults.commands and default.bwrap defines.
-- this directory is set (chdir) before running sandbox.setup.commands blocks, and when applying some features.
-- this directory may be deleted on sandbox shutdown, if it is located inside tunables.basedir (default).
-- you can change this parameter if you want to use your own persistent\non-standard chroot and\or perform some dynamic changes with it.
-- example:
-- tunables.chrootdir=loader.path.combine(tunables.basedir,"chroot") -- default
-- tunables.chrootdir=loader.path.combine(loader.workdir,"chroot-"..config.sandbox_uid)
-- chroot construction dir: tunables.configdir
-- used by builtin defaults.commands and default.bwrap defines.
-- this directory may be deleted on sandbox shutdown, if it is located inside tunables.basedir (by default).
-- you can change this parameter if you want to debug dynamic configudation creation, or for use with your own generation routines.
-- and also want to use some builtin commands to perform some dynamic setup on each run.
-- example:
-- tunables.configdir=loader.path.combine(loader.workdir,"dynconfig-"..config.sandbox_uid)
-- user id: tunables.uid
-- numeric user id, used in various sandbox.setup.commands and when applying some features
-- may be used when launching bwrap with custom uid\gid option
-- default value - user id of user launched sandboxer.sh script
-- example:
-- tunables.uid=config.uid -- default
-- group id id: tunables.gid
-- similiar to user id (above)
-- default value - effective gid of user launched sandboxer.sh script
-- example:
-- tunables.gid=config.gid -- default
-- username, used inside sandbox: tunables.user
-- username, string, used by some sandbox.setup.commands blocks (for example defaults.commands.pwd command)
-- default value - sandboxer
-- example:
-- tunables.user="sandboxer" -- default
-- persistent directory for userdata: tunables.datadir
-- used by some sandbox.setup.commands and sandbox.bwrap blocks.
-- stores user's home and configs, persistent cache, persistent tmp (/var/tmp)
-- default value - unique directory based on config file name + it's fs location.
-- this directory created by default in the same directory as current config file.
-- example:
-- tunables.datadir=loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid) -- default
-- tunables.datadir=loader.path.combine(os.getenv("HOME"),"sandboxer-"..config.sandbox_uid)
-- etc directory path that will a source path for some construction commands
-- that used to dynamically build etc directory for sandbox.
-- by default it is equal to host etc directory location (/etc).
-- you may override this tunable parameter if you want to create dynamic etc directory for sandbox from your own source
-- (separate extracted rootfs directory, for example)
-- tunables.etchost_path="/etc"
-- TODO: add descriptions for features tunables:
-- tunables.features.dbus_search_prefix
-- tunables.features.xpra_search_prefix
-- tunables.features.xpra_show_tray
-- tunables.features.xpra_use_mmap
-- tunables.features.gvfs_fix_search_prefix
-- tunables.features.gvfs_fix_search_locations
-- tunables.features.gvfs_fix_mounts
-- tunables.features.x11util_build
-- tunables.features.x11util_build_alt
-- tunables.features.x11util_enable
-- tunables.features.pulse_skip_sanity_checks
-- tunables.features.pulse_force_disable_shm -- see this bug (at the end, it is a bug with pid namespaces): https://bugs.freedesktop.org/show_bug.cgi?id=92141
-- tunables.features.pulse_env_alsa_config -- path to alsa config file, special values: "skip", "unset"
-- if you changed ANY of tunable defaults (above), you MUST run defaults.recalculate() function here,
-- this will update and recalculate all deps used by other defaults definitions and setup commands.
-- uncomment this if you changed anything above:
-- defaults.recalculate()
sandbox={
-- sandbox features and host-integration stuff that require some complex or dynamic preparations.
-- features are enabled in order of appearance, feature name may contain only lowercase letters, numbers and underscores.
features={
"dbus", -- run dbus-session instance inside sandbox, and allow other sandbox sessions to use it
"gvfs_fix", -- fix gvfs setup inside sandbox, and strip down it's features to bare minimum. TODO: find out what removed gvfs features works inside sandbox and reenable it
"pulse", -- make pass-through of running pulseaudio daemon from host to sandbox env. may be used together with defaults.mounts.devsnd_mount if you also need alsa and mixer functionality
"x11host", -- make pass-through for host x11 env to sandbox. HIGHLY UNSECURE. NOT FOR RUNNING UNTRUSTED CODE.
--"xpra", -- make x11 pass-through with xpra software. FOR RUNNING X11 APPS IN MORE SECURE MANNER than with x11host feature.
-- you must select only one of x11 forwarding method - x11host or xpra. Requires dbus feature to be activated before.
-- xpra software with server-mode support must be installed on host (and inside sandbox - when using external chroot).
-- TODO: add some additional checks for xpra in sandbox sanity.
-- (for example, xauth utility is needed for official xpra installation on debian stretch, but it will be not installed by default)
"envfix", -- fix final env variables in sandbox - change all links to host home dir to sandboxed home dir
},
-- main sandbox setup parameters such as:
-- location of control and temporary directories;
-- persistent user data locations;
-- some chroot construction parameters, dynamic creation and fillup of data directories
-- commander\executor options
--
-- this table and most of it's parameters are mandatory
setup={
-- security key used in hash calculation process for all communications between sandbox and host
-- for now it is just a 32-bit unsigned number, it may change in future
security_key=42, -- optional
-- select executor build for use inside sandox. builds other than "default" may be downloaded with sandboxer-download-extra.sh script
executor_build="default", -- optional
-- perform control directory cleanup after all sandbox sessions are closed and sandbox is destroyed.
-- may be disabled for debug purposes. may also decrease time to full sandbox startup that is performed when no sessions currently running
cleanup_on_exit=true, -- optional, will be set automatically to true if missing.
-- table with commands, that will be run to create and prepare chroot.
-- commands defined by "groups", each group is a table with "strings" that will be executed by sandboxer.sh script.
-- command-groups executed in order of appearence.
-- current dir will be set to chroot directory (located at sandbox.setup.basedir/chroot) before process any command group.
-- command-groups are executed by using eval in a forked context, so there is no risk to corrupt main sandboxer.sh state.
-- this list will execute in parallel with other preparation tasks made by main sandboxer.sh script.
-- exit code from command group ($?) is examined, sandboxer.sh will automatically terminate is case of errors ($?!=0)
-- this mechanism should be used to dynamically create configuration files and other things to mount inside sandbox later.
-- there are several "builtin" commands that sandboxer system supports. all such commands are listed here with it's brief descriptions.
-- defaults commands may be changed in future, and may vary depending on your distribution or some general setup options above.
commands={-- optional
--user command example:
-- {'mkdir -p "etc"', 'touch "hello"'}
defaults.commands.etc_min, -- copy minimal config to tunables.chrootdir, should not include system, kernel, and other machine stuff
defaults.commands.etc_dbus, -- copy dbus config to tunables.chrootdir
defaults.commands.etc_x11, -- copy x11 config to tunables.chrootdir
defaults.commands.etc_udev, -- copy /etc/udev config to tunables.chrootdir. may be needed for some apps, may leak some information about current hardware config
-- defaults.commands.etc_full, -- copy full /etc to to tunables.chrootdir
defaults.commands.passwd, -- generate default /etc/passwd and /etc/group files with "sandbox" user (mapped to current uid)
defaults.commands.home, -- create userdata/home at this config file directory, if missing
defaults.commands.home_gui_config, -- copy and process supported gui-toolkits configuration from host env. this command must go after defaults.commands.home.
defaults.commands.machineid, -- generate machine id for sandbox, and place it to constructed etc dir, id value rely on host machine-id and sandbox_uid
--defaults.commands.machineid_static, -- generate machine id for sandbox, and place it to constructed etc dir. id value rely only on sandbox_uid
--defaults.commands.machineid_host_etc, -- generate machine id (if missing) and place it to HOST /etc directory. may be used when creating sandbox on top of external chroot.
defaults.commands.resolvconf, -- generate resolvconf file. for now only copy resolv.conf from /etc. TODO: add options for generation resolv.conf
defaults.commands.hosts, -- generate (copy) hosts file and place it to dynamic etc directory
defaults.commands.hostname, -- generate (copy) hostname file and place it to dynamic etc directory
-- defaults.commands.machineid_host_etc, -- generate machine id for sandbox if not exist already, and place it to host etc dir specified by tunables.etchost_path tubalble parameter, useful when working with sandbox based on custom rootfs.
defaults.commands.var_cache, -- create userdata/cache at this config file directory, if missing
defaults.commands.var_tmp, -- create userdata/tmp at this config file directory, if missing
},
-- blacklist for env variables.
-- all variables from this list will be unset on start
env_blacklist={
defaults.env.blacklist_main,
defaults.env.blacklist_audio,
defaults.env.blacklist_desktop,
defaults.env.blacklist_home,
defaults.env.blacklist_xdg,
},
-- whitelist for env variables. all env variables not in list will be unset in sandboxed env
-- opposite to blacklist, blacklist processing will be skipped if env_whitelist is defined and enabled (even if it is empty!)
env_whitelist={
enabled=false, -- optional, to quick enable\disable whitelist logic. applied only if true
--"HOST",
--"INPUTRC",
},
-- set custom env variables,
env_set={
-- setup user env, essential for normal operation (especially, for shells and scripts)
-- use this when "defaults.commands.passwd" used when constructing sandbox (recommended)
-- also define some env variables normally only defined when launching "login" shell
-- (launching login shell is usually overkill for sandbox and it may also expose some unneded env variables unset earlier by blacklist feature)
defaults.env.set_home,
defaults.env.set_xdg_runtime,
},
-- define mounts and directories to create inside sandbox, every "mount" entry is a subtable
-- with same format as bwrap table entries (see below)
-- TODO: add detailed info about mount entries, valid mount operations and other.
-- for now see sandboxer.pre.lua source file for example mount entires (defaults.mounts)
mounts={
defaults.mounts.system_group,
-- defaults.mounts.run_dir, -- included in "system_group"
-- defaults.mounts.tmp_dir, -- included in "system_group"
-- defaults.mounts.proc_mount, -- included in "system_group". mount /proc prepared by bwrap (according by unshare_* options)
-- defaults.mounts.dev_mount, -- included in "system_group". mount /dev, prepared and filtered by bwrap
-- defaults.mounts.var_dir, -- included in "system_group"
defaults.mounts.xdg_runtime_dir,
-- make some essential mounts
defaults.mounts.home_mount, -- mount directory with persistent user-data to /home, created with "defaults.commands.home" (recommended)
defaults.mounts.var_cache_mount, -- mount directory with persistent cache to /var/cache, created with "defaults.commands.var_cache" (recommended)
defaults.mounts.var_tmp_mount, -- mount directory with persistent cache to /var/cache, created with "defaults.commands.var_tmp" (recommended)
defaults.mounts.etc_ro_mount, -- readonly mount etc directory from tunables.chrootdir, constructed with defaults.commands.etc_* commands or created manually
-- defaults.mounts.etc_rw_mount, -- read-write mount etc directory from tunables.chrootdir, constructed with defaults.commands.etc_* commands or created manually
-- defaults.mounts.host_etc_mount, -- readonly mount host etc directory, may be overriden by changing tunables.etchost_path tunable
-- defaults.mounts.passwd_mount, -- readonly mount passwd and group files automatically generated with defaults.commands.passwd. for use with host etc mount entry above, not needed when using commands for dynamically generate etc directory.
-- other mounts, also essential for normal operation
-- defaults.mounts.dbus_system_mount, -- mount dbus system socket from host, may possess a potential security risk.
-- defaults.mounts.resolvconf_mount, -- mount custom resolv.conf, only needed if you NOT using defaults.mounts.etc_ro_mount
-- defaults.mounts.hosts_mount, -- only needed if you NOT using defaults.mounts.etc_ro_mount
-- defaults.mounts.hostname_mount, -- only needed if you NOT using defaults.mounts.etc_ro_mount
defaults.mounts.devsnd_mount, -- mount /dev/snd to allow alsa, may be not needed for pure pulseadio client to work
defaults.mounts.devdri_mount, -- mount /dev/dri to allow hardware acceleration
defaults.mounts.devinput_mount, -- mount /dev/input. may be needed for some apps to detect input devices (joystics?)
-- TODO: add mounts only to some parts of sys directory only needed for particular apps to work
defaults.mounts.sys_mount, -- mount /sys directory (readonly). will leak sensitive information about hw config, but may be needed for some complex multimedia apps to work. needed for mesa and 3d to work.
-- defaults.mounts.devshm_mount, -- mount /dev/shm. if mounted - disables posix-shm isolation (not to be confused with sys.v-shm). may be needed for some applications to work. unsecure - exposes shared memory buffers from other host applications to sandbox. may also break host pulseadio daemon if it's version is < than 9.0 when used with defaults.bwrap.unshare_pid option.
defaults.mounts.host_bin_mount, -- readonly mount host /bin directory
defaults.mounts.host_sbin_mount, -- readonly mount host /sbin directory
defaults.mounts.host_usr_mount, -- readonly mount host /usr directory
defaults.mounts.host_lib_mount, -- readonly mount host /lib directory
defaults.mounts.host_lib64_mount, -- readonly mount host /lib64 directory
defaults.mounts.host_var_lib_mount, -- readonly mount host /var/lib directory. not required for most apps. may expose some system configuration.
-- defaults.mounts.bin_ro_mount, -- readonly mount bin directory from tunables.chrootdir, constructed manually
-- defaults.mounts.sbin_ro_mount, -- readonly mount sbin directory from tunables.chrootdir, constructed manually
-- defaults.mounts.usr_ro_mount, -- readonly mount usr directory from tunables.chrootdir, constructed manually
-- defaults.mounts.lib_ro_mount, -- readonly mount lib directory from tunables.chrootdir, constructed manually
-- defaults.mounts.lib64_ro_mount, -- readonly mount lib64 directory from tunables.chrootdir, constructed manually
-- defaults.mounts.bin_rw_mount, -- mount bin directory from tunables.chrootdir, constructed manually
-- defaults.mounts.sbin_rw_mount, -- mount sbin directory from tunables.chrootdir, constructed manually
-- defaults.mounts.usr_rw_mount, -- mount usr directory from tunables.chrootdir, constructed manually
-- defaults.mounts.lib_rw_mount, -- mount lib directory from tunables.chrootdir, constructed manually
-- defaults.mounts.lib64_rw_mount, -- mount lib64 directory from tunables.chrootdir, constructed manually
}
},
-- parameters for bwrap utility. parameter string should be wrapped to subtable, and applied acording to its priorities (see below)
-- you must add mount commands here to form root directory layout for sandboxed application.
bwrap={
--[[
-- example parameter entry subtable
{
-- entry priority. optional.
-- parameter-entries sorted by its prio (0<=prio<=100). 0 goes first, 100 goes last.
-- defaut priority is 100, you MUST define different priority to entries that must be applied in correct order
-- for entries with equal priorities - same order is not guaranteed even if it defined in correct order
prio=50,
-- mandatory fields below.
-- this parameters will be applied to bwap in order of appearence.
-- first parameter must be a string. because all bwrap command line parameters prefixed with "--"
-- there is no need to prepend "--" to this field, it will be done automatically
-- TODO: add validation to supported bwrap parameters
"ro-bind",
-- all other fields - optional arguments for selected bwrap parameter
loader.path.combine(loader.workdir,"test"), -- directory "test" at basedir of this config file.
"/test" -- mount point at sandbox
}, ]]--
-- there are builtin "defaults" for most of bwrap commands.
-- theese defaults covers most of the bwrap parameters needed for proper sanbox function.
-- if you change any tunable parameter at the beginning of this file,
-- defaults will be also tuned according to your changes
-- (do not forget to run defaults.recalculate() function (see top of config file for more info)
defaults.bwrap.unshare_user,
defaults.bwrap.unshare_ipc, -- use IPC namespace inside sandbox. May break X11 applications when using x11host feature (x11xpra feature should work).
defaults.bwrap.unshare_pid, -- use separate pid namespace. recommended. but it may break host pulseaudio < v9.0 when using "pulse" feature (to provide pulseudio pass-through) and defaults.mounts.devshm_mount option (see above).
-- defaults.bwrap.unshare_net, -- separate network namespace, not much use right now - it will create only lo interface, may be useful to isolate apps from network.
defaults.bwrap.unshare_uts,
-- defaults.bwrap.unshare_cgroup,
defaults.bwrap.uid, -- set uid inside sandbox according to tunables.uid setting. if you manually change tunables.uid - use of this entry is mandatory.
defaults.bwrap.gid, -- set gid inside sandbox according to tunables.gid setting. if you manually change tunables.gid - use of this entry is mandatory.
}
}
-- configuration for applications to run inside this sandbox
-- must be a table with any name that is not already defined for service needs (see this list at the top of this file)
-- some parameters are mandatory, some is optional
shell={
exec="/bin/bash", -- mandatory, absolute path to binary inside sandbox
path="/", -- optional, chdir to this directory inside sandbox before exec
args=loader.args, -- optional, argument-list for launched binary inside sandbox. loader.args table contain extra arguments appended to sandboxer.sh
env_unset={"TERM"}, -- optional, variables list to unset
env_set= -- optional, variables list to set
{
{"TERM",os.getenv("TERM")},
},
term_signal=defaults.signals.SIGHUP, -- optional, number. signal, to gracefully terminate binary. will be sent to binary and all other processes from it's session (childs)
term_child_only=false, -- optional, default value is false. if set to true - send term_signal and terminate only child process started by exec profile, instead of whole process tree started by this exec profile.
term_orphans=false, -- optional, default value is false. if set to true - terminate all orphan processes left when this and other exec profiles complete its execution. termination performed by master executor after some timeout if no exec profiles running. setting this option to true may interfere with other exec profiles - it will terminate orphan processes left from any exec profile.
attach=true, -- optional, default value is false. if true - start in attached mode, commander module and sandboxer.sh script will not terminate and it will link stdin\stdout from sandboxed process and current terminal, so user can control running application.
pty=true, -- optional, default value is false. allocate new pty to executor process in sandbox and target process. useful to run interactive shells inside sandbox.
exclusive=false, -- optional, default value is false. exclusive mode - will create io channels with name match to profile name instead of random. refuse to launch this profile if already running
term_on_interrupt=true, -- optional, default value is false. if set to true perform grace termination with term_signal when detecting SIGHUP or SIGINT signals from host terminal window (when closing terminal window, for example).
-- optional section for desktop file creator script
desktop={
name = "Shell for example sandbox",
comment = "shell for sandbox uid "..config.sandbox_uid,
icon = "terminal",
--mimetype = "text/x-sandboxer-test",
terminal = true,
startupnotify = false,
-- optional info about mime xml package file deploy. for use with desktop file creator
mime =
{
-- for each string it will create <stringname>.xml file at ~/.local/share/mime and run update-mime-database
test='<?xml version="1.0" encoding="UTF-8"?>\
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">\
<mime-type type="text/x-sandboxer-test">\
<comment>Sandboxer Test File</comment>\
<icon name="Text"/>\
<glob-deleteall/>\
<glob pattern="*.sandboxer.test"/>\
</mime-type>\
</mime-info>'
},
},
}
-- another example profile. do not allocate new pty, just connect stdout\stderr\stdin
shell_no_pty={
exec="/bin/bash",
path="/",
args=loader.args,
env_unset={"TERM"},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=false,
log_stderr=loader.path.combine(loader.workdir,"example.err.log"),
log_stdout=loader.path.combine(loader.workdir,"example.out.log"),
}
|
local function setup()
require("toggleterm").setup({
open_mapping = require("mappings").functions_terminal,
})
end
return {
setup = setup,
}
|
local SpatialDownSampling, parent = torch.class('nn.SpatialDownSampling', 'nn.Module')
local help_desc = [[
Applies a 2D down-sampling over an input image composed of
several input planes. The input tensor in forward(input) is
expected to be a 3D tensor (nInputPlane x width x height).
The number of output planes will be the same as nInputPlane.
The downsampling is done using the simple average
technique. For interpolated (bicubic) downsampling, use
nn.SpatialReSampling().
If the input image is a 3D tensor nInputPlane x width x height,
the output image size will be nInputPlane x owidth x oheight where
owidth = floor(width/rW)
oheight = floor(height/rH) ]]
function SpatialDownSampling:__init(...)
parent.__init(self)
-- get args
xlua.unpack_class(self, {...}, 'nn.SpatialDownSampling', help_desc,
{arg='rW', type='number', help='ratio width', req=true},
{arg='rH', type='number', help='ratio height', req=true})
end
function SpatialDownSampling:updateOutput(input)
if (input:size(2) / self.rH) < 1 then
error('input too small in dimension 2')
elseif (input:size(3) / self.rW) < 1 then
error('input too small in dimension 3')
end
self.output:resize(input:size(1), math.floor(input:size(2) / self.rH),
math.floor(input:size(3) / self.rW))
input.nn.SpatialDownSampling_updateOutput(self, input)
return self.output
end
function SpatialDownSampling:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input)
input.nn.SpatialDownSampling_updateGradInput(self, gradOutput)
return self.gradInput
end
|
--[[customData = {
type = "custom",
reference = "MyAddonCustomControl", --(optional) unique name for your control to use as reference
refreshFunc = function(customControl) end, --(optional) function to call when panel/controls refresh
width = "full", --or "half" (optional)
} ]]
local widgetVersion = 6
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("custom", widgetVersion) then return end
local wm = WINDOW_MANAGER
local tinsert = table.insert
local function UpdateValue(control)
if control.data.refreshFunc then
control.data.refreshFunc(control)
end
end
local MIN_HEIGHT = 26
function LAMCreateControl.custom(parent, customData, controlName)
local control = LAM.util.CreateBaseControl(parent, customData, controlName)
local width = control:GetWidth()
control:SetResizeToFitDescendents(true)
if control.isHalfWidth then --note these restrictions
control:SetDimensionConstraints(width / 2, MIN_HEIGHT, width / 2, MIN_HEIGHT * 4)
else
control:SetDimensionConstraints(width, MIN_HEIGHT, width, MIN_HEIGHT * 4)
end
control.UpdateValue = UpdateValue
if control.panel.data.registerForRefresh or control.panel.data.registerForDefaults then --if our parent window wants to refresh controls, then add this to the list
tinsert(control.panel.controlsToRefresh, control)
end
return control
end
|
local awful = require("awful")
local wibox = require("wibox")
local beautiful = require("beautiful")
local widget = require('util.widgets')
local font = require("util.font")
-- widgets for the monitor bar
local ram = require("widgets.ram")({ layout = "horizontal", mode = "progressbar", bar_size = 100 })
local volume = require("widgets.volume")({ layout = "horizontal", mode = "progressbar", bar_size = 100 })
local brightness = require("widgets.brightness")({ layout = "horizontal", mode = "progressbar", bar_size = 100 })
local battery = require("widgets.battery")({ layout = "horizontal", mode = "progressbar", bar_size = 100 })
local cpu = require("widgets.cpu")({ mode = "dotsbar" })
local disk = require("widgets.disks")({ mode = "block" })
local network = require("widgets.network")({ mode = "block" })
local music_player = require("widgets.music-player")({ mode = "block" })
-- init tables
local mybar = class()
-- {{{ Wibar
function mybar:init(s)
-- bottom bar
s.monitor_bar = awful.wibar({ position = "bottom", height = dpi(84), screen = s })
s.monitor_bar.bg = M.x.surface
-- widget to decorate
local boxes = function(w, size)
local s = size or 200
return wibox.widget {
{ -- margin top, bottom
{ -- left
font.button("", M.x.primary, 16), nil, nil, -- top
layout = wibox.layout.align.vertical
},
{ -- center,
widget.centered(w, "vertical"),
left = 12, right = 12,
forced_width = dpi(s),
widget = wibox.container.margin
},
{ -- right
font.button("", M.x.secondary, 16), nil, nil, -- top
layout = wibox.layout.align.vertical
},
layout = wibox.layout.align.horizontal
},
top = 1, bottom = 1,
widget = wibox.container.margin
}
end
local w1 = wibox.widget {
ram,
brightness,
forced_height = 30,
layout = wibox.layout.fixed.horizontal
}
local w2 = wibox.widget {
volume,
battery,
forced_height = 30,
layout = wibox.layout.fixed.horizontal
}
s.monitor_bar:setup {
nil, -- Left widgets
{
boxes(music_player),
boxes(disk, 250),
boxes(widget.box('vertical', { w1, w2 }), 300),
boxes(network, 250),
{ -- the only who need a top margin, idkw
boxes(cpu),
top = 10,
widget = wibox.container.margin,
},
spacing = beautiful.widget_spacing,
layout = wibox.layout.fixed.horizontal
},
nil, -- Right widgets
expand ="none",
layout = wibox.layout.align.horizontal
}
end
return mybar
|
pork = {
use = function(player)
local health = 128
player:sendAction(8, 25)
player.attacker = player.ID
player:addHealthExtend(health, 0, 0, 0, 0, 0)
if player.health == player.maxHealth then
player:sendMinitext("You feel satiated.")
end
end
}
rare_pork = {
use = function(player)
local health = 31
player:sendAction(8, 25)
player.attacker = player.ID
player:addHealthExtend(health, 0, 0, 0, 0, 0)
if player.health == player.maxHealth then
player:sendMinitext("You feel satiated.")
end
end
}
|
--
-- Aliases for map generator outputs
--
minetest.register_alias("mapgen_stone", "default:stone")
minetest.register_alias("mapgen_dirt", "default:dirt")
minetest.register_alias("mapgen_dirt_with_grass", "default:dirt_with_grass")
minetest.register_alias("mapgen_sand", "default:sand")
minetest.register_alias("mapgen_water_source", "default:water_source")
minetest.register_alias("mapgen_river_water_source", "default:river_water_source")
minetest.register_alias("mapgen_lava_source", "default:lava_source")
minetest.register_alias("mapgen_gravel", "default:gravel")
minetest.register_alias("mapgen_tree", "default:tree")
minetest.register_alias("mapgen_leaves", "default:leaves")
minetest.register_alias("mapgen_apple", "default:apple")
minetest.register_alias("mapgen_junglegrass", "default:junglegrass")
minetest.register_alias("mapgen_cobble", "default:cobble")
minetest.register_alias("mapgen_stair_cobble", "stairs:stair_cobble")
minetest.register_alias("mapgen_mossycobble", "default:mossycobble")
--
-- Ore generation
--
-- Blob ore first to avoid other ores inside blobs
minetest.register_ore({
ore_type = "blob",
ore = "default:clay",
wherein = {"default:sand"},
clust_scarcity = 24*24*24,
clust_size = 7,
y_min = -15,
y_max = 0,
noise_threshold = 0,
noise_params = {
offset=0.35,
scale=0.2,
spread={x=5, y=5, z=5},
seed=-316,
octaves=1,
persist=0.5
},
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_coal",
wherein = "default:stone",
clust_scarcity = 8*8*8,
clust_num_ores = 8,
clust_size = 3,
y_min = -31000,
y_max = 64,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_iron",
wherein = "default:stone",
clust_scarcity = 12*12*12,
clust_num_ores = 3,
clust_size = 2,
y_min = -15,
y_max = 2,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_iron",
wherein = "default:stone",
clust_scarcity = 9*9*9,
clust_num_ores = 5,
clust_size = 3,
y_min = -63,
y_max = -16,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_iron",
wherein = "default:stone",
clust_scarcity = 7*7*7,
clust_num_ores = 5,
clust_size = 3,
y_min = -31000,
y_max = -64,
})
--
-- Register biomes for biome API
--
minetest.clear_registered_biomes()
minetest.clear_registered_decorations()
minetest.register_biome({
name = "default:grassland",
--node_dust = "",
node_top = "default:dirt_with_grass",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 1,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
y_min = 5,
y_max = 31000,
heat_point = 50,
humidity_point = 50,
})
minetest.register_biome({
name = "default:grassland_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 2,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
y_min = -31000,
y_max = 4,
heat_point = 50,
humidity_point = 50,
})
|
--!A cross-platform build utility based on Lua
--
-- 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.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file package.lua
--
-- imports
import("core.base.semver")
import("core.base.option")
import("core.base.global")
import("lib.detect.cache", {alias = "detectcache"})
import("core.project.project")
import("core.package.package", {alias = "core_package"})
import("action")
import("devel.git")
import("net.fasturl")
import("repository")
--
-- parse require string
--
-- add_requires("zlib")
-- add_requires("tbox >=1.5.1", "zlib >=1.2.11")
-- add_requires("zlib master")
-- add_requires("xmake-repo@tbox >=1.5.1")
-- add_requires("aaa_bbb_ccc >=1.5.1 <1.6.0", {optional = true, alias = "mypkg", debug = true})
-- add_requires("tbox", {config = {coroutine = true, abc = "xxx"}})
-- add_requires("xmake::xmake-repo@tbox >=1.5.1")
-- add_requires("conan::OpenSSL/1.0.2n@conan/stable")
-- add_requires("brew::pcre2/libpcre2-8 10.x", {alias = "pcre2"})
--
-- {system = nil/true/false}:
-- nil: get local or system packages
-- true: only get system package
-- false: only get local packages
--
function _parse_require(require_str, requires_extra, parentinfo)
-- get it from cache first
local requires = _g._REQUIRES or {}
local required = requires[require_str]
if required then
return required.packagename, required.requireinfo
end
-- split package and version info
local splitinfo = require_str:split('%s+')
assert(splitinfo and #splitinfo > 0, "require(\"%s\"): invalid!", require_str)
-- get package info
local packageinfo = splitinfo[1]
-- get version
--
-- e.g.
--
-- lastest
-- >=1.5.1 <1.6.0
-- master || >1.4
-- ~1.2.3
-- ^1.1
--
local version = "lastest"
if #splitinfo > 1 then
version = table.concat(table.slice(splitinfo, 2), " ")
end
assert(version, "require(\"%s\"): unknown version!", require_str)
-- require third-party packages? e.g. brew::pcre2/libpcre2-8
local reponame = nil
local packagename = nil
if require_str:find("::", 1, true) then
packagename = packageinfo
else
-- get repository name, package name and package url
local pos = packageinfo:find_last('@', true)
if pos then
-- get package name
packagename = packageinfo:sub(pos + 1)
-- get reponame
reponame = packageinfo:sub(1, pos - 1)
else
packagename = packageinfo
end
end
-- check package name
assert(packagename, "require(\"%s\"): the package name not found!", require_str)
-- get require extra
local require_extra = {}
if requires_extra then
require_extra = requires_extra[require_str] or {}
end
-- get required building configurations
local require_build_configs = require_extra.configs or require_extra.config
if require_extra.debug then
require_build_configs = require_build_configs or {}
require_build_configs.debug = true
end
-- require packge in the current host platform
if require_extra.host then
require_extra.plat = os.host()
require_extra.arch = os.arch()
end
-- init required item
local required = {}
parentinfo = parentinfo or {}
required.packagename = packagename
required.requireinfo =
{
originstr = require_str,
reponame = reponame,
version = version,
plat = require_extra.plat, -- require package in the given platform
arch = require_extra.arch, -- require package in the given architecture
alias = require_extra.alias, -- set package alias name
group = require_extra.group, -- only uses the first package in same group
system = require_extra.system, -- default: true, we can set it to disable system package manually
option = require_extra.option, -- set and attach option
configs = require_build_configs, -- the required building configurations
default = require_extra.default, -- default: true, we can set it to disable package manually
optional = parentinfo.optional or require_extra.optional -- default: false, inherit parentinfo.optional
}
-- save this required item to cache
requires[require_str] = required
_g._REQUIRES = requires
-- ok
return required.packagename, required.requireinfo
end
-- load package package from system
function _load_package_from_system(packagename)
return core_package.load_from_system(packagename)
end
-- load package package from project
function _load_package_from_project(packagename)
return core_package.load_from_project(packagename)
end
-- load package package from repositories
function _load_package_from_repository(packagename, reponame)
-- get package directory from the given package name
local packagedir, repo = repository.packagedir(packagename, reponame)
if packagedir then
-- load it
return core_package.load_from_repository(packagename, repo, packagedir)
end
end
-- search packages from repositories
function _search_packages(name)
local packages = {}
for _, packageinfo in ipairs(repository.searchdirs(name)) do
local package = core_package.load_from_repository(packageinfo.name, packageinfo.repo, packageinfo.packagedir)
if package then
table.insert(packages, package)
end
end
return packages
end
-- sort package deps
--
-- e.g.
--
-- a.deps = b
-- b.deps = c
--
-- orderdeps: c -> b -> a
--
function _sort_packagedeps(package)
local orderdeps = {}
for _, dep in pairs(package:deps()) do
table.join2(orderdeps, _sort_packagedeps(dep))
table.insert(orderdeps, dep)
end
return orderdeps
end
-- add some builtin configurations to package
function _add_package_configurations(package)
package:add("configs", "debug", {builtin = true, description = "Enable debug symbols.", default = false, type = "boolean"})
package:add("configs", "shared", {builtin = true, description = "Enable shared library.", default = false, type = "boolean"})
package:add("configs", "cflags", {builtin = true, description = "Set the C compiler flags."})
package:add("configs", "cxflags", {builtin = true, description = "Set the C/C++ compiler flags."})
package:add("configs", "cxxflags", {builtin = true, description = "Set the C++ compiler flags."})
package:add("configs", "asflags", {builtin = true, description = "Set the assembler flags."})
package:add("configs", "vs_runtime", {builtin = true, description = "Set vs compiler runtime.", default = "MT", values = {"MT", "MD"}})
end
-- select package version
function _select_package_version(package, requireinfo)
-- exists urls? otherwise be phony package (only as package group)
if #package:urls() > 0 then
-- has git url?
local has_giturl = false
for _, url in ipairs(package:urls()) do
if git.checkurl(url) then
has_giturl = true
break
end
end
-- select package version
local source = nil
local version = nil
local require_version = requireinfo.version
if #package:versions() > 0 and (require_version == "lastest" or require_version:find('.', 1, true)) then -- select version?
version, source = semver.select(require_version, package:versions())
elseif has_giturl then -- select branch?
version, source = require_version ~= "lastest" and require_version or "master", "branches"
else
raise("package(%s %s): not found!", package:name(), require_version)
end
return version, source
end
end
-- check the configurations of packages
--
-- package("pcre2")
-- add_configs("bitwidth", {description = "Set the code unit width.", default = "8", values = {"8", "16", "32"}})
-- add_configs("bitwidth", {type = "number", values = {8, 16, 32}})
-- add_configs("bitwidth", {restrict = function(value) if tonumber(value) < 100 then return true end})
--
function _check_package_configurations(package)
local configs_defined = {}
for _, name in ipairs(package:get("configs")) do
configs_defined[name] = package:extraconf("configs", name) or {}
end
for name, value in pairs(package:configs()) do
local conf = configs_defined[name]
if conf then
local config_type = conf.type or "string"
if type(value) ~= config_type then
raise("package(%s %s): invalid type(%s) for config(%s), need type(%s)!", package:name(), package:version_str(), type(value), name, config_type)
end
if conf.values then
local found = false
for _, config_value in ipairs(conf.values) do
if tostring(value) == tostring(config_value) then
found = true
break
end
end
if not found then
raise("package(%s %s): invalid value(%s) for config(%s), please run `xmake require --info %s` to get all valid values!", package:name(), package:version_str(), value, name, package:name())
end
end
if conf.restrict then
if not conf.restrict(value) then
raise("package(%s %s): invalid value(%s) for config(%s)!", package:name(), package:version_str(), value, name)
end
end
else
raise("package(%s %s): invalid config(%s), please run `xmake require --info %s` to get all configurations!", package:name(), package:version_str(), name, package:name())
end
end
end
-- load required packages
function _load_package(packagename, requireinfo)
-- attempt to get it from cache first
local packages = _g._PACKAGES or {}
local package = packages[packagename]
if package then
-- satisfy required version?
local version_required = _select_package_version(package, requireinfo)
if version_required and version_required ~= package:version_str() then
raise("package(%s): version conflict, '%s' does not satisfy '%s'!", packagename, package:version_str(), requireinfo.version)
end
return package
end
-- load package from project first
if os.isfile(os.projectfile()) then
package = _load_package_from_project(packagename)
end
-- load package from repositories
if not package then
package = _load_package_from_repository(packagename, requireinfo.reponame)
end
-- load package from system
if not package then
package = _load_package_from_system(packagename)
end
-- check
assert(package, "package(%s) not found!", packagename)
-- select package version
local version, source = _select_package_version(package, requireinfo)
if version then
package:version_set(version, source)
end
-- save require info to package
package:requireinfo_set(requireinfo)
-- add some builtin configurations to package
_add_package_configurations(package)
-- check package configurations
_check_package_configurations(package)
-- do load for package
local on_load = package:script("load")
if on_load then
on_load(package)
end
-- load environments from the manifest to enable the environments of on_install()
package:envs_load()
-- save this package package to cache
packages[packagename] = package
_g._PACKAGES = packages
-- ok
return package
end
-- load all required packages
function _load_packages(requires, opt)
-- no requires?
if not requires or #requires == 0 then
return {}
end
-- load packages
local packages = {}
for _, requireinfo in ipairs(load_requires(requires, opt.requires_extra, opt.parentinfo)) do
-- load package
local package = _load_package(requireinfo.name, requireinfo.info)
-- maybe package not found and optional
if package then
-- load dependent packages and save them first of this package
if not package._DEPS then
local deps = package:get("deps")
if deps and opt.nodeps ~= true then
local packagedeps = {}
for _, dep in ipairs(_load_packages(deps, {requires_extra = package:get("__extra_deps"), parentinfo = requireinfo.info, nodeps = opt.nodeps})) do
dep:parents_add(package)
table.insert(packages, dep)
packagedeps[dep:name()] = dep
end
package._DEPS = packagedeps
package._ORDERDEPS = table.unique(_sort_packagedeps(package))
end
end
-- save this package package
table.insert(packages, package)
end
end
return packages
end
-- sort packages urls
function _sort_packages_urls(packages)
-- add all urls to fasturl and prepare to sort them together
for _, package in pairs(packages) do
fasturl.add(package:urls())
end
-- sort and update urls
for _, package in pairs(packages) do
package:urls_set(fasturl.sort(package:urls()))
end
end
-- get package status string
function _get_package_status_str(package)
local status = {}
if package:debug() then
table.insert(status, "debug")
end
if package:optional() then
table.insert(status, "optional")
end
return #status > 0 and "(" .. table.concat(status, ", ") .. ")" or ""
end
-- get user confirm
function _get_confirm(packages)
-- no confirmed packages?
if #packages == 0 then
return true
end
-- get confirm
local confirm = utils.confirm({default = true, description = function ()
-- get packages for each repositories
local packages_repo = {}
local packages_group = {}
for _, package in ipairs(packages) do
-- achive packages by repository
local reponame = package:repo() and package:repo():name() or (package:isSys() and "system" or "")
if package:is3rd() then
reponame = package:name():lower():split("::")[1]
end
packages_repo[reponame] = packages_repo[reponame] or {}
table.insert(packages_repo[reponame], package)
-- achive packages by group
local group = package:group()
if group then
packages_group[group] = packages_group[group] or {}
table.insert(packages_group[group], package)
end
end
-- show tips
cprint("${bright color.warning}note: ${clear}try installing these packages (pass -y to skip confirm)?")
for reponame, packages in pairs(packages_repo) do
if reponame ~= "" then
print("in %s:", reponame)
end
local packages_showed = {}
for _, package in ipairs(packages) do
if not packages_showed[tostring(package)] then
local group = package:group()
if group and packages_group[group] and #packages_group[group] > 1 then
for idx, package_in_group in ipairs(packages_group[group]) do
cprint(" ${yellow}%s${clear} %s %s %s", idx == 1 and "->" or " or", package_in_group:name(), package_in_group:version_str() or "", _get_package_status_str(package_in_group))
packages_showed[tostring(package_in_group)] = true
end
packages_group[group] = nil
else
cprint(" ${yellow}->${clear} %s %s %s", package:name(), package:version_str() or "", _get_package_status_str(package))
packages_showed[tostring(package)] = true
end
end
end
end
end})
return confirm
end
-- patch some builtin dependent packages
function _patch_packages(packages_install, packages_download)
-- @NOTE use git.apply instead of patch
-- we can add some builtin packages like this
--[[
-- add package(patch)
local patched_package = nil
for _, package in ipairs(packages_install) do
if package:patches() then
patched_package = package
break
end
end
if patched_package then
local packages = load_packages("patch")
if packages and #packages > 0 then
-- install patch package
local package = packages[1]
if not package:fetch() then
packages_download[tostring(package)] = package
table.insert(packages_install, 1, package)
end
-- add dependences to ensure to be installed first
patched_package:deps_add(package)
end
end
]]
end
-- install packages
function _install_packages(packages_install, packages_download)
local waitindex = 0
local waitchars = {'\\', '-', '/', '|'}
local packages_installing = {}
local packages_downloading = {}
local packages_pending = table.copy(packages_install)
local packages_in_group = {}
local installing_count = 0
local parallelize = true
process.runjobs(function (index)
-- fetch a new package
local package = nil
while package == nil and #packages_pending > 0 do
for idx, pkg in ipairs(packages_pending) do
-- all dependences has been installed? we install it now
local ready = true
for _, dep in ipairs(pkg:orderdeps()) do
if not dep:exists() then
ready = false
end
end
local group = pkg:group()
if ready and group then
-- this group has been installed? skip it
local group_status = packages_in_group[group]
if group_status == 1 then
table.remove(packages_pending, idx)
break
-- this group is installing? wait it
elseif group_status == 0 then
ready = false
end
end
-- get a package with the ready status
if ready then
package = pkg
table.remove(packages_pending, idx)
break
end
end
if package == nil and #packages_pending > 0 then
local curdir = os.curdir()
coroutine.yield()
os.cd(curdir)
end
end
if package then
-- only install the first package in same group
local group = package:group()
if not group or not packages_in_group[group] then
-- disable parallelize?
if not package:parallelize() then
parallelize = false
end
if not parallelize then
while installing_count > 0 do
local curdir = os.curdir()
coroutine.yield()
os.cd(curdir)
end
end
installing_count = installing_count + 1
-- mark this group as 'installing'
if group then
packages_in_group[group] = 0
end
-- download this package first
local downloaded = true
if packages_download[tostring(package)] then
packages_downloading[index] = package
downloaded = action.download(package)
packages_downloading[index] = nil
end
-- install this package
packages_installing[index] = package
if downloaded then
action.install(package)
end
packages_installing[index] = nil
-- mark this group as 'installed' or 'failed'
if group then
packages_in_group[group] = package:exists() and 1 or -1
end
-- enable parallelize
parallelize = true
installing_count = installing_count - 1
end
end
packages_installing[index] = nil
packages_downloading[index] = nil
end, #packages_install, (option.get("verbose") or option.get("diagnosis")) and 1 or 4, 300, function (indices, tips)
-- do not print progress info if be verbose
if option.get("verbose") then
return
end
-- update waitchar index
waitindex = ((waitindex + 1) % #waitchars)
-- make installing and downloading packages list
local installing = {}
local downloading = {}
for _, index in ipairs(indices) do
local package = packages_installing[index]
if package then
table.insert(installing, package:name())
end
local package = packages_downloading[index]
if package then
table.insert(downloading, package:name())
end
end
-- trace
utils.clearline()
cprintf("${yellow} => ${clear}")
if #downloading > 0 then
cprintf("downloading ${magenta}%s${clear}", table.concat(downloading, ", "))
end
if #installing > 0 then
cprintf("%sinstalling ${magenta}%s${clear}", #downloading > 0 and ", " or "", table.concat(installing, ", "))
end
cprintf(" .. ${dim}%s${clear}%s", tips and (tips .. " ") or "", waitchars[waitindex + 1])
io.flush()
end)
end
-- the cache directory
function cachedir()
return path.join(global.directory(), "cache", "packages")
end
-- load requires
function load_requires(requires, requires_extra, parentinfo)
-- parse requires
local requireinfos = {}
for _, require_str in ipairs(requires) do
-- parse require info
local packagename, requireinfo = _parse_require(require_str, requires_extra, parentinfo)
-- save this required package
table.insert(requireinfos, {name = packagename, info = requireinfo})
end
-- ok
return requireinfos
end
-- load all required packages
function load_packages(requires, opt)
opt = opt or {}
local unique = {}
local packages = {}
for _, package in ipairs(_load_packages(requires, opt)) do
-- remove repeat packages with same the package name and version
local key = package:name() .. (package:version_str() or "")
if not unique[key] then
table.insert(packages, package)
unique[key] = true
end
end
return packages
end
-- install packages
function install_packages(requires, opt)
-- init options
opt = opt or {}
-- load packages
local packages = load_packages(requires, opt)
-- fetch packages (with system) from local first
process.runjobs(function (index)
local package = packages[index]
if package and (not option.get("force") or (option.get("shallow") and package:parents())) then
package:envs_enter()
package:fetch()
package:envs_leave()
end
end, #packages)
-- filter packages
local packages_install = {}
local packages_download = {}
local packages_unsupported = {}
for _, package in ipairs(packages) do
if not package:exists() and (#package:urls() > 0 or package:script("install")) then
if package:supported() then
if #package:urls() > 0 then
packages_download[tostring(package)] = package
end
table.insert(packages_install, package)
elseif not package:optional() then
table.insert(packages_unsupported, package)
end
end
end
-- exists unsupported packages?
if #packages_unsupported > 0 then
-- show tips
cprint("${bright color.warning}note: ${clear}the following packages are unsupported for $(plat)/$(arch)!")
for _, package in ipairs(packages_unsupported) do
print(" -> %s %s", package:name(), package:version_str() or "")
end
raise()
end
-- patch some dependent builtin packages
_patch_packages(packages_install, packages_download)
-- get user confirm
if not _get_confirm(packages_install) then
local packages_must = {}
for _, package in ipairs(packages_install) do
if not package:optional() then
table.insert(packages_must, package:name())
end
end
if #packages_must > 0 then
raise("packages(%s): must be installed!", table.concat(packages_must, ", "))
else
-- continue other actions
return
end
end
-- sort package urls
_sort_packages_urls(packages_download)
-- install all required packages from repositories
_install_packages(packages_install, packages_download)
-- ok
return packages
end
-- uninstall packages
function uninstall_packages(requires, opt)
-- init options
opt = opt or {}
-- do not remove dependent packages
opt.nodeps = true
-- clear the detect cache
detectcache.clear()
-- remove all packages
local packages = {}
for _, instance in ipairs(load_packages(requires, opt)) do
if os.isfile(instance:manifest_file()) then
table.insert(packages, instance)
end
os.tryrm(instance:installdir())
end
return packages
end
-- search packages
function search_packages(names)
-- search all names
local results = {}
for _, name in ipairs(names) do
local packages = _search_packages(name)
if packages then
results[name] = packages
end
end
return results
end
|
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
local UF = E:GetModule('UnitFrames');
--Cache global variables
--Lua functions
local unpack = unpack
--WoW API / Variables
local UnitIsWarModePhased = UnitIsWarModePhased
local texCoords = {
[1] = {1 / 128, 33 / 128, 1 / 64, 33 / 64},
[2] = {34 / 128, 66 / 128, 1 / 64, 33 / 64},
}
function UF:PostUpdate_PhaseIcon(isInSamePhase)
if not isInSamePhase then
self:SetTexCoord(unpack(texCoords[UnitIsWarModePhased(self.__owner.unit) and 2 or 1]))
end
end
function UF:Construct_PhaseIcon(frame)
local PhaseIndicator = frame.RaisedElementParent.TextureParent:CreateTexture(nil, 'ARTWORK', nil, 1)
PhaseIndicator:SetSize(30, 30)
PhaseIndicator:SetPoint('CENTER', frame.Health, 'CENTER')
PhaseIndicator:SetTexture('Interface\\AddOns\\ElvUI\\media\\textures\\phaseIcons')
PhaseIndicator:SetDrawLayer('OVERLAY', 7)
PhaseIndicator.PostUpdate = UF.PostUpdate_PhaseIcon
return PhaseIndicator
end
function UF:Configure_PhaseIcon(frame)
local PhaseIndicator = frame.PhaseIndicator
PhaseIndicator:ClearAllPoints()
PhaseIndicator:Point(frame.db.phaseIndicator.anchorPoint, frame.Health, frame.db.phaseIndicator.anchorPoint, frame.db.phaseIndicator.xOffset, frame.db.phaseIndicator.yOffset)
local scale = frame.db.phaseIndicator.scale or 1
PhaseIndicator:Size(30 * scale)
if frame.db.phaseIndicator.enable and not frame:IsElementEnabled('PhaseIndicator') then
frame:EnableElement('PhaseIndicator')
elseif not frame.db.phaseIndicator.enable and frame:IsElementEnabled('PhaseIndicator') then
frame:DisableElement('PhaseIndicator')
end
end
|
-----------------------------------
-- Area: Garlaige Citadel [S]
-- NPC: Randecque
-- !pos 61 -6 137 164
-- Notes: Gives Red Letter required to start "Steamed Rams"
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/keyitems")
local ID = require("scripts/zones/Garlaige_Citadel_[S]/IDs")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if (player:getCampaignAllegiance() > 0) then
if (player:getCampaignAllegiance() == 2) then
player:startEvent(3)
else
-- message for other nations missing
player:startEvent(3)
end
elseif (player:hasKeyItem(tpz.ki.RED_RECOMMENDATION_LETTER) == true) then
player:startEvent(2)
elseif (player:hasKeyItem(tpz.ki.RED_RECOMMENDATION_LETTER) == false) then
player:startEvent(1)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 1 and option == 0) then
player:addKeyItem(tpz.ki.RED_RECOMMENDATION_LETTER)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.RED_RECOMMENDATION_LETTER)
end
end
|
-- obtain mouse state
local mouseX = screen.getMouseX()
local mouseY = screen.getMouseY()
local mouseState = screen.getMouseState()
-- convert mouse coordinates to HSV
local h = mouseX * 255
local s = 255
local v = 255
if mouseY < 0.5 then
s = (mouseY*2) * 255
end
if mouseY > 0.5 then
v = (1 - ((mouseY-0.5)*2)) * 255
end
-- convert HSV to RGB which is what the lights accept
r, g, b = HSVtoRGB(h, s, v)
-- set light color if holding lmb
if mouseState == 1 then
light.setRGBColor(r,g,b)
end
-- print stuff to console
--system.print(string.format("x: %.1f, y: %.1f, state: %d", mouseX, mouseY, mouseState))
--system.print(string.format("H: %.1f, S: %.1f, V: %.1f", h, s, v))
--system.print(string.format("R: %.1f, G: %.1f, B: %.1f", r, g, b))
|
module("luci.controller.changewifi", package.seeall)
function index()
entry({"admin" , "changewifi"}, cbi("changewifi"), _("修改wifi信息"), 100)
end
|
--[[
Name: HttpService.lua / init.lua
Author: DontRevealMe
Description: Provides an httpservice queuing system
--]]
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Framework"))
local Signal = require("Signal")
local Promise = require("Promise")
local HttpService = game:GetService("HttpService")
local Module = {}
Module._cache = {}
Module._queueData = {
queue = {},
lastReset = tick(),
requestsMade = 0,
wakeQueue = Signal.new()
}
--[[**
Sends an HTTPService request.
@param [t:dictionary] requestDictionary See https://developer.roblox.com/en-us/api-reference/function/HttpService/RequestAsync for more info
@param [t:bool] cache If true, the method will cache the response
@param [t:boool] useCache If true, the method will search the cache for a response and if there isn't one, it will send a request.
@returns [t:Promise]
**--]]
function Module:RequestAsync(requestDictionary, cache, useCache)
return Promise.async(function(resolve, reject, onCancel)
if useCache and Module._cache[requestDictionary.Url] then
return Module._cache[requestDictionary.Url]
else
if tick() - Module._queueData.lastReset >= 60 then
Module._queueData.requestsMade = 0
Module._queueData.lastReset = tick()
end
if Module._queueData.requestsMade >= 500 or #Module._queueData.queue>0 then
-- Queue is full or is on going!
local isEmpty = #Module._queueData.queue == 0
local placeOnQueue = #Module._queueData.queue + 1
-- Add it to the queue
table.insert(Module._queueData.queue, placeOnQueue, {
Response = function(succ, res)
if succ then
resolve(res)
else
reject(res)
end
end,
Data = requestDictionary
})
if isEmpty then Module._queueData.wakeQueue:Fire() end
else
-- Queue is not full
resolve(HttpService:RequestAsync(requestDictionary))
Module._queueData.requestsMade = Module._queueData.requestsMade + 1
end
end
end):andThen(function(response)
if cache and response["Success"] then
Module._cache[response.Url] = response
end
return response
end)
end
--[[
"Quicker" method of sending requests without having to go through the hassle of setting application/json.
DEPRECATED METHOD. USE :RequestAsync.
@param [t:dictionary] requestDictionary See https://developer.roblox.com/en-us/api-reference/function/HttpService/RequestAsync for more info
@param [t:bool] cache If true, the method will cache the response
@param [t:boool] useCache If true, the method will search the cache for a response and if there isn't one, it will send a request.
@returns [t:Promise]
--]]
function Module:QuickRequestAsync(dictionary, cache, useCache)
dictionary.Method = dictionary.Method:upper()
if not dictionary["Headers"] then
dictionary.Headers = {}
end
if not dictionary.Headers["Content-Type"] then
dictionary.Headers["Content-Type"] = "application/json"
end
dictionary.Body = HttpService:JSONEncode(dictionary.Body)
return Module:RequestAsync(dictionary, cache, useCache):andThen(function(res)
if res["Success"] then
res = HttpService:JSONDecode(res)
end
return res
end)
end
return Module
|
------------------
-- Cells are agents used to represent the space. They are also known as tiles or patches in other systems.
-- @classmod
-- Cell
local class = require 'Thirdparty.pl.class'
local Cell = class.Cell(Agent)
------------------
-- Cell constructor.
-- When a new Cell is created, some properties are given to it (If we do not have done it yet)
-- @function _init
-- @param p_table Table of pairs 'name_of_attribute:value'
-- @return Agent. A new instance of Cell class.
-- @usage new_instance = Cell( {} )
Cell._init = function(self,p_table)
self:super(p_table)
for k,v in pairs(p_table) do
self[k] = v
end
self.pos = p_table.pos or {0,0,0}
self.label = p_table.label or ''
self.label_color= p_table.color or {1,1,1,1}
self.color = p_table.color or {1,1,1,1}
self.shape = p_table.shape or 'square'
self.width = p_table.width or 1
self.height = p_table.height or 1
self.region = p_table.region or {}
self.neighbors = p_table.neighbors or Collection()
self.my_agents = p_table.my_agents or Collection()
self.z_order = p_table.z_order or 0
return self
end;
------------------
-- It returns the x coordinate of the Cell
-- @function xcor
-- @return the first position of the vector 'pos'
-- @usage instance:xcor()
Cell.xcor = function(self)
return self.pos[1]
end
------------------
-- It returns the y coordinate of the Cell
-- @function ycor
-- @return the second position of the vector 'pos'
-- @usage instance:ycor()
Cell.ycor = function(self)
return self.pos[2]
end
------------------
-- It returns the z coordinate of the Cell
-- @function zcor
-- @return the third position of the vector 'pos'
-- @usage instance:zcor()
Cell.zcor = function(self)
return self.pos[3]
end
------------------
-- A function to determine if a position is in the region of the Cell.
-- @function region
-- @param pos A vector of n dimensions.
-- @return true if the position is in the region of the cell. A square region of 1 unit side is considered by default.
-- @usage instance:region()
Cell.region = function(self,pos)
local x,y = pos[1],pos[2]
local width_limit, height_limit = self.width / 2, self.height / 2
local x_right_limit, x_left_limit = self:xcor() + width_limit, self:xcor() - width_limit
local y_down_limit, y_up_limit = self:ycor() - height_limit, self:ycor() + height_limit
if x_right_limit >= x and x > x_left_limit then
if y_up_limit >= y and y > y_down_limit then
return true
end
end
return false
end
------------------
-- A function to update the Collection of agents in a Cell by adding an agent.
-- @function come_in
-- @param agent An Agent, new member of the Collection of agents with a position inside the region of the Cell.
-- @return Nothing
-- @usage
-- Cell:come_in(an_agent)
Cell.come_in = function(self, agent)
self.my_agents:add(agent)
end
------------------
-- A function to update the Collection of agents in a Cell by removing an agent.
-- @function come_out
-- @param agent An Agent, current member of the Collection of agents with a position inside the region of the Cell. This agent will be removed of the Collection.
-- @return Nothing
-- @usage
-- Cell:come_out(an_agent)
Cell.come_out = function(self, agent)
self.my_agents:remove(agent)
end
return Cell
|
local patch_id = "GAMESTATE_ADD_AGENT_RM_OLD_SKIN"
if not rawget(_G, patch_id) then
rawset(_G, patch_id, true)
print("Loaded patch:"..patch_id)
local old_fn = GameState.AddAgent
GameState.AddAgent = function(self, agent)
local result = old_fn(self,agent)
agent.original_skin = nil
return result
end
local old_skin_fn = Agent.GetSkinID
Agent.GetSkinID = function(self)
return self.original_skin and self.original_skin.uuid or old_skin_fn(self)
end
end
|
return {
PlaceObj('ModItemCode', {
'name', "Crime",
'FileName', "Code/Crime.lua",
}),
PlaceObj('ModItemCode', {
'name', "CrimeUI",
'FileName', "Code/CrimeUI.lua",
}),
PlaceObj('ModItemCode', {
'name', "DomesticViolence",
'FileName', "Code/DomesticViolence.lua",
}),
PlaceObj('ModItemCode', {
'name', "FirstResponders",
'FileName', "Code/FirstResponders.lua",
}),
PlaceObj('ModItemCode', {
'name', "Notifications",
'FileName', "Code/Notifications.lua",
}),
PlaceObj('ModItemCode', {
'name', "OffDutyHeroes",
'FileName', "Code/OffDutyHeroes.lua",
}),
PlaceObj('ModItemCode', {
'name', "Rehabilitation",
'FileName', "Code/Rehabilitation.lua",
}),
PlaceObj('ModItemCode', {
'name', "RehabilitationUI",
'FileName', "Code/RehabilitationUI.lua",
}),
PlaceObj('ModItemCode', {
'name', "UnitTests",
'FileName', "Code/UnitTests.lua",
}),
PlaceObj('ModItemTraitPreset', {
__copy_group = "",
_incompatible = "Renegade",
category = "Positive",
description = T(598838342649, --[[ModItemTraitPreset Vindicated description]] "Vindicated Renegades will no longer become Renegades and will gain (+20) additional performance on all jobs"),
display_icon = "",
display_name = T(520259899232, --[[ModItemTraitPreset Vindicated display_name]] "Vindicated"),
dome_filter_only = true,
group = "Positive",
id = "Vindicated",
incompatible = {
Renegade = true,
Violent = true,
},
modify_amount = 20,
modify_property = "performance",
modify_target = "self",
name = "Vindicated",
weight = 0,
}),
PlaceObj('ModItemTraitPreset', {
_incompatible = "Composed,Vindicated",
category = "Negative",
description = T(635612439152, --[[ModItemTraitPreset Violent description]] "Violent people will resort to domestic violence more often, and their victims will be more scared to talk about it. Violent people cannot be Vindicated. Can be obtained via sanity breakdown or by being the victim of domestic violence."),
display_icon = "",
display_name = T(151354650363, --[[ModItemTraitPreset Violent display_name]] "Violent"),
group = "Negative",
id = "Violent",
incompatible = {
Composed = true,
Vindicated = true,
},
initial_filter = true,
name = "Violent",
sanatorium_trait = true,
weight = 100,
}),
}
|
local socket = require("socket")
client = socket.connect("google.com", 80)
client:send("GET /robots.txt HTTP/1.0\r\n\r\n")
while true do
s, status, partial = client:receive(1024)
print(s or partial)
if status == "closed" then
break
end
end
client:close()
|
-- soft.lua v0.1
-- Copyright (c) 2016 Ulysse Ramage
-- 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 soft, softObject = {
speed = 5,
var = {}
}, {}
setmetatable(soft, soft)
--[[ Private ]]--
local function lerp(a, b, k) --smooth transitions
if a == b then
return a
else
if math.abs(a-b) < 0.005 then return b else return a * (1-k) + b * k end
end
end
--[[ Public ]]--
function soft:update(dt)
for k, v in pairs(self.var) do
v:update(dt)
end
end
function softObject:update(dt)
if self.target then self.value = lerp(self.value, self.target, self.speed * dt) end
end
--
function soft:new(value)
local _object = {
value = value
}
setmetatable(_object, { __index = softObject })
self.var[_object] = _object
return _object
end
function softObject:set(value, params)
if params and params.reset then self.target = value end
self.value = value
return self
end
function softObject:to(target, params)
self.target = target
self.speed = params and params.speed or soft.speed
return self
end
function softObject:setSpeed(speed)
self.speed = speed
return self
end
function softObject:get(target)
return target and self.target or self.value
end
function softObject:getTarget() return self:get(true) end
--[[ Aliases ]]--
softObject.s = softObject.set
softObject.t = softObject.to
softObject.g = softObject.get
softObject.gt = softObject.getTarget
--[[ End ]]--
return soft
|
--
-- acme.lua
--
-- ACME v2 protocol client implementation for HAProxy Lua host
--
-- ACME RFC:
-- https://tools.ietf.org/html/draft-ietf-acme-acme-12
--
-- Copyright (c) 2017-2020. Adis Nezirovic <anezirovic@haproxy.com>
-- Copyright (c) 2017-2020. HAProxy Technologies, LLC.
--
-- 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.
--
-- SPDX-License-Identifier: Apache-2.0
local _author = "Adis Nezirovic <anezirovic@haproxy.com>"
local _copyright = "Copyright 2017-2020. HAProxy Technologies, LLC."
local _version = "1.0.0"
local http = require "http"
local json = require "json"
local openssl = {
pkey = require "openssl.pkey",
x509 = require "openssl.x509",
name = require "openssl.x509.name",
altname = require "openssl.x509.altname",
csr = require "openssl.x509.csr",
digest = require "openssl.digest"
}
if not config then
config = {
-- ACME certificate authority configuration
ca = {
-- HAProxy backend which proxies requests to ACME server
proxy_uri = "http://127.0.0.1:9012",
-- ACME server URI (also returned by ACME directory listings)
uri = "https://acme-v02.api.letsencrypt.org"
},
registration = {
termsOfServiceAgreed = false,
contact = {"mailto:user@example.net"}
}
}
end
-- Storage area for serving challanges to ACME server
local http_challenges = {}
local ACME = {}
ACME.__index = ACME
function ACME.create(conf)
local self = setmetatable({}, ACME)
self.conf = conf or {}
-- ACME resources, only 'directory' resource should be known in advance
self.resources = nil
local resp
local err
resp, err = self:get{url=config.ca.proxy_uri .. "/directory"}
if resp and resp.status_code == 200 and resp.headers["content-type"]
and resp.headers["content-type"]:match("application/json") then
self.resources = json.decode(resp.content)
self.nonce = resp.headers["replay-nonce"]
end
if not self.resources then
return nil, err
end
assert(self.resources["newNonce"])
assert(self.resources["newAccount"])
assert(self.resources["newOrder"])
assert(self.resources["revokeCert"])
self.account = {
key = nil,
kid = nil
}
return self
end
--- Adapt resource URLs when going through HAProxy
function ACME.proxy_url(self, url)
if url:sub(1, #self.conf.ca.uri) == self.conf.ca.uri then
return string.format("%s%s", self.conf.ca.proxy_uri, url:sub(#self.conf.ca.uri))
else
return url
end
end
--- ACME wrapper for http.get()
--
-- @param resource ACME resource type
-- @param url Valid HTTP url (mandatory)G
--
-- @return Response object or tuple (nil, msg) on errors
function ACME.get(self, t)
local resp, err = http.get{url=self:proxy_url(t.url)}
if (not t.retry or t.retry < 5) and (not resp or (resp and resp.status_code == 503)) then
t.retry = not t.retry and 1 or t.retry + 1
return self:get(t)
end
return resp, err
end
--- ACME wrapper for http.post()
--
-- @param resource ACME resource type
-- @param url Valid HTTP url (mandatory)G
-- @param headers Lua table with request headers
-- @param data Request content
--
-- @return Response object or tuple (nil, msg) on errors
function ACME.post(self, t)
local jws, err = self:jws{resource=t.resource, url=t.url, payload=t.data}
if not jws then
return nil, err
end
if not t.headers then
t.headers = {
["content-type"] = "application/jose+json"
}
elseif not t.headers["content-type"] then
t.headers["content-type"] = "application/jose+json"
end
local resp, err = http.post{url=self:proxy_url(t.url), data=jws,
headers=t.headers, timeout=t.timeout}
if resp and resp.headers then
self.nonce = resp.headers["replay-nonce"]
if resp.status_code == 400 then
local info = resp:json()
if info and info.type == "urn:ietf:params:acme:error:badNonce" then
-- We need to retry once more with new nonce (hence new jws)
jws, err = self:jws{resource=t.resource, url=t.url,
payload=t.data}
if not jws then
return nil, err
end
resp, err = self:post{url=self:proxy_url(t.url), data=jws,
headers=t.headers}
end
end
end
if (not t.retry or t.retry < 5) and (not resp or (resp and resp.status_code == 503)) then
t.retry = not t.retry and 1 or t.retry + 1
return self:post(t)
end
return resp, err
end
--- ACME wrapper for POST-as-GET
--
-- @param resource ACME resource type
-- @param url Valid HTTP url (mandatory)G
-- @param headers Lua table with request headers
-- @param data Request content
--
-- @return Response object or tuple (nil, msg) on errors
function ACME.postAsGet(self, t)
local jws, err = self:jws{url=t.url, payload=nil}
if not jws then
return nil, err
end
if not t.headers then
t.headers = {
["content-type"] = "application/jose+json"
}
elseif not t.headers["content-type"] then
t.headers["content-type"] = "application/jose+json"
end
local resp, err = http.post{url=self:proxy_url(t.url), data=jws,
headers=t.headers, timeout=t.timeout}
if resp and resp.headers then
self.nonce = resp.headers["replay-nonce"]
if resp.status_code == 400 then
local info = resp:json()
if info and info.type == "urn:ietf:params:acme:error:badNonce" then
-- We need to retry once more with new nonce (hence new jws)
jws, err = self:jws{resource=t.resource, url=t.url,
payload=""}
if not jws then
return nil, err
end
resp, err = self:post{url=self:proxy_url(t.url), data=jws,
headers=t.headers}
end
end
end
if (not t.retry or t.retry < 5) and (not resp or (resp and resp.status_code == 503)) then
t.retry = not t.retry and 1 or t.retry + 1
return self:postAsGet(t)
end
return resp, err
end
--- Return the ACME nonce
--
-- Nonce is volatile, if nonce is not present (i.e.from previous request),
-- a fresh nonce is requested from the ACME server, otherwise, the stored
-- nonce is returned (and deleted)
--
function ACME.refresh_nonce(self)
local nonce = self.nonce
self.nonce = nil
if nonce then return nonce end
local resp, e = http.head{url=self:proxy_url(self.resources["newNonce"])}
if resp and resp.headers then
-- TODO: Expect status code 204
-- TODO: Expect Cache-Control: no-store
-- TODO: Expect content size 0
return resp.headers["replay-nonce"]
else
return nil, e
end
end
--- Enclose the provided payload in JWS
--
-- @param url URL
-- @param resource ACME resource type
-- @param payload (json) data which will be wrapped in JWS
function ACME.jws(self, t)
if not self.account or not self.account.key then
return nil, "ACME.jws: Account key does not exist."
end
if not t or not t.url then
return nil,
"ACME.jws: Missing one or more parameters (url)"
end
-- if key:type() == rsaEncryption
local params = self.account.key:getParameters()
if not params then
return nil, "ACME.jws: Could not extract account key parameters."
end
local jws = {
protected = {
alg = "RS256",
nonce = self:refresh_nonce(),
url = t.url
},
payload = t.payload
}
if t.resource == "newAccount" then
-- if self.account.key:type() == "rsaEncryption" then
jws.protected.jwk = {
e = http.base64.encode(params.e:toBinary(), base64enc),
kty = "RSA",
n = http.base64.encode(params.n:toBinary(), base64enc)
}
local jwk_ordered = string.format('{"e":"%s","kty":"%s","n":"%s"}',
jws.protected.jwk.e,
jws.protected.jwk.kty,
jws.protected.jwk.n)
local tdigest = openssl.digest.new("SHA256"):final(jwk_ordered)
self.account.thumbprint = http.base64.encode(tdigest, base64enc)
else
jws.protected.kid = self.account.kid
end
jws.protected = http.base64.encode(json.encode(jws.protected), base64enc)
jws.payload = t.payload and http.base64.encode(json.encode(t.payload), base64enc) or ""
local digest = openssl.digest.new("SHA256")
digest:update(jws.protected .. "." .. jws.payload)
jws.signature = http.base64.encode(self.account.key:sign(digest), base64enc)
return json.encode(jws)
end
function ACME.register(self)
if not self.account then
return nil, 'No account key'
end
local resp, err = self:post{url=self.resources["newAccount"],
data=self.conf.registration,
resource="newAccount"}
if not resp then
return nil, err
end
self.account.kid = resp.headers['location']
return resp
end
local function new_order(applet)
local acme, err = ACME.create(config)
if not acme then
return http.response.create{status_code=500, content=err}:send(applet)
end
function base64enc(s)
return applet.c:base64(s)
end
function base64dec(s)
-- Depends on HAProxy v1.8
return applet.c:b64dec(s)
end
local r = http.request.parse(applet)
if not (r and r.data) then
return http.response.create{status_code=400, content=err}:send(applet)
end
local form, err = r:parse_multipart()
if not form then
return http.response.create{status_code=400, content=err}:send(applet)
end
if not (form.account_key and form.domain_key and form.domain) then
local err = 'Missing one of mandatory form fields: account_key, domain, domain_key'
return http.response.create{status_code=400, content=err}:send(applet)
end
acme.account = {
key = openssl.pkey.new(form.account_key.data or form.account_key)
}
local resp, err = acme:register()
if not resp then
return http.response.create{status_code=500, data=err}:send(applet)
elseif resp.status_code ~= 200 and resp.status_code ~= 201 then
return resp:send(applet)
end
local aliases = {}
if form.aliases then
aliases = core.tokenize(form.aliases, ",")
end
local order_payload = {
identifiers = {
[1] = {
type = "dns",
value = form.domain
}
}
}
for idx, alias in pairs(aliases) do
order_payload.identifiers[idx+1] = {type = "dns", value = alias}
end
-- Place new order
local order, err = acme:post{url=acme.resources["newOrder"], data=order_payload,
resource="newOrder"}
if not order then
return http.response.create{status_code=500, data=err}:send(applet)
elseif order.status_code ~= 201 then
return order:send(applet)
end
local order_json = order:json()
local challenge_token
for _, auth in ipairs(order_json.authorizations) do
--
local auth_payload = {
keyAuthorization = nil
}
-- Get auth token
local auth, err = acme:postAsGet{url=auth}
if auth then
local auth_json = auth:json()
for _, ch in ipairs(auth_json.challenges) do
if ch.type == "http-01" then
http_challenges[ch.token] = string.format("%s.%s",
ch.token, acme.account.thumbprint)
resp, err = acme:post{url=ch.url, data=ch,
resource="challengeDone"}
challenge_token = ch.token
break
end
end
end
end
-- Wait until the order is ready
local order_status
for _, t in pairs({1, 1, 2, 3, 5, 8, 13}) do
core.sleep(t)
local resp, err = acme:postAsGet{url=order.headers["location"]}
if resp then
order_status = resp:json()
if order_status.status == "ready" then
break
elseif order_status.status == "invalid" then
return resp:send(applet)
end
end
end
if not order_status then
return http.response.create{status_code=500,
content="Could not get order status"}:send(applet)
end
if order_status.status ~= "ready" then
return http.response.create{status_code=500, content=order_status}:send(applet)
end
if challenge_token and http_challenges[challenge_token] then
http_challenges[challenge_token] = nil
end
-- CSR creation
local dn = openssl.name.new()
dn:add("CN", form.domain)
local alt = openssl.altname.new()
alt:add("DNS", form.domain)
for _, alias in pairs(aliases) do
alt:add("DNS", alias)
end
local csr = openssl.csr.new()
csr:setSubject(dn)
csr:setSubjectAlt(alt)
local key = openssl.pkey.new(form.domain_key.data or form.domain_key)
csr:setPublicKey(key)
csr:sign(key)
local payload = {
csr = http.base64.encode(csr:tostring("DER"), base64enc)
}
resp, err = acme:post{url=order_json.finalize, data=payload,
resource="finalizeOrder"}
if resp and resp.status_code == 200 then
local resp_json = resp:json()
if not resp.headers["content-type"] == "application/pem-certificate-chain" then
return http.response.create{status_code=500,
content="Wrong content type"}:send(applet)
end
if not resp_json.certificate then
return http.response.create{status_code=500, content="No cert"}:send(applet)
end
local resp, err = acme:postAsGet{url=resp_json.certificate}
local bundle = string.format("%s%s", resp.content, key:toPEM("private"))
return http.response.create{status_code=200, content=bundle}:send(applet)
else
return resp:send(applet)
end
end
local function acme_challenge(applet)
local p = core.tokenize(applet.path, "/", true)
if not p[3] or not http_challenges[p[3]] then
return http.response.create{status_code=404}:send(applet)
end
http.response.create{status_code=200, content=http_challenges[p[3]]}:send(applet)
end
--- Request handler/router
--
--
local function request_handler(applet)
local p = core.tokenize(applet.path, "/", true)
local m = applet.method
local h = {
acme = {
order = {
POST = new_order
}
},
[".well-known"] = {
["acme-challenge"] = {
GET = acme_challenge
}
}
}
if h[p[1]] and h[p[1]][p[2]] and h[p[1]][p[2]][m] then
return h[p[1]][p[2]][m]
end
return nil
end
local function main(applet)
local handler = request_handler(applet)
if not handler then
http.response.create{status_code=404}:send(applet)
else
handler(applet)
end
end
core.register_service("acme", "http", main)
|
addEventHandler ( 'onClientPlayerDamage', root, function ( )
if ( isElement ( source ) ) then
if ( getElementModel ( source ) == 217 or getElementData ( source, "isGodmodeEnabled" ) == true ) then
cancelEvent ( )
end
end
end )
|
local display = {}
local sharedDirector = cc.Director:getInstance()
-- check device screen size
local glview = sharedDirector:getOpenGLView()
local size = glview:getFrameSize()
display.sizeInPixels = {width = size.width, height = size.height}
local w = display.sizeInPixels.width
local h = display.sizeInPixels.height
function display.newScene(name)
local scene = cc.Scene:create()
scene.name = name or "<unknown-scene>"
return scene
end
function display.replaceScene(newScene, transitionType, time, more)
if sharedDirector:getRunningScene() then
-- if transitionType then
-- newScene = display.wrapSceneWithTransition(newScene, transitionType, time, more)
-- end
sharedDirector:replaceScene(newScene)
else
sharedDirector:runWithScene(newScene)
end
end
function display.getRunningScene()
return sharedDirector:getRunningScene()
end
return display
|
function GBayEntityPageFull(DFrame, data)
if IsValid(HomePanel) then
HomePanel:Remove()
end
if IsValid(HomePanel2) then
HomePanel2:Remove()
end
if not IsValid(DFrame) then
return
end
HomePanel = vgui.Create("DFrame", DFrame)
HomePanel:SetPos(50, 180)
HomePanel:SetSize(DFrame:GetWide() - 60, DFrame:GetTall() - 190)
HomePanel:SetDraggable(false)
HomePanel:SetTitle("")
HomePanel:ShowCloseButton(false)
HomePanel.Paint = function() end
local ScrollList = vgui.Create("DPanelList", HomePanel)
ScrollList:SetPos(50, 0)
ScrollList:SetSize(HomePanel:GetWide(), HomePanel:GetTall() - 55)
ScrollList:EnableHorizontal(true)
ScrollList:SetSpacing(20)
ScrollList:EnableVerticalScrollbar(true)
local CreateItemPage = vgui.Create("DButton", HomePanel)
CreateItemPage:SetPos(HomePanel:GetWide() - 30, HomePanel:GetTall() - 30)
CreateItemPage:SetSize(25, 25)
CreateItemPage:SetText("+")
CreateItemPage:SetFont("GBayLabelFontLarge")
CreateItemPage:SetTextColor(Color(214, 214, 214))
CreateItemPage.DoClick = function()
GBaySideBarOpened(DFrame, "Create", false, data, false)
end
CreateItemPage.Paint = function(s, w, h) end
for k, v in pairs(data[5]) do
local ItemMain = vgui.Create("DFrame")
ItemMain:SetSize(270, 130)
ItemMain:SetDraggable(false)
ItemMain:SetTitle("")
ItemMain:ShowCloseButton(false)
ItemMain.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h - 30, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 34, Color(255, 255, 255))
draw.RoundedBox(0, 0, 0, 100, 100, Color(238, 238, 238))
end
if LocalPlayer():GBayIsAdmin(data) or v[2] == LocalPlayer():SteamID64() then
local ViewMoreBTN = vgui.Create("DButton", ItemMain)
ViewMoreBTN:SetPos(5, ItemMain:GetTall() - 20)
ViewMoreBTN:SetSize(80, 20)
ViewMoreBTN:SetText("View More")
ViewMoreBTN:SetTextColor(Color(185, 201, 229))
ViewMoreBTN.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 4, Color(255, 255, 255))
end
ViewMoreBTN.DoClick = function()
GBayViewMoreItemFull("Entity", DFrame, data, v)
end
local EditBTN = vgui.Create("DButton", ItemMain)
EditBTN:SetPos(95, ItemMain:GetTall() - 20)
EditBTN:SetSize(80, 20)
EditBTN:SetText("Edit")
EditBTN:SetTextColor(Color(255, 0, 0))
EditBTN.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 4, Color(255, 255, 255))
end
EditBTN.DoClick = function()
LocalPlayer().GBayIsEditing = v[1]
GBaySideBarOpened(DFrame, "EditEnt", false, data, false)
end
local RemoveBTN = vgui.Create("DButton", ItemMain)
RemoveBTN:SetPos(185, ItemMain:GetTall() - 20)
RemoveBTN:SetSize(80, 20)
RemoveBTN:SetText("Remove")
RemoveBTN:SetTextColor(Color(255, 0, 0))
RemoveBTN.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 4, Color(255, 255, 255))
end
RemoveBTN.DoClick = function()
Derma_Query("Are you sure you want to remove this item?", "GBay Remove Item", "Yes", function()
net.Start("GBayRemoveEnt")
net.WriteFloat(v[1])
net.SendToServer()
end, "No", function() end)
end
else
local ViewMoreBTN = vgui.Create("DButton", ItemMain)
ViewMoreBTN:SetPos(20, ItemMain:GetTall() - 20)
ViewMoreBTN:SetSize(ItemMain:GetWide() - 40, 20)
ViewMoreBTN:SetText("View More")
ViewMoreBTN:SetTextColor(Color(185, 201, 229))
ViewMoreBTN.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 4, Color(255, 255, 255))
end
ViewMoreBTN.DoClick = function()
GBayViewMoreItemFull("Entity", DFrame, data, v)
end
end
local theweaponpic = false
if file.Exists("materials/vgui/entities/" .. v[5] .. ".vmt", "GAME") then
theweaponpic = "vgui/entities/" .. v[5] .. ".vmt"
elseif file.Exists("materials/entities/" .. v[5] .. ".png", "GAME") then
theweaponpic = "entities/" .. v[5] .. ".png"
end
local WeaponModel = vgui.Create("DImage", ItemMain)
WeaponModel:SetPos(0, 0)
WeaponModel:SetSize(100, 100)
WeaponModel:SetImage(theweaponpic)
local ItemName = vgui.Create("DLabel", ItemMain)
ItemName:SetPos(110, 10)
ItemName:SetSize(ItemMain:GetWide(), 20)
ItemName:SetText(v[3])
ItemName:SetTextColor(Color(0, 0, 0))
ItemName:SetFont("GBayLabelFontSmall")
local UserRatingText = vgui.Create("DLabel", ItemMain)
UserRatingText:SetPos(110, 30)
UserRatingText:SetSize(ItemMain:GetWide(), 20)
UserRatingText:SetText("User Rating: ")
UserRatingText:SetTextColor(Color(0, 0, 0))
UserRatingText:SetFont("GBayLabelFontSmall")
for pid, player in pairs(data[1]) do
if player[2] == v[2] then
playerdata = player
end
end
local thestars = 0
local numbers = {playerdata[4], -playerdata[5], -playerdata[6]}
local sum = 0
local total = 0
for i = 1, #numbers do
sum = sum + numbers[i]
total = total + math.abs(numbers[i])
end
local percent = math.Round(numbers[1] / total * 100, 1)
if percent <= 20 then
thestars = 1
elseif percent <= 40 then
thestars = 2
elseif percent <= 60 then
thestars = 3
elseif percent <= 80 then
thestars = 4
elseif percent <= 100 then
thestars = 5
end
local theposforstars = 185
for i = 1, thestars do
local RatingStars = vgui.Create("DImage", ItemMain)
RatingStars:SetPos(theposforstars, 35)
RatingStars:SetSize(10, 10)
RatingStars:SetImage("gbay/Star128.png")
theposforstars = theposforstars + 15
end
local UserRatingText = vgui.Create("DLabel", ItemMain)
UserRatingText:SetPos(110, 50)
UserRatingText:SetSize(ItemMain:GetWide(), 20)
UserRatingText:SetText("Price: " .. DarkRP.formatMoney(v[6]))
UserRatingText:SetTextColor(Color(0, 0, 0))
UserRatingText:SetFont("GBayLabelFontSmall")
local PlayerAvatar = vgui.Create("EnhancedAvatarImage", ItemMain)
PlayerAvatar:SetPos(ItemMain:GetWide() - 40, 60)
PlayerAvatar:SetSize(34, 34)
PlayerAvatar:SetSteamID(v[2], 64)
ScrollList:AddItem(ItemMain)
end
end
function GBayEntityPageSmall(DFrame, data)
if IsValid(HomePanel) then
HomePanel:Remove()
end
if IsValid(HomePanel2) then
HomePanel2:Remove()
end
if not IsValid(DFrame) then
return
end
HomePanel = vgui.Create("DFrame", DFrame)
HomePanel:SetPos(290, 180)
HomePanel:SetSize(DFrame:GetWide() - 300, DFrame:GetTall() - 190)
HomePanel:SetDraggable(false)
HomePanel:SetTitle("")
HomePanel:ShowCloseButton(false)
HomePanel.Paint = function() end
local ScrollList = vgui.Create("DPanelList", HomePanel)
ScrollList:SetPos(50, 0)
ScrollList:SetSize(HomePanel:GetWide(), HomePanel:GetTall())
ScrollList:EnableHorizontal(true)
ScrollList:SetSpacing(20)
ScrollList:EnableVerticalScrollbar(true)
local CreateItemPage = vgui.Create("DButton", HomePanel)
CreateItemPage:SetPos(HomePanel:GetWide() - 30, HomePanel:GetTall() - 30)
CreateItemPage:SetSize(25, 25)
CreateItemPage:SetText("+")
CreateItemPage:SetFont("GBayLabelFontLarge")
CreateItemPage:SetTextColor(Color(214, 214, 214))
CreateItemPage.DoClick = function()
GBaySideBarOpened(DFrame, "Create", false, data, false)
end
CreateItemPage.Paint = function(s, w, h) end
for k, v in pairs(data[5]) do
local ItemMain = vgui.Create("DFrame")
ItemMain:SetSize(270, 130)
ItemMain:SetDraggable(false)
ItemMain:SetTitle("")
ItemMain:ShowCloseButton(false)
ItemMain.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h - 30, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 34, Color(255, 255, 255))
draw.RoundedBox(0, 0, 0, 100, 100, Color(238, 238, 238))
end
if LocalPlayer():GBayIsAdmin(data) or v[2] == LocalPlayer():SteamID64() then
local ViewMoreBTN = vgui.Create("DButton", ItemMain)
ViewMoreBTN:SetPos(5, ItemMain:GetTall() - 20)
ViewMoreBTN:SetSize(80, 20)
ViewMoreBTN:SetText("View More")
ViewMoreBTN:SetTextColor(Color(185, 201, 229))
ViewMoreBTN.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 4, Color(255, 255, 255))
end
ViewMoreBTN.DoClick = function()
GBayViewMoreItemSmall("Entity", DFrame, data, v)
end
local EditBTN = vgui.Create("DButton", ItemMain)
EditBTN:SetPos(95, ItemMain:GetTall() - 20)
EditBTN:SetSize(80, 20)
EditBTN:SetText("Edit")
EditBTN:SetTextColor(Color(255, 0, 0))
EditBTN.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 4, Color(255, 255, 255))
end
EditBTN.DoClick = function()
LocalPlayer().GBayIsEditing = v[1]
GBaySideBarOpened(DFrame, "EditEnt", false, data, false)
end
local RemoveBTN = vgui.Create("DButton", ItemMain)
RemoveBTN:SetPos(185, ItemMain:GetTall() - 20)
RemoveBTN:SetSize(80, 20)
RemoveBTN:SetText("Remove")
RemoveBTN:SetTextColor(Color(255, 0, 0))
RemoveBTN.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 4, Color(255, 255, 255))
end
RemoveBTN.DoClick = function()
Derma_Query("Are you sure you want to remove this item?", "GBay Remove Item", "Yes", function()
net.Start("GBayRemoveEnt")
net.WriteFloat(v[1])
net.SendToServer()
end, "No", function() end)
end
else
local ViewMoreBTN = vgui.Create("DButton", ItemMain)
ViewMoreBTN:SetPos(20, ItemMain:GetTall() - 20)
ViewMoreBTN:SetSize(ItemMain:GetWide() - 40, 20)
ViewMoreBTN:SetText("View More")
ViewMoreBTN:SetTextColor(Color(185, 201, 229))
ViewMoreBTN.Paint = function(s, w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(238, 238, 238))
draw.RoundedBox(0, 2, 2, w - 4, h - 4, Color(255, 255, 255))
end
ViewMoreBTN.DoClick = function()
GBayViewMoreItemSmall("Entity", DFrame, data, v)
end
end
local theweaponpic = false
if file.Exists("materials/vgui/entities/" .. v[5] .. ".vmt", "GAME") then
theweaponpic = "vgui/entities/" .. v[5] .. ".vmt"
elseif file.Exists("materials/entities/" .. v[5] .. ".png", "GAME") then
theweaponpic = "entities/" .. v[5] .. ".png"
end
local WeaponModel = vgui.Create("DImage", ItemMain)
WeaponModel:SetPos(0, 0)
WeaponModel:SetSize(100, 100)
WeaponModel:SetImage(theweaponpic)
local ItemName = vgui.Create("DLabel", ItemMain)
ItemName:SetPos(110, 10)
ItemName:SetSize(ItemMain:GetWide(), 20)
ItemName:SetText(v[3])
ItemName:SetTextColor(Color(0, 0, 0))
ItemName:SetFont("GBayLabelFontSmall")
local UserRatingText = vgui.Create("DLabel", ItemMain)
UserRatingText:SetPos(110, 30)
UserRatingText:SetSize(ItemMain:GetWide(), 20)
UserRatingText:SetText("User Rating: ")
UserRatingText:SetTextColor(Color(0, 0, 0))
UserRatingText:SetFont("GBayLabelFontSmall")
for pid, player in pairs(data[1]) do
if player[2] == v[2] then
playerdata = player
end
end
local thestars = 0
local numbers = {playerdata[4], -playerdata[5], -playerdata[6]}
local sum = 0
local total = 0
for i = 1, #numbers do
sum = sum + numbers[i]
total = total + math.abs(numbers[i])
end
local percent = math.Round(numbers[1] / total * 100, 1)
if percent <= 20 then
thestars = 1
elseif percent <= 40 then
thestars = 2
elseif percent <= 60 then
thestars = 3
elseif percent <= 80 then
thestars = 4
elseif percent <= 100 then
thestars = 5
end
local theposforstars = 185
for i = 1, thestars do
local RatingStars = vgui.Create("DImage", ItemMain)
RatingStars:SetPos(theposforstars, 35)
RatingStars:SetSize(10, 10)
RatingStars:SetImage("gbay/Star128.png")
theposforstars = theposforstars + 15
end
local UserRatingText = vgui.Create("DLabel", ItemMain)
UserRatingText:SetPos(110, 50)
UserRatingText:SetSize(ItemMain:GetWide(), 20)
UserRatingText:SetText("Price: " .. DarkRP.formatMoney(v[6]))
UserRatingText:SetTextColor(Color(0, 0, 0))
UserRatingText:SetFont("GBayLabelFontSmall")
local PlayerAvatar = vgui.Create("EnhancedAvatarImage", ItemMain)
PlayerAvatar:SetPos(ItemMain:GetWide() - 40, 60)
PlayerAvatar:SetSize(34, 34)
PlayerAvatar:SetSteamID(v[2], 64)
ScrollList:AddItem(ItemMain)
end
end
|
local Line = {}
function Line:new(world, x1, y1, x2, y2)
local line = {}
setmetatable(line, self)
self.__index = self
line.b = love.physics.newBody(world, 0, 0, 'static')
line.s = love.physics.newEdgeShape( x1, y1, x2, y2 )
line.f = love.physics.newFixture( line.b, line.s )
line.color = {
math.random(1, 255)/255,
math.random(1, 255)/255,
math.random(1, 255)/255
}
return line
end
function Line.update(self, dt)
return
end
function Line.draw(self, tx, ty)
tx = tx or 0
ty = ty or 0
local x, y, xx, yy = self.b:getWorldPoints(self.s:getPoints())
love.graphics.setColor(self.color)
love.graphics.line(x+tx, y+ty, xx+tx, yy+ty)
love.graphics.setColor(1,1,1)
end
function Line.destroy(self)
self.f:release()
end
return setmetatable({}, {__call = function(_, ...) return Line:new(...) end})
|
----
-- @file WorldInput
---- Brief description.
-- @return <#return value description#>
function WorldInput:WorldInput()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function WorldInput:getClassName()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function WorldInput:getType()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:getTouch()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:getTouch()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:numberOfTouches()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:setTouch()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:setTouch()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:clearNodeTouches()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:touchDown()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:touchUp()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:touchMove()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:touchCancelled()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:setOrientation()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:isPortraitOrientation()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:isLandscapeOrientation()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:getOrientation()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:showKeyboard()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:clearTouches()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:WorldInput()
end
---- Brief description.
-- @return <#return value description#>
function WorldInput:operator=()
end
|
-- luacheck: globals unpack vim
local nvim = vim.api
--[[ -> iron
-- Here is the complete iron API.
-- Below is a brief description of module separation:
-- -->> behavior:
-- Functions that alter iron's behavior and are set to be used
-- within configuration by the user
--
-- -->> memory:
-- Iron's repl database, so it knows which instances it's managing.
--
-- -->> ll:
-- Low level functions that interact with neovim's windows and buffers.
--
-- -->> config:
-- This is what guides irons behavior.
--
-- -->> fts:
-- File types and their repl definitions.
--
-- -->> core:
-- User api, should have all public functions there.
-- mostly a reorganization of core, hiding the complexity
-- of managing memory and config from the user.
--]]
local function echoerr(msg)
nvim.nvim_command('echohl ErrorMsg')
nvim.nvim_command('echomsg "'..msg..'"')
nvim.nvim_command('echohl')
end
local ext = {
repl = require("iron.fts.common").functions,
strings = require("iron.util.strings"),
tables = require("iron.util.tables"),
}
local iron = {
memory = {},
behavior = {
debug_level = require("iron.debug_level"),
manager = require("iron.memory_management"),
visibility = require("iron.visibility")
},
ll = {},
core = {},
debug = {
ll = {},
mem = {}
},
last = {},
fts = require("iron.fts")
}
local defaultconfig = {
debug_level = iron.behavior.debug_level.fatal,
visibility = iron.behavior.visibility.toggle,
manager = iron.behavior.manager.path_based,
preferred = {},
repl_open_cmd = "topleft vertical 100 split"
}
-- [[ Low-level
iron.ll.get_from_memory = function(ft)
return iron.config.manager.get(iron.memory, ft)
end
iron.ll.set_on_memory = function(ft, fn)
return iron.config.manager.set(iron.memory, ft, fn)
end
iron.ll.get_buffer_ft = function(bufnr)
local ft = nvim.nvim_buf_get_option(bufnr, 'filetype')
if ext.tables.get(iron.fts, ft) == nil then
echoerr("There's no REPL definition for current filetype "..ft)
else
return ft
end
end
iron.ll.get_file_ft = function()
return nvim.nvim_get_option("ft")
end
iron.ll.get_repl_definitions = function(ft)
return iron.fts[ft]
end
iron.ll.get_preferred_repl = function(ft)
local repl_definitions = iron.ll.get_repl_definitions(ft)
local preference = iron.config.preferred[ft]
local repl_def = nil
if preference ~= nil then
repl_def = repl_definitions[preference]
elseif repl_definitions ~= nil then
for _, v in pairs(repl_definitions) do
if nvim.nvim_call_function('exepath', {v.command[1]}) ~= '' then
repl_def = v
break
end
end
if repl_def == nil then
echoerr("Failed to locate REPL executable, aborting")
end
else
echoerr("There's no REPL definition for current filetype "..ft)
end
return repl_def
end
iron.ll.new_repl_window = function(buff)
if type(iron.config.repl_open_cmd) == "function" then
iron.config.repl_open_cmd(buff)
else
nvim.nvim_command(iron.config.repl_open_cmd .. '| ' .. buff .. ' | set wfw | startinsert')
end
end
iron.ll.create_new_repl = function(ft, repl, new_win)
-- make creation of new windows optional
if new_win == nil then
new_win = true
end
if new_win then
iron.ll.new_repl_window("enew")
else
-- just want to open a new empty buffer, as termopen destroys the
-- currently active buffer
nvim.nvim_command('enew')
end
local job_id = nvim.nvim_call_function('termopen', {repl.command})
local bufnr = nvim.nvim_call_function('bufnr', {'%'})
local inst = {
bufnr = bufnr,
job = job_id,
repldef = repl
}
iron.ll.set_on_memory(ft, function() return inst end)
return inst
end
iron.ll.create_preferred_repl = function(ft, new_win)
if new_win == nil then
new_win = true
end
local repl = iron.ll.get_preferred_repl(ft)
if repl ~= nil then
return iron.ll.create_new_repl(ft, repl, new_win)
end
return nil
end
iron.ll.ensure_repl_exists = function(ft, newfn)
newfn = newfn or iron.ll.create_preferred_repl
local mem = iron.ll.get_from_memory(ft)
local created = false
if mem == nil or nvim.nvim_call_function('bufname', {mem.bufnr}) == "" then
mem = newfn(ft)
created = true
end
return mem, created
end
iron.ll.send_to_repl = function(ft, data)
local dt = data
if type(data) == "string" then
dt = ext.strings.split(data, '\n')
end
local mem = iron.ll.get_from_memory(ft)
dt = ext.repl.format(mem.repldef, dt)
iron.debug.ll.store{
where = "send_to_repl",
raw_lines = data,
lines = dt,
repl = mem,
level = iron.behavior.debug_level.info
}
local window = nvim.nvim_call_function('bufwinnr', {mem.bufnr})
if window ~= -1 then
nvim.nvim_command(window .. "windo normal! G")
nvim.nvim_command(window .. "wincmd p")
end
nvim.nvim_call_function('chansend', {mem.job, dt})
end
iron.ll.get_repl_ft_for_bufnr = function(bufnr)
-- given a buffer number, tries to look up the corresponding
-- filetype of the REPL
-- If the corresponding buffer number does not exist or is not
-- a REPL, then return nil
local ft_found = nil
for ft in pairs(iron.memory) do
local mem = iron.ll.get_from_memory(ft)
if mem ~= nil and bufnr == mem.bufnr then
ft_found = ft
end
end
return ft_found
end
-- Low-level ]]
iron.core.repl_here = function(ft)
-- first check if the repl for the current filetype already exists
local mem = iron.ll.get_from_memory(ft)
local exists = not (mem == nil or
nvim.nvim_call_function('bufname', {mem.bufnr}) == "")
if exists then
-- it exists so just activate the buffer in the current window
nvim.nvim_command('b ' .. mem.bufnr)
else
-- the repl does not exist, so we have to create a new one,
-- but in the current window
mem = iron.ll.create_preferred_repl(ft, false)
end
return mem
end
iron.core.repl_restart = function()
-- First, check if the cursor is on top or a REPL
-- Then, start a new REPL of the same time and enter it into the window
-- Afterwards, wipe out the old REPL buffer
-- This is done without asking for confirmation, so user beware
local bufnr_here = nvim.nvim_call_function('bufnr', {"%"})
local ft_here = iron.ll.get_repl_ft_for_bufnr(bufnr_here)
local mem = nil
if ft_here ~= nil then
mem = iron.ll.create_preferred_repl(ft_here, false)
-- created a new one, now have to kill the old one
nvim.nvim_command('bwipeout! ' .. bufnr_here)
else
local ft = nvim.nvim_buf_get_option(bufnr_here, 'filetype')
local mem = iron.ll.get_from_memory(ft)
local exists = not (mem == nil or
nvim.nvim_call_function('bufname', {mem.bufnr}) == "")
if exists then
-- Wipe the old REPL and then create a new one
nvim.nvim_command('bwipeout! ' .. mem.bufnr)
mem, _ = iron.ll.ensure_repl_exists(ft)
nvim.nvim_command('wincmd p')
else
-- no repl found, so nothing to do
echoerr ('No repl found in current buffer; cannot restart')
end
end
return mem
end
iron.core.repl_for = function(ft)
local mem, created = iron.ll.ensure_repl_exists(ft)
if not created then
local showfn = function()
iron.ll.new_repl_window('b ' .. mem.bufnr)
end
iron.config.visibility(mem.bufnr, showfn)
else
nvim.nvim_command('wincmd p')
end
return mem
end
iron.core.focus_on = function(ft)
local mem = iron.ll.ensure_repl_exists(ft)
local showfn = function()
iron.ll.new_repl_window('b ' .. mem.bufnr)
end
iron.behavior.visibility.focus(mem.bufnr, showfn)
return mem
end
iron.core.set_config = function(cfg)
iron.config = ext.tables.clone(defaultconfig)
for k, v in pairs(cfg) do
iron.config[k] = v
end
end
iron.core.add_repl_definitions = function(defns)
for ft, defn in pairs(defns) do
if iron.fts[ft] == nil then
iron.fts[ft] = {}
end
for repl, repldfn in pairs(defn) do
iron.fts[ft][repl] = repldfn
end
end
end
iron.core.send = function(ft, data)
iron.ll.ensure_repl_exists(ft)
iron.ll.send_to_repl(ft, data)
end
iron.core.send_line = function()
local ft = iron.ll.get_buffer_ft(0)
if ft ~= nil then
local linenr = nvim.nvim_win_get_cursor(0)[1]
local cur_line = nvim.nvim_buf_get_lines(0, linenr-1, linenr, 0)[1]
if #cur_line == 0 then return end
iron.debug.ll.store{
linenr = linenr,
cur_line = cur_line,
where = "send_line",
level = iron.behavior.debug_level.info
}
iron.ll.ensure_repl_exists(ft)
iron.ll.send_to_repl(ft, cur_line)
end
end
iron.core.send_motion = function(mtype)
local ft = iron.ll.get_buffer_ft(0)
if ft == nil then return end
local b_line, b_col, e_line, e_col, _
_, b_line, b_col = unpack(nvim.nvim_call_function("getpos", {"'["}))
_, e_line, e_col = unpack(nvim.nvim_call_function("getpos", {"']"}))
local lines = nvim.nvim_buf_get_lines(0, b_line - 1, e_line, 0)
if #lines == 0 then return end
if mtype == 'char' then
lines[#lines] = string.sub(lines[#lines], 1, e_col)
lines[1] = string.sub(lines[1], b_col)
end
iron.debug.ll.store{
b_col = b_col,
e_col = e_col,
b_line = b_line,
e_line = e_line,
lines = lines,
where = "send_motion",
level = iron.behavior.debug_level.info
}
iron.ll.ensure_repl_exists(ft)
iron.ll.send_to_repl(ft, lines)
iron.last.b_line = b_line
iron.last.b_col = b_col
iron.last.e_col = e_col
iron.last.e_line = e_line
end
iron.core.visual_send = function()
local ft = iron.ll.get_buffer_ft(0)
if ft == nil then return end
local b_line, b_col, e_line, e_col, _
_, b_line, b_col = unpack(nvim.nvim_call_function("getpos", {"'<"}))
_, e_line, e_col = unpack(nvim.nvim_call_function("getpos", {"'>"}))
local lines = nvim.nvim_buf_get_lines(0, b_line - 1, e_line, 0)
lines[#lines] = string.sub(lines[#lines], 1, e_col)
lines[1] = string.sub(lines[1], b_col)
iron.debug.ll.store{
b_col = b_col,
e_col = e_col,
b_line = b_line,
e_line = e_line,
lines = lines,
where = "visual_send",
level = iron.behavior.debug_level.info
}
iron.ll.ensure_repl_exists(ft)
iron.ll.send_to_repl(ft, lines)
iron.last.b_line = b_line
iron.last.b_col = b_col
iron.last.e_col = e_col
iron.last.e_line = e_line
end
iron.core.repeat_cmd = function()
local ft = iron.ll.get_buffer_ft(0)
if ft == nil then return end
local b_line, b_col, e_line, e_col
b_line = iron.last.b_line
b_col = iron.last.b_col
e_line = iron.last.e_line
e_col = iron.last.e_col
local lines = nvim.nvim_buf_get_lines(0, b_line - 1, e_line, 0)
lines[#lines] = string.sub(lines[#lines], 1, e_col)
lines[1] = string.sub(lines[1], b_col)
iron.debug.ll.store{
b_col = b_col,
e_col = e_col,
b_line = b_line,
e_line = e_line,
lines = lines,
where = "repeat_cmd",
level = iron.behavior.debug_level.info
}
iron.ll.ensure_repl_exists(ft)
iron.ll.send_to_repl(ft, lines)
end
iron.core.list_fts = function()
local lst = {}
for k, _ in pairs(iron.fts) do
table.insert(lst, k)
end
return lst
end
iron.core.list_definitions_for_ft = function(ft)
local lst = {}
local defs = ext.tables.get(iron.fts, ft)
if defs == nil then
echoerr("There's no REPL definition for current filetype " .. ft)
else
for k, v in pairs(defs) do
table.insert(lst, {k, v})
end
end
return lst
end
iron.debug.ll.store = function(opt)
opt.level = opt.level or iron.behavior.debug_level.info
if opt.level > iron.config.debug_level then
table.insert(iron.debug.mem, opt)
end
end
iron.debug.dump = function(level, to_buff)
level = level or iron.behavior.debug_level.info
local inspect = require("vim.inspect")
local dump
if to_buff then
nvim.nvim_command("rightbelow vertical edit +set\\ nobl\\ bh=delete\\ bt=nofile iron://debug-logs")
dump = function(data)
nvim.nvim_call_function("writefile", {{data}, "iron://debug-logs"})
end
else
dump = function(data)
print(inspect(data))
end
end
for _, v in ipairs(iron.debug.mem) do
if v.level <= level then
dump(v)
end
end
end
iron.core.list_fts = function()
local lst = {}
for k, _ in pairs(iron.fts) do
table.insert(lst, k)
end
return lst
end
iron.core.list_definitions_for_ft = function(ft)
local lst = {}
local defs = ext.tables.get(iron.fts, ft)
if defs == nil then
echoerr ("There's no REPL definition for current filetype " .. ft)
else
for k, v in pairs(defs) do
table.insert(lst, {k, v})
end
end
return lst
end
iron.debug.ll.store = function(opt)
opt.level = opt.level or iron.behavior.debug_level.info
if opt.level > iron.config.debug_level then
table.insert(iron.debug.mem, opt)
end
end
iron.debug.dump = function(level, to_buff)
level = level or iron.behavior.debug_level.info
local inspect = require("vim.inspect")
local dump
if to_buff then
nvim.nvim_command("rightbelow vertical edit +set\\ nobl\\ bh=delete\\ bt=nofile iron://debug-logs")
dump = function(data)
nvim.nvim_call_function("writefile", {{data}, "iron://debug-logs"})
end
else
dump = function(data)
print(inspect(data))
end
end
for _, v in ipairs(iron.debug.mem) do
if v.level <= level then
dump(v)
end
end
end
iron.debug.definitions = function(lang)
local defs = lang and iron.fts[lang] or iron.fts
print(require("vim.inspect")(defs))
end
iron.debug.memory = function()
print(require("vim.inspect")(iron.memory))
end
-- [[ Setup ]] --
iron.config = ext.tables.clone(defaultconfig)
return iron
|
-- A progress bar. Simple functional component, nothing to see here.
local Roact = require(game:GetService("ReplicatedStorage"):WaitForChild("Roact"))
local c = Roact.createElement
local Bar = {}
Bar.Direction = {
Horizontal = 0;
Vertical = 1;
}
Bar.Origin = {
Left = 0;
Middle = 1;
Right = 2;
Top = 0;
Bottom = 2;
}
function Bar.Render(props)
local origin = props.Origin or Bar.Origin.Left
local direction = props.Direction or Bar.Direction.Horizontal
local sizeFraction = props.Value or 0
local anchor, size, position
if direction == Bar.Direction.Horizontal then
size = UDim2.new(sizeFraction, 0, 1, 0)
if origin == Bar.Origin.Left then
anchor = Vector2.new(0, 0)
position = UDim2.new(0, 0, 0, 0)
elseif origin == Bar.Origin.Middle then
anchor = Vector2.new(0.5, 0)
position = UDim2.new(0.5, 0, 0, 0)
elseif origin == Bar.Origin.Right then
anchor = Vector2.new(1, 0)
position = UDim2.new(1, 0, 0, 0)
end
elseif direction == Bar.Direction.Vertical then
size = UDim2.new(1, 0, sizeFraction, 0)
if origin == Bar.Origin.Top then
anchor = Vector2.new(0, 0)
position = UDim2.new(0, 0, 0, 0)
elseif origin == Bar.Origin.Middle then
anchor = Vector2.new(0, 0.5)
position = UDim2.new(0, 0, 0.5, 0)
elseif origin == Bar.Origin.Bottom then
anchor = Vector2.new(0, 1)
position = UDim2.new(0, 0, 1, 0)
end
end
return c("Frame", {
AnchorPoint = props.AnchorPoint or Vector2.new(0, 0),
BackgroundColor3 = props.BackgroundColor3 or Color3.fromRGB(200, 200, 200),
BorderColor3 = props.BorderColor3 or Color3.new(0, 0, 0),
BorderSizePixel = props.BorderSizePixel or 0,
ClipsDescendants = true,
LayoutOrder = props.LayoutOrder or 1,
Position = props.Position or UDim2.new(0, 0, 0, 0),
Size = props.Size or UDim2.new(0, 100, 0, 5),
ZIndex = props.ZIndex or 1,
}, {
RealBar = c("Frame", {
AnchorPoint = anchor,
BackgroundColor3 = props.BarColor3 or Color3.new(0, 0, 0),
BorderSizePixel = 0,
Position = position,
Size = size,
})
})
end
setmetatable(Bar, { __call = function(_, ...) return Bar.Render(...) end })
return Bar
|
-----------------------------------
-- Area: Misareaux Coast
-- NPC: Spacial Displacement
-- Entrance to Riverne Site #A01 and #B01
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:hasCompletedMission(COP,tpz.mission.id.cop.SHELTERING_DOUBT)) then
player:startEvent(551); -- Access to Sites A & B
elseif (player:getCurrentMission(COP) == tpz.mission.id.cop.ANCIENT_VOWS and player:getCharVar("PromathiaStatus") == 1) then
player:startEvent(8);
else
player:startEvent(550); -- Access to Site A Only
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 8) then
player:setCharVar("PromathiaStatus",2);
player:setPos(732.55,-32.5,-506.544,90,30); -- Go to Riverne #A01 {R}
elseif ((csid == 551 or csid == 550) and option == 1) then
player:setPos(732.55,-32.5,-506.544,90,30); -- Go to Riverne #A01 {R}
elseif (csid == 551 and option == 2) then
player:setPos(729.749,-20.319,407.153,90,29); -- Go to Riverne #B01 {R}
end;
end;
|
-- icarus v1.3.0
--
-- I warn you, fly a middle
-- course: go too low & water
-- will weigh you down;
-- go too high and the sun's
-- fire will burn you.
-- keep to the middle way.
--
-- (plug in midi keyboard first)
-- E1 = time
-- E2 = filter
-- E3 = feedback
-- K1,2,3 bounce
-- speeding up time more easily
-- destroys the sun
engine.name="Icarus"
icarus=include("icarus/lib/icarus")
local MusicUtil=require "musicutil"
local Formatters=require 'formatters'
local feedback_temp=0
local vol_current=0
local vol_target=0
local time_change=0
local time_button=false
local filter_change=0
local filter_button=false
local current_time=0
function init()
skeys=icarus:new()
setup_midi()
-- osc input
osc.event=osc_in
clock.run(redraw_clock)
end
function setup_midi()
-- get list of devices
local mididevice={}
local mididevice_list={"none"}
midi_channels={"all"}
for i=1,16 do
table.insert(midi_channels,i)
end
for _,dev in pairs(midi.devices) do
if dev.port~=nil then
local name=string.lower(dev.name)
table.insert(mididevice_list,name)
print("adding "..name.." to port "..dev.port)
mididevice[name]={
name=name,
port=dev.port,
midi=midi.connect(dev.port),
active=false,
}
mididevice[name].midi.event=function(data)
if mididevice[name].active==false then
do return end
end
local d=midi.to_msg(data)
--if d.type~="clock" then
-- tab.print(d)
--end
if d.ch~=midi_channels[params:get("midichannel")] and params:get("midichannel")>1 then
do return end
end
if d.type=="note_on" then
skeys:on(d.note)
elseif d.type=="note_off" then
skeys:off(d.note)
elseif d.type=="pitchbend" then
local bend_st = (util.round(d.val / 2)) / 8192 * 2 -1 -- Convert to -1 to 1
engine.bend(bend_st * params:get("bend_range"))
end
end
end
end
tab.print(mididevice_list)
params:add{type="option",id="midi",name="midi in",options=mididevice_list,default=1}
params:set_action("midi",function(v)
if v==1 then
do return end
end
for name,_ in pairs(mididevice) do
mididevice[name].active=false
end
mididevice[mididevice_list[v]].active=true
end)
params:add{type="option",id="midichannel",name="midi ch",options=midi_channels,default=1}
params:add_number("bend_range", "bend range", 0, 48, 2)
if #mididevice_list>1 then
params:set("midi",2)
end
end
function enc(k,d)
if k==1 then
params:delta("delaytime",d)
if params:get("delaytime")<0.25 then
params:delta("destruction",d)
-- params:set("pressdisablesfeedback",2)
else
-- params:set("pressdisablesfeedback",1)
end
elseif k==2 then
params:delta("lpf",-1*sign(d))
elseif k==3 then
params:delta("feedback",d)
end
end
function key(k,z)
if k==1 then
time_button=z==1
elseif k==2 then
filter_button=z==1
elseif k==3 then
if z==1 then
feedback_temp=params:get("feedback")
params:set("feedback",0.85)
else
params:set("feedback",feedback_temp)
end
end
end
function redraw_clock() -- our grid redraw clock
while true do -- while it's running...
-- if time button is on, do some shifting
if time_button then
time_change=time_change-1
params:delta("delaytime",3)
elseif time_change<0 then
time_change=time_change+1
params:delta("delaytime",-3)
end
if filter_button then
filter_change=filter_change-1
params:delta("lpf",-1)
elseif filter_change<0 then
filter_change=filter_change+1
params:delta("lpf",1)
end
-- have this clock move target volume to current volume
if math.abs(vol_target-vol_current)>0.005 then
vol_current=vol_current+sign(vol_target-vol_current)/200
end
-- print(vol_current,vol_target)
clock.sleep(1/14) -- refresh
current_time=current_time+1/14
redraw()
end
end
function redraw()
screen.clear()
-- make the sun curve in the sky based on delay time
local delay_range={0.05,0.5}
local rdelay=util.linlin(delay_range[1],delay_range[2],270,90,params:get("delaytime"))
local center={64,32}
local rpos={center[1]+40*math.sin(math.rad(rdelay)),center[2]+40*math.cos(math.rad(rdelay))}
local rfeedback=util.linlin(0.9,1.5,4,20,params:get("feedback"))
local rvolume=util.linlin(0,1,0,32,vol_current)
local rlow=rfeedback
local rhigh=rfeedback+rvolume
for i=rhigh,rlow,-1 do
local ll=math.floor(util.linlin(rlow,rhigh,14,1,i))
screen.level(ll)
i=i*math.pow(1.5,1/ll)
screen.circle(rpos[1],rpos[2]+10,i)
screen.fill()
end
screen.level(15)
screen.circle(rpos[1],rpos[2]+10,rfeedback)
screen.fill()
screen.update()
-- the ocean
local rfilter=util.linlin(0,18000,20,62,params:get("lpf"))
-- screen.level(0)
-- screen.rect(0,rfilter,129,65)
-- screen.fill()
-- -- draw reflection of the sun in the water
-- screen.level(1)
-- screen.move(0,rfilter)
-- screen.line(129,rfilter)
-- screen.stroke()
-- screen.level(10)
-- for i=1,10 do
-- screen.level(11-i)
-- screen.move(rpos[1]-rfeedback/i*0.8,rfilter+i*2)
-- screen.line(rpos[1]+rfeedback/i*0.8,rfilter+i*2)
-- screen.stroke()
-- end
local horizon=math.floor(rfilter)
--cls()
-- circfill(30,22,15,7)
screen.update()
math.randomseed(4)
screen.level(0)
screen.rect(0,rfilter,129,65)
screen.fill()
for y=0,64 do
local z=64/(y+1)
for i=0,z*5 do
x=(rnd(160)+current_time*160/z)%150-16
w=cos(rnd()+current_time)*12/z
if (w>0) then
local s = screen.peek(math.floor(x),math.floor(horizon-1-y/2), math.floor(x+1),math.floor(horizon-y/2))
if s ~= nil then
local pgot = util.clamp(string.byte(s,1),1,15)
screen.level(pgot+1)
screen.move(x-w,y+horizon)
screen.line(x+w,y+horizon)
screen.stroke()
end
end
end
end
screen.update()
end
--- Cos of value
-- Value is expected to be between 0..1 (instead of 0..360)
-- @param x value
function cos(x)
return math.cos(math.rad(x * 360))
end
function rnd(x)
if x == 0 then
return 0
end
if (not x) then
x = 1
end
x = x * 100
x = math.random(x) / 100
return x
end
function rerun()
norns.script.load(norns.state.script)
end
function sign(x)
if x>0 then
return 1
elseif x<0 then
return-1
else
return 0
end
end
--
-- osc
--
function osc_in(path,args,from)
vol_target=util.linlin(0,0.15,0,1,args[2])
end
|
electrician_energy_absorption = class( AbilityBaseClass )
LinkLuaModifier( "modifier_electrician_energy_absorption", "abilities/electrician/electrician_energy_absorption.lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
function electrician_energy_absorption:OnSpellStart()
local caster = self:GetCaster()
local casterOrigin = caster:GetAbsOrigin()
local radius = self:GetSpecialValueFor( "radius" )
-- grab all enemes around the caster
local units = FindUnitsInRadius(
caster:GetTeamNumber(),
casterOrigin,
nil,
radius,
self:GetAbilityTargetTeam(),
self:GetAbilityTargetType(),
self:GetAbilityTargetFlags(),
FIND_ANY_ORDER,
false
)
-- make the aoe particle, it's dumbshit as of this comment's writing because
--
-- i don't need an excuse i'm not doing aesthetics
local part = ParticleManager:CreateParticle( "particles/econ/generic/generic_aoe_explosion_sphere_1/generic_aoe_explosion_sphere_1.vpcf", PATTACH_ABSORIGIN, caster )
ParticleManager:SetParticleControl( part, 1, Vector( radius, radius, radius ) )
ParticleManager:SetParticleControl( part, 2, Vector( 1, 1, 1 ) )
ParticleManager:ReleaseParticleIndex( part )
-- play sound
caster:EmitSound( "Hero_StormSpirit.StaticRemnantPlant" )
-- make particle
-- caster:AddNewModifier( caster, self, "modifier_electrician_shell", {
-- duration = self:GetSpecialValueFor( "move_speed_duration" )
-- } )
-- don't bother with anything after this if we didnt' hit a single enemy
if #units > 0 then
-- grab abilityspecials
local damage = self:GetSpecialValueFor( "damage" )
local damageType = self:GetAbilityDamageType()
local manaBreak = self:GetSpecialValueFor( "mana_break" ) * 0.01
local manaRestoreCreep = self:GetSpecialValueFor( "creep_mana_restore" )
local manaRestoreHero = self:GetSpecialValueFor( "hero_mana_restore" )
-- talent integration
local talent = self:GetCaster():FindAbilityByName( "special_bonus_electrician_absorption_hero_mana_restore" )
if talent and talent:GetLevel() > 0 then
manaRestoreHero = manaRestoreHero * talent:GetSpecialValueFor( "value" )
end
-- set up the amount of mana restored by this cast
local manaRestored = 0
-- iterate through each unit struck
for _, target in pairs( units ) do
-- deal damage
ApplyDamage( {
victim = target,
attacker = caster,
damage = damage,
damage_type = damageType,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
ability = self,
} )
-- track the starting mana
local manaStart = target:GetMana()
-- don't bother breaking mana if they have none
if manaStart > 0 then
target:ReduceMana( target:GetMaxMana() * manaBreak )
-- for the mana burn number; restricting to heroes as to
-- reduce spam, can't ignore illusions tho because
-- that'd make it too obvious
if target:IsHero() then
local manaBurnt = math.floor( manaStart - target:GetMana() )
local numLength = tostring( manaBurnt ):len() + 1
local partNum = ParticleManager:CreateParticle( "particles/units/heroes/hero_nyx_assassin/nyx_assassin_mana_burn_msg.vpcf", PATTACH_OVERHEAD_FOLLOW, target )
ParticleManager:SetParticleControl( partNum, 1, Vector( 1, manaBurnt, 0 ) )
ParticleManager:SetParticleControl( partNum, 2, Vector( 1, numLength, 0 ) )
ParticleManager:ReleaseParticleIndex( partNum )
end
end
-- figure out the mana restore amount for this unit
if target:IsRealHero() then
manaRestored = manaRestored + manaRestoreHero
else
manaRestored = manaRestored + manaRestoreCreep
end
-- create a projectile that's just for visual effect
-- would like to just have a particle here that hits the caster
-- after like ~0.25 seconds
ProjectileManager:CreateTrackingProjectile( {
Ability = self,
Target = caster,
Source = target,
EffectName = "particles/units/heroes/hero_zuus/zuus_base_attack.vpcf",
iMoveSpeed = caster:GetRangeToUnit( target ) / 0.25,
iSourceAttachment = DOTA_PROJECTILE_ATTACHMENT_HITLOCATION,
bDodgeable = false,
flExpireTime = GameRules:GetGameTime() + 10,
} )
-- play hit sound
target:EmitSound( "Hero_StormSpirit.Attack" )
end
-- now that we're done with all the hit units
-- add the mana restored to the caster and
-- do a number for all mana restored
caster:GiveMana( manaRestored )
SendOverheadEventMessage( caster:GetPlayerOwner(), OVERHEAD_ALERT_MANA_ADD, caster, manaRestored, nil )
-- give the speed modifier
caster:AddNewModifier( caster, self, "modifier_electrician_energy_absorption", {
duration = self:GetSpecialValueFor( "move_speed_duration" )
} )
end
end
--------------------------------------------------------------------------------
modifier_electrician_energy_absorption = class( ModifierBaseClass )
--------------------------------------------------------------------------------
function modifier_electrician_energy_absorption:IsDebuff()
return false
end
function modifier_electrician_energy_absorption:IsHidden()
return false
end
function modifier_electrician_energy_absorption:IsPurgable()
return true
end
--------------------------------------------------------------------------------
function modifier_electrician_energy_absorption:OnCreated( event )
local parent = self:GetParent()
self.partShell = ParticleManager:CreateParticle( "particles/hero/electrician/electrician_energy_absorbtion.vpcf", PATTACH_ABSORIGIN_FOLLOW, parent )
ParticleManager:SetParticleControlEnt( self.partShell, 1, parent, PATTACH_ABSORIGIN_FOLLOW, nil, parent:GetAbsOrigin(), true )
self.moveSpeed = self:GetAbility():GetSpecialValueFor( "move_speed_bonus" )
end
--------------------------------------------------------------------------------
function modifier_electrician_energy_absorption:OnRefresh( event )
self.moveSpeed = self:GetAbility():GetSpecialValueFor( "move_speed_bonus" )
-- destroy the shield particles
ParticleManager:DestroyParticle( self.partShell, false )
ParticleManager:ReleaseParticleIndex( self.partShell )
end
--------------------------------------------------------------------------------
function modifier_electrician_energy_absorption:OnDestroy()
-- destroy the shield particles
ParticleManager:DestroyParticle( self.partShell, false )
ParticleManager:ReleaseParticleIndex( self.partShell )
end
--------------------------------------------------------------------------------
function modifier_electrician_energy_absorption:DeclareFunctions()
local func = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT,
}
return func
end
--------------------------------------------------------------------------------
function modifier_electrician_energy_absorption:GetModifierMoveSpeedBonus_Constant( event )
return self.moveSpeed
end
|
spider_egg_sack = class( AbilityBaseClass )
LinkLuaModifier( "modifier_spider_egg_sack", "modifiers/modifier_spider_egg_sack", LUA_MODIFIER_MOTION_NONE )
-------------------------------------------------------------------------
function spider_egg_sack:GetIntrinsicModifierName()
return "modifier_spider_egg_sack"
end
|
-- A set of functions which aids the other lua scripts
local function toFactorioUnit(settings, kmH)
if settings.global["aircraft-speed-unit"].value == "imperial" then
kmH = kmH * 1.609 --Thanks google!
end
-- Convert the lua speed into km/h with * 60 * 3.6
return kmH / 216
end
-- Converts factorio's speed to km/h or mph per runtime global
local function fromFactorioUnit(settings, unit)
unit = unit * 216
if settings.global["aircraft-speed-unit"].value == "imperial" then
unit = unit / 1.609
end
return unit
end
-- Converts factorio's speed to km/h or mph per the user's settings
local function fromFactorioUnitUser(settings, player, unit)
unit = unit * 216
if settings.get_player_settings(player)["aircraft-realism-user-speed-unit"].value == "imperial" then
unit = unit / 1.609
end
return unit
end
local function getTableLength(table)
local count = 0
for _ in pairs(table) do
count = count + 1
end
return count
end
local function roundNumber(number)
if (number - (number % 0.1)) - (number - (number % 1)) < 0.5 then
number = number - (number % 1)
else
number = (number - (number % 1)) + 1
end
return number
end
-- You have no idea how scared I am writing a new function in Lua after seeing nils from all sorts of places
local function playSound(settings, player, soundName)
if settings.get_player_settings(player)["aircraft-realism-sounds-enabled"].value then
player.play_sound({path=soundName})
end
end
-- Makes these functions available to the lua script which requires this file
local functions = {}
functions.toFactorioUnit = toFactorioUnit
functions.fromFactorioUnit = fromFactorioUnit
functions.fromFactorioUnitUser = fromFactorioUnitUser
functions.getTableLength = getTableLength
functions.roundNumber = roundNumber
functions.playSound = playSound
return functions
|
--[[
Info.lua
--]]
return {
appName = "Raw Plus Jpeg",
author = "Rob Cole",
authorsWebsite = "www.robcole.com",
donateUrl = "http://www.robcole.com/Rob/Donate",
platforms = { 'Windows', 'Mac' },
pluginId = "com.robcole.lightroom.RawPlusJpeg",
xmlRpcUrl = "http://www.robcole.com/Rob/_common/cfpages/XmlRpc.cfm",
LrPluginName = "rc Raw Plus Jpeg",
LrSdkMinimumVersion = 3.0,
LrSdkVersion = 5.0,
LrPluginInfoUrl = "http://www.robcole.com/Rob/ProductsAndServices/RawPlusJpegLrPlugin",
LrPluginInfoProvider = "ExtendedManager.lua",
LrToolkitIdentifier = "com.robcole.RawPlusJpeg",
LrInitPlugin = "Init.lua",
LrShutdownPlugin = "Shutdown.lua",
LrMetadataTagsetFactory = "Tagsets.lua",
LrLibraryMenuItems = {
{
title = "&Find Raws with Jpegs",
file = "mFindRawsWithJpegs.lua",
},
{
title = "&View Jpegs",
file = "mViewJpegs.lua",
},
{
title = "&Sync (RAW -> JPEG)",
file = "mSyncRawToJpeg.lua",
},
{
title = "&Sync (JPEG -> RAW)",
file = "mSyncJpegToRaw.lua",
},
{
title = "Delete Jpegs",
file = "mDeleteJpegs.lua",
},
{
title = "&Import Jpegs",
file = "mImportJpegs.lua",
},
{
title = "E&xtract Jpegs",
file = "mExtractJpegs.lua",
},
},
VERSION = { display = "2.5.2 Build: 2013-10-02 23:18:32" },
}
|
output_directory = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}/"
build_directory = "%{wks.location}/build/bin/" .. output_directory .. "%{prj.name}"
int_build_directory = "%{wks.location}/build/bin-int/" .. output_directory .. "%{prj.name}"
project_dirs = {
engine = "%{wks.location}/projects/hydra",
sandbox = "%{wks.location}/projects/sandbox",
spdlog = "%{wks.location}/projects/vendor/spdlog",
GLFW = "%{wks.location}/projects/vendor/glfw",
vulkan = os.getenv("VULKAN_SDK"),
}
include_dirs = {
engine = "%{project_dirs.engine}/src",
sandbox = "%{project_dirs.sandbox}/src",
spdlog = "%{project_dirs.spdlog}/include",
GLFW = "%{project_dirs.GLFW}/include",
vulkan = "%{project_dirs.vulkan}/Include",
}
|
-- Thanks Acecool and HandsomeMatt for your code
local function generateCircle( radius )
local seg = 100
local cir = {}
table.insert( cir, { x = 0, y = 0, u = 0.5, v = 0.5 } )
for i = 0, seg do
local a = math.rad( ( i / seg ) * -360 )
table.insert( cir, { x = radius / 2 + math.sin( a ) * radius * 0.5, y = radius / 2 + math.cos( a ) * radius * 0.5, u = math.sin( a ) / 2 + 0.5, v = math.cos( a ) / 2 + 0.5 } )
end
local a = math.rad( 0 ) -- This is needed for non absolute segment counts
table.insert( cir, { x = radius / 2 + math.sin( a ) * radius * 0.5, y = radius / 2 + math.cos( a ) * radius * 0.5, u = math.sin( a ) / 2 + 0.5, v = math.cos( a ) / 2 + 0.5 } )
return cir
end
local _material = Material( "effects/flashlight001" );
local PANEL = {}
function PANEL:Init()
self.Avatar = vgui.Create( "AvatarImage", self )
self.Avatar:SetPaintedManually( true )
self:UpdatePoly()
end
function PANEL:UpdatePoly()
self.poly = generateCircle( self:GetWide() )
end
function PANEL:OnSizeChanged()
self:SetSize( self:GetWide(), self:GetWide() )
self:UpdatePoly()
end
function PANEL:PerformLayout()
self.Avatar:SetSize( self:GetWide(), self:GetTall() )
end
function PANEL:Paint( w, h )
render.ClearStencil()
render.SetStencilEnable( true )
render.SetStencilWriteMask( 1 )
render.SetStencilTestMask( 1 )
render.SetStencilFailOperation( STENCIL_REPLACE )
render.SetStencilPassOperation( STENCIL_ZERO )
render.SetStencilZFailOperation( STENCIL_ZERO )
render.SetStencilCompareFunction( STENCIL_NEVER )
render.SetStencilReferenceValue( 1 )
draw.NoTexture( );
surface.SetMaterial( _material );
surface.SetDrawColor( color_black )
surface.DrawPoly( self.poly )
render.SetStencilFailOperation( STENCIL_ZERO )
render.SetStencilPassOperation( STENCIL_REPLACE )
render.SetStencilZFailOperation( STENCIL_ZERO )
render.SetStencilCompareFunction( STENCIL_EQUAL )
render.SetStencilReferenceValue( 1 )
self.Avatar:SetPaintedManually( false )
self.Avatar:PaintManual()
self.Avatar:SetPaintedManually( true )
render.SetStencilEnable( false )
render.ClearStencil()
end
function PANEL:SetPlayer( ply )
self.Avatar:SetPlayer( ply )
end
function PANEL:SetClickable( c )
self.clickable = c
if self.clickable then
function self.Avatar.OnMousePressed( keyCode )
if keyCode == MOUSE_LEFT then
ply:ShowProfile()
end
end
self.Avatar:SetCursor( "hand" )
else
self.Avatar.OnMousePressed = nil
self.Avatar:SetCursor( "none" )
end
end
function PANEL:GetClickable()
return self.clickable
end
vgui.Register( "AvatarImageCircle", PANEL )
|
-- Copyright 2011 by Jannis Pohlmann
--
-- This file may be distributed and/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/layered/NodeRankingGansnerKNV1993.lua,v 1.1 2012/11/27 17:24:26 tantau Exp $
local NodeRankingGansnerKNV1993 = {}
-- Imports
local Edge = require "pgf.gd.deprecated.Edge"
local Node = require "pgf.gd.deprecated.Node"
local NetworkSimplex = require "pgf.gd.layered.NetworkSimplex"
function NodeRankingGansnerKNV1993:run()
local simplex = NetworkSimplex.new(self.graph, NetworkSimplex.BALANCE_TOP_BOTTOM)
simplex:run()
self.ranking = simplex.ranking
return simplex.ranking
end
function NodeRankingGansnerKNV1993:mergeClusters()
self.cluster_nodes = {}
self.cluster_node = {}
self.cluster_edges = {}
self.original_nodes = {}
self.original_edges = {}
for _,cluster in ipairs(self.graph.clusters) do
local cluster_node = Node.new{
name = 'cluster@' .. cluster.name,
}
table.insert(self.cluster_nodes, cluster_node)
for _,node in ipairs(cluster.nodes) do
self.cluster_node[node] = cluster_node
table.insert(self.original_nodes, node)
end
self.graph:addNode(cluster_node)
end
for _,edge in ipairs(self.graph.edges) do
local tail = edge:getTail()
local head = edge:getHead()
if self.cluster_node[tail] or self.cluster_node[head] then
table.insert(self.original_edges, edge)
local cluster_edge = Edge.new{
direction = Edge.RIGHT,
weight = edge.weight,
minimum_levels = edge.minimum_levels,
}
table.insert(self.cluster_edges, cluster_edge)
if self.cluster_node[tail] then
cluster_edge:addNode(self.cluster_node[tail])
else
cluster_edge:addNode(tail)
end
if self.cluster_node[head] then
cluster_edge:addNode(self.cluster_node[head])
else
cluster_edge:addNode(head)
end
end
end
for _,edge in ipairs(self.cluster_edges) do
self.graph:addEdge(edge)
end
for _,edge in ipairs(self.original_edges) do
self.graph:deleteEdge(edge)
end
for _,node in ipairs(self.original_nodes) do
self.graph:deleteNode(node)
end
end
function NodeRankingGansnerKNV1993:createClusterEdges()
for n = 1, #self.cluster_nodes-1 do
local first_cluster = self.cluster_nodes[n]
local second_cluster = self.cluster_nodes[n+1]
local edge = Edge.new{
direction = Edge.RIGHT,
weight = 1,
minimum_levels = 1,
}
edge:addNode(first_cluster)
edge:addNode(second_cluster)
self.graph:addEdge(edge)
table.insert(self.cluster_edges, edge)
end
end
function NodeRankingGansnerKNV1993:removeClusterEdges()
end
function NodeRankingGansnerKNV1993:expandClusters()
for _,node in ipairs(self.original_nodes) do
assert(self.ranking:getRank(self.cluster_node[node]))
self.ranking:setRank(node, self.ranking:getRank(self.cluster_node[node]))
self.graph:addNode(node)
end
for _,edge in ipairs(self.original_edges) do
for _,node in ipairs(edge.nodes) do
node:addEdge(edge)
end
self.graph:addEdge(edge)
end
for _,node in ipairs(self.cluster_nodes) do
self.ranking:setRank(node, nil)
self.graph:deleteNode(node)
end
for _,edge in ipairs(self.cluster_edges) do
self.graph:deleteEdge(edge)
end
end
-- done
return NodeRankingGansnerKNV1993
|
local awful = require('awful')
local wibox = require('wibox')
local gears = require('gears')
local beautiful = require('beautiful')
local dpi = beautiful.xresources.apply_dpi
local clickable_container = require('widget.clickable-container')
-- Variable used for switching panel modes
right_panel_mode = 'today_mode'
local active_button = beautiful.groups_title_bg
local inactive_button = beautiful.transparent
local notif_text = wibox.widget
{
text = 'Notifications',
font = 'Inter Bold 11',
align = 'center',
valign = 'center',
widget = wibox.widget.textbox
}
local notif_button = clickable_container(
wibox.container.margin(
notif_text, dpi(0), dpi(0), dpi(7), dpi(7)
)
)
local wrap_notif = wibox.widget {
notif_button,
forced_width = dpi(140),
bg = inactive_button,
border_width = dpi(1),
border_color = beautiful.groups_title_bg,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(
cr, width, height, false, true, true, false, beautiful.groups_radius
)
end,
widget = wibox.container.background
}
local today_text = wibox.widget {
text = 'Today',
font = 'Inter Bold 11',
align = 'center',
valign = 'center',
widget = wibox.widget.textbox
}
local today_button = clickable_container(
wibox.container.margin(
today_text, dpi(0), dpi(0), dpi(7), dpi(7)
)
)
local wrap_today = wibox.widget {
today_button,
forced_width = dpi(140),
bg = active_button,
border_width = dpi(1),
border_color = beautiful.groups_title_bg,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(
cr, width, height, true, false, false, true, beautiful.groups_radius
)
end,
widget = wibox.container.background
}
local switcher = wibox.widget {
expand = 'none',
layout = wibox.layout.fixed.horizontal,
wrap_today,
wrap_notif
}
function switch_rdb_pane(right_panel_mode)
local focused = awful.screen.focused()
if right_panel_mode == 'notif_mode' then
-- Update button color
wrap_notif.bg = active_button
wrap_today.bg = inactive_button
-- Change panel content of right-panel.lua
focused.right_panel:switch_pane(right_panel_mode)
elseif right_panel_mode == 'today_mode' then
-- Update button color
wrap_notif.bg = inactive_button
wrap_today.bg = active_button
-- Change panel content of right-panel.lua
focused.right_panel:switch_pane(right_panel_mode)
end
end
notif_button:buttons(
gears.table.join(
awful.button(
{},
1,
nil,
function()
switch_rdb_pane('notif_mode')
end
)
)
)
today_button:buttons(
gears.table.join(
awful.button(
{},
1,
nil,
function()
switch_rdb_pane('today_mode')
end
)
)
)
return switcher
|
vim.cmd "colorscheme tokyonight"
|
local _ = require ('ludash')
local observable = require('rx.observable')
return function()
return observable(_.noop)
end
|
---------------------------------------------------------------------------------------------------
--
--filename: game.ui.battle.PausePanel
--date:2019/11/21 16:21:51
--author:heguang
--desc:暂停面板
--
---------------------------------------------------------------------------------------------------
local strClassName = 'game.ui.battle.PausePanel'
local PausePanel = lua_declare(strClassName, lua_class(strClassName))
function PausePanel:Start()
local btnContinue = self.transform:Find("ButtonContinue")
if btnContinue ~= nil then
EventListener.Get(btnContinue, self).onClick = self.ContinuePlayHandler
end
local btnHome = self.transform:Find("ButtonHome")
if btnHome ~= nil then
EventListener.Get(btnHome, self).onClick = self.GoHomeHandler
end
LuaGameUtil.SetPause(true)
end
function PausePanel:OnDestroy()
LuaGameUtil.SetPause(false)
end
function PausePanel:GoHomeHandler()
Dialog.Hide()
LuaGameUtil.LoadHomeScene()
end
function PausePanel:ContinuePlayHandler()
Dialog.Hide()
end
return PausePanel
|
pg = pg or {}
pg.enemy_data_statistics_180 = {
[11800312] = {
cannon = 0,
battle_unit_type = 35,
rarity = 1,
speed_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
luck = 0,
dodge = 0,
wave_fx = "danchuanlanghuaxiao2",
cannon_growth = 0,
speed = 15,
reload_growth = 0,
dodge_growth = 0,
id = 11800312,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
reload = 150,
base = 70,
durability = 280,
armor_growth = 0,
torpedo_growth = 864,
luck_growth = 0,
hit_growth = 120,
armor = 0,
torpedo = 70,
durability_growth = 2550,
antisub = 0,
antiaircraft = 0,
antiaircraft_growth = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
569051
}
},
[11800313] = {
cannon = 60,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 80000,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 120,
durability_growth = 2550,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 1200,
star = 1,
hit = 81,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 15,
base = 80,
durability = 80,
armor_growth = 0,
torpedo_growth = 900,
luck_growth = 0,
speed = 30,
luck = 0,
id = 11800313,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
569052
}
},
[11800321] = {
cannon = 80,
reload = 150,
speed_growth = 0,
cannon_growth = 1600,
pilot_ai_template_id = 10001,
air = 0,
rarity = 4,
dodge = 11,
torpedo = 125,
durability_growth = 193600,
antiaircraft = 200,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 5,
hit = 16,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 90,
base = 190,
durability = 9220,
armor_growth = 0,
torpedo_growth = 2000,
luck_growth = 0,
speed = 20,
luck = 15,
id = 11800321,
antiaircraft_growth = 3600,
antisub = 0,
armor = 0,
appear_fx = {},
equipment_list = {
1100347,
1100377,
1100217,
1100497
}
},
[11800322] = {
cannon = 115,
reload = 150,
speed_growth = 0,
cannon_growth = 2000,
rarity = 5,
air = 0,
torpedo = 75,
dodge = 11,
durability_growth = 228800,
antiaircraft = 155,
luck = 15,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 6,
hit = 16,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 90,
base = 264,
durability = 11030,
armor_growth = 0,
torpedo_growth = 1500,
luck_growth = 0,
speed = 20,
armor = 0,
id = 11800322,
antiaircraft_growth = 3200,
antisub = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100027,
1101517,
1100447,
1101522
}
},
[11800323] = {
cannon = 80,
reload = 150,
speed_growth = 0,
cannon_growth = 1600,
pilot_ai_template_id = 10001,
air = 0,
rarity = 4,
dodge = 11,
torpedo = 125,
durability_growth = 211200,
antiaircraft = 200,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 5,
hit = 16,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 90,
base = 190,
durability = 10060,
armor_growth = 0,
torpedo_growth = 2000,
luck_growth = 0,
speed = 20,
luck = 15,
id = 11800323,
antiaircraft_growth = 3600,
antisub = 0,
armor = 0,
appear_fx = {},
equipment_list = {
1100347,
1100377,
1100217,
1100497
}
},
[11800324] = {
cannon = 115,
reload = 150,
speed_growth = 0,
cannon_growth = 2000,
rarity = 5,
air = 0,
torpedo = 75,
dodge = 11,
durability_growth = 249600,
antiaircraft = 155,
luck = 15,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 6,
hit = 16,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 90,
base = 264,
durability = 12040,
armor_growth = 0,
torpedo_growth = 1500,
luck_growth = 0,
speed = 20,
armor = 0,
id = 11800324,
antiaircraft_growth = 3200,
antisub = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100027,
1101517,
1100447,
1101522
}
},
[11800325] = {
cannon = 140,
battle_unit_type = 90,
rarity = 4,
speed_growth = 0,
pilot_ai_template_id = 10001,
air = 0,
luck = 15,
dodge = 11,
id = 11800325,
cannon_growth = 2500,
speed = 20,
reload_growth = 0,
dodge_growth = 156,
reload = 150,
star = 5,
hit = 16,
antisub_growth = 0,
air_growth = 0,
torpedo = 0,
base = 222,
durability = 16730,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 210,
armor = 0,
durability_growth = 326400,
antiaircraft = 175,
antisub = 0,
antiaircraft_growth = 3600,
smoke = {
{
70,
{
{
"smoke",
{
0.59,
0.87,
0.28
}
}
}
},
{
40,
{
{
"smoke",
{
-0.83,
2.62,
1.31
}
}
}
}
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100022,
1101527,
1101532,
1101537
},
buff_list = {
{
ID = 50500,
LV = 3
}
}
},
[11800326] = {
cannon = 80,
reload = 150,
speed_growth = 0,
cannon_growth = 1600,
pilot_ai_template_id = 10001,
air = 0,
rarity = 4,
dodge = 11,
torpedo = 125,
durability_growth = 228800,
antiaircraft = 200,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 5,
hit = 16,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 90,
base = 190,
durability = 10890,
armor_growth = 0,
torpedo_growth = 2000,
luck_growth = 0,
speed = 20,
luck = 15,
id = 11800326,
antiaircraft_growth = 3600,
antisub = 0,
armor = 0,
appear_fx = {},
equipment_list = {
1100347,
1100377,
1100217,
1100497
}
},
[11800327] = {
cannon = 115,
reload = 150,
speed_growth = 0,
cannon_growth = 2000,
rarity = 5,
air = 0,
torpedo = 75,
dodge = 11,
durability_growth = 270400,
antiaircraft = 155,
luck = 15,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 6,
hit = 16,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 90,
base = 264,
durability = 13040,
armor_growth = 0,
torpedo_growth = 1500,
luck_growth = 0,
speed = 20,
armor = 0,
id = 11800327,
antiaircraft_growth = 3200,
antisub = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100027,
1101517,
1100447,
1101522
}
},
[11800328] = {
cannon = 140,
battle_unit_type = 90,
rarity = 4,
speed_growth = 0,
pilot_ai_template_id = 10001,
air = 0,
luck = 15,
dodge = 11,
id = 11800328,
cannon_growth = 2500,
speed = 20,
reload_growth = 0,
dodge_growth = 156,
reload = 150,
star = 5,
hit = 16,
antisub_growth = 0,
air_growth = 0,
torpedo = 0,
base = 222,
durability = 18120,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
hit_growth = 210,
armor = 0,
durability_growth = 353600,
antiaircraft = 175,
antisub = 0,
antiaircraft_growth = 3600,
smoke = {
{
70,
{
{
"smoke",
{
0.59,
0.87,
0.28
}
}
}
},
{
40,
{
{
"smoke",
{
-0.83,
2.62,
1.31
}
}
}
}
},
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
1100022,
1101527,
1101532,
1101537
},
buff_list = {
{
ID = 50500,
LV = 3
}
}
},
[11800329] = {
cannon = 75,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 10001,
air = 160,
rarity = 5,
dodge = 11,
torpedo = 0,
durability_growth = 312000,
antiaircraft = 190,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 6,
hit = 16,
antisub_growth = 0,
air_growth = 3500,
battle_unit_type = 90,
base = 241,
durability = 15250,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 20,
luck = 15,
id = 11800329,
antiaircraft_growth = 3200,
antisub = 0,
armor = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
1100022,
1100312,
1100352,
1100797,
1100802,
1100807
}
},
[11800331] = {
cannon = 120,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 10001,
air = 0,
rarity = 1,
dodge = 22,
torpedo = 240,
durability_growth = 0,
antiaircraft = 185,
reload_growth = 0,
dodge_growth = 312,
hit_growth = 210,
star = 5,
hit = 25,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 95,
base = 333,
durability = 36500,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 18,
luck = 18,
id = 11800331,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
606060,
606061,
606062
}
},
[11800332] = {
cannon = 185,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 10001,
air = 0,
rarity = 1,
dodge = 20,
torpedo = 200,
durability_growth = 0,
antiaircraft = 245,
reload_growth = 0,
dodge_growth = 284,
hit_growth = 210,
star = 5,
hit = 22,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 95,
base = 334,
durability = 49500,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 18,
luck = 18,
id = 11800332,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
606070,
606071,
606072,
606073,
606074
}
},
[11800333] = {
cannon = 255,
hit_growth = 210,
rarity = 4,
speed_growth = 0,
pilot_ai_template_id = 10001,
air = 0,
luck = 20,
dodge = 20,
cannon_growth = 0,
speed = 18,
reload = 150,
reload_growth = 0,
dodge_growth = 284,
id = 11800333,
star = 5,
hit = 20,
antisub_growth = 0,
air_growth = 0,
torpedo = 150,
base = 335,
durability = 62500,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
battle_unit_type = 95,
armor = 0,
durability_growth = 0,
antiaircraft = 325,
antisub = 0,
antiaircraft_growth = 0,
appear_fx = {
"bossguangxiao",
"appearQ"
},
equipment_list = {
606080,
606081,
606082,
606083,
606084
},
buff_list = {
{
ID = 50500,
LV = 3
}
}
},
[11800401] = {
cannon = 8,
reload = 150,
speed_growth = 0,
cannon_growth = 560,
pilot_ai_template_id = 20005,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 36,
durability_growth = 13200,
antiaircraft = 80,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 25,
base = 105,
durability = 640,
armor_growth = 0,
torpedo_growth = 3250,
luck_growth = 0,
speed = 15,
luck = 0,
id = 11800401,
antiaircraft_growth = 1000,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1100103,
1100498
}
},
[11800402] = {
cannon = 8,
reload = 150,
speed_growth = 0,
cannon_growth = 560,
pilot_ai_template_id = 20005,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 36,
durability_growth = 13200,
antiaircraft = 80,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 144,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 25,
base = 101,
durability = 640,
armor_growth = 0,
torpedo_growth = 3250,
luck_growth = 0,
speed = 15,
luck = 0,
id = 11800402,
friendly_cld = 1,
antisub = 0,
antiaircraft_growth = 1000,
armor = 0,
equipment_list = {
1100483,
1100078
}
}
}
return
|
function plas_wall_images()
return
{single =
{
layers =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-single.png",
priority = "extra-high",
width = 32,
height = 46,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, -6),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-single.png",
priority = "extra-high",
width = 64,
height = 86,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, -5),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-single-shadow.png",
priority = "extra-high",
width = 50,
height = 32,
repeat_count = 2,
shift = util.by_pixel(10, 16),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-single-shadow.png",
priority = "extra-high",
width = 98,
height = 60,
repeat_count = 2,
shift = util.by_pixel(10, 17),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
straight_vertical =
{
layers =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-vertical.png",
priority = "extra-high",
width = 32,
height = 68,
variation_count = 5,
line_length = 5,
shift = util.by_pixel(0, 8),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-vertical.png",
priority = "extra-high",
width = 64,
height = 134,
variation_count = 5,
line_length = 5,
shift = util.by_pixel(0, 8),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-vertical-shadow.png",
priority = "extra-high",
width = 50,
height = 58,
repeat_count = 5,
shift = util.by_pixel(10, 28),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-vertical-shadow.png",
priority = "extra-high",
width = 98,
height = 110,
repeat_count = 5,
shift = util.by_pixel(10, 29),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
straight_horizontal =
{
layers =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-horizontal.png",
priority = "extra-high",
width = 32,
height = 50,
variation_count = 6,
line_length = 6,
shift = util.by_pixel(0, -4),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-horizontal.png",
priority = "extra-high",
width = 64,
height = 92,
variation_count = 6,
line_length = 6,
shift = util.by_pixel(0, -2),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-horizontal-shadow.png",
priority = "extra-high",
width = 62,
height = 36,
repeat_count = 6,
shift = util.by_pixel(14, 14),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-horizontal-shadow.png",
priority = "extra-high",
width = 124,
height = 68,
repeat_count = 6,
shift = util.by_pixel(14, 15),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
corner_right_down =
{
layers =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-corner-right.png",
priority = "extra-high",
width = 32,
height = 64,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, 6),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-corner-right.png",
priority = "extra-high",
width = 64,
height = 128,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, 7),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-corner-right-shadow.png",
priority = "extra-high",
width = 62,
height = 60,
repeat_count = 2,
shift = util.by_pixel(14, 28),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-corner-right-shadow.png",
priority = "extra-high",
width = 124,
height = 120,
repeat_count = 2,
shift = util.by_pixel(17, 28),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
corner_left_down =
{
layers =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-corner-left.png",
priority = "extra-high",
width = 32,
height = 68,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, 6),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-corner-left.png",
priority = "extra-high",
width = 64,
height = 134,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, 7),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-corner-left-shadow.png",
priority = "extra-high",
width = 54,
height = 60,
repeat_count = 2,
shift = util.by_pixel(8, 28),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-corner-left-shadow.png",
priority = "extra-high",
width = 102,
height = 120,
repeat_count = 2,
shift = util.by_pixel(9, 28),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
t_up =
{
layers =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-t.png",
priority = "extra-high",
width = 32,
height = 68,
variation_count = 4,
line_length = 4,
shift = util.by_pixel(0, 6),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-t.png",
priority = "extra-high",
width = 64,
height = 134,
variation_count = 4,
line_length = 4,
shift = util.by_pixel(0, 7),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-t-shadow.png",
priority = "extra-high",
width = 62,
height = 60,
repeat_count = 4,
shift = util.by_pixel(14, 28),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-t-shadow.png",
priority = "extra-high",
width = 124,
height = 120,
repeat_count = 4,
shift = util.by_pixel(14, 28),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
ending_right =
{
layers =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-ending-right.png",
priority = "extra-high",
width = 32,
height = 48,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, -4),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-ending-right.png",
priority = "extra-high",
width = 64,
height = 92,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, -3),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-ending-right-shadow.png",
priority = "extra-high",
width = 62,
height = 36,
repeat_count = 2,
shift = util.by_pixel(14, 14),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-ending-right-shadow.png",
priority = "extra-high",
width = 124,
height = 68,
repeat_count = 2,
shift = util.by_pixel(17, 15),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
ending_left =
{
layers =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-ending-left.png",
priority = "extra-high",
width = 32,
height = 48,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, -4),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-ending-left.png",
priority = "extra-high",
width = 64,
height = 92,
variation_count = 2,
line_length = 2,
shift = util.by_pixel(0, -3),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-ending-left-shadow.png",
priority = "extra-high",
width = 54,
height = 36,
repeat_count = 2,
shift = util.by_pixel(8, 14),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-ending-left-shadow.png",
priority = "extra-high",
width = 102,
height = 68,
repeat_count = 2,
shift = util.by_pixel(9, 15),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
filling =
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-filling.png",
priority = "extra-high",
width = 24,
height = 30,
variation_count = 8,
line_length = 8,
shift = util.by_pixel(0, -2),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-filling.png",
priority = "extra-high",
width = 48,
height = 56,
variation_count = 8,
line_length = 8,
shift = util.by_pixel(0, -1),
scale = 0.5
}
},
water_connection_patch =
{
sheets =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-patch.png",
priority = "extra-high",
width = 58,
height = 64,
shift = util.by_pixel(0, -2),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-patch.png",
priority = "extra-high",
width = 116,
height = 128,
shift = util.by_pixel(0, -2),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-patch-shadow.png",
priority = "extra-high",
width = 74,
height = 52,
shift = util.by_pixel(8, 14),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-patch-shadow.png",
priority = "extra-high",
width = 144,
height = 100,
shift = util.by_pixel(9, 15),
draw_as_shadow = true,
scale = 0.5
}
}
}
},
gate_connection_patch =
{
sheets =
{
{
filename = "__PCPRedux__/graphics/plastic-wall/wall-gate.png",
priority = "extra-high",
width = 42,
height = 56,
shift = util.by_pixel(0, -8),
hr_version =
{
filename = "__PCPRedux__/graphics/plastic-wall/hr-wall-gate.png",
priority = "extra-high",
width = 82,
height = 108,
shift = util.by_pixel(0, -7),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/wall/wall-gate-shadow.png",
priority = "extra-high",
width = 66,
height = 40,
shift = util.by_pixel(14, 18),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/wall/hr-wall-gate-shadow.png",
priority = "extra-high",
width = 130,
height = 78,
shift = util.by_pixel(14, 18),
draw_as_shadow = true,
scale = 0.5
}
}
}
}
}
end
empty_sprite =
{
filename = "__core__/graphics/empty.png",
priority = "extra-high",
width = 1,
height = 1,
frame_count = 1
}
-- Plastic Wall ****************************************************************************
--entity:
plaswallE = table.deepcopy(data.raw["wall"]["stone-wall"])
plaswallE.name="plaswall"
plaswallE.minable.result="plaswall"
plaswallE.max_health = 750
plaswallE.pictures =
{
single = plas_wall_images().single,
straight_horizontal = plas_wall_images().straight_horizontal,
straight_vertical = plas_wall_images().straight_vertical,
corner_right_down = plas_wall_images().corner_right_down,
corner_left_down = plas_wall_images().corner_left_down,
t_up = plas_wall_images().t_up,
ending_right = plas_wall_images().ending_right,
ending_left = plas_wall_images().ending_left,
filling = plas_wall_images().filling,
water_connection_patch = plas_wall_images().water_connection_patch,
gate_connection_patch = plas_wall_images().gate_connection_patch
}
data:extend({plaswallE})
plaswallI=table.deepcopy(data.raw.item["stone-wall"])
plaswallI.name="plaswall"
plaswallI.order="a[stone-wall]-b[plastic-wall]"
plaswallI.place_result="plaswall"
data:extend({plaswallI})
data:extend({{
type = "recipe",
name = "plaswall",
enabled = false,
ingredients = {{"plastic-bar", 3},{"stone-brick",2}},
result = "plaswall"
}})
local addTech = function (technology, recipe)
table.insert(data.raw.technology[technology].effects,{type = "unlock-recipe", recipe = recipe})
end
addTech("plastics", "plaswall")
|
--------------------------------------------------------------------------
-- This class is manages the hash table that stores the "environment"
-- variables that Lmod controls. Each instant of Var holds a single
-- environment variable, path, local variable, shell function or alias.
-- This class is at the core of Lmod. Lmod is all about controlling
-- the user environment and this is where Lmod does this.
--
-- The other point of this class is to check to see when MODULEPATH
-- has changed.
--
--------------------------------------------------------------------------
-- PATH Variables:
--------------------------------------------------------------------------
-- Storing PATH variables is complicated. Each time a path variable is
-- encountered, it is split apart into a hash table - array structure.
-- Assuming PATH="/u/bin:/u/l/bin:/u/bin" then self.tbl contains:
--
-- self.tbl["/u/bin"] = { 1, 3 }
-- self.tbl["/u/l/bin"] = { 2 }
--
-- Obviously the each key is the path. The values are a weight that
-- represents where it will appear when expanded back into a path-like
-- environment variable. If "/u/l/bin" is removed then there will be a
-- gap in the values. Each time a path is prepended it inserts a lower
-- value. Appending adds a higher value. So prepending "/a/b" and
-- appending "/d/e" results in:
--
-- self.tbl["/u/bin"] = { 1, 3 }
-- self.tbl["/u/l/bin"] = { 2 }
-- self.tbl["/a/b"] = { 0 }
-- self.tbl["/d/e"] = { 4 }
--
-- Originally Lmod removed duplicates. Even now MODULEPATH and
-- LMOD_DEFAULT_MODULEPATH remove duplicates. So depending what the
-- policy that was chosen at configure time, there may duplicates or
-- not. This is the reason for use of "remFunc" in Var:remove() and
-- "insertFunc" in Var:prepend() and Var:append().
--
--------------------------------------------------------------------------
-- PUSHENV: Supporting a stack environment variable.
--------------------------------------------------------------------------
-- A site may wish to set CC to be the name of the c compiler. They can
-- do this with pushenv("CC","gcc"). This is implemented in this class
-- via Var:prepend() to push and Var:pop() to pop the stack. So the trick
-- here is that all sites allow duplicates to be stored when prepending.
-- This way prepend will always work as a push even when append and remove
-- do not allow duplicates. Then the Var:pop() member function will work
-- correctly independent of site policy towards duplicates
--
-- @classmod Var
require("strict")
--------------------------------------------------------------------------
-- Lmod License
--------------------------------------------------------------------------
--
-- Lmod is licensed under the terms of the MIT license reproduced below.
-- This means that Lmod is free software and can be used for both academic
-- and commercial purposes at absolutely no cost.
--
-- ----------------------------------------------------------------------
--
-- Copyright (C) 2008-2014 Robert McLay
--
-- 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.
--
--------------------------------------------------------------------------
require("string_utils")
require("pairsByKeys")
require("utils")
_G._DEBUG = false -- Required by the new lua posix
local abs = math.abs
local ceil = math.ceil
local dbg = require("Dbg"):dbg()
local ModulePath = ModulePath
local concatTbl = table.concat
local getenv = os.getenv
local log = math.log
local min = math.min
local max = math.max
local huge = math.huge
local posix = require("posix")
local setenv_posix = posix.setenv
local systemG = _G
local envPrtyName = "__LMOD_PRIORITY_"
local ln10_inv = 1.0/log(10.0)
local M = {}
--------------------------------------------------------------------------
-- Rebuild the path-like priority table. So for a PATH with priorities
-- would have:
-- __LMOD_PRIORITY_PATH=/a/b/c:-100;/d/e/f:-1000
-- The entries are separated by semicolons and the key-value pairs
-- are separated by colons. The results are a table:
--
-- t['/a/b/c'] = -100
-- t['/d/e/f'] = -1000
--
-- @param self A Var object.
local function build_priorityT(self)
local value = getenv(envPrtyName .. self.name)
if (value == nil) then
return {}
end
local t = {}
local a = false
for outer in value:split(";") do
local istate = 0
for entry in outer:split(":") do
istate = istate + 1
if (istate == 1) then
t[entry] = {}
a = t[entry]
else
a[#a+1] = entry
end
end
end
return t
end
--------------------------------------------------------------------------
-- The ctor uses this routine to initialize the variable to be
-- the value from the environment. This routine assumes that
-- all variables are path like variables here. Not to worry
-- however, the set function mark the type as "var" and not
-- "path". Other functions work similarly.
local function extract(self)
local myValue = self.value or getenv(self.name)
local pathTbl = {}
local imax = 0
local imin = 1
local pathA = {}
local sep = self.sep
local priorityT = build_priorityT(self)
if (myValue and myValue ~= '') then
pathA = path2pathA(myValue, sep)
for i,v in ipairs(pathA) do
local a = pathTbl[v] or {}
local priority = 0
local vA = priorityT[v]
if (vA) then
priority = vA[1]
end
a[#a + 1] = {i,priority}
pathTbl[v] = a
imax = i
end
end
self.value = myValue
self.type = 'path'
self.tbl = pathTbl
self.imin = imin
self.imax = imax
self.export = true
end
--------------------------------------------------------------------------
-- The ctor for this class. It uses extract to build its
-- initial value from the environment.
-- @param self A Var object.
-- @param name The name of the variable.
-- @param value The value assigned to the variable.
-- @param sep The separator character. (By default it is ":")
function M.new(self, name, value, sep)
local o = {}
setmetatable(o,self)
self.__index = self
o.value = value
o.name = name
o.sep = sep or ":"
extract(o)
if (not value) then value = nil end
setenv_posix(name, value, true)
return o
end
--------------------------------------------------------------------------
-- This member function is here just when debugging.
-- @param self A Var object.
-- @param title A Descriptive title.
function M.prt(self,title)
dbg.start{"Var:prt(",title,")"}
dbg.print{"name: \"", self.name, "\"\n"}
dbg.print{"imin: ", self.imin, "\n"}
dbg.print{"imax: ", self.imax, "\n"}
local v = self.value
if (type(self.value) == "string") then
v = "\"" .. self.value .. "\""
end
dbg.print{"value: ", v, "\n"}
if (not self.tbl or type(self.tbl) ~= "table" or next(self.tbl) == nil) then
dbg.print{"tbl is empty\n"}
dbg.fini ("Var:prt")
return
end
for k,vA in pairsByKeys(self.tbl) do
dbg.print{" \"",k,"\":"}
for ii = 1,#vA do
io.stderr:write(" {",tostring(vA[ii][1]), ", ",tostring(vA[ii][2]),"} ")
end
dbg.print{"\n"}
end
dbg.print{"\n"}
dbg.fini ("Var:prt")
end
--------------------------------------------------------------------------
-- This function is called to let Lmod know that the MODULEPATH
-- has changed.
-- @param name The variable name
-- @param adding True if adding to path.
-- @param pathEntry The new value.
local function chkMP(name, adding, pathEntry)
if (name == ModulePath) then
dbg.print{"calling reEvalModulePath()\n"}
local mt = systemG.MT:mt()
mt:changePATH()
mt:reEvalModulePath(adding, pathEntry)
end
end
--------------------------------------------------------------------------
-- This handles removing entries from a path like variable.
-- @param a An array of values.
-- @param where Where to remove and how: {"first", "last", "all"}
-- @param priority The priority of the path if any (default is zero)
local function remFunc(a, where, priority, nodups)
if (where == "all" or abs(priority) > 0) then
local oldPriority = 0
if (next(a) ~= nil) then
oldPriority = tonumber(a[1][2])
end
if (oldPriority == priority or nodups) then
a = nil
end
elseif (where == "first" ) then
table.remove(a,1)
if (next(a) == nil) then
a = nil
end
elseif (where == "last" ) then
a[#a] = nil
if (next(a) == nil) then
a = nil
end
end
return a
end
--------------------------------------------------------------------------
-- Remove an entry in a path. The remove action depends on
-- "where". Note that the final action of this routine is
-- to push the new value into the current environment so that
-- any modules loaded will also know the new value.
-- @param self A Var object
-- @param value The value to remove
-- @param where where it should be removed from {"first", "last", "all"}
-- @param priority The priority of the entry.
-- @param nodup If true then there are no duplicates allowed.
function M.remove(self, value, where, priority, nodups)
dbg.start{"Var:remove(value: ",value,", where:",where,", priority: ",priority,")"}
if (value == nil) then return end
priority = priority or 0
if (where == "first") then
priority = - priority
end
if (dbg.active() and self.name == "MODULEPATH") then
self:prt()
end
where = allow_dups(true) and where or "all"
local pathA = path2pathA(value, self.sep)
local tbl = self.tbl
local adding = false
for i = 1, #pathA do
local path = pathA[i]
dbg.print{"path: ",path,"\n"}
if (tbl[path]) then
dbg.print{"removing path: ",path,"\n"}
tbl[path] = remFunc(self.tbl[path], where, priority, nodups)
chkMP(self.name,adding,path)
end
end
local v = self:expand()
dbg.print{"where: ",where,", new value: ",v,"\n"}
self.value = v
if (not v) then v = nil end
setenv_posix(self.name, v, true)
dbg.fini("Var:remove")
end
--------------------------------------------------------------------------
-- Remove the top value and return the second value or nil if
-- none are left.
-- @param self A Var object.
function M.pop(self)
self.type = 'path'
local imin = self.imin
local min2 = huge
local result = nil
if (dbg.active()) then
self:prt("(1) Var:pop()")
end
for k, idxA in pairs(self.tbl) do
local v = idxA[1][1]
dbg.print{"v: ",v,", imin: ",imin,", min2: ",min2,"\n"}
if (v == imin) then
idxA = remFunc(idxA, "first", 0)
self.tbl[k] = idxA
if (idxA ~= nil) then
v = idxA[1][1]
else
v = huge
end
end
dbg.print{"v: ",v,"\n"}
if (v < min2) then
min2 = v
result = k
end
dbg.print{"min2: ",min2,"\n"}
end
dbg.print{"imin: ",imin,", min2: ",min2,"\n"}
if (min2 < huge) then
self.imin = min2
end
local v = self:expand()
self.value = v
if (dbg.active()) then
self:prt("(2) Var:pop()")
end
if (not v) then v = nil end
setenv_posix(self.name, v, true)
return result
end
--------------------------------------------------------------------------
-- insert index into table with priority. If nodup or this
-- particular path entry has a priority then there is only
-- one entry in the path. Otherwise insert [[idx]] at
-- beginning for prepends and at the end for appends.
-- @param a Input array of entries in path like variable.
-- @param idx the index value for the entry.
-- @param isPrepend True if a prepend.
-- @param nodups True if no duplications are allowed.
-- @param priority The priority value.
local function insertFunc(a, idx, isPrepend, nodups, priority)
if (nodups or abs(priority) > 0) then
if (priority == 0) then
return { {idx,priority} }
end
local oldPriority = 0
if (next(a) ~= nil) then
oldPriority = tonumber(a[1][2])
end
if (priority < 0) then
if (priority <= oldPriority) then
return { {idx,priority} }
end
elseif (oldPriority > 0 and priority > oldPriority) then
return { {idx,priority} }
end
elseif (isPrepend) then
table.insert(a,1, {idx, priority})
else
a[#a+1] = {idx, priority}
end
return a
end
--------------------------------------------------------------------------
-- Prepend an entry into a path. [[nodups]] controls
-- policies on duplication by setting [[insertFunc]].
--
-- Report an error/warning when appending/prepending a path element
-- without the same priority
-- @param self A Var object
-- @param value The value to prepend
-- @param nodups True if no duplications are allowed.
-- @param priority The priority value.
function M.prepend(self, value, nodups, priority)
if (value == nil) then return end
if (self.type ~= 'path') then
extract(self)
end
self.type = 'path'
priority = priority or 0
local pathA = path2pathA(value, self.sep)
local is, ie, iskip = prepend_order(#pathA)
local isPrepend = true
local adding = true
local tbl = self.tbl
local imin = min(self.imin, 0)
for i = is, ie, iskip do
local path = pathA[i]
imin = imin - 1
local a = tbl[path]
if (LMOD_TMOD_PATH_RULE == "no" or not a) then
tbl[path] = insertFunc(a or {}, imin, isPrepend, nodups, priority)
chkMP(self.name, adding,path)
end
end
self.imin = imin
local v = self:expand()
self.value = v
if (not v) then v = nil end
setenv_posix(self.name, v, true)
end
--------------------------------------------------------------------------
-- Append an entry into a path. [[nodups]] controls
-- policies on duplication by setting [[insertFunc]].
-- @param self A Var object
-- @param value The value to prepend
-- @param nodups True if no duplications are allowed.
-- @param priority The priority value.
function M.append(self, value, nodups, priority)
if (value == nil) then return end
if (self.type ~= 'path') then
extract(self)
end
self.type = 'path'
nodups = not allow_dups(not nodups)
priority = tonumber(priority or "0")
local pathA = path2pathA(value, self.sep)
local isPrepend = false
local adding = true
local tbl = self.tbl
local imax = self.imax
for i = 1, #pathA do
local path = pathA[i]
imax = imax + 1
local a = tbl[path]
if (LMOD_TMOD_PATH_RULE == "no" or not a) then
tbl[path] = insertFunc(a or {}, imax, isPrepend, nodups, priority)
chkMP(self.name, adding,path)
end
end
self.imax = imax
local v = self:expand()
self.value = v
if (not v) then v = nil end
setenv_posix(self.name, v, true)
end
--------------------------------------------------------------------------
-- Set the environment variable to *value*
-- @param self A Var object
-- @param value the value to set.
function M.set(self,value)
if (not value) then value = false end
self.value = value
self.type = 'var'
if (not value) then value = nil end
setenv_posix(self.name, value, true)
end
--------------------------------------------------------------------------
-- Unset the environment variable.
-- @param self A Var object
function M.unset(self)
self.value = false
self.type = 'var'
setenv_posix(self.name, nil, true)
end
--------------------------------------------------------------------------
-- Set the local variable to *value*
-- @param self A Var object
-- @param value the value to set.
function M.setLocal(self,value)
if (not value) then value = false end
self.value = value
self.type = 'local_var'
end
--------------------------------------------------------------------------
-- Unset the local variable.
-- @param self A Var object
function M.unsetLocal(self,value)
self.value = false
self.type = 'local_var'
end
--------------------------------------------------------------------------
-- Set the alias.
-- @param self A Var object.
-- @param value the text of the alias.
function M.setAlias(self,value)
if (not value) then value = false end
self.value = value
self.type = 'alias'
end
--------------------------------------------------------------------------
-- unset the alias.
-- @param self A Var object.
function M.unsetAlias(self)
self.value = false
self.type = 'alias'
end
--------------------------------------------------------------------------
-- Set a shell function for Bash and C-shell
-- @param self A Var object.
-- @param bash_func A bash function string.
-- @param csh_func A C-shell function string.
function M.setShellFunction(self,bash_func,csh_func)
self.value = {bash_func,csh_func}
self.type = 'shell_function'
end
--------------------------------------------------------------------------
-- Unset a shell function for Bash and C-shell
-- @param self A Var object.
function M.unsetShellFunction(self)
self.value = false
self.type = 'shell_function'
end
--------------------------------------------------------------------------
-- Return the var type.
-- @param self A Var object.
function M.myType(self)
return self.type
end
--------------------------------------------------------------------------
-- Expand the value into a string. Obviously non-path
-- types are simply returned.
--
-- It is a two step process to expand the path variables.
-- First table (self.tbl) is flipped where now the indices
-- are the keys and the paths are the values. This creates
-- [[t]] with integer keys with possible gaps. Then second
-- loop uses pairByKeys to pick keys from lowest to highest.
-- @param self A Var object.
function M.expand(self)
if (self.type ~= 'path') then
return self.value, self.type, {}
end
local t = {}
local pathA = {}
local pathStr = false
local sep = self.sep
local prT = {}
local maxV = max(abs(self.imin), self.imax) + 1
local factor = 10^ceil(log(maxV)*ln10_inv+1)
local resultA = {}
local tbl = self.tbl
-- Step 1: Make a sparse array with path as values
for k, vA in pairs(tbl) do
for ii = 1,#vA do
local pair = vA[ii]
local value = pair[1]
local priority = pair[2]
local idx = value + factor*priority
t[idx] = k
if (abs(priority) > 0) then
prT[k] = priority
end
end
end
-- Step 2: Use pairByKeys to copy paths into pathA in correct order.
local n = 0
for _,v in pairsByKeys(t) do
n = n + 1
v = path_regularize(v)
if (v == ' ') then
v = ''
end
pathA[n] = v
end
-- Step 2.1: Remove extra trailing empty strings, keep only one.
local i = n
while (pathA[i] == "") do
i = i - 1
end
i = i + 2
for j = i, n do
pathA[j] = nil
end
n = #pathA
-- Step 3: convert pathA array into "sep" separated string.
-- Also Handle "" at end of "path"
if (n == 1 and pathA[1] == "") then
pathStr = sep .. sep
else
pathStr = concatTbl(pathA,sep)
if (pathA[#pathA] == "") then
pathStr = pathStr .. sep
end
end
-- Step 4: Remove leading and trailing ':' from PATH string
-- Note this cleanup is only for PATH and no other
-- path variables.
if (self.name == 'PATH') then
pathStr = pathStr:gsub('^:+','')
pathStr = pathStr:gsub(':+$','')
if (pathStr:find('::')) then
pathStr = pathStr:gsub('::+',":")
end
end
local priorityStrT = {}
local env_name = envPrtyName .. self.name
if (next(prT) == nil) then
if (getenv(env_name)) then
priorityStrT[env_name] = false
end
else
local sA = {}
for k,priority in pairsByKeys(prT) do
sA[#sA+1] = k .. ':' .. tostring(priority)
end
priorityStrT[env_name] = concatTbl(sA,';')
end
if (next(tbl) == nil) then pathStr = false end
return pathStr, "path", priorityStrT
end
return M
|
-- Condition
local equals = require "resty.taurus.condition.equals"
local contains = require "resty.taurus.condition.contains"
local startwith = require "resty.taurus.condition.startwith"
local endwith = require "resty.taurus.condition.endwith"
local range = require "resty.taurus.condition.range"
local has_fields = require "resty.taurus.condition.has_fields"
local in_array = require "resty.taurus.condition.in_array"
local count = require "resty.taurus.condition.count"
local type = type
local error = error
local pairs = pairs
local _M = { _VERSION = '0.0.1' }
function _M.equals(expr)
for key, value in pairs(expr) do
return equals.new(key, value)
end
error("syntax error: no action block for equals condition")
end
function _M.contains(expr)
for key, value in pairs(expr) do
return contains.new(key, value)
end
error("syntax error: no action block for contains condition")
end
function _M.startwith(expr)
for key, value in pairs(expr) do
return startwith.new(key, value)
end
error("syntax error: no action block for startwith condition")
end
function _M.endwith(expr)
for key, value in pairs(expr) do
return endwith.new(key, value)
end
error("syntax error: no action block for endwith condition")
end
function _M.range(expr)
for key, value in pairs(expr) do
if type(value) == "table" then
return range.new(key, value)
end
error("syntax error: bad action block for range condition")
end
error("syntax error: no action block for range condition")
end
function _M.in_array(expr)
for key, value in pairs(expr) do
return in_array.new(key, value)
end
error("syntax error: bad action block for in_array condition")
end
function _M.has_fields(expr)
if type(expr) == "table" then
return has_fields.new(expr)
end
error("syntax error: bad action block for has_fields condition")
end
function _M.count(expr)
for key, value in pairs(expr) do
if type(value) == "table" then
return count.new(key, value)
end
error("syntax error: bad action block for count condition")
end
error("syntax error: bad action block for count condition")
end
function _M.default(expr)
return {
execute = function(self, fact) return true end
}
end
return _M
|
local CropManager = {}
CropManager.__index = CropManager
local index = 1
local Crop = require "game.crops.Crop"
function CropManager:new(tilemap)
local ins = setmetatable({}, self)
ins._crops = {}
ins._tilemap = tilemap or {}
Signal.register('cropTick', function ()
ins:tick()
end)
Signal.register('save', function ()
ins:saveState()
end)
return ins
end
function CropManager:loadCrops ()
local crops = saveEngine:getDataStore("crops")
for k,v in ipairs(crops) do
self:createCrop(v.collumn, v.row, v)
end
end
function CropManager:createCrop (collumn, row, crop)
if self:_cropAt(collumn, row) == false then
local newCropX = collumn * self._tilemap:getTileWidth()
local newCropY = row * self._tilemap:getTileHeight()
local newCrop = Crop:new(crop.name, newCropX, newCropY, collumn, row, crop.growthTime, Assets.wheat, crop.harvestable, crop.blueprint)
saveEngine:saveItem("crops", newCrop:serialize())
table.insert(self._crops, newCrop)
end
end
function CropManager:harvest (collumn, row)
if self:_cropAt(collumn, row) == true then
local index = self:getCropAt(collumn, row)
local crop = self._crops[index]
if crop:getHarvestable() == true then
-- HARVEST
saveEngine:removeItem("crops", crop:getId())
barn:addItem(crop:getBlueprint())
print(crop:getBlueprint())
-- TODO Make more safe
table.remove(self._crops, index)
end
end
end
function CropManager:getCropAt (collumn, row)
local cropIndex = nil
for k,v in ipairs(self._crops) do
if v:getCollumn() == collumn and v:getRow() == row then
cropIndex = k
break
end
end
return cropIndex
end
function CropManager:_cropAt (collumn, row)
local isCrop = false
for k,v in ipairs(self._crops) do
if v:getCollumn() == collumn and v:getRow() == row then
isCrop = true
break
end
end
return isCrop
end
function CropManager:saveState()
-- Clear crops datastore and fill it up again
saveEngine:clearDataStore("crops")
for k,v in ipairs(self._crops) do
saveEngine:saveItem("crops", v:serialize())
end
end
function CropManager:update (dt)
for k,v in ipairs(self._crops) do
v:update(dt)
end
end
function CropManager:tick ()
for k,v in ipairs(self._crops) do
v:tick()
end
end
function CropManager:draw ()
for k,v in ipairs(self._crops) do
v:draw()
end
end
return CropManager
|
local g = vim.g
g.indentLine_char = '│'
g.indent_blankline_use_treesitter = true
g.indentLine_faster = 1
g.indentLine_fileTypeExclude = {'tex', 'markdown', 'txt', 'startify', 'packer'}
g.indent_blankline_show_first_indent_level = false
g.indent_blankline_show_trailing_blankline_indent = false
|
if (SERVER) then
AddCSLuaFile()
end
--Panzerfaust
sound.Add({
name="Weapon_Panzerfaust.Explode",
volume = 1.0,
sound = "weapons/panzerfaust/panzerfaust_detonate_01.wav",
level = 140, --how loud are booms?
channel = CHAN_STATIC
})
sound.Add({
name="Weapon_Panzerfaust.Single",
volume = 1.0,
sound = "weapons/panzerfaust/panzerfaust_fp.wav",
level = 140, --how loud are rockets?
channel = CHAN_STATIC
})
sound.Add({
name="Weapon_Panzerfaust.Pin",
volume = 0.7,
sound = "weapons/panzerfaust/handling/panzerfaust_pinout.wav",
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_Panzerfaust.Sight",
volume = 0.7,
sound = "weapons/panzerfaust/handling/Panzerfaust_sightup.wav",
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_Panzerfaust.Shoulder",
volume = 0.7,
sound = "weapons/panzerfaust/handling/panzerfaust_shoulder.wav",
channel = CHAN_ITEM
})
|
modifier_storegga_avalanche_thinker = class({})
--------------------------------------------------------------------------------
function modifier_storegga_avalanche_thinker:IsHidden()
return true
end
--------------------------------------------------------------------------------
function modifier_storegga_avalanche_thinker:IsPurgable()
return false
end
--------------------------------------------------------------------------------
function modifier_storegga_avalanche_thinker:OnCreated( kv )
if IsServer() then
self.interval = self:GetAbility():GetSpecialValueFor( "interval" )
self.slow_duration = self:GetAbility():GetSpecialValueFor( "slow_duration" )
self.damage = self:GetAbility():GetSpecialValueFor( "damage" )
self.radius = self:GetAbility():GetSpecialValueFor( "radius" )
self.movement = self:GetAbility():GetSpecialValueFor( "movement" )
self.Avalanches = {}
local enemies = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), self:GetParent():GetOrigin(), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_CLOSEST, false )
self.hAvalancheTarget = enemies[RandomInt(1, #enemies)]
self:OnIntervalThink()
self:StartIntervalThink( self.interval )
end
end
--------------------------------------------------------------------------------
function modifier_storegga_avalanche_thinker:OnIntervalThink()
if IsServer() then
if self:GetCaster():IsNull() then
self:Destroy()
return
end
local vNewAvalancheDir1 = RandomVector( 1 )
local vNewAvalancheDir2 = RandomVector( 1 )
if self.hAvalancheTarget ~= nil and self.hAvalancheTarget:IsAlive() then
vNewAvalancheDir2 = self.hAvalancheTarget:GetOrigin() - self:GetCaster():GetOrigin()
else
local enemies = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), self:GetParent():GetOrigin(), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_CLOSEST, false )
self.hAvalancheTarget = enemies[RandomInt(1, #enemies)]
if self.hAvalancheTarget ~= nil then
vNewAvalancheDir2 = self.hAvalancheTarget:GetOrigin() - self:GetCaster():GetOrigin()
end
end
EmitSoundOnLocationWithCaster( self:GetParent():GetOrigin(), "Ability.Avalanche", self:GetCaster() )
vNewAvalancheDir1 = vNewAvalancheDir1:Normalized()
vNewAvalancheDir2 = vNewAvalancheDir2:Normalized()
local vRadius = Vector( self.radius * .72, self.radius * .72, self.radius * .72 )
local nFXIndex1 = ParticleManager:CreateParticle( "particles/units/heroes/hero_tiny/tiny_avalanche.vpcf", PATTACH_CUSTOMORIGIN, nil )
ParticleManager:SetParticleControl( nFXIndex1, 0, self:GetParent():GetOrigin() )
ParticleManager:SetParticleControl( nFXIndex1, 1, vRadius )
ParticleManager:SetParticleControlForward( nFXIndex1, 0, vNewAvalancheDir1 )
self:AddParticle( nFXIndex1, false, false, -1, false, false )
local nFXIndex2 = ParticleManager:CreateParticle( "particles/units/heroes/hero_tiny/tiny_avalanche.vpcf", PATTACH_CUSTOMORIGIN, nil )
ParticleManager:SetParticleControl( nFXIndex2, 0, self:GetParent():GetOrigin() )
ParticleManager:SetParticleControl( nFXIndex2, 1, vRadius )
ParticleManager:SetParticleControlForward( nFXIndex2, 0, vNewAvalancheDir2 )
self:AddParticle( nFXIndex2, false, false, -1, false, false )
local Avalanche1 =
{
vCurPos = self:GetCaster():GetOrigin(),
vDir = vNewAvalancheDir1,
nFX = nFXIndex1,
}
local Avalanche2 =
{
vCurPos = self:GetCaster():GetOrigin(),
vDir = vNewAvalancheDir2,
nFX = nFXIndex2,
}
table.insert( self.Avalanches, Avalanche1 )
table.insert( self.Avalanches, Avalanche2 )
for _,ava in pairs ( self.Avalanches ) do
local vNewPos = ava.vCurPos + ava.vDir * self.movement
ava.vCurPos = vNewPos
ParticleManager:SetParticleControl( ava.nFX, 0, vNewPos )
local enemies = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), vNewPos, nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_CLOSEST, false )
for _,enemy in pairs( enemies ) do
if enemy ~= nil and enemy:IsInvulnerable() == false and enemy:IsMagicImmune() == false then
local damageInfo =
{
victim = enemy,
attacker = self:GetCaster(),
damage = self.damage,
damage_type = DAMAGE_TYPE_MAGICAL,
ability = self:GetAbility(),
}
ApplyDamage( damageInfo )
enemy:AddNewModifier( self:GetCaster(), self:GetAbility(), "modifier_polar_furbolg_ursa_warrior_thunder_clap", { duration = self.slow_duration } )
end
end
end
end
end
|
-- type = github -- DO NOT REMOVE THIS LINE!
local name = "uplift"
local version = "2.6.4"
local org = "gembaadvantage"
local repo = "uplift"
local base_url = "https://github.com/" .. org .. "/" .. repo
food = {
name = name,
description = "Semantic versioning the easy way. Powered by Conventional Commits. Built for use with CI",
license = "MIT",
homepage = "https://github.com/gembaadvantage/uplift",
version = version,
packages = {
{
os = "darwin",
arch = "amd64",
url = base_url .. "/releases/download/v" .. version .. "/" .. name .. "_" .. version .. "_darwin-x86_64.tar.gz",
sha256 = "3ff52bc894baadb2b7ea5935e28dfbd5e7f55a8c72c940871117c41120b1c0df",
resources = {
{
path = name,
installpath = "bin/" .. name,
executable = true
}
}
},
{
os = "darwin",
arch = "arm64",
url = base_url .. "/releases/download/v" .. version .. "/" .. name .. "_" .. version .. "_darwin-arm64.tar.gz",
sha256 = "80ff2006f6a3f8d950f11fd3eafd4c7ea776a2d65db814979bb7e05825f47875",
resources = {
{
path = name,
installpath = "bin/" .. name,
executable = true
}
}
},
{
os = "linux",
arch = "amd64",
url = base_url .. "/releases/download/v" .. version .. "/" .. name .. "_" .. version .. "_linux-x86_64.tar.gz",
sha256 = "d19a39eb00cf61960df1c98a395c3b90d8210e6b284f0b544807ed4eefb5767f",
resources = {
{
path = name,
installpath = "bin/" .. name,
executable = true
}
}
},
{
os = "windows",
arch = "amd64",
url = base_url .. "/releases/download/v" .. version .. "/" .. name .. "_" .. version .. "_windows-x86_64.zip",
sha256 = "cb99ad24efdca42c8a34bcf889f58bb308ae2ed2ee361ad08a9c6b3eb48a8ffe",
resources = {
{
path = name .. ".exe",
installpath = "bin\\" .. name .. ".exe"
}
}
}
}
}
|
local API_NPC = require(script:GetCustomProperty("API_NPC"))
local API_DS = require(script:GetCustomProperty("APIDifficultySystem"))
local API_D = require(script:GetCustomProperty("APIDamage"))
local API_RE = require(script:GetCustomProperty("APIReliableEvents"))
local RANGE = 0.0
local COOLDOWN = 18.0
local MAX_START_OFFSET = 1000.0
local FIRE_PATCH_RADIUS = 300.0
local FIRE_PATCH_JUMP_RANGE = 300.0
local FIRE_PATCH_DAMAGE_RATE = 35.0
local FIRE_PATCH_DURATION = 10.0
local FIRE_PATCH_JUMP_PERIOD = 3.0
function GetPriority(npc, taskHistory)
if API_DS.GetDifficultyLevel() > 2 then
return 1.0
else
return 0.0
end
end
function OnTaskStart(npc, threatTable)
return 1.5
end
function OnTaskEnd(npc, interrupted)
if not interrupted then
local stream = RandomStream.New()
local anchorPosition = npc:GetWorldPosition()
API_RE.BroadcastToAllPlayers("CF", npc, anchorPosition, stream:GetInitialSeed())
function GetRandomGroundedPointInCircle(center, radius)
for i = 1, 5 do
local t = 2 * math.pi * stream:GetNumber()
local u = stream:GetNumber() + stream:GetNumber()
local r = radius * (1.0 - math.abs(u - 1.0))
local p = center + r * Vector3.New(math.cos(t), math.sin(t), 0.0)
local rayStart = p + Vector3.UP * 300.0
local rayEnd = p - Vector3.UP * 300.0
local hitResult = World.Raycast(rayStart, rayEnd, {ignorePlayers = true})
if hitResult then
return hitResult:GetImpactPosition()
end
end
end
local firePosition = GetRandomGroundedPointInCircle(anchorPosition, MAX_START_OFFSET)
Task.Spawn(function()
while not API_NPC.IsDead(npc) and API_NPC.GetTarget(npc) and firePosition do
Task.Spawn(function()
local position = firePosition
firePosition = GetRandomGroundedPointInCircle(firePosition, FIRE_PATCH_JUMP_RANGE)
for i = 1, FIRE_PATCH_DURATION do
Task.Wait(1.0)
for _, player in pairs(Game.FindPlayersInSphere(position, FIRE_PATCH_RADIUS, {ignoreDead = true})) do
API_D.ApplyDamage(npc, player, FIRE_PATCH_DAMAGE_RATE, API_D.TAG_PERIODIC | API_D.TAG_AOE)
end
end
end)
Task.Wait(FIRE_PATCH_JUMP_PERIOD)
end
end)
end
end
API_NPC.RegisterTaskServer("goblinking_creepingfire", RANGE, COOLDOWN, GetPriority, OnTaskStart, OnTaskEnd)
|
require 'lfs'
-- Ensure the test is launched within the specs/ folder
assert(string.match(lfs.currentdir(), "specs")~=nil, "You must run this test in specs folder")
local initial_dir = lfs.currentdir()
-- Go to specs folder
while (not string.match(lfs.currentdir(), "/specs$")) do
lfs.chdir("..")
end
local specs_dir = lfs.currentdir()
lfs.chdir("..")-- one more directory and it is lib root
-- Include Dataframe lib
dofile("init.lua")
-- Go back into initial dir
lfs.chdir(initial_dir)
describe("Categorical column", function()
local a = Dataframe()
a:load_csv{path = specs_dir.."/data/advanced_short.csv", verbose = false}
it("Should not be a numerical column",function()
assert.is_true(not a:is_numerical('Col B'), "Column should not be a numerical")
end)
it("Should be convertible to an integer column",function()
a:as_categorical('Col B')
assert.are.same(a:get_cat_keys('Col B'), {A=1, B=2})
assert.is_true(a:is_categorical('Col B'))
assert.is_true(a:is_numerical('Col B'))
end)
it("Should be convertible to an int linspace if it's a numerical column",function()
a:as_categorical('Col C')
assert.are.same(a:get_cat_keys('Col C'), {[8] = 1, [9] = 2})
assert.is_true(a:is_categorical('Col C'))
assert.is_true(not a:is_categorical('Col A'))
end)
it("Check that reversion works",function()
a:as_string('Col C')
assert.is_false(a:is_categorical('Col C'))
assert.are.same(a:get_column('Col C')[1], 8)
assert.is.nan(a:get_column{column_name='Col C'}[2])
assert.are.same(a:get_column{column_name='Col C'}[3], 9)
end)
describe("Conversion",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
it("Should handle integers and nan #1 input",function()
assert.is.equal(a:to_categorical{data=1, column_name='Col B'}, 'A')
assert.is.equal(a:to_categorical(2, 'Col B'), 'B')
assert.is.nan(a:to_categorical(0/0, 'Col B'))
end)
it("Should handle table input",function()
assert.are.same(a:to_categorical(Df_Array(2, 1), 'Col B'), {'B', 'A'})
end)
it("Should handle tensor input",function()
assert.are.same(a:to_categorical(torch.Tensor({1,2}), 'Col B'), {'A', 'B'})
end)
it("Should return nil if a request is outside range",function()
assert.are.same(a:to_categorical(3, 'Col B'), nil)
end)
it("Should fails at converting a non-categorical value",function()
assert.has.error(function() a:to_categorical(1, 'Col A') end)
end)
end)
describe("Reverse process",function()
it("Should handle a string as input",function()
assert.are.same(a:from_categorical('A', 'Col B'), 1)
assert.are.same(a:from_categorical('B', 'Col B'), 2)
end)
it("Should handle a table as input",function()
assert.are.same(a:from_categorical(Df_Array('A', 'B'), 'Col B'), {1, 2})
end)
it("Should handle a tensor as input",function()
assert.is.equal(a:from_categorical{data = Df_Array('A', 'B'), column_name = 'Col B', as_tensor = true}[1], torch.Tensor({1, 2})[1])
assert.is.equal(a:from_categorical{data = Df_Array('A', 'B'), column_name = 'Col B', as_tensor = true}[2], torch.Tensor({1, 2})[2])
-- tester:eq(a:from_categorical{data = {'A', 'B'}, column_name = 'Col B', as_tensor = true}, torch.Tensor({1, 2}))
end)
it("Should handle nan values",function()
assert.is.nan(a:from_categorical('C', 'Col B'))
end)
it("Should fails on non-categorical column",function()
assert.has.error(function() a:from_categorical('A', 'Col A') end)
end)
end)
it("Get #11 column",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
assert.are.same(a:get_column('Col B'), {'A', 'B', 'B'})-- "Failed to retrieve categorical representations"
assert.are.same(a:get_column('Col B', true), {1,2,2})-- "Failed to retrieve raw representations"
assert.are.same(a:get_column{column_name = 'Col B', as_raw = true}, {1, 2, 2})-- "Failed to return numbers instead of strings for categorical column"
true_vals = {"TRUE", "FALSE", "TRUE"}
a:load_table{data=Df_Dict{
['Col A']=true_vals,
['Col B']={10,11,12}
}}
a:as_categorical('Col A')
assert.are.same(a:get_column('Col A'), {"true", "false", "true"})
end)
it("Returns unique values",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
assert.are.same(a:unique('Col B'), {'A', 'B'})-- "Failed to get categorical data"
assert.are.same(a:unique{column_name = 'Col B', as_raw = true}, {1, 2})-- "Failed to get raw data"
assert.are.same(a:unique{column_name ='Col B', as_keys = true}, {['A'] = 1, ['B'] = 2})-- "Failed to get data as keys"
assert.are.same(a:unique{column_name ='Col B', as_keys = true, as_raw = true}, {[1] = 1, [2] = 2})-- "Failed to get raw data as keys"
end)
it("Order the categories", function()
local b = Dataframe(Df_Dict{a={"b", "a", "c"}})
b:as_categorical('a')
assert.are.same(b:from_categorical(Df_Array("a", "b", "c"), 'a'),
{1,2,3})
end)
it("Specify levels in a different order than sorted", function()
local b = Dataframe(Df_Dict{a={"b", "a", "c"}})
b:as_categorical{column_name = 'a',
levels = Df_Array("a", "c", "b")}
assert.are.same(b:from_categorical(Df_Array("a", "b", "c"), 'a'),
{1,3,2})
b:as_string('a')
b:as_categorical('a', Df_Array("b", "a", "c"))
assert.are.same(b:from_categorical(Df_Array("a", "b", "c"), 'a'),
{2,1,3})
end)
it("Specify fewer levels than present", function()
local b = Dataframe(Df_Dict{a={"b", "a", "c"}})
b:as_categorical('a', Df_Array("a", "b"))
assert.are.same(b:get_column('a', true)[1], 2)
assert.are.same(b:get_column('a', true)[2], 1)
assert.is.nan(b:get_column('a', true)[3])
end)
it("Specify labels", function()
local b = Dataframe(Df_Dict{a={"b", "a", "c"}})
b:as_categorical('a', Df_Array("a", "b"), Df_Array("A", "B"))
assert.are.same(b:get_column('a')[1], "B")
assert.are.same(b:get_column('a')[2], "A")
assert.is.nan(b:get_column('a', true)[3])
end)
it("Specify levels in a different order than sorted", function()
local b = Dataframe(Df_Dict{a={"b", "a", "c"}})
b:as_categorical{column_name = 'a',
exclude=Df_Array("a","B")}
assert.are.same(b:get_column('a')[1], "b")
assert.are.same(b:get_column('a')[3], "c")
assert.is.nan(b:get_column('a', true)[2])
assert.are.same(b:from_categorical(Df_Array("b", "c"), 'a'),
{1,2})
end)
it("Insert new columns",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
local new_data = {
["Col A"] = 1,
["Col B"] = "C",
["Col C"] = 10
}
a:append(Df_Dict(new_data))
assert.are.same(a:get_cat_keys('Col B'), {A=1, B=2, C=3})
end)
it("Updates rows according to custom function #1",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
a:update(
function(row) return row['Col A'] == 3 end,
function(row) row['Col B'] = 'C' return row end
)
if false then
assert.are.same(a:get_column('Col B'), {'A', 'B', 'C'})-- "Should be A,B,C"
assert.are.same(a:get_cat_keys('Col B'), {A=1, B=2, C=3})-- "Expected 3 keys after changing the last key"
a:load_csv{path = specs_dir.."/data/advanced_short.csv"}
a:as_categorical('Col B')
a:update(
function(row) return row['Col B'] == 'B' end,
function(row) row['Col B'] = 'A' return row end
)
assert.are.same(a:get_column('Col B'), {'A', 'A', 'A'})-- "All should be A's"
assert.are.same(a:get_cat_keys('Col B'), {A=1, B=2})-- "Keys should not be removed without prompting"
a:clean_categorical('Col B')
assert.are.same(a:get_cat_keys('Col B'), {A=1})-- "Keys should be removed after calling clean_categorical"
a:load_csv{path = specs_dir.."/data/advanced_short.csv"}
a:as_categorical('Col B')
a:update(
function(row) return row['Col B'] == 'B' end,
function(row) row['Col B'] = 'A' return row end
)
a:clean_categorical('Col B', true)
assert.are.same(a:get_cat_keys('Col B'), {A=1})-- "Keys should be removed after calling clean_categorical with resetting"
a:load_csv{path = specs_dir.."/data/advanced_short.csv"}
a:as_categorical('Col B')
a:as_categorical('Col C')
a:update(
function(row) return row['Col A'] == 3 end,
function(row) row['Col B'] = 0/0 return row end
)
assert.is.nan(a:get_column('Col B')[3])-- "The nan should be saved as such"
assert.is.nan(a:get_column('Col C')[2])-- "The nan should be untouched"
end
end)
it("Set a new value given a column name #1", function()
local a = Dataframe()
a:load_csv{path = specs_dir.."/data/advanced_short.csv"}
a:as_categorical('Col B')
a:set('A', 'Col B', Df_Dict({['Col B'] = 'C'}))
assert.are.same(a:get_cat_keys('Col B'), {A=1, B=2, C=3})
a:set('C', 'Col B', Df_Dict({['Col B'] = 'B'}))
assert.are.same(a:get_cat_keys('Col B'), {A=1, B=2, C=3})
a:clean_categorical('Col B')
assert.are.same(a:get_cat_keys('Col B'), {B=2})
a:clean_categorical('Col B', true)
assert.are.same(a:get_cat_keys('Col B'), {B=1})
end)
it("Loads from a CSV or a table",function()
local a = Dataframe()
a:load_csv{path = specs_dir.."/data/advanced_short.csv"}
a:as_categorical('Col B')
a:load_csv{path = specs_dir.."/data/advanced_short.csv"}
assert.is_true(not a:is_categorical('Col B'))
a:as_categorical('Col B')
assert.is_true(a:is_categorical('Col B'))
a:load_table{data=Df_Dict({['Col A']="3",['Col B']={10,11,12}})}
assert.is_true(not a:is_categorical('Col B'))
a:as_categorical('Col A')
assert.is_true(a:is_categorical('Col A'))
end)
it("Renames column name",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
assert.has.error(function() a:as_categorical(1) end)
assert.is_true(a:is_categorical('Col B'))
a:rename_column('Col B', 'Alt col B')
assert.has.error(function() a:is_categorical('Col B') end)
assert.is_true(a:is_categorical('Alt col B'))
end)
it("Finds rows in column with specific values #1", function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
local ret_val = a:where('Col B', 'A')
assert.are.same(ret_val:shape(), {rows = 1, cols = 3})
assert.are.same(ret_val:from_categorical(Df_Array('A', 'B'), 'Col B'),
{1, 2})-- "The categorical values shouldn't change due to subsetting"
ret_val = a:where('Col B', 'B')
assert.are.same(ret_val:shape(), {rows = 2, cols = 3})
local new_data = {
["Col A"] = 1,
["Col B"] = "C",
["Col C"] = 10
}
ret_val:append(Df_Dict(new_data))
assert.are.same(ret_val:from_categorical(Df_Array('A', 'B', 'C'), 'Col B'),
{1, 2, 3})-- "The categorical should add the new value as the last number"
ret_val = a:where('Col B', 'A')
assert.are.same(ret_val:shape(), {rows = 1, cols = 3})
end)
it("Creates a subset", function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
local ret_val = a:sub(1,2)
assert.are.same(ret_val:shape(), {rows = 2, cols = 3})
a:add_column("Col D", Dataseries(Df_Array({0/0, "B", "C"})))
ret_val = a:sub(1,2)
assert.is.nan(ret_val:get_column('Col D')[1])-- "Should retain nan value"
assert.is.equal(ret_val:get_column('Col D')[2], 'B')-- "Should retain string value"
end)
it("Counts values #1 frequencies", function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:as_categorical('Col B')
local ret = a:value_counts('Col B')
assert.is.equal(ret:where('values', 'B'):get_column('count')[1], 2)
assert.is.equal(ret:where('values', 'A'):get_column('count')[1], 1)
local ret = a:value_counts('Col A')
assert.are.same_elements(ret:get_column('count'), {1,1,1})
assert.are.same_elements(ret:get_column('values'), {1,2,3})
local ret = a:value_counts('Col C')
assert.are.same(ret:get_column('count'), {1,1})
local tmp = ret:get_column('values')
assert.are.same(tmp, {8,9})
a:as_categorical('Col C')
local ret = a:value_counts('Col C')
assert.are.same(ret:get_column('count'), {1,1})
local tmp = ret:get_column('values')
assert.are.same(tmp, {8,9})
end)
it("Exports to tensor",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:fill_all_na(0)
tnsr = a:to_tensor()
assert.is.equal(tnsr:size(1),
a:shape()["rows"])-- "Incorrect number of rows, expecting " .. a:shape()["rows"] .. " but got " ..tnsr:size(1)
assert.is.equal(tnsr:size(2),
a:shape()["cols"] - 1)-- "Incorrect number of columns, expecting " .. a:shape()["cols"] - 1 .. " but got " .. tnsr:size(2)
sum = 0
col_no = a:get_column_order('Col A')
for i=1,tnsr:size(1) do
sum = math.abs(tnsr[i][col_no] - a:get_column('Col A')[i])
end
assert.is_true(sum < 1e-5)-- "The difference between the columns should be < 10^-5, it is currently " .. sum
a:as_categorical('Col B')
tnsr = a:to_tensor()
assert.is.equal(tnsr:size(1),
a:shape()["rows"])-- "Incorrect number of rows, expecting " .. a:shape()["rows"] .. " but got " ..tnsr:size(1)
assert.is.equal(tnsr:size(2),
a:shape()["cols"])-- "Incorrect number of columns, expecting " .. a:shape()["cols"] - 1 .. " but got " .. tnsr:size(2)
sum = 0
col_no = a:get_column_order('Col A')
for i=1,tnsr:size(1) do
sum = math.abs(tnsr[i][col_no] - a:get_column('Col A')[i])
end
assert.is_true(sum < 1e-5)-- "The difference between the columns should be < 10^-5, it is currently " .. sum
end)
end)
|
require("stategraphs/commonstates")
local actionhandlers =
{
-- ActionHandler(ACTIONS.GOHOME, "action"),
-- ActionHandler(ACTIONS.EAT, "eat"),
}
local events=
{
CommonHandlers.OnLocomote(false, true),
CommonHandlers.OnFreeze(),
CommonHandlers.OnAttacked(),
CommonHandlers.OnDeath(),
CommonHandlers.OnSleep(),
CommonHandlers.OnAttack(),
}
local states =
{
State{
name = "idle",
tags = {"idle", "canrotate"},
onenter = function(inst, playanim)
inst.Light:Enable(true)
inst.Physics:Stop()
if playanim then
inst.AnimState:PlayAnimation(playanim)
inst.AnimState:PushAnimation("idle_loop", true)
else
inst.AnimState:PlayAnimation("idle_loop", true)
end
end,
events=
{
EventHandler("animover", function(inst)
if math.random() < 0.15 then
inst.sg:GoToState("rumble")
else
inst.sg:GoToState("idle")
end
end),
},
},
State{
name = "rumble",
onenter = function(inst, playanim)
inst.Physics:Stop()
inst.AnimState:PlayAnimation("idle_rumble")
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/rumble")
end,
events=
{
EventHandler("animover", function (inst)
inst.sg:GoToState("idle")
end),
}
},
State{
name = "taunt",
tags = {"busy"},
onenter = function(inst)
inst.Physics:Stop()
inst.AnimState:PlayAnimation("taunt")
end,
timeline =
{
TimeEvent(5*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/taunt") end),
TimeEvent(17*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/taunt") end),
TimeEvent(25*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/taunt") end),
},
events=
{
EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
},
},
State{
name = "burp",
tags = {"busy"},
onenter = function(inst)
inst.shouldburp = false
inst.Physics:Stop()
inst.AnimState:PlayAnimation("burp")
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/burp")
end,
events=
{
EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
},
},
State{
name = "headslurp",
tags = {"attack", "busy", "jumping"},
onenter = function(inst, target)
inst.AnimState:PlayAnimation("headslurp")
end,
timeline =
{
TimeEvent(8*FRAMES, function(inst)
inst.Physics:SetMotorVelOverride(8,0,0)
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/jump")
end),
TimeEvent(23*FRAMES, function(inst)
inst.Physics:ClearMotorVelOverride()
inst.components.locomotor:Stop()
end),
TimeEvent(24*FRAMES, function(inst)
local target = inst.components.combat.target
if inst and target then
if inst:GetDistanceSqToInst(target) < 2*2 then
local oldhat = target.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
if oldhat then
target.components.inventory:DropItem(oldhat)
end
target.components.inventory:Equip(inst)
end
end
end),
},
events =
{
--Check attachment eligibility. Either go into hat mode or miss mode.
EventHandler("animover", function(inst)
inst.sg:GoToState("headslurpmiss")
end),
},
},
State{
name = "headslurpmiss",
tags = {"attack", "busy"},
onenter = function(inst, target)
inst.AnimState:PlayAnimation("headslurpmiss")
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/miss")
end,
events =
{
--Go to taunt
EventHandler("animover", function(inst)
--inst.shouldburp gets set in "onequip". This means he's been "feeding" so he should burp.
if not inst.shouldburp then
inst.sg:GoToState("taunt")
else
inst.sg:GoToState("burp")
end
end),
},
},
State{
name = "attack",
tags = {"attack", "busy", "jumping"},
onenter = function(inst, target)
inst.components.locomotor:Stop()
inst.components.locomotor:EnableGroundSpeedMultiplier(false)
inst.components.combat:StartAttack()
inst.AnimState:PlayAnimation("atk")
inst.sg.statemem.target = target
end,
onexit = function(inst)
inst.components.locomotor:Stop()
inst.components.locomotor:EnableGroundSpeedMultiplier(true)
end,
timeline = {
TimeEvent(20*FRAMES, function(inst)
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/roll_VO", "roll_VO")
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/roll_dirt", "roll_dirt")
inst.Physics:SetMotorVelOverride(20,0,0)
end),
TimeEvent(30*FRAMES, function(inst)
local target = inst.components.combat.target
if inst and target then
if inst:GetDistanceSqToInst(target) < 2*2 then
inst.components.combat:DoAttack(target)
end
if inst.HatTest and inst.HatTest(inst, target) then
inst.sg:GoToState("headslurp")
end
end
inst.SoundEmitter:KillSound("roll_VO")
inst.SoundEmitter:KillSound("roll_dirt")
inst.Physics:ClearMotorVelOverride()
inst.components.locomotor:Stop()
end),
},
events=
{
EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
},
},
State{
name = "hit",
tags = {"hit", "busy"},
onenter = function(inst, cb)
if inst.components.locomotor then
inst.components.locomotor:StopMoving()
end
inst.AnimState:PlayAnimation("hit")
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/hurt")
end,
events =
{
EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
},
},
State{
name = "death",
tags = {"busy"},
onenter = function(inst)
inst.AnimState:PlayAnimation("death")
if inst.components.locomotor then
inst.components.locomotor:StopMoving()
end
inst.Physics:ClearCollisionMask()
end,
timeline =
{
TimeEvent(12*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/die") end),
TimeEvent(60*FRAMES,function(inst)
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/pop")
inst.components.lootdropper:DropLoot(Vector3(inst.Transform:GetWorldPosition()))
end),
},
},
State{
name = "walk_start",
tags = {"moving", "canrotate"},
onenter = function(inst)
inst.AnimState:PlayAnimation("roll_pre")
end,
timeline =
{
TimeEvent(7*FRAMES, function(inst) inst.components.locomotor:WalkForward() end),
},
events =
{
EventHandler("animover", function(inst) inst.sg:GoToState("walk") end ),
},
},
State{
name = "walk",
tags = {"moving", "canrotate"},
onenter = function(inst)
inst.components.locomotor:WalkForward()
inst.AnimState:PlayAnimation("roll_loop", true)
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/roll_VO", "roll_VO")
inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/roll_dirt", "roll_dirt")
end,
onexit = function(inst)
inst.SoundEmitter:KillSound("roll_VO")
inst.SoundEmitter:KillSound("roll_dirt")
end,
events=
{
--EventHandler("animover", function(inst) inst.sg:GoToState("walk") end ),
},
},
State{
name = "walk_stop",
tags = {"canrotate"},
onenter = function(inst)
inst.AnimState:PlayAnimation("roll_pst")
inst.components.locomotor:StopMoving()
end,
events=
{
EventHandler("animover", function(inst)
inst.sg:GoToState("idle") end ),
},
},
}
CommonStates.AddSleepStates(states,
{
starttimeline =
{
TimeEvent(7*FRAMES, function(inst) inst.Light:Enable(false) end),
},
sleeptimeline =
{
TimeEvent(0*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/slurper/sleep") end),
},
endtimeline =
{
TimeEvent(5*FRAMES, function(inst) inst.Light:Enable(true) end),
},
})
CommonStates.AddFrozenStates(states)
return StateGraph("slurper", states, events, "idle", actionhandlers)
|
ASTEROID_SIZE = 100 -- here since we will use it in multiple files, but can also be an asteroid attribute
show_debugging = false
function calculateDistance(x1, y1, x2, y2)
return math.sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2))
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.