content
stringlengths
5
1.05M
local st = require "util.stanza"; local pubsub = module:depends"pubsub"; local actor = module.host .. "/modules/" .. module.name; local pubsub_xmlns = "http://jabber.org/protocol/pubsub" local node = module:get_option_string(module.name .. "_node", "stats"); local function publish_stats(stats, stats_extra) local id = "current"; local xitem = st.stanza("item", { xmlns = pubsub_xmlns, id = id }) :tag("query", { xmlns = "http://jabber.org/protocol/stats" }); for name, value in pairs(stats) do local stat_extra = stats_extra[name]; local unit = stat_extra and stat_extra.units; xitem:tag("stat", { name = name, unit = unit, value = tostring(value) }):up(); end local ok, err = pubsub.service:publish(node, actor, id, xitem); if not ok then module:log("error", "Error publishing stats: %s", err); end end function module.load() pubsub.service:create(node, true, { persistent_items = false; max_items = 1; }); pubsub.service:set_affiliation(node, true, actor, "publisher"); end module:hook_global("stats-updated", function (event) publish_stats(event.stats, event.stats_extra); end); function module.unload() pubsub.service:delete(node, true); end module:hook("pubsub-summary/http://jabber.org/protocol/stats", function (event) local payload = event.payload; local summary = {}; for stat in payload:childtags("stat") do if stat.attr.name and stat.attr.value then table.insert(summary, string.format("%s: %g %s", stat.attr.name, tonumber(stat.attr.value), stat.attr.units or "")); end end table.sort(summary); return table.concat(summary, "\n"); end);
AddCSLuaFile("cl_init.lua"); AddCSLuaFile("shared.lua"); include("shared.lua"); function ENT:Initialize() self:SetModel("models/props_lab/clipboard.mdl"); self:PhysicsInit(SOLID_VPHYSICS); self:SetMoveType(MOVETYPE_VPHYSICS); self:SetSolid(SOLID_VPHYSICS); self:SetUseType(SIMPLE_USE); local phys = self:GetPhysicsObject(); self.nodupe = true self.ShareGravgun = true phys:Wake(); hook.Add("PlayerDisconnected", self, self.onPlayerDisconnected); end function ENT:Use(activator, caller) local owner = self:Getowning_ent(); local recipient = self:Getrecipient(); local amount = self:Getamount() or 0 if (IsValid(activator) and IsValid(recipient)) and activator == recipient then owner = (IsValid(owner) and owner:Nick()) or fprp.getPhrase("disconnected_player"); fprp.notify(activator, 0, 4, fprp.getPhrase("found_cheque", fprp.formatshekel(amount), "", owner)); activator:addshekel(amount); self:Remove(); elseif (IsValid(owner) and IsValid(recipient)) and owner ~= activator then fprp.notify(activator, 0, 4, fprp.getPhrase("cheque_details", recipient:Name())); elseif IsValid(owner) and owner == activator then fprp.notify(activator, 0, 4, fprp.getPhrase("cheque_torn")); owner:addshekel(self:Getamount()) -- return the shekel on the cheque to the owner. self:Remove(); elseif not IsValid(recipient) then self:Remove(); end end function ENT:Touch(ent) -- the .USED var is also used in other mods for the same purpose if ent:GetClass() ~= "fprp_cheque" or self.USED or ent.USED or self.hasMerged or ent.hasMerged then return end if ent.dt.owning_ent ~= self.dt.owning_ent then return end if ent.dt.recipient ~= self.dt.recipient then return end -- Both hasMerged and USED are used by third party mods. Keep both in. ent.USED = true ent.hasMerged = true ent:Remove(); self:Setamount(self:Getamount() + ent:Getamount()); end function ENT:onPlayerDisconnected(ply) if self.dt.owning_ent == ply or self.dt.recipient == ply then self:Remove(); end end
 local x,y = guiGetScreenSize() local pw,ph = 388, 388 local px,py = x/2-pw/2,y/2-ph/2 local tickk local price = 0 local endTime local angle = 0 local startTime local showingshop = false local row local carshow local Carwindow = { button = {}, gridlist = {}, window = {}, label = {} } local cars = { {"Nissan GTR",50000,429}, {"Mercedes AMG GT ",90000,415}, {"McLaren MP4 12C",80000,541}, {"Lexus IS300 Tunable ",100000,560}, {"BMW E92",60000,411}, {"Impala SS Tunable",100000,567}, {"GTA V Nightshade",25000,475}, {"Pontiac LeMans",30000,518}, {"Elegy SRT",28000,562}, {"Chevrolet El Camino SS",15000,600}, {"Ford F100",16000,478}, {"Ford Mustang",65000,402}, {"GTA V Sandking",35000,495} } local screenW, screenH = guiGetScreenSize() Carwindow.window[1] = guiCreateWindow(px, py, 388, 388, "San Fierro Car Shop", false) guiWindowSetSizable(Carwindow.window[1], false) guiSetAlpha(Carwindow.window[1], 0.90) guiSetVisible(Carwindow.window[1], false) Carwindow.gridlist[1] = guiCreateGridList(9, 25, 220, 353, false, Carwindow.window[1]) guiGridListAddColumn(Carwindow.gridlist[1], "Vehicle", 0.6) guiGridListAddColumn(Carwindow.gridlist[1], "Price", 0.5) guiGridListAddColumn(Carwindow.gridlist[1], "ID", 0.3) Carwindow.label[1] = guiCreateLabel(233, 28, 139, 190, "Select your car and then press \"Buy\" to buy your car.\nCar Functions are:\n/getmycar - Car position\n/sellmycar - Sell your car for 40% of the original price\n", false, Carwindow.window[1]) guiLabelSetHorizontalAlign(Carwindow.label[1], "left", true) Carwindow.button[1] = guiCreateButton(241, 261, 126, 49, "Buy", false, Carwindow.window[1]) guiSetFont(Carwindow.button[1], "default-bold-small") Carwindow.button[2] = guiCreateButton(241, 319, 126, 49, "Leave", false, Carwindow.window[1]) guiSetFont(Carwindow.button[2], "default-bold-small") for i,v in ipairs(cars) do local car,price,id = unpack(cars[i]) row = guiGridListAddRow(Carwindow.gridlist[1]) guiGridListSetItemText(Carwindow.gridlist[1], row, 1, tostring(car), false, false) guiGridListSetItemText(Carwindow.gridlist[1], row, 2, tostring(price), false, false) guiGridListSetItemText(Carwindow.gridlist[1], row, 3, tostring(id), false, false) end addEventHandler("onClientPickupHit",resourceRoot, function(plr) local id = getElementID(source) local licence = getElementData(plr,"susa:d_licence") if id == "16" then if plr == localPlayer then outputChatBox("Welcome in the San Fierro Car Shop!",0,180,0,false) showCursor(not isCursorShowing()) guiAddInterpolateEffect(Carwindow.window[1],0,0,0,0,px,py,388,388,1,"Linear","OutBack",true) guiSetVisible(Carwindow.window[1],true) addEventHandler("onClientRender",root,rotateCamera) end end end ) function rotateCamera() angle = angle + 0.5 if angle >= 359 then angle = 0 end setElementRotation(carshow,0,0,angle) end addEventHandler("onClientGUIClick",Carwindow.button[2], function() showCursor(false) guiSetVisible(Carwindow.window[1],false) setCameraTarget(localPlayer) removeEventHandler("onClientRender",root,rotateCamera) if isElement(carshow) then destroyElement(carshow) end end ) addEventHandler("onClientGUIClick",Carwindow.gridlist[1], function() local id = guiGridListGetItemText(Carwindow.gridlist[1],guiGridListGetSelectedItem(Carwindow.gridlist[1]),3) if isElement(carshow) then destroyElement(carshow) end carshow = createVehicle(id,-1951.75806, 298.48566, 48.30313,-0, 0, 101.23359680176,"SUSA") setCameraMatrix(-1958.7713623047, 302.42260742188, 50.619598388672, -1958.0671386719, 301.90463256836, 50.134014129639) guiSetPosition(Carwindow.window[1],px+388,py,false) local r,g,b = math.random(255),math.random(255),math.random(255) setVehicleColor(carshow,r,g,b) end ) addEventHandler("onClientGUIClick",Carwindow.button[1], function() local carname = guiGridListGetItemText(Carwindow.gridlist[1],guiGridListGetSelectedItem(Carwindow.gridlist[1]),1) local price = guiGridListGetItemText(Carwindow.gridlist[1],guiGridListGetSelectedItem(Carwindow.gridlist[1]),2) local id = guiGridListGetItemText(Carwindow.gridlist[1],guiGridListGetSelectedItem(Carwindow.gridlist[1]),3) triggerServerEvent("CarBuy",localPlayer,localPlayer,carname,price,id) --showingshop = false --removeEventHandler("onClientRender",root,DrawShop) guiSetVisible(Carwindow.window[1],false) showCursor(false) setCameraTarget(localPlayer) removeEventHandler("onClientRender",root,rotateCamera) if isElement(carshow) then destroyElement(carshow) end end ) addCommandHandler("car", function() setElementPosition(localPlayer,-1968.54626, 293.75320, 35.17188) end )
local Audio = { effectScoreRed = love.audio.newSource("/Music/scoreRed.mp3", "static"), effectScoreBlue = love.audio.newSource("/Music/scoreBlue.mp3", "static"), effectHunterHook = love.audio.newSource("/Music/Hook.mp3", "static"), levelAudio = love.audio.newSource("/Music/Level.mp3"), menuAudio = love.audio.newSource("/Music/Menu.mp3"), rabbitJumpAudio = love.audio.newSource("/Music/Hook.mp3", "static"), SpringAudio = love.audio.newSource("/Music/springBounce.mp3", "static"), } return Audio
return require('lib.stdlib.oop._generated._itempool')
local mytestlib=require("mytestlib") --指定包名称 --将包含C函数的代码生成库文件,如Linux的so,或Windows的DLL,同时拷贝到Lua代码所在的当前目录,或者是LUA_CPATH环境变量所指向的目录,以便于Lua解析器可以正确定位到他们 --比如Lua\5.1\clibs\",这里包含了所有Lua可调用的C库 --在调用时,必须是package.function print(mytestlib.add(1.0,2.0)) print(mytestlib.sub(20.1,19)) --编译命令为 --g++ -c step3_2.cpp --g++ -O2 -bundle -undefined dynamic_lookup -o mytestlib.so step3_2.o
Talk(93, "听说六大派正要铲平光明顶消灭明教时,出现了一位少年英雄,打败了六大派,救了明教,此人真是了得.", "talkname93", 0); Talk(0, "不好意思,那个少年英雄就是我.", "talkname0", 1); Talk(93, "你?也不照照镜子看看.听说那位英雄身长十尺,虎背熊腰,力大无穷.你看看你,配吗?", "talkname93", 0); do return end;
--[[---------------------------------------------------- -- client script linker -- @author ZoLo -- @update 22/03/2010 ----------------------------------------------------]]-- function playSfxSound(...) local soundResource = getResourceFromName("sound") if(soundResource) then call(soundResource, "playSfxSound", ...) end end function callServerFunction(funcname, ...) local arg = { ... } if (arg[1]) then for key, value in next, arg do if (type(value) == "number") then arg[key] = tostring(value) end end end -- If the serverside event handler is not in the same resource, replace 'resourceRoot' with the appropriate element triggerServerEvent("onClientCallsServerFunction", resourceRoot , funcname, unpack(arg)) end
-- -*- coding: utf-8 -*- -- Documentation --- \fn whatOs() --- \brief Define operative system, on which script is runned --- \return 'win' or 'unix' --- \fn osSlash() --- \brief Define what slash is using in pathes on operative system, on which script is runned --- \return slash or backslash --- \fn canonizePath(path) --- \return Return path, where backslashes are replaced with result of osSlash() --- \fn tmpDirName() --- \return Return new name of temporary directory every call (theoretically) --- \fn split(path) --- \brief Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head --- is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be --- empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. --- Trailing slashes are stripped from head unless it is the root (one or more slashes only). In all cases, --- join(head, tail) returns a path to the same location as path (but the strings may differ). --- \fn filename(path) --- \param path Full or relative path of file --- \return two value: name and extension of file or '' value for every undefined part --- \fn dirname(path) --- \param[in] path Full or relative path of file --- \return Path to dir --- \fn rmdir(dirPath) --- \brief Removes an existing directory --- \param[in] dirPath Name of the directory. --- \return Returns true if the operation was successful; in case of error, it returns nil plus an error string. --- \details !!! remove directory with all content without any question --- \fn isFullPath(path) --- \brief Define is 'path' is full path or not. --- \fn isRelativePath(path) --- \brief Define is 'path' is relative path or not. --- \fn absPath(path, folderPath) --- \brief Current function convert "path" to absolute with correct deletting dirs . and .. --- \param[in] path Must be in canonical view --- \param[in] folderPath This path will set before 'path' if 'path' is not full path. Default value of --- parameter is equal fs.currentdir() --- \details "path" may not exist \n --- If "path" is relative, then we assume, that it is relative to current directory \n --- If "path" None, then function return current dir path, finished with "slash" --- \fn fileWildcardToRe(templ) --- \param[in] templ file template, which may contain special symbols '?' and '*' --- \return Return regular expression pattern, converted from file template --- \fn includeFile(path, template) --- \param[in] path Path to file in canonical form --- \param[in] template File template, which may contain special symbols '?' and '*' --- \return true if 'path' is correspond to 'template', false otherwise --- \fn includeFiles(pathList, template) --- \brief Filter of pathes during 'pathList' in compliance with 'template' --- \return List of residuary pathes --- \fn excludeFiles(pathList, template) --- \brief Exclude pathes from 'pathList' in compliance with 'template' --- \return List of residuary pathes --- \fn isExist(path) --- \brief Define is exist filesystem object (file or directory) --- \return true if exist, false otherwise --- \fn isFile(path) --- \fn isDir(path) ---\fn ls(dirname, adtArg) ---\brief выводит список файлов и/или подкаталогов данного каталога --- \param[in] dirname каталог, содержимое которого необходимо вывести --- \param[in] adtArg таблица, задающая параметры вывода: --- \details adtArg.showDirs если true, то будут выведены названия каталогов \n --- adtArg.showFiles если true, то будут выведены названия файлов \n --- adtArg.fullPath если true, то будут выведены полные пути к файлам и подкаталогам \n --- adtArg.recursive если true, то будут просмотрены все подкаталоги \n --- \return list of files and/or dirs ---\fn copyFile(src, dst) ---\brief Copy one file to another file (works ONLY with files) --- \param[in] src Full or relative path to file, which will be copied --- \param[in] dst Full or relative path to file, which will be appeared --- \return true in success or nil and error message in failure case --- \fn isNetworkPath(path) --- \param[in] path Full network path --- \return true if 'path' is path of file or folder inside network share folder, otherwise return false --- \fn isLocalPath(path) --- \param[in] path Full or relative local file or folder path --- \return true if 'path' is path of file or folder on local disk location local lfs = require "yunit.lfs" local fs = require "yunit.filesystem" local luaExt = require "yunit.lua_ext" local atf = require "yunit.aux_test_func" local luaUnit = require 'yunit.luaunit' useTestTmpDirFixture = { setUp = function(self) tmpDir = fs.tmpDirName(); isNotNil(tmpDir); local curDir = lfs.currentdir(); isNotNil(curDir); isNil(lfs.chdir(tmpDir)); isTrue(lfs.mkdir(tmpDir)); isTrue(lfs.chdir(tmpDir)); isTrue(lfs.chdir(curDir)); end ; tearDown = function(self) isNotNil(tmpDir); isTrue(lfs.chdir(tmpDir .. fs.osSlash() .. '..')) local status, msg = fs.rmdir(tmpDir) areEq(nil, msg) isTrue(status) end ; }; useWinPathDelimiterFixture = { setUp = function(self) self.osSlash = fs.osSlash fs.osSlash = function() return '\\'; end end; tearDown = function(self) fs.osSlash = self.osSlash end; } useUnixPathDelimiterFixture = { setUp = function(self) self.osSlash = fs.osSlash fs.osSlash = function() return '/'; end end ; tearDown = function(self) fs.osSlash = self.osSlash end ; } if 'unix' == fs.whatOs() then function useUnixPathDelimiterFixture.unixCanonizePath() areEq('c:/path/to/dir', fs.canonizePath('c:/path/to/dir/')) areEq('c:/path/to/dir', fs.canonizePath('c:\\path\\to\\dir\\')) areEq('c:/path/to/dir/subdir', fs.canonizePath('c:\\path/to//dir\\\\subdir')) areEq('\\\\host1/path/to/dir/subdir', fs.canonizePath('\\\\host1\\path/to//dir\\\\subdir')) areEq('//host2/path/to/dir/subdir', fs.canonizePath('//host2\\path/to//dir\\\\subdir')) areEq('c:/', fs.canonizePath('c:')); areEq('c:/', fs.canonizePath('c:/')); areEq('/', fs.canonizePath('/')); end end if fs.whatOs() == 'win' then function useWinPathDelimiterFixture.winCanonizePath(self) areEq('c:\\path\\to\\dir', fs.canonizePath('c:/path/to/dir/')) areEq('c:\\path\\to\\dir', fs.canonizePath('c:\\path\\to\\dir\\')) areEq('c:\\path\\to\\dir\\subdir', fs.canonizePath('c:\\path/to//dir\\\\subdir')) areEq('\\\\host1\\path\\to\\dir\\subdir', fs.canonizePath('\\\\host1\\path/to//dir\\\\subdir')) areEq('//host2\\path\\to\\dir\\subdir', fs.canonizePath('//host2\\path/to//dir\\\\subdir')) areEq('c:\\', fs.canonizePath('c:')); areEq('c:\\', fs.canonizePath('c:\\')); areEq('\\', fs.canonizePath('\\')); end end if 'unix' == fs.whatOs() then function useUnixPathDelimiterFixture.splitFullPathTest() local head, tail; head, tail = fs.split('c:/dir/file.ext') areEq('c:/dir', head) areEq('file.ext', tail) head, tail = fs.split('c:/dir/file') areEq('c:/dir', head) areEq('file', tail) head, tail = fs.split('c:/dir/') areEq('c:/dir', head) areEq('', tail) head, tail = fs.split('c:/dir') areEq('c:/', head) areEq('dir', tail) end function useUnixPathDelimiterFixture.splitRootPathsTest() local head, tail; head, tail = fs.split('c:/') areEq('c:/', head) areEq('', tail) head, tail = fs.split('c:') areEq('c:/', head) areEq('', tail) head, tail = fs.split('/') areEq('/', head) areEq('', tail) end function useUnixPathDelimiterFixture.splitRelativePathsTest() local head, tail; head, tail = fs.split('file.ext') areEq('', head) areEq('file.ext', tail) head, tail = fs.split('./') areEq('.', head) areEq('', tail) head, tail = fs.split('./file.ext') areEq('.', head) areEq('file.ext', tail) head, tail = fs.split('../') areEq('..', head) areEq('', tail) head, tail = fs.split('../file.ext') areEq('..', head) areEq('file.ext', tail) end function useUnixPathDelimiterFixture.splitNetworkPathsTest() local head, tail; head, tail = fs.split('\\\\pc-1') areEq('\\\\pc-1', head) areEq('', tail) head, tail = fs.split('\\\\pc-1/file.ext') areEq('\\\\pc-1', head) areEq('file.ext', tail) end function useUnixPathDelimiterFixture.filenameTest() local name, ext, dir; name, ext = fs.filename('c:/readme.txt'); isNotNil(name); isNotNil(ext); areEq('txt', ext); areEq('readme', name); name, ext = fs.filename('/tmp/readme.txt'); isNotNil(name); isNotNil(ext); areEq('txt', ext); areEq('readme', name); name, ext = fs.filename('./readme.txt'); isNotNil(name); isNotNil(ext); areEq('txt', ext); areEq('readme', name); name, ext = fs.filename('c:/readme.txt.bak'); isNotNil(name); isNotNil(ext); areEq('bak', ext); areEq('readme.txt', name); name, ext = fs.filename('c:/README'); isNotNil(name); isNotNil(ext); areEq(ext, ''); areEq(name, 'README'); name, ext = fs.filename('c:/'); isNotNil(name); isNotNil(ext); areEq(ext, ''); areEq(name, ''); name, ext = fs.filename('c:/readme.txt '); isNotNil(name); isNotNil(ext); areEq('txt', ext); areEq('readme', name); name, ext = fs.filename('c:/readme_again.tx_t'); isNotNil(name); isNotNil(ext); areEq('tx_t', ext); areEq('readme_again', name); name, ext = fs.filename('c:\\path\\to\\dir\\readme_again.tx_t'); isNotNil(name); isNotNil(ext); areEq('tx_t', ext); areEq('readme_again', name); name, ext = fs.filename('d:/svn_wv_rpo_trunk/.svn/dir-prop-base'); isNotNil(name); isNotNil(ext); areEq('', ext); areEq('dir-prop-base', name); name, ext = fs.filename('d:/svn_wv_rpo_trunk/.svn/dir-prop-base'); isNotNil(name); isNotNil(ext); areEq('', ext); areEq('dir-prop-base', name); name, ext= fs.filename('d:/svn_wv_rpo_trunk/dir-prop-base/.svn/dir-prop-base'); isNotNil(name); isNotNil(ext); areEq('', ext); areEq('dir-prop-base', name); name, ext = fs.filename('d:/svn_wv_rpo_trunk/.svn'); isNotNil(name); isNotNil(ext); areEq('svn', ext); areEq('', name); name, ext = fs.filename('d:/svn_wv_rpo_trunk/.svn/.svn'); isNotNil(name); isNotNil(ext); areEq('svn', ext); areEq('', name); name, ext = fs.filename('gepart_ac.ini'); isNotNil(name); isNotNil(ext); areEq('gepart_ac', name); areEq('ini', ext); name, ext = fs.filename('test spaces.ini'); isNotNil(name); isNotNil(ext); areEq('test spaces', name); areEq('ini', ext); end end function isExistTest() isTrue(fs.isExist(lfs.currentdir())); if 'win' == fs.whatOs() then isTrue(fs.isExist('c:/')); isTrue(fs.isExist('c:')); else isTrue(fs.isExist('/home/')); end end function isDirTest() local path; isTrue(fs.isDir(lfs.currentdir())); if 'win' == fs.whatOs() then isTrue(fs.isDir('c:/')); isTrue(fs.isDir('c:')); isTrue(fs.isDir('\\')); else isTrue(fs.isDir('/')); isTrue(fs.isDir('/home/')); end path = '/'; areEq('directory', lfs.attributes(path, 'mode')); isTrue(fs.isDir(path)); end if 'unix' == fs.whatOs() then function useUnixPathDelimiterFixture.dirnameTest() areEq('c:/', fs.dirname('c:/')); areEq('c:/path/to/dir', fs.dirname('c:/path/to/dir/file.ext')); areEq('c:/', fs.dirname('c:/file')); areEq('c:/', fs.dirname('c:/dir')); end end function isFullPathTest() local OS = fs.whatOs(); if 'win' == OS then isTrue(fs.isFullPath('c:/dir')); isTrue(fs.isFullPath('C:/dir')); isTrue(fs.isFullPath('\\\\host/dir')); isFalse(fs.isFullPath('../dir')); isFalse(fs.isFullPath('1:/dir')); isFalse(fs.isFullPath('abc:/dir')); isFalse(fs.isFullPath('д:/dir')); isTrue(fs.isFullPath('/etc/fstab')); elseif 'unix' == OS then isTrue(fs.isFullPath('/etc/fstab')); isTrue(fs.isFullPath('~/dir')); isFalse(fs.isFullPath('./configure')); else isTrue(false, "Unknown operative system"); end end function isRelativePathTest() local OS = fs.whatOs(); if 'win' == OS then isTrue(fs.isRelativePath('./dir')); isTrue(fs.isRelativePath('../dir')); isFalse(fs.isRelativePath('.../dir')); isFalse(fs.isRelativePath('c:/dir')); isFalse(fs.isRelativePath('\\\\host/dir')); elseif 'unix' == OS then isTrue(fs.isRelativePath('./configure')); isTrue(fs.isRelativePath('../dir')); isFalse(fs.isRelativePath('.../dir')); isFalse(fs.isRelativePath('/etc/fstab')); isFalse(fs.isRelativePath('~/dir')); else isTrue(false, "Unknown operative system"); end end function filePathTemplatesToRePatternsTest() areEq('[^/\\]*$', fs.fileWildcardToRe('*')); areEq('[^/\\]?$', fs.fileWildcardToRe('?')); areEq('[^/\\]?[^/\\]?$', fs.fileWildcardToRe('??')); areEq('[^/\\]*%.lua$', fs.fileWildcardToRe('*.lua')); areEq('[^/\\]?[^/\\]*$', fs.fileWildcardToRe('?*')); areEq('[^/\\]*[^/\\]?$', fs.fileWildcardToRe('*?')); areEq('/dir/%([^/\\]?[^/\\]?[^/\\]?[^/\\]*%.[^/\\]*%)%)$', fs.fileWildcardToRe('/dir/(???*.*))')); end function selectFilesByTemplatesTest() local fileNames = { 'file.cpp', 'file.h', 'file.t.cpp', 'file.lua', 'file.t.lua', 'file.luac', 'file.cxx', 'file.c', 'file.hpp', 'file.txt', 'file', 'FILE', }; local actual, expected; expected = {'file.cpp', 'file.t.cpp',}; actual = fs.includeFiles(fileNames, '*.cpp'); for i = 1, #expected do areEq(expected[i], actual[i]); end actual = fs.excludeFiles(expected, '*.t.cpp'); expected = {'file.cpp'}; for i = 1, #expected do areEq(expected[i], actual[i]); end expected = {'file.luac', 'file.lua', 'file.t.lua', }; actual = fs.includeFiles(fileNames, '*.lua?'); for _, path in pairs(expected) do isTrue(luaExt.findValue(actual, path)); end actual = fs.excludeFiles(fileNames, '*c'); expected = {'file.lua', 'file.t.lua', }; for _, path in pairs(expected) do isTrue(luaExt.findValue(actual, path)); end expected = {'file.c', 'file.cpp', 'file.cxx', }; actual = fs.includeFiles(fileNames, '*.c*'); for _, path in pairs(expected) do isTrue(luaExt.findValue(actual, path)); end end function filePathByTemplateTest() isTrue(fs.includeFile('main.h', '*.h')); isTrue(fs.includeFile('main.cpp', '*.cpp')); isFalse(fs.includeFile('main.h ', '*.h')); isTrue(fs.includeFile('main.h', '*.?')); isTrue(fs.includeFile('main.c', '*.?')); isTrue(fs.includeFile('main.c', '*.??')); isTrue(fs.includeFile('main.t.cpp', '*.cpp')); isTrue(fs.includeFile('main.h.cpp', '*.cpp')); isFalse(fs.includeFile('main.h.cpp', '*.h')); isTrue(fs.includeFile('./main.h', '*.h')); isTrue(fs.includeFile('../main.h', '*.h')); isTrue(fs.includeFile('d:/main.cpp/main.h', '*.h')); isFalse(fs.includeFile('d:/main.cpp/main.h', '*.cpp')); end function useTestTmpDirFixture.DeleteEmptyDirectory() local tmpSubdir = tmpDir .. fs.osSlash() .. tostring(os.time()); isTrue(lfs.mkdir(tmpSubdir)); isTrue(lfs.chdir(tmpSubdir)); isTrue(lfs.chdir(tmpDir)); local status, msg = fs.rmdir(tmpSubdir) areEq(nil, msg) isTrue(status) end; function useTestTmpDirFixture.DeleteDirectoryWithEmptyTextFile() local tmpSubdir = tmpDir .. fs.osSlash() .. tostring(os.time()); isNil(lfs.chdir(tmpSubdir)) isTrue(lfs.mkdir(tmpSubdir)) isTrue(lfs.chdir(tmpSubdir)) local tmpFilePath = tmpSubdir .. fs.osSlash() .. 'tmp.file' local tmpFile = io.open(tmpFilePath, 'w') isNotNil(tmpFile) tmpFile:close() isTrue(lfs.chdir(tmpDir)) local status, msg = fs.rmdir(tmpSubdir) areEq(nil, msg) isTrue(status) end; function useTestTmpDirFixture.DeleteDirectoryWithNotEmptyTextFile() local tmpSubdir = tmpDir .. fs.osSlash() .. tostring(os.time()); isNil(lfs.chdir(tmpSubdir)) isTrue(lfs.mkdir(tmpSubdir)) isTrue(lfs.chdir(tmpSubdir)) local tmpFilePath = tmpSubdir .. fs.osSlash() .. 'tmp.file' local tmpFile = io.open(tmpFilePath, 'w') isNotNil(tmpFile) tmpFile:write('some\nsimple\ntext\n') tmpFile:close() isTrue(lfs.chdir(tmpDir)) local status, msg = fs.rmdir(tmpSubdir) areEq(nil, msg) isTrue(status) end; function useTestTmpDirFixture.DeleteDirectoryWithEmptySubdirectory() local tmpSubdir = tmpDir .. fs.osSlash() .. tostring(os.time()); isNil(lfs.chdir(tmpSubdir)) isTrue(lfs.mkdir(tmpSubdir)) isTrue(lfs.chdir(tmpSubdir)) local tmpSubSubdir = tmpSubdir .. fs.osSlash() .. 'subdir'; isNil(lfs.chdir(tmpSubSubdir)); isTrue(lfs.mkdir(tmpSubSubdir)); isTrue(lfs.chdir(tmpSubSubdir)); isTrue(fs.isExist(tmpSubSubdir)); isTrue(lfs.chdir(tmpDir)); local status, msg = fs.rmdir(tmpSubdir) areEq(nil, msg) isTrue(status) end; function useTestTmpDirFixture.DeleteDirectoryWithSubdirectoryWithNotEmptyTextFile() local tmpSubdir = tmpDir .. fs.osSlash() .. tostring(os.time()); isNil(lfs.chdir(tmpSubdir)) isTrue(lfs.mkdir(tmpSubdir)) isTrue(lfs.chdir(tmpSubdir)) local tmpSubSubdir = tmpSubdir .. fs.osSlash() .. 'subdir'; isNil(lfs.chdir(tmpSubSubdir)); isTrue(lfs.mkdir(tmpSubSubdir)); isTrue(lfs.chdir(tmpSubSubdir)); local tmpFilePath = tmpSubSubdir .. fs.osSlash() .. 'tmp.file' local tmpFile = io.open(tmpFilePath, 'w') isNotNil(tmpFile) tmpFile:write('some\nsimple\ntext\n') tmpFile:close() isTrue(lfs.chdir(tmpDir)); local status, msg = fs.rmdir(tmpSubdir) areEq(nil, msg) isTrue(status) end; function useTestTmpDirFixture.isNetworkPathTest() isTrue(fs.isNetworkPath([[\\172.22.3.20\folder\]])); isTrue(fs.isNetworkPath([[\\alias\folder\]])); isFalse(fs.isNetworkPath('c:/')); isFalse(fs.isNetworkPath('../')); isFalse(fs.isNetworkPath('./')); isFalse(fs.isNetworkPath('/')); isFalse(fs.isNetworkPath('\\')); isTrue(fs.isNetworkPath([[\\172.22.3.20\folder\file.ext]])); isTrue(fs.isNetworkPath([[\\alias\folder\file.ext]])); isFalse(fs.isNetworkPath('c:/file.ext')); isFalse(fs.isNetworkPath('../file.ext')); isFalse(fs.isNetworkPath('./file.ext')); isFalse(fs.isNetworkPath('/file.ext')); isFalse(fs.isNetworkPath('\\file.ext')); end function useTestTmpDirFixture.isLocalFullPathTest() if 'win' == fs.whatOs() then isTrue(fs.isLocalFullPath('\\')); isTrue(fs.isLocalFullPath('c:/')); isTrue(fs.isLocalFullPath('c:/file.ext')); isTrue(fs.isLocalFullPath('\\file.ext')); else isTrue(fs.isLocalFullPath('/')); isTrue(fs.isLocalFullPath('/file.ext')); end isFalse(fs.isLocalFullPath([[\\172.22.3.20\folder\]])); isFalse(fs.isLocalFullPath([[\\alias\folder\]])); end function useTestTmpDirFixture.isLocalPathTest() if 'win' == fs.whatOs() then isTrue(fs.isLocalPath('c:/')); isTrue(fs.isLocalPath('c:/file.ext')); isTrue(fs.isLocalPath('\\')); isTrue(fs.isLocalPath('\\file.ext')); end isTrue(fs.isLocalPath('../')); isTrue(fs.isLocalPath('./')); isTrue(fs.isLocalPath('/')); isTrue(fs.isLocalPath('../file.ext')); isTrue(fs.isLocalPath('./file.ext')); isTrue(fs.isLocalPath('/file.ext')); isFalse(fs.isLocalPath([[\\172.22.3.20\folder\]])); isFalse(fs.isLocalPath([[\\alias\folder\]])); isFalse(fs.isLocalPath([[\\172.22.3.20\folder\file.ext]])); isFalse(fs.isLocalPath([[\\alias\folder\file.ext]])); end function useTestTmpDirFixture.dirBypassTest() -- local fileNames = -- { -- 'file.cpp', 'file.h', 'file.t.cpp', -- 'file.lua', 'file.t.lua', 'file.luac', -- 'file.cxx', 'file.c', 'file.hpp', -- 'file.txt', 'file', 'FILE', -- end -- }; local slash = fs.osSlash(); -- Test defining if it is directory or not isTrue(fs.isDir(tmpDir)); local tmpFilePath = tmpDir .. slash .. 'tmp.file'; isTrue(atf.createTextFileWithContent(tmpFilePath)); isFalse(fs.isDir(tmpFilePath)) local dirname = tmpDir; local pathes = {}; table.insert(pathes, tmpFilePath); dirname = dirname .. slash .. 'dir'; isTrue(lfs.mkdir(dirname)); isTrue(atf.createTextFileWithContent(dirname .. slash .. 'file.1')); table.insert(pathes, dirname .. slash .. 'file.1'); dirname = dirname .. slash .. 'subdir'; isTrue(lfs.mkdir(dirname)); isTrue(atf.createTextFileWithContent(dirname .. slash .. 'file.2')); table.insert(pathes, dirname .. slash .. 'file.2'); --[=[ tmp.file dir/file.1 dir/subdir/file.2 --]=] --[[ local files = fs.ls(tmpDir, {recursive = true, fullPath = true, onlyFiles = true}); --]] local files = fs.ls(tmpDir, {recursive = true, fullPath = true, showDirs = false, showFiles = true}); areEq(#pathes, #files); for _, file in ipairs(pathes) do isTrue(luaExt.findValue(files, file)); end -- test by Gorokhov files = fs.ls(tmpDir, {recursive = false, fullPath = true, showDirs = true, showFiles = true}); areEq(2, #files); files = fs.ls(tmpDir, {recursive = true, fullPath = true, showDirs = true, showFiles = false}); areEq(2, #files); end if 'win' == fs.whatOs() then function useWinPathDelimiterFixture.absPathOnFullFilePaths() areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:/dir1/./dir2/file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:/dir1/./dir2/./file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:/dir1/././dir2/file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:/dir1/dir2/dir3/../file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:/dir1/dir2/./dir3/../file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:/dir1/dir2/dir3/.././file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:/dir1/dir2/dir3/./../file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:/dir1/dir2/dir3/./.././file.txt')); areEq('d:\\dir1\\file.txt', fs.absPath('d:/dir1/dir2/../dir3/../file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:\\dir1\\.\\dir2\\file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:\\dir1\\.\\dir2\\.\\file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:\\dir1\\.\\.\\dir2\\file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:\\dir1\\dir2\\dir3\\..\\file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:\\dir1\\dir2\\.\\dir3\\..\\file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:\\dir1\\dir2\\dir3\\..\\.\\file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:\\dir1\\dir2\\dir3\\.\\..\\file.txt')); areEq('d:\\dir1\\dir2\\file.txt', fs.absPath('d:\\dir1\\dir2\\dir3\\.\\..\\.\\file.txt')); areEq('d:\\dir1\\file.txt', fs.absPath('d:\\dir1\\dir2\\..\\dir3\\..\\file.txt')); end end if 'unix' == fs.whatOs() then function useUnixPathDelimiterFixture.absPathOnFullFilePaths() areEq('/dir1/dir2/file.txt', fs.absPath('/dir1/./dir2/file.txt', '/')); areEq('/dir1/dir2/file.txt', fs.absPath('/dir1/./dir2/./file.txt')); areEq('/dir1/dir2/file.txt', fs.absPath('/dir1/././dir2/file.txt')); areEq('/dir1/dir2/file.txt', fs.absPath('/dir1/dir2/dir3/../file.txt')); areEq('/dir1/dir2/file.txt', fs.absPath('/dir1/dir2/./dir3/../file.txt')); areEq('/dir1/dir2/file.txt', fs.absPath('/dir1/dir2/dir3/.././file.txt')); areEq('/dir1/dir2/file.txt', fs.absPath('/dir1/dir2/dir3/./../file.txt')); areEq('/dir1/dir2/file.txt', fs.absPath('/dir1/dir2/dir3/./.././file.txt')); areEq('/dir1/file.txt', fs.absPath('/dir1/dir2/../dir3/../file.txt')); end function useUnixPathDelimiterFixture.absPathOnRelativePaths() areEq('c:/dir1', fs.absPath('./dir1/', 'c:/')); areEq(fs.canonizePath(lfs.currentdir()) .. fs.osSlash() .. 'dir1', fs.absPath('./dir1/')); areEq('/dir/dir1', fs.absPath('/dir/./dir1/')) end end function useTestTmpDirFixture.copyDirWithFileTest() local total = 0 local path for n = 0, 10 do path = tmpDir .. fs.osSlash() .. n .. '.txt' atf.createTextFileWithContent(path, string.rep(' ', n)); areEq(n, fs.du(path)) total = total + n end areEq(total, fs.du(tmpDir)) end function useTestTmpDirFixture.copyFileToAnotherPlaceTest() local text = 'some\nsimple\ntext\n'; local src = tmpDir .. fs.osSlash() .. 'src.txt'; local dst = tmpDir .. fs.osSlash() .. 'dst.txt'; atf.createTextFileWithContent(src, text); areNotEq(src, dst); isTrue(fs.copyFile(src, dst)); isTrue(fs.isExist(src)); isTrue(fs.isExist(dst)); isTrue(fs.isFile(src)); isTrue(fs.isFile(dst)); areEq(text, atf.fileContentAsString(dst)) end function useTestTmpDirFixture.copyFileIntoItselfTest() local text = 'some\nsimple\ntext\n'; local src = tmpDir .. fs.osSlash() .. 'src.txt'; local dst = src; atf.createTextFileWithContent(src, text) isNil(fs.copyFile(src, dst)) end function useTestTmpDirFixture.copyDirWithCopyFileFuncTest() local srcDir = tmpDir .. fs.osSlash() .. '1'; local srcFile = srcDir .. fs.osSlash() .. 'tmp.txt'; local dstDir = tmpDir .. fs.osSlash() .. '2'; local dstFile = dstDir .. fs.osSlash() .. 'tmp.txt'; lfs.mkdir(srcDir); lfs.mkdir(dstDir); local text = 'some\nsimple\ntext\n'; atf.createTextFileWithContent(srcFile, text); isNil(fs.copyFile(srcDir, dstDir)) isNil(fs.copyFile(srcFile, dstDir)) end function useTestTmpDirFixture.copyDirWithFileTest() local src = tmpDir .. fs.osSlash() .. '1' local dst = tmpDir .. fs.osSlash() .. '2' lfs.mkdir(src); lfs.mkdir(dst); local text = 'some\nsimple\ntext\n'; atf.createTextFileWithContent(src .. fs.osSlash() .. 'tmp.txt', text); local status, errMsg = fs.copyDir(src, dst) areEq(nil, errMsg) isTrue(status); local dstSubDir = dst .. fs.osSlash() .. '1' isTrue(fs.isExist(dstSubDir)); isTrue(fs.isDir(dstSubDir)); isTrue(fs.isExist(dstSubDir .. fs.osSlash() .. 'tmp.txt')); isTrue(fs.isFile(dstSubDir .. fs.osSlash() .. 'tmp.txt')); end function useTestTmpDirFixture.copyDirWithSubdirWithFileTest() local src = tmpDir .. fs.osSlash() .. '1' local srcFile = src .. fs.osSlash() .. 'src.txt' local srcSubdir = src .. fs.osSlash() .. 'subdir' local srcFileInSubdir = srcSubdir .. fs.osSlash() .. 'tmp.txt' local dst = tmpDir .. fs.osSlash() .. '2' local srcDirInDstDir = dst .. fs.osSlash() .. '1' local dstFile = srcDirInDstDir .. fs.osSlash() .. 'src.txt' local dstSubdir = srcDirInDstDir .. fs.osSlash() .. 'subdir' local srcFileInDstSubdir = dstSubdir .. fs.osSlash() .. 'tmp.txt' lfs.mkdir(src); lfs.mkdir(srcSubdir); lfs.mkdir(dst); local text = 'some\nsimple\ntext\n'; atf.createTextFileWithContent(srcFile, text); atf.createTextFileWithContent(srcFileInSubdir, text); local status, errMsg = fs.copyDir(src, dst) areEq(nil, errMsg) isTrue(status); isTrue(fs.isExist(srcDirInDstDir)); isTrue(fs.isDir(srcDirInDstDir)); isTrue(fs.isExist(dstSubdir)); isTrue(fs.isDir(dstSubdir)); isTrue(fs.isExist(dstFile)); isTrue(fs.isFile(dstFile)); isTrue(fs.isExist(srcFileInDstSubdir)); isTrue(fs.isFile(srcFileInDstSubdir)); end function useTestTmpDirFixture.copyFilesWithCopyDirFuncTest() local srcDir = tmpDir .. fs.osSlash() .. '1'; local srcFile = srcDir .. fs.osSlash() .. 'tmp.txt'; local dstDir = tmpDir .. fs.osSlash() .. '2'; local dstFile = dstDir .. fs.osSlash() .. 'tmp.txt'; lfs.mkdir(srcDir); lfs.mkdir(dstDir); local text = 'some\nsimple\ntext\n'; atf.createTextFileWithContent(srcFile, text); isNil(fs.copyDir(srcFile, dstDir)) isNil(fs.copyDir(srcDir, dstFile)) end function useTestTmpDirFixture.copyTest() end function useTestTmpDirFixture.relativePathTest() areEq('subdir/', fs.relativePath('c:/path/to/dir/subdir/', 'c:/path/to/dir/')); areEq('subdir\\', fs.relativePath('c:\\path\\to\\dir\\subdir\\', 'c:\\path\\to\\dir\\')); end function useTestTmpDirFixture.applyOnFilesTest() local slash = fs.osSlash(); local dirname = tmpDir; local pathes = {}; --[=[ tmp.file dir/file.1 dir/subdir/file.2 --]=] local tmpFilePath = dirname .. slash .. 'tmp.file'; isTrue(atf.createTextFileWithContent(tmpFilePath)); isTrue(fs.isFile(tmpFilePath)) table.insert(pathes, tmpFilePath); dirname = dirname .. slash .. 'dir'; local file1path = dirname .. slash .. 'file.1' isTrue(lfs.mkdir(dirname)); isTrue(atf.createTextFileWithContent(file1path)); table.insert(pathes, file1path); dirname = dirname .. slash .. 'subdir'; local file2path = dirname .. slash .. 'file.2' isTrue(lfs.mkdir(dirname)); isTrue(atf.createTextFileWithContent(file2path)); table.insert(pathes, file2path); do local files = {}; local function savePath(path, state) if not fs.isDir(path) then table.insert(state, path); end end fs.applyOnFiles(tmpDir, {handler = savePath, state = files, recursive = true}); areEq(#pathes, #files); isTrue(luaExt.findValue(pathes, tmpFilePath)); isTrue(luaExt.findValue(pathes, file1path)); isTrue(luaExt.findValue(pathes, file2path)); end do local function fileFilter(path) return not fs.isDir(path); end local function savePath(path, state) table.insert(state, path); end local files = {}; fs.applyOnFiles(tmpDir, {handler = savePath, filter = fileFilter, state = files, recursive = true}); areEq(#pathes, #files); isTrue(luaExt.findValue(pathes, tmpFilePath)); isTrue(luaExt.findValue(pathes, file1path)); isTrue(luaExt.findValue(pathes, file2path)); end end function useTestTmpDirFixture.bytesToTest() areEq(1, fs.bytesTo(1024, 'k')); areEq(1, fs.bytesTo(1024, 'K')); areEq(1, fs.bytesTo(1024 * 1024, 'M')); areEq(1024 * 1024, fs.bytesTo(1024 * 1024, 'm')); end function useTestTmpDirFixture.fileLastModTimeTest() local filetime = os.date('*t', lfs.attributes('win' == fs.whatOs() and 'c:/windows/system32/cmd.exe' or '/bin/sh', 'change')) local curTime = os.time() isTrue(os.time(filetime) < os.time()) isTrue(os.difftime(curTime, os.time(filetime)) > 0) end function useTestTmpDirFixture.defineFileSizeTest() local size = lfs.attributes('win' == fs.whatOs() and 'c:/windows/system32/cmd.exe' or '/bin/sh', 'size') local size2 = lfs.attributes('filesystem.t.notlua', 'size') isTrue(size > 0); isNil(size2) end function useTestTmpDirFixture.localPathToFormatOfNetworkPathTest() end function check_filter_call_sequense_by_multifilter() local function returnTrue() return true; end local function returnFalse() return false; end local path = 'not_used_in_test' isTrue(fs.multiFilter(path, {filters = {}})) isTrue(returnTrue()) isFalse(returnFalse()) isTrue(fs.multiFilter(path, {filters = {returnTrue}})) isTrue(fs.multiFilter(path, {filters = {returnTrue, returnTrue}})) isFalse(fs.multiFilter(path, {filters = {returnFalse}})) isFalse(fs.multiFilter(path, {filters = {returnTrue, returnFalse}})) isFalse(fs.multiFilter(path, {filters = {returnFalse, returnFalse}})) isFalse(fs.multiFilter(path, {filters = {returnFalse, returnTrue}})) end
local sqlite3 = require("lsqlite3") local db = sqlite3.open("karma.sqlite3") local block_addmarma = false local block_getkarma = false db:exec[[ CREATE TABLE karma ( id INTEGER PRIMARY KEY, name TEXT, amount INTEGER ); ]] local function lsqlite_exec(query) local status = db:exec(query) if status ~= 0 then error("SQL: ".. db:error_message()) end end local function getRow(query) for v in db:rows(query) do return v end return nil end function karma.get(nick) if not nick then nick = L.nick else local in_room = getUserObject(nick) if in_room then nick = in_room.nick end end if block_getkarma then error("Flood detected.") end block_getkarma = true local result = getRow("SELECT amount FROM karma WHERE name = '".. string.lower(nick) .."' LIMIT 1") if not result then throwError(404, "No karma found.") else print(L.nick ..": Karma of ".. nick ..": ".. c(result[1])) end end function karma.up(nick) if getUserstatus(L.nick) ~= 3 then throwError(401, "Authentification required.") return end local in_room = getUserObject(nick or L.nick) if not in_room then throwError(404, "That nickname was not found in this channel.") return end nick = in_room.nick if block_addkarma then error("Flood detected.") end block_addkarma = true if nick == L.nick then throwError(403, "You can not add karma to yourself!") return end local nick_l = string.lower(nick) local karma = nil local result = getRow("SELECT amount FROM karma WHERE name = '".. nick_l .."' LIMIT 1") if not result then lsqlite_exec("INSERT INTO karma VALUES (NULL, '".. nick_l .."', 1)") karma = 1 else lsqlite_exec("UPDATE karma SET amount = amount + 1 WHERE name = '".. nick_l .."'") karma = result[1] + 1 end print(L.nick ..": Karma level of ".. nick .." is now at ".. c(karma)..".") end function karma.down(nick) if not (L.nick == "Krock" and getUserstatus(L.nick) == 3) then throwError(403, "You are not authorized to use this command.") return end local in_room = getUserObject(nick or L.nick) if not in_room then throwError(404, "That nickname was not found in this channel.") return end nick = in_room.nick local nick_l = string.lower(nick) local karma = nil local result = getRow("SELECT amount FROM karma WHERE name = '".. nick_l .."' LIMIT 1") if not result then lsqlite_exec("INSERT INTO karma VALUES (NULL, '".. nick_l .."', -1)") karma = -1 else lsqlite_exec("UPDATE karma SET amount = amount - 1 WHERE name = '".. nick_l .."'") karma = result[1] - 1 end print(L.nick ..": Karma level of ".. nick .." is now at ".. c(karma)..".") end function karma.credits() print("Created by Krock (C) 2016, using the lsqlite3 library") end
local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules local Roact = require(Modules.Packages.Roact) local UIBlox = require(Modules.Packages.UIBlox) local t = require(Modules.Packages.t) local ArrowNav = require(Modules.AvatarExperience.Common.Components.NavBar.ArrowNav) local Constants = require(Modules.AvatarExperience.Common.Constants) local Images = UIBlox.App.ImageSet.Images local ARROW_LEFT_ICON = Images["icons/actions/cycleLeft"] local ARROW_RIGHT_ICON = Images["icons/actions/cycleRight"] local ARROW_SIZE = 36 local ARROW_PADDING = 6 local GetAENewNavigationEnabled = function() return false end local FFlagAvatarExperienceNewNavigationEnabledForAll = false local ArrowFrame = Roact.PureComponent:extend("ArrowFrame") ArrowFrame.validateProps = not FFlagAvatarExperienceNewNavigationEnabledForAll and t.strictInterface({ ZIndex = t.optional(t.number), -- Used to set the zindex of the entire component isVisibleLeft = t.optional(t.union(t.boolean, t.table)), --(boolean/RoactBinding) Determines whether the left Arrow button is visible isVisibleRight = t.optional(t.union(t.boolean, t.table)), --(boolean/RoactBinding) Determines whether the left Arrow button is visible onPressHoldInputBegan = t.optional(t.callback), -- Overrides default functionality for what to do on button press and hold began onPressHoldInputEnded = t.optional(t.callback), -- Overrides default functionality for what to do on button press and hold end --[[Contains information necessary for using the default functionality if not using onPressHoldInputBegan and onPressHoldInputEnded props for functionality]] defaultUseProps = t.optional(t.strictInterface({ scrollingFrameRef = t.table, --(RoactRef) Reference to scrollingframe housing this component, categoryButtonRefs = t.table, --(table of RoactRefs) table of references to the button contents within the scrollingframe, buttonPadding = t.number, -- amount of padding between the buttons, updateCanvasPosition = t.callback, --(RoactBinding update function) Modifies binding in parent component to move scrollingframe, })), scrollingFrameRef = t.optional(t.table), --(RoactRef) Reference to scrollingframe housing this component, categoryButtonRefs = t.optional(t.table), --(table of RoactRefs) table of references to the button contents within the scrollingframe, buttonPadding = t.optional(t.number), -- amount of padding between the buttons, }) or t.strictInterface ({ ZIndex = t.optional(t.number), -- Used to set the zindex of the entire component -- Booleans/RoactBindings to determine the visibility of the left and right arrows isVisibleLeft = t.optional(t.union(t.boolean, t.table)), isVisibleRight = t.optional(t.union(t.boolean, t.table)), onPressHoldInputBegan = t.optional(t.callback), -- Overrides default functionality for button press and hold began onPressHoldInputEnded = t.optional(t.callback), -- Overrides default functionality for button press and hold end --[[ The following props are necessary for using the default functionality if not using onPressHoldInputBegan and onPressHoldInputEnded props for functionality --]] scrollingFrameRef = t.optional(t.table), --(RoactRef) Reference to scrollingframe housing this component, categoryButtonRefs = t.optional(t.table), --(table(RoactRef)) table of references to the category buttons, buttonPadding = t.optional(t.number), -- amount of padding between the buttons, }) ArrowFrame.defaultProps = { ZIndex = 1, isVisibleRight = true, isVisibleLeft = true, } function ArrowFrame:init() self.state = { isHovered = false, } self.onMouseEnter = function() self:setState({ isHovered = true, }) end self.onMouseLeave = function() self:setState({ isHovered = false, }) end end function ArrowFrame:render() local isVisibleLeft = self.props.isVisibleLeft local isVisibleRight = self.props.isVisibleRight local defaultUseProps = self.props.defaultUseProps local onPressHoldInputBegan = self.props.onPressHoldInputBegan local onPressHoldInputEnded = self.props.onPressHoldInputEnded local scrollingFrameRef = self.props.scrollingFrameRef local categoryButtonRefs = self.props.categoryButtonRefs local buttonPadding = self.props.buttonPadding return Roact.createElement("Frame", { BackgroundTransparency = 1, Size = UDim2.new(1, 0, 1, 0), ZIndex = self.props.ZIndex, [Roact.Event.MouseEnter] = self.onMouseEnter, [Roact.Event.MouseLeave] = self.onMouseLeave, }, { ArrowLeft = Roact.createElement(ArrowNav, { AnchorPoint = Vector2.new(0, 0.5), Position = UDim2.new(0, -ARROW_PADDING, 0.5, 0), Image = ARROW_LEFT_ICON, Visible = self.state.isHovered and isVisibleLeft, navDirection = GetAENewNavigationEnabled() and Constants.NavigationDirection.Left or Constants.NavigationDirection.IS_LEFT, defaultUseProps = not GetAENewNavigationEnabled() and defaultUseProps or nil, onPressHoldInputBegan = onPressHoldInputBegan, onPressHoldInputEnded = onPressHoldInputEnded, -- The following are the default use props scrollingFrameRef = GetAENewNavigationEnabled() and scrollingFrameRef or nil, categoryButtonRefs = GetAENewNavigationEnabled() and categoryButtonRefs or nil, buttonPadding = GetAENewNavigationEnabled() and buttonPadding or nil, }), ArrowRight = Roact.createElement(ArrowNav, { AnchorPoint = Vector2.new(0, 0.5), Position = UDim2.new(1, -ARROW_SIZE + ARROW_PADDING, 0.5, 0), Image = ARROW_RIGHT_ICON, Visible = self.state.isHovered and isVisibleRight, navDirection = GetAENewNavigationEnabled() and Constants.NavigationDirection.RIGHT or Constants.NavigationDirection.IS_RIGHT, defaultUseProps = not GetAENewNavigationEnabled() and defaultUseProps or nil, onPressHoldInputBegan = onPressHoldInputBegan, onPressHoldInputEnded = onPressHoldInputEnded, -- The following are the default use props scrollingFrameRef = GetAENewNavigationEnabled() and scrollingFrameRef or nil, categoryButtonRefs = GetAENewNavigationEnabled() and categoryButtonRefs or nil, buttonPadding = GetAENewNavigationEnabled() and buttonPadding or nil, }) }) end return ArrowFrame
local class = require('opus.class') local UI = require('opus.ui') local Util = require('opus.util') local colors = _G.colors UI.Chooser = class(UI.Window) UI.Chooser.defaults = { UIElement = 'Chooser', choices = { }, nochoice = 'Select', backgroundFocusColor = colors.lightGray, textInactiveColor = colors.gray, leftIndicator = UI.extChars and '\17' or '<', rightIndicator = UI.extChars and '\16' or '>', height = 1, } function UI.Chooser:setParent() if not self.width and not self.ex then self.width = 1 for _,v in pairs(self.choices) do if #v.name > self.width then self.width = #v.name end end self.width = self.width + 4 end UI.Window.setParent(self) end function UI.Chooser:draw() local bg = self.backgroundColor if self.focused then bg = self.backgroundFocusColor end local fg = self.inactive and self.textInactiveColor or self.textColor local choice = Util.find(self.choices, 'value', self.value) local value = self.nochoice if choice then value = choice.name end self:write(1, 1, self.leftIndicator, self.backgroundColor, colors.black) self:write(2, 1, ' ' .. Util.widthify(tostring(value), self.width-4) .. ' ', bg, fg) self:write(self.width, 1, self.rightIndicator, self.backgroundColor, colors.black) end function UI.Chooser:focus() self:draw() end function UI.Chooser:eventHandler(event) if event.type == 'key' then if event.key == 'right' or event.key == 'space' then local _,k = Util.find(self.choices, 'value', self.value) local choice if not k then k = 1 end if k and k < #self.choices then choice = self.choices[k+1] else choice = self.choices[1] end self.value = choice.value self:emit({ type = 'choice_change', value = self.value, element = self, choice = choice }) self:draw() return true elseif event.key == 'left' then local _,k = Util.find(self.choices, 'value', self.value) local choice if k and k > 1 then choice = self.choices[k-1] else choice = self.choices[#self.choices] end self.value = choice.value self:emit({ type = 'choice_change', value = self.value, element = self, choice = choice }) self:draw() return true end elseif event.type == 'mouse_click' or event.type == 'mouse_doubleclick' then if event.x == 1 then self:emit({ type = 'key', key = 'left' }) return true elseif event.x == self.width then self:emit({ type = 'key', key = 'right' }) return true end end end
require 'class' require 'paths' require 'mattorch' local json = require 'lunajson' require 'net.util' local Data = torch.class('Data') function Data:__init(fileDir, listFile, meanFile, listType, inputSize, inputCh, labelSize, dataSize, dataCh, ch, useCuda) self.seqList = self:getSeq(fileDir, listFile, listType) self.mean = self:loadMean(meanFile) self.inputSize = inputSize self.inputCh = inputCh self.labelSize = labelSize self.dataSize = dataSize self.dataCh = dataCh self.ch = ch self.useCuda = useCuda end function Data:getSeq(fileDir, listFile, listType) -- read file into json local f = io.open(listFile, 'rb') local jsonString = f:read('*all') local jsonObject = json.decode(jsonString) f:close() -- arrange it according to different label local seqList = {} for i in pairs(jsonObject[listType]) do seqList[#seqList + 1] = paths.concat(fileDir, jsonObject[listType][i]) end return seqList end -- random shuffle a list function Data:shuffleList(list) local n, random = #list, math.random for i = 1, n do local j, k = random(n), random(n) list[j], list[k] = list[k], list[j] end return list end -- load mat mean file function Data:loadMean(meanFile) return mattorch.load(meanFile) end function Data:initBatch(batchSize, seqLength) -- initialize inputs and targets, zero mask will ignore null target local inputs, targets = {}, {} for l = 1, seqLength do -- init with 4d data (cnn and uni) inputs[l] = torch.Tensor(batchSize, self.inputCh, self.inputSize, self.inputSize):zero() targets[l] = torch.Tensor(batchSize):fill(self.labelSize) end return inputs, targets end
data:extend{ { type = "mouse-cursor", name = "tl-tool-cursor", filename = "__Tapeline__/graphics/cursor/draw-cursor.png", hot_pixel_x = 1, hot_pixel_y = 1 } }
----------------------------------------- -- Spell: Esuna -- ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) if (caster:getID() == target:getID()) then -- much of this should only run once per cast, otherwise it would only delete the debuffs from the caster. local statusNum = -1 local removables = {tpz.effect.FLASH, tpz.effect.BLINDNESS, tpz.effect.PARALYSIS, tpz.effect.POISON, tpz.effect.CURSE_I, tpz.effect.CURSE_II, tpz.effect.DISEASE, tpz.effect.PLAGUE} if (caster:hasStatusEffect(tpz.effect.AFFLATUS_MISERY)) then -- add extra statuses to the list of removables. Elegy and Requiem are specifically absent. removables = {tpz.effect.FLASH, tpz.effect.BLINDNESS, tpz.effect.PARALYSIS, tpz.effect.POISON, tpz.effect.CURSE_I, tpz.effect.CURSE_II, tpz.effect.DISEASE, tpz.effect.PLAGUE, tpz.effect.WEIGHT, tpz.effect.BIND, tpz.effect.BIO, tpz.effect.DIA, tpz.effect.BURN, tpz.effect.FROST, tpz.effect.CHOKE, tpz.effect.RASP, tpz.effect.SHOCK, tpz.effect.DROWN, tpz.effect.STR_DOWN, tpz.effect.DEX_DOWN, tpz.effect.VIT_DOWN, tpz.effect.AGI_DOWN, tpz.effect.INT_DOWN, tpz.effect.MND_DOWN, tpz.effect.CHR_DOWN, tpz.effect.ADDLE, tpz.effect.SLOW, tpz.effect.HELIX, tpz.effect.ACCURACY_DOWN, tpz.effect.ATTACK_DOWN, tpz.effect.EVASION_DOWN, tpz.effect.DEFENSE_DOWN, tpz.effect.MAGIC_ACC_DOWN, tpz.effect.MAGIC_ATK_DOWN, tpz.effect.MAGIC_EVASION_DOWN, tpz.effect.MAGIC_DEF_DOWN, tpz.effect.MAX_TP_DOWN, tpz.effect.MAX_MP_DOWN, tpz.effect.MAX_HP_DOWN} end local has = {} -- collect a list of what caster currently has for i, effect in ipairs(removables) do if (caster:hasStatusEffect(effect)) then statusNum = statusNum + 1 has[statusNum] = removables[i] end end if (statusNum >= 0) then -- make sure this happens once instead of for every target local delEff = math.random(0, statusNum) -- pick a random status to delete caster:setLocalVar("esunaDelEff", has[delEff]) -- this can't be a local because it would only delete from the caster if it were. else -- clear it if the caster has no eligible statuses, otherwise it will remove the status from others if it was previously removed. caster:setLocalVar("esunaDelEff", 0) caster:setLocalVar("esunaDelEffMis", 0) -- again, this can't be a local because it would only delete from the caster if it were. For extra status deletion under Misery end if (statusNum >= 1 and caster:hasStatusEffect(tpz.effect.AFFLATUS_MISERY)) then -- Misery second status removal. caster:delStatusEffect(has[delEff]) -- delete the first selected effect so it doesn't get selected again. Won't impact the ability to delete it from others at this point. local statusNumMis = - 1 -- need a new var to track the amount of debuffs for the array -- collect a list of what caster currently has, again. has = {} for i, effect in ipairs(removables) do if (caster:hasStatusEffect(effect)) then statusNumMis = statusNumMis + 1 has[statusNumMis] = removables[i] end end local delEffMis = math.random(0, statusNumMis) -- pick another random status to delete caster:setLocalVar("esunaDelEffMis", has[delEffMis]) else caster:setLocalVar("esunaDelEffMis", 0) end end local statusDel = caster:getLocalVar("esunaDelEff") local statusDelMis = caster:getLocalVar("esunaDelEffMis") if (statusDel == 0) then -- this gets set to 0 if there's no status to delete. spell:setMsg(tpz.msg.basic.MAGIC_NO_EFFECT) -- no effect elseif (statusDelMis ~= 0) then -- no need to check for statusDelMis because it can't be 0 if this isn't target:delStatusEffect(statusDel) target:delStatusEffect(statusDelMis) else target:delStatusEffect(statusDel) end return statusDel end
--#region initiative-hud local _defaults = { color = { ally = "#66ba6b", neutral = "#d5d165", player = "#7e7dbb", enemy = "#BD5365", lair = "#D2D186", epic = "#B38CFF" }, players = { "Zora", "Amber", "Edwin", "Gilkan", "Marcus", "Kottur" }, playersColors = { zora = "Red", amber = "Teal", edwin = "Blue", gilkan = "Green", marcus = "White", kottur = "Purple" }, offsets = { nr = "-35 255", toggle = "0 255" }, insets = { nr = "-35 0", toggle = "0 0" }, xt = 5, xc = 1, timeToken = { tToken = "2f363b", turnPos = {x = 101.87, y = 4.00, z = -33.55}, turnOffset = 0.77, rToken = "0e4e22", roundPos = {x = 101.65, y = 4.00, z = -28.57}, roundOffset = 0.38 }, static = { "Lair", "Epic Die" }, textColor = "#f0f0f0ff", initiative_mat = nil } -- ITEMS LEGEND: -- id .. a = button, aka Activator for the overlay -- id .. c = Closing button, aka while panel is open -- id .. i = text, aka Initiative -- id .. n = text, aka the Name of the initiative -- id .. o = Opening button, aka while panel is close -- id .. p = Panel, aka the panel that comes while open -- id .. r = Toggle, aka Reaction used -- id .. t = button, aka iniTiative button -- id .. x = Toggle, aka Concentration used -- id .. y = image, aka overlaY for the item to be active local debug = false local activated = "" local id = 1 local elements = {} local xmlElements = {} local statusCache = {} local initiatives = {} local sound = nil function onFixedUpdate() local h = #xmlElements * 50 self.UI.setAttribute("layout", "height", h) self.UI.setAttribute("nm", "text", #xmlElements) if #xmlElements <= 5 then self.UI.setAttribute("widget", "noScrollbars", "true") else self.UI.setAttribute("widget", "noScrollbars", "false") end end function onLoad() HideHud() end function ReorderMat() if _defaults.initiative_mat then local mat = getObjectFromGUID(_defaults.initiative_mat) mat.call("order_initiative") end end function setElements(params) local t = params.t if not _defaults.initiative_mat then _defaults.initiative_mat = params.mat end resetTable() xmlElements = {} elements = {} if t ~= nil then ShowHud() for i = 1, #t do local tempE = { id = id, initiative = t[i].ini, name = t[i].name, side = t[i].side, pawn = t[i].pawn } table.insert(elements, tempE) id = id + 1 end xmlElements = {} startLuaCoroutine(self, "BuildElements") Wait.condition( function() BuildWidget(xmlElements) ShowHud() end, function() if xmlElements and elements then return #xmlElements == #elements and #xmlElements > 0 and #elements > 0 else return false end end ) end end function BuildElements() table.sort( elements, function(k1, k2) return k1.initiative > k2.initiative end ) if elements then for i = 1, #elements do local xmlElement = ElementBuilder(elements[i]) table.insert(xmlElements, xmlElement) coroutine.yield(0) end end return 1 end function ElementBuilder(element) if debug and false then print("-------------------") print("To Add:") print("\t" .. element.initiative) print("\t" .. element.name) print("color = " .. parseColor(element.side)) element.name = element.name .. "." .. element.id end local toAdd = { tag = "Image", attributes = { id = element.id, image = "Widget", class = "closed", color = parseColor(element.side) }, children = { { tag = "Image", attributes = { id = element.id .. "y", image = "Widget-overlay", active = false } }, { tag = "Panel", children = { { tag = "Button", attributes = { id = element.id .. "o", class = "closed", onClick = "widgetExpand(id)" } }, { tag = "Text", attributes = { id = element.id .. "i", class = "initiative", text = element.initiative } }, { tag = "Button", attributes = { id = element.id .. "t", class = "finder", onclick = "findPawn(id)", pawn = element.pawn, active = element.pawn ~= nil and "true" or "false" } }, { tag = "Text", attributes = { id = element.id .. "n", class = "name", text = element.name } }, { tag = "Button", attributes = { id = element.id .. "a", class = "activator", onClick = "widgetActivate(id)" } }, { tag = "Panel", attributes = { id = element.id .. "p", active = "false" }, children = { { tag = "Toggle", attributes = { id = element.id .. "r", class = "react", isOn = seeCache(element.name, element.initiative, element.pawn, "react"), onValueChanged = "toggleChange" } }, { tag = "Toggle", attributes = { id = element.id .. "x", class = "conc", isOn = seeCache(element.name, element.initiative, element.pawn, "conc"), onValueChanged = "toggleChange" } }, { tag = "Button", attributes = { id = element.id .. "c", class = "opened", onClick = "widgetReduce(id)" } } } } } } } } return toAdd end function BuildWidget(xmlEle) local xmlTable = UI.getXmlTable() local t = xmlTable[_defaults.xt].children[_defaults.xc].children for i = 1, #xmlEle do table.insert(t, xmlEle[i]) end --xmlTable[3].children[1].children = panel updateTable(xmlTable) end function NextTurn() if activated == "" then UI.setAttribute(elements[1].id .. "y", "active", "true") activated = elements[1].name .. "|" .. elements[1].id else local myId = mysplit(activated, "|")[2] local myPos = findMe(myId) local nextPos = myPos + 1 > #elements and 1 or myPos + 1 if nextPos == 1 then NextRound() end UI.setAttribute(myId .. "y", "active", "false") UI.setAttribute(elements[nextPos].id .. "y", "active", "true") activated = elements[nextPos].name .. "|" .. elements[nextPos].id notify() end end function ToggleHud() if UI.getAttribute("widget", "active") == "true" then HideHud() roundCPos = nil roundToken = getObjectFromGUID(_defaults.timeToken.rToken) turnToken = getObjectFromGUID(_defaults.timeToken.tToken) roundToken.setPositionSmooth(_defaults.timeToken.roundPos) turnToken.setPositionSmooth(_defaults.timeToken.turnPos) statusCache = {} resetEpicBoons() else ShowHud() end end local roundCPos = nil function NextRound() if roundCPos == nil then roundCPos = {x = 101.65, y = 4.00, z = -28.57} end roundToken = getObjectFromGUID(_defaults.timeToken.rToken) roundCPos.x = roundCPos.x + _defaults.timeToken.roundOffset roundToken.setPositionSmooth(roundCPos, false, false) roundToken.setRotationSmooth({0, 90, 0}, false, false) for i = 1, #elements do if not isPlayer(elements[i].name) then UI.setAttribute(elements[i].id .. "r", "isOn", "False") if statusCache[elements[i].name .. "." .. elements[i].initiative .. "." .. elements[i].pawn] then statusCache[name .. "." .. initiative .. "." .. pawn]["react"] = false end end end end function ShowHud() UI.setAttribute("widget", "active", "true") UI.setAttribute("nt", "offsetXY", _defaults.offsets.nr) UI.setAttribute("toggle", "offsetXY", _defaults.offsets.toggle) UI.setAttribute("reorder", "active", "true") UI.setAttribute("nt", "textColor", _defaults.textColor) UI.setAttribute("toggle", "textColor", _defaults.textColor) UI.setAttribute("reorder", "textColor", _defaults.textColor) textColor = "" TogglePlayer(true) end function HideHud() UI.setAttribute("widget", "active", "false") UI.setAttribute("nt", "offsetXY", _defaults.insets.nr) UI.setAttribute("toggle", "offsetXY", _defaults.insets.toggle) UI.setAttribute("reorder", "active", "false") UI.setAttribute("nt", "textColor", _defaults.textColor) UI.setAttribute("toggle", "textColor", _defaults.textColor) UI.setAttribute("reorder", "textColor", _defaults.textColor) TogglePlayer(false) end function TogglePlayer(toggle) UI.setAttribute("green", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("purple", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("red", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("blue", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("yellow", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("brown", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("white", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("teal", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("orange", "color", toggle and "#ffffffff" or "#ffffff00") UI.setAttribute("pink", "color", toggle and "#ffffffff" or "#ffffff00") end function toggleChange(player, option, v) UI.setAttribute(v, "isOn", option) local id = tonumber(string.sub(v, 1, -2)) local name = UI.getAttribute(id .. "n", "text") local initiative = UI.getAttribute(id .. "i", "text") local pawn = UI.getAttribute(id .. "t", "pawn") local thing = UI.getAttribute(v, "class") local status = option == "True" and true or false if not isPlayer(name) then if not statusCache[name .. "." .. initiative .. "." .. pawn] then statusCache[name .. "." .. initiative .. "." .. pawn] = { conc = false, react = false } end statusCache[name .. "." .. initiative .. "." .. pawn][thing] = status end end function findPawn(player, request, v) local guid = UI.getAttribute(v, "pawn") local pawn = getObjectFromGUID(guid) pawn.call("toggleVisualize", {input = "true", color = "Black"}) --Player["Black"].lookAt( -- { -- position = pawn.getPosition(), -- distance = 60, -- pitch = 60, -- yaw = 270 -- } --) end function seeCache(name, initiative, pawn, thing) if not isPlayer(name) and not isStatic(name) then if statusCache[name .. "." .. initiative .. "." .. pawn] then status = statusCache[name .. "." .. initiative .. "." .. pawn][thing] return status and "True" or "False" end end return false end function widgetExpand(player, request, v) -- request is the requested variable (in this case ID) -- v is the value of said variable. in this case we are in the button -- meaning that the id will be id + o (to signify opening button) -- this will be removed local id = tonumber(string.sub(v, 1, -2)) UI.setAttribute(id, "image", "Widget-open") UI.setAttribute(id .. "p", "active", "true") UI.setAttribute(v, "active", "false") end function widgetReduce(player, request, v) local id = tonumber(string.sub(v, 1, -2)) UI.setAttribute(id, "image", "Widget") UI.setAttribute(id .. "p", "active", "false") UI.setAttribute(id .. "o", "active", "true") end function widgetActivate(player, request, v) local id = tonumber(string.sub(v, 1, -2)) if activated ~= "" then local currentId = mysplit(activated, "|")[2] UI.setAttribute(currentId .. "y", "active", "false") end local name = UI.getAttribute(id .. "n", "text") activated = name .. "|" .. id notify() UI.setAttribute(id .. "y", "active", "true") end function notify() local myId = mysplit(activated, "|")[2] local myPos = findMe(myId) if myPos then local nextPos = myPos + 1 if nextPos > #elements then nextPos = 1 end -- this will manage the card notification for the next -- in the initiative counter if isPlayer(elements[nextPos].name) then local name = string.lower(elements[nextPos].name) if (Player[_defaults.playersColors[name]].seated) then broadcastToColor( "You're next in initiative! Prepare yourself.", _defaults.playersColors[name], {1, 1, 1} ) UI.setAttribute(_defaults.playersColors[name], "active", "true") end end if isPlayer(elements[myPos].name) then local name = string.lower(elements[myPos].name) if (Player[_defaults.playersColors[name]].seated) then broadcastToColor("It's your turn!", _defaults.playersColors[name], {1, 1, 1}) UI.setAttribute(_defaults.playersColors[name], "active", "false") end end end end function isPlayer(name) for i = 1, #_defaults.players do if string.lower(name) == string.lower(_defaults.players[i]) then return true end end end function isStatic(name) for i = 1, #_defaults.static do if string.lower(name) == string.lower(_defaults.static[i]) then return true end end end function findMe(tofind) for i = 1, #elements do if tonumber(tofind) == tonumber(elements[i].id) then return i end end return nil end function nextTurn() -- here goes the movement of the turn counter if activated == "" then end end function addElement(params) -- params is from someone else -- params will be: -- ini : int -- name : string -- side : string -- owner : guid --------------------------------- -- the add element will create a new -- element in the HUD --if params then -- local element = { -- id = id, -- initiative = params.ini, -- name = params.name, -- side = params.side, -- owner = getObjectFromGUID(params.owner), -- visible = true -- } -- table.insert(elements, element) -- id = id + 1 -- RenderElements() --end end function SyncTable() RenderElements() end function RenderElements() table.sort( elements, function(k1, k2) return k1.initiative > k2.initiative end ) local xmlTable = self.UI.getXmlTable() resetTable() local t = xmlTable[3].children[1].children for i = 1, #elements do if debug then print("-------------------") print("To Add:") print("\t" .. elements[i].initiative) print("\t" .. elements[i].name) print("color = " .. parseColor(elements[i].side)) elements[i].name = elements[i].name .. "." .. elements[i].id end local toAdd = { tag = "Image", attributes = { id = elements[i].id, image = "Widget", class = "closed", color = parseColor(elements[i].side) }, children = { { tag = "Panel", children = { { tag = "Button", attributes = { id = elements[i].id .. "o", class = "closed", onClick = "widgetExpand(id)" } }, { tag = "Text", attributes = { class = "initiative", text = elements[i].initiative } }, { tag = "Text", attributes = { class = "name", text = elements[i].name } }, { tag = "Panel", attributes = { id = elements[i].id .. "p", active = "false" }, children = { { tag = "Toggle", attributes = { class = "react" } }, { tag = "Toggle", attributes = { class = "conc" } }, { tag = "Button", attributes = { id = elements[i].id .. "c", class = "opened", onClick = "widgetReduce(id)" } } } } } } } } --printTable(toAdd) table.insert(t, toAdd) toAdd = nil end updateTable(xmlTable) end function parseColor(side) return _defaults.color[side] end function updateTable(xmlTable) local h = getHeightMultiplier() UI.setXmlTable(xmlTable) UI.setAttribute("layout", "height", h) end function resetTable() local xmlTable = UI.getXmlTable() xmlTable[_defaults.xt].children[_defaults.xc].children = {} UI.setXmlTable(xmlTable) --printTable(xmlTable) end function getHeightMultiplier() local counter = 0 for i = 1, #elements do if elements[i].visible then counter = counter + 1 end end return counter * 50 end function setSeated(players) Wait.time( function() local mat = getObjectFromGUID(_defaults.initiative_mat) for i = 1, #players.input do log(Player[_defaults.playersColors[players.input[i]]].seated and "true" or "false", players.input[i]) mat.UI.setAttribute( players.input[i], "active", Player[_defaults.playersColors[players.input[i]]].seated and "true" or "false" ) if debug then mat.UI.setAttribute(players.input[i], "active", "true") end end end, 1 ) end function requestPlayer(player) if not _defaults.initiative_mat then _defaults.initiative_mat = player.call end log(Player[_defaults.playersColors[player.p]].seated, player.p .. " seated") if Player[_defaults.playersColors[player.p]].seated then UI.setAttribute(_defaults.playersColors[player.p] .. "_box", "active", "true") initiatives[_defaults.playersColors[player.p]] = {t = player.t, i = ""} end if debug then UI.setAttribute(_defaults.playersColors[player.p] .. "_box", "active", "true") initiatives[_defaults.playersColors[player.p]] = {t = player.t, i = ""} end end function submitRequest(player) -- this activates on the submit button if initiatives[player.color].i ~= "" then UI.setAttribute(player.color .. "_box", "active", "false") local playerName = getPlayerByColor(player.color) playerName = playerName:sub(1, 1):upper() .. playerName:sub(2) -- capitalize name printToAll( "[" .. Color[player.color]:toHex(false) .. "]" .. playerName .. ":[-] " .. initiatives[player.color].i, "White" ) -- print initiative in the chat local mat = getObjectFromGUID(_defaults.initiative_mat) mat.UI.setAttribute(playerName:lower(), "text", playerName .. "|" .. initiatives[player.color].i) mat.UI.setAttribute(playerName:lower(), "textColor", "#ff7f27") -- setting ui to tell DM that player has written if debug then log(playerName:lower(), "setting class to done, " .. initiatives[player.color].i) end local obj = getObjectFromGUID(initiatives[player.color].t) obj.editInput({index = 0, value = playerName .. "\n" .. initiatives[player.color].i}) initiatives[player.color].d = true end end function submitChange(player, value, obj) -- this activates while the player is writing on its little box initiatives[player.color].i = value end function isInCombat() return self.UI.getAttribute("widget", "active") == "true" end function getPlayerByColor(color) for k, v in pairs(_defaults.playersColors) do if v == color then return k end end return nil end --#endregion
require("iuplua") data = {} lastId = 0 function crud_create(surname, name) local item = {} lastId = lastId + 1 item.name = name item.surname = surname item.id = lastId data[item.id] = item return lastId end function crud_read(nextId) local n, v = next(data, nextId) if not n then return n end return n, v.surname, v.name end function crud_update(id, surname, name) data[id].name = name data[id].surname = surname end function crud_delete(id) data[id] = nil end --********************************** Main ***************************************** lbl_filter = iup.label{title = "Filter prefix:"} txt_filter = iup.text{size = "60x", expand = "HORIZONTAL"} lst_names = iup.list{size = "60x", expand = "YES", visiblelines=6} lbl_name = iup.label{title = "Name:", size = 35} txt_name = iup.text{size = 60, expand = "HORIZONTAL"} lbl_surname = iup.label{title = "Surname:", size = 35} txt_surname = iup.text{size = 60, expand = "HORIZONTAL"} btn_create = iup.button{title = "Create", size = "30"} btn_update = iup.button{title = "Update", size = "30", active = "NO"} btn_delete = iup.button{title = "Delete", size = "30", active = "NO"} hbx_filter = iup.hbox{iup.hbox{lbl_filter, txt_filter; alignment = "ACENTER"}, iup.fill{}; homogeneous = "YES"} hbx_name = iup.hbox{lbl_name, txt_name; alignment = "ACENTER"} hbx_surname = iup.hbox{lbl_surname, txt_surname; alignment = "ACENTER"} hbx_buttons = iup.hbox{btn_create, btn_update, btn_delete} vbx_input = iup.vbox{hbx_name, hbx_surname} hbox = iup.hbox{lst_names, vbx_input; homogeneous = "YES"} box = iup.vbox{hbx_filter, hbox, hbx_buttons; nmargin = "10x10"} dlg = iup.dialog{box, title = "CRUD", gap = "10"} function trim (str) return string.gsub(str, "^%s*(.-)%s*$", "%1") end function filterName(name, filter) local i,j = string.find(string.lower(name), string.lower(filter)) return i==1 end function loadList() local currId = nil local surname, name local count = 1 local filter = txt_filter.value if filter then filter = trim(filter) if filter == "" then filter = nil end end lst_names[1] = nil currId, surname, name = crud_read(currId) while currId do if not filter or filterName(surname, filter) then lst_names[count] = surname..", "..name lst_names["ID"..count] = currId count = count + 1 end currId, surname, name = crud_read(currId) end lst_names.value = 0 end function updateButtonsState() if lst_names.value == "0" then btn_delete.active = "NO" btn_update.active = "NO" else btn_delete.active = "YES" btn_update.active = "YES" end end function lst_names:valuechanged_cb() updateButtonsState() end function txt_filter:valuechanged_cb() loadList(self.value) end function btn_create:action() local name = trim(txt_name.value) local surname = trim(txt_surname.value) crud_create(surname, name) txt_name.value = "" txt_surname.value = "" loadList() updateButtonsState() end function btn_update:action() local index = lst_names.value local id = lst_names["ID"..index] local name = trim(txt_name.value) local surname = trim(txt_surname.value) crud_update(tonumber(id), surname, name) txt_name.value = "" txt_surname.value = "" loadList() updateButtonsState() end function btn_delete:action() local index = lst_names.value local id = lst_names["ID"..index] crud_delete(tonumber(id), surname, name) txt_name.value = "" txt_surname.value = "" loadList() updateButtonsState() end dlg:showxy( iup.CENTER, iup.CENTER ) if (iup.MainLoopLevel()==0) then iup.MainLoop() end
local is_avail = require("wandbox.util").is_available local config = {} config.options = { client_list = { is_avail("curl"), is_avail("wget"), is_avail("socket") }, compilers = { cpp = "clang-head", c = "gcc-head", coffee = "coffeescript-head", crystal = "crystal-head", cs = "mono-head", d = "dmd-head", elixir = "elixir-head", erlang = "erlang-head", go = "go-head", groovy = "groovy-head", haskell = "ghc-head", java = "openjdk-head", javascript = "nodejs-head", lazyk = "lazyk", lisp = "sbcl-head", lua = "lua-5.3.4", nim = "nim-head", ocaml = "ocaml-head", pascal = "fpc-head", perl = "perl-5.25.10", php = "php-head", pony = "pony-head", python = "cpython-head", rill = "rill-head", ruby = "ruby-head", rust = "rust-head", scala = "scala-2.13.x", sh = "bash", sql = "sqlite-head", swift = "swift-head", vim = "vim-head", }, options = {}, compiler_option_raw = { cpp = "-fno-color-diagnostics" }, stdin = nil, runtime_option_raw = {}, save = nil, open_qf = nil, } config.set = function(options) config.options = vim.tbl_extend("force", config.options, options) end return config
_ENV=namespace "container" using_namespace "luaClass" template("mat") function mat:mat(rowNum,colNum) local data={} self._data=data self._rowNum=rowNum self._colNum=colNum for i=1,rowNum*colNum do data[i]=false end end function mat:at(row,col) return self._data[col+(row-1)*self._colNum] or nil end function mat:set(row,col,value) self._data[col+(row-1)*self._colNum]=value end function mat:del(row,col) self:set(row,col,false) end function mat:colNum() return self._colNum end function mat:rowNum() return self._rowNum end function mat:size() return self._colNum*self._rowNum end function mat:iter() return ipairs(self._data) end function mat:clear() for i=1,self:size() do self._data[i]=false end end function mat:onFun(luaf) for i,v in ipairs(self._data) do luaf(v) end end
-- Dependencies local Assets = require("engine.Assets") local Config = require("engine.Config") local Table = require("engine.Table") -- Clouds module local Clouds = {} -- Variables local gameWidth = Config.gameWidth local gameHeight = Config.gameHeight local sprites = Assets.sprites.clouds local cloudWidth = sprites[1].width local cloudHeight = sprites[1].height local clouds = {} local maxClouds = 0 local topGeneration = false local cameraY = 0 -- Generates cloud in the specified area local function generateCloud(left, right, top, bottom) return { front = love.math.random() > 0.5, x = love.math.random(left, right), y = love.math.random(top, bottom), speed = love.math.random(16, 64), sprite = love.math.random(1, #sprites) } end -- Generates cloud in the top area local function generateCloudOnTop() local left = -cloudWidth / 2 local right = gameWidth - cloudWidth / 2 local top = cameraY - gameHeight local bottom = cameraY - cloudHeight return generateCloud(left, right, top, bottom) end -- Generates cloud in the middle area local function generateCloudInMiddle() local left = -cloudWidth / 2 local right = gameWidth - cloudWidth / 2 local top = cameraY - cloudHeight / 2 local bottom = cameraY + gameHeight - cloudHeight / 2 return generateCloud(left, right, top, bottom) end -- Generates cloud in the right area local function generateCloudOnRight() local left = gameWidth local right = gameWidth + cloudWidth / 2 local top = cameraY - cloudHeight / 2 local bottom = cameraY + gameHeight - cloudHeight / 2 return generateCloud(left, right, top, bottom) end -- Generates missing clouds using the generator function local function generateMissingClouds(generator) for i = 1, maxClouds - #clouds do table.insert(clouds, generator()) end end -- Draws clouds in front or back area local function drawClouds(front) for i, cloud in ipairs(clouds) do if cloud.front == front then sprites[cloud.sprite]:draw(cloud.x, cloud.y - cameraY) end end end -- Draws clouds in front area function Clouds.drawFront() drawClouds(true) end -- Draws clouds in back area function Clouds.drawBack() drawClouds(false) end -- Updates clouds function Clouds.update(delta) Table.filter(clouds, function(i, cloud) cloud.x = cloud.x - cloud.speed * delta return cloud.x < -cloudWidth or cloud.y > cameraY + gameHeight end) if topGeneration then generateMissingClouds(generateCloudOnTop) else generateMissingClouds(generateCloudOnRight) end end -- Fills screen with clouds function Clouds.fillScreen() generateMissingClouds(generateCloudInMiddle) end -- Sets maximum number of clouds function Clouds.setMaxClouds(value) maxClouds = value end -- Sets camera Y position function Clouds.setCameraY(value) cameraY = value end -- Enables cloud generation above the camera function Clouds.setTopGeneration(value) topGeneration = value end return Clouds
-- IupRadio Example in IupLua -- Creates a dialog for the user to select his/her gender. -- In this case, the radio element is essential to prevent the user from -- selecting both options. require( "iuplua" ) male = iup.toggle{title="Male", tip="Two state button - Exclusive - RADIO"} female = iup.toggle{title="Female", tip="Two state button - Exclusive - RADIO"} exclusive = iup.radio { iup.vbox { male, female }; value=female, } frame = iup.frame{exclusive; title="Gender"} dialog = iup.dialog { iup.hbox { iup.fill{}, frame, iup.fill{} }; title="IupRadio", size=140, resize="NO", minbox="NO", maxbox="NO" } dialog:show() if (iup.MainLoopLevel()==0) then iup.MainLoop() end
snet.Callback('qsystem_sync_players', function(_, ent, players) ent.players = players QuestSystem:Debug('SyncPlayers (' .. table.Count(players) .. ') - ' .. table.ToString(players)) end).Validator(SNET_ENTITY_VALIDATOR).Register()
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ---- -- ZO_MarketAnnouncement_Shared ---- ZO_MARKET_ANNOUNCEMENT_TILE_DIMENSIONS_X = 315 ZO_MARKET_ANNOUNCEMENT_TILE_DIMENSIONS_Y = 210 ZO_MARKET_ANNOUNCEMENT_TILE_DIMENSIONS_ASPECT_RATIO = ZO_MARKET_ANNOUNCEMENT_TILE_DIMENSIONS_X / ZO_MARKET_ANNOUNCEMENT_TILE_DIMENSIONS_Y ZO_ACTION_TILE_TYPE = { EVENT_ANNOUNCEMENT = 1, DAILY_REWARDS = 2, ZONE_STORIES = 3, } ZO_ACTION_SORTED_TILE_TYPE = { ZO_ACTION_TILE_TYPE.EVENT_ANNOUNCEMENT, ZO_ACTION_TILE_TYPE.DAILY_REWARDS, ZO_ACTION_TILE_TYPE.ZONE_STORIES, } ZO_MarketAnnouncement_Shared = ZO_Object:Subclass() function ZO_MarketAnnouncement_Shared:New(...) local announcement = ZO_Object.New(self) announcement:Initialize(...) return announcement end function ZO_MarketAnnouncement_Shared:InitializeKeybindButtons() self.closeButton = self.controlContainer:GetNamedChild("Close") self.closeButton:SetKeybind("MARKET_ANNOUNCEMENT_CLOSE") self.closeButton:SetClickSound(SOUNDS.DIALOG_ACCEPT) self.closeButton:SetCallback(function() self:OnMarketAnnouncementCloseKeybind() end) end function ZO_MarketAnnouncement_Shared:Initialize(control, fragmentConditionFunction) self.control = control local container = control:GetNamedChild("Container") self.titleLabel = container:GetNamedChild("Title") self.carouselControl = container:GetNamedChild("Carousel") self.scrollContainer = container:GetNamedChild("ScrollContainer") self.actionTileListControl = container:GetNamedChild("ActionTileList") self.crownStoreLockedControl = container:GetNamedChild("LockedCrownStore") self.crownStoreLockedTexture = self.crownStoreLockedControl:GetNamedChild("Background") self.controlContainer = container self.actionTileList = {} self.actionTileControlPoolMap = {} for _, tileType in pairs(ZO_ACTION_TILE_TYPE) do self:AddTileTypeObjectPoolToMap(tileType) end self:InitializeKeybindButtons() local fragment = ZO_FadeSceneFragment:New(control) fragment:RegisterCallback("StateChange", function(...) self:OnStateChanged(...) end) if fragmentConditionFunction then fragment:SetConditional(fragmentConditionFunction) end self.fragment = fragment self.marketProductSelectedCallback = function(...) self:UpdateLabels(...) end local function OnDailyLoginRewardsUpdated() self:OnDailyLoginRewardsUpdated() end ZO_MARKET_ANNOUNCEMENT_MANAGER:RegisterCallback("OnMarketAnnouncementDataUpdated", function() self:UpdateMarketCarousel() end) ZO_MARKET_ANNOUNCEMENT_MANAGER:RegisterCallback("EventAnnouncementExpired", function() self:LayoutActionTiles() end) control:RegisterForEvent(EVENT_DAILY_LOGIN_REWARDS_UPDATED, OnDailyLoginRewardsUpdated) end function ZO_MarketAnnouncement_Shared:AddTileTypeObjectPoolToMap(tileType) self.actionTileControlPoolMap[tileType] = ZO_ControlPool:New(self.actionTileControlByType[tileType], self.actionTileListControl) local function ResetFunction(control) control.object:Reset() end self.actionTileControlPoolMap[tileType]:SetCustomResetBehavior(ResetFunction) end function ZO_MarketAnnouncement_Shared:OnStateChanged(oldState, newState) if newState == SCENE_SHOWING then self:OnShowing() elseif newState == SCENE_SHOWN then self:OnShown() elseif newState == SCENE_HIDING then self:OnHiding() elseif newState == SCENE_HIDDEN then self:OnHidden() end end function ZO_MarketAnnouncement_Shared:OnDailyLoginRewardsUpdated() if self.fragment:IsShowing() then self:LayoutActionTiles() end end function ZO_MarketAnnouncement_Shared:UpdateLabels(productData) self:UpdatePositionLabel(productData.index) end function ZO_MarketAnnouncement_Shared:UpdatePositionLabel(index) self.carousel:UpdateSelection(index) end function ZO_MarketAnnouncement_Shared:GetFragment() return self.fragment end function ZO_MarketAnnouncement_Shared:OnShowing() PlaySound(SOUNDS.DEFAULT_WINDOW_OPEN) RequestEventAnnouncements() self:LayoutActionTiles() if GetMarketAnnouncementCrownStoreLocked() then self.carouselControl:SetHidden(true) self.crownStoreLockedControl:SetHidden(false) self.crownStoreLockedTexture:SetTexture(GetMarketAnnouncementCrownStoreLockedBackground()) else UpdateMarketAnnouncement() self:UpdateMarketCarousel() self.carousel:Activate() self.carouselControl:SetHidden(false) self.crownStoreLockedControl:SetHidden(true) end end function ZO_MarketAnnouncement_Shared:OnShown() -- To be overridden end function ZO_MarketAnnouncement_Shared:OnHiding() PlaySound(SOUNDS.DEFAULT_WINDOW_CLOSE) self.carousel:Deactivate() end function ZO_MarketAnnouncement_Shared:OnHidden() -- To be overridden end function ZO_MarketAnnouncement_Shared:UpdateMarketCarousel() if self.fragment:IsShowing() then local productInfoTable = ZO_MARKET_ANNOUNCEMENT_MANAGER:GetProductInfoTable() self.carousel:Clear() for index, productInfo in ipairs(productInfoTable) do local marketProduct = self:CreateMarketProduct() marketProduct:SetMarketProductData(productInfo.productData) local data = { marketProduct = marketProduct, callback = self.marketProductSelectedCallback, index = index } self.carousel:AddEntry(data) end self.carousel:Commit() if #productInfoTable > 0 then self.carousel:UpdateSelection(1) end end end function ZO_MarketAnnouncement_Shared:OnSelectionClicked() -- To be overridden end function ZO_MarketAnnouncement_Shared:OnHelpClicked() -- To be overridden end function ZO_MarketAnnouncement_Shared:OnCloseClicked() self.closeButton:OnClicked() end function ZO_MarketAnnouncement_Shared:OnMarketAnnouncementCloseKeybind() SCENE_MANAGER:HideCurrentScene() end function ZO_MarketAnnouncement_Shared:OnMarketAnnouncementViewCrownStoreKeybind() local targetData = self.carousel:GetSelectedData() local marketProductId = targetData.marketProduct:GetId() internalassert(marketProductId ~= 0, string.format("Announcement Crown Store Keybind for %s has a market product id: 0", targetData.marketProduct:GetMarketProductDisplayName())) self:DoOpenMarketBehaviorForMarketProductId(marketProductId) end function ZO_MarketAnnouncement_Shared:DoOpenMarketBehaviorForMarketProductId(marketProductId) local openBehavior = GetMarketProductOpenMarketBehavior(marketProductId) local additionalData = GetMarketProductOpenMarketBehaviorReferenceData(marketProductId) if openBehavior == OPEN_MARKET_BEHAVIOR_NAVIGATE_TO_PRODUCT then additionalData = marketProductId end if openBehavior == OPEN_MARKET_BEHAVIOR_SHOW_CHAPTER_UPGRADE then ZO_ShowChapterUpgradePlatformScreen(MARKET_OPEN_OPERATION_ANNOUNCEMENT, additionalData) elseif not IsInGamepadPreferredMode() and openBehavior == OPEN_MARKET_BEHAVIOR_SHOW_ESO_PLUS_CATEGORY then ESO_PLUS_OFFERS_KEYBOARD:RequestShowMarket(MARKET_OPEN_OPERATION_ANNOUNCEMENT, openBehavior, additionalData) else SYSTEMS:GetObject(ZO_MARKET_NAME):RequestShowMarket(MARKET_OPEN_OPERATION_ANNOUNCEMENT, openBehavior, additionalData) end end function ZO_MarketAnnouncement_Shared.GetEventAnnouncementTilesData(tileInfoList) --- Add tile if there is an active event if ZO_MARKET_ANNOUNCEMENT_MANAGER:GetNumEventAnnouncements() > 0 then local eventAnnouncementTileInfo = { type = ZO_ACTION_TILE_TYPE.EVENT_ANNOUNCEMENT, data = { eventAnnouncementIndex = 1 -- Always show first sorted announcement on the tile }, visible = true, } table.insert(tileInfoList, eventAnnouncementTileInfo) end end function ZO_MarketAnnouncement_Shared.GetDailyRewardsTilesData(tileInfoList) --- Add tile if Daily Rewards is unlocked if not ZO_DAILYLOGINREWARDS_MANAGER:IsDailyRewardsLocked() then local dailyRewardIndex = ZO_DAILYLOGINREWARDS_MANAGER:GetDailyLoginRewardIndex() local dailyRewardTileInfo = { type = ZO_ACTION_TILE_TYPE.DAILY_REWARDS, data = { dailyRewardIndex = dailyRewardIndex }, visible = true, } table.insert(tileInfoList, dailyRewardTileInfo) end end function ZO_MarketAnnouncement_Shared.GetZoneStoriesTilesData(tileInfoList) local zoneId if IsZoneStoryActivelyTracking() then zoneId = GetTrackedZoneStoryActivityInfo() else local zoneIndex = GetUnitZoneIndex("player") zoneId = ZO_ExplorationUtils_GetZoneStoryZoneIdByZoneIndex(zoneIndex) end if HasZoneStoriesData(zoneId) and not IsZoneStoryComplete(zoneId) then local zoneStoriesTileInfo = { type = ZO_ACTION_TILE_TYPE.ZONE_STORIES, data = { zoneId = zoneId, }, visible = true, } table.insert(tileInfoList, zoneStoriesTileInfo) end end do ZO_TILE_TYPE_TO_GET_TILE_INFO_FUNCTION = { [ZO_ACTION_TILE_TYPE.EVENT_ANNOUNCEMENT] = ZO_MarketAnnouncement_Shared.GetEventAnnouncementTilesData, [ZO_ACTION_TILE_TYPE.DAILY_REWARDS] = ZO_MarketAnnouncement_Shared.GetDailyRewardsTilesData, [ZO_ACTION_TILE_TYPE.ZONE_STORIES] = ZO_MarketAnnouncement_Shared.GetZoneStoriesTilesData, } function ZO_MarketAnnouncement_Shared:LayoutActionTiles() -- Get list of available tile infos local availableTileInfoList = {} for _, data in ipairs(ZO_ACTION_SORTED_TILE_TYPE) do local tileInfoFunction = ZO_TILE_TYPE_TO_GET_TILE_INFO_FUNCTION[data] tileInfoFunction(availableTileInfoList) end -- Clear Data from previous show self.actionTileList = {} for _, controlPool in pairs(self.actionTileControlPoolMap) do controlPool:ReleaseAllObjects() end -- Create display tiles from available tile infos (Limited at 3 as that's the most the display supports) local NUM_MAX_DISPLAY_TILES = 3 for i, actionTileInfo in ipairs(availableTileInfoList) do local visible if type(actionTileInfo.visible) == "function" then visible = actionTileInfo.visible() else visible = actionTileInfo.visible end if visible and self.actionTileControlPoolMap[actionTileInfo.type] then local actionTileControl = self.actionTileControlPoolMap[actionTileInfo.type]:AcquireObject() actionTileControl.object:Layout(actionTileInfo.data) table.insert(self.actionTileList, actionTileControl) -- Set Anchors local ACTION_TILE_HORIZONTAL_PADDING = 34 if #self.actionTileList > 1 then actionTileControl:SetAnchor(TOPLEFT, self.actionTileList[i-1], TOPRIGHT, ACTION_TILE_HORIZONTAL_PADDING) else actionTileControl:SetAnchor(TOPLEFT) end if #self.actionTileList == NUM_MAX_DISPLAY_TILES then break end else assert("ObjectPool was not defined for Action Tile " .. i) end end end end function ZO_MarketAnnouncement_Shared:CreateMarketProduct(productId) -- To be overridden end
-- This is a part of uJIT's testing suite. -- Copyright (C) 2015-2019 IPONWEB Ltd. See Copyright Notice in COPYRIGHT local function test_trim(str, expected) local actual = ujit.string.trim(str) if actual ~= expected then error(string.format('\nTest failed: trim("%s")\n\tExpected: "%s"\n\tActual: "%s"', str, expected, actual), 2) end end test_trim("", "") test_trim(" ", "") test_trim(" \t \n \v\f ", "") test_trim("foo", "foo") test_trim("foo bar", "foo bar") test_trim(" foo", "foo") test_trim("foo ", "foo") test_trim(" \t\n\v \f\r foo bar \t\v \f ", "foo bar") test_trim(" foo\0bar ", "foo\0bar") test_trim(" \t\n\0\0\0foo\0bar\0\0\v \n ", "\0\0\0foo\0bar\0\0") -- test calling with extra args (they should be ignored) assert(ujit.string.trim(" ", 42, "hello") == "") assert(ujit.string.trim(" foo ", 42, "hello") == "foo")
data:extend( { { type = "recipe", name = "gun-turret-mk2", enabled = false, energy_required = 10, ingredients = { {"gun-turret", 2}, {"titanium-alloy", 10} }, result = "gun-turret-mk2" }, { type = "recipe", name = "laser-turret-mk2", enabled = false, energy_required = 20, ingredients = { {"laser-turret", 2}, {"titanium-alloy", 10}, {"processing-unit", 10}, {"battery-equipment", 5} }, result = "laser-turret-mk2" }, { type = "recipe", name = "shattering-bullet-magazine", enabled = false, energy_required = 3, ingredients = { {"copper-plate", 2}, {"titanium-alloy", 2} }, result = "shattering-bullet-magazine" }, { type = "recipe", name = "shattering-shotgun-shell", enabled = false, energy_required = 3, ingredients = { {"copper-plate", 2}, {"titanium-alloy", 2} }, result = "shattering-shotgun-shell" }, { type = "recipe", name = "iron-wall", enabled = false, energy_required = 20, ingredients = { {"stone-wall", 1}, {"iron-plate", 2} }, result = "iron-wall" }, { type = "recipe", name = "steel-wall", enabled = false, energy_required = 20, ingredients = { {"iron-wall", 1}, {"steel-plate", 2} }, result = "steel-wall" }, { type = "recipe", name = "titanium-wall", enabled = false, energy_required = 20, ingredients = { {"steel-wall", 1}, {"titanium-alloy", 2} }, result = "titanium-wall" }, { type = "recipe", name = "iron-gate", enabled = false, energy_required = 20, ingredients = { {"gate", 2}, {"iron-plate", 10} }, result = "iron-gate" }, { type = "recipe", name = "steel-gate", enabled = false, energy_required = 20, ingredients = { {"iron-gate", 2}, {"steel-plate", 10} }, result = "steel-gate" }, { type = "recipe", name = "titanium-gate", enabled = false, energy_required = 20, ingredients = { {"steel-gate", 2}, {"titanium-alloy", 10}, }, result = "titanium-gate" } })
local config = require "api-umbrella.proxy.models.file_config" local json_decode = require("cjson").decode local xpcall_error_handler = require "api-umbrella.utils.xpcall_error_handler" local elasticsearch_templates local path = os.getenv("API_UMBRELLA_SRC_ROOT") .. "/config/elasticsearch_templates_v" .. config["elasticsearch"]["template_version"] if config["elasticsearch"]["api_version"] >= 5 then path = path .. "_es5.json" elseif config["elasticsearch"]["api_version"] >= 2 then path = path .. "_es2.json" else error("Unsupported version of elasticsearch: " .. (config["elasticsearch"]["api_version"] or "")) end local f, err = io.open(path, "rb") if err then ngx.log(ngx.ERR, "failed to open file: ", err) else local content = f:read("*all") if content then local ok, data = xpcall(json_decode, xpcall_error_handler, content) if ok then elasticsearch_templates = data -- In the test environment, disable replicas and reduce shards to speed -- things up. if config["app_env"] == "test" then for _, template in ipairs(elasticsearch_templates) do if not template["template"]["settings"] then template["template"]["settings"] = {} end if not template["template"]["settings"]["index"] then template["template"]["settings"]["index"] = {} end template["template"]["settings"]["index"]["number_of_shards"] = 1 template["template"]["settings"]["index"]["number_of_replicas"] = 0 end end else ngx.log(ngx.ERR, "failed to parse json for " .. (path or "") .. ": " .. (data or "")) end end f:close() end return elasticsearch_templates
local select, pairs, string_lower, strmatch, tremove, tinsert, getglobal, string_gsub = select, pairs, string.lower, strmatch, tremove, tinsert, getglobal, string.gsub local WorldFrame, UnitExists = WorldFrame, UnitExists local Gladdy = LibStub("Gladdy") local L = Gladdy.L local GetSpellInfo, CreateFrame, GetCVar = GetSpellInfo, CreateFrame, GetCVar --------------------------------------------------- -- Constants --------------------------------------------------- local BLIZZ = "BLIZZ" local ALOFT = "ALOFT" local SOHIGHPLATES = "SOHIGHPLATES" local ELVUI = "ELVUI" local SHAGUPLATES = "SHAGUPLATES" local PLATES = "PLATES" local totemData = { -- Fire [string_lower("Searing Totem")] = {id = 3599,texture = select(3, GetSpellInfo(3599)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Searing Totem [string_lower("Flametongue Totem")] = {id = 8227,texture = select(3, GetSpellInfo(8227)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Flametongue Totem [string_lower("Magma Totem")] = {id = 8190,texture = select(3, GetSpellInfo(8190)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Magma Totem [string_lower("Fire Nova Totem")] = {id = 1535,texture = select(3, GetSpellInfo(1535)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Fire Nova Totem [string_lower("Totem of Wrath")] = {id = 30706,texture = select(3, GetSpellInfo(30706)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 1}, -- Totem of Wrath [string_lower("Fire Elemental Totem")] = {id = 32982,texture = select(3, GetSpellInfo(32982)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Fire Elemental Totem [string_lower("Frost Resistance Totem")] = {id = 8181,texture = select(3, GetSpellInfo(8181)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Frost Resistance Totem -- Water [string_lower("Fire Resistance Totem")] = {id = 8184,texture = select(3, GetSpellInfo(8184)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Fire Resistance Totem [string_lower("Poison Cleansing Totem")] = {id = 8166,texture = select(3, GetSpellInfo(8166)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Poison Cleansing Totem [string_lower("Disease Cleansing Totem")] = {id = 8170,texture = select(3, GetSpellInfo(8170)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Disease Cleansing Totem [string_lower("Healing Stream Totem")] = {id = 5394,texture = select(3, GetSpellInfo(5394)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Healing Stream Totem [string_lower("Mana Tide Totem")] = {id = 16190,texture = select(3, GetSpellInfo(16190)), color = {r = 0.078, g = 0.9, b = 0.16, a = 1}, enabled = true, priority = 3}, -- Mana Tide Totem [string_lower("Mana Spring Totem")] = {id = 5675,texture = "Interface\\AddOns\\Gladdy\\Images\\Totems\\Spell_Nature_ManaRegenTotem_edit", color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 1}, -- Mana Spring Totem -- Earth [string_lower("Earthbind Totem")] = {id = 2484,texture = select(3, GetSpellInfo(2484)), color = {r = 0.5, g = 0.5, b = 0.5, a = 1}, enabled = true, priority = 1}, -- Earthbind Totem [string_lower("Stoneclaw Totem")] = {id = 5730,texture = select(3, GetSpellInfo(5730)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Stoneclaw Totem [string_lower("Stoneskin Totem")] = {id = 8071,texture = select(3, GetSpellInfo(8071)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Stoneskin Totem [string_lower("Strength of Earth Totem")] = {id = 8075,texture = select(3, GetSpellInfo(8075)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Strength of Earth Totem [string_lower("Earth Elemental Totem")] = {id = 33663,texture = select(3, GetSpellInfo(33663)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Earth Elemental Totem [string_lower("Tremor Totem")] = {id = 8143,texture = select(3, GetSpellInfo(8143)), color = {r = 1, g = 0.9, b = 0.1, a = 1}, enabled = true, priority = 3}, -- Tremor Totem -- Air [string_lower("Grounding Totem")] = {id = 8177,texture = select(3, GetSpellInfo(8177)), color = {r = 0, g = 0.53, b = 0.92, a = 1}, enabled = true, priority = 3}, -- Grounding Totem [string_lower("Grace of Air Totem")] = {id = 8835,texture = "Interface\\AddOns\\Gladdy\\Images\\Totems\\Spell_Nature_InvisibilityTotem_edit", color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Grace of Air Totem [string_lower("Nature Resistance Totem")] = {id = 10595,texture = select(3, GetSpellInfo(10595)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Nature Resistance Totem [string_lower("Windfury Totem")] = {id = 8512,texture = "Interface\\AddOns\\Gladdy\\Images\\Totems\\Spell_Nature_Windfury_edit", color = {r = 0.96, g = 0, b = 0.07, a = 1}, enabled = true, priority = 2}, -- Windfury Totem [string_lower("Sentry Totem")] = {id = 6495, texture = "Interface\\AddOns\\Gladdy\\Images\\Totems\\Spell_Nature_RemoveCurse_edit", color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Sentry Totem [string_lower("Windwall Totem")] = {id = 15107,texture = select(3, GetSpellInfo(15107)), color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Windwall Totem [string_lower("Wrath of Air Totem")] = {id = 3738,texture = "Interface\\AddOns\\Gladdy\\Images\\Totems\\Spell_Nature_SlowingTotem_edit", color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Wrath of Air Totem [string_lower("Tranquil Air Totem")] = {id = 25908,texture = "Interface\\Icons\\INV_Staff_07", color = {r = 0, g = 0, b = 0, a = 1}, enabled = true, priority = 0}, -- Tranquil Air Totem } local localizedTotemData = { ["default"] = { [string_lower(select(1, GetSpellInfo(3599)))] = totemData[string_lower("Searing Totem")], -- Searing Totem [string_lower(select(1, GetSpellInfo(8227)))] = totemData[string_lower("Flametongue Totem")], -- Flametongue Totem [string_lower(select(1, GetSpellInfo(8190)))] = totemData[string_lower("Magma Totem")], -- Magma Totem [string_lower(select(1, GetSpellInfo(1535)))] = totemData[string_lower("Fire Nova Totem")], -- Fire Nova Totem [string_lower(select(1, GetSpellInfo(30706)))] = totemData[string_lower("Totem of Wrath")], -- Totem of Wrath [string_lower(select(1, GetSpellInfo(32982)))] = totemData[string_lower("Fire Elemental Totem")], -- Fire Elemental Totem [string_lower(select(1, GetSpellInfo(8181)))] = totemData[string_lower("Frost Resistance Totem")], -- Frost Resistance Totem -- Water [string_lower(select(1, GetSpellInfo(8184)))] = totemData[string_lower("Fire Resistance Totem")], -- Fire Resistance Totem [string_lower(select(1, GetSpellInfo(8166)))] = totemData[string_lower("Poison Cleansing Totem")], -- Poison Cleansing Totem [string_lower(select(1, GetSpellInfo(8170)))] = totemData[string_lower("Disease Cleansing Totem")], -- Disease Cleansing Totem [string_lower(select(1, GetSpellInfo(5394)))] = totemData[string_lower("Healing Stream Totem")], -- Healing Stream Totem [string_lower(select(1, GetSpellInfo(16190)))] = totemData[string_lower("Mana Tide Totem")], -- Mana Tide Totem [string_lower(select(1, GetSpellInfo(5675)))] = totemData[string_lower("Mana Spring Totem")], -- Mana Spring Totem -- Earth [string_lower(select(1, GetSpellInfo(2484)))] = totemData[string_lower("Earthbind Totem")], -- Earthbind Totem [string_lower(select(1, GetSpellInfo(5730)))] = totemData[string_lower("Stoneclaw Totem")], -- Stoneclaw Totem [string_lower(select(1, GetSpellInfo(8071)))] = totemData[string_lower("Stoneskin Totem")], -- Stoneskin Totem [string_lower(select(1, GetSpellInfo(8075)))] = totemData[string_lower("Strength of Earth Totem")], -- Strength of Earth Totem [string_lower(select(1, GetSpellInfo(33663)))] = totemData[string_lower("Earth Elemental Totem")], -- Earth Elemental Totem [string_lower(select(1, GetSpellInfo(8143)))] = totemData[string_lower("Tremor Totem")], -- Tremor Totem -- Air [string_lower(select(1, GetSpellInfo(8177)))] = totemData[string_lower("Grounding Totem")], -- Grounding Totem [string_lower(select(1, GetSpellInfo(8835)))] = totemData[string_lower("Grace of Air Totem")], -- Grace of Air Totem [string_lower(select(1, GetSpellInfo(10595)))] = totemData[string_lower("Nature Resistance Totem")], -- Nature Resistance Totem [string_lower(select(1, GetSpellInfo(8512)))] = totemData[string_lower("Windfury Totem")], -- Windfury Totem [string_lower(select(1, GetSpellInfo(6495)))] = totemData[string_lower("Sentry Totem")], -- Sentry Totem [string_lower(select(1, GetSpellInfo(15107)))] = totemData[string_lower("Windwall Totem")], -- Windwall Totem [string_lower(select(1, GetSpellInfo(3738)))] = totemData[string_lower("Wrath of Air Totem")], -- Wrath of Air Totem [string_lower(select(1, GetSpellInfo(25908)))] = totemData[string_lower("Tranquil Air Totem")], -- Tranquil Air Totem }, ["frFR"] = { [string_lower("Totem incendiaire")] = totemData[string_lower("Searing Totem")], [string_lower("Totem Langue de feu")] = totemData[string_lower("Flametongue Totem")], [string_lower("Totem de lien terrestre")] = totemData[string_lower("Earthbind Totem")], [string_lower("Totem de Griffes de pierre")] = totemData[string_lower("Stoneclaw Totem")], [string_lower("Totem Nova de feu")] = totemData[string_lower("Fire Nova Totem")], [string_lower("Totem de Magma")] = totemData[string_lower("Magma Totem")], [string_lower("Totem de courroux")] = totemData[string_lower("Totem of Wrath")], [string_lower("Totem d'\195\169lementaire de feu")] = totemData[string_lower("Fire Elemental Totem")], [string_lower("Totem d'\195\169l\195\169mentaire de feu")] = totemData[string_lower("Fire Elemental Totem")], [string_lower("Totem de Peau de pierre")] = totemData[string_lower("Stoneskin Totem")], [string_lower("Totem d'\195\169lementaire de terre")] = totemData[string_lower("Earth Elemental Totem")], [string_lower("Totem d'\195\169l\195\169mentaire de terre")] = totemData[string_lower("Earth Elemental Totem")], [string_lower("Totem de Force de la Terre")] = totemData[string_lower("Strength of Earth Totem")], [string_lower("Totem de r\195\169sistance au Givre")] = totemData[string_lower("Frost Resistance Totem")], [string_lower("Totem de r\195\169sistance au Feu")] = totemData[string_lower("Fire Resistance Totem")], [string_lower("Totem de Gl\195\168be")] = totemData[string_lower("Grounding Totem")], [string_lower("Totem de Gr\195\162ce a\195\169rienne")] = totemData[string_lower("Grace of Air Totem")], [string_lower("Totem de R\195\169sistance \195\160 la Nature")] = totemData[string_lower("Nature Resistance Totem")], [string_lower("Totem Furie-des-vents")] = totemData[string_lower("Windfury Totem")], [string_lower("Totem Sentinelle")] = totemData[string_lower("Sentry Totem")], [string_lower("Totem de Mur des vents")] = totemData[string_lower("Windwall Totem")], [string_lower("Totem de courroux de l'air")] = totemData[string_lower("Wrath of Air Totem")], [string_lower("Totem de S\195\169isme")] = totemData[string_lower("Tremor Totem")], [string_lower("Totem gu\195\169risseur")] = totemData[string_lower("Healing Stream Totem")], [string_lower("Totem de Purification du poison")] = totemData[string_lower("Poison Cleansing Totem")], [string_lower("Totem Fontaine de mana")] = totemData[string_lower("Mana Spring Totem")], [string_lower("Totem de Purification des maladies")] = totemData[string_lower("Disease Cleansing Totem")], [string_lower("Totem de purification")] = totemData[string_lower("Disease Cleansing Totem")], [string_lower("Totem de Vague de mana")] = totemData[string_lower("Mana Tide Totem")], [string_lower("Totem de Tranquillit\195\169 de l'air")] = totemData[string_lower("Tranquil Air Totem")], } } local function GetTotemColorDefaultOptions() local defaultDB = {} local options = { headerTotemConfig = { type = "header", name = L["Totem Config"], order = 1, }, } local indexedList = {} for k,v in pairs(totemData) do tinsert(indexedList, {name = k, id = v.id, color = v.color, texture = v.texture, enabled = v.enabled}) end table.sort(indexedList, function (a, b) return a.name < b.name end) for i=1,#indexedList do defaultDB["totem" .. indexedList[i].id] = {color = indexedList[i].color, enabled = indexedList[i].enabled, alpha = 0.6} options["totem" .. indexedList[i].id] = { order = i+1, name = "", inline = true, type = "group", args = { desc = { order = 1, name = select(1, GetSpellInfo(indexedList[i].id)), desc = format("|T%s:20|t %s", indexedList[i].texture, select(1, GetSpellInfo(indexedList[i].id))), type = "toggle", image = indexedList[i].texture, width = "full", get = function(info) return Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].enabled end, set = function(info, value) Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].enabled = value Gladdy:UpdateFrame() end }, color = { type = "color", name = L["Border color"], desc = L["Color of the border"], order = 2, hasAlpha = true, width = "0.8", get = function(info) local key = info.arg or info[#info] return Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].color.r, Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].color.g, Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].color.b, Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].color.a end, set = function(info, r, g, b, a) local key = info.arg or info[#info] Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].color.r, Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].color.g, Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].color.b, Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].color.a = r, g, b, a Gladdy:UpdateFrame() end, }, alpha = { type = "range", name = L["Alpha"], order = 3, min = 0, max = 1, step = 0.1, width = "0.8", get = function(info) return Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].alpha end, set = function(info, value) Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].alpha = value end }, customText = { type = "input", name = L["Custom totem name"], order = 4, get = function(info) return Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].customText end, set = function(info, value) Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].customText = value end }, } } end return defaultDB, options, indexedList end local function GetTotemOptions() local indexedList = select(3, GetTotemColorDefaultOptions()) local colorList = {} for i=1, #indexedList do tinsert(colorList, Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id]) end return colorList end function Gladdy:GetTotemColors() return GetTotemColorDefaultOptions() end --------------------------------------------------- -- Core --------------------------------------------------- local TotemPlates = Gladdy:NewModule("TotemPlates", nil, { npTotems = true, npTotemPlatesBorderStyle = "Interface\\AddOns\\Gladdy\\Images\\Border_rounded_blp", npTotemPlatesSize = 40, npTotemPlatesWidthFactor = 1, npTremorFont = "DorisPP", npTremorFontSize = 10, npTremorFontXOffset = 0, npTremorFontYOffset = 0, npTotemPlatesAlpha = 0.6, npTotemPlatesAlphaAlways = false, npTotemPlatesAlphaAlwaysTargeted = false, npTotemColors = select(1, GetTotemColorDefaultOptions()) }) LibStub("AceHook-3.0"):Embed(TotemPlates) LibStub("AceTimer-3.0"):Embed(TotemPlates) function TotemPlates:Initialise() self.numChildren = 0 self.knownNameplates = {} self:SetScript("OnUpdate", self.Update) self.Aloft = IsAddOnLoaded("Aloft") self.SoHighPlates = IsAddOnLoaded("SoHighPlates") self.ElvUI = IsAddOnLoaded("ElvUI") self.ShaguPlates = IsAddOnLoaded("ShaguPlates-tbc") or IsAddOnLoaded("ShaguPlates") self:RegisterEvent("PLAYER_ENTERING_WORLD") self:SetScript("OnEvent", function (self, event) if event == "PLAYER_ENTERING_WORLD" then self.numChildren = 0 self.knownNameplates = {} end end) end function TotemPlates:Reset() self:CancelAllTimers() self:UnhookAll() end --------------------------------------------------- -- Nameplate functions --------------------------------------------------- local function getName(namePlate) local name local addon local _, _, _, _, nameRegion1, nameRegion2 = namePlate:GetRegions() if TotemPlates.Aloft then if namePlate.aloftData then name = namePlate.aloftData.name addon = ALOFT end elseif TotemPlates.SoHighPlates then if namePlate.oldname or namePlate.name then name = (namePlate.oldname and namePlate.oldname:GetText()) or (namePlate.name and namePlate.name:GetText()) addon = SOHIGHPLATES end else if TotemPlates.ElvUI then if namePlate.UnitFrame then name = namePlate.UnitFrame.oldName:GetText() addon = ELVUI end end if not name then if strmatch(nameRegion1:GetText(), "%d") then name = nameRegion2:GetText() else name = nameRegion1:GetText() end addon = BLIZZ end if namePlate.PlatesFrame then addon = PLATES end end if TotemPlates.ShaguPlates then addon = SHAGUPLATES end return name, addon end local updateInterval, lastUpdate, frame, region, name, addon = .001, 0 function TotemPlates:Update(elapsed) lastUpdate = lastUpdate + elapsed if lastUpdate > updateInterval then if (WorldFrame:GetNumChildren() ~= self.numChildren) then self.numChildren = WorldFrame:GetNumChildren() for i = 1, self.numChildren do frame = select(i, WorldFrame:GetChildren()) if (frame:GetNumRegions() > 2 and frame:GetNumChildren() >= 1) then local PlatesFrame = getglobal("Plate" .. i) if PlatesFrame and PlatesFrame.frame == frame then frame.PlatesFrame = PlatesFrame end self.knownNameplates[frame] = true end end end for namePlate,_ in pairs(self.knownNameplates) do if namePlate:IsVisible() then name, addon = getName(namePlate) if name and addon then self:SkinTotem(namePlate, name, addon) end end end end end ------------ ADDON specific functions ----------------- local function nameplateSetAlpha(nameplate, alpha, addonName) if (addonName == BLIZZ) then local hpborder, cbborder, cbicon, overlay, oldname, level, bossicon, raidicon = nameplate:GetRegions() local healthBar = nameplate:GetChildren() overlay:SetAlpha(alpha) hpborder:SetAlpha(alpha) oldname:SetAlpha(alpha) level:SetAlpha(alpha) healthBar:SetAlpha(alpha) elseif (addonName == ALOFT) then local aloftData = nameplate.aloftData if alpha == 1 then if aloftData.healthBar then aloftData.healthBar:Show() end if Aloft:AcquireDBNamespace("healthText").profile.enable and aloftData.healthTextRegion then aloftData.healthTextRegion:Show() end if Aloft:AcquireDBNamespace("healthText").profile.border ~= "None" and Aloft:AcquireDBNamespace("healthText").profile.backgroundAlpha ~= 0 and aloftData.backdropFrame then aloftData.backdropFrame:Show() end if Aloft:AcquireDBNamespace("nameText").profile.enable and aloftData.nameTextRegion then aloftData.nameTextRegion:Show() end if Aloft:AcquireDBNamespace("levelText").profile.enable and aloftData.levelTextRegion then aloftData.levelTextRegion:Show() end else if aloftData.healthBar then aloftData.healthBar:Hide() end if Aloft:AcquireDBNamespace("healthText").profile.enable and aloftData.healthTextRegion then aloftData.healthTextRegion:Hide() end if Aloft:AcquireDBNamespace("healthText").profile.border ~= "None" and Aloft:AcquireDBNamespace("healthText").profile.backgroundAlpha ~= 0 and aloftData.backdropFrame then aloftData.backdropFrame:Hide() end if Aloft:AcquireDBNamespace("nameText").profile.enable and aloftData.nameTextRegion then aloftData.nameTextRegion:Hide() end if Aloft:AcquireDBNamespace("levelText").profile.enable and aloftData.levelTextRegion then aloftData.levelTextRegion:Hide() end end elseif (addonName == SOHIGHPLATES) then if nameplate.background then nameplate.background:SetAlpha(alpha) end if nameplate.container then nameplate.container:SetAlpha(alpha) end if nameplate.health then nameplate.health:SetAlpha(alpha) end if nameplate.health.percent then nameplate.health.percent:SetAlpha(alpha) end if nameplate.level then nameplate.level:SetAlpha(alpha) end if nameplate.name then nameplate.name:SetAlpha(alpha) end if nameplate.oldname then nameplate.oldname:SetAlpha(alpha) end if (alpha == 1) then __sNpCore:ConfigSetValue(nameplate) end elseif (addonName == ELVUI) then if alpha == 1 then nameplate.UnitFrame:Show() else nameplate.UnitFrame:Hide() end elseif (addonName == SHAGUPLATES) then local _,_,shaguPlate = nameplate:GetChildren() if shaguPlate then if shaguPlate.health then shaguPlate.health:SetAlpha(alpha) end if shaguPlate.name then shaguPlate.name:SetAlpha(alpha) end if shaguPlate.glow then shaguPlate.glow:SetAlpha(alpha) end if shaguPlate.level then shaguPlate.level:SetAlpha(alpha) end end elseif (addonName == PLATES) then if alpha == 1 then nameplate.PlatesFrame:Show() else nameplate.PlatesFrame:Hide() end end end local totemPlateCache = {} function TotemPlates:SkinTotem(nameplate, nameplateName, addonName) local totemName = string_gsub(nameplateName, "^%s+", "") totemName = string_gsub(totemName, "%s+$", "") totemName = string_gsub(totemName, "%s+[I,V,X]+$", "") totemName = string_lower(totemName) local totemDataEntry = totemData[totemName] or localizedTotemData["default"][totemName] or localizedTotemData["frFR"][totemName] if (addonName == BLIZZ or addonName == ALOFT or addonName == ELVUI or addonName == SOHIGHPLATES and GetCVar('_sNpTotem') ~= '1' or addonName == SHAGUPLATES and ShaguPlates_config.nameplates.totemicons ~= "1" or addonName == PLATES) and Gladdy.db.npTotems then if (totemDataEntry and Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].enabled) then nameplateSetAlpha(nameplate, 0.01, addonName) if not nameplate.gladdyTotemFrame then if #totemPlateCache > 0 then nameplate.gladdyTotemFrame = tremove(totemPlateCache, #totemPlateCache) else nameplate.gladdyTotemFrame = CreateFrame("Frame", nil) nameplate.gladdyTotemFrame.totemIcon = nameplate.gladdyTotemFrame:CreateTexture(nil, "BACKGROUND") nameplate.gladdyTotemFrame.totemBorder = nameplate.gladdyTotemFrame:CreateTexture(nil, "BORDER") nameplate.gladdyTotemFrame.totemName = nameplate.gladdyTotemFrame:CreateFontString(nil, "OVERLAY") end --Gladdy.dbi.profile.npTotemColors["totem" .. indexedList[i].id].enabledName nameplate.gladdyTotemFrame:SetFrameStrata("BACKGROUND") nameplate.gladdyTotemFrame.parent = nameplate nameplate.gladdyTotemFrame:ClearAllPoints() nameplate.gladdyTotemFrame:SetPoint("CENTER", nameplate, "CENTER", 0, 0) nameplate.gladdyTotemFrame:SetWidth(Gladdy.db.npTotemPlatesSize * Gladdy.db.npTotemPlatesWidthFactor) nameplate.gladdyTotemFrame:SetHeight(Gladdy.db.npTotemPlatesSize) nameplate.gladdyTotemFrame.totemIcon:ClearAllPoints() nameplate.gladdyTotemFrame.totemIcon:SetPoint("TOPLEFT", nameplate.gladdyTotemFrame, "TOPLEFT") nameplate.gladdyTotemFrame.totemIcon:SetPoint("BOTTOMRIGHT", nameplate.gladdyTotemFrame, "BOTTOMRIGHT") nameplate.gladdyTotemFrame.totemBorder:ClearAllPoints() nameplate.gladdyTotemFrame.totemBorder:SetPoint("TOPLEFT", nameplate.gladdyTotemFrame, "TOPLEFT") nameplate.gladdyTotemFrame.totemBorder:SetPoint("BOTTOMRIGHT", nameplate.gladdyTotemFrame, "BOTTOMRIGHT") nameplate.gladdyTotemFrame:SetScript("OnUpdate", function(self) if self.parent and not self.parent:IsVisible() then self:Hide() end end) else nameplate.gladdyTotemFrame:Show() end if (UnitExists("target") and nameplate:GetAlpha() ~= 1) then -- target exists and totem is not target nameplate:SetAlpha(Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].alpha) nameplate.gladdyTotemFrame:SetAlpha(Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].alpha) elseif (UnitExists("target") and nameplate:GetAlpha() == 1 and Gladdy.db.npTotemPlatesAlphaAlwaysTargeted) then -- target but apply alpha anyways nameplate.gladdyTotemFrame:SetAlpha(Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].alpha) elseif (UnitExists("target") and nameplate:GetAlpha() == 1) then -- target exists and totem is target -> alpha 1 nameplate.gladdyTotemFrame:SetAlpha(1) elseif (not UnitExists("target") and Gladdy.db.npTotemPlatesAlphaAlways) then -- no target and option npTotemPlatesAlphaAlways == true nameplate.gladdyTotemFrame:SetAlpha(Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].alpha) else -- no target and option npTotemPlatesAlphaAlways == false nameplate.gladdyTotemFrame:SetAlpha(0.95) end nameplate.gladdyTotemFrame:SetWidth(Gladdy.db.npTotemPlatesSize * Gladdy.db.npTotemPlatesWidthFactor) nameplate.gladdyTotemFrame:SetHeight(Gladdy.db.npTotemPlatesSize) nameplate.gladdyTotemFrame:SetFrameLevel(totemDataEntry.priority or 0) nameplate.gladdyTotemFrame.totemIcon:SetTexture(totemDataEntry.texture) nameplate.gladdyTotemFrame.totemBorder:SetTexture(Gladdy.db.npTotemPlatesBorderStyle) nameplate.gladdyTotemFrame.totemBorder:SetVertexColor(Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].color.r, Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].color.g, Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].color.b, Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].color.a) nameplate.gladdyTotemFrame.totemName:SetPoint("TOP", nameplate.gladdyTotemFrame, "BOTTOM", Gladdy.db.npTremorFontXOffset, Gladdy.db.npTremorFontYOffset) nameplate.gladdyTotemFrame.totemName:SetFont(Gladdy.LSM:Fetch("font", Gladdy.db.npTremorFont), Gladdy.db.npTremorFontSize, "OUTLINE") nameplate.gladdyTotemFrame.totemName:SetText(Gladdy.db.npTotemColors["totem" .. totemDataEntry.id].customText or "") else nameplateSetAlpha(nameplate, 1, addonName) if nameplate.gladdyTotemFrame then nameplate.gladdyTotemFrame:Hide() end end else if nameplate.gladdyTotemFrame then nameplate.gladdyTotemFrame:Hide() nameplate.gladdyTotemFrame.parent = nil tinsert(totemPlateCache, nameplate.gladdyTotemFrame) nameplate.gladdyTotemFrame = nil nameplateSetAlpha(nameplate, 1, addonName) end end end --------------------------------------------------- -- Interface options --------------------------------------------------- function TotemPlates:GetOptions() return { headerTotems = { type = "header", name = L["Totem General"], order = 2, }, npTotems = Gladdy:option({ type = "toggle", name = L["Totem icons on/off"], desc = L["Turns totem icons instead of nameplates on or off. (Requires reload)"], order = 3, }), headerTotemFrame = { type = "header", name = L["Totem Icon"], order = 4, }, npTotemPlatesSize = Gladdy:option({ type = "range", name = L["Totem size"], desc = L["Size of totem icons"], order = 5, min = 20, max = 100, step = 1, }), npTotemPlatesWidthFactor = Gladdy:option({ type = "range", name = L["Icon Width Factor"], desc = L["Stretches the icon"], order = 6, min = 0.5, max = 2, step = 0.05, }), headerFont = { type = "header", name = L["Font"], order = 10, }, npTremorFont = Gladdy:option({ type = "select", name = L["Font"], desc = L["Font of the custom totem name"], order = 11, dialogControl = "LSM30_Font", values = AceGUIWidgetLSMlists.font, }), npTremorFontSize = Gladdy:option({ type = "range", name = L["Size"], desc = L["Scale of the font"], order = 12, min = 1, max = 50, step = 0.1, }), npTremorFontXOffset = Gladdy:option({ type = "range", name = L["Horizontal offset"], desc = L["Scale of the font"], order = 13, min = -300, max = 300, step = 1, }), npTremorFontYOffset = Gladdy:option({ type = "range", name = L["Vertical offset"], desc = L["Scale of the font"], order = 14, min = -300, max = 300, step = 1, }), headerAlpha = { type = "header", name = L["Alpha"], order = 20, }, npTotemPlatesAlphaAlways = Gladdy:option({ type = "toggle", name = L["Apply alpha when no target"], desc = L["Always applies alpha, even when you don't have a target. Else it is 1."], order = 21, }), npTotemPlatesAlphaAlwaysTargeted = Gladdy:option({ type = "toggle", name = L["Apply alpha when targeted, else it is 1"], desc = L["Always applies alpha, even when you target the totem. Else it is 1."], order = 22, }), --border headerBorder = { type = "header", name = L["Border"], order = 40, }, npTotemPlatesBorderStyle = Gladdy:option({ type = "select", name = L["Totem icon border style"], order = 41, values = Gladdy:GetIconStyles() }), npAllTotemColors = { type = "color", name = L["All totem border color"], order = 42, hasAlpha = true, get = function(info) local colors = GetTotemOptions() local color = colors[1].color for i=2, #colors do if colors[i].r ~= color.r or colors[i].color.r ~= color.r or colors[i].color.r ~= color.r or colors[i].color.r ~= color.r then return 0, 0, 0, 0 end end return color.r, color.g, color.b, color.a end, set = function(info, r, g, b, a) local colors = GetTotemOptions() for i=1, #colors do colors[i].color.r = r colors[i].color.g = g colors[i].color.b = b colors[i].color.a = a end end, }, npAllTotemAlphas = { type = "range", name = L["All totem border alphas"], min = 0, max = 1, step = 0.1, order = 43, get = function(info) local alphas = GetTotemOptions() for i=2, #alphas do if alphas[i].alpha ~= alphas[1].alpha then return "" end end return alphas[1].alpha end, set = function(info, value) local alphas = GetTotemOptions() for i=1, #alphas do alphas[i].alpha = value end end, }, npTotemColors = { order = 50, name = "Customize Totems", type = "group", childGroups = "simple", args = select(2, Gladdy:GetTotemColors()) }, } end
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- modifier_hoodwink_bushwhack_lua_debuff = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_hoodwink_bushwhack_lua_debuff:IsHidden() return false end function modifier_hoodwink_bushwhack_lua_debuff:IsDebuff() return true end function modifier_hoodwink_bushwhack_lua_debuff:IsStunDebuff() return true end function modifier_hoodwink_bushwhack_lua_debuff:IsPurgable() return true end -------------------------------------------------------------------------------- -- Initializations function modifier_hoodwink_bushwhack_lua_debuff:OnCreated( kv ) self.parent = self:GetParent() -- references self.height = self:GetAbility():GetSpecialValueFor( "visual_height" ) self.rate = self:GetAbility():GetSpecialValueFor( "animation_rate" ) self.distance = 150 self.speed = 900 self.interval = 0.1 if not IsServer() then return end self.tree = EntIndexToHScript( kv.tree ) self.tree_origin = self.tree:GetOrigin() -- apply motion controller if not self:ApplyHorizontalMotionController() then -- self:Destroy() return end -- tree cut down thinker self:StartIntervalThink( self.interval ) -- Play Effects self:PlayEffects1() end function modifier_hoodwink_bushwhack_lua_debuff:OnRefresh( kv ) self:OnCreated( kv ) end function modifier_hoodwink_bushwhack_lua_debuff:OnRemoved() end function modifier_hoodwink_bushwhack_lua_debuff:OnDestroy() if not IsServer() then return end self:GetParent():RemoveHorizontalMotionController( self ) end -------------------------------------------------------------------------------- -- Modifier Effects function modifier_hoodwink_bushwhack_lua_debuff:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_FIXED_DAY_VISION, MODIFIER_PROPERTY_FIXED_NIGHT_VISION, MODIFIER_PROPERTY_OVERRIDE_ANIMATION, MODIFIER_PROPERTY_OVERRIDE_ANIMATION_RATE, MODIFIER_PROPERTY_VISUAL_Z_DELTA, } return funcs end function modifier_hoodwink_bushwhack_lua_debuff:GetFixedDayVision() return 0 end function modifier_hoodwink_bushwhack_lua_debuff:GetFixedNightVision() return 0 end function modifier_hoodwink_bushwhack_lua_debuff:GetOverrideAnimation() return ACT_DOTA_FLAIL end function modifier_hoodwink_bushwhack_lua_debuff:GetOverrideAnimationRate() return self.rate end function modifier_hoodwink_bushwhack_lua_debuff:GetVisualZDelta() return self.height end -------------------------------------------------------------------------------- -- Status Effects function modifier_hoodwink_bushwhack_lua_debuff:CheckState() local state = { [MODIFIER_STATE_STUNNED] = true, } return state end -------------------------------------------------------------------------------- -- Interval Effects function modifier_hoodwink_bushwhack_lua_debuff:OnIntervalThink() -- check if the tree is still standing if not self.tree.IsStanding then -- temp tree if self.tree:IsNull() then self:Destroy() end elseif not self.tree:IsStanding() then -- temp tree self:Destroy() end end -------------------------------------------------------------------------------- -- Motion Effects function modifier_hoodwink_bushwhack_lua_debuff:UpdateHorizontalMotion( me, dt ) -- get data local origin = me:GetOrigin() local dir = self.tree_origin-origin local dist = dir:Length2D() dir.z = 0 dir = dir:Normalized() -- check if close if dist<self.distance then self:GetParent():RemoveHorizontalMotionController( self ) self:PlayEffects2( dir ) return end -- move closer to tree local target = dir * self.speed*dt me:SetOrigin( origin + target ) end function modifier_hoodwink_bushwhack_lua_debuff:OnHorizontalMotionInterrupted() self:GetParent():RemoveHorizontalMotionController( self ) end -------------------------------------------------------------------------------- -- Graphics & Animations function modifier_hoodwink_bushwhack_lua_debuff:PlayEffects1() -- Get Resources local particle_cast = "particles/units/heroes/hero_hoodwink/hoodwink_bushwhack_target.vpcf" local sound_cast = "Hero_Hoodwink.Bushwhack.Target" -- Get Data -- Create Particle local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self.parent ) ParticleManager:SetParticleControl( effect_cast, 15, self.tree_origin ) -- buff particle self:AddParticle( effect_cast, false, -- bDestroyImmediately false, -- bStatusEffect -1, -- iPriority false, -- bHeroEffect false -- bOverheadEffect ) -- Create Sound EmitSoundOn( sound_cast, self.parent ) end function modifier_hoodwink_bushwhack_lua_debuff:PlayEffects2( dir ) -- Get Resources local particle_cast = "particles/tree_fx/tree_simple_explosion.vpcf" -- Create Particle local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_WORLDORIGIN, nil ) ParticleManager:SetParticleControl( effect_cast, 0, self.parent:GetOrigin() ) ParticleManager:ReleaseParticleIndex( effect_cast ) end
------------------------------------------------------------------------------- -- -- tek.ui.class.application -- Written by Timm S. Mueller <tmueller at schulze-mueller.de> -- See copyright notice in COPYRIGHT -- -- OVERVIEW:: -- [[#ClassOverview]] : -- [[#tek.class : Class]] / -- [[#tek.ui.class.family : Family]] / -- Application ${subclasses(Application)} -- -- This class implements tekUI's application, entrypoint and main loop. -- -- EXAMPLE:: -- A tekUI application can be written in a single, nested expression: -- local ui = require "tek.ui" -- ui.Application:new { -- Children = { -- ui.Window:new { -- Children = { -- ui.Button:new { Text = "Hello World" } -- } -- } -- } -- }:run() -- -- MEMBERS:: -- - {{ApplicationId [IG]}} (string) -- Name of the application, normally used as an unique identifier -- in combination with the {{Domain}} attribute. Default is -- {{"unknown"}}. -- - {{Author [IG]}} (string) -- Names of the application's authors. Default: {{"unknown"}} -- - {{AuthorStyles [IG]}} (string) -- A string containing style sheet notation, overlaying all other -- properties, including those retrieved using the -- {{AuthorStyleSheets}} attribute. -- - {{AuthorStyleSheets [IG]}} (string) -- A string containing the names of author style sheet files -- overlaying user agent and theme declaration. Multiple style -- sheets are separated by spaces. The last style sheet has the -- highest precedence, e.g. {{"desktop texture"}} would load the -- style sheets {{desktop.css}} and {{texture.css}}. -- - {{Copyright [IG]}} (string) -- Copyright notice applying to the application, default -- {{"unknown"}} -- - {{Display [IG]}} ([[#tek.ui.class.display : Display]]) -- An initial [[#tek.ui.class.display : Display]]. By default, the -- application creates a new one during Application.new(). -- - {{Domain [IG]}} (string) -- An uniquely identifying domain name of the vendor, organization -- or author manufacturing the application (preferrably without -- domain parts like {{"www."}} if they are not significant for -- identification). Default is {{"unknown"}}. -- - {{GCControl [IG]}} (boolean or string) -- The application can perform a garbage collection of the specified -- type directly before getting suspended waiting for input. If set -- to '''false''', no explicit garbage collection is initiated. If -- the value is '''true''' or {{"step"}}, the application performs a -- single garbage collection step. Other values (e.g. {{"collect"}}) -- are passed unmodified to {{collectgarbage()}}. Default: '''true''' -- - {{ProgramName [IG]}} (string) -- Name of the application, as displayed to the user. This is -- also the fallback for the {{Title}} attribute in windows. -- If unset, the default will be {{"tekUI"}}. -- - {{Status [G]}} (string) -- Status of the application, can be {{"init"}}, {{"error"}}, -- {{"run"}}, {{"quit"}}. -- - {{Vendor [IG]}} (string) -- Name of the vendor or organization responsible for producing -- the application, as displayed to the user. Default {{"unknown"}}. -- -- NOTES:: -- The {{Domain}} and {{ApplicationId}} attributes are -- UTF-8 encoded strings, so any international character sequence is -- valid for them. Anyhow, it is recommended to avoid too adventurous -- symbolism, as its end up in a hardly decipherable, UTF-8 plus -- URL-encoded form in the file system, e.g. for loading catalog files -- from {{tek/ui/locale/<domain>/<applicationid>}}. -- -- IMPLEMENTS:: -- - Application:addCoroutine() - Adds a coroutine to the application -- - Application:addInputHandler() - Adds input handler to the application -- - Application:connect() - Connects children recursively -- - Application:easyRequest() - Opens a message box -- - Application:getById() - Returns an element by Id -- - Application:getChildren() - Returns the application's children -- - Application:getGroup() - Returns the application's group -- - Application:getLocale() - Returns a locale for the application -- - Application:quit() - Quits the application -- - Application:remInputHandler() - Removes a registered input handler -- - Application:requestFile() - Opens a file requester -- - Application:run() - Runs the application -- - Application:suspend() - Suspends the caller's coroutine -- - Application:up() - Function called when the application is up -- -- OVERRIDES:: -- - Family:addMember() -- - Class.new() -- - Family:remMember() -- ------------------------------------------------------------------------------- local db = require "tek.lib.debug" local ui = require "tek.ui".checkVersion(109) local Display = ui.require("display", 31) local Family = ui.require("family", 2) local assert = assert local band = ui.band local cocreate = coroutine.create local collectgarbage = collectgarbage local coresume = coroutine.resume local corunning = coroutine.running local costatus = coroutine.status local coyield = coroutine.yield local floor = math.floor local getmsg = Display.getMsg local insert = table.insert local io_open = io.open local max = math.max local min = math.min local pairs = pairs local remove = table.remove local select = select local traceback = debug.traceback local type = type local unpack = unpack or table.unpack local wait = Display.wait module("tek.ui.class.application", tek.ui.class.family) _VERSION = "Application 41.3" local Application = _M Family:newClass(Application) ------------------------------------------------------------------------------- -- Constants & Class data: ------------------------------------------------------------------------------- local MSG_USER = ui.MSG_USER local MSGTYPES = { MSG_USER } ------------------------------------------------------------------------------- -- new: overrides ------------------------------------------------------------------------------- function Application.new(class, self) self = self or { } self.MouseX = 0 -- absolute mouse position self.MouseY = 0 self.Application = self self.ApplicationId = self.ApplicationId or "unknown" self.Author = self.Author or "unknown" self.Clipboard = self.Clipboard or { } self.Copyright = self.Copyright or "unknown" self.Coroutines = { } self.Display = self.Display or false self.Domain = self.Domain or "unknown" self.ElementById = { } self.FocusWindow = false local t = self.GCControl if t == nil or t == true then self.GCControl = "step" end self.InputHandlers = { [MSG_USER] = { } } self.LastKey = false self.ModalWindows = { } -- stack of self.MsgDispatch = false self.OpenWindows = { } if self.Preload then ui.require("group", 22) ui.require("text", 20) ui.require("window", 22) ui.require("dirlist", 14) end self.ProgramName = self.ProgramName or self.Title or "tekUI" self.Status = "init" Application.initStylesheets(self) self = Family.new(class, self) self.MsgDispatch = { [ui.MSG_CLOSE] = self.passMsgNoModal, [ui.MSG_FOCUS] = self.passMsgAlways, [ui.MSG_NEWSIZE] = self.passMsgNewSize, [ui.MSG_REFRESH] = self.passMsgRefresh, [ui.MSG_MOUSEOVER] = self.passMsgNoModal, [ui.MSG_KEYDOWN] = self.passMsgNoModal, [ui.MSG_MOUSEMOVE] = self.passMsgMouseMove, [ui.MSG_MOUSEBUTTON] = self.passMsgNoModal, [ui.MSG_INTERVAL] = self.passMsgInterval, [ui.MSG_KEYUP] = self.passMsgNoModal, [ui.MSG_REQSELECTION] = self.passMsgNoModal, [MSG_USER] = self.passMsg, } -- Check linkage of members, connect and setup them recursively: if self:connect() then local d = self.Display if not d then d = Display:new() self.Display = d end d:decodeProperties(self.Properties) self:decodeProperties() self:setup() else db.error("Could not connect elements") self.Status = "error" end self:addInputHandler(MSG_USER, self, self.handleInput) return self end ------------------------------------------------------------------------------- -- initStyleSheets ------------------------------------------------------------------------------- function Application.initStylesheets(self, filename) local props = { [0] = { } } self.Properties = props local authorstyles = self.AuthorStyles or false self.AuthorStyles = authorstyles local authorstylesheets = self.AuthorStyleSheets or false self.AuthorStyleSheets = authorstylesheets self.Vendor = self.Vendor or "unknown" -- load 'user agent' stylesheets: -- ensures that "minimal" is the first stylesheet. -- always uses "default" as the second stylesheet, unless the user -- explicitely provides "minimal" as the first stylesheet. local stylesheets = { } if filename then local s local msg = "open failed" local f = io_open(filename) if f then s, msg = ui.loadStyleSheet(f) end if s then insert(stylesheets, s) else db.warn("failed to load/decode user stylesheet: %s", msg) end else ui.ThemeName:gsub("%S+", function(name) if name ~= "user" then insert(stylesheets, name) end end) end if stylesheets[1] ~= "minimal" then insert(stylesheets, 1, "minimal") if stylesheets[2] ~= "default" then insert(stylesheets, 2, "default") end end for i = 1, #stylesheets do local s = stylesheets[i] if type(s) ~= "table" then local msg s, msg = ui.getStyleSheet(stylesheets[i]) if not s then db.warn("failed to load/decode user stylesheet: %s", msg) end end if s then insert(props, 1, s) end end -- 'author' stylsheet(s): if authorstylesheets then authorstylesheets:gsub("%S+", function(theme) local s, msg = ui.loadStyleSheet(theme) if s then insert(props, 1, s) else db.warn("failed to decode author stylesheet: %s", msg) end end) end if authorstyles then local offs = 0 local s, msg = ui.loadStyleSheet { read = function() if offs then local old = offs offs = authorstyles:find("\n", offs + 1, true) return authorstyles:sub(old + 1, offs and offs - 1) end end } if s then insert(props, 1, s) else db.warn("failed to decode author stylesheet: %s", msg) end end -- 'user' stylesheet: local s, msg = ui.loadStyleSheet("user") if s then insert(props, 1, s) else db.info("failed to decode user stylesheet: %s", msg) end end ------------------------------------------------------------------------------- -- connect(parent): Checks member linkage and connects all children by -- invoking their [[connect()][#Element:connect]] methods. Note that -- unlike Element:connect(), this function is recursive. ------------------------------------------------------------------------------- function Application:connect(parent) local c = self:getChildren("init") if c then for i = 1, #c do local child = c[i] if child:getGroup() == child then -- descend into group: if not Application.connect(child, self) then return false end else if not child:connect(self, parent) then db.error("Connection failed: %s <- %s", self:getClassName(), child:getClassName()) return false end end end if parent then return self:connect(parent) end return true else db.trace("%s : has no children", self:getClassName()) end end ------------------------------------------------------------------------------- -- addMember: overrides ------------------------------------------------------------------------------- function Application:addMember(child, pos) -- connect recursively: self.connect(child, self) self:decodeProperties(child) child:setup(self, child) if Family.addMember(self, child, pos) then return child end end ------------------------------------------------------------------------------- -- remMember: overrides ------------------------------------------------------------------------------- function Application:remMember(window) if window.Drawable then window:hide() end Family.remMember(self, window) window:cleanup() end ------------------------------------------------------------------------------- -- addElement: ------------------------------------------------------------------------------- function Application:addElement(e) assert(not self.ElementById[e.Id], ("Id '%s' already exists"):format(e.Id)) self.ElementById[e.Id] = e end ------------------------------------------------------------------------------- -- remElement: ------------------------------------------------------------------------------- function Application:remElement(e) assert(self.ElementById[e.Id]) self.ElementById[e.Id] = nil end ------------------------------------------------------------------------------- -- element = getById(id): Returns the element that was registered with the -- Application under its unique {{id}}. Returns '''nil''' if the id was not -- found. ------------------------------------------------------------------------------- function Application:getById(id) return self.ElementById[id] end ------------------------------------------------------------------------------- -- decodeProperties: ------------------------------------------------------------------------------- function Application:decodeProperties(child) local props = self.Properties if child then child:decodeProperties(props) else local c = self.Children for i = 1, #c do c[i]:decodeProperties(props) end end end ------------------------------------------------------------------------------- -- setup: internal ------------------------------------------------------------------------------- function Application:setup() local c = self.Children for i = 1, #c do c[i]:setup(self, c[i]) end end ------------------------------------------------------------------------------- -- cleanup: internal ------------------------------------------------------------------------------- function Application:cleanup() local c = self.Children for i = 1, #c do c[i]:cleanup() end end ------------------------------------------------------------------------------- -- show: internal ------------------------------------------------------------------------------- function Application:show() local c = self.Children for i = 1, #c do local w = c[i] if w.Status ~= "hide" then c[i]:show() end end end ------------------------------------------------------------------------------- -- hide: internal ------------------------------------------------------------------------------- local function dohide(self, ...) for i = 1, select('#', ...) do local e = select(i, ...) if e:checkFlags(ui.FL_SHOW) then select(i, ...):hide() end end end function Application:hide() dohide(self, unpack(self.Children)) self:remInputHandler(MSG_USER, self, self.handleInput) end ------------------------------------------------------------------------------- -- openWindow: internal ------------------------------------------------------------------------------- function Application:openWindow(window) if window.Modal then insert(self.ModalWindows, 1, window) end insert(self.OpenWindows, window) end ------------------------------------------------------------------------------- -- setFocusWindow: internal ------------------------------------------------------------------------------- function Application:setFocusWindow(window, has_focus) if not has_focus and window == self.FocusWindow then self.FocusWindow = false elseif has_focus and window ~= self.FocusWindow then self.FocusWindow = window end end ------------------------------------------------------------------------------- -- closeWindow: internal ------------------------------------------------------------------------------- function Application:closeWindow(window) self:setFocusWindow(window, false) if window == self.ModalWindows[1] then remove(self.ModalWindows, 1) end -- NOTE: windows are purged from OpenWindows list during wait() end ------------------------------------------------------------------------------- -- quit(): Quits the application. ------------------------------------------------------------------------------- function Application:quit() self:hide() end ------------------------------------------------------------------------------- -- getModalWindow: ------------------------------------------------------------------------------- function Application:getModalWindow() return self.ModalWindows[1] end ------------------------------------------------------------------------------- -- Message handlers: passAlways() passes a message always, passMsgNoModal() -- passes a message only to the modal window (if there is one), -- passMsgNewSize() bundles new sizes, passMsgRefresh() bundles damages for -- the current window. ------------------------------------------------------------------------------- function Application:passMsgAlways(msg) msg[-1]:passMsg(msg) end function Application:passMsgNoModal(msg) local win = msg[-1] local mw = self.ModalWindows[1] if not mw or mw == win then win:passMsg(msg) end end function Application:passMsgNewSize(msg) local win = msg[-1] -- bundle newsizes: local newsize = win.NewSizeMsg if not newsize then newsize = win.NewSizeMsgStore win.NewSizeMsg = newsize else end newsize[0] = msg[0] -- update timestamp newsize[1] = msg[1] end function Application:passMsgRefresh(msg) local win = msg[-1] -- bundle damage rects: local refresh = win.RefreshMsg if not refresh then refresh = win.RefreshMsgStore win.RefreshMsg = refresh refresh[7] = msg[7] refresh[8] = msg[8] refresh[9] = msg[9] refresh[10] = msg[10] else -- bundle damage rect: refresh[7] = min(refresh[7], msg[7]) refresh[8] = min(refresh[8], msg[8]) refresh[9] = max(refresh[9], msg[9]) refresh[10] = max(refresh[10], msg[10]) end refresh[0] = msg[0] -- update timestamp refresh[1] = msg[1] end function Application:passMsgMouseMove(msg) local win = msg[-1] local mw = self.ModalWindows[1] if not mw or mw == win then local mpm = win.MouseMoveMsg if not mpm then mpm = win.MouseMoveMsgStore win.MouseMoveMsg = mpm end win.MouseX = msg[4] win.MouseY = msg[5] self.MouseX = msg[11] self.MouseY = msg[12] mpm[4] = msg[4] mpm[5] = msg[5] mpm[0] = msg[0] -- update timestamp mpm[1] = msg[1] end end function Application:passMsgInterval(msg) local win = msg[-1] local im = win.IntervalMsg if not im then im = win.IntervalMsgStore win.IntervalMsg = im end im[0] = msg[0] -- update timestamp im[1] = msg[1] end ------------------------------------------------------------------------------- -- success, status = run(): Runs the application. Returns when all child -- windows are closed or when the application's {{Status}} is set to "quit". ------------------------------------------------------------------------------- function Application:run() local gcarg = self.GCControl -- open all windows that aren't in "hide" state: self:show() self.Status = "run" local d = self.Display local ow = self.OpenWindows local wmsg = { } -- window message local msgdispatch = self.MsgDispatch self:up() -- the main loop: while self.Status == "run" do -- dispatch input messages: local msg = getmsg() while msg do msgdispatch[msg[2]](self, msg) msg:reply() msg = getmsg() end if #ow == 0 then self.Status = "quit" break end -- process geometry-altering messages first: for i = 1, #ow do local win = ow[i] if win.NewSizeMsg then win:passMsg(win.NewSizeMsg) win.NewSizeMsg = false win:update() end end -- process remaining messages for all open windows: for i = 1, #ow do local win = ow[i] -- dispatch user-generated window messages: while win:getMsg(wmsg) do msgdispatch[wmsg[2]](self, wmsg) end -- spool out bundled refreshes, mousemoves, intervals: if win.RefreshMsg then win:passMsg(win.RefreshMsg) win.RefreshMsg = false end if win.MouseMoveMsg then win:passMsg(win.MouseMoveMsg) win.MouseMoveMsg = false end if win.IntervalMsg then win:passMsg(win.IntervalMsg) win.IntervalMsg = false end -- general update: win:update() end -- service coroutines; idle means they are all suspended: local idle = self:serviceCoroutines() -- purge windows from list that may have gone to hidden state: for i = #ow, 1, -1 do if ow[i].Status ~= "show" then remove(ow, i) end end -- wait if no coroutines are running, and windows are open: if idle and #ow > 0 then if gcarg then collectgarbage(gcarg) end wait() end end self:hide() return true, self.Status end ------------------------------------------------------------------------------- -- addCoroutine(function, arg1, ...): Adds the specified function -- and arguments to the application as a new coroutine, and returns to the -- caller. The new coroutine is not started immediately, but scheduled for -- later execution during the application's update procedure. This gives the -- application an opportunity to service all pending messages and updates -- before the coroutine is actually started. ------------------------------------------------------------------------------- function Application:addCoroutine(func, ...) local arg = { ... } insert(self.Coroutines, { cocreate(function() func(unpack(arg)) end) } ) end ------------------------------------------------------------------------------- -- idle = serviceCoroutines() - internal ------------------------------------------------------------------------------- function Application:serviceCoroutines() local crt = self.Coroutines local c = remove(crt, 1) if c then local success, res = coresume(c[1]) local s = costatus(c[1]) if s == "suspended" then c[2] = res or false -- extra argument from yield insert(crt, c) else if success then db.info("Coroutine finished successfully") else db.error("Error in coroutine:\n%s\n%s", res, traceback(c[1])) end end end for i = 1, #crt do local c = crt[i] if not c[2] then return false -- a coroutine is running end end return true -- all coroutines are idle end ------------------------------------------------------------------------------- -- suspend([window]): Suspends the caller (which must be running -- in a coroutine) until it is getting rescheduled by the application. -- Coroutines can use this as a cooperation point, which gives the -- application an opportunity to service all pending messages and updates. -- If no argument is given, the application returns to the caller as quickly -- as possible. If an optional {{window}} is specified, the coroutine is put -- to sleep until something happens in the application, or an interval timer -- event is present at the window (i.e. the suspended coroutine is -- rescheduled after no longer than 1/50th of a second). ------------------------------------------------------------------------------- function Application:suspend(window) if window then window:addInterval() coyield(window) window:remInterval() else coyield() end end ------------------------------------------------------------------------------- -- status[, path, selection] = requestFile(args): -- Requests a single or multiple files or directories. Possible keys in -- the {{args}} table are: -- - {{Center}} - Boolean, whether requester should be opened centered -- - {{FocusElement}} - What element to place the initial focus on; -- see [[#tek.ui.class.dirlist : DirList]] for possible values -- - {{Height}} - Height of the requester window -- - {{Lister}} - External lister object to operate on -- - {{Location}} - Initial contents of the requester's location field -- - {{OverWindow}} - Open dialogue centered over the specified window -- - {{Path}} - The initial path -- - {{SelectMode}} - {{"multi"}} or {{"single"}} [default {{"single"}}] -- - {{SelectText}} - Text to show on the select button -- [default {{"open"}}] -- - {{Title}} - Window title [default {{"Select file or directory..."}}] -- - {{Width}} - Width of the requester window -- The first return value is a string reading either {{"selected"}} or -- {{"cancelled"}}. If the status is {{"selected"}}, the second return value -- is the path where the requester was left, and the third value is a table -- of the items that were selected. -- Note: The caller of this function must be running in a coroutine -- (see Application:addCoroutine()). ------------------------------------------------------------------------------- function Application:getRequestWindow(ww, wh, overwindow) local ow = self.FocusWindow if overwindow ~= nil then ow = overwindow end local wx, wy if ow then local w, h, x, y, sw, sh = ow.Drawable:getAttrs("whxyWH") wx = x + w / 2 - ww / 2 wy = y + h / 2 - wh / 2 wx = max(wx, 0) wy = max(wy, 0) wx = min(wx, sw - ww) wy = min(wy, sh - wh) end return ww, wh, wx, wy end function Application:requestFile(args) assert(corunning(), "Must be called in a coroutine") args = args or { } local dirlist = args.Lister or ui.DirList:new { DisplayMode = args.DisplayMode or "all", BasePath = args.BasePath or "", Path = args.Path or "/", Kind = "requester", SelectMode = args.SelectMode or "single", Location = args.Location, SelectText = args.SelectText, FocusElement = args.FocusElement, } local ww = args.Width or 400 local wh = args.Height or 500 local wx, wy local center = args.Center if not center then ww, wh, wx, wy = self:getRequestWindow(ww, wh, args.OverWindow) end local window = ui.Window:new { Class = "app-dialog", Title = args.Title or dirlist.Locale.SELECT_FILE_OR_DIRECTORY, Modal = true, Width = ww, Height = wh, Left = wx, Top = wy, MinWidth = 0, MinHeight = 0, MaxWidth = "none", MaxHeight = "none", Center = center, Children = { dirlist }, HideOnEscape = true } Application.connect(window) self:addMember(window) window:setValue("Status", "show") dirlist:showDirectory() repeat self:suspend(window) -- ! if window.Status ~= "show" then -- window closed: dirlist.Status = "cancelled" end until dirlist.Status ~= "running" dirlist:abortScan() self:remMember(window) if dirlist.Status == "selected" then return dirlist.Status, dirlist.Path, dirlist.Selection end return dirlist.Status end ------------------------------------------------------------------------------- -- selected = easyRequest(title, text, buttontext1[, ...]): -- This function shows a message box or requester. {{title}} will be -- displayed as the window title; if this argument is '''false''', the -- application's {{ProgramName}} will be used for the title. {{text}} -- (which may contain line breaks) will be used as the requester's body. -- Buttons are ordered from left to right. The first button has the number 1. -- If the window is closed using the Escape key or close button, the return -- value will be {{false}}. Note: The caller of this function must be -- running in a coroutine (see Application:addCoroutine()). ------------------------------------------------------------------------------- function Application:easyRequest(title, main, ...) assert(corunning(), "Must be called in a coroutine") local result = false local buttons = { } local window local numb = select("#", ...) for i = 1, numb do local button = ui.Text:new { Class = "button", Mode = "button", KeyCode = true, Text = select(i, ...), InitialFocus = i == numb, onClick = function(self) result = i window:setValue("Status", "hide") end } insert(buttons, button) end if type(main) == "string" then main = ui.Text:new { Class = "message", Width = "fill", Text = main } end window = ui.Window:new { Class = "app-dialog", Title = title or self.ProgramName, Modal = true, Center = true, Orientation = "vertical", HideOnEscape = true, Children = { main, ui.Group:new { Width = "fill", SameSize = true, Children = buttons } }, getReqButton = function(self, nr) return buttons[nr] end, abort = function(self) window:hide() end, } Application.connect(window) self:addMember(window) local ww, wh = window:getWindowDimensions() -- assuming here that a popup's minimum size equals its real size local wx, wy ww, wh, wx, wy = self:getRequestWindow(ww, wh) window.Left = wx or false window.Top = wy or false window:setValue("Status", "show") repeat self:suspend(window) -- ! until window.Status ~= "show" self:remMember(window) return result end ------------------------------------------------------------------------------- -- getGroup(): See Area:getGroup(). ------------------------------------------------------------------------------- function Application:getGroup() end ------------------------------------------------------------------------------- -- getChildren(): See Area:getChildren(). ------------------------------------------------------------------------------- function Application:getChildren() return self.Children end ------------------------------------------------------------------------------- -- getLocale([deflang[, language]]): Returns a table of locale strings for -- {{ApplicationId}} and {{Domain}}. See ui.getLocale() for more information. ------------------------------------------------------------------------------- function Application:getLocale(deflang, lang) return ui.getLocale(self.ApplicationId, self.Domain, deflang, lang) end ------------------------------------------------------------------------------- -- addInputHandler(msgtype, object, func): Adds an {{object}} and -- {{function}} to the application's chain of handlers for input of -- the specified type. Currently, the only message type an appliction is -- able to react on is {{ui.MSG_USER}}. All other message types are specific -- to a Window. Input handlers are invoked as follows: -- message = function(object, message) -- The handler is expected to return the message, which will in turn pass -- it on to the next handler in the chain. -- See also Window:addInputHandler() for more information. ------------------------------------------------------------------------------- function Application:addInputHandler(msgtype, object, func) local flags = msgtype local hnd = { object, func } for i = 1, #MSGTYPES do local mask = MSGTYPES[i] local ih = self.InputHandlers[mask] if ih and band(flags, mask) == mask then insert(ih, 1, hnd) end end end ------------------------------------------------------------------------------- -- remInputHandler(msgtype, object, func): Removes an input handler that was -- previously registered with Application:addInputHandler(). ------------------------------------------------------------------------------- function Application:remInputHandler(msgtype, object, func) local flags = msgtype for i = 1, #MSGTYPES do local mask = MSGTYPES[i] local ih = self.InputHandlers[mask] if ih and band(flags, mask) == mask then for i = 1, #ih do local h = ih[i] if h[1] == object and h[2] == func then remove(ih, i) break end end end end end ------------------------------------------------------------------------------- -- passMsg: See Area:passMsg() ------------------------------------------------------------------------------- function Application:passMsg(msg) local handlers = { unpack(self.InputHandlers[msg[2]]) } for i = 1, #handlers do local hnd = handlers[i] msg = hnd[2](hnd[1], msg) if not msg then return false end end return msg end ------------------------------------------------------------------------------- -- handleInput: ------------------------------------------------------------------------------- local MsgHandlers = { [MSG_USER] = function(self, msg) return msg end } function Application:handleInput(msg) MsgHandlers[msg[2]](self, msg) return false end ------------------------------------------------------------------------------- -- retrig = setLastKey([newkey]): Sets {{newkey}} as the key that was last -- pressed in the application. If no new key is given, the current key is -- unset. Returns a boolean indicating whether it is the same as the -- previously registered key. ------------------------------------------------------------------------------- function Application:setLastKey(key) local oldkey = self.LastKey key = key or false self.LastKey = key return oldkey == key end ------------------------------------------------------------------------------- -- up(): This function is called when the application is fully initialized -- and about to enter its main loop. The user can overwrite it e.g. to -- add a coroutine that shows a splash screen. ------------------------------------------------------------------------------- function Application:up() end ------------------------------------------------------------------------------- -- reconfigure() ------------------------------------------------------------------------------- function Application:reconfigure() local d = self.Display d:flushCaches() d:decodeProperties(self.Properties) self:decodeProperties() local c = self.Children for i = 1, #c do c[i]:reconfigure() end end
ITEM.name = "'Eagle' Gunpowder" ITEM.description = "'Eagle' brand gunpowder with a green top." ITEM.longdesc = "Smokeless gunpowder from the 'Eagle' brand, a mid tier producer of gunpowder. Used by some technicians in the zone to reload ammunition for sale." ITEM.model = "models/illusion/eftcontainers/gpgreen.mdl" ITEM.width = 1 ITEM.height = 2 ITEM.price = 2100 ITEM.flatweight = 0.650 ITEM.img = ix.util.GetMaterial("vgui/hud/valuable/gpgreen.png")
function RunCode(code) local code, err = load(code, '@runcode') if err then print(err) return nil, err end local status, result = pcall(code) print(result) if status then return result else return nil, result end end
register_outcome{ text = "Enemy Shields", subtext = "Can you break them?", bad = true, comment = "todo", rarity = 10, apply = function() local x, y = get_player_pos() for _, entity in pairs( EntityGetInRadiusWithTag( x, y, 1024, "enemy" ) or {} ) do local x, y = EntityGetTransform( entity ) local hitbox = EntityGetFirstComponent( entity, "HitboxComponent" ) local height, width = nil, 18, 18 if hitbox then height = tonumber( ComponentGetValue( hitbox, "aabb_max_y" ) ) - tonumber( ComponentGetValue( hitbox, "aabb_min_y" ) ) width = tonumber( ComponentGetValue( hitbox, "aabb_max_x" ) ) - tonumber( ComponentGetValue( hitbox, "aabb_min_x" ) ) end local radius = math.max( height, width ) + 6 local shield = EntityLoad( "data/entities/misc/animal_energy_shield.xml", x, y ) local inherit_transform = EntityGetFirstComponent( shield, "InheritTransformComponent" ) if inherit_transform then ComponentSetValue( inherit_transform, "parent_hotspot_tag", "shield_center" ) end local emitters = EntityGetComponent( shield, "ParticleEmitterComponent" ) for _, emitter in pairs(emitters or {}) do ComponentSetValueValueRange( emitter, "area_circle_radius", radius, radius ) end local energy_shield = EntityGetFirstComponent( shield, "EnergyShieldComponent" ) ComponentSetValue( energy_shield, "radius", tostring( radius ) ) local hotspot = EntityAddComponent( entity, "HotspotComponent", { _tags="shield_center" }) ComponentSetValueVector2( hotspot, "offset", 0, -height * 0.3 ) if shield then EntityAddChild( entity, shield ) end end end, }
return {'vuelta'}
help( [[ MUSCLE stands for MUltiple Sequence Comparison by Log- Expectation. MUSCLE is claimed to achieve both better average accuracy and better speed than ClustalW2 or T-Coffee, depending on the chosen options. ]]) whatis("MUSCLE stands for MUltiple Sequence Comparison by Log- Expectation.") local version = "3.8.31" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/muscle/"..version prepend_path("PATH", base) family('muscle')
object_tangible_quest_rebel_rtp_wedge_security_terminal = object_tangible_quest_rebel_shared_rtp_wedge_security_terminal:new { } ObjectTemplates:addTemplate(object_tangible_quest_rebel_rtp_wedge_security_terminal, "object/tangible/quest/rebel/rtp_wedge_security_terminal.iff")
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0213-rc-radio-climate-parameter-update.md -- Description: -- Preconditions: -- 1) SDL got RC.GetCapabilities("availableHdChannelsAvailable" = true) for RADIO module parameter from HMI -- In case: -- 1) Mobile app sends SetInteriorVehicleData with parameter ("hdChannels" = 7) to SDL -- SDL must: -- 1) send RC.SetInteriorVehicleData request ("hdChannel" = 7) to HMI -- 2) HMI send response RC.SetInteriorVehicleData ("hdChannel" = 7, success = true, resultCode = "SUCCESS") -- 3) sends SetInteriorVehicleData response with ("hdChannel" = 7, success = true, resultCode = "SUCCESS") to Mobile --------------------------------------------------------------------------------------------------- --[[ Requiredcontaining incorrect Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Variables ]] local mType = "RADIO" local paramValues = { 0, 7 } --[[ Local Functions ]] local function requestSuccessful(pValue) function commonRC.getModuleControlData() return commonRC.cloneTable(commonRC.actualInteriorDataStateOnHMI[mType]) end commonRC.actualInteriorDataStateOnHMI[mType].radioControlData = { hdChannel = pValue } commonRC.rpcAllowed(mType, 1, "SetInteriorVehicleData") end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI", commonRC.registerAppWOPTU) runner.Step("Activate App", commonRC.activateApp) runner.Title("Test") for _, v in pairs(paramValues) do runner.Step("SetInteriorVehicleData hdChannel " .. tostring(v), requestSuccessful, { v }) end runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
--[[ Version 3.0.7 Recent Changes: 1. Now has session persistence! Just type "quarry -restore" and your turtle will pick up where it left off 2. doRefuel argument will now take fuel from inventory while it is running, instead of waiting to come back to the start 3. Will now wait for its chest to clear if the chest is full 4. Slight modifications to the refueling system 5. Added in fuelSafety argument ]] --[[ToDo: 1. Actually get the rednet send back and forth to work 3. Send basic commands from receiver program e.g. Stop 4. Improve Session Persistence. See idea on desktop ]] --Defining things _G.civilTable = {} civilTable = nil setmetatable(civilTable, {__index = _G}) setfenv(1,civilTable) -------Defaults for Arguments---------- --Arguments assignable by text x,y,z = 3,122,3 --These are just in case tonumber fails inverted = false --False goes from top down, true goes from bottom up [Default false] rednetEnabled = false --Default rednet on or off [Default false] --Arguments assignable by tArgs dropSide = "top" --Side it will eject to when full or done [Default "front"] careAboutResources = true --Will not stop mining once inventory full if false [Default true] doCheckFuel = false --Perform fuel check [Default true] doRefuel = true --Whenever it comes to start location will attempt to refuel from inventory [Default false] invCheckFreq = 10 --Will check for inventory full every <-- moved spaces [Default 10] keepOpen = 1 --How many inventory slots it will attempt to keep open at all times [Default 1] fuelSafety = "moderate" --How much fuel it will ask for: safe, moderate, and loose [Default moderate] saveFile = "Civil_Quarry_Restore" --Where it saves restore data [Default "Civil_Quarry_Restore"] doBackup = false --If it will keep backups for session persistence [Default true] --Standard number slots for fuel (you shouldn't care) fuelTable = { --Will add in this amount of fuel to requirement. safe = 1000, moderate = 200, loose = 0 } --Default 1000, 200, 0 --Standard rednet channels channels = { send = os.getComputerID() , receive = 10 , confirm = "Confirm" } local help_paragraph = [[ -DEFAULT: This will ignore all arguments and prompts and use defaults -vanilla: This will ignore all arguments except for dimensions -dim: [num] [num] [num] This sets the dimensions of the quarry -invert: [t/f] This sets whether invert is true or false -rednet: [t/f] This sets whether it will attempt to make a rednet connection -sendChannel: [num] This sets the channel the turtle will attempt to send on -receiveChannel: [num] This sets the channel the turtle will attempt to receive on -doRefuel: Changes whether or not the turtle will refuel itself with coal when fuel is low (opposite of written config) -doCheckFuel: Changes whether or not the turtle will check its fuel level before running (opposite of written config) -chest: [chest side] Changes what side turtle will output to -keepOpen: [num] How many slots of the inventory turtle will try to keep open (Will then auto-empty) -invCheckFreq: [num] How many blocks before full inventory checks -saveFile: [word] Changes where the turtle saves its backup to. -doBackup: [t/f] Whether or not the turtle will backup its current position to a file. -restore: Turtle will check for a save file. If found will ignore all other arguments. -fuelSafety: [safe/moderate/loose] How much extra fuel the turtle will request at startup Examples [1]: The minimum amount necessary to start a turtle automatically would be one of these two --------- quarry -dim 3 3 3 -invert false -rednet false --------- quarry -dim 3 3 3 -vanilla --------- or, if you actually wanted a 3x3x3 then --------- quarry -DEFAULT Examples [2]: If you wanted start a quarry that has rednet on channels 500 and 501, outputs to a chest below itself, is inverted, and has the dimesions 5x5x21, then here is what you would type: (Remember that order does not matter) ---------- quarry -receiveChannel 501 -sendChannel 500 -invert true -dim 5 5 21 -chest bottom -rednet true Examples [2] (cont.): Now, this may be very long, but it is meant for people who want to make automated quarries with the same settings every time (or with variable setting) Examples [3]: If you are playing softcore then you can do --------- quarry -doCheckFuel false --------- Followed by any other arguments Tips: You don't actually have to type out "false" or "true" if you don't want. It actaully just checks if the first letter is "t", so you (usually) don't have to put anything at all. Putting the whole word just helps with clarity Internal Config: At the top of the program, right below the changelog is a written config. Anything not specified by arguments will be taken from here. If you have a quarry setup you use a lot, you could just edit the config and then type in the following: ---------- quarry -DEFAULT ]] --Parsing help for display --[[The way the help table works: All help indexes are numbered. There is a help[i].title that contains the title, and the other lines are in help[i][1] - help[i][#help[i] ] Different lines (e.g. other than first) start with a space. As of now, the words are not wrapped, fix that later]] local help = {} local i = 0 local titlePattern = ".-%:" --Find the beginning of the line, then characters, then a ":" local textPattern = "%:.+" --Find a ":", then characters until the end of the line for a in help_paragraph:gmatch("\n?.-\n") do --Matches in between newlines local current = string.sub(a,1,-2).."" --Concatenate Trick if string.sub(current,1,1) ~= " " then i = i + 1 help[i] = {} help[i].title = string.sub(string.match(current, titlePattern),1,-2).."" help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1) elseif string.sub(current,1,1) == " " then table.insert(help[i], string.sub(current,2, -1).."") end end local supportsRednet = (peripheral.wrap("right") ~= nil) local tArgs = {...} --You don't care about these xPos,yPos,zPos,facing,percent,mined,moved,relxPos, rowCheck, connected, isInPath, layersDone = 0, 1, 1, 0, 0, 0, 0, 1, "right", false, true, 1 local totals = {cobble = 0, fuel = 0, other = 0} -- Total for display (cannot go inside function) local function count() --Done any time inventory dropped and at end slot = {} --1: Cobble 2: Fuel 3:Other for i=1, 16 do --[1] is type, [2] is number slot[i] = {} slot[i][2] = turtle.getItemCount(i) end slot[1][1] = 1 -- = Assumes Cobble/Main for i=1, 16 do --Cobble Check turtle.select(i) if turtle.compareTo(1) then slot[i][1] = 1 totals.cobble = totals.cobble + slot[i][2] elseif turtle.refuel(0) then slot[i][1] = 2 totals.fuel = totals.fuel + slot[i][2] else slot[i][1] = 3 totals.other = totals.other + slot[i][2] end end turtle.select(1) end local function checkFuel() return turtle.getFuelLevel() end local function isFull(slots) slots = slots or 16 local numUsed = 0 sleep(0.5) for i=1, slots do if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end end if numUsed >= slots then return true end return false end ----------------------------------------------------------------- --Input Phase local function screen(xPos,yPos) xPos, yPos = xPos or 1, yPos or 1 term.setCursorPos(xPos,yPos) term.clear() end local function screenLine(xPos,yPos) term.setCursorPos(xPos,yPos) term.clearLine() end screen(1,1) print("----- Welcome to Quarry! -----") print("") local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"} --Used to whitelist sides local errorT = {num = "Numbers not recognized", zero = "Variable is out of range", word = "String failed assertion" } local changedT = {} changedT.new = function(key, value) changedT[#changedT+1] = {[key] = value} end changedT.getPair = function(i) for a, b in pairs(changedT[i]) do return a, b end end local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end local function assert(condition, message, section) section = section or "[Blank]" if condition then return condition else error("Error: "..message.."\nin section "..section, 0) end end local function checkNum(number, section) return assert(tonumber(number),errorT.num, section) end tArgs.checkStart = function(num) tArgs[tArgs[num]] = num end for i=1, #tArgs do tArgs.checkStart(i) end if tArgs["help"] or tArgs["-help"] or tArgs["-?"] then print("You have selected help, press any key to continue") print("Use arrow keys to naviate, q to quit") os.pullEvent("key") local pos = 1 local key = 0 while pos <= #help and key ~= keys.q do if pos < 1 then pos = 1 end screen(1,1) print(help[pos].title) for a=1, #help[pos] do print(help[pos][a]) end repeat _, key = os.pullEvent("key") until key == 200 or key == 208 or key == keys.q if key == 200 then pos = pos - 1 end if key == 208 then pos = pos + 1 end end error("",0) end --Saving if tArgs["doBackup"] then doBackup = (string.lower(string.sub(tArgs[tArgs["doBackup"]+1],1,1)) ~= "f") end if tArgs["saveFile"] then saveFile = tArgs[tArgs["saveFile"]+1] or saveFile end local restoreFound = false if tArgs["-restore"] then restoreFound = fs.exists(saveFile) if restoreFound then os.run(getfenv(1),saveFile) print("Restore File read successfully. Starting in 3") sleep(3) end end if not (tArgs["-DEFAULT"] or restoreFound) then local section = "Dimensions" --Dimesnions if tArgs["-dim"] then local num = tArgs["-dim"] x = checkNum(tArgs[num + 1],section) z = checkNum(tArgs[num + 2],section) y = checkNum(tArgs[num + 3],section) else print("What dimensions?") print("") --This will protect from negatives, letters, and decimals term.write("Length: ") x = math.floor(math.abs(tonumber(io.read()) or x)) term.write("Width: ") z = math.floor(math.abs(tonumber(io.read()) or z)) term.write("Height: ") y = math.floor(math.abs(tonumber(io.read()) or y)) end changedT.new("x",x) changedT.new("z",z) changedT.new("y",y) assert(x~=0, errorT.zero, section) assert(z~=0, errorT.zero, section) assert(y~=0, errorT.zero, section) assert(not(x == 1 and y == 1 and z == 1) ,"1, 1, 1 dosen't work well at all, try again", section) if not tArgs["-vanilla"] then --Invert if tArgs["-invert"] then inverted = (string.lower(string.sub(tArgs[tArgs["-invert"]+1] or "",1,1)) == "t") else term.write("Inverted? ") inverted = (string.lower(string.sub(io.read(),1,1)) == "y") end changedT.new("Inverted", inverted) --Rednet if supportsRednet then if tArgs["-rednet"] then rednetEnabled = (string.lower(string.sub(tArgs[tArgs["-rednet"]+1] or "",1,1)) == "t") else term.write("Rednet? ") rednetEnabled = (string.lower(string.sub(io.read(),1,1)) == "y") end changedT.new("Rednet Enabled", rednetEnabled) if tArgs["-sendChannel"] then channels.send = assert(tonumber(tArgs[tArgs["-sendChannel"]+1]), errorT.num) assert(channels.send > 0 and channels.send < 65535, errorT.zero) changedT.new("Send Channel",channels.send ) end if tArgs["-receiveChannel"] then channels.receive = assert(tonumber(tArgs[tArgs["-receiveChannel"]+1]), errorT.num) assert(channels.receive > 0 and channels.receive < 65535 and channels.receive ~= channels.send , errorT.zero) changedT.new("Receive Channel",channels.receive) end end --Fuel if tArgs["-doRefuel"] then doRefuel = not doRefuel changedT.new("Do Refuel",doRefuel) end if tArgs["-doCheckFuel"] then doCheckFuel = (string.lower(string.sub(tArgs[tArgs["-doCheckFuel"]+1] or "",1,1)) == "t") changedT.new("Do Check Fuel", doCheckFuel) end if tArgs["-chest"] then dropSide = sides[tArgs[tArgs["-chest"]+1]] or dropSide changedT.new("Chest Side",dropSide) end if tArgs["-fuelSafety"] then local loc = tArgs[tArgs["-fuelSafety"]+1] if fuelTable[loc] then fuelSafety = loc changedT.new("Fuel Check Safety", fuelSafety) end end --Misc if tArgs["-invCheckFreq"] then invCheckFreq = math.abs(math.floor(checkNum(tArgs[tArgs["-invCheckFreq"]+1],"Inventory Check Frequency"))) changedT.new("Inventory Check Frequency",invCheckFreq) end assert(invCheckFreq ~= 0, errorT.zero, "Inventory Check Frequency") if tArgs["-keepOpen"] then keepOpen = math.abs(math.floor(checkNum(tArgs[tArgs["-keepOpen"]+1],"Open Slots"))) changedT.new("Slots to keep open", keepOpen) end assert(keepOpen ~= 0 and keepOpen < 16, errorT.zero, "Open Slots") if tArgs["-ignoreResources"] then careAboutResources = false changedT.new("Ignore Resources?", not careAboutResources) end if tArgs["-saveFile"] then saveFile = tArgs[tArgs["-saveFile"]+1] changedT.new("Save File", saveFile) end assert(#saveFile >= 2,errorT.word, "Save File") end end --First end is for vanilla, second is for DEFAULT local function saveProgress() --Session persistence local file = fs.open(saveFile,"w") for a,b in pairs(getfenv(1)) do if type(b) == "string" then b = "\""..b.."\"" end if type(b) == "table" and a~="modem" then b = textutils.serialize(b) end if type(b) ~= "function" then file.write(a.." = "..tostring(b).."\n") end end file.write("doCheckFuel = false\n") local a = 1 if facing == 2 then a = -1 end file.write("xPos = "..xPos+a) file.close() end local area = x*z local volume = x*y*z local lastHeight = y%3 local dispY = y y = math.floor(y/3)*3 local yMult = y/3 + math.ceil(lastHeight/2) local moveVolumeCalc = ((area+x+z)*yMult) + (2 * dispY) local moveVolume = (area * yMult) --Getting Fuel if doCheckFuel then --Calculating Needed Fuel local neededFuel = moveVolume + (math.floor(volume / (64 * 8)) * (x+dispY+z)) --Standard move plus dropping off supplies --How many times come back to start| * If it were at the very far side neededFuel = neededFuel + fuelTable[fuelSafety] if neededFuel < 100 then neededFuel = 100 end if checkFuel() < neededFuel then screen(1,1) print("More Fuel Needed") print("Current Fuel: ",checkFuel()," Needed: ",neededFuel) print("Place fuel in Bottom Right") while turtle.getItemCount(16) == 0 do sleep(1) end turtle.select(16) while checkFuel() < neededFuel do if not turtle.refuel(1) then term.clearLine() print("Still too little fuel") term.clearLine() print("Insert more fuel to resume") while turtle.getItemCount(16) == 0 do sleep(1) end end local x,y = term.getCursorPos() print(checkFuel().." Fuel") term.setCursorPos(x,y) end print(checkFuel().." Units of Fuel") sleep(3) turtle.select(1) end end --Initial Rednet Handshake if rednetEnabled then screen(1,1) print("Rednet is Enabled") print("The Channel to open is "..channels.send ) modem = peripheral.wrap("right") modem.open(channels.receive) local i = 0 repeat local id = os.startTimer(3) i=i+1 print("Sending Initial Message "..i) modem.transmit(channels.send , channels.receive, "{ 'Initial' }") local message repeat local event, idCheck, channel,_,locMessage, distance = os.pullEvent() message = locMessage until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and message == channels.confirm) until message == channels.confirm connected = true print("Connection Confirmed!") sleep(1.5) end local function biometrics(sendChannel) local commands = { Confirm = "Confirm" } local tosend = { ["x"] = x, ["y"] = (y/3 + math.ceil(lastHeight/2)), ["z"] = z, --The y calc is weird... ["xPos"] = xPos, ["yPos"] = yPos, ["zPos"] = zPos, ["percent"] = percent, ["mined" ]= mined, ["fuel"] = checkFuel(), ["moved"] = moved, ["remainingBlocks"] = (volume-mined), ["ID"] = os.getComputerID(), ["isInPath"] = isInPath, --Whether it is going back to start ["volume"] = volume, ["area"] = area} modem.transmit(channels.send , channels.receive, textutils.serialize(tosend )) id = os.startTimer(0.1) local event, message repeat local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent() event, message = locEvent, locMessage until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive) if event == "modem_message" then connected = true else connected = false end --Stuff to do for different commands end --Showing changes to settings screen(1,1) print("Your selected settings:") if #changedT == 0 then print("Completely Default") else for i=1, #changedT do local title, value = changedT.getPair(i) print(capitalize(title)..": ",value) end end print("\nStarting in 3") sleep(1) print("2") sleep(1) print("1") sleep(1.5) ---------------------------------------------------------------- --Mining Phase local function display() screen(1,1) print("Total Blocks Mined: "..mined) print("Current Fuel Level: "..turtle.getFuelLevel()) print("Cobble: "..totals.cobble) print("Usable Fuel: "..totals.fuel) print("Other: "..totals.other) if rednetEnabled then print("") print("Sent Stop Message") finalTable = {{["Mined: "] = mined}, {["Cobble: "] = totals.cobble}, {["Fuel: "] = totals.fuel}, {["Other: "] = totals.other}, {["Fuel: "] = checkFuel()} } modem.transmit(channels.send ,channels.receive,"stop") modem.transmit(channels.send ,channels.receive,textutils.serialize(finalTable)) modem.close(channels.receive) end end local function updateDisplay() --Runs in Mine(), display information to the screen in a certain place screen(1,1) print("Blocks Mined") print(mined) print("Percent Complete") print(percent.."%") print("Fuel") print(checkFuel()) if rednetEnabled then screenLine(1,7) print("Connected: "..tostring(connected)) end end local function mine(digDown, digUp, outOfPath,doCheckInv) -- Basic Move Forward if doCheckInv == nil then doCheckInv = true end if digDown == nil then digDown = true end if digUp == nil then digUp = true end if doRefuel and checkFuel() < 100 then for i=1, 16 do if turtle.getItemCount(i) > 0 then turtle.select(i) if checkFuel() < 200 + fuelTable[fuelSafety] then turtle.refuel() end end end end saveProgress() --Move this to after the move. Then it will have done everything already, don't forget --to modify saveProgress to reflect the change. local count = 0 while not turtle.forward() do count = count + 1 if turtle.dig() then mined = mined + 1 else turtle.attack() end if count > 20 then if turtle.getFuelLevel() > 0 then bedrock() else error("No Fuel",0) end end end if facing == 0 then xPos = xPos +1 elseif facing == 2 then xPos = xPos-1 elseif facing == 1 then zPos = zPos+1 elseif facing == 3 then zPos = zPos-1 end if digUp then local count = 0 while turtle.detectUp() do count = count + 1 if turtle.digUp() then mined = mined + 1 end if count > 20 then bedrock() end end end if digDown then if turtle.digDown() then mined = mined + 1 end end percent = math.ceil(moved/moveVolume*100) if rowCheck == "right" then relxPos = xPos else relxPos = (x-xPos)+1 end --Maybe adjust this for out of path updateDisplay() if outOfPath then isInPath = false else isInPath = true moved = moved + 1 end if doCheckInv and careAboutResources then if moved%invCheckFreq == 0 then if isFull(16-keepOpen) then dropOff() end end end if rednetEnabled then biometrics() end end --Direction: Front = 0, Right = 1, Back = 2, Left = 3 local function facingF(num) facing = facing + num if facing > 3 then facing = 0 end if facing < 0 then facing = 3 end end if up then local temp1 = up end --Just in case another program uses this if down then local temp2 = down end function up(num, sneak) num = num or 1 sneak = sneak or 1 if inverted and sneak == 1 then down(num, -1) else for i=1, num do while not turtle.up() do while not turtle.digUp() do turtle.attackUp() sleep(0.5) end mined = mined + 1 end yPos = yPos - sneak end end end function down(num, sneak) num = num or 1 sneak = sneak or 1 if inverted and sneak == 1 then up(num, -1) else for i=1, num do local count = 0 while not turtle.down() do count = count + 1 if not turtle.digDown() then turtle.attackDown() sleep(0.2) end mined = mined+1 if count > 20 then bedrock() end end yPos = yPos + sneak end end end local function right(num) num = num or 1 for i=1, num do turtle.turnRight() facingF(1) end end local function left(num) num = num or 1 for i=1, num do turtle.turnLeft() facingF(-1) end end local function goto(x,z,y, toFace) x = x or 1 y = y or 1 z = z or 1 toFace = toFace or facing if yPos > y then while yPos~=y do up() end end if zPos > z then while facing ~= 3 do left() end elseif zPos < z then while facing ~= 1 do left() end end while zPos ~= z do mine(false,false,true,false) end if xPos> x then while facing ~= 2 do left() end elseif xPos < x then while facing ~= 0 do left() end end while xPos ~= x do mine(false,false,true,false) end if yPos < y then while yPos~=y do down() end end while facing ~= toFace do right() end saveProgress() end local function turnTo(num) num = num or 1 goto(xPos,zPos,yPos,num) end local function drop(side, final, allowSkip) turtle.digUp() turtle.select(16) turtle.placeUp(); side = sides[side] or "front" --The final number means that it will if final then final = 0 else final = 1 end --drop a whole stack at the end local allowSkip = allowSkip or (final == 0) --This will allow drop(side,t/f, rednetConnected) count() if doRefuel then for i=1, 16 do if slot[i][1] == 2 then turtle.select(i) turtle.refuel() end end turtle.select(1) end if side == "right" then turnTo(1) end if side == "left" then turnTo(3) end local whereDetect, whereDrop1, whereDropAll local _1 = slot[1][2] - final --All but one if final, all if not final if side == "top" then whereDetect = turtle.detectUp whereDrop = turtle.dropUp elseif side == "bottom" then whereDetect = turtle.detectDown whereDrop = turtle.dropDown else whereDetect = turtle.detect whereDrop = turtle.drop end local function waitDrop(val) --This will just drop, but wait if it can't val = val or 64 local try = 1 while not whereDrop(val) do print("Chest Full, Try "..try) try = try + 1 sleep(2) end end repeat local detected = whereDetect() if detected then waitDrop(_1) for i=2, 16 do if turtle.getItemCount(i) > 0 then turtle.select(i) waitDrop() end end elseif not allowSkip then print("Waiting for chest placement place a chest to continue") while not whereDetect() do sleep(1) end end until detected or allowSkip if not allowSkip then totals.cobble = totals.cobble - 1 end turtle.select(16) turtle.digUp() turtle.select(1) turnTo(0) end function dropOff() --Not local because called in mine() local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing goto(0,1,1,2) drop(dropSide,false) mine(false,false,true, false) goto(1,1,1, 0) goto(currX,currZ,currY,currFacing) end function bedrock() local origin = {x = xPos, y = yPos, z = zPos} print("Bedrock Detected") if turtle.detectUp() then print("Block Above") local var if facing == 0 then var = 2 elseif facing == 2 then var = 0 else error("Was facing left or right on bedrock") end goto(xPos,zPos,yPos,var) for i=1, relxPos do mine(true,true) end end goto(0,1,1,2) drop(dropSide, true) display() print("\nFound bedrock at these coordinates: ") print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start") error("",0) end ------------------------------------------------------------------------------------- if facing ~= 0 then if xPos > 1 then turnTo(2) else turnTo(0) end end local doDigDown, doDigUp if not inverted then doDigDown , doDigUp = (lastHeight ~= 1), false else doDigUp, doDigDown = (lastHeight ~= 1) , false end --Used in lastHeight if not restoreFound then mine(false,false, true) else if turtle.digUp() and turtle.digDown() then mined = mined + 2 end end if y ~= 0 and not restoreFound then down() end --Mining Loops turtle.select(1) while layersDone <= y do -------------Height--------- moved = moved + 1 rowCheck = "right" if rowCheck == "right" then relxPos = xPos else relxPos = (x-xPos)+1 end while zPos <= z do -------------Width---------- while relxPos < x do ------------Length--------- mine() end ---------------Length End------- if zPos ~= z then if rowCheck == "right" and zPos ~= z then --Swithcing to next row rowCheck = "left" right() mine() right() else rowCheck = "right" left() mine() left() end else break end end ---------------Width End-------- goto(1,1,yPos,0) if yPos+1 ~= y then down(3) end layersDone = layersDone + 3 end ---------------Height End------- if lastHeight ~= 0 then ---------LAST ROW--------- (copied from above) moved = moved + 1 if y ~= 0 then down(2) end --If the basic y == 2 or 1 rowCheck = "right" if rowCheck == "right" then relxPos = xPos else relxPos = (x-xPos)+1 end while zPos <= z do -------------Width---------- while relxPos < x do ------------Length--------- mine(doDigDown, doDigUp) end ---------------Length End------- if zPos ~= z then if rowCheck == "right" and zPos ~= z then --Swithcing to next row rowCheck = "left" right() mine(doDigDown, doDigUp) right() else rowCheck = "right" left() mine(doDigDown, doDigUp) left() end else break end end ---------------Width End-------- goto(1,1,yPos,0) end if not inverted then if doDigDown then if turtle.digDown() then mined = mined + 1 end end else if doDigUp then if turtle.digUp() then mined = mined + 1 end end end goto(0,1,1,2) --Output to a chest or sit there drop(dropSide, true) --Display was moved above to be used in bedrock function display() if doBackup then fs.delete(saveFile) end --The only global variables I had to use if temp1 then up = temp1 end if temp2 then down = temp2 end
ModifyEvent(-2, -2, -2, -2, -1, -1, -1, 2612, 2612, 2612, -2, -2, -2); AddItem(186, 5); do return end;
local DatabaseSource = require(script.Parent.Parent.DatabaseSource) local copyDeep = require(script.Parent.copyDeep) local DocumentData = {} DocumentData.__index = DocumentData function DocumentData.new(options) return setmetatable({ isLoaded = false, isDirty = false, _lockSession = options.lockSession, _readOnlyData = options.readOnlyData, _collection = options.collection, _currentData = nil, }, DocumentData) end function DocumentData:_load() if self._lockSession then return self._lockSession:read() else return self._readOnlyData end end function DocumentData:read() if self.isLoaded == false then local newData = self:_load() if newData == nil then newData = self._collection.defaultData or {} local defaultData = self._collection.defaultData newData = defaultData and copyDeep(defaultData) or {} end assert(self._collection:validateData(newData)) self._currentData = newData self.isLoaded = true end return self._currentData end function DocumentData:write(value) if self._lockSession == nil then error("Can't write to a readonly DocumentData") end self._currentData = value self.isDirty = true end function DocumentData:save(source) source = source or DatabaseSource.Primary if self._lockSession == nil then error("Can't save on a readonly DocumentData") end self._lockSession:write(self._currentData, source) if source == DatabaseSource.All or source == DatabaseSource.Primary then self.isDirty = false end end function DocumentData:close() if self._lockSession then self._lockSession:unlockWithFinalData(self._currentData) end end function DocumentData:getLastWriteElapsedTime() return self._lockSession:getLastWriteElapsedTime() end return DocumentData
--[[ |WARNING| THESE TESTS RUN IN YOUR REAL ENVIRONMENT. |WARNING| If your tests alter a DataStore, it will actually alter your DataStore. This is useful in allowing your tests to move Parts around in the workspace or something, but with great power comes great responsibility. Don't mess up your stuff! --------------------------------------------------------------------- Documentation and Change Log: https://devforum.roblox.com/t/benchmarker-plugin-compare-function-speeds-with-graphs-percentiles-and-more/829912/1 --------------------------------------------------------------------]] local N = 1000 local SEED = 10 math.randomseed(SEED) local math_random = math.random local RandomLib = Random.new(SEED) local NextInteger = RandomLib.NextInteger local LengthPlusOne = N + 1 return { ParameterGenerator = function() end; Functions = { ["Random:NextInteger"] = function(Profiler) for Index = 1, N do RandomLib:NextInteger(Index, LengthPlusOne) end end; ["local NextInteger"] = function(Profiler) for Index = 1, N do NextInteger(RandomLib, Index, LengthPlusOne) end end; ["math.random"] = function(Profiler) for Index = 1, N do math.random(Index, LengthPlusOne) end end; ["local math_random"] = function(Profiler) for Index = 1, N do math_random(Index, LengthPlusOne) end end; }; }
local M = {} function M.parse(arg) local cmd = torch.CmdLine() cmd:text() cmd:text('Torch-7 Image Captioning') cmd:text() cmd:text('Options:') ------------ Model options ---------------------- cmd:option('-emb_size', 100, 'Word embedding size') -- 100 cmd:option('-lstm_size', 2048, 'LSTM size') -- 1024 cmd:option('-att_size', 64, 'how many attention areas') -- 14 * 14 cmd:option('-feat_size', 1280, 'the dimension of each attention area') cmd:option('-fc7_size', 2048, 'the dimension of fc7') -- 4096 cmd:option('-google_fc7_size', 1024, 'the dimension of google last layer') -- cmd:option('-fc7_size', 1024, 'the dimension of fc7') cmd:option('-att_hid_size', 512, 'the hidden size of the attention MLP; 0 if not using hidden layer') cmd:option('-val_size', 4000, 'Validation set size') cmd:option('-test_size', 4000, 'Test set size') cmd:option('-use_attention', true, 'Use attention or not') cmd:option('-use_noun', false, 'Use noun or not') -- true cmd:option('-use_cat', false, 'Use category or not. If true then will disgard words.') cmd:option('-reason_weight', 10.0, 'weight of reasoning loss') cmd:option('-gen_weight', 6.0) -- 30 -- cmd:option('-use_reasoning', true, 'Use reasoning. Will use attention in default.') cmd:option('-model_pack', 'reason_att_copy_simp', 'the model package to use, can be reason_att, reasoning, or soft_att_lstm') -- cmd:option('-reason_step', 8, 'Reasoning steps before the decoder') ------------ General options -------------------- cmd:option('-data', 'data/', 'Path to dataset') cmd:option('-train_feat', 'train2014_inceptionv3_conv', 'Path to pre-extracted training image feature') cmd:option('-val_feat', 'val2014_inceptionv3_conv', 'Path to pre-extracted validation image feature') cmd:option('-test_feat', 'test2014_inceptionv3_conv', 'Path to pre-extracted test image feature') -- cmd:option('-train_feat', 'train2014_features_vgg_vd19_conv5', 'Path to pre-extracted training image feature') -- cmd:option('-val_feat', 'val2014_features_vgg_vd19_conv5', 'Path to pre-extracted validation image feature') -- cmd:option('-test_feat', 'test2014_features_vgg_vd19_conv5_2nd', 'Path to pre-extracted test image feature') -- cmd:option('-train_feat', 'train2014_vgg_vd16_conv5', 'Path to pre-extracted training image feature') -- cmd:option('-val_feat', 'val2014_vgg_vd16_conv5', 'Path to pre-extracted validation image feature') -- cmd:option('-test_feat', 'test2014_vgg_vd16_conv5', 'Path to pre-extracted test image feature') -- cmd:option('-train_fc7', 'train2014_features_vgg_vd19_fc7', 'Path to pre-extracted training fully connected 7') -- cmd:option('-val_fc7', 'val2014_features_vgg_vd19_fc7', 'Path to pre-extracted validation fully connected 7') -- cmd:option('-test_fc7', 'test2014_features_vgg_vd19_fc7_2nd', 'Path to pre-extracted test fully connected 7') cmd:option('-train_fc7', 'train2014_inceptionv3_fc', 'Path to pre-extracted training fully connected 7') cmd:option('-val_fc7', 'val2014_inceptionv3_fc', 'Path to pre-extracted validation fully connected 7') cmd:option('-test_fc7', 'test2014_inceptionv3_fc', 'Path to pre-extracted test fully connected 7') -- cmd:option('-train_fc7', 'train2014_inceptionv3_fc', 'Path to pre-extracted training fully connected 7') -- cmd:option('-val_fc7', 'val2014_inceptionv3_fc', 'Path to pre-extracted validation fully connected 7') -- cmd:option('-test_fc7', 'test2014_inceptionv3_fc', 'Path to pre-extracted test fully connected 7') -- cmd:option('-train_fc7_google', 'train2014_features_googlenet', 'Path to pre-extracted training fully connected 7') -- cmd:option('-val_fc7_google', 'val2014_features_googlenet', 'Path to pre-extracted validation fully connected 7') -- cmd:option('-test_fc7_google', 'test2014_features_googlenet', 'Path to pre-extracted test fully connected 7') -- cmd:option('-train_jpg', 'train2014_jpg') -- cmd:option('-val_jpg', 'val2014_jpg') -- cmd:option('-test_jpg', 'test2014_jpg') -- cmd:option('-train_jpg', 'train2014') -- cmd:option('-val_jpg', 'val2014') -- cmd:option('-test_jpg', 'test2014') cmd:option('-train_anno', 'annotations/captions_train2014.json', 'Path to training image annotaion file') cmd:option('-val_anno', 'annotations/captions_val2014.json', 'Path to validation image annotaion file') cmd:option('-cat_file', 'annotations/cats.parsed.txt', 'Path to the category file') cmd:option('-nGPU', 1, 'Index of GPU to use, 0 means CPU') cmd:option('-seed', 13, 'Random number seed') -- 13 cmd:option('-id2noun_file', 'data/annotations/id2nouns.txt', 'Path to the id 2 nouns file') cmd:option('-arctic_dir', 'arctic-captions/splits', 'Path to index file') ------------ Training options -------------------- cmd:option('-nEpochs', 100, 'Number of epochs in training') -- 100 -- cmd:option('-eval_period', 12000, 'Every certain period, evaluate current model') -- cmd:option('-loss_period', 2400, 'Every given number of iterations, compute the loss on train and test') cmd:option('-batch_size', 32, 'Batch size in SGD') -- 32 cmd:option('-val_batch_size', 10, 'Batch size for testing') cmd:option('-LR', 1e-2, 'Initial learning rate') -- 1e-2 cmd:option('-cnn_LR', 0, 'Learning rate for cnn') -- cmd:option('-truncate', 30, 'Text longer than this size gets truncated. -1 for no truncation.') cmd:option('-max_eval_batch', 50, 'max number of instances when calling comp error. 20000 = 4000 * 5') cmd:option('-save_file', true, 'whether save model file?') -- cmd:option('-save_file_name', 'reason_att_copy_simp.model', 'file name for saving model') -- cmd:option('-save_conv5_name', '12000.1e-5.fine.conv5.model') cmd:option('-save_fc7_name', '12000.1e-5.fine.fc7.model') cmd:option('-load_file', false, 'whether load model file?') -- cmd:option('-load_vgg_file', false) -- cmd:option('-load_file_name', 'reason_att_copy_simp_seed33.model') -- cmd:option('-load_conv5_name', 'vgg_input_conv5_cunn.t7') cmd:option('-load_fc7_name', 'vgg_conv5_fc7_cunn.t7') cmd:option('-train_only', false, 'if true then use 80k, else use 110k') cmd:option('-early_stop', 'cider', 'can be cider or bleu') cmd:option('-bn', false) cmd:option('-use_google', false) -- false cmd:option('-cnn_relu', false) cmd:option('-cnn_dropout', true) -- true cmd:option('-normalize', false) -- false cmd:option('-reason_dropout', 0.0) -- 0.0 cmd:option('-gen_dropout', 0.1) -- 0.1 cmd:option('-load_glove', false) -- false cmd:option('-ensemble_LR', 1e-3) -- cmd:option('-ensemble_train_mode', false) -- ------------ Evaluation options -------------------- -- cmd:option('-model', 'copy.all.val.8.w10.noun.model', 'Model to evaluate') -- cmd:option('-model', 'copy.google.val.all.8.noun.w10.model', 'Model to evaluate') cmd:option('-eval_algo', 'beam', 'Evaluation algorithm, beam or greedy') cmd:option('-beam_size', 3, 'Beam size in beam search') -- 3 cmd:option('-val_max_len', 20, 'Max length in validation state') cmd:option('-test_mode', false, 'eval on test set if true') -- cmd:option('-server_train_mode', false, 'eval on test of val, and use the rest for training') cmd:option('-server_test_mode', false, 'eval on server test set if true; if true then test_mode will be false.') cmd:option('-batch_num', 4) cmd:option('-cur_batch_num', 1) local opt = cmd:parse(arg or {}) opt.eval_period = math.floor(3000 * 32 / 32) * 2 opt.loss_period = math.floor(600 * 32 / 32) if opt.use_cat then opt.use_noun = false end if opt.server_test_mode then opt.test_mode = false end if opt.server_train_mode then opt.test_mode = false end if opt.ensemble_train_mode then opt.test_mode, opt.server_train_mode, opt.server_test_mode = false, false, false end opt.jpg = false if opt.model_pack == 'reason_att_copy_finetune' or opt.model_pack == 'reason_att_copy_fineboth' or opt.model_pack == 'reason_att_copy_fineconv' or opt.model_pack == 'reason_att_copy_simp_fineboth' then opt.jpg = true end opt.model = opt.load_file_name return opt end return M
data:extend({ { type = "custom-input", name = "map-labels-hotkey-toggle", key_sequence = "SHIFT + M", consuming = "script-only" }, })
SimpleDlg = Inherit(CppObjectBase, UUserWidget) local WidgetType_Lua = {} local BasicWidget = require "ui.widgets.basicwidget" local PathPrefix = "/Game/Git/" function SimpleDlg:NewCpp(Object, ...) if not self:Property("m_BpClass") then self.m_BpClass = UUserWidget.LoadClass(Object, PathPrefix..self.p_BP_Path.."."..self.p_BP_Path.."_C") end local inscpp = UWidgetBlueprintLibrary.Create(Object, self.m_BpClass, nil) local ins = self:NewOn(inscpp, ...) ins:AddToViewport(0) return ins end function SimpleDlg:Ctor( ... ) local names, widgets, types = ULuautils.GetAllWidgets(self, {}, {}, {}) self.m_widgets = {} for i, v in ipairs(widgets) do self.m_widgets[names[i]:lower()] = {types[i], v} end self.m_luawidgets = {} end function SimpleDlg:SetUmgPath(Path) self.m_BpClass = self.m_BpClass or UUserWidget.FClassFinder(PathPrefix..Path) return self end function SimpleDlg:DynamicLoad(Path) self.p_BP_Path = Path end function SimpleDlg:Create(Object,controler) if not self._cppinstance_ then self._cppinstance_ = UWidgetBlueprintLibrary.Create(Object, self.m_BpClass, controler) self:AddToViewport(0) local names, widgets, types = ULuautils.GetAllWidgets(self, {}, {}, {}) self.m_widgets = {} for i, v in ipairs(widgets) do self.m_widgets[names[i]] = {types[i], v} end self.m_luawidgets = {} return self end end function SimpleDlg:Load(obj, Path, controler) self._meta_.m_BpClass = self._meta_.m_BpClass or UUserWidget.LoadClass(obj, PathPrefix..Path.."."..Path.."_C") return self:Create(obj, controler) end function SimpleDlg:Wnd(name) name = name:lower() if not self.m_luawidgets[name] then local wnd_info = self.m_widgets[name] local cpp_Type_str = wnd_info[1] if not WidgetType_Lua[cpp_Type_str] then WidgetType_Lua[cpp_Type_str] = Inherit(BasicWidget, _G[cpp_Type_str]) end self.m_luawidgets[name] = WidgetType_Lua[cpp_Type_str]:NewOn(wnd_info[2]) end return self.m_luawidgets[name] end function SimpleDlg:Destroy() self:RemoveFromParent() end return SimpleDlg
-- remove all lag frame input from text-based movie. if not emu then if #arg < 2 then print("arguments: <key movie file> <lag frame database file>") return end txtpath = arg[1] dbpath = arg[2] outfile = io.stdout else txtpath = "a.dsm" dbpath = "lag.db" outfile = io.open("out.dsm", "w") if outfile == nil then error("output open error") end end local txtfile = io.open(txtpath) if not txtfile then error("emu movie open error") end local dbfile = io.open(dbpath) if not dbfile then error("db open error") end function getNextFrameInput(file) local line while true do line = file:read("*l") if line == nil then return nil end if string.sub(line, 1, 1) == "|" then break else outfile:write(line, "\n") end end return line end local line = getNextFrameInput(txtfile) local prevline = line local nextline = getNextFrameInput(txtfile) local lineno = 1 local targetlineno = tonumber(dbfile:read("*l"), 10) while line do if targetlineno and lineno == targetlineno then -- outfile:write("|0|.............000 000 0|\n") targetlineno = tonumber(dbfile:read("*l"), 10) else outfile:write(--[[lineno, ": ", ]] line, "\n") end prevline = line line = nextline nextline = getNextFrameInput(txtfile) lineno = lineno + 1 end txtfile:close() dbfile:close() if outfile ~= io.stdout then outfile:close() end
-- Copyright (C) 2018 by chrono local footer = "ocarina of time\n" ngx.log(ngx.INFO, "chunk = ", ngx.arg[1], " eof = ", ngx.arg[2]) if not ngx.arg[2] then return end ngx.arg[1] = ngx.arg[1] .. footer
-- The MIT License (MIT) -- Copyright © 2016 Pietro Ribeiro Pepe. -- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. local path = (...):match("(.-)[^%.]+$") local class = require (path.."class") local View = require (path.."View") local TextField = class.extends(View,"TextField") local keys = {space = ' '} local blinkTime = 0.7 ------------------------------------------ -- Public functions ------------------------------------------ function TextField.new(x,y,width,height) local self = TextField.newObject(x,y,width,height) self.text = '' self.textColor = {0,0,0} self.textAlignment = 'left' self.isSelected = false self.blinkOn = false self.blinkTimer = 0 return self end function TextField:mousepressed(...) self:becomeResponder() end function TextField:respondKey(key) if keys[key] then self.text = self.text .. keys[key] elseif key=='return' then self.text = self.text .. '\n' elseif key=='backspace' then local l = string.len(self.text) if l>0 then self.text = string.sub(self.text,0,l-1) end elseif string.len(key)==1 then --[[ if love.keyboard.isDown('Caps-on') then key = string.upper(key) end]] self.text = self.text .. key end end function TextField:becomeResponder() if self.screen ~= nil then self.screen:becomeResponder(self) end end function TextField:becameResponder() self.isSelected = true self.blinkOn = true self.blinkTimer = blinkTime end function TextField:endResponder() self.isSelected = false end function TextField:update(dt) self:super_update(dt) if self.isSelected then self.blinkTimer = self.blinkTimer-dt if self.blinkTimer<0 then self.blinkOn = not self.blinkOn self.blinkTimer = blinkTime end end end function TextField:during_draw() self:super_during_draw() love.graphics.setColor(self.textColor) local t = self.text if self.isSelected and self.blinkOn then t=t .. '|' end love.graphics.printf(t,0,0,self.width,self.textAlignment) end return TextField
return {'bujumbura'}
local actions = require("telescope.actions") require("telescope").setup({ defaults = { prompt_prefix = "❯ ", selection_caret = "❯ ", file_ignore_patterns = { "node_modules/*", ".git/*", "%.class", "%.pdf", "%.png", "target/", ".bloop/", }, mappings = { i = { ["<esc>"] = actions.close, ["<c-j>"] = actions.move_selection_next, ["<c-k>"] = actions.move_selection_previous, }, }, }, extensions = { fzy_native = { override_generic_sorter = false, override_file_sorter = true, }, ["ui-select"] = { require("telescope.themes").get_ivy(), }, }, }) require("telescope").load_extension("fzy_native") require("telescope").load_extension("ui-select") local M = {} M.find_files = function() require("telescope.builtin").find_files(require("telescope.themes").get_ivy({ hidden = true, })) end M.help_tags = function() require("telescope.builtin").help_tags(require("telescope.themes").get_ivy()) end M.man_pages = function() require("telescope.builtin").man_pages(require("telescope.themes").get_ivy()) end M.current_buffer_fuzzy_find = function() require("telescope.builtin").current_buffer_fuzzy_find(require("telescope.themes").get_ivy()) end M.live_grep = function() require("telescope.builtin").live_grep(require("telescope.themes").get_ivy()) end return M
cflags{ '-I $srcdir/include', '-I $srcdir/src', '-I $basedir/pkg/netsurf/libhubbub/src/include', '-I $basedir/pkg/netsurf/libparserutils/src/include', '-I $basedir/pkg/netsurf/libwapcaplet/src/include', '-isystem $builddir/pkg/expat/include', } pkg.hdrs = copy('$outdir/include/dom', '$srcdir', { 'bindings/hubbub/errors.h', 'bindings/hubbub/parser.h', 'bindings/xml/xmlerror.h', 'bindings/xml/xmlparser.h', }) pkg.deps = { 'pkg/expat/headers', 'pkg/netsurf/libhubbub/fetch', 'pkg/netsurf/libparserutils/fetch', 'pkg/netsurf/libwapcaplet/fetch', } lib('libdom.a', [[ src/( core/( string.c node.c attr.c characterdata.c element.c implementation.c text.c typeinfo.c comment.c namednodemap.c nodelist.c cdatasection.c document_type.c entity_ref.c pi.c doc_fragment.c document.c ) events/( event.c dispatch.c event_target.c document_event.c custom_event.c keyboard_event.c mouse_wheel_event.c text_event.c event_listener.c mouse_event.c mutation_event.c ui_event.c mouse_multi_wheel_event.c mutation_name_event.c ) html/( html_applet_element.c html_area_element.c html_anchor_element.c html_basefont_element.c html_base_element.c html_body_element.c html_button_element.c html_canvas_element.c html_collection.c html_document.c html_element.c html_dlist_element.c html_directory_element.c html_options_collection.c html_html_element.c html_head_element.c html_link_element.c html_title_element.c html_meta_element.c html_style_element.c html_form_element.c html_select_element.c html_input_element.c html_text_area_element.c html_opt_group_element.c html_option_element.c html_hr_element.c html_menu_element.c html_fieldset_element.c html_legend_element.c html_div_element.c html_paragraph_element.c html_heading_element.c html_quote_element.c html_pre_element.c html_br_element.c html_label_element.c html_ulist_element.c html_olist_element.c html_li_element.c html_font_element.c html_mod_element.c html_image_element.c html_object_element.c html_param_element.c html_map_element.c html_script_element.c html_tablecaption_element.c html_tablecell_element.c html_tablecol_element.c html_tablesection_element.c html_table_element.c html_tablerow_element.c html_frameset_element.c html_frame_element.c html_iframe_element.c html_isindex_element.c ) utils/(namespace.c hashtable.c character_valid.c validate.c) ) bindings/hubbub/parser.c bindings/xml/expat_xmlparser.c $builddir/pkg/expat/libexpat.a.d $builddir/pkg/netsurf/libhubbub/libhubbub.a.d $builddir/pkg/netsurf/libwapcaplet/libwapcaplet.a ]]) fetch 'git'
--[[ ╔═════════════════════════════════╗ ║ Settings for dense-analysis/ale ║ ╚═════════════════════════════════╝ --]] local g = vim.g g.ale_completion_enabled = 0 g.ale_lint_on_text_changed = "never" g.ale_lint_on_insert_leave = 0 g.ale_lint_on_enter = 0
-- Globals g_lastFetchTime = 0 g_lastFetchCode = 0 g_lastFetchData = "" -- Functions function getTime() local sec, usec = rtctime.get() sec = sec - 25200 -- -7 hours (PDT) return luatz_timetable.new_from_timestamp(sec) end -- Start a simple http server srv=net.createServer(net.TCP) function receiver(sck, data) --print data local now = getTime() local rssi = wifi.sta.getrssi() local quality = 0 if (rssi ~= nil) then quality = (100 + rssi)*2 if (quality > 100) then quality = 100 end end local uptime = tmr.time() / 60 local fsRemaining, fsUsed, fsTotal = file.fsinfo() local fsPctUsed = fsUsed * 100 / fsTotal local r = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"} r[#r + 1] = "<h1>:)</h1>" r[#r + 1] = "time: " .. now:rfc_3339() .. "</br>" r[#r + 1] = "uptime: " .. uptime .. "</br>" r[#r + 1] = "wifi: " .. quality .. "%</br>" r[#r + 1] = "heap_avail: " .. node.heap() .. " bytes</br>" r[#r + 1] = "fs_used: " .. fsPctUsed .. "% of " .. fsTotal .. " kB</br>" r[#r + 1] = "</br>" r[#r + 1] = "fetch_time: " .. g_lastFetchTime .. "</br>" r[#r + 1] = "fetch_code: " .. g_lastFetchCode .. "</br>" r[#r + 1] = "fetch_data: " .. g_lastFetchData .. "</br>" -- sends and removes the first element from the 'response' table local function send(localSocket) if #r > 0 then localSocket:send(table.remove(r, 1)) else localSocket:close() r = nil end end -- triggers send() function again for remaining rows sck:on("sent", send) send(sck) end srv:listen(80, function(conn) conn:on("receive", receiver) end) -- Periodically sync clock tmr.alarm(1, 60000, tmr.ALARM_AUTO, function() syncClock() end) -- Periodically fetch url tmr.alarm(2, 10000, tmr.ALARM_AUTO, function() if (wifi.sta.getrssi() == nil) then return end g_lastFetchTime = getTime():rfc_3339() http.get("http://secretsciencelab.appspot.com/homebot/epochtime", nil, function(code, data) if (code < 0) then --print("HTTP request failed") else g_lastFetchCode = code g_lastFetchData = data end end) end)
if SERVER then AddCSLuaFile("actors2/convars.lua") AddCSLuaFile("actors2/language.lua") AddCSLuaFile("actors2/properties.lua") AddCSLuaFile("actors2/panels/welcome.lua") AddCSLuaFile("actors2/panels/actor_settings.lua") AddCSLuaFile("actors2/panels/actor_animations.lua") end include("actors2/convars.lua") include("actors2/language.lua") include("actors2/properties.lua") include("actors2/panels/welcome.lua") include("actors2/panels/actor_settings.lua") include("actors2/panels/actor_animations.lua")
--- --- wifi.lua --- --- Generic code for setting up the wifi module in the ESP8266. --- This is shared by many of my projects, control is returned to --- application logic via a callback named event_wifi_ready() which is --- triggered when the device receives an IP address from DHCP --- --- When this file is load it commences scanning for networks. --- If a network is seen that is in the config.wifi_passwords table, --- then that network is joined. --- print("wifi: loading") -- State flags joined_ap = false have_ip = false --- -- Set the wifi in station mode and configure callbacks for all state changes --- wifi.setmode(wifi.STATION) wifi.sta.eventMonReg(wifi.STA_APNOTFOUND, function() print("wifi: no AP found") end) wifi.sta.eventMonReg(wifi.STA_IDLE, function() print("wifi: idle") end) wifi.sta.eventMonReg(wifi.STA_CONNECTING, function() print("wifi: connecting") end) wifi.sta.eventMonReg(wifi.STA_WRONGPWD, function() -- This is called when a network login fails print("wifi: wrong password") joined_ap=nil end ) wifi.sta.eventMonReg(wifi.STA_FAIL, function() -- This is called when a network connection fails print("wifi: connection failed") joined_ap = nil seek_ap() end ) wifi.sta.eventMonReg(wifi.STA_GOTIP, function() -- This is called when an IP address is obtained. -- Control passes to event_wifi_ready() ip=wifi.sta.getip() if ip then print("wifi: got IP="..ip) joined_ap = true have_ip=ip if event_wifi_ready then event_wifi_ready(ip) end end end ) wifi.sta.eventMonStart() -- -- list_ap() - this is the callback for the 'getap' operation, it -- receives a list of discovered networks and attempts to -- join the first one that it recognises. -- function list_ap(t) -- (SSID : Authmode, RSSI, BSSID, Channel) print("\n"..string.format("%32s","SSID").."\tBSSID\t\t\t\t RSSI\t\tAUTHMODE\tCHANNEL") local join = nil -- Loop over all the networks found and print their identity -- If we see one that we like, save it and attempt to join for ssid,v in pairs(t) do local authmode, rssi, bssid, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]+)") print(string.format("%32s",ssid).."\t".. bssid.."\t "..rssi.."\t\t"..authmode.."\t\t\t"..channel) if not joined_ap and not join and config.wifi_passwords[ssid] then -- Save this network to try joining it after we exit this loop join=ssid end end if not joined_ap then if join then -- We founds a netwok above that we like. Join it. print("wifi: joining "..join) wifi.sta.config(join, config.wifi_passwords[join]); wifi.sta.connect() else -- No networks yet. Wait and retry. print "wifi: No networks found, trying again in 5 seconds" tmr.alarm(1, 5000, tmr.ALARM_SINGLE, seek_ap) end end end -- -- seek_ap() - initiate an Access Point scan, and call list_ap with the result -- function seek_ap() if joined_ap then return end print "wifi: looking for networks" wifi.sta.getap(list_ap) end seek_ap() print("wifi: loaded")
-- Copyright (c) 2017-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the license found in the LICENSE file in -- the root directory of this source tree. An additional grant of patent rights -- can be found in the PATENTS file in the same directory. -- --[[ -- -- Creates a dictionary from raw text. -- --]] require 'fairseq.text' local tok = require 'fairseq.text.tokenizer' local cmd = torch.CmdLine() cmd:option('-text', 'source text') cmd:option('-out', 'target path') cmd:option('-threshold', 0, 'map words appearing less than threshold times to unknown') cmd:option('-nwords', -1, 'number of non-control target words to retain') local config = cmd:parse(arg) assert(not (config.nwords >= 0 and config.threshold > 0), 'Specify either a frequency threshold or a word count') local dict = tok.buildDictionary{ filename = config.text, threshold = config.threshold, } if config.nwords >= 0 then dict.cutoff = config.nwords + dict.nspecial end print(string.format('| Dictionary: %d types', dict:size())) torch.save(config.out, dict, 'binary', false)
local mod = DBM:NewMod(674, "DBM-Party-MoP", 9, 316) local L = mod:GetLocalizedStrings() local sndWOP = mod:SoundMM("SoundWOP") mod:SetRevision(("$Revision: 9656 $"):sub(12, -3)) mod:SetCreatureID(60040, 99999)--3977 is High Inquisitor Whitemane and 60040 is Commander Durand, we don't really need to add her ID, because we don't ever engage her, and he true death is at same time as her. mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_CAST_START", "SPELL_CAST_SUCCESS", "UNIT_SPELLCAST_SUCCEEDED boss1 boss2", "UNIT_DIED" ) --local warnRes = mod:NewCastAnnounce(111670, 4)--This spell seems to be only found in combatlog. Also, I didn't see any casting bar. (both trashes and bosses). Needs more review for this spell. local warnFlashofSteel = mod:NewSpellAnnounce(115627, 3) local warnDashingStrike = mod:NewSpellAnnounce(115676, 3) local warnMassRes = mod:NewCastAnnounce(113134, 4) local warnDeepSleep = mod:NewSpellAnnounce(9256, 2) local warnHeal = mod:NewCastAnnounce(12039, 3) local warnMC = mod:NewCastAnnounce(130857, 4)--Challenge mode only ability local specWarnMassRes = mod:NewSpecialWarningInterrupt(113134, true) local specWarnHeal = mod:NewSpecialWarningInterrupt(12039, true) local specWarnMC = mod:NewSpecialWarningInterrupt(130857, true) local timerFlashofSteel = mod:NewCDTimer(26, 115627)--not confirmed. local timerDashingStrike = mod:NewCDTimer(26, 115676)--not confirmed. local timerMassResCD = mod:NewCDTimer(21, 113134)--21-24sec variation. Earlier if phase transitions local timerDeepSleep = mod:NewBuffFadesTimer(10, 9256) local timerMCCD = mod:NewCDTimer(19, 130857) local phase = 1 function mod:OnCombatStart(delay) phase = 1 timerFlashofSteel:Start(9-delay) timerDashingStrike:Start(24-delay) end function mod:SPELL_CAST_START(args) if args.spellId == 113134 then warnMassRes:Show() specWarnMassRes:Show(args.sourceName) timerMassResCD:Start() elseif args.spellId == 12039 then warnHeal:Show() specWarnHeal:Show(args.sourceName) elseif args.spellId == 130857 then warnMC:Show() specWarnMC:Show(args.sourceName) sndWOP:Play("kickcast")--快打斷 end end --Could also use damage overkill like phase 1 but it's only .8 sec faster so no need. --3/28 16:22:43.001 SWING_DAMAGE,0x0100000000009810,"Omegal",0x511,0x0,0xF1300F8900000065,"High Inquisitor Whitemane",0x10a48,0x0,10172,-1,1,0,0,410,1,nil,nil --3/28 16:22:43.810 SPELL_CAST_SUCCESS,0xF1300F8900000065,"High Inquisitor Whitemane",0xa48,0x0,0x0000000000000000,nil,0x80000000,0x80000000,9256,"Deep Sleep",0x20 function mod:SPELL_CAST_SUCCESS(args) if args.spellId == 9256 then--Phase 3 phase = 3 warnDeepSleep:Show() timerDeepSleep:Start() sndWOP:Schedule(5, "countfive") sndWOP:Schedule(6, "countfour") sndWOP:Schedule(7, "countthree") sndWOP:Schedule(8, "counttwo") sndWOP:Schedule(9, "countone") sndWOP:Schedule(10, "phasechange")--階段轉換 timerMassResCD:Start(18)--Limited Sample size if self:IsDifficulty("challenge5") then timerMCCD:Start(19)--Pretty much immediately after first mas res, unless mass res isn't interrupted then it'll delay MC end end end function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId) if spellId == 115627 and self:AntiSpam(2, 1) then warnFlashofSteel:Show() timerFlashofSteel:Start() elseif spellId == 115676 and self:AntiSpam(2, 2) then warnDashingStrike:Show() timerDashingStrike:Start() end end function mod:UNIT_DIED(args) if self:GetCIDFromGUID(args.destGUID) == 60040 then if phase == 3 then--Fight is over on 2nd death DBM:EndCombat(self) else--it's first death, he's down and whiteman is taking over phase = 2 timerMassResCD:Start(13) if self:IsDifficulty("challenge5") then timerMCCD:Start(14) end timerFlashofSteel:Cancel() timerDashingStrike:Cancel() end end end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file check_cxxsnippets.lua -- -- imports import("lib.detect.check_cxsnippets") -- check the given c++ snippets? -- -- @param snippets the snippets -- @param opt the argument options -- e.g. -- { verbose = false, target = [target|option] -- , types = {"wchar_t", "char*"}, includes = "stdio.h", funcs = {"sigsetjmp", "sigsetjmp((void*)0, 0)"} -- , configs = {defines = "xx", cxflags = ""}} -- -- funcs: -- sigsetjmp -- sigsetjmp((void*)0, 0) -- sigsetjmp{sigsetjmp((void*)0, 0);} -- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);} -- -- @return true or false -- -- @code -- local ok = check_cxxsnippets("void test() {}") -- local ok = check_cxxsnippets({"void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"}) -- local ok = check_cxxsnippets({snippet_name = "void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"}) -- @endcode -- function main(snippets, opt) return check_cxsnippets(snippets, table.join(table.wrap(opt), {sourcekind = "cxx"})) end
local combat = Combat() combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_EARTHDAMAGE) combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_SMALLPLANTS) local area = createCombatArea(AREA_SQUAREWAVE5, AREADIAGONAL_SQUAREWAVE5) combat:setArea(area) function onGetFormulaValues(player, level, maglevel) min = -((level / 5) + (maglevel * 3.25) + 5) max = -((level / 5) + (maglevel * 6.75) + 30) return min, max end combat:setCallback(CALLBACK_PARAM_LEVELMAGICVALUE, "onGetFormulaValues") function onCastSpell(creature, var) return combat:execute(creature, var) end
require("prototypes.technology") require("prototypes.disablesciencepacks") require("prototypes.increaselabenergy")
--- Utility functions. require "socket" local M = {} --- Print a formatted string. -- Use __tostring method on tables that provide the function. local function printf(s, ...) local t = {} for i,v in ipairs{...} do if type(v) == 'table' and v.__tostring then t[i] = tostring(v) else t[i] = v end end io.write(s:format(unpack(t))) io.flush() end M.printf = printf --- Create a read only table. -- Usage: t = readOnly{'a', 'b', 'c'} local function readOnly(t) local proxy = {} local mt = { __index = t, __newindex = function (t,k,v) error("attempt to update a read-only table", 2) end } setmetatable(proxy, mt) return proxy end M.readOnly = readOnly --- Sleep for n milliseconds without busy wait. local function sleep(n) socket.select(nil, nil, n/1000) end M.sleep = sleep --- Get a higher resolution time than os.time() local function gettime() return socket.gettime()*1000 end M.gettime = gettime --- Round a number 'num' to 'idp' decimal places. local function round(num, idp) local mult = 10^(idp or 0) return math.floor(num * mult + 0.5) / mult end M.round = round --- Return true if the element x is in Table t. local function isin(t, x) for _,t_i in pairs(t) do if t_i == x then return true end end return false end M.isin = isin --- Return the sublist from index u to o (inclusive) from t. local function slice(t, u, o) local res = {} for i=u,o do res[#res+1] = t[i] end return res end M.slice = slice return M
-- imported modules local action = require 'engine.action' local class = require 'engine.oop' local color = require 'engine.color' local console = require 'engine.console' local elements = require 'engine.elements' local Entity = require 'engine.Entity' local Equipment = require 'engine.Equipment' local Inventory = require 'engine.Inventory' local soundManager = require 'engine.soundManager' local utils = require 'engine.utils' local map = require 'engine.map' -- class local Player = class('Player', Entity) Player.Base_Speed = 1200 Player.Bash_Speed = 720 Player.Throw_Speed = 720 function Player:ctor(initPos) self.base.ctor(self, initPos) self.displaySee = false self.losRadius = 15 self.seeDist = 15 self.inventory = Inventory:new(6) self.equipment = Equipment:new({ 'melee', 'light', 'heavy' }) self.equipmentActive = 0 self.color = { 0.9, 0.9, 0.9, 1.0 } self.sounds = { walk = { soundManager.get('sounds/stepdirt_1.wav', 'static') , soundManager.get('sounds/stepdirt_2.wav', 'static') , soundManager.get('sounds/stepdirt_3.wav', 'static') , soundManager.get('sounds/stepdirt_4.wav', 'static') , soundManager.get('sounds/stepdirt_5.wav', 'static') , soundManager.get('sounds/stepdirt_6.wav', 'static') , soundManager.get('sounds/stepdirt_7.wav', 'static') , soundManager.get('sounds/stepdirt_8.wav', 'static') } } end function Player:onAdd() self.name = 'Player' self:occupy() self.maxHp = 1200 self.hp = 1200 self.damage = 10 end function Player:recalcSeeMap() self.displaySee = true self.base.recalcSeeMap(self) self.displaySee = false end function Player:checkEntVis(oth, dist) self.base.checkEntVis(self, oth, dist) if self.displaySee then -- local gray = { color.hsvToRgb(0.0, 0.0, 0.8, 1.0) } -- if self.seemap[oth] then -- console.log({ -- gray, -- 'You see ', -- { color.hsvToRgb(0.00, 0.8, 1.0, 1.0) }, -- oth.name, -- }) -- end end end function Player:move() self.base.move(self) end local function play(src) if src:isPlaying() then src:stop() end src:play() end function Player:sound(actionId) if action.Action.Move == actionId then local rnd = self.rng:random(#self.sounds.walk) play(self.sounds.walk[rnd]) end end function Player:throw() local desc = self.actionData self.actionData = nil local item = self.inventory:get(desc.itemIndex) self.inventory:del(item) self.doRecalc = true return desc, item end return Player
--Sayuri·七色的人偶师 xpcall(function() require("expansions/script/c37564765") end,function() require("script/c37564765") end) local m,cm=Senya.SayuriRitualPreload(37564921) function cm.initial_effect(c) c:EnableReviveLimit() local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(m,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e1:SetCountLimit(1,m) e1:SetCondition(Senya.SummonTypeCondition(SUMMON_TYPE_RITUAL)) e1:SetTarget(cm.target) e1:SetOperation(cm.operation) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_SET_ATTACK_FINAL) e2:SetTargetRange(LOCATION_MZONE,0) e2:SetCondition(cm.atkcon) e2:SetTarget(cm.atktg) e2:SetValue(cm.atkval) c:RegisterEffect(e2) local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e4:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET) e4:SetRange(LOCATION_MZONE) e4:SetCondition(cm.tgcon) e4:SetValue(aux.imval1) c:RegisterEffect(e4) local e5=e4:Clone() e5:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e5:SetValue(1) c:RegisterEffect(e5) end function cm.atkcon(e) return Duel.GetCurrentPhase()==PHASE_DAMAGE_CAL end function cm.atktg(e,c) return c:IsCode(m+1) and c:GetBattleTarget() end function cm.atkval(e,c) return c:GetBattleTarget():GetAttack() end function cm.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,m+1,0,0x4011,0,0,1,RACE_MACHINE,ATTRIBUTE_EARTH) end local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,ft,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,ft,0,0) end function cm.operation(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft<=0 or not Duel.IsPlayerCanSpecialSummonMonster(tp,m+1,0,0x4011,0,0,1,RACE_MACHINE,ATTRIBUTE_EARTH) then return end if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end for i=1,ft do local token=Duel.CreateToken(tp,m+1) Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP) local e3=Effect.CreateEffect(e:GetHandler()) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_CANNOT_BE_LINK_MATERIAL) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e3:SetValue(1) e3:SetReset(RESET_EVENT+0x1fe0000) token:RegisterEffect(e3,true) end Duel.SpecialSummonComplete() end function cm.tgfilter(c) return c:IsFaceup() and c:IsCode(m+1) end function cm.tgcon(e) return Duel.IsExistingMatchingCard(cm.tgfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end
Citizen.CreateThread(function() while true do Citizen.Wait(1) id = PlayerId() DisablePlayerVehicleRewards(id) end end)
local Repairer = Class(function(self, inst) self.inst = inst self.workrepairvalue = 0 self.healthrepairvalue = 0 self.perishrepairvalue = 0 self.repairmaterial = nil end) function Repairer:CollectUseActions(doer, target, actions, right) if right and target.components.repairable and target.components.repairable.repairmaterial == self.repairmaterial and ((target.components.health and target.components.health:GetPercent() < 1 and self.healthrepairvalue > 0) or (target.components.workable and target.components.workable.workleft and target.components.workable.workleft < target.components.workable.maxwork and self.workrepairvalue > 0) or (target.components.perishable and target.components.perishable:GetPercent() < 1 and self.perishrepairvalue > 0)) then table.insert(actions, ACTIONS.REPAIR) end end return Repairer
--- Functions for working with directions and orientations. -- @module Area.Direction -- @usage local Direction = require('__stdlib__/stdlib/area/direction') -- @see defines.direction local Direction = { __class = 'Direction', __index = require('__stdlib__/stdlib/core'), dir = defines.direction } setmetatable(Direction, Direction) local dirs = defines.direction local floor = math.floor --- Returns the opposite direction &mdash; adapted from Factorio util.lua. -- @release 0.8.1 -- @tparam defines.direction direction the direction -- @treturn defines.direction the opposite direction function Direction.opposite_direction(direction) return (direction + 4) % 8 end --- Returns the next direction. --> For entities that only support two directions, see @{opposite_direction}. -- @tparam defines.direction direction the starting direction -- @tparam[opt=false] boolean reverse true to get the next direction in counter-clockwise fashion, false otherwise -- @tparam[opt=false] boolean eight_way true to get the next direction in 8-way (note: not many prototypes support 8-way) -- @treturn defines.direction the next direction function Direction.next_direction(direction, reverse, eight_way) return (direction + (eight_way and ((reverse and -1) or 1) or ((reverse and -2) or 2))) % 8 end --- Returns an 8 way direction from orientation. -- @tparam float orientation -- @treturn defines.direction function Direction.orientation_to_8way(orientation) return floor(orientation * 8 + 0.5) % 8 end --- Returns a 4 way direction from orientation. -- @tparam float orientation -- @treturn defines.direction function Direction.orientation_to_4way(orientation) return floor(orientation * 4 + 0.5) % 4 * 2 end --- Returns an orientation from a direction. -- @tparam defines.direction direction -- @treturn float function Direction.direction_to_orientation(direction) return direction / 8 end --- Returns a vector from a direction. -- @tparam defines.direction direction -- @tparam[opt = 1] number distance -- @treturn Position function Direction.to_vector(direction, distance) distance = distance or 1 local x, y = 0, 0 if direction == dirs.north then y = y - distance elseif direction == dirs.northeast then x, y = x + distance, y - distance elseif direction == dirs.east then x = x + distance elseif direction == dirs.southeast then x, y = x + distance, y + distance elseif direction == dirs.south then y = y + distance elseif direction == dirs.southwest then x, y = x - distance, y + distance elseif direction == dirs.west then x = x - distance elseif direction == dirs.northwest then x, y = x - distance, y - distance end return {x = x, y = y} end return Direction
--[[ Copyright 2021 0x2A ( https://github.com/0x2A-git ) 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. --]] ENT.Type = "anim" ENT.Base = "base_gmodentity" ENT.PrintName = "Tableau vote" ENT.Category = "0x2A" ENT.Author = "0x2A" ENT.Spawnable = true ENT.AdminSpawnable = true
--!nocheck --[[ Filename: GamepadMenu.lua Written by: jeditkacheff Version 1.1 Description: Controls the radial menu that appears when pressing menu button on gamepad --]] --NOTICE: This file has been branched! If you're implementing changes in this file, please consider also implementing them in the other --version. --[[ SERVICES ]] local GuiService = game:GetService('GuiService') local CoreGuiService = game:GetService('CoreGui') local InputService = game:GetService('UserInputService') local ContextActionService = game:GetService('ContextActionService') local HttpService = game:GetService('HttpService') local RunService = game:GetService('RunService') local StarterGui = game:GetService('StarterGui') local Players = game:GetService('Players') local GuiRoot = CoreGuiService:WaitForChild('RobloxGui') local TextService = game:GetService('TextService') local VRService = game:GetService('VRService') --[[ END OF SERVICES ]] --[[ MODULES ]] local isNewInGameMenuEnabled = require(GuiRoot.Modules.isNewInGameMenuEnabled) local tenFootInterface = require(GuiRoot.Modules.TenFootInterface) local utility = require(GuiRoot.Modules.Settings.Utility) local RobloxTranslator = require(GuiRoot.Modules.RobloxTranslator) local businessLogic = require(GuiRoot.Modules.BusinessLogic) local Panel3D = require(GuiRoot.Modules.VR.Panel3D) local EmotesModule = require(GuiRoot.Modules.EmotesMenu.EmotesMenuMaster) local FFlagUpdateSettingsHubGameText = require(GuiRoot.Modules.Flags.FFlagUpdateSettingsHubGameText) local InGameMenuConstants = require(GuiRoot.Modules.InGameMenu.Resources.Constants) --[[ VARIABLES ]] local gamepadSettingsFrame = nil local isVisible = false local smallScreen = utility:IsSmallTouchScreen() local isTenFootInterface = tenFootInterface:IsEnabled() local radialButtons = {} local radialButtonsByName = {} local lastInputChangedCon = nil local vrPanel = nil --[[ CONSTANTS ]] local NON_VR_FRAME_HIDDEN_SIZE = UDim2.new(0, 102, 0, 102) local NON_VR_FRAME_SIZE = UDim2.new(0, 408, 0, 408) local VR_FRAME_HIDDEN_SIZE = UDim2.new(0.125, 0, 0.125, 0) local VR_FRAME_SIZE = UDim2.new(0.75, 0, 0.75, 0) local PANEL_SIZE_STUDS = 3 local PANEL_RESOLUTION = 250 local GAMEPAD_MENU_KEY = "GamepadMenu" local function getImagesForSlot(slot) if slot == 1 then return "rbxasset://textures/ui/Settings/Radial/Top.png", "rbxasset://textures/ui/Settings/Radial/TopSelected.png", "rbxasset://textures/ui/Settings/Radial/Menu.png", UDim2.new(0.5,-26,0,18), UDim2.new(0,52,0,41), UDim2.new(0,150,0,100), UDim2.new(0.5,-75,0,0) elseif slot == 2 then return "rbxasset://textures/ui/Settings/Radial/TopRight.png", "rbxasset://textures/ui/Settings/Radial/TopRightSelected.png", "rbxasset://textures/ui/Settings/Radial/PlayerList.png", UDim2.new(1,-90,0,90), UDim2.new(0,52,0,52), UDim2.new(0,108,0,150), UDim2.new(1,-110,0,50) elseif slot == 3 then return "rbxasset://textures/ui/Settings/Radial/BottomRight.png", "rbxasset://textures/ui/Settings/Radial/BottomRightSelected.png", "rbxasset://textures/ui/Emotes/EmotesRadialIcon.png", UDim2.new(1,-85,1,-150), UDim2.new(0,42,0,58), UDim2.new(0,120,0,150), UDim2.new(1,-120,1,-200) elseif slot == 4 then return "rbxasset://textures/ui/Settings/Radial/Bottom.png", "rbxasset://textures/ui/Settings/Radial/BottomSelected.png", "rbxasset://textures/ui/Settings/Radial/Leave.png", UDim2.new(0.5,-20,1,-62), UDim2.new(0,55,0,46), UDim2.new(0,150,0,100), UDim2.new(0.5,-75,1,-100) elseif slot == 5 then return "rbxasset://textures/ui/Settings/Radial/BottomLeft.png", "rbxasset://textures/ui/Settings/Radial/BottomLeftSelected.png", "rbxasset://textures/ui/Settings/Radial/Backpack.png", UDim2.new(0,40,1,-150), UDim2.new(0,44,0,56), UDim2.new(0,110,0,150), UDim2.new(0,0,0,205) elseif slot == 6 then return "rbxasset://textures/ui/Settings/Radial/TopLeft.png", "rbxasset://textures/ui/Settings/Radial/TopLeftSelected.png", "rbxasset://textures/ui/Settings/Radial/Chat.png", UDim2.new(0,35,0,100), UDim2.new(0,56,0,53), UDim2.new(0,110,0,150), UDim2.new(0,0,0,50) end return "", "", "", UDim2.new(0,0,0,0), UDim2.new(0,0,0,0) end local vrSlotImages = {} local vrSlotBackgroundImage = "rbxasset://textures/ui/VR/Radial/SliceBackground.png" local vrSlotActiveImage = "rbxasset://textures/ui/VR/Radial/SliceActive.png" local vrSlotDisabledImage = "rbxasset://textures/ui/VR/Radial/SliceDisabled.png" local vrNumSlots = 8 for i = 1, vrNumSlots do vrSlotImages[i] = { background = vrSlotBackgroundImage, active = vrSlotActiveImage, disabled = vrSlotDisabledImage, rotation = (360 / vrNumSlots) * (i - 1) } end vrSlotImages[1].icon = "rbxasset://textures/ui/Settings/Radial/Menu.png" vrSlotImages[1].iconPosition = UDim2.new(0.5,-26,0,18) vrSlotImages[1].iconSize = UDim2.new(0,52,0,41) vrSlotImages[2].icon = "rbxasset://textures/ui/Settings/Radial/PlayerList.png" vrSlotImages[2].iconPosition = UDim2.new(0.71, 5, 0.29, -60) vrSlotImages[2].iconSize = UDim2.new(0, 52, 0, 52) vrSlotImages[3].icon = "rbxasset://textures/ui/VR/Radial/Icons/Recenter.png" vrSlotImages[3].iconPosition = UDim2.new(1, -60, 0.5, -25) vrSlotImages[3].iconSize = UDim2.new(0, 50, 0, 50) vrSlotImages[4].icon = "rbxasset://textures/ui/Emotes/EmotesRadialIcon.png" vrSlotImages[4].iconPosition = UDim2.new(0.71, 12, 0.71, 5) vrSlotImages[4].iconSize = UDim2.new(0, 42, 0, 58) vrSlotImages[5].icon = "rbxasset://textures/ui/Settings/Radial/Leave.png" vrSlotImages[5].iconPosition = UDim2.new(0.5,-20,1,-58) vrSlotImages[5].iconSize = UDim2.new(0,55,0,46) vrSlotImages[6].icon = "rbxasset://textures/ui/VR/Radial/Icons/Backpack.png" vrSlotImages[6].iconPosition = UDim2.new(0.29, -50, 0.71, 4) vrSlotImages[6].iconSize = UDim2.new(0, 42, 0, 56) vrSlotImages[7].icon = "rbxasset://textures/ui/VR/Radial/Icons/2DUI.png" vrSlotImages[7].iconPosition = UDim2.new(0, 10, 0.5, -25) vrSlotImages[7].iconSize = UDim2.new(0, 50, 0, 50) vrSlotImages[8].icon = "rbxasset://textures/ui/Settings/Radial/Chat.png" vrSlotImages[8].iconPosition = UDim2.new(0.29, -60, 0.29, -52) vrSlotImages[8].iconSize = UDim2.new(0, 56, 0, 53) local radialButtonLayout = { PlayerList = { Range = { Begin = 36, End = 96 } }, Emotes = { Range = { Begin = 96, End = 156 } }, LeaveGame = { Range = { Begin = 156, End = 216 } }, Backpack = { Range = { Begin = 216, End = 276 } }, Chat = { Range = { Begin = 276, End = 336 } }, Settings = { Range = { Begin = 336, End = 36 } }, } local vrButtonLayout = { PlayerList = { Range = { Begin = 22.5, End = 67.5 } }, Recenter = { Range = { Begin = 67.5, End = 112.5 } }, Emotes = { Range = { Begin = 112.5, End = 157.5 } }, LeaveGame = { Range = { Begin = 157.5, End = 202.5 } }, Backpack = { Range = { Begin = 202.5, End = 247.5 } }, ToggleUI = { Range = { Begin = 247.5, End = 292.5 } }, Chat = { Range = { Begin = 292.5, End = 337.5 } }, Settings = { Range = { Begin = 337.5, End = 22.5 } } } local freezeControllerActionName = "doNothingAction" local radialSelectActionName = "RadialSelectAction" local thumbstick2RadialActionName = "Thumbstick2RadialAction" local radialCancelActionName = "RadialSelectCancel" local radialAcceptActionName = "RadialSelectAccept" local toggleMenuActionName = "RBXToggleMenuAction" local noOpFunc = function() end local doGamepadMenuButton = nil local toggleCoreGuiRadial = nil local function getSelectedObjectFromAngle(angle) local closest = nil local closestDistance = 30 -- threshold of 30 for selecting the closest radial button local currentLayout = VRService.VREnabled and vrButtonLayout or radialButtonLayout for radialKey, buttonLayout in pairs(currentLayout) do if radialButtons[gamepadSettingsFrame[radialKey]]["Disabled"] == false then --Check for exact match if buttonLayout.Range.Begin < buttonLayout.Range.End then if angle > buttonLayout.Range.Begin and angle <= buttonLayout.Range.End then return gamepadSettingsFrame[radialKey] end else if angle > buttonLayout.Range.Begin or angle <= buttonLayout.Range.End then return gamepadSettingsFrame[radialKey] end end --Check if this is the closest button so far local distanceBegin = math.min(math.abs((buttonLayout.Range.Begin + 360) - angle), math.abs(buttonLayout.Range.Begin - angle)) local distanceEnd = math.min(math.abs((buttonLayout.Range.End + 360) - angle), math.abs(buttonLayout.Range.End - angle)) local distance = math.min(distanceBegin, distanceEnd) if distance < closestDistance then closestDistance = distance closest = gamepadSettingsFrame[radialKey] end end end return closest end local function setSelectedRadialButton(selectedObject) for button, buttonTable in pairs(radialButtons) do local isVisible = (button == selectedObject) button:FindFirstChild("Selected").Visible = isVisible button:FindFirstChild("RadialLabel").Visible = isVisible button:FindFirstChild("RadialBackground").Visible = isVisible if VRService.VREnabled then button.ImageTransparency = isVisible and 1 or 0 end end end local function activateSelectedRadialButton() for button, buttonTable in pairs(radialButtons) do if button:FindFirstChild("Selected").Visible then buttonTable["Function"]() return true end end return false end local function radialSelectAccept(name, state, input) if gamepadSettingsFrame.Visible and state == Enum.UserInputState.Begin then activateSelectedRadialButton() end end local function radialSelectCancel(name, state, input) if gamepadSettingsFrame.Visible and state == Enum.UserInputState.Begin then toggleCoreGuiRadial() end end local D_PAD_VR_DIRS = { [Enum.KeyCode.DPadUp] = Vector2.new(0, 1), [Enum.KeyCode.DPadDown] = Vector2.new(0, -1), [Enum.KeyCode.DPadRight] = Vector2.new(1, 0), [Enum.KeyCode.DPadLeft] = Vector2.new(-1, 0) } local function radialSelect(name, state, input) local inputVector = Vector2.new(0, 0) if input.KeyCode == Enum.KeyCode.Thumbstick1 then inputVector = Vector2.new(input.Position.x, input.Position.y) elseif input.KeyCode == Enum.KeyCode.DPadUp or input.KeyCode == Enum.KeyCode.DPadDown or input.KeyCode == Enum.KeyCode.DPadLeft or input.KeyCode == Enum.KeyCode.DPadRight then local D_PAD_BUTTONS = { [Enum.KeyCode.DPadUp] = false; [Enum.KeyCode.DPadDown] = false; [Enum.KeyCode.DPadLeft] = false; [Enum.KeyCode.DPadRight] = false; } --set D_PAD_BUTTONS status: button down->true, button up->false local gamepadState = InputService:GetGamepadState(input.UserInputType) for index, value in ipairs(gamepadState) do if value.KeyCode == Enum.KeyCode.DPadUp or value.KeyCode == Enum.KeyCode.DPadDown or value.KeyCode == Enum.KeyCode.DPadLeft or value.KeyCode == Enum.KeyCode.DPadRight then D_PAD_BUTTONS[value.KeyCode] = (value.UserInputState == Enum.UserInputState.Begin) end end if VRService.VREnabled then for index, value in pairs(D_PAD_BUTTONS) do if value then inputVector = inputVector + D_PAD_VR_DIRS[index] end end else if D_PAD_BUTTONS[Enum.KeyCode.DPadUp] or D_PAD_BUTTONS[Enum.KeyCode.DPadDown] then inputVector = D_PAD_BUTTONS[Enum.KeyCode.DPadUp] and Vector2.new(0, 1) or Vector2.new(0, -1) if D_PAD_BUTTONS[Enum.KeyCode.DPadLeft] then inputVector = Vector2.new(-1, inputVector.Y) elseif D_PAD_BUTTONS[Enum.KeyCode.DPadRight] then inputVector = Vector2.new(1, inputVector.Y) end end end inputVector = inputVector.unit end local selectedObject = nil if inputVector.magnitude > 0.8 then local angle = math.deg(math.atan2(inputVector.X, inputVector.Y)) if angle < 0 then angle = angle + 360 end selectedObject = getSelectedObjectFromAngle(angle) setSelectedRadialButton(selectedObject) end end local function unbindAllRadialActions() GuiService.CoreGuiNavigationEnabled = true ContextActionService:UnbindCoreAction(radialSelectActionName) ContextActionService:UnbindCoreAction(radialCancelActionName) ContextActionService:UnbindCoreAction(radialAcceptActionName) ContextActionService:UnbindCoreAction(freezeControllerActionName) ContextActionService:UnbindCoreAction(thumbstick2RadialActionName) ContextActionService:UnbindCoreAction(radialAcceptActionName .. "VR") end local function bindAllRadialActions() GuiService.CoreGuiNavigationEnabled = false ContextActionService:BindCoreAction(freezeControllerActionName, noOpFunc, false, Enum.UserInputType.Gamepad1) ContextActionService:BindCoreAction(radialAcceptActionName, radialSelectAccept, false, Enum.KeyCode.ButtonA) ContextActionService:BindCoreAction(radialCancelActionName, radialSelectCancel, false, Enum.KeyCode.ButtonB) ContextActionService:BindCoreAction(radialSelectActionName, radialSelect, false, Enum.KeyCode.Thumbstick1, Enum.KeyCode.DPadUp, Enum.KeyCode.DPadDown, Enum.KeyCode.DPadLeft, Enum.KeyCode.DPadRight) ContextActionService:BindCoreAction(thumbstick2RadialActionName, noOpFunc, false, Enum.KeyCode.Thumbstick2) ContextActionService:BindCoreAction(toggleMenuActionName, doGamepadMenuButton, false, Enum.KeyCode.ButtonStart) if VRService.VREnabled then ContextActionService:BindCoreAction(radialAcceptActionName .. "VR", radialSelectAccept, false, Enum.KeyCode.ButtonR2) end end local function setOverrideMouseIconBehavior(override) if override then if InputService:GetLastInputType() == Enum.UserInputType.Gamepad1 then InputService.OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.ForceHide else InputService.OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.ForceShow end else InputService.OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.None end end toggleCoreGuiRadial = function(goingToSettings) isVisible = not gamepadSettingsFrame.Visible updateGuiVisibility() if isVisible then setOverrideMouseIconBehavior(true) lastInputChangedCon = InputService.LastInputTypeChanged:connect(function() setOverrideMouseIconBehavior(true) end) gamepadSettingsFrame.Visible = isVisible local settingsChildren = gamepadSettingsFrame:GetChildren() for i = 1, #settingsChildren do if settingsChildren[i]:IsA("GuiButton") then utility:TweenProperty(settingsChildren[i], "ImageTransparency", 1, 0, 0.1, utility:GetEaseOutQuad(), nil) end end local desiredSize = VRService.VREnabled and VR_FRAME_SIZE or NON_VR_FRAME_SIZE gamepadSettingsFrame:TweenSizeAndPosition(desiredSize, UDim2.new(0.5,0,0.5,0), Enum.EasingDirection.Out, Enum.EasingStyle.Back, 0.18, true, function() updateGuiVisibility() end) else if lastInputChangedCon ~= nil then lastInputChangedCon:disconnect() lastInputChangedCon = nil end local settingsChildren = gamepadSettingsFrame:GetChildren() for i = 1, #settingsChildren do if settingsChildren[i]:IsA("GuiButton") then utility:TweenProperty(settingsChildren[i], "ImageTransparency", 0, 1, 0.1, utility:GetEaseOutQuad(), nil) end end local desiredSize = VRService.VREnabled and VR_FRAME_HIDDEN_SIZE or NON_VR_FRAME_HIDDEN_SIZE gamepadSettingsFrame:TweenSizeAndPosition(desiredSize, UDim2.new(0.5,0,0.5,0), Enum.EasingDirection.Out, Enum.EasingStyle.Sine, 0.1, true, function() if not VRService.VREnabled then setOverrideMouseIconBehavior(false) end if not isVisible then GuiService:SetMenuIsOpen(false, GAMEPAD_MENU_KEY) end gamepadSettingsFrame.Visible = isVisible if vrPanel then vrPanel:SetVisible(false) end end) end if isVisible then setSelectedRadialButton(nil) GuiService:SetMenuIsOpen(true, GAMEPAD_MENU_KEY) bindAllRadialActions() else unbindAllRadialActions() end return gamepadSettingsFrame.Visible end local function setButtonEnabled(button, enabled) if radialButtons[button]["Disabled"] == not enabled then return end if button:FindFirstChild("Selected").Visible == true then setSelectedRadialButton(nil) end local vrEnabled = VRService.VREnabled if enabled then if vrEnabled then button.Image = vrSlotBackgroundImage else button.Image = string.gsub(button.Image, "rbxasset://textures/ui/Settings/Radial/Empty", "rbxasset://textures/ui/Settings/Radial/") end button.ImageTransparency = 0 button.RadialIcon.ImageTransparency = 0 else if vrEnabled then button.Image = vrSlotDisabledImage else button.Image = string.gsub(button.Image, "rbxasset://textures/ui/Settings/Radial/", "rbxasset://textures/ui/Settings/Radial/Empty") end button.ImageTransparency = 0 button.RadialIcon.ImageTransparency = 1 end radialButtons[button]["Disabled"] = not enabled end local function setButtonVisible(button, visible) button.Visible = visible if not visible then setButtonEnabled(button, false) end end local kidSafeHint = nil; local function getVRKidSafeHint() if not kidSafeHint then local text = businessLogic.GetVisibleAgeForPlayer(Players.LocalPlayer) local textSize = TextService:GetTextSize(text, 24, Enum.Font.SourceSansBold, Vector2.new(800,800)) local bubble = utility:Create'ImageLabel' { Name = "AccountTypeBubble"; Size = UDim2.new(0, textSize.x + 20, 0, 50); Image = "rbxasset://textures/ui/TopBar/Round.png"; ScaleType = Enum.ScaleType.Slice; SliceCenter = Rect.new(10, 10, 10, 10); ImageTransparency = 0.3; BackgroundTransparency = 1; } bubble.Position = UDim2.new(0.5, -bubble.Size.X.Offset/2, 1, 10); local accountTypeTextLabel = utility:Create'TextLabel'{ Name = "AccountTypeText"; Text = text; Size = UDim2.new(1, -20, 1, -20); Position = UDim2.new(0, 10, 0, 10); Font = Enum.Font.SourceSansBold; FontSize = Enum.FontSize.Size24; BackgroundTransparency = 1; TextColor3 = Color3.new(1,1,1); TextYAlignment = Enum.TextYAlignment.Center; TextXAlignment = Enum.TextXAlignment.Center; Parent = bubble; } kidSafeHint = bubble end return kidSafeHint end local function toggleVR(vrEnabled) if vrEnabled then gamepadSettingsFrame.Size = VR_FRAME_SIZE vrPanel = Panel3D.Get("GamepadMenu") vrPanel:SetEnabled(true) vrPanel:SetVisible(false) vrPanel:SetCanFade(false) vrPanel:ResizeStuds(PANEL_SIZE_STUDS, PANEL_SIZE_STUDS, PANEL_RESOLUTION) vrPanel:SetType(Panel3D.Type.Standard, { CFrame = CFrame.new(0, 0, 0.5) }) gamepadSettingsFrame.Parent = vrPanel:GetGUI() function vrPanel:OnUpdate(dt) if not vrPanel:IsVisible() then return end local lookAtPixel = vrPanel.lookAtPixel local lookAtScale = lookAtPixel / vrPanel.gui.AbsoluteSize local inputVector = (lookAtScale - Vector2.new(0.5, 0.5)) * 2 if inputVector.magnitude > 0.4 and inputVector.magnitude < 0.8 then local angle = math.deg(math.atan2(inputVector.X, -inputVector.Y)) if angle < 0 then angle = angle + 360 end local button = getSelectedObjectFromAngle(angle) if button then setSelectedRadialButton(button) end end end for button, info in pairs(radialButtons) do if info.VRSlot then local slotImages = vrSlotImages[info.VRSlot] button.Parent = gamepadSettingsFrame button.Image = info.Disabled and slotImages.disabled or slotImages.background button.Rotation = slotImages.rotation button.RadialIcon.Image = slotImages.icon button.RadialIcon.Position = UDim2.new(0.5, 0, 0.09, 0) button.RadialIcon.AnchorPoint = Vector2.new(0.5, 0.5) button.RadialIcon.Size = slotImages.iconSize button.RadialIcon.Rotation = -slotImages.rotation button.RadialLabel.Rotation = -slotImages.rotation button.RadialLabel.AnchorPoint = Vector2.new(0.5, 0.5) button.RadialLabel.Position = UDim2.new(0.5, 0, 0.5, 0) button.RadialBackground.Rotation = -slotImages.rotation button.RadialBackground.AnchorPoint = Vector2.new(0.5, 0.5) button.RadialBackground.Position = UDim2.new(0.5, 0, 0.5, 0) local selectedImage = button:FindFirstChild("Selected") if selectedImage then selectedImage.Image = slotImages.active end button.MouseFrame.Visible = false end end local healthbarFrame = utility:Create("Frame") { Parent = gamepadSettingsFrame, Position = UDim2.new(0.8, 0, 0, 0), Size = UDim2.new(0, 192, 0, 32), BackgroundTransparency = 1 } local hint = getVRKidSafeHint() hint.Parent = gamepadSettingsFrame local chatButton = radialButtonsByName.Chat if chatButton then setButtonEnabled(chatButton, false) end else gamepadSettingsFrame.Size = NON_VR_FRAME_SIZE if vrPanel then vrPanel:SetEnabled(false) end vrPanel = nil for button, info in pairs(radialButtons) do if info.Slot then local backgroundImage, activeImage, iconImage, iconPosition, iconSize = getImagesForSlot(info.Slot) if info.Disabled then backgroundImage = string.gsub(backgroundImage, "rbxasset://textures/ui/Settings/Radial/", "rbxasset://textures/ui/Settings/Radial/Empty") end button.Image = backgroundImage button.Rotation = 0 button.RadialIcon.Position = iconPosition button.RadialIcon.Size = iconSize button.RadialIcon.Image = iconImage button.RadialIcon.Rotation = 0 button.RadialIcon.AnchorPoint = Vector2.new(0, 0) button.MouseFrame.Visible = true else button.Parent = nil end end if kidSafeHint then kidSafeHint.Parent = nil end local chatButton = radialButtonsByName.Chat if chatButton then setButtonEnabled(chatButton, not isTenFootInterface) end end if gamepadSettingsFrame.Visible then toggleCoreGuiRadial() end end local emptySelectedImageObject = utility:Create'ImageLabel' { BackgroundTransparency = 1, Size = UDim2.new(1,0,1,0), Image = "" }; local function createRadialButton(name, text, slot, vrSlot, disabled, coreGuiType, activateFunc) local slotImage, selectedSlotImage, slotIcon, slotIconPosition, slotIconSize, mouseFrameSize, mouseFramePos = getImagesForSlot(slot) local radialButton = utility:Create'ImageButton' { Name = name, Position = UDim2.new(0.5,0,0.5,0), Size = UDim2.new(1,0,1,0), AnchorPoint = Vector2.new(0.5, 0.5), BackgroundTransparency = 1, Image = slotImage, ZIndex = 2, SelectionImageObject = emptySelectedImageObject, Selectable = false, Parent = gamepadSettingsFrame }; if disabled then radialButton.Image = string.gsub(radialButton.Image, "rbxasset://textures/ui/Settings/Radial/", "rbxasset://textures/ui/Settings/Radial/Empty") end local selectedRadial = utility:Create'ImageLabel' { Name = "Selected", Position = UDim2.new(0,0,0,0), Size = UDim2.new(1,0,1,0), BackgroundTransparency = 1, Image = selectedSlotImage, ZIndex = 2, Visible = false, Parent = radialButton }; local radialIcon = utility:Create'ImageLabel' { Name = "RadialIcon", Position = slotIconPosition, Size = slotIconSize, BackgroundTransparency = 1, Image = slotIcon, ZIndex = 3, ImageTransparency = disabled and 1 or 0, Parent = radialButton }; local nameLabel = utility:Create'TextLabel' { Size = UDim2.new(0,220,0,50), Position = UDim2.new(0.5, -110, 0.5, -25), BackgroundTransparency = 1, Text = text, Font = Enum.Font.SourceSansBold, FontSize = Enum.FontSize.Size14, TextColor3 = Color3.new(1,1,1), Name = "RadialLabel", Visible = false, ZIndex = 3, Parent = radialButton }; if not smallScreen then nameLabel.FontSize = Enum.FontSize.Size36 nameLabel.Size = UDim2.new(nameLabel.Size.X.Scale, nameLabel.Size.X.Offset, nameLabel.Size.Y.Scale, nameLabel.Size.Y.Offset + 4) end local nameBackgroundImage = utility:Create'ImageLabel' { Name = "RadialBackground", Size = nameLabel.Size, Position = nameLabel.Position + UDim2.new(0,0,0,2), BackgroundTransparency = 1, Image = "rbxasset://textures/ui/Settings/Radial/[email protected]", ScaleType = Enum.ScaleType.Slice, SliceCenter = Rect.new(24,4,130,42), ZIndex = 2, Parent = radialButton }; local mouseFrame = utility:Create'ImageButton' { Name = "MouseFrame", Position = mouseFramePos, Size = mouseFrameSize, ZIndex = 3, BackgroundTransparency = 1, SelectionImageObject = emptySelectedImageObject, Parent = radialButton }; mouseFrame.MouseEnter:connect(function() if not radialButtons[radialButton]["Disabled"] then setSelectedRadialButton(radialButton) end end) mouseFrame.MouseLeave:connect(function() setSelectedRadialButton(nil) end) mouseFrame.MouseButton1Click:connect(function() if selectedRadial.Visible then activateFunc() end end) radialButtons[radialButton] = { ["Function"] = activateFunc, ["Disabled"] = disabled, ["CoreGuiType"] = coreGuiType, ["Slot"] = slot, ["VRSlot"] = vrSlot } radialButtonsByName[name] = radialButton return radialButton end local function createGamepadMenuGui() --If we've already created the gamepadSettingsFrame, don't --do it again if gamepadSettingsFrame then return end gamepadSettingsFrame = utility:Create'Frame' { Name = "GamepadSettingsFrame", Position = UDim2.new(0.5,0,0.5,0), BackgroundTransparency = 1, BorderSizePixel = 0, Size = NON_VR_FRAME_SIZE, AnchorPoint = Vector2.new(0.5, 0.5), Visible = false, Parent = GuiRoot }; --------------------------------- -------- Settings Menu ---------- local function settingsFunc() toggleCoreGuiRadial(true) if isNewInGameMenuEnabled() then -- todo: move InGameMenu to a script global when removing isNewInGameMenuEnabled local InGameMenu = require(GuiRoot.Modules.InGameMenu) InGameMenu.openGameSettingsPage() else local MenuModule = require(GuiRoot.Modules.Settings.SettingsHub) MenuModule:SetVisibility(true, nil, MenuModule.Instance.GameSettingsPage, true, InGameMenuConstants.AnalyticsMenuOpenTypes.SettingsTriggered) end end local settingsRadial = createRadialButton("Settings", "Settings", 1, 1, false, nil, settingsFunc) settingsRadial.Parent = gamepadSettingsFrame --------------------------------- -------- Player List ------------ local function playerListFunc() if VRService.VREnabled then toggleCoreGuiRadial(true) if isNewInGameMenuEnabled() then -- todo: move InGameMenu to a script global when removing isNewInGameMenuEnabled local InGameMenu = require(GuiRoot.Modules.InGameMenu) InGameMenu.openPlayersPage() else local MenuModule = require(GuiRoot.Modules.Settings.SettingsHub) MenuModule:SetVisibility(true, nil, MenuModule.Instance.PlayersPage, true, InGameMenuConstants.AnalyticsMenuOpenTypes.PlayersTriggered) end else local PlayerListMaster = require(GuiRoot.Modules.PlayerList.PlayerListManager) if not PlayerListMaster:GetVisibility() then toggleCoreGuiRadial(true) PlayerListMaster:SetVisibility(true) else toggleCoreGuiRadial() end end end local playerListRadial = createRadialButton("PlayerList", "Playerlist", 2, 2, not StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType.PlayerList), Enum.CoreGuiType.PlayerList, playerListFunc) playerListRadial.Parent = gamepadSettingsFrame --------------------------------- -------- Emotes Menu ------------ local toggleEmotesFunc = function() toggleCoreGuiRadial() GuiService.MenuClosed:Wait() if EmotesModule:isOpen() then EmotesModule:close() else EmotesModule:open() end end local emotesRadialInfo = { Name = "Emotes", Text = "Emotes", Slot = 3, VrSlot = 4, Disabled = not StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType.EmotesMenu), CoreGuiType = Enum.CoreGuiType.EmotesMenu, ActivateFunc = toggleEmotesFunc, } local emotesRadial = createRadialButton( emotesRadialInfo.Name, emotesRadialInfo.Text, emotesRadialInfo.Slot, emotesRadialInfo.VrSlot, emotesRadialInfo.Disabled, emotesRadialInfo.CoreGuiType, emotesRadialInfo.ActivateFunc ) emotesRadial.Parent = gamepadSettingsFrame --------------------------------- ---------- Leave Game ----------- local function leaveGameFunc() toggleCoreGuiRadial(true) local MenuModule = require(GuiRoot.Modules.Settings.SettingsHub) MenuModule:SetVisibility(true, false, MenuModule.Instance.LeaveGamePage, true, InGameMenuConstants.AnalyticsMenuOpenTypes.LeaveGame) end local leaveGameText = "Leave Game" if FFlagUpdateSettingsHubGameText then leaveGameText = RobloxTranslator:FormatByKey("InGame.HelpMenu.Leave") end local leaveGameRadial = createRadialButton("LeaveGame", leaveGameText, 4, 5, false, nil, leaveGameFunc) leaveGameRadial.Parent = gamepadSettingsFrame --------------------------------- ---------- Backpack ------------- local function backpackFunc() toggleCoreGuiRadial(true) local BackpackModule = require(GuiRoot.Modules.BackpackScript) BackpackModule:OpenClose() end local backpackRadial = createRadialButton("Backpack", "Backpack", 5, 6, not StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType.Backpack), Enum.CoreGuiType.Backpack, backpackFunc) backpackRadial.Parent = gamepadSettingsFrame --------------------------------- ------------ Chat --------------- local function chatFunc() toggleCoreGuiRadial() local ChatModule = require(GuiRoot.Modules.ChatSelector) ChatModule:ToggleVisibility() end local chatRadial = createRadialButton("Chat", "Chat", 6, 8, not StarterGui:GetCoreGuiEnabled(Enum.CoreGuiType.Chat), Enum.CoreGuiType.Chat, chatFunc) if isTenFootInterface then setButtonEnabled(chatRadial, false) end chatRadial.Parent = gamepadSettingsFrame -------------------------------- ------ Recenter (VR ONLY) ------ local function recenterFunc() toggleCoreGuiRadial() local RecenterModule = require(GuiRoot.Modules.VR.Recenter) RecenterModule:SetVisible(not RecenterModule:IsVisible()) end local recenterRadial = createRadialButton("Recenter", "Recenter", nil, 3, false, nil, recenterFunc) -------------------------------- ------- 2D UI (VR ONLY) -------- local function toggleUIFunc() toggleCoreGuiRadial() local UserGuiModule = require(GuiRoot.Modules.VR.UserGui) UserGuiModule:SetVisible(not UserGuiModule:IsVisible()) end local toggleUIRadial = createRadialButton("ToggleUI", "Toggle UI", nil, 7, false, nil, toggleUIFunc) --------------------------------- --------- Close Button ---------- local closeHintFrame = utility:Create'Frame' { Name = "CloseHintFrame", Position = UDim2.new(1,10,1,10), Size = UDim2.new(0, 103, 0, 60), AnchorPoint = Vector2.new(0.5, 0.5), BackgroundTransparency = 1, Parent = gamepadSettingsFrame } local closeHintImage = utility:Create'ImageLabel' { Name = "CloseHint", Position = UDim2.new(0,0,0.5,0), Size = UDim2.new(1,0,1,0), AnchorPoint = Vector2.new(0, 0.5), BackgroundTransparency = 1, Image = "rbxasset://textures/ui/Settings/Help/BButtonDark.png", Parent = closeHintFrame } utility:Create'UIAspectRatioConstraint' { AspectRatio = 1, Parent = closeHintImage } if isTenFootInterface then closeHintImage.Image = "rbxasset://textures/ui/Settings/Help/[email protected]" closeHintFrame.Size = UDim2.new(0,133,0,90) end local closeHintText = utility:Create'TextLabel' { Name = "closeHintText", Position = UDim2.new(1,0,0.5,0), Size = UDim2.new(0,43,0,24), AnchorPoint = Vector2.new(1, 0.5), Font = Enum.Font.SourceSansBold, FontSize = Enum.FontSize.Size24, BackgroundTransparency = 1, Text = "Back", TextColor3 = Color3.new(1,1,1), TextXAlignment = Enum.TextXAlignment.Left, Parent = closeHintFrame } if isTenFootInterface then closeHintText.FontSize = Enum.FontSize.Size36 end --Remove with FIntNewInGameMenuPercentRollout ------------------------------------------ --------- Stop Recording Button ---------- --todo: enable this when recording is not a verb --[[local stopRecordingImage = utility:Create'ImageLabel' { Name = "StopRecordingHint", Position = UDim2.new(0,-100,1,10), Size = UDim2.new(0,61,0,61), BackgroundTransparency = 1, Image = "rbxasset://textures/ui/Settings/Help/YButtonDark.png", Visible = recordPage:IsRecording(), Parent = gamepadSettingsFrame } local stopRecordingText = utility:Create'TextLabel' { Name = "stopRecordingHintText", Position = UDim2.new(1,10,0.5,-12), Size = UDim2.new(0,43,0,24), Font = Enum.Font.SourceSansBold, FontSize = Enum.FontSize.Size24, BackgroundTransparency = 1, Text = "Stop Recording", TextColor3 = Color3.new(1,1,1), TextXAlignment = Enum.TextXAlignment.Left, Parent = stopRecordingImage } recordPage.RecordingChanged:connect(function(isRecording) stopRecordingImage.Visible = isRecording end)]] GuiService:AddSelectionParent(HttpService:GenerateGUID(false), gamepadSettingsFrame) gamepadSettingsFrame:GetPropertyChangedSignal("Visible"):connect(function() if not gamepadSettingsFrame.Visible then unbindAllRadialActions() end end) VRService:GetPropertyChangedSignal("VREnabled"):connect(function() toggleVR(VRService.VREnabled) end) toggleVR(VRService.VREnabled) end local function isCoreGuiDisabled() for _, enumItem in pairs(Enum.CoreGuiType:GetEnumItems()) do if StarterGui:GetCoreGuiEnabled(enumItem) then return false end end return true end function updateGuiVisibility() if VRService.VREnabled and vrPanel and isVisible then vrPanel:SetVisible(true, true) end local children = gamepadSettingsFrame:GetChildren() for i = 1, #children do if children[i]:FindFirstChild("RadialIcon") then children[i].RadialIcon.Visible = isVisible end if children[i]:FindFirstChild("RadialLabel") and not isVisible then children[i].RadialLabel.Visible = isVisible end if children[i]:FindFirstChild("RadialBackground") and not isVisible then children[i].RadialBackground.Visible = isVisible end end end doGamepadMenuButton = function(name, state, input) if state ~= Enum.UserInputState.Begin then return end if game.IsLoaded then if not toggleCoreGuiRadial() then unbindAllRadialActions() end end end if InputService:GetGamepadConnected(Enum.UserInputType.Gamepad1) then createGamepadMenuGui() else InputService.GamepadConnected:connect(function(gamepadEnum) if gamepadEnum == Enum.UserInputType.Gamepad1 then createGamepadMenuGui() end end) end local defaultLoadingGuiRemovedConnection = nil local loadedConnection = nil local isLoadingGuiRemoved = false local isPlayerAdded = false local function updateRadialMenuActionBinding() if isLoadingGuiRemoved and isPlayerAdded then createGamepadMenuGui() ContextActionService:BindCoreAction(toggleMenuActionName, doGamepadMenuButton, false, Enum.KeyCode.ButtonStart) end end local function handlePlayerAdded() loadedConnection:disconnect() isPlayerAdded = true updateRadialMenuActionBinding() end loadedConnection = Players.PlayerAdded:connect( function(plr) if Players.LocalPlayer and plr == Players.LocalPlayer then handlePlayerAdded() end end ) if Players.LocalPlayer then handlePlayerAdded() end local function handleDefaultLoadingGuiRemoved() if defaultLoadingGuiRemovedConnection then defaultLoadingGuiRemovedConnection:disconnect() end isLoadingGuiRemoved = true updateRadialMenuActionBinding() end if game:GetService("ReplicatedFirst"):IsDefaultLoadingGuiRemoved() then handleDefaultLoadingGuiRemoved() elseif RunService:IsClient() and RunService:IsServer() then handleDefaultLoadingGuiRemoved() else defaultLoadingGuiRemovedConnection = game:GetService("ReplicatedFirst").DefaultLoadingGuiRemoved:connect(handleDefaultLoadingGuiRemoved) end -- some buttons always show/hide depending on platform local function canChangeButtonVisibleState(buttonType) if isTenFootInterface then if buttonType == Enum.CoreGuiType.Chat or buttonType == Enum.CoreGuiType.PlayerList then return false end end if VRService.VREnabled then if buttonType == Enum.CoreGuiType.Chat then return false end end if buttonType == Enum.CoreGuiType.EmotesMenu then return false end return true end StarterGui.CoreGuiChangedSignal:connect(function(coreGuiType, enabled) for button, buttonTable in pairs(radialButtons) do local buttonType = buttonTable["CoreGuiType"] if buttonType then if coreGuiType == buttonType or coreGuiType == Enum.CoreGuiType.All then if canChangeButtonVisibleState(buttonType) then setButtonEnabled(button, enabled) end end end end end) local function onEmotesMenuVisibilityChangedSignal(emotesMenuVisible) for button, buttonTable in pairs(radialButtons) do local buttonType = buttonTable["CoreGuiType"] if buttonType and buttonType == Enum.CoreGuiType.EmotesMenu then setButtonEnabled(button, emotesMenuVisible) end end end EmotesModule.MenuVisibilityChanged.Event:Connect(onEmotesMenuVisibilityChangedSignal) onEmotesMenuVisibilityChangedSignal(EmotesModule.MenuIsVisible)
-- -------------------- -- TellMeWhen -- Originally by Nephthys of Hyjal <[email protected]> -- Other contributions by: -- Sweetmms of Blackrock, Oozebull of Twisting Nether, Oodyboo of Mug'thol, -- Banjankri of Blackrock, Predeter of Proudmoore, Xenyr of Aszune -- Currently maintained by -- Cybeloras of Aerie Peak/Detheroc/Mal'Ganis -- -------------------- if not TMW then return end local TMW = TMW local L = TMW.L local print = TMW.print local type, pairs, gsub, strfind, strmatch, strsplit, strtrim, tonumber, tremove, ipairs, tinsert, CopyTable, setmetatable = type, pairs, gsub, strfind, strmatch, strsplit, strtrim, tonumber, tremove, ipairs, tinsert, CopyTable, setmetatable local tconcat = table.concat local GetSpellInfo = GetSpellInfo local strlowerCache = TMW.strlowerCache local _, pclass = UnitClass("player") --------------------------------- -- Spell String Parsing Functions --------------------------------- -- These functions are as old as TMW itself (except for duration stuff). They have changed much over the years, -- but they're one of the few things that are still here in some form. local function splitSpellAndDuration(str) local spell, duration = strmatch(str, "(.-):([%d:%s%.]*)$") if not spell then return str, 0 end if not duration then duration = 0 else duration = tonumber( TMW.toSeconds(duration:trim(" :;.")) ) end return spell, duration end local function parseSpellsString(setting, doLower, keepDurations) local buffNames = TMW:SplitNames(setting) -- Get a table of everything if doLower then buffNames = TMW:LowerNames(buffNames) end --INSERT EQUIVALENCIES --start at the end of the table, that way we dont have to worry --about increasing the key of buffNames to work with every time we insert something local k = #buffNames while k > 0 do local eqtt = TMW:EquivToTable(buffNames[k]) -- Get the table form of the equivalency string if eqtt then local n = k --point to start inserting the values at tremove(buffNames, k) --take the actual equavalancey itself out, because it isnt an actual spell name or anything for z, x in ipairs(eqtt) do tinsert(buffNames, n, x) --put the names into the main table n = n + 1 --increment the point of insertion end else k = k - 1 --there is no equivalency to insert, so move backwards one key towards zero to the next key end end -- REMOVE DUPLICATES TMW.tRemoveDuplicates(buffNames) -- Remove entries that the user has chosed to omit by using a "-" prefix. local k = #buffNames while k > 0 do local v = buffNames[k] if (type(v) == "string" and v:match("^%-")) or (type(v) == "number" and v < 0) then tremove(buffNames, k) local thingToRemove = tostring(v):match("^%-%s*(.*)"):lower() local spellToRemove, durationToRemove = splitSpellAndDuration(thingToRemove) local i = 1 local removed while buffNames[i] do local name = tostring(buffNames[i]):lower() local spell, duration = splitSpellAndDuration(name) if spellToRemove == spell and durationToRemove == duration then tremove(buffNames, i) removed = true else i = i + 1 end end if not removed then TMW:Printf(L["SPELL_EQUIV_REMOVE_FAILED"], thingToRemove, tconcat(buffNames, "; ")) end else -- The entry was valid, so move backwards towards the beginning. k = k - 1 end end -- Remove invalid SpellIDs for k = #buffNames, 1, -1 do local v = buffNames[k] local spell, duration = splitSpellAndDuration(v) if (tonumber(spell) or 0) >= 2^31 or duration >= 2^31 then -- Invalid spellID or duration. Remove it to prevent integer overflow errors. tremove(buffNames, k) TMW:Warn(L["ERROR_INVALID_SPELLID2"]:format(v)) end end -- REMOVE SPELL DURATIONS (FOR UNIT COOLDOWNS/ICDs) -- THIS MUST HAPPEN LAST or else the duration array and spell array can get mismatched. if not keepDurations then for k, buffName in pairs(buffNames) do local spell, duration = splitSpellAndDuration(buffName) buffNames[k] = tonumber(spell) or spell end end return buffNames end parseSpellsString = TMW:MakeFunctionCached(parseSpellsString) local function getSpellNames(setting, doLower, firstOnly, toname, hash, allowRenaming) local buffNames = parseSpellsString(setting, doLower, false) -- buffNames MUST BE COPIED because the return from parseSpellsString is cached. buffNames = CopyTable(buffNames) if hash then local hash = {} for k, v in ipairs(buffNames) do if toname and (allowRenaming or tonumber(v)) then v = GetSpellInfo(v or "") or v -- Turn the value into a name if needed end v = TMW:LowerNames(v) -- Put the final value in the table as well (may or may not be the same as the original value). -- Value should be NameArrray's key, for use with the duration table. hash[v] = k end return hash end if toname then if firstOnly then -- Turn the first value into a name and return it local ret = buffNames[1] or "" if (allowRenaming or tonumber(ret)) then ret = GetSpellInfo(ret) or ret end if doLower then ret = TMW:LowerNames(ret) end return ret else -- Convert everything to a name for k, v in ipairs(buffNames) do if (allowRenaming or tonumber(v)) then buffNames[k] = GetSpellInfo(v or "") or v end end if doLower then TMW:LowerNames(buffNames) end return buffNames end end if firstOnly then local ret = buffNames[1] or "" return ret end return buffNames end local function getSpellDurations(setting) local NameArray = parseSpellsString(setting, false, true) local DurationArray = CopyTable(NameArray) -- EXTRACT SPELL DURATIONS for k, buffName in pairs(NameArray) do local dur = strmatch(buffName, ".-:([%d:%s%.]*)$") if not dur then DurationArray[k] = 0 else DurationArray[k] = tonumber( TMW.toSeconds(dur:trim(" :;.")) ) end end return DurationArray end --------------------------------- -- TMW.C.SpellSet --------------------------------- local tableArgs = { -- lower, first, toname, hash First = { 1, 1, nil, nil }, FirstString = { 1, 1, 1, nil }, Array = { 1, nil, nil, nil }, StringArray = { 1, nil, 1, nil }, Hash = { 1, nil, nil, 1 }, StringHash = { 1, nil, 1, 1 }, -- lower, first, toname, hash FirstNoLower = { nil, 1, nil, nil }, FirstStringNoLower = { nil, 1, 1, nil }, ArrayNoLower = { nil, nil, nil, nil }, StringArrayNoLower = { nil, nil, 1, nil }, HashNoLower = { nil, nil, nil, 1 }, StringHashNoLower = { nil, nil, 1, 1 }, -- DUrations is kept in this table because it should also be cleared -- every time the cache needs to be reset (handled in the :Wipe() method). -- It is handled specially, though. Durations = true, } local __index_old = nil TMW:NewClass("SpellSet"){ instancesByName = { -- Keyed here by allowRenaming [true] = setmetatable({}, {__mode='kv'}), [false] = setmetatable({}, {__mode='kv'}), }, OnFirstInstance = function(self) self:MakeInstancesWeak() __index_old = self.instancemeta.__index local meta = {} for k, v in pairs(self.instancemeta) do meta[k] = v end meta.__index = self.__index self.betterMeta = meta end, OnNewInstance = function(self, name, allowRenaming) allowRenaming = not not allowRenaming -- make sure its a boolean self.Name = name self.AllowRenaming = allowRenaming if name then self.instancesByName[allowRenaming][name] = self end setmetatable(self, self.betterMeta) end, __index = function(self, k) local v = __index_old[k] if v then return v end if k == "Durations" then self[k] = getSpellDurations(self.Name) return self[k] end local args = tableArgs[k] if args then self[k] = getSpellNames(self.Name, args[1], args[2], args[3], args[4], self.AllowRenaming) return self[k] end end, Wipe = function(self) for k, v in pairs(self) do if tableArgs[k] then self[k] = nil end end end, } TMW:RegisterCallback("TMW_GLOBAL_UPDATE", function() -- We need to wipe the stored objects/strings on every TMW_GLOBAL_UPDATE because of issues with -- spells that replace other spells in different specs, like Corruption/Immolate. -- TMW_GLOBAL_UPDATE might fire a little too often for this, but it is a surefire way to prevent issues that should -- hold up through out all future game updates because TMW_GLOBAL_UPDATE should always react to any changes in spec/talents/etc for _, instance in pairs(TMW.C.SpellSet.instances) do instance:Wipe() end end) --- Returns an instance of {{{TMW.C.SpellSet}}} for the given spellString. -- The following can be accessed as members of the {{{TMW.C.SpellSet}}}: -- * -- * {{{SpellSet.First}}} - The first spell in the spellString. -- * {{{SpellSet.FirstString}}} - The first spell in the spellString, converted to a name if given as an ID. -- * {{{SpellSet.Array}}} - An array of all spells in the spellString. -- * {{{SpellSet.StringArray}}} - SpellSet.Array with any spellIDs converted to names. -- * {{{SpellSet.Hash}}} - A dictionary of all spells in the spellString, with the values in the table being their index in the spellString (and their index in indexed tables of the SpellSet). -- * {{{SpellSet.StringHash}}} - SpellSet.Hash with any spellIDs converted to names. -- * {{{SpellSet.Durations}}} - An array of all the durations of spells in the spellString using the "Spell: Duration" syntax. Filled with zeroes for spells that don't use the duration synxtax. -- Furthermore, all of the above, with the exception of SpellSet.Durations, may also have "NoLower" appended to prevent strlower()ing of any strings. E.g. {{{SpellSet.StringArrayNoLower}}}. -- @arg spellString [string] A semicolon-delimited list of spells that -- will be parsed and made available in various forms by the {{{TMW.C.SpellSet}}}. -- @arg allowRenaiming [boolean] True if the SpellSet should attempt to rename spells -- that were inputted by name but have different names because of the player's currently learned spells. -- @return [TMW.C.SpellSet] An instance of {{{TMW.C.SpellSet}}} for the requested spells. function TMW:GetSpells(spellString, allowRenaming) TMW:ValidateType("2 (spellString)", "TMW:GetSpells(spellString, allowRenaming)", spellString, "string;number") -- Make sure that allowRenaming is a boolean. allowRenaming = not not allowRenaming return TMW.C.SpellSet.instancesByName[allowRenaming][spellString] or TMW.C.SpellSet:New(spellString, allowRenaming) end --------------------------------- -- Misc Spell Name Helper Funcs --------------------------------- local loweredbackup = {} --- Converts a string, or all values of a table, to lowercase. Numbers are kept as numbers. -- The original case is saved so that it can be used by TMW:RestoreCase() to restore the capitalization of spells that have been lowered. -- @arg str [string|table] The string or table of spell names to strlower. -- @return Returns what was passed in after strlowering it. function TMW:LowerNames(str) if type(str) == "table" then -- Handle a table with recursion for k, v in pairs(str) do str[k] = TMW:LowerNames(v) end return str end local str_lower = strlowerCache[str] -- Dispel types retain their capitalization. Restore it here. for ds in pairs(TMW.DS) do if strlowerCache[ds] == str_lower then return ds end end if type(str_lower) == "string" then if loweredbackup[str_lower] then -- Dont replace names that are proper case with names that arent. -- Generally, assume that strings with more capitals after non-letters are more proper than ones with less local _, oldcount = gsub(loweredbackup[str_lower], "[^%a]%u", "%1") local _, newcount = gsub(str, "[^%a]%u", "%1") -- Check the first letter of each string for a capital if strfind(loweredbackup[str_lower], "^%u") then oldcount = oldcount + 1 end if strfind(str, "^%u") then newcount = newcount + 1 end -- The new string has more than the old, so use it instead if newcount > oldcount then loweredbackup[str_lower] = str end else -- There wasn't a string before, so set the base loweredbackup[str_lower] = str end end return str_lower end --- Attempts to restore the capitalization of a spell name that has been strlowered. -- Numbers are returned immediately. Otherwise, the cache of lowered names from TMW:LowerNames() -- is checked, and if it isn't in there, TMW.strlowerCache is scanned for an original string. function TMW:RestoreCase(str) if type(str) == "number" then return str elseif loweredbackup[str] then return loweredbackup[str], str else for original, lowered in pairs(strlowerCache) do if lowered == str then return original, str end end return str end end --- Generates a table of all the spells contained in a spell equivalency. -- @arg name [string] The equivalency to generate a table for. -- @return Returns the table of all the spells of the equivalency if it was valid, or nil if it wasn't. function TMW:EquivToTable(name) -- Everything in this function is handled as lowercase to prevent issues with user input capitalization. -- DONT use TMW:LowerNames() here, because the input is not the output name = strlowerCache[name] -- See if the string being checked has a duration attached to it -- (It really shouldn't because there is currently no point in doing so, -- But a user did try this and made a bug report, so I fixed it anyway local eqname, duration = strmatch(name, "(.-):([%d:%s%.]*)$") -- If there was a duration, then replace the old name with the actual name without the duration attached name = eqname or name local tbl -- Iterate over all of TMW.BE's sub-categories ('buffs', 'debuffs', 'casts', etc) for k, v in pairs(TMW.BE) do -- Iterate over each equivalency in the category for equiv, t in pairs(v) do if strlowerCache[equiv] == name then -- We found a matching equivalency, so stop searching. tbl = t break end end if tbl then break end end -- If we didnt find an equivalency string then get out if not tbl then return end -- For each spell in the equivalency: for a, b in pairs(tbl) do -- Take off trailing spaces local new = strtrim(b) -- Make sure it is a number if it can be new = tonumber(new) or new -- Tack on the duration that should be applied to all spells if there was a duration if duration then new = new .. ":" .. duration end -- Done. Stick the new value in the return table. tbl[a] = new end return tbl end TMW:MakeSingleArgFunctionCached(TMW, "EquivToTable") --------------------------------- -- Constant spell data --------------------------------- if pclass == "DRUID" then TMW.COMMON.CurrentClassTotems = { name = GetSpellInfo(145205), desc = L["ICONMENU_TOTEM_GENERIC_DESC"]:format(GetSpellInfo(145205)), { hasVariableNames = false, name = GetSpellInfo(145205), texture = GetSpellTexture(145205) } } elseif pclass == "MAGE" then TMW.COMMON.CurrentClassTotems = { name = GetSpellInfo(116011), desc = L["ICONMENU_TOTEM_GENERIC_DESC"]:format(GetSpellInfo(116011)), { hasVariableNames = false, name = GetSpellInfo(116011), texture = GetSpellTexture(116011) } } elseif pclass == "PALADIN" then TMW.COMMON.CurrentClassTotems = { name = GetSpellInfo(26573), desc = L["ICONMENU_TOTEM_GENERIC_DESC"]:format(GetSpellInfo(26573)), { hasVariableNames = false, name = GetSpellInfo(26573), texture = GetSpellTexture(26573) } } elseif pclass == "MONK" then TMW.COMMON.CurrentClassTotems = { name = L["ICONMENU_STATUE"], desc = L["ICONMENU_TOTEM_GENERIC_DESC"]:format(L["ICONMENU_STATUE"]), { hasVariableNames = false, name = L["ICONMENU_STATUE"], texture = function() if GetSpecialization() == 1 then return GetSpellTexture(163177) -- black ox else return GetSpellTexture(115313) -- jade serpent end end, } } elseif pclass == "DEATHKNIGHT" then local cachedName = TMW:TryGetNPCName(27829) local name = function() if cachedName then return cachedName end cachedName = TMW:TryGetNPCName(27829) return cachedName end TMW.COMMON.CurrentClassTotems = { name = name, desc = function() return L["ICONMENU_TOTEM_GENERIC_DESC"]:format(name()) end, texture = GetSpellTexture(49206), [3] = { -- wow blizzard, so nice. put the gargoyle in slot 3 why dontcha. hasVariableNames = false, name = name, texture = GetSpellTexture(49206), } } else -- This includes shamans now in Legion - the elements of totems is no longer a notion. TMW.COMMON.CurrentClassTotems = { name = L["ICONMENU_TOTEM"], desc = L["ICONMENU_TOTEM_DESC"], { hasVariableNames = true, name = L["GENERICTOTEM"]:format(1), texture = "Interface\\ICONS\\ability_shaman_tranquilmindtotem" }, { hasVariableNames = true, name = L["GENERICTOTEM"]:format(2), texture = "Interface\\ICONS\\ability_shaman_tranquilmindtotem" }, { hasVariableNames = true, name = L["GENERICTOTEM"]:format(3), texture = "Interface\\ICONS\\ability_shaman_tranquilmindtotem" }, { hasVariableNames = true, name = L["GENERICTOTEM"]:format(4), texture = "Interface\\ICONS\\ability_shaman_tranquilmindtotem" }, { hasVariableNames = true, name = L["GENERICTOTEM"]:format(5), texture = "Interface\\ICONS\\ability_shaman_tranquilmindtotem" }, } end
-- Array que contiene los callbacks de la pantalla local funcs = {} local name = "intro" -- Callbacks function funcs:init(...) end function funcs:update(dt) if TIME > 0 then if not savm:getLanguage(SAVEDATA) then sm:set("languageSelection") else sm:set("mainMenu") end end end function funcs:draw() love.graphics.print("LOADING", 0, 0) end function funcs:mousereleased(x, y, button, isTouch) end return Screen(name, funcs)
AddCSLuaFile() SWEP.PrintName = "ПКМ" SWEP.Category = "Call of Pripyat" SWEP.Base = "weapon_cop_base" SWEP.Slot = 3 SWEP.SlotPos = 2 SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.ViewModel = "models/wick/weapons/stalker/stcopwep/pkm_model.mdl" SWEP.WorldModel = "models/wick/weapons/stalker/stcopwep/w_pkm_model.mdl" SWEP.ViewModelFOV = 60 SWEP.ViewModelFlip = false SWEP.HoldType = "ar2" SWEP.Damage = 50 SWEP.RPM = 525 SWEP.Accuracy = 68 SWEP.Handling = 87 SWEP.Primary.ClipSize = 100 SWEP.Primary.DefaultClip = 100 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "762x54" SWEP.OriginPos = Vector(-2, -1, -8) SWEP.OriginAng = Vector(3, 0, 0) SWEP.AimPos = Vector(-7.759, 1, -6.59) SWEP.AimAng = Vector(-0.1, 0, 0) SWEP.SilencerBone = "wpn_silencer" SWEP.ScopeBone = "wpn_scope" SWEP.SprintAnim = "idle_sprint" SWEP.ScopeTexture = "wpn_crosshair" SWEP.SilencerMode = 0 SWEP.ScopeMode = 0 SWEP.AimTime = 0.2 SWEP.DeployTime = 0.6 SWEP.ReloadTime = 7.6 SWEP.ReloadFillTime = 5 SWEP.CanZoom = true SWEP.ZoomCrosshair = false SWEP.ReloadType = 0 SWEP.ZoomFOV = 64 SWEP.ScopeFOV = 25 SWEP.HiddenBones = { "wpn_launcher" } SWEP.FireSound = "COPPKM.pkm_shoot" SWEP.EmptySound = "COPPKM.pkm_empty" SWEP.ReloadSound = "COPPKM.pkm_reload" SWEP.DeploySound = "COPPKM.pkm_draw" SWEP.HolsterSound = "COPPKM.pkm_holster"
local SSort = require(game.ReplicatedStorage.Shared.SSort) local RandomLua = require(game.ReplicatedStorage.Shared.RandomLua) local SPList = {} local rand function SPList:new() local self = {} self._table = {} function self:push_back(element) self._table[#self._table + 1] = element return #self._table end function self:push_front(element) table.insert(self._table, 1, element) return #self._table end function self:push_back_table_list(arr) assert(type(arr) == "table") for i = 1, #arr do self:push_back(arr[i]) end return self end function self:push_back_from_list(list) for i = 1, list:count() do self:push_back(list:get(i)) end return self end function self:find(val, fncmp) for i = 1, #self._table do if fncmp then if fncmp(self._table[i], val) then return i end elseif self._table[i] == val then return i end end return -1 end function self:remove(element, fncmp) local i = self:find(element, fncmp) if i ~= -1 then self:remove_at(i) return true end return false end function self:contains(val) local find = self:find(val, function(a, b) return a == b end) return find ~= -1 end function self:back() return self._table[#self._table] end function self:pop_back() local rtv = self._table[#self._table] self._table[#self._table] = nil return rtv end function self:pop_front() local rtv = self:get(1) self:remove_at(1) return rtv end function self:get(i) return self._table[i] end function self:count() return #self._table end function self:remove_at(i) table.remove(self._table, i) end function self:clear() while self:count() > 0 do self:pop_back() end end function self:sort(sortfn) SSort:sort(self._table, function(a, b) local rtv = sortfn(a, b) if type(rtv) == "number" then if rtv > 0 then return true else return false end end return rtv end) end function self:random() if rand == nil then rand = RandomLua.mwc(os.time()) end local i = rand:rand_rangei(1, self:count() + 1) return self:get(i) end local function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == "table" then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else copy = orig end return copy end function self:table_copy() return deepcopy(self._table) end return self end return SPList
--[[ Swaggy Jenkins Jenkins API clients generated from Swagger / Open API specification OpenAPI spec version: 1.1.1 Contact: [email protected] Generated by: https://openapi-generator.tech ]] -- input_step_impl class local input_step_impl = {} local input_step_impl_mt = { __name = "input_step_impl"; __index = input_step_impl; } local function cast_input_step_impl(t) return setmetatable(t, input_step_impl_mt) end local function new_input_step_impl(_class, _links, id, message, ok, parameters, submitter) return cast_input_step_impl({ ["_class"] = _class; ["_links"] = _links; ["id"] = id; ["message"] = message; ["ok"] = ok; ["parameters"] = parameters; ["submitter"] = submitter; }) end return { cast = cast_input_step_impl; new = new_input_step_impl; }
local KDL = foundation_kdl.KDL local Encoder = {} -- TODO: implement Encode.encode/1 function Encoder.encode() end KDL.Encoder = Encoder
--[[ This file contains 4 examples showing off the various features of ActorFrameTextures. Drop this into any Screen's Decorations or Overlay to see the examples. --]] -- Choose which example you'd like to see local ExampleToShow = 1; -- Example 1: An ActorFrameTexture draws 3 quads and then hides itself. All of the quads are the same size, but two of them extend -- off the edge of the texture. A sprite draws the texture, which begins scrolling the texture after 2 seconds. local Example1_AlphaBuffer = true; -- Change this to see the effect of the AlphaBuffer. The white background is to demonstate this. -- Example 2: An ActorFrameTexture draws a spinning ActorFrame containing 3 color-channging quads. The texture is drawn by a sprite. local Example2_PreserveTexture = false; -- Change this to see the effect of PreserveTexture. -- Example 3: This example shows how the Float property of ActorFrameTexture works. An ActorFrameTexture draws a white quad, -- and then draws 3 quads on top of it all using "BlendMode_Add", each with either R, G, or B. Change the diffuse to see different -- colors show up as a result of the texture having RGB values greater than 1. local Example3_Diffuse = { 1,0.5,1,1 } -- Note that with Green of 50%, there is still a white rectangle where the Green square intersect the background white square. -- Example 4: Use a pair of AFTs to draw an object with a fading trail behind it. This example is a bit odd, in that the length of the -- trail ends up depending heavily on frame rate. This will look fairly different with and without VSync on. Holding tab or ~ will also -- change the length. --[[ ActorFrameTexture Explained: ActorFrameTexture is like a regular ActorFrame except that it draws to a texture instead of drawing to the screen( the way all other actors draw ). Other actor classes such as Sprite and ActorMultiVertex can draw the texture and maniplate it in ways that you cannot normally manipulate an ActorFrame. Because it is not drawing to the screen, an ActorFrameTexture's postion, rotation, and zoom have no affect. Diffuse and glow are applied to the children of an ActorFrameTexture the same way they are applied to the children of an ActorFrame. Additionally, an ActorFrameTexture can draw to it's texture at any time, by calling the Actor method Draw. For all other Actor classes, the Draw method will have no effect if called outside of the Screen's draw cycle. ActorFrameTextures draw only actors or parts of actors that are located within the range x = 0 to x = <width> and y = 0 to y = <height>. If an actor is sitting at x = 0 inside the ActorFrameTexture, only the right half of the Actor will draw. The SetWidth and SetHeight methods are used to set the width and height. They are explained in more detail below. An ActorFrameTexture can be used to cache 'expensive to draw' ensembles of objects by drawing them once to the texture, hiding the AFT, and then having a single sprite draw that texture instead. ActorFrameTexture methods: The follow methods have effect only if used BEFORE the 'Create' method. EnableAlphaBuffer( boolean ) - The texture can have transparency if this is set true. If false it will render over a black background. - See example 1 below. EnableDepthBuffer( boolean ) - If true the texture is created with a zbuffer. This allows masking to occur while rendering to the texture. Both - mask source and mask destination must drawn while rendering to the texture in order to have any effect. Regardless - of this setting, masks drawn before rendering to the texture has begun will not affect objects drawn while rendering - to the texture, and masks drawn while rending to the texture will not affect objects drawn after rendering to the - texture has finished. EnableFloat( boolean ) - This allows the values ( RGB ) to go outside the range [0,1] when using Blend modes. See example 3. SetTextureName( string ) - This allows the created texture to be called by name. - This is used in all of the examples below. SetHeight( float ) and SetWidth( float ) - These methods belong to the Actor class, but the properties they set are used in a specific way by ActorFrameTexture. - These methods are used to set the size of the created texture. The actual texture will have its dimensions rounded up - to the next power of two, but only the portion within the chose height and width will be rendered to. Create() - This creates the texture with the properties set by the above methods. Calling any of those methods after calling - create will have no effect. The following methods can be used any time. EnablePreserveTexture( boolean ) - If this is false(default) the texture will be cleared before each time the AFT renders to it. If this is true, the AFT - will render on top of the existing texture without clearing it first. This can be changed dynamically after the texture - has been created. - See example 2. GetTexture() - This returns the RageTextureRenderTarget object created with the Create method. You can use with the "SetTexture" methods - of other Actor classes including Sprite and ActorMultiVertex. This is the only way to access the texture if the texture - was created without using SetTextureName. - - This RageTextureRenderTarget has two unique methods of it's own: BeginRenderingTo and FinishRenderingTo. When it's parent - ActorFrameTexture draws it will automatically call these methods, before it begins drawing and after it finishes respectively. - These methods allow you to use a DrawFunction on any ActorFrame's to render to an AFT's texture, and there are several powerful - techinques which take advantage of this. ]] local Examples = { } Examples[1] = Def.ActorFrame{ Def.Quad{ InitCommand=cmd(FullScreen) }; -- a blank background. Def.ActorFrameTexture{ InitCommand=function(self) self:SetTextureName( "Example 1" ) self:SetWidth( 128 ); self:SetHeight( 128 ); self:EnableAlphaBuffer( Example1_AlphaBuffer ); self:Create(); -- The ActorFrameTexture only needs to draw once, so hide it after the first draw. self:Draw() self:hibernate(math.huge) end; Def.ActorFrame{ Name = "Draw"; -- three random quads, two of them strattling the edge of the texture. Def.Quad{ InitCommand=cmd(zoom,50;diffuse,1,0,0,0.5) }; Def.Quad{ InitCommand=cmd(zoom,50;diffuse,0,1,0,0.5;x,64;y,64) }; Def.Quad{ InitCommand=cmd(zoom,50;diffuse,0,0,1,0.5;x,120;y,100) }; }; }; Def.Sprite{ Texture="Example 1"; InitCommand=cmd(Center;sleep,1;queuecommand,"Scroll"); ScrollCommand=cmd(texcoordvelocity,1,0.5); -- Scroll the texture. Texture manipulation is one of the things that makes AFT special. }; } Examples[2] = Def.ActorFrame{ Def.Quad{ InitCommand=cmd(FullScreen;diffuse,0,0,0,1) }; -- a blank background. Def.ActorFrameTexture{ InitCommand=function(self) self:SetTextureName( "Example 2" ) self:SetWidth( 128 ); self:SetHeight( 128 ); self:EnableAlphaBuffer( true ); self:Create(); self:EnablePreserveTexture( Example2_PreserveTexture ); -- No draw function this time, this will draw on every frame. end; Def.ActorFrame{ Name = "Draw"; InitCommand=cmd(spin;x,64;y,64); -- Something has to change to demonstrate PreserveTexture. Def.Quad{ InitCommand=cmd(zoom,50;rainbow;effectperiod,3;effectoffset,1;x,-40;y,-56) }; Def.Quad{ InitCommand=cmd(zoom,50;rainbow;effectperiod,3;effectoffset,0) }; Def.Quad{ InitCommand=cmd(zoom,50;rainbow;effectperiod,3;effectoffset,2;x,64;y,50) }; }; }; Def.Sprite{ Texture="Example 2"; InitCommand=cmd(Center); }; } Examples[3] = Def.ActorFrame{ Def.Quad{ InitCommand=cmd(FullScreen;diffuse,0,0,0,1) }; -- a blank background. Def.ActorFrameTexture{ InitCommand=function(self) self:SetTextureName( "Example 3" ) self:SetWidth( 128 ); self:SetHeight( 128 ); self:EnableAlphaBuffer( true ); self:EnableFloat( true ); self:Create(); self:Draw() self:hibernate(math.huge) end; Def.ActorFrame{ Name = "Draw"; Def.Quad{ InitCommand=cmd(zoom,80;diffuse,1,1,1,1;x,64;y,64) }; Def.Quad{ InitCommand=cmd(zoom,80;diffuse,1,0,0,1;x,14;y,80;blend,"BlendMode_Add") }; Def.Quad{ InitCommand=cmd(zoom,80;diffuse,0,1,0,1;x,74;y,20;blend,"BlendMode_Add") }; Def.Quad{ InitCommand=cmd(zoom,80;diffuse,0,0,1,1;x,128;y,100;blend,"BlendMode_Add") }; }; }; Def.Sprite{ Texture = "Example 3"; InitCommand=cmd(Center;diffuse,Example3_Diffuse); }; } --[[ We have 2 AFTs, and a sprite to draw the final output. On each frame, the following occurs: The first AFT draws the 'final output' sprite to it's texture, showing the final output of the previous frame. The second AFT draws a sprite containing the first AFT's texture, but at reduced alpha, and then draw's it's own image. The final output sprite draws the second AFT's texture to the screen. The image drawn in a frame will be drawn again and again of subsequant frames with continuously decreasing opacity, showing a trail of where it had been. We cannot use a single AFT, having it draw a sprite containing it's own texture at lower alpha because the texture is cleared as soon as the texture begins rendering, before it can be drawn. If PreserveTexture is true, we cannot have it fade. --]] Examples[4] = Def.ActorFrame{ Def.Quad{ InitCommand=cmd(FullScreen;diffuse,0,0,0,1) }; -- a blank background. Def.ActorFrameTexture{ Name = "Memory"; InitCommand=function(self) self:SetTextureName( "Memory" ) self:SetWidth( 256 ); self:SetHeight( 256 ); self:EnableAlphaBuffer( true ); self:Create(); end; -- Cannot call the second AFT's texture by name as it has not been created when this Sprite loads. Def.Sprite{ Name = "Sprite"; InitCommand=cmd(x,128;y,128) }; }; Def.ActorFrameTexture{ InitCommand=function(self) self:SetTextureName( "Output" ) self:SetWidth( 256 ); self:SetHeight( 256 ); self:EnableAlphaBuffer( true ); self:Create(); -- Set the first AFT's child's texture to this AFT's texture, now that it has been created. self:GetParent():GetChild("Memory"):GetChild("Sprite"):SetTexture( self:GetTexture() ); end; -- A sprite to draw the 'trail' with. Def.Sprite{ Texture = "Memory"; InitCommand=cmd(x,128;y,128;diffuse,1,1,1,.995); }; Def.ActorFrame{ -- eliptical motion. InitCommand=cmd(x,128;y,128;bob;effectmagnitude,96,0,0;effectoffset,0.5); Def.ActorFrame{ InitCommand=cmd(bob;effectmagnitude,0,64,0); -- A pixel ghost. Def.Quad{ InitCommand=cmd(zoomto,32,40); }; Def.Quad{ InitCommand=cmd(zoomto,8,8;x,-8;y,-8;diffuse,0,0,0,1); }; Def.Quad{ InitCommand=cmd(zoomto,8,8;x,8;y,-8;diffuse,0,0,0,1); }; Def.Quad{ InitCommand=cmd(zoomto,24,8;x,0;y,2;diffuse,0,0,0,1); }; Def.Quad{ InitCommand=cmd(zoomto,8,16;x,-12;y,24); }; Def.Quad{ InitCommand=cmd(zoomto,8,16;x,12;y,24); }; Def.Quad{ InitCommand=cmd(zoomto,8,16;x,0;y,24); }; }; }; }; Def.Sprite{ Name = "Ghosting"; Texture = "Output"; InitCommand=cmd(Center); }; } return Examples[ ExampleToShow ]
require"pears".setup()
local function CreateFont() surface.CreateFont( "KNOTIF", { font = "Roboto Cn", extended = true, size = 30, weight = 700, antialias = true }) end CreateFont() hook.Add("CHKill","CHKillIndidator",function(ply) local col = team.GetColor(LocalPlayer():Team()) local r = col.r local g = col.g local b = col.b local time = SysTime() hook.Add("HUDPaint","CHKillIndicator",function() local timeex = SysTime()-time r = r+1 g = g+1 b = b+1 surface.SetDrawColor(r,g,b,255-timeex*300) local w1 = math.Clamp(400-timeex*600,200,500) local h1 = 20+timeex*50 surface.DrawRect((ScrW()/2)-w1/2,((ScrH()/4)*3)-h1/2,w1,h1) surface.SetDrawColor(r-100,g-100,b-100,255-timeex*300) surface.DrawRect((ScrW()/2)-(w1/2)-2,((ScrH()/4)*3)-(h1/2)-2,w1+4,h1+4) draw.SimpleText("Killed "..ply,"KNOTIF",(ScrW()/2)+math.Rand(-6,6),((ScrH()/4)*3)+math.Rand(-6,6),Color(timeex*510,0,0,255-timeex*250),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) draw.SimpleText("Killed "..ply,"KNOTIF",(ScrW()/2),((ScrH()/4)*3),Color(255,timeex*510,timeex*510,255-timeex*300),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end) timer.Remove("KillTimer") timer.Create("KillTimer",3,1,function() hook.Remove("HUDPaint","CHKillIndicator") end) end)
screenX, screenY = guiGetScreenSize() scaleX, scaleY = (screenX / 1920), (screenY / 1080) local anim = {} local anim_startingPos = 0.2900 local anim_startingPosbg = 355 local animListVisible = false local animListGlobal local chosenAnim = 0 local animCategories = { {"Leżenie", true}, {"Postać", false}, {"Barowe", false}, {"Stack", false} } local category_chosen = 1 local categoriesPos = 0.3000 local startAnim = 0 function renderAnimList() anim.W, anim.H = 460 * scaleX, 550 * scaleY anim.posX, anim.posY = (screenX - anim.W)/2, (screenY - anim.H)/2 dxDrawImage(anim.posX, anim.posY, anim.W, anim.H, "assets/bg.png", 0, 0, 0, tocolor(255, 255, 255, 209), false) dxDrawLine(screenX * 0.4631, screenY * 0.2844, screenX * 0.4631, screenY * 0.6822, tocolor(255, 255, 255, 255), 1, false) for _,cat in ipairs(animCategories) do if cat[2] == true then dxDrawText(cat[1], screenX * 0.3944, screenY * categoriesPos, screenX * 0.4612, screenY * (categoriesPos + 0.0350), tocolor(178, 233, 255, 255), 1.00, "default", "left", "center", false, false, false, false, false) else dxDrawText(cat[1], screenX * 0.3944, screenY * categoriesPos, screenX * 0.4612, screenY * (categoriesPos + 0.0350), tocolor(255, 255, 255, 255), 1.00, "default", "left", "center", false, false, false, false, false) end categoriesPos = categoriesPos + 0.0300 end categoriesPos = 0.3000 dxDrawText("Lista animacji", screenX * 0.3944, screenY * 0.2800, screenX * 0.4612, screenY * 0.3056, tocolor(255, 255, 255, 255), 1.00, "default", "left", "center", false, false, false, false, false) local found = false local firstAnim local countVisible = 0 local count = 1 for i, anims in ipairs(animListGlobal) do if anims[7] == animCategories[category_chosen][1] and countVisible <= 10 then if i >= chosenAnim then if not firstAnim then firstAnim = i end if chosenAnim == i then found = true end if chosenAnim == i then dxDrawRectangle(screenX * 0.4694, screenY * anim_startingPos, screenX * 0.08, 25, tocolor(255, 255, 255, 20), false) end dxDrawText(anims[1], screenX * 0.4694, screenY * anim_startingPos, screenX * 0.5450, screenY * (anim_startingPos + 0.02167), tocolor(255, 255, 255, 255), 1.00, "default", "center", "center", false, false, false, false, false) anim_startingPos = anim_startingPos + 0.0300 countVisible = countVisible + 1 end count = count + 1 end end if not found then chosenAnim = firstAnim end anim_startingPos = 0.2900 anim_startingPosbg = 0.2850 dxDrawRectangle(screenX * 0.5531, screenY * 0.6787, screenX * 0.0380, screenY * 0.0231, tocolor(12, 77, 6, 254), false) dxDrawText("Ustaw", screenX * 0.5791, screenY * 0.6977, screenX * 0.5681, screenY * 0.6887, tocolor(255, 255, 255, 255), 1.00, "default", "center", "center", false, false, false, false, false) end local countAnims = 1 function animKey(button, pressed) if pressed == true and animListVisible then if button == "mouse_wheel_down" then if chosenAnim + 1 <= #animListGlobal and animListGlobal[chosenAnim + 1][7] == animCategories[category_chosen][1] then chosenAnim = chosenAnim + 1 if countAnims < 10 then countAnims = countAnims + 1 end end elseif button == "mouse_wheel_up" then if chosenAnim - 1 >= 1 and animListGlobal[chosenAnim - 1][7] == animCategories[category_chosen][1] then chosenAnim = chosenAnim - 1 if countAnims >= 1 then countAnims = countAnims - 1 end end end end end function isCursorOnElement(x,y,w,h) local mx,my = getCursorPosition() local fullx,fully = guiGetScreenSize() cursorx, cursory = mx * fullx, my * fully if cursorx > x and cursorx < x + w and cursory > y and cursory < y + h then return true else return false end end function onClickedAnim(button, state, x, y) if animListVisible and state == "up" then local cat_startPos = 0.3000 for i,cat in ipairs(animCategories) do local width, height = dxGetTextWidth(cat[1]), dxGetFontHeight() if isCursorOnElement(screenX * 0.3900, screenY * cat_startPos, width, height + 20) then for _,cat2 in ipairs(animCategories) do cat2[2] = false end animCategories[i][2] = true category_chosen = i countAnims = 1 chosenAnim = 0 end cat_startPos = cat_startPos + 0.0300 end if chosenAnim and isCursorOnElement(screenX * 0.5531, screenY * 0.6787, screenX * 0.0380, screenY * 0.0231) then triggerServerEvent( "setPlayerAnim", localPlayer, chosenAnim ) showAnimationsHandler(animListGlobal) end end end addEventHandler( "onClientKey", root, animKey ) function showAnimationsHandler(animList) if not animListVisible then animListVisible = true animListGlobal = animList showCursor( true ) addEventHandler("onClientRender", root, renderAnimList) addEventHandler( "onClientClick", root, onClickedAnim ) else removeEventHandler( "onClientRender", root, renderAnimList) removeEventHandler( "onClientClick", root, onClickedAnim ) animListVisible = false showCursor( false ) end end addEvent( "showAnimationsList", true ) addEventHandler( "showAnimationsList", localPlayer, showAnimationsHandler )
-- Test complex recursive CALL of CLOSURE using Fibonacci algorithm -- Copyright (c) 2013 the authors listed at the following URL, and/or -- the authors of referenced articles or incorporated external code: -- http://en.literateprograms.org/Fibonacci_numbers_(Lua)?action=history&offset=20120305215844 function fib(n) return n<2 and n or fib(n-1)+fib(n-2) end a = fib(3)
local assert_error = require("lapis.application").assert_error local csrf = require "lapis.csrf" local generate = require "utils.generate" local Boards = require "models.boards" local Reports = require "models.reports" return { before = function(self) -- Get data self.boards = Boards:get_boards() self.reports = Reports:get_reports() -- Display a theme self.board = { theme = "yotsuba_b" } -- Generate CSRF token self.csrf_token = csrf.generate_token(self) -- Page title self.page_title = self.i18n("admin_panel") -- Verify Authorization if self.session.name then if not self.session.admin then assert_error(false, "err_not_admin") end else return end -- Delete report if self.params.action == "delete" then local report = Reports:get_report_by_id(self.params.report) assert_error(Reports:delete_report(report)) self.page_title = string.format( "%s - %s", self.i18n("admin_panel"), self.i18n("success") ) self.action = self.i18n("deleted_report", { report.id }) return end end, on_error = function(self) self.errors = generate.errors(self.i18n, self.errors) if not self.session.name then return { render = "admin.login" } elseif self.params.action == "delete" then return { render = "admin.admin" } end end, GET = function(self) if not self.session.name then return { render = "admin.login" } elseif self.params.action == "delete" then return { render = "admin.success" } end end, POST = function(self) return { redirect_to = self:format_url(self.admin_url) } end }
local _G = _G local table_insert = table.insert local table_remove = table.remove local abs = math.abs local type = type local ipairs = ipairs local next = next local assert = assert local setmetatable = setmetatable local d_getinfo = debug.getinfo local FunctionFile = debug.FunctionFile local pcall2 = pcall2 local coroutine_create = coroutine.create local coroutine_resume2 = coroutine.resume2 ----------- No globals from this point ------------ local _NOGLOBALS --------- events -- Logic: -- 'remove' should prevent currently running events from executing the removed function, but keep processing going -- newly added functions shouldn't be executed by currently running events -- So: -- no table.remove/table.insert, instead build a new event table when there are too many gaps -- invalidate the old event table (with false's), redirect(reloc) handlers stuck with it to the newer table -- (the old table otherwise stays in the state from which the newer one was created, which is important for reloc) local function fcocall(f, ...) return coroutine_resume2(coroutine_create(f), ...) end local function remake_list(f) local n = 0 local t = {from = 1} for i = f.from, f.to do local v = f[i] if v then n = n + 1 t[n] = v f[i] = false end end t.to = n f.Next = t return t end local function ProcessReloc(f, index, to) local from1, to1 = 1, 0 for i = f.from, to do if f[i] == false then to1 = to1 + 1 if i == index then from1 = to1 end end end return f.Next, from1, to1 end local function docall(f, from, to, ...) local ret for i = from, to do local v = f[i] if v then local tmp = v(...) if tmp ~= nil then ret = tmp end elseif v == false then f, from, to = ProcessReloc(f, i, to) local tmp = docall(f, from, to, ...) if tmp ~= nil then return tmp end return ret end end return ret end local function speccall(call, f, from, to, ...) local ret for i = from, to do local v = f[i] if v then local ok, tmp = call(v, ...) if tmp ~= nil and ok then ret = tmp end elseif v == false then f, from, to = ProcessReloc(f, i, to) local tmp = speccall(call, f, from, to, ...) if tmp ~= nil then return tmp end return ret end end return ret end local function make_events(evt) evt = evt or {} local t = {} local function call(a, ...) local f = t[a] return f and docall(f, f.from, f.to, ...) end evt.call, evt.Call = call, call local function pcalls(a, ...) local f = t[a] return f and speccall(pcall2, f, f.from, f.to, ...) end evt.pcalls = pcalls local function cocalls(a, ...) local f = t[a] return f and speccall(fcocall, f, f.from, f.to, ...) end evt.cocalls = cocalls local function _pcall(a, ...) local f = t[a] if f then local ok, tmp = pcall2(docall, f, f.from, f.to, ...) if ok then return tmp end end end evt.pcall = _pcall local function cocall(a, ...) local f = t[a] if f then local ok, tmp = coroutine_resume2(coroutine_create(docall), f, f.from, f.to, ...) if ok then return tmp end end end evt.cocall = cocall local function newindex(_, a, v) if v then local f = t[a] if f then f.to = f.to + 1 f[f.to] = v else t[a] = {v, from = 1, to = 1} end end end local function add(a, v) newindex(nil, a, v) end evt.add, evt.Add = add, add local function addfirst(a, v) if v then local f = t[a] if f then t.from = t.from - 1 t[t.from] = v else t[a] = {v, from = 1, to = 1} end end end evt.addfirst, evt.AddFirst = addfirst, addfirst local function check_gaps(a, f) local d = f.to - f.from if d < 0 then t[a] = nil elseif (f.gaps or 0)*2 + abs(f.from - 1) > d then -- allow 1/2 to be filled with gaps t[a] = remake_list(f) end end local function removed(f, i) if i == f.from then f.from = f.from + 1 while not f[f.from] and f.from <= f.to do f.from = f.from + 1 f.gaps = f.gaps - 1 end elseif i == f.to then f.to = f.to - 1 while not f[f.to] and f.from <= f.to do f.to = f.to - 1 f.gaps = f.gaps - 1 end else f.gaps = (f.gaps or 0) + 1 end end local function replace(a, func, f2) if type(func) == "number" then func = assert(d_getinfo(func + 1, 'f').func) end if type(f2) == "number" then f2 = assert(d_getinfo(f2 + 1, 'f').func) end local f = t[a] if f and func then for i = f.from, f.to do if f[i] == func then f[i] = f2 if not f2 then removed(f, i) check_gaps(a, f) end return func end end end end evt.replace, evt.Replace, evt.remove, evt.Remove = replace, replace, replace, replace local function clear(a) -- stop currently running handlers local f = t[a] if f then for i = f.from, f.to do f[i] = nil end end t[a] = nil end evt.clear, evt.Clear = clear, clear local function exists(a, func) local f = t[a] if f then if not func then return true end for i = f.from, f.to do if f[i] == func then return true end end end return false end evt.exists, evt.Exists = exists, exists local function RemoveFiles(files) for a, f in next, t do for i = f.from, f.to do if f[i] and files[FunctionFile(f[i])] then f[i] = nil removed(f, i) end end check_gaps(a, f) end end evt.RemoveFiles = RemoveFiles function evt.RemoveFile(f) f = f or FunctionFile(2) RemoveFiles{[f] = true} end function evt.RemoveAll() -- stop currently running handlers for a, f in next, t do for i = f.from, f.to do f[i] = nil end t[a] = nil end end local function index(_, a) local function forward(f) return function(...) return f(a, ...) end end local call = function(_, ...) return call(a, ...) end local add = function(func) newindex(nil, a, func) end local replace = function(func, f2) if type(func) == "number" then func = assert(d_getinfo(func + 1, 'f').func) end if type(f2) == "number" then f2 = assert(d_getinfo(f2 + 1, 'f').func) end return replace(a, func, f2) end local function evIndex(_, k) if k ~= "last" and k ~= "Last" then return end local f = t[a] if f then for i = f.to, f.from, -1 do if f[i] then return f[i] end end end end local remove = replace local pcalls = forward(pcalls) local _pcall = forward(_pcall) local cocalls = forward(cocalls) local cocall = forward(cocall) local exists = forward(exists) local clear = forward(clear) local t1 = {add = add, Add = add, remove = remove, Remove = remove, replace = replace, Replace = replace, exists = exists, Exists = exists, clear = clear, Clear = clear, __call = call, pcalls = pcalls, pcall = _pcall, cocalls = cocalls, cocall = cocall, __index = evIndex} return setmetatable(t1, t1) end return setmetatable(evt, {__index = index, __newindex = newindex}), t end _G.events = make_events{new = make_events}
local DECOR = { FLOAT = 1, BOOL = 2, INT = 3, UNK = 4, TIME = 5, } local DECORATORS = { ["flatbed3_bed"] = DECOR.INT, -- The bed entity ["flatbed3_car"] = DECOR.INT, -- The car entity ["flatbed3_attached"] = DECOR.BOOL, -- Is a car attached? ["flatbed3_lowered"] = DECOR.BOOL, -- Is the bed lowered? ["flatbed3_state"] = DECOR.INT, -- Multi-state for the bed } for k,v in next, DECORATORS do DecorRegister(k, v) end function lerp(a, b, t) return a + (b - a) * t end -- Value controlling all movement local LERP_VALUE = 0.0 local lastFlatbed = nil local lastBed = nil --local raisedOffset = vector3(0.0, -3.8, 0.25) local backOffset = {vector3(0.0, -4.0, 0.0), vector3(0.0, 0.0, 0.0)} local loweredOffset = {vector3(0.0, -0.4, -1.0), vector3(12.0, 0.0, 0.0)} local raisedOffset = {vector3(0.0, -3.8, 0.45), vector3(0.0, 0.0, 0.0)} local attachmentOffset = {vector3(0.0, 1.5, 0.3), vector3(0.0, 0.0, 0.0)} local bedController = {vector3(-2.5, -3.8, -1.0), vector3(0.0, 0.0, 0.0)} local controllerMessageLoweredCar = "OMNI_FB3_INST_LC" local controllerMessageLoweredNoCar = "OMNI_FB3_INST_LN" local controllerMessageRaised = "OMNI_FB3_INST_R" AddTextEntry(controllerMessageLoweredCar, "Press ~INPUT_CONTEXT~ to ~y~raise ~w~the bed.~n~Press ~INPUT_DETONATE~ to ~r~detach ~w~the vehicle.") AddTextEntry(controllerMessageLoweredNoCar, "Press ~INPUT_CONTEXT~ to ~y~raise ~w~the bed.~n~Press ~INPUT_DETONATE~ to ~g~attach ~w~a vehicle.") AddTextEntry(controllerMessageRaised, "Press ~INPUT_CONTEXT~ to ~y~lower ~w~the bed.") function drawMarker(pos) local plyPos = GetEntityCoords(PlayerPedId(), true) if IsPedInAnyVehicle(PlayerPedId(), true) then return false end local dist = #(pos - plyPos) if dist < 25.0 then DrawMarker(1, pos, vector3(0.0, 0.0, 0.0), vector3(0.0, 0.0, 0.0), vector3(1.0, 1.0, 1.0), 255, 255, 255, 150) if dist < 1.5 then return true end end return false end function showHelpText(text) BeginTextCommandDisplayHelp("STRING") AddTextComponentSubstringTextLabel(text) EndTextCommandDisplayHelp(0, 0, 1, -1) end function getVehicleInDirection(coordFrom, coordTo) local rayHandle = CastRayPointToPoint(coordFrom.x, coordFrom.y, coordFrom.z, coordTo.x, coordTo.y, coordTo.z, 10, GetPlayerPed(-1), 0) local a, b, c, d, vehicle = GetRaycastResult(rayHandle) return vehicle end function log(text) print("[omni_flatbed/client] " .. text) end Citizen.CreateThread(function() log("Flatbed Loading") RequestModel("inm_flatbed_base") while not HasModelLoaded("inm_flatbed_base") do Wait(0) end log("Flatbed Loading Complete") while true do local ped = PlayerPedId() local veh = GetVehiclePedIsIn(ped, true) if veh and GetEntityModel(veh) ~= GetHashKey("flatbed3") then veh = lastFlatbed end if lastFlatbed then if not DoesEntityExist(lastFlatbed) then log("FLATBED DELETED?") if lastBed then if DoesEntityExist(lastBed) then log("BED STILL EXISTS!") DeleteEntity(lastBed) lastBed = nil end end lastFlatbed = nil end end if veh and DoesEntityExist(veh) and GetEntityModel(veh) == GetHashKey("flatbed3") and NetworkHasControlOfEntity(veh) then lastFlatbed = veh local rightDir, fwdDir, upDir, pos = GetEntityMatrix(veh) if not DecorExistOn(veh, "flatbed3_bed") or DecorGetInt(veh, "flatbed3_bed") == 0 then DecorSetInt(veh, "flatbed3_bed", 0) local bed = CreateObjectNoOffset("inm_flatbed_base", pos, true, 0, 1) log("GENERATING BED") if DoesEntityExist(bed) then local bedNet = ObjToNet(bed) DecorSetInt(veh, "flatbed3_bed", bedNet) log("DONE GENERATING BED") end else SetVehicleExtra(veh, 1, not false) end local bedNet = DecorGetInt(veh, "flatbed3_bed") local bed = nil if bedNet ~= 0 then bed = NetToObj(bedNet) lastBed = bed if not DecorExistOn(veh, "flatbed3_attached") then DecorSetBool(veh, "flatbed3_attached", false) end local attached = DecorGetBool(veh, "flatbed3_attached") if not DecorExistOn(veh, "flatbed3_lowered") then DecorSetBool(veh, "flatbed3_lowered", true) end local lowered = DecorGetBool(veh, "flatbed3_lowered") if not DecorExistOn(veh, "flatbed3_state") then DecorSetInt(veh, "flatbed3_state", 0) end local state = DecorGetInt(veh, "flatbed3_state") if not DecorExistOn(veh, "flatbed3_car") then DecorSetInt(veh, "flatbed3_car", 0) end local carNet = DecorGetInt(veh, "flatbed3_car") local car = nil if carNet ~= 0 then car = NetToVeh(carNet) end local data = bedController local x = pos.x + (fwdDir.x * data[1].x) + (rightDir.x * data[1].y) + (upDir.x * data[1].z) local y = pos.y + (fwdDir.y * data[1].x) + (rightDir.y * data[1].y) + (upDir.y * data[1].z) local z = pos.z + (fwdDir.z * data[1].x) + (rightDir.z * data[1].y) + (upDir.z * data[1].z) local controllerPos = vector3(x, y, z) if state == 0 then -- Raised if lowered then DetachEntity(bed, 0, 0) AttachEntityToEntity(bed, veh, GetEntityBoneIndexByName(veh, "chassis"), raisedOffset[1], raisedOffset[2], 0, 0, 1, 0, 0, 1) DecorSetBool(veh, "flatbed3_lowered", false) lowered = false end if drawMarker(controllerPos) then showHelpText(controllerMessageRaised) if IsControlJustPressed(0, 38) then state = 1 DecorSetInt(veh, "flatbed3_state", state) end end elseif state == 1 then -- Moving back local offsetPos = raisedOffset[1] local offsetRot = raisedOffset[2] offsetPos = offsetPos + vector3(lerp(0.0, backOffset[1].x, LERP_VALUE), lerp(0.0, backOffset[1].y, LERP_VALUE), lerp(0.0, backOffset[1].z, LERP_VALUE)) offsetRot = offsetRot + vector3(lerp(0.0, backOffset[2].x, LERP_VALUE), lerp(0.0, backOffset[2].y, LERP_VALUE), lerp(0.0, backOffset[2].z, LERP_VALUE)) DetachEntity(bed, 0, 0) AttachEntityToEntity(bed, veh, GetEntityBoneIndexByName(veh, "chassis"), offsetPos, offsetRot, 0, 0, 1, 0, 0, 1) LERP_VALUE = LERP_VALUE + (1.0 * Timestep()) / 4.0 if LERP_VALUE >= 1.0 then state = state + 1 DecorSetInt(veh, "flatbed3_state", state) LERP_VALUE = 0.0 end elseif state == 2 then -- Lowering local offsetPos = raisedOffset[1] + backOffset[1] local offsetRot = raisedOffset[2] + backOffset[2] offsetPos = offsetPos + vector3(lerp(0.0, loweredOffset[1].x, LERP_VALUE), lerp(0.0, loweredOffset[1].y, LERP_VALUE), lerp(0.0, loweredOffset[1].z, LERP_VALUE)) offsetRot = offsetRot + vector3(lerp(0.0, loweredOffset[2].x, LERP_VALUE), lerp(0.0, loweredOffset[2].y, LERP_VALUE), lerp(0.0, loweredOffset[2].z, LERP_VALUE)) DetachEntity(bed, 0, 0) AttachEntityToEntity(bed, veh, GetEntityBoneIndexByName(veh, "chassis"), offsetPos, offsetRot, 0, 0, 1, 0, 0, 1) LERP_VALUE = LERP_VALUE + (1.0 * Timestep()) / 2.0 if LERP_VALUE >= 1.0 then state = state + 1 DecorSetInt(veh, "flatbed3_state", state) LERP_VALUE = 0.0 end elseif state == 3 then -- Lowered if not lowered then local offsetPos = raisedOffset[1] + backOffset[1] + loweredOffset[1] local offsetRot = raisedOffset[2] + backOffset[2] + loweredOffset[2] DetachEntity(bed, 0, 0) AttachEntityToEntity(bed, veh, GetEntityBoneIndexByName(veh, "chassis"), offsetPos, offsetRot, 0, 0, 1, 0, 0, 1) DecorSetBool(veh, "flatbed3_lowered", true) lowered = true end if drawMarker(controllerPos) then if attached then showHelpText(controllerMessageLoweredCar) else showHelpText(controllerMessageLoweredNoCar) end if IsControlJustPressed(0, 38) then state = 4 DecorSetInt(veh, "flatbed3_state", state) end if IsControlJustPressed(0, 47) then if attached then DetachEntity(car, 0, 1) car = nil DecorSetInt(veh, "flatbed3_car", 0) attached = false DecorSetBool(veh, "flatbed3_attached", attached) else local bedPos = GetEntityCoords(bed, false) local newCar = getVehicleInDirection(bedPos + vector3(0.0, 0.0, 0.25), bedPos + vector3(0.0, 0.0, 2.25)) if newCar then local carPos = GetEntityCoords(newCar, false) NetworkRequestControlOfEntity(newCar) while not NetworkHasControlOfEntity(newCar) do Wait(0) end AttachEntityToEntity(newCar, bed, 0, attachmentOffset[1] + vector3(0.0, 0.0, carPos.z - bedPos.z - 0.50), attachmentOffset[2], 0, 0, false, 0, 0, 1) car = newCar DecorSetInt(veh, "flatbed3_car", VehToNet(newCar)) attached = true DecorSetBool(veh, "flatbed3_attached", attached) end end end end elseif state == 4 then -- Raising local offsetPos = raisedOffset[1] + backOffset[1] local offsetRot = raisedOffset[2] + backOffset[2] offsetPos = offsetPos + vector3(lerp(loweredOffset[1].x, 0.0, LERP_VALUE), lerp(loweredOffset[1].y, 0.0, LERP_VALUE), lerp(loweredOffset[1].z, 0.0, LERP_VALUE)) offsetRot = offsetRot + vector3(lerp(loweredOffset[2].x, 0.0, LERP_VALUE), lerp(loweredOffset[2].y, 0.0, LERP_VALUE), lerp(loweredOffset[2].z, 0.0, LERP_VALUE)) DetachEntity(bed, 0, 0) AttachEntityToEntity(bed, veh, GetEntityBoneIndexByName(veh, "chassis"), offsetPos, offsetRot, 0, 0, 1, 0, 0, 1) LERP_VALUE = LERP_VALUE + (1.0 * Timestep()) / 2.0 if LERP_VALUE >= 1.0 then state = state + 1 DecorSetInt(veh, "flatbed3_state", state) LERP_VALUE = 0.0 end elseif state == 5 then -- Moving forward local offsetPos = raisedOffset[1] local offsetRot = raisedOffset[2] offsetPos = offsetPos + vector3(lerp(backOffset[1].x, 0.0, LERP_VALUE), lerp(backOffset[1].y, 0.0, LERP_VALUE), lerp(backOffset[1].z, 0.0, LERP_VALUE)) offsetRot = offsetRot + vector3(lerp(backOffset[2].x, 0.0, LERP_VALUE), lerp(backOffset[2].y, 0.0, LERP_VALUE), lerp(backOffset[2].z, 0.0, LERP_VALUE)) DetachEntity(bed, 0, 0) AttachEntityToEntity(bed, veh, GetEntityBoneIndexByName(veh, "chassis"), offsetPos, offsetRot, 0, 0, 1, 0, 0, 1) LERP_VALUE = LERP_VALUE + (1.0 * Timestep()) / 4.0 if LERP_VALUE >= 1.0 then state = 0 DecorSetInt(veh, "flatbed3_state", state) LERP_VALUE = 0.0 end else state = 0 DecorSetInt(veh, "flatbed3_state", state) end if not IsPedInVehicle(ped, veh, true) then end end end Wait(0) end end)
-- -- User: Glastis -- Date: 01/11/17 -- Time: 14:51 -- local file = require('common.file') local utilities = {} local function trim(str) return str:gsub("^%s+", ""):gsub("%s+$", "") end utilities.trim = trim local function get_elem_in_table(table, elem) local i i = 1 while i <= #table do if table[i] == elem then return i end i = i + 1 end return false end utilities.get_elem_in_table = get_elem_in_table local function concatenate_arrays(t1, t2) local i i = 1 while i <= #t2 do t1[#t1 + 1] = t2[i] i = i + 1 end return t1 end utilities.concatenate_arrays = concatenate_arrays local function split(str, separator) local t = {} local i i = 1 for line in string.gmatch(str, "([^" .. separator .. "]+)") do t[i] = line i = i + 1 end return t end utilities.split = split local function exec_function_table(actions, param) local i i = 1 if not param then param = {} end while i <= #actions do actions[i](param[i]) i = i + 1 end end utilities.exec_function_table = exec_function_table local function exec_function_table_revert(actions, param) local i i = #actions if not param then param = {} end while i > 0 do actions[i](param[i]) i = i - 1 end end utilities.exec_function_table_revert = exec_function_table_revert local function debug_info(more, calltrace) if not more then more = " " end if calltrace then local trace trace = split(split(debug.traceback(), '\n')[3], '/') file.write("trace.log", '\n' .. trace[#trace] .. '\n' .. more .. '\n') else file.write("trace.log", more .. '\n') end end utilities.debug_info = debug_info local function var_dump(var, printval) if type(var) == 'table' then local s s = '{ ' for k,v in pairs(var) do if type(k) ~= 'number' then k = '"' .. k .. '"' end s = s .. '\n[' .. k .. '] = ' .. var_dump(v) .. ',' end if printval then print(tostring(s .. '\n}')) end return s .. '\n} ' end if printval then print(tostring(var)) end return tostring(var) end utilities.var_dump = var_dump local function round(number, decimals, ext_abs) if ext_abs then ext_abs = math.floor else ext_abs = math.ceil end if not decimals then return ext_abs(number) end decimals = 10 ^ decimals return ext_abs(number * decimals) / decimals end utilities.round = round return utilities
if SERVER then AddCSLuaFile() return end --[[ https://github.com/Derpius/VisTrace/issues/13 pcall(require, "VisTrace-v0.4") -- Don't throw an error if the module failed to load ]] if not file.Exists("lua/bin/gmcl_VisTrace-v0.4_win64.dll", "GAME") then return end if not system.IsWindows() then error("VisTrace is currently only compatible with Windows, if you'd like a cross platform build to be worked on, please open an issue at https://github.com/Derpius/VisTrace/issues") end if jit.arch ~= "x64" then error("VisTrace does not work on 32 bit builds of Garry's Mod at this time, please switch to the x86-64 branch in Steam betas") end require("VisTrace-v0.4")
local menu = {} love.graphics.setBackgroundColor(130, 220, 250) function math.lerp(a, b, k) --just fun stuff if a == b then return a else if math.abs(a-b) < 0.005 then return b else return a * (1-k) + b * k end end end WWIDTH, WHEIGHT = 800, 600 function menu:load() font = love.graphics.newFont(48) myStyle = uare.newStyle({ width = 400, height = 60, color = {200, 200, 200}, hoverColor = {150, 150, 150}, holdColor = {100, 100, 100}, border = { color = {255, 255, 255}, hoverColor = {200, 200, 200}, holdColor = {150, 150, 150}, size = 5 }, text = { color = {200, 0, 0}, hoverColor = {150, 0, 0}, holdColor = {255, 255, 255}, font = font, align = "center", offset = { x = 0, y = -30 }, }, }) myButton1 = uare.new({ text = { display = "singleplayer" }, onClick = function() state:switch("src/game", false) end, x = WWIDTH*.5-200, y = WHEIGHT*.5-200 }):style(myStyle) myButton2 = uare.new({ text = { display = "multiplayer" }, onClick = function() state:switch("src/game", true) end, x = WWIDTH*.5-200, y = WHEIGHT*.5-100 }):style(myStyle) end function menu:update(dt) uare.update(dt, love.mouse.getX(), love.mouse.getY()) end function menu:draw() uare.draw() end function love.textinput(t) myButton1.text.display = myButton1.text.display .. t end return menu
------------------------------ -- Area: Gusgen Mines -- NM: Pulverized Pfeffer ------------------------------ require("scripts/globals/hunts") ------------------------------ function onMobDeath(mob, player, isKiller) tpz.hunts.checkHunt(mob, player, 232) end
-- General utility functions function tableKeys(t) local keys = {} local n = 0 for k, v in pairs(t) do n = n + 1 keys[n] = k end return keys end function shuffle(tbl) size = #tbl for i = size, 1, -1 do local rand = math.random(size) tbl[i], tbl[rand] = tbl[rand], tbl[i] end return tbl end function serializeTable(val, name, skipnewlines, depth) skipnewlines = skipnewlines or false depth = depth or 0 local tmp = string.rep(" ", depth) if name then tmp = tmp .. name .. " = " end if type(val) == "table" then tmp = tmp .. "{" .. (not skipnewlines and "\n" or "") for k, v in pairs(val) do tmp = tmp .. serializeTable(v, k, skipnewlines, depth + 1) .. "," .. (not skipnewlines and "\n" or "") end tmp = tmp .. string.rep(" ", depth) .. "}" elseif type(val) == "number" then tmp = tmp .. tostring(val) elseif type(val) == "string" then tmp = tmp .. string.format("%q", val) elseif type(val) == "boolean" then tmp = tmp .. (val and "true" or "false") else tmp = tmp .. '"[inserializeable datatype:' .. type(val) .. ']"' end return tmp end function invertTable(t) local s = {} for k, v in pairs(t) do s[v] = k end return s end function copyTable(obj, seen) if type(obj) ~= "table" then return obj end if seen and seen[obj] then return seen[obj] end local s = seen or {} local res = setmetatable({}, getmetatable(obj)) s[obj] = res for k, v in pairs(obj) do res[copyTable(k, s)] = copyTable(v, s) end return res end function colorSum(c1, c2, r1, r2) return {c1[1] * r1 + (c2[1]) * r2, c1[2] * r1 + (c2[2]) * r2, c1[3] * r1 + (c2[3]) * r2, c1[4]} end function output(thing) SCREENMAN:SystemMessage(serializeTable(thing)) end function pos(x, y) return {x = x, y = y} end
require 'optim' -- modified to include a threshold for relative changes in the loss function as stopping criterion local lbfgs_mod = require 'lbfgs' --- --- MAIN FUNCTIONS --- function runOptimization(params, net, content_image, content_losses, style_losses, temporal_losses, img, frameIdx, runIdx, max_iter, CSR) local isMultiPass = (runIdx ~= -1) -- Run it through the network once to get the proper size for the gradient -- All the gradients will come from the extra loss modules, so we just pass -- zeros into the top of the net on the backward pass. local y = net:forward(img) local dy = img.new(#y):zero() -- Declaring this here lets us access it in maybe_print local optim_state = nil if params.optimizer == 'lbfgs' then optim_state = { maxIter = max_iter, tolFunRelative = params.tol_loss_relative, tolFunRelativeInterval = params.tol_loss_relative_interval, verbose=true, } elseif params.optimizer == 'adam' then optim_state = { learningRate = params.learning_rate, } else error(string.format('Unrecognized optimizer "%s"', params.optimizer)) end local function maybe_print(t, loss, alwaysPrint) local should_print = (params.print_iter > 0 and t % params.print_iter == 0) or alwaysPrint if should_print then print(string.format('Iteration %d / %d', t, max_iter)) for i, loss_module in ipairs(content_losses) do print(string.format(' Content %d loss: %f', i, loss_module.loss)) end for i, loss_module in ipairs(temporal_losses) do print(string.format(' Temporal %d loss: %f', i, loss_module.loss)) end for i, loss_module in ipairs(style_losses) do print(string.format(' Style %d loss: %f', i, loss_module.loss)) end print(string.format(' Total loss: %f', loss)) end end local function print_end(t) --- calculate total loss local loss = 0 for _, mod in ipairs(content_losses) do loss = loss + mod.loss end for _, mod in ipairs(temporal_losses) do loss = loss + mod.loss end for _, mod in ipairs(style_losses) do loss = loss + mod.loss end -- print informations maybe_print(t, loss, true) end local function maybe_save(t, isEnd) local should_save_intermed = params.save_iter > 0 and t % params.save_iter == 0 local should_save_end = t == max_iter or isEnd if should_save_intermed or should_save_end then local filename = nil if isMultiPass then filename = build_OutFilename(params, frameIdx, runIdx) else filename = build_OutFilename(params, math.abs(frameIdx - params.start_number + 1), should_save_end and -1 or t) end save_image(img, filename) end end -- PRE-EVAL AFFINE DATA -- local mean_pixel = torch.CudaTensor({103.939, 116.779, 123.68}) local meanImage = mean_pixel:view(3, 1, 1):expandAs(content_image) -- END PRE-EVAL AFFINE DATA -- -- Function to evaluate loss and gradient. We run the net forward and -- backward to get the gradient, and sum up losses from the loss modules. -- optim.lbfgs internally handles iteration and calls this fucntion many -- times, so we manually count the number of iterations to handle printing -- and saving intermediate results. local num_calls = 0 local best local function feval(x) num_calls = num_calls + 1 -- AFFINE PRE-PROCESSING local output = torch.add(x, meanImage) local input = torch.add(content_image, meanImage) -- END AFFINE PRE-PROCESSING net:forward(x) --local grad = net:backward(x, dy) -- ADD AFFINE CODE FROM PHOTO local grad = net:updateGradInput(x, dy) local c, h, w = content_image:size(1), content_image:size(2), content_image:size(3) local gradient_LocalAffine = MattingLaplacian(output, CSR, h, w):mul(params.lambda) if num_calls % params.save_iter_affine == 0 then best = SmoothLocalAffine(output, input, params.eps, params.patch, h, w, params.f_radius, params.f_edge) end grad = torch.add(grad, gradient_LocalAffine) -- END AFFINE CODE FROM PHOTO local loss = 0 for _, mod in ipairs(content_losses) do loss = loss + mod.loss end for _, mod in ipairs(temporal_losses) do loss = loss + mod.loss end for _, mod in ipairs(style_losses) do loss = loss + mod.loss end maybe_print(num_calls, loss, false) -- Only need to print if single-pass algorithm is used. if not isMultiPass then maybe_save(num_calls, false) end collectgarbage() -- optim.lbfgs expects a vector for gradients return loss, grad:view(grad:nElement()) end start_time = os.time() -- Run optimization. if params.optimizer == 'lbfgs' then print('Running optimization with L-BFGS') local x, losses = lbfgs_mod.optimize(feval, img, optim_state) elseif params.optimizer == 'adam' then print('Running optimization with ADAM') for t = 1, max_iter do local x, losses = optim.adam(feval, img, optim_state) end end end_time = os.time() elapsed_time = os.difftime(end_time-start_time) print("Running time: " .. elapsed_time .. "s") fn = params.serial .. '/best' .. tostring(frameIdx) .. tostring(params.index) .. '_t_' .. 'final' .. '.png' image.save(fn, best) -- Library image, ask to save. print_end(num_calls) maybe_save(num_calls, true) end -- Rebuild the network, insert style loss and return the indices for content and temporal loss function buildNet(cnn, params, color_codes, style_image_caffe, color_content_masks, color_style_masks) local content_layers = params.content_layers:split(",") local style_layers = params.style_layers:split(",") -- Which layer to use for the temporal loss. By default, it uses a pixel based loss, masked by the certainty --(indicated by initWeighted). local temporal_layers = params.temporal_weight > 0 and {'initWeighted'} or {} local style_losses = {} local contentLike_layers_indices = {} local contentLike_layers_type = {} local next_content_i, next_style_i, next_temporal_i = 1, 1, 1 local current_layer_index = 1 local net = nn.Sequential() -- Set up pixel based loss. if temporal_layers[next_temporal_i] == 'init' or temporal_layers[next_temporal_i] == 'initWeighted' then print("Setting up temporal consistency.") table.insert(contentLike_layers_indices, current_layer_index) table.insert(contentLike_layers_type, (temporal_layers[next_temporal_i] == 'initWeighted') and 'prevPlusFlowWeighted' or 'prevPlusFlow') next_temporal_i = next_temporal_i + 1 end -- Set up other loss modules. -- For content loss, only remember the indices at which they are inserted, because the content changes for each frame. if params.tv_weight > 0 then local tv_mod = nn.TVLoss(params.tv_weight):float() tv_mod = MaybePutOnGPU(tv_mod, params) net:add(tv_mod) current_layer_index = current_layer_index + 1 end for i = 1, #cnn do if next_content_i <= #content_layers or next_style_i <= #style_layers or next_temporal_i <= #temporal_layers then local layer = cnn:get(i) local name = layer.name local layer_type = torch.type(layer) local is_pooling = (layer_type == 'cudnn.SpatialMaxPooling' or layer_type == 'nn.SpatialMaxPooling') -- SPECIAL LAYER DETECTION FOR PHOTO local is_conv = (layer_type == 'nn.SpatialConvolution' or layer_type == 'cudnn.SpatialConvolution') -- END if is_pooling and params.pooling == 'avg' then assert(layer.padW == 0 and layer.padH == 0) local kW, kH = layer.kW, layer.kH local dW, dH = layer.dW, layer.dH local avg_pool_layer = nn.SpatialAveragePooling(kW, kH, dW, dH):float() avg_pool_layer = MaybePutOnGPU(avg_pool_layer, params) local msg = 'Replacing max pooling at layer %d with average pooling' print(string.format(msg, i)) net:add(avg_pool_layer) else net:add(layer) end -- SPECIAL CONTENT AND STYLE MASK PREPROCESSING PER CNN LAYER if is_pooling then for k = 1, #color_codes do color_content_masks[k] = image.scale(color_content_masks[k], math.ceil(color_content_masks[k]:size(2)/2), math.ceil(color_content_masks[k]:size(1)/2)) color_style_masks[k] = image.scale(color_style_masks[k], math.ceil(color_style_masks[k]:size(2)/2), math.ceil(color_style_masks[k]:size(1)/2)) end elseif is_conv then local sap = nn.SpatialAveragePooling(3,3,1,1,1,1):float() for k = 1, #color_codes do color_content_masks[k] = sap:forward(color_content_masks[k]:repeatTensor(1,1,1))[1]:clone() color_style_masks[k] = sap:forward(color_style_masks[k]:repeatTensor(1,1,1))[1]:clone() end end color_content_masks = deepcopy(color_content_masks) color_style_masks = deepcopy(color_style_masks) -- END SPECIAL PROCESSING current_layer_index = current_layer_index + 1 if name == content_layers[next_content_i] then print("Setting up content layer", i, ":", layer.name) table.insert(contentLike_layers_indices, current_layer_index) table.insert(contentLike_layers_type, 'content') next_content_i = next_content_i + 1 end if name == temporal_layers[next_temporal_i] then print("Setting up temporal layer", i, ":", layer.name) table.insert(contentLike_layers_indices, current_layer_index) table.insert(contentLike_layers_type, 'prevPlusFlow') next_temporal_i = next_temporal_i + 1 end if name == style_layers[next_style_i] then print("Setting up style layer ", i, ":", layer.name) local gram = GramMatrix():float() gram = MaybePutOnGPU(gram, params) local target = nil local target_features = net:forward(style_image_caffe):clone() local target_grams = {} -- local target_features = net:forward(style_image_caffe):clone() -- local target_i = gram:forward(target_features):clone() -- target_i:div(target_features:nElement()) -- target_i:mul(style_blend_weights) -- target = target_i for j = 1, #color_codes do local l_style_mask_ori = color_style_masks[j]:clone():cuda() local l_style_mask = l_style_mask_ori:repeatTensor(1,1,1):expandAs(target_features) local l_style_mean = l_style_mask_ori:mean() local masked_target_features = torch.cmul(l_style_mask, target_features) local masked_target_gram = gram:forward(masked_target_features):clone() if l_style_mean > 0 then masked_target_gram:div(target_features:nElement() * l_style_mean) end table.insert(target_grams, masked_target_gram) end --local norm = params.normalize_gradients local loss_module = nn.StyleLossWithSeg(params.style_weight, target_grams, color_content_masks, color_codes, next_style_idx, false):float() loss_module = MaybePutOnGPU(loss_module, params) net:add(loss_module) current_layer_index = current_layer_index + 1 table.insert(style_losses, loss_module) next_style_i = next_style_i + 1 end end end return net, style_losses, contentLike_layers_indices, contentLike_layers_type end -- -- AFFINE MODULES FROM PHOTO -- function MattingLaplacian(output, CSR, h, w) local N, c = CSR:size(1), CSR:size(2) local CSR_rowIdx = torch.CudaIntTensor(N):copy(torch.round(CSR[{{1,-1},1}])) local CSR_colIdx = torch.CudaIntTensor(N):copy(torch.round(CSR[{{1,-1},2}])) local CSR_val = torch.CudaTensor(N):copy(CSR[{{1,-1},3}]) local output01 = torch.div(output, 256.0) local grad = cuda_utils.matting_laplacian(output01, h, w, CSR_rowIdx, CSR_colIdx, CSR_val, N) grad:div(256.0) return grad end function SmoothLocalAffine(output, input, epsilon, patch, h, w, f_r, f_e) local output01 = torch.div(output, 256.0) local input01 = torch.div(input, 256.0) local filter_radius = f_r local sigma1, sigma2 = filter_radius / 3, f_e local best01= cuda_utils.smooth_local_affine(output01, input01, epsilon, patch, h, w, filter_radius, sigma1, sigma2) return best01 end -- -- LOSS MODULES -- -- Define an nn Module to compute content loss in-place local ContentLoss, parent = torch.class('nn.ContentLoss', 'nn.Module') function ContentLoss:__init(strength, target, normalize) parent.__init(self) self.strength = strength self.target = target self.normalize = normalize or false self.loss = 0 self.crit = nn.MSECriterion() end function ContentLoss:updateOutput(input) if input:nElement() == self.target:nElement() then self.loss = self.crit:forward(input, self.target) * self.strength else print('WARNING: Skipping content loss') end self.output = input return self.output end function ContentLoss:updateGradInput(input, gradOutput) if input:nElement() == self.target:nElement() then self.gradInput = self.crit:backward(input, self.target) end if self.normalize then self.gradInput:div(torch.norm(self.gradInput, 1) + 1e-8) end self.gradInput:mul(self.strength) self.gradInput:add(gradOutput) return self.gradInput end -- Define an nn Module to compute content loss in-place local WeightedContentLoss, parent = torch.class('nn.WeightedContentLoss', 'nn.Module') function WeightedContentLoss:__init(strength, target, weights, normalize, loss_criterion) parent.__init(self) self.strength = strength if weights ~= nil then -- Take square root of the weights, because of the way the weights are applied -- to the mean square error function. We want w*(error^2), but we can only -- do (w*error)^2 = w^2 * error^2 self.weights = torch.sqrt(weights) self.target = torch.cmul(target, self.weights) else self.target = target self.weights = nil end self.normalize = normalize or false self.loss = 0 if loss_criterion == 'mse' then self.crit = nn.MSECriterion() elseif loss_criterion == 'smoothl1' then self.crit = nn.SmoothL1Criterion() else print('WARNING: Unknown flow loss criterion. Using MSE.') self.crit = nn.MSECriterion() end end function WeightedContentLoss:updateOutput(input) if input:nElement() == self.target:nElement() then self.loss = self.crit:forward(input, self.target) * self.strength if self.weights ~= nil then self.loss = self.crit:forward(torch.cmul(input, self.weights), self.target) * self.strength else self.loss = self.crit:forward(input, self.target) * self.strength end else print('WARNING: Skipping content loss') end self.output = input return self.output end function WeightedContentLoss:updateGradInput(input, gradOutput) if input:nElement() == self.target:nElement() then if self.weights ~= nil then self.gradInput = self.crit:backward(torch.cmul(input, self.weights), self.target) else self.gradInput = self.crit:backward(input, self.target) end end if self.normalize then self.gradInput:div(torch.norm(self.gradInput, 1) + 1e-8) end self.gradInput:mul(self.strength) self.gradInput:add(gradOutput) return self.gradInput end -- Returns a network that computes the CxC Gram matrix from inputs -- of size C x H x W function GramMatrix() local net = nn.Sequential() net:add(nn.View(-1):setNumInputDims(2)) local concat = nn.ConcatTable() concat:add(nn.Identity()) concat:add(nn.Identity()) net:add(concat) net:add(nn.MM(false, true)) return net end -- Define style loss with segmentation local StyleLossWithSeg, parent = torch.class('nn.StyleLossWithSeg', 'nn.Module') --function StyleLossWithSeg:__init(strength, target_grams, color_content_masks, content_seg_idxs, layer_id) function StyleLossWithSeg:__init(strength, target_grams, color_content_masks, color_codes, layer_id) parent.__init(self) self.strength = strength self.target_grams = target_grams self.color_content_masks = deepcopy(color_content_masks) self.color_codes = color_codes --self.content_seg_idxs = content_seg_idxs self.loss = 0 self.gram = GramMatrix() self.crit = nn.MSECriterion() self.layer_id = layer_id end function StyleLossWithSeg:updateOutput(input) self.output = input return self.output end function StyleLossWithSeg:updateGradInput(input, gradOutput) self.loss = 0 self.gradInput = gradOutput:clone() self.gradInput:zero() for j = 1, #self.color_codes do local l_content_mask_ori = self.color_content_masks[j]:clone():cuda() local l_content_mask = l_content_mask_ori:repeatTensor(1,1,1):expandAs(input) local l_content_mean = l_content_mask_ori:mean() local masked_input_features = torch.cmul(l_content_mask, input) local masked_input_gram = self.gram:forward(masked_input_features):clone() if l_content_mean > 0 then masked_input_gram:div(input:nElement() * l_content_mean) end local loss_j = self.crit:forward(masked_input_gram, self.target_grams[j]) loss_j = loss_j * self.strength * l_content_mean self.loss = self.loss + loss_j local dG = self.crit:backward(masked_input_gram, self.target_grams[j]) dG:div(input:nElement()) local gradient = self.gram:backward(masked_input_features, dG) if self.normalize then gradient:div(torch.norm(gradient, 1) + 1e-8) end self.gradInput:add(gradient) end self.gradInput:mul(self.strength) self.gradInput:add(gradOutput) return self.gradInput end -- Define an nn Module to compute style loss in-place local StyleLoss, parent = torch.class('nn.StyleLoss', 'nn.Module') function StyleLoss:__init(strength, target, normalize) parent.__init(self) self.normalize = normalize or false self.strength = strength self.target = target self.loss = 0 self.gram = GramMatrix() self.G = nil self.crit = nn.MSECriterion() end function StyleLoss:updateOutput(input) self.G = self.gram:forward(input) self.G:div(input:nElement()) self.loss = self.crit:forward(self.G, self.target) self.loss = self.loss * self.strength self.output = input return self.output end function StyleLoss:updateGradInput(input, gradOutput) local dG = self.crit:backward(self.G, self.target) dG:div(input:nElement()) self.gradInput = self.gram:backward(input, dG) if self.normalize then self.gradInput:div(torch.norm(self.gradInput, 1) + 1e-8) end self.gradInput:mul(self.strength) self.gradInput:add(gradOutput) return self.gradInput end local TVLoss, parent = torch.class('nn.TVLoss', 'nn.Module') function TVLoss:__init(strength) parent.__init(self) self.strength = strength self.x_diff = torch.Tensor() self.y_diff = torch.Tensor() end function TVLoss:updateOutput(input) self.output = input return self.output end -- TV loss backward pass inspired by kaishengtai/neuralart function TVLoss:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input):zero() local C, H, W = input:size(1), input:size(2), input:size(3) self.x_diff:resize(3, H - 1, W - 1) self.y_diff:resize(3, H - 1, W - 1) self.x_diff:copy(input[{{}, {1, -2}, {1, -2}}]) self.x_diff:add(-1, input[{{}, {1, -2}, {2, -1}}]) self.y_diff:copy(input[{{}, {1, -2}, {1, -2}}]) self.y_diff:add(-1, input[{{}, {2, -1}, {1, -2}}]) self.gradInput[{{}, {1, -2}, {1, -2}}]:add(self.x_diff):add(self.y_diff) self.gradInput[{{}, {1, -2}, {2, -1}}]:add(-1, self.x_diff) self.gradInput[{{}, {2, -1}, {1, -2}}]:add(-1, self.y_diff) self.gradInput:mul(self.strength) self.gradInput:add(gradOutput) return self.gradInput end function getContentLossModuleForLayer(net, layer_idx, target_img, params) local tmpNet = nn.Sequential() for i = 1, layer_idx-1 do local layer = net:get(i) tmpNet:add(layer) end local target = tmpNet:forward(target_img):clone() local loss_module = nn.ContentLoss(params.content_weight, target, params.normalize_gradients):float() loss_module = MaybePutOnGPU(loss_module, params) return loss_module end function getWeightedContentLossModuleForLayer(net, layer_idx, target_img, params, weights) local tmpNet = nn.Sequential() for i = 1, layer_idx-1 do local layer = net:get(i) tmpNet:add(layer) end local target = tmpNet:forward(target_img):clone() local loss_module = nn.WeightedContentLoss(params.temporal_weight, target, weights, params.normalize_gradients, params.temporal_loss_criterion):float() loss_module = MaybePutOnGPU(loss_module, params) return loss_module end --- --- HELPER FUNCTIONS --- function MaybePutOnGPU(obj, params) if params.gpu >= 0 then if params.backend ~= 'clnn' then return obj:cuda() else return obj:cl() end end return obj end -- COPIED FROM PHOTO STYLE (NO CONFLICTS) function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- number, string, boolean, etc copy = orig end return copy end -- COPIED FROM PHOT STYLE (NO CONFLICTS) function ExtractMask(seg, color) local mask = nil if color == 'GREEN' then mask = torch.lt(seg[1], 0.15) mask:cmul(torch.gt(seg[2], 1-0.2)) mask:cmul(torch.lt(seg[3], 0.15)) elseif color == 'PURPLISH_RED' then mask = torch.cmul(torch.gt(seg[1], 0.5), torch.lt(seg[1], 0.5+0.3)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.2), torch.lt(seg[2], 0.4))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.3), torch.lt(seg[3], 0.55))) elseif color == 'ORANGE_YELLOW' then mask = torch.cmul(torch.gt(seg[1], 0.8), torch.lt(seg[1], 0.95)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.55), torch.lt(seg[2], 0.75))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.25), torch.lt(seg[3], 0.45))) elseif color == 'VIOLET' then mask = torch.cmul(torch.gt(seg[1], 0.3), torch.lt(seg[1], 0.5)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.3), torch.lt(seg[2], 0.4))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.4), torch.lt(seg[3], 0.7))) elseif color == 'PURPLISH_PINK' then mask = torch.cmul(torch.gt(seg[1], 0.75), torch.lt(seg[1], 0.95)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.5), torch.lt(seg[2], 0.7))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.55), torch.lt(seg[3], 0.8))) elseif color == 'BUFF' then mask = torch.gt(seg[1], 0.85) mask:cmul(torch.cmul(torch.gt(seg[2], 0.75), torch.lt(seg[2], 0.95))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.4), torch.lt(seg[3], 0.6))) elseif color == 'ORANGE' then mask = torch.cmul(torch.gt(seg[1], 0.8), torch.lt(seg[1], 1)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.55), torch.lt(seg[2], 0.75))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.0), torch.lt(seg[3], 0.2))) elseif color == 'BROWN' then mask = torch.cmul(torch.gt(seg[1], 0.25), torch.lt(seg[1], 0.35)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.15), torch.lt(seg[2], 0.25))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.15), torch.lt(seg[3], 0.25))) elseif color == 'KHAKHI' then mask = torch.cmul(torch.gt(seg[1], 0.35), torch.lt(seg[1], 0.55)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.35), torch.lt(seg[2], 0.55))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.2), torch.lt(seg[3], 0.4))) elseif color == 'PINK' then mask = torch.cmul(torch.gt(seg[1], 0.6), torch.lt(seg[1], 0.8)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.35), torch.lt(seg[2], 0.55))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.35), torch.lt(seg[3], 0.55))) elseif color == 'BLACK' then mask = torch.lt(seg[1], 0.1) mask:cmul(torch.lt(seg[2], 0.1)) mask:cmul(torch.lt(seg[3], 0.1)) elseif color == 'WHITE' then mask = torch.gt(seg[1], 1-0.1) mask:cmul(torch.gt(seg[2], 1-0.1)) mask:cmul(torch.gt(seg[3], 1-0.1)) elseif color == 'RED' then mask = torch.gt(seg[1], 1-0.2) mask:cmul(torch.lt(seg[2], 0.15)) mask:cmul(torch.lt(seg[3], 0.15)) elseif color == 'BLUE' then mask = torch.lt(seg[1], 0.15) mask:cmul(torch.lt(seg[2], 0.15)) mask:cmul(torch.gt(seg[3], 1-0.2)) elseif color == 'YELLOW' then mask = torch.gt(seg[1], 1-0.2) mask:cmul(torch.gt(seg[2], 1-0.2)) mask:cmul(torch.lt(seg[3], 0.15)) elseif color == 'GREY' then mask = torch.cmul(torch.gt(seg[1], 0.5-0.1), torch.lt(seg[1], 0.5+0.1)) mask:cmul(torch.cmul(torch.gt(seg[2], 0.5-0.1), torch.lt(seg[2], 0.5+0.1))) mask:cmul(torch.cmul(torch.gt(seg[3], 0.5-0.1), torch.lt(seg[3], 0.5+0.1))) elseif color == 'LIGHT_BLUE' then mask = torch.lt(seg[1], 0.15) mask:cmul(torch.gt(seg[2], 1-0.15)) mask:cmul(torch.gt(seg[3], 1-0.15)) elseif color == 'PURPLE' then mask = torch.gt(seg[1], 1-0.2) mask:cmul(torch.lt(seg[2], 0.15)) mask:cmul(torch.gt(seg[3], 1-0.2)) else print('ExtractMask(): color not recognized, color = ', color) end return mask:float() end -- Preprocess an image before passing it to a Caffe model. -- We need to rescale from [0, 1] to [0, 255], convert from RGB to BGR, -- and subtract the mean pixel. function preprocess(img) local mean_pixel = torch.DoubleTensor({103.939, 116.779, 123.68}) local perm = torch.LongTensor{3, 2, 1} img = img:index(1, perm):mul(256.0) mean_pixel = mean_pixel:view(3, 1, 1):expandAs(img) img:add(-1, mean_pixel) return img end -- Undo the above preprocessing. function deprocess(img) local mean_pixel = torch.DoubleTensor({103.939, 116.779, 123.68}) mean_pixel = mean_pixel:view(3, 1, 1):expandAs(img) img = img + mean_pixel local perm = torch.LongTensor{3, 2, 1} img = img:index(1, perm):div(256.0) return img end function save_image(img, fileName) local disp = deprocess(img:double()) disp = image.minmax{tensor=disp, min=0, max=1} image.save(fileName, disp) end -- Checks whether a table contains a specific value function tabl_contains(tabl, val) for i=1,#tabl do if tabl[i] == val then return true end end return false end -- Sums up all element in a given table function tabl_sum(t) local sum = t[1]:clone() for i=2, #t do sum:add(t[i]) end return sum end function str_split(str, delim, maxNb) -- Eliminate bad cases... if string.find(str, delim) == nil then return { str } end if maxNb == nil or maxNb < 1 then maxNb = 0 -- No limit end local result = {} local pat = "(.-)" .. delim .. "()" local nb = 1 local lastPos for part, pos in string.gfind(str, pat) do result[nb] = part lastPos = pos nb = nb + 1 if nb == maxNb then break end end -- Handle the last field result[nb] = string.sub(str, lastPos) return result end function fileExists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function calcNumberOfContentImages(params) local frameIdx = 1 while frameIdx < 100000 do local fileName = string.format(params.content_pattern, frameIdx + params.start_number) if not fileExists(fileName) then return frameIdx end frameIdx = frameIdx + 1 end -- If there are too many content frames, something may be wrong. return 0 end function build_OutFilename(params, image_number, iterationOrRun) local ext = paths.extname(params.output_image) local basename = paths.basename(params.output_image, ext) local fileNameBase = '%s%s-' .. params.number_format if iterationOrRun == -1 then return string.format(fileNameBase .. '.%s', params.output_folder, basename, image_number, ext) else return string.format(fileNameBase .. '_%d.%s', params.output_folder, basename, image_number, iterationOrRun, ext) end end function getFormatedFlowFileName(pattern, fromIndex, toIndex) local flowFileName = pattern flowFileName = string.gsub(flowFileName, '{(.-)}', function(a) return string.format(a, fromIndex) end ) flowFileName = string.gsub(flowFileName, '%[(.-)%]', function(a) return string.format(a, toIndex) end ) return flowFileName end function getContentImage(frameIdx, params) local fileName = string.format(params.content_pattern, frameIdx) if not fileExists(fileName) then return nil end local content_image = image.load(string.format(params.content_pattern, frameIdx), 3) -- Load Segmentation -- local segmentation_img = image.load(string.format(params.content_segmentation_path,frameIdx), 3) local img_scale = math.sqrt(content_image:size(2) * content_image:size(3) / (segmentation_img:size(3) * segmentation_img:size(2))) segmentation_img = image.scale(segmentation_img, segmentation_img:size(3) * img_scale, segmentation_img:size(2) * img_scale, 'bilinear') print("Content Segementation image size: " .. segmentation_img:size(3) .. " x " .. segmentation_img:size(2)) segmentation_img = MaybePutOnGPU(segmentation_img, params) -- --- -- --- content_image = preprocess(content_image):float() content_image = MaybePutOnGPU(content_image, params) return content_image, segmentation_img end function getStyleImages(params) -- Needed to read content image size local firstContentImg = image.load(string.format(params.content_pattern, params.start_number), 3) local style_image_list = params.style_image:split(',') local style_images_caffe = {} -- Load Segmentation Image -- local segmentation_img = image.load(params.style_segmentation_image, 3) local img_scale = math.sqrt(firstContentImg:size(2) * firstContentImg:size(3) / (segmentation_img:size(3) * segmentation_img:size(2))) segmentation_img = image.scale(segmentation_img, segmentation_img:size(3) * img_scale, segmentation_img:size(2) * img_scale, 'bilinear') print("Style Segementation image size: " .. segmentation_img:size(3) .. " x " .. segmentation_img:size(2)) segmentation_img = MaybePutOnGPU(segmentation_img, params) --- ---- --- ---- --- --- for _, img_path in ipairs(style_image_list) do local img = image.load(img_path, 3) * params.style_scale -- Scale the style image so that it's area equals the area of the content image multiplied by the style scale. local img_scale = math.sqrt(firstContentImg:size(2) * firstContentImg:size(3) / (img:size(3) * img:size(2))) img = image.scale(img, img:size(3) * img_scale, img:size(2) * img_scale, 'bilinear') print("Style image size: " .. img:size(3) .. " x " .. img:size(2)) local img_caffe = preprocess(img):float() table.insert(style_images_caffe, img_caffe) end for i = 1, #style_images_caffe do style_images_caffe[i] = MaybePutOnGPU(style_images_caffe[i], params) end return style_images_caffe,segmentation_img end
local class = require('opus.class') local UI = require('opus.ui') UI.MenuItem = class(UI.FlatButton) UI.MenuItem.defaults = { UIElement = 'MenuItem', noPadding = false, textInactiveColor = 'gray', }
function test() local a, b, c end jit("compile", test) test() --[[ function <../tests/4_OP_LOADNIL.lua:1,3> (2 instructions at 0x1800500) 0 params, 3 slots, 0 upvalues, 3 locals, 0 constants, 0 functions 1 [2] LOADNIL 0 2 2 [3] RETURN 0 1 constants (0) for 0x1800500: locals (3) for 0x1800500: 0 a 2 3 1 b 2 3 2 c 2 3 upvalues (0) for 0x1800500: ]] --[[ ra = R(0); setnilvalue(ra++); setnilvalue(ra++); setnilvalue(ra++); ]]
BusStop = {} -- Gets the hash of the bus stop from the given coordinates BusStop.CalculateHash = function(coords) local x = math.floor(coords.x) local y = math.floor(coords.y) return sha1.hex('busstop:' .. tostring(x) .. ':' .. tostring(y)) end
biter_ai_settings = { destroy_when_commands_fail = true, allow_try_return_to_spawner = true }
--[[ Purpose: Provides a wrapper for database interaction so switching from mysqloo or tmysql4 can be quickly done without much hassle. There are also some utility functions for the database. --]] nut.db = nut.db or {} local dbModule = nut.config.dbModule -- SQLite doesn't need a module! if (dbModule != "sqlite") then require(nut.config.dbModule) else local SQL_CURR_VERSION = 0 local SQL_CONFIRMING = 0 SQL_LOCAL_VERSION = SQL_LOCAL_VERSION or tonumber(file.Read("nutscript/db.txt", "DATA") or 0) -- But it does require the script to setup a table. local QUERY_CREATE = [[ CREATE TABLE ]]..nut.config.dbTable..[[ ( steamid int, charname varchar(60), description varchar(240), gender varchar(6), money int, inv mediumtext, faction int, id int, chardata mediumtext, rpschema varchar(16), model tinytext ); ]] local QUERY_CREATE_PLAYERS = [[ CREATE TABLE ]]..nut.config.dbPlyTable..[[ ( steamid int, whitelists tinytext, plydata mediumtext, rpschema tinytext ); ]] local function initializeTables(recreate) local success = true if (recreate) then sql.Query("DROP TABLE "..nut.config.dbTable) sql.Query("DROP TABLE "..nut.config.dbPlyTable) end if (!sql.TableExists(nut.config.dbTable)) then local result = sql.Query(QUERY_CREATE) if (result == false) then MsgC(Color(255, 0, 0), "[Advanced Nutscript] Framework could not create characters table!\n") print(sql.LastError()) success = false else MsgC(Color(0, 255, 0), "[Advanced Nutscript] Framework has created characters table.\n") end else success = false end if (!sql.TableExists(nut.config.dbPlyTable)) then local result = sql.Query(QUERY_CREATE_PLAYERS) if (result == false) then MsgC(Color(255, 0, 0), "[Advanced Nutscript] Framework could not create players table!\n") print(sql.LastError()) success = false else MsgC(Color(0, 255, 0), "[Advanced Nutscript] Framework has created players table.\n") end else success = false end if (success) then MsgC(Color(0, 255, 0), "[Advanced Nutscript] Framework has created database tables correctly!\n") file.Write("nutscript/db.txt", SQL_CURR_VERSION) SQL_LOCAL_VERSION = SQL_CURR_VERSION end end initializeTables() if (SQL_LOCAL_VERSION != SQL_CURR_VERSION) then MsgC(Color(255, 255, 0), "\n[Advanced Nutscript] Framework has had its database tables updated.\n") MsgC(Color(255, 255, 0), "[Advanced Nutscript] You will need to enter the command: "); MsgN("nut_recreatedb") MsgC(Color(255, 255, 0), "[Advanced Nutscript] You will need to enter the command: "); MsgN("nut_recreatedb") MsgC(Color(255, 255, 0), "[Advanced Nutscript] Updating the tables will remove ALL pre-existing data.\n") MsgC(Color(255, 255, 0), "[Advanced Nutscript] Not updating the tables MAY CAUSE SAVING/LOADED ERRORS!\n\n") end concommand.Add("nut_recreatedb", function(client, command, arguments) if (!IsValid(client) or client:IsListenServerHost()) then if ((!SQL_CONFIRMING or SQL_CONFIRMING < CurTime()) and SQL_LOCAL_VERSION == SQL_CURR_VERSION) then MsgN("[Advanced Nutscript] Framework has verified that the table versions match.") MsgN("[Advanced Nutscript] If you would like to recreate the tables, type the command again within 10 seconds.") SQL_CONFIRMING = CurTime() + 10 return end initializeTables(true) SQL_CONFIRMING = 0 end end) end --[[ Purpose: Connects to the database using the configuration values from sv_config.lua and connects using the defined modules from the config file. --]] function nut.db.Connect() if (dbModule == "sqlite") then if (nut.db.sqliteInit == true) then return end MsgC(Color(0, 255, 0), "[Advanced Nutscript] using SQLite for database.\n"); nut.db.sqliteInit = true return end if (nut.db.object) then return end local hostname = nut.config.dbHost local username = nut.config.dbUser local password = nut.config.dbPassword local database = nut.config.dbDatabase local port = nut.config.dbPort if (dbModule == "tmysql4") then local fault; nut.db.object, fault = tmysql.initialize(hostname, username, password, database, port) if (!fault) then print("[Advanced Nutscript] Framework has connected to the database via tmysql4."); else print("[Advanced Nutscript] Framework could not connect to the database!") print(fault) end else nut.db.object = mysqloo.connect(hostname, username, password, database, port) nut.db.object.onConnected = function() print("[Advanced Nutscript] Framework has connected to the database via mysqloo.") end nut.db.object.onConnectionFailed = function(_, fault) print("[Advanced Nutscript] Framework could not connect to the database!") print(fault) end nut.db.object:connect() end end nut.db.Connect() --[[ Purpose: An alias to the current module's function to escape a string. --]] function nut.db.Escape(value) if (dbModule == "tmysql4") then return tmysql.escape(value) elseif (dbModule == "mysqloo") then return nut.db.object:escape(value) else return sql.SQLStr(value) end end --[[ Purpose: Makes a query using either tmysql4 or mysqloo and runs the callback function passing the data. --]] function nut.db.Query(query, callback) if (dbModule == "tmysql4") then nut.db.object:Query(query, function(result, status, fault) if (status == false) then print("Query Error: "..query) print(fault) elseif (callback) then callback(result[1], result) end end, QUERY_FLAG_ASSOC) elseif (dbModule == "mysqloo") then local result = nut.db.object:query(query) if (result) then if (callback) then result.onSuccess = function(_, data) callback(data[1], data) end end result.onError = function(_, fault) print("Query Error: "..query); print(fault) end result:start() end else local data = sql.Query(query) if (data == false) then print("Query Error: "..query) print(sql.LastError()) else local value = {} if (data and data[1]) then value = data[1] value.faction = tonumber(value.faction) value.id = tonumber(value.id) end if (callback) then callback(value, data or {}) end end end end --[[ Purpose: Inserts a table matching the key with a field in the database and a value as the value for the field. --]] function nut.db.InsertTable(data, callback, dbTable) local query = "INSERT INTO "..(dbTable or nut.config.dbTable).." (" for k, v in pairs(data) do query = query..k..", " end query = string.sub(query, 1, -3)..") VALUES (" for k, v in pairs(data) do if (type(k) == "string" and k != "steamid") then if (type(v) == "table") then v = pon.encode(v) end -- SQLite doesn't play nice with quotations. if (type(v) == "string") then if (dbModule == "sqlite") then v = nut.db.Escape(v) else v = "'"..nut.db.Escape(v).."'" end end end query = query..v..", " end query = string.sub(query, 1, -3)..")" nut.db.Query(query, callback) end --[[ Purpose: Similar to insert table, it will update the values that are passed through the second argument given the condition is true. --]] function nut.db.UpdateTable(condition, data, dbTable) local query = "UPDATE "..(dbTable or nut.config.dbTable).." SET " for k, v in pairs(data) do query = query..nut.db.Escape(k).." = " if (type(k) == "string" and k != "steamid") then if (type(v) == "table") then v = pon.encode(v) end -- SQLite doesn't play nice with quotations. if (type(v) == "string") then if (dbModule == "sqlite") then v = nut.db.Escape(v) else v = "'"..nut.db.Escape(v).."'" end end end query = query..v..", " end query = string.sub(query, 1, -3).." WHERE "..condition nut.db.Query(query, callback) end --[[ Purpose: Returns the values of given fields that are seperated by a comma and passes them into the callback function given the condition provided is true. --]] function nut.db.FetchTable(condition, tables, callback, dbTable) local query = "SELECT "..tables.." FROM "..(dbTable or nut.config.dbTable).." WHERE "..condition nut.db.Query(query, callback) end
local sti = require("lib/sti") local anim8 = require("lib/anim8") function love.load() map = sti.new("assets/maps/level") heroSprites = love.graphics.newImage("assets/spritesheets/pimple.gif") movementGrid = anim8.newGrid(58, 80, heroSprites:getWidth(), heroSprites:getHeight(), 0, 0, 3) stillGrid = anim8.newGrid(41, 70, heroSprites:getWidth(), heroSprites:getHeight(), 157, 0, 8) player = { spritesheet = heroSprites, x = 60, y = 382, speed = 140, animations = { still = anim8.newAnimation(stillGrid('1-2', 1), 1.0), right = anim8.newAnimation(movementGrid('1-5', 2), 0.08), left = anim8.newAnimation(movementGrid('1-5', 3), 0.08) }, } player.animation = player.animations.still love.graphics.setBackgroundColor(127, 117, 137) end function love.draw() map:draw() player.animation:draw(player.spritesheet, player.x, player.y) end function love.update(dt) if love.keyboard.isDown("right") then player.x = player.x + (player.speed * dt) player.animation = player.animations.right elseif love.keyboard.isDown("left") then player.x = player.x - (player.speed * dt) player.animation = player.animations.left else player.animation = player.animations.still end map:update(dt) player.animation:update(dt) end
return {'ere','ereambt','erebaan','erebaantje','erebegraafplaats','ereblijk','ereboog','ereburger','ereburgerschap','erecode','erecomite','ereconsul','erectie','erectiemiddel','erectiepil','erectiestoornis','eredame','eredegen','eredienst','erediploma','eredivisie','eredivisieclub','eredivisieduels','eredivisieteam','eredivisievoetbal','eredivisionist','eredoctor','eredoctoraat','erefunctie','eregalerij','eregast','eregaste','eregeld','erehaag','erejury','ereklasse','erekrans','erekruis','erekwestie','erelid','erelidmaatschap','erelijst','erelint','ereloon','eremedaille','eremetaal','eremiet','eremis','eren','erenaam','erepalm','erepenning','ereplaats','ereplak','ereplicht','erepodium','erepoort','erepost','ereprijs','ereronde','eresabel','eresaluut','ereschavot','ereschuld','ereteken','ereterras','eretitel','eretribune','ereveld','erevoorzitter','erewacht','erewijn','erewoord','erewraak','erezaak','erezuil','ereloge','ereorde','erectieprobleem','eredivisieniveau','eredivisiewedstrijd','eremoord','erepark','eretreffer','ereloonnota','erembodegem','erembodegemmenaar','erembodegems','erevan','erents','erenstein','eren','ereambten','ereblijken','erebogen','ereburgers','erecomites','erectiestoornissen','eredames','erediensten','eredivisiewedstrijden','eredoctoraten','eredoctoren','eredoctors','erekransen','erekruisen','ereleden','erelijstje','erelinten','erelonen','eremedailles','eremieten','eremoorden','erenamen','erepalmen','ereplaatsen','erepoorten','ereposten','ereprijzen','ereregels','ereronden','ererondes','ererondje','ererondjes','eresabels','ereschulden','eretekenen','eretekens','eretitels','erevelden','erevoorzitters','erewachten','erezuilen','erecodes','erecties','eredivisieclubs','eredivisies','eredivisionisten','eregasten','eremissen','erepenningen','eretribunes','erezaken','erepodia','erehagen','ereplakken','eresaluten','erectieproblemen','erectiepillen','ereplaatsje','erectiemiddelen','erelijsten','erebaantjes','eredivisieteams'}
--[[ behavior that makes any GridSolver AMR-friendly now to change hydro/solver/gridsolver so I can somehow modify the mins/maxs without reloading any kernels ... --]] local ffi = require 'ffi' local class = require 'ext.class' local table = require 'ext.table' local template = require 'template' local vec3sz = require 'vec-ffi.vec3sz' local roundup = require 'hydro.util.roundup' local int4ptr = ffi.new'int[4]' local function int4(a,b,c,d) int4ptr[0] = a int4ptr[1] = b int4ptr[2] = c int4ptr[3] = d return int4ptr end local function initAMR(self, args) self.amr = args.amr if not self.amr then -- in this case, we are the root: self.amr = { depth = 0, -- shared by all in the tree ctx = { --method = 'dt vs 2dt', method = 'gradient', maxdepth = 1, splitThreshold = .3, mergeThreshold = .0001, -- the size, in cells, which a node replaces nodeFromSize = ({ vec3sz(32, 1, 1), vec3sz(32, 32, 1), vec3sz(32, 32, 32), })[self.dim], nodeSizeWithoutBorder = vec3sz(self.sizeWithoutBorder), }, } -- size of the root level, in terms of nodes ('from' size) self.amr.ctx.parentSizeInFromSize = vec3sz(1,1,1) for i=0,self.dim-1 do self.amr.ctx.parentSizeInFromSize.s[i] = roundup(self.sizeWithoutBorder.s[i], self.amr.ctx.nodeFromSize.s[i]) / self.amr.ctx.nodeFromSize.s[i] end -- number of cells in the node. -- I'm matching this with the root size. if you want to change it then be prepared to change gridSize to be members of solver_t print('nodeSizeWithoutBorder', self.amr.ctx.nodeSizeWithoutBorder) -- number of cells that the node replaces print('nodeFromSize', self.amr.ctx.nodeFromSize) -- how many nodes cover the parent print('parentSizeInFromSize', self.amr.ctx.parentSizeInFromSize) -- make sure that the child boundary is at least as big as one cell in the parent for i=0,2 do assert(self.numGhost >= self.amr.ctx.parentSizeInFromSize.s[i], require 'ext.tolua'{ ['self.numGhost'] =self.numGhost, ['self.amr.ctx.parentSizeInFromSize.s[i]'] = self.amr.ctx.parentSizeInFromSize.s[i], }) end local volume = tonumber(self.amr.ctx.parentSizeInFromSize:volume()) self.amrErrorPtr = ffi.new('real[?]', volume) end self.initArgs = table(args) end local function createBuffersAMR(self) if self.amr.ctx.method == 'gradient' then -- how big each node is self.amr.nodeSize = self.amr.ctx.nodeSizeWithoutBorder + 2 * self.numGhost self.amr.child = table() end -- TODO UBufSize used to go here --[[ this used to go after createBuffers UBufSize if self.amr.ctx.method == 'gradient' then UBufSize = UBufSize + self.amrMaxNodes * self.amr.nodeSize:volume() end --]] if self.amr.ctx.method == 'dt vs 2dt' then -- here's my start at AMR, using the 1989 Berger, Collela two-small-steps vs one-big-step method self:clalloc('lastUBuf', self.eqn.symbols.cons_t, self.numCells) self:clalloc('U2Buf', self.eqn.symbols.cons_t, self.numCells) elseif self.amr.ctx.method == 'gradient' then -- this is going to be a single value for each leaf -- that means the destination will be the number of nodes it takes to cover the grid (excluding the border) -- however, do I want this to be a larger buffer, and then perform reduce on it? self:clalloc('amrErrorBuf', 'real', -- self.volume tonumber(self.amr.ctx.parentSizeInFromSize:volume()), -- here is our one use of buffer 'sizevec': assert(self.amr.ctx.parentSizeInFromSize) ) end end return function(cl) cl = class(cl) local subcl function cl:init(args) -- overriding the gridsize ... args = table(args) args.gridSize = {64,64,1} cl.super.init(self, args) end function cl:initObjs(args) cl.super.initObjs(self, args) initAMR(self, args) end function cl:createBuffers() cl.super.createBuffers(self) createBuffersAMR(self) end function cl:getSolverCode() error'TODO convert this to initCodeModules' return table{ cl.super.getSolverCode(self), self.eqn:template(({ ['dt vs 2dt'] = [[ kernel void compareUvsU2( global <?=cons_t?> * const U2Buf, global <?=cons_t?> const * const UBuf ) { <?=SETBOUNDS?>(0,0); global <?=cons_t?> * const U2 = U2Buf + index; global <?=cons_t?> const * const U = UBuf + index; //what to use to compare values ... //if we combine all primitives, they'll have to be appropriately weighted ... real sum = 0.; real tmp; <? for i=0,eqn.numStates-1 do ?> tmp = U2->ptr[<?=i?>] - U->ptr[<?=i?>]; sum += tmp * tmp; <? end ?> U2->ptr[0] = sum * 1e+5; } ]], gradient = [==[ <? local clnumber = require 'cl.obj.number' ?> kernel void calcAMRError( constant <?=solver_t?> const * const solver, //parent node's solver_t global real * const amrErrorBuf, global <?=cons_t?> const * const UBuf //parent node's UBuf ) { int4 nodei = globalInt4(); if (nodei.x >= <?=solver.amr.ctx.parentSizeInFromSize.x?> || nodei.y >= <?=solver.amr.ctx.parentSizeInFromSize.y?>) { return; } int nodeIndex = nodei.x + <?=solver.amr.ctx.parentSizeInFromSize.x?> * nodei.y; real dV_dx; real sum = 0.; // for (int nx = 0; nx < <?=solver.amr.ctx.nodeFromSize.x?>; ++nx) { // for (int ny = 0; ny < <?=solver.amr.ctx.nodeFromSize.y?>; ++ny) { <? -- without unrolling these for-loops, intel compiler takes 30 seconds (and produces bad asm) for nx=0,tonumber(solver.amr.ctx.nodeFromSize.x)-1 do for ny=0,tonumber(solver.amr.ctx.nodeFromSize.y)-1 do ?>{ int const nx = <?=nx?>; int const ny = <?=ny?>; int4 Ui = (int4)( solver->numGhost + nx + <?=solver.amr.ctx.nodeFromSize.x?> * nodei.x, solver->numGhost + ny + <?=solver.amr.ctx.nodeFromSize.y?> * nodei.y, 0,0); int Uindex = INDEXV(Ui); global <?=cons_t?> const * const U = UBuf + Uindex; //TODO this wasn't the exact formula ... // and TODO make this modular. some papers use velocity vector instead of density. // why not total energy -- that incorporates everything? <? for i=0,solver.dim-1 do ?> dV_dx = (U[solver->stepsize.s<?=i?>].rho - U[-solver->stepsize.s<?=i?>].rho) / (2. * solver->grid_dx.s<?=i?>); sum += dV_dx * dV_dx; <? end ?> // } // } }<? end end ?> amrErrorBuf[nodeIndex] = sum * 1e-2 * <?=clnumber(1/tonumber( solver.amr.ctx.nodeFromSize:volume() ))?>; } kernel void initNodeFromRoot( global <?=cons_t?> * const childUBuf, global <?=cons_t?> const * const parentUBuf, int4 from //where in the child tree ) { //'i' is the dest in the child node to write int4 i = (int4)(0,0,0,0); i.x = get_global_id(0); i.y = get_global_id(1); if (i.x >= <?=solver.amr.nodeSize.x?> || i.y >= <?=solver.amr.nodeSize.y?>) { return; } int dstIndex = i.x + <?=solver.amr.nodeSize.x?> * i.y; //'srci' is the coords within the parent node to read, relative to the child's upper-left int4 srci = (int4)(0,0,0,0); srci.x = i.x / <?= solver.amr.ctx.parentSizeInFromSize.x ?>; srci.y = i.y / <?= solver.amr.ctx.parentSizeInFromSize.y ?>; int srcIndex = solver->numGhost + srci.x + from.x * <?= solver.amr.ctx.parentSizeInFromSize.x ?> + gridSize_x * ( solver->numGhost + srci.y + from.y * <?= solver.amr.ctx.parentSizeInFromSize.y ?> ); //blitter srcU sized solver.amr.ctx.nodeFromSize (in a patch of size solver.gridSize) // to dstU sized solver.amr.nodeSize (in a patch of solver.amr.nodeSize) childUBuf[dstIndex] = parentUBuf[srcIndex]; } ]==], })[self.amr.ctx.method] or ''), }:concat'\n' end function cl:refreshSolverProgram() cl.super.refreshSolverProgram(self) if self.amr.ctx.method == 'dt vs 2dt' then self.compareUvsU2KernelObj = self.solverProgramObj:kernel('compareUvsU2', self.U2Buf, self.UBuf) elseif self.amr.ctx.method == 'gradient' then self.calcAMRErrorKernelObj = self.solverProgramObj:kernel'calcAMRError' self.initNodeFromRootKernelObj = self.solverProgramObj:kernel'initNodeFromRoot' self.initNodeFromRootKernelObj.obj:setArg(1, self.UBuf) end end --[[ maybe something in here is messing me up? -- after all, most display vars are typically all the same size -- the AMR ones are the only ones that are different -- nope...still got a crash... function cl:addDisplayVars() cl.super.addDisplayVars(self) if self.amr.ctx.method == 'dt vs 2dt' then self:addDisplayVarGroup{ name = 'U2', bufferField = 'U2Buf', bufferType = self.eqn.symbols.cons_t, vars = { {name='0', code='value.vreal = buf[index].ptr[0];'}, } } elseif self.amr.ctx.method == 'gradient' then self:addDisplayVarGroup{ name = 'amrError', bufferField = 'amrErrorBuf', bufferType = 'real', vars = { {name='0', code='value.vreal = buf[index];'}, } } end end --]] function cl:update() -- NOTICE this used to go after boundary() and before step() local t if self.amr.ctx.method == 'dt vs 2dt' then t = self.t -- back up the last buffer self.cmds:enqueueCopyBuffer{src=self.UBuf, dst=self.lastUBuf, size=self.numCells * self.eqn.numStates * ffi.sizeof(self.app.real)} end -- update children ... twice as many times, at half the timestep local childDT = self.fixedDT * .5 for _,child in pairs(self.amr.child) do child.fixedDT = childDT child.useFixedDT = true child:update() end -- now copy it to the backup buffer if self.amr.ctx.method == 'dt vs 2dt' then -- TODO have step() provide a target, and just update directly into U2Buf? self.cmds:enqueueCopyBuffer{src=self.UBuf, dst=self.U2Buf, size=self.numCells * self.eqn.numStates * ffi.sizeof(self.app.real)} self.cmds:enqueueCopyBuffer{src=self.lastUBuf, dst=self.UBuf, size=self.numCells * self.eqn.numStates * ffi.sizeof(self.app.real)} self:step(.5 * dt) self.t = t + .5 * dt self:step(.5 * dt) self.t = t + dt -- now compare UBuf and U2Buf, store in U2Buf in the first real of cons_t self.compareUvsU2KernelObj() elseif self.amr.ctx.method == 'gradient' then -- 1) compute errors from gradient, sum up errors in each root node, and output on a per-node basis local amrRootSizeInFromGlobalSize = vec3sz( roundup(self.amr.ctx.parentSizeInFromSize.x, self.localSize.x), roundup(self.amr.ctx.parentSizeInFromSize.y, self.localSize.y), roundup(self.amr.ctx.parentSizeInFromSize.z, self.localSize.z)) --print('self.amr.ctx.parentSizeInFromSize', self.amr.ctx.parentSizeInFromSize) --print('amrRootSizeInFromGlobalSize', amrRootSizeInFromGlobalSize) --print('self.localSize', self.localSize) self.calcAMRErrorKernelObj.obj:setArgs(self.solverBuf, self.amrErrorBuf, self.UBuf) self.cmds:enqueueNDRangeKernel{ kernel = self.calcAMRErrorKernelObj.obj, dim = self.dim, globalSize = amrRootSizeInFromGlobalSize.s, localSize = self.localSize.s, } local volume = tonumber(self.amr.ctx.parentSizeInFromSize:volume()) local ptr = assert(self.amrErrorPtr) self.cmds:enqueueReadBuffer{buffer=self.amrErrorBuf, block=true, size=ffi.sizeof(self.app.real) * volume, ptr=ptr} -- [[ print('depth '..self.amr.depth..' amrErrors:') for ny=0,tonumber(self.amr.ctx.parentSizeInFromSize.y)-1 do for nx=0,tonumber(self.amr.ctx.parentSizeInFromSize.x)-1 do local i = nx + self.amr.ctx.parentSizeInFromSize.x * ny io.write('\t', ('%.5f'):format(ptr[i])) end print() end --]] -- [[ if self.amr.depth < self.amr.ctx.maxdepth then for ny=0,tonumber(self.amr.ctx.parentSizeInFromSize.y)-1 do for nx=0,tonumber(self.amr.ctx.parentSizeInFromSize.x)-1 do local i = tonumber(nx + self.amr.ctx.parentSizeInFromSize.x * ny) local nodeErr = ptr[i] if nodeErr > self.amr.ctx.splitThreshold then if not self.amr.child[i+1] then print("creating depth "..tonumber(self.amr.depth).." child "..tonumber(i)) -- [==[ -- lazy way: just recreate the whole thing -- except remap the mins/maxs local dx = 1/tonumber(self.amr.ctx.parentSizeInFromSize.x) local dy = 1/tonumber(self.amr.ctx.parentSizeInFromSize.y) local ux = nx*dx local uy = ny*dy local newmins = { (self.maxs.x - self.mins.x) * nx * dx + self.mins.x, (self.maxs.y - self.mins.y) * ny * dy + self.mins.y, 0} local newmaxs = { (self.maxs.x - self.mins.x) * (nx+1) * dx + self.mins.x, (self.maxs.y - self.mins.y) * (ny+1) * dy + self.mins.y, 0} -- when running the following, upon the next update, I start to get nans in the amr error buffer local subsolver = subcl{ app = self.app, parent = self, dim = self.dim, gridSize = self.sizeWithoutBorder, coord = self.coord, mins = newmins, maxs = newmaxs, amr = { depth = self.amr.depth + 1, ctx = self.amr.ctx, }, } -- tell the root layer table which node is used -- by pointing it back to the table of the leaf nodes self.amr.child[i+1] = assert(subsolver) -- copy data from the root node location into the new node -- upsample as we go ... by nearest? -- setup kernel args self.initNodeFromRootKernelObj.obj:setArgs(subsolver.UBuf, self.UBuf, int4(nx,ny,0,0)) -- so long as node size = root size, we can use the solver.globalSize, and not --self.amr.ctx.nodeSizeWithoutBorder.s, self.initNodeFromRootKernelObj() --]==] end elseif nodeErr < self.amr.ctx.mergeThreshold then -- local subsolver= self.amr.child[i+1] --print('node '..nx..','..ny..' needs to be merged') -- self.amr.child[i+1] = nil end end end end --]] end end function cl:resetState() cl.super.resetState(self) -- TODO dealloc safely? self.amr.child = table() end -- maybe I shouldn't make a subclass -- maybe a patchlevel class is a better idea subcl = class(cl) function subcl:initObjs(args) self.parent = assert(args.parent) self.maxWorkGroupSize = self.parent.maxWorkGroupSize local sizeProps = self:getSizePropsForWorkGroupSize(self.maxWorkGroupSize) for k,v in pairs(sizeProps) do self[k] = v end self:createEqn() --subcl.super.initObjs(self, args) self.solver_t = self.parent.solver_t self.solverPtr = ffi.new(self.solver_t) initAMR(self, args) end function subcl:createEqn() self.eqn = self.parent.eqn end function subcl:refreshEqnInitState() -- don't need to create init state ... -- refreshCodePrefix is called next -- and that calls refreshIntegrator ... self:refreshCodePrefix() end -- refreshCodePrefix calls: function subcl:createCodePrefix() end function subcl:refreshIntegrator() self.integrator = self.parent.integrator end function subcl:refreshInitStateProgram() end local template = require 'template' function subcl:refreshBoundaryProgram() --[=[ self.boundaryProgramObj, self.boundaryKernelObjs = self:createBoundaryProgramAndKernel( table( self:getBoundaryProgramArgs(), -- should have the buffer and type { methods = { xmin = 'freeflow', xmax = 'freeflow', ymin = 'freeflow', ymax = 'freeflow', zmin = 'freeflow', zmax = 'freeflow', }, } ) ) --]=] --[=[ local function copyBorder(args) return template([[ ]]) end self.boundaryProgramObj, self.boundaryKernelObjs = self:createBoundaryProgramAndKernel( table( self:getBoundaryProgramArgs(), -- should have the buffer and type methods = { xmin = copyBorder, xmax = copyBorder, ymin = copyBorder, ymax = copyBorder, zmin = copyBorder, zmax = copyBorder, } ) ) -- next comes the op's boundary programs -- next comes the CTU's boundary programs --]=] end function subcl:refreshSolverProgram() local ks = table.keys(self.parent):sort() for _,k in ipairs(ks) do if k:match'KernelObj$' or k:match'KernelObjs$' or k:match'ProgramObj$' or k:match'Shader$' then self[k] = self.parent[k] end end -- still needs to call ops refreshSolverProgram (or at least steal their kernels too) for _,op in ipairs(self.ops) do op:refreshSolverProgram() end -- and the display vars ... end -- called by refreshGridSize: function subcl:refreshCommonProgram() end function subcl:resetState() end function subcl:createBuffers() local ks = table.keys(self.parent):sort() for _,k in ipairs(ks) do -- as long as we have matching size, we can reuse all buffers (except the state buffers) -- TODO will need to save primBufs as well if (k:match'Buf$' and k ~= 'UBuf' and k ~= 'solverBuf') or (k:match'BufObj$' and k ~= 'UBufObj') then self[k] = self.parent[k] end end self.tex = self.parent.tex self.texCLMem = self.parent.texCLMem self.calcDisplayVarToTexPtr = self.parent.calcDisplayVarToTexPtr self.amrErrorPtr = self.parent.amrErrorPtr -- now for our own allocations... -- this is copied from GridSolver:createBuffers print('creating subsolver ubuffer...') self:clalloc('UBuf', self.eqn.symbols.cons_t, self.numCells) createBuffersAMR(self) end function subcl:boundary() -- TODO give us a better boundary kernel, then this function can stay intact end return cl end
local yaml = require("yaml") local test = {} -- test decode function test:decode() local text = [[ a: b: 1 ]] local result, err = yaml.decode(text) assert(not err, tostring(err)) assert(result["a"]["b"] == 1, tostring(result["a"]["b"])) print("done: yaml.decode()") end -- test decode with no args throws exception function test:decode_no_args() local ok, errMsg = pcall(yaml.decode) assert(not ok) assert(errMsg) assert(errMsg:find("(string expected, got nil)"), tostring(errMsg)) end -- test encode of decoded(text) == text function test:decoded_text_equals_text() local text = [[ a: b: 1 ]] local result = { a = { b = 1 } } local encodedResult, err = yaml.encode(result) assert(not err, tostring(err)) assert(encodedResult == text, tostring(encodedResult) ) end -- test encode(slice) works function test:encode_slice_works() local encodedSlice = yaml.encode({ "foo", "bar", "baz" }) assert(encodedSlice == [[ - foo - bar - baz ]], tostring(encodedSlice)) end -- test encode(sparse slice) works function test:encode_sparse_slice_returns_map() local slice = { [0] = "foo", [1] = "bar", [2] = "baz" } local encodedSlice = yaml.encode(slice) assert(encodedSlice == [[ 0: foo 1: bar 2: baz ]], tostring(encodedSlice)) end -- test encode(map) works function test:encode_map_returns_map() local map = { foo = "bar", bar = { 1, 2, 3.45 } } local encodedMap = yaml.encode(map) assert(encodedMap == [[ bar: - 1 - 2 - 3.45 foo: bar ]], tostring(encodedMap)) end -- test encode(function) fails function test:encode_function_fails() local _, errMsg = yaml.encode(function() return "" end) assert(errMsg) assert(errMsg:find("cannot encode values with function in them"), errMsg) -- test encode with no args throws exception local ok, errMsg = pcall(yaml.encode) assert(not ok) assert(errMsg:find("(value expected)"), tostring(errMsg)) end -- test cycles function test:cycles_return_error() local t1 = {} local t2 = { t1 = t1 } t1[t2] = t2 local _, errMsg = yaml.encode(t1) assert(errMsg) assert(errMsg:find("nested table"), tostring(errMsg)) end return test
------------ --- Trace -- Trace object. Holds both request and response. -- @module middleware local Model = require 'model' local Service = require 'models.service' local Event = require 'models.event' local fn = require 'functional' local http = require 'http' local uuid4 = require 'uuid' local inspect = require 'inspect' local Config = require 'models.config' --- Trace -- @type Trace local Trace = Model:new() -- Class methods Trace.collection = 'traces' Trace.excluded_fields_to_index = {res = { body = true } } Trace.keep = 1000 local function link(uuid) local slug_name = Config.get_slug_name() return "https://" .. slug_name .. ".my.apitools.com/app/traces/find/" .. uuid end local Trace_mt = { __index = function(table, key) if key == 'link' then return link(table.uuid) else return rawget(table, key) end end } function Trace:new(req) --- Current HTTP Request like it will be stored and displayed in the UI. -- @table Trace.req -- @field[type=string] query query string -- @field[type=table] headers -- @field[type=string] uri_full whole URI including scheme, host, port, path and query string -- @field[type=string] uri_relative path + query string -- @field[type=table] args parsed query string -- @field[type=string] method HTTP Method -- @field[type=string] scheme HTTP Scheme (http/https) -- @field[type=string] uri just the path -- @field[type=string] host value of Host header --- Will contain the response like it will be stored (once it is processed). -- @table Trace.res -- @field[type=string] body -- @field[type=int] status -- @field[type=table] headers --- time in seconds how long it took APItools to return the request -- @field[type=number] total_time --- id of the service that processed the request -- @field[type=number] service_id --- starred -- @field[type=boolean] starred Model:check_dots(self, Trace, 'new') local trace = { req = req, uuid = uuid4.getUUID() } return setmetatable(trace, Trace_mt) end function Trace:delete_expired(to_keep) Model:check_dots(self, Trace, 'delete_expired') local total = Trace:count({}) if total > Trace.keep then self:delete({ starred = false }, { max_documents = total - Trace.keep }) end end -- Instance Methods function Trace:setRes(trace, res) Model:check_dots(self, Trace, 'setRes') trace.starred = false trace.res = { status = res.status, body = res.body, headers = {} } if type(res.headers) == 'table' then for k,v in pairs(res.headers) do trace.res.headers[k] = v end end -- record how long it took brainslug and remote server trace.total_time = ngx.now() - ngx.req.start_time() if trace.total_time and trace.time then trace.overhead_time = trace.total_time - trace.time end end function Trace:setError(trace, err) err = tostring(err) Model:check_dots(self, Trace, 'setError') trace.starred = false trace.res = trace.res or {} trace.res.headers = trace.res.headers or {} trace.res.status = trace.res.status or 500 trace.res.body = trace.res.body or err trace['error'] = err Event:create({ channel = "middleware", level = "error", msg = "An error happened while processing a request", trace = trace, err = err }) end function Trace:star(trace) Model:check_dots(self, Trace, 'persist') trace.starred = true Trace:save(trace) return trace end function Trace:unstar(trace) Model:check_dots(self, Trace, 'persist') trace.starred = false Trace:save(trace) return trace end local index_attrs = { _id = true, _created_at = true, time = true, overhead_time = true, total_time = true, service_id = true, starred = true } local index_req_attrs = {method = true, uri = true, headers = true} local index_res_attrs = {status = true, headers = true} function Trace:for_index(conditions, options) Model:check_dots(self, Trace, 'for_index') -- Michal: this looks weird, just use dot everywhere, they are class level methods anyway local traces = self:all(conditions, options) return fn.map(function(trace) local clean_trace = {req = {}, res={}} for attr,_ in pairs(index_attrs) do clean_trace[attr] = trace[attr] end for attr,_ in pairs(index_req_attrs) do clean_trace.req[attr] = trace.req[attr] end for attr,_ in pairs(index_res_attrs) do if trace.res then --if there's no trace.res for some reason clean_trace.res[attr] = trace.res[attr] end end return clean_trace end, traces) end function Trace:redo(trace) local query = { method = trace.req.method, url = "http://127.0.0.1:10002" .. trace.req.uri_relative, headers = trace.req.headers } query.headers.Host = trace.req.host local service = Service:find_or_error(trace.service_id, 'service ' .. trace.service_id .. ' not found') return http.simple(query, trace.req.body) end return Trace
-- Local instances of Global tables -- local PA = PersonalAssistant local PAC = PA.Constants -- --------------------------------------------------------------------------------------------------------------------- local PAMenuChoices = { PABanking = { stackingType = { GetString(SI_PA_ST_MOVE_FULL), GetString(SI_PA_ST_MOVE_INCOMPLETE_STACKS_ONLY) }, itemMoveMode = { GetString(SI_PA_BANKING_MOVE_MODE_DONOTHING), GetString(SI_PA_BANKING_MOVE_MODE_TOBANK), GetString(SI_PA_BANKING_MOVE_MODE_TOBACKPACK) }, mathOperator = { GetString(SI_PA_REL_NONE), GetString(SI_PA_REL_BACKPACK_EQUAL), -- GetString(SI_PA_REL_BACKPACK_LESSTHAN), GetString(SI_PA_REL_BACKPACK_LESSTHANEQUAL), -- GetString(SI_PA_REL_BACKPACK_GREATERTHAN), GetString(SI_PA_REL_BACKPACK_GREATERTHANEQUAL), GetString(SI_PA_REL_BANK_EQUAL), -- GetString(SI_PA_REL_BANK_LESSTHAN), GetString(SI_PA_REL_BANK_LESSTHANOREQUAL), -- GetString(SI_PA_REL_BANK_GREATERTHAN), GetString(SI_PA_REL_BANK_GREATERTHANOREQUAL), }, }, PAJunk = { qualityLevelNoDisabled = { GetString(SI_PA_QUALITY_TRASH), GetString(SI_PA_QUALITY_NORMAL), GetString(SI_PA_QUALITY_FINE), GetString(SI_PA_QUALITY_SUPERIOR), GetString(SI_PA_QUALITY_EPIC), -- GetString(SI_PA_QUALITY_LEGENDARY), }, qualityLevel = { GetString(SI_PA_QUALITY_DISABLED), GetString(SI_PA_QUALITY_TRASH), GetString(SI_PA_QUALITY_NORMAL), GetString(SI_PA_QUALITY_FINE), GetString(SI_PA_QUALITY_SUPERIOR), GetString(SI_PA_QUALITY_EPIC), -- GetString(SI_PA_QUALITY_LEGENDARY), }, qualityLevelReverse = { GetString(SI_PA_QUALITY_DISABLED), GetString(SI_PA_QUALITY_LEGENDARY), GetString(SI_PA_QUALITY_EPIC), GetString(SI_PA_QUALITY_SUPERIOR), GetString(SI_PA_QUALITY_FINE), GetString(SI_PA_QUALITY_NORMAL), GetString(SI_PA_QUALITY_TRASH), }, }, PARepair = { defaultSoulGem = { GetString("SI_DEFAULTSOULGEMCHOICE", DEFAULT_SOUL_GEM_CHOICE_GOLD), GetString("SI_DEFAULTSOULGEMCHOICE", DEFAULT_SOUL_GEM_CHOICE_CROWN), } }, } local PAMenuChoicesValues = { PABanking = { stackingType = { PAC.STACKING.FULL, PAC.STACKING.INCOMPLETE }, itemMoveMode = { PAC.MOVE.IGNORE, PAC.MOVE.DEPOSIT, PAC.MOVE.WITHDRAW, }, mathOperator = { PAC.OPERATOR.NONE, PAC.OPERATOR.BACKPACK_EQUAL, -- PAC.OPERATOR.BACKPACK_LESSTHAN, PAC.OPERATOR.BACKPACK_LESSTHANOREQUAL, -- PAC.OPERATOR.BACKPACK_GREATERTHAN, PAC.OPERATOR.BACKPACK_GREATERTHANOREQUAL, PAC.OPERATOR.BANK_EQUAL, -- PAC.OPERATOR.BANK_LESSTHAN, PAC.OPERATOR.BANK_LESSTHANOREQUAL, -- PAC.OPERATOR.BANK_GREATERTHAN, PAC.OPERATOR.BANK_GREATERTHANOREQUAL, }, }, PAJunk = { qualityLevelNoDisabled = { ITEM_FUNCTIONAL_QUALITY_TRASH, -- 0 ITEM_FUNCTIONAL_QUALITY_NORMAL, -- 1 ITEM_FUNCTIONAL_QUALITY_MAGIC, -- 2 ITEM_FUNCTIONAL_QUALITY_ARCANE, -- 3 ITEM_FUNCTIONAL_QUALITY_ARTIFACT, -- 4 -- ITEM_FUNCTIONAL_QUALITY_LEGENDARY, -- 5 }, qualityLevel = { PAC.ITEM_QUALITY.DISABLED, -- -1 (disabled) ITEM_FUNCTIONAL_QUALITY_TRASH, -- 0 ITEM_FUNCTIONAL_QUALITY_NORMAL, -- 1 ITEM_FUNCTIONAL_QUALITY_MAGIC, -- 2 ITEM_FUNCTIONAL_QUALITY_ARCANE, -- 3 ITEM_FUNCTIONAL_QUALITY_ARTIFACT, -- 4 -- ITEM_FUNCTIONAL_QUALITY_LEGENDARY, -- 5 }, qualityLevelReverse = { PAC.ITEM_QUALITY.DISABLED_REVERSE, -- 99 (disabled) ITEM_FUNCTIONAL_QUALITY_LEGENDARY, -- 5 ITEM_FUNCTIONAL_QUALITY_ARTIFACT, -- 4 ITEM_FUNCTIONAL_QUALITY_ARCANE, -- 3 ITEM_FUNCTIONAL_QUALITY_MAGIC, -- 2 ITEM_FUNCTIONAL_QUALITY_NORMAL, -- 1 ITEM_FUNCTIONAL_QUALITY_TRASH, -- 0 }, }, PARepair = { defaultSoulGem = { DEFAULT_SOUL_GEM_CHOICE_GOLD, DEFAULT_SOUL_GEM_CHOICE_CROWN, } }, } local PAMenuChoicesTooltips = { PABanking = { mathOperator = { GetString(SI_PA_REL_NONE), GetString(SI_PA_REL_BACKPACK_EQUAL_T), -- GetString(SI_PA_REL_BACKPACK_LESSTHAN_T), GetString(SI_PA_REL_BACKPACK_LESSTHANOREQUAL_T), -- GetString(SI_PA_REL_BACKPACK_GREATERTHAN_T), GetString(SI_PA_REL_BACKPACK_GREATERTHANOREQUAL_T), GetString(SI_PA_REL_BANK_EQUAL_T), -- GetString(SI_PA_REL_BANK_LESSTHAN_T), GetString(SI_PA_REL_BANK_LESSTHANOREQUAL_T), -- GetString(SI_PA_REL_BANK_GREATERTHAN_T), GetString(SI_PA_REL_BANK_GREATERTHANOREQUAL_T), } } } -- Export PA.MenuChoices = { choices = PAMenuChoices, choicesValues = PAMenuChoicesValues, choicesTooltips = PAMenuChoicesTooltips }
object_tangible_tcg_series3_greeter_deed_tusken = object_tangible_tcg_series3_shared_greeter_deed_tusken:new { } ObjectTemplates:addTemplate(object_tangible_tcg_series3_greeter_deed_tusken, "object/tangible/tcg/series3/greeter_deed_tusken.iff")
local request_key = require 'http.request_key' local http = require 'http' local Cache = {__index={ get = function(self, key) return self.items[key] end, set = function(self, key, value, time) self.items[key] = value end }} local app = http.app.new { cache = setmetatable({items = {}}, Cache), } app:use(http.middleware.caching) app:use(http.middleware.routing) local cache_profile = { key = request_key.new '$m:$p', time = 600 } local c1 = 0 local c2 = 0 app:get('', function(w) c1 = c1 + 1 w.cache_profile = cache_profile return w:write('Counter = ' .. c1 .. '\n') end) app:post('not-found', function(w) c2 = c2 + 1 w:set_status_code(404) w.cache_profile = cache_profile return w:write('Counter = ' .. c2 .. '\n') end) return app()
------------------------------------------------------------------------------ -- Additional CQUI Common LUA support functions specific to Civilization 6 ------------------------------------------------------------------------------ -- =========================================================================== -- Expansions check -- =========================================================================== -- these are global variables, will be visible in the entire context -- please note that Modding object is only available in the UI context -- in the Gameplay context a different method must be used as those variables will be nil g_bIsRiseAndFall = Modding and Modding.IsModActive("1B28771A-C749-434B-9053-D1380C553DE9"); -- Rise & Fall g_bIsGatheringStorm = Modding and Modding.IsModActive("4873eb62-8ccc-4574-b784-dda455e74e68"); -- Gathering Storm -- =========================================================================== -- VARIABLES -- =========================================================================== CQUI_ShowDebugPrint = false; -- =========================================================================== --CQUI setting control support functions -- =========================================================================== function print_debug(...) if CQUI_ShowDebugPrint then print(...); end end -- =========================================================================== function CQUI_OnSettingsUpdate() print_debug("ENTRY: CQUICommon - CQUI_OnSettingsUpdate"); if (GameInfo.CQUI_Settings ~= nil and GameInfo.CQUI_Settings["CQUI_ShowDebugPrint"] ~= nil) then CQUI_ShowDebugPrint = ( GameInfo.CQUI_Settings["CQUI_ShowDebugPrint"].Value == 1 ); else CQUI_ShowDebugPrint = GameConfiguration.GetValue("CQUI_ShowDebugPrint"); end end -- =========================================================================== -- Used to register a control to be updated whenever settings update (only necessary for controls that can be updated from multiple places) function RegisterControl(control, setting_name, update_function, extra_data) print_debug("ENTRY: CQUICommon - RegisterControl"); LuaEvents.CQUI_SettingsUpdate.Add(function() update_function(control, setting_name, extra_data); end); end -- =========================================================================== -- Companion functions to RegisterControl -- =========================================================================== function UpdateCheckbox(control, setting_name) print_debug("ENTRY: CQUICommon - UpdateCheckbox"); local value = GameConfiguration.GetValue(setting_name); if(value == nil) then return; end control:SetSelected(value); end -- =========================================================================== function UpdateSlider( control, setting_name, data_converter) print_debug("ENTRY: CQUICommon - UpdateSlider"); local value = GameConfiguration.GetValue(setting_name); if(value == nil) then return; end control:SetStep(data_converter.ToSteps(value)); end -- =========================================================================== --Used to populate combobox options function PopulateComboBox(control, values, setting_name, tooltip) print_debug("ENTRY: CQUICommon - PopulateComboBox"); control:ClearEntries(); local current_value = GameConfiguration.GetValue(setting_name); if(current_value == nil) then --LY Checks if this setting has a default state defined in the database if(GameInfo.CQUI_Settings[setting_name]) then --reads the default value from the database. Set them in Settings.sql current_value = GameInfo.CQUI_Settings[setting_name].Value; else current_value = 0; end GameConfiguration.SetValue(setting_name, current_value); --/LY end for i, v in ipairs(values) do local instance = {}; control:BuildEntry( "InstanceOne", instance ); instance.Button:SetVoid1(i); instance.Button:LocalizeAndSetText(v[1]); if(v[2] == current_value) then local button = control:GetButton(); button:LocalizeAndSetText(v[1]); end end control:CalculateInternals(); if(setting_name) then control:RegisterSelectionCallback( function(voidValue1, voidValue2, control) local option = values[voidValue1]; local button = control:GetButton(); button:LocalizeAndSetText(option[1]); GameConfiguration.SetValue(setting_name, option[2]); LuaEvents.CQUI_SettingsUpdate(); end ); end if(tooltip ~= nil)then control:SetToolTipString(tooltip); end end --Used to populate checkboxes function PopulateCheckBox(control, setting_name, tooltip) print_debug("ENTRY: CQUICommon - PopulateCheckBox"); local current_value = GameConfiguration.GetValue(setting_name); if(current_value == nil) then --LY Checks if this setting has a default state defined in the database if(GameInfo.CQUI_Settings[setting_name]) then --because 0 is true in Lua if(GameInfo.CQUI_Settings[setting_name].Value == 0) then current_value = false; else current_value = true; end else current_value = false; end GameConfiguration.SetValue(setting_name, current_value); end if(current_value == false) then control:SetSelected(false); else control:SetSelected(true); end control:RegisterCallback(Mouse.eLClick, function() local selected = not control:IsSelected(); control:SetSelected(selected); GameConfiguration.SetValue(setting_name, selected); LuaEvents.CQUI_SettingsUpdate(); end ); if(tooltip ~= nil)then control:SetToolTipString(tooltip); end end -- =========================================================================== --Used to populate sliders. data_converter is a table containing two functions: ToStep and ToValue, which describe how to hanlde converting from the incremental slider steps to a setting value, think of it as a less elegant inner class --Optional third function: ToString. When included, this function will handle how the value is converted to a display value, otherwise this defaults to using the value from ToValue function PopulateSlider(control, label, setting_name, data_converter, tooltip) print_debug("ENTRY: CQUICommon - PopulateSlider"); --This is necessary because RegisterSliderCallback fires twice when releasing the mouse cursor for some reason local hasScrolled = false; local current_value = GameConfiguration.GetValue(setting_name); if(current_value == nil) then --LY Checks if this setting has a default state defined in the database if(GameInfo.CQUI_Settings[setting_name]) then current_value = GameInfo.CQUI_Settings[setting_name].Value; else current_value = 0; end GameConfiguration.SetValue(setting_name, current_value); --/LY end control:SetStep(data_converter.ToSteps(current_value)); if(data_converter.ToString) then label:SetText(data_converter.ToString(current_value)); else label:SetText(current_value); end control:RegisterSliderCallback( function() local value = data_converter.ToValue(control:GetStep()); if(data_converter.ToString) then label:SetText(data_converter.ToString(value)); else label:SetText(value); end if(not control:IsTrackingLeftMouseButton() and hasScrolled == true) then GameConfiguration.SetValue(setting_name, value); LuaEvents.CQUI_SettingsUpdate(); hasScrolled = false; else hasScrolled = true; end end ); if(tooltip ~= nil)then control:SetToolTipString(tooltip); end end -- =========================================================================== -- Trims source information from gossip messages. Returns nil if the message couldn't be trimmed (this usually means the provided string wasn't a gossip message at all) function CQUI_TrimGossipMessage(str:string) print_debug("ENTRY: CQUICommon - CQUI_TrimGossipMessage"); -- Get a sample of a gossip source string local sourceSample = Locale.Lookup("LOC_GOSSIP_SOURCE_DELEGATE", "XX", "Y", "Z"); -- Get last word that occurs in the gossip source string. "that" in English. -- Assumes the last word is always the same, which it is in English, unsure if this holds true in other languages -- AZURENCY : the patterns means : any character 0 or +, XX exactly, any character 0 or +, space, any character other than space 1 or + at the end of the sentence. -- AZURENCY : in some languages, there is no space, in that case, take the last character (often it's a ":") last = string.match(sourceSample, ".-XX.-(%s%S+)$"); if last == nil then last = string.match(sourceSample, ".-(.)$"); end -- AZURENCY : if last is still nill, it's not normal, print an error but still allow the code to run if last == nil then print_debug("ERROR : LOC_GOSSIP_SOURCE_DELEGATE seems to be empty as last was still nil after the second pattern matching.") last = "" end -- Return the rest of the string after the last word from the gossip source string return Split(str, last .. " " , 2)[2]; end -- =========================================================================== function Initialize() print_debug("INITIALZE: CQUICommon.lua"); LuaEvents.CQUI_SettingsUpdate.Add(CQUI_OnSettingsUpdate); LuaEvents.CQUI_SettingsInitialized.Add(CQUI_OnSettingsUpdate); end Initialize();