content
stringlengths
5
1.05M
-- argument parsing local cmdPrefix = config.command_prefixes if not config.command_prefixes or not config.command_prefixes[1] then local default = "d$" print('Command prefix not found, using default "' .. default .. '"') cmdPrefix = { default } end bot.commandPrefixes = cmdPrefix local cmdArgGrouper = "[\"']" local cmdArgSeparators = "[%s,]" local cmdEscapeChar = "[\\]" function parseArgs(str) -- from mingeban2 local chars = str:split("") local grouping = false local escaping = false local grouper = false local separator = false local arg = "" local ret = {} for k, c in next, chars do local cont = true local before = chars[k - 1] -- check if there's anything behind the current char local after = chars[k + 1] -- check if there's anything after the current char if c:match(cmdEscapeChar) then escaping = true cont = false -- we're escaping a char, no need to continue end if cont then if ((arg ~= "" and grouping) or (arg == "" and not grouping)) and c:match(grouper or cmdArgGrouper) then -- do we try to group if not before or before and not escaping then -- are we escaping or starting a command if not grouper then grouper = c -- pick the current grouper end grouping = not grouping -- toggle group mode if arg ~= "" then ret[#ret + 1] = arg -- finish the job, add arg to list arg = "" -- reset arg end cont = false -- we toggled grouping mode elseif escaping then escaping = false -- we escaped the character, disable it end end if cont then if c:match(separator or cmdArgSeparators) and not grouping then -- are we separating and not grouping if not separator then separator = c -- pick the current separator end if before and not before:match(grouper or cmdArgGrouper) then -- arg ~= "" then ret[#ret + 1] = arg -- finish the job, add arg to list arg = "" -- reset arg end cont = false -- let's get the next arg going end if cont then arg = arg .. c -- go on with the arg if not after then -- in case this is the end of the sentence, add last thing written ret[#ret + 1] = arg end end end end end return ret -- give results!! end function bot.errorMsg(channel, msg, title, footer, icon_url) local _msg = { embed = { title = title, description = isstring(msg) and msg or nil, fields = istable(msg) and { msg } or nil, color = 0xFF4040 } } if _msg.embed.title then _msg.embed.title = ":interrobang: " .. _msg.embed.title else _msg.embed.description = ":interrobang: " .. _msg.embed.description end if footer then _msg.embed.footer = { icon_url = icon_url, text = footer } end channel:send(_msg) end bot.commands = {} function bot.getCommands(cat) local tbl = {} if not cat then for cmd, cmdData in next, bot.commands do local cat = cmdData.category or "No Category" if not tbl[cat] then tbl[cat] = {} end if istable(cmd) then for _, name in next, cmd do cmdData.aliases = cmd tbl[cat][name] = cmdData end else tbl[cat][cmd] = cmdData end end elseif cat == true then for cmd, cmdData in next, bot.commands do if istable(cmd) then for _, name in next, cmd do cmdData.aliases = cmd tbl[name] = cmdData end else tbl[cmd] = cmdData end end else for cmd, cmdData in next, bot.commands do if cmdData.category and cmdData.category:lower() == cat:lower() then cat = cmdData.category -- preserve original case if istable(cmd) then for _, name in next, cmd do cmdData.aliases = cmd tbl[name] = cmdData end else tbl[cmd] = cmdData end end end end return tbl, cat end function bot.getCommand(cmd) return bot.getCommands(true)[cmd:lower()] end -- load commands for file, _type in fs.scandirSync("./commands") do if _type ~= "directory" then require("./commands/" .. file) end end bot.getCommands() -- hahaa refresh .aliases. -- command handling local function call(cmdData, cmdName, msg, line, ...) _G.cmdError = function(err, footer, icon_url) -- this is gay local cmdName = cmdName coroutine.wrap(function() bot.errorMsg(msg.channel, err, cmdName .. " Error:", footer, icon_url) end)() end local _, ok, err, footer, icon_url = xpcall(cmdData.callback, function(err) local traceback = debug.traceback("Error while running " .. cmdName .. " command:", 2) print(err) print(traceback) coroutine.wrap(function() bot.errorMsg(msg.channel, { name = err:gsub(process.cwd() .. "/", ""), value = bot.errorToGithub(traceback) }, cmdName .. " Internal Error:") end)() end, msg, line, ...) if ok == false then bot.errorMsg(msg.channel, err, cmdName .. " Error:", footer, icon_url) end end client:on("messageCreate", function(msg) local text = msg.content local usedPrefix for _, prefix in next, cmdPrefix do if text:match("^" .. prefix:gsub("%$", "%%$")) then usedPrefix = prefix break end end if usedPrefix then local args = text:split(" ") local cmd = args[1]:sub(usedPrefix:len() + 1) local line = text:sub(args[1]:len() + 2):trim() args = parseArgs(line) for cmdName, cmdData in next, bot.commands do if istable(cmdName) then for _, cmdName in next, cmdName do if cmdName:lower() == cmd:lower() then msg.channel:broadcastTyping() if cmdData.ownerOnly and not config.owners[msg.author.id] then bot.errorMsg(msg.channel, "No access!", cmdName .. " Error:") return end bot.currentPrefix = usedPrefix call(cmdData, cmdName, msg, line, unpack(args)) break end end elseif cmdName:lower() == cmd:lower() then msg.channel:broadcastTyping() if cmdData.ownerOnly and not config.owners[msg.author.id] then bot.errorMsg(msg.channel, "No access!", cmdName .. " Error:") return end bot.currentPrefix = usedPrefix call(cmdData, cmdName, msg, line, unpack(args)) end end end end)
local cwtest = require "cwtest" local ltn12 = require "ltn12" local H = (require "socket.http").request local mp = (require "multipart-post").gen_request local enc = (require "multipart-post").encode local J do -- Find a JSON parser local ok, json = pcall(require, "cjson") if not ok then ok, json = pcall(require, "json") end J = json.decode assert(ok and J, "no JSON parser found :(") end local file = io.open("testfile.tmp", "w+") file:write("file data") file:flush() file:seek("set", 0) local fsz = file:seek("end") file:seek("set", 0) local T = cwtest.new() T:start("gen_request"); do local r = {} local rq = mp{ myfile = {name = "myfilename", data = "some data"}, diskfile = {name = "diskfilename", data = file, len = fsz}, ltn12file = { name = "ltn12filename", data = ltn12.source.string("ltn12 data"), len = string.len("ltn12 data") }, foo = "bar", } rq.url = "http://httpbin.org/post" rq.sink = ltn12.sink.table(r) local _, c = H(rq) T:eq(c, 200) r = J(table.concat(r)) T:eq(r.files, { myfile="some data", diskfile="file data", ltn12file="ltn12 data" }) T:eq(r.form, {foo = "bar"}) end; T:done() T:start("encode"); do local body, boundary = enc{foo="bar"} local r = {} local _, c = H{ url = "http://httpbin.org/post", source = ltn12.source.string(body), method = "POST", sink = ltn12.sink.table(r), headers = { ["content-length"] = string.len(body), ["content-type"] = string.format( "multipart/form-data; boundary=\"%s\"", boundary ), }, } T:eq(c, 200) r = J(table.concat(r)) T:eq(r.form, {foo = "bar"}) end; T:done() os.remove("testfile.tmp")
--- Date and Date Format classes. -- See @{05-dates.md|the Guide}. -- -- NOTE: the date module is deprecated! see -- https://github.com/lunarmodules/Penlight/issues/285 -- -- Dependencies: `pl.class`, `pl.stringx`, `pl.utils` -- @classmod pl.Date -- @pragma nostrip local class = require "pl.class" local os_time, os_date = os.time, os.date local stringx = require "pl.stringx" local utils = require "pl.utils" local assert_arg, assert_string = utils.assert_arg, utils.assert_string utils.raise_deprecation { source = "Penlight " .. utils._VERSION, message = "the 'Date' module is deprecated, see https://github.com/lunarmodules/Penlight/issues/285", version_removed = "2.0.0", version_deprecated = "1.9.2", } local Date = class() Date.Format = class() --- Date constructor. -- @param t this can be either -- -- * `nil` or empty - use current date and time -- * number - seconds since epoch (as returned by `os.time`). Resulting time is UTC -- * `Date` - make a copy of this date -- * table - table containing year, month, etc as for `os.time`. You may leave out year, month or day, -- in which case current values will be used. -- * year (will be followed by month, day etc) -- -- @param ... true if Universal Coordinated Time, or two to five numbers: month,day,hour,min,sec -- @function Date function Date:_init(t, ...) local time local nargs = select("#", ...) if nargs > 2 then local extra = { ... } local year = t t = { year = year, month = extra[1], day = extra[2], hour = extra[3], min = extra[4], sec = extra[5], } end if nargs == 1 then self.utc = select(1, ...) == true end if t == nil or t == "utc" then time = os_time() self.utc = t == "utc" elseif type(t) == "number" then time = t if self.utc == nil then self.utc = true end elseif type(t) == "table" then if getmetatable(t) == Date then -- copy ctor time = t.time self.utc = t.utc else if not (t.year and t.month) then local lt = os_date "*t" if not t.year and not t.month and not t.day then t.year = lt.year t.month = lt.month t.day = lt.day else t.year = t.year or lt.year t.month = t.month or (t.day and lt.month or 1) t.day = t.day or 1 end end t.day = t.day or 1 time = os_time(t) end else error("bad type for Date constructor: " .. type(t), 2) end self:set(time) end --- set the current time of this Date object. -- @int t seconds since epoch function Date:set(t) self.time = t if self.utc then self.tab = os_date("!*t", t) else self.tab = os_date("*t", t) end end --- get the time zone offset from UTC. -- @int ts seconds ahead of UTC function Date.tzone(ts) if ts == nil then ts = os_time() elseif type(ts) == "table" then if getmetatable(ts) == Date then ts = ts.time else ts = Date(ts).time end end local utc = os_date("!*t", ts) local lcl = os_date("*t", ts) lcl.isdst = false return os.difftime(os_time(lcl), os_time(utc)) end --- convert this date to UTC. function Date:toUTC() local ndate = Date(self) if not self.utc then ndate.utc = true ndate:set(ndate.time) end return ndate end --- convert this UTC date to local. function Date:toLocal() local ndate = Date(self) if self.utc then ndate.utc = false ndate:set(ndate.time) --~ ndate:add { sec = Date.tzone(self) } end return ndate end --- set the year. -- @int y Four-digit year -- @class function -- @name Date:year --- set the month. -- @int m month -- @class function -- @name Date:month --- set the day. -- @int d day -- @class function -- @name Date:day --- set the hour. -- @int h hour -- @class function -- @name Date:hour --- set the minutes. -- @int min minutes -- @class function -- @name Date:min --- set the seconds. -- @int sec seconds -- @class function -- @name Date:sec --- set the day of year. -- @class function -- @int yday day of year -- @name Date:yday --- get the year. -- @int y Four-digit year -- @class function -- @name Date:year --- get the month. -- @class function -- @name Date:month --- get the day. -- @class function -- @name Date:day --- get the hour. -- @class function -- @name Date:hour --- get the minutes. -- @class function -- @name Date:min --- get the seconds. -- @class function -- @name Date:sec --- get the day of year. -- @class function -- @name Date:yday for _, c in ipairs { "year", "month", "day", "hour", "min", "sec", "yday" } do Date[c] = function(self, val) if val then assert_arg(1, val, "number") self.tab[c] = val self:set(os_time(self.tab)) return self else return self.tab[c] end end end --- name of day of week. -- @bool full abbreviated if true, full otherwise. -- @ret string name function Date:weekday_name(full) return os_date(full and "%A" or "%a", self.time) end --- name of month. -- @int full abbreviated if true, full otherwise. -- @ret string name function Date:month_name(full) return os_date(full and "%B" or "%b", self.time) end --- is this day on a weekend?. function Date:is_weekend() return self.tab.wday == 1 or self.tab.wday == 7 end --- add to a date object. -- @param t a table containing one of the following keys and a value: -- one of `year`,`month`,`day`,`hour`,`min`,`sec` -- @return this date function Date:add(t) local old_dst = self.tab.isdst local key, val = next(t) self.tab[key] = self.tab[key] + val self:set(os_time(self.tab)) if old_dst ~= self.tab.isdst then self.tab.hour = self.tab.hour - (old_dst and 1 or -1) self:set(os_time(self.tab)) end return self end --- last day of the month. -- @return int day function Date:last_day() local d = 28 local m = self.tab.month while self.tab.month == m do d = d + 1 self:add { day = 1 } end self:add { day = -1 } return self end --- difference between two Date objects. -- @tparam Date other Date object -- @treturn Date.Interval object function Date:diff(other) local dt = self.time - other.time if dt < 0 then error("date difference is negative!", 2) end return Date.Interval(dt) end --- long numerical ISO data format version of this date. function Date:__tostring() local fmt = "%Y-%m-%dT%H:%M:%S" if self.utc then fmt = "!" .. fmt end local t = os_date(fmt, self.time) if self.utc then return t .. "Z" else local offs = self:tzone() if offs == 0 then return t .. "Z" end local sign = offs > 0 and "+" or "-" local h = math.ceil(offs / 3600) local m = (offs % 3600) / 60 if m == 0 then return t .. ("%s%02d"):format(sign, h) else return t .. ("%s%02d:%02d"):format(sign, h, m) end end end --- equality between Date objects. function Date:__eq(other) return self.time == other.time end --- ordering between Date objects. function Date:__lt(other) return self.time < other.time end --- difference between Date objects. -- @function Date:__sub Date.__sub = Date.diff --- add a date and an interval. -- @param other either a `Date.Interval` object or a table such as -- passed to `Date:add` function Date:__add(other) local nd = Date(self) if Date.Interval:class_of(other) then other = { sec = other.time } end nd:add(other) return nd end Date.Interval = class(Date) ---- Date.Interval constructor -- @int t an interval in seconds -- @function Date.Interval function Date.Interval:_init(t) self:set(t) end function Date.Interval:set(t) self.time = t self.tab = os_date("!*t", self.time) end local function ess(n) if n > 1 then return "s " else return " " end end --- If it's an interval then the format is '2 hours 29 sec' etc. function Date.Interval:__tostring() local t, res = self.tab, "" local y, m, d = t.year - 1970, t.month - 1, t.day - 1 if y > 0 then res = res .. y .. " year" .. ess(y) end if m > 0 then res = res .. m .. " month" .. ess(m) end if d > 0 then res = res .. d .. " day" .. ess(d) end if y == 0 and m == 0 then local h = t.hour if h > 0 then res = res .. h .. " hour" .. ess(h) end if t.min > 0 then res = res .. t.min .. " min " end if t.sec > 0 then res = res .. t.sec .. " sec " end end if res == "" then res = "zero" end return res end ------------ Date.Format class: parsing and renderinig dates ------------ -- short field names, explicit os.date names, and a mask for allowed field repeats local formats = { d = { "day", { true, true } }, y = { "year", { false, true, false, true } }, m = { "month", { true, true } }, H = { "hour", { true, true } }, M = { "min", { true, true } }, S = { "sec", { true, true } }, } --- Date.Format constructor. -- @string fmt. A string where the following fields are significant: -- -- * d day (either d or dd) -- * y year (either yy or yyy) -- * m month (either m or mm) -- * H hour (either H or HH) -- * M minute (either M or MM) -- * S second (either S or SS) -- -- Alternatively, if fmt is nil then this returns a flexible date parser -- that tries various date/time schemes in turn: -- -- * [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601), like `2010-05-10 12:35:23Z` or `2008-10-03T14:30+02` -- * times like 15:30 or 8.05pm (assumed to be today's date) -- * dates like 28/10/02 (European order!) or 5 Feb 2012 -- * month name like march or Mar (case-insensitive, first 3 letters); here the -- day will be 1 and the year this current year -- -- A date in format 3 can be optionally followed by a time in format 2. -- Please see test-date.lua in the tests folder for more examples. -- @usage df = Date.Format("yyyy-mm-dd HH:MM:SS") -- @class function -- @name Date.Format function Date.Format:_init(fmt) if not fmt then self.fmt = "%Y-%m-%d %H:%M:%S" self.outf = self.fmt self.plain = true return end local append = table.insert local D, PLUS, OPENP, CLOSEP = "\001", "\002", "\003", "\004" local vars, used = {}, {} local patt, outf = {}, {} local i = 1 while i < #fmt do local ch = fmt:sub(i, i) local df = formats[ch] if df then if used[ch] then error("field appeared twice: " .. ch, 4) end used[ch] = true -- this field may be repeated local _, inext = fmt:find(ch .. "+", i + 1) local cnt = not _ and 1 or inext - i + 1 if not df[2][cnt] then error("wrong number of fields: " .. ch, 4) end -- single chars mean 'accept more than one digit' local p = cnt == 1 and (D .. PLUS) or (D):rep(cnt) append(patt, OPENP .. p .. CLOSEP) append(vars, ch) if ch == "y" then append(outf, cnt == 2 and "%y" or "%Y") else append(outf, "%" .. ch) end i = i + cnt else append(patt, ch) append(outf, ch) i = i + 1 end end -- escape any magic characters fmt = utils.escape(table.concat(patt)) -- fmt = table.concat(patt):gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1') -- replace markers with their magic equivalents fmt = fmt:gsub(D, "%%d"):gsub(PLUS, "+"):gsub(OPENP, "("):gsub(CLOSEP, ")") self.fmt = fmt self.outf = table.concat(outf) self.vars = vars end local parse_date --- parse a string into a Date object. -- @string str a date string -- @return date object function Date.Format:parse(str) assert_string(1, str) if self.plain then return parse_date(str, self.us) end local res = { str:match(self.fmt) } if #res == 0 then return nil, "cannot parse " .. str end local tab = {} for i, v in ipairs(self.vars) do local name = formats[v][1] -- e.g. 'y' becomes 'year' tab[name] = tonumber(res[i]) end -- os.date() requires these fields; if not present, we assume -- that the time set is for the current day. if not (tab.year and tab.month and tab.day) then local today = Date() tab.year = tab.year or today:year() tab.month = tab.month or today:month() tab.day = tab.day or today:day() end local Y = tab.year if Y < 100 then -- classic Y2K pivot tab.year = Y + (Y < 35 and 2000 or 1999) elseif not Y then tab.year = 1970 end return Date(tab) end --- convert a Date object into a string. -- @param d a date object, or a time value as returned by @{os.time} -- @return string function Date.Format:tostring(d) local tm local fmt = self.outf if type(d) == "number" then tm = d else tm = d.time if d.utc then fmt = "!" .. fmt end end return os_date(fmt, tm) end --- force US order in dates like 9/11/2001 function Date.Format:US_order(yesno) self.us = yesno end --local months = {jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12} local months local parse_date_unsafe local function create_months() local ld, day1 = parse_date_unsafe "2000-12-31", { day = 1 } months = {} for i = 1, 12 do ld = ld:last_day() ld:add(day1) local mon = ld:month_name():lower() months[mon] = i end end --[[ Allowed patterns: - [day] [monthname] [year] [time] - [day]/[month][/year] [time] ]] local function looks_like_a_month(w) return w:match "^%a+,*$" ~= nil end local is_number = stringx.isdigit local function tonum(s, l1, l2, kind) kind = kind or "" local n = tonumber(s) if not n then error(("%snot a number: '%s'"):format(kind, s)) end if n < l1 or n > l2 then error(("%s out of range: %s is not between %d and %d"):format(kind, s, l1, l2)) end return n end local function parse_iso_end(p, ns, sec) -- may be fractional part of seconds local _, nfrac, secfrac = p:find("^%.%d+", ns + 1) if secfrac then sec = sec .. secfrac p = p:sub(nfrac + 1) else p = p:sub(ns + 1) end -- ISO 8601 dates may end in Z (for UTC) or [+-][isotime] -- (we're working with the date as lower case, hence 'z') if p:match "z$" then -- we're UTC! return sec, { h = 0, m = 0 } end p = p:gsub(":", "") -- turn 00:30 to 0030 local _, _, sign, offs = p:find "^([%+%-])(%d+)" if not sign then return sec, nil end -- not UTC if #offs == 2 then offs = offs .. "00" end -- 01 to 0100 local tz = { h = tonumber(offs:sub(1, 2)), m = tonumber(offs:sub(3, 4)) } if sign == "-" then tz.h = -tz.h tz.m = -tz.m end return sec, tz end function parse_date_unsafe(s, US) s = s:gsub("T", " ") -- ISO 8601 local parts = stringx.split(s:lower()) local i, p = 1, parts[1] local function nextp() i = i + 1 p = parts[i] end local year, min, hour, sec, apm local tz local _, nxt, day, month = p:find "^(%d+)/(%d+)" if day then -- swop for US case if US then day, month = month, day end _, _, year = p:find("^/(%d+)", nxt + 1) nextp() else -- ISO year, month, day = p:match "^(%d+)%-(%d+)%-(%d+)" if year then nextp() end end if p and not year and is_number(p) then -- has to be date if #p < 4 then day = p nextp() else -- unless it looks like a 24-hour time year = true end end if p and looks_like_a_month(p) then -- date followed by month p = p:sub(1, 3) if not months then create_months() end local mon = months[p] if mon then month = mon else error("not a month: " .. p) end nextp() end if p and not year and is_number(p) then year = p nextp() end if p then -- time is hh:mm[:ss], hhmm[ss] or H.M[am|pm] _, nxt, hour, min = p:find "^(%d+):(%d+)" local ns if nxt then -- are there seconds? _, ns, sec = p:find("^:(%d+)", nxt + 1) --if ns then sec, tz = parse_iso_end(p, ns or nxt, sec) --end else -- might be h.m _, ns, hour, min = p:find "^(%d+)%.(%d+)" if ns then apm = p:match "[ap]m$" else -- or hhmm[ss] local hourmin _, nxt, hourmin = p:find "^(%d+)" if nxt then hour = hourmin:sub(1, 2) min = hourmin:sub(3, 4) sec = hourmin:sub(5, 6) if #sec == 0 then sec = nil end sec, tz = parse_iso_end(p, nxt, sec) end end end end local today if year == true then year = nil end if not (year and month and day) then today = Date() end day = day and tonum(day, 1, 31, "day") or (month and 1 or today:day()) month = month and tonum(month, 1, 12, "month") or today:month() year = year and tonumber(year) or today:year() if year < 100 then -- two-digit year pivot around year < 2035 year = year + (year < 35 and 2000 or 1900) end hour = hour and tonum(hour, 0, apm and 12 or 24, "hour") or 12 if apm == "pm" then hour = hour + 12 end min = min and tonum(min, 0, 59) or 0 sec = sec and tonum(sec, 0, 60) or 0 --60 used to indicate leap second local res = Date { year = year, month = month, day = day, hour = hour, min = min, sec = sec } if tz then -- ISO 8601 UTC time local corrected = false if tz.h ~= 0 then res:add { hour = -tz.h } corrected = true end if tz.m ~= 0 then res:add { min = -tz.m } corrected = true end res.utc = true -- we're in UTC, so let's go local... if corrected then res = res:toLocal() end -- we're UTC! end return res end function parse_date(s) local ok, d = pcall(parse_date_unsafe, s) if not ok then -- error d = d:gsub(".-:%d+: ", "") return nil, d else return d end end return Date
local defaultOptions = { layout = DEFAULT_LAYOUT, -- set in init.lua vsync = true, showFps = true, showPing = true, fullscreen = false, classicView = not g_app.isMobile(), cacheMap = false, classicControl = not g_app.isMobile(), smartWalk = false, dash = false, autoChaseOverride = true, showStatusMessagesInConsole = true, showEventMessagesInConsole = true, showInfoMessagesInConsole = true, showTimestampsInConsole = true, showLevelsInConsole = true, showPrivateMessagesInConsole = true, showPrivateMessagesOnScreen = true, rightPanels = 1, leftPanels = g_app.isMobile() and 1 or 2, containerPanel = 8, backgroundFrameRate = 60, enableAudio = true, enableMusicSound = false, musicSoundVolume = 100, botSoundVolume = 100, enableLights = false, floorFading = 500, crosshair = 2, ambientLight = 100, optimizationLevel = 1, displayNames = true, displayHealth = true, displayMana = true, displayHealthOnTop = false, showHealthManaCircle = false, hidePlayerBars = false, highlightThingsUnderCursor = true, topHealtManaBar = true, displayText = true, dontStretchShrink = false, turnDelay = 30, hotkeyDelay = 30, wsadWalking = false, walkFirstStepDelay = 200, walkTurnDelay = 100, walkStairsDelay = 50, walkTeleportDelay = 200, walkCtrlTurnDelay = 150, actionBar1 = true, actionBar2 = false } local optionsWindow local optionsButton local optionsTabBar local options = {} local extraOptions = {} local generalPanel local interfacePanel local consolePanel local graphicsPanel local soundPanel local extrasPanel local audioButton function init() for k,v in pairs(defaultOptions) do g_settings.setDefault(k, v) options[k] = v end for _, v in ipairs(g_extras.getAll()) do extraOptions[v] = g_extras.get(v) g_settings.setDefault("extras_" .. v, extraOptions[v]) end optionsWindow = g_ui.displayUI('options') optionsWindow:hide() optionsTabBar = optionsWindow:getChildById('optionsTabBar') optionsTabBar:setContentWidget(optionsWindow:getChildById('optionsTabContent')) g_keyboard.bindKeyDown('Ctrl+Shift+F', function() toggleOption('fullscreen') end) g_keyboard.bindKeyDown('Ctrl+N', toggleDisplays) generalPanel = g_ui.loadUI('game') optionsTabBar:addTab(tr('Game'), generalPanel, '/images/optionstab/game') interfacePanel = g_ui.loadUI('interface') optionsTabBar:addTab(tr('Interface'), interfacePanel, '/images/optionstab/game') consolePanel = g_ui.loadUI('console') optionsTabBar:addTab(tr('Console'), consolePanel, '/images/optionstab/console') graphicsPanel = g_ui.loadUI('graphics') optionsTabBar:addTab(tr('Graphics'), graphicsPanel, '/images/optionstab/graphics') audioPanel = g_ui.loadUI('audio') optionsTabBar:addTab(tr('Audio'), audioPanel, '/images/optionstab/audio') extrasPanel = g_ui.createWidget('OptionPanel') for _, v in ipairs(g_extras.getAll()) do local extrasButton = g_ui.createWidget('OptionCheckBox') extrasButton:setId(v) extrasButton:setText(g_extras.getDescription(v)) extrasPanel:addChild(extrasButton) end if not g_game.getFeature(GameNoDebug) and not g_app.isMobile() then optionsTabBar:addTab(tr('Extras'), extrasPanel, '/images/optionstab/extras') end optionsButton = modules.client_topmenu.addLeftButton('optionsButton', tr('Options'), '/images/topbuttons/options', toggle) audioButton = modules.client_topmenu.addLeftButton('audioButton', tr('Audio'), '/images/topbuttons/audio', function() toggleOption('enableAudio') end) if g_app.isMobile() then audioButton:hide() end addEvent(function() setup() end) connect(g_game, { onGameStart = online, onGameEnd = offline }) end function terminate() disconnect(g_game, { onGameStart = online, onGameEnd = offline }) g_keyboard.unbindKeyDown('Ctrl+Shift+F') g_keyboard.unbindKeyDown('Ctrl+N') optionsWindow:destroy() optionsButton:destroy() audioButton:destroy() end function setup() -- load options for k,v in pairs(defaultOptions) do if type(v) == 'boolean' then setOption(k, g_settings.getBoolean(k), true) elseif type(v) == 'number' then setOption(k, g_settings.getNumber(k), true) elseif type(v) == 'string' then setOption(k, g_settings.getString(k), true) end end for _, v in ipairs(g_extras.getAll()) do g_extras.set(v, g_settings.getBoolean("extras_" .. v)) local widget = extrasPanel:recursiveGetChildById(v) if widget then widget:setChecked(g_extras.get(v)) end end if g_game.isOnline() then online() end end function toggle() if optionsWindow:isVisible() then hide() else show() end end function show() optionsWindow:show() optionsWindow:raise() optionsWindow:focus() end function hide() optionsWindow:hide() end function toggleDisplays() if options['displayNames'] and options['displayHealth'] and options['displayMana'] then setOption('displayNames', false) elseif options['displayHealth'] then setOption('displayHealth', false) setOption('displayMana', false) else if not options['displayNames'] and not options['displayHealth'] then setOption('displayNames', true) else setOption('displayHealth', true) setOption('displayMana', true) end end end function toggleOption(key) setOption(key, not getOption(key)) end function setOption(key, value, force) if extraOptions[key] ~= nil then g_extras.set(key, value) g_settings.set("extras_" .. key, value) if key == "debugProxy" and modules.game_proxy then if value then modules.game_proxy.show() else modules.game_proxy.hide() end end return end if modules.game_interface == nil then return end if not force and options[key] == value then return end local gameMapPanel = modules.game_interface.getMapPanel() if key == 'vsync' then g_window.setVerticalSync(value) elseif key == 'showFps' then modules.client_topmenu.setFpsVisible(value) if modules.game_stats and modules.game_stats.ui.fps then modules.game_stats.ui.fps:setVisible(value) end elseif key == 'showPing' then modules.client_topmenu.setPingVisible(value) if modules.game_stats and modules.game_stats.ui.ping then modules.game_stats.ui.ping:setVisible(value) end elseif key == 'fullscreen' then g_window.setFullscreen(value) elseif key == 'enableAudio' then if g_sounds ~= nil then g_sounds.setAudioEnabled(value) end if value then audioButton:setIcon('/images/topbuttons/audio') else audioButton:setIcon('/images/topbuttons/audio_mute') end elseif key == 'enableMusicSound' then if g_sounds ~= nil then g_sounds.getChannel(SoundChannels.Music):setEnabled(value) end elseif key == 'musicSoundVolume' then if g_sounds ~= nil then g_sounds.getChannel(SoundChannels.Music):setGain(value/100) end audioPanel:getChildById('musicSoundVolumeLabel'):setText(tr('Music volume: %d', value)) elseif key == 'botSoundVolume' then if g_sounds ~= nil then g_sounds.getChannel(SoundChannels.Bot):setGain(value/100) end audioPanel:getChildById('botSoundVolumeLabel'):setText(tr('Bot sound volume: %d', value)) elseif key == 'showHealthManaCircle' then modules.game_healthinfo.healthCircle:setVisible(value) modules.game_healthinfo.healthCircleFront:setVisible(value) modules.game_healthinfo.manaCircle:setVisible(value) modules.game_healthinfo.manaCircleFront:setVisible(value) elseif key == 'backgroundFrameRate' then local text, v = value, value if value <= 0 or value >= 201 then text = 'max' v = 0 end graphicsPanel:getChildById('backgroundFrameRateLabel'):setText(tr('Game framerate limit: %s', text)) g_app.setMaxFps(v) elseif key == 'enableLights' then gameMapPanel:setDrawLights(value and options['ambientLight'] < 100) graphicsPanel:getChildById('ambientLight'):setEnabled(value) graphicsPanel:getChildById('ambientLightLabel'):setEnabled(value) elseif key == 'floorFading' then gameMapPanel:setFloorFading(value) interfacePanel:getChildById('floorFadingLabel'):setText(tr('Floor fading: %s ms', value)) elseif key == 'crosshair' then if value == 1 then gameMapPanel:setCrosshair("") elseif value == 2 then gameMapPanel:setCrosshair("/images/crosshair/default.png") elseif value == 3 then gameMapPanel:setCrosshair("/images/crosshair/full.png") end elseif key == 'ambientLight' then graphicsPanel:getChildById('ambientLightLabel'):setText(tr('Ambient light: %s%%', value)) gameMapPanel:setMinimumAmbientLight(value/100) gameMapPanel:setDrawLights(options['enableLights'] and value < 100) elseif key == 'optimizationLevel' then g_adaptiveRenderer.setLevel(value - 2) elseif key == 'displayNames' then gameMapPanel:setDrawNames(value) elseif key == 'displayHealth' then gameMapPanel:setDrawHealthBars(value) elseif key == 'displayMana' then gameMapPanel:setDrawManaBar(value) elseif key == 'displayHealthOnTop' then gameMapPanel:setDrawHealthBarsOnTop(value) elseif key == 'hidePlayerBars' then gameMapPanel:setDrawPlayerBars(value) elseif key == 'topHealtManaBar' then modules.game_healthinfo.topHealthBar:setVisible(value) modules.game_healthinfo.topManaBar:setVisible(value) elseif key == 'displayText' then gameMapPanel:setDrawTexts(value) elseif key == 'dontStretchShrink' then addEvent(function() modules.game_interface.updateStretchShrink() end) elseif key == 'dash' then if value then g_game.setMaxPreWalkingSteps(2) else g_game.setMaxPreWalkingSteps(1) end elseif key == 'wsadWalking' then if modules.game_console and modules.game_console.consoleToggleChat:isChecked() ~= value then modules.game_console.consoleToggleChat:setChecked(value) end elseif key == 'hotkeyDelay' then generalPanel:getChildById('hotkeyDelayLabel'):setText(tr('Hotkey delay: %s ms', value)) elseif key == 'walkFirstStepDelay' then generalPanel:getChildById('walkFirstStepDelayLabel'):setText(tr('Walk delay after first step: %s ms', value)) elseif key == 'walkTurnDelay' then generalPanel:getChildById('walkTurnDelayLabel'):setText(tr('Walk delay after turn: %s ms', value)) elseif key == 'walkStairsDelay' then generalPanel:getChildById('walkStairsDelayLabel'):setText(tr('Walk delay after floor change: %s ms', value)) elseif key == 'walkTeleportDelay' then generalPanel:getChildById('walkTeleportDelayLabel'):setText(tr('Walk delay after teleport: %s ms', value)) elseif key == 'walkCtrlTurnDelay' then generalPanel:getChildById('walkCtrlTurnDelayLabel'):setText(tr('Walk delay after ctrl turn: %s ms', value)) end -- change value for keybind updates for _,panel in pairs(optionsTabBar:getTabsPanel()) do local widget = panel:recursiveGetChildById(key) if widget then if widget:getStyle().__class == 'UICheckBox' then widget:setChecked(value) elseif widget:getStyle().__class == 'UIScrollBar' then widget:setValue(value) elseif widget:getStyle().__class == 'UIComboBox' then if type(value) == "string" then widget:setCurrentOption(value, true) break end if value == nil or value < 1 then value = 1 end if widget.currentIndex ~= value then widget:setCurrentIndex(value, true) end end break end end g_settings.set(key, value) options[key] = value if key == 'classicView' or key == 'rightPanels' or key == 'leftPanels' or key == 'cacheMap' then modules.game_interface.refreshViewMode() elseif key == 'actionBar1' or key == 'actionBar2' then modules.game_actionbar.show() end end function getOption(key) return options[key] end function addTab(name, panel, icon) optionsTabBar:addTab(name, panel, icon) end function addButton(name, func, icon) optionsTabBar:addButton(name, func, icon) end -- hide/show function online() setLightOptionsVisibility(not g_game.getFeature(GameForceLight)) end function offline() setLightOptionsVisibility(true) end -- classic view -- graphics function setLightOptionsVisibility(value) graphicsPanel:getChildById('enableLights'):setEnabled(value) graphicsPanel:getChildById('ambientLightLabel'):setEnabled(value) graphicsPanel:getChildById('ambientLight'):setEnabled(value) interfacePanel:getChildById('floorFading'):setEnabled(value) interfacePanel:getChildById('floorFadingLabel'):setEnabled(value) interfacePanel:getChildById('floorFadingLabel2'):setEnabled(value) end
local xml2lua = require "xml2lua" local handler = require "xmlhandler.tree" local Util = require("Lua/Util/Util") --Util:MakeDir("cache_lua") local INPUT = "Lua/Data/cache/World_of_Warcraft_API.xml" local m = {} function m:SaveExport() local url = "https://wowpedia.fandom.com/wiki/Special:Export" local requestBody = "pages=World_of_Warcraft_API&curonly=1" Util:DownloadFilePost(INPUT, url, requestBody) end local symbols = { ["&lt;"] = "<", ["&gt;"] = ">", ["&amp;"] = "&", } function m:ReplaceHtml(text) return text:gsub("&.-;", symbols) end function m:GetWikitext(isRetail) local xmlstr = xml2lua.loadFile(INPUT) local parser = xml2lua.parser(handler) parser:parse(xmlstr) local text = handler.root.mediawiki.page.revision.text[1] text = self:ReplaceHtml(text) if isRetail then local str_start = text:find("== API Reference ==") local str_end = text:find("== Classic ==") return text:sub(str_start, str_end-1) else return text end end return m
--[[ Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved @file OstypeJudge.lua @author [email protected] @date 2016/03/12 11:27:24 @brief os type judge ]]-- local BDLOG = require('lua.bdlib.BdLogWrite') local setmetatable = setmetatable local tonumber = tonumber local Method = require('models.service.rule.JudgeMethods') local OstypeJudge = {} function OstypeJudge:new(userAgent, ruleType, ruleContent) local instance = {} instance.strIncludecSen = 2 instance.strIncludeInsen = 3 instance.userAgent = userAgent instance.ruleType = tonumber(ruleType) instance.ruleContent = ruleContent setmetatable(instance, {__index = self}) return instance end function OstypeJudge:judge() if self.ruleType == self.strIncludecSen then return Method.checkStrIncCaseSensitive(self.userAgent, self.ruleContent) elseif self.ruleType == self.strIncludeInsen then return Method.checkStrIncCaseInsensitive(self.userAgent, self.ruleContent) else BDLOG.log_fatal('unsupported rule type by Os_Type judge. [rule type] : %s', self.ruleType) return false end end return OstypeJudge
return { level = 49, need_exp = 70000, clothes_attrs = { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, }, }
local vehicleDef = { properties = { HealthPool = 1400, EnergyPool = 100, EnergyRechargeRate = 13, BoostEnergyCost = 20, BoostMultiplier = 1.5, MaxSpeed = 2500, MaxDivingSpeedMultiplier = 1.2, MinCrashDamageSpeed = 400, MaxCrashDamageSpeed = 2400, MinCrashDamage = 200, MaxCrashDamage = 2000, RamMinSpeed = 800, RamMaxDamageSpeed = 1900, RamMinDamage = 100, RamMaxDamage = 2400, }, } local vehicleWeaponsDef = { { name="Grav Cycle", changes={ Damage = 250, ExplosiveRadius = 200, ProjectileSpeed = 4000, ProjectileMaxSpeed = 4000, ImpactMomentum = 15000, CollisionSize = 42, DamageAgainstShrikeMultiplier = 2.5, ClipAmmo = 8, ReloadTime = 4.0, FireInterval = 0.15, MaxDamageRangeProportion = 0.5, MinDamageRangeProportion = 0.9, MinDamageProportion = 0.7 }, } } return {vehicle=vehicleDef, weapons=vehicleWeaponsDef}
---------------------- -- a module containing some classes. -- @module classes local _M = {} ---- a useful class. -- @type Bonzo _M.Bonzo = class() --- a method. -- function one function Bonzo:one() end --- a metamethod -- function __tostring function Bonzo:__tostring() end return M
modifier_kassadin_riftwalk = class({}) -------------------------------------------------------------------------------- function modifier_kassadin_riftwalk:IsHidden() return ( self:GetStackCount() == 0 ) end -------------------------------------------------------------------------------- function modifier_kassadin_riftwalk:DestroyOnExpire() return false end -------------------------------------------------------------------------------- function modifier_kassadin_riftwalk:OnCreated( kv ) self:GetAbility().modifier = self end -------------------------------------------------------------------------------- function modifier_kassadin_riftwalk:OnIntervalThink() if IsServer() then self:StartIntervalThink( -1 ) self:SetStackCount( 0 ) self:GetAbility():MarkAbilityButtonDirty() end end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
--[[ Utility functions and building blocks for functional programming styles. ]] local Tables = require(script.Parent.Tables) local t = require(script.Parent.Parent.t) local Functions = {} --[[ A simple function that does nothing, and returns nil. @usage Shorthand for `function() end`. Useful for when a function is expecting a callback but you don't want to do anything. ]] --: () -> () function Functions.noop() end --[[ A simple function that does nothing, but returns its input parameters. @trait Chainable @usage This is typically referred to as the "identity" function. Useful for when a function is expecting a callback to transform a value but you don't want to make any change to it. ]] --: <A>(...A -> ...A) function Functions.id(...) return ... end --[[ Returns a function that when called, returns the original input parameters. @trait Chainable @example findPlayer("builderman"):andThen(dash.returns("Found Dave!")) --> "Found Dave!" (soon after) @usage Useful for when you want a callback to discard the arguments passed in and instead use static ones. ]] --: <A>(...A -> () -> ...A) function Functions.returns(...) local args = {...} return function() return unpack(args) end end --[[ Return `true` if the _value_ is a function or a table with a `__call` entry in its metatable. @usage This is a more general test than checking purely for a function type. ]] --: any -> bool function Functions.isCallable(value) return type(value) == "function" or (type(value) == "table" and getmetatable(value) and getmetatable(value).__call ~= nil) end --[[ Returns a function that wraps the input _fn_ but only passes the first argument to it. @example local printOneArgument = dash.unary(function(...) print(...) end) printOneArgument("Hello", "World", "!") -->> Hello ]] --: <A, R>((A -> R) -> A -> R) function Functions.unary(fn) assert(Functions.isCallable(fn), "BadInput: fn must be callable") return function(first) return fn(first) end end --[[ Returns a function that when called, throws the original message. @example findPlayer("builderman"):andThen(dash.throws("DaveNotFound")) --!> "DaveNotFound" (soon after) @usage Useful for when you want a callback to discard any result and throw a message instead. ]] --: string -> () -> fail function Functions.throws(errorMessage) assert(t.string(errorMessage), "BadInput: errorMessage must be a string") return function() error(errorMessage) end end --[[ Takes a function _fn_ and binds _arguments_ to the head of the _fn_ argument list. Returns a function which executes _fn_, passing the bound arguments supplied, followed by any dynamic arguments. @example local function damagePlayer( player, amount ) player:Damage(amount) end local damageLocalPlayer = dash.bind(damagePlayer, game.Players.LocalPlayer) damageLocalPlayer(5) ]] --: <A, A2, R>(((...A, ...A2 -> R), ...A) -> ...A2 -> R) function Functions.bind(fn, ...) assert(Functions.isCallable(fn), "BadInput: fn must be callable") local args = {...} return function(...) return fn(unpack(args), ...) end end --[[ Takes a chainable function _fn_ and binds _arguments_ to the tail of the _fn_ argument list. Returns a function which executes _fn_, passing a subject ahead of the bound arguments supplied. @example local function setHealthTo(player, health) player.Health = health end local restoreHealth = dash.bindTail(setHealthTo, 100) local Jimbo = { Health = 5 } restoreHealth(Jimbo) Jimbo.Health --> 100 @example local filterHurtPlayers = dash.bindTail(dash.filter, function(player) return player.Health < player.MaxHealth end) local getName = dash.bindTail(dash.map, function(player) return player.Name end) local filterHurtNames = dash.compose(filterHurtPlayers, getName) filterHurtNames(game.Players) --> {"Frodo", "Boromir"} @see `dash.filter` @see `dash.compose` @usage Chainable rodash function feeds are mapped to `dash.fn`, such as `dash.fn.map(handler)`. ]] --: <S>(Chainable<S>, ...) -> S -> S function Functions.bindTail(fn, ...) assert(Functions.isCallable(fn), "BadInput: fn must be callable") local args = {...} return function(subject) return fn(subject, unpack(args)) end end --[[ Returns a function that when called, only calls _fn_ the first time the function is called. For subsequent calls, the initial return of _fn_ is returned, even if it is `nil`. @returns the function with method `:clear()` that resets the cached value. @trait Chainable @example local fry = dash.once(function(item) return "fried " .. item end) fry("sardine") --> "fried sardine" fry("squid") --> "fried sardine" fry:clear() fry("squid") --> "fried squid" fry("owl") --> "fried squid" @throws _passthrough_ - any error thrown when called will cause `nil` to cache and pass through the error. @usage Useful for when you want to lazily compute something expensive that doesn't change. ]] --: <A, R>((...A -> R), R?) -> Clearable & (...A -> R) function Functions.once(fn) assert(Functions.isCallable(fn), "BadInput: fn must be callable") local called = false local result = nil local once = { clear = function() called = false result = nil end } setmetatable( once, { __call = function(_, ...) if called then return result else called = true result = fn(...) return result end end } ) return once end --[[ Calls the supplied _fn_ on the subject and any additional arguments, returning the result. @example local function get(object, key) return object[key] end local Jimbo = { Name = "Jimbo" } dash.call(Jimbo, get, "Name") --> "Jimbo" @example local function get(object, key) return object[key] end local isABaggins = dash.fn:call(get, "Name"):endsWith("Baggins") local Jimbo = { Name = "Jimbo" } isABaggins(Jimbo) --> false @trait Chainable @usage This is useful when used in the `dash.fn:call` form to call arbitrary function inside a chain. @see `dash.chain` ]] --: <S, A, R>(S, (S, ...A -> R), ...A -> R) function Functions.call(subject, fn, ...) assert(Functions.isCallable(fn), "BadInput: fn must be callable") return fn(subject, ...) end --[[ Chain takes a dictionary of chainable functions and returns a Chain instance with methods mapped to the input functions. Chaining is useful when you want to simplify operating on data in a common form and perform sequences of operations on some data with a very concise syntax. An _actor_ function can check the value of the data at each step and change how the chain proceeds. Calling a _Chain_ with a subject reduces the chained operations in order on the subject. @param actor called for each result in the chain to determine how the next operation should process it. (default = `dash.invoke`) @example -- Define a simple chain that can operate a list of numbers. -- A chain function is called with the subject being processed as first argument, -- and any arguments passed in the chain as subsequent arguments. local numberChain = dash.chain({ addN = function(list, n) return dash.map(list, function(element) return element + n end) end, sum = function(list) return dash.sum(list) end }) local op = numberChain:addN(2):sum() op({1, 2, 3}) --> 12 @example -- Get the name of a player local function getName(player) return player.Name end) -- Create a chain that filters for hurt players and finds their name local filterHurtNames = dash.fn:filter(function(player) return player.Health < player.MaxHealth end):map(getName) -- Run the chain on the current game players filterHurtNames(game.Players) --> {"Frodo Baggins", "Boromir"} -- For fun, let's encapsulate the functionality above by -- defining a chain of operations on players... local players = dash.chain({ filterHurtPlayers = dash.fn:filter(function(player) return player.Health < player.MaxHealth end), -- Filter players by getting their name and checking it ends with 'Baggins' filterBaggins = dash.fn:filter(dash.fn:call(getName):endsWith("Baggins")) }) local hurtHobbits = players:filterHurtPlayers():filterBaggins() hurtHobbits(game.Players) --> {{Name = "Frodo Baggins", ...}} local names = dash.fn:map(getName) -- Chains are themselves chainable, so you can compose two chains together local filterHurtHobbitNames = dash.compose(hurtHobbits, names) filterHurtHobbitNames(game.Players) --> {"Frodo Baggins"} @trait Chainable @usage The "Rodash" chain: `dash.chain(_)` is aliased to `dash.fn`, so instead of writing `dash.chain(_):filter` you can simply write `dash.fn:filter`, or any other chainable method. @usage A chained function can be made using `dash.chain` or built inductively using other chained methods of `dash.fn`. @usage A chainable method is one that has the subject which is passed through a chain as the first argument, and subsequent arguments @see `dash.chainFn` - Makes a function chainable if it returns a chain. @see `dash.invoke` - the identity actor @see `dash.continue` - an actor for chains of asynchronous functions @see `dash.maybe` - an actor for chains of partial functions ]] --: <S,T:Chainable<S>{}>(T, Actor<S>) -> Chain<S,T> function Functions.chain(fns, actor) if actor == nil then actor = Functions.invoke end assert(Functions.isCallable(actor), "BadInput: actor must be callable") local chain = {} setmetatable( chain, { __index = function(self, name) local fn = fns[name] assert(Functions.isCallable(fn), "BadFn: Chain key " .. tostring(name) .. " is not callable") local feeder = function(parent, ...) assert(type(parent) == "table", "BadCall: Chain functions must be called with ':'") local stage = {} local op = Functions.bindTail(fn, ...) setmetatable( stage, { __index = chain, __call = function(self, subject) local value = parent(subject) return actor(op, value) end, __tostring = function() return tostring(parent) .. "::" .. name end } ) return stage end return feeder end, __newindex = function() error("ReadonlyKey: Cannot assign to a chain, create one with dash.chain instead.") end, __call = function(_, subject) return subject end, __tostring = function() return "Chain" end } ) return chain end --[[ Wraps a function, making it chainable if it returns a chain itself. This allows you to define custom functions in terms of the arguments they will take when called in a chain, and return a chained function which performs the operation, rather than explicitly taking the subject as first argument. @example -- In the chain example addN was defined like so: local function addN(list, n) return dash.map(list, function(element) return element + n end) end numberChain = dash.chain({ addN = addN }) local op = numberChain:addN(2):sum() op({1, 2, 3}) --> 12 -- It is more natural to define addN as a function taking one argument, -- to match the way it is called in the chain: local function addN(n) -- Methods on dash.fn are themselves chained, so "list" can be dropped. return dash.fn:map(function(element) return element + n end) end -- The dash.chainFn is used to wrap any functions which return chains. numberChain = dash.chain({ addN = dash.chainFn(addN) }) local op = numberChain:addN(2):sum() op({1, 2, 3}) --> 12 @see `dash.chain` ]] --: <T, A, R>((...A -> T -> R) -> T, ...A -> R) function Functions.chainFn(fn) assert(Functions.isCallable(fn), "BadInput: fn must be callable") return function(source, ...) return fn(...)(source) end end --[[ An [Actor](/rodash/types#Actor) which calls the supplied _fn_ with the argument tail. @example local getName = function(player) return player.Name end local Jimbo = { Name = "Jimbo" } dash.invoke(getName, Jimbo) --> "Jimbo" @usage This is the default _actor_ for `dash.chain` and acts as an identity, meaning it has no effect on the result. ]] --: <S, A>((A -> S), ...A -> S) function Functions.invoke(fn, ...) assert(Functions.isCallable(fn), "BadInput: fn must be callable") return fn(...) end --[[ An [Actor](/rodash/types#Actor) which cancels execution of a chain if a method returns nil, evaluating the chain as nil. Can wrap any other actor which handles values that are non-nil. @example -- We can define a chain of Rodash functions that will skip after a nil is returned. local maybeFn = dash.chain(_, dash.maybe()) local getName = function(player) return player.Name end local players players = dash.chain( { -- Any chainable functions can be used call = dash.call, endsWith = dash.endsWith, filterHurt = dash.fn:filter( function(player) return player.Health < 100 end ), filterBaggins = dash.chainFn( function() -- If getName returns nil here, endsWith will be skipped return dash.fn:filter(maybeFn:call(getName):endsWith("Baggins")) end ) } ) local hurtHobbits = players:filterHurt():filterBaggins() local mapNames = dash.fn:map(getName) local filterHurtBagginsNames = dash.compose(hurtHobbits, mapNames) -- Here, one player record doesn't have a Name property, so it is skipped. local crew = { { Name = "Frodo Baggins", Health = 50 }, { Name = "Bilbo Baggins", Health = 100 }, { Health = 0 } } ]] --: <S>(Actor<S>? -> Actor<S>) function Functions.maybe(actor) actor = actor or Functions.invoke assert(Functions.isCallable(actor), "BadInput: actor must be callable") return function(fn, ...) local args = {...} if args[1] == nil then return else return actor(fn, ...) end end end --[[ An [Actor](/rodash/types#Actor) getter which awaits on any promises returned by chain methods, and continues execution when the promise completes. This allows any asynchronous methods to be used in chains without modifying any of the chain's synchronous methods, removing any boilerplate needed to handle promises in the main code body. Can wrap any other actor which handles values after any promise resolution. @param actor (default = `dash.invoke`) The actor to wrap. @example -- Let's define a function which returns an answer after a delay local getName = function(player) return dash.delay(1):andThen(dash.returns(player.Name)) end local players players = dash.chain( { -- Any chainable function can be used filter = dash.filter, -- A chain which evaluates a promise of the player names mapNames = dash.fn:map(getName):parallel(), filterHurt = dash.fn:filter( function(player) return player.Health < 100 end ), mapNameIf = dash.chainFn( function(expectedName) -- Methods on self work as expected return players:mapNames():filter(dash.fn:endsWith(expectedName)) end ) }, dash.continue() ) local filterHurtHobbitNames = players:filterHurt():mapNameIf("Baggins") local crew = { { Name = "Frodo Baggins", Health = 50 }, { Name = "Bilbo Baggins", Health = 100 }, { Name = "Boromir", Health = 0 } } filterHurtHobbitNames(crew):await() --> {"Frodo Baggins"} (some time later) @rejects passthrough @see `dash.chain` ]] --: <S>(Actor<S>? -> Actor<S>) function Functions.continue(actor) actor = actor or Functions.invoke assert(Functions.isCallable(actor), "BadInput: actor must be callable") return function(fn, value, ...) local Async = require(script.Parent.Async) return Async.resolve(value):andThen( function(...) return actor(fn, ...) end ) end end local getRodashChain = Functions.once( function(rd) return Functions.chain(rd) end ) --[[ A [Chain](/rodash/types/#chain) built from Rodash itself. Any [Chainable](/rodash/types/#chainable) Rodash function can be used as a method on this object, omitting the subject until the whole chain is evaluated by calling it with the subject. @example local getNames = dash.fn:map(function( player ) return player.Name end) getNames(game.Players) --> {"Bilbo Baggins", "Frodo Baggins", "Peregrin Took"} @example local getNames = dash.fn:map(function( player ) return player.Name end):filter(function( name ) return dash.endsWith(name, "Baggins") end) getNames(game.Players) --> {"Bilbo Baggins", "Frodo Baggins"} @example local getNames = dash.fn:map(function( player ) return player.Name end):filter(dash.fn:endsWith("Baggins")) getNames(game.Players) --> {"Bilbo Baggins", "Frodo Baggins"} @see `dash.chain` - to make your own chains. ]] --: Chain<any,dash> Functions.fn = {} setmetatable( Functions.fn, { __index = function(self, key) local rd = require(script.Parent) return getRodashChain(rd)[key] end, __call = function(self, subject) return subject end, __tostring = function() return "fn" end } ) --[[ Returns a function that calls the argument functions in left-right order on an input, passing the return of the previous function as argument(s) to the next. @example local function fry(item) return "fried " .. item end local function cheesify(item) return "cheesy " .. item end local prepare = dash.compose(fry, cheesify) prepare("nachos") --> "cheesy fried nachos" @usage Useful for when you want to lazily compute something expensive that doesn't change. @trait Chainable ]] --: <A>((...A -> ...A)[]) -> ...A -> A function Functions.compose(...) local fnCount = select("#", ...) if fnCount == 0 then return Functions.id end local fns = {...} return function(...) local result = {fns[1](...)} for i = 2, fnCount do result = {fns[i](unpack(result))} end return unpack(result) end end --[[ Like `dash.once`, but caches non-nil results of calls to _fn_ keyed by some serialization of the input arguments to _fn_. By default, all the args are serialized simply using `tostring`. Optionally memoize takes `function serializeArgs(args, cache)`, a function that should return a string key which a result should be cached at for a given signature. Return nil to avoid caching the result. @param serializeArgs (default = `dash.serialize`) @returns the function with method `:clear(...)` that resets the cache for the argument specified, or `:clearAll()` to clear the entire cache. @example local menu = {"soup", "bread", "butter"} local heat = dash.memoize(function(index) return "hot " ... menu[index] end) heat(1) --> "hot soup" menu = {"caviar"} heat(1) --> "hot soup" heat(2) --> nil menu = {"beef", "potatoes"} heat(1) --> "hot soup" heat(2) --> "hot potatoes" heat:clear(1) heat(1) --> "hot beef" @see `dash.once` @see `dash.serialize` @see `dash.serializeDeep` if you want to recursively serialize arguments. ]] --: <A, R>((...A -> R), ...A -> string?) -> Clearable<A> & AllClearable & (...A -> R) function Functions.memoize(fn, serializeArgs) assert(Functions.isCallable(fn), "BadInput: fn must be callable") serializeArgs = serializeArgs or Functions.unary(Tables.serialize) assert(Functions.isCallable(serializeArgs), "BadInput: serializeArgs must be callable or nil") local cache = {} local clearable = { clear = function(_, ...) local cacheKey = serializeArgs({...}, cache) if cacheKey then cache[cacheKey] = nil end end, clearAll = function() cache = {} end } setmetatable( clearable, { __call = function(_, ...) local cacheKey = serializeArgs({...}, cache) if cacheKey == nil then return fn(...) else if cache[cacheKey] == nil then cache[cacheKey] = fn(...) end return cache[cacheKey] end end } ) return clearable end --[[ Like `delay`, this calls _fn_ after _delayInSeconds_ time has passed, with the added benefit of being cancelable. The _fn_ is called in a separate thread, meaning that it will not block the thread it is called in, and if the calling threads, the _fn_ will still be called at the expected time. @returns an instance which `:clear()` can be called on to prevent _fn_ from firing. @example local waitTimeout = dash.setTimeout(function() print("Sorry, no players came online!") end, 5) game.Players.PlayerAdded:Connect(function(player) waitTimeout:clear() end) @see `dash.delay` ]] --: (Clearable -> ()), number -> Clearable function Functions.setTimeout(fn, delayInSeconds) assert(Functions.isCallable(fn), "BadInput: fn must be callable") assert(t.number(delayInSeconds), "BadInput: delayInSeconds must be a number") local cleared = false local timeout delay( delayInSeconds, function() if not cleared then fn(timeout) end end ) timeout = { clear = function() cleared = true end } return timeout end --[[ Like `dash.setTimeout` but calls _fn_ after every interval of _intervalInSeconds_ time has passed. The _fn_ is called in a separate thread, meaning that it will not block the thread it is called in, and if the calling threads, the _fn_ will still be called at the expected times. @param delayInSeconds (default = _intervalInSeconds_) The delay before the initial call. @returns an instance which `:clear()` can be called on to prevent _fn_ from firing. @example local waitInterval = dash.setInterval(function() print("Waiting for more players...") end, 5) game.Players.PlayerAdded:Connect(function(player) waitInterval:clear() end) @see `dash.setTimeout` ]] --: (Clearable -> ()), number, number? -> Clearable function Functions.setInterval(fn, intervalInSeconds, delayInSeconds) assert(Functions.isCallable(fn), "BadInput: fn must be callable") assert(t.number(intervalInSeconds), "BadInput: intervalInSeconds must be a number") assert(t.optional(t.number)(delayInSeconds), "BadInput: delayInSeconds must be a number") local timeout local callTimeout local function handleTimeout() callTimeout() fn(timeout) end callTimeout = function() timeout = Functions.setTimeout(handleTimeout, intervalInSeconds) end if delayInSeconds ~= nil then timeout = Functions.setTimeout(handleTimeout, delayInSeconds) else callTimeout() end return { clear = function() timeout:clear() end } end --[[ Creates a debounced function that delays calling _fn_ until after _delayInSeconds_ seconds have elapsed since the last time the debounced function was attempted to be called. @returns the debounced function with method `:clear()` can be called on to cancel any scheduled call. @usage A nice [visualisation of debounce vs. throttle](http://demo.nimius.net/debounce_throttle/), the illustrated point being debounce will only call _fn_ at the end of a spurt of events. ]] --: <A, R>(...A -> R), number -> Clearable & (...A -> R) function Functions.debounce(fn, delayInSeconds) assert(Functions.isCallable(fn), "BadInput: fn must be callable") assert(type(delayInSeconds) == "number", "BadInput: delayInSeconds must be a number") local lastResult = nil local timeout local debounced = { clear = function() if timeout then timeout:clear() end end } setmetatable( debounced, { __call = function(_, ...) local args = {...} if timeout then timeout:clear() end timeout = Functions.setTimeout( function() lastResult = fn(unpack(args)) end, delayInSeconds ) return lastResult end } ) return debounced end --[[ Creates a throttle function that drops any repeat calls within a cooldown period and instead returns the result of the last call. @example local post = dash.async(HttpService.Post) local saveMap = dash.throttle(function(data) post("https://example.com/save", data) end, 10) saveMap(map) -- This saves the map saveMap(map) -- This function call is throttled and won't result in post being called saveMap(map) -- Same again wait(10) saveMap(map) -- Enough time has passed, so this saves the map again @usage A nice [visualisation of debounce vs. throttle](http://demo.nimius.net/debounce_throttle/), the illustrated point being throttle will call _fn_ every period during a spurt of events. @see `dash.async` ]] --: <A, R>((...A) -> R), number -> ...A -> R function Functions.throttle(fn, cooldownInSeconds) assert(Functions.isCallable(fn), "BadInput: fn must be callable") assert(type(cooldownInSeconds) == "number", "BadInput: cooldownInSeconds must be a number > 0") assert(cooldownInSeconds > 0, "BadInput: cooldownInSeconds must be a number > 0") local cached = false local lastResult = nil return function(...) if not cached then cached = true lastResult = fn(...) Functions.setTimeout( function() cached = false end, cooldownInSeconds ) end return lastResult end end return Functions
local feats = {} local flutedcolumn = { name = "Fluted Column", useWalkedOnImage = true, description = "A decorative stone column.", symbol = "|", passableFor={ghost=true}, color={r=200,g=200,b=200}, blocksMovement = true, alwaysDisplay = true, blocksSight = true, ghostPassable=true } function flutedcolumn:new() self.image_name = "flutedcolumn" .. random(1,2) end feats['flutedcolumn'] = flutedcolumn local seaweed = { name = "Seaweed", description = "A clump of seaweed.", symbol = "{", color={r=0,g=150,b=0,a=255}, useWalkedOnImage=true } function seaweed:new() local btype = random(1,4) self.image_name = "seaweed" .. btype end function seaweed:enter(entity,fromX,fromY) if entity:is_type('flyer') == false and not entity:has_condition('inbushes') then entity:give_condition('inbushes',-1) if player:can_see_tile(entity.x,entity.y) then output:sound('grass_rustle' .. random(1,2)) end end --end flyer if end --end enter function possibleFeatures['seaweed'] = seaweed return feats
ENDGAMESONGS = { "music/HL2_song29.mp3", "music/HL2_song14.mp3", "music/HL2_song26.mp3", "music/HL1_song20.mp3", "music/HL1_song19.mp3", "music/HL1_song16.mp3", "music/HL2_song20_submix0.mp3" } MINIGAMESONGS = { "labyrinth/music/minigame1.mp3" } GAMESTARTSONGS = { "labyrinth/music/gamestart1.mp3", "labyrinth/music/gamestart2.mp3", "labyrinth/music/gamestart3.mp3", "labyrinth/music/gamestart4.mp3", "labyrinth/music/gamestart5.mp3", "labyrinth/music/gamestart6.mp3" } MINOTAURSONGS = { "labyrinth/music/minosong1.mp3", "labyrinth/music/minosong2.mp3", "labyrinth/music/minosong3.mp3", "labyrinth/music/minosong4.mp3", "labyrinth/music/minosong5.mp3", "labyrinth/music/minosong6.mp3", "labyrinth/music/minosong7.mp3", "labyrinth/music/minosong8.mp3" } --Music Credits (All are royalty free) --"Bent and Broken" Kevin MacLeod (incompetech.com) --"Hall of the Mountain King" Kevin MacLeod (incompetech.com) --"One of Them" Kevin MacLeod (incompetech.com) --"The House of Leaves" Kevin MacLeod (incompetech.com) --"Classic Horror 3" Kevin MacLeod (incompetech.com) --"Sugar Plum Dark Mix" Kevin MacLeod (incompetech.com) --"Go Cart" Kevin MacLeod (incompetech.com) --"Club Driver" Kevin MacLeod (incompetech.com) --"Exhilarate" Kevin MacLeod (incompetech.com) --"Hitman" Kevin MacLeod (incompetech.com) --"Iron Horse" Kevin MacLeod (incompetech.com) --"Prelude and Action" Kevin MacLeod (incompetech.com) --"Video Dungeon Boss" Kevin MacLeod (incompetech.com) --"Movement Proposition" Kevin MacLeod (incompetech.com) --"Plans in Motion" Kevin MacLeod (incompetech.com) --Licensed under Creative Commons: By Attribution 3.0 --http://creativecommons.org/licenses/by/3.0/
------------------------------------- ---------------- Cuffs -------------- ------------------------------------- -- Copyright (c) 2015 Nathan Healy -- -------- All rights reserved -------- ------------------------------------- -- weapon_cuff_shackles.lua SHARED -- -- -- -- Strongest handcuffs available. -- ------------------------------------- AddCSLuaFile() SWEP.Base = "weapon_cuff_base" SWEP.Category = "Handcuffs" SWEP.Author = "my_hat_stinks" SWEP.Instructions = "Strong metal shackles." SWEP.Spawnable = true SWEP.AdminOnly = true SWEP.AdminSpawnable = true SWEP.Slot = 3 SWEP.PrintName = "Shackles" // // Handcuff Vars SWEP.CuffTime = 1.0 // Seconds to handcuff SWEP.CuffSound = Sound( "buttons/lever7.wav" ) SWEP.CuffMaterial = "phoenix_storms/cube" SWEP.CuffRope = "cable/cable2" SWEP.CuffStrength = 1.4 SWEP.CuffRegen = 0.8 SWEP.RopeLength = 0 SWEP.CuffReusable = false SWEP.CuffBlindfold = false SWEP.CuffGag = false SWEP.CuffStrengthVariance = 0.4 // Randomise strangth SWEP.CuffRegenVariance = 0.1 // Randomise regen
addEvent("onSkinChangeBuy",true) call ( getResourceFromName ( "scoreboard" ), "scoreboardAddColumn", "level" ) CPlayer = {} Players = {} --Constructor function CPlayer:constructor(id,name,password,serial,kills,tode,coins,level,adminlvl,skin) self.ID = id self.Name = name self.Password = password self.Serial = serial self.Kills = kills self.Tode = tode self.Coins = coins self.Level = level self.Adminlvl = adminlvl self.Skin = skin self:setModel(skin) self.LoggedIn = true Players[self.ID] = self setElementData(self,"kills",self.Kills) setElementData(self,"tode",self.Tode) setElementData(self,"level",self.Level) setElementData(self,"coins",self.Coins) ---EVENTS self.eOnWasted = bind(CPlayer.onWasted, self) addEventHandler("onPlayerWasted",self, self.eOnWasted) self.eOnQuit = bind(CPlayer.onQuit,self) addEventHandler("onPlayerQuit",self,self.eOnQuit) self.eOnChangeSkinBuy = bind(CPlayer.onSkinBuy,self) addEventHandler("onSkinChangeBuy",self,self.eOnChangeSkinBuy) triggerClientEvent(self,"showPlayerHud",self,"true") triggerClientEvent(self,"jetztbindediescheisse",self) end --Functions function CPlayer:onSkinBuy(id) if self.Coins >= 50 then self:setSkin(id) self:takeCoins(50) else outputChatBox("Not enough coins!",self,255,0,0) end end function CPlayer:onWasted(totalAmmo,killer,KillerWeapon,bodypart,stealth) self:newDeath(killer) if killer then if getElementType(killer) == "player" then killer:newKill(self) if killer.Level == 15 and KillerWeapon ~= 4 then outputChatBox(killer:getName().." has won the round!",getRootElement(),255,0,0) killer:giveCoins(4) for i,v in ipairs(getElementsByType("player")) do if v:isLoggedIn() then killPed(v) v:setLevel(1) v:spawning() end end elseif killer.Level <= 14 and KillerWeapon ~= 4 then killer:levelUp() self:spawning() elseif KillerWeapon == 4 then killer:giveCoins(1) self:levelDown() self:spawning() end end else outputChatBox("You killed yourself!",self,255,255,0) self:spawning() end end function CPlayer:onQuit(quitType,reason,responsibleElement) DB:query("UPDATE players SET Serial=?, Kills=?, Tode=?, Coins=?, Level=?, Adminlvl=?, Skin=? WHERE Name=?", getPlayerSerial(self),self.Kills,self.Tode,self.Coins,self.Level,self.Adminlvl,self.Skin, self:getName() ) end function CPlayer:setLevel(level) self.Level = level setElementData(self,"level",self.Level) end function CPlayer:newDeath(killer) self.Tode = self.Tode + 1 setElementData(self,"tode",self.Tode) triggerClientEvent(self,"playLooser",self) if killer then outputChatBox("You are killed by "..killer:getName(),self,255,255,0) end end function CPlayer:newKill(opfer) self.Kills = self.Kills + 1 setElementData(self,"kills",self.Kills) triggerClientEvent(self,"playWinner",self) outputChatBox("You killed "..opfer:getName(),self,255,255,0) end local WaffenListe = {} WaffenListe[1] = 22 --Pistol WaffenListe[2] = 24 --Deagle WaffenListe[3] = 25 --Shotgun WaffenListe[4] = 26 --Spawn-Off Shotgun WaffenListe[5] = 27 --Spaz-12 Combat Shotgun WaffenListe[6] = 28 --Uzi WaffenListe[7] = 29 -- MP5 WaffenListe[8] = 32-- Tec-9 WaffenListe[9] = 30 --Ak47 WaffenListe[10] = 31 --M4 WaffenListe[11] = 33 -- Country Rifle WaffenListe[12] = 34 -- Sniper WaffenListe[13] = 35 --RPG WaffenListe[14] = 36 --Jevelin --WaffenListe[15] = 37 --Flammenwerfer --WaffenListe[16] = 16 -- Granate --WaffenListe[17] = 18 --Molotov WaffenListe[15] = 38 --Minigun function CPlayer:levelUp() self.Level = self.Level + 1 setElementData(self,"level",self.Level) takeAllWeapons(self) giveWeapon(self,WaffenListe[self.Level],9999,true) giveWeapon(self,4) end function CPlayer:levelDown() outputChatBox("KNIFE KILL!",self,255,255,0) if self.Level > 1 then self.Level = self.Level - 1 setElementData(self,"level",self.Level) takeAllWeapons(self) giveWeapon(self,WaffenListe[self.Level],9999,true) giveWeapon(self,4) end end function CPlayer:giveCoins(coin) self.Coins = self.Coins + tonumber(coin) setElementData(self,"coins",self.Coins) end function CPlayer:takeCoins(coin) if self.Coins >= coin then self.Coins = self.Coins - coin setElementData(self,"coins",self.Coins) else return false end end function CPlayer:setKills(value) if value then self.Kills = value setElementData(self,"kills",self.Kills) return true end end function CPlayer:setDeath(value) if value then self.Tode = value setElementData(self,"tode",self.Tode) return true end end function CPlayer:setLevel(value) if value then self.Level = value setElementData(self,"level",self.Level) end end ------------------SPAWN------------------------------ local SpawnPlatz = {} SpawnPlatz[1] = {0,0,3} SpawnPlatz[2] = {-296,-2.4000000953674,1.1000000238419} SpawnPlatz[3] = {-196.69999694824,68.900001525879,3.0999999046326} SpawnPlatz[4] = {-48.099998474121,6.0999999046326,3.0999999046326} SpawnPlatz[5] = {-78.900001525879,-115,3.0999999046326} SpawnPlatz[6] = {-142.5,-96.800003051758,3.0999999046326} SpawnPlatz[7] = {-38.299999237061,98.099998474121,3.0999999046326} SpawnPlatz[8] = {70.400001525879,52.200000762939,0.60000002384186} SpawnPlatz[9] = {-142.5,50,3.0999999046326} SpawnPlatz[10] = {-203.80000305176,222,11.800000190735} local spawnRan = {} function CPlayer:spawning() spawnRan[self] = math.random(1,10) setTimer(function() spawnPlayer(self,SpawnPlatz[spawnRan[self]][1],SpawnPlatz[spawnRan[self]][2],SpawnPlatz[spawnRan[self]][3],0,self.Skin) setCameraTarget(self,self) fadeCamera(self,true) takeAllWeapons(self) giveWeapon(self,WaffenListe[self.Level],9999,true) giveWeapon(self,4) end,5000,1) end --Skin function CPlayer:getSkin() return self.Skin end function CPlayer:setSkin(id) if setElementModel(self,id) then self.Skin = id else return false end end --Name function CPlayer:getName() return self.Name end --login function CPlayer:isLoggedIn() if self.LoggedIn then return true else return false end end --VIP function CPlayer:getCoins() return self.Coins end function CPlayer:setCoins(value) if value then self.Coins = value setElementData(self,"coins",self.Coins) return true else return false end end --Admin function CPlayer:isAdmin() if self.Adminlvl >= 1 then return true else return false end end function CPlayer:getAdminLevel() return self.Adminlvl end function CPlayer:save() x,y,z = getElementPosition(self) int = getElementInterior(self) dim = getElementDimension(self) _,_,rz = getElementRotation(self) spawn = tostring(x).."|"..tostring(y).."|"..tostring(z).."|"..tostring(int).."|"..tostring(dim).."|"..tostring(rz) DB:query("UPDATE players SET Serial=?, Kills=?, Tode=?, Coins=?, Level=?, Adminlvl=?, Skin=? WHERE Name=?", getPlayerSerial(self),self.Kills,self.Tode,self.Coins,self.Level,self.Adminlvl,self.Skin, self:getName() ) end ----SECURE SAVE addEventHandler("onResourceStop",getResourceRootElement(getThisResource()), function() for i,v in ipairs(getElementsByType("player")) do if v:isLoggedIn() then v:save() end end end) function CPlayer:destructor() self.LoggedIn = false Players[self.ID] = nil end --COMMANDHANDLER addCommandHandler("set", function(player,cmd,target,value,new) if player:isAdmin() then if target and value and new then if getPlayerFromName(target) then target = getPlayerFromName(target) if tonumber(new) then new = tonumber(new) if value == "skin" then target:setSkin(new) outputChatBox(getPlayerName(target).."s "..value.." changed!",player,0,255,0) elseif value == "coins" then target:setCoins(new) outputChatBox(getPlayerName(target).."s "..value.." changed!",player,0,255,0) elseif value == "kills" then target:setKills(new) outputChatBox(getPlayerName(target).."s "..value.." changed!",player,0,255,0) elseif value == "death" then target:setDeath(new) outputChatBox(getPlayerName(target).."s "..value.." changed!",player,0,255,0) elseif value == "level" then target:setLevel(new) outputChatBox(getPlayerName(target).."s "..value.." changed!",player,0,255,0) end end else outputChatBox("Player not found!",player,255,0,0) end end end end)
Tools = dofile(global:getCurrentDirectory() .. "\\YayaTools\\Module\\Tools.lua") Craft = Tools.craft Movement = Tools.movement Zone = Tools.zone Packet = Tools.packet Character = Tools.character Gather = Tools.gather API = Tools.api Monsters = Tools.monsters function move() local dic = Tools.dictionnary() local list = Tools.list() for i = 0, 10 do dic:Add("test" .. i, i) list:Add(i * 10) end dic:Foreach(function(v, k) Tools:Print("Value : " .. v .. " Key : " .. k) end) list:Foreach(function(v, i) Tools:Print("Value : " .. v .. " Index : " .. i) end) --Tools:Dump(Zone:GetSubAreaObject(Zone:GetSubAreaIdByMapId(153880322))) --Tools:Print(Zone:GetAreaName(8)) --Tools:Print(Zone:GetAreaIdByMapId(153880322)) --Tools:Print(Zone:GetAreaIdByMapId("153880322")) end function messagesRegistering() Character.dialog:InitCallBack() Movement:InitCallBack() Gather:InitCallBack() end API = API() Craft = Craft({api = API}) Monsters = Monsters({api = API}) Zone = Zone({api = API}) Packet = Packet() Gather = Gather({packet = Packet}) Character = Character({packet = Packet}) Movement = Movement({zone = Zone, packet = Packet, character = Character}) Tools = Tools()
------------------------------------------------------------------------------- -- Spine Runtimes Software License v2.5 -- -- Copyright (c) 2013-2016, Esoteric Software -- All rights reserved. -- -- You are granted a perpetual, non-exclusive, non-sublicensable, and -- non-transferable license to use, install, execute, and perform the Spine -- Runtimes software and derivative works solely for personal or internal -- use. Without the written permission of Esoteric Software (see Section 2 of -- the Spine Software License Agreement), you may not (a) modify, translate, -- adapt, or develop new applications using the Spine Runtimes or otherwise -- create derivative works or improvements of the Spine Runtimes or (b) remove, -- delete, alter, or obscure any trademarks or any copyright, trademark, patent, -- or other intellectual property or proprietary rights notices on or in the -- Software, including any copy thereof. Redistributions in binary or source -- form must include this license and terms. -- -- THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -- EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF -- USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -- IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- local setmetatable = setmetatable local AttachmentType = require "spine-lua.attachments.AttachmentType" local VertexAttachment = require "spine-lua.attachments.VertexAttachment" local utils = require "spine-lua.utils" local Color = require "spine-lua.Color" local MeshAttachment = {} MeshAttachment.__index = MeshAttachment setmetatable(MeshAttachment, { __index = VertexAttachment }) function MeshAttachment.new (name) if not name then error("name cannot be nil", 2) end local self = VertexAttachment.new(name, AttachmentType.mesh) self.region = nil self.path = nil self.regionUVs = nil self.uvs = nil self.triangles = nil self.color = Color.newWith(1, 1, 1, 1) self.hullLength = 0 self.parentMesh = nil self.inheritDeform = false self.tempColor = Color.newWith(1, 1, 1, 1) setmetatable(self, MeshAttachment) return self end function MeshAttachment:updateUVs () local u = 0 local v = 0 local width = 0 local height = 0 if not self.region then u = 0 v = 0 width = 1 height = 1 else u = self.region.u; v = self.region.v; width = self.region.u2 - u; height = self.region.v2 - v; end local regionUVs = self.regionUVs if not self.uvs or (#self.uvs ~= #regionUVs) then self.uvs = utils.newNumberArray(#regionUVs) end local uvs = self.uvs if self.region and self.region.rotate then local i = 0 local n = #uvs while i < n do uvs[i + 1] = u + regionUVs[i + 2] * width; uvs[i + 2] = v + height - regionUVs[i + 1] * height; i = i + 2 end else local i = 0 local n = #uvs while i < n do uvs[i + 1] = u + regionUVs[i + 1] * width; uvs[i + 2] = v + regionUVs[i + 2] * height; i = i + 2 end end end function MeshAttachment:applyDeform (sourceAttachment) return self == sourceAttachment or (self.inheritDeform and self.parentMesh == sourceAttachment) end function MeshAttachment:setParentMesh (parentMesh) self.parentMesh = parentMesh if parentMesh then self.bones = parentMesh.bones self.vertices = parentMesh.vertices self.regionUVs = parentMesh.regionUVs self.triangles = parentMesh.triangles self.hullLength = parentMesh.hullLength end end return MeshAttachment
function start (song) print("Song: " .. song .. " @ " .. bpm .. " downscroll: " .. downscroll) changeDadIcon('spirit-glitch') end local defaultHudX = 0 local defaultHudY = 0 local defaultWindowX = 0 local defaultWindowY = 0 local lastStep = 0 function update (elapsed) local currentBeat = (songPos / 1000)*(bpm/60) end function beatHit (beat) if curBeat == 94 then inAndOutCam(0.5, 0.5, 0.5) end if curBeat == 96 then changeDadCharacterBetter(250, 460, 'senpai-angry') changeDadIcon('senpai-glitch') end if curBeat == 144 then changeDadCharacterBetter(250, 460, 'senpai-giddy') changeDadIcon('senpai-glitch') end end function stepHit (step) end
-- CSS + Less + SASS Language Server local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true require'lspconfig'.cssls.setup { capabilities = capabilities, }
commando_house_loot_deed = { minimumLevel = 0, maximumLevel = -1, customObjectName = "Commando Bunker Blueprint", directObjectTemplate = "object/tangible/loot/loot_schematic/commando_house_loot_schem.iff", craftingValues = { }, customizationStringNames = {}, customizationValues = {} } addLootItemTemplate("commando_house_loot_deed", commando_house_loot_deed)
local Native = require('lib.stdlib.native') local converter = require('lib.stdlib.enum.converter') ---@class AbilityIntegerLevelArrayField local AbilityIntegerLevelArrayField = { } return AbilityIntegerLevelArrayField
package.path = "../?.lua;" .. package.path require("tests/mock") local types = require("types") local Placeholder = require("placeholder") describe("Placeholder", function() describe("new_listener", function() it("modifies an environment to return placeholders for missing and new values", function() local temp_env = {} Placeholder.new_listener(temp_env) local name = temp_env.person.name() assert.are.equal("Placeholder", types.get(name)) assert.has_error(function() temp_env.name = "John" end, "libuix->Placeholder.new_listener: attempt to assign value " .. "to key 'name' in access listener") end) end) describe("set", function() it("can assign a value", function() local tbl = {} local key = Placeholder.index("name") Placeholder.set(tbl, key, "John") assert.are.equal(tbl.name, "John") end) it("can assign a sub-level value", function() local tbl = {person = {name = {}}} local key = Placeholder.index("person").name.first Placeholder.set(tbl, key, "John") assert.are.equal(tbl.person.name.first, "John") local bad_key = Placeholder.index("name").first assert.has_error(function() Placeholder.set(tbl, bad_key, "John") end, "libuix->Placeholder.set: attempt to index environment key 'name' (a nil value)") end) it("throws an error if any events other than access and assign are found in the key", function() local env = {name = ""} local key = Placeholder.index("name")() assert.has_error(function() Placeholder.set(env, key, "John") end, "libuix->Placeholder.set: assignment key cannot contain a call event") key = Placeholder.new_index("name") assert.has_no.error(function() Placeholder.set(env, key, "John") end) end) end) describe("evaluate", function() it("can access a top-level value", function() local instance = Placeholder.index("name") local tbl = {name = "John"} assert.are.equal("John", Placeholder.evaluate(tbl, instance)) end) it("can access a sub-level value", function() local instance = Placeholder.index("name").first local tbl = {name = {first = "John"}} assert.are.equal("John", Placeholder.evaluate(tbl, instance)) local bad_key = Placeholder.index("name").last.firstChar assert.has_error(function() Placeholder.evaluate(tbl, bad_key) end, "libuix->Placeholder.evaluate: attempt to index environment key 'firstChar' (a nil value)") instance = Placeholder.index("person").name.first tbl = {person = {name = {first = "John"}}} assert.are.equal("John", Placeholder.evaluate(tbl, instance)) instance = Placeholder.index(1).about.name.first tbl = {{about = {name = {first = "John"}}}} assert.are.equal("John", Placeholder.evaluate(tbl, instance)) end) it("can assign values", function() local tbl = {person = {name = {}}} local name = Placeholder.index("person").name name.first = "John" Placeholder.evaluate(tbl, name) assert.are.equal(tbl.person.name.first, "John") end) it("can call functions with or without self and with or without a custom environment", function() local tbl = { say = { name = "John", hello = function(self, to) return self.name .. " says hello to " .. to .. "!" end }, goodbye = function() return "Goodbye!" end, assign = function() model.message = "Hello!" end } local with_self = Placeholder.index("say"):hello("oct") assert.are.equal("John says hello to oct!", Placeholder.evaluate(tbl, with_self)) local without_self = Placeholder.index("goodbye")() assert.are.equal("Goodbye!", Placeholder.evaluate(tbl, without_self)) local with_placeholder_arg = Placeholder.index("say"):hello(Placeholder.index("say").name) assert.are.equal("John says hello to John!", Placeholder.evaluate(tbl, with_placeholder_arg)) local env = { model = {} } local with_env = Placeholder.index("assign")() Placeholder.evaluate(tbl, with_env, env) assert.are.equal("Hello!", env.model.message) end) it("can return the result of the unary minus operator", function() local tbl = {age = 16} local unm = -Placeholder.index("age") assert.are.equal(-16, Placeholder.evaluate(tbl, unm)) end) it("can return the result of math operations", function() local tbl = {count = 2, incrementor = 2} local add = Placeholder.index("count") + Placeholder.index("incrementor") + 1 assert.are.equal(5, Placeholder.evaluate(tbl, add)) local sub = Placeholder.index("count") - Placeholder.index("incrementor") - 1 assert.are.equal(-1, Placeholder.evaluate(tbl, sub)) local mul = Placeholder.index("count") * (Placeholder.index("incrementor") * 2) assert.are.equal(8, Placeholder.evaluate(tbl, mul)) local div = Placeholder.index("count") / (Placeholder.index("incrementor") / 0.5) assert.are.equal(0.5, Placeholder.evaluate(tbl, div)) local mod = (Placeholder.index("count") + 1) % Placeholder.index("incrementor") assert.are.equal(1, Placeholder.evaluate(tbl, mod)) local pow = Placeholder.index("count") ^ Placeholder.index("incrementor") assert.are.equal(4, Placeholder.evaluate(tbl, pow)) end) it("can return the result of string concatenation", function() local tbl = {one = "Hello"} local concat = Placeholder.index("one") .. " world!" assert.are.equal("Hello world!", Placeholder.evaluate(tbl, concat)) end) it("does not care about order in mathematical operations", function() local tbl = {multiplier = 10} local mul = 2 * Placeholder.index("multiplier") assert.are.equal(20, Placeholder.evaluate(tbl, mul)) end) it("allows function calls to be mixed into mathematical operations", function() local tbl = {start = 5, get_incrementor = function() return 2 end} local add = Placeholder.index("start") + Placeholder.index("get_incrementor")() assert.are.equal(7, Placeholder.evaluate(tbl, add)) end) it("throws an error if an equality check is attempted", function() assert.has_error(function() return Placeholder.index("one") <= Placeholder.index("two") end, "libuix->Placeholder:__le: comparison operators are not allowed, use 'is.le()' instead") assert.has_error(function() return Placeholder.index("one") == Placeholder.index("two") end, "libuix->Placeholder:__eq: comparison operators are not allowed, use 'is.eq()' instead") end) it("throws the correct error message for each event", function() local call = Placeholder.index("one")() assert.has_error(function() Placeholder.evaluate({}, call) end, "libuix->Placeholder.evaluate: attempt to call environment key 'one' (a nil value)") local arithmetic_error_msg = "libuix->Placeholder.evaluate: attempt to perform arithmetic on environment key 'one' " .. "(a nil value)" local unm = -Placeholder.index("one") assert.has_error(function() Placeholder.evaluate({}, unm) end, arithmetic_error_msg) local add = Placeholder.index("one") + Placeholder.index("two") assert.has_error(function() Placeholder.evaluate({}, add) end, arithmetic_error_msg) local sub = Placeholder.index("one") - Placeholder.index("two") assert.has_error(function() Placeholder.evaluate({}, sub) end, arithmetic_error_msg) local mul = Placeholder.index("one") * Placeholder.index("two") assert.has_error(function() Placeholder.evaluate({}, mul) end, arithmetic_error_msg) local div = Placeholder.index("one") / Placeholder.index("two") assert.has_error(function() Placeholder.evaluate({}, div) end, arithmetic_error_msg) local mod = Placeholder.index("one") % Placeholder.index("two") assert.has_error(function() Placeholder.evaluate({}, mod) end, arithmetic_error_msg) local pow = Placeholder.index("one") ^ Placeholder.index("two") assert.has_error(function() Placeholder.evaluate({}, pow) end, arithmetic_error_msg) local concat = Placeholder.index("one") .. Placeholder.index("two") assert.has_error(function() Placeholder.evaluate({}, concat) end, "libuix->Placeholder.evaluate: attempt to concatenate environment key 'one' (a nil value)") end) end) describe("provides custom comparison operator", function() local env = {is = Placeholder.is, one = 28, two = 28, three = 14} it("is.eq (is equal)", function() local eq = Placeholder.index("is").eq(Placeholder.index("one"), Placeholder.index("two")) assert.is_true(Placeholder.evaluate(env, eq)) eq = Placeholder.index("is").eq(Placeholder.index("one"), Placeholder.index("three")) assert.is_false(Placeholder.evaluate(env, eq)) end) it("is.ne (is not equal)", function() local ne = Placeholder.index("is").ne(Placeholder.index("one"), Placeholder.index("three")) assert.is_true(Placeholder.evaluate(env, ne)) ne = Placeholder.index("is").ne(Placeholder.index("one"), Placeholder.index("two")) assert.is_false(Placeholder.evaluate(env, ne)) end) it("is.lt (is less than)", function() local lt = Placeholder.index("is").lt(Placeholder.index("three"), Placeholder.index("two")) assert.is_true(Placeholder.evaluate(env, lt)) lt = Placeholder.index("is").lt(Placeholder.index("one"), Placeholder.index("two")) assert.is_false(Placeholder.evaluate(env, lt)) end) it("is.gt (is greater than)", function() local gt = Placeholder.index("is").gt(Placeholder.index("two"), Placeholder.index("three")) assert.is_true(Placeholder.evaluate(env, gt)) gt = Placeholder.index("is").gt(Placeholder.index("three"), Placeholder.index("two")) assert.is_false(Placeholder.evaluate(env, gt)) end) it("is.le (is less than or equal)", function() local le = Placeholder.index("is").le(Placeholder.index("one"), Placeholder.index("two")) assert.is_true(Placeholder.evaluate(env, le)) le = Placeholder.index("is").le(Placeholder.index("three"), Placeholder.index("two")) assert.is_true(Placeholder.evaluate(env, le)) le = Placeholder.index("is").le(Placeholder.index("two"), Placeholder.index("three")) assert.is_false(Placeholder.evaluate(env, le)) end) it("is.ge (is greater than or equal)", function() local ge = Placeholder.index("is").ge(Placeholder.index("one"), Placeholder.index("two")) assert.is_true(Placeholder.evaluate(env, ge)) ge = Placeholder.index("is").ge(Placeholder.index("two"), Placeholder.index("three")) assert.is_true(Placeholder.evaluate(env, ge)) ge = Placeholder.index("is").ge(Placeholder.index("three"), Placeholder.index("two")) assert.is_false(Placeholder.evaluate(env, ge)) end) end) describe("provides custom logical operator", function() local env = {logical = Placeholder.logical, one = true, two = false} it("logical.l_and (logical and)", function() local l_and = Placeholder.index("logical").l_and(Placeholder.index("one"), true) assert.is_true(Placeholder.evaluate(env, l_and)) l_and = Placeholder.index("logical").l_and(Placeholder.index("one"), Placeholder.index("two")) assert.is_false(Placeholder.evaluate(env, l_and)) end) it("logical.l_or (logical or)", function() local l_or = Placeholder.index("logical").l_or(Placeholder.index("one"), false) assert.is_true(Placeholder.evaluate(env, l_or)) l_or = Placeholder.index("logical").l_or(false, Placeholder.index("two")) assert.is_false(Placeholder.evaluate(env, l_or)) end) it("logical.l_not (logical not)", function() local l_not = Placeholder.index("logical").l_not(Placeholder.index("two")) assert.is_true(Placeholder.evaluate(env, l_not)) l_not = Placeholder.index("logical").l_not(Placeholder.index("one")) assert.is_false(Placeholder.evaluate(env, l_not)) end) end) end)
local eq = assert.are.same local status = require'neogit.status' local harness = require'tests.git_harness' local in_prepared_repo = harness.in_prepared_repo local get_git_status = harness.get_git_status local get_git_diff = harness.get_git_diff local function act(normal_cmd) vim.cmd('normal '..normal_cmd) status.wait_on_current_operation() end describe('status buffer', function () describe('staging files - s', function () it('can stage an untracked file under the cursor', in_prepared_repo(function () vim.fn.setpos('.', {0, 5, 1, 0}) act('s') status.wait_on_current_operation() local result = get_git_status('untracked.txt') eq('A untracked.txt\n', result) end)) it('can stage a tracked file under the cursor', in_prepared_repo(function () vim.fn.setpos('.', {0, 8, 1, 0}) act('s') status.wait_on_current_operation() local result = get_git_status('a.txt') eq('M a.txt\n', result) end)) it('can stage a hunk under the cursor of a tracked file', in_prepared_repo(function () vim.fn.setpos('.', {0, 8, 1, 0}) act('zajjs') status.wait_on_current_operation() eq('MM a.txt\n', get_git_status('a.txt')) eq([[--- a/a.txt +++ b/a.txt @@ -1,5 +1,5 @@ This is a text file under version control. -It exists so it can be manipulated by the test suite. +This is a change made to a tracked file. Here are some lines we can change during the tests. ]], get_git_diff('a.txt', '--cached')) end)) it('can stage a subsequent hunk under the cursor of a tracked file', in_prepared_repo(function () vim.fn.setpos('.', {0, 8, 1, 0}) act('za8js') status.wait_on_current_operation() eq('MM a.txt\n', get_git_status('a.txt')) eq([[--- a/a.txt +++ b/a.txt @@ -7,4 +7,5 @@ Here are some lines we can change during the tests. This is a second block of text to create a second hunk. It also has some line we can manipulate. +Adding a new line right here! Here is some more. ]], get_git_diff('a.txt', '--cached')) end)) it('can stage from a selection in a hunk', in_prepared_repo(function () vim.fn.setpos('.', {0, 8, 1, 0}) act('zajjjjVs') status.wait_on_current_operation() eq('MM a.txt\n', get_git_status('a.txt')) eq([[--- a/a.txt +++ b/a.txt @@ -1,5 +1,6 @@ This is a text file under version control. It exists so it can be manipulated by the test suite. +This is a change made to a tracked file. Here are some lines we can change during the tests. ]], get_git_diff('a.txt', '--cached')) end)) end) describe('unstaging files - u', function () it('can unstage a staged file under the cursor', in_prepared_repo(function () vim.fn.setpos('.', {0, 24, 1, 0}) act('u') status.wait_on_current_operation() local result = get_git_status('b.txt') eq(' M b.txt\n', result) end)) it('can unstage a hunk under the cursor of a staged file', in_prepared_repo(function () vim.fn.setpos('.', {0, 24, 1, 0}) act('zajju') status.wait_on_current_operation() eq('MM b.txt\n', get_git_status('b.txt')) eq([[--- a/b.txt +++ b/b.txt @@ -7,3 +7,4 @@ This way, unstaging staged changes can be tested. Some more lines down here to force a second hunk. I can't think of anything else. Duh. +And here as well ]], get_git_diff('b.txt', '--cached')) end)) it('can unstage from a selection in a hunk', in_prepared_repo(function () vim.fn.setpos('.', {0, 24, 1, 0}) act('zajjjjVu') status.wait_on_current_operation() eq('MM b.txt\n', get_git_status('b.txt')) eq([[--- a/b.txt +++ b/b.txt @@ -1,4 +1,5 @@ This is another test file. +Changes here! This way, unstaging staged changes can be tested. ]], get_git_diff('b.txt')) end)) it('can unstage a subsequent hunk from a staged file', in_prepared_repo(function () vim.fn.setpos('.', {0, 24, 1, 0}) act('za8ju') status.wait_on_current_operation() eq('MM b.txt\n', get_git_status('b.txt')) eq([[--- a/b.txt +++ b/b.txt @@ -7,3 +7,4 @@ This way, unstaging staged changes can be tested. Some more lines down here to force a second hunk. I can't think of anything else. Duh. +And here as well ]], get_git_diff('b.txt')) end)) end) end)
--=========== Copyright © 2019, Planimeter, All rights reserved. ===========-- -- -- Purpose: Frame Tab class -- --==========================================================================-- class "gui.frametab" ( "gui.radiobutton" ) local frametab = gui.frametab function frametab:frametab( parent, name, text ) gui.radiobutton.radiobutton( self, parent, name, text ) self:setDisplay( "inline-block" ) self:setPadding( 22 ) self.text:set( text ) self.width = nil self.height = nil end function frametab:draw() self:drawBackground() self:drawText() gui.box.draw( self ) end function frametab:drawBackground() local color = self:getScheme( "frametab.backgroundColor" ) local mouseover = self.mouseover or self:isChildMousedOver() local width = self:getWidth() local height = self:getHeight() if ( self:isSelected() ) then color = self:getScheme( "frametab.selected.backgroundColor" ) elseif ( mouseover ) then gui.panel.drawBackground( self, color ) color = self:getScheme( "frametab.mouseover.backgroundColor" ) end love.graphics.setColor( color ) local selected = mouseover or self:isSelected() mouseover = mouseover and not self:isSelected() love.graphics.rectangle( "fill", 0, 0, width - ( selected and 1 or 0 ), height - ( mouseover and 1 or 0 ) ) local lineWidth = 1 if ( selected ) then love.graphics.setColor( self:getScheme( "frametab.backgroundColor" ) ) love.graphics.setLineStyle( "rough" ) love.graphics.setLineWidth( lineWidth ) love.graphics.line( width - lineWidth / 2, 0, -- Top-left width - lineWidth / 2, height -- Bottom-left ) end selected = self:isSelected() love.graphics.setColor( self:getScheme( "frametab.borderColor" ) ) love.graphics.setLineStyle( "rough" ) love.graphics.setLineWidth( lineWidth ) love.graphics.line( width - lineWidth / 2, 0, width - lineWidth / 2, height - ( selected and 0 or 1 ) ) if ( not selected ) then love.graphics.line( 0, height - lineWidth / 2, -- Top-right width, height - lineWidth / 2 -- Bottom-right ) end end function frametab:mousepressed( x, y, button, istouch ) if ( ( self.mouseover or self:isChildMousedOver() ) and button == 1 ) then self.mousedown = true if ( not self:isDisabled() ) then local frametabgroup = self:getGroup() if ( frametabgroup ) then frametabgroup:setSelectedId( self.id ) self:onClick() end end end self:invalidate() end function frametab:mousereleased( x, y, button, istouch ) self.mousedown = false self:invalidate() end
-- Server Objects includeFile("custom_content/tangible/event_perk/empire_day_defaced_recruitment_sign.lua") includeFile("custom_content/tangible/event_perk/empire_day_missing_sign.lua") includeFile("custom_content/tangible/event_perk/empire_day_player_defaced_recruitment_sign.lua") includeFile("custom_content/tangible/event_perk/empire_day_player_placed_recruitment_sign.lua") includeFile("custom_content/tangible/event_perk/empire_day_recruitment_sign.lua") includeFile("custom_content/tangible/event_perk/frn_all_gaming_kiosk_s01.lua") includeFile("custom_content/tangible/event_perk/frn_hologram_data_disk_s01.lua") includeFile("custom_content/tangible/event_perk/frn_hologram_data_disk_s02.lua") includeFile("custom_content/tangible/event_perk/frn_loyalty_award_plaque_gold.lua") includeFile("custom_content/tangible/event_perk/frn_loyalty_award_plaque_silver.lua") includeFile("custom_content/tangible/event_perk/frn_tato_fruit_stand_small_style_01.lua") includeFile("custom_content/tangible/event_perk/frn_tato_meat_rack.lua") includeFile("custom_content/tangible/event_perk/gmf_crafted_bat_pheromone.lua") includeFile("custom_content/tangible/event_perk/gmf_crafted_spider_pheromone.lua") includeFile("custom_content/tangible/event_perk/gravestone02.lua") includeFile("custom_content/tangible/event_perk/halloween_bat_pheromone.lua") includeFile("custom_content/tangible/event_perk/halloween_coin.lua") includeFile("custom_content/tangible/event_perk/halloween_krayt_dragon_skeleton.lua") includeFile("custom_content/tangible/event_perk/halloween_painting.lua") includeFile("custom_content/tangible/event_perk/halloween_sith_o_lantern_01.lua") includeFile("custom_content/tangible/event_perk/halloween_sith_o_lantern_02.lua") includeFile("custom_content/tangible/event_perk/halloween_sith_o_lantern_03.lua") includeFile("custom_content/tangible/event_perk/halloween_sith_o_lantern_04.lua") includeFile("custom_content/tangible/event_perk/halloween_sith_o_lantern_05.lua") includeFile("custom_content/tangible/event_perk/halloween_skull_candle_01.lua") includeFile("custom_content/tangible/event_perk/halloween_skull_candle_02.lua") includeFile("custom_content/tangible/event_perk/halloween_song_book.lua") includeFile("custom_content/tangible/event_perk/halloween_spider_pheromone.lua") includeFile("custom_content/tangible/event_perk/halloween_spider_web_01.lua") includeFile("custom_content/tangible/event_perk/halloween_spider_web_02.lua") includeFile("custom_content/tangible/event_perk/halloween_spider_web_03.lua") includeFile("custom_content/tangible/event_perk/life_day_presents.lua") includeFile("custom_content/tangible/event_perk/life_day_tree.lua") includeFile("custom_content/tangible/event_perk/life_day_tree_dressed.lua") includeFile("custom_content/tangible/event_perk/lifeday_holo_table.lua") includeFile("custom_content/tangible/event_perk/lifeday_imperial_gcw_disk.lua") includeFile("custom_content/tangible/event_perk/lifeday_imperial_token.lua") includeFile("custom_content/tangible/event_perk/lifeday_monkey_cage.lua") includeFile("custom_content/tangible/event_perk/lifeday_painting.lua") includeFile("custom_content/tangible/event_perk/lifeday_pocket_aquarium.lua") includeFile("custom_content/tangible/event_perk/lifeday_rebel_gcw_disk.lua") includeFile("custom_content/tangible/event_perk/lifeday_rebel_token.lua") includeFile("custom_content/tangible/event_perk/remembrance_day_defaced_sign.lua") includeFile("custom_content/tangible/event_perk/remembrance_day_missing_sign.lua") includeFile("custom_content/tangible/event_perk/remembrance_day_player_defaced_sign.lua") includeFile("custom_content/tangible/event_perk/remembrance_day_player_resistance_sign.lua") includeFile("custom_content/tangible/event_perk/remembrance_day_resistance_sign.lua") includeFile("custom_content/tangible/event_perk/vehicle_deed_stap_speeder.lua")
messages = {} messages[2] = {bayld=7368, ease=7360, fail=7285, full=7283, notes=7367, points=7365, standing=7366, success=6388} messages[4] = {bayld=7362, ease=7354, fail=7279, full=7277, notes=7361, points=7359, standing=7360, success=6388} messages[5] = {bayld=7319, ease=7311, fail=7236, full=7234, notes=7318, points=7316, standing=7317, success=6401} messages[7] = {bayld=7313, ease=7305, fail=7230, full=7228, notes=7312, points=7310, standing=7311, success=6388} messages[24] = {bayld=7649, ease=7641, fail=7566, full=7564, notes=7648, points=7646, standing=7647, success=6388} messages[25] = {bayld=7169, ease=7161, fail=7086, full=7084, notes=7168, points=7166, standing=7167, success=6388} messages[51] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[52] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[61] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[79] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[81] = {bayld=7828, ease=7820, fail=7745, full=7743, notes=7827, points=7825, standing=7826, success=6388} messages[82] = {bayld=7460, ease=7452, fail=7377, full=7375, notes=7459, points=7457, standing=7458, success=6388} messages[83] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[84] = {bayld=7167, ease=7159, fail=7084, full=7082, notes=7166, points=7164, standing=7165, success=6388} messages[88] = {bayld=7453, ease=7445, fail=7370, full=7368, notes=7452, points=7450, standing=7451, success=6388} messages[89] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[90] = {bayld=7244, ease=7236, fail=7161, full=7159, notes=7243, points=7241, standing=7242, success=6388} messages[91] = {bayld=7167, ease=7159, fail=7084, full=7082, notes=7166, points=7164, standing=7165, success=6388} messages[95] = {bayld=7174, ease=7166, fail=7091, full=7089, notes=7173, points=7171, standing=7172, success=6388} messages[96] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[97] = {bayld=7705, ease=7697, fail=7622, full=7620, notes=7704, points=7702, standing=7703, success=6388} messages[98] = {bayld=7705, ease=7697, fail=7622, full=7620, notes=7704, points=7702, standing=7703, success=6388} messages[100] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6410} messages[101] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6410} messages[102] = {bayld=7310, ease=7302, fail=7227, full=7225, notes=7309, points=7307, standing=7308, success=6388} messages[103] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6410} messages[104] = {bayld=7802, ease=7794, fail=7719, full=7717, notes=7801, points=7799, standing=7800, success=6410} messages[105] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6410} messages[106] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6569} messages[107] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6410} messages[108] = {bayld=7310, ease=7302, fail=7227, full=7225, notes=7309, points=7307, standing=7308, success=6388} messages[109] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6410} messages[110] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6410} messages[111] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6569} messages[112] = {bayld=7345, ease=7337, fail=7262, full=7260, notes=7344, points=7342, standing=7343, success=6401} messages[113] = {bayld=7648, ease=7640, fail=7565, full=7563, notes=7647, points=7645, standing=7646, success=6388} messages[114] = {bayld=7648, ease=7640, fail=7565, full=7563, notes=7647, points=7645, standing=7646, success=6388} messages[115] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[116] = {bayld=7306, ease=7298, fail=7223, full=7221, notes=7305, points=7303, standing=7304, success=6388} messages[117] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6569} messages[118] = {bayld=7347, ease=7339, fail=7264, full=7262, notes=7346, points=7344, standing=7345, success=6423} messages[119] = {bayld=7328, ease=7320, fail=7245, full=7243, notes=7327, points=7325, standing=7326, success=6410} messages[120] = {bayld=7336, ease=7328, fail=7253, full=7251, notes=7335, points=7333, standing=7334, success=6410} messages[121] = {bayld=7648, ease=7640, fail=7565, full=7563, notes=7647, points=7645, standing=7646, success=6388} messages[122] = {bayld=7306, ease=7298, fail=7223, full=7221, notes=7305, points=7303, standing=7304, success=6388} messages[123] = {bayld=7648, ease=7640, fail=7565, full=7563, notes=7647, points=7645, standing=7646, success=6388} messages[124] = {bayld=7648, ease=7640, fail=7565, full=7563, notes=7647, points=7645, standing=7646, success=6388} messages[125] = {bayld=7306, ease=7298, fail=7223, full=7221, notes=7305, points=7303, standing=7304, success=6388} messages[126] = {bayld=7306, ease=7298, fail=7223, full=7221, notes=7305, points=7303, standing=7304, success=6388} messages[127] = {bayld=7306, ease=7298, fail=7223, full=7221, notes=7305, points=7303, standing=7304, success=6388} messages[128] = {bayld=7306, ease=7298, fail=7223, full=7221, notes=7305, points=7303, standing=7304, success=6388} messages[136] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[137] = {bayld=7669, ease=7661, fail=7586, full=7584, notes=7668, points=7666, standing=7667, success=6388} messages[260] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[261] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[262] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[263] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[265] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[266] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388} messages[267] = {bayld=7147, ease=7139, fail=7064, full=7062, notes=7146, points=7144, standing=7145, success=6388}
addEventHandler("onClientResourceStart",resourceRoot, function () SKIN_ID=277 txd = engineLoadTXD ( "277.txd" ) engineImportTXD ( txd, SKIN_ID ) dff = engineLoadDFF ( "277.dff", SKIN_ID ) engineReplaceModel ( dff, SKIN_ID ) end)
-- Server only if not Server then return end Script.Load("lua/bots/Bot.lua") kHallucinationModifyHealFactor = 0 PlayerHallucinationMixin = CreateMixin(PlayerHallucinationMixin) PlayerHallucinationMixin.type = "PlayerHallucination" PlayerHallucinationMixin.overrideFunctions = { "GetIsAllowedToBuy", } function PlayerHallucinationMixin:ModifyHealingDone(health) return 0 end function PlayerHallucinationMixin:GetIsAllowedToBuy() return false end function PlayerHallucinationMixin:ComputeDamageAttackerOverrideMixin(attacker, damage, damageType, doer, hitPoint) return 0 end function PlayerHallucinationMixin:ModifyDamageTaken(damageTable, attacker, doer, damageType, hitPoint) local multiplier = 8 if self:isa("Skulk") then multiplier = 6 elseif self:isa("Fade") then multiplier = 12 elseif self:isa("Onos") then multiplier = 16 end damageTable.damage = damageTable.damage * multiplier end function PlayerHallucinationMixin:OnUpdate(deltaTime) if not self:GetIsAlive() then return end -- generate moves for the hallucination server side if not self.brain then if self:isa("Skulk") then self.brain = SkulkBrain() elseif self:isa("Gorge") then self.brain = GorgeBrain() elseif self:isa("Lerk") then self.brain = LerkBrain() elseif self:isa("Fade") then self.brain = FadeBrain() elseif self:isa("Onos") then self.brain = OnosBrain() end self.brain:Initialize() end local move = Move() self:GetMotion():SetDesiredViewTarget(nil) self.brain:Update(self, move) local viewDir, moveDir, doJump = self:GetMotion():OnGenerateMove(self) move.yaw = GetYawFromVector(viewDir) - self:GetBaseViewAngles().yaw move.pitch = GetPitchFromVector(viewDir) moveDir.y = 0 moveDir = moveDir:GetUnit() local zAxis = Vector(viewDir.x, 0, viewDir.z):GetUnit() local xAxis = zAxis:CrossProduct(Vector(0, -1, 0)) local moveX = moveDir:DotProduct(xAxis) local moveZ = moveDir:DotProduct(zAxis) if moveX ~= 0 then moveX = GetSign(moveX) end if moveZ ~= 0 then moveZ = GetSign(moveZ) end move.move = Vector(moveX, 0, moveZ) if doJump then move.commands = AddMoveCommand(move.commands, Move.Jump) end move.time = deltaTime -- do with that move now what a real player would do self:OnProcessMove(move) UpdateHallucinationLifeTime(self) end function PlayerHallucinationMixin:GetPlayer() return self end function PlayerHallucinationMixin:ModifyHeal(healTable) healTable.health = healTable.health * kHallucinationModifyHealFactor end function PlayerHallucinationMixin:GetHealthPerBioMass() return 0 end local kBabblerAttachPoints = CompMod:GetLocalVariable(BabblerClingMixin.GetCanAttachBabbler, "kBabblerAttachPoints") function BabblerClingMixin:GetCanAttachBabbler() if not self.isHallucination then local numClingedBabbler = self:GetNumClingedBabblers() local numAttachPoints = #kBabblerAttachPoints return numClingedBabbler < numAttachPoints end return false end local kMaxShield = kMucousShieldMaxAmount function MucousableMixin:GetMaxShieldAmount() local targetMaxShield = kMaxShield if self.isHallucination then targetMaxShield = 0 end return math.floor(math.min(self:GetBaseHealth() * kMucousShieldPercent, targetMaxShield)) end --Copy for the botbrain essential methods from the playerbot metatable PlayerHallucinationMixin.GetMotion = PlayerBot.GetMotion PlayerHallucinationMixin.GetPlayerOrder = PlayerBot.GetPlayerOrder PlayerHallucinationMixin.GivePlayerOrder = PlayerBot.GivePlayerOrder PlayerHallucinationMixin.GetPlayerHasOrder = PlayerBot.GetPlayerHasOrder PlayerHallucinationMixin.GetBotCanSeeTarget = PlayerBot.GetBotCanSeeTarget
require("../utils") Log = {} function Log:new(xLabel,yLabel) -- Initialise the instance local result = {} result.data = {} result.xLabel = xLabel or "x" result.yLabel = yLabel or "y" -- Do Lua class stuff setmetatable(result,self) self.__index = self -- Return the new instance return result end function Log:log(x,y) if(self.data[x] == nil) then self.data[x] = {}; end table.insert(self.data[x],y) end function Log:get_labels() return self.xLabel, self.yLabel, self.yLabel .. "_stddev" end function Log:get_data() result = {} for x,ys in pairs(self.data) do result[x] = {} result[x].average = mean(ys) result[x].stddev = stddev(ys) end return result end
local OS_ID = os.get() local QT_MAC_BASE_PATH = "/Applications/Qt5.7.0/5.7/clang_64" local QT_MAC_LIB_BASE_PATH = QT_MAC_BASE_PATH.."/lib" local MAC_EMBEDDED_HELPER_PATH = "bin/%{cfg.buildcfg}/Asset Pipeline.app/Contents/Resources/Asset Pipeline Helper.app" function EscapeSpacesInPath(path) -- TODO: Make sure that this function works on Windows. return path:gsub(" ", "\\ ") end function GetCommandMkdirRecursive(path) if OS_ID == "macosx" then return string.format('mkdir -p "%s"', path) end end function GetQtLibPath(name) if OS_ID == "macosx" then return QT_MAC_LIB_BASE_PATH.."/"..name..".framework" end end function GetQtHeadersPath(name) if OS_ID == "macosx" then return GetQtLibPath(name).."/Headers" end end function GetQtRccCommand(input, output) if OS_ID == "macosx" then local rccPath = QT_MAC_BASE_PATH.."/bin/rcc" return string.format("%s %s -o %s", rccPath, input, output) end end function GetQtMocCommand(input, output) if OS_ID == "macosx" then local mocPath = QT_MAC_BASE_PATH.."/bin/moc" local escapedInput = EscapeSpacesInPath(input) local escapedOutput = EscapeSpacesInPath(output) -- This checks file modification timestamps, before running the moc -- (and so only runs the moc when the header has actually changed). return string.format( 'if ["$(stat -f \\"%%m\\" %s)" -ne "$(stat -f \\"%%m\\" %s)"]; then '.. '%s %s -o %s; '.. 'fi', escapedInput, escapedOutput, mocPath, escapedInput, escapedOutput ) end end function GetQtMocOutputPath(projName, file) local index, _, name = string.find(file, "([^/]*)%.h$") local path = string.sub(file, 1, index - 1) return projName.."/generated/moc/"..path.."moc_"..name..".cpp" end function GetQtMocOutputFilePaths(projName, files) local result = {} for _, file in ipairs(files) do result[#result+1] = GetQtMocOutputPath(projName, file) end return result end function GetQtMocCommands(projName, files) local result = {} for _, file in ipairs(files) do local input = projName.."/Source/"..file local output = GetQtMocOutputPath(projName, file) result[#result+1] = GetQtMocCommand(input, output) end return result end HELPER_MOC_INPUT_FILES = { "ProjectsWindow.h", "HelperApp.h", "AddProjectWindow.h", "AboutWindow.h", "ErrorsWindow.h", } MAINAPP_MOC_INPUT_FILES = { "SystemTrayApp.h", } QT_LIBS = { "QtCore", "QtGui", "QtWidgets", "QtNetwork", } workspace "AssetPipeline" configurations { "Debug", "Release" } platforms { "OSX" } project("Common") kind "StaticLib" language "C++" targetdir("bin/%{cfg.buildcfg}") files { "Common/Source/**.h", "Common/Source/**.c", "Common/Source/**.cpp" } includedirs "Common/Source" includedirs "Common/Source/lua/src" includedirs "Common/Source/lua/etc" filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On" filter "platforms:OSX" files { "Common/Source/**.m", "Common/Source/**.mm" } architecture "x64" links { "Cocoa.framework", } xcodebuildsettings { ["MACOSX_DEPLOYMENT_TARGET"] = "10.11", ["CLANG_ENABLE_OBJC_ARC"] = "YES", ["OTHER_CPLUSPLUSFLAGS"] = "-std=c++14", } project("Asset Pipeline Helper") kind "WindowedApp" language "C++" targetdir("bin/%{cfg.buildcfg}") files { "Helper/Source/**.h", "Helper/Source/**.c", "Helper/Source/**.cpp", "Helper/generated/QtResources.cpp", } files(GetQtMocOutputFilePaths("Helper", HELPER_MOC_INPUT_FILES)) prebuildcommands(GetCommandMkdirRecursive("Helper/generated/moc")) prebuildcommands(GetQtMocCommands("Helper", HELPER_MOC_INPUT_FILES)) prebuildcommands(GetQtRccCommand("Helper/Resources.qrc", "Helper/generated/QtResources.cpp")) links { "Common" } for _, lib in ipairs(QT_LIBS) do links(GetQtLibPath(lib)) end includedirs "Helper/Source" includedirs "Common/Source" for _, lib in ipairs(QT_LIBS) do includedirs(GetQtHeadersPath(lib)) end filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On" filter "platforms:OSX" files { "Helper/Source/**.m", "Helper/Source/**.mm", "Helper/Mac/**.strings", "Helper/Mac/Info.plist" } architecture "x64" links { "Cocoa.framework", } frameworkdirs { QT_MAC_LIB_BASE_PATH } xcodebuildsettings { ["MACOSX_DEPLOYMENT_TARGET"] = "10.11", ["CLANG_ENABLE_OBJC_ARC"] = "YES", ["OTHER_CPLUSPLUSFLAGS"] = "-std=c++14", ["PRODUCT_BUNDLE_IDENTIFIER"] = "com.williamih.assetpipelinehelper", } linkoptions { "-lstdc++" } filter "files:**.plist" buildaction "Resource" filter "files:**.strings" buildaction "Resource" project("Asset Pipeline") kind "WindowedApp" language "C++" targetdir("bin/%{cfg.buildcfg}") files { "MainApp/Source/**.h", "MainApp/Source/**.c", "MainApp/Source/**.cpp", "MainApp/generated/QtResources.cpp", } files(GetQtMocOutputFilePaths("MainApp", MAINAPP_MOC_INPUT_FILES)) dependson { "Asset Pipeline Helper" } prebuildcommands(GetCommandMkdirRecursive("MainApp/generated/moc")) prebuildcommands(GetQtMocCommands("MainApp", MAINAPP_MOC_INPUT_FILES)) prebuildcommands(GetQtRccCommand("MainApp/Resources.qrc", "MainApp/generated/QtResources.cpp")) links { "Common" } includedirs "MainApp/Source" includedirs "Common/Source" for _, lib in ipairs(QT_LIBS) do includedirs(GetQtHeadersPath(lib)) end filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On" filter "platforms:OSX" files { "MainApp/Source/**.m", "MainApp/Source/**.mm", "MainApp/Mac/**.strings", "MainApp/Mac/Info.plist" } architecture "x64" links { "Cocoa.framework", } frameworkdirs { QT_MAC_LIB_BASE_PATH } xcodebuildsettings { ["MACOSX_DEPLOYMENT_TARGET"] = "10.11", ["CLANG_ENABLE_OBJC_ARC"] = "YES", ["OTHER_CPLUSPLUSFLAGS"] = "-std=c++14", -- N.B. NSUserNotificationCenter popup notifications don't work if -- this isn't set! ["PRODUCT_BUNDLE_IDENTIFIER"] = "com.williamih.assetpipeline", } for _, lib in ipairs(QT_LIBS) do xcodeembeddedframeworks(GetQtLibPath(lib)) end linkoptions { "-lstdc++" } postbuildcommands { string.format('ditto "bin/%%{cfg.buildcfg}/Asset Pipeline Helper.app" "%s"', MAC_EMBEDDED_HELPER_PATH), string.format('mkdir -p "%s/Contents/Frameworks"', MAC_EMBEDDED_HELPER_PATH), } postbuildcommands { 'cp -r Scripts/ "bin/%{cfg.buildcfg}/Asset Pipeline.app/Contents/Resources"', } for _, lib in ipairs(QT_LIBS) do postbuildcommands { string.format('rm -f "%s/Contents/Frameworks/%s.framework"', MAC_EMBEDDED_HELPER_PATH, lib), string.format('ln -s ../../../../Frameworks/%s.framework "%s/Contents/Frameworks/%s.framework"', lib, MAC_EMBEDDED_HELPER_PATH, lib), } end filter "files:**.plist" buildaction "Resource" filter "files:**.strings" buildaction "Resource"
-- Copyright 2004-present Facebook. All Rights Reserved. -- Always line-buffer stdout because we want our logs not to be slow, even -- if they are redirected. io.stdout:setvbuf('line') local pl = require('pl.import_into')() local util = require('fb.util') require 'totem' -- Compatibility stuff, LuaJIT in 5.2 compat mode has renamed string.gfind -- to string.gmatch if string.gfind == nil then string.gfind = string.gmatch end -- sys.clock is broken, broken, broken! local sys = require('sys') sys.clock = util.time local timer_start local function tic() timer_start = util.monotonic_clock() end sys.tic = tic local function toc(verbose) local duration = util.monotonic_clock() - timer_start if verbose then print(duration) end return duration end sys.toc = toc -- Load C extension which loads torch and sets up error handlers local torch = require('fbtorch_ext') -- OMP tends to badly hurt performance on our multi-die multi-core NUMA -- machines, so it's off by default. Turn it on with extreme care, and -- benchmark, benchmark, benchmark -- check "user time", not just "wall -- time", since you might be inadvertently wasting a ton of CPU for a -- negligible wall-clock speedup. For context, read this thread: -- https://fb.facebook.com/groups/709562465759038/874071175974832 local env_threads = os.getenv('OMP_NUM_THREADS') if env_threads == nil or env_threads == '' then torch.setnumthreads(1) end if LuaUnit then -- modify torch.Tester and totem.Tester to use our own flavor of LuaUnit torch.Tester._assert_sub = function(self, condition, message) self._assertSubCalled = true if not condition then error(message) end end torch.Tester.run = function(self, run_tests) local tests, testnames tests = self.tests testnames = self.testnames if type(run_tests) == 'string' then run_tests = {run_tests} end if type(run_tests) == 'table' then tests = {} testnames = {} for i,fun in ipairs(self.tests) do for j,name in ipairs(run_tests) do if self.testnames[i] == name then tests[#tests+1] = self.tests[i] testnames[#testnames+1] = self.testnames[i] end end end end -- global TestTorch = {} for name,fun in pairs(tests) do TestTorch['test_' .. name] = fun end -- LuaUnit will run tests (functions whose names start with 'test') -- from all globals whose names start with 'Test' LuaUnit:run() end totem.Tester._assert_sub = torch.Tester._assert_sub totem.Tester._success = function() end totem.Tester._failure = function(message) error(message) end totem.Tester.run = function(self, run_tests) local tests = self.tests if type(run_tests) == 'string' then run_tests = {run_tests} end if type(run_tests) == 'table' then tests = {} for j, name in ipairs(run_tests) do if self.tests[name] then tests[name] = self.tests[name] end end end -- global TestTotem = tests -- LuaUnit will run tests (functions whose names start with 'test') -- from all globals whose names start with 'Test' LuaUnit:run() end end if os.getenv('LUA_DEBUG') then require('fb.debugger').enter() end -- reload: unload a module and re-require it local function reload(mod, ...) package.loaded[mod] = nil return require(mod, ...) end torch.reload = reload return torch
local _, ns = ... local B, C, L, DB, P = unpack(ns) local S = P:GetModule("Skins") ---------------------------- -- Credit: ElvUI ---------------------------- local _G = getfenv(0) local select, pairs, type = select, pairs, type local r, g, b = DB.r, DB.g, DB.b local TT = B:GetModule("Tooltip") S.EarlyAceWidgets = {} function S:Ace3() local AceGUI = LibStub and LibStub('AceGUI-3.0', true) if not AceGUI then return end if not S.db["Ace3"] then return end if AceGUITooltip then AceGUITooltip:HookScript("OnShow", TT.ReskinTooltip) end if AceConfigDialogTooltip then AceConfigDialogTooltip:HookScript("OnShow", TT.ReskinTooltip) end for _, n in next, S.EarlyAceWidgets do if n.SetLayout then S:Ace3_RegisterAsContainer(n) else S:Ace3_RegisterAsWidget(n) end end end S:RegisterSkin("Ace3", S.Ace3) function S:Ace3_SkinDropdown() if self and self.obj then if self.obj.pullout and self.obj.pullout.frame then P.ReskinTooltip(self.obj.pullout.frame) self.obj.pullout.frame.SetBackdrop = B.Dummy elseif self.obj.dropdown then P.ReskinTooltip(self.obj.dropdown) self.obj.dropdown.SetBackdrop = B.Dummy if self.obj.dropdown.slider then B.ReskinSlider(self.obj.dropdown.slider) end end end end function S:Ace3_SkinTab(tab) B.StripTextures(tab) tab.bg = B.CreateBDFrame(tab) tab.bg:SetPoint('TOPLEFT', 8, -3) tab.bg:SetPoint('BOTTOMRIGHT', -8, 0) tab.text:SetPoint("LEFT", 14, -1) tab:HookScript("OnEnter", B.Texture_OnEnter) tab:HookScript("OnLeave", B.Texture_OnLeave) hooksecurefunc(tab, 'SetSelected', function(self, selected) if selected then self.bg:SetBackdropColor(r, g, b, .25) else self.bg:SetBackdropColor(0, 0, 0, .25) end end) end local WeakAuras_RegionType = { ["icon"] = true, ["group"] = true, ["dynamicgroup"] = true, } function S:WeakAuras_SkinIcon(icon) if type(icon) ~= "table" or not icon.icon then return end if WeakAuras_RegionType[self.data.regionType] then icon.icon:SetTexCoord(unpack(DB.TexCoord)) end end function S:WeakAuras_UpdateIcon() if not self.thumbnail or not self.thumbnail.icon then return end if WeakAuras_RegionType[self.data.regionType] then self.thumbnail.icon:SetTexCoord(unpack(DB.TexCoord)) end end function S:Ace3_RegisterAsWidget(widget) local TYPE = widget.type if TYPE == 'MultiLineEditBox' then B.StripTextures(widget.scrollBG) local bg = B.CreateBDFrame(widget.scrollBG, .8) bg:SetPoint("TOPLEFT", 0, -2) bg:SetPoint("BOTTOMRIGHT", -2, 1) B.Reskin(widget.button) B.ReskinScroll(widget.scrollBar) widget.scrollBar:SetPoint('RIGHT', widget.frame, 'RIGHT', 0 -4) widget.scrollBG:SetPoint('TOPRIGHT', widget.scrollBar, 'TOPLEFT', -2, 19) widget.scrollBG:SetPoint('BOTTOMLEFT', widget.button, 'TOPLEFT') widget.scrollFrame:SetPoint('BOTTOMRIGHT', widget.scrollBG, 'BOTTOMRIGHT', -4, 8) elseif TYPE == 'CheckBox' then local check = widget.check local checkbg = widget.checkbg local highlight = widget.highlight local bg = B.CreateBDFrame(checkbg, 0) bg:SetPoint("TOPLEFT", checkbg, "TOPLEFT", 4, -4) bg:SetPoint("BOTTOMRIGHT", checkbg, "BOTTOMRIGHT", -4, 4) B.CreateGradient(bg) bg:SetFrameLevel(bg:GetFrameLevel() + 1) checkbg:SetTexture(nil) checkbg.SetTexture = B.Dummy highlight:SetTexture(DB.bdTex) highlight:SetPoint("TOPLEFT", checkbg, "TOPLEFT", 5, -5) highlight:SetPoint("BOTTOMRIGHT", checkbg, "BOTTOMRIGHT", -5, 5) highlight:SetVertexColor(r, g, b, .25) highlight.SetTexture = B.Dummy check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check") check:SetTexCoord(0, 1, 0, 1) check:SetDesaturated(true) check:SetVertexColor(r, g, b) check.SetDesaturated = B.Dummy hooksecurefunc(widget, 'SetDisabled', function(self, disabled) local check = self.check if disabled then check:SetVertexColor(.8, .8, .8) else check:SetVertexColor(r, g, b) end end) hooksecurefunc(widget, "SetType", function(self, type) if type == "radio" then self.check:SetTexture(DB.bdTex) self.check:SetInside(self.checkbg, 4, 4) else self.check:SetAllPoints(self.checkbg) end end) elseif TYPE == 'Dropdown' or TYPE == 'LQDropdown' then local frame = widget.dropdown local button = widget.button local button_cover = widget.button_cover local text = widget.text B.StripTextures(frame) local bg = B.CreateBDFrame(frame, 0) bg:SetPoint("TOPLEFT", 18, -3) bg:SetPoint("BOTTOMRIGHT", -18, 3) B.CreateGradient(bg) widget.label:ClearAllPoints() widget.label:SetPoint('BOTTOMLEFT', bg, 'TOPLEFT', 2, 0) B.ReskinArrow(button, "down") button:SetSize(20, 20) button:ClearAllPoints() button:SetPoint('RIGHT', bg) text:ClearAllPoints() text:SetJustifyH("RIGHT") text:SetPoint('RIGHT', button, 'LEFT', -3, 0) button:HookScript('OnClick', S.Ace3_SkinDropdown) button_cover:HookScript('OnClick', S.Ace3_SkinDropdown) elseif TYPE == 'LSM30_Font' or TYPE == 'LSM30_Sound' or TYPE == 'LSM30_Border' or TYPE == 'LSM30_Background' or TYPE == 'LSM30_Statusbar' then local frame = widget.frame local button = frame.dropButton local text = frame.text B.StripTextures(frame) local bg = B.CreateBDFrame(frame, 0) bg:SetPoint("TOPLEFT", 3, -22) bg:SetPoint("BOTTOMRIGHT", -1, 2) B.CreateGradient(bg) frame.label:ClearAllPoints() frame.label:SetPoint('BOTTOMLEFT', bg, 'TOPLEFT', 2, 0) B.ReskinArrow(button, "down") button:SetSize(20, 20) button:ClearAllPoints() button:SetPoint('RIGHT', bg) frame.text:ClearAllPoints() frame.text:SetPoint('RIGHT', button, 'LEFT', -2, 0) if TYPE == 'LSM30_Sound' then widget.soundbutton:SetParent(bg) widget.soundbutton:ClearAllPoints() widget.soundbutton:SetPoint('LEFT', bg, 'LEFT', 2, 0) elseif TYPE == 'LSM30_Statusbar' then widget.bar:SetParent(bg) widget.bar:ClearAllPoints() widget.bar:SetPoint('TOPLEFT', bg, 'TOPLEFT', 2, -2) widget.bar:SetPoint('BOTTOMRIGHT', button, 'BOTTOMLEFT', -1, 0) elseif TYPE == 'LSM30_Border' or TYPE == 'LSM30_Background' then bg:SetPoint("TOPLEFT", 45, -22) end button:SetParent(bg) text:SetParent(bg) button:HookScript('OnClick', S.Ace3_SkinDropdown) elseif TYPE == 'EditBox' then B.Reskin(widget.button) P.ReskinInput(widget.editbox) widget.editbox.bg:SetPoint("TOPLEFT", 0, -2) widget.editbox.bg:SetPoint("BOTTOMRIGHT", 0, 2) hooksecurefunc(widget.editbox, "SetPoint", function(self, a, b, c, d, e) if d == 7 then self:SetPoint(a, b, c, 0, e) end end) elseif TYPE == 'Button' or TYPE == 'MacroButton' then B.Reskin(widget.frame) elseif TYPE == 'Slider' then B.ReskinSlider(widget.slider) widget.editbox:SetBackdrop(nil) B.ReskinInput(widget.editbox) widget.editbox:SetPoint('TOP', widget.slider, 'BOTTOM', 0, -1) elseif TYPE == 'Keybinding' then local button = widget.button local msgframe = widget.msgframe B.Reskin(button) B.StripTextures(msgframe) B.SetBD(msgframe) msgframe.msg:ClearAllPoints() msgframe.msg:SetPoint("CENTER") elseif TYPE == 'Icon' then B.StripTextures(widget.frame) elseif TYPE == 'WeakAurasDisplayButton' then local button = widget.frame P.ReskinCollapse(widget.expand) widget.expand:SetPushedTexture("") widget.expand.SetPushedTexture = B.Dummy B.ReskinInput(widget.renamebox) button.group.texture:SetTexture(P.RotationRightTex) widget.icon:ClearAllPoints() widget.icon:SetPoint("LEFT", widget.frame, "LEFT", 1, 0) button.iconBG = B.CreateBDFrame(widget.icon, 0) button.iconBG:SetAllPoints(widget.icon) button.highlight:SetTexture(DB.bdTex) button.highlight:SetVertexColor(DB.r, DB.g, DB.b, .25) button.highlight:SetInside() hooksecurefunc(widget, "SetIcon", S.WeakAuras_SkinIcon) hooksecurefunc(widget, "UpdateThumbnail", S.WeakAuras_UpdateIcon) elseif TYPE == 'WeakAurasNewButton' then local button = widget.frame widget.icon:SetTexCoord(unpack(DB.TexCoord)) widget.icon:ClearAllPoints() widget.icon:SetPoint("LEFT", widget.frame, "LEFT", 1, 0) button.iconBG = B.CreateBDFrame(widget.icon, 0) button.iconBG:SetAllPoints(widget.icon) button.highlight:SetTexture(DB.bdTex) button.highlight:SetVertexColor(DB.r, DB.g, DB.b, .25) button.highlight:SetInside() elseif TYPE == 'WeakAurasMultiLineEditBox' then B.StripTextures(widget.scrollBG) local bg = B.CreateBDFrame(widget.scrollBG, .8) bg:SetPoint("TOPLEFT", 0, -2) bg:SetPoint("BOTTOMRIGHT", -2, 1) B.Reskin(widget.button) B.ReskinScroll(widget.scrollBar) widget.scrollBar:SetPoint('RIGHT', widget.frame, 'RIGHT', 0 -4) widget.scrollBG:SetPoint('TOPRIGHT', widget.scrollBar, 'TOPLEFT', -2, 19) widget.scrollBG:SetPoint('BOTTOMLEFT', widget.button, 'TOPLEFT') widget.scrollFrame:SetPoint('BOTTOMRIGHT', widget.scrollBG, 'BOTTOMRIGHT', -4, 8) widget.frame:HookScript("OnShow", function() if widget.extraButtons then for _, button in next, widget.extraButtons do if not button.styled then B.Reskin(button) button.styled = true end end end end) elseif TYPE == 'WeakAurasLoadedHeaderButton' then P.ReskinCollapse(widget.expand) widget.expand:SetPushedTexture("") widget.expand.SetPushedTexture = B.Dummy elseif TYPE == 'WeakAurasIconButton' then local bg = B.ReskinIcon(widget.texture) bg:SetBackdropColor(0, 0, 0, 0) local hl = widget.frame:GetHighlightTexture() hl:SetColorTexture(1, 1, 1, .25) hl:SetAllPoints() elseif TYPE == 'WeakAurasTextureButton' then local button = widget.frame B.CreateBD(button, .25) button:SetHighlightTexture(DB.bdTex) local hl = button:GetHighlightTexture() hl:SetVertexColor(DB.r, DB.g, DB.b, .25) hl:SetInside() end end function S:Ace3_RegisterAsContainer(widget) local TYPE = widget.type if TYPE == 'ScrollFrame' then B.ReskinScroll(widget.scrollbar) widget.scrollbar:DisableDrawLayer("BACKGROUND") elseif TYPE == 'InlineGroup' or TYPE == 'TreeGroup' or TYPE == 'TabGroup' or TYPE == 'Frame' or TYPE == 'DropdownGroup' or TYPE == "Window" or TYPE == "WeakAurasTreeGroup" then local frame = widget.content:GetParent() B.StripTextures(frame) if TYPE == 'Frame' then for i = 1, frame:GetNumChildren() do local child = select(i, frame:GetChildren()) if child:GetObjectType() == 'Button' and child:GetText() then B.Reskin(child) else B.StripTextures(child) end end B.SetBD(frame) else frame.bg = B.CreateBDFrame(frame, .25) frame.bg:SetPoint("TOPLEFT", 2, -2) frame.bg:SetPoint("BOTTOMRIGHT", -2, 2) end if TYPE == "Window" then B.ReskinClose(frame.obj.closebutton) end if widget.treeframe then local bg = B.CreateBDFrame(widget.treeframe, .25) bg:SetPoint("TOPLEFT", 2, -2) bg:SetPoint("BOTTOMRIGHT", -2, 2) local oldRefreshTree = widget.RefreshTree widget.RefreshTree = function(self, scrollToSelection) oldRefreshTree(self, scrollToSelection) if not self.tree then return end local status = self.status or self.localstatus local lines = self.lines local buttons = self.buttons local offset = status.scrollvalue for i = offset + 1, #lines do local button = buttons[i - offset] if button and not button.styled then local toggle = button.toggle P.ReskinCollapse(toggle) toggle.SetPushedTexture = B.Dummy button.styled = true end end end end if TYPE == 'TabGroup' then local oldCreateTab = widget.CreateTab widget.CreateTab = function(self, id) local tab = oldCreateTab(self, id) S:Ace3_SkinTab(tab) return tab end end if widget.scrollbar then B.ReskinScroll(widget.scrollbar) widget.scrollbar:DisableDrawLayer("BACKGROUND") end if TYPE == "WeakAurasTreeGroup" then local treeframe = widget.treeframe local treeframeBG = treeframe:GetChildren() treeframeBG:SetAlpha(0) end end end function S:Ace3_MetaTable(lib) local t = getmetatable(lib) if t then t.__newindex = S.Ace3_MetaIndex else setmetatable(lib, {__newindex = S.Ace3_MetaIndex}) end end function S:Ace3_MetaIndex(k, v) if k == 'RegisterAsContainer' then rawset(self, k, function(s, w, ...) if S.db["Ace3"] then S.Ace3_RegisterAsContainer(s, w, ...) end return v(s, w, ...) end) elseif k == 'RegisterAsWidget' then rawset(self, k, function(...) if S.db["Ace3"] then S.Ace3_RegisterAsWidget(...) end return v(...) end) else rawset(self, k, v) end end -- versions of AceGUI and AceConfigDialog. local minorGUI, minorConfigDialog = 36, 76 local lastMinor = 0 function S:HookAce3(lib, minor, earlyLoad) -- lib: AceGUI if not lib or (not minor or minor < minorGUI) then return end local earlyContainer, earlyWidget local oldMinor = lastMinor if lastMinor < minor then lastMinor = minor end if earlyLoad then earlyContainer = lib.RegisterAsContainer earlyWidget = lib.RegisterAsWidget end if earlyLoad or oldMinor ~= minor then lib.RegisterAsContainer = nil lib.RegisterAsWidget = nil end if not lib.RegisterAsWidget then S:Ace3_MetaTable(lib) end if earlyContainer then lib.RegisterAsContainer = earlyContainer end if earlyWidget then lib.RegisterAsWidget = earlyWidget end end do -- Early Skin Loading local Libraries = { ['AceGUI'] = true, } local LibStub = _G.LibStub if not LibStub then return end local numEnding = '%-[%d%.]+$' function S:LibStub_NewLib(major, minor) local earlyLoad = major == 'ElvUI' if earlyLoad then major = minor end local n = gsub(major, numEnding, '') if Libraries[n] then if n == 'AceGUI' then S:HookAce3(LibStub.libs[major], LibStub.minors[major], earlyLoad) end end end local findWidget local function earlyWidget(y) if y.children then findWidget(y.children) end if y.frame and (y.base and y.base.Release) then tinsert(S.EarlyAceWidgets, y) end end findWidget = function(x) for _, y in ipairs(x) do earlyWidget(y) end end for n in next, LibStub.libs do if n == 'AceGUI-3.0' then for _, x in ipairs({_G.UIParent:GetChildren()}) do if x and x.obj then earlyWidget(x.obj) end end end if Libraries[gsub(n, numEnding, '')] then S:LibStub_NewLib('ElvUI', n) end end hooksecurefunc(LibStub, 'NewLibrary', S.LibStub_NewLib) end
require 'torch' require 'optim' require 'image' require 'fast_neural_style.DataLoader' require 'fast_neural_style.PerceptualCriterion' local utils = require 'fast_neural_style.utils' local preprocess = require 'fast_neural_style.preprocess' local models = require 'fast_neural_style.models' local cmd = torch.CmdLine() --[[ Train a feedforward style transfer model --]] -- Generic options cmd:option('-arch', 'c9s1-32,d64,d128,R128,R128,R128,R128,R128,u64,u32,c9s1-3') cmd:option('-use_instance_norm', 1) cmd:option('-task', 'style', 'style|upsample') cmd:option('-h5_file', 'data/ms-coco-256.h5') cmd:option('-padding_type', 'reflect-start') cmd:option('-tanh_constant', 150) cmd:option('-preprocessing', 'vgg') cmd:option('-resume_from_checkpoint', '') -- Generic loss function options cmd:option('-pixel_loss_type', 'L2', 'L2|L1|SmoothL1') cmd:option('-pixel_loss_weight', 0.0) cmd:option('-percep_loss_weight', 1.0) cmd:option('-tv_strength', 1e-6) -- Options for feature reconstruction loss cmd:option('-content_weights', '1.0') cmd:option('-content_layers', '16') cmd:option('-loss_network', 'models/vgg16.t7') -- Options for style reconstruction loss cmd:option('-style_image', 'images/styles/candy.jpg') cmd:option('-style_image_size', 256) cmd:option('-style_weights', '5.0') cmd:option('-style_layers', '4,9,16,23') cmd:option('-style_target_type', 'gram', 'gram|mean') -- Upsampling options cmd:option('-upsample_factor', 4) -- Optimization cmd:option('-num_iterations', 40000) cmd:option('-max_train', -1) cmd:option('-batch_size', 4) cmd:option('-learning_rate', 1e-3) cmd:option('-lr_decay_every', -1) cmd:option('-lr_decay_factor', 0.5) cmd:option('-weight_decay', 0) -- Checkpointing cmd:option('-checkpoint_name', 'checkpoint') cmd:option('-checkpoint_every', 1000) cmd:option('-num_val_batches', 10) -- Backend options cmd:option('-gpu', 0) cmd:option('-use_cudnn', 1) cmd:option('-backend', 'cuda', 'cuda|opencl') function main() local opt = cmd:parse(arg) -- Parse layer strings and weights opt.content_layers, opt.content_weights = utils.parse_layers(opt.content_layers, opt.content_weights) opt.style_layers, opt.style_weights = utils.parse_layers(opt.style_layers, opt.style_weights) -- Figure out preprocessing if not preprocess[opt.preprocessing] then local msg = 'invalid -preprocessing "%s"; must be "vgg" or "resnet"' error(string.format(msg, opt.preprocessing)) end preprocess = preprocess[opt.preprocessing] -- Figure out the backend local dtype, use_cudnn = utils.setup_gpu(opt.gpu, opt.backend, opt.use_cudnn == 1) -- Build the model local model = nil if opt.resume_from_checkpoint ~= '' then print('Loading checkpoint from ' .. opt.resume_from_checkpoint) model = torch.load(opt.resume_from_checkpoint).model:type(dtype) else print('Initializing model from scratch') model = models.build_model(opt):type(dtype) end if use_cudnn then cudnn.convert(model, cudnn) end model:training() print(model) -- Set up the pixel loss function local pixel_crit if opt.pixel_loss_weight > 0 then if opt.pixel_loss_type == 'L2' then pixel_crit = nn.MSECriterion():type(dtype) elseif opt.pixel_loss_type == 'L1' then pixel_crit = nn.AbsCriterion():type(dtype) elseif opt.pixel_loss_type == 'SmoothL1' then pixel_crit = nn.SmoothL1Criterion():type(dtype) end end -- Set up the perceptual loss function local percep_crit if opt.percep_loss_weight > 0 then local loss_net = torch.load(opt.loss_network) local crit_args = { cnn = loss_net, style_layers = opt.style_layers, style_weights = opt.style_weights, content_layers = opt.content_layers, content_weights = opt.content_weights, agg_type = opt.style_target_type, } percep_crit = nn.PerceptualCriterion(crit_args):type(dtype) if opt.task == 'style' then -- Load the style image and set it local style_image = image.load(opt.style_image, 3, 'float') style_image = image.scale(style_image, opt.style_image_size) local H, W = style_image:size(2), style_image:size(3) style_image = preprocess.preprocess(style_image:view(1, 3, H, W)) percep_crit:setStyleTarget(style_image:type(dtype)) end end local loader = DataLoader(opt) local params, grad_params = model:getParameters() local function shave_y(x, y, out) if opt.padding_type == 'none' then local H, W = x:size(3), x:size(4) local HH, WW = out:size(3), out:size(4) local xs = (H - HH) / 2 local ys = (W - WW) / 2 return y[{{}, {}, {xs + 1, H - xs}, {ys + 1, W - ys}}] else return y end end local function f(x) assert(x == params) grad_params:zero() local x, y = loader:getBatch('train') x, y = x:type(dtype), y:type(dtype) -- Run model forward local out = model:forward(x) local grad_out = nil -- This is a bit of a hack: if we are using reflect-start padding and the -- output is not the same size as the input, lazily add reflection padding -- to the start of the model so the input and output have the same size. if opt.padding_type == 'reflect-start' and x:size(3) ~= out:size(3) then local ph = (x:size(3) - out:size(3)) / 2 local pw = (x:size(4) - out:size(4)) / 2 local pad_mod = nn.SpatialReflectionPadding(pw, pw, ph, ph):type(dtype) model:insert(pad_mod, 1) out = model:forward(x) end y = shave_y(x, y, out) -- Compute pixel loss and gradient local pixel_loss = 0 if pixel_crit then pixel_loss = pixel_crit:forward(out, y) pixel_loss = pixel_loss * opt.pixel_loss_weight local grad_out_pix = pixel_crit:backward(out, y) if grad_out then grad_out:add(opt.pixel_loss_weight, grad_out_pix) else grad_out_pix:mul(opt.pixel_loss_weight) grad_out = grad_out_pix end end -- Compute perceptual loss and gradient local percep_loss = 0 if percep_crit then local target = {content_target=y} percep_loss = percep_crit:forward(out, target) percep_loss = percep_loss * opt.percep_loss_weight local grad_out_percep = percep_crit:backward(out, target) if grad_out then grad_out:add(opt.percep_loss_weight, grad_out_percep) else grad_out_percep:mul(opt.percep_loss_weight) grad_out = grad_out_percep end end local loss = pixel_loss + percep_loss -- Run model backward model:backward(x, grad_out) -- Add regularization -- grad_params:add(opt.weight_decay, params) return loss, grad_params end local optim_state = {learningRate=opt.learning_rate} local train_loss_history = {} local val_loss_history = {} local val_loss_history_ts = {} local style_loss_history = nil if opt.task == 'style' then style_loss_history = {} for i, k in ipairs(opt.style_layers) do style_loss_history[string.format('style-%d', k)] = {} end for i, k in ipairs(opt.content_layers) do style_loss_history[string.format('content-%d', k)] = {} end end local style_weight = opt.style_weight for t = 1, opt.num_iterations do local epoch = t / loader.num_minibatches['train'] local _, loss = optim.adam(f, params, optim_state) table.insert(train_loss_history, loss[1]) if opt.task == 'style' then for i, k in ipairs(opt.style_layers) do table.insert(style_loss_history[string.format('style-%d', k)], percep_crit.style_losses[i]) end for i, k in ipairs(opt.content_layers) do table.insert(style_loss_history[string.format('content-%d', k)], percep_crit.content_losses[i]) end end print(string.format('Epoch %f, Iteration %d / %d, loss = %f', epoch, t, opt.num_iterations, loss[1]), optim_state.learningRate) if t % opt.checkpoint_every == 0 then -- Check loss on the validation set loader:reset('val') model:evaluate() local val_loss = 0 print 'Running on validation set ... ' local val_batches = opt.num_val_batches for j = 1, val_batches do local x, y = loader:getBatch('val') x, y = x:type(dtype), y:type(dtype) local out = model:forward(x) y = shave_y(x, y, out) local pixel_loss = 0 if pixel_crit then pixel_loss = pixel_crit:forward(out, y) pixel_loss = opt.pixel_loss_weight * pixel_loss end local percep_loss = 0 if percep_crit then percep_loss = percep_crit:forward(out, {content_target=y}) percep_loss = opt.percep_loss_weight * percep_loss end val_loss = val_loss + pixel_loss + percep_loss end val_loss = val_loss / val_batches print(string.format('val loss = %f', val_loss)) table.insert(val_loss_history, val_loss) table.insert(val_loss_history_ts, t) model:training() -- Save a JSON checkpoint local checkpoint = { opt=opt, train_loss_history=train_loss_history, val_loss_history=val_loss_history, val_loss_history_ts=val_loss_history_ts, style_loss_history=style_loss_history, } local filename = string.format('%s.json', opt.checkpoint_name) paths.mkdir(paths.dirname(filename)) utils.write_json(filename, checkpoint) -- Save a torch checkpoint; convert the model to float first model:clearState() if use_cudnn then cudnn.convert(model, nn) end model:float() checkpoint.model = model filename = string.format('%s.t7', opt.checkpoint_name) torch.save(filename, checkpoint) -- Convert the model back model:type(dtype) if use_cudnn then cudnn.convert(model, cudnn) end params, grad_params = model:getParameters() end if opt.lr_decay_every > 0 and t % opt.lr_decay_every == 0 then local new_lr = opt.lr_decay_factor * optim_state.learningRate optim_state = {learningRate = new_lr} end end end main()
#!/usr/bin/env tarantool local test = require("sqltester") test:plan(203) --!./tcltestrunner.lua -- 2015-01-19 -- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, never taking more than you give. -- ------------------------------------------------------------------------- -- This file implements regression tests for sql library. The -- focus of this file is testing ORDER BY and LIMIT on tables with -- many columns. -- -- These tests verify that ticket [f97c4637102a3ae72b7911167e1d4da12ce60722] -- from 2015-01-19 has been fixed. -- -- ["set","testdir",[["file","dirname",["argv0"]]]] -- ["source",[["testdir"],"\/tester.tcl"]] local rs = "" test:do_test( 1.0, function() test:execsql [[ CREATE TABLE t1(x INT primary key); INSERT INTO t1(x) VALUES(1),(5),(9),(7),(3),(2),(4),(6),(8); ]] rs = "x" return "x" end, -- <1.0> "x" -- </1.0> ) for i=1,200 do rs = rs..", x+"..i test:do_execsql_test( "1."..i, "SELECT x FROM (SELECT "..rs.." FROM t1 ORDER BY x LIMIT 100)", { 1, 2, 3, 4, 5, 6, 7, 8, 9 }) end -- Tests to check that ORDER BY + LIMIT + (ASC + DESC, different -- sorting orders) are forbidden. Such combination is forbidden -- because currently it returns data in wrong sorting order. -- It will be fixed when multi-directional would be introduced: -- https://github.com/tarantool/tarantool/issues/3309 test:do_catchsql_test( "1.201", [[ CREATE TABLE t2 (id INT PRIMARY KEY, a INT, b INT); INSERT INTO t2 VALUES (1, 2, 1), (2, -3, 5), (3, 2, -3), (4, 2, 12); SELECT * FROM t2 ORDER BY a ASC, b DESC LIMIT 5; ]], {1, "ORDER BY with LIMIT does not support different sorting orders"} ) test:do_catchsql_test( "1.202", [[ SELECT * FROM t2 ORDER BY a, b DESC LIMIT 5; ]], {1, "ORDER BY with LIMIT does not support different sorting orders"} ) test:finish_test()
SLASH_ANALYZE1 = "/analyze" SlashCmdList["ANALYZE"] = function(arg) if arg ~= "" then arg = _G[arg] else arg = GetMouseFocus() end if arg ~= nil then FRAME = arg end --Set the global variable FRAME to = whatever we are mousing over to simplify messing with frames that have no name. if arg ~= nil and arg:GetName() ~= nil then local name = arg:GetName() local childFrames = { arg:GetChildren() } ChatFrame1:AddMessage("|cffCC0000----------------------------") ChatFrame1:AddMessage(name) for _, child in ipairs(childFrames) do if child:GetName() then ChatFrame1:AddMessage("+="..child:GetName()) end end ChatFrame1:AddMessage("|cffCC0000----------------------------") end end SLASH_PROFILE1 = "/profile" SlashCmdList["PROFILE"] = function(arg) local cpuProfiling = GetCVar("scriptProfile") == "1" if cpuProfiling then SetCVar("scriptProfile", "0") else SetCVar("scriptProfile", "1") end ReloadUI() end
Keys = { ["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57, ["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177, ["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18, ["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182, ["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81, ["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70, ["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178, ["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173, ["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118 } ragdoll = false isDead = false prop = nil loop = { status = nil, current = nil, finish = nil, delay = 0, dettach = false, last = 0 } binds = nil binding = nil ESX = nil local PlayerData = {} CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end Citizen.Wait(5000) PlayerData = ESX.GetPlayerData() if not binds then TriggerServerEvent('esx_animations:load') end end) RegisterNetEvent('esx:playerLoaded') AddEventHandler('esx:playerLoaded', function(xPlayer) PlayerData = xPlayer end) RegisterNetEvent('esx:setJob') AddEventHandler('esx:setJob', function(job) PlayerData.job = job end) RegisterNetEvent('esx_animations:bind') AddEventHandler('esx_animations:bind', function(list) binds = list end) AddEventHandler('esx:onPlayerDeath', function(data) isDead = true end) AddEventHandler('esx:onPlayerSpawn', function(spawn) isDead = false end) RegisterNetEvent('esx_animations:trigger') AddEventHandler('esx_animations:trigger', function(anim) --local ped = Citizen.InvokeNative(0x43A66C31C68491C0, -1) --local car = GetVehiclePedIsIn(ped, false) --if car then if anim.type == 'ragdoll' then if IsPedInAnyVehicle(PlayerPedId(), false) then ragdoll = true end elseif anim.type == 'attitude' then if anim.data.car == true then if IsPedInAnyVehicle(PlayerPedId(), false) then startAttitude(anim.data.lib, anim.data.anim) end else if not IsPedInAnyVehicle(PlayerPedId(), false) then startAttitude(anim.data.lib, anim.data.anim) end end elseif anim.type == 'scenario' then if anim.data.car == true then if IsPedInAnyVehicle(PlayerPedId(), false) then startScenario(anim.data.anim, anim.data.offset) end else if not IsPedInAnyVehicle(PlayerPedId(), false) then startScenario(anim.data.anim, anim.data.offset) end end elseif anim.type == 'anim' then if anim.data.car == true then if IsPedInAnyVehicle(PlayerPedId(), false) then startAnim(anim.data.lib, anim.data.anim, anim.data.mode, anim.data.prop) end else if not IsPedInAnyVehicle(PlayerPedId(), false) then startAnim(anim.data.lib, anim.data.anim, anim.data.mode, anim.data.prop) end end elseif anim.type == 'facial' then TriggerEvent('esx_voice:facial', anim.data) elseif anim.type == 'wspolne' then if anim.data.name == 'powitaj' then local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance ~= -1 and distance <= 3.0 then TriggerServerEvent('route68_animacje:powitajSynchroS', GetPlayerServerId(closestPlayer)) else ESX.ShowNotification('~r~Brak obywatela w poblizu') end end elseif anim.data.name == 'przytul' then local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance ~= -1 and distance <= 3.0 then TriggerServerEvent('route68_animacje:przytulSynchroS', GetPlayerServerId(closestPlayer)) else ESX.ShowNotification('~r~Brak obywatela w poblizu') end end elseif anim.data.name == 'pocaluj' then local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance ~= -1 and distance <= 3.0 then TriggerServerEvent('route68_animacje:pocalujSynchroS', GetPlayerServerId(closestPlayer)) else ESX.ShowNotification('~r~Brak obywatela w poblizu') end end elseif anim.data.name == 'przenies' then local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance ~= -1 and distance <= 3.0 then TriggerServerEvent('route68_animacje:OdpalAnimacje4', GetPlayerServerId(closestPlayer)) else ESX.ShowNotification('~r~Brak obywatela w poblizu') end end end else if not IsPedInAnyVehicle(PlayerPedId(), false) then startAnimLoop(anim.data) end end --else --end end) function startAttitude(lib, anim) CreateThread(function() RequestAnimSet(anim) while not HasAnimSetLoaded(anim) do Citizen.Wait(1) end SetPedMovementClipset(PlayerPedId(), anim, true) end) end function startScenario(anim, offset) if loop.status == true then finishLoop(function() startScenario(anim, offset) end) else local ped = PlayerPedId() if offset then local coords = GetEntityCoords(ped, true) TaskStartScenarioAtPosition(ped, anim, coords.x, coords.y, coords.z + offset, GetEntityHeading(ped), 0, true, true) else TaskStartScenarioInPlace(ped, anim, 0, false) end end end function startAnim(lib, anim, mode, obj) if loop.status == true then finishLoop(function() startAnim(lib, anim, mode, obj) end) else mode = mode or 0 CreateThread(function() RequestAnimDict(lib) while not HasAnimDictLoaded(lib) do Citizen.Wait(0) end local ped = PlayerPedId() TaskPlayAnim(ped, lib, anim, 8.0, -8.0, -1, mode, 0, false, false, false) if obj then if type(prop) == 'table' then DeleteObject(prop.obj) end local coords = GetEntityCoords(ped) local boneIndex = GetPedBoneIndex(ped, obj.bone) ESX.Game.SpawnObject(obj.object, { x = coords.x, y = coords.y, z = coords.z + 2 }, function(object) AttachEntityToEntity(object, ped, boneIndex, obj.offset.x + 0.0, obj.offset.y + 0.0, obj.offset.z + 0.0, obj.rotation.x + 0.0, obj.rotation.y + 0.0, obj.rotation.z + 0.0, true, true, false, true, 1, true) prop = {obj = object, lib = lib, anim = anim} end) end end) end end function startAnimLoop(data) if loop.status == true then finishLoop(function() startAnimLoop(data) end) else CreateThread(function() while loop.status ~= nil do Citizen.Wait(1) end RequestAnimDict(data.base.lib) while not HasAnimDictLoaded(data.base.lib) do Citizen.Wait(1) end RequestAnimDict(data.idle.lib) while not HasAnimDictLoaded(data.idle.lib) do Citizen.Wait(1) end RequestAnimDict(data.finish.lib) while not HasAnimDictLoaded(data.finish.lib) do Citizen.Wait(1) end local playerPed = PlayerPedId() if data.prop then local coords = GetEntityCoords(playerPed) local boneIndex = GetPedBoneIndex(playerPed, data.prop.bone) ESX.Game.SpawnObject(data.prop.object, { x = coords.x, y = coords.y, z = coords.z + 2 }, function(object) AttachEntityToEntity(object, playerPed, boneIndex, data.prop.offset.x, data.prop.offset.y, data.prop.offset.z, data.prop.rotation.x, data.prop.rotation.y, data.prop.rotation.z, true, true, false, true, 1, true) prop = object end) end TaskPlayAnim(PlayerPedId(), data.base.lib, data.base.anim, 8.0, -8.0, -1, data.mode, 0, false, false, false) loop = {status = true, current = nil, finish = data.finish, delay = (GetGameTimer() + 100), last = 0} loop.finish.mode = data.mode if data.prop then loop.dettach = data.prop.dettach else loop.dettach = false end Citizen.Wait(data.base.length) while loop.status do local rng repeat rng = math.random(0, #data.idle.anims) until rng ~= loop.last loop.delay = GetGameTimer() + 100 loop.last = rng if rng == 0 then TaskPlayAnim(PlayerPedId(), data.base.lib, data.base.anim, 8.0, -8.0, -1, data.mode, 0, false, false, false) loop.current = data.base Citizen.Wait(data.base.length) else TaskPlayAnim(PlayerPedId(), data.idle.lib, data.idle.anims[rng][1], 8.0, -8.0, -1, data.mode, 0, false, false, false) loop.current = {lib = data.idle.lib, anim = data.idle.anims[rng][1]} Citizen.Wait(data.idle.anims[rng][2]) end end end) end end function finishLoop(cb) loop.status = false CreateThread(function() TaskPlayAnim(PlayerPedId(), loop.finish.lib, loop.finish.anim, 8.0, 8.0, -1, loop.finish.mode, 0, false, false, false) Citizen.Wait(loop.finish.length) if loop.status == false and prop then if loop.dettach then DetachEntity(prop, true, false) else DeleteObject(prop) end prop = nil end loop.status = nil if cb then cb() end end) end function OpenAnimationsMenu() local elements = {} if not binding then if binds then table.insert(elements, {label = "Ulubione (SHIFT+1-9)", value = "binds"}) end table.insert(elements, {label = "- PRZERWIJ -", value = "cancel"}) end for _, group in ipairs(Config.Animations) do if not group.resource or GetResourceState(group.resource) == 'started' then table.insert(elements, {label = group.label, value = group.name}) end end ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'animations', { title = 'Animacje', align = 'bottom-right', elements = elements }, function(data, menu) if data.current.value == 'binds' then menu.close() OpenBindsSubMenu() elseif data.current.value ~= 'cancel' then menu.close() OpenAnimationsSubMenu(data.current.value) elseif not exports['esx_policejob']:isHandcuffed() and not exports['AriviRP']:checkInTrunk() then clearTask() end end, function(data, menu) menu.close() end) end function OpenBindsSubMenu() local elements = {} for i = 1, 9 do local bind = binds[i] if bind then table.insert(elements, {label = i .. ' - ' .. bind.label, value = i, assigned = true}) else table.insert(elements, {label = i .. ' - PRZYPISZ', value = i, assigned = false}) end end window = ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'animations_binds', { title = 'Animacje - ulubione', align = 'bottom-right', elements = elements }, function(data, menu) menu.close() window = nil local index = tonumber(data.current.value) if data.current.assigned then binds[index] = nil TriggerServerEvent('esx_animations:save', binds) OpenBindsSubMenu() else binding = tonumber(data.current.value) OpenAnimationsMenu() end end, function(data, menu) menu.close() window = nil OpenAnimationsMenu() end) end function OpenAnimationsSubMenu(menu) local title, elements = nil, {} for _, group in ipairs(Config.Animations) do if group.name == menu then for _, item in ipairs(group.items) do table.insert(elements, {label = item.label .. (item.keyword and ' <span style="font-size: 11px; color: #fff000;">/e ' .. item.keyword .. '</span>' or ''), short = item.label, type = item.type, data = item.data}) end title = group.label break end end ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'animations_' .. menu, { title = title, align = 'bottom-right', elements = elements }, function(data, menu) if binding then menu.close() window = nil if not binds then binds = {} end binds[binding] = { label = '[' .. title .. '] ' .. data.current.short, type = data.current.type, data = data.current.data } TriggerServerEvent('esx_animations:save', binds) binding = nil OpenBindsSubMenu() else TriggerEvent('esx_animations:trigger', data.current) end end, function(data, menu) menu.close() OpenAnimationsMenu() end) end local GraczKuca = false CreateThread( function() while true do Citizen.Wait(1) local ped = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if DoesEntityExist(ped) and not Citizen.InvokeNative(0x5F9532F3B5CC2551, ped) then DisableControlAction(0, 36, true) -- CTRL if not IsPauseMenuActive() then if IsDisabledControlJustPressed(0, 36) and not IsPedInAnyVehicle(ped, false) then RequestAnimSet( "move_ped_crouched" ) while not HasAnimSetLoaded( "move_ped_crouched" ) do Citizen.Wait(100) end if GraczKuca == true then ResetPedMovementClipset(ped, 0) GraczKuca = false elseif GraczKuca == false then SetPedMovementClipset(ped, "move_ped_crouched", 0.25) GraczKuca = true end end end end end end) RegisterCommand("e",function(source, args) local player = PlayerPedId() if tostring(args[1]) == nil then return else if tostring(args[1]) ~= nil then local argh = tostring(args[1]) for _, group in ipairs(Config.Animations) do for _, anim in ipairs(group.items) do if argh == anim.keyword then if anim.type == 'ragdoll' then if IsPedInAnyVehicle(PlayerPedId(), false) then ragdoll = true end elseif anim.type == 'attitude' then if anim.data.car == true then if IsPedInAnyVehicle(PlayerPedId(), false) then startAttitude(anim.data.lib, anim.data.anim) end else if not IsPedInAnyVehicle(PlayerPedId(), false) then startAttitude(anim.data.lib, anim.data.anim) end end elseif anim.type == 'scenario' then if anim.data.car == true then if IsPedInAnyVehicle(PlayerPedId(), false) then startScenario(anim.data.anim, anim.data.offset) end else if not IsPedInAnyVehicle(PlayerPedId(), false) then startScenario(anim.data.anim, anim.data.offset) end end elseif anim.type == 'anim' then if anim.data.car == true then if IsPedInAnyVehicle(PlayerPedId(), false) then startAnim(anim.data.lib, anim.data.anim, anim.data.mode, anim.data.prop) end else if not IsPedInAnyVehicle(PlayerPedId(), false) then startAnim(anim.data.lib, anim.data.anim, anim.data.mode, anim.data.prop) end end elseif anim.type == 'wspolne' then if anim.data.name == 'powitaj' then local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance ~= -1 and distance <= 3.0 then TriggerServerEvent('route68_animacje:powitajSynchroS', GetPlayerServerId(closestPlayer)) else ESX.ShowNotification('~r~Brak obywatela w poblizu') end end elseif anim.data.name == 'przytul' then local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance ~= -1 and distance <= 3.0 then TriggerServerEvent('route68_animacje:przytulSynchroS', GetPlayerServerId(closestPlayer)) else ESX.ShowNotification('~r~Brak obywatela w poblizu') end end elseif anim.data.name == 'pocaluj' then local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance ~= -1 and distance <= 3.0 then TriggerServerEvent('route68_animacje:pocalujSynchroS', GetPlayerServerId(closestPlayer)) else ESX.ShowNotification('~r~Brak obywatela w poblizu') end end elseif anim.data.name == 'przenies' then local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance ~= -1 and distance <= 3.0 then TriggerServerEvent('route68_animacje:OdpalAnimacje4', GetPlayerServerId(closestPlayer)) else ESX.ShowNotification('~r~Brak obywatela w poblizu') end end end else if not IsPedInAnyVehicle(PlayerPedId(), false) then startAnimLoop(anim.data) end end end end end end end end) -- Key Controls CreateThread(function() while true do Citizen.Wait(1) local ped = PlayerPedId() if ragdoll then SetPedToRagdoll(ped, 1000, 1000, 0, 0, 0, 0) end if loop.status and loop.current and loop.delay < GetGameTimer() and not IsEntityPlayingAnim(ped, loop.current.lib, loop.current.anim, 3) then loop.status = nil if prop and type(prop) ~= 'table' then if loop.dettach then DetachEntity(prop, true, false) else DeleteObject(prop) end prop = nil end end if type(prop) == 'table' and not IsEntityPlayingAnim(ped, prop.lib, prop.anim, 3) then DeleteObject(prop.obj) prop = nil end if IsControlPressed(0, Keys['LEFTSHIFT']) and not IsPedSprinting(ped) and not IsPedRunning(ped) then local bind = nil for i, key in ipairs({157, 158, 160, 164, 165, 159, 161, 162, 163}) do DisableControlAction(0, key, true) --[[if binds[i] == nil then print(binds[i]) end]] if IsDisabledControlJustPressed(0, key) and binds[i] then bind = i break end end if bind and not exports['esx_ambulancejob']:getDeathStatus() or exports['esx_policejob']:isHandcuffed() and not getCarry() then TriggerEvent('esx_animations:trigger', binds[bind]) end end if IsControlJustPressed(0, Keys['F3']) and not isDead then OpenAnimationsMenu(PlayerPedId()) elseif IsControlJustReleased(0, Keys['X']) and GetLastInputMethod(2) and not isDead then clearTask() end end end) RegisterNetEvent('animacje') AddEventHandler('animacje', function() OpenAnimationsMenu(PlayerPedId()) end) function clearTask() if loop.status == true then finishLoop() elseif ragdoll then ragdoll = false else ClearPedTasks(PlayerPedId()) if loop.status ~= nil then loop.status = nil if prop and type(prop) ~= 'table' then if loop.dettach then DetachEntity(prop, true, false) else DeleteObject(prop) end prop = nil end elseif type(prop) == 'table' then DeleteObject(prop.obj) prop = nil end end end local Oczekuje = false local Czas = 7 local wysylajacy = nil RegisterNetEvent('route68_animacje:powitajSynchroC') AddEventHandler('route68_animacje:powitajSynchroC', function(target) Oczekuje = true wysylajacy = target end) CreateThread(function() while true do Citizen.Wait(0) if Oczekuje then if IsControlJustReleased(0, 246) then Oczekuje = false Czas = 7 TriggerServerEvent('route68_animacje:OdpalAnimacje', wysylajacy) end else Citizen.Wait(200) end end end) RegisterNetEvent('route68_animacje:PrzywitajTarget') AddEventHandler('route68_animacje:PrzywitajTarget', function(target) local playerPed = Citizen.InvokeNative(0x43A66C31C68491C0, -1) local targetPed = Citizen.InvokeNative(0x43A66C31C68491C0, GetPlayerFromServerId(target)) AttachEntityToEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), targetPed, 11816, 0.1, 1.15, 0.0, 0.0, 0.0, 180.0, false, false, false, false, 20, false) ESX.Streaming.RequestAnimDict("mp_ped_interaction", function() TaskPlayAnim(playerPed, "mp_ped_interaction", "handshake_guy_b", 8.0, -8.0, -1, 0, 0, false, false, false) end) Citizen.Wait(950) DetachEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), true, false) Oczekuje = false Czas = 7 wysylajacy = nil end) RegisterNetEvent('route68_animacje:PrzywitajSource') AddEventHandler('route68_animacje:PrzywitajSource', function() local playerPed = Citizen.InvokeNative(0x43A66C31C68491C0, -1) ESX.Streaming.RequestAnimDict("mp_ped_interaction", function() TaskPlayAnim(playerPed, "mp_ped_interaction", "handshake_guy_a", 8.0, -8.0, -1, 0, 0, false, false, false) end) end) CreateThread(function() while true do Citizen.Wait(1000) if Oczekuje then Czas = Czas - 1 end end end) CreateThread(function() while true do Citizen.Wait(250) if Czas < 1 then Oczekuje = false Czas = 7 wysylajacy = nil ESX.ShowNotification('~r~Anulowano propozycję animacji') end end end) -- pocalowanie local Oczekuje2 = false local Czas2 = 7 local wysylajacy2 = nil RegisterNetEvent('route68_animacje:pocalujSynchroC') AddEventHandler('route68_animacje:pocalujSynchroC', function(target) Oczekuje2 = true wysylajacy2 = target end) CreateThread(function() while true do Citizen.Wait(0) if Oczekuje2 then if IsControlJustReleased(0, 246) then Oczekuje2 = false Czas2 = 7 TriggerServerEvent('route68_animacje:OdpalAnimacje2', wysylajacy2) end else Citizen.Wait(200) end end end) RegisterNetEvent('route68_animacje:PocalujTarget') AddEventHandler('route68_animacje:PocalujTarget', function(target) local playerPed = Citizen.InvokeNative(0x43A66C31C68491C0, -1) local targetPed = Citizen.InvokeNative(0x43A66C31C68491C0, GetPlayerFromServerId(target)) AttachEntityToEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), targetPed, 11816, 0.0, 1.2, 0.0, 0.0, 0.0, 180.0, false, false, false, false, 20, false) ESX.Streaming.RequestAnimDict("mp_ped_interaction", function() TaskPlayAnim(playerPed, "mp_ped_interaction", "kisses_guy_a", 8.0, -8.0, -1, 0, 0, false, false, false) end) Citizen.Wait(950) DetachEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), true, false) Oczekuje2 = false Czas2 = 7 wysylajacy2 = nil end) RegisterNetEvent('route68_animacje:PocalujSource') AddEventHandler('route68_animacje:PocalujSource', function() local playerPed = Citizen.InvokeNative(0x43A66C31C68491C0, -1) ESX.Streaming.RequestAnimDict("mp_ped_interaction", function() TaskPlayAnim(playerPed, "mp_ped_interaction", "kisses_guy_b", 8.0, -8.0, -1, 0, 0, false, false, false) end) end) CreateThread(function() while true do Citizen.Wait(1000) if Oczekuje2 then Czas2 = Czas2 - 1 end end end) CreateThread(function() while true do Citizen.Wait(250) if Czas2 < 1 then Oczekuje2 = false Czas2 = 7 wysylajacy2 = nil ESX.ShowNotification('~r~Anulowano propozycję animacji') end end end) -- przytulas local Oczekuje3 = false local Czas3 = 7 local wysylajacy3 = nil RegisterNetEvent('route68_animacje:przytulSynchroC') AddEventHandler('route68_animacje:przytulSynchroC', function(target) Oczekuje3 = true wysylajacy3 = target end) CreateThread(function() while true do Citizen.Wait(0) if Oczekuje3 then if IsControlJustReleased(0, 246) then Oczekuje3 = false Czas3 = 7 TriggerServerEvent('route68_animacje:OdpalAnimacje3', wysylajacy3) end else Citizen.Wait(200) end end end) RegisterNetEvent('route68_animacje:PrzytulTarget') AddEventHandler('route68_animacje:PrzytulTarget', function(target) local playerPed = Citizen.InvokeNative(0x43A66C31C68491C0, -1) local targetPed = Citizen.InvokeNative(0x43A66C31C68491C0, GetPlayerFromServerId(target)) AttachEntityToEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), targetPed, 11816, -0.05, 0.9, 0.0, 0.0, 0.0, 180.0, false, false, false, false, 20, false) ESX.Streaming.RequestAnimDict("mp_ped_interaction", function() TaskPlayAnim(playerPed, "mp_ped_interaction", "hugs_guy_a", 8.0, -8.0, -1, 0, 0, false, false, false) end) Citizen.Wait(950) DetachEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), true, false) Oczekuje3 = false Czas3 = 7 wysylajacy3 = nil end) RegisterNetEvent('route68_animacje:PrzytulSource') AddEventHandler('route68_animacje:PrzytulSource', function() local playerPed = Citizen.InvokeNative(0x43A66C31C68491C0, -1) ESX.Streaming.RequestAnimDict("mp_ped_interaction", function() TaskPlayAnim(playerPed, "mp_ped_interaction", "hugs_guy_a", 8.0, -8.0, -1, 0, 0, false, false, false) end) end) CreateThread(function() while true do Citizen.Wait(1000) if Oczekuje3 then Czas3 = Czas3 - 1 end end end) CreateThread(function() while true do Citizen.Wait(250) if Czas3 < 1 then Oczekuje3 = false Czas3 = 7 wysylajacy3 = nil ESX.ShowNotification('~r~Anulowano propozycję animacji') end end end) --Noszenie local Oczekuje4 = false local Czas4 = 7 local wysylajacy4 = nil RegisterNetEvent('route68_animacje:przytulSynchroC2') AddEventHandler('route68_animacje:przytulSynchroC2', function(target) Oczekuje4 = true wysylajacy4 = target end) CreateThread(function() while true do Citizen.Wait(1000) if Oczekuje4 then Czas4 = Czas4 - 1 end end end) CreateThread(function() while true do Citizen.Wait(250) if Czas4 < 1 then Oczekuje4 = false Czas4 = 7 wysylajacy4 = nil ESX.ShowNotification('~r~Anulowano propozycję animacji') end end end) CreateThread(function() while true do Citizen.Wait(0) if Oczekuje4 then if IsControlJustReleased(0, 246) then Oczekuje4 = false Czas4 = 7 TriggerServerEvent('route68_animacje:OdpalAnimacje5', wysylajacy4) end else Citizen.Wait(200) end end end) local carryingBackInProgress = false local niesie = false function getCarry() return carryingBackInProgress end CreateThread(function() while true do Citizen.Wait(0) if niesie == true then local coords = GetEntityCoords(Citizen.InvokeNative(0x43A66C31C68491C0, -1)) ESX.Game.Utils.DrawText3D(coords, "NACIŚNIJ [~g~L~s~] ABY PUŚCIĆ", 0.45) if IsControlJustPressed(0, Keys['L']) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() local target = GetPlayerServerId(closestPlayer) carryingBackInProgress = false niesie = false ClearPedSecondaryTask(Citizen.InvokeNative(0x43A66C31C68491C0, -1)) DetachEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), true, false) TriggerServerEvent("cmg2_animations:stop", target) end else Citizen.Wait(200) end end end) RegisterNetEvent('cmg2_animations:startMenu2') AddEventHandler('cmg2_animations:startMenu2', function() local Gracz = Citizen.InvokeNative(0x43A66C31C68491C0, -1) if not IsPedInAnyVehicle(Gracz, false) then local closestPlayer, distance = ESX.Game.GetClosestPlayer() if closestPlayer ~= nil and distance <= 4 then TriggerEvent('cmg2_animations:startMenu', GetPlayerServerId(closestPlayer)) end end end) RegisterNetEvent('cmg2_animations:startMenu') AddEventHandler('cmg2_animations:startMenu', function(obiekt) if not carryingBackInProgress then niesie = true carryingBackInProgress = true local player = PlayerPedId() lib = 'missfinale_c2mcs_1' anim1 = 'fin_c2_mcs_1_camman' lib2 = 'nm' anim2 = 'firemans_carry' distans = 0.15 distans2 = 0.27 height = 0.63 spin = 0.0 length = 100000 controlFlagMe = 49 controlFlagTarget = 33 animFlagTarget = 1 local closestPlayer = Citizen.InvokeNative(0x43A66C31C68491C0, obiekt) target = obiekt if closestPlayer ~= nil then TriggerServerEvent('cmg2_animations:sync', closestPlayer, lib,lib2, anim1, anim2, distans, distans2, height,target,length,spin,controlFlagMe,controlFlagTarget,animFlagTarget) end else carryingBackInProgress = false ClearPedSecondaryTask(Citizen.InvokeNative(0x43A66C31C68491C0, -1)) DetachEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), true, false) local closestPlayer = obiekt target = GetPlayerServerId(closestPlayer) TriggerServerEvent("cmg2_animations:stop",target) end end) RegisterNetEvent('cmg2_animations:syncTarget') AddEventHandler('cmg2_animations:syncTarget', function(target, animationLib, animation2, distans, distans2, height, length,spin,controlFlag) local playerPed = Citizen.InvokeNative(0x43A66C31C68491C0, -1) local targetPed = Citizen.InvokeNative(0x43A66C31C68491C0, GetPlayerFromServerId(target)) carryingBackInProgress = true RequestAnimDict(animationLib) while not HasAnimDictLoaded(animationLib) do Citizen.Wait(10) end if spin == nil then spin = 180.0 end AttachEntityToEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), targetPed, 0, distans2, distans, height, 0.5, 0.5, spin, false, false, false, false, 2, false) if controlFlag == nil then controlFlag = 0 end TaskPlayAnim(playerPed, animationLib, animation2, 8.0, -8.0, length, controlFlag, 0, false, false, false) end) RegisterNetEvent('cmg2_animations:syncMe') AddEventHandler('cmg2_animations:syncMe', function(animationLib, animation,length,controlFlag,animFlag) local playerPed = Citizen.InvokeNative(0x43A66C31C68491C0, -1) RequestAnimDict(animationLib) while not HasAnimDictLoaded(animationLib) do Citizen.Wait(10) end Wait(500) if controlFlag == nil then controlFlag = 0 end TaskPlayAnim(playerPed, animationLib, animation, 8.0, -8.0, length, controlFlag, 0, false, false, false) Citizen.Wait(length) end) RegisterNetEvent('cmg2_animations:cl_stop') AddEventHandler('cmg2_animations:cl_stop', function() carryingBackInProgress = false niesie = false ClearPedSecondaryTask(Citizen.InvokeNative(0x43A66C31C68491C0, -1)) DetachEntity(Citizen.InvokeNative(0x43A66C31C68491C0, -1), true, false) end) function GetPlayers() local players = {} for _, player in ipairs(GetActivePlayers()) do table.insert(players, player) end return players end function GetClosestPlayer(radius) local players = GetPlayers() local closestDistance = -1 local closestPlayer = -1 local ply = Citizen.InvokeNative(0x43A66C31C68491C0, -1) local plyCoords = GetEntityCoords(ply, 0) for index,value in ipairs(players) do local target = Citizen.InvokeNative(0x43A66C31C68491C0, value) if(target ~= ply) then local targetCoords = GetEntityCoords(Citizen.InvokeNative(0x43A66C31C68491C0, value), 0) local distance = GetDistanceBetweenCoords(targetCoords['x'], targetCoords['y'], targetCoords['z'], plyCoords['x'], plyCoords['y'], plyCoords['z'], true) if(closestDistance == -1 or closestDistance > distance) then closestPlayer = value closestDistance = distance end end end if closestDistance <= radius then return closestPlayer else return nil end end local lockpick = false RegisterNetEvent('animki:lockpick') AddEventHandler('animki:lockpick', function(rodzaj) if rodzaj == true then lockpick = true elseif rodzaj == false then lockpick = false end end) --Zakładanie rąk CreateThread(function() local dict = "amb@world_human_hang_out_street@female_arms_crossed@base" RequestAnimDict(dict) while not HasAnimDictLoaded(dict) do Citizen.Wait(100) end local handsup = false while true do Citizen.Wait(0) if IsControlJustPressed(1, 47) then --Start holding g if not lockpick then if not handsup then TaskPlayAnim(Citizen.InvokeNative(0x43A66C31C68491C0, -1), dict, "base", 8.0, 8.0, -1, 50, 0, false, false, false) handsup = true else handsup = false ClearPedTasks(Citizen.InvokeNative(0x43A66C31C68491C0, -1)) end end end end end)
local BonusItem = GetFileConfig("server/setting/reward/reward_item_cfg.lua").RuleData -- local BonusGold = GetFileConfig("server/setting/reward/reward_gold_cfg.lua").RuleData -- local BonusExp = GetFileConfig("server/setting/reward/reward_exp_cfg.lua").BonusRule return function(Data) local Reward = {} local DataTbl = Split(Data, ",") for _, data in pairs(DataTbl) do local Tmpdate = Split(data, "|") local RewardId = tonumber(Tmpdate[1]) assert(BonusItem[RewardId], "在奖励表中找不到".. Data .. "这个奖励模板") local Count = tonumber(Tmpdate[2]) or 1 table.insert(Reward, {RewardId, Count}) end return Reward end
wmChat.chatCustom.config = wmChat.chatCustom.config or {} local CONFIG = wmChat.chatCustom.config local w, h = chat.GetChatBoxSize() CONFIG.MinWidth = 300 // Can't be larger than the chatbox CONFIG.MinHeight = 200 CONFIG.MinWidth = math.min(CONFIG.MinWidth, w) CONFIG.MinHeight = math.min(CONFIG.MinHeight, h) CONFIG.MaxFontSize = 50 CONFIG.Fonts = { ["georgia"] = "Georgia, serif", ["palatino linotype"] = "\"Palatino Linotype\", \"Book Antiqua\", Palatino, serif", ["times new roman"] = "\"Times New Roman\", Times, serif", ["arial"] = "Arial, Helvetica, sans-serif", ["arial black"] = "\"Arial Black\", Gadget, sans-serif", ["comic sans"] = "\"Comic Sans MS\", cursive, sans-serif", ["impact"] = "Impact, Charcoal, sans-serif", ["lucida sans unicode"] = "\"Lucida Sans Unicode\", \"Lucida Grande\", sans-serif", ["tahoma"] = "Tahoma, Geneva, sans-serif", ["trebuchet"] = "\"Trebuchet MS\", Helvetica, sans-serif", ["verdana"] = "Verdana, Geneva, sans-serif", ["courier new"] = "\"Courier New\", Courier, monospace", ["lucida console"] = "\"Lucida Console\", Monaco, monospace", }
--[[--------------------------------------------------------- Material Design Core Copyright © 2015 Szymon (Szymekk) Jankowski All Rights Reserved Steam: https://steamcommunity.com/id/szymski -------------------------------------------------------------]] if SERVER then return end matcore = { } matcore.mat = { } --[[------------------------------ Materials ----------------------------------]] matcore.mat.GradientUp = Material("vgui/gradient-u") matcore.mat.GradientDown = Material("vgui/gradient-d") matcore.mat.Blur = Material("pp/blurscreen") matcore.mat.SU = Material("shadow/u.png", "unlitgeneric") matcore.mat.SL = Material("shadow/l.png", "unlitgeneric") matcore.mat.SR = Material("shadow/r.png", "unlitgeneric") matcore.mat.SD = Material("shadow/d.png", "unlitgeneric") matcore.mat.SLU = Material("shadow/lu.png", "unlitgeneric") matcore.mat.SRU = Material("shadow/ru.png", "unlitgeneric") matcore.mat.SLD = Material("shadow/ld.png", "unlitgeneric") matcore.mat.SRD = Material("shadow/rd.png", "unlitgeneric") --[[------------------------------ Stencil functions ----------------------------------]] function matcore.StencilStart() render.ClearStencil() render.SetStencilEnable( true ) render.SetStencilWriteMask( 1 ) render.SetStencilTestMask( 1 ) render.SetStencilFailOperation( STENCILOPERATION_KEEP ) render.SetStencilZFailOperation( STENCILOPERATION_KEEP ) render.SetStencilPassOperation( STENCILOPERATION_REPLACE ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_ALWAYS ) render.SetStencilReferenceValue( 1 ) render.SetColorModulation( 1, 1, 1 ) end function matcore.StencilReplace(v) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_EQUAL ) render.SetStencilPassOperation( STENCILOPERATION_REPLACE ) render.SetStencilReferenceValue(v or 1) end function matcore.StencilEnd() render.SetStencilEnable( false ) end --[[------------------------------ Circles ----------------------------------]] function matcore.DrawCircle(posx, posy, radius, color) local poly = { } local v = 40 for i = 0, v do poly[i+1] = {x = math.sin(-math.rad(i/v*360)) * radius + posx, y = math.cos(-math.rad(i/v*360)) * radius + posy} end draw.NoTexture() surface.SetDrawColor(color) surface.DrawPoly(poly) end --[[------------------------------ Animations ----------------------------------]] function matcore.Lerp(t, from, to) return Lerp(t*((math.sin(3.14*math.Clamp(from/to,0,1)))*0.8+0.2), from, to) end --[[------------------------------ Material boxes ----------------------------------]] function matcore.DrawShadowC(x, y, w, h, left, top, right, bottom, cs) surface.SetDrawColor(255, 255, 255, 255) local s = cs or 16 if top then local m = { {x = x, y = y-s, u = 0, v = 0}, {x = x+w, y = y-s, u = 1/w/1024, v = 0}, {x = x+w, y = y-s+s, u = 1/w/1024, v = 1}, {x = x, y = y-s+s, u = 0, v = 1}, } surface.SetMaterial(matcore.mat.SU) surface.DrawPoly(m) end if right then local m = { {x = x+w, y = y, u = 0, v = 0}, {x = x+w+s, y = y, u = 1, v = 0}, {x = x+w+s, y = y+h, u = 1, v = 1/h/1024}, {x = x+w, y = y+h, u = 0, v = 1/h/1024}, } surface.SetMaterial(matcore.mat.SR) surface.DrawPoly(m) end if bottom then local m = { {x = x, y = y+h, u = 0, v = 0}, {x = x+w, y = y+h, u = 1/w/1024, v = 0}, {x = x+w, y = y+h+s, u = 1/w/1024, v = 1}, {x = x, y = y+h+s, u = 0, v = 1}, } surface.SetMaterial(matcore.mat.SD) surface.DrawPoly(m) end if left then local m = { {x = x-s, y = y, u = 0, v = 0}, {x = x-s+s, y = y, u = 1, v = 0}, {x = x-s+s, y = y+h, u = 1, v = 1/h/1024}, {x = x-s, y = y+h, u = 0, v = 1/h/1024}, } surface.SetMaterial(matcore.mat.SL) surface.DrawPoly(m) end end function matcore.DrawShadow(x, y, w, h) surface.SetDrawColor(255, 255, 255, 255) local m = { {x = x, y = y-16, u = 0, v = 0}, {x = x+w, y = y-16, u = 1/w/1024, v = 0}, {x = x+w, y = y-16+16, u = 1/w/1024, v = 1}, {x = x, y = y-16+16, u = 0, v = 1}, } surface.SetMaterial(matcore.mat.SU) surface.DrawPoly(m) local m = { {x = x+w, y = y, u = 0, v = 0}, {x = x+w+16, y = y, u = 1, v = 0}, {x = x+w+16, y = y+h, u = 1, v = 1/h/1024}, {x = x+w, y = y+h, u = 0, v = 1/h/1024}, } surface.SetMaterial(matcore.mat.SR) surface.DrawPoly(m) local m = { {x = x, y = y+h, u = 0, v = 0}, {x = x+w, y = y+h, u = 1/w/1024, v = 0}, {x = x+w, y = y+h+16, u = 1/w/1024, v = 1}, {x = x, y = y+h+16, u = 0, v = 1}, } surface.SetMaterial(matcore.mat.SD) surface.DrawPoly(m) local m = { {x = x-16, y = y, u = 0, v = 0}, {x = x-16+16, y = y, u = 1, v = 0}, {x = x-16+16, y = y+h, u = 1, v = 1/h/1024}, {x = x-16, y = y+h, u = 0, v = 1/h/1024}, } surface.SetMaterial(matcore.mat.SL) surface.DrawPoly(m) surface.SetMaterial(matcore.mat.SLU) surface.DrawTexturedRect(x-16, y-16, 16, 16) surface.SetMaterial(matcore.mat.SRU) surface.DrawTexturedRect(x+w, y-16, 16, 16) surface.SetMaterial(matcore.mat.SRD) surface.DrawTexturedRect(x+w, y+h, 16, 16) surface.SetMaterial(matcore.mat.SLD) surface.DrawTexturedRect(x-16, y+h, 16, 16) end function matcore.DrawRoundedBoxS(x, y, w, h, col) surface.SetDrawColor(col) draw.RoundedBox(4, x, y, w, h, col) matcore.DrawShadow(x, y, w, h) end function matcore.DrawBoxS(x, y, w, h, col) surface.SetDrawColor(col) draw.RoundedBox(0, x, y, w, h, col) matcore.DrawShadow(x, y, w, h) end --[[------------------------------ Flat buttons ----------------------------------]] surface.CreateFont("matcore_btn", { font = "Roboto", size = 30, weight = 100, blursize = 0, scanlines = 0, antialias = true, }) local PANEL = {} function PANEL:Init() self:SetHeight(48) self:SetFont("matcore_btn") self:SetColor(self.textColor) self.anim = 0 self.hAnim = 0 self.mouseX = 0 self.mouseY = 0 self.OnClick = function() end end function PANEL:Think() self.anim = math.Max(self.anim - FrameTime()*8, 0) self.hAnim = Lerp(FrameTime()*8, self.hAnim, self:IsHovered() and 1 or 0) end function PANEL:Paint(w, h) draw.RoundedBox(0, 0, 0, w, h, self.bgColor) local factor = math.sin(self.anim) draw.RoundedBox(0, 0, 0, w, h, Color(self.clickColor1.r, self.clickColor1.g, self.clickColor1.b, self.clickColor1.a*factor)) matcore.DrawCircle(self.mouseX, self.mouseY, (3.14-self.anim)*100+10, Color(self.clickColor2.r, self.clickColor2.g, self.clickColor2.b, self.clickColor2.a*math.sin(math.min(self.anim,3.14/2)))) if self.hold then draw.RoundedBox(0, 0, 0, w, h, Color(self.clickColor1.r, self.clickColor2.g, self.clickColor2.b, self.clickColor2.a*0.5*(1-factor))) end if self.hoverAnim then draw.RoundedBox(0, 0, 0, w, h, Color(self.clickColor1.r, self.clickColor1.g, self.clickColor1.b, self.clickColor1.a*0.3*self.hAnim)) end end function PANEL:UpdateColours(skin) self:SetTextStyleColor(self.textColor or Color(140,140,140,200)) end function PANEL:OnMousePressed() self.anim = 3.14 local x, y = self:LocalToScreen(0, 0) local mx, my = gui.MousePos() self.mouseX = mx - x self.mouseY = my - y self:DoClick() end derma.DefineControl("MFlatButton", "Flat button", PANEL, "DButton") function matcore.MakeFlatButton(parent, bgColor, clickColor1, clickColor2, textColor, hoverAnim) local btn = parent:Add("MFlatButton") btn.bgColor = bgColor btn.clickColor1 = clickColor1 or Color(140,140,140,100) btn.clickColor2 = clickColor2 or Color(140,140,140,200) btn.textColor = textColor or Color(140,140,140,200) btn.hoverAnim = hoverAnim return btn end --[[------------------------------ Dialogs ----------------------------------]] surface.CreateFont("matcore_dialog_big", { font = "Roboto", size = 34, weight = 5000, blursize = 0, scanlines = 0, antialias = true, }) surface.CreateFont("matcore_dialog_text", { font = "Roboto", size = 26, weight = 100, blursize = 0, scanlines = 0, antialias = true, }) surface.CreateFont("matcore_dialog_textb", { font = "Roboto", size = 26, weight = 5000, blursize = 0, scanlines = 0, antialias = true, }) surface.CreateFont("matcore_dialog_btn", { font = "Roboto", size = 25, weight = 5000, blursize = 0, scanlines = 0, antialias = true, }) local PANEL = {} function PANEL:Init() self:SetSize(0,0) self.anim = 0 self.Header = self:Add("DLabel") self.Header:DockMargin(16+24,16+16,16+24,0) self.Header:Dock(TOP) self.Header:SetWrap(true) self.Header:SetFont("matcore_dialog_big") self.Header:SetColor(Color(0,0,0)) self.Header:SetHeight(48) self.Header:SetContentAlignment(7) self.Text = self:Add("DLabel") self.Text:DockMargin(16+24,0,16+24,0) self.Text:Dock(FILL) self.Text:SetWrap(true) self.Text:SetFont("matcore_dialog_text") self.Text:SetColor(Color(0,0,0)) self.Text:SetHeight(48) self.Text:SetContentAlignment(7) self.Btns = self:Add("DPanel") self.Btns:DockMargin(16+8,0,16+8,16+8) self.Btns:Dock(BOTTOM) self.Btns:SetHeight(48) function self.Btns:Paint(w, h) end self.Agree = self.Btns:Add("DButton") self.Agree:DockMargin(4,8,8,8) self.Agree:Dock(RIGHT) self.Agree:SetFont("matcore_dialog_btn") function self.Agree:Paint(w, h) end function self.Agree:UpdateColours() if self.Depressed || self.m_bSelected then self:SetTextStyleColor(Color(21, 101, 192)) return end self:SetTextStyleColor(Color(33, 150, 243)) end self.Disagree = self.Btns:Add("DButton") self.Disagree:DockMargin(4,8,8,8) self.Disagree:Dock(RIGHT) self.Disagree:SetFont("matcore_dialog_btn") function self.Disagree:Paint(w, h) end function self.Disagree:UpdateColours() if self.Depressed || self.m_bSelected then self:SetTextStyleColor(Color(21, 101, 192)) return end self:SetTextStyleColor(Color(33, 150, 243)) end self:MakePopup() self:MoveToFront() end function PANEL:SetAnimSize(w, h) self.targetW = w self.targetH = h end function PANEL:Think() self.anim = Lerp(FrameTime()*6, self.anim, 1) self:SetAlpha(255*self.anim) self:SetSize(self.targetW*self.anim+50, self.targetH*self.anim+50) self:Center() end function PANEL:Paint(w, h) matcore.DrawBoxS(16, 16, w-32, h-32, self.maincolor) end derma.DefineControl("MDialog", "Dialog", PANEL, "DPanel") function matcore.MakeDialog(maincolor, header, text, headerColor, textColor, agreeText, disagreeText, agree, disagree) local dg = vgui.Create("MDialog") dg.Header:SetText(header) dg.Header:SetColor(headerColor) dg.Text:SetText(text) dg.Text:SetColor(textColor) dg.Agree:SetText(agreeText) dg.Disagree:SetText(disagreeText) dg.maincolor = maincolor return dg end --[[------------------------------ List Dialogs ----------------------------------]] local PANEL = {} function PANEL:Init() self:SetSize(0,0) self.anim = 0 self.Header = self:Add("DLabel") self.Header:DockMargin(16+24,16+16,16+24,0) self.Header:Dock(TOP) self.Header:SetWrap(true) self.Header:SetFont("matcore_dialog_big") self.Header:SetColor(Color(0,0,0)) self.Header:SetHeight(48) self.Header:SetContentAlignment(7) self.Content = self:Add("DScrollPanel") self.Content:DockMargin(16,0,16,0) self.Content:Dock(FILL) function self.Content:PaintOver(w, h) matcore.DrawShadowC(0, 0, w, 0, false, false, false, true) matcore.DrawShadowC(0, h, w, 0, false, true, false, false) end self.Btns = self:Add("DPanel") self.Btns:DockMargin(16+8,0,16+8,16+8) self.Btns:Dock(BOTTOM) self.Btns:SetHeight(48) function self.Btns:Paint(w, h) end self.Agree = self.Btns:Add("DButton") self.Agree:DockMargin(4,8,8,8) self.Agree:Dock(RIGHT) self.Agree:SetFont("matcore_dialog_btn") function self.Agree:Paint(w, h) end function self.Agree:UpdateColours() if self.m_bDisabled then self:SetTextStyleColor(Color(120, 120, 120)) return end if self.Depressed || self.m_bSelected then self:SetTextStyleColor(Color(21, 101, 192)) return end self:SetTextStyleColor(Color(33, 150, 243)) end self.Disagree = self.Btns:Add("DButton") self.Disagree:DockMargin(4,8,8,8) self.Disagree:Dock(RIGHT) self.Disagree:SetFont("matcore_dialog_btn") function self.Disagree:Paint(w, h) end function self.Disagree:UpdateColours() if self.Depressed || self.m_bSelected then self:SetTextStyleColor(Color(21, 101, 192)) return end self:SetTextStyleColor(Color(33, 150, 243)) end self:MakePopup() self:MoveToFront() end function PANEL:AddItem(type) local pnl = self.Content:Add(type) pnl:Dock(TOP) return pnl end function PANEL:SetAnimSize(w, h) self.targetW = w self.targetH = h end function PANEL:Think() self.anim = Lerp(FrameTime()*6, self.anim, 1) self:SetAlpha(255*self.anim) self:SetSize((self.targetW or 0)*self.anim+50, (self.targetH or 0)*self.anim+50) self:Center() end function PANEL:Paint(w, h) matcore.DrawBoxS(16, 16, w-32, h-32, self.maincolor) end derma.DefineControl("MListDialog", "List Dialog", PANEL, "DPanel") function matcore.MakeListDialog(maincolor, header, headerColor, textColor, agreeText, disagreeText, agree, disagree) local dg = vgui.Create("MListDialog") dg.Header:SetText(header) dg.Header:SetColor(headerColor) dg.Agree:SetText(agreeText) dg.Agree:SizeToContentsX() dg.Disagree:SetText(disagreeText) dg.Disagree:SizeToContentsX() dg.maincolor = maincolor return dg end
object_draft_schematic_genetic_engineering_beast_steroid_sub_adv = object_draft_schematic_genetic_engineering_shared_beast_steroid_sub_adv:new { } ObjectTemplates:addTemplate(object_draft_schematic_genetic_engineering_beast_steroid_sub_adv, "object/draft_schematic/genetic_engineering/beast_steroid_sub_adv.iff")
-- 'nvim-telescope/telescope.nvim' return function(c, s, cs) return { { 'TelescopeBorder', c.gray, cs.bg('telescope') }, { 'TelescopeNormal', c.dark_white, cs.bg('telescope') }, { 'TelescopePreviewNormal', c.dark_white, cs.bg('telescope') }, { 'TelescopePromptPrefix', c.dark_white }, { 'TelescopeSelection', c.bright_cyan, c.gray, s.bold }, { 'TelescopeMatching', c.bright_cyan, c.gray }, } end
local maxSegments = 150 local function CreateSegments(Player) local t = Def.ActorFrame { }; local bars = Def.ActorFrame{ Name="CoverBars" }; local bpmFrame = Def.ActorFrame{ Name="BPMFrame"; }; local stopFrame = Def.ActorFrame{ Name="StopFrame"; }; local delayFrame = Def.ActorFrame{ Name="DelayFrame"; }; local warpFrame = Def.ActorFrame{ Name="WarpFrame"; }; local fakeFrame = Def.ActorFrame{ Name="FakeFrame"; }; local scrollFrame = Def.ActorFrame{ Name="ScrollFrame"; }; local speedFrame = Def.ActorFrame{ Name="SpeedFrame"; }; local fFrameWidth = 380; local fFrameHeight = 8; -- XXX: doesn't work in course mode -aj if not GAMESTATE:IsSideJoined( Player ) then return t elseif not GAMESTATE:IsCourseMode() then -- Straight rip off NCRX local song = GAMESTATE:GetCurrentSong(); local steps = GAMESTATE:GetCurrentSteps( Player ); if steps then local timingData = steps:GetTimingData(); -- use the StepsSeconds, which will almost always be more proper -- than a file with ITG2r21 compatibility. if song then local songLen = song:MusicLengthSeconds(); local firstBeatSecs = song:GetFirstSecond(); local lastBeatSecs = song:GetLastSecond(); local bpms = timingData:GetBPMsAndTimes(true); local stops = timingData:GetStops(true); local delays = timingData:GetDelays(true); local warps = timingData:GetWarps(true); local fakes = timingData:GetFakes(true); local scrolls = timingData:GetScrolls(true); local speeds = timingData:GetSpeeds(true); -- we don't want too many segments to be shown. local sumSegments = #bpms + #stops + #delays + #warps + #fakes + #scrolls + #speeds if sumSegments > maxSegments then return Def.ActorFrame{} end local function CreateLine(beat, secs, firstShadow, firstDiffuse, secondShadow, firstEffect, secondEffect) local beatTime = timingData:GetElapsedTimeFromBeat(beat); if beatTime < 0 then beatTime = 0; end; return Def.ActorFrame { Def.Quad { InitCommand=function(self) self:shadowlength(0); self:shadowcolor(color(firstShadow)); -- set width self:zoomto(math.max((secs/songLen)*fFrameWidth, 1), fFrameHeight); -- find location self:x((scale(beatTime,firstBeatSecs,lastBeatSecs,-fFrameWidth/2,fFrameWidth/2))); end; OnCommand=function(self) self:diffuse(color(firstDiffuse)); end; }; --[[ there's a cool effect that can't happen because we don't fade out like we did before Def.Quad { InitCommand=function(self) --self:diffuse(HSVA(192,1,0.8,0.8)); self:shadowlength(0); self:shadowcolor(color(secondShadow)); -- set width self:zoomto(math.max((secs/songLen)*fFrameWidth, 1),fFrameHeight); -- find location self:x((scale(beatTime,firstBeatSecs,lastBeatSecs,-fFrameWidth/2,fFrameWidth/2))); end; OnCommand=function(self) self:diffusealpha(1); self:diffuseshift(); self:effectcolor1(color(firstEffect)); self:effectcolor2(color(secondEffect)); self:effectclock('beat'); self:effectperiod(1/8); -- self:diffusealpha(0); self:sleep(beatTime+1); self:diffusealpha(1); self:linear(4); self:diffusealpha(0); end; };]] }; end; for i=2,#bpms do bpmFrame[#bpmFrame+1] = CreateLine(bpms[i][1], 0, "#00808077", "#00808077", "#00808077", "#FF634777", "#FF000077"); end; for i=1,#delays do delayFrame[#delayFrame+1] = CreateLine(delays[i][1], delays[i][2], "#FFFF0077", "#FFFF0077", "#FFFF0077", "#00FF0077", "#FF000077"); end; for i=1,#stops do stopFrame[#stopFrame+1] = CreateLine(stops[i][1], stops[i][2], "#FFFFFF77", "#FFFFFF77", "#FFFFFF77", "#FFA50077", "#FF000077"); end; for i=1,#scrolls do scrollFrame[#scrollFrame+1] = CreateLine(scrolls[i][1], 0, "#4169E177", "#4169E177", "#4169E177", "#0000FF77", "#FF000077"); end; for i=1,#speeds do -- TODO: Turn beats into seconds for this calculation? speedFrame[#speedFrame+1] = CreateLine(speeds[i][1], 0, "#ADFF2F77", "#ADFF2F77", "#ADFF2F77", "#7CFC0077", "#FF000077"); end; for i=1,#warps do warpFrame[#warpFrame+1] = CreateLine(warps[i][1], 0, "#CC00CC77", "#CC00CC77", "#CC00CC77", "#FF33CC77", "#FF000077"); end; for i=1,#fakes do fakeFrame[#fakeFrame+1] = CreateLine(fakes[i][1], 0, "#BC8F8F77", "#BC8F8F77", "#BC8F8F77", "#F4A46077", "#FF000077"); end; end; bars[#bars+1] = bpmFrame; bars[#bars+1] = scrollFrame; bars[#bars+1] = speedFrame; bars[#bars+1] = stopFrame; bars[#bars+1] = delayFrame; bars[#bars+1] = warpFrame; bars[#bars+1] = fakeFrame; t[#t+1] = bars; --addition here: increase performance a ton by only rendering once t[#t+1] = Def.ActorFrameTexture{Name="Target"} t[#t+1] = Def.Sprite{Name="Actual"} local FirstPass=true; local function Draw(self) kids=self:GetChildren(); if FirstPass then kids.Target:setsize(fFrameWidth,fFrameHeight); kids.Target:EnableAlphaBuffer(true); kids.Target:Create(); kids.Target:GetTexture():BeginRenderingTo(); for k,v in pairs(kids) do if k~="Target" and k~="Actual" then v:Draw(); end end kids.Target:GetTexture():FinishRenderingTo(); kids.Actual:SetTexture(kids.Target:GetTexture()); FirstPass=false; end kids.Actual:Draw(); end t.InitCommand=function(self) self:SetDrawFunction(Draw); end end end return t end local t = LoadFallbackB() t[#t+1] = StandardDecorationFromFileOptional("ScoreFrame","ScoreFrame"); local function songMeterScale(val) return scale(val,0,1,-380/2,380/2) end for pn in ivalues(PlayerNumber) do local MetricsName = "SongMeterDisplay" .. PlayerNumberToString(pn); local songMeterDisplay = Def.ActorFrame{ InitCommand=function(self) self:player(pn); self:name(MetricsName); ActorUtil.LoadAllCommandsAndSetXY(self,Var "LoadingScreen"); end; Def.Quad { InitCommand=cmd(zoomto,420,20); OnCommand=cmd(fadeleft,0.35;faderight,0.35;diffuse,Color.Black;diffusealpha,0.5); }; LoadActor( THEME:GetPathG( 'SongMeterDisplay', 'frame ' .. PlayerNumberToString(pn) ) ) .. { InitCommand=function(self) self:name('Frame'); ActorUtil.LoadAllCommandsAndSetXY(self,MetricsName); end; }; Def.Quad { InitCommand=cmd(zoomto,2,8); OnCommand=cmd(x,songMeterScale(0.25);diffuse,PlayerColor(pn);diffusealpha,0.5); }; Def.Quad { InitCommand=cmd(zoomto,2,8); OnCommand=cmd(x,songMeterScale(0.5);diffuse,PlayerColor(pn);diffusealpha,0.5); }; Def.Quad { InitCommand=cmd(zoomto,2,8); OnCommand=cmd(x,songMeterScale(0.75);diffuse,PlayerColor(pn);diffusealpha,0.5); }; Def.SongMeterDisplay { StreamWidth=THEME:GetMetric( MetricsName, 'StreamWidth' ); Stream=LoadActor( THEME:GetPathG( 'SongMeterDisplay', 'stream ' .. PlayerNumberToString(pn) ) )..{ InitCommand=cmd(diffuse,PlayerColor(pn);diffusealpha,0.5;blend,Blend.Add;); }; Tip=LoadActor( THEME:GetPathG( 'SongMeterDisplay', 'tip ' .. PlayerNumberToString(pn) ) ) .. { InitCommand=cmd(visible,false); }; }; }; if ThemePrefs.Get("TimingDisplay") == true then songMeterDisplay[#songMeterDisplay+1] = CreateSegments(pn); end t[#t+1] = songMeterDisplay end; for pn in ivalues(PlayerNumber) do local MetricsName = "ToastyDisplay" .. PlayerNumberToString(pn); t[#t+1] = LoadActor( THEME:GetPathG("Player", 'toasty'), pn ) .. { InitCommand=function(self) self:player(pn); self:name(MetricsName); ActorUtil.LoadAllCommandsAndSetXY(self,Var "LoadingScreen"); end; }; end; t[#t+1] = StandardDecorationFromFileOptional("BPMDisplay","BPMDisplay"); t[#t+1] = StandardDecorationFromFileOptional("StageDisplay","StageDisplay"); t[#t+1] = StandardDecorationFromFileOptional("SongTitle","SongTitle"); return t
object_draft_schematic_dance_prop_prop_ribbon_magic_l = object_draft_schematic_dance_prop_shared_prop_ribbon_magic_l:new { } ObjectTemplates:addTemplate(object_draft_schematic_dance_prop_prop_ribbon_magic_l, "object/draft_schematic/dance_prop/prop_ribbon_magic_l.iff")
local path = ... if not path then error( "Expected path", 2 ) end path = shell.absolute(path) if not disk.exists(path) then error( "No such path", 2 ) end local suffixes = {"B", "kB", "MB", "GB"} local info = disk.info(path) local size = info.size local sizeSuffix = 1 while size > 1000 and sizeSuffix < #suffixes do size = size / 1000 sizeSuffix = sizeSuffix+1 end print( "Type: "..info.type ) print( "Size: "..string.format( "%.2f ", size )..suffixes[sizeSuffix] ) print( "Timestamp: "..info.modified )
----------------------------------------- -- ID: 15769 -- Olduum Ring -- Teleports to Wajoam Woodlands Leypoint ----------------------------------------- require("scripts/globals/status") ----------------------------------------- function onItemCheck(target) return 0 end function onItemUse(target) target:setPos(-199, -10, 80, 94, 51) end
endor_bordok_herd_master_neutral_none = Lair:new { mobiles = {{"bordok_herd_master",1},{"bordok_mare",1},{"bordok_foal",1},{"roaming_bordok_stud",1}}, spawnLimit = 15, buildingsVeryEasy = {}, buildingsEasy = {}, buildingsMedium = {}, buildingsHard = {}, buildingsVeryHard = {}, buildingType = "none", } addLairTemplate("endor_bordok_herd_master_neutral_none", endor_bordok_herd_master_neutral_none)
-------------------------------------------------------------------------------- -- Function......... : easeInQuad -- Author........... : -- Description...... : -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function Tweener.easeInQuad ( t, b, c, d ) -------------------------------------------------------------------------------- t = t/d return c * t * t + b -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
-- -- This is fun64 code, you can copy paste it into https://xriss.github.io/fun64/pad/ to run it. -- hardware,main=system.configurator({ mode="fun64", -- select the standard 320x240 screen using the swanky32 palette. update=function() update() end, -- called repeatedly to update+draw }) local wstr=require("wetgenes.string") -- we will call this once in the update function setup=function() -- system.components.screen.bloom=0 -- system.components.screen.filter=nil -- system.components.screen.shadow=nil print("Setup complete!") end -- updates are run at 60fps update=function() if setup then setup() setup=nil end local cmap=system.components.colors.cmap local ctext=system.components.text local bg=9 local fg=31 ctext.text_clear(0x01000000*bg) -- clear text forcing a background color for y=0,15 do for x=0,1 do local n=16*x + y local web=math.floor(cmap[n].bgra/16)%16 + math.floor(cmap[n].bgra/(16*256))%16*16 + math.floor(cmap[n].bgra/(16*256*256))%16*256 local s=string.format("%3d %2s %03X %-16s",n,cmap[n].code or "",web,cmap[n].name or "") ctext.text_print(s,x*40+1,y+2,fg,bg) -- (text,x,y,color,background) ctext.text_print(" ",x*40+1+6,y+2,fg,n) -- (text,x,y,color,background) end end local tx=wstr.trim([[ This is a data dump of the ]]..tostring(cmap.name)..[[ palette. First column is the color index number. Second column is the color. Third column is the color code used in bitdown ascii graphics. Fourth column is the hex RGB that can be used on the web. Fifth column is the name of the color. Colors may be referenced by their index number or name. ]]) -- :gsub("\n"," ") local tl=wstr.smart_wrap(tx,system.components.text.text_hx-6) for i=0,system.components.text.tilemap_hy-1 do local t=tl[i+1] if not t then break end system.components.text.text_print(t,3,19+i,fg,bg) end end
local composer = require( "composer" ) local scene = composer.newScene() -- ----------------------------------------------------------------------------------- -- Code outside of the scene event functions below will only be executed ONCE unless -- the scene is removed entirely (not recycled) via "composer.removeScene()" -- ----------------------------------------------------------------------------------- -- Required libraries local widget = require( "widget" ) local _g = require("lib.globalVariables") local _gdpr = require("lib.gdprutil") local _ads = require("lib.ads") -- Variables local bg local group function scene:onResized(event) bg.x, bg.y = _g.centerX, _g.centerY bg.width, bg.height = _g.screenWidth, _g.screenHeight group.y = _g.centerY - group.contentHeight*0.5 + 10 end function scene:onBackKey(event) -- block back key return true end -- ----------------------------------------------------------------------------------- -- Scene event functions -- ----------------------------------------------------------------------------------- -- create() function scene:create( event ) local sceneGroup = self.view -- Code here runs when the scene is first created but has not yet appeared on screen bg = display.newRect(sceneGroup, _g.centerX, _g.centerY, _g.screenWidth, _g.screenHeight) bg:setFillColor(0,0,0,0.9) group = display.newGroup() group.x, group.y = _g.centerX, 0 sceneGroup:insert(group) local textOptions = { text = "Personalize your Ads", x = 0, y = 0, font = _g.fontMain, fontSize = 24, parent = group } local text = display.newText(textOptions) text:setFillColor( 1, 1, 1, 0.9 ) local textOptions = { text = "O-ZONE personalizes your advertising experience. Our ad provider and its partners may collect and process personal data such as device identifiers, location data, and other demographic and interest data to provide you with a tailored experience. By consenting, you'll see ads that our ad provider and its partners believe are more relevant to you.", x = 0, y = 110, width = _g.screenWidth-20, font = _g.fontRegular, fontSize = 14, align = "left", parent = group } local text = display.newText(textOptions) text:setFillColor( 1, 1, 1, 0.9 ) local function learnMoreButtonEvent( event ) if ( "ended" == event.phase ) then system.openURL( "https://robbieelias.ca/ozone_privacy.html" ) end end local learnMoreButton = widget.newButton( { label = "LEARN MORE", font = _g.fontRegular, fontSize = 14, onEvent = learnMoreButtonEvent, textOnly = true, labelAlign = "left", x = 0, y = 200, labelColor = { default=_g.buttonColor, over=_g.buttonColorPressed }, } ) learnMoreButton.x = -_g.screenWidth*0.5 + learnMoreButton.contentWidth*0.5 + 10 group:insert(learnMoreButton) local textOptions = { text = "By agreeing, you confirm that you are over the age of 16 and would like a personalized ad experience.", x = 0, y = 250, width = _g.screenWidth-20, font = _g.fontRegular, fontSize = 14, align = "left", parent = group } local text = display.newText(textOptions) text:setFillColor( 1, 1, 1, 0.9 ) local function agreeButtonEvent( event ) if ( "ended" == event.phase ) then _gdpr.setConsent(true) _ads:init(true) composer.hideOverlay( "slideRight", 400 ) end end local shadow = display.newRoundedRect(group, 0, 324, 250, 50, 10) shadow:setFillColor(54/255,85/255,102/255) local agreeButton = widget.newButton( { label = "YES, I AGREE", labelColor = { default={1,1,1}, over={1,1,1} }, font = _g.fontMain, fontSize = 26, onEvent = agreeButtonEvent, shape = "roundedRect", x = 0, y = 320, width = 250, height = 50, cornerRadius = 10, fillColor = { default={_g.buttonColor[1],_g.buttonColor[2],_g.buttonColor[3]}, over={_g.buttonColorPressed[1],_g.buttonColorPressed[2],_g.buttonColorPressed[3]} }, } ) group:insert(agreeButton) local function noButtonEvent( event ) if ( "ended" == event.phase ) then _gdpr.setConsent(false) _ads:init(false) composer.hideOverlay( "slideRight", 400 ) end end local noButton = widget.newButton( { label = "NO, THANK YOU", font = _g.fontRegular, fontSize = 18, onEvent = noButtonEvent, textOnly = true, x = 0, y = 380, labelColor = { default=_g.buttonColor, over=_g.buttonColorPressed }, } ) group:insert(noButton) local textOptions = { text = "I understand that I will still see ads, but they may not be relevant to me.", x = 0, y = 415, width = _g.screenWidth-100, align = "center", font = _g.fontRegular, fontSize = 12, parent = group } local text = display.newText(textOptions) text:setFillColor( 1, 1, 1, 0.9 ) group.y = _g.centerY - group.contentHeight*0.5 + 10 end -- show() function scene:show( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Code here runs when the scene is still off screen (but is about to come on screen) elseif ( phase == "did" ) then -- Code here runs when the scene is entirely on screen end end -- hide() function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Code here runs when the scene is on screen (but is about to go off screen) elseif ( phase == "did" ) then composer.removeScene( "scenes.gdpr" ) -- Code here runs immediately after the scene goes entirely off screen end end -- destroy() function scene:destroy( event ) local sceneGroup = self.view -- Code here runs prior to the removal of scene's view end -- ----------------------------------------------------------------------------------- -- Scene event function listeners -- ----------------------------------------------------------------------------------- scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) -- ----------------------------------------------------------------------------------- return scene
-- This file is subject to copyright - contact [email protected] for more information. DEFINE_BASECLASS("gun") SWEP.GunType = "smg" SWEP.PrintName = "UMP-45" SWEP.Purpose = "High damage, long range SMG" SWEP.HoldType = "smg" SWEP.Slot = 0 CSKillIcon(SWEP, "q") -- SWEP.WorldModel = "models/weapons/w_smg_ump45.mdl" SWEP.ViewModel = "models/weapons/cstrike/c_smg_ump45.mdl" SWEP.ShootSound = "Weapon_UMP45.Single" SWEP.CSMuzzleFlashes = true SWEP.CSMuzzleX = false SWEP.CSMuzzleFlashScale = 1.15 -- SWEP.Primary.Ammo = "BULLET_PLAYER_45ACP" SWEP.Primary.ClipSize = 25 SWEP.Primary.DefaultClip = 25 SWEP.Primary.Automatic = true SWEP.Damage = 36 SWEP.CycleTime = 0.105 SWEP.HalfDamageDistance = 4096 -- SWEP.SpreadBase = 0.008 SWEP.SpreadMove = 0.02 SWEP.Spray = 0.05 SWEP.SprayExponent = 2.5 ComputeSpray(SWEP, { TapFireInterval = 0.5, ShotsTo90Spray = 16 }) -- SWEP.KickUBase = 0.3 SWEP.KickUSpray = 1 SWEP.KickLBase = 0.2 SWEP.KickLSpray = 0.3 SWEP.MoveSpeed = 1 -- SWEP.KickMoving = {0.45, 0.3, 0.2, 0.0275, 4, 2.25, 7} -- SWEP.KickStanding = {0.3, 0.225, 0.125, 0.02, 3.25, 1.25, 8} -- SWEP.KickCrouching = {0.275, 0.2, 0.125, 0.02, 3, 1, 9} -- CSParseWeaponInfo(SWEP, [[WeaponData -- { -- "MaxPlayerSpeed" "250" -- "WeaponType" "SubMachinegun" -- "FullAuto" 1 -- "WeaponPrice" "1700" -- "WeaponArmorRatio" "1.0" -- "CrosshairMinDistance" "6" -- "CrosshairDeltaDistance" "3" -- "Team" "ANY" -- "BuiltRightHanded" "0" -- "PlayerAnimationExtension" "ump45" -- "MuzzleFlashScale" "1.15" -- "CanEquipWithShield" "0" -- // Weapon characteristics: -- "Penetration" "1" -- "Damage" "30" -- "Range" "4096" -- "RangeModifier" "0.82" -- "Bullets" "1" -- "CycleTime" "0.105" -- "AccuracyQuadratic" "1" -- "AccuracyDivisor" "210" -- "AccuracyOffset" "0.5" -- "MaxInaccuracy" "1" -- "TimeToIdle" "2" -- "IdleInterval" "20" -- // New accuracy model parameters -- "Spread" 0.00100 -- "InaccuracyCrouch" 0.01439 -- "InaccuracyStand" 0.01919 -- "InaccuracyJump" 0.16941 -- "InaccuracyLand" 0.03388 -- "InaccuracyLadder" 0.04235 -- "InaccuracyFire" 0.01129 -- "InaccuracyMove" 0.01366 -- "RecoveryTimeCrouch" 0.21710 -- "RecoveryTimeStand" 0.30394 -- // Weapon data is loaded by both the Game and Client DLLs. -- "printname" "#Cstrike_WPNHUD_UMP45" -- "viewmodel" "models/weapons/v_smg_ump45.mdl" -- "playermodel" "models/weapons/w_smg_ump45.mdl" -- "anim_prefix" "anim" -- "bucket" "0" -- "bucket_position" "0" -- "clip_size" "25" -- "primary_ammo" "BULLET_PLAYER_45ACP" -- "secondary_ammo" "None" -- "weight" "25" -- "item_flags" "0" -- // Sounds for the weapon. There is a max of 16 sounds per category (i.e. max 16 "single_shot" sounds) -- SoundData -- { -- //"reload" "Default.Reload" -- //"empty" "Default.ClipEmpty_Rifle" -- "single_shot" "Weapon_UMP45.Single" -- } -- // Weapon Sprite data is loaded by the Client DLL. -- TextureData -- { -- "weapon" -- { -- "font" "CSweaponsSmall" -- "character" "Q" -- } -- "weapon_s" -- { -- "font" "CSweapons" -- "character" "Q" -- } -- "ammo" -- { -- "font" "CSTypeDeath" -- "character" "M" -- } -- "crosshair" -- { -- "file" "sprites/crosshairs" -- "x" "0" -- "y" "48" -- "width" "24" -- "height" "24" -- } -- "autoaim" -- { -- "file" "sprites/crosshairs" -- "x" "0" -- "y" "48" -- "width" "24" -- "height" "24" -- } -- } -- ModelBounds -- { -- Viewmodel -- { -- Mins "-7 -1 -15" -- Maxs "27 11 -2" -- } -- World -- { -- Mins "-10 -7 -8" -- Maxs "20 8 8" -- } -- } -- }]]) -- function SWEP:PrimaryAttack() -- if self:GetNextPrimaryFire() > CurTime() then return end -- self:GunFire(self:BuildSpread()) -- end -- function SWEP:GunFire(spread) -- if not self:BaseGunFire(spread, self.CycleTime, true) then return end -- if self:GetOwner():GetAbsVelocity():Length2D() > 5 then -- self:KickBack(0.45, 0.3, 0.2, 0.0275, 4, 2.25, 7) -- elseif not self:GetOwner():OnGround() then -- self:KickBack(0.9, 0.45, 0.35, 0.04, 5.25, 3.5, 4) -- elseif self:GetOwner():Crouching() then -- self:KickBack(0.275, 0.2, 0.125, 0.02, 3, 1, 9) -- else -- self:KickBack(0.3, 0.225, 0.125, 0.02, 3.25, 1.25, 8) -- end -- end
PJ_QUESTS = PJ_QUESTS or {} local mod = PJ_QUESTS mod.mission_sjoktraken_shipwreck_payload = function(char) cm:callback(function() CampaignUI.ToggleCinematicBorders(true) cm:stop_user_input(true) cm:scroll_camera_from_current(true, 0.01, {464.257, 490.1476, 6, d_to_r(120), 3}) cm:callback(function() cm:move_to(cm:char_lookup_str(char), 704,649, true) -- mission shipwreck cm:scroll_camera_from_current(true, 3, {470.60491943359,500.95404052734, 5, d_to_r(120), 4}) cm:callback(function() CampaignUI.ToggleCinematicBorders(false) cm:stop_user_input(false) mod.select_first_lord() cm:scroll_camera_from_current(true, 0.1, {470.60491943359,500.95404052734, 5, d_to_r(120), 4}) local custom_bundle = cm:create_new_custom_effect_bundle("pj_quests_empty_1") custom_bundle:add_effect("wh2_dlc13_effect_wulfhart_battle_army_abilities", "faction_to_force_own", 1) cm:apply_custom_effect_bundle_to_faction(custom_bundle, cm:get_faction(cm:get_local_faction(true))) mod.force_start_quest_battle("mission_sjoktraken_shipwreck") end, 4) end, 0.1) end, 0.1) end mod.mission_sjoktraken_shipwreck = { key = "mission_sjoktraken_shipwreck", ui_offsets = {528, 253}, parchment_text_offset = {-31, 0}, locs = { title="The Last of the Northern Ironclads ", desc="The Last of the Northern Ironclads", mission_desc = "The sea routes between Sjoktraken and the minor ports of the northerns holds are used to fortify and supply the realm. The last of the Ironclads, gifted by the high King og Barak Var ages ago, have gone missing. The port master of Sjoktraken, Thorin Seabborn have approached us, ininquiring our service. We are to travel two days north by the Draksfjord and search for the missing Ironclad and by any means secure it.", }, icon = "ui/small_icon_quest_battle.png", payload = mod.mission_sjoktraken_shipwreck_payload, } core:remove_listener("pj_quests_on_won_battle_shipwreck") core:add_listener( "pj_quests_on_won_battle_shipwreck", "pj_quests_won_battle_shipwreck", true, function() mod.set_state(mod.states.after_shipwreck) end, true ) core:remove_listener("pj_quests_on_won_battle_shipwreck_remove_ironclad_cannon") core:add_listener( "pj_quests_on_won_battle_shipwreck_remove_ironclad_cannon", "pj_quests_won_battle_shipwreck", true, function() cm:remove_effect_bundle("pj_quests_empty_1", cm:get_local_faction(true)) end, true ) core:remove_listener("pj_quests_on_lost_battle_shipwreck_remove_ironclad_cannon") core:add_listener( "pj_quests_on_lost_battle_shipwreck_remove_ironclad_cannon", "pj_quests_lost_battle_shipwreck", true, function() cm:remove_effect_bundle("pj_quests_empty_1", cm:get_local_faction(true)) end, true )
--[[ Name: init.lua For: SantosRP By: TalosLife ]]-- AddCSLuaFile "cl_init.lua" AddCSLuaFile "shared.lua" include "shared.lua" function ENT:Initialize() self:SetModel( "models/props/cs_office/radio.mdl" ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) self:PhysWake() end function ENT:AcceptInput( strName, entActivator, entCaller ) if not IsValid( entCaller ) or not entCaller:IsPlayer() or strName ~= "Use" then return end if CurTime() > (self.m_intLastUsed or 0) then GAMEMODE.Net:NetworkOpenRadioMenu( entCaller ) self.m_intLastUsed = CurTime() +1 end end function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end
--[[------------------------------------------------------ h1. bt.Ground Create a simple solid shape representing the ground. --]]------------------------------------------------------ function bt.Ground(restitution) local groundShape = bt.StaticPlaneShape(bt.Vector3(0,1,0),1) local groundMotionState = bt.DefaultMotionState( bt.Transform( bt.Quaternion(0,0,0,1), bt.Vector3(0,0,0) ) ) local groundRigidBodyCI = bt.RigidBody.RigidBodyConstructionInfo( 0, groundMotionState, groundShape, bt.Vector3(0,0,0) ) groundRigidBodyCI.m_restitution = restitution or 1.0 return bt.RigidBody(groundRigidBodyCI) end
local _M = {} local cjson = require 'cjson' local dyups = require 'ngx.dyups' function _M.split(str, separator, max, regex) assert(separator ~= '') assert(max == nil or max >= 1) local record = {} if str:len() > 0 then local plain = not regex max = max or -1 local field=1 start=1 local first, last = str:find(separator, start, plain) while first and max ~= 0 do record[field] = str:sub(start, first - 1) field = field + 1 start = last + 1 first, last = str:find(separator, start, plain) max = max - 1 end record[field] = str:sub(start) end return record end function _M.set_upstream(backend_name, servers_str) local status, err = dyups.update(backend_name, servers_str) if status ~= ngx.HTTP_OK then return false end return true end function _M.real_key(key) local subs = _M.split(key, '/') return subs[#subs] end function _M.servers_str(servers) local server_pattern = "server %s %s;" local data = {} for i = 1, #servers do local backend = _M.real_key(servers[i]['key']) local addition = servers[i]['value'] table.insert(data, string.format(server_pattern, backend, addition)) end return table.concat(data, '\n') end function _M.load_data(data) if not data or not data['node'] or not data['node']['nodes'] then return nil end return data['node']['nodes'] end function _M.read_data() ngx.req.read_body() local data = ngx.req.get_body_data() if not data then ngx.exit(ngx.HTTP_BAD_REQUEST) end return data end function _M.say_msg_and_exit(status, message) if status == ngx.HTTP_OK then if type(message) == 'table' then ngx.say(cjson.encode(message)) else ngx.say(cjson.encode({msg=message})) end end ngx.exit(status) end return _M
-- LTSpice parser utilities local type = type local getmetatable = getmetatable local setmetatable = setmetatable local tonumber = tonumber local tostring = tostring local table = table local io = io local math = math local winapi = require("winapi") -- To convert UTF16 to UTF8 encoding local vstruct = require("vstruct") -- To read the binary byte data local print = print -- Create the module table here local M = {} package.loaded[...] = M _ENV = M -- Lua 5.2+ _VERSION = "1.21.07.08" -- File handling functions -- To close the file local function close(fs) if not type(fs) == "table" or not getmetatable(fs) or not getmetatable(fs).v == _VERSION then return end local fsmeta = getmetatable(fs) if not fsmeta.fileHandle then return nil, "File already closed" end fsmeta.fileHandle:close() fsmeta.fileHandle = nil return true end -- Function to read the transient data -- Function to read the transient plot data -- fs is the file structure -- vars are the list of variables for which the data is required -- start is the starting time - all data >= this time is returned -- stop is the stop time - all data <= this time is returned -- maxpoints is the maximum number of points to be returned. If nil then all points returned local function read_transient(fs,vars,start,stop,maxpoints) if not type(vars) == "table" then return nil,"2nd argument should be list of variables whose data needs to be extracted." end local data = {[0]={}} local fm = getmetatable(fs) local fH = fm.fileHandle if not fH then return nil, "File already closed" end local offset = {} -- To store the data offsets -- Each offset should correspond to the vars entry for i = 1,#vars do offset[i] = 0 end for i = #vars,1,-1 do local found for j = 1,#fs.vars do if fs.vars[j] == vars[i] then found = true offset[i] = j-1 break end end if not found then table.remove(vars,i) table.remove(offset,i) end end if #vars == 0 then return nil,"No waves found!" end for i = 1,#offset do data[i] = {} end -- Do a binary search to find starting time point local chunkSize = (#fs.vars-1)*4+8 -- 4 bytes of data and 8 bytes for time local st = fs.datapos local stp = fs.datapos + (fs.numpts-1)*chunkSize local function getTime(pos) fH:seek("set",pos) local dat = fH:read(chunkSize) return math.abs(vstruct.read("f8",dat:sub(1,8))[1]) end -- First either start or stop should lie in the file data local t1,t2,tmid,pts,midpos pts = fs.numpts t1 = getTime(st) t2 = getTime(stp) if not (start >= t1 and start <= t2) and not (stop >= t1 and stop <= t2) then return data -- start - stop range does not overlap with t1 - t2 end -- Update start/stop with the range that that exists in t1-t2 if start < t1 then start = t1 end if stop > t2 then stop = t2 end -- Now find the data position with first time >= start local found while not found do if start == t1 then found = st break end if start == t2 or pts == 2 then found = stp break end midpos = st+(math.ceil(pts/2)-1)*chunkSize tmid = getTime(midpos) if start == tmid then found = midpos break end if start > tmid then st = midpos t1 = tmid pts = pts - (math.ceil(pts/2)-1) else stp = midpos t2 = tmid pts = math.ceil(pts/2) end end -- found contains the point from where the data has to be extracted --found = fs.datapos fH:seek("set",found) local dat,time,done pts = 0 local tData = data[0] while not done do dat = fH:read(chunkSize) if not dat then break end time = math.abs(vstruct.read("f8",dat:sub(1,8))[1]) if time > stop then break end if time >= start then pts = pts + 1 tData[pts] = time -- Now read all the variable data for j = 1,#vars do data[j][pts] = vstruct.read("f4",dat:sub(9+(offset[j]-1)*4,12+(offset[j]-1)*4))[1] end if maxpoints and pts >= maxpoints then break end end end return data end -- Function to calculate the total energy supplied by integrating the power from t[start] to t[stop] -- fs is the file structure -- Vp is the array containing the +ve node voltages -- Vn is the array containing the -ve node voltages (OPTIONAL). If not given this is assumed as ground. -- I is the array containing the current -- t is the array containing the time points -- start is the start index from where the integral is to be calculated (default = 1) -- stop is the stop index up till where the integral will be done (default = #t) function getEnergy(fs,t,Vp,Vn,I,start,stop) local E = 0 local Pi,Pim1 start = start or 1 stop = stop or #t local function fPi1(i,Vp,Vn,I) return (Vp[i]-Vn[i])*I[i] end local function fPi2(i,Vp,Vn,I) return Vp[i]*I[i] end local fPi = fPi1 if not Vn then fPi = fPi2 end for i = start+1,stop do -- starting from start+1 since Pim1 takes the previous point Pi = fPi(i,Vp,Vn,I) Pim1 = fPi(i-1,Vp,Vn,I) E = E + 0.5*(Pi+Pim1)*(t[i]-t[i-1]) end return E end -- Function to calculate the RMS value of the given wave vector -- fs is the file structure -- wave is the vector containing the waveform data -- start is the start index from where the integral is to be calculated (default = 1) -- stop is the stop index up till where the integral will be done (default = #t) function getRMS(fs,t,wave,start,stop) local sum = 0 start = start or 1 stop = stop or #t for i = start+1,stop do sum = sum + (wave[i]^2)*(t[i]-t[i-1]) end -- Mean sqrt return math.sqrt(sum/(t[stop]-t[start])) end -- Function to calculate the efficiency from a transient simulation -- fs is the file structure -- inv is an array containing input voltage data -- ini is an array containing the input current data -- outv is an array containing the output voltage data -- outi is an array containing the output current data -- time is an array containing the corresponding time points function getEfficiency(fs,time,inv,ini,outv,outi) -- Now calculate the input Power local Pin = getEnergy(fs,time,inv,nil,ini) Pin = Pin/(time[#time]-time[1]) -- Now calculate the output Power local Pout = getEnergy(fs,time,outv,nil,outi) Pout = Pout/(time[#time]-time[1]) return Pout/Pin,Pout,Pin end -------------------------------------------------------------------------- local function readHeaderString(fH,header,lineNo,tag) return header[lineNo]:sub(#tag+1,-1):gsub("^%s*",""):gsub("%s*$","") end local function readHeaderFlags(fH,header,lineNo,tag) local fl = header[lineNo]:sub(#tag+1,-1):gsub("^%s*",""):gsub("%s*$","").." " local flags = {} for flag in fl:gmatch("(.-) ") do flags[#flags + 1] = flag end return flags end local function readHeaderNum(fH,header,lineNo,tag) local num = header[lineNo]:sub(#tag+1,-1):gsub("^%s*",""):gsub("%s*$","") return tonumber(num) end local function readHeaderVars(fh,header,lineNo,tag) local vars = {} local i = lineNo+1 local line = header[i] while line:match("^%s%s*%d%d*%s%s*%a[^%s]*") do vars[#vars + 1] = line:match("^%s%s*%d%d*%s%s*(%a[^%s]*)") i = i + 1 line = header[i] end return vars end -- Raw file parser rawParser = function(filename) -- File structure definition local fs = { title = "", date = "", plotname = "", flags = {}, vars = {}, numpts = 0, offset = 0, mode = "Transient", -- Support Transient, AC filetype = "binary", -- Binary or ascii datapos = 0 -- position in file from where data begins } local tagMap = { -- Key is the key of fs and value is the text in the beginning of line that contains that info in the raw file {"title", "Title:", readHeaderString}, {"date", "Date:", readHeaderString}, {"plotname", "Plotname:", readHeaderString}, {"flags", "Flags:", readHeaderFlags}, {"numpts", "No. Points:", readHeaderNum}, {"offset", "Offset:", readHeaderNum}, {"vars", "Variables:", readHeaderVars} } local dataTags = { {"Binary:%c","binary"}, -- Tag text, filetype string {"Values:%c","ascii"} } local modes = { "Transient", "AC", "FFT", "Noise" } local header = {} -- To store the decoded header lines local f,msg = io.open(filename,"rb") -- Assuming UTF-16LE encoding for the file if not f then return nil,msg end local fsmeta = { fileHandle = f, __index = { v = _VERSION, close = close, } } local line = f:read("L") header[#header+1] = line -- Note UTF-8 is backward compatible with ASCII so the ASCII characters will appear with the right codepoints local headerStr = winapi.encode(winapi.CP_UTF16,winapi.CP_UTF8,table.concat(header)) -- Function to check whether header has come to an end local checkEndHeader = function(l) for i = 1,#dataTags do if l:find(dataTags[i][1]) then return dataTags[i][2] end end return false end -- Parse the header while line and not checkEndHeader(headerStr) do --print(line) line = f:read("L") if line then header[#header+1] = line headerStr = winapi.encode(winapi.CP_UTF16,winapi.CP_UTF8,table.concat(header)) end end if not line then return nil,"Premature file end" end fs.filetype = checkEndHeader(headerStr) -- Split headerStr into decoded header lines if headerStr:sub(-1,-1) ~= "\n" then headerStr = headerStr.."\n" end header = {} for l in headerStr:gmatch("([^\n]-)\n") do header[#header + 1] = l end fs.datapos = f:seek()+1 -- +1 for UTF-16 code for j = 1,#header do for i = 1,#tagMap do if header[j]:find(tagMap[i][2],1,true) then fs[tagMap[i][1]] = tagMap[i][3](f,header,j,tagMap[i][2]) break end end end -- Set the mode for i = 1,#modes do if fs.plotname:find(modes[i]) then fs.mode = modes[i] break end end -- Check whether the file length is correct local size = f:seek("end") if size < fs.datapos+((#fs.vars-1)*4+8)*fs.numpts then return nil, "Incorrect file size. Expected: "..tostring(fs.datapos+((#fs.vars-1)*4+8)*fs.numpts).." got: "..tostring(size) end if fs.mode == "Transient" then fsmeta.__index.read = read_transient fsmeta.__index.getEfficiency = getEfficiency fsmeta.__index.getEnergy = getEnergy fsmeta.__index.getRMS = getRMS elseif fs.mode == "AC" then return nil,"AC file reading not added yet" elseif fs.mode == "FFT" then return nil,"FFT file reading not added yet" elseif fs.mode == "Noise" then return nil,"Noise file reading not added yet" else return nil,"Unknown file type" end return setmetatable(fs,fsmeta) end
local module = {} module.name = 'Mqtt' module.connected = false module.onReceive = nil local moduleConfig = nil local mq = nil local user_disconnect = false local function echo (text) print('['..module.name..'] '..text) end local function handle_message (conn, topic, data) echo ("Message received! Topic "..topic .. " data " .. data ) if(module.onReceive ~= nil) then module.onReceive(topic,data) end end function module.init(cnf) moduleConfig = cnf mq = mqtt.Client(cnf.nodeId,60,cnf.user, cnf.pwd) mq:on("message", handle_message) mq:on('offline',function(client) if (module.connected) then echo('Disconnected from broker!') if(user_disconnect == false) then echo('Will attempt reconnect in 10 sec.') tmr.create():alarm(10 * 1000, tmr.ALARM_SINGLE, module.connect) else module_disconnect = false end module.connected = false end end) mq:lwt(moduleConfig.nodeTopic,'offline',moduleConfig.defaultQos) end function module.connect() mq:connect(moduleConfig.host, moduleConfig.port, moduleConfig.secure, 0, function(con) echo('Connected to broker on '.. moduleConfig.host ..'!') module.connected = true mq:publish(moduleConfig.nodeTopic,'online',moduleConfig.defaultQos,0) for i=0,9 do if(moduleConfig.subscribeTopics[i] ~= nil) then mq:subscribe(moduleConfig.subscribeTopics[i],0, function(conn) echo("Successfully subscribed to " .. moduleConfig.subscribeTopics[i]) end) end end end, function(client,reason) echo('Cannot connect to broker on '.. moduleConfig.host .. ':' .. moduleConfig.port ..'. Reason ' .. reason) tmr.create():alarm(10 * 1000, tmr.ALARM_SINGLE, module.connect) module.connected = false end ) end function module.disconnect() user_disconnect = true mq:close() end function module.publish(topic,message,qos, retain) if(module.connected == false) then echo('Not connected to broker! Cannot publish yet!') return end if (qos == nil) then qos = moduleConfig.defaultQos end if (retain == nil) then retain = 0 end echo('Sending data to '..topic) return mq:publish(moduleConfig.topic .. '/'..topic,message,qos,retain,function (client) echo('Data sent!') end) end return module
local require = require local ej = require 'war3.enhanced_jass' local Math = require 'std.math' local Point = require 'std.point' local Timer = require 'war3.timer' local Text = require 'std.class'('Text') local Init, SetTrace, Scaling, Move, MoveSin, ComputeSinTrace, ComputeMin, UpdateText, IsExpired -- ex: Text:new{ -- text: 文字, -- loc: {x, y}, -- time: 秒數, -- mode: 移動模式, -- font_size: {字體最小值, 字體增大值, 字體最大值}, -- height: {基本高度, 增加高度(沒用填0), 最大高度}, -- offset(可選): {距離, 角度}, -- on_pulse(可選): 每個週期都會調用的函數, -- } function Text:_new(data) data._invalid_ = false data._object_ = ej.CreateTextTag() data.init = Init data.loc = Point:new(data.loc[1], data.loc[2]) -- NOTE: 如果輸入random會隨機弧度;若輸入角度會自動轉換成弧度,這樣方便使用者填入,畢竟正常都用角度。 if data.offset then local angle = (data.offset[2] == 'random') and ej.GetRandomReal(0, 2 * Math.pi) or Math.rad(data.offset[2]) data.offset = Point:new(data.offset[1] * Math.cos(angle), data.offset[1] * Math.sin(angle)) end SetTrace(data) return data end Init = function(self) local TIME_FADE = 0.3 ej.SetTextTagText(self._object_, self.text, self.font_size[1]) ej.SetTextTagPos(self._object_, self.loc.x, self.loc.y, self.height[1]) -- 設置結束點、淡出動畫時間 ej.SetTextTagPermanent(self._object_, self.time > 0 and false or true) ej.SetTextTagLifespan(self._object_, self.time) ej.SetTextTagFadepoint(self._object_, TIME_FADE) end SetTrace = function(self) if self.mode == 'fix' then -- 原地縮放 self.update = Scaling elseif self.mode == 'move' then -- 移動 self.update = Move elseif self.mode == 'sin' then -- 正弦移動 self.update = MoveSin end end Scaling = function(self, runtime) ej.SetTextTagText(self._object_, self.text, ComputeMin(self.font_size, runtime)) end Move = function(self, runtime) -- 更新位置 local displacement = self.offset * runtime local loc = self.loc + displacement UpdateText(self, loc, ComputeMin(self.font_size, runtime), ComputeMin(self.height, runtime)) loc:remove() displacement:remove() end ComputeMin = function(x, t) return Math.min(x[1] + x[2] * t, x[3]) end MoveSin = function(self, runtime) -- 更新位置 local displacement = self.offset * runtime local loc = self.loc + displacement UpdateText( self, loc, ComputeSinTrace(self.font_size, self.time, runtime), ComputeSinTrace(self.height, self.time, runtime) ) loc:remove() displacement:remove() end ComputeSinTrace = function(x, max, t) return (x[3] - x[1]) * Math.sin(Math.pi * t / max) + x[1] end UpdateText = function(self, loc, font_size, height) ej.SetTextTagText(self._object_, self.text, font_size) ej.SetTextTagPos(self._object_, loc.x, loc.y, height) end function Text:_remove() ej.DestroyTextTag(self._object_) self.loc:remove() if self.offset then self.offset:remove() end end function Text:start() local PERIOD = 0.04 self:init() self._timer_ = Timer:new( PERIOD, (self.time > 0) and self.time / PERIOD or -1, function(timer) -- NOTE: 一定要放在update前面,不然on_pulse如果有更新文字之類的動作,本次週期不會更新。 if self.on_pulse then self:on_pulse(timer) end self:update(timer:getRuntime()) if IsExpired(self, timer.count_) then self._timer_:stop() self:remove() end end ):start() return self end IsExpired = function(self, count) return self._invalid_ or count == 1 end function Text:stop() self._invalid_ = true return self end function Text:setText(text) self.text = text return self end return Text
monitoring.wrap_global({"minetest", "find_nodes_in_area"}, "find_nodes_in_area") monitoring.wrap_global({"minetest", "find_node_near"}, "find_node_near") monitoring.wrap_global({"minetest", "get_objects_inside_radius"}, "get_objects_inside_radius") monitoring.wrap_global({"minetest", "check_player_privs"}, "check_player_privs") monitoring.wrap_global({"minetest", "get_craft_result"}, "get_craft_result") monitoring.wrap_global({"minetest", "get_craft_recipe"}, "get_craft_recipe") monitoring.wrap_global({"minetest", "get_all_craft_recipes"}, "get_all_craft_recipes") -- call intensive functions, only enable if explicitly set if minetest.settings:get_bool("monitoring.verbose") then monitoring.wrap_global({"minetest", "add_entity"}, "add_entity") monitoring.wrap_global({"minetest", "add_item"}, "add_item") monitoring.wrap_global({"minetest", "add_node"}, "add_node") monitoring.wrap_global({"minetest", "add_particle"}, "add_particle") monitoring.wrap_global({"minetest", "add_particlespawner"}, "add_particlespawner") monitoring.wrap_global({"minetest", "get_node"}, "get_node") monitoring.wrap_global({"minetest", "get_node_or_nil"}, "get_node_or_nil") monitoring.wrap_global({"minetest", "get_meta"}, "get_meta") monitoring.wrap_global({"minetest", "swap_node"}, "swap_node") monitoring.wrap_global({"minetest", "load_area"}, "load_area") monitoring.wrap_global({"minetest", "get_voxel_manip"}, "get_voxel_manip") monitoring.wrap_global({"minetest", "set_node"}, "set_node") monitoring.wrap_global({"minetest", "find_path"}, "find_path") monitoring.wrap_global({"minetest", "check_for_falling"}, "check_for_falling") end
local inn = require 'inn.env' local utils = {} -- a script to simplify trained net by incorporating every Spatial/VolumetricBatchNormalization -- to Spatial/VolumetricConvolution and BatchNormalization to Linear local function BNtoConv(net) for i,v in ipairs(net.modules) do if v.modules then BNtoConv(v) else local cur = v local pre = net:get(i-1) if pre and ((torch.typename(cur):find'nn.SpatialBatchNormalization' and torch.typename(pre):find'nn.SpatialConvolution') or (torch.typename(cur):find'nn.BatchNormalization' and torch.typename(pre):find'nn.Linear') or (torch.typename(cur):find'nn.VolumetricBatchNormalization' and torch.typename(pre):find'nn.VolumetricConvolution')) then local conv = pre local bn = v net:remove(i) local no = conv.weight:size(1) local conv_w = conv.weight:view(no,-1) local fold = function() local invstd = bn.running_var and (bn.running_var + bn.eps):pow(-0.5) or bn.running_std if not conv.bias then conv.bias = bn.running_mean:clone():zero() conv.gradBias = conv.bias:clone() end conv_w:cmul(invstd:view(no,-1):expandAs(conv_w)) conv.bias:add(-1,bn.running_mean):cmul(invstd) if bn.affine then conv.bias:cmul(bn.weight):add(bn.bias) conv_w:cmul(bn.weight:view(no,-1):expandAs(conv_w)) end if conv.resetWeightDescriptors then conv:resetWeightDescriptors() assert(conv.biasDesc) end end if cutorch and conv_w.getDevice then cutorch.withDevice(conv_w:getDevice(),fold) else fold() end end end end end local checklist = { 'nn.SpatialBatchNormalization', 'nn.VolumetricBatchNormalization', 'nn.BatchNormalization', 'cudnn.SpatialBatchNormalization', 'cudnn.VolumetricBatchNormalization', 'cudnn.BatchNormalization', } function utils.foldBatchNorm(net) -- works in place! BNtoConv(net) BNtoConv(net) for i,v in ipairs(checklist) do local modules = net:findModules(v) if #modules > 0 then print('Couldnt fold these:', modules) end end end function utils.BNtoFixed(net, ip) local net = net:replace(function(x) if torch.typename(x):find'BatchNormalization' then local no = x.running_mean:numel() local y = inn.ConstAffine(no, ip):type(x.running_mean:type()) assert(x.running_var and not x.running_std) local invstd = x.running_var:double():add(x.eps):pow(-0.5):cuda() y.a:copy(invstd) y.b:copy(-x.running_mean:double():cmul(invstd:double())) if x.affine then y.a:cmul(x.weight) y.b:cmul(x.weight):add(x.bias) end return y else return x end end ) assert(#net:findModules'nn.SpatialBatchNormalization' == 0) assert(#net:findModules'nn.BatchNormalization' == 0) assert(#net:findModules'cudnn.SpatialBatchNormalization' == 0) assert(#net:findModules'cudnn.BatchNormalization' == 0) return net end function utils.testSurgery(input, f, net, ...) local output1 = net:forward(input):clone() f(net,...) local output2 = net:forward(input):clone() local err = (output1 - output2):abs():max() return err end return utils
require("std/orklib") inspect = require("std/inspect") local s = ork.getscene(); printf("Hello world, from %s yo.",_VERSION) --printf( "Lua Initializing scene NumEnt<%d>",s:NumEntities() ) ------------------------------------- function OnSceneCompose() printf("OnSceneCompose()") end ------------------------------------- function OnSceneLink() printf("OnSceneLink()") end ------------------------------------- function OnSceneStart() printf("OnSceneStart()") end ------------------------------------- function OnSceneStop() printf("OnSceneStop()") end ------------------------------------- function OnSceneUnLink() printf("OnSceneUnLink()") end ------------------------------------- spawned = 0 myents = {} function OnSceneUpdate(dt,gt) local r = math.random(100) if r>91 then --printf( "SPAWN %d", spawned) local ent = s:spawn("/arch/ball","dynaentXZ"..spawned) myents[gt]=ent spawned = spawned+1 end for k,v in pairs(myents) do local age = gt-k; if age > 6.0 then s:despawn(v); myents[k]=nil end end --printf( "OnSceneUpdate") --printf( "///////////////////////////") end -------------------------------------
----------------------------------- -- Ability: Warcry ----------------------------------- require("scripts/globals/monstertpmoves") require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function OnMobSkillCheck(target, mob, skill) return 0 end function OnMobWeaponSkill(target, mob, skill) local power = 25 local duration = 180 local typeEffect = tpz.effect.WARCRY skill:setMsg(MobBuffMove(mob, typeEffect, power, 0, duration)) return typeEffect end
---- Roleplay: Prison timer.Create("HungerTick", 24.0, 0, function() local AllPlayers = player.GetAll() for Index, Player in ipairs(AllPlayers) do if Player:Team() == TEAM_ROBBER or Player:Team() == TEAM_GUARD then local HungerMultiplier = 0.5 if Player:Team() == TEAM_GUARD and UtilCheckPlayerInArea(Player, GuardRestArea) then MsgN(Format("Hunger tick for %s in rest area", Player)) Player:SetArmor(math.Clamp(Player:Armor() + 15, 0, Player:GetMaxArmor())) HungerMultiplier = 0.0 elseif UtilCheckPlayerInArea(Player, PunishmentArea) then HungerMultiplier = 3.0 end if Player.Food >= 1 * HungerMultiplier then Player.Food = Player.Food - 1 * HungerMultiplier else Player.Food = 0 end if Player.Water >= 2 * HungerMultiplier then Player.Water = Player.Water - 2 * HungerMultiplier else Player.Water = 0 end if Player.Food < 20 or Player.Water < 20 then if Player:Health() > 15 then Player:SetHealth(Player:Health() - 1) end elseif Player.Food > 50 and Player.Water > 50 then if Player:Health() < 100 then Player:SetHealth(math.Clamp(Player:Health() + 5, 0, Player:GetMaxHealth())) end end UpdatePlayerHungerValue(Player) end end end) hook.Add("OnEntityCreated", "NutritionSpawn", function(InEntity) timer.Simple(0.1, function() if not IsValid(InEntity) then return end --MsgN(InEntity:GetName()) if string.EndsWith(InEntity:GetName(), "_FoodInstance") then InEntity:SetNWBool("bFoodInstance", true) InEntity:SetNWBool("bShowHint", true) elseif string.EndsWith(InEntity:GetName(), "_WaterInstance") then InEntity:SetNWBool("bWaterInstance", true) InEntity:SetNWBool("bShowHint", true) end end) end) hook.Add("OnPlayerPhysicsPickup", "NutritionPickup", function(InPlayer, InEntity) if InEntity:GetNWBool("bFoodInstance") or InEntity:GetNWBool("bWaterInstance") then InEntity:SetNWBool("bShowHint", false) end end) hook.Add("OnPlayerPhysicsDrop", "NutritionDrop", function(InPlayer, InEntity, bThrown) if InEntity:GetNWBool("bFoodInstance") or InEntity:GetNWBool("bWaterInstance") then InEntity:SetNWBool("bShowHint", true) end end) function UpdatePlayerHungerValue(InPlayer) InPlayer.Food = math.Clamp(InPlayer.Food, 0.0, 100.0) InPlayer.Water = math.Clamp(InPlayer.Water, 0.0, 100.0) --MsgN(Format("%s Food: %i, Water: %s", InPlayer:GetNWString("RPName"), InPlayer.Food, InPlayer.Water)) InPlayer:SetNWFloat("HungerValue", 1.0 - math.Clamp((InPlayer.Food + InPlayer.Water) * 2, 0, 200) / 200) end function AddNutrition(InPlayer, InValue, bFood) if bFood then InPlayer.Food = InPlayer.Food + InValue else InPlayer.Water = InPlayer.Water + InValue end UpdatePlayerHungerValue(InPlayer) end function OnNutritionSpawn(InPlayer, InTemplateEntity) local NutritionInstance = ents.Create("prop_physics") if InTemplateEntity:GetNWBool("bFoodSpawn") then NutritionInstance:SetName("Spawned_FoodInstance") else NutritionInstance:SetName("Spawned_WaterInstance") end NutritionInstance:SetPos(InTemplateEntity:GetPos() + Vector(0.0, 0.0, 16.0)) NutritionInstance:SetAngles(InTemplateEntity:GetAngles()) NutritionInstance:SetModel(InTemplateEntity:GetModel()) NutritionInstance:Spawn() --[[ if InTemplateEntity:GetNWBool("bFoodSpawn") then NutritionInstance:SetNWBool("bFoodInstance", true) else NutritionInstance:SetNWBool("bWaterInstance", true) end NutritionInstance:SetNWBool("bShowHint", true) --]] InPlayer:PickupObject(NutritionInstance) end function OnNutritionConsume(InPlayer, InNutritionInstance) if InNutritionInstance:GetNWBool("bFoodInstance") then AddNutrition(InPlayer, 60, true) InPlayer:EmitSound("Watermelon.BulletImpact") elseif InNutritionInstance:GetNWBool("bWaterInstance") then AddNutrition(InPlayer, 60, false) InPlayer:EmitSound("Water.BulletImpact") end InNutritionInstance:Remove() end
--[[ Sequence to sequence model with attention. ]] local Seq2Seq, parent = torch.class('Seq2Seq', 'Model') local options = { -- main network {'-layers', 2, [[Number of layers in the RNN encoder/decoder]], {valid=onmt.utils.ExtendedCmdLine.isUInt()}}, {'-rnn_size', 500, [[Size of RNN hidden states]], {valid=onmt.utils.ExtendedCmdLine.isUInt()}}, {'-rnn_type', 'LSTM', [[Type of RNN cell]], {enum={'LSTM','GRU'}}}, {'-word_vec_size', 0, [[Common word embedding size. If set, this overrides -src_word_vec_size and -tgt_word_vec_size.]], {valid=onmt.utils.ExtendedCmdLine.isUInt()}}, {'-src_word_vec_size', '500', [[Comma-separated list of source embedding sizes: word[,feat1,feat2,...].]]}, {'-tgt_word_vec_size', '500', [[Comma-separated list of target embedding sizes: word[,feat1,feat2,...].]]}, {'-feat_merge', 'concat', [[Merge action for the features embeddings]], {enum={'concat','sum'}}}, {'-feat_vec_exponent', 0.7, [[When features embedding sizes are not set and using -feat_merge concat, their dimension will be set to N^exponent where N is the number of values the feature takes.]]}, {'-feat_vec_size', 20, [[When features embedding sizes are not set and using -feat_merge sum, this is the common embedding size of the features]], {valid=onmt.utils.ExtendedCmdLine.isUInt()}}, {'-input_feed', 1, [[Feed the context vector at each time step as additional input (via concatenation with the word embeddings) to the decoder.]], {enum={0,1}}}, {'-residual', false, [[Add residual connections between RNN layers.]]}, {'-brnn', false, [[Use a bidirectional encoder]]}, {'-brnn_merge', 'concat', [[Merge action for the bidirectional hidden states]], {enum={'concat','sum'}}}, {'-pre_word_vecs_enc', '', [[If a valid path is specified, then this will load pretrained word embeddings on the encoder side. See README for specific formatting instructions.]], {valid=onmt.utils.ExtendedCmdLine.fileNullOrExists}}, {'-pre_word_vecs_dec', '', [[If a valid path is specified, then this will load pretrained word embeddings on the decoder side. See README for specific formatting instructions.]], {valid=onmt.utils.ExtendedCmdLine.fileNullOrExists}}, {'-fix_word_vecs_enc', false, [[Fix word embeddings on the encoder side]]}, {'-fix_word_vecs_dec', false, [[Fix word embeddings on the decoder side]]}, {'-dropout', 0.3, [[Dropout probability. Dropout is applied between vertical LSTM stacks.]]}, -- the following options are used for adding context to input word embedding {'-gate', false, [[Use the gating mechanism for adding context vector]]}, {'-concat', false, [[Use the concat mechanism for adding context vector]]}, -- type of contextNetwork that is used to generate the context vector {'-gating_type', 'contextBiEncoder', [[ContextNetwork to generate the context vector]], {enum={'contextBiEncoder', 'leave_one_out', 'conv', 'cbow'}}}, {'-share', false, [[share contextnet lookupTable with encoder]]}, -- options for contextNetwork = biencoder {'-gating_layers', 1, [[Number of layers in the RNN encoder/decoder]], {valid=onmt.utils.ExtendedCmdLine.isUInt()}}, {'-gating_rnn_size', 500, [[Size of RNN hidden states]], {valid=onmt.utils.ExtendedCmdLine.isUInt()}}, {'-gating_rnn_type', 'LSTM', [[Type of RNN cell]], {enum={'LSTM','GRU'}}}, {'-gating_word_vec_size', 0, [[Common word embedding size. If set, this overrides -src_word_vec_size and -tgt_word_vec_size.]], {valid=onmt.utils.ExtendedCmdLine.isUInt()}}, {'-gating_src_word_vec_size', '500', [[Comma-separated list of source embedding sizes: word[,feat1,feat2,...].]]}, {'-gating_tgt_word_vec_size', '500', [[Comma-separated list of target embedding sizes: word[,feat1,feat2,...].]]}, {'-gating_feat_merge', 'concat', [[Merge action for the features embeddings]], {enum={'concat','sum'}}}, {'-gating_feat_vec_exponent', 0.7, [[When features embedding sizes are not set and using -feat_merge concat, their dimension will be set to N^exponent where N is the number of values the feature takes.]]}, {'-gating_feat_vec_size', 20, [[When features embedding sizes are not set and using -feat_merge sum, this is the common embedding size of the features]], {valid=onmt.utils.ExtendedCmdLine.isUInt()}}, {'-gating_input_feed', 1, [[Feed the context vector at each time step as additional input (via concatenation with the word embeddings) to the decoder.]], {enum={0,1}}}, {'-gating_residual', false, [[Add residual connections between RNN layers.]]}, {'-gating_brnn', true, [[Use a bidirectional encoder]]}, {'-gating_brnn_merge', 'concat', [[Merge action for the bidirectional hidden states]], {enum={'concat','sum'}}}, {'-gating_pre_word_vecs_enc', '', [[If a valid path is specified, then this will load pretrained word embeddings on the encoder side. See README for specific formatting instructions.]], {valid=onmt.utils.ExtendedCmdLine.fileNullOrExists}}, {'-gating_pre_word_vecs_dec', '', [[If a valid path is specified, then this will load pretrained word embeddings on the decoder side. See README for specific formatting instructions.]], {valid=onmt.utils.ExtendedCmdLine.fileNullOrExists}}, {'-gating_fix_word_vecs_enc', false, [[Fix word embeddings on the encoder side]]}, {'-gating_fix_word_vecs_dec', false, [[Fix word embeddings on the decoder side]]}, {'-gating_dropout', 0.3, [[Dropout probability. Dropout is applied between vertical LSTM stacks.]]} } function Seq2Seq.declareOpts(cmd) cmd:setCmdLineOptions(options, Seq2Seq.modelName()) end function Seq2Seq:__init(args, dicts, verbose) parent.__init(self, args) onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options)) self.gate = args.gate self.concat = args.concat if self.gate or self.concat then self.models.gatingNetwork = onmt.Factory.buildGatingNetwork(args, dicts.src, verbose) self.gatingType = args.gating_type end self.models.encoder = onmt.Factory.buildWordEncoder(args, dicts.src, verbose) self.models.decoder = onmt.Factory.buildWordDecoder(args, dicts.tgt, verbose) self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt)) end function Seq2Seq.load(args, models, dicts, isReplica) local self = torch.factory('Seq2Seq')() parent.__init(self, args) onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options)) self.gate = args.gate self.concat = args.concat if self.gate or self.concat then self.models.gatingNetwork = onmt.Factory.loadGatingNetwork(models.gatingNetwork, isReplica) self.gatingType = args.gating_type end self.models.encoder = onmt.Factory.loadEncoder(models.encoder, isReplica) self.models.decoder = onmt.Factory.loadDecoder(models.decoder, isReplica) self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt)) return self end -- Returns model name. function Seq2Seq.modelName() return 'Sequence to Sequence with Attention' end -- Returns expected dataMode. function Seq2Seq.dataType() return 'bitext' end function Seq2Seq:enableProfiling() if self.gate or self.concat then _G.profiler.addHook(self.models.gatingNetwork, 'gatingNetwork') end _G.profiler.addHook(self.models.encoder, 'encoder') _G.profiler.addHook(self.models.decoder, 'decoder') _G.profiler.addHook(self.models.decoder.modules[2], 'generator') _G.profiler.addHook(self.criterion, 'criterion') end function Seq2Seq:getOutput(batch) return batch.targetOutput end function Seq2Seq:forwardComputeLoss(batch) local gatingEncStates = nil local gatingContext = nil if self.gate or self.concat then -- gatingContext: batch x rho x dim tensor if self.gatingType == 'contextBiEncoder' then gatingEncStates, gatingContext = self.models.gatingNetwork:forward(batch) elseif self.gatingType == 'leave_one_out' then gatingContext = {} for t = 1, batch.sourceLength do local gateInputBatch = onmt.utils.Tensor.deepClone(batch) gateInputBatch.sourceInput[t]:fill(onmt.Constants.DOL) local finalStates, context = self.models.gatingNetwork:forward(gateInputBatch) table.insert(gatingContext, finalStates[#finalStates]) -- gatingContext then becomes rho x batch x dim -> need to transpose later end gatingContext = torch.cat(gatingContext, 1):resize(batch.sourceLength, batch.size, self.models.gatingNetwork.args.rnnSize) gatingContext = gatingContext:transpose(1,2) -- swapping dim1 with dim2 -> batch x rho x dim elseif self.gatingType == 'conv' then gatingContext = self.models.gatingNetwork:forward(batch) elseif self.gatingType == 'cbow' then gatingVector = self.models.gatingNetwork:forward(batch) local replica = nn.Replicate(batch.sourceLength, 2) if #onmt.utils.Cuda.gpuIds > 0 then replica:cuda() end gatingContext = replica:forward(gatingVector) end batch:setGateTensor(gatingContext) end local encoderStates, context = self.models.encoder:forward(batch) return self.models.decoder:computeLoss(batch, encoderStates, context, self.criterion) end function Seq2Seq:trainNetwork(batch, dryRun) local rnnSize = nil local gatingEncStates = nil local gatingContext = nil if self.gate or self.concat then rnnSize = self.models.gatingNetwork.args.rnnSize -- gatingContext: batch x rho x dim tensor if self.gatingType == 'contextBiEncoder' then rnnSize = self.models.gatingNetwork.args.rnnSize * 2 gatingEncStates, gatingContext = self.models.gatingNetwork:forward(batch) elseif self.gatingType == 'leave_one_out' then rnnSize = self.models.gatingNetwork.args.rnnSize gatingContext = {} for t = 1, batch.sourceLength do local gateInputBatch = onmt.utils.Tensor.deepClone(batch) gateInputBatch.sourceInput[t]:fill(onmt.Constants.DOL) local finalStates, context = self.models.gatingNetwork:forward(gateInputBatch) table.insert(gatingContext, finalStates[#finalStates]) -- gatingContext then becomes rho x batch x dim -> need to transpose later end gatingContext = torch.cat(gatingContext, 1):resize(batch.sourceLength, batch.size, self.models.gatingNetwork.args.rnnSize) gatingContext = gatingContext:transpose(1,2) -- swapping dim1 with dim2 -> batch x rho x dim elseif self.gatingType == 'conv' then gatingContext = self.models.gatingNetwork:forward(batch) elseif self.gatingType == 'cbow' then rnnSize = self.models.gatingNetwork.args.rnnSize gatingVector = self.models.gatingNetwork:forward(batch) local replica = nn.Replicate(batch.sourceLength, 2) if #onmt.utils.Cuda.gpuIds > 0 then replica:cuda() end gatingContext = replica:forward(gatingVector) end batch:setGateTensor(gatingContext) end -- setSourceInput local encStates, context = self.models.encoder:forward(batch) local decOutputs = self.models.decoder:forward(batch, encStates, context) if dryRun then decOutputs = onmt.utils.Tensor.recursiveClone(decOutputs) end local encGradStatesOut, gradContext, loss = self.models.decoder:backward(batch, decOutputs, self.criterion) local gradInputs = self.models.encoder:backward(batch, encGradStatesOut, gradContext) if self.gate or self.concat then if self.gatingType == 'contextBiEncoder' then local gradGatingContext = torch.Tensor(batch.size, batch.sourceLength, rnnSize):zero() if #onmt.utils.Cuda.gpuIds > 0 then gradGatingContext = gradGatingContext:cuda() end for t = 1, batch.sourceLength do gradGatingContext[{{}, t, {}}] = gradInputs[t][2] end self.models.gatingNetwork:backward(batch, nil, gradGatingContext) elseif self.gatingType == 'conv' then local gradGatingContext = torch.Tensor(batch.size, batch.sourceLength, 600):zero() if #onmt.utils.Cuda.gpuIds > 0 then gradGatingContext = gradGatingContext:cuda() end for t = 1, batch.sourceLength do gradGatingContext[{{}, t, {}}] = gradInputs[t][2] end self.models.gatingNetwork:backward(batch, gradGatingContext) elseif self.gatingType == 'cbow' then local gradGatingContext = torch.Tensor(batch.size, batch.sourceLength, rnnSize):zero() if #onmt.utils.Cuda.gpuIds > 0 then gradGatingContext = gradGatingContext:cuda() end for t = 1, batch.sourceLength do gradGatingContext[{{}, t, {}}] = gradInputs[t][2] end gradGatingVector = torch.sum(gradGatingContext, 2):squeeze(2) self.models.gatingNetwork:backward(batch, gradGatingVector) elseif self.gatingType == 'leave_one_out' then local gradStates = {} local gradContext for t = batch.sourceLength, 1, -1 do local gateInputBatch = onmt.utils.Tensor.deepClone(batch) gateInputBatch.sourceInput[t]:fill(onmt.Constants.DOL) local gradStates = torch.Tensor() gradStates = onmt.utils.Tensor.initTensorTable(self.models.gatingNetwork.args.numEffectiveLayers, gradStates, { batch.size, rnnSize }) local gradGatingContext = torch.Tensor(batch.size, batch.sourceLength, rnnSize):zero() gradStates[#gradStates] = gradInputs[t][2] if #onmt.utils.Cuda.gpuIds > 0 then for s = 1, #gradStates do gradStates[s] = gradStates[s]:cuda() gradGatingContext = gradGatingContext:cuda() end end self.models.gatingNetwork:backward(gateInputBatch, gradStates, gradGatingContext) end end end return loss end return Seq2Seq
require "upgrade_ptr_to_ref" node_id_cfgs = {} NodeIdFinder = {} function NodeIdFinder.new(tctx, node_descriptions) local self = {} self.tctx = tctx self.node_descriptions = node_descriptions setmetatable(self, NodeIdFinder) NodeIdFinder.__index = NodeIdFinder return self end function NodeIdFinder:flatten_stmt(fn, stmt, i) if stmt:kind_name() == "Local" then local locl = stmt:child(1) local pat = locl:get_pat() local pat_kind = pat:get_kind() local pat_ident = tostring(pat_kind:child(2):get_name()) if fn.locl and fn.locl[pat_ident] then node_id_cfgs[locl:get_id()] = fn.locl[pat_ident] end -- "Flatten" stmts elseif stmt:child(1):kind_name() == "While" then local block = stmt:child(1):get_kind():child(2) local stmts = block:get_stmts() for _, stmt in ipairs(stmts) do self:flatten_stmt(fn, stmt, i) i = i + 1 end end if fn.stmt and fn.stmt[i] then node_id_cfgs[stmt:get_id()] = fn.stmt[i] end end function NodeIdFinder:flat_map_item(item, walk) local kind_name = item:kind_name() local ident = tostring(item:get_ident():get_name()) local item_kind = item:get_kind() if kind_name == "Fn" then local fn_desc = self.node_descriptions["fn"] local fn = fn_desc[ident] if fn then local fn_sig = item_kind:child(1) local fn_decl = fn_sig:get_decl() local params = fn_decl:get_inputs() for _, param in ipairs(params) do local pat = param:get_pat() local pat_kind = pat:get_kind() local pat_ident = tostring(pat_kind:child(2):get_name()) if fn.param[pat_ident] then node_id_cfgs[param:get_id()] = fn.param[pat_ident] end end local block = item_kind:child(3) local stmts = block:get_stmts() local i = 1 for _, stmt in ipairs(stmts) do self:flatten_stmt(fn, stmt, i) i = i + 1 end end elseif kind_name == "Struct" then local struct_desc = self.node_descriptions["struct"] local struct = struct_desc[ident] if struct then local fields = item_kind:child(1):child(1) for _, field in ipairs(fields) do local ident = tostring(field:get_ident():get_name()) if struct.field and struct.field[ident] then node_id_cfgs[field:get_id()] = struct.field[ident] end end end end walk(item) return {item} end node_descriptions = { fn = { ten_mul = { param = { acc = ConvConfig.new{"ref"}, r = ConvConfig.new{"ref"}, }, }, struct_ptr = { param = { ctx = ConvConfig.new{"ref"}, p = ConvConfig.new{"slice", mutability="immut"}, }, }, init_buf = { param = { sd = ConvConfig.new{"ref"}, }, locl = { buf = ConvConfig.new{"opt_box_slice"}, }, }, init_buf2 = { param = { sd = ConvConfig.new{"ref"}, }, locl = { buf = ConvConfig.new{"box_slice"}, }, }, destroy_buf = { param = { sd = ConvConfig.new{"ref"}, }, }, explicit_lifetimes = { param = { _ptrs = ConvConfig.new{"ref", lifetime="a"}, }, }, init_opt_item = { param = { hi = ConvConfig.new{"ref"}, }, locl = { ptr = ConvConfig.new{"box"}, }, }, init_opt_item2 = { param = { hi = ConvConfig.new{"ref"}, }, locl = { ptr = ConvConfig.new{"opt_box"}, } }, bm = { param = { hashp = ConvConfig.new{"ref"}, }, locl = { ip = ConvConfig.new{"box_slice", mutability="mut"}, }, }, bisearch_cat = { param = { table = ConvConfig.new{"slice"}, }, }, opt_params = { param = { p1 = ConvConfig.new{"opt_ref", mutability="mut"}, p2 = ConvConfig.new{"opt_ref", mutability="immut"}, p3 = ConvConfig.new{"opt_slice"}, }, }, byteswap = { param = { srcp = ConvConfig.new{"ref"}, destp = ConvConfig.new{"ref"}, }, stmt = { [2] = ConvConfig.new{"byteswap", 790, 808}, [3] = ConvConfig.new{"del"}, [4] = ConvConfig.new{"del"}, [5] = ConvConfig.new{"del"}, [7] = ConvConfig.new{"del"}, [8] = ConvConfig.new{"byteswap", 1014, 1042}, [9] = ConvConfig.new{"del"}, [10] = ConvConfig.new{"del"}, [11] = ConvConfig.new{"del"}, [12] = ConvConfig.new{"byteswap", 1242, 1270}, }, }, byteswap2 = { param = { hashp = ConvConfig.new{"ref"}, }, locl = { hdrp = ConvConfig.new{"box"}, -- FIXME: not a box }, stmt = { [3] = ConvConfig.new{"del"}, [4] = ConvConfig.new{"del"}, [5] = ConvConfig.new{"del"}, [6] = ConvConfig.new{"byteswap", 1400, 1400}, [7] = ConvConfig.new{"del"}, }, }, }, struct = { Ptrs = { field = { r = ConvConfig.new{"ref", lifetime="r"}, r2 = ConvConfig.new{"ref", lifetime="r"}, s = ConvConfig.new{"slice", lifetime="s"}, s2 = ConvConfig.new{"slice", lifetime="s"}, boxed = ConvConfig.new{"opt_box"}, }, }, SizedData = { field = { buf = ConvConfig.new{"opt_box_slice"}, }, }, HeapItem = { field = { item = ConvConfig.new{"box"}, opt_item = ConvConfig.new{"opt_box"}, }, }, HTab = { field = { mapp = ConvConfig.new{"opt_box_slice"}, }, }, HashHDR = { field = { bitmaps = ConvConfig.new{"array"}, spares = ConvConfig.new{"array"}, }, }, }, } refactor:transform( function(transform_ctx) -- transform_ctx:dump_crate() return transform_ctx:visit_crate_new(NodeIdFinder.new(transform_ctx, node_descriptions)) end ) run_ptr_upgrades(node_id_cfgs) refactor:save_crate() print("Finished test_run_ptr_upgrades.lua")
---------------------------- --class ZMath 这个类主要用于编写数学算法 -- @author 郑灶生 -- Creation 2014-12-17 local ZMath=class("ZMath",math) --求两点间的距离 function ZMath.dist(ax, ay, bx, by) local dx, dy = bx - ax, by - ay return math.sqrt(dx * dx + dy * dy) end --算圆周上的点 传入 角度 半径 及 圆弧的x坐标 function ZMath.getrx(angle,r,x) return ((r*(math.cos((angle*3.14)/180)))+x) end --算圆周上的点 传入 角度 半径 及 圆心的y坐标 function ZMath.getry(angle,r,y) return ((r*(math.sin((angle*3.14)/180)))+y) end --角色上下移动 flag 是否碰到上下点 function ZMath.fluctuateY (flag,role) local x,y=role:getPosition() -- local x,y=self.enemy:getPosition() if not flag then if y<(display.height-role:getContentSize().height) then y=y+1 else flag=true end else if y>0 then y=y-1 else flag=false end end role:setPosition(x,y) return flag end --角色上下移动 flags 是否碰到上下左右点 function ZMath.fluctuateXY (flags,role,boundaryx) local x,y=role:getPosition() local rand=math.random(2,4) if not flags.lr then if x<(display.width-role:getContentSize().width/2) then x=x+3 else flags.lr=true end else if x>boundaryx then x=x-3 else flags.lr=false end end if not flags.flag then if y<(display.height-role:getContentSize().height/2) then y=y+3 else flags.flag=true end else if y>role:getContentSize().height/2 then y=y-3 else flags.flag=false end end local my= (math.sin((((x+rand*5)%360)*3.14)/180))*2 role:setPosition(x,y+my) x=x+1 return flags end --两个盒子的碰撞检测 function ZMath.ifRam( x1,y1,width1,height1,x2,y2,width2,height2) if x1<=(x2+width2) and y1<=(y2+height2) and (x1+width1)>=x2 and (y1+height1)>=y2 then return true end return false end --[[-- 判断盒子是否出界 @function [parent=#src.zframework.utils.ZMath] ifRam @param box userdata 视图盒子 --]] function ZMath.ifRam(x,y,w,h) if w/2>x or h/2>y or (display.height-h/2)<y or (display.width-w/2)<x then return false end return true end --[[ function ZMath.ifRam(vx,vy,w,h) local x,y,w,h= ZMath.getPosAndSize(box) if w/2>x or h/2>y or (display.height-h/2)<y or (display.width-w/2)<x then return false end return true end --]] ----------------------- --获取盒子的坐标与大小 --@param box userdata 盒子 -- function ZMath.getPosAndSize(box) local x,y=box:getPosition() local size= box:getContentSize() local w,h=size.width,size.height return x,y,w,h end --计算开火的角度 function ZMath.getFireAngle(heroX,heroY,enemyX,enemyY) -- print("heroX,heroY"..heroX.." "..heroY) -- print("enemyX,enemyY"..enemyX.." ") local value=math.atan2(enemyY-heroY,enemyX-heroX) return -value*180/math.pi+90 end --------------------------- --从右边往左边开始查找 --@param input string 需要操作的字符串 --@param str string 需要查找的字符串 --@return #int 所在的位置 function ZMath.rIndexof(input,str) local pos = string.len(input) local spos = string.len(str) pos=pos-spos while pos > 0 do local st,sp=string.find(input, str, pos, true) -- print(st,sp) if st and sp then return st,sp end pos = pos - 1 end return 0,0 end --------------------------- --以某个下标分割字符串 --@param input string 需要操作的字符串 --@param index integer 下标 --@return string,string function ZMath.subscriptSplit(input,index) local start=string.sub(input,1,index-1) local ends=string.sub(input,index) return start,ends end return ZMath
----------------------------------------------------------- -- (c) 2020 Mustafa Erkam Badin -- ----------------------------------------------------------- -- Source: https://github.com/arthurealike/turtle.lua -- ----------------------------------------------------------- package.path = package.path .. ";../../turtle/?.lua" local Spider = require "turtle" local spider = Spider() local spiderweb = function(turtle) turtle:pendown() for i=1, 6 do turtle:speed(15):forward(150):backward(150):right(60) end local side = 150 for i=1, 15 do turtle:penup():speed(11) :pendown() :setheading(0) :forward(side) :right(120) for j=1, 6 do turtle:forward(side) turtle:right(60) end turtle:setheading(0):speed(15) turtle:backward(side) side = side - 30 end end function love.keypressed(key) if key == "space" then spider:toggle() elseif key == "c" then spider:clear() end end function love.load() love.window.setTitle("Spidey") spider:name("spidey"):setsprite("spider.png"):home():speed(15) spiderweb(spider) end function love.draw() spider:draw() end
local cjson = require "cjson" resp = ngx.location.capture('/__mesos_dns/v1/services/_' .. os.getenv("APP_NAME") .. '._tcp.marathon.mesos') backends = cjson.decode(resp.body) backend = backends[1] ngx.var.target = "http://" .. backend['ip'] .. ":" .. backend['port']
dofile("/opt/domoticz/scripts/parse_config.lua") debug = false commandArray = {} time = os.date("*t") minutes = time.min + time.hour * 60 if debug then print('light=' .. otherdevices[conf['lightIntensity']]) end if (tonumber(otherdevices[conf['lightIntensity']]) < tonumber(conf['switchOnLux'])) then switchOnLux = true else switchOnLux = false end if ((minutes > (timeofday['SunsetInMinutes']) or switchOnLux) and otherdevices[conf['atHome']] == 'On' and otherdevices[conf['eveningLights']] == 'Off' and otherdevices[conf['atSleep']] == 'Off' ) then commandArray[conf['eveningLightsScene']]='On' end if ((minutes < (timeofday['SunriseInMinutes']) or switchOnLux ) and otherdevices[conf['atHome']] == 'On' and otherdevices[conf['atSleep']] == 'Off' and otherdevices[conf['eveningLights']] == 'Off' ) then commandArray[conf['eveningLightsScene']]='On' end if (minutes > (timeofday['SunriseInMinutes']) and minutes < (timeofday['SunsetInMinutes']) and otherdevices[conf['eveningLights']] == 'On' ) then if ( otherdevices[conf['atHome']] == 'On' and switchOnLux ) then if debug then print('It is still dark. Do not turn off lights') end else commandArray[conf['eveningLightsScene']]='Off' end end if (otherdevices[conf['atHome']] == 'Off' ) then commandArray[conf['theRestScene']]='Off' end return commandArray
local vRPserver = Tunnel.getInterface("vRP", "cars") local vRPCarsS = Tunnel.getInterface("cars", "cars") local vRPCarsC = {} RegisterCommand( "transferownership", function(source, args, rawCommand) local buyerID = tonumber(args[1]) local ped = GetPlayerPed(-1) local model = vRP.EXT.Garage:getNearestOwnedVehicle(2) if model == nil then return end vRPCarsS._transferOwnership(buyerID, model) end )
local MinimapHelper = {} function MinimapHelper:WorldToMiniMap(pos, screenWidth, screenHeight) local screenH = screenHeight local screenW = screenWidth local MapLeft = -8000 local MapTop = 7350 local MapRight = 7500 local MapBottom = -7200 local mapWidth = math.abs(MapLeft - MapRight) local mapHeight = math.abs(MapBottom - MapTop) local x = pos:GetX() - MapLeft local y = pos:GetY() - MapBottom local dx, dy, px, py if self.Round(screenW / screenH, 1) >= 1.7 then dx = 272 / 1920 * screenW dy = 261 / 1080 * screenH px = 11 / 1920 * screenW py = 11 / 1080 * screenH elseif self.Round(screenW / screenH, 1) >= 1.5 then dx = 267 / 1680 * screenW dy = 252 / 1050 * screenH px = 10 / 1680 * screenW py = 11 / 1050 * screenH else dx = 255 / 1280 * screenW dy = 229 / 1024 * screenH px = 6 / 1280 * screenW py = 9 / 1024 * screenH end local minimapMapScaleX = dx / mapWidth local minimapMapScaleY = dy / mapHeight local scaledX = math.min(math.max(x * minimapMapScaleX, 0), dx) local scaledY = math.min(math.max(y * minimapMapScaleY, 0), dy) local screenX = px + scaledX local screenY = screenH - scaledY - py return Vector(math.floor(screenX - 20), math.floor(screenY - 12), 0) end function MinimapHelper.Round(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end return MinimapHelper
----------------------------------- -- Ability: Chain Affinity -- Makes it possible for your next "physical" blue magic spell to be used in a skillchain. Effect varies with TP. -- Obtained: Blue Mage Level 40 -- Recast Time: 2 minutes -- Duration: 30 seconds or one Blue Magic spell -- May be used with Sneak Attack and Trick Attack. ----------------------------------- require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function onAbilityCheck(player,target,ability) return 0,0 end function onUseAbility(player, target, ability) player:addStatusEffect(tpz.effect.CHAIN_AFFINITY,1,0,30) return tpz.effect.CHAIN_AFFINITY end
---@type MessageData local MessageData = Classes.MessageData Ext.RegisterNetListener("LeaderLib_EnableFeature", function(channel, id) Features[id] = true end) Ext.RegisterNetListener("LeaderLib_DisableFeature", function(channel, id) Features[id] = false end) Ext.RegisterNetListener("LeaderLib_SyncFeatures", function(call, dataString) if Features == nil then Features = {} end local data = Common.JsonParse(dataString) if data ~= nil then for k,b in pairs(data) do Features[k] = b end end end) local function SetGlobalSettingsMetatables() for _,v in pairs(GlobalSettings.Mods) do setmetatable(v, Classes.ModSettingsClasses.ModSettings) Classes.ModSettingsClasses.SettingsData.SetMetatables(v.Global) setmetatable(v.Global, Classes.ModSettingsClasses.SettingsData) for _,p in pairs(v.Profiles) do Classes.ModSettingsClasses.SettingsData.SetMetatables(p.Settings) setmetatable(p, Classes.ModSettingsClasses.ProfileSettings) setmetatable(p.Settings, Classes.ModSettingsClasses.SettingsData) end end end ---@param settings GlobalSettings local function SyncGlobalSettings(settings) if GlobalSettings ~= nil then local length = #Listeners.ModSettingsSynced GlobalSettings.Version = settings.Version for k,v in pairs(settings.Mods) do local target = v if GlobalSettings.Mods[k] == nil then GlobalSettings.Mods[k] = v else local existing = GlobalSettings.Mods[k] if existing.Global == nil then existing.Global = v.Global else existing.Global:CopySettings(v.Global) end if existing.Profiles == nil then existing.Profiles = v.Profiles else for k2,v2 in pairs(v.Profiles) do local existingProfile = existing.Profiles[k2] if existingProfile ~= nil then existingProfile.Settings:CopySettings(v2.Settings) else existing.Profiles[k2] = v2 end end end existing.Version = v.Version target = existing end if length > 0 then for i=1,length do local callback = Listeners.ModSettingsSynced[i] local status,err = xpcall(callback, debug.traceback, k, target) if not status then Ext.PrintError("[LeaderLib:HitListeners.lua] Error calling function for 'ModSettingsSynced':\n", err) end end end end PrintDebug("[LeaderLib:CLIENT] Updated GlobalSettings.") else Ext.PrintError("[LeaderLib:CLIENT] GlobalSettings is nil.") GlobalSettings = settings end SetGlobalSettingsMetatables() end Ext.RegisterNetListener("LeaderLib_SyncGlobalSettings", function(call, dataString) local settings = Common.JsonParse(dataString) if settings ~= nil then SyncGlobalSettings(settings) end end) Ext.RegisterNetListener("LeaderLib_SyncAllSettings", function(call, dataString) local data = Common.JsonParse(dataString) if data.Features ~= nil then Features = data.Features end if data.GlobalSettings ~= nil then SyncGlobalSettings(data.GlobalSettings) end if data.GameSettings ~= nil then GameSettings = data.GameSettings setmetatable(GameSettings, Classes.LeaderLibGameSettings) --SyncStatOverrides(GameSettings) end InvokeListenerCallbacks(Listeners.ModSettingsLoaded) end) Ext.RegisterNetListener("LeaderLib_SyncScale", function(call, payload) local data = Common.JsonParse(payload) if data.Scale then local obj = Ext.GetGameObject(data.Handle) or Ext.GetGameObject(data.UUID) if obj and obj.SetScale then obj:SetScale(data.Scale) end end end) ---@class StatusMovieClip ---@field setTurns fun(turns:string) Set the turns text. ---@field setCooldown fun(turns:number) Set the turn display border. ---@class StatusMovieClipTable ---@field Status EsvStatus ---@field MC StatusMovieClip ---@param character EclCharacter The player. ---@param matchStatus string|table<string,bool>|nil An optional status to look for. ---@return StatusMovieClipTable[] local function GetPlayerStatusMovieClips(character, matchStatus) local statusMovieclips = {} local ui = Ext.GetBuiltinUI("Public/Game/GUI/playerInfo.swf") if ui ~= nil then local root = ui:GetRoot() if root ~= nil then local playerHandle = Ext.HandleToDouble(character.Handle) local player_mc = nil --root.getPlayerOrSummonByHandle(playerHandle) for i=0,#root.player_array,1 do local mc = root.player_array[i] if mc ~= nil then if mc.characterHandle == playerHandle then player_mc = mc break end end end if player_mc ~= nil then for i=0,#player_mc.status_array,1 do local status_mc = player_mc.status_array[i] if status_mc ~= nil then local handle = Ext.DoubleToHandle(status_mc.id) if handle ~= nil then local statusObj = Ext.GetStatus(character.NetID, handle) or {} --print(string.format("[%i] id(%s) name(%s) iconId(%s) tooltip(%s) handle(%s) StatusId(%s)", i, status_mc.id, status_mc.name, status_mc.iconId, status_mc.tooltip, handle, statusObj.StatusId)) if statusObj ~= nil then if matchStatus == nil then table.insert(statusMovieclips, {Status=statusObj, MC = status_mc}) else if type(matchStatus) == "table" then if matchStatus[statusObj.StatusId] == true then table.insert(statusMovieclips, {Status=statusObj, MC = status_mc}) end elseif statusObj.StatusId == matchStatus then table.insert(statusMovieclips, {Status=statusObj, MC = status_mc}) end end end end end end else error(string.format("[LeaderLib:RefreshStatusTurns] Failed to find player MC for %s", character.MyGuid), 1) end end end return statusMovieclips end local function RefreshStatusTurns(data) if data.UUID ~= nil and data.Status ~= nil then ---@type EclCharacter local character = Ext.GetCharacter(data.UUID) if character ~= nil then local statusData = GetPlayerStatusMovieClips(character, data.Status) for i,v in pairs(statusData) do ---@type EsvStatus local status = v.Status local mc = v.MC local turns = math.ceil(status.CurrentLifeTime / 6.0) local cooldown = status.LifeTime / status.CurrentLifeTime if data.Turns ~= nil then turns = data.Turns local nextLifetime = turns * 6.0 if nextLifetime >= status.LifeTime then cooldown = 1.0 else cooldown = math.min(1.0, status.LifeTime / nextLifetime) end end mc.setTurns(tostring(turns)) mc.setCoolDown(1.0) mc.tick() end end end end Ext.RegisterNetListener("LeaderLib_UI_RefreshStatusTurns", function(call, payload) local data = Common.JsonParse(payload) if data then local b,err = xpcall(RefreshStatusTurns, debug.traceback, data) if not b then Ext.PrintError(err) end end end) Ext.RegisterNetListener("LeaderLib_SetHelmetOption", function(call, dataStr) local data = MessageData:CreateFromString(dataStr) if data.Params.UUID ~= nil and data.Params.Enabled ~= nil then local ui = Ext.GetBuiltinUI("Public/Game/GUI/characterSheet.swf") if ui ~= nil then local state = data.Params.Enabled and 1 or 0 ui:ExternalInterfaceCall("setHelmetOption", state) end end end) Ext.RegisterNetListener("LeaderLib_SetArmorOption", function(call, dataStr) local data = MessageData:CreateFromString(dataStr) if data.Params.UUID ~= nil and data.Params.State ~= nil then local ui = Ext.GetBuiltinUI("Public/Game/GUI/characterCreation.swf") if ui ~= nil then ui:ExternalInterfaceCall("setArmourState", data.Params.State) end end end) Ext.RegisterNetListener("LeaderLib_UI_RefreshAll", function(cmd, uuid) local host = Ext.GetCharacter(uuid) Ext.UISetDirty(host, 0xffffffffffff) end) Ext.RegisterNetListener("LeaderLib_Client_InvokeListeners", function(cmd, payload) if string.find(payload, "{") then local data = Common.JsonParse(payload) if data._PrintSettings then for k,v in pairs(data._PrintSettings) do Vars.Print[k] = v end end if data._CommandSettings then for k,v in pairs(data._CommandSettings) do Vars.Commands[k] = v end end local listeners = Listeners[data.Event] if listeners then if data.Event == "LuaReset" then GameSettingsManager.Load() end if data.Args then InvokeListenerCallbacks(listeners, table.unpack(data.Args)) else InvokeListenerCallbacks(listeners) end else fprint(LOGLEVEL.ERROR, "[LeaderLib:LeaderLib_Client_InvokeListeners] No listeners for event (%s)", payload) end else local listeners = Listeners[payload] if listeners then if payload == "LuaReset" then GameSettingsManager.Load() end InvokeListenerCallbacks(listeners) else fprint(LOGLEVEL.ERROR, "[LeaderLib:LeaderLib_Client_InvokeListeners] No listeners for event (%s)", payload) end end end) local lastActiveSkill = -1 local function OnShowActiveSkill(ui, method, id) if id == -1 and lastActiveSkill ~= id then local char = Client:GetCharacter() if char then Ext.PostMessageToServer("LeaderLib_OnActiveSkillCleared", tostring(char.NetID)) end end lastActiveSkill = id end Ext.RegisterUITypeInvokeListener(Data.UIType.hotBar, "showActiveSkill", OnShowActiveSkill) Ext.RegisterUITypeInvokeListener(Data.UIType.bottomBar_c, "showActiveSkill", OnShowActiveSkill) Ext.RegisterNetListener("LeaderLib_Debug_MusicTest", function(cmd, payload) local data = Common.JsonParse(payload) local mType = data.Type or "Explo" local theme = data.Theme or "Fort_Joy" --Ext.Audio.SetState("Music_Type", "None") local success1 = Ext.Audio.SetState("Music_Type", mType) local success2 = Ext.Audio.SetState("Music_Theme", theme) fprint(LOGLEVEL.TRACE, "Ext.Audio.SetState(\"Music_Type\", \"%s\") = %s", mType, success1) fprint(LOGLEVEL.TRACE, "Ext.Audio.SetState(\"Music_Theme\", \"%s\") = %s", theme, success2) end) function UI.ToggleChainGroup() local targetGroupId = -1 local client = Client:GetCharacter() local characters = {} local ui = Ext.GetUIByType(Data.UIType.playerInfo) if ui then local this = ui:GetRoot() if this then for i=0,#this.player_array-1 do local player_mc = this.player_array[i] if player_mc then local groupId = player_mc.groupId local character = Ext.GetCharacter(Ext.DoubleToHandle(player_mc.characterHandle)) if character then characters[#characters+1] = { Group = groupId, NetID = character.NetID } if character.NetID == client.NetID then targetGroupId = groupId end end end end end end local groupData = { Leader = client.NetID, Targets = {}, TotalChained = 0, TotalUnchained = 0 } for i,v in pairs(characters) do if v.NetID ~= groupData.Leader then groupData.Targets[#groupData.Targets+1] = v.NetID if v.Group ~= targetGroupId then groupData.TotalUnchained = groupData.TotalUnchained + 1 else groupData.TotalChained = groupData.TotalChained + 1 end end end if groupData.Leader then Ext.PostMessageToServer("LeaderLib_ToggleChainGroup", Ext.JsonStringify(groupData)) end end Ext.RegisterUINameCall("LeaderLib_ToggleChainGroup", function(...) UI.ToggleChainGroup() end)
-- i don't think i'll really use this class local Class = require'libs.hump.class' local Entity = require'entity' -- local lg = love.graphics local Ground = Class{ -- inherit entity __includes = Entity } function Ground:init(--[[world-,-]]x,y,w,h) Entity.init(self,--[[world,--]]x,y,w,h) -- self.world:add(self, self:getRect()) end function Ground:draw() -- place holder -- lg.rectangle('fill', self.getRect()) end return Ground
--[[ This module prints the list of all Pokémon, alternative forms included, having a given ability. --]] local k = {} local tab = require('Wikilib-tables') -- luacheck: no unused local txt = require('Wikilib-strings') -- luacheck: no unused local list = require('Wikilib-lists') local oop = require('Wikilib-oop') local genlib = require('Wikilib-multigen') local css = require('Css') local ms = require('MiniSprite') local resp = require('Resp') local pokes = require("Poké-data") local abils = require('PokéAbil-data') local gens = require("Gens-data") local mw = require('mw') --[[ Class representing a list entry. Fulfills requirements of makeList, sortNdex and sortForms of Wikilib/lists --]] k.Entry = oop.makeClass(list.PokeLabelledEntry) --[[ Printing ability is a complex job: event have to be handled, as well as generation changes. The first argumetn is the ability to be printed, the second one whether it should be marked or not, to be used for events. --]] k.Entry.printAbil = function(abil, marked) if not abil then return marked and '' or 'Nessuna' end -- Marked abilities are italic local toHTML if marked then toHTML = function(ability) return table.concat{"<div>''[[", ability, "]]''</div>"} end else toHTML = function(ability) return table.concat{"[[", ability, "]]"} end end if type(abil) == 'string' then return toHTML(abil) end -- Adding generations superscripts return table.concat(table.map(genlib.getGenSpan(abil), function(v) local first, last = gens[v.first].roman, gens[v.last].roman return string.interp( '<div>${abil}<sup>${gen}</sup></div>', { abil = v.val == 'Nessuna' and v.val or toHTML(v.val), gen = v.first == v.last and first or table.concat{first, '-', last} }) end)) end --[[ Constructor: the first argument is an entry from PokéAbil/data, the second one its key. --]] k.Entry.new = function(pokeAbil, name) local pokedata = genlib.getGen(pokes[name]) local this = k.Entry.super.new(name, pokedata.ndex) this.abils = pokeAbil if this.labels[1] == "" then this.labels[1] = nil end return setmetatable(table.merge(this, pokedata), k.Entry) end -- Wikicode for a list entry: Pokémon mini sprite, name, types and abilities. k.Entry.__tostring = function(this) -- local form = this.formsData -- and this.formsData.blacklinks[this.formAbbr] or '' local form = "" if this.labels[1] then form = this.labels[1] == 'Tutte le forme' and '<div class="small-text">Tutte le forme</div>' or this.formsData.blacklinks[this.formAbbr] end return string.interp([=[| class="min-width-sm-20" data-sort-value="${ndex}" | ${static} | class="black-text min-width-sm-40 min-width-xs-80" | [[${name}]]${form} | class="min-width-xl-20 width-sm-40 width-xs-100" style="padding: 1ex 0.8ex;" | ${types} | class="black-text min-width-sm-33" style="padding: 0.3ex;" | <div class="visible-sm text-small">Prima abilit&agrave;</div>${abil1}${abilEv} | class="black-text min-width-sm-33" style="padding: 0.3ex;" | <div class="visible-sm text-small">Seconda abilit&agrave;</div>${abil2} | class="black-text min-width-sm-33" style="padding: 0.3ex;" | <div class="visible-sm text-small">Abilit&agrave; speciali</div>${abild}]=], { ndex = this.ndex and string.tf(this.ndex) or '???', static = ms.staticLua(string.tf(this.ndex or 0) .. (this.formAbbr == 'base' and '' or this.formAbbr or '')), name = this.name, form = form, types = resp.twoTypeBoxesLua(this.type1, this.type2, {'thin'}, nil, {'inline-block-sm', 'min-width-sm-70'}), abil1 = k.Entry.printAbil(this.abils.ability1), abilEv =k.Entry.printAbil(this.abils.abilitye, true), abil2 = k.Entry.printAbil(this.abils.ability2), abild = k.Entry.printAbil(this.abils.abilityd), }) end k.headers = {} -- Wikicode for list header: it takes the color name k.headers.makeHeader = function(color) return string.interp([=[{| class="sortable roundy text-center pull-center white-rows" style="border-spacing: 0; padding: 0.3ex; ${bg};" |- class="hidden-sm black-text" ! style="padding-top: 0.5ex; padding-bottom: 0.5ex;" | [[Elenco Pokémon secondo il Pokédex Nazionale|#]] ! Pok&eacute;mon ! [[Tipo|Tipi]] ! Prima abilit&agrave; ! Seconda abilit&agrave; ! Abilit&agrave; speciale]=], { bg = css.horizGradLua{type = color} }) end k.headers.separator = '|- class="roundy flex-sm flex-row flex-wrap flex-main-stretch flex-items-center" style="margin-top: 0.5rem;"' k.headers.footer = [[|- ! class="text-left font-small" colspan="6" style="padding: 0.3ex 0.3em;" | * Le abilità in ''corsivo'' sono ottenibili solo in determinate circostanze. |}]] -- =============================== AbilEntry =============================== -- Class representing an entry of a Pokémon with a certain ability. k.AbilEntry = oop.makeClass(k.Entry) --[[ Constructor: the same as the superclass but adding a filter for Pokémon with a certain ability. The first argument is an entry from PokéAbil/data, the second one its key and the third is the ability the Pokémon must have. --]] k.AbilEntry.new = function(pokeAbil, name, abil) if not table.deepSearch(pokeAbil, abil) then return nil end local this = k.AbilEntry.super.new(pokeAbil, name) return setmetatable(this, k.AbilEntry) end --[[ Funzione d'interfaccia: si passano il tipo per il colore e il titolo della pagina, da cui si ricava quello dell'abilità. --]] k.abillist = function(frame) local type = string.trim(frame.args[1]) or 'pcwiki' local abil = string.trim(mw.text.decode(frame.args[2])) abil = abil or 'Cacofonia' return list.makeList({ source = abils, iterator = list.pokeNames, entryArgs = abil, makeEntry = k.AbilEntry.new, header = k.headers.makeHeader(type), separator = k.headers.separator, footer = k.headers.footer, }) end k.Abillist = k.abillist return k
local _, Addon = ... local Dominos = _G.Dominos local GoldBar = Dominos:CreateClass("Frame", Addon.ProgressBar) function GoldBar:Init() self:Update() self:SetColor(Addon.Config:GetColor("gold")) self:SetBonusColor(Addon.Config:GetColor("gold_realm")) end function GoldBar:Update() local gold = GetMoney("player") local max = Addon.Config:GoldGoal() if DataStore then realm = 0 for _, c in pairs(DataStore:GetCharacters()) do realm = realm + DataStore:GetMoney(c) end realm = realm - gold else realm = 0 end if max == 0 then max = (gold + realm) / 10000 end self:SetValues(gold, max*10000, realm) self:UpdateText(_G.MONEY, gold/10000, max, realm/10000) end function GoldBar:IsModeActive() local goal = Addon.Config:GoldGoal() return goal and goal > 0 end -- register this as a possible progress bar mode Addon.progressBarModes = Addon.progressBarModes or {} Addon.progressBarModes["gold"] = GoldBar Addon.GoldBar = GoldBar
local layerBase = require("games/common2/module/layerBase"); --[[ 动画层 ]] local RoomAnimLayer = class(layerBase); RoomAnimLayer.s_cmds = { }; RoomAnimLayer.ctor = function(self) self:removeStateBroadcast(); end RoomAnimLayer.dtor = function(self) end -- 初始化layer的配置 RoomAnimLayer.initViewConfig = function(self) self.m_viewConfig = { [1] = { path = "games/common2/module/anim/roomAnimView"; }; [2] = { -- path = "games/common2/module/anim/roomAnimView"; }; [3] = { -- path = "games/common2/module/anim/roomAnimView"; }; }; end RoomAnimLayer.s_cmdConfig = { }; return RoomAnimLayer; --[[ 公共房间动画图层 功能:踢人、互动道具、加好友相关动画、升场、聊天、表情 说明: 动画模块,负责播放动画。有新动画播放时,发送消息通知模块,并添加接收逻辑,播放动画 动画尽量定义为layer类型的local类,避免直接继承animBase,定义成全局类。 ]]
local files = { "Blocks", "EastAsianWidth", "PropList", "Scripts", "UnicodeData", "DerivedCoreProperties", } local limit = 200000 local buffer = 190000 local head = "-- Automatically generated by build.lua, do not edit\n" for _,name in pairs(files) do local path = string.format("UCD/%s.txt", name) print("Building", path) local file = io.open(path, 'r') local contents = file:read("*a") local num = math.ceil(#contents / limit); if num == 1 then print("Below max size") local out = io.open(string.format("src/Data/%s.lua", name), 'w') out:write(head.."return [[\n") out:write(contents) out:write("]]") out:flush() out:close() else print("Above max size, using "..num.." scripts") local out local length = math.huge local i = 0 for line in contents:gmatch("([^\r\n]*)\n?") do if length + #line + 1 > buffer then if out then out:write("]]\n") out:flush() out:close() print("wrote file "..i) end i = i + 1 out = io.open(string.format("src/Data/%s%i.lua", name, i), 'w') local str = head..'return [[\n' out:write(str) length = #str end out:write(line .. '\n') length = length + #line + 1 end out:write("]]\n") out:flush() out:close() print("wrote file "..i) local out = io.open(string.format("src/Data/%s.lua", name), 'w') out:write(head.."return {\n") for j = 1, i do out:write(string.format(" require(script.Parent.%s%i),\n", name, j)) end out:write("}\n") out:flush() print("wrote index file") end end
local entity_id = GetUpdatedEntityID() function spawn_trading_post( x, y ) GamePrint("spawn_trading_post start"); EntityLoad( "data/trading/trading_post.xml", x, y ) GamePrint("spawn_trading_post end"); end
--==[[ libs ]]==-- local stringutils = {} stringutils.format = function(s, tab) return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end)) end stringutils.split = function(s, delimiter) result = {} for match in (s .. delimiter):gmatch("(.-)" .. delimiter) do table.insert(result, match) end return result end table.tostring = function(tbl, depth) local res = "{" local prev = 0 for k, v in next, tbl do if type(v) == "table" then if depth == nil or depth > 0 then res = res .. ((type(k) == "number" and prev and prev + 1 == k) and "" or k .. ": ") .. table.tostring(v, depth and depth - 1 or nil) .. ", " else res = res .. k .. ": {...}, " end else res = res .. ((type(k) == "number" and prev and prev + 1 == k) and "" or k .. ": ") .. tostring(v) .. ", " end prev = type(k) == "number" and k or nil end return res:sub(1, res:len() - 2) .. "}" end table.map = function(tbl, fn) local res = {} for k, v in next, tbl do res[k] = fn(v) end return res end table.find = function(tbl, val) for k, v in next, tbl do if v == val then return k end end end local prettyify do local typeLookup = { ["string"] = function(obj) return ("<VP>\"%s\"</VP>"):format(obj) end, ["number"] = function(obj) return ("<J>%s</J>"):format(obj) end, ["boolean"] = function(obj) return ("<J>%s</J>"):format(obj) end, ["function"] = function(obj) return ("<b><V>%s</V></b>"):format(obj) end, ["nil"] = function() return ("<G>nil</G>") end } local string_repeat = function(str, times) local res = "" while times > 0 do res = res .. str times = times - 1 end return res end prettify = function(obj, depth, opt) opt = opt or {} opt.maxDepth = opt.maxDepth or 30 opt.truncateAt = opt.truncateAt or 30 local prettifyFn = typeLookup[type(obj)] if (prettifyFn) then return { res = (prettifyFn(tostring(obj))), count = 1 } end -- not the type of object ({}, []) if depth >= opt.maxDepth then return { res = ("<b><V>%s</V></b>"):format(tostring(obj)), count = 1 } end local kvPairs = {} local totalObjects = 0 local length = 0 local shouldTruncate = false local previousKey = 0 for key, value in next, obj do if not shouldTruncate then local tn = tonumber(key) key = tn and (((previousKey and tn - previousKey == 1) and "" or "[" .. key .. "]:")) or (key .. ":") -- we only need to check if the previous key is a number, so a nil key doesn't matter previousKey = tn local prettified = prettify(value, depth + 1, opt) kvPairs[#kvPairs + 1] = key .. " " .. prettified.res totalObjects = totalObjects + prettified.count if length >= opt.truncateAt then shouldTruncate = true end end length = length + 1 end if shouldTruncate then kvPairs[#kvPairs] = (" <G><i>... %s more values</i></G>"):format(length - opt.truncateAt) end if totalObjects < 6 then return { res = "<N>{ " .. table.concat(kvPairs, ", ") .. " }</N>", count = totalObjects } else return { res = "<N>{ " .. table.concat(kvPairs, ",\n " .. string_repeat(" ", depth)) .. " }</N>", count = totalObjects } end end end local prettyprint = function(obj, opt) print(prettify(obj, 0, opt or {}).res) end local p = prettyprint -- Thanks to Turkitutu -- https://pastebin.com/raw/Nw3y1A42 bit = {} bit.lshift = function(x, by) -- Left-shift of x by n bits return x * 2 ^ by end bit.rshift = function(x, by) -- Logical right-shift of x by n bits return math.floor(x / 2 ^ by) end bit.band = function(a, b) -- bitwise and of x1, x2 local p, c = 1, 0 while a > 0 and b > 0 do local ra, rb = a % 2, b % 2 if ra + rb > 1 then c = c + p end a, b, p = (a - ra) / 2, (b - rb) / 2, p * 2 end return c end bit.bxor = function(a,b) -- Bitwise xor of x1, x2 local r = 0 for i = 0, 31 do local x = a / 2 + b / 2 if x ~= math.floor(x) then r = r + 2^i end a = math.floor(a / 2) b = math.floor(b / 2) end return r end bit.bor = function(a,b) -- Bitwise or of x1, x2 local p, c= 1, 0 while a+b > 0 do local ra, rb = a % 2, b % 2 if ra + rb > 0 then c = c + p end a, b, p = (a - ra) / 2, (b - rb) / 2, p * 2 end return c end bit.bnot = function(n) -- Bitwise not of x local p, c = 1, 0 while n > 0 do local r = n % 2 if r < 0 then c = c + p end n, p = (n - r) / 2, p * 2 end return c end local BitList = {} BitList.__index = BitList setmetatable(BitList, { __call = function(cls, ...) return cls.new(...) end }) do function BitList.new(features) local self = setmetatable({}, BitList) self.featureArray = features self.featureKeys = {} for k, v in next, features do self.featureKeys[v] = k end self.features = #self.featureArray return self end function BitList:encode(featTbl) local res = 0 for k, v in next, featTbl do if v and self.featureKeys[k] then res = bit.bor(res, bit.lshift(1, self.featureKeys[k] - 1)) end end return res end function BitList:decode(featInt) local features, index = {}, 1 while (featInt > 0) do feat = bit.band(featInt, 1) == 1 corrFeat = self.featureArray[index] features[corrFeat] = feat featInt = bit.rshift(featInt, 1) index = index + 1 end return features end function BitList:get(index) return self.featureArray[index] end function BitList:find(feature) return self.featureKeys[feature] end end local Panel = {} local Image = {} do local string_split = function(s, delimiter) result = {} for match in (s .. delimiter):gmatch("(.-)" .. delimiter) do table.insert(result, match) end return result end local table_tostring table_tostring = function(tbl, depth) local res = "{" local prev = 0 for k, v in next, tbl do if type(v) == "table" then if depth == nil or depth > 0 then res = res .. ((type(k) == "number" and prev and prev + 1 == k) and "" or k .. ": ") .. table_tostring(v, depth and depth - 1 or nil) .. ", " else res = res .. k .. ": {...}, " end else res = res .. ((type(k) == "number" and prev and prev + 1 == k) and "" or k .. ": ") .. tostring(v) .. ", " end prev = type(k) == "number" and k or nil end return res:sub(1, res:len() - 2) .. "}" end local table_copy = function(tbl) local res = {} for k, v in next, tbl do res[k] = v end return res end -- [[ class Image ]] -- Image.__index = Image Image.__tostring = function(self) return table_tostring(self) end Image.images = {} setmetatable(Image, { __call = function(cls, ...) return cls.new(...) end }) function Image.new(imageId, target, x, y, parent) local self = setmetatable({ id = #Image.images + 1, imageId = imageId, target = target, x = x, y = y, instances = {}, }, Image) Image.images[self.id] = self return self end function Image:show(target) if target == nil then error("Target cannot be nil") end if self.instances[target] then return self end self.instances[target] = tfm.exec.addImage(self.imageId, self.target, self.x, self.y, target) return self end function Image:hide(target) if target == nil then error("Target cannot be nil") end if not self.instances[target] then return end tfm.exec.removeImage(self.instances[target]) self.instances[target] = nil return self end -- [[ class Panel ]] -- Panel.__index = Panel Panel.__tostring = function(self) return table_tostring(self) end Panel.panels = {} setmetatable(Panel, { __call = function (cls, ...) return cls.new(...) end, }) function Panel.new(id, text, x, y, w, h, background, border, opacity, fixed, hidden) local self = setmetatable({ id = id, text = text, x = x, y = y, w = w, h = h, background = background, border = border, opacity = opacity, fixed = fixed, hidden = hidden, isCloseButton = false, closeTarget = nil, parent = nil, onhide = nil, onclick = nil, children = {}, temporary = {} }, Panel) Panel.panels[id] = self return self end function Panel.handleActions(id, name, event) local panelId = id - 10000 local panel = Panel.panels[panelId] if not panel then return end if panel.isCloseButton then if not panel.closeTarget then return end panel.closeTarget:hide(name) if panel.onhide then panel.onhide(panelId, name, event) end else if panel.onclick then panel.onclick(panelId, name, event) end end end function Panel:show(target) ui.addTextArea(10000 + self.id, self.text, target, self.x, self.y, self.w, self.h, self.background, self.border, self.opacity, self.opacity) self.visible = true for name in next, (target and { [target] = true } or tfm.get.room.playerList) do for id, child in next, self.children do child:show(name) end end return self end function Panel:update(text, target) ui.updateTextArea(10000 + self.id, text, target) return self end function Panel:hide(target) ui.removeTextArea(10000 + self.id, target) for name in next, (target and { [target] = true } or tfm.get.room.playerList) do for id, child in next, self.children do child:hide(name) end if self.temporary[name] then for id, child in next, self.temporary[name] do child:hide(name) end self.temporary[name] = {} end end if self.onclose then self.onclose(target) end return self end function Panel:addPanel(panel) self.children[panel.id] = panel panel.parent = self.id return self end function Panel:addImage(image) self.children["i_" .. image.id] = image return self end function Panel:addPanelTemp(panel, target) if not self.temporary[target] then self.temporary[target] = {} end panel:show(target) self.temporary[target][panel.id] = panel return self end function Panel:addImageTemp(image, target) if not self.temporary[target] then self.temporary[target] = {} end image:show(target) self.temporary[target]["i_" .. image.id] = image return self end function Panel:setActionListener(fn) self.onclick = fn return self end function Panel:setCloseButton(id, callback) local button = Panel.panels[id] if not button then return self end self.closeTarget = button self.onclose = callback button.isCloseButton = true button.closeTarget = self return self end end -- [[Timers4TFM]] -- local a={}a.__index=a;a._timers={}setmetatable(a,{__call=function(b,...)return b.new(...)end})function a.process()local c=os.time()local d={}for e,f in next,a._timers do if f.isAlive and f.mature<=c then f:call()if f.loop then f:reset()else f:kill()d[#d+1]=e end end end;for e,f in next,d do a._timers[f]=nil end end;function a.new(g,h,i,j,...)local self=setmetatable({},a)self.id=g;self.callback=h;self.timeout=i;self.isAlive=true;self.mature=os.time()+i;self.loop=j;self.args={...}a._timers[g]=self;return self end;function a:setCallback(k)self.callback=k end;function a:addTime(c)self.mature=self.mature+c end;function a:setLoop(j)self.loop=j end;function a:setArgs(...)self.args={...}end;function a:call()self.callback(table.unpack(self.args))end;function a:kill()self.isAlive=false end;function a:reset()self.mature=os.time()+self.timeout end;Timer=a --[[DataHandler v22]] local a={}a.VERSION='1.5'a.__index=a;function a.new(b,c,d)local self=setmetatable({},a)assert(b,'Invalid module ID (nil)')assert(b~='','Invalid module ID (empty text)')assert(c,'Invalid skeleton (nil)')for e,f in next,c do f.type=f.type or type(f.default)end;self.players={}self.moduleID=b;self.moduleSkeleton=c;self.moduleIndexes={}self.otherOptions=d;self.otherData={}self.originalStuff={}for e,f in pairs(c)do self.moduleIndexes[f.index]=e end;if self.otherOptions then self.otherModuleIndexes={}for e,f in pairs(self.otherOptions)do self.otherModuleIndexes[e]={}for g,h in pairs(f)do h.type=h.type or type(h.default)self.otherModuleIndexes[e][h.index]=g end end end;return self end;function a.newPlayer(self,i,j)assert(i,'Invalid player name (nil)')assert(i~='','Invalid player name (empty text)')self.players[i]={}self.otherData[i]={}j=j or''local function k(l)local m={}for n in string.gsub(l,'%b{}',function(o)return o:gsub(',','\0')end):gmatch('[^,]+')do n=n:gsub('%z',',')if string.match(n,'^{.-}$')then table.insert(m,k(string.match(n,'^{(.-)}$')))else table.insert(m,tonumber(n)or n)end end;return m end;local function p(c,q)for e,f in pairs(c)do if f.index==q then return e end end;return 0 end;local function r(c)local s=0;for e,f in pairs(c)do if f.index>s then s=f.index end end;return s end;local function t(b,c,u,v)local w=1;local x=r(c)b="__"..b;if v then self.players[i][b]={}end;local function y(n,z,A,B)local C;if z=="number"then C=tonumber(n)or B elseif z=="string"then C=string.match(n and n:gsub('\\"','"')or'',"^\"(.-)\"$")or B elseif z=="table"then C=string.match(n or'',"^{(.-)}$")C=C and k(C)or B elseif z=="boolean"then if n then C=n=='1'else C=B end end;if v then self.players[i][b][A]=C else self.players[i][A]=C end end;if#u>0 then for n in string.gsub(u,'%b{}',function(o)return o:gsub(',','\0')end):gmatch('[^,]+')do n=n:gsub('%z',','):gsub('\9',',')local A=p(c,w)local z=c[A].type;local B=c[A].default;y(n,z,A,B)w=w+1 end end;if w<=x then for D=w,x do local A=p(c,D)local z=c[A].type;local B=c[A].default;y(nil,z,A,B)end end end;local E,F=self:getModuleData(j)self.originalStuff[i]=F;if not E[self.moduleID]then E[self.moduleID]='{}'end;t(self.moduleID,self.moduleSkeleton,E[self.moduleID]:sub(2,-2),false)if self.otherOptions then for b,c in pairs(self.otherOptions)do if not E[b]then local G={}for e,f in pairs(c)do local z=f.type or type(f.default)if z=='string'then G[f.index]='"'..tostring(f.default:gsub('"','\\"'))..'"'elseif z=='table'then G[f.index]='{}'elseif z=='number'then G[f.index]=f.default elseif z=='boolean'then G[f.index]=f.default and'1'or'0'end end;E[b]='{'..table.concat(G,',')..'}'end end end;for b,u in pairs(E)do if b~=self.moduleID then if self.otherOptions and self.otherOptions[b]then t(b,self.otherOptions[b],u:sub(2,-2),true)else self.otherData[i][b]=u end end end end;function a.dumpPlayer(self,i)local m={}local function H(I)local m={}for e,f in pairs(I)do local J=type(f)if J=='table'then m[#m+1]='{'m[#m+1]=H(f)if m[#m]:sub(-1)==','then m[#m]=m[#m]:sub(1,-2)end;m[#m+1]='}'m[#m+1]=','else if J=='string'then m[#m+1]='"'m[#m+1]=f:gsub('"','\\"')m[#m+1]='"'elseif J=='boolean'then m[#m+1]=f and'1'or'0'else m[#m+1]=f end;m[#m+1]=','end end;if m[#m]==','then m[#m]=''end;return table.concat(m)end;local function K(i,b)local m={b,'=','{'}local L=self.players[i]local M=self.moduleIndexes;local N=self.moduleSkeleton;if self.moduleID~=b then M=self.otherModuleIndexes[b]N=self.otherOptions[b]b='__'..b;L=self.players[i][b]end;if not L then return''end;for D=1,#M do local A=M[D]local z=N[A].type;if z=='string'then m[#m+1]='"'m[#m+1]=L[A]:gsub('"','\\"')m[#m+1]='"'elseif z=='number'then m[#m+1]=L[A]elseif z=='boolean'then m[#m+1]=L[A]and'1'or'0'elseif z=='table'then m[#m+1]='{'m[#m+1]=H(L[A])m[#m+1]='}'end;m[#m+1]=','end;if m[#m]==','then m[#m]='}'else m[#m+1]='}'end;return table.concat(m)end;m[#m+1]=K(i,self.moduleID)if self.otherOptions then for e,f in pairs(self.otherOptions)do local u=K(i,e)if u~=''then m[#m+1]=','m[#m+1]=u end end end;for e,f in pairs(self.otherData[i])do m[#m+1]=','m[#m+1]=e;m[#m+1]='='m[#m+1]=f end;return table.concat(m)..self.originalStuff[i]end;function a.get(self,i,A,O)if not O then return self.players[i][A]else assert(self.players[i]['__'..O],'Module data not available ('..O..')')return self.players[i]['__'..O][A]end end;function a.set(self,i,A,C,O)if O then self.players[i]['__'..O][A]=C else self.players[i][A]=C end;return self end;function a.save(self,i)system.savePlayerData(i,self:dumpPlayer(i))end;function a.removeModuleData(self,i,O)assert(O,"Invalid module name (nil)")assert(O~='',"Invalid module name (empty text)")assert(O~=self.moduleID,"Invalid module name (current module data structure)")if self.otherData[i][O]then self.otherData[i][O]=nil;return true else if self.otherOptions and self.otherOptions[O]then self.players[i]['__'..O]=nil;return true end end;return false end;function a.getModuleData(self,l)local m={}for b,u in string.gmatch(l,'([0-9A-Za-z_]+)=(%b{})')do local P=self:getTextBetweenQuotes(u:sub(2,-2))for D=1,#P do P[D]=P[D]:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]","%%%0")u=u:gsub(P[D],P[D]:gsub(',','\9'))end;m[b]=u end;for e,f in pairs(m)do l=l:gsub(e..'='..f:gsub('\9',','):gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]","%%%0")..',?','')end;return m,l end;function a.convertFromOld(self,Q,R)assert(Q,'Old data is nil')assert(R,'Old skeleton is nil')local function S(l,T)local m={}for U in string.gmatch(l,'[^'..T..']+')do m[#m+1]=U end;return m end;local E=S(Q,'?')local m={}for D=1,#E do local O=E[D]:match('([0-9a-zA-Z]+)=')local u=S(E[D]:gsub(O..'=',''):gsub(',,',',\8,'),',')local G={}for V=1,#u do if R[O][V]then if R[O][V]=='table'then G[#G+1]='{'if u[V]~='\8'then local I=S(u[V],'#')for W=1,#I do G[#G+1]=I[W]G[#G+1]=','end;if G[#G]==','then table.remove(G)end end;G[#G+1]='},'elseif R[O][V]=='string'then G[#G+1]='"'if u[V]~='\8'then G[#G+1]=u[V]end;G[#G+1]='"'G[#G+1]=','else if u[V]~='\8'then G[#G+1]=u[V]else G[#G+1]=0 end;G[#G+1]=','end end end;if G[#G]==','then table.remove(G)end;m[#m+1]=O;m[#m+1]='='m[#m+1]='{'m[#m+1]=table.concat(G)m[#m+1]='}'m[#m+1]=','end;if m[#m]==','then table.remove(m)end;return table.concat(m)end;function a.convertFromDataManager(self,Q,R)assert(Q,'Old data is nil')assert(R,'Old skeleton is nil')local function S(l,T)local m={}for U in string.gmatch(l,'[^'..T..']+')do m[#m+1]=U end;return m end;local E=S(Q,'§')local m={}for D=1,#E do local O=E[D]:match('%[(.-)%]')local u=S(E[D]:gsub('%['..O..'%]%((.-)%)','%1'),'#')local G={}for V=1,#u do if R[V]=='table'then local I=S(u[V],'&')G[#G+1]='{'for W=1,#I do if tonumber(I[W])then G[#G+1]=I[W]G[#G+1]=','else G[#G+1]='"'G[#G+1]=I[W]G[#G+1]='"'G[#G+1]=','end end;if G[#G]==','then table.remove(G)end;G[#G+1]='}'G[#G+1]=','else if R[V]=='string'then G[#G+1]='"'G[#G+1]=u[V]G[#G+1]='"'else G[#G+1]=u[V]end;G[#G+1]=','end end;if G[#G]==','then table.remove(G)end;m[#m+1]=O;m[#m+1]='='m[#m+1]='{'m[#m+1]=table.concat(G)m[#m+1]='}'end;return table.concat(m)end;function a.getTextBetweenQuotes(self,l)local m={}local X=1;local Y=0;local Z=false;for D=1,#l do local _=l:sub(D,D)if _=='"'then if l:sub(D-1,D-1)~='\\'then if Y==0 then X=D;Y=Y+1 else Y=Y-1;if Y==0 then m[#m+1]=l:sub(X,D)end end end end end;return m end;DataHandler=a --[[ Makinit's XML library ]]-- local a="Makinit's XML library"local b="[%a_:][%w%.%-_:]*"function parseXml(c,d)if not d then c=string.gsub(c,"<!%[CDATA%[(.-)%]%]>",xmlEscape)c=string.gsub(c,"<%?.-%?>","")c=string.gsub(c,"<!%-%-.-%-%->","")c=string.gsub(c,"<!.->","")end;local e={}local f={}local g=e;for h,i,j,k,l in string.gmatch(c,"<(/?)("..b..")(.-)(/?)>%s*([^<]*)%s*")do if h=="/"then local m=f[g]if m and i==g.name then g=m end else local n={name=i,attribute={}}table.insert(g,n)f[n]=g;if k~="/"then g=n end;for i,o in string.gmatch(j,"("..b..")%s*=%s*\"(.-)\"")do n.attribute[i]=d and o or xmlUnescape(o)end end;if l~=""then local n={text=d and l or xmlUnescape(l)}table.insert(g,n)f[n]=g end end;return e[1]end;function generateXml(g,d)if g.name then local c="<"..g.name;for i,o in pairs(g.attribute)do c=c.." "..i.."=\""..(d and tostring(o)or xmlEscape(tostring(o))).."\""end;if#g==0 then c=c.." />"else c=c..">"for p,n in ipairs(g)do c=c..generateXml(n,d)end;c=c.."</"..g.name..">"end;return c elseif g.text then return d and tostring(g.text)or xmlEscape(tostring(g.text))end end;function path(q,...)q={q}for p,i in ipairs(arg)do local r={}for p,s in ipairs(q)do for p,n in ipairs(s)do if n.name==i then table.insert(r,n)end end end;q=r end;return q end;local t={}function xmlEscape(u)local v=t[u]if not v then local w=string.gsub;v=w(u,"&","&amp;")v=w(v,"\"","&quot;")v=w(v,"'","&apos;")v=w(v,"<","&lt;")v=w(v,">","&gt;")t[u]=v end;return v end;local x={}function xmlUnescape(u)local v=x[u]if not v then local w=string.gsub;v=w(u,"&quot;","\"")v=w(v,"&apos;","'")v=w(v,"&lt;","<")v=w(v,"&gt;",">")v=w(v,"&#(%d%d?%d?%d?);",dec2char)v=w(v,"&#x(%x%x?%x?%x?);",hex2char)v=w(v,"&amp;","&")x[u]=v end;return v end;function dec2char(y)y=tonumber(y)return string.char(y>255 and 0 or y)end;function hex2char(y)y=tonumber(y,16)return string.char(y>255 and 0 or y)end --==[[ init ]]==-- local VERSION = "v2.5.2.0" local VERSION_IMG = nil local CHANGELOG = [[ <p align='center'><font size='20'><b><V>CHANGELOG</V></b></font> <BV><a href='event:log'>[View all]</a></BV></p><font size='12' face='Lucida Console'> <font size='15' face='Lucida Console'><b><BV>v2.5.2.0</BV></b></font> <i>(7/26/2021)</i> • Player data fail safeback <font size='15' face='Lucida Console'><b><BV>v2.5.1.0</BV></b></font> <i>(7/26/2021)</i> • Minor permission changes for some commands <font size='15' face='Lucida Console'><b><BV>v2.5.0.0</BV></b></font> <i>(7/26/2021)</i> • Added new map parameters ALLOWED="" and RESTRICTED="", check the map submission thread for more information! <font size='15' face='Lucida Console'><b><BV>v2.4.0.0</BV></b></font> <i>(7/26/2021)</i> • Added a news windows <font size='15' face='Lucida Console'><b><BV>v2.3.4.0</BV></b></font> <i>(7/26/2021)</i> • Added UR (urdu) translations (Thanks to Maha010#0000) • Changed the map rotation algorithm to play latest maps more frequent • Added an indicator for stats enabled/disabled • Fixed not showing all the credits for some languages <font size='15' face='Lucida Console'><b><BV>v2.3.3.0</BV></b></font> <i>(6/12/2021)</i> • Fixed the bug that displays your badges instead of showing the target's badges • Added BR translations (Thanks to Santoex#0000) • Changed the font size of ratios in leaderboard to '9' as a temporary fix for text wrapping issuess <font size='15' face='Lucida Console'><b><BV>v2.3.2.0</BV></b></font> <i>(3/27/2021)</i> • Added badges for the roles you have obtained!!! • Fixed bugs that caused the leaderboards from not loading properly due to the last update • Fixed some internal commands <font size='15' face='Lucida Console'><b><BV>v2.3.1.0</BV></b></font> <i>(3/22/2021)</i> • Added !npp [@code] to queue maps - works only inside your tribe house • Major internal changes regarding map rotation </font> ]] tfm.exec.disableAutoNewGame() tfm.exec.disableAutoScore() tfm.exec.disableAutoShaman() tfm.exec.disableAutoTimeLeft() tfm.exec.disablePhysicalConsumables() local admins = { ["King_seniru#5890"] = true, ["Lightymouse#0421"] = true, ["Overforyou#9290"] = true } -- TEMP: Temporary fix to get rid of farmers and hackers local banned = { ["Sannntos#0000"] = true, ["Bofmfodo#1438"] = true, ["Rimuru#7401"] = true } maps = { list = { 521833, 401421, 541917, 541928, 541936, 541943, 527935, 559634, 559644 }, dumpCache = "", overwriteFile = false } local ENUM_ITEMS = { SMALL_BOX = 1, LARGE_BOX = 2, SMALL_PLANK = 3, LARGE_PLANK = 4, BALL = 6, ANVIL = 10, CANNON = 17, BOMB = 23, SPIRIT = 24, BLUE_BALOON = 28, RUNE = 32, SNOWBALL = 34, CUPID_ARROW = 35, APPLE = 39, SHEEP = 40, SMALL_ICE_PLANK = 45, SMALL_CHOCO_PLANK = 46, ICE_CUBE = 54, CLOUD = 57, BUBBLE = 59, TINY_PLANK = 60, STABLE_RUNE = 62, PUFFER_FISH = 65, TOMBSTONE = 90 } local items = { ENUM_ITEMS.SMALL_BOX, ENUM_ITEMS.LARGE_BOX, ENUM_ITEMS.SMALL_PLANK, ENUM_ITEMS.LARGE_PLANK, ENUM_ITEMS.BALL, ENUM_ITEMS.ANVIL, ENUM_ITEMS.BOMB, ENUM_ITEMS.SPIRIT, ENUM_ITEMS.BLUE_BALOON, ENUM_ITEMS.RUNE, ENUM_ITEMS.SNOWBALL, ENUM_ITEMS.CUPID_ARROW, ENUM_ITEMS.APPLE, ENUM_ITEMS.SHEEP, ENUM_ITEMS.SMALL_ICE_PLANK, ENUM_ITEMS.SMALL_CHOCO_PLANK, ENUM_ITEMS.ICE_CUBE, ENUM_ITEMS.CLOUD, ENUM_ITEMS.BUBBLE, ENUM_ITEMS.TINY_PLANK, ENUM_ITEMS.STABLE_RUNE, ENUM_ITEMS.PUFFER_FISH, ENUM_ITEMS.TOMBSTONE } local keys = { LEFT = 0, RIGHT = 2, DOWN = 3, SPACE = 32, LETTER_H = 72, LETTER_L = 76, LETTER_O = 79, LETTER_P = 80, } local assets = { banner = "173f1aa1720.png", count1 = "173f211056a.png", count2 = "173f210937b.png", count3 = "173f210089f.png", newRound = "173f2113b5e.png", heart = "173f2212052.png", iconRounds = "17434cc5748.png", iconDeaths = "17434d1c965.png", iconSurvived = "17434d0a87e.png", iconWon = "17434cff8bd.png", iconTrophy = "176463dbc3e.png", lock = "1660271f4c6.png", help = { survive = "17587d5abed.png", killAll = "17587d5ca0e.png", shoot = "17587d6acaf.png", creditors = "17587d609f1.png", commands = "17587d64557.png", weapon = "17587d67562.png", github = "1764b681c20.png", discord = "1764b73dad6.png", map = "1764b7a7692.png" }, items = { [ENUM_ITEMS.SMALL_BOX] = "17406985997.png", [ENUM_ITEMS.LARGE_BOX] = "174068e3bca.png", [ENUM_ITEMS.SMALL_PLANK] = "174069a972e.png", [ENUM_ITEMS.LARGE_PLANK] = "174069c5a7a.png", [ENUM_ITEMS.BALL] = "174069d7a29.png", [ENUM_ITEMS.ANVIL] = "174069e766a.png", [ENUM_ITEMS.CANNON] = "17406bf2f70.png", [ENUM_ITEMS.BOMB] = "17406bf6ffc.png", [ENUM_ITEMS.SPIRIT] = "17406a23cd0.png", [ENUM_ITEMS.BLUE_BALOON] = "17406a41815.png", [ENUM_ITEMS.RUNE] = "17406a58032.png", [ENUM_ITEMS.SNOWBALL] = "17406a795f4.png", [ENUM_ITEMS.CUPID_ARROW] = "17406a914a3.png", [ENUM_ITEMS.APPLE] = "17406aa2daf.png", [ENUM_ITEMS.SHEEP] = "17406ac8ab7.png", [ENUM_ITEMS.SMALL_ICE_PLANK] = "17406aefb88.png", [ENUM_ITEMS.SMALL_CHOCO_PLANK] = "17406b00239.png", [ENUM_ITEMS.ICE_CUBE] = "17406b15725.png", [ENUM_ITEMS.CLOUD] = "17406b22bd6.png", [ENUM_ITEMS.BUBBLE] = "17406b32d1f.png", [ENUM_ITEMS.TINY_PLANK] = "17406b59bd6.png", [ENUM_ITEMS.STABLE_RUNE] = "17406b772b7.png", [ENUM_ITEMS.PUFFER_FISH] = "17406b8c9f2.png", [ENUM_ITEMS.TOMBSTONE] = "17406b9eda9.png" }, widgets = { borders = { topLeft = "155cbe99c72.png", topRight = "155cbea943a.png", bottomLeft = "155cbe97a3f.png", bottomRight = "155cbe9bc9b.png" }, closeButton = "171e178660d.png", scrollbarBg = "1719e0e550a.png", scrollbarFg = "1719e173ac6.png" }, community = { int= "1651b327097.png", xx = "1651b327097.png", ar = "1651b32290a.png", bg = "1651b300203.png", br = "1651b3019c0.png", cn = "1651b3031bf.png", cz = "1651b304972.png", de = "1651b306152.png", ee = "1651b307973.png", en = "1723dc10ec2.png", e2 = "1723dc10ec2.png", es = "1651b309222.png", fi = "1651b30aa94.png", fr = "1651b30c284.png", gb = "1651b30da90.png", hr = "1651b30f25d.png", hu = "1651b310a3b.png", id = "1651b3121ec.png", il = "1651b3139ed.png", it = "1651b3151ac.png", jp = "1651b31696a.png", lt = "1651b31811c.png", lv = "1651b319906.png", nl = "1651b31b0dc.png", pl = "1651b31e0cf.png", pt = "1651b3019c0.png", ro = "1651b31f950.png", ru = "1651b321113.png", tg = "1651b31c891.png", tr = "1651b3240e8.png", vk = "1651b3258b3.png" }, dummy = "17404561700.png" } local closeSequence = { [1] = {} } local dHandler = DataHandler.new("pew", { rounds = { index = 1, type = "number", default = 0 }, survived = { index = 2, type = "number", default = 0 }, won = { index = 3, type = "number", default = 0 }, points = { index = 4, type = "number", default = 0 }, packs = { index = 5, type = "number", default = 1 }, equipped = { index = 6, type = "number", default = 1 }, roles = { index = 7, type = "number", default = 0 }, version = { index = 8, type = "string", default = "v0.0.0.0" } }) local MIN_PLAYERS = 4 local profileWindow, leaderboardWindow, changelogWindow, shopWindow, helpWindow local initialized, newRoundStarted, suddenDeath = false, false, false local currentItem = ENUM_ITEMS.CANNON local isTribeHouse = tfm.get.room.isTribeHouse local statsEnabled = not isTribeHouse local rotation, queuedMaps, currentMapIndex = {}, {}, 0 local mapProps = { allowed = nil, restricted = nil, grey = nil, items = items, fromQueue = false } local leaderboardNotifyList = {} local leaderboard, shop, roles --==[[ translations ]]==-- local translations = {} translations["en"] = { LIVES_LEFT = "<ROSE>You have <N>${lives} <ROSE>lives left. <VI>Respawning in 3...", LOST_ALL = "<ROSE>You have lost all your lives!", SD = "<VP>Sudden death! Everyone has <N>1 <VP>life left", WELCOME = "<VP>Welcome to pewpew, <N>duck <VP>or <N>spacebar <VP>to shoot items!", SOLE = "<ROSE>${player} is the sole survivor!", SURVIVORS = "<ROSE>${winners} and ${winner} have survived this round!", SELF_RANK = "<p align='center'>Your rank: ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Rounds played</N2></font>", DEATHS = "<font face='Lucida console'><N2>Deaths</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Rounds survived</N2></font>", WON = "<font face='Lucida console'><N2>Rounds won</N2></font>", LBOARD_POS = "<b><font face='Lucida console' color='#e3b134'>Global leaderboard: ${pos}</font></b>", EQUIPPED = "Equipped", EQUIP = "Equip", BUY = "Buy", POINTS = "<font face='Lucida console' size='12'> <b>Points:</b> <V>${points}</V></font>", PACK_DESC = "\n\n<font face='Lucida console' size='12' color='#cccccc'><i>“ ${desc} ”</i></font>\n<p align='right'><font size='10'>- ${author}</font></p>", GIFT_RECV = "<N>You have been rewarded with <ROSE><b>${gift}</b></ROSE> by <ROSE><b>${admin}</b></ROSE>", COMMANDS = "\n\n<N2>[ <b>H</b> ]</N2> <N><ROSE>!help</ROSE> (displays this help menu)</N><br><N2>[ <b>P</b> ]</N2> <N><ROSE>!profile <i>[player]</i></ROSE> (displays the profile of the player)</N><br></N><N2>[ <b>O</b> ]</N2> <N><ROSE>!shop</ROSE> (displays the shop)</N><br><N2>[ <b>L</b> ]</N2> <N>(displays the leaderboard)</N><br><br><N><ROSE>!changelog</ROSE> (displays the changelog)</N><br><br>", CMD_TITLE = "<font size='25' face='Comic Sans'><b><J>Commands</J></b></font>", CREDITS = "\n\nArtist - <b>${artists}</b>\nTranslators - <b>${translators}</b>\n\n\nAnd thank you for playing pewpew!", CREDS_TITLE = "<font size='25' face='Comic Sans'><b><R>Credits</R></b></font>", OBJECTIVE = "<b>Survive and kill others to win</b>", HELP_GOTIT = "<font size='15'><J><b><a href='event:close'>Got it!</a></b></J></font>", HELP_GITHUB = "<N>Want to contribute this module? Cool! Check out</N> <VI><b><i>https://github.com/Seniru/pewpew</i></b></VI>", HELP_DISCORD = "<N>Discord:</N> <VI><b><i>https://discord.gg/vaqgrgp</i></b></VI>", HELP_MAP = "<N>Want to add your maps to pewpew? Check out</N> <VI><b><i>https://atelier801.com/topic?f=6&t=892550</i></b></VI>", NEW_ROLE = "<N><ROSE><b>${player}</b></ROSE> is now a <ROSE><b>${role}</b></ROSE>", KICK_ROLE = "<N><ROSE><b>${player}</b></ROSE> is not a <ROSE><b>${role}</b></ROSE> anymore! ;c", ERR_PERMS = "<N>[</N><R>•</R><N>] <R><b>Error: You are not permitted to use this command!</b></R>", ERR_CMD = "<N>[</N><R>•</R><N>] <R><b>Error in command<br>\tUsage:</b><font face='Lucida console'>${syntax}</i></font></R>", MAP_QUEUED ="<N><ROSE><b>@${map}</b></ROSE> has been queued by <ROSE><b>${player}</b></ROSE>", STATS_ENABLED = "${author}<G> - @${code} | </G><V>STATS ENABLED", STATS_DISABLED = "${author}<G> - @${code} | </G><R>STATS DISABLED", SHOW_CLOGS = "<p align='center'><a href='event:changelog'><b>Show changelog</b></a></p>", NEW_VERSION = "<font size='16'><p align='center'><b><J>NEW VERSION <T>${version}</T></J></b></p></font>", MAP_ERROR = "<N>[</N><R>•</R><N>]</N> <R><b>[Map Error]</b>: Reason: <font face='Lucida console'>${reason}</font>\nRetrying another map in 3...</R>", LIST_MAP_PROPS = "<ROSE>[Map Info]</ROSE> <J>@${code}</J> - ${author}\n<ROSE>[Map Info]</ROSE> <VP>Item list:</VP> <N>${items}\n<ROSE>[Map Info]</ROSE> <VP>Allowed:</VP> <N>${allowed}\n<ROSE>[Map Info]</ROSE> <VP>Restricted:</VP> <N>${restricted}", DATA_LOAD_ERROR = "<N>[</N><R>•</R><N>]</N> <R><b>[Error]</b>: We had an issue loading your data; as a result we have stopped saving your data in this room. Rejoining the room might fix the problem.</R>" } translations["br"] = { LIVES_LEFT = "<ROSE>Você possuí <N>${lives} <ROSE>vidas restantes. <VI>Respawning in 3...", LOST_ALL = "<ROSE>Você perdeu todas as suas vidas!", SD = "<VP>Morte súbita! Todos agora possuem <N>1 <VP>vida restante", WELCOME = "<VP>Bem-vindo(a) ao pewpew, <N>duck <VP>or <N>pressione espaço <VP>para poder atirar itens!", SOLE = "<ROSE>${player} é o único sobrevivente!", SURVIVORS = "<ROSE>${winners} e ${winner} sobreviveram nesta rodada!", SELF_RANK = "<p align='center'>Seu rank: ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Rodadas jogadas</N2></font>", DEATHS = "<font face='Lucida console'><N2>Mortes</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Rodadas sobreviventes</N2></font>", WON = "<font face='Lucida console'><N2>Rodadas ganhas</N2></font>", LBOARD_POS = "<b><font face='Lucida console' color='#e3b134'>Tabela de classificação geral: ${pos}</font></b>", EQUIPPED = "Usando", EQUIP = "Usar", BUY = "Comprar", POINTS = "<font face='Lucida console' size='12'> <b>Pontos:</b> <V>${points}</V></font>", PACK_DESC = "\n\n<font face='Lucida console' size='12' color='#cccccc'><i>“ ${desc} ”</i></font>\n<p align='right'><font size='10'>- ${author}</font></p>", GIFT_RECV = "<N>Você foi recompensado com <ROSE><b>${gift}</b></ROSE> por <ROSE><b>${admin}</b></ROSE>", COMMANDS = "\n\n<N2>[ <b>H</b> ]</N2> <N><ROSE>!help</ROSE> (exibe este menu de ajuda)</N><br><N2>[ <b>P</b> ]</N2> <N><ROSE>!profile <i>[player]</i></ROSE> (exibe o perfil do jogador)</N><br></N><N2>[ <b>O</b> ]</N2> <N><ROSE>!shop</ROSE> (exibe o shop)</N><br><N2>[ <b>L</b> ]</N2> <N>(exibe a classificação)</N><br><br><N><ROSE>!changelog</ROSE> (exibe o changelog)</N><br><br>", CMD_TITLE = "<font size='25' face='Comic Sans'><b><J>Comandos</J></b></font>", CREDITS = "\n\nArtist - <b>${artists}</b>\nTranslators - <b>${translators}</b>\n\n\nE muito obrigado por jogar pewpew!", CREDS_TITLE = "<font size='25' face='Comic Sans'><b><R>Credits</R></b></font>", OBJECTIVE = "<b>Sobreviva e mate os demais para poder vencer</b>", HELP_GOTIT = "<font size='15'><J><b><a href='event:close'>Entendi!</a></b></J></font>", HELP_GITHUB = "<N>Quer ser um contribuidor desse module? Bacana! Saiba mais neste link</N> <VI><b><i>https://github.com/Seniru/pewpew</i></b></VI>", HELP_DISCORD = "<N>Discord:</N> <VI><b><i>https://discord.gg/vaqgrgp</i></b></VI>", HELP_MAP = "<N>Quer adicionar seus mapas ao pewpew? Saiba mais neste link</N> <VI><b><i>https://atelier801.com/topic?f=6&t=892550</i></b></VI>", NEW_ROLE = "<N><ROSE><b>${player}</b></ROSE> é agora um <ROSE><b>${role}</b></ROSE>", KICK_ROLE = "<N><ROSE><b>${player}</b></ROSE> não é um <ROSE><b>${role}</b></ROSE> mais! ;c", ERR_PERMS = "<N>[</N><R>•</R><N>] <R><b>Erro: Você não tem permissão para usar esse comando!</b></R>", ERR_CMD = "<N>[</N><R>•</R><N>] <R><b>Erro no comando<br>\tUsage:</b><font face='Lucida console'>${syntax}</i></font></R>", MAP_QUEUED ="<N><ROSE><b>@${map}</b></ROSE> foi colocado na fila por <ROSE><b>${player}</b></ROSE>" } translations["es"] = { LIVES_LEFT = "<ROSE>Te quedan <N>${lives} <ROSE>vidas restantes. <VI>Renaciendo en 3...", LOST_ALL = "<ROSE>¡Has perdido todas tus vidas!", SD = "<VP>¡Muerte súbita! A todos le quedan <N>1 <VP>vida restante", WELCOME = "<VP>¡Bienvenido a pewpew, <N>agáchate <VP>o presiona <N>la barra de espacio <VP>para disparar ítems!", SOLE = "<ROSE>¡${player} es el único superviviente!" } translations["fr"] = { LIVES_LEFT = "<ROSE>Tu as encore <N>${lives} <ROSE>vies restantes. <VI>Réapparition dans 3...", LOST_ALL = "<ROSE>Tu as perdu toutes tes vies !", SD = "<VP>Mort soudaine ! Tout le monde a <N>1 <VP>seule vie restante", WELCOME = "<VP>Bienvenue dans pewpew, <N>baisse-toi <VP>ou utilise la <N>barre d'espace <VP>pour tirer des objets !", SOLE = "<ROSE>${player} est le dernier survivant !", SURVIVORS = "<ROSE>${winners} et ${winner} ont survécu à cette manche !", SELF_RANK = "<p align='center'>Ton rang : ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Manches jouées</N2></font>", DEATHS = "<font face='Lucida console'><N2>Morts</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Manches survécues</N2></font>", WON = "<font face='Lucida console'><N2>Manches gagnées</N2></font>", LBOARD_POS = "<b><font face='Lucida console' color='#e3b134'>Classement global : ${pos}</font></b>", EQUIPPED = "Equipé", EQUIP = "Utiliser", BUY = "Acheter", POINTS = "<font face='Lucida console' size='12'> <b>Points :</b> <V>${points}</V></font>", PACK_DESC = "\n\n<font face='Lucida console' size='12' color='#cccccc'><i>“ ${desc} ”</i></font>\n<p align='right'><font size='10'>- ${author}</font></p>", GIFT_RECV = "<N>Tu as été récompensé avec un(e) <ROSE><b>${gift}</b></ROSE> de la part de <ROSE><b>${admin}</b></ROSE>", COMMANDS = "\n\n<N2>[ <b>H</b> ]</N2> <N><ROSE>!help</ROSE> (Affiche le menu d'aide)</N><br><N2>[ <b>P</b> ]</N2> <N><ROSE>!profile <i>[joueur]</i></ROSE> (Affiche le profile d'un joueur)</N><br></N><N2>[ <b>O</b> ]</N2> <N><ROSE>!shop</ROSE> (Ouvre le magasin)</N><br><N2>[ <b>L</b> ]</N2> <N>(Affiche le classement)</N><br><br><N><ROSE>!changelog</ROSE> (Affiche l'historique des changements)</N><br><br>", CMD_TITLE = "<font size='25' face='Comic Sans'><b><J>Commandes</J></b></font>", CREDITS = "\n\nArtiste - <b>${artists}</b>\nTraducteurs - <b>${translators}</b>\n\n\nEt merci de jouer à Pewpew!", CREDS_TITLE = "<font size='25' face='Comic Sans'><b><R>Credits</R></b></font>", OBJECTIVE = "<b>Survie et tue les autres pour gagner.</b>", HELP_GOTIT = "<font size='15'><J><b><a href='event:close'>Compris !</a></b></J></font>", HELP_GITHUB = "<N>Envie de contribuer à ce module ? Cool ! Va sur </N> <VI><b><i>https://github.com/Seniru/pewpew</i></b></VI>", HELP_DISCORD = "<N>Discord : </N> <VI><b><i>https://discord.gg/vaqgrgp</i></b></VI>", HELP_MAP = "<N>Tu voudrais voir tes maps dans pewpew ? Va sur </N> <VI><b><i>https://atelier801.com/topic?f=6&t=892550</i></b></VI>", NEW_ROLE = "<N><ROSE><b>${player}</b></ROSE> est maintenant un(e) <ROSE><b>${role}</b></ROSE>", KICK_ROLE = "<N><ROSE><b>${player}</b></ROSE> n'est plus un(e) <ROSE><b>${role}</b></ROSE> ! ;c", } translations["tr"] = { LIVES_LEFT = "<N>${lives} <ROSE> canınız kaldı. <VI>3 saniye içinde yeniden doğacaksınız...", LOST_ALL = "<ROSE>Bütün canınızı kaybettiniz!", SD = "<VP>Ani ölüm! Artık herkesin <N>1<VP> canı kald?", WELCOME = "<VP>pewpew odasına hoşgeldiniz, eşyaları fırlatmak için <N>eğilin <VP>ya da <N>spacebar <VP>'a basın!", SOLE = "<ROSE>Yaşayan kişi ${player}!", SURVIVORS = "<ROSE>${winners} ve ${winner} bu turda hayatta kaldı!", SELF_RANK = "<p align='center'>Your rank: ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Oynanılan turlar</N2></font>", DEATHS = "<font face='Lucida console'><N2>Ölümler</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Rounds survived</N2></f ont>", WON = "<font face='Lucida console'><N2>Kazanılan turlar</N2></font>", LBOARD_POS = "<b><font face='Lucida console' color='#e3b134'>Genel Skor Tablosu: ${pos}</font></b>", EQUIPPED = "Donanımlı", EQUIP = "Ekipman", BUY = "Satın Al", POINTS = "<font face='Lucida console' size='12'> <b>Puanlar:</b> <V>${points}</V></font>", PACK_DESC = "\n\n<font face='Lucida console' size='12' color='#cccccc'><i>“ ${desc} ”</i></font>\n<p align='right'><font size='10'>- ${author}</font></p>", GIFT_RECV = "<N>Ödülendirildin seni ödülendiren kişi <ROSE><b>${gift}</b></ROSE> by <ROSE><b>${admin}</b></ROSE>", COMMANDS = "\n\n<N2>[ <b>H</b> ]</N2> <N><ROSE>!help</ROSE> (yardım menüsünü açar)</N><br><N2>[ <b>P</b> ]</N2> <N><ROSE>!profile <i>[oyuncu]</i></ROSE> (istediğiniz kişinin profiline bakarsınız)</N><br></N><N2>[ <b>O</b> ]</N2> <N><ROSE>!shop</ROSE> (Marketi açar)</N><br><N2>[ <b>L</b> ]</N2> <N>(Skor Tablosunu açar)</N><br><br><N><ROSE>!changelog</ROSE> (displays the changelog)</N><br><br>", CMD_TITLE = "<font size='25' face='Comic Sans'><b><J>Komutlar</J></b></font>", CREDITS = "\n\nÇizimler - <b>${artists}</b>\nÇevirmenler - <b>${translators}</b>\n\n\nVe pewpew oynadığınız için teşekkür ederiz!", CREDS_TITLE = "<font size='25' face='Comic Sans'><b><R>Krediler</R></b></font>", OBJECTIVE = "<b>Hayatta kal ve kazanmak için başkalarını öldür</b>", HELP_GOTIT = "<font size='15'><J><b><a href='event:close'>Anladım!</a></b></J></font>", HELP_GITHUB = "<N>Bu modüle katkıda bulunmak ister misiniz? Güzel! Link:</N> <VI><b><i>https://github.com/Seniru/pewpew</i></b></VI>", HELP_DISCORD = "<N>Discord:</N> <VI><b><i>https://discord.gg/vaqgrgp</i></b></VI>", HELP_MAP = "<N>Haritalarınızı pewpew'e eklemek ister misiniz? Link:</N> <VI><b><i>https://atelier801.com/topic?f=6&t=892550</i></b></VI>", NEW_ROLE = "<N><ROSE><b>${player}</b></ROSE> artık bir <ROSE><b>${role}</b></ROSE>", KICK_ROLE = "<N><ROSE><b>${player}</b></ROSE> artık bir <ROSE><b>${role}</b></ROSE> değil! ;c" } translations["tg"] = { LIVES_LEFT = "<ROSE>Mayroon kang <N>${lives} <ROSE>buhay na natitira. <VI>Respawning sa 3...", LOST_ALL = "<ROSE>Nawala lahat nang buhay mo!", SD = "<VP>Biglaang kamatayan! Lahat ay mayroong <N>1 <VP>buhay na natitira", WELCOME = "<VP>Maligayang pagdating sa pewpew, <N>bumaba <VP>o <N>spacebar <VP>para bumaril nang gamit!", SOLE = "<ROSE>${player} ang nag isang nakaligtas!", SURVIVORS = "<ROSE>${winners} at ${winner} ay nakaligtas ngayong round!", SELF_RANK = "<p align='center'>Ranggo mo: ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Rounds na nalaro</N2></font>", DEATHS = "<font face='Lucida console'><N2>Pagkamatay</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Rounds na nakaligtas</N2></font>", WON = "<font face='Lucida console'><N2>Rounds na nanalo</N2></font>" } translations["pl"] = { LIVES_LEFT = "<ROSE>Pozostało ci <N>${lives} <ROSE>żyć! . <VI>Odrodzenie za 3...", LOST_ALL = "<ROSE>Straciłeś wszystkie życia!", SD = "<VP>Nagła śmierć! Każdy został z <N>1 <VP>życiem", WELCOME = "<VP>Witamy w Pewpew, kucnij, kliknij strzałkę w dół lub <N>spacje <VP>aby strzelać przedmiotami!", SOLE = "<ROSE>${player} jest jedynym ocalałym!", SURVIVORS = "<ROSE>${winners} i ${winner} przeżyli tę runde!", SELF_RANK = "<p align='center'>Twoja range: ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Rozegrane rundy</N2></font>", DEATHS = "<font face='Lucida console'><N2>Śmierci</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Przeżyte rundy</N2></font>", WON = "<font face='Lucida console'><N2>Wygrane rundy</N2></font>" } translations["ru"] = { LIVES_LEFT = "<ROSE>Оставшиеся жизни: <N>${lives}. <VI>Вернёшься в игру через 3...", LOST_ALL = "<ROSE>Вы потеряли все cвои жизни!", SD = "<VP>Внезапная смерть! У всех осталась <N>1 <VP>жизнь.", WELCOME = "<VP>Добро пожаловать в pewpew, нажмите на пробел или на s чтобы стрелять предметами.", SOLE = "<ROSE>${player} был единственным выжившим!", SURVIVORS = "<ROSE>${winners} и ${winner} выжили эту игру!", SELF_RANK = "<p align='center'>Ваше место на лидерборде: ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Номер игр</N2></font>", DEATHS = "<font face='Lucida console'><N2>Умер</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Выжил</N2></font>", WON = "<font face='Lucida console'><N2>Выиграл</N2></font>" } translations["hu"] = { LIVES_LEFT = "<ROSE><N>${lives} <ROSE>életed maradt. <VI>Újraéledés 3...", LOST_ALL = "<ROSE>Elvesztetted az összes életed!", SD = "<VP>Hirtelen halál! Mindenkinek <N>1 <VP>élete maradt.", WELCOME = "<VP>Üdvözöl a pewpew! Használd a <N>lefele <VP>vagy a <N>space <VP>gombot, hogy tárgyakat lőj!", SOLE = "<ROSE>${player} az egyetlen túlélő!", SURVIVORS = "<ROSE>${winners} és ${winner} túlélte ezt a kört!", SELF_RANK = "<p align='center'>Rangod: ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Játszott körök</N2></font>", DEATHS = "<font face='Lucida console'><N2>Halálok</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Túlélt körök</N2></font>", WON = "<font face='Lucida console'><N2>Megnyert körök</N2></font>", LBOARD_POS = "<b><font face='Lucida console' color='#e3b134'>Globális ranglista: ${pos}</font></b>", EQUIPPED = "Használva", EQUIP = "Használ", BUY = "Vásárlás", POINTS = "<font face='Lucida console' size='12'> <b>Pont:</b> <V>${points}</V></font>", PACK_DESC = "\n\n<font face='Lucida console' size='12' color='#cccccc'><i>“ ${desc} ”</i></font>\n<p align='right'><font size='10'>- ${author}</font></p>", GIFT_RECV = "<N><ROSE><b>${admin}</b></ROSE> megjutalmazott téged ezzel: <ROSE><b>${gift}</b></ROSE>", COMMANDS = "\n\n<N2>[ <b>H</b> ]</N2> <N><ROSE>!help</ROSE> (megnyitja a segítség menüt)</N><br><N2>[ <b>P</b> ]</N2> <N><ROSE>!profile <i>[játékosNév]</i></ROSE> (megnyitja a játékosNév profilját)</N><br></N><N2>[ <b>O</b> ]</N2> <N><ROSE>!shop</ROSE> (megnyitja a boltot)</N><br><N2>[ <b>L</b> ]</N2> <N>(megnyitja a ranglistát)</N><br><br><N><ROSE>!changelog</ROSE> (megnyitja a változásokat)</N><br><br>", CMD_TITLE = "<font size='25' face='Comic Sans'><b><J>Parancsok</J></b></font>", CREDITS = "\n\nMűvész - <b>${artists}</b>\nFordítók - <b>${translators}</b>\n\n\nÉs köszönöm, hogy játszol a pewpew -el!", CREDS_TITLE = "<font size='25' face='Comic Sans'><b><R>Kreditek</R></b></font>", OBJECTIVE = "<b>Éld túl és ölj meg másokat a győzelemért</b>", HELP_GOTIT = "<font size='15'><J><b><a href='event:close'>Értem!</a></b></J></font>", HELP_GITHUB = "<N>Szeretnél hozzájárulni a modulhoz? Nagyszerű! Csekkold:</N> <VI><b><i>https://github.com/Seniru/pewpew</i></b></VI>", HELP_DISCORD = "<N>Discord:</N> <VI><b><i>https://discord.gg/vaqgrgp</i></b></VI>", HELP_MAP = "<N>Szeretnél benyújtani pályákat? Csekkold:</N> <VI><b><i>https://atelier801.com/topic?f=6&t=892550</i></b></VI>", NEW_ROLE = "<N><ROSE><b>${player}</b></ROSE> most már egy <ROSE><b>${role}</b></ROSE>", KICK_ROLE = "<N><ROSE><b>${player}</b></ROSE> nem <ROSE><b>${role}</b></ROSE> többé! ;c", } translations["ur"] = { LIVES_LEFT = "<ROSE>Ap ke pas <N>${lives} <ROSE>lives hain. <VI>Apke zinda honay me time hai 3...", LOST_ALL = "<ROSE>Ap apni saari lives kho chukay hain!", SD = "<VP>Sudden Death! Sab ke paas <N>1 <VP>life hai", WELCOME = "<VP>Pewpew me khushamadeed!, <N>duck <VP>ya <N>spacebar <VP>se items shoot karain!", SOLE = "<ROSE>${player} sole survivor hain!", SURVIVORS = "<ROSE>${winners} aur ${winner} is round ke survivors hai!", SELF_RANK = "<p align='center'>Apka rank: ${rank}</p>", ROUNDS = "<font face='Lucida console'><N2>Rounds khelay</N2></font>", DEATHS = "<font face='Lucida console'><N2>Deaths</N2></font>", SURVIVED = "<font face='Lucida console'><N2>Rounds survived</N2></font>", WON = "<font face='Lucida console'><N2>Rounds jeetay</N2></font>", LBOARD_POS = "<b><font face='Lucida console' color='#e3b134'>Aalmi leaderboard: ${pos}</font></b>", EQUIPPED = "Equipped", EQUIP = "Equip", BUY = "Khareedien", POINTS = "<font face='Lucida console' size='12'> <b>Points:</b> <V>${points}</V></font>", PACK_DESC = "\n\n<font face='Lucida console' size='12' color='#cccccc'><i>“ ${desc} ”</i></font>\n<p align='right'><font size='10'>- ${author}</font></p>", GIFT_RECV = "<N>Ap ko <ROSE><b>${admin}</b></ROSE> ne <ROSE><b>${gift}</b></ROSE> inaam diya hai", COMMANDS = "\n\n<N2>[ <b>H</b> ]</N2> <N><ROSE>!help</ROSE> (help menu dekhnay ke liye)</N><br><N2>[ <b>P</b> ]</N2> <N><ROSE>!profile <i>[player]</i></ROSE> (Player ki profile dekhnay ke liye)</N><br></N><N2>[ <b>O</b> ]</N2> <N><ROSE>!shop</ROSE> (dukaan kholnay ke liye)</N><br><N2>[ <b>L</b> ]</N2> <N>(leaderboard kholnay ke liye)</N><br><br><N><ROSE>!changelog</ROSE> (changelog dekhnay ke liye)</N><br><br>", CMD_TITLE = "<font size='25' face='Comic Sans'><b><J>Commands</J></b></font>", CREDITS = "\n\nArtist - <b>${artists}</b>\nTranslators - <b>${translators}</b>\n\n\nPewpew khelnay ke liye shukariya!", CREDS_TITLE = "<font size='25' face='Comic Sans'><b><R>Credits</R></b></font>", OBJECTIVE = "<b>Dusron ko maarein aur jeetein.</b>", HELP_GOTIT = "<font size='15'><J><b><a href='event:close'>Got it!</a></b></J></font>", HELP_GITHUB = "<N>Kiya aap bhi is module ki madad krna chahtay hain? Is link pr jayein</N> <VI><b><i>https://github.com/Seniru/pewpew</i></b></VI>", HELP_DISCORD = "<N>Discord:</N> <VI><b><i>https://discord.gg/vaqgrgp</i></b></VI>", HELP_MAP = "<N>Kiya aap apnay maps pewpew mein daalna chahtay hai? Is link pr jayein</N> <VI><b><i>https://atelier801.com/topic?f=6&t=892550</i></b></VI>", NEW_ROLE = "<N><ROSE><b>${player}</b></ROSE> ab <ROSE><b>${role}</b></ROSE> hain!", KICK_ROLE = "<N><ROSE><b>${player}</b></ROSE> ab <ROSE><b>${role}</b></ROSE> nahi hain! ;c", ERR_PERMS = "<N>[</N><R>•</R><N>] <R><b>Error: Ap ye command istemaal nahi kr saktay!</b></R>", ERR_CMD = "<N>[</N><R>•</R><N>] <R><b>Command mein ghalti hai.<br>\tUsage:</b><font face='Lucida console'>${syntax}</i></font></R>", MAP_QUEUED ="<ROSE><b>${player}</b></ROSE> ne <N><ROSE><b>@${map}</b></ROSE> queue mein daala hai." } local translate = function(term, lang, page, kwargs) local translation if translations[lang] then translation = translations[lang][term] or translations.en[term] else translation = translations.en[term] end translation = page and translation[page] or translation if not translation then return end return stringutils.format(translation, kwargs) end --==[[ classes ]]==-- local Player = {} Player.players = {} Player.alive = {} Player.playerCount = 0 Player.aliveCount = 0 Player.__index = Player Player.__tostring = function(self) return table.tostring(self) end setmetatable(Player, { __call = function (cls, name) return cls.new(name) end, }) function Player.new(name) local self = setmetatable({}, Player) self.name = name self.alive = false self.lives = 0 self.inCooldown = true self.community = tfm.get.room.playerList[name].language self.hearts = {} self.rounds = 0 self.survived = 0 self.won = 0 self.score = 0 self.points = 0 self.packs = 1 self.packsArray = {} self.equipped = 1 self.roles = {} self._dataSafeLoaded = false self.tempEquipped = nil self.openedWindow = nil self.version = "v0.0.0.0" for key, code in next, keys do system.bindKeyboard(name, code, true, true) end Player.players[name] = self Player.playerCount = Player.playerCount + 1 return self end function Player:refresh() self.alive = true self.inCooldown = false self:setLives(3) if not Player.alive[self.name] then Player.alive[self.name] = self Player.aliveCount = Player.aliveCount + 1 end setNameColor(self.name) self.tempEquipped = nil end function Player:setLives(lives) self.lives = lives tfm.exec.setPlayerScore(self.name, lives) for _, id in next, self.hearts do tfm.exec.removeImage(id) end self.hearts = {} local heartCount = 0 while heartCount < lives do heartCount = heartCount + 1 self.hearts[heartCount] = tfm.exec.addImage(assets.heart, "$" .. self.name, -45 + heartCount * 15, -45) end end function Player:shoot(x, y) if newRoundStarted and self.alive and not self.inCooldown then if self.equipped == "Random" and not self.tempEquipped then self.tempEquipped = #self.packsArray == 0 and "Default" or self.packsArray[math.random(#self.packsArray)] end self.inCooldown = true local stance = self.stance local pos = getPos(currentItem, stance) local rot = getRot(currentItem, stance) local xSpeed = currentItem == 34 and 60 or 40 local object = tfm.exec.addShamanObject( currentItem, x + pos.x, y + pos.y, rot, stance == -1 and -xSpeed or xSpeed, 0, currentItem == 32 or currentItem == 62 ) local equippedPackName = self.tempEquipped or self.equipped local equippedPack = shop.packs[equippedPackName] local skin = equippedPack.skins[currentItem] if (equippedPackName ~= "Default" and equippedPackName ~= "Random") and skin and skin.image then tfm.exec.addImage( skin.image, "#" .. object, skin.adj.x, skin.adj.y ) end Timer("shootCooldown_" .. self.name, function(object) tfm.exec.removeObject(object) self.inCooldown = false end, 1500, false, object) end end function Player:die() self.lives = 0 self.alive = false tfm.exec.chatMessage(translate("LOST_ALL", self.community), self.name) if statsEnabled then self.rounds = self.rounds + 1 self:savePlayerData() end if Player.alive[self.name] then Player.alive[self.name] = nil Player.aliveCount = Player.aliveCount - 1 end if Player.aliveCount == 1 then local winner = next(Player.alive) local winnerPlayer = Player.players[winner] local n, t = extractName(winner) tfm.exec.chatMessage(translate("SOLE", tfm.get.room.language, nil, {player = "<b><VI>" .. n .. "</VI><font size='8'><N2>" .. t .. "</N2></font></b>"})) tfm.exec.giveCheese(winner) tfm.exec.playerVictory(winner) if statsEnabled then winnerPlayer.rounds = winnerPlayer.rounds + 1 winnerPlayer.survived = winnerPlayer.survived + 1 winnerPlayer.won = winnerPlayer.won + 1 winnerPlayer.points = winnerPlayer.points + 5 winnerPlayer:savePlayerData() end Timer("newRound", newRound, 3 * 1000) elseif Player.aliveCount == 0 then Timer("newRound", newRound, 3 * 1000) end end function Player:hasRole(role) return not not self.roles[role] end function Player:savePlayerData() -- if tfm.get.room.uniquePlayers < MIN_PLAYERS then return end if not self._dataSafeLoaded then return end local name = self.name dHandler:set(name, "rounds", self.rounds) dHandler:set(name, "survived", self.survived) dHandler:set(name, "won", self.won) dHandler:set(name, "points", self.points) dHandler:set(name, "packs", shop.packsBitList:encode(self.packs)) dHandler:set(name, "equipped", self.equipped == "Random" and -1 or shop.packsBitList:find(self.equipped)) dHandler:set(name, "roles", roles.list:encode(self.roles)) dHandler:set(name, "version", self.version) system.savePlayerData(name, "v2" .. dHandler:dumpPlayer(name)) end --==[[ events ]]==-- function eventNewPlayer(name) local player = Player.new(name) tfm.exec.chatMessage(translate("WELCOME", player.community), name) tfm.exec.chatMessage("<N>Discord server:</N> <VI><b><i>https://discord.gg/vaqgrgp</i></b></VI>", name) Timer("banner_" .. name, function(image) tfm.exec.removeImage(image) end, 5000, false, tfm.exec.addImage(assets.banner, ":1", 120, -85, name)) player._dataSafeLoaded = system.loadPlayerData(name) if not player._dataSafeLoaded then tfm.exec.chatMessage(translate("DATA_LOAD_ERROR", player.community), name) end setNameColor(name) end function eventLoop(tc, tr) Timer.process() if tr < 0 and initialized then if not suddenDeath then suddenDeath = true tfm.exec.chatMessage(translate("SD", tfm.get.room.language)) for name, player in next, Player.alive do player:setLives(1) end tfm.exec.setGameTime(30, true) else local aliveCount = Player.aliveCount if aliveCount > 1 then local winners = "" local winner = "" for name, player in next, Player.alive do if statsEnabled then player.rounds = player.rounds + 1 player.survived = player.survived + 1 player.points = player.points + 2 player:savePlayerData() end if aliveCount == 1 then winners = winners:sub(1, -3) local n, t = extractName(name) winner = "<b><VI>" .. n .. "</VI><font size='8'><N2>" .. t .. "</N2></font></b>" break end local n, t = extractName(name) winners = winners .. "<b><VI>" .. n .. "</VI><font size='8'><N2>" .. t .. "</N2></font></b>" .. ", " aliveCount = aliveCount - 1 end tfm.exec.chatMessage(translate("SURVIVORS", tfm.get.room.language, nil, { winners = winners, winner = winner })) end newRoundStarted = false Timer("newRound", newRound, 3 * 1000) tfm.exec.setGameTime(4, true) end end end function eventKeyboard(name, key, down, x, y) if key == keys.SPACE or key == keys.DOWN then Player.players[name]:shoot(x, y) elseif key == keys.LEFT then Player.players[name].stance = -1 elseif key == keys.RIGHT then Player.players[name].stance = 1 elseif key == keys.LETTER_H then displayHelp(name, true) elseif key == keys.LETTER_P then displayProfile(Player.players[name], name, true) elseif key == keys.LETTER_L then leaderboard.displayLeaderboard("global", 1, name, true) elseif key == keys.LETTER_O then shop.displayShop(name, 1, true) end end local attributes = { "ALLOWED", "RESTRICT", "GREY" } function eventNewGame() if not initialized then return end local fromQueue = mapProps.fromQueue mapProps = { allowed = nil, restricted = nil, grey = nil, items = items, fromQueue = fromQueue } local xml = tfm.get.room.xmlMapInfo.xml:upper() local hasSpecialAttrs = false for _, attr in next, attributes do if xml:find(attr) then hasSpecialAttrs = true break end end -- Handle special map attributes local dom = parseXml(xml, true) local P = path(dom, "P")[1] if hasSpecialAttrs then mapProps.allowed = P.attribute.ALLOWED mapProps.restricted = P.attribute.RESTRICT local mapFailback = function(err) tfm.exec.chatMessage(translate("MAP_ERROR", tfm.get.room.community, nil, { reason = err})) newRoundStarted = false Timer("newRound", newRound, 3 * 1000) tfm.exec.setGameTime(4, true) end if mapProps.allowed then mapProps.allowed = stringutils.split(mapProps.allowed, ",") mapProps.items = table.map(mapProps.allowed, tonumber) end if mapProps.restricted then mapProps.restricted = table.map(stringutils.split(mapProps.restricted, ","), tonumber) if table.find(mapProps.restricted, 17) then return mapFailback("Item 17 cannot be a restricted item") end for _, item in next, mapProps.restricted do table.remove(mapProps.items, table.find(mapProps.items, item)) end end if fromQueue then tfm.exec.chatMessage(translate("LIST_MAP_PROPS", tfm.get.room.language, nil, { code = tfm.get.room.xmlMapInfo.mapCode, author = tfm.get.room.xmlMapInfo.author, items = table.concat(mapProps.items or {"-"}, ", "), allowed = table.concat(mapProps.allowed or {"-"}, ", "), restricted = table.concat(mapProps.restricted or {"-"}, ", "), })) end end -- other visual tasks local changeItemTimer = Timer._timers["changeItem"] if changeItemTimer then changeItemTimer:setArgs(mapProps.items) changeItemTimer:call() changeItemTimer:reset() end ui.setMapName(translate(statsEnabled and "STATS_ENABLED" or "STATS_DISABLED", tfm.get.room.community, nil, { author = tfm.get.room.xmlMapInfo.author, code = tfm.get.room.xmlMapInfo.mapCode })) Timer("pre", function() Timer("count3", function(count3) tfm.exec.removeImage(count3) Timer("count2", function(count2) tfm.exec.removeImage(count2) Timer("count1", function(count1) tfm.exec.removeImage(count1) newRoundStarted = true Timer("roundStart", function(imageGo) tfm.exec.removeImage(imageGo) end, 1000, false, tfm.exec.addImage(assets.newRound, ":1", 145, -120)) end, 1000, false, tfm.exec.addImage(assets.count1, ":1", 145, -120)) end, 1000, false, tfm.exec.addImage(assets.count2, ":1", 145, -120)) end, 1000, false, tfm.exec.addImage(assets.count3, ":1", 145, -120)) end, Player.playerCount == 1 and 0 or 4000) end function eventPlayerDied(name) local player = Player.players[name] if not player then return end if not newRoundStarted then tfm.exec.respawnPlayer(name) return player:refresh() end player.lives = player.lives - 1 tfm.exec.setPlayerScore(name, player.lives) player.alive = false if player.lives == 0 then player:die() else tfm.exec.chatMessage(translate("LIVES_LEFT", player.community, nil, {lives = player.lives}), name) Timer("respawn_" .. name, function() tfm.exec.respawnPlayer(name) setNameColor(name) player:setLives(player.lives) player.alive = true end, 3000, false) end end function eventPlayerLeft(name) local player = Player.players[name] if not player then return end player:die() Player.players[name] = nil Player.playerCount = Player.playerCount - 1 -- statsEnabled = (not isTribeHouse) and tfm.get.room.uniquePlayers >= 4 end function eventPlayerDataLoaded(name, data) -- reset player data if they are stored according to the old version if data:find("^v2") then dHandler:newPlayer(name, data:sub(3)) else system.savePlayerData(name, "") dHandler:newPlayer(name, "") end local player = Player.players[name] player.rounds = dHandler:get(name, "rounds") player.survived = dHandler:get(name, "survived") player.won = dHandler:get(name, "won") player.points = dHandler:get(name, "points") player.packs = shop.packsBitList:decode(dHandler:get(name, "packs")) local counter = 1 for pack, hasPack in next, player.packs do if pack ~= "Default" and hasPack then player.packsArray[counter] = pack counter = counter + 1 end end player.packs["Random"] = true local equipped = dHandler:get(name, "equipped") player.equipped = equipped == -1 and "Random" or shop.packsBitList:get(equipped) player.roles = roles.list:decode(dHandler:get(name, "roles")) player.highestRole = roles.getHighestRole(player) setNameColor(name) player.version = dHandler:get(name, "version") if player.version ~= VERSION then player.version = VERSION player:savePlayerData() if VERSION_IMG then player.openedWindow = newsWindow newsWindow:show(name) Panel.panels[1050]:update(translate("SHOW_CLOGS", player.community)) Panel.panels[1051]:update(translate("NEW_VERSION", player.community, nil, { version = VERSION })) end end end function eventFileLoaded(id, data) -- print(table.tostring(leaderboard.leaders)) if id == leaderboard.FILE_ID or id == tostring(leaderboard.FILE_ID) then print("[STATS] Leaderboard and map data loaded!") local sections = stringutils.split(data, "\n\n") local lBoardData = sections[1] if maps.dumpCache ~= sections[2] and not maps.overwriteFile then maps.dumpCache = sections[2] maps.list = stringutils.split(maps.dumpCache, ",") end if #rotation < 50 then rotation = shuffleMaps(maps.list) end if not (leaderboard.leaderboardData == lBoardData) then leaderboard.leaderboardData = lBoardData leaderboard.leaders = leaderboard.parseLeaderboard(lBoardData) end for name, player in next, Player.players do leaderboard.addPlayer(player) end leaderboard.save(leaderboard.leaders, #leaderboardNotifyList > 0) -- force save when required end end function eventFileSaved(id) if id == leaderboard.FILE_ID or id == tostring(leaderboard.FILE_ID) then print("[STATS] Leaderboard saved!") print(os.time()) for _, player in next, leaderboardNotifyList do tfm.exec.chatMessage("<N>[</N><R>•</R><N>] Files have been updated!", player) end leaderboardNotifyList = {} leaderboard.needUpdate = false maps.overwriteFile = false end end function eventChatCommand(name, cmd) local args = stringutils.split(cmd, " ") if cmds[args[1]] then local cmdArgs = {} for i = 2, #args do cmdArgs[#cmdArgs + 1] = args[i] end cmds[args[1]](cmdArgs, cmd, name) end end function eventTextAreaCallback(id, name, event) Panel.handleActions(id, name, event) end --==[[ main ]]==-- leaderboard = {} leaderboard.FILE_ID = 2 leaderboard.DUMMY_DATA = [[*souris1,0,0,0,xx|*souris2,0,0,0,xx|*souris3,0,0,0,xx|*souris4,0,0,0,xx|*souris5,0,0,0,xx|*souris6,0,0,0,xx|*souris7,0,0,0,xx|*souris8,0,0,0,xx|*souris9,0,0,0,xx|*souris10,0,0,0,xx|*souris11,0,0,0,xx|*souris12,0,0,0,xx|*souris13,0,0,0,xx|*souris14,0,0,0,xx|*souris15,0,0,0,xx|*souris16,0,0,0,xx|*souris17,0,0,0,xx|*souris18,0,0,0,xx|*souris19,0,0,0,xx|*souris20,0,0,0,xx|*souris21,0,0,0,xx|*souris22,0,0,0,xx|*souris23,0,0,0,xx|*souris24,0,0,0,xx|*souris25,0,0,0,xx|*souris26,0,0,0,xx|*souris27,0,0,0,xx|*souris28,0,0,0,xx|*souris29,0,0,0,xx|*souris30,0,0,0,xx|*souris31,0,0,0,xx|*souris32,0,0,0,xx|*souris33,0,0,0,xx|*souris34,0,0,0,xx|*souris35,0,0,0,xx|*souris36,0,0,0,xx|*souris37,0,0,0,xx|*souris38,0,0,0,xx|*souris39,0,0,0,xx|*souris40,0,0,0,xx|*souris41,0,0,0,xx|*souris42,0,0,0,xx|*souris43,0,0,0,xx|*souris44,0,0,0,xx|*souris45,0,0,0,xx|*souris46,0,0,0,xx|*souris47,0,0,0,xx|*souris48,0,0,0,xx|*souris49,0,0,0,xx|*souris50,0,0,0,xx]] leaderboard.needUpdate = false leaderboard.indexed = {} leaderboard.leaderboardData = leaderboard.leaderboardData or leaderboard.DUMMY_DATA leaderboard.parseLeaderboard = function(data) local res = {} for i, entry in next, stringutils.split(data, "|") do local fields = stringutils.split(entry, ",") local name = fields[1] res[name] = { name = name, rounds = tonumber(fields[2]), survived = tonumber(fields[3]), won = tonumber(fields[4]), community = fields[5] } res[name].score = leaderboard.scorePlayer(res[name]) end return res end leaderboard.dumpLeaderboard = function(lboard) local res = "" for i, entry in next, lboard do res = res .. entry.name .. "," .. entry.rounds .. "," .. entry.survived .. "," .. entry.won .. "," .. entry.community .. "|" end return res:sub(1, -2) end leaderboard.load = function() local started = system.loadFile(leaderboard.FILE_ID) if started then print("[STATS] Loading leaderboard...") end end leaderboard.save = function(leaders, force) local serialised, indexes = leaderboard.prepare(leaders) --if (not force) then return end leaderboard.indexed = indexes if (not force) and serialised == leaderboard.leaderboardData and tfm.get.room.uniquePlayers < 4 then return end local started = system.saveFile(serialised .. "\n\n" .. maps.dumpCache, leaderboard.FILE_ID) if started then print("[STATS] Saving leaderboard...") end end leaderboard.scorePlayer = function(player) return player.rounds * 0.5 * ((player.won + player.survived) / (player.rounds == 0 and 1 or player.rounds)) end leaderboard.addPlayer = function(player) if not player._dataSafeLoaded then return end local score = leaderboard.scorePlayer(player) leaderboard.leaders[player.name] = { name = player.name, rounds = player.rounds, survived = player.survived, won = player.won, community = player.community, score = score } end leaderboard.prepare = function(leaders) local temp, res = {}, {} for name, leader in next, leaders do if not banned[name] then temp[#temp + 1] = leader end end table.sort(temp, function(p1, p2) return p1.score > p2.score end) for i = 1, 50 do res[i] = temp[i] end return leaderboard.dumpLeaderboard(res), res end leaderboard.displayLeaderboard = function(mode, page, target, keyPressed) local targetPlayer = Player.players[target] if targetPlayer.openedWindow then targetPlayer.openedWindow:hide(target) if targetPlayer.openedWindow == leaderboardWindow and keyPressed then targetPlayer.openedWindow = nil return end end leaderboardWindow:show(target) local leaders = {} local rankTxt, nameTxt, roundsTxt, deathsTxt, survivedTxt, wonTxt = "<br><br>", "<br><br>", "<br><br>", "<br><br>", "<br><br>", "<br><br>" if mode == "global" then for leader = (page - 1) * 10 + 1, page * 10 do leaders[#leaders + 1] = leaderboard.indexed[leader] end Panel.panels[356]:update("<font size='20'><BV><p align='center'><a href='event:1'>•</a> <a href='event:2'>•</a> <a href='event:3'>•</a> <a href='event:4'>•</a> <a href='event:5'>•</a></p>") Panel.panels[357]:update("<a href='event:switch'>Global \t ▼</a>", target) else local selfRank for name, player in next, Player.players do leaders[#leaders + 1] = player end table.sort(leaders, function(p1, p2) return leaderboard.scorePlayer(p1) > leaderboard.scorePlayer(p2) end) for i, leader in ipairs(leaders) do if leader.name == target then selfRank = i break end end -- TODO: Add translations v Panel.panels[356]:update(translate("SELF_RANK", targetPlayer.community, nil, { rank = selfRank }), target) Panel.panels[357]:update("<a href='event:switch'>Room \t ▼</a>", target) end local counter = 0 local rankPage = (page - 1) * 10 for i, leader in next, leaders do local name, tag = extractName(leader.name) if not (name and tag) then name, tag = leader.name, "" end counter = counter + 1 rankTxt = rankTxt .. "# " .. rankPage + counter .. "<br>" nameTxt = nameTxt .. " <b><V>" .. name .. "</V><N><font size='8'>" .. tag .. "</font></N></b><br>" roundsTxt = roundsTxt .. leader.rounds .. "<br>" deathsTxt = deathsTxt .. (leader.rounds - leader.survived) .. "<br>" survivedTxt = survivedTxt .. leader.survived .. " <V><i><font size='9'>(" .. math.floor(leader.survived / (leader.rounds == 0 and 1 or leader.rounds) * 100) .. " %)</font></i></V><br>" wonTxt = wonTxt .. leader.won .. " <V><i><font size='9'>(" .. math.floor(leader.won / (leader.rounds == 0 and 1 or leader.rounds) * 100) .. " %)</font></i></V><br>" Panel.panels[351]:addImageTemp(Image(assets.community[leader.community], "&1", 170, 115 + 13 * counter), target) if counter >= 10 then break end end Panel.panels[350]:update(rankTxt, target) Panel.panels[351]:update(nameTxt, target) Panel.panels[352]:update(roundsTxt, target) Panel.panels[353]:update(deathsTxt, target) Panel.panels[354]:update(survivedTxt, target) Panel.panels[355]:update(wonTxt, target) targetPlayer.openedWindow = leaderboardWindow end leaderboard.leaders = leaderboard.parseLeaderboard(leaderboard.leaderboardData) shop = {} -- Images to display in shop if some items are missing in the pack shop.defaultItemImages = { [ENUM_ITEMS.CANNON] = "175301924fd.png", [ENUM_ITEMS.ANVIL] = "17530198302.png", [ENUM_ITEMS.BALL] = "175301924fd.png", [ENUM_ITEMS.BLUE_BALOON] = "175301b5151.png", [ENUM_ITEMS.LARGE_BOX] = "175301a8692.png", [ENUM_ITEMS.SMALL_BOX] = "175301adef2.png", [ENUM_ITEMS.LARGE_PLANK] = "1753019e778.png", [ENUM_ITEMS.SMALL_PLANK] = "175301a35c2.png" } -- Item packs that are used to display in the shop interface shop.packs = { ["Random"] = { coverImage = "1756e10f5e0.png", coverAdj = { x = 3, y = 0 }, description = "It's all random 0m0", author = "rand()", price = 0, description_locales = { en = "It's all random 0m0", fr = "C'est que du hasard 0m0", br = "É tudo aleatório 0m0", ur = "Sab random hai 0m0" }, skins = { [ENUM_ITEMS.CANNON] = { image = "1756df9f351.png" }, [ENUM_ITEMS.ANVIL] = { image = "1756dfa81b1.png" }, [ENUM_ITEMS.BALL] = { image = "1756df9f351.png" }, [ENUM_ITEMS.BLUE_BALOON] = { image = "1756dfa3e9a.png" }, [ENUM_ITEMS.LARGE_BOX] = { image = "1756dfad0ff.png" }, [ENUM_ITEMS.SMALL_BOX] = { image = "1756dfafe31.png" }, [ENUM_ITEMS.LARGE_PLANK] = { image = "1756dfb428f.png" }, [ENUM_ITEMS.SMALL_PLANK] = { image = "1756e01b60d.png" } } }, ["Default"] = { coverImage = "175405f30a3.png", coverAdj = { x = 15, y = 5 }, description = "Default item pack", author = "Transformice", price = 0, description_locales = { en = "Default item pack", fr = "Pack de texture par défaut.", br = "Pacote de itens padrão", ur = "Default cheezon ka pack" }, skins = { [ENUM_ITEMS.CANNON] = { image = "1752b1c10bc.png" }, [ENUM_ITEMS.ANVIL] = { image = "1752b1b9497.png" }, [ENUM_ITEMS.BALL] = { image = "1752b1bdeee.png" }, [ENUM_ITEMS.BLUE_BALOON] = { image = "1752b1aa57c.png" }, [ENUM_ITEMS.LARGE_BOX] = { image = "1752b1adb5e.png" }, [ENUM_ITEMS.SMALL_BOX] = { image = "1752b1b1cc6.png" }, [ENUM_ITEMS.LARGE_PLANK] = { image = "1752b1b5ac3.png" }, [ENUM_ITEMS.SMALL_PLANK] = { image = "1752b0918ed.png" } } }, ["Poisson"] = { coverImage = "17540405f67.png", coverAdj = { x = 8, y = 8 }, description = "Back in old days...", author = "Transformice", price = 100, description_locales = { en = "Back in old days...", fr = "Comme au bon vieux temps...", br = "De volta aos velhos tempos...", ur = "Puranay dino mein..." }, skins = { [ENUM_ITEMS.CANNON] = { image = "174bb44115d.png", adj = { x = -16, y = -16 } }, [ENUM_ITEMS.ANVIL] = { }, [ENUM_ITEMS.BALL] = { image = "174bb405fd4.png", adj = { x = -16, y = -16 } }, [ENUM_ITEMS.BLUE_BALOON] = { }, [ENUM_ITEMS.LARGE_BOX] = { image = "174c530f384.png", adj = { x = -30, y = -30 } }, [ENUM_ITEMS.SMALL_BOX] = { image = "174c532630c.png", adj = { x = -16, y = -16 } }, [ENUM_ITEMS.LARGE_PLANK] = { image = "174c5311ea4.png", adj = { x = -104, y = -6 } }, [ENUM_ITEMS.SMALL_PLANK] = { image = "174c5324b9b.png", adj = { x = -50, y = -6 } } } }, ["Catto"] = { coverImage = "1754528ac5c.png", coverAdj = { x = 8, y = 0 }, description = "Meow!", author = "King_seniru#5890", price = 300, description_locales = { en = "Meow!", fr = "Miaou !", br = "Miau!", }, skins = { [ENUM_ITEMS.CANNON] = { image = "17530cc2bfb.png", adj = { x = -16, y = -16 } }, [ENUM_ITEMS.ANVIL] = { image = "17530cb9535.png", adj = { x = -24, y = -24 } }, [ENUM_ITEMS.BALL] = { image = "17530cb1c03.png", adj = { x = -16, y = -16 } }, [ENUM_ITEMS.BLUE_BALOON] = { image = "17530cc8b06.png", adj = { x = -18, y = -18 } }, [ENUM_ITEMS.LARGE_BOX] = { image = "17530ccf337.png", adj = { x = -30, y = -30 } }, [ENUM_ITEMS.SMALL_BOX] = { image = "17530cd4a81.png", adj = { x = -16, y = -16 } }, [ENUM_ITEMS.LARGE_PLANK] = { image = "17530cf135f.png", adj = { x = -100, y = -14 } }, [ENUM_ITEMS.SMALL_PLANK] = { image = "17530cf9d23.png", adj = { x = -50, y = -14 } } } }, ["Royal"] = { coverImage = "1754f97c21c.png", coverAdj = { x = 8, y = 0 }, description = "Only for the strongest kings!", author = "Lightymouse#0421", price = 300, description_locales = { en = "Only for the strongest kings!", fr = "Seulement pour les rois les plus fort !", br = "Apenas para os reis mais fortes!", ur = "Sab se bahadur badshah ke liye!" }, skins = { [ENUM_ITEMS.CANNON] = { image = "1754f9851c8.png", adj = { x = -17, y = -17 } }, [ENUM_ITEMS.ANVIL] = { image = "1754f98d0b8.png", adj = { x = -24, y = -34 } }, [ENUM_ITEMS.BALL] = { image = "1754f9a7601.png", adj = { x = -16, y = -16 } }, [ENUM_ITEMS.BLUE_BALOON] = { image = "1754fca819f.png", adj = { x = -22, y = -22 } }, [ENUM_ITEMS.LARGE_BOX] = { image = "1754f9b87a6.png", adj = { x = -35, y = -35 } }, [ENUM_ITEMS.SMALL_BOX] = { image = "1754f9d18f6.png", adj = { x = -19, y = -19 } }, [ENUM_ITEMS.LARGE_PLANK] = { image = "1754f9d7544.png", adj = { x = -100, y = -10 } }, [ENUM_ITEMS.SMALL_PLANK] = { image = "1754f9dc2a0.png", adj = { x = -50, y = -10 } } } }, ["Halloween 2020"] = { coverImage = "175832f4631.png", coverAdj = { x = 8, y = 0 }, description = "Trick or Treat!?", author = "Thetiger56#6961", price = 400, description_locales = { en = "Trick or Treat!?", fr = "Un bonbon ou un sort !?", br = "Gostosuras ou Travessuras?", ur = "Trick ya treat!?" }, skins = { [ENUM_ITEMS.CANNON] = { image = "175829957ec.png", adj = { x = -17, y = -17 } }, [ENUM_ITEMS.ANVIL] = { image = "17582960dfd.png", adj = { x = -22, y = -24 } }, [ENUM_ITEMS.BALL] = { image = "17582965a03.png", adj = { x = -17, y = -19 } }, [ENUM_ITEMS.BLUE_BALOON] = { image = "1758295cf4b.png", adj = { x = -22, y = -22 } }, [ENUM_ITEMS.LARGE_BOX] = { image = "175829687b2.png", adj = { x = -32, y = -32 } }, [ENUM_ITEMS.SMALL_BOX] = { image = "1758296be0c.png", adj = { x = -19, y = -19 } }, [ENUM_ITEMS.LARGE_PLANK] = { image = "175829715e2.png", adj = { x = -100, y = -6 } }, [ENUM_ITEMS.SMALL_PLANK] = { image = "17582976871.png", adj = { x = -50, y = -13 } } } }, ["Christmas 2020"] = { coverImage = "1765abc248e.png", coverAdj = { x = 0, y = 0 }, description = "Ho ho ho, Merry Christmas!!", author = "Thetiger56#6961", price = 400, description_locales = { en = "Ho ho ho, Merry Christmas!!", fr = "Ho ho Ho, Joyeux Noël !!", br = "Ho ho ho, Feliz Natal!!", ur = "Ho ho ho, Christmas mubarak!!" }, skins = { [ENUM_ITEMS.CANNON] = { image = "1765abff096.png", adj = { x = -17, y = -17 } }, [ENUM_ITEMS.ANVIL] = { image = "1765ac2ed92.png", adj = { x = -24, y = -28 } }, [ENUM_ITEMS.BALL] = { image = "1765ac10519.png", adj = { x = -17, y = -18 } }, [ENUM_ITEMS.BLUE_BALOON] = { image = "17660481ac5.png", adj = { x = -25, y = -24 } }, [ENUM_ITEMS.LARGE_BOX] = { image = "1765aca14d3.png", adj = { x = -32, y = -32 } }, [ENUM_ITEMS.SMALL_BOX] = { image = "1765ad54bea.png", adj = { x = -17, y = -17 } }, [ENUM_ITEMS.LARGE_PLANK] = { image = "1765ad8d77d.png", adj = { x = -100, y = -17 } }, [ENUM_ITEMS.SMALL_PLANK] = { image = "1765ad9f608.png", adj = { x = -50, y = -18 } } } }, } shop.totalPacks = 0 for pack in next, shop.packs do shop.totalPacks = shop.totalPacks + 1 end shop.totalPages = math.ceil((shop.totalPacks) / 6) shop.packsBitList = BitList { "Default", "Poisson", "Catto", "Royal", "Halloween 2020", "Christmas 2020" } shop.displayShop = function(target, page, keyPressed) page = page or 1 if page < 1 or page > shop.totalPages then return end local targetPlayer = Player.players[target] local commu = targetPlayer.community if targetPlayer.openedWindow then targetPlayer.openedWindow:hide(target) if targetPlayer.openedWindow == shopWindow and keyPressed then targetPlayer.openedWindow = nil return end end shopWindow:show(target) shop.displayPackInfo(target, targetPlayer.equipped) Panel.panels[520]:update(translate("POINTS", commu, nil, { points = targetPlayer.points }), target) Panel.panels[551]:update(("<a href='event:%s'><p align='center'><b>%s〈%s</b></p></a>") :format( page - 1, page - 1 < 1 and "<N2>" or "", page - 1 < 1 and "</N2>" or "" ) , target) Panel.panels[552]:update(("<a href='event:%s'><p align='center'><b>%s〉%s</b></p></a>") :format( page + 1, page + 1 > shop.totalPages and "<N2>" or "</N2>", page + 1 > shop.totalPages and "</N2>" or "</N2>" ) , target) targetPlayer.openedWindow = shopWindow local col, row, count = 0, 0, 0 for i = (page - 1) * 6 + 1, page * 6 do local name = i == 1 and "Random" or shop.packsBitList:get(i - 1) if not name then return end local pack = shop.packs[name] local packPanel = Panel(560 + count, "", 380 + col * 120, 100 + row * 120, 100, 100, 0x1A3846, 0x1A3846, 1, true) :addImageTemp(Image(pack.coverImage, "&1", 400 + (pack.coverAdj and pack.coverAdj.x or 0) + col * 120, 100 + (pack.coverAdj and pack.coverAdj.y or 0) + row * 120, target), target) :addPanel( Panel(560 + count + 1, ("<p align='center'><a href='event:%s'>%s</a></p>"):format(name, name), 385 + col * 120, 170 + row * 120, 90, 20, nil, 0x324650, 1, true) :setActionListener(function(id, name, event) shop.displayPackInfo(name, event) end) ) if not targetPlayer.packs[name] then packPanel:addImageTemp(Image(assets.lock, "&1", 380 + col * 120, 80 + row * 120, target), target) end shopWindow:addPanelTemp(packPanel, target) col = col + 1 count = count + 2 if col >= 3 then row = row + 1 col = 0 end end end shop.displayPackInfo = function(target, packName) local pack = shop.packs[packName] local player = Player.players[target] local commu = player.community Panel.panels[610]:hide(target):show(target) Panel.panels[620]:addImageTemp(Image(pack.coverImage, "&1", 80 + (pack.coverAdj and pack.coverAdj.x or 0), 80 + (pack.coverAdj and pack.coverAdj.y or 0), target), target) Panel.panels[620]:update(" <font size='15' face='Lucida console'><b><BV>" .. packName .. "</BV></b></font>", target) local hasEquipped = player.equipped == packName local hasBought = not not player.packs[packName] local hasRequiredPoints = player.points >= pack.price Panel.panels[650]:update(("<p align='center'><b><a href='event:%s:%s'>%s</a></b></p>") :format( hasEquipped and "none" or (hasBought and "equip" or (hasRequiredPoints and "buy" or "none")), packName, hasEquipped and translate("EQUIPPED", commu) or (hasBought and translate("EQUIP", commu) or (hasRequiredPoints and (translate("BUY", commu) .. ": " .. pack.price) or ("<N2>" .. translate("BUY", commu) .. ": " .. pack.price .. "</N2>") ) ) ) , target) local n, t = extractName(pack.author) Panel.panels[651]:update(translate("PACK_DESC", commu, nil, { desc = (pack.description_locales[commu] or pack.description), author = "<V>" .. n .. "</V><N2>" .. t .. "</N2>" } ), target) Panel.panels[652] :addImageTemp(Image(pack.skins[ENUM_ITEMS.CANNON].image or shop.defaultItemImages[ENUM_ITEMS.CANNON], "&1", 80, 160), target) :addImageTemp(Image(pack.skins[ENUM_ITEMS.ANVIL].image or shop.defaultItemImages[ENUM_ITEMS.ANVIL], "&1", 130, 150), target) :addImageTemp(Image(pack.skins[ENUM_ITEMS.BLUE_BALOON].image or shop.defaultItemImages[ENUM_ITEMS.BLUE_BALOON], "&1", 195, 160), target) :addImageTemp(Image(pack.skins[ENUM_ITEMS.BALL].image or shop.defaultItemImages[ENUM_ITEMS.BALL], "&1", 250, 160), target) :addImageTemp(Image(pack.skins[ENUM_ITEMS.LARGE_BOX].image or shop.defaultItemImages[ENUM_ITEMS.LARGE_BOX], "&1", 80, 220), target) :addImageTemp(Image(pack.skins[ENUM_ITEMS.SMALL_BOX].image or shop.defaultItemImages[ENUM_ITEMS.SMALL_BOX], "&1", 160, 220), target) :addImageTemp(Image(pack.skins[ENUM_ITEMS.LARGE_PLANK].image or shop.defaultItemImages[ENUM_ITEMS.LARGE_PLANK], "&1", 80, 300), target) :addImageTemp(Image(pack.skins[ENUM_ITEMS.SMALL_PLANK].image or shop.defaultItemImages[ENUM_ITEMS.SMALL_PLANK], "&1", 80, 320), target) end roles = {} roles.list = BitList { "admin", "staff", "developer", "artist", "translator", "mapper" } roles.colors = { ["admin"] = 0xFF5555, ["staff"] = 0xF3D165, ["developer"] = 0x7BC7F7, ["artist"] = 0xFF69B4, ["translator"] = 0xB69EFD, ["mapper"] = 0x87DF87 } roles.images = { ["admin"] = "178598716f4.png", ["staff"] = "17859a9985c.png", ["developer"] = "17859b0531e.png", ["artist"] = "17859ab0277.png", ["translator"] = "17859b2cb23.png", ["mapper"] = "17859b68e86.png" } roles.addRole = function(player, role) player.roles[role] = true player.highestRole = roles.getHighestRole(player) setNameColor(player.name) tfm.exec.chatMessage(translate("NEW_ROLE", tfm.get.room.language, nil, { player = player.name, role = role })) player:savePlayerData() end roles.removeRole = function(player, role) player.roles[role] = nil player.highestRole = roles.getHighestRole(player) tfm.exec.setNameColor(player.name, 0) -- set it to default color in case of all the colors are removed setNameColor(player.name) tfm.exec.chatMessage(translate("KICK_ROLE", tfm.get.room.language, nil, { player = player.name, role = role })) player:savePlayerData() end roles.getHighestRole = function(player) for i, rank in next, roles.list.featureArray do if player.roles[rank] then return rank end end return "default" end cmds = { ["profile"] = function(args, msg, author) local player = Player.players[args[1] or author] or Player.players[author] displayProfile(player, author) end, ["help"] = function(args, msg, author) displayHelp(author) end, ["shop"] = function(args, msg, author) shop.displayShop(author, 1) end, ["changelog"] = function(args, msg, author) displayChangelog(author) end, -- [[ administration commands ]] ["give"] = function(args, msg, author) local player = Player.players[author] if not (admins[author] or player:hasRole("staff")) then return end local FORMAT_ERR_MSG = "<N>[</N><R>•</R><N>] <R><b>Error in command<br>\tUsage:</b><font face='Lucida console'> !give <i>[points|pack] [target] [value]</i></font></R>" local TARGET_UNREACHABLE_ERR = "<N>[</N><R>•</R><N>] <R><b>Error: Target unreachable!</b></R>" if (not args[1]) or (not args[2]) or (not args[3]) then return tfm.exec.chatMessage(FORMAT_ERR_MSG, author) end local target = Player.players[args[2]] local n, t = extractName(author) if args[1] == "points" then if not target then return tfm.exec.chatMessage(TARGET_UNREACHABLE_ERR, author) end local points = tonumber(args[3]) if not points then return tfm.exec.chatMessage(FORMAT_ERR_MSG, author) end -- NaN target.points = target.points + points target:savePlayerData() print(("[GIFT] %s has been rewarded with %s by %s"):format(args[2], points .. " Pts.", author)) tfm.exec.chatMessage(("<N>[</N><ROSE>•</ROSE><N>] Rewarded <ROSE>%s</ROSE> with <ROSE>%s</ROSE> points"):format(args[2], points), author) tfm.exec.chatMessage(translate("GIFT_RECV", target.community, nil, { admin = "<VI>" .. n .. "</VI><font size='8'><N2>" .. t .. "</N2></font>", gift = points .. " Pts." }), args[2]) elseif args[1] == "pack" then if not target then return tfm.exec.chatMessage(TARGET_UNREACHABLE_ERR, author) end local pack = msg:match("give pack .+#%d+ (.+)") if not shop.packs[pack] then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error:</b> Could not find the pack</R>", author) end if target.packs[pack] then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error: </b>Target already own that pack</R>", author) end target.packs[pack] = true target:savePlayerData() print(("[GIFT] %s has been rewarded with %s by %s"):format(args[2], pack, author)) tfm.exec.chatMessage(("<N>[</N><ROSE>•</ROSE><N>] Rewarded <ROSE>%s</ROSE> with <ROSE>%s</ROSE>"):format(args[2], pack), author) tfm.exec.chatMessage(translate("GIFT_RECV", target.community, nil, { admin = "<VI>" .. n .. "</VI><font size='8'><N2>" .. t .. "</N2></font>", gift = pack }), args[2]) else tfm.exec.chatMessage(FORMAT_ERR_MSG, author) end end, ["pw"] = function(args, msg, author) local player = Player.players[author] if not (admins[author] or player:hasRole("staff")) then return end local pw = msg:match("^pw (.+)") tfm.exec.setRoomPassword(pw) if (not pw) or pw == "" then tfm.exec.chatMessage("<N>[</N><ROSE>•</ROSE><N>] Removed the password!", author) else tfm.exec.chatMessage(("<N>[</N><ROSE>•</ROSE><N>] Password: %s"):format(pw), author) end end, ["setrole"] = function(args, msg, author) if not admins[author] then return end if not (args[1] or args[2]) then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error in command<br>\tUsage:</b><font face='Lucida console'> !setrole <i> [target] [role]</i></font>\n\tAvailable roles - <font face='Lucida Console'>admin, staff, developer, artist, translator, mapper</font></R>", author) end local target = Player.players[args[1]] if not target then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error: Target unreachable!</b></R>", author) end if not roles.list:find(args[2]) then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error:</b> Could not find the role</R>", author) end roles.addRole(target, args[2]) end, ["remrole"] = function(args, msg, author) if not admins[author] then return end if not (args[1] or args[2]) then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error in command<br>\tUsage:</b><font face='Lucida console'> !remrole <i> [target] [role]</i></font>\n\tAvailable roles - <font face='Lucida Console'>admin, staff, developer, artist, translator, mapper</font></R>", author) end local target = Player.players[args[1]] if not target then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error: Target unreachable!</b></R>", author) end if not roles.list:find(args[2]) then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error:</b> Could not find the role</R>", author) end roles.removeRole(target, args[2]) end, ["maps"] = function(args, msg, author) p(maps) local player = Player.players[author] if not (admins[author] or (player:hasRole("staff") and player:hasRole("mapper"))) then return end local res = "<b><BV>Current rotation:</BV></b> " for index, map in next, rotation do if index == currentMapIndex then res = res .. "<b><VP> &lt; @" .. map .. " &gt; </VP></b>, " else res = res .. "@" .. map .. ", " end if #res > 980 then tfm.exec.chatMessage(res, author) res = "" end end if #res > 0 then tfm.exec.chatMessage(res:sub(1, -2), author) end tfm.exec.chatMessage("<b><BV>Queued maps:</BV></b> " .. (#queuedMaps > 0 and table.concat(queuedMaps, ", @") or "-"), author) end, ["npp"] = function(args, msg, author) local player = Player.players[author] if not isTribeHouse then if not (admins[author] or player:hasRole("staff")) then return tfm.exec.chatMessage(translate("ERR_PERMS", player.community), author) end else if tfm.get.room.name:sub(2) ~= tfm.get.room.playerList[author].tribeName then return tfm.exec.chatMessage(translate("ERR_PERMS", player.community), author) end end local map = args[1]:match("@?(%d+)") if not map then return tfm.exec.chatMessage(translate("ERR_CMD", player.community, nil, { syntax = "!npp [@code]"}), author) end queuedMaps[#queuedMaps+1] = map tfm.exec.chatMessage(translate("MAP_QUEUED", tfm.get.room.language, nil, { map = map, player = author }), author) end, ["addmap"] = function(args, msg, author) local player = Player.players[author] if not (admins[author] or (player:hasRole("staff") and player:hasRole("mapper"))) then return end if tfm.get.room.xmlMapInfo.permCode ~= 41 then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error:</b> Map should be P41</R>", author) end local map = tfm.get.room.xmlMapInfo.mapCode if isInRotation(map) then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error:</b> The map is already in the rotation</R>", author) end maps.list[#maps.list + 1] = map maps.dumpCache = table.concat(maps.list, ",") maps.overwriteFile = true tfm.exec.chatMessage( ("<N>[</N><R>•</R><N>] <N><ROSE><b>@%s</b></ROSE> [<ROSE><b>%s</b></ROSE>] has been added to the rotation. Please stay in the room for few minutes to save them properly.") :format(map, tfm.get.room.xmlMapInfo.author), author ) leaderboardNotifyList[#leaderboardNotifyList + 1] = author end, ["remmap"] = function(args, msg, author) local player = Player.players[author] if not (admins[author] or (player:hasRole("staff") and player:hasRole("mapper"))) then return end local map = args[1]:match("@?(%d+)") if not map then return tfm.exec.chatMessage(translate("ERR_CMD", target.community, nil, { syntax = "!remmap [@code]"}), author) end local isExisting, index = isInRotation(map) if not isExisting then return tfm.exec.chatMessage("<N>[</N><R>•</R><N>] <R><b>Error:</b> The map is not in the rotation</R>", author) end table.remove(maps.list, index) maps.dumpCache = table.concat(maps.list, ",") maps.overwriteFile = true tfm.exec.chatMessage( ("<N>[</N><R>•</R><N>] <N><ROSE><b>@%s</b></ROSE> has been removed from the rotation. Please stay in the room for few minutes to save them properly.") :format(map), author ) leaderboardNotifyList[#leaderboardNotifyList + 1] = author end } -- [[ aliases ]] cmds["p"] = cmds["profile"] shuffleMaps = function(maps) local res = {} local latest = {} for i = #maps, #maps - 20, -1 do local map = maps[i] latest[#latest + 1] = map res[#res + 1] = map end for _, map in next, maps do res[#res + 1] = map res[#res + 1] = map end table.sort(res, function(e1, e2) return math.random() <= 0.5 end) for _, map in next, latest do table.insert(res, math.random(25), map) end return res end newRound = function() newRoundStarted = false suddenDeath = false statsEnabled = (not isTribeHouse) and tfm.get.room.uniquePlayers >= MIN_PLAYERS mapProps.fromQueue = false if #queuedMaps > 0 then tfm.exec.newGame(queuedMaps[1]) table.remove(queuedMaps, 1) mapProps.fromQueue = true else currentMapIndex = next(rotation, currentMapIndex) tfm.exec.newGame(rotation[currentMapIndex]) if currentMapIndex >= #rotation then rotation = shuffleMaps(maps.list) currentMapIndex = 1 end end tfm.exec.setGameTime(93, true) Player.alive = {} Player.aliveCount = 0 for name, player in next, Player.players do player:refresh() end if not initialized then initialized = true closeSequence[1].images = { tfm.exec.addImage(assets.items[currentItem],":1", 740, 330) } Timer("changeItem", function(items) if math.random(1, 3) == 3 then currentItem = ENUM_ITEMS.CANNON else currentItem = items[math.random(1, #items)] end tfm.exec.removeImage(closeSequence[1].images[1]) closeSequence[1].images = { tfm.exec.addImage(assets.items[currentItem], ":1", 740, 330) } end, 10000, true) end end getPos = function(item, stance) if item == ENUM_ITEMS.CANNON then return { x = stance == -1 and 10 or -10, y = 18 } elseif item == ENUM_ITEMS.SPIRIT then return { x = 0, y = 10 } else return { x = stance == -1 and -10 or 10, y = 0 } end end getRot = function(item, stance) if item == ENUM_ITEMS.RUNE or item == ENUM_ITEMS.CUPID_ARROW or item == ENUM_ITEMS.STABLE_RUNE then return stance == -1 and 180 or 0 elseif item == ENUM_ITEMS.CANNON then return stance == -1 and -90 or 90 else return 0 end end extractName = function(username) username = username or "" local name, tag = username:match("^(.+)(#%d+)$") if name and tag then return name, tag else return username, "" end end setNameColor = function(name) local player = Player.players[name] if (not player) or player.highestRole == "default" then return end local color = roles.colors[player.highestRole] if not color then return end tfm.exec.setNameColor(name, color) end isInRotation = function(map) map = tostring(map):match("@?(%d+)") for i, m in next, maps.list do if m == map then return true, i end end return false end createPrettyUI = function(id, x, y, w, h, fixed, closeButton) local window = Panel(id * 100 + 10, "", x - 4, y - 4, w + 8, h + 8, 0x7f492d, 0x7f492d, 1, fixed) :addPanel( Panel(id * 100 + 20, "", x, y, w, h, 0x152d30, 0x0f1213, 1, fixed) ) :addImage(Image(assets.widgets.borders.topLeft, "&1", x - 10, y - 10)) :addImage(Image(assets.widgets.borders.topRight, "&1", x + w - 18, y - 10)) :addImage(Image(assets.widgets.borders.bottomLeft, "&1", x - 10, y + h - 18)) :addImage(Image(assets.widgets.borders.bottomRight, "&1", x + w - 18, y + h - 18)) if closeButton then window :addPanel( Panel(id * 100 + 30, "<a href='event:close'>\n\n\n\n\n\n</a>", x + w + 18, y - 10, 15, 20, nil, nil, 0, fixed) :addImage(Image(assets.widgets.closeButton, ":0", x + w + 15, y - 10) ) ) :setCloseButton(id * 100 + 30) end return window end displayProfile = function(player, target, keyPressed) local targetPlayer = Player.players[target] if targetPlayer.openedWindow then targetPlayer.openedWindow:hide(target) if targetPlayer.openedWindow == profileWindow and keyPressed then targetPlayer.openedWindow = nil return end end local lboardPos for i, p in next, leaderboard.indexed do if p.name == player.name then lboardPos = i break end end local count = 0 for i, role in next, roles.list.featureArray do if player.roles[role] then Panel.panels[220]:addImageTemp(Image(roles.images[role], "&1", 430 + count * 30, 82), target) count = count + 1 end end local name, tag = extractName(player.name) if (not name) or (not tag) then return end -- guest players profileWindow:show(target) Panel.panels[220]:update("<b><font size='20'><V>" .. name .. "</V></font><font size='10'><G>" .. tag, target) Panel.panels[151]:update(translate("ROUNDS", player.community) .. "<br><b><BV><font size='14'>" .. player.rounds .. "</font></BV>", target) Panel.panels[152]:update(translate("DEATHS", player.community) .. "<br><b><BV><font size='14'>" .. player.rounds - player.survived .. "</font></BV>", target) Panel.panels[153]:update(translate("SURVIVED", player.community) .. "<br><b><BV><font size='14'>" .. player.survived .. "</font></BV> <font size='10'>(" .. math.floor(player.survived / player.rounds * 100) .."%)</font>", target) Panel.panels[154]:update(translate("WON", player.community) .. "<br><b><BV><font size='14'>" .. player.won .. "</font></BV> <font size='10'>(" .. math.floor(player.won / player.rounds * 100) .."%)</font>", target) Panel.panels[155]:update(translate("LBOARD_POS", player.community, nil, { pos = lboardPos or "N/A" }), target) targetPlayer.openedWindow = profileWindow end displayHelp = function(target, keyPressed) local targetPlayer = Player.players[target] if targetPlayer.openedWindow then targetPlayer.openedWindow:hide(target) if targetPlayer.openedWindow == helpWindow and keyPressed then targetPlayer.openedWindow = nil return end end local commu = targetPlayer.community helpWindow:show(target) Panel.panels[820]:update(translate("COMMANDS", commu), target) Panel.panels[705]:update(translate("CMD_TITLE", commu), target) Panel.panels[920]:update(translate("CREDITS", commu, nil, { artists = "<BV>Lightymouse</BV><G>#0421</G>", translators = "<BV>Overjoy06#0000</BV><G>#0000</G>, <BV>Nuttysquirrel</BV><G>#0626</G>, <BV>Star</BV><G>#6725</G>, <BV>Jaker</BV><G>#9310</G>, <BV>Santoex</BV><G>#0000</G>, <BV>Maha010</BV><G>#0000</G>" }), target) Panel.panels[706]:update(translate("CREDS_TITLE", commu), target) Panel.panels[701]:update(translate("OBJECTIVE", commu), target) Panel.panels[704]:update(translate("HELP_GOTIT", commu), target) targetPlayer.openedWindow = helpWindow end displayChangelog = function(target) local targetPlayer = Player.players[target] if targetPlayer.openedWindow then targetPlayer.openedWindow:hide(target) if targetPlayer.openedWindow == changelogWindow then targetPlayer.openedWindow = nil return end end changelogWindow:show(target) targetPlayer.openedWindow = changelogWindow end do rotation = shuffleMaps(maps.list) currentMapIndex = 1 statsEnabled = (not isTribeHouse) and tfm.get.room.uniquePlayers >= MIN_PLAYERS leaderboard.load() Timer("newRound", newRound, 6 * 1000) Timer("leaderboard", leaderboard.load, 2 * 60 * 1000, true) tfm.exec.newGame(rotation[currentMapIndex]) tfm.exec.setGameTime(8) for cmd in next, cmds do system.disableChatCommandDisplay(cmd) end for name in next, tfm.get.room.playerList do eventNewPlayer(name) end profileWindow = createPrettyUI(1, 200, 100, 400, 200, true, true) :addPanel(createPrettyUI(2, 240, 80, 250, 35, true)) :addPanel( Panel(150, "", 220, 140, 360, 100, 0x1A3846 , 0x1A3846, 1, true) :addImage(Image(assets.iconRounds, "&1", 230, 125)) :addPanel(Panel(151, "", 290, 140, 120, 50, nil, nil, 0, true)) :addImage(Image(assets.iconDeaths, "&1", 400, 125)) :addPanel(Panel(152, "", 460, 140, 120, 50, nil, nil, 0, true)) :addImage(Image(assets.iconSurvived, "&1", 230, 185)) :addPanel(Panel(153, "", 290, 200, 120, 50, nil, nil, 0, true)) :addImage(Image(assets.iconWon, "&1", 400, 185)) :addPanel(Panel(154, "", 460, 200, 120, 50, nil, nil, 0, true)) :addImage(Image(assets.iconTrophy, "&1", 390, 255)) :addPanel(Panel(155, "", 420, 260, 210, 30, nil, nil, 0, true)) ) leaderboardWindow = createPrettyUI(3, 70, 50, 670, 330, true, true) :addPanel(Panel(350, "", 90, 100, 50, 240, 0x1A3846, 0x1A3846, 1, true)) :addPanel(Panel(351, "", 160, 100, 200, 240, 0x1A3846, 0x1A3846, 1, true)) :addPanel( Panel(352, "", 380, 100, 70, 240, 0x1A3846, 0x1A3846, 1, true) :addImage(Image(assets.iconRounds, "&1", 380, 70)) ) :addPanel( Panel(353, "", 470, 100, 70, 240, 0x1A3846, 0x1A3846, 1, true) :addImage(Image(assets.iconDeaths, "&1", 470, 70)) ) :addPanel( Panel(354, "", 560, 100, 70, 240, 0x1A3846, 0x1A3846, 1, true) :addImage(Image(assets.iconSurvived, "&1", 560, 70)) ) :addPanel( Panel(355, "", 650, 100, 70, 240, 0x1A3846, 0x1A3846, 1, true) :addImage(Image(assets.iconWon, "&1", 650, 70)) ) :addPanel( Panel(356, "", 70, 350, 670, 50, nil, nil, 0, true) :setActionListener(function(id, name, event) local page = tonumber(event) if page then leaderboardWindow:hide(name) leaderboard.displayLeaderboard("global", page, name) end end) ) :addPanel( Panel(357, "<a href='event:switch'>Room \t ▼</a>", 90, 55, 80, 20, 0x152d30, 0x7f492d, 1, true) :setActionListener(function(id, name, event) Panel.panels[id]:addPanelTemp( Panel(358, "<a href='event:room'>Room</a><br><a href='event:global'>Global</a>", 90, 85, 80, 30, 0x152d30, 0x7f492d, 1, true) :setActionListener(function(id, name, event) leaderboardWindow:hide(name) leaderboard.displayLeaderboard(event, 1, name) end), name) end) ) changelogWindow = createPrettyUI(4, 70, 50, 670, 330, true, true) :addPanel( Panel(450, CHANGELOG, 100, 50, 630, 330, nil, nil, 0, true) :setActionListener(function(id, name, event) tfm.exec.chatMessage("<BV>• <u><i>https://github.com/Seniru/pewpew/releases</i></u></BV>", name) end) ) :addImage(Image(assets.widgets.scrollbarBg, "&1", 720, 80)) :addImage(Image(assets.widgets.scrollbarFg, "&1", 720, 90)) shopWindow = createPrettyUI(5, 360, 50, 380, 330, true, true) -- main shop window :addPanel( -- preview window createPrettyUI(6, 70, 50, 260, 330, true, false) :addPanel( Panel(650, "", 80, 350, 240, 20, nil, 0x324650, 1, true) :setActionListener(function(id, name, event) local key, value = table.unpack(stringutils.split(event, ":")) local player = Player.players[name] local pack = shop.packs[value] if not pack then return end if key == "buy" then -- Exit if the player already have the pack or if they dont have the required points if player.packs[value] or player.points < pack.price then return end player.packs[value] = true player.equipped = value player.points = player.points - pack.price player.packsArray[#player.packsArray + 1] = value shop.displayShop(name) player:savePlayerData() elseif key == "equip" then -- Exit if the player don't have the pack if not player.packs[value] then return end player.equipped = value player:savePlayerData() shop.displayPackInfo(name, value) end end) ) :addPanel(Panel(651, "", 160, 60, 150, 90, nil, nil, 0, true)) :addPanel(Panel(652, "", 80, 160, 100, 100, nil, nil, 0, true)) ):addPanel( Panel(551, "〈", 620, 350, 40, 20, nil, 0x324650, 1, true) :setActionListener(function(id, name, event) shop.displayShop(name, tonumber(event)) end) ):addPanel( Panel(552, "〉", 680, 350, 40, 20, nil, 0x324650, 1, true) :setActionListener(function(id, name, event) shop.displayShop(name, tonumber(event)) end) ) helpWindow = Panel(700, ("<br><br>\t <J><b><a href='event:changelog'>%s</a></b></J> <a href='event:github'> </a> <a href='event:discord'> </a> <a href='event:map'> </a>"):format(VERSION), 0, 0, 800, 50, 0x324650, 0x324650, 0, true) :setActionListener(function(id, name, event) if event == "changelog" then displayChangelog(name) end end) :addImage(Image(assets.help.github, ":1", 120, 30)) :addImage(Image(assets.help.discord, ":1", 144, 30)) :addImage(Image(assets.help.map, ":1", 170, 30)) :addPanel( Panel(701, "", 180, 150, 200, 20, 0x324650, 0x324650, 0.6, true) :addImage(Image(assets.help.survive, ":1", 10, 10)) :addImage(Image(assets.help.killAll, ":1", 200, 10)) ) :addPanel( createPrettyUI(8, 10, 220, 230, 165, true) :addPanel(Panel(705, "", 90, 200, 300, 30, nil, nil, 0, true)) :addImage(Image(assets.help.commands, "&1", -55, 150)) ) :addPanel( createPrettyUI(9, 270, 220, 230, 165, true) :addPanel(Panel(706, "", 345, 200, 300, 30, nil, nil, 0, true)) :addImage(Image(assets.help.creditors, "&1", 260, 170)) ) :addImage(Image(assets.help.shoot, "&1", 521, 28)) :addImage(Image(assets.help.weapon, ":1", 480, 220)) :addPanel( Panel(704, "", 585, 370, 100, 30, nil, nil, 0, true) :addImage(Image("170970cdb9f.png", ":1", 550, 350)) ) :setCloseButton(704) :addPanel( Panel(710, "<a href='event:github'>\n\n\n\n</a>", 120, 25, 18, 20, nil, nil, 0, true) :setActionListener(function(id, name, event) tfm.exec.chatMessage(translate("HELP_GITHUB", Player.players[name].community), name) end) ) :addPanel( Panel(711, "<a href='event:discord'>\n\n\n\n</a>", 144, 25, 18, 20, nil, nil, 0, true) :setActionListener(function(id, name, event) tfm.exec.chatMessage(translate("HELP_DISCORD", Player.players[name].community), name) end) ) :addPanel( Panel(712, "<a href='event:map'>\n\n\n\n</a>", 170, 25, 18, 20, nil, nil, 0, true) :setActionListener(function(id, name, event) tfm.exec.chatMessage(translate("HELP_MAP", Player.players[name].community), name) end) ) newsWindow = createPrettyUI(10, 70, 50, 670, 330, true, true) :addImage(Image(VERSION_IMG, "&1", 80, 83)) :addPanel(Panel(1050, "$SHOW_CLOGS", 80, 357, 650, 18, 0x1A3846, 0x1A3846, 1, true) :setActionListener(function(id, name, event) displayChangelog(name) end) ) :addPanel(Panel(1051, "$VERSION", 80, 60, 650, 25, nil, nil, 0, trues)) end
module("luci.controller.onliner",package.seeall) nixio=require"nixio" function index() entry({"admin","status","onliner"},alias("admin","status","onliner","onliner"),_("Connection info")) entry({"admin","status","onliner","onliner"},template("onliner/onliner"),_("Online User"),1) entry({"admin", "status","onliner","speed"}, template("onliner/display"), _("Speed monitor"), 2) entry({"admin", "status","onliner","setnlbw"}, call("set_nlbw")) end function set_nlbw() if nixio.fs.access("/var/run/onsetnlbw") then nixio.fs.writefile("/var/run/onsetnlbw","1"); else io.popen("/usr/share/onliner/setnlbw.sh &") end luci.http.prepare_content("application/json") luci.http.write('') end
local function onFocusedWindow(callback) local window = hs.window.focusedWindow() if window then callback(window) else hs.alert.show('No active window') end end local function fullScreen() onFocusedWindow(function (window) local frame = window:frame() local screen = window:screen() local max = screen:frame() frame.x = max.x frame.y = max.y frame.w = max.w frame.h = max.h window:setFrame(frame) end) end local function center() onFocusedWindow(function (window) window:centerOnScreen() end) end local function leftHalf() onFocusedWindow(function (window) local frame = window:frame() local screen = window:screen() local max = screen:frame() frame.x = max.x frame.w = max.w / 2 window:setFrame(frame) end) end local function bottomHalf() onFocusedWindow(function (window) local frame = window:frame() local screen = window:screen() local max = screen:frame() frame.y = max.y + max.h / 2 frame.h = max.h / 2 window:setFrame(frame) end) end local function topHalf() onFocusedWindow(function (window) local frame = window:frame() local screen = window:screen() local max = screen:frame() frame.y = max.y frame.h = max.h / 2 window:setFrame(frame) end) end local function rightHalf() onFocusedWindow(function (window) local frame = window:frame() local screen = window:screen() local max = screen:frame() frame.x = max.x + max.w / 2 frame.w = max.w / 2 window:setFrame(frame) end) end local function leftScreen() onFocusedWindow(function (window) window:moveOneScreenWest(true, true) end) end local function lowerScreen() onFocusedWindow(function (window) window:moveOneScreenSouth(true, true) end) end local function upperScreen() onFocusedWindow(function (window) window:moveOneScreenNorth(true, true) end) end local function rightScreen() onFocusedWindow(function (window) window:moveOneScreenEast(true, true) end) end local function windows(hyper, hyperShift) hs.window.animationDuration = 0 hs.hotkey.bind(hyper, 'f', fullScreen) hs.hotkey.bind(hyper, 'c', center) hs.hotkey.bind(hyper, 'h', leftHalf) hs.hotkey.bind(hyper, 'j', bottomHalf) hs.hotkey.bind(hyper, 'k', topHalf) hs.hotkey.bind(hyper, 'l', rightHalf) hs.hotkey.bind(hyperShift, 'h', leftScreen) hs.hotkey.bind(hyperShift, 'j', lowerScreen) hs.hotkey.bind(hyperShift, 'k', upperScreen) hs.hotkey.bind(hyperShift, 'l', rightScreen) end return windows
type Storage = { } var M = Contract<Storage>() function M:init() end function M:start(gift_num: string) local gift = math.floor(1.2) local a = b.c(123) end print ("123") return M
--------------------------------------------------------------------- -- Project: irc -- Author: MCvarial -- Contact: [email protected] -- Version: 1.0.0 -- Date: 31.10.2010 --------------------------------------------------------------------- acl = {} local commands = {} ------------------------------------ -- Acl ------------------------------------ function func_addIRCCommandHandler (cmd,fn,level,echochanonly) if not acl[cmd] then acl[cmd] = {name = cmd,level = level,echoChannelOnly = echochannelonly} end commands[cmd] = fn return true end function func_ircGetCommands () local cmds = {} for cmd,fn in pairs (commands) do table.insert(cmds,cmd) end return cmds end function func_ircGetCommandLevel (cmd) if acl[cmd] then return tonumber(acl[cmd].level) or 0 end return false end function func_ircIsCommandEchoChannelOnly (cmd) if acl[cmd] then return acl[cmd].echoChannelOnly end return false end addEvent("onIRCMessage") addEventHandler("onIRCMessage",root, function (channel,message) if gettok(ircGetUserVhost(source),1,64) == 'echobot' then return end --ignore ourselves local cmd = gettok(message,1,32) local args = split(message,32) if commands[cmd] and acl[cmd] and acl[cmd].level and (tonumber(acl[cmd].level) or 0) <= (tonumber(ircGetUserLevel(source,channel)) or 0) then if ircIsCommandEchoChannelOnly(cmd) then if ircIsEchoChannel(channel) then commands[cmd](ircGetChannelServer(channel),channel,source,unpack(args)) end else commands[cmd](ircGetChannelServer(channel),channel,source,unpack(args)) end elseif ircIsEchoChannel(channel) and message:sub(1, 1) ~= '!' then say(ircGetChannelServer(channel),channel,source,'say',message) end end )
local _,L = ... local rematch = Rematch local dialog = RematchDialog local settings, saved rematch:InitModule(function() settings = RematchSettings saved = RematchSaved dialog:UpdateTabPicker() rematch:RegisterMenu("SaveAsTarget",{ { text=L["No Target"], npcID=nil, func=rematch.PickNpcID }, { text=function() return rematch:GetNameFromNpcID(rematch.recentTarget) end, hidden=function() return not rematch.recentTarget end, npcID=function() return rematch.recentTarget end, func=rematch.PickNpcID }, { text=function() return rematch:GetTeamTitle(settings.loadedTeam) end, hidden=function() return type(settings.loadedTeam)~="number" or settings.loadedTeam==rematch.recentTarget or settings.loadedTeam==1 end, npcID=function() return settings.loadedTeam end, func=rematch.PickNpcID }, { text=L["Noteworthy Targets"], subMenu="NotableNPCs" }, -- defined in Npcs.lua }) dialog.SaveAs.Target.tooltipTitle=L["Target For This Team"] dialog.SaveAs.Target.tooltipBody=L["A target stored in a team is used to decide which team to load when you return to that target.\n\nYou can save an unlimited number of teams to fight a target, but a target can only be saved in one team."] dialog.SaveAs.Name.Label:SetText(L["Name:"]) dialog.SaveAs.Target.Label:SetText(L["Target:"]) end) function rematch:ShowSaveAsDialog(header) rematch:ShowDialog("SaveAs",300,140+dialog.SaveAs:GetHeight(),header or L["Save As.."],L["Save this team?"],SAVE,rematch.SaveAsAccept,CANCEL) dialog.SaveAs:SetPoint("TOP",0,-40) dialog.SaveAs:Show() dialog.TabPicker:SetPoint("TOPRIGHT",dialog.SaveAs.Target,"BOTTOMRIGHT",0,-6) dialog.TabPicker:Show() rematch:UpdateSaveAsDialog() -- fills in stuff end function dialog.SaveAs.Target:OnClick() rematch:ToggleMenu("SaveAsTarget","TOPRIGHT",self,"BOTTOMRIGHT",0,2) end function rematch:UpdateSaveAsDialog() dialog:UpdateTabPicker() local team,key = rematch:GetSideline() dialog:FillTeam(dialog.SaveAs.Team,team) dialog.SaveAs.Name:SetFontObject(type(key)=="number" and "GameFontHighlight" or "GameFontNormal") dialog.SaveAs.Name:SetText(rematch:GetSidelineTitle()) dialog.SaveAs.Target.Text:SetText(rematch:GetNameFromNpcID(key)) dialog.SaveAs.Themselves:Hide() local height = 180 local yoff = -40 if rematch:GetSidelineContext("AskingOverwriteNotes") then -- if saving from loadout, and team has notes (determined in CheckToOverwriteNotesAndPreferences) -- which also sets this context, then attach a checkbox for "Save Notes & Preferences too" dialog.CheckButton:SetPoint("TOPLEFT",dialog.SaveAs.Target,"BOTTOMLEFT",-32,yoff) dialog.CheckButton.text:SetText(L["Save Notes & Preferences Too"]) dialog.CheckButton:Show() dialog.CheckButton:SetChecked(settings.OverwriteNotes and true) dialog.CheckButton:SetScript("OnClick",function(self) settings.OverwriteNotes=self:GetChecked() end) height = height + 28 yoff = yoff - 28 end dialog.SaveAs:SetHeight(height) rematch:SaveAsUpdateWarning() end function rematch:SaveAsUpdateWarning() local name = dialog.SaveAs.Name:GetText() local team,key = rematch:GetSideline() local warn if name and name:len()==0 then warn = L["All teams must have a name."] elseif rematch:GetSidelineContext("originalKey")~=key and saved[key] then if type(key)=="number" then warn = L["This target already has a team."] else warn = L["A team already has this name."] end end if warn then dialog.Warning:SetPoint("TOP",dialog.SaveAs,"BOTTOM",0,-4) dialog.Warning.Text:SetText(warn) dialog.Warning:Show() else dialog.Warning:Hide() end dialog:SetHeight((warn and 140 or 108)+dialog.SaveAs:GetHeight()) end -- call to change target in the SaveAs dialog function rematch:SetSaveAsTarget(npcID) local team,key = rematch:GetSideline() if npcID~=key then if npcID then rematch:ChangeSidelineKey(npcID) team,key = rematch:GetSideline() -- need to get them again since table changes if saved[npcID] then team.teamName = saved[npcID].teamName else team.teamName = rematch:GetNameFromNpcID(npcID) end else rematch:ChangeSidelineKey(rematch:GetSidelineContext("originalName")) team,key = rematch:GetSideline() -- need to get them again since table changes team.teamName = nil end end rematch:UpdateSaveAsDialog() end function dialog.SaveAs.Name:OnTextChanged() local text = self:GetText() if text:len()==0 then dialog.Accept:Disable() else dialog.Accept:Enable() if text~=rematch:GetSidelineTitle() then local team,key = rematch:GetSideline() if type(key)=="number" then team.teamName = text -- if an npcID-indexed team, it can be any name else rematch:ChangeSidelineKey(text) end end end rematch:SaveAsUpdateWarning() end -- when the Save button is clicked in the SaveAs dialog function rematch:SaveAsAccept() local team,key = rematch:GetSideline() if not saved[key] or not rematch:SidelinePetsDifferentThan(key) then rematch:PushSideline() rematch:ShowTeam(key) else rematch:ShowOverwriteDialog() end end -- returns true if the sidelined team's pets are different than the team of the passed key function rematch:SidelinePetsDifferentThan(key) local team1 = rematch:GetSideline() local team2 = saved[key] if team1 and team2 then for i=1,3 do if team1[i][1]~=team2[i][1] then return true -- a pet is different end end if team1.notes~=team2.notes or team1.minHP~=team2.minHP or team1.maxXP~=team2.maxXP or team1.minXP~=team2.minXP or team1.maxHP~=team2.maxHP then return true -- notes or preferences are different end return false -- the three pets are the same end return true -- one or both teams doesn't exist end -- shows an overwrite dialog to confirm whether to save a team -- make noDialog true when declining shouldn't return to the SaveAs dialog function rematch:ShowOverwriteDialog(noDialog,prompt) rematch:ShowDialog("Overwrite",300,350,L["Overwrite Team"],prompt or L["Overwrite this team?"],YES,rematch.OverwriteAccept,NO,not noDialog and rematch.ShowSaveAsDialog or nil) local team,key = rematch:GetSideline() dialog.Text:SetSize(260,72) if noDialog then -- no need to explain why overwrite happening, just show team name dialog.Text:SetSize(260,32) dialog.Text:SetJustifyH("CENTER") dialog.Text:SetText(rematch:GetTeamTitle(key,true)) dialog:SetHeight(310) else if type(key)=="number" then dialog.Text:SetText(format(L["The target %s%s\124r already has a team.\n\nA target can only have one team."],rematch.hexWhite,rematch:GetNameFromNpcID(key))) else dialog.Text:SetText(format(L["A team named %s%s\124r already exists.\n\nTeams without a target must have a unique name."],rematch.hexWhite,key)) end end dialog.Text:SetPoint("TOP",0,-32) dialog.Text:Show() dialog.OldTeam:SetPoint("TOP",dialog.Text,"BOTTOM") dialog.OldTeam:Show() dialog:FillTeam(dialog.OldTeam,saved[key]) dialog.Team:SetPoint("TOP",dialog.OldTeam,"BOTTOM",0,-32) dialog.Team:Show() dialog:FillTeam(dialog.Team,team) end -- when accept clicked on overwrite dialog function rematch:OverwriteAccept() local _,key = rematch:GetSideline() rematch:PushSideline() rematch:ShowTeam(key) end -- to be called after a loaded team is sidelined (Save As... or target's Save button) -- will turn on AskingOverwriteNotes to know whether notes can potentially overwrite function rematch:CheckToOverwriteNotesAndPreferences() local team = settings.loadedTeam and saved[settings.loadedTeam] if team and (team.notes or rematch:HasPreferences(team)) then rematch:SetSidelineContext("AskingOverwriteNotes",true) end end
local PLUGIN = PLUGIN PLUGIN.name = "Anomaly Controller" PLUGIN.author = "gumlefar" PLUGIN.desc = "Allows for randomly spawning anomaly entities" PLUGIN.anomalydefs = PLUGIN.anomalydefs or {} PLUGIN.anomalypoints = PLUGIN.anomalypoints or {} -- ANOMALYPOINTS STRUCTURE table.insert( PLUGIN.eventpoints, { position, radius, anoms } ) PLUGIN.spawnrate = 900 PLUGIN.spawnchance = 1 ix.util.Include("sh_anomalydefs.lua") if SERVER then local spawntime = 1 function PLUGIN:Think() if spawntime > CurTime() then return end spawntime = CurTime() + self.spawnrate - #player.GetAll()*5 for i, j in pairs(self.anomalypoints) do if (!j) then return end if math.random(1001) > self.spawnchance then return end local data = {} data.start = j[1] data.endpos = data.start + Vector(0, 0, -64) data.filter = client data.mins = Vector(-32, -32, 0) data.maxs = Vector(32, 32, 32) local trace = util.TraceHull(data) if trace.Entity:IsValid() then if !(trace.Entity:GetClass() == "ix_storage") then continue end end local rand = math.random(101) local rarityselector = 0 local anomalyselector = 0 if rand <= 70 then rarityselector = 0 elseif rand <= 90 then rarityselector = 1 elseif rand <= 100 then rarityselector = 2 else return end for k,v in pairs(ents.FindInSphere(j[1], 400)) do if (string.sub(v:GetClass(), 1, 5) == "anom_") then for i=1,5 do if self.anomalydefs[i].entityname == v:GetClass() then anomalyselector = i break end end end end if anomalyselector == 0 then return end local idat = 0 if rarityselector == 0 then idat = table.Random(self.anomalydefs[anomalyselector].commonArtifacts) elseif rarityselector == 1 then idat = table.Random(self.anomalydefs[anomalyselector].rareArtifacts) else idat = table.Random(self.anomalydefs[anomalyselector].veryRareArtifacts) end ix.item.Spawn(idat, j[1] + Vector( math.Rand(-8,8), math.Rand(-8,8), 20 ), nil, AngleRand(), {}) end end -- Function that cleans up all anomalies (Entities with names starting with "anom_") function PLUGIN:cleanAnomalies() for k, v in pairs( ents.GetAll() ) do if (string.sub(v:GetClass(), 1, 5) == "anom_") then v:Remove() end end end -- Function that will spawn anomalies -- It will populate all spawnpoints with valid anomalies function PLUGIN:spawnAnomalies() if CurTime() > 5 then spawntime = 1 end for k, v in pairs(self.anomalypoints) do local selectedAnoms = {} for i=1, #self.anomalydefs do if string.sub(v[3],i,i) == "1" then table.insert( selectedAnoms, self.anomalydefs[i]) end end local entity = table.Random(selectedAnoms) for i = 1, math.ceil(v[2]/entity.interval) do local position = self:GetSpawnLocation( v[1], v[2] ) local data = {} data.start = position data.endpos = position data.mins = Vector(-16, -16, 0) data.maxs = Vector(16, 16, 71) local trace = util.TraceHull(data) if trace.Entity:IsValid() then continue end local spawnedent = ents.Create(entity.entityname) spawnedent:SetPos(position) spawnedent:Spawn() spawnedent:DropToFloor() end end end function PLUGIN:LoadData() self.anomalypoints = self:GetData() or {} self:cleanAnomalies() self:spawnAnomalies() end function PLUGIN:SaveData() self:SetData(self.anomalypoints) end function PLUGIN:GetSpawnLocation( pos , radius ) local tracegood = false local teleres local tracecnt = 0 local firstTrace = util.TraceLine( { start = pos + Vector(0,0,64), endpos = pos + Vector(0,0,512), mask = MASK_ALL, ignoreworld = false } ) repeat local trace = util.TraceHull( { start = firstTrace.HitPos - Vector(0,0,64), endpos = pos + Vector(math.random(-radius,radius),math.random(-radius,radius),-400), mins = Vector( -32, -32, 0 ), maxs = Vector( 32, 32, 64 ), mask = MASK_ALL, ignoreworld = false } ) if not trace.HitSky then tracegood = true teleres = trace.HitPos + ( trace.HitNormal * 32 ) end tracecnt = tracecnt + 1 if tracecnt > 50 then tracegood = true teleres = pos + Vector(0,0,64) -- Teleport to original position if we cant find a position end until tracegood return teleres end else -- Simple hook to display points netstream.Hook("ix_DisplaySpawnPoints", function(data) for k, v in pairs(data) do local emitter = ParticleEmitter( v[1] ) local smoke = emitter:Add( "sprites/glow04_noz", v[1] ) smoke:SetVelocity( Vector( 0, 0, 1 ) ) smoke:SetDieTime(10) smoke:SetStartAlpha(255) smoke:SetEndAlpha(255) smoke:SetStartSize(64) smoke:SetEndSize(64) smoke:SetColor(255,186,50) smoke:SetAirResistance(300) end end) end -- Adds a point to to the list of anomaly spawnpoints -- Example : /anomalyadd 256 111 -- Will add a point at the users crosshair with a radius of 256 -- (meaning it will spawn anomalies in a 256 unit radius around the point) -- allowing the first three anomaly definitions to spawn there ix.command.Add("anomalyadd", { superAdminOnly = true, arguments = { ix.type.number, ix.type.string }, OnRun = function(self, client, radius, anomalies) local trace = client:GetEyeTraceNoCursor() local hitpos = trace.HitPos + trace.HitNormal*5 local radius = radius or 128 local anomalies = anomalies or 1111111111111111111 if (!radius or !isnumber(radius) or radius < 0) then return "@invalidArg", 2 end table.insert( PLUGIN.anomalypoints, { hitpos, radius, anomalies } ) client:Notify( "Anomaly point successfully added" ) end }) -- Removes anomaly spawnpoints in a radius around the users crosshair -- Example : /anomalyremove -- Will remove anomaly spawnpoints in a 128 range around the users crosshair -- Example : /anomalyremove 256 -- Will remove anomaly spawnpoints in a 256 range around the users crosshair ix.command.Add("anomalyremove", { superAdminOnly = true, arguments = { ix.type.number }, OnRun = function(self, client, range) local trace = client:GetEyeTraceNoCursor() local hitpos = trace.HitPos + trace.HitNormal*5 local range = range or 128 local mt = 0 for k, v in pairs( PLUGIN.anomalypoints ) do local distance = v[1]:Distance( hitpos ) if distance <= tonumber(range) then PLUGIN.anomalypoints[k] = nil mt = mt + 1 end end if mt > 0 then client:Notify( mt .. " anomaly locations has been removed.") else client:Notify( "No anomaly spawn points found at location.") end end }) -- Will display glow sprites at all the anomaly spawn points on the map ix.command.Add("anomalydisplay", { adminOnly = true, OnRun = function(self, client, arguments) if SERVER then netstream.Start(client, "ix_DisplaySpawnPoints", PLUGIN.anomalypoints) client:Notify( "Displayed All Points for 10 secs." ) end end }) -- Debug command for removing anomaly entities in a radius -- Example : /anomalyentremove 512 -- Will remove all entities that have names starting with "anom_" in a 512 radius around the users crosshair ix.command.Add("anomalyentremove", { adminOnly = true, arguments = { ix.type.number }, OnRun = function(self, client, range) local trace = client:GetEyeTraceNoCursor() local hitpos = trace.HitPos + trace.HitNormal*5 local range = range or 128 local mt = 0 for k, v in pairs( ents.FindInSphere(hitpos, range) ) do if (string.sub(v:GetClass(), 1, 5) == "anom_") then v:Remove() mt = mt + 1 end end if mt > 0 then client:Notify( "Removed " .. mt .. " anomalies.") else client:Notify( "No anomalies found at location.") end end }) ix.command.Add("cleananomalies", { adminOnly = true, OnRun = function(self, client, arguments) ix.plugin.list["anomalycontroller"]:cleanAnomalies() client:Notify("All anomalies have been cleaned up from the map.") end }) ix.command.Add("spawnanomalies", { adminOnly = true, OnRun = function(self, client, arguments) ix.plugin.list["anomalycontroller"]:spawnAnomalies() client:Notify("Spawned anomalies on points (if any).") end })
function onCreate() -- background shit makeLuaSprite('nightsky', 'miku concert night/nightsky', -360, -110); scaleObject('nightsky', 1.1, 1.1); makeLuaSprite('stageback', 'miku concert night/concerttop', -380, -110); setLuaSpriteScrollFactor('stageback', 0.9, 0.9); scaleObject('stageback', 1.1, 1.1); makeLuaSprite('front', 'miku concert night/front', -470, -80); scaleObject('front', 1.2, 1.1); -- sprites that only load if Low Quality is turned off if not lowQuality then makeLuaSprite('back', 'miku concert night/mainstage', -380, -110); setLuaSpriteScrollFactor('back', 0.9, 0.9); scaleObject('back', 1.1, 1.1); makeLuaSprite('speakers', 'miku concert night/speakers', -380, -110); setLuaSpriteScrollFactor('speakers', 0.9, 0.9); scaleObject('speakers', 1.1, 1.1); makeAnimatedLuaSprite('bunch_of_simps', 'miku concert night/crowd', -450, 660); setLuaSpriteScrollFactor('bunch_of_simps', 0.9, 0.9); scaleObject('bunch_of_simps', 1.7, 1.7); makeLuaSprite('stadiumback', 'miku concert night/stadiumback', -380, -110); setLuaSpriteScrollFactor('stadiumback', 0.9, 0.9); makeLuaSprite('backlight', 'miku concert night/backlight', -380, -110); setLuaSpriteScrollFactor('backlight', 0.9, 0.9); makeLuaSprite('hell', 'miku concert night/hell', -380, -110); setLuaSpriteScrollFactor('hell', 0.9, 0.9); scaleObject('hell', 1.7, 1.7); end addLuaSprite('nightsky', false); addLuaSprite('backlight', false); addLuaSprite('hell', true); addLuaSprite('stadiumback', false); addLuaSprite('stageback', false); addLuaSprite('speakers', false); addLuaSprite('back', false); addLuaSprite('front', false); addLuaSprite('bunch_of_simps', true); addAnimationByPrefix('bunch_of_simps', 'idle', 'crowdbump', 24, true); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
print(type("Hello world")) --> string print(type(10.4*3)) --> number print(type(print)) --> function print(type(type)) --> function print(type(true)) --> boolean print(type(nil)) --> nil print(type(type(X))) --> string
-- collision-pi-visualizer -- (c) Vilhelm Prytz <[email protected]> 2019 -- digits of pi d = 2 collisions = 0 -- left square left_square = {} left_square.x = 200 left_square.mass = 1 left_square.velocity = 0 -- right square right_square = {} right_square.x = 500 right_square.mass = math.pow(100, d-1) right_square.velocity = -2 -- other block_y = love.graphics.getHeight()/2 square_size = 50 function collision() collisions = collisions+1 v1 = right_square.velocity v2 = left_square.velocity m1 = right_square.mass m2 = left_square.mass -- conservation of momentum & completely elastic collision right_square.velocity = (v1 * (m1 - m2) + 2 * m2 * v2)/(m1 + m2) left_square.velocity = (v2 * (m2 - m1) + 2 * m1 * v1)/(m2 + m1) end function wall_collision() collisions = collisions+1 left_square.velocity = -(left_square.velocity) end function love.draw() love.graphics.setBackgroundColor(0, 0, 0) -- draw squares love.graphics.setColor(255, 0, 0) -- red love.graphics.rectangle("fill", left_square.x, block_y, square_size, square_size) love.graphics.setColor(0, 0, 255) -- blue love.graphics.rectangle("fill", right_square.x, block_y, square_size, square_size) -- display amount of collisions love.graphics.setColor(255, 255, 255) -- white love.graphics.print("Collisions: " .. tostring(collisions), 10, 10, 0, 1, 1) -- fps love.graphics.print("FPS: "..tostring(love.timer.getFPS()), 10, 25, 0, 1, 1) end function love.update(dt) left_square.x = left_square.x + (left_square.velocity) right_square.x = right_square.x + (right_square.velocity) -- check collision if (right_square.x-square_size/2 <= left_square.x+square_size/2) then collision() end if (left_square.x < 0) then wall_collision() end end
--[[ Copyright (C) 2013-2018 Draios Inc dba Sysdig. This file is part of sysdig. 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. --]] view_infoz = { id = "cores", name = "CPUs", description = "This is the typical top/htop process list, showing usage of resources like CPU, memory, disk and network on a by process basis.", tags = {"Default"}, view_type = "table", applies_to = {"", "container.id", "proc.pid", "thread.nametid", "k8s.pod.id", "k8s.rc.id", "k8s.rs.id", "k8s.svc.id", "k8s.ns.id", "marathon.app.id", "marathon.group.name", "mesos.task.id", "mesos.framework.name"}, is_root = true, use_defaults = true, drilldown_target = "procs", columns = { { name = "NA", field = "proc.pid", is_key = true }, { name = "NA", field = "evt.cpu", is_groupby_key = true }, { name = "CORE", description = "CPU or Core ID.", field = "evt.cpu", colsize = 8, }, { name = "CPU", field = "proc.cpu", description = "CPU usage.", colsize = 8, aggregation = "AVG", groupby_aggregation = "SUM", is_sorting = true }, { name = "TH", field = "proc.nthreads", description = "Number of threads that the process contains.", aggregation = "MAX", groupby_aggregation = "SUM", colsize = 5 } } }
local K, _, L = unpack(KkthnxUI) if (not L) then return end local _G = _G local GetLocale = _G.GetLocale if GetLocale() ~= "frFR" then return end -- Module Locales L["%s players"] = "%s joueurs" L["Account Keystones"] = "Account Keystone" L["AddContactTip"] = "|nModifier la liste de contacts dont vous avez besoin, le format de saisie est 'NomUnité-NomRoyaume'.|nVous devez saisir uniquement le nom seulement si l'unité se trouve dans le même royaume que vous.|nVous pouvez personnaliser la couleur du texte pour les classer." L["AddToIgnoreList"] = "%s SpellID %s a été ajouté a la liste des ignorés de AuraWatch. Vous pouvez maintenir CTRL+ALT enfoncées et cliquer sur l'icône de UnitAura pour le supprimer des ignorés." L["All Buffs Ready"] = "[KkthnxUI] Tous les buffs sont prêts!" L["Alt Key"] = "Alt Key" L["AttackSpeed"] = "VA" L["AuraWatch List"] = "Liste personnalisée" L["AuraWatch Switcher"] = "Bloquer les auras prédéfinies" L["AuraWatchGUI Tips"] = "|nObtenez plus d'infos en passant la souris sur chaque en-tête d'option.|n|nVous devez recharger l'IU après avoir modifié les paramètres.|n|nVous pouvez maintenir CTRL+ALT enfoncées, et cliquez sur l'icône AuraWatch pour ajouter le sort dans la liste des ignorés, ou cliquez sur l'icône UnitAura pour supprimer le sort des ignorés." L["AuraWatchGUI Title"] = "KkthnxUI AuraWatch GUI" L["Auto Quest Disabled Desc"] = "Activer l'acceptation/rendu auto des quêtes. |n|nMaintenez SHIFT désactivera temporairement l'acceptation/rendu automatique" L["Auto Quest Disabled"] = "Status: |CFFFF0000Disabled|r" L["Auto Quest Enabled Desc"] = "Désactiver l'acceptation/rendu auto des quêtes. |n|nMaintenez SHIFT désactivera temporairement l'acceptation/rendu automatique" L["Auto Quest Enabled"] = "Status: |CFF008000Enabled|r" L["Auto Quest"] = "Quête auto" L["AutoDepositTip"] = "Cliquez sur le bouton gauche pour déposer vos composants, cliquez sur le bouton droit pour faire un dépôt automatique. Si la bordure du bouton s'affiche, les composants de vos sacs seront déposés automatiquement dès que vous ouvrirez votre Banque." L["BFA Invasion"] = "Assauts des factions" L["BN"] = "BN" L["Bars"] = "Barres" L["BoE"] = "LqE" L["BoP"] = "LqR" L["BrokenSpell"] = "%s Broke %s's %s!" L["CD"] = "CD" L["CPU Usage"] = "Utilisation CPU" L["Caster Intro"] = "|nFiltrez le caster.|n|njoueur: caster est le joueur.|n|ncible: caster est la cible.|n|nfamilier: caster est le familier.|n|nToutes les auras sont surveillées si vides" L["Caster"] = "Caster" L["Changelog"] = "Changelog" L["Changes Reload"] = "Un ou plusieurs des changements que vous avez effectués nécessitent un rechargement de l'interface." L["Check Flask Food"] = "Vérifiez vos flacons et votre nourriture" L["CheckQuestComplete"] = " a été achevée!" L["CheckQuestInfo"] = "\nEntrer l'ID de quête de Wowhead\nhttp://wowhead.com/quest=ID\nExemple: /checkquest 12045\n" L["CheckQuestNotComplete"] = " n'a pas été achevée!" L["Choose a Type"] = "Vous devez sélectionner un type." L["Clear Binds"] = "|CFFFFCC66All raccourci effacé pour|r %s" L["Collect Memory"] = "Récolter la mémoire" L["Combat Intro"] = "|nSi coché, le sort ne s'affiche qu'en combat." L["Combat"] = "Combat" L["CombatLog"] = "Log" L["Combo"] = "Com" L["ContactList"] = "Liste des contacts" L["Copy Name"] = "Copier le nom" L["Crit"] = "Crit" L["Ctrl Key"] = "(Ctrl) " L["Current Invasion"] = "En cours: " L["Deficit"] = "Déficit" L["Delete Mode Enabled"] = "|nVous pouvez détruire l'objet du sac en appuyant sur CTRL+ALT. |n|nLa qualité de l'objet doit être inférieure à |cff0070ddRare|r" L["Disable to hide areas."] = "Désactiver pour cacher les zones|nque vous n'avez pas encore découvertes." L["Discard KeyBinds"] = "Raccourcis effacés." L["Discord URL"] = "https://discord.gg/Rc9wcK9cAB" L["Discord"] = "|cff7289daDiscord|r" L["Dispel"] = "Dispeled %s's %s!" L["Download"] = "Télécharger" L["Duration Intro"] = "|nLe chronomètre est déclenché." L["Duration*"] = "Durée*" L["Earned"] = "Gagnés" L["Empty Slot"] = "Emplacement vide" L["Enable to show hidden areas."] = "Permettre de montrer les zones cachées|nque vous n'avez pas encore découvertes." L["Enchant Aura"] = "Enchantement" L["Equipement Set"] = "Sets d'armure" L["ExRT Potion Check"] = "ExRT Vérification des potions" L["Exalted"] = "Exalté" L["Existing ID"] = "Le SpellID existe." L["Experience"] = "Expérience" L["FPS"] = "IPS" L["Favourite Mode Enabled"] = "|nVous pouvez maintenant mettre des objets en favoris|n|nSi l'option 'Filtre des sacs' est activée, l'objet que vous avez sélectionné sera ajouté aux emplacements du filtre des 'Préférences'.|n|nCe n'est pas disponible pour |cff9d9d9dCamelote|r" L["Favourite Mode"] = "Mode favoris" L["Fishy Loot"] = "Butin de pêche" L["Flash Intro"] = "|nSi la case est cochée, une lueur de surbrillance s'affichera sur l'icône lorsqu'elle est activée." L["Flash"] = "Surbrillance" L["Flask"] = "Fiole" L["Focus Aura"] = "FocusAura" L["Food"] = "Nourriture" L["From"] = "De" L["General"] = "Général" L["Get Close"] = "Rapprochez-vous" L["Get Out"] = "Sortez!" L["Ghost"] = "Fantôme" L["Groups"] = "Groupes" L["Hidden"] = "Caché" L["Hide Undiscovered Areas"] = "Cacher les zones non découvertes" L["Hold Shift"] = "Maintenez Shift" L["Home Latency"] = "Latence domicile" L["Home Protocol"] = "Protocole domicile" L["Honor Remaining"] = "Honneur restant:" L["Honor XP"] = "XP Honneur:" L["ID Intro"] = "|nSpell ID, doit être un nombre.|n|nVous pouvez obtenir l'ID sur l'info-bulle' du sort.|n|nSpellName n'est pas supporté." L["Incomplete Input"] = "Vous devez remplir tous les * optinos" L["Incorrect SpellID"] = "SpellID incorrecte." L["Install"] = "Installer" L["IntID Intro"] = "|nLe spellID qui déclenche le chronomètre, doit être un nombre.|n|nVous pouvez obtenir l'ID sur l'info-bulle' du sort.|n|nSpellName n'est pas supporté." L["IntID*"] = "Sorts*" L["InternalCD"] = "CustomCD" L["Interrupt"] = "Interrupted %s's %s!" L["Interrupted Message"] = "Interrompu %s's \124cff71d5ff\124Hspell:%d:0\124h[%s]\124h\124r!" L["Invalid Target"] = "Cible incorrecte" L["Invite"] = "Inviter" L["Item Delete Mode"] = "Mode suppression d'objet" L["Item Placed"] = "%s a déposé %s" L["ItemID Intro"] = "|nThe item name of the timer that triggered.|n|nThe spellName would take place if blank." L["ItemID"] = "Nom" L["Join or Invite"] = "Rejoindre ou inviter" L["KKUI_ActionBarX"] = "CustomBar" L["Key Binding"] = "Raccourcis" L["Key Bound To"] = "associée a" L["Key Index"] = "Index" L["Keybind Mode"] = "Passez votre souris sur n'importe quel bouton d'action, pour le lier. Appuyez sur la touche Echap ou clic droit pour effacer le lien du bouton d'action actuel." L["Lack"] = "Manque de" L["Latency"] = "Latence" L["Leeeeeroy!"] = "Leeeeeroy!" L["Left Click"] = "Clic gauche" L["Legion Invasion"] = "Assauts des factions" L["Local Time"] = "Heure locale" L["Loot"] = "Loot" L["MS"] = "MS" L["Mail Is COD"] = "You can't auto collect Cash on Delivery" L["Main Actionbar"] = "Barre d'action principale" L["Memory Collected"] = "Mémoire collectée" L["Missing DBM BigWigs"] = "Vous ne pouvez faire ca sans DBM ou BigWigs." L["MoveUI"] = "DéplacerIU" L["Next Invasion"] = "Suivante: " L["No Guild"] = "Aucune guilde" L["No Key Set"] = "Aucune clef" L["Paragon"] = "Paragon " L["Player Aura"] = "PlayerAura" L["Power"] = "PW" L["Press To Copy"] = "|nAppuyez sur <CTRL/C> pour copier." L["Profile"] = "Profil " L["ProfileDel"] = " Effacé: " L["ProfileInfo"] = "\n/liste des profils\n/profil #\n/profil effacé #\n\n" L["ProfileNotFound"] = "Profil introuvable" L["ProfileSelection"] = "Merci de taper le numéro du profil pour l'utiliser (exemple: /profile 5)" L["Profiles"] = "Profils" L["Profit"] = "Profit" L["Pull ABORTED!"] = "Pull REPORTÉ!" L["Pulling In"] = "Pull de %s dans %s.." L["Quick Split"] = "Quick Split" L["Raid Buff Checker"] = "[KkthnxUI] Vérificateur des Buffs de Raid:" L["Raid Buff"] = "RaidBuff" L["Raid Debuff"] = "RaidDebuff" L["Raid Disbanding"] = "[KkthnxUI] Dissolution du Raid" L["Rare Spotted"] = "Rare repéré " L["RareScanner Skin"] = "RareScanner Skin" L["Realm Time"] = "Heure du royaume" L["RealmCharacter"] = "Personnages du royaume:" L["Remaining"] = "Restant:" L["RemoveFromIgnoreList"] = "%s SpellID %s a été retiré de la liste des ignorés de AuraWatch. Vous pouvez maintenir CTRL+ALT enfoncées et cliquer sur l'icône de UnitAura pour l'ajouter de nouveau aux ignorés." L["Repaired Failed"] = "Vous n'avez pas assez d'argent pour réparer,|r " L["Repaired Items Guild"] = "Vos objets ont été réparés en utilisant les fonds de la banque de guilde pour : " L["Repaired Items"] = "Vos objets ont été réparés pour :|r " L["Replay"] = "Replay" L["Reset Data"] = "Reset Data" L["Reset Details"] = "Réinitialiser Details" L["Reset KkthnxUI"] = "Êtes-vous sûr de vouloir réinitialiser tous les paramètres de ce profil ?" L["Reset your AuraWatch List?"] = "Êtes-vous sûr d'effacer tous vos groupes de la liste personnalisée ?" L["Restart Graphics"] = "Une ou plusieurs des modifications que vous avez apportées nécessitent un redémarrage du moteur graphique." L["Rested"] = "Reposé:" L["Reveal Hidden Areas"] = "Révélez les zones cachées" L["Reveal"] = "Révélez" L["Right Click"] = "Clic Droit" L["Sapped"] = "Sapped" L["SappedBy"] = "Sapped by: " L["Save KeyBinds"] = "Raccourci(s) sauvgardé(s)." L["Saved Raid(s)"] = "Raid(s) saugardé(s)" L["Section"] = "Section" L["Session"] = "Session:" L["Show Hide Details"] = "Montrer/Masquer Details" L["Show Hide Skada"] = "Montre/Masquer Skada" L["Skipped The Cutscene"] = "Passez la cinématique." L["Slot Intro"] = "|nAfficher le cooldown des objets.|n|ne.g. Enchantement d'ingénierie sur la taille ou la cape.|n|nNe supporte que les bijoux activés." L["Slot*"] = "Emplacement*" L["Special Aura"] = "SpecialAura" L["Spell Cooldown"] = "Cooldown" L["Spent"] = "Dépensés" L["Split Count"] = "Split Count" L["Stack Buying Check"] = "Êtes-vous sûr de vouloir acheter |cffff0000une pile|r de ça?" L["Stack Cap"] = "Stack Caps" L["Stack Intro"] = "|nCumul de sort, doit être un nombre.|n|nLe sort ne s'affiche qu'une fois qu'il a atteint le cumul que vous avez défini.|n|nLe cumul sera ignoré si il est vide." L["Stack"] = "Pile" L["StackSplitEnable"] = "|nCliquez pour séparer les objets empilés dans vos sacs, vous pouvez changer 'split count' pour chaque clic dans la boîte d'édition." L["Start Stop Countdown"] = "Démarrer/Arrêter le décompte" L["Steal"] = "Stole %s's %s!" L["Stranger"] = "Etranger" L["Strike"] = "SS" L["Summon From"] = "L'invocation de" L["Summon Warning"] = "sera automatiquement acceptée dans 10 secondes, sauf annulation." L["SwitchMode"] = "Switch Mode" L["System"] = "System" L["Take All"] = "Take all" L["Target Aura"] = "TargetAura" L["Targeted By"] = "Ciblé par:" L["Text Intro"] = "|nAfficher le texte sur le sort|n|nLorsque le sort est activé, il affiche le texte que vous avez défini.|n|nLe texte sera masqué lorsque VALUE est activée ou laissée vide." L["Text"] = "Texte" L["The health for %s is low!"] = "La vie de %s est faible !" L["This Cutscene Can Not Be Skipped"] = "Cette cinématique ne peut être passée." L["Timeless Intro"] = "|nSi activé, le timer du sort devrait être caché." L["Timeless"] = "Timeless" L["Tips"] = "Astuces" L["To"] = "To" L["Toggle KkthnxUI Config"] = "Afficher la config de KkthnxUI" L["Toggle Quick Menu"] = "Afficher le menu rapide" L["Totem Intro"] = "|nAfficher la durée du totem dans son emplacement." L["Totem*"] = "Totem*" L["TotemSlot"] = "TotemSlot" L["Trade"] = "Echanger" L["Trait"] = "Trait" L["Trigger"] = "Déclencheur" L["Tutorial Page1"] = "Bienvenue au tutoriel d'installation !|n|nCliquez sur le bouton 'Appliquer' (en bas à droite) pour appliquer certains paramètres par défaut. Cela comprend (entre autres) les noms, les barres d'action, les Unitframes et autres.|n|n|cffff0000CQui sont tous recommandés.|r" L["Tutorial Page2"] = "Vous êtes passé à l'étape suivante !|n|nNous allons ici charger quelques paramètres utiles pour le Chat ! Ces paramètres sont importants et conçus pour KkthnxUI|n|n|cffff0000ATTENTION:|r|n|n|cff00ccffVous pouvez défiler vers le haut ou le bas du chat en maintenant la touche MAJ enfoncée sur la fenêtre de chat.|r" L["Tutorial Page3"] = "Toujours là ? Bien !|n|nIl s'agit de la section permettant d'appliquer l'échelle d'interface recommandée en fonction de votre résolution actuelle.|n|nVous pouvez changer cette échelle dans |cffffcc00 les options de configuration de KkthnxUI (Onglet Général)|r plus tard." L["Tutorial Page4"] = "Enfin, les paramètres de profil de Skada/DBM/BigWigs et quelques autres addOns seront importés si ces addOns sont chargés/activés actuellement.|n|nVous pouvez désactiver les skins dans |cffffcc00les options de configuration de KkthnxUI (Onglet Skins)|r." L["Tutorial Page5"] = "Eh bien, vous avez réussi à aller jusqu'au bout ! Vous avez terminé le tutoriel.|n|n|cffff0000ATTENTION:|r|n|nVous pouvez facilement définir la focalisation en maintenant les touches SHIFT et clic gauche sur l'unité désirée ;|n|nLa plupart des paramètres peuvent être modifiés dans |cffffcc00les options de configuration de KkthnxUI|r.|r Bonne chance et amusez-vous bien "..K.Name L["Type Intro"] = "|nAuraID: surveiller le statut des Buff/Debuff.|n|nSpellID: surveiller le cooldown des sorts.|n|nSlotID: surveiller le cooldown des objets.|n|nTotemID: surveiller la durée du totem activé." L["Type*"] = "Type*" L["Unit Intro"] = "|nLes informations sur les de l'unité.|n|njoueur: unité est le joueur.|n|ncible: unité est la cible.|n|nfocalisation: unité est la cible focalisée.|n|nfamilier: unité est le familier." L["Unit*"] = "Unité*" L["Value Intro"] = "|nSi activé, la valeur du sort doit être visible.|n|ne.g. Le bouclier du prêtre indiquera sa quantité d'absorption restante.|n|nIl a une priorité plus élevée que le TEXTE." L["Value"] = "Valeur" L["Vendored Items"] = "Camelote vendues pour: |r " L["Warning"] = "Attention" L["Whisper"] = "Dire à" L["WoW"] = "WoW" L["World Latency"] = "Latence du monde" L["World Protocol"] = "Protocole du monde" L["XP"] = "XP:" -- HelpTip Locales L["ChatHelpTip"] = "Faites défiler plusieurs lignes en maintenant la touche Ctrl enfoncée, et faites défiler vers le haut ou le bas en maintenant la touche Shift enfoncée." L["MinimapHelpTip"] = "Faites défiler la minimap pour faire un zoom avant ou arrière, cliquez au milieu pour basculer le micro-menu, cliquez à droite pour basculer le menu des pistes." -- GUI Group Title Locales L["ActionBar"] = "Barres d'action" L["Announcements"] = "Annonces" L["Arena"] = "Arène" L["AuraWatch"] = "AuraWatch" L["Auras"] = "Auras" L["Automation"] = "Automatisation" L["Boss"] = "Boss" L["Chat"] = "Chat" L["DataBars"] = "Barre d'info." L["DataText"] = "Textes d'info." L["Inventory"] = "Inventaire" L["Minimap"] = "Minimap" L["Misc"] = "Autres" L["Nameplate"] = "Noms" L["Party"] = "Groupe" L["QuestNotifier"] = "NotificationQuête" L["Raid"] = "Raid" L["Skins"] = "Habillages" L["Tooltip"] = "Info-bulle" L["UIFonts"] = "Polices" L["UITextures"] = "Textures" L["Unitframe"] = "Cadre d'unité" L["WorldMap"] = "Carte du monde" -- GUI Sub Options L["Fading"] = "Fading" L["Layouts"] = "Layouts" L["Scaling"] = "Scaling" L["Sizes"] = "Sizes" L["Toggles"] = "Toggles" L["Rare Alert"] = "Rare Alert" -- GUI Group Options Description Locals L["Choose Your Layout"] = "Choisissez votre disposition" L["Enable ActionBar"] = "Activer les barres d'action" L["Enable Count"] = "Activer le décompte" L["Enable CustomBar"] = "Activer la barre personnalisée" L["Enable Hotkey"] = "Activer raccourci" L["Enable Macro"] = "Activer macro" L["Enable MicroBar"] = "Activer la barre de menu" L["Enable OverrideWA"] = "Cacher les les temps de recharge avec WA" L["Format Cooldowns As Decimals"] = "Formater les temps de recharge en décimales" L["Mouseover BottomBar 1"] = "Survol barre en bas 1" L["Mouseover BottomBar 2"] = "Survol barre en bas 2" L["Mouseover BottomBar 3"] = "Survol barre en bas 3" L["Mouseover CustomBar"] = "Survol barre personnalisée" L["Mouseover MicroBar"] = "Survol MicroBar" L["Mouseover PetBar"] = "Survol barre du familier" L["Mouseover RightBar 1"] = "Survol barre droite 1" L["Mouseover RightBar 2"] = "Survol barre droite 2" L["Mouseover StanceBar"] = "Survol barre des postures" L["Set Actionbars Scale"] = "Set Actionbars Scale" L["Set CustomBar Button Size"] = "Taille des boutons de la barre personnalisée" L["Set CustomBar Num Buttons"] = "Nombre de boutons de la barre personnalisée" L["Set CustomBar Num PerRow"] = "Nombre de boutons par ligne de la barre personnalisée" L["Set MainBars Button Size"] = "Taille des boutons de la barre principale" L["Set RightBars Button Size"] = "Taille des boutons des barres droite" L["Set Stance/Pet Button Size"] = "Taille des boutons de la barre du familier/postures" L["Show Cooldowns"] = "Afficher les Cooldowns" L["Show PetBar"] = "Afficher barre du familier" L["Show StanceBar"] = "Afficher barre des postures" L["Accept Invites From Friends & Guild Members"] = "Accepter les invitations des amis et membres de guilde" L["Accept PartySync From Friends & Guild Members"] = "Accepter la Synchro. de groupe des amis et membres de guilde" L["Alert Group After Instance Resetting"] = "Alerter le groupe après la réinitialisation de l'instance" L["Announce Broken Spells"] = "Announce Broken Spells" L["Announce Dispells"] = "Announce Dispells" L["Announce Interrupts"] = "Annoncer les interruptions" L["Announce Items Being Placed"] = "Annoncer les festins et tables" L["Announce Only In Instances"] = "Announce Only In Instances" L["Announce Pull Countdown (/pc #)"] = "Annoncer le compte à rebours avant pull (/pc #)" L["Announce When Low On Health"] = "Annonce quand votre vie est faible" L["Announce When Sapped"] = "Annoncer quand assomer" L["Auto Accept Invite Keyword"] = "Accepter auto. les invitations par mot-clé" L["Auto Accept Resurrect Requests"] = "Accepter auto. les demandes de résurrection" L["Auto Accept Summon Requests"] = "Acceptez auto. les demandes d'invocation" L["Auto Collapse Objective Tracker"] = "Réduire automatiquement le suivi de quête" L["Auto Open Items In Your Inventory"] = "Ouvrir automatiquement les objets de votre inventaire" L["Auto Release in Battlegrounds & Arenas"] = "Libérer l'esprit auto. dans les Arènes et Champs de bataille" L["Auto Screenshot Achievements"] = "Capturer un screenshot après un Haut-fait" L["Auto Select Quest Rewards Best Value"] = "Sélectionner automatiquement la récompense de quête la plus cher" L["Auto Set Your Role In Groups"] = "Définir auto. votre rôle dans les groupes" L["Auto Skip All Cinematic/Movies"] = "Passer auto. les cinématiques" L["Automatically Remove Annoying Buffs"] = "Retirer auto. les améliorations inutiles" L["Blocks Invites From Strangers"] = "Bloquez les invitations des joueurs inconnus" L["Decline Pet Duels"] = "Refuser les duels de mascottes" L["Decline PvP Duels"] = "Refuser les duels JcJ" L["Don't Alert In instances"] = "Ne pas envoyer d'alertes en instance" L["Enable Event & Rare Alerts"] = "Activer les alertes d'évenement & de rare" L["Only Tab Target Enemy Players"] = "Cibler seulement les joueurs ennemis avec Tab." L["Own Dispells Announced Only"] = "Own Dispells Announced Only" L["Own Interrupts Announced Only"] = "Own Interrupts Announced Only" L["Print Alerts In Chat"] = "Ecrire les alertes dans le chat" L["Say 'Thank You' When Resurrected"] = "Dire 'Merci' quand ressusciter" L["Say Goodbye After Dungeon Completion."] = "Dire au revoir après avoir terminer le donjon." L["Anchor Every Five Rows Into One Row"] = "Anchor Every Five Rows Into One Row" L["Auto Repair Gear"] = "Réparer auto. l'équipement" L["Auto Vendor Grays"] = "Vendre la camelote auto." L["Bags Delete Button"] = "Bags Delete Button" L["Bags Width"] = "Largeur des sacs" L["Bank Width"] = "Largeur de la banque" L["Display Item Level"] = "Afficher le niveau d'objet" L["Enable Bagbar"] = "Activer la barre des sacs" L["Enable Inventory"] = "Activer inventaire" L["Fade Bagbar"] = "Barre des sacs fondue" L["Filter Anima Items"] = "Filtrer les objets Anima" L["Filter Collection Items"] = "Filter Collection Items" L["Filter Consumable Items"] = "Filrer les consommables" L["Filter EquipSet"] = "Filtrer les sets d'armure" L["Filter Equipment Items"] = "Filtrer les équipements" L["Filter Favourite Items"] = "Filtrer les objets favoris" L["Filter Goods Items"] = "Filtrer les ressources" L["Filter Items Into Categories"] = "Filtrer les objets en catégories" L["Filter Junk Items"] = "Filtrer la camelote" L["Filter Korthia Relic Items"] = "Filter Korthia Relic Items" L["Filter Legendary Items"] = "Filtrer les objets légendaires" L["Filter Quest Items"] = "Filtrer les objets de quête" L["Gather Empty Slots Into One Button"] = "Rassembler les emplacement vide en un bouton" L["Pet Trash Currencies"] = "Pet Trash Currencies" L["Show New Item Glow"] = "Mettre les nouveaux objets en surbrillance" L["Show Upgrade Icon"] = "Afficher l'icône d'amélioration" L["Slot Icon Size"] = "Dimension des emplacements" L["Umm Reverse The Sorting"] = "Umm inverser le tri" L["Auras Reminder (Shout/Intellect/Poison)"] = "Auras Reminder (Shout/Intellect/Poison)" L["Buff Icon Size"] = "Taille des icônes d'amélioration'" L["Buffs Grow Right"] = "Les améliorations s'affiche vers la droite" L["Buffs per Row"] = "Améliorations par ligne" L["DeBuff Icon Size"] = "Taille des icônes d'affaiblissement" L["DeBuffs per Row"] = "Affaiblissements par ligne" L["Debuffs Grow Right"] = "Les affaiblissements s'affiche vers la droite" L["Enable Auras"] = "Activer les Auras" L["Enable TotemBar"] = "Activer barre des totems" L["Totems IconSize"] = "Taille des icônes des Totems" L["Vertical TotemBar"] = "Barre des totems verticale" L["Alert On M+ Quake"] = "Alert On M+ Quake" L["AuraWatch GUI"] = "AuraWatch GUI" L["AuraWatch IconScale"] = "Taille des icônes d'AuraWatch" L["Disable AuraWatch Tooltip (ClickThrough)"] = "Désactiver l'info-bulle d'AuraWatch (Clic au travers)" L["Enable AuraWatch"] = "Activer AuraWatch" L["Track Auras From Previous Expansions"] = "Suivre les auras des précédentes extensions" L["Allow Spam From Friends"] = "Autoriser les spams d'amis" L["Block 'Some' AddOn Alerts"] = "Bloquer 'certaines' alertes d'AddOn" L["Block Repeated Spammer Messages"] = "Block Repeated Spammer Messages" L["Block Whispers From Strangers"] = "Bloquer les messages privés des étrangers" L["Chat History Lines To Save"] = "Chat History Lines To Save" L["ChatFilter BlackList"] = "Filtre liste noire du chat" L["ChatFilter WhiteList"] = "Filtre liste blanche du chat" L["Custom Chat Timestamps"] = "Horodatage personnalisé du Chat" L["Differ Whipser Colors"] = "Couleur différente des messages privés" L["Disable Chat Language Filter"] = "Désactiver le filtre à obscenité du chat" L["Enable Chat Filter"] = "Activer le filtre à obscenité du chat" L["Enable Chat"] = "Activer le Chat" L["Fade Chat Text"] = "Fondu du texte du chat" L["Fading Chat Visible Time"] = "Temps avant fondu du Chat" L["Filter Matches Number"] = "Filter Matches Number" L["Lock Chat Height"] = "Bloquer la hauteur du Chat" L["Lock Chat Width"] = "Bloquer la largeur du Chat" L["Lock Chat"] = "Bloquer le Chat" L["Show Chat Background"] = "Afficher le fond du Chat" L["Show Chat Loot Icons"] = "Afficher les icônes de butin du Chat" L["Show Chat Menu Buttons"] = "Afficher les boutons du menu du Chat" L["Show Emojis In Chat"] = "Show Emojis In Chat" L["Show ItemLevel on ChatFrames"] = "Afficher le niveau d'objet dans le Chat" L["Show Role Icons In Chat"] = "Show Role Icons In Chat" L["Stick On Channel If Whispering"] = "Stick On Channel If Whispering" L["Use Default Channel Names"] = "Utiliser les noms de canaux par défaut" L["DataBars Height"] = "Hauteur des barres d'info." L["DataBars Width"] = "Largeur des barres d'info." L["Enable DataBars"] = "Activer les barres d'info." L["Experience Bar Color"] = "Couleur de la barre d'Experience" L["Fade DataBars"] = "Fondu des barres d'info." L["Honor Bar Color"] = "Couleur de la barre d'Honneur" L["Pick Text Formatting"] = "Choisissez le formatage du texte" L["Rested Bar Color"] = "Couleur de la barre de repos" L["Show Text"] = "Afficher le texte" L["Track Honor"] = "Suivre l'Honneur" L["Color The Icons"] = "Color The Icons" L["Enable Currency Info"] = "Afficher les monnaies" L["Enable Friends Info"] = "Afficher les infos social" L["Enable Guild Info"] = "Afficher les infos de guilde" L["Enable Latency Info"] = "Afficher les infos de latences" L["Enable Minimap Location"] = "Afficher la localisation de la Minimap" L["Enable Minimap Time"] = "Afficher l'heure de la Minimap" L["Enable Positon Coords"] = "Enable Positon Coords" L["Enable System Info"] = "Afficher les infos système" L["Hide Icon Text"] = "Hide Icon Text" L["Auto Scale"] = "Echelle automatique" L["Border Style"] = "Style de bordure" L["Color 'Most' KkthnxUI Borders"] = "Couleur générale des bordures de KkthnxUI" L["Disable 'Some' Blizzard Tutorials"] = "Désactiver les tutoriels Blizzard" L["Disable Blizzard Error Frame Combat"] = "Désactiver la fenêtre d'erreur Blizzard pendant les combats" L["Enable Version Checking"] = "Activer la vérification de version" L["Import Profiles From Other Characters"] = "Importer les profils à partir d'autres personnages" L["Move Blizzard Frames"] = "Bouger les fenêtres Blizzard" L["Number Prefix Style"] = "Style du numéro de préfixe" L["Set UI scale"] = "Echelle de l'interface" L["Textures Color"] = "Couleur des Textures" L["Auto Confirm Loot Dialogs"] = "Confirmer automatique les fenêtres de butin" L["Auto Greed Green Items"] = "Cupidité automatique sur les objets verts" L["Enable Group Loot"] = "Activer le butin de groupe" L["Enable Loot"] = "Activer butin" L["Faster Auto-Looting"] = "Butin-Auto plus rapide" L["Blip Icon Styles"] = "Style de l'icône Blip" L["Enable Minimap"] = "Activer Minimap" L["Location Text Style"] = "Style du texte de Location" L["Minimap Size"] = "Taille de la Minimap" L["Set RecycleBin Positon"] = "Set RecycleBin Position" L["Show Minimap Button Collector"] = "Afficher l'agrégateur de bouton de la Minimap" L["Show Minimap Calendar"] = "Afficher le calendrier de la Minimap" L["AFK Camera"] = "AFK Camera" L["Add Spellbook-Like Tabs On TradeSkillFrame"] = "Ajouter des onglets type livre de sort dans TradeSkillFrame" L["Auto Emote On Your Killing Blow"] = "Envoyer un emote après un coup fatal" L["Character/Inspect Gem/Enchant Info"] = "Personnage/Inspecter Gemmes/Enchantements Info" L["Display Character Frame Full Stats"] = "Afficher les statistiques complètes du personnage" L["EasyMarking by Ctrl + LeftClick"] = "Marquage facile par Ctrl + LeftClick" L["Enable Mouse Trail"] = "Activer le tracé de la souris" L["Enhanced Color Picker"] = "Choix des couleurs amélioré" L["Enhanced Colors (Friends/Guild +)"] = "Couleurs améliorées (Amis/Guilde +)" L["Hide BossBanner"] = "Masquer la fenêtre des boss" L["Hide RaidBoss EmoteFrame"] = "Masquer RaidBoss EmoteFrame" L["Mouse Trail Color"] = "Couleur du tracé de la souris" L["Paragon Color"] = "Couleur du Parangon" L["Paragon Enable"] = "Activer Parangon" L["Paragon Text Format"] = "Format du texte Parangon" L["Paragon Toast Fade"] = "Fondu notification Parangon" L["Paragon Toast Sound"] = "Son notification Parangon" L["Paragon Toast"] = "Notification Parangon" L["Remove And Hide The TalkingHead Frame"] = "Désactiver et cacher la fenêtre parlante des PNJ" L["Replace Default Maw Threat Status"] = "Remplacer l'affichage de menace de l'Antre" L["Show Character/Inspect ItemLevel Info"] = "Afficher Personnage/Inspecter niveau d'objet" L["Show Mythic+ GuildBest"] = "Show Mythic Plus Guild Best" L["Show Slot Durability %"] = "Afficher la durabilité des objets %" L["Show Wowhead Links Above Questlog Frame"] = "Afficher un lien Wowhead au dessus de la fenêtre de suivi de quête" L["Show Your Killing Blow Info"] = "Afficher les informations de vos coups fatals" L["World Markers Bar"] = "World Markers Bar" L["Auras Filter Style"] = "Style de filtre des Auras" L["Auras Size"] = "Taille des Auras" L["Classpower/Healthbar Height"] = "Hauteur de la Barre de ressource/Barre de vie" L["Colored Custom Units"] = "Colored Custom Units" L["Custom Color"] = "Couleur personnalisée" L["Custom PowerUnit List"] = "Custom PowerUnit List" -- Needs Translations L["Custom UnitColor List"] = "Custom UnitColor List" -- Needs Translations L["Enable GCD Ticker"] = "Activer GCD Ticker" L["Enable Nameplates"] = "Activer les noms" L["Enable Personal Resource"] = "Activer l'energie personnelle" L["Force TankMode Colored"] = "Forcé la colorisation par menace" L["HealthText FontSize"] = "Taille de la police de la barre de vie" L["Insecure Color"] = "Couleur d'insécurité" L["Interacted Nameplate Stay Inside"] = "Interacted Nameplate Stay Inside" L["Max Auras"] = "Auras maximum" L["NameText FontSize"] = "Taille de la police du nom" L["Nameplate Height"] = "Hauteur de la barre de nom" L["Nameplate Vertical Spacing"] = "Espace vertical de la barre de nom" L["Nameplate Width"] = "Largeur barre de nom" L["Nameplete MaxDistance"] = "Distance max. d'affiche du nom" L["Non-Target Nameplate Alpha"] = "Alpha du nom des non-cibles" L["Non-Target Nameplate Scale"] = "Echelle du nom des non-cibles" L["Off-Tank Color"] = "Couleur des Off-Tank" L["Only Visible in Combat"] = "Seulement visible au combat" L["PlayerPlate IconSize"] = "Taille icône de la barre d'info. joueur" L["PlayerPlate Powerbar Height"] = "Hauteur barre d'energie du joueur" L["Quest Progress Indicator"] = "Indicateur de progrès de la quête" L["Revert Threat Color If Not Tank"] = "Inverser la couleur de la menace si non tank" L["Scale Nameplates for Explosives"] = "Scale Nameplates for Explosives" L["Secure Color"] = "Couleur de sécurité" L["Show AngryKeystones Progress"] = "Afficher la progression AngryKeystones" L["Show Enemy Class Icons"] = "Afficher l'icône de classe des ennemis" L["Show Friendly ClassColor"] = "Afficher la couleur de classe des cibles amicales" L["Show Health Value"] = "Afficher la valeur de santé" L["Show Hostile ClassColor"] = "Afficher la couleur de classe des cibles ennemis" L["Show Only Names For Friendly"] = "Afficher uniquement le noms des cibles amicales" L["Show Power Value"] = "Afficher la puissance" L["Smooth Bars Transition"] = "Transition des barres fluide" L["Target Nameplate ClassPower"] = "Target Nameplate ClassPower" L["TargetIndicator Color"] = "Couleur de l'indication de cible" L["TargetIndicator Style"] = "Style de l'indication de cible" L["Track Personal Class Auras"] = "Track Personal Class Auras" L["Transition Color"] = "Transition de couleur" L["Unit Execute Ratio"] = "Unit Execute Ratio" L["Bartender4 Skin"] = "Habillage de Bartender4" L["BigWigs Skin"] = "Habillage de BigWigs" L["ButtonForge Skin"] = "ButtonForge Skin" L["ChatBubbles Background Alpha"] = "Alpha du fond des bulles de Chat" L["ChatBubbles Skin"] = "Habillage des bulles de Chat" L["ChocolateBar Skin"] = "Habillage de ChocolateBar" L["Deadly Boss Mods Skin"] = "Habillage de Deadly Boss Mods" L["Details Skin"] = "Habillage de Details" L["Dominos Skin"] = "Habillage de Dominos" L["Hekili Skin"] = "Habillage d'Hekili" L["Skada Skin"] = "Habillage de Skada" L["Skin Some Blizzard Frames & Objects"] = "Habillage de certaines fenêtres Blizzard" L["Spy Skin"] = "Habillage de Spy" L["TalkingHead Skin"] = "Habillage de TalkingHead" L["TellMeWhen Skin"] = "Habillage de TellMeWhen" L["TitanPanel Skin"] = "Habillage de TitanPanel" L["WeakAuras Skin"] = "Habillage de WeakAuras" L["%month%-%day%-%year%"] = "%month%-%day%-%year%" L["Abbreviate Guild Names"] = "Abréger les noms des guildes" L["Castle Nathria"] = "Castle Nathria" L["Conduit Collected Info"] = "Informations recueillies sur les conduits" L["De Other Side"] = "De Other Side" L["Follow Cursor"] = "Suivre le curseur" L["Halls of Atonement"] = "Halls of Atonement" L["Heroic"] = "Heroic" L["Hide Guild Rank"] = "Cacher le rang de la guilde" L["Hide Player Title"] = "Cacher le titre du joueur" L["Hide Tooltip in Combat"] = "Cacher l'info-bulle en combat" L["Item Icons"] = "Icônes des objets" L["Mists of Tirna Scithe"] = "Mists of Tirna Scithe" L["Mythic Dungeons"] = "Mythic Dungeons" L["Mythic"] = "Mythic" L["Normal"] = "Normal" L["Not Completed"] = "Not Completed" L["Plaguefall"] = "Plaguefall" L["Quality Color Border"] = "Bordure de couleur en fonction de la qualité" L["Raid Finder"] = "Raid Finder" L["Sanctum of Domination"] = "Sanctum of Domination" L["Sanguine Depths"] = "Sanguine Depths" L["Shadowlands Keystone Master: Season One"] = "Shadowlands Keystone Master: Season One" L["Shadowlands Keystone Master: Season Two"] = "Shadowlands Keystone Master: Season Two" L["Show Faction Icon"] = "Afficher l'icône de faction" L["Show Player Targeted By"] = "Afficher 'Joueur Ciblé Par'" L["Show Roles Assigned Icon"] = "Afficher les icônes de rôle" L["Show Spec/ItemLevel by SHIFT"] = "Afficher Spec/Niveau d'objet avec SHIFT" L["Show Tooltip IDs"] = "Afficher l'ID des info-bulles" L["Show realm name by SHIFT"] = "Afficher le nom du royaume avec SHIFT" L["Spires of Ascension"] = "Spires of Ascension" L["Tazavesh, the Veiled Market"] = "Tazavesh, the Veiled Market" L["The Necrotic Wake"] = "The Necrotic Wake" L["Theater of Pain"] = "Theater of Pain" L["[ABBR] Castle Nathria"] = "CS" L["[ABBR] De Other Side"] = "DOS" L["[ABBR] Halls of Atonement"] = "HOA" L["[ABBR] Heroic"] = "H" L["[ABBR] Mists of Tirna Scithe"] = "MOTS" L["[ABBR] Mythic Keystone"] = "M+" L["[ABBR] Mythic"] = "M" L["[ABBR] Normal"] = "N" L["[ABBR] Plaguefall"] = "PF" L["[ABBR] Raid Finder"] = "RF" L["[ABBR] Raid"] = "R" L["[ABBR] Sanctum of Domination"] = "SoD" L["[ABBR] Sanguine Depths"] = "SD" L["[ABBR] Shadowlands Keystone Master: Season One"] = "Keystone Master S1" L["[ABBR] Shadowlands Keystone Master: Season Two"] = "Keystone Master S2" L["[ABBR] Spires of Ascension"] = "SOA" L["[ABBR] Tazavesh, the Veiled Market"] = "Tazavesh" L["[ABBR] The Necrotic Wake"] = "NW" L["[ABBR] Theater of Pain"] = "TOP" L["Set ActionBar Font"] = "Police des barres d'action" L["Set Auras Font"] = "Police des Auras" L["Set Chat Font"] = "Police du Chat" L["Set DataBars Font"] = "Police des barres d'info." L["Set DataText Font"] = "Police des textes d'info." L["Set Filger Font"] = "Police du Filger" L["Set General Font"] = "Police générale" L["Set Inventory Font"] = "Police de l'inventaire" L["Set Minimap Font"] = "Police de la Minimap" L["Set Nameplate Font"] = "Police des noms" L["Set QuestTracker Font"] = "Police du suivi de quête" L["Set Skins Font"] = "Police des habillages" L["Set Tooltip Font"] = "Police des info-bulles" L["Set Unitframe Font"] = "Police des cadres d'unité" L["Adjust QuestFont Size"] = "Ajuster la taille de la police des quêtes" L["Set DataBars Texture"] = "Texture des barres d'info." L["Set Filger Texture"] = "Texture du Filger" L["Set General Texture"] = "Texture générale" L["Set HealPrediction Texture"] = "Texture de la prédiction de soin" L["Set Loot Texture"] = "Texture du butin" L["Set Nameplate Texture"] = "Texture des noms" L["Set QuestTracker Texture"] = "Texture du suivi des quêtes" L["Set Skins Texture"] = "Texture des habillages" L["Set Tooltip Texture"] = "Texture de l'info-bulle" L["Set Unitframe Texture"] = "Texture des barres d'unités" L["Class Color Castbars"] = "Barres d'incantation' aux couleurs de classe" L["Enable Player CastBar"] = "Activer la barre d'incantation du joueur" L["Enable Simple CombatText"] = "Activer les textes de combat simple" L["Enable Target CastBar"] = "Activer la barre d'incantation de la cible" L["Enable Unitframes"] = "Activer les barres d'unités" L["Fade Unitframes"] = "Fondu des barres d'unités" L["Health Color Format"] = "Format de couleur de la vie" L["Hide TargetofTarget Frame"] = "Masquer la cible de la cible" L["Hide TargetofTarget Level"] = "Masquer le niveau de la cible de la cible" L["Hide TargetofTarget Name"] = "Masquer le nom de la cible de la cible" L["Target of Target Power Bar"] = "Barre de ressource de la cible de la cible" L["Target of Target Frame Height"] = "Hauteur de la fenêtre cible de la cible" L["Target of Target Frame Width"] = "Largeur de la fenêtre cible de la cible" L["Hide Pet Name"] = "Masquer le nom du familier" L["Hide Pet Level"] = "Masquer le niveau du familier" L["Pet Power Bar"] = "Barre de ressource du familier" L["Pet Frame Height"] = "Hauteur de la fenêtre du familier" L["Pet Frame Width"] = "Largeur de la fenêtre du familier" L["Focus Power Bar"] = "Barre de ressource du focus" L["Focus Frame Height"] = "Hauteur de la fenêtre focus" L["Focus Frame Width"] = "Largeur de la fenêtre focus" L["Number of Buffs Per Row"] = "Nombre de buffs par ligne" L["Number of Debuffs Per Row"] = "Nombre de debuffs par ligne" L["Only Show Your Debuffs"] = "Afficher seulement vos débuffs" L["Pet's Healing/Damage"] = "Dommages/Soins du familier" L["Player Power Bar"] = "Player Power Bar" L["Player Frame Height"] = "Player Frame Height" L["Player Frame Width"] = "Player Frame Width" L["Player Castbar Height"] = "Hauteur de la barre d'incantation du joueur" L["Player Castbar Width"] = "Largeur de la barre d'incantation du joueur" L["Reaction Color Castbars"] = "Reaction Color Castbars" L["Show Additional Mana Power (|CFFFF7D0ADruide|r, |CFFFFFFFFPrêtre|r, |CFF0070DEChaman|r)"] = "Afficher le mana additionel (|CFFFF7D0ADruide|r, |CFFFFFFFFPrêtre|r, |CFF0070DEChaman|r)" L["Show AutoAttack Damage"] = "Afficher les dommages des attaques auto" L["Show Castbar Latency"] = "Afficher la latence de la barre d'incantation" L["Show Class Resources"] = "Afficher les ressources de classe" L["Show Full OverHealing"] = "Afficher l'OverHealing" L["Show Global Cooldown"] = "Afficher le Global Cooldown" L["Show HealPrediction Statusbars"] = "Afficher la prédiction de heal sur les Statusbars" L["Show Health Debuff Highlight"] = "Mettre en surbrillance les affaiblissements de vie" L["Show Hots and Dots"] = "Afficher les Hots et Dots" L["Pet's Healing/Damage"] = "Pet's Healing/Damage" L["Show Player Frame Buffs"] = "Afficher les buffs du joueur" L["Show Player Frame Debuffs"] = "Afficher les débuffs du joueur" L["Show Player Frame Level"] = "Afficher le niveau du joueur" L["Show Player Frame Name"] = "Afficher le nom du joueur" L["Show Player Power Prediction"] = "Afficher la prediction d'utilisation de ressource" L["Show PvP Indicator on Player / Target"] = "Afficher l'indication JcJ sur le joueur/cible" L["Show Target Frame Buffs"] = "Afficher les buffs de la cible" L["Show Target Frame Debuffs"] = "Afficher les débuffs de la cible" L["Show |CFF00FF96Monk|r Stagger Bar"] = "Afficher la barre de report du |CFF00FF96Moine|r" L["Smooth Bars"] = "Barres fluides" L["Sound Played When You Are Resurrected"] = "Son joué lors de la résurrection" L["Target Power Bar"] = "Target Power Bar" L["Target Frame Height"] = "Target Frame Height" L["Target Frame Width"] = "Target Frame Width" L["Target Castbar Height"] = "Hauteur de la barre d'incantation de la cible" L["Target Castbar Width"] = "Largeur de la barre d'incantation de la cible" L["Target of Focus Power Bar"] = "Barre de ressource de la cible du focus" L["Target of Focus Frame Height"] = "Hauteur de la fenêtre de la cible du focus" L["Target of Focus Frame Width"] = "Largeur de la fenêtre de la cible du focus" L["Unitframe Portrait Style"] = "Style du portrait du cadre d'unité" L["Unitframe Swingbar Timer"] = "Unitframe Swingbar Timer" L["Unitframe Swingbar"] = "Unitframe Swingbar" L["Enable Party"] = "Activer les groupes" L["Show Castbars"] = "Afficher les barres d'incantation" L["Show Highlighted Target"] = "Afficher la cible mise en évidence" L["Show Party Buffs"] = "Afficher les buffs de groupe" L["Show Party Pets"] = "Afficher les familiers du groupe" L["Show Player In Party"] = "Afficher les joueurs dans le groupe" L["Smooth Bar Transition"] = "Transitions fluides des barres" L["Enable Boss"] = "Activer boss" L["Enable Arena"] = "Activer arène" L["Aura Debuff Icon Size"] = "Taille d'icône des Debuffs Aura" L["AuraWatch Icon Size"] = "Taille d'icône d'AuraWatch" L["Enable Raidframes"] = "Activer les fenêtres de raid" L["Health Format"] = "Format de la vie" L["Horizontal Raid Frames"] = "Fenêtres de raid horizontales" L["Number Of Groups to Show"] = "Nombre de groupe affichés" L["Raidframe Height"] = "Hauteur des fenêtres de raid" L["Raidframe Width"] = "Largeur des fenêtres de raid" L["Reverse Raid Frame Growth"] = "Inverser le sens d'agrandissement de la fenêtre de raid" L["Save Raid Positions Based On Specs"] = "Sauvergarder la position du raid par rapport a votre spécialisation" L["Show AuraWatch Icons"] = "Afficher les icônes AuraWatch" L["Show Away/DND Status"] = "Afficher le statut Absent/Ne pas déranger" L["Show Group Number Team Index"] = "Afficher le numéro de groupe" L["Show MainTank Frames"] = "Afficher la fenêtre des tanks principaux" L["Show Manabars"] = "Afficher les barres de mana" L["Show Raid Utility Frame"] = "Afficher la fenêtre utilitaire de raid" L["Alert QuestProgress In Chat"] = "Alerter votre progression de quête dans le chat" L["Enable QuestNotifier"] = "Activer la notification de quête" L["Only Play Complete Quest Sound"] = "Ne jouez que le son en réussite de quête" L["Alpha When Moving"] = "Alpha When Moving" L["Fade Worldmap When Moving"] = "Fondu de la carte du monde en mouvement" L["Map Reveal Shadow Color"] = "Couleur de l'ombre de révélation de la carte" L["Map Reveal Shadow"] = "Ombre de révalation de la carte" L["Show Player/Mouse Coordinates"] = "Afficher les coordonnées du joueur/souris" L["Show Smaller Worldmap"] = "Afficher une carte du monde plus petite" -- GUI Config Tooltip Locales L["AutoScaleTip"] = "Mise à l'échelle automatique de l'IU au pixel près en fonction de votre résolution.|n|nSi vous voulez changer l'échelle manuellement, vous devez désactiver 'Echelle automatique' puis appliquer l'échelle en utilisant le curseur" L["CustomUnitTip"] = "Entrez le nom de l'unité ou l'ID du PNJ. Vous pouvez voir l'ID du PNJ dans l'info-bulle en maintenant la touche MAJ enfoncée." L["ExecuteRatioTip"] = "Si le pourcentage de santé de l'unité est inférieur à la valeur plafond d'exécution que vous avez fixée, son nom devient rouge.|n|nL'indicateur d'exécution sera désactivé sur 0." L["MapRevealTip"] = "Si cette option est activée, les zones à explorer seront affichées dans une ombre légère. Vous pouvez choisir la couleur de l'ombre que vous souhaitez." L["ParagonReputationTip"] = "Remplace les barres exaltées du cadre de réputation par des barres Parangon, que vous pouvez personnaliser vous-même avec les paramètres" L["UIScaleTip"] = "Modifier l'échelle de l'IU selon vos préférences|n|nSi vous voulez changer l'échelle manuellement, vous devez désactiver 'Echelle automatique' puis appliquer l'échelle en utilisant le curseur"
object_tangible_collection_col_gcw_city_reb_4 = object_tangible_collection_shared_col_gcw_city_reb_4:new { gameObjectType = 8211,} ObjectTemplates:addTemplate(object_tangible_collection_col_gcw_city_reb_4, "object/tangible/collection/col_gcw_city_reb_4.iff")
--[[ Nginx Shard DiCT Cache operation utils --]] local cjson = require("core.utils.json") local shared_name = require("core.constants.shard_name") local shared = ngx.shared local cache_data = shared[shared_name.global_cache] local _Cache = {} function _Cache._get(key) return cache_data:get(key) end function _Cache.get_json(key) local value, flags = _Cache._get(key) if value then value = cjson.decode(value) end return value, flags end function _Cache.get(key) return _Cache._get(key) end function _Cache._set(key, value) -- success, err, forcible return cache_data:set(key, value) end function _Cache._add(key,value) -- success, err, forcible return cache_data:add(key,value) end function _Cache.set_json(key, value) if value then value = cjson.encode(value) end return _Cache._set(key, value) end function _Cache.set(key, value) -- success, err, forcible return _Cache._set(key, value) end function _Cache.add(key,value) -- success, err, forcible return _Cache._add(key,value) end function _Cache.add_json(key,value ) if value then value = cjson.encode(value) end return _Cache._add(key,value) end function _Cache.incr(key, value) return cache_data:incr(key, value) end function _Cache.delete(key) return cache_data:delete(key) end function _Cache.delete_all() cache_data:flush_all() cache_data:flush_expired() end return _Cache
-- Build configuration for logos -- Matthew Leingang, 2020-09-23 bundle = "Gotham" module = "logos" maindir = ".." -- Files to install to the tex area of the texmf tree imagefiles = {"*.eps", "*.svg", "*_*_*.pdf", "*.png", "*.jpg"} sourcefiles = imagefiles installfiles = imagefiles -- Files to typeset for documentation typesetfiles = {"nyu-logos.tex"} -- Executable for compiling doc(s) typesetexe = "xelatex" cleanfiles = {"*.log", "nyu-logos.pdf", "*.zip"} -- Root directory of the TDS structure for the module to be installed into. -- Mentally prepend the path to the correct texmf tree THEN either "tex" (for -- includes), "doc" (for documentation), or "source" (for source files). tdsroot = "generic" function update_tag(file,content,tagname,tagdate) -- This should go in a pre-tag hook, but there isn't one. -- ensure that the tagname matches `v`x.y.z assert(string.match(tagname,"^v%d+%.%d+%.%d+$"), "invalid tag name. Use a literal 'v', then a semantic version number of the form x.y.z.") -- Make sure the working directory is "clean". -- See https://unix.stackexchange.com/a/394674/62853 assert(os.execute("git diff-index --quiet HEAD .") == 0, "Working directory dirty. Commit changes and try again.") -- TeX dates are in yyyy/mm/dd format. tagdate is in yyyy-mm-dd format. tagdate_tex = string.gsub(tagdate,'-','/') if string.match(file, "%.dtx$") then content = string.gsub(content, "\n %[%d%d%d%d/%d%d/%d%d v.- ", "\n [" .. tagdate_tex .. " " .. tagname .. " " ) content = string.gsub(content, "\n%% \\changes{unreleased}", "\n%% \\changes{" .. tagname .. "}" ) return content end end kpse.set_program_name("texlua") if not release_date then dofile(kpse.lookup("l3build.lua")) end
--[[ *** This file adapted from https://github.com/nvim-lua/plenary.nvim MIT License Copyright (c) 2020 TJ DeVries 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. **** ]] --[[ Curl Wrapper all curl methods accepts url = "The url to make the request to.", (string) query = "url query, append after the url", (table) body = "The request body" (string/filepath/table) auth = "Basic request auth, 'user:pass', or {"user", "pass"}" (string/array) form = "request form" (table) raw = "any additonal curl args, it must be an array/list." (array) dry_run = "whether to return the args to be ran through curl." (boolean) output = "where to download something." (filepath) timeout = "timeout in milliseconds for synchronous requests" (number) return_job = "whether to return the Job and a function which can be called to check the response" (boolean) and returns table: exit = "The shell process exit code." (number) status = "The https response status." (number) headers = "The https response headers." (array) body = "The http response body." (string) see test/plenary/curl_spec.lua for examples. author = github.com/tami5 ]] -- local util, parse = {}, {} -- Helpers -------------------------------------------------- ------------------------------------------------------------- local F = require('plenary.functional') local J = require('plenary.job') local P = require('plenary.path') local log = require('nvim-magic-openai._log') local DEFAULT_TIMEOUT = 10000 -- milliseconds local function is_windows() return P.path.sep == '\\' end local function default_compressed() return not is_windows() -- it may be more common on Windows for curl to be installed without compression support end -- Utils ---------------------------------------------------- ------------------------------------------------------------- util.url_encode = function(str) if type(str) ~= 'number' then str = str:gsub('\r?\n', '\r\n') str = str:gsub('([^%w%-%.%_%~ ])', function(c) return string.format('%%%02X', c:byte()) end) str = str:gsub(' ', '+') return str else return str end end util.kv_to_list = function(kv, prefix, sep) return vim.tbl_flatten(F.kv_map(function(kvp) return { prefix, kvp[1] .. sep .. kvp[2] } end, kv)) end util.kv_to_str = function(kv, sep, kvsep) return F.join( F.kv_map(function(kvp) return kvp[1] .. kvsep .. util.url_encode(kvp[2]) end, kv), sep ) end util.gen_dump_path = function() local path local id = string.gsub('xxxx4xxx', '[xy]', function(l) local v = (l == 'x') and math.random(0, 0xf) or math.random(0, 0xb) return string.format('%x', v) end) if is_windows() then path = string.format('%s\\AppData\\Local\\Temp\\plenary_curl_%s.headers', os.getenv('USERPROFILE'), id) else path = '/tmp/plenary_curl_' .. id .. '.headers' end return { '-D', path } end -- Parsers ---------------------------------------------------- --------------------------------------------------------------- parse.headers = function(t) if not t then return end local upper = function(str) return string.gsub(' ' .. str, '%W%l', string.upper):sub(2) end return util.kv_to_list( (function() local normilzed = {} for k, v in pairs(t) do normilzed[upper(k:gsub('_', '%-'))] = v end return normilzed end)(), '-H', ': ' ) end parse.data_body = function(t) if not t then return end return util.kv_to_list(t, '-d', '=') end parse.raw_body = function(xs) if not xs then return end if type(xs) == 'table' then return parse.data_body(xs) else return { '--data-raw', xs } end end parse.form = function(t) if not t then return end return util.kv_to_list(t, '-F', '=') end parse.curl_query = function(t) if not t then return end return util.kv_to_str(t, '&', '=') end parse.method = function(s) if not s then return end if s ~= 'head' then return { '-X', string.upper(s) } else return { '-I' } end end parse.file = function(p) if not p then return end return { '-d', '@' .. P.expand(P.new(p)) } end parse.auth = function(xs) if not xs then return end return { '-u', type(xs) == 'table' and util.kv_to_str(xs, nil, ':') or xs } end parse.url = function(xs, q) if not xs then return end q = parse.curl_query(q) if type(xs) == 'string' then return q and xs .. '?' .. q or xs elseif type(xs) == 'table' then error('Low level URL definition is not supported.') end end parse.accept_header = function(s) if not s then return end return { '-H', 'Accept: ' .. s } end -- Parse Request ------------------------------------------- ------------------------------------------------------------ parse.request = function(opts) if opts.body then local b = opts.body opts.body = nil if type(b) == 'table' then opts.data = b elseif P.is_file(P.new(b)) then opts.in_file = b elseif type(b) == 'string' then opts.raw_body = b end end local preargs = vim.tbl_flatten({ '-sSL', opts.dump, opts.compressed and '--compressed' or nil, parse.method(opts.method), parse.headers(opts.headers), parse.accept_header(opts.accept), parse.raw_body(opts.raw_body), parse.data_body(opts.data), parse.form(opts.form), parse.file(opts.in_file), }) local postargs = vim.tbl_flatten({ opts.raw, opts.output and { '-o', opts.output } or nil, parse.url(opts.url, opts.query), }) local nonauth_args = vim.deepcopy(preargs) vim.list_extend(nonauth_args, postargs) log.fmt_debug('Parsed request options nonauth_curl_args=%s', nonauth_args) local args = preargs vim.list_extend( args, vim.tbl_flatten({ parse.auth(opts.auth), }) ) vim.list_extend(args, postargs) return preargs, opts end -- Parse response ------------------------------------------ ------------------------------------------------------------ parse.response = function(lines, dump_path, code) local headers = P.readlines(dump_path) local status = tonumber(string.match(headers[1], '([%w+]%d+)')) local body = F.join(lines, '\n') vim.loop.fs_unlink(dump_path) table.remove(headers, 1) return { status = status, headers = headers, body = body, exit = code, } end local curl_job = function(args, dump_path, callback) return J:new({ command = 'curl', args = args, on_exit = function(j, code) if code ~= 0 then callback( nil, 'curl exited with code=' .. tostring(code) .. ' stderr=' .. vim.inspect(j:stderr_result()) ) return end local output = parse.response(j:result(), dump_path, code) callback(output) end, }) end local request = function(specs) local args, opts = parse.request(vim.tbl_extend('force', { compressed = default_compressed(), dry_run = false, dump = util.gen_dump_path(), }, specs)) if opts.dry_run then return args end local response local cb local errmsg if opts.callback then cb = opts.callback else cb = function(output, error_msg) if error_msg then errmsg = error_msg end response = output end end local job = curl_job(args, opts.dump[2], cb) if opts.return_job then return job, function() return response, errmsg end end if opts.callback then return job:start() else local timeout if opts.timeout then timeout = opts.timeout else timeout = DEFAULT_TIMEOUT end job:sync(timeout) return response end end -- Main ---------------------------------------------------- ------------------------------------------------------------ return (function() local spec = {} local partial = function(method) return function(url, opts) opts = opts or {} if type(url) == 'table' then opts = url spec.method = method else spec.url = url spec.method = method end opts = method == 'request' and opts or (vim.tbl_extend('keep', opts, spec)) return request(opts) end end return { get = partial('get'), post = partial('post'), put = partial('put'), head = partial('head'), patch = partial('patch'), delete = partial('delete'), request = partial('request'), } end)()
local NumEntries = 13 local RowHeight = 24 local RpgYellow = color("0.902,0.765,0.529,1") local ItlPink = color("1,0.2,0.406,1") local paneWidth1Player = 330 local paneWidth2Player = 230 local paneWidth = (GAMESTATE:GetNumSidesJoined() == 1) and paneWidth1Player or paneWidth2Player local paneHeight = 360 local borderWidth = 2 local SetRpgStyle = function(eventAf) eventAf:GetChild("MainBorder"):diffuse(RpgYellow) eventAf:GetChild("BackgroundImage"):visible(true) eventAf:GetChild("BackgroundColor"):diffuse(color("0,0,0,0.8")) eventAf:GetChild("HeaderBorder"):diffuse(RpgYellow) eventAf:GetChild("HeaderBackground"):diffusetopedge(color("0.275,0.510,0.298,1")):diffusebottomedge(color("0.235,0.345,0.184,1")) eventAf:GetChild("Header"):diffuse(RpgYellow) eventAf:GetChild("EX"):visible(false) eventAf:GetChild("BodyText"):diffuse(Color.White) eventAf:GetChild("PaneIcons"):GetChild("Text"):diffuse(RpgYellow) local leaderboard = eventAf:GetChild("Leaderboard") for i=1, NumEntries do local entry = leaderboard:GetChild("LeaderboardEntry"..i) entry:GetChild("Rank"):diffuse(Color.White) entry:GetChild("Name"):diffuse(Color.White) entry:GetChild("Score"):diffuse(Color.White) entry:GetChild("Date"):diffuse(Color.White) end end local SetItlStyle = function(eventAf) eventAf:GetChild("MainBorder"):diffuse(ItlPink) eventAf:GetChild("BackgroundImage"):visible(false) eventAf:GetChild("BackgroundColor"):diffuse(Color.White):diffusealpha(1) eventAf:GetChild("HeaderBorder"):diffuse(ItlPink) eventAf:GetChild("HeaderBackground"):diffusetopedge(color("0.3,0.3,0.3,1")):diffusebottomedge(color("0.157,0.157,0.165,1")) eventAf:GetChild("Header"):diffuse(Color.White) eventAf:GetChild("EX"):diffuse(Color.White):visible(false) eventAf:GetChild("BodyText"):diffuse(color("0.157,0.157,0.165,1")) eventAf:GetChild("PaneIcons"):GetChild("Text"):diffuse(ItlPink) local leaderboard = eventAf:GetChild("Leaderboard") for i=1, NumEntries do local entry = leaderboard:GetChild("LeaderboardEntry"..i) entry:GetChild("Rank"):diffuse(Color.Black) entry:GetChild("Name"):diffuse(Color.Black) entry:GetChild("Score"):diffuse(Color.Black) entry:GetChild("Date"):diffuse(Color.Black) end end local SetEntryText = function(rank, name, score, date, actor) if actor == nil then return end actor:GetChild("Rank"):settext(rank) actor:GetChild("Name"):settext(name) actor:GetChild("Score"):settext(score) actor:GetChild("Date"):settext(date) end local SetLeaderboardData = function(eventAf, leaderboardData, event) local entryNum = 1 local rivalNum = 1 local leaderboard = eventAf:GetChild("Leaderboard") local defaultTextColor = event == "itl" and Color.White or Color.Black -- Hide the rival and self highlights. -- They will be unhidden and repositioned as needed below. for i=1,3 do leaderboard:GetChild("Rival"..i):visible(false) end leaderboard:GetChild("Self"):visible(false) for gsEntry in ivalues(leaderboardData) do local entry = leaderboard:GetChild("LeaderboardEntry"..entryNum) SetEntryText( gsEntry["rank"]..".", gsEntry["name"], string.format("%.2f%%", gsEntry["score"]/100), ParseGroovestatsDate(gsEntry["date"]), entry ) if gsEntry["isRival"] then if gsEntry["isFail"] then entry:GetChild("Rank"):diffuse(Color.Black) entry:GetChild("Name"):diffuse(Color.Black) entry:GetChild("Score"):diffuse(Color.Red) entry:GetChild("Date"):diffuse(Color.Black) else entry:diffuse(Color.Black) end leaderboard:GetChild("Rival"..rivalNum):y(entry:GetY()):visible(true) rivalNum = rivalNum + 1 elseif gsEntry["isSelf"] then if gsEntry["isFail"] then entry:GetChild("Rank"):diffuse(Color.Black) entry:GetChild("Name"):diffuse(Color.Black) entry:GetChild("Score"):diffuse(Color.Red) entry:GetChild("Date"):diffuse(Color.Black) else entry:diffuse(Color.Black) end leaderboard:GetChild("Self"):y(entry:GetY()):visible(true) else entry:diffuse(defaultTextColor) end -- Why does this work for normal entries but not for Rivals/Self where -- I have to explicitly set the colors for each child?? if gsEntry["isFail"] then entry:GetChild("Score"):diffuse(Color.Red) end entryNum = entryNum + 1 end -- Empty out any remaining entries. for i=entryNum, NumEntries do local entry = leaderboard:GetChild("LeaderboardEntry"..i) -- We didn't get any scores if i is still == 1. if i == 1 then SetEntryText("", "No Scores", "", "", entry) else -- Empty out the remaining rows. SetEntryText("", "", "", "", entry) end end end local GetRpgPaneFunctions = function(eventAf, rpgData, player) local score, scoreDelta, rate, rateDelta = 0, 0, 0, 0 local pss = STATSMAN:GetCurStageStats():GetPlayerStageStats(player) local paneTexts = {} local paneFunctions = {} if rpgData["result"] == "score-added" then score = pss:GetPercentDancePoints() * 100 scoreDelta = score rate = SL.Global.ActiveModifiers.MusicRate or 1.0 rateDelta = rate elseif rpgData["result"] == "improved" or rpgData["result"] == "score-not-improved" then score = pss:GetPercentDancePoints() * 100 scoreDelta = rpgData["scoreDelta"] and rpgData["scoreDelta"]/100.0 or 0.0 rate = SL.Global.ActiveModifiers.MusicRate or 1.0 rateDelta = rpgData["rateDelta"] and rpgData["rateDelta"]/100.0 or 0.0 else -- song-not-ranked (invalid case) return paneFunctions end local statImprovements = {} local skillImprovements = {} local quests = {} local progress = rpgData["progress"] if progress then if progress["statImprovements"] then for improvement in ivalues(progress["statImprovements"]) do if improvement["gained"] > 0 then table.insert( statImprovements, string.format("+%d %s", improvement["gained"], string.upper(improvement["name"])) ) end end end if progress["skillImprovements"] then skillImprovements = progress["skillImprovements"] end if progress["questsCompleted"] then for quest in ivalues(progress["questsCompleted"]) do local questStrings = {} table.insert(questStrings, string.format( "Completed \"%s\"!\n", quest["title"] )) -- Group all the rewards by type. local allRewards = {} for reward in ivalues(quest["rewards"]) do if allRewards[reward["type"]] == nil then allRewards[reward["type"]] = {} end table.insert(allRewards[reward["type"]], reward["description"]) end for rewardType, rewardDescriptions in pairs(allRewards) do table.insert(questStrings, string.format( "%s".. "%s\n", rewardType == "ad-hoc" and "" or string.upper(rewardType)..":\n", table.concat(rewardDescriptions, "\n") )) end table.insert(quests, table.concat(questStrings, "\n")) end end end table.insert(paneTexts, string.format( "Skill Improvements\n\n".. "%.2f%% (%+.2f%%) at\n".. "%.2fx (%+.2fx) rate\n\n".. "%s".. "%s", score, scoreDelta, rate, rateDelta, #statImprovements == 0 and "" or table.concat(statImprovements, "\n").."\n\n", #skillImprovements == 0 and "" or table.concat(skillImprovements, "\n").."\n\n" )) for quest in ivalues(quests) do table.insert(paneTexts, quest) end for text in ivalues(paneTexts) do table.insert(paneFunctions, function(eventAf) SetRpgStyle(eventAf) eventAf:GetChild("Header"):settext(rpgData["name"]) eventAf:GetChild("Leaderboard"):visible(false) local bodyText = eventAf:GetChild("BodyText") -- We don't want text to run out through the bottom. -- Incrementally adjust the zoom while adjust wrapwdithpixels until it fits. -- Not the prettiest solution but it works. for zoomVal=1.0, 0.1, -0.05 do bodyText:zoom(zoomVal) bodyText:wrapwidthpixels(paneWidth/(zoomVal)) bodyText:settext(text):visible(true) Trace(bodyText:GetHeight() * zoomVal) if bodyText:GetHeight() * zoomVal <= paneHeight - RowHeight*1.5 then break end end local offset = 0 while offset <= #text do -- Search for all numbers (decimals included). -- They may include the +/- prefixes and also potentially %/x as suffixes. local i, j = string.find(text, "[-+]?[%d]*%.?[%d]+[%%x]?", offset) -- No more numbers found. Break out. if i == nil then break end -- Extract the actual numeric text. local substring = string.sub(text, i, j) -- Numbers should be a blueish hue by default. local clr = color("0,1,1,1") -- Except negatives should be red. if substring:sub(1, 1) == "-" then clr = Color.Red -- And positives should be green. elseif substring:sub(1, 1) == "+" then clr = Color.Green end bodyText:AddAttribute(i-1, { Length=#substring, Diffuse=clr }) offset = j + 1 end offset = 0 while offset <= #text do -- Search for all quoted strings. local i, j = string.find(text, "\".-\"", offset) -- No more found. Break out. if i == nil then break end -- Extract the actual numeric text. local substring = string.sub(text, i, j) bodyText:AddAttribute(i-1, { Length=#substring, Diffuse=Color.Green }) offset = j + 1 end end) end table.insert(paneFunctions, function(eventAf) SetRpgStyle(eventAf) eventAf:GetChild("Header"):settext(rpgData["name"]) SetLeaderboardData(eventAf, rpgData["rpgLeaderboard"], "rpg") eventAf:GetChild("Leaderboard"):visible(true) eventAf:GetChild("BodyText"):visible(false) end) return paneFunctions end local GetItlPaneFunctions = function(eventAf, itlData, player) local pn = ToEnumShortString(player) local score = CalculateExScore(player) local paneTexts = {} local paneFunctions = {} scoreDelta = itlData["scoreDelta"]/100.0 previousRankingPointTotal = itlData["previousRankingPointTotal"] currentRankingPointTotal = itlData["currentRankingPointTotal"] rankingDelta = currentRankingPointTotal - previousRankingPointTotal previousPointTotal = itlData["previousPointTotal"] currentPointTotal = itlData["currentPointTotal"] totalDelta = currentPointTotal - previousPointTotal table.insert(paneTexts, string.format( "EX Score: %.2f%% (%+.2f%%)\n".. "Ranking Points: %d (%+d)\n".. "Total Points: %d (%+d)\n\n", score, scoreDelta, currentRankingPointTotal, rankingDelta, currentPointTotal, totalDelta )) for text in ivalues(paneTexts) do table.insert(paneFunctions, function(eventAf) SetItlStyle(eventAf) eventAf:GetChild("Header"):settext(itlData["name"]) eventAf:GetChild("Leaderboard"):visible(false) eventAf:GetChild("EX"):visible(true) local bodyText = eventAf:GetChild("BodyText") -- We don't want text to run out through the bottom. -- Incrementally adjust the zoom while adjust wrapwdithpixels until it fits. -- Not the prettiest solution but it works. for zoomVal=1.0, 0.1, -0.05 do bodyText:zoom(zoomVal) bodyText:wrapwidthpixels(paneWidth/(zoomVal)) bodyText:settext(text):visible(true) Trace(bodyText:GetHeight() * zoomVal) if bodyText:GetHeight() * zoomVal <= paneHeight - RowHeight*1.5 then break end end local offset = 0 while offset <= #text do -- Search for all numbers (decimals included). -- They may include the +/- prefixes and also potentially %/x as suffixes. local i, j = string.find(text, "[-+]?[%d]*%.?[%d]+[%%x]?", offset) -- No more numbers found. Break out. if i == nil then break end -- Extract the actual numeric text. local substring = string.sub(text, i, j) -- Numbers should be a pinkish hue by default. local clr = ItlPink -- Except negatives should be red. if substring:sub(1, 1) == "-" then clr = Color.Red -- And positives should be green. elseif substring:sub(1, 1) == "+" then clr = Color.Green end bodyText:AddAttribute(i-1, { Length=#substring, Diffuse=clr }) offset = j + 1 end offset = 0 while offset <= #text do -- Search for all quoted strings. local i, j = string.find(text, "\".-\"", offset) -- No more found. Break out. if i == nil then break end -- Extract the actual numeric text. local substring = string.sub(text, i, j) bodyText:AddAttribute(i-1, { Length=#substring, Diffuse=Color.Green }) offset = j + 1 end end) end table.insert(paneFunctions, function(eventAf) SetItlStyle(eventAf) SetLeaderboardData(eventAf, itlData["itlLeaderboard"], "itl") eventAf:GetChild("Header"):settext(itlData["name"]) eventAf:GetChild("Leaderboard"):visible(true) eventAf:GetChild("EX"):visible(true) eventAf:GetChild("BodyText"):visible(false) end) return paneFunctions end local af = Def.ActorFrame{ Name="EventOverlay", InitCommand=function(self) self:visible(false) end, -- Slightly darken the entire screen Def.Quad { InitCommand=function(self) self:FullScreen():diffuse(Color.Black):diffusealpha(0.8) end }, -- Press START to dismiss text. LoadFont("Common Normal")..{ Text=THEME:GetString("Common", "PopupDismissText"), InitCommand=function(self) self:xy(_screen.cx, _screen.h-50):zoom(1.1) end } } for player in ivalues(PlayerNumber) do af[#af+1] = Def.ActorFrame{ Name=ToEnumShortString(player).."EventAf", InitCommand=function(self) self.PaneFunctions = {} self:visible(false) if GAMESTATE:GetNumSidesJoined() == 1 then self:xy(_screen.cx, _screen.cy - 15) else self:xy(_screen.cx + 160 * (player==PLAYER_1 and -1 or 1), _screen.cy - 15) end end, PlayerJoinedMessageCommand=function(self) self:visible(GAMESTATE:IsSideJoined(player)) end, ShowCommand=function(self, params) self.PaneFunctions = {} if params.data["rpg"] then local rpgData = params.data["rpg"] for func in ivalues(GetRpgPaneFunctions(self, rpgData, player)) do self.PaneFunctions[#self.PaneFunctions+1] = func end end if params.data["itl"] then local itlData = params.data["itl"] for func in ivalues(GetItlPaneFunctions(self, itlData, player)) do self.PaneFunctions[#self.PaneFunctions+1] = func end end self.PaneIndex = 1 if #self.PaneFunctions > 0 then self.PaneFunctions[self.PaneIndex](self) self:visible(true) end end, EventOverlayInputEventMessageCommand=function(self, event) if #self.PaneFunctions == 0 then return end if event.PlayerNumber == player then if event.type == "InputEventType_FirstPress" then -- We don't use modulus because #Leaderboards might be zero. if event.GameButton == "MenuLeft" then self.PaneIndex = self.PaneIndex - 1 if self.PaneIndex == 0 then -- Wrap around if we decremented from 1 to 0. self.PaneIndex = #self.PaneFunctions end elseif event.GameButton == "MenuRight" then self.PaneIndex = self.PaneIndex + 1 if self.PaneIndex > #self.PaneFunctions then -- Wrap around if we incremented past #Leaderboards self.PaneIndex = 1 end end if event.GameButton == "MenuLeft" or event.GameButton == "MenuRight" then self.PaneFunctions[self.PaneIndex](self) end end end end, -- White border Def.Quad { Name="MainBorder", InitCommand=function(self) self:zoomto(paneWidth + borderWidth, paneHeight + borderWidth + 1) end }, -- Main Black cement background Def.Sprite { Name="BackgroundImage", Texture=THEME:GetPathG("", "_VisualStyles/SRPG6/Overlay-BG.png"), InitCommand=function(self) self:CropTo(paneWidth, paneHeight) end }, -- A quad that goes over the black cement background to try and lighten/darken it however we want. Def.Quad { Name="BackgroundColor", InitCommand=function(self) self:zoomto(paneWidth, paneHeight) end }, -- Header border Def.Quad { Name="HeaderBorder", InitCommand=function(self) self:zoomto(paneWidth + borderWidth, RowHeight + borderWidth + 1):y(-paneHeight/2 + RowHeight/2) end }, -- Green Header Def.Quad { Name="HeaderBackground", InitCommand=function(self) self:zoomto(paneWidth, RowHeight):y(-paneHeight/2 + RowHeight/2) end }, -- Header Text LoadFont("Wendy/_wendy small").. { Name="Header", Text="Stamina RPG", InitCommand=function(self) self:zoom(0.5) self:y(-paneHeight/2 + 12) end }, -- EX Score text (if applicable) LoadFont("Wendy/_wendy small").. { Name="EX", Text="EX", InitCommand=function(self) self:zoom(0.5) self:y(-paneHeight/2 + 12) self:x(paneWidth/2 - 18) self:visible(false) end }, -- Main Body Text LoadFont("Common Normal").. { Name="BodyText", Text="", InitCommand=function(self) self:valign(0) self:wrapwidthpixels(paneWidth) self:y(-paneHeight/2 + RowHeight * 3/2) end, ResetCommand=function(self) self:zoom(1) self:wrapwidthpixels(paneWidth) self:setext("") end, }, -- This is always visible as we will always have multiple panes for RPG Def.ActorFrame{ Name="PaneIcons", InitCommand=function(self) self:y(paneHeight/2 - RowHeight/2) end, LoadFont("Common Normal").. { Name="LeftIcon", Text="&MENULEFT;", InitCommand=function(self) self:x(-paneWidth2Player/2 + 10) end, OnCommand=function(self) self:queuecommand("Bounce") end, BounceCommand=function(self) self:decelerate(0.5):addx(10):accelerate(0.5):addx(-10) self:queuecommand("Bounce") end, }, LoadFont("Common Normal").. { Name="Text", Text="More Information", InitCommand=function(self) self:addy(-2) end, }, LoadFont("Common Normal").. { Name="RightIcon", Text="&MENURiGHT;", InitCommand=function(self) self:x(paneWidth2Player/2 - 10) end, OnCommand=function(self) self:queuecommand("Bounce") end, BounceCommand=function(self) self:decelerate(0.5):addx(-10):accelerate(0.5):addx(10) self:queuecommand("Bounce") end, }, } } local af2 = af[#af] -- The Leaderboard for the RPG data. Currently hidden until we want to display it. af2[#af2+1] = Def.ActorFrame{ Name="Leaderboard", InitCommand=function(self) self:visible(false) end, -- Highlight backgrounds for the leaderboard. Def.Quad { Name="Rival1", InitCommand=function(self) self:diffuse(color("#BD94FF")):zoomto(paneWidth, RowHeight) end, }, Def.Quad { Name="Rival2", InitCommand=function(self) self:diffuse(color("#BD94FF")):zoomto(paneWidth, RowHeight) end, }, Def.Quad { Name="Rival3", InitCommand=function(self) self:diffuse(color("#BD94FF")):zoomto(paneWidth, RowHeight) end, }, Def.Quad { Name="Self", InitCommand=function(self) self:diffuse(color("#A1FF94")):zoomto(paneWidth, RowHeight) end, }, } local af3 = af2[#af2] for i=1, NumEntries do --- Each entry has a Rank, Name, and Score subactor. af3[#af3+1] = Def.ActorFrame{ Name="LeaderboardEntry"..i, InitCommand=function(self) self:x(-(paneWidth-paneWidth2Player)/2) if NumEntries % 2 == 1 then self:y(RowHeight*(i - (NumEntries+1)/2) ) else self:y(RowHeight*(i - NumEntries/2)) end end, LoadFont("Common Normal").. { Name="Rank", Text="", InitCommand=function(self) self:horizalign(right) self:maxwidth(30) self:x(-paneWidth2Player/2 + 30 + borderWidth) end, }, LoadFont("Common Normal").. { Name="Name", Text="", InitCommand=function(self) self:horizalign(center) self:maxwidth(130) self:x(-paneWidth2Player/2 + 100) end, }, LoadFont("Common Normal").. { Name="Score", Text="", InitCommand=function(self) self:horizalign(right) self:x(paneWidth2Player/2-borderWidth) end, }, LoadFont("Common Normal").. { Name="Date", Text="", InitCommand=function(self) self:horizalign(right) self:x(paneWidth2Player/2 + 100 - borderWidth) self:visible(GAMESTATE:GetNumSidesJoined() == 1) end, }, } end end return af
return PlaceObj("ModDef", { "title", "Example Delay Mystery", "version", 1, "version_major", 0, "version_minor", 1, "saved", 0, "image", "Preview.png", "id", "ChoGGi_ExampleDelayMystery", "author", "ChoGGi", "lua_revision", 249143, "code", { "Code/Script.lua", }, "description", [[Looks for a gamerule id called "replace with gamerule id", if it finds it then the start of the mystery will be delayed 100 days (sols).]], })
local M = {} local titan_packer_util = require("titan.packer.util") local plugin_specs = nil local plugin_specs_by_name = nil local skip_plugins = nil local skip_all_plugins = false local function use(plugin_spec) local spec = { spec = plugin_spec, line = debug.getinfo(2, 'l').currentline, } spec.name = titan_packer_util.plugin_name(spec.spec, spec.line) plugin_specs[#plugin_specs+1] = spec plugin_specs_by_name[spec.name] = spec end local function skip(name) skip_plugins[#skip_plugins+1] = name end local function skip_all() skip_all_plugins = true end function M.reset() plugin_specs = {} plugin_specs_by_name = {} skip_plugins = {} skip_all_plugins = false end function M.config() M.reset() -- User plugins and overrides go here -- skip_all() -- skip "toggleterm.nvim" -- use "~/dev/titan.nvim" -- use "~/dev/lunarized" use { "ryansch/habitats.nvim", requires = { "nvim-telescope/telescope-file-browser.nvim", "natecraddock/sessions.nvim", "natecraddock/workspaces.nvim" } } return { plugin_specs = plugin_specs, plugin_specs_by_name = plugin_specs_by_name, skip_plugins = skip_plugins, skip_all_plugins = skip_all_plugins, } end return M
return { strike1 = { animationId = "rbxassetid://2065686536"; looped = false; priority = Enum.AnimationPriority.Action; }; strike2 = { animationId = "rbxassetid://2035777674"; looped = false; priority = Enum.AnimationPriority.Action; }; strike3 = { animationId = "rbxassetid://4272381396"; looped = false; priority = Enum.AnimationPriority.Action; }; }
---------------------------------------------------------------------------------------------- -- NETWORKING NETWORKING NETWORKING NETWORKING NETWORKING NETWORKING NETWORKING NETWOR ---------------------------------------------------------------------------------------------- net.Receive( "BP::OpenGui", function( len ) print("Cliente received") local Data = net.ReadTable() -- local PData = net.ReadTable() BattlePass.Achievement[ LocalPlayer():SteamID64() ] = Data BattlePass.AchievementList = ACV.Achievements -- BattlePass.PlayerParsed = util.JSONToTable(PData[1].parsed) BattlePassUI(Data) -- PrintTable(BattlePass.AchievementList) end) net.Receive("BP::PlayerRewards", function(len, ply) local PData = net.ReadTable() BattlePass.PlayerParsed = util.JSONToTable(PData[1].parsed) end) ---------------------------------------------------------------------------------------------- -- FUNCTIONS FUNCTIONS FUNCTIONS FUNCTIONS FUNCTIONS FUNCTIONS FUNCTIONS FUNCTIONS FUNCTIONS ---------------------------------------------------------------------------------------------- local ACVTTime = CurTime() hook.Add("Think","ACV Test",function() if ACVTTime < CurTime() then ACVTTime = CurTime() + 8 -- ACV_DrawNoticer("ACV_Normal_Say_100") end end) ACV_ClientInventory = ACV_ClientInventory or {} net.Receive( "BP::SavedData", function( len ) local DATA = net.ReadTable() ACV_ClientInventory = DATA end) net.Receive( "BP::SyncData", function( len ) local DA = net.ReadTable() ACV_ClientInventory[DA.LN] = DA.AM local ADB = ACVTable(DA.LN) if DA.AM >= ADB.Max then ACV_DrawNoticer(DA.LN) end end) function ACV_DrawNoticer(ACVLuaName) local ADB = ACVTable(ACVLuaName) hook.Remove( "HUDPaint", "ACVNotice_HUD" ) local StartTime = CurTime() local PosX = ScrW()/2-250 local PosY = ScrH()+50 local SizeX,SizeY = 500,100 hook.Add("HUDPaint","ACVNotice_HUD",function() local DeltaTime = CurTime() - StartTime if DeltaTime < ACVCustomizer.CompleteNoticerHUDDuration then local AnimationLerp = 100/(1/FrameTime()) AnimationLerp = AnimationLerp/15 PosY = Lerp(AnimationLerp,PosY,ScrH()-150) else local AnimationLerp = 100/(1/FrameTime()) AnimationLerp = AnimationLerp/25 PosY = Lerp(AnimationLerp,PosY,ScrH()+50) end surface.SetDrawColor(0,0,0,250) surface.DrawRect(PosX,PosY,SizeX,SizeY) surface.SetDrawColor(0,150,255,250) surface.DrawRect(PosX,PosY,SizeX,1) surface.DrawRect(PosX,PosY+SizeY-1,SizeX,1) surface.DrawRect(PosX,PosY,1,SizeY) surface.DrawRect(PosX+SizeX-1,PosY,1,SizeY) draw.SimpleText("Achievement Complete!!", "RXF_TrebOut_S30", PosX+SizeX/2, PosY+5, Color(0,200,255,255), TEXT_ALIGN_CENTER) render.SetScissorRect( PosX+10, 0, PosX+SizeX -10 , ScrH(), true ) draw.SimpleText("< " .. ADB.PrintName .. " >", "RXF_TrebOut_S25", PosX+SizeX/2, PosY+35, Color(0,255,255,255), TEXT_ALIGN_CENTER) draw.SimpleText("< " .. ADB.Description .. " >", "RXF_TrebOut_S20", PosX+SizeX/2, PosY+70, Color(150,150,255,255), TEXT_ALIGN_CENTER) render.SetScissorRect( PosX+10, 0, PosX+SizeX -10, ScrH() , false ) if DeltaTime > ACVCustomizer.CompleteNoticerHUDDuration+1 then hook.Remove( "HUDPaint", "ACVNotice_HUD" ) return end end) end function BattlePassUI( Data, PData ) local frame = vgui.Create("BP::Frame") frame:SetSize(ScrW(), ScrH()) frame:Center() frame:MakePopup() -- local background = frame:Add("BP::Canvas") -- background:Dock(FILL) local navbar = frame:Add("BP::Navbar") navbar:Dock(TOP) navbar:SetTall( ScrH() * 0.1) navbar:SetBody( frame ) navbar:AddMenu( "Recompensas", "BP::Main") navbar:AddMenu( "Missões", "BP::Quests") navbar:AddMenu( "Como funciona?", "MenuBackgroundGradient") navbar:SetActive( 1 ) -- navbar:SetTargetData( Data ) -- navbar:SetActive(1) -- navbar:AddPanel( , 1, 0, 0 ) -- navbar:AddPanel( ,2 ,1, 0 ) end concommand.Add("bp", BattlePassUI)
do local _ = { ['item-with-tags'] = { icon = '__base__/graphics/icons/wooden-chest.png', name = 'item-with-tags', icon_mipmaps = 4, type = 'item-with-tags', order = 's[item-with-tags]-o[item-with-tags]', flags = {'hidden'}, subgroup = 'other', stack_size = 1, icon_size = 64 } }; return _; end