content
stringlengths
5
1.05M
local states = {} states.all = {} states.common = {} -- Common variables for all the states. Stored in the state environments as 'out' states.commonModules = {} -- Common module variables for all the states. Stored in the state environments as 'mods' states.current = nil local env_mt = {} function env_mt.__index(t, k) return rawget(t, k) or _G[k] end function env_mt.__newindex(t, k, v) _G[k] = v end local function initenv() local env = {} -- Add main global variables -- Add common variable tables env.out = states.common env.modules = states.commonModules return setmetatable(env, env_mt) end local function null() end function states.add(mod, tag) local err if tag == nil then tag = mod end mod, err = loadstring(love.filesystem.read(mod)) if err then error(err) else local env = initenv() setfenv(mod, env) mod = mod() mod.env = env states.all[tag] = mod return mod end end function states.load(tag, args) local mod = states.all[tag] assert(mod ~= nil, string.format("state '%s' is not initalized", tag)) if states.current ~= nil then states.unload() end states.current = tag if mod.load ~= nil then mod.load(args) end end function states.unload() local cur = states.getCurrent() if cur.unload() then cur.unload() end states.current = nil end function states.getCurrent() return states.all[states.current] end function states.getFromCurrent(k) return states.getCurrent()[k] or null end function states.cur(k) --Shortcut for states.getCurrent() and states.getFromCurrent() local cur = states.getCurrent() if k == nil then return cur end return cur[k] or null end return states
local name, addon = ... local oUF = addon.oUF or oUF local Config = addon.Config local Functions = CreateFrame('Frame') addon.Functions = Functions ------------ -- Utilities ------------ Functions.CreateStatusBar = function(name, parent, texture, color) local StatusBar = CreateFrame('StatusBar', name or nil, parent or UIParent) StatusBar:SetStatusBarTexture(texture or Config.Textures.StatusBar) StatusBar:GetStatusBarTexture():SetHorizTile(false) if(color) then StatusBar:SetStatusBarColor(unpack(color)) end return StatusBar end Functions.ApplyBackdrop = function(self) if(not self) then return end self:SetBackdrop(Config.Backdrop) self:SetBackdropColor(0, 0, 0, 1) end Functions.FontString = function(parent, layer, type, size, style, justifyH, shadow) local fontString = parent:CreateFontString(nil, layer or 'OVERLAY') fontString:SetFont(type, size or 10, style or nil) fontString:SetJustifyH(justifyH or 'CENTER') if(shadow) then fontString:SetShadowColor(0, 0, 0) fontString:SetShadowOffset(1.25, -1.25) end return fontString end ---------------- -- Power updates ---------------- Functions.PreUpdatePower = function(self, unit) local powerType = select(2, UnitPowerType(unit)) local colors = Config.Colors.Power[powerType] if(colors) then self:SetStatusBarTexture(unpack(colors)) end end Functions.PostUpdatePower = function(self, unit, min, max) if(not UnitIsPlayer(unit)) then self.Value:SetText('') self.Percent:SetText('') else local powerType = select(2, UnitPowerType(unit)) local colors = Config.Colors.Power[powerType] self.Value:SetText(min .. '/' .. max) if(powerType == 'MANA') then self.Percent:SetText(math.floor(min/max * 100) .. '%') else self.Percent:SetText(min) end end end ----------------- -- Health updates ----------------- Functions.PreUpdateHealth = function(self, unit) local class, classFileName = UnitClass(unit) local color = RAID_CLASS_COLORS[classFileName] if(color) then self:SetStatusBarTexture(color.r, color.g, color.b, 1.0) end end Functions.PostUpdateHealth = function(self, unit, min, max) local r, g, b local duration = math.floor(min/max*100) if(max ~= 0) then r, g, b = oUF.ColorGradient(min, max, 1, 0, 0, 1, 1, 0, 1, 1, 1) end if(not UnitIsConnected(unit)) then self.Value:SetText('') self.Percent:SetText('offline') self.Percent:SetTextColor(0.8, 0.8, 0.8) elseif(UnitIsGhost(unit)) then self.Value:SetText('') self.Percent.SetText('ghost') self.Percent:SetTextColor(0.8, 0.8, 0.8) elseif(UnitIsDead(unit)) then self.Value:SetText('') self.Percent:SetText('dead') self.Percent:SetTextColor(0.8, 0.8, 0.8) elseif(unit == 'player') then self.Value:SetText(min .. '/' .. max) self.Percent:SetText(duration .. '%') self.Percent:SetTextColor(r, g, b) elseif(unit == 'target' or unit == 'focus' or self:GetParent():GetName():match('oUF_Party')) then self.Value:SetText(min .. '/' .. max) self.Percent:SetText(duration .. '%') self.Percent:SetTextColor(r, g, b) else self.Value:SetText('') self.Percent:SetText(duration .. '%') end end
local config = require("conf.config") local shell = require("shell") local item_utils = require("util.item_utils") local args, _ = shell.parse(...) local _M = {} local input = config.chestInput.proxy local inputSide = config.chestInput.chestSourceSide local function readData(data) if type(data) == "table" then for k, v in pairs(data) do print(k .. ":" .. tostring(v)) end else print(data) end end function _M.default() local stacks = input.getAllStacks(inputSide) for k, v in pairs(stacks.getAll()) do if v.name then print("slot:" .. k .. " identity ---> " .. item_utils.itemIdentity(v)) end end end function _M.allInfo() local item = input.getStackInSlot(inputSide, 1) if item then readData(item) end end function _M.readFluid() local fluid = input.getFluidInTank(inputSide, 1) if fluid then readData(fluid) end end local functionName; if type(args) == "table" then functionName = args[1] or "default" end if _M[functionName] then _M[functionName]() end return _M
--[[ Modulo temporaneo che sostituisce il modulo squadra: le chiamate al modulo attuale presentano codice non compatibile con questo modulo che è stato reso mobile friendly, pertanto si è reso necessario creare questa pagina temporanea prima di riunire il tutto. I parametri dovrebbero essere gli stessi del modulo squadra, a loro volta gli stessi del template squadra, con gli stessi nomi. Per quanto riguarda i colori invece, possono essere inseriti sia valori esadecimali che colori memorizzati sul wiki: in questo caso basta inserire "parametro=nomecolore variante", es: {{#invoke: party | ... | color=erba dark}} {{#invoke: party | ... | headcolor2=elettro}} --]] local s = {} local mw = require('mw') local w = require('Wikilib') local wdata = require("Wikilib-data") local lib = require('Wikilib-squadra') local txt = require('Wikilib-strings') -- luacheck: no unused local tab = require('Wikilib-tables') -- luacheck: no unused local gbl = require('GamesColorLinks') local css = require('Css') -- Stringa per la trainerclass, non sempre presente local classString = [=[<div style="line-height: 10px" class="text-small">'''[[${classlink}|<span style="color:#000">${class}</span>]]'''</div>]=] --[[ Modulo squadra intero: sostituisce entrambe le altre due funzioni. Per renderlo uguale a tag aggiungere il parametro tag=yes --]] -- Returns true iff the text should be white on the passed color variant local needWhiteText = function(color) local back2name, back2var = lib.getColor(color) return back2var == 'dark' or (back2var == 'normale' and table.search(wdata.whitetext, back2name)) end -- Creates the table of colors common to both single and tag local calcBaseColors = function(p) local colors = lib.gethex{ color = p.color or 'sconosciuto', bordercolor = p.bordercolor or 'sconosciuto', headcolor = p.headcolor or 'sconosciuto' } colors = lib.gethex({ back1 = p.back1 or colors.headcolor, back2 = p.back2 or colors.bordercolor, head1 = p.head1 or colors.color, head2 = p.head2 or p.back1 or colors.headcolor, sprcolor1 = p.sprcolor1 or p.head1 or colors.color, sprcolor2 = p.sprcolor2 or p.back1 or colors.headcolor, }, colors) return colors end -- Create the interpData common to both single and party local calcBaseInterpData = function(p, colors, collapsiblebackground) local collapsiblelighttext -- Can't use and/or syntax because the value may be false if p.expandiblelight then collapsiblelighttext = p.expandiblelight:lower() == 'yes' else collapsiblelighttext = needWhiteText(collapsiblebackground) end local games = mw.text.split(p.game, ' ') local keyGame = table.remove(games, 1) local interpData = { sprite = p.sprite, size = p.size and '|' .. p.size or '', class = p.class and string.interp(classString, {class = p.class, classlink = p.classlink or lib.trainerClass[p.name] or p.class .. ' (classe allenatore)'}) or '', name = p.name or 'Oak', location = p.location or 'Brockolandia', locationname = p.locationname or p.location or 'Brockolandia', game = gbl[keyGame .. 'Lua']{games = games, '000'} or p.game, prize = p.prize or '[[File:PokémonDollar.png|link=Dollari Pokémon]]0', balls = lib.balls(tonumber(p.pokemon or p.pokemon1) or 0), collapsiblelighttext = collapsiblelighttext and 'light-text' or '', mainBackground = css.horizGradLua{colors.back1, colors.back2}, spriteBackground = css.horizGradLua{colors.sprcolor1, colors.sprcolor2}, detailsBackground = css.horizGradLua{colors.head1, colors.head2}, } interpData.ballsBackground = interpData.detailsBackground return interpData end -- Squadra/Single s.single = function(frame) local p = w.trimAll(mw.clone(frame.args)) local colors = calcBaseColors(p) local interpData = calcBaseInterpData(p, colors, p.back2 or p.bordercolor or '') interpData.pkmnBackground = interpData.mainBackground return string.interp([=[{| class="mw-collapsible mw-collapsed ${collapsiblelighttext} text-center pull-left roundy" style="padding: 0.5ex; ${mainBackground}" |- | <div class="flex flex-row flex-nowrap flex-items-center flex-main-center" style="padding: 0 2.5em;"> <div> <div class="roundy-full" style="padding: 0.3ex; ${spriteBackground}">[[File:${sprite}${size}]]</div> <div class="text-small" style="margin-top: 0.5ex; line-height: 10px">Ricompensa:</div> <div>'''${prize}'''</div> </div> <div> <div class="roundy text-center" style="margin-left: 1ex; width: 18em; padding: 0.2ex; ${detailsBackground}"> ${class} <div class="text-big">'''${name}'''</div> <div>'''[[${location}|<span style="color: #000;">${locationname}</span>]]'''</div> <div class="text-small">${game}</div> </div> <div class="roundy pull-center" style="margin-top: 0.5ex; width: 14ex; padding: 0.2ex; line-height: 10px; ${ballsBackground}">${balls}</div> </div> </div> |- | style="padding: 0;" | <div class="roundy flex flex-row flex-nowrap flex-items-center flex-main-space-around" style="${pkmnBackground}">]=], interpData) end s.Single = s.single -- Squadra/Tag s.tag = function(frame) local p = w.trimAll(mw.clone(frame.args)) local colors = calcBaseColors(p) colors = lib.gethex({ spr2color1 = p.spr2color1 or 'sconosciuto', spr2color2 = p.spr2color2 or 'sconosciuto', }, colors ) local interpData = calcBaseInterpData(p, colors, p.back2 or p.bordercolor or '') interpData.class2 = p.class2 and string.interp(classString, {class = p.class2, classlink = p.classlink2 or lib.trainerClass[p.name2] or p.class2 .. ' (classe allenatore)'}) or '' interpData.name2 = p.name2 or 'Oak' interpData.sprite2 = p.sprite2 interpData.size2 = p.size2 and '|' .. p.size2 or '' interpData.balls = lib.balls(tonumber(p.pokemon1) or 0, tonumber(p.pokemon2) or 0) interpData.sprite2Background = css.horizGradLua{colors.spr2color1, colors.spr2color2} interpData.pkmnBackground = css.vertGradLua{colors.sprcolor1, colors.spr2color2} return string.interp([=[{| class="mw-collapsible mw-collapsed ${collapsiblelighttext} text-center pull-left roundy" style="padding: 0.5ex; ${mainBackground}" |- | <div class="flex flex-row flex-nowrap flex-items-center flex-main-center" style="padding: 0 2.5em;"> <div> <div class="roundy-full" style="padding: 0.3ex; ${spriteBackground}">[[File:${sprite}${size}]]</div> <div class="text-small" style="margin-top: 0.5ex; line-height: 10px">Ricompensa:</div> <div>'''${prize}'''</div> </div> <div> <div class="roundy text-center" style="margin-left: 1ex; width: 18em; padding: 0.2ex; ${detailsBackground}"><div class="flex flex-row flex-nowrap flex-items-center flex-main-center"> <div> ${class} <div class="text-big">'''${name}'''</div> </div> <div>''e''</div> <div> ${class2}<div class="big-text">'''${name2}'''</div> </div> </div> <div>'''[[${location}|<span style="color: #000;">${locationname}</span>]]'''</div> <div class="text-small">${game}</div> </div> <div class="roundy pull-center" style="margin-top: 0.5ex; width: 14ex; padding: 0.2ex; ${ballsBackground} line-height: 10px">${balls}</div> </div> <div class="flex-items-self-start roundy-full" style="margin-left: 1ex; padding: 0.3ex; ${sprite2Background}">[[File:${sprite2}]]</div> </div> |- | <div class="roundy" style="padding: 0.5ex; ${pkmnBackground}"> <div class="flex flex-row flex-nowrap flex-items-center flex-main-space-around">]=], interpData) end s.Tag = s.tag -- Party/Div s.div = function(frame) return string.interp([=[</div> <div class="flex flex-row flex-nowrap flex-items-center flex-main-space-around" style="margin-top: 0.5ex;">]=]) end s.Div = s.div --[[ Squadra/Footer: data la sua semplicità, è meglio non usarlo: il traduttore di macro, per esempio, non lo fa --]] s.footer = function(frame) return '</div>\n|}<br><br clear="left">' end s.Footer = s.footer return s
local sensorInfo = { name = "isInDanger", desc = "Returns whether unit is in danger", author = "Petrroll", date = "2018-07-29", license = "notAlicense", } local EVAL_PERIOD_DEFAULT = -1 -- acutal, no caching function getInfo() return { period = EVAL_PERIOD_DEFAULT } end local retUnitPosition = Sensors.retUnitPosition local retAreaDPSRatio = Sensors.retAreaDPSRatio local SpringGetProjectilesInRectangle = Spring.GetProjectilesInRectangle -- @description returns whether unit is in danger return function(uid, radius, treshold) local unitLoc = retUnitPosition(uid) if unitLoc == nil then return nil end local DPSRatio = Sensors.retAreaDPSRatio(unitLoc, radius) return DPSRatio < treshold end
-- TODO: clean this up! module(..., package.seeall) require "source/gridNeighbors" require "source/gui/guiUtilities" require "source/utilities/vector" -- import local flower = flower -- local variables local layer = nil local view = nil -- MapEditor singleton MapEditor = {} MapEditor.texture = "hex-tiles.png" MapEditor.width = 10 MapEditor.height = 35 MapEditor.tileWidth = 128 MapEditor.tileHeight = 111 MapEditor.radius = 24 MapEditor.saveFile = "assets/grid.sav" MapEditor.currentAlgorithm = 1 MapEditor.currentColor = 1 MapEditor.algorithms = {} function MapEditor.buildGrid(params) params = params or {} MapEditor.texture = params.texture or MapEditor.texture MapEditor.width = params.width or MapEditor.width MapEditor.height = params.height or MapEditor.height MapEditor.tileWidth = params.tileWidth or MapEditor.tileWidth MapEditor.tileHeight = params.tileHeight or MapEditor.tileHeight MapEditor.radius = params.radius or MapEditor.radius MapEditor.grid = flower.MapImage(MapEditor.texture, MapEditor.width, MapEditor.height, MapEditor.tileWidth, MapEditor.tileHeight, MapEditor.radius) MapEditor.grid:setShape(MOAIGridSpace.HEX_SHAPE) MapEditor.grid:setLayer(layer) end -- This function is used by the GuiUtilities file to generate -- the status field in the UI function MapEditor.generateStatus() return "Current Algorithm: " .. MapEditor.algorithms[MapEditor.currentAlgorithm].name .. "\nCurrent Color: " .. MapEditor.currentColor end -- Load/Save grid to file function MapEditor.serializeGrid(file, streamIn) file = file or MapEditor.saveFile streamIn = streamIn or false local fileStream = MOAIFileStream.new() local success = fileStream:open(file, streamIn and MOAIFileStream.READ or MOAIFileStream.READ_WRITE_NEW) if success then if streamIn then MapEditor.grid.grid:streamTilesIn(fileStream) else MapEditor.grid.grid:streamTilesOut(fileStream) end fileStream:close() end end function MapEditor.onTouchDown(pos) MapEditor.algorithms[MapEditor.currentAlgorithm].func(pos) end -- TODO: move these painting algorithms into another file function MapEditor._algorithmRippleOut(pos) local function ValidTile(pos) return pos[1] >= 1 and pos[1] <= MapEditor.width and pos[2] >= 1 and pos[2] <= MapEditor.height end --[[if not ValidTile(pos) then return end]] local visited = {} local list = {} table.insert(list, {position = pos, depth = 1}) local counter = 1 while #list > 0 and counter < 20 do local currentNode = list[1] table.remove(list, 1) flower.Executors.callLaterTime(currentNode.depth / 20, MapEditor._algorithmFillSingleTile, currentNode.position) local directions = getHexNeighbors(currentNode.position) for i, dir in ipairs(directions) do local newPos = currentNode.position + dir local key = newPos[1] + newPos[2] * (MapEditor.width + 1) if ValidTile(newPos) and not visited[key] then visited[key] = true table.insert(list, {position = newPos, depth = currentNode.depth + 1}) end end counter = counter + 1 end end function MapEditor._algorithmFillSingleTile(pos, tile) tile = tile or MapEditor.currentColor MapEditor.grid:setTile(pos[1], pos[2], tile) end table.insert(MapEditor.algorithms, {name = "Tile", func = MapEditor._algorithmFillSingleTile}) table.insert(MapEditor.algorithms, {name = "Fill", func = MapEditor._algorithmRippleOut}) function MapEditor.setColor(colorNum) MapEditor.currentColor = colorNum end function onCreate(e) view = e.data.view layer = flower.Layer() layer:setTouchEnabled(true) scene:addChild(layer) MapEditor.buildGrid() -- Build GUI from parent view buildUI("MapEditor", view, MapEditor, MapEditor.serializeGrid, nil, MapEditor.setColor) MapEditor.serializeGrid(saveFile, true) -- Make the grid touchable -- TODO: move this code into the map editor addTouchEventListeners(MapEditor.grid) flower.Runtime:addEventListener("resize", onResize) end function updateLayout() _resizeComponents(view) end function onResize(e) updateLayout() end function onStart(e) end function onStop(e) end function addTouchEventListeners(item) item:addEventListener("touchDown", item_onTouchDown) item:addEventListener("touchUp", item_onTouchUp) item:addEventListener("touchMove", item_onTouchMove) item:addEventListener("touchCancel", item_onTouchCancel) end function item_onTouchDown(e) local prop = e.prop if prop == nil or prop.touchDown and prop.touchIdx ~= e.idx then return end local x = e.wx local y = e.wy x, y = layer:wndToWorld(x, y) x, y = prop:worldToModel(x, y) -- TODO: move this into the map editor local xCoord, yCoord = MapEditor.grid.grid:locToCoord(x, y) MapEditor.onTouchDown(vector{xCoord, yCoord}) prop.touchDown = true prop.touchIdx = e.idx prop.touchLast = vector{e.wx, e.wy} end function item_onTouchUp(e) local prop = e.prop if prop == nil or prop.touchDown and prop.touchIdx ~= e.idx then return end prop.touchDown = false prop.touchIdx = nil prop.touchLast = nil end function item_onTouchMove(e) local prop = e.prop if prop == nil or not prop.touchDown then return end local moveVec = {e.wx, e.wy} - prop.touchLast prop:addLoc(moveVec[1], moveVec[2], 0) prop.touchLast = vector{e.wx, e.wy} end function item_onTouchCancel(e) local prop = e.prop if prop == nil or not prop.touchDown then return end prop.touchDown = false prop.touchIdx = nil prop.touchLast = nil end
local trg = CreateTrigger() ModeInstructionFlush = function() DestroyTrigger(trg) trg = nil end local modes local modeword = {} TriggerRegisterPlayerChatEvent(trg, FirstPlayer, "-", false) TriggerAddCondition(trg, Condition( function() local w = GetEventPlayerChatString() w = w:gsub("[^%w%.]", ""):upper() while #w > 1 do local s = w:sub(1, 2) if modes[s] and not table.has(GameMode, s) then table.insert(GameMode, s) table.insert(modeword, ("|cffffcc00%s|r(|cffff1111%s|r)"):format(modes[s].name, s)) w = w:sub(3) w = modes[s].code(w) or w else w = w:sub(2) end end if #modeword > 0 then print(table.concat(modeword, "/")) RefreshGamemode() end end )) modes = { SP = { name = "洗牌模式", code = function() local f1 = {} local f2 = {} --将所有玩家加入玩家组 for i = 1, 10 do if IsPlayer(P[i]) or IsComputer(P[i]) then table.insert(f1, P[i]) else table.insert(f2, P[i]) end end --拉一个随机玩家出来 local getRandom = function() local f local w if #f1 > 0 then f = f1 else f = f2 end local i = GetRandomInt(1, #f) local p = f[i] table.remove(f, i) return p end --进行重组 for i = 1, 5 do if GetRandomInt(1, 2) == 1 then PA[i], PB[i] = getRandom(), getRandom() else PB[i], PA[i] = getRandom(), getRandom() end P[i] = PA[i] P[i+5] = PB[i] end --刷新 RefreshAlliance() CreateBoard() toEvent("洗牌后", {}) end }, AR = { name = "全体随机", code = function() for i = 1, 10 do BanPlayerHeroType(P[i]) end StartGameIn(90) Wait(2, function() ModeInstructionFlush() local ps = {} for i = 1, 10 do if IsPlayer(P[i]) then table.insert(ps, P[i]) end end Loop(0.5, function() if #ps == 0 then EndLoop() else SelectRandomHero(ps[1]) table.remove(ps, 1) end end ) end ) end, }, MH = { name = "复选模式", code = function() end }, RC = { name = "急速冷却", code = function() for _, this in pairs(SkillTable) do if type(this) == "table" then this.cool = 0 if this._cool then this._cool = 0 end end end end }, UM = { name = "无限法力", code = function() for _, this in pairs(SkillTable) do if type(this) == "table" then this.mana = 0 if this._mana then this._mana = 0 end end end end }, MD = { name = "启用主机MOD", code = function() local texts = {} if SELFP == FirstPlayer then local mods = {} for i = 1, 100 do local suc, mod = pcall(old.require, "MoeUshio\\PI2\\Mod" .. i .. ".lua") if suc then table.insert(mods, mod) end end for i, mod in ipairs(mods) do table.insert(texts, mod.name) table.insert(texts, mod.ver) table.insert(texts, mod.author) table.insert(texts, mod.tip) table.insert(texts, mod.script) end end local chars = table.concat(texts, "><") or "" local text = [[ Mod大小 |cffffcc00% 6s|r 字节 压缩后大小 |cffffcc00% 6s|r 字节 经过时间 |cffffcc00% 6.2f|r 秒 已传输 |cffffcc00% 6s|r 字节 传输进度 |cffffcc00% 6.2f|r%% 传输速度 |cffffcc00% 5.2f|r 字节/秒 文本传输器版本 |cffffcc00%s|r 文本压缩器版本 |cffffcc00%s|r %s ]] upload.start{ player = FirstPlayer, text = chars, ready = function(data) if data.len == 0 then print("没有检测到任何有效的Mod!") return true end local id = |A1AG| UnitAddAbility(gg_unit_h000_0024, id) UnitAddAbility(gg_unit_h000_0025, id) print("提示:你可以在泉水处查看Mod传输进度") end, past = function(data) local ab = japi.EXGetUnitAbility(gg_unit_h000_0024, |A1AG|) local text = text:format( data.len, data.size, data.pasttime, data.pastbyte, math.min(100, data.pastbyte / math.max(1, data.size) * 100), data.speed, upload.ver, upload.zipver, "" ) japi.EXSetAbilityDataString(ab, 1, 218, text) RefreshTips(gg_unit_h000_0024) end, finish = function(data) local texts = string.split(data.text, "><") local names = {} local vers = {} local authors = {} local tips = {} local scripts = {} for i, text in ipairs(texts) do if i % 5 == 1 then table.insert(names, text) elseif i % 5 == 2 then table.insert(vers, text) elseif i % 5 == 3 then table.insert(authors, text) elseif i % 5 == 4 then table.insert(tips, text) else table.insert(scripts, text) end end local modtips = {} local modtip = [[ Mod名称:|cffffcc00%s|r[%s] Mod作者:|cffffcc00%s|r %s ]] for i = 1, #names do print(("已加载Mod:|cffffcc00%s|r[%s]"):format(names[i], vers[i])) loadstring(scripts[i])() table.insert(modtips, modtip:format(names[i], vers[i], authors[i], tips[i])) end local ab = japi.EXGetUnitAbility(gg_unit_h000_0024, |A1AG|) local text = text:format( data.len, data.size, data.pasttime, data.pastbyte, math.min(100, data.pastbyte / math.max(1, data.size) * 100), data.speed, upload.ver, upload.zipver, "====================================\n\n" .. table.concat(modtips, "\n\n") ) japi.EXSetAbilityDataString(ab, 1, 218, text) RefreshTips(gg_unit_h000_0024) end } end } }
function getVehiclesOwnedByCharacter(thePlayer) local dbid = tonumber(getElementData(thePlayer, "dbid")) local carids = { } local numcars = 0 local indexcars = 1 for key, value in ipairs(exports.mrp_pool:getPoolElementsByType("vehicle")) do local owner = tonumber(getElementData(value, "owner")) if (owner) and (owner==dbid) then local id = getElementData(value, "dbid") carids[numcars+1] = id numcars = numcars + 1 end end return numcars, carids end function canPlayerBuyVehicle(thePlayer) if (isElement(thePlayer)) then if getElementData(thePlayer, "loggedin") == 1 then local maxvehicles = getElementData(thePlayer, "maxvehicles") or 0 local novehicles, veharray = getVehiclesOwnedByCharacter(thePlayer) if (novehicles < maxvehicles) then return true end return false, "Too much vehicles" end return false, "Player not logged in" end return false, "Element not found" end
local combat = Combat() combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_ENERGYDAMAGE) combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_ENERGYHIT) local condition = Condition(CONDITION_ENERGY) condition:setParameter(CONDITION_PARAM_DELAYED, true) condition:addDamage(20, 10000, -25) combat:setCondition(condition) function onCastSpell(creature, variant) return combat:execute(creature, variant) end
--[[ this looks a lot like GRHDBehavior it does the same thing -- adds 'getADMArgs' and 'getADMVarCode' for the eqn to use make it a behavior for adding ADM args to eqns --]] local class = require 'ext.class' local template = require 'template' return function(parent) local templateClass = class(parent) -- eqn/grhd.cl needs this implemented for deducing alpha, beta, gamma function templateClass:getADMArgs() return '' end --[[ args: alpha = (optional) alpha var name beta = (optional) beta var name gamma = (optional) gamma var name suffix = (optional) suffix for default variable names index = (optional) index in grid associated with metric. default 'index' I made args volatile because I was lazy --]] function templateClass:getADMVarCode(args) args = args or {} args.suffix = args.suffix or '' args.alpha = args.alpha or ('alpha'..args.suffix) args.beta = args.beta or ('beta'..args.suffix) args.gamma = args.gamma or ('gamma'..args.suffix) return template([[ real <?=args.alpha?> = 1; real3 <?=args.beta?> = real3_zero; sym3 <?=args.gamma?> = sym3_ident; ]], {args=args}) end return templateClass end
local path = "hall/message_pin.png" local message_pin_map = { ["msg_item_detail_bg.png"] = { file=path, x=2,y=2, width=129,height=129, rotated=false }, ["sys_msg.png"] = { file=path, x=2,y=133, width=200,height=52, rotated=false }, ["msg_attachment.png"] = { file=path, x=133,y=2, width=123,height=73, rotated=false }, ["read_icon.png"] = { file=path, x=258,y=2, width=123,height=73, rotated=false }, ["msg_havegot.png"] = { file=path, x=383,y=2, width=90,height=50, rotated=false }, } return message_pin_map
local ALIASES = { static_variable = "static_variables", static_getter = "static_getters", static_setter = "static_setters", static_method = "static_methods", variable = "variables", getter = "getters", setter = "setters", method = "methods", } local METHOD_DUPLICATES = {"static_variables", "static_getters", "static_setters", "static_methods", "variables", "getters", "setters", "methods"} local STATIC_DUPLICATES = {"static_methods", "variables", "getters", "setters", "methods"} local INSTANCE_DUPLICATES = {"static_variables", "static_getters", "static_setters", "static_methods", "methods"} local NIL, environmentFrom, mainClassEnvironment, mainEnvironment = nil, nil, nil, nil -- set through init function local propertyFrom, metatables, _checkers, checkers = setmetatable({}, {__mode = "k"}), {}, {}, {} --===== UTILS =====-- local function invalidInterfaceProperty(property) return false, "cannot define property '"..property.."' in interface" end local function typeError(expectedType, actualType, additionalInfo) local exception = "expected <"..expectedType..">, got: <"..actualType..">" if additionalInfo then exception = exception.." - "..additionalInfo end return exception end local function checkArray(array, expectedTypeChecker) if type(array) ~= "table" then return false, typeError("table", type(array)) end local output = {} for index, value in ipairs(array) do local ok, _value = expectedTypeChecker(value) if ok then output[index] = _value else return false, "invalid value at index "..tostring(index).." - ".._value end end return true, output end local function checkTable(table, expectedKeyTypeChecker, expectedValueTypeChecker) if type(table) ~= "table" then return false, typeError("table", type(table)) end local output = {} for key, value in pairs(table) do local ok, _key = expectedKeyTypeChecker(key) if not ok then return false, "invalid key "..tostring(key).." - ".._key end local ok, _value = expectedValueTypeChecker(value) if not ok then return false, "invalid value at key "..tostring(key).." - ".._value end output[_key] = _value end return true, output end local function splitFullName(full_name) return full_name:match("(.*)%.") or "", full_name:match("([^%.]*)$") end local propertyProperties = { imports = { metatableType = "array", valueType = "imports_string", duplicates = {}, }, static_methods = { metatableType = "stringIndexedTable", valueType = "function", duplicates = METHOD_DUPLICATES, }, methods = { metatableType = "stringIndexedTable", valueType = "function", duplicates = METHOD_DUPLICATES, }, implements = { metatableType = "array", valueType = "full_interface_string", duplicates = {}, }, static_variables = { metatableType = "stringIndexedTable", valueType = "any", duplicates = STATIC_DUPLICATES, }, static_getters = { metatableType = "stringIndexedTable", valueType = "function", duplicates = STATIC_DUPLICATES, }, static_setters = { metatableType = "stringIndexedTable", valueType = "function", duplicates = STATIC_DUPLICATES, }, variables = { metatableType = "stringIndexedTable", valueType = "any", duplicates = INSTANCE_DUPLICATES, }, getters = { metatableType = "stringIndexedTable", valueType = "function", duplicates = INSTANCE_DUPLICATES, }, setters = { metatableType = "stringIndexedTable", valueType = "function", duplicates = INSTANCE_DUPLICATES, }, } local function newEnvironment() local environment = { -- class + interface package = "", imports = {}, extends = false, static_methods = {}, methods = {}, -- class class = false, implements = {}, static_variables = {}, static_getters = {}, static_setters = {}, variables = {}, getters = {}, setters = {}, constructor = false, -- interface interface = false, } -- set up tracking table local tracking = {} for propertyName in pairs(environment) do tracking[propertyName] = false end -- set up property proxies local proxies = {} for propertyName, property in pairs(environment) do local propProps = propertyProperties[propertyName] if propProps then local proxy = setmetatable({}, metatables[propProps.metatableType]) local propertyInfo = { property = property, propertyName = propertyName, valueType = propProps.valueType, duplicates = propProps.duplicates, } environmentFrom[proxy], propertyFrom[proxy] = environment, propertyInfo proxies[propertyName] = proxy end end environment.tracking = tracking environment.proxies = proxies return environment end local function checkPropertyArray(value, arrayType, duplicates, propertyName, environment) -- check is correct array type local ok, _value = _checkers[arrayType](value) if not ok then return false, _value end -- check for duplicates in other properties for _, object in ipairs(_value) do for _, objectType in ipairs(duplicates) do for _, otherObject in ipairs(environment[objectType]) do if object == otherObject then return false, "cannot set '"..object.."' in '"..propertyName.."', it is already defined in "..objectType end end end end -- copy into environment property local property = environment[propertyName] for objectIndex, objectValue in ipairs(_value) do property[objectIndex] = objectValue end return true, property end local function checkPropertyTable(value, tableType, duplicates, propertyName, environment) -- check is correct table type local ok, _value = _checkers[tableType](value) if not ok then return false, _value end -- check for duplicates in other properties for objectKey in pairs(_value) do for _, objectType in ipairs(duplicates) do if environment[objectType][objectKey] then return false, "cannot set '"..objectKey.."' for '"..propertyName.."', it is already defined in "..objectType end end end -- copy into environment property local property = environment[propertyName] for objectKey, objectValue in pairs(_value) do property[objectKey] = objectValue end return true, property end --===== METATABLES =====-- metatables.environment = { __index = function(proxy, alias) local key = ALIASES[alias] or alias return environmentFrom[proxy].proxies[key] or environmentFrom[proxy][key] or mainClassEnvironment[key] or mainEnvironment[key] end, __newindex = function(proxy, alias, value) local environment = environmentFrom[proxy] local key = ALIASES[alias] or alias if environment[key] ~= nil then local tracking = environment.tracking if tracking then -- check if property has already been set if tracking[key] == true then local err = "class property '"..alias.."' has already been set" if key ~= alias then err = err.." through property '"..key.."'" end return error(err) end -- check if property value is valid local checker = checkers[key] local ok, _value = checker(value, environment, tracking) if not ok then return error("error setting property '"..alias.."': ".._value) end -- set property value in environment and add to tracked properties environment[key], tracking[key] = _value, true return end return error("attempt to set class property '"..tostring(alias).."' after class loading has completed") elseif alias == "_ENV" then environment._ENV = value return end return error("attempt to set non-local variable '"..tostring(alias).."'") end, } metatables.array = { __index = function(proxy, index) return propertyFrom[proxy].property[index] end, __newindex = function(proxy, index, value) local environment = environmentFrom[proxy] local tracking = environment.tracking if tracking then local propertyInfo = propertyFrom[proxy] local property = propertyInfo.property -- check index is valid type local ok, err = _checkers.index(index) if not ok then return false, err end -- check index is valid for property if index ~= #property + 1 then return error("expected index '"..tostring(#property + 1).."', got '"..tostring(index).."'") end -- check value is valid type local ok, err = _checkers[propertyInfo.valueType](value) if not ok then return false, err end -- check not already defined in property for _index, _value in ipairs(property) do if value == _value then return error("property value '"..value.."' is already defined at index '"..tostring(_index).."'") end end -- check not already defined in duplicates for _, objectType in ipairs(propertyInfo.duplicates) do for _, otherObject in ipairs(environment[objectType]) do if _value == otherObject then return error("cannot set '".._value.."' in '"..propertyInfo.propertyName.."', it is already defined in "..objectType) end end end -- add value to environment property table.insert(property, value) -- mark tracking as true tracking[propertyInfo.propertyName] = true return end return error("attempt to set class property '"..tostring("TEST").."' after class loading has completed") end, } metatables.stringIndexedTable = { __index = function(proxy, key) local value = propertyFrom[proxy].property[key] return (value == NIL and nil) or value end, __newindex = function(proxy, key, value) local environment = environmentFrom[proxy] local tracking = environment.tracking if tracking then local propertyInfo = propertyFrom[proxy] local property = propertyInfo.property -- check key is valid type local ok, err = _checkers.string(key) if not ok then return false, err end -- check value is valid type local ok, err = _checkers[propertyInfo.valueType](value) if not ok then return false, err end -- check not already defined in property for _key in pairs(property) do if key == _key then return error("property key '"..key.."' for '"..propertyInfo.propertyName.."' has already been defined") end end -- check not already defined in duplicates for _, objectType in ipairs(propertyInfo.duplicates) do for _key in pairs(environment[objectType]) do if _key == key then return error("cannot set '"..key.."' in '"..propertyInfo.propertyName.."', it is already defined in "..objectType) end end end -- add value to environment property if value == nil then value = NIL end property[key] = value -- mark tracking as true tracking[propertyInfo.propertyName] = true return end return error("attempt to set class property '"..tostring("TEST").."' after class loading has completed") end, } --===== INTERNAL CHECKERS =====-- _checkers.any = function(value) return true, value end _checkers.index = function(value) if type(value) ~= "number" then return false, typeError("number", type(value)) end if value < 1 or math.floor(value) ~= value then return false, typeError("non-negative integer", type(value), "got value "..tostring(value)) end return true, value end _checkers.string = function(value) if type(value) ~= "string" then return false, typeError("string", type(value)) end return true, value end _checkers.package_string = function(value) if type(value) ~= "string" then return false, typeError("string", type(value)) end local length = value:len() if length == 0 then return true, value end local sub_package_string, seek = nil, 0 while seek <= length do sub_package_string, seek = value:match("([^.]*).-()", seek + 1) local ok, err = _checkers.sub_package_string(sub_package_string) if not ok then return false, typeError("string", type(value), tostring(value).." - "..err) end end return true, value end _checkers.sub_package_string = function(value) if type(value) ~= "string" then return false, typeError("string", type(value)) end if value:len() == 0 then return false, "zero length sub_package_string not allowed" end if value:match("[^%l%d_]") then return false, "only lowercase alphanumeric characters + underscores allowed in sub_package_string" end return true, value end _checkers.imports_array = function(value) return checkArray(value, _checkers.imports_string) end _checkers.string_array = function(value) return checkArray(value, _checkers.string) end _checkers.imports_string = function(value) if type(value) ~= "string" then return false, typeError("string", type(value)) end local package_string, name = splitFullName(value) local ok, err = _checkers.package_string(package_string) if not ok then return false, typeError("import_package_string", type(value), tostring(value).." - "..err) end if not (_checkers.short_class_string(name) or _checkers.short_interface_string(name) or name == "*") then local err = "expected class_name / interface_name / wildcard at end of imports_string" return false, typeError("string", type(value), tostring(value).." - "..err) end return true, value end _checkers.short_class_string = function(value) if type(value) ~= "string" then return false, typeError("string", type(value)) end if value:len() == 0 then return false, typeError("class_name", type(value), tostring(value).." - zero length class_name not allowed") end if value:find("[^%w_]") then return false, typeError("class_name", type(value), tostring(value).." - class_name must only contain alphanumeric characters + underscores") end if value:find("%u") ~= 1 then return false, typeError("class_name", type(value), tostring(value).." - class_name must start with capital letter") end if _checkers.short_interface_string(value) then return false, typeError("class_name", type(value), tostring(value).." - class_name cannot have the same format as interface_name") end return true, value end _checkers.full_class_string = function(value) if type(value) ~= "string" then return false, typeError("full_class_name", type(value), tostring(value)) end local package_string, class_name = splitFullName(value) local ok, err = _checkers.package_string(package_string) if not ok then return false, typeError("full_class_name", type(value), tostring(value).." - "..err) end local ok, err = _checkers.short_class_string(class_name) if not ok then return false, typeError("full_class_name", type(value), tostring(value).." - "..err) end return true, value end _checkers.short_interface_string = function(value) if type(value) ~= "string" then return false, typeError("interface_name", type(value), tostring(value)) end if value:len() < 1 then return false, typeError("interface_name", type(value), tostring(value).." - interface_name too short") end if value:find("[^%w_]") then return false, typeError("interface_name", type(value), tostring(value).." - interface_name must only contain alphanumeric characters + underscores") end if value:find("I") ~= 1 then return false, typeError("interface_name", type(value), tostring(value).." - interface_name must start with capital letter 'I'") end if value:find("%u", 2) ~= 2 then return false, typeError("interface_name", type(value), tostring(value).." - interface_name must start with capital letter 'I' then a capital letter") end return true, value end _checkers.full_interface_string = function(value) if type(value) ~= "string" then return false, typeError("full_interface_name", type(value), tostring(value)) end local package_string, interface_name = splitFullName(value) local ok, err = _checkers.package_string(package_string) if not ok then return false, err end local ok, err = _checkers.short_interface_string(interface_name) if not ok then return false, err end return true, value end _checkers.string_to_function_table = function(value) return checkTable(value, _checkers.string, _checkers["function"]) end _checkers.implements_array = function(value) return checkArray(value, _checkers.full_interface_string) end _checkers.string_to_any_table = function(value) return checkTable(value, _checkers.string, _checkers.any) end _checkers["function"] = function(value) if type(value) ~= "function" then return false, typeError("function", type(value), tostring(value)) end return true, value end --===== MAIN CHECKERS =====-- -- class + interface checkers.package = function(value, environment, tracking) return _checkers.package_string(value) end checkers.imports = function(value, environment, tracking) local valueType = type(value) if valueType == "table" then return checkPropertyArray(value, "imports_array", {}, "imports", environment) elseif valueType == "string" then local ok, _value = _checkers.imports_string(value) if not ok then return false, typeError("imports_string", type(value), _value) end table.insert(environment.imports, _value) return true, environment.imports end return false, typeError("imports_string_array or imports_string", valueType) end checkers.extends = function(value, environment, tracking) if tracking.class then return _checkers.full_class_string(value) elseif tracking.interface then return _checkers.full_interface_string(value) else return false, "must define class or interface first" end end checkers.static_methods = function(value, environment, tracking) if tracking.class then return checkPropertyTable(value, "string_to_function_table", METHOD_DUPLICATES, "static_methods", environment) elseif tracking.interface then return checkPropertyArray(value, "string_array", {"methods"}, "static_methods", environment) end return false, "must define class or interface first" end checkers.methods = function(value, environment, tracking) if tracking.class then return checkPropertyTable(value, "string_to_function_table", METHOD_DUPLICATES, "methods", environment) elseif tracking.interface then return checkPropertyArray(value, "string_array", {"static_methods"}, "methods", environment) end return false, "must define class or interface first" end -- class only checkers.class = function(value, environment, tracking) if tracking.interface then return false, "cannot define class and interface in same file" end local ok, _value = _checkers.short_class_string(value) if not ok then return false, typeError("short_class_string", type(value), _value) end return true, _value end checkers.implements = function(value, environment, tracking) if tracking.interface then return invalidInterfaceProperty("implements") end if not tracking.class then return false, "must define class first" end local valueType = type(value) if valueType == "table" then return checkPropertyArray(value, "implements_array", {}, "implements", environment) elseif valueType == "string" then local ok, _value = _checkers.full_interface_string(value) if not ok then return false, _value end table.insert(environment.implements, _value) return true, environment.implements end return false, typeError("imports_string_array or imports_string", valueType) end checkers.static_variables = function(value, environment, tracking) if tracking.interface then return invalidInterfaceProperty("static_variables") end if not tracking.class then return false, "must define class first" end return checkPropertyTable(value, "string_to_any_table", STATIC_DUPLICATES, "static_variables", environment) end checkers.static_getters = function(value, environment, tracking) if tracking.interface then return invalidInterfaceProperty("static_getters") end if not tracking.class then return false, "must define class first" end return checkPropertyTable(value, "string_to_function_table", STATIC_DUPLICATES, "static_getters", environment) end checkers.static_setters = function(value, environment, tracking) if tracking.interface then return invalidInterfaceProperty("static_setters") end if not tracking.class then return false, "must define class first" end return checkPropertyTable(value, "string_to_function_table", STATIC_DUPLICATES, "static_setters", environment) end checkers.variables = function(value, environment, tracking) if tracking.interface then return invalidInterfaceProperty("variables") end if not tracking.class then return false, "must define class first" end return checkPropertyTable(value, "string_to_any_table", INSTANCE_DUPLICATES, "variables", environment) end checkers.getters = function(value, environment, tracking) if tracking.interface then return invalidInterfaceProperty("getters") end if not tracking.class then return false, "must define class first" end return checkPropertyTable(value, "string_to_function_table", INSTANCE_DUPLICATES, "getters", environment) end checkers.setters = function(value, environment, tracking) if tracking.interface then return invalidInterfaceProperty("setters") end if not tracking.class then return false, "must define class first" end return checkPropertyTable(value, "string_to_function_table", INSTANCE_DUPLICATES, "setters", environment) end checkers.constructor = function(value, environment, tracking) if tracking.interface then return invalidInterfaceProperty("constructor") end if not tracking.class then return false, "must define class first" end if type(value) ~= "function" then return false, typeError("function", type(value)) end return true, value end -- interface only checkers.interface = function(value, environment, tracking) if tracking.class then return false, "cannot define class and interface in same file" end local ok, _value = _checkers.short_interface_string(value) if not ok then return false, typeError("short_interface_string", type(value), _value) end -- update static_methods local staticMethodsProxy = environment.proxies.static_methods setmetatable(staticMethodsProxy, metatables.array) propertyFrom[staticMethodsProxy].valueType = "string" propertyFrom[staticMethodsProxy].duplicates = {"methods"} -- update methods local methodsProxy = environment.proxies.methods setmetatable(methodsProxy, metatables.array) propertyFrom[methodsProxy].valueType = "string" propertyFrom[methodsProxy].duplicates = {"static_methods"} return true, _value end --===== EXTERNAL FUNCTIONS =====-- local function init(_NIL, _environmentFrom, _mainClassEnvironment, _mainEnvironment) NIL, environmentFrom, mainClassEnvironment, mainEnvironment = _NIL, _environmentFrom, _mainClassEnvironment, _mainEnvironment end local function new() local environment, proxy = newEnvironment(), setmetatable({NIL = NIL}, metatables.environment) environmentFrom[proxy] = environment return environment, proxy end local function check(environment, proxy) -- check for class if environment.class ~= false then if environment.extends == false then environment.extends = nil end if environment.constructor == false then local constructor if environment.extends then constructor = function(self, ...) self.super(...) end else constructor = function(self, ...) end end setfenv(constructor, proxy) environment.constructor = constructor end -- create live class data local class = { package = environment.package, imports = environment.imports, name = environment.class, extends = environment.extends, implements = environment.implements, static = { variables = environment.static_variables, getters = environment.static_getters, setters = environment.static_setters, methods = environment.static_methods, }, instance = { variables = environment.variables, getters = environment.getters, setters = environment.setters, methods = environment.methods, constructor = environment.constructor, }, extendedBy = {}, } class.fullName = environment.class if environment.package ~= "" then class.fullName = environment.package.."."..class.fullName end return class, "class" elseif environment.interface ~= false then if environment.extends == false then environment.extends = nil end -- create live interface data local interface = { package = environment.package, imports = environment.imports, name = environment.interface, extends = environment.extends, static_methods = environment.static_methods, methods = environment.methods, extendedBy = {}, } interface.fullName = environment.interface if environment.package ~= "" then interface.fullName = environment.package.."."..interface.fullName end return interface, "interface" end return false, "no class or interface defined" end local function clearTracking(environment) environment.tracking = nil end return { init = init, new = new, check = check, clearTracking = clearTracking, }
if Server then function AlienTeamInfo:UpdateAllLocationsSlotData() local statusEnts = GetEntitiesMatchAnyTypesForTeam( AlienTeamInfo.kLocationEntityTypes, self:GetTeamNumber() ) for _, entity in ipairs(statusEnts) do if entity:GetIsAlive() then if entity:isa("Hive") then self:UpdateLocationSlotHiveData( entity.locationId, entity:GetTechId(), entity:GetBuiltFraction(), entity:GetHealthScalar(), entity:GetMaxHealth(), entity:GetIsInCombat() ) elseif entity:isa("Egg") then self:UpdateLocationEggCounts( entity.locationId, entity:GetIsInCombat() ) end end end end end --End-ServerOnly
--[[ Name: LibGratuity-3.0 Revision: $Rev: 42 $ Author: Tekkub Stoutwrithe (tekkub@gmail.com) SVN: svn://svn.wowace.com/root/trunk/LibGratuity-3.0 Description: Tooltip parsing library Dependencies: (optional) Deformat-2.0 ]] local vmajor, vminor = "LibGratuity-3.0", 90000 + tonumber(("$Revision: 42 $"):match("%d+")) local lib = LibStub:NewLibrary(vmajor, vminor) if not lib then return end local methods = { "SetBagItem", "SetAction", "SetAuctionItem", "SetAuctionSellItem", "SetBuybackItem", "SetCraftItem", "SetCraftSpell", "SetHyperlink", "SetInboxItem", "SetInventoryItem", "SetLootItem", "SetLootRollItem", "SetMerchantItem", "SetPetAction", "SetPlayerBuff", "SetQuestItem", "SetQuestLogItem", "SetQuestRewardSpell", "SetSendMailItem", "SetShapeshift", "SetSpellByID", "SetTalent", "SetTrackingSpell", "SetTradePlayerItem", "SetTradeSkillItem", "SetTradeTargetItem", "SetTrainerService", "SetUnit", "SetUnitBuff", "SetUnitDebuff", "SetGuildBankItem", } if select(4, GetBuildInfo()) >= 40000 then table.insert(methods, "SetSpellBookItem") else table.insert(methods, "SetSpell") end function lib:CreateTooltip() local tt = CreateFrame("GameTooltip") self.vars.tooltip = tt tt:SetOwner(UIParent, "ANCHOR_NONE") -- tt:SetOwner(tt, "ANCHOR_NONE") -- tooltip:SetParent() self.vars.Llines, self.vars.Rlines = {}, {} for i=1,30 do self.vars.Llines[i], self.vars.Rlines[i] = tt:CreateFontString(), tt:CreateFontString() self.vars.Llines[i]:SetFontObject(GameFontNormal) self.vars.Rlines[i]:SetFontObject(GameFontNormal) tt:AddFontStrings(self.vars.Llines[i], self.vars.Rlines[i]) end end -- Clears the tooltip completely, none of this "erase left, hide right" crap blizzard does function lib:Erase() self.vars.tooltip:ClearLines() -- Ensures tooltip's NumLines is reset for i=1,30 do self.vars.Rlines[i]:SetText() end -- Clear text from right side (ClearLines only hides them) -- if not self.vars.tooltip:IsOwned(self.vars.tooltip) then self.vars.tooltip:SetOwner(self.vars.tooltip, "ANCHOR_NONE") end if not self.vars.tooltip:IsOwned(UIParent) then self.vars.tooltip:SetOwner(UIParent, "ANCHOR_NONE") end -- if not self.vars.tooltip:IsOwned(self.vars.tooltip) then -- error("Gratuity's tooltip is not scannable", 2) -- end if not self.vars.tooltip:IsOwned(UIParent) then error("Gratuity's tooltip is not scannable", 2) end end -- Get the number of lines -- Arg: endln - If passed and tooltip's NumLines is higher, endln is returned back function lib:NumLines(endln) local num = self.vars.tooltip:NumLines() return endln and num > endln and endln or num or 0 end local FindDefault = function(str, pattern) return string.find(str, pattern); end; local FindExact = function(str, pattern) if (str == pattern) then return string.find(str, pattern); end; end; -- If text is found on tooltip then results of string.find are returned -- Args: -- txt - The text string to find -- startln - First tooltip line to check, default 1 -- endln - Last line to test, default 30 -- ignoreleft / ignoreright - Causes text on one side of the tooltip to be ignored -- exact - the compare will be an exact match vs the default behaviour of function lib:Find(txt, startln, endln, ignoreleft, ignoreright, exact) local searchFunction = FindDefault; if (exact == true) then searchFunction = FindExact; end; assert(type(txt) == "string" or type(txt) == "number") local t1, t2 = type(startln or 1), type(self:NumLines(endln)) if (t1 ~= "number" or t2 ~= "number" ) then print(t1, t2, (startln or 1),self:NumLines(endln)) end for i=(startln or 1),self:NumLines(endln) do if not ignoreleft and self.vars.Llines[i] then local txtl = self.vars.Llines[i]:GetText() if (txtl and searchFunction(txtl, txt)) then return string.find(txtl, txt) end end if not ignoreright and self.vars.Rlines[i] then local txtr = self.vars.Rlines[i]:GetText() if (txtr and searchFunction(txtr, txt)) then return string.find(txtr, txt) end end end end -- Calls Find many times. -- Args are passed directly to Find, t1-t10 replace the txt arg -- Returns Find results for the first match found, if any function lib:MultiFind(startln, endln, ignoreleft, ignoreright, t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11) assert(type(t1) == "string" or type(t1) == "number") if t1 and self:Find(t1, startln, endln, ignoreleft, ignoreright) then return self:Find(t1, startln, endln, ignoreleft, ignoreright) elseif t2 then return self:MultiFind(startln, endln, ignoreleft, ignoreright, t2,t3,t4,t5,t6,t7,t8,t9,t10,t11) end end local deformat -- If text is found on tooltip then results of deformat:Deformat are returned -- Args: -- txt - The text string to deformat and serach for -- startln - First tooltip line to check, default 1 -- endln - Last line to test, default 30 -- ignoreleft / ignoreright - Causes text on one side of the tooltip to be ignored function lib:FindDeformat(txt, startln, endln, ignoreleft, ignoreright) assert(type(txt) == "string" or type(txt) == "number") if not deformat then if not AceLibrary or not AceLibrary:HasInstance("Deformat-2.0") then error("FindDeformat requires Deformat-2.0 to be available", 2) end deformat = AceLibrary("Deformat-2.0") end for i=(startln or 1),self:NumLines(endln) do if not ignoreleft and self.vars.Llines[i] then local txtl = self.vars.Llines[i]:GetText() if (txtl and deformat(txtl, txt)) then return deformat(txtl, txt) end end if not ignoreright and self.vars.Rlines[i] then local txtr = self.vars.Rlines[i]:GetText() if (txtr and deformat(txtr, txt)) then return deformat(txtr, txt) end end end end -- Returns a table of strings pulled from the tooltip, or nil if no strings in tooltip -- Args: -- startln - First tooltip line to check, default 1 -- endln - Last line to test, default 30 -- ignoreleft / ignoreright - Causes text on one side of the tooltip to be ignored function lib:GetText(startln, endln, ignoreleft, ignoreright) local retval for i=(startln or 1),(endln or 30) do local txtl, txtr if not ignoreleft and self.vars.Llines[i] then txtl = self.vars.Llines[i]:GetText() end if not ignoreright and self.vars.Rlines[i] then txtr = self.vars.Rlines[i]:GetText() end if txtl or txtr then if not retval then retval = {} end local t = {txtl, txtr} table.insert(retval, t) end end return retval end -- Returns the text from a specific line (both left and right unless second arg is true) -- Args: -- line - the line number you wish to retrieve -- getright - if passed the right line will be returned, if not the left will be returned function lib:GetLine(line, getright) assert(type(line) == "number") if self.vars.tooltip:NumLines() < line then return end if getright then return self.vars.Rlines[line] and self.vars.Rlines[line]:GetText() elseif self.vars.Llines[line] then return self.vars.Llines[line]:GetText(), self.vars.Rlines[line]:GetText() end end ----------------------------------- -- Set tooltip methods -- ----------------------------------- -- These methods are designed to immitate the GameTooltip API local testmethods = { SetAction = function(id) return HasAction(id) end, } local gettrue = function() return true end local function handlePcall(success, ...) if not success then geterrorhandler()(...) return end return ... end function lib:CreateSetMethods() for _,m in pairs(methods) do local meth = m local func = testmethods[meth] or gettrue self[meth] = function(self, ...) self:Erase() if not func(...) then return end return handlePcall(pcall(self.vars.tooltip[meth], self.vars.tooltip, ...)) end end end -- Activate a new instance of this library if not lib.vars then lib.vars = {} lib:CreateTooltip() end lib:CreateSetMethods() local function createCompat() createCompat = nil local Gratuity20 = setmetatable({}, {__index=function(self, key) if type(lib[key]) == "function" then self[key] = function(self, ...) return lib[key](lib, ...) end else self[key] = lib[key] end return self[key] end}) AceLibrary:Register(Gratuity20, "Gratuity-2.0", vminor+70000000) end if not AceLibrary then local frame = CreateFrame("Frame") frame:RegisterEvent("ADDON_LOADED") frame:SetScript("OnEvent", function(this) if not AceLibrary then return end createCompat() frame:SetScript("OnEvent", nil) frame:UnregisterAllEvents() frame:Hide() end) else createCompat() end
--------------------------------------------------------------------------------- -- -- GlobalComplete - A debug tool for World of Warcraft -- -- Copyright (C) 2006-2018 Jon S Akhtar (Sylvanaar) -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- ------------------------------------------------------------------------------- local name, _M = ... local pairs, ipairs, _G, table, LibStub, wipe, type, loadstring = pairs, ipairs, _G, table, LibStub, wipe, type, loadstring local setfenv, tostring, getmetatable, error = setfenv, tostring, getmetatable, error if not LibStub then error("globalcomplete requires LibStub") return end local AceTab = LibStub("AceTab-3.0") if not AceTab then error("globalcomplete requires AceTab") return end function _M:EnableGlobalCompletions(overrideName, maxResults, prematches) self.tabcompleteName = overrideName or (name .. "-debug-globals") self.maxResults = maxResults or 25 self.globalKeys = {} self.preMatches = prematches or { "/print%s+", "/dump%s+", "/script%s+", "/run%s+" } self:ReloadGlobals() self:GlobalTabComplete() self:FieldTabComplete() end function _M:GlobalTabComplete() if not AceTab:IsTabCompletionRegistered(self.tabcompleteName) then AceTab:RegisterTabCompletion(self.tabcompleteName, self.preMatches, function(t, text, pos) if (text:trim():len() < 1) then return nil end return self:GetPrefilteredCompletions(t, text, pos) end, function(...) return self:GetResultCompletions(...) end, nil, -- listenframes nil, -- postfunc nil) -- pmoverwrite end end function _M:FieldTabComplete() if not AceTab:IsTabCompletionRegistered(self.tabcompleteName .. "-fields") then AceTab:RegisterTabCompletion(self.tabcompleteName .. "-fields", ".+", function(t, text, pos, textToCursor) self:GetPrefilteredFieldCompletions(t, text, pos) end, function(...) return self:GetResultCompletions(...) end, nil, -- listenframes nil, -- postfunc nil) -- pmoverwrite end end function _M:GetResultCompletions(u, cands, gcss, prematch) local candcount = 0 for k, v in pairs(cands) do candcount = candcount + 1 end if candcount <= self.maxResults then local t = {} for key, cand in pairs(cands) do t[#t + 1] = key end table.sort(t) for i, v in ipairs(t) do local common = "|cffffffff" .. v:sub(1,gcss:len()) .. "|r" DEFAULT_CHAT_FRAME:AddMessage(" " .. common .. v:sub(gcss:len()+1), 0.1, 0.8, 0.1) end return else return " " .. ("Too many matches (%d possible)"):format(candcount) end return "error in usage function" end function _M:GetPrefilteredCompletions(t, text, pos) for i, v in ipairs(self.globalKeys) do t[#t + 1] = v end end function _M:GetPrefilteredFieldCompletions(t, text, pos) local globalPrematches = self.prematches if type(globalPrematches) == "string" then if tostring(text):lower():find(globalPrematches:lower(), 1, true) ~= 1 then return end elseif type(globalPrematches) == "table" then local result = false for i, v in ipairs(globalPrematches) do if tostring(v):lower():find(text:lower(), 1, true) == 1 then result = true end if not result then return end end end local lastDot = 0 for m in text:gmatch("()[:.]") do lastDot = m end local s = text:find("%s") if lastDot == 0 then return end if not s then return end local m, dot, fs = text:sub(s + 1, lastDot - 1), text:sub(lastDot, lastDot), text:sub(lastDot + 1, -1) fs = fs or "" if type(m) == "string" then local tmp = setfenv(loadstring("return " .. m), _G)() if type(tmp) == "table" then if dot == ":" then tmp = getmetatable(tmp) and getmetatable(tmp).__index or tmp end for k in pairs(tmp) do local candidate = m .. dot .. k if dot == ":" then if type(setfenv(loadstring("return " .. candidate:gsub(":", ".")), _G)()) ~= "function" then candidate = nil else candidate = candidate .. "()" end end if fs:len() > 0 then if tostring(k):lower():find(fs:lower(), 1, true) == 1 then t[#t + 1] = candidate end else t[#t + 1] = candidate end end return t end end end function _M:ReloadGlobals() wipe(self.globalKeys) for k in pairs(_G) do self.globalKeys[#self.globalKeys + 1] = k end end
local function foo(...) local args = { ... } print(table.unpack(args)) end
class = require '30log' deflate = require 'deflate' require 'stream' Chunk = class() Chunk.__name = "Chunk" Chunk.length = 0 Chunk.name = "" Chunk.data = "" Chunk.crc = "" function Chunk:__init(stream) if stream.__name == "Chunk" then self.length = stream.length self.name = stream.name self.data = stream.data self.crc = stream.crc else self.length = stream:readInt() self.name = stream:readChars(4) self.data = stream:readChars(self.length) self.crc = stream:readChars(4) end end function Chunk:getDataStream() return Stream({input = self.data}) end IHDR = Chunk:extends() IHDR.__name = "IHDR" IHDR.width = 0 IHDR.height = 0 IHDR.bitDepth = 0 IHDR.colorType = 0 IHDR.compression = 0 IHDR.filter = 0 IHDR.interlace = 0 function IHDR:__init(chunk) self.super.__init(self, chunk) local stream = chunk:getDataStream() self.width = stream:readInt() self.height = stream:readInt() self.bitDepth = stream:readByte() self.colorType = stream:readByte() self.compression = stream:readByte() self.filter = stream:readByte() self.interlace = stream:readByte() end IDAT = Chunk:extends() IDAT.__name = "IDAT" function IDAT:__init(chunk) self.super.__init(self, chunk) end PLTE = Chunk:extends() PLTE.__name = "PLTE" PLTE.numColors = 0 PLTE.colors = {} function PLTE:__init(chunk) self.super.__init(self, chunk) self.numColors = math.floor(chunk.length/3) local stream = chunk:getDataStream() for i = 1, self.numColors do self.colors[i] = { R = stream:readByte(), G = stream:readByte(), B = stream:readByte(), } end end function PLTE:getColor(index) return self.colors[index] end Pixel = class() Pixel.__name = "Pixel" Pixel.R = 0 Pixel.G = 0 Pixel.B = 0 Pixel.A = 0 function Pixel:__init(stream, depth, colorType, palette) local bps = math.floor(depth/8) if colorType == 0 then local grey = stream:readInt(bps) self.R = grey self.G = grey self.B = grey self.A = 255 end if colorType == 2 then self.R = stream:readInt(bps) self.G = stream:readInt(bps) self.B = stream:readInt(bps) self.A = 255 end if colorType == 3 then local index = stream:readInt(bps)+1 local color = palette:getColor(index) self.R = color.R self.G = color.G self.B = color.B self.A = 255 end if colorType == 4 then local grey = stream:readInt(bps) self.R = grey self.G = grey self.B = grey self.A = stream:readInt(bps) end if colorType == 6 then self.R = stream:readInt(bps) self.G = stream:readInt(bps) self.B = stream:readInt(bps) self.A = stream:readInt(bps) end end function Pixel:format() return string.format("R: %d, G: %d, B: %d, A: %d", self.R, self.G, self.B, self.A) end ScanLine = class() ScanLine.__name = "ScanLine" ScanLine.pixels = {} ScanLine.filterType = 0 function ScanLine:__init(stream, depth, colorType, palette, length) bpp = math.floor(depth/8) * self:bitFromColorType(colorType) bpl = bpp*length self.filterType = stream:readByte() stream:seek(-1) stream:writeByte(0) local startLoc = stream.position if self.filterType == 0 then for i = 1, length do self.pixels[i] = Pixel(stream, depth, colorType, palette) end end if self.filterType == 1 then for i = 1, length do for j = 1, bpp do local curByte = stream:readByte() stream:seek(-(bpp+1)) local lastByte = 0 if stream.position >= startLoc then lastByte = stream:readByte() or 0 else stream:readByte() end stream:seek(bpp-1) stream:writeByte((curByte + lastByte) % 256) end stream:seek(-bpp) self.pixels[i] = Pixel(stream, depth, colorType, palette) end end if self.filterType == 2 then for i = 1, length do for j = 1, bpp do local curByte = stream:readByte() stream:seek(-(bpl+2)) local lastByte = stream:readByte() or 0 stream:seek(bpl) stream:writeByte((curByte + lastByte) % 256) end stream:seek(-bpp) self.pixels[i] = Pixel(stream, depth, colorType, palette) end end if self.filterType == 3 then for i = 1, length do for j = 1, bpp do local curByte = stream:readByte() stream:seek(-(bpp+1)) local lastByte = 0 if stream.position >= startLoc then lastByte = stream:readByte() or 0 else stream:readByte() end stream:seek(-(bpl)+bpp-2) local priByte = stream:readByte() or 0 stream:seek(bpl) stream:writeByte((curByte + math.floor((lastByte+priByte)/2)) % 256) end stream:seek(-bpp) self.pixels[i] = Pixel(stream, depth, colorType, palette) end end if self.filterType == 4 then for i = 1, length do for j = 1, bpp do local curByte = stream:readByte() stream:seek(-(bpp+1)) local lastByte = 0 if stream.position >= startLoc then lastByte = stream:readByte() or 0 else stream:readByte() end stream:seek(-(bpl + 2 - bpp)) local priByte = stream:readByte() or 0 stream:seek(-(bpp+1)) local lastPriByte = 0 if stream.position >= startLoc - (length * bpp + 1) then lastPriByte = stream:readByte() or 0 else stream:readByte() end stream:seek(bpl + bpp) stream:writeByte((curByte + self:_PaethPredict(lastByte, priByte, lastPriByte)) % 256) end stream:seek(-bpp) self.pixels[i] = Pixel(stream, depth, colorType, palette) end end end function ScanLine:bitFromColorType(colorType) if colorType == 0 then return 1 end if colorType == 2 then return 3 end if colorType == 3 then return 1 end if colorType == 4 then return 2 end if colorType == 6 then return 4 end error 'Invalid colortype' end function ScanLine:getPixel(pixel) return self.pixels[pixel] end --Stolen right from w3. function ScanLine:_PaethPredict(a, b, c) local p = a + b - c local varA = math.abs(p - a) local varB = math.abs(p - b) local varC = math.abs(p - c) if varA <= varB and varA <= varC then return a end if varB <= varC then return b end return c end pngImage = class() pngImage.__name = "PNG" pngImage.width = 0 pngImage.height = 0 pngImage.depth = 0 pngImage.colorType = 0 pngImage.scanLines = {} function pngImage:__init(path, progCallback) local str = Stream({inputF = path}) if str:readChars(8) ~= "\137\080\078\071\013\010\026\010" then error 'Not a PNG' end local ihdr = {} local plte = {} local idat = {} local num = 1 while true do ch = Chunk(str) if ch.name == "IHDR" then ihdr = IHDR(ch) end if ch.name == "PLTE" then plte = PLTE(ch) end if ch.name == "IDAT" then idat[num] = IDAT(ch) num = num+1 end if ch.name == "IEND" then break end end self.width = ihdr.width self.height = ihdr.height self.depth = ihdr.bitDepth self.colorType = ihdr.colorType local dataStr = "" for k,v in pairs(idat) do dataStr = dataStr .. v.data end local output = {} deflate.inflate_zlib {input = dataStr, output = function(byte) output[#output+1] = string.char(byte) end, disable_crc = true} imStr = Stream({input = table.concat(output)}) for i = 1, self.height do self.scanLines[i] = ScanLine(imStr, self.depth, self.colorType, plte, self.width) if progCallback ~= nil then progCallback(i, self.height) end end end function pngImage:getPixel(x, y) local pixel = self.scanLines[y].pixels[x] return pixel end
local kLastRebirthUpdate = 1532713086 local menu_was_opened = false local function GetShouldOpenChangelog() if menu_was_opened then return false end menu_was_opened = true local last = Client.GetOptionInteger( "lastRebirthModUpdate", 0) Log("Last viewed rebirth changlog: " .. last) if last < kLastRebirthUpdate then last = os.time(os.date("!*t")) Client.SetOptionInteger("lastRebirthModUpdate", last) return true end return false end local oldSendKeyEvent = Player.SendKeyEvent function Player:SendKeyEvent(key, down) oldSendKeyEvent(self, key, down) if GetShouldOpenChangelog() then MainMenu_Open() menu_was_opened = true end end
---练习11.1 当我们对一段文本执行统计单词出现频率的程序时,结果常常是一些注入冠词和介词之类的没有太多意义 ---的短词汇。请改写该程序,使他忽略长度小于4个字母的单词 ---练习11.2 重复上面的练习,除了按照长度忽略单词外,该程序还能从一个文本文件中读取要忽略的单词列表。 local ignore = {} for line in io.lines("ignorewords.txt") do for word in string.gmatch(line,"%w+") do ignore[word] = true end end local counter = {} for line in io.lines("content.txt") do for word in string.gmatch(line,"%w%w%w+") do if not ignore[word] then counter[word] = (counter[word] or 0) + 1 end end end local words = {} for w in pairs(counter) do words[#words + 1] = w end table.sort(words,function (w1,w2) return counter[w1] > counter[w2] or counter[w1] == counter[w2] and w1 < w2 end) local n = math.min(tonumber(arg[1]) or math.huge,#words) for i = 1, n do io.write(words[i] , "\t",counter[words[i]],"\n") end
--=========== Copyright © 2019, Planimeter, All rights reserved. ===========-- -- -- Purpose: Main Menu Button class -- --==========================================================================-- class "gui.mainmenubutton" ( "gui.button" ) local mainmenubutton = gui.mainmenubutton function mainmenubutton:mainmenubutton( parent, text ) local name = text and text or "Blank" .. " Button" gui.button.button( self, parent, name, text or "" ) self:setBorderWidth( 0 ) local font = self:getScheme( "mainmenuFont" ) self.text:set( text ) self.text:setFont( font ) self.height = font:getHeight() end function mainmenubutton:draw() local textColor = "mainmenubutton.dark.textColor" local mouseover = ( self.mouseover or self:isChildMousedOver() ) if ( self:isDisabled() ) then textColor = "mainmenubutton.dark.disabled.textColor" elseif ( self.mousedown and mouseover ) then textColor = "mainmenubutton.dark.mousedown.textColor" elseif ( self.mousedown or mouseover or self.focus ) then textColor = "mainmenubutton.dark.mouseover.textColor" end self.text:setColor( self:getScheme( textColor ) ) gui.box.draw( self ) end
--[[ Server: AuroraRPG Resource Name: Races Version: 1.0 Developer/s: Curt ]]-- function createRaceMarkerForCheckpoint(checkpoint, index, numberOfCheckpoints) local r,g,b, a = 255, 0, 0, 110 local x,y,z = checkpoint[1], checkpoint[2], checkpoint[3] local hitMarkerSize = 17 local visualMarkerSize = 6 if (index == 1) then r,g,b = 0, 0, 255 elseif (index == numberOfCheckpoints) then r,g,b = 0, 255, 0 hitMarkerSize = 17 visualMarkerSize = 10 end local hitMarker if (not editingTrack and not loadingTrack) then hitMarker = createMarker (x, y, z, "checkpoint", 20 , 0, 0, 0, 0) setMarkerSize (hitMarker, -hitMarkerSize) end local visualMarker = createMarker (x, y, z, "checkpoint", visualMarkerSize , r, g, b, a) setElementData (visualMarker, "markerSize", visualMarkerSize) return hitMarker, visualMarker end addEvent ("aurillegalraces.startPreRace", true) function startRacePre (raceName, checkpoints, racers) if (not racing) then if (isElement (GUI_manageRaceButton_toggleRace)) then guiSetText (GUI_manageRaceButton_toggleRace, "Stop Race") end race_racers = racers checkpoints = fromJSON (checkpoints) racing = true addEventHandler ("onClientPlayerQuit", root, onRacerQuit) if (playerGodMode) then removeEventHandler ("onClientPlayerDamage", localPlayer, cancelDamage, false) playerGodMode = false end race_checkpointsData = checkpoints race_checkpoints = {} startRaceticks = false race_checkpoints_hit = {} playerFinished = false setElementData (localPlayer ,"aurillegalraces.checkpointIndexLastHit", 0) for i=1, #race_checkpointsData do local hitMarker, visualMarker = createRaceMarkerForCheckpoint (race_checkpointsData[i], i, #race_checkpointsData) adjustElementProperties (visualMarker, i, #race_checkpointsData) if (i == 1) then local blip = createBlipAttachedTo (visualMarker, 0) adjustElementProperties (visualMarker, i, #race_checkpointsData) if (#race_checkpointsData > 2) then local x2,y2,z2 = race_checkpointsData[i+1][1], race_checkpointsData[i+1][2], race_checkpointsData[i+1][3] setMarkerTarget (visualMarker, x2, y2, z2) table.insert (race_checkpoints, { hitMarker, visualMarker, blip, arrowObject }) else table.insert (race_checkpoints, { hitMarker, visualMarker, blip }) end elseif (i == 2) then local blip = createBlipAttachedTo (visualMarker, 0) adjustElementProperties (visualMarker, i, #race_checkpointsData) table.insert (race_checkpoints, { hitMarker, visualMarker, blip }) setMarkerSize (visualMarker, -6) else table.insert (race_checkpoints, { hitMarker, visualMarker }) setMarkerSize (visualMarker, -6) end end if (isElementWithinMarker (localPlayer, race_checkpoints[1][2]) or isElementWithinMarker (getPedOccupiedVehicle (localPlayer), race_checkpoints[1][2])) then race_onMarkerHit(localPlayer, hitMarker) end rankString = "" addEventHandler ("onClientPlayerWasted", localPlayer, onPlayerWasted, false) countdownRGB = { math.random (0, 255), math.random (0, 255), math.random (0, 255) } setElementFrozen (getPedOccupiedVehicle (localPlayer) or localPlayer, true) if (not drawingRaceGUI) then drawingRaceGUI = true end setPedCanBeKnockedOffBike (localPlayer, false) toggleControl ("accelerate", false) toggleControl ("brake_reverse", false) toggleControl ("vehicle_left", false) toggleControl ("vehicle_right", false) if (editingTrack) then trackEditor_saveTrack ("GUI", true) trackEditor_closeTrack() end if (isTimer (changeCountDownColorTimer)) then killTimer (changeCountDownColorTimer) end changeCountDownColorTimer = setTimer ( function () countdownRGB = { math.random (0, 255), math.random (0, 255), math.random (0, 255) } end , math.random (100, 250), 0) drawPositions = false end end addEventHandler ("aurillegalraces.startPreRace", root, startRacePre) addEvent ("aurillegalraces.startRace", true) function startRace (raceStartTicks) if (not raceStarted) then startRaceticks = getTickCount() if (isElement (race_checkpoints[1][1])) then addEventHandler ("onClientMarkerHit", race_checkpoints[1][1], race_onMarkerHit, false) addEventHandler ("onClientMarkerHit", race_checkpoints[1][2], race_onMarkerHit, false) end raceStarted = true toggleControl ("accelerate", true) toggleControl ("brake_reverse", true) toggleControl ("vehicle_left", true) toggleControl ("vehicle_right", true) if (isTimer (changeCountDownColorTimer)) then killTimer (changeCountDownColorTimer) end end end addEventHandler ("aurillegalraces.startRace", root, startRace) addEvent ("aurillegalraces.stopRace", true) function stopRace () if (racing) then racing = false removeEventHandler ("onClientPlayerQuit", root, onRacerQuit) raceStarted = false race_racers = nil updateRanksTimer = nil rankString = nil removeEventHandler ("onClientPlayerWasted", localPlayer, onPlayerWasted, false) for i=1, #race_checkpoints do for index=1, #race_checkpoints[i] do if (isElement(race_checkpoints[i][index])) then destroyElement (race_checkpoints[i][index]) end end end playerFinished = false startRaceticks = false setElementData (localPlayer ,"aurillegalraces.checkpointIndexLastHit", false) race_checkpointsData = nil race_checkpoints = nil race_checkpoints_hit = nil inSpectatorMode = false if (getPedOccupiedVehicle (localPlayer)) then setVehicleDamageProof (getPedOccupiedVehicle (localPlayer), false) setElementFrozen (getPedOccupiedVehicle (localPlayer), false) end if (drawingRaceGUI) then drawingRaceGUI = false end setElementFrozen (localPlayer, false) setPedCanBeKnockedOffBike (localPlayer, true) toggleControl ("accelerate", true) toggleControl ("brake_reverse", true) toggleControl ("vehicle_left", true) toggleControl ("vehicle_right", true) fadeCamera (true) if (isTimer (changeCountDownColorTimer)) then killTimer (changeCountDownColorTimer) end setElementData (localPlayer, "aurillegalraces.isFinished", false) drawPositions = false end end addEventHandler ("aurillegalraces.stopRace", root, stopRace) function distanceFromPlayerToCheckpoint (player, checkpointIndex) if (race_checkpoints[checkpointIndex + 1]) then local px, py, pz = getElementPosition (player) local cx, cy, cz = getElementPosition (race_checkpoints[checkpointIndex + 1][1]) return getDistanceBetweenPoints3D (px, py, pz, cx, cy, cz) end end function race_onMarkerHit(hitElement, marker) if (not source) then source = marker end if (hitElement == localPlayer) then local visualMarker local newIndex for i=1, #race_checkpoints do if (race_checkpoints[i][source]) then visualMarker = race_checkpoints[i][2] newIndex = i elseif (race_checkpoints[i][2] == source) then visualMarker = source source = race_checkpoints[i][1] newIndex = i end end if (not race_checkpoints_hit[source]) then local oldIndex = getElementData (localPlayer ,"aurillegalraces.checkpointIndexLastHit") local newIndex = oldIndex + 1 local nextMarkerIndex = newIndex + 1 setElementData (localPlayer ,"aurillegalraces.checkpointIndexLastHit", newIndex) table.insert (race_checkpoints_hit, source) if (newIndex == #race_checkpoints) then race_onHitFinish() removeEventHandler ("onClientMarkerHit", race_checkpoints[newIndex][1], race_onMarkerHit, false) else for i=1, newIndex do for ind=1, #race_checkpoints[i] do if (isElement (race_checkpoints[i][ind])) then destroyElement (race_checkpoints[i][ind]) end if (isElement (race_checkpoints[i][ind])) then table.remove (race_checkpoints[i], ind) end end end local blip = createBlipAttachedTo (race_checkpoints[nextMarkerIndex][1], 0) adjustElementProperties (blip, nextMarkerIndex, #race_checkpoints) table.insert (race_checkpoints[nextMarkerIndex], blip) addEventHandler ("onClientMarkerHit", race_checkpoints[nextMarkerIndex][1], race_onMarkerHit, false) setMarkerSize (race_checkpoints[nextMarkerIndex ][2], getElementData (race_checkpoints[nextMarkerIndex ][2], "markerSize")) if (nextMarkerIndex+1 <= #race_checkpoints) then local blip = createBlipAttachedTo (race_checkpoints[nextMarkerIndex + 1][1], 0) adjustElementProperties (blip, nextMarkerIndex+1, #race_checkpoints) table.insert (race_checkpoints[nextMarkerIndex + 1 ], blip) local x2,y2, z2 = getElementPosition (race_checkpoints[nextMarkerIndex + 1][1]) setMarkerTarget (race_checkpoints[nextMarkerIndex][2], x2, y2, z2) end end end end end function race_onHitFinish() triggerServerEvent ("aurillegalraces.onPlayerFinish", localPlayer) playerFinished = true end function onRacerQuit () if (race_racers[source]) then for i=1,#race_racers do if (source == race_racers[i]) then table.remove (race_racers, i) end end end end addEventHandler ("onClientResourceStop", getResourceRootElement(getThisResource()), function () toggleControl ("accelerate", true) toggleControl ("brake_reverse", true) toggleControl ("vehicle_left", true) toggleControl ("vehicle_right", true) setCameraTarget (localPlayer) stopRace() setElementData (localPlayer, "aurillegalraces.isSignedUp", false) if (getPedOccupiedVehicle (localPlayer)) then setVehicleDamageProof (getPedOccupiedVehicle (localPlayer), false) setElementFrozen (getPedOccupiedVehicle (localPlayer), false) end setElementFrozen (localPlayer, false) end ) function onPlayerWasted () if (racing) then stopRace() end end function isPedDead (ped) if (isElement (ped)) then return getElementHealth (ped) <=0 end end function adjustElementProperties (element, index, maximum) if (getElementType (element) == "marker" and getElementData (element, "markerSize")) then local r,g,b, a = 255, 0, 0, 110 local visualMarkerSize = 6 if (index == 1) then r,g,b = 0, 0, 255 elseif (index == maximum) then r,g,b = 0, 255, 0 visualMarkerSize = 10 end setMarkerColor (element, r, g, b, a) setMarkerSize (element, visualMarkerSize) setElementData (element, "markerSize", visualMarkerSize) elseif (getElementType (element) == "blip") then local r,g,b = 4, 255, 0 local blipSize = 4 local blipIcon = 0 if (index ~= 1 and maximum == index) then blipIcon = 53 elseif (index == 1) then r,g,b = 0,0,255 end setBlipSize (element, blipSize) setBlipIcon (element, blipIcon) setBlipColor (element, r, g, b, 255) end end
-- Tests for getbufvar(), getwinvar(), gettabvar() and gettabwinvar(). local helpers = require('test.functional.helpers') local insert, source = helpers.insert, helpers.source local clear, expect = helpers.clear, helpers.expect describe('context variables', function() setup(clear) it('is working', function() insert("start:") -- Test for getbufvar(). -- Use strings to test for memory leaks. source([[ let t:testvar='abcd' $put =string(gettabvar(1, 'testvar')) $put =string(gettabvar(1, 'testvar')) let b:var_num = '1234' let def_num = '5678' $put =string(getbufvar(1, 'var_num')) $put =string(getbufvar(1, 'var_num', def_num)) $put =string(getbufvar(1, '')) $put =string(getbufvar(1, '', def_num)) unlet b:var_num $put =string(getbufvar(1, 'var_num', def_num)) $put =string(getbufvar(1, '')) $put =string(getbufvar(1, '', def_num)) $put =string(getbufvar(9, '')) $put =string(getbufvar(9, '', def_num)) unlet def_num $put =string(getbufvar(1, '&autoindent')) $put =string(getbufvar(1, '&autoindent', 1)) ]]) -- Open new window with forced option values. source([[ set fileformats=unix,dos new ++ff=dos ++bin ++enc=iso-8859-2 let otherff = getbufvar(bufnr('%'), '&fileformat') let otherbin = getbufvar(bufnr('%'), '&bin') let otherfenc = getbufvar(bufnr('%'), '&fenc') close $put =otherff $put =string(otherbin) $put =otherfenc unlet otherff otherbin otherfenc ]]) -- Test for getwinvar(). source([[ let w:var_str = "Dance" let def_str = "Chance" $put =string(getwinvar(1, 'var_str')) $put =string(getwinvar(1, 'var_str', def_str)) $put =string(getwinvar(1, '')) $put =string(getwinvar(1, '', def_str)) unlet w:var_str $put =string(getwinvar(1, 'var_str', def_str)) $put =string(getwinvar(1, '')) $put =string(getwinvar(1, '', def_str)) $put =string(getwinvar(9, '')) $put =string(getwinvar(9, '', def_str)) $put =string(getwinvar(1, '&nu')) $put =string(getwinvar(1, '&nu', 1)) unlet def_str ]]) -- Test for gettabvar(). source([[ tabnew tabnew let t:var_list = [1, 2, 3] let t:other = 777 let def_list = [4, 5, 6, 7] tabrewind $put =string(gettabvar(3, 'var_list')) $put =string(gettabvar(3, 'var_list', def_list)) $put =string(gettabvar(3, '')) $put =string(gettabvar(3, '', def_list)) tablast unlet t:var_list tabrewind $put =string(gettabvar(3, 'var_list', def_list)) $put =string(gettabvar(9, '')) $put =string(gettabvar(9, '', def_list)) $put =string(gettabvar(3, '&nu')) $put =string(gettabvar(3, '&nu', def_list)) unlet def_list tabonly ]]) -- Test for gettabwinvar(). source([[ tabnew tabnew tabprev split split wincmd w vert split wincmd w let w:var_dict = {'dict': 'tabwin'} let def_dict = {'dict2': 'newval'} wincmd b tabrewind $put =string(gettabwinvar(2, 3, 'var_dict')) $put =string(gettabwinvar(2, 3, 'var_dict', def_dict)) $put =string(gettabwinvar(2, 3, '')) $put =string(gettabwinvar(2, 3, '', def_dict)) tabnext 3wincmd w unlet w:var_dict tabrewind $put =string(gettabwinvar(2, 3, 'var_dict', def_dict)) $put =string(gettabwinvar(2, 3, '')) $put =string(gettabwinvar(2, 3, '', def_dict)) $put =string(gettabwinvar(2, 9, '')) $put =string(gettabwinvar(2, 9, '', def_dict)) $put =string(gettabwinvar(9, 3, '')) $put =string(gettabwinvar(9, 3, '', def_dict)) unlet def_dict $put =string(gettabwinvar(2, 3, '&nux')) $put =string(gettabwinvar(2, 3, '&nux', 1)) tabonly ]]) -- Assert buffer contents. expect([[ start: 'abcd' 'abcd' '1234' '1234' {'var_num': '1234'} {'var_num': '1234'} '5678' {} {} '' '5678' 0 0 dos 1 iso-8859-2 'Dance' 'Dance' {'var_str': 'Dance'} {'var_str': 'Dance'} 'Chance' {} {} '' 'Chance' 0 0 [1, 2, 3] [1, 2, 3] {'var_list': [1, 2, 3], 'other': 777} {'var_list': [1, 2, 3], 'other': 777} [4, 5, 6, 7] '' [4, 5, 6, 7] '' [4, 5, 6, 7] {'dict': 'tabwin'} {'dict': 'tabwin'} {'var_dict': {'dict': 'tabwin'}} {'var_dict': {'dict': 'tabwin'}} {'dict2': 'newval'} {} {} '' {'dict2': 'newval'} '' {'dict2': 'newval'} '' 1]]) end) end)
???!?? (Γ;??d???|c'?d?1?? ?.\?s?f??v? ? (2?1?$v^??-???O?p??c{??=?.!89y???z????o??:j<? W(????2Q??cA??h????{?require 'signatured3' print('signatured1: this source was signatured!')
require "hello2" function foo(a,b,c,...) local sum = a+b return sum, c -- 可以返回多个值 end r1, r2 = foo(1,"123","hello") print(r1,r2) v1, v2 = 4, 6; callForMe("dadf"); print(myadd(1,3)); print(package.path); print(_VERSION) print(math.pi) local twoFace4 = math.pow(2,4) print(twoFace4) local a = {}; function doSomething() print("do ...") end local caller="sell" a[caller] = doSomething a[caller]()
-- "Welcome to Jumpy Town!" https://youtu.be/KfyKD959IeM?t=26 local moonshine = require 'moonshine' local Sounds = require 'src/util/sounds' local GAME_WIDTH = 400 local GAME_HEIGHT = 670 -- in [0, 1). exponential decay. lower = game gets difficult more quickly local ENTROPY_FACTOR = 0.9975 local GRAVITY = -1600 local JUMP_STANDARD_LAUNCH_VEL = (GRAVITY / 1.8) local JUMP_SPRING_LAUNCH_VEL = GRAVITY * 1.5 local MOVING_PLATFORM_SPEED = 60.0 local PLATFORM_HIT_GLOW_DUR = 0.6 local PLAYER_JUMP_GLOW_DUR = PLATFORM_HIT_GLOW_DUR local avatarImage = nil local player = {} local platforms = {} local num_platforms_cleared local bg_horiz_line_heights = {} local NUM_GRID_ROWS = 20 local NUM_GRID_COLS = NUM_GRID_ROWS * (GAME_WIDTH/GAME_HEIGHT) local PLATFORM_WIDTH = (GAME_WIDTH / 5) local platform_width = PLATFORM_WIDTH local PLATFORM_HEIGHT = (GAME_HEIGHT / 35) local PLATFORM_SPAWN_RATE_DEFAULT = 1.0 local platform_spawn_rate = PLATFORM_SPAWN_RATE_DEFAULT local screen_effect = screen_effect or moonshine(moonshine.effects.glow) .chain(moonshine.effects.godsray) .chain(moonshine.effects.pixelate) .chain(moonshine.effects.filmgrain) .chain(moonshine.effects.crt) screen_effect.pixelate.feedback = 0.0 screen_effect.pixelate.size = {2,2} screen_effect.glow.strength = 5.0 screen_effect.filmgrain.size = 5.0 screen_effect.filmgrain.opacity = 0.5 screen_effect.crt.x = 1.0 screen_effect.crt.y = 1.0 screen_effect.crt.feather = 0.1 screen_effect.godsray.exposure = 0.0 -- carefully set domain of below three numbers -- see spawnPlatformAtHeight local red_platform_chance = 0.08 local blue_platform_chance = 0.00 local function spawnPlatformAtHeight(height) newPlatform = { x = ((GAME_WIDTH - PLATFORM_WIDTH) * math.random()) + (PLATFORM_WIDTH / 2.0), y = height, width = platform_width, height = PLATFORM_HEIGHT, time_since_hit = -1.0, } local randomType = math.random() if randomType < red_platform_chance then newPlatform.type = "spring" elseif randomType < blue_platform_chance then newPlatform.type = "moving" newPlatform.x_vel = MOVING_PLATFORM_SPEED else newPlatform.type = "default" end platforms[#platforms + 1] = newPlatform end local function initSounds() Sounds.jump = Sound:new('jump.mp3', 2) Sounds.jump:setVolume(0.5) Sounds.springJump = Sound:new('spring_jump.mp3', 4) Sounds.springJump:setVolume(0.5) Sounds.movingPlatform = Sound:new('moving_platform.mp3', 1) Sounds.movingPlatform:setVolume(0.06) Sounds.movingPlatform:setLooping(true) Sounds.movingPlatformBounce = Sound:new('moving_platform_bounce.mp3', 3) Sounds.movingPlatformBounce:setVolume(0.3) Sounds.ambience = Sound:new('ambience.mp3', 1) Sounds.ambience:setVolume(0.2) Sounds.ambience:setLooping(true) Sounds.music = Sound:new('music.mp3', 1) Sounds.music:setVolume(0.2) Sounds.music:setLooping(true) end local function resetGame() total_time_elapsed = 0.0 red_platform_chance = 0.08 blue_platform_chance = 0.00 screen_effect.crt.x = 1 screen_effect.crt.y = 1 Sounds.movingPlatform:stop() Sounds.ambience:stop() Sounds.ambience:play() num_platforms_cleared = 0 platform_width = PLATFORM_WIDTH platform_spawn_rate = PLATFORM_SPAWN_RATE_DEFAULT -- reset player player.move_speed = 320 player.width = GAME_WIDTH / 8 player.height = player.width player.x = GAME_WIDTH / 2 - player.width / 2 player.y = GAME_HEIGHT - player.height - 1 player.xPrev = player.x player.yPrev = player.y player.y_velocity = GRAVITY player.time_since_jumped = -1.0 -- clear all data structures for platform_idx in pairs(platforms) do platforms[platform_idx] = nil end for idx in pairs(bg_horiz_line_heights) do bg_horiz_line_heights[idx] = nil end -- spawn initial platforms platforms[#platforms + 1] = { x = GAME_WIDTH / 2 - platform_width / 2, y = GAME_HEIGHT * 0.8, width = platform_width, height = PLATFORM_HEIGHT, type = "default", time_since_hit = -1.0 } spawnPlatformAtHeight(GAME_HEIGHT * 0.85) spawnPlatformAtHeight(GAME_HEIGHT * 0.7) spawnPlatformAtHeight(GAME_HEIGHT * 0.65) spawnPlatformAtHeight(GAME_HEIGHT * 0.55) spawnPlatformAtHeight(GAME_HEIGHT * 0.4) spawnPlatformAtHeight(GAME_HEIGHT * 0.3) spawnPlatformAtHeight(GAME_HEIGHT * 0.23) spawnPlatformAtHeight(GAME_HEIGHT * 0.2) spawnPlatformAtHeight(GAME_HEIGHT * 0.14) spawnPlatformAtHeight(GAME_HEIGHT * 0.1) spawnPlatformAtHeight(GAME_HEIGHT * 0.0) -- bg grid lines for i = 1, NUM_GRID_ROWS do bg_horiz_line_heights[#bg_horiz_line_heights + 1] = { y = (i - 1)/NUM_GRID_ROWS * GAME_HEIGHT } end end function love.load() math.randomseed(os.time()) initSounds() Sounds.music:play() avatarImage = love.graphics.newImage('assets/img/avatar.png') resetGame() end -- ensure game isn't impossible by adding a platform if necessary local function ensureGameIsPossible() table.sort(platforms, function(left, right) return left.y < right.y end) local biggestAllowedGap = GAME_HEIGHT / 2.8 for i, platform in ipairs(platforms) do -- spawn at top if first platform on screen -- leaves too big of gap at top of screen if platform.y > 0 then if platform.y > biggestAllowedGap then spawnPlatformAtHeight(-PLATFORM_HEIGHT) end break end -- skip last iteration if i < #platforms then nextPlatform = platforms[i + 1] verticalGap = nextPlatform.y - platform.y if verticalGap > biggestAllowedGap then spawnPlatformAtHeight(platform.y + verticalGap/2.0) end end end end local function updateScreenDistortionBasedUponProgress() if num_platforms_cleared > 400 then -- make player look in the corners to reason about where to go screen_effect.crt.x = -3.0 screen_effect.crt.y = -3.0 elseif num_platforms_cleared > 260 then -- intentionally let amt go into the negative amt = 1.0 - ((num_platforms_cleared - 260) / 10) warp_amt = 1.0 + amt * math.sin(total_time_elapsed * (0.5 + 5.0)) screen_effect.crt.x = warp_amt screen_effect.crt.y = warp_amt elseif num_platforms_cleared > 110 then amt = ((num_platforms_cleared - 110) / 150) warp_amt = 1.0 + amt * math.sin(total_time_elapsed * (0.5 + (5.0 * amt))) screen_effect.crt.x = warp_amt screen_effect.crt.y = warp_amt if num_platforms_cleared > 200 then blue_platform_chance = 0.5 end elseif num_platforms_cleared > 100 then amt = 1.5 - 0.5 * ((num_platforms_cleared - 100) / 10) screen_effect.crt.x = amt screen_effect.crt.y = amt blue_platform_chance = 0.15 elseif num_platforms_cleared > 0 then local pct_done_w_section = num_platforms_cleared / 100 amt = 1.0 + 0.5 * pct_done_w_section screen_effect.crt.x = amt screen_effect.crt.y = amt -- fade music in from platforms 50-100 if num_platforms_cleared > 50 then vol = ((num_platforms_cleared - 50.0) / 50.0) * 0.2 Sounds.music:setVolume(vol) else Sounds.music:setVolume(0.0) end end end function love.update(dt) if love.keyboard.isDown("d") or love.keyboard.isDown("right") then player.x = player.x + (player.move_speed * dt) if player.x > GAME_WIDTH - player.width then player.x = GAME_WIDTH - player.width end elseif love.keyboard.isDown("a") or love.keyboard.isDown("left") then player.x = player.x - (player.move_speed * dt) if player.x < 0 then player.x = 0 end end player.y = player.y + player.y_velocity * dt player.y_velocity = player.y_velocity - GRAVITY * dt if player.y > GAME_HEIGHT * 3 then resetGame() return end -- for all existing platforms local platformPlayerHit = nil local movingPlatformIsOnscreen = false for i = #platforms, 1, -1 do local platform = platforms[i] -- update moving platforms if platform.type == "moving" then if platform.x + platform.width > GAME_WIDTH then platform.x = GAME_WIDTH - platform.width platform.x_vel = -platform.x_vel Sounds.movingPlatformBounce:play() elseif platform.x < 0 then platform.x = 0 platform.x_vel = -platform.x_vel Sounds.movingPlatformBounce:play() end platform.x = platform.x + platform.x_vel * dt movingPlatformIsOnscreen = true end -- update platform's time for animation if was touched if platform.time_since_hit > 0.0 then if platform.time_since_hit > PLATFORM_HIT_GLOW_DUR then platform.time_since_hit = -1.0 else platform.time_since_hit = platform.time_since_hit + dt end end -- handle collisions with player if player.yPrev + player.height < platform.y and player.y + player.height > platform.y and player.x + player.width > platform.x and player.x < platform.x + platform.width and player.y + player.height > 0 then platformPlayerHit = platform end -- remove platforms when they go off bottom of screen if (platform.y > GAME_HEIGHT) then num_platforms_cleared = num_platforms_cleared + 1 table.remove(platforms, i) -- maybe spawn a new platform at a small offset above screen's top local shouldSpawnPlatform = (math.random() < platform_spawn_rate) if (shouldSpawnPlatform) then spawnPlatformAtHeight(-PLATFORM_HEIGHT) end -- Try exponential decay on platform spawn rate platform_spawn_rate = platform_spawn_rate * ENTROPY_FACTOR platform_width = platform_width * ENTROPY_FACTOR end -- slide platforms downward as player is above threshold on screen local camera_threshold = (GAME_HEIGHT / 2.0) - (player.height / 2.0) if player.y < camera_threshold and player.y_velocity < 0 then player.y = camera_threshold - 1 platform.y = platform.y - player.y_velocity * dt -- bg grid lines for i = 1, NUM_GRID_ROWS do line = bg_horiz_line_heights[i] line.y = line.y - player.y_velocity * dt -- wrap if line.y < 0 then line.y = line.y + GAME_HEIGHT elseif line.y > GAME_HEIGHT then line.y = line.y - GAME_HEIGHT end end end end if movingPlatformIsOnscreen then Sounds.movingPlatform:play() else Sounds.movingPlatform:stop() end if platformPlayerHit ~= nil then player.time_since_jumped = 0.01 platformPlayerHit.time_since_hit = 0.01 player.y = platformPlayerHit.y - player.height if platformPlayerHit.type == "default" or platformPlayerHit.type == "moving" then player.y_velocity = JUMP_STANDARD_LAUNCH_VEL Sounds.jump:play() elseif platformPlayerHit.type == "spring" then player.y_velocity = JUMP_SPRING_LAUNCH_VEL Sounds.springJump:play() end end if player.time_since_jumped > PLAYER_JUMP_GLOW_DUR then player.time_since_jumped = -1.0 else player.time_since_jumped = player.time_since_jumped + dt end ensureGameIsPossible() updateScreenDistortionBasedUponProgress() player.xPrev = player.x player.yPrev = player.y total_time_elapsed = total_time_elapsed + dt end function love.draw() screen_effect(function() -- bg love.graphics.setColor(0.20, 0.20, 0.26, 1.0) love.graphics.rectangle("fill", 0, 0, GAME_WIDTH, GAME_HEIGHT) -- bg gridlines love.graphics.setLineWidth(4.0) love.graphics.setColor(0.1, 0.1, 0.1, 1.0) for i = 1, #bg_horiz_line_heights do local line = bg_horiz_line_heights[i] love.graphics.line(0, line.y, GAME_WIDTH, line.y) end for i = 1, NUM_GRID_COLS do local x = i/NUM_GRID_COLS * GAME_WIDTH love.graphics.line(x, 0, x, GAME_HEIGHT) end -- platforms for i = 1, #platforms do plat = platforms[i] -- platforms glow for a bit when hit local extra = 0.0 if plat.time_since_hit > 0.0 then extra = 0.3 * (1.0 - (plat.time_since_hit/PLATFORM_HIT_GLOW_DUR)) end if plat.type == "default" then love.graphics.setColor(0.4 + extra, 1.0, 0.4 + extra, 1.0) elseif plat.type == "moving" then love.graphics.setColor(0.4 + extra, 0.4 + extra, 1.0, 1.0) elseif plat.type == "spring" then love.graphics.setColor(1.0, 0.4 + extra, 0.4 + extra, 1.0) end love.graphics.rectangle("fill", plat.x, plat.y, plat.width, plat.height, plat.width/16, plat.height/16, 32) end -- player local playerExtra = 0.0 if player.time_since_jumped > 0.0 then playerExtra = 0.2 * (1.0 - (player.time_since_jumped/PLAYER_JUMP_GLOW_DUR)) end love.graphics.setColor(0.8 + playerExtra, 0.8 + playerExtra, 0.8 + playerExtra, 1.0) love.graphics.draw(avatarImage, player.x, player.y, 0, 0.056, 0.056, 0, 0) -- frame --love.graphics.setColor(1.0, 1.0, 1.0, 1.0) --love.graphics.rectangle("line", 0, 0, GAME_WIDTH, GAME_HEIGHT) -- score love.graphics.setColor(1, 1, 1, 1) love.graphics.print("$"..tostring(num_platforms_cleared), 16, 16, 0, 3, 3) end) -- end effect function end
-- Badges & Bandits: Connection Configuration (SERVER)
-- This helper module help retro-generate the clients layout from awful -- this is a giant hack and doesn't even always work and require upstream -- patches local setmetatable = setmetatable local ipairs,math = ipairs,math local awful = require("awful") local beautiful = require("beautiful") local color = require( "gears.color") local util = require( "collision.util" ) local shape = require( "gears.shape" ) local capi = { screen = screen, client=client } local module = {} local margin = 2 local radius = 4 -- Emulate a client using meta table magic local function gen_cls(c,results) local ret = setmetatable({},{__index = function(t,i) local ret2 = c[i] if type(ret2) == "function" then if i == "geometry" then return function(self,...) if #{...} > 0 then local geom = ({...})[1] -- Make a copy as the original will be changed results[c] = awful.util.table.join(({...})[1],{}) return geom end return c:geometry() end else return function(self,...) return ret2(c,...) end end end return ret2 end}) return ret end function module.get_geometry(tag) local cls,results,flt = {},setmetatable({},{__mode="k"}),{} local s = tag.screen local l = awful.tag.getproperty(tag,"layout") local focus,focus_wrap = capi.client.focus,nil for k,c in ipairs (tag:clients()) do -- Handle floating client separately if not c.minimized then local floating = c.floating if (not floating) and (not l == awful.layout.suit.floating) then cls[#cls+1] = gen_cls(c,results) if c == focus then focus_wrap = cls[#cls] end else flt[#flt+1] = c:geometry() end end end -- The magnifier layout require a focussed client -- there wont be any as that layout is not selected -- take one at random or (TODO) use stack data if not focus_wrap then focus_wrap = cls[1] end local param = { tag = tag, screen = 1, clients = cls, focus = focus_wrap, workarea = capi.screen[s or 1].workarea } l.arrange(param) return results,flt end function module.draw(tag,cr,width,height) local worked = false local l,l2 = module.get_geometry(tag) local s = tag.screen local scr_geo = capi.screen[s or 1].workarea local ratio = height/scr_geo.height local w_stretch = width/(scr_geo.width*ratio) local r,g,b = util.get_rgb( beautiful.collision_max_fg or beautiful.fg_normal ) local lshape = beautiful.collision_layout_shape or shape.rounded_rect cr:set_line_width(3) for c,ll in ipairs({l,l2}) do for c,geom in pairs(ll) do shape.transform(lshape) : translate(geom.x*ratio*w_stretch+margin, geom.y*ratio+margin) ( cr, geom.width*ratio*w_stretch-margin*2, geom.height*ratio-margin*2, radius ) cr:close_path() cr:set_source_rgba(r,g,b,0.7) cr:stroke_preserve() cr:set_source_rgba(r,g,b,0.2) cr:fill() -- Draw an icon in the region --TODO worked = true end end --TODO floating clients return worked end return module -- kate: space-indent on; indent-width 2; replace-tabs on;
local et = require("entity") local abcTool = et:new() -- TODO Not implemented
TOOL.Category = "Wire Extras/Input, Output" TOOL.Name = "Keycard" TOOL.Command = nil TOOL.ConfigName = "" TOOL.Tab = "Wire" if ( CLIENT ) then language.Add( "Tool.wire_keycard.name", "Keycard Tool (Wire)" ) language.Add( "Tool.wire_keycard.desc", "Create portable media for use with the wire system." ) language.Add( "Tool.wire_keycard.0", "Primary: Create/Update Spawner Secondary: Create/Update Reader" ) language.Add( "sboxlimit_wire_keycardspawners", "You've hit keycard spawner limit!" ) language.Add( "sboxlimit_wire_keycardreaders", "You've hit keycard reader limit!" ) language.Add( "undone_wirekeycardspawner", "Undone Wire Keycard Spawner" ) language.Add( "undone_wirekeycardreader", "Undone Wire Keycard Reader" ) language.Add( "WireKeycardTool_GeneralOpt", "General Options" ) language.Add( "WireKeycardTool_LockCode", "Lock Code Modifier" ) language.Add( "WireKeycardTool_ReaderOpt", "Reader Options" ) language.Add( "WireKeycardTool_ReadMode", "Read Mode" ) language.Add( "WireKeycardTool_LCMode", "Lock Code Matching" ) language.Add( "WireKeycardTool_BeamLength", "Range" ) CreateClientConVar("wire_keycardtool_lockcode", "0", true, true) CreateClientConVar("wire_keycardtool_beamlength", "100", true, true) CreateClientConVar("wire_keycardtool_readmode", "0", true, true) CreateClientConVar("wire_keycardtool_lcmode", "0", true, true) end if (SERVER) then CreateConVar('sbox_maxwire_keycardspawners', 10) CreateConVar('sbox_maxwire_keycardreaders', 10) end // TOOL.ClientConVar[ "z_only" ] = "1" TOOL.Model = "models/keycardspawner/keycardspawner.mdl" cleanup.Register( "wire_keycardspawners" ) cleanup.Register( "wire_keycardreaders" ) function TOOL:LeftClick( trace ) if trace.Entity && trace.Entity:IsPlayer() then return false end // If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end if (CLIENT) then return true end local ply = self:GetOwner() // local z_only = (self:GetClientNumber("z_only") ~= 0) // If we shot a wire_keycardspawner or wire_keycardreader do nothing if ( trace.Entity:IsValid() && trace.Entity.pl == ply ) then if (trace.Entity:GetClass() == "gmod_wire_keycardspawner") then // trace.Entity:Setup(z_only) // trace.Entity.z_only = z_only return true elseif (trace.Entity:GetClass() == "gmod_wire_keycardreader") then // Handle card reader stuff on right-click. return true end end if ( !self:GetSWEP():CheckLimit( "wire_keycardspawners" ) ) then return false end if (not util.IsValidModel(self.Model)) then return false end if (not util.IsValidProp(self.Model)) then return false end // Allow ragdolls to be used? local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 wire_keycardspawner = MakeWireKeycardSpawner( ply, Ang, trace.HitPos ) // TODO: pass configs as parameters to this fn (eg. z_only) local min = wire_keycardspawner:OBBMins() wire_keycardspawner:SetPos( trace.HitPos - trace.HitNormal * min.z ) local const = WireLib.Weld(wire_keycardspawner, trace.Entity, trace.PhysicsBone, true) undo.Create("WireKeycardSpawner") undo.AddEntity( wire_keycardspawner ) undo.AddEntity( const ) undo.SetPlayer( ply ) undo.Finish() ply:AddCleanup( "wire_keycardspawner", wire_keycardspawner ) ply:AddCleanup( "wire_keycardspawner", const ) return true end function TOOL:RightClick( trace ) if trace.Entity && trace.Entity:IsPlayer() then return false end // If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end if (CLIENT) then return true end local ply = self:GetOwner() // local z_only = (self:GetClientNumber("z_only") ~= 0) // If we shot a wire_keycardspawner or wire_keycardreader do nothing if ( trace.Entity:IsValid() && trace.Entity.pl == ply ) then if (trace.Entity:GetClass() == "gmod_wire_keycardspawner") then // Handle card spawner stuff on right-click. return true elseif (trace.Entity:GetClass() == "gmod_wire_keycardreader") then // trace.Entity:Setup(z_only) // trace.Entity.z_only = z_only return true end end if ( !self:GetSWEP():CheckLimit( "wire_keycardreaders" ) ) then return false end if (not util.IsValidModel(self.Model)) then return false end if (not util.IsValidProp(self.Model)) then return false end // Allow ragdolls to be used? local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 wire_keycardreader = MakeWireKeycardReader( ply, Ang, trace.HitPos ) // TODO: pass configs as parameters to this fn (eg. z_only) local min = wire_keycardreader:OBBMins() wire_keycardreader:SetPos( trace.HitPos - trace.HitNormal * min.z ) wire_keycardreader:SetRange(math.Max(0, ply:GetInfoNum("wire_keycardtool_beamlength", 100))) wire_keycardreader:SetReadMode(ply:GetInfoNum("wire_keycardtool_readmode", 0)) wire_keycardreader:SetLCMatchMode(ply:GetInfoNum("wire_keycardtool_lcmode", 0)) local const = WireLib.Weld(wire_keycardreader, trace.Entity, trace.PhysicsBone, true) undo.Create("WireKeycardReader") undo.AddEntity( wire_keycardreader ) undo.AddEntity( const ) undo.SetPlayer( ply ) undo.Finish() ply:AddCleanup( "wire_keycardreader", wire_keycardreader ) ply:AddCleanup( "wire_keycardreader", const ) return true end if (SERVER) then function MakeWireKeycardSpawner( pl, Ang, Pos ) if ( !pl:CheckLimit( "wire_keycardspawners" ) ) then return false end local wire_keycardspawner = ents.Create( "gmod_wire_keycardspawner" ) if (!wire_keycardspawner:IsValid()) then return false end wire_keycardspawner:SetAngles( Ang ) wire_keycardspawner:SetPos( Pos ) wire_keycardspawner:SetModel( Model("models/keycardspawner/keycardspawner.mdl") ) wire_keycardspawner:SetLockCode((pl:UserID() + 1) * 100 + math.Clamp(math.Round(pl:GetInfoNum("wire_keycardtool_lockcode", 0)), 0, 99)) wire_keycardspawner:Spawn() pl:AddCount( "wire_keycardspawners", wire_keycardspawner ) return wire_keycardspawner end function MakeWireKeycardReader( pl, Ang, Pos ) if ( !pl:CheckLimit( "wire_keycardreaders" ) ) then return false end local wire_keycardreader = ents.Create( "gmod_wire_keycardreader" ) if (!wire_keycardreader:IsValid()) then return false end wire_keycardreader:SetAngles( Ang ) wire_keycardreader:SetPos( Pos ) wire_keycardreader:SetModel( Model("models/jaanus/wiretool/wiretool_range.mdl") ) wire_keycardreader:SetLockCode((pl:UserID() + 1) * 100 + math.Clamp(math.Round(pl:GetInfoNum("wire_keycardtool_lockcode", 0)), 0, 99)) wire_keycardreader:SetRange(math.Max(0, pl:GetInfoNum("wire_keycardtool_beamlength", 100))) wire_keycardreader:SetReadMode(pl:GetInfoNum("wire_keycardtool_readmode", 0)) wire_keycardreader:SetLCMatchMode(pl:GetInfoNum("wire_keycardtool_lcmode", 0)) wire_keycardreader:Spawn() pl:AddCount( "wire_keycardreaders", wire_keycardreader ) return wire_keycardreader end // TODO: Examine this. Keycards need to be Duplicator compatible. // duplicator.RegisterEntityClass("gmod_wire_keycardspawner", MakeWireKeycardSpawner, "Ang", "Pos", "z_only", "nocollide", "Vel", "aVel", "frozen") // duplicator.RegisterEntityClass("gmod_wire_keycardreader", MakeWireKeycardReader, "Ang", "Pos", "z_only", "nocollide", "Vel", "aVel", "frozen") end function TOOL:UpdateGhostWireKeycardSpawner( ent, player ) if ( !ent ) then return end if ( !ent:IsValid() ) then return end local tr = util.GetPlayerTrace( player, player:GetAimVector() ) local trace = util.TraceLine( tr ) if (!trace.Hit) then return end if (trace.Entity && trace.Entity:GetClass() == "gmod_wire_keycardspawner" || trace.Entity:IsPlayer()) then ent:SetNoDraw( true ) return end local Ang = trace.HitNormal:Angle() Ang.pitch = Ang.pitch + 90 local min = ent:OBBMins() ent:SetPos( trace.HitPos - trace.HitNormal * min.z ) ent:SetAngles( Ang ) ent:SetNoDraw( false ) end function TOOL:Think() if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self.Model ) then self:MakeGhostEntity( self.Model, Vector(0,0,0), Angle(0,0,0) ) end self:UpdateGhostWireKeycardSpawner( self.GhostEntity, self:GetOwner() ) end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool.wire_keycard.name", Description = "#Tool.wire_keycard.desc" }) panel:AddControl("Header", { Text = "#WireKeycardTool_GeneralOpt" } ) panel:AddControl("Slider", { Label = "#WireKeycardTool_LockCode", Description = "", Type = "Integer", Min = "0", Max = "99", Command = "wire_keycardtool_lockcode"}) panel:AddControl("Header", { Text = "#WireKeycardTool_ReaderOpt" } ) local combobox = {} combobox.Label = "#WireKeycardTool_ReadMode" combobox.MenuButton = 0 combobox.Options = {} combobox.Options["Read with a beam"] = {wire_keycardtool_readmode = 0} combobox.Options["Read nearest keycard"] = {wire_keycardtool_readmode = 1} panel:AddControl("ComboBox", combobox) local combobox = {} combobox.Label = "#WireKeycardTool_LCMode" combobox.MenuButton = 0 combobox.Options = {} combobox.Options["Inclusive (read even if lock code is different)"] = {wire_keycardtool_lcmode = 0} combobox.Options["Exclusive (ignore if lock code is different)"] = {wire_keycardtool_lcmode = 1} panel:AddControl("ComboBox", combobox) panel:AddControl("Slider", { Label = "#WireKeycardTool_BeamLength", Description = "", Type = "Float", Min = "1", Max = "1000", Command = "wire_keycardtool_beamlength"}) end
------------------------------------------------------------------ -- -- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Copyright (C) 2017-2019 Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Licensed according to the included 'LICENSE' document -- -- This file is part of lua-lluv-qless library. -- ------------------------------------------------------------------ local ut = require "lluv.utils" local super = require "lluv.qless.utils".super local QLessErrorClassesNames = {} ------------------------------------------------------------------------------- local QLessError = ut.class() do function QLessError:__init(name, msg, ext, no) self._name = name or 'user' self._no = no or -1 self._msg = msg self._ext = ext return self end function QLessError:cat() return 'QLESS' end function QLessError:name() return self._name end function QLessError:no() return self._no end function QLessError:msg() return self._msg end function QLessError:ext() return self._ext end function QLessError:__tostring() local name = QLessErrorClassesNames[self] if name then return "QLess::Error::" .. name .. " class" end local err = string.format("[%s][%s] %s (%d)", self:cat(), self:name(), self:msg(), self:no() ) if self:ext() then err = string.format("%s - %s", err, self:ext()) end return err end function QLessError:__eq(lhs) if QLessErrorClassesNames[self] then return rawequal(self, lhs) end return getmetatable(lhs) == getmetatable(self) and self:name() == lhs:name() and self:msg() == lhs:msg() end end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- local QLessLuaScriptError = ut.class(QLessError) do local super = function(...) return super(QLessLuaScriptError, ...) end -- @classmethod local pat = 'user_script:(%d+):%s*(.-)%s*$' function QLessLuaScriptError.match(s) local l, e = string.match(s, pat) if e then local _, e2 = string.match(e, pat) if e2 then e = e2 end return QLessLuaScriptError.new(e, 'Line: ' .. l) end end function QLessLuaScriptError:__init(msg, ext) return super(self, '__init', 'LuaScript', msg, ext, -1) end function QLessLuaScriptError:__tostring() return super(self, '__tostring') end function QLessLuaScriptError:__eq(lhs) return super(self, '__eq', lhs) end end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- local QLessLockLostError = ut.class(QLessError) do local super = function(...) return super(QLessLockLostError, ...) end local single function QLessLockLostError:__init(jid, msg) return super(self, '__init', 'LockLost', msg or 'Lost lock for job', jid, -1) end function QLessLockLostError:__tostring() return super(self, '__tostring') end function QLessLockLostError:__eq(lhs) return super(self, '__eq', lhs) end end ------------------------------------------------------------------------------- local function is(klass, err) return err and (getmetatable(err) == klass) end QLessErrorClassesNames = { [QLessError] = 'General'; [QLessLuaScriptError] = 'LuaScript'; [QLessLockLostError] = 'LockLost'; } return { is = is; General = QLessError; LuaScript = QLessLuaScriptError; LockLost = QLessLockLostError; }
local Class, Table, getters, setters, newFunc = _Inherit(Instance, "Workspace") function setters:Gravity(value) Check("Set(Gravity)", "number", value, "value") self:Set("Gravity", value) end function setters:FallenPartsDestroyHeight(value) Check("Set(FallenPartsDestroyHeight)", "number", value, "value") self:Set("FallenPartsDestroyHeight", value) end function setters:CurrentCamera(instance) local currentCamera = rawget(self, "_CurrentCamera") if currentCamera == instance then --setting to current value return end if instance == nil then instance = Instance.new("Camera") instance.Parent = self else Check("Set(CurrentCamera)", "table", instance, "instance") assert(instance:IsA("Camera"), Blox2D._ErrorMessages.__newindex:format( self, "CurrentCamera", tostring(instance), type(instance))) assert(rawget(instance, "_Parent") == self, "CurrentCamera must be a child of workspace") end self:Set("CurrentCamera", instance) end function Table:Destroy() error(Blox2D._ErrorMessages.CantCollonFunction:format("Destroy", tostring(self))) end Class.new = function () local instance = newFunc() rawset(instance, "_Gravity", 9.8) rawset(instance, "_FallenPartsDestroyHeight", -1000) instance.ChildRemoved:Connect(function(child) if child == rawget(instance, "_CurrentCamera") then instance.CurrentCamera = nil end end) return instance end return Class
function onCreate() -- background shit makeLuaSprite('comicstrip', 'comicstrip', -600, -300); setScrollFactor('comicstrip', 0.9, 0.9); addLuaSprite('comicstrip', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
--region CRect.lua --Author : jefflwq --Date : 2016/04/24 --说明 : Rect类 --endregion using "Joop" namespace "System.Drawing" { class "CRect" { -- 此 Rect 的 Location 。 Location = false, -- 此 Rect 的 Size 。 Size = false, -- 初始化 Rect 类的新实例。 CRect = function(self, left, top, right, bottom) self.Location = CPoint() self.Size = CSize() self:SetLTRB(left, top, right, bottom) end, SetLTRB = function(self, left, top, right, bottom) self.Location.X = left or 0 self.Location.Y = top or 0 self.Size.Width = right and (right - (left or 0)) or 0 self.Size.Height = bottom and (bottom - (top or 0)) or 0 end, Empty = function(self) self.Location:Empty() self.Size:Empty() end, GetLTRB = function(self) return self:GetLeft(), self:GetTop(), self:GetRight(), self:GetBottom() end, -- 获取一个值,该值指示此 Rect 是否为空。 -- 返回结果: -- 如果 Location 和 Size 均为 Empty,则为 true;否则为 false。 IsEmpty = function(self) return self.Location:IsEmpty() and self.Size:IsEmpty() end, -- 指定此 Rect 是否与指定 rect 相同。 Equals = function(self, rect) return self.Location:Equals(rect.Location) and self.Size:Equals(rect.Size) end, -- 克隆此 Rect。 Clone = function(self) return CRect(self.Location:Clone(), self.Size:Clone()) end, GetTop = function(self) return math.min(self.Location.Y, self.Location.Y + self.Size.Height) end, GetBottom = function(self) return math.max(self.Location.Y, self.Location.Y + self.Size.Height) end, GetLeft = function(self) return math.min(self.Location.X, self.Location.X + self.Size.Width) end, GetRight = function(self) return math.max(self.Location.X, self.Location.X + self.Size.Width) end, -- 将此 Rect 加上指定的 Rect。 Union = function(self, rect) local left = math.min(self:GetLeft(), rect:GetLeft()) local right = math.max(self:GetRight(), rect:GetRight()) local top = math.min(self:GetTop(), rect:GetTop()) local bottom = math.max(self:GetBottom(), rect:GetBottom()) self:SetLTRB(left, top, right, bottom) end, UnionPoint = function(self, point) local left = math.min(self:GetLeft(), point.X) local right = math.max(self:GetRight(), point.X) local top = math.min(self:GetTop(), point.Y) local bottom = math.max(self:GetBottom(), point.Y) self:SetLTRB(left, top, right, bottom) end, UnionXY = function(self, x, y) local left = math.min(self:GetLeft(), x) local right = math.max(self:GetRight(), x) local top = math.min(self:GetTop(), y) local bottom = math.max(self:GetBottom(), y) self:SetLTRB(left, top, right, bottom) end, -- 将此 Rect 与指定的 Rect 取交集。 Intersect = function(self, rect) local left = math.max(self:GetLeft(), rect:GetLeft()) local right = math.min(self:GetRight(), rect:GetRight()) local top = math.max(self:GetTop(), rect:GetTop()) local bottom = math.min(self:GetBottom(), rect:GetBottom()) if left <= right and top <= bottom then self:SetLTRB(left, top, right, bottom) return true else self:Empty() end end, -- 判断2个Rect是否相交 IntersectsWith = function(self, rect) local left = math.max(self:GetLeft(), rect:GetLeft()) local right = math.min(self:GetRight(), rect:GetRight()) local top = math.max(self:GetTop(), rect:GetTop()) local bottom = math.min(self:GetBottom(), rect:GetBottom()) return left <= right and top <= bottom end, Contains = function(self, rect) return self:GetLeft() <= rect:GetLeft() and self:GetRight() >= rect:GetRight() and self:GetTop() <= rect:GetTop() and self:GetBottom() >= rect:GetBottom() end, ContainsPoint = function(self, point) return self:GetLeft() <= point.x and self:GetRight() >= point.x and self:GetTop() <= point.y and self:GetBottom() >= point.y end, ContainsXY = function(self, x, y) return self:GetLeft() <= x and self:GetRight() >= x and self:GetTop() <= y and self:GetBottom() >= y end, -- 将此 Rect 转换为可读字符串。 ToString = function(self) return self.Location:ToString() .. ", " .. self.Size:ToString() end, } }
--戦華の孟-曹徳 --Scripted by nekrozar function c101012020.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(101012020,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e1:SetCode(EVENT_CUSTOM+101012020) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,101012020) e1:SetCondition(c101012020.spcon1) e1:SetCost(c101012020.spcost1) e1:SetTarget(c101012020.sptg1) e1:SetOperation(c101012020.spop1) c:RegisterEffect(e1) --cannot be target local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e2:SetRange(LOCATION_MZONE) e2:SetCondition(c101012020.tgcon) e2:SetValue(aux.tgoval) c:RegisterEffect(e2) --indestructable local e3=e2:Clone() e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e3:SetValue(aux.indoval) c:RegisterEffect(e3) --special summon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(101012020,1)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e4:SetCode(EVENT_BATTLE_DESTROYING) e4:SetCountLimit(1,101012120) e4:SetCondition(aux.bdogcon) e4:SetTarget(c101012020.sptg2) e4:SetOperation(c101012020.spop2) c:RegisterEffect(e4) if not c101012020.global_check then c101012020.global_check=true local ge1=Effect.CreateEffect(c) ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) ge1:SetCode(EVENT_DESTROYED) ge1:SetCondition(c101012020.regcon) ge1:SetOperation(c101012020.regop) Duel.RegisterEffect(ge1,0) end end function c101012020.regfilter(c,tp) return c:IsReason(REASON_BATTLE+REASON_EFFECT) and c:GetPreviousControler()==tp and c:IsPreviousLocation(LOCATION_ONFIELD) end function c101012020.regcon(e,tp,eg,ep,ev,re,r,rp) local v=0 if eg:IsExists(c101012020.regfilter,1,nil,0) then v=v+1 end if eg:IsExists(c101012020.regfilter,1,nil,1) then v=v+2 end if v==0 then return false end e:SetLabel(({0,1,PLAYER_ALL})[v]) return true end function c101012020.regop(e,tp,eg,ep,ev,re,r,rp) Duel.RaiseEvent(eg,EVENT_CUSTOM+101012020,re,r,rp,ep,e:GetLabel()) end function c101012020.spcon1(e,tp,eg,ep,ev,re,r,rp) return ev==1-tp or ev==PLAYER_ALL end function c101012020.costfilter(c,tp) return c:IsAbleToGraveAsCost() and Duel.GetMZoneCount(tp,c)>0 end function c101012020.spcost1(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return Duel.IsExistingMatchingCard(c101012020.costfilter,tp,LOCATION_ONFIELD+LOCATION_HAND,0,1,c,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c101012020.costfilter,tp,LOCATION_ONFIELD+LOCATION_HAND,0,1,1,c,tp) Duel.SendtoGrave(g,REASON_COST) end function c101012020.sptg1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c101012020.spop1(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end end function c101012020.cfilter(c) return c:IsFaceup() and c:IsSetCard(0x137) end function c101012020.tgcon(e) return Duel.IsExistingMatchingCard(c101012020.cfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,e:GetHandler()) end function c101012020.sptg2(e,tp,eg,ep,ev,re,r,rp,chk) local bc=e:GetHandler():GetBattleTarget() if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and bc:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE) end Duel.SetTargetCard(bc) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,bc,1,0,0) end function c101012020.spop2(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE) end end
--[=[ Copyright (C) 2013-2014 Richard Hundt and contributors. See Copyright Notice in shine ]=] local util = require('shine.lang.util') local tvm = require("tvm") local DEBUG = true local Op = { } setmetatable(Op, { __call = function(Op, ...) local v = ... local t = type(v) if t == 'string' then if v == '...' then return '!vararg' end return tvm.quote(v) elseif v == true then return '!true' elseif v == false then return '!false' elseif v == nil then if select('#', ...) == 0 then return setmetatable({ }, Op) else return '!nil' end elseif t == 'table' then return setmetatable(v, Op) else return tostring(v) end end }) local wantnl = { ['!line'] = true, ['!do'] = true, } function Op.__tostring(o) local t = { } if o[0] then t[#t+1] = '0: '..tostring(o[0]) end for i = 1, #o do t[#t+1] = tostring(o[i]) end for k, v in pairs(o) do if type(k) ~= 'number' or k < 0 or k > #o then t[#t+1] = tostring(k)..': '..tostring(v) end end return (wantnl[o[1]] and "\n(" or "(")..table.concat(t, ' ')..')' end local OpList = { } setmetatable(OpList, { __call = function(mt, t) return setmetatable(t or { }, mt) end }) function OpList.__tostring(o) local t = { } for i=1, #o do t[#t+1] = tostring(o[i]) end return table.concat(t, " ") end local OpChunk = { } setmetatable(OpChunk, { __call = function(mt, t) return setmetatable(t or { }, mt) end }) function OpChunk.__tostring(o) local t = { } for i=1, #o do t[#t+1] = tostring(o[i]) end return table.concat(t, "") end local Scope = { } Scope.__index = Scope function Scope.new(outer) local self = { outer = outer; entries = { }; hoist = { }; block = { }; macro = { }; } if outer then setmetatable(self.macro, { __index = outer.macro }) else local function reify(ctx, expr) if expr.type == 'FunctionDeclaration' and expr.expression then return ctx:oplist{ctx:op(tostring(ctx:get(expr.body)))} end return ctx:oplist{ctx:op(tostring(ctx:get(expr)))} end self.macro['reify!'] = reify end return setmetatable(self, Scope) end function Scope:define(name, info) info.name = name self.entries[name] = info end function Scope:lookup(name) if self.entries[name] then return self.entries[name] elseif self.outer then return self.outer:lookup(name) else return nil end end local Context = { } Context.__index = Context function Context.new(name, opts) local self = { scope = Scope.new(); line = 1; name = name or "(eval)"; undef = { }; opts = opts or { }; } return setmetatable(self, Context) end function Context:abort(mesg, line) mesg = string.format("shine: %s:%s: %s\n", self.name, line or self.line, mesg) if DEBUG then error(mesg) else io.stderr:write(mesg) os.exit(1) end end function Context:enter(type) local topline if type == "function" or type == "module" then topline = self.line else topline = self.scope.topline end self.scope.type = type self.scope = Scope.new(self.scope) self.scope.topline = topline if type == "function" then self.scope.level = (self.scope.outer.level or 0) + 1 else self.scope.level = self.scope.outer.level or 1 end return self.scope.block end function Context:leave(block) block = block or self.scope.hoist -- propagate hoisted statements to outer scope self:unhoist(block) self.scope = self.scope.outer end function Context:in_module() return self.scope.outer and self.scope.outer.type == "module" end function Context:hoist(stmt) self.scope.hoist[#self.scope.hoist + 1] = stmt end function Context:unhoist(block) for i=#self.scope.hoist, 1, -1 do table.insert(block, 1, self.scope.hoist[i]) end self.scope.hoist = { } end function Context:push(stmt) local scope = self.scope.outer or self.scope scope.block[#scope.block + 1] = stmt end function Context:shift(into) for i=1, #self.scope.block do into[#into + 1] = self.scope.block[i] end self.scope.block = { } end function Context:define(name, info, guard) info = info or { line = self.line } if guard then info.guard = guard end self.scope:define(name, info) for i=#self.undef, 1, -1 do local u = self.undef[i] if u.name == name and u.line < self.line then if u.from.level <= self.scope.level then self:abort(string.format("%q used before defined", u.name), u.line) else -- XXX: scan up table.remove(self.undef, i) end end end return info end function Context:lookup(name) return self.scope:lookup(name) end function Context:resolve(name) if not self.opts.eval then self.undef[#self.undef + 1] = { name = name, line = self.line, from = self.scope } end end function Context:close() for i=1, #self.undef do local u = self.undef[i] self:abort(string.format("%q used but not defined", u.name), u.line) end end function Context:op(...) return Op(...) end function Context:opchunk(...) return OpChunk(...) end function Context:oplist(...) return OpList(...) end function Context:reify(code) local parser = require('shine.lang.parser') local translator = require('shine.lang.translator') local srctree = parser.parse(code, self.name, self.line) return translator.translate(srctree, self.name, { eval = true }) end function Context:sync(node) if node.line then self.line = node.line end return self.line end local match = { } local globals = { 'Nil','Number','Boolean', 'String', 'Function', 'Coroutine', 'Range', 'UserData', 'Table', 'Array', 'Error', 'Module', 'Class', 'Object', 'Grammar', 'Pattern', 'ArrayPattern', 'TablePattern', 'ApplyPattern', '__magic__', 'yield', 'take', 'typeof', 'null', 'warn', 'eval', 'any', 'all', '__FILE__', '__LINE__', '_M', '_PACKAGE', '_NAME', 'Meta', 'Any', 'All' } for k,v in pairs(_G) do globals[#globals + 1] = k end local magic = { 'null', '__range__', '__spread__', '__match__', '__extract__', '__each__', '__var__', '__in__', '__is__', '__as__', '__lshift__', '__rshift__', '__arshift__', '__bor__', '__bxor__', '__band__', '__bnot__' } function match:Chunk(node, opts) local chunk = { } for i=1, #globals do self.ctx:define(globals[i]) end self.ctx:enter("module") -- import magic from core chunk[#chunk + 1] = Op{'!line', Op("@"..self.ctx.name), Op(1) } if not self.ctx.opts.eval then chunk[#chunk + 1] = OpChunk{ Op{'!define', '__magic__', Op{'!index', Op{'!call1', 'require', Op "core" }, Op"__magic__" } }, Op{'!call', Op{'!index', '_G', Op"module"}, '!vararg', Op{'!index', '__magic__', Op"environ" } } } --[[ local sym = { } for i = 1, #magic do sym[#sym + 1] = magic[i] end chunk[#chunk + 1] = Op{'!define', Op(sym), Op(sym)} --]] end for i=1, #node.body do local line = self.ctx:sync(node.body[i]) local stmt = self:get(node.body[i]) self.ctx:shift(chunk) chunk[#chunk + 1] = OpList{Op{'!line', line}, stmt} end local seen_export = self.ctx.seen_export if seen_export then self.ctx:hoist(Op{'!define', 'export', Op{ }}) end self.ctx:leave(chunk) if seen_export then chunk[#chunk + 1] = Op{'!return', 'export'} end return OpChunk(chunk) end local translate local function import_macro_func(import, package_name, func_name) local errs = string.format( "imported macro body for '%s' cannot be resolved", name) assert(type(package_name) == 'string', errs) package_name = util.unquote(package_name) local func = import(package_name, func_name) assert(func ~= nil, errs) return func end local function iterate_imported_symbols(import_stmt_node) local function iterator(names_num, i) if i >= names_num then return end i = i + 1 local current_name = import_stmt_node.names[i] local imported_symbol_alias = current_name[1].name local imported_symbol if current_name[2] then imported_symbol = current_name[2].name else imported_symbol = imported_symbol_alias end return i, imported_symbol_alias, imported_symbol end return iterator, #import_stmt_node.names, 0 end function match:ImportStatement(node) if node.macro then local import = require("core").__magic__.import local package_name = self:get(node.from) for i, macro_name, func_name in iterate_imported_symbols(node) do local macro_func = import_macro_func(import, package_name, func_name) self.ctx.scope.macro[macro_name] = macro_func end return OpChunk{ } end local args = OpList{ self:get(node.from) } local syms = OpList{ } for i=1, #node.names do local n = node.names[i] self.ctx:define(n[1].name, { type = "import", node = node }) if n[2] then args[#args + 1] = Op(n[2].name) else args[#args + 1] = Op(n[1].name) end syms[#syms + 1] = n[1].name end if self.ctx.opts.eval then return Op{'!massign', Op{ syms }, Op{ Op{'!call', 'import', args } } } else return Op{'!define', Op{ syms }, Op{ Op{'!call', 'import', args } } } end end function match:ExportStatement(node) local ops = { } self.ctx.seen_export = true for i=1, #node.names do local expr = Op{'!index', 'export', Op(self:get(node.names[i])) } ops[#ops + 1] = Op{'!assign', expr, self:get(node.names[i]) } end return OpChunk(ops) end function match:Literal(node) return Op(node.value) end function match:Identifier(node) if node.name == '__FILE__' then return Op(self.ctx.name) end if node.name == '__LINE__' then return Op(self.ctx.line) end if node.check then local info = self.ctx:lookup(node.name) if info == nil then self.ctx:resolve(node.name) end end return node.name end function match:MacroDeclaration(node) local eval = self.ctx.opts.eval self.ctx.opts.eval = true local name = node.name.name local core = require("core") local func if node.head == '=' then local nref = node.body.name local info = self.ctx:lookup(nref) if info.type == 'import' then local from = self:get(info.node.from) local function import(package_name, func_name) return require(package_name)[func_name] end for i, alias, func_name in iterate_imported_symbols(info.node) do if alias == nref then func = import_macro_func(import, from, func_name) break end end elseif info.type == 'function' then local defn = self:get(info.node) local wrap = OpChunk{ defn, Op{'!return', nref} } wrap = assert(tvm.load(tostring(wrap))) setfenv(wrap, core.__magic__.environ({ })) func = wrap() end else local head = self:list(node.head) local body = self:list(node.body) local wrap = OpChunk{ Op{'!return', Op{'!lambda', Op{ OpList(head) }, OpChunk(body) } } } wrap = assert(tvm.load(tostring(wrap))) setfenv(wrap, core.__magic__.environ({ })) func = wrap() end self.ctx.opts.eval = eval self.ctx.scope.macro[name] = func return OpChunk{ } end local function extract_bindings(node, ident) local list = { } local queue = { node } while #queue > 0 do local n = table.remove(queue) if n.type == 'ArrayPattern' then for i=#n.elements, 1, -1 do queue[#queue + 1] = n.elements[i] end elseif n.type == 'TablePattern' then for i=#n.entries, 1, -1 do queue[#queue + 1] = n.entries[i].value end elseif n.type == 'ApplyPattern' then for i=#n.arguments, 1, -1 do queue[#queue + 1] = n.arguments[i] end elseif n.type == 'Identifier' then list[#list + 1] = n elseif n.type == 'MemberExpression' then if ident then queue[#queue + 1] = n.object else list[#list + 1] = n end else assert(n.type == 'Literal') end end return list end function match:LocalDeclaration(node) node.is_local = true local decl = { } for i=1, #node.names do local list = extract_bindings(node.names[i]) for i=1, #list do if list[i].type == 'Identifier' then decl[#decl + 1] = list[i].name end end end node.left = node.names node.right = node.inits local frag = OpChunk{ match.AssignmentExpression(self, node) } for i=#node.decorators, 1, -1 do local deco = node.decorators[i] frag[#frag + 1] = Op{'!massign', Op{decl}, Op{Op{'!call', self:get(deco.term), OpList(decl) }} } end return frag end function match:AssignmentExpression(node) local body = { } local decl = { } local init = { } local dest = { } local chks = { } local exps if node.right then exps = self:list(node.right) else exps = Op{Op(nil)} end for i=1, #node.left do local n = node.left[i] local t = n.type if t == 'TablePattern' or t == 'ArrayPattern' or t == 'ApplyPattern' then -- destructuring local temp = util.genid() self.ctx:define(temp) local left = { } n.temp = temp n.left = left init[#init + 1] = temp decl[#decl + 1] = temp dest[#dest + 1] = n -- define new variables local bind = extract_bindings(n) for i=1, #bind do local n = bind[i] if n.type == 'Identifier' then if node.is_local or n.guard or not self.ctx:lookup(n.name) then local guard if n.guard then guard = util.genid() body[#body + 1] = Op{'!let', guard, self:get(n.guard)} end self.ctx:define(n.name, nil, guard) if not self.ctx.opts.eval then decl[#decl + 1] = n.name end end if self.ctx:lookup(n.name).guard then chks[#chks + 1] = self.ctx:lookup(n.name) end left[#left + 1] = n.name elseif n.type == 'MemberExpression' then left[#left + 1] = self:get(n) end end else -- simple case if n.type == 'Identifier' then if node.is_local or n.guard or not self.ctx:lookup(n.name) then local guard if n.guard then guard = util.genid() body[#body + 1] = Op{'!let', guard, self:get(n.guard)} end self.ctx:define(n.name, nil, guard) if not self.ctx.opts.eval then decl[#decl + 1] = n.name end end if self.ctx:lookup(n.name).guard then chks[#chks + 1] = self.ctx:lookup(n.name) end end init[#init + 1] = self:get(n) end end -- declare locals if #decl > 0 then if #decl == 0 then body[#body + 1] = Op{'!define', Op(decl)} else body[#body + 1] = Op{'!define', Op(decl), Op{Op(nil)}} end end for i=1, #dest do local patt = util.genid() body[#body + 1] = Op{'!define', Op{ patt }, Op{ self:get(dest[i])} } dest[i].patt = patt end body[#body + 1] = Op{'!massign', Op(init), Op(exps) } -- destructure for i=1, #dest do body[#body + 1] = Op{'!massign', Op(dest[i].left), Op{ Op{'!call', '__extract__', dest[i].patt, dest[i].temp } } } end for i=1, #chks do body[#body + 1] = Op{'!call', '__check__', Op(chks[i].name), chks[i].name, chks[i].guard } end return OpChunk(body) end function match:ArrayPattern(node) local list = { } for i=1, #node.elements do local n = node.elements[i] if n.type == 'Identifier' or n.type == 'MemberExpression' then list[#list + 1] = '__var__' else list[#list + 1] = self:get(n) end end return Op{'!call', 'ArrayPattern', unpack(list) } end function match:TablePattern(node) local idx = 1 local keys = { } local desc = { } for i=1, #node.entries do local n = node.entries[i] local key, val if n.name then key = Op(n.name.name) elseif n.expr then key = self:get(n.expr) else -- array part key = Op(idx) idx = idx + 1 end local nv = n.value if nv.type == 'Identifier' or nv.type == 'MemberExpression' then val = '__var__' else val = self:get(nv) end keys[#keys + 1] = key desc[key] = val end keys = Op(keys) desc = Op(desc) local args = { keys, desc } if node.coerce then args[#args + 1] = self:get(node.coerce) end return Op{'!call', 'TablePattern', unpack(args)} end function match:ApplyPattern(node) local args = { self:get(node.callee) } for i=1, #node.arguments do local n = node.arguments[i] if n.type == 'Identifier' or n.type == 'MemberExpression' then args[#args + 1] = '__var__' else args[#args + 1] = self:get(n) end end return Op{'!call', 'ApplyPattern', unpack(args)} end function match:InExpression(node) local names = { } for i=1, #node.names do names[#names + 1] = Op(node.names[i].name) end return Op{ '!call', '__in__', Op(names), self:get(node.expression) } end function match:UpdateExpression(node) local oper = string.sub(node.operator, 1, -2) local expr if oper == 'or' or oper == 'and' then expr = match.LogicalExpression(self, { operator = oper, left = node.left, right = node.right }) else expr = match.BinaryExpression(self, { operator = oper, left = node.left, right = node.right }) end return Op{'!assign', self:get(node.left), expr} end function match:MemberExpression(node) if node.computed then return Op{'!index', self:get(node.object), self:get(node.property)} else return Op{'!index', self:get(node.object), Op(self:get(node.property))} end end function match:SelfExpression(node) return 'self' end function match:SuperExpression(node) return 'super' end function match:ThrowStatement(node) return Op{'!call', 'throw', self:get(node.argument)} end function match:ReturnStatement(node) local args = self:list(node.arguments) if self.retsig then return Op{'!do', Op{'!assign', self.retsig, '!true' }, Op{'!assign', self.retval, #args > 0 and OpList(args) or '!nil'}, Op{'!return', self.retval }, } end return Op{'!return', OpList(args)} end function match:IfStatement(node) local test, cons, altn = self:get(node.test), nil, nil if node.consequent then self.ctx:enter() cons = self:get(node.consequent) self.ctx:leave() end if node.alternate then self.ctx:enter() altn = self:get(node.alternate) self.ctx:leave() end return Op{'!if', test, Op{'!do', cons}, Op{'!do', altn } } end function match:GivenStatement(node) local body = { } local disc = util.genid() body[#body + 1] = Op{'!define', disc, self:get(node.discriminant) } local labels = { } for i=1, #node.cases do labels[#labels + 1] = util.genid() end self.ctx:enter() for i=1, #node.cases do local n = node.cases[i] if n.test then local t = n.test.type local case = { } if t == 'ArrayPattern' or t == 'TablePattern' or t == 'ApplyPattern' then local cons = { } -- for storing the template local temp = util.genid() self.ctx:define(temp) case[#case + 1] = Op{'!define', temp, self:get(n.test) } cons[#cons + 1] = Op{'!if', Op{'!not', Op{'!call', '__match__', temp, disc } }, Op{'!goto', labels[i] } } self.ctx:enter() -- consequent local into = { } local bind = extract_bindings(n.test) local vars = { } local chks = { } for i=1, #bind do local n = bind[i] if n.type == 'Identifier' then local guard if n.guard then guard = util.genid() case[#case + 1] = Op{'!let', guard, self:get(n.guard)} end self.ctx:define(n.name, nil, guard) if guard then chks[#chks + 1] = self.ctx:lookup(n.name) end vars[#vars + 1] = n.name end bind[i] = self:get(n) end if #vars > 0 then case[#case + 1] = Op{'!define', Op(vars), Op{ Op(nil) } } end cons[#cons + 1] = Op{'!massign', Op(bind), Op{ Op{'!call', '__extract__', temp, disc } } } for i=1, #chks do cons[#cons + 1] = Op{'!call', '__check__', Op(chks[i].name), chks[i].name, chks[i].guard } end if n.guard then cons[#cons + 1] = Op{'!if', Op{'!not', self:get(n.guard) }, Op{'!goto', labels[i] } } end cons[#cons + 1] = self:get(n.consequent) self.ctx:leave() case[#case + 1] = Op{'!do', OpChunk(cons)} case[#case + 1] = Op{'!goto', labels[#labels] } else case[#case + 1] = Op{'!if', Op{'!not', Op{'!call', '__match__', self:get(n.test), disc } }, Op{'!goto', labels[i] } } if n.guard then case[#case + 1] = Op{'!if', Op{'!not', self:get(n.guard) }, Op{'!goto', labels[i] } } end case[#case + 1] = self:get(n.consequent) case[#case + 1] = Op{'!goto', labels[#labels] } end body[#body + 1] = Op{'!do', OpChunk(case) } else -- else clause body[#body + 1] = Op{'!do', self:get(n.consequent) } end body[#body + 1] = Op{'!label', labels[i]} end self.ctx:leave(body) return Op{'!do', OpChunk(body) } end function match:TryStatement(node) local oldret = self.retsig local oldval = self.retval local oldbrk = self.brksig local oldcnt = self.cntsig self.retsig = util.genid() self.retval = util.genid() self.brksig = util.genid() self.cntsig = util.genid() local try = Op{'!lambda', Op{ }, self:get(node.body)} local finally if node.finalizer then finally = Op{'!lambda', Op{ }, self:get(node.finalizer)} end local exit = util.genid() local clauses = { } for i=#node.guardedHandlers, 1, -1 do local clause = node.guardedHandlers[i] self.ctx:define(clause.param.name) local cons = self:get(clause.body) local head = Op{'!define', self:get(clause.param), '!vararg'} cons[#cons + 1] = Op{'!goto', exit } clauses[#clauses + 1] = Op{'!do', head, Op{'!if', self:get(clause.guard), Op{'!do', OpChunk(cons)}} } end if node.handler then local clause = node.handler self.ctx:define(clause.param.name) local cons = self:get(clause.body) local head = Op{'!define', self:get(clause.param), '!vararg'} cons[#cons + 1] = Op{'!goto', exit} clauses[#clauses + 1] = Op{'!do', head, Op{'!do', OpChunk(cons)}} end clauses[#clauses + 1] = Op{'!label', exit } local catch = Op{'!lambda', Op{'!vararg'}, OpChunk(clauses)} local expr = Op{'!call', 'try', try, catch, finally } local temp = self.retval local rets = self.retsig local brks = self.brksig local cnts = self.cntsig self.retsig = oldret self.retval = oldval self.brksig = oldbrk self.cntsig = oldcnt local frag = Op{'!do', Op{'!define', Op{ rets, brks, cnts }, Op{ '!false', '!false', '!false' } }, Op{'!define', temp, Op(nil) }, Op(expr), Op{'!if', rets, Op{'!return', temp } } } if self.loop then frag[#frag + 1] = Op{'!if', cnts, Op{'!goto', self.loop} } frag[#frag + 1] = Op{'!if', brks, Op{'!break'} } end return frag end function match:LabelStatement(node) return Op{'!label', node.label.name } end function match:GotoStatement(node) return Op{'!goto', node.label.name } end function match:BreakStatement(node) if self.brksig then return OpChunk{ Op{'!assign', self.brksig, '!true'}, Op{'!return'} } end return Op{'!break'} end function match:ContinueStatement(node) if not self.loop then self.ctx:fail("no loop to continue") end if self.cntsig then return OpChunk{ Op{'!assign', self.cntsig, '!true'}, Op{'!return'} } end return Op{'!goto', self.loop} end function match:LogicalExpression(node) local op = node.operator if op == 'and' then return Op{'!and', self:get(node.left), self:get(node.right) } elseif op == 'or' then return Op{'!or', self:get(node.left), self:get(node.right) } else assert(false, "Unhandled operator "..op.." in logical expression") end end local bitop = { [">>"] = '__rshift__', [">>>"] = '__arshift__', ["<<"] = '__lshift__', ["|"] = '__bor__', ["&"] = '__band__', ["^"] = '__bxor__', } local binop = { ['+'] = '!add', ['-'] = '!sub', ['*'] = '!mul', ['/'] = '!div', ['%'] = '!mod', ['**'] = '!pow', ['~'] = '!concat', ['=='] = '!eq', ['!='] = '!ne', ['>='] = '!ge', ['<='] = '!le', ['>'] = '!gt', ['<'] = '!lt', } function match:BinaryExpression(node) local o = node.operator if bitop[o] then return Op{'!call', bitop[o], self:get(node.left), self:get(node.right) } end if o == 'is' then return Op{'!call', '__is__', self:get(node.left), self:get(node.right)} end if o == 'as' then return Op{'!call', '__as__', self:get(node.left), self:get(node.right)} end if o == '..' then return Op{'!call', '__range__', self:get(node.left), self:get(node.right)} end if o == "~~" then return Op{'!call', '__match__', self:get(node.right), self:get(node.left)} end if o == "!~" then return Op{'!not', Op{'!call', '__match__', self:get(node.right), self:get(node.left)} } end if string.sub(o, 1, 1) == ':' then return Op{'!call', '__usrop__', Op(o), self:get(node.left), self:get(node.right) } end return Op{binop[o], self:get(node.left), self:get(node.right)} end local unop = { ['#'] = '!len', ['-'] = '!neg', ['!'] = '!not', ['not'] = '!not', } function match:UnaryExpression(node) local o = node.operator local a = self:get(node.argument) if o == '~' then return Op{'!call', '__bnot__', a } end return Op{unop[o], a } end function match:ParenExpression(node) return self:get(node.expression) end local function apply_decorators(self, node, decl) if #node.decorators > 0 then for i=#node.decorators, 1, -1 do local deco = node.decorators[i] decl = Op{'!call1', self:get(deco.term), decl } end end return decl end function match:FunctionDeclaration(node) local name if not node.expression then name = self:get(node.name) if node.name.type == 'Identifier' then if node.islocal or self.ctx:in_module() then self.ctx:define(name, { type = "function", node = node }) else -- in function scope, hoist it self.ctx:define(name, { type = "function", line = self.ctx.scope.topline, node = node }) self.ctx:hoist(Op{'!define', name }) end end end local params = { } local prelude = { } self.ctx:enter("function") for i=1, #node.params do self.ctx:define(node.params[i].name) local name = self:get(node.params[i]) params[#params + 1] = name if node.defaults[i] then local test = Op{'!eq', name, '!nil'} local expr = self:get(node.defaults[i]) local cons = Op{'!assign', name, expr } prelude[#prelude + 1] = Op{'!if', test, cons } end if node.guards[i] then local expr = self:get(node.guards[i]) -- hoist guards constructors to the outer scope local temp = util.genid() self.ctx:push(Op{'!let', temp, expr}) expr = temp local test = Op{'!call', '__is__', name, expr } local mesg if i == 1 and expr == '__self__' then mesg = "calling '%s' on bad self (%s expected got %s)" else mesg = string.format( "bad argument #%s to '%%s' (%%s expected got %%s)", i ) end local level = node.level or 1 local cons if node.name then cons = Op{'!call', 'error', Op{'!callmeth', Op(mesg), 'format', Op(self:get(node.name)), Op{'!call1', 'tostring', expr }, Op{'!call1', 'typeof', name } }, Op(level + 1) } else cons = Op{'!call', 'error', Op{'!callmeth', Op(mesg), 'format', Op{'!or', Op{'!index', Op{'!call1', Op{'!index', 'debug', Op"getinfo"}, Op(level), Op"n" }, Op"name" }, Op('?') }, Op{'!call1', 'tostring', expr }, Op{'!call1', 'typeof', name } }, Op(level + 1) } end prelude[#prelude + 1] = Op{'!if', Op{'!not', test }, cons } end end if node.rest then params[#params + 1] = '!vararg' if node.rest ~= "" then self.ctx:define(node.rest.name) prelude[#prelude + 1] = Op{'!define', node.rest.name, Op{'!call1', 'Array', '!vararg' } } end end local body = self:get(node.body) for i=#prelude, 1, -1 do table.insert(body, 1, prelude[i]) end self.ctx:leave(body) local func if node.generator then local inner = Op{'!lambda', Op{ }, body} func = Op{'!lambda', Op(params), OpChunk{ Op{'!return', Op{'!call1', Op{'!index', 'coroutine', Op"wrap"}, inner}} }} else func = Op{'!lambda', Op(params), body} end if node.expression then return func end func = apply_decorators(self, node, func) local decl if node.islocal then decl = OpChunk{ Op{'!define', name}, Op{'!assign', name, func} } else decl = Op{'!assign', name, func } end local wrap = OpChunk{ } self.ctx:shift(wrap) wrap[#wrap + 1] = decl return wrap end function match:IncludeStatement(node) local args = self:list(node.list) table.insert(args, 1, 'self') return Op{'!call', 'include', unpack(args)} end function match:ModuleDeclaration(node) local name = self:get(node.id) if self.ctx:in_module() and node.scope ~= 'local' then self.ctx:define(name) else self.ctx:define(name, { line = self.ctx.scope.topline }) self.ctx:hoist(Op{'!define', name}) end self.ctx:enter("module") self.ctx:define('self') self.ctx:define('__self__') self.ctx:hoist(Op{'!let', Op{node.id.name}, Op{'self'}}) local body = self:get(node.body) self.ctx:unhoist(body) self.ctx:leave() local init = Op{'!call', 'module', Op(node.id.name), Op{'!lambda', Op{ 'self', '!vararg' }, body } } init = apply_decorators(self, node, init) return Op{'!assign', name, init} end function match:ClassDeclaration(node) local name = self:get(node.id) if self.ctx:in_module() and node.scope ~= 'local' then self.ctx:define(name) else self.ctx:define(name, { line = self.ctx.scope.topline }) self.ctx:hoist(Op{'!define', name}) end local base = node.base and self:get(node.base) or nil self.ctx:enter("module") self.ctx:define('self') self.ctx:define('super') self.ctx:define('__self__') self.ctx:hoist(Op{'!let', Op{node.id.name}, Op{'self'}}) local body = self:get(node.body) self.ctx:unhoist(body) self.ctx:leave() local init = Op{'!call', 'class', Op(node.id.name), Op{'!lambda', Op{ 'self', 'super' }, body }, base } init = apply_decorators(self, node, init) return Op{'!assign', name, init} end function match:ClassBodyStatement(node, body) local line = self.ctx:sync(node) line = Op{'!line', line } if node.type == "PropertyDefinition" then local prop = node if prop.kind == "get" then -- self.__getters__[key] = desc.get prop.value.name = prop.key prop.value.level = 2 local decl = self:get(prop) self.ctx:shift(body) decl = apply_decorators(self, prop, decl) body[#body + 1] = OpList{line, Op{'!assign', Op{'!index', Op{'!index', 'self', Op"__getters__" }, Op(prop.key.name) }, decl }} elseif prop.kind == "set" then -- self.__setters__[key] = desc.set prop.value.name = prop.key prop.value.level = 2 local decl = self:get(prop) self.ctx:shift(body) decl = apply_decorators(self, prop, decl) body[#body + 1] = OpList{line, Op{'!assign', Op{'!index', Op{'!index', 'self', Op"__setters__" }, Op(prop.key.name) }, decl }} else -- hack to skip a frame for the constructor if prop.key.name == 'self' then prop.value.level = 2 end local decl = self:get(prop) self.ctx:shift(body) decl = apply_decorators(self, prop, decl) -- self.__members__[key] = desc.value body[#body + 1] = OpList{line, Op{'!assign', Op{'!index', Op{'!index', 'self', Op"__members__" }, Op(prop.key.name) }, decl }} end elseif node.type == 'ClassDeclaration' or node.type == 'ModuleDeclaration' or node.type == 'GrammarDeclaraion' then local stmt = self:get(node) self.ctx:shift(body) body[#body + 1] = stmt if node.scope ~= 'local' then local inner_name = self:get(node.id) body[#body + 1] = OpList{line, Op{'!assign', Op{'!index', 'self', Op(inner_name)}, inner_name } } end else local stmt = self:get(node) self.ctx:shift(body) body[#body + 1] = OpList{line, stmt} end end function match:ClassBody(node) local body = { } for i=1, #node.body do match.ClassBodyStatement(self, node.body[i], body) end return OpChunk(body) end function match:SpreadExpression(node) if node.argument ~= '...' then return Op{'!call', '__spread__', self:get(node.argument) } else return '!vararg' end end function match:NilExpression(node) return '!nil' end function match:PropertyDefinition(node) node.value.generator = node.generator return self:get(node.value) end function match:DoStatement(node) return Op{'!do', self:get(node.body)} end function match:BlockStatement(node) local body = OpChunk{ } for i=1, #node.body do local line = self.ctx:sync(node.body[i]) local stmt = self:get(node.body[i]) self.ctx:shift(body) body[#body + 1] = OpList{Op{'!line', line}, stmt} end return body end function match:ExpressionStatement(node) if node.expression.type == 'Identifier' then return Op{'!call', self:get(node.expression)} end return self:get(node.expression) end function match:CallExpression(node) local callee = node.callee if callee.type == 'MemberExpression' and not callee.computed then if callee.object.type == 'SuperExpression' then local args = self:list(node.arguments) local recv = Op{'!index', 'super', Op(self:get(callee.property)) } table.insert(args, 1, 'self') return Op{'!call', recv, unpack(args)} else if callee.namespace then return Op{'!call', self:get(callee), unpack(self:list(node.arguments))} else local recv = self:get(callee.object) local prop = self:get(callee.property) return Op{'!callmeth', recv, prop, unpack(self:list(node.arguments))} end end else if callee.type == 'SuperExpression' then local args = self:list(node.arguments) local recv = Op{'!index', 'super', Op('self')} table.insert(args, 1, 'self') return Op{'!call', recv, unpack(args)} else local scope = self.ctx.scope if callee.type == 'Identifier' and scope.macro[callee.name] then local macro = scope.macro[callee.name] local frag = macro(self.ctx, unpack(node.arguments)) return frag else local args = self:list(node.arguments) return Op{'!call', self:get(callee), unpack(args)} end end end end function match:WhileStatement(node) local loop = util.genid() local save = self.loop self.loop = loop self.ctx:enter() local body = self:get(node.body) body[#body + 1] = Op{'!label', loop} self.ctx:leave() self.loop = save return Op{'!while', self:get(node.test), body} end function match:RepeatStatement(node) local loop = util.genid() local save = self.loop self.loop = loop self.ctx:enter() local body = self:get(node.body) body[#body + 1] = Op{'!label',loop} self.ctx:leave() self.loop = save return Op{'!repeat', body, self:get(node.test) } end function match:ForStatement(node) local loop = util.genid() local save = self.loop self.loop = loop self.ctx:enter() self.ctx:define(node.name.name) local name = self:get(node.name) local init = self:get(node.init) local last = self:get(node.last) local step = self:get(node.step) local body = self:get(node.body) body[#body + 1] = Op{'!label',loop} self.loop = save self.ctx:leave() return Op{'!loop', OpList{name, init, last, step}, body} end function match:ForInStatement(node) local loop = util.genid() local save = self.loop self.loop = loop local none = util.genid() local temp = util.genid() local iter = Op{'!call', '__each__', self:get(node.right) } self.ctx:enter() local left = { } for i=1, #node.left do self.ctx:define(node.left[i].name) left[i] = self:get(node.left[i]) end local body = self:get(node.body) body[#body + 1] = Op{'!label', loop} self.loop = save self.ctx:leave() return Op{'!for', OpList{Op(left), Op{iter}}, body} end function match:RangeExpression(node) return Op{'!call1', '__range__', self:get(node.left), self:get(node.left) } end function match:ArrayExpression(node) return Op{'!call1', 'Array', unpack(self:list(node.elements))} end function match:TableExpression(node) local tab = { } for i=1, #node.entries do local item = node.entries[i] local key, val if item.name then key = Op(item.name.name) elseif item.expr then key = self:get(item.expr) end if key ~= nil then tab[key] = self:get(item.value) else tab[#tab + 1] = self:get(item.value) end end return Op(tab) end function match:RawString(node) if #node.expressions == 0 then return Op("") elseif #node.expressions == 1 then return Op(node.expressions[1]) end local list = { } for i=1, #node.expressions do local expr = node.expressions[i] if type(expr) == 'string' then list[#list + 1] = Op(expr) else list[#list + 1] = Op{'!call', 'tostring', self:get(expr.expression) } end end return Op{'!mconcat', unpack(list)} end function match:ArrayComprehension(node) local temp = util.genid() for i=1, #node.blocks do local n = node.blocks[i] for j=1, #n.left do self.ctx:define(n.left[j].name) end end local head = Op{'!define', temp, Op{'!call', 'Array'} }; local body = OpChunk{ Op{'!assign', Op{'!index', temp, Op{'!len', temp}}, self:get(node.body) }; } local tail = Op{'!return', temp } for i=1, #node.blocks do body = self:get(node.blocks[i], body) end return Op{'!call', Op{'!lambda', Op{ }, OpChunk{ head, body, tail }}} end function match:ComprehensionBlock(node, body) local iter = Op{'!call', '__each__', self:get(node.right) } local left = OpList(self:list(node.left)) if node.filter then body = Op{'!if', self:get(node.filter), Op{'!do', body }} end return Op{'!for', OpList{Op{ left }, Op{ iter }}, OpChunk{ body }} end function match:RegExp(node) return Op{'!call1', Op{'!index', '__rule__', Op'P' }, self:get(node.pattern) } end function match:GrammarDeclaration(node) local name = self:get(node.id) if self.ctx:in_module() and node.scope ~= 'local' then self.ctx:define(name) else self.ctx:define(name, { line = self.ctx.scope.topline }) self.ctx:hoist(Op{'!define', name}) end self.ctx:enter("module") self.ctx:define('self') self.ctx:define('__self__') self.ctx:hoist(Op{'!let', Op{node.id.name}, Op{'self'}}) local body = OpChunk{ } local init = nil for i=1, #node.body do local n = node.body[i] if n.type == 'PatternRule' then if not init then init = n.name body[#body + 1] = Op{'!assign', Op{'!index', Op{'!index', 'self', Op"__members__" }, Op(1) }, Op(n.name) } end self.ctx:shift(body) body[#body + 1] = Op{'!assign', Op{'!index', Op{'!index', 'self', Op"__members__"}, Op(n.name) }, self:get(n.body) } else match.ClassBodyStatement(self, n, body) end end if not init then self.ctx:abort("no initial rule in grammar '"..name.."'") end self.ctx:unhoist(body) self.ctx:leave() body = Op{'!lambda', Op{ 'self' }, body } local init = Op{'!call1', 'grammar', Op(name), body} init = apply_decorators(self, node, init) return Op{'!assign', name, init } end function match:PatternGrammar(node) local tab = { [1] = Op(node.rules[1].name) } for i=1, #node.rules do local n = node.rules[i] local key = Op(n.name) local val = self:get(n.body) tab[key] = OpList{ Op{'!line', self.ctx:sync(n.body) }, val } end return Op{'!call1', Op{'!index', '__rule__', Op'P'}, Op(tab) } end function match:PatternAlternate(node) local left, right if node.left then left = self:get(node.left) right = self:get(node.right) else left = self:get(node.right) end local line = self.ctx:sync(node) return OpList{ Op{'!line', line}, Op{'!call1', Op{'!index', '__rule__', Op"__add"}, left, right} } end function match:PatternSequence(node) local left, right if node.left then left = self:get(node.left) right = self:get(node.right) else left = self:get(node.right) end local line = self.ctx:sync(node) return OpList{ Op{'!line', line}, Op{'!call1', Op{'!index', '__rule__', Op"__mul"}, left, right} } end function match:PatternAny(node) return Op{'!call1', Op{'!index', '__rule__', Op"P"}, Op(1)} end function match:PatternAssert(node) local call if node.operator == '&' then call = '__len' else call = '__unm' end return Op{'!call1', Op{'!index', '__rule__', Op(call)}, self:get(node.argument)} end function match:PatternProduction(node) local oper, call = node.operator if oper == '~>' then call = 'Cf' elseif oper == '+>' then call = 'Cmt' else assert(oper == '->') call = '__div' end local left = self:get(node.left) local right = self:get(node.right) return Op{'!call1', Op{'!index', '__rule__', Op(call)}, left, right} end function match:PatternRepeat(node) local left, right = self:get(node.left), Op(node.count) return Op{'!call1', Op{'!index', '__rule__', Op"__pow"}, left, right} end function match:PatternCaptBasic(node) return Op{'!call1', Op{'!index', '__rule__', Op"C"}, self:get(node.pattern)} end function match:PatternCaptSubst(node) return Op{'!call1', Op{'!index', '__rule__', Op"Cs"}, self:get(node.pattern)} end function match:PatternCaptTable(node) return Op{'!call1', Op{'!index', '__rule__', Op"Ct"}, self:get(node.pattern)} end function match:PatternCaptConst(node) return Op{'!call1', Op{'!index', '__rule__', Op"Cc"}, self:get(node.argument)} end function match:PatternCaptGroup(node) local args = { self:get(node.pattern) } if node.name then args[#args + 1] = Op(node.name) end return Op{'!call1', Op{'!index', '__rule__', Op"Cg"}, unpack(args)} end function match:PatternCaptBack(node) return Op{'!call1', Op{'!index', '__rule__', Op"Cb"}, Op(node.name)} end function match:PatternCaptBackRef(node) return Op{'!call1', Op{'!index', '__rule__', Op"Cbr"}, Op(node.name)} end function match:PatternReference(node) return Op{'!call1', Op{'!index', '__rule__', Op"V"}, Op(node.name)} end function match:PatternClass(node) local expr = self:get(node.alternates) if node.negated then local any = Op{'!call1', Op{'!index', '__rule__', Op"P"}, Op(1)} expr = Op{'!call1', Op{'!index', '__rule__', Op"__sub"}, any, expr} end return expr end function match:PatternRange(node) return Op{'!call1', Op{'!index', '__rule__', Op"R"}, Op(node.left..node.right)} end function match:PatternTerm(node) return Op{'!call1', Op{'!index', '__rule__', Op"P"}, Op(node.literal)} end function match:PatternPredef(node) return Op{'!call1', Op{'!index', '__rule__', Op"Def"}, Op(node.name)} end function match:PatternArgument(node) local argn = tonumber(node.index) return Op{'!call1', Op{'!index', '__rule__', Op"Carg"}, Op(argn)} end function translate(tree, name, opts) local self = { } self.ctx = Context.new(name, opts) function self:get(node, ...) if not match[node.type] then error("no handler for "..tostring(node.type)) end self.ctx:sync(node) local out = match[node.type](self, node, ...) --if out then out.line = node.line or self.ctx.line end return out end function self:list(nodes, ...) local list = { } for i=1, #nodes do list[#list + 1] = self:get(nodes[i], ...) end return list end -- TODO: this is messy function self.ctx.get(_, ...) return self:get(...) end function self.ctx.list(_, ...) return self:list(...) end local tout = self:get(tree) self.ctx:close() return tout, self.ctx end return { translate = translate }
if not _G.ttnsTemp then _G.ttnsTemp = {sectorIndex = {}, sectors = {}, turtles = {}} end ttns = {} function ttns.toSectorCoords(x, z) return math.floor(x / 64), math.floor(z / 64), math.mod(x, 64), math.mod(z, 64) end function ttns.getSectorCoords(id) if not _G.ttnsTemp.sectorIndex[id] then return nil end return table.unpack(_G.ttnsTemp.sectorIndex[id]) end function ttns.getSectorId(x, z) for k, v in ipairs(_G.ttnsTemp.sectorIndex) do if v == {x, z} then return k end end return nil end function ttns.loadConfigs() if not fs.exists(".ttns") then return false end f = fs.open(".ttns", "r") _G.ttnsTemp.sectorIndex = textutils.unserialize(f.readAll()) f.close() return true end function ttns.saveConfigs() f = fs.open(".ttns", "wb") f.write(textutils.serialize(_G.ttnsTemp.sectorIndex)) f.close() return true end function ttns.loadSector(id) if not fs.exists("disk"..id.."/data.ttns") then return false end f = fs.open("disk"..id.."/data.ttns", "r") _G.ttnsTemp.sectors[id] = textutils.unserialize(f.readAll()) f.close() return true end function ttns.saveSector(id) if not fs.exists("disk"..id) then printError("Can't save sector "..id..", add disks") return false end f = fs.open("disk"..id.."/data.ttns", "wb") f.write(textutils.serialize(_G.ttnsTemp.sectors[id])) f.close() return true end function ttns.newSector(x, z) if not ttns.getSectorId(x, z) then table.insert(_G.ttnsTemp.sectorIndex, {x, z}) id = table.getn(_G.ttnsTemp.sectorIndex) _G.ttnsTemp.sectors[id] = {} return id end end function ttns.setBlock(x, y, z, block) sx, sz = ttns.toSectorCoords(x, z) id = ttns.getSectorId(sx, sz) if not id then id = ttns.newSector(sx, sz) end if not _G.ttnsTemp.sectors[id][x] then _G.ttnsTemp.sectors[id][x] = {} end if not _G.ttnsTemp.sectors[id][x][y] then _G.ttnsTemp.sectors[id][x][y] = {} end _G.ttnsTemp.sectors[id][x][y][z] = block end function ttns.getBlock(x, y, z) sx, sz = ttns.toSectorCoords(x, z) id = ttns.getSectorId(sx, sz) if not id then if not _G.ttnsTemp.sectors[id][x] then return nil end if not _G.ttnsTemp.sectors[id][x][y] then return nil end return _G.ttnsTemp.sectors[id][x][y][z] end end function ttns.init() write("Loading configs... ") ttns.loadConfigs() print("Done") print("Loading sectors... ") for k, v in ipairs(_G.ttnsTemp.sectorIndex) do ttns.loadSector(k) print("Sector "..k.." loaded") end print("Done") end function ttns.saveAll() print("Saving sectors... ") for k, v in ipairs(_G.ttnsTemp.sectorIndex) do ttns.saveSector(k) print("Sector "..k.." saved") end print("Done") end return ttns
object_mobile_dressed_meatlump_male_05 = object_mobile_shared_dressed_meatlump_male_05:new { } ObjectTemplates:addTemplate(object_mobile_dressed_meatlump_male_05, "object/mobile/dressed_meatlump_male_05.iff")
#!/usr/bin/env sysbench -- This test is designed for testing MariaDB's key_cache_segments for MyISAM, -- and should work with other storage engines as well. -- -- For details about key_cache_segments please refer to: -- http://kb.askmonty.org/v/segmented-key-cache -- require("oltp_common") -- Add --number-of-ranges and --delta to the list of standard OLTP options sysbench.cmdline.options.number_of_ranges = {"Number of random BETWEEN ranges per SELECT", 10} sysbench.cmdline.options.delta = {"Size of BETWEEN ranges", 5} -- Override standard prepare/cleanup OLTP functions, as this benchmark does not -- support multiple tables oltp_prepare = prepare oltp_cleanup = cleanup function prepare() assert(sysbench.opt.tables == 1, "this benchmark does not support " .. "--tables > 1") oltp_prepare() end function cleanup() assert(sysbench.opt.tables == 1, "this benchmark does not support " .. "--tables > 1") oltp_cleanup() end function thread_init() drv = sysbench.sql.driver() con = drv:connect() local ranges = string.rep("k BETWEEN ? AND ? OR ", sysbench.opt.number_of_ranges - 1) .. "k BETWEEN ? AND ?" stmt = con:prepare(string.format([[ SELECT count(k) FROM sbtest1 WHERE %s]], ranges)) params = {} for j = 1, sysbench.opt.number_of_ranges*2 do params[j] = stmt:bind_create(sysbench.sql.type.INT) end stmt:bind_param(unpack(params)) rlen = sysbench.opt.table_size / sysbench.opt.threads thread_id = sysbench.tid % sysbench.opt.threads end function thread_done() stmt:close() con:disconnect() end function event() -- To prevent overlapping of our range queries we need to partition the whole -- table into 'threads' segments and then make each thread work with its -- own segment. for i = 1, sysbench.opt.number_of_ranges*2, 2 do local rmin = rlen * thread_id local rmax = rmin + rlen local val = sysbench.rand.default(rmin, rmax) params[i]:set(val) params[i+1]:set(val + sysbench.opt.delta) end stmt:execute() end
if vim.g.vscode then return end if not pcall(require, 'onedarkpro') then return end local onedarkpro = require('onedarkpro') local colors = require('jonz94.colors') local is_win = vim.fn.has('win32') onedarkpro.setup({ colors = { onedark = { bg = colors.bg, black = colors.black, -- additional colors cursorline = colors.cursorline, selection = colors.selection, color_column = colors.color_column, indentline = colors.indentline, menu = colors.menu, menu_scroll = colors.menu_scroll, }, }, styles = { strings = 'NONE', comments = 'italic', keywords = 'bold', functions = 'NONE', variables = 'NONE', }, options = { bold = true, italic = true, underline = false, undercurl = false, -- curly underline cursorline = true, }, hlgroups = { -- 'nbsp', 'space', 'tab' and 'trail' in 'listchars' Whitespace = { fg = colors.cursorline }, -- current line number CursorLineNr = { bg = colors.cursorline, fg = colors.yellow, style = 'bold' }, -- the character under the cursor or just before it, -- if it is a paired bracket, and its match. |pi_paren.txt| MatchParen = { fg = colors.none, bg = colors.gray }, -- remove italic style on operator Operator = { style = 'NONE' }, -- operators that are English words, e.g. `and`, `as`, `or` TSKeywordOperator = { fg = colors.purple }, -- html tag attributes. TSTagAttribute = { fg = colors.orange }, TSConstructor = { fg = colors.yellow }, TSTypeBuiltin = { fg = colors.yellow }, TSLabel = { fg = colors.red, style = 'NONE' }, TSInclude = { fg = colors.purple }, -- telescope TelescopeSelection = { bg = colors.cursorline, fg = colors.yellow }, TelescopeMatching = { style = 'italic' }, TelescopePromptPrefix = { link = 'TelescopeNormal' }, -- nvim-tree inactive NvimTreeNormalNC = { bg = colors.bg }, -- nvim-tree NvimTreeFolderName = { fg = colors.fg }, NvimTreeFolderIcon = { fg = colors.yellow }, NvimTreeOpenedFolderName = { fg = colors.fg }, NvimTreeMarkdownFile = { fg = colors.fg }, NvimTreeExecFile = { fg = is_win and colors.fg or colors.green, style = is_win and 'NONE' or 'bold', }, NvimTreeOpenedFile = { fg = colors.yellow, style = 'italic' }, }, }) onedarkpro.load()
(terralib.loadfile("test.t"))() import "darkroom" test(im(x,y) testinput(x,y)+[uint8](100) end)
QhunUnitTest.Base = {} QhunUnitTest.Base.__index = QhunUnitTest.Base -- constructor --[[ { methodOrder?: string[] } ]] function QhunUnitTest.Base.new(methodOrder) -- private properties local instance = { __lastAssertCount = 0, __lastErrorCount = 0, __methodOrder = methodOrder } setmetatable(instance, QhunUnitTest.Base) return instance end --[[ PUBLIC FUNCTIONS ]] -- a setup function that will be executed once before the class tests run function QhunUnitTest.Base:setupClass() end -- a teardown function that will be executed one after all tests of the class as been run function QhunUnitTest.Base:teardownClass() end -- a setup function that will be executed before each test function QhunUnitTest.Base:setup(methodName) end -- a teardown function that will be executed after each test has been run function QhunUnitTest.Base:teardown(methodName) end -- reset the assert counts for the next test run function QhunUnitTest.Base:resetAssertCounts() self.__lastAssertCount = 0 self.__lastErrorCount = 0 end -- get the assert counts for the last test run -- returns numberOkAsserts, numberOfErrors function QhunUnitTest.Base:getAssertCounts() return self.__lastAssertCount, self.__lastErrorCount end -- tests if the given value is an instance of expectedClass --[[ { value: {}, expectedClass: {}, message?: string } returns boolean ]] function QhunUnitTest.Base:assertClassOf(value, expectedClass, message) self.__lastAssertCount = self.__lastAssertCount + 1 -- make the assertion local assertion = value.__index == expectedClass -- write an error if not assertion then self:_assertError(message or "Expected value to be an instanceof class") end return assertion end -- tests if the given value is derived from the expected class --[[ { value: {}, expectedClass: {}, message?: string } returns boolean ]] function QhunUnitTest.Base:assertDerivedFrom(value, expectedClass, message) self.__lastAssertCount = self.__lastAssertCount + 1 -- make the assertion local assertion = getmetatable(getmetatable(value).__index).__index == expectedClass -- write an error if not assertion then self:_assertError(message or "Expected value to be a derived class") end return assertion end -- tests if the given table has a size of the expected size --[[ { table: {}, expectedSize: number, message?: string } returns boolean ]] function QhunUnitTest.Base:assertTableSize(table, expectedSize, message) self.__lastAssertCount = self.__lastAssertCount + 1 local size = 0 for _, _ in pairs(table) do size = size + 1 end if size ~= expectedSize then self:_assertError(message or "The given table size is " .. size .. " but expected was " .. expectedSize) end return size == expectedSize end -- tests if a given value is true (typesafe) --[[ { booleanValue: boolean, message?: string } returns boolean ]] function QhunUnitTest.Base:assertTrue(booleanValue, message) self.__lastAssertCount = self.__lastAssertCount + 1 if type(booleanValue) ~= "boolean" or not booleanValue then self:_assertError(message or "The given boolean value was FALSE but expected to be TRUE") end return booleanValue == true end -- tests if a given value is false (typesafe) --[[ { booleanValue: boolean, message?: string } returns boolean ]] function QhunUnitTest.Base:assertFalse(booleanValue, message) self.__lastAssertCount = self.__lastAssertCount + 1 if type(booleanValue) ~= "boolean" or booleanValue then self:_assertError(message or "The given boolean value was TRUE but expected to be FALSE") end return booleanValue == false end -- tests if a given value is nill --[[ { value: nil, message?: string } returns boolean ]] function QhunUnitTest.Base:assertNil(value, message) self.__lastAssertCount = self.__lastAssertCount + 1 if value ~= nil then self:_assertError(message or "The given value was expected to be NIL. Current value is typeof " .. type(value)) end return value == nil end -- tests if the two objects are equal using == operator --[[ { value1: any, value2: any, message?: string } returns boolean ]] function QhunUnitTest.Base:assertEqual(value1, value2, message) self.__lastAssertCount = self.__lastAssertCount + 1 local match = value1 == value2 if not match then self:_assertError( message or "The two values are not equal. Type 1 is " .. type(value1) .. " and type 2 is " .. type(value2) ) end return match end -- tests if the two tables have the save key and values but different links -- NOTE: this is used for tables with the save content but there the == operator does not work --[[ { o1: table, p2: table, ignoreMetatable?: boolean = true, message?: string } returns boolean ]] function QhunUnitTest.Base:assertTableSimilar(o1, o2, ignoreMetatable, message) self.__lastAssertCount = self.__lastAssertCount + 1 local msg = self:_similarTable(o1, o2, ignoreMetatable) if msg ~= true then self:_assertError(message or msg) end return true end -- tests if the two objects are unequal using ~= operator --[[ { value1: any, value2: any, message?: string } returns boolean ]] function QhunUnitTest.Base:assertNotEqual(value1, value2, message) self.__lastAssertCount = self.__lastAssertCount + 1 local match = value1 ~= value2 if not match then self:_assertError(message or "The two values are equal. They should not be") end return match end -- tests if a given variable has a expected type --[[ { variable: any, expectedType: string, message?: string } returns boolean ]] function QhunUnitTest.Base:assertTypeof(variable, expectedType, message) self.__lastAssertCount = self.__lastAssertCount + 1 local match = type(variable) == expectedType if not match then self:_assertError( message or 'The given variable\'s type ("' .. type(variable) .. '") does not match with the expected ("' .. expectedType .. '").' ) end return match end -- tests if a given number is greater than or equal to the expected number --[[ { variable: number, expectedNumber: number, message?: string } returns boolean ]] function QhunUnitTest.Base:assertNumberGreaterThanEqual(variable, expectedNumber, message) self.__lastAssertCount = self.__lastAssertCount + 1 if type(variable) == "number" then if not (variable >= expectedNumber) then self:_assertError( message or "the number " .. variable .. " expected to be greater then or equal to " .. expectedNumber ) end else self:_assertError("the variable should be a number but typeof " .. type(variable) .. " given") end return true end -- tests if a given string has the expected length --[[ { variable: string, expectedLength: number, message?: string } returns boolean ]] function QhunUnitTest.Base:assertStringLength(variable, expectedLength, message) self.__lastAssertCount = self.__lastAssertCount + 1 if type(variable) == "string" then local currentLength = variable:len() if currentLength ~= expectedLength then self:_assertError( message or "the length of the string was " .. currentLength .. " but expected to be " .. expectedLength ) end else self:_assertError("the variable should be a string but typeof " .. type(variable) .. " given") end return true end -- tests if a method was invoked at least one time --[[ { wrappedInstance: {QhunUnitTest.Wrapper}, methodName: string, message?: string } returns boolean ]] function QhunUnitTest.Base:assertMethodCalled(wrappedInstance, methodName, message) self.__lastAssertCount = self.__lastAssertCount + 1 local actualCalls = wrappedInstance:__unittest_getMethodCallAmount(methodName) if actualCalls < 1 then self:_assertError( message or 'the wrapped instance does not make any calls to the given method "' .. methodName '"' ) end return true end -- tests if a method was invoked at least one time --[[ { wrappedInstance: {QhunUnitTest.Wrapper}, methodName: string, -- the amount of calls to the given method expectedCalls: number, message?: string } returns boolean ]] function QhunUnitTest.Base:assertMethodCalledTimes(wrappedInstance, methodName, expectedCalls, message) self.__lastAssertCount = self.__lastAssertCount + 1 local actualCalls = wrappedInstance:__unittest_getMethodCallAmount(methodName) if actualCalls ~= expectedCalls then self:_assertError( message or "the wrapped instance done " .. actualCalls .. ' to the given method "' .. methodName '" but expected are ' .. expectedCalls ) end return true end -- tests if a method was invoked with the given arguments --[[ { wrappedInstance: {QhunUnitTest.Wrapper}, methodName: string, -- the amount of calls to the given method arguments: {...}, message?: string } returns boolean ]] function QhunUnitTest.Base:assertMethodCalledWith(wrappedInstance, methodName, arguments, message) self.__lastAssertCount = self.__lastAssertCount + 1 local calls = wrappedInstance:__unittest_getAllMethodCalls(methodName) -- check if the method was called with the given arguments for _, call in pairs(calls) do if self:_similarTable(arguments, call.parameter, true) == true then return true end end self:_assertError(message or 'the method "' .. methodName .. '" was not called with the given arguments.') end -- tests if a given method was not called --[[ { wrappedInstance: {QhunUnitTest.Wrapper}, methodName: string, message?: string } returns boolean ]] function QhunUnitTest.Base:assertMethodNotCalled(wrappedInstance, methodName, message) self.__lastAssertCount = self.__lastAssertCount + 1 local actualCalls = wrappedInstance:__unittest_getMethodCallAmount(methodName) if actualCalls ~= 0 then self:_assertError(message or 'the wrapped instance has made calls to "' .. methodName '". this was unexpected') end return true end -- tests if a given method was not called with the given arguments --[[ { wrappedInstance: {QhunUnitTest.Wrapper}, methodName: string, arguments: {...}, message?: string } returns boolean ]] function QhunUnitTest.Base:assertMethodNotCalledWith(wrappedInstance, methodName, arguments, message) self.__lastAssertCount = self.__lastAssertCount + 1 local calls = wrappedInstance:__unittest_getAllMethodCalls(methodName) -- check if the method was called with the given arguments for _, call in pairs(calls) do if self:_similarTable(arguments, call.parameter, true) == true then self:_assertError( message or 'the method "' .. methodName .. '" was called with the given arguments. this was unexpected.' ) end end return true end -- test if a callback function throws a lua error --[[ { callback: function, -- arguments will be passed to the callback in that order -- NOTE: because of using pcall, the current function context will be lost arguments: {...}, message?: string } ]] function QhunUnitTest.Base:assertError(callback, arguments, message) self.__lastAssertCount = self.__lastAssertCount + 1 -- check if there are arguments given if type(arguments) ~= "table" then arguments = {} end local status, error = pcall(callback, unpack(arguments)) if status then self:_assertError(message or error or "An error was expected but no error was thrown") end return status end --[[ PRIVATE FUNCTIONS ]] function QhunUnitTest.Base:_assertError(message) self.__lastErrorCount = self.__lastErrorCount + 1 error(message) end function QhunUnitTest.Base:_similarTable(o1, o2, ignoreMetatable) -- default value check if type(ignoreMetatable) ~= "boolean" then ignoreMetatable = true end if o1 == o2 then return true end local o1Type = type(o1) local o2Type = type(o2) if o1Type ~= o2Type then return false end if o1Type ~= "table" then return "type missmatch for table 1. expected table but got " .. o1Type end if not ignoreMetatable then local mt1 = getmetatable(o1) if mt1 and mt1.__eq then --compare using built in method local result = o1 == o2 if not result then return "the two tables are not equal using == operator and metatableSearch" end return result end end local keySet = {} for key1, value1 in pairs(o1) do local value2 = o2[key1] if value2 == nil or self:_similarTable(value1, value2, ignoreMetatable) ~= true then return "some values differ in the two tables" end keySet[key1] = true end for key2, _ in pairs(o2) do if not keySet[key2] then return "some keys differ in the two tables" end end return true end
local unpack = table.unpack local function write(self, n, b) local sn, sb = self.sn, self.sb + b if sb <= 8 then sn = sn | (n << (8 - sb)) else sb = sb - 8 table.insert(self.r, sn | (n >> sb)) while sb > 8 do sb = sb - 8 table.insert(self.r, (n >> sb) & 0xff) end sn = (n << (8 - sb)) & 0xff end if sb == 8 then table.insert(self.r, sn) sn, sb = 0, 0 end self.sn, self.sb = sn, sb end local function write_int(self, n, B) if not B then B = 2 end if (n >> B) == 0 then self:write(0, 1) self:write(n, B) else self:write(1, 1) return self:write_int(n - (1 << B), B + 1) end end local function data(self) return string.char(unpack(self.r)) .. string.char(self.sn), self.sb end local methods = { write = write, write_int = write_int, data = data, } local mt = { __index = methods } local function new() local self = { r = {}, sn = 0, sb = 0 } return setmetatable(self, mt) end return {new = new}
local project_list = { "PracticaFinal", } local function new_project(name) project(name) kind ("ConsoleApp") includedirs{"include", "src/deps/glfw", "src/deps/glad", "src/deps/stb"} files { "tests/" ..name.. "/*.cpp", "tests/" ..name.. "/*.h", "src/*.cpp", "include/**.h", "src/deps/glfw/context.c", "src/deps/glfw/init.c", "src/deps/glfw/input.c", "src/deps/glfw/monitor.c", "src/deps/glfw/window.c", "src/deps/glfw/vulkan.c", "src/deps/glfw/glad.c", "src/deps/glfw/stb/*"} defines {"_GLFW_USE_OPENGL=1"} vpaths { ["Headers"] = "include/*.h", ["Source"] = {"src/*.cpp"}, ["Deep Headers"] = {"include/GLFW/*", "include/glad/**", "include/KHR/**", "include/glm/**"}, ["Deps Srcs"] = "src/deps/**", ["Tests"] = {"tests/"..name.. "/*.cpp", "tests/"..name.."/*.h"}} configuration{"debug"} flags{"Symbols"} targetsuffix("_d") libdirs { "libs/Debug" } configuration{"release"} flags{"Optimize"} targetsuffix("_r") libdirs { "libs/Release" } configuration{"windows"} files{"src/deps/glfw/egl_context.c", "src/deps/glfw/win32*", "src/deps/glfw/wgl_*", "src/deps/glfw/winm_*",} links{"OpenGL32", "assimp-vc140-mt"} defines{"_GLFW_WIN32", "_GLFW_WGL"} flags{"NoEditAndcontinue"} windowstargetplatformversion ="10.0.16299.0" end solution "PracticaFinal" configurations {"debug", "release"} language ("c++") platforms("x64") location("build") debugdir("build") targetdir("bin") flags{"ExtraWarnings"} for k,v in pairs(project_list) do new_project(v) end
TOOL.Category = 'GmodZ' TOOL.Name = 'NPC Spawner' TOOL.Command = nil TOOL.ConfigName = '' local ClassName = "npc_spawner_tool" local PluginName = "npc_spawner" local function lang(id) return "#tool." .. ClassName .. "." .. id end local function cvar(id) return ClassName .. "_" .. id end local cvars = { npc = "npc_combine_s", weapon = "weapon_smg1", spawnheight = 16, spawnradius = 16, maximum = 5, delay = 1, nocollide = 1, healthmul = 1, decrease = 0, skill = WEAPON_PROFICIENCY_AVERAGE, killreward = -1, } local cvars_type = { npc = "string", weapon = "string", spawnheight = "number", spawnradius = "number", maximum = "number", delay = "number", nocollide = "boolean", healthmul = "number", decrease = "number", skill = "number", killreward = "number", } table.Merge(TOOL.ClientConVar, cvars) local wepprof = {} local npcflags = { {512, 'Fade corpse on death'}, {8192, 'Don\'t drop weapons on death'}, {8, 'Drop healthkit on death'}, {256, 'Increase visibility and shoot distance'}, {16384, '[PHYS] Ignore player push'}, {4096, '[PHYS] Alternate collision (don\'t avoid players)'}, {1, '[IDLE] Remain idle till seen'}, {2, '[IDLE] Make no idle sounds until angry'}, {16, '[IDLE] Don\'t acquire enemies or avoid obstacles'}, {128, '[DEV] Wait for script'}, {4, '[DEV] Fall to ground instead of teleporting'}, {1024, '[DEV] Think outside PVS'}, {2048, '[DEV] Template NPC'}, } for _, v in ipairs(npcflags) do TOOL.ClientConVar['SF_'..v[1]] = 0 if (CLIENT) then language.Add('tool.'..ClassName..'.SF_'..v[1], v[2]) end end TOOL.ClientConVar['SF_512'] = 1 TOOL.ClientConVar['SF_1024'] = 1 TOOL.ClientConVar['SF_8192'] = 1 if (SERVER) then function TOOL:SetKVs(index, PLUGIN) PLUGIN = PLUGIN or ix.plugin.Get(PluginName) for key in pairs(cvars) do if (cvars_type[key]) then if (cvars_type[key] == "number") then PLUGIN.spawners[index][key] = tonumber(self:GetClientInfo(key)) elseif (cvars_type[key] == "boolean") then PLUGIN.spawners[index][key] = tobool(self:GetClientInfo(key)) else PLUGIN.spawners[index][key] = self:GetClientInfo(key) end else PLUGIN.spawners[index][key] = self:GetClientInfo(key) end end local flags = 0 for _, v in ipairs(npcflags) do if self:GetClientNumber('SF_'..v[1], 0) ~= 0 then flags = bit.bor(flags, v[1]) PLUGIN.spawners[index].flagsIDs = PLUGIN.spawners[index].flagsIDs or {} PLUGIN.spawners[index].flagsIDs[v[1]] = true end end PLUGIN.spawners[index]["flags"] = flags PLUGIN.spawners[index]["lastSpawned"] = os.time() + (tonumber(PLUGIN.spawners[index]["delay"]) * 60) net.Start("ixNPCSpawnerSync") net.WriteTable(PLUGIN.spawners) net.Send(self:GetOwner()) PLUGIN:SaveData() end else language.Add('tool.'..ClassName..'.name','NPC Spawner') language.Add('tool.'..ClassName..'.desc','NPC Spawner Tool') language.Add('tool.'..ClassName..'.left','Create/Update spawner') language.Add('tool.'..ClassName..'.right','Delete spawner') language.Add('tool.'..ClassName..'.reload','Copy info from spawner') language.Add('tool.'..ClassName..'.panel_npc','NPC Selection') language.Add('tool.'..ClassName..'.npc','NPC') language.Add('tool.'..ClassName..'.all_npcs','All NPCs') language.Add('tool.'..ClassName..'.weapon','Weapon') language.Add('tool.'..ClassName..'.skill','Weapon Skill') language.Add('tool.'..ClassName..'.panel_spawning','Spawning Rates') language.Add('tool.'..ClassName..'.delay','Spawning Delay (minutes)') language.Add('tool.'..ClassName..'.maximum','Max count') language.Add('tool.'..ClassName..'.decrease','Wave Delay Decrease') language.Add('tool.'..ClassName..'.decrease.help','Every time you kill (Max count) NPCs, the spawning delay will be decreased by this amount') language.Add('tool.'..ClassName..'.panel_positioning','Positioning') language.Add('tool.'..ClassName..'.positioning.help',"Because spawning is random, NPCs can get stuck.\nYou can either make them not collide with each other or space out where they spawn.") language.Add('tool.'..ClassName..'.nocollide','Disable NPC Collisions') language.Add('tool.'..ClassName..'.spawnheight','Spawn Height') language.Add('tool.'..ClassName..'.spawnradius','Spawn Distance') language.Add('tool.'..ClassName..'.panel_other','Other') language.Add('tool.'..ClassName..'.healthmul','Health multiplier') language.Add('tool.'..ClassName..'.killreward','Kill Reward') language.Add('tool.'..ClassName..'.killreward.help','Some gamemodes and addons give you a reward for killing NPCs. If you want to override the reward for NPCs spawned by this platform, set the value to anything other than -1.') language.Add('tool.'..ClassName..'.weapon_rebel','Random Rebel Weapon') language.Add('tool.'..ClassName..'.weapon_combine','Random Combine Weapon') language.Add('tool.'..ClassName..'.weapon_citizen','Random Citizen Weapon') language.Add('tool.'..ClassName..'.panel_spawn_flags','Spawn Flags') TOOL.Information = { { name = "left" }, { name = "right" }, { name = 'reload' }, } wepprof[WEAPON_PROFICIENCY_POOR] = 'Poor = 0' wepprof[WEAPON_PROFICIENCY_AVERAGE] = 'Average = 1' wepprof[WEAPON_PROFICIENCY_GOOD] = 'Good = 2' wepprof[WEAPON_PROFICIENCY_VERY_GOOD] = 'Very good = 3' wepprof[WEAPON_PROFICIENCY_PERFECT] = 'Perfect = 4' end function TOOL:AreaInRect(v, location) local radius = 16 return (v.position.x >= location.x - radius and v.position.x <= (location.x + radius) and v.position.y >= location.y - radius and v.position.y <= (location.y + radius) and v.position.z >= location.z - radius and v.position.z <= (location.z + radius)) end if (SERVER) then function TOOL:LeftClick(trace) local owner = self:GetOwner() if (!owner:IsSuperAdmin()) then return false end local PLUGIN = ix.plugin.Get(PluginName) if (!PLUGIN) then return false end local stop = nil local location = trace.HitPos + trace.HitNormal * 0.04 for k, v in ipairs(PLUGIN.spawners) do if (self:AreaInRect(v, location)) then if (!v.static) then self:SetKVs(k, PLUGIN) end stop = true break end end if (stop) then return true end local ang = trace.HitNormal:Angle() ang.r = 0 ang.p = 0 ang.y = ang.y + 180 local data = { position = trace.HitPos + trace.HitNormal * 0.04, angles = ang, title = "NPC Spawner #" .. #PLUGIN.spawners + 1, spawnedNPCs = {}, totalSpawnedNPCs = 0 } for key, default in pairs(cvars) do if (cvars_type[key]) then if (cvars_type[key] == "number") then data[key] = tonumber(default) elseif (cvars_type[key] == "boolean") then data[key] = tobool(default) else data[key] = default end else data[key] = default end end data.lastSpawned = os.time() + (tonumber(data.delay) * 60) data.flagsIDs = {} local flags = 0 for _, v in ipairs(npcflags) do local num = self:GetClientNumber('SF_'..v[1], 0) if self:GetClientNumber('SF_'..v[1], 0) ~= 0 then flags = bit.bor(flags,v[1]) data.flagsIDs[v[1]] = true end end data.flags = flags local index = table.insert(PLUGIN.spawners, data) self:SetKVs(index) return true end function TOOL:RightClick(trace) local owner = self:GetOwner() if (!owner:IsSuperAdmin()) then return false end local PLUGIN = ix.plugin.Get(PluginName) if (!PLUGIN or table.IsEmpty(PLUGIN.spawners)) then return false end local location = trace.HitPos + trace.HitNormal * 0.04 local index for k, v in ipairs(PLUGIN.spawners) do if (!v.static and self:AreaInRect(v, location)) then index = k break end end if (index) then owner:Notify("Точка спавна была удалена.") for ent in pairs(PLUGIN.spawners[index].spawnedNPCs or {}) do if (IsValid(ent) and !ent:IsPlayer()) then ent:Remove() end end table.remove(PLUGIN.spawners, index) net.Start("ixNPCSpawnerSync") net.WriteTable(PLUGIN.spawners) net.Send(owner) PLUGIN:SaveData() else return false end return true end function TOOL:Reload(trace) local owner = self:GetOwner() if (!owner:IsSuperAdmin()) then return false end local PLUGIN = ix.plugin.Get(PluginName) if (!PLUGIN) then return false end local location = trace.HitPos + trace.HitNormal * 0.04 local index for k, v in ipairs(PLUGIN.spawners) do if (!v.static and self:AreaInRect(v, location)) then index = k break end end if (!index) then return false end for key in pairs(self.ClientConVar) do local res = PLUGIN.spawners[index][key] if (res) then owner:ConCommand(cvar(key) .. " " .. tostring(res) .. "\n") end end for _, v in ipairs(npcflags) do if (PLUGIN.spawners[index].flagsIDs[v[1]]) then owner:ConCommand(cvar("SF_" .. v[1]) .. " 1\n") else owner:ConCommand(cvar("SF_" .. v[1]) .. " 0\n") end end return true end function TOOL:Deploy() local owner = self:GetOwner() if (!owner:IsSuperAdmin()) then return false end local PLUGIN = ix.plugin.Get(PluginName) if (!PLUGIN or table.IsEmpty(PLUGIN.spawners)) then return false end net.Start("ixNPCSpawnerSync") net.WriteTable(PLUGIN.spawners) net.Send(owner) return true end end if (CLIENT) then function TOOL:LeftClick(trace) return self:GetOwner():IsSuperAdmin() end function TOOL:RightClick(trace) return self:GetOwner():IsSuperAdmin() end function TOOL:Reload(trace) return self:GetOwner():IsSuperAdmin() end function TOOL:Deploy() return self:GetOwner():IsSuperAdmin() end end if (CLIENT) then local function AddControl(CPanel, control, name, data) data = data or {} data.Label = lang(name) if (control ~= "ControlPanel" and control ~= "ListBox") then data.Command = cvar(name) end local ctrl = CPanel:AddControl(control, data) if (data.Tooltip) then ctrl:SetToolTip(lang(name .. ".tooltip")) end ctrl:SetSkin("Default") return ctrl end function TOOL.BuildCPanel(CPanel) CPanel:AddControl("Header", {Text = lang "name", Description = lang "desc"}):SetSkin("Default") local combo, options -- Presets local CVars = {} local defaults = {} for key, default in pairs(cvars) do key = cvar(key) table.insert(CVars, key) defaults[key] = default end CPanel:AddControl("ComboBox", { Label = "#Presets", Folder = "spawnplatform", CVars = CVars, Options = { default = defaults, }, MenuButton = 1, }):SetSkin("Default") do -- NPC Selector local CPanel = AddControl(CPanel, "ControlPanel", "panel_npc") -- Type select AddControl(CPanel, "NPCSpawnSelecter", "npc") -- Weapon select AddControl(CPanel, "NPCWeaponSelecter", "weapon") -- Skill select local skill = CPanel:ComboBox('Skill', cvar("skill")) skill:SetMinimumSize(nil,20) skill:SetSortItems(false) function skill.UpdateData() skill:Clear() local currentProficiency = GetConVar(cvar("skill")):GetInt() for k,v in pairs(wepprof) do local showDefault = false if currentProficiency == k then showDefault = true end skill:AddChoice(v,k,showDefault) end end skill:UpdateData() end do local CPanel = AddControl(CPanel, "ControlPanel", "panel_spawn_flags") for k,v in ipairs(npcflags) do local fstr = 'SF_'..v[1] local check_flag = AddControl(CPanel, "Checkbox", fstr) check_flag.OnChange = function(self,bool) GetConVar(cvar(fstr)):SetInt(bool and 1 or 0) end check_flag.UpdateData = function(this) if (GetConVar(cvar(fstr)):GetString() == "1") then check_flag:SetChecked(true) else check_flag:SetChecked(false) end end check_flag:UpdateData() end end do local CPanel = AddControl(CPanel, "ControlPanel", "panel_spawning") -- Timer select AddControl(CPanel, "Slider", "delay", {Type = "Float", Min = 0.1, Max = 60}) -- Maximum select AddControl(CPanel, "Slider", "maximum", {Type = "Integer", Min = 1, Max = 20}) -- Timer Reduction AddControl(CPanel, "Slider", "decrease", {Type = "Float", Min = 0, Max = 2, Help = true}) end do -- Positions local CPanel = AddControl(CPanel, "ControlPanel", "panel_positioning", {Closed = true}) CPanel:Help(lang "positioning.help") -- Nocollide AddControl(CPanel, "Checkbox", "nocollide") -- Spawnheight select AddControl(CPanel, "Slider", "spawnheight", {Type = "Float", Min = 8, Max = 128}) -- Spawnradius select AddControl(CPanel, "Slider", "spawnradius", {Type = "Float", Min = 0, Max = 128}) end do -- Other local CPanel = AddControl(CPanel, "ControlPanel", "panel_other", {Closed = true}) -- Healthmul select AddControl(CPanel, "Slider", "healthmul", {Type = "Float", Min = 0.5, Max = 5}) -- NPC Kill Reward AddControl(CPanel, "Slider", "killreward", {Type = "Integer", Min = -1, Max = 1000, Help = true}) end end local nearDist = math.pow(3000, 2) local PLUGIN function TOOL:DrawHUD() PLUGIN = PLUGIN or ix.plugin.Get(PluginName) if (!PLUGIN or !PLUGIN.spawners) then return false end local spawners = PLUGIN.spawners or {} if (table.IsEmpty(spawners)) then return false end local trace = self:GetOwner():GetEyeTraceNoCursor() local location = trace.HitPos + trace.HitNormal * 0.04 for _, v in ipairs(spawners) do local col = !v.static and color_white or Color("gray") local a = v.position:ToScreen() local title = Format("%s (%s)", v.title, v.npc) surface.SetFont("DermaDefaultBold") local tW, tH = surface.GetTextSize(title) surface.SetDrawColor(0, 0, 0, 150) surface.DrawRect(a.x - tW * 0.5 - 5, a.y - 50, tW + 10, tH * 5) for _, v2 in ipairs(ents.FindInSphere(v.position, v.spawnradius or cvars.spawnradius)) do if (IsValid(v2) and (v2:IsPlayer() and v2:GetMoveType() != MOVETYPE_NOCLIP or v2:IsNPC() or v2:IsNextBot())) then col = Color("red") break end end if (LocalPlayer():GetMoveType() != MOVETYPE_NOCLIP and LocalPlayer():GetPos():DistToSqr(v.position) < nearDist) then col = Color("red") end if (self:AreaInRect(v, location)) then if (!v.static) then col = Color("green") end end local space = 10 surface.SetDrawColor(Color("sky_blue")) surface.DrawRect(a.x, a.y, 8, 8) draw.SimpleTextOutlined(title, "DermaDefaultBold", a.x, a.y - space, col, 1, 1, 1, color_black) space = space + 15 draw.SimpleTextOutlined("Wep: " .. v.weapon, "DermaDefaultBold", a.x, a.y - space, Color("yellow"), 1, 1, 1, color_black) space = space + 15 draw.SimpleTextOutlined(Format("MaxNPCs: %d, Delay: %d", v.maximum, v.delay), "DermaDefaultBold", a.x, a.y - space, Color("yellow"), 1, 1, 1, color_black) end end end
local utils = {} -- check whether a lua table is an array or a dictionary -- note: this will only work if the table is either an array or a dictionary. if the table is both, god help us all -- https://stackoverflow.com/a/25709704/2513803 function utils.is_array(t) local i = 0 for _ in pairs(t) do i = i + 1 if t[i] == nil then return false end end return true end -- check whether a table contains a value -- https://stackoverflow.com/a/33511182/2513803 function utils.has_value (tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end return utils
require 'rnn' lfs=require('lfs') --matio=require('matio') version = 1 --[[command line arguments]]-- cmd = torch.CmdLine() cmd:text() cmd:text('Train a RNN Model on sample dataset using LSTM or GRU to compute state-values in EMD.') cmd:text('Example:') cmd:text("my-code.lua --cuda --useDevice 2 --progress --zeroFirst --cutoffNorm 4 --rho 10") cmd:text('Options:') cmd:option('--lr', 0.001, 'learning rate at t=0') cmd:option('--minLR', 0.00001, 'minimum learning rate') cmd:option('--saturateEpoch', 400, 'epoch at which linear decayed LR will reach minLR') cmd:option('--momentum', 0.99, 'momentum') cmd:option('--maxOutNorm', -1, 'max l2-norm of each layer\'s output neuron weights') cmd:option('--cutoffNorm', -1, 'max l2-norm of concatenation of all gradParam tensors') cmd:option('--batchSize', 32, 'number of examples per batch') cmd:option('--cuda', true, 'use CUDA') cmd:option('--useDevice', 2, 'sets the device (GPU) to use') cmd:option('--nIteration', 2000, 'maximum number of iteration to run') cmd:option('--subIteration',50,'number of training steps in each subset') cmd:option('--maxTries', 50, 'maximum number of epochs to try to find a better local minima for early-stopping') cmd:option('--silent', false, 'don\'t print anything to stdout') cmd:option('--uniform', 0.1, 'initialize parameters using uniform distribution between -uniform and uniform. -1 means default initialization') -- recurrent layer cmd:option('--lstm', false, 'use Long Short Term Memory (nn.LSTM instead of nn.Recurrent)') cmd:option('--gru', true, 'use Gated Recurrent Units (nn.GRU instead of nn.Recurrent)') cmd:option('--rho', 6, 'back-propagate through time (BPTT) for rho time-steps') cmd:option('--zeroFirst', false, 'first step will forward zero through recurrence (i.e. add bias of recurrence). As opposed to learning bias specifically for first step.') cmd:option('--dropout', true, 'apply dropout after each recurrent layer') cmd:option('--dropoutProb', 0.1, 'probability of zeroing a neuron (dropout probability)') -- file path cmd:option('--fpath','/home/jchen16/code/Tracking_System/code/train','directory to data') cmd:option('--trainType','gt','gt or seg') cmd:text() opt = cmd:parse(arg or {}) if opt.cuda then require 'cutorch' require 'cunn' cutorch.setDevice(opt.useDevice) end local fpath=opt.fpath local trainType = opt.trainType --[[Data]]-- numPredict=5 local datapath=string.format('%s/%s/%s',fpath,trainType,'data'); local targetpath=string.format('%s/%s/%s',fpath,trainType,'target'); local iter_data, datadir = lfs.dir(datapath) local datafile = datadir:next() local f_data = datapath..'/'..datafile local attr_data = lfs.attributes (f_data) while datafile == "." or datafile == ".." or attr_data.mode == "directory" do datafile = datadir:next() f_data = datapath..'/'..datafile attr_data = lfs.attributes (f_data) end local iter_target, targetdir = lfs.dir(targetpath) local targetfile = targetdir:next() local f_target = targetpath..'/'..targetfile local attr_target = lfs.attributes(f_target) while targetfile == "." or targetfile == ".." or attr_target.mode == "directory" do targetfile = targetdir:next() f_target = targetpath..'/'..targetfile attr_target = lfs.attributes (f_target) end local data = torch.load(f_data) local labels = torch.load(f_target) COLS = data:size(2) SEQS = labels:size(1) ROWS = SEQS*6; if opt.cuda then print('shipping data to cuda') data=data:cuda() labels=labels:cuda() end print('Good') collectgarbage() print('start to build model...') --[[Model]]-- -- RNN model lm = nn.Sequential() local hiddenSize= {512,512,512,512,512} local inputSize = 512 lm:add(nn.Sequencer(nn.Linear(COLS,inputSize))) for i,hs in ipairs(hiddenSize) do -- recurrent layer local rnn if opt.gru then -- Gated Recurrent Units rnn = nn.GRU(inputSize, hs) elseif opt.lstm then -- Long Short Term Memory rnn = nn.FastLSTM(inputSize, hs) end lm:add(nn.Sequencer(rnn)) if opt.dropout then -- dropout it applied between recurrent layers lm:add(nn.Sequencer(nn.Dropout(opt.dropoutProb))) end inputSize = hs end -- output layer lm:add(nn.SelectTable(-1)) lm:add(nn.Linear(inputSize, numPredict)) if opt.uniform > 0 then for k,param in ipairs(lm:parameters()) do param:uniform(-opt.uniform, opt.uniform) end end criterion = nn.MSECriterion() -- linear decay opt.decayFactor = (opt.minLR - opt.lr)/opt.saturateEpoch print('model is done') if opt.cuda then print('shipping model to cuda') lm:cuda() print('shippig criterion to cuda') criterion = criterion:cuda() end --[[Experiment]]-- offsets = torch.LongTensor(opt.batchSize):random(1,SEQS) for k=1, opt.nIteration do for innerK=1, opt.subIteration do local inputs = {} indices = offsets:clone() indices:add(-1) indices:mul(opt.rho) indices:add(1) -- local inputs=torch.LongTensor(opt.rho,opt.batchSize,COLS) for step=1, opt.rho do inputs[step]= inputs[step] or data.new() inputs[step]:index(data,1,indices) indices:add(1) end --local targets=torch.LongTensor(opt.rho,numPredict) targets = labels.new() targets:index(labels,1,offsets) offsets:add(1) offsets[offsets:gt(SEQS)]=1 local outputs = lm:forward(inputs) local err = criterion:forward(outputs:float(),targets:float()) print('Iter: '.. k .. ' Inner: '.. innerK.. ' Err: '.. err) lm:zeroGradParameters() local gradOutputs = criterion:backward(outputs,targets) local gradInputs = lm:backward(inputs,gradOutputs) lm:updateParameters(opt.lr) if innerK % 10 == 0 then collectgarbage() end end if (k % 50 ==0) then --print('Iter: '.. k ..' Err: '.. err) filename=string.format('%s/checkpoint/net_%f.bin',lfs.currentdir(),k); torch.save(filename,lm); end datafile = datadir:next() targetfile = targetdir:next() if (not datafile) or (not targetfile) then assert(not pcall(datadir.next, datadir)) assert(not pcall(targetdir.next, targetdir)) iter_data, datadir = lfs.dir(datapath) iter_target, targetdir = lfs.dir(targetpath) datafile = datadir:next() targetfile = targetdir:next() end f_target = targetpath..'/'..targetfile attr_target = lfs.attributes(f_target) while targetfile == "." or targetfile == ".." or attr_target.mode == "directory" do targetfile = targetdir:next() f_target = targetpath..'/'..targetfile attr_target = lfs.attributes (f_target) end f_data = datapath..'/'..datafile attr_data = lfs.attributes (f_data) while datafile == "." or datafile == ".." or attr_data.mode == "directory" do datafile = datadir:next() f_data = datapath..'/'..datafile attr_data = lfs.attributes (f_data) end data = torch.load(f_data) labels = torch.load(f_target) COLS = data:size(2) SEQS = labels:size(1) ROWS = SEQS*6; if opt.cuda then data=data:cuda() labels=labels:cuda() end offsets = torch.LongTensor(opt.batchSize):random(1,SEQS) collectgarbage() end datadir:close() targetdir:close() --local inputs = {} --for step=1, opt.rho do -- inputs[step]= inputs[step] or data.new() -- inputs[step]:index(data,1,offsets) -- offsets:add(1) --end --local outputs=lm:forward(inputs) --matio.save('write.mat',outputs:float()) --print(outputs:float()) --print(type(outputs:float())) --[[ local myfile = hdf5.open('write.h5','w') myfile:write('path/to/data',outputs) myfile:close() --]]
--some code taken from moreblocks(the collision and selection boxes), license below: --Copyright (c) 2011-2015 Calinou and contributors. --Licensed under the zlib license. function scifi_nodes.register_slope(name, desc, texture, light) minetest.register_node("scifi_nodes:slope_"..name, { description = desc.." Slope", sunlight_propagates = false, drawtype = "mesh", mesh = "scifi_nodes_slope.obj", tiles = texture, selection_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}, {-0.5, -0.25, -0.25, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.25, 0.5}, {-0.5, 0.25, 0.25, 0.5, 0.5, 0.5} } }, collision_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}, {-0.5, -0.25, -0.25, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.25, 0.5}, {-0.5, 0.25, 0.25, 0.5, 0.5, 0.5} } }, paramtype = "light", paramtype2 = "facedir", use_texture_alpha = "clip", light_source = light, groups = {cracky=1}, on_place = minetest.rotate_node }) end -- register some blocks in stairsplus if available (part of moreblocks) scifi_nodes.register_slope("white2", "Plastic", {"scifi_nodes_white2.png",}, 0) scifi_nodes.register_slope("super_white", "Super Plastic", {"scifi_nodes_super_white.png",}, 11) scifi_nodes.register_slope("ultra_white", "Super Plastic", {"scifi_nodes_ultra_white.png",}, minetest.LIGHT_MAX) scifi_nodes.register_slope("black", "Black", {"scifi_nodes_black.png",}, 0) scifi_nodes.register_slope("white", "White", {"scifi_nodes_white.png",}, 0) scifi_nodes.register_slope("grey", "Grey", {"scifi_nodes_grey.png",}, 0) scifi_nodes.register_slope("bluebars", "Blue bars", {"scifi_nodes_bluebars.png",}, 0) scifi_nodes.register_slope("mesh2", "Metal floormesh", {"scifi_nodes_mesh2.png",}, 0) scifi_nodes.register_slope("mesh", "Metal mesh", {"scifi_nodes_mesh.png",}, 0) scifi_nodes.register_slope("vent", "Vent", {"scifi_nodes_vent2.png",}, 0) scifi_nodes.register_slope("rlight", "Red light", {"scifi_nodes_redlight.png",}, 10) scifi_nodes.register_slope("blight", "Blue light", {"scifi_nodes_light.png",}, 10) scifi_nodes.register_slope("glight", "Green light", {"scifi_nodes_greenlight.png",}, 10) scifi_nodes.register_slope("holes", "Holes", {"scifi_nodes_holes.png",}, 0) scifi_nodes.register_slope("pipe", "Pipe", {"scifi_nodes_pipe.png",}, 0) scifi_nodes.register_slope("stripes", "Stripes", {"scifi_nodes_stripes.png",}, 0) scifi_nodes.register_slope("screen", "Screen", {"scifi_nodes_screen3.png",}, 5) scifi_nodes.register_slope("lightstripe", "Lightstripe", {"scifi_nodes_lightstripe.png",}, minetest.LIGHT_MAX) scifi_nodes.register_slope("blight2", "Blue Light 2", {"scifi_nodes_capsule3.png",}, minetest.LIGHT_MAX) scifi_nodes.register_slope("wallpipe", "Alien Pipe", {"scifi_nodes_wallpipe.png",}, 0) scifi_nodes.register_slope("alien", "Alien Wall", {"scifi_nodes_alnslp.png",}, 0) scifi_nodes.register_slope("purple", "Purple", {"scifi_nodes_purple.png",}, 0) scifi_nodes.register_slope("gblock", "Gblock", {"scifi_nodes_gblock2_front1.png",}, 0) scifi_nodes.register_slope("greenmetal", "Green metal", {"scifi_nodes_greenmetal.png",}, 0) scifi_nodes.register_slope("bluemetal", "Blue metal", {"scifi_nodes_bluemetal.png",}, 0) scifi_nodes.register_slope("wall", "Metal wall", {"scifi_nodes_wall.png",}, 0) scifi_nodes.register_slope("rough", "Rough metal", {"scifi_nodes_rough.png",}, 0) scifi_nodes.register_slope("blklt2", "Black stripe light", {"scifi_nodes_black_light2.png",}, 10) -- Register Nodes for Stairsplus local node = {} node.types = { {"blue", "blue lines"}, {"holes", "metal with holes"}, {"white2", "plastic",}, {"super_white", "Super Plastic", 11}, {"ultra_white", "Ultra Plastic", minetest.LIGHT_MAX}, -- {"engine", "engine", "engine"}, {"wall", "metal wall"}, {"white", "plastic wall"}, {"stripes2top", "dirty metal block"}, {"rough", "rough metal"}, {"lighttop", "metal block"}, {"red", "red lines"}, {"green", "green lines"}, {"vent2", "vent"}, {"stripes", "hazard stripes"}, {"rust", "rusty metal"}, {"mesh", "metal mesh"}, {"black", "black wall"}, {"blackoct", "black octagon"}, {"blackpipe", "black pipe"}, {"blacktile", "black tile"}, {"blacktile2", "black tile 2"}, {"blackvent", "black vent"}, {"bluebars", "blue bars"}, {"bluemetal", "blue metal"}, {"bluetile", "blue tile"}, {"greytile", "grey tile"}, {"mesh2", "metal floormesh"}, {"pipe", "wall pipe"}, {"pipeside", "side pipe"}, {"tile", "white tile"}, {"whiteoct", "white octagon"}, {"whitetile", "white tile2"}, {"black_detail", "black detail"}, {"green_square", "green metal block"}, {"red_square", "red metal block"}, {"grey_square", "grey metal block"}, {"blue_square", "blue metal block"}, {"black_mesh", "black vent block"}, {"dent", "dented metal block"}, {"greenmetal", "green metal wall"}, {"greenmetal2", "green metal wall2"}, {"greenlights", "green wall lights", 10}, {"greenlights2", "green wall lights2", 10}, {"greenbar", "green light bar", 10}, {"green2", "green wall panel"}, {"greentubes", "green pipes"}, {"grey", "grey wall"}, {"greybolts", "grey wall bolts"}, {"greybars", "grey bars"}, {"greydots", "grey wall dots"}, {"greygreenbar", "gray power pipe", 10}, {"octofloor", "Doom floor"}, {"octofloor2", "Brown Doom floor"}, {"doomwall1", "Doom wall 1"}, {"doomwall2", "Doom wall 2"}, {"doomwall3", "Doom wall 3"}, {"doomwall4", "Doom wall 4"}, {"doomwall41", "Doom wall 4.1"}, {"doomwall42", "Doom wall 4.2"}, {"doomwall43", "Doom wall 4.3"}, {"doomwall431", "Doom wall 4.3.1"}, {"doomwall44", "Doom wall 4.4"}, {"blackdmg", "Damaged black wall"}, {"blackdmgstripe", "Damaged black wall(stripes)"}, {"doomengine", "Doom engine wall"}, -- {"monitorwall", "Wall monitors", "monitorwall"}, {"screen3", "Wall monitor"}, {"doomlight", "Doom light", 12}, {"bluwllight", "Blue wall light", minetest.LIGHT_MAX}, {"bluegrid", "Blue Grid", 5}, {"fan", "Fan"}, {"ppllght", "Purple wall light", minetest.LIGHT_MAX}, {"pplwll", "Purple wall"}, {"pplwll2", "Purple wall2"}, {"pplwll3", "Purple wall3"}, {"pplwll4", "Purple wall4"}, {"pplblk", "Purple tile"}, {"purple", "Purple node"}, {"rock", "Moonstone"}, {"rock2", "Moonstone2"}, {"blackvnt", "Black vent"}, {"blackplate", "Black plate"}, } if minetest.global_exists("stairsplus") then for _, row in ipairs(node.types) do local name = row[1] -- Node Definition stairsplus:register_all("scifi_nodes", name, "scifi_nodes:"..name, { description = row[2], tiles = {"scifi_nodes_"..name..".png"}, use_texture_alpha = "clip", groups = {cracky=1}, paramtype = "light", paramtype2 = "facedir", light_source = row[3], }) end end
--- Turbo.lua Parameters example -- -- Copyright 2013 John Abrahamsen -- -- 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 turbo = require "turbo" local NumericHandler = class("NumericHandler", turbo.web.RequestHandler) function NumericHandler:get(num) -- This handler takes one parameter from the Application class. -- The argument must consists of arbitrary length of digits. self:write("Numeric resource is: " .. num) end local ArgumentsHandler = class("ArgumentsHandler", turbo.web.RequestHandler) function ArgumentsHandler:get() -- This handler takes one GET argument. self:write("Argument is: " .. self:get_argument("query")) end function ArgumentsHandler:post() -- This handler takes one POST argument. self:write("Argument is: " .. self:get_argument("query")) end turbo.web.Application({ {"^/num/(%d*)$", NumericHandler}, {"^/argument$", ArgumentsHandler} }):listen(8888) turbo.ioloop.instance():start()
return { tllasgard = { acceleration = 0.006, brakerate = 0.44, buildangle = 16384, buildcostenergy = 158728, buildcostmetal = 11289, builder = false, buildpic = "tllasgard.dds", buildtime = 65000, canattack = true, canguard = true, canmove = true, canpatrol = true, canstop = 1, category = "ALL HUGE MOBILE SURFACE UNDERWATER", collisionvolumeoffsets = "0 0 0", collisionvolumescales = "77 77 210", collisionvolumetype = "CylZ", corpse = "dead", defaultmissiontype = "Standby", description = "Artillery BattleShip", energystorage = 600, explodeas = "CRAWL_BLASTSML", firestandorders = 1, floater = true, footprintx = 6, footprintz = 6, idleautoheal = 5, idletime = 1800, losemitheight = 80, maneuverleashlength = 640, mass = 11289, maxdamage = 18750, maxvelocity = 1.4, minwaterdepth = 30, mobilestandorders = 1, movementclass = "DBOAT6", name = "Asgard", noautofire = false, objectname = "TLLASGARD", radaremitheight = 56, selfdestructas = "CRAWL_BLAST", sightdistance = 550, standingfireorder = 2, standingmoveorder = 0, steeringmode = 1, turninplaceanglelimit = 140, turninplacespeedlimit = 1.122, turnrate = 70, unitname = "tllasgard", waterline = 8, customparams = { buildpic = "tllasgard.dds", faction = "TLL", }, featuredefs = { dead = { blocking = true, damage = 11313, description = "Asgard Wreckage", featuredead = "heap", footprintx = 6, footprintz = 6, metal = 8400, object = "tllasgard_dead", reclaimable = true, customparams = { fromunit = 1, }, }, heap = { blocking = false, damage = 14142, description = "Asgard Debris", featuredead = "heap2", footprintx = 6, footprintz = 6, metal = 4480, object = "4x4c", reclaimable = true, customparams = { fromunit = 1, }, }, heap2 = { blocking = false, damage = 7071, description = "Asgard Metal Shards", footprintx = 6, footprintz = 6, metal = 2800, object = "3x3a", reclaimable = true, customparams = { fromunit = 1, }, }, }, sfxtypes = { explosiongenerators = { [1] = "custom:MEDIUMFLARE", }, pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { canceldestruct = "cancel2", underattack = "warning1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "sharmmov", }, select = { [1] = "sharmsel", }, }, weapondefs = { tll_crus = { areaofeffect = 32, avoidfeature = false, cegtag = "Trail_cannon_med", craterareaofeffect = 0, craterboost = 0, cratermult = 0, explosiongenerator = "custom:FLASH1", impactonly = 1, impulseboost = 0.123, impulsefactor = 0.123, name = "CruiserCannon", noselfdamage = true, range = 875, reloadtime = 1, soundhitdry = "xplomed2", soundhitwet = "splshbig", soundhitwetvolume = 0.6, soundstart = "cannhvy1", targetmoveerror = 0.1, turret = true, weapontype = "Cannon", weaponvelocity = 550, damage = { default = 150, subs = 5, }, }, hailstorm = { accuracy = 800, alphadecay = 0.3, areaofeffect = 225, avoidfeature = false, cegtag = "vulcanfx_lowp", craterareaofeffect = 0, craterboost = 0, cratermult = 0, energypershot = 500, explosiongenerator = "custom:BERTHASHOT_LOWP", gravityaffected = "TRUE", impulseboost = 0, impulsefactor = 0, name = "Gauss HailStorm", nogap = 1, noselfdamage = true, proximitypriority = -3, range = 1800, reloadtime = 0.4, rgbcolor = "0.81 0.54 0", separation = 0.45, size = 2.25, sizedecay = -0.15, soundhitdry = "xplomed4", soundhitwet = "splslrg", soundhitwetvolume = 0.6, soundstart = "cannhvy2", stages = 20, turret = true, weapontype = "Cannon", weaponvelocity = 700, damage = { commanders = 175, default = 350, }, }, }, weapons = { [1] = { def = "HAILSTORM", onlytargetcategory = "SURFACE", }, [2] = { def = "TLL_CRUS", maindir = "0 0 1", maxangledif = 300, onlytargetcategory = "SURFACE", }, [3] = { def = "TLL_CRUS", maindir = "0 0 1", maxangledif = 300, onlytargetcategory = "SURFACE", }, }, }, }
PropertiesEncoder = {} PropertiesEncoder.__index = PropertiesEncoder local KEY_VALUE_SEPARATOR = " = " --- Reads/writes .properties files function PropertiesEncoder:create() local this = {} setmetatable(this, self) return this end --- Turns a table into a set of key-value pairs. The values must be string or cast-able to string -- @param tableToEncode {table} -- @returns {string} function PropertiesEncoder:encode(tableToEncode) local encodedArray = {} for k, v in pairs(tableToEncode) do if type(v) == "table" then error("Cannot encode a table value") elseif v == nil then error("Cannot encode a nil value") end encodedArray[#encodedArray + 1] = k .. KEY_VALUE_SEPARATOR .. v end return table.concat(encodedArray, "\n") .. "\n" end --- Decode map data from a string -- @param rawData {string} - The source encoded data -- @returns {table} - The decoded data function PropertiesEncoder:decode(rawData) local result = {} for k, v in string.gmatch(rawData .. "\n", "([^\n]+) = ([^\n]+)") do result[k] = v end for k, v in pairs(result) do local asNumber = tonumber(v) if asNumber ~= nil then result[k] = asNumber end end return result end
-- Matter import 'matter/matter' local clear = playdate.graphics.clear -- Create an engine local engine = Engine.create() local world = engine.world -- Create a renderer local render = Render.create({ element = nil, engine = engine, options = { width = 400, height = 240, -- showInternalEdges = true, -- wireframes = false, -- FIX ME showAngleIndicator = true, -- showCollisions = true, showIds = true, -- showAxes = true, -- showBounds = true, -- showVelocity = true, -- showSeparations = true, -- FIX ME -- showVertexNumbers = true, -- -- grid -- showBroadphase = true, -- showGridId = false, } }) -- Create runner local runner = Runner.create() -- Add bodies World.add(world, { -- Walls Bodies.rectangle(210, 0, 420, 30, { isStatic= true }), Bodies.rectangle(210, 240, 420, 30, { isStatic= true }), Bodies.rectangle(0, 130, 30, 260, { isStatic= true }), Bodies.rectangle(400, 130, 30, 260, { isStatic= true }), -- Falling blocks Bodies.rectangle(100, 50, 30, 30, { frictionAir = 0.005 }), Bodies.rectangle(200, 50, 30, 30, { frictionAir = 0.05 }), Bodies.rectangle(300, 50, 30, 30, { frictionAir = 0.3 }), }) -- Tick TICK = 1 function tick() clear() Runner.tick(runner, engine, TICK) Render.run(render) TICK = TICK + 1 end local ft = playdate.frameTimer.new(1, tick) ft.repeats = true
-- Copyright 2021 SmartThings -- -- 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 test = require "integration_test" local capabilities = require "st.capabilities" local zw = require "st.zwave" local zw_test_utils = require "integration_test.zwave_test_utils" local Basic = (require "st.zwave.CommandClass.Basic")({version=1}) local SwitchBinary = (require "st.zwave.CommandClass.SwitchBinary")({version=2}) local t_utils = require "integration_test.utils" -- supported comand classes local sensor_endpoints = { { command_classes = { {value = zw.BASIC}, {value = zw.SWITCH_BINARY}, }, command_classes = { {value = zw.BASIC}, {value = zw.SWITCH_BINARY}, }, command_classes = { {value = zw.BASIC}, {value = zw.SWITCH_BINARY}, }, command_classes = { {value = zw.BASIC}, {value = zw.SWITCH_BINARY}, }, } } local mock_device = test.mock_device.build_test_zwave_device({ profile = t_utils.get_profile_definition("alarm-switch-3.yml"), zwave_endpoints = sensor_endpoints, zwave_manufacturer_id = 0x014A, zwave_product_type = 0x0005, zwave_product_id = 0x000A }) local function test_init() test.mock_device.add_test_device(mock_device) end test.set_test_init_function(test_init) test.register_message_test( "Basic set 0x00 should be handled as alarm off, swtich off in main component", { { channel = "device_lifecycle", direction = "receive", message = { mock_device.id, "init" } }, { channel = "zwave", direction = "receive", message = { mock_device.id, zw_test_utils.zwave_test_build_receive_command(Basic:Set({ value = 0x00 })) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("main", capabilities.alarm.alarm.off()) } } ) test.register_message_test( "Basic set 0x00 should be handled as alarm off, swtich off in siren1 component", { { channel = "device_lifecycle", direction = "receive", message = { mock_device.id, "init" } }, { channel = "zwave", direction = "receive", message = { mock_device.id, zw_test_utils.zwave_test_build_receive_command( Basic:Set( { value = 0x00 }, { encap = zw.ENCAP.AUTO, src_channel = 2, dst_channels = { 0 } } ) ) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("siren1", capabilities.alarm.alarm.off()) } } ) test.register_message_test( "Basic set 0x00 should be handled as alarm off, swtich off in siren2 component", { { channel = "device_lifecycle", direction = "receive", message = { mock_device.id, "init" } }, { channel = "zwave", direction = "receive", message = { mock_device.id, zw_test_utils.zwave_test_build_receive_command( Basic:Set( { value = 0xFF }, { encap = zw.ENCAP.AUTO, src_channel = 3, dst_channels = { 0 } } ) ) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("siren2", capabilities.alarm.alarm.both()) } } ) test.register_message_test( "Basic set 0xFF should be handled as alarm on, swtich both in main component", { { channel = "device_lifecycle", direction = "receive", message = { mock_device.id, "init" } }, { channel = "zwave", direction = "receive", message = { mock_device.id, zw_test_utils.zwave_test_build_receive_command(Basic:Set({ value = 0xFF })) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("main", capabilities.alarm.alarm.both()) } } ) test.register_message_test( "Basic set 0xFF should be handled as alarm on, swtich both in siren1 component", { { channel = "device_lifecycle", direction = "receive", message = { mock_device.id, "init" } }, { channel = "zwave", direction = "receive", message = { mock_device.id, zw_test_utils.zwave_test_build_receive_command( Basic:Set( { value = 0xFF }, { encap = zw.ENCAP.AUTO, src_channel = 2, dst_channels = { 0 } } ) ) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("siren1", capabilities.alarm.alarm.both()) } } ) test.register_message_test( "Basic set 0xFF should be handled as alarm on, swtich both in siren2 component", { { channel = "device_lifecycle", direction = "receive", message = { mock_device.id, "init" } }, { channel = "zwave", direction = "receive", message = { mock_device.id, zw_test_utils.zwave_test_build_receive_command( Basic:Set( { value = 0xFF }, { encap = zw.ENCAP.AUTO, src_channel = 3, dst_channels = { 0 } } ) ) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("siren2", capabilities.alarm.alarm.both()) } } ) test.register_coroutine_test( "Refresh should generate the correct commands", function() test.socket.zwave:__set_channel_ordering("relaxed") test.socket.capability:__queue_receive({ mock_device.id, { capability = "refresh", command = "refresh", component = "main", args = {} } }) test.socket.zwave:__expect_send( zw_test_utils.zwave_test_build_send_command( mock_device, SwitchBinary:Get({}) ) ) test.socket.zwave:__expect_send( zw_test_utils.zwave_test_build_send_command( mock_device, SwitchBinary:Get({}, { encap = zw.ENCAP.AUTO, src_channel = 0, dst_channels = { 2 } }) ) ) test.socket.zwave:__expect_send( zw_test_utils.zwave_test_build_send_command( mock_device, SwitchBinary:Get({}, { encap = zw.ENCAP.AUTO, src_channel = 0, dst_channels = { 3 } }) ) ) test.socket.zwave:__expect_send( zw_test_utils.zwave_test_build_send_command( mock_device, SwitchBinary:Get({}, { encap = zw.ENCAP.AUTO, src_channel = 0, dst_channels = { 4 } }) ) ) end ) test.run_registered_tests()
local _SKYNET = require("src.skynet") local _ID = require("src.id") local _gate local _lobby local _readyFd local _CMD = {} function _CMD.OnHandshake(id, fd) if (not _SKYNET.Call(_gate, "CheckAgent", fd)) then return end if (not _readyFd) then _readyFd = fd else _SKYNET.Send(_lobby, "NewRoom", _readyFd, fd) _readyFd = nil end end function _CMD.OnDisconnect(id, fd) if (_readyFd == fd) then _readyFd = nil end end local function _Start() _gate = _SKYNET.queryservice("gate") _lobby = _SKYNET.queryservice("lobby") _SKYNET.DispatchCommand(_CMD) _SKYNET.Send(_gate, "Register", _ID.handshake, _SKYNET.self(), "OnHandshake") _SKYNET.Send(_gate, "Register", _ID.disconnect, _SKYNET.self(), "OnDisconnect") end _SKYNET.start(_Start)
w1 = Instance.new("Weld") w1.Parent = Game.Players.yfc.Character.Torso w1.Part0 = Game.Players.yfc.Character.Head w1.Part1 = Game.Players.yfc.Character.Torso w1.C0 = CFrame.fromEulerAnglesXYZ(2, 0, 0) + Vector3.new(0, 0, 0) w1 = Instance.new("Weld") w1.Parent = Game.Players.yfc.Character.Torso w1.Part0 = Game.Players.yfc.Character["Right Arm"] w1.Part1 = Game.Players.yfc.Character.Torso w1.C0 = CFrame.fromEulerAnglesXYZ(1, 0, 0) + Vector3.new(0, 0, 0) w1 = Instance.new("Weld") w1.Parent = Game.Players.yfc.Character.Torso w1.Part0 = Game.Players.yfc.Character["Left Arm"] w1.Part1 = Game.Players.yfc.Character.Torso w1.C0 = CFrame.fromEulerAnglesXYZ(0, 0, 0) + Vector3.new(0, 0, 0) w1 = Instance.new("Weld") w1.Parent = Game.Players.yfc.Character.Torso w1.Part0 = Game.Players.yfc.Character["Right Leg"] w1.Part1 = Game.Players.yfc.Character.Torso w1.C0 = CFrame.fromEulerAnglesXYZ(-1, 0, 0) + Vector3.new(0, 0, 0) w1 = Instance.new("Weld") w1.Parent = Game.Players.yfc.Character.Torso w1.Part0 = Game.Players.yfc.Character["Left Leg"] w1.Part1 = Game.Players.yfc.Character.Torso w1.C0 = CFrame.fromEulerAnglesXYZ(-2, 0, 0) + Vector3.new(0, 0, 0) f = Instance.new("Fire") f.Parent = Game.Players.yfc.Character.Torso f.Heat = 0 f = Instance.new("Smoke") f.Parent = Game.Players.yfc.Character.Torso while true do f.Heat = 1 wait() f.Heat = 7 wait() f.Heat = 9 wait() f.Heat = 12 wait() f.Heat = 9 wait() f.Heat = 7 wait() f.Heat = 1 wait() f.Heat = 0 wait() end
local sButton = Var "Button" local sEffect = Var "Effect" local sPlayer = Var "Player" local sColor = Var "Color" if sColor == "" then sColor = "4th" end return Def.ActorFrame { Def.Model { --fever note color InitCommand=function(self) if string.find(sButton, "Strum") then local color1 = color(PalladiumQuantumColorTable[sColor]) local color2 = color(PalladiumQuantumColorTable["Fever"]) self:rotationx(90):diffuse((color1[1] + color2[1]) * 0.5, (color1[2] + color2[2]) * 0.5, (color1[3] + color2[3]) * 0.5, 1) else self:rotationx(90):diffuse(color(PalladiumQuantumColorTable[sColor])) end if tonumber(sEffect) <= 0 then self:diffusealpha(0) self.isHidden = true else self.isHidden = false end end, --If this is not a fever note from the get-go, don't even bother loading the real model Meshes=(tonumber(sEffect) <= 0 and "non.txt") or (string.find(sButton, "Strum") and "strum color.txt") or "star color.txt", Materials=(string.find(sButton, "Strum") and "resource/Strum mats.txt") or "resource/Fret mats.txt", Bones="star color.txt", FeverMissedMessageCommand=function(self,params) if params.pn ~= sPlayer then return end if tonumber(sEffect) > 0 then if params.Missed then self:diffusealpha(0) self.isHidden = true else self:diffusealpha(1) self.isHidden = false end end end }, Def.Model { --fever note glow InitCommand=function(self) self:rotationx(90):diffuse(color(PalladiumQuantumColorTable["Fever"])) if tonumber(sEffect) <= 0 then self:diffusealpha(0) self.isHidden = true else self.isHidden = false end end, --If this is not a fever note from the get-go, don't even bother loading the real model Meshes=(tonumber(sEffect) <= 0 and "non.txt") or (string.find(sButton, "Strum") and "strum.txt") or "star glow.txt", Materials=(string.find(sButton, "Strum") and "resource/Strum hopo mats.txt") or "resource/Fret mats.txt", Bones="star glow.txt", FeverMissedMessageCommand=function(self,params) if params.pn ~= sPlayer then return end if tonumber(sEffect) > 0 then if params.Missed then self:diffusealpha(0) self.isHidden = true else self:diffusealpha(1) self.isHidden = false end end end }, Def.Model { --fever note InitCommand=function(self) self:rotationx(90) if tonumber(sEffect) <= 0 then self:diffusealpha(0) self.isHidden = true else self.isHidden = false end end, --If this is not a fever note from the get-go, don't even bother loading the real model Meshes=(tonumber(sEffect) <= 0 and "non.txt") or (string.find(sButton, "Strum") and "non.txt") or "star.txt", Materials=(string.find(sButton, "Strum") and "resource/Strum mats.txt") or "resource/Fret mats.txt", Bones="star.txt", FeverMissedMessageCommand=function(self,params) if params.pn ~= sPlayer then return end if tonumber(sEffect) > 0 then if params.Missed then self:diffusealpha(0) self.isHidden = true else self:diffusealpha(1) self.isHidden = false end end end }, Def.Model { --regular note color InitCommand=function(self) self:rotationx(90):diffuse(color(PalladiumQuantumColorTable[sColor])) if tonumber(sEffect) > 0 then self:diffusealpha(0) self.isHidden = true else self.isHidden = false end end, Meshes=string.find(sButton, "Strum") and "strum color.txt" or "gem color.txt", Materials=(string.find(sButton, "Strum") and "resource/Strum mats.txt") or "resource/Fret mats.txt", Bones="gem color.txt", FeverMissedMessageCommand=function(self,params) if params.pn ~= sPlayer then return end if tonumber(sEffect) > 0 then if params.Missed then self:diffusealpha(1) self.isHidden = false else self:diffusealpha(0) self.isHidden = true end end end }, Def.Model { --regular note InitCommand=function(self) self:rotationx(90) if tonumber(sEffect) > 0 then self:diffusealpha(0) self.isHidden = true else self.isHidden = false end end, Meshes=string.find(sButton, "Strum") and "strum.txt" or "gem.txt", Materials=(string.find(sButton, "Strum") and "resource/Strum mats.txt") or "resource/Fret mats.txt", Bones="gem.txt", FeverMissedMessageCommand=function(self,params) if params.pn ~= sPlayer then return end if tonumber(sEffect) > 0 then if params.Missed then self:diffusealpha(1) self.isHidden = false else self:diffusealpha(0) self.isHidden = true end end end } }
max_fov = 360 max_vfov = 180 lens_width = 2*sqrt(2)*2 lens_height = sqrt(2)*2 onload = "f_contain" function lens_inverse(x,y) if x*x/8+y*y/2 > 1 then return nil end local z = sqrt(1-0.0625*x*x-0.25*y*y) local lon = 2*atan(z*x/(2*(2*z*z-1))) local lat = asin(z*y) return latlon_to_ray(lat,lon) end function lens_forward(x,y,z) local lat,lon = ray_to_latlon(x,y,z) local x = 2*sqrt(2)*cos(lat)*sin(lon*0.5) / sqrt(1+cos(lat)*cos(lon*0.5)) local y = sqrt(2)*sin(lat) / sqrt(1+cos(lat)*cos(lon*0.5)) return x,y end
local max = math.max; local GetText = GetText; local GetTexture = GetTexture; local NumLines = NumLines; local _; local _G = _G; local After = C_Timer.After; local GetItemInfo = GetItemInfo; local UIFrameFadeIn = UIFrameFadeIn; local UIFrameFadeOut = UIFrameFadeOut; local PlaySound = PlaySound; local _, _, _, tocversion = GetBuildInfo(); ------------------------ --Redirect API for 9.0-- ------------------------ tocversion = tonumber(tocversion); local HasQuestCompleted; if tocversion == 80300 then function HasQuestCompleted(questID) return IsQuestComplete(questID); end elseif tocversion > 89999 and C_QuestLog.IsComplete then function HasQuestCompleted(questID) return C_QuestLog.IsComplete(questID); end else function HasQuestCompleted(questID) return false end end -------------------- ----API Datebase---- -------------------- local SlotIDtoName = { --[SlotID] = {InventorySlotName, Localized Name, SlotID} [1] = {"HeadSlot", HEADSLOT, INVTYPE_HEAD}, [2] = {"NeckSlot", NECKSLOT, INVSLOT_NECK}, [3] = {"ShoulderSlot", SHOULDERSLOT, INVTYPE_SHOULDER}, [4] = {"ShirtSlot", SHIRTSLOT, INVTYPE_BODY}, [5] = {"ChestSlot", CHESTSLOT, INVTYPE_CHEST}, [6] = {"WaistSlot", WAISTSLOT, INVTYPE_WAIST}, [7] = {"LegsSlot", LEGSSLOT, INVTYPE_LEGS}, [8] = {"FeetSlot", FEETSLOT, INVTYPE_FEET}, [9] = {"WristSlot", WRISTSLOT, INVTYPE_WRIST}, [10]= {"HandsSlot", HANDSSLOT, INVTYPE_HAND}, [11]= {"Finger0Slot", FINGER0SLOT_UNIQUE, INVSLOT_FINGER1}, [12]= {"Finger1Slot", FINGER1SLOT_UNIQUE, INVSLOT_FINGER2}, [13]= {"Trinket0Slot", TRINKET0SLOT_UNIQUE, INVSLOT_TRINKET1}, [14]= {"Trinket1Slot", TRINKET1SLOT_UNIQUE, INVSLOT_TRINKET2}, [15]= {"BackSlot", BACKSLOT, INVTYPE_CLOAK}, [16]= {"MainHandSlot", MAINHANDSLOT, INVTYPE_WEAPONMAINHAND}, [17]= {"SecondaryHandSlot", SECONDARYHANDSLOT, INVTYPE_WEAPONOFFHAND}, [18]= {"AmmoSlot", RANGEDSLOT, INVSLOT_RANGED}, [19]= {"TabardSlot", TABARDSLOT, INVTYPE_TABARD}, } Narci.SlotIDtoName = SlotIDtoName; ----------------------------------------------------- local _, CommanderOfArgus = GetAchievementInfo(12078); --Argus Weapon Transmogs: Arsenal: Weapons of the Lightforged CommanderOfArgus = CommanderOfArgus or "Commander of Argus"; CommanderOfArgus = "|cFFFFD100"..BATTLE_PET_SOURCE_6 .."|r "..CommanderOfArgus; --local EnsorcelledEverwyrm = C_MountJournal.GetMountFromSpell(307932); local _, _, PROMOTION_SHADOWLANDS = C_MountJournal.GetMountInfoExtraByID(1289); --EnsorcelledEverwyrm Promotion: Shadowlands Heroic Edition local HERITAGE_ARMOR = Narci.L["Heritage Armor"]; local HeritageArmorItemIDs = { 165931, 165932, 165933, 165934, 165935, 165936, 165937, 16598, --Dwarf 161008, 161009, 161010, 161011, 161012, 161013, 161014, 161015, --Dark Iron 156668, 156669, 156670, 156671, 156672, 156673, 156674, 156684, --Highmountain 156699, 156700, 156701, 156702, 156703, 156704, 156705, 156706, --Lightforged 161050, 161051, 161052, 161054, 161055, 161056, 161057, 161058, --Mag'har Orc (Blackrock Recolor) 161059, 161060, 161061, 161062, 161063, 161064, 161065, 161066, --Mag'har Orc (Frostwolf Recolor) 160992, 160993, 160994, 160999, 161000, 161001, 161002, 161003, --Mag'har Orc (Warsong Recolor) 156690, 156691, 156692, 156693, 156694, 156695, 156696, 156697, 157758, 158917, --Void Elf 156675, 156676, 156677, 156678, 156679, 156680, 156681, 156685, --Nightborne 166348, 166349, 166351, 166352, 166353, 166354, 166355, 166356, 166357, --Blood Elf 164993, 164994, 164995, 164996, 164997, 164998, 164999, 165000, --Zandalari 165002, 165003, 165004, 165005, 165006, 165007, 165008, 165009, --Kul'tiran 168282, 168283, 168284, 168285, 168286, 168287, 168288, 168289, 168290, --Gnome 168291, 168292, 168293, 168294, 168295, 168296, 168297, 168298, 170063, --Tauren 173968, 173966, 173970, 173971, 173967, 173969, 174354, 174355, --Vulpera 173961, 173962, 173963, 173964, 173958, 173972, --Mechagnome 174000, 174001, 174002, 174003, 174004, 174005, 174006, 173999, 173998, --Worgen --Reserved for test ↓ } local SecretlItemIDs = { [162690] = true, --Waist of Time } local SpecialItemList = { [152332] = CommanderOfArgus, --Brilliant Daybreak Aegis [152333] = CommanderOfArgus, --Lustrous Daybreak Aegis [152334] = CommanderOfArgus, --Brilliant Eventide Aegis [152335] = CommanderOfArgus, --Lustrous Eventide Aegis [152336] = CommanderOfArgus, --Lustrous Daybreak Blade [152336] = CommanderOfArgus, --Lustrous Daybreak Blade [152336] = CommanderOfArgus, --Lustrous Daybreak Blade [152337] = CommanderOfArgus, --Brilliant Daybreak Blade [152338] = CommanderOfArgus, --Lustrous Eventide Blade [152339] = CommanderOfArgus, --Brilliant Daybreak Blade [152340] = CommanderOfArgus, --Lustrous Daybreak Greatsword [152341] = CommanderOfArgus, --Lustrous Eventide Greatsword [152342] = CommanderOfArgus, --Lustrous Daybreak Staff [152343] = CommanderOfArgus, --Lustrous Eventide Staff [172075] = PROMOTION_SHADOWLANDS, --The Eternal Traveler's [172076] = PROMOTION_SHADOWLANDS, [172077] = PROMOTION_SHADOWLANDS, [172078] = PROMOTION_SHADOWLANDS, [172079] = PROMOTION_SHADOWLANDS, [172080] = PROMOTION_SHADOWLANDS, [172081] = PROMOTION_SHADOWLANDS, [172082] = PROMOTION_SHADOWLANDS, [172083] = PROMOTION_SHADOWLANDS, --[134110] = PROMOTION_SHADOWLANDS, --Test } local Ensemble_TheChosenDead_ItemIDs = { 142423, 142421, 142422, 142434, 142420, 142433, --Mail 142427, 142425, 142431, 142435, 142426, 142424, --Plate 142419, 142430, 142432, 142417, 142418, 142416, --Leather 142415, 142411, 142410, 142413, 142429, 142414, --Cloth 143355, 143345, 143334, 143354, 143346, 143347, 143356, 143339, 143349, 143342, 143344, 143335, 143353, 143368, 143340, 143337, 143348, 143341, 143343, 143367, 143336, 143352, 143366, 143351, 143360, 143358, 143350, 143361, 143364, 143359, 143338, 143369, 143365, 143363, 143362, 143357, }; local function BuildSearchTable(table) if type(table) ~="table" then return; end local newTable = {}; for k, v in pairs(table) do newTable[v] = true; end wipe(table); return newTable; end local HeritageArmorList = BuildSearchTable(HeritageArmorItemIDs); local Ensemble_TheChosenDead = BuildSearchTable(Ensemble_TheChosenDead_ItemIDs); function GetArtifactVisualModID(colorID) colorID = colorID or 42; local PRINT = false; local baseSourceID, baseVisualID, appliedSourceID, appliedVisualID, pendingSourceID, pendingVisualID, hasPendingUndo, hideVisual = C_Transmog.GetSlotVisualInfo(16, 0); if not appliedSourceID or appliedSourceID == 0 then appliedSourceID = baseSourceID; end local categoryID, visualID, canEnchant, icon, _, itemLink, transmogLink, _ = C_TransmogCollection.GetAppearanceSourceInfo(appliedSourceID) local sourceInfo = C_TransmogCollection.GetSourceInfo(appliedSourceID) if sourceInfo and PRINT then for k, v in pairs(sourceInfo) do print(k.." "..tostring(v)) end else print(sourceInfo.itemModID); end itemID = sourceInfo.itemID or 127829; itemLink = "\124cffe5cc80\124Hitem:".. itemID .."::::::::120::16777472::2:::"..colorID..":::::::::::::\124h[".. (sourceInfo.name or "") .."]\124h\124r" DEFAULT_CHAT_FRAME:AddMessage(itemLink) end -----Color API------ Narci_GlobalColorIndex = 0; Narci_ColorTable = { --[0] = { 35, 96, 147}, --default Blue 0.1372, 0.3765, 0.5765 [0] = {78, 78, 78}, --Default Black [1] = {121, 31, 35}, --Orgrimmar [2] = { 49, 176, 107}, --Zuldazar [3] = {187, 161, 134}, --Vol'dun [4] = { 89, 140, 123}, --Tiragarde Sound [5] = {127, 164, 114}, --Stormsong [6] = {156, 165, 153}, --Drustvar [7] = { 42, 63, 79}, --Halls of Shadow --Major City-- --[UiMapID] = {r, g, b} [84] = {129, 144, 155}, --Stormwind City [85] = {121, 52, 55}, --Orgrimmar [86] = {121, 31, 35}, --Orgrimmar - Cleft of Shadow [463] = {163, 99, 89}, --Echo Isles [87] = {102, 64, 58}, --Ironforge [27] = {151, 198, 213}, --Dun Morogh [469] = {151, 198, 213}, --New Tinkertown [88] = {115, 140, 113}, --Thunder Bluff [89] = {121, 31, 35}, --Darnassus R.I.P. [90] = { 42, 63, 79}, --Undercity [110] = {172, 58, 54}, --Silvermoon City [202] = {78, 78, 78}, --Gilneas City [217] = {78, 78, 78}, --Ruins of Gilneas [627] = {102, 58, 64}, --Dalaran Broken Isles [111] = {88, 108, 91}, --Shattrath City -- TBC -- [107] = {181, 151, 93}, --Nagrand Outland [109] = {96, 48, 108}, --Netherstorm [102] = {61, 77, 162}, --Zangarmash [105] = {123, 104, 80}, --Blade's Edge Mountains -- MOP -- [378] = {120, 107, 81}, --The Wandering Isle [371] = { 95, 132, 78}, --The Jade Forrest [379] = { 90, 119, 156}, --Kun-Lai Summit -- LEG -- [641] = { 70, 128, 116}, --Val'sharah -- BFA -- [81] = { 98, 84, 77}, --Silithus [1473]= {168, 136, 90}, --Chamber of Heart [1163]= { 89, 140, 123}, --Dazar'alor - The Great Seal [1164]= { 89, 140, 123}, --Dazar'alor - Hall of Chroniclers [1165]= { 89, 140, 123}, --Dazar'alor [862] = { 89, 140, 123}, --Zuldazar [864] = {187, 161, 134}, --Vol'dun [863] = {113, 173, 183}, --Nazmir [895] = { 89, 140, 123}, --Tiragarde Sound [1161]= { 89, 140, 123}, --Boralus [942] = {127, 164, 114}, --Stormsong [896] = {156, 165, 153}, --Drustvar [1462] = {16, 156, 192}, --Mechagon [1355] = {41, 74, 127}, --Nazjatar [249] = {180,149, 121}, --Uldum Normal [1527] = {180,149, 121}, --Uldum Assault [390] = {150, 117, 94}, --Eternal Blossoms Normal [1530] = {150, 117, 94}, --Eternal Blossoms Assault ["NZ"] = {105, 71, 156}, --During Assault: N'Zoth Purple Skybox [1580] = {105, 71, 156}, --Ny'alotha - Vision of Destiny [1581] = {105, 71, 156}, --Ny'alotha - Annex of Prophecy [1582] = {105, 71, 156}, --Ny'alotha - Ny'alotha [1590] = {105, 71, 156}, --Ny'alotha - The Hive [1591] = {105, 71, 156}, --Ny'alotha - Terrace of Desolation [1592] = {105, 71, 156}, --Ny'alotha - The Ritual Chamber [1593] = {105, 71, 156}, --Ny'alotha - Twilight Landing [1594] = {105, 71, 156}, --Ny'alotha - Maw of Gor'ma [1595] = {105, 71, 156}, --Ny'alotha - Warren of Decay [1596] = {105, 71, 156}, --Ny'alotha - Chamber of Rebirth [1597] = {105, 71, 156}, --Ny'alotha - Locus of Infinite Truths --Allied Race Starting Zone-- [124] = {87, 56, 132}, --DK [1186] = {117, 26, 22}, --Dark Iron [971] = {65, 57, 124}, --Void Elf --Class Hall [625] = { 42, 63, 79}, --Dalaran, Broken Isles Halls of Shadow [626] = { 42, 63, 79}, --Hall of Shadow [715] = {149, 180, 146}, --Emerald Dreamway [747] = { 70, 128, 116}, --The Dreamgrove --Frequently Visited [198] = {78, 78, 78}, --Hyjal }; -- 8.3 When Assault: N'Zoth is active, the map uses a different skybox (purple). This quest's location alters every week, so we need to re-index a color preset during the login local AssignColor = CreateFrame("Frame"); AssignColor:RegisterEvent("PLAYER_ENTERING_WORLD"); AssignColor:SetScript("OnEvent", function(self) self:UnregisterEvent("PLAYER_ENTERING_WORLD"); After(2, function() local tag; tag = HasQuestCompleted(57566); --N'Zoth Assault Tracker (Uldum) --/dump C_QuestLog.IsQuestFlaggedCompleted(57566) if tag then Narci_ColorTable[1527] = {105, 71, 156}; --print("N'Zoth in Uldum") else tag = HasQuestCompleted(57567); --N'Zoth Assault Tracker (Vale) if tag then Narci_ColorTable[1530] = {105, 71, 156}; end end end) end); ---------------------------------------------------------------------- Narci_FontColor = { ["Brown"] = {0.85098, 0.80392, 0.70588, "|cffd9cdb4"}, ["DarkGrey"] = {0.42, 0.42, 0.42, "|cff6b6b6b"}, ["LightGrey"] = {0.72, 0.72, 0.72, "|cffb8b8b8"}, ["White"] = {0.88, 0.88, 0.88, "|cffe0e0e0"}, ["Good"] = {0.4862, 0.7725, 0.4627, "|cff7cc576"}, ["Bad"] = {1, 0.3137, 0.3137, 0.3137, "|cffff5050"}, ["Corrupt"] = {0.584, 0.428, 0.82, "|cff946dd1"}, }; local BorderTexture = { ["Bright"] = { [0] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Black", [1] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder", [2] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Uncommon", [3] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Rare", [4] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Epic", --Epic NZoth [5] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Legendary", [6] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Artifact", [7] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Heirloom", --Void [8] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Azerite", [12] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Special", ["Heart"] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-Heart", --Heart ["NZoth"] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-NZoth", ["BlackDragon"] = "Interface/AddOns/Narcissus/Art/Border/HexagonBorder-BlackDragon", --8.3 Legendary Cloak ["Minimap"] = "Interface/AddOns/Narcissus/Art/Minimap/LOGO-Large", }, ["Dark"] = { [0] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Black", [1] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Black", [2] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Uncommon", [3] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Rare", [4] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Epic", --Epic [5] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Legendary", [6] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Artifact", [7] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Heirloom", --Void [8] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Azerite", [12] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Black", ["Heart"] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-Heart", --Heart ["NZoth"] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-NZoth", ["BlackDragon"] = "Interface/AddOns/Narcissus/Art/Border-Thick/HexagonThickBorder-BlackDragon", --8.3 Legendary Cloak ["Minimap"] = "Interface/AddOns/Narcissus/Art/Minimap/LOGO-Large", --only enable Thick minimap when AzeriteUI is loaded }, } function NarciAPI_GetBorderTexture() local index = NarcissusDB and NarcissusDB.BorderTheme if not index then return BorderTexture["Bright"], BorderTexture["Bright"]["Minimap"], "Bright" else return (BorderTexture[index] or BorderTexture["Bright"]), BorderTexture[index]["Minimap"], index end end -------------------- ------Item API------ -------------------- function NarciAPI_GetItemEnchant(itemLink) local _, _, _, linkType, linkID, EnchantID = strsplit(":|H", itemLink); return tonumber(EnchantID) or 0; end local function IsHeritageArmor(itemID) if not itemID then return false; end if HeritageArmorList[itemID] then return true; else return false; end end function NarciAPI_IsSpecialItem(itemID, modID) if not itemID then return false; end if IsHeritageArmor(itemID) then return true, HERITAGE_ARMOR; end local itemSource = SpecialItemList[itemID]; if itemSource ~= nil then --print("Is Special") return true, itemSource; end if SecretlItemIDs[itemID] then return true, ITEMSOURCE_SECRETFINDING; end if Ensemble_TheChosenDead[itemID] then return true, "|cFFFFD100"..DUNGEON_FLOOR_HELHEIMRAID1.."|r"; end return false; end local PrimaryStatsList = { [LE_UNIT_STAT_STRENGTH] = NARCI_STAT_STRENGTH, [LE_UNIT_STAT_AGILITY] = NARCI_STAT_AGILITY, [LE_UNIT_STAT_INTELLECT] = NARCI_STAT_INTELLECT, }; function NarciAPI_GetPrimaryStats() --Return name and value local currentSpec = GetSpecialization() or 1; local _, _, _, _, _, primaryStat = GetSpecializationInfo(currentSpec); primaryStat = primaryStat or 1; local value = UnitStat("player", primaryStat); local name = PrimaryStatsList[primaryStat]; return name, value; end local GetItemEnchant = NarciAPI_GetItemEnchant; local GemInfo = Narci_GemInfo; local EnchantInfo = Narci_EnchantInfo; local DoesItemExist = C_Item.DoesItemExist; local GetCurrentItemLevel = C_Item.GetCurrentItemLevel; local GetItemLink = C_Item.GetItemLink local GetItemStats = GetItemStats; function NarciAPI_GetItemStats(itemLocation) local statsTable = {}; statsTable.gems = 0; if not itemLocation or not DoesItemExist(itemLocation) then statsTable.prim = 0; statsTable.stamina = 0; statsTable.crit = 0; statsTable.haste = 0; statsTable.mastery = 0; statsTable.versatility = 0; statsTable.corruption = 0; statsTable.GemIcon = ""; statsTable.GemPos = ""; statsTable.EnchantPos = ""; statsTable.EnchantSpellID = nil; statsTable.ilvl = 0; return statsTable; end local ItemLevel = GetCurrentItemLevel(itemLocation) local itemLink = GetItemLink(itemLocation) local stats = GetItemStats(itemLink) or {}; local prim = stats["ITEM_MOD_AGILITY_SHORT"] or stats["ITEM_MOD_STRENGTH_SHORT"] or stats["ITEM_MOD_INTELLECT_SHORT"] or 0; local stamina = stats["ITEM_MOD_STAMINA_SHORT"] or 0; local crit = stats["ITEM_MOD_CRIT_RATING_SHORT"] or 0; local haste = stats["ITEM_MOD_HASTE_RATING_SHORT"] or 0; local mastery = stats["ITEM_MOD_MASTERY_RATING_SHORT"] or 0; local versatility = stats["ITEM_MOD_VERSATILITY"] or 0; local corruption = stats["ITEM_MOD_CORRUPTION"] or 0; statsTable.prim = prim; statsTable.stamina = stamina; statsTable.crit = crit; statsTable.haste = haste; statsTable.mastery = mastery; statsTable.versatility = versatility; statsTable.corruption = corruption; statsTable.ilvl = ItemLevel; --Calculate bonus from Gems and Enchants-- local gemIndex = 1; --BFA 1 gem for each item. local GemName, GemLink = GetItemGem(itemLink, gemIndex); if GemLink then local GemID = GetItemInfoInstant(GemLink) --local _, _, _, _, _, _, _, _, _, GemIcon, _, _, itemSubClassID = GetItemInfo(GemLink) local _, _, _, _, GemIcon, _, itemSubClassID = GetItemInfoInstant(GemLink); statsTable.GemIcon = GemIcon statsTable.gems = 1; if GemInfo[GemID] then local GemInfo = GemInfo[GemID] statsTable.GemPos = GemInfo[1]; if GemInfo[1] == "crit" then statsTable.crit = statsTable.crit + GemInfo[2]; elseif GemInfo[1] == "haste" then statsTable.haste = statsTable.haste + GemInfo[2]; elseif GemInfo[1] == "mastery" then statsTable.mastery = statsTable.mastery + GemInfo[2]; elseif GemInfo[1] == "versatility" then statsTable.versatility = statsTable.versatility + GemInfo[2]; elseif GemInfo[1] == "AGI" or GemInfo[1] == "STR" or GemInfo[1] == "INT" then statsTable.prim = statsTable.prim + GemInfo[2]; statsTable.GemPos = "prim"; end end end local EnchantID = GetItemEnchant(itemLink) if EnchantID ~= 0 and EnchantInfo[EnchantID] then local EnchantInfo = EnchantInfo[EnchantID] statsTable.EnchantPos = EnchantInfo[1]; if EnchantInfo[1] == "crit" then statsTable.crit = statsTable.crit + EnchantInfo[2]; elseif EnchantInfo[1] == "haste" then statsTable.haste = statsTable.haste + EnchantInfo[2]; elseif EnchantInfo[1] == "mastery" then statsTable.mastery = statsTable.mastery + EnchantInfo[2]; elseif EnchantInfo[1] == "versatility" then statsTable.versatility = statsTable.versatility + EnchantInfo[2]; elseif EnchantInfo[1] == "AGI" or EnchantInfo[1] == "STR" or EnchantInfo[1] == "INT" then statsTable.prim = statsTable.prim + EnchantInfo[2]; statsTable.EnchantPos = "prim"; end statsTable.EnchantSpellID = EnchantInfo[3]; end return statsTable; end function NarciAPI_GetItemStatsFromSlot(slotID) local itemLocation = ItemLocation:CreateFromEquipmentSlot(slotID); local itemLink = C_Item.GetItemLink(itemLocation) return GetItemStats(itemLink); end -------------------- ----Tooltip Scan---- -------------------- local TP = CreateFrame("GameTooltip", "NarciVirtualTooltip", nil, "GameTooltipTemplate"); TP:SetScript("OnLoad", GameTooltip_OnLoad); TP:SetOwner(UIParent, 'ANCHOR_NONE'); local SocketAction = ITEM_SOCKETABLE; local find = string.find; local SocketPath = "ItemSocketingFrame"; function NarciAPI_IsItemSocketable(itemLink, SocketID) if not itemLink then return; end if not SocketID then SocketID = 1; end local gemName, gemLink = GetItemGem(itemLink, SocketID) if gemName then return gemName, gemLink; end --]] local tex, texID; for i = 1, 3 do tex = _G["NarciVirtualTooltip".."Texture"..i] tex = tex:SetTexture(nil); end TP:SetHyperlink(itemLink); for i = 1, 3 do --max 10 tex = _G["NarciVirtualTooltip".."Texture"..i] texID = tex and tex:GetTexture(); --print(texID) if texID == 458977 then --no file name anymore 458977:Regular empty socket texture return "Empty", nil; end end --[[ for i = begin, num do local str = _G["NarciVirtualTooltip".."TextLeft"..i] if str and str:GetText() == SocketAction then print("Has Socket") return; end end --]] return nil, nil; end function NarciAPI_GetItemRank(itemLink, statName) --Items that can get upgraded if not itemLink then return; end TP:SetHyperlink(itemLink); local fontstring = _G["NarciVirtualTooltip".."TextLeft"..2]; fontstring = fontstring:GetText() or ""; fontstring = strtrim(fontstring, "|r"); local rank = string.match(fontstring, "%d+", -2) or ""; if statName then local stats = GetItemStats(itemLink) or {}; return "|cff00ccff"..rank.."|r", stats[statName] or 0 else return "|cff00ccff"..rank.."|r" end end local strtrim = strtrim; local gsub = gsub; local greyFont = "|cff959595"; local leftBrace = "%("; local rightBrace = "%)"; if (GetLocale() == "zhCN") or (GetLocale() == "zhTW") then leftBrace = "(" rightBrace = ")" end local SOURCE_KNOWN = TRANSMOGRIFY_TOOLTIP_APPEARANCE_KNOWN; local APPEARANCE_KNOWN = TRANSMOGRIFY_TOOLTIP_ITEM_UNKNOWN_APPEARANCE_KNOWN; local APPEARANCE_UNKNOWN = TRANSMOGRIFY_TOOLTIP_APPEARANCE_UNKNOWN; function NarciAPI_IsAppearanceKnown(itemLink) --Need to correspond with C_TransmogCollection.PlayerHasTransmog if not itemLink then return; end TP:SetHyperlink(itemLink); local str; local num = TP:NumLines(); for i = num, num - 2, -1 do str = nil; str = _G["NarciVirtualTooltip".."TextLeft"..i] if not str then return false; else str = str:GetText(); end if str == SOURCE_KNOWN or str == APPEARANCE_KNOWN then return true; elseif str == APPEARANCE_UNKNOWN then return false; end end return false; end local function trimComma(text) return strtrim(text, "::"); end local function formatString(text, removedText) text = strtrim(text, removedText); text = trimComma(text); text = strtrim(text); --remove space text = gsub(text, leftBrace, "\n\n"..greyFont) text = gsub(text, rightBrace, "|r") return text; end local onUse = ITEM_SPELL_TRIGGER_ONUSE; local onEquip = ITEM_SPELL_TRIGGER_ONEQUIP; local onProc = ITEM_SPELL_TRIGGER_ONPROC; local minLevel = SOCKETING_ITEM_MIN_LEVEL_I; local _onUse = trimComma(onUse) local _onEquip = trimComma(onEquip) local _onProc = trimComma(onProc) function NarciAPI_GetItemExtraEffect(itemLink) if not itemLink then return; end TP:SetHyperlink(itemLink); local num = TP:NumLines(); local begin = max(num - 6, 0); local output = ""; local category, str; for i = begin, num, 1 do str = nil; str = _G["NarciVirtualTooltip".."TextLeft"..i] if not str then return; else str = str:GetText(); end if find(str, onUse) then str = formatString(str, _onUse); if not category then category = _onUse; end --return _onUse, str; output = output..str.."\n\n" elseif find(str, onEquip) then str = formatString(str, _onEquip); if not category then category = _onEquip; end --return _onEquip, str; output = output..str.."\n\n" elseif find(str, onProc) then str = formatString(str, _onProc); if not category then category = _onProc; end --return _onProc, str; output = output..str.."\n\n" end end return category, output; end function NarciAPI_GetGemBonus(itemID) --itemID: Gem's Item ID or hyperlink if not itemID then return; end if type(itemID) == "number" then TP:SetItemByID(itemID) else TP:SetHyperlink(itemID) end local num = TP:NumLines(); local output; local str, level; for i = 1, num do str = _G["NarciVirtualTooltip".."TextLeft"..i] if not str then return; else str = str:GetText(); if not str then return; end end if strsub(str, 1, 1) == "+" then output = str; end if find(str, minLevel) then level = formatString(str, minLevel); end if level and output then return output, tonumber(level); end end return output, level; end function TestItemLinkAffix(from, to) local TP = TP; local max = max; local total = 0; local s = from --6500; local e = to --6600; local output; local itemLink; local function GetExtraInfo() itemLink = "\124cffa335ee\124Hitem:174954::::::::120::::2:1477:".. s ..":\124h[]\124h\124r"; TP:SetHyperlink(itemLink); local num = TP:NumLines(); local begin = max(num - 3, 0); local str; for i = begin, num, 1 do str = nil; str = _G["NarciVirtualTooltip".."TextLeft"..i] if not str then break; else str = str:GetText(); end if find(str, onEquip) then print("|cFFFFD100"..s.."|r "..str); break end end s = s + 1; total = total + 1; if s < e and total < 1000 then After(0, GetExtraInfo); else print("Search Complete") end end print("Search from "..s.." to "..e); for i = s, e do --Cache itemLink = "\124cffa335ee\124Hitem:174954::::::::120::::2:1477:".. i ..":\124h[]\124h\124r"; TP:SetHyperlink(itemLink); end After(1, GetExtraInfo); end -------------------- ---Formating API---- -------------------- function NarciAPI_FormatLargeNumbers(value) value = tonumber(value) or 0; local formatedNumber = "" if value >= 1000 and value < 1000000 then formatedNumber = strsub(value, 1, -4) .. "," .. strsub(value, -3); elseif value >= 1000000 and value < 1000000000 then formatedNumber = strsub(value, 1, -7) .. "," .. strsub(value, -6, -4) .. "," .. strsub(value, -3); else formatedNumber = tostring(value) end return formatedNumber end -------------------- ---Fade Frame API--- -------------------- local function SetFade_finishedFunc(frame) if frame.fadeInfo.mode == "OUT" then frame:Hide(); elseif frame.fadeInfo.mode == "IN" then frame:Show(); end end function NarciAPI_FadeFrame(frame, time, mode) if mode == "IN" then UIFrameFadeIn(frame, time, frame:GetAlpha(), 1); elseif mode == "OUT" then if not frame:IsShown() then return; end UIFrameFadeOut(frame, time, frame:GetAlpha(), 0); elseif mode == "Forced_IN" then UIFrameFadeIn(frame, time, 0, 1); elseif mode == "Forced_OUT" then UIFrameFadeOut(frame, time, 1, 0); end if not frame.fadeInfo then return; end frame.fadeInfo.finishedArg1 = frame; frame.fadeInfo.finishedFunc = SetFade_finishedFunc end ------------------------------------------------------------------ -------------------- ---UI Element API--- -------------------- NarciUIMixin = {}; function NarciUIMixin:Highlight(state) if state then self.Border.Highlight:SetAlpha(1); self.Border.Normal:SetAlpha(0); else self.Border.Highlight:SetAlpha(0); self.Border.Normal:SetAlpha(1); end end function NarciUIMixin:SetColor(r, g, b) if self.Color then self.Color:SetColorTexture(r/255, g/255, b/255); end end local screenWidth, screenHeight = GetPhysicalScreenSize(); local UIParentWidth, UIParentHeight = UIParent:GetSize(); function NarciAPI_OptimizeBorderThickness(self) if not self.HasOptimized then local point, relativeTo, relativePoint, xOfs, yOfs = self:GetPoint() local uiScale = self:GetEffectiveScale(); --local scale = string.match(GetCVar( "gxWindowedResolution" ), "%d+x(%d+)" ); --local rate = 768/scale/uiScale; --local _, screenHeight = GetPhysicalScreenSize(); local rate = (768/screenHeight)/uiScale local borderWeight = 2.0; local weight = borderWeight * rate; local weight2 = weight * math.sqrt(2); self.Border:SetPoint("TOPLEFT", self, "TOPLEFT", weight, -weight) self.Border:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", -weight, weight) if self.ThumbBorder then self.ThumbBorder:SetPoint("TOPLEFT", self.VirtualThumb, -weight2, weight2) self.ThumbBorder:SetPoint("BOTTOMRIGHT", self.VirtualThumb,weight2, -weight2) end if self.Marks then for i=1, #self.Marks do self.Marks[i]:SetWidth(weight); end end self.HasOptimized = true; end end local OptimizeBorderThickness = NarciAPI_OptimizeBorderThickness; function NarciAPI_SliderWithSteps_OnLoad(self) self.oldValue = -1208; self.Marks = {}; local width = self:GetWidth(); local step = self:GetValueStep(); local sliderMin, sliderMax = self:GetMinMaxValues() local range = sliderMax - sliderMin; local num_Gap = math.floor((range / step) + 0.5); if num_Gap == 0 then return; end; local tex; local markOffset = 5; width = width - 2*markOffset --print(self:GetName().." "..(num_Gap + 1)) for i=1, (num_Gap + 1) do tex = self:CreateTexture(nil, "BACKGROUND", nil, 1); --tex:SetAllPoints() tex:SetSize(2, 10) tex:SetColorTexture(0.3, 0.3, 0.3, 1) --print((i-1)*width/num_Gap) tex:SetPoint("LEFT", self, "LEFT", markOffset + (i-1)*width/num_Gap, 0) tinsert(self.Marks, tex); end end --Internal Keybinding NarciGenericKeyBindingButtonMixin = {}; local function ResetBindVisualAndScript(self) self.Border:SetColorTexture(0, 0, 0); self.Value:SetTextColor(1, 1, 1); self.Value:SetShadowColor(0, 0, 0); self.Value:SetShadowOffset(0.6, -0.6); self:SetPropagateKeyboardInput(true) self:SetScript("OnKeyDown", nil); --self:SetScript("OnKeyUp", nil); self.IsOn = false; end local function GenericKeyBindingButton_OnKeydown(self, key) if key == "ESCAPE" or key == "SPACE" or key == "ENTER" then self:ExitKeyBinding(); return end if self.keyValue then self:ExitKeyBinding(true); NarcissusDB[self.keyValue] = key; end end function NarciGenericKeyBindingButtonMixin:ExitKeyBinding(success) ResetBindVisualAndScript(self); After(0, function() self:GetBindingKey(); end) if success then self.Highlight:SetColorTexture(0.4862, 0.7725, 0.4627); self.Description:SetText("|cff7cc576".. KEY_BOUND); UIFrameFadeIn(self.Highlight, 0.2, 0, 1); UIFrameFadeIn(self.Description, 0.2, 0, 1); self.Timer:Stop(); self.Timer:SetScript("OnFinished", function() UIFrameFadeOut(self.Highlight, 0.5, 1, 0); UIFrameFadeOut(self.Description, 0.5, 1, 0); end); self.Timer:Play(); end end function NarciGenericKeyBindingButtonMixin:GetBindingKey() OptimizeBorderThickness(self); if self.keyValue then self.Value:SetText(NarcissusDB[self.keyValue] or NOT_BOUND); else self.Value:SetText(NARCI_COLOR_RED_MILD.. "No Action"); end end function NarciGenericKeyBindingButtonMixin:ReleaseBindingKey() ResetBindVisualAndScript(self); if self.keyValue then self.Value:SetText(self.defaultKey or NOT_BOUND); NarcissusDB[self.keyValue] = self.defaultKey; self.Highlight:SetColorTexture(0.9333, 0.1961, 0.1412); self.Description:SetText(NARCI_COLOR_RED_MILD.."Hotkey reset"); UIFrameFadeIn(self.Description, 0.2, 0, 1); UIFrameFadeIn(self.Highlight, 0.2, 0, 1); self.Timer:Stop(); self.Timer:SetScript("OnFinished", function() UIFrameFadeOut(self.Highlight, 0.5, 1, 0); UIFrameFadeOut(self.Description, 0.5, 1, 0); end); self.Timer:Play(); end end function NarciGenericKeyBindingButtonMixin:OnClick(button) self.IsOn = not self.IsOn; if button == "LeftButton" then if self.IsOn then self.Border:SetColorTexture(0.9, 0.9, 0.9); self.Value:SetTextColor(0, 0, 0); self.Value:SetShadowColor(1, 1, 1); self.Value:SetShadowOffset(0.6, -0.6); self:SetPropagateKeyboardInput(false); self:SetScript("OnKeyDown", GenericKeyBindingButton_OnKeydown); end else self:ReleaseBindingKey(); end end function NarciGenericKeyBindingButtonMixin:OnHide() self:StopAnimating(); end -----Smooth Scroll----- local min = math.min; local max = math.max; local minOffset = 2; local function SmoothScrollContainer_OnUpdate(self, elapsed) local delta = self.delta; local scrollBar = self.scrollBar; local value = scrollBar:GetValue(); local step = max(abs(value - self.endValue)*(self.timeRatio) , self.minOffset); --if the step (Δy) is too small, the fontstring will jitter. local remainedStep; if ( delta == 1 ) then --Up remainedStep = min(self.endValue - value, 0); if - remainedStep <= ( self.minOffset) then self:Hide(); scrollBar:SetValue(min(self.maxVal, self.endValue)); else scrollBar:SetValue(max(0, value - step)); end else remainedStep = max(self.endValue - value, 0); if remainedStep <= ( self.minOffset) then self:Hide(); scrollBar:SetValue(min(self.maxVal, self.endValue)); else scrollBar:SetValue(min(self.maxVal, value + step)); end end end local function NarciAPI_SmoothScroll_OnMouseWheel(self, delta, stepSize) if ( not self.scrollBar:IsVisible() ) then return; end local ScrollContainer = self.SmoothScrollContainer; local stepSize = stepSize or self.stepSize or self.buttonHeight; ScrollContainer.stepSize = stepSize; ScrollContainer.maxVal = self.range self.scrollBar:SetValueStep(0.01); ScrollContainer.delta = delta; local Current = self.scrollBar:GetValue(); if not((Current == 0 and delta > 0) or (Current == self.range and delta < 0 )) then ScrollContainer:Show() end local deltaRatio = ScrollContainer.deltaRatio or 1; local endValue = min(max(0, ScrollContainer.endValue - delta*deltaRatio*self.buttonHeight), self.range); ScrollContainer.endValue = endValue; if self.positionFunc then self.positionFunc(endValue); end end function NarciAPI_SmoothScroll_Initialization(self, updatedList, updateFunc, deltaRatio, timeRatio, minOffset, positionFunc) --self=ListScrollFrame self.update = updateFunc; self.positionFunc = positionFunc; self.updatedList = UpdatedList; local parentName = self:GetName(); local frameName = parentName and (parentName .. "SmoothScrollContainer") or nil; local SmoothScrollContainer = CreateFrame("Frame", frameName, self); SmoothScrollContainer:Hide(); local scale = string.match(GetCVar( "gxWindowedResolution" ), "%d+x(%d+)" ); local uiScale = self:GetEffectiveScale(); --local pixel = 768/scale/uiScale; --local _, screenHeight = GetPhysicalScreenSize(); local pixel = (768/screenHeight)/uiScale; self.scrollBar:SetValueStep(0.001); SmoothScrollContainer.stepSize = 0; SmoothScrollContainer.delta = 0; SmoothScrollContainer.animationDuration = 0; SmoothScrollContainer.endValue = 0; SmoothScrollContainer.maxVal = 0; SmoothScrollContainer.deltaRatio = deltaRatio or 1; SmoothScrollContainer.timeRatio = timeRatio or 1; SmoothScrollContainer.minOffset = minOffset or pixel; SmoothScrollContainer.scrollBar = self.scrollBar; SmoothScrollContainer:SetScript("OnUpdate", SmoothScrollContainer_OnUpdate); SmoothScrollContainer:SetScript("OnShow", function(self) self.endValue = self:GetParent().scrollBar:GetValue(); end); self.SmoothScrollContainer = SmoothScrollContainer; self:SetScript("OnMouseWheel", NarciAPI_SmoothScroll_OnMouseWheel); --a position-related function end -----Create A List of Button---- function NarciAPI_BuildButtonList(self, buttonTemplate, buttonNameTable, initialOffsetX, initialOffsetY, initialPoint, initialRelative, offsetX, offsetY, point, relativePoint) local button, buttonHeight, buttons, numButtons; local parentName = self:GetName(); local buttonName = parentName and (parentName .. "Button") or nil; initialPoint = initialPoint or "TOPLEFT"; initialRelative = initialRelative or "TOPLEFT"; initialOffsetX = initialOffsetX or 0; initialOffsetY = initialOffsetY or 0; point = point or "TOPLEFT"; relativePoint = relativePoint or "BOTTOMLEFT"; offsetX = offsetX or 0; offsetY = offsetY or 0; if ( self.buttons ) then buttons = self.buttons; buttonHeight = buttons[1]:GetHeight(); else button = CreateFrame("BUTTON", buttonName and (buttonName .. 1) or nil, self, buttonTemplate); buttonHeight = button:GetHeight(); button:SetPoint(initialPoint, self, initialRelative, initialOffsetX, initialOffsetY); button:SetID(0); buttons = {} button.Name:SetText(buttonNameTable[1]) tinsert(buttons, button); end local numButtons = #buttonNameTable; for i = 2, numButtons do button = CreateFrame("BUTTON", buttonName and (buttonName .. i) or nil, self, buttonTemplate); button:SetPoint(point, buttons[i-1], relativePoint, offsetX, offsetY); button:SetID(i-1); button.Name:SetText(buttonNameTable[i]) tinsert(buttons, button); end self.buttons = buttons; end -----Language Adaptor----- function Narci_LanguageDetector(string) local str = string local len = strlen(str) local i = 1 while i <= len do local c = string.byte(str, i) local shift = 1 --print(c) if (c > 0 and c <= 127)then shift = 1 elseif c== 195 then shift = 2 --Latin/Greek elseif (c >= 208 and c <=211) then shift = 2 return "RU" --RU included elseif (c >= 224 and c <= 227) then shift = 3 --JP return "JP" elseif (c >= 228 and c <= 233) then shift = 3 --CN return "CN" elseif (c >= 234 and c <= 237) then shift = 3 --KR return "KR" elseif (c >= 240 and c <= 244) then shift = 4 --Unknown invalid end local char = string.sub(str, i, i+shift-1) i = i + shift end return "RM" end --[[ function LDTest(string) local str = string local lenInByte = #str for i=1,lenInByte do local char = strsub(str, i,i) local curByte = string.byte(str, i) print(char.." "..curByte) end return "roman" end local Eng = "abcdefghijklmnopqrstuvwxyz" --abcdefghijklmnopqrstuvwxyz Z~90 z~122 1-1 local DE = "äöüß" --195 1-2 local CN = "乀氺" --228 229 230 233 HEX E4-E9 Hexadecimal UTF-8 CJK local KR = "제" --237 236 235 234 1-3 EB-ED local RU = "ѱӧ" --D0400-D04C0 208 209 210 211 1-2 local FR = "ÀÃÇÊÉÕàãçêõáéíóúà" --1-2 195 C3 -PR local JP = "ひらがな" --1-3 227 E3 Kana --LDTest("繁體繁体") --local language = LanguageDetector("繁體中文") --print("Str is: "..language) --]] local LanguageDetector = Narci_LanguageDetector; local PlayerNameFont={ ["CN"] = "Interface\\AddOns\\Narcissus\\Font\\NotoSansCJKsc-Medium.otf", ["RM"] = "Interface\\AddOns\\Narcissus\\Font\\SemplicitaPro-Semibold.otf", ["RU"] = "Interface\\AddOns\\Narcissus\\Font\\NotoSans-Medium.ttf", ["KR"] = "Interface\\AddOns\\Narcissus\\Font\\NotoSansCJKsc-Medium.otf", ["JP"] = "Interface\\AddOns\\Narcissus\\Font\\NotoSansCJKsc-Medium.otf", } local EditBoxFont={ ["CN"] = {"Interface\\AddOns\\Narcissus\\Font\\NotoSansCJKsc-Medium.otf", 8}, ["RM"] = {"Interface\\AddOns\\Narcissus\\Font\\SourceSansPro-Semibold.ttf", 9}, ["RU"] = {"Interface\\AddOns\\Narcissus\\Font\\NotoSans-Medium.ttf", 8}, ["KR"] = {"Interface\\AddOns\\Narcissus\\Font\\NotoSansCJKsc-Medium.otf", 8}, ["JP"] = {"Interface\\AddOns\\Narcissus\\Font\\NotoSansCJKsc-Medium.otf", 8}, } --SetTextColor(0.85098, 0.80392, 0.70588) local function SmartFontType(self, height, fontTable) local str = self:GetText(); local Language = LanguageDetector(str); --print(str.." Language is: "..Language); local Height = self:GetHeight(); if Language and fontTable[Language] then self:SetFont(fontTable[Language] , Height); end end local function SmartEditBoxFont(self, extraHeight) local str = self:GetText(); local Language = LanguageDetector(str); if Language and EditBoxFont[Language] then local height = extraHeight or 0; self:SetFont(EditBoxFont[Language][1] , EditBoxFont[Language][2] + height); end end function NarciAPI_SmartFontType(self, height) SmartFontType(self, height, PlayerNameFont); end function NarciAPI_SmartEditBoxType(self, extraHeight) SmartEditBoxFont(self, extraHeight); end function NarciAPI_EditBox_OnLanguageChanged(self, language) SmartEditBoxFont(self); end -----Filter Shared Functions----- function NarciAPI_LetterboxAnimation(command) local frame = Narci_FullScreenMask; frame:StopAnimating(); if command == "IN" then frame:Show(); frame.BottomMask.animIn:Play(); frame.TopMask.animIn:Play(); elseif command == "OUT" then frame.BottomMask.animOut:Play(); frame.TopMask.animOut:Play(); else if NarcissusDB.LetterboxEffect then Narci_PhotoModeController.PhotoModeController_AnimFrame.toAlpha = 0 frame:Show(); frame.BottomMask.animIn:Play(); frame.TopMask.animIn:Play(); end end end -----Format Normalization----- local function SplitTooltipByLineBreak(str) local str1, _, str2 = strsplit("\n", str); return str1 or "", str2 or ""; end NARCI_CRIT_TOOLTIP, NARCI_CRIT_TOOLTIP_FORMAT = SplitTooltipByLineBreak(CR_CRIT_TOOLTIP); _, NARCI_HASTE_TOOLTIP_FORMAT = SplitTooltipByLineBreak(STAT_HASTE_BASE_TOOLTIP); NARCI_VERSATILITY_TOOLTIP_FORMAT_1, NARCI_VERSATILITY_TOOLTIP_FORMAT_2 = SplitTooltipByLineBreak(CR_VERSATILITY_TOOLTIP); -----Delayed Tooltip----- local timeDelay = 0.6; local GetCursorPosition = GetCursorPosition; local DelayedTP = CreateFrame("Frame"); DelayedTP:Hide(); DelayedTP:SetScript("OnShow", function(self) self.TotalTime = 0; --Total time after ShowDelayedTooltip gets called --self.ScanTime = 0; --Cursor scaning time --self.CursorX, self.CursorY = GetCursorPosition(); --Cursor position end) DelayedTP:SetScript("OnHide", function(self) self.TotalTime = 0; --self.ScanTime = 0; end) DelayedTP:SetScript("OnUpdate", function(self, elapsed) self.TotalTime = self.TotalTime + elapsed; --self.ScanTime = self.ScanTime + elapsed; if self.TotalTime >= timeDelay then if self.focus and self.focus == GetMouseFocus() then NarciGameTooltip:ClearAllPoints(); NarciGameTooltip:SetPoint(self.point, self.relativeTo, self.relativePoint, self.ofsx, self.ofsy); UIFrameFadeIn(NarciGameTooltip, 0.12, 0, 1); end self:Hide(); end end) function NarciAPI_ShowDelayedTooltip(point, relativeTo, relativePoint, ofsx, ofsy) local TP = DelayedTP; TP.focus = GetMouseFocus(); TP.point, TP.relativeTo, TP.relativePoint, TP.ofsx, TP.ofsy = point, relativeTo, relativePoint, ofsx, ofsy; TP:Hide(); TP:Show(); end -----Run Delayed Function----- local DelayedFunc = CreateFrame("Frame"); DelayedFunc:Hide(); DelayedFunc.delay = 0; DelayedFunc.t = 0; DelayedFunc:SetScript("OnHide", function(self) self.focus = nil; self.t = 0; end) DelayedFunc:SetScript("OnUpdate", function(self, elapsed) self.t = self.t + elapsed; if self.t >= self.delay then if self.focus == GetMouseFocus() then self.func(); end self:Hide(); end end) function NarciAPI_RunDelayedFunction(frame, delay, func) DelayedFunc:Hide(); if func and type(func) == "function" then delay = delay or 0; DelayedFunc.focus = frame; DelayedFunc.delay = delay; DelayedFunc.func = func; DelayedFunc:Show(); end end -----Alert Frame----- NarciAlertFrameMixin = {}; local function CreateErrorAnimation(frame) if frame.animError then return; end; local ag = frame:CreateAnimationGroup() local a1 = ag:CreateAnimation("Translation") a1:SetOrder(1); a1:SetOffset(4, 0); a1:SetDuration(0.05); local a2 = ag:CreateAnimation("Translation") a2:SetOrder(2); a2:SetOffset(-8, 0); a2:SetDuration(0.1); local a3 = ag:CreateAnimation("Translation") a3:SetOrder(3); a3:SetOffset(8, 0); a3:SetDuration(0.1); local a4 = ag:CreateAnimation("Translation") a4:SetOrder(4); a4:SetOffset(-4, 0); a4:SetDuration(0.05); frame.animError = ag; end function NarciAlertFrameMixin:SetAnchor(frame, offsetY, AddErrorAnimation) frame:RegisterEvent("UI_ERROR_MESSAGE"); self:Hide(); self:ClearAllPoints(); self:SetScale(Narci_Character:GetEffectiveScale()) local y = offsetY or -12; self:SetPoint("BOTTOM", frame, "TOP", 0, y); self:SetFrameLevel(50) self.anchor = frame; if AddErrorAnimation then CreateErrorAnimation(frame); end After(0.5, function() frame:UnregisterEvent("UI_ERROR_MESSAGE"); end) end function NarciAlertFrameMixin:AddMessage(msg, UseErrorAnimation) self.Text:SetText(msg); self:SetHeight(self.Background:GetHeight()); UIFrameFadeIn(self, 0.2, self:GetAlpha(), 1); PlaySound(138528); --Mechagon_HK8_Lockon local anchorFrame = self.anchor; if anchorFrame then if anchorFrame.animError and UseErrorAnimation then anchorFrame.animError:Play(); end anchorFrame:UnregisterEvent("UI_ERROR_MESSAGE"); end end ------------------------ --Filled Bar Animation-- ------------------------ local cos = math.cos; local pi = math.pi; local function inOutSine(t, b, c, d) return -c / 2 * (cos(pi * t / d) - 1) + b end local FluidAnim = CreateFrame("Frame"); FluidAnim:Hide(); FluidAnim.d = 0.5; FluidAnim.d1 = 0.25; FluidAnim.d2 = 0.5; local function FluidLevel(self, elapsed) self.t = self.t + elapsed; local height = inOutSine(self.t, self.startHeight, self.endHeight - self.startHeight, self.d); if self.t >= self.d then height = self.endHeight; self:Hide(); end self.Fluid:SetHeight(height); end local function FluidUp(self, elapsed) self.t = self.t + elapsed; local height; if self.t <= self.d1 then height = inOutSine(self.t, self.startHeight, 84 - self.startHeight, self.d1); elseif self.t < self.d3 then if not self.colorChanged then self.colorChanged = true; self.Fluid:SetColorTexture(self.r, self.g, self.b); end height = inOutSine(self.t - self.d1, 0.01, self.endHeight, self.d2); else height = self.endHeight; self:Hide(); end self.Fluid:SetHeight(height); end local function FluidDown(self, elapsed) self.t = self.t + elapsed; local height; if self.t <= self.d1 then height = inOutSine(self.t, self.startHeight, 0.01 - self.startHeight, self.d1); elseif self.t < self.d3 then if not self.colorChanged then self.colorChanged = true; self.Fluid:SetColorTexture(self.r, self.g, self.b); end height = inOutSine(self.t - self.d1, 84, self.endHeight - 84, self.d2); else height = self.endHeight; self:Hide(); end self.Fluid:SetHeight(height); end FluidAnim:SetScript("OnShow", function(self) self.t = 0; self.colorChanged = false; end); function NarciAPI_SmoothFluid(bar, newHeight, newLevel, r, g, b) local FluidAnim = FluidAnim; FluidAnim:Hide(); FluidAnim.endHeight = newHeight; FluidAnim.Fluid = bar; FluidAnim.r, FluidAnim.g, FluidAnim.b = r, g, b; local oldLevel = FluidAnim.oldCorruptionLevel or newLevel; FluidAnim.oldCorruptionLevel = newLevel; local t1, t2; local h = FluidAnim.Fluid:GetHeight(); FluidAnim.startHeight = h; if newLevel == oldLevel then FluidAnim:SetScript("OnUpdate", FluidLevel); FluidAnim.d = math.max( math.abs(h - FluidAnim.endHeight) / 84 , 0.35); bar:SetColorTexture(r, g, b); elseif newLevel < oldLevel then FluidAnim:SetScript("OnUpdate", FluidDown); t1 = math.max(h / 84, 0); t2 = math.max((84 - FluidAnim.endHeight) / 84, 0.4); FluidAnim.d1 = t1 FluidAnim.d2 = t2 FluidAnim.d3 = t1 + t2; else FluidAnim:SetScript("OnUpdate", FluidUp); t1 = math.max((84 - h) / 84, 0); t2 = math.max(FluidAnim.endHeight / 84, 0.4); FluidAnim.d1 = t1 FluidAnim.d2 = t2 FluidAnim.d3 = t1 + t2; end After(0, function() FluidAnim:Show(); end) return t1 end local EyeballTexture = "Interface\\AddOns\\Narcissus\\ART\\Widgets\\CorruptionSystem\\Eyeball-Orange"; local CorruptionColor = "|cfff57f20"; local FluidColors = {0.847, 0.349, 0.145}; function NarciAPI_GetEyeballColor() return EyeballTexture, CorruptionColor, FluidColors[1], FluidColors[2], FluidColors[3]; end function NarciAPI_SetEyeballColor(index) if index == 4 then EyeballTexture = "Interface\\AddOns\\Narcissus\\ART\\Widgets\\CorruptionSystem\\Eyeball-Blue"; CorruptionColor = "|cff83c7e7"; FluidColors = {0.596, 0.73, 0.902}; elseif index == 2 then EyeballTexture = "Interface\\AddOns\\Narcissus\\ART\\Widgets\\CorruptionSystem\\Eyeball-Purple"; CorruptionColor = "|cfff019ff"; FluidColors = {0.87, 0.106, 0.949}; elseif index == 3 then EyeballTexture = "Interface\\AddOns\\Narcissus\\ART\\Widgets\\CorruptionSystem\\Eyeball-Green"; CorruptionColor = "|cff8cdacd"; FluidColors = {0.56, 0.855, 0.757}; else index = 1; EyeballTexture = "Interface\\AddOns\\Narcissus\\ART\\Widgets\\CorruptionSystem\\Eyeball-Orange"; CorruptionColor = "|cfff57f20"; FluidColors = {0.847, 0.349, 0.145}; end NarcissusDB.EyeColor = index; local Preview = Narci_EyeColorPreview; local ColorButtons = Preview:GetParent().ColorButtons; Preview:SetTexCoord(0.25*(index - 1), 0.25*index, 0, 1); for i = 1, #ColorButtons do ColorButtons[i]:Highlight(false); end ColorButtons[index]:Highlight(true); Narci:SetItemLevel(); end -------------------- --UI 3D Animation--- -------------------- Narci.AnimSequenceInfo = { ["Controller"] = { ["TotalFrames"] = 30, ["cX"] = 0.205078125, ["cY"] = 0.1171875, ["Column"] = 4, ["Row"] = 8, }, ["Heart"] = { ["TotalFrames"] = 28, ["cX"] = 0.25, ["cY"] = 0.140625, ["Column"] = 4, ["Row"] = 7, }, ["ActorPanel"] = { ["TotalFrames"] = 26, ["cX"] = 0.4296875, ["cY"] = 0.056640625, ["Column"] = 2, ["Row"] = 17, }, } function NarciAPI_PlayAnimationSequence(index, SequenceInfo, Texture) local Frames = SequenceInfo["TotalFrames"]; local cX, cY = SequenceInfo["cX"], SequenceInfo["cY"]; local Column, Row = SequenceInfo["Column"], SequenceInfo["Row"] if index > Frames or index < 1 then return false; end local n = math.modf((index -1)/ Row) + 1; local m = index % Row if m == 0 then m = Row; end local left, right = (n-1)*cX, n*cX; local top, bottom = (m-1)*cY, m*cY; Texture:SetTexCoord(left, right, top, bottom); Texture:SetAlpha(1) return true; end -------------------- -----Play Voice----- -------------------- local _, _, raceID = UnitRace("player"); local genderID = UnitSex("player") or 2; raceID = raceID or 1; genderID = genderID - 1; --(2→1) Male (3→2) Female if raceID == 25 or raceID == 26 then --Pandaren faction raceID = 24; end local VOICE_BY_RACE = { --[raceID] = { [gender] = {Error_NoTarget, } } [1] = {[1] = {1906, 2669, }, [2] = {2030, 2681, }}, --1 Human [2] = {[1] = {2317, 2693, }, [2] = {2372, 2705, }}, --2 Orc [3] = {[1] = {1614, 2717, }, [2] = {1684, 2729, }}, --3 Dwarf [4] = {[1] = {56231, 56311, }, [2] = {56096, 56174, }}, --4 NE [5] = {[1] = {2085, 2765, }, [2] = {2205, 2777, }}, --5 UD [6] = {[1] = {2459, 2789, }, [2] = {2458, 2802, }}, --6 Tauren [7] = {[1] = {1741, 2827, }, [2] = {1796, 2839, }}, --7 Gnome [8] = {[1] = {1851, 2851, }, [2] = {1961, 2863, }}, --8 Troll [9] = {[1] = {19109, 19137, }, [2] = {19218, 19246}}, --9 Goblin [10] = {[1] = {9597, 9664, }, [2] = {9598, 9624, }}, --10 BloodElf [11] = {[1] = {9463, 9714, }, [2] = {9514, 9689, }}, --11 Goat [22] = {[1] = {18991, 19346, }, [2] = {18719, 19516, }}, --22 Worgen [24] = {[1] = {28846, 28924, }, [2] = {29899, 29812, }}, --24 Pandaren [27] = {[1] = {96356, 96383, }, [2] = {96288, 96315, }}, --27 Nightborne [28] = {[1] = {95931, 95844, }, [2] = {95510, 95543, }}, --28 Highmountain Tauren [29] = {[1] = {95636, 95665, }, [2] = {95806, 95857, }}, --29 Void Elf [30] = {[1] = {96220, 96247, }, [2] = {96152, 96179, }}, --30 Light-forged [31] = {[1] = {127289, 1273128, }, [2] = {126915, 126944, }}, --31 Zandalari [32] = {[1] = {127102, 127131, }, [2] = {127008, 127037, }}, --32 Kul'Tiran [34] = {[1] = {101933, 101962, }, [2] = {101859, 101888, }}, --36 Dark Iron Dwarf [35] = {[1] = {144073, 144111, }, [2] = {143981, 144019, }}, --35 Vulpera [36] = {[1] = {110370, 110399, }, [2] = {110295, 110324, }}, --36 Mag'har [37] = {[1] = {143863, 143892, }, [2] = {144223, 144275, }}, --37 Mechagnome!!!! } local ERROR_NOTARGET, ALERT_INCOMING; if VOICE_BY_RACE[raceID] then ERROR_NOTARGET = VOICE_BY_RACE[raceID][genderID][1]; ALERT_INCOMING = VOICE_BY_RACE[raceID][genderID][2]; end ERROR_NOTARGET = ERROR_NOTARGET or 2030; ALERT_INCOMING = ALERT_INCOMING or 2669; function Narci:PlayVoice(name) if name == "ERROR" then PlaySound(ERROR_NOTARGET, "Dialog"); elseif name == "DANGER" then PlaySound(ALERT_INCOMING, "Dialog"); end end --Time --C_DateAndTime.GetCurrentCalendarTime local ActorIDByRace = { --local GenderID = UnitSex(unit); 2 Male 3 Female --[raceID] = {male actorID, female actorID, bustOffsetZ_M, bustOffsetZ_F}, [2] = {483, 483}, -- Orc bow [3] = {471, nil}, -- Dwarf [5] = {472, 487}, -- UD 0.9585 seems small [6] = {449, 484}, -- Tauren [7] = {450, 450}, -- Gnome [8] = {485, 486}, -- Troll 0.9414 too high? [9] = {476, 477}, -- Goblin [11] = {475, 501}, -- Goat [22] = {474, 500}, -- Worgen [24] = {473, 473}, -- Pandaren [28] = {490, 491}, -- Highmountain Tauren [30] = {488, 489}, -- Lightforged Draenei [31] = {492, 492}, -- Zandalari [32] = {494, 497}, -- Kul'Tiran [34] = {499, nil}, -- Dark Iron Dwarf [35] = {924, 923}, -- Vulpera [36] = {495, 498}, -- Mag'har [37] = {929, 931}, -- Mechagnome } local ZoomDistanceByRace = { --[raceID] = {male Zoom, female Zoom, bustOffsetZ_M, bustOffsetZ_F}, [1] = {2.4, 2}, -- Human [2] = {2.5, 2}, -- Orc bow [3] = {2.5, 2}, -- Dwarf [4] = {2.2, 2.1}, -- Night Elf [5] = {2.5, 2}, -- UD [6] = {3, 2.5}, -- Tauren [7] = {2.6, 2.8}, -- Gnome [8] = {2.5, 2}, -- Troll [9] = {2.9, 2.9}, -- Goblin [10] = {2, 2}, -- Blood Elf [11] = {2.4, 2}, -- Goat [22] = {2.8, 2}, -- Worgen [24] = {2.9, 2.4}, -- Pandaren [27] = {2, 2}, -- Nightborne --[29] = {2, 2}, -- Void Elf --[28] = {2, 2}, -- Highmountain Tauren --[30] = {2, 2}, -- Lightforged Draenei [31] = {2.2, 2}, -- Zandalari [32] = {2.4, 2.3}, -- Kul'Tiran --[34] = {2, 2}, -- Dark Iron Dwarf [35] = {2.6, 2.1}, -- Vulpera --[36] = {2, 2}, -- Mag'har --[37] = {2, 2}, -- Mechagnome } function NarciAPI_GetCameraZoomDistanceByUnit(unit) if not UnitExists(unit) or not UnitIsPlayer(unit) or not CanInspect(unit, false) then return; end local _, _, raceID = UnitRace(unit); local genderID = UnitSex(unit); if raceID == 25 or raceID == 26 then --Pandaren A|H raceID = 24; elseif raceID == 29 then raceID = 10; elseif raceID == 37 then raceID = 7; elseif raceID == 30 then raceID = 11; elseif raceID == 28 then raceID = 6; elseif raceID == 34 then raceID = 3; elseif raceID == 36 then raceID = 2; elseif raceID == 22 then if unit == "player" then local _, inAlternateForm = HasAlternateForm(); if not inAlternateForm then --Wolf raceID = 22; else raceID = 1; end end end if not (raceID and genderID) then return 2 elseif ZoomDistanceByRace[raceID] then return ZoomDistanceByRace[raceID][genderID - 1] or 2; else return 2 end end local DEFAULT_ACTOR_INFO_ID = 438; local PanningYOffsetByRace = { --[raceID] = { { male = {offsetY1 when frame maximiazed, offsetY2} }, {female = ...} } [0] = { --default {-290, -110}, }, [4] = { --NE {-317, -117}, {-282, -115.5}, }, [10] = { --BE {-282, -110}, {-290, -116}, } --/dump DressUpFrame.ModelScene:GetActiveCamera().panningYOffset } PanningYOffsetByRace[29] = PanningYOffsetByRace[10]; local function GetPanningYOffset(raceID, genderID) genderID = genderID -1; if PanningYOffsetByRace[raceID] and PanningYOffsetByRace[raceID][genderID] then return PanningYOffsetByRace[raceID][genderID] else return PanningYOffsetByRace[0][1] end end local GetModelSceneActorInfoByID = C_ModelInfo.GetModelSceneActorInfoByID; function NarciAPI_GetActorInfoByUnit(unit) if not UnitExists(unit) or not UnitIsPlayer(unit) or not CanInspect(unit, false) then return nil, PanningYOffsetByRace[0][1]; end local _, _, raceID = UnitRace(unit); local genderID = UnitSex(unit); if raceID == 25 or raceID == 26 then --Pandaren A|H raceID = 24 end local actorInfoID; if not (raceID and genderID) then actorInfoID = DEFAULT_ACTOR_INFO_ID; --438 elseif ActorIDByRace[raceID] then actorInfoID = ActorIDByRace[raceID][genderID - 1] or DEFAULT_ACTOR_INFO_ID; else actorInfoID = DEFAULT_ACTOR_INFO_ID; --438 end return GetModelSceneActorInfoByID(actorInfoID), GetPanningYOffset(raceID, genderID) end function NarciAPI_SetupModelScene(modelScene, modelFileID, zoomDistance, view, actorIndex, UseTransit) local pi = math.pi; local model = modelScene; local actorTag; if not actorIndex then actorTag = "narciEffectActor"; else actorTag = "narciEffectActor"..actorIndex end local actor = model[actorTag]; if not actor then local actorID = 156; --effect C_ModelInfo.GetModelSceneActorInfoByID(156) local actorInfo = C_ModelInfo.GetModelSceneActorInfoByID(actorID); actor = model:AcquireAndInitializeActor(actorInfo); actor:SetYaw(pi); model[actorTag] = actor; local parentFrame = model:GetParent(); if parentFrame then model:SetFrameLevel(parentFrame:GetFrameLevel() + 1 or 20); else model:SetFrameLevel(20); end end local cameraTag = "NarciUI"; local camera = model.narciCamera; if not camera then camera = CameraRegistry:CreateCameraByType("OrbitCamera"); if camera then model.narciCamera = camera; model:AddCamera(camera); local modelSceneCameraInfo = C_ModelInfo.GetModelSceneCameraInfoByID(114); camera:ApplyFromModelSceneCameraInfo(modelSceneCameraInfo, 1, 1); --1 ~ CAMERA_TRANSITION_TYPE_IMMEDIATE / CAMERA_MODIFICATION_TYPE_DISCARD end end model:SetActiveCamera(camera); if modelFileID then actor:SetModelByFileID(modelFileID); end if zoomDistance then if UseTransit then --change camera.targetInterpolationAmount for smoothing time --:GetTargetInterpolationAmount() :SetTargetInterpolationAmount(value) camera:SetZoomDistance(1); camera:SnapAllInterpolatedValues(); After(0, function() camera:SetZoomDistance(zoomDistance); end); else camera:SetZoomDistance(zoomDistance); camera:SynchronizeCamera(); end end if view then local pitch, yaw; if type(view) == "string" then view = strupper(view); if view == "FRONT" then pitch = 0; yaw = pi; elseif view == "BACK" then pitch = 0; yaw = 0; elseif view == "TOP" then pitch = pi/2; yaw = pi; elseif view == "BOTTOM" then pitch = -pi/2; yaw = pi; elseif view == "LEFT" then pitch = 0; yaw = -pi/2; elseif view == "RIGHT" then pitch = 0; yaw = pi/2; else return; end elseif type(view) == "table" then pitch = view[1]; yaw = view[2]; if not (pitch and yaw) then return; end end actor:SetPitch(pitch); actor:SetYaw(yaw); end return actor, camera --[[ if rollDegree then actor:SetRoll(rad(-rollDegree)) --Clockwise end --]] end local function ReAnchorFrame(frame) --maintain frame top position when changing its height local oldCenterX = frame:GetCenter(); --local oldBottom = frame:GetBottom(); local oldTop = frame:GetTop(); local screenWidth = WorldFrame:GetWidth(); local screenHeight = WorldFrame:GetHeight(); local scale = frame:GetEffectiveScale(); if not scale or scale == 0 then scale = 1; end local width = frame:GetWidth()/2; frame:ClearAllPoints(); --frame:SetPoint("BOTTOMRIGHT", nil, "BOTTOMRIGHT", oldCenterX + width - screenWidth / scale , oldBottom); frame:SetPoint("TOPRIGHT", nil, "TOPRIGHT", oldCenterX + width - screenWidth / scale , oldTop - screenHeight/scale); end local function ParserButton_ShowTooltip(self) if self.itemLink and not CursorHasItem() then local frame =self:GetParent(); local TP = frame.tooltip; --GameTooltip_SetBackdropStyle(TP, GAME_TOOLTIP_BACKDROP_STYLE_CORRUPTED_ITEM); TP:SetBackdrop(nil); TP:SetOwner(self, "ANCHOR_NONE"); TP:SetPoint("TOP", frame.ItemString, "BOTTOM", 0, -14); TP:SetHyperlink(self.itemLink); TP:SetMinimumWidth(254 / 0.8); TP:Show(); frame:SetHeight( math.max (math.floor(TP:GetHeight() - 260), 0) + 400); ReAnchorFrame(frame); end end local function ParserButton_GetCursor(self) local infoType, itemID, itemLink = GetCursorInfo(); self.Highlight:Hide() if not (infoType and infoType == "item") then return elseif not IsCorruptedItem(itemLink) then local frame = self:GetParent(); frame.ItemName:SetText("Not a Corrupted Item"); local itemString = string.match(itemLink, "item:([%-?%d:]+)"); frame.ItemString:SetText(itemString); After(2, function() frame.ItemName:SetText("Drop a Corrupted Item Here"); end); ClearCursor(); return end ClearCursor(); self.itemLink = itemLink; local itemName, _, itemQuality, itemLevel, _, _, _, _, itemEquipLoc, itemIcon = GetItemInfo(itemLink); local itemString = string.match(itemLink, "item:([%-?%d:]+)"); local supposedEffect, corruptionID = NarciAPI_GetCorruptedItemAffix(itemLink); local hasGem = NarciAPI_IsItemSocketable(itemLink); local enchantID = GetItemEnchant(itemLink); local corruption = GetItemStats(itemLink)["ITEM_MOD_CORRUPTION"] or 0; local _, extraEffect = NarciAPI_GetItemExtraEffect(itemLink); local r, g, b = GetItemQualityColor(itemQuality); local HEX_PURPLE = "|c"..CORRUPTION_COLOR:GenerateHexColor(); if extraEffect then extraEffect = HEX_PURPLE.. extraEffect end if supposedEffect then supposedEffect = supposedEffect.." ".."|cff946dd1"..corruption.."|r"; else supposedEffect = "|cff946dd1"..corruption.."|r"; end if hasGem then supposedEffect = supposedEffect.." ".."|cff40C7ebSocket|r" end local enchantName; local colorizedString = itemString; if enchantID and enchantID ~= 0 then local GREEN = "|cff1eff00"; local info = Narci_EnchantInfo[enchantID]; if info then enchantName = string.gsub(info[1], "%a", string.upper, 1).." "..info[2]; supposedEffect = supposedEffect.." "..GREEN..enchantName.."|r"; end colorizedString = string.gsub(itemString, enchantID, GREEN..enchantID.."|r", 1); end if corruptionID then colorizedString = string.gsub(colorizedString, corruptionID, HEX_PURPLE..corruptionID.."|r", 1); end --Show info self.ItemIcon:SetTexture(itemIcon); local frame = self:GetParent(); frame.ItemName:SetText(supposedEffect); frame.ItemName:SetTextColor(r, g, b); frame.ItemString:SetText(colorizedString); frame.SupposedEffect:SetText(supposedEffect); frame.ActualEffect:SetText(extraEffect); frame.Pointer:Hide(); ParserButton_ShowTooltip(self) end function Narci_ItemParser_OnLoad(self) self:SetUserPlaced(false) self:ClearAllPoints(); self:SetPoint("CENTER", UIParent, "CENTER", 0, 0); self:RegisterForDrag("LeftButton"); self:SetScript("OnShow", ReAnchorFrame); self.ItemButton:SetScript("OnReceiveDrag", ParserButton_GetCursor); self.ItemButton:SetScript("OnClick", ParserButton_GetCursor); self.ItemButton:SetScript("OnEnter", ParserButton_ShowTooltip); local locale = GetLocale(); local version, build, date, tocversion = GetBuildInfo(); self.ClientInfo:SetText(locale.." "..version.."."..build.." "..NARCI_VERSION_INFO); local TP = CreateFrame("GameTooltip", "Narci_ItemParserTooltip", self, "GameTooltipTemplate"); TP:Hide(); self.tooltip = TP; local scale = 0.8; local tooltipScale = 0.8; self:SetScale(0.8); TP:SetScale(tooltipScale); end ----------------- -----Utility----- ----------------- local DistanceCalculator; local MovementListener; function NarciAPI_ActivateDistanceCalculator(calibrateDistance) if not DistanceCalculator then --Timer frame DistanceCalculator = CreateFrame("Frame"); DistanceCalculator:Hide(); DistanceCalculator.basicSpeed = 0; local function OnUpdate(self, elapsed) self.t = self.t + elapsed; end DistanceCalculator:SetScript("OnShow", function(self) self.t = 0; end); DistanceCalculator:SetScript("OnHide", function(self) print(self.t); if self.basicSpeed > 0 then local d = self.basicSpeed * self.t; d = math.floor(d * 100 + 0.5) / 100; print("|cffFFF569"..d.." yd|r"); elseif self.t > 0.2 then if self.calibrateDistance then self.basicSpeed = self.calibrateDistance / self.t; self.calibrateDistance = nil; print("Speed: ".. math.floor(self.basicSpeed * 100 + 0.5) / 100 .. " yd/s" ); else print("Speed Not Calibrated"); end end self.t = 0; end); DistanceCalculator:SetScript("OnUpdate", OnUpdate); --Event listener MovementListener = CreateFrame("Frame"); MovementListener:Hide(); MovementListener:SetScript("OnShow", function(self) self:RegisterEvent("PLAYER_STARTED_MOVING"); self:RegisterEvent("PLAYER_STOPPED_MOVING"); end); local function OnEvent(self, event) if event == "PLAYER_STARTED_MOVING" then DistanceCalculator:Show(); else DistanceCalculator:Hide(); end end MovementListener:SetScript("OnEvent", OnEvent); --Global function NarciAPI_DeactivateDistanceCalculator() MovementListener:Hide(); DistanceCalculator:Hide(); end end MovementListener:Show(); if calibrateDistance and type(calibrateDistance) == "number" and calibrateDistance >= 5 then DistanceCalculator.basicSpeed = 0; DistanceCalculator.calibrateDistance = calibrateDistance; end end local Globals = {}; local totalGlobals = 1; for k, v in pairs(_G) do Globals[totalGlobals] = k; totalGlobals = totalGlobals + 1; end local SEARCH_PER_FRAME = 240; local numLoop = 0; local numMatch = 0; local function SearchLoop(b, key) local find = string.find; local index; for i = b, b + SEARCH_PER_FRAME do if Globals[i] then index = i; if find(Globals[i], key) then numMatch = numMatch + 1; local t = type(_G[ Globals[i] ]); if t == "number" or t == "string" then print("|cffffd200".. Globals[i].."|r = ".. (_G[Globals[i]] or "nil") ); else print("|cff808080"..t.." |cffffd200".. Globals[i]); end end else print("Search Completes ---------------") print("Found ".. "|cffffd200".. numMatch .. "|r matches.") numLoop = 0; return end end After(0, function() SearchLoop(b + SEARCH_PER_FRAME + 1, key) end) numLoop = numLoop + 1; if numLoop == 100 then numLoop = 0; print(math.floor(index / totalGlobals * 10000 + 0.5)/100 .. "% ----------------------------") end end function SearchGlobalString(key) if type(key) ~= "string" then print("The key must be a string!"); return end numLoop = 0; numMatch = 0; local beginning = 1; SearchLoop(beginning, key) end ---------------------------- -----Item Import/Export----- ---------------------------- local WOWHEAD_ENCODING = "0zMcmVokRsaqbdrfwihuGINALpTjnyxtgevElBCDFHJKOPQSUWXYZ123456789"; --version: 9 WH.calc.hash.getEncoding(9) local WOWHEAD_DELIMITER = 8; --WH.calc.hash.getDelimiter(9) local COMPRESSION_INDICATOR = 7; --WH.calc.hash.getZeroDelimiterCompressionIndicator(9) :7 + single letter local WOWHEAD_MAXCODING_INDEX = 58 --WH.calc.hash.getMaxEncodingIndex(a); //9 ~ 58 local WOWHEAD_CUSTOMIZATION = "0zJ89b"; local EncodeValue = {} for i = 0, #WOWHEAD_ENCODING do EncodeValue[i] = strsub(WOWHEAD_ENCODING, i+1, i+1); end local EquipmentOrderToCharacterSlot = { [1] = 1, [2] = 3, [3] = 15, [4] = 5, [5] = 4, [6] = 19, [7] = 9, [8] = 10, [9] = 6, [10]= 7, [11]= 8, [12]= 16, [13]= 17, }; local CharacterSlotToEquipmentOrder = {} for k, v in pairs(EquipmentOrderToCharacterSlot) do CharacterSlotToEquipmentOrder[v] = tostring(k); v = tostring(v); end local function EncodeLongValue(number) local m = WOWHEAD_MAXCODING_INDEX; if number <= m then return EncodeValue[number]; end local floor = math.floor; local shortValues = {number}; local v = 0; while(shortValues[1] > m) do v = floor(shortValues[1] / m); tinsert(shortValues, shortValues[1] - m * v); shortValues[1] = v; end local str = EncodeValue[ shortValues[1] ]; for i = #shortValues, 2, -1 do if shortValues[2] ~= "0" then str = str .. EncodeValue[ shortValues[i] ] else str = str .. "7" end end return str end function NarciBridge_EncodeItemlist(itemlist, unitInfo) if not itemlist or type(itemlist) ~= "table" or itemlist == {} then return ""; end --itemlist = {[slot] = {itemID, bonusID}} local raceID, genderID, classID; if unitInfo then raceID, genderID, classID = unitInfo.raceID, unitInfo.genderID, unitInfo.classID; else local _; local unit = "player"; _, _, raceID = UnitRace(unit); genderID = UnitSex(unit); _, _, classID = UnitClass(unit); end if not (raceID and genderID and classID) then local _; local unit = "player"; _, _, raceID = UnitRace(unit); _, _, classID = UnitClass(unit); genderID = UnitSex(unit) or 2; raceID = raceID or 1; classID = classID or 1; end genderID = genderID - 2; --Male 2 → 0 Female 3 → 1 local wowheadLink = "https://www.wowhead.com/dressing-room#s".. EncodeValue[raceID] .. EncodeValue[genderID] .. EncodeValue[classID] .. WOWHEAD_CUSTOMIZATION.. WOWHEAD_DELIMITER; local segment, slot; local blanks = 0; for i = 1, #EquipmentOrderToCharacterSlot do --item = { itemID, bonusID } slot = EquipmentOrderToCharacterSlot[i] item = itemlist[slot]; if item and item[1] then segment = EncodeLongValue(item[1]) if #segment < 3 then segment = "7".. CharacterSlotToEquipmentOrder[slot] .. segment end item[2] = item[2] or 0; --bonusID if slot == 16 and item[2] > 0 and item[2] < 99 then local offHand = itemlist[17]; if offHand and offHand[1] then segment = segment .. WOWHEAD_DELIMITER .. "0" .. WOWHEAD_DELIMITER .. EncodeLongValue(offHand[1]) .. WOWHEAD_DELIMITER .. "7c" .. EncodeValue[ item[2] ]; else segment = segment .. WOWHEAD_DELIMITER .. "7V" .. EncodeValue[ item[2] ]; end wowheadLink = wowheadLink .. segment; break; else segment = segment .. WOWHEAD_DELIMITER .. EncodeLongValue(item[2]) .. WOWHEAD_DELIMITER; end wowheadLink = wowheadLink .. segment; else blanks = blanks + 1; wowheadLink = wowheadLink .. "7M" end end return wowheadLink end ---------------------------- ----UI Animation Generic---- ---------------------------- function NarciAPI_CreateAnimationFrame(duration) local frame = CreateFrame("Frame"); frame:Hide(); frame.total = 0; frame.duration = duration; frame:SetScript("OnHide", function(self) self.total = 0; end); return frame; end ---------------------------- -------Frame Template------- ---------------------------- NarciFrameMixin = {}; function NarciFrameMixin:ShowFrame(state) self:SetShown(state); if state then self:SetAlpha(1); else self:SetAlpha(0); end end function NarciFrameMixin:HideFrame() self:ShowFrame(false); end function NarciFrameMixin:SetHeaderText(text, r, g, b) self.Header:SetText(text); self.Header:SetTextColor(r or 0.4, g or 0.4, b or 0.4); end function NarciFrameMixin:SetSizeAndAnchor(x, y, point, relativeTo, relativePoint, offsetX, offsetY) if x then x = max(x, 40) end; if y then y = max(y, 40) end; if x then if y then self:SetSize(x, y); else self:SetWidth(x); end else self:SetHeight(y); end self:ClearAllPoints(); self:SetPoint(point, relativeTo, relativePoint, offsetX, offsetY); end function NarciFrameMixin:SetRelativeFrameLevel(offset) local parent = self:GetParent(); if parent then local parentLevel = parent:GetFrameLevel() or 0; self:SetFrameStrata(parent:GetFrameStrata()); self:SetFrameLevel( max(parentLevel + offset, 0) ); end end function NarciFrameMixin:HideWhenParentIsHidden(state) if state then self:SetScript("OnHide", function(self) self:HideFrame(); end); local parent = self:GetParent(); if parent and not parent:IsVisible() then self:HideFrame(); end else self:SetScript("OnHide", nil); end end --[[ function TestFX(modelFileID, zoomDistance, view) NarciAPI_SetupModelScene(TestScene, modelFileID, zoomDistance, view); end --]] --/run TestFX(3152608, nil, ) 122972 --/run TestFX(1011653, 8, " --/run TestFX(3004122, 8, "LEFT") --Eyeball
GLib.Lua.Precedence = GLib.Enum ( { Lowest = 0, Addition = 1, Subtraction = 2, Multiplication = 3, Division = 4, Modulo = 5, Exponentiation = 6, LeftUnaryOperator = 7, Atom = 8 } ) local associativePrecedences = { [GLib.Lua.Precedence.Addition] = true, [GLib.Lua.Precedence.Multiplication] = true, [GLib.Lua.Precedence.LeftUnaryOperator] = true } function GLib.Lua.IsPrecedenceAssociative (precedence) return associativePrecedences [precedence] or false end
--异次元纪念碑 local m=14010105 local cm=_G["c"..m] function cm.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER) e1:SetCost(cm.cost) c:RegisterEffect(e1) --cannot activate local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_CANNOT_ACTIVATE) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e2:SetRange(LOCATION_SZONE) e2:SetTargetRange(1,1) e2:SetValue(cm.aclimit) c:RegisterEffect(e2) --act in hand local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_TRAP_ACT_IN_HAND) c:RegisterEffect(e3) end function cm.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return (not e:GetHandler():IsLocation(LOCATION_HAND) or Duel.IsExistingMatchingCard(Card.IsAbleToRemoveAsCost,tp,LOCATION_HAND,0,1,e:GetHandler())) end if e:GetHandler():IsStatus(STATUS_ACT_FROM_HAND) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemoveAsCost,tp,LOCATION_HAND,0,1,1,e:GetHandler()) Duel.Remove(g,POS_FACEUP,REASON_COST) end end function cm.acfilter(c,code) return c:IsFaceup() and c:IsCode(code) end function cm.aclimit(e,re,tp) return Duel.IsExistingMatchingCard(cm.acfilter,e:GetHandlerPlayer(),LOCATION_REMOVED,LOCATION_REMOVED,1,nil,re:GetHandler():GetCode()) and not re:GetHandler():IsImmuneToEffect(e) end
--[[ Upbit Open API ## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [open-api@upbit.com] OpenAPI spec version: 1.0.0 Contact: ujhin942@gmail.com Generated by: https://github.com/swagger-api/swagger-codegen.git ]] -- candle_minutes class local candle_minutes = {} local candle_minutes_mt = { __name = "candle_minutes"; __index = candle_minutes; } local function cast_candle_minutes(t) return setmetatable(t, candle_minutes_mt) end local function new_candle_minutes(market, candle_date_time_utc, candle_date_time_kst, opening_price, high_price, low_price, trade_price, timestamp, candle_acc_trade_price, candle_acc_trade_volume, unit) return cast_candle_minutes({ ["market"] = market; ["candle_date_time_utc"] = candle_date_time_utc; ["candle_date_time_kst"] = candle_date_time_kst; ["opening_price"] = opening_price; ["high_price"] = high_price; ["low_price"] = low_price; ["trade_price"] = trade_price; ["timestamp"] = timestamp; ["candle_acc_trade_price"] = candle_acc_trade_price; ["candle_acc_trade_volume"] = candle_acc_trade_volume; ["unit"] = unit; }) end return { cast = cast_candle_minutes; new = new_candle_minutes; }
-------------------------------- -- @module TransitionMoveInL -- @extend TransitionScene,TransitionEaseScene -- @parent_module cc ---@class cc.TransitionMoveInL:cc.TransitionScene,cc.TransitionEaseScene local TransitionMoveInL = {} cc.TransitionMoveInL = TransitionMoveInL -------------------------------- --- Returns the action that will be performed. --- return The action that will be performed. ---@return cc.ActionInterval function TransitionMoveInL:action() end -------------------------------- --- ---@param action cc.ActionInterval ---@return cc.ActionInterval function TransitionMoveInL:easeActionWithAction(action) end -------------------------------- --- Creates a transition with duration and incoming scene. --- param t Duration time, in seconds. --- param scene A given scene. --- return A autoreleased TransitionMoveInL object. ---@param t number ---@param scene cc.Scene ---@return cc.TransitionMoveInL function TransitionMoveInL:create(t, scene) end -------------------------------- --- ---@return cc.TransitionMoveInL function TransitionMoveInL:TransitionMoveInL() end return nil
m = Map("babeld", translate("Babeld Overview")) m.pageaction = false s = m:section(NamedSection, "__babeldoverview__") function s.render(self, sid) local tpl = require "luci.template" tpl.render_string([[ <% local utl = require "luci.util" local v6_port = 33123 -- FIXME: check if call is correct local dump = utl.exec("(echo dump | nc ::1 %d)" % v6_port) local t = {} for strline in string.gmatch(dump, "[^\n]+") do t[#t+1] = strline; end local babel_version = t[1] local babeld_version = t[2] local babeld_host = string.split(t[3], " ")[2] local babeld_id = string.split(t[4], " ")[2] local babeld_status = t[5] %> <div class="cbi-section-node"> <h3>Babel-Info</h3> <div class="table" id=babel_status_main"> <div class="tr table-titles"> <div class="th">Version</div> <div class="th">Version-Daemon</div> <div class="th">Host</div> <div class="th">ID</div> <div class="th">Status</div> </div> <div class="tr"> <div class="td"><%= babel_version %></div> <div class="td"><%= babeld_version %></div> <div class="td"><%= babeld_host %></div> <div class="td"><%= babeld_id %></div> <div class="td"><%= babeld_status %></div> </div> </div> </div> <% local xroutes = {} for key,value in ipairs(t) do if string.match(value, "xroute") then xroutes[#xroutes+1] = value end end %> <div class="cbi-section-node"> <h3>X-Routes</h3> <div class="table" id=babel_overview_xroute"> <div class="tr table-titles"> <div class="th">Route</div> <div class="th">Prefix</div> <div class="th">From</div> <div class="th">Metric</div> </div> <% for key,route in ipairs(xroutes) do local route_sep = string.split(route," ") %> <div class="tr"> <div class="td"><%= route_sep[3] %></div> <div class="td"><%= route_sep[5] %></div> <div class="td"><%= route_sep[7] %></div> <div class="td"><%= route_sep[9] %></div> </div> <% end %> </div> </div> <% local routes = {} for key,value in ipairs(t) do if string.match(value, "add route") then routes[#routes+1] = value end end %> <div class="cbi-section-node"> <h3>Routes</h3> <div class="table" id=babel_overview_route"> <div class="tr table-titles"> <div class="th">Prefix</div> <div class="th">From</div> <div class="th">Installed</div> <div class="th">ID</div> <div class="th">Metric</div> <div class="th">Ref-Metric</div> <div class="th">Via</div> <div class="th">Interface</div> </div> <% for key,route in ipairs(routes) do local route_sep = string.split(route," ") %> <div class="tr"> <div class="td"><%= route_sep[5] %></div> <div class="td"><%= route_sep[7] %></div> <div class="td"><%= route_sep[9] %></div> <div class="td"><%= route_sep[11] %></div> <div class="td"><%= route_sep[13] %></div> <div class="td"><%= route_sep[15] %></div> <div class="td"><%= route_sep[17] %></div> <div class="td"><%= route_sep[19] %></div> </div> <% end %> </div> </div> ]]) end return m
local CONST = require(script:GetCustomProperty("MetaAbilityProgressionConstants_API")) local LOCAL_PLAYER = Game.GetLocalPlayer() local NETWORKED = script:GetCustomProperty("METARewards_Networked"):WaitForObject() local PERK_PANEL = script:GetCustomProperty("Perks"):WaitForObject() local VIP_MEMBER_PANEL = PERK_PANEL:GetCustomProperty("VIPMember"):WaitForObject() local VIP_BOOST_TEXT = VIP_MEMBER_PANEL:GetCustomProperty("ActiveText"):WaitForObject() local XP_BOOST_PANEL = PERK_PANEL:GetCustomProperty("XPBoost"):WaitForObject() local XP_BOOST_TEXT = XP_BOOST_PANEL:GetCustomProperty("ActiveText"):WaitForObject() local XP_MULITPLIER_TEXT = XP_BOOST_PANEL:GetCustomProperty("Multiplier"):WaitForObject() local GOLD_BOOST_PANEL = PERK_PANEL:GetCustomProperty("GoldBoost"):WaitForObject() local GOLD_BOOST_TEXT = GOLD_BOOST_PANEL:GetCustomProperty("ActiveText"):WaitForObject() local GOLD_MULITPLIER_TEXT = GOLD_BOOST_PANEL:GetCustomProperty("Multiplier"):WaitForObject() local VIP_MULTIPLIER = script:GetCustomProperty("VIP_MULTIPLIER"):WaitForObject() local SERVER_MULTIPLIER = script:GetCustomProperty("SERVER_MULTIPLIER"):WaitForObject() local EVENT_BONUS = script:GetCustomProperty("EVENT_BONUS"):WaitForObject() local META_EventsAPI = script:GetCustomProperty("META_EventsAPI") local eventsAPI = require(META_EventsAPI) local goldBoostTime = 0 local xpBoostTime = 0 local isVip = false local xpIsVisable = false local goldIsVisable = false while not _G.PerPlayerDictionary do Task.Wait() end _G.PerPlayerDictionary.WaitForPlayer(LOCAL_PLAYER) function Update() goldBoostTime = _G.PerPlayerDictionary.GetNumber(LOCAL_PLAYER, CONST.SELF_GOLD_BOOST_KEY) or 0 xpBoostTime = _G.PerPlayerDictionary.GetNumber(LOCAL_PLAYER, CONST.SELF_XP_BOOST_KEY) or 0 isVip = _G.PerPlayerDictionary.Get(LOCAL_PLAYER, CONST.VIP_MEMBERSHIP_KEY) if isVip then --VIP_MEMBER_PANEL.visibility = Visibility.FORCE_ON VIP_BOOST_TEXT.text = "VIP ACTIVE" VIP_BOOST_TEXT:SetColor(Color.GREEN) else -- VIP_MEMBER_PANEL.visibility = Visibility.FORCE_OFF VIP_BOOST_TEXT.text = "Press P" VIP_BOOST_TEXT:SetColor(Color.RED) end for _, xpText in ipairs(XP_MULITPLIER_TEXT:GetChildren()) do local multiplier = 1 if isVip then multiplier = multiplier + CONST.VIP_XP_MULTIPLIER end if xpBoostTime and xpBoostTime > 0 then multiplier = multiplier + CONST.XP_SELF_BOOST_MULTIPLIER end if eventsAPI.IsEventKeyActive("2CXP") then multiplier = multiplier * 2 end xpText.text = tostring(multiplier) .. "x" end for _, goldText in ipairs(GOLD_MULITPLIER_TEXT:GetChildren()) do local multiplier = 1 if isVip then multiplier = multiplier + CONST.VIP_GOLD_MULTIPLIER end if goldBoostTime and goldBoostTime > 0 then multiplier = multiplier + CONST.GOLD_SELF_BOOST_MULTIPLIER end if eventsAPI.IsEventKeyActive("2Gold") then multiplier = multiplier * 2 end goldText.text = tostring(multiplier) .. "x" end end function OnDictionaryChanged(player, key, value) if player ~= LOCAL_PLAYER then return end if key == CONST.SELF_GOLD_BOOST_KEY then goldBoostTime = value or 0 if goldBoostTime - time() > 0 then GOLD_BOOST_PANEL.visibility = Visibility.FORCE_ON goldIsVisable = true else GOLD_BOOST_PANEL.visibility = Visibility.FORCE_OFF goldIsVisable = false end end if key == CONST.SELF_XP_BOOST_KEY then xpBoostTime = value or 0 if xpBoostTime - time() > 0 then XP_BOOST_PANEL.visibility = Visibility.FORCE_ON xpIsVisable = true else XP_BOOST_PANEL.visibility = Visibility.FORCE_OFF xpIsVisable = false end end if key == CONST.VIP_MEMBERSHIP_KEY then if value == "1" then VIP_MEMBER_PANEL.visibility = Visibility.FORCE_ON VIP_BOOST_TEXT.text = "ACTIVE" VIP_BOOST_TEXT:SetColor(Color.GREEN) else VIP_MEMBER_PANEL.visibility = Visibility.FORCE_OFF VIP_BOOST_TEXT.text = "Press P" VIP_BOOST_TEXT:SetColor(Color.RED) end end end function Tick() -- GOLD SERVER BOOST local currentGoldBoost = goldBoostTime - time() local isGoldEventActive = eventsAPI.IsEventKeyActive("2Gold") if currentGoldBoost > 0 then local hours = math.floor(currentGoldBoost / 3600) if hours > 23 then GOLD_BOOST_TEXT.text = "1 Day+" else local minutes = math.floor(currentGoldBoost) // 60 % 60 local seconds = math.floor(currentGoldBoost) % 60 GOLD_BOOST_TEXT.text = string.format("%02d:%02d:%02d", hours, minutes, seconds) end elseif isGoldEventActive and not goldIsVisable then GOLD_BOOST_PANEL.visibility = Visibility.FORCE_ON GOLD_BOOST_TEXT.text = "" goldIsVisable = true elseif goldIsVisable and not isGoldEventActive then GOLD_BOOST_PANEL.visibility = Visibility.FORCE_OFF goldIsVisable = false end local currentXpBoost = xpBoostTime - time() local isXpEventActive = eventsAPI.IsEventKeyActive("2CXP") -- XP SERVER BOOST if currentXpBoost > 0 then local hours = math.floor(currentXpBoost / 3600) if hours > 23 then XP_BOOST_TEXT.text = "1 Day+" else local minutes = math.floor(currentXpBoost) // 60 % 60 local seconds = math.floor(currentXpBoost) % 60 XP_BOOST_TEXT.text = string.format("%02d:%02d:%02d", hours, minutes, seconds) end elseif isXpEventActive and not xpIsVisable then XP_BOOST_PANEL.visibility = Visibility.FORCE_ON xpIsVisable = true XP_BOOST_TEXT.text = "" elseif xpIsVisable and not isXpEventActive then XP_BOOST_PANEL.visibility = Visibility.FORCE_OFF xpIsVisable = false end Update() end _G.PerPlayerDictionary.valueChangedEvent:Connect(OnDictionaryChanged) Update()
local myNAME, myVERSION = "libCommonInventoryFilters", 1.2 local libCIF = LibStub:NewLibrary(myNAME, myVERSION) if not libCIF then return end local function enableGuildStoreSellFilters() local tradingHouseLayout = BACKPACK_TRADING_HOUSE_LAYOUT_FRAGMENT.layoutData if not tradingHouseLayout.hiddenFilters then tradingHouseLayout.hiddenFilters = {} end tradingHouseLayout.hiddenFilters[ITEMFILTERTYPE_QUEST] = true tradingHouseLayout.inventoryTopOffsetY = 45 tradingHouseLayout.sortByOffsetY = 63 tradingHouseLayout.backpackOffsetY = 96 local originalFilter = tradingHouseLayout.additionalFilter function tradingHouseLayout.additionalFilter(slot) return originalFilter(slot) and not IsItemBound(slot.bagId, slot.slotIndex) end local tradingHouseHiddenColumns = { statValue = true, age = true } local zorgGetTabFilterInfo = PLAYER_INVENTORY.GetTabFilterInfo function PLAYER_INVENTORY:GetTabFilterInfo(inventoryType, tabControl) if libCIF._tradingHouseModeEnabled then local filterType, activeTabText = zorgGetTabFilterInfo(self, inventoryType, tabControl) return filterType, activeTabText, tradingHouseHiddenColumns else return zorgGetTabFilterInfo(self, inventoryType, tabControl) end end end local function fixSearchBoxBugs() -- http://www.esoui.com/forums/showthread.php?t=4551 -- search box bug #1: stale searchData after swapping equipment SHARED_INVENTORY:RegisterCallback("SlotUpdated", function(bagId, slotIndex, slotData) if slotData and slotData.searchData then slotData.searchData.cached = false slotData.searchData.cache = nil end end) -- guild bank search box bug #2: wrong inventory updated ZO_GuildBankSearchBox:SetHandler("OnTextChanged", function(editBox) ZO_EditDefaultText_OnTextChanged(editBox) PLAYER_INVENTORY:UpdateList(INVENTORY_GUILD_BANK) end) -- guild bank search box bug #3: wrong search box cleared local guildBankScene = SCENE_MANAGER:GetScene("guildBank") guildBankScene:RegisterCallback("StateChange", function(oldState, newState) if newState == SCENE_HIDDEN then ZO_PlayerInventory_EndSearch(ZO_GuildBankSearchBox) end end) end local function showSearchBoxes() -- re-anchoring is necessary because they overlap with sort headers ZO_PlayerInventorySearchBox:ClearAnchors() ZO_PlayerInventorySearchBox:SetAnchor(BOTTOMLEFT, nil, TOPLEFT, 36, -8) ZO_PlayerInventorySearchBox:SetHidden(false) ZO_PlayerBankSearchBox:ClearAnchors() ZO_PlayerBankSearchBox:SetAnchor(BOTTOMLEFT, nil, TOPLEFT, 36, -8) ZO_PlayerBankSearchBox:SetWidth(ZO_PlayerInventorySearchBox:GetWidth()) ZO_PlayerBankSearchBox:SetHidden(false) ZO_GuildBankSearchBox:ClearAnchors() ZO_GuildBankSearchBox:SetAnchor(BOTTOMLEFT, nil, TOPLEFT, 36, -8) ZO_GuildBankSearchBox:SetWidth(ZO_PlayerInventorySearchBox:GetWidth()) ZO_GuildBankSearchBox:SetHidden(false) end local function onPlayerActivated(eventCode) EVENT_MANAGER:UnregisterForEvent(myNAME, eventCode) fixSearchBoxBugs() if not libCIF._searchBoxesDisabled then showSearchBoxes() end if not libCIF._guildStoreSellFiltersDisabled then -- note that this sets trading house layout offsets, so it -- has to be done before they are shifted enableGuildStoreSellFilters() end local shiftY = libCIF._backpackLayoutShiftY if shiftY then local function doShift(layoutData) layoutData.sortByOffsetY = layoutData.sortByOffsetY + shiftY layoutData.backpackOffsetY = layoutData.backpackOffsetY + shiftY end doShift(BACKPACK_MENU_BAR_LAYOUT_FRAGMENT.layoutData) doShift(BACKPACK_BANK_LAYOUT_FRAGMENT.layoutData) doShift(BACKPACK_TRADING_HOUSE_LAYOUT_FRAGMENT.layoutData) doShift(BACKPACK_MAIL_LAYOUT_FRAGMENT.layoutData) doShift(BACKPACK_PLAYER_TRADE_LAYOUT_FRAGMENT.layoutData) doShift(BACKPACK_STORE_LAYOUT_FRAGMENT.layoutData) doShift(BACKPACK_FENCE_LAYOUT_FRAGMENT.layoutData) doShift(BACKPACK_LAUNDER_LAYOUT_FRAGMENT.layoutData) -- added in ESO 2.1 if BACKPACK_GUILD_BANK_LAYOUT_FRAGMENT then doShift(BACKPACK_GUILD_BANK_LAYOUT_FRAGMENT.layoutData) end end -- replace ZO_InventoryManager:SetTradingHouseModeEnabled -- no need to call the original, as it only does two things we don't need: -- 1) saves/restores the current filter -- - or would, if the filter wasn't reset in ApplyBackpackLayout -- - this simply doesn't work -- 2) shows the search box and hides the filters tab, or vice versa -- - we want to show or hide them according to add-on requirements -- specified during start-up local savedSearchBoxAnchor = {false} function PLAYER_INVENTORY:SetTradingHouseModeEnabled(enabled) libCIF._tradingHouseModeEnabled = enabled if enabled then ZO_PlayerInventorySearchBox:SetHidden(false) ZO_PlayerInventoryTabs:SetHidden(libCIF._guildStoreSellFiltersDisabled) -- move search box if custom sell filters are enabled (AwesomeGuildStore) if not savedSearchBoxAnchor[1] and libCIF._guildStoreSellFiltersDisabled then savedSearchBoxAnchor = {ZO_PlayerInventorySearchBox:GetAnchor(0)} ZO_PlayerInventorySearchBox:ClearAnchors() ZO_PlayerInventorySearchBox:SetAnchor(BOTTOMLEFT, nil, TOPLEFT, 36, -8) end else ZO_PlayerInventorySearchBox:SetHidden(libCIF._searchBoxesDisabled) ZO_PlayerInventoryTabs:SetHidden(false) -- restore original search box position (FilterIt) if savedSearchBoxAnchor[1] then ZO_PlayerInventorySearchBox:ClearAnchors() ZO_PlayerInventorySearchBox:SetAnchor(unpack(savedSearchBoxAnchor, 2)) savedSearchBoxAnchor[1] = false end end end end -- shift backpack sort headers and item list down (shiftY > 0) or up (shiftY < 0) -- add-ons should only call this from their EVENT_ADD_ON_LOADED handler function libCIF:addBackpackLayoutShiftY(shiftY) libCIF._backpackLayoutShiftY = (libCIF._backpackLayoutShiftY or 0) + shiftY end -- tell libCIF to skip enabling inventory filters on guild store sell tab -- add-ons should only call this from their EVENT_ADD_ON_LOADED handler function libCIF:disableGuildStoreSellFilters() libCIF._guildStoreSellFiltersDisabled = true end -- tell libCIF to skip showing inventory search boxes outside guild store sell tab -- add-ons should only call this from their EVENT_ADD_ON_LOADED handler function libCIF:disableSearchBoxes() libCIF._searchBoxesDisabled = true end EVENT_MANAGER:UnregisterForEvent(myNAME, EVENT_PLAYER_ACTIVATED) EVENT_MANAGER:RegisterForEvent(myNAME, EVENT_PLAYER_ACTIVATED, onPlayerActivated)
local present, ts_config = pcall(require, "nvim-treesitter.configs") if not present then return end ts_config.setup { -- one of "all", "maintained" (parsers with maintainers), or a list of languages --ensure_installed = {"yaml", "lua", "json", "dockerfile", "markdown"}, ensure_installed = {"go", "c", "cpp", "yaml", "lua", "json", "dockerfile", "markdown"}, sync_install = false, -- install languages synchronously (only applied to `ensure_installed`) --ignore_install = { "javascript" }, -- List of parsers to ignore installing highlight = { enable = true, -- false will disable the whole extension --disable = { "c", "rust" }, -- list of language that will be disabled -- Setting this to true will run `:h syntax` and tree-sitter at the same time. -- Set this to `true` if you depend on 'syntax' being enabled (like for indentation). -- Using this option may slow down your editor, and you may see some duplicate highlights. -- Instead of true it can also be a list of languages use_languagetree = true, additional_vim_regex_highlighting = false, }, -- enable Indentation indent = {enable = false }, -- enable Incremental selection incremental_selection = { enable = true, keymaps = { init_selection = "gnn", node_incremental = "grn", scope_incremental = "grc", node_decremental = "grm", }, }, --[[ ensure_installed = { "lua", "vim", }, highlight = { enable = true, use_languagetree = true, }, ]] }
object_tangible_furniture_flooring_tile_frn_flooring_tile_s35 = object_tangible_furniture_flooring_tile_shared_frn_flooring_tile_s35:new { } ObjectTemplates:addTemplate(object_tangible_furniture_flooring_tile_frn_flooring_tile_s35, "object/tangible/furniture/flooring/tile/frn_flooring_tile_s35.iff")
---------------------------------------------------------------------------------- -- Total RP 3 -- Pets/mounts managements -- --------------------------------------------------------------------------- -- Copyright 2014 Sylvain Cossement (telkostrasz@telkostrasz.be) -- -- 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. ---------------------------------------------------------------------------------- TRP3_API.companions = { player = {}, register = {} } -- imports local Globals, Utils, Events = TRP3_API.globals, TRP3_API.utils, TRP3_API.events; local loc = TRP3_API.loc; local log = Utils.log.log; local pairs, assert, tostring, wipe, tinsert, type, strtrim, tonumber = pairs, assert, tostring, wipe, tinsert, type, strtrim, tonumber; local registerMenu, selectMenu = TRP3_API.navigation.menu.registerMenu, TRP3_API.navigation.menu.selectMenu; local registerPage, setPage = TRP3_API.navigation.page.registerPage, TRP3_API.navigation.page.setPage; local isMenuRegistered, rebuildMenu = TRP3_API.navigation.menu.isMenuRegistered, TRP3_API.navigation.menu.rebuildMenu; local showAlertPopup, showTextInputPopup, showConfirmPopup = TRP3_API.popup.showAlertPopup, TRP3_API.popup.showTextInputPopup, TRP3_API.popup.showConfirmPopup; local GetSpellInfo = GetSpellInfo; local displayMessage = Utils.message.displayMessage; local companionIDToInfo = Utils.str.companionIDToInfo; local EMPTY = Globals.empty; local tcopy = Utils.table.copy; local TYPE_CHARACTER = TRP3_API.ui.misc.TYPE_CHARACTER; local TYPE_PET = TRP3_API.ui.misc.TYPE_PET; local TYPE_BATTLE_PET = TRP3_API.ui.misc.TYPE_BATTLE_PET; local TYPE_MOUNT = TRP3_API.ui.misc.TYPE_MOUNT; TRP3_API.navigation.menu.id.COMPANIONS_MAIN = "main_20_companions"; function TRP3_API.companions.getCompanionNameFromSpellID(spellID) local name = GetSpellInfo(tonumber(spellID)); return name or spellID; end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Player's companions : API --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local playerCompanions; local PROFILE_DEFAULT_ICON = "INV_Box_PetCarrier_01"; TRP3_API.companions.PROFILE_DEFAULT_ICON = PROFILE_DEFAULT_ICON; local DEFAULT_PROFILE = { data = { IC = PROFILE_DEFAULT_ICON, v = 1, }, PE = { v = 1 }, links = {} }; local playerProfileAssociation = {}; local function getCompanionProfileID(companionID) return playerProfileAssociation[companionID]; end TRP3_API.companions.player.getCompanionProfileID = getCompanionProfileID; local function getCompanionProfile(companionID) if playerProfileAssociation[companionID] then return playerCompanions[playerProfileAssociation[companionID]]; end end TRP3_API.companions.player.getCompanionProfile = getCompanionProfile; local function getCompanionProfileByID(profileID) if playerCompanions[profileID] then return playerCompanions[profileID]; end end TRP3_API.companions.player.getCompanionProfileByID = getCompanionProfileByID; local function parsePlayerProfiles(profiles) for profileID, profile in pairs(profiles) do for companionID, _ in pairs(profile.links or EMPTY) do playerProfileAssociation[companionID] = profileID; end end end local function boundPlayerCompanion(companionID, profileID, targetType) assert(playerCompanions[profileID], "Unknown profile: "..tostring(profileID)); if not playerCompanions[profileID].links then playerCompanions[profileID].links = {}; end playerCompanions[profileID].links[companionID] = targetType; -- Unbound from others for id, profile in pairs(playerCompanions) do if id ~= profileID then profile.links[companionID] = nil; end end playerProfileAssociation[companionID] = profileID; if targetType == TYPE_MOUNT then Events.fireEvent(Events.REGISTER_DATA_UPDATED, Globals.player_id, profileID); else Events.fireEvent(Events.REGISTER_DATA_UPDATED, Globals.player_id .. "_" .. companionID, profileID); end log(("%s bounded to profile %s"):format(companionID, profileID)); end TRP3_API.companions.player.boundPlayerCompanion = boundPlayerCompanion; local function unboundPlayerCompanion(companionID, targetType) local profileID = playerProfileAssociation[companionID]; assert(profileID, "Cannot find any bound for companionID " .. tostring(companionID)); playerProfileAssociation[companionID] = nil; if profileID and playerCompanions[profileID] and playerCompanions[profileID].links then playerCompanions[profileID].links[companionID] = nil; end if targetType == TYPE_MOUNT then Events.fireEvent(Events.REGISTER_DATA_UPDATED, Globals.player_id, profileID); else Events.fireEvent(Events.REGISTER_DATA_UPDATED, Globals.player_id .. "_" .. companionID, profileID); end log(("%s unbounded"):format(companionID)); end TRP3_API.companions.player.unboundPlayerCompanion = unboundPlayerCompanion; -- Check if the profileName is not already used local function isProfileNameAvailable(profileName) for profileID, profile in pairs(playerCompanions) do if profile.profileName == profileName then return false; end end return true; end TRP3_API.companions.player.isProfileNameAvailable = isProfileNameAvailable; -- Duplicate an existing profile local function duplicateProfile(duplicatedProfile, profileName) assert(duplicatedProfile, "Nil profile"); assert(isProfileNameAvailable(profileName), "Unavailable profile name: "..tostring(profileName)); local profileID = Utils.str.id(); playerCompanions[profileID] = {}; Utils.table.copy(playerCompanions[profileID], duplicatedProfile); playerCompanions[profileID].profileName = profileName; displayMessage(loc.PR_PROFILE_CREATED:format(Utils.str.color("g")..profileName.."|r")); return profileID; end TRP3_API.companions.player.duplicateProfile = duplicateProfile; -- Creating a new profile using PR_DEFAULT_PROFILE as a template local function createProfile(profileName) local profileID = duplicateProfile(DEFAULT_PROFILE, profileName); playerCompanions[profileID].data.NA = profileName; return profileID; end TRP3_API.companions.player.createProfile = createProfile; -- Edit a profile name local function editProfile(profileID, newName) assert(playerCompanions[profileID], "Unknown profile: "..tostring(profileID)); assert(isProfileNameAvailable(newName), "Unavailable profile name: "..tostring(newName)); playerCompanions[profileID]["profileName"] = newName; end TRP3_API.companions.player.editProfile = editProfile; -- Delete a profile -- If the deleted profile is the currently selected one, assign the default profile local function deleteProfile(profileID, silently) assert(playerCompanions[profileID], "Unknown profile: "..tostring(profileID)); local profileName = playerCompanions[profileID]["profileName"]; for companionID, _ in pairs(playerCompanions[profileID].links or EMPTY) do unboundPlayerCompanion(companionID); end wipe(playerCompanions[profileID]); playerCompanions[profileID] = nil; if not silently then displayMessage(loc.PR_PROFILE_DELETED:format(Utils.str.color("g")..profileName.."|r")); Events.fireEvent(Events.REGISTER_PROFILE_DELETED, profileID); end end TRP3_API.companions.player.deleteProfile = deleteProfile; local registerCompanions; function TRP3_API.companions.player.getProfiles() return playerCompanions; end local GetMountIDs, GetMountInfoByID, IsMounted = C_MountJournal.GetMountIDs, C_MountJournal.GetMountInfoByID, IsMounted; local function getCurrentMountSpellID() if IsMounted() then for i, id in pairs(GetMountIDs()) do local creatureName, spellID, icon, active = GetMountInfoByID(id); if active then return spellID; end end end end TRP3_API.companions.player.getCurrentMountSpellID = getCurrentMountSpellID; local function getCurrentMountProfile() local currentMountSpellID = getCurrentMountSpellID(); if currentMountSpellID then local currentMountID = tostring(currentMountSpellID); if playerProfileAssociation[currentMountID] then return playerCompanions[playerProfileAssociation[currentMountID]], playerProfileAssociation[currentMountID]; end end end TRP3_API.companions.player.getCurrentMountProfile = getCurrentMountProfile; --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Exchange --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local GetSummonedPetGUID, GetPetInfoByPetID = C_PetJournal.GetSummonedPetGUID, C_PetJournal.GetPetInfoByPetID; local function getCompanionVersionNumbers(profileID) local profile = playerCompanions[profileID]; if profile and profile.data then return profile.data.v, profile.PE.v; end end function TRP3_API.companions.player.getCurrentMountQueryLine() local currentMountSpellID = getCurrentMountSpellID(); if currentMountSpellID then local queryLine = tostring(currentMountSpellID); local summonedMountProfile, summonedMountProfileID = getCurrentMountProfile(); if summonedMountProfile then return queryLine .. "_" .. summonedMountProfileID, getCompanionVersionNumbers(summonedMountProfileID); end return queryLine; end end function TRP3_API.companions.player.getCurrentBattlePetQueryLine() local summonedPetGUID = GetSummonedPetGUID(); if summonedPetGUID then local _, customName, _, _, _, _, _, name = GetPetInfoByPetID(summonedPetGUID); local queryLine = customName or name; if getCompanionProfileID(customName or name) then local profileID = getCompanionProfileID(customName or name); return queryLine .. "_" .. profileID, getCompanionVersionNumbers(profileID); end return queryLine; end end function TRP3_API.companions.player.getCurrentPetQueryLine() local summonedPet = UnitName("pet"); if summonedPet then local queryLine = summonedPet; if getCompanionProfileID(summonedPet) then local profileID = getCompanionProfileID(summonedPet); return queryLine .. "_" .. profileID, getCompanionVersionNumbers(profileID); end return queryLine; end end function TRP3_API.companions.player.getCompanionData(profileID, v) local profile = playerCompanions[profileID]; local data = {}; if profile and profile.data then if v == "1" then tcopy(data, profile.data); elseif v == "2" then tcopy(data, profile.PE); end end return data; end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Register companions (other players companions) --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* local registerProfileAssociation = {}; local function parseRegisterProfiles(profiles) for profileID, profile in pairs(profiles) do for fullID, _ in pairs(profile.links or EMPTY) do registerProfileAssociation[fullID] = profileID; end end end local function registerCreateProfile(profileID) registerCompanions[profileID] = { data = { v = 0, }, PE = { v = 0 }, links = {} }; log(("Create companion register profile %s"):format(profileID)); end TRP3_API.companions.register.registerCreateProfile = registerCreateProfile; function TRP3_API.companions.register.boundAndCheckCompanion(queryLine, ownerID, masterProfileID, v1, v2) local companionID, profileID, companionFullID; if queryLine:find("_") then companionID = queryLine:sub(1, queryLine:find('_') - 1); profileID = queryLine:sub(queryLine:find('_') + 1); else companionID = queryLine; end companionFullID = ownerID .. "_" .. companionID; local isMount = companionID:match("^%d+$"); if companionID and companionID:len() > 0 then if profileID then -- Check profile exists if not registerCompanions[profileID] then registerCreateProfile(profileID); end local profile = registerCompanions[profileID]; -- Check profile link registerProfileAssociation[companionFullID] = profileID; if not profile.links[companionFullID] then -- Unbound from others for id, profile in pairs(registerCompanions) do profile.links[companionFullID] = nil; end profile.links[companionFullID] = 1; log(("Bound %s to profile %s"):format(companionFullID, profileID)); if isMount then Events.fireEvent(Events.REGISTER_DATA_UPDATED, ownerID, nil); else Events.fireEvent(Events.REGISTER_DATA_UPDATED, companionFullID, profileID); end end return profileID, profile.data.v ~= v1, profile.PE.v ~= v2; else local old = registerProfileAssociation[companionFullID]; registerProfileAssociation[companionFullID] = nil; if old and registerCompanions[old] then log(("Unbound %s"):format(companionFullID)); registerCompanions[old].links[companionFullID] = nil; if isMount then Events.fireEvent(Events.REGISTER_DATA_UPDATED, ownerID, nil); else Events.fireEvent(Events.REGISTER_DATA_UPDATED, companionFullID, nil); end end end end end function TRP3_API.companions.register.saveInformation(profileID, v, data) local profile = registerCompanions[profileID]; assert(profile, "Profile does not exists: " .. tostring(profileID)); if v == "1" then wipe(profile.data); tcopy(profile.data, data); profile.data.read = not profile.data.TX or strtrim(profile.data.TX):len() == 0; Events.fireEvent(Events.REGISTER_DATA_UPDATED, nil, profileID, "characteristics"); elseif v == "2" then wipe(profile.PE); tcopy(profile.PE, data); Events.fireEvent(Events.REGISTER_DATA_UPDATED, nil, profileID, "misc"); end end function TRP3_API.companions.register.setProfileData(profileID, profile) registerCompanions[profileID] = profile; Events.fireEvent(Events.REGISTER_DATA_UPDATED, nil, profileID, "characteristics"); Events.fireEvent(Events.REGISTER_DATA_UPDATED, nil, profileID, "misc"); end function TRP3_API.companions.register.getCompanionProfile(companionFullID) if registerProfileAssociation[companionFullID] and registerCompanions[registerProfileAssociation[companionFullID]] then return registerCompanions[registerProfileAssociation[companionFullID]]; end end function TRP3_API.companions.register.companionHasProfile(companionFullID) return registerProfileAssociation[companionFullID]; end function TRP3_API.companions.register.getProfiles() return registerCompanions; end function TRP3_API.companions.register.getAssociationsForProfile(profileID) local list = {}; for companionFullID, id in pairs(registerProfileAssociation) do if id == profileID then tinsert(list, companionFullID); end end return list; end function TRP3_API.companions.register.deleteProfile(profileID, silently) assert(registerCompanions[profileID], "Unknown profile ID: " .. tostring(profileID)); wipe(registerCompanions[profileID]); registerCompanions[profileID] = nil; for key, value in pairs(registerProfileAssociation) do if value == profileID then registerProfileAssociation[key] = nil; end end if not silently then Events.fireEvent(Events.REGISTER_DATA_UPDATED, nil, profileID, nil); Events.fireEvent(Events.REGISTER_PROFILE_DELETED, profileID); end end function TRP3_API.companions.register.getUnitMount(ownerID, unitType) local buffIndex = 1; local spellBuffID = select(11, UnitAura(unitType, buffIndex)); while(spellBuffID) do spellBuffID = select(11, UnitAura(unitType, buffIndex)); local companionFullID = ownerID .. "_" .. tostring(spellBuffID); if registerProfileAssociation[companionFullID] then return companionFullID, registerProfileAssociation[companionFullID], tostring(spellBuffID); end buffIndex = buffIndex + 1; end end --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* -- Init --*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* TRP3_API.events.listenToEvent(TRP3_API.events.WORKFLOW_ON_LOAD, function() if not TRP3_Companions then TRP3_Companions = {}; end if not TRP3_Companions.player then TRP3_Companions.player = {}; end playerCompanions = TRP3_Companions.player; parsePlayerProfiles(playerCompanions); if not TRP3_Register.companion then TRP3_Register.companion = {}; end registerCompanions = TRP3_Register.companion; parseRegisterProfiles(registerCompanions); registerMenu({ id = TRP3_API.navigation.menu.id.COMPANIONS_MAIN, text = loc.REG_COMPANIONS, onSelected = function() setPage(TRP3_API.navigation.page.id.COMPANIONS_PROFILES) end, closeable = true, }); end);
local new_obstacle = require("obstacle") local function new() local obstacle_list = {} local next_spawn_time local spawn_delay local obstacles_spawned local max_modifier local function is_time_to_spawn(now) if now >= next_spawn_time then return true end return false end local function spawn() local obstacle = new_obstacle(love.math.random(0, max_modifier)) table.insert(obstacle_list, obstacle) next_spawn_time = love.timer.getTime() + spawn_delay end local function reduce_spawn_time(dt) if spawn_delay > 0.05 then spawn_delay = spawn_delay - (dt / 100) else spawn_delay = 0.05 end if max_modifier < 2 then max_modifier = max_modifier + (dt / 100) else max_modifier = 2 end end local function get_obstacle_list() return obstacle_list end local function reset() next_spawn_time = 0 spawn_delay = 0.5 obstacles_spawned = 0 max_modifier = 0 for i=#obstacle_list, 1, -1 do table.remove(obstacle_list, i) end end reset() local function update(dt) for i, obstacle in ipairs(obstacle_list) do obstacle.update(dt) if obstacle.get_y() > love.graphics.getHeight() then table.remove(obstacle_list, i) end end end local function draw() for _, obstacle in ipairs(obstacle_list) do obstacle.draw() end end return { is_time_to_spawn = is_time_to_spawn, spawn = spawn, reduce_spawn_time = reduce_spawn_time, get_obstacle_list = get_obstacle_list, reset = reset, update = update, draw = draw, } end return new
require("utils/functions.lua") if technologyUnlocked("EnergyPowerModule") then game.print("Mobile Factory: Unlocked all Modules") local DistributionModule = game.forces["player"].recipes["DistributionModule"] DistributionModule.enabled = true local DrainModule = game.forces["player"].recipes["DrainModule"] DrainModule.enabled = true end
--[[ file:sg_enum.lua desc:三公 auth:Carol Luo ]] local class = require("class") local pokerEnum = require("poker.enum") ---@class sgEnum:pokerEnum local enum = class(pokerEnum) ---构造 function enum:ctor() end ---跟注 ---@return senum function enum.sg_gz() return "sg_gz" end ---跟到底 ---@return senum function enum.sg_gdd() return "sg_gdd" end ---加注 ---@return senum function enum.sg_jz() return "sg_jz" end ---梭哈 ---@return senum function enum.sg_sh() return "sg_sh" end ---弃牌 ---@return senum function enum.sg_qp() return "sg_qp" end ---大三公 ---@return senum function enum.sg_dsg() return "sg_dsg" end ---小三公 ---@return senum function enum.sg_xsg() return "sg_xsg" end ---九点 ---@return senum function enum.sg_9d() return "sg_9d" end ---八点 ---@return senum function enum.sg_8d() return "sg_8d" end ---七点 ---@return senum function enum.sg_7d() return "sg_7d" end ---六点 ---@return senum function enum.sg_6d() return "sg_6d" end ---五点 ---@return senum function enum.sg_5d() return "sg_5d" end ---4点 ---@return senum function enum.sg_4d() return "sg_4d" end ---3点 ---@return senum function enum.sg_3d() return "sg_3d" end ---2点 ---@return senum function enum.sg_2d() return "sg_2d" end ---1点 ---@return senum function enum.sg_1d() return "sg_1d" end ---0点 ---@return senum function enum.sg_0d() return "sg_1d" end return enum
-- LV Lamp - a powerful light source. -- Illuminates a 7x7x3(H) volume below itself with light bright as the sun. local S = technic.getter local desc = S("%s Lamp"):format("LV") local active_desc = S("%s Active"):format(desc) local unpowered_desc = S("%s Unpowered"):format(desc) local off_desc = S("%s Off"):format(desc) local demand = 50 -- Invisible light source node used for illumination minetest.register_node("technic:dummy_light_source", { description = S("Dummy light source node"), inventory_image = "technic_dummy_light_source.png", wield_image = "technic_dummy_light_source.png", paramtype = "light", drawtype = "airlike", light_source = 14, sunlight_propagates = true, walkable = false, buildable_to = true, diggable = false, pointable = false, --drop = "", -- Intentionally allowed to drop itself groups = {not_in_creative_inventory = 1} }) local function illuminate(pos, active) local pos1 = {x = pos.x - 3, y = pos.y - 1, z = pos.z - 3} local pos2 = {x = pos.x + 3, y = pos.y - 3, z = pos.z + 3} local find_node = active and "air" or "technic:dummy_light_source" local set_node = {name = (active and "technic:dummy_light_source" or "air")} for _,p in pairs(minetest.find_nodes_in_area(pos1, pos2, find_node)) do minetest.set_node(p, set_node) end end local function lamp_run(pos, node) local meta = minetest.get_meta(pos) if meta:get_int("LV_EU_demand") == 0 then return -- Lamp is turned off end local eu_input = meta:get_int("LV_EU_input") if node.name == "technic:lv_lamp_active" then if eu_input < demand then technic.swap_node(pos, "technic:lv_lamp") meta:set_string("infotext", unpowered_desc) illuminate(pos, false) else illuminate(pos, true) end elseif node.name == "technic:lv_lamp" then if eu_input >= demand then technic.swap_node(pos, "technic:lv_lamp_active") meta:set_string("infotext", active_desc) illuminate(pos, true) end end end local function lamp_toggle(pos, node, player) if not player or minetest.is_protected(pos, player:get_player_name()) then return end local meta = minetest.get_meta(pos) if meta:get_int("LV_EU_demand") == 0 then meta:set_string("infotext", active_desc) meta:set_int("LV_EU_demand", demand) else illuminate(pos, false) technic.swap_node(pos, "technic:lv_lamp") meta:set_string("infotext", off_desc) meta:set_int("LV_EU_demand", 0) end end minetest.register_node("technic:lv_lamp", { description = desc, drawtype = "nodebox", node_box = { type = "fixed", fixed = {0.5,0.5,0.5,-0.5,-0.2,-0.5} }, collision_box = { type = "fixed", fixed = {0.5,0.5,0.5,-0.5,-0.2,-0.5} }, selection_box = { type = "fixed", fixed = {0.5,0.5,0.5,-0.5,-0.2,-0.5} }, tiles = { "technic_lv_lamp_top.png", "technic_lv_lamp_bottom.png", "technic_lv_lamp_side.png", "technic_lv_lamp_side.png", "technic_lv_lamp_side.png", "technic_lv_lamp_side.png" }, groups = {cracky = 2, technic_machine = 1, technic_lv = 1}, connect_sides = {"front", "back", "left", "right", "top"}, can_dig = technic.machine_can_dig, technic_run = lamp_run, on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", desc) meta:set_int("LV_EU_demand", demand) end, on_destruct = illuminate, on_rightclick = lamp_toggle }) minetest.register_node("technic:lv_lamp_active", { description = active_desc, drawtype = "nodebox", node_box = { type = "fixed", fixed = {0.5, 0.5, 0.5, -0.5, -0.2, -0.5} }, collision_box = { type = "fixed", fixed = {0.5, 0.5, 0.5, -0.5, -0.2, -0.5} }, selection_box = { type = "fixed", fixed = {0.5, 0.5, 0.5, -0.5, -0.2, -0.5} }, tiles = { "technic_lv_lamp_top.png", "technic_lv_lamp_bottom.png", "technic_lv_lamp_side.png", "technic_lv_lamp_side.png", "technic_lv_lamp_side.png", "technic_lv_lamp_side.png" }, paramtype = "light", light_source = 14, drop = "technic:lv_lamp", groups = {cracky = 2, technic_machine = 1, technic_lv = 1, not_in_creative_inventory = 1}, connect_sides = {"front", "back", "left", "right", "top"}, can_dig = technic.machine_can_dig, technic_run = lamp_run, technic_on_disable = function(pos) illuminate(pos, false) technic.swap_node(pos, "technic:lv_lamp") end, on_destruct = illuminate, on_rightclick = lamp_toggle, }) technic.register_machine("LV", "technic:lv_lamp", technic.receiver) technic.register_machine("LV", "technic:lv_lamp_active", technic.receiver) minetest.register_craft({ output = "technic:lv_lamp", recipe = { {"default:glass", "default:glass", "default:glass"}, {"technic:lv_led", "technic:lv_led", "technic:lv_led"}, {"mesecons_materials:glue", "technic:lv_cable", "mesecons_materials:glue"}, } })
local m = require 'lpeg' local re = require 're' local make_schema = require 'parse.yaml.make.schema' local schema = make_schema() local core_schema = {} core_schema.scalar_tag_resolvers = { re.compile[[ ('null' / ('N' ('ull' / 'ULL')) / '~')? !. ]] * m.Cc'tag:yaml.org,2002:null'; re.compile[[ ( 'true' / ('T' ('rue' / 'RUE')) / 'false' / ('F' ('alse' / 'ALSE')) ) !. ]] * m.Cc'tag:yaml.org,2002:bool'; re.compile[[ [-+]? %d+ !. ]] * m.Cc'tag:yaml.org,2002:int'; re.compile[[ '0o' [0-7]+ !. ]] * m.Cc'tag:yaml.org,2002:int'; re.compile[[ '0x' %x+ !. ]] * m.Cc'tag:yaml.org,2002:int'; re.compile[[ [-+]? ( ('.' %d+) / (%d+ ('.' %d*)?) ) ([eE] [-+]? %d+)? !. ]] * m.Cc'tag:yaml.org,2002:float'; re.compile[[ [-+]? ('.inf' / ('.I' ('nf' / 'NF'))) !. ]] * m.Cc'tag:yaml.org,2002:float'; re.compile[[ ('.nan' / ('.N' [aA] 'N')) !. ]] * m.Cc'tag:yaml.org,2002:float'; default = 'tag:yaml.org,2002:str'; } return core_schema
local fox = Entity.new() local t = fox:add(Transform.new()) t.scale.x = 0.1 t.scale.y = 0.1 t.scale.z = 0.1 t.position.y = -30 fox:add(Renderable.new(assets.models['fox'])) fox:add(SkeletalAnimation.new(assets.models['fox'], assets.animations['fox_run']))
--[[ Copyright 2013 Wiremod Developers https://github.com/wiremod/ 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. ]]-- if VERSION < 140403 and VERSION > 5 then -- VERSION > 5 check added June 2013, to address issues regarding the Steampipe update sometimes setting VERSION to 1. ErrorNoHalt("WireMod: This branch of wiremod only supports Gmod13+.\n") return end if SERVER then -- this file AddCSLuaFile("autorun/wire_load.lua") -- shared includes AddCSLuaFile("wire/wire_paths.lua") AddCSLuaFile("wire/wireshared.lua") AddCSLuaFile("wire/wiregates.lua") AddCSLuaFile("wire/wiremonitors.lua") AddCSLuaFile("wire/gpulib.lua") AddCSLuaFile("wire/cpulib.lua") AddCSLuaFile("wire/timedpairs.lua") AddCSLuaFile("wire/default_data_decompressor.lua") AddCSLuaFile("wire/flir.lua") AddCSLuaFile("wire/von.lua") -- client includes AddCSLuaFile("wire/client/cl_wirelib.lua") AddCSLuaFile("wire/client/cl_modelplug.lua") AddCSLuaFile("wire/client/cl_wire_map_interface.lua") AddCSLuaFile("wire/client/wiredermaexts.lua") AddCSLuaFile("wire/client/wiremenus.lua") AddCSLuaFile("wire/client/wire_expression2_browser.lua") AddCSLuaFile("wire/client/wire_filebrowser.lua") AddCSLuaFile("wire/client/wire_listeditor.lua") AddCSLuaFile("wire/client/wire_soundpropertylist.lua") AddCSLuaFile("wire/client/e2helper.lua") AddCSLuaFile("wire/client/e2descriptions.lua") AddCSLuaFile("wire/client/e2_extension_menu.lua") AddCSLuaFile("wire/client/gmod_tool_auto.lua") AddCSLuaFile("wire/client/sound_browser.lua") AddCSLuaFile("wire/client/thrusterlib.lua") AddCSLuaFile("wire/client/rendertarget_fix.lua") AddCSLuaFile("wire/client/customspawnmenu.lua") -- text editor AddCSLuaFile("wire/client/text_editor/texteditor.lua") AddCSLuaFile("wire/client/text_editor/wire_expression2_editor.lua") AddCSLuaFile("wire/client/text_editor/modes/e2.lua") AddCSLuaFile("wire/client/text_editor/modes/zcpu.lua") -- HL-ZASM AddCSLuaFile("wire/client/hlzasm/hc_compiler.lua") AddCSLuaFile("wire/client/hlzasm/hc_opcodes.lua") AddCSLuaFile("wire/client/hlzasm/hc_expression.lua") AddCSLuaFile("wire/client/hlzasm/hc_preprocess.lua") AddCSLuaFile("wire/client/hlzasm/hc_syntax.lua") AddCSLuaFile("wire/client/hlzasm/hc_codetree.lua") AddCSLuaFile("wire/client/hlzasm/hc_optimize.lua") AddCSLuaFile("wire/client/hlzasm/hc_output.lua") AddCSLuaFile("wire/client/hlzasm/hc_tokenizer.lua") -- ZVM AddCSLuaFile("wire/zvm/zvm_core.lua") AddCSLuaFile("wire/zvm/zvm_features.lua") AddCSLuaFile("wire/zvm/zvm_opcodes.lua") AddCSLuaFile("wire/zvm/zvm_data.lua") if CreateConVar("wire_force_workshop", 1, {FCVAR_ARCHIVE}, "Should Wire force all clients to download the Workshop edition of Wire, for models? (requires restart to disable)"):GetBool() then resource.AddWorkshop("160250458") end end -- shared includes include("wire/wireshared.lua") include("wire/wire_paths.lua") include("wire/wiregates.lua") include("wire/wiremonitors.lua") include("wire/gpulib.lua") include("wire/cpulib.lua") include("wire/timedpairs.lua") include("wire/default_data_decompressor.lua") include("wire/flir.lua") include("wire/von.lua") -- server includes if SERVER then include("wire/server/wirelib.lua") include("wire/server/modelplug.lua") include("wire/server/radiolib.lua") include("wire/server/debuggerlib.lua") end -- client includes if CLIENT then include("wire/client/cl_wirelib.lua") include("wire/client/cl_modelplug.lua") include("wire/client/cl_wire_map_interface.lua") include("wire/client/wiredermaexts.lua") include("wire/client/wiremenus.lua") include("wire/client/text_editor/texteditor.lua") include("wire/client/wire_expression2_browser.lua") include("wire/client/text_editor/wire_expression2_editor.lua") include("wire/client/wire_filebrowser.lua") include("wire/client/wire_listeditor.lua") include("wire/client/wire_soundpropertylist.lua") include("wire/client/e2helper.lua") include("wire/client/e2descriptions.lua") include("wire/client/e2_extension_menu.lua") include("wire/client/gmod_tool_auto.lua") include("wire/client/sound_browser.lua") include("wire/client/thrusterlib.lua") include("wire/client/rendertarget_fix.lua") include("wire/client/hlzasm/hc_compiler.lua") include("wire/client/customspawnmenu.lua") end -- Load UWSVN, done here so its definitely after Wire is loaded. if file.Find("wire/uwsvn_load.lua","LUA")[1] then if SERVER then AddCSLuaFile( "wire/uwsvn_load.lua" ) end include("wire/uwsvn_load.lua") end if SERVER then print("Wiremod Version '"..WireLib.GetVersion().."' loaded") end hook.Run("WiremodLoaded")
require("pgevents") function Definitions() Category = "Raid" TaskForce = { { "RaidForce" ,"DenyHeroAttach" ,"Infantry | Vehicle | Air = 2" ,"LandHero = 0,1" } } LandSecured = false difficulty = "Easy" if PlayerObject then difficulty = PlayerObject.Get_Difficulty() end sleep_duration = DifficultyBasedMinPause(difficulty) end function RaidForce_Thread() AssembleForce(RaidForce) if not RaidForce.Is_Raid_Capable() then ScriptExit() end RaidForce.Set_Plan_Result(true) if not LaunchUnits(RaidForce) then ScriptExit() end BlockOnCommand(RaidForce.Raid(Target)) RaidForce.Set_As_Goal_System_Removable(false) RaidForce.Test_Target_Contrast(false) if RaidForce.Get_Force_Count() == 0 then Sleep(sleep_duration) ScriptExit() end LandSecured = true RaidForce.Release_Forces(1.0) FundBases(PlayerObject, Target) if (not GalacticAttackAllowed(difficulty, 1)) then Sleep(sleep_duration) end ScriptExit() end function RaidForce_Production_Failed(tf, failed_object_type) ScriptExit() end function RaidForce_Original_Target_Owner_Changed(tf, old_owner, new_owner) if new_owner ~= PlayerObject and new_owner.Is_Neutral() == false then if (not LandSecured) or (PlayerObject.Get_Difficulty() == "Hard") then ScriptExit() end end end function RaidForce_No_Units_Remaining(tf) ScriptExit() end
while true do local block = io.read(2^13) if not block then break end io.write(block) end
local null_ls = require("null-ls") -- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/formatting local formatting = null_ls.builtins.formatting -- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/diagnostics local diagnostics = null_ls.builtins.diagnostics null_ls.setup { debug = false, sources = { -- To see supported formatters, visit -- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/formatting formatting.prettier.with { extra_args = { "--no-semi", "--single-quote", "--jsx-single-quote" } }, formatting.black.with { extra_args = { "--fast" } }, -- formatting.yapf, formatting.stylua, diagnostics.flake8, }, }
#!/usr/bin/env tarantool local timer_events = {} local timer_events_private = {} local box = box local fiber = require 'fiber' local inspect = require 'libs/inspect' local digest = require 'digest' local logger = require 'logger' local config = require 'config' local system = require 'system' local scripts = require 'scripts' local http_system = require 'http_system' local timer_event_script_bodies = {} timer_events_private.init_body = [[-- The generated script is filled with the default content -- function event_handler() end]] local function log_timer_events_error(msg, uuid) logger.add_entry(logger.ERROR, "Timer-event subsystem", msg, uuid, "") end local function log_timer_events_warning(msg, uuid) logger.add_entry(logger.WARNING, "Timer-event subsystem", msg, uuid, "") end local function log_timer_events_info(msg, uuid) logger.add_entry(logger.INFO, "Timer-event subsystem", msg, uuid, "") end ------------------↓ Private functions ↓------------------ function timer_events_private.load(uuid) local body local script_params = scripts.get({uuid = uuid}) if (script_params.type ~= scripts.type.TIMER_EVENT) then log_timer_events_error('Attempt to start non-timer-event script "'..script_params.name..'"', script_params.uuid) return false end if (script_params.uuid == nil) then log_timer_events_error('Timer-event script "'..script_params.name..'" not start (not found)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: not found'}) return false end if (script_params.body == nil) then log_timer_events_error('Timer-event script "'..script_params.name..'" not start (body nil)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: no body'}) return false end if (script_params.active_flag == nil or script_params.active_flag ~= scripts.flag.ACTIVE) then --log_timer_events_info('Timer-event script "'..script_params.name..'" not start (non-active)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.STOPPED, status_msg = 'Non-active'}) return true end local current_func, error_msg = loadstring(script_params.body, script_params.name) if (current_func == nil) then log_timer_events_error('Timer-event script "'..script_params.name..'" not start (body load error: '..(error_msg or "")..')', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: body load error: '..(error_msg or "")}) return false end local log_script_name = "Timer-event '"..(script_params.name or "undefined name").."'" body = scripts.generate_body(script_params, log_script_name) local status, returned_data = pcall(setfenv(current_func, body)) if (status ~= true) then log_timer_events_error('Timer-event script "'..script_params.name..'" not start (load error: '..(returned_data or "")..')', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: pcall error: '..(returned_data or "")}) return false end if (body.destroy ~= nil) then if (type(body.destroy) ~= "function") then log_timer_events_error('Timer-event script "'..script_params.name..'" not start (destroy not function)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: destroy not function'}) return false end end if (body.init ~= nil) then if (type(body.init) ~= "function") then log_timer_events_error('Timer-event script "'..script_params.name..'" not start (init not function)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: init not function'}) return false end local init_status, init_returned_data = pcall(body.init) if (init_status ~= true) then log_timer_events_error('Timer-event script "'..script_params.name..'" not start (init function error: '..(init_returned_data or "")..')', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: init function error: '..(init_returned_data or "")}) return false end end if (body.event_handler == nil or type(body.event_handler) ~= "function") then log_timer_events_error('Timer-event "'..script_params.name..'" not start ("event_handler" function not found or no function)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: "event_handler" function not found or no function'}) return false end local sec_counter = tonumber(script_params.object) if (sec_counter == nil or sec_counter < 1) then log_timer_events_error('Timer-event script "'..script_params.name..'" not start (period no number or <1)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Start: period no number or <1'}) return false end timer_event_script_bodies[uuid] = nil timer_event_script_bodies[uuid] = {} timer_event_script_bodies[uuid].body = body timer_event_script_bodies[uuid].counter = 0 timer_event_script_bodies[uuid].period = sec_counter log_timer_events_info('Timer-event script "'..script_params.name..'" active on period '..sec_counter.." s", script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.NORMAL, status_msg = 'Active'}) end function timer_events_private.unload(uuid) local script_params = scripts.get({uuid = uuid}) if (timer_event_script_bodies[uuid] == nil) then log_timer_events_error('Attempt to stop bus-event script "'..script_params.name..'": no loaded', script_params.uuid) return false end local body = timer_event_script_bodies[uuid].body if (script_params.type ~= scripts.type.TIMER_EVENT) then log_timer_events_error('Attempt to stop non-timer-event script "'..script_params.name..'"', script_params.uuid) return false end if (body == nil) then log_timer_events_error('Timer-event script "'..script_params.name..'" not stop (script body error)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Stop: script body error'}) return false end if (body.init ~= nil) then if (type(body.init) ~= "function") then log_timer_events_error('Timer-event script "'..script_params.name..'" not stop (init not function)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Stop: init not function'}) return false end end if (body.destroy ~= nil) then if (type(body.destroy) ~= "function") then log_timer_events_error('Timer-event script "'..script_params.name..'" not stop (destroy not function)', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Stop: destroy not function'}) return false end local destroy_status, destroy_returned_data = pcall(body.destroy) if (destroy_status ~= true) then log_timer_events_error('Timer-event script "'..script_params.name..'" not stop (destroy function error: '..(destroy_returned_data or "")..')', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.ERROR, status_msg = 'Stop: destroy function error: '..(destroy_returned_data or "")}) return false end if (destroy_returned_data == false) then log_timer_events_warning('Timer-event script "'..script_params.name..'" not stopped, need restart glial', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.WARNING, status_msg = 'Not stopped, need restart glial'}) return false end end log_timer_events_info('Timer-event script "'..script_params.name..'" set status to non-active', script_params.uuid) scripts.update({uuid = uuid, status = scripts.statuses.STOPPED, status_msg = 'Not active'}) timer_event_script_bodies[uuid] = nil return true end function timer_events_private.reload(uuid) local data = scripts.get({uuid = uuid}) if (data.status == scripts.statuses.NORMAL or data.status == scripts.statuses.WARNING) then local result = timer_events_private.unload(uuid) if (result == true) then return timer_events_private.load(uuid, false) else return false end else return timer_events_private.load(uuid, false) end end function timer_events_private.process() for uuid, scripts_table in pairs(timer_event_script_bodies) do local script_params = scripts.get({uuid = uuid}) if (script_params.status == scripts.statuses.NORMAL and script_params.active_flag == scripts.flag.ACTIVE and type(scripts_table.counter) == "number") then if (scripts_table.counter <= 1) then if (type(scripts_table.body.event_handler) == "function") then local status, returned_data, time = system.pcall_timecalc(scripts_table.body.event_handler) scripts.update_worktime(uuid, time) if (status ~= true) then returned_data = tostring(returned_data) log_timer_events_error('Timer-event script event "'..script_params.name..'" generate error: '..(returned_data or ""), script_params.uuid) scripts.update({uuid = script_params.uuid, status = scripts.statuses.ERROR, status_msg = 'Timer-event script error: '..(returned_data or "")}) end end scripts_table.counter = scripts_table.period else scripts_table.counter = scripts_table.counter - 1 end end fiber.yield() end end function timer_events_private.worker() while true do timer_events_private.process() fiber.sleep(1) end end ------------------↓ HTTP API functions ↓------------------ function timer_events_private.http_api_get_list(params, req) local tag if (params["tag"] ~= nil) then tag = digest.base64_decode(params["tag"]) end local table = scripts.get_list(scripts.type.TIMER_EVENT, tag) return req:render{ json = table } end function timer_events_private.http_api_get_tags(params, req) local table = scripts.get_tags() return req:render{ json = table } end function timer_events_private.http_api_create(params, req) local data = {} if (params["name"] ~= nil) then data.name = digest.base64_decode(params["name"]) end if (params["object"] ~= nil) then data.object = digest.base64_decode(params["object"]) end if (params["comment"] ~= nil) then data.comment = digest.base64_decode(params["comment"]) end if (params["tag"] ~= nil) then data.tag = digest.base64_decode(params["tag"]) end local status, table, err_msg = scripts.create(data.name, scripts.type.TIMER_EVENT, data.object, data.tag, data.comment, timer_events_private.init_body) return req:render{ json = {result = status, script = table, err_msg = err_msg} } end function timer_events_private.http_api_copy(params, req) local status, table, err_msg = scripts.copy(digest.base64_decode(params["name"]), params["uuid"]) return req:render{ json = {result = status, script = table, err_msg = err_msg} } end function timer_events_private.http_api_delete(params, req) if (params["uuid"] ~= nil and params["uuid"] ~= "") then local script_table = scripts.get({uuid = params["uuid"]}) if (script_table ~= nil) then if (script_table.status ~= scripts.statuses.STOPPED) then script_table.unload_result = timer_events_private.unload(params["uuid"]) if (script_table.unload_result == true) then script_table.delete_result = scripts.delete({uuid = params["uuid"]}) else log_timer_events_warning('Timer-event script "'..script_table.name..'" not deleted(not stopped), need restart glial', script_table.uuid) scripts.update({uuid = script_table.uuid, status = scripts.statuses.WARNING, status_msg = 'Not deleted(not stopped), need restart glial'}) end return req:render{ json = script_table } else script_table.delete_result = scripts.delete({uuid = params["uuid"]}) return req:render{ json = script_table } end else return req:render{ json = {result = false, error_msg = "Timer-event API delete: UUID not found"} } end else return req:render{ json = {result = false, error_msg = "Timer-event API delete: no UUID"} } end end function timer_events_private.http_api_get(params, req) if (params["uuid"] ~= nil and params["uuid"] ~= "") then local table = scripts.get({uuid = params["uuid"]}) if (table ~= nil) then return req:render{ json = table } else return req:render{ json = {result = false, error_msg = "Timer-event API get: UUID not found"} } end else return req:render{ json = {result = false, error_msg = "Timer-event API get: no UUID"} } end end function timer_events_private.http_api_reload(params, req) if (params["uuid"] ~= nil and params["uuid"] ~= "") then if (scripts.get({uuid = params["uuid"]}) ~= nil) then local result = timer_events_private.reload(params["uuid"]) return req:render{ json = {result = result} } else return req:render{ json = {result = false, error_msg = "Timer-event API reload: UUID not found"} } end else return req:render{ json = {result = false, error_msg = "Timer-event API reload: no valid UUID"} } end end function timer_events_private.http_api_update(params, req) if (params["uuid"] ~= nil and params["uuid"] ~= "") then if (scripts.get({uuid = params["uuid"]}) ~= nil) then local data = {} data.uuid = params["uuid"] data.active_flag = params["active_flag"] if (params["name"] ~= nil) then data.name = digest.base64_decode(params["name"]) end if (params["object"] ~= nil) then data.object = digest.base64_decode(params["object"]) end if (params["comment"] ~= nil) then data.comment = digest.base64_decode(params["comment"]) end if (params["tag"] ~= nil) then data.tag = digest.base64_decode(params["tag"]) end local table = scripts.update(data) table.reload_result = timer_events_private.reload(params["uuid"]) return req:render{ json = table } else return req:render{ json = {result = false, error_msg = "Timer-event API update: UUID not found"} } end else return req:render{ json = {result = false, error_msg = "Timer-event API update: no UUID"} } end end function timer_events_private.http_api_update_body(params, req) local uuid = req:query_param().uuid local post_params = req:post_param() local text_base64 = pairs(post_params)(post_params) local text_decoded local data = {} local _,_, base_64_string = string.find(text_base64 or "", "data:text/plain;base64,(.+)") if (base_64_string ~= nil) then text_decoded = digest.base64_decode(base_64_string) end if (uuid ~= nil and text_decoded ~= nil) then data.uuid = uuid data.body = text_decoded if (scripts.get({uuid = uuid}) ~= nil) then local table = scripts.update(data) if (params["reload"] ~= "none") then table.reload_result = timer_events_private.reload(params["uuid"]) end return req:render{ json = table } else return req:render{ json = {result = false, error_msg = "Timer-event API body update: UUID not found"} } end else return req:render{ json = {result = false, error_msg = "Timer-event API body update: no UUID or no body"} } end end function timer_events_private.http_api(req) local params = req:param() local return_object if (params["action"] == "reload") then return_object = timer_events_private.http_api_reload(params, req) elseif (params["action"] == "get_list") then return_object = timer_events_private.http_api_get_list(params, req) elseif (params["action"] == "get_tags") then return_object = timer_events_private.http_api_get_tags(params, req) elseif (params["action"] == "update") then return_object = timer_events_private.http_api_update(params, req) elseif (params["action"] == "update_body") then return_object = timer_events_private.http_api_update_body(params, req) elseif (params["action"] == "create") then return_object = timer_events_private.http_api_create(params, req) elseif (params["action"] == "copy") then return_object = timer_events_private.http_api_copy(params, req) elseif (params["action"] == "delete") then return_object = timer_events_private.http_api_delete(params, req) elseif (params["action"] == "get") then return_object = timer_events_private.http_api_get(params, req) else return_object = req:render{ json = {result = false, error_msg = "Timer-event API: No valid action"} } end return_object = return_object or req:render{ json = {result = false, error_msg = "Timer-event API: unknown error(2433)"} } return system.add_headers(return_object) end ------------------↓ Public functions ↓------------------ function timer_events.init() timer_events.start_all() fiber.create(timer_events_private.worker) http_system.endpoint_config("/timerevents", timer_events_private.http_api) end function timer_events.start_all() local list = scripts.get_all({type = scripts.type.TIMER_EVENT}) for _, timer_event in pairs(list) do timer_events_private.load(timer_event.uuid) fiber.yield() end end return timer_events
local skynet = require "skynet" local cluster = require "skynet.cluster" local faci = require "faci.module" local module = faci.get_module("login") local dispatch = module.dispatch local forward = module.forward local event = module.event env.users = env.users or {} --users[uid]={ --node = skynet.getenv("nodename"), --fd = fd, --gate = source, --agent = agent 的source (register后才有) --key = key --登录时的key,验证登录服的唯一性 --} --true/false function dispatch.login(uid, data) local user = env.users[uid] --正常登录 if not user then env.users[uid] = data --log.debug("center login: %d", uid) return true end --登录过程中 if not user.agent then log.debug("center %d login fail not user.game", uid) return false end --踢下线 --if not dispatch.logout(uid, user.key, "login in other place") then -- log.debug("center %d login fail not not D.logout", uid) -- return false --end --gate的 向gate 发kick 原因 需要关闭客户端之前的连接 --local ret = cluster.call(user.node, user.gate, "kick", user.fd) local ret = skynet.call(user.gate, 'lua', 'kick', user.fd) if not ret then log.debug("center logout call gate fail") return false end user = env.users[uid] if user then log.debug("have login uid: " .. uid) return false end env.users[uid] = data return true end --true/false function dispatch.register(uid, data) local user = env.users[uid] if not user then log.debug("center %d register fail, not user", uid) return false end if user.key ~= data.key then log.debug("center %d register fail, key err", uid) return false end if user.agent then log.debug("center %d register fail, has game", uid) return false end --log.debug("center register: %d", uid) user.agent = data.agent user.logined = 1 return true end --true/false function dispatch.logout(uid, key, season) local user = env.users[uid] if not user then return true end if user.key ~= key then log.debug("center logout key fail") return false end if user.agent then --agent --local ret = cluster.call(user.node, user.agent, "kick", uid, season) local ret = skynet.call(user.agent, 'lua', 'kick', uid, season) if not ret then log.debug("center logout call agent fail") return false end -- --gate的 取消向gate 发kick 原因 gate kick又会调用到此 -- local ret = cluster.call(user.node, user.gate, "kick", user.fd) -- if not ret then -- log.debug("center logout call gate fail") -- return false -- end end env.users[uid] = nil --DEBUG("++++++++++center logout uid: ", uid, "++++++++++++++") return true end function module.watch(acm) --统计在线人数 local logined = 0 --成功登陆 local logining = 0 --登陆流程 for i, v in pairs(env.users) do if v.logined then logined = logined + 1 else logining = logining + 1 end end local ret = {logined = logined, logining = logining} --总统计 acm.logined = acm.logined and acm.logined + logined or logined acm.logining = acm.logining and acm.logining + logining or logining return ret, acm end
class("StateStartingGrid") function StateStartingGrid:__init(race) ; EGUSM.SubscribeUtility.__init(self) self.race = race -- Number of times PostTick has been called. self.numTicks = 0 -- Array of Racers. This is used to call UpdateRacer on us once per tick. self.updateList = {} for id , racer in pairs(self.race.playerIdToRacer) do table.insert(self.updateList , racer) end -- Assign racers local course = self.race.course local numRacers = table.count(self.race.playerIdToRacer) local maxRacers = course:GetMaxPlayers() if numRacers > maxRacers and self.race.overflowHandling ~= Race.OverflowHandling.StackSpawns then error("Too many racers for course! "..course.name..", "..numRacers.."/"..maxRacers) end local racers = {} for id , racer in pairs(self.race.playerIdToRacer) do table.insert(racers , racer) end -- Randomly sort the racers table. Otherwise, the starting grid is consistent; we want it to -- always be completely random. table.sortrandom(racers) -- Assign racers to spawns. local spawnIndex = 1 for index , racer in ipairs(racers) do racer.startPosition = index -- TODO: Starting grid bug is here. local IsRacerCompatibleWithSpawn = function(spawn) -- This is WAY more complex than it should be. It should just be able to compare an index. for index , vehicleInfo in ipairs(spawn.vehicleInfos) do if vehicleInfo.modelId ~= racer.assignedVehicleInfo.modelId then goto continue end if #vehicleInfo.templates == 0 then goto continue end for index , template in ipairs(vehicleInfo.templates) do if racer.assignedVehicleInfo.template == template then return true end end ::continue:: end return false end local foundSpawn = false for index , spawn in ipairs(course.spawns) do if spawn.racer == nil and IsRacerCompatibleWithSpawn(spawn) == true then spawn.racer = racer foundSpawn = true break end end if foundSpawn == false then warn("Could not find appropriate spawn for "..tostring(racer.player)) for index , spawn in ipairs(course.spawns) do if spawn.racer == nil then spawn.racer = racer break end end end spawnIndex = spawnIndex + 1 end -- Spawn vehicles for n , spawn in ipairs(course.spawns) do if spawn.racer then spawn:SpawnVehicle() end end -- Spawn checkpoints for n, checkpoint in ipairs(course.checkpoints) do checkpoint:Spawn() end -- Spawn racers for n , spawn in ipairs(course.spawns) do spawn:SpawnRacer() end self.startTimer = Timer() -- Loop through all racers -- * Set their world. -- * Create their raceTimer. for playerId , racer in pairs(self.race.playerIdToRacer) do racer.raceTimer = Timer() racer.player:SetWorld(self.race.world) racer.player:SetNetworkValue( "GameMode", "Гонки" ) end -- Update database. -- TODO: why is this here Stats.RaceStart(self.race) -- TODO: This is completely broken. self.startPositions = {} for playerId , racer in pairs(self.race.playerIdToRacer) do self.startPositions[racer.playerId] = racer.startPosition end -- Send info to clients. local args = { stateName = "StateStartingGrid" , startPositions = self.startPositions } for id , racer in pairs(self.race.playerIdToRacer) do args.assignedVehicleId = racer.assignedVehicleId Network:Send(racer.player , "RaceSetState" , args) end args.assignedVehicleId = nil for id , spectator in pairs(self.race.playerIdToSpectator) do Network:Send(spectator.player , "RaceSetState" , args) end self:EventSubscribe("PostTick") self:EventSubscribe("PlayerEnterVehicle") self:EventSubscribe("PlayerSpawn") end function StateStartingGrid:End() self:Destroy() end function StateStartingGrid:UpdateRacer(racer) -- If they travel too far from their starting slot, respawn them. local shouldRespawn = false if racer.assignedVehicleId == -1 then local distance = Vector3.Distance2D(racer.courseSpawn.position , racer.player:GetPosition()) if distance >= 1.2 and distance < 150 then shouldRespawn = true end else local vehicle = Vehicle.GetById(racer.assignedVehicleId) if vehicle then -- Dilute the effect of the Y axis on the resulting distance. local a = Copy(racer.courseSpawn.position) local b = Copy(vehicle:GetPosition()) a.y = a.y * 0.4 b.y = b.y * 0.4 local distanceSquared = Vector3.DistanceSqr(a , b) if distanceSquared >= 4.2 then shouldRespawn = true end if vehicle:GetHealth() < 0.75 then shouldRespawn = true end end end if shouldRespawn then if settings.debugLevel >= 2 then print("Respawning player because they're out of their starting slot") end racer:Respawn() end end -- Race callbacks function StateStartingGrid:RacerLeave(racerThatLeft) -- Remove them from self.startPositions. for playerId , startPosition in pairs(self.startPositions) do if playerId == racerThatLeft.playerId then self.startPositions[playerId] = nil break end end -- Remove them from self.updateList. for index , racer in ipairs(self.updateList) do if racer.player == racerThatLeft.player then table.remove(self.updateList , index) break end end end -- Events function StateStartingGrid:PostTick() if self.startTimer:GetSeconds() >= self.race.startingGridSeconds then self.race:SetState("StateRacing") end -- Call UpdateRacer on one racer. If the list is less than 50, then sometimes skip. local index = (self.numTicks % math.max(50 , #self.updateList)) + 1 if index <= #self.updateList then local racer = self.updateList[index] if IsValid(racer.player) then self:UpdateRacer(racer) end end self.numTicks = self.numTicks + 1 end function StateStartingGrid:PlayerEnterVehicle(args) local racer = self.race.playerIdToRacer[args.player:GetId()] if racer then racer:EnterVehicle(args) end end function StateStartingGrid:PlayerSpawn(args) local racer = self.race.playerIdToRacer[args.player:GetId()] if racer then racer:Respawn() end return false end
ITEM.name = "Glock 17" ITEM.description= "An Austrian handgun that fires 9x19mm." ITEM.longdesc = "The Glock is an Austrian polymer handgun, famous for it's price, reliability and trigger safety mechanism.\nIt's favored by police agencies around the world and comes in many flavors.\n\nAmmo: 9x19mm\nMagazine Capacity: 17" ITEM.model = "models/cw2_g18/w_dmg_glock.mdl" ITEM.class = "cw_glock17" ITEM.weaponCategory = "secondary" ITEM.price = 4800 ITEM.width = 2 ITEM.height = 1 ITEM.validAttachments = {"md_tundra9mm"} ITEM.bulletweight = 0.008 ITEM.unloadedweight = 0.625 ITEM.repair_PartsComplexity = 1 ITEM.repair_PartsRarity = 3 function ITEM:GetWeight() return self.unloadedweight + (self.bulletweight * self:GetData("ammo", 0)) end ITEM.iconCam = { pos = Vector(20, 0, -2.9000000953674), ang = Angle(0, 180, 5), fov = 45, } ITEM.pacData = { [1] = { ["children"] = { [1] = { ["children"] = { [1] = { ["children"] = { }, ["self"] = { ["Model"] = "models/cw2_g18/w_dmg_glock.mdl", ["ClassName"] = "model", ["Position"] = Vector(-6.774, 2.172, 3.359), ["EditorExpand"] = true, ["UniqueID"] = "3547633835", ["Bone"] = "pelvis", ["Name"] = "glock17", ["Angles"] = Angle(180, 0, 210), }, }, }, ["self"] = { ["AffectChildrenOnly"] = true, ["ClassName"] = "event", ["UniqueID"] = "1640766402", ["Event"] = "weapon_class", ["EditorExpand"] = true, ["Name"] = "weapon class find simple\"@@1\"", ["Arguments"] = "cw_glock17@@0", }, }, }, ["self"] = { ["ClassName"] = "group", ["UniqueID"] = "1980487467", ["EditorExpand"] = true, }, }, }
-- Neuron is a World of Warcraft® user interface addon. -- Copyright (c) 2017-2021 Britt W. Yazel -- Copyright (c) 2006-2014 Connor H. Chenoweth -- This code is licensed under the MIT license (see LICENSE for details) ---@class EXTRABTN : BUTTON @define class EXTRABTN inherits from class BUTTON local EXTRABTN = setmetatable({}, { __index = Neuron.BUTTON }) Neuron.EXTRABTN = EXTRABTN ---------------------------------------------------------- ---Constructor: Create a new Neuron BUTTON object (this is the base object for all Neuron button types) ---@param bar BAR @Bar Object this button will be a child of ---@param buttonID number @Button ID that this button will be assigned ---@param defaults table @Default options table to be loaded onto the given button ---@return EXTRABTN @ A newly created EXTRABTN object function EXTRABTN.new(bar, buttonID, defaults) --call the parent object constructor with the provided information specific to this button type local newButton = Neuron.BUTTON.new(bar, buttonID, EXTRABTN, "ExtraBar", "ExtraActionButton", "NeuronActionButtonTemplate") if defaults then newButton:SetDefaults(defaults) end return newButton end ---------------------------------------------------------- function EXTRABTN:SetType() self:RegisterEvent("UPDATE_EXTRA_ACTIONBAR", "OnEvent") self:RegisterEvent("ZONE_CHANGED", "OnEvent") self:RegisterEvent("SPELLS_CHANGED", "OnEvent") self:RegisterEvent("PLAYER_ENTERING_WORLD", "OnEvent") self:RegisterEvent("SPELL_UPDATE_COOLDOWN", "OnEvent") self:RegisterEvent("SPELL_UPDATE_CHARGES", "OnEvent") self:RegisterEvent("SPELL_UPDATE_USABLE", "OnEvent") self:SetAttribute("type1", "action") self:SetAttribute("action1", 169) --baseline actionID for most extra actions self:SetSize(52,52) self.Style:SetPoint("CENTER", -2, 0) --action content gets set in UpdateData self:UpdateData() self:SetScript("PostClick", function() self:SetChecked(false) end) self:SetScript("OnEnter", function(self) self:UpdateTooltip() end) self:SetScript("OnLeave", GameTooltip_Hide) self:SetSkinned() end function EXTRABTN:OnEvent(event, ...) self:UpdateData() if event == "PLAYER_ENTERING_WORLD" then self.Binder:ApplyBindings() self:UpdateIcon() end end ---overwrite function in parent class BUTTON function EXTRABTN:UpdateData() --get specific extrabutton actionID. Try to query it long form, but if it can't will fall back to 169 (as is the 7.0+ default) if HasExtraActionBar() then --default to 169 as is the most of then the case as of 8.1 self.actionID = 169 local extraPage = GetExtraBarIndex() self.actionID = extraPage*12 - 11 --1st slot on the extraPage (page 15 as of 8.1, so 169) if not InCombatLockdown() then self:SetAttribute("action1", self.actionID) end _, self.spellID = GetActionInfo(self.actionID) if self.spellID then self.spell = GetSpellInfo(self.spellID); else self.spell = nil end else self.actionID = nil self.spellID = nil self.spell = nil end ----------------------- self.Name:Hide() self:UpdateObjectVisibility() self:UpdateIcon() self:UpdateCooldown() --extra button charges (some quests have ability charges) self:UpdateCount() --make sure our button gets the correct Normal texture if we're not using a Masque skin self:UpdateNormalTexture() end function EXTRABTN:UpdateObjectVisibility() if HasExtraActionBar() then --set alpha instead of :Show or :Hide, to avoid taint and to allow the button to appear in combat self.isShown = true else self.isShown = false end Neuron.BUTTON.UpdateObjectVisibility(self) --call parent function end ---overwrite function in parent class BUTTON function EXTRABTN:UpdateIcon() local spellTexture = GetSpellTexture(self.spellID) self.Icon:SetTexture(spellTexture) local texture = GetOverrideBarSkin() or "Interface\\ExtraButton\\Default" self.Style:SetTexture(texture) if self.bar.data.showBorderStyle then self.Style:Show() --this actually show/hide the fancy button theme surrounding the bar. If you wanted to do a toggle for the style, it should be here. else self.Style:Hide() end end function EXTRABTN:UpdateTooltip() if not self.isShown then return end if self.bar then if self.tooltipsCombat and InCombatLockdown() then return end if self.tooltips then GameTooltip:SetOwner(self, "ANCHOR_RIGHT") if self.tooltipsEnhanced and self.spellID then GameTooltip:SetSpellByID(self.spellID) elseif self.spell then GameTooltip:SetText(self.spell) end GameTooltip:Show() end end end
module(..., lunit.testcase, package.seeall) local common = dofile("common.lua") local http = require("luanode.http") -- Verify that the HTTP server implementation handles multiple instances -- of the same header as per RFC2616: joining the handful of fields by ', ' -- that support it, and dropping duplicates for other fields. function test() local srv = http.createServer(function(self, req, res) assert_equal('abc, def, ghijklmnopqrst', req.headers.accept) assert_equal('foo', req.headers.host) assert_equal('bingo', req.headers['x-foo']) assert_equal('banjo, bango', req.headers['x-bar']) res:writeHead(200, {['Content-Type'] = 'text/plain'}) res:finish('EOF') self:close() end) srv:listen(common.PORT, function () local hc = http.createClient(common.PORT, 'localhost') local hr = hc:request('/', { {'accept', 'abc'}, {'accept', 'def'}, {'Accept', 'ghijklmnopqrst'}, {'host', 'foo'}, {'Host', 'bar'}, {'hOst', 'baz'}, {'x-foo', 'bingo'}, {'x-bar', 'banjo'}, {'x-bar', 'bango'} }) hr:finish() end) process:loop() end
return { Name = "run"; Aliases = {}; Description = "Runs a given command string (replacing embedded commands)."; Group = "DefaultUtil"; Args = { { Type = "string"; Name = "Command"; Description = "The command string to run" }, }; Run = function(context, command) return context.Dispatcher:EvaluateAndRun(context.Cmdr.Util.RunEmbeddedCommands(context.Dispatcher, command)) end }
object_tangible_loot_creature_loot_kashyyyk_loot_bolotaur_fang_01 = object_tangible_loot_creature_loot_kashyyyk_loot_shared_bolotaur_fang_01:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_kashyyyk_loot_bolotaur_fang_01, "object/tangible/loot/creature_loot/kashyyyk_loot/bolotaur_fang_01.iff")
package.path = './data/lua/?.lua;' .. package.path require("io/piumk6/defs") require("iop/output-anim") require("screen/attract/defs") local ANIM_CAB_CYCLE_TIME_MS = 3000 local ANIM_PAD_CYCLE_TIME_MS = 2800 local ANIM_TIME_CAB_MS = 300 local ANIM_TIME_PAD_MS = 200 local __anim_cab local __anim_pad local __selection_confirmed = false local function __init() __anim_cab = iop_output_anim_create(ANIM_CAB_CYCLE_TIME_MS) __anim_pad = iop_output_anim_create(ANIM_PAD_CYCLE_TIME_MS) -- similar to nx title screen -- cabinet iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOL2, ANIM_TIME_CAB_MS * 0, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOL1, ANIM_TIME_CAB_MS * 0, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOR2, ANIM_TIME_CAB_MS * 1, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOR1, ANIM_TIME_CAB_MS * 1, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_BASS, ANIM_TIME_CAB_MS * 2, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOR2, ANIM_TIME_CAB_MS * 4, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOR1, ANIM_TIME_CAB_MS * 4, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOL2, ANIM_TIME_CAB_MS * 5, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOL1, ANIM_TIME_CAB_MS * 5, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_BASS, ANIM_TIME_CAB_MS * 6, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOL2, ANIM_TIME_CAB_MS * 8, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOL1, ANIM_TIME_CAB_MS * 8, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOR2, ANIM_TIME_CAB_MS * 8, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_HALOR1, ANIM_TIME_CAB_MS * 8, ANIM_TIME_CAB_MS) iop_output_anim_add_event_digital(__anim_cab, IO_PIUMK6_DO_BASS, ANIM_TIME_CAB_MS * 8, ANIM_TIME_CAB_MS) -- pad iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_LU, ANIM_TIME_PAD_MS * 0, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_RU, ANIM_TIME_PAD_MS * 1, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_CN, ANIM_TIME_PAD_MS * 2, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_LD, ANIM_TIME_PAD_MS * 3, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_RD, ANIM_TIME_PAD_MS * 4, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_RU, ANIM_TIME_PAD_MS * 5, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_LU, ANIM_TIME_PAD_MS * 6, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_CN, ANIM_TIME_PAD_MS * 7, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_RD, ANIM_TIME_PAD_MS * 8, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_LD, ANIM_TIME_PAD_MS * 9, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_LU, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_RU, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_CN, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_LD, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P1_RD, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_RU, ANIM_TIME_PAD_MS * 0, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_LU, ANIM_TIME_PAD_MS * 1, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_CN, ANIM_TIME_PAD_MS * 2, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_RD, ANIM_TIME_PAD_MS * 3, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_LD, ANIM_TIME_PAD_MS * 4, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_LU, ANIM_TIME_PAD_MS * 5, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_RU, ANIM_TIME_PAD_MS * 6, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_CN, ANIM_TIME_PAD_MS * 7, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_LD, ANIM_TIME_PAD_MS * 8, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_RD, ANIM_TIME_PAD_MS * 9, ANIM_TIME_PAD_MS) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_LU, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_RU, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_CN, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_LD, 2200, 400) iop_output_anim_add_event_digital(__anim_pad, IO_PIUMK6_DO_P2_RD, 2200, 400) end local function __activate() iop_output_anim_start(__anim_cab) iop_output_anim_start(__anim_pad) __selection_confirmed = false end local function __deactivate() end local function __process(src) local dest = { digital = {}, analog = {}, analog_u8 = {}, text = {} } if src.digital[SCREEN_ATTRACT_DO_EXIT_SCREEN] == true then -- turn all lights off for i = IO_PIUMK6_DO_P1_LU, IO_PIUMK6_DO_HALOL1 do dest.digital[i] = false end elseif __selection_confirmed == true or src.digital[SCREEN_ATTRACT_DO_ENTRY_SELECTION_CONFIRMED] == true then -- all lights on for i = IO_PIUMK6_DO_P1_LU, IO_PIUMK6_DO_HALOL1 do dest.digital[i] = true end __selection_confirmed = true else local light_state = src.analog_u8[SCREEN_ATTRACT_AO_LIGHT_ANIMATION_STATE] if light_state == SCREEN_ATTRACT_LA_ATTRACT then iop_output_anim_update(__anim_cab, dest) iop_output_anim_update(__anim_pad, dest) elseif light_state == SCREEN_ATTRACT_LA_ENTRY then iop_output_anim_update(__anim_cab, dest) iop_output_anim_update(__anim_pad, dest) elseif light_state == SCREEN_ATTRACT_LA_OFF then -- execution, turn everything off -- restart animation if application can't be started iop_output_anim_start(__anim_cab) iop_output_anim_start(__anim_pad) for i = IO_PIUMK6_DO_P1_LU, IO_PIUMK6_DO_HALOL1 do dest.digital[i] = false end end end return dest end return { device = IO_PIUMK6_IDENTIFIER, screen = SCREEN_ATTRACT_IDENTIFIER, f_init = __init, f_activate = __activate, f_deactivate = __deactivate, f_process = __process, }
require('init'); tester = torch.Tester() tester:add(require('test.Linear')) tester:add(require('test.TransferFunctionALU')) tester:add(require('test.TransferFunctionReCU')) tester:add(require('test.TransferFunctionFactory')) tester:add(require('test.NetworkSequential')) tester:add(require('test.NetworkScalarFunction')) tester:add(require('test.ErrorCriterionSquare')) tester:add(require('test.ErrorCriterionSquareRelative')) tester:add(require('test.ErrorCriterionRelative')) tester:add(require('test.ApproximationNormalizatorFactory')) tester:run()
require "my_init" local skynet = require "skynet" local match = require "match" local match_mgr = require "match_mgr" local id = tonumber(...) local CMD = {} function CMD.create_game(info) local obj = match.new(info) match_mgr:add(obj) end function CMD.dissolve_game(room_info) local match = match_mgr:get(room_info.room_id) match:on_outside_force_end() match_mgr:remove_by_id(room_info.room_id) end function CMD.on_user_offline(info) local id = info.room_id local match = match_mgr:get(id) match:on_user_offline(info.account) end function CMD.on_user_login(info) local id = info.room_id local match = match_mgr:get(id) match:on_user_login(info.player_info) end function CMD.deal_game_msg(account, msg) local match = match_mgr:get(msg.id) return match:deal_msg(account, msg.proto_name, msg.content) end skynet.start(function () skynet.dispatch("lua", function (_, session, cmd, ...) local f = CMD[cmd] assert(f, cmd) if session == 0 then f(...) else skynet.ret(skynet.pack(f(...))) end end) match_mgr:init() end)
object_tangible_container_food_shared_ice_cream_fryer = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/container/food/shared_ice_cream_fryer.iff" } ObjectTemplates:addClientTemplate(object_tangible_container_food_shared_ice_cream_fryer, "object/tangible/container/food/shared_ice_cream_fryer.iff") ------------------------------------------------------------------------------------------------------------------------------------
local lib = {} -- Returns the current lua local path to this script. local function scriptPath() local str = debug.getinfo(2, "S").source:sub(2) return str:match("(.*/)") or "" end local libpath = scriptPath() -- These two libraries hook directly into native lua functions. require(libpath .. "/math") require(libpath .. "/utility") -- Default libraries. lib.color = require(libpath .. "/color") lib.collision = require(libpath .. "/collision") lib.vector = require(libpath .. "/vector") lib.gamedata = require(libpath .. "/gamedata") lib.gamestate = require(libpath .. "/gamestate") lib.camera = require(libpath .. "/camera") -- Input libraries. lib.keys = require(libpath .. "/keys") lib.mouse = require(libpath .. "/mouse") lib.joystick = require(libpath .. "/joystick") -- Uncomment the following line to make the library objects global without using the library object reference. -- color, collision, vector, gamedata,´gamestate, camera, keys, mouse, joystick = lib.color, lib.collision, lib.vector, lib.gamedata, lib.gamestate, lib.camera, lib.keys, lib.mouse, lib.joystick return lib -- Return the library reference to the user.
set('srcdir', '$dir') cflags{ '-Wall', '-Wextra', '-Wno-unused-parameter', '-pedantic', '-std=c11', } file('libexec/applyperms', '755', exe('applyperms', {'applyperms.c'})) file('libexec/devd-trigger', '755', exe('devd-trigger', {'devd-trigger.c'})) file('libexec/mergeperms', '755', exe('mergeperms', {'mergeperms.c'})) file('libexec/shutdown', '755', exe('shutdown', {'shutdown.c'})) file('bin/devd', '755', exe('devd', {'devd.c'})) file('bin/syslogd', '755', exe('syslogd', {'syslogd.c'}))
-- 矩形モジュール local Rectangle = {} -- 横アライメントの割合 local hAligns = { left = 0, center = 0.5, right = 1 } -- 縦アライメントの割合 local vAligns = { top = 0, middle = 0.5, bottom = 1 } -- アライメントのオフセットを取得 local function alignOffsets(w, h, h_align, v_align) local x, y = 0, 0 w = w or 0 h = h or 0 -- 横アライメントのデフォルトは left h_align = h_align or 'left' --横アライメントのみ center が指定されていれば、縦アライメントは middle if h_align == 'center' and v_align == nil then v_align = 'middle' end -- 縦アライメントのデフォルトは top v_align = v_align or 'top' -- 横アライメント if type(h_align) == 'number' then -- 数値ならそのまま渡す x = h_align else x = w * hAligns[h_align] end -- 縦アライメント if type(v_align) == 'number' then -- 数値ならそのまま渡す y = v_align else y = h * vAligns[v_align] end return x, y end -- 初期化 function Rectangle:initializeRectangle(x, y, w, h, h_align, v_align) self.x = x or self.x or 0 self.y = y or self.y or 0 self.width = w or self.width or 0 self.height = h or self.height or 0 local pivotX, pivotY = alignOffsets(self.width, self.height, h_align, v_align) self.pivotX = h_align and pivotX or self.pivotX self.pivotY = (h_align == 'center' or v_align) and pivotY or self.pivotY -- プライベート self._rectangle = {} end -- 矩形の描画 function Rectangle:drawRectangle() love.graphics.rectangle('line', self:left(), self:top(), self:right() - self:left(), self:bottom() - self:top()) end -- 左端の座標 function Rectangle:left() return self.x - self.pivotX end -- 右端の座標 function Rectangle:right() return self:left() + self.width end -- 横の中心の座標 function Rectangle:center() return self:left() + self.width * 0.5 end -- 上端の座標 function Rectangle:top() return self.y - self.pivotY end -- 下端の座標 function Rectangle:bottom() return self:top() + self.height end -- 縦の中心の座標 function Rectangle:middle() return self:top() + self.height * 0.5 end return Rectangle
local addonName = ... local addon = _G[addonName] addon.Config = {} function addon.Config:OnShow(...) _G["BrewSpeakConfigFrameBattleground"]:SetChecked(addon.db.Battleground) _G["BrewSpeakConfigFrameGuild"]:SetChecked(addon.db.Guild) _G["BrewSpeakConfigFrameOfficer"]:SetChecked(addon.db.Officer) _G["BrewSpeakConfigFrameParty"]:SetChecked(addon.db.Party) _G["BrewSpeakConfigFrameRaid"]:SetChecked(addon.db.Raid) _G["BrewSpeakConfigFrameSay"]:SetChecked(addon.db.Say) _G["BrewSpeakConfigFrameWhisper"]:SetChecked(addon.db.Whisper) _G["BrewSpeakConfigFrameYell"]:SetChecked(addon.db.Yell) end function addon.Config:OnOkay() addon.db.Battleground = _G["BrewSpeakConfigFrameBattleground"]:GetChecked() and true or false addon.db.Guild = _G["BrewSpeakConfigFrameGuild"]:GetChecked() and true or false addon.db.Officer = _G["BrewSpeakConfigFrameOfficer"]:GetChecked() and true or false addon.db.Party = _G["BrewSpeakConfigFrameParty"]:GetChecked() and true or false addon.db.Raid = _G["BrewSpeakConfigFrameRaid"]:GetChecked() and true or false addon.db.Say = _G["BrewSpeakConfigFrameSay"]:GetChecked() and true or false addon.db.Whisper = _G["BrewSpeakConfigFrameWhisper"]:GetChecked() and true or false addon.db.Yell = _G["BrewSpeakConfigFrameYell"]:GetChecked() and true or false end function addon.Config:Initialize(...) BrewSpeakConfigFrame = BrewSpeakConfigFrame BrewSpeakConfigFrame.name = "BrewSpeak"; BrewSpeakConfigFrame.okay = self.OnOkay BrewSpeakConfigFrame.refresh = self.OnShow; InterfaceOptions_AddCategory(BrewSpeakConfigFrame); _G["BrewSpeakConfigFrameBattlegroundText"]:SetText("Battleground Chat") _G["BrewSpeakConfigFrameGuildText"]:SetText("Guild Chat") _G["BrewSpeakConfigFrameOfficerText"]:SetText("Officer Chat") _G["BrewSpeakConfigFramePartyText"]:SetText("Party Chat") _G["BrewSpeakConfigFrameRaidText"]:SetText("Raid Chat") _G["BrewSpeakConfigFrameSayText"]:SetText("Say") _G["BrewSpeakConfigFrameWhisperText"]:SetText("Private Chat") _G["BrewSpeakConfigFrameYellText"]:SetText("Yell") end
----------------------------------- -- -- Zone: GM Home (210) -- -- Some cs event info: -- 0 = Abyssea Debug -- 1 = Mogsack Debug -- ... -- 139 = Janken challenges player to "Rock, Paper, Scissors" -- ... -- 140 = Camera test. -- 141 = "Press confirm button to proceed" nonworking test. -- ----------------------------------- local ID = require("scripts/zones/GM_Home/IDs") ----------------------------------- function onInitialize(zone) end; function onZoneIn( player, prevZone) local cs = -1; return cs; end; function onEventUpdate( player, csid, option) end; function onEventFinish( player, csid, option) end;
--[[ Spot Welder with dual pulse controller https://github.com/northox/spot-welder - OLED Display: SDA->D1/5, SCL->D2/4 - Solid State Relay: D8/15 - Welding switch: D4/2 - Rotary encoder: CLK->D5/14, DT->D6/12, SW->D7/13 ]] sda_pin = 2 -- gpio 4 scl_pin = 1 -- gpio 5 oled_id = 0 -- i2c interface id zap_pin = 4 -- gpio 2 relay_pin=0 -- gpio 16 enco_clk_pin = 5 -- gpio 14 enco_dt_pin = 6 -- gpio 12 enco_sm_pin = 7 -- gpio 13 pulse1 = 0 delay = 0 pulse2 = 0 pos_old = 0 select_line = 0 str1_sep = "*" str2_sep = ":" str3_sep = ":" last_zap = 0 debounce_delay = 1000000 -- 1-second re-trigger delay -- turn off the SSR at start in case we are recovering from a crash gpio.mode(zap_pin, gpio.INPUT, gpio.PULLUP) gpio.mode(relay_pin, gpio.OUTPUT) gpio.write(relay_pin, gpio.LOW) -- XXXXXXXXXXXXXXXXXXXXX function load_config() files = file.list() if files["pulse1.conf"] then if file.open("pulse1.conf", "r") then pulse1 = file.read() file.close() end if file.open("delay.conf", "r") then delay = file.read() file.close() end if file.open("pulse2.conf", "r") then pulse2 = file.read() file.close() end end str1="Pulse1" .. str1_sep .. " " .. pulse1 .. " ms" str2="Delay " .. str2_sep .. " " .. delay .. " ms" str3="Pulse2" .. str3_sep .. " " .. pulse2 .. " ms" end -- XXXXXXXXXXXXXXXXXXXXXXXX function save_config() files = file.list() if file.open("pulse1.conf", "w") then file.write(pulse1) file.close() end if file.open("delay.conf", "w") then file.write(delay) file.close() end if file.open("pulse2.conf", "w") then file.write(pulse2) file.close() end end function init_OLED(sda, scl, id) sla = 0x3C -- i2c slave offset i2c.setup(id, sda, scl, i2c.SLOW) disp = u8g2.sh1106_i2c_128x64_noname(id, sla) disp:setFlipMode(1) disp:clearBuffer() disp:setContrast(255) disp:setFontMode(0) disp:setDrawColor(1) disp:setBitmapMode(0) disp:setFont(u8g2.font_6x10_tf) disp:setFontRefHeightExtendedText() disp:setFontPosTop() disp:setFontDirection(0) end function top_line(str) disp:clearBuffer() disp:drawStr(5, 0, str) disp:sendBuffer() end function print_OLED() disp:clearBuffer() disp:drawFrame(2,2,126,62) disp:drawStr(5, 16, str1) disp:drawStr(5, 30, str2) disp:drawStr(5, 44, str3) disp:sendBuffer() end rotary.setup(0, enco_clk_pin, enco_dt_pin, enco_sm_pin, 1000, 250) load_config() init_OLED(sda_pin, scl_pin, oled_id) print_OLED() gpio.trig(zap_pin, "down", function (level, when) local delta = when - last_zap if delta < 0 then delta = delta + 2147483647 end; if delta > debounce_delay then last_zap = when if level == 0 then -- Keeping the if statements outside the timing loop complicates the code, but gives more accurate timings. pulse1us = (pulse1*1000)-750 pulse2us = (pulse2*1000)-750 bothus = ((pulse1+pulse2)*1000)-750 delayus = (delay*1000) -- XXXXXXXXXXXXXXXXXXx what happend if you submit a 0 delay??? if this works, remove all of that if pulse1 == 0 and pulse2 == 0 then -- Do nothing top_line("No Zap...") elseif pulse2 == 0 then -- Only do pulse1 top_line("Zap Pulse 1...") gpio.write(relay_pin, gpio.HIGH) tmr.delay(pulse1us) gpio.write(relay_pin, gpio.LOW) elseif pulse1 == 0 then -- Only do pulse2 top_line("Zap Pulse 2...") gpio.write(relay_pin, gpio.HIGH) tmr.delay(pulse2us) gpio.write(relay_pin, gpio.LOW) elseif delay == 0 then -- Add pulse1+pulse2 into single longer pulse top_line("Zap Pulse 1+2...") gpio.write(relay_pin, gpio.HIGH) tmr.delay(bothus) gpio.write(relay_pin, gpio.LOW) else -- Double-zap cycle - pulse1, delay, pulse2 top_line("Double Zap...") gpio.write(relay_pin, gpio.HIGH) tmr.delay(pulse1us) gpio.write(relay_pin, gpio.LOW) tmr.delay(delayus) gpio.write(relay_pin, gpio.HIGH) tmr.delay(pulse2us) gpio.write(relay_pin, gpio.LOW) end print_OLED() end end end ) rotary.on(0, rotary.TURN, function (type, pos, when) if bit.isclear(pos,1) then if bit.isclear(pos,0) then diff = pos - pos_old pos_old = pos -- XXXXXXXXXXXXXXXXXXXX this is all the same thing, extract in a function if select_line == 0 then pulse1 = pulse1 + diff if pulse1 < 0 then pulse1 = 0 end if pulse1 > 1000 then pulse1 = 1000 end str1="Pulse 1" .. str1_sep .. " " .. pulse1 .. " ms" end if select_line == 1 then delay = delay + diff if delay < 0 then delay = 0 end if delay > 1000 then delay = 1000 end str2="Delay " .. str2_sep .. " " .. delay .. " ms" end if select_line == 2 then pulse2 = pulse2 + diff if pulse2 < 0 then pulse2 = 0 end if pulse2 > 1000 then pulse2 = 1000 end str3="Pulse 2" .. str3_sep .. " " .. pulse2 .. " ms" end print_OLED() end end end ) rotary.on(0, rotary.CLICK, function (type, pos, when) if select_line < 2 then select_line = select_line+1 else select_line = 0 end -- use case if select_line == 0 then str1_sep = "*" else str1_sep = ":" end if select_line == 1 then str2_sep = "*" else str2_sep = ":" end if select_line == 2 then str3_sep = "*" else str3_sep = ":" end str1="Pulse1" .. str1_sep .. " " .. pulse1 .. " ms" str2="Delay " .. str2_sep .. " " .. delay .. " ms" str3="Pulse2" .. str3_sep .. " " .. pulse2 .. " ms" print_OLED() end ) rotary.on(0, rotary.DBLCLICK, function (type, pos, when) top_line("Saving...") save_config() print_OLED() end ) rotary.on(0, rotary.LONGPRESS, function (type, pos, when) top_line("Loading...") load_config() select_line=2 print_OLED() end )
--tds protocol parser and encoder require "suproxy.utils.stringUtils" require "suproxy.utils.pureluapack" local ok,cjson=pcall(require,"cjson") local tableUtils=require "suproxy.utils.tableUtils" local orderTable=tableUtils.OrderedTable local extends=tableUtils.extends if not ok then cjson = require("suproxy.utils.json") end local logger=require "suproxy.utils.compatibleLog" local unicode = require "suproxy.utils.unicode" local tdsToken = require "suproxy.tds.token" local TokenType=tdsToken.TokenType local sqlVersion = require "suproxy.tds.version" local TokenType=tdsToken.TokenType local _M={} _M.Packet={ desc="BasePacket", parseHeader=function(self,headerBytes,cursor) self.code,self.status,self.dataLength,self.channel,self.packetID,self.window,cursor=string.unpack(">BBI2I2BB",headerBytes,cursor) return cursor end, packHeader=function(self,payloadLen) return string.pack(">BBI2I2BB",self.code,self.status,payloadLen+8,self.channel,self.packetID,self.window) end, pack=function(self) local payloadBytes=self:packPayload() local headerBytes=self:packHeader(#payloadBytes) self.allBytes=headerBytes..payloadBytes logger.logWithTitle(logger.DEBUG,"packing",self.allBytes:hex16F()) return self.allBytes end, --skipHeaderCursor indicates that header was parsed, just skip the header part and directly parse payload part parse=function(self,allBytes,pos) pos=self:parseHeader(allBytes) self:parsePayload(allBytes,pos) self.allBytes=allBytes return self end, parsePayload=function(allBytes,pos) end, new=function(self,o) local o=o or {} return orderTable.new(self,o) end } _M.SQLBatch={ code=0x01, parsePayload=function(self,bytes,cursor) local headerLength=string.byte(bytes,cursor) self.sql=unicode.utf16to8(bytes:sub(cursor+headerLength)) end, packPayload=function(self) error("not implemented") end } extends(_M.SQLBatch,_M.Packet) local function calcPass(password,enc) local mask = enc and 0x5a or 0xa5 return password:gsub(".", function(i) local c = bit.bxor(string.byte( i ), mask) local m1= bit.band(bit.rshift( c,4 ) , 0x0F) local m2= bit.band(bit.lshift( c ,4 ) , 0xF0) return string.pack("<B", bit.bor(m1 , m2) ) end) end _M.Login7={ code=0x10, desc="Login7", parsePayload=function(self,bytes,cursor) local pos=cursor self.loginPacketLength,pos=string.unpack("<I4",bytes,pos) self.TDSVersion,pos=string.unpack(">c4",bytes,pos) self.PacketSize,pos = string.unpack("<I4",bytes,pos) self.ClientProgVer,pos = string.unpack(">c4",bytes,pos) self.ClientPID ,pos= string.unpack("<I4",bytes,pos) self.ConnectionID,pos = string.unpack("<I4",bytes,pos) self.OptionFlags1,pos = string.unpack("B",bytes,pos) self.OptionFlags2,pos = string.unpack("B",bytes,pos) self.TypeFlag,pos = string.unpack("B",bytes,pos) self.OptionFlags3,pos=string.unpack("B",bytes,pos) self.ClientTimeZone,pos=string.unpack("<I4",bytes,pos) self.ClientLCID,pos=string.unpack("<I4",bytes,pos) local clientNameOffset,clientNameLength,pos=string.unpack("<I2I2",bytes,pos) local nameOffset,nameLength,pos=string.unpack("<I2I2",bytes,pos) local passOffset,passLength,pos=string.unpack("<I2I2",bytes,pos) local appNameOffset,appNameLength,pos=string.unpack("<I2I2",bytes,pos) local serverNameOffset,serverNameLength,pos=string.unpack("<I2I2",bytes,pos) local unUsedOffset,unUsedLength,pos=string.unpack("<I2I2",bytes,pos) local cltIntNameOffset,cltIntNameLength,pos=string.unpack("<I2I2",bytes,pos) local langOffset,langLength,pos=string.unpack("<I2I2",bytes,pos) local databaseOffset,databaseLength,pos=string.unpack("<I2I2",bytes,pos) --6 bytes MAC self.clientId,pos=string.unpack("<c6",bytes,pos) --local ibSSPI,cbSSPI,ibAtchDbFile,cchAtchDbFile,ibChpwd,cchChapwd,cbSSPILong=string.unpack("<I2I2I2I2I2I2I4",bytes,pos) self.iDontCare=string.unpack("c16",bytes,pos) self.clientName=unicode.utf16to8(string.unpack("c"..clientNameLength*2,bytes,cursor+clientNameOffset)) self.username=unicode.utf16to8(string.unpack("c"..nameLength*2,bytes,cursor+nameOffset)) self.password=unicode.utf16to8(calcPass(string.unpack("c"..passLength*2,bytes,cursor+passOffset),false)) self.appName=unicode.utf16to8(string.unpack("c"..appNameLength*2,bytes,cursor+appNameOffset)) self.serverName=unicode.utf16to8(string.unpack("c"..serverNameLength*2,bytes,cursor+serverNameOffset)) self.unUsed=string.unpack("c"..unUsedLength,bytes,cursor+unUsedOffset) self.libName=unicode.utf16to8(string.unpack("c"..cltIntNameLength*2,bytes,cursor+cltIntNameOffset)) self.locale=unicode.utf16to8(string.unpack("c"..langLength*2,bytes,cursor+langOffset)) local database,pos=string.unpack("c"..databaseLength*2,bytes,cursor+databaseOffset) self.database=unicode.utf16to8(database) self.remain=bytes:sub(pos) end, packPayload=function(self) --pointer to real data local dataOffset = 94 self.loginPacketLength = dataOffset + 2 * ( self.clientName:len() +self.username:len()+ self.password:len()+self.appName:len() + self.serverName:len() + self.libName:len() + self.database:len() )+self.unUsed:len()+self.remain:len() local data={ string.pack("<I4",self.loginPacketLength), string.pack(">c4",self.TDSVersion), string.pack("<I4",self.PacketSize), string.pack(">c4",self.ClientProgVer), string.pack("<I4",self.ClientPID ), string.pack("<I4",self.ConnectionID), string.pack("<B",self.OptionFlags1), string.pack("<B",self.OptionFlags2), string.pack("<B",self.TypeFlag), string.pack("<B",self.OptionFlags3), string.pack("<I4",self.ClientTimeZone), string.pack("<I4",self.ClientLCID), string.pack("<I2I2",dataOffset,self.clientName:len()) } dataOffset=dataOffset+2*self.clientName:len() data[#data+1]=string.pack("<I2I2",dataOffset,self.username:len()) dataOffset=dataOffset+2*self.username:len() data[#data+1]=string.pack("<I2I2",dataOffset,self.password:len()) dataOffset=dataOffset+2*self.password:len() data[#data+1]=string.pack("<I2I2",dataOffset,self.appName:len()) dataOffset=dataOffset+2*self.appName:len() data[#data+1]=string.pack("<I2I2",dataOffset,self.serverName:len()) dataOffset=dataOffset+2*self.serverName:len() data[#data+1]=string.pack("<I2I2",dataOffset,self.unUsed:len()) dataOffset=dataOffset+self.unUsed:len() data[#data+1]=string.pack("<I2I2",dataOffset,self.libName:len()) dataOffset=dataOffset+2*self.libName:len() data[#data+1]=string.pack("<I2I2",dataOffset,self.locale:len()) dataOffset=dataOffset+2*self.locale:len() data[#data+1]=string.pack("<I2I2",dataOffset,self.database:len()) dataOffset=dataOffset+2*self.database:len() --MAC data[#data+1]=string.pack("<c6",self.clientId) --string.pack("<I2I2I2I2I2I2I4",ibSSPI,cbSSPI,ibAtchDbFile,cchAtchDbFile,ibChpwd,cchChapwd,cbSSPILong) data[#data+1]=string.pack("c16",self.iDontCare) data[#data+1]=unicode.utf8to16(self.clientName) data[#data+1]=unicode.utf8to16(self.username) data[#data+1]=calcPass(unicode.utf8to16(self.password),true) data[#data+1]=unicode.utf8to16(self.appName) data[#data+1]=unicode.utf8to16(self.serverName) data[#data+1]=self.unUsed data[#data+1]=unicode.utf8to16(self.libName) data[#data+1]=unicode.utf8to16(self.database) data[#data+1]=self.remain return table.concat(data) end } extends(_M.Login7,_M.Packet) _M.Prelogin={ code=0x12, desc="PreLogin", -- TDS pre-login option types OPTION_TYPE = { Version = 0x00, Encryption = 0x01, InstOpt = 0x02, ThreadId = 0x03, MARS = 0x04, TraceId = 0x05, Terminator = 0xFF, }, parsePayload=function(self,bytes,cursor) local status, pos = false, cursor local preLoginPacket = _M.Prelogin:new() local i=0 self.options={} while true do local optionType, optionPos, optionLength, optionData, expectedOptionLength, _ if pos > #bytes then logger.log(logger.ERR,"MSSQL: Could not extract optionType." ) return false, "Invalid pre-login response" end optionType, pos = ("B"):unpack(bytes, pos) if ( optionType == _M.Prelogin.OPTION_TYPE.Terminator ) then status = true break end if pos + 4 > #bytes + 1 then logger.log(logger.ERR,"MSSQL: Could not unpack optionPos and optionLength." ) return false, "Invalid pre-login response" end optionPos, optionLength, pos = (">I2I2"):unpack(bytes, pos) optionData = bytes:sub( cursor+optionPos, cursor+optionPos + optionLength - 1 ) if #optionData ~= optionLength then logger.log(logger.ERR,"MSSQL: Could not read sufficient bytes from version data." ) return false, "Invalid pre-login response" end if ( optionType == _M.Prelogin.OPTION_TYPE.Version ) then local major, minor, build, subBuild = (">BBI2I2"):unpack(optionData) local version = sqlVersion:new() version:SetVersion( major, minor, build, subBuild, "SSNetLib" ) self.options["Version"]=version --https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/60f56408-0188-4cd5-8b90-25c6f2423868 elseif ( optionType == _M.Prelogin.OPTION_TYPE.Encryption ) then self.options["Encryption"]=("B"..optionLength):unpack(optionData) elseif ( optionType == _M.Prelogin.OPTION_TYPE.InstOpt ) then self.options["InstOpt"]=("z"):unpack(optionData) elseif ( optionType == _M.Prelogin.OPTION_TYPE.ThreadId ) then self.options["ThreadId"]= optionLength>0 and (">I"..optionLength):unpack(optionData) or "" elseif ( optionType == _M.Prelogin.OPTION_TYPE.MARS ) then self.options["MARS"]=("B"..optionLength):unpack(optionData) elseif (optionType==_M.Prelogin.OPTION_TYPE.TraceId) then self.options["TraceId"]=optionData else self.options["T"..tostring(optionType)]=("c"..optionLength):unpack(optionData) end i=i+1 end self.optionSize=i self.status=status and 1 or 0 end, packPayload=function(self) local options={} local optionLength, optionType = 0, 0 local offset=self.optionSize*5+1 local data local i=1 for k,v in pairs(self.options) do optionType = _M.Prelogin.OPTION_TYPE[k] if ( optionType == _M.Prelogin.OPTION_TYPE.Version ) then data=string.pack( ">BBI2I2", v.major, v.minor,v.build, v.subBuild ) elseif ( optionType == _M.Prelogin.OPTION_TYPE.Encryption ) then data=("B"):pack(v) elseif ( optionType == _M.Prelogin.OPTION_TYPE.InstOpt ) then data=("z"):pack(v) elseif ( optionType == _M.Prelogin.OPTION_TYPE.ThreadId ) then data= v=="" and v or (">I4"):pack(v) elseif ( optionType == _M.Prelogin.OPTION_TYPE.MARS ) then data=("B"):pack(v) elseif (optionType==_M.Prelogin.OPTION_TYPE.TraceId) then data=v else data=("c"..#data):pack(v) end optionLength=#data options[i]=string.pack( ">BI2I2", optionType, offset, optionLength ) options[self.optionSize+1+i]=data offset = offset + optionLength i=i+1 end options[self.optionSize+1]=string.pack( "B", _M.Prelogin.OPTION_TYPE.Terminator ) return table.concat(options) end, } extends(_M.Prelogin,_M.Packet) --this packet extends PreloginPacket _M.PreloginResponse={ code=0x04, desc="PreLoginResponse", preCode=_M.Prelogin.code } extends(_M.PreloginResponse,_M.Prelogin) _M.LoginResponse={ code=0x04, preCode=_M.Login7.code, desc="LoginResponse", parsePayload=function(self,bytes,cursor) local pos=cursor while pos<=#bytes do local tokenType=bytes:byte(pos) local token token,pos=tdsToken.doParse(tokenType,bytes,pos) if token.type==TokenType.LoginAck.code then self.success=true self.TDSVersion=token.TDSVersion self.progName=token.progName self.interface=token.interface self.serverVersion=token.serverVersion end if token.type==TokenType.Error.code then self.errNo=token.number self.message=token.message end end end } extends(_M.LoginResponse,_M.Packet) _M.SQLResponse={ code=0x04, preCode=_M.SQLBatch.code, desc="SQLResponse", new=function(self,param) local o=param or {} o.tokens={} return setmetatable(o, {__index=self}) end, parsePayload=function(self,bytes,cursor) local pos=cursor local tokenType=bytes:byte(pos) while tokenType ~= TokenType.Done.code do local token,err if tokenType==TokenType.Row.code or tokenType==TokenType.NBCRow.code then token=tdsToken.RowToken:new() pos,err=token:parse(bytes,pos,self.columnToken.colList) else token,pos,err=tdsToken.doParse(tokenType,bytes,pos) if tokenType==TokenType.ColMetaData.code then self.columnToken=token elseif tokenType==TokenType.Error.code then self.errToken=token end end if err then logger.log(logger.ERR,"err happend when parsing sqlresponse token",err) break end tokenType=bytes:byte(pos) self.tokens[#(self.tokens)+1]=token end end, packPayload=function(self,bytes,cursor) local buf={} for i,v in self.tokens do buf[#buf+1]=v.pack() end return table.concat(buf) end, tostring=function(self) local res={} for i=1,#self.tokens do res[i]=self.tokens[i]:tostring() end return table.concat(res,"\r\n") end } extends(_M.SQLResponse,_M.Packet) function _M.packErrorResponse(message,errNo) local errToken=tdsToken.ErrorToken:new({ --about error number check https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors?view=sql-server-ver15 number=errNo or 15343, state=1, class=16,message=message, serverName="GATEWAY", procName="", lineNo=1 }) local buf=errToken:pack()..string.char( 0xfd,0x02,0x00,0xfd,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00) local p=_M.Packet:new({code=4,status=1,channel=53,packetID=1,window=0}) return p:packHeader(#buf)..buf end ----------------------test starts from here------------------ _M.unitTest={} function _M.unitTest.headerTest() local tds7PreloginBytes=string.fromhex("120100580000010000001f000601002500010200260001030027000404002b000105002c0024ff0b001976000000006016000000ec2f0228b3392c4cae4c21d02f494f60d342ed1afdee6848b07fb65cf4a095be02000000") local packet=_M.Packet:new() packet:parseHeader(tds7PreloginBytes) local dataLength=packet.dataLength assert(packet.dataLength==88,packet.dataLength) assert(packet.status==1,packet.status) assert(packet.code==18,packet.code) assert(packet.channel==0,packet,channel) assert(packet.window==0,packet.window) end function _M.unitTest.PreloginPacketTest() local tds7PreloginBytes=string.fromhex("120100580000010000001f000601002500010200260001030027000404002b000105002c0024ff0b001976000000006016000000ec2f0228b3392c4cae4c21d02f494f60d342ed1afdee6848b07fb65cf4a095be02000000") local packet=require("suproxy.tds.parser"):new().C2PParser:parse(tds7PreloginBytes) assert(packet.options["Encryption"]==0,packet.options["Encryption"]) assert(packet.options["Version"].versionNumber=="11.00.6518.00",packet.options["Version"].versionNumber) assert(packet.options["Version"].brandedVersion=="2012",packet.options["Version"].brandedVersion) assert(packet.options["InstOpt"]=="",packet.options["InstOpt"]) assert(packet.options["ThreadId"]==1612054528,packet.options["ThreadId"]) assert(packet.options["MARS"]==0,packet.options["MARS"]) assert(packet.options["TraceId"]==string.fromhex("ec2f0228b3392c4cae4c21d02f494f60d342ed1afdee6848b07fb65cf4a095be02000000"),packet.options["TraceId"]) packet.options.Encryption=2 packet:pack() tds7PreloginBytes=packet.allBytes local packet=require("suproxy.tds.parser"):new().C2PParser:parse(tds7PreloginBytes) assert(packet.options["Encryption"]==2,packet.options["Encryption"]) assert(packet.options["Version"].versionNumber=="11.00.6518.00",packet.options["Version"].versionNumber) assert(packet.options["Version"].brandedVersion=="2012",packet.options["Version"].brandedVersion) assert(packet.options["InstOpt"]=="",packet.options["InstOpt"]) assert(packet.options["ThreadId"]==1612054528,packet.options["ThreadId"]) assert(packet.options["MARS"]==0,packet.options["MARS"]) assert(packet.options["TraceId"]==string.fromhex("ec2f0228b3392c4cae4c21d02f494f60d342ed1afdee6848b07fb65cf4a095be02000000"),packet.options["TraceId"]) end function _M.unitTest.PreloginResponseTest() local preloginRespBytes=string.fromhex("040100300000010000001f000601002500010200260001030027000004002700010500280000ff0b000c380000020000") local packet=require("suproxy.tds.parser"):new().S2PParser:parse(preloginRespBytes,nil,_M.Prelogin.code) assert(packet.options["Encryption"]==2,packet.options["Encryption"]) assert(packet.options["Version"].versionNumber=="11.00.3128.00",packet.options["Version"].versionNumber) assert(packet.options["Version"].brandedVersion=="2012",packet.options["Version"].brandedVersion) assert(packet.options["InstOpt"]=="",packet.options["InstOpt"]) assert(packet.options["ThreadId"]=="",packet.options["ThreadId"]) assert(packet.options["MARS"]==0,packet.options["MARS"]) assert(packet.options["TraceId"]=="",packet.options["TraceId"]) packet.options.Encryption=0 packet:pack() preloginRespBytes=packet.allBytes local packet=require("suproxy.tds.parser"):new().S2PParser:parse(preloginRespBytes,nil,_M.Prelogin.code) assert(packet.options["Encryption"]==0,packet.options["Encryption"]) assert(packet.options["Version"].versionNumber=="11.00.3128.00",packet.options["Version"].versionNumber) assert(packet.options["Version"].brandedVersion=="2012",packet.options["Version"].brandedVersion) assert(packet.options["InstOpt"]=="",packet.options["InstOpt"]) assert(packet.options["ThreadId"]=="",packet.options["ThreadId"]) assert(packet.options["MARS"]==0,packet.options["MARS"]) assert(packet.options["TraceId"]=="",packet.options["TraceId"]:hex()) end function _M.unitTest.SQLBatchTest() local sqlbatchBytes=string.fromhex("0101004200000100160000001200000002000000000000000000010000005300450054002000440041005400450046004f0052004d0041005400200079006d006400") local packet=require("suproxy.tds.parser"):new().C2PParser:parse(sqlbatchBytes) print(packet.sql) assert(packet.sql=="SET DATEFORMAT ymd",packet.sql:hexF()) end function _M.unitTest.calcPassTest() local pass="aA123.." print(unicode.utf8to16(pass):hex()) local encodePass=calcPass(unicode.utf8to16(pass),true) assert(encodePass==string.fromhex(" B3 A5 B1 A5 B6 A5 86 A5 96 A5 47 A5 47 A5")) assert(pass==unicode.utf16to8(calcPass(encodePass)),false) end function _M.unitTest.Login7Test() local login7bytes=string.fromhex("100100e000000100d80000000400007400000000000000070059000000000000e003001020feffff040800005e000f007c000200800007008e0007009c000900ae000400b2000400ba000000ba0006009aa81b19eb3c00000000c600000000000000000000004400450053004b0054004f0050002d0050004e004f00300036004c00430073006100b1a5b3a5b6a586a596a547a547a54e006100760069006300610074003100320037002e0030002e0030002e003100c60000004f004400420043006d00610073007400650072000901000000010a01000000010100000000ff") local packet=require("suproxy.tds.parser"):new().C2PParser:parse(login7bytes) assert(packet.username=="sa",packet.username) assert(packet.clientName=="DESKTOP-PNO06LC",packet.clientName) assert(packet.appName=="Navicat",packet.appName) assert(packet.serverName=="127.0.0.1",packet.serverName) assert(packet.libName=="ODBC",packet.libName) assert(packet.password=="Aa123..",packet.password) assert(packet.database=="master",packet.database) length=packet.loginPacketLength packet.username="sb" packet.password="Aa123.." packet:pack() print(packet.allBytes:compare16F(login7bytes)) local login7bytes=packet.allBytes local packet=require("suproxy.tds.parser"):new().C2PParser:parse(login7bytes) assert(packet.loginPacketLength==length,packet.loginPacketLength.." "..length) assert(packet.username=="sb",packet.username) assert(packet.clientName=="DESKTOP-PNO06LC",packet.clientName) assert(packet.appName=="Navicat",packet.appName) assert(packet.serverName=="127.0.0.1",packet.serverName) assert(packet.libName=="ODBC",packet.libName) assert(packet.password=="Aa123..",packet.password) assert(packet.database=="master",packet.database) end function _M.unitTest.LoginResponseTest() local bytes=string.fromhex("0401013d00340100e31b0001066d0061007300740065007200066d0061007300740065007200ab54004516000002001500f25d065c70656e63935e0a4e0b4e8765f46639653a4e200027006d0061007300740065007200270002300e4a004100590058005f00520045004d004f00540045004100500050000001000000e3080007050408d0000000e30b000204807b534f2d4e876500ab48004716000001000f00f25d065ced8b008abe8b6e7ff46639653a4e2000807b534f2d4e876502300e4a004100590058005f00520045004d004f00540045004100500050000001000000ad36000174000004164d006900630072006f0073006f00660074002000530051004c002000530065007200760065007200000000000b000c38e3130004043400300039003600043400300039003600fd000000000000000000000000") local packet=require("suproxy.tds.parser"):new().S2PParser:parse(bytes,nil,_M.Login7.code) assert(packet.success) end function _M.unitTest.SQLResponseTest() local bytes=string.fromhex("040100d90035010081020000000000210062491f00000c500072006f0064007500630074004c006500760065006c0000000000210062491f000007450064006900740069006f006e00d10f000000e7070408d0000000015300500031006b000000e7070408d00000000145006e00740065007200700072006900730065002000450064006900740069006f006e003a00200043006f00720065002d006200610073006500640020004c006900630065006e00730069006e00670020002800360034002d006200690074002900fd1000c1000100000000000000") local packet=require("suproxy.tds.parser"):new(true).S2PParser:parse(bytes,nil,_M.SQLBatch.code) print (packet:tostring():ascii()) local bytes=string.fromhex("040100cf003601008106000000000008007f0269006400000000000900a7ff000408d00000046e0061006d0065000000000008003803610067006500000000000900680106670065006e00640065007200000000000900e7ffff0408d000000469006e0066006f000000000009002a00046400610074006500d21001000000000000000100610100000001010699df0062410bd102000000000000000100620000000001000c000000000000000c0000006800610068006100680061000000000000fd1000c1000200000000000000") local packet=require("suproxy.tds.parser"):new(true).S2PParser:parse(bytes,nil,_M.SQLBatch.code) print (packet:tostring():ascii()) --[[ a1 int 0 0 0 -1 0 0 0 0 0 0 sys a2 int 0 0 -1 0 0 0 0 0 0 0 sys a3 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a4 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a5 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a6 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a7 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a8 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a9 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a10 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a11 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a12 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a13 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS_KS_WS 0 0 0 0 0 sys a14 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a15 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a16 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a17 varchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a18 bigint 0 0 -1 0 0 0 0 0 0 0 sys a19 binary 255 0 -1 0 0 0 0 0 0 0 sys a20 bit 0 0 -1 0 0 0 0 0 0 0 sys a21 char 8 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a22 date 0 0 -1 0 0 0 0 0 0 0 sys a23 datetime 0 0 -1 0 0 0 0 0 0 0 sys a24 datetime2 7 0 -1 0 0 0 0 0 0 0 sys a25 datetimeoffset 7 0 -1 0 0 0 0 0 0 0 sys a26 decimal 18 0 -1 0 0 0 0 0 0 0 sys a27 float 53 0 -1 0 0 0 0 0 0 0 sys a28 money 0 0 -1 0 0 0 0 0 0 0 sys a29 nchar 8 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys a30 numeric 18 0 -1 0 0 0 0 0 0 0 sys a31 nvarchar 255 0 -1 0 0 Chinese_PRC_CI_AS 0 0 0 0 0 sys ]] local bytes=string.fromhex("0401047700340100811f0000000000080038026100310000000000090026040261003200000000000900a7ff000408d000000261003300000000000900a7ff000408d000000261003400000000000900a7ff000408d000000261003500000000000900a7ff000408d000000261003600000000000900a7ff000408d000000261003700000000000900a7ff000408d000000261003800000000000900a7ff000408d000000261003900000000000900a7ff000408d0000003610031003000000000000900a7ff000408d0000003610031003100000000000900a7ff000408d0000003610031003200000000000900a7ff00040810000003610031003300000000000900a7ff000408d0000003610031003400000000000900a7ff000408d0000003610031003500000000000900a7ff000408d0000003610031003600000000000900a7ff000408d0000003610031003700000000000900260803610031003800000000000900adff0003610031003900000000000900680103610032003000000000000900af08000408d000000361003200310000000000090028036100320032000000000009006f08036100320033000000000009002a07036100320034000000000009002b07036100320035000000000009006a111200036100320036000000000009006d08036100320037000000000009006e0803610032003800000000000900ef10000408d00000036100320039000000000009006c11120003610033003000000000000900e7fe010408d0000003610033003100d2fcfffe4f20000000040a1a00000300613137100061006100205f094e62006200200020000501837d0000d2f8fd0720210000000401000000070079616e6778696e020032330100080079616e6778696e200363410b0808ac0000f850e30008007230f8785c410b0a00854a43795d410b0000050115cd5b0708ec51b81e85ebf13f080000000020120a001000610061006100200020002000200020000c0061007300386e0f6264006100d2b8af7d5f22000000041600000008007a68616e676e616e0100310100320200323208120000000000000008808bc11a7763410b050101000000d27cff8760230000000463c554000200736101000800d1eef6ce202020200357410b08fcab0000a855e3000a000cde467957410b00000501d2040000080000000000d0844008000000006c49341b100062006200620020002000200020002000d2bed57e1f2400000002003233020032330300613132010073030061313708007cbc1d7757410b050116000000040053626b62d2fcdee75f25000000046f000000040064617364020064730101080020202020202020200501d5000000d24afee71f6f00000001003101003102006666020061380200613901010800b0a4b4f2202020200501150000000c00610061006100610078007800d2fefda77fde00000003006131300101080056d0cdb3d476202008fcab0000585ae300d2fc6be57f71f25b2e049a0200000300613131030061313302003636081200000000000000010108002020202020202020fd1000c1000900000000000000") local packet=require("suproxy.tds.parser"):new(true).S2PParser:parse(bytes,nil,_M.SQLBatch.code) assert(#(packet.tokens)==10,#(packet.tokens)) print("3,27:"..packet.tokens[3].rowData[27]) print (packet:tostring():ascii()) --ssvar test local bytes=string.fromhex("040100d90034010081020000000000210062491f00000c500072006f0064007500630074004c006500760065006c0000000000210062491f000007450064006900740069006f006e00d10f000000e7070408d0000000015300500031006b000000e7070408d00000000145006e00740065007200700072006900730065002000450064006900740069006f006e003a00200043006f00720065002d006200610073006500640020004c006900630065006e00730069006e00670020002800360034002d006200690074002900fd1000c1000100000000000000") local packet=require("suproxy.tds.parser"):new(true).S2PParser:parse(bytes,nil,_M.SQLBatch.code) assert(#(packet.tokens)==2,#(packet.tokens)) print (packet:tostring():ascii()) end function _M.unitTest.SQLResponseErrorTest() local bytes=string.fromhex("0401006a00350100aa5200d000000001101400f95b618c0d5420002700670075006500730074002e00750073006500720027002000e065486502300e4a004100590058005f00520045004d004f00540045004100500050000001000000fd0200fd000000000000000000") local packet=require("suproxy.tds.parser"):new(true).S2PParser:parse(bytes,nil,_M.SQLBatch.code) assert(packet.errToken.number==208,packet.errToken.number) assert(packet.errToken.state==1,packet.errToken.state) assert(packet.errToken.class==16,packet.errToken.class) assert(packet.errToken.serverName=="JAYX_REMOTEAPP",packet.errToken.serverName) assert(packet.errToken.procName=="",packet.errToken.procName) assert(packet.errToken.lineNo==1,packet.errToken.LineNo) local bytes=_M.packErrorResponse("hahaha") local packet=require("suproxy.tds.parser"):new(true).S2PParser:parse(bytes,nil,_M.SQLBatch.code) assert(packet.errToken.number==15343,packet.errToken.number) assert(packet.errToken.state==1,packet.errToken.state) assert(packet.errToken.class==16,packet.errToken.class) assert(packet.errToken.message=="hahaha",packet.errToken.message) assert(packet.errToken.serverName=="GATEWAY",packet.errToken.serverName) assert(packet.errToken.procName=="",packet.errToken.procName) assert(packet.errToken.lineNo==1,packet.errToken.LineNo) end function _M.test() for k,v in pairs(_M.unitTest) do print("------------running "..k) v() print("------------"..k.." finished") end end return _M
--[[ ____ _ _ _ / ___| _ _ _ __ ___ / \ __| |_ __ ___ (_)_ __ \___ \| | | | '_ \ / __| / _ \ / _` | '_ ` _ \| | '_ \ ___) | |_| | | | | (__ / ___ \ (_| | | | | | | | | | | |____/ \__, |_| |_|\___/_/ \_\__,_|_| |_| |_|_|_| |_| |___/ @Description: SyncAdmin plugin command to give the selected player a hat from the Roblox catalog. @Author: Dominik [VolcanoINC], Hannah Jane [DataSynchronized] --]] local command = {} command.PermissionLevel = 1 command.Shorthand = nil command.Params = {"Number"} command.Usage = "dhat <ID>" command.Description = "[Donator]: Give yourself a hat." command.AllowDonators = true command.Init = function(main) end command.Run = function(main,user,id) if (user == nil) then error("No user found") end local hat = game:GetService("InsertService"):LoadAsset(id):GetChildren() if #hat < 1 then return false,"ID could not be loaded" end hat = hat[1] if not hat:IsA("Hat") and not hat:IsA("Accoutrement") then return false, "ID is not a hat" end hat:Clone().Parent = user.Character return true,"Given hat to you." end return command
------------------------------------------------ -- Copyright © 2013-2020 Hugula: Arpg game Engine -- -- author pu ------------------------------------------------ local table = table -- local type = type local table_insert = table.insert local table_remove = table.remove -- local table_remove_item = table.remove_item local string_format = string.format -- local ipairs = ipairs -- local pairs = pairs local class = class local ilist_table = class( function(self, items) self.items = items or {} self.Count = #self.items self.IsReadOnly = false self.IsFixedSize = false end ) local get_item = function(self, index) return self.items[index + 1] end local function set_count(self) self.Count = #self.items end ---设置index索引处的元素item ---@overload fun(index:int,item:any):void ---@param index int ---@param item any local function set_item(self, index, item) if index == nil then error("Argument index is nil") end local items = self.items local size = #items index = index + 1 if index < 1 or index > size then error("Argument index Out of Range") end -- local old = items[index] items[index] = item end ---从索引处删除count个元素 count默认为1 ---@overload fun(index:index,count:int):void ---@param index index ---@param count int local function remove_at(self, index, count) if count == nil then count = 1 end index = index + 1 local items = self.items local size = #items local end_idx = index + count - 1 if end_idx > size then end_idx = size end local changedItems = {} local item for i = end_idx, index, -1 do item = table_remove(items, i) table_insert(changedItems, item) end set_count(self) end local function indexof(self, item) local idx = table.indexof(self.items, item) if idx == nil then return -1 else return idx end end local function contains(self, item) local idx = table.indexof(self.items, item) if idx ~= nil then return true else return false end end ---在索引index插入一个元素,index默认为size。 ---@overload fun(index:int,item:any):void ---@param index int ---@param item any local function insert_item(self, index, item) if item == nil then error("Argument item is nil") end table_insert(self.items, index + 1, item) set_count(self) end local function add(self, item) if item == nil then error("Argument item is nil") end insert_item(self, #self.items, item) end ---交换old_index和new_index的数据 ---@overload fun(old_index:int,new_index:int):void ---@param old_index int ---@param new_index int local function move_item(self, old_index, new_index) if old_index == nil or new_index == nil then error("Argument old_index or new_index is nil") end local items = self.items local size = #items old_index = old_index + 1 new_index = new_index + 1 if old_index < 1 or old_index > size then error("Argument old_index Out of Range") end if new_index < 1 or new_index > size then error("Argument new_index Out of Range") end local old = items[old_index] local new = items[new_index] items[old_index] = new items[new_index] = old set_count(self) end ---删除index处的元素 ---@overload fun(index:int):void ---@param index int local function remove_item(self, index) if index == nil then error("Argument index is nil") end local items = self.items local size = #items index = index + 1 if index < 1 or index > size then error("Argument index Out of Range") end local old = table_remove(items, index) set_count(self) end local function clear(self) table.clear(self.items) set_count(self) end local function tostring(self) return string_format("IListTable(%s)", self.items) end ------IList ilist_table.set_Item = set_item --object this[int] ilist_table.get_Item = get_item --this[int] = object ilist_table.Add = add --int Add(object value); ilist_table.Clear = clear --void Clear(); ilist_table.Contains = contains --bool Contains(object value); ilist_table.IndexOf = indexof --int IndexOf(object value); ilist_table.Insert = insert_item --void Insert(int index, object value); ilist_table.Remove = remove_item --void Remove(object value); ilist_table.RemoveAt = remove_at --void RemoveAt(int index); ilist_table.__tostring = tostring ---Ilist的lua实现,在列表绑定不需要监听改变的时候可以使用这个数据结构 ---@class IListTable ---@class IListTable ---@module Assets\Lua\core\databinding\ilist_table.lua ---@overload fun():IListTable ---@return NotifyTable ---@field Add function ---@field Clear function ---@field Contains function ---@field IndexOf function ---@field RemoveAt function ---@field Insert function ---@field Remove function ---@field set_Item function ---@field get_Item function IListTable = ilist_table
return { uiEffect = "", name = "随机技能-召唤地狱火", cd = 60, painting = 1, id = 60027, picture = "0", aniEffect = "", desc = "召唤地狱火-召唤", effect_list = { { type = "BattleSkillSummon", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { monsterTemplateID = 101020300, delay = 0.2, isBulletPos = true, pilotAITemplateID = 10012, equipmentList = { 30002 } } } } }
boot -.builder ..DAW:NUC enter.matrix <script.action=drop>{ much.enter/7.bin=fex root.bin /rate.if else.factory:user } total.command if.band/proper RAT:nuc leave.server /for.use-on.space room.verb category?ajax.aspx build.database /self.delete .use-format.b <totaly.builded.unit/roll.faction-work.jobs> steve.jobs/enter.item=matrix { ground.global control.configuration exponse.target/=matrix.user } space.work banch.marked:unit cage.var(2) item.class(c.1) mode.leap ambulancies ..RAW:nuc category.kloud filemanager/.uppend.star ;end