content
stringlengths
5
1.05M
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('XTemplate', { __is_kind_of = "XPropControl", group = "PreGame", id = "PropTrait", PlaceObj('XTemplateWindow', { '__class', "XPropControl", 'RolloverOnFocus', true, 'MouseCursor', "UI/Cursors/Rollover.tga", 'FXMouseIn', "MenuItemHover", 'FXPress', "NewMissionParamsClick", }, { PlaceObj('XTemplateTemplate', { '__template', "PropArrow", 'Id', "idArrow", }), PlaceObj('XTemplateTemplate', { '__template', "PropName", 'VAlign', "center", }), PlaceObj('XTemplateTemplate', { '__template', "PropCheckBoxValue", 'Id', "idNegative", 'HandleMouse', true, 'Image', "UI/Icons/traits_disapprove_disable.tga", }, { PlaceObj('XTemplateFunc', { 'name', "OnMouseButtonDown(self, pos, button)", 'func', function (self, pos, button) if button == "L" and not self.parent.prop_meta.submenu then self:Press() return "break" end end, }), PlaceObj('XTemplateFunc', { 'name', "Press", 'func', function (self, ...) local obj = ResolvePropObj(self.parent.context) local dlg = GetDialog(self) local prop_meta = self.parent.prop_meta obj:FilterTrait(prop_meta, false) end, }), }), PlaceObj('XTemplateTemplate', { '__template', "PropCheckBoxValue", 'RolloverAnchor', "left", 'Id', "idPositive", 'Margins', box(0, 0, 5, 0), 'HandleMouse', true, 'Image', "UI/Icons/traits_approve_disable.tga", }, { PlaceObj('XTemplateFunc', { 'name', "OnMouseButtonDown(self, pos, button)", 'func', function (self, pos, button) if button == "L" and not self.parent.prop_meta.submenu then self:Press() return "break" end end, }), PlaceObj('XTemplateFunc', { 'name', "Press", 'func', function (self, ...) local obj = ResolvePropObj(self.parent.context) local dlg = GetDialog(self) local prop_meta = self.parent.prop_meta obj:FilterTrait(prop_meta, true) end, }), }), PlaceObj('XTemplateFunc', { 'name', "OnPropUpdate(self, context, prop_meta, value)", 'func', function (self, context, prop_meta, value) self.idArrow:SetVisible(prop_meta.submenu) local obj = ResolvePropObj(context) if prop_meta.add_count_in_name then local name = obj:GetPropTraitDisplayName(prop_meta) self.idName:SetText(name) end obj:UpdateImages(self, prop_meta) end, }), PlaceObj('XTemplateFunc', { 'name', "OnMouseButtonDown(self, pos, button)", 'func', function (self, pos, button) local obj = ResolvePropObj(self.context) if self.prop_meta.submenu or obj.dome then XPropControl.OnMouseButtonDown(self, pos, button) if button == "L" and self.prop_meta.submenu then obj:CountApprovedColonistsForCategory(self.prop_meta.id) SetDialogMode(self, "items", self.prop_meta) return "break" end end end, }), PlaceObj('XTemplateFunc', { 'name', "OnMouseButtonDoubleClick(self, pos, button)", 'func', function (self, pos, button) local obj = ResolvePropObj(self.context) if obj.dome and button == "L" then XPropControl.OnMouseButtonDoubleClick(self, pos, button) CloseDialog("DomeTraits") CreateRealTimeThread(function() OpenCommandCenter({dome = obj.dome, trait = {name = self.prop_meta.value, display_name = self.prop_meta.name}}, "Colonists") end) return "break" end end, }), PlaceObj('XTemplateFunc', { 'name', "OnShortcut(self, shortcut, source)", 'func', function (self, shortcut, source) if self.prop_meta.submenu and (shortcut == "DPadLeft" or shortcut == "LeftThumbLeft" or shortcut == "DPadRight" or shortcut == "LeftThumbRight") then return self:OnMouseButtonDown(nil, "L") elseif not self.prop_meta.submenu and shortcut == "ButtonX" then return self:OnMouseButtonDoubleClick(nil, "L") elseif shortcut == "DPadLeft" or shortcut == "LeftThumbLeft" then self.idPositive:Press() return "break" elseif shortcut == "DPadRight" or shortcut == "LeftThumbRight" then self.idNegative:Press() return "break" end end, }), PlaceObj('XTemplateFunc', { 'name', "OnSetRollover(self, rollover)", 'func', function (self, rollover) XPropControl.OnSetRollover(self, rollover) local arrow = self:ResolveId("idArrow") if arrow then arrow:OnSetRollover(rollover) end end, }), PlaceObj('XTemplateFunc', { 'name', "SetSelected(self, selected)", 'func', function (self, selected) if GetUIStyleGamepad() then self:SetFocus(selected) end end, }), }), PlaceObj('XTemplateWindow', { '__condition', function (parent, context) return context.prop_meta.leave_space end, '__class', "XContextWindow", }, { PlaceObj('XTemplateFunc', { 'name', "IsSelectable", 'func', function (self, ...) return false end, }), }), })
local StringBuffer = require("string_buffer") local Command = require("uci.command") local M = {} local options = { "btime", "wtime", "binc", "winc", } function M.parse(list) local data = {} assert(list[1] == "go") data.command = Command.GO local index = 2 while index <= #list do for _, v in ipairs(options) do if list[index] == v then data[v] = tonumber(list[index + 1]) index = index + 2 break end end end return data end function M.tostring(data) assert(data.command == Command.GO) local str = StringBuffer("go") if data.ponder then str:append(" "):append("ponder") end if data.infinite then str:append(" "):append("infinite") else data.btime = data.btime or 0 data.wtime = data.wtime or 0 end if data.mate then str:append(" "):append("mate") if tonumber(data.mate) or data.mate == "infinite" then str:append(" "):append(data.mate) end end for i = 1, #options do if data[options[i]] then str:append(" "):append(options[i]) :append(" "):append(data[options[i]]) end end return str:tostring() end return M
Weapon.PrettyName = "M16A4 ACOG" Weapon.WeaponID = "m9k_m16a4_acog" Weapon.DamageMultiplier = 0.6 Weapon.WeaponType = WEAPON_PRIMARY
local function getEncoder() local model = nn.Sequential() local ct = 0 function _bottleneck(internal_scale, use_relu, asymetric, dilated, input, output, downsample) local internal = output / internal_scale local input_stride = downsample and 2 or 1 local sum = nn.ConcatTable() local main = nn.Sequential() local other = nn.Sequential() sum:add(main):add(other) main:add(nn.SpatialConvolution(input, internal, input_stride, input_stride, input_stride, input_stride, 0, 0):noBias()) main:add(nn.SpatialBatchNormalization(internal, 1e-3)) if use_relu then main:add(nn.PReLU(internal)) end if not asymetric and not dilated then main:add(nn.SpatialConvolution(internal, internal, 3, 3, 1, 1, 1, 1)) elseif asymetric then local pad = (asymetric-1) / 2 main:add(nn.SpatialConvolution(internal, internal, asymetric, 1, 1, 1, pad, 0):noBias()) main:add(nn.SpatialConvolution(internal, internal, 1, asymetric, 1, 1, 0, pad)) elseif dilated then main:add(nn.SpatialDilatedConvolution(internal, internal, 3, 3, 1, 1, dilated, dilated, dilated, dilated)) else assert(false, 'You shouldn\'t be here') end main:add(nn.SpatialBatchNormalization(internal, 1e-3)) if use_relu then main:add(nn.PReLU(internal)) end main:add(nn.SpatialConvolution(internal, output, 1, 1, 1, 1, 0, 0):noBias()) main:add(nn.SpatialBatchNormalization(output, 1e-3)) main:add(nn.SpatialDropout((ct < 5) and 0.01 or 0.1)) ct = ct + 1 other:add(nn.Identity()) if downsample then other:add(nn.SpatialMaxPooling(2, 2, 2, 2)) end if input ~= output then other:add(nn.Padding(1, output-input, 3)) end return nn.Sequential():add(sum):add(nn.CAddTable()):add(nn.PReLU(output)) end local _ = require 'moses' local bottleneck = _.bindn(_bottleneck, 4, true, false, false) local cbottleneck = _.bindn(_bottleneck, 4, true, false, false) local xbottleneck = _.bindn(_bottleneck, 4, true, 7, false) local wbottleneck = _.bindn(_bottleneck, 4, true, 5, false) local dbottleneck = _.bindn(_bottleneck, 4, true, false, 2) local xdbottleneck = _.bindn(_bottleneck, 4, true, false, 4) local xxdbottleneck = _.bindn(_bottleneck, 4, true, false, 8) local xxxdbottleneck = _.bindn(_bottleneck, 4, true, false, 16) local xxxxdbottleneck = _.bindn(_bottleneck, 4, true, false, 32) local initial_block = nn.ConcatTable(2) initial_block:add(nn.SpatialConvolution(3, 13, 3, 3, 2, 2, 1, 1)) initial_block:add(nn.SpatialMaxPooling(2, 2, 2, 2)) model:add(initial_block) -- 128x256 model:add(nn.JoinTable(2)) -- can't use Concat, because SpatialConvolution needs contiguous gradOutput model:add(nn.SpatialBatchNormalization(16, 1e-3)) model:add(nn.PReLU(16)) model:add(bottleneck(16, 64, true)) -- 64x128 for i = 1,4 do model:add(bottleneck(64, 64)) end model:add(bottleneck(64, 128, true)) -- 32x64 for i = 1,2 do model:add(cbottleneck(128, 128)) model:add(dbottleneck(128, 128)) model:add(wbottleneck(128, 128)) model:add(xdbottleneck(128, 128)) model:add(cbottleneck(128, 128)) model:add(xxdbottleneck(128, 128)) model:add(wbottleneck(128, 128)) model:add(xxxdbottleneck(128, 128)) end --model:add(nn.SpatialConvolution(128, classes, 1, 1)) return model end -------------------------------------------------------------------------------- -- Model definition starts here -------------------------------------------------------------------------------- local classes = 30 local model = getEncoder() -- SpatialMaxUnpooling requires nn modules... model:apply(function(module) if module.modules then for i,submodule in ipairs(module.modules) do if torch.typename(submodule):match('nn.SpatialMaxPooling') then module.modules[i] = nn.SpatialMaxPooling(2, 2, 2, 2) -- TODO: make more flexible end end end end) -- find pooling modules local pooling_modules = {} model:apply(function(module) if torch.typename(module):match('nn.SpatialMaxPooling') then table.insert(pooling_modules, module) end end) assert(#pooling_modules == 3, 'There should be 3 pooling modules') function bottleneck(input, output, upsample, reverse_module) local internal = output / 4 local input_stride = upsample and 2 or 1 local module = nn.Sequential() local sum = nn.ConcatTable() local main = nn.Sequential() local other = nn.Sequential() sum:add(main):add(other) main:add(nn.SpatialConvolution(input, internal, 1, 1, 1, 1, 0, 0):noBias()) main:add(nn.SpatialBatchNormalization(internal, 1e-3)) main:add(nn.ReLU(true)) if not upsample then main:add(nn.SpatialConvolution(internal, internal, 3, 3, 1, 1, 1, 1)) else main:add(nn.SpatialFullConvolution(internal, internal, 3, 3, 2, 2, 1, 1, 1, 1)) end main:add(nn.SpatialBatchNormalization(internal, 1e-3)) main:add(nn.ReLU(true)) main:add(nn.SpatialConvolution(internal, output, 1, 1, 1, 1, 0, 0):noBias()) main:add(nn.SpatialBatchNormalization(output, 1e-3)) other:add(nn.Identity()) if input ~= output or upsample then other:add(nn.SpatialConvolution(input, output, 1, 1, 1, 1, 0, 0):noBias()) other:add(nn.SpatialBatchNormalization(output, 1e-3)) if upsample and reverse_module then other:add(nn.SpatialMaxUnpooling(reverse_module)) end end if upsample and not reverse_module then main:remove(#main.modules) -- remove BN return main end return module:add(sum):add(nn.CAddTable()):add(nn.ReLU(true)) end --model:add(bottleneck(128, 128)) model:add(bottleneck(128, 64, true, pooling_modules[3])) -- 32x64 model:add(bottleneck(64, 64)) model:add(bottleneck(64, 64)) model:add(bottleneck(64, 16, true, pooling_modules[2])) -- 64x128 model:add(bottleneck(16, 16)) model:add(nn.SpatialFullConvolution(16, classes, 2, 2, 2, 2)) return model
local diamondShop_pin_map = require("qnFiles/qnPlist/hall/diamondShop_pin"); local gameHelpTabListItem= { name="gameHelpTabListItem",type=0,typeName="View",time=0,report=0,x=0,y=0,width=330,height=120,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft, { name="left_tab_btn",type=2,typeName="Button",time=77357163,report=0,x=0,y=0,width=330,height=110,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file="hall/common/bg_blank.png", { name="selImg",type=1,typeName="Image",time=90129643,report=0,x=0,y=0,width=344,height=196,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignLeft,file=diamondShop_pin_map['diamondshop_tab_seleted.png'] }, { name="left_tab_text",type=4,typeName="Text",time=90129696,report=0,x=0,y=0,width=88,height=40,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=245,colorBlue=204,string=[[通 用]] } }, { name="line",type=1,typeName="Image",time=90130484,report=0,x=0,y=0,width=696,height=2,fillTopLeftX=30,fillTopLeftY=118,fillBottomRightX=40,fillBottomRightY=0,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignBottom,file="hall/common/line.png" } } return gameHelpTabListItem;
-- Lua bindings for /Volumes/Brume/Celedev CodeFlow/CodeFlow Sample Applications/LuaNavController/LuaNavController/DetailViewController.h -- Generated by Celedev® LuaBindingsGenerator on 2015-09-16 09:03:14 +0000 -- Objective C interface: @interface DetailViewController local DetailViewController = objc.classInterface ("DetailViewController") --[[ @inherits UIViewController]]
local a,b,c,d,e,f,g,h,i,j,k,l,m,n={"/init.lua","/OS.lua","/boot.lua"},{},{},unicode,computer;local function o(p)local q={e.pullSignal(p or math.huge)}q[1]=q[1]or""if#q>0 and h.n>0 and(q[1]:match"key"and not h[q[5]]or q[1]:match"cl"and not h[q[4]])then return{""}end;c[q[4]or""]=q[1]=="key_down"and 1;if c[29]and(c[56]and c[46]or c[32])then return"F"end;return table.unpack(q)end;local function r(s)local t=component.list(s)()return t and component.proxy(t)end;local function u(v,w,x)local y,z=load("return "..v,w,F,x)if not y then y,z=load(v,w,F,x)end;if y then return xpcall(y,debug.traceback)else return F,z end end;local function A(B,C)n={}for D in B:gmatch"[^\r\n]+"do n[#n+1]=D:gsub("\t",C and" "or"")end end;local function E(p,G,H)local I,J,v,K=e.uptime()+(p or math.huge)repeat J,K,K,v=o(I-e.uptime())if J=="F"or J=="key_down"and(v==G or G==0)then if H then H()end;return 1 end until e.uptime()>=I end;local L,M,N=r"gp"or{},r"pr",component.list"sc"()local O,P=M.getData(),M.setData;M.setData=function(Q,R)O=R and Q or(O:match"[a-f-0-9]+"and O:gsub("[a-f-0-9]+",Q)or Q)P(O)end;M.getData=function()return O:match"[a-f-0-9]+"or O end;e.setBootAddress=M.setData;e.getBootAddress=M.getData;h=select(2,pcall(load("return "..(O:match"#(.+)#"or""))))or{}i=O:match"*"h.n=#h;for S=1,#h do h[h[S]],h[S]=1,F end;if L and N then L.bind(N)k,l=L.maxResolution()g=l/2;L.setPaletteColor(9,0x002b36)L.setPaletteColor(11,0x8cb9c5)end;local function T(U,V,W,X,Y)L.setBackground(X or 0x002b36)L.setForeground(Y or 0x8cb9c5)L.set(U,V,W)end;local function Z(U,V,_,a0,a1,X,Y)L.setBackground(X or 0x002b36)L.setForeground(Y or 0x8cb9c5)L.fill(U,V,_,a0,a1)end;local function a2()Z(1,1,k,l," ")end;local function a3(a4)return math.ceil(k/2-a4/2)end;local function a5(V,B,X,Y)T(a3(d.len(B)),V,B,X,Y)end;local function a6(B,a7,a8,G,H,a9,z)if L and N then A(B)local aa,V=L.set,math.ceil(g-#n/2)L.setPaletteColor(9,0x002b36)L.setPaletteColor(11,0x8cb9c5)a2()if a7 then a5(V-1,a7,0x002b36,0xFFFFFF)V=V+1 end;for S=1,#n do a5(V,n[S])V=V+1 end;if a9 and L and N then L.set=function(...)L.setPaletteColor(9,0x969696)L.setPaletteColor(11,0xb4b4b4)aa(...)L.set=aa end end;return E(a8 or 0,G,H)end end;local function ab(z)return L and N and a6(z,[[¯\_(ツ)_/¯]],math.huge,0,e.shutdown,1)or error(z)end;local function ac(t)local r=component.proxy(t)if r and r.spaceTotal and t~=e.tmpAddress()then b[#b+1]={r,r.getLabel()or"N/A",t}for S=1,#a do if r.exists(a[S])then b[#b][4]=a[S]end end end end;local function ad()b={}ac(M.getData())for ae in pairs(component.list"f")do ac(M.getData()~=ae and ae or"")end end;local function af(B,ag)return d.len(B)>ag and d.sub(B,1,ag).."…"or B end;local function ah(ai,aj,V,ak,al)local ah,am,an,ao,U,ap,J,aq,v,K="",d.len(ai),1,1::ar::J,K,aq,v=o(.5)if J=="F"then ah=F;goto as elseif J=="key_down"then if aq>=32 and d.len(am..ah)<k-am-1 then ah=d.sub(ah,1,an-1)..d.char(aq)..d.sub(ah,an,-1)an=an+1 elseif aq==8 and#ah>0 then ah=d.sub(d.sub(ah,1,an-1),1,-2)..d.sub(ah,an,-1)an=an-1 elseif aq==13 then goto as elseif v==203 and an>1 then an=an-1 elseif v==205 and an<=d.len(ah)then an=an+1 elseif v==200 and al then ah=al;an=d.len(al)+1 elseif v==208 and al then ah=""an=1 end;ao=1 elseif J:match"cl"then ah=d.sub(ah,1,an-1)..aq..d.sub(ah,an,-1)an=an+d.len(aq)elseif J~="key_up"then ao=not ao end;U=ak and a3(d.len(ah)+am)or aj;ap=U+am+an-1;Z(1,V,k,1," ")T(U,V,ai..ah,0x002b36,0xFFFFFF)if ap<=k then T(ap,V,L.get(ap,V),ao and 0xFFFFFF or 0x002b36,ao and 0x002b36 or 0xFFFFFF)end;goto ar::as::Z(1,V,k,1," ")return ah end;local function at(...)local B=table.pack(...)for S=1,B.n do B[S]=tostring(B[S])end;A(table.concat(B," "),1)for S=1,#n do L.copy(1,1,k,l-1,0,-1)Z(1,l-1,k,1," ")T(1,l-1,n[S])end end;local function au(av,a9)local t=af(av[3],a9 and 36 or 6)return av[4]and("Boot%s %s from %s (%s)"):format(a9 and"ing"or"",av[4],av[2],t)or("Boot from %s (%s) is not available"):format(av[2],t)end;local function aw(av)if av[4]then local ax,Q,y,ay,z,aw=av[1].open(av[4],"r"),""::ar::y=av[1].read(ax,math.huge)if y then Q=Q..y;goto ar end;av[1].close(ax)aw=function()a6(au(av,1),F,.5,F,F,1)if M.getData()~=av[3]then M.setData(av[3])end;ay,z=u(Q,"="..av[4])if not ay then ab(z)end;return 1 end;Q=i and not j and a6("Hold any button to boot",F,math.huge,0,aw)or aw()end end;local function az(aA,V,aB,aC,aD)return{e=aA,s=1,y=V,k=aC,b=aB,d=function(aE,aF,aG)V=aE.y;aB=aE.b;Z(1,V-1,k,3," ",0x002b36)f=aG and f or aE;local aH,aI,aJ,U,aK,aL=0,aB==1 and 6 or 8;if aD then aD(aE)end;for S=1,#aE.e do aH=aH+d.len(aE.e[S].t)+aI end;aH=aH-aI;U=a3(aH)for S=1,#aE.e do aK,aL=aE.s==S and 1,aE.e[S]aJ=d.len(aL.t)if aK and not aF then Z(U-aI/2,V-(aB==1 and 0 or 1),aJ+aI,aB==1 and 1 or 3," ",0x8cb9c5)T(U,V,aL.t,0x8cb9c5,0x002b36)else T(U,V,aL.t,0x002b36,0x8cb9c5)end;U=U+aJ+aI end end}end;local function aM()j=1::aN::m=r"et"ad()local x,J,v,Q,aO,aP,aQ,av,r,aR,aS,aT,ax,y,aU,aV,K=setmetatable({print=at,proxy=r,os={sleep=function(p)E(p)end},read=function(al)at(" ")local Q=ah("",1,l-1,F,al)T(1,l-1,Q)return Q end},{__index=_G})aO=az({{t="Power off",a=function()e.shutdown()end},{t="Lua",a=function()a2()::ar::Q=ah("> ",1,l,F,Q)if Q then at("> "..Q)T(1,l,">")at(select(2,u(Q,"=stdin",x)))goto ar end;aQ(F,F,1,1)end}},g+2,1,function()f=aP;aQ(1,1,F,F)end)aO.e[#aO.e+1]=m and{t="Netboot",a=function()aT,Q=ah("URL: ",F,g+7,1),""if#aT>0 then ax,y=m.request(aT),""if ax then a6("Downloading "..aT.."...")::ar::y=ax.read()if y then Q=Q..y;goto ar end;ax.close()a6(select(2,u(Q,"=netboot"))or"is empty","Netboot:",math.huge,0)else a6("Invalid URL","Netboot:",math.huge,0)end end;aQ(F,F,1,1)end}if#b>0 then aU=#aO.e+1;aP=az({},g-2,2,function()f=aO;aQ(F,F,1,1)end,function(aE)av=b[aE.s]r=av[1]aV=r.spaceTotal()aR=r.isReadOnly()Z(1,g+5,k,3," ")a5(g+5,au(av),F,0xFFFFFF)a5(g+7,("Disk usage %s%% / %s / %s"):format(math.floor(r.spaceUsed()/(aV/100)),aR and"Read only"or"Read & Write",aV<2^20 and"FDD"or aV<2^20*12 and"HDD"or"RAID"))for S=aU,#aO.e do aO.e[S]=F end;if aR then aO.s=aO.s>#aO.e and#aO.e or aO.s else aO.e[aU]={t="Rename",a=function()aS=ah("New label: ",F,g+7,1)if#aS>0 then pcall(r.setLabel,aS)av[2]=af(aS,16)aP.e[aE.s].t=af(aS,6)end;aP:d(1,1)aO:d()end}aO.e[#aO.e+1]={t="Format",a=function()av[4]=F;r.remove("/")aP:d(1,1)aO:d()end}end;aO:d(1,1)end)for S=1,#b do aP.e[S]={t=af(b[S][2],6),a=function(aE)aw(b[aE.s])end}end else aO.y=g;aO.b=2 end;aQ=function(aW,aX,aY,aZ)a2()if aP then aP:d(aY,aZ)aO:d(aW,aX)else a5(g+4,"No drives available",0x002b36,0xFFFFFF)aO:d()end;a5(l,"Use ← ↑ → key to move cursor; Enter to do action; CTRL+D to shutdown")end;aQ(1,1)::ar::J,K,K,v=o()if J=="key_down"then if v==200 then f.k()elseif v==208 then f.k()elseif v==203 then f.s=f.s>1 and f.s-1 or#f.e;f:d()elseif v==205 then f.s=f.s<#f.e and f.s+1 or 1;f:d()elseif v==28 then f.e[f.s].a(f)end elseif J:match"component"then goto aN elseif J=="F"then e.shutdown()end;goto ar end;ad()a6("Hold CTRL to stay in bootloader",F,1.3,29,aM)for S=1,#b do if aw(b[S])then e.shutdown()end end;m=L and N and aM()or error"No drives available"
function onCreate() -- background shit makeLuaSprite('ChamberBG', 'ChamberBG', -600, -300); setScrollFactor('ChamberBG', 0.9, 0.9); makeLuaSprite('ChamberFloor', 'ChamberFloor', -650, -200); setScrollFactor('ChamberFloor', 0.9, 0.9); scaleObject('ChamberFloor', 1.1, 1.1); addLuaSprite('ChamberBG', false); addLuaSprite('ChamberFloor', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
local lVector = require 'Q/RUNTIME/VCTR/lua/lVector' local ffi = require 'ffi' local qconsts = require 'Q/UTILS/lua/q_consts' local qc = require 'Q/UTILS/lua/q_core' local get_ptr = require 'Q/UTILS/lua/get_ptr' local cmem = require 'libcmem' local function eigen(X, stand_alone_test) local stand_alone = stand_alone_test or false local soqc if stand_alone_test then local hdr = [[ extern int eigenvectors( uint64_t n, double *W, double *A, double **X ); ]] ffi.cdef(hdr) soqc = ffi.load("../src/libeigen.so") end -- START: verify inputs assert(type(X) == "table", "X must be a table ") local m local qtype for k, v in ipairs(X) do assert(type(v) == "lVector", "Each element of X must be a lVector") -- Check the vector v for eval(), if not then call eval() if not v:is_eov() then v:eval() end if (m == nil) then m = v:length() qtype = v:fldtype() assert( (qtype == "F4") or ( qtype == "F8"), "only F4/F8 supported") else assert(v:length() == m, "each element of X must have the same length") assert(v:fldtype() == qtype) end -- Note: not checking symmetry, left to user's discretion to interpret -- results if they pass in a matrix that is not symmetric end local ctype = qconsts.qtypes[qtype].ctype local fldsz = qconsts.qtypes[qtype].width assert(#X == m, "X must be a square matrix") -- END: verify inputs -- malloc space for eigenvalues (w) and eigenvectors (A) local wptr = assert(cmem.new(fldsz * m), "malloc failed") local wptr_copy = ffi.cast(ctype .. " *", get_ptr(wptr)) local Aptr = assert(cmem.new(fldsz * m * m), "malloc failed") local Aptr_copy = ffi.cast(ctype .. " *", get_ptr(Aptr)) local Xptr = assert(get_ptr(cmem.new(ffi.sizeof(ctype .. " *") * m)), "malloc failed") Xptr = ffi.cast(ctype .. " **", Xptr) for xidx = 1, m do local x_len, xptr, nn_xptr = X[xidx]:get_all() assert(nn_xptr == nil, "Values cannot be nil") Xptr[xidx-1] = ffi.cast(ctype .. " *", get_ptr(xptr)) end local cfn = nil if ( stand_alone_test ) then cfn = soqc["eigenvectors"] else cfn = qc["eigenvectors"] end print("starting eigenvectors C function") assert(cfn, "C function for eigenvectors not found") local status = cfn(m, wptr_copy, Aptr_copy, Xptr) assert(status == 0, "eigenvectors could not be calculated") print("done with C, creating outputs") local E = {} -- for this to work, m needs to be less than q_consts.chunk_size for i = 1, m do E[i] = lVector.new({qtype = "F8", gen = true, has_nulls = false}) E[i]:put_chunk(Aptr, nil, m) Aptr_copy = Aptr_copy + m end print("done with E") local W = lVector.new({qtype = qtype, gen = true, has_nulls = false}) W:put_chunk(wptr, nil, m) return({eigenvalues = W, eigenvectors = E}) end --return eigen return require('Q/q_export').export('eigen', eigen)
-- "modifier_wisp_spirit_invulnerable", -- "modifier_wisp_spirits", -- "modifier_wisp_spirits_slow", -- //================================================================================================================= -- // Wisp: Spirits -- //================================================================================================================= -- "wisp_spirits" -- { -- // General -- //------------------------------------------------------------------------------------------------------------- -- "ID" "5486" // unique ID number for this ability. Do not change this once established or it will invalidate collected stats. -- "AbilityBehavior" "DOTA_ABILITY_BEHAVIOR_NO_TARGET | DOTA_ABILITY_BEHAVIOR_IMMEDIATE" -- "AbilityUnitDamageType" "DAMAGE_TYPE_MAGICAL" -- "SpellImmunityType" "SPELL_IMMUNITY_ENEMIES_NO" -- "SpellDispellableType" "SPELL_DISPELLABLE_NO" -- "AbilitySound" "Hero_Wisp.Spirits.Cast" -- "HasScepterUpgrade" "1" -- // Casting -- //------------------------------------------------------------------------------------------------------------- -- "AbilityCastPoint" "0" -- "AbilityCastAnimation" "ACT_INVALID" -- // Time -- //------------------------------------------------------------------------------------------------------------- -- "AbilityCooldown" "26.0 24.0 22.0 20.0" -- "AbilityDuration" "19.0 19.0 19.0 19.0" -- // Cost -- //------------------------------------------------------------------------------------------------------------- -- "AbilityManaCost" "120 130 140 150" -- // Special -- //------------------------------------------------------------------------------------------------------------- -- "AbilitySpecial" -- { -- "01" -- { -- "var_type" "FIELD_INTEGER" -- "creep_damage" "10 18 26 34" -- } -- "02" -- { -- "var_type" "FIELD_INTEGER" -- "hero_damage" "20 40 60 80" -- "LinkedSpecialBonus" "special_bonus_unique_wisp" -- } -- "03" -- { -- "var_type" "FIELD_FLOAT" -- "revolution_time" "5.0 5.0 5.0 5.0" -- } -- "04" -- { -- "var_type" "FIELD_INTEGER" -- "min_range" "200" -- } -- "05" -- { -- "var_type" "FIELD_INTEGER" -- "max_range" "700" -- "LinkedSpecialBonus" "special_bonus_unique_wisp_3" -- } -- "06" -- { -- "var_type" "FIELD_INTEGER" -- "hero_hit_radius" "110" -- } -- "07" -- { -- "var_type" "FIELD_INTEGER" -- "explode_radius" "360" -- } -- "08" -- { -- "var_type" "FIELD_INTEGER" -- "hit_radius" "150 150 150 150" -- } -- "09" -- { -- "var_type" "FIELD_INTEGER" -- "spirit_movement_rate" "250 250 250 250" -- } -- "10" -- { -- "var_type" "FIELD_FLOAT" -- "spirit_duration" "19.0 19.0 19.0 19.0" -- } -- } -- } LinkLuaModifier("modifier_imba_wisp_spirits_v2", "components/abilities/heroes/hero_wisp_v2", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_imba_wisp_spirit_v2_invulnerable", "components/abilities/heroes/hero_wisp_v2", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_imba_wisp_spirits_v2_slow", "components/abilities/heroes/hero_wisp_v2", LUA_MODIFIER_MOTION_NONE) imba_wisp_spirits_v2 = imba_wisp_spirits_v2 or class({}) modifier_imba_wisp_spirits_v2 = modifier_imba_wisp_spirits_v2 or class({}) modifier_imba_wisp_spirit_v2_invulnerable = modifier_imba_wisp_spirit_v2_invulnerable or class({}) modifier_imba_wisp_spirits_v2_slow = modifier_imba_wisp_spirits_v2_slow or class({}) imba_wisp_spirits_in_v2 = imba_wisp_spirits_in_v2 or class({}) -------------------------- -- IMBA_WISP_SPIRITS_V2 -- -------------------------- function imba_wisp_spirits_v2:OnSpellStart() self:GetCaster():RemoveModifierByName("modifier_imba_wisp_spirits_v2") self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_spirits_v2", {duration = self:GetDuration()}) end ----------------------------------- -- MODIFIER_IMBA_WISP_SPIRITS_V2 -- ----------------------------------- function modifier_imba_wisp_spirits_v2:OnCreated() if not self:GetAbility() then self:Destroy() return end self.creep_damage = self:GetAbility():GetSpecialValueFor("creep_damage") self.revolution_time = self:GetAbility():GetSpecialValueFor("revolution_time") self.min_range = self:GetAbility():GetSpecialValueFor("min_range") self.hero_hit_radius = self:GetAbility():GetSpecialValueFor("hero_hit_radius") self.explode_radius = self:GetAbility():GetSpecialValueFor("explode_radius") self.hit_radius = self:GetAbility():GetSpecialValueFor("hit_radius") self.spirit_movement_rate = self:GetAbility():GetSpecialValueFor("spirit_movement_rate") self.spirit_duration = self:GetAbility():GetSpecialValueFor("spirit_duration") self.number_of_spirits = self:GetAbility():GetSpecialValueFor("number_of_spirits") self.spawn_interval = self:GetAbility():GetSpecialValueFor("spawn_interval") if not IsServer() then return end self.hero_damage = self:GetAbility():GetTalentSpecialValueFor("hero_damage") self.max_range = self:GetAbility():GetTalentSpecialValueFor("min_range") self.ability_duration = self:GetAbility():GetDuration() self.spirits_spawned = 0 self:StartIntervalThink(self.spawn_interval) end function modifier_imba_wisp_spirits_v2:OnIntervalThink() local spirit = CreateUnitByName("npc_dota_wisp_spirit", self:GetCaster():GetAbsOrigin() + Vector(0, self.max_range, 0), false, self:GetCaster(), self:GetCaster(), self:GetCaster():GetTeamNumber()) spirit:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_wisp_spirit_v2_invulnerable", {}) spirit:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_kill", {duration = self.ability_duration}) self.spirits_spawned = self.spirits_spawned + 1 if self.spirits_spawned >= self.number_of_spirits then end end -- -- Editors: -- -- EarthSalamander #42, 23.05.2018 (contributor) -- -- Naowin, 13.06.2018 (creator) -- -- Based on old Dota 2 Spell Library: https://github.com/Pizzalol/SpellLibrary/blob/master/game/scripts/vscripts/heroes/hero_wisp -- ------------------------------ -- -- TETHER -- -- ------------------------------ -- imba_wisp_tether = class({}) -- -- This modifier applies on Wisp and deals with giving the target heal and mana amp -- LinkLuaModifier("modifier_imba_wisp_tether", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_tether_ally", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_tether_latch", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_tether_slow", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- -- LinkLuaModifier("modifier_imba_wisp_tether_slow_immune", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_tether_ally_attack", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- -- LinkLuaModifier("modifier_imba_wisp_tether_bonus_regen", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- -- This deals with the auto-cast logic for the Backpack Wisp IMBAfication -- LinkLuaModifier("modifier_imba_wisp_tether_handler", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_tether_backpack", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- function imba_wisp_tether:GetIntrinsicModifierName() -- return "modifier_imba_wisp_tether_handler" -- end -- function imba_wisp_tether:GetBehavior() -- if self:GetCaster():GetLevel() < self:GetSpecialValueFor("backpack_level_unlock") then -- return self.BaseClass.GetBehavior(self) -- else -- return tonumber(tostring(self.BaseClass.GetBehavior(self))) + DOTA_ABILITY_BEHAVIOR_AUTOCAST -- end -- end -- function imba_wisp_tether:GetCastRange(location, target) -- if self:GetCaster():GetModifierStackCount("modifier_imba_wisp_tether_handler", self:GetCaster()) == 0 then -- return self.BaseClass.GetCastRange(self, location, target) + self:GetCaster():FindTalentValue("special_bonus_imba_wisp_5") -- else -- -- If the below value is negative then it doesn't show cast range properly on client-side, but still respects no cast range increases in server-side so... -- return self:GetSpecialValueFor("backpack_distance") - self:GetCaster():GetCastRangeBonus() -- end -- end -- function imba_wisp_tether:GetCustomCastErrorTarget(target) -- if target == self:GetCaster() then -- return "dota_hud_error_cant_cast_on_self" -- elseif target:HasModifier("modifier_imba_wisp_tether") and self:GetCaster():HasModifier("modifier_imba_wisp_tether_ally") then -- return "WHY WOULD YOU DO THIS" -- end -- end -- function imba_wisp_tether:GetAbilityTextureName() -- if not IsClient() then return end -- if not self:GetCaster().arcana_style then return "wisp_tether" end -- return "imba_wisp_tether_arcana" -- end -- function imba_wisp_tether:CastFilterResultTarget(target) -- if IsServer() then -- local caster = self:GetCaster() -- local casterID = caster:GetPlayerOwnerID() -- local targetID = target:GetPlayerOwnerID() -- if target == caster then -- return UF_FAIL_CUSTOM -- end -- if target:IsCourier() then -- return UF_FAIL_COURIER -- end -- if target:HasModifier("modifier_imba_wisp_tether") and self:GetCaster():HasModifier("modifier_imba_wisp_tether_ally") then -- return UF_FAIL_CUSTOM -- end -- local nResult = UnitFilter(target, self:GetAbilityTargetTeam(), self:GetAbilityTargetType(), self:GetAbilityTargetFlags(), caster:GetTeamNumber()) -- return nResult -- end -- end -- function imba_wisp_tether:OnSpellStart() -- local ability = self:GetCaster():FindAbilityByName("imba_wisp_tether") -- local caster = self:GetCaster() -- local destroy_tree_radius = ability:GetSpecialValueFor("destroy_tree_radius") -- local movespeed = ability:GetSpecialValueFor("movespeed") -- local regen_bonus = ability:GetSpecialValueFor("tether_bonus_regen") -- local latch_distance = self:GetSpecialValueFor("latch_distance") -- if caster:HasTalent("special_bonus_imba_wisp_5") then -- ability.bonus_range = caster:FindTalentValue("special_bonus_imba_wisp_5") -- latch_distance = latch_distance + ability.bonus_range -- end -- -- needed to be accessed globaly -- ability.slow_duration = ability:GetSpecialValueFor("stun_duration") -- ability.slow = ability:GetSpecialValueFor("slow") -- self.caster_origin = self:GetCaster():GetAbsOrigin() -- self.target_origin = self:GetCursorTarget():GetAbsOrigin() -- self.tether_ally = self:GetCursorTarget() -- self.tether_slowedUnits = {} -- self.target = self:GetCursorTarget() -- -- Shifting caster of modifier from Wisp to the target so you can access their stats on client-side without laggy ass nettables or hack methods -- caster:AddNewModifier(self.target, self, "modifier_imba_wisp_tether", {}) -- -- Why are there always so many stupid hidden OP buffs programmed in I'm commenting these out -- -- local self_regen_bonus = caster:AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_tether_bonus_regen", {}) -- -- self_regen_bonus:SetStackCount(regen_bonus) -- local tether_modifier = self:GetCursorTarget():AddNewModifier(self:GetCaster(), ability, "modifier_imba_wisp_tether_ally", {}) -- tether_modifier:SetStackCount(movespeed) -- -- local target_regen_bonus = self:GetCursorTarget():AddNewModifier(self:GetCaster(), ability, "modifier_imba_wisp_tether_bonus_regen", {}) -- -- target_regen_bonus:SetStackCount(regen_bonus) -- if caster:HasModifier("modifier_imba_wisp_overcharge") then -- if self.target:HasModifier("modifier_imba_wisp_overcharge") then -- self.target:RemoveModifierByName("modifier_imba_wisp_overcharge") -- end -- imba_wisp_overcharge:AddOvercharge(self:GetCaster(), self.target) -- end -- --7.21 version -- if caster:HasAbility("imba_wisp_overcharge_721") and caster:HasModifier("modifier_imba_wisp_overcharge_721") then -- self.target:AddNewModifier(caster, caster:FindAbilityByName("imba_wisp_overcharge_721"), "modifier_imba_wisp_overcharge_721", {}) -- end -- if caster:HasTalent("special_bonus_imba_wisp_2") then -- self.tether_ally:SetStolenScepter(true) -- if self.tether_ally.CalculateStatBonus then -- self.tether_ally:CalculateStatBonus(true) -- end -- end -- if caster:HasTalent("special_bonus_imba_wisp_6") then -- self.target:AddNewModifier(self:GetCaster(), ability, "modifier_imba_wisp_tether_ally_attack", {}) -- end -- if not self:GetAutoCastState() then -- local distToAlly = (self:GetCursorTarget():GetAbsOrigin() - caster:GetAbsOrigin()):Length2D() -- if distToAlly >= latch_distance then -- caster:AddNewModifier(caster, self, "modifier_imba_wisp_tether_latch", { destroy_tree_radius = destroy_tree_radius}) -- end -- else -- caster:AddNewModifier(self.target, self, "modifier_imba_wisp_tether_backpack", {}) -- end -- -- Let's manually add Tether Break for Rubick and Morphling so they can use the skill properly -- if not caster:HasAbility("imba_wisp_tether_break") then -- caster:AddAbility("imba_wisp_tether_break") -- end -- caster:SwapAbilities("imba_wisp_tether", "imba_wisp_tether_break", false, true) -- caster:FindAbilityByName("imba_wisp_tether_break"):SetLevel(1) -- -- "Goes on a 0.25-second cooldown when Tether is cast, so that it cannot be immediately broken." -- caster:FindAbilityByName("imba_wisp_tether_break"):StartCooldown(0.25) -- end -- -- Remove Tether Break for Rubick and Morphling when skill is lost -- function imba_wisp_tether:OnUnStolen() -- if self:GetCaster():HasAbility("imba_wisp_tether_break") then -- self:GetCaster():RemoveAbility("imba_wisp_tether_break") -- end -- end -- --------------------- -- -- TETHER MODIFIER -- -- --------------------- -- modifier_imba_wisp_tether = class({}) -- function modifier_imba_wisp_tether:IsHidden() return false end -- function modifier_imba_wisp_tether:IsPurgable() return false end -- function modifier_imba_wisp_tether:GetPriority() return MODIFIER_PRIORITY_SUPER_ULTRA end -- function modifier_imba_wisp_tether:OnCreated(params) -- self.target = self:GetCaster() -- -- Store this value in those scenarios where Wisp would otherwise be sloweed by the tethered target (ex. Pangolier's Rolling Thunder) -- -- Second parameter of CDOTA_BaseNPC:GetMoveSpeedModifier checks if you want the value with no slows accounted for returned -- -- False for original means that Wisp can get slowed, and true for target means Wisp won't get slowed if the target gets slowed -- self.original_speed = self:GetParent():GetMoveSpeedModifier(self:GetParent():GetBaseMoveSpeed(), false) -- self.target_speed = self.target:GetMoveSpeedModifier(self.target:GetBaseMoveSpeed(), true) -- self.difference = self.target_speed - self.original_speed -- if IsServer() then -- self.radius = self:GetAbility():GetSpecialValueFor("radius") -- self.tether_heal_amp = self:GetAbility():GetSpecialValueFor("tether_heal_amp") -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_5") then -- self.radius = self.radius + self:GetCaster():FindTalentValue("special_bonus_imba_wisp_5") -- end -- -- used to count total health/mana gained during 1sec -- self.total_gained_mana = 0 -- self.total_gained_health = 0 -- self.update_timer = 0 -- self.time_to_send = 1 -- self:GetCaster():EmitSound("Hero_Wisp.Tether") -- end -- self:StartIntervalThink(FrameTime()) -- end -- function modifier_imba_wisp_tether:OnIntervalThink() -- self.difference = 0 -- self.original_speed = self:GetParent():GetMoveSpeedModifier(self:GetParent():GetBaseMoveSpeed(), false) -- self.target_speed = self.target:GetMoveSpeedModifier(self.target:GetBaseMoveSpeed(), true) -- self.difference = self.target_speed - self.original_speed -- if not IsServer() then return end -- -- Morphling/Rubick exception...as per usual -- if not self:GetAbility() or not self:GetAbility().tether_ally then -- self:Destroy() -- return -- end -- self.update_timer = self.update_timer + FrameTime() -- -- handle health and mana -- if self.update_timer > self.time_to_send then -- SendOverheadEventMessage(nil, OVERHEAD_ALERT_HEAL, self.target, self.total_gained_health * self.tether_heal_amp, nil) -- SendOverheadEventMessage(nil, OVERHEAD_ALERT_MANA_ADD, self.target, self.total_gained_mana * self.tether_heal_amp, nil) -- self.total_gained_mana = 0 -- self.total_gained_health = 0 -- self.update_timer = 0 -- end -- if (self:GetParent():IsOutOfGame()) then -- self:GetParent():RemoveModifierByName("modifier_imba_wisp_tether") -- return -- end -- if self:GetParent():HasModifier("modifier_imba_wisp_tether_latch") then -- return -- end -- if (self:GetAbility().tether_ally:GetAbsOrigin() - self:GetParent():GetAbsOrigin()):Length2D() <= self.radius then -- return -- end -- self:GetParent():RemoveModifierByName("modifier_imba_wisp_tether") -- end -- function modifier_imba_wisp_tether:DeclareFunctions() -- local decFuncs = { -- MODIFIER_EVENT_ON_HEAL_RECEIVED, -- MODIFIER_EVENT_ON_MANA_GAINED, -- MODIFIER_PROPERTY_MOVESPEED_BASE_OVERRIDE, -- MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT, -- MODIFIER_PROPERTY_MOVESPEED_LIMIT, -- MODIFIER_PROPERTY_IGNORE_MOVESPEED_LIMIT -- } -- return decFuncs -- end -- function modifier_imba_wisp_tether:OnHealReceived(keys) -- if keys.unit == self:GetParent() then -- self.target:Heal(keys.gain * self.tether_heal_amp, self:GetAbility()) -- -- in order to avoid spam in "OnGained" we group it up in total_gained. Value is sent and reset each 1s -- self.total_gained_health = self.total_gained_health + keys.gain -- end -- end -- function modifier_imba_wisp_tether:OnManaGained(keys) -- if keys.unit == self:GetParent() and self.target.GiveMana then -- self.target:GiveMana(keys.gain * self.tether_heal_amp) -- -- in order to avoid spam in "OnGained" we group it up in total_gained. Value is sent and reset each 1s -- self.total_gained_mana = self.total_gained_mana + keys.gain -- end -- end -- function modifier_imba_wisp_tether:GetModifierMoveSpeedOverride() -- if self.target and self.target.GetBaseMoveSpeed then -- return self.target:GetBaseMoveSpeed() -- end -- end -- function modifier_imba_wisp_tether:GetModifierMoveSpeedBonus_Constant() -- if self.original_speed and self.target:GetMoveSpeedModifier(self.target:GetBaseMoveSpeed(), true) >= self.original_speed and self.difference then -- return self.difference -- end -- end -- function modifier_imba_wisp_tether:GetModifierMoveSpeed_Limit() -- return self.target_speed -- end -- function modifier_imba_wisp_tether:GetModifierIgnoreMovespeedLimit() -- return 1 -- end -- function modifier_imba_wisp_tether:OnRemoved() -- if IsServer() then -- if self:GetParent():HasModifier("modifier_imba_wisp_tether_latch") then -- self:GetParent():RemoveModifierByName("modifier_imba_wisp_tether_latch") -- end -- -- if self:GetParent():HasModifier("modifier_imba_wisp_tether_bonus_regen") then -- -- self:GetParent():RemoveModifierByName("modifier_imba_wisp_tether_bonus_regen") -- -- end -- if self:GetParent():HasModifier("modifier_imba_wisp_tether_backpack") then -- self:GetParent():RemoveModifierByName("modifier_imba_wisp_tether_backpack") -- end -- if self.target:HasModifier("modifier_imba_wisp_tether_ally") then -- self.target:RemoveModifierByName("modifier_imba_wisp_overcharge") -- self.target:RemoveModifierByName("modifier_imba_wisp_tether_ally") -- --self.target:RemoveModifierByName("modifier_imba_wisp_tether_bonus_regen") -- end -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_2") then -- self.target:SetStolenScepter(false) -- if self.target.CalculateStatBonus then -- self.target:CalculateStatBonus(true) -- end -- end -- self:GetCaster():EmitSound("Hero_Wisp.Tether.Stop") -- self:GetCaster():StopSound("Hero_Wisp.Tether") -- self:GetParent():SwapAbilities("imba_wisp_tether_break", "imba_wisp_tether", false, true) -- end -- end -- ------------------------------ -- -- TETHER Regen modifier -- -- ------------------------------ -- -- modifier_imba_wisp_tether_bonus_regen = class({}) -- -- function modifier_imba_wisp_tether_bonus_regen:IsHidden() return true end -- -- function modifier_imba_wisp_tether_bonus_regen:IsPurgable() return false end -- -- function modifier_imba_wisp_tether_bonus_regen:DeclareFunctions() -- -- local decFuncs = { -- -- MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE -- -- } -- -- return decFuncs -- -- end -- -- function modifier_imba_wisp_tether_bonus_regen:GetTexture() -- -- return "wisp_tether" -- -- end -- -- function modifier_imba_wisp_tether_bonus_regen:GetModifierHealthRegenPercentage() -- -- return self:GetStackCount() / 100 -- -- end -- ------------------------------ -- -- TETHER AllY modifier -- -- ------------------------------ -- modifier_imba_wisp_tether_ally = class({}) -- function modifier_imba_wisp_tether_ally:IsHidden() return false end -- function modifier_imba_wisp_tether_ally:IsPurgable() return false end -- function modifier_imba_wisp_tether_ally:OnCreated() -- if IsServer() then -- self.pfx = ParticleManager:CreateParticle(self:GetCaster().tether_effect, PATTACH_ABSORIGIN_FOLLOW, self:GetParent()) -- ParticleManager:SetParticleControlEnt(self.pfx, 0, self:GetCaster(), PATTACH_POINT_FOLLOW, "attach_hitloc", self:GetCaster():GetAbsOrigin(), true) -- ParticleManager:SetParticleControlEnt(self.pfx, 1, self:GetParent(), PATTACH_POINT_FOLLOW, "attach_hitloc", self:GetParent():GetAbsOrigin(), true) -- EmitSoundOn("Hero_Wisp.Tether.Target", self:GetParent()) -- self:StartIntervalThink(FrameTime()) -- end -- end -- function modifier_imba_wisp_tether_ally:OnIntervalThink() -- if IsServer() then -- -- Morphling/Rubick exception -- if not self:GetAbility() then -- self:Destroy() -- return -- end -- local velocity = self:GetParent():GetAbsOrigin() - self:GetCaster():GetAbsOrigin() -- local vVelocity = velocity / FrameTime() -- vVelocity.z = 0 -- local projectile = -- { -- Ability = self:GetAbility(), -- EffectName = "particles/hero/ghost_revenant/blackjack_projectile.vpcf", -- vSpawnOrigin = self:GetCaster():GetAbsOrigin(), -- fDistance = velocity:Length2D(), -- fStartRadius = 100, -- fEndRadius = 100, -- bReplaceExisting = false, -- iMoveSpeed = vVelocity, -- Source = self:GetCaster(), -- iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY, -- iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE, -- iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- fExpireTime = GameRules:GetGameTime() + 1, -- bDeleteOnHit = false, -- vVelocity = vVelocity / 3, -- ExtraData = { -- slow_duration = self:GetAbility().slow_duration, -- slow = self:GetAbility().slow -- } -- } -- ProjectileManager:CreateLinearProjectile(projectile) -- end -- end -- function imba_wisp_tether:OnProjectileHit_ExtraData(target, location, ExtraData) -- if target ~= nil then -- -- Variables -- local caster = self:GetCaster() -- local slow = ExtraData.slow -- local slow_duration = ExtraData.slow_duration -- -- Acalia wants more stuff here... -- -- Apply slow debuff -- local slow_ref = target:AddNewModifier(caster, self, "modifier_imba_wisp_tether_slow", { duration = slow_duration }) -- slow_ref:SetStackCount(slow) -- -- An enemy unit may only be slowed once per cast. -- -- We store the enemy unit to the hashset, so we can check whether the unit has got debuff already later on. -- --self:GetAbility().tether_slowedUnits[target] = true -- end -- end -- function modifier_imba_wisp_tether_ally:OnRemoved() -- if IsServer() then -- self:GetParent():StopSound("Hero_Wisp.Tether.Target") -- ParticleManager:DestroyParticle(self.pfx, false) -- ParticleManager:ReleaseParticleIndex(self.pfx) -- if self:GetAbility() then -- self:GetAbility().target = nil -- end -- -- self:GetParent():RemoveModifierByName("modifier_imba_wisp_tether_slow_immune") -- -- self:GetCaster():RemoveModifierByName("modifier_imba_wisp_tether_slow_immune") -- self:GetParent():RemoveModifierByName("modifier_imba_wisp_tether_ally_attack") -- self:GetCaster():RemoveModifierByName("modifier_imba_wisp_tether") -- --7.21 version -- local overcharge_modifier = self:GetParent():FindModifierByNameAndCaster("modifier_imba_wisp_overcharge_721", self:GetCaster()) -- if overcharge_modifier then -- overcharge_modifier:Destroy() -- end -- end -- end -- function modifier_imba_wisp_tether_ally:DeclareFunctions() -- local decFuncs = { -- MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE -- } -- return decFuncs -- end -- function modifier_imba_wisp_tether_ally:GetModifierMoveSpeedBonus_Percentage() -- if self:GetAbility() then -- return self:GetAbility():GetSpecialValueFor("movespeed") -- end -- end -- -------------------------------------- -- -- TETHER Track attack modifier -- -- -------------------------------------- -- modifier_imba_wisp_tether_ally_attack = class({}) -- function modifier_imba_wisp_tether_ally_attack:IsHidden() return true end -- function modifier_imba_wisp_tether_ally_attack:IsPurgable() return false end -- function modifier_imba_wisp_tether_ally_attack:DeclareFunctions() -- local decFuncs = { -- MODIFIER_EVENT_ON_ATTACK -- } -- return decFuncs -- end -- function modifier_imba_wisp_tether_ally_attack:OnAttack(params) -- if IsServer() then -- if params.attacker == self:GetParent() then -- self:GetCaster():PerformAttack(params.target, true, true, true, false, true, false, false) -- end -- end -- end -- -------------------------------------- -- -- TETHER slow immune modifier -- -- -------------------------------------- -- -- modifier_imba_wisp_tether_slow_immune = class({}) -- -- function modifier_imba_wisp_tether_slow_immune:IsHidden() return true end -- -- function modifier_imba_wisp_tether_slow_immune:DeclareFunctions() -- -- local funcs = { -- -- MODIFIER_PROPERTY_MOVESPEED_ABSOLUTE_MIN, -- -- MODIFIER_PROPERTY_MOVESPEED_LIMIT -- -- } -- -- return funcs -- -- end -- -- function modifier_imba_wisp_tether_slow_immune:OnCreated(params) -- -- if IsServer() then -- -- self.limit = params.limit -- -- self.minimum_speed = params.minimum_speed -- -- else -- -- local net_table = CustomNetTables:GetTableValue("player_table", tostring(self:GetCaster():GetPlayerOwnerID())) or {} -- -- self.minimum_speed = net_table.tether_minimum_speed or 0 -- -- self.limit = net_table.tether_limit or 0 -- -- end -- -- end -- -- function modifier_imba_wisp_tether_slow_immune:GetModifierMoveSpeed_AbsoluteMin() -- -- return self.minimum_speed -- -- end -- -- function modifier_imba_wisp_tether_slow_immune:GetModifierMoveSpeed_Limit() -- -- return self.limit -- -- end -- ------------------------------ -- -- TETHER slow modifier -- -- ------------------------------ -- modifier_imba_wisp_tether_slow = class({}) -- function modifier_imba_wisp_tether_slow:DeclareFunctions() -- local funcs = { -- MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT, -- MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT -- } -- return funcs -- end -- function modifier_imba_wisp_tether_slow:GetModifierMoveSpeedBonus_Constant() -- return self:GetStackCount() -- end -- function modifier_imba_wisp_tether_slow:GetModifierAttackSpeedBonus_Constant() -- return self:GetStackCount() -- end -- ------------------------------ -- -- TETHER latch modifier -- -- ------------------------------ -- modifier_imba_wisp_tether_latch = class({}) -- function modifier_imba_wisp_tether_latch:IsHidden() return true end -- function modifier_imba_wisp_tether_latch:IsPurgable() return false end -- function modifier_imba_wisp_tether_latch:OnCreated(params) -- if IsServer() then -- self.target = self:GetAbility().target -- self.destroy_tree_radius = params.destroy_tree_radius -- -- "Pulls Io at a speed of 1000, until coming within 300 range of the target." -- self.final_latch_distance = 300 -- self:StartIntervalThink(FrameTime()) -- end -- end -- function modifier_imba_wisp_tether_latch:OnIntervalThink() -- if IsServer() then -- --"The pull gets interrupted when Io gets stunned, hexed, hidden, feared, hypnotize, or rooted during the pull." -- -- self:GetParent():IsFeared() and self:GetParent():IsHypnotized() don't actually exist as Valve functions but they'll be placeholders for if it gets implemented one way or another -- if self:GetParent():IsStunned() or self:GetParent():IsHexed() or self:GetParent():IsOutOfGame() or (self:GetParent().IsFeared and self:GetParent():IsFeared()) or (self:GetParent().IsHypnotized and self:GetParent():IsHypnotized()) or self:GetParent():IsRooted() then -- self:StartIntervalThink(-1) -- self:Destroy() -- return -- end -- -- Calculate the distance -- local casterDir = self:GetCaster():GetAbsOrigin() - self.target:GetAbsOrigin() -- local distToAlly = casterDir:Length2D() -- casterDir = casterDir:Normalized() -- if distToAlly > self.final_latch_distance then -- -- Leap to the target -- distToAlly = distToAlly - self:GetAbility():GetSpecialValueFor("latch_speed") * FrameTime() -- distToAlly = math.max( distToAlly, self.final_latch_distance ) -- Clamp this value -- local pos = self.target:GetAbsOrigin() + casterDir * distToAlly -- pos = GetGroundPosition(pos, self:GetCaster()) -- self:GetCaster():SetAbsOrigin(pos) -- end -- if distToAlly <= self.final_latch_distance then -- -- We've reached, so finish latching -- GridNav:DestroyTreesAroundPoint(self:GetCaster():GetAbsOrigin(), self.destroy_tree_radius, false) -- ResolveNPCPositions(self:GetCaster():GetAbsOrigin(), 128) -- self:GetCaster():RemoveModifierByName("modifier_imba_wisp_tether_latch") -- end -- end -- end -- function modifier_imba_wisp_tether_latch:OnDestroy() -- if not IsServer() then return end -- FindClearSpaceForUnit(self:GetParent(), self:GetParent():GetAbsOrigin(), false) -- end -- ------------------------------ -- -- BREAK TETHER -- -- ------------------------------ -- imba_wisp_tether_break = class({}) -- function imba_wisp_tether_break:IsInnateAbility() return true end -- function imba_wisp_tether_break:IsStealable() return false end -- function imba_wisp_tether_break:OnSpellStart() -- -- Let's manually add Tether for Morphling so they can use the skill properly (super bootleg) -- if not self:GetCaster():HasAbility("imba_wisp_tether") then -- local stolenAbility = self:GetCaster():AddAbility("imba_wisp_tether") -- stolenAbility:SetLevel(min((self:GetCaster():GetLevel() / 2) - 1, 4)) -- self:GetCaster():SwapAbilities("imba_wisp_tether_break", "imba_wisp_tether", false, true) -- end -- self:GetCaster():RemoveModifierByName("modifier_imba_wisp_tether") -- local target = self:GetCaster():FindAbilityByName("imba_wisp_tether").target -- if target ~= nil and target:HasModifier("modifier_imba_wisp_overcharge") then -- target:RemoveModifierByName("modifier_imba_wisp_overcharge") -- end -- end -- -- ugh -- function imba_wisp_tether_break:OnUnStolen() -- if self:GetCaster():HasAbility("imba_wisp_tether") then -- self:GetCaster():RemoveAbility("imba_wisp_tether") -- end -- end -- ----------------------------- -- -- TETHER HANDLER MODIFIER -- -- ----------------------------- -- modifier_imba_wisp_tether_handler = class({}) -- function modifier_imba_wisp_tether_handler:IsHidden() return true end -- function modifier_imba_wisp_tether_handler:IsPurgable() return false end -- function modifier_imba_wisp_tether_handler:RemoveOnDeath() return false end -- function modifier_imba_wisp_tether_handler:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end -- function modifier_imba_wisp_tether_handler:DeclareFunctions() -- local decFuncs = {MODIFIER_EVENT_ON_ORDER} -- return decFuncs -- end -- function modifier_imba_wisp_tether_handler:OnOrder(keys) -- if not IsServer() or keys.unit ~= self:GetParent() or keys.order_type ~= DOTA_UNIT_ORDER_CAST_TOGGLE_AUTO or keys.ability ~= self:GetAbility() then return end -- -- Due to logic order, this is actually reversed -- if self:GetAbility():GetAutoCastState() then -- self:SetStackCount(0) -- else -- self:SetStackCount(1) -- end -- end -- ----------------------------- -- -- TETHER BACKPACK MODIFIER -- -- ----------------------------- -- modifier_imba_wisp_tether_backpack = class({}) -- function modifier_imba_wisp_tether_backpack:IsPurgable() return false end -- function modifier_imba_wisp_tether_backpack:OnCreated() -- if not IsServer() then return end -- self.backpack_distance = self:GetAbility():GetSpecialValueFor("backpack_distance") -- self:GetParent():SetAbsOrigin(self:GetCaster():GetAbsOrigin() + (self:GetCaster():GetForwardVector() * self.backpack_distance * (-1))) -- self:StartIntervalThink(FrameTime()) -- end -- function modifier_imba_wisp_tether_backpack:OnIntervalThink() -- if self:GetParent():IsStunned() or self:GetParent():IsHexed() or self:GetParent():IsRooted() or self:GetParent():IsOutOfGame() then -- self:Destroy() -- return -- end -- self:GetParent():SetAbsOrigin(self:GetCaster():GetAbsOrigin() + (self:GetCaster():GetForwardVector() * self.backpack_distance * (-1))) -- end -- function modifier_imba_wisp_tether_backpack:OnDestroy() -- if not IsServer() then return end -- FindClearSpaceForUnit(self:GetParent(), self:GetParent():GetAbsOrigin(), false) -- end -- ------------------------------ -- -- SPIRITS -- -- ------------------------------ -- imba_wisp_spirits = class({}) -- LinkLuaModifier("modifier_imba_wisp_spirits", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_spirit_handler", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_spirits_hero_hit", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_spirits_creep_hit", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_spirits_slow", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_spirit_damage_handler", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_spirits_true_sight", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- function imba_wisp_spirits:GetAbilityTextureName() -- if not IsClient() then return end -- if not self:GetCaster().arcana_style then return "wisp_spirits" end -- return "imba_wisp_spirits_arcana" -- end -- function imba_wisp_spirits:GetCooldown(level) -- return self.BaseClass.GetCooldown(self, level) * math.max(self:GetCaster():FindTalentValue("special_bonus_imba_wisp_10", "cdr_mult"), 1) -- end -- function imba_wisp_spirits:OnSpellStart() -- if IsServer() then -- self.caster = self:GetCaster() -- self.ability = self.caster:FindAbilityByName("imba_wisp_spirits") -- self.start_time = GameRules:GetGameTime() -- self.spirits_num_spirits = 0 -- local spirit_min_radius = self.ability:GetSpecialValueFor("min_range") -- local spirit_max_radius = self.ability:GetSpecialValueFor("max_range") -- local spirit_movement_rate = self.ability:GetSpecialValueFor("spirit_movement_rate") -- local creep_damage = self.ability:GetSpecialValueFor("creep_damage") -- local explosion_damage = self.ability:GetTalentSpecialValueFor("explosion_damage") -- local slow = self.ability:GetSpecialValueFor("slow") -- local spirit_duration = self.ability:GetSpecialValueFor("spirit_duration") -- local spirit_summon_interval = self.ability:GetSpecialValueFor("spirit_summon_interval") -- local max_spirits = self.ability:GetSpecialValueFor("num_spirits") -- local collision_radius = self.ability:GetSpecialValueFor("collision_radius") -- local explosion_radius = self.ability:GetSpecialValueFor("explode_radius") -- local spirit_turn_rate = self.ability:GetSpecialValueFor("spirit_turn_rate") -- local vision_radius = self.ability:GetSpecialValueFor("explode_radius") -- local vision_duration = self.ability:GetSpecialValueFor("vision_duration") -- local slow_duration = self.ability:GetSpecialValueFor("slow_duration") -- local damage_interval = self.ability:GetSpecialValueFor("damage_interval") -- -- Large Hadron Collider talent -- if self.caster:HasTalent("special_bonus_imba_wisp_10") then -- spirit_movement_rate = spirit_movement_rate * math.max(self.caster:FindTalentValue("special_bonus_imba_wisp_10"), 1) -- spirit_summon_interval = spirit_summon_interval / math.max(self.caster:FindTalentValue("special_bonus_imba_wisp_10"), 1) -- max_spirits = max_spirits * math.max(self.caster:FindTalentValue("special_bonus_imba_wisp_10"), 1) -- spirit_turn_rate = spirit_turn_rate * math.max(self.caster:FindTalentValue("special_bonus_imba_wisp_10"), 1) -- end -- self.spirits_movementFactor = 1 -- self.ability.spirits_spiritsSpawned = {} -- EmitSoundOn("Hero_Wisp.Spirits.Cast", self.caster) -- -- Exception for naughty Morphlings... -- if self.caster:HasModifier("modifier_imba_wisp_spirits") then -- self.caster:RemoveModifierByName("modifier_imba_wisp_spirits") -- end -- -- Let's manually add Toggle Spirits for Rubick and Morphling so they can use the skill properly -- if not self.caster:HasAbility("imba_wisp_spirits_toggle") then -- self.caster:AddAbility("imba_wisp_spirits_toggle") -- end -- self.caster:SwapAbilities("imba_wisp_spirits", "imba_wisp_spirits_toggle", false, true ) -- self.caster:FindAbilityByName("imba_wisp_spirits_toggle"):SetLevel(1) -- self.caster:AddNewModifier( -- self.caster, -- self.ability, -- "modifier_imba_wisp_spirits", -- { -- duration = spirit_duration, -- spirits_starttime = GameRules:GetGameTime(), -- spirit_summon_interval = spirit_summon_interval, -- max_spirits = max_spirits, -- collision_radius = collision_radius, -- explosion_radius = explosion_radius, -- spirit_min_radius = spirit_min_radius, -- spirit_max_radius = spirit_max_radius, -- spirit_movement_rate = spirit_movement_rate, -- spirit_turn_rate = spirit_turn_rate, -- vision_radius = vision_radius, -- vision_duration = vision_duration, -- creep_damage = creep_damage, -- explosion_damage = explosion_damage, -- slow_duration = slow_duration, -- slow = slow -- }) -- self.caster:AddNewModifier(self.caster, self.ability, "modifier_imba_wisp_spirit_damage_handler", {duration = -1, damage_interval = damage_interval}) -- end -- end -- -- Remove Toggle Spirits for Rubick and Morphling when skill is lost -- function imba_wisp_spirits:OnUnStolen() -- if self:GetCaster():HasAbility("imba_wisp_spirits_toggle") then -- self:GetCaster():RemoveAbility("imba_wisp_spirits_toggle") -- end -- end -- modifier_imba_wisp_spirit_damage_handler = class({}) -- function modifier_imba_wisp_spirit_damage_handler:IsHidden() return true end -- function modifier_imba_wisp_spirit_damage_handler:IsPurgable() return false end -- function modifier_imba_wisp_spirit_damage_handler:OnCreated(params) -- if IsServer() then -- self.caster = self:GetCaster() -- self.ability = self:GetAbility() -- self:StartIntervalThink(params.damage_interval) -- end -- end -- function modifier_imba_wisp_spirit_damage_handler:OnIntervalThink() -- if IsServer() then -- self.ability.hit_table = {} -- end -- end -- ------------------------------ -- -- SPIRITS modifier -- -- ------------------------------ -- modifier_imba_wisp_spirits = class({}) -- function modifier_imba_wisp_spirits:OnCreated(params) -- if IsServer() then -- self.start_time = params.spirits_starttime -- self.spirit_summon_interval = params.spirit_summon_interval -- self.max_spirits = params.max_spirits -- self.collision_radius = params.collision_radius -- self.explosion_radius = params.explosion_radius -- self.spirit_radius = params.collision_radius -- self.spirit_min_radius = params.spirit_min_radius -- self.spirit_max_radius = params.spirit_max_radius -- self.spirit_movement_rate = params.spirit_movement_rate -- self.spirit_turn_rate = params.spirit_turn_rate -- self.vision_radius = params.vision_radius -- self.vision_duration = params.vision_duration -- self.creep_damage = params.creep_damage -- self.explosion_damage = params.explosion_damage -- self.slow_duration = params.slow_duration -- self.slow = params.slow -- -- timers for tracking update of FX -- self:GetAbility().update_timer = 0 -- self.time_to_update = 0.5 -- EmitSoundOn("Hero_Wisp.Spirits.Loop", self:GetCaster()) -- self:StartIntervalThink(0.03) -- end -- end -- function modifier_imba_wisp_spirits:OnIntervalThink() -- if IsServer() then -- local caster = self:GetCaster() -- local caster_position = caster:GetAbsOrigin() -- local ability = self:GetAbility() -- local elapsedTime = GameRules:GetGameTime() - self.start_time -- local idealNumSpiritsSpawned = elapsedTime / self.spirit_summon_interval -- -- add time to update timer -- ability.update_timer = ability.update_timer + FrameTime() -- idealNumSpiritsSpawned = math.min(idealNumSpiritsSpawned, self.max_spirits) -- if ability.spirits_num_spirits < idealNumSpiritsSpawned then -- -- Spawn a new spirit -- local newSpirit = CreateUnitByName("npc_dota_wisp_spirit", caster_position, false, caster, caster, caster:GetTeam()) -- -- Create particle FX -- local pfx = ParticleManager:CreateParticle(particle, PATTACH_ABSORIGIN_FOLLOW, newSpirit) -- if caster:HasModifier("modifier_imba_wisp_swap_spirits_disarm") then -- local pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_wisp/wisp_guardian_disarm_a.vpcf", PATTACH_ABSORIGIN_FOLLOW, newSpirit) -- newSpirit.spirit_pfx_disarm = pfx -- elseif caster:HasModifier("modifier_imba_wisp_swap_spirits_silence") then -- local pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_wisp/wisp_guardian_silence_a.vpcf", PATTACH_ABSORIGIN_FOLLOW, newSpirit) -- newSpirit.spirit_pfx_silence = pfx -- else -- Just for Rubick...since he's not stealing the silence/disarm skill right now -- local pfx = ParticleManager:CreateParticle(caster.spirits_effect, PATTACH_ABSORIGIN_FOLLOW, newSpirit) -- newSpirit.spirit_pfx_silence = pfx -- end -- if caster:HasTalent("special_bonus_imba_wisp_3") then -- self.true_sight_radius = caster:FindTalentValue("special_bonus_imba_wisp_3", "true_sight_radius") -- local true_sight_aura = newSpirit:AddNewModifier(caster, self, "modifier_imba_wisp_spirits_true_sight", {}) -- true_sight_aura:SetStackCount(self.true_sight_radius) -- newSpirit:SetDayTimeVisionRange(self.true_sight_radius) -- newSpirit:SetNightTimeVisionRange(self.true_sight_radius) -- end -- -- Update the state -- local spiritIndex = ability.spirits_num_spirits + 1 -- newSpirit.spirit_index = spiritIndex -- ability.spirits_num_spirits = spiritIndex -- ability.spirits_spiritsSpawned[spiritIndex] = newSpirit -- -- Apply the spirit modifier -- newSpirit:AddNewModifier( -- caster, -- ability, -- "modifier_imba_wisp_spirit_handler", -- { -- duraiton = -1, -- vision_radius = self.vision_radius, -- vision_duration = self.vision_duration, -- tinkerval = 360 / self.spirit_turn_rate / self.max_spirits, -- collision_radius = self.collision_radius, -- explosion_radius = self.explosion_radius, -- creep_damage = self.creep_damage, -- explosion_damage = self.explosion_damage, -- slow_duration = self.slow_duration, -- slow = self.slow -- } -- ) -- end -- -------------------------------------------------------------------------------- -- -- Update the radius -- -------------------------------------------------------------------------------- -- local currentRadius = self.spirit_radius -- local deltaRadius = ability.spirits_movementFactor * self.spirit_movement_rate * 0.03 -- currentRadius = currentRadius + deltaRadius -- currentRadius = math.min( math.max( currentRadius, self.spirit_min_radius ), self.spirit_max_radius ) -- self.spirit_radius = currentRadius -- -------------------------------------------------------------------------------- -- -- Update the spirits' positions -- -------------------------------------------------------------------------------- -- local currentRotationAngle = elapsedTime * self.spirit_turn_rate -- local rotationAngleOffset = 360 / self.max_spirits -- local numSpiritsAlive = 0 -- for k,spirit in pairs( ability.spirits_spiritsSpawned ) do -- if not spirit:IsNull() then -- numSpiritsAlive = numSpiritsAlive + 1 -- -- Rotate -- local rotationAngle = currentRotationAngle - rotationAngleOffset * (k - 1) -- local relPos = Vector(0, currentRadius, 0) -- relPos = RotatePosition(Vector(0,0,0), QAngle( 0, -rotationAngle, 0 ), relPos) -- local absPos = GetGroundPosition( relPos + caster_position, spirit) -- spirit:SetAbsOrigin(absPos) -- -- Update particle... switch particle depending on currently active effect. -- -- the dealy is needed since it takes 0.3s for spirits to fade in. -- if ability.update_timer > self.time_to_update then -- if caster:HasModifier("modifier_imba_wisp_swap_spirits_disarm") then -- if spirit.spirit_pfx_silence ~= nil then -- ParticleManager:DestroyParticle(spirit.spirit_pfx_silence, true) -- end -- elseif caster:HasModifier("modifier_imba_wisp_swap_spirits_silence") then -- if spirit.spirit_pfx_disarm ~= nil then -- ParticleManager:DestroyParticle(spirit.spirit_pfx_disarm, true) -- end -- end -- end -- if spirit.spirit_pfx_silence ~= nil then -- spirit.currentRadius = Vector(currentRadius, 0, 0) -- ParticleManager:SetParticleControl(spirit.spirit_pfx_silence, 1, Vector(currentRadius, 0, 0)) -- end -- if spirit.spirit_pfx_disarm ~= nil then -- spirit.currentRadius = Vector(currentRadius, 0, 0) -- ParticleManager:SetParticleControl(spirit.spirit_pfx_disarm, 1, Vector(currentRadius, 0, 0)) -- end -- end -- end -- if ability.update_timer > self.time_to_update then -- ability.update_timer = 0 -- end -- if ability.spirits_num_spirits == self.max_spirits and numSpiritsAlive == 0 then -- -- All spirits have been exploded. -- caster:RemoveModifierByName("modifier_imba_wisp_spirits") -- return -- end -- end -- end -- function modifier_imba_wisp_spirits:Explode(caster, spirit, explosion_radius, explosion_damage, ability) -- if IsServer() then -- EmitSoundOn("Hero_Wisp.Spirits.Target", spirit) -- ParticleManager:CreateParticle(caster.spirits_explosion_effect, PATTACH_ABSORIGIN_FOLLOW, spirit) -- -- Check if we hit stuff -- local nearby_enemy_units = FindUnitsInRadius( -- caster:GetTeam(), -- spirit:GetAbsOrigin(), -- nil, -- explosion_radius, -- DOTA_UNIT_TARGET_TEAM_ENEMY, -- DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- DOTA_UNIT_TARGET_FLAG_NONE, -- FIND_ANY_ORDER, -- false -- ) -- local damage_table = {} -- damage_table.attacker = caster -- damage_table.ability = ability -- damage_table.damage_type = ability:GetAbilityDamageType() -- damage_table.damage = explosion_damage -- -- Deal damage to each enemy hero -- for _,enemy in pairs(nearby_enemy_units) do -- if enemy ~= nil then -- damage_table.victim = enemy -- ApplyDamage(damage_table) -- end -- end -- -- Let's just have another one here for Rubick to "properly" destroy Spirit particles -- if spirit_pfx_silence ~= nil then -- ParticleManager:DestroyParticle(spirit.spirit_pfx_silence, true) -- ParticleManager:ReleaseParticleIndex(spirit.spirit_pfx_silence) -- end -- ability.spirits_spiritsSpawned[spirit.spirit_index] = nil -- end -- end -- function modifier_imba_wisp_spirits:OnRemoved() -- if IsServer() then -- self:GetCaster():SwapAbilities("imba_wisp_spirits_toggle", "imba_wisp_spirits", false, true ) -- local ability = self:GetAbility() -- local caster = self:GetCaster() -- for k,spirit in pairs( ability.spirits_spiritsSpawned ) do -- if not spirit:IsNull() then -- spirit:RemoveModifierByName("modifier_imba_wisp_spirit_handler") -- end -- end -- self:GetCaster():StopSound("Hero_Wisp.Spirits.Loop") -- end -- end -- -- not required -- --[[ -- function modifier_imba_wisp_spirits:GetTexture() -- if self:GetAbility().spirits_movementFactor == 1 then -- return "kunnka_tide_red" -- else -- return "kunnka_tide_high" -- end -- end -- --]] -- ---------------------------------------------------------------------- -- -- SPIRITS true_sight modifier -- -- ---------------------------------------------------------------------- -- modifier_imba_wisp_spirits_true_sight = class({}) -- function modifier_imba_wisp_spirits_true_sight:IsAura() -- return true -- end -- function modifier_imba_wisp_spirits_true_sight:IsHidden() -- return true -- end -- function modifier_imba_wisp_spirits_true_sight:IsPurgable() -- return false -- end -- function modifier_imba_wisp_spirits_true_sight:GetAuraRadius() -- return self:GetStackCount() -- end -- function modifier_imba_wisp_spirits_true_sight:GetModifierAura() -- return "modifier_truesight" -- end -- function modifier_imba_wisp_spirits_true_sight:GetAuraSearchTeam() -- return DOTA_UNIT_TARGET_TEAM_ENEMY -- end -- function modifier_imba_wisp_spirits_true_sight:GetAuraSearchFlags() -- return DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES -- end -- function modifier_imba_wisp_spirits_true_sight:GetAuraSearchType() -- return DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_OTHER -- end -- function modifier_imba_wisp_spirits_true_sight:GetAuraDuration() -- return 0.5 -- end -- ---------------------------------------------------------------------- -- -- SPIRITS on creep hit modifier -- -- ---------------------------------------------------------------------- -- modifier_imba_wisp_spirits_creep_hit = class({}) -- function modifier_imba_wisp_spirits_creep_hit:IsHidden() return true end -- function modifier_imba_wisp_spirits_creep_hit:OnCreated() -- if IsServer() then -- local target = self:GetParent() -- EmitSoundOn("Hero_Wisp.Spirits.TargetCreep", target) -- self.pfx = ParticleManager:CreateParticle(self:GetCaster().spirits_explosion_small_effect, PATTACH_ABSORIGIN_FOLLOW, target) -- end -- end -- function modifier_imba_wisp_spirits_creep_hit:OnRemoved() -- if IsServer() then -- ParticleManager:DestroyParticle(self.pfx, false) -- end -- end -- ---------------------------------------------------------------------- -- -- SPIRITS on hero hit modifier -- -- ---------------------------------------------------------------------- -- modifier_imba_wisp_spirits_hero_hit = class({}) -- function modifier_imba_wisp_spirits_hero_hit:IsHidden() return true end -- function modifier_imba_wisp_spirits_hero_hit:OnCreated(params) -- if IsServer() then -- local target = self:GetParent() -- local slow_modifier = target:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_wisp_spirits_slow", {duration = params.slow_duration}) -- slow_modifier:SetStackCount(params.slow) -- end -- end -- ---------------------------------------------------------------------- -- -- SPIRITS on hero hit slow modifier -- -- ---------------------------------------------------------------------- -- modifier_imba_wisp_spirits_slow = class({}) -- function modifier_imba_wisp_spirits_slow:IsDebuff() return true end -- function modifier_imba_wisp_spirits_slow:IsHidden() return true end -- function modifier_imba_wisp_spirits_slow:DeclareFunctions() -- local funcs = {MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE, -- MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT} -- return funcs -- end -- function modifier_imba_wisp_spirits_slow:GetModifierMoveSpeedBonus_Percentage() -- return self:GetStackCount() -- end -- function modifier_imba_wisp_spirits_slow:GetModifierAttackSpeedBonus_Constant() -- return self:GetStackCount() -- end -- ---------------------------------------------------------------------- -- -- SPIRITS modifier (keep them from getting targeted) -- -- ---------------------------------------------------------------------- -- modifier_imba_wisp_spirit_handler = class({}) -- function modifier_imba_wisp_spirit_handler:CheckState() -- local state = { -- [MODIFIER_STATE_NO_TEAM_MOVE_TO] = true, -- [MODIFIER_STATE_NO_TEAM_SELECT] = true, -- [MODIFIER_STATE_COMMAND_RESTRICTED] = true, -- [MODIFIER_STATE_ATTACK_IMMUNE] = true, -- [MODIFIER_STATE_MAGIC_IMMUNE] = true, -- [MODIFIER_STATE_INVULNERABLE] = true, -- [MODIFIER_STATE_UNSELECTABLE] = true, -- [MODIFIER_STATE_NOT_ON_MINIMAP] = true, -- [MODIFIER_STATE_NO_HEALTH_BAR] = true, -- } -- return state -- end -- function modifier_imba_wisp_spirit_handler:OnCreated(params) -- if IsServer() then -- self.caster = self:GetCaster() -- self.ability = self:GetAbility() -- self.vision_radius = params.vision_radius -- self.vision_duration = params.vision_duration -- self.tinkerval = params.tinkerval -- self.collision_radius = params.collision_radius -- self.explosion_radius = params.explosion_radius -- self.creep_damage = params.creep_damage -- self.explosion_damage = params.explosion_damage -- self.slow_duration = params.slow_duration -- self.slow = params.slow -- -- dmg timer and hittable -- self.damage_interval = 0.10 -- self.damage_timer = 0 -- self.ability.hit_table = {} -- self:StartIntervalThink(self.damage_interval) -- end -- end -- function modifier_imba_wisp_spirit_handler:OnIntervalThink() -- if IsServer() then -- local spirit = self:GetParent() -- -- Check if we hit stuff -- local nearby_enemy_units = FindUnitsInRadius( -- self.caster:GetTeam(), -- spirit:GetAbsOrigin(), -- nil, -- self.collision_radius, -- DOTA_UNIT_TARGET_TEAM_ENEMY, -- DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- DOTA_UNIT_TARGET_FLAG_NONE, -- FIND_ANY_ORDER, -- false -- ) -- spirit.hit_table = self.ability.hit_table -- if nearby_enemy_units ~= nil and #nearby_enemy_units > 0 then -- modifier_imba_wisp_spirit_handler:OnHit(self.caster, spirit, nearby_enemy_units, self.creep_damage, self.ability, self.slow_duration, self.slow) -- end -- end -- end -- function modifier_imba_wisp_spirit_handler:OnHit(caster, spirit, enemies_hit, creep_damage, ability, slow_duration, slow) -- local hit_hero = false -- -- Initialize damage table -- local damage_table = {} -- damage_table.attacker = caster -- damage_table.ability = ability -- damage_table.damage_type = ability:GetAbilityDamageType() -- -- Deal damage to each enemy hero -- for _,enemy in pairs(enemies_hit) do -- -- cant dmg ded stuff + cant dmg if ded -- if enemy:IsAlive() and not spirit:IsNull() then -- local hit = false -- damage_table.victim = enemy -- if enemy:IsConsideredHero() and not enemy:IsIllusion() then -- enemy:AddNewModifier(caster, ability, "modifier_imba_wisp_spirits_hero_hit", {duration = 0.03, slow_duration = slow_duration, slow = slow}) -- if caster:HasModifier("modifier_imba_wisp_swap_spirits_disarm") then -- enemy:AddNewModifier(caster, ability, "modifier_disarmed", {duration=ability:GetSpecialValueFor("spirit_debuff_duration")}):SetDuration(ability:GetSpecialValueFor("spirit_debuff_duration") * (1 - enemy:GetStatusResistance()), true) -- elseif caster:HasModifier("modifier_imba_wisp_swap_spirits_silence") then -- enemy:AddNewModifier(caster, ability, "modifier_silence", {duration=ability:GetSpecialValueFor("spirit_debuff_duration")}):SetDuration(ability:GetSpecialValueFor("spirit_debuff_duration") * (1 - enemy:GetStatusResistance()), true) -- end -- hit_hero = true -- --hit = true -- else -- if spirit.hit_table[enemy] == nil then -- spirit.hit_table[enemy] = true -- enemy:AddNewModifier(caster, ability, "modifier_imba_wisp_spirits_creep_hit", {duration = 0.03}) -- damage_table.damage = creep_damage -- hit = true -- end -- end -- if hit then -- ApplyDamage(damage_table) -- end -- end -- end -- if hit_hero then -- spirit:RemoveModifierByName("modifier_imba_wisp_spirit_handler") -- end -- end -- function modifier_imba_wisp_spirit_handler:OnRemoved() -- if IsServer() then -- local spirit = self:GetParent() -- local ability = self:GetAbility() -- modifier_imba_wisp_spirits:Explode(self.caster, spirit, self.explosion_radius, self.explosion_damage, ability) -- if spirit.spirit_pfx_silence ~= nil then -- ParticleManager:DestroyParticle(spirit.spirit_pfx_silence, true) -- end -- if spirit.spirit_pfx_disarm ~= nil then -- ParticleManager:DestroyParticle(spirit.spirit_pfx_disarm, true) -- end -- -- Create vision -- ability:CreateVisibilityNode(spirit:GetAbsOrigin(), self.vision_radius, self.vision_duration) -- -- Kill -- spirit:ForceKill( true ) -- end -- end -- -------------------------------------- -- -- SPIRITS TOGGLE Near/Far -- -- -------------------------------------- -- imba_wisp_spirits_toggle = class({}) -- function imba_wisp_spirits_toggle:GetAbilityTextureName() -- if not IsClient() then return end -- if not self:GetCaster().arcana_style then return "wisp_spirits_in" end -- return "imba_wisp_spirits_in_arcana" -- end -- function imba_wisp_spirits_toggle:IsStealable() return false end -- function imba_wisp_spirits_toggle:OnSpellStart() -- if IsServer() then -- -- Let's manually add Spirits for Morphling so they can use the skill properly (super bootleg) -- if not self:GetCaster():HasAbility("imba_wisp_spirits") then -- local stolenAbility = self:GetCaster():AddAbility("imba_wisp_spirits") -- stolenAbility:SetLevel(min((self:GetCaster():GetLevel() / 2) - 1, 4)) -- self:GetCaster():SwapAbilities("imba_wisp_spirits_toggle", "imba_wisp_spirits", false, true) -- end -- local caster = self:GetCaster() -- local ability = caster:FindAbilityByName("imba_wisp_spirits") -- local spirits_movementFactor = ability.spirits_movementFactor -- if ability.spirits_movementFactor == 1 then -- ability.spirits_movementFactor = -1 -- else -- ability.spirits_movementFactor = 1 -- end -- end -- end -- -- ugh -- function imba_wisp_spirits_toggle:OnUnStolen() -- if self:GetCaster():HasAbility("imba_wisp_spirits") then -- self:GetCaster():RemoveAbility("imba_wisp_spirits") -- end -- end -- ------------------------------------------ -- -- SPIRITS Swap silence/disarm -- -- ------------------------------------------ -- LinkLuaModifier("modifier_imba_wisp_swap_spirits_disarm", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_swap_spirits_silence", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- imba_wisp_swap_spirits = class({}) -- function imba_wisp_swap_spirits:IsInnateAbility() return true end -- function imba_wisp_swap_spirits:IsStealable() return false end -- function imba_wisp_swap_spirits:GetIntrinsicModifierName() -- return "modifier_imba_wisp_swap_spirits_silence" -- end -- function imba_wisp_swap_spirits:GetIntrinsicModifierName() -- return "modifier_imba_wisp_swap_spirits_silence" -- end -- function imba_wisp_swap_spirits:GetAbilityTextureName() -- if self:GetCaster():HasModifier("modifier_imba_wisp_swap_spirits_silence") then -- return "wisp_swap_spirits_silence" -- elseif self:GetCaster():HasModifier("modifier_imba_wisp_swap_spirits_disarm") then -- return "wisp_swap_spirits_disarm" -- end -- end -- function imba_wisp_swap_spirits:OnSpellStart() -- if IsServer() then -- local caster = self:GetCaster() -- local ability = caster:FindAbilityByName("imba_wisp_spirits") -- --local spirits_movementFactor = ability.spirits_movementFactor -- local particle = nil -- local silence = false -- local disarm = false -- if not self.particles then -- self.particles = {} -- end -- if caster:HasModifier("modifier_imba_wisp_swap_spirits_disarm") then -- caster:RemoveModifierByName("modifier_imba_wisp_swap_spirits_disarm") -- caster:AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_swap_spirits_silence", {}) -- elseif caster:HasModifier("modifier_imba_wisp_swap_spirits_silence") then -- caster:RemoveModifierByName("modifier_imba_wisp_swap_spirits_silence") -- caster:AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_swap_spirits_disarm", {}) -- end -- if caster:HasModifier("modifier_imba_wisp_swap_spirits_silence") then -- particle = "particles/units/heroes/hero_wisp/wisp_guardian_silence_a.vpcf" -- silence = true -- disarm = false -- elseif caster:HasModifier("modifier_imba_wisp_swap_spirits_disarm") then -- particle = "particles/units/heroes/hero_wisp/wisp_guardian_disarm_a.vpcf" -- silence = false -- disarm = true -- end -- if ability.spirits_spiritsSpawned then -- for k,spirit in pairs( ability.spirits_spiritsSpawned ) do -- if not spirit:IsNull() then -- if self.particles[k] then -- ParticleManager:DestroyParticle(self.particles[k], false) -- ParticleManager:ReleaseParticleIndex(self.particles[k]) -- end -- self.particles[k] = ParticleManager:CreateParticle(particle, PATTACH_ABSORIGIN_FOLLOW, spirit) -- if silence then -- spirit.spirit_pfx_silence = self.particles[k] -- elseif disarm then -- spirit.spirit_pfx_disarm = self.particles[k] -- end -- end -- end -- end -- end -- end -- modifier_imba_wisp_swap_spirits_disarm = class({}) -- function modifier_imba_wisp_swap_spirits_disarm:IsHidden() return true end -- function modifier_imba_wisp_swap_spirits_disarm:IsPurgable() return false end -- function modifier_imba_wisp_swap_spirits_disarm:RemoveOnDeath() return false end -- modifier_imba_wisp_swap_spirits_silence = class({}) -- function modifier_imba_wisp_swap_spirits_silence:IsHidden() return true end -- function modifier_imba_wisp_swap_spirits_silence:IsPurgable() return false end -- function modifier_imba_wisp_swap_spirits_silence:RemoveOnDeath() return false end -- ------------------------------ -- -- OVERCHARGE -- -- ------------------------------ -- imba_wisp_overcharge = class({}) -- LinkLuaModifier("modifier_imba_wisp_overcharge", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_overcharge_drain", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_overcharge_regen_talent", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_overcharge_aura", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- function imba_wisp_overcharge:GetAbilityTextureName() -- if not IsClient() then return end -- if not self:GetCaster().arcana_style then return "wisp_overcharge" end -- return "imba_wisp_overcharge_arcana" -- end -- function imba_wisp_overcharge:IsNetherWardStealable() -- return false -- end -- function imba_wisp_overcharge:AddOvercharge(caster, target, efficiency, overcharge_duration) -- local ability = caster:FindAbilityByName("imba_wisp_overcharge") -- local tether_ability = caster:FindAbilityByName("imba_wisp_tether") -- local bonus_attack_speed = ability:GetSpecialValueFor("bonus_attack_speed") -- local bonus_cast_speed = ability:GetSpecialValueFor("bonus_cast_speed") -- local bonus_missile_speed = ability:GetSpecialValueFor("bonus_missile_speed") -- local bonus_damage_pct = ability:GetSpecialValueFor("bonus_damage_pct") -- local bonus_attack_range = ability:GetSpecialValueFor("bonus_attack_range") -- if caster:HasTalent("special_bonus_imba_wisp_1") then -- local bonus_effect = caster:FindTalentValue("special_bonus_imba_wisp_1") -- bonus_attack_speed = bonus_attack_speed + bonus_effect -- bonus_cast_speed = bonus_cast_speed -- bonus_missile_speed = bonus_missile_speed + bonus_effect -- bonus_attack_range = bonus_attack_range + bonus_effect -- end -- if caster:HasTalent("special_bonus_imba_wisp_4") then -- local damage_reduction = caster:FindTalentValue("special_bonus_imba_wisp_4") -- bonus_damage_pct = bonus_damage_pct - damage_reduction -- end -- if caster:HasTalent("special_bonus_imba_wisp_8") and efficiency == 1.0 then -- local bonus_regen = caster:FindTalentValue("special_bonus_imba_wisp_8", "bonus_regen") -- local overcharge_regen = caster:AddNewModifier(caster, ability, "modifier_imba_wisp_overcharge_regen_talent", {}) -- overcharge_regen:SetStackCount(bonus_regen) -- end -- if efficiency ~= nil and efficiency < 1.0 then -- bonus_attack_speed = bonus_attack_speed * efficiency -- bonus_cast_speed = bonus_cast_speed * efficiency -- bonus_missile_speed = bonus_missile_speed * efficiency -- bonus_attack_range = bonus_attack_range * efficiency -- bonus_damage_pct = bonus_damage_pct * efficiency -- end -- -- set stats for client -- CustomNetTables:SetTableValue( -- "player_table", -- tostring(caster:GetPlayerOwnerID()), -- { -- overcharge_bonus_attack_speed = bonus_attack_speed, -- overcharge_bonus_cast_speed = bonus_cast_speed, -- overcharge_bonus_missile_speed = bonus_missile_speed, -- overcharge_bonus_damage_pct = bonus_damage_pct, -- overcharge_bonus_attack_range = bonus_attack_range, -- }) -- target:AddNewModifier( -- caster, -- ability, -- "modifier_imba_wisp_overcharge", -- { -- duration = overcharge_duration, -- bonus_attack_speed = bonus_attack_speed, -- bonus_cast_speed = bonus_cast_speed, -- bonus_missile_speed = bonus_missile_speed, -- bonus_damage_pct = bonus_damage_pct, -- bonus_attack_range = bonus_attack_range, -- }) -- end -- function imba_wisp_overcharge:OnToggle() -- if IsServer() then -- local caster = self:GetCaster() -- local ability = caster:FindAbilityByName("imba_wisp_overcharge") -- local tether_ability = caster:FindAbilityByName("imba_wisp_tether") -- if ability:GetToggleState() then -- EmitSoundOn("Hero_Wisp.Overcharge", caster) -- local drain_interval = ability:GetSpecialValueFor("drain_interval") -- local drain_pct = ability:GetSpecialValueFor("drain_pct") -- imba_wisp_overcharge:AddOvercharge(caster, caster, 1.0, -1) -- if caster:HasModifier("modifier_imba_wisp_tether") then -- if tether_ability.target:HasModifier("modifier_imba_wisp_overcharge") then -- tether_ability.target:RemoveModifierByName("modifier_imba_wisp_overcharge") -- end -- imba_wisp_overcharge:AddOvercharge(caster, tether_ability.target, 1.0, -1) -- end -- if caster:HasScepter() then -- caster:AddNewModifier(caster, ability, "modifier_imba_wisp_overcharge_aura", {}) -- end -- drain_pct = drain_pct / 100 -- caster:AddNewModifier( caster, ability, "modifier_imba_wisp_overcharge_drain", { duration = -1, drain_interval = drain_interval, drain_pct = drain_pct }) -- else -- caster:StopSound("Hero_Wisp.Overcharge") -- caster:RemoveModifierByName("modifier_imba_wisp_overcharge") -- caster:RemoveModifierByName("modifier_imba_wisp_overcharge_drain") -- caster:RemoveModifierByName("modifier_imba_wisp_overcharge_regen_talent") -- caster:RemoveModifierByName("modifier_imba_wisp_overcharge_aura") -- if caster:HasModifier("modifier_imba_wisp_tether") then -- tether_ability.target:RemoveModifierByName("modifier_imba_wisp_overcharge") -- tether_ability.target:RemoveModifierByName("modifier_imba_wisp_overcharge_regen_talent") -- end -- end -- end -- end -- ---------------------------------- -- -- Overchargge Aura modifier -- -- ---------------------------------- -- modifier_imba_wisp_overcharge_aura = class({}) -- function modifier_imba_wisp_overcharge_aura:IsHidden() return false end -- function modifier_imba_wisp_overcharge_aura:IsPurgable() return false end -- function modifier_imba_wisp_overcharge_aura:IsNetherWardStealable() -- return false -- end -- function modifier_imba_wisp_overcharge_aura:OnCreated() -- if IsServer() then -- self.ability = self:GetAbility() -- self.tether_ability = self:GetCaster():FindAbilityByName("imba_wisp_tether") -- self.scepter_radius = self.ability:GetSpecialValueFor("scepter_radius") -- self.scepter_efficiency = self.ability:GetSpecialValueFor("scepter_efficiency") -- self:StartIntervalThink(0.1) -- end -- end -- function modifier_imba_wisp_overcharge_aura:OnIntervalThink() -- if IsServer() then -- local caster = self:GetCaster() -- local nearby_friendly_units = FindUnitsInRadius( -- caster:GetTeam(), -- caster:GetAbsOrigin(), -- nil, -- self.scepter_radius, -- DOTA_UNIT_TARGET_TEAM_FRIENDLY, -- DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- DOTA_UNIT_TARGET_FLAG_NOT_ANCIENTS, -- FIND_ANY_ORDER, -- false) -- for _,unit in pairs(nearby_friendly_units) do -- if unit ~= caster and unit ~= self.tether_ability.target and unit ~= "npc_dota_hero" then -- imba_wisp_overcharge:AddOvercharge(caster, unit, self.scepter_efficiency, 1) -- end -- end -- end -- end -- ---------------------------------- -- -- Overchargge buff modifier -- -- ---------------------------------- -- modifier_imba_wisp_overcharge = class({}) -- function modifier_imba_wisp_overcharge:IsBuff() return true end -- function modifier_imba_wisp_overcharge:IsPurgable() return false end -- function modifier_imba_wisp_overcharge:IsNetherWardStealable() return false end -- function modifier_imba_wisp_overcharge:DeclareFunctions() -- local funcs = { -- MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT, -- MODIFIER_PROPERTY_CASTTIME_PERCENTAGE, -- MODIFIER_PROPERTY_PROJECTILE_SPEED_BONUS, -- MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE, -- -- MODIFIER_PROPERTY_ATTACK_RANGE_BONUS, -- } -- return funcs -- end -- function modifier_imba_wisp_overcharge:OnCreated(params) -- if IsServer() then -- self.overcharge_pfx = ParticleManager:CreateParticle(self:GetCaster().overcharge_effect, PATTACH_ABSORIGIN_FOLLOW, self:GetParent()) -- self.bonus_attack_speed = params.bonus_attack_speed -- self.bonus_cast_speed = params.bonus_cast_speed -- self.bonus_missile_speed = params.bonus_missile_speed -- self.bonus_damage_pct = params.bonus_damage_pct -- self.bonus_attack_range = params.bonus_attack_range -- else -- local net_table = CustomNetTables:GetTableValue("player_table", tostring(self:GetCaster():GetPlayerOwnerID())) or {} -- self.bonus_attack_speed = net_table.overcharge_bonus_attack_speed or 0 -- self.bonus_cast_speed = net_table.overcharge_bonus_cast_speed or 0 -- self.bonus_missile_speed = net_table.overcharge_bonus_missile_speed or 0 -- self.bonus_damage_pct = net_table.overcharge_bonus_damage_pct or 0 -- self.bonus_attack_range = net_table.overcharge_bonus_attack_range or 0 -- end -- end -- function modifier_imba_wisp_overcharge:OnRemoved() -- if IsServer() then -- ParticleManager:DestroyParticle(self.overcharge_pfx, false) -- if not self:GetCaster():HasModifier("modifier_imba_wisp_overcharge") then -- self:GetCaster():RemoveModifierByName("modifier_imba_wisp_overcharge_drain") -- end -- end -- end -- function modifier_imba_wisp_overcharge:GetModifierAttackSpeedBonus_Constant() -- return self.bonus_attack_speed -- end -- function modifier_imba_wisp_overcharge:GetModifierPercentageCasttime() -- return self.bonus_cast_speed -- end -- function modifier_imba_wisp_overcharge:GetModifierProjectileSpeedBonus() -- return self.bonus_missile_speed -- end -- function modifier_imba_wisp_overcharge:GetModifierIncomingDamage_Percentage() -- return self.bonus_damage_pct -- end -- -- function modifier_imba_wisp_overcharge:GetModifierAttackRangeBonus() -- -- return self.bonus_attack_range -- -- end -- ---------------------------------------------- -- -- Overchargge health/mana-drain modifier -- -- ---------------------------------------------- -- modifier_imba_wisp_overcharge_drain = class({}) -- function modifier_imba_wisp_overcharge_drain:IsHidden() return true end -- function modifier_imba_wisp_overcharge_drain:IsPurgable() return false end -- function modifier_imba_wisp_overcharge_drain:OnCreated(params) -- if IsServer() then -- self.caster = self:GetCaster() -- self.ability = self:GetAbility() -- self.drain_pct = params.drain_pct -- self.drain_interval = params.drain_interval -- self.deltaDrainPct = self.drain_interval * self.drain_pct -- self:StartIntervalThink(self.drain_interval) -- end -- end -- function modifier_imba_wisp_overcharge_drain:OnIntervalThink() -- -- hp removal instead of self dmg... this wont break urn or salve -- local current_health = self.caster:GetHealth() -- local health_drain = current_health * self.deltaDrainPct -- self.caster:ModifyHealth(current_health - health_drain, self.ability, true, 0) -- self.caster:SpendMana(self.caster:GetMana() * self.deltaDrainPct, self.ability) -- end -- ------------------------------ -- -- Overcharge Talent -- -- ------------------------------ -- modifier_imba_wisp_overcharge_regen_talent = class({}) -- function modifier_imba_wisp_overcharge_regen_talent:IsHidden() return true end -- function modifier_imba_wisp_overcharge_regen_talent:IsPurgable() return false end -- function modifier_imba_wisp_overcharge_regen_talent:DeclareFunctions() -- local decFuncs = { -- MODIFIER_PROPERTY_MANA_REGEN_TOTAL_PERCENTAGE -- } -- return decFuncs -- end -- function modifier_imba_wisp_overcharge_regen_talent:GetModifierTotalPercentageManaRegen() -- return self:GetStackCount() -- end -- ------------------------------ -- -- RELOCATE -- -- ------------------------------ -- imba_wisp_relocate = class({}) -- LinkLuaModifier("modifier_imba_wisp_relocate", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_relocate_cast_delay", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_relocate_talent", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- function imba_wisp_relocate:GetAbilityTextureName() -- if not IsClient() then return end -- if not self:GetCaster().arcana_style then return "wisp_relocate" end -- return "imba_wisp_relocate_arcana" -- end -- function imba_wisp_relocate:GetCooldown(level) -- return self.BaseClass.GetCooldown(self, level) - self:GetCaster():FindTalentValue("special_bonus_imba_wisp_9") -- end -- function imba_wisp_relocate:GetBehavior() -- if IsServer() then -- return DOTA_ABILITY_BEHAVIOR_UNIT_TARGET + DOTA_ABILITY_BEHAVIOR_OPTIONAL_POINT -- else -- return DOTA_ABILITY_BEHAVIOR_POINT + DOTA_ABILITY_BEHAVIOR_OPTIONAL_UNIT_TARGET -- end -- end -- function imba_wisp_relocate:OnSpellStart() -- if IsServer() then -- local unit = self:GetCursorTarget() -- local tether_ability = self:GetCaster():FindAbilityByName("imba_wisp_tether") -- self.relocate_target_point = self:GetCursorPosition() -- local vision_radius = self:GetSpecialValueFor("vision_radius") -- local cast_delay = self:GetSpecialValueFor("cast_delay") -- local return_time = self:GetSpecialValueFor("return_time") -- local destroy_tree_radius = self:GetSpecialValueFor("destroy_tree_radius") -- EmitSoundOn(self:GetCaster().relocate_sound, self:GetCaster()) -- if unit == self:GetCaster() then -- if self:GetCaster():GetTeam() == DOTA_TEAM_GOODGUYS then -- -- radiant fountain location -- self.relocate_target_point = Vector(-7168, -6646, 528) -- else -- -- dire fountain location -- self.relocate_target_point = Vector(7037, 6458, 512) -- end -- end -- local channel_pfx = ParticleManager:CreateParticle(self:GetCaster().relocate_channel_effect, PATTACH_ABSORIGIN_FOLLOW, self:GetCaster()) -- ParticleManager:SetParticleControl(channel_pfx, 0, self:GetCaster():GetAbsOrigin()) -- local endpoint_pfx = ParticleManager:CreateParticle(self:GetCaster().relocate_marker_endpoint_effect, PATTACH_WORLDORIGIN, self:GetCaster()) -- ParticleManager:SetParticleControl(endpoint_pfx, 0, self.relocate_target_point) -- -- Create vision -- self:CreateVisibilityNode(self.relocate_target_point, vision_radius, cast_delay) -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_7") then -- local immunity_duration = self:GetCaster():FindTalentValue("special_bonus_imba_wisp_7", "duration") -- self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_relocate_talent", {duration = immunity_duration}) -- if tether_ability.target ~= nil then -- tether_ability.target:AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_relocate_talent", {duration = immunity_duration}) -- end -- end -- self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_relocate_cast_delay", {duration = cast_delay}) -- Timers:CreateTimer({ -- endTime = cast_delay, -- callback = function() -- ParticleManager:DestroyParticle(channel_pfx, false) -- ParticleManager:DestroyParticle(endpoint_pfx, false) -- if not imba_wisp_relocate:InterruptRelocate(self:GetCaster(), self, tether_ability) then -- EmitSoundOn(self:GetCaster().relocate_return_in_sound, self:GetCaster()) -- EmitSoundOn("Hero_Wisp.ReturnCounter", self:GetCaster()) -- GridNav:DestroyTreesAroundPoint(self.relocate_target_point, destroy_tree_radius, false) -- -- Here we go again (Rubick) -- if not self:GetCaster():HasAbility("imba_wisp_relocate_break") then -- self:GetCaster():AddAbility("imba_wisp_relocate_break") -- end -- self:GetCaster():SwapAbilities("imba_wisp_relocate", "imba_wisp_relocate_break", false, true) -- local break_ability = self:GetCaster():FindAbilityByName("imba_wisp_relocate_break") -- break_ability:SetLevel(1) -- if self:GetCaster():HasModifier("modifier_imba_wisp_tether") and tether_ability.target:IsHero() then -- self.ally = tether_ability.target -- else -- self.ally = nil -- end -- self:GetCaster():AddNewModifier( self:GetCaster(), self, "modifier_imba_wisp_relocate", { duration = return_time, return_time = return_time }) -- end -- end -- }) -- end -- end -- function imba_wisp_relocate:InterruptRelocate(caster, ability, tether_ability) -- if not caster:IsAlive() or caster:IsStunned() or caster:IsHexed() or caster:IsNightmared() or caster:IsOutOfGame() or caster:IsRooted() then -- return true -- end -- return false -- end -- -- Remove Relocate Break for Rubick when skill is lost -- function imba_wisp_relocate:OnUnStolen() -- if self:GetCaster():HasAbility("imba_wisp_relocate_break") then -- self:GetCaster():RemoveAbility("imba_wisp_relocate_break") -- end -- end -- ---------------------- -- -- Relocate timer -- -- ---------------------- -- modifier_imba_wisp_relocate_cast_delay = class({}) -- -------------------------- -- -- Relocate modifier -- -- -------------------------- -- modifier_imba_wisp_relocate = class({}) -- function modifier_imba_wisp_relocate:IsDebuff() return false end -- function modifier_imba_wisp_relocate:IsHidden() return false end -- function modifier_imba_wisp_relocate:IsPurgable() return false end -- function modifier_imba_wisp_relocate:IsStunDebuff() return false end -- function modifier_imba_wisp_relocate:IsPurgeException() return false end -- function modifier_imba_wisp_relocate:OnCreated(params) -- if IsServer() then -- local caster = self:GetCaster() -- local ability = self:GetAbility() -- local ally = ability.ally -- self.return_time = params.return_time -- self.return_point = self:GetCaster():GetAbsOrigin() -- self.eject_cooldown_mult = self:GetAbility():GetSpecialValueFor("eject_cooldown_mult") -- -- Create marker at origin -- self.caster_origin_pfx = ParticleManager:CreateParticle(caster.relocate_marker_effect, PATTACH_WORLDORIGIN, caster) -- ParticleManager:SetParticleControl(self.caster_origin_pfx, 0, caster:GetAbsOrigin()) -- -- Add teleport effect -- local caster_teleport_pfx = ParticleManager:CreateParticle(caster.relocate_teleport_effect, PATTACH_CUSTOMORIGIN, caster) -- ParticleManager:SetParticleControl(caster_teleport_pfx, 0, caster:GetAbsOrigin()) -- -- Move units -- FindClearSpaceForUnit(caster, ability.relocate_target_point, true) -- caster:Interrupt() -- if caster:HasModifier("modifier_imba_wisp_tether") and ally ~= nil and ally:IsHero() then -- self.ally_teleport_pfx = ParticleManager:CreateParticle(caster.relocate_teleport_effect, PATTACH_CUSTOMORIGIN, ally) -- ParticleManager:SetParticleControl(self.ally_teleport_pfx, 0, ally:GetAbsOrigin()) -- FindClearSpaceForUnit(ally, ability.relocate_target_point + Vector( 100, 0, 0 ), true) -- ally:Interrupt() -- end -- self.timer_buff = ParticleManager:CreateParticle(caster.relocate_timer_buff, PATTACH_ABSORIGIN_FOLLOW, caster) -- ParticleManager:SetParticleControlEnt(self.timer_buff, 0, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), true) -- ParticleManager:SetParticleControlEnt(self.timer_buff, 1, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), true) -- self.relocate_timerPfx = ParticleManager:CreateParticle("particles/units/heroes/hero_wisp/wisp_relocate_timer.vpcf", PATTACH_OVERHEAD_FOLLOW, caster) -- local timerCP1_x = self.return_time >= 10 and 1 or 0 -- local timerCP1_y = self.return_time % 10 -- ParticleManager:SetParticleControl(self.relocate_timerPfx, 1, Vector( timerCP1_x, timerCP1_y, 0 ) ) -- self:StartIntervalThink(1.0) -- end -- end -- function modifier_imba_wisp_relocate:OnIntervalThink() -- self.return_time = self.return_time - 1 -- local timerCP1_x = self.return_time >= 10 and 1 or 0 -- local timerCP1_y = self.return_time % 10 -- ParticleManager:SetParticleControl(self.relocate_timerPfx, 1, Vector( timerCP1_x, timerCP1_y, 0 ) ) -- end -- function modifier_imba_wisp_relocate:OnRemoved() -- if IsServer() then -- EmitSoundOn(self:GetCaster().relocate_return_out_sound, self:GetCaster()) -- StopSoundOn("Hero_Wisp.ReturnCounter", self:GetCaster()) -- -- Add teleport effect -- local caster_teleport_pfx = ParticleManager:CreateParticle(self:GetCaster().relocate_teleport_effect, PATTACH_CUSTOMORIGIN, self:GetCaster()) -- ParticleManager:SetParticleControl(caster_teleport_pfx, 0, self:GetCaster():GetAbsOrigin()) -- -- remove origin marker + delay timer -- ParticleManager:DestroyParticle(self.relocate_timerPfx, false) -- ParticleManager:DestroyParticle(self.caster_origin_pfx, false) -- ParticleManager:DestroyParticle(self.timer_buff, false) -- self:GetCaster():SetAbsOrigin(self.return_point) -- self:GetCaster():Interrupt() -- local tether_ability = self:GetCaster():FindAbilityByName("imba_wisp_tether") -- if self:GetCaster():HasModifier("modifier_imba_wisp_tether") and tether_ability.target ~= nil and tether_ability.target:IsHero() and self:GetCaster():IsAlive() then -- self.ally_teleport_pfx = ParticleManager:CreateParticle(self:GetCaster().relocate_teleport_effect, PATTACH_CUSTOMORIGIN, tether_ability.target) -- ParticleManager:SetParticleControlEnt(self.ally_teleport_pfx, 0, tether_ability.target, PATTACH_POINT, "attach_hitloc", tether_ability.target:GetAbsOrigin(), true) -- tether_ability.target:SetAbsOrigin(self.return_point + Vector( 100, 0, 0 ) ) -- tether_ability.target:Interrupt() -- end -- self:GetCaster():SwapAbilities("imba_wisp_relocate_break", "imba_wisp_relocate", false, true) -- if self:GetRemainingTime() >= 0 then -- local relocate_ability = self:GetCaster():FindAbilityByName("imba_wisp_relocate") -- relocate_ability:StartCooldown(relocate_ability:GetCooldownTimeRemaining() + (self:GetRemainingTime() * self.eject_cooldown_mult)) -- end -- end -- end -- modifier_imba_wisp_relocate_talent = class({}) -- function modifier_imba_wisp_relocate_talent:IsDebuff() return false end -- function modifier_imba_wisp_relocate_talent:IsHidden() return false end -- function modifier_imba_wisp_relocate_talent:IsPurgable() return false end -- function modifier_imba_wisp_relocate_talent:IsStunDebuff() return false end -- function modifier_imba_wisp_relocate_talent:IsPurgeException() return false end -- function modifier_imba_wisp_relocate_talent:RemoveOnDeath() return true end -- function modifier_imba_wisp_relocate_talent:CheckState() -- local state = {[MODIFIER_STATE_MAGIC_IMMUNE] = true} -- return state -- end -- function modifier_imba_wisp_relocate_talent:GetEffectName() -- return "particles/item/black_queen_cape/black_king_bar_avatar.vpcf" -- end -- function modifier_imba_wisp_relocate_talent:GetEffectAttachType() -- return PATTACH_ABSORIGIN_FOLLOW -- end -- ------------------------------ -- -- RELOCATE BREAK -- -- ------------------------------ -- imba_wisp_relocate_break = class({}) -- function imba_wisp_relocate_break:IsStealable() return false end -- function imba_wisp_relocate_break:OnSpellStart() -- if IsServer() then -- local caster = self:GetCaster() -- caster:RemoveModifierByName("modifier_imba_wisp_relocate") -- end -- end -- ------------------------------- -- -- OVERCHARGE (7.21 VERSION) -- -- ------------------------------- -- LinkLuaModifier("modifier_imba_wisp_overcharge_721", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_overcharge_721_aura", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_imba_wisp_overcharge_721_handler", "components/abilities/heroes/hero_wisp.lua", LUA_MODIFIER_MOTION_NONE) -- imba_wisp_overcharge_721 = class({}) -- modifier_imba_wisp_overcharge_721 = class({}) -- modifier_imba_wisp_overcharge_721_aura = class({}) -- modifier_imba_wisp_overcharge_721_handler = class({}) -- function imba_wisp_overcharge_721:GetBehavior() -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_12") then -- if self:GetCaster():GetModifierStackCount("modifier_imba_wisp_overcharge_721_handler", self:GetCaster()) == 0 then -- return DOTA_ABILITY_BEHAVIOR_NO_TARGET + DOTA_ABILITY_BEHAVIOR_TOGGLE + DOTA_ABILITY_BEHAVIOR_AUTOCAST -- else -- return DOTA_ABILITY_BEHAVIOR_NO_TARGET + DOTA_ABILITY_BEHAVIOR_IMMEDIATE + DOTA_ABILITY_BEHAVIOR_AUTOCAST -- end -- else -- return DOTA_ABILITY_BEHAVIOR_NO_TARGET + DOTA_ABILITY_BEHAVIOR_IMMEDIATE -- end -- end -- function imba_wisp_overcharge_721:GetCooldown(level) -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_12") then -- if self:GetCaster():GetModifierStackCount("modifier_imba_wisp_overcharge_721_handler", self:GetCaster()) == 0 then -- return self:GetSpecialValueFor("talent_cooldown") -- else -- return self.BaseClass.GetCooldown(self, level) -- end -- else -- return self.BaseClass.GetCooldown(self, level) -- end -- end -- function imba_wisp_overcharge_721:GetIntrinsicModifierName() -- return "modifier_imba_wisp_overcharge_721_handler" -- end -- function imba_wisp_overcharge_721:GetAbilityTextureName() -- if not IsClient() then return end -- if not self:GetCaster().arcana_style then return "wisp_overcharge" end -- return "imba_wisp_overcharge_arcana" -- end -- function imba_wisp_overcharge_721:OnSpellStart() -- if not IsServer() then return end -- self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_overcharge_721", {duration = self:GetSpecialValueFor("duration")}) -- end -- function imba_wisp_overcharge_721:OnToggle() -- if not IsServer() then return end -- if self:GetToggleState() then -- self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_wisp_overcharge_721", {}) -- else -- self:GetCaster():RemoveModifierByNameAndCaster("modifier_imba_wisp_overcharge_721", self:GetCaster()) -- end -- end -- ---------------------------------------- -- -- OVERCHARGE MODIFIER (7.21 VERSION) -- -- ---------------------------------------- -- function modifier_imba_wisp_overcharge_721:IsPurgable() return false end -- function modifier_imba_wisp_overcharge_721:GetEffectName() -- return self:GetParent().overcharge_effect -- end -- function modifier_imba_wisp_overcharge_721:OnCreated() -- self.ability = self:GetAbility() -- self.caster = self:GetCaster() -- self.parent = self:GetParent() -- -- AbilitySpecials -- self.bonus_attack_speed = self.ability:GetSpecialValueFor("bonus_attack_speed") -- self.bonus_damage_pct = self.ability:GetSpecialValueFor("bonus_damage_pct") - self.caster:FindTalentValue("special_bonus_imba_wisp_4") -- self.hp_regen = self.ability:GetSpecialValueFor("hp_regen") -- self.bonus_missile_speed = self.ability:GetSpecialValueFor("bonus_missile_speed") -- self.bonus_cast_speed = self.ability:GetSpecialValueFor("bonus_cast_speed") -- self.bonus_attack_range = self.ability:GetSpecialValueFor("bonus_attack_range") -- self.talent_drain_interval = self.ability:GetSpecialValueFor("talent_drain_interval") -- self.talent_drain_pct = self.ability:GetSpecialValueFor("talent_drain_pct") -- if not IsServer() then return end -- self:GetParent():EmitSound("Hero_Wisp.Overcharge") -- local tether_ability = self:GetCaster():FindAbilityByName("imba_wisp_tether") -- if tether_ability and tether_ability.target and not tether_ability.target:HasModifier("modifier_imba_wisp_overcharge_721") then -- tether_ability.target:AddNewModifier(self.caster, self.ability, "modifier_imba_wisp_overcharge_721", {}) -- end -- if self.caster == self.parent and self.ability:GetToggleState() then -- if not self.ability:GetAutoCastState() then -- self:SetDuration(-1, true) -- self:StartIntervalThink(self.talent_drain_interval) -- else -- -- Toggle off the ability and re-cast with the proper default logic -- self.ability:ToggleAbility() -- self:StartIntervalThink(-1) -- self.ability:CastAbility() -- end -- end -- end -- function modifier_imba_wisp_overcharge_721:OnIntervalThink() -- self.parent:ModifyHealth(self.caster:GetHealth() * (1 - (self.talent_drain_pct * 0.01 * self.talent_drain_interval)), self.ability, false, 0) -- self.parent:ReduceMana(self.caster:GetMana() * self.talent_drain_pct * 0.01 * self.talent_drain_interval) -- end -- function modifier_imba_wisp_overcharge_721:OnRefresh() -- self:OnCreated() -- end -- function modifier_imba_wisp_overcharge_721:OnDestroy() -- if not IsServer() then return end -- self:GetParent():StopSound("Hero_Wisp.Overcharge") -- local tether_ability = self:GetCaster():FindAbilityByName("imba_wisp_tether") -- if tether_ability and tether_ability.target then -- local overcharge_modifier = tether_ability.target:FindModifierByNameAndCaster("modifier_imba_wisp_overcharge_721", self:GetCaster()) -- if overcharge_modifier then -- overcharge_modifier:Destroy() -- end -- end -- end -- function modifier_imba_wisp_overcharge_721:DeclareFunctions() -- local decFuncs = { -- MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT, -- -- MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE, -- MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE, -- -- IMBAfication: Fundamental Shift -- MODIFIER_PROPERTY_PROJECTILE_SPEED_BONUS, -- MODIFIER_PROPERTY_CASTTIME_PERCENTAGE, -- -- MODIFIER_PROPERTY_ATTACK_RANGE_BONUS, -- } -- return decFuncs -- end -- function modifier_imba_wisp_overcharge_721:GetModifierAttackSpeedBonus_Constant() -- return self.bonus_attack_speed -- end -- -- function modifier_imba_wisp_overcharge_721:GetModifierIncomingDamage_Percentage() -- -- return self.bonus_damage_pct -- -- end -- function modifier_imba_wisp_overcharge_721:GetModifierHealthRegenPercentage() -- return self.hp_regen -- end -- function modifier_imba_wisp_overcharge_721:GetModifierProjectileSpeedBonus() -- return self.bonus_missile_speed -- end -- function modifier_imba_wisp_overcharge_721:GetModifierPercentageCasttime(keys) -- if self:GetParent().HasAbility and self:GetParent():HasAbility("furion_teleportation") and self:GetParent():FindAbilityByName("furion_teleportation"):IsInAbilityPhase() then -- return 0 -- else -- return self.bonus_cast_speed -- end -- end -- -- function modifier_imba_wisp_overcharge_721:GetModifierAttackRangeBonus() -- -- return self.bonus_attack_range -- -- end -- -- Scepter stuff -- function modifier_imba_wisp_overcharge_721:IsAura() return self:GetParent() == self:GetCaster() and self:GetCaster():HasScepter() end -- function modifier_imba_wisp_overcharge_721:IsAuraActiveOnDeath() return false end -- function modifier_imba_wisp_overcharge_721:GetAuraRadius() return self:GetAbility():GetSpecialValueFor("scepter_radius") end -- function modifier_imba_wisp_overcharge_721:GetAuraSearchFlags() return DOTA_UNIT_TARGET_FLAG_NONE end -- function modifier_imba_wisp_overcharge_721:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_FRIENDLY end -- function modifier_imba_wisp_overcharge_721:GetAuraSearchType() return DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC end -- function modifier_imba_wisp_overcharge_721:GetModifierAura() return "modifier_imba_wisp_overcharge_721_aura" end -- function modifier_imba_wisp_overcharge_721:GetAuraEntityReject(hEntity) return hEntity:HasModifier("modifier_imba_wisp_overcharge_721") end -- --------------------------------------------- -- -- OVERCHARGE AURA MODIFIER (7.21 VERSION) -- -- --------------------------------------------- -- function modifier_imba_wisp_overcharge_721_aura:IsPurgable() return false end -- function modifier_imba_wisp_overcharge_721_aura:GetEffectName() -- return self:GetParent().overcharge_effect -- end -- function modifier_imba_wisp_overcharge_721_aura:OnCreated() -- self.ability = self:GetAbility() -- self.caster = self:GetCaster() -- self.parent = self:GetParent() -- -- AbilitySpecials -- self.scepter_efficiency = self.ability:GetSpecialValueFor("scepter_efficiency") -- self.bonus_attack_speed = self.ability:GetSpecialValueFor("bonus_attack_speed") * self.scepter_efficiency -- self.bonus_damage_pct = self.ability:GetSpecialValueFor("bonus_damage_pct") - self.caster:FindTalentValue("special_bonus_imba_wisp_4") * self.scepter_efficiency -- self.hp_regen = self.ability:GetSpecialValueFor("hp_regen") * self.scepter_efficiency -- self.bonus_missile_speed = self.ability:GetSpecialValueFor("bonus_missile_speed") * self.scepter_efficiency -- self.bonus_cast_speed = self.ability:GetSpecialValueFor("bonus_cast_speed") * self.scepter_efficiency -- self.bonus_attack_range = self.ability:GetSpecialValueFor("bonus_attack_range") * self.scepter_efficiency -- end -- function modifier_imba_wisp_overcharge_721_aura:OnRefresh() -- self:OnCreated() -- end -- function modifier_imba_wisp_overcharge_721_aura:DeclareFunctions() -- local decFuncs = { -- MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT, -- -- MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE, -- MODIFIER_PROPERTY_HEALTH_REGEN_PERCENTAGE, -- -- IMBAfication: Fundamental Shift -- MODIFIER_PROPERTY_PROJECTILE_SPEED_BONUS, -- MODIFIER_PROPERTY_CASTTIME_PERCENTAGE, -- -- MODIFIER_PROPERTY_ATTACK_RANGE_BONUS, -- } -- return decFuncs -- end -- function modifier_imba_wisp_overcharge_721_aura:GetModifierAttackSpeedBonus_Constant() -- return self.bonus_attack_speed -- end -- -- function modifier_imba_wisp_overcharge_721_aura:GetModifierIncomingDamage_Percentage() -- -- return self.bonus_damage_pct -- -- end -- function modifier_imba_wisp_overcharge_721_aura:GetModifierHealthRegenPercentage() -- return self.hp_regen -- end -- function modifier_imba_wisp_overcharge_721_aura:GetModifierProjectileSpeedBonus() -- return self.bonus_missile_speed -- end -- function modifier_imba_wisp_overcharge_721_aura:GetModifierPercentageCasttime() -- return self.bonus_cast_speed -- end -- -- function modifier_imba_wisp_overcharge_721_aura:GetModifierAttackRangeBonus() -- -- return self.bonus_attack_range -- -- end -- ------------------------------------------------ -- -- OVERCHARGE HANDLER MODIFIER (7.21 VERSION) -- -- ------------------------------------------------ -- -- A talent that adds an auto-cast function to an ability...that's new -- function modifier_imba_wisp_overcharge_721_handler:IsHidden() return true end -- function modifier_imba_wisp_overcharge_721_handler:DeclareFunctions() -- local decFuncs = {MODIFIER_EVENT_ON_ORDER} -- return decFuncs -- end -- function modifier_imba_wisp_overcharge_721_handler:OnOrder(keys) -- if not IsServer() or keys.unit ~= self:GetParent() or not self:GetParent():HasTalent("special_bonus_imba_wisp_12") or keys.order_type ~= DOTA_UNIT_ORDER_CAST_TOGGLE_AUTO or keys.ability ~= self:GetAbility() then return end -- -- Due to logic order, this is actually reversed -- if self:GetAbility():GetAutoCastState() then -- self:SetStackCount(0) -- else -- self:SetStackCount(1) -- end -- end -- -- Client-side helper functions -- LinkLuaModifier("modifier_special_bonus_imba_wisp_4", "components/abilities/heroes/hero_wisp", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_special_bonus_imba_wisp_9", "components/abilities/heroes/hero_wisp", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_special_bonus_imba_wisp_10", "components/abilities/heroes/hero_wisp", LUA_MODIFIER_MOTION_NONE) -- LinkLuaModifier("modifier_special_bonus_imba_wisp_12", "components/abilities/heroes/hero_wisp", LUA_MODIFIER_MOTION_NONE) -- modifier_special_bonus_imba_wisp_4 = class({}) -- function modifier_special_bonus_imba_wisp_4:IsHidden() return true end -- function modifier_special_bonus_imba_wisp_4:IsPurgable() return false end -- function modifier_special_bonus_imba_wisp_4:RemoveOnDeath() return false end -- modifier_special_bonus_imba_wisp_9 = class({}) -- function modifier_special_bonus_imba_wisp_9:IsHidden() return true end -- function modifier_special_bonus_imba_wisp_9:IsPurgable() return false end -- function modifier_special_bonus_imba_wisp_9:RemoveOnDeath() return false end -- modifier_special_bonus_imba_wisp_10 = class({}) -- function modifier_special_bonus_imba_wisp_10:IsHidden() return true end -- function modifier_special_bonus_imba_wisp_10:IsPurgable() return false end -- function modifier_special_bonus_imba_wisp_10:RemoveOnDeath() return false end -- modifier_special_bonus_imba_wisp_12 = class({}) -- function modifier_special_bonus_imba_wisp_12:IsHidden() return true end -- function modifier_special_bonus_imba_wisp_12:IsPurgable() return false end -- function modifier_special_bonus_imba_wisp_12:RemoveOnDeath() return false end -- function imba_wisp_spirits:OnOwnerSpawned() -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_10") and not self:GetCaster():HasModifier("modifier_special_bonus_imba_wisp_10") then -- self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("special_bonus_imba_wisp_10"), "modifier_special_bonus_imba_wisp_10", {}) -- end -- end -- function imba_wisp_overcharge_721:OnOwnerSpawned() -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_4") and not self:GetCaster():HasModifier("modifier_special_bonus_imba_wisp_4") then -- self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("special_bonus_imba_wisp_4"), "modifier_special_bonus_imba_wisp_4", {}) -- end -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_12") and not self:GetCaster():HasModifier("modifier_special_bonus_imba_wisp_12") then -- self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("special_bonus_imba_wisp_12"), "modifier_special_bonus_imba_wisp_12", {}) -- end -- end -- function imba_wisp_relocate:OnOwnerSpawned() -- if self:GetCaster():HasTalent("special_bonus_imba_wisp_9") and not self:GetCaster():HasModifier("modifier_special_bonus_imba_wisp_9") then -- self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("special_bonus_imba_wisp_9"), "modifier_special_bonus_imba_wisp_9", {}) -- end -- end
----------------------------------------------- -- Digital Instruments -- -- Uses imgui for the UI element. See imgui_demo.lua -- for documentation. ----------------------------------------------- if not SUPPORTS_FLOATING_WINDOWS then logMsg('Please update your FlyWithLua to the latest version') return end require('graphics') require('math') dataref('gps1_crs', 'sim/cockpit/radios/gps_course_degtm') dataref('nav1_obs', 'sim/cockpit/radios/nav1_obs_degm') dataref('nav1_fromto', 'sim/cockpit/radios/nav1_fromto') dataref('nav1_dme', 'sim/cockpit/radios/nav1_dme_dist_m') dataref('gps2_crs', 'sim/cockpit/radios/gps2_course_degtm2') dataref('nav2_obs', 'sim/cockpit/radios/nav2_obs_degm') dataref('nav2_fromto', 'sim/cockpit/radios/nav2_fromto') dataref('nav2_dme', 'sim/cockpit/radios/nav2_dme_dist_m') local fromto_text = {[0]='OFF', [1]='TO', [2]='FROM'} local wnd = float_wnd_create(180, 100, 1, true) float_wnd_set_position(wnd, 100, SCREEN_HIGHT - 150) float_wnd_set_title(wnd, 'Digital Instruments') float_wnd_set_imgui_builder(wnd, 'DIGI_build_window') local function clampAngle(angle) return math.fmod(angle + 3600, 360) end function DIGI_build_window(wnd, x, y) imgui.TextUnformatted(' NAV1 NAV2') imgui.TextUnformatted('GPS ' .. string.format('%03d', clampAngle(gps1_crs)) .. string.format(' %03d', clampAngle(gps2_crs))) imgui.TextUnformatted('OBS ' .. string.format('%03d', clampAngle(nav1_obs)) .. string.format(' %03d', clampAngle(nav2_obs))) imgui.TextUnformatted('FLAG ' .. string.format('%-4s', fromto_text[nav1_fromto]) .. string.format(' %-4s', fromto_text[nav2_fromto])) imgui.TextUnformatted('DME ' .. string.format('%.1f', nav1_dme) .. string.format(' %.1f', nav2_dme)) end
-- local _HYPER = {'cmd,ctrl,alt,shift'} -- hs.hotkey.bind(_HYPER, "k", function() -- hs.osascript.applescript([[ -- tell application "Calendar" -- switch view to day view -- view calendar at current date -- end tell -- ]]) -- end) -- hs.grid.HINTS = { -- { "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P" }, -- { "A", "S", "D", "F", "G", "H", "J", "K", "L", ";" }, -- { "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/" } -- } -- Set some resize grids up -- hs.grid.setGrid('10x3') -- default to something that maps nicely ... -- hs.grid.setGrid('8x3', '1680x1050') -- hs.grid.setGrid('12x4', '3440x1440') -- hs.grid.setMargins({0,0}) -- gapless -- hs.window.animationDuration = 0 -- disable animations -- hs.hotkey.bind(_HYPER, 'g', hs.grid.toggleShow) -- fullscreen = function() hs.grid.maximizeWindow(hs.window.focusedWindow()) end -- hs.hotkey.bind(_HYPER, "space", fullscreen) -- BAM! -- hs.hotkey.bind(_HYPER, "Left", function() -- local win = hs.window.focusedWindow() -- win:moveOneScreenWest(false, true, 0) -- end) -- hs.hotkey.bind(_HYPER, "Right", function() -- local win = hs.window.focusedWindow() -- win:moveOneScreenEast(false, true, 0) -- end) -- hs.hotkey.bind(_HYPER, "[", function() -- local win = hs.window.focusedWindow() -- local f = win:frame() -- local screen = win:screen() -- local max = screen:frame() -- f.x = max.x -- f.y = max.y -- f.w = max.w / 2 -- f.h = max.h -- win:setFrame(f, 0) -- end) -- hs.hotkey.bind(_HYPER, "]", function() -- local win = hs.window.focusedWindow() -- local f = win:frame() -- local screen = win:screen() -- local max = screen:frame() -- f.x = max.x + (max.w / 2) -- f.y = max.y -- f.w = max.w / 2 -- f.h = max.h -- win:setFrame(f, 0) -- end)
-- Setup function host extangels = {} extangels.triggers = {} -- Create function to check whether the new number function is live function extangels.validate_numeral_function() return angelsmods.functions.add_number_icon_layer({}, 1, angelsmods["smelting"].number_tint) end -- Append angel numerals and return an icons definition function extangels.numeral_tier(icon_data, tier, tint) if pcall(extangels.validate_numeral_function) then local icons = angelsmods.functions.add_number_icon_layer({icon_data}, tier, tint) return icons else return { icon_data, { icon = "__angelsrefining__/graphics/icons/num_"..tier..".png", icon_size = 32, tint = tint, scale = 0.32, shift = {-12, -12} } } end end
return {'rayon','rayonchef','rayondirecteur','rayongericht','rayonhoofd','rayonkantoor','rayonleider','rayonmanager','rayonverband','rayonarchitect','rayonbestuur','raymond','rays','raya','raymon','raymakers','ray','rayonchefs','rayonhoofden','rayonleiders','rayonmanagers','rayons','rays','rayas','raymons','raymonds'}
local function scatter(view, percent, height) local oldp = percent if percent < 0 then percent = -percent end local i = 0 while true do i = i + 1 local v = view[i] if v == nil then break end local mult = 1 if (i % 2 == 0) then mult = -1 end v:translate(0, mult*percent*height/2, 0) end end return function(page, offset, screen_width, screen_height) local percent = offset/page.width scatter(page, percent, page.height) end
-- simplified config for saving an loading lua tables local Config = {} function Config:init(appname,vendorname) local config = wx.wxFileConfig(appname, vendorname,lua2scpath.."optionsfile") if config then config:SetRecordDefaults() self.config = config else error("Could not create config") end end function Config:save_table(key,t) local oldpath = self.config:GetPath() --self.config:DeleteGroup(path) self.config:SetPath("/") self.config:Write(key,serializeTableF(t)) self.config:Flush() self.config:SetPath(oldpath) end function Config:load_table(key) local oldpath = self.config:GetPath() --self.config:DeleteGroup(path) self.config:SetPath("/") local goodread,serialized = self.config:Read(key) self.config:SetPath(oldpath) if goodread then return assert(loadstring(serialized))() else return nil end end function Config:delete() self.config:delete() end return Config
local sh = { } sh.type = "light" sh.func = "sampleShadowSun" function sh:constructDefinesGlobal(dream) return [[ float sampleShadowSun2(Image tex, vec2 shadowUV, float depth) { float ox = float(fract(love_PixelCoord.x * 0.5) > 0.25); float oy = float(fract(love_PixelCoord.y * 0.5) > 0.25) + ox; if (oy > 1.1) oy = 0.0; float ss_texelSize = 1.0 / love_ScreenSize.x; float r0 = texture(tex, shadowUV + vec2(-1.5 + ox, 0.5 + oy) * ss_texelSize).x; float r1 = texture(tex, shadowUV + vec2(0.5 + ox, 0.5 + oy) * ss_texelSize).x; float r2 = texture(tex, shadowUV + vec2(-1.5 + ox, -1.5 + oy) * ss_texelSize).x; float r3 = texture(tex, shadowUV + vec2(0.5 + ox, -1.5 + oy) * ss_texelSize).x; return (r0 > depth ? 0.25 : 0.0) + (r1 > depth ? 0.25 : 0.0) + (r2 > depth ? 0.25 : 0.0) + (r3 > depth ? 0.25 : 0.0) ; } ]] .. self:constructDefinesGlobalCommon(dream) end function sh:constructDefinesGlobalCommon(dream) return [[ float ]] .. self.func .. [[(vec3 vertexPos, vec3 pos, mat4 proj1, mat4 proj2, mat4 proj3, Image tex1, Image tex2, Image tex3, float factor, float shadowDistance, float fade, float bias) { float dist = distance(vertexPos, pos) * shadowDistance; float f2 = factor * factor; float v1 = clamp((1.0 - dist) * fade * f2, 0.0, 1.0); float v2 = clamp((factor - dist) * fade * factor, 0.0, 1.0) - v1; float v3 = clamp((f2 - dist) * fade, 0.0, 1.0) - v2 - v1; float v = 1.0 - v1 - v2 - v3; if (v1 > 0.0) { vec3 uvs = (proj1 * vec4(vertexPos, 1.0)).xyz; v += v1 * ]] .. self.func ..[[2(tex1, uvs.xy * 0.5 + 0.5, uvs.z - bias); } if (v2 > 0.0) { vec3 uvs = (proj2 * vec4(vertexPos, 1.0)).xyz; v += v2 * ]] .. self.func ..[[2(tex2, uvs.xy * 0.5 + 0.5, uvs.z - bias * factor); } if (v3 > 0.0) { vec3 uvs = (proj3 * vec4(vertexPos, 1.0)).xyz; v += v3 * ]] .. self.func ..[[2(tex3, uvs.xy * 0.5 + 0.5, uvs.z - bias * f2); } return v; } ]] end function sh:constructDefines(dream, ID) return ([[ extern float ss_factor_#ID#; extern float ss_distance_#ID#; extern float ss_fade_#ID#; extern vec3 ss_pos_#ID#; extern mat4 ss_proj1_#ID#; extern mat4 ss_proj2_#ID#; extern mat4 ss_proj3_#ID#; extern Image ss_tex1_#ID#; extern Image ss_tex2_#ID#; extern Image ss_tex3_#ID#; extern vec3 ss_vec_#ID#; extern vec3 ss_color_#ID#; ]]):gsub("#ID#", ID) end function sh:constructPixelGlobal(dream) end function sh:constructPixelBasicGlobal(dream) end function sh:constructPixel(dream, ID) return ([[ float bias = mix(1.0, 0.01, dot(normal, ss_vec_#ID#)) / 512.0; float shadow = ]] .. self.func .. [[(vertexPos, ss_pos_#ID#, ss_proj1_#ID#, ss_proj2_#ID#, ss_proj3_#ID#, ss_tex1_#ID#, ss_tex2_#ID#, ss_tex3_#ID#, ss_factor_#ID#, ss_distance_#ID#, ss_fade_#ID#, bias); if (shadow > 0.0) { vec3 lightColor = ss_color_#ID# * shadow; light += getLight(lightColor, viewVec, ss_vec_#ID#, normal, albedo, roughness, metallic); } ]]):gsub("#ID#", ID) end function sh:constructPixelBasic(dream, ID) return ([[ float bias = 1.0 / 512.0; float shadow = ]] .. self.func .. [[(vertexPos, ss_pos_#ID#, ss_proj1_#ID#, ss_proj2_#ID#, ss_proj3_#ID#, ss_tex1_#ID#, ss_tex2_#ID#, ss_tex3_#ID#, ss_factor_#ID#, ss_distance_#ID#, ss_fade_#ID#, bias); light += ss_color_#ID# * shadow; ]]):gsub("#ID#", ID) end function sh:sendGlobalUniforms(dream, shaderObject) end function sh:sendUniforms(dream, shaderObject, light, ID) local shader = shaderObject.shader if light.shadow.canvases and light.shadow.canvases[3] then shader:send("ss_factor_" .. ID, light.shadow.cascadeFactor) shader:send("ss_fade_" .. ID, 4 / light.shadow.cascadeFactor / light.shadow.cascadeFactor) shader:send("ss_distance_" .. ID, 2 / light.shadow.cascadeDistance) shader:send("ss_pos_" .. ID, light.shadow.cams[1].pos) shader:send("ss_proj1_" .. ID, light.shadow.cams[1].transformProj) shader:send("ss_proj2_" .. ID, light.shadow.cams[2].transformProj) shader:send("ss_proj3_" .. ID, light.shadow.cams[3].transformProj) shader:send("ss_tex1_" .. ID, light.shadow.canvases[1]) shader:send("ss_tex2_" .. ID, light.shadow.canvases[2]) shader:send("ss_tex3_" .. ID, light.shadow.canvases[3]) shader:send("ss_color_" .. ID, light.color * light.brightness) if shader:hasUniform("ss_vec_" .. ID) then shader:send("ss_vec_" .. ID, light.direction) end else shader:send("ss_color_" .. ID, {0, 0, 0}) end end return sh
local widget = require("widget") local sounds = require('libraries.sounds') local slide_menu = {} local group = display.newGroup() local onTouch local _W = display.contentWidth local _H = display.contentHeight local real_H = display.actualContentHeight local real_x0 = (_H - real_H) * 0.5 function slide_menu:new(params) local button_group = display.newGroup() local params = params or {} local id = params.id or nil local default = params.default or nil local over = params.over or nil local text = params.text or nil local menu_event = params.event or nil local bg = params.bg or nil local back_image = params.back_image or nil local back_image_press = params.back_image_press or nil local background, slideBackButton2 if bg then background = display.newImage(group, bg, true) background.x = display.contentWidth - background.width * 0.12 background.y = real_H * 0.5 background.width = 40 background.height = display.contentHeight end local function back_event(e) local target = e.target if ("ended" == e.phase) then sounds.play('onTap') slide_menu:hide_slide_menu() end end local function scrollViewTouchHandler(event) if event.phase == "ended" then if gameHasStarted and slideMenuOpen and not colorUpdated then slide_menu:hide_slide_menu() end elseif event.phase == "moved" then if gameHasStarted and slideMenuOpen and not colorUpdated then slide_menu:hide_slide_menu() end end return true end sidebarScrollView = widget.newScrollView{ top = 0, left = 0, height = real_H + 120, horizontalScrollDisabled = true, hideBackground = true, scrollHeight = 8000, } for i = 1, #text do buttons = widget.newButton({ defaultFile = type(default) == "table" and default[i] or default, overFile = type(over) == "table" and over[i] or over, left = 0, top = 0, onRelease = function() if (i == 1) then colorId = 1 elseif (i == 2) then colorId = 2 elseif (i == 3) then colorId = 3 elseif (i == 4) then colorId = 4 elseif (i == 5) then colorId = 5 elseif (i == 6) then colorId = 6 elseif (i == 7) then colorId = 7 elseif (i == 8) then colorId = 8 elseif (i == 9) then colorId = 9 end sounds.play('onColorPick') colorUpdated = true menu_event() end }) button_group:insert(buttons) buttons.x = _W * 0.483 buttons.y = button_group.height + buttons.height * 0.2 buttons.width = 22 buttons.height = 22 end sidebarScrollView:insert(button_group) sidebarScrollView.x = _W - button_group.width * 0.450 sidebarScrollView.y = 75 group:insert(sidebarScrollView) group.y = 0 group.x = 0 return group end function slide_menu:hide_slide_menu() slideMenuOpen = false transition.to(group, { time = 300, alpha = 1, x = group.width, y = group.y }) end function slide_menu:show_slide_menu() colorUpdated = false slideMenuOpen = true transition.to(group, { time = 300, alpha = 1, x = 0, y = group.y }) end return slide_menu
local tvm = require('tvm') local parser = require('shine.lang.parser') local translator = require('shine.lang.translator') local magic = string.char(0x1b, 0x4c, 0x4a, 0x01) local function loadchunk(code, name, opts) if string.sub(code, 1, #magic) ~= magic then local srctree = parser.parse(code, name, 1, opts) local dsttree = translator.translate(srctree, name, opts) code = tostring(dsttree) end return tvm.load(code, name) end local function loader(modname, opts) local filename, havepath if string.find(modname, '/') or string.sub(modname, -4) == '.shn' then filename = modname else filename = package.searchpath(modname, package.path) end if filename then local file = io.open(filename) if file then local code = file:read('*a') file:close() if string.sub(filename, -4) == '.shn' then return assert(loadchunk(code, filename, opts)) elseif string.sub(filename, -3) == '.tp' then return tvm.load(code, '@'..filename) else require("lunokhod") return assert(loadstring(code, '@'..filename)) end else -- die? end end end return { loader = loader; loadchunk = loadchunk; }
local isActive = true local AWSBehaviorAPITest = { } function AWSBehaviorAPITest:OnActivate() local runTestEventId = GameplayNotificationId(self.entityId, "Run Tests") self.gamePlayHandler = GameplayNotificationBus.Connect(self, runTestEventId) self.apiHandler = AWSBehaviorAPINotificationsBus.Connect(self, self.entityId) end function AWSBehaviorAPITest:OnEventBegin() if isActive == false then Debug.Log("AWSBehaviorAPITest not active") self:NotifyMainEntity("success") return end local apiCall = AWSBehaviorAPI() local timeVal = os.date("%b %d %Y %H:%M") local lang = "Eng" apiCall.ResourceName = "CloudGemMessageOfTheDay.ServiceApi" apiCall.Query = "/player/messages?time=" .. timeVal .. "&lang=" .. lang apiCall.HTTPMethod = "GET" apiCall:Execute() end function AWSBehaviorAPITest:OnSuccess(resultBody) Debug.Log("Lua AWSBehaviorAPITest: Passed") Debug.Log("Result body: " .. resultBody) self:NotifyMainEntity("success") end function AWSBehaviorAPITest:OnError(errorBody) Debug.Log("Lua AWSBehaviorAPITest: Failed") Debug.Log("Error Body: " .. errorBody) self:NotifyMainEntity("fail") end function AWSBehaviorAPITest:GetResponse(responseCode, jsonResponseData) Debug.Log("Lua AWSBehaviorAPITest response code: " .. tostring(responseCode)) Debug.Log("Lua AWSBehaviorAPITest jsonResponseData: " .. jsonResponseData) local jsonObject = JSON() jsonObject:FromString(jsonResponseData) end function AWSBehaviorAPITest:OnDeactivate() self.apiHandler:Disconnect() self.gamePlayHandler:Disconnect() end function AWSBehaviorAPITest:NotifyMainEntity(message) local entities = {TagGlobalRequestBus.Event.RequestTaggedEntities(Crc32("Main"))} GameplayNotificationBus.Event.OnEventBegin(GameplayNotificationId(entities[1], "Run Tests"), message) end return AWSBehaviorAPITest
--[[ GD50 Breakout Remake -- ServeState Class -- Author: Colton Ogden cogden@cs50.harvard.edu The state in which we are waiting to serve the ball; here, we are basically just moving the paddle left and right with the ball until we press Enter, though everything in the actual game now should render in preparation for the serve, including our current health and score, as well as the level we're on. ]] ServeState = Class{__includes = BaseState} function ServeState:enter(params) -- grab game state from params self.paddle = params.paddle self.bricks = params.bricks self.health = params.health self.score = params.score self.highScores = params.highScores self.level = params.level self.recoverPoints = params.recoverPoints self.numLockedBricks = 0 for k, brick in pairs(self.bricks) do if brick.locked == true then self.numLockedBricks = self.numLockedBricks + 1 end end -- init new ball (random color for fun) self.ball = Ball() self.ball.skin = math.random(7) end function ServeState:update(dt) -- have the ball track the player self.paddle:update(dt) self.ball.x = self.paddle.x + (self.paddle.width / 2) - 4 self.ball.y = self.paddle.y - 8 if love.keyboard.wasPressed('enter') or love.keyboard.wasPressed('return') then -- pass in all important state info to the PlayState gStateMachine:change('play', { paddle = self.paddle, bricks = self.bricks, health = self.health, score = self.score, highScores = self.highScores, ball = self.ball, level = self.level, recoverPoints = self.recoverPoints, numLockedBricks = self.numLockedBricks }) end if love.keyboard.wasPressed('escape') then love.event.quit() end end function ServeState:render() self.paddle:render() self.ball:render() for k, brick in pairs(self.bricks) do brick:render() end renderScore(self.score) renderHealth(self.health) love.graphics.setFont(gFonts['large']) love.graphics.printf('Level ' .. tostring(self.level), 0, VIRTUAL_HEIGHT / 3, VIRTUAL_WIDTH, 'center') love.graphics.setFont(gFonts['medium']) love.graphics.printf('Press Enter to serve!', 0, VIRTUAL_HEIGHT / 2, VIRTUAL_WIDTH, 'center') end
-- Sort petrochem buildings into more rows local petrochem_buildings = { ["angels-air-filter"] = "petrochem-buildings-air-filter", ["angels-air-filter-2"] = "petrochem-buildings-air-filter", ["angels-air-filter-3"] = "petrochem-buildings-air-filter", ["angels-air-filter-4"] = "petrochem-buildings-air-filter", ["liquifier"] = "petrochem-buildings-liquifier", ["liquifier-2"] = "petrochem-buildings-liquifier", ["liquifier-3"] = "petrochem-buildings-liquifier", ["liquifier-4"] = "petrochem-buildings-liquifier", ["advanced-chemical-plant"] = "petrochem-buildings-advanced-chemical-plant", ["advanced-chemical-plant-2"] = "petrochem-buildings-advanced-chemical-plant", ["advanced-chemical-plant-3"] = "petrochem-buildings-advanced-chemical-plant", ["gas-refinery"] = "petrochem-buildings-advanced-gas-refinery", ["gas-refinery-2"] = "petrochem-buildings-advanced-gas-refinery", ["gas-refinery-3"] = "petrochem-buildings-advanced-gas-refinery", ["gas-refinery-4"] = "petrochem-buildings-advanced-gas-refinery", ["separator"] = "petrochem-buildings-separator", ["separator-2"] = "petrochem-buildings-separator", ["separator-3"] = "petrochem-buildings-separator", ["separator-4"] = "petrochem-buildings-separator", } if settings.startup["extangels-adjust-ordering"].value then for name, subgroup in pairs(petrochem_buildings) do local item = data.raw.item[name] local entity = data.raw["assembling-machine"][name] local recipe = data.raw.recipe[name] if item then item.subgroup = subgroup end -- Clear entity/recipe subgroups for proper inheritance from item if entity then entity.subgroup = nil end if recipe then recipe.subgroup = nil end end end
local addonName, addon, _ = ... local plugin = addon:NewModule('Tracker', 'AceEvent-3.0') local defaults = { char = { trackProfession = { [1] = true, -- primary (first) [2] = true, -- primary (second) [3] = true, -- archaeology [4] = true, -- fishing [5] = true, -- cooking [6] = true, -- first aid }, hideMaxed = false, }, } local ARCHAEOLOGY = 794 local MINING = 186 local TRACKER = ObjectiveTracker_GetModuleInfoTable() TRACKER.updateReasonEvents = OBJECTIVE_TRACKER_UPDATE_ALL TRACKER.usedBlocks = {} plugin.tracker = TRACKER function TRACKER:OnBlockHeaderClick(block, mouseButton) local name, _, _, _, _, spellOffset, skillLine = GetProfessionInfo(block.id) local spellLink, tradeSkillLink = GetSpellLink(spellOffset + 1, BOOKTYPE_PROFESSION) if tradeSkillLink or skillLine == ARCHAEOLOGY or skillLine == MINING then CastSpell(spellOffset + 1, BOOKTYPE_PROFESSION) if IsModifiedClick('CHATLINK') and ChatEdit_GetActiveWindow() and tradeSkillLink then ChatEdit_InsertLink(tradeSkillLink) CloseTradeSkill() else -- toggle off CastSpell(spellOffset + 1, BOOKTYPE_PROFESSION) end end end local professions, expansionMaxRank, expansionMaxName = {}, unpack(PROFESSION_RANKS[#PROFESSION_RANKS]) function TRACKER:Update() local prof1, prof2, archaeology, fishing, cooking, firstAid = GetProfessions() professions[1] = prof1 or 0 professions[2] = prof2 or 0 professions[3] = archaeology or 0 professions[4] = fishing or 0 professions[5] = cooking or 0 professions[6] = firstAid or 0 TRACKER:BeginLayout() for index, profession in ipairs(professions) do local name, icon, rank, maxRank, numSpells, spelloffset, skillLine, rankModifier, specializationIndex, specializationOffset = GetProfessionInfo(profession) rank, maxRank = rank or 0, maxRank or 0 local isMaxSkill = rank >= expansionMaxRank and rank == maxRank if profession > 0 and rank > 0 and plugin.db.char.trackProfession[index] and (not isMaxSkill or not plugin.db.char.hideMaxed) then local block = self:GetBlock(profession) self:SetBlockHeader(block, ('|T%s:0|t %s'):format(icon, name)) local skill = isMaxSkill and expansionMaxName or ('%d/%d'):format(rank, maxRank) local line = self:AddObjective(block, profession, skill, nil, nil, true) if not isMaxSkill then -- abusing timer bar as progress bar -- cause line to move up into objective line local lineSpacing = block.module.lineSpacing block.module.lineSpacing = -16 local timerBar = self:AddTimerBar(block, line, maxRank, nil) timerBar:SetScript('OnUpdate', nil) timerBar.Bar:SetMinMaxValues(0, maxRank) timerBar.Bar:SetValue(rank) block.module.lineSpacing = lineSpacing -- indicate higher learning required if maxRank < expansionMaxRank and rank/maxRank > 0.9 then timerBar.Bar:SetStatusBarColor(1, 0, 0) else timerBar.Bar:SetStatusBarColor(0.26, 0.42, 1) end else self:FreeProgressBar(block, line) end -- add to tracker block:SetHeight(block.height) if ObjectiveTracker_AddBlock(block) then block:Show() TRACKER:FreeUnusedLines(block) else -- we've run out of space block.used = false break end end end TRACKER:EndLayout() -- TODO: FIXME: when in bonus objective, boxes get moved... if BONUS_OBJECTIVE_TRACKER_MODULE.firstBlock then if ACHIEVEMENT_TRACKER_MODULE.firstBlock then -- move below achievements else -- move below bonus objective -- AnchorBlock(ACHIEVEMENT_TRACKER_MODULE.Header, BONUS_OBJECTIVE_TRACKER_MODULE.lastBlock) end end end local function InitTracker(self) table.insert(self.MODULES, TRACKER) self.BlocksFrame.ProfessionHeader = CreateFrame('Frame', nil, self.BlocksFrame, 'ObjectiveTrackerHeaderTemplate') TRACKER:SetHeader(self.BlocksFrame.ProfessionHeader, _G.TRADE_SKILLS, 0) plugin:RegisterEvent('SKILL_LINES_CHANGED', function() ObjectiveTracker_Update() end) ObjectiveTracker_Update() end plugin.Update = TRACKER.Update function plugin:OnEnable() self.db = addon.db:RegisterNamespace('Tracker', defaults) if ObjectiveTrackerFrame.initialized then InitTracker(ObjectiveTrackerFrame) else hooksecurefunc('ObjectiveTracker_Initialize', InitTracker) end end
--- --- Created by dhh. --- -- Load the shdict shared_conf = ngx.shared.ct_shared_dict
return function( s, is_text, path ) if is_text then local chunk = assert( (loadstring or load)( s, '@' .. path ) ) return string.dump( chunk, true ), false else return s, false end end
local function config() require("trouble").setup {use_lsp_diagnostic_signs = true} end local function setup() vim.api.nvim_set_keymap("n", "<leader>xx", "<cmd>TroubleToggle<cr>", {silent = true, noremap = true}) vim.api.nvim_set_keymap( "n", "<leader>ew", "<cmd>Trouble lsp_workspace_diagnostics<cr>", {silent = true, noremap = true}) vim.api.nvim_set_keymap( "n", "<leader>ed", "<cmd>Trouble lsp_document_diagnostics<cr>", {silent = true, noremap = true}) vim.api.nvim_set_keymap("n", "<leader>xl", "<cmd>Trouble loclist<cr>", {silent = true, noremap = true}) vim.api.nvim_set_keymap("n", "<leader>xq", "<cmd>Trouble quickfix<cr>", {silent = true, noremap = true}) vim.api.nvim_set_keymap("n", "gr", "<cmd>Trouble lsp_references<cr>", {silent = true, noremap = true}) end return {setup = setup, config = config}
--[[ Copyright (c) 2021 LeonAirRC 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 labelsKey = "ps_lab" local upSwitchKey = "ps_up" local downSwitchKey = "ps_down" local neutralKey = "ps_neu" local enabledKey = "ps_act" local delaysKey = "ps_del" local labels local upSwitches, downSwitches local neutralPoints local enabled local values = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} local delays local lastTime -- saves the last loop time for intergration local controlIndex = 0 -- index of the currently selected control (1-10) or 0 if the main page is displayed local checkboxIndex local locale = system.getLocale() local appName = {en = "Proportional Switches", de = "Proportionale Schalter", cz = "proporcionální spínač"} local labelText = {en = "Label", de = "Bezeichnung", cz = "název"} local enabledText = {en = "Enabled", de = "Aktiv", cz = "činný"} local switchText = {en = "Switch", de = "Switch", cz = "vypínač"} local neutralPointText = {en = "Neutral point", de = "Neutralpunkt", cz = "neutrální bod"} local delayText = {en = "Delay [s]", de = "Verzögerung [s]", cz = "Zpoždění [s]"} local registerErrorText = {en = "Control %d is already in use", de = "Geber %d wird bereits verwendet", cz = "ovládání %d se již používá"} local function getTranslation(table) return table[locale] or table["en"] end ---------------------- -- callback functions ---------------------- local function onLabelChanged(value) labels[controlIndex] = value system.pSave(labelsKey, labels) end local function onEnableChanged(value) if value then system.unregisterControl(controlIndex) enabled[controlIndex] = 0 else if system.registerControl(controlIndex, labels[controlIndex], "C" .. tostring(controlIndex)) ~= nil then enabled[controlIndex] = 1 else enabled[controlIndex] = 0 system.messageBox(string.format(getTranslation(registerErrorText), controlIndex)) end end form.reinit() form.setValue(checkboxIndex, enabled[controlIndex] == 1) system.pSave(enabledKey, enabled) end local function onUpSwitchChanged(value) local info = system.getSwitchInfo(value) upSwitches[controlIndex] = (info and info.assigned) and value or nil system.pSave(upSwitchKey .. tostring(controlIndex), value) end local function onDownSwitchChanged(value) local info = system.getSwitchInfo(value) downSwitches[controlIndex] = (info and info.assigned) and value or nil system.pSave(downSwitchKey .. tostring(controlIndex), value) end local function onNeutralPointChanged(value) neutralPoints[controlIndex] = value system.pSave(neutralKey, neutralPoints) end local function onDelayChanged(value) delays[controlIndex] = value system.pSave(delaysKey, delays) end local function onKeyPressed(keyCode) if controlIndex ~= 0 and (keyCode == KEY_ESC or keyCode == KEY_5) then form.preventDefault() controlIndex = 0 form.reinit() end end local function loop() local time = system.getTimeCounter() for i = 1, 10 do if upSwitches[i] or downSwitches[i] then local total = ((system.getInputsVal(upSwitches[i]) or neutralPoints[i]) - neutralPoints[i]) / (1 - neutralPoints[i]) - ((system.getInputsVal(downSwitches[i]) or neutralPoints[i]) - neutralPoints[i]) / (1 - neutralPoints[i]) -- sum of switch inputs values[i] = values[i] + total * (time - lastTime) / (100 * delays[i]) -- add total multiplied by time to approximate the integral if values[i] > 1 then values[i] = 1 -- max 1 elseif values[i] < -1 then values[i] = -1 -- min -1 end if system.setControl(i, values[i], 0) == nil then -- setControl failed enabled[i] = 0 system.messageBox(string.format(getTranslation(registerErrorText), i)) -- notify that the control was unassigned, probably due to intersection with another app end end end lastTime = time end ---------------------------------------------- -- prints the amplitude as a bar and a number ---------------------------------------------- local function printForm(width, height) if controlIndex ~= 0 and enabled[controlIndex] == 1 then local x = width // 2 local str = string.format("%.2f", values[controlIndex]) lcd.drawText(x - lcd.getTextWidth(FONT_NORMAL, str) // 2, height - 40, str) lcd.drawRectangle(x - 60, height - 20, 120, 20) lcd.drawLine(x, height - 20, x, height - 1) local rectWidth = math.floor(values[controlIndex] * 60 + 0.5) lcd.drawFilledRectangle(math.min(rectWidth, 0) + x, height - 20, math.abs(rectWidth), 20) end end local function initForm() if controlIndex == 0 then for i = 1, 10 do form.addRow(4) form.addLabel({ label = "C" .. tostring(i), font = FONT_BOLD, width = 60 }) form.addLabel({ label = labels[i], width = 180 }) form.addCheckbox(enabled[i] == 1, nil, { enabled = false, width = 30 }) form.addLink(function() controlIndex = i form.reinit() end, { label = ">> ", alignRight = true }) end else form.setTitle("C" .. tostring(controlIndex)) form.addRow(4) form.addLabel({ label = getTranslation(labelText), font = FONT_BOLD, width = 100 }) form.addTextbox(labels[controlIndex], 12, onLabelChanged, { font = FONT_BOLD, width = 120 }) form.addLabel({ label = getTranslation(enabledText), font = FONT_BOLD, width = 70 }) checkboxIndex = form.addCheckbox(enabled[controlIndex] == 1, onEnableChanged) if enabled[controlIndex] == 1 then form.addRow(2) form.addLabel({ label = getTranslation(switchText) .. " +" }) form.addInputbox(upSwitches[controlIndex], true, onUpSwitchChanged) form.addRow(2) form.addLabel({ label = getTranslation(switchText) .. " -" }) form.addInputbox(downSwitches[controlIndex], true, onDownSwitchChanged) form.addRow(2) form.addLabel({ label = getTranslation(neutralPointText) }) form.addIntbox(neutralPoints[controlIndex], -1, 0, -1, 0, 1, onNeutralPointChanged) form.addRow(2) form.addLabel({ label = getTranslation(delayText) }) form.addIntbox(delays[controlIndex], 1, 600, 10, 1, 1, onDelayChanged) end end form.setFocusedRow(1) end local function init() labels = system.pLoad(labelsKey) or {"Control 1", "Control 2", "Control 3", "Control 4", "Control 5", "Control 6", "Control 7", "Control 8", "Control 9", "Control 10"} neutralPoints = system.pLoad(neutralKey) or {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1} enabled = system.pLoad(enabledKey) or {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} delays = system.pLoad(delaysKey) or {10, 10, 10, 10, 10, 10, 10, 10, 10, 10} upSwitches = {} downSwitches = {} for i = 1, 10 do upSwitches[i] = system.pLoad(upSwitchKey .. tostring(i)) downSwitches[i] = system.pLoad(downSwitchKey .. tostring(i)) end system.registerForm(1, MENU_APPS, getTranslation(appName), initForm, onKeyPressed, printForm) for i = 1, 10 do if enabled[i] == 1 and system.registerControl(i, labels[i], "C" .. tostring(i)) == nil then -- register failed enabled[i] = 0 -- deactivate control system.messageBox(string.format(getTranslation(registerErrorText), i)) end end lastTime = system.getTimeCounter() end local function destroy() for i = 1, 10 do if enabled[i] then system.unregisterControl(i) end end collectgarbage() end return { init = init, loop = loop, destroy = destroy, author = "LeonAir RC", version = "1.1.3", name = getTranslation(appName) }
-- vim: ts=2 sw=2 sts=2 et : -- # Sym.lua -- Summarizing symbolic columns. -- (c) 2021 Tim Menzies (timm@ieee.org) unlicense.org local r=require local Lib,Col,Count = r("lib"),r("col"),r("count") local Sym = Lib.class(Col) function Sym:_init(at,txt) self:super(at,txt) self.seen,self.most,self.mode = {},0,nil end function Sym:add1(x, n) local d = (self.seen[x] or 0) + (n or 1) self.seen[x] = d if d > self.most then self.most, self.mode = d, x end end function Sym:ent( e,p) e = 0 for _,n in pairs(self.seen) do p = n/self.n e = e - p*math.log(p)/math.log(2) end return e end function Sym:mid(x) return self.mode end function Sym:norm1(x) return x end function Sym:dist1(x,y) return x==y and 0 or 1 end function Sym:spread() return self:ent() end function Sym:merge(j) local k = Sym(self.at, self.txt) for _,seen1 in pairs({self.seen, j.seen}) do for x,n in pairs(seen1) do k:add(x,n) end end local e1,n1 = self:ent(), self.n local e2,n2 = j:ent(), j.n local e ,n = k:ent(), k.n local xpect = n1/n*e1 + n2/n*e2 if e<=xpect then return k end end function Sym:discretize(other,counts,_) for x,n in pairs(self.seen) do Count(true, self.txt,self.at,x,x,n,counts) end for x,n in pairs(other.seen) do Count(false,self.txt,self.at,x,x,n,counts) end end return Sym
print("Hello from Lua, ", system.version) do local t = 0 local f function f() print("timer demo ", t, ", cur time: ", system.time) t = t + 1 if t <= 5 then setTimeout(f, 1000) end end f() end function bindings.exit() print("Good Bye from Lua") end function bindings.serverStart() print("Lua: server started …") end function bindings.serverStop() print("Lua: server stopped …") end function bindings.gamePrepare() print("Lua: game prepare …") end function bindings.gameBegin() print("Lua: game begin …") end function bindings.gameOver() print("Lua: game over …") end function bindings.gotoLobby() print("Lua: goto lobby …") end
class('GS_Software','GS_Class',{ ReadSuper = function(this,fin) fin:read(5) end; Read = function() end; SaveSuper = function(this,fout) fwrite(fout,5,0) end; Save = function() end; })
local luawa = require('luawa.core'):init() luawa:run()
--Script Name : insert MS track --Author : Jean Loup Pecquais --Description : insert MS track --v1.0.0 local libPath = reaper.GetExtState("Reaper Evolution", "libPath") if not libPath or libPath == "" then reaper.MB("Reaper Evolution library is not found. Please refer to user guide", "Library not found", 0) return end loadfile(libPath .. "reaVolutionLib.lua")() ------------------------------------------------------------------------------------------------------------- function main() local frames = 10 reaper.PreventUIRefresh(-1*frames) local numTr = reaper.CountTracks(0) reaper.Main_OnCommandEx(41067, 0, 0) local newNumTr = reaper.CountTracks(0) if numTr == newNumTr then return end local selTr = reaper.CountSelectedTracks(0) for i = 0, selTr-1 do local tr = reaper.GetSelectedTrack(0, i) setAudioStream( tr, 1, 2 ) end reaper.PreventUIRefresh(frames) end reaper.Undo_BeginBlock() main() reaper.Undo_EndBlock('Insert M/S track', -1)
-- /////////////////////////////////////////////////////////////////// -- // Name: inifile.lua -- // Purpose: Inifile parser 1.0 -- // Created: 2018/10/09 -- // Copyright: (c) 2018 Hernan Dario Cano [dcanohdev[at]gmail.com] -- // License: GNU GENERAL PUBLIC LICENSE -- /////////////////////////////////////////////////////////////////// local inifile = {} -- Delimit string to table: function string.delim(str, d) local a,t,c,b = 0, {} repeat b = str:find(d or '|', a) if b then c = str:sub(a, b-1) a = b +1 else c = str:sub(a, #str) end t[#t+1] = c until b == nil return t --------------------------------------- -- usage: -- t = string.delim "thedary|thd" -- t = string.delim("thedary, dario, cano",',') --------------------------------------- end local function trim2(s) return s:match "^%s*(.-)%s*$" end function inifile.parse ( inistring ) local h_list, h1, h2, h_name = {}; repeat --- Extract headers: h1 = inistring:find ('%[', h2); h2 = inistring:find ('%]', h1); if h1 and h2 then h_name = inistring:sub(h1+1, h2-1); h_list[#h_list+1] = '%['.. h_name .. '%]' end until not h1 local _initable = {}; for k,v in pairs(h_list) do if h_list[k] then local si1, se1, si2, se2; local section_str; si1, se1 = inistring:find ( h_list[k] ); --> SectionEnd1 if h_list[k+1] then si2, se2 = inistring:find ( h_list[k+1] ); --> SectionInit2, SectionEnd2 else se2 = #inistring si2 = se2 end --- if is the last: if (si2 == #inistring) then section_str = (inistring:sub(se1+1, si2)); else section_str = (inistring:sub(se1+1, si2-1)); end for line in section_str:gmatch("[^\r\n]+") do if line:gsub(' ', '') ~= '' then local line_del = line:delim '='; local section_name = h_list[k]:sub(3, #h_list[k]-2); local skey_name = trim2(line_del[1]:gsub(' ', '')); _initable[section_name] = _initable[section_name] or {} _initable[section_name][skey_name] = trim2(line_del[2]) end end end end return _initable end function inifile.parse_file ( file ) local thefile = io.open(file, 'r'); local file_content = thefile:read '*a'; return inifile.parse(file_content); end return inifile
local options = { frames = { {x=0,y=0,width=16,height=16,}, -- frame 1 {x=16,y=0,width=16,height=16,}, -- frame 2 {x=32,y=0,width=16,height=16,}, -- frame 3 {x=48,y=0,width=16,height=16,}, -- frame 4 {x=64,y=0,width=16,height=16,}, -- frame 5 {x=80,y=0,width=16,height=16,}, -- frame 6 {x=96,y=0,width=16,height=16,}, -- frame 7 {x=112,y=0,width=16,height=16,}, -- frame 8 {x=128,y=0,width=16,height=16,}, -- frame 9 {x=144,y=0,width=16,height=16,}, -- frame 10 {x=160,y=0,width=16,height=16,}, -- frame 11 {x=176,y=0,width=16,height=16,}, -- frame 12 {x=192,y=0,width=16,height=16,}, -- frame 13 {x=208,y=0,width=16,height=16,}, -- frame 14 {x=224,y=0,width=16,height=16,}, -- frame 15 {x=240,y=0,width=16,height=16,}, -- frame 16 {x=0,y=16,width=16,height=16,}, -- frame 17 {x=16,y=16,width=16,height=16,}, -- frame 18 {x=32,y=16,width=16,height=16,}, -- frame 19 {x=48,y=16,width=16,height=16,}, -- frame 20 {x=64,y=16,width=16,height=16,}, -- frame 21 {x=80,y=16,width=16,height=16,}, -- frame 22 {x=96,y=16,width=16,height=16,}, -- frame 23 {x=112,y=16,width=16,height=16,}, -- frame 24 {x=128,y=16,width=16,height=16,}, -- frame 25 {x=144,y=16,width=16,height=16,}, -- frame 26 {x=160,y=16,width=16,height=16,}, -- frame 27 {x=176,y=16,width=16,height=16,}, -- frame 28 {x=192,y=16,width=16,height=16,}, -- frame 29 {x=208,y=16,width=16,height=16,}, -- frame 30 {x=224,y=16,width=16,height=16,}, -- frame 31 {x=240,y=16,width=16,height=16,}, -- frame 32 {x=0,y=32,width=16,height=16,}, -- frame 33 {x=16,y=32,width=16,height=16,}, -- frame 34 {x=32,y=32,width=16,height=16,}, -- frame 35 {x=48,y=32,width=16,height=16,}, -- frame 36 {x=64,y=32,width=16,height=16,}, -- frame 37 {x=80,y=32,width=16,height=16,}, -- frame 38 {x=96,y=32,width=16,height=16,}, -- frame 39 {x=112,y=32,width=16,height=16,}, -- frame 40 {x=128,y=32,width=16,height=16,}, -- frame 41 {x=144,y=32,width=16,height=16,}, -- frame 42 {x=160,y=32,width=16,height=16,}, -- frame 43 {x=176,y=32,width=16,height=16,}, -- frame 44 {x=192,y=32,width=16,height=16,}, -- frame 45 {x=208,y=32,width=16,height=16,}, -- frame 46 {x=224,y=32,width=16,height=16,}, -- frame 47 {x=240,y=32,width=16,height=16,}, -- frame 48 {x=0,y=48,width=16,height=16,}, -- frame 49 {x=16,y=48,width=16,height=16,}, -- frame 50 {x=32,y=48,width=16,height=16,}, -- frame 51 {x=48,y=48,width=16,height=16,}, -- frame 52 {x=64,y=48,width=16,height=16,}, -- frame 53 {x=80,y=48,width=16,height=16,}, -- frame 54 {x=96,y=48,width=16,height=16,}, -- frame 55 {x=112,y=48,width=16,height=16,}, -- frame 56 {x=128,y=48,width=16,height=16,}, -- frame 57 {x=144,y=48,width=16,height=16,}, -- frame 58 {x=160,y=48,width=16,height=16,}, -- frame 59 {x=176,y=48,width=16,height=16,}, -- frame 60 {x=192,y=48,width=16,height=16,}, -- frame 61 {x=208,y=48,width=16,height=16,}, -- frame 62 {x=224,y=48,width=16,height=16,}, -- frame 63 {x=240,y=48,width=16,height=16,}, -- frame 64 {x=0,y=64,width=16,height=16,}, -- frame 65 {x=16,y=64,width=16,height=16,}, -- frame 66 {x=32,y=64,width=16,height=16,}, -- frame 67 {x=48,y=64,width=16,height=16,}, -- frame 68 {x=64,y=64,width=16,height=16,}, -- frame 69 {x=80,y=64,width=16,height=16,}, -- frame 70 {x=96,y=64,width=16,height=16,}, -- frame 71 {x=112,y=64,width=16,height=16,}, -- frame 72 {x=128,y=64,width=16,height=16,}, -- frame 73 {x=144,y=64,width=16,height=16,}, -- frame 74 {x=160,y=64,width=16,height=16,}, -- frame 75 {x=176,y=64,width=16,height=16,}, -- frame 76 {x=192,y=64,width=16,height=16,}, -- frame 77 {x=208,y=64,width=16,height=16,}, -- frame 78 {x=224,y=64,width=16,height=16,}, -- frame 79 {x=240,y=64,width=16,height=16,}, -- frame 80 {x=0,y=80,width=16,height=16,}, -- frame 81 {x=16,y=80,width=16,height=16,}, -- frame 82 {x=32,y=80,width=16,height=16,}, -- frame 83 {x=48,y=80,width=16,height=16,}, -- frame 84 {x=64,y=80,width=16,height=16,}, -- frame 85 {x=80,y=80,width=16,height=16,}, -- frame 86 {x=96,y=80,width=16,height=16,}, -- frame 87 {x=112,y=80,width=16,height=16,}, -- frame 88 {x=128,y=80,width=16,height=16,}, -- frame 89 {x=144,y=80,width=16,height=16,}, -- frame 90 {x=160,y=80,width=16,height=16,}, -- frame 91 {x=176,y=80,width=16,height=16,}, -- frame 92 {x=192,y=80,width=16,height=16,}, -- frame 93 {x=208,y=80,width=16,height=16,}, -- frame 94 {x=224,y=80,width=16,height=16,}, -- frame 95 {x=240,y=80,width=16,height=16,}, -- frame 96 {x=0,y=96,width=16,height=16,}, -- frame 97 {x=16,y=96,width=16,height=16,}, -- frame 98 {x=32,y=96,width=16,height=16,}, -- frame 99 {x=48,y=96,width=16,height=16,}, -- frame 100 {x=64,y=96,width=16,height=16,}, -- frame 101 {x=80,y=96,width=16,height=16,}, -- frame 102 {x=96,y=96,width=16,height=16,}, -- frame 103 {x=112,y=96,width=16,height=16,}, -- frame 104 {x=128,y=96,width=16,height=16,}, -- frame 105 {x=144,y=96,width=16,height=16,}, -- frame 106 {x=160,y=96,width=16,height=16,}, -- frame 107 {x=176,y=96,width=16,height=16,}, -- frame 108 {x=192,y=96,width=16,height=16,}, -- frame 109 {x=208,y=96,width=16,height=16,}, -- frame 110 {x=224,y=96,width=16,height=16,}, -- frame 111 {x=240,y=96,width=16,height=16,}, -- frame 112 {x=0,y=112,width=16,height=16,}, -- frame 113 {x=16,y=112,width=16,height=16,}, -- frame 114 {x=32,y=112,width=16,height=16,}, -- frame 115 {x=48,y=112,width=16,height=16,}, -- frame 116 {x=64,y=112,width=16,height=16,}, -- frame 117 {x=80,y=112,width=16,height=16,}, -- frame 118 {x=96,y=112,width=16,height=16,}, -- frame 119 {x=112,y=112,width=16,height=16,}, -- frame 120 {x=128,y=112,width=16,height=16,}, -- frame 121 {x=144,y=112,width=16,height=16,}, -- frame 122 {x=160,y=112,width=16,height=16,}, -- frame 123 {x=176,y=112,width=16,height=16,}, -- frame 124 {x=192,y=112,width=16,height=16,}, -- frame 125 {x=208,y=112,width=16,height=16,}, -- frame 126 {x=224,y=112,width=16,height=16,}, -- frame 127 {x=240,y=112,width=16,height=16,}, -- frame 128 {x=0,y=128,width=16,height=16,}, -- frame 129 {x=16,y=128,width=16,height=16,}, -- frame 130 {x=32,y=128,width=16,height=16,}, -- frame 131 {x=48,y=128,width=16,height=16,}, -- frame 132 {x=64,y=128,width=16,height=16,}, -- frame 133 {x=80,y=128,width=16,height=16,}, -- frame 134 {x=96,y=128,width=16,height=16,}, -- frame 135 {x=112,y=128,width=16,height=16,}, -- frame 136 {x=128,y=128,width=16,height=16,}, -- frame 137 {x=144,y=128,width=16,height=16,}, -- frame 138 {x=160,y=128,width=16,height=16,}, -- frame 139 {x=176,y=128,width=16,height=16,}, -- frame 140 {x=192,y=128,width=16,height=16,}, -- frame 141 {x=208,y=128,width=16,height=16,}, -- frame 142 {x=224,y=128,width=16,height=16,}, -- frame 143 {x=240,y=128,width=16,height=16,}, -- frame 144 {x=0,y=144,width=16,height=16,}, -- frame 145 {x=16,y=144,width=16,height=16,}, -- frame 146 {x=32,y=144,width=16,height=16,}, -- frame 147 {x=48,y=144,width=16,height=16,}, -- frame 148 {x=64,y=144,width=16,height=16,}, -- frame 149 {x=80,y=144,width=16,height=16,}, -- frame 150 {x=96,y=144,width=16,height=16,}, -- frame 151 {x=112,y=144,width=16,height=16,}, -- frame 152 {x=128,y=144,width=16,height=16,}, -- frame 153 {x=144,y=144,width=16,height=16,}, -- frame 154 {x=160,y=144,width=16,height=16,}, -- frame 155 {x=176,y=144,width=16,height=16,}, -- frame 156 {x=192,y=144,width=16,height=16,}, -- frame 157 {x=208,y=144,width=16,height=16,}, -- frame 158 {x=224,y=144,width=16,height=16,}, -- frame 159 {x=240,y=144,width=16,height=16,}, -- frame 160 {x=0,y=160,width=16,height=16,}, -- frame 161 {x=16,y=160,width=16,height=16,}, -- frame 162 {x=32,y=160,width=16,height=16,}, -- frame 163 {x=48,y=160,width=16,height=16,}, -- frame 164 {x=64,y=160,width=16,height=16,}, -- frame 165 {x=80,y=160,width=16,height=16,}, -- frame 166 {x=96,y=160,width=16,height=16,}, -- frame 167 {x=112,y=160,width=16,height=16,}, -- frame 168 {x=128,y=160,width=16,height=16,}, -- frame 169 {x=144,y=160,width=16,height=16,}, -- frame 170 {x=160,y=160,width=16,height=16,}, -- frame 171 {x=176,y=160,width=16,height=16,}, -- frame 172 {x=192,y=160,width=16,height=16,}, -- frame 173 {x=208,y=160,width=16,height=16,}, -- frame 174 {x=224,y=160,width=16,height=16,}, -- frame 175 {x=240,y=160,width=16,height=16,}, -- frame 176 {x=0,y=176,width=16,height=16,}, -- frame 177 {x=16,y=176,width=16,height=16,}, -- frame 178 {x=32,y=176,width=16,height=16,}, -- frame 179 {x=48,y=176,width=16,height=16,}, -- frame 180 {x=64,y=176,width=16,height=16,}, -- frame 181 {x=80,y=176,width=16,height=16,}, -- frame 182 {x=96,y=176,width=16,height=16,}, -- frame 183 {x=112,y=176,width=16,height=16,}, -- frame 184 {x=128,y=176,width=16,height=16,}, -- frame 185 {x=144,y=176,width=16,height=16,}, -- frame 186 {x=160,y=176,width=16,height=16,}, -- frame 187 {x=176,y=176,width=16,height=16,}, -- frame 188 {x=192,y=176,width=16,height=16,}, -- frame 189 {x=208,y=176,width=16,height=16,}, -- frame 190 {x=224,y=176,width=16,height=16,}, -- frame 191 {x=240,y=176,width=16,height=16,}, -- frame 192 {x=0,y=192,width=16,height=16,}, -- frame 193 {x=16,y=192,width=16,height=16,}, -- frame 194 {x=32,y=192,width=16,height=16,}, -- frame 195 {x=48,y=192,width=16,height=16,}, -- frame 196 {x=64,y=192,width=16,height=16,}, -- frame 197 {x=80,y=192,width=16,height=16,}, -- frame 198 {x=96,y=192,width=16,height=16,}, -- frame 199 {x=112,y=192,width=16,height=16,}, -- frame 200 {x=128,y=192,width=16,height=16,}, -- frame 201 {x=144,y=192,width=16,height=16,}, -- frame 202 {x=160,y=192,width=16,height=16,}, -- frame 203 {x=176,y=192,width=16,height=16,}, -- frame 204 {x=192,y=192,width=16,height=16,}, -- frame 205 {x=208,y=192,width=16,height=16,}, -- frame 206 {x=224,y=192,width=16,height=16,}, -- frame 207 {x=240,y=192,width=16,height=16,}, -- frame 208 {x=0,y=208,width=16,height=16,}, -- frame 209 {x=16,y=208,width=16,height=16,}, -- frame 210 {x=32,y=208,width=16,height=16,}, -- frame 211 {x=48,y=208,width=16,height=16,}, -- frame 212 {x=64,y=208,width=16,height=16,}, -- frame 213 {x=80,y=208,width=16,height=16,}, -- frame 214 {x=96,y=208,width=16,height=16,}, -- frame 215 {x=112,y=208,width=16,height=16,}, -- frame 216 {x=128,y=208,width=16,height=16,}, -- frame 217 {x=144,y=208,width=16,height=16,}, -- frame 218 {x=160,y=208,width=16,height=16,}, -- frame 219 {x=176,y=208,width=16,height=16,}, -- frame 220 {x=192,y=208,width=16,height=16,}, -- frame 221 {x=208,y=208,width=16,height=16,}, -- frame 222 {x=224,y=208,width=16,height=16,}, -- frame 223 {x=240,y=208,width=16,height=16,}, -- frame 224 {x=0,y=224,width=16,height=16,}, -- frame 225 {x=16,y=224,width=16,height=16,}, -- frame 226 {x=32,y=224,width=16,height=16,}, -- frame 227 {x=48,y=224,width=16,height=16,}, -- frame 228 {x=64,y=224,width=16,height=16,}, -- frame 229 {x=80,y=224,width=16,height=16,}, -- frame 230 {x=96,y=224,width=16,height=16,}, -- frame 231 {x=112,y=224,width=16,height=16,}, -- frame 232 {x=128,y=224,width=16,height=16,}, -- frame 233 {x=144,y=224,width=16,height=16,}, -- frame 234 {x=160,y=224,width=16,height=16,}, -- frame 235 {x=176,y=224,width=16,height=16,}, -- frame 236 {x=192,y=224,width=16,height=16,}, -- frame 237 {x=208,y=224,width=16,height=16,}, -- frame 238 {x=224,y=224,width=16,height=16,}, -- frame 239 {x=240,y=224,width=16,height=16,}, -- frame 240 {x=0,y=240,width=16,height=16,}, -- frame 241 {x=16,y=240,width=16,height=16,}, -- frame 242 {x=32,y=240,width=16,height=16,}, -- frame 243 {x=48,y=240,width=16,height=16,}, -- frame 244 {x=64,y=240,width=16,height=16,}, -- frame 245 {x=80,y=240,width=16,height=16,}, -- frame 246 {x=96,y=240,width=16,height=16,}, -- frame 247 {x=112,y=240,width=16,height=16,}, -- frame 248 {x=128,y=240,width=16,height=16,}, -- frame 249 {x=144,y=240,width=16,height=16,}, -- frame 250 {x=160,y=240,width=16,height=16,}, -- frame 251 {x=176,y=240,width=16,height=16,}, -- frame 252 {x=192,y=240,width=16,height=16,}, -- frame 253 {x=208,y=240,width=16,height=16,}, -- frame 254 {x=224,y=240,width=16,height=16,}, -- frame 255 {x=240,y=240,width=16,height=16,}, -- frame 256 } } return options
-- See LICENSE for terms return { PlaceObj("ModItemOptionToggle", { "name", "EnableMod", "DisplayName", T(302535920011303, "<color ChoGGi_yellow>Enable Mod</color>"), "Help", T(302535920011793, "Disable mod without having to see missing mod msg."), "DefaultValue", true, }), PlaceObj("ModItemOptionToggle", { "name", "ForceClearLines", "DisplayName", T(302535920011833, "Force Clear Lines"), "Help", T(302535920011834, "This will remove any lines stuck on the map (including any from my other mods)."), "DefaultValue", false, }), PlaceObj("ModItemOptionToggle", { "name", "EnableLines", "DisplayName", T(302535920011841, "Enable Lines"), "DefaultValue", true, }), PlaceObj("ModItemOptionToggle", { "name", "EnableText", "DisplayName", T(302535920011717, "Enable Text"), "DefaultValue", true, }), PlaceObj("ModItemOptionToggle", { "name", "ShowNames", "DisplayName", T(302535920011846, "Show Names"), "DefaultValue", false, }), PlaceObj("ModItemOptionToggle", { "name", "DroneBatteryInfo", "DisplayName", T(302535920011842, "Drone Battery Info"), "Help", T(302535920011842, "Show Drone remaining battery life with unit info."), "DefaultValue", true, }), PlaceObj("ModItemOptionToggle", { "name", "OnlyBatteryInfo", "DisplayName", T(302535920011844, "Only Battery Info"), "Help", T(302535920011845, "Only show battery info when selecting drones."), "DefaultValue", false, }), PlaceObj("ModItemOptionToggle", { "name", "TextBackground", "DisplayName", T(302535920011376, "Text Background"), "Help", T(302535920011553, "Add black background to text."), "DefaultValue", false, }), PlaceObj("ModItemOptionNumber", { "name", "TextOpacity", "DisplayName", T(302535920011377, "Text Opacity"), "Help", T(302535920011718, "0 = 100% visible, 255 = 0%"), "DefaultValue", 0, "MinValue", 0, "MaxValue", 255, }), PlaceObj("ModItemOptionNumber", { "name", "TextStyle", "DisplayName", T(302535920011378, "Text Style"), "Help", T(302535920011496, [[<style EncyclopediaArticleTitle>Example Text 1</style> <style BugReportScreenshot>Example Text 2</style> <style CategoryTitle>Example Text 3</style> <style ConsoleLog>Example Text 4</style> <style DomeName>Example Text 5</style> <style GizmoText>Example Text 6</style> <style InfopanelResourceNoAccept>Example Text 7</style> <style ListItem1>Example Text 8</style> <style ModsUIItemStatusWarningBrawseConsole>Example Text 9</style> <style LandingPosNameAlt>Example Text 10</style>]]), "DefaultValue", 1, "MinValue", 1, "MaxValue", 10, }), }
endor_gondula_loremaster_neutral_small_theater = Lair:new { mobiles = { {"gondula_loremaster",1}, {"gifted_gondula_shaman",1}, {"gondula_shaman",1}, {"gondula_tribesman",1} }, spawnLimit = 9, buildingsVeryEasy = {"object/building/poi/endor_ewok_small1.iff","object/building/poi/endor_ewok_small2.iff","object/building/poi/endor_ewok_small3.iff"}, buildingsEasy = {"object/building/poi/endor_ewok_small1.iff","object/building/poi/endor_ewok_small2.iff","object/building/poi/endor_ewok_small3.iff"}, buildingsMedium = {"object/building/poi/endor_ewok_small1.iff","object/building/poi/endor_ewok_small2.iff","object/building/poi/endor_ewok_small3.iff"}, buildingsHard = {"object/building/poi/endor_ewok_small1.iff","object/building/poi/endor_ewok_small2.iff","object/building/poi/endor_ewok_small3.iff"}, buildingsVeryHard = {"object/building/poi/endor_ewok_small1.iff","object/building/poi/endor_ewok_small2.iff","object/building/poi/endor_ewok_small3.iff"}, mobType = "npc", buildingType = "theater" } addLairTemplate("endor_gondula_loremaster_neutral_small_theater", endor_gondula_loremaster_neutral_small_theater)
return { [1] = {x4=1,x1=true,x2=3,x3=128,x5=11223344,x6=1.2,x7=1.23432,x8_0=12312,x8=112233,x9=223344,x10="hq",x12={x1=10,},x13=2,x14={ _name='DemoD2',x1=1,x2=2,},s1={key='/asfa',text="aabbcc"},v2={x=1,y=2},v3={x=1.1,y=2.2,z=3.4},v4={x=10.1,y=11.2,z=12.3,w=13.4},t1=-28800,k1={1,2,},k2={2,3,},k5={1,6,},k8={[2]=2,[4]=10,},k9={{y1=1,y2=true,},{y1=2,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=2,},},}, [11] = {x4=11,x1=true,x2=4,x3=128,x5=112233445566,x6=1.3,x7=1112232.43123,x8_0=123,x8=112233,x9=112334,x10="yf",x12={x1=1,},x13=4,x14={ _name='DemoD2',x1=1,x2=2,},s1={key='xml_key1',text="xml text"},v2={x=1,y=2},v3={x=1.2,y=2.3,z=3.4},v4={x=1.2,y=2.2,z=3.2,w=4.3},t1=-28800,k1={1,2,},k2={1,2,},k5={1,2,},k8={[2]=10,[3]=30,},k9={{y1=1,y2=true,},{y1=2,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=2,},},}, [2] = {x4=2,x1=true,x2=3,x3=128,x5=11223344,x6=1.2,x7=1.23432,x8_0=12312,x8=112233,x9=223344,x10="hq",x12={x1=10,},x13=2,x14={ _name='DemoD2',x1=1,x2=2,},s1={key='/asfa32',text="aabbcc22"},v2={x=1,y=2},v3={x=1.1,y=2.2,z=3.4},v4={x=10.1,y=11.2,z=12.3,w=13.4},t1=-28800,k1={1,2,},k2={2,3,},k5={1,6,},k8={[2]=2,[4]=10,},k9={{y1=1,y2=true,},{y1=2,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=2,},},}, [12] = {x4=12,x1=true,x2=4,x3=128,x5=112233445566,x6=1.3,x7=1112232.43123,x8_0=123,x8=112233,x9=112334,x10="yf",x12={x1=1,},x13=4,x14={ _name='DemoD2',x1=1,x2=2,},s1={key='xml_key2',text="xml text222"},v2={x=1,y=2},v3={x=1.2,y=2.3,z=3.4},v4={x=1.2,y=2.2,z=3.2,w=4.3},t1=-28800,k1={1,2,},k2={1,2,},k5={1,2,},k8={[2]=10,[3]=30,},k9={{y1=1,y2=true,},{y1=2,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=2,},},}, [40] = {x4=40,x1=true,x2=3,x3=128,x5=11223344,x6=1.2,x7=1.23432,x8_0=12312,x8=112233,x9=223344,x10="hq",x12={x1=10,},x13=2,x14={ _name='DemoD2',x1=1,x2=2,},s1={key='/asfa32',text="aabbcc22"},v2={x=1,y=2},v3={x=1.1,y=2.2,z=3.4},v4={x=10.1,y=11.2,z=12.3,w=13.4},t1=-28800,k1={1,2,},k2={2,3,},k5={1,6,},k8={[2]=2,[4]=10,},k9={{y1=1,y2=true,},{y1=2,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=2,},},}, [22] = {x4=22,x1=false,x2=2,x3=128,x5=112233445566,x6=1.3,x7=1122,x8_0=13,x8=12,x9=123,x10="yf",x12={x1=1,},x13=5,x14={ _name='DemoD2',x1=1,x2=3,},s1={key='lua/key1',text="lua text "},v2={x=1,y=2},v3={x=0.1,y=0.2,z=0.3},v4={x=1,y=2,z=3.5,w=4},t1=-28800,k1={1,2,},k2={2,3,},k5={1,3,},k8={[2]=10,[3]=12,},k9={{y1=1,y2=true,},{y1=10,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=3,},},}, }
function Exec() -- Initialize local modem = peripheral.find("modem") if modem == nil then print("Please attach an ender modem to the extra_internal_core computer") return end local modemName = peripheral.getName(modem) rednet.open(modemName) rednet.host(extra.ServiceName(), extra.ServiceHost()) while true do local clientID, msg, protocol = rednet.receive(extra.ServiceName()) local response = nil local ok, err = pcall(function () response = RouteEvent(clientID, msg) end) if not ok then printError(err) rednet.send(clientID, nil, extra.ServiceResponseName()) elseif response ~= nil then rednet.send(clientID, response, extra.ServiceResponseName()) end end end function RouteEvent(clientID, msg) local route = msg.route -- The function being called by the client local req = msg.req -- The data the client sent in the request if route == "Say" then return extra_internal_requests.Say(req, clientID) elseif route == "Msg" then return extra_internal_requests.Msg(req, clientID) elseif route == "GetPlayers" then return extra_internal_requests.GetPlayers(req, clientID) elseif route == "Particle" then return extra_internal_requests.Particle(req, clientID) end end -- Allow this to also detect turtles function ComputerAtPos(compID, x, y, z) local blockData = commands.getBlockInfo(x, y, z) return blockData.nbt ~= nil and blockData.nbt.ComputerId == compID and blockData.nbt.On == 1 end
-- Capsaicin Dependencies VULKAN_SDK = os.getenv("VULKAN_SDK") IncludeDir = {} IncludeDir["stb"] = "%{wks.location}/Capsaicin/vendor/stb" IncludeDir["GLFW"] = "%{wks.location}/Capsaicin/vendor/GLFW/include" IncludeDir["Glad"] = "%{wks.location}/Capsaicin/vendor/Glad/include" IncludeDir["glm"] = "%{wks.location}/Capsaicin/vendor/glm" IncludeDir["shaderc"] = "%{wks.location}/Capsaicin/vendor/shaderc/include" IncludeDir["SPIRV_Cross"] = "%{wks.location}/Capsaicin/vendor/SPIRV-Cross" IncludeDir["VulkanSDK"] = "%{VULKAN_SDK}/Include" LibraryDir = {} LibraryDir["VulkanSDK"] = "%{VULKAN_SDK}/Lib" LibraryDir["VulkanSDK_Debug"] = "%{wks.location}/Capsaicin/vendor/VulkanSDK/Lib" LibraryDir["VulkanSDK_DebugDLL"] = "%{wks.location}/Capsaicin/vendor/VulkanSDK/Bin" Library = {} Library["Vulkan"] = "%{LibraryDir.VulkanSDK}/vulkan-1.lib" Library["VulkanUtils"] = "%{LibraryDir.VulkanSDK}/VkLayer_utils.lib" Library["ShaderC_Debug"] = "%{LibraryDir.VulkanSDK_Debug}/shaderc_sharedd.lib" Library["SPIRV_Cross_Debug"] = "%{LibraryDir.VulkanSDK_Debug}/spirv-cross-cored.lib" Library["SPIRV_Cross_GLSL_Debug"] = "%{LibraryDir.VulkanSDK_Debug}/spirv-cross-glsld.lib" Library["SPIRV_Tools_Debug"] = "%{LibraryDir.VulkanSDK_Debug}/SPIRV-Toolsd.lib" Library["ShaderC_Release"] = "%{LibraryDir.VulkanSDK}/shaderc_shared.lib" Library["SPIRV_Cross_Release"] = "%{LibraryDir.VulkanSDK}/spirv-cross-core.lib" Library["SPIRV_Cross_GLSL_Release"] = "%{LibraryDir.VulkanSDK}/spirv-cross-glsl.lib"
--[[ --------------------------------------------------------------------------- Name: SimpleUnitFrames Author: Pneumatus About: An extension to the default WoW Unit Frames. Rather than a complete unitframe replacement, this addon adds further information and features to the existing frames and allows a greater degree of customization to enhance their usability. ----------------------------------------------------------------------------- ]] local SUF = LibStub("AceAddon-3.0"):GetAddon("SimpleUnitFrames") local L = LibStub("AceLocale-3.0"):GetLocale("SimpleUnitFrames") local CI = SUF:GetModule("ClassIcon", true) local TO = SUF:GetModule("TextOverlay", true) local BT = SUF:GetModule("BarTexture", true) SUF.defaults.profile.player = {} SUF.options.args.player = { type = 'group', name = L["Player Frame"], args = {}, order = 110, } if CI then CI.frameSettings.player = { PlayerFrame, 1.1, { "TOPLEFT", PlayerFrame, "TOPLEFT", 85, -5 } } SUF.defaults.profile.player.icon = true SUF.options.args.player.args.icon = { type = 'toggle', name = L["Display Class Icon"], desc = L["Display a Class Icon on this frame"], get = function(info) return info.handler.db.profile.player.icon end, set = function(info, val) info.handler.db.profile.player.icon = val CI:UpdateClassIcon("player") end, order = 100, } end if TO then TO.frameSettings.player = { parent = PlayerFrame, text = { mhp = { "TOP", PlayerFrameHealthBar, "TOP" }, rhp = { "TOPLEFT", PlayerFrameHealthBar, "TOPRIGHT", 5, 0 }, mmp = { "TOP", PlayerFrameManaBar, "TOP" }, rmp = { "TOPLEFT", PlayerFrameManaBar, "TOPRIGHT", 5, 0 }, }, } SUF.defaults.profile.player.mhp = "HPcurrmax" SUF.defaults.profile.player.rhp = "HPpercent" SUF.defaults.profile.player.mmp = "MPcurrmax" SUF.defaults.profile.player.rmp = "MPpercent" SUF.options.args.player.args.mhp = { type = 'select', name = L["Middle HP"], desc = L["Middle HP Style"], get = function(info) return info.handler.db.profile.player.mhp end, set = function(info, val) info.handler.db.profile.player.mhp = val TO:RefreshFontStrings("player") end, style = 'dropdown', values = TO.formatList.HP, order = 200, } SUF.options.args.player.args.rhp = { type = 'select', name = L["Right HP"], desc = L["Right HP Style"], get = function(info) return info.handler.db.profile.player.rhp end, set = function(info, val) info.handler.db.profile.player.rhp = val TO:RefreshFontStrings("player") end, style = 'dropdown', values = TO.formatList.HP, order = 210, } SUF.options.args.player.args.mmp = { type = 'select', name = L["Middle MP"], desc = L["Middle MP Style"], get = function(info) return info.handler.db.profile.player.mmp end, set = function(info, val) info.handler.db.profile.player.mmp = val TO:RefreshFontStrings("player") end, style = 'dropdown', values = TO.formatList.MP, order = 220, } SUF.options.args.player.args.rmp = { type = 'select', name = L["Right MP"], desc = L["Right MP Style"], get = function(info) return info.handler.db.profile.player.rmp end, set = function(info, val) info.handler.db.profile.player.rmp = val TO:RefreshFontStrings("player") end, style = 'dropdown', values = TO.formatList.MP, order = 230, } -- Disable the default HP/MP text TO:SecureHook(PlayerFrameHealthBar.TextString, "Show", function(f) f:Hide() end) TO:SecureHook(PlayerFrameManaBar.TextString, "Show", function(f) f:Hide() end) end if BT then BT.bars[PlayerFrameHealthBar] = true BT.bars[PlayerFrameManaBar] = true end
local res = ngx.location.capture('/fetch_api', { method = ngx.HTTP_GET, args = {} }); ngx.log(ngx.ERR, res.status); if res.status == ngx.HTTP_OK then ngx.var.api_result = res.body; else ngx.exit(403); end
data.raw["gui-style"]["default"]["ca_frame"] = { type = "frame_style", font = "default-frame", font_color = {r=1, g=1, b=1}, top_padding = 3, right_padding = 3, bottom_padding = 3, left_padding = 3, graphical_set = { type = "composition", filename = "__core__/graphics/gui.png", priority = "extra-high-no-scale", corner_size = {1, 1}, position = {3, 3} }, flow_style = { horizontal_spacing = 0, vertical_spacing = 0 } } data.raw["gui-style"]["default"]["ca_flow"] = { type = "flow_style", horizontal_spacing = 0, vertical_spacing = 0, max_on_row = 0, resize_row_to_width = false, resize_to_row_height = false } data:extend({ { type = "font", name = "font_bold_fre", from = "default-bold", border = false, size = 15 }, }) data.raw["gui-style"]["default"].frame_ca_style = { type="frame_style", parent="frame_style", top_padding = 4, right_padding = 4, bottom_padding = 4, left_padding = 4, resize_row_to_width = true, resize_to_row_height = false, } data.raw["gui-style"]["default"].flow_ca_style = { type = "flow_style", top_padding = 0, bottom_padding = 0, left_padding = 0, right_padding = 0, horizontal_spacing = 2, vertical_spacing = 2, resize_row_to_width = true, resize_to_row_height = false, max_on_row = 1, graphical_set = { type = "none" }, } data.raw["gui-style"]["default"].textfield_ca_style = { type = "textfield_style", font="font_bold_fre", align = "left", font_color = {}, default_font_color= {r=1, g=1, b=1}, hovered_font_color= {r=1, g=1, b=1}, selection_background_color= {r=0.66, g=0.7, b=0.83}, top_padding = 0, bottom_padding = 0, left_padding = 1, right_padding = 0, minimal_width = 200, maximal_width = 200, graphical_set = { type = "composition", filename = "__core__/graphics/gui.png", priority = "extra-high-no-scale", corner_size = {3, 3}, position = {16, 0} }, } data.raw["gui-style"]["default"].button_ca_style = { type="button_style", parent="button_style", font="font_bold_fre", default_font_color= {r=1, g=1, b=1}, hovered_font_color= {r=1, g=1, b=1}, top_padding = 0, right_padding = 4, bottom_padding = 0, left_padding = 4, left_click_sound = { { filename = "__core__/sound/gui-click.ogg", volume = 1 } }, } data.raw["gui-style"]["default"].ca_title_label = { type="label_style", parent="label_style", font="font_bold_fre", align = "left", default_font_color= {r=1, g=1, b=1}, hovered_font_color= {r=1, g=1, b=1}, top_padding = 0, bottom_padding = 0, left_padding = 1, -- I can't figure out how this shitty GUI system works, manually right align this like it's CSS in 1999 -- -- We're a game that encourages modding! Let's not document how anything works! HAHAHAHAHAHA -- When people ask questions give them useless answers or ignore them! -- https://forums.factorio.com/viewtopic.php?f=28&t=38024 -- https://forums.factorio.com/viewtopic.php?f=25&t=28688 minimal_width = 227, maximal_width = 227, }
#!/usr/bin/env tarantool -- -- gh-5632: Lua code should not use any global buffers or objects without -- proper ownership protection. Otherwise these items might be suddenly reused -- during Lua GC which happens almost at any moment. That might lead to data -- corruption. -- local tap = require('tap') local ffi = require('ffi') local uuid = require('uuid') local uri = require('uri') local msgpackffi = require('msgpackffi') local function test_uuid(test) test:plan(1) local gc_count = 100 local iter_count = 1000 local is_success = true local function uuid_to_str() local uu = uuid.new() local str1 = uu:str() local str2 = uu:str() if str1 ~= str2 then is_success = false assert(false) end end local function create_gc() for _ = 1, gc_count do ffi.gc(ffi.new('char[1]'), function() uuid_to_str() end) end end for _ = 1, iter_count do create_gc() uuid_to_str() end test:ok(is_success, 'uuid in gc') end local function test_uri(test) test:plan(1) local gc_count = 100 local iter_count = 1000 local port = 1 local ip = 1 local login = 1 local pass = 1 local is_success = true local function uri_parse() local loc_ip = ip local loc_port = port local loc_pass = pass local loc_login = login ip = ip + 1 port = port + 1 pass = pass + 1 login = login + 1 if port > 60000 then port = 1 end if ip > 255 then ip = 1 end loc_ip = string.format('127.0.0.%s', loc_ip) loc_port = tostring(loc_port) loc_pass = string.format('password%s', loc_pass) loc_login = string.format('login%s', loc_login) local host = string.format('%s:%s@%s:%s', loc_login, loc_pass, loc_ip, loc_port) local u = uri.parse(host) if u.host ~= loc_ip or u.login ~= loc_login or u.service ~= loc_port or u.password ~= loc_pass then is_success = false assert(false) end end local function create_gc() for _ = 1, gc_count do ffi.gc(ffi.new('char[1]'), uri_parse) end end for _ = 1, iter_count do create_gc() uri_parse() end test:ok(is_success, 'uri in gc') end local function test_msgpackffi(test) test:plan(1) local mp_encode = msgpackffi.encode local mp_decode = msgpackffi.decode local gc_count = 100 local iter_count = 1000 local is_success = true local data = {0, 1, 1000, 100000000, 'str', true, 1.1} local function do_encode() if not is_success then return end local t = mp_encode(data) t = mp_decode(t) if #t ~= #data then is_success = false return end for i = 1, #t do if t[i] ~= data[i] then is_success = false return end end end local function create_gc() for _ = 1, gc_count do ffi.gc(ffi.new('char[1]'), do_encode) end end for _ = 1, iter_count do create_gc() do_encode() end test:ok(is_success, 'msgpackffi in gc') end local test = tap.test('gh-5632-gc-buf-reuse') test:plan(3) test:test('uuid in __gc', test_uuid) test:test('uri in __gc', test_uri) test:test('msgpackffi in __gc', test_msgpackffi) os.exit(test:check() and 0 or 1)
function OnInit() print("Gametype: Starting galaxy map level!") Rule_AddInterval("Rule_Init", 0) end function Rule_Init() StartMission() Rule_Remove("Rule_Init") end Events = {}
object_ship_nova_orion_smuggler_light_tier7 = object_ship_shared_nova_orion_smuggler_light_tier7:new { } ObjectTemplates:addTemplate(object_ship_nova_orion_smuggler_light_tier7, "object/ship/nova_orion_smuggler_light_tier7.iff")
local uv = require('luv') local channel = require('coro-channel') local wrapRead = channel.wrapRead local wrapWrite = channel.wrapWrite return function(path, options) local stdin, stdout, stderr local stdio = options.stdio -- If no custom stdio is passed in, create pipes for stdin, stdout, stderr. if not stdio then stdio = {true, true, true} options.stdio = stdio end if stdio then if stdio[1] == true then stdin = uv.new_pipe(false) stdio[1] = stdin end if stdio[2] == true then stdout = uv.new_pipe(false) stdio[2] = stdout end if stdio[3] == true then stderr = uv.new_pipe(false) stdio[3] = stderr end end local exitThread, exitCode, exitSignal local function onExit(code, signal) exitCode = code exitSignal = signal if not exitThread then return end local thread = exitThread exitThread = nil return assert(coroutine.resume(thread, code, signal)) end local handle, pid = uv.spawn(path, options, onExit) if not handle then return nil, pid end -- If the process has exited already, return the cached result. -- Otherwise, wait for it to exit and return the result. local function waitExit() if exitCode then return exitCode, exitSignal end assert(not exitThread, "Already waiting on exit") exitThread = coroutine.running() return coroutine.yield() end local result = {handle = handle, pid = pid, waitExit = waitExit} if stdin then result.stdin = {handle = stdin, write = wrapWrite(stdin)} end if stdout then result.stdout = {handle = stdout, read = wrapRead(stdout)} end if stderr then result.stderr = {handle = stderr, read = wrapRead(stderr)} end return result end
--[[ Play message options to the user. ]] -- Message data. message_number = storage("counter", "message_number") deleted = storage("message", "deleted_" .. message_number) total_messages = storage("message", "__count") prev_message = "" next_message = "" delete_undelete_message = "delete" -- Build the initial options announcements. announcements = { ["3"] = "advanced_options", ["5"] = "repeat_message", ["7"] = "delete_message", ["8"] = "forward_message", ["9"] = "save_message", ["*"] = "help_exit", -- The # key is not included here because the helpexit audio file contains -- both announcements -- so we just announce the * key. } -- More than one message exists, so we might need prev/next announcements. if total_messages > 1 then -- Not on the first message, so we need a prev announcement. if message_number > 1 then announcements["4"] = "prev_message" end -- Not on the last message, so we need a next announcement. if message_number < total_messages then announcements["6"] = "next_message" end end -- If the message is already marked deleted, then change the annoucement option -- to undelete. if deleted == "1" then announcements["7"] = "undelete_message" end return { { action = "play_keys", key_announcements = announcements, keys = { ["2"] = "top:change_folders", ["3"] = "top:advanced_options", ["4"] = "top:prev_message", ["5"] = "top:repeat_message", ["6"] = "top:next_message", ["7"] = "top:delete_undelete_message", ["8"] = "top:forward_message_menu", ["9"] = "top:save_message", ["0"] = "mailbox_options", ["*"] = "top:help", ["#"] = "top:exit exit_extension", }, order = { "4", "3", "5", "6", "7", "8", "9", "*", }, repetitions = profile.menu_repetitions, wait = profile.menu_replay_wait, }, { action = "call_sequence", sequence = "top:exit", }, }
local nvim_lsp = require("lspconfig") --[[ local utils = require("utils") local global = utils.global ]] -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end --Enable completion triggered by <c-x><c-o> buf_set_option("omnifunc", "v:lua.vim.lsp.omnifunc") -- Mappings. local opts = { noremap = true, silent = true } -- See `:help vim.lsp.*` for documentation on any of the below functions buf_set_keymap("n", "gD", "<Cmd>lua vim.lsp.buf.declaration()<CR>", opts) buf_set_keymap("n", "gd", "<Cmd>lua vim.lsp.buf.definition()<CR>", opts) buf_set_keymap("n", "K", "<Cmd>lua vim.lsp.buf.hover()<CR>", opts) buf_set_keymap("n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts) buf_set_keymap("n", "<C-K>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts) buf_set_keymap("n", "<leader>wa", "<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>", opts) buf_set_keymap("n", "<leader>wr", "<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>", opts) buf_set_keymap("n", "<leader>wl", "<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>", opts) buf_set_keymap("n", "<leader>D", "<cmd>lua vim.lsp.buf.type_definition()<CR>", opts) buf_set_keymap("n", "<leader>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts) buf_set_keymap("n", "<leader>ca", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts) buf_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts) buf_set_keymap("n", "<leader>e", "<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>", opts) buf_set_keymap("n", "<leader>re", "<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>", opts) buf_set_keymap("n", "<localleader>n", "<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>", opts) buf_set_keymap("n", "<localleader>p", "<cmd>lua vim.lsp.diagnostic.goto_next()<CR>", opts) buf_set_keymap("n", "<leader>q", "<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>", opts) buf_set_keymap("n", "<leader>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) buf_set_keymap("n", "<leader>T", '<cmd>lua require"lsp_extensions".inlay_hints()<CR>', opts) if client.resolved_capabilities.document_formatting then vim.cmd([[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()]]) end end -- tabnine for cmp local tabnine = require("cmp_tabnine.config") tabnine:setup({ max_lines = 1000, max_num_results = 2, sort = true, run_on_every_keystroke = true, }) local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end local luasnip = require("luasnip") -- Setup nvim-cmp. local cmp = require("cmp") -- Set completeopt to have better completion experience vim.o.completeopt = "menuone,noinsert" cmp.setup({ snippet = { expand = function(args) require("luasnip").lsp_expand(args.body) end, }, mapping = { -- `:help ins-completion` ["<C-d>"] = cmp.mapping.scroll_docs(-4), ["<C-f>"] = cmp.mapping.scroll_docs(4), ["<C-Space>"] = cmp.mapping.complete(), ["<C-e>"] = cmp.mapping.close(), ["<CR>"] = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true, }), -- Add snippet support, fallback to default settings when not in use ["<c-n>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() elseif has_words_before() then cmp.complete() else fallback() end end, { "i", "s", }), ["<c-p>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { "i", "s", }), }, sources = { -- the order of your sources matter (by default). That gives them priority -- you can configure: -- keyword_length -- priority -- max_item_count -- (more?) { name = "luasnip" }, { name = "nvim_lsp" }, { name = "cmp_tabnine", keyword_length = 2 }, { name = "buffer", keyword_length = 5 }, { name = "path", keyword_length = 5 }, -- { name = 'nvim_lua' }, -- { name = "treesitter" }, -- { name = 'calc' }, -- { name = 'emoji' }, -- { name = 'spell' }, }, formatting = { format = function(entry, vim_item) -- fancy icons and a name of kind vim_item.kind = require("lspkind").presets.default[vim_item.kind] .. " " .. vim_item.kind -- set a name for each source vim_item.menu = ({ buffer = "[Buffer]", nvim_lsp = "[LSP]", luasnip = "[LuaSnip]", nvim_lua = "[Lua]", latex_symbols = "[Latex]", cmp_tabnine = "[TN]", })[entry.source.name] return vim_item end, }, experimental = { -- Prettier, menu native_menu = false, -- What's this ghost_text = true, }, }) local system_name if vim.fn.has("mac") == 1 then system_name = "macOS" elseif vim.fn.has("unix") == 1 then system_name = "Linux" elseif vim.fn.has("win32") == 1 then system_name = "Windows" else print("Unsupported system for sumneko") end local runtime_path = vim.split(package.path, ";") table.insert(runtime_path, "lua/?.lua") table.insert(runtime_path, "lua/?/init.lua") local capabilities = require("cmp_nvim_lsp").update_capabilities(vim.lsp.protocol.make_client_capabilities()) capabilities.textDocument.completion.completionItem.snippetSupport = true require("null-ls").setup({ on_attach = on_attach, sources = { require("null-ls").builtins.formatting.stylua, -- null_ls.builtins.formatting.black, -- null_ls.builtins.diagnostics.write_good, -- null_ls.builtins.diagnostics.pylint, }, }) -- Use a loop to conveniently call 'setup' on multiple servers and -- map buffer local keybindings when the language server attaches local servers = { "pylsp", "gopls", "clangd", "html", "cmake", "tsserver" } -- "pyright" for _, lsp in ipairs(servers) do nvim_lsp[lsp].setup({ on_attach = on_attach, flags = { -- debounce_text_changes = 125, }, capabilities = capabilities, }) end -- vim.cmd([[autocmd BufEnter *.crs set filetype=rust]]) require("rust-tools").setup({ server = { on_attach = on_attach, capabilities = capabilities, settings = { ["rust-analyzer"] = { --[[ cargo = { loadOutDirsFromCheck = true, allFeatures = true, }, ]] procMacro = { enable = true, }, checkOnSave = { command = "clippy", }, --[[ rustcSource = "discover", updates = { channel = "nightly", }, ]] }, }, }, })
tusken_death_hunter = Creature:new { objectName = "@mob/creature_names:tusken_death_hunter", socialGroup = "tusken_raider", faction = "tusken_raider", level = 300, chanceHit = 25.0, damageMin = 1450, damageMax = 1850, baseXp = 25000, baseHAM = 100000, baseHAMmax = 110000, armor = 2, resists = {115,115,115,115,115,115,115,115,115}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + KILLER + STALKER, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = {"object/mobile/tusken_raider.iff"}, lootGroups = { { groups = { {group = "trash_rare", chance = 10000000}, }, lootChance = 2000000 }, { groups = { {group = "trash_common", chance = 10000000}, }, lootChance = 10000000 }, { groups = { {group = "weapon_component_advanced", chance = 10000000}, }, lootChance = 7000000 }, { groups = { {group = "tierone", chance = 1500000}, {group = "tiertwo", chance = 3500000}, {group = "tierthree", chance = 2500000}, {group = "tierdiamond", chance = 2500000}, }, lootChance = 3000000 } }, weapons = {"tusken_weapons"}, conversationTemplate = "", attacks = merge(marksmanmaster,brawlermaster,fencermaster,riflemanmaster) } CreatureTemplates:addCreatureTemplate(tusken_death_hunter, "tusken_death_hunter")
ccs = ccs or {} ---RotationFrame object ---@class RotationFrame : Frame local RotationFrame = {} ccs.RotationFrame = RotationFrame -------------------------------- -- ---@param rotation float ---@return RotationFrame function RotationFrame:setRotation(rotation) end -------------------------------- -- ---@return float function RotationFrame:getRotation() end -------------------------------- -- ---@return RotationFrame function RotationFrame:create() end -------------------------------- -- ---@return Frame function RotationFrame:clone() end -------------------------------- -- ---@return RotationFrame function RotationFrame:RotationFrame() end return RotationFrame
-- * Metronome IM * -- -- This file is part of the Metronome XMPP server and is released under the -- ISC License, please see the LICENSE file in this source package for more -- information about copyright and licensing. -- -- As per the sublicensing clause, this file is also MIT/X11 Licensed. -- ** Copyright (c) 2012, Matthew Wild if not module:host_is_muc() then error("mod_muc_limits can only be loaded on a muc component!", 0); end local st = require "util.stanza"; local new_throttle = require "util.throttle".create; local jid_bare = require "util.jid".bare; local jid_section = require "util.jid".section; local jid_split = require "util.jid".split; local math, tonumber, t_insert = math, tonumber, table.insert; local xmlns_muc = "http://jabber.org/protocol/muc"; local period = math.max(module:get_option_number("muc_event_rate", 0.5), 0); local burst = math.max(module:get_option_number("muc_burst_factor", 6), 1); local exclusion_list = module:get_option_set("muc_throttle_host_exclusion"); local parent_host = module:get_option_boolean("muc_whitelist_parent_peers") == true and module.host:match("%.([^%.].*)"); local disconnect_after = module:get_option_number("muc_disconnect_after_throttles", 20); local use_gate_guard = module:get_option_boolean("muc_use_gate_guard", true); local gate_guard_hits = module:get_option_number("muc_gate_guard_max_hits", 150); local gate_guard_time = module:get_option_number("muc_gate_guard_ban_time", 3600); local hosts = metronome.hosts; local host_object = hosts[module.host]; local _parent, _default_period, _default_burst = nil, period*2, burst*10; -- Handlers local function handle_stanza(event) local origin, stanza = event.origin, event.stanza; if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Don't limit room leaving return; end local domain = jid_section(stanza.attr.from, "host"); if exclusion_list and exclusion_list:contains(domain) then module:log("debug", "Skipping stanza from excluded host %s...", domain); return; end if _parent and _parent.events.fire_event("peer-is-subscribed", domain) then module:log("debug", "Skipping stanza from server peer %s...", domain); return; end local dest_room, dest_host, dest_nick = jid_split(stanza.attr.to); local room = host_object.muc and host_object.muc.rooms[dest_room.."@"..dest_host]; if not room then return; end local from_jid = stanza.attr.from; local occupant_jid = room._jid_nick[from_jid]; local occupant = room._occupants[occupant_jid]; if (occupant and occupant.affiliation) or (not(occupant) and room._affiliations[jid_bare(from_jid)]) then module:log("debug", "Skipping stanza from affiliated user..."); return; end local throttle = room.throttle; if not room.throttle then local _period, _burst; if not room:get_option("limits_enabled") then _period, _burst = _default_period, _default_burst; else _period, _burst = room:get_option("limits_seconds") or period, room:get_option("limits_stanzas") or burst; end throttle = new_throttle(_period*_burst, _burst); room.throttle = throttle; end if not throttle:poll(1) then local trigger = origin.muc_limits_trigger; module:log("warn", "Dropping stanza for %s@%s from %s, over rate limit", dest_room, dest_host, from_jid); if stanza.attr.type == "error" then return true; end -- drop errors silently if trigger and trigger >= disconnect_after then room:set_role(true, occupant_jid, "none", nil, "Exceeded number of allowed throttled stanzas"); if origin.type ~= "component" then origin:close{ condition = "policy-violation", text = "Exceeded number of allowed throttled stanzas" }; end return true; end origin.muc_limits_trigger = (not trigger and 1) or trigger + 1; if use_gate_guard and origin.type ~= "component" then module:fire_event("call-gate-guard", { origin = origin, from = from_jid, reason = "MUC Flooding/DoS", ban_time = gate_guard_time, hits = gate_guard_hits } ); end local reply = st.error_reply(stanza, "wait", "policy-violation", "The room is currently overactive, please try again later"); local body = stanza:get_child_text("body"); if body then reply:up():tag("body"):text(body):up(); end local x = stanza:get_child("x", xmlns_muc); if x then reply:add_child(st.clone(x)); end origin.send(reply); return true; end end -- MUC Custom Form local field_enabled = "muc#roomconfig_limits_enabled"; local field_stanzas = "muc#roomconfig_limits_stanzas"; local field_seconds = "muc#roomconfig_limits_seconds"; module:hook("muc-fields", function(room, layout) t_insert(layout, { name = field_enabled, type = "boolean", label = "Enable stanza limits?", value = room:get_option("limits_enabled"); }); t_insert(layout, { name = field_stanzas, type = "text-single", label = "Number of Stanzas", value = tostring(room:get_option("limits_stanzas") or burst); }); t_insert(layout, { name = field_seconds, type = "text-single", label = "Per how many seconds", value = tostring(room:get_option("limits_seconds") or period); }); end, -101); module:hook("muc-fields-process", function(room, fields, stanza, changed) room.throttle = nil; local enabled, stanzas, seconds = fields[field_enabled], fields[field_stanzas], fields[field_seconds]; room:set_option("limits_enabled", enabled, changed); if enabled then if not tonumber(stanzas) or not tonumber(seconds) then return st.error_reply(stanza, "cancel", "forbidden", "You need to submit valid number values for muc_limits fields"); end stanzas, seconds = math.max(tonumber(stanzas), 1), math.max(tonumber(seconds), 0); room:set_option("limits_stanzas", stanzas, changed); room:set_option("limits_seconds", seconds, changed); else room:set_option("limits_stanzas", nil, changed); room:set_option("limits_seconds", nil, changed); end end, -101); function module.unload() local rooms = host_object.muc and host_object.muc.rooms; for room_jid, room in pairs(rooms) do room.throttle = nil; end end module:hook("message/bare", handle_stanza, 100); module:hook("message/full", handle_stanza, 100); module:hook("presence/bare", handle_stanza, 100); module:hook("presence/full", handle_stanza, 100); if parent_host then _parent = hosts[parent_host]; module:hook_global("host-activated", function(host) if host == parent_host then _parent = hosts[host]; end end); module:hook_global("host-deactivated", function(host) if host == parent_host then _parent = nil; end end); end
local rotate_torch_rules = function (rules, param2) if param2 == 5 then return mesecon.rotate_rules_right(rules) elseif param2 == 2 then return mesecon.rotate_rules_right(mesecon.rotate_rules_right(rules)) --180 degrees elseif param2 == 4 then return mesecon.rotate_rules_left(rules) elseif param2 == 1 then return mesecon.rotate_rules_down(rules) elseif param2 == 0 then return mesecon.rotate_rules_up(rules) else return rules end end local output_rules = { {x = 1, y = 0, z = 0}, {x = 0, y = 0, z = 1}, {x = 0, y = 0, z =-1}, {x = 0, y = 1, z = 0}, {x = 0, y =-1, z = 0} } local torch_get_output_rules = function(node) return rotate_torch_rules(output_rules, node.param2) end local input_rules = { {x = -2, y = 0, z = 0}, {x = -1, y = 1, z = 0} } local torch_get_input_rules = function(node) return rotate_torch_rules(input_rules, node.param2) end minetest.register_craft({ output = "moremesecons_switchtorch:switchtorch_off 4", recipe = { {"default:stick"}, {"group:mesecon_conductor_craftable"}, } }) local torch_selectionbox = { type = "wallmounted", wall_top = {-0.1, 0.5-0.6, -0.1, 0.1, 0.5, 0.1}, wall_bottom = {-0.1, -0.5, -0.1, 0.1, -0.5+0.6, 0.1}, wall_side = {-0.5, -0.1, -0.1, -0.5+0.6, 0.1, 0.1}, } minetest.register_node("moremesecons_switchtorch:switchtorch_off", { description = "Switch Torch", inventory_image = "moremesecons_switchtorch_on.png", wield_image = "moremesecons_switchtorch_on.png", drawtype = "torchlike", tiles = {"moremesecons_switchtorch_off.png", "moremesecons_switchtorch_off_ceiling.png", "moremesecons_switchtorch_off_side.png"}, paramtype = "light", walkable = false, paramtype2 = "wallmounted", selection_box = torch_selectionbox, groups = {dig_immediate = 3}, mesecons = {receptor = { state = mesecon.state.off, rules = torch_get_output_rules }}, on_construct = function(pos)-- For EndPower minetest.get_meta(pos):set_int("EndPower", 1) -- 1 for true, 0 for false end }) minetest.register_node("moremesecons_switchtorch:switchtorch_on", { drawtype = "torchlike", tiles = {"moremesecons_switchtorch_on.png", "moremesecons_switchtorch_on_ceiling.png", "moremesecons_switchtorch_on_side.png"}, paramtype = "light", sunlight_propagates = true, walkable = false, paramtype2 = "wallmounted", selection_box = torch_selectionbox, groups = {dig_immediate=3, not_in_creative_inventory = 1}, drop = "moremesecons_switchtorch:switchtorch_off", light_source = 9, mesecons = {receptor = { state = mesecon.state.on, rules = torch_get_output_rules }}, }) minetest.register_abm({ nodenames = {"moremesecons_switchtorch:switchtorch_off","moremesecons_switchtorch:switchtorch_on"}, interval = 1, chance = 1, action = function(pos, node) local is_powered = false for _, rule in ipairs(torch_get_input_rules(node)) do local src = vector.add(pos, rule) if mesecon.is_power_on(src) then is_powered = true break end end local meta = minetest.get_meta(pos) if meta:get_int("EndPower") == 0 == is_powered then return end if not is_powered then meta:set_int("EndPower", 1) return end if node.name == "moremesecons_switchtorch:switchtorch_on" then minetest.swap_node(pos, {name = "moremesecons_switchtorch:switchtorch_off", param2 = node.param2}) mesecon.receptor_off(pos, torch_get_output_rules(node)) elseif node.name == "moremesecons_switchtorch:switchtorch_off" then minetest.swap_node(pos, {name = "moremesecons_switchtorch:switchtorch_on", param2 = node.param2}) mesecon.receptor_on(pos, torch_get_output_rules(node)) end meta:set_int("EndPower", 0) end }) -- Param2 Table (Block Attached To) -- 5 = z-1 -- 3 = x-1 -- 4 = z+1 -- 2 = x+1 -- 0 = y+1 -- 1 = y-1
module 'mock' local function buildGammaShader() local vsh = [[ attribute vec4 position; attribute vec2 uv; attribute vec4 color; varying LOWP vec4 colorVarying; varying MEDP vec2 uvVarying; void main () { gl_Position = position; uvVarying = uv; colorVarying = color; } ]] local fsh = [[ varying LOWP vec4 colorVarying; varying MEDP vec2 uvVarying; uniform float gamma; uniform sampler2D sampler; void main () { LOWP vec4 color = texture2D ( sampler, uvVarying ); gl_FragColor.rgb = pow(color.rgb, vec3(1.0/gamma) ); } ]] local prog = buildShaderProgramFromString( vsh, fsh , { uniforms = { { name = "sampler", type = "sampler", value = 1 }, { name = "gamma", type = "float", value = 1.0 } } } ) return prog:buildShader() end -------------------------------------------------------------------- CLASS: CameraImageEffectGamma ( CameraImageEffect ) :MODEL{ Field 'gamma' :onset( 'updateParam' ) :meta{ step = 0.1 }; } function CameraImageEffectGamma:__init() self.gamma = 1.8 self.shader = false end function CameraImageEffectGamma:onBuild( prop, layer ) self.shader = buildGammaShader() prop:setShader( self.shader:getMoaiShader() ) self:updateParam() end function CameraImageEffectGamma:updateParam() if not self.shader then return end self.shader:setAttr( 'gamma', self.gamma ) end mock.registerComponent( 'CameraImageEffectGamma', CameraImageEffectGamma )
-------------------------------------------------------------------------------- -- Радиостанция типа "Моторола" -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Metrostroi.DefineSystem("Motorola") TRAIN_SYSTEM.DontAccelerateSimulation = true function TRAIN_SYSTEM:Initialize() self.Train:LoadSystem("MotorolaF1","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaMenu","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaF2","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaOff","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaUp","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaDown","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaLeft","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaRight","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaOn","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola1","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola2","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola3","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola4","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola5","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola6","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola7","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola8","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola9","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola*","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola0","Relay","Switch",{button = true}) self.Train:LoadSystem("Motorola#","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaF4","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaF5","Relay","Switch",{button = true}) self.Train:LoadSystem("MotorolaF6","Relay","Switch",{button = true}) self.TriggerNames = { "MotorolaF1", "MotorolaMenu", "MotorolaF2", "MotorolaOff", "MotorolaUp", "MotorolaDown", "MotorolaLeft", "MotorolaRight", "MotorolaOn", "Motorola1", "Motorola2", "Motorola3", "Motorola4", "Motorola5", "Motorola6", "Motorola7", "Motorola8", "Motorola9", "Motorola*", "Motorola0", "Motorola#", "MotorolaF4", "MotorolaF5", "MotorolaF6", } self.Enabled = true self.Triggers = {} self.Timer = CurTime() self.State = 0 self.RealState = 99 self.RouteNumber = "" self.FirstStation = "" self.LastStation = "" self.Bright = 1 self.MenuChoosed = 0 self.AnnMenuChoosed = 0 self.Mode = 0 self.Mode1 = 0 end function TRAIN_SYSTEM:ClientInitialize() end if TURBOSTROI then return end function TRAIN_SYSTEM:Inputs() return { "Press" } end if CLIENT then local gr_up = Material("vgui/gradient-d") function TRAIN_SYSTEM:Motorola(train) surface.SetAlphaMultiplier(1) draw.NoTexture() if train:GetNW2Int("Motorola:State",-1) >= 0 then surface.SetDrawColor(Color(20,20,20)) surface.DrawRect(0,0,140,107) else surface.SetDrawColor(Color(0,0,0)) surface.DrawRect(0,0,140,107) end --surface.SetAlphaMultiplier(train:GetNW2Int("Motorola:Bright",1)) if train:GetNW2Int("Motorola:State",-1) == 1 then surface.SetDrawColor(Color(255,255,255)) surface.DrawRect(0,0,94,107) surface.SetDrawColor(Color(139,200,235)) surface.DrawRect(94,0,46,107) Metrostroi.DrawLine(7, 2, 10, 5,Color(0,0,0),1) Metrostroi.DrawLine(10, 1, 10, 9,Color(0,0,0),1) Metrostroi.DrawLine(13, 2, 10, 5,Color(0,0,0),1) Metrostroi.DrawLine(16, 8, 16, 9,Color(060,240,106),1) Metrostroi.DrawLine(18, 6, 18, 9,Color(060,240,106),1) Metrostroi.DrawLine(20, 4, 20, 9,Color(060,240,106),1) Metrostroi.DrawLine(22, 2, 22, 9,Color(060,240,106),1) if not train:GetNW2Bool("Motorola:Menu",false) and train:GetNW2Int("Motorola:Mode",0) == 0 then local RouteNumber = train:GetNW2Int("Motorola:RouteNumber",-1) > -1 and tostring(train:GetNW2Int("Motorola:RouteNumber")) or "N/A" draw.SimpleText(train:EntIndex().."/"..RouteNumber,"Metrostroi_PAM1_20",47, 30,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("Folder 1","Metrostroi_PAM1_20",47, 48,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("TRL "..(train:GetNW2Int("Motorola:Line",0) > 0 and train:GetNW2Int("Motorola:Line") or "N/A"),"Metrostroi_PAM1_20",47, 66,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText(os.date("!%d-%m-%y %H.%M",os.time()),"Metrostroi_PAM15",47, 82,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("DURA","Metrostroi_PAM15",117, 23,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) Metrostroi.DrawLine(94, 47, 140, 47,Color(89,150,175),1) draw.SimpleText("Menu","Metrostroi_PAM15",117, 53,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("Annou-","Metrostroi_PAM15",117, 77,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("nces ","Metrostroi_PAM15",117, 89,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) Metrostroi.DrawLine(94, 61, 140, 61,Color(89,150,175),1) elseif train:GetNW2Int("Motorola:Mode",0) == 0 then Metrostroi.DrawRectOL(1,13*1, 93, 13,Color(89,150,175),1,Color(139,200,235)) draw.SimpleText("Main Menu","Metrostroi_PAM15",46, 6+13*1,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) --surface.DrawRect(0,13*1,94,13) surface.SetDrawColor(Color(255,255,255)) surface.DrawRect(94,47,46,14) draw.SimpleText("Back","Metrostroi_PAM15",117, 23,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("Select","Metrostroi_PAM15",117, 83,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) surface.SetDrawColor(Color(103,178,209)) surface.DrawRect(11,1+13*(2+train:GetNW2Int("Motorola:MenuChoosed",0)) , 83, 13) draw.SimpleText("UPO","Metrostroi_PAM15",13, 7+13*2,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) draw.SimpleText("Route number","Metrostroi_PAM15",13, 7+13*3,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) draw.SimpleText("Announces","Metrostroi_PAM15",13, 7+13*4,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) draw.SimpleText("DURA","Metrostroi_PAM15",13, 7+13*5,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) else surface.SetDrawColor(Color(255,255,255)) if train:GetNW2Int("Motorola:Mode",0) == 2 then surface.DrawRect(94,47,46,60) else surface.DrawRect(94,47,46,14) end draw.SimpleText("Back","Metrostroi_PAM15",117, 23,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) if train:GetNW2Int("Motorola:Mode",0) == 1 then draw.SimpleText("OK","Metrostroi_PAM15",117, 83,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end if train:GetNW2Int("Motorola:Mode",0) == 1 then local Line = train:GetNW2Int("Motorola:Line",-1) > -1 and tostring(train:GetNW2Int("Motorola:Line")) or "" local FirstStation = train:GetNW2Int("Motorola:FirstStation",-1) > -1 and tostring(train:GetNW2Int("Motorola:FirstStation")) or "" local LastStation = train:GetNW2Int("Motorola:LastStation",-1) > -1 and tostring(train:GetNW2Int("Motorola:LastStation")) or "" Metrostroi.DrawRectOL(1,13 + 32*0, 93, 13,Color(89,150,175),1,Color(139,200,235)) draw.SimpleText("Line","Metrostroi_PAM15",46, 19+32*0,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText(Line,"Metrostroi_PAM1_20",5, 35 + 32*0,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) if train:GetNW2Int("Motorola:Mode1",0) == 0 and CurTime()%0.5>0.25 then Metrostroi.DrawLine(5 +9*#Line, 40 + 32*0, 15+9*#Line, 40 + 32*0,Color(0,0,0),2) end Metrostroi.DrawRectOL(1,13 + 32*1, 93, 13,Color(89,150,175),1,Color(139,200,235)) draw.SimpleText("First station","Metrostroi_PAM15",46, 19+32*1,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText(FirstStation,"Metrostroi_PAM1_20",5, 35 + 32*1,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) if train:GetNW2Int("Motorola:Mode1",0) == 1 and CurTime()%0.5>0.25 then Metrostroi.DrawLine(5 +9*#FirstStation, 40 + 32*1, 15+9*#FirstStation, 40 + 32*1,Color(0,0,0),2) end Metrostroi.DrawRectOL(1,13 + 32*2, 93, 13,Color(89,150,175),1,Color(139,200,235)) draw.SimpleText("Last station","Metrostroi_PAM15",46, 19+32*2,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText(LastStation,"Metrostroi_PAM1_20",5, 35 + 32*2,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) if train:GetNW2Int("Motorola:Mode1",0) == 2 and CurTime()%0.5>0.25 then Metrostroi.DrawLine(5 +9*#LastStation, 40 + 32*2, 15+9*#LastStation, 40 + 32*2,Color(0,0,0),2) end end if train:GetNW2Int("Motorola:Mode",0) == 2 then Metrostroi.DrawRectOL(1,13*1, 93, 13,Color(89,150,175),1,Color(139,200,235)) draw.SimpleText("Route number","Metrostroi_PAM15",46, 6+13*1,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) local RouteNumber = train:GetNW2Int("Motorola:RouteNumber",-1) > -1 and tostring(train:GetNW2Int("Motorola:RouteNumber")) or "" draw.SimpleText(RouteNumber,"Metrostroi_PAM1_20",5, 35,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) if CurTime()%0.5>0.25 then Metrostroi.DrawLine(5 +9*#RouteNumber, 40, 15+9*#RouteNumber, 40,Color(0,0,0),2) end end if train:GetNW2Int("Motorola:Mode",0) == 3 then Metrostroi.DrawRectOL(1,13*1, 93, 13,Color(89,150,175),1,Color(139,200,235)) draw.SimpleText("Announces","Metrostroi_PAM15",46, 6+13*1,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) --surface.DrawRect(0,13*1,94,13) surface.SetDrawColor(Color(255,255,255)) surface.DrawRect(94,47,46,14) draw.SimpleText("Back","Metrostroi_PAM15",117, 23,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("Play","Metrostroi_PAM15",117, 83,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) surface.SetDrawColor(Color(103,178,209)) surface.DrawRect(3,1+13*(2+train:GetNW2Int("Motorola:AnnMenuChoosed",0)) , 88, 13) draw.SimpleText("Go out from tr..","Metrostroi_PAM15",5, 7+13*2,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) draw.SimpleText("Go faster","Metrostroi_PAM15",5, 7+13*3,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) draw.SimpleText("Release doors","Metrostroi_PAM15",5, 7+13*4,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) draw.SimpleText("Train dep. soon","Metrostroi_PAM15",5, 7+13*5,Color(0,0,0,255),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER) end if train:GetNW2Int("Motorola:Mode",0) == 4 then Metrostroi.DrawRectOL(1,13*1, 93, 13,Color(89,150,175),1,Color(139,200,235)) draw.SimpleText("Dura control","Metrostroi_PAM15",46, 6+13*1,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) --surface.DrawRect(0,13*1,94,13) surface.SetDrawColor(Color(255,255,255)) surface.DrawRect(94,47,46,14) draw.SimpleText("Back","Metrostroi_PAM15",117, 23,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("Send","Metrostroi_PAM15",117, 78,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) local Sel = train:GetNW2Bool("Motorola:DURAs", false) local DURA1 = train:GetNW2Bool("Motorola:DURA1", false) local DURA2 = train:GetNW2Bool("Motorola:DURA2", false) if not Sel and DURA1 or Sel and DURA2 then draw.SimpleText("Main","Metrostroi_PAM15",117, 88,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) else draw.SimpleText("Alter","Metrostroi_PAM15",117, 88,Color(0,0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end draw.SimpleText("1","Metrostroi_PAM1_20",22, 40,Color(0,not Sel and 200 or 0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) if not Sel and CurTime()%0.5>0.25 then Metrostroi.DrawLine(18, 47, 28, 47,Color(0,0,0),2) end Metrostroi.DrawLine(15,50, 15, 70,Color(DURA1 and 0 or 200,0,0),2) Metrostroi.DrawLine(15,71, 29, 50,Color(DURA1 and 200 or 0,0,0),2) Metrostroi.DrawLine(15,70, 15, 90,Color(200,0,0),2) draw.SimpleText("2","Metrostroi_PAM1_20",67, 40,Color(0,Sel and 200 or 0,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) if Sel and CurTime()%0.5>0.25 then Metrostroi.DrawLine(63, 47, 73, 47,Color(0,0,0),2) end Metrostroi.DrawLine(60,50, 60, 70,Color(DURA2 and 0 or 200,0,0),2) Metrostroi.DrawLine(60,71, 74, 50,Color(DURA2 and 200 or 0,0,0),2) Metrostroi.DrawLine(60,70, 60, 90,Color(200,0,0),2) end end end surface.SetAlphaMultiplier(1-train:GetNW2Int("Motorola:Bright",1)) surface.SetDrawColor(Color(20,20,20)) surface.DrawRect(0,0,145,110) surface.SetAlphaMultiplier(1) end function TRAIN_SYSTEM:ClientThink() end end function TRAIN_SYSTEM:UpdateUPO() for k,v in pairs(self.Train.WagonList) do if v.UPO then v.UPO:SetStations(self.Line,self.FirstStation,self.LastStation,v == self.Train) end v:OnButtonPress("RouteNumberUpdate",self.RouteNumber) end end function TRAIN_SYSTEM:Trigger(name) if self.Mode == 0 then if self.Menu then if name == "MotorolaF1" then self.Menu = false end if name == "MotorolaUp" then self.MenuChoosed = math.max(0,self.MenuChoosed - 1) end if name == "MotorolaDown" then self.MenuChoosed = math.min(3,self.MenuChoosed + 1) end if name == "MotorolaF2" then self.Mode = self.MenuChoosed + 1 if self.Mode == 3 then self.AnnChoosed = 0 end end local Char = tonumber(name:sub(9,9)) if Char and Char > 0 and Char < 5 then self.Mode = Char end else if name == "MotorolaF2" then self.Mode = 3 self.AnnChoosed = 0 end if name == "MotorolaF1" then self.Mode = 4 end if name == "MotorolaMenu" then self.Menu = true self.MenuChoosed = 0 end end else if self.Mode == 1 then if name == "MotorolaUp" then self.Mode1 = math.max(0,self.Mode1 - 1) end if name == "MotorolaDown" then self.Mode1 = math.min(2,self.Mode1 + 1) end if name == "MotorolaLeft" then if self.Mode1 == 1 then self.FirstStation= self.FirstStation:sub(1,-2) end if self.Mode1 == 2 then self.LastStation= self.LastStation:sub(1,-2) end self:UpdateUPO() end local Char = tonumber(name:sub(9,9)) if Char then if self.Mode1 == 0 then self.Line = Char if Metrostroi.WorkingStations[self.Line] then local Routelength = #Metrostroi.WorkingStations[self.Line] self.FirstStation = tostring(Metrostroi.WorkingStations[self.Line][1]) self.LastStation = tostring(Metrostroi.WorkingStations[self.Line][Routelength]) end end if self.Mode1 == 1 and #self.FirstStation < 3 and (Char ~= 0 or #self.FirstStation > 0) then self.FirstStation= self.FirstStation..tostring(Char) end if self.Mode1 == 2 and #self.LastStation < 3 and (Char ~= 0 or #self.LastStation > 0) then self.LastStation= self.LastStation..tostring(Char) end self:UpdateUPO() end if name == "MotorolaF2" then if not Metrostroi.WorkingStations[self.Line] or not Metrostroi.WorkingStations[self.Line][tonumber(self.FirstStation)] or not Metrostroi.AnnouncerData[tonumber(self.FirstStation)] or not Metrostroi.WorkingStations[self.Line][tonumber(self.LastStation)] or not Metrostroi.AnnouncerData[tonumber(self.LastStation)] then self.Error = not self.Error else if not self.Error then self.Mode = 0 else self.Error = false end end end --[[ if name == "MotorolaLeft" then self.RouteNumber= self.RouteNumber:sub(1,-2) self.Train:OnButtonPress("RouteNumberUpdate",self.RouteNumber) end local Char = tonumber(name:sub(9,9)) if Char and self.RouteNumber and #self.RouteNumber < 3 then self.RouteNumber= self.RouteNumber..tostring(Char) self.Train:OnButtonPress("RouteNumberUpdate",self.RouteNumber) end]] end if self.Mode == 2 then if name == "MotorolaLeft" then self.RouteNumber= self.RouteNumber:sub(1,-2) self.Train:OnButtonPress("RouteNumberUpdate",self.RouteNumber) end local Char = tonumber(name:sub(9,9)) if Char and self.RouteNumber and #self.RouteNumber < 3 then self.RouteNumber= self.RouteNumber..tostring(Char) self.Train:OnButtonPress("RouteNumberUpdate",self.RouteNumber) end end if self.Mode == 3 then if name == "MotorolaUp" then self.AnnMenuChoosed = math.max(0,self.AnnMenuChoosed - 1) end if name == "MotorolaDown" then self.AnnMenuChoosed = math.min(3,self.AnnMenuChoosed + 1) end if name == "MotorolaF2" then self.Mode = 0 self.Train.UPO:II(self.AnnMenuChoosed+1) end local Char = tonumber(name:sub(9,9)) if Char and Char > 0 and Char < 5 and self.Train.R_UPO.Value > 0 then self.Mode = 0 self.Train.UPO:II(Char) self.AnnChoosed = 0 end end if self.Mode == 4 then if name == "MotorolaLeft" then self.Train.DURA:TriggerInput("SelectChannel",1) end if name == "MotorolaRight" then self.Train.DURA:TriggerInput("SelectChannel",2) end local Char = tonumber(name:sub(9,9)) if Char and Char > 0 and Char < 3 then self.Train.DURA:TriggerInput("SelectChannel",Char) if self.Train.DURA.Channel == 1 then if self.Train.DURA.Channel1Alternate then self.Train.DURA:TriggerInput("SelectMain",1) else self.Train.DURA:TriggerInput("SelectAlternate",1) end end if self.Train.DURA.Channel == 2 then if self.Train.DURA.Channel2Alternate then self.Train.DURA:TriggerInput("SelectMain",1) else self.Train.DURA:TriggerInput("SelectAlternate",1) end end end if name == "MotorolaF2" then if self.Train.DURA.Channel == 1 then if self.Train.DURA.Channel1Alternate then self.Train.DURA:TriggerInput("SelectMain",1) else self.Train.DURA:TriggerInput("SelectAlternate",1) end end if self.Train.DURA.Channel == 2 then if self.Train.DURA.Channel2Alternate then self.Train.DURA:TriggerInput("SelectMain",1) else self.Train.DURA:TriggerInput("SelectAlternate",1) end end end end if name == "MotorolaF1" then if not self.Error then self.Mode = 0 else self.Error = false end end end if name == "MotorolaF6" then self.Bright = self.Bright + 0.25 if self.Bright > 1 then self.Bright = 0 end end end function TRAIN_SYSTEM:GetTimer(val) return self.TimerMod and (CurTime() - self.Timer) > val end function TRAIN_SYSTEM:SetTimer(mod) if mod then if self.TimerMod == mod then return end self.TimerMod = mod else self.TimerMod = nil end self.Timer = CurTime() end function TRAIN_SYSTEM:SetState(state,add,state9) local Train = self.Train local ARS = Train.ALS_ARS local Announcer = Train.Announcer if state and self.State ~= state then self.State = state if state == 1 or state == 1.1 then self.NextState = add end self:SetTimer() elseif not state then state = self.NextState self.State = self.NextState else return end if state == 1 then self.Bright = 1 end end function TRAIN_SYSTEM:Think(dT) local Train = self.Train local ARS = Train.ALS_ARS local Announcer = Train.Announcer if Train.MotorolaOff.Value >0.5 and not self.OffTimer and not self.OnTimer then --self.VPA and if self.Enabled then self.OffTimer = CurTime() + 1 else self.Enabled = true end end if self.OffTimer and (CurTime() - self.OffTimer) > 0 then self.Enabled = false end if Train.MotorolaOff.Value <0.5 and self.OffTimer then self.OffTimer = nil end if Train.Panel["V1"] < 0.5 or Train.VB.Value < 0.5 then self:SetState(-1) end if not self.Enabled then self:SetState(-1) end if self.Enabled and self.State == -1 and Train.Panel["V1"] > 0.5 and Train.VB.Value > 0.5 then self:SetState(0) end --self.Train.UPO.Station = self.Train:ReadCell(49160) > 0 and self.Train:ReadCell(49160) or self.Train:ReadCell(49161) --self.Train.UPO.Path = self.Train:ReadCell(49170) --self.Train.UPO.Distance = math.min(9999,self.Train:ReadCell(49165) + (Train.Autodrive.Corrections[self.Train.UPO.Station] or 0)) if Train.VB.Value > 0.5 and Train.Battery.Voltage > 55 and self.State > 0 then for k,v in pairs(self.TriggerNames) do if Train[v] and (Train[v].Value > 0.5) ~= self.Triggers[v] then if Train[v].Value > 0.5 then self:Trigger(v) end --print(v,self.Train[v].Value > 0.5) self.Triggers[v] = Train[v].Value > 0.5 end end end if self.State == 0 then self:SetTimer(1) if self:GetTimer(3) then self:SetState(1) end end if self.State ~= self.RealState then self.RealState = self.State self.TimeOverride = true end self.Time = self.Time or CurTime() if (CurTime() - self.Time) > 0.1 or self.TimeOverride then self.TimeOverride = nil --print(1) self.Time = CurTime() Train:SetNW2Int("Motorola:State",self.State) Train:SetNW2Int("Motorola:Line",Train.UPO.Line) Train:SetNW2Int("Motorola:RouteNumber",tonumber(self.RouteNumber ~= "" and self.RouteNumber or -1)) Train:SetNW2Int("Motorola:Bright",self.Bright) Train:SetNW2Bool("Motorola:Menu",self.Menu == true) Train:SetNW2Int("Motorola:MenuChoosed",self.MenuChoosed) Train:SetNW2Int("Motorola:Mode",self.Mode) Train:SetNW2Bool("Motorola:Error",self.Error) if self.Mode == 1 then Train:SetNW2Int("Motorola:Mode1",self.Mode1) Train:SetNW2Int("Motorola:FirstStation",tonumber(self.FirstStation ~= "" and self.FirstStation or -1)) Train:SetNW2Int("Motorola:LastStation",tonumber(self.LastStation ~= "" and self.LastStation or -1)) elseif self.Mode == 2 then elseif self.Mode == 3 then Train:SetNW2Int("Motorola:AnnMenuChoosed",self.AnnMenuChoosed) elseif self.Mode == 4 then Train:SetNW2Int("Motorola:DURAs",self.Train.DURA.Channel == 2) Train:SetNW2Int("Motorola:DURA1",self.Train.DURA.Channel1Alternate) Train:SetNW2Int("Motorola:DURA2",self.Train.DURA.Channel2Alternate) end end self.RouteNumber = string.gsub(Train.RouteNumber or "","^(0+)","") self.Line = Train.UPO.Line self.FirstStation = tostring(Train.UPO.FirstStation or "") self.LastStation = tostring(Train.UPO.LastStation or "") self.RealState = self.State end
local helpers = require('test.functional.helpers')(after_each) local eq = helpers.eq local eval = helpers.eval local feed = helpers.feed local clear = helpers.clear local expect = helpers.expect local command = helpers.command local funcs = helpers.funcs local meths = helpers.meths local insert = helpers.insert local curbufmeths = helpers.curbufmeths before_each(clear) describe('macros', function() it('can be recorded and replayed', function() feed('qiahello<esc>q') expect('hello') eq('ahello', eval('@i')) feed('@i') expect('hellohello') eq('ahello', eval('@i')) end) it('applies maps', function() command('imap x l') command('nmap l a') feed('qilxxx<esc>q') expect('lll') eq('lxxx', eval('@i')) feed('@i') expect('llllll') eq('lxxx', eval('@i')) end) it('can be replayed with Q', function() insert [[hello hello hello]] feed [[gg]] feed [[qqAFOO<esc>q]] eq({'helloFOO', 'hello', 'hello'}, curbufmeths.get_lines(0, -1, false)) feed[[Q]] eq({'helloFOOFOO', 'hello', 'hello'}, curbufmeths.get_lines(0, -1, false)) feed[[G3Q]] eq({'helloFOOFOO', 'hello', 'helloFOOFOOFOO'}, curbufmeths.get_lines(0, -1, false)) end) end) describe('immediately after a macro has finished executing,', function() before_each(function() command([[let @a = 'gg0']]) end) describe('reg_executing() from RPC returns an empty string', function() it('if the macro does not end with a <Nop> mapping', function() feed('@a') eq('', funcs.reg_executing()) end) it('if the macro ends with a <Nop> mapping', function() command('nnoremap 0 <Nop>') feed('@a') eq('', funcs.reg_executing()) end) end) describe('characters from a mapping are not treated as a part of the macro #18015', function() before_each(function() command('nnoremap s qa') end) it('if the macro does not end with a <Nop> mapping', function() feed('@asq') -- "q" from "s" mapping should start recording a macro instead of being no-op eq({mode = 'n', blocking = false}, meths.get_mode()) expect('') eq('', eval('@a')) end) it('if the macro ends with a <Nop> mapping', function() command('nnoremap 0 <Nop>') feed('@asq') -- "q" from "s" mapping should start recording a macro instead of being no-op eq({mode = 'n', blocking = false}, meths.get_mode()) expect('') eq('', eval('@a')) end) end) end) describe('reg_recorded()', function() it('returns the correct value', function() feed [[qqyyq]] eq('q', eval('reg_recorded()')) end) end)
local Class = require 'lib.hump.class' local Frame = getClass 'wyx.ui.Frame' local CheckButton = getClass 'wyx.ui.CheckButton' local Button = getClass 'wyx.ui.Button' local Text = getClass 'wyx.ui.Text' local TextEntry = getClass 'wyx.ui.TextEntry' local property = require 'wyx.component.property' local command = require 'wyx.ui.command' local depths = require 'wyx.system.renderDepths' local floor = math.floor local gsub = string.gsub local match = string.match local format = string.format local DEFAULT_NAME = 'Unnamed Adventurer' -- events local InputCommandEvent = getClass 'wyx.event.InputCommandEvent' -- CreateCharUI local CreateCharUI = Class{name='CreateCharUI', inherits=Frame, function(self, ui) verify('table', ui) Frame.construct(self, 0, 0, WIDTH, HEIGHT) self:setDepth(depths.menu) self._name = DEFAULT_NAME if ui and ui.keys then UISystem:registerKeys(ui.keysID, ui.keys) self._uikeys = true end self._ui = ui self:_makePanel() end } -- destructor function CreateCharUI:destroy() if self._uikeys then UISystem:unregisterKeys(self._ui.keysID) self._uikeys = nil end if self._checkButtons then for i=1,#self._checkButtons do self._checkButtons[i] = nil end self._checkButtons = nil end for k in pairs(self._charTable) do self._charTable[k] = nil end self._charTable = nil self._ui = nil self._selectedChar = nil self._name = nil self._nameText = nil Frame.destroy(self) end -- make the panel function CreateCharUI:_makePanel() local ui = self._ui local f = Frame(ui.panel.x, ui.panel.y, ui.panel.w, ui.panel.h) f:setNormalStyle(ui.panel.normalStyle) self:addChild(f) self._panel = f f = Frame(ui.innerpanel.x, ui.innerpanel.y, ui.innerpanel.w, ui.innerpanel.h) self._panel:addChild(f) self._innerPanel = f self:_makeCharButtons() self:_makeButtons() self:_makeNamePanel() end -- make the buttons to choose the char function CreateCharUI:_makeCharButtons() local ui = self._ui self:_loadCharTable() if self._charTable then local x, y = 0, 0 local dx = ui.charbutton.w + ui.innerpanel.hmargin local dy = ui.charbutton.h + ui.innerpanel.vmargin local num = #self._charTable for i=1,num do local info = self._charTable[i] local btn = CheckButton(x, y, ui.charbutton.w, ui.charbutton.h) btn:setNormalStyle(ui.charbutton.normalStyle) btn:setHoverStyle(ui.charbutton.hoverStyle) btn:setActiveStyle(ui.charbutton.activeStyle) btn:setMaxLines(2) btn:setMargin(ui.charbutton.margin) local gender = info.variation == 1 and 'Male' or 'Female' btn:setText({info.name, gender}) btn:setJustifyRight() local icon = self:_makeIcon(info) if icon then btn:addChild(icon) end btn:setCheckedCallback(function(checked) if checked then self._selectedChar = info self:_uncheckAllBut(btn) end end) self._innerPanel:addChild(btn) self._checkButtons = self._checkButtons or {} self._checkButtons[#self._checkButtons + 1] = btn x = x + dx if x + dx > ui.innerpanel.w then x = 0 y = y + dy end end end end function CreateCharUI:_uncheckAllBut(btn) if self._checkButtons then local num = #self._checkButtons for i=1,num do local button = self._checkButtons[i] if button ~= btn then button:uncheck() end end end end function CreateCharUI:_makeIcon(info) if not (info.components and info.components.GraphicsComponent) then return nil end local ui = self._ui local gc = info.components.GraphicsComponent local tileset = gc[property('TileSet')] or property.default('TileSet') local image = Image[tileset] local size = gc[property('TileSize')] or property.default('TileSize') local coords = gc[property('TileCoords')] or property.default('TileCoords') local which = coords.front or coords.left or coords.right if not which then for k in pairs(coords) do which = coords[k] break end end if which then local x, y = (which[1] - 1)*size, (which[2] - 1)*size local icon = Frame(ui.icon.x, ui.icon.y, ui.icon.w, ui.icon.h) local normalStyle = ui.icon.normalStyle:clone({fgimage = image}) normalStyle:setFGQuad(x, y, size, size) icon:setNormalStyle(normalStyle) return icon end end function CreateCharUI:_loadCharTable() self._charTable = {} local count = 0 for char,info in HeroDB:iterate() do count = count + 1 self._charTable[count] = info end table.sort(self._charTable, function(a, b) if a == nil then return true end if b == nil then return false end if a.name == nil then return true end if b.name == nil then return false end if a.name == b.name then return a.variation < b.variation end return a.name < b.name end) end -- make the buttons function CreateCharUI:_makeButtons() local ui = self._ui local num = #ui.buttons local x = floor(ui.innerpanel.w/2) x = x - floor((ui.button.w + floor(ui.innerpanel.hmargin/2)) * num/2) local y = ui.innerpanel.h - (ui.button.h + ui.innerpanel.vmargin) local dx = ui.button.w + ui.innerpanel.hmargin for i=1,num do local info = ui.buttons[i] local btn = Button(x, y, ui.button.w, ui.button.h) btn:setNormalStyle(ui.button.normalStyle) btn:setHoverStyle(ui.button.hoverStyle) btn:setActiveStyle(ui.button.activeStyle) btn:setText(info[1]) btn:setCallback('l', function() InputEvents:notify(InputCommandEvent(info[2])) end) self._innerPanel:addChild(btn) x = x + dx end end function CreateCharUI:_makeNamePanel() local ui = self._ui local x = floor(ui.innerpanel.w/2) x = x - (floor(ui.namepanel.w/2) + floor(ui.innerpanel.hmargin/2)) local y = ui.innerpanel.h y = y - (ui.button.h + ui.innerpanel.vmargin*5 + ui.nameentry.h) local namePanel = Frame(x, y, ui.namepanel.w, ui.namepanel.h) namePanel:setNormalStyle(ui.namepanel.normalStyle) namePanel:setHoverStyle(ui.namepanel.hoverStyle) namePanel:hoverWithChildren(true) local f = Text(ui.innerpanel.hmargin, ui.innerpanel.vmargin, ui.namelabel.w, ui.namelabel.h) f:setNormalStyle(ui.namelabel.normalStyle) f:setText(ui.namelabel.label) f:setJustifyRight() f:setAlignCenter() namePanel:addChild(f) f = TextEntry(ui.innerpanel.hmargin + ui.namelabel.w, ui.innerpanel.vmargin, ui.nameentry.w, ui.nameentry.h) f:setNormalStyle(ui.nameentry.normalStyle) f:setHoverStyle(ui.nameentry.hoverStyle) f:setActiveStyle(ui.nameentry.activeStyle) f:setDefaultText(self._name) f:setJustifyLeft() f:setAlignCenter() self._nameText = f namePanel:addChild(f) self._innerPanel:addChild(namePanel) end -- return the currently selected character function CreateCharUI:getChar() local info = self._selectedChar if info then if self._nameText then local text = self._nameText:getText() self._name = text and text[1] or self._name end info.name = self._name end return info end -- the class return CreateCharUI
--[[- Mechanical and ammunition malfuctions. @module RFF.Malfuctions @author Fenris_Wolf @release 1.0-alpha @copyright 2018 ]] --[[ Checking malfunctions depends on a variety of factors: over all condition of the firearm how many rounds have been shot since the last time the firearm was cleaned. For some action types this is less important then others (ie: revolvers vs gas powered automatics) was WD-40 used and not been properly cleaned after? The use of WD-40 as a 'repair kit' is really quite incorrect. That stuff is NASTY for firearms. It creates extra dirt and gunk, strips away proper gun lubricants, and being a penetrating oil, can leak into ammo primers creating dud rounds. It has its uses unseizing stuck parts, but without a proper cleaning after it creates additional problems ]] local Firearm = require(ENV_RFF_PATH .. "firearm/init") local Ammo = require(ENV_RFF_PATH .. "ammo/init") local Bit = require(ENV_RFF_PATH .. "interface/bit32") local Malfunctions = {} local Ammunition = { } local Mechanical = {} local Failure = {} local ipairs = ipairs local select = select local band = Bit.band --[[ ammo status flags. For InventoryItem loose ammo, use modData.status (if not 0). Boxes and Canisters should use a table: keys being flag sums, values being number of rounds in the box with those flags. Magazines (internal/external) should use a table: position in magazine, flags for that ammo (similar to magazineData table) Guns need a extra variable for the flags of the round in chamber. Status.DUD = 1 -- obvious dud. primer has already been struck Status.POWDERNONE = 2 -- no powder. if the primer is active this may squib (probably) Status.POWDERLOW = 4 -- low powder. weak shot, hangfire or squib. Status.POWDERHIGH = 8 -- high powder. excessive pressure. Status.BRASSWEAK = 16 -- neck or rim might rip on extraction. Status.BRASSDEFORMED = 32 -- brass is slightly deformed or bad measurements. possible feeding issues. Status.PRIMERDEAD = 64 -- the primer is dead. dud round. Status.PRIMERSEATPOS = 128 -- primer not seated far enough. causes slamfires Status.PRIMERSEATNEG = 256 -- primer seated to far. causes duds, hangfires (pin does not strike hard enough) Status.BULLETSEATPOS = 512 -- bullet not seated far enough. feeding and pressure issues. Status.BULLETSEATNEG = 1024 -- bullet seated to far. excessive pressure. Status.BULLETDEFORMED = 2048 -- bullet is slightly deformed. possible feeding/performance issues. ]] local check = function(firearm_data, game_item, game_player, is_firing, ...) --if not Settings.JammingEnabled then return false end local gunData = Firearm.get(firearm_data.type) local ammoData = Ammo.get(ammoType) for i, failure in ipairs({select(1, ...)}) do repeat if failure:onEvent(firearm_data, game_item, game_player, is_firing) then return true end until true end return false end Malfunctions.checkFeed = function(firearm_data, game_item, game_player, is_firing) return check(firearm_data, game_item, game_player, is_firing, Ammunition.FailToFeed1, -- poorly shaped bullet or neck not properly clearing the ramp. Mechanical.FailToFeed1, -- dirt Mechanical.FailToFeed2, -- worn recoil spring Mechanical.FailToFeed3, -- worn ramp Mechanical.FailToFeed4, -- bad magazine Mechanical.FailToFeed5, -- Chamber not empty Mechanical.FailToFeed6, -- slam fire. faulty firing pin (too long) Ammunition.FailToFeed2 -- slamfire. poorly seated primer ) end Malfunctions.checkExtract = function(firearm_data, game_item, game_player, is_firing) return check(firearm_data, game_item, game_player, is_firing, Ammunition.FailToExtract1, -- brass rim failure Ammunition.FailToExtract2, -- case-head seperation. the head of the case is stuck in the chamber and needs to be extracted with tools. Ammunition.FailToExtract3, -- lack of pressure - autos only. Mechanical.FailToExtract1, -- dirt Mechanical.FailToExtract2, -- worn extractor hook Mechanical.FailToExtract3 -- recoil spring too strong ) end Malfunctions.checkEject = function(firearm_data, game_item, game_player, is_firing) return check(firearm_data, game_item, game_player, is_firing, -- stovepipes! Ammunition.FailToEject, -- not enough pressure to cycle the action in automatics. Mechanical.FailToEject1, -- dirt Mechanical.FailToEject2 -- recoil to strong ) end Malfunctions.checkFire = function(firearm_data, game_item, game_player, is_firing) return check(firearm_data, game_item, game_player, is_firing, Mechanical.FailToFire1, -- dirt Mechanical.FailToFire2, -- worn firing pin spring Mechanical.FailToFire3, -- worn firing pin Ammunition.FailToFire1, -- dud round. refuses to fire. Ammunition.FailToFire2, -- squib load. bullet will lodged in the barrel and needs to be cleared. Will not cycle automatics. (FailToEject) Ammunition.FailToFire3 -- delay firing for a few seconds. ) end Ammunition.FailToFire1 = { name = "Failure-To-Fire, Dud Round", description = "For whatever reason, the round is a dud and will not fire.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- check the status flags of the current ammo: -- PRIMERDEAD = true -- PRIMERSEATNEG probably returns true -- POWDERNONE might return true...if the player is lucky... -- any true result here needs to set DUD flag return false end, } Ammunition.FailToFire2 = { name = "Failure-To-Fire, Squib Load", description = "Bullet becomes lodged in the barrel due to bad ammo. Next shot is disastrous. Squib loads can be detected by the shot sound, less of a bang and more of a pop. <LINE> Automatics will not properly cycle with a squib, causing a failure to extract or eject.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- check the status flags of the current ammo: -- POWDERNONE = true (if not a dud in FailToFire1) -- POWDERLOW might return true, or result in a hangfire return false end, } Ammunition.FailToFire3 = { name = "Failure-To-Fire, Hang-Fire", description = "Firing of the shot is delayed due to bad ammo. When a firearm refuses to fire, it should be pointed in a safe direction for 2 minutes to rule out a hangfire. <LINE> This can cause severe damage to the shooter if the weapon has been holstered, and will be disastrous if a revolver and the cylinder was rotated.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- check the status flags of the current ammo: -- POWDERLOW = true (if not a squib in FailToFire2) -- PRIMERSEATNEG = high random chance of true (if not a dud in FailToFire1) return false end, } Ammunition.FailToFeed1 = { name = "Failure-To-Feed, Bad Ammo", description = "Poorly shaped bullet or neck not properly clearing the ramp.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- check the status flags of the current ammo: -- BRASSDEFORMED random chance of true -- BULLETSEATPOS random chance of true -- BULLETDEFORMED random chance of true return false end, } Ammunition.FailToFeed2 = { name = "Slam-Fire, Primer Seating", description = "The ammo has a poorly seated primer, sticking out slightly too far causing the gun to fire when the bolt is closed", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- check the status flags of the current ammo: -- PRIMERSEATPOS random chance of true return false end, } Ammunition.FailToExtract1 = { name = "Failure-To-Extract, Brass Failure", description = "The brass rim on the case has ripped, causing it not to extract from the chamber.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- check the status flags of the current ammo: -- BRASSWEAK random chance of true return false end, } Ammunition.FailToExtract2 = { name = "Case-Head Separation, Brass Failure", description = "The neck of the case has ripped, and the head is stuck in the chamber and needs to be extracted with tools.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- check the status flags of the current ammo: -- BRASSWEAK random chance of true return false end, } Ammunition.FailToExtract3 = { name = "Failure-To-Extract, Low Pressure", description = "Casing failed to extract due not enough pressure to cycle the bolt.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- these should slightly adjust our recoil factor (guns preference vs ammo recoil) -- POWDERLOW -- PRIMERSEATNEG -- BULLETSEATPOS end, } Ammunition.FailToEject = { name = "Failure-To-Eject, Low Pressure", description = "Casing failed to eject due not enough pressure to cycle the bolt.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- these should slightly adjust our recoil factor (guns preference vs ammo recoil) -- POWDERLOW -- PRIMERSEATNEG -- BULLETSEATPOS return false end, } --[[ This table lists malfunctions caused by firearms in poor condition. These should not be confused with actual mechanical failure (ie: broken parts), as they may not happen consistently. The firearm might function normally, suffer a malfunction, then continue to function normally after without maintenance or repair. ]] Mechanical.FailToFeed1 = { name = "Failure-To-Feed, Dirt", description = "Excessive dirt causing the gun to fail to chamber rounds.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) -- check dirt threshold return false end } Mechanical.FailToFeed2 = { name = "Failure-To-Feed, Worn Recoil Spring", description = "The recoil spring is not providing enough tension to properly chamber rounds.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end } Mechanical.FailToFeed3 = { name = "Failure-To-Feed, Worn Chamber Ramp", description = "The chamber ramp is worn, causing the gun to fail to chamber rounds.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end } Mechanical.FailToFeed4 = { name = "Failure-To-Feed, Magazine Failure", description = "Issues with the magazine preventing the gun from properly chambering rounds.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToFeed5 = { name = "Failure-To-Feed, Chamber Obstructed", description = "Something in the chamber is preventing ammo from feeding.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToFeed6 = { name = "Slam-Fire, Faulty Firing Pin", description = "The firing pin is slighty too long, causing the gun to slamfire (also known as Hammer Follow).", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToFire1 = { name = "Failure-To-Fire, Dirt", description = "Excessive dirt is jamming up the firing pin.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToFire2 = { name = "Failure-To-Fire, Faulty Firing Pin Spring", description = "The firing pin spring is worn, causing the firing pin to not have enough force.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToFire3 = { name = "Failure-To-Fire, Faulty Firing Pin", description = "The firing pin is worn, causing it to not fully engage the primer.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToExtract1 = { name = "Failure-To-Extract, Dirt", description = "Excessive chamber dirt causing casings to become stuck.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToExtract2 = { name = "Failure-To-Extract, Worn Extractor Hook", description = "The extractor hook is worn out, causing it to fail to extract casings from the chamber.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToExtract3 = { name = "Failure-To-Extract, Recoil Spring Issues", description = "The recoil spring is providing too much tension preventing the action from cycling properly, causing it to fail to extract.", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToEject1 = { name = "Failue-To-Eject, Dirt", description = "Excessive dirt is preventing the action from cycling properly, leading to a failure to eject. (also known as Stovepipe)", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } Mechanical.FailToEject2 = { name = "Failue-To-Eject, Dirt", description = "The recoil spring is providing too much tension preventing the action from cycling properly, leading to a failure to eject. (also known as Stovepipe)", onEvent = function(self, firearm_data, game_item, game_player, is_firing) return false end, } --[[ ORGM.MechanicaFailureTable This table contains potential mechanical failures (broken or seized parts). These will consistently lead to the mechanical malfunctions listed above. ]] --[[ The crude, old mechanics (see how far we've come?) local chance = (weaponItem:getConditionMax() / weaponItem:getCondition()) *2 if playerObj:HasTrait("Lucky") then chance = chance * 0.8 elseif playerObj:HasTrait("Unlucky") then chance = chance * 1.2 end local result = ZombRand(300 - math.ceil(chance)*2)+1 if result <= chance then this.isJammed = true weaponItem:getModData().isJammed = true return true end ]] return Malfunctions
--Dylang140 --January 29, 2022 --CC Tewaked GUI Prorgam --Intended for CC Tweaked and Immersive Engineering for Minecraft 1.18 --Feel free to change or copy this code for other mods, versions, or projects --======CONFIG SECTION======-- local speaker = peripheral.find("speaker") local bundledConnection = "bottom" local bundledInput = "left" local monitor = peripheral.find("monitor") local dataSave = "disk/savedData.txt" local diskDrive = peripheral.wrap("left") local capA, capB, capC, capD, capE = peripheral.find("capacitor_hv") local currentOne, currentTwo, currentThree, currentFour = peripheral.find("current_transformer") local currents = {currentOne, currentTwo, currentThree, currentFour} local currentValues = {} local numCurrents = 8 local caps = {capA, capB, capC, capD, capE} local capNumbers = {3, 4, 5, 6, 7} --Number for the capacitors used (capacitor_hv_4, ex) local capMaxes = {0,2,3,4,5} local capValues = {} local numCaps = 5 local bgColor = colors.black --local capA = caps[1] --local capB = caps[2] --How often the screen refreshes (in seconds) (also affects save frequency and custom logic, like alarms) local refreshRate = 2 --==========================-- --========GUI BUILD SECTION=========-- --Define output (0 - 15) for each connected redstone device on bundled output 1 local outOne = 1 local outTwo = 2 local outThree = 3 local outFour = 4 local outFive = 5 local outSix = 6 local outSeven = 7 local outEight = 8 local outNine = 9 local outTen = 10 local outEleven = 11 local outTwelve = 12 --Define Inputs(1-16) (work in progress) --local inputOne --Some variables for helping build the gui --These are not necessary, but can help add items without doing the math for the coordinates local width, height = monitor.getSize() local buttonRowOne = height - 20 local buttonRowTwo = height - 13 local buttonRowThree = height - 6 local colWidth = (width - 15) / 6 local col1 = 2 local col2 = col1 + colWidth + 3 local col3 = col2 + colWidth + 3 local col4 = col3 + colWidth + 3 local col5 = col4 + colWidth + 3 local col6 = col5 + colWidth + 3 local rebootButton = {width - 17, 4, width - 2, 8} --Define BUTTONS as nested tables --xOne, yOne, xTwo, yTwo, control, state, label local buttons = { --Col 1 {col1, buttonRowOne, col1 + colWidth, buttonRowOne + 5, outOne, false, "Generator A" }, {col1, buttonRowTwo, col1 + colWidth, buttonRowTwo + 5, outTwo, false, "Generator B"}, {col1, buttonRowThree, col1 + colWidth, buttonRowThree + 5, outThree, false,"Generator C"}, --Col 2 --Col 3 {col3, buttonRowOne, col3 + colWidth, buttonRowOne + 5, outFour, false, "A Enable"}, {col3, buttonRowTwo, col3 + colWidth, buttonRowTwo + 5, outFive, false, "B Enable"}, {col3, buttonRowThree, col3 + colWidth, buttonRowThree + 5, outSix, false, "C Enable"}, --Col 4 {col4, buttonRowOne, col4 + colWidth, buttonRowOne + 5, outSeven, false, "D Enable"}, {col4, buttonRowTwo, col4 + colWidth, buttonRowTwo + 5, outEight, false, "E Enable"}, --Col 5 {col5, buttonRowOne, col5 + colWidth, buttonRowOne + 5, outNine, false, "Fake Load A"}, {col5, buttonRowTwo, col5 + colWidth, buttonRowTwo + 5, outTen, false, "Fake Load B"}, {col5, buttonRowThree, col5 + colWidth, buttonRowThree + 5, outEleven, false, "Fake Load C" }, --Col 6 {col6, buttonRowOne, col6 + colWidth, buttonRowOne + 5, outTwelve, false, "Fake Load D"} --Other } --Must manually update!!! local numButtons = 12 --Define ENERGY Bar GRAPHS (horizontal) as nested tables --xPosTop, yPosTop, width, height(down), input), vertical (1) or horizontal (0) local graphs = { {2, 4, 20, 2, {1}, "Capcitor A", 0}, {2, 9, 20, 2, {2}, "Capcitor B", 0}, {2, 14, 20, 2, {3}, "Capcitor C", 0}, {2, 19, 20, 2, {4}, "Capcitor D", 0}, {2, 24, 20, 2, {5}, "Capcitor E", 0}, {55, 14, 30, 3, {1,2,3,4,5}, "Total Stored", 0} } --Define LABELS as nested tables --xPos, yPos, text, color, graph number (to link a percentage) local labels = { {2, 3, "Capacitor A", colors.purple, {1}}, {2, 8, "Capacitor B", colors.purple, {2}}, {2, 13, "Capacitor C", colors.purple, {3}}, {2, 18, "Capacitor D", colors.purple, {4}}, {2, 23, "Capacitor E", colors.purple, {5}}, {61, 8, "Total Power Stored: Loading...", colors.cyan, {}}, {70, 9, "", colors.cyan, {1,2,3,4,5}}, {107, 13, "Load A", colors.purple, {}}, {107, 17, "Load B", colors.purple, {}}, {107, 23, "Load C", colors.purple, {}}, {107, 27, "Load D", colors.purple, {}} } --Define ALARMS as nested tables --graph number, threshold percentage, over or under (1 or 0) local alarms = { {1, 25, 0}, {2, 25, 0}, {3, 25, 0}, {4, 25, 0}, {5, 25, 0} } --Must manually update!!! local numAlarms = 5 --Define OUTPUT INDICATORS as nested tables (Buttons, but that cannot be clicked) - True if any of specified outputs true, else false --x, y, width, height, true color, false color, {list of states from 'Outputs'}, label --Color Codes: https://tweaked.cc/module/colors.html local outputIndicators = { {30, 4, 15, 3, 2048, 256, {2}, "Generator #1"}, {30, 10, 15, 3, 2048, 256, {3}, "Generator #2"}, {30, 16, 15, 3, 2048, 256, {4}, "Generator #3"} } --Define OUTPUT INDICATOR LINES as nested tables (Buttons, but that cannot be clicked) - True if any of specified outputs true, else false --Lines draw left to right, then top to bottom if the y coordinates are different --x start, y start, x end, y end, true color, false color, {list of states from 'Outputs'} --Color Codes: https://tweaked.cc/module/colors.html local outputLineIndicators = { } --Define CURRENT INDICATOR LINES as nested tables (Buttons, but that cannot be clicked) - True if any of specified outputs true, else false --Lines draw left to right, then top to bottom if the y coordinates are different --x start, y start, x end, y end, true color, false color, {list of current transformers}, currentVal (use 0) --Remeber: The TOP LEFT corner is (0,0) so going down means HIGHER Y values --Color Codes: https://tweaked.cc/module/colors.html local currentLineIndicators = { {46, 6, 50, 12, 1024, 256, {2}}, {46, 11, 50, 12, 1024, 256, {3}}, {46, 17, 50, 12, 1024, 256, {4}}, {50, 11, 70, 13, 1024, 256, {2, 3, 4}}, {70, 18, 70, 19, 1024, 256, {1}}, {70, 20, 100, 20, 1024, 256, {1}}, {100, 21, 100, 23, 1024, 256, {7, 8}}, {101, 23, 105, 23, 1024, 256, {7}}, {100, 24, 100, 27, 1024, 256, {8}}, {100, 27, 105, 27, 1024, 256, {8}}, {100, 19, 100, 17, 1024, 256, {5, 6}}, {101, 17, 105, 17, 1024, 256, {6}}, {100, 16, 100, 13, 1024, 256, {5}}, {100, 13, 105, 13, 1024, 256, {5}} } --=============================================== --============END CONFIG SECTION================= --=============================================== --Array that initializes all redstone outputs as false and stores states while the program runs -- 1 - 16 represent redstone outputs, thelast 4 are extra states for other logic that should be saved --This table is overwritten each time the program starts if there is a file with saved data avaliable local outputs = {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false} local allColors = colors.combine( colors.white, colors.orange, colors.magenta, colors.lightBlue, colors.yellow, colors.lime, colors.pink, colors.gray, colors.lightGray, colors.cyan, colors.purple, colors.blue, colors.brown, colors.green, colors.red, colors.black) term.redirect(monitor) monitor.setTextScale(0.5) --Misc Variables local tempNum = 0 local alarmPhase = 0 local activeAlarms = 0 --Functions function saveAll() f = io.open(dataSave, "w+") for i = 1, 20 do if outputs[i] == true then f:write("a" .. "\n") else f:write("b" .. "\n") end end io.close(f) end function readData() f = io.open(dataSave) i = 1 for line in io.lines(dataSave) do if line == "a" then outputs[i] = true else outputs[i] = false end i = i + 1 end io.close(f) end local currents = peripheral.find("current_transformer") local currentValues = {} function updateCurrentValues() local tempString for i = 0, numCurrents do tempString = "current_transformer_" tempString = tempString .. (i) currentValues[i + 1] = peripheral.call(tempString, "getAveragePower") end end function updateCapValues() local tempString for i, v in ipairs(capNumbers) do tempString = "capacitor_hv_" tempString = tempString .. (v) capValues[i] = peripheral.call(tempString, "getEnergyStored") capMaxes[i] = peripheral.call(tempString, "getMaxEnergyStored") end end function getSumCapVals() local t = 0 for i, v in ipairs(capValues) do t = t + v end return t end function alarmTrigger() if alarmPhase == 0 then speaker.playNote("bit", 3.0, 6) speaker.playNote("flute", 3.0, 9) elseif alarmPhase == 1 then speaker.playNote("bit", 3.0, 8) speaker.playNote("flute", 3.0, 10) alarmPhase = -1 end alarmPhase = alarmPhase + 1 end function doAlarm(n) alarmTemp = alarms[n] currentVal = capValues[alarmTemp[1]] / capMaxes[alarmTemp[1]] * 100 if alarmTemp[3] == 0 then if currentVal < alarmTemp[2] then activeAlarms = activeAlarms + 1 end elseif alarmTemp[3] == 1 then if currentVal > alarmTemp[2] then activeAlarms = activeAlarms + 1 end end end function printAndClearAlarms() xPos, yPos = monitor.getSize() monitor.setCursorPos(xPos - 12, 2) if activeAlarms > 0 then if alarmPhase == 0 then monitor.setTextColor(colors.red) else monitor.setTextColor(colors.white) end alarmTrigger() end print(activeAlarms .. " Alarm(s)!") monitor.setTextColor(colors.white) activeAlarms = 0 end function graphCalc(n) graphs[n][6] = graphs[n][5].getEnergyStored() graphs[n][7] = graphs[n][5].getMaxEnergyStored() end function graphInit(n) graphCalc(n) end function drawButton(n) local tab = buttons[n] if tab[6] == true then paintutils.drawFilledBox(tab[1], tab[2], tab[3], tab[4], colors.green) else paintutils.drawFilledBox(tab[1], tab[2], tab[3], tab[4], colors.red) end monitor.setCursorPos((((tab[3] + tab[1]) / 2) - string.len(tab[7]) / 2) + 1, ((tab[4] + tab[2]) / 2)) print(tab[7]) monitor.setBackgroundColor(colors.black) end function updateOutput() local colorStatesColors = allColors for i = 0, 16 do if outputs[i] == false then if i == 0 then colorStatesColors = colors.subtract(colorStatesColors, 1) else colorStatesColors = colors.subtract(colorStatesColors, 2 ^ i) end end end redstone.setBundledOutput(bundledConnection, colorStatesColors) end function drawGraphs() local tempCurrent local tempMax local threshold for i, v in ipairs(graphs) do tempCurrent = 0 tempMax = 0 for j, b in ipairs(v[5]) do tempCurrent = tempCurrent + capValues[b] tempMax = tempMax + capMaxes[b] end threshold = (tempCurrent / tempMax) * v[3] for i = v[1], v[3] + v[1] do for j = v[2], v[4] + v[2] do if i < (threshold + v[1] + 1) then if threshold < (v[3] / 4) then if threshold < (v[3] / 10) then monitor.setBackgroundColor(colors.red) else monitor.setBackgroundColor(colors.yellow) end else monitor.setBackgroundColor(colors.blue) end else monitor.setBackgroundColor(colors.lightGray) end monitor.setCursorPos(i, j) print(" ") end end monitor.setBackgroundColor(colors.black) end end function drawLabel(n) label = labels[n] monitor.setCursorPos(label[1], label[2]) monitor.setTextColor(label[4]) print(label[3]) if not (label[5] == nil) then monitor.setCursorPos(label[1] + #label[3], label[2]) print(" " .. (capValues[label[5]] / capMaxes[label[5]]) * 100 .. "%") end monitor.setTextColor(colors.white) end function drawLabels() local tempMax, tempVal for i, v in ipairs(labels) do tempMax = 0 tempVal = 0 for j, k in ipairs(v[5]) do tempMax = tempMax + capMaxes[k] tempVal = tempVal + capValues[k] end monitor.setCursorPos(v[1], v[2]) monitor.setTextColor(v[4]) print(v[3]) if not (tempMax == 0) then monitor.setCursorPos(v[1] + #v[3], v[2]) print(" " .. string.format("%.2f", ((tempVal / tempMax) * 100)) .. "%") end monitor.setTextColor(colors.white) end end function toggleOn(n) outputs[n] = true; updateOutput(); end function toggleOff(n) outputs[n] = false; updateOutput(); end function toggle(n) outputs[n] = not outputs[n]; updateOutput(); end function doButton(n, xPos, yPos) local tab = buttons[n] if(xPos >= tab[1] and xPos <= tab[3] and yPos >= tab[2] and yPos <= tab[4]) then tab[6] = not tab[6] toggle(tab[5]) end if (xPos >= rebootButton[1] and xPos <= rebootButton[3] and yPos >= rebootButton[2] and yPos <= rebootButton[4]) then monitor.clear() os.reboot() end drawButton(n) end function buttonInit(n) local tab = buttons[n] if outputs[tab[5]] == true then tab[6] = true else tab[6] = false end end function drawOutputIndicators() local tempBool for i, v in ipairs(outputIndicators) do tempBool = false for j, b in ipairs(v[7]) do if outputs[b] == true then tempBool = true end end if tempBool then monitor.setBackgroundColor(v[5]) else monitor.setBackgroundColor(v[6]) end paintutils.drawFilledBox(v[1], v[2], v[1] + v[3], v[2] + v[4]) term.setCursorPos(v[1] + (v[3]/2) - (string.len(v[8]) / 2), v[2] + (v[4] / 2)) print(v[8]) end monitor.setBackgroundColor(bgColor) end function drawOutputLineIndicators() local tempBool for i, v in ipairs(outputLineIndicators) do tempBool = false for j, b in ipairs(v[7]) do if outputs[b] == true then tempBool = true end end if tempBool then monitor.setBackgroundColor(v[5]) else monitor.setBackgroundColor(v[6]) end paintutils.drawLine(v[1], v[2], v[3], v[2]) paintutils.drawLine(v[3], v[2], v[3], v[4]) end monitor.setBackgroundColor(bgColor) end function drawCurrentLineIndicators() local tempVal for i, v in ipairs(currentLineIndicators) do tempVal = 0 for j, b in ipairs(v[7]) do tempVal = tempVal + currentValues[b] end if tempVal > 1 then monitor.setBackgroundColor(v[5]) else monitor.setBackgroundColor(v[6]) end paintutils.drawLine(v[1], v[2], v[3], v[2]) paintutils.drawLine(v[3], v[2], v[3], v[4]) end monitor.setBackgroundColor(bgColor) end function formatNum(n) local str = "" local result = "" str = str .. n for i = 1, string.len(str) do result = result .. string.sub(str, i, i) if ((string.len(str) - i) % 3 == 0) and not (i == string.len(str)) then result = result .. "," end end return result end --Main Section for Creating GUI readData() for i = 1, numButtons do buttonInit(i) end monitor.clear() updateOutput() updateCurrentValues() updateCapValues() monitor.setCursorPos(width / 2, height / 2) print("Welcome") monitor.setCursorPos(width / 2 - 6, height / 2 + 1) print("Starting Program...") os.sleep(1) monitor.clear() timeout = os.startTimer(refreshRate) while true do for i = 1, numButtons do drawButton(i) end drawGraphs() for i = 1, numAlarms do doAlarm(i) end drawLabels() drawOutputIndicators() drawOutputLineIndicators() drawCurrentLineIndicators() printAndClearAlarms() paintutils.drawFilledBox(rebootButton[1], rebootButton[2], rebootButton[3], rebootButton[4], colors.brown) monitor.setCursorPos((rebootButton[3] - rebootButton[1]) / 2 + rebootButton[1] - 2, (rebootButton[4] - rebootButton[2] / 2)) print("Reboot") monitor.setBackgroundColor(bgColor) --event, side, xPos, yPos = os.pullEvent("monitor_touch") event = {os.pullEvent()} if event[1] == "monitor_touch" then --handle monitor touches for j = 1, numButtons do doButton(j, event[3], event[4]) end timeout = os.startTimer(refreshRate) elseif event[1] == "timer" and event[2] == timeout then timeout = os.startTimer(refreshRate) end updateCurrentValues() updateCapValues() --============== Add Custom Logic Here ================= --Note: Getting data from a peripheral (like getting accumulator capacity) in the loop --might cause the screen to blink as it refreshes. Putting it here SHOULD prevent that, --since it is before the screen clears labels[6][3] = "Total Power Stored: " .. formatNum(getSumCapVals()) .. " IF" monitor.clear() saveAll() end
-- --Rockmonster -- ccmobs2 = {} minetest.register_node("ccmobs2:rockmonster_block", { drawtype = "nodebox", node_box = { type = "fixed", fixed = { {0.0625, -0.5, -0.125, 0.3125, -0.375, 0.125}, {-0.3125, -0.5, -0.125, -0.0625, -0.375, 0.125}, {0.0625, -0.375, -0.125, 0.25, -0.1875, 0.0625}, {-0.25, -0.375, -0.125, -0.0625, -0.1875, 0.0625}, {-0.25, -0.254703, -0.125, 0.25, 0.25, 0.0625}, {-0.3125, -0.1875, -0.1875, 0.3125, 0.125, 0.125}, {-0.125, 0.25, -0, 0.125, 0.375, 0.099219}, {-0.125, 0.1875, -0.1875, 0.125, 0.4375, 0.0625}, {-0.1875, 0.4375, -0.1875, 0.1875, 0.5, 0.157427}, {0.125, 0.25, -0.1875, 0.1875, 0.5, 0.125}, {-0.1875, 0.25, -0.1875, -0.125, 0.5, 0.125}, {0.25, 0.0625, -0.1875, 0.5, 0.3125, 0.0625}, {-0.5, 0.0625, -0.1875, -0.25, 0.3125, 0.0625}, {0.333452, -0.25, -0.125, 0.474025, 0.0625, -0}, {-0.474025, -0.25, -0.125, -0.339991, 0.0625, -0}, {-0.3125, 0.0625, -0.207698, 0.3125, 0.235111, 0.154782}, {-0.292365, -0.1875, -0.198212, 0.292365, 0.125, 0.215763}, }, }, tiles = {"ccmobs2_rockmonster_top.png", "ccmobs2_rockmonster_bottom.png", "ccmobs2_rockmonster_right_side.png", "ccmobs2_rockmonster_left_side.png", "ccmobs2_rockmonster_front.png", "ccmobs2_rockmonster_back.png"}, groups = {not_in_creative_inventory = 1}, }) mobs:register_mob("ccmobs2:rockmonster", { type = "monster", passive = false, damage = 4, attack_type = "dogshoot", dogshoot_switch = 1, dogshoot_count_max = 12, -- shoot for 10 seconds dogshoot_count2_max = 3, -- dogfight for 3 seconds reach = 3, shoot_interval = 2.2, arrow = "ccmobs2:boulder", shoot_offset = 1, pathfinding = false, hp_min = 12, hp_max = 35, armor = 80, collisionbox = {-1.2, -1.7, -1.2, 1.2, 1.7, 1.2}, visual = "wielditem", textures = {"ccmobs2:rockmonster_block"}, visual_size = {x = 2.0, y = 2.25}, blood_texture = "default_clay_lump.png", makes_footstep_sound = true, sounds = { random = "ccmobs2_rockmonster", shoot_attack = "ccmobs2_rockmonster", shoot_explode = "default_place_node_hard", }, walk_velocity = 0.5, run_velocity = 1.25, jump_height = 0, stepheight = 1.1, floats = 0, view_range = 15, drops = { {name = "default:cobble", chance = 1, min = 0, max = 2}, {name = "default:coal_lump", chance = 3, min = 0, max = 2}, {name = "default:stone", chance = 5, min = 0, max = 1}, }, water_damage = 0, lava_damage = 1, light_damage = 0.5, fall_damage = 1, fear_height = 5, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, shoot_start = 36, shoot_end = 48, }, on_rightclick = function(self, clicker) ccmobs2:capture_mob(self, clicker, "ccmobs2:rockmonster") end, }) -- boulder (weapon) mobs:register_arrow("ccmobs2:boulder", { visual = "sprite", visual_size = {x = 1.5, y = 1.5}, textures = {"ccmobs2_boulder.png"}, collisionbox = {-0.1, -0.1, -0.1, 0.1, 0.1, 0.1}, velocity = 15, on_activate = function(self, staticdata, dtime_s) self.object:set_armor_groups({immortal = 1, fleshy = 100}) end, hit_player = function(self, player) player:punch(self.object, 1.0, { full_punch_interval = 1.0, damage_groups = {fleshy = 8}, }, nil) end, hit_mob = function(self, player) player:punch(self.object, 1.0, { full_punch_interval = 1.0, damage_groups = {fleshy = 8}, }, nil) end, hit_node = function(self, pos, node) self.object:remove() end })
-- "Test cases" for Statlist-fullevo local s = require('Statlist-fullevo') print(s.statlist())
---Module responsible for running a single test class; -- can be used stand-alone from LuaUnit if desired. --'absolute reference' for setter local DEFAULT_VERBOSITY = 1 local stringbuffer = require 'lua_stringbuffer' ---- CLASSRUNNER RESULTS CLASS ----------------------------------------------- local Result = {} Result.addSuccess = function(self, name) self.passed[#self.passed + 1] = name end Result.addFailure = function(self, name, msg, trace) self.failed[#self.failed + 1] = {name, msg, trace} end Result.addSkip = function(self, name, reason) self.skipped[#self.skipped + 1] = {name, reason} end Result.getRunCount = function(self) return #self[1] end Result.new = function() return {passed = {}, failed = {}, skipped = {}, addSuccess = Result.addSuccess, addFailure = Result.addFailure, addSkip = Result.addSkip, getSkippedCount = function(self) return #self.skipped end, getRunCount = function(self) return #self.failed + #self.passed end, getSuccessCount = function(self) return #self.passed end, getFailureCount = function(self) return #self.failed end, getFailures = function(self) return self.failed end, } end ---- CLASSRUNNER CLASS ------------------------------------------------------- local Runner = {_VERSION = '1.0.0', verbosity = DEFAULT_VERBOSITY, } ---(ClassRunner):addTest(name) -- Add a function found by name in the global namespace to the Runner; -- will not add duplicates. -- @param name {String} Name of a function in global namespace. -- TODO: param to specify order? -- @error iff name is not string or function not found local function addTest(self, name) assert(type(name) == 'string') assert(type(_G[name] ) == 'function') if #self.tests == 0 then self.tests[1] = name elseif self.tests[name] then -- no duplicates! return else -- insert in alphabetical order local added = false for i=1, #self.tests do if name < self.tests[i] then table.insert(self.tests, i, name) added = true break end end if not added then self.tests[#self.tests+1] = name end end self.class[name] = _G[name] end ---(ClassRunner):getName() local function getName(self) return self.name end ---(ClassRunner):getResults() local function getResults(self) return self.results:getRunCount(), self.results:getFailures(), self.results:getSkippedCount() end ---(ClassRunner):_appendOutput(s) -- Universal call to handle output; will add to accumulated output iff flagged, -- else prints to stdout. -- @param s {String} Literal to output. local function appendOutput(self, s) self.buffer:add(s) if not self.silent then io.stdout:write(s) end end ---(ClassRunner):setSilent(flag) -- Runner will not print as tests execute -- @param flag {Boolean} (default true) local function setSilent(self, flag) flag = flag or true assert (type(flag) == 'boolean', 'flag must be boolean') self.silent = flag end ---(ClassRunner):getOutput() -- Get the accumulated output, if any. -- @return {String} Any redirected output if set to accumulate; -- else nil. local function getOutput(self) --if not self.shouldAccumulated then return end if not self.buffer then return '' end return self.buffer:getString() end ---Will attempt to run any functions in class whose name are found in t. -- @param t {Table} Array of {String}s. -- @param class {Table} local function _blindRunAny(t, class) for _,v in ipairs(t) do if type(class[v]) == 'function' then class[v](class) --> class:<v>() end end end ---(ClassRunner):_runMethod(name) -- Run a single test method and any before/after routines. -- @param name {String} Name of the test routine. local function runMethod(self, name) if self.verbosity > 0 then self:_appendOutput('\n ['..name..']\t') end if not self.class[name] then self.results:addSkip(name, 'absent') self:_appendOutput('A') if self.verbosity > 0 then self:_appendOutput('bsent') end return end local function _err_handler(e) --if VERBOSITY > 0 then return e..'\n'..debug.traceback() --end --return e..'\n' end -- local ok, msg = xpcall(self.class[name], _err_handler, self.class) -- required because lua5.1 xpcall does not accept arguments local callfn = function() return self.class[name](self.class) end local ok, msg = xpcall(callfn, _err_handler) if ok then self.results:addSuccess(name) if self.verbosity > 0 then self:_appendOutput('Ok') else self:_appendOutput('.') end else self:_appendOutput('F') if self.verbosity > 0 then self:_appendOutput('ailed') end local errmsg, stack, a, b a, b = msg:find('stack traceback:\n') if not a then error('could not find the "stack traceback" in pcall error:\n' .. msg .. '\n') end errmsg = msg:sub(1, a-1):gsub('^%s*(.-)%s*$', '%1') stack = msg:sub(b+1) self.results:addFailure(name, errmsg, stack) end end ---(ClassRunner):run(...) -- Run the test and any before/after routines. Accepts optional arguments of -- names of tests to be run. -- @param ... {String, String} Optional sequence (in order) of tests; -- overrides any auto-generated test listing. -- @error Iff any of the passed arguments are not a {String}. local function run(self, ...) -- use tests if provided manually (but make sure they're name strings) local tests = {...} if #tests > 0 then for i=1, #tests do assert(type(tests[i]) == 'string', "Method name is not a string! "..tostring(tests[i])) end else tests = self.tests end -- prevent the running of duplicate tests by name local seen, seenset = false, {} for i=1, #tests do seen = false for j=1, #seenset do if seenset[j] == tests[i] then seen = true end end if not seen then seenset[#seenset+1] = tests[i] end end tests, seenset = seenset, nil self.results = Result.new() self.buffer = stringbuffer.new() self:_appendOutput(self.name) if self.verbosity == 0 then self:_appendOutput('\t') end _blindRunAny({'setUpClass'}, self.class) for i=1, #tests do _blindRunAny({'setUp', 'Setup', 'SetUp'}, self.class) self:_runMethod(tests[i]) _blindRunAny({'tearDown', 'Teardown', 'TearDown'}, self.class) end _blindRunAny({'tearDownClass'}, self.class) self:_appendOutput('\n') end ---Utility function to auto-name ClassRunners if necessary; -- id increments to avoide name clashes. local function _crIdClosure() local i = 0 return function() i = i+1 return i end end local _cic = _crIdClosure() ---(ClassRunner):getVerbosity local function getVerbosity(self) return self.verbosity end ---(ClassRunner):setVerbosity(v) local function setVerbosity(self, v) v = v or DEFAULT_VERBOSITY assert (type(v) == 'number', 'verbosity must be a number') self.verbosity = v end ---Get the string-indices starting with 'test' or 'Test' in alphabetical order -- @param t local function _getAlphabeticalTestNames(t) local list = {} local added for k,_ in pairs(t) do if type(k) == 'string' and type(t[k]) == 'function' and ( string.sub(k,1,4) == 'test' or string.sub(k,1,4) == 'Test') then added = false if not list[1] then list[1] = k added = true else for i=1, #list do if k < list[i] then table.insert(list, i, k) added = true break end end end if not added then list[#list + 1] = k end end end return list end ---ClassRunner:getVerbosity() -- @return current value of the module's verbosity setting. Runner.getVerbosity = function(self) return Runner.verbosity end ---ClassRunner:setVerbosity([level]) -- @param level (default DEFAULT_VERBOSITY). Runner.setVerbosity = function(level) Runner.verbosity = level or DEFAULT_VERBOSITY end ---ClassRunner.new([classname], [verbosity]) -- @param classname {String} Optional argument; -- iff _G[classname] exists and is a table, it will try to -- self-add test, setup, and teardown functions. -- @param verboisty {Number} optional number to set verbosity. -- @return new ClassRunner. Runner.new = function(classname, verbosity) classname = classname or 'ClassRunner'..tostring(_cic()) verbosity = verbosity or Runner.verbosity assert(type(classname) == 'string', 'classname must be a string') assert(type(verbosity) == 'number', 'verbosity must be a number') local testclass, testlist = {}, {} if type(_G[classname]) == 'table' then testclass = _G[classname] testlist = _getAlphabeticalTestNames(testclass) end return {class = testclass, name = classname, results = Result.new(), tests = testlist, verbosity = verbosity, setSilent = setSilent, addTest = addTest, _appendOutput = appendOutput, getOutput = getOutput, getName = getName, getVerbosity = getVerbosity, setVerbosity = setVerbosity, getResults = getResults, run = run, _runMethod = runMethod, } end return Runner
DoorSlotSelection = CustomItem:extend() DoorSlotSelection.Types = { [1] = "unknown", [2] = "one_way", [3] = "dead_end", [4] = "event", [5] = "trainer", [6] = "coal_badge", [7] = "forest_badge", [8] = "cobble_badge", [9] = "fen_badge", [10] = "relic_badge", [11] = "mine_badge", [12] = "icicle_badge", [13] = "beacon_badge", [14] = "e4_bug", [15] = "e4_ground", [16] = "e4_fire", [17] = "e4_psychic", [18] = "champ", [19] = "cut", [20] = "rock_smash", [21] = "strength", [22] = "surf", [23] = "waterfall", [24] = "rock_climb", [25] = "hm1", [26] = "hm2", [27] = "hm3", [28] = "hm4", [29] = "hm5", [30] = "hm6", [31] = "hm7", [32] = "hm8", [33] = "custom1", [34] = "custom2", [35] = "custom3", [36] = "custom4", [37] = "custom5", [38] = "custom6", [39] = "custom7", [40] = "custom8", [41] = "center", [42] = "mart", [43] = "bike", [44] = "1", [45] = "2", [46] = "3", [47] = "4", [48] = "5", [49] = "6", [50] = "7", [51] = "8", [52] = "acuity_lakefront", [53] = "canalave", [54] = "celestic", [55] = "coronet", [56] = "coronet_peak", [57] = "dept", [58] = "eterna", [59] = "eterna_galactic", [60] = "fight_area", [61] = "floaroma", [62] = "eterna_forest", [63] = "galactic_hq", [64] = "hearthome", [65] = "iron_island", [66] = "fuego_ironworks", [67] = "jubilife", [68] = "jubilife_tv", [69] = "league", [70] = "mansion", [71] = "floaroma_meadow", [72] = "oreburgh", [73] = "pastoria", [74] = "poketch", [75] = "resort_area", [76] = "solaceon_ruins", [77] = "sandgem", [78] = "snowpoint", [79] = "solaceon", [80] = "spring_path", [81] = "stark", [82] = "sunyshore", [83] = "survival_area", [84] = "valor_lakefront", [85] = "veilstone", [86] = "verity_lakefront", [87] = "victory_road", [88] = "valley_windworks", [89] = "route_203", [90] = "route_204", [91] = "route_205", [92] = "route_206", [93] = "route_207", [94] = "route_208", [95] = "route_209", [96] = "route_210", [97] = "route_211", [98] = "route_212", [99] = "route_213", [100] = "route_214", [101] = "route_215", [102] = "route_216", [103] = "route_217", [104] = "route_221", [105] = "route_222", [106] = "route_225", [107] = "route_226", [108] = "route_227", [109] = "route_228", [110] = "old_chateau", [111] = "oreburgh_gate" } DoorSlotSelection.Selection = 2 function DoorSlotSelection:init(index) self:createItem("Door Slot Selection") self.index = index self.code = "doorslot_" .. DoorSlotSelection.Types[index] self.image = DoorSlot.Icons[index] self:setState(0) end function DoorSlotSelection:setState(state) self:setProperty("state", state) end function DoorSlotSelection:getState() return self:getProperty("state") end function DoorSlotSelection:updateIcon() local overlay = "" if self:getState() > 0 then if DoorSlotSelection.Selection < 52 then overlay = "overlay|images/other/selected_tag.png" else overlay = "overlay|images/other/selected_hub.png" end end self.ItemInstance.Icon = ImageReference:FromPackRelativePath("images/" .. self.image .. ".png", overlay) end function DoorSlotSelection:updateNeighbors() for i = 1, #DoorSlot.Icons do if DoorSlotSelection.Types[i] and self.index ~= i then local item = Tracker:FindObjectForCode("doorslot_" .. DoorSlotSelection.Types[i]) if item then item.ItemState:setState(0) end end end end function DoorSlotSelection:onLeftClick() local selection = self.index local current_warp = Tracker:FindObjectForCode(DoorSlot.Selection).ItemState local current_warp_hub = current_warp.hubIcon if current_warp and current_warp_hub then current_warp:setState(selection) current_warp_hub:setState(selection) if selection < 52 then current_warp.ItemInstance.Icon = ImageReference:FromPackRelativePath("images/" .. DoorSlot.Icons[selection] .. ".png", "overlay|images/other/selected_tag.png") else current_warp_hub.ItemInstance.Icon = ImageReference:FromPackRelativePath("images/" .. DoorSlot.Icons[selection] .. ".png", "overlay|images/other/selected_hub.png") end end end function DoorSlotSelection:onRightClick() DoorSlotSelection.Selection = self.index self:setState(1) self:updateNeighbors() end function DoorSlotSelection:canProvideCode(code) if code == self.code then return true else return false end end function DoorSlotSelection:providesCode(code) if code == self.code and self:getState() ~= 0 then return self:getState() end return 0 end function DoorSlotSelection:advanceToCode(code) if code == nil or code == self.code then self:setState((self:getState() + 1) % 2) end end function DoorSlotSelection:propertyChanged(key, value) if key == "state" then self:updateIcon() end end
local example = {} example.title = "Textinput" example.category = "Object Demonstrations" function example.func(loveframes, centerarea) local frame = loveframes.Create("frame") frame:SetName("Text Input") frame:SetSize(500, 90) frame:CenterWithinArea(unpack(centerarea)) local textinput = loveframes.Create("textinput", frame) textinput:SetPos(5, 30) textinput:SetWidth(490) textinput.OnEnter = function(object) if not textinput.multiline then object:Clear() end end textinput:SetFont(love.graphics.newFont(12)) local togglebutton = loveframes.Create("button", frame) togglebutton:SetPos(5, 60) togglebutton:SetWidth(490) togglebutton:SetText("Toggle Multiline") togglebutton.OnClick = function(object) if textinput.multiline then frame:SetHeight(90) frame:Center() togglebutton:SetPos(5, 60) textinput:SetMultiline(false) textinput:SetHeight(25) textinput:SetText("") frame:CenterWithinArea(unpack(centerarea)) else frame:SetHeight(365) frame:Center() togglebutton:SetPos(5, 335) textinput:SetMultiline(true) textinput:SetHeight(300) textinput:SetText("") frame:CenterWithinArea(unpack(centerarea)) end end end return example
--@name Fog Controller --@author Name --@client local distance = 0 local density = 0 local function setupFog(scale) -- distances have to be corrected according to skybox's scale local skybox_mul = scale or 1 -- only calculate fog properties once, in SetupWorldFog hook if not scale then local chipPos = chip():getPos() local ownerPos = owner():getPos() distance = chipPos:getDistance(ownerPos) density = 1 - math.clamp(distance / 500, 0, 1) end render.setFogMode(1) render.setFogColor(Color(230,245,255)) -- thickens the fog when you get closer to the chip render.setFogDensity(density) render.setFogStart(distance / 500 * skybox_mul) render.setFogEnd((distance + 1000) * skybox_mul) end hook.add("SetupWorldFog", "", setupFog) hook.add("SetupSkyboxFog", "", setupFog) if player() == owner() then render.setHUDActive(true) end
module 'mock' require 'mock.ui.light' require 'mock.ui.tb'
-- See LICENSE for terms local mod_EnableMod -- fired when settings are changed/init local function ModOptions() mod_EnableMod = CurrentModOptions:GetProperty("EnableMod") end -- load default/saved settings OnMsg.ModsReloaded = ModOptions -- fired when option is changed function OnMsg.ApplyModOptions(id) if id == CurrentModId then ModOptions() end end function OnMsg.LoadGame() if not mod_EnableMod then return end local type = type -- get all the marks then check pos of each for the parsystem and remove it as well local marks = MapGet("map", "AlienDiggerMarker") for i = 1, #marks do local mark = marks[i] -- get all pars at the same pos local pars = MapGet(mark:GetPos(), 0, "ParSystem") for j = 1, #pars do local par = pars[j] -- check that it's the right particle if par:GetParticlesName() == "Rocket_Landing_Pos_02" and type(par.polyline) == "string" and par.polyline:find("\0") then par:delete() end end mark:delete() end end
require("common.classType") require("common.container") require("common.definitions") local _xpcall = xpcall local _debug_traceback = debug.traceback local function msg_hander(msg) return _debug_traceback(msg, 2) end function TRACEBACK_PCALL(func, ...) return _xpcall(func, msg_hander, ...) end function TRACE_LOAD_FILE(path, env, ...) if not FileData.Exists(path) then error('File '..script..' not exists.'); return; end local buf = FileData.Read(path); local f,err = load(buf, path, 'bt', env or _ENV); if f==nil then error(err); return; end return f(...); end local string_id_string_map = {}; function STRING_ID(str) local string_id = string_id_string_map[str]; if string_id == nil then string_id = StringID:new(str); string_id_string_map[str] = string_id; end return string_id; end STRING_ID_EMPTY = STRING_ID("");
project "FastLZ" SetupNativeDependencyProject() local version = "0.1.0" local repo = "http://fastlz.googlecode.com/svn/trunk/" local license = "MIT" kind "StaticLib" files { "src/*.c" } includedirs { "include" }
minetest.register_biome({ name = "warm_crystal", node_top = "default:stone", depth_top = 1, node_filler = "default:stone", depth_filler = 1, node_stone = "default:stone", node_riverbed = "default:sand", depth_riverbed = 2, y_min = 1, y_max = weird_biomes.max.y, heat_point = 80, humidity_point = 10, }) minetest.register_biome({ name = "warm_crystal_ocean", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, node_stone = "default:stone", node_riverbed = "default:sand", depth_riverbed = 2, y_min = weird_biomes.secondary_min, y_max = 0, heat_point = 80, humidity_point = 10, }) minetest.register_biome({ name = "cold_crystal", node_top = "default:stone", depth_top = 1, node_filler = "default:stone", depth_filler = 1, node_stone = "default:stone", node_riverbed = "caverealms:salt_crystal", depth_riverbed = 2, node_water_top = "caverealms:thin_ice", depth_water_top = 2, node_river_water = "caverealms:thin_ice", y_min = 1, y_max = weird_biomes.max.y, heat_point = 10, humidity_point = 10, }) minetest.register_biome({ name = "cold_crystal_ocean", node_top = "caverealms:salt_crystal", depth_top = 1, node_filler = "caverealms:salt_crystal", depth_filler = 2, node_stone = "default:stone", node_riverbed = "caverealms:salt_crystal", depth_riverbed = 2, node_water_top = "caverealms:thin_ice", depth_water_top = 2, node_river_water = "caverealms:thin_ice", y_min = weird_biomes.secondary_min, y_max = 0, heat_point = 10, humidity_point = 10, }) weird_biomes.include("crystal_decorations.lua") weird_biomes.include("crystal_ores.lua")
PartyFrameModule = classes.class(Module) local function modifyPartyFrameUI() for i = 1, 4 do _G["PartyMemberFrame"..i]:SetScale(1.6) end end function PartyFrameModule:init() self.super:init() self:addEvent("PLAYER_ENTERING_WORLD") end function PartyFrameModule:eventHandler(event, ...) if event == "PLAYER_ENTERING_WORLD" then modifyPartyFrameUI() -- Modify PartyFrame position Utils.ModifyFrameFixed(PartyMemberFrame1, "LEFT", nil, 175, 125, nil) end end
local M = {} local memory = _G.memory local luap = require 'luap' local config = require 'config' local draw = require 'draw' local widget = require 'widget' local smw = require 'game.smw' local empty = luap.empty_array local OPTIONS = config.OPTIONS local COLOUR = config.COLOUR -- Private methods local function check_collision() local slot = memory.getregister('x') local target = memory.getregister('y') local RAM = memory.readregion('WRAM', 0, 0xC) local str = string.format('#%x vs #%x, (%d, %d) is %dx%d vs (%d, %d) is %dx%d', slot, target, 0x100 * RAM[8] + RAM[0], 0x100 * RAM[9] + RAM[1], RAM[2], RAM[3], 0x100 * RAM[0xA] + RAM[4], 0x100 * RAM[0xB] + RAM[5], RAM[6], RAM[7]) return str end local function register(t) local watch = t.watch memory.registerexec('BUS', smw.CHECK_FOR_CONTACT_ROUTINE, function() local flag = memory.getregister('p') % 2 == 1 if flag or OPTIONS.display_collision_routine_fail then watch[#watch + 1] = {text = check_collision(), collision_flag = flag} end end) end -- Public methods function M:init() self.watch = {} register(self) end function M:reset() local watch = self.watch if watch[1] then empty(watch) end end -- Check for collision -- TODO: unregisterexec when this option is OFF function M:display() draw.Font = 'Uzebox8x12' local height = draw.font_height() local x = draw.AR_x * widget:get_property('collision', 'x') local y = draw.AR_y * widget:get_property('collision', 'y') local watch = self.watch local do_display = OPTIONS.debug_collision_routine draw.text(x, y, 'Collisions', do_display and COLOUR.text or COLOUR.very_weak) y = y + height if do_display and watch[1] then for _, id in ipairs(watch) do local text = id.text local flag = id.collision_flag local color = flag and COLOUR.warning or COLOUR.weak draw.text(x, y, text, color) y = y + height end end end function M.new() local t = {} setmetatable(t, {__index = M}) t:init() widget:new('collision', 0, 224) widget:set_property('collision', 'display_flag', true) return t end return M
--------------------------------------------------------------------------------------------------- ---view3d.lua ---date: 2021.8.13 ---references: -x/src/core/view.lua, -x/src/core/screen.lua ---desc: Defines View3d, storing parameters for the 3d camera --------------------------------------------------------------------------------------------------- ---@class View3d local M = LuaClass("View3d") --------------------------------------------------------------------------------------------------- ---init function M.__create() return {} end function M:ctor() self:reset() end --------------------------------------------------------------------------------------------------- ---modifiers ---重置self的值 | reset the value of view3d function M:reset() self.eye = { 0, 0, -1 } -- camera position self.at = { 0, 0, 0 } -- camera target position self.up = { 0, 1, 0 } -- camera up, used for determining the orientation of the camera self.fovy = PI_2 -- controls size of spherical view field in vertical direction (in radians) self.z = { 1, 2 } -- clipping plane, {near, far} self.fog = { 0, 0, Color(0x00000000) } -- fog param, {start, end, color} self.dirty = true -- a flag set to true if any of the above attribute(s) has changed via api end ---设置self的值 | set one attribute of view3d ---@param key string specifies which attribute to set; will set the value of self[key] ---@param a number parameter ---@param b number additional parameter if needed ---@param c number|lstg.Color additional parameter if needed function M:set3D(key, a, b, c) if key == "fog" then a = tonumber(a or 0) b = tonumber(b or 0) self.fog = { a, b, c } return end a = tonumber(a or 0) b = tonumber(b or 0) c = tonumber(c or 0) if key == "eye" then self.eye = { a, b, c } elseif key == "at" then self.at = { a, b, c } elseif key == "up" then self.up = { a, b, c } elseif key == "fovy" then self.fovy = a elseif key == "z" then self.z = { a, b } end self.dirty = true end --------------------------------------------------------------------------------------------------- ---debugging function M:getStringRepr() local eye_str = string.format( 'eye: (%.1f, %.1f, %.1f)', self.eye[1], self.eye[2], self.eye[3]) local at_str = string.format( 'at: (%.1f, %.1f, %.1f)', self.at[1], self.at[2], self.at[3]) local up_str = string.format( 'up: (%.1f, %.1f, %.1f)', self.up[1], self.up[2], self.up[3]) local fovy_z_str = string.format( 'fovy: %.2f z: (%.1f, %.1f)', self.fovy, self.z[1], self.z[2]) local fog = self.fog local fog_str = string.format( 'fog: (%.2f, %.2f) with color (%.2f, %.2f, %.2f)', fog[1], fog[2], fog[3][1], fog[3][2], fog[3][3]) local ret = string.format( "%s\n%s\n%s\n%s\n%s", eye_str, at_str, up_str, fovy_z_str, fog_str) return ret end return M
#showtooltip Evocation /equip Soulkeeper /cast Evocation /equip Rod of the Ogre Magi
--[[ � CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). --]] local CLASS = Clockwork.class:New("Vortigaunt"); CLASS.color = Color(255, 200, 100, 255); CLASS.factions = {FACTION_VORTIGAUNT}; CLASS.isDefault = true; CLASS.wagesName = "Supplies"; CLASS.description = "An alien race from the planet Xen."; CLASS.defaultPhysDesc = "A strange, alien creature with a large eye, surrounded by three smaller eyes."; CLASS_VORTIGAUNT = CLASS:Register();
local PANEL = {} function PANEL:Init() self:SetWide(300) self:SetKeyboardInputEnabled(true) self.F1Down = true self:SetFont("DarkRPHUD2") -- This will eventually be gone when placeholder support is added to GMod self.lblSearch = vgui.Create("DLabel", self) self.lblSearch:SetFont("DarkRPHUD2") self.lblSearch:SetText(DarkRP.getPhrase("f1Search")) self.lblSearch:SizeToContents() self.lblSearch:SetPos(5) function self.lblSearch:UpdateColours(skin) self:SetTextStyleColor(skin.colTextEntryTextPlaceholder or Color(169, 169, 169)) end end function PANEL:OnLoseFocus() end local F1Bind function PANEL:Think() F1Bind = F1Bind or input.KeyNameToNumber(input.LookupBinding("gm_showhelp")) if not F1Bind then return end if self.F1Down and not input.IsKeyDown(F1Bind) then self.F1Down = false return elseif not self.F1Down and input.IsKeyDown(F1Bind) then self.F1Down = true self:GetParent():slideOut() end end hook.Add("PlayerBindPress", "DarkRPF1Bind", function(ply, bind, pressed) if string.find(bind, "gm_showhelp", 1, true) then F1Bind = input.KeyNameToNumber(input.LookupBinding(bind)) end end) function PANEL:OnTextChanged() self.BaseClass.OnTextChanged(self) if self:GetText() == "" then self.lblSearch:SetVisible(true) else self.lblSearch:SetVisible(false) end end derma.DefineControl("F1SearchBox", "The search box to search chat commands", PANEL, "DTextEntry")
-------------------------------------------------------------------------------- -- Handler.......... : onDlcItemConfirmation -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function Steam.onDlcItemConfirmation ( sDlcAppId, sOptionalEnvironmentVariable ) -------------------------------------------------------------------------------- --[[ if system.getOSType ( ) ~= system.kOSTypeWindows then return -- plugin not updated for osx yet end --]] local sPlayer = Steamworks.GetLocalPlayerName ( ) if string.getLength ( sPlayer ) > 0 then local bInstalled = Steamworks.IsDlcInstalled ( sDlcAppId ) -- if an env var has been given and if the value is true we set it if bInstalled and sOptionalEnvironmentVariable then log.message( "Dlc id: ",sDlcAppId," confirmed and saved as ",sOptionalEnvironmentVariable ) application.setCurrentUserEnvironmentVariable ( sOptionalEnvironmentVariable, true ) else log.message( "Dlc :",sOptionalEnvironmentVariable," not installed" ) application.setCurrentUserEnvironmentVariable ( sOptionalEnvironmentVariable, false ) end else log.message( "No Steam Player found" ) end -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
object_draft_schematic_clothing_clothing_backpack_treasure_map_s01 = object_draft_schematic_clothing_shared_clothing_backpack_treasure_map_s01:new { } ObjectTemplates:addTemplate(object_draft_schematic_clothing_clothing_backpack_treasure_map_s01, "object/draft_schematic/clothing/clothing_backpack_treasure_map_s01.iff")
data.raw["accumulator"]["basic-accumulator"].fast_replaceable_group = "accumulator" data.raw["solar-panel"]["solar-panel"].fast_replaceable_group = "solar-panel" data.raw["generator"]["steam-engine"].fast_replaceable_group = "steam-engine"
local lpeg = require("lpeg") local json = require("json") local lunit = require("lunit") local math = require("math") local testutil = require("testutil") local encode = json.encode -- DECODE NOT 'local' due to requirement for testutil to access it decode = json.decode.getDecoder(false) module("lunit-calls", lunit.testcase, package.seeall) function setup() -- Ensure that the decoder is reset _G["decode"] = json.decode.getDecoder(false) end local values = { 0, 1, 0.2, "Hello", true, {hi=true}, {1,2} } function test_identity() local function testFunction(capturedName, ...) assert_equal('call', capturedName) return (...) end local strict = { calls = { defs = { call = testFunction } } } local decode = json.decode.getDecoder(strict) for i, v in ipairs(values) do local str = "call(" .. encode(v) .. ")" local decoded = decode(str) if type(decoded) == 'table' then for k2, v2 in pairs(v) do assert_equal(v2, decoded[k2]) decoded[k2] = nil end assert_nil(next(decoded)) else assert_equal(v, decoded) end end end -- Test for a function that throws function test_function_failure() local function testFunction(...) error("CANNOT CONTINUE") end local strict = { calls = { defs = { call = testFunction } } } local decode = json.decode.getDecoder(strict) for i, v in ipairs(values) do local str = "call(" .. encode(v) .. ")" assert_error(function() decode(str) end) end end -- Test for a function that is not a function function test_not_a_function_fail() local notFunction = { 0/0, 1/0, -1/0, 0, 1, "Hello", {}, coroutine.create(function() end) } for _, v in ipairs(notFunction) do assert_error(function() local strict = { calls = { defs = { call = v }, allowUndefined = false } } json.decode.getDecoder(strict) end) end end function test_not_permitted_fail() local strict = { calls = { defs = { call = false } } } local decoder = json.decode.getDecoder(strict) assert_error(function() decoder("call(1)") end) end function test_permitted() local strict = { calls = { defs = { call = true } } } local decoder = json.decode.getDecoder(strict) assert(decoder("call(1)").name == 'call') end function test_not_defined_fail() local decoder = json.decode.getDecoder({ calls = { allowUndefined = false } }) assert_error(function() decoder("call(1)") end) end function test_not_defined_succeed() local decoder = json.decode.getDecoder({ calls = { allowUndefined = true } }) assert(decoder("call(1)").name == 'call') end -- Test for a name that is not a string function test_name_not_string() local notString = { true, false, 0/0, 1/0, -1/0, 0, 1, {}, function() end, coroutine.create(function() end) } for _, v in ipairs(notString) do assert_error(function() local defs = { [v] = function() end } local strict = { calls = { defs = defs } } json.decode.getDecoder(strict) end) end end -- Test for a name that is a string or a pattern function test_name_matches_string_or_pattern() local matchedValues = { ["mystring"] = "mystring", [lpeg.C(lpeg.P("m") * (lpeg.P("y") + lpeg.P("Y")) * "string")] = "mystring", [lpeg.C(lpeg.P("m") * (lpeg.P("y") + lpeg.P("Y")) * "string")] = "mYstring" } for pattern, value in pairs(matchedValues) do local matched = false local function mustBeCalled(capturedName, ...) assert_equal(value, capturedName) matched = true end matched = false local strict = { calls = { defs = { [pattern] = mustBeCalled } } } json.decode.getDecoder(strict)(value .. "(true)") assert_true(matched, "Value <" .. value .. "> did not match the given pattern") end end
-- webapi.lua v0.1 -- Copyright (c) 2017 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 http = require("socket.http") local ltn12 = require("ltn12") local webapi = { prefix = 'WEBAPI_', queries = {} } if type(...) == "number" then require "love.timer" local i = ... --let's avoid the strange ".. ... .." syntax local args = love.thread.getChannel(webapi.prefix .. i .. '_ARGS'):pop() local body = {} args.sink = ltn12.sink.table(body) local r, c, h = http.request(args) love.thread.getChannel(webapi.prefix .. i .. '_RES'):push({ table.concat(body), h, c }) else local filepath = (...):gsub("%.", "/") .. ".lua" function webapi.request(args, callback) local thread = love.thread.newThread(filepath) local query = { thread = thread, callback = callback, index = #webapi.queries + 1, active = true } webapi.queries[query.index] = query love.thread.getChannel(webapi.prefix .. query.index .. '_ARGS'):push(args) thread:start(query.index) return query end function webapi.update() for i, query in pairs(webapi.queries) do if query.thread then if not query.thread:isRunning() then --either done, or error query.active = false local err = query.thread:getError() assert(not err, err) local result = love.thread.getChannel(webapi.prefix .. i .. '_RES'):pop() if result ~= nil then if query.callback then query.callback(unpack(result)) end love.thread.getChannel(webapi.prefix .. i .. '_RES'):push(nil) end webapi.queries[query.index] = nil end end end end function webapi.cancel(query) if query.thread and query.thread:isRunning() then --TODO query.callback = nil --let's just remove callback for now end end return webapi end
local test = {} local json = require('arken.json') local Class = require('arken.oop.Class') local ActiveRecord = require('arken.ActiveRecord') local Adapter = require('arken.ActiveRecord.PostgresAdapter') test.beforeAll = function() ActiveRecord.reset() ActiveRecord.config = "util/config/active_record_postgres_database_invalid.json" end test.afterAll = function() ActiveRecord.config = nil end test.should_error_connect_with_database_invalid = function() Adapter.instanceConnection = nil local PostgresConnect = Class.new("PostgresConnect", "ActiveRecord") local status, message = pcall( PostgresConnect.columns ) assert( status == false ) assert( message:contains('LuaSQL: error connecting to database. PostgreSQL: FATAL: role "userunknow" does not exist') == true, message ) end return test
AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") include("shared.lua") --------------------------------------------------------- -- --------------------------------------------------------- function ENT:Initialize() self:SetModel("models/sassafrass/icecube.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_NONE) self:SetCollisionGroup(COLLISION_GROUP_PLAYER) self:DrawShadow(false) self.life = 1 end --------------------------------------------------------- -- --------------------------------------------------------- function ENT:StartTouch(entity) if (!self.removed) then if (IsValid(entity) and entity.IsPlayer and entity:IsPlayer()) then local position = self:GetPos() local playerPosition = entity:GetPos() if (playerPosition.z >= position.z) then if (!self.timer) then timer.Simple(0.6, function() if IsValid(entity) then self.life = 0 end end) self.timer = true end end end local physicsObject = self:GetPhysicsObject() if (IsValid(physicsObject)) then physicsObject:Sleep() physicsObject:EnableMotion(false) end end end --------------------------------------------------------- -- --------------------------------------------------------- function ENT:Think() if !self.removed then if (self.life <= 0) then self.removed = true self:SetNoDraw(true) self:SetNotSolid(true) end end self:NextThink(CurTime() +0.05) return true end
mtbench.register("get_node", function(executeCondition) local count = 0 while executeCondition() do local pos = { x = math.random(10000), y = math.random(10000), z = math.random(10000) } minetest.get_node(pos) count = count + 1 end return count end) mtbench.register("get_node_or_nil", function(executeCondition) local count = 0 while executeCondition() do local pos = { x = math.random(10000), y = math.random(10000), z = math.random(10000) } minetest.get_node_or_nil(pos) count = count + 1 end return count end) mtbench.register("get_meta", function(executeCondition) local count = 0 while executeCondition() do local pos = { x = math.random(10000), y = math.random(10000), z = math.random(10000) } minetest.get_meta(pos) count = count + 1 end return count end) mtbench.register("get_node_timer", function(executeCondition) local count = 0 while executeCondition() do local pos = { x = math.random(10000), y = math.random(10000), z = math.random(10000) } minetest.get_node_timer(pos) count = count + 1 end return count end)
require("src/State") --local M_lrandom = require("random") Util = Util or {} local M = Util --[[M.data = M.data or { rng = nil }--]] function M.init() --M.data.rng = M_lrandom.new(os.time()) math.randomseed(os.time()) end function ternary(cond, x, y) return (cond) and x or y end function optional(value, default) return (nil ~= value) and value or default end function is_type(x, tc) return type(tc) == "table" and (type(x) == "table" and tc == x.__index) or tc == type(x) end function type_assert(x, tc, opt) opt = optional(opt, false) assert( (opt and nil == x) or is_type(x, tc), "type_assert: '" .. tostring(x) .. "' (a " .. type(x) .. ") is not of type " .. tostring(tc) ) end function type_assert_obj(x, tc, opt) opt = optional(opt, false) assert( (opt and nil == x) or x:typeOf(tc) ) end function table.last(table) assert(0 < #table) return table[#table] end local function get_trace() local info = debug.getinfo(3, "Sl") local function pad(str, length) if #str < length then while #str < length do str = ' ' .. str end end return str end return info.short_src .. " @ " .. pad(tostring(info.currentline), 4) end function trace() print(get_trace() .. ": TRACE") end function log(msg, ...) type_assert(msg, "string") print(get_trace() .. ": " .. string.format(msg, ...)) end function log_debug_sys(sys, msg, ...) type_assert(msg, "string") if true == sys then print(get_trace() .. ": debug: " .. string.format(msg, ...)) end end function log_debug(msg, ...) type_assert(msg, "string") if true == State.gen_debug then print(get_trace() .. ": debug: " .. string.format(msg, ...)) end end function random(x, y) --return M.data.rng:value(x, y) return math.random(x, y) end function choose_random(table) return table[random(1, #table)] end function set_functable(t, func) if not t.__class_static then t.__class_static = {} t.__class_static.__index = t.__class_static setmetatable(t, t.__class_static) end t.__class_static.__call = func end function class(c) if nil == c then c = {} c.__index = c set_functable(c, function(c, ...) local obj = {} setmetatable(obj, c) obj:__init(...) return obj end) end return c end function def_module(name, data) type_assert(name, "string") type_assert(data, "table", true) local m = _G[name] or {} if not m.data and data then m.data = data end _G[name] = m return m end function def_module_unit(name, data) local m = def_module(name, data) set_functable(m, function(m, ...) local obj = {} setmetatable(obj, m.Unit) obj:__init(...) return obj end) return m end function min(x, y) return x < y and x or y end function max(x, y) return x > y and x or y end function clamp(x, min, max) return x < min and min or x > max and max or x end -- takes: -- (rgba, alpha_opt), -- (rgb, alpha), or -- (rgb) with alpha = 255 function set_color_table(rgb, alpha) alpha = optional( alpha, optional(rgb[4], 255) ) Gfx.setColor(rgb[1],rgb[2],rgb[3], alpha) end return M
--[[ ########################################################################## ## ## ## Project: 'Taser' - resource for MTA: San Andreas ## ## ## ########################################################################## [C] Copyright 2013-2014, Falke ]] local cFunc = {} local cSetting = {} cSetting["shots"] = {} cSetting["shot_calcs"] = {} local last_shot = 1 -- FUNCTIONS -- --[[ cFunc["render_shots"] = function() for index, tbl in pairs(cSetting["shots"]) do dxDrawFuckedLine3D(tbl[1], tbl[2], tbl[3], tbl[4], tbl[5], tbl[6], tocolor(0, 255, 0)) end end]] cFunc["draw_shot"] = function(x1, y1, z1, x2, y2, z2) table.insert(cSetting["shots"], last_shot, {x1, y1, z1, x2, y2, z2}) -- SHOT CALCULATING local lastx, lasty, lastz = x1, y1, z1 local dis = getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2) cSetting["shot_calcs"][last_shot] = {} for i = 1, dis, 0.5 do -- cSetting["shot_calcs"][i] = nx, ny, nz -- cSetting["shot_calcs"][last_shot][i] = end last_shot = last_shot+1 end cFunc["shot_weapon"] = function(hitX, hitY, hitZ, x, y, z) playSound3D("data/Fire.wav", x, y, z) local s = playSound3D("data/Fire.wav", hitX, hitY, hitZ) setSoundMaxDistance(s, 50) for i = 1, 5, 1 do fxAddPunchImpact(hitX, hitY, hitZ, 0, 0, 0) fxAddSparks(hitX, hitY, hitZ, 0, 0, 0, 8, 1, 0, 0, 0, true, 3, 1) end cFunc["draw_shot"](x, y, z, hitX, hitY, hitZ) fxAddPunchImpact(x, y, z, 0, 0, -3) end cFunc["wait_shot"] = function() toggleControl("fire", false) setTimer(function() toggleControl("fire", true) end, 350, 1) end cFunc["shot_check"] = function(wp, _, _, hitX, hitY, hitZ, element, startX, startY, startZ) if(wp == 23) then cFunc["shot_weapon"](hitX, hitY, hitZ, startX, startY, startZ) if(source == localPlayer) then cFunc["wait_shot"]() end end end dxDrawFuckedLine3D = function(x1, y1, z1, x2, y2, z2, color) local dis = getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2) local lastx, lasty, lastz = x1, y1, z1 for i = 1, dis, 3 do dxDrawLine3D(x1, y1, z1, x2, y2, z2) end end cFunc["anim_check"] = function(_, wep, bodypart) if(wep == 23) and (bodypart == 9) then setPedAnimation(source, "ped", "KO_shot_face", 10000, false, true, false) elseif(wep == 23) and (bodypart == 8) then setPedAnimation(source, "CRACK", "crckdeth2", 10000, false, true, false) elseif(wep == 23) and (bodypart == 7) then setPedAnimation(source, "CRACK", "crckdeth2", 10000, false, true, false) elseif(wep == 23) and (bodypart == 6) then setPedAnimation(source, "CRACK", "crckdeth2", 10000, false, true, false) elseif(wep == 23) and (bodypart == 5) then setPedAnimation(source, "CRACK", "crckdeth2", 10000, false, true, false) elseif(wep == 23) and (bodypart == 4) then setPedAnimation(source, "CRACK", "crckdeth3", 10000, false, true, false) elseif(wep == 23) and (bodypart == 3) then setPedAnimation(source, "ped", "KO_shot_stom", 10000, false, true, false) elseif(wep == 23) and (bodypart == 2) then setPedAnimation(source, "CRACK", "crckdeth2", 10000, false, true, false) elseif(wep == 23) and (bodypart == 1) then setPedAnimation(source, "CRACK", "crckdeth2", 10000, false, true, false) end end -- EVENT HANDLER -- addEventHandler("onClientPlayerWeaponFire", getRootElement(), cFunc["shot_check"]) addEventHandler("onClientRender", getRootElement(), cFunc["render_shots"]) addEventHandler("onClientPedDamage", getRootElement(),cFunc["anim_check"]) addEventHandler("onClientPlayerDamage", getRootElement(),cFunc["anim_check"])
if select(1,...) == "-?" then printUsage( "lua","Starts Lua interpreter" ) return end print("LuaJIT ".._VERSION) print("Type 'exit' to exit") pushColor() while true do color(7) print("> ",false) local code = input(); print("") if not code or code == "exit" then break end local chunk, err = loadstring(code) if not chunk then color(8) print("C-ERR: "..tostring(err)) else popColor() local ok, err = pcall(chunk) pushColor() if not ok then color(8) print("R-ERR: "..tostring(err)) else print("") end end end
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local cjson = require "cjson" local STUB_GET_URL = spec_helper.STUB_GET_URL describe("RateLimiting Plugin", function() setup(function() spec_helper.prepare_db() spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() spec_helper.reset_db() end) describe("Without authentication (IP address)", function() it("should get blocked if exceeding limit", function() -- Default ratelimiting plugin for this API says 6/minute local limit = 6 for i = 1, limit do local response, status, headers = http_client.get(STUB_GET_URL, {}, {host = "test4.com"}) assert.are.equal(200, status) assert.are.same(tostring(limit), headers["x-ratelimit-limit"]) assert.are.same(tostring(limit - i), headers["x-ratelimit-remaining"]) end -- Additonal request, while limit is 6/minute local response, status, headers = http_client.get(STUB_GET_URL, {}, {host = "test4.com"}) local body = cjson.decode(response) assert.are.equal(429, status) assert.are.equal("API rate limit exceeded", body.message) end) end) describe("With authentication", function() describe("Default plugin", function() it("should get blocked if exceeding limit", function() -- Default ratelimiting plugin for this API says 6/minute local limit = 6 for i = 1, limit do local response, status, headers = http_client.get(STUB_GET_URL, {apikey = "apikey123"}, {host = "test3.com"}) assert.are.equal(200, status) assert.are.same(tostring(limit), headers["x-ratelimit-limit"]) assert.are.same(tostring(limit - i), headers["x-ratelimit-remaining"]) end -- Third query, while limit is 2/minute local response, status, headers = http_client.get(STUB_GET_URL, {apikey = "apikey123"}, {host = "test3.com"}) local body = cjson.decode(response) assert.are.equal(429, status) assert.are.equal("API rate limit exceeded", body.message) end) end) describe("Plugin customized for specific consumer", function() it("should get blocked if exceeding limit", function() -- This plugin says this consumer can make 4 requests/minute, not 6 like the default local limit = 8 for i = 1, limit do local response, status, headers = http_client.get(STUB_GET_URL, {apikey = "apikey122"}, {host = "test3.com"}) assert.are.equal(200, status) assert.are.same(tostring(limit), headers["x-ratelimit-limit"]) assert.are.same(tostring(limit - i), headers["x-ratelimit-remaining"]) end local response, status, headers = http_client.get(STUB_GET_URL, {apikey = "apikey122"}, {host = "test3.com"}) local body = cjson.decode(response) assert.are.equal(429, status) assert.are.equal("API rate limit exceeded", body.message) end) end) end) end)
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false) local ns = vim.api.nvim_create_namespace('test') -- print the namespace id so that we can call nvim_buf_clear_namespace manually to clear everything print('namespace', ns) for li, line in pairs(lines) do for col = 1, #line, 2 do vim.api.nvim_buf_set_extmark( 0, ns, li - 1, col - 1, { virt_text = {{ 'a', 'ErrorMsg'}}, virt_text_pos = 'overlay' } ) end end
if enableRemoteControl == true then --Send Command 3 local selected_machine = elements[selected_machine_index] for _,db in pairs(databanks) do if command_3:find("MAINTAIN") or command_3:find("BATCH") then craft_quantity = "" for _,digit in pairs(craft_quantity_digits) do craft_quantity = craft_quantity .. digit end command_3 = command_3 .. "_" .. craft_quantity end --selected_machine.command = command_3 db.setStringValue(selected_machine.id, command_3) if command_3:find("MAINTAIN") then command_3 = "MAINTAIN" end if command_3:find("BATCH") then command_3 = "BATCH" end end if emitter ~= nil then emitter.send(channels[elementsTypes[selected_index]:lower()], "") else system.print("Emitter not Linked") end end
ESX = nil local doorState = {} TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) RegisterServerEvent('esx_doorlock:updateState') AddEventHandler('esx_doorlock:updateState', function(doorIndex, state) local xPlayer = ESX.GetPlayerFromId(source) if xPlayer and type(doorIndex) == 'number' and type(state) == 'boolean' and Config.DoorList[doorIndex] and isAuthorized(xPlayer.job.name, Config.DoorList[doorIndex]) then doorState[doorIndex] = state TriggerClientEvent('esx_doorlock:setDoorState', -1, doorIndex, state) end end) ESX.RegisterServerCallback('esx_doorlock:getDoorState', function(source, cb) cb(doorState) end) function isAuthorized(jobName, doorObject) for k,job in pairs(doorObject.authorizedJobs) do if job == jobName then return true end end return false end
require('color') function Particle(x,y,color,accent) local part = {} part.tick = 0 part.color = color part.accent = accent addXYComponent(part,x,y) part.fragments = {} for i=1,7 do part.fragments[i] = {} addXYComponent(part.fragments[i],x,y) part.fragments[i].vel = {} addXYComponent(part.fragments[i].vel,math.floor( (love.math.random()-0.5) * 20),-math.floor(love.math.random() * 20 + 15)) end addLiveFunction(part,'draw',function(self) local old_color = {love.graphics.getColor()} self.radius = self.radius * 1.4 local dx,dy = actualPosition(self.x, self.y) love.graphics.setColor(self.color) love.graphics.circle('line',dx,dy, self.radius, math.floor(love.math.random()*5 + 3) ) love.graphics.setColor(self.accent) love.graphics.circle('line',dx,dy, self.radius, math.floor(love.math.random()*5 + 2) ) --love.graphics.circle('fill',dx+math.sin(angle)*self.radius/2,dy+math.cos(angle)*self.radius/2,20,math.floor(love.math.random()*5 + 2)) for i=1,#self.fragments do local f = self.fragments[i] love.graphics.setColor(self.color) love.graphics.circle('fill',dx + f.x,dy + f.y,20,math.floor(love.math.random()*5 + 5)) f.x = f.x + f.vel.x f.y = f.y + f.vel.y f.vel.y = f.vel.y + 2 end self.tick = self.tick + 1 if self.tick > 60 * 10 then removeLiveFunction(self,'draw') end love.graphics.setColor(old_color) end) part.radius = 16 return part end function particleExplosion(self) self.radius = self.radius + 1 print(self.radius) love.graphics.circle('line', self.x, self.y, self.radius, 5) end
local crypt = require "crypt" local md5 = crypt.md5 local pairs = pairs local ipairs = ipairs local sort = table.sort local concat = table.concat local __Version__ = 0.1 return function (mchid, key, map) map["mchid"] = mchid local keys = {} for key, value in pairs(map) do if value ~= '' then keys[#keys+1] = key end end sort(keys) local args = {} local parms = {} for index, key in ipairs(keys) do local k, v = key, map[key] args[#args+1] = {k, v} parms[#parms+1] = k .. '=' .. v end parms[#parms+1] = "key=" .. key args[#args+1] = {"sign", md5(concat(parms, "&"), true):upper()} return args end
local addonName, addonTable = ... local Addon = _G[addonName] local S = LibStub:GetLibrary("ShockahUtils") local Class = { prototype = { isActionFrameType = true, }, } Addon.ActionFrameType = Class local Instance = Class.prototype local Private = {} Class["__Private"] = Private function Class:New(type, name) local obj = Addon.FrameType:New(type, name) S:CloneInto(Class.prototype, obj) return obj end function Private:Register() Addon.FrameType:Register(Class:New(nil, "Action: Any")) Addon.FrameType:Register(Class:New("spell", "Action: Spell")) Addon.FrameType:Register(Class:New("item", "Action: Item")) Addon.FrameType:Register(Class:New("flyout", "Action: Flyout")) Addon.FrameType:Register(Class:New("companion", "Action: Companion")) Addon.FrameType:Register(Class:New("macro", "Action: Macro")) end function Instance:GetActionName(tracker) return tracker.actionName end function Instance:MatchesAction(tracker, action) if tracker.actionType and tracker.actionType ~= action.type then return false end if tracker.actionName then local number = tonumber(tracker.actionName) if number then if number ~= action.slot then return false end else if tracker.actionName ~= action.name then return false end end else return false end return true end function Instance:CreateConfigMenu(configAddon, tracker, container) local AceGUI = LibStub("AceGUI-3.0") local actionNameEditbox = AceGUI:Create("EditBox") actionNameEditbox:SetLabel("Action name") actionNameEditbox:SetText(tracker.actionName) actionNameEditbox:SetFullWidth(true) actionNameEditbox:SetCallback("OnEnterPressed", function(self, event, text) tracker.actionName = S:StringOrNil(text) self:ClearFocus() configAddon:Refresh(tracker) end) container:AddChild(actionNameEditbox) end function Instance:GetIcon(tracker, withPlaceholderTexture) return Addon.Tracker:GetIcon(tracker.actionType, tracker.actionName, withPlaceholderTexture) end function Instance:GetNameWithoutType(tracker) local number = tonumber(tracker.actionName) if number then return "Action Button #"..number end return (tracker.actionName or "<empty>") end function Instance:GetName(tracker) return self:GetNameWithoutType(tracker) end function Instance:Serialize(tracker, output) output.actionName = tracker.actionName end function Instance:Deserialize(input, tracker) tracker.actionName = input.actionName end function Instance:GetDefaultTexture(parentFrame) return parentFrame and parentFrame.Border:GetTexture(), "<button border>" end
function solve() local str = string.format("%.0f", 2 ^ 1000) local sum = 0 for i=1, #str do local char = str:sub(i, i) sum = sum + char end return math.floor(sum) end local result = solve() print(result)
function LoadDatabase(dataConfig, excluded_categories) ----------------------------------------------------------------- -- Reads the list of images in the videos from annotDir -- inputs: -- dataConfig: The data configuration to load from. Look at config.train -- and config.test. -- exclude_category: exclude this category in training -- outputs: -- dataset: a table with list of files for each category -- dataset[category][angle][video_directory] -- e.g., dataset['sliding-ski'][1]["181_1"] contains the files -- for video "181_1", which is annotated as the first angle ----------------------------------------------------------------- local max_angles = config.max_angles; -- 8 local annotDir = dataConfig.annotation.dir; local dataset = {}; -- categories local categories = paths.dir(annotDir); RemoveDotDirs(categories); categories = removeExcludedCategories(categories, excluded_categories); local nClasses = table.getn(categories); for i=1,nClasses do dataset[categories[i]] = {}; end for i=1,nClasses do -- videos local viddir = paths.concat(annotDir,categories[i]); local videos = paths.dir(viddir); RemoveDotDirs(videos); -- all viewpoint annotations will be similar to 00000_00's local angles = {}; for k,v in pairs(videos) do local viewannot if paths.filep(paths.concat(annotDir, categories[i], videos[k], '00000_00_ge.mat')) then viewannot = mattorch.load(paths.concat(annotDir, categories[i], videos[k], '00000_00_ge.mat')); else viewannot = mattorch.load(paths.concat(annotDir, categories[i], videos[k], 'view.mat')); end -- if categories[i] == 'scenario6-basketball' then -- debugger.enter() -- end angles[k] = viewannot.ge; end for j=1,max_angles do --maximum 8 different angles dataset[categories[i]][j] = {}; end for k,v in pairs(videos) do -- 1 018_03 scenario4-bowling -- if k == 1 and categories[i] == 'scenario4-bowling' then -- debugger.enter() -- end -- print(k,v,categories[i]) dataset[categories[i]][angles[k][1][1]][v] = {}; end for j=1,#dataset[categories[i]] do for k,v in pairs(dataset[categories[i]][j]) do local dir2 = paths.concat(annotDir,categories[i],k); local flist = paths.dir(dir2); RemoveDotDirs(flist); table.sort(flist, function (a,b) return a < b end); local pruned_flist = {} for id,f in pairs(flist) do if f:find("_00_ge.mat") then pruned_flist[#pruned_flist+1] = f end end dataset[categories[i]][j][k] = {}; dataset[categories[i]][j][k] = pruned_flist; end end end dataset.config = dataConfig; return dataset; end function LoadTrainDatabase(exclude_category) return LoadDatabase(config.train, exclude_category) end function LoadTestDatabase(exclude_category) return LoadDatabase(config.test, exclude_category) end function ReadIndividualFrame(dataset, category, angle, video_id, imname, savefile, input_type) ----------------------------------------------------------------- -- Reads a specific frame of a video for a category and an angle -- inputs: -- dataset: The output of "LoadTrainDatabase" -- category: Video category, e.g., 'sliding-ski', 'falling-diving', etc. -- angle: View angle (1 out of 8 or 1 out of 3 for symmetric categories) -- video_id: Video folder -- imname: The name of frame's image to be read. -- savefile: Save the tensor in this file. -- input_type: The type of the data to be read. Should be one of -- image, depth, normal or flow. -- output: -- images: 4D or 3D Tensor, -- [5 (orig + 4 crops) x] 3 (channels) x imH (image height) x imW (image width) ----------------------------------------------------------------- local imH = config.imH; local imW = config.imW; local w_crop = config.w_crop; local annotDir = dataset.config.annotation.dir local trainDir = dataset.config[input_type].dir; local image_type = dataset.config[input_type].type; local mean = dataset.config[input_type].mean; local std = dataset.config[input_type].std; local impath = paths.concat(trainDir, category, video_id, imname .. "." .. image_type); local im = loadImageOrig(impath); local imnorm = normalizeImage(image.scale(im, imW, imH), mean, std); local nChannels = dataset.config[input_type].nChannels; if w_crop and dataset.config[input_type].croppable then local images = torch.Tensor(5, nChannels, imH, imW) local coord = mattorch.load(paths.concat(annotDir, category, video_id, imname .. "_00.mat")); local imSize = im:size(); local height = imSize[2]; local width = imSize[3]; local x1 = math.max(math.floor(coord.box[1][1]), 1); local y1 = math.max(math.floor(coord.box[1][2]), 1); local x2 = math.min(math.floor(coord.box[1][3]), width); local y2 = math.min(math.floor(coord.box[1][4]), height); local crop1 = im[{{},{y1,height},{x1,width}}]; local crop2 = im[{{},{1,y2},{1,x2}}]; local crop3 = im[{{},{y1,height},{1,x2}}]; local crop4 = im[{{},{1,y2},{x1,width}}]; images[1] = imnorm; images[2] = normalizeImage(image.scale(crop1, imW, imH), mean, std); images[3] = normalizeImage(image.scale(crop2, imW, imH), mean, std); images[4] = normalizeImage(image.scale(crop3, imW, imH), mean, std); images[5] = normalizeImage(image.scale(crop4, imW, imH), mean, std); for i=1,5 do images[i] = images[i][{{1,nChannels}, {}, {}}] end images = images:reshape(5 * nChannels, imH, imW) torch.save(savefile, images); return images else imnorm = imnorm[{{1, nChannels}, {}}] torch.save(savefile, imnorm); return imnorm end end function LoadIndividualFrame(dataset, category, angle, video_id, imname, input_type) ----------------------------------------------------------------- -- Loads a specific frame of a video for a category and an angle -- inputs: -- dataset: The output of "LoadTrainDatabase" -- category: Video category, e.g., 'sliding-ski', 'falling-diving', etc. -- angle: View angle (1 out of 8 or 1 out of 3 for symmetric categories) -- video_id: Video folder -- imname: The name of frame's image to be read. -- savefile: Save the tensor in this file. -- input_type: Optional type of the data to be read. Should be one of -- image, depth, normal, flow or mask. -- output: -- images: 4D or 3D Tensor, -- [5 (orig + 4 crops) x] 3 (channels) x imH (image height) x imW (image width) ----------------------------------------------------------------- if not input_type then local imH = config.imH; local imW = config.imW; local all_input_types = GetEnableInputTypes(dataset.config) local nChannels = GetValuesSum(all_input_types) local result = torch.Tensor(nChannels, imH, imW); local i = 1 for input_type, nChannels in pairs(all_input_types) do result[{{i, i+nChannels-1}, {}, {}}] = LoadIndividualFrame(dataset, category, angle, video_id, imname, input_type) i = i + nChannels end return result end local suffix = dataset.config[input_type].suffix; local w_crop = config.w_crop; local saveDir = dataset.config.save_dir; if not paths.dirp(saveDir) then paths.mkdir(saveDir) end -- NOTE: If we may have different oids for a video, we need to use different -- save paths for w_crop = true. local fname = paths.concat(saveDir, category .. '_' .. video_id .. '_' .. (w_crop and '1' or '0') .. '_' .. suffix .. '_' .. imname .. '.t7'); if paths.filep(fname) then return torch.load(fname) else return ReadIndividualFrame(dataset, category, angle, video_id, imname, fname, input_type) end end function ReadTrainImagesPerVideo(dataset, category, angle, video_id, savefile, input_type) ----------------------------------------------------------------- -- Reads training images for a video for a category and an angle -- inputs: -- dataset: The output of "LoadTrainDatabase" -- category: Video category, e.g., 'sliding-ski', 'falling-diving', etc. -- angle: View angle (1 out of 8 or 1 out of 3 for symmetric categories) -- video_id: Video folder -- savefile: Save the tensor in this file. -- opts -- output: -- images: 5D Tensor, -- # of images x 5 (orig + 4 crops) x 3 (channels) x imH (image height) x imW (image width) ----------------------------------------------------------------- local imH = config.imH; local imW = config.imW; local trainDir = dataset.config[input_type].dir; local mean = dataset.config[input_type].mean; local std = dataset.config[input_type].std; local image_type = dataset.config[input_type].type; local w_crop = config.w_crop; local nImages = #dataset[category][angle][video_id]; local images if w_crop then -- FIXME(hessam): nChannel needs to be fixe images = torch.Tensor(nImages, 5, 3, imH, imW) else images = torch.Tensor(nImages, 3, imH, imW) end local cnt = 0; for _,f in ipairs(dataset[category][angle][video_id]) do cnt = cnt + 1; local matname = f; local imname, oid = f:match("([^_]+)_([^_]+)"); images[cnt] = LoadIndividualFrame(dataset, category, angle, video_id, imname, input_type) end collectgarbage() torch.save(savefile, images) return images end function LoadTrainImagesPerVideo(dataset, category, angle, video_id, input_type) ----------------------------------------------------------------- -- If files do not exist, it calls "ReadTrainImagesPerVideo" or "ReadTrainImagesPerVideoNoCrop". -- Otherwise, it loads from the disk. -- -- inputs: -- dataset: The output of "LoadTrainDatabase" -- category: Video category, e.g., 'sliding-ski', 'falling-diving', etc. -- angle: View angle (1 out of 8 or 1 out of 3 for symmetric categories) -- video_id: Video folder -- opts -- outputs: -- images: 4D or 5D Tensor, -- # of images x 5 (orig + 4 crops)? x 3 (channels) x -- imH (image height) x imW (image width) ----------------------------------------------------------------- local imH = config.imH; local imW = config.imW; local nImages = #dataset[category][angle][video_id]; local images, nChannels if input_type then nChannels = dataset.config[input_type].nChannels else local all_input_types = GetEnableInputTypes(dataset.config) nChannels = GetValuesSum(all_input_types) end images = torch.Tensor(nImages, nChannels, imH, imW) local cnt = 0; for _,f in ipairs(dataset[category][angle][video_id]) do cnt = cnt + 1; local matname = f; local imname, oid = f:match("([^_]+)_([^_]+)"); images[cnt] = LoadIndividualFrame(dataset, category, angle, video_id, imname, input_type) end return images end function LoadRandomFrameOfVideo(dataset, category, angle, video_id, input_type) ----------------------------------------------------------------- -- If files do not exist, it calls "ReadTrainImagesPerVideo" or "ReadTrainImagesPerVideoNoCrop". -- Otherwise, it loads from the disk. -- -- inputs: -- dataset: The output of "LoadTrainDatabase" -- category: Video category, e.g., 'sliding-ski', 'falling-diving', etc. -- angle: View angle (1 out of 8 or 1 out of 3 for symmetric categories) -- video_id: Video folder -- opts -- outputs: -- images: 3D or 4D Tensor, -- 5 (orig + 4 crops)? x 3 (channels) x -- imH (image height) x imW (image width) ----------------------------------------------------------------- local randomFrame = GetRandomValue(dataset[category][angle][video_id]) local imname = randomFrame:match('[^_]+') return LoadIndividualFrame(dataset, category, angle, video_id, imname, input_type) end
local addonName = ... local function split(pString, pPattern) local Table = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pPattern local last_end = 1 local s, e, cap = pString:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(Table,cap) end last_end = e+1 s, e, cap = pString:find(fpat, last_end) end if last_end <= #pString then cap = pString:sub(last_end) table.insert(Table, cap) end return Table end function PajMarker:InitializeChatCommands() -- Register /pm to call HandlePM using AceConsole-3.0 self:RegisterChatCommand("pm", "HandlePM") -- Register chat handlers for each "sub command" self.chatHandlers = { config = { func = "PMHandleConfig", usage = "Open the addon config dialog", }, lists = { func = "PMHandleLists", usage = "Configure lists", }, list = { func = "PMHandleList", usage = "Change list (e.g. /pm list bwl technician trash)", }, reset = { func = "PMHandleReset", usage = "Reset the current session", }, clear = { func = "PMHandleClear", usage = "Clear all raid markers currently assigned to units", }, usage = { func = "PMHandleUsage", usage = "Shows this help text", }, help = { func = "PMHandleUsage", hidden = true, }, export = { func = "ExportLists", usage = "Export lists to a string", }, import = { func = "ImportLists", usage = "Import lists from a string", }, } end function PajMarker:PMHandleUsage(subCommandName) if subCommandName ~= nil and type(subCommandName) == "string" then self:Print("Error: No sub command with the key '" .. subCommandName .. "' exists") end self:Print('PajMarker usage:') for key, value in pairs(self.chatHandlers) do if not value.hidden then self:Print(' /pm ' .. key .. ' - ' .. value.usage) end end end function PajMarker:PMReset() self:ResetSession() end -- Clear raid targets by setting all targets on yourself function PajMarker:PMHandleClear() SetRaidTarget("player", 1) SetRaidTarget("player", 2) SetRaidTarget("player", 3) SetRaidTarget("player", 4) SetRaidTarget("player", 5) SetRaidTarget("player", 6) SetRaidTarget("player", 7) SetRaidTarget("player", 8) SetRaidTarget("player", 0) end function PajMarker:PMHandleConfig() InterfaceOptionsFrame_OpenToCategory(addonName) InterfaceOptionsFrame_OpenToCategory(addonName) -- need a second time cuz this is bugged KKona end function PajMarker:PMHandleLists() self:ConfigureLists() end function PajMarker:PMHandleList(commands, command_i) local listName = commands[command_i] command_i = command_i + 1 local ll repeat ll = commands[command_i] if ll ~= nil then listName = listName .. " " .. ll end command_i = command_i + 1 until (ll == nil) if listName == nil then self:PMHandleUsage() return end if not self:SwitchList(listName) then self:Print("No list named " .. listName .. " exists") end end function PajMarker:PMHandleReset() self:ResetSession() end function PajMarker:HandlePM(msg, editbox) local commands = split(msg, " ") local command_i = 1 local subCommandName = commands[command_i] if subCommandName == nil then return self:PMHandleUsage(nil) end local subCommand = self.chatHandlers[subCommandName] if subCommand ~= nil then self[subCommand.func](self, commands, command_i + 1) return end self:PMHandleUsage(subCommandName) end
require('modules.revised') local suit = require('modules.suit') local Button = class() function Button:createButton(tableTitleAxistableSizetable) local title = tableTitleAxistableSizetable[1] local axisx = tableTitleAxistableSizetable[2].axisx local axisy = tableTitleAxistableSizetable[2].axisy local width = tableTitleAxistableSizetable[3].width local height = tableTitleAxistableSizetable[3].height local button = suit.Button(title, axisx, axisy, width, height) return button end function Button:createButtonInLayoutRow(tableTitleSuitinstanceSizetable) local title = tableTitleSuitinstanceSizetable[1] local suitInstance = tableTitleSuitinstanceSizetable[2] or suit local width = tableTitleSuitinstanceSizetable[3].width local height = tableTitleSuitinstanceSizetable[3].height return suitInstance.Button(title, suitInstance.layout:row(width, height)) end function Button:createButtonInLayoutCol(tableTitleSuitinstanceSizetable) local title = tableTitleSuitinstanceSizetable[1] local suitInstance = tableTitleSuitinstanceSizetable[2] or suit local width = tableTitleSuitinstanceSizetable[3].width local height = tableTitleSuitinstanceSizetable[3].height return suitInstance.Button(title, suitInstance.layout:col(width, height)) end function Button:createButtonInLayoutUp(tableTitleSuitinstanceSizetable) local title = tableTitleSuitinstanceSizetable[1] local suitInstance = tableTitleSuitinstanceSizetable[2] or suit local width = tableTitleSuitinstanceSizetable[3].width local height = tableTitleSuitinstanceSizetable[3].height return suitInstance.Button(title, suitInstance.layout:up(width, height)) end function Button:createButtonInLayoutDown(tableTitleSuitinstanceSizetable) local title = tableTitleSuitinstanceSizetable[1] local suitInstance = tableTitleSuitinstanceSizetable[2] or suit local width = tableTitleSuitinstanceSizetable[3].width local height = tableTitleSuitinstanceSizetable[3].height return suitInstance.Button(title, suitInstance.layout:down(width, height)) end function Button:createButtonInLayoutLeft(tableTitleSuitinstanceSizetable) local title = tableTitleSuitinstanceSizetable[1] local suitInstance = tableTitleSuitinstanceSizetable[2] or suit local width = tableTitleSuitinstanceSizetable[3].width local height = tableTitleSuitinstanceSizetable[3].height return suitInstance.Button(title, suitInstance.layout:left(width, height)) end return Button
dofile"setup.lua" do print"test: decode ipv4" local n = net.init() n:udp{src=1, dst=2, payload=" "} n:ipv4{src="1.2.3.1", dst="1.2.3.2", protocol=17, options="AAAA"} local b0 = n:block() print"= constructed:" print(n:dump()) print("b0", h(b0)) n:clear() print(n:dump()) print"= decoded:" assert(n:decode_ipv4(b0)) local ip1 = n:block(n:tag_below()) local b1 = n:block() print(n:dump()) print("b1", h(b1)) print"" assert(b0 == b1) local bot = assert(n:tag_below()) local top = assert(n:tag_above()) assert(bot == 3) assert(n:tag_below(bot) == nil) assert(n:tag_above(bot) == 2) assert(top == 1) assert(n:tag_above(top) == nil) assert(n:tag_below(top) == 2) assert(n:tag_type(bot) == "ipv4", n:tag_type(bot)) assert(n:tag_type(top) == "udp", n:tag_type(top)) local udpt = n:get_udp() udpt.payload = "\0" assert(n:udp(udpt)) local b2 = n:block() print(n:dump()) print("b2", h(b2)) -- everything up to the checksum should be the same assert(b1:sub(1, 20+4+6) == b2:sub(1, 20+4+6)) assert(b1:sub(20+4+7, 20+4+8) ~= b2:sub(20+4+7, 20+4+8)) assert(n:block(n:tag_below()) == ip1) print"+pass" end print""
ITEM.name = "23mm Shells" ITEM.model = "models/Items/BoxBuckshot.mdl" ITEM.width = 1 ITEM.height = 1 ITEM.ammo = "23mm Shell" ITEM.description = "A Box that contains 23mm Buckshot shells." ITEM.category = "Ammunition" ITEM.ammoAmount = 45 ITEM.isAmmo = true ITEM.ammoPerBox = 15 ITEM.price = 600 ITEM.weight = 0.2
fx_version 'cerulean' game 'gta5' lua54 'yes' files {'**.png', '**.jpg', '**.json', '**.txt'} server_script {'sv_*.lua'}