content
stringlengths 5
1.05M
|
---|
-- title: TICuare
-- author: Crutiatix
-- desc: UI library for TIC-80 v0.4.0
-- script: lua
-- input: mouse
-- Based on Uare (c) 2015 Ulysse Ramage
-- Copyright (c) 2017 Crutiatix
-- 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.
ticuare={name="ticuare",elements={},z=1,hz=nil} ticuare.__index=ticuare local e={__index=ticuare} local function i(e,n,o,t,r,d) return e>o and e<r and n>t and n<d end local function r(n,d,o) for e,t in pairs(d)do if type(t)=="table"then if type(n[e]or false)=="table"then r(n[e]or{},d[e]or{},o) else if not n[e]or o then n[e]=t end end else if not n[e]or o then n[e]=t end end end return n end local function a(r) local n={} local function t(e) if type(e)~="table"then return e elseif n[e]then return n[e] end local o={} n[e]=o for e,n in pairs(e)do o[t(e)]=t(n) end return setmetatable(o,getmetatable(e)) end return t(r) end function ticuare.mlPrint(a,o,d,l,n,c,i,u,s) local t={} local e=0 local r=0 for e in a:gmatch("([^\n]+)")do table.insert(t,e) end for a,t in ipairs(t)do if i then e=font(t,o,d+((a-1)*n),u,s) else e=print(t,o,d+((a-1)*n),l,c) end if e>r then r=e end end return e,#t*n end function ticuare.element(t,n) if not n then n=t t="element"end local e=n setmetatable(e,ticuare) e.hover,e.click=false,false e.active=n.active or true e.drag=n.drag or{enabled=false} e.visible=n.visible or true if e.content then if not e.content.scroll then e.content.scroll={x=0,y=0}end e.content.w,e.content.h=e.content.w or e.w,e.content.h or e.h end e.type,e.z=t,ticuare.z ticuare.z=ticuare.z+1 ticuare.hz=ticuare.z table.insert(ticuare.elements,e) return e end function ticuare.newElement(e)return ticuare.element("element",e)end function ticuare.newStyle(e)return e end function ticuare.newGroup()local e={type="group",elements={}}setmetatable(e,ticuare)return e end function ticuare:updateSelf(t,o,e,n) local a=n~="s"and e or false local e=i(t,o,self.x,self.y,self.x+self.w,self.y+self.h) if self.center then e=i(t,o,self.x-self.w*.5,self.y-self.h*.5,self.x+self.w*.5,self.y+self.h*.5) end local e=n~="s"and e or false local r,d=self.hover,self.hold self.hover=e or(self.drag.enabled and ticuare.holdt and ticuare.holdt.obj==self) self.hold=((n=="c"and e)and true)or(a and self.hold)or((e and n~="r"and self.hold)) if n=="c"and e and self.onClick then self.onClick() elseif(n=="r"and e and d)and self.onCleanRelease then self.onCleanRelease() elseif((n=="r"and e and d)or(self.hold and not e))and self.onRelease then self.onRelease() elseif self.hold and self.onHold then self.onHold() elseif not r and self.hover and self.onStartHover then self.onStartHover() elseif self.hover and self.onHover then self.onHover() elseif r and not self.hover and self.onReleaseHover then self.onReleaseHover() end if self.hold and(not e or self.drag.enabled)and not ticuare.holdt then self.hold=self.drag.enabled ticuare.holdt={obj=self,d={x=self.x-t,y=self.y-o}} elseif not self.hold and e and(ticuare.holdt and ticuare.holdt.obj==self)then self.hold=true ticuare.holdt=nil end if ticuare.holdt and ticuare.holdt.obj==self and self.drag.enabled then self.x=(not self.drag.fixed or not self.drag.fixed[1])and t+ticuare.holdt.d.x or self.x self.y=(not self.drag.fixed or not self.drag.fixed[2])and o+ticuare.holdt.d.y or self.y if self.drag.bounds then self.drag.bounds[1].x=self.drag.bounds[1].x or self.x self.drag.bounds[1].y=self.drag.bounds[1].y or self.y self.drag.bounds[2].x=self.drag.bounds[2].x or self.x self.drag.bounds[2].y=self.drag.bounds[2].y or self.y self.x=(self.drag.bounds[1].x and self.x<self.drag.bounds[1].x)and self.drag.bounds[1].x or self.x self.y=(self.drag.bounds[1].y and self.y<self.drag.bounds[1].y)and self.drag.bounds[1].y or self.y self.x=(self.drag.bounds[2].x and self.x>self.drag.bounds[2].x)and self.drag.bounds[2].x or self.x self.y=(self.drag.bounds[2].y and self.y>self.drag.bounds[2].y)and self.drag.bounds[2].y or self.y end if self.track then self:anchor(self.track.ref) end end return e end function ticuare:updateTrack() if self.track then self.x,self.y=self.track.ref.x+self.track.d.x,self.track.ref.y+self.track.d.y end end function ticuare:drawSelf() if self.visible then local t,e=self.x,self.y if self.center then t,e=self.x-self.w*.5,self.y-self.h*.5 end if self.colors then local n=((self.hold and self.colors[3])and self.colors[3])or((self.hover and self.colors[2])and self.colors[2])or self.colors[1]or nil if n then rect(t,e,self.w,self.h,n)end end if self.border and self.border.colors and self.border.width then local o=((self.hold and self.border.colors[3])and self.border.colors[3])or((self.hover and self.border.colors[2])and self.border.colors[2])or self.border.colors[1]or nil if o then for n=0,self.border.width-1 do rectb(t+n,e+n,self.w-2*n,self.h-2*n,o) end end end if self.icon and self.icon.sprites and#self.icon.sprites>0 then local o=((self.hold and self.icon.sprites[3])and self.icon.sprites[3])or((self.hover and self.icon.sprites[2])and self.icon.sprites[2])or self.icon.sprites[1] local n=self.icon.offset or{x=0,y=0} self.icon.key=self.icon.key or-1 self.icon.scale=self.icon.scale or 1 self.icon.flip=self.icon.flip or 0 self.icon.rotate=self.icon.rotate or 0 self.icon.size=self.icon.size or 1 for d=1,self.icon.size do for r=1,self.icon.size do spr(o+(d-1)+((r-1)*16), (t+(self.center and 0 or self.w*.5)+n.x-4), (e+(self.center and 0 or self.h*.5)+n.y-4), self.icon.key, self.icon.scale, self.icon.flip, self.icon.rotate) end end end if self.text and self.text.display and self.text.colors[1]then self.text.colors[1]=self.text.colors[1]or 14 self.text.space=self.text.space or 5 self.text.key=self.text.key or-1 self.text.spacing=self.text.spacing or(self.text.font and 8 or 6) self.text.fixed=self.text.fixed or false local e if(self.hold and self.text.colors[3])then e=self.text.colors[3] elseif(self.hover and self.text.colors[2])then e=self.text.colors[2] else e=self.text.colors[1]end local n=self.text.offset or{x=0,y=0} local t,o=ticuare.mlPrint(self.text.display,300,300,-1,self.text.spacing,self.text.fixed,self.text.font,self.text.key,self.text.space) ticuare.mlPrint(self.text.display, self.x-(self.center and(self.w*.5)or 0)+(self.text.center and(self.w*.5)-(t*.5)or 0)+n.x+(self.text.center and 0 or self.border.width), self.y-(self.center and(self.h*.5)or 0)+(self.text.center and(self.h*.5)-(o*.5)or 0)+n.y+(self.text.center and 0 or self.border.width), e,self.text.spacing,self.text.fixed,self.text.font,self.text.key,self.text.space ) end if self.content and self.drawContent then self:renderContent() end end end function ticuare:renderContent() local t,e=self.x,self.y if self.center then t,e=self.x-self.w*.5,self.y-self.h*.5 end local n=self.border.width and self.border.width+1 or 1 local t=t-(self.content.scroll.x or 0)*(self.content.w-self.w)+n local e=e-(self.content.scroll.y or 0)*(self.content.h-self.h)+n self.drawContent(self,t,e) end function ticuare:setContent(e) self.drawContent=e end function ticuare:setContentDimensions(n,e) if self.content then self.content.w,self.content.h=n,e end end function ticuare:setScroll(e) e.x=e.x or 0 e.y=e.y or 0 if self.content then e.x=(e.x<0 and 0)or(e.x>1 and 1)or e.x e.y=(e.y<0 and 0)or(e.y>1 and 1)or e.y self.content.scroll.x,self.content.scroll.y=e.x or self.content.scroll.x,e.y or self.content.scroll.y end end function ticuare:getScroll() if self.content then return{x=self.content.scroll.x,y=self.content.scroll.y} end end function ticuare.update(r,d,o) if r and d then local n,e="n",o if ticuare.c and not e then ticuare.c=false n="r"ticuare.holdt=nil elseif not ticuare.c and e then ticuare.c=true n="c"ticuare.holdt=nil end local t=false local e={} for n=1,#ticuare.elements do table.insert(e,ticuare.elements[n])end table.sort(e,function(e,n)return e.z>n.z end) for a=1,#e do local e=e[a] if e then if e:updateSelf(r,d,o,((t or(ticuare.holdt and ticuare.holdt.obj~=e))or not e.active)and"s"or n)then t=true end end end for e=#ticuare.elements,1,-1 do if ticuare.elements[e]then ticuare.elements[e]:updateTrack() end end end end function ticuare.draw() local e={} for n=1,#ticuare.elements do if ticuare.elements[n].draw then table.insert(e,ticuare.elements[n])end end table.sort(e,function(n,e)return n.z<e.z end) for n=1,#e do e[n]:drawSelf()end end function ticuare:style(e) if self.type=="group"then for n=1,#self.elements do r(self.elements[n],a(e),false) end else r(self,a(e),false) end return self end function ticuare:anchor(e) if self.type=="group"then self.elements[1].track={ref=e.elements[1],d={x=self.x-e.elements[1].x,y=self.y-otherelements.other.y}} else self.track={ref=e,d={x=self.x-e.x,y=self.y-e.y}} end return self end function ticuare:group(e) table.insert(e.elements,self) return self end function ticuare:setActive(e) if self.type=="group"then for n=1,#self.elements do self.elements[n]:setActive(e) end else self.active=e end end function ticuare:enable()return self:setActive(true)end function ticuare:disable()return self:setActive(false)end function ticuare:getActive()if self.active~=nil then return self.active end end function ticuare:setVisible(e) if self.type=="group"then for n=1,#self.elements do self.elements[n]:setVisible(e) end else self.visible=e end end function ticuare:show(e)return self:setVisible(true,e)end function ticuare:hide(e)return self:setVisible(false,e)end function ticuare:getVisible()if self.visible~=nil then return self.visible end end function ticuare:setDragBounds(e) self.drag.bounds=e end function ticuare:setHorizontalRange(e) self.x=self.drag.bounds[1].x+(self.drag.bounds[2].x-self.drag.bounds[1].x)*e end function ticuare:setVerticalRange(e) self.y=self.drag.bounds[1].y+(self.drag.bounds[2].y-self.drag.bounds[1].y)*e end function ticuare:getHorizontalRange() assert(self.drag.bounds and self.drag.bounds[1]and self.drag.bounds[2]and self.drag.bounds[1].x and self.drag.bounds[2].x,"Element must have 2 horizontal boundaries") return(self.x-self.drag.bounds[1].x)/(self.drag.bounds[2].x-self.drag.bounds[1].x) end function ticuare:getVerticalRange() assert(self.drag.bounds and self.drag.bounds[1]and self.drag.bounds[2]and self.drag.bounds[1].y and self.drag.bounds[2].y,"Element must have 2 vertical boundaries") return(self.y-self.drag.bounds[1].y)/(self.drag.bounds[2].y-self.drag.bounds[1].y) end function ticuare:setIndex(e) if self.type=="group"then local n for e=1,#self.elements do if not n or self.elements[e].z<n then n=self.elements[e].z end end for t=1,#self.elements do local e=self.elements[t].z-n+e self.elements[t]:setIndex(e) end else self.z=e if e>ticuare.hz then ticuare.hz=e end end end function ticuare:toFront() if self.z<ticuare.hz or self.type=="group"then return self:setIndex(ticuare.hz+1)end end function ticuare:getIndex()return self.z end function ticuare:remove() for e=#ticuare.elements,1,-1 do if ticuare.elements[e]==self then table.remove(ticuare.elements,e)self=nil end end end function ticuare.clear() for e=1,#ticuare.elements do ticuare.elements[e]=nil end end
ffont = false
function load()
sliders={{},{},{}}
for a=1, 3 do
for s=1, 3 do
sliders[a][s]={}
local x = (15*s)+(60*(s-1))
local y = 50+(a*20)
sliders[a][s].sliderBg=ticuare.element({
x=x,y=y,w=60,h=11,
colors={7,7,7},
border={
colors={3,3,3},
width=2
}
})
sliders[a][s].slider=ticuare.element({
x=x, y=y,w=20,h=11,
colors={1,2,3},
border={
colors={4,5,6},
width=1
},
drag = {
bounds={
{x=x},
{x=x+(60-20)}
},
enabled = true,
fixed = {x = false, y = true},
},
text={
center = true,
colors = {7,8,9},
offset={x=0,y=1},
}
})
end
end
button = ticuare.element({
x = 185, y = 40, w = 80, h = 40,
colors = {},
center = true,
border={
colors={},
width=5
},
text = {
display = "Example\n Button",
center = true,
colors = {},
font = false,
key = 5,
space = 5,
spacing = 8
},
onCleanRelease = function ()
if button.text.font then button.text.font = false else button.text.font = true end
if ffont then ffont = false else ffont = true end
end
})
end
function draw ()
ticuare.draw()
ticuare.mlPrint(
"button = ticuare.element({\n"..
" colors={"..table.concat(button.colors,",").."},\n"..
" border={\n"..
" colors={"..table.concat(button.border.colors,",").."},\n"..
" },\n"..
" text={\n"..
" colors={"..table.concat(button.text.colors,",").."},\n"..
" },\n"..
"})\n", 5,5,9,8,false,ffont,5,5
)
end
function update()
ticuare.update(mouse())
local value
for ia, va in ipairs(sliders) do
for is, vs in ipairs(va) do
value = math.floor(vs.slider:getHorizontalRange()*15)
vs.slider.text.display = tostring(value)
vs.slider.colors = {value,value,3}
vs.slider.border.colors = {15,0,value}
vs.slider.text.colors = {0,15,value}
if ia == 1 then
button.colors[is] = value
elseif ia == 2 then
button.border.colors[is] = value
elseif ia == 3 then
button.text.colors[is] = value
end
end
end
end
load()
function TIC()
cls(1)
update()
draw()
end
|
object_tangible_tcg_series7_garage_display_vehicles_landspeeder_desert_skiff = object_tangible_tcg_series7_garage_display_vehicles_shared_landspeeder_desert_skiff:new {
}
ObjectTemplates:addTemplate(object_tangible_tcg_series7_garage_display_vehicles_landspeeder_desert_skiff, "object/tangible/tcg/series7/garage_display_vehicles/landspeeder_desert_skiff.iff")
|
-------------------------------------------
------- EDITED BY GITHUB.COM/AVAN0X -------
--------------- AvaN0x#6348 ---------------
-------------------------------------------
--================================================================================================
--== VARIABLES - DO NOT EDIT ==
--================================================================================================
ESX = nil
inMenu = false
local showblips = true
local atbank = false
local bankMenu = true
local banks = {
{name="Pacific Standard", id=108, colour = 18, x=242.04, y=224.45, z=106.286},
{name="Banque", id=108, colour = 4, x=-1212.980, y=-330.841, z=37.787},
{name="Banque", id=108, colour = 4, x=-2962.582, y=482.627, z=15.703},
{name="Banque", id=108, colour = 4, x=-112.202, y=6469.295, z=31.626},
{name="Banque", id=108, colour = 4, x=314.187, y=-278.621, z=54.170},
{name="Banque", id=108, colour = 4, x=-351.534, y=-49.529, z=49.042},
{name="Banque", id=108, colour = 4, x=1175.0643310547, y=2706.6435546875, z=38.094036102295},
{name="Banque", id=108, colour = 4, x=149.4551, y=-1038.95, z=29.366}
}
local atms = {
{name="ATM", id=277, x=237.43, y=217.87, z=106.840, w = 296.0},
{name="ATM", id=277, x=-386.733, y=6045.953, z=31.501, w = 0.0},
{name="ATM", id=277, x=-386.733, y=6045.953, z=31.501, w = 0.0},
{name="ATM", id=277, x=-284.037, y=6224.385, z=31.187, w = 0.0},
{name="ATM", id=277, x=-284.037, y=6224.385, z=31.187, w = 0.0},
{name="ATM", id=277, x=-135.165, y=6365.738, z=31.101, w = 0.0},
{name="ATM", id=277, x=-110.753, y=6467.703, z=31.784, w = 0.0},
{name="ATM", id=277, x=-94.9690, y=6455.301, z=31.784, w = 0.0},
{name="ATM", id=277, x=155.4300, y=6641.991, z=31.784, w = 0.0},
{name="ATM", id=277, x=174.6720, y=6637.218, z=31.784, w = 0.0},
{name="ATM", id=277, x=1703.138, y=6426.783, z=32.730, w = 0.0},
{name="ATM", id=277, x=1735.114, y=6411.035, z=35.164, w = 0.0},
{name="ATM", id=277, x=1702.842, y=4933.593, z=42.051, w = 0.0},
{name="ATM", id=277, x=1967.333, y=3744.293, z=32.272, w = 0.0},
{name="ATM", id=277, x=1821.917, y=3683.483, z=34.244, w = 0.0},
{name="ATM", id=277, x=1174.532, y=2705.278, z=38.027, w = 0.0},
{name="ATM", id=277, x=540.0420, y=2671.007, z=42.177, w = 0.0},
{name="ATM", id=277, x=2564.399, y=2585.100, z=38.016, w = 0.0},
{name="ATM", id=277, x=2558.683, y=349.6010, z=108.050, w = 0.0},
{name="ATM", id=277, x=2558.051, y=389.4817, z=108.660, w = 0.0},
{name="ATM", id=277, x=1077.692, y=-775.796, z=58.218, w = 0.0},
{name="ATM", id=277, x=1139.018, y=-469.886, z=66.789, w = 0.0},
{name="ATM", id=277, x=1168.975, y=-457.241, z=66.641, w = 0.0},
{name="ATM", id=277, x=1153.884, y=-326.540, z=69.245, w = 0.0},
{name="ATM", id=277, x=381.2827, y=323.2518, z=103.270, w = 0.0},
{name="ATM", id=277, x=265.0043, y=212.1717, z=106.780, w = 0.0},
{name="ATM", id=277, x=285.2029, y=143.5690, z=104.970, w = 0.0},
{name="ATM", id=277, x=157.7698, y=233.5450, z=106.450, w = 0.0},
{name="ATM", id=277, x=-164.568, y=233.5066, z=94.919, w = 0.0},
{name="ATM", id=277, x=-1827.04, y=785.5159, z=138.020, w = 0.0},
{name="ATM", id=277, x=-1409.39, y=-99.2603, z=52.473, w = 0.0},
{name="ATM", id=277, x=-1205.35, y=-325.579, z=37.870, w = 0.0},
{name="ATM", id=277, x=-1215.64, y=-332.231, z=37.881, w = 0.0},
{name="ATM", id=277, x=-2072.41, y=-316.959, z=13.345, w = 0.0},
{name="ATM", id=277, x=-2975.72, y=379.7737, z=14.992, w = 0.0},
{name="ATM", id=277, x=-2962.60, y=482.1914, z=15.762, w = 0.0},
{name="ATM", id=277, x=-2955.70, y=488.7218, z=15.486, w = 0.0},
{name="ATM", id=277, x=-3044.22, y=595.2429, z=7.595, w = 0.0},
{name="ATM", id=277, x=-3144.13, y=1127.415, z=20.868, w = 0.0},
{name="ATM", id=277, x=-3241.10, y=996.6881, z=12.500, w = 0.0},
{name="ATM", id=277, x=-3241.11, y=1009.152, z=12.877, w = 0.0},
{name="ATM", id=277, x=-1305.40, y=-706.240, z=25.352, w = 0.0},
{name="ATM", id=277, x=-538.225, y=-854.423, z=29.234, w = 0.0},
{name="ATM", id=277, x=-711.156, y=-818.958, z=23.768, w = 0.0},
{name="ATM", id=277, x=-717.614, y=-915.880, z=19.268, w = 0.0},
{name="ATM", id=277, x=-526.566, y=-1222.90, z=18.434, w = 0.0},
{name="ATM", id=277, x=-256.831, y=-719.646, z=33.444, w = 0.0},
{name="ATM", id=277, x=-203.548, y=-861.588, z=30.205, w = 0.0},
{name="ATM", id=277, x=112.4102, y=-776.162, z=31.427, w = 0.0},
{name="ATM", id=277, x=112.9290, y=-818.710, z=31.386, w = 0.0},
{name="ATM", id=277, x=119.9000, y=-883.826, z=31.191, w = 0.0},
{name="ATM", id=277, x=-846.304, y=-340.402, z=38.687, w = 0.0},
{name="ATM", id=277, x=-1204.35, y=-324.391, z=37.877, w = 0.0},
{name="ATM", id=277, x=-1216.27, y=-331.461, z=37.773, w = 0.0},
{name="ATM", id=277, x=-56.1935, y=-1752.53, z=29.452, w = 0.0},
{name="ATM", id=277, x=-261.692, y=-2012.64, z=30.121, w = 0.0},
{name="ATM", id=277, x=-273.001, y=-2025.60, z=30.197, w = 0.0},
{name="ATM", id=277, x=314.187, y=-278.621, z=54.170, w = 0.0},
{name="ATM", id=277, x=-351.534, y=-49.529, z=49.042, w = 0.0},
{name="ATM", id=277, x=24.589, y=-946.056, z=29.357, w = 0.0},
{name="ATM", id=277, x=-254.112, y=-692.483, z=33.616, w = 0.0},
{name="ATM", id=277, x=-1570.197, y=-546.651, z=34.955, w = 0.0},
{name="ATM", id=277, x=-1415.909, y=-211.825, z=46.500, w = 0.0},
{name="ATM", id=277, x=-1430.112, y=-211.014, z=46.500, w = 0.0},
{name="ATM", id=277, x=33.232, y=-1347.849, z=29.497, w = 0.0},
{name="ATM", id=277, x=129.216, y=-1292.347, z=29.269, w = 0.0},
{name="ATM", id=277, x=287.645, y=-1282.646, z=29.659, w = 0.0},
{name="ATM", id=277, x=289.012, y=-1256.545, z=29.440, w = 0.0},
{name="ATM", id=277, x=295.839, y=-895.640, z=29.217, w = 0.0},
{name="ATM", id=277, x=1686.753, y=4815.809, z=42.008, w = 0.0},
{name="ATM", id=277, x=-302.408, y=-829.945, z=32.417, w = 0.0},
{name="ATM", id=277, x=5.134, y=-919.949, z=29.557, w = 0.0},
{name="ATM", id=277, x=-1132.024, y=-1704.055, z=3.44, w = 0.0},
{name="ATM", id=277, x=-572.796, y=-397.908, z=33.9, w = 0.0},
{name="ATM", id=277, x=903.69, y=-164.06, z=74.17, w = 0.0}, -- taxi
}
--================================================================================================
--== THREADING - DO NOT EDIT ==
--================================================================================================
--===============================================
--== Base ESX Threading ==
--===============================================
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
end)
--===============================================
--== Core Threading ==
--===============================================
if bankMenu then
Citizen.CreateThread(function()
while true do
Wait(0)
local ped = PlayerPedId()
local bank = nearBank()
local atm = nearATM()
if bank and not inMenu then
DisplayHelpText("Appuie sur ~INPUT_PICKUP~ pour accèder à compte ~b~")
if IsControlJustPressed(1, 38) then
OpenBank()
end
elseif atm and not inMenu then
DisplayHelpText("Appuie sur ~INPUT_PICKUP~ pour accèder à compte ~b~")
if IsControlJustPressed(1, 38) then
TaskGoStraightToCoord(ped, atm.x, atm.y, atm.z, 10.0, 10, atm.w, 0.5)
Wait(2500)
-- ClearPedTasksImmediately(ped)
TaskStartScenarioInPlace(ped, "PROP_HUMAN_ATM", 0, false)
Wait(8000)
OpenBank()
Wait(15000)
ClearPedTasksImmediately(ped)
end
end
if IsControlJustPressed(1, 322) and inMenu then
SetNuiFocus(false, false)
SendNUIMessage({type = 'close'})
-- ClearPedTasks(ped)
Wait(500)
ClearPedTasksImmediately(ped)
inMenu = false
end
end
end)
end
function OpenBank()
inMenu = true
SetNuiFocus(true, true)
SendNUIMessage({type = 'openGeneral'})
TriggerServerEvent('bank:balance')
local ped = GetPlayerPed(-1)
end
--===============================================
--== Map Blips ==
--===============================================
Citizen.CreateThread(function()
if showblips then
for k,v in ipairs(banks)do
local blip = AddBlipForCoord(v.x, v.y, v.z)
SetBlipSprite(blip, v.id)
SetBlipColour(blip, v.colour)
SetBlipScale(blip, 0.7)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(tostring(v.name))
EndTextCommandSetBlipName(blip)
end
end
end)
--===============================================
--== Deposit Event ==
--===============================================
RegisterNetEvent('currentbalance1')
AddEventHandler('currentbalance1', function(balance)
local id = PlayerId()
local playerName = GetPlayerName(id)
SendNUIMessage({
type = "balanceHUD",
balance = balance,
player = playerName
})
end)
--===============================================
--== Deposit Event ==
--===============================================
RegisterNUICallback('deposit', function(data)
TriggerServerEvent('bank:deposit1', tonumber(data.amount))
TriggerServerEvent('bank:balance')
end)
--===============================================
--== Withdraw Event ==
--===============================================
RegisterNUICallback('withdrawl', function(data)
TriggerServerEvent('bank:withdraw1', tonumber(data.amountw))
TriggerServerEvent('bank:balance')
end)
--===============================================
--== Balance Event ==
--===============================================
RegisterNUICallback('balance', function()
TriggerServerEvent('bank:balance')
end)
RegisterNetEvent('balance:back')
AddEventHandler('balance:back', function(balance)
SendNUIMessage({type = 'balanceReturn', bal = balance})
end)
--===============================================
--== Transfer Event ==
--===============================================
RegisterNUICallback('transfer', function(data)
TriggerServerEvent('bank:transfer', data.to, data.amountt)
TriggerServerEvent('bank:balance')
end)
--===============================================
--== Result Event ==
--===============================================
RegisterNetEvent('bank:result')
AddEventHandler('bank:result', function(type, message)
SendNUIMessage({type = 'result', m = message, t = type})
end)
--===============================================
--== NUIFocusoff ==
--===============================================
RegisterNUICallback('NUIFocusOff', function()
SetNuiFocus(false, false)
SendNUIMessage({type = 'closeAll'})
local ped = GetPlayerPed()
-- ClearPedTasks(ped)
Wait(500)
ClearPedTasksImmediately(ped)
inMenu = false
end)
--===============================================
--== Capture Bank Distance ==
--===============================================
function nearBank()
local player = GetPlayerPed(-1)
local playerloc = GetEntityCoords(player, 0)
for _, search in pairs(banks) do
local distance = GetDistanceBetweenCoords(search.x, search.y, search.z, playerloc['x'], playerloc['y'], playerloc['z'], true)
if distance <= 3 then
return search
end
end
return nil
end
function nearATM()
local player = GetPlayerPed(-1)
local playerloc = GetEntityCoords(player, 0)
for _, search in pairs(atms) do
local distance = GetDistanceBetweenCoords(search.x, search.y, search.z, playerloc['x'], playerloc['y'], playerloc['z'], true)
if distance <= 1.5 then
return search
end
end
return nil
end
function DisplayHelpText(str)
SetTextComponentFormat("STRING")
AddTextComponentString(str)
DisplayHelpTextFromStringLabel(0, 0, 1, -1)
end
|
local mod_path = "mods/Test"
local mod = {}
local function load_assets(toAdd, toPath)
local filesTable = love.filesystem.getDirectoryItems(toPath)
for i,v in ipairs(filesTable) do
local file = toPath.."/"..v
if love.filesystem.isFile(file) then
if string.find(file, ".lua") then
local sfile = string.gsub(file, ".lua", "")
local afile = string.gsub(string.gsub(file, toPath.."/", ""), ".lua", "")
toAdd[afile] = require(sfile)
print("Including '"..sfile..".lua'")
end
elseif love.filesystem.isDirectory(file) then
load_assets(toAdd, file)
end
end
end
local function mod_init()
mod.name = "Last Chance HD"
mod.paths = {}
mod.paths.root = mod_path
mod.script = require(mod_path.."/script")
mod.characters = {}
mod.locations = {}
mod.saves = {}
mod.paths.characters = mod_path.."/characters"
mod.paths.saves = mod_path.."/saves"
mod.paths.locations = mod_path.."/locations"
load_assets(mod.characters, mod.paths.characters)
load_assets(mod.locations, mod.paths.locations)
load_assets(mod.saves, mod.paths.saves)
mod.save_file = mod.saves["1"]
return true
end
if mod_init() then
return mod
else
return false
end
|
local default_opts = require("blaz.lsp.opts.defaults")
local opts = {}
return vim.tbl_deep_extend("force", default_opts, opts)
|
return { sharp = { 15, 14, 9, 7 }, sharpp = { 15, 14, 9, 18 } }
|
--[[
The MIT License (MIT)
Copyright (c) 2015 Matthias Richter
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 BASE = ...
local shine = {}
shine.__index = shine
-- commonly used utility function
function shine._render_to_canvas(_, canvas, func, ...)
local old_canvas = love.graphics.getCanvas()
love.graphics.setCanvas(canvas)
love.graphics.clear()
func(...)
love.graphics.setCanvas(old_canvas)
end
function shine._apply_shader_to_scene(_, shader, canvas, func, ...)
local s = love.graphics.getShader()
local co = {love.graphics.getColor()}
-- draw scene to canvas
shine._render_to_canvas(_, canvas, func, ...)
-- apply shader to canvas
love.graphics.setColor(co)
love.graphics.setShader(shader)
local b = love.graphics.getBlendMode()
love.graphics.setBlendMode('alpha', 'premultiplied')
love.graphics.draw(canvas, 0,0)
love.graphics.setBlendMode(b)
-- reset shader and canvas
love.graphics.setShader(s)
end
-- effect chaining
function shine.chain(first, second)
local effect = {}
function effect:set(k, v)
local ok = pcall(first.set, first, k, v)
ok = pcall(second.set, second, k, v) or ok
if not ok then
error("Unknown property: " .. tostring(k))
end
end
function effect:draw(func, ...)
local args = {n = select('#',...), ...}
second(function() first(func, unpack(args, 1, args.n)) end)
end
return setmetatable(effect, {__newindex = shine.__newindex, __index = shine, __call = effect.draw})
end
-- guards
function shine.draw()
error("Incomplete effect: draw(func) not implemented", 2)
end
function shine.set()
error("Incomplete effect: set(key, value) not implemented", 2)
end
function shine.__newindex(self, k, v)
if k == "parameters" then
assert(type(v) == "table")
for k,v in pairs(v) do
self:set(k,v)
end
else
self:set(k, v)
end
end
return setmetatable({}, {__index = function(self, key)
local ok, effect = pcall(require, BASE .. "." .. key)
if not ok then
error("No such effect: "..key, 2)
end
setmetatable(effect, shine)
local constructor = function(t)
local instance = {}
effect.new(instance)
setmetatable(instance, {__newindex = shine.__newindex, __index = effect, __call = effect.draw})
if t and type(t) == "table" then
instance.parameters = t
end
return instance
end
self[key] = constructor
return constructor
end})
|
#!/usr/bin/env lua
require 'ext'
local gnuplot = require 'gnuplot'
for f in os.listdir'.' do
local ident = f:match'^results%-(.*)%.txt$'
if ident then
local names = file[f]:split'\n'[1]:sub(2):split'\t'
local args, argsDiff
if os.fileexists'gnuplot-config.lua' then
args, argsDiff = table.unpack(dofile'gnuplot-config.lua')
end
gnuplot(table(args, {
terminal = 'png size 2400,1400',
output = 'results-'..ident..'.png',
style = 'data lines',
xlabel = names[1],
ylabel = names[2]:sub(1,-5),
xrange = {0,10},
key = 'left Left reverse',
{datafile=f, using='1:2', title=names[2]},
{datafile=f, using='1:3', title=names[3]},
{datafile=f, using='1:4', title=names[4]},
}))
gnuplot(table(argsDiff, {
terminal = 'png size 2400,1400',
output = 'diff'..ident..'.png',
style = 'data lines',
xlabel = names[1],
ylabel = names[2]:sub(1,-5),
xrange = {0,10},
key = 'left Left reverse',
{datafile=f, using='1:($2-$3)', title=names[2]..' - '..names[3]},
{datafile=f, using='1:($4-$3)', title=names[4]..' - '..names[3]},
}))
end
end
|
local config = {
waypointDirectory = "waypoints/",
}
local stop = false
local isAttacking = false
local isFollowing = false
local currentTargetPositionId = 1
local waypoints = {}
local autowalkTargetPosition = waypoints[currentTargetPositionId]
local itemHealingLoopId = nil
local hasLured = false
local player = nil
local healingItem
local manaItem
function init()
luniaBotWindow = g_ui.displayUI('luniabot')
player = g_game.getLocalPlayer()
waypointList = luniaBotWindow:getChildById("waypoints")
luniaBotWindow:hide()
luniaBotButton = modules.client_topmenu.addLeftGameButton('luniaBotButton', tr('Tasker'), 'icon', toggle)
atkButton = luniaBotWindow:getChildById("autoAttack")
walkButton = luniaBotWindow:getChildById("walking")
healthSpellButton = luniaBotWindow:getChildById("AutoHealSpell")
healthItemButton = luniaBotWindow:getChildById("AutoHealItem")
manaRestoreButton = luniaBotWindow:getChildById("AutoMana")
atkSpellButton = luniaBotWindow:getChildById("AtkSpell")
manaTrainButton = luniaBotWindow:getChildById("ManaTrain")
hasteButton = luniaBotWindow:getChildById("AutoHaste")
buffButton = luniaBotWindow:getChildById("AutoBuff")
lureButton = luniaBotWindow:getChildById("LureMonsters")
manaShieldButton = luniaBotWindow:getChildById("AutoManaShield")
antiIdleButton = luniaBotWindow:getChildById("AntiIdle")
buttonEvent = {
autoAttack = {f = atkLoop, e = nil },
walking = {f = walkToTarget, e = nil },
AutoHealSpell = {f = healingSpellLoop, e = nil },
AtkSpell = {f = atkSpellLoop, e = nil },
ManaTrain = {f = manaTrainLoop, e = nil },
AutoHaste = {f = hasteLoop, e = nil },
AutoManaShield = {f = shieldLoop, e = nil },
AntiIdle = {f = antiIdleLoop, e = nil },
AutoBuff = {f = buffLoop, e = nil }
}
healthItemButton.onCheckChange = autoHealPotion
manaRestoreButton.onCheckChange = autoManaPotion
luniaBotWindow:getChildById("AtkSpellText").onTextChange = saveBotText
luniaBotWindow:getChildById("HealSpellText").onTextChange = saveBotText
luniaBotWindow:getChildById("HealthSpellPercent").onTextChange = saveBotText
luniaBotWindow:getChildById("HealItem").onTextChange = saveBotText
luniaBotWindow:getChildById("HealItemPercent").onTextChange = saveBotText
luniaBotWindow:getChildById("ManaItem").onTextChange = saveBotText
luniaBotWindow:getChildById("ManaPercent").onTextChange = saveBotText
luniaBotWindow:getChildById("WptName").onTextChange = saveBotText
luniaBotWindow:getChildById("ManaSpellText").onTextChange = saveBotText
luniaBotWindow:getChildById("ManaTrainPercent").onTextChange = saveBotText
luniaBotWindow:getChildById("HasteText").onTextChange = saveBotText
luniaBotWindow:getChildById("BuffText").onTextChange = saveBotText
luniaBotWindow:getChildById("LureMinimum").onTextChange = saveBotText
luniaBotWindow:getChildById("LureMaximum").onTextChange = saveBotText
connect(g_game, { onGameStart = logIn, onGameEnd = logOut})
end
function saveBotText()
g_settings.set(player:getName() .. " " .. luniaBotWindow:getFocusedChild():getId(), luniaBotWindow:getFocusedChild():getText())
end
function logIn()
player = g_game.getLocalPlayer()
print("Logged in as player: "..player:getName())
-- Fixes default values
if(luniaBotWindow:getChildById("HealItem"):getText()) == ",266" then
luniaBotWindow:getChildById("HealItem"):setText('266')
end
if(luniaBotWindow:getChildById("ManaItem"):getText()) == ",268" then
luniaBotWindow:getChildById("ManaItem"):setText('268')
end
local checkButtons = {atkButton, healthSpellButton, walkButton, healthItemButton, manaRestoreButton, atkSpellButton, manaTrainButton, hasteButton, manaShieldButton, antiIdleButton, buffButton, lureButton}
for _,checkButton in ipairs(checkButtons) do
checkButton:setChecked(g_settings.getBoolean(player:getName() .. " " .. checkButton:getId()))
end
local textBoxes = {luniaBotWindow.ManaSpellText, luniaBotWindow.HasteText, luniaBotWindow.AtkSpellText, luniaBotWindow.HealSpellText, luniaBotWindow.HealthSpellPercent, luniaBotWindow.HealItem, luniaBotWindow.HealItemPercent, luniaBotWindow.ManaItem, luniaBotWindow.ManaPercent, luniaBotWindow.WptName, luniaBotWindow.BuffText, luniaBotWindow.LureMinimum, luniaBotWindow.LureMaximum}
for _,textBox in ipairs(textBoxes) do
local storedText = g_settings.get(player:getName() .. " " .. textBox:getId())
if string.len(storedText) >= 1 then
textBox:setText(g_settings.get(player:getName() .. " " .. textBox:getId()))
end
end
end
function logOut()
print("Logged out with player: "..player:getName())
player = nil
end
function terminate()
luniaBotWindow:destroy()
luniaBotButton:destroy()
end
function disable()
luniaBotButton:hide()
end
function hide()
luniaBotWindow:hide()
end
function show()
luniaBotWindow:show()
luniaBotWindow:raise()
luniaBotWindow:focus()
end
function toggleLoop(key)
print("toggleLoop("..key..")")
--maybe remove some looops, for example healing could be done through events
local btn = luniaBotWindow:getChildById(key)
local btn_id = btn:getId()
if (btn:isChecked()) then
g_settings.set(player:getName() .. " " .. btn:getId(), true)
if buttonEvent[btn_id] then
print("Toggle Starting: "..key)
buttonEvent[btn_id]['e'] = scheduleEvent(buttonEvent[btn_id]['f'], 100)
end
else
g_settings.set(player:getName() .. " " .. btn:getId(), false)
if buttonEvent[btn_id] then
print("Toggle Stopping: "..key)
removeEvent(buttonEvent[btn_id]['e'])
end
end
end
function autoHealPotion()
healingItem = healthItemButton:isChecked()
g_settings.set(player:getName() .. " " .. healthItemButton:getId(), healthItemButton:isChecked())
if (healingItem and itemHealingLoopId == nil) then
itemHealingLoop()
end
if (not manaItem and not healingItem) then
removeEvent(itemHealingLoopId)
itemHealingLoopId = nil
end
end
function autoManaPotion()
manaItem = manaRestoreButton:isChecked()
g_settings.set(player:getName() .. " " .. manaRestoreButton:getId(), manaRestoreButton:isChecked())
if (manaItem and itemHealingLoopId == nil) then
itemHealingLoop()
end
if (not manaItem and not healingItem) then
removeEvent(itemHealingLoopId)
itemHealingLoopId = nil
end
end
function toggle()
if luniaBotWindow:isVisible() then
hide()
else
show()
end
end
local function getDistanceBetween(p1, p2)
return math.max(math.abs(p1.x - p2.x), math.abs(p1.y - p2.y))
end
function Player.canAttack(self)
return not self:hasState(16384) and not g_game.isAttacking()
end
function Creature:canReach(creature)
--function from candybot
if not creature then
return false
end
local myPos = self:getPosition()
local otherPos = creature:getPosition()
local neighbours = {
{x = 0, y = -1, z = 0},
{x = -1, y = -1, z = 0},
{x = -1, y = 0, z = 0},
{x = -1, y = 1, z = 0},
{x = 0, y = 1, z = 0},
{x = 1, y = 1, z = 0},
{x = 1, y = 0, z = 0},
{x = 1, y = -1, z = 0}
}
for k,v in pairs(neighbours) do
local checkPos = {x = myPos.x + v.x, y = myPos.y + v.y, z = myPos.z + v.z}
if postostring(otherPos) == postostring(checkPos) then
return true
end
local steps, result = g_map.findPath(otherPos, checkPos, 40000, 0)
if result == PathFindResults.Ok then
return true
end
end
return false
end
function atkLoop()
if not player or not buttonEvent['autoAttack']['e'] then print("autoAttack loop cancelled") return end
if player:canAttack() then
local pPos = player:getPosition()
local luredMob = {}
local lureAmount = tonumber(luniaBotWindow:getChildById("LureMaximum"):getText())
local lureMinimum = tonumber(luniaBotWindow:getChildById("LureMinimum"):getText())
local luring = lureButton:isChecked()
if pPos then --solves some weird bug, in the first login, the players position is nil in the start for some reason
local creatures = g_map.getSpectators(pPos, false)
if (luring) then
for _, mob in ipairs(creatures) do
cPos = mob:getPosition()
if getDistanceBetween(pPos, cPos) <= 5 and mob:isMonster() and player:canReach(mob) then
table.insert(luredMob, mob)
end
end
end
if (luring and #luredMob >= lureAmount) then
hasLured = true
end
if (luring and #luredMob <= lureMinimum) then
hasLured = false
end
for _, creature in ipairs(creatures) do
cPos = creature:getPosition()
if getDistanceBetween(pPos, cPos) <= 5 and creature:isMonster() and player:canReach(creature) then
if (not luring or hasLured) then
g_game.attack(creature)
buttonEvent['autoAttack']['e'] = scheduleEvent(buttonEvent['autoAttack']['f'], 250)
return
end
end
end
end
end
buttonEvent['autoAttack']['e'] = scheduleEvent(buttonEvent['autoAttack']['f'], 250)
end
function fag()
local label = g_ui.createWidget('Waypoint', waypointList)
local pos = player:getPosition()
label:setText(pos.x .. "," .. pos.y .. "," .. pos.z)
table.insert(waypoints, pos)
end
function walkToTarget()
if not player or not buttonEvent['walking']['e'] then print("walking loop cancelled 1") return end
--found this function made by gesior, i edited it abit, maybe there's better ways to walk?
autowalkTargetPosition = waypoints[currentTargetPositionId]
local playerPos = player:getPosition()
if (playerPos and autowalkTargetPosition) then
if (getDistanceBetween(playerPos, autowalkTargetPosition) >= 150) then
currentTargetPositionId = currentTargetPositionId + 1
if (currentTargetPositionId > #waypoints) then
currentTargetPositionId = 1
end
buttonEvent['walking']['e'] = scheduleEvent(buttonEvent['walking']['f'], 1500)
return
end
end
if g_game.isAttacking() or isFollowing then
buttonEvent['walking']['e'] = scheduleEvent(buttonEvent['walking']['f'], 300)
return
end
if not autowalkTargetPosition then
currentTargetPositionId = currentTargetPositionId + 1
if (currentTargetPositionId > #waypoints) then
currentTargetPositionId = 1
end
buttonEvent['walking']['e'] = scheduleEvent(buttonEvent['walking']['f'], 100)
return
end
-- fast search path on minimap (known tiles)
if not player or not buttonEvent['walking']['e'] then print("walking loop cancelled 2") return end
steps, result = g_map.findPath(player:getPosition(), autowalkTargetPosition, 5000, 0)
if result == PathFindResults.Ok then
g_game.walk(steps[1], true)
elseif result == PathFindResults.Position then
currentTargetPositionId = currentTargetPositionId + 1
if (currentTargetPositionId > #waypoints) then
currentTargetPositionId = 1
end
else
-- slow search path on minimap, if not found, start 'scanning' map
if not player then return end
steps, result = g_map.findPath(player:getPosition(), autowalkTargetPosition, 25000, 1)
if result == PathFindResults.Ok then
g_game.walk(steps[1], true)
else
-- can't reach? so skip this waypoint. improve this somehow
currentTargetPositionId = currentTargetPositionId + 1
end
end
-- limit steps to 10 per second (100 ms between steps)
local nextStep = math.max(100, player:getStepTicksLeft())
buttonEvent['walking']['e'] = scheduleEvent(buttonEvent['walking']['f'], nextStep)
end
function saveWaypoints()
local saveText = '{\n'
for _,v in pairs(waypoints) do
saveText = saveText .. '{x = '.. v.x ..', y = ' .. v.y .. ', z = ' .. v.z .. '},\n'
end
saveText = saveText .. '}'
local file = io.open(config.waypointDirectory .. luniaBotWindow:getChildById("WptName"):getText() .. ".lua", "w")
file:write(saveText)
file:close()
end
function loadWaypoints()
local f = io.open(config.waypointDirectory .. luniaBotWindow:getChildById("WptName"):getText() ..'.lua', "r")
local content = f:read("*all")
f:close()
clearWaypoints()
waypoints = loadstring("return "..content)()
for _,v in ipairs(waypoints) do
local labelt = g_ui.createWidget('Waypoint', waypointList)
labelt:setText(v.x .. "," .. v.y .. "," .. v.z)
end
end
function clearWaypoints()
waypoints = {}
autowalkTargetPosition = currentTargetPositionId
autowalkTargetPosition = waypoints[currentTargetPositionId]
clearLabels()
walkButton:setChecked(false)
end
function clearLabels()
while waypointList:getChildCount() > 0 do
local child = waypointList:getLastChild()
waypointList:destroyChildren(child)
end
end
function itemHealingLoop()
if not player then return end
-- Prioritize healing item instead of mana
if healingItem then
local hpItemPercentage = tonumber(luniaBotWindow:getChildById("HealItemPercent"):getText())
local hpItemId = tonumber(luniaBotWindow:getChildById("HealItem"):getText())
if (player:getHealth() <= (player:getMaxHealth() * (hpItemPercentage/100))) then
g_game.useInventoryItemWith(hpItemId, player)
-- maybe don't try using mana after healing item?
end
end
if manaItem then
local manaItemPercentage = tonumber(luniaBotWindow.ManaPercent:getText())
local manaItemId = tonumber(luniaBotWindow.ManaItem:getText())
if (player:getMana() <= (player:getMaxMana() * (manaItemPercentage/100))) then
g_game.useInventoryItemWith(manaItemId, player)
end
end
itemHealingLoopId = scheduleEvent(itemHealingLoop, 250)
end
function healingSpellLoop()
if not player or not buttonEvent['AutoHealSpell']['e'] then print("AutoHealSpell loop cancelled") return end
local healingSpellPercentage = tonumber(luniaBotWindow:getChildById("HealthSpellPercent"):getText())
local healSpell = luniaBotWindow:getChildById("HealSpellText"):getText()
if (player:getHealth() <= (player:getMaxHealth() * (healingSpellPercentage/100))) then
g_game.talk(healSpell)
end
buttonEvent['AutoHealSpell']['e'] = scheduleEvent(buttonEvent['AutoHealSpell']['f'], 502)
end
function manaTrainLoop()
if not player or not buttonEvent['ManaTrain']['e'] then print("ManaTrain loop cancelled") return end
local manaTrainPercentage = tonumber(luniaBotWindow:getChildById("ManaTrainPercent"):getText())
local manaSpell = luniaBotWindow:getChildById("ManaSpellText"):getText()
if (player:getMana() >= (player:getMaxMana() * (manaTrainPercentage/100))) then
g_game.talk(manaSpell)
end
buttonEvent['ManaTrain']['e'] = scheduleEvent(buttonEvent['ManaTrain']['f'], 1000)
end
function hasteLoop()
if not player or not buttonEvent['AutoHaste']['e'] then print("AutoHaste loop cancelled") return end
local hasteSpell = luniaBotWindow:getChildById("HasteText"):getText()
if (player:getHealth() >= (player:getMaxHealth() * (70/100))) then -- only cast when healthy
if (not player:hasState(PlayerStates.Haste, player:getStates())) then
g_game.talk(hasteSpell)
end
end
buttonEvent['AutoHaste']['e'] = scheduleEvent(buttonEvent['AutoHaste']['f'], 1000)
end
function buffLoop()
if not player or not buttonEvent['AutoBuff']['e'] then print("AutoBuff loop cancelled") return end
local buffSpell = luniaBotWindow:getChildById("BuffText"):getText()
if (not player:hasState(PlayerStates.PartyBuff, player:getStates())) then
g_game.talk(buffSpell)
end
buttonEvent['AutoBuff']['e'] = scheduleEvent(buttonEvent['AutoBuff']['f'], 1000)
end
function shieldLoop()
if not player or not buttonEvent['AutoManaShield']['e'] then print("AutoManaShield loop cancelled") return end
if (not player:hasState(PlayerStates.ManaShield, player:getStates())) then
g_game.talk('utamo vita')
end
buttonEvent['AutoManaShield']['e'] = scheduleEvent(buttonEvent['AutoManaShield']['f'], 1000)
end
function antiIdleTurnPlayer()
if not player or not player:getPosition() then return end
g_game.turn((player:getDirection() + 2) % 4)
end
function antiIdleLoop()
if not player or not buttonEvent['AntiIdle']['e'] then print("AntiIdle loop cancelled") return end
antiIdleTurnPlayer()
scheduleEvent(antiIdleTurnPlayer, 200)
local nextLoop = math.random(8, 14) * 60 * 1000
--local nextLoop = math.random(2, 4) * 1000
buttonEvent['AntiIdle']['e'] = scheduleEvent(buttonEvent['AntiIdle']['f'], nextLoop)
end
function atkSpellLoop()
if not player or not buttonEvent['AtkSpell']['e'] then print("AtkSpell loop cancelled") return end
local atkSpell = luniaBotWindow:getChildById("AtkSpellText"):getText()
if (g_game.isAttacking()) then
g_game.talk(atkSpell)
end
buttonEvent['AtkSpell']['e'] = scheduleEvent(buttonEvent['AtkSpell']['f'], 502)
end
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
local _slots = {
{
flags_missing = 1,
goto_spot = "LeadToSpot",
groups = {
["A"] = true,
},
spots = {
"Playground",
},
},
{
flags_missing = 1,
goto_spot = "LeadToSpot",
groups = {
["A"] = true,
},
spots = {
"Playtablet",
},
},
}
PrgAmbientLife["VisitNursery"] = function(unit, bld)
local spot, obj, desc, slot, slotname, pos, __placed
unit:PushDestructor(function(unit)
if IsValid(__placed) then
DoneObject(__placed)
end
end)
spot, obj, desc, slot, slotname = PrgGetObjRandomSpotFromGroup(bld, nil, "A", _slots, unit)
pos = spot and obj:GetSpotLocPos(spot)
if spot then
if slotname == "Playtablet" then
__placed = PlaceObject("Tablet", nil, const.cfComponentEx + const.cfComponentAttach)
NetTempObject(__placed)
unit:Attach(__placed, unit:GetRandomSpot("Tablet"))
end
PrgVisitSlot(unit, bld, obj, spot, desc, slot, slotname)
if unit.visit_restart then unit:PopAndCallDestructor() return end
else
PrgVisitHolder(unit, bld)
if unit.visit_restart then unit:PopAndCallDestructor() return end
end
PrgLeadToExit(unit, bld)
if unit.visit_restart then unit:PopAndCallDestructor() return end
unit:PopAndCallDestructor()
end
|
local log = require("log")
local remote = require('net.box')
local compat = require('compat')
local new_parts_format_supported = compat.check_version{1, 7, 6}
local is_nullable_supported = compat.check_version{1, 7, 6}
local function create_space(space)
log.info{message2="Creating space.", name=space.name}
local format = {}
for name, field in pairs(space.fields) do
format[field.index] = { name=name, type=field.type }
if is_nullable_supported then
format[field.index].is_nullable = false
if field.is_nullable then
format[field.index].is_nullable = true
end
end
end
local created_space = box.schema.space.create(space.name, { format = format, if_not_exists=true, field_count=#format })
log.info{message2="Created space.", name=space.name}
return created_space
end
local function create_index(space, name, unique, type, sequence, ...)
local parts = {}
for i, v in ipairs({...}) do
if new_parts_format_supported then
table.insert(parts, v.name)
else
table.insert(parts, v.index)
table.insert(parts, v.type)
end
end
local options = {
unique = unique,
type = type,
parts = parts,
if_not_exists = true,
sequence = sequence
}
log.info{message2="Creating index", space=space.name, name=name, options=options}
local index = space:create_index(name, options)
log.info{message2="Created index", space=space.name, name=name}
return index
end
local spaces = {
primary_only_index = {
name = "primary_only_index",
fields = {
id = { index = 1, name="id", type = "unsigned" },
name = { index = 2, name="name", type = "string" },
price = { index = 3, name="price", type = "scalar", is_nullable=true }
}
},
performance = {
name = "performance",
fields = {
id = { index = 1, name="id", type = "unsigned" },
name = { index = 2, name="name", type = "string" }
}
},
treeIndexMethods = {
name = "space_TreeIndexMethods",
fields = {
id = { index = 1, name="id", type = "unsigned" },
name = { index = 2, name="name", type = "string" }
}
}
}
local function create_spaces_and_indecies()
local space = create_space(spaces.primary_only_index)
create_index(space, "primary", true, "HASH", nil, spaces.primary_only_index.fields.id)
space = create_space(spaces.performance)
create_index(space, "primary", true, "HASH", nil, spaces.performance.fields.id)
space = box.schema.space.create('with_scalar_index', { if_not_exists = true })
space:create_index('primary', {type='tree', parts={1, 'scalar'}, if_not_exists = true})
end
local function init()
create_spaces_and_indecies()
box.schema.user.create('notSetPassword', { if_not_exists = true })
box.schema.user.create('emptyPassword', { password = '', if_not_exists = true })
box.schema.user.create('operator', {password = 'operator', if_not_exists = true })
box.schema.user.grant('operator','read,write,execute','universe', { if_not_exists = true })
box.schema.user.grant('guest','read,write,execute','universe', { if_not_exists = true })
box.schema.user.grant('emptyPassword','read,write,execute','universe', { if_not_exists = true })
box.schema.user.passwd('admin', 'adminPassword')
end
local function space_TreeIndexMethods()
local sequence = box.schema.sequence.create('space_TreeIndexMethods_id')
local space = create_space(spaces.treeIndexMethods)
create_index(space, "treeIndex", true, "TREE", sequence.name, spaces.treeIndexMethods.fields.id)
space:insert{nil, 'asdf'}
space:insert{nil, 'zcxv'}
space:insert{nil, 'qwer'}
end
box.once('init', init)
box.once('space_TreeIndexMethods', space_TreeIndexMethods)
local log = require('log')
function log_connect ()
local m = 'Connection. user=' .. box.session.user() .. ' id=' .. box.session.id()
log.info(m)
end
function log_disconnect ()
local m = 'Disconnection. user=' .. box.session.user() .. ' id=' .. box.session.id()
log.info(m)
end
function log_auth ()
local m = 'Authentication attempt'
log.info(m)
end
function log_auth_ok (user_name)
local m = 'Authenticated user ' .. user_name
log.info(m)
end
box.session.on_connect(log_connect)
box.session.on_disconnect(log_disconnect)
box.session.on_auth(log_auth)
box.session.on_auth(log_auth_ok)
function return_null()
log.info('return_null called')
return require('msgpack').NULL
end
function return_tuple_with_null()
log.info('return_tuple_with_null called')
return { require('msgpack').NULL }
end
function return_tuple()
log.info('return_tuple called')
return { 1, 2 }
end
function return_array()
log.info('return_array called')
return {{ "abc", "def" }}
end
function return_scalar()
log.info('return_scalar called')
return 1
end
function return_nothing()
log.info('return_nothing called')
end
function replace(t)
return box.space.with_scalar_index:replace(t)
end
local truncate_space = function(name)
local space = box.space[name]
if space then
log.info("Truncating space %s...", name)
space:truncate()
log.info("Space %s trancated.", name)
else
log.warning("There is no space %s", name)
end
end
function create_sql_test()
box.sql.execute('create table sql_test(id int primary key, name text)')
box.sql.execute("insert into sql_test values (1, 'asdf'), (2, 'zxcv'), (3, 'qwer')")
end
function drop_sql_test()
box.sql.execute('drop table sql_test')
end
function clear_data(spaceNames)
log.info('clearing data...')
for _, spaceName in ipairs(spaceNames) do
truncate_space(spaceName)
end
end
local test_int = 0
function test_for_benchmarking()
test_int = test_int + 1
return test_int
end
|
local uv = require 'couv'
local TEST_PORT = 9123
coroutine.wrap(function()
local handle = uv.Tcp.new()
handle:connect(uv.SockAddrV6.new('::1', TEST_PORT))
handle:startRead()
handle:write({"PING"})
print('tcp_client send message {"PING"}')
local nread, buf = handle:read()
if nread and nread > 0 then
print("tcp_client read msg=", buf:toString(1, nread))
end
handle:write({"hello, ", "tcp"})
print('tcp_client send message {"hello, ", "tcp"}')
nread, buf = handle:read()
if nread and nread > 0 then
print("tcp_client read msg=", buf:toString(1, nread))
end
handle:write({"QUIT"})
handle:stopRead()
handle:close()
end)()
uv.run()
|
return {'maori','maoisme','maoist','maoistisch','mao','maoris','maoisten','maoistische'}
|
env = require('test_run')
test_run = env.new()
fiber = require'fiber'
ch = fiber.channel(3)
_ = box.schema.space.create('test'):create_index('pk')
test_run:cmd("setopt delimiter ';'")
function add_index()
box.space.test:create_index('sec', {parts = {2, 'num'}})
ch:put(true)
end;
function insert_tuple(tuple)
ch:put({pcall(box.space.test.replace, box.space.test, tuple)})
end;
test_run:cmd("setopt delimiter ''");
_ = {fiber.create(insert_tuple, {1, 2, 'a'}), fiber.create(add_index), fiber.create(insert_tuple, {2, '3', 'b'})}
{ch:get(), ch:get(), ch:get()}
box.space.test:select()
test_run:cmd('restart server default')
box.space.test:select()
box.space.test:drop()
|
object_tangible_loot_creature_loot_collections_statuette_piece_008 = object_tangible_loot_creature_loot_collections_shared_statuette_piece_008:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_statuette_piece_008, "object/tangible/loot/creature/loot/collections/statuette_piece_008.iff")
|
local module = {
authenticationRequired = true;
};
function module.run(authentication,groupId,timePeriod)
local endpoint = "https://economy.roblox.com/v1/groups/"..groupId.."/revenue/summary/"..timePeriod;
local response,body = api.request("GET",endpoint,{},{},authentication,false,true);
if(response.code == 200) then
return true,json.decode(body);
else
return false,response;
end
end
return module;
|
local _, private = ...
-- RealUI --
local RealUI = private.RealUI
local db
local MODNAME = "Objectives Adv."
local ObjectivesAdv = RealUI:NewModule(MODNAME, "AceEvent-3.0")
local CombatFader = RealUI:GetModule("CombatFader")
---------------------
-- Collapse / Hide --
---------------------
local function ResetState()
if ObjectivesAdv.hidden and _G.ObjectiveTrackerFrame.realUIHidden then
ObjectivesAdv.hidden = false
_G.ObjectiveTrackerFrame.realUIHidden = false
_G.ObjectiveTrackerFrame:Show()
-- Refresh fade, since fade won't update while hidden
if RealUI:GetModuleEnabled("CombatFader") then
CombatFader:UpdateStatus(true)
end
end
if ObjectivesAdv.collapsed and _G.ObjectiveTrackerFrame.userCollapsed then
ObjectivesAdv.collapsed = false
_G.ObjectiveTracker_Expand()
end
end
function ObjectivesAdv:UpdateState()
ResetState()
local _, instanceType = _G.GetInstanceInfo()
if not db.hidden.enabled or instanceType == "none" then return end
if _G.C_Garrison.IsOnGarrisonMap() then return end
local hide = db.hidden.hide[instanceType] or false
local collapse = db.hidden.collapse[instanceType] or false
if hide then
self.hidden = true
_G.ObjectiveTrackerFrame.realUIHidden = true
_G.ObjectiveTrackerFrame:Hide()
elseif collapse then
self.collapsed = true
_G.ObjectiveTrackerFrame.userCollapsed = true
_G.ObjectiveTracker_Collapse()
end
end
------------------
---- Position ----
------------------
-- Position
local movingTracker = false
local function UpdatePosition()
if movingTracker then return end
movingTracker = true
_G.ObjectiveTrackerFrame:ClearAllPoints()
_G.ObjectiveTrackerFrame:SetPoint(db.position.anchorfrom, "UIParent", db.position.anchorto, db.position.x, db.position.y)
_G.ObjectiveTrackerFrame:SetHeight(_G.UIParent:GetHeight() - db.position.negheightofs)
movingTracker = false
end
-----------------------
function ObjectivesAdv:UI_SCALE_CHANGED()
UpdatePosition()
end
function ObjectivesAdv:PLAYER_ENTERING_WORLD()
if not RealUI:GetModuleEnabled(MODNAME) then return end
self:UpdateState()
end
function ObjectivesAdv:ADDON_LOADED()
if _G.ObjectiveTrackerFrame then
self:RegisterEvent("PLAYER_ENTERING_WORLD")
self:RegisterEvent("UI_SCALE_CHANGED")
self:UnregisterEvent("ADDON_LOADED")
_G.hooksecurefunc(_G.ObjectiveTrackerFrame, "SetPoint", UpdatePosition)
CombatFader:RegisterFrameForFade(MODNAME, _G.ObjectiveTrackerFrame)
self:RefreshMod()
end
end
function ObjectivesAdv:RefreshMod()
if not RealUI:GetModuleEnabled(MODNAME) then return end
db = self.db.profile
UpdatePosition()
end
function ObjectivesAdv:OnInitialize()
self.db = RealUI.db:RegisterNamespace(MODNAME)
self.db:RegisterDefaults({
profile = {
position = {
enabled = true,
anchorto = "TOPRIGHT",
anchorfrom = "TOPRIGHT",
x = -32,
y = -200,
negheightofs = 300,
},
hidden = {
enabled = true,
collapse = {
pvp = true,
arena = false,
scenario = false,
party = true,
raid = false,
},
hide = {
pvp = false,
arena = true,
scenario = false,
party = false,
raid = true,
},
combatfade = {
enabled = true,
opacity = {
incombat = 0.25,
hurt = .75,
target = .75,
harmtarget = 0.85,
outofcombat = 1,
},
},
},
},
})
db = self.db.profile
self:SetEnabledState(RealUI:GetModuleEnabled(MODNAME))
end
function ObjectivesAdv:OnEnable()
CombatFader:RegisterModForFade(MODNAME, "profile", "hidden", "combatfade")
if not _G.ObjectiveTrackerFrame then
self:RegisterEvent("ADDON_LOADED")
else
self:ADDON_LOADED()
end
end
function ObjectivesAdv:OnDisable()
self:UnregisterEvent("PLAYER_ENTERING_WORLD")
self:UnregisterEvent("UI_SCALE_CHANGED")
end
|
--------------------------------------------------------------------------------
--- LuaSTG Sub 对象池与游戏对象
--- 璀境石
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- 游戏对象的回调函数集合
---@class lstg.Class
local game_object_class = {
--数组部分
function(self)
end, --init
function(self, ...)
end, --del
function(self)
end, --frame
lstg.DefaultRenderFunc, --render
function(self, other)
end, --colli
function(self, ...)
end; --kill
--散列部分
---标识一个table是否为合法的lstg.Class
is_class = true,
---[不稳定的特性,可能会在日后更改] 标识这个lstg.Class是否可以创建一个lstg.RenderObject对象
--[".render"] = false,
}
---@param self lstg.GameObject
---@vararg any @随着lstg.New传入的参数
function game_object_class.init(self, ...)
end
---@param self lstg.GameObject
function game_object_class.frame(self)
end
---@param self lstg.GameObject
function game_object_class.render(self)
end
---@param self lstg.GameObject
---@vararg any @随着lstg.Del传入的参数
function game_object_class.del(self, ...)
end
---@param self lstg.GameObject
---@vararg any @随着lstg.Kill传入的参数
function game_object_class.kill(self, ...)
end
---@param self lstg.GameObject
---@param other lstg.GameObject
function game_object_class.colli(self, other)
end
--------------------------------------------------------------------------------
--- 实例化的游戏对象
---@alias lstg.GameObject.Status '"normal"' | '"del"' | '"kill"'
---luastg中实例化的游戏对象
---@class lstg.GameObject
local game_object = {
--数组部分
---class
---@type lstg.Class
game_object_class,
---id
0;
--散列部分
--========object========
---状态,可以为"normal"、"kill"、"del",分别代表正常状态、被标记为kill、被标记为del
---@type lstg.GameObject.Status
status = "normal",
---class,实际上映射到数组部分索引为1的位置
---@type lstg.Class
class = game_object_class,
--========user========
---计数器,会每帧自增
timer = 0,
--========position========
---x坐标
x = 0,
---y坐标
y = 0,
---x坐标相对上一帧的变化量
dx = 0,
---y坐标相对上一帧的变化量
dy = 0,
--========movement========
---x轴加速度分量
ax = 0,
---y轴加速度分量
ay = 0,
---重力加速度,方向永远朝向y轴负方向
ag = 0,
---x轴速度分量
vx = 0,
---y轴速度分量
vy = 0,
---最大速度
maxv = 1e100,
---x轴最大速度分量
maxvx = 1e100,
---y轴最大速度分量
maxvy = 1e100,
--========render========
---动画图片精灵计数器,只读
ani = 0,
---渲染图层(和游戏对象的渲染顺序有关)
layer = 0,
---不参与渲染
hide = false,
---图片精灵朝向
rot = 0,
---朝向自增量,和navi属性冲突
omiga = 0,
---自动根据坐标变换计算朝向,和omiga属性冲突
navi = false,
---图片精灵横向缩放
hscale = 1,
---图片精灵纵向缩放
vscale = 1,
---可应用图片精灵资源、动画资源、HGE粒子资源,赋值为nil时将会释放绑定在对象上的资源
img = "unkown",
--========collision========
---碰撞组id,取值范围 0 到 15
group = 0,
---是否出界自动删除,参考lstg.SetBound
bound = true,
---是否参与碰撞
colli = true,
---如果rect属性为true,则为矩形半宽,否则为椭圆半长轴,如果a严格等于b,则为圆的半径
a = 0,
---如果rect属性为true,则为矩形半高,否则为椭圆半短轴,如果a严格等于b,则为圆的半径
b = 0,
---碰撞体类型,false时为圆或椭圆,true时为有向矩形
rect = false,
--[[
--========ex+========
---自动根据当前坐标和上一帧坐标计算vx,vy
rmove = false,
---计算出的朝向
_angle = 0,
---计算出的速度
_speed = 0,
--]]
---剩余暂停时间,影响frame回调的执行、速度与坐标的计算、timer和ani等的更新
pause = 0,
---不受暂停影响
nopause = false,
---世界掩码,与渲染、碰撞检测有关
world = 1,
}
--[[
---@class lstg.RenderObject : lstg.GameObject
local render_object = {
--========.render========
---渲染时使用的混合模式
_blend = "",
---顶点色
---@type lstg.Color
_color = {},
---顶点色alpha分量
_a = 255,
---顶点色红色分量
_r = 255,
---顶点色绿色分量
_g = 255,
---顶点色蓝色分量
_b = 255,
}
--]]
---@class object : lstg.GameObject
local _ = game_object
--------------------------------------------------------------------------------
--- 游戏对象池
---获取申请的对象数
---@return number
function lstg.GetnObj()
end
---回收所有对象,并释放绑定的资源
function lstg.ResetPool()
end
---【禁止在协同程序中调用此方法】
---更新所有游戏对象并触发游戏对象的frame回调函数
function lstg.ObjFrame()
end
---【禁止在协同程序中调用此方法】
---绘制所有游戏对象并触发游戏对象的render回调函数
function lstg.ObjRender()
end
---【禁止在协同程序中调用此方法】
---对所有游戏对象进行出界判断,如果离开场景边界,将会触发对象的del回调函数
function lstg.BoundCheck()
end
---更改场景边界,默认为-100, 100, -100, 100
---@param left number
---@param right number
---@param bottom number
---@param top number
function lstg.SetBound(left, right, bottom, top)
end
---【禁止在协同程序中调用此方法】
---对两个碰撞组的对象进行碰撞检测,如果发生碰撞则触发groupidA内的对象的colli回调函数,并传入groupidB内的对象作为参数
---@param groupidA number @只能为0到15范围内的整数
---@param groupidB number @只能为0到15范围内的整数
function lstg.CollisionCheck(groupidA, groupidB)
end
---【禁止在协同程序中调用此方法】
---保存游戏对象的x, y坐标并计算dx, dy
function lstg.UpdateXY()
end
---【禁止在协同程序中调用此方法】
---增加游戏对象的timer, ani计数器,如果对象被标记为kill或者del,则回收该对象
function lstg.AfterFrame()
end
--------------------------------------------------------------------------------
--- 游戏对象
--- 申请游戏对象,并将游戏对象和指定的class绑定,剩余的参数将会传递给init回调函数并执行
---@param class lstg.Class
---@vararg any
---@return lstg.GameObject
function lstg.New(class, ...)
---@type lstg.GameObject
local ret = {}
return ret
end
--- 触发指定游戏对象的del回调函数,并将该对象标记为del状态,剩余参数将传递给del回调函数
---@param unit lstg.GameObject
---@vararg any
function lstg.Del(unit, ...)
end
--- 触发指定游戏对象的kill回调函数,并将该对象标记为kill状态,剩余参数将传递给kill回调函数
---@param unit lstg.GameObject
---@vararg any
function lstg.Kill(unit, ...)
end
--- 检查指定游戏对象的引用是否有效,如果返回假,则该对象已经被对象池回收或不是 有效的lstg.GameObject对象;
--- unit参数可以是任何值,因此也可以用来判断传入的参数 是否是游戏对象
---@param unit any
---@return boolean
function lstg.IsValid(unit)
return false
end
--------------------------------------------------------------------------------
--- 碰撞相关
--- 检查指定对象是否在指定的矩形区域内
---@param unit lstg.GameObject
---@param left number
---@param right number
---@param bottom number
---@param top number
---@return boolean
function lstg.BoxCheck(unit, left, right, bottom, top)
return true
end
--- 检查两个对象是否发生碰撞
---@param unitA lstg.GameObject
---@param unitB lstg.GameObject
---@param ignoreworldmask boolean @如果该参数为true,则忽略world掩码
function lstg.ColliCheck(unitA, unitB, ignoreworldmask)
return false
end
--- 碰撞组迭代器,如果填写的碰撞组不是有效的碰撞组,则对所有游戏对象进行迭代
---@param groupid number @[0~15]碰撞组
---@return fun(groupid:number):number, lstg.GameObject @第一个返回值为下一个对象的id,第二个返回值为lstg.GameObject
function lstg.ObjList(groupid)
end
--------------------------------------------------------------------------------
--- 属性访问(用于游戏对象的 lua metatable)
--- 更改游戏对象上某些属性的值
---@param t lstg.GameObject
---@param k number|string
---@param v any
function lstg.SetAttr(t, k, v)
end
--- 获取游戏对象上某些属性的值
---@param t lstg.GameObject
---@param k number|string
function lstg.GetAttr(t, k)
end
--------------------------------------------------------------------------------
--- 帮助函数
---设置游戏对象的速度
---@param unit lstg.GameObject
---@param v number
---@param a number
---@param updaterot boolean @如果该参数为true,则同时设置对象的rot
function lstg.SetV(unit, v, a, updaterot)
end
---@param unit lstg.GameObject
---@return number, number @速度大小,速度朝向
function lstg.GetV(unit)
end
--- 计算向量的朝向,可以以以下的组合方式填写参数:
--- ```txt
--- lstg.GameObject, lstg.GameObject
--- lstg.GameObject, x, y
--- x, y, lstg.GameObject
--- x1, y1, x2, y2
--- ```
---@param x1 lstg.GameObject|number
---@param y1 lstg.GameObject|number
---@param x2 lstg.GameObject|number|nil
---@param y2 number|nil
---@return number
function lstg.Angle(x1, y1, x2, y2)
return 0
end
--- 计算向量的模,可以以以下的组合方式填写参数:
--- ```txt
--- lstg.GameObject, lstg.GameObject
--- lstg.GameObject, x, y
--- x, y, lstg.GameObject
--- x1, y1, x2, y2
--- ```
---@param x1 lstg.GameObject|number
---@param y1 lstg.GameObject|number
---@param x2 lstg.GameObject|number|nil
---@param y2 number|nil
---@return number
function lstg.Dist(x1, y1, x2, y2)
return 0
end
--------------------------------------------------------------------------------
--- 渲染
--- 设置绑定在游戏对象上的资源的混合模式和顶点颜色
---@param unit lstg.GameObject
---@param blend string
---@param a number @[0~255]
---@param r number @[0~255]
---@param g number @[0~255]
---@param b number @[0~255]
function lstg.SetImgState(unit, blend, a, r, g, b)
end
--- 执行游戏对象默认渲染方法
---@param unit lstg.GameObject
function lstg.DefaultRenderFunc(unit)
end
--------------------------------------------------------------------------------
--- 游戏对象上的粒子对象
--- 设置绑定在游戏对象上的粒子特效的混合模式和顶点颜色
---@param unit lstg.GameObject
---@param blend string
---@param a number @[0~255]
---@param r number @[0~255]
---@param g number @[0~255]
---@param b number @[0~255]
function lstg.SetParState(unit, blend, a, r, g, b)
end
--- 停止游戏对象上的粒子发射器
---@param unit lstg.GameObject
function lstg.ParticleStop(unit)
end
--- 启动游戏对象上的粒子发射器
---@param unit lstg.GameObject
function lstg.ParticleFire(unit)
end
--- 获取游戏对象上的粒子发射器的粒子数量
---@param unit lstg.GameObject
---@return number
function lstg.ParticleGetn(unit)
end
--- 设置粒子发射器的粒子发射密度
---@param unit lstg.GameObject
---@param emission number @每秒发射的粒子数量
function lstg.ParticleSetEmission(unit, emission)
end
--- 获取粒子发射器的粒子发射密度
---@param unit lstg.GameObject
---@return number @每秒发射的粒子数量
function lstg.ParticleGetEmission(unit)
end
--------------------------------------------------------------------------------
--- 游戏对象池更新暂停(高级功能)
--- 设置游戏对象池下一帧开始暂停更新的时间(帧)
---@param t number
function lstg.SetSuperPause(t)
end
--- 更改游戏对象池下一帧开始暂停更新的时间(帧),等效于GetSuperPause并加上t,然后SetSuperPause
---@param t number
function lstg.AddSuperPause(t)
end
--- 获取游戏对象池暂停更新的时间(帧),获取的是下一帧的
---@return number
function lstg.GetSuperPause()
end
--- 获取当前帧游戏对象池暂停更新的时间(帧)
function lstg.GetCurrentSuperPause()
end
--------------------------------------------------------------------------------
--- 游戏对象world掩码(高级功能)
--- 设置当前激活的world掩码
---@param mask number
function lstg.SetWorldFlag(mask)
end
--- 获取当前激活的 world 掩码
---@return number
function lstg.GetWorldFlag()
end
--- 判断两个对象是否在同一个 world 内,当两个游戏对象的 world 掩码相同或者按位与不为 0 时返回 true
---@param unitA lstg.GameObject
---@param unitB lstg.GameObject
---@return boolean
function lstg.IsSameWorld(unitA, unitB)
end
--- 设置多 world 的掩码,最多可支持 4 个不同的掩码,将会在进行碰撞检测的时候用到
---@param maskA number
---@param maskB number
---@param maskC number
---@param maskD number
function lstg.ActiveWorlds(maskA, maskB, maskC, maskD)
end
--- 检查两个对象是否存在于相同的 world 内,参考ActiveWorlds
---@param unitA lstg.GameObject
---@param unitB lstg.GameObject
---@return boolean
function lstg.CheckWorlds(unitA, unitB)
end
|
local snownet = require "snownet"
local harbor = require "snownet.harbor"
require "snownet.manager" -- import snownet.launch, ...
local memory = require "snownet.memory"
snownet.start(function()
local sharestring = tonumber(snownet.getenv "sharestring" or 4096)
memory.ssexpand(sharestring)
local standalone = snownet.getenv "standalone"
local launcher = assert(snownet.launch("snlua","launcher"))
snownet.name(".launcher", launcher)
local harbor_id = tonumber(snownet.getenv "harbor" or 0)
if harbor_id == 0 then
assert(standalone == nil)
standalone = true
snownet.setenv("standalone", "true")
local ok, slave = pcall(snownet.newservice, "cdummy")
if not ok then
snownet.abort()
end
snownet.name(".cslave", slave)
else
if standalone then
if not pcall(snownet.newservice,"cmaster") then
snownet.abort()
end
end
local ok, slave = pcall(snownet.newservice, "cslave")
if not ok then
snownet.abort()
end
snownet.name(".cslave", slave)
end
if standalone then
local datacenter = snownet.newservice "datacenterd"
snownet.name("DATACENTER", datacenter)
end
snownet.newservice "service_mgr"
pcall(snownet.newservice,snownet.getenv "start" or "main")
snownet.exit()
end)
|
require "coxpcall"
local _lib
if package.loaded.core then
_lib = true
else
_lib = false
require "core"
end
_exports = {}
local _main = function()
local object = object
local array = array
local number = number
local string = base_string
local exception = exception
local hash = hash
local regex = regex
local _self = object
local _type = type
local _error = error
local _tostring = tostring
local brat_function = brat_function
local _lifted_call = _lifted_call
local _rawget = rawget
local _table = table
local _lifted = {}
setfenv(1, {})
_lifted[2] = function(_argtable, _self)
local _temp25 = _argtable['_temp25']
local _temp23 = _argtable['_temp23']
local _temp40
local _temp39
local _temp38
if _type(_temp25) == "function" or (_type(_temp25) == "table" and _rawget(_temp25, "__call_thing")) then
_temp38 = _temp25(_self)
elseif _temp25 then
_temp38 = _temp25
else
_error(exception:name_error("my"))
end
if _type(_temp38) == 'number' then
_temp38 = number:new(_temp38)
elseif _type(_temp38) == "function" or (_type(_temp38) == "table" and _rawget(_temp38, "__call_thing")) then
_temp38 = brat_function:new(_temp38)
end
local _m = _temp38.nodes
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp39 = _m(_temp38)
elseif _m ~= nil then
_temp39 = _m
elseif _temp38.no_undermethod then
_temp39 = _temp38:no_undermethod(string:new('nodes'))
else
_error(exception:method_error(_temp38, 'nodes'))
end
local _temp42
local _temp41
if _type(_temp23) == "function" or (_type(_temp23) == "table" and _rawget(_temp23, "__call_thing")) then
_temp41 = _temp23(_self)
elseif _temp23 then
_temp41 = _temp23
else
_error(exception:name_error("rhs"))
end
if _type(_temp41) == 'number' then
_temp41 = number:new(_temp41)
elseif _type(_temp41) == "function" or (_type(_temp41) == "table" and _rawget(_temp41, "__call_thing")) then
_temp41 = brat_function:new(_temp41)
end
local _m = _temp41.nodes
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp42 = _m(_temp41)
elseif _m ~= nil then
_temp42 = _m
elseif _temp41.no_undermethod then
_temp42 = _temp41:no_undermethod(string:new('nodes'))
else
_error(exception:method_error(_temp41, 'nodes'))
end
if _type(_temp39) == 'number' then
_temp39 = number:new(_temp39)
elseif _type(_temp39) == "function" or (_type(_temp39) == "table" and _rawget(_temp39, "__call_thing")) then
_temp39 = brat_function:new(_temp39)
end
local _m = _temp39._equal_equal
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp40 = _m(_temp39, _temp42)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp39.no_undermethod then
_temp40 = _temp39:no_undermethod(string:new('=='), _temp42)
else
_error(exception:method_error(_temp39, '_equal_equal'))
end
return _temp40
end
_lifted[1] = function(_argtable, _self)
local _temp23 = _argtable['_temp23']
local _temp25 = _argtable['_temp25']
local _temp35
local _temp34
local _temp33
if _type(_temp25) == "function" or (_type(_temp25) == "table" and _rawget(_temp25, "__call_thing")) then
_temp33 = _temp25(_self)
elseif _temp25 then
_temp33 = _temp25
else
_error(exception:name_error("my"))
end
if _type(_temp33) == 'number' then
_temp33 = number:new(_temp33)
elseif _type(_temp33) == "function" or (_type(_temp33) == "table" and _rawget(_temp33, "__call_thing")) then
_temp33 = brat_function:new(_temp33)
end
local _m = _temp33.name
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp34 = _m(_temp33)
elseif _m ~= nil then
_temp34 = _m
elseif _temp33.no_undermethod then
_temp34 = _temp33:no_undermethod(string:new('name'))
else
_error(exception:method_error(_temp33, 'name'))
end
local _temp37
local _temp36
if _type(_temp23) == "function" or (_type(_temp23) == "table" and _rawget(_temp23, "__call_thing")) then
_temp36 = _temp23(_self)
elseif _temp23 then
_temp36 = _temp23
else
_error(exception:name_error("rhs"))
end
if _type(_temp36) == 'number' then
_temp36 = number:new(_temp36)
elseif _type(_temp36) == "function" or (_type(_temp36) == "table" and _rawget(_temp36, "__call_thing")) then
_temp36 = brat_function:new(_temp36)
end
local _m = _temp36.name
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp37 = _m(_temp36)
elseif _m ~= nil then
_temp37 = _m
elseif _temp36.no_undermethod then
_temp37 = _temp36:no_undermethod(string:new('name'))
else
_error(exception:method_error(_temp36, 'name'))
end
if _type(_temp34) == 'number' then
_temp34 = number:new(_temp34)
elseif _type(_temp34) == "function" or (_type(_temp34) == "table" and _rawget(_temp34, "__call_thing")) then
_temp34 = brat_function:new(_temp34)
end
local _m = _temp34._equal_equal
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp35 = _m(_temp34, _temp37)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp34.no_undermethod then
_temp35 = _temp34:no_undermethod(string:new('=='), _temp37)
else
_error(exception:method_error(_temp34, '_equal_equal'))
end
local _temp43 = _lifted_call(_lifted[2], {})
_temp43.arg_table['_temp23'] = _temp23
_temp43.arg_table['_temp25'] = _temp25
if _type(_temp35) == 'number' then
_temp35 = number:new(_temp35)
elseif _type(_temp35) == "function" or (_type(_temp35) == "table" and _rawget(_temp35, "__call_thing")) then
_temp35 = brat_function:new(_temp35)
end
local _m = _temp35._and_and
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp37 = _m(_temp35, _temp43)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp35.no_undermethod then
_temp37 = _temp35:no_undermethod(string:new('&&'), _temp43)
else
_error(exception:method_error(_temp35, '_and_and'))
end
return _temp37
end
_lifted[3] = function(_argtable, _self)
local _temp74 = _argtable['_temp74']
local _temp82
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp82 = _m(_self)
elseif _m then
_temp82 = _m
elseif _self.no_undermethod then
_temp82 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
local _temp84
local _temp83
if _type(_temp74) == "function" or (_type(_temp74) == "table" and _rawget(_temp74, "__call_thing")) then
_temp83 = _temp74(_self)
elseif _temp74 then
_temp83 = _temp74
else
_error(exception:name_error("nodes"))
end
if _type(_temp83) == 'number' then
_temp83 = number:new(_temp83)
elseif _type(_temp83) == "function" or (_type(_temp83) == "table" and _rawget(_temp83, "__call_thing")) then
_temp83 = brat_function:new(_temp83)
end
local _m = _temp83.last
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp84 = _m(_temp83)
elseif _m ~= nil then
_temp84 = _m
elseif _temp83.no_undermethod then
_temp84 = _temp83:no_undermethod(string:new('last'))
else
_error(exception:method_error(_temp83, 'last'))
end
if _type(_temp82) == 'table' then
_temp82['value'] = _temp84
else
_error('Cannot set method on ' .. _temp82)
end
return _temp84
end
_lifted[5] = function(_argtable, _self)
local _temp93 = _argtable['_temp93']
local _temp99
local _temp98
local _m
if nodes then
_m = nodes
else
_m = _self["nodes"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp98 = _m(_self)
elseif _m then
_temp98 = _m
elseif _self.no_undermethod then
_temp98 = _self:no_undermethod(string:new('nodes'))
else
_error(exception:name_error("nodes"))
end
local _temp100
if _type(_temp93) == "function" or (_type(_temp93) == "table" and _rawget(_temp93, "__call_thing")) then
_temp100 = _temp93(_self)
elseif _temp93 then
_temp100 = _temp93
else
_error(exception:name_error("i"))
end
if _type(_temp98) == 'number' then
_temp98 = number:new(_temp98)
elseif _type(_temp98) == "function" or (_type(_temp98) == "table" and _rawget(_temp98, "__call_thing")) then
_temp98 = brat_function:new(_temp98)
end
local _m = _temp98.get
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp99 = _m(_temp98, _temp100)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp98.no_undermethod then
_temp99 = _temp98:no_undermethod(string:new('get'), _temp100)
else
_error(exception:method_error(_temp98, 'get'))
end
return _temp99
end
_lifted[4] = function(_argtable, _self, _temp92, _temp93)
local _temp89 = _argtable['_temp89']
if _temp92 == nil then
_error(exception:argument_error('function', 1, 0))
end
if _temp93 == nil then
_error(exception:argument_error('function', 2, 1))
end
local _temp96
local _temp95
local _temp94
if _type(_temp89) == "function" or (_type(_temp89) == "table" and _rawget(_temp89, "__call_thing")) then
_temp94 = _temp89(_self)
elseif _temp89 then
_temp94 = _temp89
else
_error(exception:name_error("new_underthing"))
end
if _type(_temp94) == 'number' then
_temp94 = number:new(_temp94)
elseif _type(_temp94) == "function" or (_type(_temp94) == "table" and _rawget(_temp94, "__call_thing")) then
_temp94 = brat_function:new(_temp94)
end
local _m = _temp94.prototype
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp95 = _m(_temp94)
elseif _m ~= nil then
_temp95 = _m
elseif _temp94.no_undermethod then
_temp95 = _temp94:no_undermethod(string:new('prototype'))
else
_error(exception:method_error(_temp94, 'prototype'))
end
local _temp97
if _type(_temp92) == "function" or (_type(_temp92) == "table" and _rawget(_temp92, "__call_thing")) then
_temp97 = _temp92(_self)
elseif _temp92 then
_temp97 = _temp92
else
_error(exception:name_error("name"))
end
local _temp101 = _lifted_call(_lifted[5], {})
_temp101.arg_table['_temp93'] = _temp93
if _type(_temp95) == 'number' then
_temp95 = number:new(_temp95)
elseif _type(_temp95) == "function" or (_type(_temp95) == "table" and _rawget(_temp95, "__call_thing")) then
_temp95 = brat_function:new(_temp95)
end
local _m = _temp95.add_undermethod
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp96 = _m(_temp95, _temp97, _temp101)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 1))
elseif _temp95.no_undermethod then
_temp96 = _temp95:no_undermethod(string:new('add_method'), _temp97, _temp101)
else
_error(exception:method_error(_temp95, 'add_undermethod'))
end
return _temp96
end
_lifted[6] = function(_argtable, _self)
local _temp1 = _argtable['_temp1']
local _temp138 = _argtable['_temp138']
local _temp144
local _temp143
local _temp142
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp142 = _temp1(_self)
elseif _temp1 then
_temp142 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp142) == 'number' then
_temp142 = number:new(_temp142)
elseif _type(_temp142) == "function" or (_type(_temp142) == "table" and _rawget(_temp142, "__call_thing")) then
_temp142 = brat_function:new(_temp142)
end
local _m = _temp142.types
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp143 = _m(_temp142)
elseif _m ~= nil then
_temp143 = _m
elseif _temp142.no_undermethod then
_temp143 = _temp142:no_undermethod(string:new('types'))
else
_error(exception:method_error(_temp142, 'types'))
end
local _temp146
local _temp145
if _type(_temp138) == "function" or (_type(_temp138) == "table" and _rawget(_temp138, "__call_thing")) then
_temp145 = _temp138(_self)
elseif _temp138 then
_temp145 = _temp138
else
_error(exception:name_error("val"))
end
if _type(_temp145) == 'number' then
_temp145 = number:new(_temp145)
elseif _type(_temp145) == "function" or (_type(_temp145) == "table" and _rawget(_temp145, "__call_thing")) then
_temp145 = brat_function:new(_temp145)
end
local _m = _temp145.name
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp146 = _m(_temp145)
elseif _m ~= nil then
_temp146 = _m
elseif _temp145.no_undermethod then
_temp146 = _temp145:no_undermethod(string:new('name'))
else
_error(exception:method_error(_temp145, 'name'))
end
if _type(_temp143) == 'number' then
_temp143 = number:new(_temp143)
elseif _type(_temp143) == "function" or (_type(_temp143) == "table" and _rawget(_temp143, "__call_thing")) then
_temp143 = brat_function:new(_temp143)
end
local _m = _temp143.get
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp144 = _m(_temp143, _temp146)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp143.no_undermethod then
_temp144 = _temp143:no_undermethod(string:new('get'), _temp146)
else
_error(exception:method_error(_temp143, 'get'))
end
return _temp144
end
local _temp1
local _temp2
if _type(object) == "function" or (_type(object) == "table" and _rawget(object, "__call_thing")) then
_temp2 = object(_self)
elseif object then
_temp2 = object
else
_error(exception:name_error("object"))
end
if _type(_temp2) == 'number' then
_temp2 = number:new(_temp2)
elseif _type(_temp2) == "function" or (_type(_temp2) == "table" and _rawget(_temp2, "__call_thing")) then
_temp2 = brat_function:new(_temp2)
end
local _m = _temp2.new
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp1 = _m(_temp2)
elseif _m ~= nil then
_temp1 = _m
elseif _temp2.no_undermethod then
_temp1 = _temp2:no_undermethod(string:new('new'))
else
_error(exception:method_error(_temp2, 'new'))
end
local _temp3
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp3 = _temp1(_self)
elseif _temp1 then
_temp3 = _temp1
else
_error(exception:name_error("sexp"))
end
local _temp4 = hash:new()
if _type(_temp3) == 'table' then
_temp3['types'] = _temp4
else
_error('Cannot set method on ' .. _temp3)
end
local _temp5
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp5 = _temp1(_self)
elseif _temp1 then
_temp5 = _temp1
else
_error(exception:name_error("sexp"))
end
local _temp7 = function(_self, _temp6)
if _temp6 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp8
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp8 = _m(_self)
elseif _m then
_temp8 = _m
elseif _self.no_undermethod then
_temp8 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
local _temp9
if _type(_temp6) == "function" or (_type(_temp6) == "table" and _rawget(_temp6, "__call_thing")) then
_temp9 = _temp6(_self)
elseif _temp6 then
_temp9 = _temp6
else
_error(exception:name_error("name"))
end
if _type(_temp8) == 'table' then
_temp8['name'] = _temp9
else
_error('Cannot set method on ' .. _temp8)
end
return _temp9
end
if _type(_temp5) == 'table' then
_temp5['init'] = _temp7
else
_error('Cannot set method on ' .. _temp5)
end
local _temp11
local _temp10
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp10 = _temp1(_self)
elseif _temp1 then
_temp10 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp10) == 'number' then
_temp10 = number:new(_temp10)
elseif _type(_temp10) == "function" or (_type(_temp10) == "table" and _rawget(_temp10, "__call_thing")) then
_temp10 = brat_function:new(_temp10)
end
local _m = _temp10.prototype
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp11 = _m(_temp10)
elseif _m ~= nil then
_temp11 = _m
elseif _temp10.no_undermethod then
_temp11 = _temp10:no_undermethod(string:new('prototype'))
else
_error(exception:method_error(_temp10, 'prototype'))
end
local _temp12 = function(_self)
local _temp13
do
local _temp14 = {}
_temp14[1] = "s"
local _temp18
local _temp15
do
local _temp16
_temp15 = {}
local _temp17
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp17 = _m(_self)
elseif _m then
_temp17 = _m
elseif _self.no_undermethod then
_temp17 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
if _type(_temp17) == 'number' then
_temp17 = number:new(_temp17)
elseif _type(_temp17) == "function" or (_type(_temp17) == "table" and _rawget(_temp17, "__call_thing")) then
_temp17 = brat_function:new(_temp17)
end
local _m = _temp17.name
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp16 = _m(_temp17)
elseif _m ~= nil then
_temp16 = _m
elseif _temp17.no_undermethod then
_temp16 = _temp17:no_undermethod(string:new('name'))
else
_error(exception:method_error(_temp17, 'name'))
end
_temp15[1] = _temp16
_temp15 = array:new(_temp15)
end
local _temp20
local _temp19
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp19 = _m(_self)
elseif _m then
_temp19 = _m
elseif _self.no_undermethod then
_temp19 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
if _type(_temp19) == 'number' then
_temp19 = number:new(_temp19)
elseif _type(_temp19) == "function" or (_type(_temp19) == "table" and _rawget(_temp19, "__call_thing")) then
_temp19 = brat_function:new(_temp19)
end
local _m = _temp19.nodes
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp20 = _m(_temp19)
elseif _m ~= nil then
_temp20 = _m
elseif _temp19.no_undermethod then
_temp20 = _temp19:no_undermethod(string:new('nodes'))
else
_error(exception:method_error(_temp19, 'nodes'))
end
if _type(_temp15) == 'number' then
_temp15 = number:new(_temp15)
elseif _type(_temp15) == "function" or (_type(_temp15) == "table" and _rawget(_temp15, "__call_thing")) then
_temp15 = brat_function:new(_temp15)
end
local _m = _temp15._plus
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp18 = _m(_temp15, _temp20)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp15.no_undermethod then
_temp18 = _temp15:no_undermethod(string:new('+'), _temp20)
else
_error(exception:method_error(_temp15, '_plus'))
end
_temp14[2] = _temp18
_temp14[2] = _tostring(_temp14[2])
_temp13 = string:new(_table.concat(_temp14))
end
return _temp13
end
if _type(_temp11) == 'table' then
_temp11['to_unders'] = _temp12
else
_error('Cannot set method on ' .. _temp11)
end
local _temp22
local _temp21
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp21 = _temp1(_self)
elseif _temp1 then
_temp21 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp21) == 'number' then
_temp21 = number:new(_temp21)
elseif _type(_temp21) == "function" or (_type(_temp21) == "table" and _rawget(_temp21, "__call_thing")) then
_temp21 = brat_function:new(_temp21)
end
local _m = _temp21.prototype
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp22 = _m(_temp21)
elseif _m ~= nil then
_temp22 = _m
elseif _temp21.no_undermethod then
_temp22 = _temp21:no_undermethod(string:new('prototype'))
else
_error(exception:method_error(_temp21, 'prototype'))
end
local _temp24 = function(_self, _temp23)
if _temp23 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp25
if _type(_temp25) == "function" or (_type(_temp25) == "table" and _rawget(_temp25, "__call_thing")) then
_temp25 = _temp25(_self)
elseif _temp25 then
_temp25 = _temp25
else
_error(exception:name_error("my"))
end
local _temp26
local _temp28
local _temp27
if _type(_temp23) == "function" or (_type(_temp23) == "table" and _rawget(_temp23, "__call_thing")) then
_temp27 = _temp23(_self)
elseif _temp23 then
_temp27 = _temp23
else
_error(exception:name_error("rhs"))
end
local _temp29 = string:new('name')
if _type(_temp27) == 'number' then
_temp27 = number:new(_temp27)
elseif _type(_temp27) == "function" or (_type(_temp27) == "table" and _rawget(_temp27, "__call_thing")) then
_temp27 = brat_function:new(_temp27)
end
local _m = _temp27.has_undermethod_question
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp28 = _m(_temp27, _temp29)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp27.no_undermethod then
_temp28 = _temp27:no_undermethod(string:new('has_method?'), _temp29)
else
_error(exception:method_error(_temp27, 'has_undermethod_question'))
end
local _temp31
local _temp30
if _type(_temp23) == "function" or (_type(_temp23) == "table" and _rawget(_temp23, "__call_thing")) then
_temp30 = _temp23(_self)
elseif _temp23 then
_temp30 = _temp23
else
_error(exception:name_error("rhs"))
end
local _temp32 = string:new('nodes')
if _type(_temp30) == 'number' then
_temp30 = number:new(_temp30)
elseif _type(_temp30) == "function" or (_type(_temp30) == "table" and _rawget(_temp30, "__call_thing")) then
_temp30 = brat_function:new(_temp30)
end
local _m = _temp30.has_undermethod_question
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp31 = _m(_temp30, _temp32)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp30.no_undermethod then
_temp31 = _temp30:no_undermethod(string:new('has_method?'), _temp32)
else
_error(exception:method_error(_temp30, 'has_undermethod_question'))
end
if _type(_temp28) == 'number' then
_temp28 = number:new(_temp28)
elseif _type(_temp28) == "function" or (_type(_temp28) == "table" and _rawget(_temp28, "__call_thing")) then
_temp28 = brat_function:new(_temp28)
end
local _m = _temp28._and_and
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp29 = _m(_temp28, _temp31)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp28.no_undermethod then
_temp29 = _temp28:no_undermethod(string:new('&&'), _temp31)
else
_error(exception:method_error(_temp28, '_and_and'))
end
_temp31 = _lifted_call(_lifted[1], {})
_temp31.arg_table['_temp25'] = _temp25
_temp31.arg_table['_temp23'] = _temp23
if true_question then
_temp26 = true_question(_self, _temp29, _temp31)
else
if _type(_self) == 'number' then
_self = number:new(_self)
elseif _type(_self) == "function" or (_type(_self) == "table" and _rawget(_self, "__call_thing")) then
_self = brat_function:new(_self)
end
local _m = _self.true_question
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp26 = _m(_self, _temp29, _temp31)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 1))
elseif _self.no_undermethod then
_temp26 = _self:no_undermethod(string:new('true?'), _temp29, _temp31)
else
_error(exception:method_error(_self, 'true_question'))
end
end
return _temp26
end
if _type(_temp22) == 'table' then
_temp22['_equal_equal'] = _temp24
else
_error('Cannot set method on ' .. _temp22)
end
local _temp45
local _temp44
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp44 = _temp1(_self)
elseif _temp1 then
_temp44 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp44) == 'number' then
_temp44 = number:new(_temp44)
elseif _type(_temp44) == "function" or (_type(_temp44) == "table" and _rawget(_temp44, "__call_thing")) then
_temp44 = brat_function:new(_temp44)
end
local _m = _temp44.prototype
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp45 = _m(_temp44)
elseif _m ~= nil then
_temp45 = _m
elseif _temp44.no_undermethod then
_temp45 = _temp44:no_undermethod(string:new('prototype'))
else
_error(exception:method_error(_temp44, 'prototype'))
end
local _temp47 = function(_self, _temp46)
if _temp46 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp50
local _temp49
local _temp48
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp48 = _m(_self)
elseif _m then
_temp48 = _m
elseif _self.no_undermethod then
_temp48 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
if _type(_temp48) == 'number' then
_temp48 = number:new(_temp48)
elseif _type(_temp48) == "function" or (_type(_temp48) == "table" and _rawget(_temp48, "__call_thing")) then
_temp48 = brat_function:new(_temp48)
end
local _m = _temp48.nodes
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp49 = _m(_temp48)
elseif _m ~= nil then
_temp49 = _m
elseif _temp48.no_undermethod then
_temp49 = _temp48:no_undermethod(string:new('nodes'))
else
_error(exception:method_error(_temp48, 'nodes'))
end
local _temp51
if _type(_temp46) == "function" or (_type(_temp46) == "table" and _rawget(_temp46, "__call_thing")) then
_temp51 = _temp46(_self)
elseif _temp46 then
_temp51 = _temp46
else
_error(exception:name_error("val"))
end
if _type(_temp49) == 'number' then
_temp49 = number:new(_temp49)
elseif _type(_temp49) == "function" or (_type(_temp49) == "table" and _rawget(_temp49, "__call_thing")) then
_temp49 = brat_function:new(_temp49)
end
local _m = _temp49._less_less
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp50 = _m(_temp49, _temp51)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp49.no_undermethod then
_temp50 = _temp49:no_undermethod(string:new('<<'), _temp51)
else
_error(exception:method_error(_temp49, '_less_less'))
end
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp51 = _m(_self)
elseif _m then
_temp51 = _m
elseif _self.no_undermethod then
_temp51 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
return _temp51
end
if _type(_temp45) == 'table' then
_temp45['_less_less'] = _temp47
else
_error('Cannot set method on ' .. _temp45)
end
local _temp53
local _temp52
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp52 = _temp1(_self)
elseif _temp1 then
_temp52 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp52) == 'number' then
_temp52 = number:new(_temp52)
elseif _type(_temp52) == "function" or (_type(_temp52) == "table" and _rawget(_temp52, "__call_thing")) then
_temp52 = brat_function:new(_temp52)
end
local _m = _temp52.prototype
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp53 = _m(_temp52)
elseif _m ~= nil then
_temp53 = _m
elseif _temp52.no_undermethod then
_temp53 = _temp52:no_undermethod(string:new('prototype'))
else
_error(exception:method_error(_temp52, 'prototype'))
end
local _temp55 = function(_self, _temp54)
if _temp54 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp57
local _temp56
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp56 = _m(_self)
elseif _m then
_temp56 = _m
elseif _self.no_undermethod then
_temp56 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
if _type(_temp56) == 'number' then
_temp56 = number:new(_temp56)
elseif _type(_temp56) == "function" or (_type(_temp56) == "table" and _rawget(_temp56, "__call_thing")) then
_temp56 = brat_function:new(_temp56)
end
local _m = _temp56.nodes
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp57 = _m(_temp56)
elseif _m ~= nil then
_temp57 = _m
elseif _temp56.no_undermethod then
_temp57 = _temp56:no_undermethod(string:new('nodes'))
else
_error(exception:method_error(_temp56, 'nodes'))
end
local _temp58
if _type(_temp54) == "function" or (_type(_temp54) == "table" and _rawget(_temp54, "__call_thing")) then
_temp58 = _temp54(_self)
elseif _temp54 then
_temp58 = _temp54
else
_error(exception:name_error("val"))
end
if _type(_temp57) == 'number' then
_temp57 = number:new(_temp57)
elseif _type(_temp57) == "function" or (_type(_temp57) == "table" and _rawget(_temp57, "__call_thing")) then
_temp57 = brat_function:new(_temp57)
end
local _m = _temp57.concat
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_dummy = _m(_temp57, _temp58)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp57.no_undermethod then
_dummy = _temp57:no_undermethod(string:new('concat'), _temp58)
else
_error(exception:method_error(_temp57, 'concat'))
end
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp58 = _m(_self)
elseif _m then
_temp58 = _m
elseif _self.no_undermethod then
_temp58 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
return _temp58
end
if _type(_temp53) == 'table' then
_temp53['concat'] = _temp55
else
_error('Cannot set method on ' .. _temp53)
end
local _temp60
local _temp59
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp59 = _temp1(_self)
elseif _temp1 then
_temp59 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp59) == 'number' then
_temp59 = number:new(_temp59)
elseif _type(_temp59) == "function" or (_type(_temp59) == "table" and _rawget(_temp59, "__call_thing")) then
_temp59 = brat_function:new(_temp59)
end
local _m = _temp59.prototype
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp60 = _m(_temp59)
elseif _m ~= nil then
_temp60 = _m
elseif _temp59.no_undermethod then
_temp60 = _temp59:no_undermethod(string:new('prototype'))
else
_error(exception:method_error(_temp59, 'prototype'))
end
local _temp61 = function(_self)
local _temp64
local _temp63
local _temp62
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp62 = _m(_self)
elseif _m then
_temp62 = _m
elseif _self.no_undermethod then
_temp62 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
if _type(_temp62) == 'number' then
_temp62 = number:new(_temp62)
elseif _type(_temp62) == "function" or (_type(_temp62) == "table" and _rawget(_temp62, "__call_thing")) then
_temp62 = brat_function:new(_temp62)
end
local _m = _temp62.nodes
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp63 = _m(_temp62)
elseif _m ~= nil then
_temp63 = _m
elseif _temp62.no_undermethod then
_temp63 = _temp62:no_undermethod(string:new('nodes'))
else
_error(exception:method_error(_temp62, 'nodes'))
end
if _type(_temp63) == 'number' then
_temp63 = number:new(_temp63)
elseif _type(_temp63) == "function" or (_type(_temp63) == "table" and _rawget(_temp63, "__call_thing")) then
_temp63 = brat_function:new(_temp63)
end
local _m = _temp63.last
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp64 = _m(_temp63)
elseif _m ~= nil then
_temp64 = _m
elseif _temp63.no_undermethod then
_temp64 = _temp63:no_undermethod(string:new('last'))
else
_error(exception:method_error(_temp63, 'last'))
end
return _temp64
end
if _type(_temp60) == 'table' then
_temp60['last'] = _temp61
else
_error('Cannot set method on ' .. _temp60)
end
local _temp66
local _temp65
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp65 = _temp1(_self)
elseif _temp1 then
_temp65 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp65) == 'number' then
_temp65 = number:new(_temp65)
elseif _type(_temp65) == "function" or (_type(_temp65) == "table" and _rawget(_temp65, "__call_thing")) then
_temp65 = brat_function:new(_temp65)
end
local _m = _temp65.prototype
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp66 = _m(_temp65)
elseif _m ~= nil then
_temp66 = _m
elseif _temp65.no_undermethod then
_temp66 = _temp65:no_undermethod(string:new('prototype'))
else
_error(exception:method_error(_temp65, 'prototype'))
end
local _temp68 = function(_self, _temp67)
if _temp67 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp71
local _temp70
local _temp69
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp69 = _m(_self)
elseif _m then
_temp69 = _m
elseif _self.no_undermethod then
_temp69 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
if _type(_temp69) == 'number' then
_temp69 = number:new(_temp69)
elseif _type(_temp69) == "function" or (_type(_temp69) == "table" and _rawget(_temp69, "__call_thing")) then
_temp69 = brat_function:new(_temp69)
end
local _m = _temp69.nodes
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp70 = _m(_temp69)
elseif _m ~= nil then
_temp70 = _m
elseif _temp69.no_undermethod then
_temp70 = _temp69:no_undermethod(string:new('nodes'))
else
_error(exception:method_error(_temp69, 'nodes'))
end
local _temp72
if _temp67 then
_temp72 = _temp67
else
_error(exception:null_error("block", "access it"))
end
if _type(_temp70) == 'number' then
_temp70 = number:new(_temp70)
elseif _type(_temp70) == "function" or (_type(_temp70) == "table" and _rawget(_temp70, "__call_thing")) then
_temp70 = brat_function:new(_temp70)
end
local _m = _temp70.map_bang
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp71 = _m(_temp70, _temp72)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp70.no_undermethod then
_temp71 = _temp70:no_undermethod(string:new('map!'), _temp72)
else
_error(exception:method_error(_temp70, 'map_bang'))
end
return _temp71
end
if _type(_temp66) == 'table' then
_temp66['map_bang'] = _temp68
else
_error('Cannot set method on ' .. _temp66)
end
local _temp73
_temp73 = function(_self, _temp74)
if _temp74 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp75
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp75 = _m(_self)
elseif _m then
_temp75 = _m
elseif _self.no_undermethod then
_temp75 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
local _temp76
if _type(_temp74) == "function" or (_type(_temp74) == "table" and _rawget(_temp74, "__call_thing")) then
_temp76 = _temp74(_self)
elseif _temp74 then
_temp76 = _temp74
else
_error(exception:name_error("nodes"))
end
if _type(_temp75) == 'table' then
_temp75['nodes'] = _temp76
else
_error('Cannot set method on ' .. _temp75)
end
local _temp77
local _temp78
local _temp81
local _temp80
local _temp79
local _m
if my then
_m = my
else
_m = _self["my"]
end
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp79 = _m(_self)
elseif _m then
_temp79 = _m
elseif _self.no_undermethod then
_temp79 = _self:no_undermethod(string:new('my'))
else
_error(exception:name_error("my"))
end
if _type(_temp79) == 'number' then
_temp79 = number:new(_temp79)
elseif _type(_temp79) == "function" or (_type(_temp79) == "table" and _rawget(_temp79, "__call_thing")) then
_temp79 = brat_function:new(_temp79)
end
local _m = _temp79.nodes
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp80 = _m(_temp79)
elseif _m ~= nil then
_temp80 = _m
elseif _temp79.no_undermethod then
_temp80 = _temp79:no_undermethod(string:new('nodes'))
else
_error(exception:method_error(_temp79, 'nodes'))
end
if _type(_temp80) == 'number' then
_temp80 = number:new(_temp80)
elseif _type(_temp80) == "function" or (_type(_temp80) == "table" and _rawget(_temp80, "__call_thing")) then
_temp80 = brat_function:new(_temp80)
end
local _m = _temp80.length
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp81 = _m(_temp80)
elseif _m ~= nil then
_temp81 = _m
elseif _temp80.no_undermethod then
_temp81 = _temp80:no_undermethod(string:new('length'))
else
_error(exception:method_error(_temp80, 'length'))
end
if _type(_temp81) == 'number' then
if number._unchanged('_equal_equal') then
if _temp81 == 1 then
_temp78 = object.__true
else
_temp78 = object.__false
end
else
if _type(_temp81) == 'number' then
_temp81 = number:new(_temp81)
elseif _type(_temp81) == "function" or (_type(_temp81) == "table" and _rawget(_temp81, "__call_thing")) then
_temp81 = brat_function:new(_temp81)
end
local _m = _temp81._equal_equal
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp78 = _m(_temp81, 1)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp81.no_undermethod then
_temp78 = _temp81:no_undermethod(string:new('=='), 1)
else
_error(exception:method_error(_temp81, '_equal_equal'))
end
end
else
if _type(_temp81) == 'number' then
_temp81 = number:new(_temp81)
elseif _type(_temp81) == "function" or (_type(_temp81) == "table" and _rawget(_temp81, "__call_thing")) then
_temp81 = brat_function:new(_temp81)
end
local _m = _temp81._equal_equal
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp78 = _m(_temp81, 1)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp81.no_undermethod then
_temp78 = _temp81:no_undermethod(string:new('=='), 1)
else
_error(exception:method_error(_temp81, '_equal_equal'))
end
end
local _temp85 = _lifted_call(_lifted[3], {})
_temp85.arg_table['_temp74'] = _temp74
if true_question then
_temp77 = true_question(_self, _temp78, _temp85)
else
if _type(_self) == 'number' then
_self = number:new(_self)
elseif _type(_self) == "function" or (_type(_self) == "table" and _rawget(_self, "__call_thing")) then
_self = brat_function:new(_self)
end
local _m = _self.true_question
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp77 = _m(_self, _temp78, _temp85)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 1))
elseif _self.no_undermethod then
_temp77 = _self:no_undermethod(string:new('true?'), _temp78, _temp85)
else
_error(exception:method_error(_self, 'true_question'))
end
end
return _temp77
end
local _temp86
_temp86 = function(_self, _temp87, ...)
if _temp87 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp88 = array:new(...)
local _temp89
local _temp90
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp90 = _temp1(_self)
elseif _temp1 then
_temp90 = _temp1
else
_error(exception:name_error("sexp"))
end
local _temp91
if _type(_temp87) == "function" or (_type(_temp87) == "table" and _rawget(_temp87, "__call_thing")) then
_temp91 = _temp87(_self)
elseif _temp87 then
_temp91 = _temp87
else
_error(exception:name_error("name"))
end
if _type(_temp90) == 'number' then
_temp90 = number:new(_temp90)
elseif _type(_temp90) == "function" or (_type(_temp90) == "table" and _rawget(_temp90, "__call_thing")) then
_temp90 = brat_function:new(_temp90)
end
local _m = _temp90.new
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp89 = _m(_temp90, _temp91)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp90.no_undermethod then
_temp89 = _temp90:no_undermethod(string:new('new'), _temp91)
else
_error(exception:method_error(_temp90, 'new'))
end
if _type(_temp88) == "function" or (_type(_temp88) == "table" and _rawget(_temp88, "__call_thing")) then
_temp91 = _temp88(_self)
elseif _temp88 then
_temp91 = _temp88
else
_error(exception:name_error("meths"))
end
local _temp102 = _lifted_call(_lifted[4], {})
_temp102.arg_table['_temp89'] = _temp89
if _type(_temp91) == 'number' then
_temp91 = number:new(_temp91)
elseif _type(_temp91) == "function" or (_type(_temp91) == "table" and _rawget(_temp91, "__call_thing")) then
_temp91 = brat_function:new(_temp91)
end
local _m = _temp91.each_underwith_underindex
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_dummy = _m(_temp91, _temp102)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp91.no_undermethod then
_dummy = _temp91:no_undermethod(string:new('each_with_index'), _temp102)
else
_error(exception:method_error(_temp91, 'each_underwith_underindex'))
end
if _type(_temp89) == "function" or (_type(_temp89) == "table" and _rawget(_temp89, "__call_thing")) then
_temp102 = _temp89(_self)
elseif _temp89 then
_temp102 = _temp89
else
_error(exception:name_error("new_underthing"))
end
local _temp103
if _temp73 then
_temp103 = _temp73
else
_error(exception:null_error("initializer", "access it"))
end
if _type(_temp102) == 'table' then
_temp102['init'] = _temp103
else
_error('Cannot set method on ' .. _temp102)
end
local _temp106
local _temp105
local _temp104
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp104 = _temp1(_self)
elseif _temp1 then
_temp104 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp104) == 'number' then
_temp104 = number:new(_temp104)
elseif _type(_temp104) == "function" or (_type(_temp104) == "table" and _rawget(_temp104, "__call_thing")) then
_temp104 = brat_function:new(_temp104)
end
local _m = _temp104.types
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp105 = _m(_temp104)
elseif _m ~= nil then
_temp105 = _m
elseif _temp104.no_undermethod then
_temp105 = _temp104:no_undermethod(string:new('types'))
else
_error(exception:method_error(_temp104, 'types'))
end
local _temp107
if _type(_temp87) == "function" or (_type(_temp87) == "table" and _rawget(_temp87, "__call_thing")) then
_temp107 = _temp87(_self)
elseif _temp87 then
_temp107 = _temp87
else
_error(exception:name_error("name"))
end
local _temp108
if _type(_temp89) == "function" or (_type(_temp89) == "table" and _rawget(_temp89, "__call_thing")) then
_temp108 = _temp89(_self)
elseif _temp89 then
_temp108 = _temp89
else
_error(exception:name_error("new_underthing"))
end
if _type(_temp105) == 'number' then
_temp105 = number:new(_temp105)
elseif _type(_temp105) == "function" or (_type(_temp105) == "table" and _rawget(_temp105, "__call_thing")) then
_temp105 = brat_function:new(_temp105)
end
local _m = _temp105.set
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp106 = _m(_temp105, _temp107, _temp108)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 1))
elseif _temp105.no_undermethod then
_temp106 = _temp105:no_undermethod(string:new('set'), _temp107, _temp108)
else
_error(exception:method_error(_temp105, 'set'))
end
return _temp106
end
local _temp109
local _temp110 = string:new('grammar')
_temp109 = _temp86(_self, _temp110)
local _temp111 = string:new('rule_def')
_temp110 = _temp86(_self, _temp111)
local _temp112 = string:new('any')
_temp111 = _temp86(_self, _temp112)
local _temp113 = string:new('seq')
_temp112 = _temp86(_self, _temp113)
local _temp114 = string:new('str')
_temp113 = _temp86(_self, _temp114)
local _temp115 = string:new('rule_ref')
_temp114 = _temp86(_self, _temp115)
local _temp116 = string:new('anything')
_temp115 = _temp86(_self, _temp116)
local _temp117 = string:new('nothing')
_temp116 = _temp86(_self, _temp117)
local _temp118 = string:new('regex')
_temp117 = _temp86(_self, _temp118)
local _temp119 = string:new('label')
_temp118 = _temp86(_self, _temp119)
local _temp120 = string:new('maybe')
_temp119 = _temp86(_self, _temp120)
local _temp121 = string:new('kleene')
_temp120 = _temp86(_self, _temp121)
local _temp122 = string:new('many')
_temp121 = _temp86(_self, _temp122)
local _temp123 = string:new('no')
_temp122 = _temp86(_self, _temp123)
local _temp124 = string:new('and')
_temp123 = _temp86(_self, _temp124)
local _temp125 = string:new('action')
_temp124 = _temp86(_self, _temp125)
local _temp126 = string:new('squish')
_temp125 = _temp86(_self, _temp126)
local _temp127
if _type(object) == "function" or (_type(object) == "table" and _rawget(object, "__call_thing")) then
_temp126 = object(_self)
elseif object then
_temp126 = object
else
_error(exception:name_error("object"))
end
if _type(_temp126) == 'number' then
_temp126 = number:new(_temp126)
elseif _type(_temp126) == "function" or (_type(_temp126) == "table" and _rawget(_temp126, "__call_thing")) then
_temp126 = brat_function:new(_temp126)
end
local _m = _temp126.new
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp127 = _m(_temp126)
elseif _m ~= nil then
_temp127 = _m
elseif _temp126.no_undermethod then
_temp127 = _temp126:no_undermethod(string:new('new'))
else
_error(exception:method_error(_temp126, 'new'))
end
local _temp128
if _type(_temp127) == "function" or (_type(_temp127) == "table" and _rawget(_temp127, "__call_thing")) then
_temp128 = _temp127(_self)
elseif _temp127 then
_temp128 = _temp127
else
_error(exception:name_error("s"))
end
local _temp131 = function(_self, _temp129, ...)
if _temp129 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp130 = array:new(...)
local _temp134
local _temp133
local _temp132
if _type(_temp1) == "function" or (_type(_temp1) == "table" and _rawget(_temp1, "__call_thing")) then
_temp132 = _temp1(_self)
elseif _temp1 then
_temp132 = _temp1
else
_error(exception:name_error("sexp"))
end
if _type(_temp132) == 'number' then
_temp132 = number:new(_temp132)
elseif _type(_temp132) == "function" or (_type(_temp132) == "table" and _rawget(_temp132, "__call_thing")) then
_temp132 = brat_function:new(_temp132)
end
local _m = _temp132.types
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp133 = _m(_temp132)
elseif _m ~= nil then
_temp133 = _m
elseif _temp132.no_undermethod then
_temp133 = _temp132:no_undermethod(string:new('types'))
else
_error(exception:method_error(_temp132, 'types'))
end
local _temp135
if _type(_temp129) == "function" or (_type(_temp129) == "table" and _rawget(_temp129, "__call_thing")) then
_temp135 = _temp129(_self)
elseif _temp129 then
_temp135 = _temp129
else
_error(exception:name_error("name"))
end
if _type(_temp133) == 'number' then
_temp133 = number:new(_temp133)
elseif _type(_temp133) == "function" or (_type(_temp133) == "table" and _rawget(_temp133, "__call_thing")) then
_temp133 = brat_function:new(_temp133)
end
local _m = _temp133.get
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp134 = _m(_temp133, _temp135)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp133.no_undermethod then
_temp134 = _temp133:no_undermethod(string:new('get'), _temp135)
else
_error(exception:method_error(_temp133, 'get'))
end
local _temp136
if _type(_temp130) == "function" or (_type(_temp130) == "table" and _rawget(_temp130, "__call_thing")) then
_temp136 = _temp130(_self)
elseif _temp130 then
_temp136 = _temp130
else
_error(exception:name_error("args"))
end
if _type(_temp134) == 'number' then
_temp134 = number:new(_temp134)
elseif _type(_temp134) == "function" or (_type(_temp134) == "table" and _rawget(_temp134, "__call_thing")) then
_temp134 = brat_function:new(_temp134)
end
local _m = _temp134.new
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp135 = _m(_temp134, _temp136)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp134.no_undermethod then
_temp135 = _temp134:no_undermethod(string:new('new'), _temp136)
else
_error(exception:method_error(_temp134, 'new'))
end
return _temp135
end
if _type(_temp128) == 'table' then
_temp128['get'] = _temp131
else
_error('Cannot set method on ' .. _temp128)
end
local _temp137
_temp137 = function(_self, _temp138)
if _temp138 == nil then
_error(exception:argument_error('function', 1, 0))
end
local _temp140
local _temp139
if _type(_temp138) == "function" or (_type(_temp138) == "table" and _rawget(_temp138, "__call_thing")) then
_temp139 = _temp138(_self)
elseif _temp138 then
_temp139 = _temp138
else
_error(exception:name_error("val"))
end
local _temp141 = string:new('name')
if _type(_temp139) == 'number' then
_temp139 = number:new(_temp139)
elseif _type(_temp139) == "function" or (_type(_temp139) == "table" and _rawget(_temp139, "__call_thing")) then
_temp139 = brat_function:new(_temp139)
end
local _m = _temp139.has_undermethod_question
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp140 = _m(_temp139, _temp141)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp139.no_undermethod then
_temp140 = _temp139:no_undermethod(string:new('has_method?'), _temp141)
else
_error(exception:method_error(_temp139, 'has_undermethod_question'))
end
local _temp147 = _lifted_call(_lifted[6], {})
_temp147.arg_table['_temp1'] = _temp1
_temp147.arg_table['_temp138'] = _temp138
if _type(_temp140) == 'number' then
_temp140 = number:new(_temp140)
elseif _type(_temp140) == "function" or (_type(_temp140) == "table" and _rawget(_temp140, "__call_thing")) then
_temp140 = brat_function:new(_temp140)
end
local _m = _temp140._and_and
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp141 = _m(_temp140, _temp147)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 0))
elseif _temp140.no_undermethod then
_temp141 = _temp140:no_undermethod(string:new('&&'), _temp147)
else
_error(exception:method_error(_temp140, '_and_and'))
end
return _temp141
end
local _temp148
local _temp149
if _temp137 then
_temp149 = _temp137
else
_error(exception:null_error("sexp_question", "access it"))
end
local _temp150 = string:new('sexp?')
if export then
_temp148 = export(_self, _temp149, _temp150)
else
if _type(_self) == 'number' then
_self = number:new(_self)
elseif _type(_self) == "function" or (_type(_self) == "table" and _rawget(_self, "__call_thing")) then
_self = brat_function:new(_self)
end
local _m = _self.export
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp148 = _m(_self, _temp149, _temp150)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 1))
elseif _self.no_undermethod then
_temp148 = _self:no_undermethod(string:new('export'), _temp149, _temp150)
else
_error(exception:method_error(_self, 'export'))
end
end
if _type(_temp127) == "function" or (_type(_temp127) == "table" and _rawget(_temp127, "__call_thing")) then
_temp149 = _temp127(_self)
elseif _temp127 then
_temp149 = _temp127
else
_error(exception:name_error("s"))
end
local _temp151 = string:new('s')
if export then
_temp150 = export(_self, _temp149, _temp151)
else
if _type(_self) == 'number' then
_self = number:new(_self)
elseif _type(_self) == "function" or (_type(_self) == "table" and _rawget(_self, "__call_thing")) then
_self = brat_function:new(_self)
end
local _m = _self.export
if _type(_m) == "function" or (_type(_m) == "table" and _rawget(_m, "__call_thing")) then
_temp150 = _m(_self, _temp149, _temp151)
elseif _m ~= nil then
_error(exception:argument_error('function', 0, 1))
elseif _self.no_undermethod then
_temp150 = _self:no_undermethod(string:new('export'), _temp149, _temp151)
else
_error(exception:method_error(_self, 'export'))
end
end
end
local _result = coxpcall(_main, exception._handler)
if not _lib then
if not _result then
os.exit(-1)
else
os.exit(0)
end
end
|
-- Run with test script using...
--
-- $ lua -l luarocks.require wrn_test.lua
--
require('test/test_base')
ambox = require('ambox')
wrn = require('wrn')
do
local sent_arr = {}
local recv_calls = 0
local recv_arr = {}
ambox = {
recv =
function()
recv_calls = recv_calls + 1
assert(recv_calls <= #sent_arr)
assert(recv_calls <= #recv_arr)
local r = assert(recv_arr[recv_calls])
local si = assert(r.sent_id)
local sa = assert(sent_arr[si])
assert(sa[1] == "send")
local filter = assert(sa[4])
filter(assert(r.head),
assert(r.body))
return true, nil, assert(sa[5])
end
}
local function fresh()
sent_arr = {}
recv_calls = 0
recv_arr = {}
end
local function node_send(self, request, filter, ambox_reply_data)
assert(self and request and filter and ambox_reply_data)
sent_arr[#sent_arr + 1] = { "send", self, request, filter, ambox_reply_data }
return self.ok
end
local function node_sendq(self, request)
sent_arr[#sent_arr + 1] = { "sendq", self, request }
return self.ok
end
function TEST_replicate_request()
local nodes, ok, err, state
-- Test min_replica of 0.
--
fresh()
nodes = {}
ok, err, state = wrn.replicate_request("a", nodes, 0)
assert(ok and (not err) and state)
assert(state.request == "a" and state.replica_nodes == nodes)
assert(state.replica_min == 0)
assert(state.replica_next == 1)
assert(state.received_err == 0)
assert(state.received_ok == 0)
assert(#state.sent_err == 0)
assert(#state.sent_ok == 0)
assert(#state.responses == 0)
assert(#sent_arr == 0)
assert(recv_calls == 0)
-- Test min_replica of 1, but there are no nodes.
--
fresh()
nodes = {}
ok, err, state = wrn.replicate_request("a", nodes, 1)
assert((not ok) and err and state)
assert(state.request == "a" and state.replica_nodes == nodes)
assert(state.replica_min == 1)
assert(state.replica_next == 1)
assert(state.received_err == 0)
assert(state.received_ok == 0)
assert(#state.sent_err == 0)
assert(#state.sent_ok == 0)
assert(#state.responses == 0)
assert(#sent_arr == 0)
assert(recv_calls == 0)
-- Test min_replica of 1, and there's just one node.
--
fresh()
nodes = {
{ id = 1, ok = true, send = node_send, sendq = node_sendq }
}
recv_arr = { { sent_id = 1, head = 100, body = 101 } }
ok, err, state = wrn.replicate_request("a", nodes, 1)
assert(ok and (not err) and state)
assert(state.request == "a" and state.replica_nodes == nodes)
assert(state.replica_min == 1)
assert(state.replica_next == 2)
assert(state.received_err == 0)
assert(state.received_ok == 1)
assert(#state.sent_err == 0)
assert(#state.sent_ok == 1)
assert(#state.responses[nodes[1]] == 1)
assert(#sent_arr == 1)
assert(recv_calls == 1)
assert(sent_arr[1][1] == 'send')
assert(sent_arr[1][2].id == 1)
assert(sent_arr[1][3] == 'a')
assert(state.responses[nodes[1]][1].head == 100)
assert(state.responses[nodes[1]][1].body == 101)
-- Test min_replica of 1, and there are a few nodes.
--
fresh()
nodes = {
{ id = 1, ok = true, send = node_send, sendq = node_sendq },
{ id = 2, ok = true, send = node_send, sendq = node_sendq },
{ id = 3, ok = true, send = node_send, sendq = node_sendq },
}
recv_arr = { { sent_id = 1, head = 100, body = 101 } }
ok, err, state = wrn.replicate_request("a", nodes, 1)
assert(ok and (not err) and state)
assert(state.request == "a" and state.replica_nodes == nodes)
assert(state.replica_min == 1)
assert(state.replica_next == 2)
assert(state.received_err == 0)
assert(state.received_ok == 1)
assert(#state.sent_err == 0)
assert(#state.sent_ok == 1)
assert(#state.responses[nodes[1]] == 1)
assert(#sent_arr == 1)
assert(recv_calls == 1)
assert(sent_arr[1][1] == 'send')
assert(sent_arr[1][2].id == 1)
assert(sent_arr[1][3] == 'a')
assert(state.responses[nodes[1]][1].head == 100)
assert(state.responses[nodes[1]][1].body == 101)
-- Test min_replica of 2, and there are a few nodes > 2.
--
fresh()
nodes = {
{ id = 1, ok = true, send = node_send, sendq = node_sendq },
{ id = 2, ok = true, send = node_send, sendq = node_sendq },
{ id = 3, ok = true, send = node_send, sendq = node_sendq },
}
recv_arr = { { sent_id = 1, head = 100, body = 101 },
{ sent_id = 2, head = 200, body = 201 } }
ok, err, state = wrn.replicate_request("a", nodes, 2)
assert(ok and (not err) and state)
assert(state.request == "a" and state.replica_nodes == nodes)
assert(state.replica_min == 2)
assert(state.replica_next == 3)
assert(state.received_err == 0)
assert(state.received_ok == 2)
assert(#state.sent_err == 0)
assert(#state.sent_ok == 2)
assert(#state.responses[nodes[1]] == 1)
assert(#state.responses[nodes[2]] == 1)
assert(state.responses[nodes[3]] == nil)
assert(#sent_arr == 2)
assert(recv_calls == 2)
assert(sent_arr[1][1] == 'send')
assert(sent_arr[1][2].id == 1)
assert(sent_arr[1][3] == 'a')
assert(sent_arr[2][1] == 'send')
assert(sent_arr[2][2].id == 2)
assert(sent_arr[2][3] == 'a')
assert(state.responses[nodes[1]][1].head == 100)
assert(state.responses[nodes[1]][1].body == 101)
assert(state.responses[nodes[2]][1].head == 200)
assert(state.responses[nodes[2]][1].body == 201)
-- Test when min_replica > number of nodes, should return error.
--
fresh()
nodes = {
{ id = 1, ok = true, send = node_send, sendq = node_sendq }
}
recv_arr = { { sent_id = 1, head = 100, body = 101 } }
ok, err, state = wrn.replicate_request("a", nodes, 2)
assert((not ok) and err and state)
assert(state.request == "a" and state.replica_nodes == nodes)
assert(state.replica_min == 2)
assert(state.replica_next == 2)
assert(state.received_err == 0)
assert(state.received_ok == 1)
assert(#state.sent_err == 0)
assert(#state.sent_ok == 1)
assert(#state.responses[nodes[1]] == 1)
assert(#sent_arr == 1)
assert(recv_calls == 1)
assert(sent_arr[1][1] == 'send')
assert(sent_arr[1][2].id == 1)
assert(sent_arr[1][3] == 'a')
assert(state.responses[nodes[1]][1].head == 100)
assert(state.responses[nodes[1]][1].body == 101)
-- Test min_replica of 2, and there are a enough nodes,
-- but one of them is not ok.
--
fresh()
nodes = {
{ id = 1, ok = true, send = node_send, sendq = node_sendq },
{ id = 2, ok = false, send = node_send, sendq = node_sendq },
{ id = 3, ok = true, send = node_send, sendq = node_sendq },
}
recv_arr = { { sent_id = 1, head = 100, body = 101 },
{ sent_id = 3, head = 300, body = 301 } }
ok, err, state = wrn.replicate_request("a", nodes, 2)
assert(ok and (not err) and state)
assert(state.request == "a" and state.replica_nodes == nodes)
assert(state.replica_min == 2)
assert(state.replica_next == 4)
assert(state.received_err == 0)
assert(state.received_ok == 2)
assert(#state.sent_err == 1)
assert(#state.sent_ok == 2)
assert(#state.responses[nodes[1]] == 1)
assert(state.responses[nodes[2]] == nil)
assert(#state.responses[nodes[3]] == 1)
assert(#sent_arr == 3)
assert(recv_calls == 2)
assert(sent_arr[1][1] == 'send')
assert(sent_arr[1][2].id == 1)
assert(sent_arr[1][3] == 'a')
assert(sent_arr[2][1] == 'send')
assert(sent_arr[2][2].id == 2)
assert(sent_arr[2][3] == 'a')
assert(sent_arr[3][1] == 'send')
assert(sent_arr[3][2].id == 3)
assert(sent_arr[3][3] == 'a')
assert(state.responses[nodes[1]][1].head == 100)
assert(state.responses[nodes[1]][1].body == 101)
assert(state.responses[nodes[3]][1].head == 300)
assert(state.responses[nodes[3]][1].body == 301)
-- Test min_replica of 2, and there are a enough nodes,
-- but one of them is not ok.
--
fresh()
nodes = {
{ id = 1, ok = false, send = node_send, sendq = node_sendq },
{ id = 2, ok = true, send = node_send, sendq = node_sendq },
{ id = 3, ok = true, send = node_send, sendq = node_sendq },
}
recv_arr = { { sent_id = 2, head = 200, body = 201 },
{ sent_id = 3, head = 300, body = 301 } }
ok, err, state = wrn.replicate_request("a", nodes, 2)
assert(ok and (not err) and state)
assert(state.request == "a" and state.replica_nodes == nodes)
assert(state.replica_min == 2)
assert(state.replica_next == 4)
assert(state.received_err == 0)
assert(state.received_ok == 2)
assert(#state.sent_err == 1)
assert(#state.sent_ok == 2)
assert(state.responses[nodes[1]] == nil)
assert(#state.responses[nodes[2]] == 1)
assert(#state.responses[nodes[3]] == 1)
assert(#sent_arr == 3)
assert(recv_calls == 2)
assert(sent_arr[1][1] == 'send')
assert(sent_arr[1][2].id == 1)
assert(sent_arr[1][3] == 'a')
assert(sent_arr[2][1] == 'send')
assert(sent_arr[2][2].id == 2)
assert(sent_arr[2][3] == 'a')
assert(sent_arr[3][1] == 'send')
assert(sent_arr[3][2].id == 3)
assert(sent_arr[3][3] == 'a')
assert(state.responses[nodes[2]][1].head == 200)
assert(state.responses[nodes[2]][1].body == 201)
assert(state.responses[nodes[3]][1].head == 300)
assert(state.responses[nodes[3]][1].body == 301)
print("done!")
return true
end
end
TEST_replicate_request()
----------------------------------------
-- From Voldemort talk...
--
-- Dynamo-style R + W > N tunable knobs
--
-- N is number of replicas
-- W is number of blocking replica writes that must succeed
-- before returning a success.
-- R is number of blocking replica reads that must succeed
-- before returning a success.
--
-- Vector Clock
--
-- tuple {t1, t2, ..., tn} of counters
-- if network partition, then vector clocks might not be comparable,
-- so an app-level conflict
--
-- Vector Clock versus Timestamp
--
-- Logical Architecture
--
-- client API
-- conflict resolution
-- serialization
-- pluggable (thrift, protocol buffers, compressed json)
-- data lives for > 5 years
-- (compression)
-- [network - optional]
-- routing layer
-- hash calculation
-- replication (N, R, W)
-- failures if node is down, maintain failed node list
-- read repair (online repair mechanism)
-- failover (hinted handoff - catchup after failure)
-- [network - optional]
-- storage engine
--
-- Optional network allows multiple physical architecture options
-- and best-effort partition-aware routing, with
-- no additional backend routing
--
-- Failure Detection
-- Needs to be very fast
-- View of server state may be inconsistent
-- A can see B but C cannot,
-- A can see B, B can see C, C cannot see A
-- Routing layer has timeouts (policy decision)
-- Periodically retry failed nodes
--
-- Read Repair
-- Read from multiple nodes. Update nodes that have old values.
--
-- Hinted Handoff
-- If write fails, write to any random node, but marked special.
-- Each node periodically tries to get rid of special entries.
-- If node was down a long time, their current naive Hinted Handoff
-- might give a lot of updates.
-- Need better Hinted Handoff Bootstrap to avoid too many messages.
-- Their Hinted Handoff feature is off by default.
--
-- Dynamic N, R, W changes
-- Currently lazy. Need to bounce nodes and rolling restart.
-- No 'drain/fill' for voldemort yet?
--
-- Pluggable storage
-- No flush on write is huge win.
--
-- Simple key value lookup use cases
-- - user profile
-- - best seller lists
-- - shopping carts
-- - customer prefs
-- - session mgmt
-- - sales rank
-- - product catalog
|
local ls = require "luasnip"
local s = ls.snippet
local t = ls.text_node
local snippets = {
ls.parser.parse_snippet("lm", "local M = {}\n\nfunction M.setup()\n $1 \nend\n\nreturn M"),
-- s("lm", { t { "local M = {}", "", "function M.setup()", "" }, i(1, ""), t { "", "end", "", "return M" } }),
s("todo", t "print('TODO')"),
}
return snippets
|
local M = {
title = 'plugins',
keypress = function() end,
draw_status = function() end,
}
function M:render()
green()
addstr(' -= plugins =-\n')
normal()
for i, plugin in ipairs(plugins) do
local name = plugin.name or '#' .. tostring(i)
normal()
bold()
addstr(name .. '\n')
normal()
local widget = plugin.widget
if widget ~= nil then
local success, result = pcall(widget)
if success then
normal()
else
red()
addstr(tostring(result))
end
end
end
draw_global_load('cliconn', conn_tracker)
end
return M
|
dependency 'rage-device'
flags { 'NoRuntimeChecks' }
return function()
filter {}
add_dependencies { 'net:tcp-server' }
end
|
--[[
file:login.lua
desc:登陆结构
auth:Carol Luo
]]
---@class c2s_loginTourists @游客登录
---@field accredit string @登录凭证
---@class c2s_loginAccount @账号登陆
---@field users string @用户账号
---@field password string @账号密码
---@class c2s_loginPhone @手机登录
---@field phonenum string @手机号码
---@field password string @账号密码
---@class c2s_loginWeChat @微信登陆
---@field accredit string @微信授权
---@class c2s_changeNickname @更改昵称
---@field nickname string @新的昵称
---@class c2s_changeLogolink @更改昵称
---@field logolink string @新的昵称
---@class s2c_loginResult @登录结果
---@field loginMod string @登录方式
---@field loginBid string @绑定账号
---@field nickname string @用户昵称
---@field users string @用户账号
---@field logolink string @用户头像
---@field rid integer @用户编号
---@field coin score @硬币分数
---@field silver score @银币分数
---@field gold score @金币分数
---@field masonry score @砖石分数
---@field loginCount count @登录次数
---@class role:s2c_loginResult @角色数据
---@class gateClient @连接信息
---@field address ip @地址
---@class client @前端信息
---@field fd socket @套接字
---@field role role @角色数据
---@field online boolean @是否在线
---@class loginClient:client @网关用户信息
---@field assign service @所在分配
---@field competition service @所在桌子
|
require "cocos.3d.3dConstants"
----------------------------------------
----TerrainSimple
----------------------------------------
local TerrainSimple = class("TerrainSimple", function ()
local layer = cc.Layer:create()
return layer
end)
function TerrainSimple:ctor()
-- body
self:init()
end
function TerrainSimple:init()
local visibleSize = cc.Director:getInstance():getVisibleSize()
--use custom camera
self._camera = cc.Camera:createPerspective(60, visibleSize.width/visibleSize.height, 0.1, 800)
self._camera:setCameraFlag(cc.CameraFlag.USER1)
self._camera:setPosition3D(cc.vec3(-1, 1.6, 4))
self:addChild(self._camera)
Helper.initWithLayer(self)
Helper.titleLabel:setString(self:title())
Helper.subtitleLabel:setString(self:subtitle())
local detailMapR = { _detailMapSrc = "TerrainTest/dirt.jpg", _detailMapSize = 35}
local detailMapG = { _detailMapSrc = "TerrainTest/Grass2.jpg", _detailMapSize = 35}
local detailMapB = { _detailMapSrc = "TerrainTest/road.jpg", _detailMapSize = 35}
local detailMapA = { _detailMapSrc = "TerrainTest/GreenSkin.jpg", _detailMapSize = 35}
local terrainData = { _heightMapSrc = "TerrainTest/heightmap16.jpg", _alphaMapSrc = "TerrainTest/alphamap.png" , _detailMaps = {detailMapR, detailMapG, detailMapB, detailMapA}, _detailMapAmount = 4 }
self._terrain = cc.Terrain:create(terrainData,cc.Terrain.CrackFixedType.SKIRT)
self._terrain:setLODDistance(3.2, 6.4, 9.6)
self._terrain:setMaxDetailMapAmount(4)
self:addChild(self._terrain)
self._terrain:setCameraMask(2)
self._terrain:setDrawWire(false)
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(function (touches, event)
local delta = cc.Director:getInstance():getDeltaTime()
local touch = touches[1]
local location = touch:getLocation()
local previousLocation = touch:getPreviousLocation()
local newPos = {x=previousLocation.x - location.x, y=previousLocation.y - location.y}
local matTransform = self:getNodeToWorldTransform()
local cameraDir = {x = -matTransform[9], y = -matTransform[10], z = -matTransform[11]}
cameraDir = cc.vec3normalize(cameraDir)
cameraDir.y = 0
local cameraRightDir = {x = matTransform[1], y = matTransform[2], z = matTransform[3]}
cameraRightDir = cc.vec3normalize(cameraRightDir)
cameraRightDir.y = 0
local cameraPos = self._camera:getPosition3D()
cameraPos = { x = cameraPos.x + cameraDir.x * newPos.y * 0.5 * delta, y = cameraPos.y + cameraDir.y * newPos.y * 0.5 * delta, z = cameraPos.z + cameraDir.z * newPos.y * 0.5 * delta }
cameraPos = { x = cameraPos.x + cameraRightDir.x * newPos.x * 0.5 * delta, y = cameraPos.y + cameraRightDir.y * newPos.x * 0.5 * delta, z = cameraPos.z + cameraRightDir.z * newPos.x * 0.5 * delta }
self._camera:setPosition3D(cameraPos)
end,cc.Handler.EVENT_TOUCHES_MOVED)
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
--add Particle3D for test blend
local rootps = cc.PUParticleSystem3D:create("Particle3D/scripts/mp_torch.pu")
rootps:setCameraMask(cc.CameraFlag.USER1)
rootps:startParticleSystem()
self:addChild(rootps, 0, 0)
end
function TerrainSimple:title()
return "Terrain with skirt"
end
function TerrainSimple:subtitle()
return "Drag to walkThru"
end
----------------------------------------
----TerrainWalkThru
----------------------------------------
local PLAER_STATE =
{
LEFT = 0,
RIGHT = 1,
IDLE = 2,
FORWARD = 3,
BACKWARD = 4,
}
local PLAYER_HEIGHT = 0
local camera_offset = cc.vec3(0, 45, 60)
local Player = class("Player", function(file, cam, terrain)
local sprite = cc.Sprite3D:create(file)
if nil ~= sprite then
sprite._headingAngle = 0
sprite._playerState = PLAER_STATE.IDLE
sprite._cam = cam
sprite._terrain = terrain
end
return sprite
end)
function Player:ctor()
-- body
self:init()
end
function Player:init()
self._headingAxis = cc.vec3(0.0, 0.0, 0.0)
self:scheduleUpdateWithPriorityLua(function(dt)
local curPos = self:getPosition3D()
if self._playerState == PLAER_STATE.IDLE then
elseif self._playerState == PLAER_STATE.FORWARD then
local newFaceDir = cc.vec3sub(self._targetPos, curPos)
newFaceDir.y = 0.0
newFaceDir = cc.vec3normalize(newFaceDir)
local offset = cc.vec3mul(newFaceDir, 25.0 * dt)
curPos = cc.vec3add(curPos, offset)
self:setPosition3D(curPos)
elseif self._playerState == PLAER_STATE.BACKWARD then
local transform = self:getNodeToWorldTransform()
local forward_vec = cc.vec3(-transform[9], -transform[10], -transform[11])
forward_vec = cc.vec3normalize(forward_vec)
self:setPosition3D(cc.vec3sub(curPos, cc.vec3mul(forward_vec, 15 * dt)))
elseif self._playerState == PLAER_STATE.LEFT then
player:setRotation3D(cc.vec3(curPos.x, curPos.y + 25 * dt, curPos.z))
elseif self._playerState == PLAER_STATE.RIGHT then
player:setRotation3D(cc.vec3(curPos.x, curPos.y - 25 * dt, curPos.z))
end
local normal = cc.vec3(0.0, 0.0, 0.0)
local player_h, normal = self._terrain:getHeight(self:getPositionX(), self:getPositionZ(), normal)
self:setPositionY(player_h + PLAYER_HEIGHT)
--need to scriptfile
local q2 = cc.quaternion_createFromAxisAngle(cc.vec3(0, 1, 0), -math.pi)
local headingQ = cc.quaternion_createFromAxisAngle(self._headingAxis, self._headingAngle)
local x = headingQ.w * q2.x + headingQ.x * q2.w + headingQ.y * q2.z - headingQ.z * q2.y
local y = headingQ.w * q2.y - headingQ.x * q2.z + headingQ.y * q2.w + headingQ.z * q2.x
local z = headingQ.w * q2.z + headingQ.x * q2.y - headingQ.y * q2.x + headingQ.z * q2.w
local w = headingQ.w * q2.w - headingQ.x * q2.x - headingQ.y * q2.y - headingQ.z * q2.z
headingQ = cc.quaternion(x, y, z, w)
self:setRotationQuat(headingQ)
local vec_offset = cc.vec4(camera_offset.x, camera_offset.y, camera_offset.z, 1)
local transform = self:getNodeToWorldTransform()
vec_offset = mat4_transformVector(transform, vec_offset)
local playerPos = self:getPosition3D()
self._cam:setPosition3D(cc.vec3add(playerPos, camera_offset))
self:updateState()
end, 0)
self:registerScriptHandler(function (event)
-- body
if "exit" == event then
self:unscheduleUpdate()
end
end)
end
function Player:updateState()
if self._playerState == PLAER_STATE.FORWARD then
local player_pos = cc.p(self:getPositionX(),self:getPositionZ())
local targetPos = cc.p(self._targetPos.x, self._targetPos.z)
local dist = cc.pGetDistance(player_pos, targetPos)
if dist < 1 then
self._playerState = PLAER_STATE.IDLE
end
end
end
local TerrainWalkThru = class("TerrainWalkThru", function ()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
return layer
end)
function TerrainWalkThru:ctor()
-- body
self:init()
end
function TerrainWalkThru:init()
Helper.titleLabel:setString(self:title())
Helper.subtitleLabel:setString(self:subtitle())
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(function (touches, event)
end,cc.Handler.EVENT_TOUCHES_BEGAN)
listener:registerScriptHandler(function (touches, event)
local touch = touches[1]
local location = touch:getLocationInView()
if self._camera ~= nil then
if self._player ~= nil then
local nearP = cc.vec3(location.x, location.y, 0.0)
local farP = cc.vec3(location.x, location.y, 1.0)
local size = cc.Director:getInstance():getWinSize()
nearP = self._camera:unproject(size, nearP, nearP)
farP = self._camera:unproject(size, farP, farP)
local dir = cc.vec3sub(farP, nearP)
dir = cc.vec3normalize(dir)
local collisionPoint = cc.vec3(-999,-999,-999)
local ray = cc.Ray:new(nearP, dir)
local isInTerrain = true
isInTerrain, collisionPoint = self._terrain:getIntersectionPoint(ray, collisionPoint)
if( not isInTerrain) then
self._player._playerState = PLAER_STATE.IDLE
return
end
local playerPos = self._player:getPosition3D()
dir = cc.vec3sub(collisionPoint, playerPos)
dir.y = 0
dir = cc.vec3normalize(dir)
self._player._headingAngle = -1 * math.acos(-dir.z)
self._player._headingAxis = vec3_cross(dir, cc.vec3(0, 0, -1), self._player._headingAxis)
self._player._targetPos = collisionPoint
-- self._player:forward()
self._player._playerState = PLAER_STATE.FORWARD
end
end
end,cc.Handler.EVENT_TOUCHES_ENDED)
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
local visibleSize = cc.Director:getInstance():getVisibleSize()
self._camera = cc.Camera:createPerspective(60, visibleSize.width/visibleSize.height, 0.1, 200)
self._camera:setCameraFlag(cc.CameraFlag.USER1)
self:addChild(self._camera)
local detailMapR = { _detailMapSrc = "TerrainTest/dirt.jpg", _detailMapSize = 35}
local detailMapG = { _detailMapSrc = "TerrainTest/Grass2.jpg", _detailMapSize = 10}
local detailMapB = { _detailMapSrc = "TerrainTest/road.jpg", _detailMapSize = 35}
local detailMapA = { _detailMapSrc = "TerrainTest/GreenSkin.jpg", _detailMapSize = 20}
local terrainData = { _heightMapSrc = "TerrainTest/heightmap16.jpg", _alphaMapSrc = "TerrainTest/alphamap.png" , _detailMaps = {detailMapR, detailMapG, detailMapB, detailMapA}, _detailMapAmount = 4, _mapHeight = 40.0, _mapScale = 2.0 }
self._terrain = cc.Terrain:create(terrainData,cc.Terrain.CrackFixedType.SKIRT)
self._terrain:setMaxDetailMapAmount(4)
self._terrain:setCameraMask(2)
self._terrain:setDrawWire(false)
self._terrain:setSkirtHeightRatio(3)
self._terrain:setLODDistance(64,128,192)
self._player = Player:create("Sprite3DTest/girl.c3b", self._camera, self._terrain)
self._player:setCameraMask(2)
self._player:setScale(0.08)
self._player:setPositionY(self._terrain:getHeight(self._player:getPositionX(), self._player:getPositionZ()) + PLAYER_HEIGHT)
--add Particle3D for test blend
local rootps = cc.PUParticleSystem3D:create("Particle3D/scripts/mp_torch.pu")
rootps:setCameraMask(cc.CameraFlag.USER1)
rootps:setScale(30.0)
rootps:startParticleSystem()
self._player:addChild(rootps)
--add BillBoard for test blend
local billboard = cc.BillBoard:create("Images/btn-play-normal.png")
billboard:setPosition3D(cc.vec3(0,180,0))
billboard:setCameraMask(cc.CameraFlag.USER1)
self._player:addChild(billboard)
local animation = cc.Animation3D:create("Sprite3DTest/girl.c3b","Take 001")
if nil ~= animation then
local animate = cc.Animate3D:create(animation)
self._player:runAction(cc.RepeatForever:create(animate))
end
local playerPos = self._player:getPosition3D()
self._camera:setPosition3D(cc.vec3add(playerPos, camera_offset))
self._camera:setRotation3D(cc.vec3(-45,0,0))
self:addChild(self._player)
self:addChild(self._terrain)
end
function TerrainWalkThru:title()
return "Player walk around in terrain"
end
function TerrainWalkThru:subtitle()
return "touch to move"
end
function TerrainTest()
local scene = cc.Scene:create()
Helper.createFunctionTable =
{
TerrainSimple.create,
TerrainWalkThru.create,
}
Helper.index = 1
scene:addChild(TerrainSimple.create())
scene:addChild(CreateBackMenuItem())
return scene
end
|
-- a port of LuaFileSystem
-- https://keplerproject.github.io/luafilesystem/manual.html
local fs = _G.fs
local shell = _ENV.shell
local lfs = {
_VERSION = '1.8.0.computercraft'
}
-- lfs.attributes (filepath [, request_name | result_table])
-- Returns a table with the file attributes corresponding to filepath (or nil followed
-- by an error message and a system-dependent error code in case of error). If the second
-- optional argument is given and is a string, then only the value of the named attribute
-- is returned (this use is equivalent to lfs.attributes(filepath)[request_name], but the
-- table is not created and only one attribute is retrieved from the O.S.). if a table is
-- passed as the second argument, it (result_table) is filled with attributes and returned
-- instead of a new table. The attributes are described as follows; attribute mode is a
-- string, all the others are numbers, and the time related attributes use the same time
-- reference of os.time:
function lfs.attributes(path, request_name)
path = shell.resolve(path)
local s, fsattr = pcall(fs.attributes, path)
if not s then
return nil, fsattr, 1
end
local attributes = type(request_name) == 'table' and request_name or { }
-- on Unix systems, this represents the device that the inode resides on.
-- On Windows systems, represents the drive number of the disk containing the file
attributes.dev = fs.getDrive(path)
-- on Unix systems, this represents the inode number.
-- On Windows systems this has no meaning
attributes.ino = nil
--string representing the associated protection mode
-- (the values could be file, directory, link, socket, named pipe,
-- char device, block device or other)
attributes.mode = fsattr.isDir and 'directory' or 'file'
-- number of hard links to the file
attributes.nlink = 0
-- user-id of owner (Unix only, always 0 on Windows)
attributes.uid = 0
-- group-id of owner (Unix only, always 0 on Windows)
attributes.gid = 0
-- on Unix systems, represents the device type, for special file inodes.
-- On Windows systems represents the same as dev
attributes.rdev = attributes.dev
-- time of last access
attributes.access = fsattr.modification
-- time of last data modification
attributes.modification = fsattr.modification
-- time of last file status change
attributes.change = fsattr.modification
-- file size, in bytes
attributes.size = fsattr.size
-- file permissions string
local perm = (fs.isDir or fs.isReadOnly(path)) and 'r-x' or 'rwx'
attributes.permissions = perm .. perm .. perm
-- block allocated for file; (Unix only)
attributes.blocks = nil
-- optimal file system I/O blocksize; (Unix only)
attributes.blksize = nil
return type(request_name) ~= 'string' and attributes or attributes[request_name]
end
-- lfs.chdir (path)
-- Changes the current working directory to the given path.
-- Returns true in case of success or nil plus an error string.
function lfs.chdir(path)
path = shell.resolve(path)
if fs.isDir(path) then
shell.setDir(path)
return true
end
return nil, path .. ': No such directory'
end
-- lfs.currentdir ()
-- Returns a string with the current working directory or nil plus an error string.
function lfs.currentdir()
return '/' .. shell.dir()
end
-- iter, dir_obj = lfs.dir (path)
-- Lua iterator over the entries of a given directory.
-- Each time the iterator is called with dir_obj it returns a directory
-- entry's name as a string, or nil if there are no more entries.
-- You can also iterate by calling dir_obj:next(), and explicitly close the
-- directory before the iteration finished with dir_obj:close().
-- Raises an error if path is not a directory.
function lfs.dir(path)
path = shell.resolve(path)
local set = fs.list(path)
local iter = function()
local key, value = next(set)
set[key or false] = nil
return value
end
return iter, {
valid = true,
closed = false,
next = function(self)
if not self.valid then
error('file iterator invalid')
end
local n = iter()
if not n then
self.valid = false
end
return n
end,
close = function(self)
if self.closed then
error('file iterator invalid')
end
self.closed = true
self.valid = false
end,
}
end
-- lfs.link (old, new[, symlink])
-- Creates a link. The first argument is the object to link to and the second is the
-- name of the link. If the optional third argument is true, the link will by a symbolic
-- link (by default, a hard link is created).
function lfs.link(old, new, symlink)
if not symlink then
return false
end
-- hard links are not supported in vfs :(
old = shell.resolve(old)
new = shell.resolve(new)
return not not fs.mount(new, 'linkfs', old)
end
-- lfs.mkdir (dirname)
-- Creates a new directory. The argument is the name of the new directory.
-- Returns true in case of success or nil, an error message and a system-dependent
-- error code in case of error.
function lfs.mkdir(dirname)
dirname = shell.resolve(dirname)
if fs.exists(fs.getDir(dirname)) then
fs.makeDir(dirname)
if fs.isDir(dirname) then
return true
end
end
return nil, dirname .. ': Unable to create directory', 1
end
-- lfs.rmdir (dirname)
-- Removes an existing directory. The argument is the name of the directory.
-- Returns true in case of success or nil, an error message and a system-dependent
-- error code in case of error.
function lfs.rmdir(dirname)
dirname = shell.resolve(dirname)
if not fs.exists(dirname) or not fs.isDir(dirname) then
return false, dirname .. ': Not a directory', 1
end
pcall(fs.delete, dirname)
return not fs.exists(dirname) or false, dirname .. ': Unable to remove directory', 1
end
-- lfs.setmode (file, mode)
-- Sets the writing mode for a file. The mode string can be either "binary" or "text".
-- Returns true followed the previous mode string for the file, or nil followed by an
-- error string in case of errors. On non-Windows platforms, where the two modes are
-- identical, setting the mode has no effect, and the mode is always returned as binary.
function lfs.setmode(file)
if tostring(file) == 'file (closed)' then
error('closed file')
end
return true, 'binary'
end
-- lfs.symlinkattributes (filepath [, request_name])
-- Identical to lfs.attributes except that it obtains information about the link itself
-- (not the file it refers to). It also adds a target field, containing the file name that
-- the symlink points to. On Windows this function does not yet support links, and is
-- identical to lfs.attributes.
function lfs.symlinkattributes(filepath, request_name)
filepath = shell.resolve(filepath)
local target = fs.resolve(filepath)
local attribs = lfs.attributes('/' .. target)
if filepath ~= target then
attribs.target = '/' .. target
attribs.mode = 'link'
end
return request_name and attribs[request_name] or attribs
end
-- lfs.touch (filepath [, atime [, mtime]])
-- Set access and modification times of a file. This function is a bind to utime function.
-- The first argument is the filename, the second argument (atime) is the access time, and
-- the third argument (mtime) is the modification time. Both times are provided in seconds
-- (which should be generated with Lua standard function os.time). If the modification time
-- is omitted, the access time provided is used; if both times are omitted, the current time
-- is used.
-- Returns true in case of success or nil, an error message and a system-dependent error
-- code in case of error.
function lfs.touch(filename, atime, mtime)
mtime = mtime or atime
filename = shell.resolve(filename)
if atime or mtime then
error('setting access/modification time is not supported')
end
-- cc does not suport setting atime/mtime
-- error('lfs.touch not supported')
if not fs.exists(filename) then
local f = fs.open(filename, 'w')
if f then
f.close()
end
end
end
return lfs
|
--[[
-- levelscripts.lua
-- contains scripts which indicate behavior on objects etc. on a per-level base
--
--]]--
local scripts = {bossspawned = 0}
local creatureSpecs = {
spider = { size=32},
goblin = { size=40},
colossus = { size=64},
boss = { size=128, spawned = false}
}
function shop(key, character, game)
if nil ~= character.area and character.area["Shop"] then
print ("shop transaction")
if key == "1" and
character.loot >= game.shop.attack
then
character.attack.damage = character.attack.damage + 0.5
character.loot = character.loot - game.shop.attack
end
if key == "2" and
character.loot >= game.shop.range
then
character.attack.range = character.attack.range + 0.5
character.loot = character.loot - game.shop.range
end
if key == "3" and
character.loot >= game.shop.speed
then
character.speed = character.speed + 0.5
character.loot = character.loot - game.shop.speed
end
if key == "4" and
character.loot >= game.shop.health
then
character.loot = character.loot - game.shop.health
character.health = character.health + 1
end
end
key = nil
return character, game, key
end
function scripts.default(character, condition, game)
if (game == nil) then
game = _G['game']
end
if condition == "init" then
for key, object in pairs(game.tiledobjects) do
local spawnarea = nil
if object.name == "SpawnArea" then
spawnarea = object
local randomcreature = {"spider", "goblin", "colossus"}
for i = 1, 10, 1 do
local crid = math.random(3)
local spec = creatureSpecs[randomcreature[crid]]
game.createCreature(
spawnarea.x + math.random(spawnarea.width),
spawnarea.y + math.random(spawnarea.height),
math.pi * i/30,
spec.size, 5*crid,
randomcreature[crid])
-- game.createCreature(400, math.random(600), math.pi * i/30, math.random(10, 30), math.random(5, 60))
end
end
end
table.insert(game.inputScripts, shop)
else
if (nil ~= character.area) then
-- print ("in script. Area: " .. character.area)
end
--- check if player is in area
for i ,to in ipairs(game.tiledobjects) do
local temparea = game.getCharacterObjectArea(character, to)
if nil~= temparea then character.area[temparea] = true end
if character.area["WayDown"] then
--Todo: go to next level
game.levels.next()
if nil == game.levels.currentlevel then break end
character, game = game.loadLevelByIndex(game.levels.index, character)
break
end
if character.area["Shop"] then
game = game.inShop()
end
end
end
return character, game
end
function scripts.level2(character, condition, game)
love.graphics.print("level 2", 960/2, 300)
for i ,to in ipairs(game.tiledobjects) do
local temparea = game.getCharacterObjectArea(character, to)
if nil ~= temparea then character.area[temparea] = true end
if character.area["Treasure"] and condition =="init" then
for i = 1, 10 do
game.createLoot(to.x + math.random(to.width), to.y + math.random(to.height))
end
end
if character.area["WayDown"] then
--Todo: go to next level
game.levels.next()
if nil == game.levels.currentlevel then break end
character, game = game.loadLevelByIndex(game.levels.index, character)
break
end
end
return character, game
end
function scripts.bosslevel(character, condition, game)
character, game = scripts.default(character, condition, game)
if condition == "init" then
TiledMap_SetLayerInvisByName("Hidden")
TiledMap_SetLayerInvisByName("Hidden2")
if nil ~= game.music.default then
game.music.default:stop();
end
if nil ~= game.music.battle then
game.music.battle:play();
end
--table.insert(game.inputScripts, shop)
else
if nil ~= character.area and character.area["ItemRoom"] then
--love.graphics.print (character.area, 700, 10)
end
for i, to in ipairs(game.tiledobjects) do
--print(to.name)
local temparea = game.getCharacterObjectArea(character, to)
-- if nil ~= temparea then character.area[temparea] = true
if character.area["ItemRoom"] then
love.graphics.print ("Found Secret Area!", 700, 10)
if nil == scripts.chestlooted then
TiledMap_SetLayerVisibleByName("Hidden")
end
TiledMap_SetLayerVisibleByName("Hidden2")
end
if character.area["Chest"] then
-- give money
if nil ~= to.properties then
for j, prop in ipairs(to.properties) do
if prop.name == "loot" then
character.loot = character.loot + prop.value
prop.value = 0
scripts.chestlooted = true
end
end
end
--to.loot = 0
TiledMap_SetLayerInvisByName("Hidden")
end
if to.name == "BossSpawn" then
if scripts.bossspawned == 0 then
local spawnarea = to
love.graphics.print("boss!", to.x, game.adjustY(to.y))
game.createCreature(
spawnarea.x,
spawnarea.y,
math.pi * i/30,
creatureSpecs["boss"].size, 100,
"colossus")
scripts.bossspawned = 1
end
end
--[[if character.area == "Shop" then
game.inShop()
end
]]--
if (game.scripts.creatureSlain == nil) then
game.scripts.creatureSlain = function(creature)
for i = 0, 10, 1 do
game.createLoot(creature.x + math.random(creature.size), creature.y + math.random(creature.size))
end
end
end
--clear on exit
if character.area["WayDown"] then
game.scripts.creatureSlain =nil
game.scripts.bossspawned = 0
game.scripts.chestlooted = nil
--standard snippet
game.levels.next()
if nil == game.levels.currentlevel then break end
character, game = game.loadLevelByIndex(game.levels.index, character)
break
end
end
end
return character, game
end
return scripts
|
if not modules then modules = { } end modules ['mtx-pdf'] = {
version = 1.001,
comment = "companion to mtxrun.lua",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
local tonumber = tonumber
local format, gmatch = string.format, string.gmatch
local utfchar = utf.char
local concat = table.concat
local setmetatableindex, sortedhash, sortedkeys = table.setmetatableindex, table.sortedhash, table.sortedkeys
local helpinfo = [[
<?xml version="1.0"?>
<application>
<metadata>
<entry name="name">mtx-pdf</entry>
<entry name="detail">ConTeXt PDF Helpers</entry>
<entry name="version">0.10</entry>
</metadata>
<flags>
<category name="basic">
<subcategory>
<flag name="info"><short>show some info about the given file</short></flag>
<flag name="metadata"><short>show metadata xml blob</short></flag>
<flag name="fonts"><short>show used fonts (<ref name="detail)"/></short></flag>
<flag name="linearize"><short>linearize given file</short></flag>
</subcategory>
</category>
</flags>
</application>
]]
local application = logs.application {
name = "mtx-pdf",
banner = "ConTeXt PDF Helpers 0.10",
helpinfo = helpinfo,
}
local report = application.report
dofile(resolvers.findfile("lpdf-epd.lua","tex"))
scripts = scripts or { }
scripts.pdf = scripts.pdf or { }
local function loadpdffile(filename)
if not filename or filename == "" then
report("no filename given")
elseif not lfs.isfile(filename) then
report("unknown file '%s'",filename)
else
local pdffile = lpdf.epdf.load(filename)
if pdffile then
return pdffile
else
report("no valid pdf file '%s'",filename)
end
end
end
function scripts.pdf.info(filename)
local pdffile = loadpdffile(filename)
if pdffile then
local catalog = pdffile.Catalog
local info = pdffile.Info
local pages = pdffile.pages
local nofpages = pages.n -- no # yet. will be in 5.2
report("filename > %s",filename)
report("pdf version > %s",catalog.Version)
report("number of pages > %s",nofpages)
report("title > %s",info.Title)
report("creator > %s",info.Creator)
report("producer > %s",info.Producer)
report("creation date > %s",info.CreationDate)
report("modification date > %s",info.ModDate)
local width, height, start
for i=1, nofpages do
local page = pages[i]
local bbox = page.CropBox or page.MediaBox
local w, h = bbox[4]-bbox[2],bbox[3]-bbox[1]
if w ~= width or h ~= height then
if start then
report("cropbox > pages: %s-%s, width: %s, height: %s",start,i-1,width,height)
end
width, height, start = w, h, i
end
end
report("cropbox > pages: %s-%s, width: %s, height: %s",start,nofpages,width,height)
end
end
function scripts.pdf.metadata(filename)
local pdffile = loadpdffile(filename)
if pdffile then
local catalog = pdffile.Catalog
local metadata = catalog.Metadata
if metadata then
report("metadata > \n\n%s\n",metadata())
else
report("no metadata")
end
end
end
local function getfonts(pdffile)
local usedfonts = { }
for i=1,pdffile.pages.n do
local page = pdffile.pages[i]
local fontlist = page.Resources.Font
for k, v in next, lpdf.epdf.expand(fontlist) do
usedfonts[k] = lpdf.epdf.expand(v)
end
end
return usedfonts
end
local function getunicodes(font)
local cid = font.ToUnicode
if cid then
cid = cid()
local counts = { }
-- for s in gmatch(cid,"begincodespacerange%s*(.-)%s*endcodespacerange") do
-- for a, b in gmatch(s,"<([^>]+)>%s+<([^>]+)>") do
-- print(a,b)
-- end
-- end
setmetatableindex(counts, function(t,k) t[k] = 0 return 0 end)
for s in gmatch(cid,"beginbfrange%s*(.-)%s*endbfrange") do
for first, last, offset in gmatch(s,"<([^>]+)>%s+<([^>]+)>%s+<([^>]+)>") do
first = tonumber(first,16)
last = tonumber(last,16)
offset = tonumber(offset,16)
offset = offset - first
for i=first,last do
local c = i + offset
counts[c] = counts[c] + 1
end
end
end
for s in gmatch(cid,"beginbfchar%s*(.-)%s*endbfchar") do
for old, new in gmatch(s,"<([^>]+)>%s+<([^>]+)>") do
for n in gmatch(new,"....") do
local c = tonumber(n,16)
counts[c] = counts[c] + 1
end
end
end
return counts
end
end
function scripts.pdf.fonts(filename)
local pdffile = loadpdffile(filename)
if pdffile then
local usedfonts = getfonts(pdffile)
local found = { }
for k, v in table.sortedhash(usedfonts) do
local counts = getunicodes(v)
local codes = { }
local chars = { }
local freqs = { }
if counts then
codes = sortedkeys(counts)
for i=1,#codes do
local k = codes[i]
local c = utfchar(k)
chars[i] = c
freqs[i] = format("U+%05X %s %s",k,counts[k] > 1 and "+" or " ", c)
end
for i=1,#codes do
codes[i] = format("U+%05X",codes[i])
end
end
found[k] = {
basefont = v.BaseFont or "no basefont",
encoding = v.Encoding or "no encoding",
subtype = v.Subtype or "no subtype",
unicode = v.ToUnicode and "unicode" or "no unicode",
chars = chars,
codes = codes,
freqs = freqs,
}
end
if environment.argument("detail") then
for k, v in sortedhash(found) do
report("id : %s",k)
report("basefont : %s",v.basefont)
report("encoding : %s",v.encoding)
report("subtype : %s",v.subtype)
report("unicode : %s",v.unicode)
report("characters : %s", concat(v.chars," "))
report("codepoints : %s", concat(v.codes," "))
report("")
end
else
local results = { { "id", "basefont", "encoding", "subtype", "unicode", "characters" } }
for k, v in sortedhash(found) do
results[#results+1] = { k, v.basefont, v.encoding, v.subtype, v.unicode, concat(v.chars," ") }
end
utilities.formatters.formatcolumns(results)
report(results[1])
report("")
for i=2,#results do
report(results[i])
end
report("")
end
end
end
-- this is a quick hack ... proof of concept .. will change (derived from luigi's example) ...
-- i will make a ctx wrapper
local qpdf
function scripts.pdf.linearize(filename)
qpdf = qpdf or swiglib("qpdf.core")
local oldfile = filename or environment.files[1]
if not oldfile then
return
end
file.addsuffix(oldfile,"pdf")
if not lfs.isfile(oldfile) then
return
end
local newfile = environment.files[2]
if not newfile or file.removesuffix(oldfile) == file.removesuffix(newfile)then
newfile = file.addsuffix(file.removesuffix(oldfile) .. "-linearized","pdf")
end
local password = environment.arguments.password
local instance = qpdf.qpdf_init()
if bit32.band(qpdf.qpdf_read(instance,oldfile,password),qpdf.QPDF_ERRORS) ~= 0 then
report("unable to open input file")
elseif bit32.band(qpdf.qpdf_init_write(instance,newfile),qpdf.QPDF_ERRORS) ~= 0 then
report("unable to open output file")
else
report("linearizing %a into %a",oldfile,newfile)
qpdf.qpdf_set_static_ID(instance,qpdf.QPDF_TRUE)
qpdf.qpdf_set_linearization(instance,qpdf.QPDF_TRUE)
qpdf.qpdf_write(instance)
end
while qpdf.qpdf_more_warnings(instance) ~= 0 do
report("warning: %s",qpdf.qpdf_get_error_full_text(instance,qpdf.qpdf_next_warning(qpdf)))
end
if qpdf.qpdf_has_error(instance) ~= 0 then
report("error: %s",qpdf.qpdf_get_error_full_text(instance,qpdf.qpdf_get_error(qpdf)))
end
qpdf.qpdf_cleanup_p(instance)
end
-- scripts.pdf.info("e:/tmp/oeps.pdf")
-- scripts.pdf.metadata("e:/tmp/oeps.pdf")
-- scripts.pdf.fonts("e:/tmp/oeps.pdf")
-- scripts.pdf.linearize("e:/tmp/oeps.pdf")
local filename = environment.files[1] or ""
if filename == "" then
application.help()
elseif environment.argument("info") then
scripts.pdf.info(filename)
elseif environment.argument("metadata") then
scripts.pdf.metadata(filename)
elseif environment.argument("fonts") then
scripts.pdf.fonts(filename)
elseif environment.argument("linearize") then
scripts.pdf.linearize(filename)
elseif environment.argument("exporthelp") then
application.export(environment.argument("exporthelp"),filename)
else
application.help()
end
-- a variant on an experiment by hartmut
--~ function downloadlinks(filename)
--~ local document = lpdf.epdf.load(filename)
--~ if document then
--~ local pages = document.pages
--~ for p = 1,#pages do
--~ local annotations = pages[p].Annots
--~ if annotations then
--~ for a=1,#annotations do
--~ local annotation = annotations[a]
--~ local uri = annotation.Subtype == "Link" and annotation.A and annotation.A.URI
--~ if uri and string.find(uri,"^http") then
--~ os.execute("wget " .. uri)
--~ end
--~ end
--~ end
--~ end
--~ end
--~ end
|
--Diablo 3 Resource Globe
function Start()
scene=Scene()
scene:CreateComponent("Octree")
cameraNode = scene:CreateChild("Camera")
local camera=cameraNode:CreateComponent("Camera")
cameraNode.position = Vector3(0.0, 5.0, 0.0)
local viewport = Viewport:new(scene, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
camera:SetOrthographic(true)
camera:SetOrthoSize(100)
cameraNode:LookAt(Vector3(0,0,0), Vector3(0,1,0))
local planeNode = scene:CreateChild("Plane")
planeNode.scale = Vector3(100.0, 1.0, 100.0)
local planeObject = planeNode:CreateComponent("StaticModel")
planeObject.model = cache:GetResource("Model", "Models/health.mdl")
planeObject.material = cache:GetResource("Material", "Materials/health.xml")
planeNode = scene:CreateChild("Plane")
planeNode.scale = Vector3(100.0, 1.0, 100.0)
local planeObject = planeNode:CreateComponent("StaticModel")
planeObject.model = cache:GetResource("Model", "Models/mana.mdl")
planeObject.material = cache:GetResource("Material", "Materials/mana.xml")
--mat=cache:GetResource("Material", "Materials/resourcebubble.xml")
--mat:SetShaderParameter("Level", Variant(0.5))
health=cache:GetResource("Material", "Materials/health.xml")
mana=cache:GetResource("Material", "Materials/mana.xml")
level=0.5
hlevel=0.5
dir=1
hdir=1
SubscribeToEvent("Update", "HandleUpdate")
SubscribeToEvent("KeyDown", "HandleKeyDown")
input.mouseVisible=true
end
function Stop()
end
function Update(dt)
level=level+0.1*dt*dir
if level>1 then dir=-1
elseif level<0 then dir=1
end
hlevel=hlevel+0.18*dt*hdir
if hlevel>1 then hdir=-1
elseif hlevel<0 then hdir=1
end
print(level)
health:SetShaderParameter("Level", Variant(hlevel))
mana:SetShaderParameter("Level", Variant(1-level))
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
Update(timeStep)
end
function HandleKeyDown(eventType, eventData)
local key = eventData["Key"]:Get()
local vm=VariantMap()
-- Close console (if open) or exit when ESC is pressed
if key==KEY_P then
local t=os.date("*t")
local filename="screen_"..tostring(t.year).."_"..tostring(t.month).."_"..tostring(t.day).."_"..tostring(t.hour).."_"..tostring(t.min).."_"..tostring(t.sec)..".png"
local img=Image()
graphics:TakeScreenShot(img)
img:SavePNG(filename)
return
elseif key == KEY_ESCAPE then
engine:Exit()
end
end
|
return Device {
strManufacturer = "TeenyUSB",
strProduct = "TeenyUSB Composite DEMO",
strSerial = "TUSB123456",
idVendor = 0x0483,
idProduct = 0x0011,
prefix = "COMP",
Config {
USB_HID{
ReadEp = EndPoint(IN(2), Interrupt, 16),
WriteEp = EndPoint(OUT(2), Interrupt, 16),
report = HID_InOut(16),
},
CDC_ACM{
EndPoint(IN(5), Interrupt, 16),
EndPoint(IN(1), BulkDouble, 32),
EndPoint(OUT(1), BulkDouble, 32),
},
Interface{
WCID=WinUSB,
strInterface = "TeenyUSB WinUSB",
GUID="{1D4B2365-4749-48EA-B38A-7C6FDDDD7E26}",
EndPoint(IN(3), BulkDouble, 32),
EndPoint(OUT(3), BulkDouble, 32),
},
Interface{
bInterfaceClass = 0x08, -- MSC
bInterfaceSubClass = 0x06, -- SCSI
bInterfaceProtocol = 0x50, -- BOT
EndPoint(IN(4), BulkDouble, 64),
EndPoint(OUT(4), BulkDouble, 64),
},
}
}
|
local EntityTypes = {}
EntityTypes.GUI = "gui"
EntityTypes.PLAYER = "player"
EntityTypes.BULLET = "bullet"
EntityTypes.BOXY = "boxy"
EntityTypes.DEATH_WALL = "death wall"
EntityTypes.BOUNCER = "bouncer"
EntityTypes.SHIELD = "shield"
EntityTypes.BOUNCER_SWORD = "bouncer sword"
return EntityTypes
|
---------------------------------------------------------------------------
--declaring addon stuff----------------------------------------------------
callTarget = LibStub("AceAddon-3.0"):NewAddon("callTarget", "AceComm-3.0", "LibNameplateRegistry-1.0");
---------------------------------------------------------------------------
--globals
target = nil
lasttarget = nil
lastNameplate = nil
lastNameplate2 = nil
markernumber = nil
lastmarkernumber = nil
--slash commands
SLASH_CT1 = "/calltarget"
SlashCmdList["CT"] = function(msg)
if msg == '2' then
setTarget("2")
else
setTarget("1")
end
end
function callTarget:OnInitialize()
self:RegisterComm("14ae3c00985a1a89");
end
function callTarget:OnEnable()
-- Subscribe to callbacks
self:LNR_RegisterCallback("LNR_ON_NEW_PLATE");
self:LNR_RegisterCallback("LNR_ON_RECYCLE_PLATE");
end
function callTarget:OnDisable()
-- Unsubscribe to callbacks
self:LNR_UnregisterAllCallbacks();
end
--call target
function setTarget(markernumber)
if UnitExists("target") then
lasttarget = target
target = UnitGUID("target")
if target == lasttarget then
removemarker(markernumber)
else
target = target .. markernumber
if IsInInstance() then
callTarget:SendCommMessage("14ae3c00985a1a89", target, "INSTANCE_CHAT") --broadcast the selected target
else
callTarget:SendCommMessage("14ae3c00985a1a89", target, "RAID") --broadcast the selected target
end
end
elseif lastNameplate then
removemarker(markernumber)
end
end
-- remove marker
function removemarker(markernumber)
if IsInInstance() then
callTarget:SendCommMessage("14ae3c00985a1a89", "0" .. markernumber, "INSTANCE_CHAT") --broadcast clear
else
callTarget:SendCommMessage("14ae3c00985a1a89", "0" .. markernumber, "RAID") --broadcast clear
end
end
--put the marker on target's nameplate
function callTarget:LNR_ON_NEW_PLATE(eventname, plateFrame, plateData)
if plateData then
if target == plateData.GUID then
if not plateFrame.myIndicator then
plateFrame.myIndicator = plateFrame:CreateTexture(nil, "OVERLAY")
plateFrame.myIndicator:SetSize(60,60)
plateFrame.myIndicator:SetPoint("TOP", 0, 40)
end
if lastmarkernumber ~= markernumber then
if markernumber == "1" then
plateFrame.myIndicator:SetTexture("Interface\\AddOns\\CallTarget\\marker.tga")
else
plateFrame.myIndicator:SetTexture("Interface\\AddOns\\CallTarget\\marker2.tga")
end
plateFrame.myIndicator:Show()
else
plateFrame.myIndicator:Show()
end
if markernumber == "1" then
if lastNameplate and lastNameplate ~=plateFrame then
lastNameplate.myIndicator:Hide()
end
lastNameplate = plateFrame
else
if lastNameplate2 and lastNameplate2 ~=plateFrame then
lastNameplate2.myIndicator:Hide()
end
lastNameplate2 = plateFrame
end
end
elseif markernumber == "2" then
lastNameplate2.myIndicator:Hide()
else
lastNameplate.myIndicator:Hide()
end
end
function callTarget:LNR_ON_RECYCLE_PLATE(eventname, plateFrame, plateData)
if plateFrame.myIndicator then
plateFrame.myIndicator:Hide()
end
end
-- process the broadcasted message
function callTarget:OnCommReceived(prefix, message, distribution, sender)
target = message:sub(0,string.len(message)-1)
markernumber = string.sub(message, -1)
plateFrame, plateData = callTarget:GetPlateByGUID(target)
callTarget:LNR_ON_NEW_PLATE( _, plateFrame, plateData)
end
|
-- require('lib')
require('config')
-- require('settings')
-- require('screen')
require('reload')
require('window')
require('layout')
-- require('util')
require('shortcut')
|
return {'node','nodeloos','noden','nodig','nodigen','nodiger','nodeloze','nodelozer','nodigde','nodigden','nodige','nodigst','nodigt','nodigers','nodeloost'}
|
local shared = require('shared')
local table = require('table')
local client = shared.get('packet_service', 'packets')
local get_last = function(_, path)
return get_last(path)
end
local get_lasts = function(_, path)
return get_lasts(path)
end
local make_event = function(_, path)
return make_event(path)
end
local inject = function(_, path, values)
inject(path, values)
end
local block = function(_)
block()
end
local update = function(_, p)
update(p)
end
local registry = {}
local fns = {}
local register_path = function(path, fn)
local events = registry[path]
if not events then
events = {}
registry[path] = events
end
local event = client:call(make_event, path)
events[fn] = event
event:register(fn)
end
fns.register = function(t, fn)
register_path(t.path, fn)
end
fns.unregister = function(t, fn)
registry[t.path][fn] = nil
end
fns.register_init = function(t, init_table)
local paths = {}
local path_count = 0
for indices, fn in pairs(init_table) do
local path = t.path .. '/' .. table.concat(indices, '/')
register_path(path, fn)
path_count = path_count + 1
paths[path_count] = { path = path, fn = fn }
end
local lasts = {}
local lasts_count = 0
for i = 1, #paths do
local path = paths[i]
local lasts_path = client:call(get_lasts, path.path)
for j = 1, #lasts_path do
local entry = lasts_path[j]
local packet = entry.packet
local info = entry.info
lasts_count = lasts_count + 1
lasts[lasts_count] = { packet = packet, info = info, fn = path.fn , timestamp = info.timestamp }
end
end
table.sort(lasts, function(l1, l2)
return l1.timestamp < l2.timestamp
end)
for i = 1, #lasts do
local last = lasts[i]
last.fn(last.packet, last.info)
end
end
fns.inject = function(t, values)
client:call(inject, t.path, values)
end
local make_table = function(path, allow_injection)
return {
path = path,
register = fns.register,
unregister = fns.unregister,
register_init = fns.register_init,
inject = allow_injection and fns.inject or nil,
}
end
local packet_meta
packet_meta = {
__index = function(t, k)
if k == 'last' then
return client:call(get_last, t.path)
end
return setmetatable(make_table(t.path .. '/' .. tostring(k), true), packet_meta)
end,
}
local packets = make_table('', false)
packets.incoming = setmetatable(make_table('/incoming', false), packet_meta)
packets.outgoing = setmetatable(make_table('/outgoing', false), packet_meta)
packets.block = function()
client:call(block)
end
packets.update = function(p)
client:call(update, p)
end
return packets
--[[
Copyright © 2018, Windower Dev Team
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Windower Dev Team nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE WINDOWER DEV TEAM BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
|
--[[ Copyright (c) 2017 David-John Miller AKA Anoyomouse
* Part of the Warehousing mod
*
* See License.txt in the project directory for license information.
--]]
data:extend({
{ -- Basic Warehouse
type = "recipe",
name = "warehouse-basic",
enabled = "false",
ingredients =
{
{ "steel-plate", 200 },
{ "stone-brick", 40 },
{ "iron-stick", 85 },
},
energy_required = 30,
result = "warehouse-basic",
},
{ -- Passive Provider Warehouse
type = "recipe",
name = "warehouse-passive-provider",
enabled = "false",
ingredients =
{
{ "warehouse-basic", 1 },
{ "logistic-chest-passive-provider", 1 },
{ "steel-plate", 10 },
{ "iron-stick", 15 },
},
energy_required = 5,
result = "warehouse-passive-provider",
},
{ -- Storage Warehouse
type = "recipe",
name = "warehouse-storage",
enabled = "false",
ingredients =
{
{ "warehouse-basic", 1 },
{ "logistic-chest-storage", 1 },
{ "steel-plate", 10 },
{ "iron-stick", 15 },
},
energy_required = 5,
result = "warehouse-storage",
},
{ -- Active Provider Warehouse
type = "recipe",
name = "warehouse-active-provider",
enabled = "false",
ingredients =
{
{ "warehouse-basic", 1 },
{ "logistic-chest-active-provider", 1 },
{ "steel-plate", 10 },
{ "iron-stick", 15 },
},
energy_required = 5,
result = "warehouse-active-provider",
},
{ -- Requester Warehouse
type = "recipe",
name = "warehouse-requester",
enabled = "false",
ingredients =
{
{ "warehouse-basic", 1 },
{ "logistic-chest-requester", 1 },
{ "steel-plate", 10 },
{ "iron-stick", 15 },
},
energy_required = 5,
result = "warehouse-requester",
},
{ -- Buffer Warehouse
type = "recipe",
name = "warehouse-buffer",
enabled = "false",
ingredients =
{
{ "warehouse-basic", 1 },
{ "logistic-chest-buffer", 1 },
{ "steel-plate", 10 },
{ "iron-stick", 15 },
},
energy_required = 5,
result = "warehouse-buffer",
},
{ -- Basic Storehouse
type = "recipe",
name = "storehouse-basic",
enabled = "false",
ingredients =
{
{ "steel-plate", 50 },
{ "stone-brick", 10 },
{ "iron-stick", 16 },
},
energy_required = 30,
result = "storehouse-basic",
},
{ -- Passive Provider Storehouse
type = "recipe",
name = "storehouse-passive-provider",
enabled = "false",
ingredients =
{
{ "storehouse-basic", 1 },
{ "logistic-chest-passive-provider", 1 },
{ "iron-stick", 4 },
},
energy_required = 5,
result = "storehouse-passive-provider",
},
{ -- Storage Storehouse
type = "recipe",
name = "storehouse-storage",
enabled = "false",
ingredients =
{
{ "storehouse-basic", 1 },
{ "logistic-chest-storage", 1 },
{ "iron-stick", 4 },
},
energy_required = 5,
result = "storehouse-storage",
},
{ -- Active Provider Storehouse
type = "recipe",
name = "storehouse-active-provider",
enabled = "false",
ingredients =
{
{ "storehouse-basic", 1 },
{ "logistic-chest-active-provider", 1 },
{ "iron-stick", 4 },
},
energy_required = 5,
result = "storehouse-active-provider",
},
{ -- Requester Storehouse
type = "recipe",
name = "storehouse-requester",
enabled = "false",
ingredients =
{
{ "storehouse-basic", 1 },
{ "logistic-chest-requester", 1 },
{ "iron-stick", 4 },
},
energy_required = 5,
result = "storehouse-requester",
},
{ -- Buffer Storehouse
type = "recipe",
name = "storehouse-buffer",
enabled = "false",
ingredients =
{
{ "storehouse-basic", 1 },
{ "logistic-chest-buffer", 1 },
{ "iron-stick", 4 },
},
energy_required = 5,
result = "storehouse-buffer",
},
})
|
local nk = require("nakama")
local inventory = require("inventory")
local F = {}
F.cast_lure = function(user_id, avatar)
-- eventually lookup their inventory, check up fishing pole etc
return {
timeDelay = math.random(5, 20),
weight = math.random(5, 30)
}
end
local function cast_lure(context, payload)
local lure_call = F.cast_lure(context.user_id, payload)
return nk.json_encode(lure_call)
end
nk.register_rpc(cast_lure, "fishing.cast_lure")
return F
|
-- Loss function for the segmentation mask, L1 loss function used in GAN for implementing baselines
-- By: Kiana Ehsani
local SeGANCriterion, parent = torch.class('nn.SeGANCriterion', 'nn.Criterion')
function SeGANCriterion:__init(nchannel, weights, sizeAverage)
parent.__init(self)
if weights == nil then
print('weights are not defined')
return nil
end
if nchannel == nil then
print('nchannel is not defined')
return nil
end
self.nchannel = nchannel
if self.nchannel == 3 then
self.weights = weights:repeatTensor(1,self.nchannel,1,1) -- it means we will repeat the channels because the output is three channels
else
self.weights = weights:clone()
end
if opt.nc_output == 1 then
self.norms = opt.norm1C
else --nc_output = 3
self.norms = opt.norm3C
end
if sizeAverage ~= nil then
self.sizeAverage = sizeAverage
else
self.sizeAverage = true
end
end
function convert_them(input, target, weights)
local selfinput = torch.Tensor(#(weights))
selfinput = selfinput:repeatTensor(3,1,1,1,1):zero():cuda()
local selftarget = torch.Tensor(#(weights))
selftarget = selftarget:repeatTensor(3,1,1,1,1):zero():cuda()
for i = 1,3 do
selfinput[i] = input:clone()
selfinput[i][torch.ne(weights, i - 1)] = 0
selftarget[i] = target:clone()
selftarget[i][torch.ne(weights, i - 1)] = 0
end
return selfinput, selftarget
end
function SeGANCriterion:updateOutput(input, target)
self.totalOutput = {}
local res = 0
self.input , self.target = convert_them(input, target, self.weights)
for i = 1, 3 do
input = self.input[i]
target = self.target[i]
self.output_tensor = self.output_tensor or input.new(1)
input.THNN.AbsCriterion_updateOutput(
input:cdata(),
target:cdata(),
self.output_tensor:cdata(),
self.sizeAverage
)
self.output = self.output_tensor[1]
self.totalOutput[i] = self.output
this_weight = opt.weights_loss[i] / self.norms[i]
res = res + this_weight * self.totalOutput[i]
opt.sum[i] = opt.sum[i] + self.output
end
opt.counter = opt.counter + 1
return res
end
function SeGANCriterion:updateGradInput(input, target)
self.totalGrad = torch.Tensor(#input):zero():cuda()
self.input , self.target = convert_them(input, target, self.weights)
for i = 1,3 do
input.THNN.AbsCriterion_updateGradInput(
self.input[i]:cdata(),
self.target[i]:cdata(),
self.gradInput:cdata(),
self.sizeAverage
)
this_weight = opt.weights_loss[i] / self.norms[i]
self.totalGrad = self.totalGrad:add(self.gradInput:mul(this_weight))
end
return self.totalGrad
end
-- local SeGANCriterion, parent = torch.class('nn.SeGANCriterion', 'nn.Criterion')
-- local eps = 1e-12
-- function SeGANCriterion:_init(weights)
-- parent._init(self)
-- if weights then
-- assert(weights:dim() == 1, "weights input should be 1-D Tensor")
-- self.weights = weights
-- end
-- end
-- function SeGANCriterion:updateOutput(input, target)
-- assert(input:nElement() == target:nElement(), "input and target size mismatch")
-- local weights = self.weights
-- local numerator, denom, common
-- if weights ~= nil and target:dim() ~= 1 then
-- weights = self.weights:view(1, target:size(2)):expandAs(target)
-- end
-- -- compute numerator: 2 * |X n Y| ; eps for numeric stability
-- common = torch.eq(input, target) --find logical equivalence between both
-- common:mul(2)
-- numerator = torch.sum(common)
-- -- compute denominator: |X| + |Y|
-- denom = input:nElement() + target:nElement() + eps
-- self.output = numerator/denom
-- return self.output
-- end
-- function SeGANCriterion:updateGradInput(input, target)
-- assert(input:nElement() == target:nElement(), "inputs and target size mismatch")
-- --[[
-- 2 * |X| * |Y|
-- Gradient = ----------------------
-- |X|*(|X| + |Y|)^2
-- ]]
-- local weights = self.weights
-- local gradInput = self.gradInput or input.new()
-- local numerator, denom, den_term2, output
-- gradInput:resizeAs(input)
-- if weights ~= nil and target:dim() ~= 1 then
-- weights = self.weights:view(1, target:size(2)):expandAs(target)
-- end
-- if weights ~= nil then
-- gradInput:cmul(weights)
-- end
-- if self.sizeAverage then
-- gradInput:div(target:nElement())
-- end
-- -- compute 2 * |X| * |Y|
-- numerator = 2 * input:nElement() * target:nElement()
-- -- compute |X|
-- denom = input:nElement()
-- -- compute (|X| + |Y|)
-- den_term2 = input:nElement() + target:nElement()
-- -- compute |X| * (|X| + |Y|)^2
-- denom = denom * (den_term2 * den_term2)
-- -- compute gradients
-- gradInput = numerator / denom
-- self.gradInput = gradInput
-- return self.gradInput
-- end
|
-- Максимальное количество чекпойнтов в дуэли
local DUEL_CHECKPOINTS_COUNT = 15
-- Максимальная длительность дуэли в секундах
local DUEL_DURATION = 300
local activeDuels = {}
local function getVehicleSpawnpoint(vehicle)
if not isElement(vehicle) then
return false
end
local x, y, z = getElementPosition(vehicle)
local rx, ry, rz = getElementRotation(vehicle)
return {x, y, z, rx, ry, rz}
end
function startDuel(player1, player2, bet)
if not isElement(player1) or not isElement(player2) then
outputDebugString("Duel: no player")
return
end
if not player1.vehicle or not player2.vehicle then
outputDebugString("Duel: no vehicle")
return false
end
if player1:getData("dpCore.state") or player2:getData("dpCore.state") then
return
end
if not bet then
outputDebugString("Duel: no bet")
return
end
-- TODO: Проверить расстояние между игроками
-- Генерация случайной трассы
local checkpoints = PathGenerator.generateCheckpointsForPlayer(player1, DUEL_CHECKPOINTS_COUNT)
if not checkpoints then
return false
end
-- Спавны
local spawnpoints = {
getVehicleSpawnpoint(player1.vehicle),
getVehicleSpawnpoint(player2.vehicle)
}
-- Создание карты и настройки
local raceMap = exports.dpRaceManager:createRaceMap(checkpoints, spawnpoints)
if not raceMap then
outputDebugString("No race map")
return false
end
local raceSettings = {
separateDimension = false,
gamemode = "duel",
duration = DUEL_DURATION
}
local race = exports.dpRaceManager:createRace(raceSettings, raceMap)
if not race then
return false
end
-- Добавить игроков в гонку
exports.dpRaceManager:raceAddPlayer(race, player1)
exports.dpRaceManager:raceAddPlayer(race, player2)
race:setData("dpDuels.duelInfo", {
bet = bet
})
setTimer(function ()
exports.dpRaceManager:startRace(race)
end, 3000, 1)
end
addEvent("RaceDuel.finished", false)
addEventHandler("RaceDuel.finished", root, function (playerWinner, timePassed)
local duelInfo = source:getData("dpDuels.duelInfo")
if type(duelInfo) ~= "table" then
return
end
source:setData("dpDuels.duelInfo", true)
if type(duelInfo.bet) ~= "number" then
duelInfo.bet = 0
end
-- Выдача приза победителю
local prize = duelInfo.bet * 2
if isElement(playerWinner) then
exports.dpCore:givePlayerMoney(playerWinner, prize)
end
-- Отображение экрана финиша
local players = exports.dpRaceManager:raceGetAllPlayers(source)
if type(players) ~= "table" then
return
end
for i, player in ipairs(players) do
triggerClientEvent(player, "dpDuels.showWinner", resourceRoot, playerWinner, prize, timePassed)
end
end)
addEventHandler("onResourceStop", resourceRoot, function ()
for i, race in ipairs(getElementsByType("race")) do
if race:getData("dpDuels.duelInfo") then
exports.dpRaceManager:destroyRace(race)
end
end
end)
-- Export
function getNearestCheckpoint(...)
return PathGenerator.getNearestCheckpoint(...)
end
|
--mill flats up to shoulders
--written by Jesse Meade-Clift
--THIS CURRENTLY SUCKS
--would like to require lib and use tool_dia_mazak()
--require broken by load, but lib is already loaded by iup...
--##
z_clearance = 4
feed = 0.05
z_zero = -1.5
depth = 1.5
cutter_dia = 3
cut_depth = 0.06
start_clear = "x"
shoulder = {"x2"}
rectangle = {x1=0, y1=-3.5, x2=25.625, y2=3.5}
safety=0.03
cut_percent = 0.45
--##
cutter_half = cutter_dia/2
cutter_offset = cut_percent*cutter_half
number_cuts = num_cuts(depth, cut_depth)
z_start = (number_cuts - 1)*cut_depth+z_zero
function pass(z, z_return)
local x_primary = true
if (rectangle.x2 - rectangle.x1) < (rectangle.y2 - rectangle.y1) then
x_primary = false
end
G00
end
paths = { xx2=[[]],
xx1=[[]],
xy1=[[]],
xy2=[[]],
yx2=[[]],
yx1=[[]],
yy1=[[]],
yy2=[[]]
}
function passes(z_st, num)
local depth = z_st
for i=1, num do
parallel_clear(rectangle, depth, depth + cut_depth + safety)
depth = depth - cut_depth
end
end
--table values must be in $()s for $ vars. Perhaps the . is getting lost
--this is deprecated
start = {x=rectangle.x1+ cutter_offset,y=rectangle.y1-cutter_half - safety}
--[[This function controls one z level pass of a square machined up to a
shoulder at the largest X value of the square. Starts clear on the X axis,
moves in a right angle fashion.]]
function perpendicular_clear(rect, z, ret)
local sx = rectangle.x1-cutter_half-safety
local sy = rectangle.y2-cutter_offset
G00 Z$ret
for i=1, num_cuts(rect.y2-rect.y1, cutter_dia*cut_percent) do
G00 X$sx Y$sy
G00 Z$z
G01 X$(rect.x2-cutter_half) F$feed
G01 Y$(rect.y2 + cutter_half + safety) F$feed
G00 Z$ret
sy = sy - cutter_dia*cut_percent
end
end
function parallel_clear(rect, z, ret)
local horiz_num = num_cuts(rect.x2-rect.x1 - cutter_half, cutter_dia*cut_percent)
local sx = rectangle.x2 - (horiz_num)*cutter_dia*cut_percent - cutter_half
local sy = rectangle.y1 - cutter_half - safety
G00 Z$ret
for i=1, horiz_num +1 do
G00 X$sx Y$sy
G00 Z$z
G01 Y$(rect.y2 + cutter_half + safety) F$feed
G00 Z$ret
sx = sx + cutter_dia*cut_percent
end
end
G90
G95
G00 X0Y0
G00 Z$z_clearance
passes(z_start, number_cuts)
G00 Z$z_clearance
M99
|
--[[ BPM Library ]]
local bpm = {}
bpm.beats = {}
bpm.time = 0
bpm.bpm = 100
bpm.snap = true
bpm.update = function(dt)
local hitBeats = {}
local beatsHit = false
for k,v in pairs(bpm.beats) do
v.accumulator = v.accumulator + dt
if v.last + v.accumulator > v.last + v.length then
v.last = v.last + v.length
v.accumulator = v.accumulator - v.length
v.hits = v.hits + 1
hitBeats[v.name] = v
beatsHit = true
end
end
if beatsHit then
bpm.beat(hitBeats)
end
bpm.time = bpm.time + dt
end
bpm.beat = function(beats) end
bpm.attach = function(name, beatLength, offset, tag)
local beat = {name=name,beatLength=beatLength,length=60/bpm.bpm * beatLength,accumulator=-60/bpm.bpm * offset,last=0,hits=0,tag=tag}
local attachTime = bpm.time
if bpm.snap then
attachTime = bpm.calculateSnap(bpm.bpm,beatLength,bpm.time)
end
beat.last = attachTime
bpm.beats[name] = beat
end
bpm.detach = function(name)
bpm.beat[name] = nil
end
bpm.calculateSnap = function(bpm, length, time)
return time - time % (bpm * length / 60)
end
bpm.changeBpm = function(newBpm)
if newBpm <= 0 then
newBpm = 0.00
end
for k,v in pairs(bpm.beats) do
local oldLength = v.length
local accumulatorRatio = v.accumulator / oldLength
v.length = 60/newBpm * v.beatLength
v.accumulator = v.length *accumulatorRatio
bpm.bpm = newBpm
end
end
return bpm
|
workspace "NavMeshScene"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
targetdir "../bin/"
language "C++"
includedirs {
"..",
"../Detour/Include",
"../DetourTileCache/Include",
"../Contrib/fastlz",
}
flags {
"C++11",
"StaticRuntime",
}
filter "configurations:Debug"
defines { "_DEBUG" }
flags { "Symbols" }
libdirs { }
filter "configurations:Release"
defines { "NDEBUG" }
libdirs { }
optimize "On"
filter { }
project "NavMeshScene"
kind "StaticLib"
targetname "NavMeshScene"
files {
"../*.h",
"../*.cpp",
"../Detour/**",
"../DetourTileCache/**",
"../Contrib/fastlz/**",
"../aoi/impl/*.h",
"../aoi/*.h",
}
project "example1"
kind "ConsoleApp"
targetname "example1"
libdirs { "../bin" }
links { "NavMeshScene" }
files {
"../example1/*.h",
"../example1/*.cpp",
}
if os.is("windows") then
project "example2"
kind "ConsoleApp"
targetname "example2"
includedirs {
"../example2/Contrib/SDL/include/",
"../example2/Contrib/",
"../example2/DebugUtils/Include/",
"../example2/Recast/Include/",
-- "../example2/Detour/Include/",
"../example2/DetourCrowd/Include/",
-- "../example2/DetourTileCache/Include/",
"../example2/RecastDemo/Include/",
}
libdirs { "../bin" }
links { "NavMeshScene" }
files {
"../example2/**",
}
defines { "WIN32", "_WINDOWS", "_CRT_SECURE_NO_WARNINGS", "_HAS_EXCEPTIONS=0" }
configuration { "linux", "gmake" }
buildoptions {
"`pkg-config --cflags sdl2`",
"`pkg-config --cflags gl`",
"`pkg-config --cflags glu`"
}
linkoptions {
"`pkg-config --libs sdl2`",
"`pkg-config --libs gl`",
"`pkg-config --libs glu`"
}
configuration { "windows" }
includedirs {
"../example2/Contrib/SDL/include",
-- "../example2/Contrib/fastlz",
}
links {
"glu32",
"opengl32",
"SDL2",
"SDL2main",
}
filter { "platforms:x32" }
libdirs { "../example2/Contrib/SDL/lib/x86" }
postbuildcommands {
-- Copy the SDL2 dll to the Bin folder.
'{COPY} "%{wks.location}../example2/Contrib/SDL/lib/x86/SDL2.dll" "%{cfg.targetdir}"'
}
filter { "platforms:x64" }
libdirs { "../example2/Contrib/SDL/lib/x64" }
postbuildcommands {
-- Copy the SDL2 dll to the Bin folder.
'{COPY} "%{wks.location}../example2/Contrib/SDL/lib/x64/SDL2.dll" "%{cfg.targetdir}"'
}
end
project "test1"
kind "ConsoleApp"
targetname "test1"
libdirs { "../bin" }
links { "NavMeshScene" }
files {
"../tests/test1/*.h",
"../tests/test1/*.cpp",
}
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf/protobuf"
module('PvpRoleBrief_pb')
PVPROLEBRIEF = protobuf.Descriptor();
local PVPROLEBRIEF_ROLEID_FIELD = protobuf.FieldDescriptor();
local PVPROLEBRIEF_ROLENAME_FIELD = protobuf.FieldDescriptor();
local PVPROLEBRIEF_ROLELEVEL_FIELD = protobuf.FieldDescriptor();
local PVPROLEBRIEF_ROLEPROFESSION_FIELD = protobuf.FieldDescriptor();
local PVPROLEBRIEF_ROLESERVERID_FIELD = protobuf.FieldDescriptor();
PVPROLEBRIEF_ROLEID_FIELD.name = "roleid"
PVPROLEBRIEF_ROLEID_FIELD.full_name = ".KKSG.PvpRoleBrief.roleid"
PVPROLEBRIEF_ROLEID_FIELD.number = 1
PVPROLEBRIEF_ROLEID_FIELD.index = 0
PVPROLEBRIEF_ROLEID_FIELD.label = 1
PVPROLEBRIEF_ROLEID_FIELD.has_default_value = false
PVPROLEBRIEF_ROLEID_FIELD.default_value = 0
PVPROLEBRIEF_ROLEID_FIELD.type = 4
PVPROLEBRIEF_ROLEID_FIELD.cpp_type = 4
PVPROLEBRIEF_ROLENAME_FIELD.name = "rolename"
PVPROLEBRIEF_ROLENAME_FIELD.full_name = ".KKSG.PvpRoleBrief.rolename"
PVPROLEBRIEF_ROLENAME_FIELD.number = 2
PVPROLEBRIEF_ROLENAME_FIELD.index = 1
PVPROLEBRIEF_ROLENAME_FIELD.label = 1
PVPROLEBRIEF_ROLENAME_FIELD.has_default_value = false
PVPROLEBRIEF_ROLENAME_FIELD.default_value = ""
PVPROLEBRIEF_ROLENAME_FIELD.type = 9
PVPROLEBRIEF_ROLENAME_FIELD.cpp_type = 9
PVPROLEBRIEF_ROLELEVEL_FIELD.name = "rolelevel"
PVPROLEBRIEF_ROLELEVEL_FIELD.full_name = ".KKSG.PvpRoleBrief.rolelevel"
PVPROLEBRIEF_ROLELEVEL_FIELD.number = 3
PVPROLEBRIEF_ROLELEVEL_FIELD.index = 2
PVPROLEBRIEF_ROLELEVEL_FIELD.label = 1
PVPROLEBRIEF_ROLELEVEL_FIELD.has_default_value = false
PVPROLEBRIEF_ROLELEVEL_FIELD.default_value = 0
PVPROLEBRIEF_ROLELEVEL_FIELD.type = 13
PVPROLEBRIEF_ROLELEVEL_FIELD.cpp_type = 3
PVPROLEBRIEF_ROLEPROFESSION_FIELD.name = "roleprofession"
PVPROLEBRIEF_ROLEPROFESSION_FIELD.full_name = ".KKSG.PvpRoleBrief.roleprofession"
PVPROLEBRIEF_ROLEPROFESSION_FIELD.number = 4
PVPROLEBRIEF_ROLEPROFESSION_FIELD.index = 3
PVPROLEBRIEF_ROLEPROFESSION_FIELD.label = 1
PVPROLEBRIEF_ROLEPROFESSION_FIELD.has_default_value = false
PVPROLEBRIEF_ROLEPROFESSION_FIELD.default_value = 0
PVPROLEBRIEF_ROLEPROFESSION_FIELD.type = 13
PVPROLEBRIEF_ROLEPROFESSION_FIELD.cpp_type = 3
PVPROLEBRIEF_ROLESERVERID_FIELD.name = "roleserverid"
PVPROLEBRIEF_ROLESERVERID_FIELD.full_name = ".KKSG.PvpRoleBrief.roleserverid"
PVPROLEBRIEF_ROLESERVERID_FIELD.number = 5
PVPROLEBRIEF_ROLESERVERID_FIELD.index = 4
PVPROLEBRIEF_ROLESERVERID_FIELD.label = 1
PVPROLEBRIEF_ROLESERVERID_FIELD.has_default_value = false
PVPROLEBRIEF_ROLESERVERID_FIELD.default_value = 0
PVPROLEBRIEF_ROLESERVERID_FIELD.type = 13
PVPROLEBRIEF_ROLESERVERID_FIELD.cpp_type = 3
PVPROLEBRIEF.name = "PvpRoleBrief"
PVPROLEBRIEF.full_name = ".KKSG.PvpRoleBrief"
PVPROLEBRIEF.nested_types = {}
PVPROLEBRIEF.enum_types = {}
PVPROLEBRIEF.fields = {PVPROLEBRIEF_ROLEID_FIELD, PVPROLEBRIEF_ROLENAME_FIELD, PVPROLEBRIEF_ROLELEVEL_FIELD, PVPROLEBRIEF_ROLEPROFESSION_FIELD, PVPROLEBRIEF_ROLESERVERID_FIELD}
PVPROLEBRIEF.is_extendable = false
PVPROLEBRIEF.extensions = {}
PvpRoleBrief = protobuf.Message(PVPROLEBRIEF)
|
-- Ext.Require("Stats/Shared/Effects.lua")
Ext.Require("Shared/_InitShared.lua")
SScarID = "ff4dba5a-16e3-420a-aa51-e5c8531b0095"
CustomStatSystem = Mods.LeaderLib.CustomStatSystem
ts = Mods.LeaderLib.Classes.TranslatedString
--- function to retrieve custom stat set through tags
--- Stat tags shall be in the following format : PREFIX_Stat_Value
--- @param character EclCharacter
--- @param tagPrefix string
function RetrieveCharacterCustomStatValue(character, tagPrefix)
local tags = character:GetTags()
local value
for i,tag in pairs(tags) do
if tag:match(tagPrefix) ~= nil then
value = tag:gsub(".*_", "")
end
end
if value ~= nil then
return tonumber(value)
else
return 0
end
end
--- @param character EclCharacter
--- @param tagPrefix string
function ClearCharacterCustomStatTag(character, tagPrefix)
local tags = character:GetTags()
local value
for i,tag in pairs(tags) do
if tag:match(tagPrefix) ~= nil then
ClearTag(character.MyGuid, tag)
end
end
end
---@param str string
function SubstituteString(str, ...)
local args = {...}
local result = str
for k, v in pairs(args) do
if type(v) == "number" then
if v == math.floor(v) then v = math.floor(v) end -- Formatting integers to not show .0
result = result:gsub("%["..tostring(k).."%]", v)
else
result = result:gsub("%["..tostring(k).."%]", v)
end
end
return result
end
|
game:DefineFastFlag("AvatarExperienceOutfitRecommendations", false)
return function()
return game:GetFastFlag("AvatarExperienceOutfitRecommendations")
end
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('XTemplate', {
group = "Infopanel Sections",
id = "ipShuttle",
PlaceObj('XTemplateTemplate', {
'__template', "Infopanel",
'Description', T{7383, --[[XTemplate ipShuttle Description]] "<description>"},
}, {
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelText",
'Margins', box(60, 4, 20, 8),
'Text', T{660271041264, --[[XTemplate ipShuttle Text]] "<CarriedResourceStr>"},
}),
}),
})
|
function love.load()
rcoll = {}
rstrr = "1234567890-=qwertyuiop[]asdfghjkl;'zxcvbnm,./'"
rstrr:gsub(".",function(c) table.insert(rcoll,c) end)
rposs = love.math.random(1, #rcoll)
st = rcoll[rposs]
print(st)
font = love.graphics.getFont()
font:setFilter("nearest")
love.graphics.setFont(font)
end
function love.textinput(inp)
if inp == st then
rposs = love.math.random(1, #rcoll)
st = rcoll[rposs]
print(st)
love.graphics.setBackgroundColor(35, 209, 139)
else
love.graphics.setBackgroundColor(58, 139, 228)
end
end
function love.draw()
love.graphics.print(tostring(st), 350, 100, 0, 15, 15)
end
|
function widget:GetInfo()
return {
name = "Load Own Moving",
desc = "Enables loading of your own units when they're moving",
author = "Niobium",
version = "1.0",
date = "June 18, 2010",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
-------------------------------------------------------------------
-- Globals
-------------------------------------------------------------------
local watchList = {} -- watchList[uID] = tID
local isTransport = {} -- isTransport[uDefID] = UnitDefs[uDefID].isTransport
for uDefID, uDef in pairs(UnitDefs) do
if uDef.isTransport and uDef.canFly then
isTransport[uDefID] = true
end
end
-------------------------------------------------------------------
-- Speedups
-------------------------------------------------------------------
local spGetMyTeamID = Spring.GetMyTeamID
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitCommands = Spring.GetUnitCommands
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spGetUnitSeparation = Spring.GetUnitSeparation
local spGetUnitVelocity = Spring.GetUnitVelocity
local CMD_INSERT = CMD.INSERT
local CMD_LOAD_UNITS = CMD.LOAD_UNITS
local CMD_OPT_ALT = CMD.OPT_ALT
-------------------------------------------------------------------
-- Local functions
-------------------------------------------------------------------
local function GetTransportTarget(uID)
local uCmds = spGetUnitCommands(uID, 1)
if not uCmds then return end
local uCmd = uCmds[1]
if uCmd and uCmd.id == CMD_LOAD_UNITS and #uCmd.params == 1 then
local tID = uCmd.params[1]
if spGetUnitTeam(tID) == spGetMyTeamID() then
return tID
end
end
end
-------------------------------------------------------------------
-- Callins
-------------------------------------------------------------------
function widget:UnitCommand(uID, uDefID, uTeam)
if isTransport[uDefID] and uTeam == spGetMyTeamID() and GetTransportTarget(uID) then
watchList[uID] = true
end
end
function widget:UnitCmdDone(uID, uDefID, uTeam)
widget:UnitCommand(uID, uDefID, uTeam)
end
function widget:GameFrame(n)
-- Limit command rate to 3/sec (Sufficient for coms)
if n % 10 > 0 then return end
for uID, _ in pairs(watchList) do
-- Re-get transports target
local tID = GetTransportTarget(uID)
if tID then
-- Only issue if transport is close
if spGetUnitSeparation(uID, tID, true) < 100 then
-- Only issue if target is moving
local vx, _, vz = spGetUnitVelocity(tID)
if vx ~= 0 or vz ~= 0 then
spGiveOrderToUnit(uID, CMD_INSERT, {0, CMD_LOAD_UNITS, 0, tID}, CMD_OPT_ALT)
end
end
else
-- No trans or no valid target, stop watching
watchList[uID] = nil
end
end
end
function widget:UnitTaken(uID)
watchList[uID] = nil
end
function maybeRemoveSelf()
if Spring.GetSpectatingState() and (Spring.GetGameFrame() > 0 or gameStarted) then
widgetHandler:RemoveWidget(self)
end
end
function widget:GameStart()
gameStarted = true
maybeRemoveSelf()
end
function widget:PlayerChanged(playerID)
maybeRemoveSelf()
end
function widget:Initialize()
if Spring.IsReplay() or Spring.GetGameFrame() > 0 then
maybeRemoveSelf()
end
end
|
---------------------------------------------------------------------------------------------------
-- Issue: https://github.com/smartdevicelink/sdl_core/issues/2405
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/Defects/5_0/2405/common')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local grp = {
[1] = { name = "Dummy-1", prompt = "Dummy_1", params = nil },
[2] = { name = "Dummy-2", prompt = "Dummy_2", params = nil }
}
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("Activate App", common.activateApp)
runner.Step("PolicyTableUpdate", common.policyTableUpdate, { grp })
runner.Title("Test")
runner.Step("Send GetListOfPermissions", common.getListOfPermissions, { grp })
runner.Step("Consent Groups", common.consentGroups, { grp })
runner.Step("Send GetVehicleData speed", common.getVD, { "speed", "SUCCESS", true })
runner.Step("Send GetVehicleData rpm", common.getVD, { "rpm", "SUCCESS", true })
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
ZO_TRADING_HOUSE_NAME_SEARCH_AUTOCOMPLETE_ENTRY_HEIGHT = 28
ZO_TRADING_HOUSE_NAME_SEARCH_MAX_ENTRIES = 22
ZO_TRADING_HOUSE_NAME_SEARCH_AUTOCOMPLETE_MAX_HEIGHT = ZO_TRADING_HOUSE_NAME_SEARCH_MAX_ENTRIES * ZO_TRADING_HOUSE_NAME_SEARCH_AUTOCOMPLETE_ENTRY_HEIGHT
ZO_TRADING_HOUSE_NAME_SEARCH_AUTOCOMPLETE_WIDTH = 400
ZO_TradingHouseNameSearchAutoComplete = ZO_Object:Subclass()
function ZO_TradingHouseNameSearchAutoComplete:New(...)
local object = ZO_Object.New(self)
object:Initialize(...)
return object
end
function ZO_TradingHouseNameSearchAutoComplete:Initialize(menuListControl, editControl)
self:InitializeMenuList(menuListControl)
self:AttachToEditControl(editControl)
end
local MENU_ITEM_DATA = 1
function ZO_TradingHouseNameSearchAutoComplete:InitializeMenuList(menuListControl)
self.menuList = menuListControl
self.lastKeyboardSelectedData = nil
local function SetupMenuItem(itemControl, itemData)
local nameLabel = itemControl:GetNamedChild("Name")
nameLabel:SetText(itemData.name)
itemControl.itemData = itemData
itemControl.autoCompleteObject = self
end
ZO_ScrollList_AddDataType(self.menuList, MENU_ITEM_DATA, "ZO_TradingHouseNameSearchAutoComplete_MenuItem", ZO_TRADING_HOUSE_NAME_SEARCH_AUTOCOMPLETE_ENTRY_HEIGHT, SetupMenuItem)
ZO_ScrollList_EnableSelection(self.menuList, "ZO_SelectionHighlight")
ZO_ScrollList_IgnoreMouseDownEditFocusLoss(self.menuList)
ZO_ScrollList_SetUseFadeGradient(self.menuList, false)
end
function ZO_TradingHouseNameSearchAutoComplete:AttachToEditControl(editControl)
ZO_PreHookHandler(editControl, "OnEnter", function()
if self:IsMenuOpen() then
self:SetEditTextFromSelectedData()
self.editControl:LoseFocus()
end
end)
ZO_PreHookHandler(editControl, "OnTab", function()
if self:IsMenuOpen() then
if not ZO_ScrollList_GetSelectedData(self.menuList) then
ZO_ScrollList_TrySelectFirstData(self.menuList)
end
self:SetEditTextFromSelectedData()
self.editControl:LoseFocus()
end
end)
-- Because the mouse cursor can also change the currently selected item we need to track the "keyboard cursor" independently, which is represented using lastKeyboardSelectedData
-- When performing a keyboard action, we apply the keyboard cursor immediately, then perform the action, and then save the state of the keyboard cursor for the next action.
-- Then we can change the state of the actual selected item as much as we want and it will not affect this code path
local function MoveKeyboardCursorUp()
if self:IsMenuOpen() then
ZO_ScrollList_SelectData(self.menuList, self.lastKeyboardSelectedData)
if ZO_ScrollList_GetSelectedData(self.menuList) == nil then
ZO_ScrollList_TrySelectLastData(self.menuList)
else
ZO_ScrollList_SelectPreviousData(self.menuList)
end
self.lastKeyboardSelectedData = ZO_ScrollList_GetSelectedData(self.menuList)
end
end
ZO_PreHookHandler(editControl, "OnUpArrow", MoveKeyboardCursorUp)
local function MoveKeyboardCursorDown()
if self:IsMenuOpen() then
ZO_ScrollList_SelectData(self.menuList, self.lastKeyboardSelectedData)
if ZO_ScrollList_GetSelectedData(self.menuList) == nil then
ZO_ScrollList_TrySelectFirstData(self.menuList)
else
ZO_ScrollList_SelectNextData(self.menuList)
end
self.lastKeyboardSelectedData = ZO_ScrollList_GetSelectedData(self.menuList)
end
end
ZO_PreHookHandler(editControl, "OnDownArrow", MoveKeyboardCursorDown)
local function HideMenu()
self:Hide()
end
ZO_PreHookHandler(editControl, "OnFocusLost", HideMenu)
ZO_PreHookHandler(editControl, "OnHide", HideMenu)
self.editControl = editControl
end
function ZO_TradingHouseNameSearchAutoComplete:SetEditTextFromSelectedData()
local selectedData = ZO_ScrollList_GetSelectedData(self.menuList)
if selectedData then
local exactSearchText = ZO_TradingHouseNameSearchFeature_Shared.MakeExactSearchText(selectedData.name)
self.editControl:SetText(exactSearchText)
--Move the cursor to the start to scroll the edit box back for long names so the player can see the start of the name instead of the end
self.editControl:SetCursorPosition(0)
end
end
function ZO_TradingHouseNameSearchAutoComplete:IsMenuOpen()
return not self.menuList:IsHidden()
end
function ZO_TradingHouseNameSearchAutoComplete:Hide()
self.menuList:SetHidden(true)
self.menuList:SetHeight(0)
ZO_ScrollList_ResetToTop(self.menuList)
end
function ZO_TradingHouseNameSearchAutoComplete:ShowListForNameSearch(nameMatchId, numResults)
if numResults == 0 or not self.editControl:HasFocus() then
self:Hide()
return
else
self.menuList:SetHidden(false)
end
ZO_ScrollList_Clear(self.menuList)
self.lastKeyboardSelectedData = nil
local scrollData = ZO_ScrollList_GetDataList(self.menuList)
for itemIndex = 1, numResults do
local name, _ = GetMatchTradingHouseItemNamesResult(nameMatchId, itemIndex)
local dataEntry = ZO_ScrollList_CreateDataEntry(MENU_ITEM_DATA, { name = name })
scrollData[itemIndex] = dataEntry
end
ZO_ScrollList_SetHeight(self.menuList, zo_min(ZO_TRADING_HOUSE_NAME_SEARCH_AUTOCOMPLETE_MAX_HEIGHT, numResults * ZO_TRADING_HOUSE_NAME_SEARCH_AUTOCOMPLETE_ENTRY_HEIGHT))
ZO_ScrollList_Commit(self.menuList)
end
function ZO_TradingHouseNameSearchAutoComplete:OnItemClicked(menuItemControl)
ZO_ScrollList_SelectData(self.menuList, menuItemControl.itemData)
self:SetEditTextFromSelectedData()
self.editControl:LoseFocus()
end
function ZO_TradingHouseNameSearchAutoComplete:OnItemMouseEnter(menuItemControl)
-- Normally, scrollLists track what you're moused over using a highlight, but instead we use a selection. This is why we aren't calling the usual ZO_ScrollList_MouseEnter functions
ZO_ScrollList_SelectData(self.menuList, menuItemControl.itemData)
end
function ZO_TradingHouseNameSearchAutoComplete:OnItemMouseExit(menuItemControl)
ZO_ScrollList_SelectData(self.menuList, self.lastKeyboardSelectedData)
end
-- XML Globals
function ZO_TradingHouseNameSearchAutoComplete_MenuItem_OnMouseClick(menuItemControl)
local autoComplete = menuItemControl.autoCompleteObject
autoComplete:OnItemClicked(menuItemControl)
end
function ZO_TradingHouseNameSearchAutoComplete_MenuItem_OnMouseEnter(menuItemControl)
local autoComplete = menuItemControl.autoCompleteObject
autoComplete:OnItemMouseEnter(menuItemControl)
end
function ZO_TradingHouseNameSearchAutoComplete_MenuItem_OnMouseExit(menuItemControl)
local autoComplete = menuItemControl.autoCompleteObject
autoComplete:OnItemMouseExit(menuItemControl)
end
|
local PART = {}
PART.ClassName = "proxy"
PART.NonPhysical = true
PART.ThinkTime = 0
PART.Group = 'modifiers'
PART.Icon = 'icon16/calculator.png'
pac.StartStorableVars()
pac.SetPropertyGroup()
pac.GetSet(PART, "VariableName", "", {enums = function(part)
local parent = part:GetTarget()
if not parent:IsValid() then return end
local tbl = {}
for key, _ in pairs(parent.StorableVars) do
if key == "UniqueID" then goto CONTINUE end
local T = type(parent[key])
if T == "number" or T == "Vector" or T == "Angle" or T == "boolean" then
tbl[key] = key
end
::CONTINUE::
end
return tbl
end})
pac.GetSet(PART, "RootOwner", false)
pac.SetupPartName(PART, "TargetPart")
pac.GetSet(PART, "AffectChildren", false)
pac.GetSet(PART, "Expression", "")
pac.SetPropertyGroup(PART, "easy setup")
pac.GetSet(PART, "Input", "time", {enums = function(part) return part.Inputs end})
pac.GetSet(PART, "Function", "sin", {enums = function(part) return part.Functions end})
pac.GetSet(PART, "Axis", "")
pac.GetSet(PART, "Min", 0)
pac.GetSet(PART, "Max", 1)
pac.GetSet(PART, "Offset", 0)
pac.GetSet(PART, "InputMultiplier", 1)
pac.GetSet(PART, "InputDivider", 1)
pac.GetSet(PART, "Pow", 1)
pac.SetPropertyGroup(PART, "behavior")
pac.GetSet(PART, "Additive", false)
pac.GetSet(PART, "PlayerAngles", false)
pac.GetSet(PART, "ZeroEyePitch", false)
pac.GetSet(PART, "ResetVelocitiesOnHide", true)
pac.GetSet(PART, "VelocityRoughness", 10)
pac.EndStorableVars()
function PART:GetTarget(physical)
local part = self:GetTargetPart()
if part:IsValid() then
return part
end
if physical then
local parent = self:GetParent()
repeat
if not parent.Parent:IsValid() then break end
parent = parent.Parent
until not parent.cached_pos:IsZero()
return parent
end
return self:GetParent()
end
function PART:SetVariableName(str)
self.VariableName = str
self.set_key = "Set" .. str
self.get_key = "Get" .. str
end
function PART:GetNiceName()
if self:GetVariableName() == "" then
return self.ClassName
end
local target
if self.AffectChildren then
target = "children"
else
local part = self:GetTarget()
if part == self.Parent then
target = "parent"
else
target = part:GetName()
end
end
return target .. "." .. pac.PrettifyName(self:GetVariableName()) .. " = " .. (self.debug_var or "?")
end
function PART:Initialize()
self.vec_additive = {}
self.next_vel_calc = 0
end
PART.Functions =
{
none = function(n) return n end,
sin = math.sin,
cos = math.cos,
tan = math.tan,
abs = math.abs,
mod = function(n, s) return n%s.Max end,
sgn = function(n) return n>0 and 1 or n<0 and -1 or 0 end,
}
local FrameTime = FrameTime
function PART:CalcVelocity()
self.last_vel = self.last_vel or Vector()
self.last_vel_smooth = self.last_vel_smooth or self.last_vel or Vector()
self.last_vel_smooth = (self.last_vel_smooth + (self.last_vel - self.last_vel_smooth) * FrameTime() * math.max(self.VelocityRoughness, 0.1))
end
function PART:GetVelocity(part)
local pos = part.cached_pos
if not pos or pos == Vector() then
if IsEntity(part) then
pos = part:GetPos()
elseif part:GetOwner():IsValid() then
pos = part:GetOwner():GetPos()
end
end
local time = pac.RealTime
if self.next_vel_calc < time then
self.next_vel_calc = time + 0.1
self.last_vel = (self.last_pos or pos) - pos
self.last_pos = pos
end
return self.last_vel_smooth / 5
end
function PART:CalcEyeAngles(ent)
local ang = self.PlayerAngles and ent:GetAngles() or ent:EyeAngles()
if self.ZeroEyePitch then
ang.p = 0
end
return ang
end
local function try_viewmodel(ent)
return ent == pac.LocalPlayer:GetViewModel() and pac.LocalPlayer or ent
end
PART.Inputs = {
owner_position = function(s, p)
local owner = s:GetOwner(s.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local pos = owner:GetPos()
return pos.x, pos.y, pos.z
end
return 0,0,0
end,
owner_fov = function(s, p)
local owner = s:GetOwner(s.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() and owner.GetFOV then
return owner:GetFOV()
end
return 0
end,
visible = function(s, p, radius)
p.proxy_pixvis = p.proxy_pixvis or util.GetPixelVisibleHandle()
return util.PixelVisible(p.cached_pos, radius or 16, p.proxy_pixvis) or 0
end,
time = RealTime,
synced_time = CurTime,
systime = SysTime,
stime = SysTime,
frametime = FrameTime,
ftime = FrameTime,
framenumber = FrameNumber,
fnumber = FrameNumber,
random = function(s, p)
return math.random()
end,
timeex = function(s, p)
s.time = s.time or pac.RealTime
return pac.RealTime - s.time
end,
eye_position_distance = function(self, parent)
local pos = parent.cached_pos
if parent.NonPhysical then
local owner = parent:GetOwner(self.RootOwner)
if owner:IsValid() then
pos = owner:GetPos()
end
end
return pos:Distance(pac.EyePos)
end,
eye_angle_distance = function(self, parent)
local pos = parent.cached_pos
if parent.NonPhysical then
local owner = parent:GetOwner(self.RootOwner)
if owner:IsValid() then
pos = owner:GetPos()
end
end
return math.Clamp(math.abs(pac.EyeAng:Forward():DotProduct((pos - pac.EyePos):GetNormalized())) - 0.5, 0, 1)
end,
aim_length = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local res = util.QuickTrace(owner:EyePos(), self:CalcEyeAngles(owner):Forward() * 16000, {owner, owner:GetParent()})
return res.StartPos:Distance(res.HitPos)
end
return 0
end,
aim_length_fraction = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local res = util.QuickTrace(owner:EyePos(), self:CalcEyeAngles(owner):Forward() * 16000, {owner, owner:GetParent()})
return res.Fraction
end
return 0
end,
owner_eye_angle_pitch = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local n = self:CalcEyeAngles(owner).p
return -(1 + math.NormalizeAngle(n) / 89) / 2 + 1
end
return 0
end,
owner_eye_angle_yaw = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local n = self:CalcEyeAngles(owner).y
return math.NormalizeAngle(n)/90
end
return 0
end,
owner_eye_angle_roll = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local n = self:CalcEyeAngles(owner).r
return math.NormalizeAngle(n)/90
end
return 0
end,
owner_scale_x = function(self)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return owner.pac_model_scale and owner.pac_model_scale.x or (owner.GetModelScale and owner:GetModelScale()) or 1
end
return 1
end,
owner_scale_y = function(self)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return owner.pac_model_scale and owner.pac_model_scale.y or (owner.GetModelScale and owner:GetModelScale()) or 1
end
return 1
end,
owner_scale_z = function(self)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return owner.pac_model_scale and owner.pac_model_scale.z or (owner.GetModelScale and owner:GetModelScale()) or 1
end
return 1
end,
-- outfit owner
owner_velocity_length = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return self:GetVelocity(owner):Length()
end
return 0
end,
owner_velocity_forward = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return self:CalcEyeAngles(owner):Forward():Dot(self:GetVelocity(owner))
end
return 0
end,
owner_velocity_right = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return self:CalcEyeAngles(owner):Right():Dot(self:GetVelocity(owner))
end
return 0
end,
owner_velocity_up = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return self:CalcEyeAngles(owner):Up():Dot(self:GetVelocity(owner))
end
return 0
end,
owner_velocity_world_forward = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return self:GetVelocity(owner)[1]
end
return 0
end,
owner_velocity_world_right = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return self:GetVelocity(owner)[2]
end
return 0
end,
owner_velocity_world_up = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
return self:GetVelocity(owner)[3]
end
return 0
end,
-- outfit owner vel increase
owner_velocity_length_increase = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local vel = self:GetVelocity(owner):Length()
self.ov_length_i = (self.ov_length_i or 0) + vel * FrameTime()
return self.ov_length_i
end
return 0
end,
owner_velocity_forward_increase = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local vel = self:CalcEyeAngles(owner):Forward():Dot(self:GetVelocity(owner))
self.ov_forward_i = (self.ov_forward_i or 0) + vel * FrameTime()
return self.ov_forward_i
end
return 0
end,
owner_velocity_right_increase = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local vel = self:CalcEyeAngles(owner):Right():Dot(self:GetVelocity(owner))
self.ov_right_i = (self.ov_right_i or 0) + vel * FrameTime()
return self.ov_right_i
end
return 0
end,
owner_velocity_up_increase = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local vel = self:CalcEyeAngles(owner):Up():Dot(self:GetVelocity(owner))
self.ov_up_i = (self.ov_up_i or 0) + vel * FrameTime()
return self.ov_up_i
end
return 0
end,
owner_velocity_world_forward_increase = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local vel = self:GetVelocity(owner)[1]
self.ov_wforward_i = (self.ov_wforward_i or 0) + vel * FrameTime()
return self.ov_wforward_i
end
return 0
end,
owner_velocity_world_right_increase = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local vel = self:GetVelocity(owner)[2]
self.ov_wright_i = (self.ov_wright_i or 0) + vel * FrameTime()
return self.ov_wright_i
end
return 0
end,
owner_velocity_world_up_increase = function(self, parent)
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() then
local vel = self:GetVelocity(owner)[3]
self.ov_wup_i = (self.ov_wup_i or 0) + vel * FrameTime()
return self.ov_wup_i
end
return 0
end,
-- parent part
parent_velocity_length = function(self, parent)
parent = self:GetTarget(true)
return self:GetVelocity(parent):Length()
end,
parent_velocity_forward = function(self, parent)
parent = self:GetTarget(true)
return -parent.cached_ang:Forward():Dot(self:GetVelocity(parent))
end,
parent_velocity_right = function(self, parent)
parent = self:GetTarget(true)
return parent.cached_ang:Right():Dot(self:GetVelocity(parent))
end,
parent_velocity_up = function(self, parent)
parent = self:GetTarget(true)
return parent.cached_ang:Up():Dot(self:GetVelocity(parent))
end,
parent_scale_x = function(self, parent)
if parent:IsValid() then
return parent.Scale and parent.Scale.x*parent.Size or 1
end
return 1
end,
parent_scale_y = function(self, parent)
if parent:IsValid() then
return parent.Scale and parent.Scale.y*parent.Size or 1
end
return 1
end,
parent_scale_z = function(self, parent)
if parent:IsValid() then
return parent.Scale and parent.Scale.z*parent.Size or 1
end
return 1
end,
pose_parameter = function(self, parent, name)
if name then
local owner = self:GetOwner(self.RootOwner)
owner = try_viewmodel(owner)
if owner:IsValid() and owner.GetPoseParameter then
return owner:GetPoseParameter(name)
end
end
return 0
end,
command = function(self, index)
local ply = self:GetPlayerOwner()
if ply.pac_proxy_events then
local data = ply.pac_proxy_events[self.Name]
if data then
data.x = data.x or 0
data.y = data.y or 0
data.z = data.z or 0
return data.x, data.y, data.z
end
end
return 0, 0, 0
end,
voice_volume = function(self)
local ply = self:GetPlayerOwner()
return ply:VoiceVolume()
end,
light_amount_r = function(self, parent)
if parent:IsValid() then
return render.GetLightColor(parent.cached_pos):ToColor().r
end
return 0
end,
light_amount_g = function(self, parent)
if parent:IsValid() then
return render.GetLightColor(parent.cached_pos):ToColor().g
end
return 0
end,
light_amount_b = function(self, parent)
if parent:IsValid() then
return render.GetLightColor(parent.cached_pos):ToColor().b
end
return 0
end,
light_value = function(self, parent)
if parent:IsValid() then
local h, s, v = ColorToHSV(render.GetLightColor(parent.cached_pos):ToColor())
return v
end
return 0
end,
ambient_light_r = function(self, parent)
if parent:IsValid() then
return render.GetAmbientLightColor():ToColor().r
end
return 0
end,
ambient_light_g = function(self, parent)
if parent:IsValid() then
return render.GetAmbientLightColor():ToColor().g
end
return 0
end,
ambient_light_b = function(self, parent)
if parent:IsValid() then
return render.GetAmbientLightColor():ToColor().b
end
return 0
end,
owner_health = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:Health()
end
return 0
end,
owner_max_health = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:GetMaxHealth()
end
return 0
end,
owner_armor = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:Armor()
end
return 0
end,
owner_total_ammo = function(self, parent, id)
local owner = self:GetPlayerOwner()
id = id and id:lower()
if owner:IsValid() then
return (owner.GetAmmoCount and id) and owner:GetAmmoCount(id) or 0
end
return 0
end,
player_color_r = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:GetPlayerColor().r
end
return 1
end,
player_color_g = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:GetPlayerColor().g
end
return 1
end,
player_color_b = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:GetPlayerColor().b
end
return 1
end,
weapon_color_r = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:GetWeaponColor().r
end
return 1
end,
weapon_color_g = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:GetWeaponColor().g
end
return 1
end,
weapon_color_b = function(self)
local owner = self:GetPlayerOwner()
if owner:IsValid() then
return owner:GetWeaponColor().b
end
return 1
end,
weapon_primary_ammo = function(self)
local owner = self:GetOwner(true)
if owner:IsValid() and not owner.GetActiveWeapon and not owner:IsWeapon() then
owner = self:GetPlayerOwner()
end
if owner:IsValid() then
owner = owner.GetActiveWeapon and owner:GetActiveWeapon() or owner
return owner.Clip1 and owner:Clip1() or 0
end
return 0
end,
weapon_primary_total_ammo = function(self)
local owner = self:GetOwner(true)
if owner:IsValid() and not owner.GetActiveWeapon and not owner:IsWeapon() then
owner = self:GetPlayerOwner()
end
if owner:IsValid() then
local wep = owner.GetActiveWeapon and owner:GetActiveWeapon() or owner
return (wep.GetPrimaryAmmoType and owner.GetAmmoCount) and owner:GetAmmoCount(wep:GetPrimaryAmmoType()) or 0
end
return 0
end,
weapon_primary_clipsize = function(self)
local owner = self:GetOwner(true)
if owner:IsValid() and not owner.GetActiveWeapon and not owner:IsWeapon() then
owner = self:GetPlayerOwner()
end
if owner:IsValid() then
owner = owner.GetActiveWeapon and owner:GetActiveWeapon() or owner
return owner.GetMaxClip1 and owner:GetMaxClip1() or 0
end
return 0
end,
weapon_secondary_ammo = function(self)
local owner = self:GetOwner(true)
if owner:IsValid() and not owner.GetActiveWeapon and not owner:IsWeapon() then
owner = self:GetPlayerOwner()
end
if owner:IsValid() then
owner = owner.GetActiveWeapon and owner:GetActiveWeapon() or owner
return owner.Clip2 and owner:Clip2() or 0
end
return 0
end,
weapon_secondary_total_ammo = function(self)
local owner = self:GetOwner(true)
if owner:IsValid() and not owner.GetActiveWeapon and not owner:IsWeapon() then
owner = self:GetPlayerOwner()
end
if owner:IsValid() then
local wep = owner.GetActiveWeapon and owner:GetActiveWeapon() or owner
return (wep.GetSecondaryAmmoType and owner.GetAmmoCount) and owner:GetAmmoCount(wep:GetSecondaryAmmoType()) or 0
end
return 0
end,
weapon_secondary_clipsize = function(self)
local owner = self:GetOwner(true)
if owner:IsValid() and not owner.GetActiveWeapon and not owner:IsWeapon() then
owner = self:GetPlayerOwner()
end
if owner:IsValid() then
owner = owner.GetActiveWeapon and owner:GetActiveWeapon() or owner
return owner.GetMaxClip2 and owner:GetMaxClip2() or 0
end
return 0
end,
hsv_to_color = function(self, parent, h, s, v)
h = tonumber(h) or 0
s = tonumber(s) or 1
v = tonumber(v) or 1
local c = HSVToColor(h%360, s, v)
return c.r, c.g, c.b
end,
lerp = function(self, parent, m, a, b)
m = tonumber(m) or 0
a = tonumber(a) or -1
b = tonumber(b) or 1
return (b - a) * m + a
end,
feedback = function(self)
if not self.feedback then return 0 end
return self.feedback[1] or 0
end,
feedback_x = function(self)
if not self.feedback then return 0 end
return self.feedback[1] or 0
end,
feedback_y = function(self)
if not self.feedback then return 0 end
return self.feedback[2] or 0
end,
feedback_z = function(self)
if not self.feedback then return 0 end
return self.feedback[3] or 0
end,
}
net.Receive("pac_proxy", function()
local ply = net.ReadEntity()
local str = net.ReadString()
local x = net.ReadFloat()
local y = net.ReadFloat()
local z = net.ReadFloat()
if ply:IsValid() then
ply.pac_proxy_events = ply.pac_proxy_events or {}
ply.pac_proxy_events[str] = {name = str, x = x, y = y, z = z}
end
end)
function PART:CheckLastVar(parent)
if self.last_var ~= self.VariableName then
if self.last_var then
parent[self.set_key](parent, self.last_var_val)
end
self.last_var = self.VariableName
self.last_var_val = parent[self.get_key](parent)
end
end
local allowed = {
number = true,
Vector = true,
Angle = true,
boolean = true,
}
function PART:SetExpression(str)
self.Expression = str
self.ExpressionFunc = nil
if str and str ~= "" then
local parent = self:GetTarget()
if not parent:IsValid() then return end
local lib = {}
for name, func in pairs(PART.Inputs) do
lib[name] = function(...) return func(self, parent, ...) end
end
local ok, res = pac.CompileExpression(str, lib)
if ok then
self.ExpressionFunc = res
self.ExpressionError = nil
else
self.ExpressionFunc = true
self.ExpressionError = res
end
end
end
function PART:OnHide()
self.time = nil
self.vec_additive = Vector()
if self.ResetVelocitiesOnHide then
self.last_vel = nil
self.last_pos = nil
self.last_vel_smooth = nil
end
end
function PART:OnShow()
self.time = nil
self.vec_additive = Vector()
end
local function set(self, part, x, y, z, children)
local T = type(part[self.VariableName])
if allowed[T] then
if T == "boolean" then
x = x or part[self.VariableName] == true and 1 or 0
part[self.set_key](part, tonumber(x) > 0)
elseif T == "number" then
x = x or part[self.VariableName]
part[self.set_key](part, tonumber(x) or 0)
else
local val = part[self.VariableName]
if self.Axis ~= "" and val[self.Axis] then
val[self.Axis] = x
else
if T == "Angle" then
val.p = x or val.p
val.y = y or val.y
val.r = z or val.r
elseif T == "Vector" then
val.x = x or val.x
val.y = y or val.y
val.z = z or val.z
end
end
part[self.set_key](part, val)
end
end
if children then
for _, part in ipairs(part:GetChildren()) do
set(self, part, x, y, z, true)
end
end
end
function PART:RunExpression(ExpressionFunc)
if ExpressionFunc==true then
return false,self.ExpressionError
end
return pcall(ExpressionFunc)
end
function PART:OnThink()
local parent = self:GetTarget()
if not parent:IsValid() then return end
if parent.ClassName == 'woohoo' then return end
self:CalcVelocity()
local ExpressionFunc = self.ExpressionFunc
if not ExpressionFunc then
self:SetExpression(self.Expression)
ExpressionFunc = self.ExpressionFunc
end
if ExpressionFunc then
local ok, x,y,z = self:RunExpression(ExpressionFunc)
if not ok then
if self:GetPlayerOwner() == pac.LocalPlayer and self.Expression ~= self.LastBadExpression then
chat.AddText(Color(255,180,180),"============\n[ERR] PAC Proxy error on "..tostring(self)..":\n"..x.."\n============\n")
self.LastBadExpression = self.Expression
end
return
end
if self.Additive then
if x then
self.vec_additive[1] = (self.vec_additive[1] or 0) + x
x = self.vec_additive[1]
end
if y then
self.vec_additive[2] = (self.vec_additive[2] or 0) + y
y = self.vec_additive[2]
end
if z then
self.vec_additive[3] = (self.vec_additive[3] or 0) + z
z = self.vec_additive[3]
end
end
self.feedback = self.feedback or {}
self.feedback[1] = x
self.feedback[2] = y
self.feedback[3] = z
if self.AffectChildren then
for _, part in ipairs(self:GetChildren()) do
set(self, part, x, y, z, true)
end
else
set(self, parent, x, y, z)
end
if pace and pace.IsActive() then
local str = ""
if x then str = str .. math.Round(x, 3) end
if y then str = str .. ", " .. math.Round(y, 3) end
if z then str = str .. ", " .. math.Round(z, 3) end
self.debug_var = str
end
else
local F = self.Functions[self.Function]
local I = self.Inputs[self.Input]
if F and I then
local num = self.Min + (self.Max - self.Min) * ((F(((I(self, parent) / self.InputDivider) + self.Offset) * self.InputMultiplier, self) + 1) / 2) ^ self.Pow
if self.Additive then
self.vec_additive[1] = (self.vec_additive[1] or 0) + num
num = self.vec_additive[1]
end
if self.AffectChildren then
for _, part in ipairs(self:GetChildren()) do
set(self, part, num, nil, nil, true)
end
else
set(self, parent, num)
end
if pace and pace.IsActive() then
self.debug_var = math.Round(num, 3)
end
end
end
end
pac.RegisterPart(PART)
|
------------------------------------------------------------------------------
--
-- This file is part of the Corona game engine.
-- For overview and more information on licensing please refer to README.md
-- Home page: https://github.com/coronalabs/corona
-- Contact: [email protected]
--
------------------------------------------------------------------------------
simulator =
{
device = "desktop-3840x2160",
screenOriginX = 0,
screenOriginY = 0,
screenWidth = 3840,
screenHeight = 2160,
deviceImage = nil,
displayManufacturer = "",
displayName = "Linux Desktop",
supportsScreenRotation = false,
windowTitleBarName = "Desktop 6"
}
|
local name, _FishMaster = ...;
LibStub("AceConfig-3.0"):RegisterOptionsTable(name, {
type = "group",
childGroups = "tab",
args = {
general = _FishMaster.settings.general
}
})
LibStub("AceConfigDialog-3.0"):AddToBlizOptions(name, name);
|
return {'opulent','opulentie','opus','opusnummer','opussen','opulente','opusnummers'}
|
local state = {}
state._NAME = ...
local Body = require'Body'
local t_entry, t_update, t_exit
local timeout = 10.0
function state.entry()
print(state._NAME..' Entry' )
local t_entry_prev = t_entry
t_entry = Body.get_time()
t_update = t_entry
end
function state.update()
local t = Body.get_time()
local dt = t - t_update
if t-t_entry>1.0 then return "done" end
end
function state.exit()
print(state._NAME..' Exit' )
end
return state
|
-- granchild v2.0.2
-- granular sequencer
--
-- llllllll.co/t/granchild
--
-- thx @artfwo, @cfdrake,
-- @justmat
--
engine.name="ZGlut"
local granchild=include("granchild/lib/granchild")
local position={1,1}
local press_positions={{0,0},{0,0}}
local norns_screen={}
local divisions={1,2,4,6,8,12,16}
local division_names={"2 wn","wn","hn","hn-t","qn","qn-t","eighth"}
local param_list={"overtones","overtoneslfo","subharmonics","subharmonicslfo","sizelfo","densitylfo","speedlfo","volumelfo","spreadlfo","jitterlfo","spread","jitter","size","pos","q","division","speed","send","q","cutoff","fade","pitch","density","volume","seek","play","sample"}
local param_list_delay={"delay_volume","delay_mod_freq","delay_mod_depth","delay_fdbk","delay_diff","delay_damp","delay_size","delay_time"}
local function bang(scene)
for i=1,4 do
for _,param_name in ipairs(param_list) do
local p=params:lookup_param(i..param_name..scene)
p:bang()
end
local p=params:lookup_param(i.."pattern"..scene)
p:bang()
end
for _,param_name in ipairs(param_list_delay) do
local p=params:lookup_param(param_name..scene)
p:bang()
end
end
local function setup_params()
params:add_separator("samples")
local num_voices=4
local old_volume={0.25,0.25,0.25,0.25}
for i=1,num_voices do
params:add_group("sample "..i,55)
params:add_option(i.."scene","scene",{"a","b"},1)
params:set_action(i.."scene",function(scene)
for _,param_name in ipairs(param_list) do
params:hide(i..param_name..(3-scene))
params:show(i..param_name..scene)
local p=params:lookup_param(i..param_name..scene)
p:bang()
end
local p=params:lookup_param(i.."pattern"..scene)
p:bang()
if params:get(i.."pattern"..scene)=="" or params:get(i.."pattern"..scene)=="[]" then
granchild_grid:toggle_playing_voice(i,false)
end
if _menu.rebuild_params~=nil then
_menu.rebuild_params()
end
end)
for scene=1,2 do
params:add_file(i.."sample"..scene,"sample")
params:set_action(i.."sample"..scene,function(file)
print("sample "..file)
if file~="-" then
engine.read(i,file)
params:set(i.."play"..scene,2)
if params:get(i.."sample"..(3-scene))=="-" then
-- load for other scene by default
params:set(i.."sample"..(3-scene),file,true)
params:set(i.."play"..(3-scene),2,true)
end
end
end)
params:add_option(i.."play"..scene,"play",{"off","on"},1)
params:set_action(i.."play"..scene,function(x) engine.gate(i,x-1) end)
params:add_control(i.."seek"..scene,"seek",controlspec.new(0,1,"lin",0.001,0,"",0.001/1))
params:set_action(i.."seek"..scene,function(value) engine.seek(i,util.clamp(value+params:get(i.."pos"..scene),0,1)) end)
params:add_control(i.."volume"..scene,"volume",controlspec.new(0,1.0,"lin",0.05,0.25,"vol",0.05/1))
params:set_action(i.."volume"..scene,function(value)
engine.volume(i,value)
-- turn off the delay if volume is zero
if value==0 then
engine.send(i,0)
elseif value>0 and old_volume[i]==0 then
engine.send(i,params:get(i.."send"..scene))
end
old_volume[i]=value
end)
params:add_option(i.."volumelfo"..scene,"volume lfo",{"off","on"},1)
params:add_control(i.."density"..scene,"density",controlspec.new(1,40,"lin",1,12,"/beat",1/40))
params:set_action(i.."density"..scene,function(value) engine.density(i,value/(4*clock.get_beat_sec())) end)
params:add_option(i.."densitylfo"..scene,"density lfo",{"off","on"},1)
params:add_control(i.."pitch"..scene,"pitch",controlspec.new(-48,48,"lin",1,0,"note",1/96))
params:set_action(i.."pitch"..scene,function(value) engine.pitch(i,math.pow(0.5,-value/12)) end)
params:add_taper(i.."fade"..scene,"att / dec",1,9000,1000,3,"ms")
params:set_action(i.."fade"..scene,function(value) engine.envscale(i,value/1000) end)
params:add_control(i.."cutoff"..scene,"filter cutoff",controlspec.new(20,20000,"exp",0,20000,"hz"))
params:set_action(i.."cutoff"..scene,function(value) engine.cutoff(i,value) end)
params:add_control(i.."q"..scene,"filter rq",controlspec.new(0.1,1.00,"lin",0.01,1))
params:set_action(i.."q"..scene,function(value) engine.q(i,value) end)
params:add_control(i.."send"..scene,"delay send",controlspec.new(0.0,1.0,"lin",0.01,0.2))
params:set_action(i.."send"..scene,function(value) engine.send(i,value) end)
params:add_control(i.."speed"..scene,"speed",controlspec.new(-2.0,2.0,"lin",0.1,0,"",0.1/4))
params:set_action(i.."speed"..scene,function(value) engine.speed(i,value) end)
params:add_option(i.."speedlfo"..scene,"speed lfo",{"off","on"},1)
params:add_option(i.."division"..scene,"division",division_names,5)
params:set_action(i.."division"..scene,function(value)
if granchild_grid~=nil then
granchild_grid:set_division(i,divisions[value])
end
end)
params:add_control(i.."pos"..scene,"pos",controlspec.new(-1/40,1/40,"lin",0.001,0))
params:set_action(i.."pos"..scene,function(value) engine.seek(i,util.clamp(value+params:get(i.."seek"..scene),0,1)) end)
params:add_control(i.."size"..scene,"size",controlspec.new(1,15,"lin",1,5,"",1/15))
params:set_action(i.."size"..scene,function(value) engine.size(i,value*clock.get_beat_sec()/10) end)
params:add_option(i.."sizelfo"..scene,"size lfo",{"off","on"},1)
params:add_taper(i.."jitter"..scene,"jitter",0,500,0,5,"ms")
params:set_action(i.."jitter"..scene,function(value) engine.jitter(i,value/1000) end)
params:add_option(i.."jitterlfo"..scene,"jitter lfo",{"off","on"},2)
params:add_taper(i.."spread"..scene,"spread",0,100,0,0,"%")
params:set_action(i.."spread"..scene,function(value) engine.spread(i,value/100) end)
params:add_option(i.."spreadlfo"..scene,"spread lfo",{"off","on"},2)
params:add_control(i.."subharmonics"..scene,"subharmonic vol",controlspec.new(0.00,1.00,"lin",0.01,0))
params:set_action(i.."subharmonics"..scene,function(value) engine.subharmonics(i,value) end)
params:add_option(i.."subharmonicslfo"..scene,"subharmonic lfo",{"off","on"},1)
params:add_control(i.."overtones"..scene,"overtone vol",controlspec.new(0.00,1.00,"lin",0.01,0))
params:set_action(i.."overtones"..scene,function(value) engine.overtones(i,value) end)
params:add_option(i.."overtoneslfo"..scene,"overtone lfo",{"off","on"},1)
params:add_text(i.."pattern"..scene,"pattern","")
params:hide(i.."pattern"..scene)
params:set_action(i.."pattern"..scene,function(value)
if granchild_grid~=nil then
granchild_grid:set_steps(i,value)
end
end)
end
end
params:add_group("delay",17)
params:add_option("delayscene","scene",{"a","b"},1)
params:set_action("delayscene",function(scene)
for _,param_name in ipairs(param_list_delay) do
params:hide(i..param_name..(3-scene))
params:show(i..param_name..scene)
local p=params:lookup_param(i..param_name..scene)
p:bang()
end
end)
for scene=1,2 do
-- effect controls
-- delay time
params:add_control("delay_time"..scene,"*".."delay time",controlspec.new(0.0,60.0,"lin",.01,2.00,""))
params:set_action("delay_time"..scene,function(value) engine.delay_time(value) end)
-- delay size
params:add_control("delay_size"..scene,"*".."delay size",controlspec.new(0.5,5.0,"lin",0.01,2.00,""))
params:set_action("delay_size"..scene,function(value) engine.delay_size(value) end)
-- dampening
params:add_control("delay_damp"..scene,"*".."delay damp",controlspec.new(0.0,1.0,"lin",0.01,0.10,""))
params:set_action("delay_damp"..scene,function(value) engine.delay_damp(value) end)
-- diffusion
params:add_control("delay_diff"..scene,"*".."delay diff",controlspec.new(0.0,1.0,"lin",0.01,0.707,""))
params:set_action("delay_diff"..scene,function(value) engine.delay_diff(value) end)
-- feedback
params:add_control("delay_fdbk"..scene,"*".."delay fdbk",controlspec.new(0.00,1.0,"lin",0.01,0.20,""))
params:set_action("delay_fdbk"..scene,function(value) engine.delay_fdbk(value) end)
-- mod depth
params:add_control("delay_mod_depth"..scene,"*".."delay mod depth",controlspec.new(0.0,1.0,"lin",0.01,0.00,""))
params:set_action("delay_mod_depth"..scene,function(value) engine.delay_mod_depth(value) end)
-- mod rate
params:add_control("delay_mod_freq"..scene,"*".."delay mod freq",controlspec.new(0.0,10.0,"lin",0.01,0.10,"hz"))
params:set_action("delay_mod_freq"..scene,function(value) engine.delay_mod_freq(value) end)
-- delay output volume
params:add_control("delay_volume"..scene,"*".."delay output volume",controlspec.new(0.0,1.0,"lin",0,1.0,""))
params:set_action("delay_volume"..scene,function(value) engine.delay_volume(value) end)
end
-- hide scene 2 initially
for i=1,4 do
for _,param_name in ipairs(param_list) do
params:hide(i..param_name.."2")
end
end
for _,param_name in ipairs(param_list_delay) do
params:hide(param_name.."2")
end
bang(1)
end
function init()
setup_params()
granchild_grid=granchild:new({grid_on=true,toggleable=false})
-- local kolor = include("kolor/lib/kolor")
-- kolor_grid = kolor:new({grid_on=false,toggleable=true})
-- kolor_grid:toggle_grid(false)
-- granchild_grid:toggle_grid(true)
-- kolor_grid:set_toggle_callback(function()
-- granchild_grid:toggle_grid()
-- end)
-- granchild_grid:set_toggle_callback(function()
-- kolor_grid:toggle_grid()
-- end)
-- setup grid
-- kolor_grid.lattice.hard_sync()
-- granchild_grid.lattice.hard_sync()
clock.run(function()
while true do
clock.sleep(1/10) -- refresh
-- toggle norns screen between the granchild and kolor
if granchild_grid.grid_on then
norns_screen=granchild_grid.visual
elseif kolor_grid~=nil and kolor_grid.grid_on then
norns_screen=kolor_grid.visual
end
redraw()
end
end) -- start the grid redraw clock
-- params:set("1sample1",_path.audio.."splices/lr.wav")
-- params:set("1sample1","/home/we/dust/audio/kolor/bank12/loop_break_bpm175.wav")
-- params:set("1cutoff1",3000)
-- params:set("1cutoff2",3000)
end
function enc(k,d)
if k==2 then
position[1]=position[1]+d
if position[1]>8 then
position[1]=8
elseif position[1]<1 then
position[1]=1
end
elseif k==3 then
position[2]=position[2]+d
if position[2]>16 then
position[2]=16
elseif position[2]<1 then
position[2]=1
end
end
end
function key(k,z)
if k>1 then
if z==1 then
press_positions[k-1]={position[1],position[2]}
end
granchild_grid:key_press(press_positions[k-1][1],press_positions[k-1][2],z==1)
elseif k==1 and z==1 then
granchild_grid:toggle_grid64_side()
end
end
function redraw()
screen.clear()
screen.level(0)
screen.rect(1,1,128,64)
screen.fill()
if norns_screen~=nil and norns_screen[1]~=nil then
local gd=norns_screen
rows=#gd
cols=#gd[1]
for row=1,rows do
for col=1,cols do
if gd[row][col]~=0 then
screen.level(gd[row][col])
screen.rect(col*8-7,row*8-8+1,6,6)
screen.fill()
end
end
end
screen.level(15)
screen.rect(position[2]*8-7,position[1]*8-8+1,7,7)
screen.stroke()
end
screen.update()
end
function rerun()
norns.script.load(norns.state.script)
end
|
-- Borrowed from UnNethack
--
--
des.level_init({ style = "solidfill", fg = " " });
des.level_flags("mazelevel", "noteleport", "hardfloor", "premapped", "solidify");
des.map([[
----
|..|
|..-------------
|..............|
|-.--FFFFFF---+|
|..........F...|
|...|......F...|
---.|......F...|
|.|...|..F...|
|.|......F...|
|.|.|....F...|
|.|....-------
|.---..|
|....|.|
----...|
-----
]]);
des.levregion({ region = {08,13,08,13}, type = "branch" })
des.stair("up",13,10)
des.door("closed",14,4)
des.region(selection.area(00,00,30,12),"lit")
des.non_diggable(selection.area(00,00,30,15))
des.non_passwall(selection.area(00,00,30,15))
-- Boulders
des.object("boulder",02,04)
des.object("boulder",02,05)
des.object("boulder",04,05)
des.object("boulder",06,07)
des.object("boulder",07,07)
des.object("boulder",09,07)
des.object("boulder",09,08)
des.object("boulder",06,09)
des.object("boulder",07,09)
des.object("boulder",08,10)
des.object("boulder",09,10)
des.object("boulder",07,11)
-- Traps
des.trap("pit",3,3)
des.trap("pit",4,3)
des.trap("pit",5,3)
des.trap("pit",6,3)
des.trap("pit",7,3)
des.trap("pit",8,3)
des.trap("pit",9,3)
des.trap("pit",10,3)
des.trap("pit",11,3)
des.trap("pit",12,3)
des.trap("pit",13,3)
-- A little help
des.object("earth",1,1)
des.object("earth",2,1)
-- Random objects
des.object({ class = "%" });
des.object({ class = "%" });
des.object({ class = "%" });
des.object({ class = "%" });
des.object({ class = "=" });
des.object({ class = "/" });
|
require("modules/externals/luafft") -- we need to add this to the game folder
require("audioManager") -- Game modules
require("modules/utils/miscUtils")
require("modules/utils/fxUtils")
require("modules/utils/debugUtils")
require("splash")
require("selection")
require("gameover")
require("fileParser")
require("modules/objectParsing")
class = require("modules/externals/30log") -- Object Orientation library, needed for some stuff
require("modules/gameObjects") -- Now we create the objects we need in order to get stuff working
require("modules/externals/lovedebug") --Unexpected crashes often get handled by this, also provides a nice console
require("game")
require("modules/externals/extractor")
bit = require("bit")
reloadSelectionScreen = false
-- Enables debugging in the game section, can be enabled by lovedebug console
debuggingEnabled = false
-- Module name for debug infos
local moduleName = "[MainThread]"
-- Debug infos
debugTimer()
debugLog("BeatFever Mania Debugger, v0.8 =-=-=-=", 1, moduleName)
-- gets screen dimensions.
ScreenSizeW = love.graphics.getWidth()
ScreenSizeH = love.graphics.getHeight()
ScreenSizeHOld = ScreenSizeH
ScreenSizeWOld = ScreenSizeW
debugLog("Initial screen res is: " .. ScreenSizeW .. "x" .. ScreenSizeH, 1, moduleName)
-- Current screen to render
Screen = 0
Count = 0
-- Font
font = love.graphics.newFont("fonts/bignoodle.ttf", ScreenSizeH / 16)
fontSelectionSongTitle = love.graphics.newFont("fonts/bignoodle.ttf", ScreenSizeH / 25)
fontSelectionArtistName = love.graphics.newFont("fonts/bignoodle.ttf", ScreenSizeH / 32)
ingameFont = love.graphics.newFont("fonts/bignoodle.ttf", ScreenSizeH / 8)
fontRating = love.graphics.newFont("fonts/bignoodle.ttf", clamp(ScreenSizeH / 1.6, ScreenSizeH, 1))
-- Window settings
--Window = love.window.setMode(1280, 720, {resizable = true, vsync = false})
-- Vars for mouse control
oldMouseClicked = nil
newMouseClicked = nil
mouseTrail = 10
function love.load()
mx, my = love.mouse.getPosition()
mouseScreenX, mouseScreenY = mx, my
min_dt = 1/120
next_time = love.timer.getTime()
love.mouse.setVisible(false)
--Creates mouse cursor
mouseCursor = love.graphics.newImage("img/lecursor.png")
mouseList = {}
lowerScreenAlpha = love.graphics.newImage("img/gradient.png")
splashLoad()
end
function love.update(dt)
--MouseTrail
mx, my = love.mouse.getPosition()
mouseScreenX, mouseScreenY = mx, my
mouseInfo = {X = mouseScreenX, Y = mouseScreenY}
table.insert(mouseList, mouseInfo)
if #mouseList > mouseTrail then
table.remove(mouseList, 1)
end
-- Make sure mouse clicks only once
oldMouseClicked = newMouseClicked
newMouseClicked = love.mouse.isDown(1)
--FPS at 120 on menus, 200 ingame
if Screen == 2 then
min_dt = 1/120
else
min_dt = 1/60
end
next_time = next_time + min_dt
-- Update screen sizes only on some frames
if Count % 32 == 0 then
ScreenSizeW = love.graphics.getWidth() -- gets screen dimensions.
ScreenSizeH = love.graphics.getHeight() -- gets screen dimensions.
end
-- If size changed, update accordingly
if ScreenSizeWOld ~= ScreenSizeW or ScreenSizeH ~= ScreenSizeHOld then
ScreenSizeHOld = ScreenSizeH
ScreenSizeWOld = ScreenSizeW
debugLog("Screen size changed! Redefining certain assets...", 2, moduleName)
font = love.graphics.newFont("fonts/bignoodle.ttf", ScreenSizeH / 16)
fontSelectionSongTitle = nil
fontSelectionArtistName = nil
ingameFont = nil
fontRating = nil
font = love.graphics.newFont("fonts/bignoodle.ttf", clamp(ScreenSizeH / 16, ScreenSizeH, 1))
fontSelectionSongTitle = love.graphics.newFont("fonts/bignoodle.ttf", clamp(ScreenSizeH / 25, ScreenSizeH, 1))
fontSelectionArtistName = love.graphics.newFont("fonts/bignoodle.ttf", clamp(ScreenSizeH / 32, ScreenSizeH, 1))
ingameFont = love.graphics.newFont("fonts/bignoodle.ttf", ScreenSizeH / 8)
fontRating = love.graphics.newFont("fonts/bignoodle.ttf", clamp(ScreenSizeH / 1.6, ScreenSizeH, 1))
collectgarbage("collect")
end
-- Update FPS only on some frames
if Count % 120 == 0 then
local stats = love.graphics.getStats()
memUsage = stats.texturememory + round(collectgarbage("count"), 2)
love.window.setTitle("BeatFever Mania -- "..love.timer.getFPS().." FPS || Game Memory: "..round(memUsage/1024, 2).."kb")
end
-- Screen switcharoo magic
if Screen == 0 then
splashUpdate(dt)
elseif Screen == 1 then
selectionUpdate(dt)
elseif Screen == 2 then
gameUpdate(dt)
elseif Screen == 3 then
gameOverUpdate(dt)
end
--musicVolume(0)
end
function love.draw()
-- Screen switcharoo magic
if Screen == 0 then
splashDraw()
elseif Screen == 1 then
selectionDraw()
elseif Screen == 2 then
gameDraw()
elseif Screen == 3 then
gameOverDraw()
end
Count = Count + 1
if Screen == 2 then
love.graphics.setColor(255, 255, 255, 23)
end
love.graphics.draw(mouseCursor, mouseScreenX, mouseScreenY, 0,(ScreenSizeW/1280)*1.6,(ScreenSizeH/720)*1.6, mouseCursor:getWidth()/2, mouseCursor:getHeight()/2)
for i = 1, #mouseList do
love.graphics.setColor(255, 255, 255, (124/#mouseList*1.5)*i)
if (i > 1) and (mouseList[i].X == mouseList[i - 1].X and mouseList[i].Y == mouseList[i-1].Y) == false then
love.graphics.draw(mouseCursor, mouseList[i].X, mouseList[i].Y, 0,(ScreenSizeW/1280)*1.6,(ScreenSizeH/720)*1.6, mouseCursor:getWidth()/2, mouseCursor:getHeight()/2)
end
end
-- 120fps cap
local cur_time = love.timer.getTime()
if next_time <= cur_time then
next_time = cur_time
return
end
love.timer.sleep(next_time - cur_time)
end
-- TODO list
-- Arrumar barras do FFT e trails atualizando mais lentamente se framerate/update rate diminuir
|
--[[
about messagebox.lua
convienence functions for the message box C api
]]
messagebox =
{
text = nil --the c pointer
}
function messagebox:new(text)
o = {};
setmetatable(o, self);
self.__index = self;
o.text = text;
message_box_create(text);
return o;
end
|
html_title = '<h1>Sensor Data</h1>'
sensor = require('sensor')
utils = require('utils')
config = require('config')
sensor.setup()
function sensor_data_to_html()
return "<h3><b>" .. sensor.id .. ":</b> <i>" .. tostring(utils.avg_values(sensor.get_data, 10, 1000)) .. "</i></h3>"
end
function setup_http_server(get_data_formatted)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
data_formatted = get_data_formatted()
conn:send("<!DOCTYPE html><html><body>" .. html_title .. data_formatted .. "</body></html>")
conn:on("sent",function(conn) conn:close() end)
end)
end
function wait_for_network()
if wifi.sta.getip() ~= nil then
print('Connected to ip: '..tostring(wifi.sta.getip()))
tmr.stop(0)
setup_http_server(sensor_data_to_html)
end
end
wifi.setmode(wifi.STATION)
wifi.sta.config(config.wifi.ssid, config.wifi.pass)
tmr.alarm(0, 1000, 1, wait_for_network)
|
local gauntlet_data = require "gauntlet_data"
local CHIP_DATA = require "defs.chip_data_defs"
local CHIP_ID = require "defs.chip_id_defs"
local CHIP_CODE = require "defs.chip_code_defs"
local CHIP = require "defs.chip_defs"
local ELEMENT_DEFS = require "defs.entity_element_defs"
local GENERIC_DEFS = require "defs.generic_defs"
local BOUNTY_FRAME_PERFECT = {
NAME = "Bounty: Frame Perfect",
REMOVE_AFTER_ACTIVATION = 1,
DOUBLE_RARITY = 1
}
function shuffle(tbl)
size = #tbl
for i = size, 1, -1 do
local rand = gauntlet_data.math.random_buff_activation(size)
tbl[i], tbl[rand] = tbl[rand], tbl[i]
end
return tbl
end
local REWARD_STRING = "LootBox (Drop)"
local NUM_SECONDS = 40
local NUM_BATTLES = 10
local HP_RATIO = 0.2
function BOUNTY_FRAME_PERFECT:activate(current_round)
self.fight_hp_string = ""
self.last_known_hp = nil
self.last_max_hp = 0
self.fight_counter = 0
self.total_fight_counter = 0
end
function BOUNTY_FRAME_PERFECT:deactivate(current_round)
end
function BOUNTY_FRAME_PERFECT:get_description(current_round)
return "Finish " .. tostring(NUM_BATTLES) .. " battles in under " .. tostring(NUM_SECONDS) .. " seconds:\nReward: " .. REWARD_STRING
end
function BOUNTY_FRAME_PERFECT:get_brief_description()
if self.total_fight_counter ~= 0 then
return BOUNTY_FRAME_PERFECT.NAME .. ": " .. tostring(NUM_BATTLES) .. " battles under " ..tostring(NUM_SECONDS) .. "s\n-> " .. REWARD_STRING .. " (Total: " .. self.fight_hp_string .. " / " .. tostring(NUM_BATTLES) .. ", Last: " .. self.last_time_string .. "s)"
else
return BOUNTY_FRAME_PERFECT.NAME .. ": " .. tostring(NUM_BATTLES) .. " battles under " ..tostring(NUM_SECONDS) .. "s\n-> " .. REWARD_STRING
end
end
function BOUNTY_FRAME_PERFECT:on_patch_before_battle_start(state_logic, gauntlet_data)
self.last_round_over_limit = nil
self.last_known_hp = nil
end
function BOUNTY_FRAME_PERFECT:on_first_cust_screen(state_logic, gauntlet_data)
self.last_round_over_limit = nil
self.last_known_hp = nil
self.start_time = os.clock()
end
function BOUNTY_FRAME_PERFECT:on_finish_battle(state_logic, gauntlet_data)
local end_time = os.clock()
self.last_battle_time = end_time - self.start_time
if self.last_battle_time > NUM_SECONDS then
self.last_round_over_limit = 1
end
if self.last_round_over_limit == nil then
self.fight_counter = self.fight_counter + 1
end
self.fight_hp_string = tostring(self.fight_counter)
self.last_time_string = tostring(math.floor(self.last_battle_time))
if self.fight_counter == NUM_BATTLES then
self.ON_PATCH_BEFORE_BATTLE_START_CALLBACK = nil
self.FINISH_BATTLE_CALLBACK = nil
self.UPDATE_CALLBACK = nil
self.reward_chip = 1
end
self.total_fight_counter = self.total_fight_counter + 1
self.last_known_hp = nil
end
function BOUNTY_FRAME_PERFECT:on_chip_drop(state_logic, gauntlet_data)
if self.reward_chip == nil then
return
end
self.ON_CHIP_DROP_CALLBACK = nil
local lootbox = CHIP.lootbox_chips()
for chip_idx = 1, #state_logic.dropped_chips do
if lootbox[chip_idx] == nil then
break
end
state_logic.dropped_chips[chip_idx] = lootbox[chip_idx]
state_logic.dropped_chips[chip_idx].RARITY = 3
end
end
function BOUNTY_FRAME_PERFECT.new()
local new_buff = deepcopy(BOUNTY_FRAME_PERFECT)
new_buff.DESCRIPTION = new_buff:get_description(1)
new_buff.ON_PATCH_BEFORE_BATTLE_START_CALLBACK = 1
new_buff.FINISH_BATTLE_CALLBACK = 1
new_buff.ON_CHIP_DROP_CALLBACK = 1
new_buff.ON_FIRST_CUST_SCREEN_CALLBACK = 1
return deepcopy(new_buff)
end
return BOUNTY_FRAME_PERFECT
|
-- plat
set_config("plat", os.host())
-- project
set_project("co")
-- set xmake minimum version
set_xmakever("2.2.5")
-- set common flags
set_languages("c++11")
set_optimize("faster") -- faster: -O2 fastest: -O3 none: -O0
set_warnings("all") -- -Wall
set_symbols("debug") -- dbg symbols
-- check sse/avx
--includes("check_cincludes.lua")
--check_cincludes("CO_AVX", "immintrin.h")
--check_cincludes("CO_SSE2", "emmintrin.h")
--check_cincludes("CO_SSE42", "nmmintrin.h")
--add_vectorexts("avx")
if is_plat("macosx", "linux") then
add_cxflags("-g3", "-Wno-narrowing")
if is_plat("macosx") then
add_cxflags("-fno-pie")
end
add_syslinks("pthread", "dl")
end
if is_plat("windows") then
add_cxflags("-MD", "-EHsc")
end
-- include dir
add_includedirs("include")
-- install header files
add_installfiles("(include/**)", {prefixdir = ""})
add_installfiles("*.md", {prefixdir = "include/co"})
-- include sub-projects
includes("src", "gen", "test", "unitest")
|
local Event = require("api.Event")
-- TODO
-- local function archetype_on_spawn_monster(map)
-- end
local function archetype_starting_pos(map, params, result)
local archetype = map:archetype()
if not (archetype and archetype.starting_pos) then
return result
end
if type(archetype.starting_pos) == "table" then
local pos = archetype.starting_pos
assert(pos.x and pos.y, "`starting_pos` must declare `x` and `y` fields if table")
return pos
end
local chara = params.chara
local prev_map = params.prev_map
local feat = params.feat
return archetype.starting_pos(map, chara, prev_map, feat)
end
Event.register("base.calc_map_starting_pos", "Archetype callback (starting_pos)", archetype_starting_pos, {priority = 200000})
local function archetype_on_map_renew_minor(map, params)
local archetype = map:archetype()
if not (archetype and archetype.on_map_renew_minor) then
return
end
archetype.on_map_renew_minor(map, params)
end
Event.register("base.on_map_renew_minor", "Archetype callback (on_map_renew_minor)", archetype_on_map_renew_minor, {priority = 200000})
local function archetype_on_map_renew_major(map, params)
local archetype = map:archetype()
if not (archetype and archetype.on_map_renew_major) then
return
end
archetype.on_map_renew_major(map, params)
end
Event.register("base.on_map_renew_major", "Archetype callback (on_map_renew_major)", archetype_on_map_renew_major, {priority = 200000})
local function archetype_on_map_renew_geometry(map, params)
local archetype = map:archetype()
if not (archetype and archetype.on_map_renew_geometry) then
return
end
archetype.on_map_renew_geometry(map, params)
end
Event.register("base.on_map_renew_geometry", "Archetype callback (on_map_renew_geometry)", archetype_on_map_renew_geometry, {priority = 200000})
local function archetype_on_map_loaded_events(map, params)
local archetype = map:archetype()
if not (archetype and archetype.on_map_loaded) then
return
end
archetype.on_map_loaded(map, params)
end
Event.register("base.on_map_loaded", "Archetype callback (on_map_loaded)", archetype_on_map_loaded_events, {priority = 200000})
local function archetype_on_map_entered(map, params)
local archetype = map:archetype()
if not (archetype and archetype.on_map_entered) then
return
end
archetype.on_map_entered(map, params)
end
Event.register("base.on_map_entered", "Archetype callback (on_map_entered)", archetype_on_map_entered, {priority = 200000})
local function archetype_on_map_pass_turn(chara, params, result)
-- >>>>>>>> shade2/main.hsp:733 ..
local map = chara:current_map()
if not chara:is_player() or not map then
return result
end
if params.is_first_turn then
return result
end
local archetype = map:archetype()
if not (archetype and archetype.on_map_pass_turn) then
return
end
archetype.on_map_pass_turn(map, params)
-- <<<<<<<< shade2/main.hsp:735 ..
end
Event.register("base.before_chara_turn_start", "Archetype callback (on_map_pass_turn)", archetype_on_map_pass_turn, {priority = 200000})
|
include("shared.lua")
function ENT:Draw()
self:DrawModel()
local angle = LocalPlayer():EyeAngles()
angle:RotateAroundAxis( angle:Forward(), 90 )
angle:RotateAroundAxis( angle:Right(), 90 )
local text = "Artifact"
surface.SetFont( "se_NPCFont" )
local width, _ = surface.GetTextSize( text )
cam.Start3D2D(self:GetPos() + Vector(0, 0, 25), angle, 0.2)
draw.SimpleText(text, "se_NPCFont", -width / 2, 0, Color(200, 200, 200, 255), 0, 0, TEXT_ALIGN_CENTER);
cam.End3D2D()
end
|
--[[--------------------------------------------------------------------------
Improved Anti-Noclip
File name:
antinoclip_improved.lua
Author:
- Original :: RabidToaster (STEAM_0:1:9334395)
- Rewritten :: Mista Tea (STEAM_0:0:27507323)
Changelog:
----------------------------------------------------------------------------]]
local mode = TOOL.Mode -- defined by the name of this file (default should be antinoclip_improved)
--[[--------------------------------------------------------------------------
-- Modules & Dependencies
--------------------------------------------------------------------------]]--
-- needed for localization support (depends on GMod locale: "gmod_language")
include( "improvedanc/localify.lua" )
localify.LoadSharedFile( "improvedanc/localization.lua" ) -- loads the file containing localized phrases
local L = localify.Localize -- used for translating string tokens into localized phrases
local prefix = "#tool."..mode.."." -- prefix used for this tool's localization tokens
-- needed for noclip handler functions
include( "improvedanc/improvedanc.lua" )
improvedanc.SetDefaultEffect( "bounce" )
improvedanc.SetDefaultAffect( "ignore_self" )
--[[--------------------------------------------------------------------------
-- Localized Functions & Variables
--------------------------------------------------------------------------]]--
-- localizing global functions/tables is an encouraged practice that improves code efficiency,
-- since accessing a local value is considerably faster than a global value
local net = net
local hook = hook
local util = util
local cvars = cvars
local pairs = pairs
local tobool = tobool
local IsValid = IsValid
local surface = surface
local language = language
local GetConVarNumber = GetConVarNumber
-- enums for sending notifications
-- certain gamemodes like DarkRP don't have these enums, so there are hardcoded fallback values in place to fix this
local NOTIFY_GENERIC = NOTIFY_GENERIC or 0
local NOTIFY_ERROR = NOTIFY_ERROR or 1
local NOTIFY_CLEANUP = NOTIFY_CLEANUP or 4
local MIN_NOTIFY_BITS = 3 -- the minimum number of bits needed to send a NOTIFY enum
local NOTIFY_DURATION = 5 -- the number of seconds to display notifications
--[[--------------------------------------------------------------------------
-- Tool Settings
--------------------------------------------------------------------------]]--
TOOL.Name = L(prefix.."name")
TOOL.Category = "Construction"
TOOL.Information = {
"left",
"right",
"reload",
}
if ( CLIENT ) then
--[[--------------------------------------------------------------------------
-- Language Settings
--------------------------------------------------------------------------]]--
language.Add( "tool."..mode..".name", L(prefix.."name") )
language.Add( "tool."..mode..".desc", L(prefix.."desc") )
language.Add( "tool."..mode..".left", L(prefix.."left") )
language.Add( "tool."..mode..".right", L(prefix.."right") )
language.Add( "tool."..mode..".reload", L(prefix.."reload") )
--[[--------------------------------------------------------------------------
-- Net Messages
--------------------------------------------------------------------------]]--
--[[--------------------------------------------------------------------------
-- Net :: <toolmode>_notif( string )
--]]--
net.Receive( mode.."_notif", function( bytes )
notification.AddLegacy( net.ReadString(), net.ReadUInt(MIN_NOTIFY_BITS), NOTIFY_DURATION )
local sound = net.ReadString()
if ( sound ~= "" and GetConVarNumber( mode.."_notifs_sound" ) == 1 ) then surface.PlaySound( sound ) end
end )
--[[--------------------------------------------------------------------------
-- Net :: <toolmode>_error( string )
--]]--
net.Receive( mode.."_error", function( bytes )
surface.PlaySound( "buttons/button10.wav" )
notification.AddLegacy( net.ReadString(), net.ReadUInt(MIN_NOTIFY_BITS), NOTIFY_DURATION )
end )
--[[--------------------------------------------------------------------------
-- CVars
--------------------------------------------------------------------------]]--
TOOL.ClientConVar[ "mode" ] = improvedanc.GetDefaultAffect() or ""
TOOL.ClientConVar[ "notifs"] = "1"
TOOL.ClientConVar[ "notifs_sound" ] = "1"
TOOL.ClientConVar[ "tooltip_show" ] = "0"
TOOL.ClientConVar[ "tooltip_scale" ] = "24"
TOOL.ClientConVar[ "halo" ] = "1"
TOOL.ClientConVar[ "halo_r" ] = "255"
TOOL.ClientConVar[ "halo_g" ] = "0"
TOOL.ClientConVar[ "halo_b" ] = "0"
TOOL.ClientConVar[ "halo_a" ] = "255"
for name, func in pairs( improvedanc.GetEffects() ) do
TOOL.ClientConVar[ name ] = "0"
end
--[[--------------------------------------------------------------------------
-- Client Functions
--------------------------------------------------------------------------]]--
local cvarAddHalo = GetConVar( mode.."_halo" )
local cvarHaloR = GetConVar( mode.."_halo_r" )
local cvarHaloG = GetConVar( mode.."_halo_g" )
local cvarHaloB = GetConVar( mode.."_halo_b" )
local cvarHaloA = GetConVar( mode.."_halo_a" )
function TOOL:Init()
-- setup the fonts we'll be using when drawing the HUD
surface.CreateFont( mode.."_tooltip", { font = "coolvetica", size = GetConVarNumber( mode.."_tooltip_scale", 24 ), weight = 500 } )
cvarAddHalo = GetConVar( mode.."_halo" )
cvarHaloR = GetConVar( mode.."_halo_r" )
cvarHaloG = GetConVar( mode.."_halo_g" )
cvarHaloB = GetConVar( mode.."_halo_b" )
cvarHaloA = GetConVar( mode.."_halo_a" )
end
--[[--------------------------------------------------------------------------
-- ShouldAddHalo(), GetHaloColor()
-- Returns true if the anti-noclip protected props should have halos drawn on them for added visibility.
-- Gets the RGBA values of the halo color.
--]]--
local function ShouldAddHalo() return cvarAddHalo:GetBool() end
local function GetHaloColor() return Color( cvarHaloR:GetInt(), cvarHaloG:GetInt(), cvarHaloB:GetInt(), cvarHaloA:GetInt() ) end
--[[--------------------------------------------------------------------------
-- CVar :: <toolmode>_tooltip_scale( string, string, string )
--
-- Callback function to automatically create a new font with the given scale size.
-- This method is a bit excessive if the player changes the scale thousands of times,
-- but otherwise shouldn't be an issue.
--]]--
cvars.AddChangeCallback( mode.."_tooltip_scale", function( name, old, new )
new = tonumber( new )
if ( not new ) then return false end
surface.CreateFont( mode.."_tooltip", {
font = "coolvetica",
size = (new > 0 and new or 1),
weight = 500,
})
end, mode )
--[[--------------------------------------------------------------------------
-- ComplexText( string, table, table, number, number, number, number, function, color )
--
-- Draws a complex line of text on the screen, allowing multiple colors and a callback
-- function to paint things behind it or change the x,y coordinates.
--]]--
local function ComplexText( font, textTbl, colorTbl, x, y, alignX, alignY, callback, defaultColor )
surface.SetFont( font )
local w, h = 0, 0
local str = ""
for i, text in pairs( textTbl ) do
str = str .. text
w, h = surface.GetTextSize( str )
end
x, y = callback( x, y, w, h ) or x, y
w, h = 0, 0
str = ""
for i, text in pairs( textTbl ) do
draw.SimpleText( text, font, x + w, y, colorTbl[i] or defaultColor or color_white, alignX, alignY )
str = str .. text
w, h = surface.GetTextSize( str )
end
return w, h
end
local COLOR_BLUE = Color( 100, 150, 255 )
local COLOR_TRANSPARENT = Color( 0, 0, 0, 200 )
local font = mode .. "_tooltip"
--[[--------------------------------------------------------------------------
-- DrawHUD (Hook :: HUDPaint)
--
-- Draws the tooltip onto the client's screen whenever they have the improved anti-noclip tool selected.
--]]--
local function DrawHUD()
local ply = LocalPlayer()
if ( not IsValid( ply ) ) then return end
-- if they aren't forcing the tooltip to always show, check if they have the toolgun out and have anti-noclip selected
local wep = ply:GetActiveWeapon()
if ( not tobool( ply:GetInfo( mode.."_tooltip_show" ) ) and (not IsValid( wep ) or wep:GetClass() ~= "gmod_tool" or ply:GetInfo( "gmod_toolmode" ) ~= mode) ) then return end
local tr = ply:GetEyeTrace()
local ent = tr.Entity
-- ignore invalid entities and players
if ( not IsValid( ent ) ) then return end
if ( ent:IsPlayer() ) then return end
-- check if the entity has anti-noclip protection applied to it
if ( ent:GetNWString( "AntiNoClipAffect" ) ~= "" ) then
local pos = (ent:GetPos() + ent:OBBCenter()):ToScreen()
-- draws the multicolored tooltip on the client's screen
ComplexText( font,
{ "Affect: ", ent:GetNWString( "AntiNoClipAffect" ) },
{ color_white, COLOR_BLUE }, pos.x, pos.y, 0, 0,
function( x, y, w, h )
x = x - w/2
draw.RoundedBox( 0, x-10, y-5, w+20, h+10, COLOR_TRANSPARENT )
draw.RoundedBox( 0, x-8, y-3, w+16, h+6, COLOR_TRANSPARENT )
return x, y
end
)
if ( not ShouldAddHalo() ) then return end
halo.Add( {ent}, GetHaloColor() )
end
end
hook.Add( "HUDPaint", mode.."_hud", DrawHUD )
elseif ( SERVER ) then
util.AddNetworkString( mode.."_notif" )
util.AddNetworkString( mode.."_error" )
--[[--------------------------------------------------------------------------
-- TOOL:SendNotif( string )
--
-- Convenience function for sending a notification to the tool owner.
--]]--
function TOOL:SendNotif( str, notify, sound )
if ( not self:ShouldSendNotification() ) then return end
net.Start( mode.."_notif" )
net.WriteString( str )
net.WriteUInt( notify or NOTIFY_GENERIC, MIN_NOTIFY_BITS )
net.WriteString( sound or "" )
net.Send( self:GetOwner() )
end
--[[--------------------------------------------------------------------------
-- TOOL:SendError( str )
--
-- Convenience function for sending an error to the tool owner.
--]]--
function TOOL:SendError( str )
net.Start( mode.."_error" )
net.WriteString( str )
net.WriteUInt( notify or NOTIFY_ERROR, MIN_NOTIFY_BITS )
net.Send( self:GetOwner() )
end
--[[--------------------------------------------------------------------------
-- TOOL:ShouldSendNotification()
--]]--
function TOOL:ShouldSendNotification() return
self:GetClientNumber( "notifs" ) == 1
end
--[[--------------------------------------------------------------------------
-- TOOL:GetAffects()
--]]--
function TOOL:GetAffects() return
self:GetClientInfo( "mode" ) == "" and improvedanc.GetDefaultAffect() or self:GetClientInfo( "mode" )
end
--[[--------------------------------------------------------------------------
-- TOOL:GetEffects()
--]]--
function TOOL:GetEffects()
local tbl = {}
for name, func in pairs( improvedanc.GetEffects() ) do
if ( tobool( self:GetClientNumber( name ) ) ) then
tbl[ name ] = true
end
end
return tbl
end
end
--[[--------------------------------------------------------------------------
-- Tool Functions
--------------------------------------------------------------------------]]--
--[[--------------------------------------------------------------------------
--
-- TOOL:LeftClick( table )
--
--]]--
function TOOL:LeftClick( tr, isRemoving )
local ent = tr.Entity
if ( not IsValid( ent ) ) then return false end -- ignore invalid entities
if ( ent:IsPlayer() ) then return false end -- ignore players
if ( CLIENT ) then return true end -- leave the rest up to the server
if ( hook.Run( "AntiNoClip", self:GetOwner(), ent ) == false ) then return false end
local handler = improvedanc.GetHandler( ent )
if ( isRemoving ) then
if ( not IsValid( handler ) ) then
self:SendError( L(prefix.."notif_no_handler", localify.GetLocale( self:GetOwner() )) )
return false
end
improvedanc.RemoveHandler( ent )
self:SendNotif( L(prefix.."notif_removed", localify.GetLocale( self:GetOwner() )), NOTIFY_ERROR )
else
improvedanc.AddHandler( self:GetOwner(), ent, { affects = self:GetAffects(), effects = self:GetEffects() } )
self:SendNotif( L(prefix.."notif_applied", localify.GetLocale( self:GetOwner() )), NOTIFY_GENERIC, "buttons/button14.wav" )
end
return true
end
--[[--------------------------------------------------------------------------
--
-- TOOL:RightClick( table )
--
--]]--
function TOOL:RightClick( tr )
local ent = tr.Entity
if ( not IsValid( ent ) ) then return false end -- ignore invalid entities
if ( ent:IsPlayer() ) then return false end -- ignore players
if ( CLIENT ) then return true end -- leave the rest up to the server
local handler = improvedanc.GetHandler( ent )
if ( not IsValid( handler ) ) then
self:SendError( L(prefix.."notif_no_handler", localify.GetLocale( self:GetOwner() )) )
return false
end
self:GetOwner():ConCommand( mode.."_mode "..tostring( ( handler:GetNoClipAffects() ) ) )
local effects = handler:GetNoClipEffects()
for name, func in pairs( improvedanc.GetEffects() ) do
self:GetOwner():ConCommand( mode.."_"..name.." "..(effects[name] and "1" or "0") )
end
self:SendNotif( L(prefix.."notif_copied", localify.GetLocale( self:GetOwner() )), NOTIFY_CLEANUP )
return true
end
--[[--------------------------------------------------------------------------
--
-- TOOL:Reload( table )
--
--]]--
function TOOL:Reload( tr )
return self:LeftClick( tr, true )
end
local TOOL = TOOL
--[[--------------------------------------------------------------------------
--
-- TOOL.BuildCPanel( panel )
--
--]]--
local function buildCPanel( cpanel )
-- quick presets for default settings
local presetsDefault = {}
local presetsCvars = {}
for name, value in pairs( TOOL.ClientConVar ) do
presetsDefault[ mode.."_"..name ] = value
presetsCvars[ #presetsCvars + 1 ] = mode.."_"..name
end
local presets = {
Label = "Presets",
MenuButton = 1,
Folder = mode,
Options = {
[L(prefix.."combobox_default")] = presetsDefault
},
CVars = presetsCvars
}
-- populate the table of 'affect' options
local affects = {
Label = L(prefix.."label_affects"),
MenuButton = 0,
Options = {}
}
for name, func in pairs( improvedanc.GetAffects() ) do
affects.Options[L(prefix.."combobox_"..name)] = { [mode.."_mode"] = name }
end
-- populate the table 'effects' checkboxes
local sortedEffects = table.GetKeys( improvedanc.GetEffects() )
table.sort( sortedEffects )
local effectsCheckboxes = {}
for k, name in ipairs( sortedEffects ) do
effectsCheckboxes[ k ] = { Label = L(prefix.."checkbox_"..name), Command = mode .. "_"..name }
end
-- populate the table of valid languages that clients can switch between
local languageOptions = {}
for code, tbl in pairs( localify.GetLocalizations() ) do
if ( not L(prefix.."language_"..code, code) ) then continue end
languageOptions[ L(prefix.."language_"..code, code) ] = { localify_language = code }
end
local languages = {
Label = L(prefix.."label_language"),
MenuButton = 0,
Options = languageOptions,
}
-- listen for changes to the localify language and reload the menu to update the localizations
cvars.AddChangeCallback( "localify_language", function( name, old, new )
local cpanel = controlpanel.Get( mode )
if ( not IsValid( cpanel ) ) then return end
cpanel:ClearControls()
buildCPanel( cpanel )
end, "improvedantinoclip" )
cpanel:AddControl( "ComboBox", languages )
cpanel:ControlHelp( "\n" .. L(prefix.."label_credits") )
cpanel:AddControl( "Label", { Text = L(prefix.."desc") } )
cpanel:AddControl( "ComboBox", presets )
cpanel:ControlHelp( "" )
cpanel:AddControl( "ComboBox", affects )
cpanel:ControlHelp( "" )
for k,v in ipairs( effectsCheckboxes ) do
cpanel:AddControl( "Checkbox", v )
end
cpanel:ControlHelp( "\n" )
cpanel:AddControl( "Slider", { Label = L(prefix.."label_tooltip_scale"), Command = mode.."_tooltip_scale", Type = "Numeric", Min = "1", Max = "128" } )
cpanel:ControlHelp( L(prefix.."help_tooltip_scale") .. "\n" )
cpanel:AddControl( "Checkbox", { Label = L(prefix.."checkbox_tooltip_show"), Command = mode.."_tooltip_show" } )
cpanel:ControlHelp( L(prefix.."help_tooltip_show") )
cpanel:AddControl( "Checkbox", { Label = L(prefix.."checkbox_notifs"), Command = mode.."_notifs" } )
cpanel:ControlHelp( L(prefix.."help_notifs") )
cpanel:AddControl( "Checkbox", { Label = L(prefix.."checkbox_notifs_sound"), Command = mode.."_notifs_sound" } )
cpanel:ControlHelp( L(prefix.."help_notifs_sound") )
cpanel:AddControl( "Checkbox", { Label = L(prefix.."checkbox_halo"), Command = mode.."_halo" } )
cpanel:AddControl( "Color", { Label = L(prefix.."label_halo_color"), Red = mode.."_halo_r", Green = mode.."_halo_g", Blue = mode.."_halo_b", Alpha = mode.."_halo_a" } )
end
TOOL.BuildCPanel = buildCPanel
|
local Paused = false
local CurSel = 1
local cursor_on_window = false
local Choices = {
{
Name = "continue_playing",
Action = function( screen )
screen:PauseGame(false)
end
},
{
Name = "restart_song",
Action = function( screen )
screen:SetPrevScreenName('ScreenStageInformation'):begin_backing_out()
end
},
{
Name = "forfeit_song",
Action = function( screen )
screen:SetPrevScreenName(SelectMusicOrCourse()):begin_backing_out()
end
},
}
if GAMESTATE:IsCourseMode() then
Choices = {
{
Name = "continue_playing",
Action = function( screen )
screen:PauseGame(false)
end
},
{
Name = "skip_song",
Action = function( screen )
screen:PostScreenMessage('SM_NotesEnded', 0)
end
},
{
Name = "forfeit_course",
Action = function( screen )
screen:SetPrevScreenName(SelectMusicOrCourse()):begin_backing_out()
end
},
{
Name = "end_course",
Action = function( screen )
screen:PostScreenMessage('SM_LeaveGameplay', 0)
end
},
}
end
local Selections = Def.ActorFrame{
Name="Selections",
InitCommand=function(self)
-- As this process is starting, we'll already highlight the first option with the color.
self:GetChild(1):playcommand("GainFocus")
end,
OnCommand=function(self)
end,
PlayerHitPauseMessageCommand=function(self, param)
if not Paused then
self:stoptweening()
self:x(SCREEN_CENTER_X)
self:easeoutexpo(0.1)
self:addx(-SCREEN_CENTER_X)
else
self:stoptweening()
self:x(0)
self:easeinexpo(0.1)
self:addx(SCREEN_CENTER_X)
end
end,
}
local function ChangeSel(self,offset)
-- Do not allow cursor to move if we're not in the pause menu.
if not Paused then return end
CurSel = CurSel + offset
if CurSel < 1 then CurSel = 1 end
if CurSel > #Choices then CurSel = #Choices end
for i = 1,#Choices do
self:GetChild("Selections"):GetChild(i):playcommand( i == CurSel and "GainFocus" or "LoseFocus" )
end
end
local ColorTable = LoadModule("Theme.Colors.lua")
local menu_item_height = 64
local menu_spacing= menu_item_height + 12
local menu_bg_width= SCREEN_WIDTH * .2
local menu_text_width= SCREEN_WIDTH * .35
local middlepoint = menu_item_height * #Choices
for i,v in ipairs(Choices) do
Selections[#Selections+1] = Def.ActorFrame {
Name=i,
InitCommand=function(self)
self:y( (- (middlepoint*.6) ) +((menu_item_height + 8)*i))
self:addx(SCREEN_CENTER_X * 0.65 - 36 * (i - 1))
self:addy(SCREEN_CENTER_Y * 0.45)
self:skewx(-0.5)
end,
Def.Quad {
InitCommand=function(self)
self:zoomto(menu_bg_width,menu_item_height):diffuse( ColorTable.Primary )
end
},
Def.ActorFrame {
InitCommand= function(self) self:playcommand("LoseFocus") end,
LoseFocusCommand= function(self) self:diffusealpha(0.2) end,
GainFocusCommand= function(self) self:diffusealpha(0.8) end,
-- Fade BG
Def.Quad {InitCommand=function(self) self:halign(1):faderight(0.9):zoomto(menu_bg_width/2,menu_item_height):diffuse( ColorTable.Elements ) end,},
Def.Quad {InitCommand=function(self) self:halign(0):fadeleft(0.9):zoomto(menu_bg_width/2,menu_item_height):diffuse( ColorTable.Elements ) end,},
-- Stripeys
Def.Quad {InitCommand=function(self) self:y(menu_item_height/2):vertalign(bottom):zoomto(menu_bg_width,menu_item_height*0.11):diffuse( ColorTable.Primary ):diffuserightedge( ColorTable.Secondary ):blend("Add") end,},
Def.Quad {InitCommand=function(self) self:y(-(menu_item_height/2)):vertalign(top):zoomto(menu_bg_width,menu_item_height*0.11):diffuse( ColorTable.Primary ):diffuserightedge( ColorTable.Secondary ):blend("Add") end,},
},
Def.BitmapText{
Font="Common Normal",
Text=THEME:GetString("PauseMenu", v.Name),
InitCommand= function(self)
self:maxwidth(menu_text_width * 0.5)
self:skewx(0.5)
self:diffuse( ColorTable.White ):playcommand("LoseFocus")
end,
LoseFocusCommand= function(self) self:diffusealpha(0.5) end,
GainFocusCommand= function(self) self:diffusealpha(1) end,
}
}
end
return Def.ActorFrame {
OnCommand = function(self)
self:queuecommand('ReportCursor')
end,
ReportCursorCommand = function(self)
if not Paused then
local mousex, mousey = INPUTFILTER:GetMouseX(), INPUTFILTER:GetMouseY()
if not cursor_on_window and (mousex > SCREEN_LEFT and mousex < SCREEN_RIGHT) and (mousey > SCREEN_TOP and mousey < SCREEN_BOTTOM) then
cursor_on_window = true
if PREFSMAN:GetPreference('ShowMouseCursor') then
SCREENMAN:SystemMessage("If you're recording, you might want to move your cursor.")
end
elseif (mousex <= SCREEN_LEFT or mousex >= SCREEN_RIGHT) or (mousey <= SCREEN_TOP or mousey >= SCREEN_BOTTOM) then
cursor_on_window = false
end
end
end,
Def.ActorFrame{
OnCommand=function(self)
SCREENMAN:GetTopScreen():AddInputCallback(LoadModule("Lua.InputSystem.lua")(self))
self:visible(false):Center()
end,
CurrentSongChangedMessageCommand=function(self)
SCREENMAN:GetTopScreen():PauseGame(false)
end,
NonGameBackCommand=function(self)
if not Paused then
SCREENMAN:GetTopScreen():PauseGame(true)
ChangeSel(self,0)
MESSAGEMAN:Broadcast("PlayerHitPause", {pn = self.pn})
self:visible(true)
self:GetChild("Dim"):playcommand("ShowOrHide",{state="show"})
end
Paused = true
end,
StartCommand=function(self)
if Paused then
Choices[CurSel].Action( SCREENMAN:GetTopScreen() )
self:visible(false)
self:GetChild("Dim"):playcommand("ShowOrHide",{state="hide"})
end
Paused = false
end,
MenuLeftCommand=function(self) if Paused then ChangeSel(self,-1) end end,
MenuRightCommand=function(self) if Paused then ChangeSel(self,1) end end,
MenuUpCommand=function(self) if Paused then ChangeSel(self,-1) end end,
MenuDownCommand=function(self) if Paused then ChangeSel(self,1) end end,
Def.Quad{
Name="Dim",
InitCommand=function(self)
self:stretchto(SCREEN_WIDTH*-1,SCREEN_HEIGHT*-1,SCREEN_WIDTH,SCREEN_HEIGHT):diffuse( Color.Black ):diffusealpha(0)
end,
ShowOrHideCommand=function(self,param)
MESSAGEMAN:Broadcast('PauseMenu')
self:stoptweening():linear(0.2):diffusealpha( param.state == "show" and 0.5 or 0 )
end
},
Selections
},
}
|
--氷結界の封魔団
function c73061465.initial_effect(c)
--act limit
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(73061465,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c73061465.cost)
e1:SetOperation(c73061465.operation)
c:RegisterEffect(e1)
end
function c73061465.cfilter(c,e,tp)
if c:IsLocation(LOCATION_HAND) then
return c:IsSetCard(0x2f) and c:IsType(TYPE_MONSTER) and c:IsAbleToGraveAsCost()
else
return e:GetHandler():IsSetCard(0x2f) and c:IsAbleToRemove() and c:IsHasEffect(100340202,tp)
end
end
function c73061465.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c73061465.cfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c73061465.cfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,1,nil,e,tp)
local tc=g:GetFirst()
local te=tc:IsHasEffect(100340202,tp)
if te then
te:UseCountLimit(tp)
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT+REASON_REPLACE)
else
Duel.SendtoGrave(tc,REASON_COST)
end
end
function c73061465.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFacedown() or not c:IsRelateToEffect(e) then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(1,1)
e1:SetValue(c73061465.tgval)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE+RESET_PHASE+PHASE_END,3)
c:RegisterEffect(e1)
end
function c73061465.tgval(e,re,rp)
return re:IsActiveType(TYPE_SPELL) and re:IsHasType(EFFECT_TYPE_ACTIVATE)
end
|
--====================================================================--
-- dmc_wamp.roles
--
--
-- by David McCuskey
-- Documentation: http://docs.davidmccuskey.com/display/docs/dmc_wamp.lua
--====================================================================--
--[[
Copyright (C) 2014 David McCuskey. All Rights Reserved.
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.
--]]
--[[
Wamp support adapted from:
* AutobahnPython (https://github.com/tavendo/AutobahnPython/)
--]]
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
-- Imports
local Objects = require 'lua_objects'
local Utils = require 'lua_utils'
--====================================================================--
-- Subscriber Role Features
--====================================================================--
local roleSubscriberFeatures = {
ROLE = 'subscriber',
features = {}
}
--====================================================================--
-- Subscriber Caller Features
--====================================================================--
local roleCallerFeatures = {
ROLE = 'caller',
features = {}
}
--====================================================================--
-- Roles Facade
--====================================================================--
return {
subscriberFeatures=roleSubscriberFeatures,
callerFeatures=roleCallerFeatures
}
|
--マジェスティ・ヒュペリオン
--Majesty Hyperion
--scripted by XyLeN
function c100312001.initial_effect(c)
aux.AddCodeList(c,56433456)
--spsummon proc
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND+LOCATION_GRAVE)
e1:SetCountLimit(1,100312001+EFFECT_COUNT_CODE_OATH)
e1:SetCondition(c100312001.hspcon)
e1:SetOperation(c100312001.hspop)
c:RegisterEffect(e1)
--reflect damage
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_ALSO_BATTLE_DAMAGE)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(aux.TargetBoolFunction(Card.IsRace,RACE_FAIRY))
c:RegisterEffect(e2)
--banish
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(100312001,0))
e3:SetCategory(CATEGORY_REMOVE)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c100312001.rmcon)
e3:SetCost(c100312001.rmcost)
e3:SetTarget(c100312001.rmtg)
e3:SetOperation(c100312001.rmop)
c:RegisterEffect(e3)
end
function c100312001.spcfilter(c,tp)
return c:IsSetCard(0x44) and (not c:IsLocation(LOCATION_MZONE) or c:IsFaceup())
and c:IsAbleToRemoveAsCost() and Duel.GetMZoneCount(tp,c)>0
end
function c100312001.hspcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.IsExistingMatchingCard(c100312001.spcfilter,tp,LOCATION_HAND+LOCATION_MZONE+LOCATION_GRAVE,0,1,nil,tp)
end
function c100312001.hspop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c100312001.spcfilter,tp,LOCATION_HAND+LOCATION_MZONE+LOCATION_GRAVE,0,1,1,nil,tp)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c100312001.rmcon(e,tp,eg,ep,ev,re,r,rp)
local check=Duel.IsEnvironment(56433456) or Duel.IsExistingMatchingCard(Card.IsCode,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil,56433456)
if check then return e:GetHandler():GetFlagEffect(100312001)<2
else return e:GetHandler():GetFlagEffect(100312001)<1 end
end
function c100312001.costfilter(c,tp)
return c:IsRace(RACE_FAIRY) and c:IsAbleToRemoveAsCost()
and Duel.IsExistingTarget(Card.IsAbleToRemove,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,c)
end
function c100312001.rmcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c100312001.costfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c100312001.costfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,1,nil,tp)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c100312001.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsAbleToRemove() end
if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToRemove,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0)
e:GetHandler():RegisterFlagEffect(100312001,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,0,1)
end
function c100312001.rmop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end
|
--[[
Copyright 2021 Flant CJSC
Licensed under the Deckhouse Platform Enterprise Edition (EE) license. See https://github.com/deckhouse/deckhouse/blob/main/ee/LICENSE
--]]
local _M = {}
local function _send(premature, buffer)
if premature then
return
end
local udp = ngx.socket.udp()
udp:setpeername("127.0.0.1", 9125)
udp:send(buffer)
udp:close()
end
local function _write(buffer, data)
if buffer["len"] + #data > 1472 then
ngx.timer.at(0, _send, table.concat(buffer))
buffer["len"] = 0
local n = #buffer
while n >= 1 do
buffer[n] = nil
n = n - 1
end
end
table.insert(buffer, data)
buffer["len"] = buffer["len"] + #data
end
local function _hist(buffer, metric, value)
-- prometheus statsd exporter divides all values by 1000
_write(buffer, metric .. ":" .. value * 1000 .. "|h\n")
end
local function _count(buffer, metric, value)
_write(buffer, metric .. ":" .. value .. "|c\n")
end
local function _incr(buffer, metric)
_count(buffer, metric, 1)
end
function _M.call()
local buffer = {}
buffer["len"] = 0
local var_server_name = ngx.var.server_name:gsub("^*", "")
-- Миграция 2019-07-19: https://github.com/deckhouse/deckhouse/merge_requests/929
--
-- Эту переменную и ссылки на неё можно будет удалить после миграции на новый формат rewrite-target.
local var_ingress_name = ngx.var.ingress_name:gsub("%-rwr", "")
if var_server_name == "_" then
_incr(buffer, "l#")
else
local content_kind
local var_upstream_x_content_kind = ngx.var.upstream_x_content_kind
local var_upstream_addr = ngx.var.upstream_addr
local var_http_upgrade = ngx.var.http_upgrade
local var_upstream_http_cache_control = ngx.var.upstream_http_cache_control
local var_upstream_http_expires = ngx.var.upstream_http_expires
if var_upstream_x_content_kind then
content_kind = var_upstream_x_content_kind
elseif not var_upstream_addr then
content_kind = 'served-without-upstream'
elseif var_http_upgrade then
content_kind = string.lower(var_http_upgrade)
elseif var_upstream_http_cache_control or var_upstream_http_expires then
local cacheable = true
if var_upstream_http_cache_control then
if string.match(var_upstream_http_cache_control, "no-cache") or string.match(var_upstream_http_cache_control, "no-store") or string.match(var_upstream_http_cache_control, "private") then
cacheable = false
end
end
if var_upstream_http_expires then
local var_upstream_http_expires_parsed = ngx.parse_http_time(var_upstream_http_expires)
if not var_upstream_http_expires_parsed or var_upstream_http_expires_parsed <= ngx.time() then
cacheable = false
end
end
local var_upstream_http_vary = ngx.var.upstream_http_vary
if var_upstream_http_vary and var_upstream_http_vary == "*" then
cacheable = false
end
if ngx.var.upstream_http_set_cookie then
cacheable = false
end
if cacheable then
content_kind = 'cacheable'
else
content_kind = 'non-cacheable'
end
else
content_kind = 'cache-headers-not-present'
end
ngx.var.content_kind = content_kind
local var_namespace = ngx.var.namespace
local overall_key = content_kind .. "#" .. var_namespace .. "#" .. var_server_name
local detail_key = content_kind .. "#" .. var_namespace .. "#" .. var_ingress_name .. "#" .. ngx.var.service_name .. "#" .. ngx.var.service_port .. "#" .. var_server_name .. "#" .. ngx.var.location_path
local backend_key = var_namespace .. "#" .. var_ingress_name .. "#" .. ngx.var.service_name .. "#" .. ngx.var.service_port .. "#" .. var_server_name .. "#" .. ngx.var.location_path
-- requests
local var_scheme = ngx.var.scheme
local var_request_method = ngx.var.request_method
_incr(buffer, "ao#" .. overall_key .. "#" .. var_scheme .. "#" .. var_request_method)
_incr(buffer, "ad#" .. detail_key .. "#" .. var_scheme .. "#" .. var_request_method)
-- responses
local var_status = ngx.var.status
_incr(buffer, "bo#" .. overall_key .. "#" .. var_status)
_incr(buffer, "bd#" .. detail_key .. "#" .. var_status)
-- request time
local var_request_time = tonumber(ngx.var.request_time)
_hist(buffer, "co#" .. overall_key, var_request_time)
_hist(buffer, "cd#" .. detail_key, var_request_time)
-- bytes sent
local var_bytes_sent = ngx.var.bytes_sent
_hist(buffer, "do#" .. overall_key, var_bytes_sent)
_hist(buffer, "dd#" .. detail_key, var_bytes_sent)
-- bytes received (according to https://serverfault.com/questions/346853/logging-request-response-size-in-access-log-of-nginx)
local var_request_length = ngx.var.request_length
_hist(buffer, "eo#" .. overall_key, var_request_length)
_hist(buffer, "ed#" .. detail_key, var_request_length)
-- upstreams
ngx.var.total_upstream_response_time = 0
ngx.var.upstream_retries = 0
if var_upstream_addr then
local backends = {}
for backend in string.gmatch(var_upstream_addr, "([%d.]+):") do
table.insert(backends, backend)
end
local n = 0
local var_upstream_response_time = ngx.var.upstream_response_time
local upstream_response_time = 0.0
local upstream_requests = 0
for t in string.gmatch(var_upstream_response_time, "[%d.]+") do
local response_time = tonumber(t)
n = n + 1
upstream_response_time = upstream_response_time + response_time
upstream_requests = upstream_requests + 1
-- upstream response time (for each backend)
_hist(buffer, "ka#" .. backend_key .. "#" .. backends[n], response_time)
end
ngx.var.total_upstream_response_time = upstream_response_time
-- upstream response time
_hist(buffer, "fo#" .. overall_key, upstream_response_time)
_hist(buffer, "go#" .. overall_key, upstream_response_time)
_hist(buffer, "fd#" .. detail_key, upstream_response_time)
_hist(buffer, "gd#" .. detail_key, upstream_response_time)
local upstream_redirects = 0
for _ in string.gmatch(var_upstream_response_time, ":") do
upstream_redirects = upstream_redirects + 1
end
local upstream_retries = upstream_requests - upstream_redirects - 1
ngx.var.upstream_retries = upstream_retries
if upstream_retries > 0 then
-- upstream retries (count)
_incr(buffer, "ho#" .. overall_key)
_incr(buffer, "hd#" .. detail_key)
-- upstream retries (sum)
_count(buffer, "io#" .. overall_key, upstream_retries)
_count(buffer, "id#" .. detail_key, upstream_retries)
end
n = 0
for status in string.gmatch(ngx.var.upstream_status, "[%d]+") do
-- responses (for each backend)
n = n + 1
_incr(buffer, "kb#" .. backend_key .. "#" .. backends[n] .. "#" .. string.sub(status, 1, 1))
end
n = 0
for upstream_bytes_received in string.gmatch(ngx.var.upstream_bytes_received, "[%d]+") do
-- upstream bytes received (for each backend)
n = n + 1
_count(buffer, "kc#" .. backend_key .. "#" .. backends[n], upstream_bytes_received)
end
end
local geoip_latitude = tonumber(ngx.var.geoip_latitude)
local geoip_longitude = tonumber(ngx.var.geoip_longitude)
if geoip_latitude and geoip_longitude then
GeoHash = require "geohash"
GeoHash.precision(2)
local geohash = GeoHash.encode(geoip_latitude, geoip_longitude)
local place = "Unknown"
local var_geoip_city = ngx.var.geoip_city
local var_geoip_region_name = ngx.var.geoip_region_name
local var_geoip_country_name = ngx.var.geoip_city_country_code
if var_geoip_city then
place = var_geoip_city
elseif var_geoip_region_name then
place = var_geoip_region_name
elseif var_geoip_country_name then
place = var_geoip_country_name
end
-- geohash
_incr(buffer, "jo#" .. overall_key .. "#" .. geohash .. "#" .. place)
end
end
buffer["len"] = nil
ngx.timer.at(0, _send, buffer)
end
return _M
|
-- If LuaRocks is installed, make sure that packages installed through it are
-- found (e.g. lgi). If LuaRocks is not installed, do nothing.
pcall(require, "luarocks.loader")
-- Standard awesome library
local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
-- Widget and layout library
local wibox = require("wibox")
local battery = require("power_widget")
-- Theme handling library
local beautiful = require("beautiful")
-- Notification library
local naughty = require("naughty")
local menubar = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup")
-- Enable hotkeys help widget for VIM and other apps
-- when client with a matching name is opened:
require("awful.hotkeys_popup.keys")
naughty.config.defaults['icon_size'] = 100
-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
naughty.notify({
preset = naughty.config.presets.critical,
title = "Oops, there were errors during startup!",
text = awesome.startup_errors
})
end
-- Handle runtime errors after startup
do
local in_error = false
awesome.connect_signal("debug::error", function(err)
-- Make sure we don't go into an endless error loop
if in_error then
return
end
in_error = true
naughty.notify({
preset = naughty.config.presets.critical,
title = "Oops, an error happened!",
text = tostring(err)
})
in_error = false
end)
end
-- }}}
-- {{{ Variable definitions
-- Themes define colours, icons, font and wallpapers.
--beautiful.init(os.getenv("HOME") .. "/.config/awesome/themes/custom/theme.lua")
beautiful.init(os.getenv("HOME") .. "/.config/awesome/themes/purple/theme.lua")
--beautiful.init(os.getenv("HOME") .. "/.config/awesome/themes/custom/custom_theme.lua")
--beautiful.init(gears.filesystem.get_themes_dir() .. "xresources/theme.lua")
-- This is used later as the default terminal and editor to run.
terminal = "kitty"
editor = os.getenv("EDITOR") or "vim"
editor_cmd = terminal .. " -e " .. editor
-- Default modkey.
-- Usually, Mod4 is the key with a logo between Control and Alt.
-- If you do not like this or do not have such a key,
-- I suggest you to remap Mod4 to another key using xmodmap or other tools.
-- However, you can use another modifier like Mod1, but it may interact with others.
modkey = "Mod4"
-- Table of layouts to cover with awful.layout.inc, order matters.
awful.layout.layouts = {
-- awful.layout.suit.floating,
awful.layout.suit.tile,
-- awful.layout.suit.tile.left,
awful.layout.suit.tile.bottom,
-- awful.layout.suit.tile.top,
-- awful.layout.suit.fair,
-- awful.layout.suit.fair.horizontal,
-- awful.layout.suit.spiral,
-- awful.layout.suit.spiral.dwindle,
awful.layout.suit.max,
-- awful.layout.suit.max.fullscreen,
-- awful.layout.suit.magnifier,
-- awful.layout.suit.corner.nw,
-- awful.layout.suit.corner.ne,
-- awful.layout.suit.corner.sw,
-- awful.layout.suit.corner.se,
}
-- }}}
-- Autostart commands
awful.spawn('nm-applet')
awful.spawn('autorandr --change')
-- {{{ Menu
-- Create a launcher widget and a main menu
myawesomemenu = {
{
"hotkeys", function()
hotkeys_popup.show_help(nil, awful.screen.focused())
end
},
{ "manual", terminal .. " -e man awesome" },
{ "edit config", editor_cmd .. " " .. awesome.conffile },
{ "restart", awesome.restart },
{
"quit", function()
awesome.quit()
end
},
}
mymainmenu = awful.menu({
items = {
{ "awesome", myawesomemenu, beautiful.awesome_icon },
{ "open terminal", terminal }
}
})
mylauncher = awful.widget.launcher({
image = beautiful.awesome_icon,
menu = mymainmenu
})
--power.warning_config = {
-- percentage = 10,
-- message = "The battery is getting low",
-- preset = {
-- shape = gears.shape.rounded_rect,
-- timeout = 12,
-- bg = "#FFFF00",
-- fg = "#000000",
-- },
--}
-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}
-- Keyboard map indicator and switcher
mykeyboardlayout = awful.widget.keyboardlayout()
awful.key({ "Mod1" }, "space", function()
mykeyboardlayout.next_layout();
end)
-- {{{ Wibar
-- Create a textclock widget
mytextclock = wibox.widget.textclock()
mybattery = battery.get_widget(wibox, "BAT1")
-- Create a wibox for each screen and add it
local taglist_buttons = gears.table.join(awful.button({}, 1, function(t)
t:view_only()
end),
awful.button({ modkey }, 1, function(t)
if client.focus then
client.focus:move_to_tag(t)
end
end),
awful.button({}, 3, awful.tag.viewtoggle),
awful.button({ modkey }, 3, function(t)
if client.focus then
client.focus:toggle_tag(t)
end
end),
awful.button({}, 4, function(t)
awful.tag.viewnext(t.screen)
end),
awful.button({}, 5, function(t)
awful.tag.viewprev(t.screen)
end))
local tasklist_buttons = gears.table.join(awful.button({}, 1, function(c)
if c == client.focus then
c.minimized = true
else
c:emit_signal("request::activate",
"tasklist",
{ raise = true })
end
end),
awful.button({}, 3, function()
awful.menu.client_list({ theme = { width = 250 } })
end),
awful.button({}, 4, function()
awful.client.focus.byidx(1)
end),
awful.button({}, 5, function()
awful.client.focus.byidx(-1)
end))
local function set_wallpaper(s)
-- Wallpaper
if beautiful.wallpaper then
local wallpaper = beautiful.wallpaper
-- If wallpaper is a function, call it with the screen
if type(wallpaper) == "function" then
wallpaper = wallpaper(s)
end
gears.wallpaper.maximized(wallpaper, s, true)
end
end
-- Re-set wallpaper when a screen's geometry changes (e.g. different resolution)
screen.connect_signal("property::geometry", set_wallpaper)
layouts = awful.layout.layouts
my_tags = {
tags = {
{
names = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" },
layout = { layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1] },
},
{
names = { "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" },
layout = { layouts[3], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1], layouts[1] },
}
}
}
awful.screen.connect_for_each_screen(function(s)
-- Wallpaper
set_wallpaper(s)
-- Each screen has its own tag table.
local screen_index = s.index
awful.tag(my_tags.tags[screen_index].names, s, my_tags.tags[screen_index].layout)
-- Create a promptbox for each screen
--s.mypromptbox = awful.widget.prompt()
-- Create an imagebox widget which will contain an icon indicating which layout we're using.
-- We need one layoutbox per screen.
s.mylayoutbox = awful.widget.layoutbox(s)
s.mylayoutbox:buttons(gears.table.join(awful.button({}, 1,
function()
awful.layout.inc(1)
end),
awful.button({}, 3, function()
awful.layout.inc(-1)
end),
awful.button({}, 4, function()
awful.layout.inc(1)
end),
awful.button({}, 5, function()
awful.layout.inc(-1)
end)))
-- Create a taglist widget
s.mytaglist = awful.widget.taglist {
screen = s,
-- filter = awful.widget.taglist.filter.all,
filter = function(t) return t.selected or #t:clients() > 0 end,
buttons = taglist_buttons
}
-- Create a tasklist widget
s.mytasklist = awful.widget.tasklist {
screen = s,
filter = awful.widget.tasklist.filter.currenttags,
buttons = tasklist_buttons
}
-- Create the wibox
s.mywibox = awful.wibar({ position = "top", screen = s })
-- Add widgets to the wibox
s.mywibox:setup {
layout = wibox.layout.align.horizontal,
{
-- Left widgets
layout = wibox.layout.fixed.horizontal,
-- mylauncher,
s.mytaglist,
},
s.mytasklist, -- Middle widget
{
-- Right widgets
layout = wibox.layout.fixed.horizontal,
mykeyboardlayout,
wibox.widget.systray(),
mybattery,
mytextclock,
s.mylayoutbox,
},
}
end)
-- }}}
-- {{{ Mouse bindings
root.buttons(gears.table.join(awful.button({}, 3, function()
mymainmenu:toggle()
end),
awful.button({}, 4, awful.tag.viewnext),
awful.button({}, 5, awful.tag.viewprev)))
-- }}}
-- {{{ Key bindings
globalkeys = gears.table.join(awful.key({ modkey, }, "s", hotkeys_popup.show_help,
{ description = "show help", group = "awesome" }),
awful.key({ modkey, }, "Left", awful.tag.viewprev,
{ description = "view previous", group = "tag" }),
awful.key({ modkey, }, "Right", awful.tag.viewnext,
{ description = "view next", group = "tag" }),
awful.key({ modkey, }, "Escape", awful.tag.history.restore,
{ description = "go back", group = "tag" }),
awful.key({ modkey, }, "j",
function()
awful.client.focus.byidx(1)
end,
{ description = "focus next by index", group = "client" }),
awful.key({ modkey, }, "k",
function()
awful.client.focus.byidx(-1)
end,
{ description = "focus previous by index", group = "client" }),
awful.key({ modkey, }, "w", function()
mymainmenu:show()
end,
{ description = "show main menu", group = "awesome" }),
-- Layout manipulation
awful.key({ modkey, "Shift" }, "j", function()
awful.client.swap.byidx(1)
end,
{ description = "swap with next client by index", group = "client" }),
awful.key({ modkey, "Shift" }, "k", function()
awful.client.swap.byidx(-1)
end,
{ description = "swap with previous client by index", group = "client" }),
awful.key({ modkey, "Control" }, "j", function()
awful.screen.focus_relative(1)
end,
{ description = "focus the next screen", group = "screen" }),
awful.key({ modkey, "Control" }, "k", function()
awful.screen.focus_relative(-1)
end,
{ description = "focus the previous screen", group = "screen" }),
awful.key({ modkey, }, "u", awful.client.urgent.jumpto,
{ description = "jump to urgent client", group = "client" }),
awful.key({ modkey, }, "Tab",
function()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end,
{ description = "go back", group = "client" }),
-- Standard program
awful.key({ modkey, }, "Return", function()
awful.spawn(terminal)
end,
{ description = "open a terminal", group = "launcher" }),
awful.key({ modkey, "Control" }, "r", awesome.restart,
{ description = "reload awesome", group = "awesome" }),
awful.key({ modkey, "Shift" }, "e", awesome.quit,
{ description = "quit awesome", group = "awesome" }),
awful.key({ modkey, }, "l", function()
awful.tag.incmwfact(0.05)
end,
{ description = "increase master width factor", group = "layout" }),
awful.key({ modkey, }, "h", function()
awful.tag.incmwfact(-0.05)
end,
{ description = "decrease master width factor", group = "layout" }),
awful.key({ modkey, "Shift" }, "h", function()
awful.tag.incnmaster(1, nil, true)
end,
{ description = "increase the number of master clients", group = "layout" }),
awful.key({ modkey, "Shift" }, "l", function()
awful.tag.incnmaster(-1, nil, true)
end,
{ description = "decrease the number of master clients", group = "layout" }),
awful.key({ modkey, "Control" }, "h", function()
awful.tag.incncol(1, nil, true)
end,
{ description = "increase the number of columns", group = "layout" }),
awful.key({ modkey, "Control" }, "l", function()
awful.tag.incncol(-1, nil, true)
end,
{ description = "decrease the number of columns", group = "layout" }),
awful.key({ modkey, }, "space", function()
awful.layout.inc(1)
end,
{ description = "select next", group = "layout" }),
awful.key({ modkey, "Shift" }, "space", function()
awful.layout.inc(-1)
end,
{ description = "select previous", group = "layout" }),
awful.key({ modkey, "Control" }, "n",
function()
local c = awful.client.restore()
-- Focus restored client
if c then
c:emit_signal("request::activate", "key.unminimize", { raise = true })
end
end,
{ description = "restore minimized", group = "client" }),
--
awful.key({ modkey }, "d", function()
awful.spawn("rofi -show drun")
end,
{ description = "run rofi", group = "launcher" }),
awful.key({ modkey }, "x",
function()
awful.prompt.run {
prompt = "Run Lua code: ",
textbox = awful.screen.focused().mypromptbox.widget,
exe_callback = awful.util.eval,
history_path = awful.util.get_cache_dir() .. "/history_eval"
}
end,
{ description = "lua execute prompt", group = "awesome" }),
awful.key({ modkey}, "c", awful.placement.centered),
-- Menubar
awful.key({ modkey }, "p", function()
menubar.show()
end,
{ description = "show the menubar", group = "launcher" }),
-- Lock screen
awful.key({ modkey, "Control" }, "l", function()
-- awful.spawn("gdmflexiserver")
awful.spawn("xscreensaver-command --lock")
end,
{ description = "Lock the screen", group = "screen" }))
clientkeys = gears.table.join(awful.key({ modkey, }, "f",
function(c)
c.fullscreen = not c.fullscreen
c:raise()
end,
{ description = "toggle fullscreen", group = "client" }),
awful.key({ modkey, "Shift" }, "c", function(c)
c:kill()
end,
{ description = "close", group = "client" }),
awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle,
{ description = "toggle floating", group = "client" }),
awful.key({ modkey, "Control" }, "Return", function(c)
c:swap(awful.client.getmaster())
end,
{ description = "move to master", group = "client" }),
awful.key({ modkey, }, "o", function(c)
c:move_to_screen()
end,
{ description = "move to screen", group = "client" }),
awful.key({ modkey, }, "t", function(c)
c.ontop = not c.ontop
end,
{ description = "toggle keep on top", group = "client" }),
awful.key({ modkey, }, "n",
function(c)
-- The client currently has the input focus, so it cannot be
-- minimized, since minimized clients can't have the focus.
c.minimized = true
end,
{ description = "minimize", group = "client" }),
awful.key({ modkey, }, "m",
function(c)
c.maximized = not c.maximized
c:raise()
end,
{ description = "(un)maximize", group = "client" }),
awful.key({ modkey, "Control" }, "m",
function(c)
c.maximized_vertical = not c.maximized_vertical
c:raise()
end,
{ description = "(un)maximize vertically", group = "client" }),
awful.key({ modkey, "Shift" }, "m",
function(c)
c.maximized_horizontal = not c.maximized_horizontal
c:raise()
end,
{ description = "(un)maximize horizontally", group = "client" }))
-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it work on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, 9 do
globalkeys = gears.table.join(globalkeys,
--View tag only.
awful.key({ modkey }, "" .. i,
function()
local tag = awful.tag.find_by_name(nil, tostring(i))
if tag then
tag:view_only()
end
end,
{ description = "view tag #" .. i, group = "tag" }),
-- Move client to tag.
awful.key({ modkey, "Shift" }, "" .. i,
function()
if client.focus then
local tag = awful.tag.find_by_name(nil, tostring(i))
if tag then
client.focus:move_to_tag(tag)
end
end
end,
{ description = "move focused client to tag #" .. i, group = "tag" }))
end
for i = 11, 19 do
globalkeys = gears.table.join(globalkeys,
-- View tag only.
awful.key({ modkey, "Mod1" }, "" .. (i - 10),
function()
local tag = awful.tag.find_by_name(nil, tostring(i))
if tag then
tag:view_only()
end
end,
{ description = "view tag #" .. i, group = "tag" }),
-- Move client to tag.
awful.key({ "Mod1", modkey, "Shift" }, "" .. (i - 10),
function()
if client.focus then
local tag = awful.tag.find_by_name(nil, tostring(i))
if tag then
client.focus:move_to_tag(tag)
end
end
end,
{ description = "move focused client to tag #" .. i, group = "tag" }))
end
globalkeys = gears.table.join(globalkeys,
--View tag only.
awful.key({ modkey }, "" .. 0,
function()
local tag = awful.tag.find_by_name(nil, tostring(10))
if tag then
tag:view_only()
end
end,
{ description = "view tag #" .. 10, group = "tag" }),
-- Move client to tag.
awful.key({ modkey, "Shift" }, "" .. 0,
function()
if client.focus then
local tag = awful.tag.find_by_name(nil, tostring(10))
if tag then
client.focus:move_to_tag(tag)
end
end
end,
{ description = "move focused client to tag #" .. 10, group = "tag" }))
globalkeys = gears.table.join(globalkeys,
-- View tag only.
awful.key({ modkey, "Mod1" }, "" .. 0,
function()
local tag = awful.tag.find_by_name(nil, tostring(20))
if tag then
tag:view_only()
end
end,
{ description = "view tag #" .. 20, group = "tag" }),
-- Move client to tag.
awful.key({ "Mod1", modkey, "Shift" }, "" .. 0,
function()
if client.focus then
local tag = awful.tag.find_by_name(nil, tostring(20))
if tag then
client.focus:move_to_tag(tag)
end
end
end,
{ description = "move focused client to tag #" .. 20, group = "tag" }))
globalkeys = gears.table.join(globalkeys,
-- Brightness
awful.key({ }, "XF86MonBrightnessDown", function ()
awful.util.spawn("light -U 5") end,
{ description = "Brightness down", group = "screen" }),
awful.key({ }, "XF86MonBrightnessUp", function ()
awful.util.spawn("light -A 5") end,
{ description = "Brightness up", group = "screen" }),
awful.key({ }, "XF86AudioRaiseVolume", function ()
awful.util.spawn("pactl set-sink-volume @DEFAULT_SINK@ +5%") end,
{ description = "Volume up", group = "audio" }),
awful.key({ }, "XF86AudioLowerVolume", function ()
awful.util.spawn("pactl set-sink-volume @DEFAULT_SINK@ -5%") end,
{ description = "Volume down", group = "audio" }),
awful.key({ }, "XF86AudioMute", function ()
awful.util.spawn("pactl set-sink-mute @DEFAULT_SINK@ toggle") end,
{ description = "Mute audio", group = "audio" }),
awful.key({ }, "XF86AudioMicMute", function ()
awful.util.spawn("pactl set-source-mute @DEFAULT_SOURCE@ toggle") end,
{ description = "Mute mic", group = "audio" }),
awful.key({ }, "XF86AudioPlay", function ()
awful.util.spawn("playerctl play-pause") end,
{ description = "Audio play-pause", group = "audio" }),
awful.key({ }, "XF86AudioNext", function ()
awful.util.spawn("playerctl next") end,
{ description = "Audio next", group = "audio" }),
awful.key({ }, "XF86AudioPrev", function ()
awful.util.spawn("playerctl prev") end,
{ description = "Audio prev", group = "audio" }),
awful.key({ "Shift", "Mod1" }, "v", function ()
awful.util.spawn("rofi -modi \"clipboard:greenclip print\" -show clipboard -run-command '{cmd}'") end,
{ description = "Show clipboard selection menu", group = "clipboard" }),
awful.key({ "Shift", "Mod1" }, "p", function ()
awful.util.spawn("rofi-pass") end,
{ description = "Show pass selection menu", group = "password" }),
awful.key({ }, "Print", function ()
awful.util.spawn("flameshot gui") end,
{ description = "Show screenshot tool gui", group = "screen" }),
awful.key({ "Shift" }, "Print", function ()
awful.util.spawn("gnome-screenshot -i") end,
{ description = "Show Gnome screenshot tool gui", group = "screen" }),
awful.key({ modkey, "Control" }, "d", function ()
awful.util.spawn("xrandr --output eDP1 --off") end,
{ description = "Disable laptop screen", group = "screen" }),
awful.key({ modkey, "Control", "Shift" }, "d", function ()
awful.util.spawn("autorandr --change") end,
{ description = "Restore correct full displays layout (run autorandr)", group = "screen" })
)
-- Logic for laptop + external monitor setup
-- Once an external monitor disconnected, all tags should move to laptop display
-- Then an external monitor connected, all tags should move back
--moved_tags = {};
tag.connect_signal("request::screen", function(tag)
for s in screen do
if s ~= tag.screen then
local same_name_tag = awful.tag.find_by_name(s, tag.name)
if same_name_tag then
tag:swap(same_name_tag)
else
tag.screen = s
-- table.insert(moved_tags, tag.name)
end
return
end
end
end)
screen.connect_signal("added", awesome.restart)
-- function(s)
-- for screen_i in screen do
-- if screen_i ~= s then
-- for i, tag in ipairs(screen_i.tags) do
-- local same_tag_new_screen = awful.tag.find_by_name(s, tag.name)
-- if same_tag_new_screen then
-- same_tag_new_screen:swap(tag)
-- tag.volatile = true
-- tag.screen = nil
-- tag:delete()
-- end
-- end
-- for i, moved_tag in ipairs(moved_tags) do
-- local tag_by_name = awful.tag.find_by_name(screen_i, moved_tag)
-- local same_name_tag = awful.tag.find_by_name(s, moved_tag)
-- if same_name_tag then
-- tag_by_name:swap(same_name_tag)
-- tag_by_name:delete()
-- else
-- tag_by_name.screen = s
-- end
--
-- table.remove(moved_tags, i)
-- end
-- end
-- end
-- for s in screen do
-- if s ~= tag.screen then
-- local same_name_tag = awful.tag.find_by_name(s, tag.name)
-- if same_name_tag then
-- tag:swap(same_name_tag)
-- else
-- tag.screen = s
-- table.insert(moved_tags, tag.name)
-- end
-- end
-- end
--end)
clientbuttons = gears.table.join(awful.button({}, 1, function(c)
c:emit_signal("request::activate", "mouse_click", { raise = true })
end),
awful.button({ modkey }, 1, function(c)
c:emit_signal("request::activate", "mouse_click", { raise = true })
awful.mouse.client.move(c)
end),
awful.button({ modkey }, 3, function(c)
c:emit_signal("request::activate", "mouse_click", { raise = true })
awful.mouse.client.resize(c)
end))
-- Set keys
root.keys(globalkeys)
-- }}}
-- {{{ Rules
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
-- All clients will match this rule.
{
rule = {},
properties = {
border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
raise = true,
keys = clientkeys,
buttons = clientbuttons,
screen = awful.screen.preferred,
placement = awful.placement.no_overlap + awful.placement.no_offscreen
}
},
-- Floating clients.
{
rule_any = {
instance = {
"DTA", -- Firefox addon DownThemAll.
"copyq", -- Includes session name in class.
"pinentry",
},
class = {
"Arandr",
".arandr-wrapped",
"Blueman-manager",
"Gpick",
"Kruler",
"MessageWin", -- kalarm.
"Sxiv",
"Wpa_gui",
"veromix",
"xtightvncviewer",
"jetbrains-toolbox",
"JetBrains Toolbox"
},
-- Note that the name property shown in xprop might be set slightly after creation of the client
-- and the name shown there might not match defined rules here.
name = {
"Event Tester", -- xev.
"JetBrains Toolbox"
},
role = {
"AlarmWindow", -- Thunderbird's calendar.
"ConfigManager", -- Thunderbird's about:config.
"pop-up", -- e.g. Google Chrome's (detached) Developer Tools.
}
},
properties = {
floating = true,
placement = awful.placement.centered
}
},
-- Add titlebars to normal clients and dialogs
--{ rule_any = {type = { "normal", "dialog" }
-- }, properties = { titlebars_enabled = true }
--},
-- Remove titlebars
{
rule_any = {
type = { "normal", "dialog" }
},
properties = { titlebars_enabled = false }
},
-- Set Firefox to always map on the tag named "2" on screen 1.
-- { rule = { class = "Firefox" },
-- properties = { screen = 1, tag = "2" } },
}
-- }}}
--
--
-- {{{ Signals
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function(c)
-- Set the windows at the slave,
-- i.e. put it at the end of others instead of setting it master.
-- if not awesome.startup then awful.client.setslave(c) end
if awesome.startup
and not c.size_hints.user_position
and not c.size_hints.program_position then
-- Prevent clients from being unreachable after screen count changes.
awful.placement.no_offscreen(c)
end
end)
-- Add a titlebar if titlebars_enabled is set to true in the rules.
client.connect_signal("request::titlebars", function(c)
-- buttons for the titlebar
local buttons = gears.table.join(awful.button({}, 1, function()
c:emit_signal("request::activate", "titlebar", { raise = true })
awful.mouse.client.move(c)
end),
awful.button({}, 3, function()
c:emit_signal("request::activate", "titlebar", { raise = true })
awful.mouse.client.resize(c)
end))
awful.titlebar(c):setup {
{
-- Left
awful.titlebar.widget.iconwidget(c),
buttons = buttons,
layout = wibox.layout.fixed.horizontal
},
{
-- Middle
{
-- Title
align = "center",
widget = awful.titlebar.widget.titlewidget(c)
},
buttons = buttons,
layout = wibox.layout.flex.horizontal
},
{
-- Right
awful.titlebar.widget.floatingbutton(c),
awful.titlebar.widget.maximizedbutton(c),
awful.titlebar.widget.stickybutton(c),
awful.titlebar.widget.ontopbutton(c),
awful.titlebar.widget.closebutton(c),
layout = wibox.layout.fixed.horizontal()
},
layout = wibox.layout.align.horizontal
}
end)
-- Hide border for floating or not tiling windows
screen.connect_signal("arrange", function (s)
local max = s.selected_tag.layout.name == "max"
local only_one = #s.tiled_clients == 1 -- use tiled_clients so that other floating windows don't affect the count
-- but iterate over clients instead of tiled_clients as tiled_clients doesn't include maximized windows
for _, c in pairs(s.clients) do
if (max or only_one) and not c.floating or c.maximized then
c.border_width = 0
else
c.border_width = beautiful.border_width
end
end
end)
-- Enable sloppy focus, so that focus follows mouse.
client.connect_signal("mouse::enter", function(c)
c:emit_signal("request::activate", "mouse_enter", { raise = false })
end)
client.connect_signal("focus", function(c)
c.border_color = beautiful.border_focus
end)
client.connect_signal("unfocus", function(c)
c.border_color = beautiful.border_normal
end)
-- }}}
|
local C = require('Comment.api')
return {
setup = C.setup,
toggle = C.toggle,
comment = C.comment,
uncomment = C.uncomment,
get_config = C.get_config,
}
|
local anim = {
stand = {x = 0, y = 0},
sit = {x = 1, y = 1},
walk = {x = 2, y = 42},
mine = {x = 43, y = 57},
lay = {x = 58, y = 58},
walk_mine = {x = 59, y = 103},
}
player_api.register_model("nc_player.b3d", {
animation_speed = 57,
animations = anim,
collisionbox = {-0.3, 0.0, -0.3, 0.3, 1.83, 0.3},
stepheight = 0.6,
eye_height = 1.65,
})
minetest.register_on_joinplayer(function(player)
minetest.after(1, function()
player_api.set_model(player, "nc_player.b3d")
player:set_local_animation(
{x = 0, y = 0},
{x = 2, y = 41},
{x = 43, y = 57},
{x = 59, y = 103},
57
)
end)
end)
minetest.register_chatcommand("set_anim", {
description = "Set the player's animation\n" ..
"stand, sit, walk, mine, lay, walk_mine",
func = function(name)
local p = minetest.get_player_by_name(name)
if anim[param] then
p:set_animation(anim[param], 57)
end
end
})
|
data:extend({
{
type = "item",
name = "gcharcoal",
icon = "__base__/graphics/icons/coal.png",
dark_background_icon = "__base__/graphics/icons/coal-dark-background.png",
flags = { "goes-to-main-inventory" },
fuel_category = "chemical",
fuel_value = "7.5MJ",
subgroup = "raw-resource",
order = "b[charcoal]", -- no idea what this does!
stack_size = 50
}
})
|
-- local nk = require("nakama")
-- local user_id = "d598da17-322c-4020-ad9b-1ea848c0b36a"
-- local sender_id = nil -- "nil" for server sent.
-- local content = {
-- text = "更新补偿",
-- awards = {["物品1"] = 10, ["物品2"] = 10},
-- }
-- local subject = "12月23日停机更新补偿"
-- local code = 1
-- local persistent = true
-- nk.notification_send(user_id, subject, content, code, sender_id, persistent)
|
-- TODO
-- you cant craft flowers yet
|
object_tangible_item_beast_converted_baz_nitch_decoration = object_tangible_item_beast_shared_converted_baz_nitch_decoration:new {
}
ObjectTemplates:addTemplate(object_tangible_item_beast_converted_baz_nitch_decoration, "object/tangible/item/beast/converted_baz_nitch_decoration.iff")
|
local Node = {}
Node.__index = Node;
function Node.new(x, y)
local self = setmetatable({
transform = jge.Transform(x, y),
components = {},
components_named = {},
components_draw = {},
components_update = {},
children = {},
groups = {},
layer = 0,
-- child caches so that we know what needs drawn/updated and what doesn't
children_draw = {},
children_update = {},
need_reset_updates = false,
need_reset_draws = false,
_i_am_a_node = true,
_parent = nil,
_paused = false,
_visible = true,
_timescale = 1,
-- A system of caches so that positions can
-- be lazily evaluated for efficiency
_cache_x = x or 0,
_cache_y = y or 0,
_cache_rotation = 0,
-- incremental IDs that correspond to '_id' in 'transform'
-- If IDs are different, then caches need to be recalculated
_self_id = -1,
-- Draw data for previous frame
-- _prev_x = 0,
-- _prev_y = 0,
-- _prev_rot = 0,
-- _prev_scalex = 1,
-- _prev_scaley = 1,
--
-- _lerp_x = x or 0,
-- _lerp_y = y or 0,
-- debug information
_debug = false,
}, Node);
self.transform:set_hook(jge.bind(self._transform_hook, self))
return self;
end
--[[ Debugging functions ]]
local time_count = 1;
function _node_debug_update_real(node, dt)
local ptime = love.timer.getTime()
Node.update_real(node, dt)
local diff = love.timer.getTime() - ptime
dt = love.timer.getRealDelta();
node._debug._u = node._debug._u + diff
node._debug.timer = node._debug.timer + dt
if node._debug.timer >= time_count then
-- local total = node._debug.utime + node._dtime
node._debug.utime = node._debug._u / node._debug.timer
node._debug.dtime = node._debug._d / node._debug.timer
node._debug._d = 0
node._debug._u = 0
node._debug.timer = 0
-- print("UPDATE")
end
end
function _node_debug_update(node, dt)
local ptime = love.timer.getTime()
Node.update(node, dt)
local diff = love.timer.getTime() - ptime
node._debug._u = node._debug._u + diff
end
function _node_debug_draw(node, lerp)
local ptime = love.timer.getTime()
Node.draw(node, lerp)
node._debug._d = node._debug._d + love.timer.getTime() - ptime
end
function Node:set_debug(val)
self._debug = val and (self._debug or {utime = 0, dtime = 0, timer = 0, _u = 0, _d = 0}) or false
if val then
self.update = _node_debug_update
self.draw = _node_debug_draw
self.update_real = _node_debug_update_real
else
self.update = Node.update
self.draw = Node.draw
self.update_real = Node.update_real
end
end
function Node:set_debug_depth(d, val)
if val == nil then val = true end
if d > 0 then
self:set_debug(val);
for _, node in pairs(self.children) do
node:set_debug_depth(d - 1, val)
end
end
end
local function draw_rect_aabb(x1, y1, x2, y2, mode)
love.graphics.rectangle(mode or "fill", x1, y1, x2-x1, y2-y1)
-- love.graphics.setColor(255, 255, 255)
-- love.graphics.rectangle("line", x1, y1, x2-x1, y2-y1)
end
function Node:debug_draw(label, x1, y1, x2, y2)
if not self._debug then return end
x1 = x1 or 8
if not x2 or not y1 or not y2 then
local ww, wh = love.graphics.getDimensions();
y1 = y1 or wh - 20
x2 = x2 or ww - 8
y2 = y2 or y1 + 12
end
local uratio = self._debug.utime
local dratio = self._debug.dtime
love.graphics.setColor(240, 240, 240)
draw_rect_aabb(x1, y1, x2, y2)
-- love.graphics.setColor(0, 0, 0)
-- draw_rect_aabb(x1, y1, x2, y2)
local x_mid = jge.lerp(uratio, x1, x2)
local x_final = jge.lerp(uratio + dratio, x1, x2)
love.graphics.setColor(120, 140, 240)
draw_rect_aabb(x1, y1, x_mid, y2)
love.graphics.setColor(240, 120, 140)
draw_rect_aabb(x_mid, y1, x_final, y2)
love.graphics.setColor(0, 0, 0)
draw_rect_aabb(x_mid, y1, x_mid, y2)
love.graphics.print(label, x1 + 4, y1)
local width = x2 - x1
local height = y2 - y1
-- x1 = x1 + width + 8
-- x2 = x2 + width + 8
-- local height = y2 - y1
for name, node in pairs(self.children) do
if node._debug then
y2 = y2 - height - 8
y1 = y1 - height - 8
-- x1 = x1 + 16
-- local node_time = node._debug.utime + node._debug.dtime
-- local node_ratio = node_time-- / total_time
-- local x2 = x1 + node_ratio * width
node:debug_draw(label .. "/" .. name, x1 + 16, y1, x2, y2)
end
end
end
--[[ Node state functions ]]
function Node:pause()
self._paused = true
end
function Node:unpause()
self._paused = false
end
function Node:hide()
self._visible = false
end
function Node:show()
self._visible = true
end
function Node:set_timescale(scale)
scale = scale or 1
self._timescale = scale
end
function Node:on_remove()
for _, c in pairs(self.components) do
if c.on_remove then c:on_remove() end
end
for _, node in pairs(self.children) do
node:on_remove()
end
end
function Node:on_add()
for _, c in pairs(self.components) do
if c.on_add then c:on_add() end
end
for _, node in pairs(self.children) do
node:on_add()
end
end
-- Group functions
function Node:add_to_group(name)
self.groups[name] = name
end
function Node:remove_from_group(name)
self.groups[name] = nil
end
function Node:is_in_group(name)
return self.groups[name]
end
-- Matrix functions
function Node:get_mat()
if self._parent then
return self._parent:get_mat() * self.transform:get_mat()
else
return self.transform:get_mat()
end
end
function Node:get_mat_inv()
if self._parent then
return self.transform:get_mat_inv() * self._parent:get_mat_inv()
else
return self.transform:get_mat_inv()
end
end
-- Transform functions
function Node:_transform_hook()
self._cache_rotation = self.transform.rotation;
if self:get_parent() then
self._cache_rotation = self._cache_rotation + self:get_parent().transform.rotation
end
self._cache_x, self._cache_y = self:transform_point(0, 0);
for _, c in pairs(self.components) do
if c.on_transform then
c:on_transform(self.transform)
end
end
for _, c in pairs(self.children) do
c:_transform_hook()
end
end
function Node:transform_point(x, y, w) -- local -> global
local mat = self:get_mat()
return mat:transform_point(x, y, w)
end
function Node:transform_point_inv(x, y, w) -- global -> local
local mat = self:get_mat_inv();
return mat:transform_point(x, y, w)
end
function Node:getpos()
return self._cache_x, self._cache_y
end
function Node:getrot()
return self._cache_rotation;
end
--
-- function Node:getdrawpos()
-- return self._lerp_x, self._lerp_y;
-- end
-- Regular functions
-- local val = 100 / math.pi
function Node:update_real(dt)
if self._paused then return end
dt = dt * self._timescale;
-- self:_recalculate();
for i, c in pairs(self.components_update) do
if c.on_update_real then c:on_update_real(dt); end
end
for i, node in pairs(self.children_update) do
node:update_real(dt)
end
end
function Node:_reset_draws()
self.need_reset_draws = true;
if self._parent then self._parent:_reset_draws() end
end
function Node:_reset_updates()
self.need_reset_updates = true;
if self._parent then self._parent:_reset_updates() end
end
function Node:_finalize_reset_updates()
self.components_update = {}
self.children_update = {}
for _,v in pairs(self.components) do
if v.on_update or v.on_update_real then
table.insert(self.components_update, v)
end
end
for _,v in pairs(self.children) do
v:_finalize_reset_updates();
if #v.components_update > 0 then
table.insert(self.children_update, v)
end
end
self.need_reset_updates = false
end
function Node:update(dt)
if self._paused then return end
dt = dt * self._timescale;
-- self._prev_x = self.transform.x
-- self._prev_y = self.transform.y
-- self._prev_scalex = self.transform.scalex
-- self._prev_scaley = self.transform.scaley
-- self._prev_rot = self.transform.rotation
if self.need_reset_updates then
self:_finalize_reset_updates()
end
-- self:_recalculate();
for i, c in pairs(self.components_update) do
if c.on_update then c:on_update(dt); end
end
local children = self.need_reset_updates and self.children or self.children_update
for i, node in pairs(children) do
node:update(dt)
end
end
local function _sort_layers(a, b)
if a.layer ~= b.layer then return a.layer < b.layer end
return tostring(a) < tostring(b)
end
function Node:_finalize_reset_draws()
self.components_draw = {}
self.children_draw = {}
for _,v in pairs(self.components) do
if v.pre_draw or v.on_draw or v.post_draw then
table.insert(self.components_draw, v)
end
end
for _,v in pairs(self.children) do
v:_finalize_reset_draws();
if #v.components_draw > 0 then
table.insert(self.children_draw, v)
end
end
table.sort(self.children_draw, _sort_layers)
self.need_reset_draws = false;
end
function Node:draw(lerp)
if not self._visible then return end
-- local x = self.transform.x
-- local y = self.transform.y
-- local scalex = self.transform.scalex
-- local scaley = self.transform.scaley
-- local rot = self.transform.rotation
--
-- assert(0 <= lerp and lerp <= 1, "Lerp is not between 0 and 1")
--
-- self.transform.x = jge.lerp(lerp, self._prev_x, x)
-- self.transform.y = jge.lerp(lerp, self._prev_y, y)
-- self.transform.scalex = jge.lerp(lerp, self._prev_scalex, scalex)
-- self.transform.scaley = jge.lerp(lerp, self._prev_scaley, scaley)
-- self.transform.rotation = jge.lerp(lerp, self._prev_rot, rot)
--
-- self._lerp_x, self._lerp_y = self.transform:get_translation();
if self.need_reset_draws then
self:_finalize_reset_draws();
end
for i, c in pairs(self.components_draw) do
if c.pre_draw then c:pre_draw(lerp); end
end
self.transform:draw_push();
for i, c in pairs(self.components_draw) do
if c.on_draw then c:on_draw(lerp); end
end
local children = self.need_reset_draws and self.children or self.children_draw
for i, node in pairs(children) do
node:draw(lerp);
end
for i, c in pairs(self.components_draw) do
if c.post_draw then c:post_draw(lerp); end
end
self.transform:draw_pop();
-- self.transform.x = x
-- self.transform.y = y
-- self.transform.scalex = scalex
-- self.transform.scaley = scaley
-- self.transform.rotation = rot
end
-- Children/parent functions
function Node:get_root()
if self._parent then
return self._parent:get_root()
else
return self
end
end
function Node:get_parent_with_component(cname, canretself)
local c = self:get_component(cname);
if canretself ~= false and c then
return self, c
elseif self._parent then
return self._parent:get_parent_with_component(cname, true);
end
end
function Node:add_child(name, child)
if name == nil or type(name) == "table" then
return self:add_child(#self.children+1, name)
end
if not child then
child = Node()
end
if child._parent then
child._parent:remove_child(child);
end
self.children[name] = child
child._parent = self
child:on_add();
self:_reset_updates();
self:_reset_draws();
return child
end
function Node:has_child(name)
return self.children[name]
end
function Node:remove_child(child)
for k,v in pairs(self.children) do
if v == child or k == child then
self.children[k]:on_remove();
self.children[k] = nil
end
end
self:_reset_updates();
self:_reset_draws();
end
function Node:get_node(name)
if name == ".." then return self._parent end
if name == "." then return self end
local pos_s, pos_e = name:find('/');
if pos_s then
local pre, post = name:sub(1,pos_s-1), name:sub(pos_e+1);
local c = pre == "" and self:get_root() or self:get_node(pre);
return c:get_node(post)
else
return self.children[name]
end
end
function Node:get_child(name)
return self.children[name]
end
function Node:get_children_recursive(t)
t = t or {}
for _, child in pairs(self.children) do
table.insert(t, child)
child:get_children_recursive(t)
end
return t
end
function Node:find_node(name, plain)
plain = jge.try_or(plain, true)
for child_name, child_node in pairs(self.children) do
if child_name:find(name, 1, plain) then return child_node end
local ret = child_node:find_node(name, plain)
if ret then return ret end
end
return nil;
end
function Node:find_nodes(name, plain, t)
t = t or {}
plain = jge.try_or(plain, true)
for child_name, child_node in pairs(self.children) do
if child_name:find(name, 1, plain) then
table.insert(t, child_node)
end
child_node:find_nodes(name, plain, t)
end
return t
end
function Node:find_node_group(group)
for _, child in pairs(self.children) do
if child:is_in_group(group) then return child end
local ret = child:find_node_group(group)
if ret then return ret end
end
return nil;
end
function Node:destroy()
if self._parent then self._parent:remove(self) end
end
function Node:get_parent()
return self._parent
end
-- Component functions
function Node:call_signal(cname, fname, recursive, ...)
local recursive = jge.try_or(recursive, false)
for _,c in pairs(self.components) do
if (cname == nil or c._name == cname) and c[fname] then
c[fname](c, ...)
end
end
if recursive == true or (type(recursive) == "number" and recursive > 1) then
local next_recursive = recursive == true and true or recursive - 1
for _, node in pairs(self.children) do
node:call_signal(cname, fname, next_recursive, ...)
end
end
end
function Node:get_component(name)
return self.components_named[name];
end
Node.has_component = Node.get_component;
function Node:get_components_all(name)
local ret = {};
for i, c in pairs(self.components) do
if c._name == name then
table.insert(ret, c)
end
end
return ret
end
function Node:add_component(name, ...)
local c = jge.ncs.Component.instance(name);
table.insert(self.components, c);
self.components_named[name] = c;
c.node = self;
c:on_init(...);
if c.on_add then c:on_add() end
self:_reset_updates();
self:_reset_draws();
return c
end
function Node:_add_component_json(name, jsondata)
local c = jge.ncs.Component.instance(name);
table.insert(self.components, c);
self.components_named[name] = c;
c.node = self;
if c.on_add then c:on_add() end
self:_reset_updates();
self:_reset_draws();
return c
end
function Node:add_component_json(name, jsondata)
local c = self:_add_component_json(name, jsondata)
c:from_json(jsondata)
end
local _contains = function(t, val)
for _,v in pairs(t) do
if v == val then return true end
end
return false
end
function Node:from_json(json, override)
-- load json
if type(json) == "string" then
-- print(json)
-- print("LOADING NODE FROM JSON: " .. tostring(json))
-- json = json:gsub("/[^/%.]+/%.%.", "")
json = jge.fix_path(json)
print("LOADING NODE FROM JSON: " .. tostring(json))
local contents = love.filesystem.read(json)
local pos, err
json,pos,err = jge.json.decode(contents)
if err then error(err) end
end
-- inheritance
if json.inherit then
self:from_json(json.inherit)
end
-- override variables
local override_t = {}
if override then
for ok, ov in pairs(override) do
local target_key = json.override and json.override[ok] or ok
local a, b = target_key:match("([^,]+)%.(.*)")
if a and b then
override_t[a] = override_t[a] or {}
override_t[a][b] = ov
else
print(("Warning: %s is an invalid override!"))
end
end
end
-- load groups
if json.layer then
self.layer = json.layer
end
if json.groups then
for _, name in pairs(json.groups) do
self:add_to_group(name)
end
end
-- load transforms
self.transform:scale(
json.scale or json.sx or json.scalex or 1,
json.scale or json.sy or json.scaley or 1)
self.transform:translate(json.x or 0, json.y or 0)
self.transform:rotate(
json.r or json.rot or json.rotation or json.angle or 0)
-- load components
if json.components then
local t = {}
for k,v in pairs(json.components) do
if type(v) == "string" then
local contents = love.filesystem.read(v)
local json,pos,err = jge.json.decode(contents)
if err then error(err) end
v = json
end
local cname = v.component or k
local override_component = override_t[cname]
if override_component then
for ok, ov in pairs(override_component) do
v[ok] = ov
end
end
local obj = self:_add_component_json(cname, v)
table.insert(t, obj)
obj._depends = v.depends or obj._depends
obj._jsondata = v
end
table.sort(t, function(a, b)
local a_dependson_b = a._depends and _contains(a._depends, b._name) or false
local b_dependson_a = b._depends and _contains(b._depends, a._name) or false
if a_dependson_b and b_dependson_a then
error("Circular dependencies!")
end
if a_dependson_b then
return false
end
if b_dependson_a then
return true
end
return tostring(a) < tostring(b)
end)
for i,v in ipairs(t) do
v:from_json(v._jsondata)
end
end
-- load children
if json.children then
for k,v in pairs(json.children) do
local c = self:add_child(k);
c:from_json(v)
if c.on_add then c:on_add() end
end
end
return self
-- self:_transformed();
end
return setmetatable(Node, {
__call = function(t, ...)
return Node.new(...)
end
})
|
local help = [[
SAW2: best or rest multi-objective optimization.
(c) 2022 Tim Menzies, [email protected]
"I think the highest and lowest points are the important ones.
Anything else is just...in between." ~ Jim Morrison
USAGE: lua saw2.lua [OPTIONS]
OPTIONS:
-b --bins max bins = 16
-s --seed random number seed = 10019
-S --some number of nums to keep = 256
OPTIONS (other):
-f --file where to find data = ../etc/data/auto93.csv
-d --dump dump stack+exit on error = false
-h --help show help = false
-g --go start up action = nothing
Usage of the works is permitted provided that this instrument is
retained with the works, so that any entity that uses the works is
notified of this instrument. DISCLAIMER:THE WORKS ARE WITHOUT WARRANTY. ]]
local function string2thing(x)
x = x:match"^%s*(.-)%s*$"
if x=="true" then return true elseif x=="false" then return false end
return math.tointeger(x) or tonumber(x) or x end
local the={}
help:gsub("\n ([-][^%s]+)[%s]+([-][-]([^%s]+))[^\n]*%s([^%s]+)",function(f1,f2,k,x)
for n,flag in ipairs(arg) do if flag==f1 or flag==f2 then
x = x=="false" and"true" or x=="true" and"false" or arg[n+1] end end
the[k] = string2thing(x) end)
--------------------------------------------------------------------------------
local any,atom,csv,has,many,map,merge,o,oo,obj,ok
local part,patch,per,push,rows,same,slice,sort
local _,GO,RANGE,SOME,NUM,SYM,COLS,ROW,EGS
local R,big,fmt
big = math.huge
R = math.random
fmt = string.format
function same(x) return x end
function push(t,x) t[1+#t]=x; return x end
function sort(t,f) table.sort(#t>0 and t or map(t,same), f); return t end
function map(t,f, u) u={}; for k,v in pairs(t) do u[1+#u]=f(v) end;return u end
function slice(t,i,j,k, u)
u={}; for n=(i or 1), (j or #t),(k or 1) do u[1+#u] = t[n] end return u end
function has(i, defaults, also)
for k,v in pairs(defaults) do i[k] = v end
for k,v in pairs(also or {}) do assert(i[k]~=nil,"unknown:"..k);i[k]=v end end
function csv(src)
src = io.input(src)
return function(line, row)
line=io.read()
if not line then io.close(src) else
row={}; for x in line:gmatch("([^,]+)") do row[1+#row]=string2thing(x) end
return row end end end
function oo(t) print(o(t)) end
function o(t, u)
if #t>0 then return "{"..table.concat(map(t,tostring)," ").."}" else
u={}; for k,v in pairs(t) do u[1+#u] = fmt(":%s %s",k,v) end
return (t.is or "").."{"..table.concat(sort(u)," ").."}" end end
function obj(name, t,new)
function new(kl,...)
local x=setmetatable({},kl); kl.new(x,...); return x end
t = {__tostring=o, is=name or ""}; t.__index=t
_ = t
return setmetatable(t, {__call=new}) end
--------------------------------------------------------------------------------
RANGE=obj"RANGE"
function _.new(i,t) has(i,{at=0, txt="", lo=big, hi= -big, ys=SYM()},t) end
function _.of(i,x) return i.ys.all[x] or 0 end
function _.__lt(i,j) return i.lo < j.lo end
function _.add(i,x,y)
if x=="?" then return x end
if x>i.hi then i.hi=x end
if x<i.lo then i.lo=x end
i.ys:add(y) end
function _.select(i,t, x)
t = t.cells and t.cells or t
x = t[i.pos]
return x=="?" or i.lo == i.hi and i.lo == x or i.lo <= x and x < i.hi end
function _.__tostring(i)
local x, lo, hi = i.txt, i.lo, i.hi
if lo == hi then return fmt("%s == %s",x, lo)
elseif hi == big then return fmt("%s >= %s",x, lo)
elseif lo == -big then return fmt("%s < %s", x, hi)
else return fmt("%s <= %s < %s",lo,x,hi) end end
function _.merged(i,j,n0, k)
if i.at == j.at then
k = i.ys:merged(j.ys,n0)
if k then
return RANGE{at=i.at, txt=i.txt, lo=i.lo, hi=j.hi, ys=k} end end end
--------------------------------------------------------------------------------
SOME=obj"SOME"
function _.new(i) i.all, i.ok, i.n = {}, false,0 end
function _.nums(i) i.all=i.ok and i.all or sort(i.all);i.ok=true;return i.all end
function _.add(i,x)
if x=="?" then return x end
i.n = 1 + i.n
if #i.all < the.some then i.ok=false; push(i.all,x)
elseif R() < the.some/i.n then i.ok=false; i.all[R(#i.all)]=x end end
function _.per(i,p, a)
a = i:nums()
return a[math.max(1, math.min(#a, (p or .5)*#a//1))] end
-------------------------------------------------------------------------------
SYM=obj"SYM"
function _.new(i,t) has(i,{at=0, txt="", n=0, all={}},t) end
function _.add(i,x,n)
if x~="?" then n=n or 1; i.n=i.n+n; i.all[x]=n+(i.all[x] or 0) end end
function _.mid(i, m,x)
m=0; for y,n in pairs(i.all) do if n>m then m,x=n,y end end; return x end
function _.div(i, n,e)
e=0; for k,n in pairs(i.all) do e=e-n/i.n*math.log(n/i.n,2) end ;return e end
function _.merge(i,j,n0, k)
k = SYM{at=i.at, txt=i.txt}
for x,n in pairs(i.all) do k:add(x,n) end
for x,n in pairs(j.all) do k:add(x,n) end
return f end
function _.merged(i,j,n0, k)
n0, k = (n0 or 0), i:merge(j)
if i.n<n0 or j.n<n0 or
(i:div()*i.n+j:div()*j.n)/k.n > k:div() then return k end end
function _.discretize(i,x,bins) return x end
--------------------------------------------------------------------------------
NUM=obj"NUM"
function _.new(i,t)
has(i,{at=0,txt="",lo= big,hi= -big, all=SOME()},t)
i.w = i.txt:find"-$" and -1 or 1 end
function _.mid(i) return i.all:per(.5) end
function _.div(i) return (i.all:per(.9) - i.all:per(.1)) / 2.56 end
function _.norm(i,x) return x=="?" and x or (x-i.lo)/(i.hi - i.lo) end
function _.add(i,x)
if x=="?" then return x end
if x>i.hi then i.hi=x end
if x<i.lo then i.lo=x end
i.all:add(x) end
function _.discretize(i,x,bins, base)
base = (i.hi - i.lo)/bins; return math.floor(x/base + 0.5)*base end
--------------------------------------------------------------------------------
ROW=obj"ROW"
function _.new(i,t) has(i,{cells={},backdrop={}},t) end
function _.__lt(i,j, s1,s2,e,y,a,b)
y = i.backdrop.cols.y
s1, s2, e = 0, 0, math.exp(1)
for _,col in pairs(y) do
a = col:norm(i.cells[col.at])
b = col:norm(j.cells[col.at])
s1= s1 - e^(col.w * (a - b) / #y)
s2= s2 - e^(col.w * (b - a) / #y) end
return s1/#y < s2/#y end
--------------------------------------------------------------------------------
COLS=obj"COLS"
function _.new(i,t, col)
has(i, {all={}, x={}, y={}, names={}},t)
for at,txt in pairs(i.names) do
col = push(i.all, (txt:find"^[A-Z]" and NUM or SYM){at=at, txt=txt})
if not txt:find":$" then
push(txt:find"[-+!]$" and i.y or i.x, col) end end end
--------------------------------------------------------------------------------
EGS=obj"EGS"
function _.new(i) i.rows,i.cols= {},nil end
function _.file(i,file) for row in csv(file) do i:add(row) end; return i end
function _.add(i,row)
if i.cols
then row = push(i.rows, row.cells and row or ROW{backdrop=i, cells=row}).cells
for k,col in pairs(i.cols.all) do col:add(row[col.at]) end
else i.cols = COLS{names=row} end
return i end
function _.mid(i,cs) return map(cs or i.cols.y,function(c)return c:mid() end)end
function _.div(i,cs) return map(cs or i.cols.y,function(c)return c:div() end)end
function _.copy(i,rows, out)
out=EGS():add(i.cols.names)
for _,row in pairs(rows or {}) do out:add(row) end
return out end
local _merge, _xpand, _ranges
function _.ranges(i,one,two, t)
t={}; for _,c in pairs(i.cols.x) do t[c.at]=_ranges(c,one,two) end;return t end
function _ranges(col,yes,no, out,x,d)
out = {}
for _,what in pairs{{rows=yes, klass=true}, {rows=no, klass=false}} do
for _,row in pairs(what.rows) do x = row.cells[col.at]; if x~="?" then
d = col:discretize(x,the.bins)
out[d] = out[d] or RANGE{at=col.at,txt=col.txt,lo=x,hi=x}
out[d]:add(x, what.klass) end end end
return _xpand(_merge(sort(out))) end
function _merge(b4, a,b,c,j,n,tmp)
j,n,tmp = 1,#b4,{}
while j<=n do a, b = b4[j], b4[j+1]
if b then c = a:merged(b); if c then a,j = c,j+1 end end
tmp[#tmp+1] = a
j = j+1 end
return #tmp==#b4 and tmp or _merge(tmp) end
function _xpand(t)
for j=2,#t do t[j].lo=t[j-1].hi end; t[1].lo, t[#t].hi= -big,big; return t end
--------------------------------------------------------------------------------
GO=obj"GO"
function ok(test,msg)
print("", test and "PASS "or "FAIL ", msg or "")
if not test then
GO.fails= GO.fails+1
if the.dump then assert(test,msg) end end end
function _.new(i,todo, defaults,go)
defaults={}; for k,v in pairs(the) do defaults[k]=v end
go={}; for k,_ in pairs(GO) do
if k~="new" and type(GO[k])=="function" then go[1+#go]=k end end
GO.fails = 0
for _,x in pairs(todo=="all" and sort(go) or {todo}) do
for k,v in pairs(defaults) do the[k]=v end
math.randomseed(the.seed)
if GO[x] then print(x); GO[x]() end end
GO.rogue()
os.exit(GO.fails) end
function GO.rogue( t)
t={}; for _,k in pairs{ "_G", "_VERSION", "arg", "assert", "collectgarbage",
"coroutine", "debug", "dofile", "error", "getmetatable", "io", "ipairs",
"load", "loadfile", "math", "next", "os", "package", "pairs", "pcall",
"print", "rawequal", "rawget", "rawlen", "rawset", "require", "select",
"setmetatable", "string", "table", "tonumber", "tostring", "type", "utf8",
"warn", "xpcall"} do t[k]=k end
for k,v in pairs(_ENV) do if not t[k] then print("?",k, type(v)) end end end
function GO.cols()
oo(COLS{names={"Cyldrs", "Acc+"}}) end
function GO.egs( egs,n)
egs = EGS():file(the.file)
sort(egs.rows)
print("all", o(egs:mid()))
n = (#egs.rows)^.5 // 1
print("best",o(egs:copy(slice(egs.rows,1,n)):mid()))
print("rest",o(egs:copy(slice(egs.rows,n+1)):mid())) end
function GO.egs1( egs,best,rest,n)
egs = EGS():file(the.file)
sort(egs.rows)
n = (#egs.rows)^.5 // 1
best = slice(egs.rows, 1, n)
rest = slice(egs.rows, n+1, #egs.rows, (#egs.rows - n)//(3*n))
print("all", o(egs:mid()))
print("best",o(egs:copy(best):mid()))
print("rest",o(egs:copy(rest):mid()))
egs:ranges(best,rest)
end
--------------------------------------------------------------------------------
--xxx replace part with a slice wit one extra art
function part(t,n,lo,hi, u)
lo, hi = 1, hi or #t
u={};for j = lo, hi, (hi-lo)//n do push(u,t[j]) end; return u end
if the.help
then print(help:gsub("%u%u+", "\27[31m%1\27[0m")
:gsub("(%s)([-][-]?[^%s]+)(%s)","%1\27[33m%2\27[0m%3"),"")
else GO(the.go) end
-- | |
-- -= _________ =-
-- ___ ___
-- | )=( |
-- --- ---
-- ###
-- # = # "This ain't chemistry.
-- ####### This is art."
|
-- A simple scene with some miscellaneous geometry.
-- This file is very similar to nonhier.lua, but interposes
-- an additional transformation on the root node.
-- The translation moves the scene, and the position of the camera
-- and lights have been modified accordingly.
mat1 = gr.material({0.7, 1.0, 0.7}, {0.5, 0.7, 0.5}, 25)
mat2 = gr.material({0.5, 0.5, 0.5}, {0.5, 0.7, 0.5}, 25)
mat3 = gr.material({1.0, 0.6, 0.1}, {0.5, 0.7, 0.5}, 25)
mat4 = gr.material({0.7, 0.6, 1.0}, {0.5, 0.4, 0.8}, 25)
scene = gr.node( 'scene' )
scene:translate(0, 0, -800)
s1 = gr.nh_sphere('s1', {0, 0, -400}, 100)
scene:add_child(s1)
s1:set_material(mat1)
s2 = gr.nh_sphere('s2', {200, 50, -100}, 150)
scene:add_child(s2)
s2:set_material(mat1)
s3 = gr.nh_sphere('s3', {0, -1200, -500}, 1000)
scene:add_child(s3)
s3:set_material(mat2)
b1 = gr.nh_box('b1', {-200, -125, 0}, 100)
scene:add_child(b1)
b1:set_material(mat4)
s4 = gr.nh_sphere('s4', {-100, 25, -300}, 50)
scene:add_child(s4)
s4:set_material(mat3)
s5 = gr.nh_sphere('s5', {0, 100, -250}, 25)
scene:add_child(s5)
s5:set_material(mat1)
-- A small stellated dodecahedron.
steldodec = gr.mesh( 'dodec', 'smstdodeca.obj' )
steldodec:set_material(mat3)
scene:add_child(steldodec)
white_light = gr.light({-100.0, 150.0, -400.0}, {0.9, 0.9, 0.9}, {1, 0, 0})
orange_light = gr.light({400.0, 100.0, -650.0}, {0.7, 0.0, 0.7}, {1, 0, 0})
gr.render(scene, 'nonhier2.png', 256, 256,
{0, 0, 0}, {0, 0, -1}, {0, 1, 0}, 50,
{0.3, 0.3, 0.3}, {white_light, orange_light})
|
-- anim8 v1.2.0 - 2012-06
-- Copyright (c) 2011 Enrique García Cota
-- 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 Grid = {}
local _frames = {}
local function assertPositiveInteger(value, name)
if type(value) ~= 'number' then error(("%s should be a number, was %q"):format(name, tostring(value))) end
if value < 1 then error(("%s should be a positive number, was %d"):format(name, value)) end
if value ~= math.floor(value) then error(("%s should be an integer, was %d"):format(name, value)) end
end
local function createFrame(self, x, y)
local fw, fh = self.frameWidth, self.frameHeight
return love.graphics.newQuad(
self.left + (x-1) * fw + x * self.border,
self.top + (y-1) * fh + y * self.border,
fw,
fh,
self.imageWidth,
self.imageHeight
)
end
local function getGridKey(...)
return table.concat( {...} ,'-' )
end
local function getOrCreateFrame(self, x, y)
if x < 1 or x > self.width or y < 1 or y > self.height then
error(("There is no frame for x=%d, y=%d"):format(x, y))
end
local key = self._key
_frames[key] = _frames[key] or {}
_frames[key][x] = _frames[key][x] or {}
_frames[key][x][y] = _frames[key][x][y] or createFrame(self, x, y)
return _frames[key][x][y]
end
local function parseInterval(str)
str = str:gsub(' ', '')
local min, max = str:match("^(%d+)-(%d+)$")
if not min then
min = str:match("^%d+$")
max = min
end
assert(min and max, ("Could not parse interval from %q"):format(str))
min, max = tonumber(min), tonumber(max)
local step = min <= max and 1 or -1
return min, max, step
end
local function parseIntervals(str)
local left, right = str:match("(.+),(.+)")
assert(left and right, ("Could not parse intervals from %q"):format(str))
local minx, maxx, stepx = parseInterval(left)
local miny, maxy, stepy = parseInterval(right)
return minx, maxx, stepx, miny, maxy, stepy
end
local function parseFrames(self, args, result, position)
local current = args[position]
local kind = type(current)
if kind == 'number' then
result[#result + 1] = getOrCreateFrame(self, current, args[position + 1])
return position + 2
elseif kind == 'string' then
local minx, maxx, stepx, miny, maxy, stepy = parseIntervals(current)
for y = miny, maxy, stepy do
for x = minx, maxx, stepx do
result[#result+1] = getOrCreateFrame(self,x,y)
end
end
return position + 1
else
error(("Invalid type: %q (%s)"):format(kind, tostring(args[position])))
end
end
function Grid:getFrames(...)
local args = {...}
local length = #args
local result = {}
local position = 1
while position <= length do
position = parseFrames(self, args, result, position)
end
return result
end
local Gridmt = {
__index = Grid,
__call = Grid.getFrames
}
local function newGrid(frameWidth, frameHeight, imageWidth, imageHeight, left, top, border)
assertPositiveInteger(frameWidth, "frameWidth")
assertPositiveInteger(frameHeight, "frameHeight")
assertPositiveInteger(imageWidth, "imageWidth")
assertPositiveInteger(imageHeight, "imageHeight")
left = left or 0
top = top or 0
border = border or 0
local key = getGridKey(frameWidth, frameHeight, imageWidth, imageHeight, left, top, border)
local grid = setmetatable(
{ frameWidth = frameWidth,
frameHeight = frameHeight,
imageWidth = imageWidth,
imageHeight = imageHeight,
left = left,
top = top,
border = border,
width = math.floor(imageWidth/frameWidth),
height = math.floor(imageHeight/frameHeight),
_key = key
},
Gridmt
)
return grid
end
-----------------------------------------------------------
local Animation = {}
local function cloneArray(arr)
local result = {}
for i=1,#arr do result[i] = arr[i] end
return result
end
local function parseDelays(delays)
local parsedDelays = {}
local tk,min,max,step
for k,v in pairs(delays) do
tk = type(k)
if tk == "number"
then parsedDelays[k] = v
elseif tk == "string" then
min, max, step = parseInterval(k)
for i = min,max,step do parsedDelays[i] = v end
else
error(("Unexpected delay key: [%s]. Expected a number or a string"):format(tostring(k)))
end
end
return parsedDelays
end
local function repeatValue(value, times)
local result = {}
for i=1,times do result[i] = value end
return result
end
local function createDelays(frames, defaultDelay, delays)
local maxFrames = #frames
local result = repeatValue(defaultDelay, maxFrames)
for i,v in pairs(parseDelays(delays)) do
if i > maxFrames then
error(("The delay value %d is too high; there are only %d frames"):format(i, maxFrames))
end
result[i] = v
end
return result
end
local animationModes = {
loop = function(self) self.position = 1 end,
once = function(self)
self.position = #self.frames
self.status = "finished"
end,
bounce = function(self)
self.direction = self.direction * -1
self.position = self.position + self.direction + self.direction
end
}
local Animationmt = { __index = Animation }
local function newAnimation(mode, frames, defaultDelay, delays, flippedH, flippedV)
delays = delays or {}
assert(animationModes[mode], ("%q is not a valid mode"):format(tostring(mode)))
assert(type(defaultDelay) == 'number' and defaultDelay > 0, "defaultDelay must be a positive number" )
assert(type(delays) == 'table', "delays must be a table or nil")
return setmetatable({
mode = mode,
frames = cloneArray(frames),
endSequence = animationModes[mode],
delays = createDelays(frames, defaultDelay, delays),
timer = 0,
position = 1,
direction = 1,
status = "playing",
flippedH = not not flippedH,
flippedV = not not flippedV
},
Animationmt
)
end
function Animation:clone()
return newAnimation(self.mode, self.frames, 1, self.delays, self.flippedH, self.flippedV)
end
function Animation:flipH()
self.flippedH = not self.flippedH
end
function Animation:flipV()
self.flippedV = not self.flippedV
end
function Animation:update(dt)
if self.status ~= "playing" then return end
self.timer = self.timer + dt
while self.timer > self.delays[self.position] do
self.timer = self.timer - self.delays[self.position]
self.position = self.position + self.direction
if self.position < 1 or self.position > #self.frames then
self:endSequence()
end
end
end
function Animation:pause()
self.status = "paused"
end
function Animation:resume()
self.status = "playing"
end
function Animation:gotoFrame(position)
self.position = position
end
function Animation:draw(image, x, y, r, sx, sy, ox, oy, ...)
local frame = self.frames[self.position]
if self.flippedH or self.flippedV then
r,sx,sy,ox,oy = r or 0, sx or 1, sy or 1, ox or 0, oy or 0
local _,_,w,h = frame:getViewport()
if self.flippedH then
sx = sx * -1
ox = w - ox
end
if self.flippedV then
sy = sy * -1
oy = h - oy
end
end
love.graphics.drawq(image, frame, x, y, r, sx, sy, ox, oy, ...)
end
-----------------------------------------------------------
local anim8 = {
newGrid = newGrid,
newAnimation = newAnimation
}
return anim8
|
GPIO16 = 0
GPIO5 = 1
GPIO4 =2
GPIO0 = 3
GPIO2 = 4
GPIO14 = 5
GPIO12 = 6
GPIO13 = 7
GPIO15 = 8
GPIO3 = 9
GPIO1 = 10
GPIO9 = 11
GPIO10 = 12
|
function add(a, adasdas, dfsdf, xzzxc, aewqe, asdas , zxczxc, asdasd, asdas, asdas,sas, as,asd,asd,asd,asd,zxv,qwe,cs,ryert,d,ds,xcv,asfd)
end
|
---@meta
---@class sharemapwriter
local sharemapwriter = {}
---@class sharemapreader
local sharemapreader = {}
---* 一个使用 stm 模块实现的,用于在服务间共享数据的模块
---* 这里使用了 sproto 来描述序列化数据
---* 其内部引用了代表 Lua 的源数据
---* 和由 stm 构造的 stmobj
---@class sharemap
local sharemap = {}
---* 注册 sproto 协议描述文件
function sharemap.register(protofile)
end
---* 将 Lua 数据,按 sproto 描述中的 某一类型进行序列化后,构造 stm 对象
---@param typename string
---@param obj any
---@return sharemapwriter
function sharemap.writer(typename, obj)
end
---* writer 实际上是将一分 Lua 数据,经过 sproto 序列化后,重新放到内存中
function sharemap:commit()
end
---* writer 使用,生成一个指针,用来传递到其他服务
function sharemap:copy()
end
---* reader 使用,若stm对象有更新,将内存重新序列化出来。
function sharemap:update()
end
---* 为一 stm 对象构造一个 reader
---@param typename any
---@param stmcpy any
---@return sharemapreader
function sharemap.reader(typename, stmcpy)
end
---@type stmobj
sharemapwriter.__obj = nil
sharemapwriter.__data = nil
---@type string
sharemapwriter.__typename = nil
sharemapwriter.copy = sharemap.copy
sharemapwriter.commit = sharemap.commit
sharemapreader.__typename = nil
---@type stmobj
sharemapreader.__obj = nil
---反序列化后的数据
sharemapreader.__data = nil
---* 调用此方法,会将内存中的数据重新序列化
sharemapreader.__update = sharemap.update
return sharemap
|
ESX = nil
Citizen.CreateThread(function()
while ESX == nil do
Citizen.Wait(10)
TriggerEvent("esx:getSharedObject", function(obj)
ESX = obj
end)
end
Wait(1000)
while not ESX.IsPlayerLoaded() do
Citizen.Wait(10)
end
Citizen.Wait(2000)
ESX.TriggerServerCallback('new_hud:getConnectedPlayers', function(connectedPlayers)
UpdatePlayerTable(connectedPlayers)
end)
end)
function UpdatePlayerTable(connectedPlayers)
local players = 0 -- Añadir aqui los trabajos
for k,v in pairs(connectedPlayers) do
players = players + 1
end
print(players)
if players == 1 then
TriggerServerEvent("firstSpawn")
end
end
-- Debug printer
function dprint(msg)
if debugMode then
print(msg)
end
end
Citizen.CreateThread(function()
while true do
local vehicle = GetVehiclePedIsEntering(GetPlayerPed(-1))
SetEntityAsMissionEntity(vehicle, true, false)
Citizen.Wait(0)
end
end)
-- AddEventHandler("playerSpawned", function()
-- local onlinePlayers = 0
-- print(onlinePlayers)
-- for i = 0, 127 do
-- if NetworkIsPlayerActive(i) then
-- onlinePlayers = onlinePlayers+1
-- end
-- end
-- if onlinePlayers == 1 then
-- TriggerServerEvent("firstSpawn")
-- dprint('First Spawn Cars')
-- end
-- -- local test = ESX.Game.GetPlayers(false, false, false)
-- print(test)
-- end)
-- Citizen.CreateThread(function()
-- while true do
-- dprint('Empezando loop de testeo..................!')
-- TriggerServerEvent("firstSpawn")
-- Citizen.Wait(intervals.check*1000)
-- break
-- end
-- end)
RegisterNetEvent('spawncar')
AddEventHandler('spawncar', function(veh)
dprint('Aqui spawneando')
dprint(veh.pos)
dprint(veh.owner)
dprint(veh.plate)
dprint(veh.vehicle)
dprint(veh.model)
dprint(veh.fuel)
local owner = veh.owner
local plate = veh.plate
local vehicle = veh.vehicle
local vPos = json.decode(veh.pos)
local fuel = veh.fuel
-- local vHealth = json.decode(veh.health)
dprint('Aqui el modelito')
dprint(tonumber(veh.model))
dprint(vPos)
dprint(vPos.x)
dprint(vPos.y)
dprint(vPos.z)
LoadModel(tonumber(veh.model))
local coche = CreateVehicle(tonumber(veh.model), vPos.x, vPos.y, vPos.z, veh.heading+0.1, true, false)
SetVehicleHasBeenOwnedByPlayer(coche, true)
ESX.Game.SetVehicleProperties(coche, vehicle)
SetEntityAsMissionEntity(coche, true, false)
SetVehicleLivery(coche, veh.livery)
SetVehicleOnGroundProperly(coche)
SetNetworkIdCanMigrate(NetworkGetNetworkIdFromEntity(coche), true)
SetVehicleHasBeenOwnedByPlayer(coche, true)
SetVehicleOnGroundProperly(coche)
SetVehRadioStation(coche, 'OFF')
SetModelAsNoLongerNeeded(coche)
local vehicleLockState = GetVehicleDoorLockStatus(coche)
Citizen.Wait(100)
if vehicleLockState == 1 then
SetVehicleDoorsLocked(coche, 2)
SetVehicleDoorsLockedForAllPlayers(coche, false)
end
Citizen.Wait(100)
if veh["windows"] then
for windowId = 1, 13, 1 do
if veh["windows"][windowId] == false then
SmashVehicleWindow(coche, windowId)
end
end
end
if veh["tyres"] then
for tyreId = 1, 7, 1 do
if veh["tyres"][tyreId] ~= false then
SetVehicleTyreBurst(coche, tyreId, true, 1000)
end
end
end
if veh["doors"] then
for doorId = 0, 5, 1 do
if veh["doors"][doorId] ~= false then
SetVehicleDoorBroken(coche, doorId - 1, true)
end
end
end
Wait(100)
end)
RegisterNetEvent("StopDespawn:update")
AddEventHandler("StopDespawn:update", function(vehicle, estado)
saveVeh(vehicle, estado)
end)
function saveVeh(vehicle, estado)
local pos = {
x = GetEntityCoords(vehicle).x,
y = GetEntityCoords(vehicle).y,
z = GetEntityCoords(vehicle).z
}
local heading = GetEntityHeading(vehicle)
local vehicleProps = ESX.Game.GetVehicleProperties(vehicle)
local playerplate = GetVehicleNumberPlateText(vehicle)
local model = GetEntityModel(vehicle)
local livery = GetVehicleLivery(vehicle)
local fuel = GetVehicleFuelLevel(vehicle)
vehicleProps["tyres"] = {}
vehicleProps["windows"] = {}
vehicleProps["doors"] = {}
for id = 1, 7 do
local tyreId = IsVehicleTyreBurst(vehicle, id, false)
if tyreId then
vehicleProps["tyres"][#vehicleProps["tyres"] + 1] = tyreId
if tyreId == false then
tyreId = IsVehicleTyreBurst(vehicle, id, true)
vehicleProps["tyres"][ #vehicleProps["tyres"]] = tyreId
end
else
vehicleProps["tyres"][#vehicleProps["tyres"] + 1] = false
end
end
for id = 1, 13 do
local windowId = IsVehicleWindowIntact(vehicle, id)
if windowId ~= nil then
vehicleProps["windows"][#vehicleProps["windows"] + 1] = windowId
else
vehicleProps["windows"][#vehicleProps["windows"] + 1] = true
end
end
for id = 0, 5 do
local doorId = IsVehicleDoorDamaged(vehicle, id)
if doorId then
vehicleProps["doors"][#vehicleProps["doors"] + 1] = doorId
else
vehicleProps["doors"][#vehicleProps["doors"] + 1] = false
end
end
dprint(vehicle)
dprint('Player plate: ' .. playerplate)
if string.match(playerplate, "%a%a%a %d%d%d%d") then
local playertype = "player"
dprint('Matricula correcta... Saving')
-- TriggerServerEvent('sd:save', vehicle, model, x, y, z, heading, playerplate)
print(estado)
TriggerServerEvent('sd:savedb', playerplate, pos, heading, playertype, model, estado, livery, fuel)
else
local playertype = "npc"
dprint('Matricula robada...')
end
end
function LoadModel(model)
while not HasModelLoaded(model) do
RequestModel(model)
dprint('loadmodel?')
Citizen.Wait(1)
end
end
|
-- Default keybindings for launching apps in Hyper Mode
--
-- To launch _your_ most commonly-used apps via Hyper Mode, create a copy of
-- this file, save it as `hyper-apps.lua`, and edit the table below to configure
-- your preferred shortcuts.
local bindingsList = {
{ 'e', 'Visual Studio Code' }, -- "E" for "editor"
{ 'f', 'Finder' }, -- "F" for "Finder"
{ 'g', 'Fork' }, -- "G" for "Git GUI"
{ 'j', 'Join' }, -- "J" for "Join"
{ 'n', 'Notion' }, -- "N" for "Notion"
{ 'o', 'Obsidian' }, -- "O" for "Obsidian"
{ 't', 'Todoist'}, -- "T" for "Todoist"
{ 'y', 'YNAB' }, -- "Y" for "YNAB"
{ 'return', 'iTerm' },
}
local personalBindings = {
{ 'b', 'Brave Browser' }, -- "B" for "Browser"
{ 'c', 'Google Chrome' }, -- "C" for "Chrome"
{ 'd', 'Dashlane' }, -- "D" for "Dashlane"
{'x', function()
if hs.application.get("OpenOffice") then
hs.application.launchOrFocus("OpenOffice")
else
hs.application.launchOrFocus("OpenOffice")
hs.timer.doAfter(1, function()
hs.eventtap.keyStroke(null, "s")
end)
end
end},
}
local workBindings = {
{ 'b', 'Google Chrome' }, -- "B" for "Browser"
{ 'c', 'Microsoft Teams' }, -- "C" for "Chat"
{ 'm', 'Microsoft Outlook' }, -- "M" for "eMail"
{ 't', 'Todoist'},
{ 'x', 'Microsoft Excel' }, -- "x" for "Excel"
{ 'z', 'zoom.us' }, -- "Z" for "Zoom"
}
-- Work computer name
if hs.host.localizedName() == "OF014X1C3UJG5JI" then
bindingsList = hs.fnutils.concat(bindingsList, workBindings)
else
bindingsList = hs.fnutils.concat(bindingsList, personalBindings)
end
return bindingsList
|
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local ffi = require("ffi")
local libbcc = require("bcc.libbcc")
local TracerPipe = require("bcc.tracerpipe")
local Table = require("bcc.table")
local Sym = require("bcc.sym")
local Bpf = class("BPF")
Bpf.static.open_kprobes = {}
Bpf.static.open_uprobes = {}
Bpf.static.perf_buffers = {}
Bpf.static.KPROBE_LIMIT = 1000
Bpf.static.tracer_pipe = nil
Bpf.static.DEFAULT_CFLAGS = {
'-D__HAVE_BUILTIN_BSWAP16__',
'-D__HAVE_BUILTIN_BSWAP32__',
'-D__HAVE_BUILTIN_BSWAP64__',
}
function Bpf.static.check_probe_quota(n)
local cur = table.count(Bpf.static.open_kprobes) + table.count(Bpf.static.open_uprobes)
assert(cur + n <= Bpf.static.KPROBE_LIMIT, "number of open probes would exceed quota")
end
function Bpf.static.cleanup()
local function detach_all(probe_type, all_probes)
for key, fd in pairs(all_probes) do
libbcc.bpf_close_perf_event_fd(fd)
-- skip bcc-specific kprobes
if not key:starts("bcc:") then
if probe_type == "kprobes" then
libbcc.bpf_detach_kprobe(key)
elseif probe_type == "uprobes" then
libbcc.bpf_detach_uprobe(key)
end
end
all_probes[key] = nil
end
end
detach_all("kprobes", Bpf.static.open_kprobes)
detach_all("uprobes", Bpf.static.open_uprobes)
for key, perf_buffer in pairs(Bpf.static.perf_buffers) do
libbcc.perf_reader_free(perf_buffer)
Bpf.static.perf_buffers[key] = nil
end
if Bpf.static.tracer_pipe ~= nil then
Bpf.static.tracer_pipe:close()
end
end
function Bpf.static.SymbolCache(pid)
return Sym.create_cache(pid)
end
function Bpf.static.num_open_uprobes()
return table.count(Bpf.static.open_uprobes)
end
function Bpf.static.num_open_kprobes()
return table.count(Bpf.static.open_kprobes)
end
Bpf.static.SCRIPT_ROOT = "./"
function Bpf.static.script_root(root)
local dir, file = root:match'(.*/)(.*)'
Bpf.static.SCRIPT_ROOT = dir or "./"
return Bpf
end
local function _find_file(script_root, filename)
if filename == nil then
return nil
end
if os.exists(filename) then
return filename
end
if not filename:starts("/") then
filename = script_root .. filename
if os.exists(filename) then
return filename
end
end
assert(nil, "failed to find file "..filename.." (root="..script_root..")")
end
function Bpf:initialize(args)
self.funcs = {}
self.tables = {}
if args.usdt and args.text then
args.text = args.usdt:_get_text() .. args.text
end
local cflags = table.join(Bpf.DEFAULT_CFLAGS, args.cflags)
local cflags_ary = ffi.new("const char *[?]", #cflags, cflags)
local llvm_debug = rawget(_G, "LIBBCC_LLVM_DEBUG") or args.debug or 0
assert(type(llvm_debug) == "number")
if args.text then
log.info("\n%s\n", args.text)
self.module = libbcc.bpf_module_create_c_from_string(args.text, llvm_debug, cflags_ary, #cflags, true)
elseif args.src_file then
local src = _find_file(Bpf.SCRIPT_ROOT, args.src_file)
if src:ends(".b") then
local hdr = _find_file(Bpf.SCRIPT_ROOT, args.hdr_file)
self.module = libbcc.bpf_module_create_b(src, hdr, llvm_debug)
else
self.module = libbcc.bpf_module_create_c(src, llvm_debug, cflags_ary, #cflags, true)
end
end
assert(self.module ~= nil, "failed to compile BPF module")
if args.usdt then
args.usdt:_attach_uprobes(self)
end
end
function Bpf:load_funcs(prog_type)
prog_type = prog_type or "BPF_PROG_TYPE_KPROBE"
local result = {}
local fn_count = tonumber(libbcc.bpf_num_functions(self.module))
for i = 0,fn_count-1 do
local name = ffi.string(libbcc.bpf_function_name(self.module, i))
table.insert(result, self:load_func(name, prog_type))
end
return result
end
function Bpf:load_func(fn_name, prog_type)
if self.funcs[fn_name] ~= nil then
return self.funcs[fn_name]
end
assert(libbcc.bpf_function_start(self.module, fn_name) ~= nil,
"unknown program: "..fn_name)
local fd = libbcc.bcc_prog_load(prog_type,
fn_name,
libbcc.bpf_function_start(self.module, fn_name),
libbcc.bpf_function_size(self.module, fn_name),
libbcc.bpf_module_license(self.module),
libbcc.bpf_module_kern_version(self.module),
0, nil, 0)
assert(fd >= 0, "failed to load BPF program "..fn_name)
log.info("loaded %s (%d)", fn_name, fd)
local fn = {bpf=self, name=fn_name, fd=fd}
self.funcs[fn_name] = fn
return fn
end
function Bpf:dump_func(fn_name)
local start = libbcc.bpf_function_start(self.module, fn_name)
assert(start ~= nil, "unknown program")
local len = libbcc.bpf_function_size(self.module, fn_name)
return ffi.string(start, tonumber(len))
end
function Bpf:attach_uprobe(args)
Bpf.check_probe_quota(1)
local path, addr = Sym.check_path_symbol(args.name, args.sym, args.addr, args.pid)
local fn = self:load_func(args.fn_name, 'BPF_PROG_TYPE_KPROBE')
local ptype = args.retprobe and "r" or "p"
local ev_name = string.format("%s_%s_0x%p", ptype, path:gsub("[^%a%d]", "_"), addr)
local retprobe = args.retprobe and 1 or 0
local res = libbcc.bpf_attach_uprobe(fn.fd, retprobe, ev_name, path, addr,
args.pid or -1)
assert(res >= 0, "failed to attach BPF to uprobe")
self:probe_store("uprobe", ev_name, res)
return self
end
function Bpf:attach_kprobe(args)
-- TODO: allow the caller to glob multiple functions together
Bpf.check_probe_quota(1)
local fn = self:load_func(args.fn_name, 'BPF_PROG_TYPE_KPROBE')
local event = args.event or ""
local ptype = args.retprobe and "r" or "p"
local ev_name = string.format("%s_%s", ptype, event:gsub("[%+%.]", "_"))
local offset = args.fn_offset or 0
local retprobe = args.retprobe and 1 or 0
local res = libbcc.bpf_attach_kprobe(fn.fd, retprobe, ev_name, event, offset)
assert(res >= 0, "failed to attach BPF to kprobe")
self:probe_store("kprobe", ev_name, res)
return self
end
function Bpf:pipe()
if Bpf.tracer_pipe == nil then
Bpf.tracer_pipe = TracerPipe:new()
end
return Bpf.tracer_pipe
end
function Bpf:get_table(name, key_type, leaf_type)
if self.tables[name] == nil then
self.tables[name] = Table(self, name, key_type, leaf_type)
end
return self.tables[name]
end
function Bpf:probe_store(t, id, fd)
if t == "kprobe" then
Bpf.open_kprobes[id] = fd
elseif t == "uprobe" then
Bpf.open_uprobes[id] = fd
else
error("unknown probe type '%s'" % t)
end
log.info("%s -> %s", id, fd)
end
function Bpf:perf_buffer_store(id, reader)
Bpf.perf_buffers[id] = reader
log.info("%s -> %s", id, reader)
end
function Bpf:probe_lookup(t, id)
if t == "kprobe" then
return Bpf.open_kprobes[id]
elseif t == "uprobe" then
return Bpf.open_uprobes[id]
else
return nil
end
end
function Bpf:_perf_buffer_array()
local perf_buffer_count = table.count(Bpf.perf_buffers)
local readers = ffi.new("struct perf_reader*[?]", perf_buffer_count)
local n = 0
for _, r in pairs(Bpf.perf_buffers) do
readers[n] = r
n = n + 1
end
assert(n == perf_buffer_count)
return readers, n
end
function Bpf:perf_buffer_poll_loop()
local perf_buffers, perf_buffer_count = self:_perf_buffer_array()
return pcall(function()
while true do
libbcc.perf_reader_poll(perf_buffer_count, perf_buffers, -1)
end
end)
end
function Bpf:kprobe_poll_loop()
return self:perf_buffer_poll_loop()
end
function Bpf:perf_buffer_poll(timeout)
local perf_buffers, perf_buffer_count = self:_perf_buffer_array()
libbcc.perf_reader_poll(perf_buffer_count, perf_buffers, timeout or -1)
end
function Bpf:kprobe_poll(timeout)
self:perf_buffer_poll(timeout)
end
return Bpf
|
local b45 = require("base45")
local function b45_test (data, b45data)
print("Testing: \"" .. data .. "\" == \"" .. b45data .. "\"")
assert(b45.encode(data) == b45data)
assert(b45.decode(b45data) == data)
assert(b45.encode(b45.decode(b45data)) == b45data)
assert(b45.decode(b45.encode(data)) == data)
assert(b45.encode(b45.decode(b45data)) == b45.encode(data))
assert(b45.decode(b45.encode(data)) == b45.decode(b45data))
end
local test_arr = {
{
data = "base-45",
enc_data = "UJCLQE7W581"
},
{
data = "ietf!",
enc_data = "QED8WEX0"
},
{
data = "AB",
enc_data = "BB8"
},
{
data = "Hello!!",
enc_data = "%69 VD92EX0"
}
}
for _, v in pairs(test_arr) do
b45_test(v.data, v.enc_data)
end
print("Success!")
|
local llthreads = require"llthreads"
local utils = require "utils"
local include = utils.thread_init .. [[
local llthreads = require"llthreads"
]]
do
local thread = llthreads.new(include .. [[
error({})
]])
thread:start()
local ok, err = thread:join()
print(ok, err)
assert(not ok)
end
do
local thread = llthreads.new(include .. [[
llthreads.set_logger(function(msg) print("XXX", msg) end)
error({})
]])
thread:start()
local ok, err = thread:join()
print(ok, err)
assert(not ok)
end
do
local thread = llthreads.new(include .. [[
llthreads.set_logger(function(msg) end)
error({})
]])
thread:start()
local ok, err = thread:join()
print(ok, err)
assert(not ok)
end
print("Done!")
|
-- ***************************************************
-- ** Deadly Bar Timers **
-- ** http://www.deadlybossmods.com **
-- ***************************************************
--
-- This addon is written and copyrighted by:
-- * Paul Emmerich (Tandanu @ EU-Aegwynn) (DBM-Core)
-- * Martin Verges (Nitram @ EU-Azshara) (DBM-GUI)
--
-- The localizations are written by:
-- * enGB/enUS: Tandanu http://www.deadlybossmods.com
-- * deDE: Tandanu http://www.deadlybossmods.com
-- * zhCN: Diablohu http://wow.gamespot.com.cn
-- * ruRU: BootWin [email protected]
-- * ruRU: Vampik [email protected]
-- * zhTW: Hman [email protected]
-- * zhTW: Azael/kc10577 [email protected]
-- * koKR: BlueNyx/nBlueWiz [email protected] / [email protected]
-- * esES: Snamor/1nn7erpLaY [email protected]
--
-- Special thanks to:
-- * Arta
-- * Omegal @ US-Whisperwind (continuing mod support for 3.2+)
-- * Tennberg (a lot of fixes in the enGB/enUS localization)
--
--
-- The code of this addon is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License. (see license.txt)
-- All included textures and sounds are copyrighted by their respective owners.
--
--
-- You are free:
-- * to Share ?to copy, distribute, display, and perform the work
-- * to Remix ?to make derivative works
-- Under the following conditions:
-- * Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).
-- * Noncommercial. You may not use this work for commercial purposes.
-- * Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.
---------------
-- Globals --
---------------
DBT = {}
DBT_PersistentOptions = {}
--------------
-- Locals --
--------------
local barPrototype = {}
local unusedBars = {}
local unusedBarObjects = setmetatable({}, {__mode = "kv"})
local updateClickThrough
local options
local setupHandlers
local applyFailed = false
local totalBars = 0
local barIsAnimating = false
local function stringFromTimer(t)
if t <= DBM.Bars:GetOption("Decimal") then
return ("%.1f"):format(t)
elseif t <= 60 then
return ("%d"):format(t)
else
return ("%d:%0.2d"):format(t/60, math.fmod(t, 60))
end
end
local ipairs, pairs, next, type = ipairs, pairs, next, type
local tinsert = table.insert
local GetTime = GetTime
--Hard code STANDARD_TEXT_FONT since skinning mods like to taint it (or worse, set it to nil, wtf?)
local standardFont = STANDARD_TEXT_FONT
if (LOCALE_koKR) then
standardFont = "Fonts\\2002.TTF"
elseif (LOCALE_zhCN) then
standardFont = "Fonts\\ARKai_T.ttf"
elseif (LOCALE_zhTW) then
standardFont = "Fonts\\blei00d.TTF"
elseif (LOCALE_ruRU) then
standardFont = "Fonts\\FRIZQT___CYR.TTF"
else
standardFont = "Fonts\\FRIZQT__.TTF"
end
-----------------------
-- Default Options --
-----------------------
options = {
BarXOffset = {
type = "number",
default = 0,
},
BarYOffset = {
type = "number",
default = 0,
},
HugeBarXOffset = {
type = "number",
default = 0,
},
HugeBarYOffset = {
type = "number",
default = 0,
},
ExpandUpwards = {
type = "boolean",
default = false,
},
ExpandUpwardsLarge = {
type = "boolean",
default = false,
},
Flash = {
type = "boolean",
default = true,
},
Spark = {
type = "boolean",
default = true,
},
Sort = {
type = "boolean",
default = true,
},
ColorByType = {
type = "boolean",
default = true,
},
InlineIcons = {
type = "boolean",
default = true,
},
IconLeft = {
type = "boolean",
default = true,
},
IconRight = {
type = "boolean",
default = false,
},
IconLocked = {
type = "boolean",
default = true,
},
Texture = {
type = "string",
default = "Interface\\AddOns\\DBM-DefaultSkin\\textures\\default.blp",
},
StartColorR = {
type = "number",
default = 1,
},
StartColorG = {
type = "number",
default = 0.7,
},
StartColorB = {
type = "number",
default = 0,
},
EndColorR = {
type = "number",
default = 1,
},
EndColorG = {
type = "number",
default = 0,
},
EndColorB = {
type = "number",
default = 0,
},
--Type 1 (Add)
StartColorAR = {
type = "number",
default = 0.375,
},
StartColorAG = {
type = "number",
default = 0.545,
},
StartColorAB = {
type = "number",
default = 1,
},
EndColorAR = {
type = "number",
default = 0.15,
},
EndColorAG = {
type = "number",
default = 0.385,
},
EndColorAB = {
type = "number",
default = 1,
},
--Type 2 (AOE)
StartColorAER = {
type = "number",
default = 1,
},
StartColorAEG = {
type = "number",
default = 0.466,
},
StartColorAEB = {
type = "number",
default = 0.459,
},
EndColorAER = {
type = "number",
default = 1,
},
EndColorAEG = {
type = "number",
default = 0.043,
},
EndColorAEB = {
type = "number",
default = 0.247,
},
--Type 3 (Targeted)
StartColorDR = {
type = "number",
default = 0.9,
},
StartColorDG = {
type = "number",
default = 0.3,
},
StartColorDB = {
type = "number",
default = 1,
},
EndColorDR = {
type = "number",
default = 1,
},
EndColorDG = {
type = "number",
default = 0,
},
EndColorDB = {
type = "number",
default = 1,
},
--Type 4 (Interrupt)
StartColorIR = {
type = "number",
default = 0.47,
},
StartColorIG = {
type = "number",
default = 0.97,
},
StartColorIB = {
type = "number",
default = 1,
},
EndColorIR = {
type = "number",
default = 0.047,
},
EndColorIG = {
type = "number",
default = 0.88,
},
EndColorIB = {
type = "number",
default = 1,
},
--Type 5 (Role)
StartColorRR = {
type = "number",
default = 0.5,
},
StartColorRG = {
type = "number",
default = 1,
},
StartColorRB = {
type = "number",
default = 0.5,
},
EndColorRR = {
type = "number",
default = 0.11,
},
EndColorRG = {
type = "number",
default = 1,
},
EndColorRB = {
type = "number",
default = 0.3,
},
--Type 6 (Phase)
StartColorPR = {
type = "number",
default = 1,
},
StartColorPG = {
type = "number",
default = 0.776,
},
StartColorPB = {
type = "number",
default = 0.420,
},
EndColorPR = {
type = "number",
default = 0.5,
},
EndColorPG = {
type = "number",
default = 0.41,
},
EndColorPB = {
type = "number",
default = 0.285,
},
--Type 7 (Important/User set only)
StartColorUIR = {
type = "number",
default = 1,
},
StartColorUIG = {
type = "number",
default = 1,
},
StartColorUIB = {
type = "number",
default = 0.0627450980392157,
},
EndColorUIR = {
type = "number",
default = 1,
},
EndColorUIG = {
type = "number",
default = 0.92156862745098,
},
EndColorUIB = {
type = "number",
default = 0.0117647058823529,
},
Bar7ForceLarge = {
type = "boolean",
default = false,
},
Bar7CustomInline = {
type = "boolean",
default = true,
},
TextColorR = {
type = "number",
default = 1,
},
TextColorG = {
type = "number",
default = 1,
},
TextColorB = {
type = "number",
default = 1,
},
DynamicColor = {
type = "boolean",
default = true,
},
Width = {
type = "number",
default = 183,
},
Height = {
type = "number",
default = 20,
},
Decimal = {
type = "number",
default = 60,
},
Scale = {
type = "number",
default = 0.9,
},
HugeBarsEnabled = {
type = "boolean",
default = true,
},
HugeWidth = {
type = "number",
default = 200,
},
HugeScale = {
type = "number",
default = 1.03,
},
TimerPoint = {
type = "string",
default = "TOPRIGHT",
},
TimerX = {
type = "number",
default = -223,
},
TimerY = {
type = "number",
default = -260,
},
HugeTimerPoint = {
type = "string",
default = "CENTER",
},
HugeTimerX = {
type = "number",
default = 0,
},
HugeTimerY = {
type = "number",
default = -120,
},
EnlargeBarTime = {
type = "number",
default = 11,
},
EnlargeBarsPercent = {
type = "number",
default = 0.125,
},
FillUpBars = {
type = "boolean",
default = true,
},
FillUpLargeBars = {
type = "boolean",
default = true,
},
ClickThrough = {
type = "boolean",
default = false,
},
Font = {
type = "string",
default = standardFont,
},
FontFlag = {
type = "string",
default = "None",
},
FontSize = {
type = "number",
default = 10
},
Template = {
type = "string",
default = "DBTBarTemplate"
},
Skin = {
type = "string",
default = "DefaultSkin"
},
BarStyle = {
type = "string",
default = "NoAnim",
},
}
--------------------------
-- Double Linked List --
--------------------------
local DLL = {}
DLL.__index = DLL
function DLL:Append(obj)
if self.first == nil then -- list is empty
self.first = obj
self.last = obj
obj:SetPosition()
elseif not obj.owner.options.Sort then -- list is not emty
obj.prev = self.last
self.last.next = obj
self.last = obj
obj:SetPosition()
else
local ptr = self.first
local barInserted = false
while ptr do
if not barInserted then
if ptr.timer > obj.timer then
if ptr == self.first then
obj.prev = nil
obj.next = self.first
self.first.prev = obj
self.first = obj
obj:SetPosition()
ptr.moving = nil
ptr:SetPosition()
else
obj.prev = ptr.prev
obj.next = ptr
obj.prev.next = obj
obj.next.prev = obj
obj:SetPosition()
ptr.moving = nil
ptr:SetPosition()
end
barInserted = true
end
end
ptr = ptr.next
end
if not barInserted then
obj.prev = self.last
obj.next = nil
self.last.next = obj
self.last = obj
obj:SetPosition()
end
end
return obj
end
function DLL:Remove(obj)
if self.first == nil then -- list is empty...
-- ...meaning the object is not even in the list, nothing we can do here expect for removing the "prev" and "next" entries from obj
elseif self.first == obj and self.last == obj then -- list has only one element
self.first = nil
self.last = nil
elseif self.first == obj then -- trying to remove the first element
self.first = obj.next
self.first.prev = nil
self.first:MoveToNextPosition()
elseif self.last == obj then -- trying to remove the last element
self.last = obj.prev
self.last.next = nil
elseif obj.prev and obj.next then -- trying to remove something in the middle of the list
obj.prev.next, obj.next.prev = obj.next, obj.prev
obj.next:MoveToNextPosition()
end
obj.prev = nil
obj.next = nil
end
function DLL:New()
return setmetatable({
first = nil,
last = nil
}, self)
end
setmetatable(DLL, {__call = DLL.New})
-------------------------------
-- DBT Constructor/Options --
-------------------------------
do
local mt = {__index = DBT}
local optionMT = {
__index = function(t, k)
if options[k] then
return options[k].default
else
return nil
end
end
}
function DBT:New()
local obj = setmetatable(
{
options = setmetatable({}, optionMT),
defaultOptions = setmetatable({}, optionMT),
mainAnchor = CreateFrame("Frame", nil, UIParent),
secAnchor = CreateFrame("Frame", nil, UIParent),
bars = {},
smallBars = DLL(),
hugeBars = DLL()
},
mt
)
obj.mainAnchor:SetHeight(1)
obj.mainAnchor:SetWidth(1)
obj.mainAnchor:SetPoint("TOPRIGHT", 223, -260)
obj.mainAnchor:SetClampedToScreen(true)
obj.mainAnchor:SetMovable(true)
obj.mainAnchor:Show()
obj.secAnchor:SetHeight(1)
obj.secAnchor:SetWidth(1)
obj.secAnchor:SetPoint("CENTER", 0, -120)
obj.secAnchor:SetClampedToScreen(true)
obj.secAnchor:SetMovable(true)
obj.secAnchor:Show()
return obj
end
local function delaySkinCheck(self)
local skins = self:GetSkins()
if not skins then--Returns nil if checked too soon
DBM:Schedule(3, delaySkinCheck, self)
return
end
local enabled = GetAddOnEnableState(UnitName("player"), "DBM-DefaultSkin")
local loaded = "nil"
if skins and self and self.options and self.options.Skin and skins[self.options.Skin] and skins[self.options.Skin].loaded then
loaded = tostring(skins[self.options.Skin].loaded)
else
DBM:Debug("delaySkinCheck detected corrupt skin settings attempting set back to DefaultSkin")
end
if enabled and enabled ~= 0 and loaded ~= "true" then
-- The currently set skin is no longer loaded, revert to DefaultSkin. If enabled (else, person wants textureless bar on purpose)
self:SetSkin("DefaultSkin")
DBM:Debug("delaySkinCheck firing DefaultSkin successful")
end
end
function DBT:LoadOptions(id)
--init
if not DBT_AllPersistentOptions then DBT_AllPersistentOptions = {} end
if not DBT_AllPersistentOptions[_G["DBM_UsedProfile"]] then DBT_AllPersistentOptions[_G["DBM_UsedProfile"]] = {} end
--migrate old options
if DBT_PersistentOptions and DBT_PersistentOptions[id] and not DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] then
DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] = DBT_PersistentOptions[id]
end
DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] = DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] or {}
self.options = setmetatable(DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id], optionMT)
self:Rearrange()
DBM:Schedule(2, delaySkinCheck, self)
if not self.options.Font then--Fix font if it's nil
self.options.Font = standardFont
end
--Repair options from texture conversions
if self.options.Texture == "Interface\\AddOns\\DBM-DefaultSkin\\textures\\default.tga" then
self.options.Texture = "Interface\\AddOns\\DBM-DefaultSkin\\textures\\default.blp"
elseif self.options.Texture == "Interface\\AddOns\\DBM-DefaultSkin\\textures\\smooth.tga" then
self.options.Texture = "Interface\\AddOns\\DBM-DefaultSkin\\textures\\smooth.blp"
elseif self.options.Texture == "Interface\\AddOns\\DBM-DefaultSkin\\textures\\glaze.tga" then
self.options.Texture = "Interface\\AddOns\\DBM-DefaultSkin\\textures\\glaze.blp"
elseif self.options.Texture == "Interface\\AddOns\\DBM-DefaultSkin\\textures\\otravi.tga" then
self.options.Texture = "Interface\\AddOns\\DBM-DefaultSkin\\textures\\otravi.blp"
end
end
function DBT:CreateProfile(id)
if not DBT_AllPersistentOptions[_G["DBM_UsedProfile"]] then DBT_AllPersistentOptions[_G["DBM_UsedProfile"]] = {} end
DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] = DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] or {}
self.options = setmetatable(DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id], optionMT)
self:Rearrange()
end
function DBT:ApplyProfile(id)
if not DBT_AllPersistentOptions[_G["DBM_UsedProfile"]] then return end
self.options = setmetatable(DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id], optionMT)
self:Rearrange()
end
function DBT:CopyProfile(name, id)
if not DBT_AllPersistentOptions[_G["DBM_UsedProfile"]] then DBT_AllPersistentOptions[_G["DBM_UsedProfile"]] = {} end
if not DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] then DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] = {} end
if not DBT_AllPersistentOptions[name] then DBT_AllPersistentOptions[name] = {} end
if not DBT_AllPersistentOptions[name][id] then DBT_AllPersistentOptions[name][id] = {} end
DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id] = DBT_AllPersistentOptions[name][id]
self.options = setmetatable(DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id], optionMT)
self:Rearrange()
end
function DBT:DeleteProfile(name, id)
if name == "Default" or not DBT_AllPersistentOptions[name] then return end
DBT_AllPersistentOptions[name] = nil
self.options = setmetatable(DBT_AllPersistentOptions[_G["DBM_UsedProfile"]][id], optionMT)
self:Rearrange()
end
function DBT:Rearrange()
self.mainAnchor:ClearAllPoints()
self.secAnchor:ClearAllPoints()
self.mainAnchor:SetPoint(self.options.TimerPoint, UIParent, self.options.TimerPoint, self.options.TimerX, self.options.TimerY)
self.secAnchor:SetPoint(self.options.HugeTimerPoint, UIParent, self.options.HugeTimerPoint, self.options.HugeTimerX, self.options.HugeTimerY)
self:ApplyStyle()
end
end
function DBT:SetOption(option, value)
if not options[option] then
error(("Invalid option: %s"):format(tostring(option)), 2)
elseif options[option].type and type(value) ~= options[option].type then
error(("The option %s requires a %s value. (tried to assign a %s value)"):format(tostring(option), tostring(options[option].type), tostring(type(value))), 2)
elseif options[option].checkFunc then
local ok, errMsg = options[option].checkFunc(self, option, value)
if not ok then
error(("Error while setting option %s to %s: %s"):format(tostring(option), tostring(value), tostring(errMsg)), 2)
end
end
local oldValue = self.options[option]
self.options[option] = value
if options[option].onChange then
options[option].onChange(self, value, oldValue)
end
self:ApplyStyle()
end
function DBT:GetOption(option)
return self.options[option]
end
function DBT:GetDefaultOption(option)
return self.defaultOptions[option]
end
-----------------------
-- Bar Constructor --
-----------------------
do
local fCounter = 1
local function createBarFrame(self)
local frame
if unusedBars[#unusedBars] then
frame = unusedBars[#unusedBars]
unusedBars[#unusedBars] = nil
else
frame = CreateFrame("Frame", "DBT_Bar_"..fCounter, self.mainAnchor, self.options.Template)
setupHandlers(frame)
fCounter = fCounter + 1
end
frame:EnableMouse(not self.options.ClickThrough or self.movable)
return frame
end
local mt = {__index = barPrototype}
function DBT:CreateBar(timer, id, icon, huge, small, color, isDummy, colorType, inlineIcon)
if timer <= 0 then return end
if (self.numBars or 0) >= 15 and not isDummy then return end
--Most efficient place to block it, nil colorType instead of checking option every update
if not self.options.ColorByType then colorType = nil end
local newBar = self:GetBar(id)
if newBar then -- update an existing bar
newBar.lastUpdate = GetTime()
newBar.huge = huge or nil
newBar:SetTimer(timer) -- this can kill the timer and the timer methods don't like dead timers
if newBar.dead then return end
newBar:SetElapsed(0) -- same
if newBar.dead then return end
newBar:ApplyStyle()
newBar:SetText(id)
newBar:SetIcon(icon)
else -- create a new one
newBar = next(unusedBarObjects, nil)
local newFrame = createBarFrame(self)
if newBar then
newBar.lastUpdate = GetTime()
unusedBarObjects[newBar] = nil
newBar.dead = nil -- resurrected it :)
newBar.frame = newFrame
newBar.id = id
newBar.timer = timer
newBar.totalTime = timer
newBar.owner = self
newBar.moving = nil
newBar.enlarged = nil
newBar.fadingIn = 0
newBar.small = small
newBar.color = color
newBar.colorType = colorType
newBar.flashing = nil
newBar.inlineIcon = inlineIcon
else -- duplicate code ;(
newBar = setmetatable({
frame = newFrame,
id = id,
timer = timer,
totalTime = timer,
owner = self,
moving = nil,
enlarged = nil,
fadingIn = 0,
small = small,
color = color,
flashing = nil,
colorType = colorType,
inlineIcon = inlineIcon,
lastUpdate = GetTime()
}, mt)
end
newFrame.obj = newBar
self.numBars = (self.numBars or 0) + 1
totalBars = self.numBars
local enlargeTime = self.options.BarStyle ~= "NoAnim" and self.options.EnlargeBarTime or 11
local importantBar = colorType and colorType == 7 and self:GetOption("Bar7ForceLarge")
if (importantBar or (timer <= enlargeTime or huge)) and self:GetOption("HugeBarsEnabled") then -- start enlarged
newBar.enlarged = true
newBar.huge = true
if huge then
self.enlargeHack = true
end
self.hugeBars:Append(newBar)
else
newBar.huge = nil
self.smallBars:Append(newBar)
end
newBar:SetText(id)
newBar:SetIcon(icon)
self.bars[newBar] = true
newBar:ApplyStyle()
newBar:Update(0)
end
return newBar
end
end
-----------------
-- Dummy Bar --
-----------------
do
local dummyBars = 0
local function dummyCancel(self)
self.timer = self.totalTime
self.flashing = nil
self:Update(0)
self.flashing = nil
_G[self.frame:GetName().."BarSpark"]:SetAlpha(1)
end
function DBT:CreateDummyBar(colorType, inlineIcon)
dummyBars = dummyBars + 1
local dummy = self:CreateBar(25, "dummy"..dummyBars, "Interface\\Icons\\Spell_Nature_WispSplode", nil, true, nil, true, colorType, inlineIcon)
dummy:SetText("Dummy", inlineIcon)
dummy:Cancel()
self.bars[dummy] = true
unusedBars[#unusedBars] = nil
unusedBarObjects[dummy] = nil
dummy.frame.obj = dummy
dummy.frame:SetParent(UIParent)
dummy.frame:ClearAllPoints()
dummy.frame:SetScript("OnUpdate", nil)
dummy.Cancel = dummyCancel
dummy:ApplyStyle()
dummy.dummy = true
return dummy
end
end
-----------------------------
-- General Bar Functions --
-----------------------------
function DBT:GetBarIterator()
if not self.bars then
DBM:Debug("GetBarIterator failed for unknown reasons")
return
end
return pairs(self.bars)
end
function DBT:GetBar(id)
for bar in self:GetBarIterator() do
if id == bar.id then
return bar
end
end
end
function DBT:CancelBar(id)
for bar in self:GetBarIterator() do
if id == bar.id then
bar:Cancel()
return true
end
end
return false
end
function DBT:UpdateBar(id, elapsed, totalTime)
for bar in self:GetBarIterator() do
if id == bar.id then
bar:SetTimer(totalTime or bar.totalTime)
bar:SetElapsed(elapsed or self.totalTime - self.timer)
return true
end
end
return false
end
---------------------------
-- General Bar Methods --
---------------------------
function DBT:ShowTestBars()
self:CreateBar(10, "Test 1", "Interface\\Icons\\Spell_Nature_WispSplode")
self:CreateBar(14, "Test 2", "Interface\\Icons\\Spell_Nature_WispSplode")
self:CreateBar(20, "Test 3", "Interface\\Icons\\Spell_Nature_WispSplode")
self:CreateBar(12, "Test 4", "Interface\\Icons\\Spell_Nature_WispSplode")
self:CreateBar(21.5, "Test 5", "Interface\\Icons\\Spell_Nature_WispSplode")
end
function barPrototype:SetTimer(timer)
self.totalTime = timer
self:Update(0)
end
function barPrototype:ResetAnimations()
self:RemoveFromList()
self.enlarged = nil
self.moving = nil
self.owner.smallBars:Append(self)
self:ApplyStyle()
end
function barPrototype:Pause()
self.flashing = nil
self.ftimer = nil
self:Update(0)
self.paused = true
if self.moving == "enlarge" then
self:ResetAnimations()
end
end
function barPrototype:Resume()
self.paused = nil
end
function barPrototype:SetElapsed(elapsed)
self.timer = self.totalTime - elapsed
local enlargeTime = self.owner.options.BarStyle ~= "NoAnim" and self.owner.options.EnlargeBarTime or 11
local enlargePer = self.owner.options.BarStyle ~= "NoAnim" and self.owner.options.EnlargeBarsPercent or 0
if (self.enlarged or self.moving == "enlarge") and not (self.timer <= enlargeTime or (self.timer/self.totalTime) <= enlargePer) then
self:ResetAnimations()
DBM:Debug("ResetAnimations firing for a a bar :Update() call", 2)
elseif self.owner.options.Sort and self.moving ~= "enlarge" then
local group = self.enlarged and self.owner.hugeBars or self.owner.smallBars
group:Remove(self)
group:Append(self)
end
self:Update(0)
end
function barPrototype:SetText(text, inlineIcon)
if not self.owner.options.InlineIcons then inlineIcon = nil end
--Force change color type 7 yo custom inlineIcon
local forcedIcon = (self.colorType and self.colorType == 7 and self.owner.options.Bar7CustomInline) and DBM_CORE_IMPORTANT_ICON or inlineIcon or ""
_G[self.frame:GetName().."BarName"]:SetText(forcedIcon..text)
end
function barPrototype:SetIcon(icon)
local frame_name = self.frame:GetName()
_G[frame_name.."BarIcon1"]:SetTexture("")
_G[frame_name.."BarIcon1"]:SetTexture(icon)
_G[frame_name.."BarIcon2"]:SetTexture("")
_G[frame_name.."BarIcon2"]:SetTexture(icon)
end
function barPrototype:SetColor(color)
self.color = color
local frame_name = self.frame:GetName()
_G[frame_name.."Bar"]:SetStatusBarColor(color.r, color.g, color.b)
_G[frame_name.."BarSpark"]:SetVertexColor(color.r, color.g, color.b)
end
------------------
-- Bar Update --
------------------
function barPrototype:Update(elapsed)
local frame = self.frame
local frame_name = frame:GetName()
local bar = _G[frame_name.."Bar"]
local texture = _G[frame_name.."BarTexture"]
local spark = _G[frame_name.."BarSpark"]
local timer = _G[frame_name.."BarTimer"]
local obj = self.owner
local barOptions = obj.options
local currentStyle = barOptions.BarStyle
local sparkEnabled = currentStyle ~= "NoAnim" and barOptions.Spark
local isMoving = self.moving
local isFadingIn = self.fadingIn
local isEnlarged = self.enlarged
local fillUpBars = isEnlarged and barOptions.FillUpLargeBars or not isEnlarged and barOptions.FillUpBars
local ExpandUpwards = isEnlarged and barOptions.ExpandUpwardsLarge or not isEnlarged and barOptions.ExpandUpwards
self.timer = self.timer - elapsed
local timerValue = self.timer
local totaltimeValue = self.totalTime
local colorCount = self.colorType
local enlargeHack = self.enlargeHack or false
if barOptions.DynamicColor and not self.color then
local r, g, b
if colorCount and colorCount >= 1 then
if colorCount == 1 then--Add
r = barOptions.StartColorAR + (barOptions.EndColorAR - barOptions.StartColorAR) * (1 - timerValue/totaltimeValue)
g = barOptions.StartColorAG + (barOptions.EndColorAG - barOptions.StartColorAG) * (1 - timerValue/totaltimeValue)
b = barOptions.StartColorAB + (barOptions.EndColorAB - barOptions.StartColorAB) * (1 - timerValue/totaltimeValue)
elseif colorCount == 2 then--AOE
r = barOptions.StartColorAER + (barOptions.EndColorAER - barOptions.StartColorAER) * (1 - timerValue/totaltimeValue)
g = barOptions.StartColorAEG + (barOptions.EndColorAEG - barOptions.StartColorAEG) * (1 - timerValue/totaltimeValue)
b = barOptions.StartColorAEB + (barOptions.EndColorAEB - barOptions.StartColorAEB) * (1 - timerValue/totaltimeValue)
elseif colorCount == 3 then--Debuff
r = barOptions.StartColorDR + (barOptions.EndColorDR - barOptions.StartColorDR) * (1 - timerValue/totaltimeValue)
g = barOptions.StartColorDG + (barOptions.EndColorDG - barOptions.StartColorDG) * (1 - timerValue/totaltimeValue)
b = barOptions.StartColorDB + (barOptions.EndColorDB - barOptions.StartColorDB) * (1 - timerValue/totaltimeValue)
elseif colorCount == 4 then--Interrupt
r = barOptions.StartColorIR + (barOptions.EndColorIR - barOptions.StartColorIR) * (1 - timerValue/totaltimeValue)
g = barOptions.StartColorIG + (barOptions.EndColorIG - barOptions.StartColorIG) * (1 - timerValue/totaltimeValue)
b = barOptions.StartColorIB + (barOptions.EndColorIB - barOptions.StartColorIB) * (1 - timerValue/totaltimeValue)
elseif colorCount == 5 then--Role
r = barOptions.StartColorRR + (barOptions.EndColorRR - barOptions.StartColorRR) * (1 - timerValue/totaltimeValue)
g = barOptions.StartColorRG + (barOptions.EndColorRG - barOptions.StartColorRG) * (1 - timerValue/totaltimeValue)
b = barOptions.StartColorRB + (barOptions.EndColorRB - barOptions.StartColorRB) * (1 - timerValue/totaltimeValue)
elseif colorCount == 6 then--Phase
r = barOptions.StartColorPR + (barOptions.EndColorPR - barOptions.StartColorPR) * (1 - timerValue/totaltimeValue)
g = barOptions.StartColorPG + (barOptions.EndColorPG - barOptions.StartColorPG) * (1 - timerValue/totaltimeValue)
b = barOptions.StartColorPB + (barOptions.EndColorPB - barOptions.StartColorPB) * (1 - timerValue/totaltimeValue)
elseif colorCount == 7 then--Important
if barOptions.Bar7ForceLarge then
enlargeHack = true
end
r = barOptions.StartColorUIR + (barOptions.EndColorUIR - barOptions.StartColorUIR) * (1 - timerValue/totaltimeValue)
g = barOptions.StartColorUIG + (barOptions.EndColorUIG - barOptions.StartColorUIG) * (1 - timerValue/totaltimeValue)
b = barOptions.StartColorUIB + (barOptions.EndColorUIB - barOptions.StartColorUIB) * (1 - timerValue/totaltimeValue)
end
else
r = barOptions.StartColorR + (barOptions.EndColorR - barOptions.StartColorR) * (1 - timerValue/totaltimeValue)
g = barOptions.StartColorG + (barOptions.EndColorG - barOptions.StartColorG) * (1 - timerValue/totaltimeValue)
b = barOptions.StartColorB + (barOptions.EndColorB - barOptions.StartColorB) * (1 - timerValue/totaltimeValue)
end
bar:SetStatusBarColor(r, g, b)
if sparkEnabled then
spark:SetVertexColor(r, g, b)
end
end
if timerValue <= 0 then
return self:Cancel()
else
if fillUpBars then
if currentStyle == "NoAnim" and isEnlarged and not enlargeHack then
bar:SetValue(1 - timerValue/(totaltimeValue < 11 and totaltimeValue or 11))
else
bar:SetValue(1 - timerValue/totaltimeValue)
end
else
if currentStyle == "NoAnim" and isEnlarged and not enlargeHack then
bar:SetValue(timerValue/(totaltimeValue < 11 and totaltimeValue or 11))
else
bar:SetValue(timerValue/totaltimeValue)
end
end
timer:SetText(stringFromTimer(timerValue))
end
if isFadingIn and isFadingIn < 0.5 and currentStyle ~= "NoAnim" then
self.fadingIn = isFadingIn + elapsed
frame:SetAlpha((isFadingIn) / 0.5)
elseif isFadingIn then
self.fadingIn = nil
end
if timerValue <= 7.75 and not self.flashing and barOptions.Flash and currentStyle ~= "NoAnim" then
self.flashing = true
self.ftimer = 0
elseif self.flashing and timerValue > 7.75 then
self.flashing = nil
self.ftimer = nil
end
if sparkEnabled then
spark:ClearAllPoints()
spark:SetSize(12, barOptions.Height * 3)
spark:SetPoint("CENTER", bar, "LEFT", bar:GetValue() * bar:GetWidth(), -1)
else
spark:SetAlpha(0)
end
if self.flashing then
local ftime = self.ftimer % 1.25
if ftime >= 0.5 then
texture:SetAlpha(1)
if sparkEnabled then
spark:SetAlpha(1)
end
elseif ftime >= 0.25 then
texture:SetAlpha(1 - (0.5 - ftime) / 0.25)
if sparkEnabled then
spark:SetAlpha(1 - (0.5 - ftime) / 0.25)
end
else
texture:SetAlpha(1 - (ftime / 0.25))
if sparkEnabled then
spark:SetAlpha(1 - (ftime / 0.25))
end
end
self.ftimer = self.ftimer + elapsed
end
local melapsed = self.moveElapsed
if isMoving == "move" and melapsed <= 0.5 then
barIsAnimating = true
self.moveElapsed = melapsed + elapsed
local newX = self.moveOffsetX + (barOptions[isEnlarged and "HugeBarXOffset" or "BarXOffset"] - self.moveOffsetX) * (melapsed / 0.5)
local newY
if ExpandUpwards then
newY = self.moveOffsetY + (barOptions[isEnlarged and "HugeBarYOffset" or "BarYOffset"] - self.moveOffsetY) * (melapsed / 0.5)
else
newY = self.moveOffsetY + (-barOptions[isEnlarged and "HugeBarYOffset" or "BarYOffset"] - self.moveOffsetY) * (melapsed / 0.5)
end
frame:ClearAllPoints()
frame:SetPoint(self.movePoint, self.moveAnchor, self.moveRelPoint, newX, newY)
elseif isMoving == "move" then
barIsAnimating = false
self.moving = nil
isMoving = nil
self:SetPosition()
elseif isMoving == "enlarge" and melapsed <= 1 then
barIsAnimating = true
self:AnimateEnlarge(elapsed)
elseif isMoving == "enlarge" then
barIsAnimating = false
self.moving = nil
isMoving = nil
self.enlarged = true
isEnlarged = true
obj.hugeBars:Append(self)
self:ApplyStyle()
elseif isMoving == "nextEnlarge" then
barIsAnimating = false
self.moving = nil
isMoving = nil
self.enlarged = true
isEnlarged = true
obj.hugeBars:Append(self)
self:ApplyStyle()
end
local enlargeTime = currentStyle ~= "NoAnim" and barOptions.EnlargeBarTime or 11
local enlargePer = currentStyle ~= "NoAnim" and barOptions.EnlargeBarsPercent or 0
if (timerValue <= enlargeTime or (timerValue/totaltimeValue) <= enlargePer) and not self.small and not isEnlarged and isMoving ~= "enlarge" and obj:GetOption("HugeBarsEnabled") then
self:RemoveFromList()
self:Enlarge()
end
end
-------------------
-- Movable Bar --
-------------------
function DBT:SavePosition()
local point, _, _, x, y = self.mainAnchor:GetPoint(1)
self:SetOption("TimerPoint", point)
self:SetOption("TimerX", x)
self:SetOption("TimerY", y)
local point, _, _, x, y = self.secAnchor:GetPoint(1)
self:SetOption("HugeTimerPoint", point)
self:SetOption("HugeTimerX", x)
self:SetOption("HugeTimerY", y)
end
do
local function moveEnd(self)
updateClickThrough(self, self:GetOption("ClickThrough"))
self.movable = false
end
function DBT:ShowMovableBar(small, large)
if small or small == nil then
local bar1 = self:CreateBar(20, "Move1", "Interface\\Icons\\Spell_Nature_WispSplode", nil, true)
bar1:SetText(DBM_CORE_MOVABLE_BAR)
end
if large or large == nil then
local bar2 = self:CreateBar(20, "Move2", "Interface\\Icons\\Spell_Nature_WispSplode", true)
bar2:SetText(DBM_CORE_MOVABLE_BAR)
end
updateClickThrough(self, false)
self.movable = true
DBM:Unschedule(moveEnd, self)
DBM:Schedule(20, moveEnd, self)
end
end
--------------------
-- Bar Handling --
--------------------
function barPrototype:RemoveFromList()
if self.moving ~= "enlarge" then
(self.enlarged and self.owner.hugeBars or self.owner.smallBars):Remove(self)
end
end
------------------
-- Bar Cancel --
------------------
function barPrototype:Cancel()
tinsert(unusedBars, self.frame)
self.frame:Hide()
self.frame.obj = nil
self:RemoveFromList()
self.owner.bars[self] = nil
unusedBarObjects[self] = self
self.dead = true
self.owner.numBars = (self.owner.numBars or 1) - 1
totalBars = self.owner.numBars
end
-----------------
-- Bar Style --
-----------------
function DBT:ApplyStyle()
for bar in self:GetBarIterator() do
bar:ApplyStyle()
end
end
function barPrototype:ApplyStyle()
local frame = self.frame
local frame_name = frame:GetName()
local bar = _G[frame_name.."Bar"]
local spark = _G[frame_name.."BarSpark"]
local texture = _G[frame_name.."BarTexture"]
local icon1 = _G[frame_name.."BarIcon1"]
local icon2 = _G[frame_name.."BarIcon2"]
local name = _G[frame_name.."BarName"]
local timer = _G[frame_name.."BarTimer"]
local barOptions = self.owner.options
local sparkEnabled = barOptions.BarStyle ~= "NoAnim" and barOptions.Spark
local enlarged = self.enlarged
texture:SetTexture(barOptions.Texture)
if self.color then
local barRed, barGreen, barBlue = self.color.r, self.color.g, self.color.b
bar:SetStatusBarColor(barRed, barGreen, barBlue)
if sparkEnabled then
spark:SetVertexColor(barRed, barGreen, barBlue)
end
else
local barStartRed, barStartGreen, barStartBlue
if self.colorType then
local colorCount = self.colorType
if colorCount == 1 then--Add
barStartRed, barStartGreen, barStartBlue = barOptions.StartColorAR, barOptions.StartColorAG, barOptions.StartColorAB
elseif colorCount == 2 then--AOE
barStartRed, barStartGreen, barStartBlue = barOptions.StartColorAER, barOptions.StartColorAEG, barOptions.StartColorAEB
elseif colorCount == 3 then--Debuff
barStartRed, barStartGreen, barStartBlue = barOptions.StartColorDR, barOptions.StartColorDG, barOptions.StartColorDB
elseif colorCount == 4 then--Interrupt
barStartRed, barStartGreen, barStartBlue = barOptions.StartColorIR, barOptions.StartColorIG, barOptions.StartColorIB
elseif colorCount == 5 then--Role
barStartRed, barStartGreen, barStartBlue = barOptions.StartColorRR, barOptions.StartColorRG, barOptions.StartColorRB
elseif colorCount == 6 then--Phase
barStartRed, barStartGreen, barStartBlue = barOptions.StartColorPR, barOptions.StartColorPG, barOptions.StartColorPB
elseif colorCount == 7 then--Important
barStartRed, barStartGreen, barStartBlue = barOptions.StartColorUIR, barOptions.StartColorUIG, barOptions.StartColorUIB
end
else
barStartRed, barStartGreen, barStartBlue = barOptions.StartColorR, barOptions.StartColorG, barOptions.StartColorB
end
bar:SetStatusBarColor(barStartRed, barStartGreen, barStartBlue)
if sparkEnabled then
spark:SetVertexColor(barStartRed, barStartGreen, barStartBlue)
end
end
local barTextColorRed, barTextColorGreen, barTextColorBlue = barOptions.TextColorR, barOptions.TextColorG, barOptions.TextColorB
local barHeight, barWidth, barHugeWidth = barOptions.Height, barOptions.Width, barOptions.HugeWidth
name:SetTextColor(barTextColorRed, barTextColorGreen, barTextColorBlue)
timer:SetTextColor(barTextColorRed, barTextColorGreen, barTextColorBlue)
if barOptions.IconLeft then icon1:Show() else icon1:Hide() end
if barOptions.IconRight then icon2:Show() else icon2:Hide() end
if enlarged then bar:SetWidth(barHugeWidth); bar:SetHeight(barHeight); else bar:SetWidth(barWidth) bar:SetHeight(barHeight); end
if enlarged then frame:SetScale(barOptions.HugeScale) else frame:SetScale(barOptions.Scale) end
if barOptions.IconLocked then
if enlarged then frame:SetWidth(barHugeWidth); frame:SetHeight(barHeight); else frame:SetWidth(barWidth); frame:SetHeight(barHeight); end
icon1:SetWidth(barHeight)
icon1:SetHeight(barHeight)
icon2:SetWidth(barHeight)
icon2:SetHeight(barHeight)
end
self.frame:Show()
if sparkEnabled then
spark:SetAlpha(1)
end
texture:SetAlpha(1)
bar:SetAlpha(1)
frame:SetAlpha(1)
local barFont, barFontSize, barFontFlag = barOptions.Font, barOptions.FontSize, barOptions.FontFlag
name:SetFont(barFont, barFontSize, barFontFlag)
name:SetPoint("LEFT", bar, "LEFT", 3, 0)
timer:SetFont(barFont, barFontSize, barFontFlag)
self:Update(0)
end
local function updateOrientation(self)
for bar in self:GetBarIterator() do
if not bar.dummy then
if bar.moving == "enlarge" then
bar.enlarged = true
bar.moving = nil
self.hugeBars:Append(bar)
bar:ApplyStyle()
else
bar.moving = nil
bar:SetPosition()
end
end
end
end
options.ExpandUpwards.onChange = updateOrientation
options.ExpandUpwardsLarge.onChange = updateOrientation
options.BarYOffset.onChange = updateOrientation
options.BarXOffset.onChange = updateOrientation
options.HugeBarYOffset.onChange = updateOrientation
options.HugeBarXOffset.onChange = updateOrientation
function updateClickThrough(self, newValue)
if not self.movable then
for bar in self:GetBarIterator() do
if not bar.dummy then
bar.frame:EnableMouse(not newValue)
end
end
end
end
options.ClickThrough.onChange = updateClickThrough
--------------------
-- Skinning API --
--------------------
do
local skins = {}
local textures = {}
local fonts = {}
local skin = {}
skin.__index = skin
function DBT:RegisterSkin(id)
if id:sub(0, 4) == "DBM-" then
id = id:sub(5)
end
local obj = skins[id]
if not obj then
error("unknown skin id; the id must be equal to the addon's name (with the DBM- prefix being optional)", 2)
end
obj.loaded = true
obj.defaults = {}
return obj
end
function DBT:SetSkin(id)
local skin = skins[id]
if not skin then
error("skin " .. id .. " doesn't exist", 2)
end
--[[ -- changing the skin cancels all timers; this is much easier than creating new frames for all currently running timers
-- This just fails and I can't see why so disabling this and just blocking setting skins with timers active instead
for bar in self:GetBarIterator() do
bar:Cancel()
end--]]
self:SetOption("Skin", id)
-- throw away old bars (note: there is no way to re-use them as the new skin uses a different XML template)
-- note: this doesn't update dummy bars (and can't do it by design); anyone who has a dummy bar for preview purposes (i.e. the GUI) must create new bars (e.g. in a callback)
unusedBars = {}
-- apply default options from the skin and reset all other options
for k, v in pairs(options) do
if k ~= "TimerPoint" and k ~= "TimerX" and k ~= "TimerY" -- do not reset the position
and k ~= "HugeTimerPoint" and k ~= "HugeTimerX" and k ~= "HugeTimerY"
and k ~= "Skin" then -- do not reset the skin we just set
-- A custom skin might have some settings as false, so need to check explicitly for nil.
-- skin.defaults will be nil if there isn't a skin (e.g. DefaultSkin) loaded, so check for that too.
if skin.defaults and skin.defaults[k] ~= nil then
self:SetOption(k, skin.defaults[k])
else
self:SetOption(k, v.default)
end
end
end
end
for i = 1, GetNumAddOns() do
if GetAddOnMetadata(i, "X-DBM-Timer-Skin") then
-- load basic skin data
local id = GetAddOnInfo(i)
if id:sub(0, 4) == "DBM-" then
id = id:sub(5)
end
local name = GetAddOnMetadata(i, "X-DBM-Timer-Skin-Name")
skins[id] = setmetatable({
name = name
}, skin)
-- load textures and fonts that might be embedded in this skin (to make them available to other skins)
local skinTextures = { strsplit(",", GetAddOnMetadata(i, "X-DBM-Timer-Skin-Textures") or "") }
local skinTextureNames = { strsplit(",", GetAddOnMetadata(i, "X-DBM-Timer-Skin-Texture-Names") or "") }
if #skinTextures ~= #skinTextureNames then
geterrorhandler()(id .. ": toc file defines " .. #skinTextures .. " textures but " .. #skinTextureNames .. " names for textures")
else
for i = 1, #skinTextures do
textures[skinTextureNames[i]:trim()] = skinTextures[i]:trim()
end
end
local skinFonts = { strsplit(",", GetAddOnMetadata(i, "X-DBM-Timer-Skin-Fonts") or "") }
local skinFontNames = { strsplit(",", GetAddOnMetadata(i, "X-DBM-Timer-Skin-Font-Names") or "") }
if #skinFonts ~= #skinFontNames then
geterrorhandler()(id .. ": toc file defines " .. #skinFonts .. " fonts but " .. #skinFontNames .. " names for fonts")
else
for i = 1, #skinFonts do
fonts[skinFontNames[i]:trim()] = skinFonts[i]:trim()
end
end
end
end
function DBT:GetSkins()
return skins
end
function DBT:GetTextures()
return textures
end
function DBT:GetFonts()
return fonts
end
end
--------------------
-- Bar Announce --
--------------------
function barPrototype:Announce()
local msg
if self.owner.announceHook then
msg = self.owner.announceHook(self)
end
local text = tostring(_G[self.frame:GetName().."BarName"]:GetText())
text = text:gsub("|T.-|t", "")
msg = msg or ("%s %d:%02d"):format(text, math.floor(self.timer / 60), self.timer % 60)
local chatWindow = ChatEdit_GetActiveWindow()
if chatWindow then
chatWindow:Insert(msg)
else
SendChatMessage(msg, (IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT") or (IsInRaid() and "RAID") or "PARTY")
end
end
function DBT:SetAnnounceHook(f)
self.announceHook = f
end
-----------------------
-- Bar Positioning --
-----------------------
function barPrototype:SetPosition()
if self.moving == "enlarge" then return end
local anchor = (self.prev and self.prev.frame) or (self.enlarged and self.owner.secAnchor) or self.owner.mainAnchor
local Enlarged = self.enlarged
local ExpandUpwards = Enlarged and self.owner.options.ExpandUpwardsLarge or not Enlarged and self.owner.options.ExpandUpwards
self.frame:ClearAllPoints()
if ExpandUpwards then
self.frame:SetPoint("BOTTOM", anchor, "TOP", self.owner.options[Enlarged and "HugeBarXOffset" or "BarXOffset"], self.owner.options[Enlarged and "HugeBarYOffset" or "BarYOffset"])
else
self.frame:SetPoint("TOP", anchor, "BOTTOM", self.owner.options[Enlarged and "HugeBarXOffset" or "BarXOffset"], -self.owner.options[Enlarged and "HugeBarYOffset" or "BarYOffset"])
end
end
function barPrototype:MoveToNextPosition()
if self.moving == "enlarge" then return end
local newAnchor = (self.prev and self.prev.frame) or (self.enlarged and self.owner.secAnchor) or self.owner.mainAnchor
local oldX = self.frame:GetRight() - self.frame:GetWidth()/2
local oldY = self.frame:GetTop()
local Enlarged = self.enlarged
local ExpandUpwards = Enlarged and self.owner.options.ExpandUpwardsLarge or not Enlarged and self.owner.options.ExpandUpwards
self.frame:ClearAllPoints()
if ExpandUpwards then
self.movePoint = "BOTTOM"
self.moveRelPoint = "TOP"
self.frame:SetPoint("BOTTOM", newAnchor, "TOP", self.owner.options[Enlarged and "HugeBarXOffset" or "BarXOffset"], self.owner.options[Enlarged and "HugeBarYOffset" or "BarYOffset"])
else
self.movePoint = "TOP"
self.moveRelPoint = "BOTTOM"
self.frame:SetPoint("TOP", newAnchor, "BOTTOM", self.owner.options[Enlarged and "HugeBarXOffset" or "BarXOffset"], -self.owner.options[Enlarged and "HugeBarYOffset" or "BarYOffset"])
end
local newX = self.frame:GetRight() - self.frame:GetWidth()/2
local newY = self.frame:GetTop()
if self.owner.options.BarStyle ~= "NoAnim" then
self.frame:ClearAllPoints()
self.frame:SetPoint(self.movePoint, newAnchor, self.moveRelPoint, -(newX - oldX), -(newY - oldY))
self.moving = "move"
end
self.moveAnchor = newAnchor
self.moveOffsetX = -(newX - oldX)
self.moveOffsetY = -(newY - oldY)
self.moveElapsed = 0
end
function barPrototype:Enlarge()
local newAnchor = (self.owner.hugeBars.last and self.owner.hugeBars.last.frame) or self.owner.secAnchor
local oldX = self.frame:GetRight() - self.frame:GetWidth()/2
local oldY = self.frame:GetTop()
local Enlarged = self.enlarged
local ExpandUpwards = Enlarged and self.owner.options.ExpandUpwardsLarge or not Enlarged and self.owner.options.ExpandUpwards
self.frame:ClearAllPoints()
if ExpandUpwards then
self.movePoint = "BOTTOM"
self.moveRelPoint = "TOP"
self.frame:SetPoint("BOTTOM", newAnchor, "TOP", self.owner.options[Enlarged and "HugeBarXOffset" or "BarXOffset"], self.owner.options[Enlarged and "HugeBarYOffset" or "BarYOffset"])
else
self.movePoint = "TOP"
self.moveRelPoint = "BOTTOM"
self.frame:SetPoint("TOP", newAnchor, "BOTTOM", self.owner.options[Enlarged and "HugeBarXOffset" or "BarXOffset"], -self.owner.options[Enlarged and "HugeBarYOffset" or "BarYOffset"])
end
local newX = self.frame:GetRight() - self.frame:GetWidth()/2
local newY = self.frame:GetTop()
self.frame:ClearAllPoints()
self.frame:SetPoint("TOP", newAnchor, "BOTTOM", -(newX - oldX), -(newY - oldY))
self.moving = self.owner.options.BarStyle == "NoAnim" and "nextEnlarge" or "enlarge"
self.moveAnchor = newAnchor
self.moveOffsetX = -(newX - oldX)
self.moveOffsetY = -(newY - oldY)
self.moveElapsed = 0
end
---------------------------
-- Bar Special Effects --
---------------------------
function barPrototype:AnimateEnlarge(elapsed)
self.moveElapsed = self.moveElapsed + elapsed
local melapsed = self.moveElapsed
local newX = self.moveOffsetX + (self.owner.options.HugeBarXOffset - self.moveOffsetX) * (melapsed / 1)
local newY = self.moveOffsetY + (self.owner.options.HugeBarYOffset - self.moveOffsetY) * (melapsed / 1)
local newWidth = self.owner.options.Width + (self.owner.options.HugeWidth - self.owner.options.Width) * (melapsed / 1)
local newScale = self.owner.options.Scale + (self.owner.options.HugeScale - self.owner.options.Scale) * (melapsed / 1)
if melapsed < 1 then
self.frame:ClearAllPoints()
self.frame:SetPoint(self.movePoint, self.moveAnchor, self.moveRelPoint, newX, newY)
self.frame:SetScale(newScale)
self.frame:SetWidth(newWidth)
_G[self.frame:GetName().."Bar"]:SetWidth(newWidth)
else
self.moving = nil
self.enlarged = true
self.owner.hugeBars:Append(self)
self:ApplyStyle()
end
end
------------------------
-- Bar event handlers --
------------------------
do
local function onUpdate(self, elapsed)
if self.obj then
self.obj.curTime = GetTime()
self.obj.delta = self.obj.curTime - self.obj.lastUpdate
if barIsAnimating and self.obj.delta >= 0.02 or self.obj.delta >= 0.04 then
self.obj.lastUpdate = self.obj.curTime
self.obj:Update(self.obj.delta)
end
else
-- This should *never* happen; .obj is only set to nil when calling :Hide() and :Show() is only called in a function that also sets .obj
-- However, there have been several reports of this happening since WoW 5.x, wtf?
-- Unfortunately, none of the developers was ever able to reproduce this.
-- The bug reports show screenshots of expired timers that are still visible (showing 0.00) with all clean-up operations (positioning, list entry) except for the :Hide() call being performed...
self:Hide()
end
end
local function onMouseDown(self, btn)
if self.obj then
if self.obj.owner.movable and btn == "LeftButton" then
if self.obj.enlarged then
self.obj.owner.secAnchor:StartMoving()
else
self.obj.owner.mainAnchor:StartMoving()
end
end
end
end
local function onMouseUp(self, btn)
if self.obj then
self.obj.owner.mainAnchor:StopMovingOrSizing()
self.obj.owner.secAnchor:StopMovingOrSizing()
self.obj.owner:SavePosition()
if btn == "RightButton" then
self.obj:Cancel()
elseif btn == "LeftButton" and IsShiftKeyDown() then
self.obj:Announce()
end
end
end
local function onHide(self)
if self.obj then
self.obj.owner.mainAnchor:StopMovingOrSizing()
self.obj.owner.secAnchor:StopMovingOrSizing()
end
end
function setupHandlers(frame)
frame:SetScript("OnUpdate", onUpdate)
frame:SetScript("OnMouseDown", onMouseDown)
frame:SetScript("OnMouseUp", onMouseUp)
frame:SetScript("OnHide", onHide)
_G[frame:GetName() .. "Bar"]:SetMinMaxValues(0, 1) -- used to be in the OnLoad handler
end
end
|
local t = require( "taptest" )
local isinf = require( "isinf" )
t( isinf( 0.0 ), false )
t( isinf( 1.0 / 0.0 ), true )
t( isinf( -1.0 / 0.0 ), true )
t( isinf( math.sqrt( -1.0 ) ), false )
t()
|
local olua = require "olua"
local function check_func(cls, fn, refmap)
if not fn.STATIC and refmap[fn.RET.TYPE.CPPCLS] then
if not (fn.RET.ATTR.DELREF or fn.RET.ATTR.REF) then
print('not specify ref: ' .. cls.CPPCLS .. ' => ' .. fn.FUNC_DECL)
end
end
end
local function check_class(cls, refmap)
for _, fns in ipairs(cls.FUNCS) do
for _, fn in ipairs(fns) do
check_func(cls, fn, refmap)
end
end
end
local function check_should_ref(cls, refmap, classmap)
if cls then
local NAME = cls.CPPCLS .. ' *'
if refmap[NAME] == nil then
if cls.SUPERCLS and check_should_ref(classmap[cls.SUPERCLS], refmap, classmap) then
refmap[NAME] = true
return true
end
elseif refmap[NAME] then
return true
end
end
end
function olua.checkref(conf)
local classmap = olua.getclass('*')
local refmap = {}
for _, v in ipairs(conf.REF) do
refmap[v] = true
end
for _, cls in pairs(classmap) do
check_should_ref(cls, refmap, classmap)
end
for _, cls in pairs(classmap) do
check_class(cls, refmap)
end
end
return olua
|
maleHash = GetHashKey("mp_m_freemode_01")
femaleHash = GetHashKey("mp_f_freemode_01")
copUniform = {
[maleHash] = {
[3] = {draw = 0, text = 0},
[4] = {draw = 35, text = 0},
[6] = {draw = 54, text = 0},
[8] = {draw = 122, text = 0},
[11] = {draw = 55, text = 0}
},
[femaleHash] = {
[3] = {draw = 14, text = 0},
[4] = {draw = 34, text = 0},
[6] = {draw = 27, text = 0},
[8] = {draw = 152, text = 0},
[11] = {draw = 48, text = 0}
}
}
-- Agencies:
-- [1] LSPD [2] LSSD [3] BCSO [4] HP [5] Ranger [6] MP [7] FIB
depts = {
[1] = { -- Mission Row
zone = 1, title = "LSPD Station", agency = 1,
duty = vector3(452.811, -989.455, 30.689), -- Duty spot detection
walkTo = vector3(447.79, -986.319, 30.689), -- Where to walk out to
leave = nil, -- Optional (TP here before leaving)
camview = vector3(410.313, -961.877, 32.4769), -- Camera view on duty switch
exitcam = vector3(445.723, -988.74, 30.25), -- Cam position on exit
getCar = vector3(445.726, -996.293, 30.689), -- Where to obtain a vehicle
carPos = vector3(449.426, -1021.88, 28.0861), -- Where to spawn the car
heliPos = vector3(449.689, -981.328, 44.0797), -- Where to spawn the heli
caminfo = {
h = 235.00, fov = 60.0,
eh = 235.00, efov = 80.0,
rotx = 0.0, roty = 0.0, rotz = 235.0,
erotx = 0.0, eroty = 0.0, erotz = 292.0
}
},
[2] = { -- Vespucci Beach
zone = 1, title = "LSPD Station", agency = 1,
duty = vector3(-1060.22, -826.492, 19.212),
leave = vector3(-1107.84, -846.551, 19.317),
walkTo = vector3(-1114.27, -841.893, 19.317),
camview = vector3(-1085.09, -783.761, 21.150),
exitcam = vector3(-1117.06, -856.142, 22.694),
getCar = vector3(0.0,0.0,0.0),
heliPos = vector3(-1096.42, -836.155, 38.0635),
carPos = vector3(449.426, -1021.88, 28.0861),
caminfo = {
h = 188.00, fov = 60.0,
eh = 342.00, efov = 80.0,
rotx = 0.0, roty = 0.0, rotz = 188.0,
erotx = 0.0, eroty = 0.0, erotz = 342.0
}
},
[3] = { -- Vinewood Station
zone = 1, title = "LSPD Station", agency = 1,
duty = vector3(639.60, 1.343, 82.787),
leave = vector3(620.156, 18.32, 87.91),
walkTo = vector3(621.442, 21.902, 88.341),
camview = vector3(662.551, -13.46, 83.58),
exitcam = vector3(618.47, 28.510, 88.741),
getCar = vector3(0.0,0.0,0.0),
heliPos = vector3(580.119, 11.9018, 103.621),
carPos = vector3(449.426, -1021.88, 28.0861),
caminfo = {
h = 90.0, fov = 80.0,
eh = 180.0, efov = 60.0,
rotx = 0.0, roty = 0.0, rotz = 90.0,
erotx = 0.0, eroty = 0.0, erotz = 180.0
}
},
[4] = { -- Davis Station
zone = 1, title = "Sheriff's Office", agency = 2,
duty = vector3(360.73, -1584.57, 29.292),
leave = vector3(369.89, -1607.80, 29.292),
walkTo = vector3(375.20, -1615.17, 29.292),
camview = vector3(386.57, -1571.61, 33.342),
exitcam = vector3(380.17, -1624.35, 31.61),
getCar = vector3(0.0,0.0,0.0),
carPos = vector3(449.426, -1021.88, 28.0861),
heliPos = vector3(363.259, -1598.38, 37.3365),
caminfo = {
h = 162.0, fov = 80.0,
eh = 36.0, efov = 60.0,
rotx = 0.0, roty = 0.0, rotz = 162.0,
erotx = 0.0, eroty = 0.0, erotz = 36.0
}
},
[5] = { -- Beaver Bush Station
zone = 2, title = "Ranger Station", agency = 5,
duty = vector3(379.219, 792.047, 190.408),
walkTo = vector3(385.185, 791.670, 190.409),
camview = vector3(370.397, 784.786, 191.625),
exitcam = vector3(398.483, 788.866, 187.984),
getCar = vector3(0.0,0.0,0.0),
carPos = vector3(449.426, -1021.88, 28.0861),
heliPos = vector3(422.011, 723.176, 198.10),
caminfo = {
h = 0.0, fov = 60.0,
eh = 180.0, efov = 60.0,
rotx = 0.0, roty = 0.0, rotz = 326.0,
erotx = 0.0, eroty = 0.0, erotz = 56.0
}
},
[6] = { -- Sandy Shores Station
zone = 1, title = "Sheriff's Office", agency = 3,
duty = vector3(1854.17, 3684.85, 34.26),
walkTo = vector3(1856.01, 3682.29, 34.26),
camview = vector3(1857.08, 3671.20, 36.85),
exitcam = vector3(1857.08, 3671.20, 36.85),
getCar = vector3(0.0,0.0,0.0),
carPos = vector3(449.426, -1021.88, 28.0861),
heliPos = vector3(1870.08, 3631.55, 34.94),
caminfo = {
h = 0.0, fov = 60.0,
eh = 180.0, efov = 60.0,
rotx = 0.0, roty = 0.0, rotz = 0.0,
erotx = 0.0, eroty = 0.0, erotz = 0.0
}
},
[7] = { -- Fort Zancudo Station
zone = 4, title = "Military Police", agency = 6,
duty = vector3(-2441.04, 2951.72, 34.848),
walkTo = vector3(-2440.32, 2956.20, 32.960),
camview = vector3(-2445.09, 2983.29, 37.310),
exitcam = vector3(-2447.89, 2962.14, 32.810),
getCar = vector3(0.0,0.0,0.0),
carPos = vector3(449.426, -1021.88, 28.0861),
heliPos = vector3(-2414.84, 2977.07, 34.013),
caminfo = {
h = 0.0, fov = 60.0,
eh = 0.0, efov = 60.0,
rotx = 0.0, roty = 0.0, rotz = 210.0,
erotx = 0.0, eroty = 0.0, erotz = 240.0
}
},
[8] = { -- Paleto Bay Station
zone = 3, title = "Sheriff's Office", agency = 3,
duty = vector3(-444.676, 6014.86, 31.716),
walkTo = vector3(-441.16, 6018.55, 31.542),
camview = vector3(-440.71, 6036.50, 34.741),
exitcam = vector3(-436.51, 6023.62, 32.690),
getCar = vector3(0.0,0.0,0.0),
carPos = vector3(449.426, -1021.88, 28.0861),
heliPos = vector3(-475.922, 5988.51, 31.7212),
caminfo = {
h = 0.0, fov = 60.0,
eh = 0.0, efov = 60.0,
rotx = 0.0, roty = 0.0, rotz = 164.0,
erotx = 0.0, eroty = 0.0, erotz = 135.5
}
},
[9] = { -- Federal Bureau of Investigations
zone = 1, title = "FBI Headquarters", agency = 7,
duty = vector3(136.287, -761.694, 45.752),
leave = vector3(111.575, -744.141, 45.751),
walkTo = vector3(103.283, -744.824, 45.754),
camview = vector3(102.772, -708.203, 248.525),
exitcam = vector3(94.7996, -737.857, 46.457),
getCar = vector3(0.0,0.0,0.0),
carPos = vector3(449.426, -1021.88, 28.0861),
caminfo = {
h = 0.0, fov = 80.0,
eh = 0.0, efov = 80.0,
rotx = 0.0, roty = 0.0, rotz = 230.0,
erotx = 0.0, eroty = 0.0, erotz = 220.0
}
},
[10] = { -- Highway Patrol Station
zone = 1, title = "Highway Patrol", agency = 4,
duty = vector3(826.367, -1290.09, 28.241),
leave = vector3(849.955, -1281.40, 28.004),
walkTo = vector3(849.946, -1276.92, 26.498),
camview = vector3(801.910, -1302.53, 29.250),
exitcam = vector3(855.501, -1270.78, 27.880),
getCar = vector3(0.0,0.0,0.0),
carPos = vector3(449.426, -1021.88, 28.0861),
caminfo = {
h = 0.0, fov = 60.0,
eh = 0.0, efov = 60.0,
rotx = 0.0, roty = 0.0, rotz = 278.0,
erotx = 0.0, eroty = 0.0, erotz = 156.0
}
}
}
-- Add Police Blips
Citizen.CreateThread(function()
for _,v in pairs(depts) do
local blip = AddBlipForCoord(v.duty)
SetBlipSprite(blip, 526)
SetBlipDisplay(blip, 2)
SetBlipScale(blip, 1.0)
if v.agency == 1 then SetBlipColour(blip, 67) -- Blue (LSPD)
elseif v.agency == 2 then SetBlipColour(blip, 10) -- Brown (LSSD)
elseif v.agency == 3 then SetBlipColour(blip, 70) -- Brown (BCSO)
elseif v.agency == 4 then SetBlipColour(blip, 16) -- Tan (SAHP)
elseif v.agency == 5 then SetBlipColour(blip, 25) -- Green (Ranger)
else SetBlipColour(blip, 62) -- Silver (MP/Federal)
end
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(v.title)
EndTextCommandSetBlipName(blip)
Citizen.Wait(1)
end
end)
policeCar = {
["POLICE"] = true,
["POLICEB"] = true,
["POLICE2"] = true,
["POLICE3"] = true,
["POLICE4"] = true,
["POLICE5"] = true,
["SHERIFF"] = true,
["SHERIFF2"] = true,
["PRANGER"] = true,
["FBI"] = true,
["FBI2"] = true,
["PRANCHER"] = true,
}
function IsUsingPoliceVehicle()
if not IsPedInAnyPoliceVehicle(PlayerPedId()) then
local veh = GetDisplayNameFromVehicleModel(GetEntityModel(GetVehiclePedIsIn(ped)))
if policeCar[veh] then return true end
else return true end
return false
end
|
local K = unpack(KkthnxUI)
local Module = K:GetModule("Skins")
function Module:ReskinSimulationcraft()
if not IsAddOnLoaded("Simulationcraft") then
return
end
local Simulationcraft = LibStub("AceAddon-3.0"):GetAddon("Simulationcraft")
hooksecurefunc(Simulationcraft, "GetMainFrame", function()
if not SimcFrame.isSkinned then
SimcFrame:StripTextures()
SimcFrame:CreateBorder()
SimcFrameButton:SetHeight(22)
SimcFrameButton:SkinButton()
SimcScrollFrameScrollBar:SkinScrollBar()
SimcFrame.isSkinned = true
end
end)
end
|
local Native = require('lib.native.native')
---@class UnitType
local UnitType = {
Hero = Native.ConvertUnitType(0), --UNIT_TYPE_HERO
Dead = Native.ConvertUnitType(1), --UNIT_TYPE_DEAD
Structure = Native.ConvertUnitType(2), --UNIT_TYPE_STRUCTURE
Flying = Native.ConvertUnitType(3), --UNIT_TYPE_FLYING
Ground = Native.ConvertUnitType(4), --UNIT_TYPE_GROUND
AttacksFlying = Native.ConvertUnitType(5), --UNIT_TYPE_ATTACKS_FLYING
AttacksGround = Native.ConvertUnitType(6), --UNIT_TYPE_ATTACKS_GROUND
MeleeAttacker = Native.ConvertUnitType(7), --UNIT_TYPE_MELEE_ATTACKER
RangedAttacker = Native.ConvertUnitType(8), --UNIT_TYPE_RANGED_ATTACKER
Giant = Native.ConvertUnitType(9), --UNIT_TYPE_GIANT
Summoned = Native.ConvertUnitType(10), --UNIT_TYPE_SUMMONED
Stunned = Native.ConvertUnitType(11), --UNIT_TYPE_STUNNED
Plagued = Native.ConvertUnitType(12), --UNIT_TYPE_PLAGUED
Snared = Native.ConvertUnitType(13), --UNIT_TYPE_SNARED
Undead = Native.ConvertUnitType(14), --UNIT_TYPE_UNDEAD
Mechanical = Native.ConvertUnitType(15), --UNIT_TYPE_MECHANICAL
Peon = Native.ConvertUnitType(16), --UNIT_TYPE_PEON
Sapper = Native.ConvertUnitType(17), --UNIT_TYPE_SAPPER
Townhall = Native.ConvertUnitType(18), --UNIT_TYPE_TOWNHALL
Ancient = Native.ConvertUnitType(19), --UNIT_TYPE_ANCIENT
Tauren = Native.ConvertUnitType(20), --UNIT_TYPE_TAUREN
Poisoned = Native.ConvertUnitType(21), --UNIT_TYPE_POISONED
Polymorphed = Native.ConvertUnitType(22), --UNIT_TYPE_POLYMORPHED
Sleeping = Native.ConvertUnitType(23), --UNIT_TYPE_SLEEPING
Resistant = Native.ConvertUnitType(24), --UNIT_TYPE_RESISTANT
Ethereal = Native.ConvertUnitType(25), --UNIT_TYPE_ETHEREAL
MagicImmune = Native.ConvertUnitType(26), --UNIT_TYPE_MAGIC_IMMUNE
}
return UnitType
|
local M = {}
M.base_30 = {
white = "#272f35",
darker_black = "#f5efde",
black = "#fff9e8", -- nvim bg
black2 = "#ebe5d4",
one_bg = "#c6c2aa",
one_bg2 = "#b6b29a",
one_bg3 = "#a6a28a",
grey = "#a6b0a0",
grey_fg = "#939f91",
grey_fg2 = "#829181",
light_grey = "#798878",
red = "#c85552",
baby_pink = "#ce8196",
pink = "#ef6590",
line = "#e8e2d1", -- for lines like vertsplit
green = "#5da111",
vibrant_green = "#87a060",
nord_blue = "#656c5f",
blue = "#3a94c5",
yellow = "#dfa000",
sun = "#d1b171",
purple = "#b67996",
dark_purple = "#966986",
teal = "#69a59d",
orange = "#F7954F",
cyan = "#7521e9",
statusline_bg = "#f0ead9",
lightbg = "#c9c3b2",
pmenu_bg = "#5f9b93",
folder_bg = "#747b6e",
}
M.base_16 = {
base00 = "#fff9e8",
base01 = "#f6f0df",
base02 = "#ede7d6",
base03 = "#e5dfce",
base04 = "#ddd7c6",
base05 = "#495157",
base06 = "#3b4349",
base07 = "#272f35",
base08 = "#5f9b93",
base09 = "#b67996",
base0A = "#8da101",
base0B = "#d59600",
base0C = "#ef615e",
base0D = "#87a060",
base0E = "#c85552",
base0F = "#c85552",
}
M.polish_hl = {
DiffAdd = {
fg = M.base_30.green,
},
TSTag = {
fg = M.base_30.orange,
},
TSField = {
fg = M.base_16.base05,
},
TSInclude = {
fg = M.base_16.base08,
},
TSConstructor = {
fg = M.base_30.blue,
},
WhichKeyDesc = {
fg = M.base_30.white,
},
WhichKey = {
fg = M.base_30.white,
},
NvimTreeFolderName = {
fg = "#4e565c",
},
}
M.type = "light"
M = require("base46").override_theme(M, "everforest_light")
return M
|
local pathJoin = require('luvi').path.join
local static = require('weblit-static')
local blog = require('controllers/blog')
local env = require('env')
require('weblit-app')
.bind({host = "0.0.0.0", port = env.get("PORT") or 8080})
-- Configure weblit server
.use(require('weblit-logger'))
.use(require('weblit-auto-headers'))
.use(require('weblit-etag-cache'))
-- Serve non-blog content pages
.route({ method = "GET", path = "/" }, require('controllers/page'))
.route({ method = "GET", path = "/:name.html" }, require('controllers/page'))
-- Serve blog articles
.route({ method = "GET", path = "/blog/"}, blog.index)
.route({ method = "GET", path = "/blog/tags/:tag"}, blog.tags)
.route({ method = "GET", path = "/blog/:name.html" }, blog.article)
.route({ method = "GET", path = "/blog/:path:"}, static(pathJoin(module.dir, "articles")))
.use(static(pathJoin(module.dir, "static")))
.start()
|
require("pgevents")
function Definitions()
DebugMessage("%s -- In Definitions", tostring(Script))
Category = "Build_Scanner"
IgnoreTarget = true
TaskForce = {
{
"StructureForce",
"Empire_Orbital_Long_Range_Scanner | Rebel_Orbital_Long_Range_Scanner | Empire_Heavy_Ship_Yard | Rebel_Heavy_Ship_Yard = 1"
}
}
DebugMessage("%s -- Done Definitions", tostring(Script))
end
function StructureForce_Thread()
DebugMessage("%s -- In StructureForce_Thread.", tostring(Script))
Sleep(1)
StructureForce.Set_As_Goal_System_Removable(false)
AssembleForce(StructureForce)
StructureForce.Set_Plan_Result(true)
DebugMessage("%s -- StructureForce done!", tostring(Script));
ScriptExit()
end
function StructureForce_Production_Failed(tf, failed_object_type)
DebugMessage("%s -- Abandonning plan owing to production failure.", tostring(Script))
ScriptExit()
end
|
local memory = require 'fsp.memory'
local data = require 'fsp.data'
local learn = require 'fsp.learner'
local class = require 'class'
local optim = require 'optim'
local util = require 'fsp.util'
local fsp = class('FSP3')
function fsp:__init(params)
-- logging
self.logger = optim.Logger(params.log_file)
self.plot_eval = params.plot_eval or false
self.save_file = params.save_file
-- policies and learners
self.nPlayers = params.nPlayers
self.dataGen = params.dataGen
self.rl_memories = params.rl_memories
self.sl_memories = params.sl_memories
self.br_policies = params.br_policies
self.avg_policies = params.avg_policies
self.br_learners = params.br_learners
self.avg_learners = params.avg_learners
self.evaluator = params.evaluator
-- dynamic params
self.iter_counter = 0
-- params
self.gpu = params.gpu or (params.gpu == nil and true)
self.eval_freq = params.eval_freq
self.save_freq = params.save_freq
--self.burnIn = params.burnIn
self.minReplayData = params.minReplayData
self.budget_train_br = params.budget_train_br
self.budget_train_avg = params.budget_train_avg
self.anticipatory_min = params.anticipatory_min
self.anticipatory_base = params.anticipatory_base
self.anticipatory_const = params.anticipatory_const
self.br_lr_base = params.lr_base.br
self.br_lr_const = params.lr_const.br
self.avg_lr_base = params.lr_base.avg
self.avg_lr_const = params.lr_const.avg
self._br_lr = self.br_lr_base
self._avg_lr = self.avg_lr_base
self.explo_base = params.explo_base
self.explo_const = params.explo_const
-- misc
self.sl_mem_reset = false
self.rl_buffer = memory.createTransitionBuffer(params.rl_minibatch_size, self.dataGen:stateDim(), self.gpu)
self.sl_buffer = memory.createActionBuffer(params.sl_minibatch_size, self.dataGen:stateDim(), self.gpu)
end
function fsp:run(nIter)
local evaluation
self.iter_counter = 1
for i=1,nIter do
self:iteration()
self.iter_counter = self.iter_counter + 1
if self.iter_counter % self.eval_freq == 0 then
self:evaluate()
local values, styles = self.evaluator(self.br_policies, self.avg_policies)
print("Iteration "..self.iter_counter..", Evaluation:")
print(values)
self.logger:add(values)
if self.plot_eval then
self.logger:style(styles)
self.logger:plot()
end
self:check_save()
end
end
end
function fsp:check_save()
if self.save_freq >= 0 then
if self.save_freq == 0 then
self:save(self.save_file..".th7")
else
local num_evals = self.iter_counter / self.eval_freq
if num_evals % self.save_freq == 0 then
self:save(self.save_file.."_"..num_evals..".th7")
end
end
end
end
function fsp:update_scheduled_params()
self.anticipatory = math.max(self.anticipatory_min, util.polynomialDecay(self.anticipatory_base, self.anticipatory_const, 0.5, self.iter_counter)) -- == learning rate of FP
self._br_lr = util.polynomialDecay(self.br_lr_base, self.br_lr_const, 0.5, self.iter_counter)
self._avg_lr = util.linearDecay(self.avg_lr_base, self.avg_lr_const, self.iter_counter)
local explo = util.polynomialDecay(self.explo_base, self.explo_const, 0.5, self.iter_counter)
for p=1,self.nPlayers do
self.dataGen:setExploration(explo)
self.dataGen:setAnticipatory(self.anticipatory)
self.br_learners[p].optim_state.learningRate = self._br_lr
self.avg_learners[p].optim_state.learningRate = self._avg_lr
end
if self.iter_counter % self.eval_freq == 0 then
print("Using scheduled params: br_lr "..self._br_lr..", avg_lr "..self._avg_lr..", anticipatory "..self.anticipatory..", exploration "..explo)
end
end
function fsp:save(filename)
local to_save = {
br = self.br_policies,
avg = self.avg_policies,
}
torch.save(filename, to_save)
end
function fsp:training()
for p=1,self.nPlayers do
self.br_policies[p].net:training()
self.avg_policies[p].net:training()
end
end
function fsp:evaluate()
for p=1,self.nPlayers do
self.br_policies[p].net:evaluate()
self.avg_policies[p].net:evaluate()
end
end
function fsp:iteration()
self:update_scheduled_params()
self:generate_experience()
self:replay_experience()
end
function fsp:generate_experience()
self:evaluate()
self.dataGen:generate()
end
function fsp:replay_experience()
self:training()
self:train_br()
self:train_avg()
end
function fsp:train_br()
for i=1,self.nPlayers do
if self.rl_memories[i]:length() > self.minReplayData then
if self.iter_counter % self.eval_freq == 0 then
print("Player "..i.." training its BR on memory of length "..self.rl_memories[i]:length())
end
learn.Learn(self.budget_train_br, self.rl_buffer, self.br_learners[i], self.rl_memories[i])
end
end
end
function fsp:train_avg()
for i=1,self.nPlayers do
if self.sl_memories[i]:length() > self.minReplayData then
if self.iter_counter % self.eval_freq == 0 then
print("Player "..i.." training its AVG on memory of length "..self.sl_memories[i]:length())
end
learn.Learn(self.budget_train_avg, self.sl_buffer, self.avg_learners[i], self.sl_memories[i])
end
end
end
return {FSP3 = fsp}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.