repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
imeteora/cocos2d-x-3.x-Qt
tests/lua-tests/src/MenuTest/MenuTest.lua
16
18464
local kTagMenu = 1 local kTagMenu0 = 0 local kTagMenu1 = 1 local MID_CALLBACK = 1000 local MID_CALLBACK2 = 1001 local MID_DISABLED = 1002 local MID_ENABLE = 1003 local MID_CONFIG = 1004 local MID_QUIT = 1005 local MID_OPACITY = 1006 local MID_ALIGN = 1007 local MID_CALLBACK3 = 1008 local MID_BACKCALLBACK = 1009 -------------------------------------------------------------------- -- -- MenuLayerMainMenu -- -------------------------------------------------------------------- local function MenuLayerMainMenu() local m_disabledItem = nil local ret = cc.Layer:create() -- Font Item local spriteNormal = cc.Sprite:create(s_MenuItem, cc.rect(0,23*2,115,23)) local spriteSelected = cc.Sprite:create(s_MenuItem, cc.rect(0,23*1,115,23)) local spriteDisabled = cc.Sprite:create(s_MenuItem, cc.rect(0,23*0,115,23)) local item1 = cc.MenuItemSprite:create(spriteNormal, spriteSelected, spriteDisabled) local function menuCallback(sender) cclog("menuCallback...") ret:getParent():switchTo(1) end item1:registerScriptTapHandler(menuCallback) -- Image Item local function menuCallback2(sender) ret:getParent():switchTo(2) end local item2 = cc.MenuItemImage:create(s_SendScore, s_PressSendScore) item2:registerScriptTapHandler(menuCallback2) local schedulerEntry = nil local scheduler = cc.Director:getInstance():getScheduler() local function allowTouches(dt) local pDirector = cc.Director:getInstance() --pDirector:getTouchDispatcher():setPriority(cc.MENU_HANDLER_PRIORITY +1, ret) if nil ~= schedulerEntry then scheduler:unscheduleScriptEntry(schedulerEntry) schedulerEntry = nil end cclog("TOUCHES ALLOWED AGAIN") end local function menuCallbackDisabled(sender) -- hijack all touch events for 5 seconds local pDirector = cc.Director:getInstance() --pDirector:getTouchDispatcher():setPriority(cc.MENU_HANDLER_PRIORITY -1, ret) schedulerEntry = scheduler:scheduleScriptFunc(allowTouches, 5, false) cclog("TOUCHES DISABLED FOR 5 SECONDS") end -- Label Item (LabelAtlas) local labelAtlas = cc.LabelAtlas:_create("0123456789", "fonts/labelatlas.png", 16, 24, string.byte('.')) local item3 = cc.MenuItemLabel:create(labelAtlas) item3:registerScriptTapHandler(menuCallbackDisabled) item3:setDisabledColor( cc.c3b(32,32,64) ) item3:setColor( cc.c3b(200,200,255) ) local function menuCallbackEnable(sender) m_disabledItem:setEnabled(not m_disabledItem:isEnabled() ) end -- Font Item local item4 = cc.MenuItemFont:create("I toggle enable items") item4:registerScriptTapHandler(menuCallbackEnable) item4:setFontSizeObj(20) cc.MenuItemFont:setFontName("Marker Felt") local function menuCallbackConfig(sender) ret:getParent():switchTo(3) end -- Label Item (cc.LabelBMFont) local label = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "configuration") label:setAnchorPoint(cc.p(0.5, 0.5)) local item5 = cc.MenuItemLabel:create(label) item5:registerScriptTapHandler(menuCallbackConfig) -- Testing issue #500 item5:setScale( 0.8 ) -- Events cc.MenuItemFont:setFontName("Marker Felt") local function menuCallbackBugsTest(pSender) ret:getParent():switchTo(4) end -- Bugs Item local item6 = cc.MenuItemFont:create("Bugs") item6:registerScriptTapHandler(menuCallbackBugsTest) local function onQuit(sender) cclog("onQuit item is clicked.") end -- Font Item local item7 = cc.MenuItemFont:create("Quit") item7:registerScriptTapHandler(onQuit) local function menuMovingCallback(pSender) ret:getParent():switchTo(5) end local item8 = cc.MenuItemFont:create("Remove menu item when moving") item8:registerScriptTapHandler(menuMovingCallback) local color_action = cc.TintBy:create(0.5, 0, -255, -255) local color_back = color_action:reverse() local seq = cc.Sequence:create(color_action, color_back) item7:runAction(cc.RepeatForever:create(seq)) local menu = cc.Menu:create() menu:addChild(item1) menu:addChild(item2) menu:addChild(item3) menu:addChild(item4) menu:addChild(item5) menu:addChild(item6) menu:addChild(item7) menu:addChild(item8) menu:alignItemsVertically() -- elastic effect local s = cc.Director:getInstance():getWinSize() local i = 0 local child = nil local pArray = menu:getChildren() local len = table.getn(pArray) local pObject = nil for i = 0, len-1 do pObject = pArray[i + 1] if pObject == nil then break end child = pObject local dstPointX, dstPointY = child:getPosition() local offset = s.width/2 + 50 if i % 2 == 0 then offset = 0-offset end child:setPosition( cc.p( dstPointX + offset, dstPointY) ) child:runAction( cc.EaseElasticOut:create(cc.MoveBy:create(2, cc.p(dstPointX - offset,0)), 0.35) ) end m_disabledItem = item3 item3:retain() m_disabledItem:setEnabled( false ) ret:addChild(menu) menu:setPosition(cc.p(s.width/2, s.height/2)) -- local schedulerEntry = nil local function onNodeEvent(event) if event == "exit" then if (schedulerEntry ~= nil) then scheduler:unscheduleScriptEntry(schedulerEntry) end if m_disabledItem ~= nil then -- m_disabledItem:release() end end end ret:registerScriptHandler(onNodeEvent) return ret end -------------------------------------------------------------------- -- -- MenuLayer2 -- -------------------------------------------------------------------- local function MenuLayer2() local ret = cc.Layer:create() local m_centeredMenu = nil local m_alignedH = false local function alignMenusH() local i = 0 for i=0, 1 do local menu = ret:getChildByTag(100+i) menu:setPosition( m_centeredMenu ) if i==0 then -- TIP: if no padding, padding = 5 menu:alignItemsHorizontally() local x, y = menu:getPosition() menu:setPosition( cc.pAdd(cc.p(x, y), cc.p(0,30)) ) else -- TIP: but padding is configurable menu:alignItemsHorizontallyWithPadding(40) local x, y = menu:getPosition() menu:setPosition( cc.pSub(cc.p(x, y), cc.p(0,30)) ) end end end local function alignMenusV() local i = 0 for i=0, 1 do local menu = ret:getChildByTag(100+i) menu:setPosition( m_centeredMenu ) if i==0 then -- TIP: if no padding, padding = 5 menu:alignItemsVertically() local x, y = menu:getPosition() menu:setPosition( cc.pAdd(cc.p(x, y), cc.p(100,0)) ) else -- TIP: but padding is configurable menu:alignItemsVerticallyWithPadding(40) local x, y = menu:getPosition() menu:setPosition( cc.pSub(cc.p(x, y), cc.p(100,0)) ) end end end local function menuCallback(sender) ret:getParent():switchTo(0) end local function menuCallbackOpacity(tag, sender) local menu = sender:getParent() local opacity = menu:getOpacity() if opacity == 128 then menu:setOpacity(255) else menu:setOpacity(128) end end local function menuCallbackAlign(sender) m_alignedH = not m_alignedH if m_alignedH then alignMenusH() else alignMenusV() end end local i = 0 for i=0, 1 do local item1 = cc.MenuItemImage:create(s_PlayNormal, s_PlaySelect) item1:registerScriptTapHandler(menuCallback) local item2 = cc.MenuItemImage:create(s_HighNormal, s_HighSelect) item2:registerScriptTapHandler(menuCallbackOpacity) local item3 = cc.MenuItemImage:create(s_AboutNormal, s_AboutSelect) item3:registerScriptTapHandler(menuCallbackAlign) item1:setScaleX( 1.5 ) item2:setScaleX( 0.5 ) item3:setScaleX( 0.5 ) local menu = cc.Menu:create() menu:addChild(item1) menu:addChild(item2) menu:addChild(item3) local s = cc.Director:getInstance():getWinSize() menu:setPosition(cc.p(s.width/2, s.height/2)) menu:setTag( kTagMenu ) ret:addChild(menu, 0, 100+i) local x, y = menu:getPosition() m_centeredMenu = cc.p(x, y) end m_alignedH = true alignMenusH() return ret end -------------------------------------------------------------------- -- -- MenuLayer3 -- -------------------------------------------------------------------- local function MenuLayer3() local m_disabledItem = nil local ret = cc.Layer:create() local function menuCallback(sender) ret:getParent():switchTo(0) end local function menuCallback2(sender) cclog("Label clicked. Toogling AtlasSprite") m_disabledItem:setEnabled( not m_disabledItem:isEnabled() ) m_disabledItem:stopAllActions() end local function menuCallback3(sender) cclog("MenuItemSprite clicked") end cc.MenuItemFont:setFontName("Marker Felt") cc.MenuItemFont:setFontSize(28) local label = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "Enable AtlasItem") label:setAnchorPoint(cc.p(0.5, 0.5)) local item1 = cc.MenuItemLabel:create(label) item1:registerScriptTapHandler(menuCallback2) local item2 = cc.MenuItemFont:create("--- Go Back ---") item2:registerScriptTapHandler(menuCallback) local spriteNormal = cc.Sprite:create(s_MenuItem, cc.rect(0,23*2,115,23)) local spriteSelected = cc.Sprite:create(s_MenuItem, cc.rect(0,23*1,115,23)) local spriteDisabled = cc.Sprite:create(s_MenuItem, cc.rect(0,23*0,115,23)) local item3 = cc.MenuItemSprite:create(spriteNormal, spriteSelected, spriteDisabled) item3:registerScriptTapHandler(menuCallback3) m_disabledItem = item3 item3:retain() m_disabledItem:setEnabled( false ) local menu = cc.Menu:create() menu:addChild(item1) menu:addChild(item2) menu:addChild(item3) menu:setPosition( cc.p(0,0) ) local s = cc.Director:getInstance():getWinSize() item1:setPosition( cc.p(s.width/2 - 150, s.height/2) ) item2:setPosition( cc.p(s.width/2 - 200, s.height/2) ) item3:setPosition( cc.p(s.width/2, s.height/2 - 100) ) local jump = cc.JumpBy:create(3, cc.p(400,0), 50, 4) item2:runAction( cc.RepeatForever:create(cc.Sequence:create( jump, jump:reverse()))) local spin1 = cc.RotateBy:create(3, 360) local spin2 = spin1:clone() local spin3 = spin1:clone() item1:runAction( cc.RepeatForever:create(spin1) ) item2:runAction( cc.RepeatForever:create(spin2) ) item3:runAction( cc.RepeatForever:create(spin3) ) ret:addChild( menu ) menu:setPosition(cc.p(0,0)) local function onNodeEvent(event) if event == "exit" then if m_disabledItem ~= nil then --m_disabledItem:release() end end end ret:registerScriptHandler(onNodeEvent) return ret end -------------------------------------------------------------------- -- -- MenuLayer4 -- -------------------------------------------------------------------- local function MenuLayer4() local ret = cc.Layer:create() cc.MenuItemFont:setFontName("American Typewriter") cc.MenuItemFont:setFontSize(18) local title1 = cc.MenuItemFont:create("Sound") title1:setEnabled(false) cc.MenuItemFont:setFontName( "Marker Felt" ) cc.MenuItemFont:setFontSize(34) local item1 = cc.MenuItemToggle:create(cc.MenuItemFont:create( "On" )) local function menuCallback(tag, sender) cclog("selected item: tag: %d, index:%d", tag, sender:getSelectedIndex() ) end local function backCallback(tag, sender) ret:getParent():switchTo(0) end item1:registerScriptTapHandler(menuCallback) item1:addSubItem(cc.MenuItemFont:create( "Off")) cc.MenuItemFont:setFontName( "American Typewriter" ) cc.MenuItemFont:setFontSize(18) local title2 = cc.MenuItemFont:create( "Music" ) title2:setEnabled(false) cc.MenuItemFont:setFontName( "Marker Felt" ) cc.MenuItemFont:setFontSize(34) local item2 = cc.MenuItemToggle:create(cc.MenuItemFont:create( "On" )) item2:registerScriptTapHandler(menuCallback) item2:addSubItem(cc.MenuItemFont:create( "Off")) cc.MenuItemFont:setFontName( "American Typewriter" ) cc.MenuItemFont:setFontSize(18) local title3 = cc.MenuItemFont:create( "Quality" ) title3:setEnabled( false ) cc.MenuItemFont:setFontName( "Marker Felt" ) cc.MenuItemFont:setFontSize(34) local item3 = cc.MenuItemToggle:create(cc.MenuItemFont:create( "High" )) item3:registerScriptTapHandler(menuCallback) item3:addSubItem(cc.MenuItemFont:create( "Low" )) cc.MenuItemFont:setFontName( "American Typewriter" ) cc.MenuItemFont:setFontSize(18) local title4 = cc.MenuItemFont:create( "Orientation" ) title4:setEnabled(false) cc.MenuItemFont:setFontName( "Marker Felt" ) cc.MenuItemFont:setFontSize(34) local item4 = cc.MenuItemToggle:create(cc.MenuItemFont:create( "Off"), cc.MenuItemFont:create( "33%" ), cc.MenuItemFont:create( "66%" ), cc.MenuItemFont:create( "100%")) item4:registerScriptTapHandler(menuCallback) -- you can change the one of the items by doing this item4:setSelectedIndex( 2 ) cc.MenuItemFont:setFontName( "Marker Felt" ) cc.MenuItemFont:setFontSize( 34 ) local label = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "go back") label:setAnchorPoint(cc.p(0.5, 0.5)) local back = cc.MenuItemLabel:create(label) back:registerScriptTapHandler(backCallback) local menu = cc.Menu:create() menu:addChild(title1) menu:addChild(title2) menu:addChild(item1 ) menu:addChild(item2 ) menu:addChild(title3) menu:addChild(title4) menu:addChild(item3 ) menu:addChild(item4 ) menu:addChild(back ) menu:alignItemsInColumns(2, 2, 2, 2, 1) ret:addChild(menu) local s = cc.Director:getInstance():getWinSize() menu:setPosition(cc.p(s.width/2, s.height/2)) return ret end -- BugsTest local function BugsTest() local ret = cc.Layer:create() local function issue1410MenuCallback(tag, pSender) local menu = pSender:getParent() menu:setEnabled(false) menu:setEnabled(true) cclog("NO CRASHES") end local function issue1410v2MenuCallback(tag, pSender) local menu = pSender:getParent() menu:setEnabled(true) menu:setEnabled(false) cclog("NO CRASHES. AND MENU SHOULD STOP WORKING") end local function backMenuCallback(tag, pSender) ret:getParent():switchTo(0) end local issue1410 = cc.MenuItemFont:create("Issue 1410") issue1410:registerScriptTapHandler(issue1410MenuCallback) local issue1410_2 = cc.MenuItemFont:create("Issue 1410 #2") issue1410_2:registerScriptTapHandler(issue1410v2MenuCallback) local back = cc.MenuItemFont:create("Back") back:registerScriptTapHandler(backMenuCallback) local menu = cc.Menu:create() menu:addChild(issue1410) menu:addChild(issue1410_2) menu:addChild(back) ret:addChild(menu) menu:alignItemsVertically() local s = cc.Director:getInstance():getWinSize() menu:setPosition(cc.p(s.width/2, s.height/2)) return ret end local function RemoveMenuItemWhenMove() local ret = cc.Layer:create() local s = cc.Director:getInstance():getWinSize() local label = cc.Label:createWithTTF("click item and move, should not crash", s_arialPath, 20) label:setAnchorPoint(cc.p(0.5, 0.5)) label:setPosition(cc.p(s.width/2, s.height - 30)) ret:addChild(label) local item = cc.MenuItemFont:create("item 1") item:retain() local back = cc.MenuItemFont:create("go back") local function goBack(tag, pSender) ret:getParent():switchTo(0) end back:registerScriptTapHandler(goBack) local menu = cc.Menu:create() menu:addChild(item) menu:addChild(back) ret:addChild(menu) menu:alignItemsVertically() menu:setPosition(cc.p(s.width/2, s.height/2)) local function onTouchBegan(touch, event) return true end local function onTouchMoved(touch, event) if item ~= nil then item:removeFromParent(true) --item:release() --item = nil end end local listener = cc.EventListenerTouchOneByOne:create() listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) local eventDispatcher = ret:getEventDispatcher() eventDispatcher:addEventListenerWithFixedPriority(listener, -129) local function onNodeEvent(event) if event == "exit" then ret:getEventDispatcher():removeEventListener(listener) end end ret:registerScriptHandler(onNodeEvent) return ret end function MenuTestMain() cclog("MenuTestMain") local scene = cc.Scene:create() local pLayer1 = MenuLayerMainMenu() local pLayer2 = MenuLayer2() local pLayer3 = MenuLayer3() local pLayer4 = MenuLayer4() local pLayer5 = BugsTest() local pLayer6 = RemoveMenuItemWhenMove() local layer = cc.LayerMultiplex:create(pLayer1, pLayer2, pLayer3, pLayer4, pLayer5, pLayer6 ) scene:addChild(layer, 0) scene:addChild(CreateBackMenuItem()) return scene end
gpl-2.0
PAC3-Server/ServerContent
lua/notagain/aowl/commands/play.lua
2
1506
AddCSLuaFile() if SERVER then API_YT_SEARCH_URL = "https://www.googleapis.com/youtube/v3/search?key=%s&part=id&type=video&q=%s" API_YT_KEY = file.Read("translation_key.txt") local function RequestYTSearch( q, c ) local url = string.format( API_YT_SEARCH_URL, API_YT_KEY, q ) url = string.Replace( url, " ", "%20" ) // Encoding Url http.Fetch(url, function( res ) local tab = util.JSONToTable(res) if tab then local vid = tab.items[1].id.videoId if vid then c( vid ) end end c( false ) end, function( err ) c( false ) end ) end util.AddNetworkString( "s2c_mpyt" ) local urls = { "youtu%.be/([%w_%-]+)", "youtube%.com/watch%?v%=([%w_%-]+)" } local function getYoutubeID( url ) for _, v in pairs( urls ) do for m in string.gmatch( url, v ) do return m end end return false end aowl.AddCommand("ytplay", function(ply, line, q) local id = getYoutubeID( q ) if id then net.Start( "s2c_mpyt" ) net.WriteString( id ) net.Send( ply ) else RequestYTSearch( q, function( data ) if data then net.Start( "s2c_mpyt" ) net.WriteString( data ) net.Send( ply ) end end ) end end) end if CLIENT then net.Receive("s2c_mpyt", function() local data = net.ReadString() local ent = LocalPlayer():GetEyeTrace().Entity if ent.IsMediaPlayerEntity then local q = string.format( "https://www.youtube.com/watch?v=%s", data ) MediaPlayer.Request( ent, q ) end end) end
mit
sutt0n/essentialmode-mysql
client/main.lua
1
2245
--[[ -- @author smuttoN -- @website www.github.com/sutt0n -- @date 5/22/2017 --]] -- first join Citizen.CreateThread(function() while true do Citizen.Wait(0) if NetworkIsSessionStarted() then TriggerServerEvent("es:firstJoinProper") return end end end) local oldPos Citizen.CreateThread(function() while true do Citizen.Wait(1000) local pos = GetEntityCoords(GetPlayerPed(-1)) if(oldPos ~= pos) then TriggerServerEvent("es:updatePositions", pos.x, pos.y, pos.z) -- init SendNUIMessage({ setmoney = true, money = 0 }) oldPos = pos end end end) local decorators = {} --[[ -- @param {string} key -- @param {string} val -- @param {bool} now -]] RegisterNetEvent("es:setPlayerDecorator") AddEventHandler("es:setPlayerDecorator", function(key, val, now) decorators[key] = value DecorRegister(key, 3) if(now) then DecorSetInt(GetPlayerPed(-1), key, val) end end) AddEventHandler("playerSpawned", function() for key, val in pairs(decorators) do DecorSetInt(GetPlayerPed(-1), key, val) end end) --[[ -- @param {int} _money -- @param {Player} player -]] RegisterNetEvent("es:activateMoney") AddEventHandler("es:activateMoney", function(_money) SendNUIMessage({ setmoney = true, money = _money }) end) --[[ -- @param {int} _money -]] RegisterNetEvent("es:addedMoney") AddEventHandler("es:addedMoney", function(_money) SendNUIMessage({ addmoney = true, money = _money }) end) --[[ -- @param {int} _money -]] RegisterNetEvent("es:removedMoney") AddEventHandler("es:removedMoney", function(_money) SendNUIMessage({ removemoney = true, money = _money }) end) RegisterNetEvent("es:setMoneyDisplay") --[[ -- @param {string} _display -]] AddEventHandler("es:setMoneyDisplay", function(_display) SendNUIMessage({ setDisplay = true, display = _display }) end) RegisterNetEvent("es:enablePvp") AddEventHandler("es:enablePvp", function() Citizen.CreateThread(function() while true do Citizen.Wait(0) for i = 0,32 do if NetworkIsPlayerConnected(i) then if NetworkIsPlayerConnected(i) and GetPlayerPed(i) ~= nil then SetCanAttackFriendly(GetPlayerPed(i), true, true) NetworkSetFriendlyFireOption(true) end end end end end) end)
gpl-3.0
christopherjwang/rackspace-monitoring-agent
hostinfo/disk.lua
1
1382
--[[ Copyright 2014 Rackspace 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 HostInfo = require('./base').HostInfo local sigar = require('sigar') local sigarutil = require('virgo/util/sigar') local table = require('table') --[[ Info ]]-- local Info = HostInfo:extend() function Info:initialize() HostInfo.initialize(self) local ctx, disks, usage_fields ctx = sigar:new() disks = sigarutil.diskTargets(ctx) usage_fields = { 'read_bytes', 'reads', 'rtime', 'time', 'write_bytes', 'writes', 'wtime' } for i=1, #disks do local name = disks[i]:name() local usage = disks[i]:usage() if name and usage then local obj = {} for _, v in pairs(usage_fields) do obj[v] = usage[v] end obj['name'] = name table.insert(self._params, obj) end end end function Info:getType() return 'DISK' end return Info
apache-2.0
Germanunkol/GridCars
lib/punchUI/inputBlock.lua
4
4847
local PATH = (...):match("(.-)[^%.%/]+$") local class = require( PATH .. "middleclass" ) local TextBlock = require( PATH .. "textBlock" ) local col = require(PATH .. "colors") local COLORS, COLORS_INACTIVE = col[1], col[2] col = nil local InputBlock = TextBlock:subclass("InputBlock") function InputBlock:initialize( name, x, y, width, height, font, returnEvent, password, maxLetters ) TextBlock.initialize( self, name, x, y, width, height, "", font, false ) self.fullContent = "" self.front = "" self.back = "" self.cursorX = 0 self.cursorY = 0 self.password = password or false self.maxLetters = maxLetters or math.huge self.maxLines = math.floor(height/self.font:getHeight()) self.returnEvent = returnEvent end function InputBlock:keypressed( key ) -- back up text incase anything goes wrong: self.oldFront, self.oldBack = self.front, self.back local stop, jump if key == "backspace" then local len = #self.front if len > 0 then self.front = self.front:sub(1, len-1) self:update( "left" ) end elseif key == "escape" then self.front = self.fullContent self.back = "" self:update() stop = true elseif key == "return" then self.fullContent = self.front .. self.back stop = true if self.returnEvent then self.returnEvent( self.fullContent ) end elseif key == "left" then local len = #self.front if len > 0 then self.back = self.front:sub( len,len ) .. self.back self.front = self.front:sub(1, len-1) self:update( "left" ) end elseif key == "right" then local len = #self.back if len > 0 then self.front = self.front .. self.back:sub(1,1) self.back = self.back:sub(2,len) self:update( "right" ) end elseif key == "delete" then local len = #self.back if len > 0 then self.back = self.back:sub(2,len) self:update() end elseif key == "home" then self.back = self.front .. self.back self.front = "" self.cursorX, self.cursorY = self:getCharPos( #self.front ) elseif key == "end" then self.front = self.front .. self.back self.back = "" self.cursorX, self.cursorY = self:getCharPos( #self.front ) elseif key == "tab" then self.fullContent = self.front .. self.back self:update() if love.keyboard.isDown("lshift", "rshift") then jump = "backward" else jump = "forward" end if self.returnEvent then self.returnEvent( self.fullContent ) end end if stop then return "stop" elseif jump then return jump end end function InputBlock:textinput( letter ) -- make sure to ignore first letter that's input: if not self.ignoredFirst then self.ignoredFirst = true return end if #self.front + #self.back < self.maxLetters then self.oldFront, self.oldBack = self.front, self.back --local chr = string.char(unicode) self.front = self.front .. letter self:update( "right" ) end end function InputBlock:setContent( txt ) local success = self:setText( txt ) if success then self.fullContent = txt self.front = txt self.back = "" self.cursorX, self.cursorY = self:getCharPos( #self.front ) end end function InputBlock:update( cursorDirection ) local lines = self.lines local original = self.original local plain = self.plain -- Check if the last operation split up an umlaut or -- similar: -- last is the last character on the front part -- first is the first character of the second part local last = self.front:sub(-1) local first = self.back:sub(1,1) local bLast = string.byte(last) local bFirst = string.byte(first) if bLast and bLast >= 194 then if bFirst and bFirst > 127 and bFirst < 194 then if cursorDirection == "left" then self.front = self.front:sub(1, #self.front - 1) self.back = last .. self.back else self.front = self.front .. self.back:sub(1,1) self.back = self.back:sub(2) end else self.front = self.front:sub(1, #self.front -1) end elseif bFirst and bFirst > 127 and bFirst < 194 then self.back = self.back:sub(2) end -- is the new text not too long? local success = self:setText( self.front .. self.back ) if success then self.cursorX, self.cursorY = self:getCharPos( #self.front ) else -- change back because text was too long self.lines = lines self.original = original self.plain = plain self.front = self.oldFront self.back = self.oldBack end end function InputBlock:setActive( bool ) self.active = bool if self.active then self.canvas = nil self.renderImg = false self.ignoredFirst = false self.front = self.fullContent self.back = "" else self.renderImg = true self:render() end end function InputBlock:draw() love.graphics.setColor( COLORS.INPUT_BG ) love.graphics.rectangle( "fill", self.x, self.y, self.width, self.height ) TextBlock.draw( self ) if self.active then love.graphics.print("|", self.x + self.cursorX, self.y+self.cursorY ) end end return InputBlock
mit
rafael/kong
kong/plugins/mashape-analytics/handler.lua
5
2842
-- Analytics plugin handler. -- -- How it works: -- Keep track of calls made to configured APIs on a per-worker basis, using the ALF format -- (alf_serializer.lua) and per-API buffers. `:access()` and `:body_filter()` are implemented to record some properties -- required for the ALF entry. -- -- When an API buffer is full (it reaches the `batch_size` configuration value or the maximum payload size), send the batch to the server. -- -- In order to keep Analytics as real-time as possible, we also start a 'delayed timer' running in background. -- If no requests are made during a certain period of time (the `delay` configuration value), the -- delayed timer will fire and send the batch + flush the data, not waiting for the buffer to be full. -- -- @see alf_serializer.lua -- @see buffer.lua local ALFBuffer = require "kong.plugins.mashape-analytics.buffer" local BasePlugin = require "kong.plugins.base_plugin" local ALFSerializer = require "kong.plugins.log-serializers.alf" local ALF_BUFFERS = {} -- buffers per-api local AnalyticsHandler = BasePlugin:extend() function AnalyticsHandler:new() AnalyticsHandler.super.new(self, "mashape-analytics") end function AnalyticsHandler:access(conf) AnalyticsHandler.super.access(self) -- Retrieve and keep in memory the bodies for this request ngx.ctx.analytics = { req_body = "", res_body = "", req_post_args = {} } ngx.req.read_body() local status, res = pcall(ngx.req.get_post_args) if not status then if res == "requesty body in temp file not supported" then ngx.log(ngx.ERR, "[mashape-analytics] cannot read request body from temporary file. Try increasing the client_body_buffer_size directive.") else ngx.log(ngx.ERR, res) end else ngx.ctx.analytics.req_post_args = res end if conf.log_body then ngx.ctx.analytics.req_body = ngx.req.get_body_data() end end function AnalyticsHandler:body_filter(conf) AnalyticsHandler.super.body_filter(self) local chunk, eof = ngx.arg[1], ngx.arg[2] -- concatenate response chunks for ALF's `response.content.text` if conf.log_body then ngx.ctx.analytics.res_body = ngx.ctx.analytics.res_body..chunk end if eof then -- latest chunk ngx.ctx.analytics.response_received = ngx.now() * 1000 end end function AnalyticsHandler:log(conf) AnalyticsHandler.super.log(self) local api_id = ngx.ctx.api.id -- Create the ALF buffer if not existing for this API if not ALF_BUFFERS[api_id] then ALF_BUFFERS[api_id] = ALFBuffer.new(conf) end local buffer = ALF_BUFFERS[api_id] -- Creating the ALF local alf = ALFSerializer.new_alf(ngx, conf.service_token, conf.environment) if alf then -- Simply adding the ALF to the buffer, it will decide if it is necessary to flush itself buffer:add_alf(alf) end end return AnalyticsHandler
apache-2.0
UB12/wnww
plugins/invite.lua
47
1193
do local function callbackres(extra, success, result) -- Callback for res_user in line 27 local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then -- Ignore bans send_large_msg(chat, 'User is banned.') elseif is_gbanned(result.id) then -- Ignore globall bans send_large_msg(chat, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) -- Add user on chat end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end --if not is_admin(msg) then -- For admins only ! --return 'Only admins can invite.' --end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^دعوت (.*)$" }, run = run } end
gpl-2.0
CarabusX/Zero-K
scripts/chickenflyerqueen.lua
5
7346
include "constants.lua" local spGetUnitHealth = Spring.GetUnitHealth --pieces local body, head, tail, leftWing1, rightWing1, leftWing2, rightWing2 = piece("body","head","tail","lwing1","rwing1","lwing2","rwing2") local leftThigh, leftKnee, leftShin, leftFoot, rightThigh, rightKnee, rightShin, rightFoot = piece("lthigh", "lknee", "lshin", "lfoot", "rthigh", "rknee", "rshin", "rfoot") local lforearml,lbladel,rforearml,rbladel,lforearmu,lbladeu,rforearmu,rbladeu = piece("lforearml", "lbladel", "rforearml", "rbladel", "lforearmu", "lbladeu", "rforearmu", "rbladeu") local spike1, spike2, spike3, firepoint, spore1, spore2, spore3 = piece("spike1", "spike2", "spike3", "firepoint", "spore1", "spore2", "spore3") local smokePiece = {} local turretIndex = { } --constants local wingAngle = math.rad(40) local wingSpeed = math.rad(120) local tailAngle = math.rad(20) local bladeExtendSpeed = math.rad(600) local bladeRetractSpeed = math.rad(120) local bladeAngle = math.rad(140) --variables local feet = true local malus = GG.malus or 1 --maximum HP for additional weapons local healthSpore3 = 0.55 local healthDodoDrop = 0.65 local healthDodo2Drop = 0.3 local healthBasiliskDrop = 0.5 local healthTiamatDrop = 0.2 --signals local SIG_Aim = 1 local SIG_Fly = 16 --cob values ---------------------------------------------------------- local function RestoreAfterDelay() Sleep(1000) end -- used for queen morph - blank in this case as it does nothing function MorphFunc() end local function Fly() Signal(SIG_Fly) SetSignalMask(SIG_Fly) while true do Turn(leftWing1, z_axis, -wingAngle, wingSpeed) Turn(rightWing1, z_axis, wingAngle, wingSpeed) Turn(leftWing2, z_axis, wingAngle*0.7, wingSpeed) Turn(rightWing2, z_axis, -wingAngle*0.7, wingSpeed) Turn(tail, x_axis, tailAngle, math.rad(40)) Move(body, y_axis, 10, 20) Sleep(0) WaitForTurn(leftWing1, z_axis) Turn(leftWing1, z_axis, wingAngle, wingSpeed) Turn(rightWing1, z_axis, -wingAngle, wingSpeed) Turn(leftWing2, z_axis, -wingAngle*0.7, wingSpeed*2) Turn(rightWing2, z_axis, wingAngle*0.7, wingSpeed*2) Turn(tail, x_axis, -tailAngle, math.rad(40)) Move(body, y_axis, -10, 20) -- EmitSfx(body, 4096+5) --Queen Crush Sleep(0) WaitForTurn(leftWing1, z_axis) end end local function StopFly() Signal(SIG_Fly) Turn(leftWing1, z_axis, 0, wingSpeed) Turn(rightWing1, z_axis, 0, wingSpeed) Turn(leftWing2, z_axis, 0, wingSpeed) Turn(rightWing2, z_axis, 0, wingSpeed) Turn(leftFoot, x_axis, 0, math.rad(420)) Turn(rightFoot, x_axis, 0, math.rad(420)) Turn(leftShin, x_axis, 0, math.rad(420)) Turn(rightShin, x_axis, 0, math.rad(420)) Move(body, y_axis, 0, 20) end local function DropDodoLoop() while true do local health, maxHealth = spGetUnitHealth(unitID) if (health/maxHealth) < healthDodoDrop then for i=1,malus do if (feet) then EmitSfx(leftFoot,2048+4) else EmitSfx(rightFoot,2048+4) end feet = not feet Sleep(500) end end Sleep(1500) if (health/maxHealth) < healthDodo2Drop then for i=1,malus do if (feet) then EmitSfx(leftFoot,2048+4) else EmitSfx(rightFoot,2048+4) end feet = not feet Sleep(500) end end Sleep(4500) end end local function DropBasiliskLoop() while true do local health, maxHealth = spGetUnitHealth(unitID) if (health/maxHealth) < healthTiamatDrop then for i=1,malus do EmitSfx(body,2048+6) Sleep(1000) end elseif (health/maxHealth) < healthBasiliskDrop then for i=1,malus do EmitSfx(body,2048+5) Sleep(1000) end end Sleep(8000) end end local function Moving() Signal(SIG_Fly) SetSignalMask(SIG_Fly) StartThread(Fly) Turn(leftFoot, x_axis, math.rad(-20), math.rad(420)) Turn(rightFoot, x_axis, math.rad(-20), math.rad(420)) Turn(leftShin, x_axis, math.rad(-40), math.rad(420)) Turn(rightShin, x_axis, math.rad(-40), math.rad(420)) end function script.StartMoving() StartThread(Moving) end function script.StopMoving() StartThread(StopFly) end function script.Create() Turn(rightWing1, x_axis, math.rad(15)) Turn(leftWing1, x_axis, math.rad(15)) Turn(rightWing1, x_axis, math.rad(0), math.rad(60)) Turn(leftWing1, x_axis, math.rad(0), math.rad(60)) Turn(rightWing1, z_axis, math.rad(-60)) Turn(rightWing2, z_axis, math.rad(100)) Turn(leftWing1, z_axis, math.rad(60)) Turn(leftWing2, z_axis, math.rad(-100)) EmitSfx(body, 1026) EmitSfx(head, 1026) EmitSfx(tail, 1026) EmitSfx(firepoint, 1026) EmitSfx(leftWing1, 1026) EmitSfx(rightWing1, 1026) EmitSfx(spike1, 1026) EmitSfx(spike2, 1026) EmitSfx(spike3, 1026) Turn(spore1, x_axis, math.rad(90)) Turn(spore2, x_axis, math.rad(90)) Turn(spore3, x_axis, math.rad(90)) StartThread(DropDodoLoop) StartThread(DropBasiliskLoop) end function script.AimFromWeapon(weaponNum) if weaponNum == 1 then return firepoint elseif weaponNum == 2 then return spore1 elseif weaponNum == 3 then return spore2 elseif weaponNum == 4 then return spore3 --elseif weaponNum == 5 then return body else return body end end function script.AimWeapon(weaponNum, heading, pitch) if weaponNum == 1 then Signal(SIG_Aim) SetSignalMask(SIG_Aim) Turn(head, y_axis, heading, math.rad(250)) Turn(head, x_axis, pitch, math.rad(200)) WaitForTurn(head, y_axis) WaitForTurn(head, x_axis) StartThread(RestoreAfterDelay) return true elseif weaponNum == 4 then local health, maxHealth = spGetUnitHealth(unitID) if (health/maxHealth) < healthSpore3 then return true end elseif weaponNum >= 2 and weaponNum <= 4 then return true else return false end end function script.QueryWeapon(weaponNum) if weaponNum == 1 then return firepoint elseif weaponNum == 2 then return spore1 elseif weaponNum == 3 then return spore2 elseif weaponNum == 4 then return spore3 --elseif weaponNum == 5 then -- if feet then return leftFoot -- else return rightFoot end else return body end end function script.FireWeapon(weaponNum) if weaponNum == 1 then Turn(lforearmu, y_axis, -bladeAngle, bladeExtendSpeed) Turn(lbladeu, y_axis, bladeAngle, bladeExtendSpeed) Turn(lforearml, y_axis, -bladeAngle, bladeExtendSpeed) Turn(lbladel, y_axis, bladeAngle, bladeExtendSpeed) Turn(rforearmu, y_axis, bladeAngle, bladeExtendSpeed) Turn(rbladeu, y_axis, -bladeAngle, bladeExtendSpeed) Turn(rforearml, y_axis, bladeAngle, bladeExtendSpeed) Turn(rbladel, y_axis, -bladeAngle, bladeExtendSpeed) Sleep(500) Turn(lforearmu, y_axis, 0, bladeRetractSpeed) Turn(lbladeu, y_axis, 0, bladeRetractSpeed) Turn(lforearml, y_axis, 0, bladeRetractSpeed) Turn(lbladel, y_axis, 0, bladeRetractSpeed) Turn(rforearmu, y_axis, 0, bladeRetractSpeed) Turn(rbladeu, y_axis, 0, bladeRetractSpeed) Turn(rforearml, y_axis, 0, bladeRetractSpeed) Turn(rbladel, y_axis, 0, bladeRetractSpeed) --WaitForTurn(lbladeu, y_axis) end return true end function script.Killed(recentDamage, maxHealth) EmitSfx(body, 1025) Explode(body, SFX.FALL) Explode(head, SFX.FALL) Explode(tail, SFX.FALL) Explode(leftWing1, SFX.FALL) Explode(rightWing1, SFX.FALL) Explode(spike1, SFX.FALL) Explode(spike2, SFX.FALL) Explode(spike3, SFX.FALL) Explode(leftThigh, SFX.FALL) Explode(rightThigh, SFX.FALL) Explode(leftShin, SFX.FALL) Explode(rightShin, SFX.FALL) end function script.HitByWeapon(x, z, weaponID, damage) EmitSfx(body, 1024) --return 100 end
gpl-2.0
amirmrbad/superbot
plugins/lock_link.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
hacker44-h44/hacker44-spamer36
plugins/anti-flood.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
ReclaimYourPrivacy/cloak-luci
build/luadoc/luadoc/taglet/standard/tags.lua
46
5543
------------------------------------------------------------------------------- -- Handlers for several tags -- @release $Id: tags.lua,v 1.8 2007/09/05 12:39:09 tomas Exp $ ------------------------------------------------------------------------------- local luadoc = require "luadoc" local util = require "luadoc.util" local string = require "string" local table = require "table" local assert, type, tostring, tonumber = assert, type, tostring, tonumber module "luadoc.taglet.standard.tags" ------------------------------------------------------------------------------- local function author (tag, block, text) block[tag] = block[tag] or {} if not text then luadoc.logger:warn("author `name' not defined [["..text.."]]: skipping") return end table.insert (block[tag], text) end ------------------------------------------------------------------------------- -- Set the class of a comment block. Classes can be "module", "function", -- "table". The first two classes are automatic, extracted from the source code local function class (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function cstyle (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function sort (tag, block, text) block[tag] = tonumber(text) or 0 end ------------------------------------------------------------------------------- local function copyright (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function description (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function field (tag, block, text) if block["class"] ~= "table" then luadoc.logger:warn("documenting `field' for block that is not a `table'") end block[tag] = block[tag] or {} local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") assert(name, "field name not defined") table.insert(block[tag], name) block[tag][name] = desc end ------------------------------------------------------------------------------- -- Set the name of the comment block. If the block already has a name, issue -- an error and do not change the previous value local function name (tag, block, text) if block[tag] and block[tag] ~= text then luadoc.logger:error(string.format("block name conflict: `%s' -> `%s'", block[tag], text)) end block[tag] = text end ------------------------------------------------------------------------------- -- Processes a parameter documentation. -- @param tag String with the name of the tag (it must be "param" always). -- @param block Table with previous information about the block. -- @param text String with the current line beeing processed. local function param (tag, block, text) block[tag] = block[tag] or {} -- TODO: make this pattern more flexible, accepting empty descriptions local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") if not name then luadoc.logger:warn("parameter `name' not defined [["..text.."]]: skipping") return end local i = table.foreachi(block[tag], function (i, v) if v == name then return i end end) if i == nil then luadoc.logger:warn(string.format("documenting undefined parameter `%s'", name)) table.insert(block[tag], name) end block[tag][name] = desc end ------------------------------------------------------------------------------- local function release (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function ret (tag, block, text) tag = "ret" if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- -- @see ret local function see (tag, block, text) -- see is always an array block[tag] = block[tag] or {} -- remove trailing "." text = string.gsub(text, "(.*)%.$", "%1") local s = util.split("%s*,%s*", text) table.foreachi(s, function (_, v) table.insert(block[tag], v) end) end ------------------------------------------------------------------------------- -- @see ret local function usage (tag, block, text) if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- local handlers = {} handlers["author"] = author handlers["class"] = class handlers["cstyle"] = cstyle handlers["copyright"] = copyright handlers["description"] = description handlers["field"] = field handlers["name"] = name handlers["param"] = param handlers["release"] = release handlers["return"] = ret handlers["see"] = see handlers["sort"] = sort handlers["usage"] = usage ------------------------------------------------------------------------------- function handle (tag, block, text) if not handlers[tag] then luadoc.logger:error(string.format("undefined handler for tag `%s'", tag)) return end if text then text = text:gsub("`([^\n]-)`", "<code>%1</code>") text = text:gsub("`(.-)`", "<pre>%1</pre>") end -- assert(handlers[tag], string.format("undefined handler for tag `%s'", tag)) return handlers[tag](tag, block, text) end
apache-2.0
lunjesse/GaW4-bot
Fire Attack (Classic).lua
1
1588
memory.usememorydomain("Combined WRAM") function move_fire(dest) local player = memory.readbyte(0x03C130) local hit = memory.readbyte(0x03C132) -- console.log(dest) if (player == dest) then if (hit == 0) then joypad.set({A = true}) return end else if (player == 0 and dest == 1) then joypad.set({Right = true}) elseif (player == 0 and dest == 2) then joypad.set({Down = true}) elseif (player == 0 and dest == 3) then joypad.set({Down = true, Right = true}) elseif (player == 1 and dest == 0) then joypad.set({Left = true}) elseif (player == 1 and dest == 2) then joypad.set({Down = true, Left = true}) elseif (player == 1 and dest == 3) then joypad.set({Down = true}) elseif (player == 2 and dest == 0) then joypad.set({Up = true}) elseif (player == 2 and dest == 1) then joypad.set({Up = true, Right = true}) elseif (player == 2 and dest == 3) then joypad.set({Right = true}) elseif (player == 3 and dest == 0) then joypad.set({Up = true, Left = true}) elseif (player == 3 and dest == 1) then joypad.set({Up = true}) elseif (player == 3 and dest == 2) then joypad.set({Left = true}) end end end while true do local fire_address = 0x03AB18 local fire local pos = {[4] = 0, [10] = 1, [16] = 2, [23] = 3} --positions of fire, and where the player should be at for i = 0, 7 do fire = memory.readbyte(fire_address+(0x7C*i)) --4 cases: top left, top right, bottom left, bottom right gui.text(0,60+15*i,i.." f "..fire) if (pos[fire] ~= nil) then --this means the positions exists move_fire(pos[fire]) end end emu.frameadvance() console.clear() end
mit
kbara/snabb
lib/ljsyscall/syscall/openbsd/types.lua
24
9707
-- OpenBSD types local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(types) local abi = require "syscall.abi" local t, pt, s, ctypes = types.t, types.pt, types.s, types.ctypes local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2 local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn = h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn local ntohl, ntohl, ntohs, htons, octal = h.ntohl, h.ntohl, h.ntohs, h.htons, h.octal local c = require "syscall.openbsd.constants" local mt = {} -- metatables local addtypes = { } local addstructs = { } for k, v in pairs(addtypes) do addtype(types, k, v) end for k, v in pairs(addstructs) do addtype(types, k, v, lenmt) end -- 32 bit dev_t, 24 bit minor, 8 bit major, but minor is a cookie and neither really used just legacy local function makedev(major, minor) if type(major) == "table" then major, minor = major[1], major[2] end local dev = major or 0 if minor then dev = bit.bor(minor, bit.lshift(major, 8)) end return dev end mt.device = { index = { major = function(dev) return bit.bor(bit.band(bit.rshift(dev.dev, 8), 0xff)) end, minor = function(dev) return bit.band(dev.dev, 0xffff00ff) end, device = function(dev) return tonumber(dev.dev) end, }, newindex = { device = function(dev, major, minor) dev.dev = makedev(major, minor) end, }, __new = function(tp, major, minor) return ffi.new(tp, makedev(major, minor)) end, } addtype(types, "device", "struct {dev_t dev;}", mt.device) mt.stat = { index = { dev = function(st) return t.device(st.st_dev) end, mode = function(st) return st.st_mode end, ino = function(st) return tonumber(st.st_ino) end, nlink = function(st) return st.st_nlink end, uid = function(st) return st.st_uid end, gid = function(st) return st.st_gid end, rdev = function(st) return t.device(st.st_rdev) end, atime = function(st) return st.st_atim.time end, ctime = function(st) return st.st_ctim.time end, mtime = function(st) return st.st_mtim.time end, birthtime = function(st) return st.st_birthtim.time end, size = function(st) return tonumber(st.st_size) end, blocks = function(st) return tonumber(st.st_blocks) end, blksize = function(st) return tonumber(st.st_blksize) end, flags = function(st) return st.st_flags end, gen = function(st) return st.st_gen end, type = function(st) return bit.band(st.st_mode, c.S_I.FMT) end, todt = function(st) return bit.rshift(st.type, 12) end, isreg = function(st) return st.type == c.S_I.FREG end, isdir = function(st) return st.type == c.S_I.FDIR end, ischr = function(st) return st.type == c.S_I.FCHR end, isblk = function(st) return st.type == c.S_I.FBLK end, isfifo = function(st) return st.type == c.S_I.FIFO end, islnk = function(st) return st.type == c.S_I.FLNK end, issock = function(st) return st.type == c.S_I.FSOCK end, iswht = function(st) return st.type == c.S_I.FWHT end, }, } -- add some friendlier names to stat, also for luafilesystem compatibility mt.stat.index.access = mt.stat.index.atime mt.stat.index.modification = mt.stat.index.mtime mt.stat.index.change = mt.stat.index.ctime local namemap = { file = mt.stat.index.isreg, directory = mt.stat.index.isdir, link = mt.stat.index.islnk, socket = mt.stat.index.issock, ["char device"] = mt.stat.index.ischr, ["block device"] = mt.stat.index.isblk, ["named pipe"] = mt.stat.index.isfifo, } mt.stat.index.typename = function(st) for k, v in pairs(namemap) do if v(st) then return k end end return "other" end addtype(types, "stat", "struct stat", mt.stat) mt.flock = { index = { type = function(self) return self.l_type end, whence = function(self) return self.l_whence end, start = function(self) return self.l_start end, len = function(self) return self.l_len end, pid = function(self) return self.l_pid end, sysid = function(self) return self.l_sysid end, }, newindex = { type = function(self, v) self.l_type = c.FCNTL_LOCK[v] end, whence = function(self, v) self.l_whence = c.SEEK[v] end, start = function(self, v) self.l_start = v end, len = function(self, v) self.l_len = v end, pid = function(self, v) self.l_pid = v end, sysid = function(self, v) self.l_sysid = v end, }, __new = newfn, } addtype(types, "flock", "struct flock", mt.flock) mt.dirent = { index = { fileno = function(self) return tonumber(self.d_fileno) end, reclen = function(self) return self.d_reclen end, namlen = function(self) return self.d_namlen end, type = function(self) return self.d_type end, name = function(self) return ffi.string(self.d_name, self.d_namlen) end, toif = function(self) return bit.lshift(self.d_type, 12) end, -- convert to stat types }, __len = function(self) return self.d_reclen end, } mt.dirent.index.ino = mt.dirent.index.fileno -- alternate name -- TODO previously this allowed lower case values, but this static version does not -- could add mt.dirent.index[tolower(k)] = mt.dirent.index[k] but need to do consistently elsewhere for k, v in pairs(c.DT) do mt.dirent.index[k] = function(self) return self.type == v end end addtype(types, "dirent", "struct dirent", mt.dirent) mt.fdset = { index = { fds_bits = function(self) return self.__fds_bits end, }, } addtype(types, "fdset", "fd_set", mt.fdset) -- TODO see Linux notes. Also maybe can be shared with BSDs, have not checked properly -- TODO also remove WIF prefixes. mt.wait = { __index = function(w, k) local _WSTATUS = bit.band(w.status, octal("0177")) local _WSTOPPED = octal("0177") local WTERMSIG = _WSTATUS local EXITSTATUS = bit.band(bit.rshift(w.status, 8), 0xff) local WIFEXITED = (_WSTATUS == 0) local tab = { WIFEXITED = WIFEXITED, WIFSTOPPED = bit.band(w.status, 0xff) == _WSTOPPED, WIFSIGNALED = _WSTATUS ~= _WSTOPPED and _WSTATUS ~= 0 } if tab.WIFEXITED then tab.EXITSTATUS = EXITSTATUS end if tab.WIFSTOPPED then tab.WSTOPSIG = EXITSTATUS end if tab.WIFSIGNALED then tab.WTERMSIG = WTERMSIG end if tab[k] then return tab[k] end local uc = 'W' .. k:upper() if tab[uc] then return tab[uc] end end } function t.waitstatus(status) return setmetatable({status = status}, mt.wait) end local signames = {} for k, v in pairs(c.SIG) do signames[v] = k end mt.siginfo = { index = { signo = function(s) return s.si_signo end, errno = function(s) return s.si_errno end, code = function(s) return s.si_code end, pid = function(s) return s.si_pid end, uid = function(s) return s.si_uid end, status = function(s) return s.si_status end, addr = function(s) return s.si_addr end, value = function(s) return s.si_value end, trapno = function(s) return s._fault._trapno end, timerid = function(s) return s._timer._timerid end, overrun = function(s) return s._timer._overrun end, mqd = function(s) return s._mesgq._mqd end, band = function(s) return s._poll._band end, signame = function(s) return signames[s.signo] end, }, newindex = { signo = function(s, v) s.si_signo = v end, errno = function(s, v) s.si_errno = v end, code = function(s, v) s.si_code = v end, pid = function(s, v) s.si_pid = v end, uid = function(s, v) s.si_uid = v end, status = function(s, v) s.si_status = v end, addr = function(s, v) s.si_addr = v end, value = function(s, v) s.si_value = v end, trapno = function(s, v) s._fault._trapno = v end, timerid = function(s, v) s._timer._timerid = v end, overrun = function(s, v) s._timer._overrun = v end, mqd = function(s, v) s._mesgq._mqd = v end, band = function(s, v) s._poll._band = v end, }, __len = lenfn, } addtype(types, "siginfo", "siginfo_t", mt.siginfo) -- sigaction, standard POSIX behaviour with union of handler and sigaction addtype_fn(types, "sa_sigaction", "void (*)(int, siginfo_t *, void *)") mt.sigaction = { index = { handler = function(sa) return sa.__sigaction_u.__sa_handler end, sigaction = function(sa) return sa.__sigaction_u.__sa_sigaction end, mask = function(sa) return sa.sa_mask end, flags = function(sa) return tonumber(sa.sa_flags) end, }, newindex = { handler = function(sa, v) if type(v) == "string" then v = pt.void(c.SIGACT[v]) end if type(v) == "number" then v = pt.void(v) end sa.__sigaction_u.__sa_handler = v end, sigaction = function(sa, v) if type(v) == "string" then v = pt.void(c.SIGACT[v]) end if type(v) == "number" then v = pt.void(v) end sa.__sigaction_u.__sa_sigaction = v end, mask = function(sa, v) if not ffi.istype(t.sigset, v) then v = t.sigset(v) end sa.sa_mask = v end, flags = function(sa, v) sa.sa_flags = c.SA[v] end, }, __new = function(tp, tab) local sa = ffi.new(tp) if tab then for k, v in pairs(tab) do sa[k] = v end end if tab and tab.sigaction then sa.sa_flags = bit.bor(sa.flags, c.SA.SIGINFO) end -- this flag must be set if sigaction set return sa end, } addtype(types, "sigaction", "struct sigaction", mt.sigaction) return types end return {init = init}
apache-2.0
CarabusX/Zero-K
LuaRules/Configs/StartBoxes/TheHunters-v3.lua
17
1313
return { [0] = { startpoints = { {860,451}, }, boxes = { { {819,410}, {901,410}, {901,492}, {819,492}, }, }, }, [1] = { startpoints = { {7496,7578}, }, boxes = { { {7455,7537}, {7537,7537}, {7537,7619}, {7455,7619}, }, }, }, [2] = { startpoints = { {7414,532}, }, boxes = { { {7373,492}, {7455,492}, {7455,573}, {7373,573}, }, }, }, [3] = { startpoints = { {778,7414}, }, boxes = { { {737,7373}, {819,7373}, {819,7455}, {737,7455}, }, }, }, [4] = { startpoints = { {614,3236}, }, boxes = { { {573,3195}, {655,3195}, {655,3277}, {573,3277}, }, }, }, [5] = { startpoints = { {7496,5202}, }, boxes = { { {7455,5161}, {7537,5161}, {7537,5243}, {7455,5243}, }, }, }, [6] = { startpoints = { {4219,7660}, }, boxes = { { {4178,7619}, {4260,7619}, {4260,7700}, {4178,7700}, }, }, }, [7] = { startpoints = { {4628,614}, }, boxes = { { {4588,573}, {4669,573}, {4669,655}, {4588,655}, }, }, }, [8] = { startpoints = { {4055,4055}, }, boxes = { { {3277,3277}, {4833,3277}, {4833,4833}, {3277,4833}, }, }, }, }
gpl-2.0
Adirelle/AdiBags
widgets/ItemButton.lua
1
17463
--[[ AdiBags - Adirelle's bag addon. Copyright 2010-2021 Adirelle (adirelle@gmail.com) All rights reserved. This file is part of AdiBags. AdiBags is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AdiBags is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with AdiBags. If not, see <http://www.gnu.org/licenses/>. --]] local addonName, addon = ... --<GLOBALS local _G = _G local BankButtonIDToInvSlotID = _G.BankButtonIDToInvSlotID local BANK_CONTAINER = _G.BANK_CONTAINER local ContainerFrame_UpdateCooldown = _G.ContainerFrame_UpdateCooldown local format = _G.format local GetContainerItemID = _G.GetContainerItemID local GetContainerItemInfo = _G.GetContainerItemInfo local GetContainerItemLink = _G.GetContainerItemLink local GetContainerItemQuestInfo = _G.GetContainerItemQuestInfo local GetContainerNumFreeSlots = _G.GetContainerNumFreeSlots local GetItemInfo = _G.GetItemInfo local GetItemQualityColor = _G.GetItemQualityColor local hooksecurefunc = _G.hooksecurefunc local IsContainerItemAnUpgrade = _G.IsContainerItemAnUpgrade local IsInventoryItemLocked = _G.IsInventoryItemLocked local ITEM_QUALITY_COMMON = _G.Enum.ItemQuality.Common local ITEM_QUALITY_POOR = _G.Enum.ItemQuality.Poor local next = _G.next local pairs = _G.pairs local select = _G.select local SetItemButtonDesaturated = _G.SetItemButtonDesaturated local StackSplitFrame = _G.StackSplitFrame local TEXTURE_ITEM_QUEST_BANG = _G.TEXTURE_ITEM_QUEST_BANG local TEXTURE_ITEM_QUEST_BORDER = _G.TEXTURE_ITEM_QUEST_BORDER local tostring = _G.tostring local wipe = _G.wipe --GLOBALS> local GetSlotId = addon.GetSlotId local GetBagSlotFromId = addon.GetBagSlotFromId local ITEM_SIZE = addon.ITEM_SIZE -------------------------------------------------------------------------------- -- Button initialization -------------------------------------------------------------------------------- local buttonClass, buttonProto = addon:NewClass("ItemButton", "ItemButton", "ContainerFrameItemButtonTemplate", "ABEvent-1.0") local childrenNames = { "Cooldown", "IconTexture", "IconQuestTexture", "Count", "Stock", "NormalTexture", "NewItemTexture" } function buttonProto:OnCreate() local name = self:GetName() for i, childName in pairs(childrenNames ) do if not self[childName] then self[childName] = _G[name..childName] end end self:RegisterForDrag("LeftButton") self:RegisterForClicks("LeftButtonUp","RightButtonUp") self:SetScript('OnShow', self.OnShow) self:SetScript('OnHide', self.OnHide) self:SetWidth(ITEM_SIZE) self:SetHeight(ITEM_SIZE) if self.NewItemTexture then self.NewItemTexture:Hide() end self.SplitStack = nil -- Remove the function set up by the template end function buttonProto:OnAcquire(container, bag, slot) self.container = container self.bag = bag self.slot = slot self.stack = nil self:SetParent(addon.itemParentFrames[bag]) self:SetID(slot) self:FullUpdate() end function buttonProto:OnRelease() self:SetSection(nil) self.container = nil self.itemId = nil self.itemLink = nil self.hasItem = nil self.texture = nil self.bagFamily = nil self.stack = nil end function buttonProto:ToString() return format("Button-%s-%s", tostring(self.bag), tostring(self.slot)) end function buttonProto:IsLocked() return select(3, GetContainerItemInfo(self.bag, self.slot)) end function buttonProto:SplitStack(split) SplitContainerItem(self.bag, self.slot, split) end -------------------------------------------------------------------------------- -- Generic bank button sub-type -------------------------------------------------------------------------------- local bankButtonClass, bankButtonProto = addon:NewClass("BankItemButton", "ItemButton") bankButtonClass.frameTemplate = "BankItemButtonGenericTemplate" function bankButtonProto:OnAcquire(container, bag, slot) self.GetInventorySlot = nil -- Remove the method added by the template self.inventorySlot = bag == REAGENTBANK_CONTAINER and ReagentBankButtonIDToInvSlotID(slot) or BankButtonIDToInvSlotID(slot) return buttonProto.OnAcquire(self, container, bag, slot) end function bankButtonProto:IsLocked() return IsInventoryItemLocked(self.inventorySlot) end function bankButtonProto:UpdateNew() -- Not supported end function bankButtonProto:GetInventorySlot() return self.inventorySlot end function bankButtonProto:UpdateUpgradeIcon() if self.bag ~= BANK_CONTAINER and self.bag ~= REAGENTBANK_CONTAINER then buttonProto.UpdateUpgradeIcon(self) end end -------------------------------------------------------------------------------- -- Pools and acquistion -------------------------------------------------------------------------------- local containerButtonPool = addon:CreatePool(buttonClass) local bankButtonPool = addon:CreatePool(bankButtonClass) function addon:AcquireItemButton(container, bag, slot) if bag == BANK_CONTAINER or bag == REAGENTBANK_CONTAINER then return bankButtonPool:Acquire(container, bag, slot) else return containerButtonPool:Acquire(container, bag, slot) end end -- Pre-spawn a bunch of buttons, when we are out of combat -- because buttons created in combat do not work well hooksecurefunc(addon, 'OnInitialize', function() addon:Debug('Prespawning buttons') containerButtonPool:PreSpawn(160) end) -------------------------------------------------------------------------------- -- Model data -------------------------------------------------------------------------------- function buttonProto:SetSection(section) local oldSection = self.section if oldSection ~= section then self.section = section if oldSection then oldSection:RemoveItemButton(self) end return true end end function buttonProto:GetSection() return self.section end function buttonProto:GetItemId() return self.itemId end function buttonProto:GetItemLink() return self.itemLink end function buttonProto:GetCount() return select(2, GetContainerItemInfo(self.bag, self.slot)) or 0 end function buttonProto:GetBagFamily() return self.bagFamily end local BANK_BAG_IDS = addon.BAG_IDS.BANK function buttonProto:IsBank() return not not BANK_BAG_IDS[self.bag] end function buttonProto:IsStack() return false end function buttonProto:GetRealButton() return self end function buttonProto:SetStack(stack) self.stack = stack end function buttonProto:GetStack() return self.stack end local function SimpleButtonSlotIterator(self, slotId) if not slotId and self.bag and self.slot then return GetSlotId(self.bag, self.slot), self.bag, self.slot, self.itemId, self.stack end end function buttonProto:IterateSlots() return SimpleButtonSlotIterator, self end -------------------------------------------------------------------------------- -- Scripts & event handlers -------------------------------------------------------------------------------- function buttonProto:OnShow() self:RegisterEvent('BAG_UPDATE_COOLDOWN', 'UpdateCooldown') self:RegisterEvent('ITEM_LOCK_CHANGED', 'UpdateLock') self:RegisterEvent('QUEST_ACCEPTED', 'UpdateBorder') self:RegisterEvent('BAG_NEW_ITEMS_UPDATED', 'UpdateNew') self:RegisterEvent('PLAYER_EQUIPMENT_CHANGED', 'FullUpdate') if self.UpdateSearch then self:RegisterEvent('INVENTORY_SEARCH_UPDATE', 'UpdateSearch') end self:RegisterEvent('UNIT_QUEST_LOG_CHANGED') self:RegisterMessage('AdiBags_UpdateAllButtons', 'Update') self:RegisterMessage('AdiBags_GlobalLockChanged', 'UpdateLock') self:FullUpdate() end function buttonProto:OnHide() self:UnregisterAllEvents() self:UnregisterAllMessages() if self.hasStackSplit and self.hasStackSplit == 1 then StackSplitFrame:Hide() end end function buttonProto:UNIT_QUEST_LOG_CHANGED(event, unit) if unit == "player" then self:UpdateBorder(event) end end -------------------------------------------------------------------------------- -- Display updating -------------------------------------------------------------------------------- function buttonProto:CanUpdate() if not self:IsVisible() or addon.holdYourBreath then return false end return true end function buttonProto:FullUpdate() local bag, slot = self.bag, self.slot self.itemId = GetContainerItemID(bag, slot) self.itemLink = GetContainerItemLink(bag, slot) self.hasItem = not not self.itemId self.texture = GetContainerItemInfo(bag, slot) self.bagFamily = select(2, GetContainerNumFreeSlots(bag)) self:Update() end function buttonProto:Update() if not self:CanUpdate() then return end local icon = self.IconTexture if self.texture then icon:SetTexture(self.texture) icon:SetTexCoord(0,1,0,1) else icon:SetTexture([[Interface\BUTTONS\UI-EmptySlot]]) icon:SetTexCoord(12/64, 51/64, 12/64, 51/64) end local tag = (not self.itemId or addon.db.profile.showBagType) and addon:GetFamilyTag(self.bagFamily) if tag then self.Stock:SetText(tag) self.Stock:Show() else self.Stock:Hide() end self:UpdateCount() self:UpdateBorder() self:UpdateCooldown() self:UpdateLock() self:UpdateNew() self:UpdateUpgradeIcon() if self.UpdateSearch then self:UpdateSearch() end addon:SendMessage('AdiBags_UpdateButton', self) end function buttonProto:UpdateCount() local count = self:GetCount() or 0 self.count = count if count > 1 then self.Count:SetText(count) self.Count:Show() else self.Count:Hide() end end function buttonProto:UpdateLock(isolatedEvent) if addon.globalLock then SetItemButtonDesaturated(self, true) self:Disable() else self:Enable() SetItemButtonDesaturated(self, self:IsLocked()) end if isolatedEvent then addon:SendMessage('AdiBags_UpdateLock', self) end end function buttonProto:UpdateSearch() local _, _, _, _, _, _, _, isFiltered = GetContainerItemInfo(self.bag, self.slot) if isFiltered then self.searchOverlay:Show(); else self.searchOverlay:Hide(); end end function buttonProto:UpdateCooldown() return ContainerFrame_UpdateCooldown(self.bag, self) end function buttonProto:UpdateNew() self.BattlepayItemTexture:SetShown(IsBattlePayItem(self.bag, self.slot)) end function buttonProto:UpdateUpgradeIcon() -- Use Pawn's (third-party addon) function if present; else fallback to Blizzard's. local PawnIsContainerItemAnUpgrade = _G.PawnIsContainerItemAnUpgrade local itemIsUpgrade = PawnIsContainerItemAnUpgrade and PawnIsContainerItemAnUpgrade(self.bag, self.slot) or IsContainerItemAnUpgrade(self.bag, self.slot) self.UpgradeIcon:SetShown(itemIsUpgrade or false) end local function GetBorder(bag, slot, itemId, settings) if settings.questIndicator then local isQuestItem, questId, isActive = GetContainerItemQuestInfo(bag, slot) if questId and not isActive then return TEXTURE_ITEM_QUEST_BANG end if questId or isQuestItem then return TEXTURE_ITEM_QUEST_BORDER end end if not settings.qualityHighlight then return end local _, _, _, quality = GetContainerItemInfo(bag, slot) if quality == ITEM_QUALITY_POOR and settings.dimJunk then local v = 1 - 0.5 * settings.qualityOpacity return true, v, v, v, 1, nil, nil, nil, nil, "MOD" end local color = quality ~= ITEM_QUALITY_COMMON and BAG_ITEM_QUALITY_COLORS[quality] if color then return [[Interface\Buttons\UI-ActionButton-Border]], color.r, color.g, color.b, settings.qualityOpacity, 14/64, 49/64, 15/64, 50/64, "ADD" end end function buttonProto:UpdateBorder(isolatedEvent) local texture, r, g, b, a, x1, x2, y1, y2, blendMode if self.hasItem then texture, r, g, b, a, x1, x2, y1, y2, blendMode = GetBorder(self.bag, self.slot, self.itemLink or self.itemId, addon.db.profile) end if not texture then self.IconQuestTexture:Hide() else local border = self.IconQuestTexture if texture == true then border:SetVertexColor(1, 1, 1, 1) border:SetColorTexture(r or 1, g or 1, b or 1, a or 1) else border:SetTexture(texture) border:SetVertexColor(r or 1, g or 1, b or 1, a or 1) end border:SetTexCoord(x1 or 0, x2 or 1, y1 or 0, y2 or 1) border:SetBlendMode(blendMode or "BLEND") border:Show() end if self.JunkIcon then local quality = self.hasItem and select(3, GetItemInfo(self.itemLink or self.itemId)) self.JunkIcon:SetShown(quality == ITEM_QUALITY_POOR and addon:GetInteractingWindow() == "MERCHANT") end if isolatedEvent then addon:SendMessage('AdiBags_UpdateBorder', self) end end -------------------------------------------------------------------------------- -- Item stack button -------------------------------------------------------------------------------- local stackClass, stackProto = addon:NewClass("StackButton", "Frame", "ABEvent-1.0") addon:CreatePool(stackClass, "AcquireStackButton") function stackProto:OnCreate() self:SetWidth(ITEM_SIZE) self:SetHeight(ITEM_SIZE) self.slots = {} self:SetScript('OnShow', self.OnShow) self:SetScript('OnHide', self.OnHide) self.GetCountHook = function() return self.count end end function stackProto:OnAcquire(container, key) self.container = container self.key = key self.count = 0 self.dirtyCount = true self:SetParent(container) end function stackProto:OnRelease() self:SetVisibleSlot(nil) self:SetSection(nil) self.key = nil self.container = nil wipe(self.slots) end function stackProto:GetCount() return self.count end function stackProto:IsStack() return true end function stackProto:GetRealButton() return self.button end function stackProto:GetKey() return self.key end function stackProto:UpdateVisibleSlot() local bestLockedId, bestLockedCount local bestUnlockedId, bestUnlockedCount if self.slotId and self.slots[self.slotId] then local _, count, locked = GetContainerItemInfo(GetBagSlotFromId(self.slotId)) count = count or 1 if locked then bestLockedId, bestLockedCount = self.slotId, count else bestUnlockedId, bestUnlockedCount = self.slotId, count end end for slotId in pairs(self.slots) do local _, count, locked = GetContainerItemInfo(GetBagSlotFromId(slotId)) count = count or 1 if locked then if not bestLockedId or count > bestLockedCount then bestLockedId, bestLockedCount = slotId, count end else if not bestUnlockedId or count > bestUnlockedCount then bestUnlockedId, bestUnlockedCount = slotId, count end end end return self:SetVisibleSlot(bestUnlockedId or bestLockedId) end function stackProto:ITEM_LOCK_CHANGED() return self:Update() end function stackProto:AddSlot(slotId) local slots = self.slots if not slots[slotId] then slots[slotId] = true self.dirtyCount = true self:Update() end end function stackProto:RemoveSlot(slotId) local slots = self.slots if slots[slotId] then slots[slotId] = nil self.dirtyCount = true self:Update() end end function stackProto:IsEmpty() return not next(self.slots) end function stackProto:OnShow() self:RegisterMessage('AdiBags_UpdateAllButtons', 'Update') self:RegisterMessage('AdiBags_PostContentUpdate') self:RegisterEvent('ITEM_LOCK_CHANGED') if self.button then self.button:Show() end self:Update() end function stackProto:OnHide() if self.button then self.button:Hide() end self:UnregisterAllEvents() self:UnregisterAllMessages() end function stackProto:SetVisibleSlot(slotId) if slotId == self.slotId then return end self.slotId = slotId local button = self.button local mouseover = false if button then if button:IsMouseOver() then mouseover = true button:GetScript('OnLeave')(button) end button.GetCount = nil button:Release() end if slotId then button = addon:AcquireItemButton(self.container, GetBagSlotFromId(slotId)) button.GetCount = self.GetCountHook button:SetAllPoints(self) button:SetStack(self) button:Show() if mouseover then button:GetScript('OnEnter')(button) end else button = nil end self.button = button return true end function stackProto:Update() if not self:CanUpdate() then return end self:UpdateVisibleSlot() self:UpdateCount() if self.button then self.button:Update() end end stackProto.FullUpdate = stackProto.Update function stackProto:UpdateCount() local count = 0 for slotId in pairs(self.slots) do count = count + (select(2, GetContainerItemInfo(GetBagSlotFromId(slotId))) or 1) end self.count = count self.dirtyCount = nil end function stackProto:AdiBags_PostContentUpdate() if self.dirtyCount then self:UpdateCount() end end function stackProto:GetItemId() return self.button and self.button:GetItemId() end function stackProto:GetItemLink() return self.button and self.button:GetItemLink() end function stackProto:IsBank() return self.button and self.button:IsBank() end function stackProto:GetBagFamily() return self.button and self.button:GetBagFamily() end local function StackSlotIterator(self, previous) local slotId = next(self.slots, previous) if slotId then local bag, slot = GetBagSlotFromId(slotId) local _, count = GetContainerItemInfo(bag, slot) return slotId, bag, slot, self:GetItemId(), count end end function stackProto:IterateSlots() return StackSlotIterator, self end -- Reuse button methods stackProto.CanUpdate = buttonProto.CanUpdate stackProto.SetSection = buttonProto.SetSection stackProto.GetSection = buttonProto.GetSection
gpl-3.0
create-bot/mybot
plugins/all.lua
1
4199
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'chat stats! \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) if not data[tostring(target)] then return 'Group is not added.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group \n \n" local settings = show_group_settings(target) text = text.."Group settings \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\n"..modlist local link = get_link(target) text = text.."\n\n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] and msg.to.id ~= our_id then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end return end return { patterns = { "^[](all)$", "^[](all) (%d+)$" }, run = run } end
gpl-2.0
CarabusX/Zero-K
effects/solange.lua
7
1941
-- solange -- solange_pillar return { ["solange"] = { nw = { air = true, class = [[CExpGenSpawner]], count = 150, ground = true, water = true, underwater = true, properties = { delay = [[0 i4]], explosiongenerator = [[custom:SOLANGE_PILLAR]], pos = [[20 r40, i20, -20 r40]], }, }, }, ["solange_pillar"] = { rocks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, underwater = true, properties = { airdrag = 0.97, alwaysvisible = true, colormap = [[0.0 0.00 0.0 0.01 0.9 0.90 0.0 0.50 0.9 0.90 0.0 0.50 0.8 0.80 0.1 0.50 0.7 0.70 0.2 0.50 0.5 0.35 0.0 0.50 0.5 0.35 0.0 0.50 0.5 0.35 0.0 0.50 0.5 0.35 0.0 0.50 0.0 0.00 0.0 0.01]], directional = true, emitrot = 90, emitrotspread = 10, emitvector = [[0, 1, 0]], gravity = [[0.001 r-0.002, 0.01 r-0.02, 0.001 r-0.002]], numparticles = 1, particlelife = 150, particlelifespread = 150, particlesize = 90, particlesizespread = 90, particlespeed = 3, particlespeedspread = 3, pos = [[0, 0, 0]], sizegrowth = 0.05, sizemod = 1.0, texture = [[fireball]], }, }, }, }
gpl-2.0
houqp/koreader-base
ffi/blitbuffer.lua
1
66239
--[[-- Generic blitbuffer/GFX stuff that works on memory buffers @module ffi.blitbuffer --]] local bit = require("bit") local ffi = require("ffi") local util = require("ffi/util") local C = ffi.C -- we will use this extensively local floor = math.floor local ceil = math.ceil local min = math.min local rshift = bit.rshift local lshift = bit.lshift local band = bit.band local bor = bit.bor local bxor = bit.bxor local uint32pt = ffi.typeof("uint32_t*") local uint16pt = ffi.typeof("uint16_t*") local uint8pt = ffi.typeof("uint8_t*") local posix = require("ffi/posix_h") -- luacheck: ignore 211 local debug = debug -- the following definitions are redundant. -- they need to be since only this way we can set -- different metatables for them. ffi.cdef[[ typedef struct Color4L { uint8_t a; } Color4L; typedef struct Color4U { uint8_t a; } Color4U; typedef struct Color8 { uint8_t a; } Color8; typedef struct Color8A { uint8_t a; uint8_t alpha; } Color8A; typedef struct ColorRGB16 { uint16_t v; } ColorRGB16; typedef struct ColorRGB24 { uint8_t r; uint8_t g; uint8_t b; } ColorRGB24; typedef struct ColorRGB32 { uint8_t r; uint8_t g; uint8_t b; uint8_t alpha; } ColorRGB32; typedef struct BlitBuffer { int w; int phys_w; int h; int phys_h; int pitch; uint8_t *data; uint8_t config; } BlitBuffer; typedef struct BlitBuffer4 { int w; int phys_w; int h; int phys_h; int pitch; uint8_t *data; uint8_t config; } BlitBuffer4; typedef struct BlitBuffer8 { int w; int phys_w; int h; int phys_h; int pitch; Color8 *data; uint8_t config; } BlitBuffer8; typedef struct BlitBuffer8A { int w; int phys_w; int h; int phys_h; int pitch; Color8A *data; uint8_t config; } BlitBuffer8A; typedef struct BlitBufferRGB16 { int w; int phys_w; int h; int phys_h; int pitch; ColorRGB16 *data; uint8_t config; } BlitBufferRGB16; typedef struct BlitBufferRGB24 { int w; int phys_w; int h; int phys_h; int pitch; ColorRGB24 *data; uint8_t config; } BlitBufferRGB24; typedef struct BlitBufferRGB32 { int w; int phys_w; int h; int phys_h; int pitch; ColorRGB32 *data; uint8_t config; } BlitBufferRGB32; void BB_fill_rect(BlitBuffer *bb, int x, int y, int w, int h, uint8_t v); void BB_blend_rect(BlitBuffer *bb, int x, int y, int w, int h, Color8A *color); void BB_invert_rect(BlitBuffer *bb, int x, int y, int w, int h); void BB_blit_to(BlitBuffer *source, BlitBuffer *dest, int dest_x, int dest_y, int offs_x, int offs_y, int w, int h); void BB_add_blit_from(BlitBuffer *dest, BlitBuffer *source, int dest_x, int dest_y, int offs_x, int offs_y, int w, int h, uint8_t alpha); void BB_alpha_blit_from(BlitBuffer *dest, BlitBuffer *source, int dest_x, int dest_y, int offs_x, int offs_y, int w, int h); void BB_pmulalpha_blit_from(BlitBuffer *dest, BlitBuffer *source, int dest_x, int dest_y, int offs_x, int offs_y, int w, int h); void BB_invert_blit_from(BlitBuffer *dest, BlitBuffer *source, int dest_x, int dest_y, int offs_x, int offs_y, int w, int h); void BB_color_blit_from(BlitBuffer *dest, BlitBuffer *source, int dest_x, int dest_y, int offs_x, int offs_y, int w, int h, Color8A *color); void *malloc(int size); void free(void *ptr); ]] -- NOTE: Try the C blitter, unless it was disabled by the user local no_cbb_flag = os.getenv("KO_NO_CBB") local use_cblitbuffer, cblitbuffer if not no_cbb_flag or no_cbb_flag == "false" then use_cblitbuffer, cblitbuffer = pcall(ffi.load, 'blitbuffer') end -- NOTE: This works-around a number of corner-cases which may end up with LuaJIT's optimizer blacklisting this very codepath, -- which'd obviously *murder* performance (to the effect of a soft-lock, essentially). -- c.f., #4137, #4752, #4782 if not use_cblitbuffer then io.write("Tweaking LuaJIT's max loop unroll factor (15 -> 45)\n") io.flush() jit.opt.start("loopunroll=45") end -- color value types local Color4U = ffi.typeof("Color4U") local Color4L = ffi.typeof("Color4L") local Color8 = ffi.typeof("Color8") local Color8A = ffi.typeof("Color8A") local ColorRGB16 = ffi.typeof("ColorRGB16") local ColorRGB24 = ffi.typeof("ColorRGB24") local ColorRGB32 = ffi.typeof("ColorRGB32") -- color value pointer types local P_Color4U = ffi.typeof("Color4U*") local P_Color4L = ffi.typeof("Color4L*") local P_Color8 = ffi.typeof("Color8*") -- luacheck: ignore 211 local P_Color8A = ffi.typeof("Color8A*") -- luacheck: ignore 211 local P_ColorRGB16 = ffi.typeof("ColorRGB16*") -- luacheck: ignore 211 local P_ColorRGB24 = ffi.typeof("ColorRGB24*") -- luacheck: ignore 211 local P_ColorRGB32 = ffi.typeof("ColorRGB32*") -- luacheck: ignore 211 -- metatables for color types: local Color4L_mt = {__index={}} local Color4U_mt = {__index={}} local Color8_mt = {__index={}} local Color8A_mt = {__index={}} local ColorRGB16_mt = {__index={}} local ColorRGB24_mt = {__index={}} local ColorRGB32_mt = {__index={}} -- color setting function Color4L_mt.__index:set(color) self.a = bor(band(0xF0, self.a), color:getColor4L().a) end function Color4U_mt.__index:set(color) self.a = bor(band(0x0F, self.a), color:getColor4U().a) end function Color8_mt.__index:set(color) self.a = color:getColor8().a end function Color8A_mt.__index:set(color) local c = color:getColor8A() self.a = c.a self.alpha = c.alpha end function ColorRGB16_mt.__index:set(color) self.v = color:getColorRGB16().v end function ColorRGB24_mt.__index:set(color) local c = color:getColorRGB24() self.r = c.r self.g = c.g self.b = c.b end function ColorRGB32_mt.__index:set(color) local c = color:getColorRGB32() self.r = c.r self.g = c.g self.b = c.b self.alpha = c.alpha end -- alpha blending (8bit alpha value): local function div255(value) return rshift(value + 0x01 + rshift(value, 8), 8) end local function div4080(value) return rshift(value + 0x01 + rshift(value, 8), 12) end function Color4L_mt.__index:blend(color, coverage) local alpha = coverage or color:getAlpha() -- simplified: we expect a 8bit grayscale "color" as parameter local value = div4080(band(self.a, 0x0F) * 0x11 * bxor(alpha, 0xFF) + color:getR() * alpha) self:set(Color4L(value)) end function Color4U_mt.__index:blend(color, coverage) local alpha = coverage or color:getAlpha() local orig = band(self.a, 0xF0) -- simplified: we expect a 8bit grayscale "color" as parameter local value = div255((orig + rshift(orig, 4)) * bxor(alpha, 0xFF) + color:getR() * alpha) self:set(Color4U(value)) end function Color8_mt.__index:blend(color, coverage) local alpha = coverage or color:getAlpha() -- simplified: we expect a 8bit grayscale "color" as parameter local value = div255(self.a * bxor(alpha, 0xFF) + color:getR() * alpha) self:set(Color8(value)) end function Color8A_mt.__index:blend(color, coverage) local alpha = coverage or color:getAlpha() -- simplified: we expect a 8bit grayscale "color" as parameter local value = div255(self.a * bxor(alpha, 0xFF) + color:getR() * alpha) self:set(Color8A(value, self:getAlpha())) end function ColorRGB16_mt.__index:blend(color, coverage) local alpha = coverage or color:getAlpha() local ainv = bxor(alpha, 0xFF) local r = div255(self:getR() * ainv + color:getR() * alpha) local g = div255(self:getG() * ainv + color:getG() * alpha) local b = div255(self:getB() * ainv + color:getB() * alpha) self:set(ColorRGB24(r, g, b)) end ColorRGB24_mt.__index.blend = ColorRGB16_mt.__index.blend function ColorRGB32_mt.__index:blend(color, coverage) local alpha = coverage or color:getAlpha() local ainv = bxor(alpha, 0xFF) local r = div255(self:getR() * ainv + color:getR() * alpha) local g = div255(self:getG() * ainv + color:getG() * alpha) local b = div255(self:getB() * ainv + color:getB() * alpha) self:set(ColorRGB32(r, g, b, self:getAlpha())) end -- alpha blending with a premultiplied input (i.e., color OVER self, w/ color being premultiplied) function Color4L_mt.__index:pmulblend(color) local alpha = color:getAlpha() -- simplified: we expect a 8bit grayscale "color" as parameter local value = div4080(band(self.a, 0x0F) * 0x11 * bxor(alpha, 0xFF) + color:getR() * 0xFF) self:set(Color4L(value)) end function Color4U_mt.__index:pmulblend(color) local alpha = color:getAlpha() local orig = band(self.a, 0xF0) -- simplified: we expect a 8bit grayscale "color" as parameter local value = div255((orig + rshift(orig, 4)) * bxor(alpha, 0xFF) + color:getR() * 0xFF) self:set(Color4U(value)) end function Color8_mt.__index:pmulblend(color) local alpha = color:getAlpha() -- simplified: we expect a 8bit grayscale "color" as parameter local value = div255(self.a * bxor(alpha, 0xFF) + color:getR() * 0xFF) self:set(Color8(value)) end function Color8A_mt.__index:pmulblend(color) local alpha = color:getAlpha() -- simplified: we expect a 8bit grayscale "color" as parameter local value = div255(self.a * bxor(alpha, 0xFF) + color:getR() * 0xFF) self:set(Color8A(value, self:getAlpha())) end function ColorRGB16_mt.__index:pmulblend(color) local alpha = color:getAlpha() local ainv = bxor(alpha, 0xFF) local r = div255(self:getR() * ainv + color:getR() * 0xFF) local g = div255(self:getG() * ainv + color:getG() * 0xFF) local b = div255(self:getB() * ainv + color:getB() * 0xFF) self:set(ColorRGB24(r, g, b)) end ColorRGB24_mt.__index.pmulblend = ColorRGB16_mt.__index.pmulblend function ColorRGB32_mt.__index:pmulblend(color) local alpha = color:getAlpha() local ainv = bxor(alpha, 0xFF) local r = div255(self:getR() * ainv + color:getR() * 0xFF) local g = div255(self:getG() * ainv + color:getG() * 0xFF) local b = div255(self:getB() * ainv + color:getB() * 0xFF) self:set(ColorRGB32(r, g, b, self:getAlpha())) end -- color conversions: -- to Color4L: function Color4L_mt.__index:getColor4L() return Color4L(band(0x0F, self.a)) end function Color4U_mt.__index:getColor4L() return Color4L(rshift(self.a, 4)) end function Color8_mt.__index:getColor4L() return Color4L(rshift(self.a, 4)) end function Color8A_mt.__index:getColor4L() return Color4L(rshift(self.a, 4)) end --[[ Uses luminance match for approximating the human perception of colour, as per http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale L = 0.299*Red + 0.587*Green + 0.114*Blue --]] function ColorRGB16_mt.__index:getColor4L() local r = rshift(self.v, 11) local g = band(rshift(self.v, 5), 0x3F) local b = band(self.v, 0x001F) return Color4L(rshift(39919*r + 39185*g + 15220*b, 18)) end function ColorRGB24_mt.__index:getColor4L() return Color4L(rshift(4898*self.r + 9618*self.g + 1869*self.b, 18)) end ColorRGB32_mt.__index.getColor4L = ColorRGB24_mt.__index.getColor4L -- to Color4U: function Color4L_mt.__index:getColor4U() return Color4U(lshift(self.a, 4)) end function Color4U_mt.__index:getColor4U() return Color4U(band(0xF0, self.a)) end function Color8_mt.__index:getColor4U() return Color4U(band(0xF0, self.a)) end function Color8A_mt.__index:getColor4U() return Color4U(band(0xF0, self.a)) end function ColorRGB16_mt.__index:getColor4U() local r = rshift(self.v, 11) local g = band(rshift(self.v, 5), 0x3F) local b = band(self.v, 0x001F) return Color4U(band(0xF0, rshift(39919*r + 39185*g + 15220*b, 14))) end function ColorRGB24_mt.__index:getColor4U() return Color4U(band(0xF0, rshift(4898*self.r + 9618*self.g + 1869*self.b, 14))) end ColorRGB32_mt.__index.getColor4U = ColorRGB24_mt.__index.getColor4U -- to Color8: function Color4L_mt.__index:getColor8() local v = band(0x0F, self.a) return Color8(v*0x11) end function Color4U_mt.__index:getColor8() local v = band(0xF0, self.a) return Color8(bor(rshift(v, 4), v)) end function Color8_mt.__index:getColor8() return self end function Color8A_mt.__index:getColor8() return Color8(self.a) end function ColorRGB16_mt.__index:getColor8() local r = rshift(self.v, 11) local g = band(rshift(self.v, 5), 0x3F) local b = band(self.v, 0x001F) return Color8(rshift(39919*r + 39185*g + 15220*b, 14)) end function ColorRGB24_mt.__index:getColor8() return Color8(rshift(4898*self:getR() + 9618*self:getG() + 1869*self:getB(), 14)) end ColorRGB32_mt.__index.getColor8 = ColorRGB24_mt.__index.getColor8 -- to Color8A: function Color4L_mt.__index:getColor8A() local v = band(0x0F, self.a) return Color8A(v*0x11, 0xFF) end function Color4U_mt.__index:getColor8A() local v = band(0xF0, self.a) return Color8A(bor(rshift(v, 4), v), 0xFF) end function Color8_mt.__index:getColor8A() return Color8A(self.a, 0xFF) end function Color8A_mt.__index:getColor8A() return self end function ColorRGB16_mt.__index:getColor8A() local r = rshift(self.v, 11) local g = band(rshift(self.v, 5), 0x3F) local b = band(self.v, 0x001F) return Color8A(rshift(39919*r + 39185*g + 15220*b, 14), 0xFF) end function ColorRGB24_mt.__index:getColor8A() return Color8A(rshift(4898*self:getR() + 9618*self:getG() + 1869*self:getB(), 14), 0xFF) end function ColorRGB32_mt.__index:getColor8A() return Color8A(rshift(4898*self:getR() + 9618*self:getG() + 1869*self:getB(), 14), self:getAlpha()) end -- to ColorRGB16: function Color4L_mt.__index:getColorRGB16() local v = self:getColor8().a local v5bit = rshift(v, 3) return ColorRGB16(lshift(v5bit, 11) + lshift(band(v, 0xFC), 3) + v5bit) end Color4U_mt.__index.getColorRGB16 = Color4L_mt.__index.getColorRGB16 Color8_mt.__index.getColorRGB16 = Color4L_mt.__index.getColorRGB16 Color8A_mt.__index.getColorRGB16 = Color4L_mt.__index.getColorRGB16 function ColorRGB16_mt.__index:getColorRGB16() return self end function ColorRGB24_mt.__index:getColorRGB16() return ColorRGB16(lshift(band(self.r, 0xF8), 8) + lshift(band(self.g, 0xFC), 3) + rshift(self.b, 3)) end ColorRGB32_mt.__index.getColorRGB16 = ColorRGB24_mt.__index.getColorRGB16 -- to ColorRGB24: function Color4L_mt.__index:getColorRGB24() local v = self:getColor8() return ColorRGB24(v.a, v.a, v.a) end Color4U_mt.__index.getColorRGB24 = Color4L_mt.__index.getColorRGB24 Color8_mt.__index.getColorRGB24 = Color4L_mt.__index.getColorRGB24 Color8A_mt.__index.getColorRGB24 = Color4L_mt.__index.getColorRGB24 function ColorRGB16_mt.__index:getColorRGB24() local r = rshift(self.v, 11) local g = band(rshift(self.v, 5), 0x3F) local b = band(self.v, 0x001F) return ColorRGB24(lshift(r, 3) + rshift(r, 2), lshift(g, 2) + rshift(g, 4), lshift(b, 3) + rshift(b, 2)) end function ColorRGB24_mt.__index:getColorRGB24() return self end function ColorRGB32_mt.__index:getColorRGB24() return ColorRGB24(self.r, self.g, self.b) end -- to ColorRGB32: function Color4L_mt.__index:getColorRGB32() local v = self:getColor8() return ColorRGB32(v.a, v.a, v.a, 0xFF) end Color4U_mt.__index.getColorRGB32 = Color4L_mt.__index.getColorRGB32 Color8_mt.__index.getColorRGB32 = Color4L_mt.__index.getColorRGB32 function Color8A_mt.__index:getColorRGB32() return ColorRGB32(self.a, self.a, self.a, self.alpha) end function ColorRGB16_mt.__index:getColorRGB32() local r = rshift(self.v, 11) local g = band(rshift(self.v, 5), 0x3F) local b = band(self.v, 0x001F) return ColorRGB32(lshift(r, 3) + rshift(r, 2), lshift(g, 2) + rshift(g, 4), lshift(b, 3) + rshift(b, 2), 0xFF) end function ColorRGB24_mt.__index:getColorRGB32() return ColorRGB32(self.r, self.g, self.b, 0xFF) end function ColorRGB32_mt.__index:getColorRGB32() return self end -- RGB getters (special case for 4bpp mode) function Color4L_mt.__index:getR() return self:getColor8().a end Color4L_mt.__index.getG = Color4L_mt.__index.getR Color4L_mt.__index.getB = Color4L_mt.__index.getR function Color4L_mt.__index:getAlpha() return 0xFF end Color4U_mt.__index.getR = Color4L_mt.__index.getR Color4U_mt.__index.getG = Color4L_mt.__index.getR Color4U_mt.__index.getB = Color4L_mt.__index.getR Color4U_mt.__index.getAlpha = Color4L_mt.__index.getAlpha Color8_mt.__index.getR = Color4L_mt.__index.getR Color8_mt.__index.getG = Color4L_mt.__index.getR Color8_mt.__index.getB = Color4L_mt.__index.getR Color8_mt.__index.getAlpha = Color4L_mt.__index.getAlpha Color8A_mt.__index.getR = Color4L_mt.__index.getR Color8A_mt.__index.getG = Color4L_mt.__index.getR Color8A_mt.__index.getB = Color4L_mt.__index.getR function Color8A_mt.__index:getAlpha() return self.alpha end function ColorRGB16_mt.__index:getR() local r = rshift(self.v, 11) return lshift(r, 3) + rshift(r, 2) end function ColorRGB16_mt.__index:getG() local g = band(rshift(self.v, 5), 0x3F) return lshift(g, 2) + rshift(g, 4) end function ColorRGB16_mt.__index:getB() local b = band(self.v, 0x001F) return lshift(b, 3) + rshift(b, 2) end ColorRGB16_mt.__index.getAlpha = Color4L_mt.__index.getAlpha function ColorRGB24_mt.__index:getR() return self.r end function ColorRGB24_mt.__index:getG() return self.g end function ColorRGB24_mt.__index:getB() return self.b end ColorRGB24_mt.__index.getAlpha = Color4L_mt.__index.getAlpha ColorRGB32_mt.__index.getR = ColorRGB24_mt.__index.getR ColorRGB32_mt.__index.getG = ColorRGB24_mt.__index.getG ColorRGB32_mt.__index.getB = ColorRGB24_mt.__index.getB function ColorRGB32_mt.__index:getAlpha() return self.alpha end -- modifications: -- inversion: function Color4L_mt.__index:invert() return Color4L(bxor(self.a, 0x0F)) end function Color4U_mt.__index:invert() return Color4U(bxor(self.a, 0xF0)) end function Color8_mt.__index:invert() return Color8(bxor(self.a, 0xFF)) end function Color8A_mt.__index:invert() return Color8A(bxor(self.a, 0xFF), self.alpha) end function ColorRGB16_mt.__index:invert() return ColorRGB16(bxor(self.v, 0xFFFF)) end function ColorRGB24_mt.__index:invert() return ColorRGB24(bxor(self.r, 0xFF), bxor(self.g, 0xFF), bxor(self.b, 0xFF)) end function ColorRGB32_mt.__index:invert() return ColorRGB32(bxor(self.r, 0xFF), bxor(self.g, 0xFF), bxor(self.b, 0xFF), self.alpha) end -- comparison: function ColorRGB32_mt:__eq(c) c = c:getColorRGB32() return (self:getR() == c:getR()) and (self:getG() == c:getG()) and (self:getB() == c:getB()) and (self:getAlpha() == c:getAlpha()) end Color4L_mt.__eq = ColorRGB32_mt.__eq Color4U_mt.__eq = ColorRGB32_mt.__eq Color8_mt.__eq = ColorRGB32_mt.__eq Color8A_mt.__eq = ColorRGB32_mt.__eq ColorRGB16_mt.__eq = ColorRGB32_mt.__eq ColorRGB24_mt.__eq = ColorRGB32_mt.__eq -- pretty printing function Color4L_mt:__tostring() return "Color4L("..band(self.a, 0x0F)..")" end function Color4U_mt:__tostring() return "Color4U("..rshift(band(self.a, 0xF0),4)..")" end function Color8_mt:__tostring() return "Color8("..self.a..")" end function Color8A_mt:__tostring() return "Color8A("..self.a ..", "..self.alpha..")" end function ColorRGB16_mt:__tostring() return "ColorRGB16("..self:getR()..", "..self:getG()..", "..self:getB()..")" end function ColorRGB24_mt:__tostring() return "ColorRGB24("..self:getR()..", "..self:getG()..", "..self:getB()..")" end function ColorRGB32_mt:__tostring() return "ColorRGB32("..self:getR()..", "..self:getG()..", "..self:getB()..", "..self:getAlpha()..")" end local MASK_ALLOCATED = 0x01 local SHIFT_ALLOCATED = 0 local MASK_INVERSE = 0x02 local SHIFT_INVERSE = 1 local MASK_ROTATED = 0x0C local SHIFT_ROTATED = 2 local MASK_TYPE = 0xF0 local SHIFT_TYPE = 4 local TYPE_BB4 = 0 local TYPE_BB8 = 1 local TYPE_BB8A = 2 local TYPE_BBRGB16 = 3 local TYPE_BBRGB24 = 4 local TYPE_BBRGB32 = 5 local BB = {} -- metatables for BlitBuffer objects: local BB4_mt = {__index={}} local BB8_mt = {__index={}} local BB8A_mt = {__index={}} local BBRGB16_mt = {__index={}} local BBRGB24_mt = {__index={}} local BBRGB32_mt = {__index={}} -- this is like a metatable for the others, -- but we don't make it a metatable because LuaJIT -- doesn't cope well with ctype metatables with -- metatables on them -- we just replicate what's in the following table -- when we set the other metatables for their types local BB_mt = {__index={}} function BB_mt.__index:getRotation() return rshift(band(MASK_ROTATED, self.config), SHIFT_ROTATED) end function BB_mt.__index:setRotation(rotation_mode) self.config = bor(band(self.config, bxor(MASK_ROTATED, 0xFF)), lshift(rotation_mode, SHIFT_ROTATED)) end function BB_mt.__index:rotateAbsolute(degree) local mode = (degree % 360) / 90 self:setRotation(mode) return self end function BB_mt.__index:rotate(degree) degree = degree + self:getRotation()*90 return self:rotateAbsolute(degree) end function BB_mt.__index:getInverse() return rshift(band(MASK_INVERSE, self.config), SHIFT_INVERSE) end function BB_mt.__index:setInverse(inverse) self.config = bor(band(self.config, bxor(MASK_INVERSE, 0xFF)), lshift(inverse, SHIFT_INVERSE)) end function BB_mt.__index:invert() self:setInverse(band(self:getInverse() + 1, 1)) return self end function BB_mt.__index:getAllocated() return rshift(band(MASK_ALLOCATED, self.config), SHIFT_ALLOCATED) end function BB_mt.__index:setAllocated(allocated) self.config = bor(band(self.config, bxor(MASK_ALLOCATED, 0xFF)), lshift(allocated, SHIFT_ALLOCATED)) end function BB_mt.__index:getType() return rshift(band(MASK_TYPE, self.config), SHIFT_TYPE) end -- Bits per pixel function BB4_mt.__index:getBpp() return 4 end function BB8_mt.__index:getBpp() return 8 end function BB8A_mt.__index:getBpp() return 16 end function BBRGB16_mt.__index:getBpp() return 16 end function BBRGB24_mt.__index:getBpp() return 24 end function BBRGB32_mt.__index:getBpp() return 32 end -- Or, generally more useful, bytes per pixel function BB4_mt.__index:getBytesPerPixel() return 0.5 end function BB8_mt.__index:getBytesPerPixel() return 1 end function BB8A_mt.__index:getBytesPerPixel() return 2 end function BBRGB16_mt.__index:getBytesPerPixel() return 2 end function BBRGB24_mt.__index:getBytesPerPixel() return 3 end function BBRGB32_mt.__index:getBytesPerPixel() return 4 end function BB_mt.__index:isRGB() local bb_type = self:getType() if bb_type == TYPE_BBRGB16 or bb_type == TYPE_BBRGB24 or bb_type == TYPE_BBRGB32 then return true end return false end function BB_mt.__index:setType(type_id) self.config = bor(band(self.config, bxor(MASK_TYPE, 0xFF)), lshift(type_id, SHIFT_TYPE)) end function BB_mt.__index:getPhysicalCoordinates(x, y) local rotation = self:getRotation() if rotation == 0 then return x, y elseif rotation == 1 then return self.w - y - 1, x elseif rotation == 2 then return self.w - x - 1, self.h - y - 1 elseif rotation == 3 then return y, self.h - x - 1 end end function BB_mt.__index:getPhysicalRect(x, y, w, h) local rotation = self:getRotation() if rotation == 0 then return x, y, w, h elseif rotation == 1 then return self.w - (y + h), x, h, w elseif rotation == 2 then return self.w - (x + w), self.h - (y + h), w, h elseif rotation == 3 then return y, self.h - (x + w), h, w end end -- physical coordinate checking function BB_mt.__index:checkCoordinates(x, y) assert(x >= 0, "x coordinate >= 0") assert(y >= 0, "y coordinate >= 0") assert(x < self:getWidth(), "x coordinate < width") assert(y < self:getHeight(), "y coordinate < height") end -- getPixelP (pointer) routines, working on physical coordinates function BB_mt.__index:getPixelP(x, y) --self:checkCoordinates(x, y) return ffi.cast(self.data, ffi.cast(uint8pt, self.data) + self.pitch*y) + x end function BB4_mt.__index:getPixelP(x, y) --self:checkCoordinates(x, y) local p = self.data + self.pitch*y + rshift(x, 1) if band(x, 1) == 0 then return ffi.cast(P_Color4U, p) else return ffi.cast(P_Color4L, p) end end function BB_mt.__index:getPixel(x, y) local px, py = self:getPhysicalCoordinates(x, y) local color = self:getPixelP(px, py)[0] if self:getInverse() == 1 then color = color:invert() end return color end -- blitbuffer specific color conversions function BB4_mt.__index.getMyColor(color) return color:getColor4L() end function BB8_mt.__index.getMyColor(color) return color:getColor8() end function BB8A_mt.__index.getMyColor(color) return color:getColor8A() end function BBRGB16_mt.__index.getMyColor(color) return color:getColorRGB16() end function BBRGB24_mt.__index.getMyColor(color) return color:getColorRGB24() end function BBRGB32_mt.__index.getMyColor(color) return color:getColorRGB32() end -- set pixel values function BB_mt.__index:setPixel(x, y, color) local px, py = self:getPhysicalCoordinates(x, y) -- NOTE: The cbb exemption is because it's assuming you're using an inverted bb copy to handle nightmode (c.f., Android & SDL2), -- and setPixel can be used from outside blitFrom, unlike the other setters. if not use_cblitbuffer and self:getInverse() == 1 then color = color:invert() end self:getPixelP(px, py)[0]:set(color) end function BB_mt.__index:setPixelAdd(x, y, color, alpha) -- fast path: if alpha == 0 then return elseif alpha == 0xFF then return self:setPixel(x, y, color) end -- this method works with a grayscale value local px, py = self:getPhysicalCoordinates(x, y) color = color:getColor8A() if self:getInverse() == 1 then color = color:invert() end color.alpha = alpha self:getPixelP(px, py)[0]:blend(color) end function BBRGB16_mt.__index:setPixelAdd(x, y, color, alpha) -- fast path: if alpha == 0 then return elseif alpha == 0xFF then return self:setPixel(x, y, color) end -- this method uses an RGB color value local px, py = self:getPhysicalCoordinates(x, y) if self:getInverse() == 1 then color = color:invert() end color = color:getColorRGB32() color.alpha = alpha self:getPixelP(px, py)[0]:blend(color) end BBRGB24_mt.__index.setPixelAdd = BBRGB16_mt.__index.setPixelAdd BBRGB32_mt.__index.setPixelAdd = BBRGB16_mt.__index.setPixelAdd function BB_mt.__index:setPixelBlend(x, y, color) -- fast path: local alpha = color:getAlpha() if alpha == 0 then return end local px, py = self:getPhysicalCoordinates(x, y) if alpha == 0xFF then self:getPixelP(px, py)[0]:set(color) else -- The blend method for these types of target BB assumes a grayscale input color = color:getColor8A() if self:getInverse() == 1 then color = color:invert() end self:getPixelP(px, py)[0]:blend(color) end end function BBRGB16_mt.__index:setPixelBlend(x, y, color) -- fast path: local alpha = color:getAlpha() if alpha == 0 then return end local px, py = self:getPhysicalCoordinates(x, y) if alpha == 0xFF then self:getPixelP(px, py)[0]:set(color) else if self:getInverse() == 1 then color = color:invert() end self:getPixelP(px, py)[0]:blend(color) end end BBRGB24_mt.__index.setPixelBlend = BBRGB16_mt.__index.setPixelBlend BBRGB32_mt.__index.setPixelBlend = BBRGB16_mt.__index.setPixelBlend function BB_mt.__index:setPixelPmulBlend(x, y, color) -- fast path: local alpha = color:getAlpha() if alpha == 0 then return end local px, py = self:getPhysicalCoordinates(x, y) if alpha == 0xFF then self:getPixelP(px, py)[0]:set(color) else -- The pmulblend method for these types of target BB assumes a grayscale input color = color:getColor8A() if self:getInverse() == 1 then color = color:invert() end self:getPixelP(px, py)[0]:pmulblend(color) end end function BBRGB16_mt.__index:setPixelPmulBlend(x, y, color) -- fast path: local alpha = color:getAlpha() if alpha == 0 then return end local px, py = self:getPhysicalCoordinates(x, y) if alpha == 0xFF then self:getPixelP(px, py)[0]:set(color) else if self:getInverse() == 1 then color = color:invert() end self:getPixelP(px, py)[0]:pmulblend(color) end end BBRGB24_mt.__index.setPixelPmulBlend = BBRGB16_mt.__index.setPixelPmulBlend BBRGB32_mt.__index.setPixelPmulBlend = BBRGB16_mt.__index.setPixelPmulBlend function BB_mt.__index:setPixelColorize(x, y, mask, color) -- use 8bit grayscale pixel value as alpha for blitting local alpha = mask:getColor8().a -- fast path: if alpha == 0 then return end local px, py = self:getPhysicalCoordinates(x, y) if alpha == 0xFF then self:getPixelP(px, py)[0]:set(color) else -- NOTE: We're using an alpha mask, not color's actual alpha value, which we don't want to mess with, -- as that's a pointer to our set_param... -- Avoids screwing with alpha when blitting to 8A or RGB32 bbs (c.f., #3949). self:getPixelP(px, py)[0]:blend(color, alpha) end end function BB_mt.__index:setPixelInverted(x, y, color) self:setPixel(x, y, color:invert()) end -- checked Pixel setting: function BB_mt.__index:setPixelClamped(x, y, color) if x >= 0 and x < self:getWidth() and y >= 0 and y < self:getHeight() then self:setPixel(x, y, color) end end -- functions for accessing dimensions function BB_mt.__index:getWidth() if 0 == band(1, self:getRotation()) then return self.w else return self.h end end function BB_mt.__index:getPhysicalWidth() -- NOTE: On eInk devices, alignment is very different between xres_virtual & yres_virtual, -- so honoring rotation here is a bit iffy... -- c.f., framebuffer_linux.lua -- This is why we generally access phys_w or phys_h directly, -- unless we're sure having those inverted is going to be irrelevant. if 0 == band(1, self:getRotation()) then return self.phys_w else return self.phys_h end end function BB_mt.__index:getHeight() if 0 == band(1, self:getRotation()) then return self.h else return self.w end end function BB_mt.__index:getPhysicalHeight() if 0 == band(1, self:getRotation()) then return self.phys_h else return self.phys_w end end -- names of optimized blitting routines BB_mt.__index.blitfunc = "blitDefault" -- not optimized BB4_mt.__index.blitfunc = "blitTo4" BB8_mt.__index.blitfunc = "blitTo8" BB8A_mt.__index.blitfunc = "blitTo8A" BBRGB16_mt.__index.blitfunc = "blitToRGB16" BBRGB24_mt.__index.blitfunc = "blitToRGB24" BBRGB32_mt.__index.blitfunc = "blitToRGB32" --[[ generic boundary check for copy operations @param length length of copy operation @param target_offset where to place part into target @param source_offset where to take part from in source @param target_size length of target buffer @param source_size length of source buffer @return adapted length that actually fits @return adapted target offset, guaranteed within range 0..(target_size-1) @return adapted source offset, guaranteed within range 0..(source_size-1) --]] function BB.checkBounds(length, target_offset, source_offset, target_size, source_size) -- deal with negative offsets if target_offset < 0 then length = length + target_offset source_offset = source_offset - target_offset target_offset = 0 end if source_offset < 0 then length = length + source_offset target_offset = target_offset - source_offset source_offset = 0 end -- calculate maximum lengths (size left starting at offset) local target_left = target_size - target_offset local source_left = source_size - source_offset -- return corresponding values if target_left <= 0 or source_left <= 0 then return 0, 0, 0 elseif length <= target_left and length <= source_left then -- length is the smallest value return floor(length), floor(target_offset), floor(source_offset) elseif target_left < length and target_left < source_left then -- target_left is the smalles value return floor(target_left), floor(target_offset), floor(source_offset) else -- source_left must be the smallest value return floor(source_left), floor(target_offset), floor(source_offset) end end function BB_mt.__index:blitDefault(dest, dest_x, dest_y, offs_x, offs_y, width, height, setter, set_param) -- slow default variant: local hook, mask, count = debug.gethook() debug.sethook() local o_y = offs_y for y = dest_y, dest_y+height-1 do local o_x = offs_x for x = dest_x, dest_x+width-1 do setter(dest, x, y, self:getPixel(o_x, o_y), set_param) o_x = o_x + 1 end o_y = o_y + 1 end debug.sethook(hook, mask) end -- no optimized blitting by default: BB_mt.__index.blitTo4 = BB_mt.__index.blitDefault BB_mt.__index.blitTo8 = BB_mt.__index.blitDefault BB_mt.__index.blitTo8A = BB_mt.__index.blitDefault BB_mt.__index.blitToRGB16 = BB_mt.__index.blitDefault BB_mt.__index.blitToRGB24 = BB_mt.__index.blitDefault BB_mt.__index.blitToRGB32 = BB_mt.__index.blitDefault -- Same to same fast blitting function BB8_mt.__index:blitTo8(dest, dest_x, dest_y, offs_x, offs_y, width, height, setter, set_param) -- We can only do fast copy for simple blitting with no processing (setPixel, no rota, no invert) if setter ~= self.setPixel or self:getRotation() ~= 0 or dest:getRotation() ~= 0 or (self:getInverse() ~= dest:getInverse()) then return self:blitDefault(dest, dest_x, dest_y, offs_x, offs_y, width, height, setter, set_param) end -- NOTE: We need to compare against the fb's *actual* scanline width, off-screen/padding regions included (i.e., xres_virtual instead of xres) if offs_x == 0 and dest_x == 0 and width == self.phys_w and width == dest.phys_w then -- Single step for contiguous scanlines (on both sides) --print("BB8 to BB8 full copy") -- BB8 is 1 byte per pixel local srcp = self.data + self.pitch*offs_y local dstp = dest.data + dest.pitch*dest_y ffi.copy(dstp, srcp, width*height) else -- Scanline per scanline copy --print("BB8 to BB8 scanline copy") local o_y = offs_y for y = dest_y, dest_y+height-1 do -- BB8 is 1 byte per pixel local srcp = self.data + self.pitch*o_y + offs_x local dstp = dest.data + dest.pitch*y + dest_x ffi.copy(dstp, srcp, width) o_y = o_y + 1 end end end function BBRGB32_mt.__index:blitToRGB32(dest, dest_x, dest_y, offs_x, offs_y, width, height, setter, set_param) -- We can only do fast copy for simple blitting with no processing (setPixel, no rota, no invert) if setter ~= self.setPixel or self:getRotation() ~= 0 or dest:getRotation() ~= 0 or (self:getInverse() ~= dest:getInverse()) then return self:blitDefault(dest, dest_x, dest_y, offs_x, offs_y, width, height, setter, set_param) end -- NOTE: We need to compare against the fb's *actual* scanline width, off-screen/padding regions included (i.e., xres_virtual instead of xres) if offs_x == 0 and dest_x == 0 and width == self.phys_w and width == dest.phys_w then -- Single step for contiguous scanlines (on both sides) --print("BBRGB32 to BBRGB32 full copy") -- BBRGB32 is 4 bytes per pixel local srcp = ffi.cast(uint8pt, self.data) + self.pitch*offs_y local dstp = ffi.cast(uint8pt, dest.data) + dest.pitch*dest_y ffi.copy(dstp, srcp, lshift(width, 2)*height) else -- Scanline per scanline copy --print("BBRGB32 to BBRGB32 scanline copy") local o_y = offs_y for y = dest_y, dest_y+height-1 do -- BBRGB32 is 4 bytes per pixel local srcp = ffi.cast(uint8pt, self.data) + self.pitch*o_y + lshift(offs_x, 2) local dstp = ffi.cast(uint8pt, dest.data) + dest.pitch*y + lshift(dest_x, 2) ffi.copy(dstp, srcp, lshift(width, 2)) o_y = o_y + 1 end end end function BB_mt.__index:blitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height, setter, set_param) width, height = width or source:getWidth(), height or source:getHeight() -- NOTE: If we convince CRe to render to a padded buffer (to match phys_w and allow us single-copy blitting), -- change the self:get* calls to self:getPhysical* ones ;). -- c.f., https://github.com/koreader/koreader-base/pull/878#issuecomment-476312508 width, dest_x, offs_x = BB.checkBounds(width, dest_x or 0, offs_x or 0, self:getWidth(), source:getWidth()) height, dest_y, offs_y = BB.checkBounds(height, dest_y or 0, offs_y or 0, self:getHeight(), source:getHeight()) if width <= 0 or height <= 0 then return end if not setter then setter = self.setPixel end if use_cblitbuffer and setter == self.setPixel then cblitbuffer.BB_blit_to(ffi.cast("struct BlitBuffer *", source), ffi.cast("struct BlitBuffer *", self), dest_x, dest_y, offs_x, offs_y, width, height) else source[self.blitfunc](source, self, dest_x, dest_y, offs_x, offs_y, width, height, setter, set_param) end end BB_mt.__index.blitFullFrom = BB_mt.__index.blitFrom -- blitting with a per-blit alpha value function BB_mt.__index:addblitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height, intensity) if use_cblitbuffer then width, height = width or source:getWidth(), height or source:getHeight() width, dest_x, offs_x = BB.checkBounds(width, dest_x or 0, offs_x or 0, self:getWidth(), source:getWidth()) height, dest_y, offs_y = BB.checkBounds(height, dest_y or 0, offs_y or 0, self:getHeight(), source:getHeight()) if width <= 0 or height <= 0 then return end cblitbuffer.BB_add_blit_from(ffi.cast("struct BlitBuffer *", self), ffi.cast("struct BlitBuffer *", source), dest_x, dest_y, offs_x, offs_y, width, height, intensity*0xFF) else self:blitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height, self.setPixelAdd, intensity*0xFF) end end -- alpha-pane aware blitting -- straight alpha function BB_mt.__index:alphablitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height) if use_cblitbuffer then width, height = width or source:getWidth(), height or source:getHeight() width, dest_x, offs_x = BB.checkBounds(width, dest_x or 0, offs_x or 0, self:getWidth(), source:getWidth()) height, dest_y, offs_y = BB.checkBounds(height, dest_y or 0, offs_y or 0, self:getHeight(), source:getHeight()) if width <= 0 or height <= 0 then return end cblitbuffer.BB_alpha_blit_from(ffi.cast("struct BlitBuffer *", self), ffi.cast("struct BlitBuffer *", source), dest_x, dest_y, offs_x, offs_y, width, height) else self:blitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height, self.setPixelBlend) end end -- premultiplied alpha function BB_mt.__index:pmulalphablitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height) if use_cblitbuffer then width, height = width or source:getWidth(), height or source:getHeight() width, dest_x, offs_x = BB.checkBounds(width, dest_x or 0, offs_x or 0, self:getWidth(), source:getWidth()) height, dest_y, offs_y = BB.checkBounds(height, dest_y or 0, offs_y or 0, self:getHeight(), source:getHeight()) if width <= 0 or height <= 0 then return end cblitbuffer.BB_pmulalpha_blit_from(ffi.cast("struct BlitBuffer *", self), ffi.cast("struct BlitBuffer *", source), dest_x, dest_y, offs_x, offs_y, width, height) else self:blitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height, self.setPixelPmulBlend) end end -- invert blitting function BB_mt.__index:invertblitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height) if use_cblitbuffer then width, height = width or source:getWidth(), height or source:getHeight() width, dest_x, offs_x = BB.checkBounds(width, dest_x or 0, offs_x or 0, self:getWidth(), source:getWidth()) height, dest_y, offs_y = BB.checkBounds(height, dest_y or 0, offs_y or 0, self:getHeight(), source:getHeight()) if width <= 0 or height <= 0 then return end cblitbuffer.BB_invert_blit_from(ffi.cast("struct BlitBuffer *", self), ffi.cast("struct BlitBuffer *", source), dest_x, dest_y, offs_x, offs_y, width, height) else self:blitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height, self.setPixelInverted) end end -- colorize area using source blitbuffer as a alpha-map function BB_mt.__index:colorblitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height, color) -- we need color with alpha later: color = color:getColor8A() if use_cblitbuffer then width, height = width or source:getWidth(), height or source:getHeight() width, dest_x, offs_x = BB.checkBounds(width, dest_x or 0, offs_x or 0, self:getWidth(), source:getWidth()) height, dest_y, offs_y = BB.checkBounds(height, dest_y or 0, offs_y or 0, self:getHeight(), source:getHeight()) if width <= 0 or height <= 0 then return end cblitbuffer.BB_color_blit_from(ffi.cast("struct BlitBuffer *", self), ffi.cast("struct BlitBuffer *", source), dest_x, dest_y, offs_x, offs_y, width, height, color) else if self:getInverse() == 1 then color = color:invert() end self:blitFrom(source, dest_x, dest_y, offs_x, offs_y, width, height, self.setPixelColorize, color) end end -- scale method does not modify the original blitbuffer, instead, it allocates -- and returns a new scaled blitbuffer. function BB_mt.__index:scale(new_width, new_height) local self_w, self_h = self:getWidth(), self:getHeight() local scaled_bb = BB.new(new_width, new_height, self:getType()) -- uses very simple nearest neighbour scaling for y=0, new_height-1 do for x=0, new_width-1 do scaled_bb:setPixel(x, y, self:getPixel(util.idiv(x*self_w, new_width), util.idiv(y*self_h, new_height))) end end return scaled_bb end -- rotatedCopy method, unlike rotate method, does not modify the original -- blitbuffer, instead, it allocates and returns a new rotated blitbuffer. function BB_mt.__index:rotatedCopy(degree) self:rotate(degree) -- rotate in-place local rot_w, rot_h = self:getWidth(), self:getHeight() local rot_bb = BB.new(rot_w, rot_h, self:getType()) rot_bb:blitFrom(self, 0, 0, 0, 0, rot_w, rot_h) self:rotate(-degree) -- revert in-place rotation return rot_bb end --[[ explicit unset will free resources immediately this is also called upon garbage collection --]] function BB_mt.__index:free() if band(lshift(1, SHIFT_ALLOCATED), self.config) ~= 0 then self.config = band(self.config, bxor(0xFF, lshift(1, SHIFT_ALLOCATED))) C.free(self.data) end end --[[ memory management --]] BB_mt.__gc = BB_mt.__index.free --[[ PAINTING --]] --[[ fill the whole blitbuffer with a given (grayscale) color value --]] function BB_mt.__index:fill(value) -- NOTE: We need to account for the *actual* length of a scanline, padding included (hence phys_w instead of w). ffi.fill(self.data, self.phys_w*self:getBytesPerPixel()*self.h, value:getColor8().a) end function BB4_mt.__index:fill(value) local v = value:getColor4L().a v = bor(lshift(v, 4), v) ffi.fill(self.data, self.pitch*self.h, v) end --[[ invert a rectangle within the buffer @param x X coordinate @param y Y coordinate @param w width @param h height --]] function BB_mt.__index:invertRect(x, y, w, h) self:invertblitFrom(self, x, y, x, y, w, h) end function BB_mt.__index:invertRect(x, y, w, h) w, x = BB.checkBounds(w, x, 0, self:getWidth(), 0xFFFF) h, y = BB.checkBounds(h, y, 0, self:getHeight(), 0xFFFF) if w <= 0 or h <= 0 then return end if use_cblitbuffer then cblitbuffer.BB_invert_rect(ffi.cast("struct BlitBuffer *", self), x, y, w, h) else local hook, mask, count = debug.gethook() debug.sethook() -- Handle rotation... x, y, w, h = self:getPhysicalRect(x, y, w, h) -- Handle any target pitch properly (i.e., fetch the amount of bytes taken per pixel)... local bpp = self:getBytesPerPixel() -- If we know the native data type of a pixel, we can use that instead of doing it byte-per-byte... local bbtype = self:getType() -- We check against the BB's unrotated coordinates (i.e., self.w and not self:getWidth()), -- as our memory region has a fixed layout, too! if x == 0 and w == self.w then -- Single step for contiguous scanlines --print("Full invertRect") if bbtype == TYPE_BBRGB32 then local p = ffi.cast(uint32pt, ffi.cast(uint8pt, self.data) + self.pitch*y) -- Account for potentially off-screen scanline bits by using self.phys_w instead of w, -- as we've just assured ourselves that the requested w matches self.w ;). for i = 1, self.phys_w*h do p[0] = bxor(p[0], 0x00FFFFFF) -- Pointer arithmetics magic: +1 on an uint32_t* means +4 bytes (i.e., next pixel) ;). p = p+1 end elseif bbtype == TYPE_BBRGB16 then local p = ffi.cast(uint16pt, ffi.cast(uint8pt, self.data) + self.pitch*y) for i = 1, self.phys_w*h do p[0] = bxor(p[0], 0xFFFF) p = p+1 end else -- Should only be BB8 left, but honor bpp for safety instead of relying purely on pointer arithmetics... local p = ffi.cast(uint8pt, self.data) + self.pitch*y for i = 1, bpp*self.phys_w*h do p[0] = bxor(p[0], 0xFF) p = p+1 end end else -- Pixel per pixel --print("Pixel invertRect") if bbtype == TYPE_BBRGB32 then for j = y, y+h-1 do local p = ffi.cast(uint32pt, ffi.cast(uint8pt, self.data) + self.pitch*j) + x for i = 0, w-1 do p[0] = bxor(p[0], 0x00FFFFFF) p = p+1 end end elseif bbtype == TYPE_BBRGB16 then for j = y, y+h-1 do local p = ffi.cast(uint16pt, ffi.cast(uint8pt, self.data) + self.pitch*j) + x for i = 0, w-1 do p[0] = bxor(p[0], 0xFFFF) p = p+1 end end else -- Again, honor bpp for safety instead of relying purely on pointer arithmetics... for j = y, y+h-1 do local p = ffi.cast(uint8pt, self.data) + self.pitch*j + bpp*x for i = 0, bpp*(w-1) do p[0] = bxor(p[0], 0xFF) p = p+1 end end end end debug.sethook(hook, mask) end end -- No fast paths for BB4 & BB8A function BB4_mt.__index:invertRect(x, y, w, h) self:invertblitFrom(self, x, y, x, y, w, h) end function BB8A_mt.__index:invertRect(x, y, w, h) self:invertblitFrom(self, x, y, x, y, w, h) end --[[ paint a rectangle onto this buffer @param x X coordinate @param y Y coordinate @param w width @param h height @param value color value @param setter function used to set pixels (defaults to normal setPixel) --]] function BB_mt.__index:paintRect(x, y, w, h, value, setter) setter = setter or self.setPixel value = value or Color8(0) w, x = BB.checkBounds(w, x, 0, self:getWidth(), 0xFFFF) h, y = BB.checkBounds(h, y, 0, self:getHeight(), 0xFFFF) if w <= 0 or h <= 0 then return end if use_cblitbuffer and setter == self.setPixel then cblitbuffer.BB_fill_rect(ffi.cast("struct BlitBuffer *", self), x, y, w, h, value:getColor8().a) else local hook, mask, count = debug.gethook() debug.sethook() -- We can only do fast filling when there's no complex processing involved (i.e., simple setPixel only) -- NOTE: We cheat a bit when targeting non-grayscale BBs, -- because we know we're only used with a grayscale color as input ;). -- The cbb also takes advantage of the same shortcut. if setter == self.setPixel then -- Handle rotation... x, y, w, h = self:getPhysicalRect(x, y, w, h) -- Handle invert... local v = value:getColor8() if self:getInverse() == 1 then v = v:invert() end -- Handle any target pitch properly (i.e., fetch the amount of bytes taken per pixel)... local bpp = self:getBytesPerPixel() -- We check against the BB's unrotated coordinates (i.e., self.w and not self:getWidth()), -- as our memory region has a fixed layout, too! if x == 0 and w == self.w then -- Single step for contiguous scanlines --print("Single fill paintRect") local p = ffi.cast(uint8pt, self.data) + self.pitch*y -- Account for potentially off-screen scanline bits by using self.phys_w instead of w, -- as we've just assured ourselves that the requested w matches self.w ;). ffi.fill(p, bpp*self.phys_w*h, v.a) else -- Scanline per scanline fill --print("Scanline fill paintRect") for j = y, y+h-1 do local p = ffi.cast(uint8pt, self.data) + self.pitch*j + bpp*x ffi.fill(p, bpp*w, v.a) end end else --print("Old-style paintRect pixel loop") for tmp_y = y, y+h-1 do for tmp_x = x, x+w-1 do setter(self, tmp_x, tmp_y, value) end end end debug.sethook(hook, mask) end end -- BB4 version, identical if not for the lack of fast filling, because nibbles aren't addressable... -- Also, no cbb branch, as cbb doesn't handle 4bpp targets at all. function BB4_mt.__index:paintRect(x, y, w, h, value, setter) setter = setter or self.setPixel value = value or Color8(0) w, x = BB.checkBounds(w, x, 0, self:getWidth(), 0xFFFF) h, y = BB.checkBounds(h, y, 0, self:getHeight(), 0xFFFF) if w <= 0 or h <= 0 then return end local hook, mask, count = debug.gethook() debug.sethook() for tmp_y = y, y+h-1 do for tmp_x = x, x+w-1 do setter(self, tmp_x, tmp_y, value) end end debug.sethook(hook, mask) end --[[ paint a circle onto this buffer @param x1 X coordinate of the circle's center @param y1 Y coordinate of the circle's center @param r radius @param c color value (defaults to black) @param w width of line (defaults to radius) --]] function BB_mt.__index:paintCircle(center_x, center_y, r, c, w) c = c or Color8(0) if r == 0 then return end if w == nil then w = r end if w > r then w = r end -- for outer circle local x = 0 local y = r local delta = 5/4 - r -- for inner circle local r2 = r - w local x2 = 0 local y2 = r2 local delta2 = 5/4 - r -- draw two axles for tmp_y = r, r2+1, -1 do self:setPixelClamped(center_x+0, center_y+tmp_y, c) self:setPixelClamped(center_x-0, center_y-tmp_y, c) self:setPixelClamped(center_x+tmp_y, center_y+0, c) self:setPixelClamped(center_x-tmp_y, center_y-0, c) end while x < y do -- decrease y if we are out of circle x = x + 1; if delta > 0 then y = y - 1 delta = delta + 2*x - 2*y + 2 else delta = delta + 2*x + 1 end -- inner circle finished drawing, increase y linearly for filling if x2 > y2 then y2 = y2 + 1 x2 = x2 + 1 else x2 = x2 + 1 if delta2 > 0 then y2 = y2 - 1 delta2 = delta2 + 2*x2 - 2*y2 + 2 else delta2 = delta2 + 2*x2 + 1 end end for tmp_y = y, y2+1, -1 do self:setPixelClamped(center_x+x, center_y+tmp_y, c) self:setPixelClamped(center_x+tmp_y, center_y+x, c) self:setPixelClamped(center_x+tmp_y, center_y-x, c) self:setPixelClamped(center_x+x, center_y-tmp_y, c) self:setPixelClamped(center_x-x, center_y-tmp_y, c) self:setPixelClamped(center_x-tmp_y, center_y-x, c) self:setPixelClamped(center_x-tmp_y, center_y+x, c) self:setPixelClamped(center_x-x, center_y+tmp_y, c) end end if r == w then self:setPixelClamped(center_x, center_y, c) end end function BB_mt.__index:paintRoundedCorner(off_x, off_y, w, h, bw, r, c) if 2*r > h or 2*r > w or r == 0 then -- no operation return end r = min(r, h, w) if bw > r then bw = r end -- for outer circle local x = 0 local y = r local delta = 5/4 - r -- for inner circle local r2 = r - bw local x2 = 0 local y2 = r2 local delta2 = 5/4 - r while x < y do -- decrease y if we are out of circle x = x + 1 if delta > 0 then y = y - 1 delta = delta + 2*x - 2*y + 2 else delta = delta + 2*x + 1 end -- inner circle finished drawing, increase y linearly for filling if x2 > y2 then y2 = y2 + 1 x2 = x2 + 1 else x2 = x2 + 1 if delta2 > 0 then y2 = y2 - 1 delta2 = delta2 + 2*x2 - 2*y2 + 2 else delta2 = delta2 + 2*x2 + 1 end end for tmp_y = y, y2+1, -1 do self:setPixelClamped((w-r)+off_x+x-1, (h-r)+off_y+tmp_y-1, c) self:setPixelClamped((w-r)+off_x+tmp_y-1, (h-r)+off_y+x-1, c) self:setPixelClamped((w-r)+off_x+tmp_y-1, (r)+off_y-x, c) self:setPixelClamped((w-r)+off_x+x-1, (r)+off_y-tmp_y, c) self:setPixelClamped((r)+off_x-x, (r)+off_y-tmp_y, c) self:setPixelClamped((r)+off_x-tmp_y, (r)+off_y-x, c) self:setPixelClamped((r)+off_x-tmp_y, (h-r)+off_y+x-1, c) self:setPixelClamped((r)+off_x-x, (h-r)+off_y+tmp_y-1, c) end end end --[[ Draw a border @x: start position in x axis @y: start position in y axis @w: width of the border @h: height of the border @bw: line width of the border @c: color for loading bar @r: radius of for border's corner (nil or 0 means right corner border) --]] function BB_mt.__index:paintBorder(x, y, w, h, bw, c, r) x, y = ceil(x), ceil(y) h, w = ceil(h), ceil(w) if not r or r == 0 then self:paintRect(x, y, w, bw, c) self:paintRect(x, y+h-bw, w, bw, c) self:paintRect(x, y+bw, bw, h - 2*bw, c) self:paintRect(x+w-bw, y+bw, bw, h - 2*bw, c) else if h < 2*r then r = floor(h/2) end if w < 2*r then r = floor(w/2) end self:paintRoundedCorner(x, y, w, h, bw, r, c) self:paintRect(r+x, y, w-2*r, bw, c) self:paintRect(r+x, y+h-bw, w-2*r, bw, c) self:paintRect(x, r+y, bw, h-2*r, c) self:paintRect(x+w-bw, r+y, bw, h-2*r, c) end end --[[ Draw an inner border @x: start position in x axis @y: start position in y axis @w: width of the border @h: height of the border @bw: line width of the border @c: color for loading bar @r: radius of for border's corner (nil or 0 means right corner border) [FIXME? UNSUPPORTED] --]] function BB_mt.__index:paintInnerBorder(x, y, w, h, bw, c, r) x, y = ceil(x), ceil(y) h, w = ceil(h), ceil(w) -- T -> B -> L -> R self:paintRect(x, y, w, bw, c) self:paintRect(x, y+h-bw, w, bw, c) self:paintRect(x, y, bw, h, c) self:paintRect(x+w-bw, y, bw, h, c) end --[[ Fill a rounded corner rectangular area @x: start position in x axis @y: start position in y axis @w: width of the area @h: height of the area @c: color used to fill the area @r: radius of for four corners --]] function BB_mt.__index:paintRoundedRect(x, y, w, h, c, r) x, y = ceil(x), ceil(y) h, w = ceil(h), ceil(w) if not r or r == 0 then self:paintRect(x, y, w, h, c) else if h < 2*r then r = floor(h/2) end if w < 2*r then r = floor(w/2) end self:paintBorder(x, y, w, h, r, c, r) self:paintRect(x+r, y+r, w-2*r, h-2*r, c) end end --[[ Draw a progress bar according to following args: @x: start position in x axis @y: start position in y axis @w: width for progress bar @h: height for progress bar @load_m_w: width margin for loading bar @load_m_h: height margin for loading bar @load_percent: progress in percent @c: color for loading bar --]] function BB_mt.__index:progressBar(x, y, w, h, load_m_w, load_m_h, load_percent, c) if load_m_h*2 > h then load_m_h = h/2 end self:paintBorder(x, y, w, h, 2, 15) self:paintRect(x+load_m_w, y+load_m_h, (w-2*load_m_w)*load_percent, (h-2*load_m_h), c) end --[[ dim color values in rectangular area @param x X coordinate @param y Y coordinate @param w width @param h height @param by dim by this factor (default: 0.5) --]] function BB_mt.__index:dimRect(x, y, w, h, by) local color = Color8A(0xFF, 0xFF*(by or 0.5)) if use_cblitbuffer then w, x = BB.checkBounds(w, x, 0, self:getWidth(), 0xFFFF) h, y = BB.checkBounds(h, y, 0, self:getHeight(), 0xFFFF) if w <= 0 or h <= 0 then return end cblitbuffer.BB_blend_rect(ffi.cast("struct BlitBuffer *", self), x, y, w, h, color) else self:paintRect(x, y, w, h, color, self.setPixelBlend) end end --[[ lighten color values in rectangular area @param x X coordinate @param y Y coordinate @param w width @param h height @param by lighten by this factor (default: 0.5) --]] function BB_mt.__index:lightenRect(x, y, w, h, by) local color = Color8A(0, 0xFF*(by or 0.5)) if use_cblitbuffer then w, x = BB.checkBounds(w, x, 0, self:getWidth(), 0xFFFF) h, y = BB.checkBounds(h, y, 0, self:getHeight(), 0xFFFF) if w <= 0 or h <= 0 then return end cblitbuffer.BB_blend_rect(ffi.cast("struct BlitBuffer *", self), x, y, w, h, color) else self:paintRect(x, y, w, h, color, self.setPixelBlend) end end --[[ make a full copy of the current buffer, with its own memory --]] function BB_mt.__index:copy() local mytype = ffi.typeof(self) local buffer = C.malloc(self.pitch * self.h) assert(buffer, "cannot allocate buffer") ffi.copy(buffer, self.data, self.pitch * self.h) local copy = mytype(self.w, self.phys_w, self.h, self.phys_h, self.pitch, buffer, self.config) copy:setAllocated(1) return copy end --[[ return a new Blitbuffer object that works on a rectangular subset of the current Blitbuffer Note that the caller has to make sure that the underlying memory (of the Blitbuffer this method is called on) stays in place. In other words, a viewport does not create a new buffer with memory. --]] function BB_mt.__index:viewport(x, y, w, h) x, y, w, h = self:getPhysicalRect(x, y, w, h) local viewport = BB.new(w, h, self:getType(), self:getPixelP(x, y), self.pitch, self:getPhysicalWidth(), self:getPhysicalHeight()) viewport:setRotation(self:getRotation()) viewport:setInverse(self:getInverse()) return viewport end --[[ write blitbuffer contents to a PNG file @param filename the name of the file to be created --]] local Png -- lazy load ffi/png function BB_mt.__index:writePNG(filename, bgr) if not Png then Png = require("ffi/png") end local hook, mask, _ = debug.gethook() debug.sethook() local w, h = self:getWidth(), self:getHeight() local cdata = C.malloc(w * h * 4) local mem = ffi.cast("char*", cdata) for y = 0, h-1 do local offset = 4 * w * y for x = 0, w-1 do local c = self:getPixel(x, y):getColorRGB32() -- NOTE: Kobo's FB is BGR(A), we already trick MuPDF into doing it that way for us, so, keep faking it here! if bgr then mem[offset] = c.b mem[offset + 1] = c.g mem[offset + 2] = c.r else mem[offset] = c.r mem[offset + 1] = c.g mem[offset + 2] = c.b end mem[offset + 3] = 0xFF offset = offset + 4 end end Png.encodeToFile(filename, mem, w, h) C.free(cdata) debug.sethook(hook, mask) end -- if no special case in BB???_mt exists, use function from BB_mt -- (we do not use BB_mt as metatable for BB???_mt since this causes -- a major slowdown and would not get properly JIT-compiled) for name, func in pairs(BB_mt.__index) do if not BB4_mt.__index[name] then BB4_mt.__index[name] = func end if not BB8_mt.__index[name] then BB8_mt.__index[name] = func end if not BB8A_mt.__index[name] then BB8A_mt.__index[name] = func end if not BBRGB16_mt.__index[name] then BBRGB16_mt.__index[name] = func end if not BBRGB24_mt.__index[name] then BBRGB24_mt.__index[name] = func end if not BBRGB32_mt.__index[name] then BBRGB32_mt.__index[name] = func end end -- set metatables for the BlitBuffer types local BlitBuffer4 = ffi.metatype("BlitBuffer4", BB4_mt) local BlitBuffer8 = ffi.metatype("BlitBuffer8", BB8_mt) local BlitBuffer8A = ffi.metatype("BlitBuffer8A", BB8A_mt) local BlitBufferRGB16 = ffi.metatype("BlitBufferRGB16", BBRGB16_mt) local BlitBufferRGB24 = ffi.metatype("BlitBufferRGB24", BBRGB24_mt) local BlitBufferRGB32 = ffi.metatype("BlitBufferRGB32", BBRGB32_mt) -- set metatables for the Color types ffi.metatype("Color4L", Color4L_mt) ffi.metatype("Color4U", Color4U_mt) ffi.metatype("Color8", Color8_mt) ffi.metatype("Color8A", Color8A_mt) ffi.metatype("ColorRGB16", ColorRGB16_mt) ffi.metatype("ColorRGB24", ColorRGB24_mt) ffi.metatype("ColorRGB32", ColorRGB32_mt) function BB.new(width, height, buffertype, dataptr, pitch, phys_width, phys_height) local bb = nil buffertype = buffertype or TYPE_BB8 -- Remember the fb's _virtual dimensions if we specified them, as we'll need 'em for fast blitting codepaths phys_width = phys_width or width phys_height = phys_height or height if pitch == nil then if buffertype == TYPE_BB4 then pitch = band(1, width) + rshift(width, 1) elseif buffertype == TYPE_BB8 then pitch = width elseif buffertype == TYPE_BB8A then pitch = lshift(width, 1) elseif buffertype == TYPE_BBRGB16 then pitch = lshift(width, 1) elseif buffertype == TYPE_BBRGB24 then pitch = width * 3 elseif buffertype == TYPE_BBRGB32 then pitch = lshift(width, 2) end end if buffertype == TYPE_BB4 then bb = BlitBuffer4(width, phys_width, height, phys_height, pitch, nil, 0) elseif buffertype == TYPE_BB8 then bb = BlitBuffer8(width, phys_width, height, phys_height, pitch, nil, 0) elseif buffertype == TYPE_BB8A then bb = BlitBuffer8A(width, phys_width, height, phys_height, pitch, nil, 0) elseif buffertype == TYPE_BBRGB16 then bb = BlitBufferRGB16(width, phys_width, height, phys_height, pitch, nil, 0) elseif buffertype == TYPE_BBRGB24 then bb = BlitBufferRGB24(width, phys_width, height, phys_height, pitch, nil, 0) elseif buffertype == TYPE_BBRGB32 then bb = BlitBufferRGB32(width, phys_width, height, phys_height, pitch, nil, 0) else error("unknown blitbuffer type") end bb:setType(buffertype) if dataptr == nil then dataptr = C.malloc(pitch*height) assert(dataptr, "cannot allocate memory for blitbuffer") ffi.fill(dataptr, pitch*height) bb:setAllocated(1) end bb.data = ffi.cast(bb.data, dataptr) return bb end function BB.compat(oldbuffer) return ffi.cast("BlitBuffer4*", oldbuffer)[0] end function BB.fromstring(width, height, buffertype, str, pitch) local dataptr = C.malloc(#str) ffi.copy(dataptr, str, #str) local bb = BB.new(width, height, buffertype, dataptr, pitch) bb:setAllocated(1) return bb end function BB.tostring(bb) return ffi.string(bb.data, bb.pitch * bb.h) end --[[ return a Color value resembling a given level of blackness/gray 0 is white, 1.0 is black --]] function BB.gray(level) return Color8(bxor(floor(0xFF * level), 0xFF)) end -- some generic color values: BB.COLOR_WHITE = Color8(0xFF) BB.COLOR_GRAY_E = Color8(0xEE) BB.COLOR_LIGHT_GRAY = Color8(0xCC) BB.COLOR_GRAY = Color8(0xAA) BB.COLOR_WEB_GRAY = Color8(0x99) BB.COLOR_DARK_GRAY = Color8(0x88) BB.COLOR_DIM_GRAY = Color8(0x55) BB.COLOR_BLACK = Color8(0) -- accessors for color types: BB.Color4 = Color4L BB.Color4L = Color4L BB.Color4U = Color4U BB.Color8 = Color8 BB.Color8A = Color8A BB.ColorRGB16 = ColorRGB16 BB.ColorRGB24 = ColorRGB24 BB.ColorRGB32 = ColorRGB32 -- accessors for Blitbuffer types BB.BlitBuffer4 = BlitBuffer4 BB.BlitBuffer8 = BlitBuffer8 BB.BlitBuffer8A = BlitBuffer8A BB.BlitBufferRGB16 = BlitBufferRGB16 BB.BlitBufferRGB24 = BlitBufferRGB24 BB.BlitBufferRGB32 = BlitBufferRGB32 BB.TYPE_BB4 = TYPE_BB4 BB.TYPE_BB8 = TYPE_BB8 BB.TYPE_BB8A = TYPE_BB8A BB.TYPE_BBRGB16 = TYPE_BBRGB16 BB.TYPE_BBRGB24 = TYPE_BBRGB24 BB.TYPE_BBRGB32 = TYPE_BBRGB32 return BB
agpl-3.0
tgp1994/LiquidRP-tgp1994
gamemode/modules/chat/sv_chatcommands.lua
1
2055
/*--------------------------------------------------------- Talking ---------------------------------------------------------*/ local function GroupMsg(ply, args) if args == "" then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("invalid_x", "argument", "")) return "" end local DoSay = function(text) if text == "" then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("invalid_x", "argument", "")) return end local t = ply:Team() local col = team.GetColor(ply:Team()) local hasReceived = {} for _, func in pairs(GAMEMODE.DarkRPGroupChats) do -- not the group of the player if not func(ply) then continue end for _, target in pairs(player.GetAll()) do if func(target) and not hasReceived[target] then hasReceived[target] = true DarkRP.talkToPerson(target, col, DarkRP.getPhrase("group") .. " " .. ply:Nick(), Color(255,255,255,255), text, ply) end end end if next(hasReceived) == nil then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("unable", "/g", "")) end end return args, DoSay end DarkRP.defineChatCommand("g", GroupMsg, 1.5) -- here's the new easter egg. Easier to find, more subtle, doesn't only credit FPtje and unib5 -- WARNING: DO NOT EDIT THIS -- You can edit DarkRP but you HAVE to credit the original authors! -- You even have to credit all the previous authors when you rename the gamemode. local CreditsWait = true local function GetDarkRPAuthors(ply, args) local target = DarkRP.findPlayer(args); -- Only send to one player. Prevents spamming if not IsValid(target) then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("player_doesnt_exist")) return "" end if not CreditsWait then DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("wait_with_that")) return "" end CreditsWait = false timer.Simple(60, function() CreditsWait = true end)--so people don't spam it local rf = RecipientFilter() rf:AddPlayer(target) if ply ~= target then rf:AddPlayer(ply) end umsg.Start("DarkRP_Credits", rf) umsg.End() return "" end DarkRP.defineChatCommand("credits", GetDarkRPAuthors, 50)
gpl-3.0
yinjun322/ejoy2d
examples/ex01.lua
19
1027
local ej = require "ejoy2d" local fw = require "ejoy2d.framework" local pack = require "ejoy2d.simplepackage" pack.load { pattern = fw.WorkDir..[[examples/asset/?]], "sample", } local obj = ej.sprite("sample","cannon") local turret = obj.turret -- set position (-100,0) scale (0.5) obj:ps(-100,0,0.5) local obj2 = ej.sprite("sample","mine") obj2.resource.frame = 70 -- set position(100,0) scale(1.2) separately obj2:ps(100,0) obj2:ps(1.2) local game = {} local screencoord = { x = 512, y = 384, scale = 1.2 } local x1,y1,x2,y2 = obj2:aabb(screencoord) obj2.label.text = string.format("AABB\n%d x %d", x2-x1, y2-y1) function game.update() turret.frame = turret.frame + 3 obj2.frame = obj2.frame + 1 end function game.drawframe() ej.clear(0xff808080) -- clear (0.5,0.5,0.5,1) gray obj:draw(screencoord) obj2:draw(screencoord) end function game.touch(what, x, y) end function game.message(...) end function game.handle_error(...) end function game.on_resume() end function game.on_pause() end ej.start(game)
mit
dmccuskey/lua-megaphone
spec/lua_megaphone_spec.lua
1
4330
--====================================================================-- -- spec/lua_megaphone_spec.lua -- -- Testing for lua-megaphone using Busted --====================================================================-- package.path = './dmc_lua/?.lua;' .. package.path --====================================================================-- --== Test: Lua Objects --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== Imports local Megaphone = require 'lua_megaphone' --====================================================================-- --== Testing Setup --====================================================================-- describe( "Module Test: lua_megaphone.lua", function() describe( "megaphone has properties", function() it( "has property NAME", function() assert.is.equal( Megaphone.NAME, "Lua Megaphone" ) end) it( "has property EVENT", function() assert.is.equal( Megaphone.EVENT, 'megaphone_event' ) end) it( "has property EVENT", function() assert.is.equal( Megaphone.EVENT, 'megaphone_event' ) end) end) describe( "megaphone has methods", function() it( "has method listen", function() assert.is.equal( type(Megaphone.listen), 'function' ) end) it( "has method say", function() assert.is.equal( type(Megaphone.say), 'function' ) end) it( "has method ignore", function() assert.is.equal( type(Megaphone.ignore), 'function' ) end) it( "has method setDebug", function() assert.is.equal( type(Megaphone.setDebug), 'function' ) end) end) describe( "megaphone has errors", function() it( "throws errors with improper params", function() assert.is.error( function() Megaphone:listen() end ) assert.is.error( function() Megaphone:listen( 'event' ) end ) end) it( "throws errors with improper params", function() assert.is.error( function() Megaphone:say( {} ) end ) assert.is.error( function() Megaphone:say() end ) end) it( "throws errors with improper params", function() assert.is.error( function() Megaphone:ignore() end ) assert.is.error( function() Megaphone:ignore( 'event' ) end ) end) end) describe( "megaphone communicates", function() it( "can dispatch events", function() assert.is_not.error( function() Megaphone:say( "hello" ) end ) end) it( "can setup listener and get events", function() local event, data local etype = 'bogus_event' local callback = function( e ) event = e end -- test no data assert.is_not.error( function() Megaphone:listen( callback ) end ) assert.is_not.error( function() Megaphone:say( etype ) end ) assert.is.equal( event.name, 'megaphone_event' ) assert.is.equal( event.type, etype ) assert.is.equal( event.data, nil ) event = nil -- test string data assert.is_not.error( function() Megaphone:say( etype, "hello" ) end ) assert.is.equal( event.name, 'megaphone_event' ) assert.is.equal( event.type, etype ) assert.is.equal( event.data, "hello" ) event = nil data = {one=1} assert.is_not.error( function() Megaphone:say( etype, data ) end ) assert.is.equal( event.name, 'megaphone_event' ) assert.is.equal( event.type, etype ) assert.is.equal( event.data, data ) event = nil data = {one=1,two=2} assert.is_not.error( function() Megaphone:say( etype, data, {merge=true} ) end ) assert.is.equal( event.name, 'megaphone_event' ) assert.is.equal( event.type, etype ) assert.is.equal( event.one, data.one ) assert.is.equal( event.two, data.two ) event = nil assert.is_not.error( function() Megaphone:ignore( callback ) end ) assert.is_not.error( function() Megaphone:say( etype ) end ) assert.is.equal( event, nil ) end) it( "throws errors with improper params", function() local etype = 'bogus_event' local data = "hello" assert.is.error( function() Megaphone:say( etype, data, "params" ) end ) assert.is.error( function() Megaphone:say( etype, data, 2 ) end ) assert.is.error( function() Megaphone:say( etype, nil, "params" ) end ) assert.is.error( function() Megaphone:say( etype, nil, 2 ) end ) end) end) end)
mit
CarabusX/Zero-K
LuaUI/Widgets/api_preselection.lua
6
6971
function widget:GetInfo() return { name = "Pre-Selection Handler", desc = "Utility Functions for handling units in selection box and under selection cursor", author = "Shadowfury333", date = "Jan 6th, 2016", license = "GPLv2", version = "1", layer = 1000, enabled = true, -- loaded by default? api = true, alwaysStart = true, } end ---------------------------------------------------------------------------- -------------------------Interface--------------------------------------- WG.PreSelection_GetUnitUnderCursor = function (onlySelectable) --return nil | unitID end WG.PreSelection_IsSelectionBoxActive = function () --return boolean end WG.PreSelection_GetUnitsInSelectionBox = function () --return nil | {[1] = unitID, etc.} end WG.PreSelection_IsUnitInSelectionBox = function (unitID) --return boolean end ---------------------------------------------------------------------------- ----------------------Implementation------------------------------------- include("Widgets/COFCtools/TraceScreenRay.lua") local math_acos = math.acos local math_atan2 = math.atan2 local math_pi = math.pi local math_min = math.min local math_max = math.max local spIsUnitSelected = Spring.IsUnitSelected local spTraceScreenRay = Spring.TraceScreenRay local spGetMouseState = Spring.GetMouseState local spIsAboveMiniMap = Spring.IsAboveMiniMap local spWorldToScreenCoords = Spring.WorldToScreenCoords local start local screenStartX, screenStartY = 0, 0 local cannotSelect = false local holdingForSelection = false local thruMinimap = false local boxedUnitIDs local function SafeTraceScreenRay(x, y, onlyCoords, useMinimap, includeSky, ignoreWater) local type, pt = Spring.TraceScreenRay(x, y, onlyCoords, useMinimap, includeSky, ignoreWater) if not pt then local cs = Spring.GetCameraState() local camPos = {px=cs.px,py=cs.py,pz=cs.pz} local camRot = {} if cs.rx then camRot = {rx=cs.rx,ry=cs.ry,rz=cs.rz} else local ry = (math_pi - math_atan2(cs.dx, -cs.dz)) --goes from 0 to 2PI instead of -PI to PI, but the trace maths work either way camRot = {rx=math_pi/2 - math_acos(cs.dy),ry=ry,rz=0} end local vsx, vsy = Spring.GetViewGeometry() local gx, gy, gz = TraceCursorToGround(vsx, vsy, {x=x, y=y}, cs.fov, camPos, camRot, -4900) pt = {gx, gy, gz} type = "ground" end return type, pt end WG.PreSelection_GetUnitUnderCursor = function (onlySelectable, ignoreSelectionBox) local x, y, lmb, mmb, rmb, outsideSpring = spGetMouseState() if mmb or rmb or outsideSpring then cannotSelect = true elseif cannotSelect and not lmb then cannotSelect = false end if outsideSpring then return end local aboveMiniMap = spIsAboveMiniMap(x, y) local onAndUsingMinimap = (not WG.MinimapDraggingCamera and aboveMiniMap) or not aboveMiniMap if (ignoreSelectionBox or not WG.PreSelection_IsSelectionBoxActive()) and onAndUsingMinimap and (not onlySelectable or (onlySelectable and not cannotSelect)) then --holding time when starting box selection, that way it avoids flickering if the hovered unit is selected quickly in the box selection local pointedType, data = spTraceScreenRay(x, y, false, true) if pointedType == 'unit' and Spring.ValidUnitID(data) and not WG.drawtoolKeyPressed then -- and not spIsUnitIcon(data) then return data else return nil end end end WG.PreSelection_IsSelectionBoxActive = function () local x, y, lmb = spGetMouseState() local _, here = SafeTraceScreenRay(x, y, true, thruMinimap) if lmb and not cannotSelect and holdingForSelection and not (here[1] == start[1] and here[2] == start[2] and here[3] == start[3]) then return true end return false end WG.PreSelection_GetUnitsInSelectionBox = function () local x, y, lmb = spGetMouseState() if lmb and not cannotSelect and holdingForSelection then local spec, fullview, fullselect = Spring.GetSpectatingState() local myTeamID = Spring.GetMyTeamID() if thruMinimap then local posX, posY, sizeX, sizeY = Spring.GetMiniMapGeometry() x = math_max(x, posX) x = math_min(x, posX+sizeX) y = math_max(y, posY) y = math_min(y, posY+sizeY) local _, here = SafeTraceScreenRay(x, y, true, thruMinimap) local left = math_min(start[1], here[1]) local bottom = math_min(start[3], here[3]) local right = math_max(start[1], here[1]) local top = math_max(start[3], here[3]) local units = Spring.GetUnitsInRectangle(left, bottom, right, top) if spec and fullselect then return (WG.SelectionRank_GetFilteredSelection and WG.SelectionRank_GetFilteredSelection(units)) or units --nil if empty else local myUnits = {} local teamID = 0 for i = 1, #units do teamID = Spring.GetUnitTeam(units[i]) if teamID == myTeamID and not Spring.GetUnitNoSelect(units[i]) then myUnits[#myUnits+1] = units[i] end end if #myUnits > 0 then return (WG.SelectionRank_GetFilteredSelection and WG.SelectionRank_GetFilteredSelection(myUnits)) or myUnits else return nil end end else local allBoxedUnits = {} local units = {} if spec and fullselect then units = Spring.GetAllUnits() else units = Spring.GetTeamUnits(myTeamID) end for i=1, #units do local uvx, uvy, uvz = Spring.GetUnitViewPosition(units[i], true) local ux, uy, uz = spWorldToScreenCoords(uvx, uvy, uvz) local hereMouseX, hereMouseY = x, y if ux and not Spring.GetUnitNoSelect(units[i]) then if ux >= math_min(screenStartX, hereMouseX) and ux < math_max(screenStartX, hereMouseX) and uy >= math_min(screenStartY, hereMouseY) and uy < math_max(screenStartY, hereMouseY) then allBoxedUnits[#allBoxedUnits+1] = units[i] end end end if #allBoxedUnits > 0 then return (WG.SelectionRank_GetFilteredSelection and WG.SelectionRank_GetFilteredSelection(allBoxedUnits)) or allBoxedUnits else return nil end end else holdingForSelection = false return nil end end WG.PreSelection_IsUnitInSelectionBox = function (unitID) if not boxedUnitIDs then boxedUnitIDs = {} local boxedUnits = WG.PreSelection_GetUnitsInSelectionBox() if boxedUnits then for i=1, #boxedUnits do boxedUnitIDs[boxedUnits[i]] = true end end end return boxedUnitIDs[unitID] or false end function widget:ShutDown() WG.PreSelection_GetUnitUnderCursor = nil WG.PreSelection_IsSelectionBoxActive = nil WG.PreSelection_GetUnitsInSelectionBox = nil WG.PreSelection_IsUnitInSelectionBox = nil end function widget:Update() boxedUnitIDs = nil end function widget:MousePress(x, y, button) screenStartX = x screenStartY = y if (button == 1) and Spring.GetActiveCommand() == 0 then thruMinimap = not WG.MinimapDraggingCamera and spIsAboveMiniMap(x, y) local _ _, start = SafeTraceScreenRay(x, y, true, thruMinimap) holdingForSelection = true end return false end
gpl-2.0
CarabusX/Zero-K
LuaRules/Gadgets/Include/GetNukeIntercepted.lua
6
1569
local atan = math.atan local cos = math.cos local sin = math.sin local pi = math.pi local sqrt = math.sqrt -- Unit (antinuke) position, Projectile (nuke silo) position, Target position local function GetNukeIntercepted(ux, uz, px, pz, tx, tz, radiusSq) -- Translate projectile position to the origin. ux, uz, tx, tz, px, pz = ux - px, uz - pz, tx - px, tz - pz, 0, 0 -- Get direction from projectile to target local tDir if tx == 0 then if tz == 0 then return ux^2 + uz^2 < radiusSq elseif tz > 0 then tDir = pi * 0.5 else tDir = pi * 1.5 end elseif tx > 0 then tDir = atan(tz/tx) else tDir = atan(tz/tx) + pi end -- Rotate space such that direction from projectile to target is 0 -- The nuke projectile will travel along the positive x-axis local cosDir = cos(-tDir) local sinDir = sin(-tDir) ux, uz = ux*cosDir - uz*sinDir, uz*cosDir + ux*sinDir tx, tz = tx*cosDir - tz*sinDir, tz*cosDir + tx*sinDir -- Find intersection of antinuke range with x-axis -- Quadratic formula, a = 1 local b = -2*ux local c = ux^2 + uz^2 - radiusSq local determinate = b^2 - 4*c if determinate < 0 then -- No real solutions so the circle does not intersect x-axis. -- This means that antinuke projectile does not cross intercept -- range. return false end determinate = sqrt(determinate) local leftInt = (-b - determinate)/2 local rightInt = (-b + determinate)/2 -- IF the nuke does not fall short of coverage -- AND the projectile is still within coverage return leftInt < tx and rightInt > 0 end return GetNukeIntercepted
gpl-2.0
junkblocker/hammerspoon
extensions/_coresetup/test_coresetup.lua
5
3503
function testOSExit() assertIsEqual("function", type(hs._exit)) assertIsEqual(hs._exit, os.exit) return success() end function testConfigDir() assertIsString(hs.configdir) assertTrue(hs.configdir ~= "") return success() end function testDocstringsJSONFile() assertIsString(hs.docstrings_json_file) assertTrue(hs.docstrings_json_file ~= "") local jsonFD = io.open(hs.docstrings_json_file, "r") local json = jsonFD:read("*all") assertIsTable(hs.json.decode(json)) return success() end function testProcessInfo() assertIsTable(hs.processInfo) assertIsString(hs.processInfo["bundleID"]) assertIsString(hs.processInfo["bundlePath"]) assertIsString(hs.processInfo["executablePath"]) assertIsNumber(hs.processInfo["processID"]) assertIsString(hs.processInfo["resourcePath"]) assertIsString(hs.processInfo["version"]) return success() end function testShutdownCallback() hs.shutdownCallback = shutdownLib.verifyShutdown hs.reload() return success() end function testAccessibilityState() local result = hs.accessibilityState(false) assertIsBoolean(result) return success() end function testAutoLaunch() local orig = hs.autoLaunch() assertIsBoolean(orig) assertIsEqual(orig, hs.autoLaunch(orig)) assertIsEqual(not orig, hs.autoLaunch(not orig)) -- Be nice and put it back hs.autoLaunch(orig) return success() end function testAutomaticallyCheckForUpdates() -- NB It's not safe to actually call the function on a non-release build, so we can just check that it is a function assertIsFunction(hs.automaticallyCheckForUpdates) return success() end function testCheckForUpdates() -- NB It is not safe to actually call the function on a non-release build, so we can just check that it is a function assertIsFunction(hs.checkForUpdates) return success() end function testCleanUTF8forConsole() local orig = "Simple test string" assertIsEqual(orig, hs.cleanUTF8forConsole(orig)) return success() end function testConsoleOnTop() local orig = hs.consoleOnTop() assertIsBoolean(orig) assertIsEqual(orig, hs.consoleOnTop(orig)) assertIsEqual(not orig, hs.consoleOnTop(not orig)) -- Be nice and put it back hs.consoleOnTop(orig) return success() end function testDockIcon() local orig = hs.dockIcon() assertIsBoolean(orig) assertIsEqual(orig, hs.dockIcon(orig)) assertIsEqual(not orig, hs.dockIcon(not orig)) -- Be nice and put it back hs.dockIcon(orig) return success() end -- Note: This test is not called for the moment, it doesn't seem to work when run from a process under Xcode function testExecute() local output, status, type, rc output, status, type, rc = hs.execute("/usr/bin/uname", false) assertIsEqual(0, rc) assertIsEqual("exit", type) assertTrue(status) assertIsNotNil(string.find(output, "Darwin")) output, status, type, rc = hs.execute("/usr/bin/uname", true) assertIsEqual(0, rc) assertIsEqual("exit", type) assertTrue(status) assertIsNotNil(string.find(output, "Darwin")) return success() end function testGetObjectMetatable() require("hs.screen") local meta = hs.getObjectMetatable("hs.screen") assertIsTable(meta) assertIsEqual("hs.screen", meta["__type"]) return success() end function testMenuIcon() local orig = hs.menuIcon() assertIsBoolean(orig) assertIsEqual(orig, hs.menuIcon(orig)) assertIsEqual(not orig, hs.menuIcon(not orig)) -- Be nice and put it back hs.menuIcon(orig) return success() end
mit
PeqNP/GameKit
src/royal/AdVendor.lua
1
2856
-- -- Manages which tiers can be presented. -- -- @todo Filter adunits and tiers to have the highest paid tiers displayed first. -- @todo Add a 'stylize' parameter that is used to style the button being presented. -- -- @copyright Upstart Illustration LLC. All rights reserved. -- local ClickableAdUnit = require("royal.ClickableAdUnit") local AdVendor = Class() -- -- @param AdManifest -- @param configMatches - function used to determine if the config matches criteria of the current app state. -- must return 'true', if the tier config matches. 'false', otherwise. -- function AdVendor.new(self) local adConfig local style local adUnits local fn__configMatches local unitPos = 1 function self.init(_adConfig, _style, _adUnits, _fn) adConfig = _adConfig style = _style adUnits = _adUnits fn__configMatches = _fn end function self.reset() unitPos = 1 end local function addClickableAdUnit(subject, adUnit, key) local click = ClickableAdUnit(adConfig, adUnit, key) if click.isActive() then table.insert(subject, click) end end function self.getNextAdUnits(amount) if not adUnits or #adUnits == 0 then -- #adUnits condition is untested return nil end local ret = {} -- Add units to return. local currPos = unitPos while true do local adUnit = adUnits[unitPos] -- Add one ad unit, if validator passes. if adUnit.isActive() then local config = adUnit.getConfig() if config and fn__configMatches then local matches, key = fn__configMatches(config) if matches then addClickableAdUnit(ret, adUnit, key) end elseif not config then addClickableAdUnit(ret, adUnit) end end unitPos = unitPos + 1 if unitPos > #adUnits then unitPos = 1 end -- Back to the first ad we will vend. Do not dupe and return only -- what we have. if currPos == unitPos then break end if #ret >= amount then break end end return ret end function self.getNextAdUnitButtons(amount, fn__callback) local buttons = {} local nextUnits = self.getNextAdUnits(amount) for _, adUnit in ipairs(nextUnits) do local function fn__clicked() fn__callback(adUnit) end local button = style.getButton(adUnit, fn__clicked) table.insert(buttons, button) end return buttons end end return AdVendor
mit
luciouskami/YDWE
Development/Component/plugin/w3x2lni/script/gui/old/plugin.lua
2
3210
fs = require 'bee.filesystem' require 'utility' local root = fs.current_path():remove_filename() local plugin_path = root / 'plugin' local function load_one_plugin(path) local plugin = assert(load(io.load(path), '@'..path:string(), 't', _ENV))() return { path = path:stem():string(), name = plugin.info and plugin.info.name or path:stem():string(), version = plugin.info and plugin.info.version or '未知', author = plugin.info and plugin.info.author or '未知', description = plugin.info and plugin.info.description, } end local function load_plugins() local plugins = {} for path in plugin_path:list_directory() do if not fs.is_directory(path) and path:extension():string() == '.lua' then local ok, res = pcall(load_one_plugin, path) if ok then plugins[#plugins+1] = res end end end table.sort(plugins, function (a, b) return a.name < b.name end) return plugins end local function load_enable_list() local list = {} local buf = io.load(plugin_path / '.config') if buf then for name in buf:gmatch '[^\r\n]+' do list[name] = true end end return list end local function save_enable_list(list) local array = {} for name, enable in pairs(list) do if enable then array[#array+1] = name end end table.sort(array) array[#array+1] = '' io.save(plugin_path / '.config', table.concat(array, '\r\n')) end local plugins local last_clock local current_plugin local check_plugins local enable_list local function checkbox_plugin(canvas, text, plugin, active) canvas:layout_space_push(0, 0, 320, 25) local ok, _, state = canvas:checkbox(text, active) if state & NK_WIDGET_STATE_LEFT ~= 0 then current_plugin = plugin end if plugin.description then canvas:layout_space_push(0, 0, 320, 25) canvas:text('', NK_TEXT_LEFT, plugin.description) end return ok end local function show_plugin(canvas) check_plugins() current_plugin = nil canvas:layout_row_dynamic(415, 1) canvas:group('说明', function() if plugins then for _, plugin in ipairs(plugins) do canvas:layout_space(25, 2) if checkbox_plugin(canvas, plugin.name, plugin, enable_list[plugin.path]) then enable_list[plugin.path] = not enable_list[plugin.path] save_enable_list(enable_list) end end end end) canvas:layout_row_dynamic(25, 1) if current_plugin then canvas:text('作者:' .. current_plugin.author, NK_TEXT_LEFT) canvas:text('版本:' .. current_plugin.version, NK_TEXT_LEFT) else canvas:text('', NK_TEXT_LEFT) canvas:text('', NK_TEXT_LEFT) end end function check_plugins() if not last_clock or os.clock() - last_clock > 1 then last_clock = os.clock() plugins = load_plugins() enable_list = load_enable_list() end if #plugins == 0 then return nil end return show_plugin end return check_plugins
gpl-3.0
luohancfd/FluidDynamicTools
Thermo_Chemical_Properties/Molecule_Properties/RawData/I2.lua
1
1648
-- Author: Rowan J. Gollan -- Date: 30-Oct-2008 -- diatomic iodine I2 = {} I2.M = { value = 253.8089400e-3, units = 'kg/mol', description = 'molecular mass', reference = 'molecular weight from CEA2' } I2.atomic_constituents = {I=2} I2.charge = 0 I2.gamma = { value = 1.4, units = 'non-dimensional', description = '(ideal) ratio of specific heats at room temperature', reference = 'diatomic molecule at low temperatures, gamma = 7/5' } I2.e_zero = { value = 245933.0, units = 'J/kg', description = 'reference energy, from CEA enthalpy of formation' } I2.CEA_coeffs = { { T_low = 200.0, T_high = 1000.0, coeffs = { -5.087968770e+03, -1.249585210e+01, 4.504219090e+00, 1.370962533e-04, -1.390523014e-07, 1.174813853e-10, -2.337541043e-14, 6.213469810e+03, 5.583836940e+00 } }, { T_low = 1000.000, T_high = 6000.000, coeffs = { -5.632594160e+06, 1.793961560e+04, -1.723055169e+01, 1.244214080e-02, -3.332768580e-06, 4.125477940e-10, -1.960461713e-14, -1.068505292e+05, 1.600531883e+02 } } } -- Presently these values are oxygen values. I2.d = { value = 3.433e-10, units = 'm', description = 'equivalent hard sphere diameter, based on L-J parameters', reference = 'Bird, Stewart and Lightfoot (2001), p. 864' } I2.viscosity = { model = "Sutherland", parameters = { mu_ref = 1.919e-05, T_ref = 273.0, S = 139.0, ref = "Table 1-2, White (2006)" } } I2.thermal_conductivity = { model = "Sutherland", parameters = { k_ref = 0.0244, T_ref = 273.0, S = 240.0, ref = "Table 1-3, White (2006)" } }
gpl-3.0
CarabusX/Zero-K
LuaUI/Widgets/unit_icons.lua
6
9615
------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Unit Icons", desc = "v0.033 Shows icons above units", author = "CarRepairer and GoogleFrog", date = "2012-01-28", license = "GNU GPL, v2 or later", layer = -10,-- enabled = true, -- loaded by default? } end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local echo = Spring.Echo local spGetUnitDefID = Spring.GetUnitDefID local spIsUnitInView = Spring.IsUnitInView local spGetUnitViewPosition = Spring.GetUnitViewPosition local spGetGameFrame = Spring.GetGameFrame local glDepthTest = gl.DepthTest local glDepthMask = gl.DepthMask local glAlphaTest = gl.AlphaTest local glTexture = gl.Texture local glTexRect = gl.TexRect local glTranslate = gl.Translate local glBillboard = gl.Billboard local glDrawFuncAtUnit = gl.DrawFuncAtUnit local glPushMatrix = gl.PushMatrix local glPopMatrix = gl.PopMatrix local GL_GREATER = GL.GREATER local min = math.min local max = math.max local floor = math.floor local abs = math.abs local iconsize = 5 local forRadarIcons = true ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- options_path = 'Settings/Interface/Hovering Icons' options = { iconsize = { name = 'Hovering Icon Size', type = 'number', value = 30, min=10, max = 40, OnChange = function(self) iconsize = self.value end }, forRadarIcons = { name = 'Draw on Icons', desc = 'Draws state icons when zoomed out.', type = 'bool', value = true, noHotkey = true, OnChange = function(self) forRadarIcons = self.value end }, } options.iconsize.OnChange(options.iconsize) ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- local unitHeights = {} local iconOrders = {} local iconOrders_order = {} local iconoffset = 26 local iconUnitTexture = {} --local textureUnitsXshift = {} local textureData = {} local textureIcons = {} local textureOrdered = {} local textureColors = {} --local xshiftUnitTexture = {} local hideIcons = {} local pulseIcons = {} local updateTime, iconFade = 0, 0 WG.icons = {} ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local function OrderIcons() iconOrders_order = {} for iconName, _ in pairs(iconOrders) do iconOrders_order[#iconOrders_order+1] = iconName end table.sort(iconOrders_order, function(a,b) return iconOrders[ a ] < iconOrders[ b ] end) end local function OrderIconsOnUnit(unitID ) local iconCount = 0 for i=1, #iconOrders_order do local iconName = iconOrders_order[i] if (not hideIcons[iconName]) and iconUnitTexture[iconName] and iconUnitTexture[iconName][unitID] then iconCount = iconCount + 1 end end local xshift = (0.5 - iconCount*0.5)*iconsize for i=1, #iconOrders_order do local iconName = iconOrders_order[i] local texture = iconUnitTexture[iconName] and iconUnitTexture[iconName][unitID] if texture then if hideIcons[iconName] then --textureUnitsXshift[texture][unitID] = nil textureData[texture][iconName][unitID] = nil else --textureUnitsXshift[texture][unitID] = xshift textureData[texture][iconName][unitID] = xshift xshift = xshift + iconsize end end end end local function SetOrder(iconName, order) iconOrders[iconName] = order OrderIcons() end local function ReOrderIconsOnUnits() local units = Spring.GetAllUnits() for i=1,#units do OrderIconsOnUnit(units[i]) end end function WG.icons.SetDisplay( iconName, show ) local hide = (not show) or nil curHide = hideIcons[iconName] if curHide ~= hide then hideIcons[iconName] = hide ReOrderIconsOnUnits() end end function WG.icons.SetOrder( iconName, order ) SetOrder(iconName, order) end function WG.icons.SetPulse( iconName, pulse ) pulseIcons[iconName] = pulse end function WG.icons.SetUnitIcon(unitID, data) local iconName = data.name local texture = data.texture local color = data.color if not iconOrders[iconName] then SetOrder(iconName, math.huge) end local oldTexture = iconUnitTexture[iconName] and iconUnitTexture[iconName][unitID] if oldTexture then --textureUnitsXshift[oldTexture][unitID] = nil textureData[oldTexture][iconName][unitID] = nil iconUnitTexture[iconName][unitID] = nil if (not hideIcons[iconName])then OrderIconsOnUnit(unitID) end end if not texture then return end --[[ if not textureUnitsXshift[texture] then textureUnitsXshift[texture] = {} end textureUnitsXshift[texture][unitID] = 0 --]] --new if not textureData[texture] then textureData[texture] = {} end if not textureData[texture][iconName] then textureData[texture][iconName] = {} end textureData[texture][iconName][unitID] = 0 if color then if not textureColors[unitID] then textureColors[unitID] = {} end textureColors[unitID][iconName] = color end if not iconUnitTexture[iconName] then iconUnitTexture[iconName] = {} end iconUnitTexture[iconName][unitID] = texture if not unitHeights[unitID] then local ud = UnitDefs[spGetUnitDefID(unitID)] if (ud == nil) then unitHeights[unitID] = nil else --unitHeights[unitID] = Spring.Utilities.GetUnitHeight(ud) + iconoffset unitHeights[unitID] = Spring.GetUnitHeight(unitID) + iconoffset end end OrderIconsOnUnit(unitID) end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function widget:UnitDestroyed(unitID, unitDefID, unitTeam) unitHeights[unitID] = nil --xshiftUnitTexture[unitID] = nil end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local function DrawFuncAtUnitIcon2(unitID, xshift, yshift) local x,y,z = spGetUnitViewPosition(unitID) glPushMatrix() glTranslate(x,y,z) glTranslate(0,yshift,0) glBillboard() glTexRect(xshift -iconsize*0.5, -5, xshift + iconsize*0.5, iconsize-5) glPopMatrix() end local function DrawUnitFunc(xshift, yshift) glTranslate(0,yshift,0) glBillboard() glTexRect(xshift - iconsize*0.5, -9, xshift + iconsize*0.5, iconsize-9) end local function DrawWorldFunc() if Spring.IsGUIHidden() then return end if (next(unitHeights) == nil) then return -- avoid unnecessary GL calls end local gameFrame = spGetGameFrame() gl.Color(1,1,1,1) glDepthMask(true) glDepthTest(true) glAlphaTest(GL_GREATER, 0.001) --for texture, units in pairs(textureUnitsXshift) do for texture, curTextureData in pairs(textureData) do for iconName, units in pairs(curTextureData) do glTexture(texture) for unitID,xshift in pairs(units) do local textureColor = textureColors[unitID] and textureColors[unitID][iconName] if textureColor then gl.Color( textureColor ) elseif pulseIcons[iconName] then gl.Color( 1,1,1,iconFade ) end local unitInView = spIsUnitInView(unitID) if unitInView and xshift and unitHeights and unitHeights[unitID] then if forRadarIcons then DrawFuncAtUnitIcon2(unitID, xshift, unitHeights[unitID]) else glDrawFuncAtUnit(unitID, false, DrawUnitFunc,xshift,unitHeights[unitID]) end end if textureColor or pulseIcons[iconName] then gl.Color(1,1,1,1) end end end end glTexture(false) glAlphaTest(false) glDepthTest(false) glDepthMask(false) end function widget:DrawWorld() DrawWorldFunc() end function widget:DrawWorldRefraction() DrawWorldFunc() end function widget:Update(dt) updateTime = (updateTime + dt)%2 iconFade = min(abs(((updateTime*30) % 60) - 20) / 20, 1 ) end -- drawscreen method -- the problem with this one is it draws at same size regardless of how far away the unit is --[[ function widget:DrawScreenEffects() if Spring.IsGUIHidden() then return end if (next(unitHeights) == nil) then return -- avoid unnecessary GL calls end gl.Color(1,1,1,1) glDepthMask(true) glDepthTest(true) glAlphaTest(GL_GREATER, 0.001) for texture, units in pairs(textureUnitsXshift) do glTexture( texture ) for unitID,xshift in pairs(units) do gl.PushMatrix() local x,y,z = Spring.GetUnitPosition(unitID) y = y + (unitHeights[unitID] or 0) x,y,z = Spring.WorldToScreenCoords(x,y,z) glTranslate(x,y,z) if xshift and unitHeights then glTranslate(xshift,0,0) --glBillboard() glTexRect(-iconsize*0.5, -9, iconsize*0.5, iconsize-9) end gl.PopMatrix() end end glTexture(false) glAlphaTest(false) glDepthTest(false) glDepthMask(false) end ]] function widget:Initialize() end function widget:Shutdown() --for texture,_ in pairs(textureUnitsXshift) do for texture,_ in pairs(textureData) do gl.DeleteTexture(texture) end end ------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------
gpl-2.0
PAC3-Server/ServerContent
lua/notagain/essential/libraries/debug_traceback2.lua
2
5299
local function tostringx(obj) local t = type(obj) if obj == NULL then return t .. "(NULL)" elseif t == "string" then if obj:find("\n", nil, true) then obj = obj:gsub("\n", "\\n"):sub(0,50) .. "..." end return '"' .. obj .. '"' elseif t == "Player" then return "Player("..obj:UserID()..") -- " .. obj:Nick() .. " / " .. obj:SteamID64() elseif t == "Entity" then return "Entity("..obj:EntIndex()..")" elseif t == "function" then local info = debug.getinfo(obj) if info.source == "=[C]" then return "function() end -- C function" else local params = {} for i = 1, math.huge do local key = debug.getlocal(obj, i) if key then table.insert(params, key) else break end end return "function(" .. table.concat(params, ", ") .. ") end" -- " .. info.source .. ":" .. info.linedefined end end local ok, str = pcall(tostring, obj) if not ok then return "tostring error: " .. str end return str end local function line_from_info(info, line) local lua if file then if info.source:find("<", nil, true) then lua = file.Read(info.source:match("%<(.-)%>"), "MOD") -- luadata elseif info.source:sub(1,1) == "@" then lua = file.Read(info.source:sub(2), "LUA") or file.Read(info.source:sub(2), "MOD") end else if info.source:sub(1,1) == "@" then local f = io.open(info.source:sub(2), "r") if f then lua = f:read("*all") f:close() end end end if lua then local i = 1 for str in (lua .. "\n"):gmatch("(.-)\n") do if line == i then return str end i = i + 1 end end end local function func_line_from_info(info, line_override, fallback_info, nocomment) if info.namewhat == "metamethod" then if info.name == "__add" then print(debug.getlocal(info.func, 0), "!") print(debug.getlocal(info.func, 1), "!") return "+" end end if info.source then local line = line_from_info(info, line_override or info.linedefined) if line and line:find("%b()") then line = line:gsub("^%s*", ""):reverse():gsub("^%s*", ""):reverse() -- trim return line .. (nocomment and "" or " -- inlined function " .. (info.name or fallback_info or "__UNKNOWN__")) end end if info.source == "=[C]" then return "function " .. (info.name or fallback_info or "__UNKNOWN__") .. "(=[C])" end local str = "function " .. (info.name or fallback_info or "__UNKNOWN__") str = str .. "(" local arg_line = {} if info.isvararg then table.insert(arg_line, "...") else for i = 1, info.nparams do local key, val = debug.getlocal(info.func, i) if not key then break end if key == "(*temporary)" then table.insert(arg_line, tostringx(val)) elseif key:sub(1, 1) ~= "(" then table.insert(arg_line, key) end end end str = str .. table.concat(arg_line, ", ") str = str .. ")" return str end return function(offset, check_level) offset = offset or 0 local str = "" local max_level = 0 local min_level = offset for level = min_level, math.huge do if not debug.getinfo(level) then break end max_level = level end local extra_indent = 3 local for_loop local for_gen for level = max_level, min_level, -1 do local info = debug.getinfo(level) if not info then break end if check_level and check_level(info, level) ~= nil then break end local normalized_level = -level + max_level local t = (" "):rep(normalized_level + extra_indent) if level == max_level then str = str .. normalized_level .. ": " str = str .. func_line_from_info(info) .. "\n" elseif level ~= min_level then if info.source ~= "=[C]" then str = str .. "\n" local info = debug.getinfo(level+1) or info str = str .. t .. func_line_from_info(info, info.currentline, nil, true) .. " >> \n" end str = str .. normalized_level .. ": " t = t:sub(4) str = str .. t .. func_line_from_info(info) str = str .. "\n" extra_indent = extra_indent + 1 end local t = (" "):rep(normalized_level + extra_indent) for i = 1, math.huge do local key, val = debug.getlocal(level, i) if not key then break end if key == "(for generator)" then for_gen = "" elseif key == "(for state)" then elseif key == "(for control)" then elseif key == "(for index)" then for_loop = "" elseif key == "(for limit)" then for_loop = for_loop .. val .. ", " elseif key == "(for step)" then for_loop = for_loop .. val .. " do" elseif key ~= "(*temporary)" then if for_loop then str = str .. t .. "for " .. key .. " = " .. val .. ", " .. for_loop .. "\n" extra_indent = extra_indent + 1 t = (" "):rep(-level + max_level + extra_indent) for_loop = nil else if for_gen then if for_gen == "" then for_gen = "for " .. key .. " = " .. tostringx(val) .. ", " else for_gen = for_gen .. key .. " = " .. tostringx(val) .. " in ??? do" str = str .. t .. for_gen .. "\n" extra_indent = extra_indent + 1 t = (" "):rep(normalized_level + extra_indent) for_gen = nil end else str = str .. t .. key .. " = " .. tostringx(val) .. "\n" end end end end if level == min_level then str = str .. ">>" .. t:sub(3) .. func_line_from_info(info, info.currentline) .. " <<\n" end end return str end
mit
rainfiel/skynet
test/testbson.lua
12
1411
local bson = require "bson" sub = bson.encode_order( "hello", 1, "world", 2 ) local function tbl_next(...) print("--- next.a", ...) local k, v = next(...) print("--- next.b", k, v) return k, v end local function tbl_pairs(obj) return tbl_next, obj.__data, nil end local obj_a = { __data = { [1] = 2, [3] = 4, [5] = 6, } } setmetatable( obj_a, { __index = obj_a.__data, __pairs = tbl_pairs, } ) local obj_b = { __data = { [7] = 8, [9] = 10, [11] = obj_a, } } setmetatable( obj_b, { __index = obj_b.__data, __pairs = tbl_pairs, } ) local metaarray = setmetatable({ n = 5 }, { __len = function(self) return self.n end, __index = function(self, idx) return tostring(idx) end, }) b = bson.encode { a = 1, b = true, c = bson.null, d = { 1,2,3,4 }, e = bson.binary "hello", f = bson.regex ("*","i"), g = bson.regex "hello", h = bson.date (os.time()), i = bson.timestamp(os.time()), j = bson.objectid(), k = { a = false, b = true }, l = {}, m = bson.minkey, n = bson.maxkey, o = sub, p = 2^32-1, q = obj_b, r = metaarray, } print "\n[before replace]" t = b:decode() for k, v in pairs(t) do print(k,type(v)) end for k,v in ipairs(t.r) do print(k,v) end b:makeindex() b.a = 2 b.b = false b.h = bson.date(os.time()) b.i = bson.timestamp(os.time()) b.j = bson.objectid() print "\n[after replace]" t = b:decode() print("o.hello", bson.type(t.o.hello))
mit
Bpalkmim/LadyLuck
Tests/tests.lua
1
1243
-- @module Test -- @file tests.lua -- @author Bernardo Pinto de Alkmim -- @creation 2016/04/11 -- @description Este arquivo é responsável por rodar os testes de IO -- (e quaisquer outros que sejam necessários). -- @version 0.8 package.path = package.path .. ";../Dice/dice.lua" local testsDice = require("testsDice") package.path = package.path .. ";../IO/reader.lua" local testsReader = require("testsReader") package.path = package.path .. ";../IO/writer.lua" local testsWriter = require("testsWriter") -- Módulo de Lua que representa esse arquivo. local tests = {} -- Função principal do módulo, que executa todos os testes dos módulos -- de teste específicos. function tests.executeSuite() testsDice.executeDiceTests() print("Erros nos testes de Dice:", testsDice.errorsDice) -- TODO depois da parte gráfica --testsReader.executeReaderTests() print("Erros nos testes de Reader:", testsReader.errorsReader) -- TODO depois da parte gráfica --testsWriter.executeWriterTests() print("Erros nos testes de Writer:", testsWriter.errorsWriter) print("Total de erros nos testes:", testsDice.errorsDice + testsReader.errorsReader + testsWriter.errorsWriter) end -- Execução dos testes tests.executeSuite() return tests
gpl-3.0
mattyx14/otxserver
data/monster/bosses/zoralurk.lua
2
4637
local mType = Game.createMonsterType("Zoralurk") local monster = {} monster.description = "Zoralurk" monster.experience = 30000 monster.outfit = { lookType = 12, lookHead = 0, lookBody = 98, lookLegs = 86, lookFeet = 94, lookAddons = 0, lookMount = 0 } monster.health = 55000 monster.maxHealth = 55000 monster.race = "undead" monster.corpse = 6068 monster.speed = 400 monster.manaCost = 0 monster.changeTarget = { interval = 10000, chance = 20 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = true, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 98, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.summon = { maxSummons = 2, summons = { {name = "demon", chance = 50, interval = 4000, count = 2} } } monster.voices = { interval = 5000, chance = 10, {text = "I AM ZORALURK, THE DEMON WITH A THOUSAND FACES!", yell = true}, {text = "BRING IT, COCKROACHES!", yell = true} } monster.loot = { {name = "white pearl", chance = 10000, maxCount = 5}, {name = "gold coin", chance = 100000, maxCount = 100}, {name = "gold coin", chance = 50000, maxCount = 90}, {name = "boots of haste", chance = 16033}, {name = "giant sword", chance = 60000}, {name = "bright sword", chance = 20000}, {name = "bright sword", chance = 20000}, {name = "warlord sword", chance = 6000}, {name = "patched boots", chance = 7000}, {id = 3123, chance = 16000} -- worn leather boots } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -1013}, {name ="combat", interval = 1000, chance = 12, type = COMBAT_ENERGYDAMAGE, minDamage = -600, maxDamage = -900, radius = 7, effect = CONST_ME_ENERGYHIT, target = false}, {name ="combat", interval = 1000, chance = 12, type = COMBAT_EARTHDAMAGE, minDamage = -400, maxDamage = -800, radius = 7, effect = CONST_ME_SMALLPLANTS, target = false}, {name ="combat", interval = 2000, chance = 25, type = COMBAT_MANADRAIN, minDamage = -500, maxDamage = -800, range = 7, effect = CONST_ME_MAGIC_BLUE, target = false}, {name ="combat", interval = 3000, chance = 35, type = COMBAT_FIREDAMAGE, minDamage = -200, maxDamage = -600, range = 7, radius = 7, shootEffect = CONST_ANI_FIRE, effect = CONST_ME_FIREAREA, target = true} } monster.defenses = { defense = 65, armor = 55, {name ="combat", interval = 2000, chance = 35, type = COMBAT_HEALING, minDamage = 300, maxDamage = 800, effect = CONST_ME_MAGIC_BLUE, target = false}, {name ="speed", interval = 4000, chance = 80, speedChange = 440, effect = CONST_ME_MAGIC_RED, target = false, duration = 6000}, {name ="outfit", interval = 2000, chance = 10, effect = CONST_ME_CRAPS, target = false, duration = 10000, outfitMonster = "behemoth"}, {name ="outfit", interval = 2000, chance = 10, effect = CONST_ME_CRAPS, target = false, duration = 10000, outfitMonster = "fire devil"}, {name ="outfit", interval = 2000, chance = 10, effect = CONST_ME_CRAPS, target = false, duration = 10000, outfitMonster = "giant spider"}, {name ="outfit", interval = 2000, chance = 10, effect = CONST_ME_CRAPS, target = false, duration = 10000, outfitMonster = "undead dragon"}, {name ="outfit", interval = 2000, chance = 10, effect = CONST_ME_CRAPS, target = false, duration = 10000, outfitMonster = "lost soul"} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 100}, {type = COMBAT_EARTHDAMAGE, percent = 100}, {type = COMBAT_FIREDAMAGE, percent = 100}, {type = COMBAT_LIFEDRAIN, percent = 100}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 0}, {type = COMBAT_HOLYDAMAGE , percent = 0}, {type = COMBAT_DEATHDAMAGE , percent = 0} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = true}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType.onThink = function(monster, interval) end mType.onAppear = function(monster, creature) if monster:getType():isRewardBoss() then monster:setReward(true) end end mType.onDisappear = function(monster, creature) end mType.onMove = function(monster, creature, fromPosition, toPosition) end mType.onSay = function(monster, creature, type, message) end mType:register(monster)
gpl-2.0
bobkersten/domoticz
scripts/lua/script_time_demo.lua
55
1932
-- demo time script -- script names have three name components: script_trigger_name.lua -- trigger can be 'time' or 'device', name can be any string -- domoticz will execute all time and device triggers when the relevant trigger occurs -- -- copy this script and change the "name" part, all scripts named "demo" are ignored. -- -- Make sure the encoding is UTF8 of the file -- -- ingests tables: otherdevices,otherdevices_svalues -- -- otherdevices and otherdevices_svalues are two item array for all devices: -- otherdevices['yourotherdevicename']="On" -- otherdevices_svalues['yourotherthermometer'] = string of svalues -- -- Based on your logic, fill the commandArray with device commands. Device name is case sensitive. -- -- Always, and I repeat ALWAYS start by checking for a state. -- If you would only specify commandArray['AnotherDevice']='On', every time trigger (e.g. every minute) will switch AnotherDevice on. -- -- The print command will output lua print statements to the domoticz log for debugging. -- List all otherdevices states for debugging: -- for i, v in pairs(otherdevices) do print(i, v) end -- List all otherdevices svalues for debugging: -- for i, v in pairs(otherdevices_svalues) do print(i, v) end print('this will end up in the domoticz log') t1 = os.time() s = otherdevices_lastupdate['Garagedoor'] -- returns a date time like 2013-07-11 17:23:12 year = string.sub(s, 1, 4) month = string.sub(s, 6, 7) day = string.sub(s, 9, 10) hour = string.sub(s, 12, 13) minutes = string.sub(s, 15, 16) seconds = string.sub(s, 18, 19) commandArray = {} t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds} difference = (os.difftime (t1, t2)) if (otherdevices['Garagedoor'] == 'Open' and difference > 600 and difference < 700) then commandArray['SendNotification']='Garage door alert#The garage door has been open for more than 10 minutes!' end return commandArray
gpl-3.0
tgp1994/LiquidRP-tgp1994
entities/weapons/weapon_real_base_pistol/shared.lua
1
1586
-- Read the weapon_real_base if you really want to know what each action does if (SERVER) then AddCSLuaFile("shared.lua") end if (CLIENT) then SWEP.DrawAmmo = true SWEP.DrawCrosshair = false SWEP.ViewModelFOV = 60 SWEP.ViewModelFlip = true end /*--------------------------------------------------------- Muzzle Effect + Shell Effect ---------------------------------------------------------*/ SWEP.MuzzleEffect = "rg_muzzle_pistol" -- This is an extra muzzleflash effect -- Available muzzle effects: rg_muzzle_grenade, rg_muzzle_highcal, rg_muzzle_hmg, rg_muzzle_pistol, rg_muzzle_rifle, rg_muzzle_silenced, none SWEP.ShellEffect = "rg_shelleject" -- This is a shell ejection effect -- Available shell eject effects: rg_shelleject, rg_shelleject_rifle, rg_shelleject_shotgun, none SWEP.MuzzleAttachment = "1" -- Should be "1" for CSS models or "muzzle" for hl2 models SWEP.ShellEjectAttachment = "2" -- Should be "2" for CSS models or "1" for hl2 models /*-------------------------------------------------------*/ SWEP.Base = "weapon_real_base" SWEP.Spawnable = false SWEP.AdminSpawnable = false SWEP.HoldType = "pistol" SWEP.Primary.Sound = Sound("Weapon_AK47.Single") SWEP.Primary.Recoil = 0 SWEP.Primary.Damage = 0 SWEP.Primary.NumShots = 0 SWEP.Primary.Cone = 0 SWEP.Primary.ClipSize = 0 SWEP.Primary.Delay = 0 SWEP.Primary.DefaultClip = 0 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "pistol" SWEP.Secondary.ClipSize = 0 SWEP.Secondary.DefaultClip = 0 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none"
gpl-3.0
asiftastos/Yamac
scripts/genie.lua
2
2218
ROOT_DIR = path.getabsolute("..") BUILD_DIR = path.join(ROOT_DIR, "build") LIBS_DIR = path.join(ROOT_DIR, "libs") -- Clean action. if _ACTION == "clean" then os.rmdir(BUILD_DIR) os.rmdir(LIBS_DIR) os.exit(1) end solution "habiwoodext" configurations { "Debug", "Release" } platforms { "x64" } location(path.join(BUILD_DIR, _ACTION)) objdir (path.join(BUILD_DIR, "obj")) project "habiwoodext" kind "StaticLib" language "C" targetdir(LIBS_DIR) includedirs { path.join(ROOT_DIR, "embed", "stb"), path.join(ROOT_DIR, "embed", "glfw", "include"), path.join(ROOT_DIR, "embed", "glfw", "src") } files { path.join(ROOT_DIR, "embed", "habiwoodext", "**.c"), path.join(ROOT_DIR, "embed", "glfw", "src/context.c"), path.join(ROOT_DIR, "embed", "glfw", "src/init.c"), path.join(ROOT_DIR, "embed", "glfw", "src/input.c"), path.join(ROOT_DIR, "embed", "glfw", "src/monitor.c"), path.join(ROOT_DIR, "embed", "glfw", "src/window.c"), path.join(ROOT_DIR, "embed", "glfw", "src/vulkan.c") } configuration "windows" defines { "_WIN64", "WINDOWS", "_WIN32", "_GLFW_WIN32" } targetprefix "" targetextension ".lib" files { path.join(ROOT_DIR, "embed", "glfw", "src/win32*.c"), path.join(ROOT_DIR, "embed", "glfw", "src/wgl_context.c"), path.join(ROOT_DIR, "embed", "glfw", "src/egl_context.c"), path.join(ROOT_DIR, "embed", "glfw", "src/osmesa_context.c"), } links { "gdi32" } configuration { "Debug" } targetsuffix "_d" defines { "_DEBUG" } flags { "Symbols" } configuration { "Release" } defines { "NDEBUG" } flags { "NoBufferSecurityCheck", "OptimizeSpeed" } configuration {}
mit
CarabusX/Zero-K
LuaRules/Configs/StartBoxes/Rage_v1.lua
17
2366
return { [0] = { startpoints = { {870,3635}, }, boxes = { { {512,3277}, {1229,3277}, {1229,3994}, {512,3994}, }, }, }, [1] = { startpoints = { {9574,5990}, }, boxes = { { {9216,5632}, {9933,5632}, {9933,6349}, {9216,6349}, }, }, }, [2] = { startpoints = { {7424,973}, }, boxes = { { {7066,614}, {7782,614}, {7782,1331}, {7066,1331}, }, }, }, [3] = { startpoints = { {3123,8960}, }, boxes = { { {2765,8602}, {3482,8602}, {3482,9318}, {2765,9318}, }, }, }, [4] = { startpoints = { {3226,1382}, }, boxes = { { {2867,1024}, {3584,1024}, {3584,1741}, {2867,1741}, }, }, }, [5] = { startpoints = { {7322,9574}, }, boxes = { { {6963,9216}, {7680,9216}, {7680,9933}, {6963,9933}, }, }, }, [6] = { startpoints = { {973,5786}, }, boxes = { { {614,5427}, {1331,5427}, {1331,6144}, {614,6144}, }, }, }, [7] = { startpoints = { {9472,3738}, }, boxes = { { {9114,3379}, {9830,3379}, {9830,4096}, {9114,4096}, }, }, }, [8] = { startpoints = { {768,870}, }, boxes = { { {410,512}, {1126,512}, {1126,1229}, {410,1229}, }, }, }, [9] = { startpoints = { {9574,870}, }, boxes = { { {9216,512}, {9933,512}, {9933,1229}, {9216,1229}, }, }, }, [10] = { startpoints = { {9574,9267}, }, boxes = { { {9216,8909}, {9933,8909}, {9933,9626}, {9216,9626}, }, }, }, [11] = { startpoints = { {768,9677}, }, boxes = { { {410,9318}, {1126,9318}, {1126,10035}, {410,10035}, }, }, }, [12] = { startpoints = { {3123,3430}, }, boxes = { { {2765,3072}, {3482,3072}, {3482,3789}, {2765,3789}, }, }, }, [13] = { startpoints = { {7219,3738}, }, boxes = { { {6861,3379}, {7578,3379}, {7578,4096}, {6861,4096}, }, }, }, [14] = { startpoints = { {7117,6912}, }, boxes = { { {6758,6554}, {7475,6554}, {7475,7270}, {6758,7270}, }, }, }, [15] = { startpoints = { {3226,6605}, }, boxes = { { {2867,6246}, {3584,6246}, {3584,6963}, {2867,6963}, }, }, }, }
gpl-2.0
luohancfd/FluidDynamicTools
Thermo_Chemical_Properties/Molecule_Properties/RawData/H2O.lua
1
5422
-- Collater: Rowan J. Gollan -- Date: 30-Mar-2009 H2O = {} H2O.M = { value = 18.01528e-3, units = 'kg/mol', description = 'molecular mass', reference = 'CEA2::thermo.inp' } H2O.atomic_constituents = {H=2,O=1} H2O.charge = 0 H2O.gamma = { value = 1.329, units = 'non-dimensional', description = 'ratio of specific heats at room temperature (= Cp/(Cp - R))', reference = 'using Cp evaluated from CEA2 coefficients at T=300.0 K' } H2O.viscosity = { model = "CEA", parameters = { {T_low=373.2, T_high=1073.2, A=0.50019557e+00, B=-0.69712796e+03, C=0.88163892e+05, D=0.30836508e+01}, {T_low=1073.2, T_high=5000.0, A=0.58988538e+00, B=-0.53769814e+03, C=0.54263513e+05, D=0.23386375e+01}, {T_low=5000.0, T_high=15000.0, A=0.64330087e+00, B=-0.95668913e+02, C=-0.37742283e+06, D=0.18125190e+01}, ref = 'from CEA2::trans.inp which cites Sengers and Watson (1986)' } } H2O.thermal_conductivity = { model = "CEA", parameters = { {T_low=373.2, T_high=1073.2, A=0.10966389e+01, B=-0.55513429e+03, C=0.10623408e+06, D=-0.24664550e+00}, {T_low=1073.2, T_high=5000.0, A=0.39367933e+00, B=-0.22524226e+04, C=0.61217458e+06, D=0.58011317e+01}, {T_low=5000.0, T_high=15000.0, A=-0.41858737e+00, B=-0.14096649e+05, C=0.19179190e+08, D=0.14345613e+02}, ref = 'from CEA2::trans.inp which cites Sengers and Watson (1986)' } } H2O.CEA_coeffs = { { T_low = 200.0, T_high = 1000.0, coeffs = { -3.947960830e+04, 5.755731020e+02, 9.317826530e-01, 7.222712860e-03, -7.342557370e-06, 4.955043490e-09, -1.336933246e-12, -3.303974310e+04, 1.724205775e+01 } }, { T_low = 1000.0, T_high = 6000.0, coeffs = { 1.034972096e+06, -2.412698562e+03, 4.646110780e+00, 2.291998307e-03, -6.836830480e-07, 9.426468930e-11, -4.822380530e-15, -1.384286509e+04, -7.978148510e+00 } }, ref="from CEA2::thermo.inp" } H2O.T_c = { value = 647.14, units = 'K', description = 'critical temperature', reference = 'Poling, B.E. et al. (2001). The Properties of Gases and Liquids. Section A, p.A.5' } H2O.p_c = { value = 220.64e+05, units = 'Pa', description = 'critical pressure', reference = 'Poling, B.E. et al. (2001). The Properties of Gases and Liquids. Section A, p.A.5' } -- Nonequilibrium data H2O.species_type = "nonlinear polar polyatomic" H2O.s_0 = { value = 0.0, units = 'J/kg-K', description = 'Dummy standard state entropy at 1 bar', reference = 'NA' } H2O.h_f = { value = -13423382.82, units = 'J/kg', description = 'Heat of formation', reference = 'from CEA2::thermo.inp' } H2O.Z = { value = 0, units = 'ND', description = 'Charge number', reference = 'NA' } H2O.I = { value = 0.0, units = 'J/kg', description = 'Dummy ground state ionization energy', reference = 'none' } H2O.electronic_levels = { n_levels = 1, ref = 'JANAF Tables 1985 (3rd edition)', -- ==================================================================================================================================== -- n Te re g dzero A0 B0 C0 sigma sigma_rot we[0] we[1] we[2] -- ==================================================================================================================================== ilev_0 = { 0.00, 0.9587, 1, 0.0, 27.8847, 14.5118, 9.2806, 2, 0, 3651.1, 1594.7, 3755.9 } -- ==================================================================================================================================== } -- Real gas data H2O.reference_state = { description = 'Reference temperature, internal energy and entropy', reference = 'None', note = 'Ideal gas reference when U=0, S=0 for saturated liquid at T0', units = 'K, J/kg, J/kg.K', T0 = 273.16, u0 = 2.3741e6, s0 = 6.6945e3, } H2O.Cp0_coeffs = { description = 'Coefficients for Cp0 polynomial of form T^(-2) to T^4.', reference = 'Polt, A and G Maurer (1992). Fluid Phase Equilibria, 73: 27-38.', note = 'Polt published these coefficients in kJ/(kg.K)', units = 'J/kg.K', -- Resulting unit when using these coefficients in Cp0 equation. T_low = 273.15, -- Range of validity. T_high = 923.91, G = {0.0, -- First element zero to align array indexes with equation coefficient numbers. 0.0, 1.94077e+03, -9.67660e-01, 3.08550e-03, -2.63140e-06, 8.60950e-10} } H2O.Bender_EOS_coeffs = { description = 'Coefficients for Bender equation of state', reference = 'Polt, A and G Maurer (1992). Fluid Phase Equilibria, 73: 27-38.', units = 'Pa', -- Resulting unit when usng these coefficients in p-rho-T equation. A = {0.0, -- First element zero to align array indexes with equation coefficient numbers. -1.3002084070e-07, 7.6533762730e-04, -9.0745855500e-01, -2.9984514510e+02, -1.6148196450e+04, 4.4890768230e-06, -6.3451282300e-03, 3.6353975160e+00, -8.1460085550e-06, 6.0971223530e-03, 1.0426877550e-05, -1.0516986730e-02, 2.7385365060e-03, -2.2453231530e+03, 2.1342907950e+06, -3.1262434070e+08, 4.9365926510e+03, -5.7492854100e+06, 1.1440257530e+09, 4.0e-6} -- Final element is "gamma", roughly 1/(rho_c^2) as used in the MBWR EOS. }
gpl-3.0
mattyx14/otxserver
data/monster/quests/cults_of_tibia/bosses/malkhar_deathbringer_stop.lua
2
2153
local mType = Game.createMonsterType("Malkhar Deathbringer Stop") local monster = {} monster.name = "Malkhar Deathbringer" monster.description = "Malkhar Deathbringer" monster.experience = 0 monster.outfit = { lookType = 134, lookHead = 19, lookBody = 94, lookLegs = 41, lookFeet = 57, lookAddons = 0, lookMount = 0 } monster.health = 15000 monster.maxHealth = 15000 monster.race = "blood" monster.corpse = 0 monster.speed = 0 monster.manaCost = 0 monster.changeTarget = { interval = 4000, chance = 20 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 95, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, } monster.loot = { } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -400}, {name ="combat", interval = 2000, chance = 40, type = COMBAT_DEATHDAMAGE, minDamage = 0, maxDamage = -500, range = 6, radius = 8, shootEffect = CONST_ANI_DEATH, effect = CONST_ME_MORTAREA, target = true} } monster.defenses = { defense = 50, armor = 35 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 100}, {type = COMBAT_ENERGYDAMAGE, percent = 100}, {type = COMBAT_EARTHDAMAGE, percent = 100}, {type = COMBAT_FIREDAMAGE, percent = 100}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 100}, {type = COMBAT_HOLYDAMAGE , percent = 100}, {type = COMBAT_DEATHDAMAGE , percent = 100} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
fo369/luci-1505
applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua
141
1031
--[[ smap_devinfo - SIP Device Information (c) 2009 Daniel Dickinson 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 $Id$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug) luci.controller.luci_diag.smap_common.action_links(m, true) return m
apache-2.0
luciouskami/YDWE
Development/Component/plugin/w3x2lni/script/gui/new/common_attribute.lua
3
3987
local gui = require 'yue.gui' local function BindValue(t, data, bind, name, func) if t.bind and t.bind[name] then bind[name] = data:bind(t.bind[name], function() func(bind[name]:get()) end) func(bind[name]:get()) else if t[name] ~= nil then func(t[name]) end end end local function GetHoverColor(color) if #color == 4 then return ('#%01X%01X%01X'):format( math.min(tonumber(color:sub(2, 2), 16) + 0x1, 0xF), math.min(tonumber(color:sub(3, 3), 16) + 0x1, 0xF), math.min(tonumber(color:sub(4, 4), 16) + 0x1, 0xF) ) elseif #color == 7 then return ('#%02X%02X%02X'):format( math.min(tonumber(color:sub(2, 3), 16) + 0x10, 0xFF), math.min(tonumber(color:sub(4, 5), 16) + 0x10, 0xFF), math.min(tonumber(color:sub(6, 7), 16) + 0x10, 0xFF) ) else return color end end local function label_color(self, t, data, bind) local color_hover = '' local color_normal = '' local event = false BindValue(t, data, bind, 'color', function (color) color_normal = color self:setbackgroundcolor(color_normal) end) BindValue(t, data, bind, 'color_hover', function (color) color_hover = color if not event then event = true function self:onmouseleave() self:setbackgroundcolor(color_normal) end function self:onmouseenter() self:setbackgroundcolor(color_hover) end end end) end local function button_color(self1, self2, t, data, bind) local color_hover = '' local color_normal = '' local has_hover = false local event = false BindValue(t, data, bind, 'color', function (color) color_normal = color if not has_hover then color_hover = GetHoverColor(color) end if not event then event = true function self1:onmouseleave() self2:setbackgroundcolor(color_normal) end function self1:onmouseenter() self2:setbackgroundcolor(color_hover) end end self2:setbackgroundcolor(color_normal) end) BindValue(t, data, bind, 'color_hover', function (color) color_hover = true color_hover = color if not event then event = true function self1:onmouseleave() self2:setbackgroundcolor(color_normal) end function self1:onmouseenter() self2:setbackgroundcolor(color_hover) end end end) end local function visible(self, t, data, bind) BindValue(t, data, bind, 'visible', function (value) self:setvisible(value) end) end local fontPool = {} local fontDefault = gui.app:getdefaultfont() local fontName = fontDefault:getname() local fontSize = fontDefault:getsize() local function font(self, t) if not t.font then return end local name = t.font.name or fontName local size = t.font.size or fontSize local weight = t.font.weight or 'normal' local style = t.font.style or 'normal' local key = ('%s|%d|%s|%s'):format(name, size, weight, style) local r = fontPool[key] if not r then r = gui.Font.create(name, size, weight, style) fontPool[key] = r end self:setfont(r) end local function event(self, t, data, name) if not t.on or not t.on[name] then return end local on = t.on[name] if type(on) == 'function' then self['on'..name] = function (self) on(t) end elseif type(on) == 'string' then self['on'..name] = function (self) data:execute(on, t) end end end return { label_color = label_color, button_color = button_color, visible = visible, font = font, event = event, }
gpl-3.0
jucor/lua-sci
fmin/_diffevol.lua
1
4988
-------------------------------------------------------------------------------- -- Differential evolution algorithm module. -- -- Copyright (C) 2011-2013 Stefano Peluchetti. All rights reserved. -- -- Features, documention and more: http://www.scilua.org . -- -- This file is part of the SciLua library, which is released under the MIT -- license: full text in file LICENSE.TXT in the library's root folder. -------------------------------------------------------------------------------- local xsys = require "xsys" local alg = require "sci.alg" local prng = require "sci.prng" local dist = require "sci.dist" -- TODO: Fix sci.fmin being reported in sci.fmax functions. local err, chk = xsys.handlers("sci.fmin") local min, max, abs, int, ceil = xsys.from(math, "min, max, abs, floor, ceil") -- PERF: better to just do a single check, condition is true with high -- PERF: probability and sampling uniform not expensive. local function distinctj(j, sd, r) local j1, j2, j3 = int(sd:sample(r)), int(sd:sample(r)), int(sd:sample(r)) while min(abs(j1 - j2), abs(j1 - j3), abs(j2 - j3), abs(j1 - j)) == 0 do j1 = int(sd:sample(r)) j2 = int(sd:sample(r)) j3 = int(sd:sample(r)) end return j1, j2, j3 end local function updatemin(xmin, fmin, xval, fval) if fval < fmin then return xval, fval else return xmin, fmin end end local boundf = { reflect = function(x, xl, xu) local b = max(min(x, xu), xl) -- Value of b must be xl if x < xl, xu if x > xu and x otherwise. return 2*b - x end, absorb = function(x, xl, xu) return max(min(x, xu), xl) end, no = function(x, xl, xu) return x end } -- TODO: Introduce integer distribution via uniform(vec). -- For integer from a to b use u(a, b+1) and floor it --> index of the vec! -- TODO: maxinitsample >= NP check. -- Options: -- (xval and fval) or (xlower and xupper and NP) -- stop -- o: rng -- o: F (0, 2] -- o: CR (0, 1] -- TODO: o: strategy "des" -- o: maxinitsample -- o: bounds "reflect", "absorb", "no" local function diffevol(f, o) chk((o.xval and o.fval) or (o.xlower and o.xupper and o.NP), "constraint", "(xval and fval) or (xlower and xupper and NP) required") chk(o.stop, "constraint", "stop required") local xl = o.xlower local xu = o.xupper local NP = o.NP or o.xval:nrow() local stop = o.stop() local rng = o.rng or prng.std() local F = o.F or 1 local CR = o.CR or 0.75 -- local evol = evolf[o.strategy or "des"] local maxin = o.maxinitsample or 100*NP -- At least 1% in support zone. local bound = boundf[o.bounds or "reflect"] local dim = o.xlower and #o.xlower or o.xval:ncol() chk(NP >= 4, "constraint", "NP:", NP, ", required >= 4") chk(0 < F and F <= 2, "constraint", "F:", F, ", required 0<F<=2") chk(0 < CR and CR <= 1, "constraint", "CR:", CR, ", required 0<CR<=1") chk(dim >= 1, "constraint", "dimension:", dim, ", required dimension>=1") local popd = dist.mduniform(o.xlower, o.xupper) local idxd = dist.uniform(1, NP + 1) local movd = dist.uniform(1, dim + 1) local u01d = dist.uniform(0, 1) local xval = alg.mat(NP, dim) local fval = alg.vec(NP) local fmin = math.huge local xmin local u = alg.mat(NP, dim) if o.xval then -- Population has priority. xval:set(o.xval) fval:set(o.fval) -- In case of no bounds infinite values are allowed. for j=1,NP do xmin, fmin = updatemin(xmin, fmin, xval:row(j), fval[j]) end else local iter = 0 for j=1,NP do repeat iter = iter + 1 chk(iter <= maxin, "error", "maxinitsample=", maxin, " exceeded") popd:sample(rng, xval:row(j)) fval[j] = f(xval:row(j)) until fval[j] < math.huge --print(xval:row(j), fval[j], fmin) xmin, fmin = updatemin(xmin, fmin, xval:row(j), fval[j]) end end while not stop(xmin, fmin, xval, fval) do for j=1,NP do -- Sample the three otehr distrinct indexes of population, local j1, j2, j3 = distinctj(j, idxd, rng) -- Mutation v, faster with expression than with vector! local v = xval:row(j1) + (xval:row(j2) - xval:row(j3))*F -- Crossover —> proposed u. local kmove = int(movd:sample(rng)) for k=1,dim do --> #unroll(10) -- Move if z == 0. local z = min(abs(k - kmove), ceil(u01d:sample(rng) - CR)) u[j][k] = (1 - z)*v[k] + z*xval[j][k] -- Bounds. u[j][k] = bound(u[j][k], xl[k], xu[k]) end end -- Selection. for j=1,NP do local fuj = f(u:row(j)) if fuj < fval[j] then -- It's an improvement --> select. fval[j] = fuj xval:row(j):set(u:row(j)) xmin, fmin = updatemin(xmin, fmin, xval:row(j), fuj) end end end return xmin:copy(), fmin, xval, fval end return { diffevol = diffevol }
mit
dbltnk/macro-prototype
PhaseManager.lua
1
8780
-- PhaseManager PhaseManager = Sprite:extend { class = "PhaseManager", props = {"gameId", "x", "y", "width", "height", "phase", "round", "round_start_time", "round_end_time", "next_xp_reset_time"}, sync_high = {"fakeHours", "fakeDays"}, phase = "init_needed", -- "init_needed", "warmup", "playing", "after" round = 0, owner = 0, gameId = 0, round_start_time = 0, next_xp_reset_time = 0, round_end_time = 0, highscore_displayed = false, width = 1, height = 1, fakeHours = 0, fakeDays = 0, onNew = function (self) self.x = -1000 self.y = -1000 self.visible = false self:mixin(GameObject) the.phaseManager = self the.app.view.layers.management:add(self) if self.phase == "warmup" and localconfig.spectator == false then switchToPlayer() end -- rejoin? if self:isLocal() == false and self.phase == "playing" then network.get("gameId", function(gameId) print("REJOIN", gameId) track("rejoin") local lastState = storage.load("game.json") if lastState and lastState.gameId == gameId then if the.player then if the.player.class == "Ghost" then the.player:die() the.player = Player:new(lastState.props) the.app.view:setFogEnabled(true) end end end end) end self:every(1, function() self:storePlayerState() end) self:every(config.treasureSpawnTimer, function() if self:isLocal() then self:spawnTreasure() end end) end, spawnTreasure = function (self) if self.treasure then self.treasure:die() end self.treasure = Treasure:new{x = math.random(100,900), y = math.random(100,900)} end, storePlayerState = function (self) if the.player and the.player.props and self.gameId and self.phase == "playing" then local lastState = { gameId = self.gameId, props = {} } local propsToStore = {"x", "y", "rotation", "image", "width", "height", "currentPain", "maxPain", "level", "anim_name", "anim_speed", "velocity", "alive", "incapacitated", "name", "weapon", "armor", "team", "deaths", "xp", } for _,v in pairs(propsToStore) do lastState.props[v] = the.player[v] end lastState.props["oid"] = the.player.oid storage.save("game.json", lastState) end end, forceNextPhase = function (self) if self.phase == "warmup" then self.round_start_time = network.time self.round_end_time = network.time + config.roundTime elseif self.phase == "playing" then self.round_end_time = network.time elseif self.phase == "after" then self.round_end_time = network.time - config.afterTime end end, onUpdateLocal = function (self) --~ print("onUpdateLocal", self.phase) if self.phase == "init_needed" then self:changePhaseToWarmup() track("phase_warmup") elseif self.phase == "warmup" then if network.time > self.round_start_time then self:changePhaseToPlaying() track("phase_playing") track("game_start") end elseif self.phase == "playing" then --~ if the.barrier and the.barrier.alive == false then --~ object_manager.send(self.oid, "barrier_died") --~ end if network.time > self.round_end_time then self:changePhaseToAfter() track("game_end", the.barrier and the.barrier.alive == true) --~ if the.barrier then --~ for team, points in pairs(the.barrier.teamscore) do --~ track("game_end_score_team", team, points) --~ end --~ for oid, points in pairs(the.barrier.highscore) do --~ local name = object_manager.get_field(oid, "name", "?") --~ local team = object_manager.get_field(oid, "team", "?") --~ track("game_end_score_player", oid, name, team, points) --~ end --~ end track("phase_after") end -- reset xp --~ if network.time > self.next_xp_reset_time then --~ self.next_xp_reset_time = self.next_xp_reset_time + config.xpCapTimer --~ object_manager.visit(function(oid,o) --~ if o.class == "Character" then --~ object_manager.send(oid, "reset_xp") --~ end --~ end) --~ end elseif self.phase == "after" then if network.time > self.round_end_time + config.afterTime then self:changePhaseToWarmup() track("phase_warmup") end end end, onUpdateBoth = function (self, elapsed) the.app.view.game_start_time = self.round_start_time if self.phase == "after" then --~ if self.highscore_displayed == false then --~ local text = "The players lost, here's how you did:" --~ the.barrier:showHighscore(text) --~ self.highscore_displayed = true --~ end end end, onDieBoth = function (self) the.app.view.layers.management:remove(self) end, formatSeconds = function (self, deltaTime) deltaTime = math.floor(deltaTime) if deltaTime < 0 then deltaTime = 0 end local minutes = math.floor(deltaTime / 60) local seconds = (deltaTime - minutes * 60) if seconds >= 10 then return minutes .. ":" .. seconds elseif seconds < 10 then return minutes .. ":0" .. seconds else return math.floor(deltaTime) .. "" end end, formatToFakeDays = function (self, deltaTime) if deltaTime < 0 then deltaTime = 0 end deltaTime = deltaTime - config.roundTime deltaTime = math.floor(deltaTime) * config.timecompression deltaTime = math.abs(deltaTime) local calcHours = math.floor(deltaTime / 5) self.fakeDays = math.floor(calcHours / 24) + 1 self.fakeHours = calcHours - ((self.fakeDays - 1) * 24) return "Day " .. self.fakeDays .. ", " .. self.fakeHours .. ":00" end, getTimeText = function (self) local addendum = "" --~ if the.player.class == "Ghost" or localconfig.spectator then addendum = "\n You are spectating. Wait for the next game to start to join." else addendum = "" end if self.phase == "init_needed" then return "init in progress..." elseif self.phase == "warmup" then local dt = self.round_start_time - network.time return "The game starts in " .. self:formatSeconds(dt) .. "." .. addendum elseif self.phase == "playing" then local dt = self.round_end_time - network.time return self:formatToFakeDays(dt) .. addendum .. "\n Mine fights: " .. config.ressStart .. " to " .. config.ressEnd elseif self.phase == "after" then local dt = (self.round_end_time + config.afterTime) - network.time return "Game over. Restart in " .. self:formatSeconds(dt) .. "." .. addendum end end, receiveBoth = function (self, message_name, ...) --~ print("############ receiveBoth", message_name) if message_name == "barrier_died" then --~ if self.highscore_displayed == false then --~ local text = "The players won, here's how you did:" --~ the.barrier:showHighscore(text) --~ self.highscore_displayed = true --~ end elseif message_name == "reset_game" then switchToGhost() if localconfig.spectator == false then switchToPlayer() end elseif message_name == "set_phase" then local phase_name = ... if the.barrier and phase_name == "warmup" then the.barrier:hideHighscore() end elseif message_name == "ghost_all_players" then switchToGhost() end end, receiveLocal = function (self, message_name, ...) --~ print("############ receiveLocal", message_name) if message_name == "reset_game" then -- destroy non player stuff local l = object_manager.find_where(function(oid, o) return o.class and NetworkSyncedObjects[o.class] end) for _,o in pairs(l) do o:die() end -- recreate map objects local mapFile = '/assets/map/worldmap.lua' the.app.view:loadMap(mapFile, function (o) return o.name and NetworkSyncedObjects[o.name] end) elseif message_name == "force_next_phase" then self:forceNextPhase() end end, resetGame = function (self) object_manager.send(self.oid, "reset_game") end, ghostAllPlayers = function (self) object_manager.send(self.oid, "ghost_all_players") end, changePhaseToWarmup = function (self) self.round_start_time = network.time + config.warmupTime self.round_end_time = self.round_start_time + config.roundTime self.highscore_displayed = false self.phase = "warmup" object_manager.send(self.oid, "set_phase", self.phase) self.round = self.round + 1 print("changePhaseToWarmup", self.phase, self.round) --~ self:resetGame() end, changePhaseToPlaying = function (self) self.phase = "playing" self.next_xp_reset_time = network.time + config.xpCapTimer object_manager.send(self.oid, "set_phase", self.phase) --~ self:resetGame() print("changePhaseToPlaying", self.phase, self.round) self.gameId = tonumber(math.random(1,1000000)) network.set("gameId", self.gameId) end, changePhaseToAfter = function (self) self.phase = "after" object_manager.send(self.oid, "set_phase", self.phase) print("changePhaseToAfter", self.phase, self.round) end, }
mit
Germanunkol/GridCars
network/client.lua
2
6835
local BASE = (...):match("(.-)[^%.]+$") local socket = require("socket") local User = require( BASE .. "user" ) local CMD = require( BASE .. "commands" ) local utility = require( BASE .. "utility" ) local Client = {} Client.__index = Client local userList = {} local numberOfUsers = 0 local partMessage = "" local messageLength = nil function Client:new( address, port, playerName, authMsg ) local o = {} setmetatable( o, self ) authMsg = authMsg or "" print("[NET] Initialising Client...") o.conn = socket.tcp() o.conn:settimeout(5) local ok, msg = o.conn:connect( address, port ) --ok, o.conn = pcall(o.conn.connect, o.conn, address, port) if ok and o.conn then o.conn:settimeout(0) self.send( o, CMD.AUTHORIZATION_REQUREST, authMsg ) print("[NET] -> Client connected", o.conn) else o.conn = nil return nil end o.callbacks = { authorized = nil, received = nil, connected = nil, disconnected = nil, otherUserConnected = nil, otherUserDisconnected = nil, customDataChanged = nil, } userList = {} partMessage = "" o.clientID = nil o.playerName = playerName numberOfUsers = 0 -- Filled if user is kicked: o.kickMsg = "" return o end function Client:update( dt ) if self.conn then local data, msg, partOfLine = self.conn:receive( 9999 ) if data then partMessage = partMessage .. data else if msg == "timeout" then if #partOfLine > 0 then partMessage = partMessage .. partOfLine end elseif msg == "closed" then --self.conn:shutdown() print("[NET] Disconnected.") if self.callbacks.disconnected then self.callbacks.disconnected( self.kickMsg ) end self.conn = nil return false else print("[NET] Err Received:", msg, data) end end if not messageLength then if #partMessage >= 1 then local headerLength = nil messageLength, headerLength = utility:headerToLength( partMessage:sub(1,5) ) if messageLength and headerLength then partMessage = partMessage:sub(headerLength + 1, #partMessage ) end end end -- if I already know how long the message should be: if messageLength then if #partMessage >= messageLength then -- Get actual message: local currentMsg = partMessage:sub(1, messageLength) -- Remember rest of already received messages: partMessage = partMessage:sub( messageLength + 1, #partMessage ) command, content = string.match( currentMsg, "(.)(.*)") command = string.byte( command ) self:received( command, content ) messageLength = nil end end --[[if data then if #partMessage > 0 then data = partMessage .. data partMessage = "" end -- First letter stands for the command: command, content = string.match(data, "(.)(.*)") command = string.byte( command ) self:received( command, content ) else if msg == "timeout" then -- only part of the message could be received if #partOfLine > 0 then partMessage = partMessage .. partOfLine end elseif msg == "closed" then --self.conn:shutdown() print("[NET] Disconnected.") if self.callbacks.disconnected then self.callbacks.disconnected( self.kickMsg ) end self.conn = nil return false else print("[NET] Err Received:", msg, data) end end]] return true else return false end end function Client:received( command, msg ) if command == CMD.PING then -- Respond to ping: self:send( CMD.PONG, "" ) elseif command == CMD.USER_PINGTIME then local id, ping = msg:match("(.-)|(.*)") id = tonumber(id) if userList[id] then userList[id].ping.pingReturnTime = tonumber(ping) end elseif command == CMD.NEW_PLAYER then local id, playerName = string.match( msg, "(.*)|(.*)" ) id = tonumber(id) local user = User:new( nil, playerName, id ) userList[id] = user numberOfUsers = numberOfUsers + 1 if self.playerName ~= playerName then if self.callbacks.otherUserConnected then self.callbacks.otherUserConnected( user ) end end elseif command == CMD.PLAYER_LEFT then local id = tonumber(msg) local u = userList[id] userList[id] = nil numberOfUsers = numberOfUsers - 1 if self.callbacks.otherUserDisconnected then self.callbacks.otherUserDisconnected( u ) end elseif command == CMD.AUTHORIZED then local authed, reason = string.match( msg, "(.*)|(.*)" ) if authed == "true" then self.authorized = true print( "[NET] Connection authorized by server." ) -- When authorized, send player name: self:send( CMD.PLAYERNAME, self.playerName ) else print( "[NET] Not authorized to join server. Reason: " .. reason ) end if self.callbacks.authorized then self.callbacks.authorized( self.authorized, reason ) end elseif command == CMD.PLAYERNAME then local id, playerName = string.match( msg, "(.*)|(.*)" ) self.playerName = playerName self.clientID = tonumber(id) -- At this point I am fully connected! if self.callbacks.connected then self.callbacks.connected() end --self.conn:settimeout(5) elseif command == CMD.USER_VALUE then local id, keyType, key, valueType, value = string.match( msg, "(.*)|(.*)|(.*)|(.*)|(.*)" ) key = stringToType( key, keyType ) value = stringToType( value, valueType ) id = tonumber( id ) userList[id].customData[key] = value if self.callbacks.customDataChanged then self.callback.customDataChanged( user, value, key ) end elseif command == CMD.KICKED then self.kickMsg = msg print("[NET] Kicked from server: " .. msg ) elseif self.callbacks.received then self.callbacks.received( command, msg ) end end function Client:send( command, msg ) local fullMsg = string.char(command) .. (msg or "") --.. "\n" local len = #fullMsg assert( len < 256^4, "Length of packet must not be larger than 4GB" ) fullMsg = utility:lengthToHeader( len ) .. fullMsg local result, err, num = self.conn:send( fullMsg ) while err == "timeout" do fullMsg = fullMsg:sub( num+1, #fullMsg ) result, err, num = self.conn:send( fullMsg ) end return end function Client:getUsers() return userList end function Client:getNumUsers() return numberOfUsers end function Client:close() if self.conn then --self.conn:shutdown() self.conn:close() print( "[NET] Closed.") end end function Client:setUserValue( key, value ) local keyType = type( key ) local valueType = type( value ) self:send( CMD.USER_VALUE, keyType .. "|" .. tostring(key) .. "|" .. valueType .. "|" .. tostring(value) ) end function Client:getID() return self.clientID end function Client:getUserValue( key ) if not self.clientID then return nil end local u = userList[self.clientID] if u then return u.customData[key] end return nil end function Client:getUserPing( id ) if users[id] then return users[id].ping.pingReturnTime end end return Client
mit
tenplus1/ethereal
food.lua
1
5628
local S = ethereal.intllib -- Banana (Heals one heart when eaten) minetest.register_node("ethereal:banana", { description = S("Banana"), drawtype = "torchlike", tiles = {"banana_single.png"}, inventory_image = "banana_single.png", wield_image = "banana_single.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.31, -0.5, -0.31, 0.31, 0.5, 0.31} }, groups = { food_banana = 1, fleshy = 3, dig_immediate = 3, flammable = 2, leafdecay = 1, leafdecay_drop = 1 }, drop = "ethereal:banana", on_use = minetest.item_eat(2), sounds = default.node_sound_leaves_defaults(), after_place_node = function(pos, placer) if placer:is_player() then minetest.set_node(pos, {name = "ethereal:banana", param2 = 1}) end end, }) -- Banana Dough minetest.register_craftitem("ethereal:banana_dough", { description = S("Banana Dough"), inventory_image = "banana_dough.png", }) minetest.register_craft({ type = "shapeless", output = "ethereal:banana_dough", recipe = {"group:food_flour", "group:food_banana"} }) minetest.register_craft({ type = "cooking", cooktime = 14, output = "ethereal:banana_bread", recipe = "ethereal:banana_dough" }) -- Orange (Heals 2 hearts when eaten) minetest.register_node("ethereal:orange", { description = S("Orange"), drawtype = "plantlike", tiles = {"farming_orange.png"}, inventory_image = "farming_orange.png", wield_image = "farming_orange.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.27, -0.37, -0.27, 0.27, 0.44, 0.27} }, groups = { food_orange = 1, fleshy = 3, dig_immediate = 3, flammable = 2, leafdecay = 3, leafdecay_drop = 1 }, drop = "ethereal:orange", on_use = minetest.item_eat(4), sounds = default.node_sound_leaves_defaults(), after_place_node = function(pos, placer) if placer:is_player() then minetest.set_node(pos, {name = "ethereal:orange", param2 = 1}) end end, }) -- Pine Nuts (Heals 1/2 heart when eaten) minetest.register_craftitem("ethereal:pine_nuts", { description = S("Pine Nuts"), inventory_image = "pine_nuts.png", wield_image = "pine_nuts.png", groups = {food_pine_nuts = 1, flammable = 2}, on_use = minetest.item_eat(1), }) -- Banana Loaf (Heals 3 hearts when eaten) minetest.register_craftitem("ethereal:banana_bread", { description = S("Banana Loaf"), inventory_image = "banana_bread.png", wield_image = "banana_bread.png", groups = {food_bread = 1, flammable = 3}, on_use = minetest.item_eat(6), }) -- Coconut (Gives 4 coconut slices, each heal 1/2 heart) minetest.register_node("ethereal:coconut", { description = S("Coconut"), drawtype = "plantlike", walkable = false, paramtype = "light", sunlight_propagates = true, tiles = {"moretrees_coconut.png"}, inventory_image = "moretrees_coconut.png", wield_image = "moretrees_coconut.png", selection_box = { type = "fixed", fixed = {-0.31, -0.43, -0.31, 0.31, 0.44, 0.31} }, groups = { food_coconut = 1, snappy = 1, oddly_breakable_by_hand = 1, cracky = 1, choppy = 1, flammable = 1, leafdecay = 3, leafdecay_drop = 1 }, drop = "ethereal:coconut_slice 4", sounds = default.node_sound_wood_defaults(), }) -- Coconut Slice (Heals half heart when eaten) minetest.register_craftitem("ethereal:coconut_slice", { description = S("Coconut Slice"), inventory_image = "moretrees_coconut_slice.png", wield_image = "moretrees_coconut_slice.png", groups = {food_coconut_slice = 1, flammable = 1}, on_use = minetest.item_eat(1), }) -- Golden Apple (Found on Healing Tree, heals all 10 hearts) minetest.register_node("ethereal:golden_apple", { description = S("Golden Apple"), drawtype = "plantlike", tiles = {"default_apple_gold.png"}, inventory_image = "default_apple_gold.png", wield_image = "default_apple_gold.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.2, -0.37, -0.2, 0.2, 0.31, 0.2} }, groups = { fleshy = 3, dig_immediate = 3, leafdecay = 3,leafdecay_drop = 1 }, drop = "ethereal:golden_apple", on_use = minetest.item_eat(20), sounds = default.node_sound_leaves_defaults(), after_place_node = function(pos, placer, itemstack) if placer:is_player() then minetest.set_node(pos, {name = "ethereal:golden_apple", param2 = 1}) end end, }) -- Hearty Stew (Heals 5 hearts - thanks to ZonerDarkRevention for his DokuCraft DeviantArt bowl texture) minetest.register_craftitem("ethereal:hearty_stew", { description = S("Hearty Stew"), inventory_image = "hearty_stew.png", wield_image = "hearty_stew.png", on_use = minetest.item_eat(10, "ethereal:bowl"), }) minetest.register_craft({ output = "ethereal:hearty_stew", recipe = { {"group:food_onion","flowers:mushroom_brown", "group:food_tuber"}, {"","flowers:mushroom_brown", ""}, {"","group:food_bowl", ""}, } }) -- Extra recipe for hearty stew if farming and farming.mod and farming.mod == "redo" then minetest.register_craft({ output = "ethereal:hearty_stew", recipe = { {"group:food_onion","flowers:mushroom_brown", "group:food_beans"}, {"","flowers:mushroom_brown", ""}, {"","group:food_bowl", ""}, } }) end -- Bucket of Cactus Pulp minetest.register_craftitem("ethereal:bucket_cactus", { description = S("Bucket of Cactus Pulp"), inventory_image = "bucket_cactus.png", wield_image = "bucket_cactus.png", stack_max = 1, on_use = minetest.item_eat(2, "bucket:bucket_empty"), }) minetest.register_craft({ output = "ethereal:bucket_cactus", recipe = { {"bucket:bucket_empty","default:cactus"}, } })
mit
clementfarabet/nn
Parallel.lua
39
3780
local Parallel, parent = torch.class('nn.Parallel', 'nn.Container') function Parallel:__init(inputDimension,outputDimension) parent.__init(self) self.modules = {} self.size = torch.LongStorage() self.inputDimension = inputDimension self.outputDimension = outputDimension end function Parallel:updateOutput(input) local nModule=input:size(self.inputDimension) local outputs = {} for i=1,nModule do local currentInput = input:select(self.inputDimension,i) local currentOutput = self.modules[i]:updateOutput(currentInput) table.insert(outputs, currentOutput) local outputSize = currentOutput:size(self.outputDimension) if i == 1 then self.size:resize(currentOutput:dim()):copy(currentOutput:size()) else self.size[self.outputDimension] = self.size[self.outputDimension] + outputSize end end self.output:resize(self.size) local offset = 1 for i=1,nModule do local currentOutput = outputs[i] local outputSize = currentOutput:size(self.outputDimension) self.output:narrow(self.outputDimension, offset, outputSize):copy(currentOutput) offset = offset + currentOutput:size(self.outputDimension) end return self.output end function Parallel:updateGradInput(input, gradOutput) local nModule=input:size(self.inputDimension) self.gradInput:resizeAs(input) local offset = 1 for i=1,nModule do local module=self.modules[i] local currentInput = input:select(self.inputDimension,i) local currentOutput = module.output local outputSize = currentOutput:size(self.outputDimension) local currentGradOutput = gradOutput:narrow(self.outputDimension, offset, outputSize) local currentGradInput = module:updateGradInput(currentInput, currentGradOutput) self.gradInput:select(self.inputDimension,i):copy(currentGradInput) offset = offset + outputSize end return self.gradInput end function Parallel:accGradParameters(input, gradOutput, scale) local nModule=input:size(self.inputDimension) local offset = 1 for i=1,nModule do local module = self.modules[i] local currentOutput = module.output local outputSize = currentOutput:size(self.outputDimension) module:accGradParameters( input:select(self.inputDimension,i), gradOutput:narrow(self.outputDimension, offset,outputSize), scale ) offset = offset + outputSize end end function Parallel:accUpdateGradParameters(input, gradOutput, lr) local nModule=input:size(self.inputDimension) local offset = 1 for i=1,nModule do local module = self.modules[i]; local currentOutput = module.output module:accUpdateGradParameters( input:select(self.inputDimension,i), gradOutput:narrow(self.outputDimension, offset, currentOutput:size(self.outputDimension)), lr) offset = offset + currentOutput:size(self.outputDimension) end end function Parallel:__tostring__() local tab = ' ' local line = '\n' local next = ' |`-> ' local ext = ' | ' local extlast = ' ' local last = ' ... -> ' local str = torch.type(self) str = str .. ' {' .. line .. tab .. 'input' for i=1,#self.modules do if i == self.modules then str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast) else str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext) end end str = str .. line .. tab .. last .. 'output' str = str .. line .. '}' return str end
bsd-3-clause
CarabusX/Zero-K
effects/sumo.lua
7
3226
return { ["sumosmoke"] = { muzzlesmoke = { air = true, class = [[CSimpleParticleSystem]], count = 6, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.20 0.11 0.0 0.3 0.20 0.11 0.0 0.03 0 0 0 0.01]], directional = false, emitrot = 60, emitrotspread = 0, emitvector = [[0, -1, 0]], gravity = [[0, 0.3, 0]], numparticles = 1, particlelife = 8, particlelifespread = 10, particlesize = [[3 i-0.4]], particlesizespread = 1, particlespeed = [[4 i-1]], particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 0.8, sizemod = 1.0, texture = [[smokesmall]], }, }, }, ["sumoland"] = { dustcloud = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.7, colormap = [[0.52 0.41 0.21 1 0 0 0 0.01]], directional = false, emitrot = 90, emitrotspread = 10, emitvector = [[0, 1, 0]], gravity = [[0, 0.03, 0]], numparticles = 30, particlelife = 50, particlelifespread = 0, particlesize = 1, particlesizespread = 3, particlespeed = 6, particlespeedspread = 12, pos = [[0, -10, 0]], sizegrowth = 1.7, sizemod = 1, texture = [[smokesmall]], }, }, dirt = { air = true, class = [[CSimpleParticleSystem]], count = 30, ground = true, water = true, properties = { airdrag = 0.995, alwaysvisible = true, colormap = [[0.22 0.18 0.15 1 0.22 0.18 0.15 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 70, emitvector = [[0, 1, 0]], gravity = [[0, -0.1, 0]], numparticles = 8, particlelife = 190, particlelifespread = 0, particlesize = [[1 r10]], particlesizespread = 0, particlespeed = 3, particlespeedspread = 4, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[debris2]], }, }, fanny = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 30, explosiongenerator = [[custom:FANNY]], pos = [[0, 0, 0]], }, }, }, }
gpl-2.0
CarabusX/Zero-K
LuaUI/Widgets/cmd_customformations2.lua
4
42934
function widget:GetInfo() return { name = "CustomFormations2", desc = "Dragged commands follow the wobbly line instead of treating it as a line segment", author = "Niobium, modified by Skasi", -- Based on 'Custom Formations' by jK and gunblob version = "v3.4", -- With modified dot drawing from v4.3 date = "Mar, 2010", license = "GNU GPL, v2 or later", layer = 1000000, enabled = true, handler = true, } end VFS.Include("LuaRules/Configs/customcmds.h.lua") -------------------------------------------------------------------------------- -- Epic Menu Options -------------------------------------------------------------------------------- local overrideCmdSingleUnit = { [CMD.GUARD] = true, } options_path = 'Settings/Interface/Command Visibility'--/Formations' options_order = { 'drawmode_v2', 'linewidth', 'dotsize', 'overrideGuard' } options = { drawmode_v2 = { name = 'Draw mode', -- desc is not supported here :( -- desc = 'Change the formation display. Formations are drawn by moving the mouse while the mouse button is pressed. Supported commands are Move, Fight, Patrol, Manual attacks, Jump and with the ALT key held down Attack, Set target and Unload.' -- (new) players might not even know about custom formations, so ultimately this should probably be displayed above these options type = 'radioButton', value = 'both', items={ {key='lines', name='Lines only', desc='Draw stippled lines along the drawn formation'}, {key='dots', name='Dots only', desc='Draw dots at command locations'}, {key='both', name='Draw both', desc='Draw lines and dots'}, }, noHotkey = true, }, linewidth = { name = 'Width of lines', type = 'number', value = 2, min = 1, max = 2, step=1, -- For some reason drawing lines fails for numbers higher than 2. }, dotsize = { name = 'Size of dots', type = 'number', value = 1, min = 0.5, max = 2, step=0.1, }, overrideGuard = { name = "Override Guard on single unit", desc = "When enabled, dragging a short line on a unit will give move commands rather than a guard command.", type = "bool", value = true, path = 'Settings/Interface/Commands', OnChange = function (self) if self.value then overrideCmdSingleUnit = { [CMD.GUARD] = true, } else overrideCmdSingleUnit = {} end end, }, } -------------------------------------------------------------------------------- -- User Configurable Constants -------------------------------------------------------------------------------- -- Minimum spacing between commands (Squared) when drawing a path for a single unit, must be >16*16 (Or orders overlap and cancel) local minPathSpacingSq = 50 * 50 -- Minimum line length to cause formation move instead of single-click-style order local minFormationLength = 20 -- How long should algorithms take. (~0.1 gives visible stutter, default: 0.05) local maxHngTime = 0.05 -- Desired maximum time for hungarian algorithm local maxNoXTime = 0.05 -- Strict maximum time for backup algorithm local defaultHungarianUnits = 20 -- Need a baseline to start from when no config data saved local minHungarianUnits = 10 -- If we kept reducing maxUnits it can get to a point where it can never increase, so we enforce minimums on the algorithms. local unitIncreaseThresh = 0.85 -- We only increase maxUnits if the units are great enough for time to be meaningful local SMALL_FORMATION_THRESHOLD = 8 -- For guard override. -- Alpha loss per second after releasing mouse local lineFadeRate = 2.0 -- What commands are eligible for custom formations local formationCmds = { [CMD.MOVE] = true, [CMD_RAW_MOVE] = true, [CMD.FIGHT] = true, [CMD.ATTACK] = true, [CMD.MANUALFIRE] = true, [CMD.PATROL] = true, [CMD.UNLOAD_UNIT] = true, [CMD_JUMP] = true, -- jump [CMD_PLACE_BEACON] = true, -- teleport beacon [CMD_UNIT_SET_TARGET] = true, -- settarget [CMD_UNIT_SET_TARGET_CIRCLE] = true, -- settarget } -- What commands require alt to be held (Must also appear in formationCmds) local requiresAlt = { [CMD.ATTACK] = true, [CMD.MANUALFIRE] = true, [CMD.UNLOAD_UNIT] = true, [CMD_UNIT_SET_TARGET] = true, -- settarget [CMD_UNIT_SET_TARGET_CIRCLE] = true, -- settarget } -- Context-based default commands that can be overridden (i.e. guard when mouseover unit) -- If the mouse remains on the same target for both Press/Release then the formation is ignored and original command is issued. -- Normal logic will follow after override, i.e. must be a formationCmd to get formation, alt must be held if requiresAlt, etc. local overrideCmds = { [CMD.GUARD] = CMD_RAW_MOVE, [CMD_WAIT_AT_BEACON] = CMD_RAW_MOVE, } -- What commands are issued at a position or unit/feature ID (Only used by GetUnitPosition) local positionCmds = { [CMD.MOVE] = true, [CMD_RAW_MOVE] = true, [CMD_RAW_BUILD] = true, [CMD.ATTACK] = true, [CMD.RECLAIM] = true, [CMD.RESTORE] = true, [CMD.PATROL] = true, [CMD.CAPTURE] = true, [CMD.FIGHT] = true, [CMD.MANUALFIRE] = true, [CMD_JUMP] = true, [CMD.RESURRECT] = true, [CMD.UNLOAD_UNIT] = true, [CMD.UNLOAD_UNITS] = true,[CMD.LOAD_UNITS] = true, [CMD.GUARD] = true, [CMD.AREA_ATTACK] = true, } -------------------------------------------------------------------------------- -- Globals -------------------------------------------------------------------------------- local maxHungarianUnits = defaultHungarianUnits -- Also set when loading config local fNodes = {} -- Formation nodes, filled as we draw local fDists = {} -- fDists[i] = distance from node 1 to node i local totaldxy = 0 -- Measure of distance mouse has moved, used to unjag lines drawn in minimap local lineLength = 0 -- Total length of the line local dimmCmd = nil -- The dimming command (Used for color) local dimmNodes = {} -- The current nodes of dimming line local dimmAlpha = 0 -- The current alpha of dimming line local pathCandidate = false -- True if we should start a path on mouse move local draggingPath = false -- True if we are dragging a path for unit(s) to follow local lastPathPos = nil -- The last point added to the path, used for min-distance check local overriddenCmd = nil -- The command we ignored in favor of move local overriddenTarget = nil -- The target (for params) we ignored local usingCmd = nil -- The command to execute across the line local usingRMB = false -- If the command is the default it uses right click, otherwise it is active and uses left click local inMinimap = false -- Is the line being drawn in the minimap local endShift = false -- True to reset command when shift is released local MiniMapFullProxy = (Spring.GetConfigInt("MiniMapFullProxy", 0) == 1) -------------------------------------------------------------------------------- -- Speedups -------------------------------------------------------------------------------- local GL_LINE_STRIP = GL.LINE_STRIP local glVertex = gl.Vertex local glLineStipple = gl.LineStipple local glLineWidth = gl.LineWidth local glColor = gl.Color local glBeginEnd = gl.BeginEnd local glPushMatrix = gl.PushMatrix local glPopMatrix = gl.PopMatrix local glScale = gl.Scale local glTranslate = gl.Translate local glLoadIdentity = gl.LoadIdentity local spGetActiveCommand = Spring.GetActiveCommand local spSetActiveCommand = Spring.SetActiveCommand local spGetDefaultCommand = Spring.GetDefaultCommand local spFindUnitCmdDesc = Spring.FindUnitCmdDesc local spGetModKeyState = Spring.GetModKeyState local spGetInvertQueueKey = Spring.GetInvertQueueKey local spIsAboveMiniMap = Spring.IsAboveMiniMap local spGetSelectedUnitsCount = Spring.GetSelectedUnitsCount local spGetSelectedUnits = Spring.GetSelectedUnits local spGetUnitDefID = Spring.GetUnitDefID local spGiveOrder = Spring.GiveOrder local spGetUnitIsTransporting = Spring.GetUnitIsTransporting local spGetCommandQueue = Spring.GetCommandQueue local spGetUnitPosition = Spring.GetUnitPosition local spGetGroundHeight = Spring.GetGroundHeight local spGetFeaturePosition = Spring.GetFeaturePosition local spGiveOrderToUnit = Spring.GiveOrderToUnit local spGetUnitHeight = Spring.GetUnitHeight local spGetCameraPosition = Spring.GetCameraPosition local spGetViewGeometry = Spring.GetViewGeometry local spTraceScreenRay = Spring.TraceScreenRay local mapSizeX, mapSizeZ = Game.mapSizeX, Game.mapSizeZ local maxUnits = Game.maxUnits local osclock = os.clock local tsort = table.sort local floor = math.floor local ceil = math.ceil local sqrt = math.sqrt local sin = math.sin local cos = math.cos local max = math.max local huge = math.huge local pi2 = 2*math.pi local CMD_INSERT = CMD.INSERT local CMD_MOVE = CMD.MOVE local CMD_ATTACK = CMD.ATTACK local CMD_UNLOADUNIT = CMD.UNLOAD_UNIT local CMD_UNLOADUNITS = CMD.UNLOAD_UNITS local CMD_SET_WANTED_MAX_SPEED = CMD.SET_WANTED_MAX_SPEED local CMD_OPT_ALT = CMD.OPT_ALT local CMD_OPT_CTRL = CMD.OPT_CTRL local CMD_OPT_META = CMD.OPT_META local CMD_OPT_SHIFT = CMD.OPT_SHIFT local CMD_OPT_RIGHT = CMD.OPT_RIGHT local REMOVED_SET_WANTED_MAX_SPEED = not CMD.SET_WANTED_MAX_SPEED local keyShift = 304 local filledCircleOutFading = {} --Table of display lists keyed by cmdID -------------------------------------------------------------------------------- -- Helper Functions -------------------------------------------------------------------------------- local function CulledTraceScreenRay(mx, my, coords, minimap) local targetType, params = spTraceScreenRay(mx, my, coords, minimap) if targetType == "ground" then params[4], params[5], params[6] = nil, nil, nil return targetType, params end return targetType, params end local function GetModKeys() local alt, ctrl, meta, shift = spGetModKeyState() if spGetInvertQueueKey() then -- Shift inversion shift = not shift end return alt, ctrl, meta, shift end local function GetUnitFinalPosition(uID) local ux, uy, uz = spGetUnitPosition(uID) local cmds = spGetCommandQueue(uID, -1) if not cmds then return 0, 0, 0 end for i = #cmds, 1, -1 do local cmd = cmds[i] if (cmd.id < 0) or positionCmds[cmd.id] then local params = cmd.params if #params >= 3 then return params[1], params[2], params[3] else if #params == 1 then local pID = params[1] local px, py, pz if pID > maxUnits then px, py, pz = spGetFeaturePosition(pID - maxUnits) else px, py, pz = spGetUnitPosition(pID) end if px then return px, py, pz end end end end end return ux, uy, uz end local function SetColor(cmdID, alpha) if cmdID == CMD_MOVE or cmdID == CMD_RAW_MOVE then glColor(0.5, 1.0, 0.5, alpha) -- Green elseif cmdID == CMD_ATTACK then glColor(1.0, 0.2, 0.2, alpha) -- Red elseif cmdID == CMD.MANUALFIRE then glColor(1.0, 1.0, 1.0, alpha) -- White elseif cmdID == CMD_UNLOADUNIT then glColor(1.0, 1.0, 0.0, alpha) -- Yellow elseif cmdID == CMD_UNIT_SET_TARGET then glColor(1.0, 0.75, 0.0, alpha) -- Orange elseif cmdID == CMD_UNIT_SET_TARGET_CIRCLE then glColor(1.0, 0.75, 0.0, alpha) -- Orange elseif cmdID == CMD_JUMP then glColor(0.2, 1.0, 0.2, alpha) -- Deeper Green else glColor(0.5, 0.5, 1.0, alpha) -- Blue end end local function CanUnitExecute(uID, cmdID) if cmdID == CMD_UNLOADUNIT then local transporting = spGetUnitIsTransporting(uID) return (transporting and #transporting > 0) end return (spFindUnitCmdDesc(uID, cmdID) ~= nil) end local function GetExecutingUnits(cmdID) local units = {} local selUnits = spGetSelectedUnits() for i = 1, #selUnits do local uID = selUnits[i] if CanUnitExecute(uID, cmdID) then units[#units + 1] = uID end end return units end local function AddFNode(pos) local px, pz = pos[1], pos[3] if px < 0 or pz < 0 or px > mapSizeX or pz > mapSizeZ then return false end local n = #fNodes if n == 0 then fNodes[1] = pos fDists[1] = 0 else local prevNode = fNodes[n] local dx, dz = px - prevNode[1], pz - prevNode[3] local distSq = dx*dx + dz*dz if distSq == 0.0 then -- Don't add if duplicate return false end local dis = sqrt(distSq) fNodes[n + 1] = pos fDists[n + 1] = fDists[n] + dis lineLength = lineLength + dis end totaldxy = 0 return true end local function HasWaterWeapon(UnitDefID) local haswaterweapon = false local numweapons = #(UnitDefs[UnitDefID]["weapons"]) for j=1, numweapons do local weapondefid = UnitDefs[UnitDefID]["weapons"][j]["weaponDef"] local iswaterweapon = WeaponDefs[weapondefid]["waterWeapon"] if iswaterweapon then haswaterweapon=true end end return haswaterweapon end local function GetInterpNodes(mUnits) local number = #mUnits local spacing = fDists[#fNodes] / (#mUnits - 1) local haswaterweapon = {} for i=1, number do local UnitDefID = spGetUnitDefID(mUnits[i]) haswaterweapon[i] = HasWaterWeapon(UnitDefID) end --result of this and code below is that the height of the aimpoint for a unit [i] will be: --(a) on GetGroundHeight(units aimed position), if the unit has a waterweapon --(b) on whichever is highest out of water surface (=0) and GetGroundHeight(units aimed position), if the unit does not have water weapon. --in BA this must match the behaviour of prevent_range_hax or commands will get modified. local interpNodes = {} local sPos = fNodes[1] local sX = sPos[1] local sZ = sPos[3] local sDist = 0 local eIdx = 2 local ePos = fNodes[2] local eX = ePos[1] local eZ = ePos[3] local eDist = fDists[2] local sY = math.max(0, spGetGroundHeight(sX,sZ)) interpNodes[1] = {sX, sY, sZ} for n = 1, number - 2 do local reqDist = n * spacing while (reqDist > eDist) do sX = eX sZ = eZ sDist = eDist eIdx = eIdx + 1 ePos = fNodes[eIdx] eX = ePos[1] eZ = ePos[3] eDist = fDists[eIdx] end local nFrac = (reqDist - sDist) / (eDist - sDist) local nX = sX * (1 - nFrac) + eX * nFrac local nZ = sZ * (1 - nFrac) + eZ * nFrac local nY = math.max(0, spGetGroundHeight(nX, nZ)) interpNodes[n + 1] = {nX, nY, nZ} end ePos = fNodes[#fNodes] eX = ePos[1] eZ = ePos[3] local eY = math.max(0, spGetGroundHeight(eX, eZ)) interpNodes[number] = {eX, eY, eZ} --DEBUG for i=1,number do Spring.Echo(interpNodes[i]) end return interpNodes end local function GetCmdOpts(alt, ctrl, meta, shift, right) local opts = { alt=alt, ctrl=ctrl, meta=meta, shift=shift, right=right } local coded = 0 if alt then coded = coded + CMD_OPT_ALT end if ctrl then coded = coded + CMD_OPT_CTRL end if meta then coded = coded + CMD_OPT_META end if shift then coded = coded + CMD_OPT_SHIFT end if right then coded = coded + CMD_OPT_RIGHT end opts.coded = coded return opts end local function GiveNotifyingOrder(cmdID, cmdParams, cmdOpts) if widgetHandler:CommandNotify(cmdID, cmdParams, cmdOpts) then return end spGiveOrder(cmdID, cmdParams, cmdOpts.coded) end local function GiveNonNotifyingOrder(cmdID, cmdParams, cmdOpts) spGiveOrder(cmdID, cmdParams, cmdOpts.coded) end local function GiveNotifyingOrderToUnit(uID, cmdID, cmdParams, cmdOpts) if widgetHandler:UnitCommandNotify(uID, cmdID, cmdParams, cmdOpts) then return end spGiveOrderToUnit(uID, cmdID, cmdParams, cmdOpts.coded) end local function SendSetWantedMaxSpeed(alt, ctrl, meta, shift) -- Move Speed (Applicable to every order) local wantedSpeed = 99999 -- High enough to exceed all units speed, but not high enough to cause errors (i.e. vs math.huge) if ctrl then local selUnits = spGetSelectedUnits() for i = 1, #selUnits do local ud = UnitDefs[spGetUnitDefID(selUnits[i])] local uSpeed = ud and ud.speed if ud and (ud.customParams.level or ud.customParams.dynamic_comm) then uSpeed = uSpeed * (Spring.GetUnitRulesParam(selUnits[i], "upgradesSpeedMult") or 1) end if uSpeed and uSpeed > 0 and uSpeed < wantedSpeed then wantedSpeed = uSpeed end end elseif REMOVED_SET_WANTED_MAX_SPEED then wantedSpeed = -1 end -- Directly giving speed order appears to work perfectly, including with shifted orders ... -- ... But other widgets CMD.INSERT the speed order into the front (Posn 1) of the queue instead (which doesn't work with shifted orders) if REMOVED_SET_WANTED_MAX_SPEED then local units = Spring.GetSelectedUnits() Spring.GiveOrderToUnitArray(units, CMD_WANTED_SPEED, {wantedSpeed}, 0) else local speedOpts = GetCmdOpts(alt, ctrl, meta, shift, true) GiveNotifyingOrder(CMD_SET_WANTED_MAX_SPEED, {wantedSpeed / 30}, speedOpts) end end -------------------------------------------------------------------------------- -- Mouse/keyboard Callins -------------------------------------------------------------------------------- function widget:MousePress(mx, my, mButton) -- Where did we click inMinimap = spIsAboveMiniMap(mx, my) if inMinimap and not MiniMapFullProxy then return false end if (mButton == 1 or mButton == 3) and fNodes and #fNodes > 0 then -- already issuing command return true end lineLength = 0 -- Get command that would've been issued local _, activeCmdID = spGetActiveCommand() if activeCmdID then if mButton ~= 1 then return false end usingCmd = activeCmdID usingRMB = false else if mButton ~= 3 then return false end local _, defaultCmdID = spGetDefaultCommand() if not defaultCmdID then return false end local overrideCmdID = overrideCmds[defaultCmdID] if overrideCmdID then local targType, targID = CulledTraceScreenRay(mx, my, false, inMinimap) if targType == 'unit' then overriddenCmd = defaultCmdID overriddenTarget = targID elseif targType == 'feature' then overriddenCmd = defaultCmdID overriddenTarget = targID + maxUnits else -- We can't reversibly override a command if we can't get the original target, so we give up overriding it. return false end usingCmd = overrideCmdID else overriddenCmd = nil overriddenTarget = nil usingCmd = defaultCmdID end usingRMB = true end -- Without this, the unloads issued will use the area of the last area unload if usingCmd == CMD_UNLOADUNITS then usingCmd = CMD_UNLOADUNIT end -- Is this command eligible for a custom formation ? local alt, ctrl, meta, shift = GetModKeys() if not (formationCmds[usingCmd] and (alt or not requiresAlt[usingCmd])) then return false end -- Get clicked position local _, pos = CulledTraceScreenRay(mx, my, true, inMinimap) if not pos then return false end -- Setup formation node array if not AddFNode(pos) then return false end -- Is this line a path candidate (We don't do a path off an overriden command) pathCandidate = (not overriddenCmd) and (spGetSelectedUnitsCount()==1 or (alt and not requiresAlt[usingCmd])) -- We handled the mouse press return true end function widget:MouseMove(mx, my, dx, dy, mButton) -- It is possible for MouseMove to fire after MouseRelease if #fNodes == 0 then return false end -- Minimap-specific checks if inMinimap then totaldxy = totaldxy + dx*dx + dy*dy if (totaldxy < 5) or not spIsAboveMiniMap(mx, my) then return false end end -- Get clicked position local _, pos = CulledTraceScreenRay(mx, my, true, inMinimap) if not pos then return false end -- Add the new formation node if not AddFNode(pos) then return false end -- Have we started drawing a line? if #fNodes == 2 then -- We have enough nodes to start drawing now widgetHandler:UpdateWidgetCallIn("DrawInMiniMap", self) widgetHandler:UpdateWidgetCallIn("DrawWorld", self) -- If the line is a path, start the units moving to this node if pathCandidate then local alt, ctrl, meta, shift = GetModKeys() local cmdOpts = GetCmdOpts(false, ctrl, meta, shift, usingRMB) -- using alt uses springs box formation, so we set it off always GiveNotifyingOrder(usingCmd, pos, cmdOpts) lastPathPos = pos draggingPath = true SendSetWantedMaxSpeed(alt, ctrl, meta, shift) end else -- Are we dragging a path? if draggingPath then local dx, dz = pos[1] - lastPathPos[1], pos[3] - lastPathPos[3] if (dx*dx + dz*dz) > minPathSpacingSq then local alt, ctrl, meta, shift = GetModKeys() local cmdOpts = GetCmdOpts(false, ctrl, meta, true, usingRMB) -- using alt uses springs box formation, so we set it off always GiveNonNotifyingOrder(usingCmd, pos, cmdOpts) lastPathPos = pos end end end return false end local function StopCommandAndRelinquishMouse() local ownerName = widgetHandler.mouseOwner and widgetHandler.mouseOwner.GetInfo and widgetHandler.mouseOwner.GetInfo() ownerName = ownerName and ownerName.name if ownerName == "CustomFormations2" then widgetHandler.mouseOwner = nil end -- Cancel the command fNodes = {} fDists = {} -- Modkeys / command reset local alt, ctrl, meta, shift = GetModKeys() if not usingRMB then if shift then endShift = true -- Reset on release of shift else spSetActiveCommand(0) -- Reset immediately end end end function widget:MouseRelease(mx, my, mButton) if (mButton == 1 or mButton == 3) and (not usingRMB) == (mButton == 3) then StopCommandAndRelinquishMouse() return false end -- It is possible for MouseRelease to fire after MouseRelease if #fNodes == 0 then return false end -- Modkeys / command reset local alt, ctrl, meta, shift = GetModKeys() if not usingRMB then if shift then endShift = true -- Reset on release of shift else spSetActiveCommand(0) -- Reset immediately end end -- Are we going to use the drawn formation? local usingFormation = true -- Override checking if overriddenCmd and ((not overrideCmdSingleUnit[overriddenCmd]) or #fNodes < SMALL_FORMATION_THRESHOLD) then local targetID local targType, targID = CulledTraceScreenRay(mx, my, false, inMinimap) if targType == 'unit' then targetID = targID elseif targType == 'feature' then targetID = targID + maxUnits end if targetID and targetID == overriddenTarget then local selectedUnits = Spring.GetSelectedUnits() -- The overridden commands cannot be self-issued, so give a move command instead. if not (#selectedUnits == 1 and selectedUnits[1] == targetID) then -- Signal that we are no longer using the drawn formation usingFormation = false -- Process the original command instead local cmdOpts = GetCmdOpts(alt, ctrl, meta, shift, usingRMB) GiveNotifyingOrder(overriddenCmd, {overriddenTarget}, cmdOpts) end end end -- Using path? If so then we do nothing if draggingPath then draggingPath = false elseif usingFormation then -- Using formation? If so then it's time to calculate and issue orders. -- Add final position (Sometimes we don't get the last MouseMove before this MouseRelease) if (not inMinimap) or spIsAboveMiniMap(mx, my) then local _, pos = CulledTraceScreenRay(mx, my, true, inMinimap) if pos then AddFNode(pos) end end -- Get command options local cmdOpts = GetCmdOpts(alt, ctrl, meta, shift, usingRMB) -- Single click ? (no line drawn) --if (#fNodes == 1) then if fDists[#fNodes] < minFormationLength then -- We should check if any units are able to execute it, -- but the order is small enough network-wise that the tiny bug potential isn't worth it. GiveNotifyingOrder(usingCmd, fNodes[1], cmdOpts) else -- Order is a formation -- Are any units able to execute it? local mUnits = GetExecutingUnits(usingCmd) if #mUnits > 0 then local interpNodes = GetInterpNodes(mUnits) local orders if (#mUnits <= maxHungarianUnits) then orders = GetOrdersHungarian(interpNodes, mUnits, #mUnits, shift and not meta) else orders = GetOrdersNoX(interpNodes, mUnits, #mUnits, shift and not meta) end if meta then local altOpts = GetCmdOpts(true, false, false, false, false) for i = 1, #orders do local orderPair = orders[i] local orderPos = orderPair[2] GiveNotifyingOrderToUnit(orderPair[1], CMD_INSERT, {0, usingCmd, cmdOpts.coded, orderPos[1], orderPos[2], orderPos[3]}, altOpts) end else for i = 1, #orders do local orderPair = orders[i] GiveNotifyingOrderToUnit(orderPair[1], usingCmd, orderPair[2], cmdOpts) end end end end SendSetWantedMaxSpeed(alt, ctrl, meta, shift) end if #fNodes > 1 then dimmCmd = usingCmd dimmNodes = fNodes dimmAlpha = 1.0 widgetHandler:UpdateWidgetCallIn("Update", self) end fNodes = {} fDists = {} local ownerName = widgetHandler.mouseOwner and widgetHandler.mouseOwner.GetInfo and widgetHandler.mouseOwner.GetInfo() ownerName = ownerName and ownerName.name if ownerName == "CustomFormations2" then widgetHandler.mouseOwner = nil end return true end function widget:KeyRelease(key) if (key == keyShift) and endShift then spSetActiveCommand(0) endShift = false end end -------------------------------------------------------------------------------- -- Drawing -------------------------------------------------------------------------------- local function tVerts(verts) for i = 1, #verts do local v = verts[i] if v[1] and v[2] and v[3] then glVertex(v[1], v[2], v[3]) end end end local function tVertsMinimap(verts) for i = 1, #verts do local v = verts[i] if v[1] and v[3] then glVertex(v[1], v[3], 1) end end end local function filledCircleVerts(cmd, cornerCount) SetColor(cmd, 1) glVertex(0,0,0) SetColor(cmd, 0) for t = 0, pi2, pi2 / cornerCount do glVertex(sin(t), 0, cos(t)) end end -- local function DrawFilledCircle(pos, size, cornerCount) -- glPushMatrix() -- glTranslate(pos[1], pos[2], pos[3]) -- glScale(size, 1, size) -- gl.CallList(filledCircleVerts) -- glPopMatrix() -- end local function DrawFilledCircleOutFading(pos, size, cornerCount) glPushMatrix() glTranslate(pos[1], pos[2], pos[3]) glScale(size, 1, size) local cmd = usingCmd if filledCircleOutFading[usingCmd] == nil then cmd = 0 end gl.CallList(filledCircleOutFading[cmd]) -- glBeginEnd(GL.TRIANGLE_FAN, function() -- glVertex(0,0,0) -- for t = 0, pi2, pi2 / cornerCount do -- glVertex(sin(t), 0, cos(t)) -- end -- end) -- draw extra glow as base -- has hardly any effect but doubles gpuTime, so disabled for now -- glBeginEnd(GL.TRIANGLE_FAN, function() -- SetColor(usingCmd, 1/15) -- glVertex(0,0,0) -- SetColor(usingCmd, 0) -- local baseSize = size * 2.8 -- for t = 0, pi2, pi2 / 8 do -- glVertex(sin(t) * baseSize, 0, cos(t) * baseSize) -- end -- end) glPopMatrix() end local function DrawFormationDots(vertFunction, zoomY, unitCount) gl.PushAttrib( GL.ALL_ATTRIB_BITS ) local currentLength = 0 local lengthPerUnit = lineLength / (unitCount-1) local lengthUnitNext = lengthPerUnit local dotSize = sqrt(zoomY*0.1)*options.dotsize.value if (#fNodes > 1) and (unitCount > 1) then SetColor(usingCmd, 1) DrawFilledCircleOutFading(fNodes[1], dotSize, 8) if (#fNodes > 2) then for i=1, #fNodes-2 do -- first and last circle are drawn before and after the for loop local x = fNodes[i][1] local y = fNodes[i][3] local x2 = fNodes[i+1][1] local y2 = fNodes[i+1][3] local dx = x - x2 local dy = y - y2 local length = sqrt((dx*dx)+(dy*dy)) while (currentLength + length >= lengthUnitNext) do local factor = (lengthUnitNext - currentLength) / length local factorPos = {fNodes[i][1] + ((fNodes[i+1][1] - fNodes[i][1]) * factor), fNodes[i][2] + ((fNodes[i+1][2] - fNodes[i][2]) * factor), fNodes[i][3] + ((fNodes[i+1][3] - fNodes[i][3]) * factor)} DrawFilledCircleOutFading(factorPos, dotSize, 8) lengthUnitNext = lengthUnitNext + lengthPerUnit end currentLength = currentLength + length end end DrawFilledCircleOutFading(fNodes[#fNodes], dotSize, 8) end gl.PopAttrib( GL.ALL_ATTRIB_BITS ) end local function DrawFormationLines(vertFunction, lineStipple) glLineStipple(lineStipple, 4095) glLineWidth(options.linewidth.value) if #fNodes > 1 then SetColor(usingCmd, 1.0) glBeginEnd(GL_LINE_STRIP, vertFunction, fNodes) glColor(1,1,1,1) end if #dimmNodes > 1 then SetColor(dimmCmd, dimmAlpha) glBeginEnd(GL_LINE_STRIP, vertFunction, dimmNodes) glColor(1,1,1,1) end glLineWidth(1.0) glLineStipple(false) end local Xs, Ys = spGetViewGeometry() Xs, Ys = Xs*0.5, Ys*0.5 function widget:ViewResize(viewSizeX, viewSizeY) Xs, Ys = spGetViewGeometry() Xs, Ys = Xs*0.5, Ys*0.5 end function widget:DrawWorld() -- Draw lines when a path is drawn instead of a formation, OR when drawmode_v2 for formations is not "dots" only if pathCandidate or options.drawmode_v2.value ~= "dots" then DrawFormationLines(tVerts, 2) end -- Draw dots when no path is drawn AND nodenumber is high enough AND drawmode_v2 for formations is not "lines" only if not pathCandidate and (#fNodes > 1 or #dimmNodes > 1) and options.drawmode_v2.value ~= "lines" then local camX, camY, camZ = spGetCameraPosition() local at, p = CulledTraceScreenRay(Xs,Ys,true,false,false) if at == "ground" then local dx, dy, dz = camX-p[1], camY-p[2], camZ-p[3] --zoomY = ((dx*dx + dy*dy + dz*dz)*0.01)^0.25 --tests show that sqrt(sqrt(x)) is faster than x^0.25 zoomY = sqrt(dx*dx + dy*dy + dz*dz) else --zoomY = sqrt((camY - max(spGetGroundHeight(camX, camZ), 0))*0.1) zoomY = camY - max(spGetGroundHeight(camX, camZ), 0) end if zoomY < 6 then zoomY = 6 end if lineLength > 0 then --don't try and draw if the command was cancelled by having two mouse buttons pressed at once local unitCount = spGetSelectedUnitsCount() DrawFormationDots(tVerts, zoomY, unitCount) end end end function widget:DrawInMiniMap() glPushMatrix() glLoadIdentity() glTranslate(0, 1, 0) glScale(1 / mapSizeX, -1 / mapSizeZ, 1) DrawFormationLines(tVertsMinimap, 1) glPopMatrix() end function InitFilledCircle(cmdID) filledCircleOutFading[cmdID] = gl.CreateList(gl.BeginEnd, GL.TRIANGLE_FAN, filledCircleVerts, cmdID, 8) end function widget:Initialize() -- filledCircle = gl.CreateList(gl.BeginEnd, GL.TRIANGLE_FAN, filledCircleVerts, 8) InitFilledCircle(CMD_MOVE) InitFilledCircle(CMD_RAW_MOVE) InitFilledCircle(CMD_ATTACK) InitFilledCircle(CMD.MANUALFIRE) InitFilledCircle(CMD_UNLOADUNIT) InitFilledCircle(CMD_UNIT_SET_TARGET) InitFilledCircle(CMD_UNIT_SET_TARGET_CIRCLE) InitFilledCircle(CMD_JUMP) InitFilledCircle(0) end function widget:Update(deltaTime) dimmAlpha = dimmAlpha - lineFadeRate * deltaTime if dimmAlpha <= 0 then dimmNodes = {} widgetHandler:RemoveWidgetCallIn("Update", self) if #fNodes == 0 then widgetHandler:RemoveWidgetCallIn("DrawWorld", self) widgetHandler:RemoveWidgetCallIn("DrawInMiniMap", self) end end end --------------------------------------------------------------------------------------------------------- -- Config --------------------------------------------------------------------------------------------------------- function widget:GetConfigData() -- Saving return { ['maxHungarianUnits'] = maxHungarianUnits, } end function widget:SetConfigData(data) -- Loading maxHungarianUnits = data['maxHungarianUnits'] or defaultHungarianUnits end --------------------------------------------------------------------------------------------------------- -- Matching Algorithms --------------------------------------------------------------------------------------------------------- function GetOrdersNoX(nodes, units, unitCount, shifted) -- Remember when we start -- This is for capping total time -- Note: We at least complete initial assignment local startTime = osclock() --------------------------------------------------------------------------------------------------------- -- Find initial assignments --------------------------------------------------------------------------------------------------------- local unitSet = {} local fdist = -1 local fm for u = 1, unitCount do -- Get unit position local ux, uz if shifted then ux, _, uz = GetUnitFinalPosition(units[u]) else ux, _, uz = spGetUnitPosition(units[u]) end unitSet[u] = {ux, units[u], uz, -1} -- Such that x/z are in same place as in nodes (So we can use same sort function) -- Work on finding furthest points (As we have ux/uz already) for i = u - 1, 1, -1 do local up = unitSet[i] local vx, vz = up[1], up[3] local dx, dz = vx - ux, vz - uz local dist = dx*dx + dz*dz if (dist > fdist) then fdist = dist fm = (vz - uz) / (vx - ux) end end end -- Maybe nodes are further apart than the units for i = 1, unitCount - 1 do local np = nodes[i] local nx, nz = np[1], np[3] for j = i + 1, unitCount do local mp = nodes[j] local mx, mz = mp[1], mp[3] local dx, dz = mx - nx, mz - nz local dist = dx*dx + dz*dz if (dist > fdist) then fdist = dist fm = (mz - nz) / (mx - nx) end end end local function sortFunc(a, b) -- y = mx + c -- c = y - mx -- c = y + x / m (For perp line) return (a[3] + a[1] / fm) < (b[3] + b[1] / fm) end tsort(unitSet, sortFunc) tsort(nodes, sortFunc) for u = 1, unitCount do unitSet[u][4] = nodes[u] end --------------------------------------------------------------------------------------------------------- -- Main part of algorithm --------------------------------------------------------------------------------------------------------- -- M/C for each finished matching local Ms = {} local Cs = {} -- Stacks to hold finished and still-to-check units local stFin = {} local stFinCnt = 0 local stChk = {} local stChkCnt = 0 -- Add all units to check stack for u = 1, unitCount do stChk[u] = u end stChkCnt = unitCount -- Begin algorithm while ((stChkCnt > 0) and (osclock() - startTime < maxNoXTime)) do -- Get unit, extract position and matching node position local u = stChk[stChkCnt] local ud = unitSet[u] local ux, uz = ud[1], ud[3] local mn = ud[4] local nx, nz = mn[1], mn[3] -- Calculate M/C local Mu = (nz - uz) / (nx - ux) local Cu = uz - Mu * ux -- Check for clashes against finished matches local clashes = false for i = 1, stFinCnt do -- Get opposing unit and matching node position local f = stFin[i] local fd = unitSet[f] local tn = fd[4] -- Get collision point local ix = (Cs[f] - Cu) / (Mu - Ms[f]) local iz = Mu * ix + Cu -- Check bounds if ((ux - ix) * (ix - nx) >= 0) and ((uz - iz) * (iz - nz) >= 0) and ((fd[1] - ix) * (ix - tn[1]) >= 0) and ((fd[3] - iz) * (iz - tn[3]) >= 0) then -- Lines cross -- Swap matches, note this retains solution integrity ud[4] = tn fd[4] = mn -- Remove clashee from finished stFin[i] = stFin[stFinCnt] stFinCnt = stFinCnt - 1 -- Add clashee to top of check stack stChkCnt = stChkCnt + 1 stChk[stChkCnt] = f -- No need to check further clashes = true break end end if not clashes then -- Add checked unit to finished stFinCnt = stFinCnt + 1 stFin[stFinCnt] = u -- Remove from to-check stack (Easily done, we know it was one on top) stChkCnt = stChkCnt - 1 -- We can set the M/C now Ms[u] = Mu Cs[u] = Cu end end --------------------------------------------------------------------------------------------------------- -- Return orders --------------------------------------------------------------------------------------------------------- local orders = {} for i = 1, unitCount do local unit = unitSet[i] orders[i] = {unit[2], unit[4]} end return orders end function GetOrdersHungarian(nodes, units, unitCount, shifted) ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- -- (the following code is written by gunblob) -- this code finds the optimal solution (slow, but effective!) -- it uses the hungarian algorithm from http://www.public.iastate.edu/~ddoty/HungarianAlgorithm.html -- if this violates gpl license please let gunblob and me know ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local t = osclock() -------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------- -- cache node<->unit distances local distances = {} --for i = 1, unitCount do distances[i] = {} end for i = 1, unitCount do local uID = units[i] local ux, uz if shifted then ux, _, uz = GetUnitFinalPosition(uID) else ux, _, uz = spGetUnitPosition(uID) end distances[i] = {} local dists = distances[i] for j = 1, unitCount do local nodePos = nodes[j] local dx, dz = nodePos[1] - ux, nodePos[3] - uz dists[j] = floor(sqrt(dx*dx + dz*dz) + 0.5) -- Integer distances = greatly improved algorithm speed end end -------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------- -- find optimal solution and send orders local result = findHungarian(distances, unitCount) -------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------- -- determine needed time and optimize the maxUnits limit local delay = osclock() - t if (delay > maxHngTime) and (maxHungarianUnits > minHungarianUnits) then -- Delay is greater than desired, we have to reduce units maxHungarianUnits = maxHungarianUnits - 1 else -- Delay is less than desired, so thats OK -- To make judgements we need number of units to be close to max -- Because we are making predictions of time and we want them to be accurate if (#units > maxHungarianUnits*unitIncreaseThresh) then -- This implementation of Hungarian algorithm is O(n3) -- Because we have less than maxUnits, but are altering maxUnits... -- We alter the time, to 'predict' time we would be getting at maxUnits -- We then recheck that against maxHngTime local nMult = maxHungarianUnits / #units if ((delay*nMult*nMult*nMult) < maxHngTime) then maxHungarianUnits = maxHungarianUnits + 1 else if (maxHungarianUnits > minHungarianUnits) then maxHungarianUnits = maxHungarianUnits - 1 end end end end -- Return orders local orders = {} for i = 1, unitCount do local rPair = result[i] orders[i] = {units[rPair[1]], nodes[rPair[2]]} end return orders end function findHungarian(array, n) -- Vars local colcover = {} local rowcover = {} local starscol = {} local primescol = {} -- Initialization for i = 1, n do rowcover[i] = false colcover[i] = false starscol[i] = false primescol[i] = false end -- Subtract minimum from rows for i = 1, n do local aRow = array[i] local minVal = aRow[1] for j = 2, n do if aRow[j] < minVal then minVal = aRow[j] end end for j = 1, n do aRow[j] = aRow[j] - minVal end end -- Subtract minimum from columns for j = 1, n do local minVal = array[1][j] for i = 2, n do if array[i][j] < minVal then minVal = array[i][j] end end for i = 1, n do array[i][j] = array[i][j] - minVal end end -- Star zeroes for i = 1, n do local aRow = array[i] for j = 1, n do if (aRow[j] == 0) and not colcover[j] then colcover[j] = true starscol[i] = j break end end end -- Start solving system while true do -- Are we done ? local done = true for i = 1, n do if not colcover[i] then done = false break end end if done then local pairings = {} for i = 1, n do pairings[i] = {i, starscol[i]} end return pairings end -- Not done local r, c = stepPrimeZeroes(array, colcover, rowcover, n, starscol, primescol) stepFiveStar(colcover, rowcover, r, c, n, starscol, primescol) end end function doPrime(array, colcover, rowcover, n, starscol, r, c, rmax, primescol) primescol[r] = c local starCol = starscol[r] if starCol then rowcover[r] = true colcover[starCol] = false for i = 1, rmax do if not rowcover[i] and (array[i][starCol] == 0) then local rr, cc = doPrime(array, colcover, rowcover, n, starscol, i, starCol, rmax, primescol) if rr then return rr, cc end end end return else return r, c end end function stepPrimeZeroes(array, colcover, rowcover, n, starscol, primescol) -- Infinite loop while true do -- Find uncovered zeros and prime them for i = 1, n do if not rowcover[i] then local aRow = array[i] for j = 1, n do if (aRow[j] == 0) and not colcover[j] then local i, j = doPrime(array, colcover, rowcover, n, starscol, i, j, i-1, primescol) if i then return i, j end break -- this row is covered end end end end -- Find minimum uncovered local minVal = huge for i = 1, n do if not rowcover[i] then local aRow = array[i] for j = 1, n do if (aRow[j] < minVal) and not colcover[j] then minVal = aRow[j] end end end end -- There is the potential for minVal to be 0, very very rarely though. (Checking for it costs more than the +/- 0's) -- Covered rows = + -- Uncovered cols = - for i = 1, n do local aRow = array[i] if rowcover[i] then for j = 1, n do if colcover[j] then aRow[j] = aRow[j] + minVal end end else for j = 1, n do if not colcover[j] then aRow[j] = aRow[j] - minVal end end end end end end function stepFiveStar(colcover, rowcover, row, col, n, starscol, primescol) -- Star the initial prime primescol[row] = false starscol[row] = col local ignoreRow = row -- Ignore the star on this row when looking for next repeat local noFind = true for i = 1, n do if (starscol[i] == col) and (i ~= ignoreRow) then noFind = false -- Unstar the star -- Turn the prime on the same row into a star (And ignore this row (aka star) when searching for next star) local pcol = primescol[i] primescol[i] = false starscol[i] = pcol ignoreRow = i col = pcol break end end until noFind for i = 1, n do rowcover[i] = false colcover[i] = false primescol[i] = false end for i = 1, n do local scol = starscol[i] if scol then colcover[scol] = true end end end
gpl-2.0
garrysmodlua/wire
lua/wire/stools/hologrid.lua
8
2091
WireToolSetup.setCategory( "Visuals/Holographic" ) WireToolSetup.open( "hologrid", "HoloGrid", "gmod_wire_hologrid", nil, "HoloGrids" ) if CLIENT then language.Add( "tool.wire_hologrid.name", "Holographic Grid Tool (Wire)" ) language.Add( "tool.wire_hologrid.desc", "The grid to aid in holographic projections" ) TOOL.Information = { { name = "left_0", stage = 0, text = "Create grid" }, { name = "right_0", stage = 0, text = "Link HoloGrid with HoloEmitter or reference entity" }, { name = "reload_0", stage = 0, text = "Unlink HoloEmitter or HoloGrid" }, { name = "right_1", stage = 1, text = "Select the HoloGrid to link to" }, } language.Add( "Tool_wire_hologrid_usegps", "Use GPS coordinates" ) end WireToolSetup.BaseLang() WireToolSetup.SetupMax( 20 ) if SERVER then function TOOL:GetConVars() return self:GetClientNumber( "usegps" )~=0 end -- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function end TOOL.ClientConVar = { model = "models/jaanus/wiretool/wiretool_siren.mdl", usegps = 0, } function TOOL:RightClick( trace ) if CLIENT then return true end local ent = trace.Entity if (self:GetStage() == 0) then if (ent:GetClass() == "gmod_wire_holoemitter") then self.Target = ent self:SetStage(1) else self:GetOwner():ChatPrint("That's not a holoemitter.") return false end else if (self.Target == ent or ent:IsWorld()) then self:GetOwner():ChatPrint("Holoemitter unlinked.") self.Target:UnLink() self:SetStage(0) return true end self.Target:Link( ent ) self:SetStage(0) self:GetOwner():ChatPrint( "Holoemitter linked to entity (".. tostring(ent)..")" ) end return true end function TOOL.Reload(trace) self.Linked = nil self:SetStage(0) if IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_hologrid" then self.Linked:TriggerInput("Reference", nil) return true end end function TOOL.BuildCPanel( panel ) WireDermaExts.ModelSelect(panel, "wire_hologrid_model", list.Get( "Wire_Misc_Tools_Models" ), 1) panel:CheckBox("#Tool_wire_hologrid_usegps", "wire_hologrid_usegps") end
apache-2.0
ReclaimYourPrivacy/cloak-luci
modules/luci-base/luasrc/model/network.lua
8
33786
-- Copyright 2009-2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local type, next, pairs, ipairs, loadfile, table = type, next, pairs, ipairs, loadfile, table local tonumber, tostring, math = tonumber, tostring, math local require = require local nxo = require "nixio" local nfs = require "nixio.fs" local ipc = require "luci.ip" local sys = require "luci.sys" local utl = require "luci.util" local dsp = require "luci.dispatcher" local uci = require "luci.model.uci" local lng = require "luci.i18n" module "luci.model.network" IFACE_PATTERNS_VIRTUAL = { } IFACE_PATTERNS_IGNORE = { "^wmaster%d", "^wifi%d", "^hwsim%d", "^imq%d", "^ifb%d", "^mon%.wlan%d", "^sit%d", "^gre%d", "^lo$" } IFACE_PATTERNS_WIRELESS = { "^wlan%d", "^wl%d", "^ath%d", "^%w+%.network%d" } protocol = utl.class() local _protocols = { } local _interfaces, _bridge, _switch, _tunnel local _ubusnetcache, _ubusdevcache, _ubuswificache local _uci_real, _uci_state function _filter(c, s, o, r) local val = _uci_real:get(c, s, o) if val then local l = { } if type(val) == "string" then for val in val:gmatch("%S+") do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci_real:set(c, s, o, table.concat(l, " ")) else _uci_real:delete(c, s, o) end elseif type(val) == "table" then for _, val in ipairs(val) do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci_real:set(c, s, o, l) else _uci_real:delete(c, s, o) end end end end function _append(c, s, o, a) local val = _uci_real:get(c, s, o) or "" if type(val) == "string" then local l = { } for val in val:gmatch("%S+") do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci_real:set(c, s, o, table.concat(l, " ")) elseif type(val) == "table" then local l = { } for _, val in ipairs(val) do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci_real:set(c, s, o, l) end end function _stror(s1, s2) if not s1 or #s1 == 0 then return s2 and #s2 > 0 and s2 else return s1 end end function _get(c, s, o) return _uci_real:get(c, s, o) end function _set(c, s, o, v) if v ~= nil then if type(v) == "boolean" then v = v and "1" or "0" end return _uci_real:set(c, s, o, v) else return _uci_real:delete(c, s, o) end end function _wifi_iface(x) local _, p for _, p in ipairs(IFACE_PATTERNS_WIRELESS) do if x:match(p) then return true end end return false end function _wifi_state(key, val, field) local radio, radiostate, ifc, ifcstate if not next(_ubuswificache) then _ubuswificache = utl.ubus("network.wireless", "status", {}) or {} -- workaround extended section format for radio, radiostate in pairs(_ubuswificache) do for ifc, ifcstate in pairs(radiostate.interfaces) do if ifcstate.section and ifcstate.section:sub(1, 1) == '@' then local s = _uci_real:get_all('wireless.%s' % ifcstate.section) if s then ifcstate.section = s['.name'] end end end end end for radio, radiostate in pairs(_ubuswificache) do for ifc, ifcstate in pairs(radiostate.interfaces) do if ifcstate[key] == val then return ifcstate[field] end end end end function _wifi_lookup(ifn) -- got a radio#.network# pseudo iface, locate the corresponding section local radio, ifnidx = ifn:match("^(%w+)%.network(%d+)$") if radio and ifnidx then local sid = nil local num = 0 ifnidx = tonumber(ifnidx) _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device == radio then num = num + 1 if num == ifnidx then sid = s['.name'] return false end end end) return sid -- looks like wifi, try to locate the section via state vars elseif _wifi_iface(ifn) then local sid = _wifi_state("ifname", ifn, "section") if not sid then _uci_state:foreach("wireless", "wifi-iface", function(s) if s.ifname == ifn then sid = s['.name'] return false end end) end return sid end end function _iface_virtual(x) local _, p for _, p in ipairs(IFACE_PATTERNS_VIRTUAL) do if x:match(p) then return true end end return false end function _iface_ignore(x) local _, p for _, p in ipairs(IFACE_PATTERNS_IGNORE) do if x:match(p) then return true end end return _iface_virtual(x) end function init(cursor) _uci_real = cursor or _uci_real or uci.cursor() _uci_state = _uci_real:substate() _interfaces = { } _bridge = { } _switch = { } _tunnel = { } _ubusnetcache = { } _ubusdevcache = { } _ubuswificache = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") local prnt = name:match("^([^%.]+)%.") if _iface_virtual(name) then _tunnel[name] = true end if _tunnel[name] or not _iface_ignore(name) then _interfaces[name] = _interfaces[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if prnt then _switch[name] = true _switch[prnt] = true end if i.family == "packet" then _interfaces[name].flags = i.flags _interfaces[name].stats = i.data _interfaces[name].macaddr = i.addr elseif i.family == "inet" then _interfaces[name].ipaddrs[#_interfaces[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then _interfaces[name].ip6addrs[#_interfaces[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { _interfaces[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end _bridge[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = _interfaces[r[2]] b.ifnames[#b.ifnames].bridge = b end end end return _M end function save(self, ...) _uci_real:save(...) _uci_real:load(...) end function commit(self, ...) _uci_real:commit(...) _uci_real:load(...) end function ifnameof(self, x) if utl.instanceof(x, interface) then return x:name() elseif utl.instanceof(x, protocol) then return x:ifname() elseif type(x) == "string" then return x:match("^[^:]+") end end function get_protocol(self, protoname, netname) local v = _protocols[protoname] if v then return v(netname or "__dummy__") end end function get_protocols(self) local p = { } local _, v for _, v in ipairs(_protocols) do p[#p+1] = v("__dummy__") end return p end function register_protocol(self, protoname) local proto = utl.class(protocol) function proto.__init__(self, name) self.sid = name end function proto.proto(self) return protoname end _protocols[#_protocols+1] = proto _protocols[protoname] = proto return proto end function register_pattern_virtual(self, pat) IFACE_PATTERNS_VIRTUAL[#IFACE_PATTERNS_VIRTUAL+1] = pat end function has_ipv6(self) return nfs.access("/proc/net/ipv6_route") end function add_network(self, n, options) local oldnet = self:get_network(n) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not oldnet then if _uci_real:section("network", "interface", n, options) then return network(n) end elseif oldnet and oldnet:is_empty() then if options then local k, v for k, v in pairs(options) do oldnet:set(k, v) end end return oldnet end end function get_network(self, n) if n and _uci_real:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } local nls = { } _uci_real:foreach("network", "interface", function(s) nls[s['.name']] = network(s['.name']) end) local n for n in utl.kspairs(nls) do nets[#nets+1] = nls[n] end return nets end function del_network(self, n) local r = _uci_real:delete("network", n) if r then _uci_real:delete_all("network", "alias", function(s) return (s.interface == n) end) _uci_real:delete_all("network", "route", function(s) return (s.interface == n) end) _uci_real:delete_all("network", "route6", function(s) return (s.interface == n) end) _uci_real:foreach("wireless", "wifi-iface", function(s) local net local rest = { } for net in utl.imatch(s.network) do if net ~= n then rest[#rest+1] = net end end if #rest > 0 then _uci_real:set("wireless", s['.name'], "network", table.concat(rest, " ")) else _uci_real:delete("wireless", s['.name'], "network") end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = _uci_real:section("network", "interface", new, _uci_real:get_all("network", old)) if r then _uci_real:foreach("network", "alias", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("network", "route", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("network", "route6", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("wireless", "wifi-iface", function(s) local net local list = { } for net in utl.imatch(s.network) do if net == old then list[#list+1] = new else list[#list+1] = net end end if #list > 0 then _uci_real:set("wireless", s['.name'], "network", table.concat(list, " ")) end end) _uci_real:delete("network", old) end end return r or false end function get_interface(self, i) if _interfaces[i] or _wifi_iface(i) then return interface(i) else local ifc local num = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 if s['.name'] == i then ifc = interface( "%s.network%d" %{s.device, num[s.device] }) return false end end end) return ifc end end function get_interfaces(self) local iface local ifaces = { } local seen = { } local nfs = { } local baseof = { } -- find normal interfaces _uci_real:foreach("network", "interface", function(s) for iface in utl.imatch(s.ifname) do if not _iface_ignore(iface) and not _wifi_iface(iface) then seen[iface] = true nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(_interfaces) do if not (seen[iface] or _iface_ignore(iface) or _wifi_iface(iface)) then nfs[iface] = interface(iface) end end -- find vlan interfaces _uci_real:foreach("network", "switch_vlan", function(s) if not s.device then return end local base = baseof[s.device] if not base then if not s.device:match("^eth%d") then local l for l in utl.execi("swconfig dev %q help 2>/dev/null" % s.device) do if not base then base = l:match("^%w+: (%w+)") end end if not base or not base:match("^eth%d") then base = "eth0" end else base = s.device end baseof[s.device] = base end local vid = tonumber(s.vid or s.vlan) if vid ~= nil and vid >= 0 and vid <= 4095 then local iface = "%s.%d" %{ base, vid } if not seen[iface] then seen[iface] = true nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[iface] end -- find wifi interfaces local num = { } local wfs = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local i = "%s.network%d" %{ s.device, num[s.device] } wfs[i] = interface(i) end end) for iface in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[iface] end return ifaces end function ignore_interface(self, x) return _iface_ignore(x) end function get_wifidev(self, dev) if _uci_real:get("wireless", dev) == "wifi-device" then return wifidev(dev) end end function get_wifidevs(self) local devs = { } local wfd = { } _uci_real:foreach("wireless", "wifi-device", function(s) wfd[#wfd+1] = s['.name'] end) local dev for _, dev in utl.vspairs(wfd) do devs[#devs+1] = wifidev(dev) end return devs end function get_wifinet(self, net) local wnet = _wifi_lookup(net) if wnet then return wifinet(wnet) end end function add_wifinet(self, net, options) if type(options) == "table" and options.device and _uci_real:get("wireless", options.device) == "wifi-device" then local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) return wifinet(wnet) end end function del_wifinet(self, net) local wnet = _wifi_lookup(net) if wnet then _uci_real:delete("wireless", wnet) return true end return false end function get_status_by_route(self, addr, mask) local _, object for _, object in ipairs(utl.ubus()) do local net = object:match("^network%.interface%.(.+)") if net then local s = utl.ubus(object, "status", {}) if s and s.route then local rt for _, rt in ipairs(s.route) do if not rt.table and rt.target == addr and rt.mask == mask then return net, s end end end end end end function get_status_by_address(self, addr) local _, object for _, object in ipairs(utl.ubus()) do local net = object:match("^network%.interface%.(.+)") if net then local s = utl.ubus(object, "status", {}) if s and s['ipv4-address'] then local a for _, a in ipairs(s['ipv4-address']) do if a.address == addr then return net, s end end end if s and s['ipv6-address'] then local a for _, a in ipairs(s['ipv6-address']) do if a.address == addr then return net, s end end end end end end function get_wannet(self) local net = self:get_status_by_route("0.0.0.0", 0) return net and network(net) end function get_wandev(self) local _, stat = self:get_status_by_route("0.0.0.0", 0) return stat and interface(stat.l3_device or stat.device) end function get_wan6net(self) local net = self:get_status_by_route("::", 0) return net and network(net) end function get_wan6dev(self) local _, stat = self:get_status_by_route("::", 0) return stat and interface(stat.l3_device or stat.device) end function network(name, proto) if name then local p = proto or _uci_real:get("network", name, "proto") local c = p and _protocols[p] or protocol return c(name) end end function protocol.__init__(self, name) self.sid = name end function protocol._get(self, opt) local v = _uci_real:get("network", self.sid, opt) if type(v) == "table" then return table.concat(v, " ") end return v or "" end function protocol._ubus(self, field) if not _ubusnetcache[self.sid] then _ubusnetcache[self.sid] = utl.ubus("network.interface.%s" % self.sid, "status", { }) end if _ubusnetcache[self.sid] and field then return _ubusnetcache[self.sid][field] end return _ubusnetcache[self.sid] end function protocol.get(self, opt) return _get("network", self.sid, opt) end function protocol.set(self, opt, val) return _set("network", self.sid, opt, val) end function protocol.ifname(self) local ifname if self:is_floating() then ifname = self:_ubus("l3_device") else ifname = self:_ubus("device") end if not ifname then local num = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifname = "%s.network%d" %{ s.device, num[s.device] } return false end end end end) end return ifname end function protocol.proto(self) return "none" end function protocol.get_i18n(self) local p = self:proto() if p == "none" then return lng.translate("Unmanaged") elseif p == "static" then return lng.translate("Static address") elseif p == "dhcp" then return lng.translate("DHCP client") else return lng.translate("Unknown") end end function protocol.type(self) return self:_get("type") end function protocol.name(self) return self.sid end function protocol.uptime(self) return self:_ubus("uptime") or 0 end function protocol.expires(self) local a = tonumber(_uci_state:get("network", self.sid, "lease_acquired")) local l = tonumber(_uci_state:get("network", self.sid, "lease_lifetime")) if a and l then l = l - (nxo.sysinfo().uptime - a) return l > 0 and l or 0 end return -1 end function protocol.metric(self) return tonumber(_uci_state:get("network", self.sid, "metric")) or 0 end function protocol.ipaddr(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and addrs[1].address end function protocol.netmask(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and ipc.IPv4("0.0.0.0/%d" % addrs[1].mask):mask():string() end function protocol.gwaddr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "0.0.0.0" and route.mask == 0 then return route.nexthop end end end function protocol.dnsaddrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if not addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.ip6addr(self) local addrs = self:_ubus("ipv6-address") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } else addrs = self:_ubus("ipv6-prefix-assignment") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } end end end function protocol.gw6addr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "::" and route.mask == 0 then return ipc.IPv6(route.nexthop):string() end end end function protocol.dns6addrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.is_bridge(self) return (not self:is_virtual() and self:type() == "bridge") end function protocol.opkg_package(self) return nil end function protocol.is_installed(self) return true end function protocol.is_virtual(self) return false end function protocol.is_floating(self) return false end function protocol.is_empty(self) if self:is_floating() then return false else local rv = true if (self:_get("ifname") or ""):match("%S+") then rv = false end _uci_real:foreach("wireless", "wifi-iface", function(s) local n for n in utl.imatch(s.network) do if n == self.sid then rv = false return false end end end) return rv end end function protocol.add_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wifi interface, change its network option local wif = _wifi_lookup(ifname) if wif then _append("wireless", wif, "network", self.sid) -- add iface to our iface list else _append("network", self.sid, "ifname", ifname) end end end function protocol.del_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wireless interface, clear its network option local wif = _wifi_lookup(ifname) if wif then _filter("wireless", wif, "network", self.sid) end -- remove the interface _filter("network", self.sid, "ifname", ifname) end end function protocol.get_interface(self) if self:is_virtual() then _tunnel[self:proto() .. "-" .. self.sid] = true return interface(self:proto() .. "-" .. self.sid, self) elseif self:is_bridge() then _bridge["br-" .. self.sid] = true return interface("br-" .. self.sid, self) else local ifn = nil local num = { } for ifn in utl.imatch(_uci_real:get("network", self.sid, "ifname")) do ifn = ifn:match("^[^:/]+") return ifn and interface(ifn, self) end ifn = nil _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifn = "%s.network%d" %{ s.device, num[s.device] } return false end end end end) return ifn and interface(ifn, self) end end function protocol.get_interfaces(self) if self:is_bridge() or (self:is_virtual() and not self:is_floating()) then local ifaces = { } local ifn local nfs = { } for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("^[^:/]+") nfs[ifn] = interface(ifn, self) end for ifn in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[ifn] end local num = { } local wfs = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifn = "%s.network%d" %{ s.device, num[s.device] } wfs[ifn] = interface(ifn, self) end end end end) for ifn in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[ifn] end return ifaces end end function protocol.contains_interface(self, ifname) ifname = _M:ifnameof(ifname) if not ifname then return false elseif self:is_virtual() and self:proto() .. "-" .. self.sid == ifname then return true elseif self:is_bridge() and "br-" .. self.sid == ifname then return true else local ifn for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("[^:]+") if ifn == ifname then return true end end local wif = _wifi_lookup(ifname) if wif then local n for n in utl.imatch(_uci_real:get("wireless", wif, "network")) do if n == self.sid then return true end end end end return false end function protocol.adminlink(self) return dsp.build_url("admin", "network", "network", self.sid) end interface = utl.class() function interface.__init__(self, ifname, network) local wif = _wifi_lookup(ifname) if wif then self.wif = wifinet(wif) self.ifname = _wifi_state("section", wif, "ifname") end self.ifname = self.ifname or ifname self.dev = _interfaces[self.ifname] self.network = network end function interface._ubus(self, field) if not _ubusdevcache[self.ifname] then _ubusdevcache[self.ifname] = utl.ubus("network.device", "status", { name = self.ifname }) end if _ubusdevcache[self.ifname] and field then return _ubusdevcache[self.ifname][field] end return _ubusdevcache[self.ifname] end function interface.name(self) return self.wif and self.wif:ifname() or self.ifname end function interface.mac(self) return (self:_ubus("macaddr") or "00:00:00:00:00:00"):upper() end function interface.ipaddrs(self) return self.dev and self.dev.ipaddrs or { } end function interface.ip6addrs(self) return self.dev and self.dev.ip6addrs or { } end function interface.type(self) if self.wif or _wifi_iface(self.ifname) then return "wifi" elseif _bridge[self.ifname] then return "bridge" elseif _tunnel[self.ifname] then return "tunnel" elseif self.ifname:match("%.") then return "vlan" elseif _switch[self.ifname] then return "switch" else return "ethernet" end end function interface.shortname(self) if self.wif then return "%s %q" %{ self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() } else return self.ifname end end function interface.get_i18n(self) if self.wif then return "%s: %s %q" %{ lng.translate("Wireless Network"), self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() } else return "%s: %q" %{ self:get_type_i18n(), self:name() } end end function interface.get_type_i18n(self) local x = self:type() if x == "wifi" then return lng.translate("Wireless Adapter") elseif x == "bridge" then return lng.translate("Bridge") elseif x == "switch" then return lng.translate("Ethernet Switch") elseif x == "vlan" then return lng.translate("VLAN Interface") elseif x == "tunnel" then return lng.translate("Tunnel Interface") else return lng.translate("Ethernet Adapter") end end function interface.adminlink(self) if self.wif then return self.wif:adminlink() end end function interface.ports(self) local members = self:_ubus("bridge-members") if members then local _, iface local ifaces = { } for _, iface in ipairs(members) do ifaces[#ifaces+1] = interface(iface) end end end function interface.bridge_id(self) if self.br then return self.br.id else return nil end end function interface.bridge_stp(self) if self.br then return self.br.stp else return false end end function interface.is_up(self) return self:_ubus("up") or false end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.is_bridgeport(self) return self.dev and self.dev.bridge and true or false end function interface.tx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.tx_bytes or 0 end function interface.rx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.rx_bytes or 0 end function interface.tx_packets(self) local stat = self:_ubus("statistics") return stat and stat.tx_packets or 0 end function interface.rx_packets(self) local stat = self:_ubus("statistics") return stat and stat.rx_packets or 0 end function interface.get_network(self) return self:get_networks()[1] end function interface.get_networks(self) if not self.networks then local nets = { } local _, net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) or net:ifname() == self.ifname then nets[#nets+1] = net end end table.sort(nets, function(a, b) return a.sid < b.sid end) self.networks = nets return nets else return self.networks end end function interface.get_wifinet(self) return self.wif end wifidev = utl.class() function wifidev.__init__(self, dev) self.sid = dev self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } end function wifidev.get(self, opt) return _get("wireless", self.sid, opt) end function wifidev.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifidev.name(self) return self.sid end function wifidev.hwmodes(self) local l = self.iwinfo.hwmodelist if l and next(l) then return l else return { b = true, g = true } end end function wifidev.get_i18n(self) local t = "Generic" if self.iwinfo.type == "wl" then t = "Broadcom" elseif self.iwinfo.type == "madwifi" then t = "Atheros" end local m = "" local l = self:hwmodes() if l.a then m = m .. "a" end if l.b then m = m .. "b" end if l.g then m = m .. "g" end if l.n then m = m .. "n" end if l.ac then m = "ac" end return "%s 802.11%s Wireless Controller (%s)" %{ t, m, self:name() } end function wifidev.is_up(self) if _ubuswificache[self.sid] then return (_ubuswificache[self.sid].up == true) end local up = false _uci_state:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then if s.up == "1" then up = true return false end end end) return up end function wifidev.get_wifinet(self, net) if _uci_real:get("wireless", net) == "wifi-iface" then return wifinet(net) else local wnet = _wifi_lookup(net) if wnet then return wifinet(wnet) end end end function wifidev.get_wifinets(self) local nets = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then nets[#nets+1] = wifinet(s['.name']) end end) return nets end function wifidev.add_wifinet(self, options) options = options or { } options.device = self.sid local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) if wnet then return wifinet(wnet, options) end end function wifidev.del_wifinet(self, net) if utl.instanceof(net, wifinet) then net = net.sid elseif _uci_real:get("wireless", net) ~= "wifi-iface" then net = _wifi_lookup(net) end if net and _uci_real:get("wireless", net, "device") == self.sid then _uci_real:delete("wireless", net) return true end return false end wifinet = utl.class() function wifinet.__init__(self, net, data) self.sid = net local num = { } local netid _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 if s['.name'] == self.sid then netid = "%s.network%d" %{ s.device, num[s.device] } return false end end end) local dev = _wifi_state("section", self.sid, "ifname") or netid self.netid = netid self.wdev = dev self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } self.iwdata = data or _uci_state:get_all("wireless", self.sid) or _uci_real:get_all("wireless", self.sid) or { } end function wifinet.get(self, opt) return _get("wireless", self.sid, opt) end function wifinet.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifinet.mode(self) return _uci_state:get("wireless", self.sid, "mode") or "ap" end function wifinet.ssid(self) return _uci_state:get("wireless", self.sid, "ssid") end function wifinet.bssid(self) return _uci_state:get("wireless", self.sid, "bssid") end function wifinet.network(self) return _uci_state:get("wifinet", self.sid, "network") end function wifinet.id(self) return self.netid end function wifinet.name(self) return self.sid end function wifinet.ifname(self) local ifname = self.iwinfo.ifname if not ifname or ifname:match("^wifi%d") or ifname:match("^radio%d") then ifname = self.wdev end return ifname end function wifinet.get_device(self) if self.iwdata.device then return wifidev(self.iwdata.device) end end function wifinet.is_up(self) local ifc = self:get_interface() return (ifc and ifc:is_up() or false) end function wifinet.active_mode(self) local m = _stror(self.iwinfo.mode, self.iwdata.mode) or "ap" if m == "ap" then m = "Master" elseif m == "sta" then m = "Client" elseif m == "adhoc" then m = "Ad-Hoc" elseif m == "mesh" then m = "Mesh" elseif m == "monitor" then m = "Monitor" end return m end function wifinet.active_mode_i18n(self) return lng.translate(self:active_mode()) end function wifinet.active_ssid(self) return _stror(self.iwinfo.ssid, self.iwdata.ssid) end function wifinet.active_bssid(self) return _stror(self.iwinfo.bssid, self.iwdata.bssid) or "00:00:00:00:00:00" end function wifinet.active_encryption(self) local enc = self.iwinfo and self.iwinfo.encryption return enc and enc.description or "-" end function wifinet.assoclist(self) return self.iwinfo.assoclist or { } end function wifinet.frequency(self) local freq = self.iwinfo.frequency if freq and freq > 0 then return "%.03f" % (freq / 1000) end end function wifinet.bitrate(self) local rate = self.iwinfo.bitrate if rate and rate > 0 then return (rate / 1000) end end function wifinet.channel(self) return self.iwinfo.channel or tonumber(_uci_state:get("wireless", self.iwdata.device, "channel")) end function wifinet.signal(self) return self.iwinfo.signal or 0 end function wifinet.noise(self) return self.iwinfo.noise or 0 end function wifinet.country(self) return self.iwinfo.country or "00" end function wifinet.txpower(self) local pwr = (self.iwinfo.txpower or 0) return pwr + self:txpower_offset() end function wifinet.txpower_offset(self) return self.iwinfo.txpower_offset or 0 end function wifinet.signal_level(self, s, n) if self:active_bssid() ~= "00:00:00:00:00:00" then local signal = s or self:signal() local noise = n or self:noise() if signal < 0 and noise < 0 then local snr = -1 * (noise - signal) return math.floor(snr / 5) else return 0 end else return -1 end end function wifinet.signal_percent(self) local qc = self.iwinfo.quality or 0 local qm = self.iwinfo.quality_max or 0 if qc > 0 and qm > 0 then return math.floor((100 / qm) * qc) else return 0 end end function wifinet.shortname(self) return "%s %q" %{ lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid() } end function wifinet.get_i18n(self) return "%s: %s %q (%s)" %{ lng.translate("Wireless Network"), lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid(), self:ifname() } end function wifinet.adminlink(self) return dsp.build_url("admin", "network", "wireless", self.netid) end function wifinet.get_network(self) return self:get_networks()[1] end function wifinet.get_networks(self) local nets = { } local net for net in utl.imatch(tostring(self.iwdata.network)) do if _uci_real:get("network", net) == "interface" then nets[#nets+1] = network(net) end end table.sort(nets, function(a, b) return a.sid < b.sid end) return nets end function wifinet.get_interface(self) return interface(self:ifname()) end -- setup base protocols _M:register_protocol("static") _M:register_protocol("dhcp") _M:register_protocol("none") -- load protocol extensions local exts = nfs.dir(utl.libpath() .. "/model/network") if exts then local ext for ext in exts do if ext:match("%.lua$") then require("luci.model.network." .. ext:gsub("%.lua$", "")) end end end
apache-2.0
jucor/lua-sci
quad/_dblexp_precomputed.lua
1
17605
-------------------------------------------------------------------------------- -- Precomputed abscissas and weights for double exponential quadrature method. -- -- Copyright (C) 2011-2013 Stefano Peluchetti. All rights reserved. -- -- Features, documention and more: http://www.scilua.org . -- -- This file is part of the SciLua library, which is released under the MIT -- license: full text in file LICENSE.TXT in the library's root folder. -------------------------------------------------------------------------------- -- Weigths and abscissas computed using the MPRF library with 120 bits of -- precision (around 36 digits of accuracy), then converted to doubles. -- Truncation range for infinite integral is [-3, 3] extremes included. -- 7 levels => total of 2^7 + 1 = 385 abscissas and weigths. -- This choice of levels is shown to be enough for double precision evaluation -- of integrals, see: -- http://crd-legacy.lbl.gov/~dhbailey/dhbpapers/quadrature.pdf . -- In order to be able to start from level 1 (h = 1/2) the next available range -- would be [-3.5, 3.5] but abscissas(3.5) is == 1 in double precision, and -- this is an issue (for instance for transformations from non-bounded -- integration regions to [-1, 1] which is the region expected from the -- algorithm here considered). -- Weights (and abscissas) reversed in order because it's better to start -- adding the potentially smaller (because of the weigths) terms first. -- TODO: Investigate differences by expanding to [-3.5, 3.5] and capping -- TODO: abscissas to 1 - epsilon. return { abscissas = { {0.99999999999995703,0.99999998887566488,0.99997747719246155,0.99751485645722437,0.95136796407274693,0.67427149224843574,0}, {0.99999999995285638,0.99999920473711468,0.9996882640283532,0.98704056050737687,0.85956905868989653,0.37720973816403414}, {0.99999999999823208,0.99999999914270499,0.99999989278161239,0.99999531604122049,0.9999093846951439,0.99906519645578584,0.99405550663140207,0.97396686819567735,0.91487926326457458,0.78060743898320029,0.53914670538796772,0.19435700332493541}, {0.99999999999970801,0.99999999999039391,0.99999999978973275,0.99999999678719909,0.99999996423908089,0.99999969889415252,0.99999801714059533,0.99998948201481841,0.99995387100562794,0.99982882207287493,0.99945143443527451,0.99845420876769764,0.99610866543750853,0.99112699244169877,0.98145482667733508,0.96411216422354729,0.93516085752198463,0.88989140278426015,0.8233170055064023,0.73101803479256144,0.61027365750063889,0.46125354393958568,0.28787993274271589,0.09792388528783233}, {0.99999999999988631,0.99999999999927147,0.99999999999582456,0.99999999997845523,0.99999999989927768,0.99999999957078767,0.99999999832336184,0.99999999396413419,0.99999997987450318,0.99999993755407834,0.9999998188937127,0.99999950700571938,0.99999873547186591,0.9999969324491903,0.99999293787666288,0.99998451990227077,0.99996759306794336,0.99993501992508238,0.99987486504878031,0.99976797159956077,0.9995847503515175,0.99928111192179192,0.9987935342988058,0.99803333631543367,0.99688031812819178,0.9951760261553273,0.99271699719682727,0.98924843109013383,0.98445883116743083,0.97797623518666488,0.96936673289691733,0.95813602271021359,0.94373478605275707,0.92556863406861256,0.90301328151357385,0.87543539763040867,0.84221924635075684,0.80279874134324125,0.75669390863372987,0.70355000514714194,0.64317675898520466,0.5755844906351516,0.50101338937930906,0.41995211127844712,0.33314226457763807,0.24156631953888363,0.14641798429058792,0.049055967305077885}, {0.99999999999992983,0.99999999999981715,0.99999999999953715,0.99999999999886124,0.99999999999727396,0.9999999999936463,0.99999999998556877,0.99999999996803313,0.99999999993088839,0.99999999985405608,0.9999999996987543,0.99999999939177686,0.9999999987979834,0.99999999767323666,0.99999999558563357,0.99999999178645604,0.9999999850030763,0.99999997311323585,0.99999995264266439,0.99999991800479471,0.99999986037121458,0.9999997660233324,0.9999996139885502,0.9999993727073353,0.99999899541068993,0.99999841381096466,0.99999752962380506,0.9999962033471661,0.99999423962761658,0.9999913684483448,0.99998722128200057,0.99998130127012064,0.99997294642523216,0.99996128480785662,0.99994518061445858,0.99992317012928922,0.99989338654759252,0.99985347277311132,0.99980048143113831,0.99973076151980844,0.9996398313456003,0.99952223765121717,0.99937140114093759,0.99917944893488586,0.99893703483351215,0.99863314864067743,0.99825491617199624,0.99778739195890642,0.99721334704346865,0.99651305464025375,0.99566407681695313,0.99464105571251116,0.99341551316926402,0.99195566300267757,0.99022624046752772,0.98818835380074255,0.98579936302528337,0.9830127914811011,0.97977827580061572,0.97604156025657673,0.97174454156548729,0.96682537031235583,0.9612186151511164,0.9548554958050226,0.94766419061515306,0.93957022393327472,0.93049693799715338,0.92036605303195274,0.90909831816302034,0.89661425428007602,0.88283498824466888,0.86768317577564591,0.85108400798784867,0.83296629391941079,0.81326360850297374,0.79191549237614201,0.76886868676824649,0.74407838354734734,0.71750946748732403,0.68913772506166759,0.65895099174335003,0.62695020805104285,0.59315035359195312,0.55758122826077816,0.52028805069123008,0.48133184611690499,0.44078959903390086,0.39875415046723772,0.3553338251650745,0.31065178055284592,0.26484507658344791,0.218063473469712,0.1704679723820105,0.12222912220155764,0.073525122985671293,0.024539763574649157}, {0.99999999999994504,0.99999999999991063,0.99999999999985567,0.99999999999976874,0.99999999999963207,0.9999999999994188,0.9999999999990884,0.99999999999857991,0.99999999999780287,0.99999999999662348,0.99999999999484512,0.99999999999218125,0.99999999998821665,0.99999999998235345,0.99999999997373656,0.9999999999611503,0.99999999994287725,0.99999999991650601,0.99999999987867016,0.99999999982469845,0.99999999974814635,0.99999999964017294,0.99999999948871821,0.99999999927742189,0.99999999898420988,0.99999999857945798,0.99999999802361939,0.99999999726417366,0.99999999623172697,0.99999999483505064,0.99999999295480446,0.9999999904356327,0.9999999870762647,0.99999998261717338,0.99999997672526708,0.99999996897499022,0.9999999588251014,0.99999994559027294,0.99999992840651408,0.99999990618926848,0.99999987758285502,0.99999984089973593,0.99999979404787598,0.99999973444423285,0.99999965891215925,0.9999995635602319,0.99999944363972881,0.99999929337766846,0.99999910578199569,0.99999887241516183,0.99999858313198442,0.99999822577731134,0.99999778583863519,0.9999972460484261,0.99999658593057072,0.99999578128492839,0.99999480360364879,0.99999361941253884,0.99999218953043356,0.99999046823921378,0.99998840235683317,0.99998593020547477,0.99998298046675649,0.99997947091575146,0.99997530702549198,0.99997038043358921,0.99996456726262606,0.99995772628607793,0.99994969693168922,0.99994029711447929,0.99992932089188413,0.99991653593395113,0.99990168080200281,0.99988446202976611,0.99986455100163496,0.99984158062348205,0.99981514178227304,0.99978477959165113,0.99974998942164883,0.99971021271175098,0.99966483256766459,0.99961316914334686,0.99955447481109672,0.99948792912382323,0.99941263357495247,0.9993276061628299,0.99923177576789879,0.99912397635238981,0.99900294099372877,0.99886729576436373,0.99871555347220875,0.99854610727741266,0.99835722420266371,0.99814703855574838,0.99791354528457699,0.99765459328637784,0.99736787869423538,0.99705093816560908,0.99670114219891259,0.99631568850566088,0.99589159546710015,0.99542569570562278,0.99491462980263878,0.9943548401959208,0.99374256529076155,0.99307383382058434,0.99234445949391814,0.99155003596589164,0.990685932173615,0.989747288075987,0.9887290108396023,0.98762577151351061,0.98643200223660843,0.98514189402239793,0.98374939516673121,0.98224821032494103,0.98063180030544861,0.97889338262749392,0.97702593289105788,0.97502218700730625,0.97287464433796378,0.97057557179190035,0.96811700892685626,0.96549077410362039,0.96268847173907823,0.9597015007033366,0.95652106390458091,0.95313817910339371,0.94954369099593627,0.94572828460263214,0.94168249999576925,0.93739674839571907,0.93286132966124002,0.92806645119455511,0.9230022482765543,0.91765880584154924,0.91202618169448679,0.90609443116640409,0.89985363319617007,0.89329391781821088,0.88640549502697863,0.87917868497938934,0.87160394948637765,0.86367192473410515,0.85537345516427143,0.84669962843146362,0.83764181134359994,0.82819168667935705,0.81834129076409778,0.80808305167333849,0.79740982792031223,0.78631494747181951,0.77479224692443527,0.76283611066139234,0.7504415097992404,0.73760404072282515,0.72431996299740742,0.71058623643800578,0.69640055710845916,0.68176139201642727,0.66666801226573758,0.65112052442430413,0.63511989986442174,0.61866800183272797,0.60176761000963341,0.58442244232266394,0.56663717378501877,0.54841745213979232,0.52976991010177454,0.51070217400255813,0.49122286866081144,0.47134161831799842,0.45106904350045196,0.43041675369143706,0.40939733572152948,0.3880243378121177,0.36631224923490407,0.34427647557970487,0.32193330965336914,0.29929989806396046,0.27639420357617861,0.25323496335600021,0.22984164325436074,0.20623438831102875,0.18243396969028913,0.1584617282892995,0.13433951528767221,0.11008962993262801,0.085734754877651045,0.061297889413659976,0.036802280950025079,0.012271355118082201}, }, weigths = { {1.3581784274539089e-012,2.1431204556943039e-007,0.00026620051375271687,0.018343166989927839,0.23002239451478868,0.96597657941230108,1.5707963267948966}, {1.1631165814255782e-009,1.1983701363170719e-005,0.0029025177479013132,0.076385743570832304,0.53107827542805397,1.3896147592472563}, {4.9378538776631926e-011,1.8687282268736407e-008,1.8263320593710658e-006,6.2482559240744075e-005,0.00094994680428346862,0.0077426010260642402,0.039175005493600777,0.13742210773316771,0.36046141846934365,0.7374378483615478,1.1934630258491568,1.523283718634705}, {8.6759314149796041e-012,2.5216347918530147e-010,4.8760060974240624e-009,6.583518512718339e-008,6.4777566035929716e-007,4.8237182032615495e-006,2.8110164327940134e-005,0.00013205234125609973,0.00051339382406790333,0.0016908739981426396,0.004816298143928463,0.012083543599157953,0.027133510013712,0.055289683742240581,0.10343215422333289,0.17932441211072828,0.29024067931245418,0.44083323627385823,0.63040513516474361,0.85017285645662,1.0816349854900702,1.2974757504249779,1.4660144267169657,1.5587733555333301}, {3.4841937670261058e-012,2.0989335404511467e-011,1.130605534749468e-010,5.4828357797094976e-010,2.409177325647594e-009,9.649888896108962e-009,3.543477717142195e-008,1.199244278290277e-007,3.7595411862360629e-007,1.0968835125901263e-006,2.9916615878138786e-006,7.6595758525203149e-006,1.8481813599879215e-005,4.2183183841757599e-005,9.1390817490710112e-005,0.00018856442976700316,0.00037166693621677759,0.00070185951568424226,0.0012733279447082382,0.0022250827064786423,0.003754250977431834,0.0061300376320830297,0.0097072237393916877,0.01493783509605013,0.022379471063648473,0.032698732726609031,0.046668208054846609,0.065155533432536203,0.089103139240941459,0.11949741128869591,0.15732620348436613,0.20352399885860173,0.25890463951405351,0.32408253961152889,0.39938474152571712,0.48475809121475538,0.57967810308778756,0.68306851634426369,0.79324270082051662,0.90787937915489525,1.0240449331118113,1.1382722433763053,1.2467012074518575,1.3452788847662516,1.4300083548722995,1.4972262225410362,1.543881116176959,1.5677814313072218}, {2.1835922099233607e-012,5.518236946817488e-012,1.3542512912336273e-011,3.230446433325236e-011,7.4967397573818219e-011,1.6939457789411645e-010,3.7299501843052787e-010,8.0099784479729664e-010,1.6788897682161906e-009,3.437185674465009e-009,6.8784610955899e-009,1.3464645522302038e-008,2.5799568229535891e-008,4.8420950198072366e-008,8.9071395140242379e-008,1.6069394579076223e-007,2.8449923659159806e-007,4.9458288702754198e-007,8.4473756384859861e-007,1.4183067155493917e-006,2.3421667208528095e-006,3.8061983264644897e-006,6.0899100320949032e-006,9.598194128378471e-006,1.4908514031870607e-005,2.2832118109036146e-005,3.4492124759343198e-005,5.1421497447658797e-005,7.5683996586201475e-005,0.00011002112846666696,0.00015802788400701192,0.00022435965205008549,0.00031497209186021199,0.00043739495615911686,0.00060103987991147413,0.00081754101332469483,0.0011011261134519382,0.0014690143599429789,0.0019418357759843675,0.0025440657675291729,0.00330446699403483,0.0042565295990178572,0.0054388997976239977,0.0068957859690660034,0.0086773307495391812,0.010839937168255907,0.01344653660528573,0.016566786254247574,0.020277183817500124,0.024661087314753281,0.029808628117310124,0.035816505604196434,0.042787652157725675,0.050830757572570467,0.060059642358636298,0.070592469906866989,0.082550788110701726,0.096058391865189455,0.11123999898874452,0.12821973363120098,0.14711941325785691,0.16805663794826914,0.19114268413342747,0.21648020911729615,0.24416077786983989,0.2742622296890681,0.3068459094179169,0.34195379592301678,0.37960556938665158,0.41979566844501548,0.46249039805536774,0.50762515883190806,0.55510187800363342,0.6047867305784036,0.6565082461316275,0.71005590120546891,0.76517929890895608,0.82158803526696467,0.87895234555278201,0.93690461274566783,0.99504180404613263,1.0529288799552665,1.1101031939653403,1.1660798699324344,1.2203581095793581,1.2724283455378627,1.3217801174437727,1.3679105116808963,1.4103329714462589,1.4485862549613224,1.482243297885538,1.5109197230741696,1.5342817381543032,1.5520531698454121,1.5640214037732321,1.5700420292795931}, {1.7237644036042717e-012,2.7608587671398282e-012,4.3888651899779303e-012,6.9255280152681376e-012,1.0849161834337119e-011,1.6874519343915022e-011,2.6061960502805292e-011,3.9973389519930265e-011,6.0893387064380662e-011,9.2140564226518881e-011,1.3850287525834143e-010,2.0684203539029217e-010,3.0692702078723327e-010,4.525757610415382e-010,6.6320863470162091e-010,9.6594851858099294e-010,1.3984414312565442e-009,2.0126210218867171e-009,2.8797013464471103e-009,4.0967579139685196e-009,5.7953495730966062e-009,8.1527464828576535e-009,1.1406465554850481e-008,1.5872978090968231e-008,2.1971648917089348e-008,3.0255196464899464e-008,4.1448233558505381e-008,5.649576387167062e-008,7.6623873974817583e-008,1.0341528040745607e-007,1.3890286996035951e-007,1.8568491370025131e-007,2.4706624511249697e-007,3.2723037330517557e-007,4.314482558716538e-007,5.6633028402050766e-007,7.401289349090861e-007,9.6310052117659242e-007,1.247935512117745e-006,1.6102680094507651e-006,2.0692761257364667e-006,2.6483862254043407e-006,3.3760952348055106e-006,4.2869264939998223e-006,5.4225358918240326e-006,6.8329862774218501e-006,8.5782093537079076e-006,1.072967540685234e-005,1.3372292284532372e-005,1.6606555976508335e-005,2.0550975944934244e-005,2.5344798968850108e-005,3.115105567744835e-005,3.8159954120245754e-005,4.6592644630494618e-005,5.6705379853932874e-005,6.8794093113496371e-005,8.3199417240036467e-005,0.00010031216460112419,0.00012057928729056995,0.00014451033429094585,0.00017268441988592921,0.00020575771467998817,0.00024447146728689159,0.00028966056108877171,0.00034226260646297687,0.00040332756454954089,0.00047402789401816719,0.00055566920742578549,0.00064970141867429037,0.00075773035782735918,0.00088152982417296992,0.001023054042974541,0.0011844504858902771,0.0013680730096097039,0.001576495261910556,0.0018125242991288641,0.0020792143540086659,0.0023798806881004382,0.0027181134583502261,0.0030977915233008206,0.0035230961104429862,0.0039985242627335309,0.0045289019791562883,0.0051193969614537812,0.0057755308768065484,0.0065031910442825787,0.0073086414513132475,0.0081985330052611986,0.0091799129243109005,0.010260233171410768,0.011447357834799755,0.012749569358731162,0.01417557352833046,0.015734503113059795,0.01743592007397746,0.019289816240845598,0.02130661236612607,0.023497155463988527,0.025872714343617643,0.028444973247334235,0.03122602350533174,0.034228353120175692,0.037464834195628967,0.040948708125867296,0.04469356846276553,0.048713341380701429,0.053022263660287172,0.05763485811465472,0.062565906384455097,0.067830419030657965,0.073443602857638762,0.079420825403008155,0.085777576535268185,0.092529427105778453,0.099691984607788567,0.10728084580255642,0.11531154628093733,0.12379950693841295,0.13275997735244552,0.14220797606340183,0.15215822777419971,0.16262509749938431,0.17362252171163128,0.18516393655277549,0.19726220319743717,0.20992953048020752,0.22317739492218458,0.23701645831941898,0.25145648308451035,0.26650624556313512,0.28217344757959606,0.29846462649944494,0.31538506413267808,0.3329386948377478,0.35112801322442522,0.36995398189211387,0.38941593967921201,0.4095115109381936,0.43023651638978894,0.45158488614754488,0.47354857554061397,0.49611748439731618,0.51927938048424627,0.54301982782484282,0.5673221206467387,0.59216722372820685,0.6175337199299088,0.6433977657082528,0.66973305541029093,0.69651079514654679,0.72369968702683019,0.75126592452435681,0.77917319970479793,0.80738272301876302,0.83585325630826712,0.86454115961966893,0.89340045234719589,0.92238288915245514,0.9514380510163527,0.98051345168085502,1.0095546596294298,1.0385054356373922,1.0673078857975038,1.0959026297929721,1.1242289840506032,1.1522251592625474,1.1798284716173337,1.206975566931308,1.2336026567219467,1.2596457651166706,1.2850409853467271,1.3097247444374396,1.333634074575756,1.3567068895156054,1.3788822642731373,1.4001007162694445,1.4203044859996912,1.4394378152464069,1.4574472208125486,1.4742817617280797,1.4898932978832971,1.5042367380636772,1.5172702754050547,1.5289556083545806,1.5392581453118817,1.5481471912355573,1.5555961146316604,1.5615824934918106,1.5660882389174613,1.5690996953516689,1.570607716538275}, }, }
mit
mattyx14/otxserver
data/scripts/talkactions/god/add_skill.lua
2
1979
local function getSkillId(skillName) if skillName == "club" then return SKILL_CLUB elseif skillName == "sword" then return SKILL_SWORD elseif skillName == "axe" then return SKILL_AXE elseif skillName:sub(1, 4) == "dist" then return SKILL_DISTANCE elseif skillName:sub(1, 6) == "shield" then return SKILL_SHIELD elseif skillName:sub(1, 4) == "fish" then return SKILL_FISHING else return SKILL_FIST end end local function getExpForLevel(level) level = level - 1 return ((50 * level * level * level) - (150 * level * level) + (400 * level)) / 3 end local addSkill = TalkAction("/addskill") function addSkill.onSay(player, words, param) if not player:getGroup():getAccess() or player:getAccountType() < ACCOUNT_TYPE_GOD then return true end if param == "" then player:sendCancelMessage("Command param required.") return false end local split = param:split(",") if not split[2] then player:sendCancelMessage("Insufficient parameters.") return false end local target = Player(split[1]) if not target then player:sendCancelMessage("A player with that name is not online.") return false end -- Trim left split[2] = split[2]:gsub("^%s*(.-)$", "%1") local count = 1 if split[3] then count = tonumber(split[3]) end local ch = split[2]:sub(1, 1) if ch == "l" or ch == "e" then targetLevel = target:getLevel() + count targetExp = getExpForLevel(targetLevel) addExp = targetExp - target:getExperience() target:addExperience(addExp, false) elseif ch == "m" then for i = 1, count do target:addManaSpent(target:getVocation():getRequiredManaSpent(target:getBaseMagicLevel() + 1) - target:getManaSpent(), true) end else local skillId = getSkillId(split[2]) for i = 1, count do target:addSkillTries(skillId, target:getVocation():getRequiredSkillTries(skillId, target:getSkillLevel(skillId) + 1) - target:getSkillTries(skillId), true) end end return false end addSkill:separator(" ") addSkill:register()
gpl-2.0
mattyx14/otxserver
data/monster/humanoids/troll.lua
2
2920
local mType = Game.createMonsterType("Troll") local monster = {} monster.description = "a troll" monster.experience = 20 monster.outfit = { lookType = 15, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.raceId = 15 monster.Bestiary = { class = "Humanoid", race = BESTY_RACE_HUMANOID, toKill = 250, FirstUnlock = 10, SecondUnlock = 100, CharmsPoints = 5, Stars = 1, Occurrence = 0, Locations = "In many dungeons around Tibia like the troll cave in Thais, south of Carlin (out the east \z exit and down the hole), Island of Destiny, Edron Troll Cave, and in Ab'Dendriel. Also found in Rookgaard." } monster.health = 50 monster.maxHealth = 50 monster.race = "blood" monster.corpse = 5960 monster.speed = 126 monster.manaCost = 290 monster.changeTarget = { interval = 4000, chance = 0 } monster.strategiesTarget = { nearest = 100, } monster.flags = { summonable = true, attackable = true, hostile = true, convinceable = true, pushable = true, rewardBoss = false, illusionable = true, canPushItems = false, canPushCreatures = false, staticAttackChance = 90, targetDistance = 1, runHealth = 15, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "Grrr", yell = false}, {text = "Groar", yell = false}, {text = "Gruntz!", yell = false}, {text = "Hmmm, bugs", yell = false}, {text = "Hmmm, dogs", yell = false} } monster.loot = { {id = 3003, chance = 7950}, -- rope {name = "gold coin", chance = 65300, maxCount = 12}, {name = "silver amulet", chance = 80}, {name = "hand axe", chance = 18000}, {name = "spear", chance = 13000}, {name = "studded club", chance = 5000}, {name = "leather helmet", chance = 12000}, {id = 3412, chance = 4730}, -- wooden shield {name = "leather boots", chance = 10000}, {name = "meat", chance = 15000}, {name = "bunch of troll hair", chance = 1000}, {id = 23986, chance = 1000} -- heavy old tome } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -15} } monster.defenses = { defense = 10, armor = 10 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 20}, {type = COMBAT_EARTHDAMAGE, percent = -10}, {type = COMBAT_FIREDAMAGE, percent = 0}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 0}, {type = COMBAT_HOLYDAMAGE , percent = 10}, {type = COMBAT_DEATHDAMAGE , percent = -10} } monster.immunities = { {type = "paralyze", condition = false}, {type = "outfit", condition = false}, {type = "invisible", condition = false}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
mnemnion/loon
src/mods/peg/core-rules.lua
1
1231
-- Core Syntax Rules -- A collection of useful regular patterns local lpeg = require "lpeg" local epeg = require "peg/epeg" local match = lpeg.match -- match a pattern against a string local P = lpeg.P -- match a string literally local S = lpeg.S -- match anything in a set local R = epeg.R -- match anything in a range local B = lpeg.B local C = lpeg.C -- captures a match local Csp = epeg.Csp -- captures start and end position of match local Ct = lpeg.Ct -- a table with all captures from the pattern local V = lpeg.V -- create a variable within a grammar local Cmt = lpeg.Cmt local digit = R"09" local letter = R"AZ" + R"az" local int = digit^1 local float = digit^1 * P"." * digit^1 * ((P"e" + P"E") * digit^1)^0 local escape = -P"\\" * P(1) + P"\\" * P(1) local string_single = P"'" * (-P"'" * escape)^0 * P"'" local string_double = P'"' * (-P'"' * escape)^0 * P'"' local string_backtick = P"`" * (-P"`" * escape)^0 * P"`" local strings = string_single + string_double + string_backtick return { digit = digit, letter = letter, int = int, float = float, strings = strings, escape = escape, string_single = string_single, string_double = string_double, string_back = string_backtick }
mit
bullno1/Akuma
premake4.lua
1
1172
solution "Akuma" configurations {"Develop"} location "build" project "Akuma" kind "ConsoleApp" language "C++" targetdir "bin" files { "src/**.h", "src/main.cpp", "src/Simulator.cpp", "src/Input.cpp", "src/FileWatcher/FileWatcher.cpp" } includedirs { "src", os.getenv("MOAI_INCLUDE") } libdirs { "deps", os.getenv("MOAI_LIB") } debugargs { "iPhone_portrait", "../samples/basic/main.lua" } links { "moaicore", "moaiext-luaext", "moaiext-untz", "SDL", "moai-lua" } defines { "BOOST_FILESYSTEM_VERSION=3" } configuration "windows" defines { "WIN32", "_CONSOLE" } links { "opengl32", "advapi32", "ws2_32", "iphlpapi", "user32", "gdi32", "psapi", "dsound", "strmiids", "rpcrt4" } files { "src/FileWatcher/FileWatcherWin32.cpp", "src/Akuma.ico", "src/Akuma.rc" } excludes { "src/FileWatcher/FileWatcherLinux.h", "src/FileWatcher/FileWatcherOSX.h" } configuration "Develop" defines { "NDEBUG" } flags { "Optimize", "OptimizeSpeed", "Symbols", "NoEditAndContinue" }
mit
nitheeshkl/kln_awesome
awesome_3.4/themes/redhalo/theme.lua
1
5141
-- redhalo, awesome3 theme --{{{ Main require("awful.util") theme = {} home = os.getenv("HOME") config = "/home/kln/.config/awesome" shared = "/home/kln/.config/awesome" --config = awful.util.getdir("config") --shared = "/usr/share/awesome" if not awful.util.file_readable(shared .. "/icons/awesome16.png") then shared = "/usr/share/local/awesome" end sharedicons = shared .. "/icons" sharedthemes = shared .. "/themes" themes = config .. "/themes" themename = "/redhalo" if not awful.util.file_readable(themes .. themename .. "/theme.lua") then themes = sharedthemes end themedir = themes .. themename wallpaper1 = themedir .. "/background.jpg" wallpaper2 = themedir .. "/background.png" wallpaper3 = sharedthemes .. "/zenburn/zenburn-background.png" wallpaper4 = sharedthemes .. "/default/background.png" wpscript = home .. "/.wallpaper" if awful.util.file_readable(wallpaper1) then theme.wallpaper_cmd = { "awsetbg " .. wallpaper1 } elseif awful.util.file_readable(wallpaper2) then theme.wallpaper_cmd = { "awsetbg " .. wallpaper2 } elseif awful.util.file_readable(wpscript) then theme.wallpaper_cmd = { "sh " .. wpscript } elseif awful.util.file_readable(wallpaper3) then theme.wallpaper_cmd = { "awsetbg " .. wallpaper3 } else theme.wallpaper_cmd = { "awsetbg " .. wallpaper4 } end if awful.util.file_readable(config .. "/vain/init.lua") then theme.useless_gap_width = "3" end --}}} theme.font = "profont 8" theme.fg_normal = "#bcbcbc" --theme.fg_normal = "#f8f8f8" theme.fg_focus = "#262729" theme.fg_urgent = "#262729" --theme.fg_title = "#66d9ef" theme.fg_title = "#34bdef" theme.fg_disabled = "#262729" theme.bg_normal = "#262729" theme.bg_focus = "#a6e22e" theme.bg_urgent = "#f92671" theme.bg_disabled = "#5e7175" theme.bg_hover = "#5e7175" theme.border_width = 0 theme.border_normal = "#505050" theme.border_focus = "#292929" theme.border_marked = "#ce5666" --{{{ Taglist icons --theme.taglist_squares = true --theme.taglist_squares_sel = themedir .. "/taglist/squaref_b-blue.png" --theme.taglist_squares_unsel = themedir .. "/taglist/squaref_b-green.png" --}}} --{{{ F-f-float theme.tasklist_floating_icon = themedir .. "/layouts-huge/floating-greyish.png" --}}} -- {{{ Layout icons theme.layout_tile = themedir .. "/layouts-huge/tile-blue.png" theme.layout_tileleft = themedir .. "/layouts-huge/tileleft-red.png" theme.layout_tilebottom = themedir .. "/layouts-huge/tilebottom-green.png" theme.layout_tiletop = themedir .. "/layouts-huge/tiletop-blue.png" theme.layout_fairv = themedir .. "/layouts-huge/fairv-red.png" theme.layout_fairh = themedir .. "/layouts-huge/fairh-green.png" theme.layout_spiral = themedir .. "/layouts-huge/spiral-blue.png" theme.layout_dwindle = themedir .. "/layouts-huge/dwindle-red.png" theme.layout_max = themedir .. "/layouts-huge/max-green.png" theme.layout_fullscreen = themedir .. "/layouts-huge/fullscreen-blue.png" theme.layout_magnifier = themedir .. "/layouts-huge/magnifier-red.png" theme.layout_floating = themedir .. "/layouts-huge/floating-green.png" -- }}} -- {{{ Titlebar icons theme.titlebar_close_button_focus = themedir .. "/titlebar/close_focus-darkbrown.png" theme.titlebar_ontop_button_focus_active = themedir .. "/titlebar/ontop_focus_active-darkbrown.png" theme.titlebar_ontop_button_focus_inactive = themedir .. "/titlebar/ontop_focus_inactive-darkbrown.png" theme.titlebar_sticky_button_focus_active = themedir .. "/titlebar/sticky_focus_active-darkbrown.png" theme.titlebar_sticky_button_focus_inactive = themedir .. "/titlebar/sticky_focus_inactive-darkbrown.png" theme.titlebar_floating_button_focus_active = themedir .. "/titlebar/floating_focus_active-darkbrown.png" theme.titlebar_floating_button_focus_inactive = themedir .. "/titlebar/floating_focus_inactive-darkbrown.png" theme.titlebar_maximized_button_focus_active = themedir .. "/titlebar/maximized_focus_active-darkbrown.png" theme.titlebar_maximized_button_focus_inactive = themedir .. "/titlebar/maximized_focus_inactive-darkbrown.png" theme.titlebar_close_button_normal = themedir .. "/titlebar/close_normal-red.png" theme.titlebar_ontop_button_normal_active = themedir .. "/titlebar/ontop_normal_active-red.png" theme.titlebar_ontop_button_normal_inactive = themedir .. "/titlebar/ontop_normal_inactive-green.png" theme.titlebar_sticky_button_normal_active = themedir .. "/titlebar/sticky_normal_active-green.png" theme.titlebar_sticky_button_normal_inactive = themedir .. "/titlebar/sticky_normal_inactive-blue.png" theme.titlebar_floating_button_normal_active = themedir .. "/titlebar/floating_normal_active-red.png" theme.titlebar_floating_button_normal_inactive = themedir .. "/titlebar/floating_normal_inactive-blue.png" theme.titlebar_maximized_button_normal_active = themedir .. "/titlebar/maximized_normal_active-red.png" theme.titlebar_maximized_button_normal_inactive = themedir .. "/titlebar/maximized_normal_inactive-green.png" -- }}} theme.awesome_icon = themedir .. "/logo/awesome-red.png" return theme
gpl-2.0
amirhosein2233/uzzbot
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
CarabusX/Zero-K
LuaUI/savetable.lua
6
3715
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: savetable.lua -- brief: a human friendly table writer -- author: Dave Rodgers -- -- Copyright (C) 2007. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (table.save) then return end local indentString = '\t' local savedTables = {} -- setup a lua keyword map local keyWords = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" } local keyWordSet = {} for _, w in ipairs(keyWords) do keyWordSet[w] = true end keyWords = nil -- don't need the array anymore -------------------------------------------------------------------------------- local function encloseStr(s) return string.format('%q', s) end local function encloseKey(s) local wrap = not (string.find(s, '^%a[_%a%d]*$')) if (not wrap) then if (string.len(s) <= 0) then wrap = true end end if (not wrap) then if (keyWordSet[s]) then wrap = true end end if (wrap) then return string.format('[%q]', s) else return s end end local keyTypes = { ['string'] = true, ['number'] = true, ['boolean'] = true, } local valueTypes = { ['string'] = true, ['number'] = true, ['boolean'] = true, ['table'] = true, } local function CompareKeys(kv1, kv2) local k1, v1 = kv1[1], kv1[2] local k2, v2 = kv2[1], kv2[2] local ktype1 = type(k1) local ktype2 = type(k2) if (ktype1 ~= ktype2) then return (ktype1 > ktype2) end local vtype1 = type(v1) local vtype2 = type(v2) if ((vtype1 == 'table') and (vtype2 ~= 'table')) then return false end if ((vtype1 ~= 'table') and (vtype2 == 'table')) then return true end return (k1 < k2) end local function MakeSortedTable(t) local st = {} for k, v in pairs(t) do if (keyTypes[type(k)] and valueTypes[type(v)]) then table.insert(st, { k, v }) end end table.sort(st, CompareKeys) return st end local function SaveTable(t, file, indent) local indent = indent .. indentString local st = MakeSortedTable(t) for _, kv in ipairs(st) do local k, v = kv[1], kv[2] local ktype = type(k) local vtype = type(v) -- output the key if (ktype == 'string') then file:write(indent..encloseKey(k)..' = ') else file:write(indent..'['..tostring(k)..'] = ') end -- output the value if (vtype == 'string') then file:write(encloseStr(v)..',\n') elseif (vtype == 'number') then if (v == math.huge) then file:write('math.huge,\n') elseif (v == -math.huge) then file:write('-math.huge,\n') else file:write(tostring(v)..',\n') end elseif (vtype == 'boolean') then file:write(tostring(v)..',\n') elseif (vtype == 'table') then if (savedTables[v]) then error("table.save() does not support recursive tables") end if (next(v)) then savedTables[t] = true file:write('{\n') SaveTable(v, file, indent) file:write(indent..'},\n') savedTables[t] = nil else file:write('{},\n') -- empty table end end end end function table.save(t, filename, header) local file = io.open(filename, 'w') if (file == nil) then return end if (header) then file:write(header..'\n') end file:write('return {\n') if (type(t) == "table") or (type(t) == "metatable") then SaveTable(t, file, '') end file:write('}\n') file:close() for k, v in pairs(savedTables) do savedTables[k] = nil end end
gpl-2.0
mattyx14/otxserver
data/chatchannels/scripts/help.lua
2
3074
local CHANNEL_HELP = 7 local storage = 456112 local muted = Condition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT) muted:setParameter(CONDITION_PARAM_SUBID, CHANNEL_HELP) muted:setParameter(CONDITION_PARAM_TICKS, 3600000) function onSpeak(player, type, message) local playerAccountType = player:getAccountType() if player:getLevel() == 1 and playerAccountType == ACCOUNT_TYPE_NORMAL then player:sendCancelMessage("You may not speak into channels as long as you are on level 1.") return false end if player:getStorageValue(storage) > os.time() then player:sendCancelMessage("You are muted from the Help channel for using it inappropriately.") return false end if playerAccountType >= ACCOUNT_TYPE_TUTOR then if string.sub(message, 1, 6) == "!mute " then local targetName = string.sub(message, 7) local target = Player(targetName) if target then if playerAccountType > target:getAccountType() then if not target:getCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP) then target:addCondition(muted) target:setStorageValue(storage, os.time() + 180) sendChannelMessage(CHANNEL_HELP, TALKTYPE_CHANNEL_R1, target:getName() .. " has been muted by " .. player:getName() .. " for using Help Channel inappropriately.") else player:sendCancelMessage("That player is already muted.") end else player:sendCancelMessage("You are not authorized to mute that player.") end else player:sendCancelMessage(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE) end return false elseif string.sub(message, 1, 8) == "!unmute " then local targetName = string.sub(message, 9) local target = Player(targetName) if target then if playerAccountType > target:getAccountType() then if target:getStorageValue(storage) > os.time() then target:removeCondition(CONDITION_CHANNELMUTEDTICKS, CONDITIONID_DEFAULT, CHANNEL_HELP) sendChannelMessage(CHANNEL_HELP, TALKTYPE_CHANNEL_R1, target:getName() .. " has been unmuted.") target:setStorageValue(storage, -1) else player:sendCancelMessage("That player is not muted.") end else player:sendCancelMessage("You are not authorized to unmute that player.") end else player:sendCancelMessage(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE) end return false end end if type == TALKTYPE_CHANNEL_Y then if playerAccountType >= ACCOUNT_TYPE_TUTOR or player:hasFlag(PlayerFlag_TalkOrangeHelpChannel) then type = TALKTYPE_CHANNEL_O end elseif type == TALKTYPE_CHANNEL_O then if playerAccountType < ACCOUNT_TYPE_TUTOR and not player:hasFlag(PlayerFlag_TalkOrangeHelpChannel) then type = TALKTYPE_CHANNEL_Y end elseif type == TALKTYPE_CHANNEL_R1 then if playerAccountType < ACCOUNT_TYPE_GAMEMASTER and not player:hasFlag(PlayerFlag_CanTalkRedChannel) then if playerAccountType >= ACCOUNT_TYPE_TUTOR or player:hasFlag(PlayerFlag_TalkOrangeHelpChannel) then type = TALKTYPE_CHANNEL_O else type = TALKTYPE_CHANNEL_Y end end end return type end
gpl-2.0
mattyx14/otxserver
data/scripts/spells/monster/gaz'haragoth_summon.lua
2
1039
local spell = Spell("instant") function spell.onCastSpell(creature, var) local t, spectator = Game.getSpectators(creature:getPosition(), false, false, 5, 5, 5, 5) local check = 0 if #t ~= nil then for i = 1, #t do spectator = t[i] if spectator:getName() == "Minion Of Gaz'haragoth" then check = check + 1 end end end local hp = (creature:getHealth()/creature:getMaxHealth())* 100 if ((check < 2) and hp <= 95) or ((check < 4) and hp <= 75) or ((check < 6) and hp <= 55) or ((check < 10) and hp <= 35) then for j = 1, 5 do creature:say("Minions! Follow my call!", TALKTYPE_ORANGE_1) end for k = 1, 2 do local monster = Game.createMonster("minion of gaz'haragoth", creature:getPosition(), true, false) if not monster then return end creature:getPosition():sendMagicEffect(CONST_ME_SOUND_RED) end else end return true end spell:name("gaz'haragoth summon") spell:words("###125") spell:blockWalls(true) spell:needLearn(true) spell:register()
gpl-2.0
CarabusX/Zero-K
scripts/commrecon.lua
4
15880
include "constants.lua" include "JumpRetreat.lua" -------------------------------------------------------------------------------- -- pieces -------------------------------------------------------------------------------- local base = piece 'base' local pelvis = piece 'pelvis' local turret = piece 'turret' local torso = piece 'torso' local head = piece 'head' local armhold = piece 'armhold' local ruparm = piece 'ruparm' local rarm = piece 'rarm' local rloarm = piece 'rloarm' local luparm = piece 'luparm' local larm = piece 'larm' local lloarm = piece 'lloarm' local rupleg = piece 'rupleg' local lupleg = piece 'lupleg' local lloleg = piece 'lloleg' local rloleg = piece 'rloleg' local rfoot = piece 'rfoot' local lfoot = piece 'lfoot' local gun = piece 'gun' local flare = piece 'flare' local rsword = piece 'rsword' local lsword = piece 'lsword' local jet1 = piece 'jet1' local jet2 = piece 'jet2' local jx1 = piece 'jx1' local jx2 = piece 'jx2' local stab = piece 'stab' local nanospray = piece 'nanospray' local grenade = piece 'grenade' local smokePiece = {torso} local nanoPieces = {nanospray} -------------------------------------------------------------------------------- -- constants -------------------------------------------------------------------------------- local SIG_RESTORE = 1 local SIG_AIM = 2 local SIG_AIM_2 = 4 --local SIG_AIM_3 = 8 --step on -------------------------------------------------------------------------------- -- vars -------------------------------------------------------------------------------- local restoreHeading, restorePitch = 0, 0 local canDgun = UnitDefs[unitDefID].canDgun local dead = false local bMoving = false local bAiming = false local shieldOn = true local inJumpMode = false -------------------------------------------------------------------------------- -- funcs -------------------------------------------------------------------------------- local function BuildPose(heading, pitch) Turn(luparm, x_axis, math.rad(-60), math.rad(250)) Turn(luparm, y_axis, math.rad(-15), math.rad(250)) Turn(luparm, z_axis, math.rad(-10), math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) Turn(larm, y_axis, math.rad(-30), math.rad(250)) Turn(larm, z_axis, math.rad(26), math.rad(250)) Turn(lloarm, y_axis, math.rad(-37), math.rad(250)) Turn(lloarm, z_axis, math.rad(-152), math.rad(450)) Turn(turret, y_axis, heading, math.rad(350)) Turn(lloarm, x_axis, -pitch, math.rad(250)) end local function RestoreAfterDelay() Signal(SIG_RESTORE) SetSignalMask(SIG_RESTORE) Sleep(6000) if not dead then if GetUnitValue(COB.INBUILDSTANCE) == 1 then BuildPose(restoreHeading, restorePitch) else Turn(turret, x_axis, 0, math.rad(150)) Turn(turret, y_axis, 0, math.rad(150)) --torso Turn(torso, x_axis, 0, math.rad(250)) Turn(torso, y_axis, 0, math.rad(250)) Turn(torso, z_axis, 0, math.rad(250)) --head Turn(head, x_axis, 0, math.rad(250)) Turn(head, y_axis, 0, math.rad(250)) Turn(head, z_axis, 0, math.rad(250)) -- at ease pose Turn(armhold, x_axis, math.rad(-45), math.rad(250)) --upspring at -45 Turn(ruparm, x_axis, 0, math.rad(250)) Turn(ruparm, y_axis, 0, math.rad(250)) Turn(ruparm, z_axis, 0, math.rad(250)) Turn(rarm, x_axis, math.rad(2), math.rad(250)) --up 2 Turn(rarm, y_axis, 0, math.rad(250)) Turn(rarm, z_axis, math.rad(-(-12)), math.rad(250)) --up -12 Turn(rloarm, x_axis, math.rad(47), math.rad(250)) --up 47 Turn(rloarm, y_axis, math.rad(76), math.rad(250)) --up 76 Turn(rloarm, z_axis, math.rad(-(-47)), math.rad(250)) --up -47 Turn(luparm, x_axis, math.rad(-9), math.rad(250)) --up -9 Turn(luparm, y_axis, 0, math.rad(250)) Turn(luparm, z_axis, 0, math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) --up 5 Turn(larm, y_axis, math.rad(-3), math.rad(250)) --up -3 Turn(larm, z_axis, math.rad(-(22)), math.rad(250)) --up 22 Turn(lloarm, x_axis, math.rad(92), math.rad(250)) -- up 82 Turn(lloarm, y_axis, 0, math.rad(250)) Turn(lloarm, z_axis, math.rad(-(94)), math.rad(250)) --upspring 94 -- done at ease Sleep(100) end bAiming = false end end local function Walk() if not bAiming then Turn(torso, x_axis, math.rad(12)) --tilt forward Turn(torso, y_axis, math.rad(3.335165)) end Move(pelvis, y_axis, 0) Turn(rupleg, x_axis, math.rad(5.670330)) Turn(lupleg, x_axis, math.rad(-26.467033)) Turn(lloleg, x_axis, math.rad(26.967033)) Turn(rloleg, x_axis, math.rad(26.967033)) Turn(rfoot, x_axis, math.rad(-19.824176)) Sleep(90) --had to + 20 to all sleeps in walk if not bAiming then Turn(torso, y_axis, math.rad(1.681319)) end Turn(rupleg, x_axis, math.rad(-5.269231)) Turn(lupleg, x_axis, math.rad(-20.989011)) Turn(lloleg, x_axis, math.rad(20.945055)) Turn(rloleg, x_axis, math.rad(41.368132)) Turn(rfoot, x_axis, math.rad(-15.747253)) Sleep(70) if not bAiming then Turn(torso, y_axis, 0) end Turn(rupleg, x_axis, math.rad(-9.071429)) Turn(lupleg, x_axis, math.rad(-12.670330)) Turn(lloleg, x_axis, math.rad(12.670330)) Turn(rloleg, x_axis, math.rad(43.571429)) Turn(rfoot, x_axis, math.rad(-12.016484)) Sleep(50) if not bAiming then Turn(torso, y_axis, math.rad(-1.77)) end Turn(rupleg, x_axis, math.rad(-21.357143)) Turn(lupleg, x_axis, math.rad(2.824176)) Turn(lloleg, x_axis, math.rad(3.560440)) Turn(lfoot, x_axis, math.rad(-4.527473)) Turn(rloleg, x_axis, math.rad(52.505495)) Turn(rfoot, x_axis, 0) Sleep(40) if not bAiming then Turn(torso, y_axis, math.rad(-3.15)) end Turn(rupleg, x_axis, math.rad(-35.923077)) Turn(lupleg, x_axis, math.rad(7.780220)) Turn(lloleg, x_axis, math.rad(8.203297)) Turn(lfoot, x_axis, math.rad(-12.571429)) Turn(rloleg, x_axis, math.rad(54.390110)) Sleep(50) if not bAiming then Turn(torso, y_axis, math.rad(-4.2)) end Turn(rupleg, x_axis, math.rad(-37.780220)) Turn(lupleg, x_axis, math.rad(10.137363)) Turn(lloleg, x_axis, math.rad(13.302198)) Turn(lfoot, x_axis, math.rad(-16.714286)) Turn(rloleg, x_axis, math.rad(32.582418)) Sleep(50) if not bAiming then Turn(torso, y_axis, math.rad(-3.15)) end Turn(rupleg, x_axis, math.rad(-28.758242)) Turn(lupleg, x_axis, math.rad(12.247253)) Turn(lloleg, x_axis, math.rad(19.659341)) Turn(lfoot, x_axis, math.rad(-19.659341)) Turn(rloleg, x_axis, math.rad(28.758242)) Sleep(90) if not bAiming then Turn(torso, y_axis, math.rad(-1.88)) end Turn(rupleg, x_axis, math.rad(-22.824176)) Turn(lupleg, x_axis, math.rad(2.824176)) Turn(lloleg, x_axis, math.rad(34.060440)) Turn(rfoot, x_axis, math.rad(-6.313187)) Sleep(70) if not bAiming then Turn(torso, y_axis, 0) end Turn(rupleg, x_axis, math.rad(-11.604396)) Turn(lupleg, x_axis, math.rad(-6.725275)) Turn(lloleg, x_axis, math.rad(39.401099)) Turn(lfoot, x_axis, math.rad(-13.956044)) Turn(rloleg, x_axis, math.rad(19.005495)) Turn(rfoot, x_axis, math.rad(-7.615385)) Sleep(50) if not bAiming then Turn(torso, y_axis, math.rad(1.88)) end Turn(rupleg, x_axis, math.rad(1.857143)) Turn(lupleg, x_axis, math.rad(-24.357143)) Turn(lloleg, x_axis, math.rad(45.093407)) Turn(lfoot, x_axis, math.rad(-7.703297)) Turn(rloleg, x_axis, math.rad(3.560440)) Turn(rfoot, x_axis, math.rad(-4.934066)) Sleep(40) if not bAiming then Turn(torso, y_axis, math.rad(3.15)) end Turn(rupleg, x_axis, math.rad(7.148352)) Turn(lupleg, x_axis, math.rad(-28.181319)) Turn(rfoot, x_axis, math.rad(-9.813187)) Sleep(50) if not bAiming then Turn(torso, y_axis, math.rad(4.2)) end Turn(rupleg, x_axis, math.rad(8.423077)) Turn(lupleg, x_axis, math.rad(-32.060440)) Turn(lloleg, x_axis, math.rad(27.527473)) Turn(lfoot, x_axis, math.rad(-2.857143)) Turn(rloleg, x_axis, math.rad(24.670330)) Turn(rfoot, x_axis, math.rad(-33.313187)) Sleep(70) end local function MotionControl() local moving, aiming local justmoved = true while true do moving = bMoving aiming = bAiming if moving then Walk() justmoved = true else if justmoved then Turn(rupleg, x_axis, 0, math.rad(200.071429)) Turn(rloleg, x_axis, 0, math.rad(200.071429)) Turn(rfoot, x_axis, 0, math.rad(200.071429)) Turn(lupleg, x_axis, 0, math.rad(200.071429)) Turn(lloleg, x_axis, 0, math.rad(200.071429)) Turn(lfoot, x_axis, 0, math.rad(200.071429)) if not aiming then Turn(torso, x_axis, 0) --untilt forward Turn(torso, y_axis, 0, math.rad(90.027473)) Turn(ruparm, x_axis, 0, math.rad(200.071429)) -- Turn(luparm, x_axis, 0, math.rad(200.071429)) end justmoved = false end Sleep(100) end end end function script.Create() --alert to dirt Turn(armhold, x_axis, math.rad(-45), math.rad(250)) --upspring at -45 Turn(ruparm, x_axis, 0, math.rad(250)) Turn(ruparm, y_axis, 0, math.rad(250)) Turn(ruparm, z_axis, 0, math.rad(250)) Turn(rarm, x_axis, math.rad(2), math.rad(250)) --up 2 Turn(rarm, y_axis, 0, math.rad(250)) Turn(rarm, z_axis, math.rad(-(-12)), math.rad(250)) --up -12 Turn(rloarm, x_axis, math.rad(47), math.rad(250)) --up 47 Turn(rloarm, y_axis, math.rad(76), math.rad(250)) --up 76 Turn(rloarm, z_axis, math.rad(-(-47)), math.rad(250)) --up -47 Turn(luparm, x_axis, math.rad(-9), math.rad(250)) --up -9 Turn(luparm, y_axis, 0, math.rad(250)) Turn(luparm, z_axis, 0, math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) --up 5 Turn(larm, y_axis, math.rad(-3), math.rad(250)) --up -3 Turn(larm, z_axis, math.rad(-(22)), math.rad(250)) --up 22 Turn(lloarm, x_axis, math.rad(92), math.rad(250)) -- up 82 Turn(lloarm, y_axis, 0, math.rad(250)) Turn(lloarm, z_axis, math.rad(-(94)), math.rad(250)) --upspring 94 Hide(flare) Hide(jx1) Hide(jx2) Hide(grenade) StartThread(MotionControl) StartThread(RestoreAfterDelay) StartThread(GG.Script.SmokeUnit, unitID, smokePiece) Spring.SetUnitNanoPieces(unitID, nanoPieces) end function script.StartMoving() bMoving = true end function script.StopMoving() bMoving = false end function script.AimFromWeapon(num) return armhold end local function AimRifle(heading, pitch, isDgun) --torso Turn(torso, x_axis, math.rad(15), math.rad(250)) Turn(torso, y_axis, math.rad(-25), math.rad(250)) Turn(torso, z_axis, 0, math.rad(250)) --head Turn(head, x_axis, math.rad(-15), math.rad(250)) Turn(head, y_axis, math.rad(25), math.rad(250)) Turn(head, z_axis, 0, math.rad(250)) --rarm Turn(ruparm, x_axis, math.rad(-83), math.rad(250)) Turn(ruparm, y_axis, math.rad(30), math.rad(250)) Turn(ruparm, z_axis, math.rad(-(10)), math.rad(250)) Turn(rarm, x_axis, math.rad(41), math.rad(250)) Turn(rarm, y_axis, math.rad(19), math.rad(250)) Turn(rarm, z_axis, math.rad(-(-3)), math.rad(250)) Turn(rloarm, x_axis, math.rad(18), math.rad(250)) Turn(rloarm, y_axis, math.rad(19), math.rad(250)) Turn(rloarm, z_axis, math.rad(-(14)), math.rad(250)) Turn(gun, x_axis, math.rad(15.0), math.rad(250)) Turn(gun, y_axis, math.rad(-15.0), math.rad(250)) Turn(gun, z_axis, math.rad(31), math.rad(250)) --larm Turn(luparm, x_axis, math.rad(-80), math.rad(250)) Turn(luparm, y_axis, math.rad(-15), math.rad(250)) Turn(luparm, z_axis, math.rad(-10), math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) Turn(larm, y_axis, math.rad(-77), math.rad(250)) Turn(larm, z_axis, math.rad(-(-26)), math.rad(250)) Turn(lloarm, x_axis, math.rad(65), math.rad(250)) Turn(lloarm, y_axis, math.rad(-37), math.rad(250)) Turn(lloarm, z_axis, math.rad(-152), math.rad(450)) WaitForTurn(ruparm, x_axis) Turn(turret, y_axis, heading, math.rad(350)) Turn(armhold, x_axis, - pitch, math.rad(250)) WaitForTurn(turret, y_axis) WaitForTurn(armhold, x_axis) WaitForTurn(lloarm, z_axis) StartThread(RestoreAfterDelay) return true end function script.AimWeapon(num, heading, pitch) if num >= 5 then Signal(SIG_AIM) SetSignalMask(SIG_AIM) bAiming = true return AimRifle(heading, pitch) elseif num == 3 then Signal(SIG_AIM) Signal(SIG_AIM_2) SetSignalMask(SIG_AIM_2) bAiming = true return AimRifle(heading, pitch, canDgun) elseif num == 2 or num == 4 then Sleep(100) return (shieldOn) end return false end function script.QueryWeapon(num) if num == 3 then return grenade elseif num == 2 or num == 4 then return torso end return flare end function script.FireWeapon(num) if num == 3 then EmitSfx(grenade, 1026) elseif num == 5 then EmitSfx(flare, 1024) end end function script.Shot(num) if num == 3 then EmitSfx(grenade, 1027) elseif num == 5 then EmitSfx(flare, 1025) end end local function JumpExhaust() while inJumpMode do EmitSfx(jx1, 1028) EmitSfx(jx2, 1028) Sleep(33) end end function beginJump() inJumpMode = true --[[ StartThread(JumpExhaust) --]] end function jumping() GG.PokeDecloakUnit(unitID, unitDefID) EmitSfx(jx1, 1028) EmitSfx(jx2, 1028) end function endJump() inJumpMode = false EmitSfx(base, 1029) end function script.StopBuilding() SetUnitValue(COB.INBUILDSTANCE, 0) restoreHeading, restorePitch = 0, 0 if not bAiming then StartThread(RestoreAfterDelay) end end function script.StartBuilding(heading, pitch) --larm restoreHeading, restorePitch = heading, pitch BuildPose(heading, pitch) SetUnitValue(COB.INBUILDSTANCE, 1) restoreHeading, restorePitch = heading, pitch end function script.QueryNanoPiece() GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),nanospray) return nanospray end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth dead = true -- Turn(turret, y_axis, 0, math.rad(500)) if severity <= 0.5 and not inJumpMode then Turn(base, x_axis, math.rad(80), math.rad(80)) Turn(turret, x_axis, math.rad(-16), math.rad(50)) Turn(turret, y_axis, 0, math.rad(90)) Turn(rloleg, x_axis, math.rad(9), math.rad(250)) Turn(rloleg, y_axis, math.rad(-73), math.rad(250)) Turn(rloleg, z_axis, math.rad(-(3)), math.rad(250)) Turn(lupleg, x_axis, math.rad(7), math.rad(250)) Turn(lloleg, y_axis, math.rad(21), math.rad(250)) Turn(lfoot, x_axis, math.rad(24), math.rad(250)) Sleep(200) --give time to fall Turn(ruparm, x_axis, math.rad(-48), math.rad(350)) Turn(ruparm, y_axis, math.rad(32), math.rad(350)) --was -32 Turn(luparm, x_axis, math.rad(-50), math.rad(350)) Turn(luparm, y_axis, math.rad(47), math.rad(350)) Turn(luparm, z_axis, math.rad(-(50)), math.rad(350)) Sleep(600) EmitSfx(turret, 1027) --impact --StartThread(burn) --Sleep((1000 * rand (2, 5))) Sleep(100) return 1 elseif severity <= 0.5 then Explode(gun, SFX.FALL + SFX.SMOKE + SFX.EXPLODE) Explode(head, SFX.FIRE + SFX.EXPLODE) Explode(pelvis, SFX.FIRE + SFX.EXPLODE) Explode(lloarm, SFX.FIRE + SFX.EXPLODE) Explode(luparm, SFX.FIRE + SFX.EXPLODE) Explode(lloleg, SFX.FIRE + SFX.EXPLODE) Explode(lupleg, SFX.FIRE + SFX.EXPLODE) Explode(rloarm, SFX.FIRE + SFX.EXPLODE) Explode(rloleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(ruparm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(rupleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(torso, SFX.SHATTER + SFX.EXPLODE) return 1 else Explode(gun, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(head, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(pelvis, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(lloarm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(luparm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(lloleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(lupleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(rloarm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(rloleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(ruparm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(rupleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(torso, SFX.SHATTER + SFX.EXPLODE) return 2 end end
gpl-2.0
mattyx14/otxserver
data/monster/quests/the_dream_courts/bosses/izcandar_the_banished.lua
2
2997
local mType = Game.createMonsterType("Izcandar the Banished") local monster = {} monster.description = "Izcandar the Banished" monster.experience = 6900 monster.outfit = { lookType = 1137, lookHead = 19, lookBody = 95, lookLegs = 76, lookFeet = 38, lookAddons = 2, lookMount = 0 } monster.health = 7600 monster.maxHealth = 7600 monster.race = "blood" monster.corpse = 6068 monster.speed = 250 monster.manaCost = 0 monster.changeTarget = { interval = 4000, chance = 10 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = true, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 90, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = true, canWalkOnFire = true, canWalkOnPoison = true } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, } monster.loot = { {name = "berserk potion", chance = 100000, maxCount = 10}, {name = "crystal coin", chance = 100000}, {name = "energy bar", chance = 100000}, {name = "giant sapphire", chance = 100000}, {name = "gold token", chance = 100000, maxCount = 2}, {name = "silver token", chance = 100000, maxCount = 2}, {name = "royal star", chance = 100000, maxCount = 100}, {name = "green gem", chance = 100000, maxCount = 2}, {name = "huge chunk of crude iron", chance = 25100}, {name = "mysterious remains", chance = 25000}, {name = "piggy bank", chance = 12800}, {name = "platinum coin", chance = 12000, maxCount = 10}, {name = "supreme health potion", chance = 12000, maxCount = 10}, {name = "ultimate mana potion", chance = 12000, maxCount = 20} } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -5} } monster.defenses = { defense = 0, armor = 76 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 0}, {type = COMBAT_EARTHDAMAGE, percent = 0}, {type = COMBAT_FIREDAMAGE, percent = 0}, {type = COMBAT_LIFEDRAIN, percent = 100}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 0}, {type = COMBAT_HOLYDAMAGE , percent = 0}, {type = COMBAT_DEATHDAMAGE , percent = 0} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType.onThink = function(monster, interval) end mType.onAppear = function(monster, creature) if monster:getType():isRewardBoss() then monster:setReward(true) end end mType.onDisappear = function(monster, creature) end mType.onMove = function(monster, creature, fromPosition, toPosition) end mType.onSay = function(monster, creature, type, message) end mType:register(monster)
gpl-2.0
mumuqz/luci
protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_ppp.lua
47
3692
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, username, password local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty*S*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6") ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_failure.write = keepalive_interval.write keepalive_failure.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
apache-2.0
fo369/luci-1505
protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_6rd.lua
72
2039
-- Copyright 2011-2012 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ipaddr, peeraddr, ip6addr, tunnelid, username, password local defaultroute, metric, ttl, mtu ipaddr = s:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" peeraddr = s:taboption("general", Value, "peeraddr", translate("Remote IPv4 address"), translate("This IPv4 address of the relay")) peeraddr.rmempty = false peeraddr.datatype = "ip4addr" ip6addr = s:taboption("general", Value, "ip6prefix", translate("IPv6 prefix"), translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>")) ip6addr.rmempty = false ip6addr.datatype = "ip6addr" ip6prefixlen = s:taboption("general", Value, "ip6prefixlen", translate("IPv6 prefix length"), translate("The length of the IPv6 prefix in bits")) ip6prefixlen.placeholder = "16" ip6prefixlen.datatype = "range(0,128)" ip6prefixlen = s:taboption("general", Value, "ip4prefixlen", translate("IPv4 prefix length"), translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses.")) ip6prefixlen.placeholder = "0" ip6prefixlen.datatype = "range(0,32)" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
apache-2.0
nitheeshkl/kln_awesome
awesome_3.5/lain/layout/centerfair.lua
1
5802
--[[ Licensed under GNU General Public License v2 * (c) 2014, projektile * (c) 2013, Luke Bonham * (c) 2010, Nicolas Estibals * (c) 2010-2012, Peter Hofmann --]] local tag = require("awful.tag") local beautiful = require("beautiful") local math = { ceil = math.ceil, floor = math.floor, max = math.max } local tonumber = tonumber local centerfair = { name = "centerfair" } function centerfair.arrange(p) -- Layout with fixed number of vertical columns (read from nmaster). -- Cols are centerded until there is nmaster columns, then windows -- are stacked in the slave columns, with at most ncol clients per -- column if possible. -- with nmaster=3 and ncol=1 you'll have -- (1) (2) (3) -- +---+---+---+ +-+---+---+-+ +---+---+---+ -- | | | | | | | | | | | | | -- | | 1 | | -> | | 1 | 2 | | -> | 1 | 2 | 3 | -> -- | | | | | | | | | | | | | -- +---+---+---+ +-+---+---+-+ +---+---+---+ -- (4) (5) -- +---+---+---+ +---+---+---+ -- | | | 3 | | | 2 | 4 | -- + 1 + 2 +---+ -> + 1 +---+---+ -- | | | 4 | | | 3 | 5 | -- +---+---+---+ +---+---+---+ -- A useless gap (like the dwm patch) can be defined with -- beautiful.useless_gap_width . local useless_gap = tonumber(beautiful.useless_gap_width) or 0 if useless_gap < 0 then useless_gap = 0 end -- A global border can be defined with -- beautiful.global_border_width local global_border = tonumber(beautiful.global_border_width) or 0 if global_border < 0 then global_border = 0 end -- Themes border width requires an offset local bw = tonumber(beautiful.border_width) or 0 -- Screen. local wa = p.workarea local cls = p.clients -- Borders are factored in. wa.height = wa.height - ((global_border * 2) + (bw * 2)) wa.width = wa.width - ((global_border * 2) + (bw * 2)) -- How many vertical columns? Read from nmaster on the tag. local t = tag.selected(p.screen) local num_x = centerfair.nmaster or tag.getnmaster(t) local ncol = centerfair.ncol or tag.getncol(t) if num_x <= 2 then num_x = 2 end if num_x > #cls then num_x = #cls end local width = math.floor((wa.width-(num_x+1)*useless_gap) / num_x) local offset_y = wa.y + useless_gap if #cls < num_x then -- Less clients than the number of columns, let's center it! local offset_x = wa.x + useless_gap + (wa.width - #cls*width - (#cls+1)*useless_gap) / 2 local g = {} g.width = width g.height = wa.height - 2*useless_gap - 2 g.y = offset_y + global_border for i = 1, #cls do g.x = offset_x + (i - 1) * (width + useless_gap + 2) + global_border cls[i]:geometry(g) end else -- More clients than the number of columns, let's arrange it! local offset_x = wa.x if useless_gap > 0 then offset_x = offset_x end -- Master client deserves a special treatement local g = {} g.width = wa.width - (num_x - 1) * width - num_x * useless_gap g.height = wa.height - 2*useless_gap - 2 g.x = offset_x + useless_gap + global_border g.y = offset_y + global_border cls[1]:geometry(g) -- Treat the other clients -- Compute distribution of clients among columns local num_y ={} do local remaining_clients = #cls-1 local ncol_min = math.ceil(remaining_clients/(num_x-1)) if ncol >= ncol_min then for i = (num_x-1), 1, -1 do if (remaining_clients-i+1) < ncol then num_y[i] = remaining_clients-i + 1 else num_y[i] = ncol end remaining_clients = remaining_clients - num_y[i] end else local rem = remaining_clients % (num_x-1) if rem ==0 then for i = 1, num_x-1 do num_y[i] = ncol_min end else for i = 1, num_x-1 do num_y[i] = ncol_min - 1 end for i = 0, rem-1 do num_y[num_x-1-i] = num_y[num_x-1-i] + 1 end end end end -- Compute geometry of the other clients local nclient = 2 g.x = g.x + g.width+useless_gap + 2 g.width = width if useless_gap > 0 then g.width = g.width - useless_gap/2 - 2 end for i = 1, (num_x-1) do to_remove = 2 g.height = math.floor((wa.height - (num_y[i] * useless_gap)) / num_y[i]) g.y = offset_y + global_border for j = 0, (num_y[i]-2) do cls[nclient]:geometry(g) nclient = nclient + 1 g.y = g.y + g.height+useless_gap + 2 to_remove = to_remove + 2 end g.height = wa.height - num_y[i]*useless_gap - (num_y[i]-1)*g.height - useless_gap - to_remove cls[nclient]:geometry(g) nclient = nclient + 1 g.x = g.x+g.width+useless_gap + 2 end end end return centerfair
gpl-2.0
nilsbrummond/ESO-CrystalFragment
CrystalFragmentsPassive.lua
1
7427
-- -- Crystal Fragment Passive -- -- github.com/nilsbrummond/ESO-CrystalFragments -- -- Detects the effect 'Crystal Fragment Passive' which grants the -- next use of 'Crystal Fragment' as an instant cast ability. -- -- The default game indicator of the passive effect is glowing purple -- hands on the player. -- -- This addon's goal is to give a clearer indication of the presense of -- the passive effect. -- Release Notes: -- Indicator now hidden when in UI mode. -- Better looking now. -- Notes: -- -- Sorcerer: -- GetUnitClassId('player') == 2 -- GetBuffAbilityType(string unitTag, integer serverSlot) -- Returns: integer buffAbilityType -- CheckUnitBuffsForAbilityType(string unitTag, integer abilityType) -- Returns: bool found CFP = {} CFP.version = 0.04 CFP.debug = false CFP.active = false CFP.enabled = false local function Debug(text) if CFP.debug then d (text) end end -- Just cause a chain by itself is boring. local function BallAndChain( object ) local T = {} setmetatable( T , { __index = function( self , func ) if func == "__BALL" then return object end return function( self , ... ) assert( object[func] , func .. " missing in object" ) object[func]( object , ... ) return self end end }) return T end local function Initialize( self, addOnName ) if addOnName ~= "CrystalFragmentsPassive" then return end CFP.InitializeGUI() EVENT_MANAGER:RegisterForEvent( "CrystalFragmentsPassive", EVENT_PLAYER_ACTIVATED, CFP.EventPlayerActivated ) -- In case the player is already active. if IsPlayerActivated() then CFP.EventPlayerActivated() end end function CFP.EventPlayerActivated() -- TODO: find the global constant for 2 - sorcerer... if GetUnitClassId('player') == 2 then if not CFP.enabled then CFP.enabled = true EVENT_MANAGER:RegisterForEvent( "CrystalFragmentsPassive", EVENT_EFFECT_CHANGED, CFP.EventEffectChanged ) EVENT_MANAGER:RegisterForEvent( "CrystalFragmentsPassive", EVENT_ACTIVE_WEAPON_PAIR_CHANGED, CFP.EventWeaponSwap ) EVENT_MANAGER:RegisterForEvent( "CrystalFragmentsPassive", EVENT_RETICLE_HIDDEN_UPDATE, CFP.EventReticleHiddenUpdate ) end else if CFP.enabled then CFP.enabled = false -- TODO: need to verify UnregisterForEvent signature... EVENT_MANAGER:UnregisterForEvent( "CrystalFragmentsPassive", EVENT_EFFECT_CHANGED, CFP.EventEffectChanged ) EVENT_MANAGER:UnregisterForEvent( "CrystalFragmentsPassive", EVENT_ACTIVE_WEAPON_PAIR_CHANGED, CFP.EventWeaponSwap ) EVENT_MANAGER:UnregisterForEvent( "CrystalFragmentsPassive", EVENT_RETICLE_HIDDEN_UPDATE, CFP.EventReticleHiddenUpdate ) -- Just in case.. CFP.DisableIndicator() end end end -- Fade the Indicator over time from alpha 1 to .2 function CFP.Update() if CFP.active then local gameTime = GetGameTimeMilliseconds() / 1000 local left = CFP.endTime - gameTime if ( left > 0.01 ) then local alpha = (left / CFP.duration) + 0.2 CFP.TLW:SetAlpha(alpha) else CFP.TLW:SetAlpha(0) end end end function CFP.EventEffectChanged( eventCode, changeType, effectSlot, effectName, unitTag, beginTime, endTime, stackCount, iconName, buffType, effectType, abilityType, statusEffectType) -- self buffs only if unitTag ~= "player" then return end -- This is the buff by name if effectName ~= "Crystal Fragments Passive" then return end Debug( "CFP:" .. " " .. changeType .. " " .. effectSlot .. " " .. effectName .. " " .. unitTag .. " " .. beginTime .. " " .. endTime .. " " .. stackCount .. " " .. " " .. iconName .. " " .. buffType .. " " .. effectType .. " " .. abilityType .. " " .. statusEffectType ) -- TODO: Need to find the CONSTants for 1, 2, and 3 in here: if (2 == changeType) then -- Buff ended CFP.DisableIndicator() elseif (1 == changeType) or (3 == changeType) then -- Buff added CFP.EnableIndicator(beginTime, endTime) end end function CFP.EventWeaponSwap( activeWeaponPair, locked ) Debug ( "SWAP lvl=" .. activeWeaponPair .. " lock=" .. locked ) CFP.UpdateIndicator() end function CFP.EventReticleHiddenUpdate(event, hidden) Debug ( "Reticle hidden=" .. tostring(hidden) ) CFP.UpdateIndicator() end function CFP.EnableIndicator(beginTime, endTime) Debug ( "CFP.EnableIndicator" ) CFP.active = true CFP.endTime = endTime CFP.duration = endTime - beginTime CFP.TLW:SetAlpha(1) CFP.TLW:SetHidden(false) CFP.UpdateIndicator() end function CFP.DisableIndicator() Debug ( "CFP.DisableIndicator" ) CFP.active = false CFP.TLW:SetHidden(true) end function CFP.UpdateIndicator() if not CFP.active then return end Debug ( "CFP.UpdateIndicator" ) if IsReticleHidden() then -- hide al the combat UI stuff... -- in charcter sheet, inventory, etc.. CFP.TLW:SetHidden(true) return end -- Find which slot the "Crystal Fragment" ability is slotted. local index = -1 for x = 3,8 do if GetSlotName(x) == "Crystal Fragments" then index = x end end if index < 0 then -- Crystal Fragments is not on the action bar. CFP.TLW:SetHidden(true) return end -- anchor the indicator to the correct action button and show it. CFP.Anchor(index) CFP.TLW:SetHidden(false) end -- Anchor the indicator over the correct button. local function MakeAnchor(h) -- Why h/3 as the offset above the action button? -- Rule of thirds is always a good place to start... -- http://en.wikipedia.org/wiki/Rule_of_thirds local y_offset = -h/3 return function (index) local win = CFP.TLW win:SetAnchor( BOTTOM, -- Action Slots vs the UI buttons - index is off by 1. ZO_ActionBar1:GetChild(index+1), TOP, 0, y_offset) end end -- Anchor the indicator covering the correct button. -- local function MakeAnchorFill(h) -- -- return function (index) -- local win = CFP.TLW -- win:SetAnchor( -- BOTTOM, -- -- Action Slots vs the UI buttons - index is off by 1. -- ZO_ActionBar1:GetChild(index+1), -- TOP, -- 0, -10) -- end -- -- end function CFP.InitializeGUI() -- Just use the first action button for sizing... local w,h = ZO_ActionBar1:GetChild(3):GetDimensions() CFP.TLW = BallAndChain( WINDOW_MANAGER:CreateTopLevelWindow("CFPBuffDisplay") ) :SetHidden(true) :SetDimensions(2*w/3,2*h/3) .__BALL CFP.icon = BallAndChain( WINDOW_MANAGER:CreateControl("CFPIcon", CFP.TLW, CT_TEXTURE) ) :SetHidden(false) :SetTexture('esoui/art/icons/ability_sorcerer_thunderclap.dds') :SetDimensions(2*w/3,2*h/3) :SetAnchorFill(CFP.TLW) .__BALL CFP.decoration = BallAndChain( WINDOW_MANAGER:CreateControl("CFPDecoration", CFP.TLW, CT_TEXTURE) ) :SetHidden(false) :SetTexture('/esoui/art/actionbar/actionslot_toggledon.dds') :SetDimensions(2*w/3,2*h/3) :SetAnchorFill(CFP.TLW) .__BALL CFP.Anchor = MakeAnchor(h) -- CFP.Anchor = MakeAnchorFill(h) CFP.Anchor(3) end -- Init Hook -- EVENT_MANAGER:RegisterForEvent( "CrystalFragmentsPassive", EVENT_ADD_ON_LOADED, Initialize )
mit
houqp/koreader-base
spec/unit/png_spec.lua
1
1659
local ffi = require("ffi") local BB = require("ffi/blitbuffer") local Png = require("ffi/png") describe("Png module", function() it("should write bitmap to png file", function() local re, ok local fn = os.tmpname() local w, h = 400, 600 local bb = BB.new(w, h, BB.TYPE_BBRGB32) bb:setPixel(0, 0, BB.ColorRGB32(128, 128, 128, 0)) bb:setPixel(200, 300, BB.ColorRGB32(10, 128, 205, 50)) bb:setPixel(400, 100, BB.ColorRGB32(120, 28, 25, 255)) local cdata = ffi.C.malloc(w * h * 4) local mem = ffi.cast("unsigned char*", cdata) for x = 0, w-1 do for y = 0, h-1 do local c = bb:getPixel(x, y):getColorRGB32() local offset = 4 * w * y + 4 * x mem[offset] = c.r mem[offset + 1] = c.g mem[offset + 2] = c.b mem[offset + 3] = c.alpha end end ok = Png.encodeToFile(fn, mem, w, h) ffi.C.free(cdata) assert.are.same(ok, true) ok, re = Png.decodeFromFile(fn, 4) assert.are.same(ok, true) local bb2 = BB.new(re.width, re.height, BB.TYPE_BBRGB32, re.data) local c = bb2:getPixel(0, 0) assert.are.same({0x80, 0x80, 0x80, 0}, {c.r, c.g, c.b, c.alpha}) c = bb2:getPixel(200, 200) assert.are.same({0, 0, 0, 0}, {c.r, c.g, c.b, c.alpha}) c = bb2:getPixel(200, 300) assert.are.same({10, 128, 205, 50}, {c.r, c.g, c.b, c.alpha}) c = bb2:getPixel(400, 100) assert.are.same({120, 28, 25, 255}, {c.r, c.g, c.b, c.alpha}) os.remove(fn) end) end)
agpl-3.0
PAC3-Server/ServerContent
lua/notagain/jrpg/libraries/client/draw_skewed_rect.lua
2
5874
local rect_mesh = {} for i = 1, 6 do rect_mesh[i] = {x = 0, y = 0, u = 0, v = 0} end local mesh = _G.mesh local mesh_Begin = mesh.Begin local mesh_Position = mesh.Position local mesh_TexCoord = mesh.TexCoord local mesh_Color = mesh.Color local mesh_AdvanceVertex = mesh.AdvanceVertex local mesh_End = mesh.End local temp_vec = Vector() local R,G,B = 1,1,1 local A = 1 local function draw_rectangle(x,y, w,h, u1,v1,u2,v2, sx,sy) -- scale uv coordinates where sx and sy are maybe texture size u1 = u1 / sx v1 = v1 / sy u2 = u2 / sx v2 = v2 / sy -- make u2 and v2 relative to u1 and v1 u2 = u2 + u1 v2 = v2 + v1 -- make w and h relative to x and y w = w + x h = h + y -- flip y local t = v2 v2 = v1 v1 = t rect_mesh[1].x = w rect_mesh[1].y = h rect_mesh[1].u = u2 rect_mesh[1].v = v1 rect_mesh[2].x = x rect_mesh[2].y = y rect_mesh[2].u = u1 rect_mesh[2].v = v2 rect_mesh[3].x = w rect_mesh[3].y = y rect_mesh[3].u = u2 rect_mesh[3].v = v2 rect_mesh[4].x = x rect_mesh[4].y = h rect_mesh[4].u = u1 rect_mesh[4].v = v1 rect_mesh[5].x = x rect_mesh[5].y = y rect_mesh[5].u = u1 rect_mesh[5].v = v2 rect_mesh[6].x = w rect_mesh[6].y = h rect_mesh[6].u = u2 rect_mesh[6].v = v1 mesh_Begin(MATERIAL_TRIANGLES, 6) for i = 1, 6 do local v = rect_mesh[i] temp_vec.x = v.x temp_vec.y = v.y mesh_Position(temp_vec) mesh_TexCoord(0, v.u, v.v) mesh_Color(R,G,B,A) mesh_AdvanceVertex() end mesh_End() end local nince_slice_mesh = {} for i = 1, 128 do nince_slice_mesh[i] = {x = 0, y = 0, u = 0, v = 0} end local function draw_rectangle2(i, x,y, w,h, u1,v1,u2,v2, sx,sy) -- scale uv coordinates where sx and sy are maybe texture size u1 = u1 / sx v1 = v1 / sy u2 = u2 / sx v2 = v2 / sy -- make u2 and v2 relative to u1 and v1 u2 = u2 + u1 v2 = v2 + v1 -- make w and h relative to x and y w = w + x h = h + y -- flip y local t = v2 v2 = v1 v1 = t nince_slice_mesh[i + 1].x = w nince_slice_mesh[i + 1].y = h nince_slice_mesh[i + 1].u = u2 nince_slice_mesh[i + 1].v = v1 nince_slice_mesh[i + 2].x = x nince_slice_mesh[i + 2].y = y nince_slice_mesh[i + 2].u = u1 nince_slice_mesh[i + 2].v = v2 nince_slice_mesh[i + 3].x = w nince_slice_mesh[i + 3].y = y nince_slice_mesh[i + 3].u = u2 nince_slice_mesh[i + 3].v = v2 nince_slice_mesh[i + 4].x = x nince_slice_mesh[i + 4].y = h nince_slice_mesh[i + 4].u = u1 nince_slice_mesh[i + 4].v = v1 nince_slice_mesh[i + 5].x = x nince_slice_mesh[i + 5].y = y nince_slice_mesh[i + 5].u = u1 nince_slice_mesh[i + 5].v = v2 nince_slice_mesh[i + 6].x = w nince_slice_mesh[i + 6].y = h nince_slice_mesh[i + 6].u = u2 nince_slice_mesh[i + 6].v = v1 end local function draw_sliced_texture(x,y,w,h, uv_size, corner_size, size, dont_draw_center) local s = size local u = uv_size local c = corner_size if w/2 < c then c = w/2 end if h/2 < c then c = h/2 end local i = 0 if not dont_draw_center then draw_rectangle2( i, x+c,y+c,w-c*2,h-c*2, u,u,s-u*2,s-u*2, s,s ) i = i + 6 end draw_rectangle2( i, x,y,c,c, 0,0,u,u, s,s ) i = i + 6 draw_rectangle2( i, x+c,y,w/2-c,c, u,0,s/2-u,u, s,s ) i = i + 6 draw_rectangle2( i, w/2+x,y,w/2-c,c, s/2,0,s/2-u,u, s,s ) i = i + 6 draw_rectangle2( i, x+w-c,y,c,c, s-u,0,u,u, s,s ) i = i + 6 draw_rectangle2( i, x,y+h-c,c,c, 0,s-u,u,u, s,s ) i = i + 6 draw_rectangle2( i, x+c,y+h-c,w/2-c,c, u,s-u,s/2-u,u, s,s ) i = i + 6 draw_rectangle2( i, w/2+x,y+h-c,w/2-c,c, s/2,s-u,s/2-u,u, s,s ) i = i + 6 draw_rectangle2( i, x+w-c,y+h-c,c,c, s-u,s-u,u,u, s,s ) i = i + 6 draw_rectangle2( i, x,y+c,c,h/2-c, 0,u,u,s/2-u, s,s ) i = i + 6 draw_rectangle2( i, x,h/2+y,c,h/2-c, 0,s/2,u,s/2-u, s,s ) i = i + 6 draw_rectangle2( i, x+w-c,y+c,c,h/2-c, s-u,u,u,s/2-u, s,s ) i = i + 6 draw_rectangle2( i, x+w-c,h/2+y,c,h/2-c, s-u,s/2,u,s/2-u, s,s ) i = i + 6 mesh_Begin(MATERIAL_TRIANGLES, i) for i = 1, i do local v = nince_slice_mesh[i] temp_vec.x = v.x temp_vec.y = v.y mesh_Position(temp_vec) mesh_TexCoord(0, v.u, v.v) mesh_Color(R, G, B, A) mesh_AdvanceVertex() end mesh_End() end local math_rad = math.rad local math_tan = math.tan local temp_matrix = Matrix() local function skew_matrix(m, x, y) x = math_rad(x) y = math_rad(y or x) local skew = temp_matrix --skew:Identity() skew:SetField(1,1, 1) skew:SetField(1,2, math_tan(x)) skew:SetField(2,1, math_tan(y)) skew:SetField(2,2, 1) m:Set(m * skew) end local cam_PushModelMatrix = cam.PushModelMatrix local cam_PopModelMatrix = cam.PopModelMatrix local temp_matrix = Matrix() local function draw_skewed_rect(x,y,w,h, skew, border, uv_size, corner_size, texture_size, dont_draw_center) border = border or 0 skew = skew or 0 R,G,B = render.GetColorModulation() R = R*255 G = G*255 B = B*255 A = render.GetBlend() A = A*255 local m if skew ~= 0 then m = temp_matrix m:Identity() m:Translate(Vector(x + w/2,y + h/2)) skew_matrix(m, skew, 0) m:Translate(-Vector(x + w/2,y + h/2)) end x = x - border y = y - border w = w + border * 2 h = h + border * 2 if m then cam_PushModelMatrix(m) end if uv_size then draw_sliced_texture(x,y,w,h, uv_size, corner_size, texture_size, dont_draw_center) else draw_rectangle(x,y,w,h, 0,0,1,1, 1,1) end if m then cam_PopModelMatrix() end end if LocalPlayer() == me then local border = CreateMaterial(tostring({}), "UnlitGeneric", { ["$BaseTexture"] = "props/metalduct001a", ["$VertexAlpha"] = 1, ["$VertexColor"] = 1, }) hook.Add("HUDPaint", "", function() render.SetColorModulation(1,1,0,1) render.SetBlend(0.1) render.SetMaterial(border) draw_skewed_rect(50,50,256,128, 0, 1, nil,8, border:GetTexture("$BaseTexture"):Width(), true) end) end return draw_skewed_rect
mit
mattyx14/otxserver
data/monster/quests/the_dream_courts/mind-wrecking_dream.lua
2
2832
local mType = Game.createMonsterType("Mind-Wrecking Dream") local monster = {} monster.description = "a mind-wrecking dream" monster.experience = 5500 monster.outfit = { lookType = 300, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.health = 3900 monster.maxHealth = 3900 monster.race = "undead" monster.corpse = 8127 monster.speed = 260 monster.manaCost = 0 monster.changeTarget = { interval = 5000, chance = 20 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 80, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = true, canWalkOnFire = true, canWalkOnPoison = true } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, } monster.loot = { } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -320}, {name ="combat", interval = 2000, chance = 20, type = COMBAT_PHYSICALDAMAGE, minDamage = 0, maxDamage = -165, range = 7, shootEffect = CONST_ANI_SUDDENDEATH, effect = CONST_ME_MORTAREA, target = false}, {name ="combat", interval = 2000, chance = 10, type = COMBAT_DEATHDAMAGE, minDamage = -350, maxDamage = -720, length = 8, spread = 3, target = false}, {name ="combat", interval = 2000, chance = 15, type = COMBAT_PHYSICALDAMAGE, minDamage = 0, maxDamage = -300, length = 7, spread = 3, effect = CONST_ME_EXPLOSIONAREA, target = false}, {name ="combat", interval = 2000, chance = 10, type = COMBAT_DEATHDAMAGE, minDamage = -225, maxDamage = -275, radius = 4, target = false} } monster.defenses = { defense = 35, armor = 35, {name ="combat", interval = 2000, chance = 15, type = COMBAT_HEALING, minDamage = 130, maxDamage = 205, target = false}, {name ="speed", interval = 2000, chance = 15, speedChange = 450, effect = CONST_ME_MAGIC_RED, target = false, duration = 5000} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 20}, {type = COMBAT_ENERGYDAMAGE, percent = -10}, {type = COMBAT_EARTHDAMAGE, percent = 40}, {type = COMBAT_FIREDAMAGE, percent = -10}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 65}, {type = COMBAT_HOLYDAMAGE , percent = -10}, {type = COMBAT_DEATHDAMAGE , percent = 80} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
clementfarabet/nn
SpatialDropout.lua
33
1453
local SpatialDropout, Parent = torch.class('nn.SpatialDropout', 'nn.Module') function SpatialDropout:__init(p) Parent.__init(self) self.p = p or 0.5 self.train = true self.noise = torch.Tensor() end function SpatialDropout:updateOutput(input) self.output:resizeAs(input):copy(input) if self.train then if input:dim() == 4 then self.noise:resize(input:size(1), input:size(2), 1, 1) elseif input:dim() == 3 then self.noise:resize(input:size(1), 1, 1) else error('Input must be 4D (nbatch, nfeat, h, w) or 3D (nfeat, h, w)') end self.noise:bernoulli(1-self.p) -- We expand the random dropouts to the entire feature map because the -- features are likely correlated accross the map and so the dropout -- should also be correlated. self.output:cmul(torch.expandAs(self.noise, input)) else self.output:mul(1-self.p) end return self.output end function SpatialDropout:updateGradInput(input, gradOutput) if self.train then self.gradInput:resizeAs(gradOutput):copy(gradOutput) self.gradInput:cmul(torch.expandAs(self.noise, input)) -- simply mask the gradients with the noise vector else error('backprop only defined while training') end return self.gradInput end function SpatialDropout:setp(p) self.p = p end function SpatialDropout:__tostring__() return string.format('%s(%f)', torch.type(self), self.p) end
bsd-3-clause
mattyx14/otxserver
data/monster/bosses/diseased_fred.lua
2
3334
local mType = Game.createMonsterType("Diseased Fred") local monster = {} monster.description = "a diseased Fred" monster.experience = 300 monster.outfit = { lookType = 299, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.health = 1100 monster.maxHealth = 1100 monster.race = "venom" monster.corpse = 8123 monster.speed = 150 monster.manaCost = 0 monster.changeTarget = { interval = 60000, chance = 0 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = true, illusionable = false, canPushItems = true, canPushCreatures = false, staticAttackChance = 95, targetDistance = 1, runHealth = 1, healthHidden = false, isBlockable = false, canWalkOnEnergy = true, canWalkOnFire = true, canWalkOnPoison = true } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "You will suffer the same fate as I do!", yell = false}, {text = "The pain! The pain!", yell = false}, {text = "Stay away! I am contagious!", yell = false}, {text = "The plague will get you!", yell = false} } monster.loot = { {name = "gold coin", chance = 28000, maxCount = 17} } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -207, condition = {type = CONDITION_POISON, totalDamage = 4, interval = 4000}}, {name ="combat", interval = 2000, chance = 100, type = COMBAT_LIFEDRAIN, minDamage = -90, maxDamage = -140, effect = CONST_ME_MAGIC_RED, target = true}, {name ="combat", interval = 1000, chance = 40, type = COMBAT_PHYSICALDAMAGE, minDamage = -100, maxDamage = -175, radius = 2, shootEffect = CONST_ANI_SMALLEARTH, target = false}, {name ="speed", interval = 3000, chance = 40, speedChange = -900, effect = CONST_ME_MAGIC_RED, target = true, duration = 20000} } monster.defenses = { defense = 15, armor = 10, {name ="speed", interval = 10000, chance = 40, speedChange = 310, effect = CONST_ME_MAGIC_GREEN, target = false, duration = 20000}, {name ="combat", interval = 5000, chance = 60, type = COMBAT_HEALING, minDamage = 50, maxDamage = 80, effect = CONST_ME_MAGIC_BLUE, target = false} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 20}, {type = COMBAT_EARTHDAMAGE, percent = 100}, {type = COMBAT_FIREDAMAGE, percent = 15}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 15}, {type = COMBAT_HOLYDAMAGE , percent = 15}, {type = COMBAT_DEATHDAMAGE , percent = 0} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType.onThink = function(monster, interval) end mType.onAppear = function(monster, creature) if monster:getType():isRewardBoss() then monster:setReward(true) end end mType.onDisappear = function(monster, creature) end mType.onMove = function(monster, creature, fromPosition, toPosition) end mType.onSay = function(monster, creature, type, message) end mType:register(monster)
gpl-2.0
mumuqz/luci
libs/luci-lib-nixio/docsrc/nixio.bit.lua
171
2044
--- Bitfield operators and mainpulation functions. -- Can be used as a drop-in replacement for bitlib. module "nixio.bit" --- Bitwise OR several numbers. -- @class function -- @name bor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Invert given number. -- @class function -- @name bnot -- @param oper Operand -- @return number --- Bitwise AND several numbers. -- @class function -- @name band -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Bitwise XOR several numbers. -- @class function -- @name bxor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Left shift a number. -- @class function -- @name lshift -- @param oper number -- @param shift bits to shift -- @return number --- Right shift a number. -- @class function -- @name rshift -- @param oper number -- @param shift bits to shift -- @return number --- Arithmetically right shift a number. -- @class function -- @name arshift -- @param oper number -- @param shift bits to shift -- @return number --- Integer division of 2 or more numbers. -- @class function -- @name div -- @param oper1 Operand 1 -- @param oper2 Operand 2 -- @param ... More Operands -- @return number --- Cast a number to the bit-operating range. -- @class function -- @name cast -- @param oper number -- @return number --- Sets one or more flags of a bitfield. -- @class function -- @name set -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Unsets one or more flags of a bitfield. -- @class function -- @name unset -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Checks whether given flags are set in a bitfield. -- @class function -- @name check -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return true when all flags are set, otherwise false
apache-2.0
mattyx14/otxserver
data/monster/quests/cults_of_tibia/orc_cult_minion.lua
2
2716
local mType = Game.createMonsterType("Orc Cult Minion") local monster = {} monster.description = "an orc cult minion" monster.experience = 850 monster.outfit = { lookType = 50, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.raceId = 1507 monster.Bestiary = { class = "Humanoid", race = BESTY_RACE_HUMANOID, toKill = 1000, FirstUnlock = 50, SecondUnlock = 500, CharmsPoints = 25, Stars = 3, Occurrence = 0, Locations = "Edron Orc Cave." } monster.health = 1000 monster.maxHealth = 1000 monster.race = "blood" monster.corpse = 5996 monster.speed = 105 monster.manaCost = 310 monster.changeTarget = { interval = 4000, chance = 10 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = false, staticAttackChance = 95, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "Orc powaaa!", yell = false} } monster.loot = { {name = "gold coin", chance = 100000, maxCount = 166}, {name = "strong health potion", chance = 15930}, {name = "small topaz", chance = 1238, maxCount = 3}, {name = "orcish axe", chance = 9190}, {name = "cultish robe", chance = 19360}, {name = "red mushroom", chance = 6250, maxCount = 3}, {name = "berserk potion", chance = 860, maxCount = 2}, {name = "meat", chance = 4780} } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -230}, {name ="combat", interval = 2000, chance = 20, type = COMBAT_PHYSICALDAMAGE, minDamage = -120, maxDamage = -170, range = 7, shootEffect = CONST_ANI_SPEAR, target = false} } monster.defenses = { defense = 30, armor = 30 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 0}, {type = COMBAT_EARTHDAMAGE, percent = 0}, {type = COMBAT_FIREDAMAGE, percent = 0}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 0}, {type = COMBAT_HOLYDAMAGE , percent = 0}, {type = COMBAT_DEATHDAMAGE , percent = 10} } monster.immunities = { {type = "paralyze", condition = false}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
mattyx14/otxserver
data/monster/quests/bigfoots_burden/humorless_fungus.lua
2
2913
local mType = Game.createMonsterType("Humorless Fungus") local monster = {} monster.description = "a humorless fungus" monster.experience = 0 monster.outfit = { lookType = 517, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.health = 2500 monster.maxHealth = 2500 monster.race = "venom" monster.corpse = 16083 monster.speed = 230 monster.manaCost = 0 monster.changeTarget = { interval = 4000, chance = 10 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 90, targetDistance = 4, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = true, canWalkOnFire = true, canWalkOnPoison = true } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "Munch munch munch!", yell = false}, {text = "Chatter", yell = false} } monster.loot = { } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -475}, {name ="combat", interval = 2000, chance = 10, type = COMBAT_EARTHDAMAGE, minDamage = -40, maxDamage = -197, range = 7, shootEffect = CONST_ANI_SMALLEARTH, effect = CONST_ME_SMALLPLANTS, target = true}, {name ="combat", interval = 2000, chance = 10, type = COMBAT_ICEDAMAGE, minDamage = 0, maxDamage = -525, range = 7, shootEffect = CONST_ANI_SNOWBALL, effect = CONST_ME_ICEAREA, target = true}, -- poison {name ="condition", type = CONDITION_POISON, interval = 2000, chance = 10, minDamage = -400, maxDamage = -640, range = 7, radius = 3, effect = CONST_ME_HITBYPOISON, target = false}, {name ="drunk", interval = 2000, chance = 10, range = 7, radius = 4, effect = CONST_ME_STUN, target = true, duration = 4000} } monster.defenses = { defense = 0, armor = 0, {name ="combat", interval = 2000, chance = 5, type = COMBAT_HEALING, minDamage = 0, maxDamage = 230, effect = CONST_ME_MAGIC_BLUE, target = false}, {name ="invisible", interval = 2000, chance = 10, effect = CONST_ME_MAGIC_BLUE} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 15}, {type = COMBAT_EARTHDAMAGE, percent = 100}, {type = COMBAT_FIREDAMAGE, percent = 5}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 15}, {type = COMBAT_HOLYDAMAGE , percent = 5}, {type = COMBAT_DEATHDAMAGE , percent = 0} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
CarabusX/Zero-K
units/tankriot.lua
3
3992
return { tankriot = { unitname = [[tankriot]], name = [[Ogre]], description = [[Heavy Riot Support Tank]], acceleration = 0.132, brakeRate = 0.516, buildCostMetal = 500, builder = false, buildPic = [[tankriot.png]], canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], selectionVolumeOffsets = [[0 0 0]], selectionVolumeScales = [[55 55 55]], selectionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { bait_level_default = 0, cus_noflashlight = 1, selection_scale = 0.92, aim_lookahead = 160, set_target_range_buffer = 40, }, explodeAs = [[BIG_UNITEX]], footprintX = 4, footprintZ = 4, iconType = [[tankriot]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 1950, maxSlope = 18, maxVelocity = 2.3, maxWaterDepth = 22, movementClass = [[TANK4]], noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE SUB]], objectName = [[corbanish.s3o]], script = [[tankriot.lua]], selfDestructAs = [[BIG_UNITEX]], sightDistance = 400, trackOffset = 8, trackStrength = 10, trackStretch = 1, trackType = [[StdTank]], trackWidth = 50, turninplace = 0, turnRate = 568, workerTime = 0, weapons = { { def = [[TAWF_BANISHER]], mainDir = [[0 0 1]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { TAWF_BANISHER = { name = [[Heavy Missile]], areaOfEffect = 160, cegTag = [[BANISHERTRAIL]], craterBoost = 1, craterMult = 2, customParams = { burst = Shared.BURST_RELIABLE, gatherradius = [[120]], smoothradius = [[80]], smoothmult = [[0.25]], force_ignore_ground = [[1]], script_reload = [[2.3]], script_burst = [[2]], light_color = [[1.4 1 0.7]], light_radius = 320, }, damage = { default = 240.1, }, edgeEffectiveness = 0.4, explosionGenerator = [[custom:xamelimpact]], fireStarter = 20, flightTime = 4, impulseBoost = 0, impulseFactor = 0.6, interceptedByShieldType = 2, leadlimit = 0, model = [[corbanishrk.s3o]], -- Model radius 100 for QuadField fix. noSelfDamage = true, range = 320, reloadtime = 0.3, smokeTrail = false, soundHit = [[weapon/bomb_hit]], soundStart = [[weapon/missile/banisher_fire]], startVelocity = 400, texture1 = [[flarescale01]], tolerance = 9000, tracks = true, trajectoryHeight = 0.45, turnRate = 22000, turret = true, weaponAcceleration = 70, weaponType = [[MissileLauncher]], weaponVelocity = 400, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, object = [[corbanish_dead.s3o]], }, HEAP = { blocking = false, footprintX = 3, footprintZ = 3, object = [[debris3x3a.s3o]], }, }, } }
gpl-2.0
imeteora/cocos2d-x-3.x-Qt
tests/lua-tests/src/TouchesTest/Paddle.lua
5
2575
require "extern" require "src/VisibleRect" Paddle = class("Paddle", function(texture) return cc.Sprite:createWithTexture(texture) end) Paddle.__index = Paddle local kPaddleStateGrabbed = 0 local kPaddleStateUngrabbed = 1 Paddle._state = kPaddleStateGrabbed function Paddle:rect() local s = self:getTexture():getContentSize() return cc.rect(-s.width / 2, -s.height / 2, s.width, s.height) end function Paddle:containsTouchLocation(x,y) local position = cc.p(self:getPosition()) local s = self:getTexture():getContentSize() local touchRect = cc.rect(-s.width / 2 + position.x, -s.height / 2 + position.y, s.width, s.height) local b = cc.rectContainsPoint(touchRect, cc.p(x,y)) return b end function Paddle:paddleWithTexture(aTexture) local pPaddle = Paddle.new(aTexture) pPaddle._state = kPaddleStateUngrabbed pPaddle:registerScriptHandler(function(tag) if "enter" == tag then pPaddle:onEnter() elseif "exit" == tag then end end) return pPaddle end function Paddle:onEnter() local listenner = cc.EventListenerTouchOneByOne:create() listenner:setSwallowTouches(true) listenner:registerScriptHandler(function(touch, event) print(string.format("Paddle::onTouchBegan id = %d, x = %f, y = %f", touch:getId(), touch:getLocation().x, touch:getLocation().y)) if (self._state ~= kPaddleStateUngrabbed) then return false end if not self:containsTouchLocation(touch:getLocation().x,touch:getLocation().y) then return false end self._state = kPaddleStateGrabbed return true end,cc.Handler.EVENT_TOUCH_BEGAN ) listenner:registerScriptHandler(function(touch, event) print(string.format("Paddle::onTouchMoved id = %d, x = %f, y = %f", touch:getId(), touch:getLocation().x, touch:getLocation().y)) assert(self._state == kPaddleStateGrabbed, "Paddle - Unexpected state!") local touchPoint = touch:getLocation() local curPosX,curPosY = self:getPosition() self:setPosition(cc.p(touchPoint.x,curPosY)) end,cc.Handler.EVENT_TOUCH_MOVED ) listenner:registerScriptHandler(function(touch, event) assert(self._state == kPaddleStateGrabbed, "Paddle - Unexpected state!") self._state = kPaddleStateUngrabbed end,cc.Handler.EVENT_TOUCH_ENDED ) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listenner, self) end
gpl-2.0
kbara/snabb
lib/ljsyscall/syscall/netbsd/nr.lua
24
9205
-- NetBSD syscall numbers local nr = { SYS = { syscall = 0, exit = 1, fork = 2, read = 3, write = 4, open = 5, close = 6, compat_50_wait4 = 7, compat_43_ocreat = 8, link = 9, unlink = 10, chdir = 12, fchdir = 13, compat_50_mknod = 14, chmod = 15, chown = 16, ["break"] = 17, compat_20_getfsstat = 18, compat_43_olseek = 19, getpid = 20, compat_40_mount = 21, unmount = 22, setuid = 23, getuid = 24, geteuid = 25, ptrace = 26, recvmsg = 27, sendmsg = 28, recvfrom = 29, accept = 30, getpeername = 31, getsockname = 32, access = 33, chflags = 34, fchflags = 35, sync = 36, kill = 37, compat_43_stat43 = 38, getppid = 39, compat_43_lstat43 = 40, dup = 41, pipe = 42, getegid = 43, profil = 44, ktrace = 45, compat_13_sigaction13 = 46, getgid = 47, compat_13_sigprocmask13 = 48, __getlogin = 49, __setlogin = 50, acct = 51, compat_13_sigpending13 = 52, compat_13_sigaltstack13 = 53, ioctl = 54, compat_12_oreboot = 55, revoke = 56, symlink = 57, readlink = 58, execve = 59, umask = 60, chroot = 61, compat_43_fstat43 = 62, compat_43_ogetkerninfo = 63, compat_43_ogetpagesize = 64, compat_12_msync = 65, vfork = 66, sbrk = 69, sstk = 70, compat_43_ommap = 71, vadvise = 72, munmap = 73, mprotect = 74, madvise = 75, mincore = 78, getgroups = 79, setgroups = 80, getpgrp = 81, setpgid = 82, compat_50_setitimer = 83, compat_43_owait = 84, compat_12_oswapon = 85, compat_50_getitimer = 86, compat_43_ogethostname = 87, compat_43_osethostname = 88, compat_43_ogetdtablesize = 89, dup2 = 90, fcntl = 92, compat_50_select = 93, fsync = 95, setpriority = 96, compat_30_socket = 97, connect = 98, compat_43_oaccept = 99, getpriority = 100, compat_43_osend = 101, compat_43_orecv = 102, compat_13_sigreturn13 = 103, bind = 104, setsockopt = 105, listen = 106, compat_43_osigvec = 108, compat_43_osigblock = 109, compat_43_osigsetmask = 110, compat_13_sigsuspend13 = 111, compat_43_osigstack = 112, compat_43_orecvmsg = 113, compat_43_osendmsg = 114, compat_50_gettimeofday = 116, compat_50_getrusage = 117, getsockopt = 118, readv = 120, writev = 121, compat_50_settimeofday = 122, fchown = 123, fchmod = 124, compat_43_orecvfrom = 125, setreuid = 126, setregid = 127, rename = 128, compat_43_otruncate = 129, compat_43_oftruncate = 130, flock = 131, mkfifo = 132, sendto = 133, shutdown = 134, socketpair = 135, mkdir = 136, rmdir = 137, compat_50_utimes = 138, compat_50_adjtime = 140, compat_43_ogetpeername = 141, compat_43_ogethostid = 142, compat_43_osethostid = 143, compat_43_ogetrlimit = 144, compat_43_osetrlimit = 145, compat_43_okillpg = 146, setsid = 147, compat_50_quotactl = 148, compat_43_oquota = 149, compat_43_ogetsockname = 150, nfssvc = 155, compat_43_ogetdirentries = 156, compat_20_statfs = 157, compat_20_fstatfs = 158, compat_30_getfh = 161, compat_09_ogetdomainname = 162, compat_09_osetdomainname = 163, compat_09_ouname = 164, sysarch = 165, compat_10_osemsys = 169, compat_10_omsgsys = 170, compat_10_oshmsys = 171, pread = 173, pwrite = 174, compat_30_ntp_gettime = 175, ntp_adjtime = 176, setgid = 181, setegid = 182, seteuid = 183, lfs_bmapv = 184, lfs_markv = 185, lfs_segclean = 186, compat_50_lfs_segwait = 187, compat_12_stat12 = 188, compat_12_fstat12 = 189, compat_12_lstat12 = 190, pathconf = 191, fpathconf = 192, getrlimit = 194, setrlimit = 195, compat_12_getdirentries = 196, mmap = 197, __syscall = 198, lseek = 199, truncate = 200, ftruncate = 201, __sysctl = 202, mlock = 203, munlock = 204, undelete = 205, compat_50_futimes = 206, getpgid = 207, reboot = 208, poll= 209, compat_14___semctl = 220, semget = 221, semop = 222, semconfig = 223, compat_14_msgctl = 224, msgget = 225, msgsnd = 226, msgrcv = 227, shmat = 228, compat_14_shmctl = 229, shmdt = 230, shmget = 231, compat_50_clock_gettime = 232, compat_50_clock_settime = 233, compat_50_clock_getres = 234, timer_create = 235, timer_delete = 236, compat_50_timer_settime = 237, compat_50_timer_gettime = 238, timer_getoverrun = 239, compat_50_nanosleep = 240, fdatasync = 241, mlockall = 242, munlockall = 243, compat_50___sigtimedwait = 244, sigqueueinfo = 245, _ksem_init = 247, _ksem_open = 248, _ksem_unlink = 249, _ksem_close = 250, _ksem_post = 251, _ksem_wait = 252, _ksem_trywait = 253, _ksem_getvalue = 254, _ksem_destroy = 255, mq_open = 257, mq_close = 258, mq_unlink = 259, mq_getattr = 260, mq_setattr = 261, mq_notify = 262, mq_send = 263, mq_receive = 264, compat_50_mq_timedsend = 265, compat_50_mq_timedreceive = 266, __posix_rename = 270, swapctl = 271, compat_30_getdents = 272, minherit = 273, lchmod = 274, lchown = 275, compat_50_lutimes = 276, __msync13 = 277, compat_30___stat13 = 278, compat_30___fstat13 = 279, compat_30___lstat13 = 280, __sigaltstack14 = 281, __vfork14 = 282, __posix_chown = 283, __posix_fchown = 284, __posix_lchown = 285, getsid = 286, __clone = 287, fktrace = 288, preadv = 289, pwritev = 290, compat_16___sigaction14 = 291, __sigpending14 = 292, __sigprocmask14 = 293, __sigsuspend14 = 294, compat_16___sigreturn14 = 295, __getcwd = 296, fchroot = 297, compat_30_fhopen = 298, compat_30_fhstat = 299, compat_20_fhstatfs = 300, compat_50_____semctl13 = 301, compat_50___msgctl13 = 302, compat_50___shmctl13 = 303, lchflags = 304, issetugid = 305, utrace = 306, getcontext = 307, setcontext = 308, _lwp_create = 309, _lwp_exit = 310, _lwp_self = 311, _lwp_wait = 312, _lwp_suspend = 313, _lwp_continue = 314, _lwp_wakeup = 315, _lwp_getprivate = 316, _lwp_setprivate = 317, _lwp_kill = 318, _lwp_detach = 319, compat_50__lwp_park = 320, _lwp_unpark = 321, _lwp_unpark_all = 322, _lwp_setname = 323, _lwp_getname = 324, _lwp_ctl = 325, compat_60_sa_register = 330, compat_60_sa_stacks = 331, compat_60_sa_enable = 332, compat_60_sa_setconcurrency = 333, compat_60_sa_yield = 334, compat_60_sa_preempt = 335, __sigaction_sigtramp = 340, pmc_get_info = 341, pmc_control = 342, rasctl = 343, kqueue = 344, compat_50_kevent = 345, _sched_setparam = 346, _sched_getparam = 347, _sched_setaffinity = 348, _sched_getaffinity = 349, sched_yield = 350, fsync_range = 354, uuidgen = 355, getvfsstat = 356, statvfs1 = 357, fstatvfs1 = 358, compat_30_fhstatvfs1 = 359, extattrctl = 360, extattr_set_file = 361, extattr_get_file = 362, extattr_delete_file = 363, extattr_set_fd = 364, extattr_get_fd = 365, extattr_delete_fd = 366, extattr_set_link = 367, extattr_get_link = 368, extattr_delete_link = 369, extattr_list_fd = 370, extattr_list_file = 371, extattr_list_link = 372, compat_50_pselect = 373, compat_50_pollts = 374, setxattr = 375, lsetxattr = 376, fsetxattr = 377, getxattr = 378, lgetxattr = 379, fgetxattr = 380, listxattr = 381, llistxattr = 382, flistxattr = 383, removexattr = 384, lremovexattr = 385, fremovexattr = 386, compat_50___stat30 = 387, compat_50___fstat30 = 388, compat_50___lstat30 = 389, __getdents30 = 390, compat_30___fhstat30 = 392, compat_50___ntp_gettime30 = 393, __socket30 = 394, __getfh30 = 395, __fhopen40 = 396, __fhstatvfs140 = 397, compat_50___fhstat40 = 398, aio_cancel = 399, aio_error = 400, aio_fsync = 401, aio_read = 402, aio_return = 403, compat_50_aio_suspend = 404, aio_write = 405, lio_listio = 406, __mount50 = 410, mremap = 411, pset_create = 412, pset_destroy = 413, pset_assign = 414, _pset_bind = 415, __posix_fadvise50 = 416, __select50 = 417, __gettimeofday50 = 418, __settimeofday50 = 419, __utimes50 = 420, __adjtime50 = 421, __lfs_segwait50 = 422, __futimes50 = 423, __lutimes50 = 424, __setitimer50 = 425, __getitimer50 = 426, __clock_gettime50 = 427, __clock_settime50 = 428, __clock_getres50 = 429, __nanosleep50 = 430, ____sigtimedwait50 = 431, __mq_timedsend50 = 432, __mq_timedreceive50 = 433, compat_60__lwp_park = 434, __kevent50 = 435, __pselect50 = 436, __pollts50 = 437, __aio_suspend50 = 438, __stat50 = 439, __fstat50 = 440, __lstat50 = 441, ____semctl50 = 442, __shmctl50 = 443, __msgctl50 = 444, __getrusage50 = 445, __timer_gettime50 = 447, __ntp_gettime50 = 448, __wait450 = 449, __mknod50 = 450, __fhstat50 = 451, pipe2 = 453, dup3 = 454, kqueue1 = 455, paccept = 456, linkat = 457, renameat = 458, mkfifoat = 459, mknodat = 460, mkdirat = 461, faccessat = 462, fchmodat = 463, fchownat = 464, fexecve = 465, fstatat = 466, utimensat = 467, openat = 468, readlinkat = 469, symlinkat = 470, unlinkat = 471, futimens = 472, __quotactl = 473, posix_spawn = 474, recvmmsg = 475, sendmmsg = 476, clock_nanosleep = 477, ___lwp_park60 = 478, } } return nr
apache-2.0
kbara/snabb
lib/ljsyscall/syscall/linux/nl.lua
18
36273
-- modularize netlink code as it is large and standalone local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(S) local nl = {} -- exports local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local util = S.util local types = S.types local c = S.c local htonl = h.htonl local align = h.align local t, pt, s = types.t, types.pt, types.s local adtt = { [c.AF.INET] = t.in_addr, [c.AF.INET6] = t.in6_addr, } local function addrtype(af) local tp = adtt[tonumber(af)] if not tp then error("bad address family") end return tp() end local function mktype(tp, x) if ffi.istype(tp, x) then return x else return tp(x) end end local mt = {} -- metatables local meth = {} -- similar functions for netlink messages local function nlmsg_align(len) return align(len, 4) end local nlmsg_hdrlen = nlmsg_align(s.nlmsghdr) local function nlmsg_length(len) return len + nlmsg_hdrlen end local function nlmsg_ok(msg, len) return len >= nlmsg_hdrlen and msg.nlmsg_len >= nlmsg_hdrlen and msg.nlmsg_len <= len end local function nlmsg_next(msg, buf, len) local inc = nlmsg_align(msg.nlmsg_len) return pt.nlmsghdr(buf + inc), buf + inc, len - inc end local rta_align = nlmsg_align -- also 4 byte align local function rta_length(len) return len + rta_align(s.rtattr) end local function rta_ok(msg, len) return len >= s.rtattr and msg.rta_len >= s.rtattr and msg.rta_len <= len end local function rta_next(msg, buf, len) local inc = rta_align(msg.rta_len) return pt.rtattr(buf + inc), buf + inc, len - inc end local addrlenmap = { -- map interface type to length of hardware address TODO are these always same? [c.ARPHRD.ETHER] = 6, [c.ARPHRD.EETHER] = 6, [c.ARPHRD.LOOPBACK] = 6, } local ifla_decode = { [c.IFLA.IFNAME] = function(ir, buf, len) ir.name = ffi.string(buf) end, [c.IFLA.ADDRESS] = function(ir, buf, len) local addrlen = addrlenmap[ir.type] if (addrlen) then ir.addrlen = addrlen ir.macaddr = t.macaddr() ffi.copy(ir.macaddr, buf, addrlen) end end, [c.IFLA.BROADCAST] = function(ir, buf, len) local addrlen = addrlenmap[ir.type] -- TODO always same if (addrlen) then ir.broadcast = t.macaddr() ffi.copy(ir.broadcast, buf, addrlen) end end, [c.IFLA.MTU] = function(ir, buf, len) local u = pt.uint(buf) ir.mtu = tonumber(u[0]) end, [c.IFLA.LINK] = function(ir, buf, len) local i = pt.int(buf) ir.link = tonumber(i[0]) end, [c.IFLA.QDISC] = function(ir, buf, len) ir.qdisc = ffi.string(buf) end, [c.IFLA.STATS] = function(ir, buf, len) ir.stats = t.rtnl_link_stats() -- despite man page, this is what kernel uses. So only get 32 bit stats here. ffi.copy(ir.stats, buf, s.rtnl_link_stats) end } local ifa_decode = { [c.IFA.ADDRESS] = function(ir, buf, len) ir.addr = addrtype(ir.family) ffi.copy(ir.addr, buf, ffi.sizeof(ir.addr)) end, [c.IFA.LOCAL] = function(ir, buf, len) ir.loc = addrtype(ir.family) ffi.copy(ir.loc, buf, ffi.sizeof(ir.loc)) end, [c.IFA.BROADCAST] = function(ir, buf, len) ir.broadcast = addrtype(ir.family) ffi.copy(ir.broadcast, buf, ffi.sizeof(ir.broadcast)) end, [c.IFA.LABEL] = function(ir, buf, len) ir.label = ffi.string(buf) end, [c.IFA.ANYCAST] = function(ir, buf, len) ir.anycast = addrtype(ir.family) ffi.copy(ir.anycast, buf, ffi.sizeof(ir.anycast)) end, [c.IFA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.ifa_cacheinfo() ffi.copy(ir.cacheinfo, buf, ffi.sizeof(t.ifa_cacheinfo)) end, } local rta_decode = { [c.RTA.DST] = function(ir, buf, len) ir.dst = addrtype(ir.family) ffi.copy(ir.dst, buf, ffi.sizeof(ir.dst)) end, [c.RTA.SRC] = function(ir, buf, len) ir.src = addrtype(ir.family) ffi.copy(ir.src, buf, ffi.sizeof(ir.src)) end, [c.RTA.IIF] = function(ir, buf, len) local i = pt.int(buf) ir.iif = tonumber(i[0]) end, [c.RTA.OIF] = function(ir, buf, len) local i = pt.int(buf) ir.oif = tonumber(i[0]) end, [c.RTA.GATEWAY] = function(ir, buf, len) ir.gateway = addrtype(ir.family) ffi.copy(ir.gateway, buf, ffi.sizeof(ir.gateway)) end, [c.RTA.PRIORITY] = function(ir, buf, len) local i = pt.int(buf) ir.priority = tonumber(i[0]) end, [c.RTA.PREFSRC] = function(ir, buf, len) local i = pt.uint32(buf) ir.prefsrc = tonumber(i[0]) end, [c.RTA.METRICS] = function(ir, buf, len) local i = pt.int(buf) ir.metrics = tonumber(i[0]) end, [c.RTA.TABLE] = function(ir, buf, len) local i = pt.uint32(buf) ir.table = tonumber(i[0]) end, [c.RTA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.rta_cacheinfo() ffi.copy(ir.cacheinfo, buf, s.rta_cacheinfo) end, -- TODO some missing } local nda_decode = { [c.NDA.DST] = function(ir, buf, len) ir.dst = addrtype(ir.family) ffi.copy(ir.dst, buf, ffi.sizeof(ir.dst)) end, [c.NDA.LLADDR] = function(ir, buf, len) ir.lladdr = t.macaddr() ffi.copy(ir.lladdr, buf, s.macaddr) end, [c.NDA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.nda_cacheinfo() ffi.copy(ir.cacheinfo, buf, s.nda_cacheinfo) end, [c.NDA.PROBES] = function(ir, buf, len) -- TODO what is this? 4 bytes end, } local ifflist = {} for k, _ in pairs(c.IFF) do ifflist[#ifflist + 1] = k end mt.iff = { __tostring = function(f) local s = {} for _, k in pairs(ifflist) do if bit.band(f.flags, c.IFF[k]) ~= 0 then s[#s + 1] = k end end return table.concat(s, ' ') end, __index = function(f, k) if c.IFF[k] then return bit.band(f.flags, c.IFF[k]) ~= 0 end end } nl.encapnames = { [c.ARPHRD.ETHER] = "Ethernet", [c.ARPHRD.LOOPBACK] = "Local Loopback", } meth.iflinks = { fn = { refresh = function(i) local j, err = nl.interfaces() if not j then return nil, err end for k, _ in pairs(i) do i[k] = nil end for k, v in pairs(j) do i[k] = v end return i end, }, } mt.iflinks = { __index = function(i, k) if meth.iflinks.fn[k] then return meth.iflinks.fn[k] end end, __tostring = function(is) local s = {} for _, v in ipairs(is) do s[#s + 1] = tostring(v) end return table.concat(s, '\n') end } meth.iflink = { index = { family = function(i) return tonumber(i.ifinfo.ifi_family) end, type = function(i) return tonumber(i.ifinfo.ifi_type) end, typename = function(i) local n = nl.encapnames[i.type] return n or 'unknown ' .. i.type end, index = function(i) return tonumber(i.ifinfo.ifi_index) end, flags = function(i) return setmetatable({flags = tonumber(i.ifinfo.ifi_flags)}, mt.iff) end, change = function(i) return tonumber(i.ifinfo.ifi_change) end, }, fn = { setflags = function(i, flags, change) local ok, err = nl.newlink(i, 0, flags, change or c.IFF.ALL) if not ok then return nil, err end return i:refresh() end, up = function(i) return i:setflags("up", "up") end, down = function(i) return i:setflags("", "up") end, setmtu = function(i, mtu) local ok, err = nl.newlink(i.index, 0, 0, 0, "mtu", mtu) if not ok then return nil, err end return i:refresh() end, setmac = function(i, mac) local ok, err = nl.newlink(i.index, 0, 0, 0, "address", mac) if not ok then return nil, err end return i:refresh() end, address = function(i, address, netmask) -- add address if type(address) == "string" then address, netmask = util.inet_name(address, netmask) end if not address then return nil end local ok, err if ffi.istype(t.in6_addr, address) then ok, err = nl.newaddr(i.index, c.AF.INET6, netmask, "permanent", "local", address) else local broadcast = address:get_mask_bcast(netmask).broadcast ok, err = nl.newaddr(i.index, c.AF.INET, netmask, "permanent", "local", address, "broadcast", broadcast) end if not ok then return nil, err end return i:refresh() end, deladdress = function(i, address, netmask) if type(address) == "string" then address, netmask = util.inet_name(address, netmask) end if not address then return nil end local af if ffi.istype(t.in6_addr, address) then af = c.AF.INET6 else af = c.AF.INET end local ok, err = nl.deladdr(i.index, af, netmask, "local", address) if not ok then return nil, err end return i:refresh() end, delete = function(i) local ok, err = nl.dellink(i.index) if not ok then return nil, err end return true end, move_ns = function(i, ns) -- TODO also support file descriptor form as well as pid local ok, err = nl.newlink(i.index, 0, 0, 0, "net_ns_pid", ns) if not ok then return nil, err end return true -- no longer here so cannot refresh end, rename = function(i, name) local ok, err = nl.newlink(i.index, 0, 0, 0, "ifname", name) if not ok then return nil, err end i.name = name -- refresh not working otherwise as done by name TODO fix so by index return i:refresh() end, refresh = function(i) local j, err = nl.interface(i.name) if not j then return nil, err end for k, _ in pairs(i) do i[k] = nil end for k, v in pairs(j) do i[k] = v end return i end, } } mt.iflink = { __index = function(i, k) if meth.iflink.index[k] then return meth.iflink.index[k](i) end if meth.iflink.fn[k] then return meth.iflink.fn[k] end if k == "inet" or k == "inet6" then return end -- might not be set, as we add it, kernel does not provide if c.ARPHRD[k] then return i.ifinfo.ifi_type == c.ARPHRD[k] end end, __tostring = function(i) local hw = '' if not i.loopback and i.macaddr then hw = ' HWaddr ' .. tostring(i.macaddr) end local s = i.name .. string.rep(' ', 10 - #i.name) .. 'Link encap:' .. i.typename .. hw .. '\n' if i.inet then for a = 1, #i.inet do s = s .. ' ' .. 'inet addr: ' .. tostring(i.inet[a].addr) .. '/' .. i.inet[a].prefixlen .. '\n' end end if i.inet6 then for a = 1, #i.inet6 do s = s .. ' ' .. 'inet6 addr: ' .. tostring(i.inet6[a].addr) .. '/' .. i.inet6[a].prefixlen .. '\n' end end s = s .. ' ' .. tostring(i.flags) .. ' MTU: ' .. i.mtu .. '\n' s = s .. ' ' .. 'RX packets:' .. i.stats.rx_packets .. ' errors:' .. i.stats.rx_errors .. ' dropped:' .. i.stats.rx_dropped .. '\n' s = s .. ' ' .. 'TX packets:' .. i.stats.tx_packets .. ' errors:' .. i.stats.tx_errors .. ' dropped:' .. i.stats.tx_dropped .. '\n' return s end } meth.rtmsg = { index = { family = function(i) return tonumber(i.rtmsg.rtm_family) end, dst_len = function(i) return tonumber(i.rtmsg.rtm_dst_len) end, src_len = function(i) return tonumber(i.rtmsg.rtm_src_len) end, index = function(i) return tonumber(i.oif) end, flags = function(i) return tonumber(i.rtmsg.rtm_flags) end, dest = function(i) return i.dst or addrtype(i.family) end, source = function(i) return i.src or addrtype(i.family) end, gw = function(i) return i.gateway or addrtype(i.family) end, -- might not be set in Lua table, so return nil iif = function() return nil end, oif = function() return nil end, src = function() return nil end, dst = function() return nil end, }, flags = { -- TODO rework so iterates in fixed order. TODO Do not seem to be set, find how to retrieve. [c.RTF.UP] = "U", [c.RTF.GATEWAY] = "G", [c.RTF.HOST] = "H", [c.RTF.REINSTATE] = "R", [c.RTF.DYNAMIC] = "D", [c.RTF.MODIFIED] = "M", [c.RTF.REJECT] = "!", } } mt.rtmsg = { __index = function(i, k) if meth.rtmsg.index[k] then return meth.rtmsg.index[k](i) end -- if S.RTF[k] then return bit.band(i.flags, S.RTF[k]) ~= 0 end -- TODO see above end, __tostring = function(i) -- TODO make more like output of ip route local s = "dst: " .. tostring(i.dest) .. "/" .. i.dst_len .. " gateway: " .. tostring(i.gw) .. " src: " .. tostring(i.source) .. "/" .. i.src_len .. " if: " .. (i.output or i.oif) return s end, } meth.routes = { fn = { match = function(rs, addr, len) -- exact match if type(addr) == "string" then local sl = addr:find("/", 1, true) if sl then len = tonumber(addr:sub(sl + 1)) addr = addr:sub(1, sl - 1) end if rs.family == c.AF.INET6 then addr = t.in6_addr(addr) else addr = t.in_addr(addr) end end local matches = {} for _, v in ipairs(rs) do if len == v.dst_len then if v.family == c.AF.INET then if addr.s_addr == v.dest.s_addr then matches[#matches + 1] = v end else local match = true for i = 0, 15 do if addr.s6_addr[i] ~= v.dest.s6_addr[i] then match = false end end if match then matches[#matches + 1] = v end end end end matches.tp, matches.family = rs.tp, rs.family return setmetatable(matches, mt.routes) end, refresh = function(rs) local nr = nl.routes(rs.family, rs.tp) for k, _ in pairs(rs) do rs[k] = nil end for k, v in pairs(nr) do rs[k] = v end return rs end, } } mt.routes = { __index = function(i, k) if meth.routes.fn[k] then return meth.routes.fn[k] end end, __tostring = function(is) local s = {} for k, v in ipairs(is) do s[#s + 1] = tostring(v) end return table.concat(s, '\n') end, } meth.ifaddr = { index = { family = function(i) return tonumber(i.ifaddr.ifa_family) end, prefixlen = function(i) return tonumber(i.ifaddr.ifa_prefixlen) end, index = function(i) return tonumber(i.ifaddr.ifa_index) end, flags = function(i) return tonumber(i.ifaddr.ifa_flags) end, scope = function(i) return tonumber(i.ifaddr.ifa_scope) end, } } mt.ifaddr = { __index = function(i, k) if meth.ifaddr.index[k] then return meth.ifaddr.index[k](i) end if c.IFA_F[k] then return bit.band(i.ifaddr.ifa_flags, c.IFA_F[k]) ~= 0 end end } -- TODO functions repetitious local function decode_link(buf, len) local iface = pt.ifinfomsg(buf) buf = buf + nlmsg_align(s.ifinfomsg) len = len - nlmsg_align(s.ifinfomsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({ifinfo = t.ifinfomsg()}, mt.iflink) ffi.copy(ir.ifinfo, iface, s.ifinfomsg) while rta_ok(rtattr, len) do if ifla_decode[rtattr.rta_type] then ifla_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_address(buf, len) local addr = pt.ifaddrmsg(buf) buf = buf + nlmsg_align(s.ifaddrmsg) len = len - nlmsg_align(s.ifaddrmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({ifaddr = t.ifaddrmsg(), addr = {}}, mt.ifaddr) ffi.copy(ir.ifaddr, addr, s.ifaddrmsg) while rta_ok(rtattr, len) do if ifa_decode[rtattr.rta_type] then ifa_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_route(buf, len) local rt = pt.rtmsg(buf) buf = buf + nlmsg_align(s.rtmsg) len = len - nlmsg_align(s.rtmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({rtmsg = t.rtmsg()}, mt.rtmsg) ffi.copy(ir.rtmsg, rt, s.rtmsg) while rta_ok(rtattr, len) do if rta_decode[rtattr.rta_type] then rta_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) else error("NYI: " .. rtattr.rta_type) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_neigh(buf, len) local rt = pt.rtmsg(buf) buf = buf + nlmsg_align(s.rtmsg) len = len - nlmsg_align(s.rtmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({rtmsg = t.rtmsg()}, mt.rtmsg) ffi.copy(ir.rtmsg, rt, s.rtmsg) while rta_ok(rtattr, len) do if nda_decode[rtattr.rta_type] then nda_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) else error("NYI: " .. rtattr.rta_type) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end -- TODO other than the first few these could be a table local nlmsg_data_decode = { [c.NLMSG.NOOP] = function(r, buf, len) return r end, [c.NLMSG.ERROR] = function(r, buf, len) local e = pt.nlmsgerr(buf) if e.error ~= 0 then r.error = t.error(-e.error) else r.ack = true end -- error zero is ACK, others negative return r end, [c.NLMSG.DONE] = function(r, buf, len) return r end, [c.NLMSG.OVERRUN] = function(r, buf, len) r.overrun = true return r end, [c.RTM.NEWADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.newaddr, ir.nl = "newaddr", true, c.RTM.NEWADDR r[#r + 1] = ir return r end, [c.RTM.DELADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.deladdr, ir.nl = "delddr", true, c.RTM.DELADDR r[#r + 1] = ir return r end, [c.RTM.GETADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.getaddr, ir.nl = "getaddr", true, c.RTM.GETADDR r[#r + 1] = ir return r end, [c.RTM.NEWLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.newlink, ir.nl = "newlink", true, c.RTM.NEWLINK r[ir.name] = ir r[#r + 1] = ir return r end, [c.RTM.DELLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.dellink, ir.nl = "dellink", true, c.RTM.DELLINK r[ir.name] = ir r[#r + 1] = ir return r end, -- TODO need test that returns these, assume updates do [c.RTM.GETLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.getlink, ir.nl = "getlink", true, c.RTM.GETLINK r[ir.name] = ir r[#r + 1] = ir return r end, [c.RTM.NEWROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.newroute, ir.nl = "newroute", true, c.RTM.NEWROUTE r[#r + 1] = ir return r end, [c.RTM.DELROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.delroute, ir.nl = "delroute", true, c.RTM.DELROUTE r[#r + 1] = ir return r end, [c.RTM.GETROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.getroute, ir.nl = "getroute", true, c.RTM.GETROUTE r[#r + 1] = ir return r end, [c.RTM.NEWNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.newneigh, ir.nl = "newneigh", true, c.RTM.NEWNEIGH r[#r + 1] = ir return r end, [c.RTM.DELNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.delneigh, ir.nl = "delneigh", true, c.RTM.DELNEIGH r[#r + 1] = ir return r end, [c.RTM.GETNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.getneigh, ir.nl = "getneigh", true, c.RTM.GETNEIGH r[#r + 1] = ir return r end, } function nl.read(s, addr, bufsize, untildone) addr = addr or t.sockaddr_nl() -- default to kernel bufsize = bufsize or 8192 local reply = t.buffer(bufsize) local ior = t.iovecs{{reply, bufsize}} local m = t.msghdr{msg_iov = ior.iov, msg_iovlen = #ior, msg_name = addr, msg_namelen = ffi.sizeof(addr)} local done = false -- what should we do if we get a done message but there is some extra buffer? could be next message... local r = {} while not done do local len, err = s:recvmsg(m) if not len then return nil, err end local buffer = reply local msg = pt.nlmsghdr(buffer) while not done and nlmsg_ok(msg, len) do local tp = tonumber(msg.nlmsg_type) if nlmsg_data_decode[tp] then r = nlmsg_data_decode[tp](r, buffer + nlmsg_hdrlen, msg.nlmsg_len - nlmsg_hdrlen) if r.overrun then return S.read(s, addr, bufsize * 2) end -- TODO add test if r.error then return nil, r.error end -- not sure what the errors mean though! if r.ack then done = true end else error("unknown data " .. tp) end if tp == c.NLMSG.DONE then done = true end msg, buffer, len = nlmsg_next(msg, buffer, len) end if not untildone then done = true end end return r end -- TODO share with read side local ifla_msg_types = { ifla = { -- IFLA.UNSPEC [c.IFLA.ADDRESS] = t.macaddr, [c.IFLA.BROADCAST] = t.macaddr, [c.IFLA.IFNAME] = "asciiz", -- TODO IFLA.MAP [c.IFLA.MTU] = t.uint32, [c.IFLA.LINK] = t.uint32, [c.IFLA.MASTER] = t.uint32, [c.IFLA.TXQLEN] = t.uint32, [c.IFLA.WEIGHT] = t.uint32, [c.IFLA.OPERSTATE] = t.uint8, [c.IFLA.LINKMODE] = t.uint8, [c.IFLA.LINKINFO] = {"ifla_info", c.IFLA_INFO}, [c.IFLA.NET_NS_PID] = t.uint32, [c.IFLA.NET_NS_FD] = t.uint32, [c.IFLA.IFALIAS] = "asciiz", --[c.IFLA.VFINFO_LIST] = "nested", --[c.IFLA.VF_PORTS] = "nested", --[c.IFLA.PORT_SELF] = "nested", --[c.IFLA.AF_SPEC] = "nested", }, ifla_info = { [c.IFLA_INFO.KIND] = "ascii", [c.IFLA_INFO.DATA] = "kind", }, ifla_vlan = { [c.IFLA_VLAN.ID] = t.uint16, -- other vlan params }, ifa = { -- IFA.UNSPEC [c.IFA.ADDRESS] = "address", [c.IFA.LOCAL] = "address", [c.IFA.LABEL] = "asciiz", [c.IFA.BROADCAST] = "address", [c.IFA.ANYCAST] = "address", -- IFA.CACHEINFO }, rta = { -- RTA_UNSPEC [c.RTA.DST] = "address", [c.RTA.SRC] = "address", [c.RTA.IIF] = t.uint32, [c.RTA.OIF] = t.uint32, [c.RTA.GATEWAY] = "address", [c.RTA.PRIORITY] = t.uint32, [c.RTA.METRICS] = t.uint32, -- RTA.PREFSRC -- RTA.MULTIPATH -- RTA.PROTOINFO -- RTA.FLOW -- RTA.CACHEINFO }, veth_info = { -- VETH_INFO_UNSPEC [c.VETH_INFO.PEER] = {"ifla", c.IFLA}, }, nda = { [c.NDA.DST] = "address", [c.NDA.LLADDR] = t.macaddr, [c.NDA.CACHEINFO] = t.nda_cacheinfo, -- [c.NDA.PROBES] = , }, } --[[ TODO add static const struct nla_policy ifla_vfinfo_policy[IFLA_VF_INFO_MAX+1] = { [IFLA_VF_INFO] = { .type = NLA_NESTED }, }; static const struct nla_policy ifla_vf_policy[IFLA_VF_MAX+1] = { [IFLA_VF_MAC] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_mac) }, [IFLA_VF_VLAN] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_vlan) }, [IFLA_VF_TX_RATE] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_tx_rate) }, [IFLA_VF_SPOOFCHK] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_spoofchk) }, }; static const struct nla_policy ifla_port_policy[IFLA_PORT_MAX+1] = { [IFLA_PORT_VF] = { .type = NLA_U32 }, [IFLA_PORT_PROFILE] = { .type = NLA_STRING, .len = PORT_PROFILE_MAX }, [IFLA_PORT_VSI_TYPE] = { .type = NLA_BINARY, .len = sizeof(struct ifla_port_vsi)}, [IFLA_PORT_INSTANCE_UUID] = { .type = NLA_BINARY, .len = PORT_UUID_MAX }, [IFLA_PORT_HOST_UUID] = { .type = NLA_STRING, .len = PORT_UUID_MAX }, [IFLA_PORT_REQUEST] = { .type = NLA_U8, }, [IFLA_PORT_RESPONSE] = { .type = NLA_U16, }, }; ]] local function ifla_getmsg(args, messages, values, tab, lookup, kind, af) local msg = table.remove(args, 1) local value, len local tp if type(msg) == "table" then -- for nested attributes local nargs = msg len = 0 while #nargs ~= 0 do local nlen nlen, nargs, messages, values, kind = ifla_getmsg(nargs, messages, values, tab, lookup, kind, af) len = len + nlen end return len, args, messages, values, kind end if type(msg) == "cdata" or type(msg) == "userdata" then tp = msg value = table.remove(args, 1) if not value then error("not enough arguments") end value = mktype(tp, value) len = ffi.sizeof(value) messages[#messages + 1] = tp values[#values + 1] = value return len, args, messages, values, kind end local rawmsg = msg msg = lookup[msg] tp = ifla_msg_types[tab][msg] if not tp then error("unknown message type " .. tostring(rawmsg) .. " in " .. tab) end if tp == "kind" then local kinds = { vlan = {"ifla_vlan", c.IFLA_VLAN}, veth = {"veth_info", c.VETH_INFO}, } tp = kinds[kind] end if type(tp) == "table" then value = t.rtattr{rta_type = msg} -- missing rta_len, but have reference and can fix messages[#messages + 1] = t.rtattr values[#values + 1] = value tab, lookup = tp[1], tp[2] len, args, messages, values, kind = ifla_getmsg(args, messages, values, tab, lookup, kind, af) len = nlmsg_align(s.rtattr) + len value.rta_len = len return len, args, messages, values, kind -- recursion base case, just a value, not nested else value = table.remove(args, 1) if not value then error("not enough arguments") end end if tab == "ifla_info" and msg == c.IFLA_INFO.KIND then kind = value end local slen if tp == "asciiz" then -- zero terminated tp = t.buffer(#value + 1) slen = nlmsg_align(s.rtattr) + #value + 1 elseif tp == "ascii" then -- not zero terminated tp = t.buffer(#value) slen = nlmsg_align(s.rtattr) + #value else if tp == "address" then tp = adtt[tonumber(af)] end value = mktype(tp, value) end len = nlmsg_align(s.rtattr) + nlmsg_align(ffi.sizeof(tp)) slen = slen or len messages[#messages + 1] = t.rtattr messages[#messages + 1] = tp values[#values + 1] = t.rtattr{rta_type = msg, rta_len = slen} values[#values + 1] = value return len, args, messages, values, kind end local function ifla_f(tab, lookup, af, ...) local len, kind local messages, values = {t.nlmsghdr}, {false} local args = {...} while #args ~= 0 do len, args, messages, values, kind = ifla_getmsg(args, messages, values, tab, lookup, kind, af) end local len = 0 local offsets = {} local alignment = nlmsg_align(1) for i, tp in ipairs(messages) do local item_alignment = align(ffi.sizeof(tp), alignment) offsets[i] = len len = len + item_alignment end local buf = t.buffer(len) for i = 2, #offsets do -- skip header local value = values[i] if type(value) == "string" then ffi.copy(buf + offsets[i], value) else -- slightly nasty if ffi.istype(t.uint32, value) then value = t.uint32_1(value) end if ffi.istype(t.uint16, value) then value = t.uint16_1(value) end if ffi.istype(t.uint8, value) then value = t.uint8_1(value) end ffi.copy(buf + offsets[i], value, ffi.sizeof(value)) end end return buf, len end local rtpref = { [c.RTM.NEWLINK] = {"ifla", c.IFLA}, [c.RTM.GETLINK] = {"ifla", c.IFLA}, [c.RTM.DELLINK] = {"ifla", c.IFLA}, [c.RTM.NEWADDR] = {"ifa", c.IFA}, [c.RTM.GETADDR] = {"ifa", c.IFA}, [c.RTM.DELADDR] = {"ifa", c.IFA}, [c.RTM.NEWROUTE] = {"rta", c.RTA}, [c.RTM.GETROUTE] = {"rta", c.RTA}, [c.RTM.DELROUTE] = {"rta", c.RTA}, [c.RTM.NEWNEIGH] = {"nda", c.NDA}, [c.RTM.DELNEIGH] = {"nda", c.NDA}, [c.RTM.GETNEIGH] = {"nda", c.NDA}, [c.RTM.NEWNEIGHTBL] = {"ndtpa", c.NDTPA}, [c.RTM.GETNEIGHTBL] = {"ndtpa", c.NDTPA}, [c.RTM.SETNEIGHTBL] = {"ndtpa", c.NDTPA}, } function nl.socket(tp, addr) tp = c.NETLINK[tp] local sock, err = S.socket(c.AF.NETLINK, c.SOCK.RAW, tp) if not sock then return nil, err end if addr then if type(addr) == "table" then addr.type = tp end -- need type to convert group names from string if not ffi.istype(t.sockaddr_nl, addr) then addr = t.sockaddr_nl(addr) end local ok, err = S.bind(sock, addr) if not ok then S.close(sock) return nil, err end end return sock end function nl.write(sock, dest, ntype, flags, af, ...) local a, err = sock:getsockname() -- to get bound address if not a then return nil, err end dest = dest or t.sockaddr_nl() -- kernel destination default local tl = rtpref[ntype] if not tl then error("NYI: ", ntype) end local tab, lookup = tl[1], tl[2] local buf, len = ifla_f(tab, lookup, af, ...) local hdr = pt.nlmsghdr(buf) hdr[0] = {nlmsg_len = len, nlmsg_type = ntype, nlmsg_flags = flags, nlmsg_seq = sock:seq(), nlmsg_pid = a.pid} local ios = t.iovecs{{buf, len}} local m = t.msghdr{msg_iov = ios.iov, msg_iovlen = #ios, msg_name = dest, msg_namelen = s.sockaddr_nl} return sock:sendmsg(m) end -- TODO "route" should be passed in as parameter, test with other netlink types local function nlmsg(ntype, flags, af, ...) ntype = c.RTM[ntype] flags = c.NLM_F[flags] local sock, err = nl.socket("route", {}) -- bind to empty sockaddr_nl, kernel fills address if not sock then return nil, err end local k = t.sockaddr_nl() -- kernel destination local ok, err = nl.write(sock, k, ntype, flags, af, ...) if not ok then sock:close() return nil, err end local r, err = nl.read(sock, k, nil, true) -- true means until get done message if not r then sock:close() return nil, err end local ok, err = sock:close() if not ok then return nil, err end return r end -- TODO do not have all these different arguments for these functions, pass a table for initialization. See also iplink. function nl.newlink(index, flags, iflags, change, ...) if change == 0 then change = c.IFF.NONE end -- 0 should work, but does not flags = c.NLM_F("request", "ack", flags) if type(index) == 'table' then index = index.index end local ifv = {ifi_index = index, ifi_flags = c.IFF[iflags], ifi_change = c.IFF[change]} return nlmsg("newlink", flags, nil, t.ifinfomsg, ifv, ...) end function nl.dellink(index, ...) if type(index) == 'table' then index = index.index end local ifv = {ifi_index = index} return nlmsg("dellink", "request, ack", nil, t.ifinfomsg, ifv, ...) end -- read interfaces and details. function nl.getlink(...) return nlmsg("getlink", "request, dump", nil, t.rtgenmsg, {rtgen_family = c.AF.PACKET}, ...) end -- read routes function nl.getroute(af, tp, tab, prot, scope, ...) local rtm = t.rtmsg{family = af, table = tab, protocol = prot, type = tp, scope = scope} local r, err = nlmsg(c.RTM.GETROUTE, "request, dump", af, t.rtmsg, rtm) if not r then return nil, err end return setmetatable(r, mt.routes) end function nl.routes(af, tp) af = c.AF[af] if not tp then tp = c.RTN.UNICAST end tp = c.RTN[tp] local r, err = nl.getroute(af, tp) if not r then return nil, err end local ifs, err = nl.getlink() if not ifs then return nil, err end local indexmap = {} -- TODO turn into metamethod as used elsewhere for i, v in pairs(ifs) do v.inet, v.inet6 = {}, {} indexmap[v.index] = i end for k, v in ipairs(r) do if ifs[indexmap[v.iif]] then v.input = ifs[indexmap[v.iif]].name end if ifs[indexmap[v.oif]] then v.output = ifs[indexmap[v.oif]].name end if tp > 0 and v.rtmsg.rtm_type ~= tp then r[k] = nil end -- filter unwanted routes end r.family = af r.tp = tp return r end local function preftable(tab, prefix) for k, v in pairs(tab) do if k:sub(1, #prefix) ~= prefix then tab[prefix .. k] = v tab[k] = nil end end return tab end function nl.newroute(flags, rtm, ...) flags = c.NLM_F("request", "ack", flags) rtm = mktype(t.rtmsg, rtm) return nlmsg("newroute", flags, rtm.family, t.rtmsg, rtm, ...) end function nl.delroute(rtm, ...) rtm = mktype(t.rtmsg, rtm) return nlmsg("delroute", "request, ack", rtm.family, t.rtmsg, rtm, ...) end -- read addresses from interface TODO flag cleanup function nl.getaddr(af, ...) local family = c.AF[af] local ifav = {ifa_family = family} return nlmsg("getaddr", "request, root", family, t.ifaddrmsg, ifav, ...) end -- TODO may need ifa_scope function nl.newaddr(index, af, prefixlen, flags, ...) if type(index) == 'table' then index = index.index end local family = c.AF[af] local ifav = {ifa_family = family, ifa_prefixlen = prefixlen or 0, ifa_flags = c.IFA_F[flags], ifa_index = index} --__TODO in __new return nlmsg("newaddr", "request, ack", family, t.ifaddrmsg, ifav, ...) end function nl.deladdr(index, af, prefixlen, ...) if type(index) == 'table' then index = index.index end local family = c.AF[af] local ifav = {ifa_family = family, ifa_prefixlen = prefixlen or 0, ifa_flags = 0, ifa_index = index} return nlmsg("deladdr", "request, ack", family, t.ifaddrmsg, ifav, ...) end function nl.getneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("getneigh", "request, dump", ndm.family, t.ndmsg, ndm, ...) end function nl.newneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("newneigh", "request, ack, excl, create", ndm.family, t.ndmsg, ndm, ...) end function nl.delneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("delneigh", "request, ack", ndm.family, t.ndmsg, ndm, ...) end function nl.interfaces() -- returns with address info too. local ifs, err = nl.getlink() if not ifs then return nil, err end local addr4, err = nl.getaddr(c.AF.INET) if not addr4 then return nil, err end local addr6, err = nl.getaddr(c.AF.INET6) if not addr6 then return nil, err end local indexmap = {} for i, v in pairs(ifs) do v.inet, v.inet6 = {}, {} indexmap[v.index] = i end for i = 1, #addr4 do local v = ifs[indexmap[addr4[i].index]] v.inet[#v.inet + 1] = addr4[i] end for i = 1, #addr6 do local v = ifs[indexmap[addr6[i].index]] v.inet6[#v.inet6 + 1] = addr6[i] end return setmetatable(ifs, mt.iflinks) end function nl.interface(i) -- could optimize just to retrieve info for one local ifs, err = nl.interfaces() if not ifs then return nil, err end return ifs[i] end local link_process_f local link_process = { -- TODO very incomplete. generate? name = function(args, v) return {"ifname", v} end, link = function(args, v) return {"link", v} end, address = function(args, v) return {"address", v} end, type = function(args, v, tab) if v == "vlan" then local id = tab.id if id then tab.id = nil return {"linkinfo", {"kind", "vlan", "data", {"id", id}}} end elseif v == "veth" then local peer = tab.peer tab.peer = nil local peertab = link_process_f(peer) return {"linkinfo", {"kind", "veth", "data", {"peer", {t.ifinfomsg, {}, peertab}}}} end return {"linkinfo", "kind", v} end, } function link_process_f(tab, args) args = args or {} for _, k in ipairs{"link", "name", "type"} do local v = tab[k] if v then if link_process[k] then local a = link_process[k](args, v, tab) for i = 1, #a do args[#args + 1] = a[i] end else error("bad iplink command " .. k) end end end return args end -- TODO better name. even more general, not just newlink. or make this the exposed newlink interface? -- I think this is generally a nicer interface to expose than the ones above, for all functions function nl.iplink(tab) local args = {tab.index or 0, tab.modifier or 0, tab.flags or 0, tab.change or 0} local args = link_process_f(tab, args) return nl.newlink(unpack(args)) end -- TODO iplink may not be appropriate always sort out flags function nl.create_interface(tab) tab.modifier = c.NLM_F.CREATE return nl.iplink(tab) end return nl end return {init = init}
apache-2.0
tgp1994/LiquidRP-tgp1994
gamemode/modules/language/sh_english.lua
1
20517
-- DO NOT edit this file! local english = { -- Admin things need_admin = "You need admin privileges in order to be able to %s", need_sadmin = "You need super admin privileges in order to be able to %s", no_privilege = "You don't have the right privileges to perform this action", no_jail_pos = "No jail position", invalid_x = "Invalid %s! %s", -- F1 menu f1ChatCommandTitle = "Chat commands", f1Search = "Search...", -- Money things: price = "Price: %s%d", priceTag = "Price: %s", reset_money = "%s has reset all players' money!", has_given = "%s has given you %s", you_gave = "You gave %s %s", npc_killpay = "%s for killing an NPC!", profit = "profit", loss = "loss", -- backwards compatibility deducted_x = "Deducted %s%d", need_x = "Need %s%d", deducted_money = "Deducted %s", need_money = "Need %s", payday_message = "Payday! You received %s!", payday_unemployed = "You received no salary because you are unemployed!", payday_missed = "Pay day missed! (You're Arrested)", property_tax = "Property tax! %s", property_tax_cant_afford = "You couldn't pay the taxes! Your property has been taken away from you!", taxday = "Tax Day! %s%% of your income was taken!", found_cheque = "You have found %s%s in a cheque made out to you from %s.", cheque_details = "This cheque is made out to %s.", cheque_torn = "You have torn up the cheque.", cheque_pay = "Pay: %s", signed = "Signed: %s", found_cash = "You have found %s%d!", -- backwards compatibility found_money = "You have found %s!", owner_poor = "The %s owner is too poor to subsidize this sale!", -- Police Wanted_text = "Wanted!", wanted = "Wanted by Police!\nReason: %s", youre_arrested = "You have been arrested for %d seconds!", youre_arrested_by = "You have been arrested by %s.", youre_unarrested_by = "You were unarrested by %s.", hes_arrested = "%s has been arrested for %d seconds!", hes_unarrested = "%s has been released from jail!", warrant_ordered = "%s ordered a search warrant for %s. Reason: %s", warrant_request = "%s requests a search warrant for %s\nReason: %s", warrant_request2 = "Search warrant request sent to Mayor %s!", warrant_approved = "Search warrant approved for %s!\nReason: %s\nOrdered by: %s", warrant_approved2 = "You are now able to search his house.", warrant_denied = "Mayor %s has denied your search warrant request.", warrant_expired = "The search warrant for %s has expired!", warrant_required = "You need a warrant in order to be able to open this door.", warrant_required_unfreeze = "You need a warrant in order to be able to unfreeze this prop.", warrant_required_unweld = "You need a warrant in order to be able to unweld this prop.", wanted_by_police = "%s is wanted by the police!\nReason: %s\nOrdered by: %s", wanted_by_police_print = "%s has made %s wanted, reason: %s", wanted_expired = "%s is no longer wanted by the Police.", wanted_revoked = "%s is no longer wanted by the Police.\nRevoked by: %s", cant_arrest_other_cp = "You cannot arrest other CPs!", must_be_wanted_for_arrest = "The player must be wanted in order to be able to arrest them.", cant_arrest_fadmin_jailed = "You cannot arrest a player who has been jailed by an admin.", cant_arrest_no_jail_pos = "You cannot arrest people since there are no jail positions set!", cant_arrest_spawning_players = "You cannot arrest players who are spawning.", suspect_doesnt_exist = "Suspect does not exist.", actor_doesnt_exist = "Actor does not exist.", get_a_warrant = "get a warrant", make_someone_wanted = "make someone wanted", remove_wanted_status = "remove wanted status", already_a_warrant = "There already is a search warrant for this suspect.", already_wanted = "The suspect is already wanted.", not_wanted = "The suspect is not wanted.", need_to_be_cp = "You have to be a member of the police force.", suspect_must_be_alive_to_do_x = "The suspect must be alive in order to %s.", suspect_already_arrested = "The suspect is already in jail.", -- Players health = "Health: %s", job = "Job: %s", salary = "Salary: %s%s", wallet = "Wallet: %s%s", weapon = "Weapon: %s", kills = "Kills: %s", deaths = "Deaths: %s", rpname_changed = "%s changed their RPName to: %s", disconnected_player = "Disconnected player", -- Teams need_to_be_before = "You need to be %s first in order to be able to become %s", need_to_make_vote = "You need to make a vote to become a %s!", team_limit_reached = "Can not become %s as the limit is reached", wants_to_be = "%s\nwants to be\n%s", has_not_been_made_team = "%s has not been made %s!", job_has_become = "%s has been made a %s!", -- Disasters meteor_approaching = "WARNING: Meteor storm approaching!", meteor_passing = "Meteor storm passing.", meteor_enabled = "Meteor Storms are now enabled.", meteor_disabled = "Meteor Storms are now disabled.", earthquake_report = "Earthquake reported of magnitude %sMw", earthtremor_report = "Earth tremor reported of magnitude %sMw", -- Keys, vehicles and doors keys_allowed_to_coown = "You are allowed to co-own this\n(Press Reload with keys or press F2 to co-own)\n", keys_other_allowed = "Allowed to co-own:", keys_allow_ownership = "(Press Reload with keys or press F2 to allow ownership)", keys_disallow_ownership = "(Press Reload with keys or press F2 to disallow ownership)", keys_owned_by = "Owned by:", keys_unowned = "Unowned\n(Press Reload with keys or press F2 to own)", keys_everyone = "(Press Reload with keys or press F2 to enable for everyone)", door_unown_arrested = "You can not own or unown things while arrested!", door_unownable = "This door cannot be owned or unowned!", door_sold = "You have sold this for %s", door_already_owned = "This door is already owned by someone!", door_cannot_afford = "You can not afford this door!", door_hobo_unable = "You can not buy a door if you are a hobo!", vehicle_cannot_afford = "You can not afford this vehicle!", door_bought = "You've bought this door for %s%s", vehicle_bought = "You've bought this vehicle for %s%s", door_need_to_own = "You need to own this door in order to be able to %s", door_rem_owners_unownable = "You can not remove owners if a door is non-ownable!", door_add_owners_unownable = "You can not add owners if a door is non-ownable!", rp_addowner_already_owns_door = "%s already owns (or is already allowed to own) this door!", add_owner = "Add owner", remove_owner = "Remove owner", coown_x = "Co-own %s", allow_ownership = "Allow ownership", disallow_ownership = "Disallow ownership", edit_door_group = "Edit door group", door_groups = "Door groups", door_group_doesnt_exist = "Door group does not exist!", door_group_set = "Door group set successfully.", sold_x_doors_for_y = "You have sold %d doors for %s%d!", -- backwards compatibility sold_x_doors = "You have sold %d doors for %s!", -- Entities drugs = "Drugs", drug_lab = "Drug Lab", gun_lab = "Gun Lab", gun = "gun", microwave = "Microwave", food = "Food", money_printer = "Money Printer", sign_this_letter = "Sign this letter", signed_yours = "Yours,", money_printer_exploded = "Your money printer has exploded!", money_printer_overheating = "Your money printer is overheating!", contents = "Contents: ", amount = "Amount: ", picking_lock = "Picking lock", cannot_pocket_x = "You cannot put this in your pocket!", object_too_heavy = "This object is too heavy.", pocket_full = "Your pocket is full!", pocket_no_items = "Your pocket contains no items.", drop_item = "Drop item", bonus_destroying_entity = "destroying this illegal entity.", switched_burst = "Switched to burst-fire mode.", switched_fully_auto = "Switched to fully automatic fire mode.", switched_semi_auto = "Switched to semi-automatic fire mode.", keypad_checker_shoot_keypad = "Shoot a keypad to see what it controls.", keypad_checker_shoot_entity = "Shoot an entity to see which keypads are connected to it", keypad_checker_click_to_clear = "Right click to clear.", keypad_checker_entering_right_pass = "Entering the right password", keypad_checker_entering_wrong_pass = "Entering the wrong password", keypad_checker_after_right_pass = "after having entered the right password", keypad_checker_after_wrong_pass = "after having entered the wrong password", keypad_checker_right_pass_entered = "Right password entered", keypad_checker_wrong_pass_entered = "Wrong password entered", keypad_checker_controls_x_entities = "This keypad controls %d entities", keypad_checker_controlled_by_x_keypads = "This entity is controlled by %d keypads", keypad_on = "ON", keypad_off = "OFF", seconds = "seconds", persons_weapons = "%s's illegal weapons:", returned_persons_weapons = "Returned %s's confiscated weapons.", no_weapons_confiscated = "%s had no weapons confiscated!", no_illegal_weapons = "%s had no illegal weapons.", confiscated_these_weapons = "Confiscated these weapons:", checking_weapons = "Checking weapons", shipment_antispam_wait = "Please wait before spawning another shipment.", -- Talking hear_noone = "No-one can hear you %s!", hear_everyone = "Everyone can hear you!", hear_certain_persons = "Players who can hear you %s: ", whisper = "whisper", yell = "yell", advert = "[Advert]", broadcast = "[Broadcast!]", radio = "radio", request = "(REQUEST!)", group = "(group)", demote = "(DEMOTE)", ooc = "OOC", radio_x = "Radio %d", talk = "talk", speak = "speak", speak_in_ooc = "speak in OOC", perform_your_action = "perform your action", talk_to_your_group = "talk to your group", channel_set_to_x = "Channel set to %s!", -- Notifies disabled = "%s is disabled! %s", limit = "You have reached the %s limit!", have_to_wait = "You need to wait another %d seconds before using %s!", must_be_looking_at = "You need to be looking at a %s!", incorrect_job = "You do not have the right job to %s", unavailable = "This %s is unavailable", unable = "You are unable to %s. %s", cant_afford = "You cannot afford this %s", created_x = "%s created a %s", cleaned_up = "Your %s were cleaned up.", you_bought_x = "You have bought %s for %s%d.", -- backwards compatibility you_bought = "You have bought %s for %s.", you_received_x = "You have received %s for %s.", created_first_jailpos = "You have created the first jail position!", added_jailpos = "You have added one extra jail position!", reset_add_jailpos = "You have removed all jail positions and you have added a new one here.", created_spawnpos = "%s's spawn position created.", updated_spawnpos = "%s's spawn position updated.", do_not_own_ent = "You do not own this entity!", cannot_drop_weapon = "Can't drop this weapon!", job_switch = "Jobs switched successfully!", job_switch_question = "Switch jobs with %s?", job_switch_requested = "Job switch requested.", cooks_only = "Cooks only.", -- Misc unknown = "Unknown", arguments = "arguments", no_one = "no one", door = "door", vehicle = "vehicle", door_or_vehicle = "door/vehicle", driver = "Driver: %s", name = "Name: %s", locked = "Locked.", unlocked = "Unlocked.", player_doesnt_exist = "Player does not exist.", job_doesnt_exist = "Job does not exist!", must_be_alive_to_do_x = "You must be alive in order to %s.", banned_or_demoted = "Banned/demoted", wait_with_that = "Wait with that.", could_not_find = "Could not find %s", f3tovote = "Hit F3 to vote", listen_up = "Listen up:", -- In rp_tell or rp_tellall nlr = "New Life Rule: Do Not Revenge Arrest/Kill.", reset_settings = "You have reset all settings!", must_be_x = "You must be a %s in order to be able to %s.", agenda_updated = "The agenda has been updated", job_set = "%s has set his/her job to '%s'", demoted = "%s has been demoted", demoted_not = "%s has not been demoted", demote_vote_started = "%s has started a vote for the demotion of %s", demote_vote_text = "Demotion nominee:\n%s", -- '%s' is the reason here cant_demote_self = "You cannot demote yourself.", i_want_to_demote_you = "I want to demote you. Reason: %s", tried_to_avoid_demotion = "You tried to escape demotion. You failed and have been demoted.", -- naughty boy! lockdown_started = "The mayor has initiated a Lockdown, please return to your homes!", lockdown_ended = "The lockdown has ended", gunlicense_requested = "%s has requested %s a gun license", gunlicense_granted = "%s has granted %s a gun license", gunlicense_denied = "%s has denied %s a gun license", gunlicense_question_text = "Grant %s a gun license?", gunlicense_remove_vote_text = "%s has started a vote for the gun license removal of %s", gunlicense_remove_vote_text2 = "Revoke gunlicense:\n%s", -- Where %s is the reason gunlicense_removed = "%s's license has been removed!", gunlicense_not_removed = "%s's license has not been removed!", vote_specify_reason = "You need to specify a reason!", vote_started = "The vote is created", vote_alone = "You have won the vote since you are alone in the server.", you_cannot_vote = "You cannot vote!", x_cancelled_vote = "%s cancelled the last vote.", cant_cancel_vote = "Could not cancel the last vote as there was no last vote to cancel!", jail_punishment = "Punishment for disconnecting! Jailed for: %d seconds.", admin_only = "Admin only!", -- When doing /addjailpos chief_or = "Chief or ",-- When doing /addjailpos frozen = "Frozen.", dead_in_jail = "You now are dead until your jail time is up!", died_in_jail = "%s has died in jail!", credits_for = "CREDITS FOR %s\n", credits_see_console = "DarkRP credits printed to console.", rp_getvehicles = "Available vehicles for custom vehicles:", data_not_loaded_one = "Your data has not been loaded yet. Please wait.", data_not_loaded_two = "If this persists, try rejoining or contacting an admin.", cant_spawn_weapons = "You cannot spawn weapons.", drive_disabled = "Drive disabled for now.", property_disabled = "Property disabled for now.", not_allowed_to_purchase = "You are not allowed to purchase this item.", rp_teamban_hint = "rp_teamban [player name/ID] [team name/id]. Use this to ban a player from a certain team.", rp_teamunban_hint = "rp_teamunban [player name/ID] [team name/id]. Use this to unban a player from a certain team.", x_teambanned_y = "%s has banned %s from being a %s.", x_teamunbanned_y = "%s has unbanned %s from being a %s.", -- Backwards compatibility: you_set_x_salary_to_y = "You set %s's salary to %s%d.", x_set_your_salary_to_y = "%s set your salary to %s%d.", you_set_x_money_to_y = "You set %s's money to %s%d.", x_set_your_money_to_y = "%s set your money to %s%d.", you_set_x_salary = "You set %s's salary to %s.", x_set_your_salary = "%s set your salary to %s.", you_set_x_money = "You set %s's money to %s.", x_set_your_money = "%s set your money to %s.", you_set_x_name = "You set %s's name to %s", x_set_your_name = "%s set your name to %s", someone_stole_steam_name = "Someone is already using your Steam name as their RP name so we gave you a '1' after your name.", -- Uh oh already_taken = "Already taken.", job_doesnt_require_vote_currently = "This job does not require a vote at the moment!", x_made_you_a_y = "%s has made you a %s!", cmd_cant_be_run_server_console = "This command cannot be run from the server console.", -- The lottery lottery_started = "There is a lottery! Participate for %s%d?", -- backwards compatibility lottery_has_started = "There is a lottery! Participate for %s?", lottery_entered = "You entered the lottery for %s", lottery_not_entered = "%s did not enter the lottery", lottery_noone_entered = "No-one has entered the lottery", lottery_won = "%s has won the lottery! He has won %s", -- Animations custom_animation = "Custom animation!", bow = "Bow", dance = "Dance", follow_me = "Follow me!", laugh = "Laugh", lion_pose = "Lion pose", nonverbal_no = "Non-verbal no", thumbs_up = "Thumbs up", wave = "Wave", -- Hungermod starving = "Starving!", -- AFK afk_mode = "AFK Mode", salary_frozen = "Your salary has been frozen.", salary_restored = "Welcome back, your salary has now been restored.", no_auto_demote = "You will not be auto-demoted.", youre_afk_demoted = "You were demoted for being AFK for too long. Next time use /afk.", hes_afk_demoted = "%s has been demoted for being AFK for too long.", afk_cmd_to_exit = "Type /afk again to exit AFK mode.", player_now_afk = "%s is now AFK.", player_no_longer_afk = "%s is no longer AFK.", -- Hitmenu hit = "hit", hitman = "Hitman", current_hit = "Hit: %s", cannot_request_hit = "Cannot request hit! %s", hitmenu_request = "Request", player_not_hitman = "This player is not a hitman!", distance_too_big = "Distance too big.", hitman_no_suicide = "The hitman won't kill himself.", hitman_no_self_order = "A hitman cannot order a hit for himself.", hitman_already_has_hit = "The hitman already has a hit ongoing.", price_too_low = "Price too low!", hit_target_recently_killed_by_hit = "The target was recently killed by a hit,", customer_recently_bought_hit = "The customer has recently requested a hit.", accept_hit_question = "Accept hit from %s\nregarding %s for %s%d?", -- backwards compatibility accept_hit_request = "Accept hit from %s\nregarding %s for %s?", hit_requested = "Hit requested!", hit_aborted = "Hit aborted! %s", hit_accepted = "Hit accepted!", hit_declined = "The hitman declined the hit!", hitman_left_server = "The hitman has left the server!", customer_left_server = "The customer has left the server!", target_left_server = "The target has left the server!", hit_price_set_to_x = "Hit price set to %s%d.", -- backwards compatibility hit_price_set = "Hit price set to %s.", hit_complete = "Hit by %s complete!", hitman_died = "The hitman died!", target_died = "The target has died!", hitman_arrested = "The hitman was arrested!", hitman_changed_team = "The hitman changed team!", x_had_hit_ordered_by_y = "%s had an active hit ordered by %s", -- Vote Restrictions hobos_no_rights = "Hobos have no voting rights!", gangsters_cant_vote_for_government = "Gangsters cannot vote for government things!", government_cant_vote_for_gangsters = "Government officials cannot vote for gangster things!", -- VGUI and some more doors/vehicles vote = "Vote", time = "Time: %d", yes = "Yes", no = "No", ok = "Okay", cancel = "Cancel", add = "Add", remove = "Remove", none = "None", x_options = "%s options", sell_x = "Sell %s", set_x_title = "Set %s title", set_x_title_long = "Set the title of the %s you are looking at.", jobs = "Jobs", buy_x = "Buy %s", -- F4menu no_extra_weapons = "This job has no extra weapons.", become_job = "Become job", create_vote_for_job = "Create vote", shipments = "Shipments", F4guns = "Weapons", F4entities = "Miscellaneous", F4ammo = "Ammo", F4vehicles = "Vehicles", -- Tab 1 give_money = "Give money to the player you're looking at", drop_money = "Drop money", change_name = "Change your DarkRP name", go_to_sleep = "Go to sleep/wake up", drop_weapon = "Drop current weapon", buy_health = "Buy health(%s)", request_gunlicense = "Request gunlicense", demote_player_menu = "Demote a player", searchwarrantbutton = "Make a player wanted", unwarrantbutton = "Remove the wanted status from a player", noone_available = "No one available", request_warrant = "Request a search warrant for a player", make_wanted = "Make someone wanted", make_unwanted = "Make someone unwanted", set_jailpos = "Set the jail position", add_jailpos = "Add a jail position", set_custom_job = "Set a custom job (press enter to activate)", set_agenda = "Set the agenda (press enter to activate)", initiate_lockdown = "Initiate a lockdown", stop_lockdown = "Stop the lockdown", start_lottery = "Start a lottery", give_license_lookingat = "Give <lookingat> a gun license", laws_of_the_land = "LAWS OF THE LAND", law_added = "Law added.", law_removed = "Law removed.", law_reset = "Laws reset.", law_too_short = "Law too short.", laws_full = "The laws are full.", default_law_change_denied = "You are not allowed to change the default laws.", -- Second tab job_name = "Name: ", job_description = "Description: ", job_weapons = "Weapons: ", -- Entities tab buy_a = "Buy %s: %s", -- Licenseweaponstab license_tab = [[License weapons Tick the weapons people should be able to get WITHOUT a license! ]], license_tab_other_weapons = "Other weapons:", } DarkRP.addLanguage("en", english) -- Make sure "en" is a valid entry for the convar gmod_language.
gpl-3.0
Links7094/nwf
npl_mod/nwf/resty/template/html.lua
14
1235
local template = require "resty.template" local setmetatable = setmetatable local escape = template.escape local concat = table.concat local pairs = pairs local type = type local function tag(name, content, attr) local r, a, content = {}, {}, content or attr r[#r + 1] = "<" r[#r + 1] = name if attr then for k, v in pairs(attr) do if type(k) == "number" then a[#a + 1] = escape(v) else a[#a + 1] = k .. '="' .. escape(v) .. '"' end end if #a > 0 then r[#r + 1] = " " r[#r + 1] = concat(a, " ") end end if type(content) == "string" then r[#r + 1] = ">" r[#r + 1] = escape(content) r[#r + 1] = "</" r[#r + 1] = name r[#r + 1] = ">" else r[#r + 1] = " />" end return concat(r) end local html = { __index = function(_, name) return function(attr) if type(attr) == "table" then return function(content) return tag(name, content, attr) end else return tag(name, attr) end end end } template.html = setmetatable(html, html) return template.html
mit
yinjun322/ejoy2d
ejoy2d/sprite.lua
3
3226
local debug = debug local c = require "ejoy2d.sprite.c" local pack = require "ejoy2d.spritepack" local shader = require "ejoy2d.shader" local richtext = require "ejoy2d.richtext" local setmetatable = setmetatable local method = c.method local method_fetch = method.fetch local method_test = method.test local method_fetch_by_index = method.fetch_by_index local dfont_method = c.dfont_method local fetch local test local get = c.get local set = c.set local get_material = get.material function get:material() local m = get_material(self) if m == nil then local prog m, prog = c.new_material(self) if m == nil then return end local meta = shader.material_meta(prog) setmetatable(m, meta) end return m end local set_program = set.program function set:program(prog) if prog == nil then set_program(self) else set_program(self, shader.id(prog)) end end local set_text = set.text function set:text(txt) if not txt or txt == "" then set_text(self, nil) else local t = type(txt) assert(t=="string" or t=="number") set_text(self, richtext.format(self, tostring(txt))) end end local sprite_meta = {} function sprite_meta.__index(spr, key) if method[key] then return method[key] end local getter = get[key] if getter then return getter(spr) end local child = fetch(spr, key) if child then return child else print("Unsupport get " .. key) return nil end end function sprite_meta.__newindex(spr, key, v) local setter = set[key] if setter then setter(spr, v) return end assert(debug.getmetatable(v) == sprite_meta, "Need a sprite") method.mount(spr, key, v) end local get_parent = get.parent function get:parent() local p = get_parent(self) if p and not getmetatable(p) then return debug.setmetatable(p, sprite_meta) end return p end -- local function function fetch(spr, child) local cobj = method_fetch(spr, child) if cobj then return debug.setmetatable(cobj, sprite_meta) end end -- local function function test(...) local cobj = method_test(...) if cobj then return debug.setmetatable(cobj, sprite_meta) end end local function fetch_by_index(spr, index) local cobj = method_fetch_by_index(spr, index) if cobj then return debug.setmetatable(cobj, sprite_meta) end end method.fetch = fetch method.fetch_by_index = fetch_by_index method.test = test local sprite = {} function sprite.new(packname, name) local pack, id = pack.query(packname, name) local cobj = c.new(pack,id) if cobj then return debug.setmetatable(cobj, sprite_meta) end end function sprite.label(tbl) local size = tbl.size or tbl.height - 2 local l = (c.label(tbl.width, tbl.height, size, tbl.color, tbl.align)) if l then l = debug.setmetatable(l, sprite_meta) if tbl.text then l.text = tbl.text end return l end end function sprite.proxy() local cobj = c.proxy() return debug.setmetatable(cobj, sprite_meta) end local dfont_meta = {} function dfont_meta.__index(spr, key) if dfont_method[key] then return dfont_method[key] else error("Unsupport dfont get " .. key) end end function sprite.dfont(width, height, fmt, tid) local cobj = c.dfont(width, height, fmt, tid) return debug.setmetatable(cobj, dfont_meta) end return sprite
mit
garrysmodlua/wire
lua/wire/stools/consolescreen.lua
9
1033
WireToolSetup.setCategory( "Visuals/Screens" ) WireToolSetup.open( "consolescreen", "Console Screen", "gmod_wire_consolescreen", nil, "Screens" ) if CLIENT then language.Add( "tool.wire_consolescreen.name", "Console Screen Tool (Wire)" ) language.Add( "tool.wire_consolescreen.desc", "Spawns a console screen" ) TOOL.Information = { { name = "left", text = "Create " .. TOOL.Name } } WireToolSetup.setToolMenuIcon( "icon16/application_xp_terminal.png" ) end WireToolSetup.BaseLang() WireToolSetup.SetupMax( 20 ) TOOL.NoLeftOnClass = true -- no update ent function needed TOOL.ClientConVar = { model = "models/props_lab/monitor01b.mdl", createflat = 0, } function TOOL.BuildCPanel(panel) WireDermaExts.ModelSelect(panel, "wire_consolescreen_model", list.Get( "WireScreenModels" ), 5) panel:CheckBox("#Create Flat to Surface", "wire_consolescreen_createflat") panel:Help("CharParam is LBBBFFF format: background and foreground colour of the character (one digit each for RGB), if L is nonzero the char flashes") end
apache-2.0
rainfiel/skynet
lualib/dns.lua
23
8758
--[[ lua dns resolver library See https://github.com/xjdrew/levent/blob/master/levent/dns.lua for more detail -- resource record type: -- TYPE value and meaning -- A 1 a host address -- NS 2 an authoritative name server -- MD 3 a mail destination (Obsolete - use MX) -- MF 4 a mail forwarder (Obsolete - use MX) -- CNAME 5 the canonical name for an alias -- SOA 6 marks the start of a zone of authority -- MB 7 a mailbox domain name (EXPERIMENTAL) -- MG 8 a mail group member (EXPERIMENTAL) -- MR 9 a mail rename domain name (EXPERIMENTAL) -- NULL 10 a null RR (EXPERIMENTAL) -- WKS 11 a well known service description -- PTR 12 a domain name pointer -- HINFO 13 host information -- MINFO 14 mailbox or mail list information -- MX 15 mail exchange -- TXT 16 text strings -- AAAA 28 a ipv6 host address -- only appear in the question section: -- AXFR 252 A request for a transfer of an entire zone -- MAILB 253 A request for mailbox-related records (MB, MG or MR) -- MAILA 254 A request for mail agent RRs (Obsolete - see MX) -- * 255 A request for all records -- -- resource recode class: -- IN 1 the Internet -- CS 2 the CSNET class (Obsolete - used only for examples in some obsolete RFCs) -- CH 3 the CHAOS class -- HS 4 Hesiod [Dyer 87] -- only appear in the question section: -- * 255 any class -- ]] --[[ -- struct header { -- uint16_t tid # identifier assigned by the program that generates any kind of query. -- uint16_t flags # flags -- uint16_t qdcount # the number of entries in the question section. -- uint16_t ancount # the number of resource records in the answer section. -- uint16_t nscount # the number of name server resource records in the authority records section. -- uint16_t arcount # the number of resource records in the additional records section. -- } -- -- request body: -- struct request { -- string name -- uint16_t atype -- uint16_t class -- } -- -- response body: -- struct response { -- string name -- uint16_t atype -- uint16_t class -- uint16_t ttl -- uint16_t rdlength -- string rdata -- } --]] local skynet = require "skynet" local socket = require "socket" local MAX_DOMAIN_LEN = 1024 local MAX_LABEL_LEN = 63 local MAX_PACKET_LEN = 2048 local DNS_HEADER_LEN = 12 local TIMEOUT = 30 * 100 -- 30 seconds local QTYPE = { A = 1, CNAME = 5, AAAA = 28, } local QCLASS = { IN = 1, } local weak = {__mode = "kv"} local CACHE = {} local dns = {} function dns.flush() CACHE[QTYPE.A] = setmetatable({},weak) CACHE[QTYPE.AAAA] = setmetatable({},weak) end dns.flush() local function verify_domain_name(name) if #name > MAX_DOMAIN_LEN then return false end if not name:match("^[_%l%d%-%.]+$") then return false end for w in name:gmatch("([_%w%-]+)%.?") do if #w > MAX_LABEL_LEN then return false end end return true end local next_tid = 1 local function gen_tid() local tid = next_tid next_tid = next_tid + 1 return tid end local function pack_header(t) return string.pack(">HHHHHH", t.tid, t.flags, t.qdcount, t.ancount or 0, t.nscount or 0, t.arcount or 0) end local function pack_question(name, qtype, qclass) local labels = {} for w in name:gmatch("([_%w%-]+)%.?") do table.insert(labels, string.pack("s1",w)) end table.insert(labels, '\0') table.insert(labels, string.pack(">HH", qtype, qclass)) return table.concat(labels) end local function unpack_header(chunk) local tid, flags, qdcount, ancount, nscount, arcount, left = string.unpack(">HHHHHH", chunk) return { tid = tid, flags = flags, qdcount = qdcount, ancount = ancount, nscount = nscount, arcount = arcount }, left end -- unpack a resource name local function unpack_name(chunk, left) local t = {} local jump_pointer local tag, offset, label while true do tag, left = string.unpack("B", chunk, left) if tag & 0xc0 == 0xc0 then -- pointer offset,left = string.unpack(">H", chunk, left - 1) offset = offset & 0x3fff if not jump_pointer then jump_pointer = left end -- offset is base 0, need to plus 1 left = offset + 1 elseif tag == 0 then break else label, left = string.unpack("s1", chunk, left - 1) t[#t+1] = label end end return table.concat(t, "."), jump_pointer or left end local function unpack_question(chunk, left) local name, left = unpack_name(chunk, left) local atype, class, left = string.unpack(">HH", chunk, left) return { name = name, atype = atype, class = class }, left end local function unpack_answer(chunk, left) local name, left = unpack_name(chunk, left) local atype, class, ttl, rdata, left = string.unpack(">HHI4s2", chunk, left) return { name = name, atype = atype, class = class, ttl = ttl, rdata = rdata },left end local function unpack_rdata(qtype, chunk) if qtype == QTYPE.A then local a,b,c,d = string.unpack("BBBB", chunk) return string.format("%d.%d.%d.%d", a,b,c,d) elseif qtype == QTYPE.AAAA then local a,b,c,d,e,f,g,h = string.unpack(">HHHHHHHH", chunk) return string.format("%x:%x:%x:%x:%x:%x:%x:%x", a, b, c, d, e, f, g, h) else error("Error qtype " .. qtype) end end local dns_server local request_pool = {} local function resolve(content) if #content < DNS_HEADER_LEN then -- drop skynet.error("Recv an invalid package when dns query") return end local answer_header,left = unpack_header(content) -- verify answer assert(answer_header.qdcount == 1, "malformed packet") local question,left = unpack_question(content, left) local ttl local answer local answers_ipv4 local answers_ipv6 for i=1, answer_header.ancount do answer, left = unpack_answer(content, left) local answers if answer.atype == QTYPE.A then answers_ipv4 = answers_ipv4 or {} answers = answers_ipv4 elseif answer.atype == QTYPE.AAAA then answers_ipv6 = answers_ipv6 or {} answers = answers_ipv6 end if answers then local ip = unpack_rdata(answer.atype, answer.rdata) ttl = ttl and math.min(ttl, answer.ttl) or answer.ttl answers[#answers+1] = ip end end if answers_ipv4 then CACHE[QTYPE.A][question.name] = { answers = answers_ipv4, ttl = skynet.now() + ttl * 100 } end if answers_ipv6 then CACHE[QTYPE.AAAA][question.name] = { answers = answers_ipv6, ttl = skynet.now() + ttl * 100 } end local resp = request_pool[answer_header.tid] if not resp then -- the resp may be timeout return end if question.name ~= resp.name then skynet.error("Recv an invalid name when dns query") end local r = CACHE[resp.qtype][resp.name] if r then resp.answers = r.answers end skynet.wakeup(resp.co) end function dns.server(server, port) if not server then local f = assert(io.open "/etc/resolv.conf") for line in f:lines() do server = line:match("%s*nameserver%s+([^%s]+)") if server then break end end f:close() assert(server, "Can't get nameserver") end dns_server = socket.udp(function(str, from) resolve(str) end) socket.udp_connect(dns_server, server, port or 53) return server end local function lookup_cache(name, qtype, ignorettl) local result = CACHE[qtype][name] if result then if ignorettl or (result.ttl > skynet.now()) then return result.answers end end end local function suspend(tid, name, qtype) local req = { name = name, tid = tid, qtype = qtype, co = coroutine.running(), } request_pool[tid] = req skynet.fork(function() skynet.sleep(TIMEOUT) local req = request_pool[tid] if req then -- cancel tid skynet.error(string.format("DNS query %s timeout", name)) request_pool[tid] = nil skynet.wakeup(req.co) end end) skynet.wait(req.co) local answers = req.answers request_pool[tid] = nil if not req.answers then local answers = lookup_cache(name, qtype, true) if answers then return answers[1], answers end error "timeout or no answer" end return req.answers[1], req.answers end function dns.resolve(name, ipv6) local qtype = ipv6 and QTYPE.AAAA or QTYPE.A local name = name:lower() assert(verify_domain_name(name) , "illegal name") local answers = lookup_cache(name, qtype) if answers then return answers[1], answers end local question_header = { tid = gen_tid(), flags = 0x100, -- flags: 00000001 00000000, set RD qdcount = 1, } local req = pack_header(question_header) .. pack_question(name, qtype, QCLASS.IN) assert(dns_server, "Call dns.server first") socket.write(dns_server, req) return suspend(question_header.tid, name, qtype) end return dns
mit
aqasaeed/sparta
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
CarabusX/Zero-K
LuaUI/Configs/customCmdTypes.lua
2
11038
-- This is the list of name ("action name") related to unit command. This name won't work using command line (eg: /fight, won't activate FIGHT command) but it can be binded to a key (eg: /bind f fight, will activate FIGHT when f is pressed) -- In reverse, one can use Spring.GetActionHotkey(name) to get the key binded to this name. -- This table is used in Epicmenu for hotkey management. VFS.Include("LuaRules/Configs/customcmds.h.lua") local custom_cmd_actions = { -- cmdTypes are: -- 1: Targeted commands (eg attack) -- 2: State commands (eg on/off). Parameter 'state' creates actions to set a particular state -- 3: Instant commands (eg self-d) --SPRING COMMANDS selfd = {cmdType = 3, name = "Self Destruct"}, attack = {cmdType = 1, name = "Force Fire"}, stop = {cmdType = 3, name = "Stop"}, fight = {cmdType = 1, name = "Attack Move"}, guard = {cmdType = 1, name = "Guard"}, move = {cmdType = 1, name = "Move"}, patrol = {cmdType = 1, name = "Patrol"}, wait = {cmdType = 3, name = "Wait"}, timewait = {cmdType = 3, name = "Wait: Timer"}, deathwait = {cmdType = 3, name = "Wait: Death"}, squadwait = {cmdType = 3, name = "Wait: Squad"}, gatherwait = {cmdType = 3, name = "Wait: Gather"}, repair = {cmdType = 1, name = "Repair"}, reclaim = {cmdType = 1, name = "Reclaim"}, resurrect = {cmdType = 1, name = "Resurrect"}, manualfire = {cmdType = 1, name = "Fire Special Weapon"}, loadunits = {cmdType = 1, name = "Load Units"}, unloadunits = {cmdType = 1, name = "Unload Units"}, areaattack = {cmdType = 1, name = "Area Attack"}, rawmove = {cmdType = 1, name = "Move"}, -- states wantonoff = {cmdType = 2, cmdID = CMD_WANT_ONOFF, name = "On/Off", states = {'Off', 'On'}}, ['repeat'] = {cmdType = 2, cmdID = CMD.REPEAT, name = "Repeat", states = {'Off', 'On'}}, wantcloak = {cmdType = 2, cmdID = CMD_WANT_CLOAK, name = "Cloak", states = {'Off', 'On'}}, movestate = {cmdType = 2, cmdID = CMD.MOVE_STATE, name = "Move State", states = {'Hold Position', 'Maneuver', 'Roam'}}, firestate = {cmdType = 2, cmdID = CMD.FIRE_STATE, name = "Fire State", states = {'Hold Fire', 'Return Fire', 'Fire At Will'}}, idlemode = {cmdType = 2, cmdID = CMD.IDLEMODE, name = "Air Idle State", states = {'Land', 'Fly'}}, autorepairlevel = {cmdType = 2, name = "Air Retreat Threshold", states = {'Off', '30%', '50%', '80%'}}, preventoverkill = {cmdType = 2, cmdID = CMD_PREVENT_OVERKILL, name = "Prevent Overkill", states = {'Off', 'On'}}, preventbait = {cmdType = 2, cmdID = CMD_PREVENT_BAIT, name = "Avoid Bad Targets", states = {'Disabled', '40', '100', '300', '600'}}, fireatshields = {cmdType = 2, cmdID = CMD_FIRE_AT_SHIELD, name = "Fire at Shields", states = {'Off', 'On'}}, firetowards = {cmdType = 2, cmdID = CMD_FIRE_TOWARDS_ENEMY, name = "Fire Towards Enemies", states = {'Off', 'On'}}, trajectory = {cmdType = 2, cmdID = CMD.TRAJECTORY, name = "Trajectory", states = {'Low', 'High'}}, --CUSTOM COMMANDS sethaven = {cmdType = 1, name = "Add Retreat Zone"}, excludeairpad = {cmdType = 1, name = "Exclude an Airpad"}, --build = {cmdType = 1, name = "--build"}, areamex = {cmdType = 1, name = "Area Mex"}, areaterramex = {cmdType = 1, name = "Area Terra Mex"}, mine = {cmdType = 1, name = "Mine"}, build = {cmdType = 1, name = "Build"}, jump = {cmdType = 1, name = "Jump"}, find_pad = {cmdType = 3, name = "Return to Airbase"}, exclude_pad = {cmdType = 1, name = "Exclude Airpad"}, embark = {cmdType = 3, name = "Embark"}, disembark = {cmdType = 3, name = "Disembark"}, loadselected = {cmdType = 3, name = "Load Selected Units"}, oneclickwep = {cmdType = 3, name = "Activate Special"}, settargetcircle = {cmdType = 1, name = "Set Target"}, settarget = {cmdType = 1, name = "Set Target (rectangle)"}, canceltarget = {cmdType = 3, name = "Cancel Target"}, setferry = {cmdType = 1, name = "Create Ferry Route"}, setfirezone = {cmdType = 1, name = "Set Newton Fire Zone"}, cancelfirezone = {cmdType = 3, name = "Cancel Newton Fire Zone"}, --selectmissiles = {cmdType = 3, name = "Select Missiles"}, -- doesn't seem to appear, maybe it doesn't support widget commands? radialmenu = {cmdType = 3, name = "Open Radial Build Menu"}, placebeacon = {cmdType = 1, name = "Place Lamp"}, recalldrones = {cmdType = 3, name = "Recall Drones to Carrier"}, buildprev = {cmdType = 1, name = "Build Previous"}, areaguard = {cmdType = 1, name = "Area Guard"}, dropflag = {cmdType = 3, name = "Drop Flag"}, upgradecomm = {cmdType = 3, name = "Upgrade Commander"}, upgradecommstop = {cmdType = 3, name = "Stop Upgrade Commander"}, stopproduction = {cmdType = 3, name = "Stop Factory Production"}, globalbuildcancel = {cmdType = 1, name = "Cancel Global Build Tasks"}, evacuate = {cmdType = 3, name = "Evacuate"}, morph = {cmdType = 3, name = "Morph (and stop morph)"}, -- terraform rampground = {cmdType = 1, name = "Terraform Ramp"}, levelground = {cmdType = 1, name = "Terraform Level"}, raiseground = {cmdType = 1, name = "Terraform Raise"}, smoothground = {cmdType = 1, name = "Terraform Smooth"}, restoreground = {cmdType = 1, name = "Terraform Restore"}, --terraform_internal = {cmdType = 1, name = "--terraform_internal"}, --build a "generic" plate from build factory menu buildplate = {cmdType = 1, name = "Build Plate"}, resetfire = {cmdType = 3, name = "Reset Fire"}, resetmove = {cmdType = 3, name = "Reset Move"}, --states -- stealth = {cmdType = 2, name = "stealth"}, --no longer applicable cloak_shield = {cmdType = 2, cmdID = CMD_CLOAK_SHIELD, name = "Area Cloaker", states = {'Off', 'On'}}, retreat = {cmdType = 2, cmdID = CMD_RETREAT, name = "Retreat Threshold", states = {'Off', '30%', '65%', '99%'}, actionOverride = {'cancelretreat'}}, ['luaui noretreat'] = {cmdType = 2, name = "luaui noretreat"}, priority = {cmdType = 2, cmdID = CMD_PRIORITY, name = "Construction Priority", states = {'Low', 'Normal', 'High'}}, miscpriority = {cmdType = 2, cmdID = CMD_MISC_PRIORITY, name = "Misc. Priority", states = {'Low', 'Normal', 'High'}}, ap_fly_state = {cmdType = 2, cmdID = CMD_AP_FLY_STATE, name = "Air Idle State", states = {'Land', 'Fly'}}, ap_autorepairlevel = {cmdType = 2, name = "Auto Repair", states = {'Off', '30%', '50%', '80%'}}, floatstate = {cmdType = 2, name = "Float State", states = {'Sink', 'When Shooting', 'Float'}}, dontfireatradar = {cmdType = 2, cmdID = CMD_DONT_FIRE_AT_RADAR, name = "Firing at Radar Dots", states = {'Off', 'On'}}, antinukezone = {cmdType = 2, name = "Ceasefire Antinuke Zone", states = {'Off', 'On'}}, unitai = {cmdType = 2, cmdID = CMD_UNIT_AI, name = "Unit AI", states = {'Off', 'On'}}, selection_rank = {cmdType = 2, name = "Selection Rank", states = {'0', '1', '2', '3'}}, autocalltransport = {cmdType = 2, name = "Auto Call Transport", states = {'Off', 'On'}}, unit_kill_subordinates = {cmdType = 2, cmdID = CMD_UNIT_KILL_SUBORDINATES, name = "Dominatrix Kill", states = {'Off', 'On'}}, goostate = {cmdType = 2, cmdID = CMD_GOO_GATHER, name = "Goo State", states = {'Off', 'When uncloaked', 'On'}}, disableattack = {cmdType = 2, cmdID = CMD_DISABLE_ATTACK, name = "Allow Attack", states = {'Allowed', 'Blocked'}}, pushpull = {cmdType = 2, cmdID = CMD_PUSH_PULL, name = "Impulse Mode", states = {'Pull', 'Push'}}, autoassist = {cmdType = 2, cmdID = CMD_FACTORY_GUARD, name = "Factory Auto Assist", states = {'Off', 'On'}}, airstrafe = {cmdType = 2, cmdID = CMD_AIR_STRAFE, name = "Gunship Strafe", states = {'Off', 'On'}}, divestate = {cmdType = 2, cmdID = CMD_UNIT_BOMBER_DIVE_STATE, name = "Raven Dive", states = {'Never', 'Under Shields', 'For Mobiles', 'Always Low'}}, globalbuild = {cmdType = 2, cmdID = CMD_GLOBAL_BUILD, name = "Constructor Global AI", states = {'Off', 'On'}}, toggledrones = {cmdType = 2, cmdID = CMD_TOGGLE_DRONES, name = "Drone Construction.", states = {'Off', 'On'}}, } -- These actions are created from echoing all actions that appear when all units are selected. -- See cmd_layout_handler for how to generate these actions. local usedActions = { ["stop"] = true, ["attack"] = true, ["wait"] = true, ["timewait"] = true, ["deathwait"] = true, ["squadwait"] = true, ["gatherwait"] = true, ["selfd"] = true, ["firestate"] = true, ["movestate"] = true, ["repeat"] = true, ["loadonto"] = true, ["rawmove"] = true, ["patrol"] = true, ["fight"] = true, ["guard"] = true, ["areaguard"] = true, ["orbitdraw"] = true, ["preventoverkill"] = true, ["preventbait"] = true, ["retreat"] = true, ["unitai"] = true, ["settarget"] = true, ["settargetcircle"] = true, ["canceltarget"] = true, ["embark"] = true, ["disembark"] = true, ["transportto"] = true, ["wantonoff"] = true, ["miscpriority"] = true, ["manualfire"] = true, ["repair"] = true, ["reclaim"] = true, ["areamex"] = true, ["areaterramex"] = true, ["priority"] = true, ["rampground"] = true, ["levelground"] = true, ["raiseground"] = true, ["smoothground"] = true, ["restoreground"] = true, ["buildplate"] = true, ["jump"] = true, ["idlemode"] = true, ["areaattack"] = true, --["rearm"] = true, -- Not useful to send directly so unbindable to prevent confusion. Right click on pad is better. ["find_pad"] = true, ["recalldrones"] = true, ["toggledrones"] = true, ["divestate"] = true, ["wantcloak"] = true, ["oneclickwep"] = true, ["floatstate"] = true, ["airstrafe"] = true, ["dontfireatradar"] = true, ["stockpile"] = true, ["trajectory"] = true, ["cloak_shield"] = true, ["stopproduction"] = true, ["resurrect"] = true, ["loadunits"] = true, ["unloadunits"] = true, ["loadselected"] = true, ["apFlyState"] = true, ["placebeacon"] = true, ["morph"] = true, --["prevmenu"] = true, --["nextmenu"] = true, ["upgradecomm"] = true, ["autoassist"] = true, ["autocalltransport"] = true, ["setferry"] = true, ["sethaven"] = true, ["exclude_pad"] = true, ["setfirezone"] = true, ["cancelfirezone"] = true, ["selection_rank"] = true, ["pushpull"] = true, ["unit_kill_subordinates"] = true, ["fireatshields"] = true, ["goostate"] = true, -- These actions are used, just not by selecting everything with default UI ["globalbuild"] = true, ["upgradecommstop"] = true, ["autoeco"] = true, ["evacuate"] = true, } -- Clear unused actions. for name,_ in pairs(custom_cmd_actions) do if not usedActions[name] then custom_cmd_actions[name] = nil end end -- Add toggle-to-particular-state commands local fullCustomCmdActions = {} for name, data in pairs(custom_cmd_actions) do if data.states then for i = 1, #data.states do local cmdName = (data.actionOverride and data.actionOverride[i]) or (name .. " " .. (i-1)) fullCustomCmdActions[cmdName] = { cmdType = data.cmdType, name = data.name .. ": set " .. data.states[i], setValue = (i - 1), cmdID = data.cmdID, } end data.name = data.name .. ": toggle" end fullCustomCmdActions[name] = data end return fullCustomCmdActions
gpl-2.0
Undeadsewer/M.O.RE
Melee Overhaul REvamped/lua/copmovement.lua
1
6447
function CopMovement:add_dismemberment( part , variant ) self._dismemberments = self._dismemberments or {} self._dismemberments[ part ] = true if variant then self._dismemberments.variant = variant end self._unit:set_extension_update_enabled( Idstring( "movement" ) , true ) end Hooks:PreHook( CopMovement , "update" , "MeleeOverhaulCopMovementPreUpdate" , function( self , unit , t , dt ) if self._dismemberments then if self._dismemberments.Head then if not self._dismemberments.t then self._dismemberments.t = t + 5 end if MeleeOverhaul.MenuOptions.MultipleChoice[ "SpurtEffect" ][ 4 ][ MeleeOverhaul:HasSetting( "SpurtEffect" ) ] and MeleeOverhaul.MenuOptions.MultipleChoice[ "SpurtEffect" ][ 4 ][ MeleeOverhaul:HasSetting( "SpurtEffect" ) ][ 2 ] then local l = { [ 1 ] = unit:get_object( Idstring( "Neck" ) ):rotation(), [ 2 ] = unit:get_object( Idstring( "Neck" ) ):rotation():y() } local s = { [ 1 ] = unit:get_object( Idstring( "Neck" ) ):rotation(), [ 2 ] = unit:movement():m_head_rot():x() } self._dismemberments.fx = World:effect_manager():spawn({ effect = Idstring( MeleeOverhaul.MenuOptions.MultipleChoice[ "SpurtEffect" ][ 4 ][ MeleeOverhaul:HasSetting( "SpurtEffect" ) ][ 2 ] ), position = unit:get_object( Idstring( "Neck" ) ):position(), rotation = self._dismemberments.variant == "LargeBladed" and l[ MeleeOverhaul.MenuOptions.MultipleChoice[ "SpurtEffect" ][ 4 ][ MeleeOverhaul:HasSetting( "SpurtEffect" ) ][ 3 ] ] or self._dismemberments.variant == "SmallBladed" and s[ MeleeOverhaul.MenuOptions.MultipleChoice[ "SpurtEffect" ][ 4 ][ MeleeOverhaul:HasSetting( "SpurtEffect" ) ][ 3 ] ] or l[ MeleeOverhaul.MenuOptions.MultipleChoice[ "SpurtEffect" ][ 4 ][ MeleeOverhaul:HasSetting( "SpurtEffect" ) ][ 3 ] ] }) end local splatter_from = unit:get_object( Idstring("Neck") ):position() local splatter_to = splatter_from + unit:get_object( Idstring( "Neck" ) ):rotation():y() * 100 local splatter_ray = unit:raycast( "ray" , splatter_from , splatter_to , "slot_mask" , managers.slot:get_mask( "world_geometry" ) ) if splatter_ray then self._dismemberments.splatter = World:project_decal( Idstring( "blood_spatter" ) , splatter_ray.position , splatter_ray.ray , splatter_ray.unit , nil , splatter_ray.normal ) end end if self._dismemberments.LeftArm then self._unit:get_object( Idstring( "LeftArm") ):m_position( self._unit:get_object( Idstring( "LeftShoulder" ) ):position() ) self._unit:get_object( Idstring( "LeftArm" ) ):set_position( self._unit:get_object( Idstring( "LeftShoulder" ) ):position() ) self._unit:get_object( Idstring( "LeftArm" ) ):set_rotation( self._unit:get_object( Idstring( "LeftShoulder" ) ):rotation() ) self._unit:get_object( Idstring( "LeftForeArm" ) ):m_position( self._unit:get_object( Idstring( "LeftArm" ) ):position() ) self._unit:get_object( Idstring( "LeftForeArm" ) ):set_position( self._unit:get_object( Idstring( "LeftArm" ) ):position() ) self._unit:get_object( Idstring( "LeftForeArm" ) ):set_rotation( self._unit:get_object( Idstring( "Spine1" ) ):rotation() ) self._unit:get_object( Idstring( "LeftHand" ) ):m_position( self._unit:get_object( Idstring( "Spine1" ) ):position() ) self._unit:get_object( Idstring( "LeftHand" ) ):set_position( self._unit:get_object( Idstring( "Spine1" ) ):position() ) self._unit:get_object( Idstring( "LeftHand" ) ):set_rotation( self._unit:get_object( Idstring( "Spine1" ) ):rotation() ) end if self._dismemberments.RightArm then self._unit:get_object( Idstring( "RightArm") ):m_position( self._unit:get_object( Idstring( "RightShoulder" ) ):position() ) self._unit:get_object( Idstring( "RightArm" ) ):set_position( self._unit:get_object( Idstring( "RightShoulder" ) ):position() ) self._unit:get_object( Idstring( "RightArm" ) ):set_rotation( self._unit:get_object( Idstring( "RightShoulder" ) ):rotation() ) self._unit:get_object( Idstring( "RightForeArm" ) ):m_position( self._unit:get_object( Idstring( "RightArm" ) ):position() ) self._unit:get_object( Idstring( "RightForeArm" ) ):set_position( self._unit:get_object( Idstring( "RightArm" ) ):position() ) self._unit:get_object( Idstring( "RightForeArm" ) ):set_rotation( self._unit:get_object( Idstring( "Spine1" ) ):rotation() ) self._unit:get_object( Idstring( "RightHand" ) ):m_position( self._unit:get_object( Idstring( "Spine1" ) ):position() ) self._unit:get_object( Idstring( "RightHand" ) ):set_position( self._unit:get_object( Idstring( "Spine1" ) ):position() ) self._unit:get_object( Idstring( "RightHand" ) ):set_rotation( self._unit:get_object( Idstring( "Spine1" ) ):rotation() ) end if self._dismemberments.LeftLeg then self._unit:get_object( Idstring( "LeftLeg" ) ):m_position( self._unit:get_object( Idstring( "LeftUpLeg" ) ):position() ) self._unit:get_object( Idstring( "LeftLeg" ) ):set_position( self._unit:get_object( Idstring( "LeftUpLeg" ) ):position() ) self._unit:get_object( Idstring( "LeftLeg" ) ):set_rotation( self._unit:get_object( Idstring( "LeftUpLeg" ) ):rotation() ) self._unit:get_object( Idstring( "LeftFoot" ) ):m_position( self._unit:get_object( Idstring( "Hips" ) ):position() ) self._unit:get_object( Idstring( "LeftFoot" ) ):set_position( self._unit:get_object( Idstring( "Hips" ) ):position() ) self._unit:get_object( Idstring( "LeftFoot" ) ):set_rotation( self._unit:get_object( Idstring( "Hips" ) ):rotation() ) end if self._dismemberments.RightLeg then self._unit:get_object( Idstring( "RightLeg" ) ):m_position( self._unit:get_object( Idstring( "RightUpLeg" ) ):position() ) self._unit:get_object( Idstring( "RightLeg" ) ):set_position( self._unit:get_object( Idstring( "RightUpLeg" ) ):position() ) self._unit:get_object( Idstring( "RightLeg" ) ):set_rotation( self._unit:get_object( Idstring( "RightUpLeg" ) ):rotation() ) self._unit:get_object( Idstring( "RightFoot" ) ):m_position( self._unit:get_object( Idstring( "Hips" ) ):position() ) self._unit:get_object( Idstring( "RightFoot" ) ):set_position( self._unit:get_object( Idstring( "Hips" ) ):position() ) self._unit:get_object( Idstring( "RightFoot" ) ):set_rotation( self._unit:get_object( Idstring( "Hips" ) ):rotation() ) end end if self._dismemberments and self._dismemberments.t and t >= self._dismemberments.t then self._dismemberments = nil end end )
gpl-3.0
Suprcheese/Vehicle-Wagon
stdlib/log/logger.lua
8
4009
--- Logger module -- @module Logger Logger = {} --- Creates a new logger object.<p> -- In debug mode, the logger writes immediately. Otherwise the loggers buffers lines. -- The logger flushes after 60 seconds has elapsed since the last message. -- <p> -- When loggers are created, a table of options may be specified. The valid options are: -- <code> -- log_ticks -- whether to include the game tick timestamp in logs. Defaults to false. -- file_extension -- a string that overides the default 'log' file extension. -- force_append -- each time a logger is created, it will always append, instead of -- -- the default behavior, which is to write out a new file, then append -- </code> -- -- @usage --LOGGER = Logger.new('cool_mod_name') --LOGGER.log("this msg will be logged!") -- -- @usage --LOGGER = Logger.new('cool_mod_name', 'test', true) --LOGGER.log("this msg will be logged and written immediately in test.log!") -- -- @usage --LOGGER = Logger.new('cool_mod_name', 'test', true, { file_extension = data }) --LOGGER.log("this msg will be logged and written immediately in test.data!") -- -- @param mod_name [required] the name of the mod to create the logger for -- @param log_name (optional, default: 'main') the name of the logger -- @param debug_mode (optional, default: false) toggles the debug state of logger. -- @param options (optional) table with optional arguments -- @return the logger instance function Logger.new(mod_name, log_name, debug_mode, options) if not mod_name then error("Logger must be given a mod_name as the first argument") end if not log_name then log_name = "main" end if not options then options = {} end local Logger = {mod_name = mod_name, log_name = log_name, debug_mode = debug_mode, buffer = {}, last_written = 0, ever_written = false} --- Logger options Logger.options = { log_ticks = options.log_ticks or false, -- whether to add the ticks in the timestamp, default false file_extension = options.file_extension or 'log', -- extension of the file, default: log force_append = options.force_append or false, -- append the file on first write, default: false } Logger.file_name = 'logs/' .. Logger.mod_name .. '/' .. Logger.log_name .. '.' .. Logger.options.file_extension Logger.ever_written = Logger.options.force_append --- Logs a message -- @param msg a string, the message to log -- @return true if the message was written, false if it was queued for a later write function Logger.log(msg) local format = string.format if _G.game then local tick = game.tick local floor = math.floor local time_s = floor(tick/60) local time_minutes = floor(time_s/60) local time_hours = floor(time_minutes/60) if Logger.options.log_ticks then table.insert(Logger.buffer, format("%02d:%02d:%02d.%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, tick - time_s*60, msg)) else table.insert(Logger.buffer, format("%02d:%02d:%02d: %s\n", time_hours, time_minutes % 60, time_s % 60, msg)) end -- write the log every minute if (Logger.debug_mode or (tick - Logger.last_written) > 3600) then return Logger.write() end else table.insert(Logger.buffer, format("00:00:00: %s\n", msg)) end return false end --- Writes out all buffered messages immediately -- @return true if there any messages were written, false if not function Logger.write() if _G.game then Logger.last_written = game.tick game.write_file(Logger.file_name, table.concat(Logger.buffer), Logger.ever_written) Logger.buffer = {} Logger.ever_written = true return true end return false end return Logger end return Logger
mit
MeshGeometry/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/function.lua
25
14265
-- tolua: function class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Function class -- Represents a function or a class method. -- The following fields are stored: -- mod = type modifiers -- type = type -- ptr = "*" or "&", if representing a pointer or a reference -- name = name -- lname = lua name -- args = list of argument declarations -- const = if it is a method receiving a const "this". classFunction = { mod = '', type = '', ptr = '', name = '', args = {n=0}, const = '', } classFunction.__index = classFunction setmetatable(classFunction,classFeature) -- declare tags function classFunction:decltype () self.type = typevar(self.type) if strfind(self.mod,'const') then self.type = 'const '..self.type self.mod = gsub(self.mod,'const','') end local i=1 while self.args[i] do self.args[i]:decltype() i = i+1 end end -- Write binding function -- Outputs C/C++ binding function. function classFunction:supcode (local_constructor) local overload = strsub(self.cname,-2,-1) - 1 -- indicate overloaded func local nret = 0 -- number of returned values local class = self:inclass() local _,_,static = strfind(self.mod,'^%s*(static)') if class then if self.name == 'new' and self.parent.flags.pure_virtual then -- no constructor for classes with pure virtual methods return end if local_constructor then output("/* method: new_local of class ",class," */") else output("/* method:",self.name," of class ",class," */") end else output("/* function:",self.name," */") end if local_constructor then output("#ifndef TOLUA_DISABLE_"..self.cname.."_local") output("\nstatic int",self.cname.."_local","(lua_State* tolua_S)") else output("#ifndef TOLUA_DISABLE_"..self.cname) output("\nstatic int",self.cname,"(lua_State* tolua_S)") end output("{") -- check types if overload < 0 then output('#ifndef TOLUA_RELEASE\n') end output(' tolua_Error tolua_err;') output(' if (\n') -- check self local narg if class then narg=2 else narg=1 end if class then local func = get_is_function(self.parent.type) local type = self.parent.type if self.name=='new' or static~=nil then func = 'tolua_isusertable' type = self.parent.type end if self.const ~= '' then type = "const "..type end output(' !'..func..'(tolua_S,1,"'..type..'",0,&tolua_err) ||\n') end -- check args if self.args[1].type ~= 'void' then local i=1 while self.args[i] do local btype = isbasic(self.args[i].type) if btype ~= 'value' and btype ~= 'state' then output(' '..self.args[i]:outchecktype(narg)..' ||\n') end if btype ~= 'state' then narg = narg+1 end i = i+1 end end -- check end of list output(' !tolua_isnoobj(tolua_S,'..narg..',&tolua_err)\n )') output(' goto tolua_lerror;') output(' else\n') if overload < 0 then output('#endif\n') end output(' {') -- declare self, if the case local narg if class then narg=2 else narg=1 end if class and self.name~='new' and static==nil then output(' ',self.const,self.parent.type,'*','self = ') output('(',self.const,self.parent.type,'*) ') local to_func = get_to_function(self.parent.type) output(to_func,'(tolua_S,1,0);') elseif static then _,_,self.mod = strfind(self.mod,'^%s*static%s%s*(.*)') end -- declare parameters if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:declare(narg) if isbasic(self.args[i].type) ~= "state" then narg = narg+1 end i = i+1 end end -- check self if class and self.name~='new' and static==nil then output('#ifndef TOLUA_RELEASE\n') output(' if (!self) tolua_error(tolua_S,"'..output_error_hook("invalid \'self\' in function \'%s\'", self.name)..'", NULL);'); output('#endif\n') end -- get array element values if class then narg=2 else narg=1 end if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:getarray(narg) narg = narg+1 i = i+1 end end pre_call_hook(self) local out = string.find(self.mod, "tolua_outside") -- call function if class and self.name=='delete' then output(' Mtolua_delete(self);') elseif class and self.name == 'operator&[]' then if flags['1'] then -- for compatibility with tolua5 ? output(' self->operator[](',self.args[1].name,'-1) = ',self.args[2].name,';') else output(' self->operator[](',self.args[1].name,') = ',self.args[2].name,';') end else output(' {') if self.type ~= '' and self.type ~= 'void' then output(' ',self.mod,self.type,self.ptr,'tolua_ret = ') output('(',self.mod,self.type,self.ptr,') ') else output(' ') end if class and self.name=='new' then output('Mtolua_new((',self.type,')(') elseif class and static then if out then output(self.name,'(') else output(class..'::'..self.name,'(') end elseif class then if out then output(self.name,'(') else if self.cast_operator then --output('static_cast<',self.mod,self.type,self.ptr,' >(*self') output('self->operator ',self.mod,self.type,'(') else output('self->'..self.name,'(') end end else output(self.name,'(') end if out and not static then output('self') if self.args[1] and self.args[1].name ~= '' then output(',') end end -- write parameters local i=1 while self.args[i] do self.args[i]:passpar() i = i+1 if self.args[i] then output(',') end end if class and self.name == 'operator[]' and flags['1'] then output('-1);') else if class and self.name=='new' then output('));') -- close Mtolua_new( else output(');') end end -- return values if self.type ~= '' and self.type ~= 'void' then nret = nret + 1 local t,ct = isbasic(self.type) if t and self.name ~= "new" then if self.cast_operator and _basic_raw_push[t] then output(' ',_basic_raw_push[t],'(tolua_S,(',ct,')tolua_ret);') else output(' tolua_push'..t..'(tolua_S,(',ct,')tolua_ret);') end else t = self.type new_t = string.gsub(t, "const%s+", "") local owned = false if string.find(self.mod, "tolua_owned") then owned = true end local push_func = get_push_function(t) if self.ptr == '' then output(' {') output('#ifdef __cplusplus\n') output(' void* tolua_obj = Mtolua_new((',new_t,')(tolua_ret));') output(' ',push_func,'(tolua_S,tolua_obj,"',t,'");') output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') output('#else\n') output(' void* tolua_obj = tolua_copy(tolua_S,(void*)&tolua_ret,sizeof(',t,'));') output(' ',push_func,'(tolua_S,tolua_obj,"',t,'");') output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') output('#endif\n') output(' }') elseif self.ptr == '&' then output(' ',push_func,'(tolua_S,(void*)&tolua_ret,"',t,'");') else output(' ',push_func,'(tolua_S,(void*)tolua_ret,"',t,'");') if owned or local_constructor then output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') end end end end local i=1 while self.args[i] do nret = nret + self.args[i]:retvalue() i = i+1 end output(' }') -- set array element values if class then narg=2 else narg=1 end if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:setarray(narg) narg = narg+1 i = i+1 end end -- free dynamically allocated array if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:freearray() i = i+1 end end end post_call_hook(self) output(' }') output(' return '..nret..';') -- call overloaded function or generate error if overload < 0 then output('#ifndef TOLUA_RELEASE\n') output('tolua_lerror:\n') output(' tolua_error(tolua_S,"'..output_error_hook("#ferror in function \'%s\'.", self.lname)..'",&tolua_err);') output(' return 0;') output('#endif\n') else local _local = "" if local_constructor then _local = "_local" end output('tolua_lerror:\n') output(' return '..strsub(self.cname,1,-3)..format("%02d",overload).._local..'(tolua_S);') end output('}') output('#endif //#ifndef TOLUA_DISABLE\n') output('\n') -- recursive call to write local constructor if class and self.name=='new' and not local_constructor then self:supcode(1) end end -- register function function classFunction:register (pre) if not self:check_public_access() then return end if self.name == 'new' and self.parent.flags.pure_virtual then -- no constructor for classes with pure virtual methods return end output(pre..'tolua_function(tolua_S,"'..self.lname..'",'..self.cname..');') if self.name == 'new' then output(pre..'tolua_function(tolua_S,"new_local",'..self.cname..'_local);') output(pre..'tolua_function(tolua_S,".call",'..self.cname..'_local);') --output(' tolua_set_call_event(tolua_S,'..self.cname..'_local, "'..self.parent.type..'");') end end -- Print method function classFunction:print (ident,close) print(ident.."Function{") print(ident.." mod = '"..self.mod.."',") print(ident.." type = '"..self.type.."',") print(ident.." ptr = '"..self.ptr.."',") print(ident.." name = '"..self.name.."',") print(ident.." lname = '"..self.lname.."',") print(ident.." const = '"..self.const.."',") print(ident.." cname = '"..self.cname.."',") print(ident.." lname = '"..self.lname.."',") print(ident.." args = {") local i=1 while self.args[i] do self.args[i]:print(ident.." ",",") i = i+1 end print(ident.." }") print(ident.."}"..close) end -- check if it returns an object by value function classFunction:requirecollection (t) local r = false if self.type ~= '' and not isbasic(self.type) and self.ptr=='' then local type = gsub(self.type,"%s*const%s+","") t[type] = "tolua_collect_" .. clean_template(type) r = true end local i=1 while self.args[i] do r = self.args[i]:requirecollection(t) or r i = i+1 end return r end -- determine lua function name overload function classFunction:overload () return self.parent:overload(self.lname) end function param_object(par) -- returns true if the parameter has an object as its default value if not string.find(par, '=') then return false end -- it has no default value local _,_,def = string.find(par, "=(.*)$") if string.find(par, "|") then -- a list of flags return true end if string.find(par, "%*") then -- it's a pointer with a default value if string.find(par, '=%s*new') or string.find(par, "%(") then -- it's a pointer with an instance as default parameter.. is that valid? return true end return false -- default value is 'NULL' or something end if string.find(par, "[%(&]") then return true end -- default value is a constructor call (most likely for a const reference) --if string.find(par, "&") then -- if string.find(def, ":") or string.find(def, "^%s*new%s+") then -- -- it's a reference with default to something like Class::member, or 'new Class' -- return true -- end --end return false -- ? end function strip_last_arg(all_args, last_arg) -- strips the default value from the last argument local _,_,s_arg = string.find(last_arg, "^([^=]+)") last_arg = string.gsub(last_arg, "([%%%(%)])", "%%%1"); all_args = string.gsub(all_args, "%s*,%s*"..last_arg.."%s*%)%s*$", ")") return all_args, s_arg end -- Internal constructor function _Function (t) setmetatable(t,classFunction) if t.const ~= 'const' and t.const ~= '' then error("#invalid 'const' specification") end append(t) if t:inclass() then --print ('t.name is '..t.name..', parent.name is '..t.parent.name) if string.gsub(t.name, "%b<>", "") == string.gsub(t.parent.original_name or t.parent.name, "%b<>", "") then t.name = 'new' t.lname = 'new' t.parent._new = true t.type = t.parent.name t.ptr = '*' elseif string.gsub(t.name, "%b<>", "") == '~'..string.gsub(t.parent.original_name or t.parent.name, "%b<>", "") then t.name = 'delete' t.lname = 'delete' t.parent._delete = true end end t.cname = t:cfuncname("tolua")..t:overload(t) return t end -- Constructor -- Expects three strings: one representing the function declaration, -- another representing the argument list, and the third representing -- the "const" or empty string. function Function (d,a,c) --local t = split(strsub(a,2,-2),',') -- eliminate braces --local t = split_params(strsub(a,2,-2)) if not flags['W'] and string.find(a, "%.%.%.%s*%)") then warning("Functions with variable arguments (`...') are not supported. Ignoring "..d..a..c) return nil end local i=1 local l = {n=0} a = string.gsub(a, "%s*([%(%)])%s*", "%1") local t,strip,last = strip_pars(strsub(a,2,-2)); if strip then --local ns = string.sub(strsub(a,1,-2), 1, -(string.len(last)+1)) local ns = join(t, ",", 1, last-1) ns = "("..string.gsub(ns, "%s*,%s*$", "")..')' --ns = strip_defaults(ns) local f = Function(d, ns, c) for i=1,last do t[i] = string.gsub(t[i], "=.*$", "") end end while t[i] do l.n = l.n+1 l[l.n] = Declaration(t[i],'var',true) i = i+1 end local f = Declaration(d,'func') f.args = l f.const = c return _Function(f) end function join(t, sep, first, last) first = first or 1 last = last or table.getn(t) local lsep = "" local ret = "" local loop = false for i = first,last do ret = ret..lsep..t[i] lsep = sep loop = true end if not loop then return "" end return ret end function strip_pars(s) local t = split_c_tokens(s, ',') local strip = false local last for i=t.n,1,-1 do if not strip and param_object(t[i]) then last = i strip = true end --if strip then -- t[i] = string.gsub(t[i], "=.*$", "") --end end return t,strip,last end function strip_defaults(s) s = string.gsub(s, "^%(", "") s = string.gsub(s, "%)$", "") local t = split_c_tokens(s, ",") local sep, ret = "","" for i=1,t.n do t[i] = string.gsub(t[i], "=.*$", "") ret = ret..sep..t[i] sep = "," end return "("..ret..")" end
mit
mattyx14/otxserver
data/scripts/spells/monster/terofar_skill_reducer_1.lua
2
1183
local combat = {} for i = 1, 10 do combat[i] = Combat() combat[i]:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_RED) local condition = Condition(CONDITION_ATTRIBUTES) condition:setParameter(CONDITION_PARAM_TICKS, 15000) condition:setParameter(CONDITION_PARAM_SKILL_MELEEPERCENT, i) condition:setParameter(CONDITION_PARAM_SKILL_FISTPERCENT, i) condition:setParameter(CONDITION_PARAM_SKILL_SHIELDPERCENT, i) condition:setParameter(CONDITION_PARAM_SKILL_DISTANCEPERCENT, i) local area = createCombatArea({ {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0} }) combat[i]:setArea(area) combat[i]:addCondition(condition) end local spell = Spell("instant") function spell.onCastSpell(creature, var) return combat[math.random(1, 10)]:execute(creature, var) end spell:name("terofar skill reducer 1") spell:words("###214") spell:isAggressive(true) spell:blockWalls(true) spell:needLearn(true) spell:needDirection(true) spell:register()
gpl-2.0
CarabusX/Zero-K
gamedata/modularcomms/weapons/clusterbomb.lua
6
1464
local name = "commweapon_clusterbomb" local weaponDef = { name = [[Cluster Bomb]], accuracy = 200, avoidFeature = false, avoidNeutral = false, areaOfEffect = 160, burst = 2, burstRate = 0.033, commandFire = true, craterBoost = 1, craterMult = 2, customParams = { is_unit_weapon = 1, slot = [[3]], muzzleEffectFire = [[custom:HEAVY_CANNON_MUZZLE]], miscEffectFire = [[custom:RIOT_SHELL_H]], manualfire = 1, light_camera_height = 2500, light_color = [[0.22 0.19 0.05]], light_radius = 380, reaim_time = 1, }, damage = { default = 300, }, explosionGenerator = [[custom:MEDMISSILE_EXPLOSION]], fireStarter = 180, impulseBoost = 0, impulseFactor = 0.2, interceptedByShieldType = 2, model = [[wep_b_canister.s3o]], projectiles = 4, range = 360, reloadtime = 30, smokeTrail = true, soundHit = [[explosion/ex_med6]], soundHitVolume = 8, soundStart = [[weapon/cannon/cannon_fire3]], soundStartVolume = 2, soundTrigger = true, sprayangle = 2500, turret = true, weaponType = [[Cannon]], weaponVelocity = 400, } return name, weaponDef
gpl-2.0
ldrumm/libbeemo
tests/testingunit.lua
1
23314
#!/usr/bin/env lua TestingUnit = setmetatable({}, { __call = function(self, ...) local test_table = { --[[this table value should be considered immutable as it is used for table discovery]] is_testing_unit = true, fixtures = {}, _assertion_failure = function(self, ...) error("override me", 4) end, assert_raises = function(self, func, args) --[[ given a callable ``func`` and table of arguments ``args``, assert that ``func(unpack(args))`` throws an error. ]] local args = args or {} local success, result = pcall(func, unpack(args)) --we don't want success as this is assert_raises() if success then self:_assertion_failure{ err_str=result, func=func, args=args, traceback=debug.traceback(2), debug_info=debug.getinfo(2) } end end, assert_equal = function(self, a, b) if a ~= b then self:_assertion_failure{ traceback=debug.traceback(2), err_str=string.format("assert_equal failed: %s ~= %s", a , b ), debug_info=debug.getinfo(2), args={a, b} } end end, assert_almost_equal = function(self, a, b, epsilon) local epsilon = epsilon or 0.000001 if (math.abs(a) - math.abs(b)) > epsilon then self:_assertion_failure{ traceback=debug.traceback(2), err_str=string.format( "assert_almost equal failed: %s ~= %s +/-%s", a , b, epsilon ), debug_info=debug.getinfo(2), args={a, b}, } end end, assert_truthy = function(self, x) if not x then self:_assertion_failure{ traceback=debug.traceback(2), err_str=string.format( "assert_truthy failed: '%s' is not truthy", x ), debug_info=debug.getinfo(2), args={x} } end end, assert_true = function(self, x) if x ~= true then self:_assertion_failure{ traceback=debug.traceback(2), err_str=string.format( "assert_true failed:'%s' ~= true", x ), debug_info=debug.getinfo(2), args={x} } end end, fail = function(self, msg, args) self:_assertion_failure{ traceback=debug.traceback(2), err_str=msg, debug_info=debug.getinfo(2), args={args} } end, assert_false = function(self, x) if x ~= false then self:_assertion_failure{ err_str=string.format( "assert_false failed: '%s' ~= false", x ), debug_info=debug.getinfo(2), args={x} } end end, assert_match = function(self, s, exp) if not string.match(s, exp) then self:_assertion_failure{ err_str=string.format( "'%s' does not match '%s'", s, exp ), debug_info=debug.getinfo(2), args={s, exp} } end end, assert_in = function(self, haystack, needle) if type(haystack) ~= 'string' and type(haystack) ~= 'table' then self:_assertion_failure{ err_str=string.format( "type('%s') is not a container type", haystack ), debug_info=debug.getinfo(2), args={needle=needle, haystack=haystack} } return end if type(haystack) == 'string' then if type(needle) ~= 'string' then self:_assertion_failure{ err_str=string.format( "'%s' cannot be a substring of '%s'", tostring(needle), haystack ), debug_info=debug.getinfo(2), args={needle=needle, haystack=haystack} } return end local start, finish = string.find(haystack, needle) if start == nil then self:_assertion_failure{ err_str=string.format( "'%s' not found in '%s'", needle, haystack ), debug_info=debug.getinfo(2), args={needle=needle, haystack=haystack} } return end end if type(haystack) == 'table' then local in_table = false for k, v in pairs(haystack) do if v == needle then in_table = true end end if not in_table then self:_assertion_failure{ traceback=debug.traceback(2), err_str=string.format( "'%s' not found in '%s'", needle, haystack ), debug_info=debug.getinfo(2), args={needle=needle, haystack=haystack} } end end end, assert_nil = function(self, x) if x ~= nil then self:_assertion_failure{ traceback=debug.traceback(2), err_str=string.format("'%s' not nil", x), debug_info=debug.getinfo(2), args={needle=needle, haystack=haystack} } end end, assert_calls = function(self, caller, callee, args) if(type(caller)~='function') or (type(callee)~='function') then error( string.format( [[callable arguments required for assert_calls(). 'Got %s, %s, %s]], caller, callee, args ), 2 ) end local was_called = false local function trace_hook() if debug.getinfo(2, "f").func == callee then was_called = true end end local function getname(func) --From PiL 'the debug library local n = debug.getinfo(func) if n.what == "C" then return n.name end local lc = string.format("[%s]:%d", n.short_src, n.linedefined ) if n.what ~= "main" and n.namewhat ~= "" then return string.format("%s, (%s)", lc, n.name) else return lc end end debug.sethook(trace_hook, 'c') --[[pcall is required here because any errors prevent reporting / cancelling the debug hook]] pcall(caller,args) debug.sethook() if not was_called then self:_assertion_failure{ traceback=debug.traceback(2), err_str=string.format( "assert_calls failure:'%s' not called by '%s' with args(%s)'", getname(callee), getname(caller), table.concat(type(args) == 'table' and args or {args}, ', ') ), debug_info=debug.getinfo(2), args={caller=caller, callee=callee, args=args} } end end } --inherit called values before return. if ... ~= nil then for k, v in pairs(...) do test_table[k] = v end end return test_table end, __tostring = function(self) local tests = {} for k, v in pairs(self) do if type(v) == 'function' and string.match(k, '^test.+') then tests[#tests + 1] = k .. '()' end end return string.format("TestingUnit{%s}", table.concat(tests, ',\n')) end }) function find_test_files(dirs, depth, pattern) --[[discover all lua test scripts in the given directories and put their filenames in the returned array. This currently uses the posix `find` command, so we expect it on $PATH. Sorry Win32... except I'm not. ]] local tests = {} local function enumerate_files(dirs, depth, pattern) -- generator function to enumerate all files within a given directory local dirs = dirs or {'.'} local depth = tonumber(depth) or 2 local pattern = pattern or nil if pattern then pattern = string.format('-iname %q', pattern) else pattern = "" end local function scandir(directory) local t = {} --This quoting is not security safe, but should prevent accidents for filename in io.popen( string.format("find %s -maxdepth %s %s -type f", string.format("%q", directory), depth, pattern ) ):lines() do t[#t + 1] = filename end return t end local all_files = {} for _, dir in pairs(dirs) do for _, v in pairs(scandir(dir)) do all_files[#all_files + 1] = v end end local index = 0 local function file_iter() index = index + 1 return all_files[index] end return file_iter end local function basename(path) local index = string.find(path:reverse(), '/', 1, true) if not index then return path end return string.sub(path, #path-index+2) end for file in enumerate_files(dirs, depth, pattern) do if string.match(basename(file), '^test.*.lua$') then tests[#tests + 1] = file end end return tests end function runtests(all_test_files, show_tracebacks, silence_output) --[[ Given a table containing paths of testing scripts, load each one in turn and execute any TestingUnits instantiated into the global table by the script. The global namespace is reset between each file load, so there are no side-effects from other test files, it is not reset per suite in the case that multiple test suites exist in a single file. This shouldn't present a problem in most cases. ]] local old_globals = {} --we store a clean copy of _G to restore between tests. local n_tests_run = 0 local n_tests_failed = 0 local n_tests_passed = 0 local n_tests_expected_failed = 0 local n_test_errors = 0 local start_time = 0 local stop_time = 0 local failures = {} local errors = {} local expected_failures = {} local function report(...) if not(silence_output) then print(...) end end local function save_globals() --store the contents of the global table locally for k, v in pairs(_G) do old_globals[k] = v end end local function reset_globals() --set the global table back to the saved upvalue local pairs = pairs for k, v in pairs(_G) do if not old_globals[k] then _G[k] = nil end end end local function load_files_iter(files_list) --[[ Given a list of files, load the test into the global environment and return all discovered test tables. warns on failure to load, but skips to the next test. ]] local index = 0 local file_iter = ipairs(files_list) local function iter() local _, file = file_iter(files_list, index) index = index + 1 if file == nil then return nil end local func, err = loadfile(file) report(string.format("loading '%s'...", file)) if func then if not pcall(func) then report(string.format("ERROR:failed to exec '%s'", file)) errors[#errors] = {file=file} return {} else local all_test_units = {} --[[ Iterate the global registry for tables with key ``is_testing_unit == true ``. Add that table to the list of unit test tables. ]] for k, v in pairs(_G) do if type(v) == 'table' then if v.is_testing_unit == true then all_test_units[#all_test_units +1] = v end end end return all_test_units end else report(string.format("ERROR:failed to load '%s':\n\t%s", file, err)) n_test_errors = n_test_errors + 1 return {} end end return iter end function get_fixtures(t, member_name) if not t.fixtures[member_name] then return {{}} end return t.fixtures[member_name] end local function run_test_unit(t) --[[ Search each identified table ``t`` for member functions named ``test*`` and execute each one within pcall, identifying and counting failures, expected failures, and execution errors. ]] local is_expected_failure local last_assertion --[[We inject the following function into the test table so we can reference ``last_assertion`` as a nonlocal variable, and the test table can call self:_assertion_failure() ]] local function _assertion_failure(self, t) last_assertion = t end t._assertion_failure = _assertion_failure --iterate all callables and iterate/call with any supplied fixtures for k, v in pairs(t) do if type(v) == 'function' or (type(v) == 'table' and getmetatable(v) ~= nil and type(getmetatable(v)['__call']) == 'function') then local func_name, callable = k, v if string.match(string.lower(func_name), '^test') then for _, fixture in ipairs(get_fixtures(t, func_name)) do --[[ Expected failures are indicated by naming convention. rather than decorators or similar conventions used in other langauges. The following member functions will be treated as expected failures: test_myfunction_expected_fail' 'TestExpectedFailure' 'test_myfunctionExpected_failREALLYUGLY' Basically any sane name beginning with 'test' having the substrings, 'expected' and 'fail' following. See pattern below for details. ]] is_expected_failure = false last_assertion = nil if string.match( string.lower(func_name), '^test[%a%d_]*expected[%a%d_]*fail' ) then --[[The expected failure handling is a hack relying on the nonlocal variable ``last_assertion`` as semi-global state,but it significantly simplifies the assert_* functions and that's a good thing. ]] is_expected_failure = true end --execute the test with data if t.setup then t:setup(callable, fixture) end local success, ret if #fixture > 0 then success, ret = pcall(callable, t, unpack(fixture)) else success, ret = pcall(callable, t) end n_tests_run = n_tests_run + 1 if not success then errors[#errors +1] = { name=func_name, err_str=ret, args=fixture } end if t.teardown then t:teardown(callable, fixture) end if is_expected_failure then if not last_assertion then n_tests_failed = n_tests_failed + 1 failures[#failures +1 ] = { err_str=string.format( "%s: did not fail as expected", func_name ), debug_info=debug.getinfo(callable), args=fixture, func_name=func_name } else n_tests_expected_failed = n_tests_expected_failed + 1 end else if last_assertion then last_assertion.func_name = func_name n_tests_failed = n_tests_failed + 1 failures[#failures +1 ] = last_assertion else n_tests_passed = n_tests_passed +1 end end end end end end end --actually run all the tests save_globals() start_time = os.time() for t in load_files_iter(all_test_files) do if t then for _, v in ipairs(t) do run_test_unit(v) end end reset_globals() end stop_time = os.time() local function print_results() local function getname(func) --From PiL 'the debug library local n = debug.getinfo(func) if n.what == "C" then return n.name end local lc = string.format("[%s]:%d", n.short_src, n.linedefined) if n.what ~= "main" and n.namewhat ~= "" then return string.format("%s, (%s)", lc, n.name) else return lc end end local function format_args(args) local t = {} if args == nil then return '' end print("args:",args) for k, v in pairs(args)do print(k, v) end for _, arg in ipairs(args) do t[#t + 1] = tostring(arg) end return string.format('(%s)', table.concat(t, ', ')) end for _, f in ipairs(failures) do report(string.rep("=", 70)) report( string.format("FAILURE:%s%s\n%s", f.func_name, format_args(f.args), getname(f.debug_info.func)) ) report(string.rep("-", 70)) report(f.err_str) if show_tracebacks then report(string.format("Traceback:\n%s", f.traceback)) end report() end for _, e in ipairs(errors) do n_test_errors = n_test_errors + 1 report(string.rep("=", 70)) report("ERROR:execution failure:%s%s\n%s") for k, v in pairs(e) do report(k, v) end report(string.rep("-", 70)) end end print_results() report( string.format([[Ran %s tests in %s seconds. %s failures, %s expected failures, %s errors, %s passed]], n_tests_run, os.difftime(stop_time, start_time), n_tests_failed, n_tests_expected_failed, n_test_errors, n_tests_passed ) ) return n_tests_failed + n_test_errors end if arg then script_name = arg[0]:match("[.%w]*$") end if script_name == 'testingunit' or script_name == 'testingunit.lua'then --[[ `arg` is set by the lua repl: 'lua_setglobal(L, "arg");', not by the Lua VM, so this will work in an embedded system that doesn't set `arg`. Fragile much? ]] local test_dirs = #arg > 0 and {} or {'.', 'tests'} local depth = 1 for _, v in ipairs(arg) do if v:match('^--depth=[%d]$') ~= nil then depth = tonumber(v:match('%d')) else test_dirs[#test_dirs + 1] = v end end return os.exit(runtests(find_test_files(test_dirs, depth, "*.lua"))) else return TestingUnit end
lgpl-2.1
mattyx14/otxserver
data/monster/undeads/gravedigger.lua
2
3837
local mType = Game.createMonsterType("Gravedigger") local monster = {} monster.description = "a gravedigger" monster.experience = 950 monster.outfit = { lookType = 558, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.raceId = 975 monster.Bestiary = { class = "Undead", race = BESTY_RACE_UNDEAD, toKill = 1000, FirstUnlock = 50, SecondUnlock = 500, CharmsPoints = 25, Stars = 3, Occurrence = 0, Locations = "Around the higher level areas of Drefia, \z including the Drefia Grim Reaper Dungeons and the Drefia Vampire Crypt." } monster.health = 1500 monster.maxHealth = 1500 monster.race = "blood" monster.corpse = 18962 monster.speed = 240 monster.manaCost = 0 monster.changeTarget = { interval = 4000, chance = 10 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 70, targetDistance = 1, runHealth = 200, healthHidden = false, isBlockable = false, canWalkOnEnergy = true, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "High Five!", yell = false}, {text = "scrabble", yell = false}, {text = "Put it there!", yell = false} } monster.loot = { {name = "gold coin", chance = 100000, maxCount = 137}, {name = "platinum coin", chance = 24470}, {name = "yellow gem", chance = 800}, {name = "wand of inferno", chance = 5590}, {name = "sudden death rune", chance = 7300}, {name = "skull staff", chance = 130}, {name = "mysterious voodoo skull", chance = 100}, {id = 6299, chance = 800}, -- death ring {name = "strong health potion", chance = 2260, maxCount = 2}, {name = "strong mana potion", chance = 3600, maxCount = 2}, {name = "unholy bone", chance = 9570}, {name = "pile of grave earth", chance = 6650}, {name = "safety pin", chance = 6000} } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -320, condition = {type = CONDITION_POISON, totalDamage = 180, interval = 4000}}, {name ="combat", interval = 2000, chance = 10, type = COMBAT_MANADRAIN, minDamage = -40, maxDamage = -250, range = 1, effect = CONST_ME_MAGIC_BLUE, target = false}, {name ="combat", interval = 2000, chance = 15, type = COMBAT_DEATHDAMAGE, minDamage = -175, maxDamage = -300, range = 1, shootEffect = CONST_ANI_DEATH, target = false}, {name ="drunk", interval = 2000, chance = 10, radius = 5, effect = CONST_ME_SMALLCLOUDS, target = false, duration = 4000} } monster.defenses = { defense = 20, armor = 20, {name ="invisible", interval = 2000, chance = 15, effect = CONST_ME_MAGIC_RED}, {name ="combat", interval = 2000, chance = 20, type = COMBAT_HEALING, minDamage = 100, maxDamage = 250, effect = CONST_ME_MAGIC_BLUE, target = false}, {name ="speed", interval = 2000, chance = 15, speedChange = 420, effect = CONST_ME_MAGIC_RED, target = false, duration = 5000} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 100}, {type = COMBAT_EARTHDAMAGE, percent = -5}, {type = COMBAT_FIREDAMAGE, percent = -10}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 100}, {type = COMBAT_HOLYDAMAGE , percent = -5}, {type = COMBAT_DEATHDAMAGE , percent = 100} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
rafael/kong
spec/plugins/rate-limiting/schema_spec.lua
10
1279
local schemas = require "kong.dao.schemas_validation" local validate_entity = schemas.validate_entity local plugin_schema = require "kong.plugins.rate-limiting.schema" describe("Rate Limiting schema", function() it("should be invalid when no config is being set", function() local config = {} local valid, _, err = validate_entity(config, plugin_schema) assert.falsy(valid) assert.are.equal("You need to set at least one limit: second, minute, hour, day, month, year", err.message) end) it("should work when the proper config is being set", function() local config = { second = 10 } local valid, _, err = validate_entity(config, plugin_schema) assert.truthy(valid) assert.falsy(err) end) it("should work when the proper config are being set", function() local config = { second = 10, hour = 20 } local valid, _, err = validate_entity(config, plugin_schema) assert.truthy(valid) assert.falsy(err) end) it("should not work when invalid data is being set", function() local config = { second = 20, hour = 10 } local valid, _, err = validate_entity(config, plugin_schema) assert.falsy(valid) assert.are.equal("The limit for hour cannot be lower than the limit for second", err.message) end) end)
apache-2.0
mattyx14/otxserver
data/monster/magicals/blue_djinn.lua
2
3670
local mType = Game.createMonsterType("Blue Djinn") local monster = {} monster.description = "a blue djinn" monster.experience = 215 monster.outfit = { lookType = 80, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.raceId = 80 monster.Bestiary = { class = "Magical", race = BESTY_RACE_MAGICAL, toKill = 1000, FirstUnlock = 50, SecondUnlock = 500, CharmsPoints = 25, Stars = 3, Occurrence = 0, Locations = "Kha'zeel, Magician Quarter, Forgotten Tomb." } monster.health = 330 monster.maxHealth = 330 monster.race = "blood" monster.corpse = 6020 monster.speed = 220 monster.manaCost = 0 monster.changeTarget = { interval = 4000, chance = 10 } monster.strategiesTarget = { nearest = 100, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = false, staticAttackChance = 90, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "Simsalabim", yell = false}, {text = "Feel the power of my magic, tiny mortal!", yell = false}, {text = "Be careful what you wish for.", yell = false}, {text = "Wishes can come true", yell = false} } monster.loot = { {id = 2829, chance = 2350}, -- book {name = "small oil lamp", chance = 690}, {name = "small sapphire", chance = 2560, maxCount = 4}, {name = "gold coin", chance = 60000, maxCount = 70}, {name = "gold coin", chance = 70000, maxCount = 45}, {name = "mystic turban", chance = 70}, {id = 3595, chance = 23480}, -- carrot {name = "blue rose", chance = 440}, {name = "blue piece of cloth", chance = 1920}, {name = "royal spear", chance = 4500, maxCount = 2}, {name = "mana potion", chance = 860}, {name = "dirty turban", chance = 1890} } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -110}, {name ="combat", interval = 2000, chance = 15, type = COMBAT_FIREDAMAGE, minDamage = -45, maxDamage = -80, range = 7, shootEffect = CONST_ANI_FIRE, target = false}, {name ="combat", interval = 2000, chance = 10, type = COMBAT_DEATHDAMAGE, minDamage = -60, maxDamage = -105, range = 7, radius = 1, shootEffect = CONST_ANI_SUDDENDEATH, effect = CONST_ME_SMALLCLOUDS, target = true}, {name ="drunk", interval = 2000, chance = 10, range = 7, shootEffect = CONST_ANI_ENERGY, target = false, duration = 5000}, {name ="outfit", interval = 2000, chance = 1, range = 7, effect = CONST_ME_MAGIC_BLUE, target = false, duration = 4000, outfitMonster = "rabbit"}, {name ="djinn electrify", interval = 2000, chance = 15, range = 5, target = false}, {name ="djinn cancel invisibility", interval = 2000, chance = 10, target = false} } monster.defenses = { defense = 15, armor = 15 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 50}, {type = COMBAT_EARTHDAMAGE, percent = 0}, {type = COMBAT_FIREDAMAGE, percent = 80}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = -10}, {type = COMBAT_HOLYDAMAGE , percent = 20}, {type = COMBAT_DEATHDAMAGE , percent = -13} } monster.immunities = { {type = "paralyze", condition = true}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
mojo2012/factorio-mojo-resource-processing
prototypes/recipe/ore-processing/ore-copper.lua
1
2076
-- reset original iron plate recipe data.raw["recipe"]["copper-plate"] = nil data:extend({ { -- ore materials type = "recipe", name = "ore-copper-crushed", category = "ore-crusher", subgroup = "copper", energy_required = 3, icon = "__mojo-resource-processing__/graphics/icons/ore-copper/crushed-ore-copper.png", ingredients = { {"copper-ore", 3} }, enabled = false, results = { {"ore-copper-crushed", 2}, {"stone", 2} } }, { type = "recipe", name = "ore-copper-pulverized", category = "ore-pulverizer", subgroup = "copper", energy_required = 3, icon = "__mojo-resource-processing__/graphics/icons/ore-copper/pulverized-ore-copper.png", ingredients = { {"ore-copper-crushed", 3} }, enabled = false, results = { {"ore-copper-pulverized", 5}, {"gravel", 1} } }, { -- copper plates type = "recipe", name = "copper-plate", category = "smelting", subgroup = "copper", energy_required = 10, icon = "__base__/graphics/icons/copper-plate.png", ingredients = { {"copper-ore", 3} }, enabled = true, results = { {"copper-plate", 1}, {"slag", 1} } }, { type = "recipe", name = "copper-plate-crushed-ore", category = "smelting", subgroup = "copper", energy_required = 8, icon = "__base__/graphics/icons/copper-plate.png", ingredients = { {"ore-copper-crushed", 3} }, enabled = false, results = { {"copper-plate", 3}, {"slag", 1}, } }, { type = "recipe", name = "copper-plate-pulverized-ore", category = "smelting", subgroup = "copper", energy_required = 8, icon = "__base__/graphics/icons/copper-plate.png", ingredients = { {"ore-copper-pulverized", 1} }, enabled = false, results = { {"copper-plate", 1} } }, })
gpl-3.0
dinodeck/rpg_conversation_graph
nwn_dialog_advanced/code/combat_events/CESlash.lua
10
3716
CESlash = {} CESlash.__index = CESlash function CESlash:Create(state, owner, def, targets) local this = { mState = state, mOwner = owner, mDef = def, mFinished = false, mCharacter = state.mActorCharMap[owner], mTargets = targets, mIsFinished = false } this.mController = this.mCharacter.mController this.mController:Change(CSRunAnim.mName, {'prone'}) this.mName = string.format("Slash for %s", this.mOwner.mName) setmetatable(this, self) local storyboard = nil this.mAttackAnim = gEntities.slash this.mDefaultTargeter = CombatSelector.SideEnemy storyboard = { SOP.Function(function() this:ShowNotice() end), SOP.Wait(0.2), SOP.RunState(this.mController, CSMove.mName, {dir = 1}), SOP.RunState(this.mController, CSRunAnim.mName, {'slash', false, 0.05}), SOP.NoBlock( SOP.RunState(this.mController, CSRunAnim.mName, {'prone'}) ), SOP.Function(function() this:DoAttack() end), SOP.RunState(this.mController, CSMove.mName, {dir = -1}), SOP.Wait(0.2), SOP.Function(function() this:OnFinish() end) } this.mStoryboard = Storyboard:Create(this.mState.mStack, storyboard) return this end function CESlash:TimePoints(queue) local speed = self.mOwner.mStats:Get("speed") local tp = queue:SpeedToTimePoints(speed) return tp + self.mDef.time_points end function CESlash:ShowNotice() self.mState:ShowNotice(self.mDef.name) end function CESlash:Execute(queue) self.mState.mStack:Push(self.mStoryboard) for i = #self.mTargets, 1, -1 do local v = self.mTargets[i] local hp = v.mStats:Get("hp_now") if hp <= 0 then table.remove(self.mTargets, i) end end if not next(self.mTargets) then -- Find another enemy self.mTargets = self.mDefaultTargeter(self.mState) end end function CESlash:OnFinish() self.mIsFinished = true end function CESlash:IsFinished() return self.mIsFinished end function CESlash:Update() end function CESlash:DoAttack() self.mState:HideNotice() local mp = self.mOwner.mStats:Get("mp_now") local cost = self.mDef.mp_cost local mp = math.max(mp - cost, 0) -- don't handle fizzle self.mOwner.mStats:Set("mp_now", mp) for _, target in ipairs(self.mTargets) do self:AttackTarget(target) if not self.mDef.counter then self:CounterTarget(target) end end end -- Decide if the attack is countered. function CESlash:CounterTarget(target) local countered = Formula.IsCountered(self.mState, self.mOwner, target) if countered then self.mState:ApplyCounter(target, self.mOwner) end end function CESlash:AttackTarget(target) local damage, hitResult = Formula.MeleeAttack(self.mState, self.mOwner, target) -- hit result lets us know the status of this attack local entity = self.mState.mActorCharMap[target].mEntity if hitResult == HitResult.Miss then self.mState:ApplyMiss(target) return elseif hitResult == HitResult.Dodge then self.mState:ApplyDodge(target) else local isCrit = hitResult == HitResult.Critical self.mState:ApplyDamage(target, damage, isCrit) end local x = entity.mX local y = entity.mY local effect = AnimEntityFx:Create(x, y, self.mAttackAnim, self.mAttackAnim.frames) self.mState:AddEffect(effect) end
mit
williamhogman/dsv-gamejam16
hump/gamestate.lua
14
3533
--[[ Copyright (c) 2010-2013 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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 function __NULL__() end -- default gamestate produces error on every callback local state_init = setmetatable({leave = __NULL__}, {__index = function() error("Gamestate not initialized. Use Gamestate.switch()") end}) local stack = {state_init} local initialized_states = setmetatable({}, {__mode = "k"}) local state_is_dirty = true local GS = {} function GS.new(t) return t or {} end -- constructor - deprecated! local function change_state(stack_offset, to, ...) local pre = stack[#stack] -- initialize only on first call ;(initialized_states[to] or to.init or __NULL__)(to) initialized_states[to] = __NULL__ stack[#stack+stack_offset] = to state_is_dirty = true return (to.enter or __NULL__)(to, pre, ...) end function GS.switch(to, ...) assert(to, "Missing argument: Gamestate to switch to") assert(to ~= GS, "Can't call switch with colon operator") ;(stack[#stack].leave or __NULL__)(stack[#stack]) return change_state(0, to, ...) end function GS.push(to, ...) assert(to, "Missing argument: Gamestate to switch to") assert(to ~= GS, "Can't call push with colon operator") return change_state(1, to, ...) end function GS.pop(...) assert(#stack > 1, "No more states to pop!") local pre, to = stack[#stack], stack[#stack-1] stack[#stack] = nil ;(pre.leave or __NULL__)(pre) state_is_dirty = true return (to.resume or __NULL__)(to, pre, ...) end function GS.current() return stack[#stack] end -- fetch event callbacks from love.handlers local all_callbacks = { 'draw', 'errhand', 'update' } for k in pairs(love.handlers) do all_callbacks[#all_callbacks+1] = k end function GS.registerEvents(callbacks) local registry = {} callbacks = callbacks or all_callbacks for _, f in ipairs(callbacks) do registry[f] = love[f] or __NULL__ love[f] = function(...) registry[f](...) return GS[f](...) end end end -- forward any undefined functions setmetatable(GS, {__index = function(_, func) -- call function only if at least one 'update' was called beforehand -- (see issue #46) if not state_is_dirty or func == 'update' then state_is_dirty = false return function(...) return (stack[#stack][func] or __NULL__)(stack[#stack], ...) end end return __NULL__ end}) return GS
mit
rafael/kong
kong/api/routes/apis.lua
7
2490
local crud = require "kong.api.crud_helpers" local syslog = require "kong.tools.syslog" local constants = require "kong.constants" return { ["/apis/"] = { GET = function(self, dao_factory) crud.paginated_set(self, dao_factory.apis) end, PUT = function(self, dao_factory) crud.put(self.params, dao_factory.apis) end, POST = function(self, dao_factory) crud.post(self.params, dao_factory.apis) end }, ["/apis/:name_or_id"] = { before = crud.find_api_by_name_or_id, GET = function(self, dao_factory, helpers) return helpers.responses.send_HTTP_OK(self.api) end, PATCH = function(self, dao_factory) crud.patch(self.params, self.api, dao_factory.apis) end, DELETE = function(self, dao_factory) crud.delete(self.api, dao_factory.apis) end }, ["/apis/:name_or_id/plugins/"] = { before = function(self, dao_factory, helpers) crud.find_api_by_name_or_id(self, dao_factory, helpers) self.params.api_id = self.api.id end, GET = function(self, dao_factory) crud.paginated_set(self, dao_factory.plugins) end, POST = function(self, dao_factory, helpers) crud.post(self.params, dao_factory.plugins, function(data) if configuration.send_anonymous_reports then data.signal = constants.SYSLOG.API syslog.log(syslog.format_entity(data)) end end) end, PUT = function(self, dao_factory, helpers) crud.put(self.params, dao_factory.plugins) end }, ["/apis/:name_or_id/plugins/:plugin_id"] = { before = function(self, dao_factory, helpers) crud.find_api_by_name_or_id(self, dao_factory, helpers) self.params.api_id = self.api.id local fetch_keys = { api_id = self.api.id, id = self.params.plugin_id } self.params.plugin_id = nil local data, err = dao_factory.plugins:find_by_keys(fetch_keys) if err then return helpers.yield_error(err) end self.plugin = data[1] if not self.plugin then return helpers.responses.send_HTTP_NOT_FOUND() end end, GET = function(self, dao_factory, helpers) return helpers.responses.send_HTTP_OK(self.plugin) end, PATCH = function(self, dao_factory, helpers) crud.patch(self.params, self.plugin, dao_factory.plugins) end, DELETE = function(self, dao_factory) crud.delete(self.plugin, dao_factory.plugins) end } }
apache-2.0
junkblocker/hammerspoon
extensions/redshift/init.lua
5
20133
--- === hs.redshift === --- --- Inverts and/or lowers the color temperature of the screen(s) on a schedule, for a more pleasant experience at night --- --- Usage: --- ``` --- -- make a windowfilterDisable for redshift: VLC, Photos and screensaver/login window will disable color adjustment and inversion --- local wfRedshift=hs.window.filter.new({VLC={focused=true},Photos={focused=true},loginwindow={visible=true,allowRoles='*'}},'wf-redshift') --- -- start redshift: 2800K + inverted from 21 to 7, very long transition duration (19->23 and 5->9) --- hs.redshift.start(2800,'21:00','7:00','4h',true,wfRedshift) --- -- allow manual control of inverted colors --- hs.hotkey.bind(HYPER,'f1','Invert',hs.redshift.toggleInvert) --- ``` local screen=require'hs.screen' local timer=require'hs.timer' local windowfilter=require'hs.window.filter' local settings=require'hs.settings' local log=require'hs.logger'.new('redshift') local redshift={setLogLevel=log.setLogLevel} -- module local type,ipairs,pairs,next,floor,abs,min,max,sformat=type,ipairs,pairs,next,math.floor,math.abs,math.min,math.max,string.format local SETTING_INVERTED_OVERRIDE='hs.redshift.inverted.override' local SETTING_DISABLED_OVERRIDE='hs.redshift.disabled.override' --local BLACKPOINT = {red=0.00000001,green=0.00000001,blue=0.00000001} local BLACKPOINT = {red=0,green=0,blue=0} --local COLORRAMP local running,nightStart,nightEnd,dayStart,dayEnd,nightTemp,dayTemp local tmr,tmrNext,applyGamma,screenWatcher local invertRequests,invertCallbacks,invertAtNight,invertUser,prevInvert={},{} local disableRequests,disableUser={} local wfDisable,modulewfDisable local function round(v) return floor(0.5+v) end local function lerprgb(p,a,b) return {red=a[1]*(1-p)+b[1]*p,green=a[2]*(1-p)+b[2]*p,blue=a[3]*(1-p)+b[3]*p} end local function ilerp(v,s,e,a,b) if s>e then if v<e then v=v+86400 end e=e+86400 end local p=(v-s)/(e-s) return a*(1-p)+b*p end local function getGamma(temp) local R,lb,ub=redshift.COLORRAMP for k,v in pairs(R) do if k<=temp then lb=max(lb or 0,k) else ub=min(ub or 10000,k) end end if lb==nil or ub==nil then local t=R[ub or lb] return {red=t[1],green=t[2],blue=t[3]} end local p=(temp-lb)/(ub-lb) return lerprgb(p,R[lb],R[ub]) -- local idx=floor(temp/100)-9 -- local p=(temp%100)/100 -- return lerprgb(p,COLORRAMP[idx],COLORRAMP[idx+1]) end local function between(v,s,e) if s<=e then return v>=s and v<=e else return v>=s or v<=e end end local function isInverted() if not running then return false end if invertUser~=nil then return invertUser and 'user' else return next(invertRequests) or false end end local function isDisabled() if not running then return true end if disableUser~=nil then return disableUser and 'user' else return next(disableRequests) or false end end -- core fn applyGamma=function() if tmrNext then tmrNext:stop() tmrNext=nil end local now=timer.localTime() local temp,timeNext,invertReq if isDisabled() then temp=6500 timeNext=now-1 log.i('disabled') elseif between(now,nightStart,nightEnd) then temp=ilerp(now,nightStart,nightEnd,dayTemp,nightTemp) --dusk elseif between(now,dayStart,dayEnd) then temp=ilerp(now,dayStart,dayEnd,nightTemp,dayTemp) --dawn elseif between(now,dayEnd,nightStart) then temp=dayTemp timeNext=nightStart log.i('daytime')--day elseif between(now,nightEnd,dayStart) then invertReq=invertAtNight temp=nightTemp timeNext=dayStart log.i('nighttime')--night else error('wtf') end redshift.requestInvert('redshift-night',invertReq) local invert=isInverted() local gamma=getGamma(temp) log.df('set color temperature %dK (gamma %d,%d,%d)%s',floor(temp),round(gamma.red*100), round(gamma.green*100),round(gamma.blue*100),invert and (' - inverted by '..invert) or '') for _,scr in ipairs(screen.allScreens()) do scr:setGamma(invert and BLACKPOINT or gamma,invert and gamma or BLACKPOINT) end if invert~=prevInvert then log.i('inverted status changed',next(invertCallbacks) and '- notifying callbacks' or '') for _,fn in pairs(invertCallbacks) do fn(invert) end prevInvert=invert end if timeNext then tmrNext=timer.doAt(timeNext,applyGamma) else tmr:start() end end --- hs.redshift.invertSubscribe([id,]fn) --- Function --- Subscribes a callback to be notified when the color inversion status changes --- --- You can use this to dynamically adjust the UI colors in your modules or configuration, if appropriate. --- --- Parameters: --- * id - (optional) a string identifying the requester (usually the module name); if omitted, `fn` --- itself will be the identifier; this identifier must be passed to `hs.redshift.invertUnsubscribe()` --- * fn - a function that will be called whenever color inversion status changes; it must accept a --- single parameter, a string or false as per the return value of `hs.redshift.isInverted()` --- --- Returns: --- * None function redshift.invertSubscribe(key,fn) if type(key)=='function' then fn=key end if type(key)~='string' and type(key)~='function' then error('invalid key',2) end if type(fn)~='function' then error('invalid callback',2) end invertCallbacks[key]=fn log.i('add invert callback',key) return running and fn(isInverted()) end --- hs.redshift.invertUnsubscribe(id) --- Function --- Unsubscribes a previously subscribed color inversion change callback --- --- Parameters: --- * id - a string identifying the requester or the callback function itself, depending on how you --- called `hs.redshift.invertSubscribe()` --- --- Returns: --- * None function redshift.invertUnsubscribe(key) if not invertCallbacks[key] then return end log.i('remove invert callback',key) invertCallbacks[key]=nil end --- hs.redshift.isInverted() -> string or false --- Function --- Checks if the colors are currently inverted --- --- Parameters: --- * None --- --- Returns: --- * false if the colors are not currently inverted; otherwise, a string indicating the reason, one of: --- * "user" for the user override (see `hs.redshift.toggleInvert()`) --- * "redshift-night" if `hs.redshift.start()` was called with `invertAtNight` set to true, --- and it's currently night time --- * the ID string (usually the module name) provided to `hs.redshift.requestInvert()`, if another module requested color inversion redshift.isInverted=isInverted redshift.isDisabled=isDisabled --- hs.redshift.requestInvert(id,v) --- Function --- Sets or clears a request for color inversion --- --- Parameters: --- * id - a string identifying the requester (usually the module name) --- * v - a boolean indicating whether to invert the colors (if true) or clear any previous requests (if false or nil) --- --- Returns: --- * None --- --- Notes: --- * you can use this function e.g. to automatically invert colors if the ambient light sensor reading drops below --- a certain threshold (`hs.brightness.DDCauto()` can optionally do exactly that) --- * if the user's configuration doesn't explicitly start the redshift module, calling this will have no effect local function request(t,k,v) if type(k)~='string' then error('key must be a string',3) end if v==false then v=nil end if t[k]~=v then t[k]=v return true end end function redshift.requestInvert(key,v) if request(invertRequests,key,v) then log.f('invert request from %s %s',key,v and '' or 'canceled') return running and applyGamma() end end function redshift.requestDisable(key,v) if request(disableRequests,key,v) then log.f('disable color adjustment request from %s %s',key,v and '' or 'canceled') return running and applyGamma() end end --- hs.redshift.toggleInvert([v]) --- Function --- Sets or clears the user override for color inversion. --- --- This function should be bound to a hotkey, e.g.: --- `hs.hotkey.bind('ctrl-cmd','=','Invert',hs.redshift.toggleInvert)` --- --- Parameters: --- * v - (optional) a boolean; if true, the override will invert the colors no matter what; if false, --- the override will disable color inversion no matter what; if omitted or nil, it will toggle the --- override, i.e. clear it if it's currently enforced, or set it to the opposite of the current --- color inversion status otherwise. --- --- Returns: --- * None function redshift.toggleInvert(v) if not running then return end if v==nil and invertUser==nil then v=not isInverted() end if v~=nil and type(v)~='boolean' then error ('v must be a boolean or nil',2) end log.f('invert user override%s',v==true and ': inverted' or (v==false and ': not inverted' or ' cancelled')) if v==nil then settings.clear(SETTING_INVERTED_OVERRIDE) else settings.set(SETTING_INVERTED_OVERRIDE,v) end invertUser=v return applyGamma() end --- hs.redshift.toggle([v]) --- Function --- Sets or clears the user override for color temperature adjustment. --- --- This function should be bound to a hotkey, e.g.: --- `hs.hotkey.bind('ctrl-cmd','-','Redshift',hs.redshift.toggle)` --- --- Parameters: --- * v - (optional) a boolean; if true, the override will enable color temperature adjustment on --- the given schedule; if false, the override will disable color temperature adjustment; --- if omitted or nil, it will toggle the override, i.e. clear it if it's currently enforced, or --- set it to the opposite of the current color temperature adjustment status otherwise. --- --- Returns: --- * None function redshift.toggle(v) if not running then return end if v==nil then if disableUser==nil then v=not isDisabled() end elseif type(v)~='boolean' then error ('v must be a boolean or nil',2) else v=not v end log.f('color adjustment user override%s',v==true and ': disabled' or (v==false and ': enabled' or ' cancelled')) if v==nil then settings.clear(SETTING_DISABLED_OVERRIDE) else settings.set(SETTING_DISABLED_OVERRIDE,v) end disableUser=v return applyGamma() end --- hs.redshift.stop() --- Function --- Stops the module and disables color adjustment and color inversion --- --- Parameters: --- * None --- --- Returns: --- * None function redshift.stop() if not running then return end log.i('stopped') tmr:stop() screen.restoreGamma() if wfDisable then if modulewfDisable then modulewfDisable:delete() modulewfDisable=nil else wfDisable:unsubscribe(redshift.wfsubs) end wfDisable=nil end if tmrNext then tmrNext:stop() tmrNext=nil end screenWatcher:stop() screenWatcher=nil running=nil end local function gc(t) return t.stop()end local function stime(time) return sformat('%02d:%02d:%02d',floor(time/3600),floor(time/60)%60,floor(time%60)) end tmr=timer.delayed.new(10,applyGamma) --- hs.redshift.start(colorTemp,nightStart,nightEnd[,transition[,invertAtNight[,windowfilterDisable[,dayColorTemp]]]]) --- Function --- Sets the schedule and (re)starts the module --- --- Parameters: --- * colorTemp - a number indicating the desired color temperature (Kelvin) during the night cycle; --- the recommended range is between 3600K and 1400K; lower values (minimum 1000K) result in a more pronounced adjustment --- * nightStart - a string in the format "HH:MM" (24-hour clock) or number of seconds after midnight --- (see `hs.timer.seconds()`) indicating when the night cycle should start --- * nightEnd - a string in the format "HH:MM" (24-hour clock) or number of seconds after midnight --- (see `hs.timer.seconds()`) indicating when the night cycle should end --- * transition - (optional) a string or number of seconds (see `hs.timer.seconds()`) indicating the duration of --- the transition to the night color temperature and back; if omitted, defaults to 1 hour --- * invertAtNight - (optional) a boolean indicating whether the colors should be inverted (in addition to --- the color temperature shift) during the night; if omitted, defaults to false --- * windowfilterDisable - (optional) an `hs.window.filter` instance that will disable color adjustment --- (and color inversion) whenever any window is allowed; alternatively, you can just provide a list of application --- names (typically media apps and/or apps for color-sensitive work) and a windowfilter will be created --- for you that disables color adjustment whenever one of these apps is focused --- * dayColorTemp - (optional) a number indicating the desired color temperature (in Kelvin) during the day cycle; --- you can use this to maintain some degree of "redshift" during the day as well, or, if desired, you can --- specify a value higher than 6500K (up to 10000K) for more bluish colors, although that's not recommended; --- if omitted, defaults to 6500K, which disables color adjustment and restores your screens' original color profiles --- --- Returns: --- * None function redshift.start(nTemp,nStart,nEnd,dur,invert,wf,dTemp) if not dTemp then dTemp=6500 end if nTemp<1000 or nTemp>10000 or dTemp<1000 or dTemp>10000 then error('invalid color temperature',2) end nStart,nEnd=timer.seconds(nStart),timer.seconds(nEnd) dur=timer.seconds(dur or 3600) if dur>14400 then error('max transition time is 4h',2) end if abs(nStart-nEnd)<dur or abs(nStart-nEnd+86400)<dur or abs(nStart-nEnd-86400)<dur then error('nightTime too close to dayTime',2) end nightTemp,dayTemp=floor(nTemp),floor(dTemp) redshift.stop() invertAtNight=invert nightStart,nightEnd=(nStart-dur/2)%86400,(nStart+dur/2)%86400 dayStart,dayEnd=(nEnd-dur/2)%86400,(nEnd+dur/2)%86400 log.f('started: %dK @ %s -> %dK @ %s,%s %dK @ %s -> %dK @ %s', dayTemp,stime(nightStart),nightTemp,stime(nightEnd),invert and ' inverted,' or '',nightTemp,stime(dayStart),dayTemp,stime(dayEnd)) running=true tmr:setDelay(max(1,dur/200)) screenWatcher=screen.watcher.new(function()tmr:start(5)end):start() invertUser=settings.get(SETTING_INVERTED_OVERRIDE) disableUser=settings.get(SETTING_DISABLED_OVERRIDE) applyGamma() if wf~=nil then if windowfilter.iswf(wf) then wfDisable=wf else wfDisable=windowfilter.new(wf,'wf-redshift',log.getLogLevel()) modulewfDisable=wfDisable if type(wf=='table') then local isAppList=true for k,v in pairs(wf) do if type(k)~='number' or type(v)~='string' then isAppList=false break end end if isAppList then wfDisable:setOverrideFilter{focused=true} end end end redshift.wfsubs={ [windowfilter.hasWindow]=function()redshift.requestDisable('wf-redshift',true)end, [windowfilter.hasNoWindows]=function()redshift.requestDisable('wf-redshift')end, } wfDisable:subscribe(redshift.wfsubs,true) end end --- hs.redshift.COLORRAMP --- Variable --- A table holding the gamma values for given color temperatures; each key must be a color temperature number in K (useful values are between --- 1400 and 6500), and each value must be a list of 3 gamma numbers between 0 and 1 for red, green and blue respectively. --- The table must have at least two entries (a lower and upper bound); the actual gamma values used for a given color temperature --- are linearly interpolated between the two closest entries; linear interpolation isn't particularly precise for this use case, --- so you should provide as many values as possible. --- --- Notes: --- * `hs.inspect(hs.redshift.COLORRAMP)` from the console will show you how the table is built --- * the default ramp has entries from 1000K to 10000K every 100K redshift.COLORRAMP={ -- from https://github.com/jonls/redshift/blob/master/src/colorramp.c [1000]={1.00000000, 0.18172716, 0.00000000}, -- 1000K [1100]={1.00000000, 0.25503671, 0.00000000}, -- 1100K [1200]={1.00000000, 0.30942099, 0.00000000}, -- 1200K [1300]={1.00000000, 0.35357379, 0.00000000}, -- ... [1400]={1.00000000, 0.39091524, 0.00000000}, [1500]={1.00000000, 0.42322816, 0.00000000}, [1600]={1.00000000, 0.45159884, 0.00000000}, [1700]={1.00000000, 0.47675916, 0.00000000}, [1800]={1.00000000, 0.49923747, 0.00000000}, [1900]={1.00000000, 0.51943421, 0.00000000}, [2000]={1.00000000, 0.54360078, 0.08679949}, [2100]={1.00000000, 0.56618736, 0.14065513}, [2200]={1.00000000, 0.58734976, 0.18362641}, [2300]={1.00000000, 0.60724493, 0.22137978}, [2400]={1.00000000, 0.62600248, 0.25591950}, [2500]={1.00000000, 0.64373109, 0.28819679}, [2600]={1.00000000, 0.66052319, 0.31873863}, [2700]={1.00000000, 0.67645822, 0.34786758}, [2800]={1.00000000, 0.69160518, 0.37579588}, [2900]={1.00000000, 0.70602449, 0.40267128}, [3000]={1.00000000, 0.71976951, 0.42860152}, [3100]={1.00000000, 0.73288760, 0.45366838}, [3200]={1.00000000, 0.74542112, 0.47793608}, [3300]={1.00000000, 0.75740814, 0.50145662}, [3400]={1.00000000, 0.76888303, 0.52427322}, [3500]={1.00000000, 0.77987699, 0.54642268}, [3600]={1.00000000, 0.79041843, 0.56793692}, [3700]={1.00000000, 0.80053332, 0.58884417}, [3800]={1.00000000, 0.81024551, 0.60916971}, [3900]={1.00000000, 0.81957693, 0.62893653}, [4000]={1.00000000, 0.82854786, 0.64816570}, [4100]={1.00000000, 0.83717703, 0.66687674}, [4200]={1.00000000, 0.84548188, 0.68508786}, [4300]={1.00000000, 0.85347859, 0.70281616}, [4400]={1.00000000, 0.86118227, 0.72007777}, [4500]={1.00000000, 0.86860704, 0.73688797}, [4600]={1.00000000, 0.87576611, 0.75326132}, [4700]={1.00000000, 0.88267187, 0.76921169}, [4800]={1.00000000, 0.88933596, 0.78475236}, [4900]={1.00000000, 0.89576933, 0.79989606}, [5000]={1.00000000, 0.90198230, 0.81465502}, [5100]={1.00000000, 0.90963069, 0.82838210}, [5200]={1.00000000, 0.91710889, 0.84190889}, [5300]={1.00000000, 0.92441842, 0.85523742}, [5400]={1.00000000, 0.93156127, 0.86836903}, [5500]={1.00000000, 0.93853986, 0.88130458}, [5600]={1.00000000, 0.94535695, 0.89404470}, [5700]={1.00000000, 0.95201559, 0.90658983}, [5800]={1.00000000, 0.95851906, 0.91894041}, [5900]={1.00000000, 0.96487079, 0.93109690}, [6000]={1.00000000, 0.97107439, 0.94305985}, [6100]={1.00000000, 0.97713351, 0.95482993}, [6200]={1.00000000, 0.98305189, 0.96640795}, [6300]={1.00000000, 0.98883326, 0.97779486}, [6400]={1.00000000, 0.99448139, 0.98899179}, [6500]={1.00000000, 1.00000000, 1.00000000}, -- 6500K -- [6500]={0.99999997, 0.99999997, 0.99999997}, --6500K [6600]={0.98947904, 0.99348723, 1.00000000}, [6700]={0.97940448, 0.98722715, 1.00000000}, [6800]={0.96975025, 0.98120637, 1.00000000}, [6900]={0.96049223, 0.97541240, 1.00000000}, [7000]={0.95160805, 0.96983355, 1.00000000}, [7100]={0.94303638, 0.96443333, 1.00000000}, [7200]={0.93480451, 0.95923080, 1.00000000}, [7300]={0.92689056, 0.95421394, 1.00000000}, [7400]={0.91927697, 0.94937330, 1.00000000}, [7500]={0.91194747, 0.94470005, 1.00000000}, [7600]={0.90488690, 0.94018594, 1.00000000}, [7700]={0.89808115, 0.93582323, 1.00000000}, [7800]={0.89151710, 0.93160469, 1.00000000}, [7900]={0.88518247, 0.92752354, 1.00000000}, [8000]={0.87906581, 0.92357340, 1.00000000}, [8100]={0.87315640, 0.91974827, 1.00000000}, [8200]={0.86744421, 0.91604254, 1.00000000}, [8300]={0.86191983, 0.91245088, 1.00000000}, [8400]={0.85657444, 0.90896831, 1.00000000}, [8500]={0.85139976, 0.90559011, 1.00000000}, [8600]={0.84638799, 0.90231183, 1.00000000}, [8700]={0.84153180, 0.89912926, 1.00000000}, [8800]={0.83682430, 0.89603843, 1.00000000}, [8900]={0.83225897, 0.89303558, 1.00000000}, [9000]={0.82782969, 0.89011714, 1.00000000}, [9100]={0.82353066, 0.88727974, 1.00000000}, [9200]={0.81935641, 0.88452017, 1.00000000}, [9300]={0.81530175, 0.88183541, 1.00000000}, [9400]={0.81136180, 0.87922257, 1.00000000}, [9500]={0.80753191, 0.87667891, 1.00000000}, [9600]={0.80380769, 0.87420182, 1.00000000}, [9700]={0.80018497, 0.87178882, 1.00000000}, [9800]={0.79665980, 0.86943756, 1.00000000}, [9900]={0.79322843, 0.86714579, 1.00000000}, [10000]={0.78988728, 0.86491137, 1.00000000}, -- 10000K } return setmetatable(redshift,{__gc=gc})
mit
UB12/wnww
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
CarabusX/Zero-K
LuaRules/Gadgets/Include/LuaShader.lua
10
13124
local UNIFORM_TYPE_MIXED = 0 -- includes arrays; float or int local UNIFORM_TYPE_INT = 1 -- includes arrays local UNIFORM_TYPE_FLOAT = 2 -- includes arrays local UNIFORM_TYPE_FLOAT_MATRIX = 3 local glGetUniformLocation = gl.GetUniformLocation local glUseShader = gl.UseShader local glActiveShader = gl.ActiveShader local glUniform = gl.Uniform local glUniformInt = gl.UniformInt local glUniformMatrix = gl.UniformMatrix local glUniformArray = gl.UniformArray local function new(class, shaderParams, shaderName, logEntries) local logEntriesSanitized if type(logEntries) == "number" then logEntriesSanitized = logEntries else logEntriesSanitized = 1 end return setmetatable( { shaderName = shaderName or "Unnamed Shader", shaderParams = shaderParams or {}, logEntries = logEntriesSanitized, logHash = {}, shaderObj = nil, active = false, ignoreActive = false, ignoreUnkUniform = false, uniforms = {}, }, class) end local function IsGeometryShaderSupported() return gl.HasExtension("GL_ARB_geometry_shader4") and (gl.SetShaderParameter ~= nil or gl.SetGeometryShaderParameter ~= nil) end local function IsTesselationShaderSupported() return gl.HasExtension("GL_ARB_tessellation_shader") and (gl.SetTesselationShaderParameter ~= nil) end local function IsDeferredShadingEnabled() return (Spring.GetConfigInt("AllowDeferredMapRendering") == 1) and (Spring.GetConfigInt("AllowDeferredModelRendering") == 1) and (Spring.GetConfigInt("AdvMapShading") == 1) end local function GetAdvShadingActive() local advUnitShading, advMapShading = Spring.HaveAdvShading() if advMapShading == nil then advMapShading = true end --old engine return advUnitShading and advMapShading end local LuaShader = setmetatable({}, { __call = function(self, ...) return new(self, ...) end, }) LuaShader.__index = LuaShader LuaShader.isGeometryShaderSupported = IsGeometryShaderSupported() LuaShader.isTesselationShaderSupported = IsTesselationShaderSupported() LuaShader.isDeferredShadingEnabled = IsDeferredShadingEnabled() LuaShader.GetAdvShadingActive = GetAdvShadingActive -----------------============ Warnings & Error Gandling ============----------------- function LuaShader:OutputLogEntry(text, isError) local message local warnErr = (isError and "error") or "warning" message = string.format("LuaShader: [%s] shader %s(s):\n%s", self.shaderName, warnErr, text) if self.logHash[message] == nil then self.logHash[message] = 0 end if self.logHash[message] <= self.logEntries then local newCnt = self.logHash[message] + 1 self.logHash[message] = newCnt if (newCnt == self.logEntries) then message = message .. string.format("\nSupressing further %s of the same kind", warnErr) end Spring.Echo(message) end end function LuaShader:ShowWarning(text) self:OutputLogEntry(text, false) end function LuaShader:ShowError(text) self:OutputLogEntry(text, true) end -----------------============ Handle Ghetto Include<> ==============----------------- local includeRegexps = { '.-#include <(.-)>.-', '.-#include \"(.-)\".-', '.-#pragma(%s+)include <(.-)>.-', '.-#pragma(%s+)include \"(.-)\".-', } function LuaShader:HandleIncludes(shaderCode, shaderName) local incFiles = {} local t1 = Spring.GetTimer() repeat local incFile local regEx for _, rx in ipairs(includeRegexps) do _, _, incFile = string.find(shaderCode, rx) if incFile then regEx = rx break end end Spring.Echo(shaderName, incFile) if incFile then shaderCode = string.gsub(shaderCode, regEx, '', 1) table.insert(incFiles, incFile) end until (incFile == nil) local t2 = Spring.GetTimer() Spring.Echo(Spring.DiffTimers(t2, t1, true)) local includeText = "" for _, incFile in ipairs(incFiles) do if VFS.FileExists(incFile) then includeText = includeText .. VFS.LoadFile(incFile) .. "\n" else self:ShowError(string.format("Attempt to execute %s with file that does not exist in VFS", incFile)) return false end end if includeText ~= "" then return includeText .. shaderCode else return shaderCode end end -----------------========= End of Handle Ghetto Include<> ==========----------------- -----------------============ General LuaShader methods ============----------------- function LuaShader:Compile() if not gl.CreateShader then self:ShowError("GLSL Shaders are not supported by hardware or drivers") return false end -- LuaShader:HandleIncludes is too slow. Figure out faster way. --[[ for _, shaderType in ipairs({"vertex", "tcs", "tes", "geometry", "fragment"}) do if self.shaderParams[shaderType] then local newShaderCode = LuaShader:HandleIncludes(self.shaderParams[shaderType], self.shaderName) if newShaderCode then self.shaderParams[shaderType] = newShaderCode end end end ]]-- self.shaderObj = gl.CreateShader(self.shaderParams) local shaderObj = self.shaderObj local shLog = gl.GetShaderLog() or "" if not shaderObj then self:ShowError(shLog) return false elseif (shLog ~= "") then self:ShowWarning(shLog) end local uniforms = self.uniforms for idx, info in ipairs(gl.GetActiveUniforms(shaderObj)) do local uniName = string.gsub(info.name, "%[0%]", "") -- change array[0] to array uniforms[uniName] = { location = glGetUniformLocation(shaderObj, uniName), --type = info.type, --size = info.size, values = {}, } --Spring.Echo(uniName, uniforms[uniName].location, uniforms[uniName].type, uniforms[uniName].size) --Spring.Echo(uniName, uniforms[uniName].location) end return true end LuaShader.Initialize = LuaShader.Compile function LuaShader:GetHandle() if self.shaderObj ~= nil then return self.shaderObj else local funcName = (debug and debug.getinfo(1).name) or "UnknownFunction" self:ShowError(string.format("Attempt to use invalid shader object in [%s](). Did you call :Compile() or :Initialize()?", funcName)) end end function LuaShader:Delete() if self.shaderObj ~= nil then gl.DeleteShader(self.shaderObj) else local funcName = (debug and debug.getinfo(1).name) or "UnknownFunction" self:ShowError(string.format("Attempt to use invalid shader object in [%s](). Did you call :Compile() or :Initialize()", funcName)) end end LuaShader.Finalize = LuaShader.Delete function LuaShader:Activate() if self.shaderObj ~= nil then self.active = true return glUseShader(self.shaderObj) else local funcName = (debug and debug.getinfo(1).name) or "UnknownFunction" self:ShowError(string.format("Attempt to use invalid shader object in [%s](). Did you call :Compile() or :Initialize()", funcName)) return false end end function LuaShader:SetActiveStateIgnore(flag) self.ignoreActive = flag end function LuaShader:SetUnknownUniformIgnore(flag) self.ignoreUnkUniform = flag end function LuaShader:ActivateWith(func, ...) if self.shaderObj ~= nil then self.active = true glActiveShader(self.shaderObj, func, ...) self.active = false else local funcName = (debug and debug.getinfo(1).name) or "UnknownFunction" self:ShowError(string.format("Attempt to use invalid shader object in [%s](). Did you call :Compile() or :Initialize()", funcName)) end end function LuaShader:Deactivate() self.active = false glUseShader(0) end -----------------============ End of general LuaShader methods ============----------------- -----------------============ Friend LuaShader functions ============----------------- local function getUniformImpl(self, name) local uniform = self.uniforms[name] if uniform and type(uniform) == "table" then return uniform elseif uniform == nil then --used for indexed elements. nil means not queried for location yet local location = glGetUniformLocation(self.shaderObj, name) if location and location > -1 then self.uniforms[name] = { location = location, values = {}, } return self.uniforms[name] else self.uniforms[name] = false --checked dynamic uniform name and didn't find it end end -- (uniform == false) return nil end local function getUniform(self, name) if not (self.active or self.ignoreActive) then self:ShowError(string.format("Trying to set uniform [%s] on inactive shader object. Did you use :Activate() or :ActivateWith()?", name)) return nil end local uniform = getUniformImpl(self, name) if not (uniform ~= nil or self.ignoreUnkUniform) then self:ShowWarning(string.format("Attempt to set uniform [%s], which does not exist in the compiled shader", name)) return nil end return uniform end local function isUpdateRequired(uniform, tbl) if (#tbl == 1) and (type(tbl[1]) == "string") then --named matrix return true --no need to update cache end local update = false local cachedValues = uniform.values for i, val in ipairs(tbl) do if cachedValues[i] ~= val then cachedValues[i] = val --update cache update = true end end return update end -----------------============ End of friend LuaShader functions ============----------------- -----------------============ LuaShader uniform manipulation functions ============----------------- -- TODO: do it safely with types, len, size check function LuaShader:GetUniformLocation(name) return (getUniform(self, name) or {}).location or -1 end --FLOAT UNIFORMS local function setUniformAlwaysImpl(uniform, ...) glUniform(uniform.location, ...) return true --currently there is no way to check if uniform is set or not :( end function LuaShader:SetUniformAlways(name, ...) local uniform = getUniform(self, name) if not uniform then return false end return setUniformAlwaysImpl(uniform, ...) end local function setUniformImpl(uniform, ...) if isUpdateRequired(uniform, {...}) then return setUniformAlwaysImpl(uniform, ...) end return true end function LuaShader:SetUniform(name, ...) local uniform = getUniform(self, name) if not uniform then return false end return setUniformImpl(uniform, ...) end LuaShader.SetUniformFloat = LuaShader.SetUniform LuaShader.SetUniformFloatAlways = LuaShader.SetUniformAlways --INTEGER UNIFORMS local function setUniformIntAlwaysImpl(uniform, ...) glUniformInt(uniform.location, ...) return true --currently there is no way to check if uniform is set or not :( end function LuaShader:SetUniformIntAlways(name, ...) local uniform = getUniform(self, name) if not uniform then return false end return setUniformIntAlwaysImpl(uniform, ...) end local function setUniformIntImpl(uniform, ...) if isUpdateRequired(uniform, {...}) then return setUniformIntAlwaysImpl(uniform, ...) end return true end function LuaShader:SetUniformInt(name, ...) local uniform = getUniform(self, name) if not uniform then return false end return setUniformIntImpl(uniform, ...) end --FLOAT ARRAY UNIFORMS local function setUniformFloatArrayAlwaysImpl(uniform, tbl) glUniformArray(uniform.location, UNIFORM_TYPE_FLOAT, tbl) return true --currently there is no way to check if uniform is set or not :( end function LuaShader:SetUniformFloatArrayAlways(name, tbl) local uniform = getUniform(self, name) if not uniform then return false end return setUniformFloatArrayAlwaysImpl(uniform, tbl) end local function setUniformFloatArrayImpl(uniform, tbl) if isUpdateRequired(uniform, tbl) then return setUniformFloatArrayAlwaysImpl(uniform, tbl) end return true end function LuaShader:SetUniformFloatArray(name, tbl) local uniform = getUniform(self, name) if not uniform then return false end return setUniformFloatArrayImpl(uniform, tbl) end --INT ARRAY UNIFORMS local function setUniformIntArrayAlwaysImpl(uniform, tbl) glUniformArray(uniform.location, UNIFORM_TYPE_INT, tbl) return true --currently there is no way to check if uniform is set or not :( end function LuaShader:SetUniformIntArrayAlways(name, tbl) local uniform = getUniform(self, name) if not uniform then return false end return setUniformIntArrayAlwaysImpl(uniform, tbl) end local function setUniformIntArrayImpl(uniform, tbl) if isUpdateRequired(uniform, tbl) then return setUniformIntArrayAlwaysImpl(uniform, tbl) end return true end function LuaShader:SetUniformIntArray(name, tbl) local uniform = getUniform(self, name) if not uniform then return false end return setUniformIntArrayImpl(uniform, tbl) end --MATRIX UNIFORMS local function setUniformMatrixAlwaysImpl(uniform, tbl) glUniformMatrix(uniform.location, unpack(tbl)) return true --currently there is no way to check if uniform is set or not :( end function LuaShader:SetUniformMatrixAlways(name, ...) local uniform = getUniform(self, name) if not uniform then return false end return setUniformMatrixAlwaysImpl(uniform, {...}) end local function setUniformMatrixImpl(uniform, tbl) if isUpdateRequired(uniform, tbl) then return setUniformMatrixAlwaysImpl(uniform, tbl) end return true end function LuaShader:SetUniformMatrix(name, ...) local uniform = getUniform(self, name) if not uniform then return false end return setUniformMatrixImpl(uniform, {...}) end -----------------============ End of LuaShader uniform manipulation functions ============----------------- return LuaShader
gpl-2.0